File size: 5,435 Bytes
25cbcc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
from pathlib import Path
from typing import Any

import numpy as np
import pandas as pd
from PIL import Image

REQUIRED_COLUMNS = (
    "sample_id",
    "edit_type",
    "before",
    "after",
    "instruction_pos",
    "instruction_neg_list",
    "instruction_neg_types",
)

PATH_COLUMNS = ("before", "after")


def load_dataset(dataset_root: str | Path) -> pd.DataFrame:
    dataset_root = Path(dataset_root)
    parquet_path = dataset_root / "benchmark.parquet"
    if not parquet_path.exists():
        raise FileNotFoundError(f"Missing dataset parquet: {parquet_path}")
    return pd.read_parquet(parquet_path)


def as_list(value: Any) -> list[Any]:
    if value is None:
        return []
    if isinstance(value, float) and np.isnan(value):
        return []
    if isinstance(value, np.ndarray):
        return value.tolist()
    if isinstance(value, (list, tuple)):
        return list(value)
    return [value]


def parse_metadata(value: Any) -> dict[str, Any]:
    if isinstance(value, dict):
        return value
    if isinstance(value, str):
        try:
            parsed = json.loads(value)
            return parsed if isinstance(parsed, dict) else {}
        except json.JSONDecodeError:
            return {}
    return {}


def expand_triplets(df: pd.DataFrame) -> pd.DataFrame:
    """Expand edit-level rows into positive/negative verification triplets."""
    rows: list[dict[str, Any]] = []
    for row_index, row in df.reset_index(drop=True).iterrows():
        sample_id = row.get("sample_id", f"row-{row_index:05d}")
        base = {
            "sample_id": sample_id,
            "parquet_row_index": int(row.get("parquet_row_index", row_index)),
            "edit_type": row["edit_type"],
            "before": row["before"],
            "after": row["after"],
        }
        rows.append(
            {
                **base,
                "instruction": row["instruction_pos"],
                "label": 1,
                "ground_truth": True,
                "example_type": "positive",
                "negative_type": "positive",
                "negative_index": -1,
            }
        )

        negs = as_list(row["instruction_neg_list"])
        neg_types = as_list(row["instruction_neg_types"])
        if len(negs) != len(neg_types):
            raise ValueError(f"Negative instruction/type length mismatch for {sample_id}")
        for neg_index, (instruction, negative_type) in enumerate(zip(negs, neg_types)):
            rows.append(
                {
                    **base,
                    "instruction": instruction,
                    "label": 0,
                    "ground_truth": False,
                    "example_type": "negative",
                    "negative_type": str(negative_type),
                    "negative_index": neg_index,
                }
            )
    return pd.DataFrame(rows)


def _is_portable_relative_path(value: Any) -> bool:
    if value is None:
        return False
    path = Path(str(value))
    return not path.is_absolute() and ".." not in path.parts


def validate_dataset(dataset_root: str | Path, strict_core: bool = True) -> dict[str, Any]:
    """Validate the public Hugging Face dataset layout."""
    dataset_root = Path(dataset_root)
    df = load_dataset(dataset_root)
    report: dict[str, Any] = {
        "row_count": int(len(df)),
        "required_missing": [col for col in REQUIRED_COLUMNS if col not in df.columns],
        "edit_type_counts": df["edit_type"].value_counts().sort_index().to_dict()
        if "edit_type" in df.columns
        else {},
    }

    before_exists = df["before"].map(lambda p: (dataset_root / str(p)).exists())
    after_exists = df["after"].map(lambda p: (dataset_root / str(p)).exists())
    report["before_paths_resolvable"] = int(before_exists.sum())
    report["after_paths_resolvable"] = int(after_exists.sum())

    length_matches = []
    for _, row in df.iterrows():
        length_matches.append(
            len(as_list(row["instruction_neg_list"])) == len(as_list(row["instruction_neg_types"]))
        )
    report["negative_instruction_lengths_match"] = int(sum(length_matches))

    non_portable_paths: dict[str, int] = {}
    for col in PATH_COLUMNS:
        if col in df.columns:
            bad_count = int((~df[col].map(_is_portable_relative_path)).sum())
            if bad_count:
                non_portable_paths[col] = bad_count
    report["non_portable_path_columns"] = non_portable_paths

    dimensions: dict[str, int] = {}
    for path_text in pd.concat([df["before"], df["after"]]).head(100):
        path = dataset_root / str(path_text)
        if path.exists():
            with Image.open(path) as image:
                key = f"{image.width}x{image.height}"
                dimensions[key] = dimensions.get(key, 0) + 1
    report["sampled_image_dimension_counts"] = dimensions

    checks = [
        not report["required_missing"],
        report["before_paths_resolvable"] == len(df),
        report["after_paths_resolvable"] == len(df),
        report["negative_instruction_lengths_match"] == len(df),
        not report["non_portable_path_columns"],
    ]
    if strict_core:
        checks.extend(
            [
                len(df) == 1500,
                set(report["edit_type_counts"].values()) == {150},
            ]
        )
    report["passed"] = bool(all(checks))
    return report