]>
apps.delaporte.us Git - dotfiles.git/blob - run/ocr/ocr.py
61a69ba41b74f9db1e0211591330c54c0decd2ea
3 from ollama_ocr
import OCRProcessor
5 def ocr_image(ocr
, image_path
):
6 """Perform OCR on an image and return the extracted text."""
8 print(f
"Processing {image_path}...")
9 result
= ocr
.process_image(
10 image_path
=image_path
,
12 custom_prompt
="Extract all text",
16 except Exception as e
:
17 print(f
"Error processing {image_path}: {e}")
20 def ocr_directory(input_dir
):
21 """Recursively process all files in the directory and its subdirectories."""
22 ocr
= OCRProcessor(model_name
='llama3.2-vision:11b')
23 for root
, _
, files
in os
.walk(input_dir
):
24 for file_name
in files
:
25 # Check if the file is an image
26 if file_name
.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
27 input_path
= os
.path
.join(root
, file_name
)
28 output_path
= os
.path
.join(root
, file_name
.replace('.', '_ocr.'))
31 if os
.path
.exists(output_path
):
32 print(f
'{output_path} exists.')
34 # Perform OCR on the image
35 text
= ocr_image(ocr
, input_path
)
37 # Write the OCR result to a JSON file
38 json_output_path
= output_path
.rsplit('.', 1)[0] + '.json'
40 with open(json_output_path
, 'w') as f
:
41 f
.write(f
'{{"text": "{text}"}}')
42 print(f
"Saved OCR result for {input_path} to {json_output_path}")
45 if __name__
== "__main__":
46 parser
= argparse
.ArgumentParser(description
="OCR all images in a directory and save the results as JSON files.")
47 parser
.add_argument('directory', type=str, help='Path to the directory containing image files')
49 args
= parser
.parse_args()
50 input_directory
= args
.directory
51 ocr_directory(input_directory
)