File size: 8,824 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#!/usr/bin/env python3
"""Independently recompute Spotify tables and inspect each SVG chart."""

import csv
import html
import math
import os
import re
import shutil
import statistics
import subprocess
import sys
import tempfile
from collections import Counter, defaultdict
from html.parser import HTMLParser
from pathlib import Path


def csv_rows(path):
    with path.open(newline="", encoding="utf-8-sig") as handle:
        reader = csv.DictReader(handle)
        return reader.fieldnames, list(reader)


class Charts(HTMLParser):
    def __init__(self):
        super().__init__()
        self.current = None
        self.charts = {}

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag == "svg" and "data-chart" in attrs:
            assert self.current is None
            self.current = attrs["data-chart"]
            assert self.current not in self.charts, "duplicate chart"
            self.charts[self.current] = []
        elif tag == "rect" and self.current is not None:
            self.charts[self.current].append(attrs)

    def handle_endtag(self, tag):
        if tag == "svg":
            self.current = None


def check_chart(charts, kind, expected):
    assert kind in charts, f"missing {kind} chart"
    rects = charts[kind]
    assert len(rects) == len(expected), f"{kind} bar count mismatch"
    positive = []
    by_key = {str(key): value for key, value in expected}
    seen = set()
    for rect in rects:
        key = rect.get('data-key')
        assert key in by_key and key not in seen, f'{kind} key missing or duplicated'
        seen.add(key)
        value = by_key[key]
        actual = float(rect["data-value"])
        assert abs(actual - value) <= 5e-5, f"{kind} value mismatch for {key}"
        height = float(rect["height"])
        assert float(rect["width"]) > 0 and height >= 0, f"{kind} invalid bar geometry"
        assert math.isfinite(height), f"{kind} bar height is not finite"
        if value == 0:
            assert height == 0, f"{kind} zero value has nonzero bar"
        else:
            assert height > 0, f"{kind} nonzero value has invisible bar"
            positive.append(height / value)
    if positive:
        assert max(positive) - min(positive) <= 0.01 * max(positive), (
            f"{kind} bar heights are not proportional to values"
        )


def check(root):
    fields, source = csv_rows(root / "spotify_songs.csv")
    assert fields is not None
    filtered = []
    for row in source:
        year = int(row["track_album_release_date"][:4])
        if year >= 2000:
            score = (float(row["energy"]) + float(row["valence"])) / 2
            filtered.append((row, year, score))
    out_fields, out = csv_rows(root / "filtered_songs.csv")
    assert out_fields == fields + ["release_year", "activity_score"]
    assert len(out) == len(filtered)
    for got, (row, year, score) in zip(out, filtered):
        assert all(got[key] == row[key] for key in fields), "filtered row differs from source"
        assert int(got["release_year"]) == year
        assert re.fullmatch(r"-?\d+\.\d{4}", got["activity_score"])
        assert abs(float(got["activity_score"]) - round(score, 4)) <= 1e-10

    top_fields, top = csv_rows(root / "top_5_activity_songs.csv")
    assert top_fields is not None and len(top) == min(5, len(filtered))
    assert {'track_name', 'track_artist', 'release_year', 'activity_score'} <= set(top_fields)
    expected_top = [filtered[i] for i in sorted(range(len(filtered)), key=lambda i: -filtered[i][2])[:5]]
    for got, (row, year, score) in zip(top, expected_top):
        assert all(got[key] == row[key] for key in ('track_name', 'track_artist'))
        assert int(got["release_year"]) == year
        assert re.fullmatch(r"-?\d+\.\d{4}", got['activity_score'])
        assert abs(float(got["activity_score"]) - round(score, 4)) <= 1e-10

    years = Counter(year for _, year, _ in filtered)
    annual_expected = [(year, years[year]) for year in sorted(years)]
    header, annual = csv_rows(root / "annual_counts.csv")
    assert header == ["release_year", "count"]
    assert [(int(r["release_year"]), int(r["count"])) for r in annual] == annual_expected

    grouped = defaultdict(list)
    for row, _, _ in filtered:
        grouped[row["playlist_genre"]].append(float(row["danceability"]))
    genre_expected = [(name, round(statistics.mean(values), 4)) for name, values in sorted(grouped.items())]
    header, genre = csv_rows(root / "genre_danceability.csv")
    assert header == ["playlist_genre", "mean_danceability"]
    assert [(r["playlist_genre"], float(r["mean_danceability"])) for r in genre] == genre_expected

    tempos = [float(row["tempo"]) for row, _, _ in filtered]
    bin_expected = []
    if tempos:
        first = math.floor(min(tempos) / 10) * 10
        last = math.floor(max(tempos) / 10) * 10
        bin_expected = [(start, start + 10, sum(start <= value < start + 10 for value in tempos))
                        for start in range(first, last + 1, 10)]
    header, bins = csv_rows(root / "tempo_bins.csv")
    assert header == ["bin_start", "bin_end", "count"]
    assert [(int(r["bin_start"]), int(r["bin_end"]), int(r["count"])) for r in bins] == bin_expected

    report = (root / "report.html").read_text(encoding="utf-8")
    charts = Charts()
    charts.feed(report)
    assert set(charts.charts) == {"annual", "genre", "tempo"}
    check_chart(charts.charts, "annual", annual_expected)
    check_chart(charts.charts, "genre", genre_expected)
    check_chart(charts.charts, "tempo", [(start, count) for start, _, count in bin_expected])
    visible = html.unescape(re.sub(r"<[^>]*>", " ", report))
    for row, _, _ in expected_top:
        assert row["track_name"] in visible and row["track_artist"] in visible, "top song missing from report"
    if tempos:
        mean = re.search(r"(?:tempo\s*)?(?:mean|average|均值|平均值?)\s*[:=:]?\s*(-?\d+(?:\.\d+)?)", visible, re.I)
        median = re.search(r"(?:median|中位数?)\s*[:=:]?\s*(-?\d+(?:\.\d+)?)", visible, re.I)
        assert mean and median, "tempo mean/median not labeled"
        assert abs(float(mean.group(1)) - statistics.mean(tempos)) <= 5e-4
        assert abs(float(median.group(1)) - statistics.median(tempos)) <= 5e-4


