180 lines
6.9 KiB
Python
180 lines
6.9 KiB
Python
#!/usr/bin/env python3
|
|
import argparse
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
from PIL import Image
|
|
from transformers import AutoProcessor, AutoModelForMultimodalLM
|
|
import torch
|
|
|
|
# ──────────────────────────────────────────────
|
|
# Parameterhåndtering
|
|
# ──────────────────────────────────────────────
|
|
parser = argparse.ArgumentParser(
|
|
description="OCR: ekstrahér tekst og tabeller fra et billede til JSON."
|
|
)
|
|
parser.add_argument("input", help="Sti til inputbilledet (png, jpg, tiff mv.)")
|
|
parser.add_argument("output", nargs="?", default=None,
|
|
help="Sti til output-JSON-fil (valgfri). "
|
|
"Standard: input-filnavn med .json-endelse.")
|
|
args = parser.parse_args()
|
|
|
|
# Bestem output-filnavn
|
|
input_path = Path(args.input)
|
|
if not input_path.exists():
|
|
print(f"Fejl: Filen '{input_path}' findes ikke.", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
if args.output:
|
|
output_path = Path(args.output)
|
|
else:
|
|
output_path = input_path.with_suffix(".json")
|
|
|
|
# ──────────────────────────────────────────────
|
|
# Streng JSON-prompt
|
|
# ──────────────────────────────────────────────
|
|
SYSTEM_PROMPT = (
|
|
"You are a precise OCR engine. Extract ALL visible text and tables "
|
|
"from the provided image and return them as a single valid JSON object.\n\n"
|
|
|
|
"STRICT RULES — violating any of these is a failure:\n"
|
|
"1. Output ONLY a valid JSON object. No markdown, no code fences, no "
|
|
"explanations, no commentary, no trailing text.\n"
|
|
|
|
"2. The JSON must conform to this schema:\n"
|
|
' {"elements": ['
|
|
'{"type": "text", "content": "..."}, '
|
|
'{"type": "table", "headers": [...], "rows": [[...], ...]}'
|
|
']}\n'
|
|
" Each element must be either a text element or a table element, "
|
|
"using only the fields defined for that type.\n"
|
|
|
|
"3. Extract ALL visible text, including titles, headings, labels, "
|
|
"captions, footnotes, page headers, page footers, and text located "
|
|
"outside tables. Do not omit text merely because it is separate from "
|
|
"the main table or document structure.\n"
|
|
|
|
"4. Represent text outside tables as separate 'text' elements. "
|
|
"Preserve paragraph breaks as \\n within the content string.\n"
|
|
|
|
"5. If a page contains a heading followed by a table, represent the "
|
|
"heading as a text element and the table as a table element. "
|
|
"Do not absorb the heading into the table or omit it.\n"
|
|
|
|
"6. For table elements, 'headers' is an array of column-header strings; "
|
|
"'rows' is an array of arrays, one inner array per row, with each cell "
|
|
"represented as a string. Preserve the original row and column order.\n"
|
|
|
|
"7. Order all elements from top to bottom and left to right, following "
|
|
"their visual positions in the image.\n"
|
|
|
|
"8. Transcribe text verbatim. Do NOT invent, correct, paraphrase, "
|
|
"summarize, or silently omit visible text. Preserve the original "
|
|
"spelling, capitalization, numbers, and punctuation as accurately "
|
|
"as possible.\n"
|
|
|
|
"9. If part of a text region is unclear, transcribe the readable "
|
|
"parts rather than omitting the entire region. Do not guess at "
|
|
"unreadable characters.\n"
|
|
|
|
"10. If the image contains no extractable text or tables, output: "
|
|
'{"elements": []}\n'
|
|
|
|
"11. Do NOT wrap the JSON in any other structure."
|
|
)
|
|
|
|
USER_PROMPT = (
|
|
"Extract all visible text and tables from this image, including any "
|
|
"headings or labels outside the tables. Transcribe the content "
|
|
"verbatim and return only the JSON object defined in the system prompt."
|
|
)
|
|
|
|
# ──────────────────────────────────────────────
|
|
# Model-setup
|
|
# ──────────────────────────────────────────────
|
|
MODEL_ID = "Lamapi/next-ocr"
|
|
|
|
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
|
|
|
model = AutoModelForMultimodalLM.from_pretrained(
|
|
MODEL_ID,
|
|
dtype=torch.float16,
|
|
device_map="auto"
|
|
)
|
|
|
|
model.eval()
|
|
|
|
# ──────────────────────────────────────────────
|
|
# Kør OCR
|
|
# ──────────────────────────────────────────────
|
|
img = Image.open(input_path).convert("RGB")
|
|
|
|
messages = [
|
|
{"role": "system", "content": SYSTEM_PROMPT},
|
|
{
|
|
"role": "user",
|
|
"content": [
|
|
{"type": "image", "image": img},
|
|
{"type": "text", "text": USER_PROMPT},
|
|
],
|
|
},
|
|
]
|
|
|
|
prompt = processor.apply_chat_template(
|
|
messages, tokenize=False, add_generation_prompt=True
|
|
)
|
|
inputs = processor(
|
|
text=prompt, images=[img], return_tensors="pt"
|
|
).to(model.device)
|
|
|
|
with torch.no_grad():
|
|
generated = model.generate(**inputs, max_new_tokens=2048)
|
|
print("Input keys:", inputs.keys())
|
|
print("Input token count:", inputs["input_ids"].shape[1])
|
|
print("Generated shape:", generated.shape)
|
|
print("Input token IDs:", inputs["input_ids"][0, -10:].tolist())
|
|
print("Generated token IDs:", generated[0, -10:].tolist())
|
|
|
|
input_length = inputs["input_ids"].shape[1]
|
|
|
|
raw_output = processor.decode(
|
|
generated[0][input_length:],
|
|
skip_special_tokens=True
|
|
)
|
|
|
|
# Find begyndelsen på modellens JSON-svar.
|
|
start = raw_output.find('{\n "elements"')
|
|
|
|
if start != -1:
|
|
raw_output = raw_output[start:]
|
|
|
|
# ──────────────────────────────────────────────
|
|
# Valider og skriv JSON
|
|
# ──────────────────────────────────────────────
|
|
try:
|
|
# Fjern evt. code-fences, hvis modellen alligevel lægger til
|
|
cleaned = raw_output.strip()
|
|
if cleaned.startswith("```"):
|
|
cleaned = cleaned.split("\n", 1)[1]
|
|
if cleaned.endswith("```"):
|
|
cleaned = cleaned[:-3]
|
|
cleaned = cleaned.strip()
|
|
|
|
parsed = json.loads(cleaned)
|
|
|
|
with open(output_path, "w", encoding="utf-8") as f:
|
|
json.dump(parsed, f, ensure_ascii=False, indent=2)
|
|
|
|
print(f"✔ Resultat skrevet til: {output_path}")
|
|
except json.JSONDecodeError as e:
|
|
# Skriv rå output som fallback, så du kan debugge
|
|
fallback = output_path.with_suffix(".raw.txt")
|
|
with open(fallback, "w", encoding="utf-8") as f:
|
|
f.write(raw_output)
|
|
print(
|
|
f"✘ Modellen returnerede ugyldig JSON ({e}).\n"
|
|
f" Rå output er gemt som: {fallback}",
|
|
file=sys.stderr,
|
|
)
|
|
sys.exit(1)
|