| from pathlib import Path |
| import re |
|
|
| from tqdm import tqdm |
| import core |
|
|
|
|
| if __name__ == "__main__": |
| prob_re = re.compile(r"(?i)(?:\n|##* )(?:Problem (\d+)|№(\d+)\.|(\d+)\.)(.)?") |
| sol_re = re.compile( |
| r"(?i)(?:\n|##* )(?:Solution|Alternative solution[:\.]|Solution I*[\.:]|Sol[:\.]|Solution \d+)(.)?" |
| ) |
|
|
| base_path = Path(__file__).resolve().parent.parent |
| md_path = base_path / "md" / "en-official" |
| seg_output_path = base_path / "segmented" / "en-official" |
| seg_output_path.mkdir(parents=True, exist_ok=True) |
|
|
| problem_count = 0 |
| solution_count = 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) |
| |
| problem_count += len(prob_tags) |
| solution_count += len(part_pairs) |
|
|
| print(f"problem count: {problem_count}, solution count: {solution_count}") |
|
|