File size: 4,482 Bytes
028b945
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Compute APM row-level metrics for model output files."""

from __future__ import annotations

import argparse
import re
from pathlib import Path
from typing import Iterable, Iterator, Optional, Tuple

from apm_metrics import compute_metrics, load_json_or_jsonl, write_json


NOISE_RE = re.compile(r"N\d+")
JSON_EXTENSIONS = {".json", ".jsonl"}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--input-root",
        type=Path,
        required=True,
        help="Root containing <model>/<noise>/results.jsonl outputs.",
    )
    parser.add_argument(
        "--output-root",
        type=Path,
        default=Path("metrics"),
        help="Directory where metric JSON files will be written.",
    )
    parser.add_argument(
        "--model",
        help="Model name to use when --input-root directly contains N*/ folders or is a file.",
    )
    parser.add_argument(
        "--noise",
        help="Noise label to use when --input-root is a single file.",
    )
    return parser.parse_args()


def is_json_data_file(path: Path) -> bool:
    return path.suffix in JSON_EXTENSIONS and path.name not in {"metrics.json", "compiled.json"}


def preferred_files(noise_dir: Path) -> Iterable[Path]:
    for preferred in ("results.jsonl", "results.json"):
        path = noise_dir / preferred
        if path.exists():
            return [path]
    return sorted(path for path in noise_dir.iterdir() if path.is_file() and is_json_data_file(path))


def direct_noise_dirs(root: Path) -> bool:
    dirs = [path for path in root.iterdir() if path.is_dir()]
    return bool(dirs) and all(NOISE_RE.fullmatch(path.name) for path in dirs)


def discover_inputs(
    input_root: Path,
    model_override: Optional[str],
    noise_override: Optional[str],
) -> Iterator[Tuple[str, str, Path, Path]]:
    """Yield model, noise, input path, and output-relative metric path."""

    if input_root.is_file():
        if not model_override or not noise_override:
            raise SystemExit("Single-file mode requires --model and --noise")
        yield model_override, noise_override, input_root, Path(model_override) / noise_override / "metrics.json"
        return

    if direct_noise_dirs(input_root):
        model = model_override or input_root.name
        for noise_dir in sorted(path for path in input_root.iterdir() if path.is_dir()):
            for file_path in preferred_files(noise_dir):
                out_name = "metrics.json" if file_path.stem == "results" else f"{file_path.stem}_metrics.json"
                yield model, noise_dir.name, file_path, Path(model) / noise_dir.name / out_name
        return

    for model_dir in sorted(path for path in input_root.iterdir() if path.is_dir()):
        model = model_override or model_dir.name
        for noise_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()):
            if noise_override and noise_dir.name != noise_override:
                continue
            for file_path in preferred_files(noise_dir):
                out_name = "metrics.json" if file_path.stem == "results" else f"{file_path.stem}_metrics.json"
                yield model, noise_dir.name, file_path, Path(model) / noise_dir.name / out_name


def evaluate_file(input_path: Path, output_path: Path, model: str, noise: str) -> Tuple[int, int]:
    records = load_json_or_jsonl(input_path)
    metrics = []
    skipped = 0

    for record in records:
        row = compute_metrics(record, model=model, noise=noise)
        if row is None:
            skipped += 1
            continue
        metrics.append(row)

    write_json(metrics, output_path)
    return len(metrics), skipped


def main() -> None:
    args = parse_args()

    total_rows = 0
    total_skipped = 0
    total_files = 0

    for model, noise, input_path, rel_output_path in discover_inputs(
        args.input_root,
        args.model,
        args.noise,
    ):
        output_path = args.output_root / rel_output_path
        rows, skipped = evaluate_file(input_path, output_path, model=model, noise=noise)
        total_rows += rows
        total_skipped += skipped
        total_files += 1
        print(f"{model}/{noise}: {rows} rows, {skipped} skipped -> {output_path}")

    print(
        f"Processed {total_files} files with {total_rows} metric rows "
        f"and {total_skipped} skipped rows"
    )


if __name__ == "__main__":
    main()