Image-Text-to-Text
Transformers
Safetensors
qwen3_5
decision-model
system-one
flide
ocr
pdf
document-understanding
hf_jobs
conversational
Instructions to use davanstrien/ocr-decision-0.8b with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use davanstrien/ocr-decision-0.8b with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="davanstrien/ocr-decision-0.8b") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("davanstrien/ocr-decision-0.8b") model = AutoModelForMultimodalLM.from_pretrained("davanstrien/ocr-decision-0.8b", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use davanstrien/ocr-decision-0.8b with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "davanstrien/ocr-decision-0.8b" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "davanstrien/ocr-decision-0.8b", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/davanstrien/ocr-decision-0.8b
- SGLang
How to use davanstrien/ocr-decision-0.8b with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "davanstrien/ocr-decision-0.8b" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "davanstrien/ocr-decision-0.8b", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "davanstrien/ocr-decision-0.8b" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "davanstrien/ocr-decision-0.8b", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use davanstrien/ocr-decision-0.8b with Docker Model Runner:
docker model run hf.co/davanstrien/ocr-decision-0.8b
Download audit_pdf.py from davanstrien/ocr-decision-0.8b: direct link, hf CLI and curl.
- Browser
- Download file 7.35 kB
-
https://huggingface.co/davanstrien/ocr-decision-0.8b/resolve/main/audit_pdf.py
- Command line
-
hf download hf://davanstrien/ocr-decision-0.8b/audit_pdf.py
-
curl -L -o audit_pdf.py https://huggingface.co/davanstrien/ocr-decision-0.8b/resolve/main/audit_pdf.py
7.35 kB
| # /// script | |
| # requires-python = ">=3.11" | |
| # dependencies = [ | |
| # "torch>=2.5", | |
| # "torchvision", | |
| # "transformers>=5.0", | |
| # "accelerate", | |
| # "pypdfium2>=4.30", | |
| # "pillow>=10", | |
| # "rich>=13", | |
| # ] | |
| # /// | |
| """Audit a local PDF's embedded text layer and page layout with ocr-decision-0.8b. | |
| Usage: | |
| uv run audit_pdf.py sample.pdf --max-pages 10 | |
| uv run audit_pdf.py sample.pdf --flide-url http://127.0.0.1:8000 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import base64 | |
| import io | |
| import json | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import pypdfium2 as pdfium | |
| from PIL import Image | |
| from rich.console import Console | |
| from rich.table import Table | |
| DEFAULT_MODEL = "davanstrien/ocr-decision-0.8b" | |
| CALIBRATION_T = 2.5 | |
| QUESTIONS = { | |
| "has_text": ("Is there printed text on this page?", False), | |
| "has_table": ("The page contains a table.", False), | |
| "has_equation": ("The page contains mathematical or chemical equations.", False), | |
| "omission": ("Is a block of printed text on this page missing from the transcription?", True), | |
| "extra": ("Does this transcription contain text that is not printed on the page?", True), | |
| } | |
| def render_page(pdf_doc: pdfium.PdfDocument, idx: int, max_side: int = 1024) -> tuple[Image.Image, str]: | |
| page = pdf_doc[idx] | |
| text = page.get_textpage().get_text_range().strip() | |
| pil = page.render(scale=2.0).to_pil().convert("RGB") | |
| pil.thumbnail((max_side, max_side)) | |
| return pil, text | |
| def score_flide(flide_url: str, img: Image.Image, text: str) -> dict[str, float]: | |
| import urllib.request | |
| buf = io.BytesIO() | |
| img.save(buf, format="JPEG", quality=90) | |
| data_url = "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii") | |
| payload = { | |
| "state": {"page": "<image:1>", "ocr_transcription": text[:6000]}, | |
| "media": [{"type": "image", "data": data_url}], | |
| "questions": {k: {"type": "noul", "instructions": q} for k, (q, _) in QUESTIONS.items()}, | |
| } | |
| req = urllib.request.Request( | |
| f"{flide_url.rstrip('/')}/v1/systemone", | |
| data=json.dumps(payload).encode(), | |
| headers={"Content-Type": "application/json"}, | |
| ) | |
| with urllib.request.urlopen(req, timeout=60) as resp: | |
| ans = json.loads(resp.read().decode())["answers"] | |
| return {k: float(ans[k]["noul"]) for k in QUESTIONS} | |
| class TransformersScorer: | |
| def __init__(self, model_id: str): | |
| import torch | |
| from transformers import AutoModelForImageTextToText, AutoProcessor | |
| self.torch = torch | |
| self.processor = AutoProcessor.from_pretrained(model_id) | |
| if torch.cuda.is_available(): | |
| dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 | |
| elif torch.backends.mps.is_available(): | |
| dtype = torch.bfloat16 | |
| else: | |
| dtype = torch.float32 | |
| self.model = AutoModelForImageTextToText.from_pretrained( | |
| model_id, dtype=dtype, device_map="auto" | |
| ).eval() | |
| self.slot_ids = [ | |
| self.processor.tokenizer.encode(c, add_special_tokens=False)[0] for c in ("A", "B") | |
| ] | |
| def score(self, img: Image.Image, text: str) -> dict[str, float]: | |
| out: dict[str, float] = {} | |
| for key, (question, needs_text) in QUESTIONS.items(): | |
| state_tail = ( | |
| f'",\n "ocr_transcription": {json.dumps(text[:6000])}\n}}\n</state>' | |
| if needs_text | |
| else '"\n}\n</state>' | |
| ) | |
| messages = [ | |
| { | |
| "role": "system", | |
| "content": ( | |
| "Apply the question to the state. Choose exactly one of the listed options. " | |
| "Respond with only its uppercase letter, with no explanation or reasoning." | |
| ), | |
| }, | |
| { | |
| "role": "user", | |
| "content": [ | |
| {"type": "text", "text": '<state>\n{\n "page": "'}, | |
| {"type": "image"}, | |
| { | |
| "type": "text", | |
| "text": ( | |
| f"{state_tail}\n\n" | |
| f"Question: {question}\n\n" | |
| "Options:\n" | |
| "A. yes: the statement is true / the answer is yes\n" | |
| "B. no: the statement is false / the answer is no\n\n" | |
| "Answer with one letter: A, B." | |
| ), | |
| }, | |
| ], | |
| }, | |
| ] | |
| prompt = self.processor.apply_chat_template( | |
| messages, tokenize=False, add_generation_prompt=True, enable_thinking=False | |
| ) | |
| inputs = self.processor(text=[prompt], images=[img], return_tensors="pt").to( | |
| self.model.device | |
| ) | |
| with self.torch.inference_mode(): | |
| logits = self.model(**inputs).logits[0, -1, self.slot_ids].float() | |
| probs = self.torch.softmax(logits / CALIBRATION_T, dim=-1).tolist() | |
| out[key] = float(probs[0]) | |
| return out | |
| def main() -> None: | |
| ap = argparse.ArgumentParser(description="Audit PDF text layers & layout with doc-decision-0.8b") | |
| ap.add_argument("pdf", type=Path, help="Path to local PDF") | |
| ap.add_argument("--model", default=DEFAULT_MODEL, help="HF model repo ID") | |
| ap.add_argument("--flide-url", default="", help="Optional running flide server URL (much faster)") | |
| ap.add_argument("--max-pages", type=int, default=20, help="Max pages to audit") | |
| ap.add_argument("--threshold", type=float, default=0.50, help="Omission/extra escalation threshold") | |
| args = ap.parse_args() | |
| if not args.pdf.exists(): | |
| sys.exit(f"File not found: {args.pdf}") | |
| console = Console() | |
| doc = pdfium.PdfDocument(str(args.pdf)) | |
| n = min(len(doc), args.max_pages) | |
| scorer = None if args.flide_url else TransformersScorer(args.model) | |
| table = Table(title=f"PDF Audit: {args.pdf.name} ({n}/{len(doc)} pages)") | |
| for col in ("Page", "Layer chars", "has_text", "table", "eq", "omission", "extra", "Route", "ms"): | |
| table.add_column(col, justify="right" if col != "Route" else "left") | |
| escalate = 0 | |
| for i in range(n): | |
| img, text = render_page(doc, i) | |
| t0 = time.perf_counter() | |
| s = score_flide(args.flide_url, img, text) if args.flide_url else scorer.score(img, text) | |
| ms = (time.perf_counter() - t0) * 1000 | |
| needs_ocr = (s["has_text"] >= 0.5) and (s["omission"] >= args.threshold or s["extra"] >= args.threshold) | |
| if needs_ocr: | |
| escalate += 1 | |
| route = "[bold red]RUN OCR[/]" if needs_ocr else "[green]KEEP LAYER[/]" | |
| table.add_row( | |
| str(i + 1), | |
| str(len(text)), | |
| f"{s['has_text']:.2f}", | |
| f"{s['has_table']:.2f}", | |
| f"{s['has_equation']:.2f}", | |
| f"{s['omission']:.2f}", | |
| f"{s['extra']:.2f}", | |
| route, | |
| f"{ms:.0f}", | |
| ) | |
| console.print(table) | |
| console.print(f"[bold]Summary:[/] {escalate}/{n} pages flagged for VLM OCR, {n - escalate}/{n} safe to keep embedded text layer.") | |
| if __name__ == "__main__": | |
| main() | |