Download task_028/tests/validate_enhanced.py from Lego-X/UXInteract: direct link, hf CLI and curl.
- Browser
- Download file 7.78 kB
-
https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_028/tests/validate_enhanced.py
- Command line
-
hf download hf://datasets/Lego-X/UXInteract/task_028/tests/validate_enhanced.py
-
curl -L -o validate_enhanced.py https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_028/tests/validate_enhanced.py
7.78 kB
| """Instruction-derived deterministic checks for Task 44.""" | |
| import csv | |
| import html | |
| import os | |
| import pathlib | |
| import re | |
| import shutil | |
| import statistics | |
| import subprocess | |
| import tempfile | |
| ROOT = pathlib.Path.cwd() | |
| def read_csv(name): | |
| with (ROOT / name).open(encoding="utf-8-sig", newline="") as handle: | |
| return list(csv.DictReader(handle)) | |
| def matching_field(row, alternatives): | |
| for name in row: | |
| normalized = name.strip().casefold() | |
| if any(term in normalized for term in alternatives): | |
| return name | |
| raise AssertionError(f"missing column matching {alternatives}: {list(row)}") | |
| def contains_rounded_value(values, target): | |
| # Normal report rounding from 0 through 4 decimal places is accepted. | |
| return any( | |
| any(abs(value - round(target, places)) <= 10 ** (-(places + 2)) for places in range(5)) | |
| for value in values | |
| ) | |
| fixture = read_csv("spotify_songs.csv") | |
| filtered = [row for row in fixture if int(row["track_album_release_date"][:4]) >= 2000] | |
| report_raw = (ROOT / "report.html").read_text(encoding="utf-8", errors="ignore") | |
| report = html.unescape(report_raw).casefold() | |
| # ENHANCED_CASE_1: all five songs—not merely the maximum—must be the exact | |
| # descending ranking produced by the specified equal-weight activity formula. | |
| def enhanced_case_1(): | |
| top_rows = read_csv("top_5_activity_songs.csv") | |
| assert top_rows, "top_5_activity_songs.csv is empty" | |
| name_key = matching_field(top_rows[0], ("track_name", "track", "song", "歌曲")) | |
| artist_key = matching_field(top_rows[0], ("artist", "歌手", "艺人")) | |
| expected_top = sorted( | |
| filtered, | |
| key=lambda row: (float(row["energy"]) + float(row["valence"])) / 2, | |
| reverse=True, | |
| )[:5] | |
| assert len(top_rows) == len(expected_top), "top activity row count is not min(5, filtered rows)" | |
| actual_pairs = [(row[name_key].strip(), row[artist_key].strip()) for row in top_rows] | |
| expected_pairs = [(row["track_name"].strip(), row["track_artist"].strip()) for row in expected_top] | |
| assert actual_pairs == expected_pairs, ( | |
| f"activity ranking differs: actual={actual_pairs}, expected={expected_pairs}" | |
| ) | |
| score_fields = [name for name in top_rows[0] if "activ" in name.casefold() or "活跃" in name] | |
| if score_fields: | |
| score_key = score_fields[0] | |
| for actual, source_row in zip(top_rows, expected_top): | |
| expected_score = (float(source_row["energy"]) + float(source_row["valence"])) / 2 | |
| assert contains_rounded_value([float(actual[score_key])], expected_score), ( | |
| f"wrong activity score for {source_row['track_name']}" | |
| ) | |
| # ENHANCED_CASE_2: a metamorphic check makes the sole pre-2000 song the highest | |
| # activity row, reruns the candidate, and requires it to remain excluded. This | |
| # validates the requested year extraction/filter. Data-driven charts are | |
| # checked separately by validate_contract.py. | |
| def enhanced_case_2(): | |
| old_rows = [row for row in fixture if int(row["track_album_release_date"][:4]) < 2000] | |
| assert old_rows, "fixture has no pre-2000 row with which to verify the filter" | |
| excluded_pair = (old_rows[0]["track_name"].strip(), old_rows[0]["track_artist"].strip()) | |
| py_files = sorted( | |
| path for path in ROOT.rglob("*.py") | |
| if "tests" not in path.parts and "logs" not in path.parts | |
| ) | |
| assert py_files, "no candidate Python program found" | |
| main_py = py_files[0] | |
| for path in py_files: | |
| if any(token in path.name.casefold() for token in ("analysis", "example", "transform", "main")): | |
| main_py = path | |
| break | |
| with tempfile.TemporaryDirectory(prefix="task44_case2_") as tmp_name: | |
| work = pathlib.Path(tmp_name) / "work" | |
| shutil.copytree( | |
| ROOT, | |
| work, | |
| ignore=shutil.ignore_patterns("tests", "logs", "*.pyc", "__pycache__"), | |
| ) | |
| with (work / "spotify_songs.csv").open(encoding="utf-8-sig", newline="") as handle: | |
| reader = csv.DictReader(handle) | |
| names = reader.fieldnames | |
| mutated = list(reader) | |
| assert names and mutated, "cannot prepare mutated Spotify fixture" | |
| for row in mutated: | |
| if (row["track_name"].strip(), row["track_artist"].strip()) == excluded_pair: | |
| row["energy"] = "1.0" | |
| row["valence"] = "1.0" | |
| with (work / "spotify_songs.csv").open("w", encoding="utf-8", newline="") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=names) | |
| writer.writeheader() | |
| writer.writerows(mutated) | |
| (work / "top_5_activity_songs.csv").unlink(missing_ok=True) | |
| env = os.environ.copy() | |
| for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): | |
| env.pop(key, None) | |
| env["PYTHONHASHSEED"] = "1" | |
| subprocess.run( | |
| ["python3", str(main_py.relative_to(ROOT))], cwd=work, env=env, | |
| timeout=60, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, | |
| ) | |
| with (work / "top_5_activity_songs.csv").open(encoding="utf-8-sig", newline="") as handle: | |
| changed_top = list(csv.DictReader(handle)) | |
| assert changed_top, "isolated rerun did not emit top_5_activity_songs.csv" | |
| name_key = matching_field(changed_top[0], ("track_name", "track", "song", "歌曲")) | |
| artist_key = matching_field(changed_top[0], ("artist", "歌手", "艺人")) | |
| actual_pairs = {(row[name_key].strip(), row[artist_key].strip()) for row in changed_top} | |
| assert excluded_pair not in actual_pairs, ( | |
| "pre-2000 song leaked into top activity output after its score was increased" | |
| ) | |
| assert re.search(r"release[_ -]?year|发行年|发布年|年份", report), "report does not identify the release_year analysis" | |
| # ENHANCED_CASE_3: recompute the requested tempo mean and median from the | |
| # post-2000 fixture. Both summaries must be labeled and accurate under normal | |
| # report rounding; the histogram is checked by validate_contract.py. | |
| def enhanced_case_3(): | |
| tempo_values = [float(row["tempo"]) for row in filtered] | |
| tempo_mean = statistics.mean(tempo_values) | |
| tempo_median = statistics.median(tempo_values) | |
| plain = re.sub(r"<[^>]+>", " ", report) | |
| assert "tempo" in plain, "report omits the tempo analysis" | |
| tempo_context = plain | |
| mean_match = re.search(r"(?:mean|average|均值|平均)\s*[:=]?\s*(-?\d+(?:\.\d+)?)", tempo_context) | |
| median_match = re.search(r"(?:median|中位(?:数)?)\s*[:=]?\s*(-?\d+(?:\.\d+)?)", tempo_context) | |
| assert mean_match, "report does not label a tempo mean" | |
| assert median_match, "report does not label a tempo median" | |
| assert contains_rounded_value([float(mean_match.group(1))], tempo_mean), ( | |
| f"wrong tempo mean: expected {tempo_mean}, got {mean_match.group(1)}" | |
| ) | |
| assert contains_rounded_value([float(median_match.group(1))], tempo_median), ( | |
| f"wrong tempo median: expected {tempo_median}, got {median_match.group(1)}" | |
| ) | |
| all_cases = ( | |
| ("ENHANCED_CASE_1", enhanced_case_1), | |
| ("ENHANCED_CASE_2", enhanced_case_2), | |
| ("ENHANCED_CASE_3", enhanced_case_3), | |
| ) | |
| selected = os.environ.get("ENHANCED_CASE") | |
| assert selected is None or selected in dict(all_cases), f"unknown ENHANCED_CASE: {selected}" | |
| failures = [] | |
| for case_id, validator in all_cases: | |
| if selected and case_id != selected: | |
| continue | |
| try: | |
| validator() | |
| print(f"PASS {case_id}") | |
| except Exception as error: # keep cases independently executable/reportable | |
| failures.append((case_id, error)) | |
| print(f"FAIL {case_id}: {error}") | |
| assert not failures, f"{len(failures)} enhanced case(s) failed" | |