File size: 6,638 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
 
 
eebb93b
 
139f968
 
eebb93b
139f968
 
 
 
eebb93b
139f968
 
 
 
 
0d95119
139f968
 
 
 
 
 
 
 
 
 
 
 
0d95119
139f968
 
 
 
 
 
 
 
72f5d73
139f968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eebb93b
 
 
 
 
 
 
 
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# -----------------------------------------------------------------------------
# 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