Download task_026/tests/validate_enhancement.py from Lego-X/UXInteract: direct link, hf CLI and curl.
- Browser
- Download file 6.55 kB
-
https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_026/tests/validate_enhancement.py
- Command line
-
hf download hf://datasets/Lego-X/UXInteract/task_026/tests/validate_enhancement.py
-
curl -L -o validate_enhancement.py https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_026/tests/validate_enhancement.py
6.55 kB
| import csv | |
| import math | |
| import pathlib | |
| import re | |
| import sys | |
| ROOT = pathlib.Path.cwd() | |
| def read_csv(path): | |
| with path.open(encoding="utf-8-sig", newline="") as handle: | |
| return list(csv.DictReader(handle)) | |
| def read_boston_fixture(path): | |
| lines = [line.split() for line in path.read_text(encoding="utf-8-sig").splitlines() if line.strip()] | |
| assert len(lines) > 1, "Boston fixture is empty" | |
| header = lines[0] | |
| rows = [dict(zip(header, values)) for values in lines[1:] if len(values) == len(header)] | |
| assert rows, "Boston fixture contains no parseable records" | |
| return header, rows | |
| def boston_core_rows(path, fixture_header): | |
| """Read conventional CSV or a lossless CSV export of the whitespace source.""" | |
| rows = read_csv(path) | |
| assert rows, "boston_clean.csv is empty" | |
| lookup = {key.lower(): key for key in rows[0]} | |
| if all(name.lower() in lookup for name in fixture_header): | |
| return [ | |
| {name: row[lookup[name.lower()]] for name in fixture_header} | |
| for row in rows | |
| ] | |
| combined_key = next( | |
| (key for key in rows[0] if key.split() == fixture_header), | |
| None, | |
| ) | |
| assert combined_key is not None, "Boston export does not preserve the fixture columns" | |
| parsed = [] | |
| for row in rows: | |
| values = str(row.get(combined_key, "")).split() | |
| assert len(values) == len(fixture_header), "Boston export contains a malformed fixture record" | |
| parsed.append(dict(zip(fixture_header, values))) | |
| return parsed | |
| def quantile(values, fraction): | |
| ordered = sorted(values) | |
| position = (len(ordered) - 1) * fraction | |
| lower, upper = math.floor(position), math.ceil(position) | |
| if lower == upper: | |
| return ordered[lower] | |
| return ordered[lower] * (upper - position) + ordered[upper] * (position - lower) | |
| def keyed_titanic(rows): | |
| result = {} | |
| for row in rows: | |
| key = float(row["fare"]) | |
| assert key not in result, "fixture fare values must be unique" | |
| result[key] = row | |
| return result | |
| def titanic_rows(): | |
| source = keyed_titanic(read_csv(ROOT / "titanic.csv")) | |
| output = keyed_titanic(read_csv(ROOT / "titanic_clean.csv")) | |
| assert output and set(output) <= set(source), "Titanic output must contain only fixture records" | |
| for key, before in source.items(): | |
| if key not in output: | |
| assert not before.get('age', '').strip() or not before.get('deck', '').strip(), 'only missing age/deck rows may be deleted' | |
| for key, after in output.items(): | |
| before = source[key] | |
| for field in ('sex', 'class', 'embarked'): | |
| assert after[field] == before[field], f'original category changed: {field}' | |
| for field in ('survived', 'pclass', 'sibsp', 'parch'): | |
| assert float(after[field]) == float(before[field]), f'original field changed: {field}' | |
| return source, output | |
| def boolean_value(value): | |
| token = re.sub(r"[^a-z0-9]+", "", str(value).lower()) | |
| if token in {"true", "1", "yes", "y"}: | |
| return True | |
| if token in {"false", "0", "no", "n"}: | |
| return False | |
| raise AssertionError(f"is_alone is not boolean-like: {value!r}") | |
| # ENHANCED_CASE_1 | |
| def case_boston_iqr_retention(): | |
| """IQR filtering removes the deliberately extreme row and retains every inlier.""" | |
| header, source = read_boston_fixture(ROOT / "BostonHousing.txt") | |
| medv = [float(row["medv"]) for row in source] | |
| q1, q3 = quantile(medv, 0.25), quantile(medv, 0.75) | |
| spread = q3 - q1 | |
| low, high = q1 - 1.5 * spread, q3 + 1.5 * spread | |
| expected = [row for row in source if low <= float(row["medv"]) <= high] | |
| assert 0 < len(expected) < len(source), "fixture must contain both inliers and outliers" | |
| output = boston_core_rows(ROOT / "boston_clean.csv", header) | |
| expected_rows = sorted(tuple(float(row[name]) for name in header) for row in expected) | |
| actual_rows = sorted(tuple(float(row[name]) for name in header) for row in output) | |
| assert actual_rows == expected_rows, "boston_clean.csv does not retain the fixture's IQR-valid records" | |
| # ENHANCED_CASE_2 | |
| def case_titanic_missing_value_fill(): | |
| """Titanic age/deck values are non-empty and supplied fixture values remain unchanged.""" | |
| source, output = titanic_rows() | |
| assert any(not row.get("deck", "").strip() for row in source.values()), "fixture must exercise deck filling" | |
| observed_ages = [float(row["age"]) for row in source.values() if row.get("age", "").strip()] | |
| for key, after in output.items(): | |
| before = source[key] | |
| assert after.get("age", "").strip(), f"age remains empty for fare={key}" | |
| assert after.get("deck", "").strip(), f"deck remains empty for fare={key}" | |
| age = float(after["age"]) | |
| assert math.isfinite(age), f"age is not finite for fare={key}" | |
| if before.get("age", "").strip(): | |
| assert age == float(before["age"]), f"observed age changed for fare={key}" | |
| else: | |
| assert min(observed_ages) <= age <= max(observed_ages), f"age fill is outside the fixture range for fare={key}" | |
| if before.get("deck", "").strip(): | |
| assert after["deck"].strip() == before["deck"].strip(), f"observed deck changed for fare={key}" | |
| # ENHANCED_CASE_3 | |
| def case_titanic_is_alone_truth_table(): | |
| """Titanic is_alone exactly follows sibsp + parch == 0, including both outcomes.""" | |
| source, output = titanic_rows() | |
| assert "is_alone" in next(iter(output.values())), "titanic_clean.csv lacks is_alone" | |
| outcomes = set() | |
| for key in output: | |
| before = source[key] | |
| expected = float(before.get("sibsp") or 0) + float(before.get("parch") or 0) == 0 | |
| outcomes.add(expected) | |
| assert boolean_value(output[key].get("is_alone")) is expected, f"is_alone mismatch for fare={key}" | |
| assert outcomes, "cleaning must retain at least one record" | |
| CASES = [ | |
| ("ENHANCED_CASE_1", case_boston_iqr_retention), | |
| ("ENHANCED_CASE_2", case_titanic_missing_value_fill), | |
| ("ENHANCED_CASE_3", case_titanic_is_alone_truth_table), | |
| ] | |
| failures = [] | |
| requested = set(sys.argv[1:]) | |
| known = {case_id for case_id, _ in CASES} | |
| assert requested <= known, f"unknown case id(s): {sorted(requested - known)}" | |
| for case_id, validator in CASES: | |
| if requested and case_id not in requested: | |
| continue | |
| try: | |
| validator() | |
| print(f"{case_id}: PASS") | |
| except Exception as exc: | |
| failures.append((case_id, exc)) | |
| print(f"{case_id}: FAIL: {exc}", file=sys.stderr) | |
| if failures: | |
| raise SystemExit(1) | |