multimodalart's picture
multimodalart HF Staff
Upload app.py with huggingface_hub
fa7a3e9 verified
Raw History Blame Contribute Delete
9.69 kB
"""OpenThai2.0-OCR-Markdown: Thai document pages to Markdown, with layout boxes.
Runs iapp/OpenThai2.0-OCR-Markdown (a Thai fine-tune of NVIDIA Nemotron 3.5
Parse, 0.63B) on Hugging Face ZeroGPU through the model's native Transformers
backend: one page image in, Markdown with HTML tables plus a box and a class
for every block out, in reading order.
"""
import copy
import json
import time
import spaces # must be imported before any torch/CUDA-touching import
import torch
from transformers import AutoModel, AutoProcessor, GenerationConfig
from PIL import Image, ImageDraw, ImageFont, ImageOps
import gradio as gr
from nemotron_parse import postprocess_document
# Gradio 6: Progress tuples are (index, total), and theme/css belong to launch().
MODEL_ID = "iapp/OpenThai2.0-OCR-Markdown"
# Box-mode prompt from the model card and run_transformers_inference.py:
# boxes + classes + markdown text + text inside pictures.
TASK_PROMPT = "</s><s><predict_bbox><predict_classes><output_markdown><predict_text_in_pic>"
MAX_SIDE = 2048 # the model's virtual canvas is 1664 x 2048 (width x height)
DEFAULT_MAX_TOKENS = 8744 # fits a full dense page; matches the reference script
print("Loading model...")
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
model = (
AutoModel.from_pretrained(MODEL_ID, trust_remote_code=True, dtype=torch.bfloat16)
.to("cuda")
.eval()
)
gen_config = GenerationConfig.from_pretrained(MODEL_ID)
gen_config.do_sample = False
gen_config.num_beams = 1
gen_config.repetition_penalty = 1.1
print("Model loaded.")
# One muted colour per layout class, for the overlay rendering.
CLASS_COLORS = {
"Title": "#b5452b",
"Section-header": "#c76b29",
"Text": "#3f6f5a",
"List-item": "#5b8a3c",
"Table": "#2f5d7c",
"Chart": "#7a4e8f",
"Picture": "#8f6d2f",
"Caption": "#6b6b6b",
"Formula": "#9c3d5e",
"Code": "#4a4a4a",
"Footnote": "#7d7468",
"Page-header": "#8a8a7a",
"Page-footer": "#8a8a7a",
"Bibliography": "#62735a",
"TOC": "#62735a",
}
_font_cache: dict = {}
def _font(size: int) -> ImageFont.FreeTypeFont:
"""Load a PIL font for overlay labels, cached by size."""
if size not in _font_cache:
try:
_font_cache[size] = ImageFont.load_default(size=size)
except TypeError:
_font_cache[size] = ImageFont.load_default()
return _font_cache[size]
def draw_blocks(image: Image.Image, blocks: list) -> Image.Image:
"""Draw predicted boxes and class labels over a copy of the page."""
img = image.copy()
draw = ImageDraw.Draw(img)
scale = max(img.size) / 1600
width = max(2, round(3 * scale))
font = _font(max(12, round(18 * scale)))
for i, block in enumerate(blocks):
x1, y1, x2, y2 = block["bbox_pixels"]
color = CLASS_COLORS.get(block["class"], "#3f6f5a")
draw.rectangle((x1, y1, x2, y2), outline=color, width=width)
label = f"{i + 1} {block['class']}"
left, top, right, bottom = draw.textbbox((0, 0), label, font=font)
pad = max(2, round(3 * scale))
label_y = y1 - (bottom - top) - 2 * pad
if label_y < 0:
label_y = y1
draw.rectangle(
(x1, label_y, x1 + (right - left) + 2 * pad, label_y + (bottom - top) + 2 * pad),
fill=color,
)
draw.text(
(x1 + pad - left, label_y + pad - top), label, font=font, fill="white"
)
return img
def fit_page(image: Image.Image) -> Image.Image:
"""Convert to RGB, fix EXIF rotation, cap the long side at 2048 px."""
image = ImageOps.exif_transpose(image).convert("RGB")
if max(image.size) > MAX_SIDE:
image.thumbnail((MAX_SIDE, MAX_SIDE), Image.LANCZOS)
return image
def _duration(image, max_new_tokens) -> int:
"""ZeroGPU seconds, calibrated on the live Space: ~2 s fixed overhead +
~100 generated tokens/s (densest example page: 1,985 tokens in 21.4 s).
At the default 8,744 budget this requests ~51 s, which covers pages ~2.5x
denser than the bundled examples without inflating visitors' quota cost.
"""
return int(12 + int(max_new_tokens) / 220)
@spaces.GPU(duration=_duration)
def parse_page(image: Image.Image, max_new_tokens: int) -> str:
"""Run one page through the model; return the raw box-mode output."""
inputs = processor(
images=[image],
text=TASK_PROMPT,
return_tensors="pt",
add_special_tokens=False,
).to("cuda")
cfg = copy.deepcopy(gen_config)
cfg.max_new_tokens = int(max_new_tokens)
with torch.inference_mode():
out = model.generate(**inputs, generation_config=cfg)
return processor.batch_decode(out, skip_special_tokens=False)[0]
def parse_document(
image,
max_new_tokens=DEFAULT_MAX_TOKENS,
progress=gr.Progress(),
):
"""Parse one page: rendered Markdown, source, block overlay, blocks JSON, raw, status."""
if image is None:
raise ValueError("Upload a document page image first.")
progress((1, 10), desc="Reading page")
page = fit_page(image)
progress((3, 10), desc="Parsing page on GPU")
t0 = time.time()
raw = parse_page(page, max_new_tokens)
progress((9, 10), desc="Rendering Markdown")
doc = postprocess_document(raw, image_size=page.size)
overlay = draw_blocks(page, doc["blocks"])
status = f"Took {time.time() - t0:.1f} s · {len(doc['blocks'])} blocks"
blocks_json = json.dumps(
[
{
"class": b["class"],
"bbox": [round(v, 4) for v in b["bbox"]],
"bbox_pixels": [round(v, 1) for v in b["bbox_pixels"]],
"content": b["content"],
}
for b in doc["blocks"]
],
ensure_ascii=False,
indent=1,
)
return (
doc["markdown"],
doc["markdown"],
overlay,
blocks_json,
doc["raw_out"],
status,
)
def parse_document_safe(
image,
max_new_tokens=DEFAULT_MAX_TOKENS,
progress=gr.Progress(),
):
"""Wrap parse_document so user-facing failures surface as gr.Error."""
try:
return parse_document(image, max_new_tokens, progress=progress)
except ValueError as err:
raise gr.Error(str(err))
except Exception as err: # pragma: no cover - surface model failures cleanly
raise gr.Error(f"Parsing failed: {err}")
EXAMPLES = [
["examples/meeting-minutes.png"],
["examples/merged-cell-table.png"],
["examples/economic-report.png"],
]
CSS = """
.gradio-container { max-width: 1400px !important; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
#md-out { max-height: 640px; overflow-y: auto; }
"""
with gr.Blocks(title="OpenThai2.0-OCR-Markdown") as demo:
gr.Markdown(
"""
# 📄 OpenThai2.0-OCR-Markdown
**Thai document pages → Markdown**, with tables as HTML and a box and a class
for every block, in reading order. Powered by
[iapp/OpenThai2.0-OCR-Markdown](https://huggingface.co/iapp/OpenThai2.0-OCR-Markdown),
a Thai fine-tune of NVIDIA Nemotron 3.5 Parse (0.63B), running on ZeroGPU.
"""
)
with gr.Row():
with gr.Column(scale=5):
image_in = gr.Image(
label="Document page", type="pil", sources=["upload", "clipboard"]
)
with gr.Accordion("Settings", open=False):
max_tokens = gr.Slider(
512,
8744,
value=DEFAULT_MAX_TOKENS,
step=8,
label="Max new tokens",
info="Generation budget; 8744 fits a full dense page.",
)
btn = gr.Button("Parse page", variant="primary")
status = gr.Markdown("Upload a page or pick an example, then press Parse.")
with gr.Column(scale=7):
with gr.Tabs():
with gr.Tab("Markdown"):
md_out = gr.Markdown(
elem_id="md-out",
latex_delimiters=[
{"left": "$$", "right": "$$", "display": True},
{"left": "$", "right": "$", "display": False},
{"left": "\\[", "right": "\\]", "display": True},
{"left": "\\(", "right": "\\)", "display": False},
],
)
with gr.Tab("Source"):
md_src = gr.Code(
language="markdown", lines=20, max_lines=40, wrap_lines=True
)
with gr.Tab("Layout"):
overlay_out = gr.Image(label="Blocks and classes", type="pil")
with gr.Tab("Blocks JSON"):
blocks_out = gr.Code(
language="json", lines=20, max_lines=40, wrap_lines=True
)
with gr.Tab("Raw output"):
raw_out = gr.Code(lines=20, max_lines=40, wrap_lines=True)
gr.Examples(
examples=EXAMPLES,
inputs=[image_in],
fn=parse_document_safe,
outputs=[md_out, md_src, overlay_out, blocks_out, raw_out, status],
cache_examples=True,
cache_mode="lazy",
label="Examples (pages from ThaiOCRBench, CC BY-SA 4.0)",
)
btn.click(
parse_document_safe,
[image_in, max_tokens],
[md_out, md_src, overlay_out, blocks_out, raw_out, status],
api_name="parse",
)
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)