Spaces:
Sleeping
Sleeping
Update app.py
Browse files145 unmodified lines1461471481491501511523 unmodified lines15615715815916016116216316416516616716816917017117217317417517617717817911 unmodified lines19119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223342 unmodified lines2762772782792802812822832842852862872882892906 unmodified lines29729829930030130230348 unmodified lines352353354355356357358359360361362363364145 unmodified linesreturn numeric_colsdef smart_parse_data(df: pd.DataFrame):if df is None or df.empty: return None, "資料為空", [], [], [], "unknown", []# 1. 資料清洗 (雙重標題偵測)data_start_idx = 03 unmodified linestotal_count = 0for val in row:total_count += 1try: float(str(val).replace(',', '')); num_count += 1except: passif total_count > 0 and (num_count / total_count) > 0.4:data_start_idx = i; breakif data_start_idx > 0:new_header = df.iloc[data_start_idx-1]df_processed = df.iloc[data_start_idx:].copy()df_processed.columns = new_headerelse:df_processed = df.copy()for col in df_processed.columns:try: df_processed[col] = pd.to_numeric(df_processed[col])except: pass# 2. 時間偵測possible_time_cols = [c for c in df_processed.columns if any(k in str(c) for k in TIME_FIELDS)]if not possible_time_cols:for col in df_processed.columns:if pd.api.types.is_numeric_dtype(df_processed[col]):11 unmodified linesavailable_times = [str(t) for t in sorted_times]except:available_times = sorted(df_processed['time_parsed'].unique(), reverse=True)# 3. 自動層級偵測 (關鍵邏輯)region_col = Nonepotential_cols = [c for c in df_processed.columns if any(k in str(c).lower() for k in REGION_FIELDS)]map_level = "county" # 預設縣市for col in potential_cols + list(df_processed.columns):if col not in df_processed.columns: continuesample = df_processed[col].dropna().head(20).astype(str).tolist()if not sample: continue# 偵測鄉鎮關鍵字has_town = any(('區' in s or '鄉' in s or '鎮' in s) for s in sample)# 偵測縣市關鍵字has_county = any(('縣' in s or '市' in s) for s in sample)if has_town:region_col = col; map_level = "town"; break # 優先判定為鄉鎮elif has_county and not region_col:region_col = col; map_level = "county"regions = []if region_col:df_processed['region_normalized'] = df_processed[region_col].apply(normalize_name)regions = sorted(df_processed[df_processed['region_normalized']!=""]['region_normalized'].unique().tolist())exclude = [region_col, time_col] if time_col else [region_col]numeric_cols = get_numeric_columns(df_processed, exclude)level_name = "鄉鎮市區" if map_level == "town" else "縣市"msg = f"✓ 偵測成功 ({level_name}層級: {region_col})"else:msg = "⚠️ 未偵測到地區欄位"exclude = [time_col] if time_col else []numeric_cols = get_numeric_columns(df_processed, exclude)return df_processed, msg, numeric_cols, available_times, regions, map_level, possible_time_cols# === 處理上傳 ===def process_uploaded_file(file_obj):if file_obj is None: return None, "請上傳檔案", [], [], [], [], [], [], "county"42 unmodified linestarget_gdf = get_gdf(map_level_state)if df is None:return None, "❌ 資料為空"if not col:return None, "❌ 未選擇指標"if target_gdf is None:return None, f"❌ 地圖檔未載入 (層級: {map_level_state})"if 'name' not in target_gdf.columns:return None, f"❌ 地圖檔缺少 name 欄位,現有欄位: {target_gdf.columns.tolist()}"if 'region_normalized' not in df.columns:return None, f"❌ 資料缺少 region_normalized 欄位,現有欄位: {df.columns.tolist()}"try:plot_df = df.copy()6 unmodified linesprint(f" 篩選前: {before_len} 筆 → 篩選後: {len(plot_df)} 筆")if len(plot_df) == 0:return None, f"⚠️ 時間 '{time}' 沒有資料"# 3. 數值轉換plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce')48 unmodified linesprint(f"\n✓ 合併完成: {len(has_data)}/{len(merged)} 個區域有資料")if len(has_data) == 0:msg = "⚠️ 警告:所有區域都沒有資料!\n"msg += "可能原因:\n"msg += "1. 資料中的區域名稱與地圖不匹配\n"msg += "2. 選擇的時間點沒有資料\n"msg += f"3. 層級不對 (目前: {map_level_state})\n"print(msg)# 仍繪製空白地圖# 7. 繪製地圖colors = {145 unmodified lines1461471481491501511521531541551561571581591603 unmodified lines16416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519611 unmodified lines20820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029142 unmodified lines3343353363373383393403413423433443453463473483493503513523536 unmodified lines36036136236336436536636748 unmodified lines416417418419420421422423424425426145 unmodified linesreturn numeric_colsdef smart_parse_data(df: pd.DataFrame):"""改進版資料解析 - 更準確的地區欄位偵測"""if df is None or df.empty:return None, "資料為空", [], [], [], "unknown", []print("\n" + "="*50)print("開始資料解析")print("="*50)print(f"資料形狀: {df.shape}")print(f"欄位: {df.columns.tolist()}")# 1. 資料清洗 (雙重標題偵測)data_start_idx = 03 unmodified linestotal_count = 0for val in row:total_count += 1try:float(str(val).replace(',', ''))num_count += 1except:passif total_count > 0 and (num_count / total_count) > 0.4:data_start_idx = ibreakif data_start_idx > 0:new_header = df.iloc[data_start_idx-1]df_processed = df.iloc[data_start_idx:].copy()df_processed.columns = new_headerprint(f"✓ 偵測到雙重標題,從第 {data_start_idx} 列開始")else:df_processed = df.copy()# 轉換數值欄位for col in df_processed.columns:try:df_processed[col] = pd.to_numeric(df_processed[col])except:pass# 2. 時間偵測possible_time_cols = [c for c in df_processed.columnsif any(k in str(c) for k in TIME_FIELDS)]if not possible_time_cols:for col in df_processed.columns:if pd.api.types.is_numeric_dtype(df_processed[col]):11 unmodified linesavailable_times = [str(t) for t in sorted_times]except:available_times = sorted(df_processed['time_parsed'].unique(), reverse=True)print(f"✓ 時間欄位: {time_col},共 {len(available_times)} 個時間點")# 3. 改進的地區欄位偵測region_col = Nonemap_level = "county"best_score = 0print("\n檢查每個欄位...")for col in df_processed.columns:score = 0sample = df_processed[col].dropna().head(30).astype(str).tolist()if not sample:continue# 計分標準# 1. 欄位名稱包含關鍵字 (+10分)col_lower = str(col).lower()if any(k in col_lower for k in ['縣市', 'county', 'region', '地區', 'site']):score += 10# 2. 內容分析county_count = sum(1 for s in sample if ('縣' in s or '市' in s))town_count = sum(1 for s in sample if ('區' in s or '鄉' in s or '鎮' in s))# 如果大部分都有縣市字樣 (+5分)if county_count / len(sample) > 0.5:score += 5# 如果有鄉鎮字樣 (+8分,優先權較高)if town_count / len(sample) > 0.3:score += 8# 3. 檢查是否有完整的「縣市+鄉鎮」格式 (+15分)full_format = sum(1 for s in sample if re.search(r'(縣|市).+(區|鄉|鎮)', s))if full_format / len(sample) > 0.5:score += 15map_level_candidate = "town"else:map_level_candidate = "county"print(f" {col}: 得分={score}, 樣本={sample[:2]}")# 選擇得分最高的欄位if score > best_score:best_score = scoreregion_col = colmap_level = map_level_candidate# 處理地區欄位regions = []numeric_cols = []if region_col and best_score >= 5: # 至少要5分才算有效df_processed['region_normalized'] = df_processed[region_col].apply(normalize_name)regions = sorted(df_processed[df_processed['region_normalized']!=""]['region_normalized'].unique().tolist())print(f"\n✅ 地區欄位: {region_col} (得分: {best_score})")print(f" 層級: {'鄉鎮' if map_level=='town' else '縣市'}")print(f" 區域數: {len(regions)}")print(f" 前5個區域: {regions[:5]}")# 取得數值欄位exclude = [region_col, time_col] if time_col else [region_col]numeric_cols = get_numeric_columns(df_processed, exclude)level_name = "鄉鎮市區" if map_level == "town" else "縣市"msg = f"✓ 偵測成功 ({level_name}: {region_col}, {len(regions)}區域)"else:print("\n⚠️ 未找到有效的地區欄位")msg = "⚠️ 未偵測到地區欄位"exclude = [time_col] if time_col else []numeric_cols = get_numeric_columns(df_processed, exclude)print("="*50 + "\n")return df_processed, msg, numeric_cols, available_times, regions, map_level, possible_time_cols# === 處理上傳 ===def process_uploaded_file(file_obj):if file_obj is None: return None, "請上傳檔案", [], [], [], [], [], [], "county"42 unmodified linestarget_gdf = get_gdf(map_level_state)if df is None:print("❌ 資料為空")return Noneif not col:print("❌ 未選擇指標")return Noneif target_gdf is None:print(f"❌ 地圖檔未載入 (層級: {map_level_state})")return Noneif 'name' not in target_gdf.columns:print(f"❌ 地圖檔缺少 name 欄位,現有欄位: {target_gdf.columns.tolist()}")return Noneif 'region_normalized' not in df.columns:print(f"❌ 資料缺少 region_normalized 欄位,現有欄位: {df.columns.tolist()}")return Nonetry:plot_df = df.copy()6 unmodified linesprint(f" 篩選前: {before_len} 筆 → 篩選後: {len(plot_df)} 筆")if len(plot_df) == 0:print(f"⚠️ 時間 '{time}' 沒有資料")return None# 3. 數值轉換plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce')48 unmodified linesprint(f"\n✓ 合併完成: {len(has_data)}/{len(merged)} 個區域有資料")if len(has_data) == 0:print("\n⚠️ 警告:所有區域都沒有資料!")print("可能原因:")print("1. 資料中的區域名稱與地圖不匹配")print("2. 選擇的時間點沒有資料")print(f"3. 層級不對 (目前: {map_level_state})")# 7. 繪製地圖colors = {
app.py+102-40