import json import os import random import re from tiny_shuffle import random_swap_contiguous # type: ignore def shuffle_words_and_punct(text: str) -> str: """ 随机打乱英文文本中的单词和标点顺序。 保留标点作为独立token。 """ # 用正则提取单词和标点 tokens = re.findall(r"[A-Za-z0-9]+|[^\w\s]", text) if not tokens: return text shuffled = tokens[:] random.shuffle(shuffled) # 重新拼接成句子 # 逻辑:若下一个是标点,则不加空格;否则加空格 result = "" for i, tok in enumerate(shuffled): if i > 0 and not re.match(r"[^\w\s]", tok): # 不是标点才加空格 result += " " result += tok return result file_path = "/vol/zhaoy/ds-ocr/data/Stories_en/data/Children-Stories-0-Final.json" save_path = f"/vol/zhaoy/ds-ocr/data/Stories_en/sample200_len0.8-1.2k/input.json" # 1. 读取 jsonl 文件 with open(file_path, "r", encoding="utf-8") as f: data_o = json.load(f) new_data = [] i = 0 while i < len(data_o): # 若只剩最后一条,直接保存 if i == len(data_o) - 1: item = { "text": data_o[i]["text"], "text_token_length": len(data_o[i]["text"].split()) } new_data.append(item) break # 合并相邻两条 text1 = data_o[i]["text"].strip() text2 = data_o[i + 1]["text"].strip() merged_text = text1 + " " + text2 item = { "text": merged_text, "text_length": len(merged_text.split()) } new_data.append(item) i += 2 # 跳过两条 # 2. 筛选满足条件的样本 filtered = [ item for item in new_data if 800 <= item["text_length"] <= 1200 ] print(f"✅ 满足条件的样本数: {len(filtered)}") # 3. 随机抽取 x 条 sampled = random.sample(filtered, min(10, len(filtered))) # 4. 组织格式 processed = [] os.makedirs("images", exist_ok=True) for i, item in enumerate(sampled, 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", "") tiny_shuffled_content, spans = random_swap_contiguous(content, n_swaps=1) shuffled_content = shuffle_words_and_punct(content) processed.append({ "id": sample_id, "image_path": image_path, "content": 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}")