File size: 9,186 Bytes
e7102e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
"""
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()