""" Extract Odia OCR text from benchmark dataset images using Gemini. This script: 1) Reads images recursively from benchmark_dataset/images (or a custom directory) 2) Sends each image to Gemini for OCR 3) Appends each result row immediately to a CSV file to avoid losing progress """ from __future__ import annotations import argparse import csv import os from pathlib import Path from typing import Any, Iterable DEFAULT_PROMPT = ( "You are an OCR assistant for Odia text.\n" "Extract all visible Odia text from this image exactly as written.\n" "Return only the extracted text, without translation or explanation." ) SUPPORTED_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tiff", ".tif"} def load_dotenv(dotenv_path: Path) -> dict[str, str]: """Parse a simple .env file (KEY=VALUE lines).""" values: dict[str, str] = {} if not dotenv_path.exists(): return values for raw_line in dotenv_path.read_text(encoding="utf-8").splitlines(): line = raw_line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) key = key.strip() value = value.strip().strip("'").strip('"') if key: values[key] = value return values def iter_image_paths(images_dir: Path) -> Iterable[Path]: """Yield all supported image files under images_dir recursively.""" for path in sorted(images_dir.rglob("*")): if path.is_file() and path.suffix.lower() in SUPPORTED_EXTENSIONS: yield path def call_gemini_ocr( image_path: Path, client: Any, model: str, prompt: str, ) -> str: """Call Gemini with prompt + image using official google-genai SDK.""" try: from PIL import Image except ImportError as exc: raise RuntimeError("Missing dependency: pillow. Install with `pip install pillow`.") from exc image = Image.open(image_path).convert("RGB") response = client.models.generate_content( model=model, contents=[prompt, image], ) output_text = (response.text or "").strip() if not output_text: raise RuntimeError("Empty OCR output in Gemini response") return output_text def normalize_stored_path(path_str: str, project_root: Path) -> str: """Normalize CSV image_path for stable matching and dedup.""" raw = str(path_str).strip() if not raw: return "" p = Path(raw) if p.is_absolute(): try: return str(p.resolve().relative_to(project_root)) except ValueError: return str(p.resolve()) return raw def load_existing_rows_by_path(output_csv: Path, project_root: Path) -> dict[str, dict[str, str]]: """Load CSV rows keyed by normalized image path (latest row wins).""" rows_by_path: dict[str, dict[str, str]] = {} if not output_csv.exists(): return rows_by_path with output_csv.open("r", encoding="utf-8", newline="") as f: reader = csv.DictReader(f) for row in reader: key = normalize_stored_path(row.get("image_path", ""), project_root) if not key: continue rows_by_path[key] = { "image_path": key, "extracted_odia_text": row.get("extracted_odia_text", "") or "", "status": row.get("status", "") or "", "error": row.get("error", "") or "", } return rows_by_path def image_path_key(image_path: Path, project_root: Path) -> str: """Use project-relative path for CSV storage and deduplication.""" resolved = image_path.resolve() try: return str(resolved.relative_to(project_root)) except ValueError: return str(resolved) def ensure_output_header(output_csv: Path, append_mode: bool) -> None: """Ensure CSV header exists when creating a new output file.""" output_csv.parent.mkdir(parents=True, exist_ok=True) if append_mode and output_csv.exists(): return with output_csv.open("w", encoding="utf-8", newline="") as f: writer = csv.writer(f) writer.writerow(["image_path", "extracted_odia_text", "status", "error"]) def write_rows(output_csv: Path, rows_by_path: dict[str, dict[str, str]]) -> None: """Rewrite CSV from rows map to keep one row per image path.""" output_csv.parent.mkdir(parents=True, exist_ok=True) with output_csv.open("w", encoding="utf-8", newline="") as f: writer = csv.DictWriter( f, fieldnames=["image_path", "extracted_odia_text", "status", "error"], ) writer.writeheader() writer.writerows(rows_by_path.values()) f.flush() def main() -> None: project_root = Path(__file__).parent.parent dotenv_values = load_dotenv(project_root / ".env") default_images_dir = ( dotenv_values.get("IMAGE_FOLDER_PATH") or str(project_root / "benchmark_dataset" / "images") ) default_output_csv = ( dotenv_values.get("OUTPUT_CSV_PATH") or str(project_root / "benchmark_dataset" / "gemini_ocr_output.csv") ) default_api_key = dotenv_values.get("GEMINI_API_KEY") or os.getenv( "GEMINI_API_KEY", "" ) parser = argparse.ArgumentParser( description="Extract Odia OCR text from benchmark images using Gemini" ) parser.add_argument( "--model", type=str, default="gemini-3-flash-preview", help="Gemini model name", ) parser.add_argument( "--prompt", type=str, default=DEFAULT_PROMPT, help="Prompt used for OCR extraction", ) parser.add_argument( "--limit", type=int, default=None, help="Optional max number of images to process", ) parser.add_argument( "--no-resume", action="store_true", help="Do not skip already processed image paths in output CSV", ) args = parser.parse_args() if not default_api_key: raise ValueError( "Gemini API key missing. Set GEMINI_API_KEY in .env or environment." ) try: from google import genai except ImportError as exc: raise RuntimeError( "Missing dependency: google-genai. Install with `pip install google-genai`." ) from exc client = genai.Client(api_key=default_api_key) images_dir = Path(default_images_dir).resolve() output_csv = Path(default_output_csv).resolve() if not images_dir.exists(): raise FileNotFoundError(f"Images directory not found: {images_dir}") all_images = list(iter_image_paths(images_dir)) if args.limit is not None: all_images = all_images[: max(args.limit, 0)] if not all_images: print(f"No images found under: {images_dir}") return rows_by_path: dict[str, dict[str, str]] = {} processed_success_paths: set[str] = set() previous_error_rows = 0 if not args.no_resume: rows_by_path = load_existing_rows_by_path(output_csv, project_root) processed_success_paths = { p for p, row in rows_by_path.items() if (row.get("status", "").strip().lower() == "ok") } previous_error_rows = sum( 1 for row in rows_by_path.values() if row.get("status", "").strip().lower() == "error" ) else: ensure_output_header(output_csv, append_mode=False) # Deduplicate/normalize existing CSV content on each resume run. if not args.no_resume and output_csv.exists(): write_rows(output_csv, rows_by_path) existing_keys = set(processed_success_paths) to_process = [p for p in all_images if image_path_key(p, project_root) not in existing_keys] total = len(to_process) if total == 0: print("No new images to process. Output CSV is already up to date.") return print(f"Found {len(all_images)} images in total") print(f"Already processed successfully: {len(processed_success_paths)}") if previous_error_rows: print(f"Previous error rows available to retry: {previous_error_rows}") print(f"Processing now: {total}") print(f"Writing incremental results to: {output_csv}") for idx, image_path in enumerate(to_process, start=1): image_str = image_path_key(image_path, project_root) status = "ok" extracted_text = "" err = "" try: extracted_text = call_gemini_ocr( image_path=image_path, client=client, model=args.model, prompt=args.prompt, ) except Exception as exc: # noqa: BLE001 status = "error" err = str(exc) # Upsert: keep a single latest row per image path. rows_by_path[image_str] = { "image_path": image_str, "extracted_odia_text": extracted_text, "status": status, "error": err, } write_rows(output_csv, rows_by_path) print(f"[{idx}/{total}] {status}: {image_str}") print("\nDone.") print(f"Final CSV: {output_csv}") if __name__ == "__main__": main()