Spaces:
Sleeping
Sleeping
feat(pptx): all exported PowerPoint files use native, editable objects
Browse files- 圖解排名 slide: map regions are vector freeforms, pills are grouped shapes
with text, title/subtitle/legend/unit/note are text boxes, leader lines
are connectors
- county slides: map regions as freeforms, labels as text boxes with leader
lines, legend as shapes + text boxes (no raster pictures any more)
- _render_manual_static collects a scene for the PPTX builder
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1424 unmodified lines1425142614271428142914301431143215 unmodified lines14481449145014511452145314541455145614571458145914601461146214631 unmodified line14651466146714681469147040 unmodified lines1511151215131514151515168 unmodified lines152515261527152815291530153121 unmodified lines15531554155515561557155815591 unmodified line156115621563156415651566156715681569157015711572157330 unmodified lines1604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631112 unmodified lines1744174517461747174817498 unmodified lines175817591760176117621763176417655 unmodified lines1771177217731774177517761 unmodified line17781779178017811782178319 unmodified lines180318041805180618071808180918101811181218131814181518161 unmodified line18181819182018211822182318241 unmodified line18261827182818291830183118321833183418351836183718381839184018411842184318441424 unmodified linesreturn figdef _render_manual_static(merged, is_numeric, level, scope, title, scheme, label_mode, label_size,vrange=None, cats=None, figsize=(12, 12)):"""靜態圖 (matplotlib)。PPTX 每頁共用 vrange(數值)或 cats(分類),各頁顏色才能互相比較。"""if is_numeric:# 縣市層級的離島外標籤會往右伸出,色條要往右讓開才不會蓋住fig = build_static_map(merged, "數值", title, scheme=scheme, figsize=figsize, vrange=vrange,15 unmodified linesif 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 {}fs = int(label_size) * 0.85# 量出座標軸實際大小,換算「每 pt 幾度」(色條、圖例都會影響軸的大小,不能用估的)ax.apply_aspect()pos = ax.get_position()(x0, x1), (y0, y1) = ax.get_xlim(), ax.get_ylim()kx = (x1 - x0) / (pos.width * fig.get_figwidth() * 72)ky = (y1 - y0) / (pos.height * fig.get_figheight() * 72)for lab in _place_labels(merged, level, label_mode, fs, kx, ky):ax.annotate(lab["text"], xy=lab["anchor"], xytext=lab["pos"], ha="center", va="center", fontsize=fs, **font_kw,bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="gray", alpha=0.92),1 unmodified line)if lab["edge"]:ax.plot(*lab["anchor"], "o", ms=2.5, color="#374151", zorder=5)return figdef regenerate_manual_map(*args):40 unmodified linesPPT_FONT = "Microsoft JhengHei"PPT_TABLE_MAX_ROWS = 22def _fig_png(fig, dpi=170):buf = io.BytesIO()fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight", transparent=True)8 unmodified lines"""from pptx import Presentationfrom pptx.util import Inches, Ptfrom PIL import Image as PILImagestore = merge_table_into_store(input_df, store)town_gdf = _town_gdf()21 unmodified linesprs.slide_width, prs.slide_height = Inches(13.333), Inches(7.5)blank = prs.slide_layouts[6]def add_slide(heading, fig, rows, info=None):slide = prs.slides.add_slide(blank)tb = slide.shapes.add_textbox(Inches(0.5), Inches(0.3), Inches(12.3), Inches(0.9))run = tb.text_frame.paragraphs[0].add_run()1 unmodified linerun.font.size, run.font.bold, run.font.name = Pt(32), True, PPT_FONTbox_w = 7.9 if (rows or info) else 12.3buf = _fig_png(fig)w, h = PILImage.open(buf).sizebuf.seek(0)scale = min(box_w / w, 5.8 / h) # 等比例縮放進圖框,置中pw, ph = w * scale, h * scaleslide.shapes.add_picture(buf, Inches(0.5 + (box_w - pw) / 2), Inches(1.35 + (5.8 - ph) / 2),Inches(pw), Inches(ph))if info: # 只有縣市資料時:右側用大字呈現該縣市的內容panel = slide.shapes.add_textbox(Inches(8.7), Inches(2.4), Inches(4.1), Inches(3.2)).text_framepanel.word_wrap = True30 unmodified linesif with_overview and county_entries:df = manual_table("縣市", MANUAL_NATIONAL, store)merged, num = _manual_frame(df, "縣市", MANUAL_NATIONAL, True)fig = _render_manual_static(merged, num, "縣市", MANUAL_NATIONAL, "", scheme, label_mode, label_size,figsize=(10, 10))rows = [(n, county_entries[n]) for n in DEFAULT_COUNTIES if n in county_entries] if with_table else []add_slide(base or "臺灣各縣市", fig, rows)done += 1; progress((done, steps), desc="產生簡報")for county in counties if county_mode else []:df = manual_table("縣市", MANUAL_NATIONAL, {county: county_entries[county]}) # 只留這個縣市有值,其餘灰色merged, _ = _manual_frame(df, "縣市", MANUAL_NATIONAL, True, numeric=is_numeric)fig = _render_manual_static(merged, is_numeric, "縣市", MANUAL_NATIONAL, "", scheme, label_mode, label_size,vrange=vrange, cats=cats, figsize=(9, 9))add_slide(f"{county}|{base}" if base else county, fig, [], info=(county, county_entries[county]))done += 1; progress((done, steps), desc="產生簡報")for county in [] if county_mode else counties:df = manual_table("鄉鎮市區", county, store)merged, _ = _manual_frame(df, "鄉鎮市區", county, True, numeric=is_numeric)fig = _render_manual_static(merged, is_numeric, "鄉鎮市區", county, "", scheme, label_mode, label_size,vrange=vrange, cats=cats, figsize=(9, 9))rows = [(n[len(county):], v) for n, v in ordered if county_of[n] == county]if is_numeric: rows.sort(key=lambda r: -float(r[1].replace(",", "")))add_slide(f"{county}|{base}" if base else f"{county}各鄉鎮市區", fig, rows if with_table else [])done += 1; progress((done, steps), desc="產生簡報")path = _tmp_path(".pptx")112 unmodified linesov = fig.add_axes([0, 0, 1, 1])ov.set_xlim(0, W); ov.set_ylim(0, H); ov.set_axis_off(); ov.patch.set_alpha(0)anchors = _county_anchors()def to_in(lonlat):px = map_ax.transData.transform(lonlat)8 unmodified linesk = klass(n)rank, raw = label_of(n)# 灰色(其他)膠囊的名次數字用較深的灰,白圈裡才看得清楚_draw_pill(ov, x, y, pill_w, pill_h, n, rank, raw, color_of[k] if k != "none" else "#d1d5db",k != "none", 15, rank_color=color_of[k] if k in ("top", "bottom") else "#6b7280")left, right = _rank_columns(anchors)line_kw = dict(color="#8a8f98", lw=0.9, zorder=3, solid_capstyle="round")5 unmodified linesedge_x = x + pill_w if x == x_left else xov.plot([edge_x, ax_, ax_], [y, y, ay_], **line_kw) # 先水平、再垂直接到縣市ov.plot([ax_], [ay_], "o", ms=3.2, color="#111827", zorder=4)# 臺北市:上方中間,垂直引線tx, ty = to_in(anchors["臺北市"])1 unmodified lineput("臺北市", tx - pill_w / 2, top_y)ov.plot([tx, tx], [top_y - pill_h / 2, ty], **line_kw)ov.plot([tx], [ty], "o", ms=3.2, color="#111827", zorder=4)# 離島:最下排,只列標籤bottom_y = y_last19 unmodified linesov.add_patch(FancyBboxPatch((lx, H - 1.28), 1.5, 0.1, boxstyle="round,pad=0,rounding_size=0.05", fc=color,ec=color, zorder=5))ov.text(lx + 0.75, H - 1.55, text, ha="center", va="center", fontsize=15, color="#111827", **font_kw)lx += 2.2if unit_note:ov.text(W - 0.45, H - 1.6, unit_note, ha="right", va="center", fontsize=9, color="#4b5563", **font_kw)if footnote:ov.text(W - 0.45, 0.28, footnote, ha="right", va="center", fontsize=11, color="#374151", **font_kw)return figdef _rank_figure(input_df, store, title, subtitle, unit_note, footnote, order, top_n, c_top, c_bottom, c_other):store = merge_table_into_store(input_df, store)entries = _county_numeric_entries(store)return render_rank_infographic(1 unmodified linecolors=(c_top or INFO_DEFAULT_COLORS[0], c_bottom or INFO_DEFAULT_COLORS[1], c_other or INFO_DEFAULT_COLORS[2]))def preview_rank_infographic(*args):fig = _rank_figure(*args)path = _tmp_path(".png")fig.savefig(path, dpi=110, facecolor="white")return path1 unmodified linedef export_rank_infographic(*args, fmt="png"):"""args = 預覽用的參數 + [透明背景];PNG/SVG/PPTX(單頁,頁面比例與圖相同)"""*render_args, transparent = argsfig = _rank_figure(*render_args)path = _tmp_path(f".{fmt}")if fmt == "pptx":from pptx import Presentationfrom pptx.util import Inchespng = _tmp_path(".png")fig.savefig(png, dpi=200, facecolor="white")w, h = fig.get_size_inches()prs = Presentation()prs.slide_width, prs.slide_height = Inches(13.333), Inches(13.333 * h / w)slide = prs.slides.add_slide(prs.slide_layouts[6])slide.shapes.add_picture(png, 0, 0, prs.slide_width, prs.slide_height)prs.save(path)else:fig.savefig(path, format=fmt, dpi=200, transparent=bool(transparent),facecolor="none" if transparent else "white")1424 unmodified lines14251426142714281429143014311432143315 unmodified lines1449145014511452145314541455145614571458145914601461146214631464146514661 unmodified line146814691470147114721473147414751476147714781479148014811482148314841485148614871488148940 unmodified lines1530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816798 unmodified lines16881689169016911692169321 unmodified lines17151716171717181719172017211 unmodified line172317241725172617271728172930 unmodified lines1760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790112 unmodified lines1903190419051906190719081909191019111912191319148 unmodified lines192319241925192619271928192919301931193219335 unmodified lines193919401941194219431944194519461 unmodified line1948194919501951195219531954195519 unmodified lines197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320541 unmodified line20562057205820592060206120621 unmodified line20642065206620672068206920702071207220731424 unmodified linesreturn figdef _render_manual_static(merged, is_numeric, level, scope, title, scheme, label_mode, label_size,vrange=None, cats=None, figsize=(12, 12), scene=None):"""靜態圖 (matplotlib)。PPTX 每頁共用 vrange(數值)或 cats(分類),各頁顏色才能互相比較。傳入 scene(dict)時,另外把地圖區塊、標籤、圖例收集起來,供匯出可編輯的原生 PPTX 使用。"""if is_numeric:# 縣市層級的離島外標籤會往右伸出,色條要往右讓開才不會蓋住fig = build_static_map(merged, "數值", title, scheme=scheme, figsize=figsize, vrange=vrange,15 unmodified linesif level == "鄉鎮市區" and scope not in DEFAULT_COUNTIES:_require_map("county").boundary.plot(ax=ax, color="#374151", linewidth=0.7)ax.apply_aspect()fs = int(label_size) * 0.85placed = []if label_mode != "不顯示標籤":font_kw = {"fontproperties": CUSTOM_FONT_PROP} if CUSTOM_FONT_PROP else {}# 量出座標軸實際大小,換算「每 pt 幾度」(色條、圖例都會影響軸的大小,不能用估的)pos = ax.get_position()(x0, x1), (y0, y1) = ax.get_xlim(), ax.get_ylim()kx = (x1 - x0) / (pos.width * fig.get_figwidth() * 72)ky = (y1 - y0) / (pos.height * fig.get_figheight() * 72)placed = _place_labels(merged, level, label_mode, fs, kx, ky)for lab in placed:ax.annotate(lab["text"], xy=lab["anchor"], xytext=lab["pos"], ha="center", va="center", fontsize=fs, **font_kw,bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="gray", alpha=0.92),1 unmodified line)if lab["edge"]:ax.plot(*lab["anchor"], "o", ms=2.5, color="#374151", zorder=5)if scene is not None:if is_numeric:vals = merged["數值"]lo, hi = vrange if vrange else (float(vals.min()), float(vals.max()))cmap = mpl.colormaps[MPL_CMAPS[scheme]]color_of = lambda row: (NO_DATA_COLOR if pd.isna(row["數值"]) elsempl.colors.to_hex(cmap((row["數值"] - lo) / (hi - lo) if hi > lo else 1.0)))legend = {"kind": "num", "lo": lo, "hi": hi, "cmap": cmap}else:cat_list, pal = _category_palette(merged, cats)color_of = lambda row: pal[row["類別"]]legend = {"kind": "cat", "items": [(c, pal[c]) for c in cat_list]}scene.update(xf=lambda a: ax.transData.transform(np.asarray(a, dtype=float)) / fig.dpi,regions=[(r["name"], r.geometry, color_of(r)) for _, r in merged.iterrows()],labels=placed, legend=legend, fs=fs)return figdef regenerate_manual_map(*args):40 unmodified linesPPT_FONT = "Microsoft JhengHei"PPT_TABLE_MAX_ROWS = 22# --- 原生 PowerPoint 物件:文字方塊、圖形、向量地圖,匯出後都能在 PowerPoint 裡直接編輯 ---def _emu(inches: float) -> int:return int(round(inches * 914400))def _pp_rgb(hex_str: str):from pptx.dml.color import RGBColorreturn RGBColor.from_string(hex_str.lstrip("#").upper())def _pp_fill_text(tf, lines, size, bold=False, color="#111827", align="c", anchor="m", margins=(0, 0, 0, 0)):"""把文字寫進 text_frame(每行一個段落)。align: l/c/r;anchor: t/m/b;margins 為英吋 (左, 上, 右, 下)。"""from pptx.util import Pt, Inchesfrom pptx.enum.text import PP_ALIGN, MSO_ANCHORtf.word_wrap = Falsetf.margin_left, tf.margin_top, tf.margin_right, tf.margin_bottom = (Inches(m) for m in margins)tf.vertical_anchor = {"t": MSO_ANCHOR.TOP, "m": MSO_ANCHOR.MIDDLE, "b": MSO_ANCHOR.BOTTOM}[anchor]lines = [lines] if isinstance(lines, str) else list(lines)for i, line in enumerate(lines):para = tf.paragraphs[0] if i == 0 else tf.add_paragraph()para.alignment = {"l": PP_ALIGN.LEFT, "c": PP_ALIGN.CENTER, "r": PP_ALIGN.RIGHT}[align]run = para.add_run()run.text = linerun.font.size, run.font.bold, run.font.name = Pt(size), bold, PPT_FONTrun.font.color.rgb = _pp_rgb(color)def _pp_text(shapes, x, y, w, h, lines, size, bold=False, color="#111827", align="c", anchor="m", name=None):from pptx.util import Inchestb = shapes.add_textbox(Inches(x), Inches(y), Inches(w), Inches(h))if name: tb.name = name_pp_fill_text(tb.text_frame, lines, size, bold, color, align, anchor)return tbdef _pp_shape(shapes, kind, x, y, w, h, fill=None, line=None, line_pt=1.0, name=None, radius=0.5):"""kind: rect / round / oval。round 的 radius=0.5 就是膠囊形。"""from pptx.util import Inches, Ptfrom pptx.enum.shapes import MSO_SHAPEshp = shapes.add_shape({"rect": MSO_SHAPE.RECTANGLE, "round": MSO_SHAPE.ROUNDED_RECTANGLE,"oval": MSO_SHAPE.OVAL}[kind], Inches(x), Inches(y), Inches(w), Inches(h))if kind == "round": shp.adjustments[0] = radiusif fill: shp.fill.solid(); shp.fill.fore_color.rgb = _pp_rgb(fill)else: shp.fill.background()if line: shp.line.color.rgb = _pp_rgb(line); shp.line.width = Pt(line_pt)else: shp.line.fill.background()shp.shadow.inherit = Falseif name: shp.name = namereturn shpdef _pp_line(shapes, p1, p2, color="#8a8f98", width_pt=0.9):from pptx.util import Inches, Ptfrom pptx.enum.shapes import MSO_CONNECTORconn = shapes.add_connector(MSO_CONNECTOR.STRAIGHT, Inches(p1[0]), Inches(p1[1]), Inches(p2[0]), Inches(p2[1]))conn.line.color.rgb = _pp_rgb(color)conn.line.width = Pt(width_pt)return conndef _pp_polygon(shapes, geom, to_slide, fill, line="#ffffff", line_pt=0.75, name=None):"""shapely 多邊形 → PowerPoint 自由形狀(向量,可在 PowerPoint 裡換色、編輯節點)。to_slide:(n,2) 座標 → 投影片英吋座標(y 向下)。外環與內環(洞)方向相反,才會正確挖洞。"""from pptx.util import Ptfrom shapely.geometry.polygon import orientrings = []for poly in getattr(geom, "geoms", [geom]):if poly.geom_type != "Polygon" or poly.is_empty: continuepoly = orient(poly, 1.0)for ring in [poly.exterior, *poly.interiors]:pts = np.asarray(to_slide(np.asarray(ring.coords)))snapped = [(round(x * 200) / 200, round(y * 200) / 200) for x, y in pts] # 0.005 英吋格點,去掉看不見的細節uniq = [snapped[0]] + [b for a, b in zip(snapped, snapped[1:]) if a != b]if uniq[0] == uniq[-1]: uniq = uniq[:-1]if len(uniq) >= 3: rings.append([(_emu(x), _emu(y)) for x, y in uniq])if not rings: return Nonebuilder = shapes.build_freeform(rings[0][0][0], rings[0][0][1], 1.0)for i, ring in enumerate(rings):if i: builder.move_to(*ring[0])builder.add_line_segments(ring[1:], close=True)shp = builder.convert_to_shape()shp.fill.solid(); shp.fill.fore_color.rgb = _pp_rgb(fill)shp.line.color.rgb = _pp_rgb(line); shp.line.width = Pt(line_pt)shp.shadow.inherit = Falseif name: shp.name = namereturn shpdef _pp_native_map(slide, scene, box):"""把 _render_manual_static 收集的 scene 畫成原生物件:地圖區塊(向量)、標籤(文字方塊)、引線、圖例。box = (x, y, w, h) 英吋;內容等比例縮放置中。"""bx, by, bw, bh = boxxf, fs = scene["xf"], scene["fs"]legend = scene["legend"]map_w = bw - (1.8 if legend else 0)def label_geom(lab): # 標籤中心與外框大小(英吋,圖形座標,y 向上)(cx, cy), (hx, hy) = (xf(np.array([lab["pos"]]))[0],xf(np.array([[lab["pos"][0] + lab["w"] / 2, lab["pos"][1] + lab["h"] / 2]]))[0])return (cx, cy), (abs(hx - cx) * 2, abs(hy - cy) * 2)corners = [xf(np.array([(g.bounds[0], g.bounds[1]), (g.bounds[2], g.bounds[3])])) for _, g, _ in scene["regions"]]xs = [p[0] for c in corners for p in c]; ys = [p[1] for c in corners for p in c]laid = [(lab, *label_geom(lab)) for lab in scene["labels"]]for _, (cx, cy), (w, h) in laid:xs += [cx - w / 2, cx + w / 2]; ys += [cy - h / 2, cy + h / 2]ex0, ex1, ey0, ey1 = min(xs), max(xs), min(ys), max(ys)k = min(map_w / (ex1 - ex0), bh / (ey1 - ey0))ox = bx + (map_w - k * (ex1 - ex0)) / 2oy = by + (bh - k * (ey1 - ey0)) / 2def to_slide(lonlat): # 經緯度 → 圖形英吋(xf)→ 投影片英吋(等比例縮放、y 向下)a = xf(np.asarray(lonlat, dtype=float).reshape(-1, 2))return np.column_stack([ox + (a[:, 0] - ex0) * k, oy + (ey1 - a[:, 1]) * k])grp = slide.shapes.add_group_shape()grp.name = "地圖"for name, geom, color in scene["regions"]:_pp_polygon(grp.shapes, geom, to_slide, color, "#ffffff", 0.75, name)for lab, _, _ in laid: # 引線與錨點在標籤下面if lab["edge"]:a, e = to_slide([lab["anchor"]])[0], to_slide([lab["edge"]])[0]_pp_line(slide.shapes, a, e, "#6b7280", 0.9)_pp_shape(slide.shapes, "oval", a[0] - 0.03, a[1] - 0.03, 0.06, 0.06, fill="#374151")for lab, (cx, cy), (w, h) in laid:X, Y = ox + (cx - ex0) * k, oy + (ey1 - cy) * kshp = _pp_shape(slide.shapes, "round", X - w * k / 2, Y - h * k / 2, w * k, h * k, fill="#ffffff",line="#9ca3af", line_pt=0.75, name=f"標籤 {lab['text'].splitlines()[0]}", radius=0.2)_pp_fill_text(shp.text_frame, lab["text"].split("\n"), max(6.0, fs * k), False, "#111827", "c", "m")if legend: # 圖例(右下角)lx, ly1 = bx + bw - 1.7, by + bhif legend["kind"] == "cat":for i, (text, color) in enumerate(reversed(legend["items"][:12])):y = ly1 - 0.3 * (i + 1)_pp_shape(slide.shapes, "rect", lx, y + 0.04, 0.2, 0.2, fill=color, line="#9ca3af", line_pt=0.5,name=f"圖例色塊 {text}")_pp_text(slide.shapes, lx + 0.3, y, 1.35, 0.28, text, 11, align="l", name=f"圖例 {text}")else:steps, top = 8, ly1 - 2.6for i in range(steps): # 上面是最大值、下面是最小值frac = 1 - i / (steps - 1)_pp_shape(slide.shapes, "rect", lx, top + i * 0.3, 0.3, 0.3, name=f"色階 {i + 1}",fill=mpl.colors.to_hex(legend["cmap"](frac)))fmt = lambda v: f"{v:,.0f}" if abs(legend["hi"]) >= 100 else f"{v:,.2f}"_pp_text(slide.shapes, lx + 0.4, top - 0.05, 1.3, 0.3, fmt(legend["hi"]), 11, align="l", name="色階最大值")_pp_text(slide.shapes, lx + 0.4, top + steps * 0.3 - 0.25, 1.3, 0.3, fmt(legend["lo"]), 11, align="l",name="色階最小值")def _fig_png(fig, dpi=170):buf = io.BytesIO()fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight", transparent=True)8 unmodified lines"""from pptx import Presentationfrom pptx.util import Inches, Ptstore = merge_table_into_store(input_df, store)town_gdf = _town_gdf()21 unmodified linesprs.slide_width, prs.slide_height = Inches(13.333), Inches(7.5)blank = prs.slide_layouts[6]def add_slide(heading, scene, rows, info=None):slide = prs.slides.add_slide(blank)tb = slide.shapes.add_textbox(Inches(0.5), Inches(0.3), Inches(12.3), Inches(0.9))run = tb.text_frame.paragraphs[0].add_run()1 unmodified linerun.font.size, run.font.bold, run.font.name = Pt(32), True, PPT_FONTbox_w = 7.9 if (rows or info) else 12.3_pp_native_map(slide, scene, (0.5, 1.35, box_w, 5.8)) # 地圖、標籤、圖例都是可編輯的原生物件if info: # 只有縣市資料時:右側用大字呈現該縣市的內容panel = slide.shapes.add_textbox(Inches(8.7), Inches(2.4), Inches(4.1), Inches(3.2)).text_framepanel.word_wrap = True30 unmodified linesif with_overview and county_entries:df = manual_table("縣市", MANUAL_NATIONAL, store)merged, num = _manual_frame(df, "縣市", MANUAL_NATIONAL, True)sc = {}_render_manual_static(merged, num, "縣市", MANUAL_NATIONAL, "", scheme, label_mode, label_size,figsize=(10, 10), scene=sc)rows = [(n, county_entries[n]) for n in DEFAULT_COUNTIES if n in county_entries] if with_table else []add_slide(base or "臺灣各縣市", sc, rows)done += 1; progress((done, steps), desc="產生簡報")for county in counties if county_mode else []:df = manual_table("縣市", MANUAL_NATIONAL, {county: county_entries[county]}) # 只留這個縣市有值,其餘灰色merged, _ = _manual_frame(df, "縣市", MANUAL_NATIONAL, True, numeric=is_numeric)sc = {}_render_manual_static(merged, is_numeric, "縣市", MANUAL_NATIONAL, "", scheme, label_mode, label_size,vrange=vrange, cats=cats, figsize=(9, 9), scene=sc)add_slide(f"{county}|{base}" if base else county, sc, [], info=(county, county_entries[county]))done += 1; progress((done, steps), desc="產生簡報")for county in [] if county_mode else counties:df = manual_table("鄉鎮市區", county, store)merged, _ = _manual_frame(df, "鄉鎮市區", county, True, numeric=is_numeric)sc = {}_render_manual_static(merged, is_numeric, "鄉鎮市區", county, "", scheme, label_mode, label_size,vrange=vrange, cats=cats, figsize=(9, 9), scene=sc)rows = [(n[len(county):], v) for n, v in ordered if county_of[n] == county]if is_numeric: rows.sort(key=lambda r: -float(r[1].replace(",", "")))add_slide(f"{county}|{base}" if base else f"{county}各鄉鎮市區", sc, rows if with_table else [])done += 1; progress((done, steps), desc="產生簡報")path = _tmp_path(".pptx")112 unmodified linesov = fig.add_axes([0, 0, 1, 1])ov.set_xlim(0, W); ov.set_ylim(0, H); ov.set_axis_off(); ov.patch.set_alpha(0)# 同步收集每個元素,匯出 PPTX 時畫成可編輯的原生物件scene = {"W": W, "H": H, "pills": [], "lines": [], "dots": [], "legend": [],"xf": lambda a: map_ax.transData.transform(np.asarray(a, dtype=float)) / fig.dpi,"regions": [(r["name"], r.geometry, color_of[r["_class"]]) for _, r in main.iterrows()],"unit": unit_note, "note": footnote, "title": (title or "各縣市排名", subtitle)}anchors = _county_anchors()def to_in(lonlat):px = map_ax.transData.transform(lonlat)8 unmodified linesk = klass(n)rank, raw = label_of(n)# 灰色(其他)膠囊的名次數字用較深的灰,白圈裡才看得清楚pill_color = color_of[k] if k != "none" else "#d1d5db"rank_color = color_of[k] if k in ("top", "bottom") else "#6b7280"_draw_pill(ov, x, y, pill_w, pill_h, n, rank, raw, pill_color, k != "none", 15, rank_color=rank_color)scene["pills"].append(dict(x=x, y=y, w=pill_w, h=pill_h, name=n, rank=rank, value=raw, color=pill_color,rank_color=rank_color, ranked=k != "none", fs=15))left, right = _rank_columns(anchors)line_kw = dict(color="#8a8f98", lw=0.9, zorder=3, solid_capstyle="round")5 unmodified linesedge_x = x + pill_w if x == x_left else xov.plot([edge_x, ax_, ax_], [y, y, ay_], **line_kw) # 先水平、再垂直接到縣市ov.plot([ax_], [ay_], "o", ms=3.2, color="#111827", zorder=4)scene["lines"] += [((edge_x, y), (ax_, y)), ((ax_, y), (ax_, ay_))]scene["dots"].append((ax_, ay_))# 臺北市:上方中間,垂直引線tx, ty = to_in(anchors["臺北市"])1 unmodified lineput("臺北市", tx - pill_w / 2, top_y)ov.plot([tx, tx], [top_y - pill_h / 2, ty], **line_kw)ov.plot([tx], [ty], "o", ms=3.2, color="#111827", zorder=4)scene["lines"].append(((tx, top_y - pill_h / 2), (tx, ty)))scene["dots"].append((tx, ty))# 離島:最下排,只列標籤bottom_y = y_last19 unmodified linesov.add_patch(FancyBboxPatch((lx, H - 1.28), 1.5, 0.1, boxstyle="round,pad=0,rounding_size=0.05", fc=color,ec=color, zorder=5))ov.text(lx + 0.75, H - 1.55, text, ha="center", va="center", fontsize=15, color="#111827", **font_kw)scene["legend"].append((color, text, lx))lx += 2.2if unit_note:ov.text(W - 0.45, H - 1.6, unit_note, ha="right", va="center", fontsize=9, color="#4b5563", **font_kw)if footnote:ov.text(W - 0.45, 0.28, footnote, ha="right", va="center", fontsize=11, color="#374151", **font_kw)return fig, scenedef build_rank_pptx(scene, path):"""圖解排名 → 單頁 PPTX。地圖區塊是向量圖形;標題、圖例、膠囊標籤(名次、縣市、數值)、說明都是文字方塊或圖形。"""from pptx import Presentationfrom pptx.util import Inches, Ptfrom pptx.enum.text import PP_ALIGN, MSO_ANCHORW, H = scene["W"], scene["H"]s = 13.333 / W # 圖的英吋 → 投影片英吋prs = Presentation()prs.slide_width, prs.slide_height = Inches(13.333), Inches(H * s)slide = prs.slides.add_slide(prs.slide_layouts[6])X = lambda x: x * sY = lambda y: (H - y) * s # 圖的 y 向上、投影片 y 向下to_slide = lambda a: np.column_stack([scene["xf"](a)[:, 0] * s, (H - scene["xf"](a)[:, 1]) * s])grp = slide.shapes.add_group_shape()grp.name = "臺灣地圖"for name, geom, color in scene["regions"]:_pp_polygon(grp.shapes, geom, to_slide, color, "#ffffff", 0.9, name)for p1, p2 in scene["lines"]:_pp_line(slide.shapes, (X(p1[0]), Y(p1[1])), (X(p2[0]), Y(p2[1])), "#8a8f98", 0.9)for x, y in scene["dots"]:_pp_shape(slide.shapes, "oval", X(x) - 0.03, Y(y) - 0.03, 0.06, 0.06, fill="#111827")for pl in scene["pills"]:x, y, w, h, fs = pl["x"] * s, Y(pl["y"]), pl["w"] * s, pl["h"] * s, pl["fs"] * swl = w * 0.64g = slide.shapes.add_group_shape()g.name = f"標籤 {pl['name']}"_pp_shape(g.shapes, "round", x, y - h / 2, w, h, fill="#ffffff", line=pl["color"], line_pt=1.3, name="外框")name_box = _pp_shape(g.shapes, "round", x, y - h / 2, wl, h, fill=pl["color"], line=pl["color"], line_pt=1.3,name="縣市")_pp_fill_text(name_box.text_frame, pl["name"], fs, True, "#ffffff", "l", "m", margins=(h * 1.05, 0, 0.02, 0))circle = _pp_shape(g.shapes, "oval", x + h / 2 - h * 0.36, y - h * 0.36, h * 0.72, h * 0.72, fill="#ffffff",name="名次")_pp_fill_text(circle.text_frame, pl["rank"], fs * 0.72, True, pl["rank_color"], "c", "m")_pp_text(g.shapes, x + wl, y - h / 2, w - wl, h, pl["value"], fs, True,"#111827" if pl["ranked"] else "#9ca3af", "c", "m", name="數值")title, sub = scene["title"] # 標題與副標放同一個文字方塊(兩個 run),方便整段修改tb = slide.shapes.add_textbox(Inches(X(0.3)), Inches(Y(H - 0.75) - 0.35), Inches(X(W - 0.6)), Inches(0.7))tb.name = "標題"tf = tb.text_frametf.word_wrap = Falsetf.vertical_anchor = MSO_ANCHOR.MIDDLEpara = tf.paragraphs[0]para.alignment = PP_ALIGN.CENTERfor text, size, bold in ((title, 27 * s, True), (" " + sub if sub else "", 15 * s, False)):if not text: continuerun = para.add_run()run.text = textrun.font.size, run.font.bold, run.font.name = Pt(size), bold, PPT_FONTrun.font.color.rgb = _pp_rgb("#111827")for color, text, lx in scene["legend"]:_pp_shape(slide.shapes, "round", X(lx), Y(H - 1.23) - 0.05 * s, 1.5 * s, 0.1 * s, fill=color, name=f"圖例色條 {text}")_pp_text(slide.shapes, X(lx), Y(H - 1.55) - 0.15, 1.5 * s, 0.3, text, 15 * s, name=f"圖例 {text}")if scene["unit"]:_pp_text(slide.shapes, X(W - 0.45) - 4.0, Y(H - 1.6) - 0.15, 4.0, 0.3, scene["unit"], 9 * s, False, "#4b5563","r", name="單位說明")if scene["note"]:_pp_text(slide.shapes, X(W - 0.45) - 6.0, Y(0.28) - 0.15, 6.0, 0.3, scene["note"], 11 * s, False, "#374151","r", name="註解")prs.save(path)def _rank_figure(input_df, store, title, subtitle, unit_note, footnote, order, top_n, c_top, c_bottom, c_other):"""回傳 (matplotlib 圖, scene);scene 供匯出原生 PPTX 使用"""store = merge_table_into_store(input_df, store)entries = _county_numeric_entries(store)return render_rank_infographic(1 unmodified linecolors=(c_top or INFO_DEFAULT_COLORS[0], c_bottom or INFO_DEFAULT_COLORS[1], c_other or INFO_DEFAULT_COLORS[2]))def preview_rank_infographic(*args):fig, _ = _rank_figure(*args)path = _tmp_path(".png")fig.savefig(path, dpi=110, facecolor="white")return path1 unmodified linedef export_rank_infographic(*args, fmt="png"):"""args = 預覽用的參數 + [透明背景];PNG/SVG/PPTX(單頁,頁面比例與圖相同)"""*render_args, transparent = argsfig, scene = _rank_figure(*render_args)path = _tmp_path(f".{fmt}")if fmt == "pptx":build_rank_pptx(scene, path)else:fig.savefig(path, format=fmt, dpi=200, transparent=bool(transparent),facecolor="none" if transparent else "white")
app.py+267-38