olympiads-ref / JBMO /segment_script /segment_shortlist.py
LxYxvv's picture
Add data for JBMO (#13)
5b52f82 verified
raw
history blame
1.73 kB
import os
from pathlib import Path
import re
from tqdm import tqdm
import core
if __name__ == '__main__':
prob_re = re.compile(r"(?i)(?:\n|##* )(?:Problem )?((?:A|ALG|G|GEO|TN|N|NT|C|COM)\s*\d+)(.)?")
sol_re = re.compile(r"(?i)(?:\n|##* )(?:Solution(\s*\d+)?|Alternative solution)(.)?")
base_path = Path(__file__).resolve().parent.parent
md_path = base_path / "md" / "en-shortlist"
seg_output_path = base_path / "segmented" / "en-shortlist"
seg_output_path.mkdir(parents=True, exist_ok=True)
total = 0
for md_file in tqdm(md_path.glob("*.md")):
text = "\n" + md_file.read_text(encoding="utf-8")
prob_tags = [(tag, 0) for tag in prob_re.finditer(text)]
sol_tags = [(tag, 1) for tag in sol_re.finditer(text)]
tags = sorted(prob_tags + sol_tags, key=lambda x: x[0].start())
pairs = core.join_prob_sol(tags, text)
part_pairs = []
for problem, solution, prob_tag, sol_tag, prob_label in pairs:
sol_part_tags = list(sol_re.finditer(solution))
if len(sol_part_tags) > 1:
pos = [tag.start() for tag in sol_part_tags] + [len(solution)]
for start, end in zip(pos[:-1], pos[1:]):
part_pairs.append((problem.strip(), solution[start:end].strip(), prob_tag, sol_tag, prob_label))
else:
part_pairs.append((problem.strip(), solution.strip(), prob_tag, sol_tag, prob_label))
if part_pairs:
core.write_pairs(
seg_output_path / (md_file.stem + ".jsonl"),
part_pairs,
)
else:
print(md_file)
total += len(part_pairs)
print(f"total count: {total}")