Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines5678910111213141 unmodified line1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931944 unmodified linesimport matplotlib.font_manager as fmimport osimport requestsimport json# === 設定中文字型 ===font_path = "kaiu.ttf"if os.path.exists(font_path):font_prop = fm.FontProperties(fname=font_path)plt.rcParams['font.family'] = font_prop.get_name()1 unmodified lineplt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']plt.rcParams['axes.unicode_minus'] = False# === 預先讀取地圖檔 ===map_file = "twCounty2010.geo.json"gdf = gpd.read_file(map_file)def process_dataframe(df):"""通用資料處理:清洗縣市名稱"""try:# 自動抓取第一個欄位當作縣市名稱county_col = df.columns[0]# 統一將 '台' 轉為 '臺',並轉為字串df['name'] = df[county_col].astype(str).str.replace('台', '臺')return dfexcept Exception as e:print(f"資料清洗失敗: {e}")return Nonedef load_from_file(file_obj):"""從上傳的檔案讀取"""if file_obj is None: return Nonefile_path = file_obj.nameext = os.path.splitext(file_path)[1].lower()try:if ext == '.csv':try:df = pd.read_csv(file_path, encoding='utf-8')except:df = pd.read_csv(file_path, encoding='big5')elif ext == '.json':df = pd.read_json(file_path)else:return Nonereturn process_dataframe(df)except Exception as e:print(f"檔案讀取錯誤: {e}")return Nonedef load_from_url(url):"""從網址 API 讀取"""if not url: return Nonetry:# verify=False 是為了避開某些政府網站 SSL 憑證驗證失敗的問題# headers 是為了模擬瀏覽器,避免被擋headers = {'User-Agent': 'Mozilla/5.0'}response = requests.get(url, verify=False, headers=headers)# 嘗試解析 JSONdata = response.json()# 處理不同結構的 JSON# 有些 API 會把資料包在 "result" 或 "records" 裡面if isinstance(data, dict):# 常見的鍵值,嘗試尋找列表資料for key in ['result', 'records', 'data', 'features']:if key in data and isinstance(data[key], list):data = data[key]breakdf = pd.DataFrame(data)return process_dataframe(df)except Exception as e:print(f"網址讀取錯誤: {e}")return Nonedef update_columns(df):"""當資料更新時,回傳新的下拉選單選項"""if df is not None:# 抓出數值欄位cols = df.select_dtypes(include=['float64', 'int64']).columns.tolist()# 如果沒有純數值欄位,就排除第一欄(縣市)後全抓if not cols:cols = df.columns[1:].tolist()return gr.Dropdown(choices=cols, value=cols[0] if cols else None), "資料載入成功!"return gr.Dropdown(choices=[], value=None), "資料讀取失敗或格式錯誤"def generate_map(df, col_to_plot):"""繪圖函數 (現在接收 df 而不是檔案路徑)"""if df is None:return None, "請先載入資料"try:# 彙整資料if col_to_plot in df.columns:df[col_to_plot] = pd.to_numeric(df[col_to_plot], errors='coerce').fillna(0)df_agg = df.groupby('name')[col_to_plot].sum().reset_index()else:return None, f"找不到欄位:{col_to_plot}"# 合併地圖merged_data = gdf.merge(df_agg, on='name', how='left')merged_data[col_to_plot] = merged_data[col_to_plot].fillna(0)# 繪圖fig, ax = plt.subplots(1, 1, figsize=(10, 10))font_kwargs = {'fontproperties': font_prop} if os.path.exists(font_path) else {}merged_data.plot(column=col_to_plot,cmap='OrRd',linewidth=0.8,ax=ax,edgecolor='0.8',legend=True,legend_kwds={'label': "數值", 'orientation': "horizontal"})ax.set_title(f'統計地圖 - {col_to_plot}', fontsize=20, **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("# 🇹🇼 台灣資料地圖產生器 (檔案 / API)")# 建立一個 State 來暫存目前的 DataFrame,讓不同分頁都能共用current_df = gr.State()with gr.Row():with gr.Column():# 使用 Tabs 分頁切換來源with gr.Tabs():with gr.TabItem("方法 1: 上傳檔案"):file_input = gr.File(label="上傳 CSV 或 JSON")with gr.TabItem("方法 2: 輸入 API 網址"):url_input = gr.Textbox(label="JSON API 網址", placeholder="例如: https://data.gov.tw/.../json")url_btn = gr.Button("抓取網址資料")# 共用的操作區gr.Markdown("---") # 分隔線col_selector = gr.Dropdown(label="選擇數值欄位", choices=[])plot_btn = gr.Button("繪製地圖", variant="primary")status_text = gr.Textbox(label="狀態", interactive=False)with gr.Column():plot_output = gr.Plot(label="地圖預覽")# === 事件綁定 ===# 1. 當上傳檔案時 -> 讀檔 -> 存入 State -> 更新下拉選單file_input.change(fn=load_from_file,inputs=file_input,outputs=current_df).then(fn=update_columns,inputs=current_df,outputs=[col_selector, status_text])# 2. 當按下網址抓取按鈕時 -> 讀網址 -> 存入 State -> 更新下拉選單url_btn.click(fn=load_from_url,inputs=url_input,outputs=current_df).then(fn=update_columns,inputs=current_df,outputs=[col_selector, status_text])# 3. 按下繪製按鈕 -> 從 State 拿資料繪圖plot_btn.click(fn=generate_map,inputs=[current_df, col_selector],outputs=[plot_output, status_text])demo.launch()4 unmodified lines5678910111213141 unmodified line1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282294 unmodified linesimport 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()1 unmodified lineplt.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": ["苗栗縣", "臺中市", "彰化縣", "南投縣", "雲林縣"],"south": ["嘉義市", "嘉義縣", "臺南市", "高雄市", "屏東縣", "澎湖縣"],"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]# --- 策略 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']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(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()
app.py+174-139