Process a single element image (text, table, formula) Args: image_path: Path to the element image model: HFModel model instance element_type: Type of element ('text', 'table', 'formula') save_dir: Directory to save results (default: same as input directory)
(image_path, model, element_type, save_dir=None)
| 119 | |
| 120 | |
| 121 | def process_element(image_path, model, element_type, save_dir=None): |
| 122 | """Process a single element image (text, table, formula) |
| 123 | |
| 124 | Args: |
| 125 | image_path: Path to the element image |
| 126 | model: HFModel model instance |
| 127 | element_type: Type of element ('text', 'table', 'formula') |
| 128 | save_dir: Directory to save results (default: same as input directory) |
| 129 | |
| 130 | Returns: |
| 131 | Parsed content of the element and recognition results |
| 132 | """ |
| 133 | # Load and prepare image |
| 134 | pil_image = Image.open(image_path).convert("RGB") |
| 135 | # pil_image = crop_margin(pil_image) |
| 136 | |
| 137 | # Select appropriate prompt based on element type |
| 138 | if element_type == "table": |
| 139 | prompt = "Parse the table in the image." |
| 140 | label = "tab" |
| 141 | elif element_type == "formula": |
| 142 | prompt = "Read formula in the image." |
| 143 | label = "equ" |
| 144 | elif element_type == "code": |
| 145 | prompt = "Read code in the image." |
| 146 | label = "code" |
| 147 | else: # Default to text |
| 148 | prompt = "Read text in the image." |
| 149 | label = "para" |
| 150 | |
| 151 | # Process the element |
| 152 | result = model.chat(prompt, pil_image) |
| 153 | |
| 154 | # Create recognition result in the same format as the document parser |
| 155 | recognition_results = [ |
| 156 | { |
| 157 | "label": label, |
| 158 | "text": result.strip(), |
| 159 | } |
| 160 | ] |
| 161 | |
| 162 | # Save results if save_dir is provided |
| 163 | save_outputs(recognition_results, pil_image, os.path.basename(image_path).split(".")[0], save_dir) |
| 164 | print(f"Results saved to {save_dir}") |
| 165 | |
| 166 | return result, recognition_results |
| 167 | |
| 168 | |
| 169 | def main(): |
no test coverage detected