Spaces:
Sleeping
Sleeping
Update app.py
Browse files8 unmodified lines91011121314155 unmodified lines2122232425262728293031323334353637389 unmodified lines484950515253545556572 unmodified lines60616263646566676813 unmodified lines8283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331343 unmodified lines13813914014114214314410 unmodified lines15515615715815916016116213 unmodified lines1761771781791801811821831841851861875 unmodified lines1931941951961971981995 unmodified lines20520620720820921021113 unmodified lines2252262272282292302312322332342352362372382392402412422432442452462472482496 unmodified lines2562572582592602612622632642652662672687 unmodified lines2762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193206 unmodified lines3273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643 unmodified lines3683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104113 unmodified lines41541641741841942042142242342442542642742842943043143243343443543615 unmodified lines4524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135148 unmodified linesfrom PIL import Imageimport ioimport osimport requests # 新增:用於下載地圖import warningsimport tempfilefrom typing import Tuple, List, Dict, Optional5 unmodified linesmatplotlib.use('Agg')plt.rcParams['axes.unicode_minus'] = False# === 0. 自動下載地圖檔 (修復沒反應的主因) ===def check_and_download_maps():# 使用 ronnywang 的 GitHub 開源地圖資料map_sources = {"twCounty2010.geo.json": "https://raw.githubusercontent.com/ronnywang/twgeojson/master/twCounty2010.geo.json","twTown2010.geo.json": "https://raw.githubusercontent.com/ronnywang/twgeojson/master/twTown2010.geo.json"}for filename, url in map_sources.items():if not os.path.exists(filename):print(f"⚠️ 找不到 {filename},正在嘗試下載...")try:r = requests.get(url)if r.status_code == 200:with open(filename, 'wb') as f:9 unmodified lines# === 1. 設定中文字型 ===def set_custom_font():# 優先嘗試系統內建字型system_fonts = ['Microsoft JhengHei', 'SimHei', 'Heiti TC', 'Taipei Sans TC Beta']# 檢查是否有自訂字型檔案font_filename = "kaiu.ttf"if os.path.exists(font_filename):try:2 unmodified linesplt.rcParams['font.family'] = font_prop.get_name()print(f"✅ 成功載入自訂字型: {font_filename}")return font_propexcept Exception:passplt.rcParams['font.sans-serif'] = system_fontsreturn None13 unmodified lines}TIME_FIELDS = ['year', 'Year', 'YEAR', '年', '年份', '年度', '民國', 'month', 'Month', 'date', 'Date', 'time']REGION_FIELDS = ['縣市', '縣市別', 'county', 'city', 'location', 'region', 'area','地區', '行政區', '代碼', 'code', 'id', 'site', 'site_id','鄉鎮', '市區', 'town', 'district', '區域別']NON_VALUE_KEYWORDS = ['code', 'number', 'serial', 'index', 'lat', 'lon', 'year', 'date', 'yyy']# === 載入與工具函數 ===def load_map_file(level="county"):filename = TOWN_MAP_FILE if level == "town" else COUNTY_MAP_FILEtry:if not os.path.exists(filename):print(f"❌ 嚴重錯誤: 找不到地圖檔 {filename},請檢查網路是否能下載檔案。")return Nonegdf = gpd.read_file(filename)if gdf.crs != "EPSG:4326": gdf = gdf.to_crs("EPSG:4326")# 為了效能稍微簡化幾何gdf['geometry'] = gdf['geometry'].simplify(tolerance=0.003, preserve_topology=True)# 欄位名稱標準化cols_lower = {c.lower(): c for c in gdf.columns}county_col = Nonetown_col = Nonefor key in ['countyname', 'county', 'c_name']:if key in cols_lower: county_col = cols_lower[key]; breakfor key in ['townname', 'town', 't_name']:if key in cols_lower: town_col = cols_lower[key]; breakif level == "town":if county_col and town_col:gdf['name'] = gdf[county_col] + gdf[town_col]elif town_col:gdf['name'] = gdf[town_col]elif 'name' in cols_lower:gdf['name'] = gdf[cols_lower['name']]else:if county_col:gdf['name'] = gdf[county_col]elif 'name' in cols_lower:gdf['name'] = gdf[cols_lower['name']]if 'name' in gdf.columns:gdf['name'] = gdf['name'].astype(str).str.replace('台', '臺')3 unmodified linesprint(f"❌ 地圖檔讀取失敗 ({filename}): {e}")return None# 全域變數快取GDF_COUNTY = NoneGDF_TOWN = None10 unmodified linesif pd.isna(value): return ""s_value = str(value).strip().replace(' ', '').replace(' ', '')if s_value in COUNTY_CODE_MAP: return COUNTY_CODE_MAP[s_value]s_value = str(s_value).split('.')[0]if s_value in COUNTY_CODE_MAP: return COUNTY_CODE_MAP[s_value]return s_value.replace('台', '臺')def get_numeric_columns(df: pd.DataFrame, exclude_cols: List[str] = None) -> List[str]:13 unmodified linesexcept: passreturn numeric_cols# === 資料解析核心 ===def smart_parse_data(df: pd.DataFrame):if df is None or df.empty:return None, "資料為空", [], [], [], "unknown", []# 1. 資料清洗data_start_idx = 0for i in range(min(5, len(df))):row = df.iloc[i]5 unmodified linesexcept: passif total_count > 0 and (num_count / total_count) > 0.4:data_start_idx = i; breakif data_start_idx > 0:new_header = df.iloc[data_start_idx-1]df_processed = df.iloc[data_start_idx:].copy()5 unmodified linestry: df_processed[col] = pd.to_numeric(df_processed[col])except: pass# 2. 時間偵測possible_time_cols = [c for c in df_processed.columns if any(k in str(c) for k in TIME_FIELDS)]if not possible_time_cols:for col in df_processed.columns:13 unmodified linesexcept:available_times = sorted(df_processed['time_parsed'].unique(), reverse=True)# 3. 地區偵測region_col = Nonepotential_cols = [c for c in df_processed.columns if any(k in str(c).lower() for k in REGION_FIELDS)]map_level = "county"# 優先檢查 potential_colsfor col in potential_cols + list(df_processed.columns):if col not in df_processed.columns: continuesample = df_processed[col].dropna().head(20).astype(str).tolist()if not sample: continuehas_town = any(('區' in s or '鄉' in s or '鎮' in s) for s in sample)has_county = any(('縣' in s or '市' in s) for s in sample)# 檢查是否為代碼has_code = any(str(s).split('.')[0] in COUNTY_CODE_MAP for s in sample)if has_town:region_col = col; map_level = "town"; breakelif has_county or has_code:if not region_col: region_col = col; map_level = "county"6 unmodified lineslevel_name = "鄉鎮市區" if map_level == "town" else "縣市"msg = f"✓ 偵測成功 ({level_name}: {region_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, regions, map_level, possible_time_cols# === 處理上傳檔案 ===def process_uploaded_file(file_obj):if file_obj is None: return None, "請上傳檔案", [], [], [], [], [], [], [], "county"try:7 unmodified linesprocessed_df, msg, cols, times, regions, map_level, time_cols = smart_parse_data(df)def_col = cols[0] if cols else Nonedef_time_col = time_cols[0] if time_cols else Nonestart_t = times[-1] if times else Noneend_t = times[0] if times else Noneregion_options = ["全國總計"] + regions if regions else []# 預先載入地圖get_gdf(map_level)return (processed_df, msg,gr.Dropdown(choices=cols, value=def_col),gr.Dropdown(choices=["全部"] + times, value="全部"),gr.Dropdown(choices=region_options, value="全國總計"),gr.Dataframe(value=processed_df.head(5)),gr.Dropdown(choices=time_cols, value=def_time_col),gr.Dropdown(choices=times, value=start_t),gr.Dropdown(choices=times, value=end_t),map_level)except Exception as e:import tracebacktraceback.print_exc()return None, f"錯誤: {e}", [], [], [], [], [], [], [], "county"# === 繪圖 ===def generate_map(df, col, time, agg_method, color_scheme, map_level_state):print(f"啟動地圖繪製: 指標={col}, 地圖層級={map_level_state}")target_gdf = get_gdf(map_level_state)if df is None:raise gr.Error("請先上傳資料")if not col:raise gr.Error("未選擇指標欄位")if target_gdf is None:raise gr.Error("地圖檔載入失敗,請檢查網際網路連線以下載地圖檔")if 'region_normalized' not in df.columns:raise gr.Error("無法識別地區欄位,請檢查資料內容")try:plot_df = df.copy()6 unmodified lineselif 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)# 檢查是否有資料成功對應matched_count = merged[merged[col] > 0].shape[0]print(f"對應到地圖的區域數量: {matched_count}")if matched_count == 0:print("⚠️ 警告:沒有任何資料成功對應到地圖區域")# 可能是名稱不匹配,嘗試印出前幾個print("CSV 區域範例:", geo_data['region_normalized'].head().tolist())print("地圖 區域範例:", target_gdf['name'].head().tolist())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 '全部'})", hover_name='name')fig.update_geos(fitbounds="locations", visible=False)fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0})return figexcept Exception as e:import tracebacktraceback.print_exc()raise gr.Error(f"繪圖錯誤: {str(e)}")def generate_trend_chart(df, col, selected_region, line_metric):if df is None or not col: return Noneif 'time_parsed' not in df.columns:raise gr.Error("資料中未偵測到時間欄位,無法繪製趨勢圖")try:trend_df = df.copy()trend_df[col] = pd.to_numeric(trend_df[col], errors='coerce').fillna(0)3 unmodified linestitle_suffix = selected_regiontry: 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')if grouped.empty:raise gr.Error("篩選後無資料")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 = Falseelif line_metric == "累積數量": line_data = grouped[col].cumsum(); secondary_y = Truex_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)if line_data is not None:fig.add_trace(go.Scatter(x=x_data, y=line_data, name=line_metric, mode='lines+markers', marker=dict(size=6), line=dict(width=3, color='rgb(219, 64, 82)')), secondary_y=secondary_y)fig.update_layout(title=f"{col} - 歷史趨勢 ({title_suffix})", xaxis_title="時間", legend=dict(orientation="h", y=1.1), hovermode="x unified")fig.update_yaxes(title_text="數量", secondary_y=False)if secondary_y and line_data is not None: fig.update_yaxes(title_text=line_metric, secondary_y=True, showgrid=False)return figexcept Exception as e: return Nonedef export_static_chart(df, col, selected_region, line_metric):if df is None or not col: return Nonetry:trend_df = df.copy()trend_df[col] = pd.to_numeric(trend_df[col], errors='coerce').fillna(0)title_suffix = "全國總計"if selected_region and selected_region != "全國總計":trend_df = trend_df[trend_df['region_normalized'] == selected_region]title_suffix = selected_regiontry: 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')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 = False3 unmodified linesy_bar = grouped[col].tolist()y_line = line_data.tolist() if line_data is not None else []fig, ax1 = plt.subplots(figsize=(12, 6))ax1.bar(x_data, y_bar, color='steelblue', alpha=0.6, label=f"{col} (數量)")ax1.set_ylabel("數量", color='steelblue')title_text = f"{col} - 歷史趨勢圖 ({title_suffix})"if CUSTOM_FONT_PROP: ax1.set_title(title_text, fontproperties=CUSTOM_FONT_PROP, size=16)else: ax1.set_title(title_text, size=16)if use_twinx:ax2 = ax1.twinx(); ax2.plot(x_data, y_line, color='crimson', marker='o', linewidth=2, label=line_metric); ax2.set_ylabel(line_metric, color='crimson')else: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 Nonedef generate_map_gif(df, col, color_scheme, fps, time_col, start_t, end_t, sort_order, map_level_state, progress=gr.Progress()):target_gdf = get_gdf(map_level_state)if df is None or not col or target_gdf is None or 'name' not in target_gdf.columns: return Noneif 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 None15 unmodified linescmap_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 = 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=(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(); plt.savefig(buf, format='png', dpi=100, bbox_inches='tight'); buf.seek(0)frames.append(Image.open(buf)); plt.close(fig)output_path = tempfile.mktemp(suffix=".gif")duration = 1000 / max(fps, 1)frames[0].save(output_path, save_all=True, append_images=frames[1:], optimize=False, duration=duration, loop=0)return output_pathexcept Exception as e: print(e); return None# === Gradio 介面 ===with gr.Blocks(title="台灣 Open Data 視覺化平台 (自動下載圖資版)") as demo:gr.Markdown("## 🇹🇼 台灣資料視覺化儀表板")current_df = gr.State()map_level_state = gr.State(value="county")with gr.Row():with gr.Column(scale=1):gr.Markdown("### 1. 資料設定")file_input = gr.File(label="上傳 CSV/JSON", file_types=['.csv', '.json', '.xlsx'])status_box = gr.Textbox(label="狀態", interactive=False)col_selector = gr.Dropdown(label="選擇指標")with gr.Accordion("地圖進階設定", open=False):time_selector = gr.Dropdown(label="時間點", choices=["全部"], value="全部")agg_method = gr.Radio(["加總", "平均", "最大值"], label="聚合方式", value="加總")color_scheme = gr.Dropdown(["紅色系", "藍色系", "綠色系", "熱力圖"], label="配色", value="紅色系")btn_map = gr.Button("更新地圖", variant="primary")with gr.Accordion("趨勢圖進階設定", open=False):trend_region = gr.Dropdown(label="選擇地區", choices=["全國總計"], value="全國總計")line_metric_selector = gr.Dropdown(label="折線圖指標", choices=["年增率 (%)", "3年移動平均", "5年移動平均", "累積數量"], value="3年移動平均")btn_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")with gr.Column(scale=2):with gr.Tabs():with gr.Tab("🗺️ 地圖分布"): map_output = gr.Plot()with gr.Tab("📈 歷史趨勢分析"): trend_output = gr.Plot(label="互動趨勢圖"); download_file = gr.File(label="下載圖檔")with gr.Tab("🎬 動態地圖 (GIF)"): gif_output = gr.Image(label="GIF 預覽")with 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_region, data_preview, gif_time_col, start_time, end_time, map_level_state])btn_map.click(fn=generate_map, inputs=[current_df, col_selector, time_selector, agg_method, color_scheme, map_level_state], outputs=map_output)btn_trend.click(fn=generate_trend_chart, inputs=[current_df, col_selector, trend_region, line_metric_selector], outputs=trend_output)btn_export.click(fn=export_static_chart, inputs=[current_df, col_selector, trend_region, line_metric_selector], outputs=download_file)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, map_level_state], outputs=gif_output)if __name__ == "__main__":8 unmodified lines91011121314155 unmodified lines212223242526272829303132333435363738394041424344454647484950515253549 unmodified lines646566676869702 unmodified lines7374757677787913 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511523 unmodified lines15615715815916016116210 unmodified lines17317417517617717813 unmodified lines1921931941951961971981992002012025 unmodified lines2082092102112122135 unmodified lines21922022122222322422513 unmodified lines2392402412422432442452462472482492502512522532542552562576 unmodified lines2642652662672682692702712722732742752767 unmodified lines2842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183196 unmodified lines3263273283293303313323333343353363373383393403413423433443453463473483493503513523 unmodified lines3563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883 unmodified lines39239339439539639739839940040140240340440540640740840941041141241341415 unmodified lines4304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884898 unmodified linesfrom PIL import Imageimport ioimport osimport requestsimport warningsimport tempfilefrom typing import Tuple, List, Dict, Optional5 unmodified linesmatplotlib.use('Agg')plt.rcParams['axes.unicode_minus'] = False# === 0. 自動下載與修復地圖檔 ===def check_and_download_maps():map_sources = {"twCounty2010.geo.json": "https://raw.githubusercontent.com/ronnywang/twgeojson/master/twCounty2010.geo.json","twTown2010.geo.json": "https://raw.githubusercontent.com/ronnywang/twgeojson/master/twTown2010.geo.json"}for filename, url in map_sources.items():# 檢查檔案是否存在,若存在則檢查是否異常 (例如鄉鎮檔過小)need_download = Falseif not os.path.exists(filename):need_download = Trueprint(f"🔍 找不到 {filename},準備下載...")else:# 簡易檢查:如果是鄉鎮地圖,檔案大小通常比較大,或者讀取後筆數要夠多try:if "Town" in filename:gdf_check = gpd.read_file(filename)if len(gdf_check) < 50: # 台灣鄉鎮絕對超過 50 個print(f"⚠️ 偵測到 {filename} 內容異常 (筆數僅 {len(gdf_check)}),判定為錯誤檔案。")os.remove(filename)need_download = Trueexcept:need_download = Trueif need_download:try:print(f"⬇️ 正在下載 {filename} ...")r = requests.get(url)if r.status_code == 200:with open(filename, 'wb') as f:9 unmodified lines# === 1. 設定中文字型 ===def set_custom_font():system_fonts = ['Microsoft JhengHei', 'SimHei', 'Heiti TC', 'Taipei Sans TC Beta']font_filename = "kaiu.ttf"if os.path.exists(font_filename):try:2 unmodified linesplt.rcParams['font.family'] = font_prop.get_name()print(f"✅ 成功載入自訂字型: {font_filename}")return font_propexcept Exception: passplt.rcParams['font.sans-serif'] = system_fontsreturn None13 unmodified lines}TIME_FIELDS = ['year', 'Year', 'YEAR', '年', '年份', '年度', '民國', 'month', 'Month', 'date', 'Date', 'time']REGION_FIELDS = ['縣市', '地區', '行政區', '代碼', 'code', 'id', 'site', 'site_id', '鄉鎮', '市區', 'town', 'district', '區域別', 'county', 'city', 'location']NON_VALUE_KEYWORDS = ['code', 'number', 'serial', 'index', 'lat', 'lon', 'year', 'date', 'yyy']# === 關鍵修正:載入地圖函數 ===def load_map_file(level="county"):filename = TOWN_MAP_FILE if level == "town" else COUNTY_MAP_FILEtry:if not os.path.exists(filename):print(f"❌ 嚴重錯誤: 找不到地圖檔 {filename}")return Nonegdf = gpd.read_file(filename)if gdf.crs != "EPSG:4326": gdf = gdf.to_crs("EPSG:4326")gdf['geometry'] = gdf['geometry'].simplify(tolerance=0.003, preserve_topology=True)# 欄位名稱偵測cols_lower = {c.lower(): c for c in gdf.columns}county_col = Nonefor key in ['countyname', 'county', 'c_name']:if key in cols_lower: county_col = cols_lower[key]; breaktown_col = Nonefor key in ['townname', 'town', 't_name']:if key in cols_lower: town_col = cols_lower[key]; break# 建立 'name' 欄位 (這是產生錯誤的關鍵點,這裡加強防呆)if level == "town":if county_col and town_col:gdf['name'] = gdf[county_col] + gdf[town_col]elif town_col:gdf['name'] = gdf[town_col]elif county_col:# 只有縣市沒有鄉鎮,但使用者要求鄉鎮地圖,這是檔案錯誤print(f"⚠️ 警告: 鄉鎮地圖檔中找不到鄉鎮欄位,僅發現 {county_col}。將使用該欄位作為名稱。")gdf['name'] = gdf[county_col]else:if county_col:gdf['name'] = gdf[county_col]# 最後防線:如果還是沒有 'name'if 'name' not in gdf.columns:if 'name' in cols_lower:gdf['name'] = gdf[cols_lower['name']]else:# 真的找不到,隨便拿第一個字串欄位或索引print("⚠️ 警告: 無法產生標準 'name' 欄位,嘗試使用索引或備用欄位。")str_cols = gdf.select_dtypes(include=['object']).columnsif len(str_cols) > 0:gdf['name'] = gdf[str_cols[0]]else:gdf['name'] = gdf.index.astype(str)if 'name' in gdf.columns:gdf['name'] = gdf['name'].astype(str).str.replace('台', '臺')3 unmodified linesprint(f"❌ 地圖檔讀取失敗 ({filename}): {e}")return None# 全域變數快取 (重置為 None 確保重新載入)GDF_COUNTY = NoneGDF_TOWN = None10 unmodified linesif pd.isna(value): return ""s_value = str(value).strip().replace(' ', '').replace(' ', '')if s_value in COUNTY_CODE_MAP: return COUNTY_CODE_MAP[s_value]return s_value.replace('台', '臺')def get_numeric_columns(df: pd.DataFrame, exclude_cols: List[str] = None) -> List[str]:13 unmodified linesexcept: passreturn numeric_cols# === 資料解析 ===def smart_parse_data(df: pd.DataFrame):if df is None or df.empty: return None, "資料為空", [], [], [], "unknown", []# 清洗表頭data_start_idx = 0for i in range(min(5, len(df))):row = df.iloc[i]5 unmodified linesexcept: passif total_count > 0 and (num_count / total_count) > 0.4:data_start_idx = i; breakif data_start_idx > 0:new_header = df.iloc[data_start_idx-1]df_processed = df.iloc[data_start_idx:].copy()5 unmodified linestry: df_processed[col] = pd.to_numeric(df_processed[col])except: pass# 時間偵測possible_time_cols = [c for c in df_processed.columns if any(k in str(c) for k in TIME_FIELDS)]if not possible_time_cols:for col in df_processed.columns:13 unmodified linesexcept:available_times = sorted(df_processed['time_parsed'].unique(), reverse=True)# 地區偵測region_col = Nonepotential_cols = [c for c in df_processed.columns if any(k in str(c).lower() for k in REGION_FIELDS)]map_level = "county"for col in potential_cols + list(df_processed.columns):if col not in df_processed.columns: continuesample = df_processed[col].dropna().head(20).astype(str).tolist()if not sample: continuehas_town = any(('區' in s or '鄉' in s or '鎮' in s) for s in sample)has_county = any(('縣' in s or '市' in s) for s in sample)has_code = any(str(s).split('.')[0] in COUNTY_CODE_MAP for s in sample)if has_town: region_col = col; map_level = "town"; breakelif has_county or has_code:if not region_col: region_col = col; map_level = "county"6 unmodified lineslevel_name = "鄉鎮市區" if map_level == "town" else "縣市"msg = f"✓ 偵測成功 ({level_name}: {region_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, regions, map_level, possible_time_cols# === 處理檔案 ===def process_uploaded_file(file_obj):if file_obj is None: return None, "請上傳檔案", [], [], [], [], [], [], [], "county"try:7 unmodified linesprocessed_df, msg, cols, times, regions, map_level, time_cols = smart_parse_data(df)# 這裡會觸發地圖下載與檢查get_gdf(map_level)return (processed_df, msg,gr.Dropdown(choices=cols, value=cols[0] if cols else None),gr.Dropdown(choices=["全部"] + times, value="全部"),gr.Dropdown(choices=["全國總計"] + regions if regions else [], value="全國總計"),gr.Dataframe(value=processed_df.head(5)),gr.Dropdown(choices=time_cols, value=time_cols[0] if time_cols else None),gr.Dropdown(choices=times, value=times[-1] if times else None),gr.Dropdown(choices=times, value=times[0] if times else None),map_level)except Exception as e:import traceback; traceback.print_exc()return None, f"錯誤: {e}", [], [], [], [], [], [], [], "county"# === 繪圖 ===def generate_map(df, col, time, agg_method, color_scheme, map_level_state):target_gdf = get_gdf(map_level_state)if df is None: raise gr.Error("請先上傳資料")if not col: raise gr.Error("未選擇指標")if target_gdf is None: raise gr.Error("地圖圖資載入失敗")# 這裡檢查 'name' 是否存在,如果不存在,手動創造一個,避免 crashif 'name' not in target_gdf.columns:print("⚠️ 地圖檔缺少 'name' 欄位,嘗試修復...")target_gdf['name'] = target_gdf.index.astype(str)try:plot_df = df.copy()6 unmodified lineselif 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()# Merge 時如果 key 不對,也不要 crash,而是顯示空地圖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",title=f"{col} - 地圖 ({time})", hover_name='name')fig.update_geos(fitbounds="locations", visible=False)fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0})return figexcept Exception as e:import traceback; traceback.print_exc()raise gr.Error(f"繪圖失敗: {e}")def generate_trend_chart(df, col, selected_region, line_metric):if df is None or not col: return Nonetry:trend_df = df.copy()trend_df[col] = pd.to_numeric(trend_df[col], errors='coerce').fillna(0)3 unmodified linestitle_suffix = selected_regiontry: 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 = Falseelif line_metric == "5年移動平均": line_data = grouped[col].rolling(window=5).mean(); secondary_y = Falseelif line_metric == "累積數量": line_data = grouped[col].cumsum(); secondary_y = Truex_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)if line_data is not None:fig.add_trace(go.Scatter(x=x_data, y=line_data, name=line_metric, mode='lines+markers', marker=dict(size=6), line=dict(width=3, color='rgb(219, 64, 82)')), secondary_y=secondary_y)fig.update_layout(title=f"{col} - 歷史趨勢 ({title_suffix})", xaxis_title="時間", legend=dict(orientation="h", y=1.1), hovermode="x unified")fig.update_yaxes(title_text="數量", secondary_y=False)if secondary_y: fig.update_yaxes(title_text=line_metric, secondary_y=True, showgrid=False)return figexcept: return Nonedef export_static_chart(df, col, selected_region, line_metric):if df is None or not col: return Nonetry:trend_df = df.copy()trend_df[col] = pd.to_numeric(trend_df[col], errors='coerce').fillna(0)if selected_region and selected_region != "全國總計":trend_df = trend_df[trend_df['region_normalized'] == selected_region]try: 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')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 = False3 unmodified linesy_bar = grouped[col].tolist()y_line = line_data.tolist() if line_data is not None else []fig, ax1 = plt.subplots(figsize=(12, 6))ax1.bar(x_data, y_bar, color='steelblue', alpha=0.6, label="數量")if CUSTOM_FONT_PROP: ax1.set_title(f"{col} 趨勢", fontproperties=CUSTOM_FONT_PROP, size=16)else: ax1.set_title(f"{col} 趨勢", size=16)if use_twinx:ax2 = ax1.twinx(); ax2.plot(x_data, y_line, color='crimson', marker='o', linewidth=2, label=line_metric)else:ax1.plot(x_data, y_line, color='crimson', marker='o', linewidth=2, label=line_metric)plt.tight_layout()with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp: plt.savefig(tmp.name, dpi=150); return tmp.nameexcept: return Nonedef generate_map_gif(df, col, color_scheme, fps, time_col, start_t, end_t, sort_order, map_level_state, progress=gr.Progress()):target_gdf = get_gdf(map_level_state)if df is None or not col or target_gdf is None: return None# GIF 同樣需要 name 欄位保護if 'name' not in target_gdf.columns: target_gdf['name'] = target_gdf.index.astype(str)if 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 None15 unmodified linescmap_map = {"紅色系": "OrRd", "藍色系": "Blues", "綠色系": "Greens", "熱力圖": "hot_r"}cmap = cmap_map.get(color_scheme.split()[0], "OrRd")frames = []for 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=(10, 10))merged.plot(column=col, cmap=cmap, linewidth=0.8, ax=ax, edgecolor='0.8', vmin=vmin, vmax=vmax)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(); plt.savefig(buf, format='png', dpi=100, bbox_inches='tight'); buf.seek(0)frames.append(Image.open(buf)); plt.close(fig)output_path = tempfile.mktemp(suffix=".gif")frames[0].save(output_path, save_all=True, append_images=frames[1:], optimize=False, duration=1000/fps, loop=0)return output_pathexcept Exception as e: print(e); return None# === Gradio ===with gr.Blocks(title="Open Data 視覺化") as demo:gr.Markdown("## 🇹🇼 資料視覺化儀表板 (強健版)")current_df = gr.State()map_level_state = gr.State(value="county")with gr.Row():with gr.Column(scale=1):file_input = gr.File(label="上傳 CSV/JSON/Excel")status_box = gr.Textbox(label="狀態", interactive=False)col_selector = gr.Dropdown(label="選擇指標")with gr.Accordion("地圖設定", open=False):time_selector = gr.Dropdown(label="時間點", choices=["全部"], value="全部")agg_method = gr.Radio(["加總", "平均", "最大值"], label="聚合", value="加總")color_scheme = gr.Dropdown(["紅色系", "藍色系", "綠色系"], label="配色", value="紅色系")btn_map = gr.Button("更新地圖", variant="primary")with gr.Accordion("趨勢圖設定", open=False):trend_region = gr.Dropdown(label="地區", choices=["全國總計"], value="全國總計")line_metric = gr.Dropdown(label="指標", choices=["年增率 (%)", "3年移動平均"], value="3年移動平均")btn_trend = gr.Button("更新趨勢")btn_export = gr.Button("下載圖檔")with gr.Accordion("GIF 動畫", open=False):gif_time_col = gr.Dropdown(label="時間欄位")start_time = gr.Dropdown(label="起始"); end_time = gr.Dropdown(label="結束")fps_slider = gr.Slider(1, 5, 2, 1, label="速度 FPS")btn_gif = gr.Button("產生 GIF")with gr.Column(scale=2):with gr.Tabs():with gr.Tab("地圖"): map_output = gr.Plot()with gr.Tab("趨勢"): trend_output = gr.Plot(); download_file = gr.File()with gr.Tab("GIF"): gif_output = gr.Image()with 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_region, data_preview, gif_time_col, start_time, end_time, map_level_state])btn_map.click(fn=generate_map, inputs=[current_df, col_selector, time_selector, agg_method, color_scheme, map_level_state], outputs=map_output)btn_trend.click(fn=generate_trend_chart, inputs=[current_df, col_selector, trend_region, line_metric], outputs=trend_output)btn_export.click(fn=export_static_chart, inputs=[current_df, col_selector, trend_region, line_metric], outputs=download_file)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, map_level_state], outputs=gif_output)if __name__ == "__main__":
app.py+115-140