Set up the data, parsing and quality-control layer for a public benchmark on the Volve daily drilling reports (DDR) and WITSML real-time data. - Data manifest with SHA-256 hashes of the three Volve subtrees in use. - DDR XML parser into DuckDB (1,759 reports, 26 wellbores, 23,447 activities, 17 tables) with locked expected counts. - Render QC of the publisher HTML against the XML (272,544 items). - OCR client for the shared chandra vLLM service, with a page cache keyed on model, prompt hash, dpi, max_tokens and temperature, and OCR QC against the HTML on a 26-report pilot. - Run logging (scripts/runlog.sh, logs/index.csv), the P0 runner and 40 tests. - Research plan, technical overview and progress page (in Vietnamese). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
427 lines
18 KiB
Python
427 lines
18 KiB
Python
"""chandra OCR of PDF pages, read the way vopec-chatbot reads a page with no text layer (app/docs/ocr.py, the vllm
|
|
route, commit 25076e6): one 200-DPI PNG per chat completion with the same prompt, temperature 0, the same token cap,
|
|
the same loop cut and the same block parsing (`LABEL_MAP`, `html_blocks`, `text_of`, `bbox`).
|
|
|
|
Differences, all additive:
|
|
* every page answer is cached on disk (`outputs/ocr/pages/<doc sha256[:16]>/pNNNN.json`) together with what produced
|
|
it: model, prompt hash, DPI, token cap, temperature. A cached answer is reused only when all of them match;
|
|
* the stream asks for token usage, and the finish reason is kept (`length` = the token cap was hit);
|
|
* transport errors and 5xx answers are retried (`retries`), a failure is recorded, and a later run retries it;
|
|
* the service is checked once before any page is rendered (`check_service`), and a run stops sending pages after
|
|
`stop_after_failed` pages in a row failed (the service went down), leaving the rest for the next run;
|
|
* a block keeps chandra's own label (`raw_label`) and its inner HTML for every label, not only for tables.
|
|
|
|
The service URL comes from VOLVE_DIA_OCR_URL (`.env`) and is never written to a log or a cache file.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
import time
|
|
from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
|
|
from dataclasses import asdict, dataclass
|
|
from datetime import datetime, timezone
|
|
from html import unescape
|
|
from pathlib import Path
|
|
from typing import Any, Iterable
|
|
|
|
import httpx
|
|
import yaml
|
|
|
|
from .paths import REPO_ROOT, load_env, outputs_dir
|
|
|
|
MEGABYTE = 1024 * 1024
|
|
CONFIG = REPO_ROOT / "configs" / "ocr.yaml"
|
|
|
|
#: chandra label -> block label, verbatim from vopec-chatbot.
|
|
LABEL_MAP = {
|
|
"title": "title", "section-header": "section_header", "section_header": "section_header",
|
|
"sectionheader": "section_header", "heading": "section_header", "text": "paragraph", "paragraph": "paragraph",
|
|
"plain-text": "paragraph", "list-item": "list_item", "list_item": "list_item", "list": "list_item",
|
|
"table": "table", "caption": "caption", "footnote": "footnote", "formula": "formula", "equation": "formula",
|
|
"page-header": "page_header", "page_header": "page_header", "page-footer": "page_footer",
|
|
"page_footer": "page_footer", "picture": "picture", "figure": "picture", "image": "picture",
|
|
"section header": "section_header", "header": "paragraph", "footer": "page_footer",
|
|
}
|
|
_DIV = re.compile(r'<div\s+data-bbox="([^"]*)"\s+data-label="([^"]*)"\s*>')
|
|
#: What a cached page answer must match to be reused.
|
|
KEY_FIELDS = ("model", "prompt_sha256", "dpi", "max_tokens", "temperature")
|
|
|
|
|
|
class OCRError(RuntimeError):
|
|
pass
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Config:
|
|
model: str
|
|
prompt: str
|
|
prompt_sha256: str
|
|
dpi: int
|
|
max_tokens: int
|
|
temperature: float
|
|
workers: int
|
|
timeout_s: float
|
|
retries: int
|
|
loop_chars: int
|
|
loop_max_unit: int
|
|
loop_check_every: int
|
|
max_page_image_mb: float
|
|
stop_after_failed: int
|
|
|
|
def key(self) -> dict:
|
|
return {k: getattr(self, k) for k in KEY_FIELDS}
|
|
|
|
|
|
def load_config(path: Path = CONFIG) -> Config:
|
|
raw = yaml.safe_load(path.read_text(encoding="utf-8"))
|
|
prompt_file = REPO_ROOT / raw.pop("prompt_file")
|
|
data = prompt_file.read_bytes()
|
|
digest = hashlib.sha256(data).hexdigest()
|
|
if digest != raw["prompt_sha256"]:
|
|
raise OCRError(f"{prompt_file.name}: sha256 {digest} != prompt_sha256 in {path.name}; "
|
|
"the prompt changed, so every cached page answer is stale")
|
|
return Config(prompt=data.decode("utf-8").strip(), **raw)
|
|
|
|
|
|
def service_url() -> str:
|
|
load_env()
|
|
url = os.environ.get("VOLVE_DIA_OCR_URL", "").strip().rstrip("/")
|
|
if not url:
|
|
raise OCRError("VOLVE_DIA_OCR_URL is not set (put it in .env)")
|
|
return url
|
|
|
|
|
|
def check_service(client: httpx.Client, cfg: Config) -> None:
|
|
"""Raise OCRError unless the service answers /v1/models and serves `cfg.model`. The message never holds the URL."""
|
|
try:
|
|
resp = client.get("/v1/models", timeout=30)
|
|
except httpx.TransportError as exc:
|
|
raise OCRError(f"OCR service not reachable: {type(exc).__name__}") from None
|
|
if resp.status_code != 200:
|
|
raise OCRError(f"OCR service not available: HTTP {resp.status_code}")
|
|
try:
|
|
served = [m.get("id") for m in resp.json().get("data", [])]
|
|
except ValueError:
|
|
raise OCRError("OCR service: /v1/models did not answer JSON") from None
|
|
if cfg.model not in served:
|
|
raise OCRError(f"OCR service does not serve {cfg.model!r} (it serves {served})")
|
|
|
|
|
|
# --------------------------------------------------------------------------- page answers -> blocks (vopec)
|
|
|
|
@dataclass
|
|
class Block:
|
|
page: int
|
|
label: str # vopec label (LABEL_MAP)
|
|
raw_label: str # chandra's own label
|
|
text: str
|
|
bbox: list[float]
|
|
reading_order: int
|
|
html: str # inner HTML of the block
|
|
|
|
|
|
def html_blocks(content: str, number: int) -> list[Block]:
|
|
blocks: list[Block] = []
|
|
parts = _DIV.split(content)
|
|
for raw_bbox, raw_label, body in zip(parts[1::3], parts[2::3], parts[3::3]):
|
|
inner = re.sub(r"</div>\s*$", "", body.strip())
|
|
text = text_of(inner)
|
|
if not text:
|
|
continue
|
|
blocks.append(Block(page=number, label=LABEL_MAP.get(raw_label.strip().lower(), "paragraph"),
|
|
raw_label=raw_label.strip(), text=text, bbox=bbox(raw_bbox.split()),
|
|
reading_order=len(blocks), html=inner))
|
|
return blocks
|
|
|
|
|
|
def text_of(html: str) -> str:
|
|
text = re.sub(r"</t[dh]>", " | ", html)
|
|
text = re.sub(r"</tr>|<br\s*/?>|</p>", "\n", text)
|
|
text = unescape(re.sub(r"<[^>]+>", "", text))
|
|
lines = [re.sub(r"\s+", " ", line).strip(" |") for line in text.splitlines()]
|
|
return "\n".join(line for line in lines if line)
|
|
|
|
|
|
def bbox(raw: Any) -> list[float]:
|
|
"""``xyxy_normalized_1000`` as four floats, or empty when unusable."""
|
|
if isinstance(raw, dict):
|
|
raw = raw.get("xyxy_normalized_1000") or raw.get("xyxy") or raw.get("bbox") or raw.get("coordinates")
|
|
if not isinstance(raw, (list, tuple)) or len(raw) != 4:
|
|
return []
|
|
try:
|
|
return [round(float(v), 1) for v in raw]
|
|
except (TypeError, ValueError):
|
|
return []
|
|
|
|
|
|
def loop_start(text: str, cfg: Config) -> int | None:
|
|
"""Where a repetition loop starts: the last `loop_chars` are one unit of at most `loop_max_unit` characters
|
|
repeated (vopec: seen on a scanned empty table grid, blank rows up to the token cap). The cut is moved back to
|
|
the start of the repetition and out of an open tag."""
|
|
if len(text) < cfg.loop_chars:
|
|
return None
|
|
tail = text[-cfg.loop_chars:]
|
|
for unit in range(1, cfg.loop_max_unit + 1):
|
|
if tail[unit:] == tail[:-unit]:
|
|
start = len(text) - cfg.loop_chars
|
|
while start > 0 and text[start - 1] == text[start - 1 + unit]:
|
|
start -= 1
|
|
if text.rfind("<", 0, start) > text.rfind(">", 0, start):
|
|
start = text.find(">", start) + 1
|
|
return start
|
|
return None
|
|
|
|
|
|
# --------------------------------------------------------------------------- one page
|
|
|
|
def payload(png: bytes, cfg: Config) -> dict:
|
|
return {"model": cfg.model, "temperature": cfg.temperature, "max_tokens": cfg.max_tokens,
|
|
"messages": [{"role": "user", "content": [
|
|
{"type": "image_url", "image_url": {"url": "data:image/png;base64," + base64.b64encode(png).decode()}},
|
|
{"type": "text", "text": cfg.prompt}]}]}
|
|
|
|
|
|
def complete(client: httpx.Client, body: dict, cfg: Config) -> dict:
|
|
"""One streamed chat completion: content (cut at a loop), looped, finish_reason, usage."""
|
|
parts: list[str] = []
|
|
size = checked = 0
|
|
finish, usage = None, None
|
|
req = {**body, "stream": True, "stream_options": {"include_usage": True}}
|
|
with client.stream("POST", "/v1/chat/completions", json=req) as resp:
|
|
if resp.status_code >= 400:
|
|
resp.read()
|
|
raise httpx.HTTPStatusError(f"{resp.status_code} {resp.text[:200]}", request=resp.request, response=resp)
|
|
for line in resp.iter_lines():
|
|
if not line.startswith("data: ") or line.strip() == "data: [DONE]":
|
|
continue
|
|
chunk = json.loads(line[6:])
|
|
usage = chunk.get("usage") or usage
|
|
choices = chunk.get("choices") or []
|
|
if not choices:
|
|
continue
|
|
finish = choices[0].get("finish_reason") or finish
|
|
delta = (choices[0].get("delta") or {}).get("content") or ""
|
|
parts.append(delta)
|
|
size += len(delta)
|
|
if size - checked >= cfg.loop_check_every:
|
|
checked = size
|
|
text = "".join(parts)
|
|
cut = loop_start(text, cfg)
|
|
if cut is not None:
|
|
return {"content": text[:cut], "looped": True, "finish_reason": "loop", "usage": usage}
|
|
return {"content": "".join(parts), "looped": False, "finish_reason": finish, "usage": usage}
|
|
|
|
|
|
def _retryable(exc: Exception) -> bool:
|
|
if isinstance(exc, httpx.HTTPStatusError):
|
|
return exc.response.status_code >= 500 or exc.response.status_code == 429
|
|
return isinstance(exc, (httpx.TransportError, json.JSONDecodeError))
|
|
|
|
|
|
def read_page(client: httpx.Client, png: bytes, cfg: Config) -> dict:
|
|
"""OCR one page image, retrying transport errors, 429 and 5xx. Never raises: a failure is a record."""
|
|
started = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
t0 = time.monotonic()
|
|
error = None
|
|
for attempt in range(1, cfg.retries + 2):
|
|
try:
|
|
answer = complete(client, payload(png, cfg), cfg)
|
|
return {"status": "ok", **answer, "seconds": round(time.monotonic() - t0, 2), "started_utc": started,
|
|
"attempts": attempt, "error": None}
|
|
except Exception as exc: # noqa: BLE001 - recorded, retried on a later run
|
|
error = f"{type(exc).__name__}: {str(exc)[:300]}"
|
|
if not _retryable(exc) or attempt > cfg.retries:
|
|
break
|
|
time.sleep(10 * attempt)
|
|
return {"status": "failed", "content": "", "looped": False, "finish_reason": None, "usage": None,
|
|
"seconds": round(time.monotonic() - t0, 2), "started_utc": started, "attempts": attempt, "error": error}
|
|
|
|
|
|
# --------------------------------------------------------------------------- documents and the page cache
|
|
|
|
def sha256_file(path: Path) -> str:
|
|
h = hashlib.sha256()
|
|
with open(path, "rb") as f:
|
|
for chunk in iter(lambda: f.read(1 << 22), b""):
|
|
h.update(chunk)
|
|
return h.hexdigest()
|
|
|
|
|
|
def cache_dir() -> Path:
|
|
return outputs_dir() / "ocr" / "pages"
|
|
|
|
|
|
def page_file(doc_sha256: str, page: int) -> Path:
|
|
return cache_dir() / doc_sha256[:16] / f"p{page:04d}.json"
|
|
|
|
|
|
def cached(doc_sha256: str, page: int, cfg: Config) -> dict | None:
|
|
"""The cached answer for a page if it was produced with the current settings (failed answers included)."""
|
|
f = page_file(doc_sha256, page)
|
|
if not f.is_file():
|
|
return None
|
|
rec = json.loads(f.read_text(encoding="utf-8"))
|
|
if rec.get("doc_sha256") != doc_sha256 or any(rec.get(k) != v for k, v in cfg.key().items()):
|
|
return None
|
|
return rec
|
|
|
|
|
|
def _write(rec: dict) -> None:
|
|
f = page_file(rec["doc_sha256"], rec["page"])
|
|
f.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = f.with_suffix(".tmp")
|
|
tmp.write_text(json.dumps(rec, ensure_ascii=False, indent=1), encoding="utf-8")
|
|
tmp.replace(f)
|
|
|
|
|
|
def image_bytes(doc, page) -> int:
|
|
"""Bytes of the images embedded in a page (vopec parse._image_bytes): a page above `max_page_image_mb` is a
|
|
log plot rendered as one big image and is skipped."""
|
|
try:
|
|
return sum(len(doc.extract_image(img[0]).get("image") or b"") for img in page.get_images(full=True))
|
|
except Exception: # noqa: BLE001 - a size hint only
|
|
return 0
|
|
|
|
|
|
@dataclass
|
|
class Task:
|
|
file: str # path relative to the Volve root, for the record
|
|
path: Path
|
|
doc_sha256: str
|
|
page: int # 1-based
|
|
n_pages: int
|
|
|
|
|
|
def tasks_for(pdfs: Iterable[Path], root: Path) -> list[Task]:
|
|
import pymupdf
|
|
|
|
out = []
|
|
for p in pdfs:
|
|
sha = sha256_file(p)
|
|
with pymupdf.open(p) as doc:
|
|
n = doc.page_count
|
|
out += [Task(str(p.relative_to(root)), p, sha, i, n) for i in range(1, n + 1)]
|
|
return out
|
|
|
|
|
|
def run(tasks: list[Task], cfg: Config, *, retry_failed: bool = True, progress_every: int = 25,
|
|
limit: int | None = None) -> dict:
|
|
"""OCR every task page not cached yet with the current settings. Pages are rendered in this thread (PyMuPDF
|
|
is not thread-safe) and at most 2 x workers requests are in flight. Returns counts by outcome."""
|
|
import pymupdf
|
|
|
|
todo = []
|
|
counts = {"cached": 0, "ok": 0, "failed": 0, "skipped": 0}
|
|
for t in tasks:
|
|
rec = cached(t.doc_sha256, t.page, cfg)
|
|
if rec is not None and (rec["status"] != "failed" or not retry_failed):
|
|
counts["cached"] += 1
|
|
else:
|
|
todo.append(t)
|
|
if limit is not None:
|
|
todo = todo[:limit]
|
|
print(f"[ocr] {len(tasks)} pages: {counts['cached']} cached, {len(todo)} to read with {cfg.workers} workers",
|
|
flush=True)
|
|
if not todo:
|
|
return counts
|
|
|
|
url = service_url()
|
|
t0 = time.monotonic()
|
|
done = streak = 0
|
|
pending: dict[Future, tuple[Task, dict]] = {}
|
|
|
|
def finish(fut: Future) -> None:
|
|
nonlocal done, streak
|
|
task, base = pending.pop(fut)
|
|
rec = {**base, **fut.result()}
|
|
_write(rec)
|
|
counts[rec["status"]] += 1
|
|
done += 1
|
|
streak = streak + 1 if rec["status"] == "failed" else 0
|
|
if rec["status"] == "failed":
|
|
print(f"[ocr] FAILED {task.file} p{task.page}: {rec['error']}", flush=True)
|
|
if done % progress_every == 0 or done == len(todo):
|
|
rate = (time.monotonic() - t0) / done
|
|
eta = rate * (len(todo) - done) / 60
|
|
print(f"[ocr] {done}/{len(todo)} pages, {rate:.1f} s/page wall, eta {eta:.0f} min,"
|
|
f" ok {counts['ok']} failed {counts['failed']} skipped {counts['skipped']}", flush=True)
|
|
|
|
with httpx.Client(base_url=url, timeout=cfg.timeout_s) as client, ThreadPoolExecutor(cfg.workers) as pool:
|
|
check_service(client, cfg)
|
|
open_doc = None
|
|
for t in todo:
|
|
if streak >= cfg.stop_after_failed:
|
|
print(f"[ocr] stopped: {streak} pages in a row failed; the other pages are left for the next run",
|
|
flush=True)
|
|
break
|
|
if open_doc is None or open_doc[0] != t.path:
|
|
if open_doc is not None:
|
|
open_doc[1].close()
|
|
open_doc = (t.path, pymupdf.open(t.path))
|
|
doc = open_doc[1]
|
|
page = doc[t.page - 1]
|
|
png = page.get_pixmap(dpi=cfg.dpi).tobytes("png")
|
|
base = {"doc_sha256": t.doc_sha256, "file": t.file, "page": t.page, "n_pages": t.n_pages,
|
|
**cfg.key(), "png_sha256": hashlib.sha256(png).hexdigest(), "png_bytes": len(png),
|
|
"image_bytes": image_bytes(doc, page)}
|
|
if base["image_bytes"] > cfg.max_page_image_mb * MEGABYTE:
|
|
rec = {**base, "status": "skipped", "content": "", "looped": False, "finish_reason": None,
|
|
"usage": None, "seconds": 0.0, "started_utc": None, "attempts": 0,
|
|
"error": f"embedded images {base['image_bytes'] / MEGABYTE:.1f} MB > {cfg.max_page_image_mb}"}
|
|
_write(rec)
|
|
counts["skipped"] += 1
|
|
done += 1
|
|
continue
|
|
while len(pending) >= 2 * cfg.workers:
|
|
finished, _ = wait(pending, return_when=FIRST_COMPLETED)
|
|
for fut in finished:
|
|
finish(fut)
|
|
pending[pool.submit(read_page, client, png, cfg)] = (t, base)
|
|
if open_doc is not None:
|
|
open_doc[1].close()
|
|
while pending:
|
|
finished, _ = wait(pending, return_when=FIRST_COMPLETED)
|
|
for fut in finished:
|
|
finish(fut)
|
|
return counts
|
|
|
|
|
|
def load_blocks(doc_sha256: str, n_pages: int, cfg: Config) -> tuple[list[Block], list[dict]]:
|
|
"""Blocks of a document from the cache, in page and reading order, and the page records (without content).
|
|
A page that is missing, failed or skipped contributes no blocks; its record says why."""
|
|
blocks: list[Block] = []
|
|
records = []
|
|
for page in range(1, n_pages + 1):
|
|
rec = cached(doc_sha256, page, cfg)
|
|
if rec is None:
|
|
records.append({"page": page, "status": "missing"})
|
|
continue
|
|
records.append({k: v for k, v in rec.items() if k != "content"})
|
|
if rec["status"] == "ok":
|
|
blocks += html_blocks(rec["content"], page)
|
|
return blocks, records
|
|
|
|
|
|
def block_dicts(blocks: list[Block]) -> list[dict]:
|
|
return [asdict(b) for b in blocks]
|
|
|
|
|
|
if __name__ == "__main__": # smoke test: python -m volve_dia.ocr some.pdf [page]
|
|
cfg = load_config()
|
|
pdf = Path(sys.argv[1]).resolve()
|
|
import pymupdf
|
|
|
|
with pymupdf.open(pdf) as d:
|
|
png = d[int(sys.argv[2]) - 1 if len(sys.argv) > 2 else 0].get_pixmap(dpi=cfg.dpi).tobytes("png")
|
|
with httpx.Client(base_url=service_url(), timeout=cfg.timeout_s) as c:
|
|
rec = read_page(c, png, cfg)
|
|
print(json.dumps({k: v for k, v in rec.items() if k != "content"}, indent=1))
|
|
for b in html_blocks(rec["content"], 1):
|
|
print(f"[{b.raw_label} -> {b.label}] {b.text[:100]!r}")
|