Spaces:
Sleeping
Sleeping
Update app.py
Browse files15 unmodified lines16171819202122232425262728293031323334353637383940411 unmodified line434445464748495051525354555657585960616263646566676869707172737475767 unmodified lines8485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515617 unmodified lines1741751761771781791801811821831841 unmodified line1861871881891901911921931941955 unmodified lines20120220320420520620713 unmodified lines2212222232242252262272 unmodified lines2302312322332342352362372382394 unmodified lines2442452462472482492502512522532542552562572582592601 unmodified line2622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942953 unmodified lines29930030130230330430525 unmodified lines33133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746815 unmodified lineswarnings.filterwarnings('ignore')# === 設定 Matplotlib 後端 ===import matplotlibmatplotlib.use('Agg')plt.rcParams['axes.unicode_minus'] = False# === 0. 自動下載與檢查地圖檔 ===def check_and_download_maps():# 修正下載連結 (Ronnywang repo 的檔名通常是小寫)map_sources = {"twCounty2010.geo.json": "https://raw.githubusercontent.com/ronnywang/twgeojson/master/twcounty2010.json","twTown2010.geo.json": "https://raw.githubusercontent.com/ronnywang/twgeojson/master/twtown2010.json"}for filename, url in map_sources.items():# 如果檔案已經存在 (使用者自己上傳了),就直接使用,不重新下載if os.path.exists(filename):print(f"📂 偵測到現有檔案: {filename},將直接使用。")continueprint(f"🔍 找不到 {filename},嘗試下載...")try:r = requests.get(url)if r.status_code == 200:1 unmodified linef.write(r.content)print(f"✅ 下載成功: {filename}")else:print(f"⚠️ 下載失敗 {filename} (HTTP {r.status_code})。請確認您已手動上傳此檔案。")except Exception as e:print(f"❌ 下載過程錯誤: {e}")# 執行檢查 (不會強制刪除你的檔案)check_and_download_maps()# === 1. 設定中文字型 ===def set_custom_font():system_fonts = ['Microsoft JhengHei', 'SimHei', 'Heiti TC', 'Taipei Sans TC Beta', 'Sans-Serif']font_filename = "kaiu.ttf"if os.path.exists(font_filename):try:fm.fontManager.addfont(font_filename)font_prop = fm.FontProperties(fname=font_filename)plt.rcParams['font.family'] = font_prop.get_name()print(f"✅ 成功載入自訂字型: {font_filename}")return font_propexcept Exception: passplt.rcParams['font.sans-serif'] = system_fontsreturn NoneCUSTOM_FONT_PROP = set_custom_font()# === 配置與常數 ===COUNTY_MAP_FILE = "twCounty2010.geo.json"TOWN_MAP_FILE = "twTown2010.geo.json"COUNTY_CODE_MAP = {'65000': '新北市', '63000': '臺北市', '68000': '桃園市', '66000': '臺中市','67000': '臺南市', '64000': '高雄市', '10002': '宜蘭縣', '10004': '新竹縣',7 unmodified linesREGION_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")# 為了效能,稍微簡化幾何 (如果你的 geojson 很精細,這步很重要)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]# 最後防線if 'name' not in gdf.columns:if 'name' in cols_lower:gdf['name'] = gdf[cols_lower['name']]else: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('台', '臺')print(f"✅ 地圖 ({level}) 載入成功,筆數: {len(gdf)}")return gdfexcept Exception as e:print(f"❌ 地圖檔讀取失敗 ({filename}): {e}")return NoneGDF_COUNTY = NoneGDF_TOWN = Nonedef get_gdf(level):global GDF_TOWN, GDF_COUNTYif level == "town":if GDF_TOWN is None: GDF_TOWN = load_map_file("town")return GDF_TOWNelse:if GDF_COUNTY is None: GDF_COUNTY = load_map_file("county")return GDF_COUNTYdef normalize_name(value) -> str:17 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]1 unmodified linetotal_count = 0for val in row:total_count += 1try: float(str(val).replace(',', '')); num_count += 1except: 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"2 unmodified linesif 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"4 unmodified linesexclude = [region_col, time_col] if time_col else [region_col]numeric_cols = get_numeric_columns(df_processed, exclude)level_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: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, "不支援的格式", [], [], [], [], [], [], [], "county"processed_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("地圖圖資載入失敗,請確認 GeoJSON 檔案存在")if 'name' not in target_gdf.columns: target_gdf['name'] = target_gdf.index.astype(str)3 unmodified linesplot_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()25 unmodified linesif 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().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 = Falseelif line_metric == "5年移動平均": line_data = grouped[col].rolling(window=5).mean(); use_twinx = Falseelif line_metric == "累積數量": line_data = grouped[col].cumsum()x_data = grouped['time_sort'].astype(str).tolist()y_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 Noneif '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 Nonetry:plot_df = df.copy()plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)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())try: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)-1if idx_start > idx_end: idx_start, idx_end = idx_end, idx_startselected_times = all_times[idx_start : idx_end + 1]except: selected_times = all_timesif sort_order == "時間反序 (新 -> 舊)": selected_times.reverse()if len(selected_times) < 2: return Noneagg_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 = []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="結束")# 這裡補回了漏掉的變數sort_order = gr.Radio(["時間正序 (舊 -> 新)", "時間反序 (新 -> 舊)"], label="播放順序", value="時間正序 (舊 -> 新)")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__":demo.queue().launch()15 unmodified lines161718192021222324252627282930313233343536373839401 unmodified line424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889907 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817 unmodified lines1961971981992002012022032042052061 unmodified line2082092102112122132142152162172182192202215 unmodified lines22722822923023123223313 unmodified lines2472482492502512522532 unmodified lines2562572582592602612622632642652662672684 unmodified lines2732742752762772782792802812822832842852862872882892902912921 unmodified line2942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343 unmodified lines33833934034134234334425 unmodified lines37037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053115 unmodified lineswarnings.filterwarnings('ignore')# === 設定 Matplotlib 後端,避免在無介面環境報錯 ===import matplotlibmatplotlib.use('Agg')plt.rcParams['axes.unicode_minus'] = False# === 0. 自動下載與檢查地圖檔 ===def check_and_download_maps():# 使用穩定的 GitHub Raw 連結map_sources = {"twCounty2010.json": "https://raw.githubusercontent.com/ronnywang/twgeojson/master/twcounty2010.json","twTown2010.json": "https://raw.githubusercontent.com/ronnywang/twgeojson/master/twtown2010.json"}for filename, url in map_sources.items():if os.path.exists(filename):print(f"📂 偵測到現有地圖檔: {filename}")continueprint(f"🔍 下載地圖檔 {filename} ...")try:r = requests.get(url)if r.status_code == 200:1 unmodified linef.write(r.content)print(f"✅ 下載成功: {filename}")else:print(f"⚠️ 下載失敗 {filename} (HTTP {r.status_code})")except Exception as e:print(f"❌ 下載過程錯誤: {e}")check_and_download_maps()# === 1. 設定中文字型 (自動下載 NotoSansTC 避免亂碼) ===def set_custom_font():font_path = "NotoSansTC-Regular.otf"# 如果沒有字型檔,嘗試下載if not os.path.exists(font_path):print("⬇️ 下載中文字型 (NotoSansTC)...")try:url = "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/TraditionalChinese/NotoSansTC-Regular.otf"r = requests.get(url, allow_redirects=True)with open(font_path, 'wb') as f:f.write(r.content)except:print("⚠️ 字型下載失敗,將使用系統預設字型")# 嘗試載入if os.path.exists(font_path):try:fm.fontManager.addfont(font_path)font_prop = fm.FontProperties(fname=font_path)plt.rcParams['font.family'] = font_prop.get_name()print(f"✅ 成功載入自訂字型: {font_prop.get_name()}")return font_propexcept Exception as e:print(f"⚠️ 字型載入錯誤: {e}")# 退路:使用系統常見字型system_fonts = ['Microsoft JhengHei', 'SimHei', 'Heiti TC', 'Taipei Sans TC Beta', 'Sans-Serif']plt.rcParams['font.sans-serif'] = system_fontsreturn NoneCUSTOM_FONT_PROP = set_custom_font()# === 配置與常數 ===COUNTY_MAP_FILE = "twCounty2010.json"TOWN_MAP_FILE = "twTown2010.json"# 縣市代碼對照表COUNTY_CODE_MAP = {'65000': '新北市', '63000': '臺北市', '68000': '桃園市', '66000': '臺中市','67000': '臺南市', '64000': '高雄市', '10002': '宜蘭縣', '10004': '新竹縣',7 unmodified linesREGION_FIELDS = ['縣市', '地區', '行政區', '代碼', 'code', 'id', 'site', 'site_id', '鄉鎮', '市區', 'town', 'district', '區域別', 'county', 'city', 'location']NON_VALUE_KEYWORDS = ['code', 'number', 'serial', 'index', 'lat', 'lon', 'year', 'date', 'yyy']# === 載入地圖函數 (修復 Crash 問題) ===GDF_COUNTY = NoneGDF_TOWN = Nonedef 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 None# 1. 讀取檔案gdf = gpd.read_file(filename)# 2. 轉換座標系if gdf.crs != "EPSG:4326":gdf = gdf.to_crs("EPSG:4326")# 3. 幾何修復 (重要修正:移除過度簡化)# 檢查無效幾何並修復if not gdf['geometry'].is_valid.all():gdf['geometry'] = gdf['geometry'].buffer(0)# 修改:將簡化程度大幅降低 (0.003 -> 0.0001) 或直接移除簡化# 0.0001 大約是 10 公尺精度,對於全台地圖來說夠用且安全try:gdf['geometry'] = gdf['geometry'].simplify(tolerance=0.0001, preserve_topology=True)except Exception as e:print(f"⚠️ 簡化幾何時發生警告 (已略過簡化): {e}")# 4. 再次過濾無效幾何 (避免 LinearRing 錯誤)gdf = gdf[gdf['geometry'].notna()]gdf = gdf[~gdf['geometry'].is_empty]# 欄位名稱標準化cols_lower = {c.lower(): c for c in gdf.columns}county_col = next((cols_lower[k] for k in ['countyname', 'county', 'c_name'] if k in cols_lower), None)town_col = next((cols_lower[k] for k in ['townname', 'town', 't_name'] if k in cols_lower), None)# 建立 '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:gdf['name'] = gdf[county_col]else:if county_col:gdf['name'] = gdf[county_col]if 'name' not in gdf.columns: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)gdf['name'] = gdf['name'].astype(str).str.replace('台', '臺')print(f"✅ 地圖 ({level}) 載入成功,筆數: {len(gdf)}")return gdfexcept Exception as e:print(f"❌ 地圖檔讀取失敗 ({filename}): {e}")# 如果出錯,回傳一個空但合法的 GeoDataFrame 以避免後續程式完全崩潰return gpd.GeoDataFrame({'name': [], 'geometry': []})def get_gdf(level):global GDF_TOWN, GDF_COUNTYif level == "town":if GDF_TOWN is None or GDF_TOWN.empty: GDF_TOWN = load_map_file("town")return GDF_TOWNelse:if GDF_COUNTY is None or GDF_COUNTY.empty: GDF_COUNTY = load_map_file("county")return GDF_COUNTYdef normalize_name(value) -> str:17 unmodified linesexcept: passreturn numeric_cols# === 資料解析邏輯 ===def smart_parse_data(df: pd.DataFrame):if df is None or df.empty: return None, "資料為空", [], [], [], "county", []# 1. 嘗試尋找真正的表頭data_start_idx = 0for i in range(min(5, len(df))):row = df.iloc[i]1 unmodified linetotal_count = 0for val in row:total_count += 1try:float(str(val).replace(',', ''))num_count += 1except: passif total_count > 0 and (num_count / total_count) > 0.4:data_start_idx = ibreakif 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"2 unmodified linesif 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"4 unmodified linesexclude = [region_col, time_col] if time_col else [region_col]numeric_cols = get_numeric_columns(df_processed, exclude)level_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, "請上傳檔案", gr.update(choices=[]), gr.update(choices=[]),gr.update(choices=[]), None, gr.update(choices=[]),gr.update(choices=[]), gr.update(choices=[]), "county")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, "不支援的格式", gr.update(choices=[]), gr.update(choices=[]),gr.update(choices=[]), None, gr.update(choices=[]),gr.update(choices=[]), gr.update(choices=[]), "county")processed_df, msg, cols, times, regions, map_level, time_cols = smart_parse_data(df)# 預先觸發地圖載入get_gdf(map_level)return (processed_df,msg,gr.update(choices=cols, value=cols[0] if cols else None),gr.update(choices=["全部"] + times, value="全部"),gr.update(choices=["全國總計"] + regions if regions else [], value="全國總計"),processed_df.head(5),gr.update(choices=time_cols, value=time_cols[0] if time_cols else None),gr.update(choices=times, value=times[-1] if times else None),gr.update(choices=times, value=times[0] if times else None),map_level)except Exception as e:import traceback; traceback.print_exc()return (None, f"錯誤: {e}", gr.update(choices=[]), gr.update(choices=[]),gr.update(choices=[]), None, gr.update(choices=[]),gr.update(choices=[]), gr.update(choices=[]), "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 or target_gdf.empty: raise gr.Error("地圖圖資載入失敗")if 'name' not in target_gdf.columns: target_gdf['name'] = target_gdf.index.astype(str)3 unmodified linesplot_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()25 unmodified linesif 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().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)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")return figexcept: 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 Noneif '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 Nonetry:plot_df = df.copy()plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)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())try:idx_start = all_times.index(str(start_t)) if str(start_t) in all_times else 0idx_end = all_times.index(str(end_t)) if str(end_t) in all_times else len(all_times)-1if idx_start > idx_end: idx_start, idx_end = idx_end, idx_startselected_times = all_times[idx_start : idx_end + 1]except: 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 = []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=(8, 8))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)raise gr.Error(f"GIF 產生失敗: {e}")# === Gradio 介面 ===with gr.Blocks(title="Open Data 視覺化", theme=gr.themes.Soft()) as demo:gr.Markdown("# 🇹🇼 臺灣 Open Data 視覺化儀表板")gr.Markdown("上傳含有「縣市/鄉鎮」與「時間」欄位的 CSV/Excel 檔案,自動生成地圖與趨勢圖。")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="📊 選擇數值指標", interactive=True)with gr.Accordion("🗺️ 地圖設定", open=True):time_selector = gr.Dropdown(label="時間點", choices=["全部"], value="全部", interactive=True)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="全國總計", interactive=True)line_metric = gr.Dropdown(label="輔助指標", choices=["年增率 (%)", "3年移動平均"], value="3年移動平均")btn_trend = gr.Button("更新趨勢圖")with gr.Accordion("🎬 GIF 動畫設定", open=False):gif_time_col = gr.Dropdown(label="時間欄位", interactive=True)with gr.Row():start_time = gr.Dropdown(label="起始時間", interactive=True)end_time = gr.Dropdown(label="結束時間", interactive=True)sort_order = gr.Radio(["時間正序 (舊 -> 新)", "時間反序 (新 -> 舊)"], label="播放順序", value="時間正序 (舊 -> 新)")fps_slider = gr.Slider(1, 10, 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()with gr.Tab("🎬 動畫輸出"):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],outputs=trend_output)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__":demo.queue().launch()
app.py+214-151