File size: 9,490 Bytes
dc247f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run Florian's document-level continuity metrics on a downloaded OCR handoff.

Original references and OCR records are read-only. This preserves raw markup and
partial text; it does not implement the strict visible-page evaluation panel.
"""

from __future__ import annotations

import argparse
import importlib.util
import json
from collections import Counter, defaultdict
from pathlib import Path


def read_rows(path: Path):
    with path.open(encoding="utf-8") as stream:
        for line in stream:
            if line.strip():
                yield json.loads(line)


def read_selection(run: Path, method: str) -> dict[str, list[int]]:
    config = json.loads((run / "run-config.json").read_text(encoding="utf-8"))
    if method not in {value["id"] for value in config["methods"]}:
        raise ValueError(f"Method {method!r} is absent from {run}/run-config.json")
    pages = defaultdict(list)
    for row in read_rows(run / "pages.jsonl"):
        document, number = row["document_id"], row["page_number"]
        if not isinstance(document, str) or not document or any(c in document for c in "/\\\0"):
            raise ValueError("Invalid document ID in the saved selection")
        if document in {".", ".."} or type(number) is not int or number < 1:
            raise ValueError("Invalid physical page number or document ID")
        if number in pages[document]:
            raise ValueError(f"Duplicate selected page: {document}/{number}")
        pages[document].append(number)
    if not pages:
        raise ValueError("The saved selection is empty")
    return {document: sorted(numbers) for document, numbers in pages.items()}


def document_prediction(run: Path, method: str, document: str,
                        numbers: list[int]) -> tuple[str, Counter, bool]:
    texts, counts, complete = [], Counter(), True
    for number in numbers:
        folder = run / method / document / f"page-{number:04d}"
        result_path, text_path = folder / "result.json", folder / "transcription.md"
        if not result_path.exists():
            counts["missing_result"] += 1
            complete = False
            text = text_path.read_bytes().decode("utf-8") if text_path.exists() else ""
        else:
            record = json.loads(result_path.read_text(encoding="utf-8"))
            if (record["page"]["document_id"], record["page"]["page_number"]) != (document, number):
                raise ValueError(f"Page identity disagrees with selection: {result_path}")
            text = record.get("markdown")
            if text is not None and not isinstance(text, str):
                raise ValueError(f"Invalid nullable transcription: {result_path}")
            counts[record["outcome"]] += 1
            complete = complete and record.get("status") == "success"
            if text_path.exists():
                if text_path.read_bytes() != (text or "").encode("utf-8"):
                    raise ValueError(f"Consumer text disagrees with saved result: {text_path}")
            else:
                counts["missing_transcription_file"] += 1
                complete = False
            if text is None:
                counts["unavailable_text"] += 1
            text = text or ""
        texts.append(text)
    counts["complete_documents" if complete else "incomplete_documents"] += 1
    return "\n\n".join(texts) if any(texts) else "", counts, complete


def evaluate(bundle: Path, output: Path, methods: list[str], evaluator: Path) -> dict:
    bundle, output = bundle.resolve(), output.resolve()
    if output == bundle or output.is_relative_to(bundle):
        raise ValueError("Evaluation output must be outside the read-only bundle")
    selected = {}
    for value in methods:
        parts = value.split("/")
        if len(parts) != 2 or any(not p or p in {".", ".."} or "\\" in p for p in parts):
            raise ValueError("Each --method must be RUN/METHOD")
        run_name, method = parts
        if method in selected:
            raise ValueError("Prediction method names must be distinct")
        run = bundle / "runs" / run_name
        selected[method] = (run, read_selection(run, method))
    if not selected:
        raise ValueError("Select at least one method")
    selection = next(iter(selected.values()))[1]
    if any(pages != selection for _, pages in selected.values()):
        raise ValueError("Methods have different saved document/page selections")
    spec = importlib.util.spec_from_file_location("florian_evaluate", evaluator)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    output.mkdir(parents=True, exist_ok=False)
    counts = defaultdict(Counter)
    weighted, per_language, seen = defaultdict(Counter), {}, set()
    total_characters = 0
    for source in sorted((bundle / "inputs").glob("*/data.json")):
        language = source.parent.name
        folder = output / language
        folder.mkdir()
        documents, characters = 0, 0
        with (folder / "data.json").open("w", encoding="utf-8") as destination:
            for reference in read_rows(source):
                document = f"{language}--{reference['id'].removeprefix('<urn:uuid:').removesuffix('>')}"
                if document not in selection:
                    continue
                if document in seen:
                    raise ValueError(f"Duplicate reference document: {document}")
                seen.add(document)
                if not isinstance(reference["text"], str):
                    raise ValueError(f"Reference text is not a string: {document}")
                row = {"id": reference["id"], "text": reference["text"]}
                prediction = reference.get("docling_prediction")
                if prediction is not None and not isinstance(prediction, str):
                    raise ValueError(f"Invalid Docling prediction: {document}")
                row["docling_prediction"] = prediction if prediction is not None else ""
                counts["docling"]["unavailable_documents" if prediction is None else "observed_documents"] += 1
                for method, (run, pages) in selected.items():
                    prediction, page_counts, _ = document_prediction(run, method, document, pages[document])
                    row[f"{method}_prediction"] = prediction
                    counts[method].update(page_counts)
                destination.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + "\n")
                documents += 1
                characters += len(reference["text"])
        if not documents:
            (folder / "data.json").unlink()
            folder.rmdir()
            continue
        if not characters:
            raise ValueError(f"No reference characters for language {language}")
        dataframe, tools = module.evaluate_folder(folder / "data.json")
        dataframe.write_ndjson(folder / "data.json")
        module.write_metrics_yaml(dataframe, tools, folder / "metrics.yaml")
        import yaml
        metrics = yaml.safe_load((folder / "metrics.yaml").read_text(encoding="utf-8"))
        for method, values in metrics.items():
            for name, score in values.items():
                weighted[method][name] += score * characters
        per_language[language] = {"documents": documents, "reference_characters": characters,
                                  "metrics": metrics}
        total_characters += characters
        print(json.dumps({"language": language, "documents": documents, "metrics": metrics}), flush=True)
    if seen != set(selection):
        raise ValueError(f"Missing references for {len(set(selection) - seen)} selected documents")
    if not total_characters:
        raise ValueError("No nonempty reference text was selected")
    summary = {"metrics": {method: {name: value / total_characters for name, value in values.items()}
                           for method, values in weighted.items()},
               "counts": {method: dict(values) for method, values in counts.items()},
               "selected_documents": len(selection), "selected_pages": sum(map(len, selection.values())),
               "reference_characters": total_characters, "per_language": per_language,
               "policy": "Raw page transcriptions joined in physical page order with two newlines. Partial and failed outputs retained; unavailable text contributes an explicitly counted empty hypothesis. Florian's NFC/case-folded document metrics, reference-character weighted. FinePDFs continuity diagnostics, not certified page-level ground truth."}
    (output / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")
    return summary


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--bundle", type=Path, required=True, help="Extracted directory containing inputs/ and runs/")
    parser.add_argument("--output", type=Path, required=True, help="Fresh results directory outside the bundle")
    parser.add_argument("--method", action="append", required=True, help="RUN/METHOD; repeat for comparisons")
    parser.add_argument("--evaluator", type=Path, default=Path(__file__).with_name("florian_evaluate.py"))
    args = parser.parse_args()
    summary = evaluate(args.bundle, args.output, args.method, args.evaluator)
    print(json.dumps({key: value for key, value in summary.items() if key != "per_language"}, ensure_ascii=False))


if __name__ == "__main__":
    main()