ARTIFACTS = ("filtered_songs.csv", "top_5_activity_songs.csv", "annual_counts.csv",
             "genre_danceability.csv", "tempo_bins.csv", "report.html")


def clear_outputs(root):
    for name in ARTIFACTS:
        (root / name).unlink(missing_ok=True)


def validate_rendered_report(root, name):
    verifier = Path(__file__).resolve().with_name("validate_aaav_dynamic.js")
    env = {**os.environ, "SPOTIFY_SCREENSHOT": name}
    subprocess.run(["node", str(verifier)], cwd=root, env=env, check=True, timeout=30)


def mutation(root):
    with tempfile.TemporaryDirectory(prefix="task44-input-") as tmp:
        work = Path(tmp) / "candidate"
        shutil.copytree(root, work, ignore=shutil.ignore_patterns("tests", "logs", "__pycache__", "*.pyc"))
        fields, rows = csv_rows(work / "spotify_songs.csv")
        assert fields and len(rows) >= 2
        target = next(row for row in rows if int(row["track_album_release_date"][:4]) >= 2000)
        target["track_album_release_date"] = "2001-01-01"
        target["energy"] = "1.0"
        target["valence"] = "1.0"
        target["danceability"] = "0.1"
        target["tempo"] = "180.0"
        with (work / "spotify_songs.csv").open("w", newline="", encoding="utf-8") as handle:
            writer = csv.DictWriter(handle, fieldnames=fields)
            writer.writeheader()
            writer.writerows(rows)
        clear_outputs(work)
        result = subprocess.run([sys.executable, "solve.py"], cwd=work, capture_output=True,
                                text=True, timeout=45)
        assert result.returncode == 0, f"candidate failed changed input: {result.stderr}"
        check(work)
        validate_rendered_report(work, "spotify-report-mutated")
        # The public empty-filter case must produce headers and valid empty charts.
        for row in rows:
            row['track_album_release_date'] = '1999-01-01'
        with (work / 'spotify_songs.csv').open('w', newline='', encoding='utf-8') as handle:
            writer = csv.DictWriter(handle, fieldnames=fields)
            writer.writeheader()
            writer.writerows(rows)
        result = subprocess.run([sys.executable, 'solve.py'], cwd=work, capture_output=True, text=True, timeout=45)
        assert result.returncode == 0, 'candidate failed the empty filtered dataset'
        check(work)
        validate_rendered_report(work, "spotify-report-empty")


if __name__ == "__main__":
    check(Path.cwd())
    mutation(Path.cwd())
    print("Spotify data tables, charts and input mutation passed")