from __future__ import annotations import argparse import csv import json from collections import Counter from pathlib import Path from typing import Any import pyarrow.parquet as pq from src.data.io_utils import write_json from src.data.manifest import build_manifest from src.data.normalize_text import json_safe, normalize_whitespace, word_count def short_sample(value: Any, limit: int = 300) -> Any: if isinstance(value, (dict, list)): rendered = json.dumps(value, ensure_ascii=False) return rendered[:limit] rendered = normalize_whitespace(value) return rendered[:limit] def inspect_parquet(path: Path) -> dict[str, Any]: table = pq.read_table(path) rows = table.to_pylist() report: dict[str, Any] = { "format": "parquet", "rows": table.num_rows, "columns": table.column_names, "dtypes": {field.name: str(field.type) for field in table.schema}, "sample": {key: short_sample(value) for key, value in rows[0].items()} if rows else {}, } for column in table.column_names: values = [row.get(column) for row in rows] if "label" in column.casefold() or column.casefold() in {"verdict"}: report.setdefault("label_counts", {})[column] = dict(Counter(str(value) for value in values)) if any(token in column.casefold() for token in ["claim", "statement", "context", "evidence", "question"]): lengths = sorted(word_count(value) for value in values if value) if lengths: report.setdefault("word_lengths", {})[column] = { "mean": sum(lengths) / len(lengths), "p95": lengths[int(0.95 * (len(lengths) - 1))], "max": max(lengths), } return report def inspect_csv(path: Path) -> dict[str, Any]: with path.open(newline="", encoding="utf-8") as handle: reader = csv.DictReader(handle) rows = list(reader) report: dict[str, Any] = { "format": "csv", "rows": len(rows), "columns": reader.fieldnames or [], "sample": {key: short_sample(value) for key, value in rows[0].items()} if rows else {}, } for column in reader.fieldnames or []: values = [row.get(column) for row in rows] if "label" in column.casefold() or column.casefold() in {"verdict"}: report.setdefault("label_counts", {})[column] = dict(Counter(str(value) for value in values)) if any(token in column.casefold() for token in ["claim", "statement", "context", "evidence", "question"]): lengths = sorted(word_count(value) for value in values if value) if lengths: report.setdefault("word_lengths", {})[column] = { "mean": sum(lengths) / len(lengths), "p95": lengths[int(0.95 * (len(lengths) - 1))], "max": max(lengths), } return report def inspect_json(path: Path) -> dict[str, Any]: with path.open(encoding="utf-8") as handle: data = json.load(handle) rows = data if isinstance(data, list) else [data] report: dict[str, Any] = { "format": "json", "rows": len(rows), "sample": {key: short_sample(value) for key, value in rows[0].items()} if rows and isinstance(rows[0], dict) else short_sample(rows[0]) if rows else {}, } if rows and isinstance(rows[0], dict): key_counts = Counter(key for row in rows if isinstance(row, dict) for key in row.keys()) report["keys"] = dict(key_counts) for key in key_counts: if "label" in key.casefold() or key.casefold() in {"verdict"}: report.setdefault("label_counts", {})[key] = dict(Counter(str(row.get(key)) for row in rows if isinstance(row, dict))) question_counts = [] question_keys = Counter() answer_keys = Counter() answer_types = Counter() for row in rows: questions = row.get("questions", []) if isinstance(row, dict) else [] if isinstance(questions, list): question_counts.append(len(questions)) for question in questions: if isinstance(question, dict): question_keys.update(question.keys()) for answer in question.get("answers", []) or []: if isinstance(answer, dict): answer_keys.update(answer.keys()) answer_types.update([answer.get("answer_type", "")]) if question_counts: sorted_counts = sorted(question_counts) report["questions_per_claim"] = { "mean": sum(question_counts) / len(question_counts), "p95": sorted_counts[int(0.95 * (len(sorted_counts) - 1))], "max": max(question_counts), } report["question_keys"] = dict(question_keys) report["answer_keys"] = dict(answer_keys) report["answer_type_counts"] = dict(answer_types) return report def inspect_file(path: Path) -> dict[str, Any]: suffix = path.suffix.lower() if suffix == ".parquet": return inspect_parquet(path) if suffix == ".csv": return inspect_csv(path) if suffix == ".json": return inspect_json(path) return {"format": suffix.lstrip("."), "rows": None, "columns": [], "note": "unsupported_for_schema_inspection"} def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--dataset-root", type=Path, default=Path("datasets")) parser.add_argument("--output", type=Path, default=Path("outputs/stats/raw_schema_report.json")) args = parser.parse_args() report: dict[str, Any] = {} for row in build_manifest(args.dataset_root): if row["ignored"]: continue path = Path(str(row["path"])) try: file_report = inspect_file(path) file_report["dataset"] = row["dataset"] file_report["can_read"] = True except Exception as exc: # noqa: BLE001 - schema report should capture read failures. file_report = { "dataset": row["dataset"], "format": path.suffix.lstrip(".").lower(), "can_read": False, "error": repr(exc), } report[str(path)] = json_safe(file_report) write_json(args.output, report) print(f"Wrote schema report for {len(report)} files to {args.output}") if __name__ == "__main__": main()