#!/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. Your task is to extract ALL 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 exactly to this schema:\n" " {\n" ' "elements": [\n' ' {\n' ' "type": "text" | "table",\n' ' "content": "..." // when type is "text"\n' ' "headers": [...] // when type is "table"\n' ' "rows": [[...], ...] // when type is "table"\n' ' }\n' ' ]\n' " }\n" "3. For 'text' elements: preserve paragraph breaks as \\n within the string.\n" "4. For 'table' elements: 'headers' is an array of column-header strings; " "'rows' is an array of arrays, one inner array per row, each cell a string.\n" "5. Order elements top-to-bottom, left-to-right as they appear in the image.\n" "6. Do NOT invent, correct, or paraphrase text. Transcribe verbatim.\n" "7. If the image contains no extractable text or tables, output: " '{"elements": []}\n' "8. Do NOT wrap the JSON in any other structure." ) USER_PROMPT = ( "Extract all text and tables from this image.\n" "Return the result as a single JSON object matching the schema defined " "in the system prompt. Output only the JSON." ) # ────────────────────────────────────────────── # 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)