File size: 5,263 Bytes
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
# -----------------------------------------------------------------------------
# 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 os 
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') 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):
    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'] = 0 # according to omnimath 
    pairs_df.rename(columns={"category": "problem_phase"}, inplace=True)
    pairs_df = pairs_df.drop(columns=['section', 'label'])
    return pairs_df

def write_pairs(filename, pairs_df):
    pairs_df.to_json(filename, orient="records", lines=True)


problems, solutions = parse(f"{base}/{basename}.md")
pairs_df = join(problems, solutions)
pairs_df = pairs_df[pairs_df.notnull().all(axis=1)]
pairs_df = add_metadata(pairs_df)
write_pairs(f"{seg_base}/{basename}.jsonl", 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