File size: 8,811 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import json
import math
import os
import pathlib
import struct
import subprocess
import sys
import shutil
import tempfile
from collections import defaultdict
from PIL import Image


root = pathlib.Path.cwd()
ARTIFACTS = ("ocr_results.json", "annotated_ocr.png", "ocr_report.md")


def clean_environment():
    env = os.environ.copy()
    for name in (
        "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
        "http_proxy", "https_proxy", "all_proxy", "no_proxy",
    ):
        env.pop(name, None)
    env["PYTHONHASHSEED"] = "0"
    return env


def run_candidate(work):
    for name in ARTIFACTS:
        (work / name).unlink(missing_ok=True)
    result = subprocess.run([sys.executable, "solve.py"], cwd=work, capture_output=True,
                            text=True, timeout=60, env=clean_environment())
    assert result.returncode == 0, f"candidate failed to annotate valid OCR metadata: {result.stderr}"
    for name in ARTIFACTS:
        assert (work / name).is_file(), f"candidate did not generate {name}"


def result_items(root):
    result = json.loads((root / "ocr_results.json").read_text(encoding="utf-8"))
    if isinstance(result, list):
        return result
    for key in ("texts", "results", "ocr_texts", "ocr_results", "items"):
        if isinstance(result.get(key), list):
            return result[key]
    raise AssertionError("ocr_results.json has no recognized-text list")


def item_text(item):
    return item.get("text", item.get("content", item.get("label")))


def rectangle(item):
    box = item.get("bbox", item.get("box"))
    assert isinstance(box, list) and len(box) in (4, 8), "each OCR item needs a rectangle or polygon"
    values = [float(value) for value in box]
    if len(values) == 4:
        return tuple(values)
    return min(values[0::2]), min(values[1::2]), max(values[0::2]), max(values[1::2])


def png_size(path: pathlib.Path):
    data = path.read_bytes()
    assert data[:8] == b"\x89PNG\r\n\x1a\n", "annotated_ocr.png is not PNG data"
    assert len(data) >= 24 and data[12:16] == b"IHDR", "annotated PNG is missing IHDR"
    return struct.unpack(">II", data[16:24])


def ppm_size(path: pathlib.Path):
    with path.open("rb") as handle:
        magic = handle.readline().strip()
        assert magic in (b"P3", b"P6"), "source fixture is not a supported PPM image"
        tokens = []
        while len(tokens) < 2:
            line = handle.readline()
            assert line, "source PPM is missing dimensions"
            line = line.split(b"#", 1)[0]
            tokens.extend(line.split())
    return int(tokens[0]), int(tokens[1])


def check_metadata(root) -> None:
    # ENHANCED_CASE_2: every recognized region is non-empty and lies on the supplied image.
    width, height = ppm_size(root / "general_ocr_002.ppm")
    for index, item in enumerate(result_items(root)):
        text = item_text(item)
        assert isinstance(text, str) and text.strip(), f"OCR item {index} has empty text"
        x1, y1, x2, y2 = rectangle(item)
        assert all(math.isfinite(value) for value in (x1, y1, x2, y2)), (
            f"OCR item {index} has a non-finite position"
        )
        assert 0 <= x1 < x2 <= width and 0 <= y1 < y2 <= height, (
            f"OCR item {index} position {(x1, y1, x2, y2)} is outside {width}x{height} source"
        )
    expected = json.loads((root / "expected_ocr.json").read_text(encoding="utf-8"))["texts"]
    actual = defaultdict(list)
    by_text = defaultdict(list)
    for item in result_items(root):
        actual[item_text(item).strip()].append(rectangle(item))
    for item in expected:
        by_text[item["text"].strip()].append(rectangle(item))
    assert actual.keys() == by_text.keys(), "OCR output changed the set of recognized strings"
    for text, boxes in by_text.items():
        assert len(boxes) == len(actual[text]), f"wrong region count for {text!r}"
        for want, got in zip(sorted(boxes), sorted(actual[text])):
            assert all(abs(a - b) <= 1 for a, b in zip(want, got)), (
                f"box moved away from upstream OCR position for {text!r}"
            )


