"""OCRia Parse API — modular pipeline with SSE streaming, upload/parse split, and ZeroGPU acceleration via @spaces.GPU. """ import asyncio import importlib.metadata as im import json import math import os import shutil import tempfile import threading import time import uuid from contextlib import asynccontextmanager from enum import Enum from pathlib import Path import spaces import uvicorn from fastapi import FastAPI, File, Form, HTTPException, UploadFile from fastapi.middleware.cors import CORSMiddleware from fastapi.openapi.docs import get_swagger_ui_html from fastapi.responses import HTMLResponse, JSONResponse, Response, StreamingResponse from pipeline import ModularParser, cuda_provider_available # --------------------------------------------------------------------------- config def _env_int(key: str, default: int) -> int: try: return max(1, int(os.getenv(key, default))) except ValueError: return default def detect_cpus() -> dict: try: affinity = len(os.sched_getaffinity(0)) except AttributeError: affinity = os.cpu_count() or 1 quota = None try: q, p = Path("/sys/fs/cgroup/cpu.max").read_text().split()[:2] if q != "max": quota = math.ceil(int(q) / int(p)) except Exception: try: q = int(Path("/sys/fs/cgroup/cpu/cpu.cfs_quota_us").read_text()) p = int(Path("/sys/fs/cgroup/cpu/cpu.cfs_period_us").read_text()) if q > 0: quota = math.ceil(q / p) except Exception: pass usable = max(1, min(affinity, quota) if quota else affinity) return {"affinity": affinity, "cgroup_quota": quota, "usable": usable} CPU = detect_cpus() POOL_SIZE = _env_int("POOL_SIZE", max(1, CPU["usable"] // 2)) MAX_PAGES = _env_int("MAX_PAGES", 200) PARSE_TIMEOUT = _env_int("PARSE_TIMEOUT", 180) MAX_MB = _env_int("MAX_UPLOAD_MB", 50) OCR_TIER = os.getenv("OCR_TIER", "small") LAYOUT_IMGSZ = _env_int("LAYOUT_IMGSZ", 640) CHUNK_SIZE = _env_int("CHUNK_SIZE", 48) CHUNK_DELAY = float(os.getenv("CHUNK_DELAY", "0.001")) UPLOAD_TTL = _env_int("UPLOAD_TTL", 3600) HEARTBEAT_S = float(os.getenv("HEARTBEAT_S", "1.0")) GPU_DURATION = _env_int("GPU_DURATION", 60) USE_GPU = os.getenv("USE_GPU", "1") not in ("0", "false", "False") UPLOAD_DIR = Path(tempfile.gettempdir()) / "ocria_uploads" UPLOAD_DIR.mkdir(parents=True, exist_ok=True) DOC_EXT = [".pdf"] IMG_EXT = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp", ".svg"] OFFICE_GROUPS = { "Word processing": [".doc", ".docx", ".docm", ".odt", ".rtf", ".pages"], "Presentations": [".ppt", ".pptx", ".pptm", ".odp", ".key"], "Spreadsheets": [".xls", ".xlsx", ".xlsm", ".ods", ".csv", ".tsv", ".numbers"], } OFFICE_EXT = [e for g in OFFICE_GROUPS.values() for e in g] HAS_SOFFICE = bool(shutil.which("soffice") or shutil.which("libreoffice")) ALLOWED = set(DOC_EXT + IMG_EXT + (OFFICE_EXT if HAS_SOFFICE else [])) STATE = {"status": "loading", "error": None, "last_device": None, "gpu_ready": False} STARTED = time.time() SEM = asyncio.Semaphore(POOL_SIZE) _parser: ModularParser | None = None _plock = threading.Lock() class OutputFormat(str, Enum): markdown = "markdown" json = "json" text = "text" class Rotation(int, Enum): r0 = 0 r90 = 90 r180 = 180 r270 = 270 # --------------------------------------------------------------------------- engine def get_parser() -> ModularParser: global _parser with _plock: if _parser is None: _parser = ModularParser(ocr_tier=OCR_TIER, layout_imgsz=LAYOUT_IMGSZ) return _parser def bootstrap() -> None: STATE.update(status="loading", error=None) try: get_parser() STATE.update( status="ready", error=None, gpu_ready=cuda_provider_available(), ) except Exception as e: # noqa: BLE001 STATE.update(status="error", error=f"{type(e).__name__}: {e}") async def _cleanup_uploads(): while True: await asyncio.sleep(300) now = time.time() for p in UPLOAD_DIR.iterdir(): try: if now - p.stat().st_mtime > UPLOAD_TTL: p.unlink() except Exception: pass @asynccontextmanager async def lifespan(_: FastAPI): boot = asyncio.create_task(asyncio.to_thread(bootstrap)) cleaner = asyncio.create_task(_cleanup_uploads()) yield boot.cancel() cleaner.cancel() # --------------------------------------------------------------------------- helpers def _pdf_to_images(path: str, max_pages: int): import pymupdf from PIL import Image doc = pymupdf.open(path) try: for i, page in enumerate(doc, 1): if i > max_pages: break pix = page.get_pixmap(dpi=200) yield i, Image.frombytes("RGB", [pix.width, pix.height], pix.samples) finally: doc.close() def _image_to_pages(path: str): from PIL import Image with Image.open(path) as im: yield 1, im.convert("RGB").copy() def _text_pages(path: str, max_pages: int): import pymupdf doc = pymupdf.open(path) try: for i, page in enumerate(doc, 1): if i > max_pages: break yield i, page.get_text() finally: doc.close() def _chunks(text: str, size: int = CHUNK_SIZE): n, i = len(text), 0 while i < n: j = min(i + size, n) if j < n: k = text.rfind(" ", i, j) if k > i + size // 2: j = k + 1 yield text[i:j] i = j def sse(event: str, data: dict) -> str: return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n" def _safe_id(s: str) -> bool: return bool(s) and len(s) == 32 and all(c in "0123456789abcdef" for c in s) def _find_upload(file_id: str) -> Path | None: if not _safe_id(file_id): return None for p in UPLOAD_DIR.glob(f"{file_id}.*"): return p return None _MAGIC = [ (b"%PDF", ".pdf"), (b"\x89PNG", ".png"), (b"\xff\xd8\xff", ".jpg"), (b"GIF87a", ".gif"), (b"GIF89a", ".gif"), (b"BM", ".bmp"), (b"II*\x00", ".tiff"), (b"MM\x00*", ".tiff"), ] def sniff(head: bytes): for sig, ext in _MAGIC: if head.startswith(sig): return ext if head[:4] == b"RIFF" and head[8:12] == b"WEBP": return ".webp" return None def cleanup(path: str) -> None: try: Path(path).unlink(missing_ok=True) except OSError: pass def rotate_image(path: str, deg: int) -> None: ext = Path(path).suffix.lower() if ext not in IMG_EXT or ext == ".svg": raise HTTPException(400, "rotate only works on raster images.") try: from PIL import Image, ImageOps with Image.open(path) as im: out = ImageOps.exif_transpose(im).rotate(-deg, expand=True) if ext in (".jpg", ".jpeg") and out.mode not in ("RGB", "L"): out = out.convert("RGB") out.save(path) except HTTPException: raise except Exception as e: raise HTTPException(422, f"Could not rotate: {e}") async def save_upload(file: UploadFile) -> tuple[str, str]: name = file.filename or "upload" ext = Path(name).suffix.lower() fd, tmp = tempfile.mkstemp(prefix="ocria_", suffix=ext or ".bin") size, head, limit = 0, b"", MAX_MB * 1024 * 1024 try: with os.fdopen(fd, "wb") as f: while chunk := await file.read(1 << 20): head = head or chunk[:16] size += len(chunk) if size > limit: raise HTTPException(413, f"File larger than {MAX_MB} MB.") f.write(chunk) if size == 0: raise HTTPException(400, "Empty upload.") if ext in OFFICE_EXT and not HAS_SOFFICE: raise HTTPException(415, f"{ext} needs LibreOffice.") if ext not in ALLOWED: real = sniff(head) if not real: raise HTTPException(415, f"Unsupported file type '{ext or name}'.") fixed = tmp.rsplit(".", 1)[0] + real os.replace(tmp, fixed) tmp = fixed except BaseException: cleanup(tmp) raise return tmp, name def ms_since(t0: float) -> int: return int((time.perf_counter() - t0) * 1000) def err_message(e: Exception) -> tuple[int, str]: if isinstance(e, asyncio.TimeoutError): return 504, f"Parsing took longer than {PARSE_TIMEOUT}s." return 422, f"Parse failed: {e}" # --------------------------------------------------------------------------- parse core def _parse_streaming(path: str, ext: str, ocr: bool): parser = get_parser() if ext == ".pdf" and not ocr: for page_num, text in _text_pages(path, MAX_PAGES): yield page_num, text, text return src = _pdf_to_images(path, MAX_PAGES) if ext == ".pdf" else _image_to_pages(path) for page_num, img in src: for block in parser.parse_stream(img): if block.label == "table" and block.html: yield page_num, block.html, "" elif block.text.strip(): yield page_num, block.text, block.text @spaces.GPU(duration=GPU_DURATION) def _parse_document_gpu(path: str, ext: str, ocr: bool): """ZeroGPU entry point. GPU window ends when this function returns, so the subsequent SSE chunk emission runs on CPU and consumes zero quota.""" parser = get_parser() use_gpu = False if USE_GPU: use_gpu = parser.try_to_cuda() STATE["last_device"] = "cuda" if use_gpu else "cpu" try: return list(_parse_streaming(path, ext, ocr)) finally: if use_gpu: try: parser.to_cpu() except Exception: pass # --------------------------------------------------------------------------- app DESCRIPTION = f""" Parse PDFs, scans, images and Office files into **Markdown**, **JSON** or **plain text** with a modular CPU/GPU pipeline: **DocLayout-YOLO + RapidOCR (PP-OCRv6) + SLANet**. **Upload + parse split.** `POST /api/upload` returns a `file_id`. Then `POST /api/parse/{{file_id}}` with `stream=true` returns SSE (`text/event-stream`) so text arrives token-by-token. **Limits.** {MAX_MB} MB, {MAX_PAGES} pages, {PARSE_TIMEOUT}s per document, GPU window {GPU_DURATION}s. """ app = FastAPI( title="OCRia Parse API", version="2.3.0", description=DESCRIPTION, docs_url=None, redoc_url=None, lifespan=lifespan, ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], expose_headers=["X-Pages", "X-Elapsed-Ms"], ) @app.get("/health", tags=["Health"]) async def health(): ready = STATE["status"] == "ready" try: version = im.version("rapidocr") except Exception: version = None body = { "status": STATE["status"], "ready": ready, "detail": STATE["error"], "model": "modular: DocLayout-YOLO + RapidOCR + SLANet", "ocr_tier": OCR_TIER, "layout_imgsz": LAYOUT_IMGSZ, "rapidocr": version, "last_device": STATE.get("last_device"), "gpu_ready": STATE.get("gpu_ready"), "gpu_enabled": USE_GPU, "gpu_duration_s": GPU_DURATION, "uptime_s": int(time.time() - STARTED), "cpu": {**CPU, "pool_size": POOL_SIZE}, "limits": {"max_upload_mb": MAX_MB, "max_pages": MAX_PAGES, "timeout_s": PARSE_TIMEOUT}, } return JSONResponse(body, status_code=200 if ready else 503) @app.post("/api/upload", tags=["Parse"]) async def upload(file: UploadFile = File(...)): if STATE["status"] != "ready": raise HTTPException(503, "Model still loading.", headers={"Retry-After": "5"}) path, name = await save_upload(file) file_id = uuid.uuid4().hex dest = UPLOAD_DIR / f"{file_id}{Path(path).suffix}" os.replace(path, dest) return { "file_id": file_id, "filename": name, "size": dest.stat().st_size, "expires_in": UPLOAD_TTL, } async def _dispatch(path: str, ext: str, fmt: str, ocr: bool, stream: bool, name: str): if stream: return StreamingResponse( _sse_stream(path, ext, fmt, ocr), media_type="text/event-stream", headers={ "Cache-Control": "no-cache, no-transform", "X-Accel-Buffering": "no", "Connection": "keep-alive", }, ) t0 = time.perf_counter() try: regions = await asyncio.to_thread(_parse_document_gpu, path, ext, ocr) except Exception as e: # noqa: BLE001 cleanup(path) code, msg = err_message(e) raise HTTPException(code, msg) finally: cleanup(path) ms = ms_since(t0) device = STATE.get("last_device") or "cpu" if fmt == "json": pages_buf: dict[int, list[str]] = {} for page_num, _md, text in regions: pages_buf.setdefault(page_num, []).append(text) pages = [{"page_num": pn, "text": "\n".join(pages_buf[pn])} for pn in sorted(pages_buf)] markdown = "\n\n-----\n\n".join( "\n\n".join(t for t in pages_buf[pn] if t) for pn in sorted(pages_buf) ) return JSONResponse({ "filename": name, "total_pages": len(pages), "elapsed_ms": ms, "device": device, "text": markdown, "pages": pages, }) if fmt == "text": body = "\n\n-----\n\n".join(text for _, _md, text in regions if text) else: body = "\n\n".join(md for _, md, _text in regions if md) media = "text/markdown; charset=utf-8" if fmt == "markdown" else "text/plain; charset=utf-8" n_pages = len({r[0] for r in regions}) return Response( body, media_type=media, headers={"X-Pages": str(n_pages), "X-Elapsed-Ms": str(ms)}, ) @app.post("/api/parse", tags=["Parse"]) async def parse_direct( file: UploadFile = File(...), output_format: OutputFormat = Form(OutputFormat.markdown), stream: bool = Form(False), ocr: bool = Form(True), rotate: Rotation = Form(Rotation.r0), ): if STATE["status"] != "ready": raise HTTPException(503, "Model still loading.", headers={"Retry-After": "5"}) path, name = await save_upload(file) ext = Path(path).suffix.lower() if rotate.value: try: await asyncio.to_thread(rotate_image, path, rotate.value) except HTTPException: cleanup(path) raise return await _dispatch(path, ext, output_format.value, ocr, stream, name) @app.post("/api/parse/{file_id}", tags=["Parse"]) async def parse_by_id( file_id: str, output_format: OutputFormat = Form(OutputFormat.markdown), stream: bool = Form(False), ocr: bool = Form(True), rotate: Rotation = Form(Rotation.r0), ): if STATE["status"] != "ready": raise HTTPException(503, "Model still loading.", headers={"Retry-After": "5"}) found = _find_upload(file_id) if not found: raise HTTPException(404, "file_id not found or expired — re-upload.") path = str(found) ext = found.suffix.lower() if rotate.value: try: await asyncio.to_thread(rotate_image, path, rotate.value) except HTTPException: cleanup(path) raise return await _dispatch(path, ext, output_format.value, ocr, stream, found.name) # --------------------------------------------------------------------------- SSE stream async def _sse_stream(path: str, ext: str, fmt: str, ocr: bool): t0 = time.perf_counter() loop = asyncio.get_running_loop() q: asyncio.Queue = asyncio.Queue() stop = threading.Event() def producer(): try: regions = _parse_document_gpu(path, ext, ocr) for page_num, md, text in regions: if stop.is_set(): return loop.call_soon_threadsafe(q.put_nowait, ("region", page_num, md, text)) loop.call_soon_threadsafe(q.put_nowait, ("end", None, None, None)) except Exception as e: # noqa: BLE001 loop.call_soon_threadsafe(q.put_nowait, ("err", e, None, None)) runner = asyncio.create_task(asyncio.to_thread(producer)) region_count = 0 pages_buf: dict[int, list[str]] = {} async with SEM: yield sse("start", {"elapsed_ms": 0}) try: while True: try: kind, a, b, c = await asyncio.wait_for(q.get(), timeout=HEARTBEAT_S) except asyncio.TimeoutError: yield sse("progress", {"elapsed_ms": ms_since(t0)}) continue if kind == "err": _, msg = err_message(a) yield sse("error", {"detail": msg}) return if kind == "end": break page_num, md, text = a, b, c region_count += 1 if fmt == "json": pages_buf.setdefault(page_num, []).append(text) else: payload = md if fmt == "markdown" else text if region_count > 1: payload = "\n\n" + payload for piece in _chunks(payload, CHUNK_SIZE): yield sse("chunk", {"text": piece}) if CHUNK_DELAY > 0: await asyncio.sleep(CHUNK_DELAY) if fmt == "json": for pn in sorted(pages_buf): yield sse("page", { "page": {"page_num": pn, "text": "\n".join(pages_buf[pn])}, "total_pages": len(pages_buf), }) yield sse("done", { "total_pages": len(pages_buf) if fmt == "json" else region_count, "elapsed_ms": ms_since(t0), "device": STATE.get("last_device") or "cpu", }) finally: stop.set() runner.cancel() cleanup(path) # --------------------------------------------------------------------------- docs @app.get("/docs", include_in_schema=False) async def docs(): page = get_swagger_ui_html( openapi_url="/openapi.json", title="OCRia Parse API", swagger_ui_parameters={"docExpansion": "list", "tryItOutEnabled": True}, ) return HTMLResponse(page.body.decode()) # --------------------------------------------------------------------------- web app INDEX = r""" OCRia parse
OCRia parse
Loading model

Turn scans and PDFs into structured text.

Modular pipeline: DocLayout-YOLO + RapidOCR + SLANet. Streams token-by-token like an LLM.

Output
""" @app.get("/", include_in_schema=False, response_class=HTMLResponse) async def index(): return HTMLResponse(INDEX) if __name__ == "__main__": try: from spaces import zero as _zero _zero.startup() except Exception: pass uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")), timeout_keep_alive=75)