DojiSum's picture
Publish the current 141-task UXInteract release
ef987bb verified
Raw History Blame Contribute Delete
2.2 kB
"""Validate the bundled OCR metadata and draw it over the actual PPM pixels."""
import json
from pathlib import Path
from PIL import Image, ImageDraw, UnidentifiedImageError
source_path = Path("general_ocr_002.ppm")
try:
with Image.open(source_path) as loaded:
loaded.verify()
with Image.open(source_path) as loaded:
image = loaded.convert("RGB")
except (OSError, UnidentifiedImageError) as exc:
raise SystemExit(f"invalid local source image: {exc}")
width, height = image.size
expected = json.loads(Path("expected_ocr.json").read_text(encoding="utf-8"))
assert isinstance(expected.get("texts"), list), "OCR metadata lacks texts"
items = []
for entry in expected["texts"]:
name = entry.get("text")
box = entry.get("bbox")
assert isinstance(name, str) and name.strip(), "OCR text must be nonempty"
assert isinstance(box, list) and len(box) == 4, "OCR bbox must be a rectangle"
x1, y1, x2, y2 = map(float, box)
assert 0 <= x1 < x2 <= width and 0 <= y1 < y2 <= height, "OCR bbox is outside the source image"
items.append({"text": name.strip(), "bbox": [x1, y1, x2, y2]})
Path("ocr_results.json").write_text(json.dumps({
"image": source_path.name, "format": "PPM", "width": width, "height": height,
"texts": items,
}, ensure_ascii=False, indent=2), encoding="utf-8")
draw = ImageDraw.Draw(image)
for item in items:
draw.rectangle(item["bbox"], outline=(255, 0, 0), width=1)
image.save("annotated_ocr.png", format="PNG")
Path("ocr_report.md").write_text(
"# OCR metadata postprocessing report\n\n"
f"- Source: local `{source_path.name}`, valid PPM image, {width}×{height} pixels.\n"
"- Text and boxes come from the supplied upstream `expected_ocr.json`; this task does not rerun OCR.\n"
f"- Valid text regions: {len(items)}; each nonempty text and in-bounds rectangle was checked.\n"
"- The original image pixels were preserved while red box outlines were drawn; output saved locally as `annotated_ocr.png`.\n"
"- Invalid/low-quality or unreadable images should produce a clear error rather than invented text; this program validates the PPM and stops on decoding errors.\n",
encoding="utf-8",
)