File size: 13,714 Bytes
efa0e35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#!/usr/bin/env python3
"""Export generation jobs and evaluate LongLongTextBench text coverage."""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys

from metrics import LANGUAGES, strip_instruction, summarize as aggregate

ROOT = Path(__file__).resolve().parent
DATA_DIR = ROOT.parent


def data_paths(data_dir=None):
    directory = Path(data_dir or DATA_DIR)
    return [directory / name for name in ("text_prompts.jsonl", "text_prompts_zh.jsonl")]


def data_hashes(data_dir=None):
    return {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in data_paths(data_dir)}


def read_jsonl(path):
    with Path(path).open(encoding="utf-8") as handle:
        return [json.loads(line) for line in handle if line.strip()]


def write_json(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def write_jsonl(path, rows):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows), encoding="utf-8")


def select_metadata(language="both", limit=0, data_dir=None):
    rows = [{**row, "language": row["language"].upper(),
             "render_text": row["prompt"], "target_text": row["gt_text"]}
            for path in data_paths(data_dir) for row in read_jsonl(path)]
    selected = []
    for lang in LANGUAGES if language == "both" else (language.upper(),):
        group = [row for row in rows if row["language"] == lang]
        selected.extend(group[:limit] if limit else group)
    return selected


def export(args):
    jobs = []
    for item in select_metadata(args.language, args.limit, args.data_dir):
        for sample in range(args.n_samples):
            pid = int(item["prompt_id"])
            jobs.append({"prompt_id": pid, "sample_id": item["sample_id"],
                         "sample_index": sample, "language": item["language"],
                         "style": item["style"], "length": item["length"],
                         "prompt": item["render_text"], "width": 1024, "height": 1024,
                         "seed": args.seed + pid * args.n_samples + sample,
                         "output_relpath": f"{pid:05d}/samples/{sample:05d}.png"})
    write_jsonl(args.output, jobs)
    print(json.dumps({"jobs": len(jobs), "output": str(Path(args.output).resolve())}))


def inspect_images(metadata, image_root, *, n_samples, image_manifest=None, data_dir=None):
    from PIL import Image
    image_root = Path(image_root).resolve()
    mapping = {}
    if image_manifest:
        valid_ids = {int(row["prompt_id"]) for row in select_metadata(data_dir=data_dir)}
        for row in read_jsonl(image_manifest):
            key = int(row["prompt_id"]), int(row["sample_index"])
            if key in mapping:
                raise ValueError(f"duplicate image mapping: {key}")
            if key[0] not in valid_ids or not 0 <= key[1] < n_samples:
                raise ValueError(f"Invalid image mapping: {key}")
            path = Path(row["image_path"])
            mapping[key] = path if path.is_absolute() else image_root / path
    report = {"expected_images": len(metadata) * n_samples, "found_images": 0,
              "missing": [], "invalid": [], "non_1024_images": 0, "sizes": {}}
    images = []
    for item in metadata:
        pid = int(item["prompt_id"])
        for sample in range(n_samples):
            path = (mapping.get((pid, sample)) if image_manifest else
                    image_root / f"{pid:05d}/samples/{sample:05d}.png")
            if path is None or not path.is_file():
                report["missing"].append({"prompt_id": pid, "sample_index": sample})
                continue
            try:
                with Image.open(path) as image:
                    image.load()
                    size = image.size
                report["non_1024_images"] += size != (1024, 1024)
                name = f"{size[0]}x{size[1]}"
                report["sizes"][name] = report["sizes"].get(name, 0) + 1
                images.append((item, sample, path))
            except (OSError, ValueError) as exc:
                report["invalid"].append({"path": str(path), "error": str(exc)})
    report["found_images"] = len(images)
    return images, report


def checked_images(args):
    metadata = select_metadata(args.language, args.limit, args.data_dir)
    images, report = inspect_images(metadata, args.images, n_samples=args.n_samples,
                                    image_manifest=args.image_manifest, data_dir=args.data_dir)
    if report["invalid"] or (report["missing"] and not args.allow_missing):
        raise ValueError("Image preflight failed: " + json.dumps(report, ensure_ascii=False))
    if not images:
        raise ValueError("No valid images found")
    return metadata, images, report


