File size: 1,498 Bytes
d7d1759
 
 
 
 
 
 
 
 
 
 
 
 
 
124d643
d7d1759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from pathlib import Path
from pydantic import BaseModel
import json

MARKDOWN_DIR = Path("markdown")

class Problem(BaseModel):
    year: str
    problem_id: str
    problem: str
    solution: str | None
    
    def to_dict(self):
        return {
            "id": f"{self.year}-imo-{self.problem_id}",
            "problem": self.problem,
            "solution": self.solution
        }

def get_problem(year: str, problem_id: str, problem_dir: Path):
    problem_file = problem_dir / "problem.md"
    solution_file = problem_dir / "solution.md"
    with open(problem_file, "r", encoding="utf-8") as f:
        problem = f.read()
    if solution_file.exists():
        with open(solution_file, "r", encoding="utf-8") as f:
            solution = f.read()
    else:
        solution = None
    return Problem(year=year, problem_id=problem_id, problem=problem, solution=solution)

def convert_problems():
    result = []
    for year_dir in MARKDOWN_DIR.iterdir():
        if not year_dir.is_dir():
            continue
        year = year_dir.name
        for problem_dir in year_dir.iterdir():
            if not problem_dir.is_dir():
                continue
            problem_number = problem_dir.name
            result.append(get_problem(year, problem_number, problem_dir).to_dict())
    result.sort(key=lambda x: x["id"])
    return result

if __name__ == "__main__":
    result = convert_problems()
    with open("imo_2025.json", "w", encoding="utf-8") as f:
        json.dump(result, f)