Upload 3 files
Browse files- README.md +27 -17
- app.py +766 -535
- requirements.txt +6 -14
README.md
CHANGED
|
@@ -1,23 +1,33 @@
|
|
| 1 |
-
--
|
| 2 |
-
title: DeepSeek OCR + Telegram
|
| 3 |
-
emoji: 📄
|
| 4 |
-
colorFrom: blue
|
| 5 |
-
colorTo: indigo
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 5.49.1
|
| 8 |
-
python_version: 3.10.13
|
| 9 |
-
app_file: app.py
|
| 10 |
-
pinned: false
|
| 11 |
-
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
|
| 17 |
-
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DeepSeek-OCR full-page CSV Space
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
This package contains a replacement `app.py` for a Gradio Space using
|
| 4 |
+
`strangervisionhf/deepseek-ocr-transformers-v4.57.6`. It supports whole-page OCR,
|
| 5 |
+
CSV preview/download in Gradio, and a Telegram polling bot.
|
| 6 |
|
| 7 |
+
## Space configuration
|
| 8 |
|
| 9 |
+
In Space **Settings → Variables and secrets**, set:
|
| 10 |
|
| 11 |
+
- Secret `TELEGRAM_BOT_TOKEN`: your Telegram bot token (do not paste it in source code).
|
| 12 |
+
- Variable `OCR_PROFILE`: `gundam` (recommended for small text), `small`, `tiny`, `base`, or `large`.
|
| 13 |
+
- Variable `GPU_DURATION_SECONDS`: `180` is the requested default; ZeroGPU must allow the request and you need enough remaining quota. If ZeroGPU reports an illegal duration, lower it to a permitted value. If it says quota exceeded, changing the number alone will not restore quota.
|
| 14 |
|
| 15 |
+
`BOT_TOKEN` is also accepted for backward compatibility, but `TELEGRAM_BOT_TOKEN` is preferred.
|
| 16 |
|
| 17 |
+
## Update the Space
|
| 18 |
+
|
| 19 |
+
1. Back up the current `app.py`.
|
| 20 |
+
2. Replace it with this package's `app.py`.
|
| 21 |
+
3. Update `requirements.txt` from this package if needed.
|
| 22 |
+
4. Save/commit the files and let the Space rebuild.
|
| 23 |
+
5. Test the Gradio UI with one representative full-page image.
|
| 24 |
+
6. In Telegram, send the image as a **document/file** (not a compressed photo) to preserve resolution.
|
| 25 |
+
7. Check the downloaded CSV against the page before using it.
|
| 26 |
+
|
| 27 |
+
## Notes
|
| 28 |
+
|
| 29 |
+
- The app issues one model inference call for the uploaded page. The `gundam` inference profile can internally crop the page into regions to read small text; that is not the same as manually sending separate pages.
|
| 30 |
+
- CSV columns: `voter_id`, `name`, `relative_type`, `relative_name`, `house_number`, `age`, `gender`, `photo_status`.
|
| 31 |
+
- OCR and visual grouping remain heuristic. Always manually review the voter ID/name association and any incomplete row.
|
| 32 |
+
- The code prevents duplicate Telegram polling starts inside one Python process. If Telegram logs `Conflict: terminated by other getUpdates request`, another running process/Space is still using the same bot token. Only one polling instance can use that token at a time.
|
| 33 |
+
- If a bot token was exposed in logs or chat, revoke it with BotFather and update the Space secret.
|
app.py
CHANGED
|
@@ -1,7 +1,13 @@
|
|
| 1 |
-
"""DeepSeek-OCR
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
from __future__ import annotations
|
|
@@ -9,639 +15,864 @@ from __future__ import annotations
|
|
| 9 |
import asyncio
|
| 10 |
import csv
|
| 11 |
import html
|
| 12 |
-
import
|
| 13 |
import logging
|
| 14 |
import os
|
| 15 |
import re
|
| 16 |
-
import sqlite3
|
| 17 |
import tempfile
|
| 18 |
import threading
|
| 19 |
import time
|
| 20 |
-
import uuid
|
| 21 |
from pathlib import Path
|
| 22 |
-
from
|
|
|
|
| 23 |
|
| 24 |
-
# Import spaces before torch, as recommended for ZeroGPU Spaces.
|
| 25 |
-
import spaces
|
| 26 |
-
import torch
|
| 27 |
import gradio as gr
|
| 28 |
-
|
|
|
|
| 29 |
from transformers import AutoModel, AutoTokenizer
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
)
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
logging.basicConfig(
|
| 43 |
-
level=os.getenv("LOG_LEVEL", "INFO"),
|
| 44 |
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 45 |
)
|
| 46 |
-
logger = logging.getLogger("
|
| 47 |
-
# httpx logs request URLs at INFO, and Telegram bot URLs contain the bot token.
|
| 48 |
-
# Keep these HTTP logs quiet so secrets are not copied into Space logs.
|
| 49 |
-
logging.getLogger("httpx").setLevel(logging.WARNING)
|
| 50 |
-
logging.getLogger("httpcore").setLevel(logging.WARNING)
|
| 51 |
-
|
| 52 |
-
MODEL_ID = os.getenv(
|
| 53 |
-
"MODEL_ID", "strangervisionhf/deepseek-ocr-transformers-v4.57.6"
|
| 54 |
-
)
|
| 55 |
|
| 56 |
-
|
| 57 |
-
#
|
| 58 |
-
#
|
| 59 |
-
#
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
OCR_PROFILE = "small"
|
| 72 |
-
_profile = OCR_PROFILES[OCR_PROFILE]
|
| 73 |
-
try:
|
| 74 |
-
_configured_duration = int(os.getenv("GPU_DURATION_SECONDS", str(_profile["max_duration"])))
|
| 75 |
-
except ValueError:
|
| 76 |
-
_configured_duration = int(_profile["max_duration"])
|
| 77 |
-
# Cap the setting by the selected profile's recommended maximum. For example,
|
| 78 |
-
# a leftover GPU_DURATION_SECONDS=180 cannot accidentally make Small mode
|
| 79 |
-
# reserve 180 seconds and fail when the user has only 65 seconds remaining.
|
| 80 |
-
GPU_DURATION_SECONDS = max(15, min(_configured_duration, int(_profile["max_duration"])))
|
| 81 |
-
logger.info(
|
| 82 |
-
"OCR profile=%s (base_size=%s, image_size=%s, crop_mode=%s), GPU reservation=%ss",
|
| 83 |
-
OCR_PROFILE, _profile["base_size"], _profile["image_size"],
|
| 84 |
-
_profile["crop_mode"], GPU_DURATION_SECONDS,
|
| 85 |
)
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
MAX_TELEGRAM_FILE_BYTES = 20 * 1024 * 1024
|
| 89 |
-
|
| 90 |
-
# Optional comma-separated allowlist of Telegram numeric user IDs.
|
| 91 |
-
# Example: TELEGRAM_ALLOWED_USER_IDS=123456789,987654321
|
| 92 |
-
_allowed_raw = os.getenv("TELEGRAM_ALLOWED_USER_IDS", "").strip()
|
| 93 |
-
if _allowed_raw:
|
| 94 |
try:
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
except
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
else:
|
| 103 |
-
ALLOWED_TELEGRAM_USER_IDS = None
|
| 104 |
-
|
| 105 |
-
PROMPTS = {
|
| 106 |
-
"Convert to Markdown": "<image>\n<|grounding|>Convert the document to markdown.",
|
| 107 |
-
"Free OCR": "<image>\nFree OCR.",
|
| 108 |
-
"Parse Figure": "<image>\nParse the figure.",
|
| 109 |
-
}
|
| 110 |
|
| 111 |
-
#
|
| 112 |
-
#
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
)
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
value = value.replace("\xa0", " ").replace("|", " ")
|
| 125 |
-
lines = [re.sub(r"[ \t\r]+", " ", line).strip() for line in value.splitlines()]
|
| 126 |
-
return "\n".join(line for line in lines if line)
|
| 127 |
|
| 128 |
|
| 129 |
-
def
|
| 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 |
-
value = re.sub(r"\s+", " ", match.group(1)).strip(" \t\r\n::-*|")
|
| 156 |
return value
|
| 157 |
|
| 158 |
|
| 159 |
-
def
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
age_text = _extract_field(cleaned, "age")
|
| 164 |
-
age_match = re.search(r"\d{1,3}", age_text)
|
| 165 |
-
return {
|
| 166 |
-
"voter_id": voter_id.strip(),
|
| 167 |
-
"name": _extract_field(cleaned, "name"),
|
| 168 |
-
"father_name": _extract_field(cleaned, "father_name"),
|
| 169 |
-
"husband_name": _extract_field(cleaned, "husband_name"),
|
| 170 |
-
"house_no": _extract_field(cleaned, "house_no"),
|
| 171 |
-
"age": int(age_match.group()) if age_match else 0,
|
| 172 |
-
"gender": _extract_field(cleaned, "gender"),
|
| 173 |
-
}
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
def _plain_cell_text(value: str) -> str:
|
| 177 |
-
"""Convert one HTML table cell to text while preserving ``<br>`` breaks."""
|
| 178 |
-
value = html.unescape(value or "")
|
| 179 |
-
value = re.sub(r"<br\s*/?>", "\n", value, flags=re.IGNORECASE)
|
| 180 |
-
value = re.sub(r"</(?:div|p|li|span)\s*>\s*", "\n", value, flags=re.IGNORECASE)
|
| 181 |
-
value = re.sub(r"<[^>]+>", "", value)
|
| 182 |
-
value = value.replace("\xa0", " ").replace("\u200b", "")
|
| 183 |
-
return "\n".join(re.sub(r"[ \t\r]+", " ", line).strip() for line in value.splitlines()).strip()
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
def _parse_flat_html_cells(raw: str) -> list[dict[str, Any]] | None:
|
| 187 |
-
"""Parse DeepSeek's split-row grid by globally pairing ID and detail cells.
|
| 188 |
-
|
| 189 |
-
In the voter-roll layout, one HTML <tr> contains serial numbers and voter IDs,
|
| 190 |
-
while the next <tr> contains the corresponding detail and photo cells. A
|
| 191 |
-
record therefore cannot be recovered reliably by treating each <tr> as a
|
| 192 |
-
separate record. We flatten all <td> cells in document order, filter IDs and
|
| 193 |
-
detail cells into parallel lists, and pair those lists by index.
|
| 194 |
-
|
| 195 |
-
Returns ``None`` when the OCR output has no HTML <td> cells, allowing the
|
| 196 |
-
Markdown/plain-text fallback to handle other output styles. An empty list
|
| 197 |
-
means an HTML table was found but no records could be confidently parsed.
|
| 198 |
-
"""
|
| 199 |
-
# Works when <table> has attributes, multiple tables exist, or the final
|
| 200 |
-
# </table> is missing: matching is based on all <td> cells in the OCR text.
|
| 201 |
-
cells = re.findall(
|
| 202 |
-
r"<td\b[^>]*>(.*?)(?:</td\s*>|(?=<td\b)|$)",
|
| 203 |
-
raw,
|
| 204 |
-
flags=re.IGNORECASE | re.DOTALL,
|
| 205 |
-
)
|
| 206 |
-
if not cells:
|
| 207 |
-
return None
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
text = _plain_cell_text(cell)
|
| 213 |
-
normalized = re.sub(r"\s+", "", text)
|
| 214 |
-
id_match = VOTER_ID_RE.fullmatch(normalized)
|
| 215 |
-
if id_match:
|
| 216 |
-
voter_ids.append(id_match.group(0))
|
| 217 |
-
# Match a standalone "नाम:" field, but not the trailing "नाम:" in
|
| 218 |
-
# "पिता का नाम:" or "पति का नाम:".
|
| 219 |
-
if re.search(r"(?<!का )नाम\s*[::]", text):
|
| 220 |
-
detail_cells.append(cell)
|
| 221 |
|
| 222 |
-
|
| 223 |
-
"
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
if not voter_ids or not detail_cells:
|
| 227 |
-
return []
|
| 228 |
|
| 229 |
-
|
| 230 |
-
for
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
"
|
| 238 |
-
|
| 239 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
)
|
| 241 |
-
|
| 242 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
return []
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
if
|
| 260 |
continue
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
continue
|
| 267 |
-
candidate_rows.append("\n".join(cells))
|
| 268 |
-
|
| 269 |
-
if not candidate_rows:
|
| 270 |
-
clean = _clean_markup(raw)
|
| 271 |
-
found = list(VOTER_ID_RE.finditer(clean))
|
| 272 |
-
for index, match in enumerate(found):
|
| 273 |
-
end = found[index + 1].start() if index + 1 < len(found) else len(clean)
|
| 274 |
-
candidate_rows.append(clean[match.start():end])
|
| 275 |
-
|
| 276 |
-
output: list[dict[str, Any]] = []
|
| 277 |
-
seen: set[str] = set()
|
| 278 |
-
id_only: list[str] = []
|
| 279 |
-
details_only: list[str] = []
|
| 280 |
-
|
| 281 |
-
for row in candidate_rows:
|
| 282 |
-
cleaned_row = _clean_markup(row)
|
| 283 |
-
ids = list(dict.fromkeys(m.group().strip() for m in VOTER_ID_RE.finditer(cleaned_row)))
|
| 284 |
-
if ids and "नाम" in cleaned_row:
|
| 285 |
-
for voter_id in ids:
|
| 286 |
-
record = _record_from_text(cleaned_row, voter_id)
|
| 287 |
-
if record and voter_id not in seen:
|
| 288 |
-
output.append(record)
|
| 289 |
-
seen.add(voter_id)
|
| 290 |
-
elif ids:
|
| 291 |
-
id_only.extend(voter_id for voter_id in ids if voter_id not in seen)
|
| 292 |
-
elif re.search(r"(?<!का )नाम\s*[::]", cleaned_row):
|
| 293 |
-
details_only.append(cleaned_row)
|
| 294 |
|
| 295 |
-
|
| 296 |
-
if
|
| 297 |
continue
|
| 298 |
-
record = _record_from_text(details, voter_id)
|
| 299 |
-
if record:
|
| 300 |
-
output.append(record)
|
| 301 |
-
seen.add(voter_id)
|
| 302 |
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
return output
|
| 305 |
|
| 306 |
|
| 307 |
-
def
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
try:
|
| 312 |
-
conn.execute(
|
| 313 |
-
"""CREATE TABLE IF NOT EXISTS voters (
|
| 314 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 315 |
-
voter_id TEXT,
|
| 316 |
-
name TEXT,
|
| 317 |
-
father_name TEXT,
|
| 318 |
-
husband_name TEXT,
|
| 319 |
-
house_no TEXT,
|
| 320 |
-
age INTEGER,
|
| 321 |
-
gender TEXT,
|
| 322 |
-
raw_json TEXT
|
| 323 |
-
)"""
|
| 324 |
-
)
|
| 325 |
-
conn.commit()
|
| 326 |
-
finally:
|
| 327 |
-
conn.close()
|
| 328 |
|
|
|
|
|
|
|
|
|
|
| 329 |
|
| 330 |
-
|
| 331 |
-
|
|
|
|
| 332 |
|
| 333 |
-
|
| 334 |
-
load_device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 335 |
-
load_dtype = torch.bfloat16 if load_device == "cuda" else torch.float32
|
| 336 |
-
model = AutoModel.from_pretrained(
|
| 337 |
-
MODEL_ID,
|
| 338 |
-
trust_remote_code=True,
|
| 339 |
-
use_safetensors=True,
|
| 340 |
-
_attn_implementation="eager",
|
| 341 |
-
torch_dtype=load_dtype,
|
| 342 |
-
low_cpu_mem_usage=True,
|
| 343 |
-
).eval()
|
| 344 |
-
model = model.to(load_device)
|
| 345 |
-
logger.info("DeepSeek-OCR loaded on %s (%s).", load_device, load_dtype)
|
| 346 |
|
| 347 |
-
# The model is shared by Gradio and Telegram, so serialize inference calls.
|
| 348 |
-
_INFERENCE_LOCK = threading.Lock()
|
| 349 |
|
|
|
|
|
|
|
|
|
|
| 350 |
|
| 351 |
@spaces.GPU(duration=GPU_DURATION_SECONDS)
|
| 352 |
-
def run_ocr(
|
| 353 |
-
"""Run
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
image_file=image_path,
|
| 362 |
-
output_path=output_dir
|
| 363 |
-
base_size=
|
| 364 |
-
image_size=
|
| 365 |
-
crop_mode=
|
| 366 |
-
save_results=
|
| 367 |
test_compress=True,
|
| 368 |
eval_mode=True,
|
| 369 |
)
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
finally:
|
| 377 |
-
output_dir.cleanup()
|
| 378 |
|
| 379 |
|
| 380 |
-
def
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
"profile such as OCR_PROFILE=tiny."
|
| 389 |
-
)
|
| 390 |
-
if "gpu task aborted" in message or "exceeding its requested duration" in message:
|
| 391 |
-
return (
|
| 392 |
-
f"The OCR task exceeded its {GPU_DURATION_SECONDS}s GPU time limit. "
|
| 393 |
-
"Try OCR_PROFILE=tiny or a smaller/cropped image. The small profile can "
|
| 394 |
-
"trade some detail for faster inference."
|
| 395 |
-
)
|
| 396 |
-
return f"OCR failed: {type(exc).__name__}: {exc}"
|
| 397 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
|
| 399 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
if image is None:
|
| 401 |
-
raise gr.Error("Upload
|
| 402 |
-
prompt = PROMPTS.get(task, PROMPTS["Convert to Markdown"])
|
| 403 |
-
temp_path = None
|
| 404 |
try:
|
| 405 |
-
|
| 406 |
-
temp_path = handle.name
|
| 407 |
-
image.convert("RGB").save(temp_path, format="PNG")
|
| 408 |
-
return run_ocr(temp_path, prompt)
|
| 409 |
except Exception as exc:
|
| 410 |
logger.exception("Gradio OCR failed")
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
|
| 416 |
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
user = update.effective_user
|
| 421 |
-
return user is not None and user.id in ALLOWED_TELEGRAM_USER_IDS
|
| 422 |
|
|
|
|
|
|
|
| 423 |
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
return
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
"
|
| 432 |
-
"when voter-style rows are detected, return a CSV for you to review. "
|
| 433 |
-
"Use the Save button only after checking the extracted data."
|
| 434 |
)
|
|
|
|
|
|
|
|
|
|
| 435 |
|
| 436 |
|
| 437 |
-
async def
|
| 438 |
message = update.effective_message
|
| 439 |
-
if message
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
|
|
|
| 444 |
|
| 445 |
-
document = message.document
|
| 446 |
-
photo = message.photo
|
| 447 |
-
if document:
|
| 448 |
-
mime_type = document.mime_type or ""
|
| 449 |
-
if not mime_type.startswith("image/"):
|
| 450 |
-
await message.reply_text("Please send an image file (PNG, JPG, or similar).")
|
| 451 |
-
return
|
| 452 |
-
file_id = document.file_id
|
| 453 |
-
original_name = document.file_name or "upload.png"
|
| 454 |
-
file_size = document.file_size
|
| 455 |
-
elif photo:
|
| 456 |
-
file_id = photo[-1].file_id
|
| 457 |
-
original_name = f"telegram_{message.message_id}.jpg"
|
| 458 |
-
file_size = photo[-1].file_size
|
| 459 |
-
else:
|
| 460 |
-
return
|
| 461 |
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
|
| 466 |
-
suffix = Path(original_name).suffix.lower()
|
| 467 |
-
if suffix not in {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"}:
|
| 468 |
-
suffix = ".jpg"
|
| 469 |
-
local_path = None
|
| 470 |
-
status = await message.reply_text("Image received. Running DeepSeek-OCR…")
|
| 471 |
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
await telegram_file.download_to_drive(custom_path=local_path)
|
| 477 |
-
|
| 478 |
-
raw = await asyncio.to_thread(run_ocr, local_path, PROMPTS["Convert to Markdown"])
|
| 479 |
-
records = parse_markdown(raw)
|
| 480 |
-
if not records:
|
| 481 |
-
await status.edit_text("OCR finished, but I could not confidently parse voter-style rows. Raw OCR follows:")
|
| 482 |
-
await message.reply_text(raw[:3500] or "The model returned no text.")
|
| 483 |
-
return
|
| 484 |
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
filename="extracted_records.csv",
|
| 507 |
-
caption=f"{len(records)} possible records. Verify the CSV before saving.",
|
| 508 |
-
reply_markup=keyboard,
|
| 509 |
-
)
|
| 510 |
except Exception as exc:
|
| 511 |
-
logger.
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
if local_path and os.path.exists(local_path):
|
| 520 |
-
os.remove(local_path)
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
async def on_button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 524 |
-
query = update.callback_query
|
| 525 |
-
if query is None:
|
| 526 |
return
|
| 527 |
-
await
|
| 528 |
-
if
|
| 529 |
-
await query.edit_message_caption(caption="This bot is not enabled for your account.")
|
| 530 |
return
|
| 531 |
|
| 532 |
-
|
| 533 |
-
records = context.user_data.get("records")
|
| 534 |
try:
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
await query.edit_message_caption(caption="Could not complete that action. Check the Space logs.")
|
| 560 |
-
finally:
|
| 561 |
-
if csv_path and os.path.exists(csv_path):
|
| 562 |
-
os.remove(csv_path)
|
| 563 |
-
context.user_data.pop("csv_path", None)
|
| 564 |
-
context.user_data.pop("records", None)
|
| 565 |
-
|
| 566 |
|
| 567 |
-
async def telegram_error(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 568 |
-
logger.error("Telegram handler error", exc_info=context.error)
|
| 569 |
|
|
|
|
|
|
|
| 570 |
|
| 571 |
-
_TELEGRAM_START_LOCK = threading.Lock()
|
| 572 |
-
_TELEGRAM_START_REQUESTED = False
|
| 573 |
|
|
|
|
|
|
|
| 574 |
|
| 575 |
-
def start_telegram_bot() -> None:
|
| 576 |
-
"""Start the bot using long polling; no inbound webhook route is needed."""
|
| 577 |
-
global _TELEGRAM_START_REQUESTED
|
| 578 |
-
with _TELEGRAM_START_LOCK:
|
| 579 |
-
if _TELEGRAM_START_REQUESTED:
|
| 580 |
-
logger.warning("Telegram polling start was requested more than once; ignoring duplicate.")
|
| 581 |
-
return
|
| 582 |
-
_TELEGRAM_START_REQUESTED = True
|
| 583 |
|
| 584 |
-
|
| 585 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 586 |
return
|
| 587 |
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
)
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
def thread_target() -> None:
|
| 607 |
-
try:
|
| 608 |
-
asyncio.run(worker())
|
| 609 |
-
except Exception:
|
| 610 |
-
logger.exception(
|
| 611 |
-
"Telegram bot failed to start. Check the bot token and confirm no other "
|
| 612 |
-
"Space, local script, or server is polling the same token. A 409 Conflict "
|
| 613 |
-
"means another getUpdates poller is active."
|
| 614 |
-
)
|
| 615 |
|
| 616 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 617 |
|
| 618 |
|
| 619 |
-
|
| 620 |
-
|
|
|
|
| 621 |
|
| 622 |
-
with gr.Blocks(title="DeepSeek-OCR") as demo:
|
| 623 |
gr.Markdown(
|
| 624 |
-
"# DeepSeek-OCR\n"
|
| 625 |
-
"Upload
|
| 626 |
-
"
|
| 627 |
)
|
| 628 |
with gr.Row():
|
| 629 |
-
with gr.Column():
|
| 630 |
-
image_input = gr.Image(type="pil", label="
|
| 631 |
-
|
| 632 |
-
choices=
|
| 633 |
-
value=
|
| 634 |
-
label="OCR
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 635 |
)
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
output_text = gr.Textbox(label="OCR output", lines=18, show_copy_button=True)
|
| 639 |
-
run_button.click(fn=gradio_ocr, inputs=[image_input, task_input], outputs=output_text)
|
| 640 |
gr.Markdown(
|
| 641 |
-
"**
|
| 642 |
-
"
|
| 643 |
-
"unless you have separately configured persistent storage."
|
| 644 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 645 |
|
| 646 |
if __name__ == "__main__":
|
| 647 |
-
|
|
|
|
|
|
| 1 |
+
"""DeepSeek-OCR full-page electoral-roll OCR with CSV export and Telegram bot.
|
| 2 |
|
| 3 |
+
Environment variables (set these in Hugging Face Space Settings):
|
| 4 |
+
TELEGRAM_BOT_TOKEN Telegram bot token (secret; never put it in this file)
|
| 5 |
+
OCR_PROFILE tiny | small | base | large | gundam (default: gundam)
|
| 6 |
+
GPU_DURATION_SECONDS ZeroGPU reservation requested by @spaces.GPU (default: 180)
|
| 7 |
+
|
| 8 |
+
The app runs one model.infer() call for each uploaded full page. The Gundam profile
|
| 9 |
+
allows the model to create internal crops while still processing the uploaded page
|
| 10 |
+
as one OCR job. OCR-to-record grouping is heuristic; check a sample of the CSV.
|
| 11 |
"""
|
| 12 |
|
| 13 |
from __future__ import annotations
|
|
|
|
| 15 |
import asyncio
|
| 16 |
import csv
|
| 17 |
import html
|
| 18 |
+
import io
|
| 19 |
import logging
|
| 20 |
import os
|
| 21 |
import re
|
|
|
|
| 22 |
import tempfile
|
| 23 |
import threading
|
| 24 |
import time
|
|
|
|
| 25 |
from pathlib import Path
|
| 26 |
+
from statistics import median
|
| 27 |
+
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
|
| 28 |
|
|
|
|
|
|
|
|
|
|
| 29 |
import gradio as gr
|
| 30 |
+
import torch
|
| 31 |
+
from PIL import Image, ImageOps
|
| 32 |
from transformers import AutoModel, AutoTokenizer
|
| 33 |
|
| 34 |
+
try:
|
| 35 |
+
import spaces
|
| 36 |
+
except ImportError: # Useful for local parser/UI checks outside Hugging Face Spaces.
|
| 37 |
+
class _SpacesFallback:
|
| 38 |
+
@staticmethod
|
| 39 |
+
def GPU(*args, **kwargs):
|
| 40 |
+
def decorator(func):
|
| 41 |
+
return func
|
| 42 |
+
return decorator
|
| 43 |
+
spaces = _SpacesFallback() # type: ignore[assignment]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# -----------------------------------------------------------------------------
|
| 47 |
+
# Configuration
|
| 48 |
+
# -----------------------------------------------------------------------------
|
| 49 |
+
|
| 50 |
+
MODEL_ID = "strangervisionhf/deepseek-ocr-transformers-v4.57.6"
|
| 51 |
+
DEFAULT_PROFILE = os.getenv("OCR_PROFILE", "gundam").strip().lower()
|
| 52 |
+
try:
|
| 53 |
+
GPU_DURATION_SECONDS = int(os.getenv("GPU_DURATION_SECONDS", "180"))
|
| 54 |
+
except ValueError:
|
| 55 |
+
GPU_DURATION_SECONDS = 180
|
| 56 |
+
GPU_DURATION_SECONDS = max(10, GPU_DURATION_SECONDS)
|
| 57 |
+
|
| 58 |
+
# Telegram BotFather token must be set as a Hugging Face Space Secret.
|
| 59 |
+
TELEGRAM_BOT_TOKEN = (
|
| 60 |
+
os.getenv("TELEGRAM_BOT_TOKEN", "").strip()
|
| 61 |
+
or os.getenv("BOT_TOKEN", "").strip()
|
| 62 |
)
|
| 63 |
|
| 64 |
+
OCR_PROFILES: Dict[str, Dict[str, Any]] = {
|
| 65 |
+
"tiny": {"base_size": 512, "image_size": 512, "crop_mode": False},
|
| 66 |
+
"small": {"base_size": 640, "image_size": 640, "crop_mode": False},
|
| 67 |
+
"base": {"base_size": 1024, "image_size": 1024, "crop_mode": False},
|
| 68 |
+
"large": {"base_size": 1280, "image_size": 1280, "crop_mode": False},
|
| 69 |
+
"gundam": {"base_size": 1024, "image_size": 640, "crop_mode": True},
|
| 70 |
+
}
|
| 71 |
+
if DEFAULT_PROFILE not in OCR_PROFILES:
|
| 72 |
+
DEFAULT_PROFILE = "gundam"
|
| 73 |
+
|
| 74 |
+
CSV_COLUMNS = [
|
| 75 |
+
"voter_id",
|
| 76 |
+
"name",
|
| 77 |
+
"relative_type",
|
| 78 |
+
"relative_name",
|
| 79 |
+
"house_number",
|
| 80 |
+
"age",
|
| 81 |
+
"gender",
|
| 82 |
+
"photo_status",
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
# The standard DeepSeek-OCR document prompt, followed by explicit instructions
|
| 86 |
+
# for the target document. The model may still emit grounded regions; the parser
|
| 87 |
+
# below handles both HTML/Markdown tables and grounded region output.
|
| 88 |
+
OCR_PROMPT = """<image>
|
| 89 |
+
<|grounding|>Convert the document to markdown.
|
| 90 |
+
The image is one complete page of an Indian electoral roll with repeated voter cards.
|
| 91 |
+
Read the entire page, not just one card. Preserve Hindi and English text as printed.
|
| 92 |
+
Keep each voter ID and the fields printed in that same card together.
|
| 93 |
+
If possible, format the output as a table with one row per voter card and these columns:
|
| 94 |
+
voter_id, name, relative_type, relative_name, house_number, age, gender, photo_status.
|
| 95 |
+
Do not invent unreadable values. Leave fields blank when they cannot be read.
|
| 96 |
+
"""
|
| 97 |
|
| 98 |
logging.basicConfig(
|
| 99 |
+
level=os.getenv("LOG_LEVEL", "INFO").upper(),
|
| 100 |
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 101 |
)
|
| 102 |
+
logger = logging.getLogger("deepseek-ocr-csv")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
+
|
| 105 |
+
# -----------------------------------------------------------------------------
|
| 106 |
+
# Load model once at startup
|
| 107 |
+
# -----------------------------------------------------------------------------
|
| 108 |
+
|
| 109 |
+
logger.info("Loading OCR model: %s", MODEL_ID)
|
| 110 |
+
logger.info("Default OCR profile=%s; GPU reservation=%ss", DEFAULT_PROFILE, GPU_DURATION_SECONDS)
|
| 111 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 112 |
+
logger.info("OCR device: %s", DEVICE)
|
| 113 |
+
|
| 114 |
+
TOKENIZER = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 115 |
+
MODEL = AutoModel.from_pretrained(
|
| 116 |
+
MODEL_ID,
|
| 117 |
+
trust_remote_code=True,
|
| 118 |
+
use_safetensors=True,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
)
|
| 120 |
+
MODEL = MODEL.to(DEVICE).eval()
|
| 121 |
+
if DEVICE.type == "cuda":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
try:
|
| 123 |
+
target_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
| 124 |
+
MODEL = MODEL.to(dtype=target_dtype)
|
| 125 |
+
logger.info("Model dtype: %s", target_dtype)
|
| 126 |
+
except Exception:
|
| 127 |
+
logger.exception("Could not select reduced-precision CUDA dtype; continuing with model default")
|
| 128 |
+
logger.info("OCR model loaded successfully")
|
| 129 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
# -----------------------------------------------------------------------------
|
| 132 |
+
# OCR and parser helpers
|
| 133 |
+
# -----------------------------------------------------------------------------
|
| 134 |
+
|
| 135 |
+
# Supports electoral-roll style IDs such as UP/53/264/726430 and EPIC-like IDs
|
| 136 |
+
# such as ABC1234567. The patterns are intentionally anchored by boundaries.
|
| 137 |
+
SLASH_ID_RE = re.compile(
|
| 138 |
+
r"(?<![A-Z0-9])([A-Z]{2,5}\s*/\s*\d{1,4}(?:\s*/\s*\d{1,8}){2,3})(?![A-Z0-9])",
|
| 139 |
+
re.IGNORECASE,
|
| 140 |
+
)
|
| 141 |
+
EPIC_ID_RE = re.compile(r"(?<![A-Z0-9])([A-Z]{3}\s*[- ]?\s*\d{6,8})(?![A-Z0-9])", re.IGNORECASE)
|
| 142 |
+
|
| 143 |
+
HTML_TD_RE = re.compile(r"<td\b[^>]*>(.*?)</td\s*>", re.IGNORECASE | re.DOTALL)
|
| 144 |
+
HTML_ROW_RE = re.compile(r"<tr\b[^>]*>(.*?)</tr\s*>", re.IGNORECASE | re.DOTALL)
|
| 145 |
+
GROUNDED_BLOCK_RE = re.compile(
|
| 146 |
+
r"<\|ref\|>(?P<ref>.*?)<\|/ref\|>\s*"
|
| 147 |
+
r"<\|det\|>\s*\[\[(?P<coords>.*?)\]\]\s*<\|/det\|>\s*"
|
| 148 |
+
r"(?P<text>.*?)(?=<\|ref\|>|$)",
|
| 149 |
+
re.DOTALL,
|
| 150 |
)
|
| 151 |
|
| 152 |
+
# Order matters: longer relative-name labels appear before the generic "नाम".
|
| 153 |
+
LABEL_RE = re.compile(
|
| 154 |
+
r"(?P<father>पिता\s*का\s*नाम|पिता\s*नाम|Father(?:'s)?\s+Name|Father)"
|
| 155 |
+
r"|(?P<husband>पति\s*का\s*नाम|पति\s*नाम|Husband(?:'s)?\s+Name|Husband)"
|
| 156 |
+
r"|(?P<mother>माता\s*का\s*नाम|माता\s*नाम|Mother(?:'s)?\s+Name|Mother)"
|
| 157 |
+
r"|(?P<other>अन्य\s*का\s*नाम|संबंधी\s*का\s*नाम|Other\s+Relative)"
|
| 158 |
+
r"|(?P<house>मकान\s*संख्या|मकान\s*नं\.?|घर\s*संख्या|House\s*(?:Number|No\.?)|House)"
|
| 159 |
+
r"|(?P<age>आयु|उम्र|Age)"
|
| 160 |
+
r"|(?P<gender>लिंग|Gender|Sex)"
|
| 161 |
+
r"|(?P<name>(?<!का\s)नाम|(?<![A-Za-z])Name(?![A-Za-z]))",
|
| 162 |
+
re.IGNORECASE,
|
| 163 |
+
)
|
| 164 |
|
| 165 |
+
PHOTO_AVAILABLE_RE = re.compile(r"फोटो\s*(?:उपलब्ध|मौजूद)\s*(?:है)?|photo\s+available", re.IGNORECASE)
|
| 166 |
+
PHOTO_UNAVAILABLE_RE = re.compile(
|
| 167 |
+
r"फोटो\s*(?:उपलब्ध\s*नहीं|नहीं\s*है|अनुपलब्ध)|photo\s+(?:not\s+available|unavailable)",
|
| 168 |
+
re.IGNORECASE,
|
| 169 |
+
)
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
|
| 172 |
+
def empty_record() -> Dict[str, str]:
|
| 173 |
+
return {column: "" for column in CSV_COLUMNS}
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _clean_text(value: Any) -> str:
|
| 177 |
+
"""Turn model markup into readable text while preserving Hindi characters."""
|
| 178 |
+
text = html.unescape(str(value or ""))
|
| 179 |
+
text = re.sub(r"<\|ref\|>.*?<\|/ref\|>", " ", text, flags=re.DOTALL)
|
| 180 |
+
text = re.sub(r"<\|det\|>.*?<\|/det\|>", " ", text, flags=re.DOTALL)
|
| 181 |
+
text = re.sub(r"<\|[^|]+\|>", " ", text)
|
| 182 |
+
text = re.sub(r"</?\s*(?:table|tbody|thead|tfoot|tr|td|th|p|div|span|li|ul|ol|strong|b|em)\b[^>]*>", "\n", text, flags=re.IGNORECASE)
|
| 183 |
+
text = re.sub(r"<br\s*/?>", "\n", text, flags=re.IGNORECASE)
|
| 184 |
+
text = re.sub(r"!\[[^\]]*\]\([^)]*\)", " ", text)
|
| 185 |
+
text = re.sub(r"[`*_#]+", " ", text)
|
| 186 |
+
text = re.sub(r"[\t\r]+", " ", text)
|
| 187 |
+
text = re.sub(r"[ ]{2,}", " ", text)
|
| 188 |
+
text = re.sub(r"\n\s*\n\s*\n+", "\n\n", text)
|
| 189 |
+
return text.strip()
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def find_voter_ids(text: str) -> List[str]:
|
| 193 |
+
clean = html.unescape(text or "")
|
| 194 |
+
found: List[Tuple[int, str]] = []
|
| 195 |
+
for pattern in (SLASH_ID_RE, EPIC_ID_RE):
|
| 196 |
+
for match in pattern.finditer(clean):
|
| 197 |
+
raw_id = match.group(1).strip()
|
| 198 |
+
if "/" in raw_id:
|
| 199 |
+
normalized = re.sub(r"\s*/\s*", "/", raw_id).upper()
|
| 200 |
+
else:
|
| 201 |
+
normalized = re.sub(r"\s*[- ]\s*", "", raw_id).upper()
|
| 202 |
+
found.append((match.start(), normalized))
|
| 203 |
+
found.sort(key=lambda item: item[0])
|
| 204 |
+
result: List[str] = []
|
| 205 |
+
seen = set()
|
| 206 |
+
for _, voter_id in found:
|
| 207 |
+
if voter_id not in seen:
|
| 208 |
+
seen.add(voter_id)
|
| 209 |
+
result.append(voter_id)
|
| 210 |
+
return result
|
| 211 |
|
| 212 |
+
|
| 213 |
+
def _value_between(text: str, start: int, end: int) -> str:
|
| 214 |
+
value = text[start:end]
|
| 215 |
+
value = re.sub(r"^[\s::=\-–—|,;]+", "", value)
|
| 216 |
+
value = re.sub(r"[\s::=\-–—|,;]+$", "", value)
|
| 217 |
+
value = re.sub(r"\s+", " ", value).strip()
|
| 218 |
+
value = re.sub(r"(?:फोटो\s*(?:उपलब्ध|मौजूद)\s*(?:है)?|photo\s+available)", "", value, flags=re.IGNORECASE).strip()
|
|
|
|
| 219 |
return value
|
| 220 |
|
| 221 |
|
| 222 |
+
def parse_fields(text: str) -> Dict[str, str]:
|
| 223 |
+
"""Extract the known fields from one voter-card text region."""
|
| 224 |
+
text = _clean_text(text)
|
| 225 |
+
rec = empty_record()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
+
ids = find_voter_ids(text)
|
| 228 |
+
if ids:
|
| 229 |
+
rec["voter_id"] = ids[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
+
if PHOTO_UNAVAILABLE_RE.search(text):
|
| 232 |
+
rec["photo_status"] = "फोटो उपलब्ध नहीं है"
|
| 233 |
+
elif PHOTO_AVAILABLE_RE.search(text):
|
| 234 |
+
rec["photo_status"] = "फोटो उपलब्ध है"
|
|
|
|
|
|
|
| 235 |
|
| 236 |
+
matches = list(LABEL_RE.finditer(text))
|
| 237 |
+
for index, match in enumerate(matches):
|
| 238 |
+
next_start = matches[index + 1].start() if index + 1 < len(matches) else len(text)
|
| 239 |
+
value = _value_between(text, match.end(), next_start)
|
| 240 |
+
if not value:
|
| 241 |
+
continue
|
| 242 |
+
|
| 243 |
+
if match.lastgroup == "father":
|
| 244 |
+
rec["relative_type"] = "पिता"
|
| 245 |
+
if not rec["relative_name"]:
|
| 246 |
+
rec["relative_name"] = value
|
| 247 |
+
elif match.lastgroup == "husband":
|
| 248 |
+
rec["relative_type"] = "पति"
|
| 249 |
+
if not rec["relative_name"]:
|
| 250 |
+
rec["relative_name"] = value
|
| 251 |
+
elif match.lastgroup == "mother":
|
| 252 |
+
rec["relative_type"] = "माता"
|
| 253 |
+
if not rec["relative_name"]:
|
| 254 |
+
rec["relative_name"] = value
|
| 255 |
+
elif match.lastgroup == "other":
|
| 256 |
+
rec["relative_type"] = "अन्य"
|
| 257 |
+
if not rec["relative_name"]:
|
| 258 |
+
rec["relative_name"] = value
|
| 259 |
+
elif match.lastgroup == "house":
|
| 260 |
+
if not rec["house_number"]:
|
| 261 |
+
rec["house_number"] = value
|
| 262 |
+
elif match.lastgroup == "age":
|
| 263 |
+
age_match = re.search(r"\d{1,3}", value)
|
| 264 |
+
if age_match and not rec["age"]:
|
| 265 |
+
rec["age"] = age_match.group(0)
|
| 266 |
+
elif match.lastgroup == "gender":
|
| 267 |
+
gender_match = re.search(r"पुरुष|स्त्री|महिला|महिल|पुरूष|male|female|other|अन्य", value, re.IGNORECASE)
|
| 268 |
+
if gender_match and not rec["gender"]:
|
| 269 |
+
rec["gender"] = gender_match.group(0)
|
| 270 |
+
elif match.lastgroup == "name":
|
| 271 |
+
if not rec["name"]:
|
| 272 |
+
rec["name"] = value
|
| 273 |
+
|
| 274 |
+
# If field labels appear inline and were not recognized due to OCR punctuation,
|
| 275 |
+
# recover the common Hindi forms with simpler targeted expressions.
|
| 276 |
+
if not rec["name"]:
|
| 277 |
+
name_match = re.search(r"(?:^|\n)\s*नाम\s*[::]?\s*([^\n]+)", text)
|
| 278 |
+
if name_match:
|
| 279 |
+
candidate = re.split(r"पिता\s*का\s*नाम|पति\s*का\s*नाम|मकान\s*संख्या|आयु|लिंग", name_match.group(1))[0]
|
| 280 |
+
rec["name"] = candidate.strip(" ::-")
|
| 281 |
+
if not rec["relative_name"]:
|
| 282 |
+
relative_match = re.search(
|
| 283 |
+
r"(पिता\s*का\s*नाम|पति\s*का\s*नाम|माता\s*का\s*नाम)\s*[::]?\s*([^\n]+)", text
|
| 284 |
)
|
| 285 |
+
if relative_match:
|
| 286 |
+
rec["relative_type"] = "पिता" if relative_match.group(1).startswith("पिता") else ("पति" if relative_match.group(1).startswith("पति") else "माता")
|
| 287 |
+
rec["relative_name"] = re.split(r"मकान\s*संख्या|आयु|लिंग", relative_match.group(2))[0].strip(" ::-")
|
| 288 |
+
if not rec["house_number"]:
|
| 289 |
+
house_match = re.search(r"(?:मकान\s*संख्या|मकान\s*नं\.?|घर\s*संख्या)\s*[::]?\s*([^\n]+)", text)
|
| 290 |
+
if house_match:
|
| 291 |
+
rec["house_number"] = re.split(r"आयु|उम्र|लिंग", house_match.group(1))[0].strip(" ::-")
|
| 292 |
+
if not rec["age"]:
|
| 293 |
+
age_match = re.search(r"(?:आयु|उम्र|Age)\s*[::]?\s*(\d{1,3})", text, re.IGNORECASE)
|
| 294 |
+
if age_match:
|
| 295 |
+
rec["age"] = age_match.group(1)
|
| 296 |
+
if not rec["gender"]:
|
| 297 |
+
gender_match = re.search(r"(?:लिंग|Gender|Sex)\s*[::]?\s*(पुरुष|स्त्री|महिला|पुरूष|male|female)", text, re.IGNORECASE)
|
| 298 |
+
if gender_match:
|
| 299 |
+
rec["gender"] = gender_match.group(1)
|
| 300 |
+
|
| 301 |
+
# Remove any leftover OCR artifacts from each value; don't translate/correct the content.
|
| 302 |
+
for col in CSV_COLUMNS:
|
| 303 |
+
rec[col] = re.sub(r"\s+", " ", rec[col]).strip(" ::|,;\t\n")
|
| 304 |
+
return rec
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def record_has_fields(record: Dict[str, str]) -> bool:
|
| 308 |
+
return any(record.get(key, "") for key in CSV_COLUMNS if key != "voter_id")
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def record_has_person_details(record: Dict[str, str]) -> bool:
|
| 312 |
+
"""Whether this region contains card details rather than only a photo label."""
|
| 313 |
+
return any(record.get(key, "") for key in (
|
| 314 |
+
"name", "relative_type", "relative_name", "house_number", "age", "gender"
|
| 315 |
+
))
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def merge_record(target: Dict[str, str], source: Dict[str, str]) -> None:
|
| 319 |
+
"""Fill empty target fields. Existing non-empty values are not overwritten."""
|
| 320 |
+
for column in CSV_COLUMNS:
|
| 321 |
+
value = (source.get(column) or "").strip()
|
| 322 |
+
if value and not target.get(column):
|
| 323 |
+
target[column] = value
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _records_from_html(raw: str) -> List[Dict[str, str]]:
|
| 327 |
+
"""Parse HTML cells emitted by the model; pair IDs/details by document order."""
|
| 328 |
+
raw = html.unescape(raw or "")
|
| 329 |
+
raw_cells = HTML_TD_RE.findall(raw)
|
| 330 |
+
if not raw_cells:
|
| 331 |
+
return []
|
| 332 |
|
| 333 |
+
cells = [_clean_text(cell) for cell in raw_cells]
|
| 334 |
+
cells = [cell for cell in cells if cell]
|
| 335 |
+
if not cells:
|
| 336 |
+
return []
|
| 337 |
|
| 338 |
+
# Preserve the flattened cell order. Some model outputs omit </table>, and some
|
| 339 |
+
# put multiple voter cards into a single visual <tr>, so row-level grouping alone
|
| 340 |
+
# is not safe for all layouts.
|
| 341 |
+
id_entries: List[Tuple[str, Dict[str, str], int]] = []
|
| 342 |
+
detail_entries: List[Tuple[Dict[str, str], int]] = []
|
| 343 |
+
photo_entries: List[Tuple[str, int]] = []
|
| 344 |
+
|
| 345 |
+
for cell_index, cell in enumerate(cells):
|
| 346 |
+
ids = find_voter_ids(cell)
|
| 347 |
+
parsed = parse_fields(cell)
|
| 348 |
+
if ids:
|
| 349 |
+
for voter_id in ids:
|
| 350 |
+
id_entries.append((voter_id, parsed, cell_index))
|
| 351 |
+
elif record_has_person_details(parsed):
|
| 352 |
+
detail_entries.append((parsed, cell_index))
|
| 353 |
+
elif parsed.get("photo_status"):
|
| 354 |
+
photo_entries.append((parsed["photo_status"], cell_index))
|
| 355 |
+
|
| 356 |
+
if not id_entries:
|
| 357 |
return []
|
| 358 |
|
| 359 |
+
records: List[Dict[str, str]] = []
|
| 360 |
+
for voter_id, parsed, _ in id_entries:
|
| 361 |
+
rec = empty_record()
|
| 362 |
+
rec["voter_id"] = voter_id
|
| 363 |
+
merge_record(rec, parsed)
|
| 364 |
+
records.append(rec)
|
| 365 |
+
|
| 366 |
+
# In most source pages each ID cell has a corresponding details cell. Flattening
|
| 367 |
+
# both lists and pairing by index also handles several cards per visual row.
|
| 368 |
+
details_only = [entry[0] for entry in detail_entries]
|
| 369 |
+
if details_only:
|
| 370 |
+
for index, details in enumerate(details_only):
|
| 371 |
+
# If one cell already contains a complete record, don't shift later details.
|
| 372 |
+
target_index = index
|
| 373 |
+
if target_index < len(records):
|
| 374 |
+
merge_record(records[target_index], details)
|
| 375 |
+
|
| 376 |
+
# Photo status is often in a separate cell. Attach statuses in cell reading order
|
| 377 |
+
# when there is one status cell per record; otherwise attach conservatively by index.
|
| 378 |
+
if photo_entries:
|
| 379 |
+
for index, (status, _) in enumerate(photo_entries):
|
| 380 |
+
if index < len(records) and not records[index].get("photo_status"):
|
| 381 |
+
records[index]["photo_status"] = status
|
| 382 |
+
|
| 383 |
+
return _deduplicate_records(records)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def _parse_grounded_blocks(raw: str) -> List[Dict[str, Any]]:
|
| 387 |
+
raw = html.unescape(raw or "")
|
| 388 |
+
blocks: List[Dict[str, Any]] = []
|
| 389 |
+
for match in GROUNDED_BLOCK_RE.finditer(raw):
|
| 390 |
+
coordinates = [int(round(float(number))) for number in re.findall(r"-?\d+(?:\.\d+)?", match.group("coords"))]
|
| 391 |
+
if len(coordinates) < 4:
|
| 392 |
+
continue
|
| 393 |
+
x1, y1, x2, y2 = coordinates[:4]
|
| 394 |
+
text = _clean_text(match.group("text"))
|
| 395 |
+
if not text:
|
| 396 |
+
continue
|
| 397 |
+
blocks.append({
|
| 398 |
+
"text": text,
|
| 399 |
+
"bbox": (x1, y1, x2, y2),
|
| 400 |
+
"cx": (x1 + x2) / 2.0,
|
| 401 |
+
"cy": (y1 + y2) / 2.0,
|
| 402 |
+
"record": parse_fields(text),
|
| 403 |
+
})
|
| 404 |
+
return blocks
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def _median_step(values: Sequence[float], fallback: float = 1000.0) -> float:
|
| 408 |
+
unique = sorted({round(value, 1) for value in values})
|
| 409 |
+
differences = [unique[i + 1] - unique[i] for i in range(len(unique) - 1)]
|
| 410 |
+
differences = [difference for difference in differences if difference > 20]
|
| 411 |
+
if differences:
|
| 412 |
+
return float(median(differences))
|
| 413 |
+
return fallback
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def _records_from_grounded(raw: str) -> List[Dict[str, str]]:
|
| 417 |
+
blocks = _parse_grounded_blocks(raw)
|
| 418 |
+
if not blocks:
|
| 419 |
+
return []
|
| 420 |
|
| 421 |
+
anchors: List[Dict[str, Any]] = []
|
| 422 |
+
for block in blocks:
|
| 423 |
+
voter_ids = find_voter_ids(block["text"])
|
| 424 |
+
if not voter_ids:
|
| 425 |
continue
|
| 426 |
+
for voter_id in voter_ids:
|
| 427 |
+
rec = empty_record()
|
| 428 |
+
rec["voter_id"] = voter_id
|
| 429 |
+
merge_record(rec, block["record"])
|
| 430 |
+
anchors.append({"voter_id": voter_id, "cx": block["cx"], "cy": block["cy"], "record": rec})
|
| 431 |
+
|
| 432 |
+
if not anchors:
|
| 433 |
+
# Retain readable details as rows, but don't invent missing IDs.
|
| 434 |
+
fallback = []
|
| 435 |
+
for block in blocks:
|
| 436 |
+
rec = block["record"]
|
| 437 |
+
if record_has_fields(rec):
|
| 438 |
+
fallback.append(rec)
|
| 439 |
+
return _deduplicate_records(fallback)
|
| 440 |
+
|
| 441 |
+
# Stable row-major reading order. Coordinates are normalized by DeepSeek-OCR
|
| 442 |
+
# to approximately a 0..1000 coordinate system.
|
| 443 |
+
anchors.sort(key=lambda anchor: (anchor["cy"], anchor["cx"]))
|
| 444 |
+
x_step = _median_step([a["cx"] for a in anchors], 1000.0)
|
| 445 |
+
y_step = _median_step([a["cy"] for a in anchors], 1000.0)
|
| 446 |
+
expected_detail_dx = 0.60 * x_step # voter ID is often above/right of personal details
|
| 447 |
+
expected_down_dy = -0.35 * y_step # ID tends to be higher on the same card
|
| 448 |
+
|
| 449 |
+
anchor_ids = {a["voter_id"] for a in anchors}
|
| 450 |
+
for block in blocks:
|
| 451 |
+
block_ids = find_voter_ids(block["text"])
|
| 452 |
+
if block_ids:
|
| 453 |
+
# IDs already created anchor rows. If this block also contains fields,
|
| 454 |
+
# merge its text with the matching row.
|
| 455 |
+
for voter_id in block_ids:
|
| 456 |
+
for anchor in anchors:
|
| 457 |
+
if anchor["voter_id"] == voter_id:
|
| 458 |
+
merge_record(anchor["record"], block["record"])
|
| 459 |
+
break
|
| 460 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
|
| 462 |
+
rec_fields = block["record"]
|
| 463 |
+
if not record_has_fields(rec_fields):
|
| 464 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
|
| 466 |
+
is_photo = bool(rec_fields.get("photo_status")) and not any(
|
| 467 |
+
rec_fields.get(col) for col in ("name", "relative_name", "house_number", "age", "gender")
|
| 468 |
+
)
|
| 469 |
+
if len(anchors) == 1:
|
| 470 |
+
chosen = anchors[0]
|
| 471 |
+
else:
|
| 472 |
+
scored: List[Tuple[float, Dict[str, Any]]] = []
|
| 473 |
+
for anchor in anchors:
|
| 474 |
+
dx = anchor["cx"] - block["cx"]
|
| 475 |
+
dy = anchor["cy"] - block["cy"]
|
| 476 |
+
expected_dx = 0.0 if is_photo else expected_detail_dx
|
| 477 |
+
expected_dy = expected_down_dy
|
| 478 |
+
# Scale each axis by the inferred spacing between ID anchors.
|
| 479 |
+
sx = max(80.0, 0.55 * x_step)
|
| 480 |
+
sy = max(80.0, 0.55 * y_step)
|
| 481 |
+
score = abs(dx - expected_dx) / sx + abs(dy - expected_dy) / sy
|
| 482 |
+
scored.append((score, anchor))
|
| 483 |
+
chosen = min(scored, key=lambda item: item[0])[1]
|
| 484 |
+
merge_record(chosen["record"], rec_fields)
|
| 485 |
+
|
| 486 |
+
return _deduplicate_records([anchor["record"] for anchor in anchors])
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def _records_from_markdown_or_plain(raw: str) -> List[Dict[str, str]]:
|
| 490 |
+
"""Fallback for Markdown tables or text output without grounded coordinates."""
|
| 491 |
+
raw = html.unescape(raw or "")
|
| 492 |
+
rows: List[str] = []
|
| 493 |
+
for row_match in HTML_ROW_RE.finditer(raw):
|
| 494 |
+
row = _clean_text(row_match.group(1))
|
| 495 |
+
if row:
|
| 496 |
+
rows.append(row)
|
| 497 |
+
|
| 498 |
+
# Markdown tables: parse a table line at a time, keeping all cells in the same row.
|
| 499 |
+
for line in raw.splitlines():
|
| 500 |
+
if "|" in line and re.search(r"[A-Za-z\u0900-\u097F]", line):
|
| 501 |
+
cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
|
| 502 |
+
joined = "\n".join(_clean_text(cell) for cell in cells if cell.strip(" -:"))
|
| 503 |
+
if joined and not re.fullmatch(r"[-: |]+", joined):
|
| 504 |
+
rows.append(joined)
|
| 505 |
+
|
| 506 |
+
if not rows:
|
| 507 |
+
# Keep separated paragraphs distinct. This avoids assuming the whole page is one voter.
|
| 508 |
+
rows = [_clean_text(chunk) for chunk in re.split(r"\n\s*\n+", raw) if _clean_text(chunk)]
|
| 509 |
+
|
| 510 |
+
parsed_rows: List[Dict[str, str]] = []
|
| 511 |
+
id_only: List[str] = []
|
| 512 |
+
detail_only: List[Dict[str, str]] = []
|
| 513 |
+
for row in rows:
|
| 514 |
+
ids = find_voter_ids(row)
|
| 515 |
+
rec = parse_fields(row)
|
| 516 |
+
if ids and record_has_fields(rec):
|
| 517 |
+
for voter_id in ids:
|
| 518 |
+
new_rec = dict(rec)
|
| 519 |
+
new_rec["voter_id"] = voter_id
|
| 520 |
+
parsed_rows.append(new_rec)
|
| 521 |
+
elif ids:
|
| 522 |
+
id_only.extend(ids)
|
| 523 |
+
elif record_has_fields(rec):
|
| 524 |
+
detail_only.append(rec)
|
| 525 |
+
|
| 526 |
+
if id_only and detail_only:
|
| 527 |
+
for index, voter_id in enumerate(id_only):
|
| 528 |
+
rec = empty_record()
|
| 529 |
+
rec["voter_id"] = voter_id
|
| 530 |
+
if index < len(detail_only):
|
| 531 |
+
merge_record(rec, detail_only[index])
|
| 532 |
+
parsed_rows.append(rec)
|
| 533 |
+
else:
|
| 534 |
+
for voter_id in id_only:
|
| 535 |
+
rec = empty_record()
|
| 536 |
+
rec["voter_id"] = voter_id
|
| 537 |
+
parsed_rows.append(rec)
|
| 538 |
+
parsed_rows.extend(detail_only)
|
| 539 |
+
|
| 540 |
+
# Last-chance single-region parse; never copy one set of fields across many IDs.
|
| 541 |
+
if not parsed_rows:
|
| 542 |
+
rec = parse_fields(raw)
|
| 543 |
+
if rec.get("voter_id") or record_has_fields(rec):
|
| 544 |
+
parsed_rows.append(rec)
|
| 545 |
+
|
| 546 |
+
return _deduplicate_records(parsed_rows)
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def _deduplicate_records(records: Iterable[Dict[str, str]]) -> List[Dict[str, str]]:
|
| 550 |
+
output: List[Dict[str, str]] = []
|
| 551 |
+
by_id: Dict[str, Dict[str, str]] = {}
|
| 552 |
+
for original in records:
|
| 553 |
+
rec = empty_record()
|
| 554 |
+
for column in CSV_COLUMNS:
|
| 555 |
+
rec[column] = re.sub(r"\s+", " ", str(original.get(column, "") or "")).strip()
|
| 556 |
+
voter_id = rec.get("voter_id", "")
|
| 557 |
+
if voter_id:
|
| 558 |
+
if voter_id in by_id:
|
| 559 |
+
merge_record(by_id[voter_id], rec)
|
| 560 |
+
else:
|
| 561 |
+
by_id[voter_id] = rec
|
| 562 |
+
output.append(rec)
|
| 563 |
+
elif record_has_fields(rec):
|
| 564 |
+
output.append(rec)
|
| 565 |
return output
|
| 566 |
|
| 567 |
|
| 568 |
+
def parse_ocr_records(raw: str) -> List[Dict[str, str]]:
|
| 569 |
+
"""Convert model output into one CSV record per detected voter ID/card."""
|
| 570 |
+
if not raw or not raw.strip():
|
| 571 |
+
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 572 |
|
| 573 |
+
html_records = _records_from_html(raw)
|
| 574 |
+
if html_records and any(record.get("voter_id") for record in html_records):
|
| 575 |
+
return html_records
|
| 576 |
|
| 577 |
+
grounded_records = _records_from_grounded(raw)
|
| 578 |
+
if grounded_records:
|
| 579 |
+
return grounded_records
|
| 580 |
|
| 581 |
+
return _records_from_markdown_or_plain(raw)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 582 |
|
|
|
|
|
|
|
| 583 |
|
| 584 |
+
# -----------------------------------------------------------------------------
|
| 585 |
+
# GPU inference
|
| 586 |
+
# -----------------------------------------------------------------------------
|
| 587 |
|
| 588 |
@spaces.GPU(duration=GPU_DURATION_SECONDS)
|
| 589 |
+
def run_ocr(image: Image.Image, profile_name: str = DEFAULT_PROFILE) -> str:
|
| 590 |
+
"""Run one full-page OCR inference; Grounding/Gundam may use internal crops."""
|
| 591 |
+
if image is None:
|
| 592 |
+
raise ValueError("Please send or upload an image first.")
|
| 593 |
+
|
| 594 |
+
profile = (profile_name or DEFAULT_PROFILE).strip().lower()
|
| 595 |
+
if profile not in OCR_PROFILES:
|
| 596 |
+
profile = DEFAULT_PROFILE
|
| 597 |
+
config = OCR_PROFILES[profile]
|
| 598 |
+
|
| 599 |
+
# Normalize orientation/color, without shrinking or cropping the page.
|
| 600 |
+
page = ImageOps.exif_transpose(image).convert("RGB")
|
| 601 |
+
started = time.perf_counter()
|
| 602 |
+
with tempfile.TemporaryDirectory(prefix="deepseek_ocr_") as output_dir:
|
| 603 |
+
image_path = os.path.join(output_dir, "input_page.png")
|
| 604 |
+
page.save(image_path, format="PNG", optimize=True)
|
| 605 |
+
with torch.inference_mode():
|
| 606 |
+
result = MODEL.infer(
|
| 607 |
+
TOKENIZER,
|
| 608 |
+
prompt=OCR_PROMPT,
|
| 609 |
image_file=image_path,
|
| 610 |
+
output_path=output_dir,
|
| 611 |
+
base_size=config["base_size"],
|
| 612 |
+
image_size=config["image_size"],
|
| 613 |
+
crop_mode=config["crop_mode"],
|
| 614 |
+
save_results=True,
|
| 615 |
test_compress=True,
|
| 616 |
eval_mode=True,
|
| 617 |
)
|
| 618 |
+
elapsed = time.perf_counter() - started
|
| 619 |
+
logger.info(
|
| 620 |
+
"OCR finished in %.1fs with profile=%s, base_size=%s, image_size=%s, crop_mode=%s",
|
| 621 |
+
elapsed, profile, config["base_size"], config["image_size"], config["crop_mode"],
|
| 622 |
+
)
|
| 623 |
+
return str(result or "").strip()
|
|
|
|
|
|
|
| 624 |
|
| 625 |
|
| 626 |
+
def records_to_csv_bytes(records: Sequence[Dict[str, str]]) -> bytes:
|
| 627 |
+
stream = io.StringIO(newline="")
|
| 628 |
+
writer = csv.DictWriter(stream, fieldnames=CSV_COLUMNS, extrasaction="ignore", lineterminator="\n")
|
| 629 |
+
writer.writeheader()
|
| 630 |
+
for record in records:
|
| 631 |
+
writer.writerow({column: record.get(column, "") for column in CSV_COLUMNS})
|
| 632 |
+
return stream.getvalue().encode("utf-8-sig")
|
| 633 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 634 |
|
| 635 |
+
def save_csv_tempfile(records: Sequence[Dict[str, str]]) -> str:
|
| 636 |
+
data = records_to_csv_bytes(records)
|
| 637 |
+
with tempfile.NamedTemporaryFile(prefix="voter_records_", suffix=".csv", delete=False) as file_obj:
|
| 638 |
+
file_obj.write(data)
|
| 639 |
+
return file_obj.name
|
| 640 |
|
| 641 |
+
|
| 642 |
+
def records_to_dataframe(records: Sequence[Dict[str, str]]) -> List[List[str]]:
|
| 643 |
+
return [[record.get(column, "") for column in CSV_COLUMNS] for record in records]
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def process_gradio_image(image: Optional[Image.Image], profile: str):
|
| 647 |
if image is None:
|
| 648 |
+
raise gr.Error("Upload a complete page image first.")
|
|
|
|
|
|
|
| 649 |
try:
|
| 650 |
+
raw = run_ocr(image, profile)
|
|
|
|
|
|
|
|
|
|
| 651 |
except Exception as exc:
|
| 652 |
logger.exception("Gradio OCR failed")
|
| 653 |
+
message = str(exc)
|
| 654 |
+
if "quota" in message.lower() or "duration" in message.lower() or "time limit" in message.lower():
|
| 655 |
+
raise gr.Error(
|
| 656 |
+
"The ZeroGPU request was rejected or timed out. Check GPU_DURATION_SECONDS and your remaining quota; "
|
| 657 |
+
"try OCR_PROFILE=tiny/small if the page still takes too long."
|
| 658 |
+
) from exc
|
| 659 |
+
raise gr.Error(f"OCR failed: {message[:500]}") from exc
|
| 660 |
+
|
| 661 |
+
records = parse_ocr_records(raw)
|
| 662 |
+
csv_path = save_csv_tempfile(records) if records else None
|
| 663 |
+
if not records:
|
| 664 |
+
summary = (
|
| 665 |
+
"No complete voter records could be grouped automatically. The raw OCR output is shown above. "
|
| 666 |
+
"Try Gundam for a clearer scan, then verify the text/coordinates before relying on a CSV."
|
| 667 |
+
)
|
| 668 |
+
else:
|
| 669 |
+
incomplete = sum(1 for record in records if not record.get("voter_id") or not record.get("name"))
|
| 670 |
+
summary = f"Parsed {len(records)} row(s). {incomplete} row(s) are missing a voter ID or name and need manual review."
|
| 671 |
+
return raw, records_to_dataframe(records), csv_path, summary
|
| 672 |
|
| 673 |
|
| 674 |
+
# -----------------------------------------------------------------------------
|
| 675 |
+
# Telegram bot: send the original image as a document for best resolution.
|
| 676 |
+
# -----------------------------------------------------------------------------
|
|
|
|
|
|
|
| 677 |
|
| 678 |
+
_bot_thread: Optional[threading.Thread] = None
|
| 679 |
+
_bot_lock = threading.Lock()
|
| 680 |
|
| 681 |
+
|
| 682 |
+
def _telegram_error_message(exc: Exception) -> str:
|
| 683 |
+
message = str(exc).lower()
|
| 684 |
+
if "quota" in message or "duration" in message or "time limit" in message:
|
| 685 |
+
return (
|
| 686 |
+
"The OCR task reached or was refused by the GPU time/quota limit. "
|
| 687 |
+
"Try a clearer/smaller page or set OCR_PROFILE=tiny/small; increasing GPU_DURATION_SECONDS only works "
|
| 688 |
+
"when ZeroGPU permits that reservation and enough quota remains."
|
|
|
|
|
|
|
| 689 |
)
|
| 690 |
+
if "out of memory" in message or "cuda" in message:
|
| 691 |
+
return "The GPU could not complete this image. Try OCR_PROFILE=tiny/small or send a clearer, smaller page."
|
| 692 |
+
return "OCR could not finish this image. Please try again or send the image as a document for better resolution."
|
| 693 |
|
| 694 |
|
| 695 |
+
async def telegram_start(update, context) -> None:
|
| 696 |
message = update.effective_message
|
| 697 |
+
if message:
|
| 698 |
+
await message.reply_text(
|
| 699 |
+
"Send one full-page electoral-roll image. I will OCR it and return a CSV file.\n\n"
|
| 700 |
+
"For best quality, send the page as a document/file so Telegram does not resize it. "
|
| 701 |
+
f"Current profile: {DEFAULT_PROFILE}."
|
| 702 |
+
)
|
| 703 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 704 |
|
| 705 |
+
async def telegram_help(update, context) -> None:
|
| 706 |
+
message = update.effective_message
|
| 707 |
+
if message:
|
| 708 |
+
await message.reply_text(
|
| 709 |
+
"How to use:\n"
|
| 710 |
+
"1. Send a clear image of one complete page.\n"
|
| 711 |
+
"2. Prefer sending it as a document/file to preserve resolution.\n"
|
| 712 |
+
"3. The bot returns voter_records.csv with voter ID, name, relative name/type, house number, age, gender and photo status.\n\n"
|
| 713 |
+
"Review the CSV before use: complex page layouts can cause OCR/grouping errors."
|
| 714 |
+
)
|
| 715 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 716 |
|
| 717 |
+
async def _download_image_from_telegram(update, context) -> Optional[Image.Image]:
|
| 718 |
+
message = update.effective_message
|
| 719 |
+
if not message:
|
| 720 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 721 |
|
| 722 |
+
telegram_file = None
|
| 723 |
+
if message.photo:
|
| 724 |
+
telegram_file = await context.bot.get_file(message.photo[-1].file_id)
|
| 725 |
+
elif message.document:
|
| 726 |
+
document = message.document
|
| 727 |
+
file_name = (document.file_name or "").lower()
|
| 728 |
+
mime_type = (document.mime_type or "").lower()
|
| 729 |
+
if not (mime_type.startswith("image/") or file_name.endswith((".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"))):
|
| 730 |
+
await message.reply_text("Please send a JPG, PNG, WEBP, BMP, or TIFF image. For best quality, send it as a document.")
|
| 731 |
+
return None
|
| 732 |
+
telegram_file = await context.bot.get_file(document.file_id)
|
| 733 |
+
if telegram_file is None:
|
| 734 |
+
return None
|
| 735 |
+
|
| 736 |
+
buffer = io.BytesIO()
|
| 737 |
+
await telegram_file.download_to_memory(buffer)
|
| 738 |
+
buffer.seek(0)
|
| 739 |
+
try:
|
| 740 |
+
image = Image.open(buffer)
|
| 741 |
+
image.load()
|
| 742 |
+
return ImageOps.exif_transpose(image).convert("RGB")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 743 |
except Exception as exc:
|
| 744 |
+
logger.warning("Telegram attachment was not a readable image: %s", exc)
|
| 745 |
+
await message.reply_text("I could not open this image. Try sending it as a JPG or PNG file.")
|
| 746 |
+
return None
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
async def _process_telegram_image(update, context) -> None:
|
| 750 |
+
message = update.effective_message
|
| 751 |
+
if not message:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 752 |
return
|
| 753 |
+
image = await _download_image_from_telegram(update, context)
|
| 754 |
+
if image is None:
|
|
|
|
| 755 |
return
|
| 756 |
|
| 757 |
+
await message.reply_text(f"Processing the complete page with profile '{DEFAULT_PROFILE}'…")
|
|
|
|
| 758 |
try:
|
| 759 |
+
# Keep the Telegram event loop responsive while the GPU call is running.
|
| 760 |
+
raw = await asyncio.to_thread(run_ocr, image, DEFAULT_PROFILE)
|
| 761 |
+
records = parse_ocr_records(raw)
|
| 762 |
+
if records:
|
| 763 |
+
csv_stream = io.BytesIO(records_to_csv_bytes(records))
|
| 764 |
+
csv_stream.name = "voter_records.csv"
|
| 765 |
+
incomplete = sum(1 for record in records if not record.get("voter_id") or not record.get("name"))
|
| 766 |
+
caption = f"Extracted {len(records)} row(s). Rows needing review: {incomplete}. Please verify against the original page."
|
| 767 |
+
await message.reply_document(
|
| 768 |
+
document=csv_stream,
|
| 769 |
+
filename="voter_records.csv",
|
| 770 |
+
caption=caption,
|
| 771 |
+
)
|
| 772 |
+
else:
|
| 773 |
+
raw_stream = io.BytesIO((raw or "No text was returned by the OCR model.").encode("utf-8"))
|
| 774 |
+
raw_stream.name = "ocr_raw_output.txt"
|
| 775 |
+
await message.reply_text(
|
| 776 |
+
"I could not reliably group the result into voter records, so I have not guessed the CSV rows. "
|
| 777 |
+
"Here is the raw OCR output for inspection. Try a full-resolution document upload or another profile."
|
| 778 |
+
)
|
| 779 |
+
await message.reply_document(document=raw_stream, filename="ocr_raw_output.txt")
|
| 780 |
+
except Exception as exc:
|
| 781 |
+
logger.exception("Telegram OCR request failed")
|
| 782 |
+
await message.reply_text(_telegram_error_message(exc))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 783 |
|
|
|
|
|
|
|
| 784 |
|
| 785 |
+
async def telegram_photo(update, context) -> None:
|
| 786 |
+
await _process_telegram_image(update, context)
|
| 787 |
|
|
|
|
|
|
|
| 788 |
|
| 789 |
+
async def telegram_document(update, context) -> None:
|
| 790 |
+
await _process_telegram_image(update, context)
|
| 791 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 792 |
|
| 793 |
+
def _telegram_worker() -> None:
|
| 794 |
+
# Imports live here so the Gradio UI can start even when PTB isn't installed.
|
| 795 |
+
try:
|
| 796 |
+
from telegram import error as telegram_error
|
| 797 |
+
from telegram.ext import Application, CommandHandler, MessageHandler, filters
|
| 798 |
+
except Exception:
|
| 799 |
+
logger.exception("python-telegram-bot is not installed; Telegram bot is disabled")
|
| 800 |
return
|
| 801 |
|
| 802 |
+
application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
|
| 803 |
+
application.add_handler(CommandHandler("start", telegram_start))
|
| 804 |
+
application.add_handler(CommandHandler("help", telegram_help))
|
| 805 |
+
application.add_handler(MessageHandler(filters.PHOTO, telegram_photo))
|
| 806 |
+
application.add_handler(MessageHandler(filters.Document.ALL, telegram_document))
|
| 807 |
+
|
| 808 |
+
logger.warning("Starting Telegram polling in PID=%s (once per app process)", os.getpid())
|
| 809 |
+
try:
|
| 810 |
+
# run_polling normally installs signal handlers, which is not allowed in a thread.
|
| 811 |
+
application.run_polling(drop_pending_updates=True, stop_signals=None)
|
| 812 |
+
except telegram_error.Conflict:
|
| 813 |
+
logger.error(
|
| 814 |
+
"Telegram polling conflict: another process is already using getUpdates for this bot token. "
|
| 815 |
+
"Stop any other bot instance and keep only one active polling process."
|
| 816 |
+
)
|
| 817 |
+
except Exception:
|
| 818 |
+
logger.exception("Telegram bot stopped unexpectedly")
|
| 819 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 820 |
|
| 821 |
+
def start_telegram_bot_once() -> None:
|
| 822 |
+
global _bot_thread
|
| 823 |
+
if not TELEGRAM_BOT_TOKEN:
|
| 824 |
+
logger.info("TELEGRAM_BOT_TOKEN/BOT_TOKEN is not set; starting Gradio UI without Telegram")
|
| 825 |
+
return
|
| 826 |
+
with _bot_lock:
|
| 827 |
+
if _bot_thread is not None and _bot_thread.is_alive():
|
| 828 |
+
logger.info("Telegram polling thread already started in this process; skipping duplicate start")
|
| 829 |
+
return
|
| 830 |
+
_bot_thread = threading.Thread(target=_telegram_worker, name="telegram-polling", daemon=True)
|
| 831 |
+
_bot_thread.start()
|
| 832 |
|
| 833 |
|
| 834 |
+
# -----------------------------------------------------------------------------
|
| 835 |
+
# Gradio UI
|
| 836 |
+
# -----------------------------------------------------------------------------
|
| 837 |
|
| 838 |
+
with gr.Blocks(title="DeepSeek-OCR — Full Page to CSV") as demo:
|
| 839 |
gr.Markdown(
|
| 840 |
+
"# DeepSeek-OCR: Full page to CSV\n"
|
| 841 |
+
"Upload one complete page. The app makes one OCR inference call, groups detected fields into rows, "
|
| 842 |
+
"and creates a UTF-8 CSV. For smaller text, try **Gundam** and send the original image as a document in Telegram."
|
| 843 |
)
|
| 844 |
with gr.Row():
|
| 845 |
+
with gr.Column(scale=1):
|
| 846 |
+
image_input = gr.Image(type="pil", label="Complete page image", sources=["upload", "clipboard"])
|
| 847 |
+
profile_input = gr.Dropdown(
|
| 848 |
+
choices=["tiny", "small", "base", "large", "gundam"],
|
| 849 |
+
value=DEFAULT_PROFILE,
|
| 850 |
+
label="OCR profile",
|
| 851 |
+
info="Gundam uses internal crops for detail; Tiny/Small are faster but may miss small text.",
|
| 852 |
+
)
|
| 853 |
+
run_button = gr.Button("OCR full page and create CSV", variant="primary")
|
| 854 |
+
with gr.Column(scale=2):
|
| 855 |
+
summary_output = gr.Textbox(label="Result summary", lines=2, interactive=False)
|
| 856 |
+
table_output = gr.Dataframe(
|
| 857 |
+
headers=CSV_COLUMNS,
|
| 858 |
+
datatype=["str"] * len(CSV_COLUMNS),
|
| 859 |
+
label="Parsed CSV rows — review before use",
|
| 860 |
+
interactive=False,
|
| 861 |
+
wrap=True,
|
| 862 |
)
|
| 863 |
+
csv_output = gr.File(label="Download CSV")
|
| 864 |
+
raw_output = gr.Textbox(label="Raw OCR output (for troubleshooting)", lines=12, max_lines=30, interactive=False)
|
|
|
|
|
|
|
| 865 |
gr.Markdown(
|
| 866 |
+
"**Important:** OCR and row grouping can make mistakes, especially when cards are close together or text is blurry. "
|
| 867 |
+
"Verify names, voter IDs and row associations against the source page."
|
|
|
|
| 868 |
)
|
| 869 |
+
run_button.click(
|
| 870 |
+
fn=process_gradio_image,
|
| 871 |
+
inputs=[image_input, profile_input],
|
| 872 |
+
outputs=[raw_output, table_output, csv_output, summary_output],
|
| 873 |
+
)
|
| 874 |
+
|
| 875 |
|
| 876 |
if __name__ == "__main__":
|
| 877 |
+
start_telegram_bot_once()
|
| 878 |
+
demo.queue(max_size=6).launch(server_name="0.0.0.0", ssr_mode=False)
|
requirements.txt
CHANGED
|
@@ -1,17 +1,9 @@
|
|
| 1 |
-
|
| 2 |
transformers==4.57.6
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
sentencepiece
|
| 6 |
-
safetensors>=0.4.3
|
| 7 |
addict
|
| 8 |
easydict
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
torchvision==0.28.0
|
| 13 |
-
pillow>=10,<12
|
| 14 |
-
pymupdf
|
| 15 |
-
python-telegram-bot>=22.0,<23.0
|
| 16 |
-
httpx>=0.27,<1.0
|
| 17 |
-
huggingface-hub>=0.34.0,<1.0
|
|
|
|
| 1 |
+
gradio>=4.44.0,<6.0
|
| 2 |
transformers==4.57.6
|
| 3 |
+
accelerate
|
| 4 |
+
einops
|
|
|
|
|
|
|
| 5 |
addict
|
| 6 |
easydict
|
| 7 |
+
Pillow
|
| 8 |
+
python-telegram-bot>=21.0,<23.0
|
| 9 |
+
spaces
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|