Spaces:
Running on Zero
Running on Zero
Download app.py from hugging-apps/venusocr2: direct link, hf CLI and curl.
- Browser
- Download file 5.77 kB
-
https://huggingface.co/spaces/hugging-apps/venusocr2/resolve/main/app.py
- Command line
-
hf download hf://spaces/hugging-apps/venusocr2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hugging-apps/venusocr2/resolve/main/app.py
5.77 kB
| 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)) | |
| 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) | |