def check(args):
    _, report = inspect_images(select_metadata(args.language, args.limit, args.data_dir), args.images,
                               n_samples=args.n_samples, image_manifest=args.image_manifest, data_dir=args.data_dir)
    if args.output:
        write_json(args.output, report)
    print(json.dumps(report, ensure_ascii=False, indent=2))
    if report["invalid"] or (report["missing"] and not args.allow_missing) or not report["found_images"]:
        raise ValueError("Image preflight failed; see the report above")


def save_scores(output, results, metadata, args):
    summary, rows = aggregate(results, metadata, n_samples=args.n_samples,
                              allow_missing=args.allow_missing)
    for language in LANGUAGES:
        if not any(item["language"] == language for item in metadata):
            continue
        directory = output / language.lower()
        directory.mkdir(parents=True, exist_ok=True)
        write_jsonl(directory / "results.jsonl", [row for row in rows if row["language"] == language])
        coverage = summary[language.lower()]["coverage"]
        (directory / "scores.txt").write_text(
            f"Text Score: {coverage:.4f}\n" if coverage is not None else "Text Score: unavailable\n")
    write_json(output / "summary.json", summary)
    print(json.dumps(summary, ensure_ascii=False, indent=2))
    return summary


def fresh_output(path):
    output = Path(path).resolve()
    if output.exists() and (not output.is_dir() or any(output.iterdir())):
        raise ValueError(f"Output must be a new or empty directory: {output}")
    output.mkdir(parents=True, exist_ok=True)
    return output


def score(args):
    from PIL import Image
    model = Path(args.ocr_model).resolve()
    if not (model / "config.json").is_file():
        raise ValueError(f"--ocr-model must point to a local HF checkpoint with config.json: {model}")
    metadata, images, report = checked_images(args)
    output = fresh_output(args.output)
    env = os.environ.copy()
    env.update({"LONGTEXT_QWEN_MODEL_PATH": str(model),
                "LONGTEXT_MAX_NEW_TOKENS": "4096", "HF_HUB_OFFLINE": "1",
                "TRANSFORMERS_OFFLINE": "1", "TOKENIZERS_PARALLELISM": "false"})
    write_json(output / "run_config.json", {
        "created_utc": datetime.now(timezone.utc).isoformat(),
        "data_sha256": data_hashes(args.data_dir),
        "ocr_model": str(model), "ocr_max_new_tokens": 4096, "requested_workers": args.workers,
        "n_samples": args.n_samples, "language": args.language, "limit_per_language": args.limit,
        "allow_missing": args.allow_missing, "image_root": str(Path(args.images).resolve()),
        "image_manifest": str(Path(args.image_manifest).resolve()) if args.image_manifest else None,
        "image_preflight": report, "ocr_input_size": [1024, 1024], "resize": "LANCZOS"})
    results = []
    image_records = []
    for language in LANGUAGES:
        selected = [image for image in images if image[0]["language"] == language]
        if not selected:
            continue
        directory = output / language.lower()
        samples = directory / "samples"
        samples.mkdir(parents=True)
        for item, sample, source in selected:
            target = samples / f"{int(item['prompt_id'])}_{sample + 1}.png"
            with Image.open(source) as image:
                size = image.size
                if size == (1024, 1024) and source.suffix.lower() == ".png":
                    shutil.copyfile(source, target)
                else:
                    image.convert("RGB").resize((1024, 1024), Image.Resampling.LANCZOS).save(target)
            image_records.append({"prompt_id": int(item["prompt_id"]), "sample_index": sample,
                                  "source": str(source.resolve()), "source_size": list(size),
                                  "ocr_image": str(target.relative_to(output))})
        prompt_file = directory / "prompt_file.jsonl"
        write_jsonl(prompt_file, [{"prompt_id": int(item["prompt_id"]), "prompt": "A paper writes:",
                                  "target_text": strip_instruction(item["target_text"]),
                                  "text": strip_instruction(item["target_text"]).splitlines()}
                                 for item in metadata if item["language"] == language])
        workers = min(args.workers, len(selected))
        command = [sys.executable, "-m", "torch.distributed.run", "--standalone",
                   f"--nproc_per_node={workers}", str(ROOT / "vendor/textbench/evaluate_text_reward.py"),
                   "--sample_dir", str(samples), "--output_dir", str(directory),
                   "--mode", language.lower(), "--prompt_file", str(prompt_file)]
        print(f"OCR {language}: {len(selected)} images, {workers} workers", flush=True)
        subprocess.run(command, cwd=str(ROOT), env=env, check=True)
        language_results = []
        for rank in range(workers):
            language_results.extend(read_jsonl(directory / f"results_chunk{rank}.jsonl"))
        expected_keys = {(int(item["prompt_id"]), sample) for item, sample, _ in selected}
        from metrics import result_key
        actual_keys = [result_key(row) for row in language_results]
        if set(actual_keys) != expected_keys or len(actual_keys) != len(expected_keys):
            raise ValueError(f"OCR results do not cover the staged {language} images exactly")
        results.extend(language_results)
    write_jsonl(output / "image_manifest.jsonl", image_records)
    save_scores(output, results, metadata, args)


