Spaces:
Sleeping
Sleeping
Update app.py
Browse files20 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697025 unmodified lines969798991001011021031041051061071081091101111127 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501514 unmodified lines15615715815916016116221 unmodified lines18418518618718818919019119219319489 unmodified lines28428528628728828929029116 unmodified lines3083093103113123133143153163173183196 unmodified lines32632732832933033133273 unmodified lines40640740840941041141236 unmodified lines44945045145245345445515 unmodified lines47147247347447547620 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:f.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']font_filename = "kaiu.ttf"if os.path.exists(font_filename):try:25 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")gdf['geometry'] = gdf['geometry'].simplify(tolerance=0.003, preserve_topology=True)# 欄位名稱偵測7 unmodified linesfor 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('台', '臺')4 unmodified linesprint(f"❌ 地圖檔讀取失敗 ({filename}): {e}")return None# 全域變數快取 (重置為 None 確保重新載入)GDF_COUNTY = NoneGDF_TOWN = None21 unmodified linesif pd.api.types.is_numeric_dtype(df[col]):numeric_cols.append(col)else:sample = df[col].dropna().head(50)if sample.empty: continuetry:numeric_count = pd.to_numeric(sample, errors='coerce').notna().sum()if numeric_count / len(sample) > 0.8: numeric_cols.append(col)except: passreturn numeric_cols89 unmodified linesprocessed_df, msg, cols, times, regions, map_level, time_cols = smart_parse_data(df)# 這裡會觸發地圖下載與檢查get_gdf(map_level)return (processed_df, msg,16 unmodified linesif 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)73 unmodified linesdef 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)36 unmodified lines# === Gradio ===with gr.Blocks(title="Open Data 視覺化") as demo:gr.Markdown("## 🇹🇼 資料視覺化儀表板 (強健版)")current_df = gr.State()map_level_state = gr.State(value="county")15 unmodified lineswith 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):20 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575825 unmodified lines848586878889909192939495969798991001011027 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351364 unmodified lines14114214314414514621 unmodified lines16816917017117217317417517689 unmodified lines26626726826927027127216 unmodified lines2892902912922932942952962976 unmodified lines30430530630730830973 unmodified lines38338438538638738836 unmodified lines42542642742842943043115 unmodified lines44744844945045145245345420 unmodified linesmatplotlib.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:with open(filename, 'wb') as f:f.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:25 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)# 欄位名稱偵測7 unmodified linesfor 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('台', '臺')4 unmodified linesprint(f"❌ 地圖檔讀取失敗 ({filename}): {e}")return NoneGDF_COUNTY = NoneGDF_TOWN = None21 unmodified linesif pd.api.types.is_numeric_dtype(df[col]):numeric_cols.append(col)else:try:if pd.to_numeric(df[col].dropna().head(50), errors='coerce').notna().sum() > 0:numeric_cols.append(col)except: passreturn numeric_cols89 unmodified linesprocessed_df, msg, cols, times, regions, map_level, time_cols = smart_parse_data(df)get_gdf(map_level) # 觸發地圖載入return (processed_df, msg,16 unmodified linesif 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)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)73 unmodified linesdef 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)36 unmodified lines# === Gradio ===with gr.Blocks(title="Open Data 視覺化") as demo:gr.Markdown("## 🇹🇼 資料視覺化儀表板 (修復版)")current_df = gr.State()map_level_state = gr.State(value="county")15 unmodified lineswith 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):
app.py+39-61