File size: 6,975 Bytes
5fed0fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
"""File I/O utilities for solution generation."""

import os
import re
from pathlib import Path
from typing import Dict, List, Tuple


def load_env_file(env_path: Path) -> None:
    """Load simple KEY=VALUE pairs from a .env file into os.environ."""
    if not env_path.is_file():
        return

    for raw_line in env_path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        if line.lower().startswith("export "):
            line = line[len("export "):].strip()
        if "=" not in line:
            continue
        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip().strip('"').strip("'")
        if key:
            os.environ[key] = value


def load_solution_targets(path: Path) -> List[Tuple[str, str]]:
    """Load solution:problem pairs from a solutions file."""
    if not path.is_file():
        raise FileNotFoundError(f"Solutions file not found: {path}")

    targets: List[Tuple[str, str]] = []
    seen: set[str] = set()
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        if ":" not in line:
            raise ValueError(f"Invalid solutions file line (expected solution:problem): {line}")
        solution, problem = line.split(":", 1)
        solution = solution.strip()
        problem = problem.strip()
        if not solution or not problem:
            continue
        key = f"{solution}:{problem}"
        if key in seen:
            continue
        seen.add(key)
        targets.append((solution, problem))

    if not targets:
        raise ValueError(f"No valid entries found in {path}")
    return targets


def read_models_file(path: Path) -> List[str]:
    """Read model names from a newline-delimited file."""
    models: List[str] = []
    seen: set[str] = set()
    if not path.is_file():
        return models
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        if line not in seen:
            models.append(line)
            seen.add(line)
    return models


def read_variant_indices_file(path: Path) -> List[int]:
    """Read variant indices from file.

    Format:
      - One integer per line (e.g., 0, 1, 2, 3, 4). 0 means no suffix.
      - Blank lines and lines starting with '#' are ignored.

    Backward compatibility:
      - If the file contains a single integer N, treat as variants [0..N-1].
    """
    if not path.is_file():
        return [0]
    raw: List[str] = []
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        raw.append(line)

    if not raw:
        return [0]

    # If single integer -> expand to range
    if len(raw) == 1:
        try:
            count = int(raw[0])
            if count <= 0:
                return [0]
            return list(range(count))
        except ValueError:
            pass  # fall through to per-line parsing

    seen: set[int] = set()
    indices: List[int] = []
    for entry in raw:
        try:
            idx = int(entry)
        except ValueError as exc:
            raise ValueError(f"Invalid variant index in {path}: '{entry}'") from exc
        if idx < 0:
            raise ValueError(f"Variant indices must be >= 0, got {idx}")
        if idx not in seen:
            seen.add(idx)
            indices.append(idx)
    if not indices:
        return [0]
    return indices


def read_readme(problem_path: Path) -> str:
    """Read the README file from a problem directory."""
    for name in ["readme", "README.md", "README", "readme.md"]:
        readme = problem_path / name
        if readme.exists():
            return readme.read_text(encoding='utf-8')
    raise FileNotFoundError(f"No README in {problem_path}")


def load_docker_config(config_path: Path) -> Dict[str, Tuple[str, bool, bool]]:
    """
    Load docker image configuration from docker_images.txt.

    Returns:
        Dict mapping problem_name -> (image, gpu_enabled, dind_enabled)
    """
    if not config_path.exists():
        return {}

    config = {}
    for line in config_path.read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        if "=" not in line:
            continue

        problem_name, rest = line.split("=", 1)
        parts = rest.split(",")
        image = parts[0].strip() if parts else ""

        gpu_enabled = False
        dind_enabled = False

        for part in parts[1:]:
            part = part.strip().lower()
            if part in ("gpu", "true", "1"):
                gpu_enabled = True
            elif part in ("dind", "docker"):
                dind_enabled = True

        config[problem_name.strip()] = (image, gpu_enabled, dind_enabled)

    return config


def write_problems_from_pairs(pairs_path: Path, target_path: Path) -> None:
    """Extract problem paths from a pairs file and write to a problems file."""
    if not pairs_path.is_file():
        return

    problems: List[str] = []
    seen: set[str] = set()
    for raw_line in pairs_path.read_text(encoding="utf-8").splitlines():
        stripped = raw_line.strip()
        if not stripped or stripped.startswith("#"):
            continue
        if ":" not in stripped:
            continue
        _, problem = stripped.split(":", 1)
        problem_clean = problem.strip()
        if not problem_clean:
            continue
        if not problem_clean.startswith("research/") and not problem_clean.startswith("./research/"):
            problem_clean = f"research/{problem_clean.lstrip('./')}"
        if problem_clean not in seen:
            seen.add(problem_clean)
            problems.append(problem_clean)

    if not problems:
        return

    target_path.write_text("\n".join(problems) + "\n", encoding="utf-8")


def sanitize_model_suffix(model: str) -> str:
    """Sanitize model name for use as a filename suffix."""
    return re.sub(r"[^a-zA-Z0-9]+", "_", model).strip("_") or "model"


def get_problem_name(problem_path: Path) -> str:
    """
    Extract the problem name from the problem path.
    Returns just the problem identifier without any model prefix.
    Examples:
    - research/vdb_pareto/balanced -> vdb_pareto_balanced
    - research/cant_be_late_multi/high_availability -> cant_be_late_multi_high_availability
    """
    if problem_path.is_absolute():
        try:
            problem_path = problem_path.relative_to(problem_path.anchor)
        except ValueError:
            pass

    parts = [p for p in problem_path.parts if p and p != "problems"]
    if not parts:
        raise ValueError(f"Unable to derive problem name from '{problem_path}'")
    return "_".join(parts)