def summarize(args):
    result_dir = Path(args.results).resolve()
    metadata = select_metadata(args.language, args.limit, args.data_dir)
    rows = []
    for language in LANGUAGES if args.language == "both" else (args.language.upper(),):
        file = result_dir / language.lower() / "results.jsonl"
        if file.is_file():
            rows.extend(read_jsonl(file))
    if not rows:
        raise ValueError("No en/results.jsonl or zh/results.jsonl found")
    output = fresh_output(args.output)
    save_scores(output, rows, metadata, args)
    write_json(output / "run_config.json", {"mode": "reuse_ocr", "source": str(result_dir),
               "data_sha256": data_hashes(args.data_dir),
               "n_samples": args.n_samples, "language": args.language,
               "limit_per_language": args.limit, "allow_missing": args.allow_missing})


def positive(value):
    number = int(value)
    if number < 1:
        raise argparse.ArgumentTypeError("must be >= 1")
    return number


def nonnegative(value):
    number = int(value)
    if number < 0:
        raise argparse.ArgumentTypeError("must be >= 0")
    return number


def parser():
    cli = argparse.ArgumentParser(description=__doc__)
    cli.add_argument("--data-dir", type=Path, default=DATA_DIR,
                     help="directory containing text_prompts.jsonl and text_prompts_zh.jsonl (default: repository root)")
    commands = cli.add_subparsers(dest="command", required=True)
    for name, handler in (("export", export), ("check", check), ("score", score), ("summarize", summarize)):
        cmd = commands.add_parser(name)
        cmd.add_argument("--data-dir", type=Path, default=argparse.SUPPRESS)
        cmd.set_defaults(handler=handler)
        cmd.add_argument("--language", choices=("both", "en", "zh"), default="both")
        cmd.add_argument("--limit", type=nonnegative, default=0, help="first N prompts per language; 0 = all")
        cmd.add_argument("--n-samples", type=positive, default=4)
        cmd.add_argument("--output", required=name != "check")
        if name == "export":
            cmd.add_argument("--seed", type=int, default=42)
        else:
            cmd.add_argument("--allow-missing", action="store_true")
        if name in ("check", "score"):
            cmd.add_argument("--images", required=True)
            cmd.add_argument("--image-manifest", help="JSONL: prompt_id, sample_index (0-based), image_path")
        if name == "score":
            cmd.add_argument("--ocr-model", required=True, help="local Qwen2.5-VL-7B-Instruct HF directory")
            cmd.add_argument("--workers", type=positive, default=1)
        if name == "summarize":
            cmd.add_argument("--results", required=True, help="directory containing en/zh/results.jsonl")
    return cli


def main():
    args = parser().parse_args()
    try:
        args.handler(args)
    except (ValueError, OSError, ImportError, subprocess.CalledProcessError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())