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(tooling): prevent silent state loss and false-success results
hugohe3627a41460d8d
diff --git a/skills/ppt-master/scripts/image_search.py b/skills/ppt-master/scripts/image_search.pyindex 0dac009f..adea9ae0 100644--- a/skills/ppt-master/scripts/image_search.py+++ b/skills/ppt-master/scripts/image_search.py@@ -280,13 +280,22 @@ def _try_provider(name: str,request: ImageSearchRequest,license_tier_filter: str,+ *,+ provider_is_explicit: bool = False,) -> tuple[Optional[list[AssetCandidate]], Optional[str]]:- """Run one provider while preserving whether it errored or returned no rows."""+ """Run one provider while preserving whether it errored or returned no rows.++ An explicitly selected provider is required; a missing key is retryable+ instead of an optional-provider skip.+ """try:module = _load_provider(name)return module.search(request, license_tier_filter=license_tier_filter), Noneexcept RuntimeError as exc:- if _is_keyed_provider_unconfigured(name, exc):+ if (+ not provider_is_explicit+ and _is_keyed_provider_unconfigured(name, exc)+ ):print(f" [{name}] skipped: {exc}",file=sys.stderr,@@ -611,6 +620,7 @@ def search_and_download(strict_no_attribution: bool,save_candidates: bool = False,max_candidates: int = 4,+ provider_is_explicit: bool = False,) -> SearchDownloadResult:"""Find a candidate AND successfully download it.@@ -621,6 +631,8 @@ def search_and_download(Returns a structured result so batch mode can keep transient/providerfailures retryable while treating a complete no-match as terminal.+ ``provider_is_explicit`` distinguishes a required provider from an optional+ member of the default fallback chain."""license_filters: list[str] = (["no-attribution-only"] if strict_no_attribution else ["all"]@@ -634,7 +646,12 @@ def search_and_download(ranked: list[tuple[float, str, AssetCandidate]] = []for provider_name in providers:print(f" -> trying {provider_name} ({stage}) ...", file=sys.stderr)- candidates, provider_error = _try_provider(provider_name, request, stage)+ candidates, provider_error = _try_provider(+ provider_name,+ request,+ stage,+ provider_is_explicit=provider_is_explicit,+ )if provider_error:provider_errors.append(provider_error)if not candidates:@@ -1469,6 +1486,7 @@ def _search_one_item(strict_no_attribution=strict,save_candidates=save_candidates,max_candidates=max_candidates,+ provider_is_explicit=bool(pinned),)if result.candidate is None:return (@@ -2044,6 +2062,7 @@ def main(argv: Optional[list[str]] = None) -> int:strict_no_attribution=args.strict_no_attribution,save_candidates=args.save_candidates,max_candidates=args.max_candidates,+ provider_is_explicit=bool(args.provider),)if result.candidate is None:diff --git a/skills/ppt-master/scripts/pptx_intake.py b/skills/ppt-master/scripts/pptx_intake.pyindex f9366be9..97abd1a5 100644--- a/skills/ppt-master/scripts/pptx_intake.py+++ b/skills/ppt-master/scripts/pptx_intake.py@@ -200,6 +200,36 @@ def build_source_profile(SOURCE_INDEX_NAME = "source_profile.json"+def _load_source_index(index_path: Path) -> dict[str, Any]:+ """Load and validate an existing multi-deck source index."""+ if not index_path.exists():+ return {}+ if not index_path.is_file():+ raise RuntimeError(f"Source index is not a file: {index_path}")++ try:+ loaded = json.loads(index_path.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, UnicodeError) as exc:+ raise RuntimeError(+ f"Source index contains invalid JSON and was left unchanged: {index_path}"+ ) from exc+ except OSError as exc:+ raise RuntimeError(f"Cannot read source index: {index_path}: {exc}") from exc++ if not isinstance(loaded, dict) or not isinstance(loaded.get("decks"), list):+ raise RuntimeError(+ f"Source index must be a JSON object with a decks array and was left unchanged: "+ f"{index_path}"+ )+ for index, deck in enumerate(loaded["decks"]):+ if not isinstance(deck, dict):+ raise RuntimeError(+ f"Source index decks[{index}] must be an object and was left unchanged: "+ f"{index_path}"+ )+ return loaded++def upsert_source_index(output_dir: Path, digest: dict[str, Any]) -> Path:"""Merge one deck's digest into the single multi-deck index `source_profile.json`.@@ -209,14 +239,7 @@ def upsert_source_index(output_dir: Path, digest: dict[str, Any]) -> Path:with the same stem replaces its entry in place."""index_path = output_dir / SOURCE_INDEX_NAME- index: dict[str, Any] = {}- if index_path.is_file():- try:- loaded = json.loads(index_path.read_text(encoding="utf-8"))- if isinstance(loaded, dict) and isinstance(loaded.get("decks"), list):- index = loaded- except (json.JSONDecodeError, OSError):- index = {}+ index = _load_source_index(index_path)stem = digest.get("stem")decks = [d for d in index.get("decks", []) if d.get("stem") != stem]decks.append(digest)diff --git a/skills/ppt-master/scripts/project_manager.py b/skills/ppt-master/scripts/project_manager.pyindex 57638a65..bd042df8 100644--- a/skills/ppt-master/scripts/project_manager.py+++ b/skills/ppt-master/scripts/project_manager.py@@ -218,6 +218,17 @@ class ProjectManager:) -> str:base_path = Path(base_dir) if base_dir else self.base_dir+ if (+ not project_name+ or project_name in {".", ".."}+ or Path(project_name).is_absolute()+ or "/" in project_name+ or "\\" in project_name+ ):+ raise ValueError(+ "Project name must be a single, non-absolute path component"+ )+normalized_format = normalize_canvas_format(canvas_format)if normalized_format not in self.CANVAS_FORMATS:available = ", ".join(sorted(self.CANVAS_FORMATS.keys()))@@ -236,6 +247,10 @@ class ProjectManager:project_dir_name = f"{project_name}_{normalized_format}_{date_str}"project_path = base_path / project_dir_name+ if not is_within_path(project_path, base_path):+ raise ValueError(+ f"Project directory must stay within the base directory: {base_path}"+ )if project_path.exists():raise FileExistsError(f"Project directory already exists: {project_path}")diff --git a/skills/ppt-master/scripts/source_to_md/web_to_md.py b/skills/ppt-master/scripts/source_to_md/web_to_md.pyindex 4dfbe9ef..b000933c 100644--- a/skills/ppt-master/scripts/source_to_md/web_to_md.py+++ b/skills/ppt-master/scripts/source_to_md/web_to_md.py@@ -912,7 +912,7 @@ def _write_emit_result(result_file: str, url: str, markdown_path: str) -> None:print(f" [WARN] Could not write --emit-result: {exc}")-def main() -> None:+def main(argv: list[str] | None = None) -> int:"""Run the CLI entry point."""parser = argparse.ArgumentParser(description="Web to Markdown Converter (Python)")@@ -926,7 +926,7 @@ def main() -> None:help="On success, write the saved output path as JSON to this file ""(single-URL dispatcher use, so a title-named file can be located)")- args = parser.parse_args()+ args = parser.parse_args(argv)if args.dir:CONFIG["output_dir"] = args.dir@@ -942,11 +942,16 @@ def main() -> None:and not l.strip().startswith("#")]targets.extend(lines)else:- print(f"Error: File {args.file} not found")+ print(f"Error: File {args.file} not found", file=sys.stderr)+ return 1if not targets:- parser.print_help()- sys.exit(0)+ parser.print_usage(sys.stderr)+ print(+ "web_to_md.py: error: at least one URL or --file is required",+ file=sys.stderr,+ )+ return 2results = []for i, url in enumerate(targets):@@ -970,10 +975,12 @@ def main() -> None:for r in results:if not r[0]:print(f" - {r[1]}: {r[2]}")+ return 1+ return 0if __name__ == "__main__":# Disable warnings for verify=False if needed, though often useful to seeimport urllib3urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)- main()+ raise SystemExit(main())diff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.pyindex eeadc3ce..71306e71 100644--- a/skills/ppt-master/scripts/svg_editor/server.py+++ b/skills/ppt-master/scripts/svg_editor/server.py@@ -597,8 +597,10 @@ def create_app(logger.warning('slide parse failed: %s: %s', svg_file.name, exc)_cache_put(_LIST_CACHE, _LIST_CACHE_LOCK, path_str, mtime, disk_count)- mem_count = len(annotations.get(svg_file.name, {}))- annotation_count = max(disk_count, mem_count)+ if svg_file.name in annotations:+ annotation_count = len(annotations[svg_file.name])+ else:+ annotation_count = disk_countslides.append({'name': svg_file.name,@@ -614,16 +616,43 @@ def create_app(def _safe_svg_path(name: str):"""Validate slide name and return safe path. Returns None if invalid.- The early string checks reject obvious bad inputs; the resolve()+startswith()+ The early string checks reject obvious bad inputs; the resolve()+relative_to()check is the authoritative path traversal guard."""if '/' in name or '\\' in name or '..' in name:return Nonesvg_file = (svg_dir / name).resolve()- if not str(svg_file).startswith(str(svg_dir.resolve())):+ try:+ svg_file.relative_to(svg_dir.resolve())+ except ValueError:return Nonereturn svg_file+ def _get_annotation_snapshot(name: str):+ """Return the page's complete staged annotation state, loading it once."""+ annotations = app.config['ANNOTATIONS']+ if name in annotations:+ return annotations[name], None++ svg_file = _safe_svg_path(name)+ if svg_file is None:+ return None, (jsonify({'error': 'Invalid slide name'}), 400)+ if not svg_file.exists():+ return None, (jsonify({'error': 'Slide not found'}), 404)++ try:+ root = ET.parse(str(svg_file)).getroot()+ except ET.ParseError as exc:+ logger.warning('slide parse failed: %s: %s', name, exc)+ return None, (jsonify({'error': f'Failed to parse SVG: {exc}'}), 500)++ assign_temp_ids(root)+ annotations[name] = {+ item['element_id']: item['annotation']+ for item in parse_annotations(root)+ }+ return annotations[name], None+@app.route('/api/slide/<name>')def get_slide(name: str):svg_file = _safe_svg_path(name)@@ -686,11 +715,13 @@ def create_app((content, warnings, disk_annotations, id_to_tag),)- mem_annotations = app.config['ANNOTATIONS'].get(name, {})- merged: dict[str, str] = {}- for ann in disk_annotations:- merged[ann['element_id']] = ann['annotation']- merged.update(mem_annotations)+ if name in app.config['ANNOTATIONS']:+ merged = dict(app.config['ANNOTATIONS'][name])+ else:+ merged = {+ ann['element_id']: ann['annotation']+ for ann in disk_annotations+ }annotations_list = [{@@ -728,29 +759,28 @@ def create_app(if len(annotation) > 10000:return jsonify({'error': 'Annotation too long (max 10000 chars)'}), 400- if name not in app.config['ANNOTATIONS']:- app.config['ANNOTATIONS'][name] = {}+ annotations, error = _get_annotation_snapshot(name)+ if error is not None:+ return error- app.config['ANNOTATIONS'][name][element_id] = annotation+ annotations[element_id] = annotationreturn jsonify({'status': 'ok',- 'annotations_count': len(app.config['ANNOTATIONS'][name]),+ 'annotations_count': len(annotations),})@app.route('/api/slide/<name>/annotate/<element_id>', methods=['DELETE'])def delete_annotate(name: str, element_id: str):- annotations = app.config['ANNOTATIONS']- # Ensure the file key exists so save-all knows to rewrite this file- # even if no new annotations were added (pure delete path).- if name not in annotations:- annotations[name] = {}- if element_id in annotations[name]:- del annotations[name][element_id]+ annotations, error = _get_annotation_snapshot(name)+ if error is not None:+ return error+ if element_id in annotations:+ del annotations[element_id]return jsonify({'status': 'ok',- 'annotations_count': len(annotations.get(name, {})),+ 'annotations_count': len(annotations),})@app.route('/api/slide/<name>/edit', methods=['POST'])@@ -896,6 +926,7 @@ def create_app(filenames = sorted(set(annotations.keys()) | set(pending_edits.keys()))for filename in filenames:+ has_staged_annotations = filename in annotationsanns = annotations.get(filename, {})edits = pending_edits.get(filename, [])# anns may be empty when the user deleted all annotations — still@@ -921,6 +952,8 @@ def create_app(item['element_id']: item['annotation']for item in parse_annotations(root)}+ if not has_staged_annotations:+ anns = old_annotations# Clear all existing annotations from the file before writing current statefor elem in root.iter():diff --git a/skills/ppt-master/scripts/update_spec.py b/skills/ppt-master/scripts/update_spec.pyindex ed3ee434..ce4c1813 100755--- a/skills/ppt-master/scripts/update_spec.py+++ b/skills/ppt-master/scripts/update_spec.py@@ -97,7 +97,10 @@ def replace_color_in_svgs("""if not HEX_RE.match(old_hex) or not HEX_RE.match(new_hex):raise ValueError(f"not a HEX color: old={old_hex!r} new={new_hex!r}")- pattern = re.compile(re.escape(old_hex), re.IGNORECASE)+ pattern = re.compile(+ rf"{re.escape(old_hex)}(?![0-9A-Fa-f])",+ re.IGNORECASE,+ )planned: list[tuple[Path, str, int]] = []for svg in sorted(svg_dir.glob("*.svg")):text = svg.read_text(encoding="utf-8")