Spaces:
Sleeping
Sleeping
Update app.py
Browse files23 unmodified lines24252627282930313233343536373839404142434445464748495051525354555657585960619 unmodified lines717273747576774 unmodified lines82838485868788899091929394959697989910010110210310424 unmodified lines1291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062071 unmodified line2092102112122132142152162172182192202214 unmodified lines22622722822923023123223323423523623723823924024124210 unmodified lines25325425525625725825926026126226326426526626726824 unmodified lines2932942952962972982993004 unmodified lines3053063073083093103113123133143153163173183193203213223233243253262 unmodified lines32933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437511 unmodified lines38738838939039139239339416 unmodified lines4114124134144154164179 unmodified lines42742842943043143243343443543643723 unmodified lines# === 0. 設定中文字型 (優先使用上傳的 kaiu.ttf) ===def set_custom_font():font_filename = "kaiu.ttf"# 檢查檔案是否存在if os.path.exists(font_filename):try:# 1. 加入字型管理員fm.fontManager.addfont(font_filename)# 2. 取得字型物件以獲取正確名稱 (有時候檔名跟內部名稱不一樣)font_prop = fm.FontProperties(fname=font_filename)font_name = font_prop.get_name()# 3. 設定為全域預設字型plt.rcParams['font.family'] = font_nameprint(f"✅ 成功載入字型: {font_filename} (名稱: {font_name})")return font_propexcept Exception as e:print(f"❌ 字型載入失敗: {e}")# 備用方案:嘗試使用系統字型plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'SimHei', 'Arial Unicode MS']return Noneelse:print(f"⚠️ 找不到 {font_filename},請確保已上傳該檔案。將使用系統預設字型。")plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'SimHei', 'Arial Unicode MS']return None# 執行字型設定CUSTOM_FONT_PROP = set_custom_font()# === 配置與常數 ===MAP_FILE = "twCounty2010.geo.json"# 1. 縣市代碼對照表COUNTY_CODE_MAP = {'65000': '新北市', '63000': '臺北市', '68000': '桃園市', '66000': '臺中市','67000': '臺南市', '64000': '高雄市', '10002': '宜蘭縣', '10004': '新竹縣',9 unmodified lines9007: '連江縣', 9020: '金門縣'}# 2. 縣市名稱標準化COUNTY_ALIASES = {'台北市': '臺北市', '台中市': '臺中市', '台南市': '臺南市', '台東縣': '臺東縣','台北': '臺北市', '台中': '臺中市', '台南': '臺南市', '台東': '臺東縣',4 unmodified lines'金門縣': '金門縣', '連江縣': '連江縣', '馬祖': '連江縣'}# 關鍵字設定TIME_FIELDS = ['year', 'Year', 'YEAR', '年', '年份', '年度', '民國','month', 'Month', 'MONTH', '月', '月份', 'date', 'Date', 'time']COUNTY_FIELDS = ['縣市', '縣市別', 'county', 'city', 'location', 'region', 'area','地區', '行政區', '代碼', 'code', 'id']NON_VALUE_KEYWORDS = ['code', 'id', 'number', 'serial', 'index', 'lat', 'lon', 'year', 'date']# === 基礎載入函數 (含地圖瘦身) ===def load_map_file():try:if not os.path.exists(MAP_FILE): return Nonegdf = gpd.read_file(MAP_FILE)if gdf.crs != "EPSG:4326": gdf = gdf.to_crs("EPSG:4326")# 地圖幾何簡化 (加速顯示)gdf['geometry'] = gdf['geometry'].simplify(tolerance=0.003, preserve_topology=True)gdf['name'] = gdf['name'].str.replace('台', '臺')return gdfexcept Exception as e:24 unmodified linesreturn filtered_colsdef smart_parse_data(df: pd.DataFrame):if df is None or df.empty: return None, "資料為空", [], [], [], "unknown"df_processed = df.copy()time_col = next((c for c in df.columns if any(k in str(c) for k in TIME_FIELDS)), None)if not time_col:for col in df.columns:if df[col].dtype in ['int64', 'float64']:sample = df[col].dropna().head()if not sample.empty and 80 < sample.mean() < 2100:time_col = colbreakavailable_times = []if time_col:df_processed['time_parsed'] = df_processed[time_col].astype(str)try:valid_times = df_processed[pd.to_numeric(df_processed[time_col], errors='coerce').notna()][time_col]sorted_times = sorted(valid_times.unique(), key=lambda x: float(x), reverse=True)available_times = [str(t) for t in sorted_times]except:available_times = sorted(df_processed['time_parsed'].unique(), reverse=True)county_col = Nonepotential_cols = [c for c in df.columns if any(k in str(c).lower() for k in COUNTY_FIELDS)]for col in df.columns:sample = df[col].dropna().head(10).astype(str).tolist()if not sample: continuehas_county_name = any('市' in s or '縣' in s for s in sample)has_county_code = Falsematch_count = 0for s in sample:s_clean = s.split('.')[0]if s_clean in COUNTY_CODE_MAP: match_count += 1if match_count > 0 and match_count / len(sample) > 0.5: has_county_code = Trueif has_county_name or has_county_code:county_col = colif col in potential_cols: breakif not county_col and potential_cols: county_col = potential_cols[0]counties = []mode = "generic"if county_col:df_processed['county_normalized'] = df_processed[county_col].apply(normalize_county_name)valid_rows = df_processed['county_normalized'] != ""counties = sorted(df_processed[valid_rows]['county_normalized'].unique().tolist())mode = "county"exclude = [county_col, time_col] if time_col else [county_col]numeric_cols = get_numeric_columns(df_processed, exclude)sample_val = df[county_col].iloc[0]if str(sample_val).strip() in COUNTY_CODE_MAP or str(sample_val).split('.')[0] in COUNTY_CODE_MAP:msg = f"✓ 偵測到縣市代碼欄位 '{county_col}'"else:msg = f"✓ 偵測到縣市名稱欄位 '{county_col}'"else:if any(re.search(r'(north|central|south|east)', c, re.IGNORECASE) for c in df.columns):mode = "regional"msg = "✓ 偵測到區域分區資料"numeric_cols = []else:msg = "⚠️ 未偵測到縣市欄位"exclude = [time_col] if time_col else []numeric_cols = get_numeric_columns(df_processed, exclude)return df_processed, msg, numeric_cols, available_times, counties, mode# === 處理上傳檔案 ===def process_uploaded_file(file_obj):if file_obj is None: return None, "請上傳檔案", [], [], [], Nonetry:file_path = file_obj.nameif file_path.endswith('.csv'):1 unmodified lineexcept: df = pd.read_csv(file_path, encoding='big5')elif file_path.endswith('.json'): df = pd.read_json(file_path)elif file_path.endswith('.xlsx'): df = pd.read_excel(file_path)else: return None, "不支援的格式", [], [], [], Noneprocessed_df, msg, cols, times, counties, mode = smart_parse_data(df)def_col = cols[0] if cols else Nonecounty_options = ["全國總計"] + counties if counties else []return processed_df, msg, gr.Dropdown(choices=cols, value=def_col), gr.Dropdown(choices=["全部"] + times, value="全部"), gr.Dropdown(choices=county_options, value="全國總計"), gr.Dataframe(value=df.head(10))except Exception as e: return None, f"錯誤: {e}", [], [], [], None# === 1. 繪製地圖 (Plotly) ===def generate_map(df, col, time, agg_method, color_scheme):4 unmodified linesplot_df = plot_df[plot_df['time_parsed'] == str(time)]if 'county_normalized' in plot_df.columns:plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)if agg_method == "加總": geo_data = plot_df.groupby('county_normalized')[col].sum().reset_index()elif agg_method == "平均": geo_data = plot_df.groupby('county_normalized')[col].mean().reset_index()elif agg_method == "最大值": geo_data = plot_df.groupby('county_normalized')[col].max().reset_index()merged = GDF.merge(geo_data, left_on='name', right_on='county_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", title=f"{col} - 地圖分布 ({time if time else '全部'})")fig.update_geos(fitbounds="locations", visible=False)fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0})10 unmodified linestrend_df[col] = pd.to_numeric(trend_df[col], errors='coerce').fillna(0)title_suffix = "全國總計"if selected_county and selected_county != "全國總計":if 'county_normalized' in trend_df.columns:trend_df = trend_df[trend_df['county_normalized'] == selected_county]title_suffix = selected_countytry: 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()grouped = grouped.sort_values('time_sort')secondary_y = Trueline_data = Noneif line_metric == "年增率 (%)": line_data = grouped[col].pct_change() * 100elif line_metric == "3年移動平均": line_data = grouped[col].rolling(window=3).mean(); secondary_y = Falseelif line_metric == "5年移動平均": line_data = grouped[col].rolling(window=5).mean(); secondary_y = False24 unmodified linesgrouped = trend_df.groupby('time_sort')[col].sum().reset_index()grouped = grouped.sort_values('time_sort')line_data = Noneuse_twinx = Trueif line_metric == "年增率 (%)": line_data = grouped[col].pct_change() * 100elif line_metric == "3年移動平均": line_data = grouped[col].rolling(window=3).mean(); use_twinx = Falseelif line_metric == "5年移動平均": line_data = grouped[col].rolling(window=5).mean(); use_twinx = False4 unmodified linesy_line = line_data.tolist() if line_data is not None else []fig, ax1 = plt.subplots(figsize=(12, 6))# 使用自訂字型 (如果有的話)if CUSTOM_FONT_PROP:title_font = CUSTOM_FONT_PROPtitle_font.set_size(14)else:title_font = {'size': 14}ax1.bar(x_data, y_bar, color='steelblue', alpha=0.6, label=f"{col} (數量)")ax1.set_ylabel("數量", color='steelblue')# 設定標題 (明確指定字型物件)if CUSTOM_FONT_PROP:ax1.set_title(f"{col} - 歷史趨勢圖 ({title_suffix})", fontproperties=CUSTOM_FONT_PROP, size=16)else:ax1.set_title(f"{col} - 歷史趨勢圖 ({title_suffix})", size=16)if use_twinx:ax2 = ax1.twinx()2 unmodified lineselse:ax1.plot(x_data, y_line, color='crimson', marker='o', linewidth=2, label=line_metric)ax1.legend(loc='upper left')plt.tight_layout()with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:plt.savefig(tmp.name, dpi=150)return tmp.nameexcept Exception as e:print(f"Export Error: {e}")return None# === 4. 產生 GIF 動態地圖 (Matplotlib + PIL) ===def generate_map_gif(df, col, color_scheme, fps, progress=gr.Progress()):if df is None or not col or GDF is None: return Noneif 'time_parsed' not in df.columns: return Nonetry:plot_df = df.copy()plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)try: times = sorted(plot_df['time_parsed'].unique(), key=lambda x: float(x))except: times = sorted(plot_df['time_parsed'].unique())if len(times) < 2: return Noneagg_all = plot_df.groupby(['time_parsed', 'county_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 = []for i, t in enumerate(progress.tqdm(times, desc="繪製圖框中...")):df_t = agg_all[agg_all['time_parsed'] == t]merged = GDF.merge(df_t, left_on='name', right_on='county_normalized', how='left')merged[col] = merged[col].fillna(0)fig, ax = plt.subplots(figsize=(10, 10))merged.plot(column=col, cmap=cmap, linewidth=0.8, ax=ax, edgecolor='0.8', vmin=vmin, vmax=vmax, legend=True, legend_kwds={'shrink': 0.6})# 設定標題 (明確指定字型)title_text = f"{col} - {t} 年"if CUSTOM_FONT_PROP:ax.set_title(title_text, fontproperties=CUSTOM_FONT_PROP, size=20)else:ax.set_title(title_text, size=20)ax.set_axis_off()buf = io.BytesIO()11 unmodified linesreturn None# === Gradio 介面 ===with gr.Blocks(title="台灣 Open Data 視覺化平台 (自訂字型版)") as demo:gr.Markdown("## 🇹🇼 台灣資料視覺化儀表板 (支援 kaiu.ttf)")current_df = gr.State()16 unmodified linesbtn_trend = gr.Button("更新趨勢圖", variant="primary")btn_export = gr.Button("📥 下載靜態全圖 (PNG)")with gr.Accordion("動態 GIF 設定", open=True):fps_slider = gr.Slider(minimum=1, maximum=5, value=2, step=1, label="播放速度 (FPS)")btn_gif = gr.Button("🎬 產生 GIF 動畫", variant="primary")9 unmodified lineswith gr.Tab("📋 資料預覽"):data_preview = gr.Dataframe()file_input.change(fn=process_uploaded_file, inputs=file_input, outputs=[current_df, status_box, col_selector, time_selector, trend_county, data_preview])btn_map.click(fn=generate_map, inputs=[current_df, col_selector, time_selector, agg_method, color_scheme], outputs=map_output)btn_trend.click(fn=generate_trend_chart, inputs=[current_df, col_selector, trend_county, line_metric_selector], outputs=trend_output)btn_export.click(fn=export_static_chart, inputs=[current_df, col_selector, trend_county, line_metric_selector], outputs=download_file)btn_gif.click(fn=generate_map_gif, inputs=[current_df, col_selector, color_scheme, fps_slider], outputs=gif_output)if __name__ == "__main__":demo.queue().launch()23 unmodified lines2425262728293031323334353637383940414243444546474849509 unmodified lines6061626364654 unmodified lines7071727374757677787980818283848586878824 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771 unmodified line1791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102114 unmodified lines21621721821922022122222322422522622722822910 unmodified lines24024124224324424524624724824925025125225324 unmodified lines2782792802812822832844 unmodified lines2892902912922932942952962972982992 unmodified lines30230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537611 unmodified lines38838939039139239339439516 unmodified lines4124134144154164174184194204214224234249 unmodified lines43443543643743843944044144244344444544644744844945045145245345445545645745845946023 unmodified lines# === 0. 設定中文字型 (優先使用上傳的 kaiu.ttf) ===def set_custom_font():font_filename = "kaiu.ttf"if os.path.exists(font_filename):try:fm.fontManager.addfont(font_filename)font_prop = fm.FontProperties(fname=font_filename)font_name = font_prop.get_name()plt.rcParams['font.family'] = font_nameprint(f"✅ 成功載入字型: {font_filename}")return font_propexcept Exception as e:print(f"❌ 字型載入失敗: {e}")plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'SimHei']return Noneelse:plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'SimHei']return NoneCUSTOM_FONT_PROP = set_custom_font()# === 配置與常數 ===MAP_FILE = "twCounty2010.geo.json"COUNTY_CODE_MAP = {'65000': '新北市', '63000': '臺北市', '68000': '桃園市', '66000': '臺中市','67000': '臺南市', '64000': '高雄市', '10002': '宜蘭縣', '10004': '新竹縣',9 unmodified lines9007: '連江縣', 9020: '金門縣'}COUNTY_ALIASES = {'台北市': '臺北市', '台中市': '臺中市', '台南市': '臺南市', '台東縣': '臺東縣','台北': '臺北市', '台中': '臺中市', '台南': '臺南市', '台東': '臺東縣',4 unmodified lines'金門縣': '金門縣', '連江縣': '連江縣', '馬祖': '連江縣'}TIME_FIELDS = ['year', 'Year', 'YEAR', '年', '年份', '年度', '民國','month', 'Month', 'MONTH', '月', '月份', 'date', 'Date', 'time']COUNTY_FIELDS = ['縣市', '縣市別', 'county', 'city', 'location', 'region', 'area','地區', '行政區', '代碼', 'code', 'id']NON_VALUE_KEYWORDS = ['code', 'id', 'number', 'serial', 'index', 'lat', 'lon', 'year', 'date']# === 載入與工具函數 ===def load_map_file():try:if not os.path.exists(MAP_FILE): return Nonegdf = gpd.read_file(MAP_FILE)if gdf.crs != "EPSG:4326": gdf = gdf.to_crs("EPSG:4326")gdf['geometry'] = gdf['geometry'].simplify(tolerance=0.003, preserve_topology=True)gdf['name'] = gdf['name'].str.replace('台', '臺')return gdfexcept Exception as e:24 unmodified linesreturn filtered_colsdef smart_parse_data(df: pd.DataFrame):if df is None or df.empty: return None, "資料為空", [], [], [], "unknown", []df_processed = df.copy()# 偵測所有可能的時間欄位possible_time_cols = [c for c in df.columns if any(k in str(c) for k in TIME_FIELDS)]# 若沒找到關鍵字,嘗試偵測數值範圍if not possible_time_cols:for col in df.columns:if df[col].dtype in ['int64', 'float64']:sample = df[col].dropna().head()if not sample.empty and 80 < sample.mean() < 2100:possible_time_cols.append(col)# 預設選第一個time_col = possible_time_cols[0] if possible_time_cols else Noneavailable_times = []if time_col:# 建立標準化時間欄位df_processed['time_parsed'] = df_processed[time_col].astype(str)try:# 嘗試數值排序valid_times = df_processed[pd.to_numeric(df_processed[time_col], errors='coerce').notna()][time_col]sorted_times = sorted(valid_times.unique(), key=lambda x: float(x), reverse=True) # 預設新到舊available_times = [str(t) for t in sorted_times]except:available_times = sorted(df_processed['time_parsed'].unique(), reverse=True)# 縣市偵測 (省略詳細邏輯,同前版)county_col = Nonepotential_cols = [c for c in df.columns if any(k in str(c).lower() for k in COUNTY_FIELDS)]for col in df.columns:sample = df[col].dropna().head(10).astype(str).tolist()if not sample: continueif any('市' in s or '縣' in s for s in sample): county_col = col; break# 簡易代碼檢查match_count = sum(1 for s in sample if str(s).split('.')[0] in COUNTY_CODE_MAP)if match_count > len(sample)*0.5: county_col = col; breakif not county_col and potential_cols: county_col = potential_cols[0]counties = []mode = "generic"if county_col:df_processed['county_normalized'] = df_processed[county_col].apply(normalize_county_name)counties = sorted(df_processed[df_processed['county_normalized']!=""]['county_normalized'].unique().tolist())mode = "county"exclude = [county_col, time_col] if time_col else [county_col]numeric_cols = get_numeric_columns(df_processed, exclude)msg = f"✓ 偵測成功 (縣市: {county_col})"else:msg = "⚠️ 未偵測到縣市欄位"exclude = [time_col] if time_col else []numeric_cols = get_numeric_columns(df_processed, exclude)return df_processed, msg, numeric_cols, available_times, counties, mode, possible_time_cols# === 處理上傳檔案 ===def process_uploaded_file(file_obj):if file_obj is None: return None, "請上傳檔案", [], [], [], [], [], []try:file_path = file_obj.nameif file_path.endswith('.csv'):1 unmodified lineexcept: df = pd.read_csv(file_path, encoding='big5')elif file_path.endswith('.json'): df = pd.read_json(file_path)elif file_path.endswith('.xlsx'): df = pd.read_excel(file_path)else: return None, "不支援的格式", [], [], [], [], [], []processed_df, msg, cols, times, counties, mode, time_cols = smart_parse_data(df)def_col = cols[0] if cols else None# 回傳預設值# 時間選單預設為全部 (None 供後端判斷)# 時間欄位預設第一個def_time_col = time_cols[0] if time_cols else None# 起迄時間預設 (取全部時間列表的頭尾)start_t = times[-1] if times else None # 最舊end_t = times[0] if times else None # 最新return (processed_df,msg,gr.Dropdown(choices=cols, value=def_col),gr.Dropdown(choices=["全部"] + times, value="全部"),gr.Dropdown(choices=["全國總計"] + counties, value="全國總計"),gr.Dataframe(value=df.head(10)),# 新增的回傳值 (GIF設定用)gr.Dropdown(choices=time_cols, value=def_time_col), # GIF 時間欄位gr.Dropdown(choices=times, value=start_t), # 起始時間gr.Dropdown(choices=times, value=end_t) # 結束時間)except Exception as e: return None, f"錯誤: {e}", [], [], [], [], [], [], []# === 1. 繪製地圖 (Plotly) ===def generate_map(df, col, time, agg_method, color_scheme):4 unmodified linesplot_df = plot_df[plot_df['time_parsed'] == str(time)]if 'county_normalized' in plot_df.columns:plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)if agg_method == "加總": geo_data = plot_df.groupby('county_normalized')[col].sum().reset_index()elif agg_method == "平均": geo_data = plot_df.groupby('county_normalized')[col].mean().reset_index()elif agg_method == "最大值": geo_data = plot_df.groupby('county_normalized')[col].max().reset_index()merged = GDF.merge(geo_data, left_on='name', right_on='county_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", title=f"{col} - 地圖分布 ({time if time else '全部'})")fig.update_geos(fitbounds="locations", visible=False)fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0})10 unmodified linestrend_df[col] = pd.to_numeric(trend_df[col], errors='coerce').fillna(0)title_suffix = "全國總計"if selected_county and selected_county != "全國總計":trend_df = trend_df[trend_df['county_normalized'] == selected_county]title_suffix = selected_countytry: 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()grouped = grouped.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 = Falseelif line_metric == "5年移動平均": line_data = grouped[col].rolling(window=5).mean(); secondary_y = False24 unmodified linesgrouped = trend_df.groupby('time_sort')[col].sum().reset_index()grouped = grouped.sort_values('time_sort')line_data = None; use_twinx = Trueif line_metric == "年增率 (%)": line_data = grouped[col].pct_change() * 100elif line_metric == "3年移動平均": line_data = grouped[col].rolling(window=3).mean(); use_twinx = Falseelif line_metric == "5年移動平均": line_data = grouped[col].rolling(window=5).mean(); use_twinx = False4 unmodified linesy_line = line_data.tolist() if line_data is not None else []fig, ax1 = plt.subplots(figsize=(12, 6))title_font = CUSTOM_FONT_PROP if CUSTOM_FONT_PROP else {'size': 14}ax1.bar(x_data, y_bar, color='steelblue', alpha=0.6, label=f"{col} (數量)")ax1.set_ylabel("數量", color='steelblue')if CUSTOM_FONT_PROP: ax1.set_title(f"{col} - 歷史趨勢圖 ({title_suffix})", fontproperties=CUSTOM_FONT_PROP, size=16)else: ax1.set_title(f"{col} - 歷史趨勢圖 ({title_suffix})", size=16)if use_twinx:ax2 = ax1.twinx()2 unmodified lineselse:ax1.plot(x_data, y_line, color='crimson', marker='o', linewidth=2, label=line_metric)ax1.legend(loc='upper left')plt.tight_layout()with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:plt.savefig(tmp.name, dpi=150); return tmp.nameexcept Exception as e: return None# === 4. 產生 GIF 動態地圖 (升級版:支援篩選與排序) ===def generate_map_gif(df, col, color_scheme, fps, time_col, start_t, end_t, sort_order, progress=gr.Progress()):if df is None or not col or GDF is None: return None# 確保使用使用者指定的「時間欄位」if time_col and time_col in df.columns:target_time_col = time_col# 暫時建立一個 parsed 欄位供排序用df['time_gif_parsed'] = df[target_time_col].astype(str)elif 'time_parsed' in df.columns:target_time_col = 'time_parsed'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)# 1. 取得時間序列try:# 嘗試數值排序all_times = sorted(plot_df['time_gif_parsed'].unique(), key=lambda x: float(x))except:all_times = sorted(plot_df['time_gif_parsed'].unique())# 2. 篩選起迄時間# 找出 indextry:idx_start = all_times.index(str(start_t)) if start_t in all_times else 0idx_end = all_times.index(str(end_t)) if end_t in all_times else len(all_times)-1# 確保 start <= end,否則交換if idx_start > idx_end: idx_start, idx_end = idx_end, idx_startselected_times = all_times[idx_start : idx_end + 1]except:selected_times = all_times # fallback# 3. 處理排序 (正序/反序)if sort_order == "時間反序 (新 -> 舊)":selected_times.reverse()if len(selected_times) < 2: return None# 4. 固定色階agg_all = plot_df.groupby(['time_gif_parsed', 'county_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 = []for i, t in enumerate(progress.tqdm(selected_times, desc="繪製圖框中...")):df_t = agg_all[agg_all['time_gif_parsed'] == t]merged = GDF.merge(df_t, left_on='name', right_on='county_normalized', how='left')merged[col] = merged[col].fillna(0)fig, ax = plt.subplots(figsize=(10, 10))merged.plot(column=col, cmap=cmap, linewidth=0.8, ax=ax, edgecolor='0.8', vmin=vmin, vmax=vmax, legend=True, legend_kwds={'shrink': 0.6})title_text = f"{col} - {t} 年"if CUSTOM_FONT_PROP: ax.set_title(title_text, fontproperties=CUSTOM_FONT_PROP, size=20)else: ax.set_title(title_text, size=20)ax.set_axis_off()buf = io.BytesIO()11 unmodified linesreturn None# === Gradio 介面 ===with gr.Blocks(title="台灣 Open Data 視覺化平台 (旗艦版)") as demo:gr.Markdown("## 🇹🇼 台灣資料視覺化儀表板 (含進階 GIF 設定)")current_df = gr.State()16 unmodified linesbtn_trend = gr.Button("更新趨勢圖", variant="primary")btn_export = gr.Button("📥 下載靜態全圖 (PNG)")with gr.Accordion("動態 GIF 進階設定", open=True):gif_time_col = gr.Dropdown(label="動畫依據的時間欄位", choices=[])with gr.Row():start_time = gr.Dropdown(label="起始時間", choices=[])end_time = gr.Dropdown(label="結束時間", choices=[])sort_order = gr.Radio(["時間正序 (舊 -> 新)", "時間反序 (新 -> 舊)"], label="播放順序", value="時間正序 (舊 -> 新)")fps_slider = gr.Slider(minimum=1, maximum=5, value=2, step=1, label="播放速度 (FPS)")btn_gif = gr.Button("🎬 產生 GIF 動畫", variant="primary")9 unmodified lineswith gr.Tab("📋 資料預覽"):data_preview = gr.Dataframe()# 事件綁定:上傳後更新所有下拉選單file_input.change(fn=process_uploaded_file,inputs=file_input,outputs=[current_df, status_box, col_selector, time_selector, trend_county, data_preview,# 新增的 GIF 設定欄位更新gif_time_col, start_time, end_time])btn_map.click(fn=generate_map, inputs=[current_df, col_selector, time_selector, agg_method, color_scheme], outputs=map_output)btn_trend.click(fn=generate_trend_chart, inputs=[current_df, col_selector, trend_county, line_metric_selector], outputs=trend_output)btn_export.click(fn=export_static_chart, inputs=[current_df, col_selector, trend_county, line_metric_selector], outputs=download_file)# GIF 生成 (傳入新的參數)btn_gif.click(fn=generate_map_gif,inputs=[current_df, col_selector, color_scheme, fps_slider, gif_time_col, start_time, end_time, sort_order],outputs=gif_output)if __name__ == "__main__":demo.queue().launch()
app.py+135-112