Spaces:
Sleeping
Sleeping
Update app.py
Browse files53 unmodified lines54555657585960616263646566676869707172222 unmodified lines2952962972982993003013023033043053063073083093103113123134 unmodified lines31831932032132232332432532612 unmodified lines3393403413423433443 unmodified lines34834935035135235315 unmodified lines3693703713723733743753763773783798 unmodified lines38838939039139239339439539639739839940040140240340440513 unmodified lines41942042142242342442542642742842943043143243343421 unmodified lines45645745845946046146246346410 unmodified lines4754764774784794807 unmodified lines4884894904914924934944954964974984995005015025035045055065074 unmodified lines51251351451551651751851952052152252352452552652752852953 unmodified linestry:fm.fontManager.addfont("kaiu.ttf")font_prop = fm.FontProperties(fname="kaiu.ttf")# 強制將 kaiu 設定為第一優先plt.rcParams['font.family'] = font_prop.get_name()print(f"✅ 成功載入本地 kaiu.ttf,已設為預設字型。")return font_propexcept Exception as e:print(f"⚠️ 載入 kaiu.ttf 失敗: {e}")# 2. 設定後備字型清單plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'KaiTi', 'SimHei', 'Arial Unicode MS', 'sans-serif'] + plt.rcParams['font.sans-serif']font_download_path = "NotoSansTC-Regular.otf"# 只有在真的沒有字型時才嘗試下載if not os.path.exists(font_download_path) and not any(f.name in ['Microsoft JhengHei', 'SimHei', 'KaiTi'] for f in fm.fontManager.ttflist):print("⬇️ 嘗試下載備用中文字型 (NotoSansTC)...")try:222 unmodified lines# === 統計摘要 ===def generate_stats_summary(df, cols):if df is None or not cols: return "<p style='color: #666;'>尚無資料</p>"stats_html = "<div style='display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 10px 0;'>"for col in cols[:4]:try:data = pd.to_numeric(df[col], errors='coerce').dropna()if len(data) == 0: continuestats_html += f"""<div style='background: linear-gradient(135deg, #8B5CF6 0%, #6D28D9 100%); padding: 20px; border-radius: 12px; color: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1);'><div style='font-size: 14px; opacity: 0.9; margin-bottom: 8px;'>{col}</div><div style='font-size: 28px; font-weight: bold; margin-bottom: 10px;'>{data.sum():,.0f}</div><div style='font-size: 12px; opacity: 0.8;'>平均: {data.mean():,.1f} | 最大: {data.max():,.0f}</div></div>"""except: continuestats_html += "</div>"return stats_html4 unmodified linesplot_df = df.copy()if time and time != "全部" and 'time_parsed' in plot_df.columns:plot_df = plot_df[plot_df['time_parsed'] == str(time)]plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)ranking = plot_df.groupby('region_normalized')[col].sum().reset_index()ranking = ranking.sort_values(col, ascending=True).tail(top_n)fig = go.Figure(go.Bar(x=ranking[col], y=ranking['region_normalized'], orientation='h',marker=dict(color=ranking[col], colorscale='Viridis', showscale=True),12 unmodified linesdf2 = df[df['time_parsed'] == str(time2)].copy()df1[col] = pd.to_numeric(df1[col], errors='coerce').fillna(0)df2[col] = pd.to_numeric(df2[col], errors='coerce').fillna(0)data1 = df1.groupby('region_normalized')[col].sum().reset_index()data2 = df2.groupby('region_normalized')[col].sum().reset_index()merged_data = data1.merge(data2, on='region_normalized', how='outer', suffixes=('_t1', '_t2')).fillna(0)3 unmodified lines)merged = target_gdf.merge(merged_data, left_on='name', right_on='region_normalized', how='left')merged['變化率'] = merged['變化率'].fillna(0)fig = px.choropleth(merged, geojson=merged.geometry, locations=merged.index, color='變化率',color_continuous_scale='RdYlGn', color_continuous_midpoint=0, projection="mercator",15 unmodified linesplot_df = plot_df[plot_df['time_parsed'] == str(time)]plot_df[col1] = pd.to_numeric(plot_df[col1], errors='coerce').fillna(0)plot_df[col2] = pd.to_numeric(plot_df[col2], errors='coerce').fillna(0)data1 = plot_df.groupby('region_normalized')[col1].sum().reset_index()data2 = plot_df.groupby('region_normalized')[col2].sum().reset_index()merged = target_gdf.merge(data1, left_on='name', right_on='region_normalized', how='left')merged = merged.merge(data2, left_on='name', right_on='region_normalized', how='left', suffixes=('', '_2'))merged[col1] = merged[col1].fillna(0); merged[col2] = merged[col2].fillna(0)fig = make_subplots(rows=1, cols=2, specs=[[{"type": "choropleth"}, {"type": "choropleth"}]], subplot_titles=(f"{col1}", f"{col2}"))fig.add_trace(go.Choropleth(geojson=eval(merged.geometry.to_json()), locations=merged.index, z=merged[col1], colorscale="Blues", name=col1, showscale=True, colorbar=dict(x=0.45, len=0.7)), row=1, col=1)fig.add_trace(go.Choropleth(geojson=eval(merged.geometry.to_json()), locations=merged.index, z=merged[col2], colorscale="OrRd", name=col2, showscale=True, colorbar=dict(x=1.0, len=0.7)), row=1, col=2)8 unmodified linesif df is None: raise gr.Error("請先上傳資料")if not col: raise gr.Error("未選擇指標")if target_gdf is None or target_gdf.empty: raise gr.Error("地圖圖資載入失敗")try:plot_df = df.copy()if time and time != "全部" and 'time_parsed' in plot_df.columns:plot_df = plot_df[plot_df['time_parsed'] == str(time)]plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)if agg_method == "加總": geo_data = plot_df.groupby('region_normalized')[col].sum().reset_index()elif agg_method == "平均": geo_data = plot_df.groupby('region_normalized')[col].mean().reset_index()elif agg_method == "最大值": geo_data = plot_df.groupby('region_normalized')[col].max().reset_index()merged = target_gdf.merge(geo_data, left_on='name', right_on='region_normalized', how='left')merged[col] = merged[col].fillna(0)colors = {"紅色系": "YlOrRd", "藍色系": "Blues", "綠色系": "Greens", "熱力圖": "Hot"}scale = colors.get(color_scheme.split()[0], "YlOrRd")fig = px.choropleth(merged, geojson=merged.geometry, locations=merged.index,color=col, color_continuous_scale=scale, projection="mercator",13 unmodified linesif time and time != "全部" and 'time_parsed' in plot_df.columns:plot_df = plot_df[plot_df['time_parsed'] == str(time)]plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)if agg_method == "加總": geo_data = plot_df.groupby('region_normalized')[col].sum().reset_index()elif agg_method == "平均": geo_data = plot_df.groupby('region_normalized')[col].mean().reset_index()merged = target_gdf.merge(geo_data, left_on='name', right_on='region_normalized', how='left')merged[col] = merged[col].fillna(0)fig, ax = plt.subplots(figsize=(15, 15))cmap_map = {"紅色系": "OrRd", "藍色系": "Blues", "綠色系": "Greens", "熱力圖": "hot_r"}merged.plot(column=col, cmap=cmap_map.get(color_scheme, "OrRd"), linewidth=0.5, ax=ax, edgecolor='0.5', legend=True)title_font = fm.FontProperties(fname="kaiu.ttf") if os.path.exists("kaiu.ttf") else Noneif title_font: ax.set_title(f"{col} - 地圖 ({time})", fontproperties=title_font, size=24)else: ax.set_title(f"{col} - 地圖 ({time})", size=24)ax.set_axis_off()output_path = tempfile.mktemp(suffix=".png")plt.savefig(output_path, dpi=300, bbox_inches='tight')21 unmodified linestry: trend_df['time_sort'] = pd.to_numeric(trend_df['time_parsed'])except: trend_df['time_sort'] = trend_df['time_parsed']grouped = trend_df.groupby('time_sort')[col].sum().reset_index().sort_values('time_sort')secondary_y = True; line_data = Noneif line_metric == "年增率 (%)": line_data = grouped[col].pct_change() * 100elif line_metric == "3年移動平均": line_data = grouped[col].rolling(window=3).mean(); secondary_y = Falsex_data = grouped['time_sort'].astype(str)fig = make_subplots(specs=[[{"secondary_y": True}]])fig.add_trace(go.Bar(x=x_data, y=grouped[col], name=f"{col} (數量)", marker_color='rgb(55, 83, 109)', opacity=0.6), secondary_y=False)10 unmodified linesif time_col and time_col in df.columns: df['time_gif_parsed'] = df[time_col].astype(str)elif 'time_parsed' in df.columns: df['time_gif_parsed'] = df['time_parsed']else: return Nonetry:plot_df = df.copy()plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)7 unmodified linesexcept: selected_times = all_timesif sort_order == "時間反序 (新 -> 舊)": selected_times.reverse()if len(selected_times) < 2: raise gr.Error("時間點過少")agg_all = plot_df.groupby(['time_gif_parsed', 'region_normalized'])[col].sum().reset_index()vmin = agg_all[col].min(); vmax = agg_all[col].max()cmap_map = {"紅色系": "OrRd", "藍色系": "Blues", "綠色系": "Greens", "熱力圖": "hot_r"}cmap = cmap_map.get(color_scheme.split()[0], "OrRd")frames = []title_font = fm.FontProperties(fname="kaiu.ttf") if os.path.exists("kaiu.ttf") else Nonefor t in progress.tqdm(selected_times, desc="繪製圖框"):df_t = agg_all[agg_all['time_gif_parsed'] == t]merged = target_gdf.merge(df_t, left_on='name', right_on='region_normalized', how='left')merged[col] = merged[col].fillna(0)fig, ax = plt.subplots(figsize=(8, 8))merged.plot(column=col, cmap=cmap, linewidth=0.8, ax=ax, edgecolor='0.8', vmin=vmin, vmax=vmax)if title_font: ax.set_title(f"{col} - {t}", fontproperties=title_font, size=20)else: ax.set_title(f"{col} - {t}", size=20)ax.set_axis_off()buf = io.BytesIO(); plt.savefig(buf, format='png', dpi=100, bbox_inches='tight'); buf.seek(0)frames.append(Image.open(buf)); plt.close(fig)4 unmodified lines# === Gradio 介面 ===# 注意:這裡不將 css 傳入 Blocks,而是用 HTML 注入的方式,保證所有舊版本兼容custom_css = """body { font-family: 'Microsoft JhengHei', 'Noto Sans TC', sans-serif; background-color: #f3f4f6; }.gradio-container { max-width: 1200px !important; margin: auto; }h1 { color: #5B21B6; }"""with gr.Blocks(title="臺灣 Open Data 視覺化儀表板", analytics_enabled=False) as demo:# === 萬用 CSS 注入法 (直接寫在 HTML 裡) ===gr.HTML(f"<style>{custom_css}</style>")gr.HTML("""<div style="text-align: center; margin-bottom: 2rem; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"><h1 style="color: #5B21B6; font-size: 2.5rem; margin-bottom: 0.5rem; font-family: 'Microsoft JhengHei', sans-serif;">🇹🇼 臺灣 Open Data 視覺化儀表板</h1>53 unmodified lines5455565758596061626364656667686970222 unmodified lines2932942952962972982993003013023033043053063073083093103113123133143153163173183193204 unmodified lines32532632732832933033133233333433512 unmodified lines3483493503513523533543 unmodified lines35835936036136236336415 unmodified lines3803813823833843853863873883893903913928 unmodified lines40140240340440540640740840941041141241341441541641741841942042142242342413 unmodified lines43843944044144244344444544644744844945045145245345445545645745845946021 unmodified lines48248348448548648748848949049149210 unmodified lines5035045055065075085097 unmodified lines5175185195205215225235245255265275285295305315325335345355365375385395405415425434 unmodified lines54854955055155255355455553 unmodified linestry:fm.fontManager.addfont("kaiu.ttf")font_prop = fm.FontProperties(fname="kaiu.ttf")plt.rcParams['font.family'] = font_prop.get_name()print(f"✅ 成功載入本地 kaiu.ttf,已設為預設字型。")return font_propexcept Exception as e:print(f"⚠️ 載入 kaiu.ttf 失敗: {e}")# 2. 如果沒有 kaiu.ttf,才去設定系統字型或下載plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'KaiTi', 'SimHei', 'Arial Unicode MS', 'sans-serif'] + plt.rcParams['font.sans-serif']font_download_path = "NotoSansTC-Regular.otf"if not os.path.exists(font_download_path) and not any(f.name in ['Microsoft JhengHei', 'SimHei', 'KaiTi'] for f in fm.fontManager.ttflist):print("⬇️ 嘗試下載備用中文字型 (NotoSansTC)...")try:222 unmodified lines# === 統計摘要 ===def generate_stats_summary(df, cols):if df is None or not cols:return "<p style='color: #666;'>尚無資料</p>"stats_html = "<div style='display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 10px 0;'>"for col in cols[:4]:try:data = pd.to_numeric(df[col], errors='coerce').dropna()if len(data) == 0: continuestats_html += f"""<div style='background: linear-gradient(135deg, #8B5CF6 0%, #6D28D9 100%);padding: 20px; border-radius: 12px; color: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1);'><div style='font-size: 14px; opacity: 0.9; margin-bottom: 8px;'>{col}</div><div style='font-size: 28px; font-weight: bold; margin-bottom: 10px;'>{data.sum():,.0f}</div><div style='font-size: 12px; opacity: 0.8;'>平均: {data.mean():,.1f} | 最大: {data.max():,.0f}</div></div>"""except: continuestats_html += "</div>"return stats_html4 unmodified linesplot_df = df.copy()if time and time != "全部" and 'time_parsed' in plot_df.columns:plot_df = plot_df[plot_df['time_parsed'] == str(time)]plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)ranking = plot_df.groupby('region_normalized')[col].sum().reset_index()ranking = ranking.sort_values(col, ascending=True).tail(top_n)fig = go.Figure(go.Bar(x=ranking[col], y=ranking['region_normalized'], orientation='h',marker=dict(color=ranking[col], colorscale='Viridis', showscale=True),12 unmodified linesdf2 = df[df['time_parsed'] == str(time2)].copy()df1[col] = pd.to_numeric(df1[col], errors='coerce').fillna(0)df2[col] = pd.to_numeric(df2[col], errors='coerce').fillna(0)data1 = df1.groupby('region_normalized')[col].sum().reset_index()data2 = df2.groupby('region_normalized')[col].sum().reset_index()merged_data = data1.merge(data2, on='region_normalized', how='outer', suffixes=('_t1', '_t2')).fillna(0)3 unmodified lines)merged = target_gdf.merge(merged_data, left_on='name', right_on='region_normalized', how='left')merged['變化率'] = merged['變化率'].fillna(0)fig = px.choropleth(merged, geojson=merged.geometry, locations=merged.index, color='變化率',color_continuous_scale='RdYlGn', color_continuous_midpoint=0, projection="mercator",15 unmodified linesplot_df = plot_df[plot_df['time_parsed'] == str(time)]plot_df[col1] = pd.to_numeric(plot_df[col1], errors='coerce').fillna(0)plot_df[col2] = pd.to_numeric(plot_df[col2], errors='coerce').fillna(0)data1 = plot_df.groupby('region_normalized')[col1].sum().reset_index()data2 = plot_df.groupby('region_normalized')[col2].sum().reset_index()merged = target_gdf.merge(data1, left_on='name', right_on='region_normalized', how='left')merged = merged.merge(data2, left_on='name', right_on='region_normalized', how='left', suffixes=('', '_2'))merged[col1] = merged[col1].fillna(0); merged[col2] = merged[col2].fillna(0)fig = make_subplots(rows=1, cols=2, specs=[[{"type": "choropleth"}, {"type": "choropleth"}]], subplot_titles=(f"{col1}", f"{col2}"))fig.add_trace(go.Choropleth(geojson=eval(merged.geometry.to_json()), locations=merged.index, z=merged[col1], colorscale="Blues", name=col1, showscale=True, colorbar=dict(x=0.45, len=0.7)), row=1, col=1)fig.add_trace(go.Choropleth(geojson=eval(merged.geometry.to_json()), locations=merged.index, z=merged[col2], colorscale="OrRd", name=col2, showscale=True, colorbar=dict(x=1.0, len=0.7)), row=1, col=2)8 unmodified linesif df is None: raise gr.Error("請先上傳資料")if not col: raise gr.Error("未選擇指標")if target_gdf is None or target_gdf.empty: raise gr.Error("地圖圖資載入失敗")try:plot_df = df.copy()if time and time != "全部" and 'time_parsed' in plot_df.columns:plot_df = plot_df[plot_df['time_parsed'] == str(time)]plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)if agg_method == "加總": geo_data = plot_df.groupby('region_normalized')[col].sum().reset_index()elif agg_method == "平均": geo_data = plot_df.groupby('region_normalized')[col].mean().reset_index()elif agg_method == "最大值": geo_data = plot_df.groupby('region_normalized')[col].max().reset_index()merged = target_gdf.merge(geo_data, left_on='name', right_on='region_normalized', how='left')merged[col] = merged[col].fillna(0)colors = {"紅色系": "YlOrRd", "藍色系": "Blues", "綠色系": "Greens", "熱力圖": "Hot"}scale = colors.get(color_scheme.split()[0], "YlOrRd")fig = px.choropleth(merged, geojson=merged.geometry, locations=merged.index,color=col, color_continuous_scale=scale, projection="mercator",13 unmodified linesif time and time != "全部" and 'time_parsed' in plot_df.columns:plot_df = plot_df[plot_df['time_parsed'] == str(time)]plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)if agg_method == "加總": geo_data = plot_df.groupby('region_normalized')[col].sum().reset_index()elif agg_method == "平均": geo_data = plot_df.groupby('region_normalized')[col].mean().reset_index()merged = target_gdf.merge(geo_data, left_on='name', right_on='region_normalized', how='left')merged[col] = merged[col].fillna(0)fig, ax = plt.subplots(figsize=(15, 15))cmap_map = {"紅色系": "OrRd", "藍色系": "Blues", "綠色系": "Greens", "熱力圖": "hot_r"}merged.plot(column=col, cmap=cmap_map.get(color_scheme, "OrRd"), linewidth=0.5, ax=ax, edgecolor='0.5', legend=True)title_font = fm.FontProperties(fname="kaiu.ttf") if os.path.exists("kaiu.ttf") else Noneif title_font:ax.set_title(f"{col} - 地圖 ({time})", fontproperties=title_font, size=24)else:ax.set_title(f"{col} - 地圖 ({time})", size=24)ax.set_axis_off()output_path = tempfile.mktemp(suffix=".png")plt.savefig(output_path, dpi=300, bbox_inches='tight')21 unmodified linestry: trend_df['time_sort'] = pd.to_numeric(trend_df['time_parsed'])except: trend_df['time_sort'] = trend_df['time_parsed']grouped = trend_df.groupby('time_sort')[col].sum().reset_index().sort_values('time_sort')secondary_y = True; line_data = Noneif line_metric == "年增率 (%)": line_data = grouped[col].pct_change() * 100elif line_metric == "3年移動平均": line_data = grouped[col].rolling(window=3).mean(); secondary_y = Falsex_data = grouped['time_sort'].astype(str)fig = make_subplots(specs=[[{"secondary_y": True}]])fig.add_trace(go.Bar(x=x_data, y=grouped[col], name=f"{col} (數量)", marker_color='rgb(55, 83, 109)', opacity=0.6), secondary_y=False)10 unmodified linesif time_col and time_col in df.columns: df['time_gif_parsed'] = df[time_col].astype(str)elif 'time_parsed' in df.columns: df['time_gif_parsed'] = df['time_parsed']else: return Nonetry:plot_df = df.copy()plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)7 unmodified linesexcept: selected_times = all_timesif sort_order == "時間反序 (新 -> 舊)": selected_times.reverse()if len(selected_times) < 2: raise gr.Error("時間點過少")agg_all = plot_df.groupby(['time_gif_parsed', 'region_normalized'])[col].sum().reset_index()vmin = agg_all[col].min(); vmax = agg_all[col].max()cmap_map = {"紅色系": "OrRd", "藍色系": "Blues", "綠色系": "Greens", "熱力圖": "hot_r"}cmap = cmap_map.get(color_scheme.split()[0], "OrRd")frames = []title_font = fm.FontProperties(fname="kaiu.ttf") if os.path.exists("kaiu.ttf") else Nonefor t in progress.tqdm(selected_times, desc="繪製圖框"):df_t = agg_all[agg_all['time_gif_parsed'] == t]merged = target_gdf.merge(df_t, left_on='name', right_on='region_normalized', how='left')merged[col] = merged[col].fillna(0)fig, ax = plt.subplots(figsize=(8, 8))merged.plot(column=col, cmap=cmap, linewidth=0.8, ax=ax, edgecolor='0.8', vmin=vmin, vmax=vmax)if title_font:ax.set_title(f"{col} - {t}", fontproperties=title_font, size=20)else:ax.set_title(f"{col} - {t}", size=20)ax.set_axis_off()buf = io.BytesIO(); plt.savefig(buf, format='png', dpi=100, bbox_inches='tight'); buf.seek(0)frames.append(Image.open(buf)); plt.close(fig)4 unmodified lines# === Gradio 介面 ===with gr.Blocks(title="臺灣 Open Data 視覺化儀表板", analytics_enabled=False) as demo:gr.HTML("""<div style="text-align: center; margin-bottom: 2rem; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"><h1 style="color: #5B21B6; font-size: 2.5rem; margin-bottom: 0.5rem; font-family: 'Microsoft JhengHei', sans-serif;">🇹🇼 臺灣 Open Data 視覺化儀表板</h1>
app.py+47-21