File size: 6,250 Bytes
5b52f82
 
 
139f968
5b52f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139f968
 
 
 
 
 
 
 
5b52f82
 
 
 
 
 
 
 
5646a5c
5b52f82
 
 
 
139f968
5b52f82
139f968
5646a5c
5b52f82
 
139f968
5646a5c
139f968
 
 
 
5b52f82
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
from collections import defaultdict
from pathlib import Path
import re


def match_tags_by_key(prob_tags, sol_tags, extract_key):
    prob_index = defaultdict(list)
    sol_index = defaultdict(list)

    for i, tag in enumerate(prob_tags):
        prob_index[extract_key(tag)].append(i)

    for i, tag in enumerate(sol_tags):
        sol_index[extract_key(tag)].append(i)

    index_pairs = []
    for num in prob_index:
        for i, j in zip(prob_index[num], sol_index[num]):
            index_pairs.append((i, j))

    return index_pairs


def solution_chapter_after_chapter_ends(chapter_starts, solution_starts, max_size):
    return solution_starts, chapter_starts[1:] + [max_size]


def solution_after_all_problem_ends(chapter_starts, solution_starts, max_size):
    return chapter_starts[1:] + [solution_starts[0]], solution_starts[1:] + [max_size]


def join_chapter_tags(
    text,
    chapter_tags,
    solution_tags,
    prob_re,
    extract_key,
    compute_ends=solution_chapter_after_chapter_ends,
):
    def segment(text, prob_tags, sol_tags, prob_end, sol_end):
        prob_pos = [tag.start() for tag in prob_tags] + [prob_end]
        sol_pos = [tag.start() for tag in sol_tags] + [sol_end]
        probs = [
            text[start:end].strip() for start, end in zip(prob_pos[:-1], prob_pos[1:])
        ]
        sols = [
            text[start:end].strip() for start, end in zip(sol_pos[:-1], sol_pos[1:])
        ]
        return probs, sols

    """
    for chapter_tag in chapter_tags:
        print(chapter_tag)
    for solution_tag in solution_tags:
        print(solution_tag)"""

    print(len(chapter_tags), len(solution_tags))
    if len(chapter_tags) != len(solution_tags):
        return []

    tags = list(prob_re.finditer(text))
    chapter_starts = [tag.start() for tag in chapter_tags]
    solution_starts = [tag.start() for tag in solution_tags]
    chapter_ends, solution_ends = compute_ends(
        chapter_starts, solution_starts, len(text)
    )

    prob_batch_tags, sol_batch_tags = [], []
    for start, end in zip(chapter_starts, chapter_ends):
        prob_batch_tags.append(
            [tag for tag in tags if tag.start() > start and tag.start() < end]
        )
    for start, end in zip(solution_starts, solution_ends):
        sol_batch_tags.append(
            [tag for tag in tags if tag.start() > start and tag.start() < end]
        )

    pairs = []
    for prob_tags, sol_tags, prob_end, sol_end in zip(
        prob_batch_tags, sol_batch_tags, chapter_ends, solution_ends
    ):
        """for tag in prob_tags:
            print(tag)
        for tag in sol_tags:
            print(tag)"""
        print(len(prob_tags), len(sol_tags))
        probs, sols = segment(text, prob_tags, sol_tags, prob_end, sol_end)
        pairs.extend(
            [
                (probs[i], sols[j], prob_tags[i], sol_tags[j])
                for i, j in match_tags_by_key(prob_tags, sol_tags, extract_key)
            ]
        )
    pairs.sort(key=lambda x: x[2].start())

    """for _, _, prob_tag, sol_tag in pairs:
        print(prob_tag, sol_tag)"""

    return pairs


def join_chapter(
    text,
    chapter_re,
    solution_re,
    prob_re,
    extract_key,
    compute_ends=solution_chapter_after_chapter_ends,
):
    chapter_tags = list(chapter_re.finditer(text))
    solution_tags = list(solution_re.finditer(text))
    return join_chapter_tags(
        text, chapter_tags, solution_tags, prob_re, extract_key, compute_ends
    )


def join_prob_sol(tags, text):
    prob = None
    prob_tag, sol_tag, prob_label = None, None, None
    pairs = []

    counter = 0
    while counter < len(tags):
        if tags[counter][1]:
            sol_tag = tags[counter][0]
            while counter < len(tags) and tags[counter][1]:
                counter += 1

            start = sol_tag.end()
            end = tags[counter][0].start() if counter < len(tags) else len(text)

            if prob:
                pairs.append((prob, text[start:end], prob_tag, sol_tag, prob_label))
        else:
            while counter < len(tags) and not tags[counter][1]:
                prob_tag = tags[counter][0]
                prob_label = tags[counter][0].group(1)
                start = prob_tag.end()
                end = (
                    tags[counter + 1][0].start()
                    if counter + 1 < len(tags)
                    else len(text)
                )
                prob = text[start:end]
                counter += 1

    return pairs


min_length = 5


project_root = Path(__file__).parent.parent.parent
problem_type_mapping = {
    "A": "Algebra",
    "C": "Combinatorics",
    "G": "Geometry",
    "N": "Number Theory"
    }

def write_pairs(filename, pairs):
    year = re.search(r"(\d{4})", str(filename)).group(1)
    with open(filename, "w", encoding="utf-8") as f:
        for problem, solution, prob_tag, sol_tag, prob_label in pairs:
            if (
                len(problem) > prob_tag.end() - prob_tag.start() + min_length
                and len(solution) > sol_tag.end() - sol_tag.start() + min_length
            ):
                resource_path = Path(filename).relative_to(project_root).as_posix()
                f.write(
                    json.dumps(
                        {
                            "year": year,
                            "tier": "T3",
                            "problem_label": prob_label,
                            "problem_type": problem_type_mapping.get(prob_label[0]),
                            "exam": "JBMO-SL" if "en-shortlist" in resource_path else "JBMO",
                            "problem": problem,
                            "solution": solution,
                            "metadata": {
                                "resource_path": resource_path,
                                "problem_match": prob_tag.group(0),
                                "solution_match": sol_tag.group(0),
                            },
                            
                        },
                        ensure_ascii=False,
                    )
                    + "\n"
                )


base = "../../ru-books"
seg_path = "."

dirname = "library"
path = os.path.join(base, dirname)