import json import difflib def highlight_diff(a, b): """生成红色高亮 HTML,红底=不同部分""" matcher = difflib.SequenceMatcher(None, a, b) html_a, html_b = [], [] for tag, i1, i2, j1, j2 in matcher.get_opcodes(): if tag == 'equal': html_a.append(a[i1:i2]) html_b.append(b[j1:j2]) elif tag == 'replace' or tag == 'delete': html_a.append(f'{a[i1:i2]}') elif tag == 'insert': html_b.append(f'{b[j1:j2]}') return ''.join(html_a), ''.join(html_b) def generate_html(data, output_path="ocr_diff_viewer.html"): """生成带翻页功能的HTML""" html_items = [] for i, item in enumerate(data): # 修改这里 text = item.get("tiny_shuffled_content", "") ocr = item.get("tiny_shuffled_content_ocr", "").replace("\n", "").replace(" ", "") html_text, html_ocr = highlight_diff(text, ocr) html_items.append(f"""

样本 {i+1}/{len(data)}

原文(text)

{html_text}

OCR 结果(ocr)

{html_ocr}
""") html_content = f""" OCR Diff Viewer

📘 OCR 文本差异可视化

{"".join(html_items)} """ with open(output_path, "w", encoding="utf-8") as f: f.write(html_content) print(f"✅ 可视化结果已保存到 {output_path}") if __name__ == "__main__": # 示例:加载 JSON 文件 input_path = "/vol/zhaoy/ds-ocr/data/CCI3-Data/sample10_len1.0-1.2k/merged_ocr.json" # 你自己的路径 with open(input_path, "r", encoding="utf-8") as f: data = json.load(f) generate_html(data, "ocr_diff_viewer.html")