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
fix(doc): handle broken EPUB manifests
hugohe3e2109bdbf31b
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 7bb655e3..36c9c356 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@@ -26,6 +26,7 @@ import reimport shutilimport subprocessimport sys+import tempfileimport zipfilefrom pathlib import Pathfrom urllib.parse import unquote, urlparse@@ -586,6 +587,129 @@ def _convert_html(input_file: Path, out_file: Path) -> str:# EPUB → Markdown (ebooklib + markdownify)# ─────────────────────────────────────────────────────────────+def _sanitize_epub_manifest(src: Path) -> tuple[Path, bool]:+ """Return an EPUB path that ebooklib can read.++ Some EPUBs contain OPF manifest entries pointing at files that are missing+ from the ZIP archive. ebooklib reads every manifest item eagerly, so one+ stale entry can abort the whole conversion. When broken entries are found,+ this writes a temporary EPUB with those manifest items and matching spine+ refs removed.+ """+ OPF_NS = "http://www.idpf.org/2007/opf"+ CONT_NS = "urn:oasis:names:tc:opendocument:xmlns:container"++ try:+ with zipfile.ZipFile(src, "r") as zin:+ names = set(zin.namelist())+ if "META-INF/container.xml" not in names:+ return src, False++ container_root = ET.fromstring(zin.read("META-INF/container.xml"))+ rootfile_el = container_root.find(f".//{{{CONT_NS}}}rootfile")+ if rootfile_el is None:+ return src, False++ opf_path = rootfile_el.get("full-path")+ if not opf_path or opf_path not in names:+ return src, False++ opf_root = ET.fromstring(zin.read(opf_path))+ manifest_el = opf_root.find(f"{{{OPF_NS}}}manifest")+ if manifest_el is None:+ return src, False++ opf_dir = posixpath.dirname(opf_path)+ bad_ids: list[str] = []+ bad_hrefs: list[str] = []+ for item_el in list(manifest_el.findall(f"{{{OPF_NS}}}item")):+ href = item_el.get("href", "")+ if not href:+ continue+ rel = unquote(href)+ zpath = posixpath.normpath(+ posixpath.join(opf_dir, rel) if opf_dir else rel+ )+ if zpath in names:+ continue++ item_id = item_el.get("id", "")+ if item_id:+ bad_ids.append(item_id)+ bad_hrefs.append(href)+ manifest_el.remove(item_el)++ if not bad_hrefs:+ return src, False++ spine_el = opf_root.find(f"{{{OPF_NS}}}spine")+ if spine_el is not None and bad_ids:+ for itemref in list(spine_el.findall(f"{{{OPF_NS}}}itemref")):+ if itemref.get("idref") in bad_ids:+ spine_el.remove(itemref)++ ET.register_namespace("", OPF_NS)+ ET.register_namespace("dc", "http://purl.org/dc/elements/1.1/")+ new_opf = ET.tostring(opf_root, encoding="utf-8", xml_declaration=True)++ tmp = tempfile.NamedTemporaryFile(suffix=".epub", delete=False)+ tmp.close()+ out_path = Path(tmp.name)++ with zipfile.ZipFile(out_path, "w", zipfile.ZIP_DEFLATED) as zout:+ if "mimetype" in names:+ zout.writestr(+ zipfile.ZipInfo("mimetype"),+ zin.read("mimetype"),+ compress_type=zipfile.ZIP_STORED,+ )+ for name in zin.namelist():+ if name == "mimetype":+ continue+ if name == opf_path:+ zout.writestr(name, new_opf)+ else:+ zout.writestr(name, zin.read(name))++ preview = ", ".join(bad_hrefs[:3])+ if len(bad_hrefs) > 3:+ preview += " ..."+ print(+ f"[INFO] EPUB manifest sanitized: removed "+ f"{len(bad_hrefs)} broken item(s) [{preview}]"+ )+ return out_path, True+ except (zipfile.BadZipFile, ET.ParseError, OSError) as exc:+ print(+ f"[WARN] EPUB sanitize skipped "+ f"({exc.__class__.__name__}: {exc}); using original file"+ )+ return src, False+++def _epub_image_candidates(src: str, document_name: str) -> list[str]:+ """Build lookup candidates for an image reference inside an EPUB document."""+ parsed = urlparse(src)+ raw_path = parsed.path if parsed.scheme else src+ decoded_path = unquote(raw_path)+ normalized_path = posixpath.normpath(decoded_path).lstrip("/")+ document_dir = posixpath.dirname(document_name)+ relative_path = posixpath.normpath(+ posixpath.join(document_dir, decoded_path)+ ).lstrip("/")++ candidates = [+ src,+ raw_path,+ decoded_path,+ normalized_path,+ relative_path,+ Path(decoded_path).name,+ Path(normalized_path).name,+ ]+ return [candidate for candidate in dict.fromkeys(candidates) if candidate]++def _convert_epub(input_file: Path, out_file: Path) -> str:try:import ebooklib@@ -598,7 +722,15 @@ def _convert_epub(input_file: Path, out_file: Path) -> str:return ""media_dir, rel_media_dir = _ensure_media_dir(out_file)- book = epub.read_epub(str(input_file))+ sanitized_path, is_temp_copy = _sanitize_epub_manifest(input_file)+ try:+ book = epub.read_epub(str(sanitized_path))+ finally:+ if is_temp_copy:+ try:+ sanitized_path.unlink()+ except OSError:+ pass# Extract images, remembering original path → new filename mappingimg_map: dict[str, str] = {}@@ -625,8 +757,8 @@ def _convert_epub(input_file: Path, out_file: Path) -> str:src = img.get("src", "")if not src:continue- # Try exact match, then basename, then normalized path- candidates = [src, Path(src).name, unquote(src), Path(unquote(src)).name]+ # Try exact match, basename, decoded path, and path relative to this XHTML file.+ candidates = _epub_image_candidates(src, item.file_name)resolved = next((img_map[c] for c in candidates if c in img_map), None)if resolved:img["src"] = f"{rel_media_dir}/{resolved}"