File size: 9,396 Bytes
9c84f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
222
223
224
225
226
227
228
229
230
231
232
"""Load project configurations from YAML files."""

import logging
from collections.abc import Mapping
from pathlib import Path
from typing import Any

import yaml

from solar_eval.core.pipeline_compose import PipelineCompositionError, compose_pipeline
from solar_eval.core.task_discovery import discover_tasks

logger = logging.getLogger(__name__)


def load_all_project_configs(
    data_dir: str | Path, config_dirs: Mapping[str, Path] | None = None
) -> list[dict[str, Any]]:
    """레포 관리 config 디렉토리 + 데이터 루트λ₯Ό 병합해 λ‘œλ“œν•œλ‹€.

    config_dirs (ν”„λ‘œμ νŠΈλͺ… β†’ accounts/<a>/<c>/03-evaluation) κ°€ μš°μ„ μ΄κ³ ,
    데이터 λ£¨νŠΈμ—μ„œλ§Œ λ°œκ²¬λ˜λŠ” ν”„λ‘œμ νŠΈ(레포 관리 μ œμ™Έ νŠΈλž™)λŠ” 뒀에 λΆ™λŠ”λ‹€.
    νŒŒμ΄ν”„λΌμΈ μ°Έμ‘°λŠ” 각 config κ°€ 놓인 디렉토리 κΈ°μ€€μœΌλ‘œ ν•΄μ„λœλ‹€.
    """
    configs: list[dict[str, Any]] = []
    seen: set[str] = set()
    for _, config_dir in sorted((config_dirs or {}).items()):
        config = _load_yaml(Path(config_dir) / "project.yaml")
        if config is None or config.get("name") in seen:
            continue
        _resolve_defaults(config, Path(config_dir), data_root=Path(data_dir))
        configs.append(config)
        seen.add(config["name"])
    for config in load_project_configs(data_dir):
        if config["name"] not in seen:
            configs.append(config)
    return configs


def load_project_configs(projects_dir: str | Path) -> list[dict[str, Any]]:
    """Load all YAML project configs from a directory.

    Searches two locations (both supported, no duplicates):
      1. projects_dir/<name>/project.yaml  (preferred β€” config inside project folder)
      2. projects_dir/<name>.yaml          (legacy β€” config at root level)

    Args:
        projects_dir: Path to directory containing project configs.

    Returns:
        List of parsed project config dicts.
    """
    configs = []
    seen_names: set[str] = set()
    projects_path = Path(projects_dir)
    if not projects_path.exists():
        logger.warning(f"Projects directory not found: {projects_path}")
        return configs

    # 1. project.yaml inside project folders (preferred)
    for project_yaml in sorted(projects_path.glob("*/project.yaml")):
        config = _load_yaml(project_yaml)
        if config and config.get("name") not in seen_names:
            project_dir = project_yaml.parent
            _resolve_defaults(config, project_dir, data_root=projects_path)
            configs.append(config)
            seen_names.add(config["name"])

    # 2. Legacy: <name>.yaml at root level
    for yaml_file in sorted(projects_path.glob("*.yaml")):
        config = _load_yaml(yaml_file)
        if config and config.get("name") not in seen_names:
            project_dir = yaml_file.parent / config["name"]
            _resolve_defaults(config, project_dir, data_root=projects_path)
            configs.append(config)
            seen_names.add(config["name"])

    return configs


def _load_yaml(path: Path) -> dict[str, Any] | None:
    """Load and validate a single project YAML file."""
    try:
        with open(path) as f:
            config = yaml.safe_load(f)
        if config and "name" in config:
            logger.debug(f"Loaded project config: {config['name']} from {path}")
            return config
    except Exception as e:
        logger.warning(f"Failed to load {path}: {e}")
    return None


