"""PowerPoint Pandoc template inspection page at `/template`."""
from __future__ import annotations
import html
from typing import Any
import gradio as gr
from services.pptx_template import (
MAPPING_CHOICES,
TemplateError,
analyze_pptx,
create_reference_pptx,
mapping_report,
row_statuses,
sequential_mapping,
structure_report_html,
uploaded_file_path,
)
def _empty_overview() -> str:
return """
WAITING FOR TEMPLATE
上傳 PPTX 後,這裡會列出版面數量與母片數量。
系統只修改 Slide Layout 的名稱,不會覆寫原始檔。
"""
def _overview(state: dict[str, Any]) -> str:
layouts = state["layouts"]
masters = len({item["master_index"] for item in layouts})
return f"""
TEMPLATE READY
{html.escape(state['source_name'])}
{masters}Masters
{len(layouts)}Layouts
{min(len(layouts), 7)}預設對應
"""
def _empty_contract() -> str:
return """
PANDOC PLACEHOLDER CONTRACT
等待檢查 Layout 結構
上傳模板並選好 Pandoc Layout 後,按下檢查按鈕。
"""
def analyze_template(template_file):
if template_file is None:
return {}, _empty_overview(), "請先上傳 PPTX 模板。"
try:
state = analyze_pptx(uploaded_file_path(template_file))
mappings = sequential_mapping(state["layouts"])
report = mapping_report(state["layouts"], mappings)
return state, _overview(state), "已讀取模板。\n" + report["text"]
except TemplateError as error:
return {}, _empty_overview(), f"讀取失敗:{error}"
except Exception:
return {}, _empty_overview(), "讀取失敗:無法解析 PPTX,請確認檔案完整後再試。"
def _check_result(state, mapping_values):
layouts = state["layouts"]
name_result = mapping_report(layouts, mapping_values)
contract_html, structure_ok, has_warning = structure_report_html(layouts, mapping_values)
if name_result["selected_count"] == 0:
prefix = "WARNING:尚未選擇任何 Mapping。"
elif not name_result["names_ok"]:
prefix = "FAIL:Pandoc Layout 名稱尚未完整。"
elif not structure_ok:
prefix = "FAIL:必要 Placeholder 不足。"
elif name_result["duplicates"] or has_warning:
prefix = "WARNING:可建立輸出,但有相容性注意事項。"
else:
prefix = "PASS:名稱與 Placeholder contract 均通過。"
return prefix + "\n" + name_result["text"], contract_html, row_statuses(layouts, mapping_values)
def check_mapping(state, *mapping_values):
if not state or not state.get("layouts"):
return "請先上傳並讀取 PPTX 模板。", _empty_contract()
status, contract_html, statuses = _check_result(state, list(mapping_values))
return status, contract_html, *statuses
def apply_sequential_preset(state):
layouts = state.get("layouts", []) if state else []
mappings = sequential_mapping(layouts)
status, contract_html, statuses = _check_result(state, mappings)
return *mappings, *statuses, status, contract_html
def clear_mapping(state):
layouts = state.get("layouts", []) if state else []
mappings = ["不修改"] * len(layouts)
status, contract_html, statuses = _check_result(state, mappings)
return *mappings, *statuses, status, contract_html
def create_template(state, *mapping_values):
if not state or not state.get("source_path") or not state.get("layouts"):
return None, "請先上傳並讀取 PPTX 模板。"
layouts = state["layouts"]
values = list(mapping_values)
try:
name_result = mapping_report(layouts, values)
_, structure_ok, has_warning = structure_report_html(layouts, values)
if name_result["selected_count"] == 0:
raise TemplateError("沒有選擇任何 Mapping;請至少指定一個 Pandoc Layout。")
if name_result["missing"]:
raise TemplateError(
"尚缺少 Pandoc 標準 Layout:" + "、".join(name_result["missing"]) + "。"
)
if not structure_ok:
raise TemplateError(
"必要 Placeholder 不足;請依相容性檢查的 FAIL 項目修正母片後再輸出。"
)
output_path = create_reference_pptx(
state["source_path"],
layouts,
values,
)
notices = ["建立完成。原始 PPTX 未被覆寫。"]
if name_result["duplicates"]:
notices.append(
"WARNING:存在重複 Pandoc Layout 名稱,Pandoc 可能只匹配第一個。"
)
if has_warning:
notices.append("WARNING:部分可選 Placeholder 缺少或 idx 重複,請參考檢查結果。")
return output_path, "\n".join(notices)
except TemplateError as error:
return None, f"建立失敗:{error}"
except Exception:
return None, "建立失敗:輸出檔案無法建立,請重新上傳後再試。"
def build_template_page():
"""Render the template tool into the active multipage route."""
template_state = gr.State({})
gr.HTML(
"""
讓自己的母片,
直接交給 Pandoc。
上傳既有 PowerPoint,檢查版面與 Placeholder,
再輸出一份可直接搭配 --reference-doc 使用的新 PPTX。
template.pptxlayout mapping
公司封面Title Slide
一般內容Title and Content
章節頁Section Header
左右雙欄Two Content
"""
)
gr.HTML(
"""
01
上傳模板
讀取所有 Slide Master 與 Slide Layout,原始檔只讀不覆寫。
"""
)
with gr.Column(elem_classes=["workbench-shell"]):
with gr.Row(equal_height=True, elem_classes=["workbench-grid"]):
with gr.Column(scale=6, min_width=360, elem_classes=["upload-pane"]):
gr.HTML('PowerPoint 來源
僅接受有效的 .pptx Open XML 檔案。
')
template_file = gr.File(
label="PowerPoint 模板",
file_types=[".pptx"],
type="filepath",
elem_classes=["file-drop"],
)
overview = gr.HTML(_empty_overview())
with gr.Column(scale=5, min_width=300, elem_classes=["guide-pane"]):
gr.HTML(
"""
安全、最小修改
分析與輸出都使用 python-pptx,檔案只存在暫存目錄。
- 依 Master / Layout 實際順序顯示所有版面。
- 前七個版面只套用可調整的預設建議。
- 直接讀取 OOXML Placeholder type 與 idx。
- 另存新的 reference.pptx,不改原始檔。
"""
)
analyze_status = gr.Textbox(
label="模板分析",
lines=4,
interactive=False,
placeholder="上傳 PPTX 後會顯示分析結果。",
elem_classes=["status-box"],
)
template_file.change(
analyze_template,
inputs=template_file,
outputs=[template_state, overview, analyze_status],
)
@gr.render(inputs=template_state)
def render_mapping_workflow(state):
layouts = (state or {}).get("layouts", [])
gr.HTML(
"""
02
對應版面
逐列選擇 Pandoc Layout;第 8 個以後預設不修改。
"""
)
with gr.Column(elem_classes=["mapping-shell"]):
with gr.Row(elem_classes=["mapping-toolbar"]):
with gr.Column(scale=5):
gr.HTML('順序預設
1~7 依序對應七個 Pandoc 標準 Layout,仍可逐列修改。
')
preset_button = gr.Button("重新套用順序預設", variant="secondary", elem_classes=["secondary-action"], interactive=bool(layouts))
clear_button = gr.Button("全部設為不修改", variant="secondary", elem_classes=["secondary-action"], interactive=bool(layouts))
gr.HTML('順序 / Master / 原始名稱 / PlaceholderPandoc Layout 對應檢查狀態
')
target_dropdowns = []
check_boxes = []
initial_mappings = sequential_mapping(layouts)
initial_statuses = row_statuses(layouts, initial_mappings) if layouts else []
with gr.Column(elem_classes=["mapping-list"]):
if not layouts:
gr.HTML('尚未讀取 Layout上傳 PPTX 後會在這裡顯示每一列的 Dropdown。
')
for index, layout in enumerate(layouts):
with gr.Row(elem_classes=["mapping-row"]):
gr.Textbox(
value=layout["name"] or "(未命名)",
label=f"{index + 1:02d} | Master {layout['master_index'] + 1} | 原始 Layout 名稱",
info=f"Placeholder:{layout['placeholder_summary']}",
interactive=False,
key=("original", index),
elem_classes=["mapping-original"],
)
target = gr.Dropdown(
label="Pandoc Layout 對應",
choices=MAPPING_CHOICES,
value=initial_mappings[index],
allow_custom_value=False,
filterable=False,
interactive=True,
key=("target", index),
elem_classes=["mapping-target"],
)
check_box = gr.Textbox(
label="檢查狀態",
value=initial_statuses[index],
interactive=False,
key=("status", index),
elem_classes=["mapping-check"],
)
target_dropdowns.append(target)
check_boxes.append(check_box)
check_button = gr.Button(
"檢查 Pandoc 名稱與 Placeholder",
variant="secondary",
elem_classes=["secondary-action"],
interactive=bool(layouts),
)
gr.HTML(
"""
03
Pandoc 相容性檢查
PASS 可直接使用;WARNING 不阻止輸出;FAIL 表示必要結構不足。
"""
)
if layouts:
initial_name_report = mapping_report(layouts, initial_mappings)
initial_report, _, _ = structure_report_html(layouts, initial_mappings)
mapping_status = gr.Textbox(
label="名稱與結構摘要",
value=initial_name_report["text"],
lines=5,
interactive=False,
elem_classes=["status-box"],
)
contract_report = gr.HTML(initial_report)
else:
mapping_status = gr.Textbox(
label="名稱與結構摘要",
value="請先上傳並讀取 PPTX 模板。",
lines=3,
interactive=False,
elem_classes=["status-box"],
)
contract_report = gr.HTML(_empty_contract())
gr.HTML(
"""
04
取得模板
通過必要檢查後,只重新命名 Layout 並另存唯一暫存檔。
"""
)
with gr.Column(elem_classes=["export-shell"]):
create_button = gr.Button(
"建立 Pandoc Reference PPTX",
variant="primary",
elem_classes=["primary-action"],
interactive=bool(layouts),
)
output_pptx = gr.File(label="調整後的 PowerPoint 模板", elem_classes=["output-file"])
output_status = gr.Textbox(label="建立結果", lines=5, interactive=False, elem_classes=["status-box"])
if layouts:
preset_button.click(
apply_sequential_preset,
inputs=template_state,
outputs=[*target_dropdowns, *check_boxes, mapping_status, contract_report],
)
clear_button.click(
clear_mapping,
inputs=template_state,
outputs=[*target_dropdowns, *check_boxes, mapping_status, contract_report],
)
check_button.click(
check_mapping,
inputs=[template_state, *target_dropdowns],
outputs=[mapping_status, contract_report, *check_boxes],
)
create_button.click(
create_template,
inputs=[template_state, *target_dropdowns],
outputs=[output_pptx, output_status],
)
gr.HTML(
"""
"""
)