Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
# 載入所有年度的資料
|
| 7 |
+
def load_all_attendance_data():
|
| 8 |
+
all_data = []
|
| 9 |
+
for year in range(1994, 2025): # 1993–1994 到 2023–2024
|
| 10 |
+
filename = f"nba_attendance_{year-1}-{year}.csv"
|
| 11 |
+
if os.path.exists(filename):
|
| 12 |
+
df = pd.read_csv(filename)
|
| 13 |
+
df["YEAR"] = f"{year-1}-{year}"
|
| 14 |
+
all_data.append(df)
|
| 15 |
+
return pd.concat(all_data, ignore_index=True)
|
| 16 |
+
|
| 17 |
+
# 整合資料
|
| 18 |
+
df_all = load_all_attendance_data()
|
| 19 |
+
|
| 20 |
+
# 整理球隊與年份選單
|
| 21 |
+
all_teams = sorted(df_all["TEAM"].unique())
|
| 22 |
+
all_years = sorted(df_all["YEAR"].unique())
|
| 23 |
+
|
| 24 |
+
# 主功能函式
|
| 25 |
+
def show_home_attendance(team, year):
|
| 26 |
+
# 找出指定年份與球隊的主場總人數
|
| 27 |
+
record = df_all[(df_all["TEAM"] == team) & (df_all["YEAR"] == year)]
|
| 28 |
+
if record.empty:
|
| 29 |
+
return f"{team} 在 {year} 沒有資料", None
|
| 30 |
+
|
| 31 |
+
total_attendance = record["HOME_TOTAL"].values[0]
|
| 32 |
+
|
| 33 |
+
# 產生直條圖:該隊從 1993-94 到 2023-24 的 HOME_TOTAL 變化
|
| 34 |
+
team_data = df_all[df_all["TEAM"] == team]
|
| 35 |
+
years = team_data["YEAR"]
|
| 36 |
+
totals = pd.to_numeric(team_data["HOME_TOTAL"].str.replace(',', ''), errors='coerce')
|
| 37 |
+
|
| 38 |
+
plt.figure(figsize=(10, 5))
|
| 39 |
+
plt.bar(years, totals)
|
| 40 |
+
plt.title(f"{team} HOME_TOTAL Attendance Over Years")
|
| 41 |
+
plt.xlabel("Season")
|
| 42 |
+
plt.ylabel("HOME_TOTAL")
|
| 43 |
+
plt.xticks(rotation=45)
|
| 44 |
+
plt.tight_layout()
|
| 45 |
+
|
| 46 |
+
# 將圖表轉為圖片傳回
|
| 47 |
+
return f"{team} 在 {year} 年的主場總人數為:{total_attendance}", plt.gcf()
|
| 48 |
+
|
| 49 |
+
# Gradio 介面
|
| 50 |
+
interface = gr.Interface(
|
| 51 |
+
fn=show_home_attendance,
|
| 52 |
+
inputs=[
|
| 53 |
+
gr.Dropdown(choices=all_teams, label="選擇球隊"),
|
| 54 |
+
gr.Dropdown(choices=all_years, label="選擇年份")
|
| 55 |
+
],
|
| 56 |
+
outputs=[
|
| 57 |
+
gr.Textbox(label="主場總人數"),
|
| 58 |
+
gr.Plot(label="歷年主場總人數變化")
|
| 59 |
+
],
|
| 60 |
+
title="NBA 主場觀眾總人數查詢器",
|
| 61 |
+
description="選擇一支球隊與一個年份,查看主場總觀眾人數,並呈現其歷年趨勢圖"
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
interface.launch()
|