Pierrax commited on
Commit
c87dcea
·
verified ·
1 Parent(s): 3086c61

Upload code/schemas/parsing_validation.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/schemas/parsing_validation.py +174 -0
code/schemas/parsing_validation.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validation orchestration for raw parsed parquets (ISO 5259).
2
+
3
+ Validates echiquiers/joueurs DataFrames and persists reports.
4
+ Reuses DataLineage/ValidationReport from training_types.
5
+
6
+ ISO Compliance:
7
+ - ISO/IEC 5259:2024 - Data Quality for ML (Lineage, Validation)
8
+ - ISO/IEC 5055:2021 - Code Quality (<300 lines, SRP)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import logging
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING
17
+
18
+ from pandera.errors import SchemaErrors
19
+
20
+ if TYPE_CHECKING:
21
+ import pandas as pd
22
+ from pandera import DataFrameSchema
23
+
24
+ from schemas.parsing_schemas import EchiquiersRawSchema, JoueursRawSchema
25
+ from schemas.training_types import (
26
+ DataLineage,
27
+ ErrorSeverity,
28
+ QualityMetrics,
29
+ ValidationError,
30
+ ValidationReport,
31
+ )
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ DEFAULT_REPORT_DIR = Path("reports/validation")
36
+
37
+
38
+ def validate_raw_echiquiers(
39
+ df: pd.DataFrame,
40
+ source_path: str = "data/echiquiers.parquet",
41
+ report_dir: Path | None = None,
42
+ ) -> ValidationReport:
43
+ """Validate raw echiquiers DataFrame and persist report."""
44
+ report = _validate_with_schema(
45
+ df=df,
46
+ schema=EchiquiersRawSchema,
47
+ source_path=source_path,
48
+ report_name="raw_echiquiers_report.json",
49
+ report_dir=report_dir or DEFAULT_REPORT_DIR,
50
+ )
51
+ logger.info(
52
+ "Echiquiers validation: valid=%s, errors=%d",
53
+ report.is_valid,
54
+ len(report.errors),
55
+ )
56
+ return report
57
+
58
+
59
+ def validate_raw_joueurs(
60
+ df: pd.DataFrame,
61
+ source_path: str = "data/joueurs.parquet",
62
+ report_dir: Path | None = None,
63
+ ) -> ValidationReport:
64
+ """Validate raw joueurs DataFrame and persist report."""
65
+ report = _validate_with_schema(
66
+ df=df,
67
+ schema=JoueursRawSchema,
68
+ source_path=source_path,
69
+ report_name="raw_joueurs_report.json",
70
+ report_dir=report_dir or DEFAULT_REPORT_DIR,
71
+ )
72
+ logger.info(
73
+ "Joueurs validation: valid=%s, errors=%d",
74
+ report.is_valid,
75
+ len(report.errors),
76
+ )
77
+ return report
78
+
79
+
80
+ def _validate_with_schema(
81
+ df: pd.DataFrame,
82
+ schema: DataFrameSchema,
83
+ source_path: str,
84
+ report_name: str,
85
+ report_dir: Path,
86
+ ) -> ValidationReport:
87
+ """Run schema validation, build report, persist to disk."""
88
+ lineage = DataLineage.from_dataframe(df, source_path)
89
+ is_valid, raw_errors = _run_validation(schema, df)
90
+ errors = _aggregate_errors(raw_errors)
91
+ error_counts = _count_by_severity(errors)
92
+ metrics = QualityMetrics(
93
+ total_rows=len(df),
94
+ valid_rows=max(0, len(df) - sum(e.failure_count for e in errors)),
95
+ null_percentages={col: float(df[col].isna().mean() * 100) for col in df.columns},
96
+ validation_rate=1.0 if is_valid else 0.0,
97
+ critical_errors=error_counts.get("critical", 0),
98
+ high_errors=error_counts.get("high", 0),
99
+ medium_errors=error_counts.get("medium", 0),
100
+ warnings=error_counts.get("warning", 0),
101
+ )
102
+ report = ValidationReport(
103
+ lineage=lineage,
104
+ metrics=metrics,
105
+ errors=errors,
106
+ is_valid=is_valid,
107
+ schema_mode="raw_parsing",
108
+ )
109
+ _persist_report(report, report_dir, report_name)
110
+ return report
111
+
112
+
113
+ def _run_validation(
114
+ schema: DataFrameSchema,
115
+ df: pd.DataFrame,
116
+ ) -> tuple[bool, list[ValidationError]]:
117
+ """Run Pandera schema validation, return (is_valid, errors)."""
118
+ try:
119
+ schema.validate(df, lazy=True)
120
+ return True, []
121
+ except SchemaErrors as exc:
122
+ errors = [
123
+ ValidationError(
124
+ column=str(row.get("column", "dataframe")),
125
+ check=str(row.get("check", "unknown")),
126
+ failure_count=1,
127
+ severity=ErrorSeverity.HIGH,
128
+ recommendation=str(row.get("check", "")),
129
+ )
130
+ for _, row in exc.failure_cases.iterrows()
131
+ ]
132
+ return False, errors
133
+
134
+
135
+ def _aggregate_errors(errors: list[ValidationError]) -> list[ValidationError]:
136
+ """Aggregate errors by (column, check), summing failure counts."""
137
+ grouped: dict[tuple[str, str], ValidationError] = {}
138
+ for error in errors:
139
+ key = (error.column, error.check)
140
+ if key in grouped:
141
+ grouped[key] = ValidationError(
142
+ column=error.column,
143
+ check=error.check,
144
+ failure_count=grouped[key].failure_count + error.failure_count,
145
+ severity=error.severity,
146
+ recommendation=error.recommendation,
147
+ )
148
+ else:
149
+ grouped[key] = error
150
+ return list(grouped.values())
151
+
152
+
153
+ def _count_by_severity(errors: list[ValidationError]) -> dict[str, int]:
154
+ """Count errors by severity level."""
155
+ counts: dict[str, int] = {}
156
+ for error in errors:
157
+ key = error.severity.value
158
+ counts[key] = counts.get(key, 0) + 1
159
+ return counts
160
+
161
+
162
+ def _persist_report(
163
+ report: ValidationReport,
164
+ report_dir: Path,
165
+ filename: str,
166
+ ) -> None:
167
+ """Save report as JSON to disk."""
168
+ report_dir.mkdir(parents=True, exist_ok=True)
169
+ report_path = report_dir / filename
170
+ report_path.write_text(
171
+ json.dumps(report.to_dict(), indent=2, default=str),
172
+ encoding="utf-8",
173
+ )
174
+ logger.info("Report saved: %s", report_path)