Spaces:
Sleeping
Sleeping
Update app.py
Browse files20 unmodified lines21222324242526272728282930313232333435363738394041424344454647484950515253545556575859603334353637383940414243444546474849625051525354675556575825 unmodified lines84858699878889909192105939495969798991001011027 unmodified lines1101111121231131141151161171181191301311201211221231241251371261271281291301421431311451461471481321331341351364 unmodified lines14114214315914414514621 unmodified lines16816917018718817119019117217317417517689 unmodified lines26626726828728826927027127216 unmodified lines2892902913112922933133143153162942952962976 unmodified lines30430530632930730830973 unmodified lines38338438540938638738836 unmodified lines42542642745242842943043115 unmodified lines44744844945045145245345420 unmodified linesmatplotlib.use('Agg') plt.rcParams['axes.unicode_minus'] = False
# === 0. 自動下載與修復地圖檔 ===# === 0. 自動下載與檢查地圖檔 ===def check_and_download_maps(): # 修正下載連結 (Ronnywang repo 的檔名通常是小寫) 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" "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(): # 檢查檔案是否存在,若存在則檢查是否異常 (例如鄉鎮檔過小) need_download = False if not os.path.exists(filename): need_download = True print(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 = True except: need_download = True
if 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}") # 如果檔案已經存在 (使用者自己上傳了),就直接使用,不重新下載 if os.path.exists(filename): print(f"📂 偵測到現有檔案: {filename},將直接使用。") continue print(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'] 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_FILE try: if not os.path.exists(filename): print(f"❌ 嚴重錯誤: 找不到地圖檔 {filename}") print(f"❌ 找不到地圖檔 {filename},請確保已上傳。") return None gdf = 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 lines for key in ['townname', 'town', 't_name']: if key in cols_lower: town_col = cols_lower[key]; break # 建立 'name' 欄位 (這是產生錯誤的關鍵點,這裡加強防呆) # 建立 '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}。將使用該欄位作為名稱。") 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']).columns if len(str_cols) > 0: gdf['name'] = gdf[str_cols[0]] else: gdf['name'] = gdf.index.astype(str) if 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 lines print(f"❌ 地圖檔讀取失敗 ({filename}): {e}") return None
# 全域變數快取 (重置為 None 確保重新載入)GDF_COUNTY = NoneGDF_TOWN = None
21 unmodified lines if pd.api.types.is_numeric_dtype(df[col]): numeric_cols.append(col) else: sample = df[col].dropna().head(50) if sample.empty: continue try: numeric_count = pd.to_numeric(sample, errors='coerce').notna().sum() if numeric_count / len(sample) > 0.8: numeric_cols.append(col) if pd.to_numeric(df[col].dropna().head(50), errors='coerce').notna().sum() > 0: numeric_cols.append(col) except: pass return numeric_cols
89 unmodified lines processed_df, msg, cols, times, regions, map_level, time_cols = smart_parse_data(df) # 這裡會觸發地圖下載與檢查 get_gdf(map_level) get_gdf(map_level) # 觸發地圖載入 return ( processed_df, msg, 16 unmodified lines if df is None: raise gr.Error("請先上傳資料") if not col: raise gr.Error("未選擇指標") if target_gdf is None: raise gr.Error("地圖圖資載入失敗") if target_gdf is None: raise gr.Error("地圖圖資載入失敗,請確認 GeoJSON 檔案存在") # 這裡檢查 'name' 是否存在,如果不存在,手動創造一個,避免 crash if 'name' not in target_gdf.columns: print("⚠️ 地圖檔缺少 'name' 欄位,嘗試修復...") target_gdf['name'] = target_gdf.index.astype(str) if 'name' not in target_gdf.columns: target_gdf['name'] = target_gdf.index.astype(str)
try: plot_df = df.copy()6 unmodified lines 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() # 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("## 🇹🇼 資料視覺化儀表板 (強健版)") gr.Markdown("## 🇹🇼 資料視覺化儀表板 (修復版)") current_df = gr.State() map_level_state = gr.State(value="county") 15 unmodified lines 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):app.py+39-61