Spaces:
Running
Running
Download services/pptx_template.py from u5ername/markdown2ppt-docker: direct link, hf CLI and curl.
- Browser
- Download file 19.3 kB
-
https://huggingface.co/spaces/u5ername/markdown2ppt-docker/resolve/main/services/pptx_template.py
- Command line
-
hf download hf://spaces/u5ername/markdown2ppt-docker/services/pptx_template.py
-
curl -L -o pptx_template.py https://huggingface.co/spaces/u5ername/markdown2ppt-docker/resolve/main/services/pptx_template.py
19.3 kB
| """PowerPoint layout inspection and minimal Pandoc reference-doc creation.""" | |
| from __future__ import annotations | |
| import html | |
| import os | |
| import re | |
| import tempfile | |
| import zipfile | |
| from collections import Counter | |
| from pathlib import Path | |
| from typing import Any, Iterable | |
| from pptx import Presentation | |
| MAX_PPTX_BYTES = 200 * 1024 * 1024 | |
| PANDOC_LAYOUTS = [ | |
| "Title Slide", | |
| "Title and Content", | |
| "Section Header", | |
| "Two Content", | |
| "Comparison", | |
| "Content with Caption", | |
| "Blank", | |
| ] | |
| MAPPING_CHOICES = ["不修改", *PANDOC_LAYOUTS] | |
| PLACEHOLDER_LABELS = { | |
| "object/content": "object/content", | |
| "title": "title", | |
| "ctrTitle": "ctrTitle", | |
| "subTitle": "subTitle", | |
| "body": "body", | |
| "date": "date", | |
| "footer": "footer", | |
| "slideNumber": "slideNumber", | |
| "picture": "picture", | |
| } | |
| _XML_TYPE_NORMALIZATION = { | |
| "obj": "object/content", | |
| "dt": "date", | |
| "ftr": "footer", | |
| "sldNum": "slideNumber", | |
| "pic": "picture", | |
| } | |
| # severity=error produces FAIL and blocks creation; warning does not. | |
| PANDOC_LAYOUT_CONTRACTS = { | |
| "Title Slide": [ | |
| { | |
| "types": ("ctrTitle",), | |
| "min": 1, | |
| "label": "Center Title Holder", | |
| "severity": "error", | |
| "why": "Pandoc 封面標題需要 Center Title / ctrTitle。", | |
| }, | |
| { | |
| "types": ("subTitle",), | |
| "min": 1, | |
| "label": "Subtitle Holder", | |
| "severity": "warning", | |
| "why": "沒有 Subtitle 時,subtitle 或 author metadata 可能無法輸出。", | |
| }, | |
| { | |
| "types": ("date",), | |
| "min": 1, | |
| "label": "Date Holder", | |
| "severity": "warning", | |
| "why": "沒有 Date 時,date metadata 可能無法輸出。", | |
| }, | |
| ], | |
| "Section Header": [ | |
| { | |
| "types": ("title", "ctrTitle"), | |
| "min": 1, | |
| "label": "Title / Center Title Holder", | |
| "severity": "error", | |
| "why": "Section Header 至少需要 Title 或 Center Title。", | |
| }, | |
| ], | |
| "Title and Content": [ | |
| { | |
| "types": ("title", "ctrTitle"), | |
| "min": 1, | |
| "label": "Title Holder", | |
| "severity": "warning", | |
| "why": "主要內容仍可放置,但投影片標題可能無法正常輸出。", | |
| }, | |
| { | |
| "types": ("object/content",), | |
| "min": 1, | |
| "label": "Content Holder", | |
| "severity": "error", | |
| "why": "一般內容需要至少 1 個沒有 type 屬性的 <p:ph>。", | |
| }, | |
| ], | |
| "Two Content": [ | |
| { | |
| "types": ("title", "ctrTitle"), | |
| "min": 1, | |
| "label": "Title Holder", | |
| "severity": "warning", | |
| "why": "主要內容仍可放置,但投影片標題可能無法正常輸出。", | |
| }, | |
| { | |
| "types": ("object/content",), | |
| "min": 2, | |
| "label": "Content Holder", | |
| "severity": "error", | |
| "why": "Pandoc 會分別使用第 1、2 個 Content Holder 建立左右雙欄。", | |
| }, | |
| ], | |
| "Comparison": [ | |
| { | |
| "types": ("title", "ctrTitle"), | |
| "min": 1, | |
| "label": "Title Holder", | |
| "severity": "warning", | |
| "why": "比較內容仍可放置,但投影片標題可能無法正常輸出。", | |
| }, | |
| { | |
| "types": ("body",), | |
| "min": 2, | |
| "label": "Body / Text Holder", | |
| "severity": "error", | |
| "why": "Comparison 需要左右各 1 個 Body / Text Holder。", | |
| }, | |
| { | |
| "types": ("object/content",), | |
| "min": 2, | |
| "label": "Content Holder", | |
| "severity": "error", | |
| "why": "Comparison 需要左右各 1 個 Content Holder。", | |
| }, | |
| ], | |
| "Content with Caption": [ | |
| { | |
| "types": ("title", "ctrTitle"), | |
| "min": 1, | |
| "label": "Title Holder", | |
| "severity": "warning", | |
| "why": "主要內容仍可放置,但投影片標題可能無法正常輸出。", | |
| }, | |
| { | |
| "types": ("body",), | |
| "min": 1, | |
| "label": "Body / Text Holder", | |
| "severity": "error", | |
| "why": "Content with Caption 需要至少 1 個 caption 文字區。", | |
| }, | |
| { | |
| "types": ("object/content",), | |
| "min": 1, | |
| "label": "Content Holder", | |
| "severity": "error", | |
| "why": "Content with Caption 需要至少 1 個主要內容區。", | |
| }, | |
| ], | |
| "Blank": [], | |
| } | |
| class TemplateError(ValueError): | |
| """Friendly, expected error raised while processing a user PPTX.""" | |
| def uploaded_file_path(file_value: Any) -> str: | |
| if file_value is None: | |
| raise TemplateError("尚未上傳 PowerPoint 模板。") | |
| return file_value if isinstance(file_value, str) else file_value.name | |
| def validate_pptx(path: str) -> None: | |
| if not path or not path.lower().endswith(".pptx"): | |
| raise TemplateError("檔案格式必須是 .pptx。") | |
| if not os.path.isfile(path): | |
| raise TemplateError("找不到上傳的 PowerPoint 檔案,請重新上傳。") | |
| if os.path.getsize(path) > MAX_PPTX_BYTES: | |
| raise TemplateError("PowerPoint 模板不可超過 200 MB。") | |
| if not zipfile.is_zipfile(path): | |
| raise TemplateError("這個檔案不是有效的 PPTX / Open XML 壓縮檔。") | |
| def _placeholder_xml(shape: Any): | |
| """Return the OOXML p:ph node without relying on the UI shape name.""" | |
| try: | |
| nodes = shape._element.xpath(".//p:ph") | |
| return nodes[0] if nodes else None | |
| except Exception: | |
| return None | |
| def _normalized_placeholder_type(ph_node: Any) -> str: | |
| xml_type = ph_node.get("type") | |
| if not xml_type: | |
| return "object/content" | |
| return _XML_TYPE_NORMALIZATION.get(xml_type, xml_type) | |
| def placeholder_item(shape: Any) -> dict[str, Any]: | |
| ph_node = _placeholder_xml(shape) | |
| if ph_node is None: | |
| return { | |
| "name": getattr(shape, "name", "") or "", | |
| "type": "unknown", | |
| "idx": None, | |
| } | |
| raw_idx = ph_node.get("idx") | |
| try: | |
| idx = int(raw_idx) if raw_idx is not None else None | |
| except ValueError: | |
| idx = raw_idx | |
| return { | |
| # Kept for diagnostics only; classification is based exclusively on p:ph. | |
| "name": getattr(shape, "name", "") or "", | |
| "type": _normalized_placeholder_type(ph_node), | |
| "idx": idx, | |
| } | |
| def placeholder_summary(placeholders: Iterable[dict[str, Any]]) -> str: | |
| counts = Counter(item.get("type", "unknown") for item in placeholders) | |
| if not counts: | |
| return "無 placeholder" | |
| preferred = [ | |
| "ctrTitle", "title", "subTitle", "body", "object/content", | |
| "picture", "date", "footer", "slideNumber", | |
| ] | |
| result = [] | |
| for placeholder_type in preferred: | |
| count = counts.pop(placeholder_type, 0) | |
| if count: | |
| label = PLACEHOLDER_LABELS.get(placeholder_type, placeholder_type) | |
| result.append(f"{label} × {count}" if count > 1 else label) | |
| for placeholder_type in sorted(counts): | |
| count = counts[placeholder_type] | |
| result.append(f"{placeholder_type} × {count}" if count > 1 else placeholder_type) | |
| return ", ".join(result) | |
| def collect_layouts(prs: Presentation) -> list[dict[str, Any]]: | |
| """Collect every layout in stable Slide Master / Slide Layout order.""" | |
| layouts: list[dict[str, Any]] = [] | |
| sequence = 0 | |
| for master_index, master in enumerate(prs.slide_masters): | |
| master_name = getattr(master, "name", "") or f"Master {master_index + 1}" | |
| for layout_index, layout in enumerate(master.slide_layouts): | |
| placeholders = [placeholder_item(shape) for shape in layout.placeholders] | |
| layouts.append( | |
| { | |
| "sequence": sequence, | |
| "master_index": master_index, | |
| "master_name": master_name, | |
| "layout_index": layout_index, | |
| "name": layout.name or "", | |
| "placeholders": placeholders, | |
| "placeholder_summary": placeholder_summary(placeholders), | |
| } | |
| ) | |
| sequence += 1 | |
| return layouts | |
| def analyze_pptx(path: str) -> dict[str, Any]: | |
| validate_pptx(path) | |
| try: | |
| presentation = Presentation(path) | |
| layouts = collect_layouts(presentation) | |
| except TemplateError: | |
| raise | |
| except Exception as error: | |
| raise TemplateError("無法解析 PPTX;檔案可能損壞或不是有效的 PowerPoint 簡報。") from error | |
| if not layouts: | |
| raise TemplateError("PPTX 中沒有找到任何 Slide Layout。") | |
| return { | |
| "source_path": path, | |
| "source_name": os.path.basename(path), | |
| "layouts": layouts, | |
| } | |
| def sequential_mapping(layouts: Iterable[dict[str, Any]]) -> list[str]: | |
| return [ | |
| PANDOC_LAYOUTS[index] if index < len(PANDOC_LAYOUTS) else "不修改" | |
| for index, _ in enumerate(layouts) | |
| ] | |
| def final_layout_names(layouts, mapping_values) -> list[str]: | |
| names = [] | |
| for index, layout in enumerate(layouts): | |
| selected = mapping_values[index] if index < len(mapping_values) else "不修改" | |
| names.append(selected if selected and selected != "不修改" else layout["name"]) | |
| return names | |
| def mapping_report(layouts, mapping_values) -> dict[str, Any]: | |
| selected_count = sum(value not in (None, "", "不修改") for value in mapping_values) | |
| final_names = final_layout_names(layouts, mapping_values) | |
| missing = [name for name in PANDOC_LAYOUTS if name not in final_names] | |
| duplicates = [name for name in PANDOC_LAYOUTS if final_names.count(name) > 1] | |
| changed = sum( | |
| index < len(mapping_values) | |
| and mapping_values[index] not in (None, "", "不修改", layout["name"]) | |
| for index, layout in enumerate(layouts) | |
| ) | |
| lines = [f"目前會修改 {changed} 個 Layout。"] | |
| if selected_count == 0: | |
| lines.append("尚未選擇任何 Mapping;請選擇至少一個 Pandoc Layout。") | |
| if missing: | |
| lines.append("缺少 Pandoc 標準名稱:" + "、".join(missing) + "。") | |
| else: | |
| lines.append("7 個 Pandoc 標準 Layout 名稱都已存在。") | |
| if duplicates: | |
| lines.append( | |
| "WARNING:以下 Pandoc 名稱出現超過一次:" | |
| + "、".join(duplicates) | |
| + "。Pandoc 可能只匹配第一個,不建議重複設定。" | |
| ) | |
| return { | |
| "text": "\n".join(lines), | |
| "selected_count": selected_count, | |
| "missing": missing, | |
| "duplicates": duplicates, | |
| "changed": changed, | |
| "names_ok": not missing, | |
| } | |
| def validate_layout_contract(layout: dict[str, Any], target_name: str) -> dict[str, Any]: | |
| placeholders = layout.get("placeholders", []) | |
| rules = PANDOC_LAYOUT_CONTRACTS.get(target_name) | |
| if rules is None: | |
| return { | |
| "status": "SKIP", | |
| "checks": [], | |
| "errors": [], | |
| "warnings": [], | |
| "found": placeholder_summary(placeholders), | |
| } | |
| checks = [] | |
| errors = [] | |
| warnings = [] | |
| for rule in rules: | |
| count = sum( | |
| item.get("type") in rule["types"] for item in placeholders | |
| ) | |
| passed = count >= rule["min"] | |
| checks.append({**rule, "count": count, "passed": passed}) | |
| if not passed: | |
| message = ( | |
| f"缺少 {rule['label']}(需要 {rule['min']} 個,目前 {count} 個)。" | |
| f"{rule['why']}" | |
| ) | |
| (errors if rule["severity"] == "error" else warnings).append(message) | |
| explicit_idxs = [item["idx"] for item in placeholders if item.get("idx") is not None] | |
| duplicate_idxs = sorted( | |
| (idx for idx, count in Counter(explicit_idxs).items() if count > 1), | |
| key=str, | |
| ) | |
| if duplicate_idxs: | |
| warnings.append( | |
| "Placeholder idx 重複:" | |
| + "、".join(map(str, duplicate_idxs)) | |
| + "。工具不會自動修改 idx;請在 PowerPoint 母片檢視中確認。" | |
| ) | |
| status = "FAIL" if errors else ("WARNING" if warnings else "PASS") | |
| return { | |
| "status": status, | |
| "checks": checks, | |
| "errors": errors, | |
| "warnings": warnings, | |
| "found": placeholder_summary(placeholders), | |
| } | |
| def validate_mapped_layouts(layouts, mapping_values) -> list[dict[str, Any]]: | |
| results = [] | |
| final_names = final_layout_names(layouts, mapping_values) | |
| for index, layout in enumerate(layouts): | |
| target = final_names[index] | |
| if target in PANDOC_LAYOUT_CONTRACTS: | |
| results.append( | |
| { | |
| "index": index, | |
| "target": target, | |
| "layout": layout, | |
| "result": validate_layout_contract(layout, target), | |
| } | |
| ) | |
| return results | |
| def row_statuses(layouts, mapping_values) -> list[str]: | |
| final_names = final_layout_names(layouts, mapping_values) | |
| statuses = [] | |
| for index, layout in enumerate(layouts): | |
| target = final_names[index] | |
| if target not in PANDOC_LAYOUT_CONTRACTS: | |
| statuses.append("不檢查") | |
| else: | |
| statuses.append(validate_layout_contract(layout, target)["status"]) | |
| return statuses | |
| def structure_report_html(layouts, mapping_values) -> tuple[str, bool, bool]: | |
| validated = validate_mapped_layouts(layouts, mapping_values) | |
| if not validated: | |
| return ( | |
| '<div class="contract-empty"><span>PANDOC PLACEHOLDER CONTRACT</span>' | |
| '<strong>沒有可檢查的 Pandoc Layout</strong>' | |
| '<p>請先把至少一個 Layout 對應到 Pandoc 標準名稱。</p></div>', | |
| False, | |
| False, | |
| ) | |
| rows = [] | |
| has_fail = False | |
| has_warning = False | |
| for item in validated: | |
| result = item["result"] | |
| has_fail |= result["status"] == "FAIL" | |
| has_warning |= result["status"] == "WARNING" | |
| badge_class = { | |
| "PASS": "contract-pass", | |
| "WARNING": "contract-warning", | |
| "FAIL": "contract-fail", | |
| }[result["status"]] | |
| checks = [] | |
| for check in result["checks"]: | |
| icon = "✓" if check["passed"] else ("✕" if check["severity"] == "error" else "!") | |
| check_class = "ok" if check["passed"] else ("bad" if check["severity"] == "error" else "warn") | |
| checks.append( | |
| f'<span class="contract-check {check_class}">{icon} ' | |
| f'{html.escape(check["label"])} {check["count"]} / {check["min"]}</span>' | |
| ) | |
| if not checks: | |
| checks.append('<span class="contract-check ok">✓ 不要求內容 Placeholder</span>') | |
| messages = result["errors"] + result["warnings"] | |
| messages_html = "" | |
| if messages: | |
| messages_html = '<ul class="contract-messages">' + "".join( | |
| f"<li>{html.escape(message)}</li>" for message in messages | |
| ) + "</ul>" | |
| layout = item["layout"] | |
| rows.append( | |
| f'''<div class="contract-row"> | |
| <div class="contract-layout"><span class="contract-index">{item["index"] + 1:02d}</span> | |
| <div><strong>{html.escape(item["target"])}</strong> | |
| <small>Master {layout["master_index"] + 1} · {html.escape(layout["name"] or "(未命名)")}</small></div></div> | |
| <div class="contract-found">{html.escape(result["found"])}</div> | |
| <div><span class="contract-badge {badge_class}">{result["status"]}</span> | |
| <div class="contract-checks">{"".join(checks)}</div>{messages_html}</div> | |
| </div>''' | |
| ) | |
| if has_fail: | |
| summary_class = "summary-fail" | |
| summary_text = "必要 Placeholder 不足;修正後才能建立 reference PPTX。" | |
| elif has_warning: | |
| summary_class = "summary-warning" | |
| summary_text = "主要結構可用,但有不阻止輸出的注意事項。" | |
| else: | |
| summary_class = "summary-pass" | |
| summary_text = "所有已對應 Layout 的 Placeholder contract 均通過。" | |
| report = f'''<div class="contract-report"> | |
| <div class="contract-summary {summary_class}"> | |
| <div><span>PANDOC PLACEHOLDER CONTRACT</span><strong>{summary_text}</strong></div> | |
| <small>共檢查 {len(validated)} 個 Pandoc Layout</small> | |
| </div> | |
| <div class="contract-head"><span>Layout</span><span>實際 Placeholder</span><span>檢查結果</span></div> | |
| {"".join(rows)} | |
| <div class="contract-footnote"><strong>Content Holder 判斷:</strong> | |
| 直接讀取 OOXML <code><p:ph></code>;沒有 <code>type</code> attribute | |
| 才視為 Pandoc 使用的 <code>object/content</code>,不依 PowerPoint shape name 判斷。</div> | |
| </div>''' | |
| return report, not has_fail, has_warning | |
| def iter_layout_objects(prs: Presentation): | |
| for master_index, master in enumerate(prs.slide_masters): | |
| for layout_index, layout in enumerate(master.slide_layouts): | |
| yield master_index, layout_index, layout | |
| def create_reference_pptx( | |
| source_path: str, | |
| layouts: list[dict[str, Any]], | |
| mapping_values: list[str], | |
| ) -> str: | |
| """Rename selected layouts and save a unique new file; never overwrite source.""" | |
| validate_pptx(source_path) | |
| if not any(value not in (None, "", "不修改") for value in mapping_values): | |
| raise TemplateError("沒有選擇任何 Mapping;請至少指定一個 Pandoc Layout。") | |
| try: | |
| presentation = Presentation(source_path) | |
| lookup = { | |
| (item["master_index"], item["layout_index"]): index | |
| for index, item in enumerate(layouts) | |
| } | |
| for master_index, layout_index, layout in iter_layout_objects(presentation): | |
| row_index = lookup.get((master_index, layout_index)) | |
| if row_index is None or row_index >= len(mapping_values): | |
| continue | |
| target_name = mapping_values[row_index] | |
| if target_name and target_name != "不修改": | |
| if target_name not in PANDOC_LAYOUTS: | |
| raise TemplateError(f"不支援的 Pandoc Layout 名稱:{target_name}") | |
| layout.name = target_name | |
| safe_stem = re.sub(r"[^A-Za-z0-9._-]+", "-", Path(source_path).stem).strip("-._") | |
| safe_stem = safe_stem or "template" | |
| output_dir = tempfile.mkdtemp(prefix="pandoc-reference-", dir="/tmp") | |
| output_path = os.path.join(output_dir, f"{safe_stem}-pandoc-reference.pptx") | |
| if os.path.realpath(output_path) == os.path.realpath(source_path): | |
| raise TemplateError("安全檢查失敗:輸出路徑不可與原始 PPTX 相同。") | |
| presentation.save(output_path) | |
| Presentation(output_path) | |
| return output_path | |
| except TemplateError: | |
| raise | |
| except Exception as error: | |
| raise TemplateError("輸出檔案建立失敗,請確認 PPTX 未損壞後再試一次。") from error | |