File size: 5,157 Bytes
eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 eebb93b 139f968 59ed96b 139f968 0d95119 139f968 72f5d73 139f968 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
# -----------------------------------------------------------------------------
# Author: Marina
# Date: 2024-11-15
# -----------------------------------------------------------------------------
"""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":
# print(f"ADD PROBLEM {section} {label} ")
problems.append({"section": section, "label": label, "problem": text_str})
elif text_class == "solution":
# print(f"ADD SOLUTION {section} {label}")
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(" ", "") # clean the label
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" # according to omnimath
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"):
# en-compendium is segmented in segment_compendium.py
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)
|