def check_png_dimensions(root) -> None:
    # ENHANCED_CASE_3: annotation is a concrete PNG artifact matching source dimensions.
    width, height = png_size(root / "annotated_ocr.png")
    assert (width, height) == ppm_size(root / "general_ocr_002.ppm"), "annotated PNG geometry differs from source"


def check_annotation_pixels(root) -> None:
    # White-canvas substitution and no-op annotations must both fail.
    with Image.open(root / "general_ocr_002.ppm") as source_image:
        source = source_image.convert("RGB")
    with Image.open(root / "annotated_ocr.png") as annotation_image:
        annotated = annotation_image.convert("RGB")
    boxes = [rectangle(item) for item in result_items(root)]
    assert source.size == annotated.size
    changed_per_box = [0] * len(boxes)
    for y in range(source.height):
        for x in range(source.width):
            before = source.getpixel((x, y))
            after = annotated.getpixel((x, y))
            relevant = [index for index, (x1, y1, x2, y2) in enumerate(boxes)
                        if x1 - 1 <= x <= x2 + 1 and y1 - 1 <= y <= y2 + 1]
            if not relevant:
                assert before == after, f"original pixel changed outside annotations at {(x, y)}"
            elif before != after:
                for index in relevant:
                    changed_per_box[index] += 1
    assert all(count > 0 for count in changed_per_box), "at least one OCR box was not drawn"
    for box in boxes:
        x1, y1, x2, y2 = map(round, box)
        sides = [
            [(x, y1) for x in range(x1, min(x2 + 1, source.width))],
            [(x, min(y2, source.height - 1)) for x in range(x1, min(x2 + 1, source.width))],
            [(x1, y) for y in range(y1, min(y2 + 1, source.height))],
            [(min(x2, source.width - 1), y) for y in range(y1, min(y2 + 1, source.height))],
        ]
        for side in sides:
            covered = sum(any(source.getpixel((nx, ny)) != annotated.getpixel((nx, ny))
                              for nx in range(max(0, x - 1), min(source.width, x + 2))
                              for ny in range(max(0, y - 1), min(source.height, y + 2)))
                          for x, y in side)
            assert covered >= len(side) * 0.8, 'each annotation must visibly outline all four box sides, not just change one pixel'


def work_copy(parent):
    work = pathlib.Path(parent) / "candidate"
    shutil.copytree(root, work, ignore=shutil.ignore_patterns(
        "tests", "logs", "node_modules", "__pycache__", *ARTIFACTS))
    return work


def check_invalid_inputs():
    for invalid_image in (True, False):
        with tempfile.TemporaryDirectory(prefix="ocr-invalid-") as directory:
            work = work_copy(directory)
            if invalid_image:
                (work / "general_ocr_002.ppm").write_bytes(b"not an image")
            else:
                meta = work / "expected_ocr.json"
                metadata = json.loads(meta.read_text())
                metadata["texts"][0]["bbox"] = [-10, 0, 10, 10]
                meta.write_text(json.dumps(metadata))
            result = subprocess.run([sys.executable, "solve.py"], cwd=work, capture_output=True,
                                    text=True, timeout=30, env=clean_environment())
            assert result.returncode != 0 and (result.stdout + result.stderr).strip(), (
                "invalid input must fail with a diagnostic"
            )
            assert not (work / "annotated_ocr.png").exists(), (
                "invalid input must not be presented as a successful annotation"
            )


def check_changed_input():
    with tempfile.TemporaryDirectory(prefix="ocr-valid-") as directory:
        work = work_copy(directory)
        meta = work / "expected_ocr.json"
        metadata = json.loads(meta.read_text())
        # Duplicate text in distinct regions is legal. Move one box while
        # preserving its positive area and keep both region associations.
        first, second = metadata["texts"][:2]
        first["text"] = second["text"]
        first["bbox"] = [value + 2 for value in first["bbox"]]
        metadata["texts"].reverse()
        meta.write_text(json.dumps(metadata))
        run_candidate(work)
        assert json.loads(meta.read_text()) == metadata, "annotation must preserve upstream metadata"
        check_metadata(work)
        check_png_dimensions(work)
        check_annotation_pixels(work)


if __name__ == "__main__":
    check_metadata(root)
    check_png_dimensions(root)
    check_annotation_pixels(root)
    check_changed_input()
    check_invalid_inputs()
    print("OCR associations, changed input, four-sided annotations and failure paths passed")