Spaces:
Sleeping
Sleeping
Upload app.py
Browse files1813 unmodified lines181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170946 unmodified lines3117311831193120312131223123312431253126312731283129313031313132180 unmodified lines331333143315331633173318331933203321332233231813 unmodified lines buf.seek(0) return buf
# ===============================================# PPTX:標註框版型(一頁總覽,地圖居中、左右長出標註框)# ===============================================# 這一版型不做色階,改成「有填內容的地區上色+標註框+指標線」:# 適合「各縣市主要受損作物」這種一格放一段文字的清單型資料。
import math
ANNO_W, ANNO_H = 13.333, 7.5 # 16:9 投影片(英吋)ANNO_PAD = 0.40 # 外距ANNO_BOX_W = 3.52 # 標註框寬ANNO_COL_GAP = 0.26 # 標註框與地圖之間留的空間ANNO_INSET = ("澎湖縣", "金門縣", "連江縣") # 這三個畫成地圖下方的小圖ANNO_MAX_PT, ANNO_MIN_PT = 12.5, 7.5
def _hex_mix(a: str, b: str, t: float) -> str: """混色:t=0 就是 a、t=1 就是 b""" a, b = a.lstrip("#"), b.lstrip("#") ca = [int(a[i:i + 2], 16) for i in (0, 2, 4)] cb = [int(b[i:i + 2], 16) for i in (0, 2, 4)] return "#" + "".join(f"{round(x + (y - x) * t):02X}" for x, y in zip(ca, cb))
def _anno_lines(content) -> List[str]: """一格裡的內容拆成幾行:換行、|、;、; 都算分隔(簡報上一個縣市常有好幾類資訊)""" return [p.strip() for p in re.split(r"[\n\r||;;]+", str(content or "")) if p.strip()]
def _anno_char_w(ch: str) -> float: """字寬(以字級為 1):全形 1.0、數字與英文字母約 0.56""" return 1.0 if ord(ch) > 0x2E7F else 0.56
ANNO_NO_START = ",。、;:?!)」』】》〉”’%…—·,.;:?!)]}>»" # 不能落在行首ANNO_NO_END = "(「『【《〈“‘([{<«" # 不能落在行尾
def _anno_wrap(text: str, max_in: float, pt: float) -> List[str]: """自己折行(不靠 PowerPoint 的自動換行,每行才會跟估算的一樣寬),並做中文避頭尾。""" unit, out, line, w = pt / 72.0, [], "", 0.0 for ch in str(text): cw = _anno_char_w(ch) * unit if line and w + cw > max_in and ch not in ANNO_NO_START: if line[-1] in ANNO_NO_END: # 開括號留在上一行很難看,跟著一起換行 out.append(line[:-1]) line, w = line[-1], _anno_char_w(line[-1]) * unit else: out.append(line) line, w = "", 0.0 line += ch w += cw if line: out.append(line) return out or [""]
def _anno_balance(text: str, max_in: float, pt: float) -> List[str]: """標題這種大字:折行後如果最後一行只剩一兩個字,改成每行等長""" lines = _anno_wrap(text, max_in, pt) n = len(lines) if n < 2: return lines total = sum(sum(_anno_char_w(c) for c in ln) * pt / 72 for ln in lines) for i in range(1, 61): # 從「總寬 ÷ 行數」往上試,找到還排得成同樣行數的最小寬度 trial = _anno_wrap(text, total / n * (1 + i * 0.01), pt) if len(trial) <= n and all(sum(_anno_char_w(c) for c in t) * pt / 72 <= max_in for t in trial): return trial return lines
def _anno_metrics(pt: float, n_lines: int): """標註框的尺寸(英吋):標題條高度、內文區高度、行距""" header = pt * 1.78 / 72 line = pt * 1.45 / 72 body = n_lines * line + pt * 1.25 / 72 return header, body, line
def _anno_projection(box, bounds): """等距圓柱投影:以範圍中心緯度修正東西向,回傳 (to_in, 每度英吋)。 to_in(lons, lats) 直接給投影片英吋座標(y 向下)。""" bx, by, bw, bh = box lon0, lat0, lon1, lat1 = [float(v) for v in bounds] kx = math.cos(math.radians((lat0 + lat1) / 2)) span_x, span_y = max((lon1 - lon0) * kx, 1e-9), max(lat1 - lat0, 1e-9) s = min(bw / span_x, bh / span_y) ox, oy = bx + (bw - span_x * s) / 2, by + (bh - span_y * s) / 2
def to_in(lons, lats): return (ox + (np.asarray(lons, dtype=float) - lon0) * kx * s, oy + (lat1 - np.asarray(lats, dtype=float)) * s)
def to_slide(pts): xs, ys = to_in(np.asarray(pts)[:, 0], np.asarray(pts)[:, 1]) return np.column_stack([xs, ys])
return to_slide, (ox, oy, span_x * s, span_y * s)
def _anno_plan(merged, title: str, subtitle: str, note: str, main_color: str, max_items: int = 12, level: str = "縣市", show_islands: bool = True) -> Dict: """算出整張投影片的配置(全部是英吋座標),畫圖與除錯預覽共用同一份計算。""" main_color = (main_color or "#2F5D8A").strip() if not re.fullmatch(r"#[0-9a-fA-F]{6}", main_color): main_color = "#2F5D8A" paper, ink = "#FFFFFF", "#111827" base_fill = _hex_mix(main_color, "#16222E", 0.32) # 沒有標註的地區:暗底 hi_fill = _hex_mix(main_color, "#FFFFFF", 0.66) # 有標註的地區:亮底 line_color = _hex_mix(main_color, "#FFFFFF", 0.45)
top, bottom = 0.28, ANNO_H - 0.32 - (0.34 if note else 0.08) inset_names = [n for n in ANNO_INSET if level == "縣市"] if show_islands else [] main_df = merged[~merged["name"].isin(inset_names)] if inset_names else merged inset_df = merged[merged["name"].isin(inset_names)] if inset_names else merged.iloc[0:0]
# 地圖區塊:夾在左右兩欄之間,下面留一條放離島小圖 mid_x0 = ANNO_PAD + ANNO_BOX_W + ANNO_COL_GAP mid_x1 = ANNO_W - ANNO_PAD - ANNO_BOX_W - ANNO_COL_GAP strip = 0.66 if len(inset_names) else 0.0 map_box = (mid_x0, top, mid_x1 - mid_x0, bottom - top - (strip + 0.16 if strip else 0.0)) bounds = main_df.total_bounds if len(main_df) else merged.total_bounds to_slide, (mx, my, mw, mh) = _anno_projection(map_box, bounds)
# 標註項目:依表格填寫的順序,超過上限就取前幾個 items = [] filled = merged[merged["filled"]] for _, row in filled.iterrows(): lines = _anno_lines(row[MANUAL_COL_CONTENT]) if not lines: continue pt = row.geometry.representative_point() items.append({"name": str(row["label_name"]), "full": str(row["name"]), "lines": lines, "lon": pt.x, "lat": pt.y}) items = items[:max(int(max_items), 1)] for it in items: it["x"], it["y"] = to_slide([(it["lon"], it["lat"])])[0]
# 離島小圖:主圖下方排一排,各自用自己的範圍放大 cards = [] if strip: cw, ch = 0.98, strip total = len(inset_names) * cw cx0 = mx + (mw - total) / 2 for i, name in enumerate(inset_names): rows = inset_df[inset_df["name"] == name] if rows.empty: continue geom = rows.geometry.iloc[0] card = (cx0 + i * cw + 0.05, bottom - strip, cw - 0.10, ch - 0.26) c_to_slide, _ = _anno_projection(card, geom.bounds) on = bool(rows["filled"].iloc[0]) cards.append({"name": name.replace("縣", ""), "full": name, "geom": geom, "on": on, "box": (cx0 + i * cw + 0.05, bottom - strip, cw - 0.10, ch), "to_slide": c_to_slide, "cx": cx0 + i * cw + cw / 2, "cy": bottom - strip + (ch - 0.26) / 2}) # 離島的錨點換成小圖中心,指標線才不會指到畫面上不存在的位置 for it in items: card = next((c for c in cards if c["full"] == it["full"]), None) if card: it["x"], it["y"] = card["cx"], card["cy"] it["side"] = "L" if it["x"] < ANNO_W / 2 else "R"
# 左右兩欄:先依位置分邊(指標線最短),再把多的搬到另一邊讓兩欄一樣長 def split(force): """force=False:兩邊都有東西才搬(線才不會橫越整張圖); force=True:一邊全空或太擠時也搬,寧可線長一點也要放得下""" for it in items: it["side"] = "L" if it["x"] < ANNO_W / 2 else "R"
def side(k): return [it for it in items if it["side"] == k]
while abs(len(side("L")) - len(side("R"))) > 1: if not force and (not side("L") or not side("R")): break big, other = ("L", "R") if len(side("L")) > len(side("R")) else ("R", "L") pick = sorted(side(big), key=lambda d: abs(d["x"] - ANNO_W / 2))[0] pick["side"] = other return sorted(side("L"), key=lambda d: d["y"]), sorted(side("R"), key=lambda d: d["y"])
# 標題區(右欄上方) title_pt, sub_pt = 21.0, 14.0 title_lines = _anno_balance(title, ANNO_BOX_W, title_pt) if title else [] sub_lines = _anno_balance(subtitle, ANNO_BOX_W, sub_pt) if subtitle else [] title_h = len(title_lines) * title_pt * 1.26 / 72 + (0.13 + len(sub_lines) * sub_pt * 1.42 / 72 if sub_lines else 0)
# 兩欄排得下嗎?放不下就把字級一路縮 def layout(pt, left, right): cols, fit = {}, True for key, lst in (("L", left), ("R", right)): boxes = [] for it in lst: lines = [ln for line in it["lines"] for ln in _anno_wrap(line, ANNO_BOX_W - 0.30, pt)] header, body, line_h = _anno_metrics(pt, len(lines)) boxes.append({"name": it["name"], "pt": pt, "lines": lines, "header": header, "body": body, "line_h": line_h, "h": header + 0.03 + body, "anchor": it, "x": ANNO_PAD if key == "L" else ANNO_W - ANNO_PAD - ANNO_BOX_W}) col_top = top if key == "L" else top + title_h + 0.22 gap = pt * 1.05 / 72 room = bottom - col_top need = sum(b["h"] for b in boxes) + gap * max(len(boxes) - 1, 0) fit = fit and need <= room
def place(g, shift=0.0): """理想位置=框心對齊地區;依序往下推、超出底部再整體往上收""" y = col_top + shift for b in boxes: want = min(max(b["anchor"]["y"] - b["h"] / 2, y), bottom - b["h"]) b["y"] = max(y, want) y = b["y"] + b["h"] + g for i in range(len(boxes) - 1, -1, -1): lim = (bottom - boxes[i]["h"]) if i == len(boxes) - 1 else boxes[i + 1]["y"] - boxes[i]["h"] - g boxes[i]["y"] = max(min(boxes[i]["y"], lim), col_top)
place(gap) # 欄位還有空間時,把留白平均分到每個間隔(每個間隔最多多 0.45 吋),框才不會全擠在一起 slack = room - need if len(boxes) > 1 and slack > 0.25: extra = min(0.45, slack / (len(boxes) - 1)) place(gap + extra, max(0.0, (room - need - extra * (len(boxes) - 1)) / 2)) cols[key] = boxes return cols, fit
# 兩種分邊都試:挑「放得下、字最大、兩欄最平均」的那個 best = None for force in (False, True): left, right = split(force) pt = ANNO_MAX_PT cols, fit = layout(pt, left, right) while not fit and pt > ANNO_MIN_PT: pt = round(pt - 0.5, 2) cols, fit = layout(pt, left, right) score = (0 if fit else 1, -pt, abs(len(left) - len(right))) if best is None or score < best[0]: best = (score, cols, fit, pt) _, cols, fit, pt = best
# 指標線:框的內側邊中點 → 地區錨點,兩頭各留一點空隙 leaders = [] for key, boxes in cols.items(): start_x = ANNO_PAD + ANNO_BOX_W if key == "L" else ANNO_W - ANNO_PAD - ANNO_BOX_W for b in boxes: ax, ay = b["anchor"]["x"], b["anchor"]["y"] ey = b["y"] + b["h"] / 2 dx, dy = ax - start_x, ay - ey dist = math.hypot(dx, dy) or 1.0 u = min(0.14, dist / 2) leaders.append({"from": (start_x + dx * u / dist, ey + dy * u / dist), "to": (ax - dx * u / dist, ay - dy * u / dist), "anchor": (ax, ay), "color": line_color})
# 地圖填色:有標註的亮、其餘暗 marked = {it["full"] for it in items} regions = [(str(r["name"]), r.geometry, hi_fill if str(r["name"]) in marked else base_fill) for _, r in main_df.iterrows()]
return {"paper": paper, "ink": ink, "main": main_color, "base_fill": base_fill, "hi_fill": hi_fill, "to_slide": to_slide, "regions": regions, "cards": cards, "boxes": cols, "leaders": leaders, "title": {"lines": title_lines, "pt": title_pt, "x": ANNO_W - ANNO_PAD - ANNO_BOX_W, "y": top, "w": ANNO_BOX_W, "h": title_h}, "subtitle": {"lines": sub_lines, "pt": sub_pt, "x": ANNO_W - ANNO_PAD - ANNO_BOX_W, "y": top + (len(title_lines) * title_pt * 1.26 / 72 + 0.13 if title_lines else 0), "w": ANNO_BOX_W, "h": len(sub_lines) * sub_pt * 1.42 / 72}, "note": {"text": note, "x": ANNO_PAD, "y": bottom + 0.12, "w": ANNO_W - 2 * ANNO_PAD, "pt": 8.5} if note else None, "bottom": bottom, "fit": fit, "pt": pt}
def _append_anno_slide(prs, plan): """把 plan 畫成一頁:底色、向量地圖、離島小圖、指標線、標註框、標題/副標/註記。 全部是原生物件,匯出後在 PowerPoint 裡可以直接改字、換色、拉位置。""" from pptx.util import Inches, Pt
slide = prs.slides.add_slide(prs.slide_layouts[6]) fill = slide.background.fill fill.solid() fill.fore_color.rgb = _pp_rgb(plan["paper"]) main = plan["main"]
grp = slide.shapes.add_group_shape() grp.name = "地圖" for name, geom, color in plan["regions"]: _pp_polygon(grp.shapes, geom, plan["to_slide"], color, "#FFFFFF", 0.75, name) for card in plan["cards"]: x, y, w, h = card["box"] _pp_shape(slide.shapes, "rect", x, y, w, h, fill=_hex_mix(plan["paper"], main, 0.04), line=_hex_mix(main, "#FFFFFF", 0.78), line_pt=0.75, name=f"離島框 {card['name']}") _pp_polygon(slide.shapes, card["geom"], card["to_slide"], plan["hi_fill"] if card["on"] else plan["base_fill"], _hex_mix(main, "#FFFFFF", 0.40), 0.6, f"離島 {card['name']}") _pp_text(slide.shapes, x, y + h - 0.24, w, 0.20, card["name"], 7.5, bold=bool(card["on"]), color=main if card["on"] else "#6B7280", align="c", anchor="m", name=f"離島名稱 {card['name']}")
for ld in plan["leaders"]: _pp_line(slide.shapes, ld["from"], ld["to"], ld["color"], 1.0) ax, ay = ld["anchor"] _pp_shape(slide.shapes, "oval", ax - 0.035, ay - 0.035, 0.07, 0.07, fill=main, name="錨點")
for key, boxes in plan["boxes"].items(): for b in boxes: shp = _pp_shape(slide.shapes, "rect", b["x"], b["y"], ANNO_BOX_W, b["header"], fill=main, name=f"標題條 {b['name']}") _pp_fill_text(shp.text_frame, b["name"], b["pt"], True, "#FFFFFF", "l", "m", (0.10, 0, 0.04, 0)) _pp_shape(slide.shapes, "rect", b["x"], b["y"] + b["header"] + 0.03, ANNO_BOX_W, b["body"], fill="#FFFFFF", line=_hex_mix(main, "#FFFFFF", 0.62), line_pt=0.75, name=f"說明框 {b['name']}") _pp_text(slide.shapes, b["x"] + 0.11, b["y"] + b["header"] + 0.03 + 0.04, ANNO_BOX_W - 0.22, b["body"] - 0.06, b["lines"], b["pt"], False, "#1F2937", "l", "t", name=f"說明 {b['name']}")
t = plan["title"] if t["lines"]: _pp_text(slide.shapes, t["x"], t["y"], t["w"], t["h"], t["lines"], t["pt"], True, plan["ink"], "l", "t", name="主標題") s = plan["subtitle"] if s["lines"]: _pp_text(slide.shapes, s["x"], s["y"], s["w"], s["h"], s["lines"], s["pt"], True, main, "l", "t", name="副標") n = plan["note"] if n: _pp_line(slide.shapes, (n["x"], n["y"] - 0.04), (n["x"] + n["w"], n["y"] - 0.04), "#E5E7EB", 0.75) _pp_text(slide.shapes, n["x"], n["y"], n["w"], 0.24, n["text"], n["pt"], False, "#6B7280", "l", "t", name="註記") return slide
def build_annotation_pptx(merged, level, scope, title, subtitle, note, main_color, max_items=12, show_islands=True) -> str: """標註框版型 → 一份一頁的 PPTX(16:9)""" from pptx import Presentation from pptx.util import Inches
plan = _anno_plan(merged, _manual_title(title, level, scope), subtitle or "", note or "", main_color, max_items=max_items, level=level, show_islands=show_islands) prs = Presentation() prs.slide_width, prs.slide_height = Inches(ANNO_W), Inches(ANNO_H) _append_anno_slide(prs, plan) path = _named_path(_manual_file_stem(title, level, scope) + "_標註框", ".pptx") prs.save(path) return path
def export_annotation_pptx(input_df, level, scope, title, subtitle, note, main_color, max_items, show_islands): """「手動填寫」表格 → 一頁標註框地圖 PPTX。內容一格可以寫好幾行(換行或 ; 分隔)。""" merged, _ = _manual_frame(input_df, level, scope, show_islands) if not merged["filled"].any(): raise gr.Error("請先在表格裡至少填一格的內容") path = build_annotation_pptx(merged, level, scope, title, subtitle, note, main_color, max_items=max_items, show_islands=show_islands) gr.Info("已產生標註框版型 PPTX(地圖、標註框、文字都是可編輯物件)") return gr.update(value=path, visible=True)
def export_manual_pptx(input_df, store, title, color_scheme, label_mode, label_size, with_overview=True, with_table=True, progress=gr.Progress()): """946 unmodified lines btn_manual_pptx = gr.Button("📊 匯出 PPTX(一頁一個縣市)", variant="primary", scale=2) manual_ppt_overview = gr.Checkbox(label="含縣市總覽頁", value=True) manual_ppt_table = gr.Checkbox(label="附資料表", value=True) with gr.Accordion("🖼️ 標註框版型(一頁總覽)", open=False): gr.HTML('<div style="color:var(--text-dim,#8892a4);font-size:0.82rem;margin-bottom:6px;">地圖放中間,有填內容的地區上色、左右長出標註框(像簡報上「各縣市主要受損作物」那種)。<b>一格可以寫好幾行</b>:用換行或「;」分隔,例如「農糧:茶;畜牧:豬」。離島會畫成地圖下方的小圖。</div>') with gr.Row(): anno_sub = gr.Textbox(label="副標(大字,可留空)", placeholder="農業產物及民間設施損失累計 4 億 4,623 萬元") anno_note = gr.Textbox(label="註記(左下角,可留空)", placeholder="資料來源:農業部農業統計年報(2025 年)") with gr.Row(): anno_color = gr.ColorPicker(label="標註主色", value="#2F5D8A") anno_max = gr.Slider(4, 16, value=12, step=1, label="最多標註幾個地區") btn_anno_pptx = gr.Button("📊 匯出 PPTX(標註框版型)", variant="primary", scale=2) anno_file = gr.File(label="下載檔案", visible=False, elem_classes="tw-download") manual_file = gr.File(label="下載檔案", visible=False, elem_classes="tw-download") manual_preview = gr.Image(label="匯出預覽(棋盤格=透明)", visible=False, interactive=False, type="filepath")180 unmodified lines inputs=[manual_input_df, manual_store, manual_title, manual_color, manual_label_mode, manual_label_size, manual_ppt_overview, manual_ppt_table], outputs=manual_file) btn_anno_pptx.click( fn=export_annotation_pptx, inputs=[manual_input_df, manual_level, manual_scope, manual_title, anno_sub, anno_note, anno_color, anno_max, manual_islands], outputs=anno_file) rank_opts = [manual_input_df, manual_store, rk_title, rk_sub, rk_unit, rk_note, rk_order, rk_topn, rk_botn, rk_c1, rk_c2, rk_c3] btn_rk.click(fn=preview_rank_infographic, inputs=rank_opts, outputs=rk_preview)app.py+366