Image-Text-to-Text
Transformers
Safetensors
qwen3_5
decision-model
system-one
flide
ocr
pdf
document-understanding
hf_jobs
conversational
File size: 7,353 Bytes
f601bcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cbf2ad1
 
 
 
 
 
f601bcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# /// 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()