AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He
feat(ppt): preserve DOCX office vector image metadata
hugohe319678c0b733c
diff --git a/skills/ppt-master/scripts/analyze_images.py b/skills/ppt-master/scripts/analyze_images.pyindex 87b8f4f2..40491f1c 100644--- a/skills/ppt-master/scripts/analyze_images.py+++ b/skills/ppt-master/scripts/analyze_images.py@@ -22,6 +22,7 @@ Output:"""import argparse+import jsonimport osimport sysfrom pathlib import Path@@ -63,6 +64,93 @@ MIN_TEXT_WIDTH = 280ImageAnalysis = dict[str, str | float | int]+def _load_image_manifest(images_dir: str) -> dict[str, dict]:+ """Load optional DOCX image metadata keyed by generated filename."""+ manifest_path = Path(images_dir) / "image_manifest.json"+ if not manifest_path.is_file():+ return {}+ try:+ data = json.loads(manifest_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ print(f"[WARN] Cannot read image manifest: {exc}")+ return {}+ if not isinstance(data, list):+ return {}++ manifest: dict[str, dict] = {}+ for item in data:+ if not isinstance(item, dict):+ continue+ filename = item.get("filename")+ if isinstance(filename, str):+ manifest[filename] = item+ return manifest+++def _manifest_ratio(meta: dict | None) -> float | None:+ """Return a positive display ratio from manifest metadata."""+ if not meta:+ return None+ value = meta.get("display_ratio")+ if not isinstance(value, (int, float)):+ return None+ ratio = float(value)+ return ratio if ratio > 0 else None+++def _manifest_display_size(meta: dict, ratio: float) -> tuple[int, int]:+ """Return a display-sized stand-in for vector media dimensions."""+ width_in = meta.get("display_width_in")+ height_in = meta.get("display_height_in")+ if isinstance(width_in, (int, float)) and isinstance(height_in, (int, float)):+ width = max(1, int(round(float(width_in) * 96)))+ height = max(1, int(round(float(height_in) * 96)))+ return width, height++ width_emu = meta.get("display_width_emu")+ height_emu = meta.get("display_height_emu")+ if isinstance(width_emu, int) and isinstance(height_emu, int):+ width = max(1, int(round(width_emu / 914400 * 96)))+ height = max(1, int(round(height_emu / 914400 * 96)))+ return width, height++ width = 960+ height = max(1, int(round(width / ratio)))+ return width, height+++def _result_from_manifest(+ filename: str,+ filepath: str,+ meta: dict,+) -> ImageAnalysis | None:+ """Build an analysis row for vector media Pillow cannot decode."""+ ratio = _manifest_ratio(meta)+ if ratio is None:+ return None+ width, height = _manifest_display_size(meta, ratio)+ result: ImageAnalysis = {+ 'filename': filename,+ 'width': width,+ 'height': height,+ 'aspect_ratio': ratio,+ 'pixel_aspect_ratio': meta.get('pixel_ratio') or ratio,+ 'ratio_source': 'manifest',+ 'layout_hint': classify_ratio(ratio),+ 'filesize_kb': os.path.getsize(filepath) / 1024,+ }+ source_ext = meta.get("source_ext")+ original_filename = meta.get("original_filename")+ if isinstance(source_ext, str):+ result["source_ext"] = source_ext+ if isinstance(original_filename, str):+ result["original_filename"] = original_filename+ result["asset_kind"] = meta.get("asset_kind", "bitmap")+ result["svg_renderable"] = meta.get("svg_renderable", True)+ result["pptx_native_supported"] = meta.get("pptx_native_supported", True)+ return result++def classify_ratio(aspect_ratio: float) -> str:"""Classify image aspect ratio into layout category.@@ -164,29 +252,62 @@ def analyze_images(images_dir: str) -> list[ImageAnalysis]:"""results: list[ImageAnalysis] = []+ manifest = _load_image_manifest(images_dir)+ seen_filenames: set[str] = set()# Iterate through all files in the directoryfor filename in sorted(os.listdir(images_dir)):filepath = os.path.join(images_dir, filename)+ meta = manifest.get(filename)# Check if it is an image fileif os.path.isfile(filepath) and Path(filename).suffix.lower() in IMAGE_EXTENSIONS:try:with Image.open(filepath) as img:width, height = img.size- aspect_ratio = width / height+ pixel_ratio = width / height+ aspect_ratio = _manifest_ratio(meta) or pixel_ratiolayout_hint = classify_ratio(aspect_ratio)- results.append({+ result: ImageAnalysis = {'filename': filename,'width': width,'height': height,'aspect_ratio': aspect_ratio,+ 'pixel_aspect_ratio': pixel_ratio,+ 'ratio_source': 'manifest' if meta else 'pixel','layout_hint': layout_hint,'filesize_kb': os.path.getsize(filepath) / 1024- })+ }+ if meta:+ source_ext = meta.get("source_ext")+ original_filename = meta.get("original_filename")+ if isinstance(source_ext, str):+ result["source_ext"] = source_ext+ if isinstance(original_filename, str):+ result["original_filename"] = original_filename+ result["asset_kind"] = meta.get("asset_kind", "bitmap")+ result["svg_renderable"] = meta.get("svg_renderable", True)+ result["pptx_native_supported"] = meta.get("pptx_native_supported", True)+ results.append(result)+ seen_filenames.add(filename)except Exception as e:print(f"[WARN] Cannot read {filename}: {e}")+ elif os.path.isfile(filepath) and meta:+ result = _result_from_manifest(filename, filepath, meta)+ if result:+ results.append(result)+ seen_filenames.add(filename)++ for filename, meta in sorted(manifest.items()):+ if filename in seen_filenames:+ continue+ filepath = os.path.join(images_dir, filename)+ if not os.path.isfile(filepath):+ continue+ result = _result_from_manifest(filename, filepath, meta)+ if result:+ results.append(result)return results@@ -224,13 +345,14 @@ def print_results(results: list[ImageAnalysis]) -> None:print("\nNote: 'Img (SxS)' shows the image area *if* the Strategist chooses the")print("side-by-side intent for this image. Decide narrative intent first — see")print("references/strategist.md §h. Hero / atmosphere / accent intents ignore it.\n")- print(f"{'No.':<4} {'Width':<7} {'Height':<7} {'Ratio':<7} {'Size':<10} {'Category':<20} {'Img (SxS)':<14} {'Filename'}")+ print(f"{'No.':<4} {'Width':<7} {'Height':<7} {'Ratio':<7} {'Source':<8} {'Size':<10} {'Category':<20} {'Img (SxS)':<14} {'Filename'}")else:- print(f"\n{'No.':<4} {'Width':<7} {'Height':<7} {'Ratio':<7} {'Size':<10} {'Category':<20} {'Filename'}")+ print(f"\n{'No.':<4} {'Width':<7} {'Height':<7} {'Ratio':<7} {'Source':<8} {'Size':<10} {'Category':<20} {'Filename'}")print("-" * REPORT_WIDTH)for i, img in enumerate(results, 1):- base = f"{i:<4} {img['width']:<7} {img['height']:<7} {img['aspect_ratio']:<7.2f} {img['filesize_kb']:<10.1f}KB {img['layout_hint']:<20}"+ ratio_source = str(img.get('ratio_source', 'pixel'))+ base = f"{i:<4} {img['width']:<7} {img['height']:<7} {img['aspect_ratio']:<7.2f} {ratio_source:<8} {img['filesize_kb']:<10.1f}KB {img['layout_hint']:<20}"if has_layout:img_area = f"{img['image_w']}x{img['image_h']}"print(f"{base} {img_area:<14} {img['filename'][:35]}")@@ -273,6 +395,19 @@ def print_results(results: list[ImageAnalysis]) -> None:if len(imgs) > 5:print(f" ... and {len(imgs) - 5} more")+ native_only = [+ img for img in results+ if img.get('asset_kind') == 'office_vector'+ and not img.get('svg_renderable', True)+ ]+ if native_only:+ print("\nOffice vector assets for PPTX native passthrough:")+ for img in native_only[:10]:+ original = img.get('original_filename', img['filename'])+ print(f" - {original} (display ratio {img['aspect_ratio']:.2f}; SVG preview not supported)")+ if len(native_only) > 10:+ print(f" ... and {len(native_only) - 10} more")+def generate_markdown(results: list[ImageAnalysis], canvas_key: str) -> None:"""Print a Markdown-ready image inventory section."""@@ -299,13 +434,20 @@ def generate_markdown(results: list[ImageAnalysis], canvas_key: str) -> None:for img in results:ratio_str = f"{img['aspect_ratio']:.2f}"+ asset_kind = str(img.get('asset_kind', 'bitmap'))+ image_type = "Office Vector" if asset_kind == "office_vector" else ""+ status = (+ "PPTX Native Only"+ if asset_kind == "office_vector" and not img.get('svg_renderable', True)+ else "Existing"+ )if has_layout:img_area = f"{img['image_w']}x{img['image_h']}"text_area = f"{img['text_w']}x{img['text_h']}"- print(f"| {img['filename']} | {img['width']}x{img['height']} | {ratio_str} | {img['layout_hint']} | {img_area} | {text_area} | (to be filled) | (to be filled) | | Existing | - |")+ print(f"| {img['filename']} | {img['width']}x{img['height']} | {ratio_str} | {img['layout_hint']} | {img_area} | {text_area} | (to be filled) | (to be filled) | {image_type} | {status} | - |")else:- print(f"| {img['filename']} | {img['width']}x{img['height']} | {ratio_str} | {img['layout_hint']} | (to be filled) | (to be filled) | | Existing | - |")+ print(f"| {img['filename']} | {img['width']}x{img['height']} | {ratio_str} | {img['layout_hint']} | (to be filled) | (to be filled) | {image_type} | {status} | - |")print("\n" + "=" * REPORT_WIDTH + "\n")@@ -319,13 +461,13 @@ def save_csv(results: list[ImageAnalysis], csv_path: str) -> None:# does not prescribe a layout.with open(csv_path, 'w', encoding='utf-8') as f:if has_layout:- f.write("No,Filename,Width,Height,AspectRatio,SizeKB,Category,ImageArea_SxS,TextArea_SxS\n")+ f.write("No,Filename,Width,Height,AspectRatio,PixelAspectRatio,RatioSource,AssetKind,SvgRenderable,PptxNativeSupported,SizeKB,Category,ImageArea_SxS,TextArea_SxS\n")for i, img in enumerate(results, 1):- f.write(f"{i},{img['filename']},{img['width']},{img['height']},{img['aspect_ratio']:.2f},{img['filesize_kb']:.1f},{img['layout_hint']},{img['image_w']}x{img['image_h']},{img['text_w']}x{img['text_h']}\n")+ f.write(f"{i},{img['filename']},{img['width']},{img['height']},{img['aspect_ratio']:.2f},{img.get('pixel_aspect_ratio', img['aspect_ratio']):.2f},{img.get('ratio_source', 'pixel')},{img.get('asset_kind', 'bitmap')},{img.get('svg_renderable', True)},{img.get('pptx_native_supported', True)},{img['filesize_kb']:.1f},{img['layout_hint']},{img['image_w']}x{img['image_h']},{img['text_w']}x{img['text_h']}\n")else:- f.write("No,Filename,Width,Height,AspectRatio,SizeKB,Category\n")+ f.write("No,Filename,Width,Height,AspectRatio,PixelAspectRatio,RatioSource,AssetKind,SvgRenderable,PptxNativeSupported,SizeKB,Category\n")for i, img in enumerate(results, 1):- f.write(f"{i},{img['filename']},{img['width']},{img['height']},{img['aspect_ratio']:.2f},{img['filesize_kb']:.1f},{img['layout_hint']}\n")+ f.write(f"{i},{img['filename']},{img['width']},{img['height']},{img['aspect_ratio']:.2f},{img.get('pixel_aspect_ratio', img['aspect_ratio']):.2f},{img.get('ratio_source', 'pixel')},{img.get('asset_kind', 'bitmap')},{img.get('svg_renderable', True)},{img.get('pptx_native_supported', True)},{img['filesize_kb']:.1f},{img['layout_hint']}\n")print(f"\nCSV saved to: {csv_path}")diff --git a/skills/ppt-master/scripts/finalize_svg.py b/skills/ppt-master/scripts/finalize_svg.pyindex 3417f1b9..2b683225 100644--- a/skills/ppt-master/scripts/finalize_svg.py+++ b/skills/ppt-master/scripts/finalize_svg.py@@ -41,7 +41,10 @@ from pathlib import Path# Import finalize helpers from the internal package.sys.path.insert(0, str(Path(__file__).parent))-from svg_finalize.align_embed_images import align_and_embed_images_in_svg+from svg_finalize.align_embed_images import (+ align_and_embed_images_in_svg,+ count_office_vector_refs_in_svg,+)from svg_finalize.embed_icons import process_svg_file as embed_icons_in_file@@ -182,7 +185,9 @@ def finalize_project(safe_print("[2/4] Aligning + embedding images...")img_count = 0img_errors = 0+ office_vector_count = 0for svg_file in svg_final.glob('*.svg'):+ office_vector_count += count_office_vector_refs_in_svg(svg_file)count, errs = align_and_embed_images_in_svg(svg_file,dry_run=False,@@ -198,6 +203,16 @@ def finalize_project(if img_errors:msg += f" ({img_errors} error(s))"safe_print(msg)+ if office_vector_count:+ safe_print(+ f" {office_vector_count} Office vector(s) left external "+ "for native PPTX passthrough"+ )+ elif office_vector_count:+ safe_print(+ f" {office_vector_count} Office vector(s) left external "+ "for native PPTX passthrough"+ )else:safe_print(" No images")diff --git a/skills/ppt-master/scripts/source_to_md/doc_to_md.py b/skills/ppt-master/scripts/source_to_md/doc_to_md.pyindex 8236a976..7bb655e3 100644--- a/skills/ppt-master/scripts/source_to_md/doc_to_md.py+++ b/skills/ppt-master/scripts/source_to_md/doc_to_md.py@@ -18,13 +18,18 @@ All paths produce the same output convention:import argparseimport base64+import hashlib+import jsonimport mimetypes+import posixpathimport reimport shutilimport subprocessimport sys+import zipfilefrom pathlib import Pathfrom urllib.parse import unquote, urlparse+from xml.etree import ElementTree as ET# ─────────────────────────────────────────────────────────────# Format registry@@ -47,6 +52,19 @@ PANDOC_FORMATS = {# Formats pandoc should extract embedded media fromPANDOC_MEDIA_FORMATS = {".odt"}+OFFICE_VECTOR_EXTENSIONS = {".emf", ".wmf"}++DOCX_NS = {+ "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",+ "wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",+ "rel": "http://schemas.openxmlformats.org/package/2006/relationships",+ "v": "urn:schemas-microsoft-com:vml",+ "o": "urn:schemas-microsoft-com:office:office",+ "mc": "http://schemas.openxmlformats.org/markup-compatibility/2006",+}+EMU_PER_INCH = 914400# ─────────────────────────────────────────────────────────────@@ -100,6 +118,265 @@ def _report_result(out_file: Path, media_dir: Path | None) -> None:print(f" Extracted {len(files)} media file(s) → {media_dir}")+def _normalize_ext(ext: str | None) -> str:+ """Return a normalized image extension, including the leading dot."""+ if not ext:+ return ".bin"+ ext = ext.lower()+ if not ext.startswith("."):+ ext = f".{ext}"+ if ext == ".jpe":+ return ".jpg"+ return ext+++def _image_size(path: Path) -> tuple[int | None, int | None]:+ """Return bitmap dimensions when Pillow can read the file."""+ try:+ from PIL import Image+ except ImportError:+ return None, None+ try:+ with Image.open(path) as img:+ return img.width, img.height+ except (OSError, ValueError):+ return None, None+++def _is_office_vector(ext: str) -> bool:+ """Return whether an extension is an Office vector preview format."""+ return ext.lower() in OFFICE_VECTOR_EXTENSIONS+++def _local_name(elem: ET.Element) -> str:+ """Return an XML element local name without its namespace."""+ return elem.tag.rsplit("}", 1)[-1]+++def _relationship_target_path(target: str) -> str:+ """Normalize a Word relationship target to a DOCX zip path."""+ target = unquote(target)+ if target.startswith("/"):+ normalized = posixpath.normpath(target.lstrip("/"))+ else:+ normalized = posixpath.normpath(posixpath.join("word", target))+ return normalized+++def _zip_sha256_for_target(media_hashes: dict[str, str], target: str) -> str | None:+ """Return the SHA-256 digest for an embedded DOCX part target."""+ if not target:+ return None+ return media_hashes.get(_relationship_target_path(target))+++def _length_to_emu(value: str) -> int | None:+ """Parse a VML CSS length into EMU."""+ match = re.match(r"^\s*([\d.]+)\s*([a-zA-Z]*)\s*$", value)+ if not match:+ return None+ number = float(match.group(1))+ unit = (match.group(2) or "pt").lower()+ factors = {+ "in": EMU_PER_INCH,+ "cm": EMU_PER_INCH / 2.54,+ "mm": EMU_PER_INCH / 25.4,+ "pt": EMU_PER_INCH / 72,+ "px": EMU_PER_INCH / 96,+ }+ factor = factors.get(unit)+ if factor is None:+ return None+ return int(round(number * factor))+++def _vml_display_size_emu(shape: ET.Element | None) -> tuple[int, int]:+ """Read VML shape width/height from its style attribute."""+ if shape is None:+ return 0, 0+ style = shape.attrib.get("style", "")+ values: dict[str, str] = {}+ for part in style.split(";"):+ if ":" not in part:+ continue+ key, value = part.split(":", 1)+ values[key.strip().lower()] = value.strip()+ width = _length_to_emu(values.get("width", "")) or 0+ height = _length_to_emu(values.get("height", "")) or 0+ return width, height+++def _occurrence_entry(+ *,+ rel_id: str | None,+ target: str,+ width_emu: int,+ height_emu: int,+ source_sha256: str | None,+ source_kind: str,+) -> dict[str, object]:+ """Build one image metadata occurrence row."""+ display_ratio = (+ width_emu / height_emu+ if width_emu > 0 and height_emu > 0+ else None+ )+ return {+ "relationship_id": rel_id,+ "source_target": target,+ "source_path": _relationship_target_path(target) if target else "",+ "source_ext": _normalize_ext(Path(target).suffix),+ "source_sha256": source_sha256,+ "source_kind": source_kind,+ "display_width_emu": width_emu,+ "display_height_emu": height_emu,+ "display_width_in": round(width_emu / EMU_PER_INCH, 4) if width_emu else None,+ "display_height_in": round(height_emu / EMU_PER_INCH, 4) if height_emu else None,+ "display_ratio": round(display_ratio, 6) if display_ratio else None,+ }+++def _docx_image_occurrences(input_file: Path) -> list[dict[str, object]]:+ """Read DOCX drawing order and Word display dimensions."""+ try:+ with zipfile.ZipFile(input_file) as docx:+ rels_root = ET.fromstring(docx.read("word/_rels/document.xml.rels"))+ doc_root = ET.fromstring(docx.read("word/document.xml"))+ media_hashes = {+ name: hashlib.sha256(docx.read(name)).hexdigest()+ for name in docx.namelist()+ if name.startswith("word/media/")+ }+ except (KeyError, ET.ParseError, zipfile.BadZipFile, OSError):+ return []++ rels: dict[str, str] = {}+ for rel in rels_root.findall("rel:Relationship", DOCX_NS):+ rel_id = rel.attrib.get("Id")+ target = rel.attrib.get("Target")+ if rel_id and target:+ rels[rel_id] = target++ parent_map = {child: parent for parent in doc_root.iter() for child in parent}++ def _inside_mc_choice(elem: ET.Element) -> bool:+ parent = parent_map.get(elem)+ while parent is not None:+ if _local_name(parent) == "Choice":+ return True+ parent = parent_map.get(parent)+ return False++ occurrences: list[dict[str, object]] = []+ for elem in doc_root.iter():+ if _inside_mc_choice(elem):+ continue+ local = _local_name(elem)+ if local == "drawing":+ container = elem.find(".//wp:inline", DOCX_NS)+ if container is None:+ container = elem.find(".//wp:anchor", DOCX_NS)+ if container is None:+ continue+ extent = container.find("wp:extent", DOCX_NS)+ blip = container.find(".//a:blip", DOCX_NS)+ if extent is None or blip is None:+ continue++ rel_id = blip.attrib.get(f"{{{DOCX_NS['r']}}}embed")+ if not rel_id:+ rel_id = blip.attrib.get(f"{{{DOCX_NS['r']}}}link")+ target = rels.get(rel_id or "", "")+ if not target:+ continue++ try:+ width_emu = int(extent.attrib.get("cx", "0"))+ height_emu = int(extent.attrib.get("cy", "0"))+ except ValueError:+ width_emu = 0+ height_emu = 0++ occurrences.append(_occurrence_entry(+ rel_id=rel_id,+ target=target,+ width_emu=width_emu,+ height_emu=height_emu,+ source_sha256=_zip_sha256_for_target(media_hashes, target),+ source_kind="drawing",+ ))+ elif local == "imagedata":+ rel_id = elem.attrib.get(f"{{{DOCX_NS['r']}}}id")+ if not rel_id:+ rel_id = elem.attrib.get(f"{{{DOCX_NS['r']}}}pict")+ target = rels.get(rel_id or "", "")+ if not target:+ continue+ width_emu, height_emu = _vml_display_size_emu(parent_map.get(elem))+ occurrences.append(_occurrence_entry(+ rel_id=rel_id,+ target=target,+ width_emu=width_emu,+ height_emu=height_emu,+ source_sha256=_zip_sha256_for_target(media_hashes, target),+ source_kind="vml",+ ))+ return occurrences+++def _match_occurrence(+ occurrences: list[dict[str, object]],+ used_indexes: set[int],+ index: int,+ image_bytes: bytes,+) -> dict[str, object] | None:+ """Match a Mammoth image callback to DOCX metadata."""+ image_hash = hashlib.sha256(image_bytes).hexdigest()+ for occurrence_index, occurrence in enumerate(occurrences):+ if occurrence_index in used_indexes:+ continue+ if occurrence.get("source_sha256") == image_hash:+ used_indexes.add(occurrence_index)+ return occurrence++ fallback_index = index - 1+ if fallback_index < len(occurrences) and fallback_index not in used_indexes:+ used_indexes.add(fallback_index)+ return occurrences[fallback_index]+ return None+++def _manifest_entry(+ index: int,+ filename: str,+ meta: dict[str, object] | None,+ file_path: Path,+ *,+ original_filename: str | None = None,+ asset_kind: str = "bitmap",+ svg_renderable: bool = True,+ pptx_native_supported: bool = True,+) -> dict[str, object]:+ width, height = _image_size(file_path)+ pixel_ratio = width / height if width and height else None+ entry: dict[str, object] = {+ "index": index,+ "filename": filename,+ "original_filename": original_filename or filename,+ "asset_kind": asset_kind,+ "svg_renderable": svg_renderable,+ "pptx_native_supported": pptx_native_supported,+ "pixel_width": width,+ "pixel_height": height,+ "pixel_ratio": round(pixel_ratio, 6) if pixel_ratio else None,+ }+ if meta:+ entry.update(meta)+ if entry.get("display_ratio") is None and pixel_ratio:+ entry["display_ratio"] = round(pixel_ratio, 6)+ return entry++# ─────────────────────────────────────────────────────────────# DOCX → Markdown (mammoth)# ─────────────────────────────────────────────────────────────@@ -113,16 +390,47 @@ def _convert_docx(input_file: Path, out_file: Path) -> str:media_dir, rel_media_dir = _ensure_media_dir(out_file)counter = {"n": 0}+ occurrences = _docx_image_occurrences(input_file)+ used_occurrence_indexes: set[int] = set()+ manifest: list[dict[str, object]] = []def _save_image(image):counter["n"] += 1- ext = mimetypes.guess_extension(image.content_type) or ".bin"- # Normalize common JPEG extension- if ext == ".jpe":- ext = ".jpg"- filename = f"image_{counter['n']:03d}{ext}"+ index = counter["n"]with image.open() as stream:- (media_dir / filename).write_bytes(stream.read())+ image_bytes = stream.read()++ meta = _match_occurrence(+ occurrences,+ used_occurrence_indexes,+ index,+ image_bytes,+ )+ source_ext = meta.get("source_ext") if meta else None+ ext = _normalize_ext(source_ext if isinstance(source_ext, str) else None)+ if ext == ".bin":+ ext = _normalize_ext(mimetypes.guess_extension(image.content_type))++ original_filename = f"image_{index:03d}{ext}"+ original_path = media_dir / original_filename+ original_path.write_bytes(image_bytes)++ filename = original_filename+ output_path = original_path+ asset_kind = "office_vector" if _is_office_vector(ext) else "bitmap"+ svg_renderable = asset_kind != "office_vector"+ pptx_native_supported = True++ manifest.append(_manifest_entry(+ index,+ filename,+ meta,+ output_path,+ original_filename=original_filename,+ asset_kind=asset_kind,+ svg_renderable=svg_renderable,+ pptx_native_supported=pptx_native_supported,+ ))return {"src": f"{rel_media_dir}/{filename}"}with input_file.open("rb") as f:@@ -134,6 +442,12 @@ def _convert_docx(input_file: Path, out_file: Path) -> str:markdown = _html_img_to_md(result.value)out_file.write_text(markdown, encoding="utf-8")+ if manifest:+ (media_dir / "image_manifest.json").write_text(+ json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",+ encoding="utf-8",+ )+if not any(media_dir.iterdir()):media_dir.rmdir()media_dir = None # type: ignore[assignment]diff --git a/skills/ppt-master/scripts/svg_finalize/align_embed_images.py b/skills/ppt-master/scripts/svg_finalize/align_embed_images.pyindex 641b4264..be007abc 100644--- a/skills/ppt-master/scripts/svg_finalize/align_embed_images.py+++ b/skills/ppt-master/scripts/svg_finalize/align_embed_images.py@@ -30,6 +30,7 @@ The merged pipeline:for image in svg:if href starts with data: → skip (already inline)if href is unresolvable / external URL → skip+ if href points to EMF/WMF → skip (native PPTX passthrough only)if missing preserveAspectRatio → just embed (do not assume meet)if align == none → just embed (no spatial transform)if mode == slice → crop in memory, embed cropped bytes@@ -73,6 +74,7 @@ _PIL_FORMAT_BY_MIME = {'image/gif': 'GIF','image/webp': 'WEBP',}+_OFFICE_VECTOR_EXTENSIONS = {'.emf', '.wmf'}def _parse_float(val: str | None, default: float = 0.0) -> float:@@ -245,6 +247,11 @@ def _process_one_image(except OSError as exc:return False, f'read failed: {exc}'+ if img_path.suffix.lower() in _OFFICE_VECTOR_EXTENSIONS:+ if verbose:+ print(f' [INFO] {img_path.name}: Office vector left external for native PPTX passthrough')+ return False, None+img = _load_pil_image(img_path)if img is None:return False, 'PIL open failed'@@ -320,6 +327,30 @@ def _process_one_image(return True, None+def count_office_vector_refs_in_svg(svg_path: str | Path) -> int:+ """Count local EMF/WMF image refs that the embed pass intentionally skips."""+ svg_path = Path(svg_path)+ svg_dir = svg_path.parent.resolve()+ try:+ tree = ET.parse(svg_path)+ except ET.ParseError:+ return 0+ count = 0+ seen: set[int] = set()+ for image in _iter_image_elements(tree.getroot()):+ ident = id(image)+ if ident in seen:+ continue+ seen.add(ident)+ href = _get_href(image)+ if not href or href.startswith('data:'):+ continue+ img_path = _resolve_image_path(href, svg_dir)+ if img_path and img_path.suffix.lower() in _OFFICE_VECTOR_EXTENSIONS:+ count += 1+ return count++def align_and_embed_images_in_svg(svg_path: str | Path,*,diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.pyindex 2621ae99..313b5182 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py@@ -99,8 +99,10 @@ _IMAGE_CONTENT_TYPES = {'webp': 'image/webp','svg': 'image/svg+xml','bmp': 'image/bmp',+ 'emf': 'image/x-emf','tif': 'image/tiff','tiff': 'image/tiff',+ 'wmf': 'image/x-wmf',}