import json import os import random from tiny_shuffle import random_swap_contiguous # type: ignore file_path = "/vol/zhaoy/ds-ocr/data/CCI3-Data/data/part-00001-6f0afd98-d375-4d7f-8299-ac5e070bf4fc-c000.jsonl" save_path = f"/vol/zhaoy/ds-ocr/data/CCI3-Data/random_sample100/input.json" # 1. 读取 jsonl 文件 data = [] with open(file_path, "r", encoding="utf-8", errors="ignore") as f: for line in f: line = line.strip() if not line: continue try: data.append(json.loads(line)) except json.JSONDecodeError: continue print(f"✅ 已读取 {len(data)} 条样本") # 2. 筛选满足条件的样本 filtered = [ item for item in data if 100 <= item.get("meta_info", {}).get("words_count", 0) <= 10000 ] print(f"✅ 满足条件的样本数: {len(filtered)}") # 3. 随机抽取 500 条 filtered = random.sample(filtered, min(200, len(filtered))) # 4. 组织格式 processed = [] os.makedirs("images", exist_ok=True) for i, item in enumerate(filtered, 1): sample_id = f"RS{i:03d}" image_path = f"images/{sample_id}.png" content = item.get("text", "") or item.get("content", "") content = content.replace("\n", "").replace(" ", "") # 预处理的时候就把这些去掉 # tiny_shuffled_content, spans = random_swap_contiguous(content, n_swaps=1) # shuffled_content = ''.join(random.sample(content, len(content))) processed.append({ "id": sample_id, "data_source": "CCI3", "language": "zh", "image_path": image_path, "content": content, "length": len(content), # "tiny_shuffled_content": tiny_shuffled_content, # "spans": spans, # "shuffled_content": shuffled_content }) # 5. 保存为 JSON 文件 with open(save_path, "w", encoding="utf-8") as f: json.dump(processed, f, ensure_ascii=False, indent=2) print(f"✅ 已生成 {len(processed)} 条样本,保存至:{save_path}") # 6. 画 length 分布柱状图 import matplotlib.pyplot as plt from collections import Counter import numpy as np lengths = [p["length"] for p in processed] bin_width = 100 # 每 50 字一个柱 max_len = max(lengths) if lengths else 0 bins = list(range(0, max_len + bin_width, bin_width)) hist, edges = np.histogram(lengths, bins=bins) plt.figure(figsize=(10, 5)) plt.bar(edges[:-1], hist, width=bin_width, align="edge", color="skyblue", edgecolor="black") plt.xticks(edges[::2], rotation=45) plt.xlabel("Length (characters)") plt.ylabel("Count") plt.title("Random-Sample Length Distribution") plt.tight_layout() plt.savefig("/vol/zhaoy/ds-ocr/data/CCI3-Data/random_sample100/length_dist.png", dpi=300) print("✅ 柱状图已保存为 length_dist.png")