Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files71 unmodified lines727374757677218 unmodified lines29629729829930030130230330430530630730864 unmodified lines37337437537637737837938068 unmodified lines449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482201 unmodified lines684685686687688689690233 unmodified lines92492592692771 unmodified linesMAX_PAGES = _env_int("MAX_PAGES", 200)PARSE_TIMEOUT = _env_int("PARSE_TIMEOUT", 180)MAX_MB = _env_int("MAX_UPLOAD_MB", 50)OCR_BACKEND = os.getenv("OCR_BACKEND", "ocria-nano")DOC_EXT = [".pdf"]218 unmodified linesParse PDFs, scans, images and (with LibreOffice) Office files into **Markdown**, **JSON** or **plain text**using **OCRia-nano-1** through LiteParse. CPU only.**Streaming.** Set `stream=true`.- `json` returns `application/x-ndjson`: a `start` event, `progress` heartbeats while the engine works,one `page` event per page, then `done`.- `markdown` and `text` return chunked `text/markdown` or `text/plain`.The engine parses the whole document before pages are emitted, so streaming keeps the connection aliveand delivers output in pieces. It does not make a single parse faster.**Limits.** {MAX_MB} MB per file, {MAX_PAGES} pages, {PARSE_TIMEOUT}s per document."""64 unmodified lines"text/plain": {"example": "Quarterly report ..."},"application/x-ndjson": {"example": '{"event":"start","filename":"report.pdf"}\n''{"event":"progress","elapsed_ms":1500}\n''{"event":"page","page":{"page_num":1,"text":"..."}}\n''{"event":"done","total_pages":1,"elapsed_ms":1730}\n'},},68 unmodified linesasync def stream_body(path: str, name: str, fmt: str, ocr: bool, items: bool):t0 = time.perf_counter()try:if fmt == "json":yield nd({"event": "start", "filename": name})task = asyncio.create_task(do_parse(path, fmt, ocr))while True:done, _ = await asyncio.wait({task}, timeout=1.5)if done:breakif fmt == "json":yield nd({"event": "progress", "elapsed_ms": ms_since(t0)})try:result = task.result()except Exception as e: # noqa: BLE001_, msg = err_message(e)if fmt == "json":yield nd({"event": "error", "detail": msg})else:yield f"\n\n> **Error:** {msg}\n"returnif fmt == "json":for p in result.pages:yield nd({"event": "page", "page": page_dict(p, items)})yield nd({"event": "done", "total_pages": total_pages(result), "elapsed_ms": ms_since(t0)})else:for c in chunks(result.text):yield cawait asyncio.sleep(0)finally:cleanup(path)201 unmodified lines</div></div><label class="tg"><input type="checkbox" id="ocr" checked><span>Read scanned pages<em>Turn off for born-digital PDFs to skip OCR.</em></span></label><label class="tg"><input type="checkbox" id="stream"><span>Stream the result<em>Output arrives in pieces instead of all at once.</em></span></label><label class="tg" id="itemsRow" hidden><input type="checkbox" id="items"><span>Include text boxes<em>Adds position and confidence for each text item.</em></span></label></fieldset><button class="go" id="go" disabled>Parse document</button>233 unmodified lines_zero.startup()except Exception:passuvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")), timeout_keep_alive=75)71 unmodified lines7273747576777879218 unmodified lines29829930030130230330430530630730830964 unmodified lines37437537637737837938068 unmodified lines449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500201 unmodified lines702703704705706707708233 unmodified lines94294394494571 unmodified linesMAX_PAGES = _env_int("MAX_PAGES", 200)PARSE_TIMEOUT = _env_int("PARSE_TIMEOUT", 180)MAX_MB = _env_int("MAX_UPLOAD_MB", 50)STREAM_BATCH = _env_int("STREAM_BATCH_PAGES", 1)PAGE_SEP = "\n\n-----\n\n"OCR_BACKEND = os.getenv("OCR_BACKEND", "ocria-nano")DOC_EXT = [".pdf"]218 unmodified linesParse PDFs, scans, images and (with LibreOffice) Office files into **Markdown**, **JSON** or **plain text**using **OCRia-nano-1** through LiteParse. CPU only.**Streaming.** Set `stream=true`. Pages are sent as each one finishes, not after the whole document.- `json` returns `application/x-ndjson`: a `start` event, one `page` event per page, then `done`.- `markdown` and `text` return chunked `text/markdown` or `text/plain`, one page at a time, separated by `-----`.Streaming parses page by page, so repeated header and footer removal works per page and the output can differslightly from a non-streamed parse on multi-page documents. A single image or one-page file has one page, so it arrives in one piece.**Limits.** {MAX_MB} MB per file, {MAX_PAGES} pages, {PARSE_TIMEOUT}s per document."""64 unmodified lines"text/plain": {"example": "Quarterly report ..."},"application/x-ndjson": {"example": '{"event":"start","filename":"report.pdf"}\n''{"event":"page","page":{"page_num":1,"text":"..."},"total_pages":1}\n''{"event":"done","total_pages":1,"elapsed_ms":1730}\n'},},68 unmodified linesasync def stream_body(path: str, name: str, fmt: str, ocr: bool, items: bool):t0 = time.perf_counter()loop = asyncio.get_running_loop()q: asyncio.Queue = asyncio.Queue()stop = threading.Event()def worker(parser):try:for batch in parser.parse_batches(path, batch_size=STREAM_BATCH):if stop.is_set():returnloop.call_soon_threadsafe(q.put_nowait, ("batch", batch))loop.call_soon_threadsafe(q.put_nowait, ("end", None))except Exception as e: # noqa: BLE001loop.call_soon_threadsafe(q.put_nowait, ("err", e))sent = 0try:async with SEM:if fmt == "json":yield nd({"event": "start", "filename": name})parser = await asyncio.to_thread(get_parser, fmt, ocr)runner = asyncio.create_task(asyncio.to_thread(worker, parser))while True:try:kind, val = await asyncio.wait_for(q.get(), timeout=PARSE_TIMEOUT)except asyncio.TimeoutError:kind, val = "err", ParseTimeoutError(f"no page finished within {PARSE_TIMEOUT}s")if kind == "err":_, msg = err_message(val)yield nd({"event": "error", "detail": msg}) if fmt == "json" else f"\n\n> **Error:** {msg}\n"returnif kind == "end":breakpages = val.result.pagesif fmt == "json":for p in pages:sent += 1yield nd({"event": "page", "page": page_dict(p, items), "total_pages": val.total_pages})else:sent += len(pages)text = val.result.text.strip("\n")yield (PAGE_SEP if sent > len(pages) else "") + textawait asyncio.sleep(0)if fmt == "json":yield nd({"event": "done", "total_pages": sent, "elapsed_ms": ms_since(t0)})finally:stop.set()cleanup(path)201 unmodified lines</div></div><label class="tg"><input type="checkbox" id="ocr" checked><span>Read scanned pages<em>Turn off for born-digital PDFs to skip OCR.</em></span></label><label class="tg"><input type="checkbox" id="stream"><span>Stream the result<em>Pages appear as each one finishes. Multi-page files only.</em></span></label><label class="tg" id="itemsRow" hidden><input type="checkbox" id="items"><span>Include text boxes<em>Adds position and confidence for each text item.</em></span></label></fieldset><button class="go" id="go" disabled>Parse document</button>233 unmodified lines_zero.startup()except Exception:passuvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")), timeout_keep_alive=75)
app.py+51-33