Spaces:
Running on Zero

d-ocr / app.py
multimodalart's picture
multimodalart HF Staff
Upload app.py with huggingface_hub
3ef23c5 verified
Raw History Blame Contribute Delete
8.66 kB
import spaces # must be imported before torch
import base64
import html
import io
import os
import sys
import tarfile
from pathlib import Path
os.environ.setdefault("PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK", "True")
os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
from huggingface_hub import snapshot_download
REPO_ID = "D-OCR/D-OCR-preview"
REVISION = "4b557b4626bdfb39db3d7a0aed120a853092c0db" # release pinned by the authors' Dockerfile
# Download the authors' release: compiled runtime + all four model components.
ROOT = Path(
snapshot_download(
REPO_ID,
revision=REVISION,
allow_patterns=[
"runtime/*",
"checkpoints/siglip_qwen/*",
"checkpoints/initial_v1/table/best/*",
"deploy/models/**",
],
)
)
RUNTIME_DIR = Path(os.environ.get("DOCR_RUNTIME_DIR", "/tmp/docr_runtime"))
if not (RUNTIME_DIR / "banglaocr").exists():
RUNTIME_DIR.mkdir(parents=True, exist_ok=True)
with tarfile.open(ROOT / "runtime/docr-runtime-cp312-linux-x86_64.tar.gz", "r:gz") as archive:
archive.extractall(RUNTIME_DIR, filter="data")
# The model assets are referenced relative to the runtime root -> symlink them in.
for name in ("checkpoints", "deploy"):
link = RUNTIME_DIR / name
if not link.exists():
link.symlink_to(ROOT / name, target_is_directory=True)
sys.path.insert(0, str(RUNTIME_DIR))
os.environ["PYTHONPATH"] = str(RUNTIME_DIR) + os.pathsep + os.environ.get("PYTHONPATH", "")
os.environ.setdefault("OCR_DATA_DIR", "/tmp/docr_data")
os.environ["HF_HUB_OFFLINE"] = "1"
import torch # noqa: E402
import gradio as gr # noqa: E402
from PIL import Image # noqa: E402
import ocr_service # noqa: E402
from banglaocr.siglip_qwen_framework import create_framework # noqa: E402
evaluator = create_framework(
str(RUNTIME_DIR),
device="cuda",
paddle_device="cpu", # Paddle layout/text detectors run on CPU, as in the official GPU image
paddle_python=sys.executable,
checkpoint=str(RUNTIME_DIR / "checkpoints/siglip_qwen/best.pt"),
detector_model=str(RUNTIME_DIR / "deploy/models/PP-OCRv5_mobile_det"),
assets=str(RUNTIME_DIR / "deploy/models/siglip_qwen"),
)
# Load the SigLIP2 + Qwen3.5 recognizer onto the GPU at startup.
evaluator.model()
# Start the CPU Paddle layout / text-detection workers once in the main process;
# the ZeroGPU worker (a fork) reuses their pipes instead of re-spawning them per call.
evaluator.layout.warm()
evaluator.detector.warm()
MAX_PDF_PAGES = 3
LAYOUT_THRESHOLD = 0.3
MAX_NEW_TOKENS = 512
def _load_pages(file_path: str):
data = Path(file_path).read_bytes()
if file_path.lower().endswith(".pdf"):
# page_images() closes each rendered page once the generator advances -> copy eagerly.
pages = [page.convert("RGB") for page in ocr_service.page_images(data)]
else:
pages = [Image.open(io.BytesIO(data)).convert("RGB")]
if not pages:
raise gr.Error("Could not read any page from this file.")
return pages[:MAX_PDF_PAGES], len(pages)
def _decode_overlay(uri):
if isinstance(uri, str) and uri.startswith("data:image"):
return Image.open(io.BytesIO(base64.b64decode(uri.split(",", 1)[1]))).convert("RGB")
return None
def _iframe(doc: str, height: int = 700) -> str:
return (
f'<iframe srcdoc="{html.escape(doc, quote=True)}" '
f'style="width:100%;height:{height}px;border:1px solid #ddd;border-radius:8px;background:white"></iframe>'
)
def _duration(file_path, mode="page", layout_threshold=LAYOUT_THRESHOLD, max_new_tokens=MAX_NEW_TOKENS):
# Measured on ZeroGPU: ~15-35 s per page warm, plus ~30 s one-off warmup on a cold worker.
n = 1
if file_path and str(file_path).lower().endswith(".pdf"):
try:
import pypdfium2
n = max(1, min(MAX_PDF_PAGES, len(pypdfium2.PdfDocument(str(file_path)))))
except Exception:
n = MAX_PDF_PAGES
return 90 + 45 * (n - 1)
@spaces.GPU(duration=_duration)
def run_ocr(
file_path: str,
mode: str = "page",
layout_threshold: float = LAYOUT_THRESHOLD,
max_new_tokens: int = MAX_NEW_TOKENS,
):
"""Run the D-OCR Bangla OCR pipeline on an image or PDF.
Args:
file_path: Path to an image (PNG/JPG/...) or a PDF document.
mode: "page" for full documents (layout detection + reading order + tables),
"table" when the input is a cropped table.
layout_threshold: Layout detection score threshold.
max_new_tokens: Maximum tokens generated per text crop.
Returns:
Detection overlays, extracted text, reading-order HTML, original-layout HTML and the raw document JSON.
"""
if not file_path:
raise gr.Error("Please upload an image or a PDF.")
pages, total = _load_pages(file_path)
overlays, texts, html_docs, positioned_docs, documents = [], [], [], [], []
for i, page in enumerate(pages):
result = evaluator.evaluate(page, mode, float(layout_threshold), int(max_new_tokens), True)
overlay = _decode_overlay(result.get("overlay"))
overlays.append((overlay if overlay is not None else page, f"Page {i + 1}"))
texts.append(result.get("text", "") if len(pages) == 1 else f"--- Page {i + 1} ---\n{result.get('text', '')}")
html_docs.append(result.get("html", ""))
positioned_docs.append(result.get("positioned_html", ""))
documents.append(result.get("document", {}))
if total > len(pages):
texts.append(f"[Only the first {MAX_PDF_PAGES} of {total} pages were processed in this demo.]")
reading_html = "".join(_iframe(d, 500) for d in html_docs if d)
positioned_html = "".join(_iframe(d, 800) for d in positioned_docs if d)
return overlays, "\n\n".join(texts), reading_html, positioned_html, {"pages": documents}
EXAMPLES = [
["examples/printed-page-input.jpg", "page"],
["examples/old-print-input.jpg", "page"],
["examples/handwriting-input.png", "page"],
["examples/table-crop-input.png", "table"],
]
with gr.Blocks(title="D-OCR Preview — Bangla OCR") as demo:
gr.Markdown(
"# D-OCR Preview — Bangla document OCR\n"
"Modular OCR pipeline for printed and handwritten **Bangla** documents: PP-DocLayout-S layout detection, "
"PP-OCRv5 text detection, Table Transformer table structure and a SigLIP2 + Qwen3.5-0.8B text recognizer. "
"Upload an image or a PDF (first 3 pages) and get the text, a detection overlay and HTML reconstructions. "
"Model: [D-OCR/D-OCR-preview](https://huggingface.co/D-OCR/D-OCR-preview) · License: CC BY-NC 4.0 (non-commercial)."
)
with gr.Row():
with gr.Column(scale=1):
file_in = gr.File(
label="Image or PDF",
file_types=["image", ".pdf"],
type="filepath",
)
mode = gr.Radio(
["page", "table"],
value="page",
label="Mode",
info="'page' for full documents, 'table' for a cropped table.",
)
with gr.Accordion("Advanced options", open=False):
layout_threshold = gr.Slider(0.05, 0.9, value=LAYOUT_THRESHOLD, step=0.05, label="Layout threshold")
max_new_tokens = gr.Slider(32, 1024, value=MAX_NEW_TOKENS, step=32, label="Max new tokens per crop")
run_btn = gr.Button("Run OCR", variant="primary")
with gr.Column(scale=2):
gallery = gr.Gallery(
label="Detections (blue = text, orange = table cells, red = reading order)",
height=520,
columns=1,
object_fit="contain",
)
with gr.Tabs():
with gr.Tab("Text"):
text_out = gr.Textbox(label="Extracted text", lines=16, buttons=["copy"])
with gr.Tab("Reading-order HTML"):
html_out = gr.HTML()
with gr.Tab("Original-layout HTML"):
pos_html_out = gr.HTML()
with gr.Tab("Document JSON"):
json_out = gr.JSON()
outputs = [gallery, text_out, html_out, pos_html_out, json_out]
run_btn.click(run_ocr, inputs=[file_in, mode, layout_threshold, max_new_tokens], outputs=outputs)
gr.Examples(
examples=EXAMPLES,
inputs=[file_in, mode],
outputs=outputs,
fn=run_ocr,
cache_examples=True,
cache_mode="lazy",
label="Examples from the D-OCR model card",
)
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), mcp_server=True)