|
|
import json |
|
|
import os |
|
|
import random |
|
|
import re |
|
|
from tiny_shuffle import random_swap_contiguous |
|
|
|
|
|
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" |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
filtered = [ |
|
|
item for item in new_data |
|
|
if 800 <= item["text_length"] <= 1200 |
|
|
] |
|
|
print(f"✅ 满足条件的样本数: {len(filtered)}") |
|
|
|
|
|
|
|
|
sampled = random.sample(filtered, min(10, len(filtered))) |
|
|
|
|
|
|
|
|
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 |
|
|
}) |
|
|
|
|
|
|
|
|
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}") |
|
|
|