def _resolve_defaults(
    config: dict[str, Any], project_dir: Path, data_root: Path | None = None
) -> None:
    """Merge top-level `defaults` into each task, then resolve derived fields.

    Also expands `discover:` rules into tasks, resolves string `pipeline_config`
    references to actual pipeline YAML files (following `extends`), and attaches a
    resolved `field_map` (see `resolve_field_map`). Mutates config in place.
    """
    # λ‘œλ”κ°€ μ±„μš°λŠ” μœ λ„ ν•„λ“œ β€” μŠ€ν…μ΄ config μ •λ³Έ κΈ°μ€€ μžμ‚°(μΉ˜ν™˜ 사전 λ“±)을
    # ν’€ λ•Œ μ“΄λ‹€. project.yaml 에 μ λŠ” 값이 μ•„λ‹ˆλ‹€.
    config["config_dir"] = str(project_dir)

    _expand_discovered_tasks(config, data_root)

    tasks = config.get("tasks", [])
    defaults = config.get("defaults", {})

    for task in tasks:
        # Merge each default key into task if not already set
        for key, value in defaults.items():
            if key not in task:
                task[key] = value

        # Resolve string pipeline_config β†’ load from pipelines/ directory
        _resolve_pipeline_ref(task, project_dir)

        # EvalSample field_map β€” explicit if declared, else derived from the
        # legacy input_fields/golden_field/golden_fields trio (no-op today: nothing
        # consumes task["field_map"] yet, this only prepares stage C/D wiring).
        task["field_map"] = resolve_field_map(task)


def _expand_discovered_tasks(config: dict[str, Any], data_root: Path | None) -> None:
    """`discover:` κ·œμΉ™μ΄ 찾은 νƒœμŠ€ν¬λ₯Ό `tasks` 뒀에 뢙인닀 (λͺ…μ‹œ νƒœμŠ€ν¬κ°€ μš°μ„ ).

    발견 μ‹€νŒ¨λŠ” μ‚Όν‚€μ§€ μ•Šκ³  둜그둜 남긴닀 β€” 데이터 λ£¨νŠΈκ°€ μ—†λŠ” ν™˜κ²½(CI λ“±)μ—μ„œλŠ”
    빈 λͺ©λ‘μ΄ μ •μƒμ΄μ§€λ§Œ, κ·œμΉ™ μžμ²΄κ°€ 잘λͺ»λœ κ²½μš°μ™€λŠ” ꡬ뢄돼야 ν•œλ‹€.
    """
    if not config.get("discover"):
        return
    try:
        found = discover_tasks(config, data_root)
    except ValueError as e:
        logger.warning("Task discovery failed for %s: %s", config.get("name"), e)
        return
    if found:
        config["tasks"] = [*(config.get("tasks") or []), *found]
        logger.debug("Discovered %d tasks for %s", len(found), config.get("name"))


def load_pipeline_file(pipelines_dir: Path, name: str) -> dict[str, Any]:
    """νŒŒμ΄ν”„λΌμΈ YAML ν•œ μž₯을 읽어 `extends`/override λ₯Ό ν•΄μ„ν•œ dict 둜 λŒλ €μ€€λ‹€.

    Args:
        pipelines_dir: `pipelines/` 디렉토리.
        name: ν™•μž₯자 μ—†λŠ” νŒŒμ΄ν”„λΌμΈ 이름.

    Raises:
        FileNotFoundError: 파일이 없을 λ•Œ.
        PipelineCompositionError: 상속·override 해석이 μ‹€νŒ¨ν–ˆμ„ λ•Œ.
    """
    path = pipelines_dir / f"{name}.yaml"
    if not path.exists():
        raise FileNotFoundError(f"Pipeline file not found: {path}")
    with open(path) as f:
        raw = yaml.safe_load(f)
    if not isinstance(raw, dict):
        raise PipelineCompositionError(f"Pipeline {name!r} is not a mapping: {path}")
    return compose_pipeline(raw, load_base=lambda base: _load_raw_pipeline(pipelines_dir, base))


