Spaces:
Running on Zero

Doc-Parser / app.py
Bruhfyyy's picture
Update app.py
e8b842b verified
Raw History Blame Contribute Delete
37.5 kB
"""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"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>OCRia parse</title>
<style>
:root{--bg:#e8ecf1;--paper:#f9fafc;--ink:#0f1b2a;--mut:#5b6b7e;--line:#c9d2dc;--scan:#1f4fff;--ok:#2f9e63;--bad:#c2362b;
--serif:ui-serif,"Iowan Old Style",Georgia,serif;--sans:system-ui,-apple-system,"Segoe UI",sans-serif;--mono:ui-monospace,Menlo,monospace}
*{box-sizing:border-box}[hidden]{display:none!important}
html{background:var(--bg)}body{margin:0;color:var(--ink);font:16px/1.55 var(--sans)}
a{color:var(--scan)}
.top{display:flex;align-items:center;gap:24px;padding:14px max(20px,calc(50% - 560px));background:var(--ink);color:#e8ecf1}
.mark{font:600 20px/1 var(--serif);color:#f4f6fa;text-decoration:none}.top nav{display:flex;gap:18px;flex:1}
.top nav a{color:#aebbd0;text-decoration:none;font-size:14px}.top nav a:hover{color:#fff}
.status{display:flex;align-items:center;gap:8px;font-size:13px;color:#aebbd0}
.status i{width:9px;height:9px;border-radius:50%;background:#7b8aa0}
.status[data-s=ready] i{background:#4fd18b}.status[data-s=loading] i{background:#ffd54a;animation:pulse 1.2s ease-in-out infinite}
.status[data-s=error] i{background:#ff6b5e}@keyframes pulse{50%{opacity:.35}}
main{max-width:1120px;margin:0 auto;padding:0 20px 64px}
.intro{padding:44px 0 26px;max-width:720px}
h1{font:600 clamp(32px,5vw,52px)/1.05 var(--serif);margin:0 0 14px}
.intro p{margin:0;color:var(--mut);font-size:17px}
.work{display:grid;gap:22px;grid-template-columns:minmax(0,5fr) minmax(0,7fr)}
@media(max-width:900px){.work{grid-template-columns:1fr}}
.src,.out{background:var(--paper);border:1px solid var(--line);border-radius:14px}.src{padding:18px}
.bed{position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;text-align:center;min-height:180px;padding:22px 18px;border-radius:8px;background:#fff;border:1px dashed var(--line);cursor:pointer}
.bed:hover,.bed.drag{border-color:var(--scan);background:#f3f5ff}
.bed b{font:600 19px var(--serif)}.bed span{color:var(--mut);font-size:14px}
.bed .file{margin-top:8px;font:13px var(--mono);background:var(--bg);border-radius:6px;padding:4px 10px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.bed input{position:absolute;inset:0;opacity:0;cursor:pointer}
.uprog{margin-top:14px;padding:12px;background:#fff;border:1px solid var(--line);border-radius:8px}
.uprog-track{height:6px;background:#e0e5ec;border-radius:3px;overflow:hidden}
.uprog-fill{height:100%;background:var(--scan);width:0;transition:width .15s}
.uprog-txt{font-size:12px;color:var(--mut);margin-top:6px;text-align:center}
.opts{border:0;padding:0;margin:16px 0 0;display:grid;gap:14px}
.lbl{font-size:14px;font-weight:600;margin-bottom:6px;display:block}
.seg{display:grid;grid-template-columns:repeat(3,1fr);border:1px solid var(--line);border-radius:8px;overflow:hidden;background:#fff}
.seg label{text-align:center;padding:8px 6px;font-size:14px;cursor:pointer;border-right:1px solid var(--line)}.seg label:last-child{border-right:0}
.seg.four{grid-template-columns:repeat(4,1fr)}
.seg input{position:absolute;opacity:0}.seg label:has(input:checked){background:var(--ink);color:#fff}
.tg{display:flex;gap:12px;align-items:flex-start;font-size:14px;cursor:pointer}
.tg input{margin-top:3px;width:17px;height:17px;accent-color:var(--scan)}
.tg em{display:block;font-style:normal;color:var(--mut);font-size:13px}
.go{margin-top:18px;width:100%;padding:13px 16px;border:0;border-radius:8px;background:var(--scan);color:#fff;font:600 16px var(--sans);cursor:pointer}
.go:disabled{background:#aab4c4;cursor:not-allowed}
.out{min-height:420px;display:flex;flex-direction:column;overflow:hidden}
.bar{display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:10px 14px;border-bottom:1px solid var(--line)}
.tabs{display:flex;gap:4px}.tabs button,.act button{border:1px solid transparent;background:none;border-radius:6px;padding:6px 11px;font:14px var(--sans);color:var(--mut);cursor:pointer}
.tabs button[aria-selected=true]{background:var(--ink);color:#fff}
.act{display:flex;gap:4px;margin-left:auto}.act button{border-color:var(--line);color:var(--ink);background:#fff}.act button:disabled{opacity:.45;cursor:not-allowed}
.stats{font-size:13px;color:var(--mut);width:100%;display:flex;gap:16px;flex-wrap:wrap}.stats:empty{display:none}
.view{padding:18px 20px;overflow:auto;max-height:640px;flex:1}
.empty{color:var(--mut);max-width:40ch;margin:60px auto;text-align:center}
.empty b{display:block;font:600 20px var(--serif);color:var(--ink);margin-bottom:6px}
.err{border-left:3px solid var(--bad);background:#fdf1ef;padding:12px 14px;border-radius:0 8px 8px 0;color:#7a1f18}
.view pre{margin:0;font:13px/1.55 var(--mono);white-space:pre-wrap;word-break:break-word}
.md{line-height:1.6}.md h1,.md h2,.md h3{font-family:var(--serif);line-height:1.2;margin:1.2em 0 .5em}
.md h1{font-size:28px}.md h2{font-size:22px}.md h3{font-size:18px}.md p{margin:.6em 0;max-width:75ch}
.md code{font:13px var(--mono);background:var(--bg);padding:1px 5px;border-radius:4px}
.md table{border-collapse:collapse;font-size:14px;margin:.8em 0}
.md th,.md td{border:1px solid var(--line);padding:6px 10px;text-align:left}.md th{background:var(--bg)}
.cursor::after{content:"▌";animation:blink 1s steps(2) infinite;color:var(--scan)}
@keyframes blink{50%{opacity:0}}
@media(prefers-reduced-motion:reduce){.status[data-s=loading] i,.cursor::after{animation:none}}
</style>
</head>
<body>
<header class="top">
<a class="mark" href="/">OCRia parse</a>
<nav><a href="/docs">API docs</a><a href="/health">Health</a></nav>
<div class="status" id="status" data-s="loading"><i></i><span>Loading model</span><small></small></div>
</header>
<main>
<section class="intro">
<h1>Turn scans and PDFs into structured text.</h1>
<p>Modular pipeline: DocLayout-YOLO + RapidOCR + SLANet. Streams token-by-token like an LLM.</p>
</section>
<section class="work">
<div class="src">
<label class="bed" id="bed">
<b id="bedTitle">Drop a document here</b>
<span id="bedHint">or click to choose a file</span>
<div class="file" id="fname" hidden></div>
<input type="file" id="file">
</label>
<div class="uprog" id="uprog" hidden>
<div class="uprog-track"><div class="uprog-fill" id="uprogFill"></div></div>
<div class="uprog-txt" id="uprogTxt"></div>
</div>
<fieldset class="opts">
<div>
<span class="lbl">Output</span>
<div class="seg" role="radiogroup">
<label><input type="radio" name="fmt" value="markdown" checked><span>Markdown</span></label>
<label><input type="radio" name="fmt" value="json"><span>JSON</span></label>
<label><input type="radio" name="fmt" value="text"><span>Text</span></label>
</div>
</div>
<div id="rotRow" hidden>
<span class="lbl">Rotate image</span>
<div class="seg four">
<label><input type="radio" name="rot" value="0" checked><span>0°</span></label>
<label><input type="radio" name="rot" value="90"><span>90°</span></label>
<label><input type="radio" name="rot" value="180"><span>180°</span></label>
<label><input type="radio" name="rot" value="270"><span>270°</span></label>
</div>
</div>
<label class="tg"><input type="checkbox" id="ocr" checked><span>Read scanned pages<em>Turn off for born-digital PDFs.</em></span></label>
<label class="tg"><input type="checkbox" id="stream" checked><span>Stream output<em>Chunks appear as they're produced.</em></span></label>
</fieldset>
<button class="go" id="go" disabled>Parse document</button>
</div>
<div class="out">
<div class="bar">
<div class="tabs"><button data-v="rendered" aria-selected="true">Preview</button><button data-v="raw" aria-selected="false">Raw</button></div>
<div class="act"><button id="copy" disabled>Copy</button><button id="dl" disabled>Download</button></div>
<div class="stats" id="stats"></div>
</div>
<div class="view" id="view"></div>
</div>
</section>
</main>
<script>
const $ = s => document.querySelector(s);
const S = {file:null, ready:false, busy:false, view:'rendered', out:'', pages:[], meta:{}, err:'', fmt:'markdown'};
const esc = t => String(t).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
const IMGX = ['.jpg','.jpeg','.png','.gif','.bmp','.tiff','.webp'];
const isImg = f => !!f && IMGX.includes('.'+f.name.split('.').pop().toLowerCase());
const rot = () => +document.querySelector('input[name=rot]:checked').value;
function setStatus(s, text, small){const el=$('#status'); el.dataset.s=s; el.querySelector('span').textContent=text; el.querySelector('small').textContent=small||'';}
async function health(){
let delay = 3000;
try{
const r = await fetch('/health'); const j = await r.json();
if(j.ready){
S.ready=true; delay=30000;
const tag = j.last_device === 'cuda' ? 'GPU' : 'CPU';
setStatus('ready','Ready',`${j.cpu.usable} cores · ${tag} · ${j.ocr_tier}`);
}
else if(j.status==='error'){setStatus('error','Model failed to load',j.detail||''); delay=8000;}
else setStatus('loading','Loading model');
}catch{setStatus('error','Server unreachable'); delay=8000;}
ui(); setTimeout(health, delay);
}
function md(src){
const inl = t => esc(t).replace(/`([^`]+)`/g,'<code>$1</code>').replace(/\*\*([^*]+)\*\*/g,'<b>$1</b>');
const L = src.split('\n'); let o = '', i = 0;
const TBL=/^\s*\|.*\|\s*$/, LST=/^\s*([-*+]|\d+\.)\s+/, HD=/^#{1,6}\s/;
while(i<L.length){
const l = L[i];
if(TBL.test(l)){
const rows=[]; while(i<L.length&&TBL.test(L[i]))rows.push(L[i++]);
const cells=r=>r.trim().replace(/^\||\|$/g,'').split('|').map(c=>c.trim());
const sep = rows[1] && /^[\s|:\-]+$/.test(rows[1]);
const head = cells(rows[0]), body = rows.slice(sep?2:1).map(cells);
o += '<table><thead><tr>'+head.map(c=>`<th>${inl(c)}</th>`).join('')+'</tr></thead><tbody>'+body.map(r=>'<tr>'+r.map(c=>`<td>${inl(c)}</td>`).join('')+'</tr>').join('')+'</tbody></table>';
continue;
}
const h = l.match(/^(#{1,6})\s+(.*)/);
if(h){ o+=`<h${h[1].length}>${inl(h[2])}</h${h[1].length}>`; i++; continue; }
if(LST.test(l)){
const ord=/^\s*\d+\./.test(l), items=[];
while(i<L.length&&LST.test(L[i]))items.push(L[i++].replace(LST,''));
o += (ord?'<ol>':'<ul>')+items.map(x=>`<li>${inl(x)}</li>`).join('')+(ord?'</ol>':'</ul>');
continue;
}
if(!l.trim()){i++;continue;}
const p=[l]; i++;
while(i<L.length&&L[i].trim()&&!TBL.test(L[i])&&!LST.test(L[i])&&!HD.test(L[i]))p.push(L[i++]);
o += '<p>'+p.map(inl).join('<br>')+'</p>';
}
return o;
}
let raf = 0;
function render(){ if(!raf) raf = requestAnimationFrame(()=>{raf=0; draw();}); }
function draw(){
const v = $('#view');
if(S.err){ v.innerHTML = `<div class="err"><b>Parse failed.</b> ${esc(S.err)}</div>`; return; }
if(!S.out && !S.busy){ v.innerHTML = '<div class="empty"><b>Nothing parsed yet</b>Choose a document and press Parse.</div>'; return; }
if(!S.out && S.busy){ v.innerHTML = '<div class="empty"><b>Reading the document</b>First chunk arrives after the first OCR pass.</div>'; return; }
if(S.view==='raw' || S.fmt==='text') v.innerHTML = '<pre>'+esc(S.out)+'</pre>';
else if(S.fmt==='markdown') v.innerHTML = '<div class="md'+(S.busy?' cursor':'')+'">'+md(S.out)+'</div>';
else v.innerHTML = S.pages.map(p=>`<div class="pg"><h4>Page ${esc(p.page_num)}</h4><pre>${esc(p.text||'')}</pre></div>`).join('');
}
function ui(){
$('#go').disabled = !S.file || !S.ready || S.busy;
$('#go').textContent = S.busy ? 'Parsing…' : 'Parse document';
$('#copy').disabled = $('#dl').disabled = !S.out;
if(S.meta.upload != null){
$('#uprog').hidden = false;
$('#uprogFill').style.width = S.meta.upload + '%';
$('#uprogTxt').textContent = S.meta.upload < 100 ? `Uploading… ${S.meta.upload}%` : 'Processing…';
} else if(S.meta.phase === 'parsing'){
$('#uprog').hidden = false;
$('#uprogFill').style.width = '100%';
$('#uprogTxt').textContent = S.meta.note || 'Processing…';
} else {
$('#uprog').hidden = true;
}
const bits = [];
if(S.meta.pages != null) bits.push(`${S.meta.pages} page${S.meta.pages==1?'':'s'}`);
if(S.meta.ms != null) bits.push(`${(S.meta.ms/1000).toFixed(2)} s`);
if(S.meta.device) bits.push(S.meta.device === 'cuda' ? 'GPU' : 'CPU');
if(S.out) bits.push(`${S.out.length.toLocaleString()} chars`);
$('#stats').innerHTML = bits.map(b=>`<span>${b}</span>`).join('');
render();
}
function uploadWithProgress(file){
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const fd = new FormData();
fd.append('file', file);
xhr.upload.onprogress = e => {
if(e.lengthComputable){
S.meta.upload = Math.round(e.loaded / e.total * 100);
ui();
}
};
xhr.onload = () => {
if(xhr.status >= 200 && xhr.status < 300){
try { resolve(JSON.parse(xhr.responseText)); }
catch(e){ reject(new Error('bad response from /api/upload')); }
} else {
let msg = `upload failed: ${xhr.status}`;
try { const j = JSON.parse(xhr.responseText); msg = j.detail || msg; } catch{}
reject(new Error(msg));
}
};
xhr.onerror = () => reject(new Error('network error during upload'));
xhr.open('POST', '/api/upload');
xhr.send(fd);
});
}
async function run(){
if(!S.file || S.busy || !S.ready) return;
S.busy = true; S.out = ''; S.pages = []; S.meta = {}; S.err = '';
S.fmt = document.querySelector('input[name=fmt]:checked').value; ui();
let uploaded;
try { uploaded = await uploadWithProgress(S.file); }
catch(e){ S.err = e.message; S.busy = false; S.meta = {}; ui(); return; }
S.meta = {phase: 'parsing'};
ui();
const stream = $('#stream').checked;
const fd = new FormData();
fd.append('output_format', S.fmt);
fd.append('stream', stream);
fd.append('ocr', $('#ocr').checked);
fd.append('rotate', isImg(S.file) ? rot() : 0);
try{
const res = await fetch(`/api/parse/${uploaded.file_id}`, {method:'POST', body: fd});
if(!res.ok){
let d = res.statusText;
try { const j = await res.json(); d = typeof j.detail === 'string' ? j.detail : JSON.stringify(j); } catch{}
throw new Error(d);
}
if(stream) await readSSE(res);
else await readFull(res);
}catch(e){ S.err = e.message || String(e); }
finally {
S.busy = false;
S.meta = Object.fromEntries(Object.entries(S.meta).filter(([k])=>k!=='phase'));
ui();
}
}
async function readFull(res){
if(S.fmt === 'json'){
const j = await res.json();
S.pages = j.pages || [];
S.meta.pages = j.total_pages; S.meta.ms = j.elapsed_ms; S.meta.device = j.device;
S.out = JSON.stringify(j, null, 2);
} else {
S.out = await res.text();
S.meta.pages = res.headers.get('X-Pages');
S.meta.ms = res.headers.get('X-Elapsed-Ms');
}
}
function parseSSEBlock(block){
let event = 'message', data = '';
for(const line of block.split('\n')){
if(line.startsWith('event: ')) event = line.slice(7);
else if(line.startsWith('data: ')) data += line.slice(6);
}
if(!data) return null;
try { return {event, ...JSON.parse(data)}; } catch { return null; }
}
async function readSSE(res){
const rd = res.body.getReader();
const dec = new TextDecoder();
let buf = '';
for(;;){
const {value, done} = await rd.read(); if(done) break;
buf += dec.decode(value, {stream: true});
let i;
while((i = buf.indexOf('\n\n')) >= 0){
const block = buf.slice(0, i);
buf = buf.slice(i + 2);
const e = parseSSEBlock(block);
if(!e) continue;
if(e.event === 'chunk'){ S.out += e.text; S.meta.note = null; render(); }
else if(e.event === 'page'){ S.pages.push(e.page); S.meta.pages = e.total_pages; render(); }
else if(e.event === 'progress'){ S.meta.note = `working… ${(e.elapsed_ms/1000).toFixed(1)}s`; ui(); }
else if(e.event === 'done'){
S.meta.pages = e.total_pages;
S.meta.ms = e.elapsed_ms;
S.meta.device = e.device || S.meta.device;
S.meta.note = null;
ui();
}
else if(e.event === 'error'){ S.err = e.detail; throw new Error(e.detail); }
}
}
}
function pick(f){
if(!f) return;
S.file = f;
$('#fname').hidden = false;
$('#fname').textContent = f.name + ' (' + (f.size/1048576).toFixed(2) + ' MB)';
$('#bedTitle').textContent = 'Ready to parse';
$('#bedHint').textContent = 'Drop another file to replace it';
$('#rotRow').hidden = !isImg(f);
document.querySelector('input[name=rot][value="0"]').checked = true;
S.meta = {};
ui();
}
$('#file').addEventListener('change', e => pick(e.target.files[0]));
const bed = $('#bed');
['dragenter','dragover'].forEach(t => bed.addEventListener(t, e => { e.preventDefault(); bed.classList.add('drag'); }));
['dragleave','drop'].forEach(t => bed.addEventListener(t, e => { e.preventDefault(); bed.classList.remove('drag'); }));
bed.addEventListener('drop', e => pick(e.dataTransfer.files[0]));
$('#go').addEventListener('click', run);
document.querySelectorAll('input[name=fmt]').forEach(r => r.addEventListener('change', () => { S.fmt = r.value; ui(); }));
document.querySelectorAll('.tabs button').forEach(b => b.addEventListener('click', () => {
S.view = b.dataset.v;
document.querySelectorAll('.tabs button').forEach(x => x.setAttribute('aria-selected', x === b));
render();
}));
$('#copy').addEventListener('click', async () => {
await navigator.clipboard.writeText(S.out);
$('#copy').textContent = 'Copied';
setTimeout(() => $('#copy').textContent = 'Copy', 1400);
});
$('#dl').addEventListener('click', () => {
const ext = {markdown:'md', json:'json', text:'txt'}[S.fmt];
const base = (S.file ? S.file.name : 'document').replace(/\.[^.]+$/, '');
const a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([S.out], {type:'text/plain'}));
a.download = `${base}.${ext}`; a.click();
URL.revokeObjectURL(a.href);
});
ui(); health();
</script>
</body>
</html>
"""
@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)