olympiads-ref / IMO /segment_script /segment_compendium.py
LxYxvv's picture
add exam column
0d95119
# -----------------------------------------------------------------------------
# Author: Marina
# Date: 2024-11-15
# -----------------------------------------------------------------------------
"""Script to segment IMO shortlist md files using regex. It takes as input
the file en-compendium.md in en-shortlist and outputs the segmentation
(problem/solution pairs) in en-shortlist-seg
To run:
`python segment_compendium.py`
To debug (or see covered use cases by regex):
`pytest test_segment_compendium`
"""
import json
import os
from pathlib import Path
import re
import pandas as pd
base = "en-shortlist"
seg_base = "en-shortlist-seg"
basename = "en-compendium"
level1_re = re.compile(r"^##\s+(Problems|Solutions|Notation and Abbreviations)$")
year_re = re.compile(r"^[^=]*,\s+(\d{4})\s*$")
problem_section_re = re.compile(r"^###\s+(\d+\.\d+\.\d+)\s+(.+)$")
solution_section_re = re.compile(r"^###\s+(\d+\.\d+)\s+([\w\s]+)\s+(\d{4})$")
problem_or_solution_re = re.compile(r"^(?:\[.*?\])?\s*(\d+)\s*\.\s*(.+)$")
def add_content(current_dict):
required_keys = ["year", "category", "section_label", "label", "lines"]
if not all(current_dict[key] for key in required_keys):
return
text_str = " ".join(current_dict["lines"]).strip()
entry = {
"year": current_dict["year"],
"category": current_dict["category"],
"section": current_dict["section_label"],
"label": current_dict["label"],
}
if current_dict["class"] == "problem":
entry["problem"] = text_str
current_dict["problems"].append(entry)
elif current_dict["class"] == "solution":
entry["solution"] = text_str
current_dict["solutions"].append(entry)
def get_category(s: str):
cat = None
if "contest" in s.lower():
cat = "contest"
elif "shortlisted" in s.lower():
cat = "shortlisted"
elif "longlisted" in s.lower():
cat = "longlisted"
return cat
def get_matching_section_label(s: str):
"""
extracts the section number to be used a a join key to pair a problem and solution
for problems: 3.44.1 -> 44
for solutions: 4.20 -> 20
"""
return s.split(".")[1]
def parse(file):
with open(file, "r", encoding="utf-8") as file:
content = file.read()
# problems, solutions = [], []
current = {
"year": None,
"category": None,
"section_label": None,
"label": None,
"class": None,
"lines": [],
"problems": [],
"solutions": [],
}
for line in content.splitlines():
if match := level1_re.match(line):
add_content(current)
(title,) = match.groups()
current["class"] = {
"Problems": "problem",
"Solutions": "solution",
}.get(title, "other")
current["lines"] = []
elif match := year_re.match(line):
add_content(current)
current["year"] = match.group(1)
current["lines"] = []
elif match := problem_section_re.match(line):
add_content(current)
number, title = match.groups()
current["section_label"] = get_matching_section_label(number)
current["category"] = get_category(title)
current["lines"] = []
elif match := solution_section_re.match(line):
add_content(current)
number, title, year = match.groups()
current["section_label"] = get_matching_section_label(number)
current["category"] = get_category(title)
current["year"] = year
current["lines"] = []
elif match := problem_or_solution_re.match(line):
add_content(current)
current["label"] = match.group(1)
current["lines"] = [line]
else:
if current["lines"]:
current["lines"].append(line)
problems_df = pd.DataFrame(current["problems"])
solutions_df = pd.DataFrame(current["solutions"])
return problems_df, solutions_df
def join(problems_df, solutions_df):
pairs_df = problems_df.merge(
solutions_df, on=["year", "category", "section", "label"], how="outer"
)
return pairs_df
def add_metadata(pairs_df, resource_path):
problem_type_mapping = {
"A": "Algebra",
"C": "Combinatorics",
"G": "Geometry",
"N": "Number Theory",
}
pairs_df["problem_type"] = pairs_df["problem"].str.extract(r"^\d+\.\s*([ACGN])\d*")[
0
]
pairs_df["problem_type"] = pairs_df["problem_type"].map(problem_type_mapping)
pairs_df["tier"] = "T0" # according to omnimath
pairs_df["exam"] = "IMO"
pairs_df["metadata"] = [{"resource_path": resource_path}] * len(pairs_df)
pairs_df.rename(
columns={"category": "problem_phase", "label": "problem_label"},
inplace=True,
)
# pairs_df = pairs_df.drop(columns=["section", "label"])
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" in md_file.name:
output_file = seg_output_path / md_file.relative_to(
compet_md_path
).with_suffix(".jsonl")
output_file.parent.mkdir(parents=True, exist_ok=True)
problems, solutions = parse(md_file)
pairs_df = join(problems, solutions)
pairs_df = pairs_df[pairs_df.notnull().all(axis=1)]
pairs_df = add_metadata(
pairs_df, output_file.relative_to(project_root).as_posix()
)
write_pairs(output_file, pairs_df)
# problems contains duplicate problems (since problem in Shortlist appears in Contest, and problem in Longlist appeasr in Shortlist)
# >>>print(len(problems))
# 2460
# >>>print(len(solutions))
# 961
# print(len(pairs_df))
# 960