Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425261 unmodified line2829303132333435363738394041424344458 unmodified lines545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162175 unmodified lines223224225226227228229import gradio as grimport geopandas as gpdimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.font_manager as fmimport osimport requestsimport re# === 1. 設定中文字型 ===font_path = "TraditionalChinese.ttf"if os.path.exists(font_path):font_prop = fm.FontProperties(fname=font_path)plt.rcParams['font.family'] = font_prop.get_name()else:plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']plt.rcParams['axes.unicode_minus'] = False# === 2. 預先讀取地圖檔 & 建立區域對照表 ===map_file = "twCounty2010.geo.json"gdf = gpd.read_file(map_file)# 台灣四大分區對照表 (用於備援模式)REGION_MAPPING = {"north": ["基隆市", "臺北市", "新北市", "桃園市", "新竹市", "新竹縣", "宜蘭縣"],"central": ["苗栗縣", "臺中市", "彰化縣", "南投縣", "雲林縣"],1 unmodified line"east": ["花蓮縣", "臺東縣"]}# 反向對照表: 縣市 -> 區域 (程式繪圖時是用縣市去找區域)COUNTY_TO_REGION = {}for region, counties in REGION_MAPPING.items():for county in counties:COUNTY_TO_REGION[county] = region# === 3. 核心邏輯:智慧資料解析 ===def smart_parse_data(df):"""判斷資料是「精細縣市版」還是「粗略區域版」,並回傳處理後的標準格式。回傳格式: (Standard_DF, Mode_Message, Available_Columns)"""df_processed = df.copy()columns = [str(c) for c in df_processed.columns]8 unmodified linesbreakif 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']if not numeric_cols:# 嘗試把 string 轉 numericfor c in columns:if c == target_col or c == 'name_mapped': continuetry:df_processed[c] = pd.to_numeric(df_processed[c])numeric_cols.append(c)except:passreturn df_processed, "模式:精細縣市 (County Level)", numeric_cols# --- 策略 B: 找區域欄位 (備援模式) ---# 檢查是否符合您提供的 JSON 格式 (column 名稱包含 district)# 您的 JSON 是 "Wide Format" (一年一列),我們需要轉置或讓使用者選欄位# 偵測關鍵字: north, central, south, easthas_regional_keywords = any(re.search(r'(north|central|south|east).*district', c, re.IGNORECASE) for c in columns)if has_regional_keywords:# 這通常是 Time Series 資料 (一年一筆),我們需要讓使用者選擇「指標 (Metric)」# 1. 先把欄位名稱拆解,找出所有可能的「指標」# 例如: "centraldistrictirrigation" -> 去掉 "centraldistrict" -> 剩下 "irrigation"metrics = set()for c in columns:cleaned = re.sub(r'(north|central|south|east)district', '', c, flags=re.IGNORECASE)if cleaned and cleaned != c and cleaned != 'year' and cleaned != 'serialnumber':metrics.add(cleaned)# 如果有年份,我們需要把資料展開 (或是讓使用者選年份,這裡我們先簡化:取最新年份)if 'year' in df_processed.columns:latest_year = df_processed['year'].max()df_processed = df_processed[df_processed['year'] == latest_year].copy()msg = f"模式:四大區域 (Regional Level) - 自動選取年份 {latest_year}"else:df_processed = df_processed.iloc[0:1].copy() # 只取第一筆msg = "模式:四大區域 (Regional Level)"# 這裡我們不回傳標準的 DataFrame,而是回傳一個標記,讓繪圖函數知道要用區域邏輯# 為了配合介面,我們把「指標」當作 columns 回傳df_processed['is_regional'] = Truereturn df_processed, msg, list(metrics)return None, "無法辨識資料格式", []# === 4. 讀取與繪圖 ===def load_data(file_obj):if file_obj is None: return Nonetry:if file_obj.name.lower().endswith('.csv'):df = pd.read_csv(file_obj.name, encoding='utf-8')else:df = pd.read_json(file_obj.name)return dfexcept:try:df = pd.read_csv(file_obj.name, encoding='big5') # 再試一次 Big5return dfexcept Exception as 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)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, "請先載入資料"fig, ax = plt.subplots(1, 1, figsize=(10, 10))font_kwargs = {'fontproperties': font_prop} if os.path.exists(font_path) else {}try:# === 分支 1: 區域模式 (Four Regions) ===if 'is_regional' in df.columns and df['is_regional'].iloc[0]:# 抓取該指標在四個區域的數值# 組合欄位名稱: e.g., "northdistrict" + "irrigation..."row = df.iloc[0]region_values = {}for region in ['north', 'central', 'south', 'east']:# 模糊比對欄位名稱 (忽略大小寫)target_key = f"{region}district{selected_col}"# 在 df columns 找符合的found_col = next((c for c in df.columns if c.lower() == target_key.lower()), None)if found_col:val = pd.to_numeric(row[found_col], errors='coerce')region_values[region] = val if not pd.isna(val) else 0else:region_values[region] = 0# 將數值映射到地圖的每個縣市# 1. 複製地圖資料plot_data = gdf.copy()# 2. 建立新欄位 'region'plot_data['region_group'] = plot_data['name'].map(COUNTY_TO_REGION)# 3. 填入數值plot_data['plot_value'] = plot_data['region_group'].map(region_values).fillna(0)title = f"區域統計: {selected_col} (四大分區)"# === 分支 2: 精細模式 (County Level) ===else:# 標準合併df['plot_value'] = pd.to_numeric(df[selected_col], errors='coerce').fillna(0)# 加總 (處理重���縣市)df_agg = df.groupby('name_mapped')['plot_value'].sum().reset_index()plot_data = gdf.merge(df_agg, left_on='name', right_on='name_mapped', how='left')plot_data['plot_value'] = plot_data['plot_value'].fillna(0)title = f"縣市統計: {selected_col}"# === 統一繪圖 ===plot_data.plot(column='plot_value',cmap='OrRd',linewidth=0.8,ax=ax,edgecolor='0.6',legend=True,legend_kwds={'label': "數值", 'orientation': "horizontal"})ax.set_title(title, fontsize=18, **font_kwargs)ax.set_axis_off()return fig, "繪製成功"except Exception as e:return None, f"繪圖錯誤: {str(e)}"# === Gradio 介面 ===with gr.Blocks() as demo:gr.Markdown("# 🇹🇼 台灣農業地圖 (智慧整合版)")gr.Markdown("系統會自動判斷:若資料有縣市欄位則畫精細圖;若只有區域欄位(如北區、中區)則畫四大色塊。")current_df = gr.State()with gr.Row():with gr.Column():file_input = gr.File(label="上傳 CSV 或 JSON")status_text = gr.Textbox(label="偵測模式", interactive=False)col_selector = gr.Dropdown(label="選擇數據指標")btn = gr.Button("繪製地圖", variant="primary")with gr.Column():plot_output = gr.Plot()# 事件處理file_input.change(5 unmodified linesbtn.click(fn=generate_map,inputs=[current_df, col_selector],outputs=[plot_output, status_text] # 狀態列會顯示繪圖結果或錯誤)demo.launch()12345678910111213141516171819202122232425261 unmodified line28293031323334353637383940414243448 unmodified lines53545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062075 unmodified lines213214215216217218219import gradio as grimport 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 = {"north": ["基隆市", "臺北市", "新北市", "桃園市", "新竹市", "新竹縣", "宜蘭縣"],"central": ["苗栗縣", "臺中市", "彰化縣", "南投縣", "雲林縣"],1 unmodified line"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]8 unmodified linesbreakif 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(plot_data,geojson=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(5 unmodified linesbtn.click(fn=generate_map,inputs=[current_df, col_selector],outputs=[plot_output, status_text])demo.launch()
app.py+106-116