def _load_raw_pipeline(pipelines_dir: Path, name: str) -> dict[str, Any]:
    """`extends` λŒ€μƒμ„ μ‘°λ¦½ν•˜μ§€ μ•Šμ€ μƒνƒœλ‘œ μ½λŠ”λ‹€ (닀단 상속 κ²€μΆœμš©)."""
    path = pipelines_dir / f"{name}.yaml"
    if not path.exists():
        raise PipelineCompositionError(f"Base pipeline {name!r} not found: {path}")
    with open(path) as f:
        raw = yaml.safe_load(f)
    if not isinstance(raw, dict):
        raise PipelineCompositionError(f"Base pipeline {name!r} is not a mapping: {path}")
    return raw


def _resolve_pipeline_ref(task: dict[str, Any], project_dir: Path) -> None:
    """If pipeline_config is a string reference, load the pipeline YAML file."""
    pipeline_ref = task.get("pipeline_config")
    if not isinstance(pipeline_ref, str):
        return

    try:
        task["pipeline_config"] = load_pipeline_file(project_dir / "pipelines", pipeline_ref)
        logger.debug(f"Resolved pipeline_config '{pipeline_ref}' from {project_dir}")
    except (FileNotFoundError, PipelineCompositionError, OSError, yaml.YAMLError) as e:
        logger.warning(f"Failed to load pipeline '{pipeline_ref}': {e}")


def resolve_field_map(task_config: dict[str, Any]) -> dict[str, Any]:
    """task μ„€μ •μ—μ„œ `EvalSample.from_row` 용 field_map 을 κ²°μ •ν•œλ‹€.

    순수 ν•¨μˆ˜ β€” task_config λ₯Ό λ³€ν˜•ν•˜μ§€ μ•Šκ³  μƒˆ dict λ₯Ό λ°˜ν™˜ν•œλ‹€.

    μš°μ„ μˆœμœ„:
      1. task_config 에 λͺ…μ‹œμ  `field_map` 이 있으면 κ·ΈλŒ€λ‘œ(사본) λ°˜ν™˜ν•œλ‹€.
      2. μ—†μœΌλ©΄ λ ˆκ±°μ‹œ `input_fields`/`golden_field`/`golden_fields` μ—μ„œ μœ λ„ν•œλ‹€:
         - `input_fields` 의 **첫 번째** ν•„λ“œ β†’ `input`
           (λ‚˜λ¨Έμ§€ ν•„λ“œλŠ” field_map 이 λ‹΄μ§€ λͺ»ν•œλ‹€ β€” 닀쀑 μž…λ ₯ ν•„λ“œ νƒœμŠ€ν¬λŠ”
           λͺ…μ‹œμ  field_map 을 μ„ μ–Έν•΄μ•Ό ν•œλ‹€)
         - `golden_field` β†’ `reference` (λ¬Έμžμ—΄ 컬럼λͺ…)
         - `golden_field` κ°€ μ—†κ³  `golden_fields` κ°€ 있으면 β†’ `reference` 에
           κ·Έ dict λ₯Ό κ·ΈλŒ€λ‘œ λ„£λŠ”λ‹€ (`EvalSample.from_row` κ°€ μ—¬λŸ¬ μ»¬λŸΌμ„ λ¬Άμ–΄
           ν•©μ„± 정닡을 λ§Œλ“ λ‹€). `runner.py` 의 `golden_fields` μ²˜λ¦¬μ™€ λ™μΉ˜.

    Args:
        task_config: `defaults` 병합이 λλ‚œ task μ„€μ • dict.

    Returns:
        EvalSample ν•„λ“œλͺ… -> 컬럼λͺ…(str) λ˜λŠ” {μ„œλΈŒν‚€: 컬럼λͺ…}(dict) λ§€ν•‘.
        μ–΄λŠ μ†ŒμŠ€λ„ μ—†μœΌλ©΄ 빈 dict.
    """
    explicit = task_config.get("field_map")
    if explicit:
        return dict(explicit)

    field_map: dict[str, Any] = {}

    input_fields = task_config.get("input_fields") or []
    if input_fields:
        field_map["input"] = input_fields[0]

    golden_field = task_config.get("golden_field")
    golden_fields = task_config.get("golden_fields")
    if golden_field:
        field_map["reference"] = golden_field
    elif golden_fields:
        field_map["reference"] = dict(golden_fields)

    return field_map