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