Upload 4 files
Browse files
README.md
CHANGED
|
@@ -14,6 +14,10 @@ pinned: false
|
|
| 14 |
|
| 15 |
This Space uses the `strangervisionhf/deepseek-ocr-transformers-v4.57.6` model.
|
| 16 |
|
| 17 |
-
To enable Telegram, add a Space secret named `TELEGRAM_BOT_TOKEN` with the token from BotFather. Long polling is used; `WEBHOOK_URL` is not required.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
The app's CSV/database extraction targets voter-style rows only. Review OCR results before saving them and avoid uploading identity documents unless you are authorized to process them.
|
|
|
|
| 14 |
|
| 15 |
This Space uses the `strangervisionhf/deepseek-ocr-transformers-v4.57.6` model.
|
| 16 |
|
| 17 |
+
To enable Telegram, add a Space secret named `TELEGRAM_BOT_TOKEN` with the token from BotFather. Long polling is used; `WEBHOOK_URL` is not required. Only one running process/Space should poll a token. A Telegram `409 Conflict` means another instance is also polling; stop it or rotate the token and configure the new token in only one Space. HTTP request logs are suppressed so token-bearing URLs are not printed at INFO level.
|
| 18 |
+
|
| 19 |
+
## ZeroGPU profiles
|
| 20 |
+
|
| 21 |
+
The default `OCR_PROFILE=small` reserves at most 60 seconds and uses the model's 640×640 Small mode to reduce quota rejections and timeouts. To prioritize speed, set `OCR_PROFILE=tiny` (512×512, less detail). To prioritize detailed OCR, set `OCR_PROFILE=gundam` (1024 base plus 640 crops), but this can take much longer and requires enough ZeroGPU quota for a 180-second reservation. `GPU_DURATION_SECONDS` can reduce a profile's reservation; it cannot raise it above that profile's maximum. DeepSeek-OCR is slower on dense tables, so verify record counts and fields before saving.
|
| 22 |
|
| 23 |
The app's CSV/database extraction targets voter-style rows only. Review OCR results before saving them and avoid uploading identity documents unless you are authorized to process them.
|
app.py
CHANGED
|
@@ -16,6 +16,7 @@ import re
|
|
| 16 |
import sqlite3
|
| 17 |
import tempfile
|
| 18 |
import threading
|
|
|
|
| 19 |
import uuid
|
| 20 |
from pathlib import Path
|
| 21 |
from typing import Any
|
|
@@ -43,11 +44,45 @@ logging.basicConfig(
|
|
| 43 |
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 44 |
)
|
| 45 |
logger = logging.getLogger("deepseek_ocr")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
MODEL_ID = os.getenv(
|
| 48 |
"MODEL_ID", "strangervisionhf/deepseek-ocr-transformers-v4.57.6"
|
| 49 |
)
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
|
@@ -318,24 +353,49 @@ def run_ocr(image_path: str, prompt: str = PROMPTS["Convert to Markdown"]) -> st
|
|
| 318 |
"""Run the model. The model is placed on the selected device at startup."""
|
| 319 |
output_dir = tempfile.TemporaryDirectory(prefix="deepseek_ocr_out_")
|
| 320 |
try:
|
|
|
|
| 321 |
with _INFERENCE_LOCK, torch.inference_mode():
|
| 322 |
result = model.infer(
|
| 323 |
tokenizer,
|
| 324 |
prompt=prompt,
|
| 325 |
image_file=image_path,
|
| 326 |
output_path=output_dir.name,
|
| 327 |
-
base_size=
|
| 328 |
-
image_size=
|
| 329 |
-
crop_mode=
|
| 330 |
save_results=False,
|
| 331 |
test_compress=True,
|
| 332 |
eval_mode=True,
|
| 333 |
)
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
finally:
|
| 336 |
output_dir.cleanup()
|
| 337 |
|
| 338 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
def gradio_ocr(image: Image.Image | None, task: str) -> str:
|
| 340 |
if image is None:
|
| 341 |
raise gr.Error("Upload an image first.")
|
|
@@ -348,7 +408,7 @@ def gradio_ocr(image: Image.Image | None, task: str) -> str:
|
|
| 348 |
return run_ocr(temp_path, prompt)
|
| 349 |
except Exception as exc:
|
| 350 |
logger.exception("Gradio OCR failed")
|
| 351 |
-
raise gr.Error(
|
| 352 |
finally:
|
| 353 |
if temp_path and os.path.exists(temp_path):
|
| 354 |
os.remove(temp_path)
|
|
@@ -449,10 +509,12 @@ async def on_image(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
|
| 449 |
)
|
| 450 |
except Exception as exc:
|
| 451 |
logger.exception("Telegram OCR pipeline failed")
|
|
|
|
|
|
|
| 452 |
try:
|
| 453 |
-
await status.edit_text(
|
| 454 |
except Exception:
|
| 455 |
-
await message.reply_text(
|
| 456 |
finally:
|
| 457 |
if local_path and os.path.exists(local_path):
|
| 458 |
os.remove(local_path)
|
|
@@ -506,8 +568,19 @@ async def telegram_error(update: object, context: ContextTypes.DEFAULT_TYPE) ->
|
|
| 506 |
logger.error("Telegram handler error", exc_info=context.error)
|
| 507 |
|
| 508 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 509 |
def start_telegram_bot() -> None:
|
| 510 |
"""Start the bot using long polling; no inbound webhook route is needed."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 511 |
if not TELEGRAM_BOT_TOKEN:
|
| 512 |
logger.warning("TELEGRAM_BOT_TOKEN is not set; Telegram integration is disabled.")
|
| 513 |
return
|
|
@@ -534,7 +607,11 @@ def start_telegram_bot() -> None:
|
|
| 534 |
try:
|
| 535 |
asyncio.run(worker())
|
| 536 |
except Exception:
|
| 537 |
-
logger.exception(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 538 |
|
| 539 |
threading.Thread(target=thread_target, daemon=True, name="telegram-polling").start()
|
| 540 |
|
|
|
|
| 16 |
import sqlite3
|
| 17 |
import tempfile
|
| 18 |
import threading
|
| 19 |
+
import time
|
| 20 |
import uuid
|
| 21 |
from pathlib import Path
|
| 22 |
from typing import Any
|
|
|
|
| 44 |
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 45 |
)
|
| 46 |
logger = logging.getLogger("deepseek_ocr")
|
| 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 |
+
# ZeroGPU checks the *reserved duration* against remaining quota before it
|
| 57 |
+
# starts inference. The prior 180s reservation was rejected when only 65s were
|
| 58 |
+
# left. A lower-resolution profile is the default so one OCR request is more
|
| 59 |
+
# likely to finish inside the smaller reservation.
|
| 60 |
+
OCR_PROFILES = {
|
| 61 |
+
# DeepSeek-OCR documented Tiny mode: fastest, but least detail.
|
| 62 |
+
"tiny": {"base_size": 512, "image_size": 512, "crop_mode": False, "max_duration": 45},
|
| 63 |
+
# DeepSeek-OCR documented Small mode: a compromise for free ZeroGPU.
|
| 64 |
+
"small": {"base_size": 640, "image_size": 640, "crop_mode": False, "max_duration": 60},
|
| 65 |
+
# Gundam/dynamic crops: more detail, but slower and needs sufficient quota.
|
| 66 |
+
"gundam": {"base_size": 1024, "image_size": 640, "crop_mode": True, "max_duration": 180},
|
| 67 |
+
}
|
| 68 |
+
OCR_PROFILE = os.getenv("OCR_PROFILE", "small").strip().lower()
|
| 69 |
+
if OCR_PROFILE not in OCR_PROFILES:
|
| 70 |
+
logger.warning("Unknown OCR_PROFILE=%r; using 'small'.", OCR_PROFILE)
|
| 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 |
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "").strip()
|
| 87 |
DB_PATH = os.getenv("DB_PATH", "ocr_records.db")
|
| 88 |
MAX_TELEGRAM_FILE_BYTES = 20 * 1024 * 1024
|
|
|
|
| 353 |
"""Run the model. The model is placed on the selected device at startup."""
|
| 354 |
output_dir = tempfile.TemporaryDirectory(prefix="deepseek_ocr_out_")
|
| 355 |
try:
|
| 356 |
+
started_at = time.perf_counter()
|
| 357 |
with _INFERENCE_LOCK, torch.inference_mode():
|
| 358 |
result = model.infer(
|
| 359 |
tokenizer,
|
| 360 |
prompt=prompt,
|
| 361 |
image_file=image_path,
|
| 362 |
output_path=output_dir.name,
|
| 363 |
+
base_size=int(_profile["base_size"]),
|
| 364 |
+
image_size=int(_profile["image_size"]),
|
| 365 |
+
crop_mode=bool(_profile["crop_mode"]),
|
| 366 |
save_results=False,
|
| 367 |
test_compress=True,
|
| 368 |
eval_mode=True,
|
| 369 |
)
|
| 370 |
+
text_result = result if isinstance(result, str) else str(result)
|
| 371 |
+
logger.info(
|
| 372 |
+
"OCR complete: profile=%s, duration=%.1fs, output_chars=%d",
|
| 373 |
+
OCR_PROFILE, time.perf_counter() - started_at, len(text_result),
|
| 374 |
+
)
|
| 375 |
+
return text_result
|
| 376 |
finally:
|
| 377 |
output_dir.cleanup()
|
| 378 |
|
| 379 |
|
| 380 |
+
def _friendly_ocr_error(exc: BaseException) -> str:
|
| 381 |
+
"""Turn ZeroGPU quota/runtime failures into actionable, non-secret text."""
|
| 382 |
+
message = str(exc).lower()
|
| 383 |
+
if "quota exceeded" in message or ("requested" in message and "left" in message and "zerogpu" in message):
|
| 384 |
+
return (
|
| 385 |
+
"ZeroGPU quota is currently too low for this OCR request. The selected "
|
| 386 |
+
f"'{OCR_PROFILE}' profile reserves up to {GPU_DURATION_SECONDS}s. "
|
| 387 |
+
"Wait until the reset time shown in the Space logs, or use a lower-cost "
|
| 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 |
def gradio_ocr(image: Image.Image | None, task: str) -> str:
|
| 400 |
if image is None:
|
| 401 |
raise gr.Error("Upload an image first.")
|
|
|
|
| 408 |
return run_ocr(temp_path, prompt)
|
| 409 |
except Exception as exc:
|
| 410 |
logger.exception("Gradio OCR failed")
|
| 411 |
+
raise gr.Error(_friendly_ocr_error(exc)) from exc
|
| 412 |
finally:
|
| 413 |
if temp_path and os.path.exists(temp_path):
|
| 414 |
os.remove(temp_path)
|
|
|
|
| 509 |
)
|
| 510 |
except Exception as exc:
|
| 511 |
logger.exception("Telegram OCR pipeline failed")
|
| 512 |
+
friendly_message = _friendly_ocr_error(exc)
|
| 513 |
+
# Keep Telegram response short; detailed traceback remains in Space logs.
|
| 514 |
try:
|
| 515 |
+
await status.edit_text(friendly_message[:1000])
|
| 516 |
except Exception:
|
| 517 |
+
await message.reply_text(friendly_message[:1000])
|
| 518 |
finally:
|
| 519 |
if local_path and os.path.exists(local_path):
|
| 520 |
os.remove(local_path)
|
|
|
|
| 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 |
if not TELEGRAM_BOT_TOKEN:
|
| 585 |
logger.warning("TELEGRAM_BOT_TOKEN is not set; Telegram integration is disabled.")
|
| 586 |
return
|
|
|
|
| 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 |
threading.Thread(target=thread_target, daemon=True, name="telegram-polling").start()
|
| 617 |
|