mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 12:24:28 +01:00
171 lines
7.5 KiB
Python
171 lines
7.5 KiB
Python
#!/usr/bin/env python3
|
|
"""What each model of the OCR lane is asked, and how what it answers becomes Mistral's page: its Markdown, its tables, its blocks.
|
|
|
|
A recipe reads its prompts from the model's own files where the model ships them (OvisOCR3's prompts/ folder, fetched with its
|
|
weights at their pinned revision), so that this repo holds none of them. Modes:
|
|
document the page in blocks, in reading order, each with its place, kind and content (tables in HTML, formulas in LaTeX), from
|
|
which the Markdown is assembled
|
|
markdown the page as one Markdown text
|
|
text the page's text alone
|
|
formula the page's formulas, in LaTeX
|
|
fields the values of named fields, as JSON
|
|
"""
|
|
import html
|
|
import json
|
|
import re
|
|
from pathlib import Path
|
|
|
|
# A block's kind, in the words of Mistral's API (OCRTextBlock and its kin), from the model's own category.
|
|
KIND = {"doc_title": "title", "paragraph_title": "title", "text": "text", "content": "text", "abstract": "text", "number": "text",
|
|
"reference_content": "references", "footnote": "text", "vision_footnote": "text", "vertical_text": "text",
|
|
"aside_text": "aside_text", "header": "header", "footer": "footer", "header_image": "image", "footer_image": "image",
|
|
"image": "image", "chart": "image", "seal": "image", "table": "table", "display_formula": "equation",
|
|
"inline_formula": "equation", "formula_number": "text", "figure_title": "caption", "algorithm": "code"}
|
|
|
|
|
|
class Recipe:
|
|
"""A model's prompts, its sampling, and what its answers mean."""
|
|
name = owner = ""
|
|
modes = ()
|
|
temperature = 0.0
|
|
max_tokens = 8192
|
|
|
|
def __init__(self, folder):
|
|
self.folder = Path(folder)
|
|
|
|
def prompt(self, mode, fields=None):
|
|
raise NotImplementedError
|
|
|
|
def request(self, served, image_url, mode, fields=None):
|
|
"""The body of /v1/chat/completions for one page."""
|
|
content = [{"type": "image_url", "image_url": {"url": image_url}}]
|
|
text = self.prompt(mode, fields)
|
|
if text:
|
|
content.append({"type": "text", "text": text})
|
|
return {"model": served, "messages": [{"role": "user", "content": content}], "temperature": self.temperature,
|
|
"max_tokens": self.max_tokens, "chat_template_kwargs": {"enable_thinking": False}}
|
|
|
|
def page(self, mode, answer, width, height):
|
|
"""(markdown, blocks, fields): what one page's answer says, blocks in pixels of the page as it was read."""
|
|
if mode == "fields":
|
|
return "", [], loose_json(answer)
|
|
return answer.strip(), [], None
|
|
|
|
|
|
class Ovis(Recipe):
|
|
"""ATH-MaaS's OvisOCR3 (0.8B, Apache-2.0), a Qwen3.5 0.8B: every mode, by the prompts of its repository."""
|
|
name, owner = "ovisocr3", "ATH-MaaS"
|
|
modes = ("document", "markdown", "text", "formula", "fields")
|
|
FILES = {"document": "document_structured", "markdown": "document_markdown", "text": "plain_ocr", "formula": "formula_recognition",
|
|
"fields": "kie_fields"}
|
|
|
|
def __init__(self, folder):
|
|
super().__init__(folder)
|
|
self.prompts = {m: (self.folder / "prompts" / f"{f}.txt").read_text(encoding="utf-8") for m, f in self.FILES.items()}
|
|
|
|
def prompt(self, mode, fields=None):
|
|
text = self.prompts[mode]
|
|
if mode == "fields":
|
|
text = text.replace("{keys_json}", json.dumps(list(fields or []), ensure_ascii=False))
|
|
return text
|
|
|
|
def page(self, mode, answer, width, height):
|
|
if mode != "document":
|
|
return super().page(mode, answer, width, height)
|
|
found = blocks_of(answer)
|
|
if not found: # no JSON at all: its text is what it read
|
|
return answer.strip(), [], None
|
|
out = []
|
|
for b in found:
|
|
box = b.get("bbox")
|
|
if not (isinstance(box, list) and len(box) == 4 and all(isinstance(v, (int, float)) for v in box)):
|
|
box = [0, 0, 0, 0]
|
|
x0, y0, x1, y1 = (max(0, min(999, v)) for v in box)
|
|
out.append({"type": KIND.get(str(b.get("category")), "text"), "category": str(b.get("category") or ""),
|
|
"top_left_x": round(x0 * width / 1000), "top_left_y": round(y0 * height / 1000),
|
|
"bottom_right_x": round(x1 * width / 1000), "bottom_right_y": round(y1 * height / 1000),
|
|
"content": str(b.get("content") or "")})
|
|
return markdown_of(out), out, None
|
|
|
|
|
|
class LightOn(Recipe):
|
|
"""LightOn's LightOnOCR-2 1B (Apache-2.0): a page in, its Markdown out, with no prompt; its card samples at 0.2."""
|
|
name, owner = "lightonocr-2", "lightonai"
|
|
modes = ("markdown",)
|
|
temperature = 0.2
|
|
|
|
def prompt(self, mode, fields=None):
|
|
return ""
|
|
|
|
|
|
RECIPES = {"ovis": Ovis, "lighton": LightOn}
|
|
|
|
|
|
def loose_json(text):
|
|
"""The JSON a model wrote, fenced or not; None when there is none."""
|
|
s = re.sub(r"^\s*```(?:json)?\s*|\s*```\s*$", "", text.strip())
|
|
try:
|
|
return json.loads(s)
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def blocks_of(text):
|
|
"""The blocks of a page as the model wrote them: a JSON array of objects. One cut short by the length of an answer, or with a
|
|
broken object among them, gives the objects that parse, in their order."""
|
|
whole = loose_json(text)
|
|
if isinstance(whole, list):
|
|
return [b for b in whole if isinstance(b, dict)]
|
|
if isinstance(whole, dict):
|
|
for key in ("blocks", "layout", "elements"):
|
|
if isinstance(whole.get(key), list):
|
|
return [b for b in whole[key] if isinstance(b, dict)]
|
|
return []
|
|
out = []
|
|
for m in re.finditer(r"\{(?:[^{}\"]|\"(?:\\.|[^\"\\])*\")*\}", text):
|
|
try:
|
|
b = json.loads(m.group(0))
|
|
except ValueError:
|
|
continue
|
|
if isinstance(b, dict) and ("bbox" in b or "category" in b):
|
|
out.append(b)
|
|
return out
|
|
|
|
|
|
def markdown_of(blocks):
|
|
"""A page's Markdown from its blocks: titles as headings, formulas between $$, tables as they came, pictures as Mistral's
|
|
placeholders; headers and footers kept, as Mistral's API does unless it is asked to set them apart."""
|
|
parts, n = [], 0
|
|
for b in blocks:
|
|
c, cat = b["content"].strip(), b["category"]
|
|
if b["type"] == "image":
|
|
parts.append(f"")
|
|
n += 1
|
|
continue
|
|
if not c:
|
|
continue
|
|
if cat == "doc_title" and not c.startswith("#"):
|
|
c = "# " + c
|
|
elif cat == "paragraph_title" and not c.startswith("#"):
|
|
c = "## " + c
|
|
elif b["type"] == "equation" and cat == "display_formula" and not c.startswith(("$$", "\\[")):
|
|
c = "$$\n" + c + "\n$$"
|
|
parts.append(c)
|
|
return "\n\n".join(parts)
|
|
|
|
|
|
def table_markdown(table_html):
|
|
"""An HTML table as a Markdown one, or None when it spans cells, which Markdown cannot say."""
|
|
if re.search(r"(?:row|col)span\s*=\s*[\"']?\s*(?:[2-9]|\d{2,})", table_html, re.I):
|
|
return None
|
|
rows = []
|
|
for tr in re.findall(r"<tr[^>]*>(.*?)</tr>", table_html, re.S | re.I):
|
|
cells = re.findall(r"<t[hd][^>]*>(.*?)</t[hd]>", tr, re.S | re.I)
|
|
rows.append([" ".join(html.unescape(re.sub(r"<[^>]+>", " ", x)).split()).replace("|", "\\|") for x in cells])
|
|
rows = [r for r in rows if r]
|
|
if not rows:
|
|
return None
|
|
width = max(map(len, rows))
|
|
rows = [r + [""] * (width - len(r)) for r in rows]
|
|
return "\n".join(["| " + " | ".join(rows[0]) + " |", "|" + " --- |" * width] + ["| " + " | ".join(r) + " |" for r in rows[1:]])
|