Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line234567891011121314151617181920212223243 unmodified lines2829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691 unmodified line1711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182191 unmodified lineimport geopandas as gpdimport pandas as pdimport plotly.express as pximport osimport requestsimport reimport json# === 1. 預先讀取地圖檔 & 建立區域對照表 ===map_file = "twCounty2010.geo.json"# 嘗試讀取地圖,若失敗則提供錯誤訊息try:gdf = gpd.read_file(map_file)# 確保座標系統是 WGS84 (經緯度),Plotly 需要這個格式if gdf.crs != "EPSG:4326":gdf = gdf.to_crs("EPSG:4326")except Exception as e:print(f"地圖檔讀取失敗: {e}")gdf = None# 台灣四大分區對照表REGION_MAPPING = {3 unmodified lines"east": ["花蓮縣", "臺東縣"]}# 反向對照表 (縣市 -> 區域)COUNTY_TO_REGION = {}for region, counties in REGION_MAPPING.items():for county in counties:COUNTY_TO_REGION[county] = region# === 2. 核心邏輯:智慧資料解析 ===def smart_parse_data(df):"""分辨資料格式並回傳: (處理後的DF, 模式訊息, 可選欄位列表)"""df_processed = df.copy()columns = [str(c) for c in df_processed.columns]# --- 策略 A: 找縣市欄位 (精細模式) ---county_keywords = ['縣市', 'City', 'County', 'location', 'site']target_col = Nonefor col in columns:if any(k in col for k in county_keywords) or \df_processed[col].astype(str).str.contains('臺北|台北|高雄').any():target_col = colbreakif target_col:# 清洗縣市名稱df_processed['name_mapped'] = df_processed[target_col].astype(str).str.replace('台', '臺')# 找出數值欄位numeric_cols = df_processed.select_dtypes(include=['float64', 'int64']).columns.tolist()numeric_cols = [c for c in numeric_cols if c != 'name_mapped']return df_processed, "精細模式 (縣市等級)", numeric_cols# --- 策略 B: 找區域欄位 (水利署資料模式) ---# 判斷邏輯:欄位名稱包含 'district' 且有 'north', 'central' 等字眼has_regional_keywords = any('district' in c.lower() for c in columns)if has_regional_keywords:# 1. 找出所有不含方位的「指標名稱」# 例如: centraldistrict[irrigation...] -> 提取 [irrigation...]metrics = set()for c in columns:# 移除方位詞和 districtcleaned = re.sub(r'(north|central|south|east)district', '', c, flags=re.IGNORECASE)# 排除非指標欄位if cleaned and cleaned not in [c, 'year', 'serialnumber', 'status']:metrics.add(cleaned)# 2. 自動過濾年份 (只取最新的一年)msg_extra = ""if 'year' in df_processed.columns:latest_year = df_processed['year'].max()df_processed = df_processed[df_processed['year'] == latest_year].copy()msg_extra = f"(已自動選取最新年份: {latest_year})"# 標記這是區域資料df_processed['is_regional'] = Truereturn df_processed, f"區域模式 (四大分區) {msg_extra}", list(metrics)return None, "無法辨識資料格式,請檢查欄位名稱", []# === 3. 讀取與繪圖 ===def load_data(file_obj):if file_obj is None: return Nonetry:# 嘗試讀取 JSON 或 CSVif file_obj.name.lower().endswith('.csv'):try:return pd.read_csv(file_obj.name, encoding='utf-8')except:return pd.read_csv(file_obj.name, encoding='big5')else:return pd.read_json(file_obj.name)except Exception as e:print(f"讀取錯誤: {e}")return Nonedef process_and_get_columns(file_obj):df = load_data(file_obj)if df is None:return None, "檔案讀取失敗", gr.Dropdown(choices=[])processed_df, mode_msg, cols = smart_parse_data(df)if processed_df is None:return None, mode_msg, gr.Dropdown(choices=[])return processed_df, mode_msg, gr.Dropdown(choices=cols, value=cols[0] if cols else None)def generate_map(df, selected_col):if df is None or not selected_col:return None, "請先載入資料"if gdf is None:return None, "錯誤:找不到地圖檔 twCounty2010.geo.json"try:plot_data = gdf.copy()plot_title = ""# === 分支 1: 區域模式 (Broadcasting) ===if 'is_regional' in df.columns and df['is_regional'].iloc[0]:# 從第一列資料中提取北中南東的數值row = df.iloc[0]region_values = {}for region in ['north', 'central', 'south', 'east']:# 組合回原本的欄位名稱target_key = f"{region}district{selected_col}"# 在 columns 裡找即使大小寫不同也能對應的欄位found_col = next((c for c in df.columns if c.lower() == target_key.lower()), None)val = 0if found_col:try:val = float(row[found_col])except:val = 0region_values[region] = val# 將數值映射到每個縣市plot_data['region_group'] = plot_data['name'].map(COUNTY_TO_REGION)plot_data['value'] = plot_data['region_group'].map(region_values).fillna(0)plot_title = f"區域統計: {selected_col}"# === 分支 2: 精細模式 (County Level) ===else:# 確保數值格式正確df['value_clean'] = pd.to_numeric(df[selected_col], errors='coerce').fillna(0)# 依照縣市名稱合併df_agg = df.groupby('name_mapped')['value_clean'].sum().reset_index()plot_data = plot_data.merge(df_agg, left_on='name', right_on='name_mapped', how='left')plot_data['value'] = plot_data['value_clean'].fillna(0)plot_title = f"縣市統計: {selected_col}"# === 使用 Plotly 繪圖 (互動式) ===# 設定 index 為 name 以便顯示plot_data = plot_data.set_index('name')fig = px.choropleth(1 unmodified linegeojson=plot_data.geometry,locations=plot_data.index,color='value',color_continuous_scale="OrRd", # 橘紅配色projection="mercator",title=plot_title)# 調整地圖顯示範圍 (聚焦台灣)fig.update_geos(fitbounds="locations", visible=False)fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0}) # 調整邊界return fig, f"繪製成功!({plot_title})"except Exception as e:return None, f"繪圖發生錯誤: {str(e)}"# === Gradio 介面 ===with gr.Blocks() as demo:gr.Markdown("# 🇹🇼 台灣農業地圖 (互動縮放版)")gr.Markdown("支援 JSON/CSV,自動判斷縣市或區域資料。滑鼠滾輪可縮放地圖。")current_df = gr.State()with gr.Row():with gr.Column(scale=1):file_input = gr.File(label="步驟 1: 上傳資料 (JSON/CSV)")status_text = gr.Textbox(label="系統訊息", interactive=False)col_selector = gr.Dropdown(label="步驟 2: 選擇指標")btn = gr.Button("繪製地圖", variant="primary")with gr.Column(scale=2):# 使用 gr.Plot 來顯示 Plotly 圖表plot_output = gr.Plot(label="互動地圖")# 事件處理file_input.change(fn=process_and_get_columns,inputs=file_input,outputs=[current_df, status_text, col_selector])btn.click(fn=generate_map,inputs=[current_df, col_selector],outputs=[plot_output, status_text])demo.launch()1 unmodified line23456789101112131415163 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622631 unmodified line2652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903911 unmodified lineimport geopandas as gpdimport pandas as pdimport plotly.express as pximport plotly.graph_objects as goimport osimport reimport warningswarnings.filterwarnings('ignore')# === 配置與常數 ===MAP_FILE = "twCounty2010.geo.json"CACHE_DIR = "./cache"# 台灣四大分區對照表REGION_MAPPING = {3 unmodified lines"east": ["花蓮縣", "臺東縣"]}COUNTY_TO_REGION = {county: region for region, counties in REGION_MAPPING.items() for county in counties}# === 1. 預先載入地圖檔 ===def load_map_file():"""載入並快取地圖檔案"""try:if not os.path.exists(MAP_FILE):raise FileNotFoundError(f"找不到地圖檔案: {MAP_FILE}")gdf = gpd.read_file(MAP_FILE)if gdf.crs != "EPSG:4326":gdf = gdf.to_crs("EPSG:4326")# 標準化縣市名稱gdf['name'] = gdf['name'].str.replace('台', '臺')print(f"✓ 地圖檔載入成功: {len(gdf)} 個縣市")return gdfexcept Exception as e:print(f"✗ 地圖檔載入失敗: {e}")return None# 全域載入地圖GDF = load_map_file()# === 2. 資料解析邏輯 ===def smart_parse_data(df):"""智慧解析資料格式回傳: (處理後的DataFrame, 模式訊息, 可選欄位, 可選年份)"""if df is None or df.empty:return None, "資料為空", [], []df_processed = df.copy()columns = [str(c) for c in df_processed.columns]# 處理年份欄位available_years = []if 'year' in df_processed.columns:df_processed['year'] = df_processed['year'].astype(str)available_years = sorted(df_processed['year'].unique().tolist(),key=lambda x: (len(x), x),reverse=True)# === 模式 A: 縣市級資料 ===county_keywords = ['縣市', 'City', 'County', 'location', 'site', 'region']county_col = Nonefor col in columns:# 檢查欄位名稱或內容if any(k in col for k in county_keywords):county_col = colbreak# 檢查內容是否包含台灣縣市名if df_processed[col].astype(str).str.contains('臺北|台北|高雄|台中|臺中').any():county_col = colbreakif county_col:df_processed['name_mapped'] = df_processed[county_col].astype(str).str.replace('台', '臺')numeric_cols = df_processed.select_dtypes(include=['float64', 'int64']).columns.tolist()numeric_cols = [c for c in numeric_cols if c not in ['name_mapped', 'year']]return df_processed, "✓ 縣市級資料模式", numeric_cols, available_years# === 模式 B: 區域級資料 (四大分區) ===regional_pattern = r'(north|central|south|east)district'has_regional = any(re.search(regional_pattern, c, re.IGNORECASE) for c in columns)if has_regional:# 提取指標名稱metrics = set()for c in columns:cleaned = re.sub(regional_pattern, '', c, flags=re.IGNORECASE)if cleaned and cleaned not in ['year', 'serialnumber', 'status', '']:metrics.add(cleaned)df_processed['is_regional'] = True# 過濾無效年份if available_years:valid_years = []for year in available_years:year_data = df_processed[df_processed['year'] == year]# 檢查是否有任何區域有數據has_data = Falsefor col in columns:if re.search(regional_pattern, col, re.IGNORECASE):val = year_data[col].iloc[0] if not year_data.empty else Noneif pd.notna(val) and str(val).strip() != "":try:if float(val) != 0:has_data = Truebreakexcept:passif has_data:valid_years.append(year)available_years = valid_years if valid_years else available_yearsreturn df_processed, "✓ 區域級資料模式 (四大分區)", sorted(list(metrics)), available_yearsreturn None, "✗ 無法識別資料格式 (請確保包含縣市或區域欄位)", [], []# === 3. 資料載入 ===def load_data(file_obj):"""載入 CSV 或 JSON 檔案"""if file_obj is None:return Nonetry:file_path = file_obj.nameif file_path.lower().endswith('.csv'):# 嘗試不同編碼for encoding in ['utf-8', 'big5', 'cp950', 'gbk']:try:df = pd.read_csv(file_path, encoding=encoding)print(f"✓ CSV 載入成功 (編碼: {encoding})")return dfexcept UnicodeDecodeError:continueraise ValueError("無法以任何編碼讀取 CSV 檔案")elif file_path.lower().endswith('.json'):df = pd.read_json(file_path)print(f"✓ JSON 載入成功")return dfelse:raise ValueError("不支援的檔案格式 (僅支援 CSV 和 JSON)")except Exception as e:print(f"✗ 資料載入失敗: {e}")return None# === 4. 處理上傳檔案 ===def process_and_get_options(file_obj):"""處理上傳的檔案並返回選項"""if file_obj is None:return None, "請上傳資料檔案", gr.Dropdown(choices=[]), gr.Dropdown(choices=[])df = load_data(file_obj)if df is None:return None, "✗ 檔案讀取失敗", gr.Dropdown(choices=[]), gr.Dropdown(choices=[])processed_df, mode_msg, cols, years = smart_parse_data(df)if processed_df is None:return None, mode_msg, gr.Dropdown(choices=[]), gr.Dropdown(choices=[])# 設定預設值default_col = cols[0] if cols else Nonedefault_year = years[0] if years else Nonestatus_msg = f"{mode_msg}\n資料筆數: {len(df)}\n可用指標: {len(cols)}\n可用年份: {len(years)}"return (processed_df,status_msg,gr.Dropdown(choices=cols, value=default_col, interactive=True),gr.Dropdown(choices=years, value=default_year, interactive=True))# === 5. 繪製地圖 ===def generate_map(df, selected_col, selected_year):"""生成互動式地圖"""if df is None:return None, "✗ 請先上傳資料檔案"if not selected_col:return None, "✗ 請選擇要顯示的指標"if GDF is None:return None, "✗ 地圖檔案載入失敗,請檢查 twCounty2010.geo.json 是否存在"try:# 過濾年份current_df = df.copy()if selected_year and 'year' in current_df.columns:current_df = current_df[current_df['year'] == str(selected_year)]if current_df.empty:return None, f"✗ {selected_year} 年無資料"plot_data = GDF.copy()# === 區域模式 ===if 'is_regional' in df.columns and df['is_regional'].iloc[0]:if current_df.empty:return None, "✗ 所選年份無資料"row = current_df.iloc[0]region_values = {}for region in ['north', 'central', 'south', 'east']:col_pattern = f"{region}district{selected_col}"matched_col = next((c for c in df.columns if c.lower() == col_pattern.lower()),None)val = 0if matched_col:try:raw_val = row[matched_col]if pd.notna(raw_val) and str(raw_val).strip() != "":val = float(raw_val)except (ValueError, TypeError):val = 0region_values[region] = valplot_data['region_group'] = plot_data['name'].map(COUNTY_TO_REGION)plot_data['value'] = plot_data['region_group'].map(region_values).fillna(0)plot_title = f"區域統計: {selected_col} ({selected_year}年)"# === 縣市模式 ===else:df_agg = current_df.copy()df_agg['value_clean'] = pd.to_numeric(df_agg[selected_col], errors='coerce').fillna(0)if 'name_mapped' in df_agg.columns:df_agg = df_agg.groupby('name_mapped')['value_clean'].sum().reset_index()plot_data = plot_data.merge(df_agg,left_on='name',right_on='name_mapped',how='left')plot_data['value'] = plot_data.get('value_clean', 0).fillna(0)plot_title = f"縣市統計: {selected_col} ({selected_year}年)"# === 繪製地圖 ===plot_data = plot_data.set_index('name')fig = px.choropleth(1 unmodified linegeojson=plot_data.geometry,locations=plot_data.index,color='value',color_continuous_scale="YlOrRd",projection="mercator",title=plot_title,hover_name=plot_data.index,hover_data={'value': ':.2f'})fig.update_geos(fitbounds="locations",visible=False)fig.update_layout(margin={"r": 0, "t": 60, "l": 0, "b": 0},height=600,font=dict(size=14),coloraxis_colorbar=dict(title=selected_col,thickness=15,len=0.7))return fig, f"✓ 繪製成功: {plot_title}"except Exception as e:import tracebackerror_detail = traceback.format_exc()print(f"繪圖錯誤:\n{error_detail}")return None, f"✗ 繪圖錯誤: {str(e)}"# === 6. Gradio 介面 ===def create_interface():"""建立 Gradio 介面"""with gr.Blocks(theme=gr.themes.Soft(),title="台灣農業地圖視覺化") as demo:gr.Markdown("""# 🇹🇼 台灣農業地圖視覺化系統上傳 CSV 或 JSON 資料檔案,系統會自動識別資料格式並生成互動式地圖。**支援格式:**- 縣市級資料 (包含縣市名稱欄位)- 區域級資料 (四大分區: north/central/south/east)""")current_df = gr.State()with gr.Row():with gr.Column(scale=1):gr.Markdown("### 📤 資料上傳與設定")file_input = gr.File(label="步驟 1: 上傳資料檔案",file_types=['.csv', '.json'],type="filepath")status_text = gr.Textbox(label="系統狀態",interactive=False,lines=4)year_selector = gr.Dropdown(label="步驟 2: 選擇年份",interactive=True)col_selector = gr.Dropdown(label="步驟 3: 選擇指標",interactive=True)btn = gr.Button("🗺️ 繪製地圖",variant="primary",size="lg")gr.Markdown("""---**使用說明:**1. 上傳資料檔案2. 選擇年份和指標3. 點擊「繪製地圖」**注意:** 地圖需要 `twCounty2010.geo.json` 檔案""")with gr.Column(scale=2):gr.Markdown("### 🗺️ 互動式地圖")plot_output = gr.Plot(label="視覺化結果")# 事件綁定file_input.change(fn=process_and_get_options,inputs=file_input,outputs=[current_df, status_text, col_selector, year_selector])btn.click(fn=generate_map,inputs=[current_df, col_selector, year_selector],outputs=[plot_output, status_text])return demo# === 7. 啟動應用 ===if __name__ == "__main__":demo = create_interface()demo.launch(server_name="0.0.0.0", # Hugging Face 需要server_port=7860, # Hugging Face 預設埠share=False,show_error=True)
app.py+317-145