File size: 4,255 Bytes
0ae36c4
 
 
 
 
 
 
 
 
 
139f968
0ae36c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139f968
0ae36c4
139f968
0d95119
0ae36c4
 
139f968
 
 
 
 
0ae36c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
import json

from tqdm import tqdm
from loguru import logger

from pathlib import Path
from typing import Tuple, List


project_root = Path(__file__).parent.parent.parent
problem_pattern = re.compile(r'\n(\d+)\.\s+', re.IGNORECASE)
solution_pattern = re.compile(r'(?:\n|# )Opgave\s+(\d+)\.', re.IGNORECASE)


def analyze_problem(text: str) -> Tuple[List, int]:
    tags = list(problem_pattern.finditer(text))
    problem_num = len(tags)
    tags.sort(key=lambda x: x.start())
    return tags, problem_num


def analyze_solution(text: str) -> Tuple[List, int]:
    tags = list(solution_pattern.finditer(text))
    solution_num = len(tags)
    tags.sort(key=lambda x: x.start())
    return tags, solution_num


def segment(text: str, tags: list):
    starts = []
    ends = []

    for i, t in enumerate(tags):
        starts.append(t.end())
        if i + 1 < len(tags):
            ends.append(tags[i + 1].start())
        else:
            ends.append(len(text))

    return [text[start:end].strip() for start, end in zip(starts, ends)]


def join(problems, solutions):
    pairs = []

    for problem in problems:
        key = problem[0].group(1)

        problem_content = problem[1]
        problem_label = key
        problem_match = problem[0].group(0)
        solution_content, solution_match = [], ''
        # (a) Oplossing 1.
        for s in solutions:
            if s[0].group(1) == key:
                solution_content = s[1]
                solution_match = s[0].group(0)
                break

        pairs.append((problem_content, solution_content, problem_label, problem_match, solution_match))

    return pairs


def write_pairs(output_file: Path, pairs):
    year = re.search(r'(\d{4})', output_file.stem).group(1)

    output_jsonl_text = ""
    for problem, solution, problem_label, problem_match, solution_match in pairs:
        output_jsonl_text += json.dumps(
            {
                'year': year,
                'tier': 'T1',
                'problem_label': problem_label,
                'problem_type': None,
                "exam": "Dutch_TST", 
                'problem': problem,
                'solution': solution,
                'metadata': {
                    'resource_path': output_file.relative_to(project_root).as_posix(),
                    'problem_match': problem_match,
                    'solution_match': solution_match
                }
            },
            ensure_ascii=False
        ) + '\n'

    output_file.write_text(output_jsonl_text, encoding="utf-8")


def main():
    compet_base_path = Path(__file__).resolve().parent.parent
    compet_md_path = compet_base_path / "md"
    seg_output_path = compet_base_path / "segmented"

    special_years_md = {
        "2007": {
            "problem": "nl-2007-opgaven.md",
            "solution": "nl-2007-uitwerkingen.md"
        },
        "2008": {
            "problem": "nl-2008-opgaven.md",
            "solution": "nl-2008-uitwerkingen.md"
        }
    }

    total_problem_count = 0
    total_solution_count = 0

    for year, md in tqdm(special_years_md.items()):
        problem_path = compet_md_path / md["problem"]
        solution_path = compet_md_path / md["solution"]

        output_file = seg_output_path / solution_path.relative_to(compet_md_path).with_suffix('.jsonl')
        output_file.parent.mkdir(parents=True, exist_ok=True)

        problem_content = problem_path.read_text(encoding="utf-8")
        problem_tags, problem_num = analyze_problem(problem_content)
        segmented_problems = segment(problem_content, problem_tags)
        problems = zip(problem_tags, segmented_problems)

        solution_content = solution_path.read_text(encoding="utf-8")
        solution_tags, solution_num = analyze_solution(solution_content)
        segmented_solutions = segment(solution_content, solution_tags)
        solutions = zip(solution_tags, segmented_solutions)

        pairs = join(problems, solutions)
        write_pairs(output_file, pairs)

        total_problem_count += problem_num
        total_solution_count += len(pairs)

    logger.info(f"Total problem count: {total_problem_count}")
    logger.info(f"Total solution count: {total_solution_count}")


if __name__ == "__main__":
    main()