| |
| |
| |
| |
| """Script to segment IMO shortlist md files using regex. |
| To run: |
| `python segment_script/segment.py` |
| To debug (or see covered use cases listed in fixtures/): |
| `pytest test_segment` |
| """ |
|
|
| from collections import defaultdict |
| import os |
| from pathlib import Path |
| import re |
| import pandas as pd |
| import json |
|
|
|
|
| section_re = re.compile(r"##\s+([A-Za-z]\w.*)") |
| problem_re = re.compile( |
| r"^(?:##\s*)?((?:[AGNC]\s*\d+))\.*\s*(.*?)(?:\((.*?)\))?$", re.MULTILINE |
| ) |
| solution_re = re.compile( |
| r"^(?:##\s*)?(Solution(?: \d+)?\.)\s*(.*?)(?=(?:Solution|Comment|A\d+|G\d+|N\d+|C\d+|##|$))", |
| re.MULTILINE | re.DOTALL, |
| ) |
|
|
|
|
| def add_content(section, label, text_class, text, problems, solutions): |
| text_str = " ".join(text).strip() |
| if text_class == "problem": |
| |
| problems.append({"section": section, "label": label, "problem": text_str}) |
| elif text_class == "solution": |
| |
| solutions.append({"label": label, "solution": text_str}) |
|
|
|
|
| def parse(file: Path): |
| content = file.read_text(encoding="utf-8") |
|
|
| problems, solutions = [], [] |
| current_section, current_label, current_class = None, None, None |
| current_lines = [] |
| for line in content.splitlines(): |
| if match := problem_re.match(line): |
| label, text, country = match.groups() |
| label = label.replace(" ", "") |
| add_content( |
| current_section, |
| current_label, |
| current_class, |
| current_lines, |
| problems, |
| solutions, |
| ) |
| current_class = "problem" |
| current_label = label |
| current_lines = [text] |
| elif match := solution_re.match(line): |
| label, text = match.groups() |
| add_content( |
| current_section, |
| current_label, |
| current_class, |
| current_lines, |
| problems, |
| solutions, |
| ) |
| current_class = "solution" |
| current_lines = [text] |
| elif match := section_re.match(line): |
| add_content( |
| current_section, |
| current_label, |
| current_class, |
| current_lines, |
| problems, |
| solutions, |
| ) |
| current_class = "section" |
| (text,) = match.groups() |
| current_section = text |
| else: |
| current_lines.append(line) |
| add_content( |
| current_section, |
| current_label, |
| current_class, |
| current_lines, |
| problems, |
| solutions, |
| ) |
| problems_df = pd.DataFrame(problems).drop_duplicates(subset=["label", "problem"]) |
| solutions_df = pd.DataFrame(solutions) |
| return problems_df, solutions_df |
|
|
|
|
| def join(problems_df, solutions_df): |
| pairs_df = problems_df.merge(solutions_df, on=["label"], how="left") |
| return pairs_df |
|
|
|
|
| def add_metadata(pairs_df, year, resource_path): |
| pairs_df.rename( |
| columns={"section": "problem_type", "label": "problem_label"}, inplace=True |
| ) |
| pairs_df["year"] = year |
| pairs_df["tier"] = "T0" |
| pairs_df["exam"] = ["IMO-SL"] * len(pairs_df) |
| pairs_df["metadata"] = [{"resource_path": resource_path}] * len(pairs_df) |
| return pairs_df[ |
| [ |
| "year", |
| "tier", |
| "problem_label", |
| "problem_type", |
| "exam", |
| "problem", |
| "solution", |
| "metadata", |
| ] |
| ] |
|
|
|
|
| def write_pairs(file_path, pairs_df): |
| pairs_df = pairs_df.replace({pd.NA: None, pd.NaT: None, float("nan"): None}) |
| pairs_dict = pairs_df.to_dict(orient="records") |
| output_text = "" |
| for pair in pairs_dict: |
| output_text += json.dumps(pair, ensure_ascii=False) + "\n" |
| file_path.write_text(output_text, encoding="utf-8") |
|
|
|
|
| if __name__ == "__main__": |
| project_root = Path(__file__).parent.parent.parent |
| compet_base_path = Path(__file__).resolve().parent.parent |
| compet_md_path = compet_base_path / "md" |
| seg_output_path = compet_base_path / "segmented" |
|
|
| for md_file in compet_md_path.glob("**/*.md"): |
| |
| if "compendium" not in md_file.name: |
| year = re.search(r"(\d{4})", md_file.name).group(1) |
| output_file = seg_output_path / md_file.relative_to( |
| compet_md_path |
| ).with_suffix(".jsonl") |
| output_file.parent.mkdir(parents=True, exist_ok=True) |
|
|
| print(md_file) |
| problems, solutions = parse(md_file) |
| pairs_df = join(problems, solutions) |
| pairs_df = add_metadata( |
| pairs_df, year, output_file.relative_to(project_root).as_posix() |
| ) |
| print(pairs_df) |
| write_pairs(output_file, pairs_df) |
|
|