Oprydning og opdeling i programfiler og datafiler - og datafiler i input og output.

This commit is contained in:
anders committed 2026-10-28 20:03:47 +01:00
1 parent 00697527f6
commit b859d67ac2
87 files changed
+22278 -61575

No files matched your search

+312
View File
@@ -0,0 +1,312 @@
#!/usr/bin/env python3
import argparse
import base64
import io
import json
import os
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
from PIL import Image
# ──────────────────────────────────────────────
# 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()
# ──────────────────────────────────────────────
# Filhåndtering
# ──────────────────────────────────────────────
input_path = Path(args.input)
if not input_path.is_file():
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")
# ──────────────────────────────────────────────
# Ollama-konfiguration
# ──────────────────────────────────────────────
OLLAMA_URL = os.getenv(
"OLLAMA_URL",
"http://localhost:11434/api/chat"
)
MODEL_NAME = os.getenv(
"OLLAMA_MODEL",
"hf.co/thelamapi/next-ocr-GGUF:Q4_K_M"
)
REQUEST_TIMEOUT = int(os.getenv("OLLAMA_TIMEOUT", "1800"))
# ──────────────────────────────────────────────
# 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."
)
# ──────────────────────────────────────────────
# Klargør billedet
# ──────────────────────────────────────────────
try:
with Image.open(input_path) as img:
img = img.convert("RGB")
buffer = io.BytesIO()
img.save(buffer, format="PNG")
image_b64 = base64.b64encode(
buffer.getvalue()
).decode("ascii")
except Exception as e:
print(
f"Fejl ved indlæsning af billedet: {e}",
file=sys.stderr
)
sys.exit(1)
# ──────────────────────────────────────────────
# Kør OCR via Ollama
# ──────────────────────────────────────────────
payload = {
"model": MODEL_NAME,
"messages": [
{
"role": "system",
"content": SYSTEM_PROMPT,
},
{
"role": "user",
"content": USER_PROMPT,
"images": [image_b64],
},
],
"stream": False,
"options": {
"temperature": 0,
"num_predict": 2048,
},
}
request = urllib.request.Request(
OLLAMA_URL,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
print(f"Input: {input_path}")
print(f"Model: {MODEL_NAME}")
print(f"Ollama: {OLLAMA_URL}")
print("Starter OCR ...", flush=True)
start_time = time.monotonic()
try:
with urllib.request.urlopen(
request,
timeout=REQUEST_TIMEOUT
) as response:
result = json.loads(
response.read().decode("utf-8")
)
raw_output = result["message"]["content"]
elapsed = time.monotonic() - start_time
print(f"OCR færdig efter {elapsed:.1f} sekunder.")
print(
f"Prompt tokens: {result.get('prompt_eval_count', 'ukendt')}"
)
print(
f"Output tokens: {result.get('eval_count', 'ukendt')}"
)
if result.get("eval_count") and result.get("eval_duration"):
tokens_per_second = (
result["eval_count"]
/ (result["eval_duration"] / 1e9)
)
print(f"Outputhastighed: {tokens_per_second:.2f} tokens/s")
except urllib.error.HTTPError as e:
error_body = e.read().decode("utf-8", errors="replace")
print(
f"Ollama returnerede HTTP-fejl {e.code}:\n{error_body}",
file=sys.stderr,
)
sys.exit(1)
except urllib.error.URLError as e:
print(
f"Kunne ikke kontakte Ollama: {e}",
file=sys.stderr,
)
print(
"Kontrollér, at Ollama kører, og at OLLAMA_URL er korrekt.",
file=sys.stderr,
)
sys.exit(1)
except TimeoutError:
print(
f"OCR overskred timeout på {REQUEST_TIMEOUT} sekunder.",
file=sys.stderr,
)
sys.exit(1)
except (KeyError, json.JSONDecodeError) as e:
print(
f"Uventet svar fra Ollama: {e}",
file=sys.stderr,
)
sys.exit(1)
# ──────────────────────────────────────────────
# Find JSON i modellens svar
# ──────────────────────────────────────────────
cleaned = raw_output.strip()
# Fjern eventuelle code fences.
if cleaned.startswith("```"):
lines = cleaned.splitlines()
if lines and lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
cleaned = "\n".join(lines).strip()
# Hvis modellen har tilføjet tekst før JSON, find første objekt.
start = cleaned.find("{")
if start != -1:
cleaned = cleaned[start:]
# ──────────────────────────────────────────────
# Valider og skriv JSON
# ──────────────────────────────────────────────
try:
parsed = json.loads(cleaned)
if not isinstance(parsed, dict):
raise ValueError("JSON-roden er ikke et objekt.")
if "elements" not in parsed or not isinstance(
parsed["elements"], list
):
raise ValueError(
"JSON mangler en gyldig 'elements'-liste."
)
with output_path.open("w", encoding="utf-8") as f:
json.dump(
parsed,
f,
ensure_ascii=False,
indent=2
)
print(f"JSON gemt i: {output_path}")
except json.JSONDecodeError as e:
print(f"Fejl: Modellens svar er ikke gyldig JSON: {e}", file=sys.stderr)
print("Modellens rå svar:", file=sys.stderr)
print(raw_output, file=sys.stderr)
sys.exit(1)
except ValueError as e:
print(f"Fejl ved validering af JSON: {e}", file=sys.stderr)
sys.exit(1)
except OSError as e:
print(f"Fejl ved skrivning af JSON-fil: {e}", file=sys.stderr)
sys.exit(1)