gaotiexinqu's picture
Upload folder using huggingface_hub
7f605ec verified
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'<span class="del">{a[i1:i2]}</span>')
elif tag == 'insert':
html_b.append(f'<span class="ins">{b[j1:j2]}</span>')
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"""
<div class="page" id="page-{i}" style="display: {'block' if i==0 else 'none'};">
<h2>样本 {i+1}/{len(data)}</h2>
<div class="block">
<h3>原文(text)</h3>
<div class="box">{html_text}</div>
</div>
<div class="block">
<h3>OCR 结果(ocr)</h3>
<div class="box">{html_ocr}</div>
</div>
</div>
""")
html_content = f"""
<html>
<head>
<meta charset="utf-8">
<title>OCR Diff Viewer</title>
<style>
body {{
font-family: "Courier New", monospace;
background-color: #f6f6f6;
padding: 20px;
}}
.block {{
margin-bottom: 30px;
}}
.box {{
background: #fff;
border: 1px solid #ccc;
padding: 15px;
white-space: pre-wrap;
font-size: 16px;
line-height: 1.5;
}}
.del {{ background-color: #ffcccc; }}
.ins {{ background-color: #ccffcc; }}
.nav {{
text-align: center;
margin-top: 30px;
}}
button {{
font-size: 16px;
padding: 6px 12px;
margin: 0 8px;
}}
</style>
</head>
<body>
<h1>📘 OCR 文本差异可视化</h1>
{"".join(html_items)}
<div class="nav">
<button onclick="prevPage()">上一条</button>
<button onclick="nextPage()">下一条</button>
<p id="page-indicator"></p>
</div>
<script>
let currentPage = 0;
const total = {len(data)};
const indicator = document.getElementById("page-indicator");
function showPage(i) {{
document.querySelectorAll('.page').forEach((el, idx) => {{
el.style.display = idx === i ? 'block' : 'none';
}});
indicator.innerText = `第 ${{i+1}} / ${{total}} 条`;
}}
function nextPage() {{
if (currentPage < total - 1) {{
currentPage++;
showPage(currentPage);
}}
}}
function prevPage() {{
if (currentPage > 0) {{
currentPage--;
showPage(currentPage);
}}
}}
showPage(currentPage);
</script>
</body>
</html>
"""
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")