Download task_028/solution/code/solve.py from Lego-X/UXInteract: direct link, hf CLI and curl.
- Browser
- Download file 4.92 kB
-
https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_028/solution/code/solve.py
- Command line
-
hf download hf://datasets/Lego-X/UXInteract/task_028/solution/code/solve.py
-
curl -L -o solve.py https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_028/solution/code/solve.py
4.92 kB
| #!/usr/bin/env python3 | |
| """Compute Spotify summaries and render data-driven inline SVG charts.""" | |
| import csv | |
| import html | |
| import math | |
| import statistics | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent | |
| def write_csv(name, fields, rows): | |
| with (ROOT / name).open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=fields) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| def bar_chart(kind, items, title): | |
| width = max(420, 52 * len(items) + 50) | |
| baseline = 145 | |
| maximum = max((float(value) for _, value in items), default=0) or 1 | |
| bars = [] | |
| for i, (key, value) in enumerate(items): | |
| height = 110 * float(value) / maximum | |
| x = 32 + i * 52 | |
| y = baseline - height | |
| safe_key = html.escape(str(key), quote=True) | |
| bars.append( | |
| f'<rect x="{x}" y="{y:.4f}" width="28" height="{height:.4f}" ' | |
| f'fill="#3779bd" data-key="{safe_key}" data-value="{float(value):.8f}"/>' | |
| f'<text data-value-label="{safe_key}" x="{x}" y="{y-5:.4f}" font-size="10">{float(value):.4f}</text>' | |
| f'<text x="{x}" y="165" font-size="10">{safe_key}</text>' | |
| ) | |
| return ( | |
| f'<figure><figcaption>{html.escape(title)}</figcaption><svg data-chart="{kind}" ' | |
| f'viewBox="0 0 {width} 180" role="img" aria-label="{html.escape(title, quote=True)}">' | |
| f'<line x1="25" y1="145" x2="{width - 10}" y2="145" stroke="#333"/>' | |
| + ''.join(bars) + '</svg></figure>' | |
| ) | |
| def main(): | |
| with (ROOT / "spotify_songs.csv").open(newline="", encoding="utf-8-sig") as handle: | |
| reader = csv.DictReader(handle) | |
| original_fields = list(reader.fieldnames or []) | |
| source_rows = list(reader) | |
| filtered = [] | |
| for row in source_rows: | |
| year = int(row["track_album_release_date"][:4]) | |
| if year < 2000: | |
| continue | |
| score = (float(row["energy"]) + float(row["valence"])) / 2 | |
| filtered.append((row, year, score)) | |
| output_rows = [{**row, "release_year": year, "activity_score": f"{score:.4f}"} | |
| for row, year, score in filtered] | |
| write_csv("filtered_songs.csv", original_fields + ["release_year", "activity_score"], output_rows) | |
| top = sorted(enumerate(filtered), key=lambda item: -item[1][2])[:5] | |
| top_rows = [output_rows[index] for index, _ in top] | |
| write_csv("top_5_activity_songs.csv", original_fields + ["release_year", "activity_score"], top_rows) | |
| years = Counter(year for _, year, _ in filtered) | |
| annual = [{"release_year": year, "count": years[year]} for year in sorted(years)] | |
| write_csv("annual_counts.csv", ["release_year", "count"], annual) | |
| genre_values = defaultdict(list) | |
| for row, _, _ in filtered: | |
| genre_values[row["playlist_genre"]].append(float(row["danceability"])) | |
| genre = [{"playlist_genre": key, "mean_danceability": f"{statistics.mean(genre_values[key]):.4f}"} | |
| for key in sorted(genre_values)] | |
| write_csv("genre_danceability.csv", ["playlist_genre", "mean_danceability"], genre) | |
| tempos = [float(row["tempo"]) for row, _, _ in filtered] | |
| bins = [] | |
| if tempos: | |
| first = math.floor(min(tempos) / 10) * 10 | |
| last = math.floor(max(tempos) / 10) * 10 | |
| for start in range(first, last + 1, 10): | |
| bins.append({"bin_start": start, "bin_end": start + 10, | |
| "count": sum(start <= tempo < start + 10 for tempo in tempos)}) | |
| write_csv("tempo_bins.csv", ["bin_start", "bin_end", "count"], bins) | |
| song_list = ''.join( | |
| f'<li>{html.escape(row["track_name"])} — {html.escape(row["track_artist"])}</li>' | |
| for row in top_rows | |
| ) | |
| tempo_mean = statistics.mean(tempos) if tempos else 0.0 | |
| tempo_median = statistics.median(tempos) if tempos else 0.0 | |
| page = ( | |
| '<!doctype html><html lang="en"><meta charset="utf-8"><title>Spotify analysis</title>' | |
| '<style>body{font:16px system-ui;max-width:960px;margin:2rem auto;padding:1rem}' | |
| 'svg{width:100%;max-width:900px;height:auto}figure{margin:1.5rem 0}</style>' | |
| '<h1>Spotify release_year and activity analysis</h1>' | |
| '<p>Filtered songs released in 2000 or later.</p>' | |
| '<h2>Top five by activity score</h2><ol>' + song_list + '</ol>' | |
| + bar_chart("annual", [(row["release_year"], row["count"]) for row in annual], "Annual song counts") | |
| + bar_chart("genre", [(row["playlist_genre"], row["mean_danceability"]) for row in genre], | |
| "Average danceability by playlist_genre") | |
| + bar_chart("tempo", [(row["bin_start"], row["count"]) for row in bins], "Tempo BPM histogram") | |
| + f'<p>tempo mean={tempo_mean:.4f}; median={tempo_median:.4f}</p></html>' | |
| ) | |
| (ROOT / "report.html").write_text(page, encoding="utf-8") | |
| if __name__ == "__main__": | |
| main() | |