"""Text normalization and coverage aggregation following X-Omni.""" from collections import Counter from pathlib import Path import re LANGUAGES = ("EN", "ZH") LENGTHS = ("short", "medium", "long") ALLOWED = r"\u4e00-\u9fa5a-zA-Z0-9àâäéèêëîïôöùûüçÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ" def strip_instruction(text): lines = str(text).splitlines() if lines and lines[0].strip() == "A paper writes:": return "\n".join(lines[1:]).lstrip("\n") return str(text) def normalize(text, language): if language == "EN": cleaned = re.sub(f"[^{ALLOWED}\\s]", "", str(text)) return re.sub(r"\s+", " ", cleaned).strip().lower() if language == "ZH": return "".join(re.findall(f"[{ALLOWED}]", str(text))).strip() raise ValueError(f"Unknown language: {language}") def measure(target, recognized, language): gt = normalize(target, language) ocr = normalize(recognized, language) gt_units = gt.split() if language == "EN" else gt ocr_units = ocr.split() if language == "EN" else ocr if not gt_units: raise ValueError("Ground truth contains no scoring units") matched = sum((Counter(gt_units) & Counter(ocr_units)).values()) return {"ocr_gt": gt, "ocr_results": ocr, "match_word_count": matched, "gt_word_count": len(gt_units), "text_accuray": matched / len(gt_units)} def result_key(row): if "prompt_id" in row and "sample_index" in row: return int(row["prompt_id"]), int(row["sample_index"]) match = re.fullmatch(r"(\d+)_(\d+)", Path(row["image"]).stem) if not match: raise ValueError(f"Cannot identify OCR image: {row['image']}") return int(match[1]), int(match[2]) - 1 def summarize(results, metadata, *, n_samples=4, allow_missing=False): by_id = {int(item["prompt_id"]): item for item in metadata} expected = {(pid, sample) for pid in by_id for sample in range(n_samples)} rows, seen = [], set() for original in results: key = result_key(original) if key in seen: raise ValueError(f"duplicate OCR result: {key}") if key not in expected: raise ValueError(f"Unexpected OCR result: {key}") seen.add(key) item = by_id[key[0]] rows.append({**original, "prompt_id": key[0], "sample_index": key[1], "sample_id": item.get("sample_id"), "language": item["language"], "length": item["length"], "style": item.get("style"), **measure(strip_instruction(item["target_text"]), original["ocr_results"], item["language"])}) missing = sorted(expected - seen) if missing and not allow_missing: raise ValueError(f"missing OCR results: {len(missing)}; first: {missing[:5]}") def stats(selected, prompts): matched = sum(row["match_word_count"] for row in selected) gt = sum(row["gt_word_count"] for row in selected) return {"coverage": matched / gt if gt else None, "images": len(selected), "expected_images": prompts * n_samples, "matched_units": matched, "gt_units": gt} summary = {"protocol": "longlongtext-official-v1", "n_samples": n_samples, "prompts": len(metadata), "images": len(rows), "expected_images": len(expected), "complete": not missing, "missing": [{"prompt_id": pid, "sample_index": sample} for pid, sample in missing]} coverages = [] for language in LANGUAGES: selected = [row for row in rows if row["language"] == language] prompts = [item for item in metadata if item["language"] == language] groups = {length: stats([row for row in selected if row["length"] == length], sum(item["length"] == length for item in prompts)) for length in LENGTHS} values = [groups[length]["coverage"] for length in LENGTHS] summary[language.lower()] = {**stats(selected, len(prompts)), "by_length": groups, "mean3": sum(values) / 3 if all(v is not None for v in values) else None} coverages.extend(values) summary["macro_overall_mean6"] = (sum(coverages) / 6 if all(v is not None for v in coverages) else None) summary["total_coverage"] = stats(rows, len(metadata))["coverage"] summary["benchmark_scope"] = "full" if len(metadata) == 240 else "subset" return summary, rows