Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files12345678910113 unmodified lines15161718192044 unmodified lines6566676869707172737447 unmodified lines1221231241251261271281291301311321331341351361371381391401411421435 unmodified lines1491501511521531541551561571581591601611621631641651664 unmodified lines1711721731741751761775 unmodified lines18318418518618718818919019119 unmodified lines2112122132142152162171 unmodified line2192202212222232242252262272282294 unmodified lines2342352362372382392402412422432442452462472482492502512522532547 unmodified lines2622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343351 unmodified line3373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304311 unmodified line4334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365372 unmodified lines5405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865876 unmodified lines5945955965975985996006016026036046056066076086095 unmodified lines61561661761861962062162262362462562662762862963063128 unmodified lines6606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917928 unmodified lines801802803804805806807"""OCRia Parse API — modular CPU pipeline edition.Stages: DocLayout-YOLO (layout) → RapidOCR/PP-OCRv6 (text) → SLANet (tables).Streaming: NDJSON with `chunk` events for markdown/text so output flows inlike an LLM response; `page` events for json.Run: python app.py (listens on 7860)"""import asyncioimport importlib.metadata as imimport json3 unmodified linesimport tempfileimport threadingimport timefrom contextlib import asynccontextmanagerfrom enum import Enumfrom pathlib import Path44 unmodified linesMAX_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") # 'small' | 'medium'LAYOUT_IMGSZ = _env_int("LAYOUT_IMGSZ", 1024)CHUNK_SIZE = _env_int("CHUNK_SIZE", 24) # chars per streamed chunkCHUNK_DELAY = float(os.getenv("CHUNK_DELAY", "0.008")) # seconds between chunksDOC_EXT = [".pdf"]IMG_EXT = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp", ".svg"]47 unmodified linesSTATE.update(status="error", error=f"{type(e).__name__}: {e}")@asynccontextmanagerasync def lifespan(_: FastAPI):task = asyncio.create_task(asyncio.to_thread(bootstrap))yieldtask.cancel()# --------------------------------------------------------------------------- helpersdef _pdf_to_images(path: str, max_pages: int):"""Yield (page_num, RGB PIL image) for each page of a PDF."""import fitzfrom PIL import Imagedoc = fitz.open(path)try:for i, page in enumerate(doc, 1):if i > max_pages:5 unmodified linesdef _image_to_pages(path: str):"""Yield a single (1, PIL image) from an image file."""from PIL import Imagewith Image.open(path) as im:yield 1, im.convert("RGB").copy()def _text_pages(path: str, max_pages: int):"""Yield (page_num, text) extracted from a born-digital PDF."""import fitzdoc = fitz.open(path)try:for i, page in enumerate(doc, 1):if i > max_pages:4 unmodified linesdef _chunks(text: str, size: int = CHUNK_SIZE):"""Word-aware chunking for streaming."""n, i = len(text), 0while i < n:j = min(i + size, n)5 unmodified linesi = j_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"),]19 unmodified linesraise HTTPException(400, "rotate only works on raster images.")try:from PIL import Image, ImageOpswith 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"):1 unmodified lineout.save(path)except HTTPException:raiseexcept Exception as e: # noqa: BLE001raise HTTPException(422, f"Could not rotate the image: {e}")async def save_upload(file: UploadFile):name = file.filename or "upload"ext = Path(name).suffix.lower()fd, tmp = tempfile.mkstemp(prefix="ocria_", suffix=ext or ".bin")4 unmodified lineshead = head or chunk[:16]size += len(chunk)if size > limit:raise HTTPException(413, f"File is larger than the {MAX_MB} MB limit.")f.write(chunk)if size == 0:raise HTTPException(400, "The uploaded file is empty.")if ext in OFFICE_EXT and not HAS_SOFFICE:raise HTTPException(415,f"{ext} needs LibreOffice. Add `libreoffice` to packages.txt, or upload a PDF.",)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] + realos.replace(tmp, fixed)tmp = fixed7 unmodified linesreturn int((time.perf_counter() - t0) * 1000)def nd(obj: dict) -> str:return json.dumps(obj, ensure_ascii=False) + "\n"def err_message(e: Exception) -> tuple[int, str]:if isinstance(e, asyncio.TimeoutError):return 504, f"Parsing took longer than {PARSE_TIMEOUT}s and was stopped."return 422, f"The document could not be parsed: {e}"# --------------------------------------------------------------------------- parse coredef _parse_pages(path: str, ext: str, ocr: bool):"""Yield (page_num, markdown_text, plain_text) per page. Blocking."""parser = get_parser()src = _pdf_to_images(path, MAX_PAGES) if ext == ".pdf" else _image_to_pages(path)for page_num, img in src:blocks = parser.parse(img)md = parser.to_markdown(blocks, page_num)text = "\n".join(b.text for b in blocks if b.text)yield page_num, md, textdef _parse_text_pages(path: str, ocr: bool):"""Born-digital fast path — no OCR, no layout model."""if ocr:return Nonereturn _text_pages(path, MAX_PAGES)# --------------------------------------------------------------------------- appDESCRIPTION = f"""Parse PDFs, scans, images and (with LibreOffice) Office files into **Markdown**, **JSON** or **plain text**with a modular CPU pipeline: **DocLayout-YOLO + RapidOCR (PP-OCRv6) + SLANet**.**Streaming.** Set `stream=true`. Output arrives as NDJSON events:- `markdown` / `text`: `start` → repeated `chunk` (small pieces, like an LLM) → `done`.- `json`: `start` → one `page` event per page → `done`.**Limits.** {MAX_MB} MB, {MAX_PAGES} pages, {PARSE_TIMEOUT}s per document."""app = FastAPI(title="OCRia Parse API",version="2.0.0",description=DESCRIPTION,docs_url=None,redoc_url=None,lifespan=lifespan,openapi_tags=[{"name": "Parse", "description": "Upload a document and get structured text back."},{"name": "Health", "description": "Readiness and runtime layout."},],)app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_methods=["*"],allow_headers=["*"],expose_headers=["X-Pages", "X-Elapsed-Ms"],)@app.get("/health", tags=["Health"], summary="Health check")async def health():ready = STATE["status"] == "ready"try:1 unmodified lineexcept Exception:version = Nonebody = {"status": STATE["status"],"ready": ready,"detail": STATE["error"],"model": "modular: DocLayout-YOLO + RapidOCR + SLANet","ocr_tier": OCR_TIER,"layout_imgsz": LAYOUT_IMGSZ,"rapidocr": version,"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},"formats": {"documents": DOC_EXT, "images": IMG_EXT, "office": OFFICE_EXT, "office_available": HAS_SOFFICE},}return JSONResponse(body, status_code=200 if ready else 503)@app.post("/api/parse", tags=["Parse"], summary="Parse a document")async def parse(file: UploadFile = File(...),output_format: OutputFormat = Form(OutputFormat.markdown),stream: bool = Form(False),ocr: bool = Form(True),include_text_items: bool = Form(False),rotate: Rotation = Form(Rotation.r0),):if STATE["status"] != "ready":raise HTTPException(503, "The model is 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)raisefmt = output_format.valueif stream:return StreamingResponse(stream_body(path, name, ext, fmt, ocr),media_type="application/x-ndjson",headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},)t0 = time.perf_counter()try:result = await _run_full(path, ext, fmt, ocr)except Exception as e: # noqa: BLE001cleanup(path)code, msg = err_message(e)raise HTTPException(code, msg)cleanup(path)n, ms = result["total_pages"], ms_since(t0)if fmt == "json":return JSONResponse({**result, "elapsed_ms": ms})media = "text/markdown; charset=utf-8" if fmt == "markdown" else "text/plain; charset=utf-8"return Response(result["text"], media_type=media, headers={"X-Pages": str(n), "X-Elapsed-Ms": str(ms)})async def _run_full(path: str, ext: str, fmt: str, ocr: bool) -> dict:async with SEM:def _work():pages, md_parts = [], []if ext == ".pdf" and not ocr:for page_num, text in _text_pages(path, MAX_PAGES):pages.append({"page_num": page_num, "text": text, "width": 612.0, "height": 792.0})md_parts.append(text)else:for page_num, md, text in _parse_pages(path, ext, ocr):pages.append({"page_num": page_num, "text": text, "width": 612.0, "height": 792.0})md_parts.append(md)return pages, "\n\n-----\n\n".join(md_parts)pages, markdown = await asyncio.to_thread(_work)return {"filename": Path(path).name,"output_format": fmt,"total_pages": len(pages),"text": markdown if fmt != "text" else "\n\n-----\n\n".join(p["text"] for p in pages),"pages": pages,}async def stream_body(path: str, name: str, ext: str, fmt: str, ocr: bool):"""NDJSON streaming: `chunk` events for text/markdown, `page` events for json."""t0 = time.perf_counter()loop = asyncio.get_running_loop()q: asyncio.Queue = asyncio.Queue()1 unmodified linedef producer():try:if ext == ".pdf" and not ocr:for page_num, text in _text_pages(path, MAX_PAGES):if stop.is_set():returnloop.call_soon_threadsafe(q.put_nowait, ("page", page_num, text, text))else:for page_num, md, text in _parse_pages(path, ext, ocr):if stop.is_set():returnloop.call_soon_threadsafe(q.put_nowait, ("page", page_num, md, text))loop.call_soon_threadsafe(q.put_nowait, ("end", None, None, None))except Exception as e: # noqa: BLE001loop.call_soon_threadsafe(q.put_nowait, ("err", e, None, None))runner = asyncio.create_task(asyncio.to_thread(producer))total = 0async with SEM:yield nd({"event": "start", "filename": name, "format": fmt})try:while True:try:kind, a, b, c = await asyncio.wait_for(q.get(), timeout=PARSE_TIMEOUT)except asyncio.TimeoutError:yield nd({"event": "error", "detail": f"timeout after {PARSE_TIMEOUT}s"})returnif kind == "err":_, msg = err_message(a)yield nd({"event": "error", "detail": msg})returnif kind == "end":breakpage_num, md, text = a, b, ctotal += 1if fmt == "json":yield nd({"event": "page", "page": {"page_num": page_num, "text": text,"width": 612.0, "height": 792.0},"total_pages": total})else:payload = md if fmt == "markdown" else text# Prefix separators for multi-page readabilityif total > 1:payload = "\n\n-----\n\n" + payloadfor piece in _chunks(payload, CHUNK_SIZE):yield nd({"event": "chunk", "text": piece})await asyncio.sleep(CHUNK_DELAY) # forces visible streamingfinally:stop.set()runner.cancel()cleanup(path)yield nd({"event": "done", "total_pages": total, "elapsed_ms": ms_since(t0)})# --------------------------------------------------------------------------- docs pageDOCS_CSS = r""":root{--ink:#0f1b2a;--mut:#5b6b7e;--line:#c9d2dc;--bg:#e8ecf1;--pan:#f9fafc;--acc:#1f4fff}html,body{background:var(--bg)}body{margin:0;color:var(--ink);font:15px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}.bar{display:flex;align-items:center;gap:22px;padding:14px max(20px,calc(50% - 560px));background:var(--ink)}.bar b{font:600 19px/1 ui-serif,"Iowan Old Style","Palatino Linotype",Georgia,serif;color:#f4f6fa}.bar a{color:#aebbd0;text-decoration:none;font-size:14px}.bar a:hover{color:#fff}.bar .sp{flex:1}.swagger-ui{font-family:inherit}.swagger-ui .wrapper{max-width:1120px;padding:0 20px}.swagger-ui .info .title{font:600 36px/1.15 ui-serif,Georgia,serif;color:var(--ink)}.swagger-ui .opblock-tag{font:600 21px ui-serif,Georgia,serif;color:var(--ink);border-bottom:1px solid var(--line)}.swagger-ui .opblock{border-radius:12px;background:var(--pan);box-shadow:none;margin:0 0 14px}.swagger-ui .opblock.opblock-post{border-color:var(--acc);background:#f3f5ff}.swagger-ui .opblock.opblock-post .opblock-summary-method{background:var(--acc)}.swagger-ui .btn.execute{background:var(--acc);border-color:var(--acc);color:#fff}.swagger-ui .topbar{display:none}"""DOCS_BAR = ('<div class="bar"><b>OCRia parse</b><span class="sp"></span>''<a href="/">Open the app</a><a href="/health">Health</a><a href="/openapi.json">OpenAPI JSON</a></div>')@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","displayRequestDuration": True,"tryItOutEnabled": True,"defaultModelsExpandDepth": -1,},)html = page.body.decode()html = html.replace("</head>", f"<style>{DOCS_CSS}</style></head>", 1)html = html.replace("<body>", f"<body>{DOCS_BAR}", 1)return HTMLResponse(html)# --------------------------------------------------------------------------- web app2 unmodified linesINDEX = 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;--glow:#ffd54a;--ok:#2f9e63;--bad:#c2362b;--serif:ui-serif,"Iowan Old Style",Georgia,serif;--sans:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;--mono:ui-monospace,Menlo,Consolas,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:26px;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:20px;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:var(--glow);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:52px 0 30px;max-width:720px}h1{font:600 clamp(34px,5.4vw,56px)/1.05 var(--serif);letter-spacing:-.015em;margin:0 0 16px}.intro p{margin:0;color:var(--mut);font-size:18px;max-width:56ch}.work{display:grid;gap:22px;grid-template-columns:minmax(0,5fr) minmax(0,7fr);align-items:start}@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:210px;padding:26px 20px;border-radius:8px;background:#fff;border:1px dashed var(--line);cursor:pointer;overflow:hidden}.bed:hover,.bed.drag{border-color:var(--scan);background:#f3f5ff}.bed b{font:600 20px 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:5px 10px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.bed input{position:absolute;inset:0;opacity:0;cursor:pointer;font-size:0}.scan{position:absolute;left:0;right:0;top:0;height:3px;background:var(--glow);box-shadow:0 0 22px 8px rgba(255,213,74,.55);opacity:0}.bed.busy .scan{opacity:1;animation:sweep 1.7s ease-in-out infinite alternate}@keyframes sweep{from{transform:translateY(0)}to{transform:translateY(208px)}}.opts{border:0;padding:0;margin:18px 0 0;display:grid;gap:16px}.lbl{font-size:14px;font-weight:600;margin-bottom:8px;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:9px 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:20px;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)}6 unmodified lines.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}.pg{border:1px solid var(--line);border-radius:8px;background:#fff;margin-bottom:12px;overflow:hidden}.pg h4{margin:0;padding:7px 12px;font:600 13px var(--sans);background:var(--bg)}.pg pre{padding:12px}.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:23px}.md h3{font-size:19px}.md p{margin:.6em 0;max-width:75ch}.md code{font:13px var(--mono);background:var(--bg);padding:1px 5px;border-radius:4px}.md .tw{overflow-x:auto;margin:.8em 0}.md table{border-collapse:collapse;font-size:14px;min-width:50%}.md th,.md td{border:1px solid var(--line);padding:6px 10px;text-align:left;vertical-align:top}.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,.bed.busy .scan,.cursor::after{animation:none}}</style></head><body>5 unmodified lines<main><section class="intro"><h1>Turn scans and PDFs into structured text.</h1><p>Drop in a document and get Markdown, JSON or plain text back. Modular CPU pipeline: DocLayout-YOLO + RapidOCR + SLANet.</p></section><section class="work"><div class="src"><label class="bed" id="bed"><i class="scan"></i><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><fieldset class="opts"><div><span class="lbl">Output</span>28 unmodified lines</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,'&').replace(/</g,'<').replace(/>/g,'>');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;setStatus('ready','Ready',`${j.cpu.usable} cores · ${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>').replace(/\*([^*\s][^*]*)\*/g,'<i>$1</i>');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+='<div class="tw"><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></div>';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>Parsing 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 document.</div>';return;}if(!S.out&&S.busy){v.innerHTML='<div class="empty"><b>Reading the document</b>Results appear as they stream in.</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';$('#bed').classList.toggle('busy',S.busy);$('#copy').disabled=$('#dl').disabled=!S.out;const m=S.meta,bits=[];if(m.pages!=null)bits.push(`${m.pages} page${m.pages==1?'':'s'}`);if(m.ms!=null)bits.push(`${(m.ms/1000).toFixed(2)} s`);if(S.out)bits.push(`${S.out.length.toLocaleString()} chars`);$('#stats').innerHTML=bits.map(b=>`<span>${b}</span>`).join('');render();}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();const stream=$('#stream').checked;const fd=new FormData();fd.append('file',S.file);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',{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.detail||j);}catch{}throw new Error(d);}if(stream)await readStream(res);else await readFull(res);}catch(e){S.err=e.message||String(e);}finally{S.busy=false;ui();}}async function readFull(res){if(S.fmt==='json'){const j=await res.json();S.pages=j.pages||[];S.meta={pages:j.total_pages,ms:j.elapsed_ms};S.out=JSON.stringify(j,null,2);}else{S.out=await res.text();S.meta={pages:res.headers.get('X-Pages'),ms:res.headers.get('X-Elapsed-Ms')};}}async function readStream(res){const rd=res.body.getReader(),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'))>=0){const line=buf.slice(0,i);buf=buf.slice(i+1);if(!line.trim())continue;let e;try{e=JSON.parse(line);}catch{continue;}if(e.event==='chunk'){S.out+=e.text;render();}else if(e.event==='page'){S.pages.push(e.page);S.meta.pages=S.pages.length;render();}else if(e.event==='done'){S.meta={pages:e.total_pages,ms:e.elapsed_ms};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;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],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>8 unmodified linesif __name__ == "__main__":try:from spaces import zero as _zero_zero.startup()except Exception:pass123453 unmodified lines910111213141544 unmodified lines60616263646566676869707172737447 unmodified lines1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541555 unmodified lines1611621631641651661671681691701711721731744 unmodified lines1791801811821831845 unmodified lines19019119219319419519619719819920020120220320420520620720820921021121221321421519 unmodified lines2352362372382392401 unmodified line2422432442452462472482492502512524 unmodified lines2572582592602612622632642652662672682692702712727 unmodified lines2802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323331 unmodified line3353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544551 unmodified line4574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255262 unmodified lines5295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745756 unmodified lines5825835845855865875885895905915925935945955 unmodified lines60160260360460560660760860961061161261361461561661761861962028 unmodified lines6496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039048 unmodified lines913914915916917918"""OCRia Parse API — modular pipeline with SSE streaming + upload/parse split."""import asyncioimport importlib.metadata as imimport json3 unmodified linesimport tempfileimport threadingimport timeimport uuidfrom contextlib import asynccontextmanagerfrom enum import Enumfrom pathlib import Path44 unmodified linesMAX_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", 1024)CHUNK_SIZE = _env_int("CHUNK_SIZE", 24)CHUNK_DELAY = float(os.getenv("CHUNK_DELAY", "0.008"))UPLOAD_TTL = _env_int("UPLOAD_TTL", 3600)HEARTBEAT_S = float(os.getenv("HEARTBEAT_S", "1.0"))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"]47 unmodified linesSTATE.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@asynccontextmanagerasync def lifespan(_: FastAPI):boot = asyncio.create_task(asyncio.to_thread(bootstrap))cleaner = asyncio.create_task(_cleanup_uploads())yieldboot.cancel()cleaner.cancel()# --------------------------------------------------------------------------- helpersdef _pdf_to_images(path: str, max_pages: int):import pymupdffrom PIL import Imagedoc = pymupdf.open(path)try:for i, page in enumerate(doc, 1):if i > max_pages:5 unmodified linesdef _image_to_pages(path: str):from PIL import Imagewith Image.open(path) as im:yield 1, im.convert("RGB").copy()def _text_pages(path: str, max_pages: int):import pymupdfdoc = pymupdf.open(path)try:for i, page in enumerate(doc, 1):if i > max_pages:4 unmodified linesdef _chunks(text: str, size: int = CHUNK_SIZE):n, i = len(text), 0while i < n:j = min(i + size, n)5 unmodified linesi = jdef 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 Nonefor p in UPLOAD_DIR.glob(f"{file_id}.*"):return preturn 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"),]19 unmodified linesraise HTTPException(400, "rotate only works on raster images.")try:from PIL import Image, ImageOpswith 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"):1 unmodified lineout.save(path)except HTTPException:raiseexcept 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")4 unmodified lineshead = 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] + realos.replace(tmp, fixed)tmp = fixed7 unmodified linesreturn 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 coredef _parse_streaming(path: str, ext: str, ocr: bool):"""Yield (page_num, markdown_payload, plain_text_payload) per region."""parser = get_parser()if ext == ".pdf" and not ocr:for page_num, text in _text_pages(path, MAX_PAGES):yield page_num, text, textreturnsrc = _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# --------------------------------------------------------------------------- appDESCRIPTION = f"""Parse PDFs, scans, images and Office files into **Markdown**, **JSON** or **plain text**.**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."""app = FastAPI(title="OCRia Parse API", version="2.1.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:1 unmodified lineexcept Exception:version = Nonebody = {"status": STATE["status"], "ready": ready, "detail": STATE["error"],"model": "modular: DocLayout-YOLO + RapidOCR + SLANet","ocr_tier": OCR_TIER, "layout_imgsz": LAYOUT_IMGSZ, "rapidocr": version,"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().hexdest = 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):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:if ext == ".pdf" and not ocr:pages = [{"page_num": n, "text": t} for n, t in _text_pages(path, MAX_PAGES)]md = "\n\n-----\n\n".join(p["text"] for p in pages)else:src = _pdf_to_images(path, MAX_PAGES) if ext == ".pdf" else _image_to_pages(path)parser = get_parser()pages, md_parts = [], []for page_num, img in src:blocks = parser.parse(img)md_parts.append(parser.to_markdown(blocks, page_num))pages.append({"page_num": page_num,"text": "\n".join(b.text for b in blocks if b.text)})md = "\n\n-----\n\n".join(md_parts)finally:cleanup(path)ms = ms_since(t0)if fmt == "json":return JSONResponse({"filename": Path(path).name, "total_pages": len(pages),"elapsed_ms": ms, "text": md, "pages": pages})media = "text/markdown; charset=utf-8" if fmt == "markdown" else "text/plain; charset=utf-8"body = md if fmt != "text" else "\n\n-----\n\n".join(p["text"] for p in pages)return Response(body, media_type=media,headers={"X-Pages": str(len(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, _ = 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)raisereturn await _dispatch(path, ext, output_format.value, ocr, stream)@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)raisereturn await _dispatch(path, ext, output_format.value, ocr, stream)# --------------------------------------------------------------------------- SSE streamasync 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()1 unmodified linedef producer():try:for page_num, md, text in _parse_streaming(path, ext, ocr):if stop.is_set():returnloop.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: BLE001loop.call_soon_threadsafe(q.put_nowait, ("err", e, None, None))runner = asyncio.create_task(asyncio.to_thread(producer))region_count = 0pages_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:# Heartbeat so UI never looks frozen during 8-16s OCR passesyield sse("progress", {"elapsed_ms": ms_since(t0)})continueif kind == "err":_, msg = err_message(a)yield sse("error", {"detail": msg})returnif kind == "end":breakpage_num, md, text = a, b, cregion_count += 1if fmt == "json":pages_buf.setdefault(page_num, []).append(text)else:payload = md if fmt == "markdown" else textif region_count > 1:payload = "\n\n" + payloadfor piece in _chunks(payload, CHUNK_SIZE):yield sse("chunk", {"text": piece})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)})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 app2 unmodified linesINDEX = 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)}6 unmodified lines.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>5 unmodified lines<main><section class="intro"><h1>Turn scans and PDFs into structured text.</h1><p>Modular CPU 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>28 unmodified lines</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,'&').replace(/</g,'<').replace(/>/g,'>');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; setStatus('ready','Ready',`${j.cpu.usable} cores · ${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;// Upload barif(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.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();// Phase 1 — uploadlet uploaded;try {uploaded = await uploadWithProgress(S.file);} catch(e){S.err = e.message; S.busy = false; S.meta = {}; ui(); return;}// Phase 2 — parseS.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.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.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>8 unmodified linesif __name__ == "__main__":try:from spaces import zero as _zero_zero.startup()except Exception:pass
app.py+438-327