Spaces:
Sleeping
Sleeping
feat(manual): town-level maps for slides, scope picker, transparent export
Browse files- level switch: counties or towns (全國 368 towns with county outlines, or
zoom to a single county); table is rebuilt per scope and entries live in
a store so switching scope never loses data
- paste accepts short town names inside a county scope, unique short names
nationally, old names (桃園縣…), and warns about unknown ones
- auto titles (臺灣各縣市 / 新北市各鄉鎮市區), town labels without county prefix
- PNG/SVG export with optional transparent background for PowerPoint
- town gdf gets a normalized 縣市 column
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
433 unmodified lines434435436437438439637 unmodified lines10771078107910801081108210831084108510861087108810891090109110925 unmodified lines109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811 unmodified lines1170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112028 unmodified lines1211121212131214121512161217121812199 unmodified lines1229123012311232123312341235123612371238123911 unmodified lines1251125212531254125512561257125812591 unmodified line1261126212631264126512661267477 unmodified lines174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777120 unmodified lines18981899190019011902190319041905190619071908190919101911433 unmodified linesgdf['name'] = gdf['name'].astype(str).str.replace('台', '臺')gdf['name'] = gdf['name'].map(modernize_name)print(f"✅ 地圖 ({level}) 載入成功,筆數: {len(gdf)}")return gdfexcept Exception as e:637 unmodified lines"宜蘭縣", "花蓮縣", "臺東縣", "澎湖縣", "金門縣", "連江縣"]MANUAL_LABEL_MODES = ["縣市名 + 內容", "僅內容", "僅縣市名", "不顯示標籤"]MANUAL_COLORS = ["紅色系 🔴", "藍色系 🔵", "綠色系 🟢", "熱力圖 🔥"]MANUAL_COL_NAME, MANUAL_COL_CONTENT = "縣市名稱", "填寫內容"# 分類模式的調色盤(Set2 + Set3,約 20 色,超過會循環)QUALITATIVE_COLORS = [_to_hex(c) for c in px.colors.qualitative.Set2 + px.colors.qualitative.Set3]UNFILLED_LABEL = "未填寫"MANUAL_FILLED_COLOR = "#667eea"def empty_manual_table() -> pd.DataFrame:return pd.DataFrame({MANUAL_COL_NAME: DEFAULT_COUNTIES, MANUAL_COL_CONTENT: [""] * len(DEFAULT_COUNTIES)})MANUAL_EXAMPLES = {"分區": {"臺北市": "北部", "新北市": "北部", "基隆市": "北部", "桃園市": "北部", "新竹市": "北部", "新竹縣": "北部",5 unmodified lines9, 11, 48, 66, 21, 13, 10, 7, 3, 4, 1])},}def _table_from_mapping(mapping: Dict[str, str]) -> pd.DataFrame:df = empty_manual_table()df[MANUAL_COL_CONTENT] = df[MANUAL_COL_NAME].map(mapping).fillna("")return dfdef load_manual_example(kind: str):return _table_from_mapping(MANUAL_EXAMPLES[kind])def import_pasted_text(text: str, current_df):"""批次貼上:每行「縣市 內容」,分隔可用 Tab(從 Excel 複製)、逗號、冒號、等號或空白。會覆蓋表格中同名縣市,其餘保留;認不得的名稱用警告列出。"""df = current_df.copy() if current_df is not None and len(current_df) else empty_manual_table()mapping, unknown = {}, []for line in (text or "").splitlines():line = line.strip()if not line: continueparts = re.split(r"[\t,,::=]+|\s+", line, maxsplit=1)if len(parts) < 2 or not parts[1].strip(): continuename = normalize_name(parts[0])if name in DEFAULT_COUNTIES: mapping[name] = parts[1].strip()else: unknown.append(parts[0])if not mapping and not unknown:raise gr.Error("沒有讀到資料:每行請寫成「縣市 內容」,例如「臺北市 85」")if unknown:gr.Warning(f"以下名稱不是縣市,已略過:{'、'.join(unknown[:8])}")df[MANUAL_COL_NAME] = df[MANUAL_COL_NAME].astype(str)df[MANUAL_COL_CONTENT] = df[MANUAL_COL_CONTENT].fillna("").astype(str)for name, content in mapping.items():df.loc[df[MANUAL_COL_NAME].map(normalize_name) == name, MANUAL_COL_CONTENT] = contentreturn dfdef _manual_frame(input_df, show_islands=True):"""把表格合併到縣市圖,回傳 (merged, is_numeric)。merged 欄位:填寫內容、filled、數值(數值模式)、類別(分類模式)。全部填寫內容都是數字 → 數值模式(漸層色階);否則 → 分類模式(相同文字同色+圖例)。"""target_gdf = _require_map("county")if input_df is None or len(input_df) == 0: raise gr.Error("請至少填寫一個縣市的內容")data = input_df.copy()data[MANUAL_COL_NAME] = data[MANUAL_COL_NAME].astype(str).map(normalize_name) # 容許填「台北市」data[MANUAL_COL_CONTENT] = data[MANUAL_COL_CONTENT].fillna("").astype(str).str.strip()valid = data[data[MANUAL_COL_CONTENT] != ""].drop_duplicates(MANUAL_COL_NAME, keep="last")if valid.empty: raise gr.Error("請至少填寫一個縣市的內容")unknown = sorted(set(valid[MANUAL_COL_NAME]) - set(target_gdf["name"]))if unknown: gr.Warning(f"找不到這些縣市,已略過:{'、'.join(unknown[:8])}")if not show_islands:target_gdf = target_gdf[~target_gdf["name"].str.startswith(ISLAND_COUNTIES)]merged = target_gdf.merge(valid, left_on="name", right_on=MANUAL_COL_NAME, how="left")merged[MANUAL_COL_CONTENT] = merged[MANUAL_COL_CONTENT].fillna("")merged["filled"] = merged[MANUAL_COL_CONTENT] != ""numbers = pd.to_numeric(merged.loc[merged["filled"], MANUAL_COL_CONTENT].str.replace(",", "", regex=False),errors="coerce")11 unmodified linespalette[UNFILLED_LABEL] = NO_DATA_COLORreturn cats, palette# 面積小又擠在一起的縣市,標籤移到海上(經度, 緯度)並以引線連回區域LABEL_OFFSETS = {"基隆市": (122.45, 25.40), "臺北市": (122.55, 25.10), "新北市": (122.55, 24.80),"桃園市": (120.30, 25.15), "新竹市": (120.15, 24.80), "嘉義市": (119.90, 23.55),}def _label_positions(filled):"""回傳 [(名稱, 內容, 區域內的點(x, y), 標籤位置(x, y))];沒有位移時標籤位置 = 區域內的點。representative_point 保證落在區域內(centroid 可能落在海上)。"""pts = filled.geometry.representative_point()out = []for (_, row), pt in zip(filled.iterrows(), pts):anchor = (pt.x, pt.y)out.append((row["name"], row[MANUAL_COL_CONTENT], anchor, LABEL_OFFSETS.get(row["name"], anchor)))return outdef _label_text(name: str, content: str, mode: str) -> str:if mode == "僅內容": return contentif mode == "僅縣市名": return namereturn f"{name}\n{content}"def _manual_title(title: str) -> str:return (title or "").strip() or "手動填寫分布圖"def generate_manual_distribution_map(input_df, title, color_scheme, label_mode, label_size, show_islands):merged, is_numeric = _manual_frame(input_df, show_islands)title = f"📝 {_manual_title(title)}"scheme = _scheme_key(color_scheme)if is_numeric:8 unmodified lines)_style_map_layout(fig, title, bottom_legend=True)filled = merged[merged["filled"]]if label_mode != "不顯示標籤" and not filled.empty:labels = _label_positions(filled)lead_lon, lead_lat = [], []for _, _, a, b in labels:if a != b: lead_lon += [a[0], b[0], None]; lead_lat += [a[1], b[1], None]9 unmodified linesfig.update_layout(height=800)return figdef export_manual(input_df, title, color_scheme, label_mode, label_size, show_islands, fmt="png"):"""匯出 PNG/SVG;顏色、標籤設定與畫面上的互動圖一致"""merged, is_numeric = _manual_frame(input_df, show_islands)scheme = _scheme_key(color_scheme)title = _manual_title(title)if is_numeric:fig = build_static_map(merged, "數值", title, scheme=scheme)11 unmodified linesax.set_title(title, size=24, **font_kw)ax.set_axis_off()if label_mode != "不顯示標籤":font_kw = {"fontproperties": CUSTOM_FONT_PROP} if CUSTOM_FONT_PROP else {}for name, content, anchor, pos in _label_positions(merged[merged["filled"]]):ax.annotate(_label_text(name, content, label_mode), xy=anchor, xytext=pos,ha="center", va="center", fontsize=int(label_size) * 0.85, **font_kw,1 unmodified linearrowprops=dict(arrowstyle="-", color="gray", alpha=0.7) if anchor != pos else None)path = _tmp_path(f".{fmt}")fig.savefig(path, format=fmt, bbox_inches="tight", dpi=200, facecolor="white")return gr.update(value=path, visible=True)# ===============================================477 unmodified linesmap_output = gr.Plot()with gr.Tab("📝 手動填寫", id="tab_manual"):gr.HTML('<div style="margin-bottom:12px; color: var(--text-dim, #8892a4); font-size:0.85rem;">✍️ 在表格填寫、或從 Excel 整批貼上。<b>全部填數字</b>→漸層色階;<b>填文字</b>→相同文字同一顏色並附圖例。縣市名稱可寫「台北市」或「臺北市」。</div>')with gr.Row():with gr.Column(scale=1, min_width=300):manual_input_df = gr.Dataframe(value=empty_manual_table(),headers=[MANUAL_COL_NAME, MANUAL_COL_CONTENT],col_count=(2, "fixed"), row_count=(len(DEFAULT_COUNTIES), "fixed"),static_columns=[0], interactive=True, max_height=520)with gr.Accordion("📋 從 Excel 批次貼上", open=False):manual_paste = gr.Textbox(label="每行一個縣市:「縣市 內容」(Tab、逗號、空白皆可)",placeholder="臺北市\t85\n高雄市\t66\n花蓮縣\t10", lines=6)btn_paste = gr.Button("⬆️ 匯入到表格", variant="secondary")with gr.Row():btn_ex_cat = gr.Button("範例:分區", size="sm", variant="secondary")btn_ex_num = gr.Button("範例:數值", size="sm", variant="secondary")btn_clear = gr.Button("🗑️ 清空", size="sm", variant="secondary")with gr.Column(scale=2, min_width=340):with gr.Row():manual_title = gr.Textbox(label="圖表標題", placeholder="手動填寫分布圖")manual_color = gr.Dropdown(MANUAL_COLORS, label="數值模式配色", value=MANUAL_COLORS[1])with gr.Row():manual_label_mode = gr.Dropdown(MANUAL_LABEL_MODES, label="標籤內容", value=MANUAL_LABEL_MODES[0])manual_label_size = gr.Slider(8, 24, value=12, step=1, label="標籤字級")manual_islands = gr.Checkbox(label="顯示離島(金門、連江、澎湖)", value=True)with gr.Row():btn_manual_map = gr.Button("🗺️ 生成分布圖", variant="primary", scale=2)btn_manual_png = gr.Button("💾 匯出 PNG", variant="secondary")120 unmodified linesoutputs=[gif_output, tabs])btn_export_csv.click(fn=export_csv, inputs=current_df, outputs=csv_output)manual_opts = [manual_input_df, manual_title, manual_color, manual_label_mode, manual_label_size, manual_islands]btn_manual_map.click(fn=generate_manual_distribution_map, inputs=manual_opts, outputs=manual_map_output)btn_manual_png.click(fn=lambda *a: export_manual(*a, fmt="png"), inputs=manual_opts, outputs=manual_file)btn_manual_svg.click(fn=lambda *a: export_manual(*a, fmt="svg"), inputs=manual_opts, outputs=manual_file)btn_paste.click(fn=import_pasted_text, inputs=[manual_paste, manual_input_df], outputs=manual_input_df)btn_ex_cat.click(fn=lambda: load_manual_example("分區"), outputs=manual_input_df)btn_ex_num.click(fn=lambda: load_manual_example("數值"), outputs=manual_input_df)btn_clear.click(fn=empty_manual_table, outputs=manual_input_df)if __name__ == "__main__":demo.queue().launch()433 unmodified lines434435436437438439440441637 unmodified lines107910801081108210831084108510861087108810891090109110921093109410951096109710985 unmodified lines1104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124611 unmodified lines1258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612878 unmodified lines129612971298129913001301130213031304130513061307130813099 unmodified lines13191320132113221323132413251326132713281329133011 unmodified lines1342134313441345134613471348134913501351135213531 unmodified line13551356135713581359136013611362477 unmodified lines184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878120 unmodified lines199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022433 unmodified linesgdf['name'] = gdf['name'].astype(str).str.replace('台', '臺')gdf['name'] = gdf['name'].map(modernize_name)if level == "town" and county_col:gdf['縣市'] = gdf[county_col].astype(str).str.replace('台', '臺').map(modernize_name)print(f"✅ 地圖 ({level}) 載入成功,筆數: {len(gdf)}")return gdfexcept Exception as e:637 unmodified lines"宜蘭縣", "花蓮縣", "臺東縣", "澎湖縣", "金門縣", "連江縣"]MANUAL_LEVELS = ["縣市", "鄉鎮市區"]MANUAL_NATIONAL = "全國"MANUAL_LABEL_MODES = ["名稱 + 內容", "僅內容", "僅名稱", "不顯示標籤"]MANUAL_COLORS = ["紅色系 🔴", "藍色系 🔵", "綠色系 🟢", "熱力圖 🔥"]MANUAL_COL_NAME, MANUAL_COL_CONTENT = "名稱", "填寫內容"# 分類模式的調色盤(Set2 + Set3,約 20 色,超過會循環)QUALITATIVE_COLORS = [_to_hex(c) for c in px.colors.qualitative.Set2 + px.colors.qualitative.Set3]UNFILLED_LABEL = "未填寫"# 面積小又擠在一起的縣市,標籤移到海上(經度, 緯度)並以引線連回區域(只用於縣市層級)LABEL_OFFSETS = {"基隆市": (122.45, 25.40), "臺北市": (122.55, 25.10), "新北市": (122.55, 24.80),"桃園市": (120.30, 25.15), "新竹市": (120.15, 24.80), "嘉義市": (119.90, 23.55),}MANUAL_EXAMPLES = {"分區": {"臺北市": "北部", "新北市": "北部", "基隆市": "北部", "桃園市": "北部", "新竹市": "北部", "新竹縣": "北部",5 unmodified lines9, 11, 48, 66, 21, 13, 10, 7, 3, 4, 1])},}# --- 名稱清單與資料表 ---def _town_gdf():gdf = get_gdf("town")if gdf is None or gdf.empty or '縣市' not in gdf.columns: raise gr.Error("鄉鎮市區圖資載入失敗")return gdfdef manual_names(level: str, scope: str) -> List[str]:"""目前表格要列出的名稱:縣市層級=22 縣市;鄉鎮層級=全國或某縣市底下的鄉鎮市區"""if level != "鄉鎮市區": return list(DEFAULT_COUNTIES)gdf = _town_gdf()if scope in DEFAULT_COUNTIES: gdf = gdf[gdf['縣市'] == scope]order = {c: i for i, c in enumerate(DEFAULT_COUNTIES)}sort_cols = ['town_id'] if 'town_id' in gdf.columns else ['name']gdf = gdf.assign(_o=gdf['縣市'].map(order)).sort_values(['_o'] + sort_cols)return gdf['name'].tolist()def all_manual_names(level: str) -> List[str]:return manual_names(level, MANUAL_NATIONAL)def manual_table(level: str, scope: str, store: Optional[Dict[str, str]]) -> pd.DataFrame:names = manual_names(level, scope)store = store or {}return pd.DataFrame({MANUAL_COL_NAME: names, MANUAL_COL_CONTENT: [store.get(n, "") for n in names]})def _scope_visibility(level):return gr.update(visible=(level == "鄉鎮市區"))def on_manual_scope_change(level, scope, store):"""切換層級/範圍時,用 store 重建表格,之前填過的內容不會遺失"""return _scope_visibility(level), manual_table(level, scope, store)def on_manual_table_input(df, store):"""使用者在表格輸入時,同步到 store(以名稱為鍵;清空內容就從 store 移除)"""store = dict(store or {})if df is None: return storefor name, content in zip(df[MANUAL_COL_NAME], df[MANUAL_COL_CONTENT]):name = str(name).strip()content = "" if content is None or (isinstance(content, float) and pd.isna(content)) else str(content).strip()if not name or name == "nan": continueif content: store[name] = contentelse: store.pop(name, None)return storedef clear_manual(level, scope, store):store = dict(store or {})for n in manual_names(level, scope): store.pop(n, None)return store, manual_table(level, scope, store)def load_manual_example(kind: str, store):store = {k: v for k, v in (store or {}).items() if k not in DEFAULT_COUNTIES}store.update(MANUAL_EXAMPLES[kind])return store, gr.update(value="縣市"), _scope_visibility("縣市"), manual_table("縣市", MANUAL_NATIONAL, store)def _resolver(level: str, scope: str):"""把使用者輸入的名稱對到標準名稱:容許「台北市」���舊名、以及在單一縣市範圍內只寫鄉鎮名(板橋區)"""names = set(all_manual_names(level))short: Dict[str, List[str]] = {}if level == "鄉鎮市區":gdf = _town_gdf()for full, county in zip(gdf['name'], gdf['縣市']):short.setdefault(full[len(county):], []).append(full)def resolve(raw: str) -> Optional[str]:n = normalize_name(raw)if n in names: return nif level == "鄉鎮市區":if scope in DEFAULT_COUNTIES and scope + n in names: return scope + ncands = short.get(n, [])if len(cands) == 1: return cands[0] # 全國範圍下,名稱唯一的鄉鎮可以只寫短名return Nonereturn resolvedef import_pasted_text(text: str, level, scope, store):"""批次貼上:每行「名稱 內容」,分隔可用 Tab(從 Excel 複製)、逗號、冒號、等號或空白。同名會覆蓋;認不得的名稱用警告列出。不在目前範圍的鄉鎮也會存起來,切換範圍就看得到。"""store = dict(store or {})resolve = _resolver(level, scope)unknown, got = [], 0for line in (text or "").splitlines():line = line.strip()if not line: continueparts = re.split(r"[\t,,::=]+|\s+", line, maxsplit=1)if len(parts) < 2 or not parts[1].strip(): continuename = resolve(parts[0])if name: store[name] = parts[1].strip(); got += 1else: unknown.append(parts[0])if not got and not unknown:raise gr.Error("沒有讀到資料:每行請寫成「名稱 內容」,例如「臺北市 85」")if unknown: gr.Warning(f"以下名稱對不到{level},已略過:{'、'.join(unknown[:8])}")return store, manual_table(level, scope, store)# --- 資料合併與繪圖 ---_COUNTY_OUTLINE_CACHE: Dict[str, Tuple[list, list]] = {}def county_outline_lines() -> Tuple[list, list]:"""全部縣市界線的座標(以 None 分段),疊在全國鄉鎮圖上,才看得出縣市邊界"""if "xy" not in _COUNTY_OUTLINE_CACHE:lon, lat = [], []for geom in _require_map("county").geometry.boundary:for line in getattr(geom, "geoms", [geom]):xs, ys = line.xylon += list(xs) + [None]; lat += list(ys) + [None]_COUNTY_OUTLINE_CACHE["xy"] = (lon, lat)return _COUNTY_OUTLINE_CACHE["xy"]def _manual_frame(input_df, level, scope, show_islands=True):"""把表格合併到地圖,回傳 (merged, is_numeric)。merged 欄位:label_name、填寫內容、filled、數值(數值模式)、類別(分類模式)。全部填寫內容都是數字 → 數值模式(漸層色階);否則 → 分類模式(相同文字同色+圖例)。"""if level == "鄉鎮市區":target = _town_gdf()if scope in DEFAULT_COUNTIES: target = target[target['縣市'] == scope]else:target = _require_map("county")if input_df is None or len(input_df) == 0: raise gr.Error("請至少填寫一個項目的內容")data = input_df.copy()data[MANUAL_COL_NAME] = data[MANUAL_COL_NAME].astype(str).map(normalize_name)data[MANUAL_COL_CONTENT] = data[MANUAL_COL_CONTENT].fillna("").astype(str).str.strip()valid = data[data[MANUAL_COL_CONTENT] != ""].drop_duplicates(MANUAL_COL_NAME, keep="last")if valid.empty: raise gr.Error("請至少填寫一個項目的內容")unknown = sorted(set(valid[MANUAL_COL_NAME]) - set(target["name"]))if unknown: gr.Warning(f"找不到這些地區,已略過:{'、'.join(unknown[:8])}")if not show_islands:target = target[~target["name"].str.startswith(ISLAND_COUNTIES)]merged = target.merge(valid, left_on="name", right_on=MANUAL_COL_NAME, how="left")merged[MANUAL_COL_CONTENT] = merged[MANUAL_COL_CONTENT].fillna("")merged["filled"] = merged[MANUAL_COL_CONTENT] != ""# 鄉鎮層級的標籤只顯示鄉鎮名(板橋區),不帶縣市前綴merged["label_name"] = merged["name"] if level != "鄉鎮市區" else [n[len(c):] for n, c in zip(merged["name"], merged["縣市"])]numbers = pd.to_numeric(merged.loc[merged["filled"], MANUAL_COL_CONTENT].str.replace(",", "", regex=False),errors="coerce")11 unmodified linespalette[UNFILLED_LABEL] = NO_DATA_COLORreturn cats, palettedef _label_positions(filled, level):"""回傳 [(顯示名稱, 內容, 區域內的點(x, y), 標籤位置(x, y))];沒有位移時標籤位置 = 區域內的點。representative_point 保證落在區域內(centroid 可能落在海上)。"""pts = filled.geometry.representative_point()out = []for (_, row), pt in zip(filled.iterrows(), pts):anchor = (pt.x, pt.y)pos = LABEL_OFFSETS.get(row["name"], anchor) if level != "鄉鎮市區" else anchorout.append((row["label_name"], row[MANUAL_COL_CONTENT], anchor, pos))return outdef _label_text(name: str, content: str, mode: str) -> str:if mode == "僅內容": return contentif mode == "僅名稱": return namereturn f"{name}\n{content}"def _manual_title(title: str, level: str, scope: str) -> str:if (title or "").strip(): return title.strip()if level != "鄉鎮市區": return "臺灣各縣市"return "全國各鄉鎮市區" if scope not in DEFAULT_COUNTIES else f"{scope}各鄉鎮市區"def generate_manual_distribution_map(input_df, level, scope, title, color_scheme, label_mode, label_size, show_islands):merged, is_numeric = _manual_frame(input_df, level, scope, show_islands)title = _manual_title(title, level, scope)scheme = _scheme_key(color_scheme)if is_numeric:8 unmodified lines)_style_map_layout(fig, title, bottom_legend=True)if level == "鄉鎮市區" and scope not in DEFAULT_COUNTIES: # 全國鄉鎮圖疊上縣市界lon, lat = county_outline_lines()fig.add_trace(go.Scattergeo(lon=lon, lat=lat, mode="lines", hoverinfo="skip", showlegend=False,line=dict(color="#374151", width=0.8)))filled = merged[merged["filled"]]if label_mode != "不顯示標籤" and not filled.empty:labels = _label_positions(filled, level)lead_lon, lead_lat = [], []for _, _, a, b in labels:if a != b: lead_lon += [a[0], b[0], None]; lead_lat += [a[1], b[1], None]9 unmodified linesfig.update_layout(height=800)return figdef export_manual(input_df, level, scope, title, color_scheme, label_mode, label_size, show_islands,transparent=False, fmt="png"):"""匯出 PNG/SVG(可透明背景,貼到簡報不留白底);顏色、標籤與畫面上的互動圖一致"""merged, is_numeric = _manual_frame(input_df, level, scope, show_islands)scheme = _scheme_key(color_scheme)title = _manual_title(title, level, scope)if is_numeric:fig = build_static_map(merged, "數值", title, scheme=scheme)11 unmodified linesax.set_title(title, size=24, **font_kw)ax.set_axis_off()if level == "鄉鎮市區" and scope not in DEFAULT_COUNTIES:_require_map("county").boundary.plot(ax=ax, color="#374151", linewidth=0.7)if label_mode != "不顯示標籤":font_kw = {"fontproperties": CUSTOM_FONT_PROP} if CUSTOM_FONT_PROP else {}for name, content, anchor, pos in _label_positions(merged[merged["filled"]], level):ax.annotate(_label_text(name, content, label_mode), xy=anchor, xytext=pos,ha="center", va="center", fontsize=int(label_size) * 0.85, **font_kw,1 unmodified linearrowprops=dict(arrowstyle="-", color="gray", alpha=0.7) if anchor != pos else None)path = _tmp_path(f".{fmt}")fig.savefig(path, format=fmt, bbox_inches="tight", dpi=200,transparent=bool(transparent), facecolor="none" if transparent else "white")return gr.update(value=path, visible=True)# ===============================================477 unmodified linesmap_output = gr.Plot()with gr.Tab("📝 手動填寫", id="tab_manual"):gr.HTML('<div style="margin-bottom:12px; color: var(--text-dim, #8892a4); font-size:0.85rem;">✍️ 做簡報用的縣市/鄉鎮地圖:選層級與範圍,在表格填寫或從 Excel 整批貼上。<b>全部填數字</b>→漸層色階;<b>填文字</b>→相同文字同一顏色並附圖例。匯出可選透明背景,直接貼進 PPT。</div>')manual_store = gr.State({})with gr.Row():with gr.Column(scale=1, min_width=300):with gr.Row():manual_level = gr.Radio(MANUAL_LEVELS, label="層級", value=MANUAL_LEVELS[0])manual_scope = gr.Dropdown([MANUAL_NATIONAL] + DEFAULT_COUNTIES, label="鄉鎮範圍(全國 或 單一縣市)",value="臺北市", visible=False)manual_input_df = gr.Dataframe(value=manual_table("縣市", MANUAL_NATIONAL, {}),headers=[MANUAL_COL_NAME, MANUAL_COL_CONTENT],col_count=(2, "fixed"), static_columns=[0], interactive=True, max_height=520)with gr.Accordion("📋 從 Excel 批次貼上", open=False):manual_paste = gr.Textbox(label="每行一個:「名稱 內容」(Tab、逗號、空白皆可;選了單一縣市可只寫鄉鎮名)",placeholder="臺北市\t85\n高雄市\t66\n花蓮縣\t10", lines=6)btn_paste = gr.Button("⬆️ 匯入到表格", variant="secondary")with gr.Row():btn_ex_cat = gr.Button("範例:分區", size="sm", variant="secondary")btn_ex_num = gr.Button("範例:數值", size="sm", variant="secondary")btn_clear = gr.Button("🗑️ 清空目前範圍", size="sm", variant="secondary")with gr.Column(scale=2, min_width=340):with gr.Row():manual_title = gr.Textbox(label="圖表標題(留空自動命名)", placeholder="臺灣各縣市")manual_color = gr.Dropdown(MANUAL_COLORS, label="數值模式配色", value=MANUAL_COLORS[1])with gr.Row():manual_label_mode = gr.Dropdown(MANUAL_LABEL_MODES, label="標籤內容", value=MANUAL_LABEL_MODES[0])manual_label_size = gr.Slider(6, 24, value=12, step=1, label="標籤字級")with gr.Row():manual_islands = gr.Checkbox(label="顯示離島(金門、連江、澎湖)", value=True)manual_transparent = gr.Checkbox(label="匯出透明背景(PNG/SVG)", value=False)with gr.Row():btn_manual_map = gr.Button("🗺️ 生成分布圖", variant="primary", scale=2)btn_manual_png = gr.Button("💾 匯出 PNG", variant="secondary")120 unmodified linesoutputs=[gif_output, tabs])btn_export_csv.click(fn=export_csv, inputs=current_df, outputs=csv_output)manual_opts = [manual_input_df, manual_level, manual_scope, manual_title, manual_color,manual_label_mode, manual_label_size, manual_islands]btn_manual_map.click(fn=generate_manual_distribution_map, inputs=manual_opts, outputs=manual_map_output)btn_manual_png.click(fn=lambda *a: export_manual(*a, fmt="png"), inputs=manual_opts + [manual_transparent],outputs=manual_file)btn_manual_svg.click(fn=lambda *a: export_manual(*a, fmt="svg"), inputs=manual_opts + [manual_transparent],outputs=manual_file)for trigger in (manual_level.change, manual_scope.change):trigger(fn=on_manual_scope_change, inputs=[manual_level, manual_scope, manual_store],outputs=[manual_scope, manual_input_df])manual_input_df.input(fn=on_manual_table_input, inputs=[manual_input_df, manual_store], outputs=manual_store)btn_paste.click(fn=import_pasted_text, inputs=[manual_paste, manual_level, manual_scope, manual_store],outputs=[manual_store, manual_input_df])for btn, kind in ((btn_ex_cat, "分區"), (btn_ex_num, "數值")):btn.click(fn=lambda store, k=kind: load_manual_example(k, store), inputs=manual_store,outputs=[manual_store, manual_level, manual_scope, manual_input_df])btn_clear.click(fn=clear_manual, inputs=[manual_level, manual_scope, manual_store],outputs=[manual_store, manual_input_df])if __name__ == "__main__":demo.queue().launch()
app.py+188-77