import os os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import spaces # noqa: E402 โ€” must precede any torch / CUDA import import torch # noqa: E402 import gradio as gr # noqa: E402 from PIL import Image # noqa: E402 from transformers import AutoModelForCausalLM, AutoProcessor # noqa: E402 MODEL_ID = "flow3rdown/VenusOCR" TASKS = [ ("๐Ÿ“„ Text โ€” plain text / Markdown", "Text"), ("โˆ‘ Formula โ€” LaTeX", "Formula"), ("โ–ฆ Table โ€” OTSL structure", "Table"), ] DEFAULT_MAX_NEW_TOKENS = 2048 # Load eagerly at module scope: ZeroGPU intercepts .to("cuda") and streams the # packed weights into VRAM on the first @spaces.GPU entry. processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True) model = ( AutoModelForCausalLM.from_pretrained( MODEL_ID, dtype=torch.bfloat16, attn_implementation="sdpa", trust_remote_code=True, ) .to("cuda") .eval() ) def _estimate_duration(*args, **kwargs) -> int: """Worst-case ZeroGPU seconds for the requested token budget (measured ~15ms/token + per-call overhead).""" max_new_tokens = kwargs.get("max_new_tokens") if max_new_tokens is None and len(args) > 2: max_new_tokens = args[2] try: max_new_tokens = int(max_new_tokens) if max_new_tokens is not None else DEFAULT_MAX_NEW_TOKENS except (TypeError, ValueError): max_new_tokens = DEFAULT_MAX_NEW_TOKENS return int(min(90, 12 + max_new_tokens * 0.015)) @spaces.GPU(duration=_estimate_duration) def run_ocr( image: Image.Image, task: str = "Text", max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS, ) -> tuple[str, str]: """Recognize text, formulas, or tables in a document image with VenusOCR 2.0. Args: image: the document region / page image to parse. task: recognition task โ€” "Text" (plain text / Markdown), "Formula" (LaTeX), or "Table" (OTSL table structure). max_new_tokens: generation budget for the output. Returns: A tuple (raw_output, rendered_copy): the raw recognized string and the same string for the rendered-preview panel. """ if image is None: raise ValueError("Please upload a document image first.") task = task or "Text" prompt_text = f"{task.capitalize()} Recognition:" messages = [ { "role": "user", "content": [ {"type": "image"}, {"type": "text", "text": prompt_text}, ], } ] prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) inputs = processor(images=image, text=prompt, return_tensors="pt").to(model.device) with torch.inference_mode(): output_ids = model.generate(**inputs, max_new_tokens=int(max_new_tokens), do_sample=False) generated_ids = output_ids[:, inputs["input_ids"].shape[1] :] text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] return text, text CSS = """ #col-container { max-width: 1100px; margin: 0 auto; } .dark .gradio-container { color: var(--body-text-color); } """ INTRO = """ # ๐Ÿ“„ VenusOCR 2.0 โ€” Document Parsing **VenusOCR 2.0** is a 1B region-level OCR / document-parsing VLM. Upload a document region or page, pick a task, and get structured output: - **Text** โ†’ plain text / Markdown - **Formula** โ†’ LaTeX - **Table** โ†’ OTSL table structure [Paper](https://huggingface.co/papers/2611.32617) ยท [Model](https://huggingface.co/flow3rdown/VenusOCR) ยท [GitHub](https://github.com/flow3rdown/VenusOCR) """ with gr.Blocks() as demo: with gr.Column(elem_id="col-container"): gr.Markdown(INTRO) with gr.Row(): with gr.Column(): image_in = gr.Image(type="pil", label="Document image") task_dd = gr.Dropdown( TASKS, value="Text", label="Recognition task", info="Which kind of content should be parsed from the image?", ) with gr.Accordion("Advanced settings", open=False): max_tokens = gr.Slider( 128, 4096, value=DEFAULT_MAX_NEW_TOKENS, step=64, label="Max new tokens", info="Generation budget. Long or dense pages may need more.", ) btn = gr.Button("Run recognition", variant="primary") with gr.Column(): out_text = gr.Textbox( label="Recognized output", lines=14, max_lines=28, buttons=["copy"], ) with gr.Accordion("Rendered preview", open=False): out_md = gr.Markdown( "Run a recognition task to see the parsed result rendered here." ) gr.Examples( examples=[ ["examples/handwriting.jpg", "Text"], ["examples/magazine_page.png", "Text"], ["examples/math_textbook.png", "Formula"], ["examples/financial_table.jpg", "Table"], ], inputs=[image_in, task_dd], outputs=[out_text, out_md], fn=run_ocr, cache_examples=True, cache_mode="lazy", examples_per_page=4, ) btn.click( run_ocr, inputs=[image_in, task_dd, max_tokens], outputs=[out_text, out_md], api_name="generate", ) demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)