import json import os import random from tiny_shuffle import random_swap_contiguous # type: ignore from collections import defaultdict # <--- 导入 defaultdict 用于分桶 import matplotlib.pyplot as plt from collections import Counter import numpy as np # --- 路径定义 --- base_dir = "/vol/zhaoy/ds-ocr/data/CCI3-Data/CCI3_5k-10k_sample100_interval500_per10" file_path = "/vol/zhaoy/ds-ocr/data/CCI3-Data/data/part-00001-6f0afd98-d375-4d7f-8299-ac5e070bf4fc-c000.jsonl" save_path = f"{base_dir}/meta.json" plot_save_path = f"{base_dir}/length_dist.png" image_save_dir = f"/images" # 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. (***修改***) 筛选满足条件的样本 # 不再使用 meta_info, 而是直接计算真实长度来进行筛选 print("🚀 开始按 'content' 真实字符长度进行预筛选...") filtered_by_char_length = [] for item in data: # 使用与步骤 3 中完全一致的 content 清洗逻辑 content = item.get("text", "") or item.get("content", "") content = content.replace("\n", "").replace(" ", "") length = len(content) # 在这里进行你想要的真实长度过滤 (例如,你希望过滤掉超过 10000 个字符的) # 注意:如果你这里设置了 10000,你就永远不会得到 [24500 - 24999] 的桶 # 假设你真正的意思是 100 到 100000 if 5000 <= length <= 10000: # <--- 在这里设置你想要的真实字符长度范围 # 将计算好的 length 存储起来,避免第 3 步重复计算 item['_true_length'] = length filtered_by_char_length.append(item) print(f"✅ 满足 '真实字符长度' 条件的样本数: {len(filtered_by_char_length)}") # 3. (***修改***) 按 'content' 字符长度进行平衡采样 print("🚀 开始按 'content' 字符长度进行平衡采样...") bin_size = 500 # 采样间隔 (每 500 个字符一个区间) samples_per_bin = 10 # 每个区间抽 10 条 # 3.1. 分桶 binned_data = defaultdict(list) # 注意:这里要遍历上一步筛选过的 filtered_by_char_length for item in filtered_by_char_length: # 直接使用上一步计算好的长度 length = item['_true_length'] # 计算所属的桶 (bin) bin_key = length // bin_size binned_data[bin_key].append(item) # 3.2. 从每个桶中采样 balanced_samples = [] print(f" -> 采样间隔: {bin_size} 字符, 每个区间最多: {samples_per_bin} 条") for bin_key in sorted(binned_data.keys()): items_in_bin = binned_data[bin_key] n_to_sample = min(samples_per_bin, len(items_in_bin)) sampled_items = random.sample(items_in_bin, n_to_sample) balanced_samples.extend(sampled_items) min_len = bin_key * bin_size max_len = (bin_key + 1) * bin_size - 1 print(f" -> 区间 [{min_len:>5d} - {max_len:>5d}]: 找到 {len(items_in_bin):>4} 条, 抽取 {n_to_sample} 条") # 3.3. 替换原来的 'filtered' 变量 filtered = balanced_samples print(f"✅ 平衡采样后总样本数: {len(filtered)}") # 4. 组织格式 (***修改***) processed = [] os.makedirs(image_save_dir, exist_ok=True) for i, item in enumerate(filtered, 1): sample_id = f"RS{i:03d}" image_path = f"{image_save_dir}/{sample_id}.png" # 再次清理(或者直接使用上一步的清理结果,但为保险起见,再次清理也无妨) content = item.get("text", "") or item.get("content", "") content = content.replace("\n", "").replace(" ", "") processed.append({ "id": sample_id, "data_source": "CCI3", "language": "zh", "image_path": image_path, "content": content, "length": item['_true_length'], # <--- 直接使用缓存的长度 }) # 5. 保存为 JSON 文件 (不变) os.makedirs(os.path.dirname(save_path), exist_ok=True) 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 分布柱状图 (基本不变) lengths = [p["length"] for p in processed] if not lengths: print("⚠️ 采样结果为空,无法绘制柱状图。") else: # 注意:这里的 bin_width 是绘图的柱宽,可以和采样的 bin_size (500) 不一样 # 使用 100 作为柱宽,可以更精细地看清分布 bin_width = bin_size max_len = max(lengths) 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") # 动态调整 x 轴刻度,避免过于密集 tick_step = max(1, len(edges) // 20) # 保持最多约 20 个刻度 plt.xticks(edges[::tick_step], rotation=45) plt.xlabel("Length (characters)") plt.ylabel("Count") plt.title(f"Balanced-Sample Length Distribution (Total: {len(lengths)})") plt.tight_layout() plt.savefig(plot_save_path, dpi=300) # 使用变量 print(f"✅ 柱状图已保存为 {plot_save_path}")