"""Page Script ID demo built with gradio.Server + ONNX Runtime (CPU). Runs both davanstrien/page-script-id (MobileNetV4-Small) and davanstrien/page-script-id-hgnet (HGNetV2-B0) side-by-side on images or PDFs. """ import base64 import io import json import os import time from pathlib import Path import fitz import numpy as np import onnxruntime as ort from fastapi.responses import FileResponse, HTMLResponse, JSONResponse from gradio import Server from gradio.data_classes import FileData from huggingface_hub import hf_hub_download from PIL import Image HERE = Path(__file__).parent EXAMPLES_DIR = HERE / "examples" HF_TOKEN = os.environ.get("HF_TOKEN") MODEL_SPECS = [ { "key": "mnv4s", "repo_id": "davanstrien/page-script-id", "title": "MobileNetV4-Small", "subtitle": "2.52M params · 10 MB ONNX · Fast default", }, { "key": "hgnet", "repo_id": "davanstrien/page-script-id-hgnet", "title": "HGNetV2-B0", "subtitle": "3.99M params · 16 MB ONNX · Higher accuracy", }, ] EXAMPLES = [ {"file": "01_japanese.jpg", "label": "Japanese", "tag": "Single script", "default_pad": False}, {"file": "02_arabic.jpg", "label": "Arabic", "tag": "RTL script", "default_pad": False}, {"file": "03_cyrillic.jpg", "label": "Cyrillic", "tag": "Single script", "default_pad": False}, {"file": "04_mixed_latn_hani.jpg", "label": "Latin + Han", "tag": "Mixed page", "default_pad": False}, {"file": "05_crop_devanagari.jpg", "label": "Devanagari crop", "tag": "Try Pad toggle", "default_pad": False}, {"file": "06_unseen_sinhala.jpg", "label": "Sinhala (unseen)", "tag": "Should refuse", "default_pad": False}, ] def load_models(): loaded = {} so = ort.SessionOptions() so.intra_op_num_threads = min(4, os.cpu_count() or 2) so.inter_op_num_threads = 1 for spec in MODEL_SPECS: repo = spec["repo_id"] cfg_path = hf_hub_download(repo, "config.json", token=HF_TOKEN) onnx_path = hf_hub_download(repo, "model.onnx", token=HF_TOKEN) inf = json.loads(Path(cfg_path).read_text())["inference"] sess = ort.InferenceSession(onnx_path, sess_options=so, providers=["CPUExecutionProvider"]) loaded[spec["key"]] = { **spec, "cfg": inf, "session": sess, } return loaded MODELS = load_models() SCRIPT_NAMES = MODELS["mnv4s"]["cfg"]["script_names"] SCRIPTS = MODELS["mnv4s"]["cfg"]["scripts"] def open_image_or_pdf(file_path: str, pdf_page: int = 1) -> tuple[Image.Image, int | None]: p = Path(file_path) is_pdf = p.suffix.lower() == ".pdf" if not is_pdf: with p.open("rb") as f: if f.read(5) == b"%PDF-": is_pdf = True if is_pdf: doc = fitz.open(str(p)) n_pages = len(doc) idx = max(0, min(n_pages - 1, int(pdf_page) - 1)) pix = doc[idx].get_pixmap(dpi=130, alpha=False) im = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) doc.close() return im, n_pages im = Image.open(str(p)) im.load() return im, None def to_data_url(im: Image.Image, max_side: int = 720) -> str: cp = im.convert("RGB") cp.thumbnail((max_side, max_side)) buf = io.BytesIO() cp.save(buf, format="JPEG", quality=84) return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii") def preprocess_grey(im: Image.Image, size: int = 640, pad_square: bool = False) -> tuple[np.ndarray, Image.Image]: g = im.convert("L") if pad_square: w, h = g.size s = max(w, h) canvas = Image.new("L", (s, s), 255) canvas.paste(g, ((s - w) // 2, (s - h) // 2)) g = canvas resized = g.resize((size, size), Image.BILINEAR) return np.asarray(resized, dtype=np.float32)[None], resized def run_both_models(file_path: str, pad_square: bool = False, pdf_page: int = 1) -> dict: im, pdf_pages = open_image_or_pdf(file_path, pdf_page=pdf_page) orig_w, orig_h = im.size arr, model_view = preprocess_grey(im, size=640, pad_square=bool(pad_square)) results = {} for key, m in MODELS.items(): inf = m["cfg"] t0 = time.perf_counter() probs = m["session"].run([inf["onnx_output_name"]], {inf["onnx_input_name"]: arr})[0][0] dt_ms = (time.perf_counter() - t0) * 1000.0 prob_map = {s: round(float(p), 4) for s, p in zip(inf["scripts"], probs.tolist())} results[key] = { "repo_id": m["repo_id"], "title": m["title"], "subtitle": m["subtitle"], "latency_ms": round(dt_ms, 1), "default_unknown_threshold": float(inf["unknown_threshold"]), "default_script_threshold": float(inf["script_threshold"]), "probs": prob_map, } return { "orig_size": [orig_w, orig_h], "pad_square": bool(pad_square), "pdf_pages": pdf_pages, "pdf_page": int(pdf_page) if pdf_pages else None, "preview_url": to_data_url(im, max_side=720), "model_view_url": to_data_url(model_view, max_side=520), "script_names": SCRIPT_NAMES, "models": results, } app = Server() @app.api(name="identify_script") def identify_script(file: FileData, pad_square: bool = False, pdf_page: int = 1) -> dict: """Identify writing scripts on an uploaded page image or PDF using both ONNX models.""" path = file["path"] if isinstance(file, dict) else getattr(file, "path", str(file)) return run_both_models(path, pad_square=pad_square, pdf_page=pdf_page) @app.api(name="identify_example") def identify_example(filename: str, pad_square: bool = False) -> dict: """Run both models on one of the bundled CC-BY-4.0 example images.""" safe_name = Path(filename).name p = EXAMPLES_DIR / safe_name if not p.exists(): raise ValueError(f"Unknown example: {safe_name}") return run_both_models(str(p), pad_square=pad_square, pdf_page=1) @app.get("/", response_class=HTMLResponse) async def homepage(): return (HERE / "index.html").read_text(encoding="utf-8") @app.get("/api/examples") async def list_examples(): return JSONResponse({"examples": EXAMPLES, "script_names": SCRIPT_NAMES}) @app.get("/examples/{filename}") async def serve_example(filename: str): p = EXAMPLES_DIR / Path(filename).name if not p.exists(): return JSONResponse({"error": "not found"}, status_code=404) return FileResponse(str(p)) if __name__ == "__main__": app.launch(show_error=True)