process_images.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. #!/usr/bin/env python3
  2. """
  3. Image processing script for OCR and entity extraction using OpenAI-compatible API.
  4. Processes images from Downloads folder and extracts structured data.
  5. """
  6. import os
  7. import json
  8. import base64
  9. from pathlib import Path
  10. from typing import Dict, List, Optional
  11. import concurrent.futures
  12. from dataclasses import dataclass, asdict
  13. from openai import OpenAI
  14. from tqdm import tqdm
  15. import argparse
  16. from dotenv import load_dotenv
  17. @dataclass
  18. class ProcessingResult:
  19. """Structure for processing results"""
  20. filename: str
  21. success: bool
  22. data: Optional[Dict] = None
  23. error: Optional[str] = None
  24. class ImageProcessor:
  25. """Process images using OpenAI-compatible vision API"""
  26. def __init__(self, api_url: str, api_key: str, model: str = "gpt-4o", index_file: str = "processing_index.json", downloads_dir: Optional[str] = None):
  27. self.client = OpenAI(api_key=api_key, base_url=api_url)
  28. self.model = model
  29. self.downloads_dir = Path(downloads_dir) if downloads_dir else Path.home() / "Downloads"
  30. self.index_file = index_file
  31. self.processed_files = self.load_index()
  32. def load_index(self) -> set:
  33. """Load the index of already processed files"""
  34. if os.path.exists(self.index_file):
  35. try:
  36. with open(self.index_file, 'r') as f:
  37. data = json.load(f)
  38. return set(data.get('processed_files', []))
  39. except Exception as e:
  40. print(f"⚠️ Warning: Could not load index file: {e}")
  41. return set()
  42. return set()
  43. def save_index(self):
  44. """Save the current index of processed files"""
  45. with open(self.index_file, 'w') as f:
  46. json.dump({
  47. 'processed_files': sorted(list(self.processed_files)),
  48. 'last_updated': str(Path.cwd())
  49. }, f, indent=2)
  50. def mark_processed(self, filename: str):
  51. """Mark a file as processed and update index"""
  52. self.processed_files.add(filename)
  53. self.save_index()
  54. def get_image_files(self) -> List[Path]:
  55. """Get all image files from Downloads folder (recursively)"""
  56. image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp'}
  57. image_files = []
  58. for ext in image_extensions:
  59. image_files.extend(self.downloads_dir.glob(f'**/*{ext}'))
  60. image_files.extend(self.downloads_dir.glob(f'**/*{ext.upper()}'))
  61. return sorted(image_files)
  62. def get_relative_path(self, file_path: Path) -> str:
  63. """Get relative path from downloads directory for unique indexing"""
  64. try:
  65. return str(file_path.relative_to(self.downloads_dir))
  66. except ValueError:
  67. # If file is not relative to downloads_dir, use full path
  68. return str(file_path)
  69. def get_unprocessed_files(self) -> List[Path]:
  70. """Get only files that haven't been processed yet"""
  71. all_files = self.get_image_files()
  72. unprocessed = [f for f in all_files if self.get_relative_path(f) not in self.processed_files]
  73. return unprocessed
  74. def encode_image(self, image_path: Path) -> str:
  75. """Encode image to base64"""
  76. with open(image_path, 'rb') as f:
  77. return base64.b64encode(f.read()).decode('utf-8')
  78. def get_system_prompt(self) -> str:
  79. """Get the system prompt for structured extraction"""
  80. return """You are an expert OCR and document analysis system.
  81. Extract ALL text from the image in READING ORDER to create a digital twin of the document.
  82. IMPORTANT: Transcribe text exactly as it appears on the page, from top to bottom, left to right, including:
  83. - All printed text
  84. - All handwritten text (inline where it appears)
  85. - Stamps and annotations (inline where they appear)
  86. - Signatures (note location)
  87. Preserve the natural reading flow. Mix printed and handwritten text together in the order they appear.
  88. Return ONLY valid JSON in this exact structure:
  89. {
  90. "document_metadata": {
  91. "page_number": "string or null",
  92. "document_number": "string or null",
  93. "date": "string or null",
  94. "document_type": "string or null",
  95. "has_handwriting": true/false,
  96. "has_stamps": true/false
  97. },
  98. "full_text": "Complete text transcription in reading order. Include ALL text - printed, handwritten, stamps, etc. - exactly as it appears from top to bottom.",
  99. "text_blocks": [
  100. {
  101. "type": "printed|handwritten|stamp|signature|other",
  102. "content": "text content",
  103. "position": "top|middle|bottom|header|footer|margin"
  104. }
  105. ],
  106. "entities": {
  107. "people": ["list of person names"],
  108. "organizations": ["list of organizations"],
  109. "locations": ["list of locations"],
  110. "dates": ["list of dates found"],
  111. "reference_numbers": ["list of any reference/ID numbers"]
  112. },
  113. "additional_notes": "Any observations about document quality, redactions, damage, etc."
  114. }"""
  115. def process_image(self, image_path: Path) -> ProcessingResult:
  116. """Process a single image through the API"""
  117. try:
  118. # Encode image
  119. base64_image = self.encode_image(image_path)
  120. # Make API call using OpenAI client
  121. response = self.client.chat.completions.create(
  122. model=self.model,
  123. messages=[
  124. {
  125. "role": "system",
  126. "content": self.get_system_prompt()
  127. },
  128. {
  129. "role": "user",
  130. "content": [
  131. {
  132. "type": "text",
  133. "text": "Extract all text and entities from this image. Return only valid JSON."
  134. },
  135. {
  136. "type": "image_url",
  137. "image_url": {
  138. "url": f"data:image/jpeg;base64,{base64_image}"
  139. }
  140. }
  141. ]
  142. }
  143. ],
  144. max_tokens=4096,
  145. temperature=0.1
  146. )
  147. # Parse response
  148. content = response.choices[0].message.content
  149. # Parse JSON from content (strip markdown if present)
  150. content = content.strip()
  151. if content.startswith('```json'):
  152. content = content[7:]
  153. if content.startswith('```'):
  154. content = content[3:]
  155. if content.endswith('```'):
  156. content = content[:-3]
  157. content = content.strip()
  158. extracted_data = json.loads(content)
  159. return ProcessingResult(
  160. filename=self.get_relative_path(image_path),
  161. success=True,
  162. data=extracted_data
  163. )
  164. except Exception as e:
  165. return ProcessingResult(
  166. filename=self.get_relative_path(image_path),
  167. success=False,
  168. error=str(e)
  169. )
  170. def process_all(self, max_workers: int = 5, limit: Optional[int] = None, resume: bool = True) -> List[ProcessingResult]:
  171. """Process all images with parallel processing"""
  172. if resume:
  173. image_files = self.get_unprocessed_files()
  174. total_files = len(self.get_image_files())
  175. already_processed = len(self.processed_files)
  176. print(f"Found {total_files} total image files")
  177. print(f"Already processed: {already_processed}")
  178. print(f"Remaining to process: {len(image_files)}")
  179. else:
  180. image_files = self.get_image_files()
  181. print(f"Found {len(image_files)} image files to process")
  182. if limit:
  183. image_files = image_files[:limit]
  184. print(f"Limited to {limit} files for this run")
  185. if not image_files:
  186. print("No files to process!")
  187. return []
  188. results = []
  189. with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
  190. futures = {executor.submit(self.process_image, img): img for img in image_files}
  191. with tqdm(total=len(image_files), desc="Processing images") as pbar:
  192. for future in concurrent.futures.as_completed(futures):
  193. result = future.result()
  194. results.append(result)
  195. # Save individual result to file
  196. if result.success:
  197. self.save_individual_result(result)
  198. # Mark as processed regardless of success/failure
  199. self.mark_processed(result.filename)
  200. pbar.update(1)
  201. if not result.success:
  202. tqdm.write(f"❌ Failed: {result.filename} - {result.error}")
  203. else:
  204. tqdm.write(f"✅ Processed: {result.filename}")
  205. return results
  206. def save_individual_result(self, result: ProcessingResult):
  207. """Save individual result to ./results/folder/imagename.json"""
  208. # Create output path mirroring the source structure
  209. result_path = Path("./results") / result.filename
  210. result_path = result_path.with_suffix('.json')
  211. # Create parent directories
  212. result_path.parent.mkdir(parents=True, exist_ok=True)
  213. # Save the extracted data
  214. with open(result_path, 'w', encoding='utf-8') as f:
  215. json.dump(result.data, f, indent=2, ensure_ascii=False)
  216. def save_results(self, results: List[ProcessingResult], output_file: str = "processed_results.json"):
  217. """Save summary results to JSON file"""
  218. output_data = {
  219. "total_processed": len(results),
  220. "successful": sum(1 for r in results if r.success),
  221. "failed": sum(1 for r in results if not r.success),
  222. "results": [asdict(r) for r in results]
  223. }
  224. with open(output_file, 'w', encoding='utf-8') as f:
  225. json.dump(output_data, f, indent=2, ensure_ascii=False)
  226. print(f"\n✅ Summary saved to {output_file}")
  227. print(f" Individual results saved to ./results/")
  228. print(f" Successful: {output_data['successful']}")
  229. print(f" Failed: {output_data['failed']}")
  230. def main():
  231. # Load environment variables
  232. load_dotenv()
  233. parser = argparse.ArgumentParser(description="Process images with OCR and entity extraction")
  234. parser.add_argument("--api-url", help="OpenAI-compatible API base URL (default: from .env or OPENAI_API_URL)")
  235. parser.add_argument("--api-key", help="API key (default: from .env or OPENAI_API_KEY)")
  236. parser.add_argument("--model", help="Model name (default: from .env, OPENAI_MODEL, or meta-llama/Llama-4-Maverick-17B-128E-Instruct)")
  237. parser.add_argument("--workers", type=int, default=5, help="Number of parallel workers (default: 5)")
  238. parser.add_argument("--limit", type=int, help="Limit number of images to process (for testing)")
  239. parser.add_argument("--output", default="processed_results.json", help="Output JSON file")
  240. parser.add_argument("--index", default="processing_index.json", help="Index file to track processed files")
  241. parser.add_argument("--downloads-dir", default="./downloads", help="Directory containing images (default: ./downloads)")
  242. parser.add_argument("--no-resume", action="store_true", help="Process all files, ignoring index")
  243. args = parser.parse_args()
  244. # Get values from args or environment variables
  245. api_url = args.api_url or os.getenv("OPENAI_API_URL", "http://...")
  246. api_key = args.api_key or os.getenv("OPENAI_API_KEY", "abcd1234")
  247. model = args.model or os.getenv("OPENAI_MODEL", "meta-llama/Llama-4-Maverick-17B-128E-Instruct")
  248. processor = ImageProcessor(
  249. api_url=api_url,
  250. api_key=api_key,
  251. model=model,
  252. index_file=args.index,
  253. downloads_dir=args.downloads_dir
  254. )
  255. results = processor.process_all(
  256. max_workers=args.workers,
  257. limit=args.limit,
  258. resume=not args.no_resume
  259. )
  260. processor.save_results(results, args.output)
  261. if __name__ == "__main__":
  262. main()