Spaces:
Running on Zero
Running on Zero
File size: 5,769 Bytes
c9a061c 6b679f5 c9a061c 6b679f5 c9a061c 4183e6c c9a061c 4183e6c c9a061c 4183e6c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | 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)
|