Upload 4 files
Browse files
README.md
CHANGED
|
@@ -14,6 +14,18 @@ pinned: false
|
|
| 14 |
|
| 15 |
This Space uses the `strangervisionhf/deepseek-ocr-transformers-v4.57.6` model.
|
| 16 |
|
| 17 |
-
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
This Space uses the `strangervisionhf/deepseek-ocr-transformers-v4.57.6` model.
|
| 16 |
|
| 17 |
+
## Telegram setup
|
| 18 |
|
| 19 |
+
1. Add a Space secret named `TELEGRAM_BOT_TOKEN` with the token from BotFather.
|
| 20 |
+
2. Long polling is used, so `WEBHOOK_URL` is not required.
|
| 21 |
+
3. For privacy, optionally set `TELEGRAM_ALLOWED_USER_IDS` to a comma-separated list of trusted Telegram numeric user IDs.
|
| 22 |
+
|
| 23 |
+
Send the bot an image as a Telegram photo or image document. It will show a status timer, use a 30-second checkpoint, and continue counting elapsed time if OCR takes longer. When processing finishes, the bot sends `deepseek_ocr_result.md` containing the **complete raw text returned by DeepSeek-OCR**. The text is not truncated, parsed into a CSV, or rewritten.
|
| 24 |
+
|
| 25 |
+
The model does not expose a dependable percentage-complete value, so the status bar represents elapsed time rather than actual model progress. The platform-side maximum for an OCR call is controlled by `GPU_DURATION_SECONDS` (default: `120` seconds). The Telegram handler itself does not time out at 30 seconds; the configured Hugging Face Space GPU runtime limit still applies. Use a value supported by your Space/account tier when changing this setting.
|
| 26 |
+
|
| 27 |
+
## Dependencies and launch
|
| 28 |
+
|
| 29 |
+
Dependencies are pinned or constrained in `requirements.txt`. `bootstrap.py` is retained as a no-op compatibility file and is not needed by `app.py`.
|
| 30 |
+
|
| 31 |
+
OCR output can be inaccurate. Review results before relying on them, and only upload documents you are authorized to process.
|
app.py
CHANGED
|
@@ -1,24 +1,19 @@
|
|
| 1 |
-
"""DeepSeek-OCR Gradio app with optional Telegram
|
| 2 |
|
| 3 |
-
Use a Gradio Space configured for Gradio 5.49.1 and ZeroGPU/GPU hardware.
|
| 4 |
Set TELEGRAM_BOT_TOKEN in Space Settings -> Variables and secrets to enable Telegram.
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
from __future__ import annotations
|
| 8 |
|
| 9 |
import asyncio
|
| 10 |
-
import csv
|
| 11 |
-
import html
|
| 12 |
-
import json
|
| 13 |
import logging
|
| 14 |
import os
|
| 15 |
-
import re
|
| 16 |
-
import sqlite3
|
| 17 |
import tempfile
|
| 18 |
import threading
|
| 19 |
-
import
|
| 20 |
from pathlib import Path
|
| 21 |
-
from typing import Any
|
| 22 |
|
| 23 |
# Import spaces before torch, as recommended for ZeroGPU Spaces.
|
| 24 |
import spaces
|
|
@@ -27,15 +22,8 @@ import gradio as gr
|
|
| 27 |
from PIL import Image
|
| 28 |
from transformers import AutoModel, AutoTokenizer
|
| 29 |
|
| 30 |
-
from telegram import Update
|
| 31 |
-
from telegram.ext import
|
| 32 |
-
Application,
|
| 33 |
-
CallbackQueryHandler,
|
| 34 |
-
CommandHandler,
|
| 35 |
-
ContextTypes,
|
| 36 |
-
MessageHandler,
|
| 37 |
-
filters,
|
| 38 |
-
)
|
| 39 |
|
| 40 |
|
| 41 |
logging.basicConfig(
|
|
@@ -47,10 +35,12 @@ logger = logging.getLogger("deepseek_ocr")
|
|
| 47 |
MODEL_ID = os.getenv(
|
| 48 |
"MODEL_ID", "strangervisionhf/deepseek-ocr-transformers-v4.57.6"
|
| 49 |
)
|
|
|
|
|
|
|
| 50 |
GPU_DURATION_SECONDS = int(os.getenv("GPU_DURATION_SECONDS", "120"))
|
| 51 |
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "").strip()
|
| 52 |
-
DB_PATH = os.getenv("DB_PATH", "ocr_records.db")
|
| 53 |
MAX_TELEGRAM_FILE_BYTES = 20 * 1024 * 1024
|
|
|
|
| 54 |
|
| 55 |
# Optional comma-separated allowlist of Telegram numeric user IDs.
|
| 56 |
# Example: TELEGRAM_ALLOWED_USER_IDS=123456789,987654321
|
|
@@ -73,158 +63,13 @@ PROMPTS = {
|
|
| 73 |
"Parse Figure": "<image>\nParse the figure.",
|
| 74 |
}
|
| 75 |
|
| 76 |
-
# Keep the existing voter-register field extraction, but support HTML tables,
|
| 77 |
-
# Markdown tables, and plain OCR text. Verify every extracted field before saving.
|
| 78 |
-
VOTER_ID_RE = re.compile(
|
| 79 |
-
r"(?<![A-Z0-9])(?:UP/\d+/\d+/\d+|[A-Z]{3}\d{7,})(?![A-Z0-9])",
|
| 80 |
-
flags=re.IGNORECASE,
|
| 81 |
-
)
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
def _clean_markup(value: str) -> str:
|
| 85 |
-
value = html.unescape(value or "")
|
| 86 |
-
value = re.sub(r"<br\s*/?>", "\n", value, flags=re.IGNORECASE)
|
| 87 |
-
value = re.sub(r"</(?:td|th|tr|p|div|li|section)>\s*", "\n", value, flags=re.IGNORECASE)
|
| 88 |
-
value = re.sub(r"<[^>]+>", " ", value)
|
| 89 |
-
value = value.replace("\xa0", " ").replace("|", " ")
|
| 90 |
-
lines = [re.sub(r"[ \t\r]+", " ", line).strip() for line in value.splitlines()]
|
| 91 |
-
return "\n".join(line for line in lines if line)
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
def _extract_field(text: str, label: str) -> str:
|
| 95 |
-
labels = (
|
| 96 |
-
r"पिता\s*का\s*नाम|पति\s*का\s*नाम|मकान\s*संख्या|आयु|लिंग|(?<!का )नाम"
|
| 97 |
-
)
|
| 98 |
-
if label == "name":
|
| 99 |
-
start = r"(?<!का )नाम"
|
| 100 |
-
elif label == "father_name":
|
| 101 |
-
start = r"पिता\s*का\s*नाम"
|
| 102 |
-
elif label == "husband_name":
|
| 103 |
-
start = r"पति\s*का\s*नाम"
|
| 104 |
-
elif label == "house_no":
|
| 105 |
-
start = r"मकान\s*संख्या"
|
| 106 |
-
elif label == "age":
|
| 107 |
-
start = r"आयु"
|
| 108 |
-
elif label == "gender":
|
| 109 |
-
start = r"लिंग"
|
| 110 |
-
else:
|
| 111 |
-
return ""
|
| 112 |
-
|
| 113 |
-
match = re.search(
|
| 114 |
-
rf"{start}\s*[::]?\s*(.*?)(?=\s*(?:{labels})\s*[::]?|$)",
|
| 115 |
-
text,
|
| 116 |
-
flags=re.DOTALL,
|
| 117 |
-
)
|
| 118 |
-
if not match:
|
| 119 |
-
return ""
|
| 120 |
-
value = re.sub(r"\s+", " ", match.group(1)).strip(" \t\r\n::-*|")
|
| 121 |
-
return value
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
def _record_from_text(row_text: str, voter_id: str) -> dict[str, Any] | None:
|
| 125 |
-
cleaned = _clean_markup(row_text)
|
| 126 |
-
if "नाम" not in cleaned:
|
| 127 |
-
return None
|
| 128 |
-
age_text = _extract_field(cleaned, "age")
|
| 129 |
-
age_match = re.search(r"\d{1,3}", age_text)
|
| 130 |
-
return {
|
| 131 |
-
"voter_id": voter_id.strip(),
|
| 132 |
-
"name": _extract_field(cleaned, "name"),
|
| 133 |
-
"father_name": _extract_field(cleaned, "father_name"),
|
| 134 |
-
"husband_name": _extract_field(cleaned, "husband_name"),
|
| 135 |
-
"house_no": _extract_field(cleaned, "house_no"),
|
| 136 |
-
"age": int(age_match.group()) if age_match else 0,
|
| 137 |
-
"gender": _extract_field(cleaned, "gender"),
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
def parse_markdown(raw: str) -> list[dict[str, Any]]:
|
| 142 |
-
"""Extract rows from OCR output when it contains voter-like IDs and labels."""
|
| 143 |
-
if not raw:
|
| 144 |
-
return []
|
| 145 |
-
|
| 146 |
-
candidate_rows: list[str] = []
|
| 147 |
-
|
| 148 |
-
# HTML tables are common in DeepSeek-OCR's Markdown/table output.
|
| 149 |
-
html_rows = re.findall(r"<tr\b[^>]*>(.*?)</tr>", raw, flags=re.IGNORECASE | re.DOTALL)
|
| 150 |
-
if html_rows:
|
| 151 |
-
for row in html_rows:
|
| 152 |
-
cells = re.findall(r"<t[dh]\b[^>]*>(.*?)</t[dh]>", row, flags=re.IGNORECASE | re.DOTALL)
|
| 153 |
-
candidate_rows.append("\n".join(cells) if cells else row)
|
| 154 |
-
else:
|
| 155 |
-
# Markdown tables: inspect each pipe-delimited row while skipping separators.
|
| 156 |
-
for line in raw.splitlines():
|
| 157 |
-
if "|" not in line:
|
| 158 |
-
continue
|
| 159 |
-
cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
|
| 160 |
-
if not cells or all(re.fullmatch(r":?-{3,}:?", c.replace(" ", "")) for c in cells if c):
|
| 161 |
-
continue
|
| 162 |
-
candidate_rows.append("\n".join(cells))
|
| 163 |
-
|
| 164 |
-
# Fallback for OCR text that is not formatted as a table: split around IDs.
|
| 165 |
-
if not candidate_rows:
|
| 166 |
-
clean = _clean_markup(raw)
|
| 167 |
-
found = list(VOTER_ID_RE.finditer(clean))
|
| 168 |
-
for index, match in enumerate(found):
|
| 169 |
-
end = found[index + 1].start() if index + 1 < len(found) else len(clean)
|
| 170 |
-
candidate_rows.append(f"{match.group()}\n{clean[match.start():end]}")
|
| 171 |
-
|
| 172 |
-
output: list[dict[str, Any]] = []
|
| 173 |
-
seen: set[str] = set()
|
| 174 |
-
id_only: list[str] = []
|
| 175 |
-
details_only: list[str] = []
|
| 176 |
-
|
| 177 |
-
for row in candidate_rows:
|
| 178 |
-
cleaned_row = _clean_markup(row)
|
| 179 |
-
ids = list(dict.fromkeys(m.group().strip() for m in VOTER_ID_RE.finditer(cleaned_row)))
|
| 180 |
-
if ids and "नाम" in cleaned_row:
|
| 181 |
-
for voter_id in ids:
|
| 182 |
-
record = _record_from_text(cleaned_row, voter_id)
|
| 183 |
-
if record and voter_id not in seen:
|
| 184 |
-
output.append(record)
|
| 185 |
-
seen.add(voter_id)
|
| 186 |
-
elif ids:
|
| 187 |
-
id_only.extend(v for v in ids if v not in seen)
|
| 188 |
-
elif "नाम" in cleaned_row:
|
| 189 |
-
details_only.append(cleaned_row)
|
| 190 |
-
|
| 191 |
-
# Some OCR layouts put the ID and details in adjacent table cells/rows.
|
| 192 |
-
for voter_id, details in zip(id_only, details_only):
|
| 193 |
-
if voter_id in seen:
|
| 194 |
-
continue
|
| 195 |
-
record = _record_from_text(details, voter_id)
|
| 196 |
-
if record:
|
| 197 |
-
output.append(record)
|
| 198 |
-
seen.add(voter_id)
|
| 199 |
-
|
| 200 |
-
return output
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
def init_db() -> None:
|
| 204 |
-
db_parent = Path(DB_PATH).expanduser().resolve().parent
|
| 205 |
-
db_parent.mkdir(parents=True, exist_ok=True)
|
| 206 |
-
conn = sqlite3.connect(DB_PATH)
|
| 207 |
-
try:
|
| 208 |
-
conn.execute(
|
| 209 |
-
"""CREATE TABLE IF NOT EXISTS voters (
|
| 210 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 211 |
-
voter_id TEXT,
|
| 212 |
-
name TEXT,
|
| 213 |
-
father_name TEXT,
|
| 214 |
-
husband_name TEXT,
|
| 215 |
-
house_no TEXT,
|
| 216 |
-
age INTEGER,
|
| 217 |
-
gender TEXT,
|
| 218 |
-
raw_json TEXT
|
| 219 |
-
)"""
|
| 220 |
-
)
|
| 221 |
-
conn.commit()
|
| 222 |
-
finally:
|
| 223 |
-
conn.close()
|
| 224 |
-
|
| 225 |
|
| 226 |
logger.info("Loading model: %s", MODEL_ID)
|
| 227 |
-
logger.info(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
|
| 229 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 230 |
load_device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
@@ -246,7 +91,7 @@ _INFERENCE_LOCK = threading.Lock()
|
|
| 246 |
|
| 247 |
@spaces.GPU(duration=GPU_DURATION_SECONDS)
|
| 248 |
def run_ocr(image_path: str, prompt: str = PROMPTS["Convert to Markdown"]) -> str:
|
| 249 |
-
"""Run
|
| 250 |
output_dir = tempfile.TemporaryDirectory(prefix="deepseek_ocr_out_")
|
| 251 |
try:
|
| 252 |
with _INFERENCE_LOCK, torch.inference_mode():
|
|
@@ -292,16 +137,48 @@ def _authorized(update: Update) -> bool:
|
|
| 292 |
return user is not None and user.id in ALLOWED_TELEGRAM_USER_IDS
|
| 293 |
|
| 294 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
|
|
|
| 296 |
if not _authorized(update):
|
| 297 |
if update.effective_message:
|
| 298 |
-
await update.effective_message.reply_text(
|
|
|
|
|
|
|
| 299 |
return
|
| 300 |
if update.effective_message:
|
| 301 |
await update.effective_message.reply_text(
|
| 302 |
-
"Send an image as a photo or image document. I
|
| 303 |
-
"
|
| 304 |
-
"
|
| 305 |
)
|
| 306 |
|
| 307 |
|
|
@@ -337,103 +214,90 @@ async def on_image(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
|
| 337 |
suffix = Path(original_name).suffix.lower()
|
| 338 |
if suffix not in {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"}:
|
| 339 |
suffix = ".jpg"
|
|
|
|
| 340 |
local_path = None
|
| 341 |
-
|
|
|
|
|
|
|
| 342 |
|
| 343 |
try:
|
| 344 |
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as handle:
|
| 345 |
local_path = handle.name
|
|
|
|
| 346 |
telegram_file = await context.bot.get_file(file_id)
|
| 347 |
await telegram_file.download_to_drive(custom_path=local_path)
|
| 348 |
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
return
|
| 355 |
|
| 356 |
-
|
| 357 |
-
with
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
)
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
context.user_data["csv_path"] = csv_path
|
| 366 |
-
context.user_data["records"] = records
|
| 367 |
-
keyboard = InlineKeyboardMarkup(
|
| 368 |
-
[[
|
| 369 |
-
InlineKeyboardButton("✅ Save to database", callback_data="save"),
|
| 370 |
-
InlineKeyboardButton("❌ Cancel", callback_data="cancel"),
|
| 371 |
-
]]
|
| 372 |
-
)
|
| 373 |
-
await status.edit_text(f"OCR finished. Found {len(records)} possible records; review the CSV before saving.")
|
| 374 |
-
with open(csv_path, "rb") as csv_file:
|
| 375 |
await message.reply_document(
|
| 376 |
-
document=
|
| 377 |
-
filename="
|
| 378 |
-
caption=
|
| 379 |
-
|
|
|
|
|
|
|
| 380 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
except Exception as exc:
|
| 382 |
logger.exception("Telegram OCR pipeline failed")
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
finally:
|
| 388 |
-
if local_path and os.path.exists(local_path):
|
| 389 |
-
os.remove(local_path)
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
async def on_button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 393 |
-
query = update.callback_query
|
| 394 |
-
if query is None:
|
| 395 |
-
return
|
| 396 |
-
await query.answer()
|
| 397 |
-
if not _authorized(update):
|
| 398 |
-
await query.edit_message_caption(caption="This bot is not enabled for your account.")
|
| 399 |
-
return
|
| 400 |
-
|
| 401 |
-
csv_path = context.user_data.get("csv_path")
|
| 402 |
-
records = context.user_data.get("records")
|
| 403 |
-
try:
|
| 404 |
-
if query.data == "save" and records:
|
| 405 |
-
conn = sqlite3.connect(DB_PATH)
|
| 406 |
-
try:
|
| 407 |
-
conn.executemany(
|
| 408 |
-
"""INSERT INTO voters
|
| 409 |
-
(voter_id, name, father_name, husband_name, house_no, age, gender, raw_json)
|
| 410 |
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
|
| 411 |
-
[
|
| 412 |
-
(
|
| 413 |
-
row["voter_id"], row["name"], row["father_name"],
|
| 414 |
-
row["husband_name"], row["house_no"], row["age"],
|
| 415 |
-
row["gender"], json.dumps(row, ensure_ascii=False),
|
| 416 |
-
)
|
| 417 |
-
for row in records
|
| 418 |
-
],
|
| 419 |
-
)
|
| 420 |
-
conn.commit()
|
| 421 |
-
finally:
|
| 422 |
-
conn.close()
|
| 423 |
-
await query.edit_message_caption(caption=f"Saved {len(records)} records to the local database.")
|
| 424 |
-
elif query.data == "cancel":
|
| 425 |
-
await query.edit_message_caption(caption="Cancelled. No records were saved.")
|
| 426 |
-
except Exception:
|
| 427 |
-
logger.exception("Could not save/cancel records")
|
| 428 |
-
await query.edit_message_caption(caption="Could not complete that action. Check the Space logs.")
|
| 429 |
finally:
|
| 430 |
-
|
| 431 |
-
os.
|
| 432 |
-
|
| 433 |
-
|
|
|
|
|
|
|
| 434 |
|
| 435 |
|
| 436 |
async def telegram_error(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
|
|
|
| 437 |
logger.error("Telegram handler error", exc_info=context.error)
|
| 438 |
|
| 439 |
|
|
@@ -448,7 +312,6 @@ def start_telegram_bot() -> None:
|
|
| 448 |
bot_app.add_handler(
|
| 449 |
MessageHandler((filters.PHOTO | filters.Document.IMAGE) & ~filters.COMMAND, on_image)
|
| 450 |
)
|
| 451 |
-
bot_app.add_handler(CallbackQueryHandler(on_button))
|
| 452 |
bot_app.add_error_handler(telegram_error)
|
| 453 |
|
| 454 |
async def worker() -> None:
|
|
@@ -465,19 +328,21 @@ def start_telegram_bot() -> None:
|
|
| 465 |
try:
|
| 466 |
asyncio.run(worker())
|
| 467 |
except Exception:
|
| 468 |
-
logger.exception(
|
|
|
|
|
|
|
| 469 |
|
| 470 |
threading.Thread(target=thread_target, daemon=True, name="telegram-polling").start()
|
| 471 |
|
| 472 |
|
| 473 |
-
init_db()
|
| 474 |
start_telegram_bot()
|
| 475 |
|
| 476 |
with gr.Blocks(title="DeepSeek-OCR") as demo:
|
| 477 |
gr.Markdown(
|
| 478 |
"# DeepSeek-OCR\n"
|
| 479 |
"Upload an image for OCR. The same model is available through Telegram when "
|
| 480 |
-
"`TELEGRAM_BOT_TOKEN` is configured in Space secrets."
|
|
|
|
| 481 |
)
|
| 482 |
with gr.Row():
|
| 483 |
with gr.Column():
|
|
@@ -492,9 +357,10 @@ with gr.Blocks(title="DeepSeek-OCR") as demo:
|
|
| 492 |
output_text = gr.Textbox(label="OCR output", lines=18, show_copy_button=True)
|
| 493 |
run_button.click(fn=gradio_ocr, inputs=[image_input, task_input], outputs=output_text)
|
| 494 |
gr.Markdown(
|
| 495 |
-
"**Note:** OCR can be inaccurate. Verify
|
| 496 |
-
"
|
| 497 |
-
"
|
|
|
|
| 498 |
)
|
| 499 |
|
| 500 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
"""DeepSeek-OCR Gradio app with an optional Telegram Markdown bot.
|
| 2 |
|
|
|
|
| 3 |
Set TELEGRAM_BOT_TOKEN in Space Settings -> Variables and secrets to enable Telegram.
|
| 4 |
+
Telegram receives an image, waits for OCR to finish, and returns the complete model
|
| 5 |
+
output as a .md file. The status message is a timer, not a measured OCR percentage.
|
| 6 |
"""
|
| 7 |
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
import asyncio
|
|
|
|
|
|
|
|
|
|
| 11 |
import logging
|
| 12 |
import os
|
|
|
|
|
|
|
| 13 |
import tempfile
|
| 14 |
import threading
|
| 15 |
+
import time
|
| 16 |
from pathlib import Path
|
|
|
|
| 17 |
|
| 18 |
# Import spaces before torch, as recommended for ZeroGPU Spaces.
|
| 19 |
import spaces
|
|
|
|
| 22 |
from PIL import Image
|
| 23 |
from transformers import AutoModel, AutoTokenizer
|
| 24 |
|
| 25 |
+
from telegram import Update
|
| 26 |
+
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
|
| 29 |
logging.basicConfig(
|
|
|
|
| 35 |
MODEL_ID = os.getenv(
|
| 36 |
"MODEL_ID", "strangervisionhf/deepseek-ocr-transformers-v4.57.6"
|
| 37 |
)
|
| 38 |
+
# This is the platform-side GPU runtime limit, not the Telegram 30-second checkpoint.
|
| 39 |
+
# Increase it only to a value supported by your Hugging Face Space/account tier.
|
| 40 |
GPU_DURATION_SECONDS = int(os.getenv("GPU_DURATION_SECONDS", "120"))
|
| 41 |
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "").strip()
|
|
|
|
| 42 |
MAX_TELEGRAM_FILE_BYTES = 20 * 1024 * 1024
|
| 43 |
+
TELEGRAM_PROGRESS_UPDATE_SECONDS = 4
|
| 44 |
|
| 45 |
# Optional comma-separated allowlist of Telegram numeric user IDs.
|
| 46 |
# Example: TELEGRAM_ALLOWED_USER_IDS=123456789,987654321
|
|
|
|
| 63 |
"Parse Figure": "<image>\nParse the figure.",
|
| 64 |
}
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
logger.info("Loading model: %s", MODEL_ID)
|
| 68 |
+
logger.info(
|
| 69 |
+
"Torch version: %s | CUDA visible: %s",
|
| 70 |
+
torch.__version__,
|
| 71 |
+
torch.cuda.is_available(),
|
| 72 |
+
)
|
| 73 |
|
| 74 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 75 |
load_device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 91 |
|
| 92 |
@spaces.GPU(duration=GPU_DURATION_SECONDS)
|
| 93 |
def run_ocr(image_path: str, prompt: str = PROMPTS["Convert to Markdown"]) -> str:
|
| 94 |
+
"""Run DeepSeek-OCR and return its raw output without post-processing."""
|
| 95 |
output_dir = tempfile.TemporaryDirectory(prefix="deepseek_ocr_out_")
|
| 96 |
try:
|
| 97 |
with _INFERENCE_LOCK, torch.inference_mode():
|
|
|
|
| 137 |
return user is not None and user.id in ALLOWED_TELEGRAM_USER_IDS
|
| 138 |
|
| 139 |
|
| 140 |
+
def _progress_text(elapsed_seconds: int) -> str:
|
| 141 |
+
"""Format an honest timer bar; model inference does not expose a true percentage."""
|
| 142 |
+
elapsed_seconds = max(0, elapsed_seconds)
|
| 143 |
+
if elapsed_seconds < 30:
|
| 144 |
+
filled = min(10, int(elapsed_seconds / 30 * 10))
|
| 145 |
+
bar = "█" * filled + "░" * (10 - filled)
|
| 146 |
+
return (
|
| 147 |
+
"🔄 DeepSeek-OCR is processing your image.\n"
|
| 148 |
+
f"[{bar}] {elapsed_seconds}/30 sec\n"
|
| 149 |
+
"This is a timer checkpoint, not an OCR percentage. "
|
| 150 |
+
"I’ll send the complete Markdown when processing finishes."
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
minutes, seconds = divmod(elapsed_seconds, 60)
|
| 154 |
+
return (
|
| 155 |
+
"🔄 DeepSeek-OCR is still processing your image.\n"
|
| 156 |
+
f"Elapsed: {minutes}m {seconds:02d}s\n"
|
| 157 |
+
"The 30-second checkpoint has passed; I’m still waiting for the full result."
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
async def _try_edit_status(status_message, text: str) -> None:
|
| 162 |
+
"""A status edit failure should not interrupt an OCR task already in progress."""
|
| 163 |
+
try:
|
| 164 |
+
await status_message.edit_text(text)
|
| 165 |
+
except Exception:
|
| 166 |
+
logger.debug("Could not update Telegram OCR status message", exc_info=True)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 170 |
+
del context
|
| 171 |
if not _authorized(update):
|
| 172 |
if update.effective_message:
|
| 173 |
+
await update.effective_message.reply_text(
|
| 174 |
+
"This bot is not enabled for your account."
|
| 175 |
+
)
|
| 176 |
return
|
| 177 |
if update.effective_message:
|
| 178 |
await update.effective_message.reply_text(
|
| 179 |
+
"Send an image as a photo or image document. I’ll run DeepSeek-OCR and "
|
| 180 |
+
"send its complete returned output as a Markdown (.md) file. "
|
| 181 |
+
"The status message counts past 30 seconds if OCR is still running."
|
| 182 |
)
|
| 183 |
|
| 184 |
|
|
|
|
| 214 |
suffix = Path(original_name).suffix.lower()
|
| 215 |
if suffix not in {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"}:
|
| 216 |
suffix = ".jpg"
|
| 217 |
+
|
| 218 |
local_path = None
|
| 219 |
+
markdown_path = None
|
| 220 |
+
status = await message.reply_text("📥 Image received. Downloading it before OCR…")
|
| 221 |
+
started_at = time.monotonic()
|
| 222 |
|
| 223 |
try:
|
| 224 |
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as handle:
|
| 225 |
local_path = handle.name
|
| 226 |
+
|
| 227 |
telegram_file = await context.bot.get_file(file_id)
|
| 228 |
await telegram_file.download_to_drive(custom_path=local_path)
|
| 229 |
|
| 230 |
+
# Run the synchronous inference off the bot event loop, and keep polling the
|
| 231 |
+
# task instead of timing out at 30 seconds. The GPU decorator remains the
|
| 232 |
+
# platform-enforced upper bound for one inference call.
|
| 233 |
+
started_at = time.monotonic()
|
| 234 |
+
await _try_edit_status(status, _progress_text(0))
|
| 235 |
+
ocr_task = asyncio.create_task(
|
| 236 |
+
asyncio.to_thread(run_ocr, local_path, PROMPTS["Convert to Markdown"])
|
| 237 |
+
)
|
| 238 |
+
last_update_elapsed = 0
|
| 239 |
+
while not ocr_task.done():
|
| 240 |
+
await asyncio.sleep(1)
|
| 241 |
+
elapsed = int(time.monotonic() - started_at)
|
| 242 |
+
if (
|
| 243 |
+
not ocr_task.done()
|
| 244 |
+
and elapsed - last_update_elapsed >= TELEGRAM_PROGRESS_UPDATE_SECONDS
|
| 245 |
+
):
|
| 246 |
+
await _try_edit_status(status, _progress_text(elapsed))
|
| 247 |
+
last_update_elapsed = elapsed
|
| 248 |
+
|
| 249 |
+
# Awaiting the task propagates any model exception instead of hiding it.
|
| 250 |
+
raw = await ocr_task
|
| 251 |
+
elapsed = max(0, int(time.monotonic() - started_at))
|
| 252 |
+
markdown = raw if isinstance(raw, str) else str(raw)
|
| 253 |
+
|
| 254 |
+
if not markdown.strip():
|
| 255 |
+
await _try_edit_status(
|
| 256 |
+
status,
|
| 257 |
+
f"OCR finished after {elapsed}s, but the model returned no text. "
|
| 258 |
+
"Please try a clearer image.",
|
| 259 |
+
)
|
| 260 |
return
|
| 261 |
|
| 262 |
+
# Save the exact raw model string: no truncation, parsing, or Markdown rewriting.
|
| 263 |
+
with tempfile.NamedTemporaryFile(
|
| 264 |
+
mode="w", encoding="utf-8", newline="", suffix=".md", delete=False
|
| 265 |
+
) as handle:
|
| 266 |
+
markdown_path = handle.name
|
| 267 |
+
handle.write(markdown)
|
| 268 |
+
|
| 269 |
+
with open(markdown_path, "rb") as markdown_file:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
await message.reply_document(
|
| 271 |
+
document=markdown_file,
|
| 272 |
+
filename="deepseek_ocr_result.md",
|
| 273 |
+
caption=(
|
| 274 |
+
f"DeepSeek-OCR finished in {elapsed}s. "
|
| 275 |
+
"Complete Markdown output is attached."
|
| 276 |
+
),
|
| 277 |
)
|
| 278 |
+
|
| 279 |
+
await _try_edit_status(
|
| 280 |
+
status,
|
| 281 |
+
f"✅ OCR completed in {elapsed}s. Sent the full Markdown file: "
|
| 282 |
+
"deepseek_ocr_result.md",
|
| 283 |
+
)
|
| 284 |
except Exception as exc:
|
| 285 |
logger.exception("Telegram OCR pipeline failed")
|
| 286 |
+
await _try_edit_status(
|
| 287 |
+
status,
|
| 288 |
+
f"OCR failed: {type(exc).__name__}. Check the Space logs for details.",
|
| 289 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
finally:
|
| 291 |
+
for temp_path in (local_path, markdown_path):
|
| 292 |
+
if temp_path and os.path.exists(temp_path):
|
| 293 |
+
try:
|
| 294 |
+
os.remove(temp_path)
|
| 295 |
+
except OSError:
|
| 296 |
+
logger.warning("Could not remove temporary file: %s", temp_path)
|
| 297 |
|
| 298 |
|
| 299 |
async def telegram_error(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 300 |
+
del update
|
| 301 |
logger.error("Telegram handler error", exc_info=context.error)
|
| 302 |
|
| 303 |
|
|
|
|
| 312 |
bot_app.add_handler(
|
| 313 |
MessageHandler((filters.PHOTO | filters.Document.IMAGE) & ~filters.COMMAND, on_image)
|
| 314 |
)
|
|
|
|
| 315 |
bot_app.add_error_handler(telegram_error)
|
| 316 |
|
| 317 |
async def worker() -> None:
|
|
|
|
| 328 |
try:
|
| 329 |
asyncio.run(worker())
|
| 330 |
except Exception:
|
| 331 |
+
logger.exception(
|
| 332 |
+
"Telegram bot failed to start. Check TELEGRAM_BOT_TOKEN and polling conflicts."
|
| 333 |
+
)
|
| 334 |
|
| 335 |
threading.Thread(target=thread_target, daemon=True, name="telegram-polling").start()
|
| 336 |
|
| 337 |
|
|
|
|
| 338 |
start_telegram_bot()
|
| 339 |
|
| 340 |
with gr.Blocks(title="DeepSeek-OCR") as demo:
|
| 341 |
gr.Markdown(
|
| 342 |
"# DeepSeek-OCR\n"
|
| 343 |
"Upload an image for OCR. The same model is available through Telegram when "
|
| 344 |
+
"`TELEGRAM_BOT_TOKEN` is configured in Space secrets. Telegram returns the full "
|
| 345 |
+
"raw OCR output as a `.md` attachment."
|
| 346 |
)
|
| 347 |
with gr.Row():
|
| 348 |
with gr.Column():
|
|
|
|
| 357 |
output_text = gr.Textbox(label="OCR output", lines=18, show_copy_button=True)
|
| 358 |
run_button.click(fn=gradio_ocr, inputs=[image_input, task_input], outputs=output_text)
|
| 359 |
gr.Markdown(
|
| 360 |
+
"**Note:** OCR can be inaccurate. Verify results before relying on them. "
|
| 361 |
+
"The Telegram progress message is a timer because the model does not expose a "
|
| 362 |
+
"reliable percentage-complete value. GPU calls are still limited by the Space's "
|
| 363 |
+
"configured `GPU_DURATION_SECONDS`."
|
| 364 |
)
|
| 365 |
|
| 366 |
if __name__ == "__main__":
|