File size: 7,778 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"""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"