Spaces:
Sleeping
Sleeping
Update app.py
Browse files411 unmodified lines4124134144154164174184194204214224234247 unmodified lines43243343443543643743820 unmodified lines4594604614624634644653 unmodified lines4694704714724734744754764774784794804 unmodified lines485486487488489490491492493494495496497220 unmodified lines7187197207217227237247257267277287297309 unmodified lines740741742743744745746170 unmodified lines91791891992092192292326 unmodified lines9509519529539549559562 unmodified lines959960961962963964965411 unmodified linesdef process_uploaded_file(file_obj):empty_update = gr.update(choices=[])# 修正:確保回傳數量為 18 個,補齊最後兩個 Slider 的更新if file_obj is None:return (None, "請先上傳資料檔案 📂", empty_update, empty_update, empty_update, None,empty_update, empty_update, empty_update, "county", empty_update, "",empty_update, empty_update, empty_update, [],gr.update(value=10), gr.update(value=2) # 補齊 Slider 更新)try:file_path = file_obj.name7 unmodified linesNone, "❌ 不支援的檔案格式", empty_update, empty_update, empty_update, None,empty_update, empty_update, empty_update, "county", empty_update, "",empty_update, empty_update, empty_update, [],gr.update(value=10), gr.update(value=2) # 補齊 Slider 更新)processed_df, msg, cols, times, regions, map_level, time_col, time_formats, region_col = smart_parse_data(df)20 unmodified linesgr.update(choices=times, value=times[0] if times else None),gr.update(choices=cols, value=cols[1] if len(cols) > 1 else None),cols,gr.update(minimum=5, maximum=50, value=10, step=5),gr.update(minimum=1, maximum=10, value=2, step=1))except Exception as e:3 unmodified linesNone, f"❌ 檔案處理錯誤: {e}", empty_update, empty_update, empty_update, None,empty_update, empty_update, empty_update, "county", empty_update, "",empty_update, empty_update, empty_update, [],gr.update(value=10), gr.update(value=2) # 補齊 Slider 更新)# === 視覺化功能 (地圖、趨勢、GIF等) ===def generate_ranking(df, col, time, top_n, map_level_state, all_cols):if df is None: return None, gr.Tabs()if not col and all_cols: col = all_cols[0]if not col: return None, gr.Tabs()4 unmodified linesplot_df = plot_df[plot_df['time_parsed'] == str(time)]plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)ranking = plot_df.groupby('region_normalized')[col].sum().reset_index()ranking = ranking.sort_values(col, ascending=True).tail(int(top_n) if top_n else 10)fig = go.Figure(go.Bar(x=ranking[col], y=ranking['region_normalized'], orientation='h',marker=dict(color=ranking[col], colorscale='Viridis', showscale=True),text=ranking[col].apply(lambda x: f'{x:,.0f}'), textposition='outside'))fig.update_layout(title=f'🏆 {col} - Top {top_n} 排行榜 ({time})', xaxis_title='數值', yaxis_title='地區', height=max(400, (top_n or 10) * 30))return fig, gr.Tabs(selected="tab_ranking")except Exception as e: raise gr.Error(f"排行榜產生失敗: {e}")220 unmodified linessecondary_y=False)# 修正:確保 line_metric 邏輯正確,並將 Series 轉為 list 以避免 Plotly 索引對齊問題if line_metric == "年增率 (%)":line_data = grouped[col].pct_change() * 100fig.add_trace(go.Scatter(x=x_data,y=line_data.tolist(), # 修正:轉為 listname="年增率 (%)",mode='lines+markers',marker=dict(size=8, color='rgb(239, 68, 68)', symbol='circle'),9 unmodified linesfig.add_trace(go.Scatter(x=x_data,y=line_data.tolist(), # 修正:轉為 listname="3年移動平均",mode='lines+markers',marker=dict(size=8, color='rgb(239, 68, 68)', symbol='diamond'),170 unmodified linesbtn_dual = gr.Button("🗺️ 產生雙指標地圖", size="sm")with gr.Accordion("🏆 排行榜設定", open=False):top_n_slider = gr.Slider(minimum=5, maximum=50, value=10, step=5, label="📊 顯示名次數量")btn_ranking = gr.Button("🔄 更新排行榜", size="sm")with gr.Accordion("📈 趨勢分析設定", open=False):26 unmodified linescsv_output = gr.File(label="📥 下載的 CSV 檔案")data_preview = gr.Dataframe(wrap=True)file_input.change(fn=process_uploaded_file, inputs=file_input, outputs=[current_df, status_box, col_selector, time_selector, trend_region, data_preview, gif_time_col, start_time, end_time, map_level_state, stats_year_selector, stats_output, comp_time1, comp_time2, col_selector_2, all_numeric_cols_state, top_n_slider, fps_slider])stats_year_selector.change(fn=generate_stats_summary, inputs=[current_df, all_numeric_cols_state, stats_year_selector], outputs=stats_output)btn_map.click(fn=generate_map, inputs=[current_df, col_selector, time_selector, agg_method, color_scheme, map_level_state, all_numeric_cols_state], outputs=[map_output, tabs], js=resize_js)2 unmodified linesbtn_trend.click(fn=generate_trend_chart, inputs=[current_df, col_selector, trend_region, line_metric, all_numeric_cols_state], outputs=[trend_output, tabs], js=resize_js)btn_ranking.click(fn=generate_ranking, inputs=[current_df, col_selector, time_selector, top_n_slider, map_level_state, all_numeric_cols_state], outputs=[ranking_output, tabs], js=resize_js)btn_compare.click(fn=generate_comparison_map, inputs=[current_df, col_selector, comp_time1, comp_time2, map_level_state, all_numeric_cols_state], outputs=[compare_output, tabs], js=resize_js)411 unmodified lines4124134144154164174184194204214224234247 unmodified lines43243343443543643743820 unmodified lines4594604614624634644653 unmodified lines4694704714724734744754764774784794804 unmodified lines485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515220 unmodified lines7367377387397407417427437447457467479 unmodified lines757758759760761762763170 unmodified lines93493593693793893994094126 unmodified lines9689699709719729739742 unmodified lines977978979980981982983411 unmodified linesdef process_uploaded_file(file_obj):empty_update = gr.update(choices=[])# 修正:確保回傳數量為 18 個,補齊最後兩個元件的更新if file_obj is None:return (None, "請先上傳資料檔案 📂", empty_update, empty_update, empty_update, None,empty_update, empty_update, empty_update, "county", empty_update, "",empty_update, empty_update, empty_update, [],gr.update(value="10"), gr.update(value=2) # 補齊 Dropdown 和 Slider 更新)try:file_path = file_obj.name7 unmodified linesNone, "❌ 不支援的檔案格式", empty_update, empty_update, empty_update, None,empty_update, empty_update, empty_update, "county", empty_update, "",empty_update, empty_update, empty_update, [],gr.update(value="10"), gr.update(value=2) # 補齊 Dropdown 和 Slider 更新)processed_df, msg, cols, times, regions, map_level, time_col, time_formats, region_col = smart_parse_data(df)20 unmodified linesgr.update(choices=times, value=times[0] if times else None),gr.update(choices=cols, value=cols[1] if len(cols) > 1 else None),cols,gr.update(value="10"), # 更新排行榜下拉選單gr.update(minimum=1, maximum=10, value=2, step=1))except Exception as e:3 unmodified linesNone, f"❌ 檔案處理錯誤: {e}", empty_update, empty_update, empty_update, None,empty_update, empty_update, empty_update, "county", empty_update, "",empty_update, empty_update, empty_update, [],gr.update(value="10"), gr.update(value=2) # 補齊 Dropdown 和 Slider 更新)# === 視覺化功能 (地圖、趨勢、GIF等) ===def generate_ranking(df, col, time, top_n_str, map_level_state, all_cols):if df is None: return None, gr.Tabs()if not col and all_cols: col = all_cols[0]if not col: return None, gr.Tabs()4 unmodified linesplot_df = plot_df[plot_df['time_parsed'] == str(time)]plot_df[col] = pd.to_numeric(plot_df[col], errors='coerce').fillna(0)ranking = plot_df.groupby('region_normalized')[col].sum().reset_index()# 處理 "全部" 或 數字if str(top_n_str) == "全部":slice_n = len(ranking)else:try: slice_n = int(top_n_str)except: slice_n = 10ranking = ranking.sort_values(col, ascending=True).tail(slice_n)fig = go.Figure(go.Bar(x=ranking[col], y=ranking['region_normalized'], orientation='h',marker=dict(color=ranking[col], colorscale='Viridis', showscale=True),text=ranking[col].apply(lambda x: f'{x:,.0f}'), textposition='outside'))# 動態調整高度,避免 "全部" 時擠在一起dynamic_height = max(400, slice_n * 30)fig.update_layout(title=f'🏆 {col} - Top {top_n_str} 排行榜 ({time})',xaxis_title='數值',yaxis_title='地區',height=dynamic_height)return fig, gr.Tabs(selected="tab_ranking")except Exception as e: raise gr.Error(f"排行榜產生失敗: {e}")220 unmodified linessecondary_y=False)if line_metric == "年增率 (%)":line_data = grouped[col].pct_change() * 100fig.add_trace(go.Scatter(x=x_data,y=line_data.tolist(),name="年增率 (%)",mode='lines+markers',marker=dict(size=8, color='rgb(239, 68, 68)', symbol='circle'),9 unmodified linesfig.add_trace(go.Scatter(x=x_data,y=line_data.tolist(),name="3年移動平均",mode='lines+markers',marker=dict(size=8, color='rgb(239, 68, 68)', symbol='diamond'),170 unmodified linesbtn_dual = gr.Button("🗺️ 產生雙指標地圖", size="sm")with gr.Accordion("🏆 排行榜設定", open=False):# 修改處:將 Slider 改為 Dropdowntop_n_selector = gr.Dropdown(choices=["10", "20", "50", "全部"], value="10", label="📊 顯示名次數量")btn_ranking = gr.Button("🔄 更新排行榜", size="sm")with gr.Accordion("📈 趨勢分析設定", open=False):26 unmodified linescsv_output = gr.File(label="📥 下載的 CSV 檔案")data_preview = gr.Dataframe(wrap=True)file_input.change(fn=process_uploaded_file, inputs=file_input, outputs=[current_df, status_box, col_selector, time_selector, trend_region, data_preview, gif_time_col, start_time, end_time, map_level_state, stats_year_selector, stats_output, comp_time1, comp_time2, col_selector_2, all_numeric_cols_state, top_n_selector, fps_slider])stats_year_selector.change(fn=generate_stats_summary, inputs=[current_df, all_numeric_cols_state, stats_year_selector], outputs=stats_output)btn_map.click(fn=generate_map, inputs=[current_df, col_selector, time_selector, agg_method, color_scheme, map_level_state, all_numeric_cols_state], outputs=[map_output, tabs], js=resize_js)2 unmodified linesbtn_trend.click(fn=generate_trend_chart, inputs=[current_df, col_selector, trend_region, line_metric, all_numeric_cols_state], outputs=[trend_output, tabs], js=resize_js)btn_ranking.click(fn=generate_ranking, inputs=[current_df, col_selector, time_selector, top_n_selector, map_level_state, all_numeric_cols_state], outputs=[ranking_output, tabs], js=resize_js)btn_compare.click(fn=generate_comparison_map, inputs=[current_df, col_selector, comp_time1, comp_time2, map_level_state, all_numeric_cols_state], outputs=[compare_output, tabs], js=resize_js)
app.py+32-14