Skip to content

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

refactor(source-to-md): unify conversion behind one dispatcher + audit profiles

hugohe3436fd0a518a1
diff --git a/AGENTS.md b/AGENTS.md
index 67d1abec..db558f38 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -43,11 +43,7 @@ Convenience summary only — full workflow in [`skills/ppt-master/SKILL.md`](ski
```bash
# Source content conversion
-python3 skills/ppt-master/scripts/source_to_md/pdf_to_md.py <PDF_file>
-python3 skills/ppt-master/scripts/source_to_md/doc_to_md.py <DOCX_or_other_file>
-python3 skills/ppt-master/scripts/source_to_md/excel_to_md.py <XLSX_or_XLSM_file>
-python3 skills/ppt-master/scripts/source_to_md/ppt_to_md.py <PPTX_file>
-python3 skills/ppt-master/scripts/source_to_md/web_to_md.py <URL>
+python3 skills/ppt-master/scripts/source_to_md.py <file_or_URL> [<file_or_URL> ...]
# Project management
python3 skills/ppt-master/scripts/project_manager.py init <project_name> --format ppt169
@@ -62,6 +58,10 @@ python3 skills/ppt-master/scripts/confirm_ui/server.py <project_path> --daemon -
# Image tools and SVG quality check
python3 skills/ppt-master/scripts/analyze_images.py <project_path>/images
+# Formula rendering — manifest written by Strategist after typography confirmation:
+python3 skills/ppt-master/scripts/latex_render.py <project_path>
+python3 skills/ppt-master/scripts/latex_render.py <project_path> --dry-run
+python3 skills/ppt-master/scripts/latex_render.py <project_path> --providers codecogs,quicklatex,mathpad,wikimedia
# In-pipeline AI image generation — manifest mode (required, even for 1 image):
python3 skills/ppt-master/scripts/image_gen.py --manifest <project_path>/images/image_prompts.json
python3 skills/ppt-master/scripts/image_gen.py --render-md <project_path>/images/image_prompts.json
diff --git a/CLAUDE.md b/CLAUDE.md
index 43cd3b8e..b33287fe 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,99 +1,5 @@
# CLAUDE.md
-This file is the project entry point for Claude Code.
+Claude Code entry point. To avoid maintaining two copies, all project instructions live in a single source of truth — **[AGENTS.md](AGENTS.md)** — imported below (Claude Code inlines `@`-referenced files into context). Always edit `AGENTS.md`; never duplicate its content here.
-**You MUST read [`skills/ppt-master/SKILL.md`](skills/ppt-master/SKILL.md) before any PPT generation task or repo modification.** This repository exists to generate presentations; SKILL.md is the authoritative workflow that owns project creation, role switching, serial execution, quality gates, post-processing, export, and every per-step command. The rest of this file only points to where related material lives — it never substitutes for SKILL.md.
-
-## Project Overview
-
-PPT Master is an AI-driven presentation generation system. Multi-role collaboration (Strategist → Image_Generator → Executor) converts source documents (PDF/DOCX/URL/Markdown) into natively editable PPTX with real PowerPoint shapes (DrawingML).
-
-**Core Pipeline**: `Source Document → Create Project → [Template] → Strategist Eight Confirmations → [Image_Generator] → Executor Live Preview → Quality Check → Post-processing → Export PPTX`
-
-**Route selection authority**: [`skills/ppt-master/workflows/routing.md`](skills/ppt-master/workflows/routing.md) owns the complete route matrix. The hard boundaries below stay inline because they bypass or redirect the main pipeline and are the most expensive to misroute.
-
-- Topic-only requests run [`topic-research`](skills/ppt-master/workflows/topic-research.md) before SKILL.md Step 1.
-- Raw PPTX template plus new material/topic routes to [`template-fill-pptx`](skills/ppt-master/workflows/template-fill-pptx.md), not the SVG pipeline.
-- Raw PPTX cannot be consumed as a Step 3 SVG template; run [`create-template`](skills/ppt-master/workflows/create-template.md) first and return with the generated template directory path.
-- PPTX beautify is strictly 1:1 page count/order and verbatim wording via [`beautify-pptx`](skills/ppt-master/workflows/beautify-pptx.md); any split/merge/drop/reorder routes to the main pipeline.
-- Finished PPTX native enhancement uses [`native-enhance-pptx`](skills/ppt-master/workflows/native-enhance-pptx.md) and must not enter SVG regeneration.
-- [`visual-review`](skills/ppt-master/workflows/visual-review.md), [`customize-animations`](skills/ppt-master/workflows/customize-animations.md), and [`generate-audio`](skills/ppt-master/workflows/generate-audio.md) are explicit-request workflows.
-
-## Execution Requirements
-
-- For standalone template creation (no source deck), read [`skills/ppt-master/workflows/create-template.md`](skills/ppt-master/workflows/create-template.md).
-- Technical SVG/PPT constraints live in [`skills/ppt-master/references/shared-standards.md`](skills/ppt-master/references/shared-standards.md).
-- Canvas choices live in [`skills/ppt-master/references/canvas-formats.md`](skills/ppt-master/references/canvas-formats.md).
-- Icon library details live in [`skills/ppt-master/templates/icons/README.md`](skills/ppt-master/templates/icons/README.md).
-
-## Required Conventions
-
-- **Repo-wide style rules** — when editing prompt files under [`skills/ppt-master/references/`](skills/ppt-master/references/), Python under [`skills/ppt-master/scripts/`](skills/ppt-master/scripts/), or any other code/prose in the repo, follow the matching style rule in [`docs/rules/`](docs/rules/).
-- **Markdown language consistency** — Markdown files under `skills/ppt-master/workflows/`, `skills/ppt-master/references/`, and `docs/` are currently single-language per directory. New files mirror the language of their siblings; do not mix English scaffolding with Chinese paragraphs (or vice versa) inside one file. Chat replies are unaffected.
-
-## Compatibility Boundary
-
-- This repository is a workflow/skill package, not an app or service scaffold.
-- Do NOT assume generic-project conventions like `.worktrees/`, `tests/`, or mandatory branch setup unless the user explicitly requests them.
-- On conflict with a generic coding skill, prioritize [`skills/ppt-master/SKILL.md`](skills/ppt-master/SKILL.md) inside this repository.
-
-## Command Quick Reference
-
-Convenience summary only — full workflow in [`skills/ppt-master/SKILL.md`](skills/ppt-master/SKILL.md).
-
-```bash
-# Source content conversion
-python3 skills/ppt-master/scripts/source_to_md/pdf_to_md.py <PDF_file>
-python3 skills/ppt-master/scripts/source_to_md/doc_to_md.py <DOCX_or_other_file>
-python3 skills/ppt-master/scripts/source_to_md/excel_to_md.py <XLSX_or_XLSM_file>
-python3 skills/ppt-master/scripts/source_to_md/ppt_to_md.py <PPTX_file>
-python3 skills/ppt-master/scripts/source_to_md/web_to_md.py <URL>
-
-# Project management
-python3 skills/ppt-master/scripts/project_manager.py init <project_name> --format ppt169
-python3 skills/ppt-master/scripts/project_manager.py import-sources <project_path> <source_files_or_URLs...> --move
-python3 skills/ppt-master/scripts/project_manager.py validate <project_path>
-
-# Icon selection — copy chosen library icons into <project>/icons/ (missing names reported + non-zero = re-pick)
-python3 skills/ppt-master/scripts/icon_sync.py <project_path> <lib/name> [<lib/name>...]
-
-# Step 4 Eight Confirmations — interactive visual page (default auto-launch; chat fallback)
-python3 skills/ppt-master/scripts/confirm_ui/server.py <project_path> --daemon --wait
-
-# Image tools and SVG quality check
-python3 skills/ppt-master/scripts/analyze_images.py <project_path>/images
-# Formula rendering — manifest written by Strategist after typography confirmation:
-python3 skills/ppt-master/scripts/latex_render.py <project_path>
-python3 skills/ppt-master/scripts/latex_render.py <project_path> --dry-run
-python3 skills/ppt-master/scripts/latex_render.py <project_path> --providers codecogs,quicklatex,mathpad,wikimedia
-# In-pipeline AI image generation — manifest mode (required, even for 1 image):
-python3 skills/ppt-master/scripts/image_gen.py --manifest <project_path>/images/image_prompts.json
-python3 skills/ppt-master/scripts/image_gen.py --render-md <project_path>/images/image_prompts.json
-# Out-of-pipeline one-off / debug / single-image fixup only (no manifest, no sidecar):
-python3 skills/ppt-master/scripts/image_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o <project_path>/images
-# Spot illustrations — slice one AI grid sheet into individual elements (see image-generator.md §4.3):
-python3 skills/ppt-master/scripts/slice_images.py <project_path>/images/<sheet>.png --grid RxC --names a,b,c --trim --alpha
-python3 skills/ppt-master/scripts/svg_editor/server.py <project_path> --live --daemon
-python3 skills/ppt-master/scripts/svg_quality_checker.py <project_path>
-python3 skills/ppt-master/scripts/animation_config.py scaffold <project_path> # optional, only for custom object-level animation
-python3 skills/ppt-master/scripts/animation_config.py validate <project_path> # optional, before re-export
-
-# Post-processing pipeline: run sequentially, one command at a time
-python3 skills/ppt-master/scripts/total_md_split.py <project_path>
-python3 skills/ppt-master/scripts/finalize_svg.py <project_path>
-python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path>
-# Mergeable dy-stacked paragraph blocks collapse into one editable text frame by default; add --no-merge to keep every line as its own frame (strict line fidelity). See SKILL.md Step 7.3.
-```
-
-## Core Directories
-
-- `skills/ppt-master/SKILL.md` — main workflow authority.
-- `skills/ppt-master/references/` — role definitions and technical specifications.
-- `skills/ppt-master/scripts/` — runnable tool scripts.
-- `skills/ppt-master/scripts/docs/` — topic-focused script docs.
-- `skills/ppt-master/templates/` — layout templates, chart templates, icon library, brand presets.
-- `skills/ppt-master/workflows/` — standalone workflow files.
-- `docs/` — user-facing documentation (FAQ, installation, technical design, templates guide, audio narration).
-- `docs/rules/` — repo-wide style rules.
-- `examples/` — example projects.
-- `projects/` — user project workspace.
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index f29cf94a..ca2ec66e 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -69,12 +69,8 @@ description: >
| Script | Purpose |
|--------|---------|
-| `${SKILL_DIR}/scripts/source_to_md/pdf_to_md.py` | PDF to Markdown |
-| `${SKILL_DIR}/scripts/source_to_md/doc_to_md.py` | Documents to Markdown — native Python for DOCX/HTML/EPUB/IPYNB, pandoc fallback for legacy formats (.doc/.odt/.rtf/.tex/.rst/.org/.typ) |
-| `${SKILL_DIR}/scripts/source_to_md/excel_to_md.py` | Excel workbooks to Markdown — supports .xlsx/.xlsm; legacy .xls should be resaved as .xlsx |
-| `${SKILL_DIR}/scripts/source_to_md/ppt_to_md.py` | PowerPoint to Markdown |
+| `${SKILL_DIR}/scripts/source_to_md.py` | Unified source-to-Markdown dispatcher — default Step 1 entry for explicit file(s) or URL(s) |
| `${SKILL_DIR}/scripts/pptx_intake.py` | Standard PPTX intake enrichment — canvas / identity / slide geometry / tables / native chart data |
-| `${SKILL_DIR}/scripts/source_to_md/web_to_md.py` | Web page to Markdown (supports WeChat via `curl_cffi`) |
| `${SKILL_DIR}/scripts/project_manager.py` | Project init / validate / manage |
| `${SKILL_DIR}/scripts/icon_sync.py` | Copy chosen library icons into `<project>/icons/` at selection time; missing names reported + non-zero (re-pick gate) |
| `${SKILL_DIR}/scripts/analyze_images.py` | Image analysis |
@@ -114,7 +110,7 @@ For complete tool documentation, see `${SKILL_DIR}/scripts/README.md`.
|---|---|
| Raw PPTX template plus new material/topic, generate a PPTX | [`template-fill-pptx`](workflows/template-fill-pptx.md) |
| Existing PPTX, preserve page count/order and slide wording 1:1, improve layout | [`beautify-pptx`](workflows/beautify-pptx.md) |
-| Existing PPTX as source material, rethink outline or change page count/order | Main pipeline via `ppt_to_md.py` plus PPTX intake |
+| Existing PPTX as source material, rethink outline or change page count/order | Main pipeline via `source_to_md.py` plus PPTX intake |
| Build a reusable template package from a PPTX/design reference | [`create-template`](workflows/create-template.md), then return with the generated template directory path |
| Finished PPTX, keep content/layout stable and add notes/audio/timing/transitions | [`native-enhance-pptx`](workflows/native-enhance-pptx.md) |
@@ -134,23 +130,26 @@ For complete tool documentation, see `${SKILL_DIR}/scripts/README.md`.
> **No source content?** When the user supplies only a topic name or requirements without any file or substantive description, run the [`topic-research`](workflows/topic-research.md) workflow first, then return here with its products as input.
-When the user provides non-Markdown content, convert immediately:
+When the user provides non-Markdown content, convert immediately through the
+unified dispatcher. It preserves the backend converters' existing behavior,
+routes by source type, and writes the standard Markdown plus conversion profile.
-| User Provides | Command |
-|---------------|---------|
-| PDF file | `python3 ${SKILL_DIR}/scripts/source_to_md/pdf_to_md.py <file>` |
-| DOCX / Word / Office document | `python3 ${SKILL_DIR}/scripts/source_to_md/doc_to_md.py <file>` |
-| XLSX / XLSM / Excel workbook | `python3 ${SKILL_DIR}/scripts/source_to_md/excel_to_md.py <file>` |
+| User Provides | Action |
+|---------------|--------|
+| PDF / DOCX / Office document / XLSX / XLSM / PPTX / EPUB / HTML / LaTeX / RST / web URL | `python3 ${SKILL_DIR}/scripts/source_to_md.py <file_or_URL> [<file_or_URL> ...]` |
| CSV / TSV | Read directly as plain-text table source |
-| PPTX / PowerPoint deck | `python3 ${SKILL_DIR}/scripts/source_to_md/ppt_to_md.py <file>` for Markdown content; after Step 2 `import-sources`, standard PPTX intake is also written to `<project>/analysis/` |
-| EPUB / HTML / LaTeX / RST / other | `python3 ${SKILL_DIR}/scripts/source_to_md/doc_to_md.py <file>` |
-| Web link | `python3 ${SKILL_DIR}/scripts/source_to_md/web_to_md.py <URL>` |
-| WeChat / high-security site | `python3 ${SKILL_DIR}/scripts/source_to_md/web_to_md.py <URL>` (requires `curl_cffi`, included in `requirements.txt`) |
| Markdown | Read directly |
+For PPTX sources, Step 1 converts the deck to Markdown content; after Step 2
+`import-sources`, standard PPTX intake is also written to `<project>/analysis/`.
+Use `source_to_md.py -t <type>` only when extension detection is ambiguous. Use
+`-o` only with a single input; explicit multi-input conversion writes one
+Markdown/profile pair per source. Backend converter details are documented in
+[`scripts/docs/conversion.md`](scripts/docs/conversion.md).
+
> **Office vector assets (EMF/WMF) from DOCX/PPTX sources**:
-> `doc_to_md.py` / `ppt_to_md.py` extract embedded Office vector images (.emf/.wmf)
-> alongside bitmap images. After `import-sources`, these land in `images/`
+> Source conversion extracts embedded Office vector images (.emf/.wmf)
+> alongside bitmap images when the source format exposes them. After `import-sources`, these land in `images/`
> together with `image_manifest.json` and are first-class assets in §VIII Image Resource List.
>
> **Do NOT convert EMF/WMF to PNG.** The PPT Master pipeline preserves them as external
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index b5d2997f..ec9c0e0a 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -5,7 +5,8 @@ This directory contains user-facing scripts for conversion, project setup, direc
## Directory Layout
- Top-level `scripts/`: runnable entry scripts
-- `scripts/source_to_md/`: source-document → Markdown converters (`pdf_to_md.py`, `doc_to_md.py`, `excel_to_md.py`, `ppt_to_md.py`, `web_to_md.py`)
+- `scripts/source_to_md.py`: unified source-document → Markdown dispatcher
+- `scripts/source_to_md/`: source-document → Markdown routing helpers and backend converters (`_dispatcher.py`, `pdf_to_md.py`, `doc_to_md.py`, `excel_to_md.py`, `ppt_to_md.py`, `web_to_md.py`)
- `scripts/image_backends/`: internal provider implementations used by `image_gen.py`
- `scripts/tts_backends/`: internal TTS provider implementations used by `notes_to_audio.py`
- `scripts/template_import/`: internal PPTX reference-preparation helpers used by `pptx_template_import.py`
@@ -18,6 +19,8 @@ This directory contains user-facing scripts for conversion, project setup, direc
Typical end-to-end workflow:
```bash
+python3 scripts/source_to_md.py <file-or-url> [<file-or-url> ...]
+# or direct backend calls:
python3 scripts/source_to_md/pdf_to_md.py <file.pdf>
# or
python3 scripts/source_to_md/ppt_to_md.py <deck.pptx>
@@ -40,7 +43,7 @@ python3 scripts/update_repo.py
| Area | Primary scripts | Documentation |
|------|-----------------|---------------|
-| Conversion | `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `pptx_intake.py` | [docs/conversion.md](./docs/conversion.md) |
+| Conversion | `source_to_md.py`, `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `pptx_intake.py` | [docs/conversion.md](./docs/conversion.md) |
| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py`, `native_enhance_pptx.py` | [docs/project.md](./docs/project.md) |
| SVG pipeline | `finalize_svg.py`, `svg_to_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `animation_config.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md) |
| Spec maintenance | `update_spec.py` | [docs/update_spec.md](./docs/update_spec.md) |
@@ -53,6 +56,7 @@ python3 scripts/update_repo.py
Conversion:
```bash
+python3 scripts/source_to_md.py <file-or-url> [<file-or-url> ...]
python3 scripts/source_to_md/pdf_to_md.py <file.pdf>
python3 scripts/source_to_md/ppt_to_md.py <deck.pptx>
python3 scripts/source_to_md/doc_to_md.py <file.docx>
diff --git a/skills/ppt-master/scripts/docs/conversion.md b/skills/ppt-master/scripts/docs/conversion.md
index 1d03272f..338b5fe1 100644
--- a/skills/ppt-master/scripts/docs/conversion.md
+++ b/skills/ppt-master/scripts/docs/conversion.md
@@ -4,6 +4,67 @@
Source conversion tools turn PDFs, documents, slide decks, and web pages into Markdown before project creation.
+Default workflow entry: use `source_to_md.py` unless a backend-specific
+diagnostic or forced route is needed.
+
+## Shared Output Contract
+
+All `source_to_md` converters keep their existing Markdown output behavior and
+now also write a lightweight sidecar profile when conversion succeeds:
+
+| Output | Convention |
+|---|---|
+| Markdown | `<stem>.md` unless `-o` selects another path |
+| Asset directory | `<stem>_files/` when the backend extracts images or media |
+| Image manifest | `<stem>_files/image_manifest.json` when image metadata is available |
+| Conversion profile | `<stem>.conversion_profile.json` beside the Markdown output |
+
+The conversion profile is metadata only. It records the converter, source path,
+Markdown structure counts, asset directory, image manifest path, and image
+count. Downstream PPT workflows still use the Markdown and image manifest as the
+content/asset contract; the profile is for inspection and debugging.
+
+## `source_to_md.py`
+
+Unified dispatcher for ad hoc explicit-source conversion. It auto-detects each
+listed input file or URL and calls the existing backend converter, so backend
+behavior remains the source of truth.
+
+Routing is centralized in `source_to_md/_dispatcher.py` and reused by
+`project_manager.py import-sources`; do not add a second type-to-backend table.
+
+```bash
+python3 scripts/source_to_md.py paper.pdf
+python3 scripts/source_to_md.py paper.pdf report.docx deck.pptx
+python3 scripts/source_to_md.py ./pdfs/*.pdf
+python3 scripts/source_to_md.py ./decks/*.pptx
+python3 scripts/source_to_md.py report.docx -o report.md
+python3 scripts/source_to_md.py workbook.xlsx --json
+python3 scripts/source_to_md.py deck.pptx
+python3 scripts/source_to_md.py https://example.com/article -o article.md
+```
+
+Useful options:
+- `-t pdf|doc|excel|pptx|web|markdown|text` forces a route when extension
+ detection is not enough.
+- `--json` prints a compact machine-readable result after success when the
+ output path is known. With multiple inputs, each successful conversion prints
+ its own JSON line after that source finishes.
+- `--images all|filtered|none`, `--no-images`, and `--filter-images` map to the
+ existing PDF image mode. They are intentionally PDF-only until other backends
+ expose the same behavior natively.
+- Unknown backend-specific flags are passed through to each selected converter.
+- `-o/--output` is valid only with one input. Multiple explicit inputs write
+ one Markdown/profile pair per source.
+
+For multi-source project intake, use `project_manager.py import-sources` with
+all source paths / URLs. `source_to_md.py` intentionally rejects directory
+batching; pass explicit files/URLs or use project intake.
+
+Backend converters are single-file tools. For ad hoc multi-file conversion,
+pass explicit files or shell-expanded globs to `source_to_md.py`; for project
+intake, use `project_manager.py import-sources`.
+
## `source_to_md/pdf_to_md.py`
Recommended first choice for native PDFs.
@@ -11,8 +72,6 @@ Recommended first choice for native PDFs.
```bash
python3 scripts/source_to_md/pdf_to_md.py book.pdf
python3 scripts/source_to_md/pdf_to_md.py book.pdf -o output.md
-python3 scripts/source_to_md/pdf_to_md.py ./pdfs
-python3 scripts/source_to_md/pdf_to_md.py ./pdfs -o ./markdown
# Image extraction control (default: filtered)
python3 scripts/source_to_md/pdf_to_md.py book.pdf --images filtered # size/quality filters applied
@@ -69,6 +128,7 @@ pip install mammoth markdownify ebooklib nbconvert beautifulsoup4
```
All paths produce the same output convention: `<input>.md` plus a sibling `<input>_files/` directory containing extracted images with relative references.
+On success, a sibling `<input>.conversion_profile.json` is also written.
## `source_to_md/excel_to_md.py`
@@ -93,6 +153,7 @@ Behavior:
- trims empty outer rows and columns
- propagates merged-cell labels for readable Markdown tables
- exports formula cells as cached values; it does not recalculate formulas
+- writes `<input>.conversion_profile.json` after successful conversion
Dependency:
@@ -114,8 +175,6 @@ Supported formats include:
```bash
python3 scripts/source_to_md/ppt_to_md.py sales_deck.pptx
python3 scripts/source_to_md/ppt_to_md.py sales_deck.pptx -o output.md
-python3 scripts/source_to_md/ppt_to_md.py ./decks
-python3 scripts/source_to_md/ppt_to_md.py ./decks -o ./markdown
python3 scripts/source_to_md/ppt_to_md.py template.ppsx -o notes/template.md
```
@@ -125,6 +184,7 @@ Behavior:
- transcribes native chart data (type + categories × series values) into a Markdown table, so chart numbers are not lost in conversion
- exports embedded pictures to a sibling `_files/` directory
- appends speaker notes when present
+- writes `<input>.conversion_profile.json` after successful conversion
Dependency:
@@ -173,6 +233,9 @@ fetch WeChat Official Accounts (`mp.weixin.qq.com`) and other sites that
block Python's default TLS fingerprint. No extra flags needed. If
`curl_cffi` is not available, it falls back to plain `requests`.
+On success, the converter writes `<output>.conversion_profile.json` beside the
+Markdown output.
+
## `rotate_images.py`
diff --git a/skills/ppt-master/scripts/project_manager.py b/skills/ppt-master/scripts/project_manager.py
index 16130091..72ad4fc6 100644
--- a/skills/ppt-master/scripts/project_manager.py
+++ b/skills/ppt-master/scripts/project_manager.py
@@ -47,21 +47,22 @@ except ImportError:
TOOLS_DIR = Path(__file__).resolve().parent
SKILL_DIR = TOOLS_DIR.parent
REPO_ROOT = SKILL_DIR.parent.parent
+SOURCE_TO_MD_TOOLS_DIR = TOOLS_DIR / "source_to_md"
+if str(SOURCE_TO_MD_TOOLS_DIR) not in sys.path:
+ sys.path.insert(0, str(SOURCE_TO_MD_TOOLS_DIR))
+
+from _dispatcher import ( # noqa: E402
+ DOC_SUFFIXES,
+ EXCEL_SUFFIXES,
+ LEGACY_EXCEL_SUFFIXES,
+ PDF_SUFFIXES,
+ PRESENTATION_SUFFIXES,
+ build_conversion_command,
+)
+
SOURCE_DIRNAME = "sources"
TEXT_SOURCE_SUFFIXES = {".md", ".markdown", ".txt"}
TABLE_TEXT_SUFFIXES = {".csv", ".tsv"}
-PDF_SUFFIXES = {".pdf"}
-PRESENTATION_SUFFIXES = {".pptx", ".pptm", ".ppsx", ".ppsm", ".potx", ".potm"}
-EXCEL_SUFFIXES = {".xlsx", ".xlsm"}
-LEGACY_EXCEL_SUFFIXES = {".xls"}
-DOC_SUFFIXES = {
- ".docx", ".doc", ".odt", ".rtf", # Office documents
- ".epub", # eBooks
- ".html", ".htm", # Web pages
- ".tex", ".latex", ".rst", ".org", # Academic / technical
- ".ipynb", ".typ", # Notebooks / Typst
-}
-WECHAT_HOST_KEYWORDS = ("mp.weixin.qq.com", "weixin.qq.com")
IMAGE_ASSET_SUFFIXES = {
".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif",
".emf", ".wmf", ".svg",
@@ -71,15 +72,6 @@ IMAGE_ASSET_SUFFIXES = {
configure_utf8_stdio()
-def _curl_cffi_available() -> bool:
- """Return whether curl_cffi is importable (enables Python TLS impersonation)."""
- try:
- import curl_cffi # noqa: F401
- return True
- except ImportError:
- return False
-
-
def is_url(value: str) -> bool:
"""Return whether a string looks like an HTTP(S) URL."""
parsed = urlparse(value)
@@ -263,37 +255,28 @@ class ProjectManager:
print(result.stdout.strip())
def _import_pdf(self, pdf_path: Path, markdown_path: Path) -> None:
- self._run_tool(
- [
- sys.executable,
- str(TOOLS_DIR / "source_to_md" / "pdf_to_md.py"),
- str(pdf_path),
- "-o",
- str(markdown_path),
- ]
+ route = build_conversion_command(
+ str(pdf_path),
+ markdown_path,
+ forced_type="pdf",
)
+ self._run_tool(route.command)
def _import_doc(self, doc_path: Path, markdown_path: Path) -> None:
- self._run_tool(
- [
- sys.executable,
- str(TOOLS_DIR / "source_to_md" / "doc_to_md.py"),
- str(doc_path),
- "-o",
- str(markdown_path),
- ]
+ route = build_conversion_command(
+ str(doc_path),
+ markdown_path,
+ forced_type="doc",
)
+ self._run_tool(route.command)
def _import_presentation(self, presentation_path: Path, markdown_path: Path) -> None:
- self._run_tool(
- [
- sys.executable,
- str(TOOLS_DIR / "source_to_md" / "ppt_to_md.py"),
- str(presentation_path),
- "-o",
- str(markdown_path),
- ]
+ route = build_conversion_command(
+ str(presentation_path),
+ markdown_path,
+ forced_type="pptx",
)
+ self._run_tool(route.command)
def _import_pptx_intake(self, presentation_path: Path, project_dir: Path) -> Path:
# Multi-deck intake: each PPTX writes its own `<stem>.identity.json` /
@@ -312,36 +295,20 @@ class ProjectManager:
return analysis_dir
def _import_excel(self, excel_path: Path, markdown_path: Path) -> None:
- self._run_tool(
- [
- sys.executable,
- str(TOOLS_DIR / "source_to_md" / "excel_to_md.py"),
- str(excel_path),
- "-o",
- str(markdown_path),
- ]
+ route = build_conversion_command(
+ str(excel_path),
+ markdown_path,
+ forced_type="excel",
)
+ self._run_tool(route.command)
def _import_url(self, url: str, markdown_path: Path) -> None:
- # Prefer web_to_md.py: it uses curl_cffi internally when available,
- # which handles WeChat and other TLS-fingerprint-blocked sites.
- # Fall back to the Node.js version only when the URL is known to
- # require TLS impersonation AND curl_cffi isn't installed.
- host = urlparse(url).netloc.lower()
- is_tls_sensitive = any(keyword in host for keyword in WECHAT_HOST_KEYWORDS)
-
- if is_tls_sensitive and not _curl_cffi_available() and shutil.which("node"):
- command = ["node", str(TOOLS_DIR / "source_to_md" / "web_to_md.cjs"),
- url, "-o", str(markdown_path)]
- else:
- command = [
- sys.executable,
- str(TOOLS_DIR / "source_to_md" / "web_to_md.py"),
- url,
- "-o",
- str(markdown_path),
- ]
- self._run_tool(command)
+ route = build_conversion_command(
+ url,
+ markdown_path,
+ forced_type="web",
+ )
+ self._run_tool(route.command)
def _is_valid_imported_url_markdown(self, markdown_path: Path) -> bool:
"""Return whether web_to_md produced a usable Markdown source."""
diff --git a/skills/ppt-master/scripts/source_to_md.py b/skills/ppt-master/scripts/source_to_md.py
new file mode 100644
index 00000000..31574885
--- /dev/null
+++ b/skills/ppt-master/scripts/source_to_md.py
@@ -0,0 +1,418 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Unified Markdown Converter
+
+Auto-detect source type and dispatch to the existing source_to_md converters.
+
+Usage:
+ python3 scripts/source_to_md.py <file_or_url> [<file_or_url> ...] [options]
+
+Examples:
+ python3 scripts/source_to_md.py paper.pdf
+ python3 scripts/source_to_md.py paper.pdf report.docx deck.pptx
+ python3 scripts/source_to_md.py report.docx -o report.md
+ python3 scripts/source_to_md.py deck.pptx --json
+
+Dependencies:
+ Same as the backend converter selected for the input.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import subprocess
+import sys
+from pathlib import Path
+from urllib.parse import urlparse
+
+_SCRIPTS_DIR = Path(__file__).resolve().parent
+if str(_SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(_SCRIPTS_DIR))
+
+from console_encoding import configure_utf8_stdio # noqa: E402
+
+_SOURCE_TO_MD_DIR = _SCRIPTS_DIR / "source_to_md"
+if str(_SOURCE_TO_MD_DIR) not in sys.path:
+ sys.path.insert(0, str(_SOURCE_TO_MD_DIR))
+
+from _conversion_profile import ( # noqa: E402
+ build_result_payload,
+ profile_path_for,
+ write_conversion_profile,
+)
+from _dispatcher import ( # noqa: E402
+ build_conversion_command,
+ default_markdown_path,
+ detect_source_type,
+ is_url,
+)
+
+configure_utf8_stdio()
+
+
+def resolve_output(output: str | None, input_arg: str) -> Path:
+ return Path(output) if output else default_markdown_path(input_arg)
+
+
+def _print_status(message: str) -> None:
+ print(message, file=sys.stderr)
+
+
+def _sanitize_output_stem(value: str) -> str:
+ safe = re.sub(r"[^A-Za-z0-9_.-]+", "_", value.strip())
+ safe = safe.strip("._-")
+ while "__" in safe:
+ safe = safe.replace("__", "_")
+ return safe[:120] or "web_source"
+
+
+def _default_batch_output(input_arg: str, conversion_type: str) -> str | None:
+ """Return a deterministic per-source output path for batch mode."""
+ if conversion_type == "web":
+ parsed = urlparse(input_arg)
+ parts = [parsed.netloc]
+ if parsed.path and parsed.path != "/":
+ parts.append(parsed.path.strip("/").replace("/", "_"))
+ return str(Path(f"{_sanitize_output_stem('_'.join(parts))}.md"))
+ return str(default_markdown_path(input_arg))
+
+
+def run_backend(command: list[str], script_name: str) -> int:
+ _print_status(f"[>>] {script_name} {' '.join(command[2:])}")
+ try:
+ result = subprocess.run(
+ command,
+ check=False,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ )
+ except KeyboardInterrupt:
+ return 130
+ if result.stdout.strip():
+ print(result.stdout.strip(), file=sys.stderr)
+ if result.stderr.strip():
+ print(result.stderr.strip(), file=sys.stderr)
+ return result.returncode
+
+
+def print_output(path: Path) -> None:
+ print(f"OUTPUT: {path.resolve()}")
+
+
+def write_passthrough(
+ input_arg: str,
+ output: Path,
+ conversion_type: str,
+ json_output: bool = False,
+) -> int:
+ """Copy text-like input to Markdown and write the profile sidecar."""
+ source = Path(input_arg)
+ try:
+ text = source.read_text(encoding="utf-8", errors="replace")
+ except OSError as exc:
+ print(f"[ERROR] Cannot read {source}: {exc}", file=sys.stderr)
+ return 1
+
+ output.parent.mkdir(parents=True, exist_ok=True)
+ if output.resolve() != source.resolve():
+ output.write_text(text, encoding="utf-8")
+ profile = write_conversion_profile(
+ input_path=input_arg,
+ markdown_path=output,
+ converter="source_to_md.py",
+ conversion_type=conversion_type,
+ )
+ _print_status(f"[OK] Saved Markdown to: {output}")
+ _print_status(f" Wrote conversion profile -> {profile}")
+ print_output(output)
+ if json_output:
+ payload = build_result_payload(
+ input_path=input_arg,
+ markdown_path=output,
+ converter="source_to_md.py",
+ conversion_type=conversion_type,
+ profile_path=profile,
+ )
+ print(json.dumps(payload, ensure_ascii=False))
+ return 0
+
+
+def ensure_profile(
+ input_arg: str,
+ output: Path,
+ converter: str,
+ conversion_type: str,
+) -> Path:
+ """Return an existing profile path, writing one if the backend did not."""
+ profile = profile_path_for(output)
+ if profile.is_file():
+ return profile
+ return write_conversion_profile(
+ input_path=input_arg,
+ markdown_path=output,
+ converter=converter,
+ conversion_type=conversion_type,
+ )
+
+
+def print_json_result(
+ input_arg: str,
+ output: Path,
+ converter: str,
+ conversion_type: str,
+ profile: Path,
+) -> None:
+ payload = build_result_payload(
+ input_path=input_arg,
+ markdown_path=output,
+ converter=converter,
+ conversion_type=conversion_type,
+ profile_path=profile,
+ )
+ print(json.dumps(payload, ensure_ascii=False))
+
+
+def _pdf_image_mode(args: argparse.Namespace) -> str | None:
+ image_mode = args.images
+ if args.no_images:
+ image_mode = "none"
+ if args.filter_images:
+ image_mode = "filtered"
+ return image_mode
+
+
+def _validate_image_options(args: argparse.Namespace) -> bool:
+ selected = sum(bool(value) for value in (args.images, args.no_images, args.filter_images))
+ if selected > 1:
+ print(
+ "[ERROR] --images, --no-images, and --filter-images are mutually exclusive",
+ file=sys.stderr,
+ )
+ return False
+ return True
+
+
+def dispatch_single(
+ input_arg: str,
+ conversion_type: str,
+ output_arg: str | None,
+ args: argparse.Namespace,
+ unknown_args: list[str],
+) -> int:
+ """Dispatch one source to the matching existing converter."""
+ if conversion_type == "auto":
+ conversion_type = detect_source_type(input_arg)
+
+ if conversion_type == "directory":
+ print(
+ "[ERROR] Directories are not supported by source_to_md.py; "
+ "use project_manager.py import-sources for multi-source project intake.",
+ file=sys.stderr,
+ )
+ return 1
+
+ if conversion_type == "markdown":
+ output = resolve_output(output_arg, input_arg)
+ return write_passthrough(input_arg, output, "markdown", args.json)
+ if conversion_type == "text":
+ output = resolve_output(output_arg, input_arg)
+ return write_passthrough(input_arg, output, "text", args.json)
+
+ if conversion_type == "web":
+ output = Path(output_arg) if output_arg else None
+ try:
+ route = build_conversion_command(
+ input_arg,
+ output,
+ forced_type="web",
+ extra_args=unknown_args,
+ )
+ except ValueError as exc:
+ print(f"[ERROR] {exc}", file=sys.stderr)
+ return 1
+ rc = run_backend(route.command, route.script_name)
+ if rc != 0:
+ return rc
+ if route.output_path and route.output_path.is_file():
+ profile = ensure_profile(input_arg, route.output_path, route.script_name, "web")
+ print_output(route.output_path)
+ if args.json:
+ print_json_result(input_arg, route.output_path, route.script_name, "web", profile)
+ return 0
+
+ if conversion_type not in {"pdf", "doc", "excel", "pptx"}:
+ print(
+ f"[ERROR] Could not determine conversion type for {input_arg!r}. "
+ "Use -t pdf|doc|excel|pptx|web|markdown|text.",
+ file=sys.stderr,
+ )
+ return 1
+
+ if not is_url(input_arg) and not Path(input_arg).exists():
+ print(f"[ERROR] File not found: {input_arg}", file=sys.stderr)
+ return 1
+
+ output = resolve_output(output_arg, input_arg)
+ try:
+ route = build_conversion_command(
+ input_arg,
+ output,
+ forced_type=conversion_type,
+ extra_args=unknown_args,
+ pdf_image_mode=_pdf_image_mode(args),
+ render_vector_figures=args.render_vector_figures,
+ )
+ except ValueError as exc:
+ print(f"[ERROR] {exc}", file=sys.stderr)
+ return 1
+ rc = run_backend(route.command, route.script_name)
+ if rc != 0:
+ return rc
+ if not output.is_file():
+ print(f"[ERROR] Expected Markdown output not found: {output}", file=sys.stderr)
+ return 1
+
+ profile = ensure_profile(input_arg, output, route.script_name, conversion_type)
+ print_output(output)
+ if args.json:
+ print_json_result(input_arg, output, route.script_name, conversion_type, profile)
+ return 0
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description="Auto-detect source type and convert to Markdown via source_to_md backends.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ python3 scripts/source_to_md.py paper.pdf
+ python3 scripts/source_to_md.py paper.pdf report.docx deck.pptx
+ python3 scripts/source_to_md.py report.docx -o output.md
+ python3 scripts/source_to_md.py deck.pptx --json
+ python3 scripts/source_to_md.py https://example.com/article -o article.md
+
+Backend-specific flags not listed here are passed through to the selected
+converter, so existing converter behavior remains the source of truth.
+ """,
+ )
+ parser.add_argument("inputs", nargs="+", help="Input file(s) or URL(s)")
+ parser.add_argument(
+ "-t",
+ "--type",
+ choices=["auto", "pdf", "doc", "excel", "pptx", "web", "markdown", "text"],
+ default="auto",
+ help="Force a conversion type (default: auto)",
+ )
+ parser.add_argument("-o", "--output", help="Output Markdown file")
+ parser.add_argument(
+ "--images",
+ choices=["all", "filtered", "none"],
+ help="PDF image extraction mode; maps to pdf_to_md.py --images",
+ )
+ parser.add_argument(
+ "--no-images",
+ action="store_true",
+ help="Alias for --images none on PDF inputs",
+ )
+ parser.add_argument(
+ "--filter-images",
+ action="store_true",
+ help="Alias for --images filtered on PDF inputs",
+ )
+ parser.add_argument(
+ "--render-vector-figures",
+ action="store_true",
+ help="Pass through to pdf_to_md.py for PDF vector figure rendering",
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Print a machine-readable result after successful conversion",
+ )
+ return parser
+
+
+def _has_pdf_image_flags(args: argparse.Namespace) -> bool:
+ return bool(args.images or args.no_images or args.filter_images or args.render_vector_figures)
+
+
+def _conversion_type_for_input(input_arg: str, requested_type: str) -> str:
+ if requested_type == "auto":
+ return detect_source_type(input_arg)
+ return requested_type
+
+
+def _validate_pdf_image_flags(args: argparse.Namespace, conversion_types: list[str]) -> bool:
+ if not _has_pdf_image_flags(args):
+ return True
+ if any(conversion_type != "pdf" for conversion_type in conversion_types):
+ print("[ERROR] Image extraction flags are currently supported only for PDFs", file=sys.stderr)
+ return False
+ return True
+
+
+def dispatch_many(
+ inputs: list[str],
+ args: argparse.Namespace,
+ unknown_args: list[str],
+ conversion_types: list[str],
+) -> int:
+ success_count = 0
+ failed: list[tuple[str, int]] = []
+ batch_mode = len(inputs) > 1
+
+ for input_arg, conversion_type in zip(inputs, conversion_types):
+ output_arg = args.output
+ if batch_mode:
+ output_arg = _default_batch_output(input_arg, conversion_type)
+ _print_status(f"\n==> {input_arg}")
+
+ rc = dispatch_single(input_arg, conversion_type, output_arg, args, unknown_args)
+ if rc == 0:
+ success_count += 1
+ else:
+ failed.append((input_arg, rc))
+
+ if batch_mode:
+ _print_status(f"\n[Done] Success: {success_count}/{len(inputs)}, Failed: {len(failed)}")
+ if failed:
+ _print_status("\n[Failed inputs]:")
+ for input_arg, rc in failed:
+ _print_status(f" - {input_arg}: exit {rc}")
+ return 1
+ return 0 if not failed else failed[0][1]
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = build_parser()
+ args, unknown_args = parser.parse_known_args(argv)
+
+ if not _validate_image_options(args):
+ return 2
+
+ if len(args.inputs) > 1 and args.output:
+ print("[ERROR] -o/--output is only valid with a single input", file=sys.stderr)
+ return 2
+
+ conversion_types = [_conversion_type_for_input(item, args.type) for item in args.inputs]
+ if not _validate_pdf_image_flags(args, conversion_types):
+ return 2
+
+ if unknown_args and any(
+ conversion_type in {"markdown", "text"} for conversion_type in conversion_types
+ ):
+ print(
+ "[ERROR] Backend-specific flags cannot be used with markdown/text passthrough inputs",
+ file=sys.stderr,
+ )
+ return 2
+
+ return dispatch_many(args.inputs, args, unknown_args, conversion_types)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/source_to_md/_conversion_profile.py b/skills/ppt-master/scripts/source_to_md/_conversion_profile.py
new file mode 100644
index 00000000..f9303fb7
--- /dev/null
+++ b/skills/ppt-master/scripts/source_to_md/_conversion_profile.py
@@ -0,0 +1,235 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Markdown Conversion Profile Helpers
+
+Write lightweight sidecar metadata for source_to_md conversion outputs.
+
+Usage:
+ Imported by scripts/source_to_md/*.py
+
+Examples:
+ write_conversion_profile(input_path="demo.pdf", markdown_path="demo.md", ...)
+
+Dependencies:
+ None
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+
+IMAGE_MANIFEST_NAME = "image_manifest.json"
+PROFILE_SCHEMA = "ppt-master.source_to_md.profile.v1"
+PROFILE_SUFFIX = ".conversion_profile.json"
+
+
+def default_asset_dir(markdown_path: Path) -> Path:
+ """Return the conventional companion asset directory for one Markdown output."""
+ return markdown_path.parent / f"{markdown_path.stem}_files"
+
+
+def profile_path_for(markdown_path: Path) -> Path:
+ """Return the sidecar profile path for one Markdown output."""
+ return markdown_path.with_name(f"{markdown_path.stem}{PROFILE_SUFFIX}")
+
+
+def _display_path(path: Path | None, root: Path) -> str:
+ if path is None:
+ return ""
+ try:
+ return path.resolve().relative_to(root.resolve()).as_posix()
+ except ValueError:
+ return path.resolve().as_posix()
+
+
+def _count_tables(lines: list[str]) -> int:
+ count = 0
+ in_table = False
+ separator_re = re.compile(
+ r"^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?$"
+ )
+ for line in lines:
+ stripped = line.strip()
+ is_table_line = stripped.startswith("|") and stripped.endswith("|")
+ has_separator = bool(separator_re.match(stripped))
+ if is_table_line or has_separator:
+ if not in_table:
+ count += 1
+ in_table = True
+ continue
+ in_table = False
+ return count
+
+
+def markdown_stats(markdown_path: Path) -> dict[str, int]:
+ """Return low-cost Markdown structure counts for inspection/debugging."""
+ if not markdown_path.is_file():
+ return {
+ "line_count": 0,
+ "char_count": 0,
+ "heading_count": 0,
+ "table_count": 0,
+ "image_ref_count": 0,
+ "link_count": 0,
+ }
+
+ text = markdown_path.read_text(encoding="utf-8", errors="replace")
+ lines = text.splitlines()
+ return {
+ "line_count": len(lines),
+ "char_count": len(text),
+ "heading_count": sum(1 for line in lines if re.match(r"^#{1,6}\s+", line)),
+ "table_count": _count_tables(lines),
+ "image_ref_count": len(re.findall(r"!\[[^\]]*\]\([^)]+\)", text)),
+ "link_count": len(re.findall(r"(?<!!)\[[^\]]+\]\([^)]+\)", text)),
+ }
+
+
+def _read_json(path: Path) -> Any:
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+
+
+def _image_count_from_manifest(path: Path) -> int:
+ payload = _read_json(path)
+ if isinstance(payload, list):
+ return len(payload)
+ if isinstance(payload, dict):
+ items = payload.get("items")
+ if isinstance(items, list):
+ return len(items)
+ return 0
+
+
+def build_conversion_profile(
+ *,
+ input_path: str,
+ markdown_path: str | Path,
+ converter: str,
+ conversion_type: str,
+ asset_dir: str | Path | None = None,
+ warnings: list[str] | None = None,
+) -> dict[str, Any]:
+ """Build a sidecar profile without changing the Markdown conversion result."""
+ markdown = Path(markdown_path)
+ root = markdown.parent
+ is_url = input_path.startswith(("http://", "https://"))
+ source = None if is_url else Path(input_path)
+ assets = Path(asset_dir) if asset_dir else default_asset_dir(markdown)
+ image_manifest = assets / IMAGE_MANIFEST_NAME
+ source_exists = bool(source and source.exists())
+
+ return {
+ "schema": PROFILE_SCHEMA,
+ "converter": converter,
+ "conversion_type": conversion_type,
+ "source": {
+ "path": input_path if is_url else _display_path(source, root),
+ "name": input_path if is_url else (source.name if source else input_path),
+ "suffix": "" if is_url else (source.suffix.lower() if source else ""),
+ "kind": "url" if is_url else "file",
+ "exists": source_exists,
+ "size_bytes": (
+ source.stat().st_size
+ if source_exists and source is not None and source.is_file()
+ else None
+ ),
+ },
+ "outputs": {
+ "markdown": _display_path(markdown, root),
+ "asset_dir": _display_path(assets, root) if assets.is_dir() else "",
+ "image_manifest": (
+ _display_path(image_manifest, root) if image_manifest.is_file() else ""
+ ),
+ "image_count": _image_count_from_manifest(image_manifest),
+ },
+ "markdown": markdown_stats(markdown),
+ "warnings": warnings or [],
+ }
+
+
+def write_conversion_profile(
+ *,
+ input_path: str,
+ markdown_path: str | Path,
+ converter: str,
+ conversion_type: str,
+ asset_dir: str | Path | None = None,
+ warnings: list[str] | None = None,
+) -> Path:
+ """Write `<stem>.conversion_profile.json` beside one Markdown output."""
+ markdown = Path(markdown_path)
+ profile_path = profile_path_for(markdown)
+ profile = build_conversion_profile(
+ input_path=input_path,
+ markdown_path=markdown,
+ converter=converter,
+ conversion_type=conversion_type,
+ asset_dir=asset_dir,
+ warnings=warnings,
+ )
+ profile_path.write_text(
+ json.dumps(profile, ensure_ascii=False, indent=2) + "\n",
+ encoding="utf-8",
+ )
+ return profile_path
+
+
+def write_conversion_profile_best_effort(
+ *,
+ input_path: str,
+ markdown_path: str | Path,
+ converter: str,
+ conversion_type: str,
+ asset_dir: str | Path | None = None,
+ warnings: list[str] | None = None,
+) -> Path | None:
+ """Write a profile sidecar, warning without changing converter success."""
+ try:
+ return write_conversion_profile(
+ input_path=input_path,
+ markdown_path=markdown_path,
+ converter=converter,
+ conversion_type=conversion_type,
+ asset_dir=asset_dir,
+ warnings=warnings,
+ )
+ except OSError as exc:
+ print(f"[WARN] Could not write conversion profile: {exc}", file=sys.stderr)
+ return None
+
+
+def build_result_payload(
+ *,
+ input_path: str,
+ markdown_path: str | Path,
+ converter: str,
+ conversion_type: str,
+ asset_dir: str | Path | None = None,
+ profile_path: str | Path | None = None,
+) -> dict[str, Any]:
+ """Return a compact JSON payload for CLI consumers."""
+ markdown = Path(markdown_path)
+ assets = Path(asset_dir) if asset_dir else default_asset_dir(markdown)
+ image_manifest = assets / IMAGE_MANIFEST_NAME
+ profile = Path(profile_path) if profile_path else profile_path_for(markdown)
+ return {
+ "input": (
+ input_path
+ if input_path.startswith(("http://", "https://"))
+ else str(Path(input_path).resolve())
+ ),
+ "markdown": str(markdown.resolve()),
+ "asset_dir": str(assets.resolve()) if assets.is_dir() else "",
+ "image_manifest": str(image_manifest.resolve()) if image_manifest.is_file() else "",
+ "conversion_profile": str(profile.resolve()) if profile.is_file() else "",
+ "converter": converter,
+ "conversion_type": conversion_type,
+ }
diff --git a/skills/ppt-master/scripts/source_to_md/_dispatcher.py b/skills/ppt-master/scripts/source_to_md/_dispatcher.py
new file mode 100644
index 00000000..36240fa0
--- /dev/null
+++ b/skills/ppt-master/scripts/source_to_md/_dispatcher.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Source to Markdown Dispatcher
+
+Shared routing and backend command construction for source-to-Markdown tools.
+
+Usage:
+ Imported by scripts/source_to_md.py and scripts/project_manager.py
+
+Examples:
+ build_conversion_command("report.pdf", "report.md")
+
+Dependencies:
+ None
+"""
+
+from __future__ import annotations
+
+import shutil
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from urllib.parse import urlparse
+
+
+SOURCE_TO_MD_DIR = Path(__file__).resolve().parent
+WECHAT_HOST_KEYWORDS = ("mp.weixin.qq.com", "weixin.qq.com")
+
+DOC_SUFFIXES = {
+ ".docx", ".doc", ".odt", ".rtf", # Office documents
+ ".epub", # eBooks
+ ".html", ".htm", # Web pages
+ ".tex", ".latex", ".rst", ".org", # Academic / technical
+ ".ipynb", ".typ", # Notebooks / Typst
+}
+EXCEL_SUFFIXES = {".xlsx", ".xlsm"}
+LEGACY_EXCEL_SUFFIXES = {".xls"}
+MARKDOWN_SUFFIXES = {".md", ".markdown"}
+PDF_SUFFIXES = {".pdf"}
+PRESENTATION_SUFFIXES = {".pptx", ".pptm", ".ppsx", ".ppsm", ".potx", ".potm"}
+TEXT_SUFFIXES = {".txt", ".text"}
+
+
+@dataclass
+class ConversionCommand:
+ """Backend command plus metadata for one conversion route."""
+
+ command: list[str]
+ script_name: str
+ conversion_type: str
+ output_path: Path | None
+
+
+def is_url(value: str) -> bool:
+ """Return whether a string looks like an HTTP(S) URL."""
+ parsed = urlparse(value)
+ return parsed.scheme in {"http", "https"} and bool(parsed.netloc)
+
+
+def detect_source_type(input_arg: str) -> str:
+ """Detect a conversion type from a URL, file, or directory."""
+ if is_url(input_arg):
+ return "web"
+
+ path = Path(input_arg)
+ if not path.exists():
+ return "unknown"
+ if path.is_dir():
+ return "directory"
+
+ suffix = path.suffix.lower()
+ if suffix in PDF_SUFFIXES:
+ return "pdf"
+ if suffix in DOC_SUFFIXES:
+ return "doc"
+ if suffix in EXCEL_SUFFIXES or suffix in LEGACY_EXCEL_SUFFIXES:
+ return "excel"
+ if suffix in PRESENTATION_SUFFIXES:
+ return "pptx"
+ if suffix in MARKDOWN_SUFFIXES:
+ return "markdown"
+ if suffix in TEXT_SUFFIXES:
+ return "text"
+ return "unknown"
+
+
+def default_markdown_path(input_arg: str) -> Path:
+ """Return the conventional Markdown output path for a local input."""
+ path = Path(input_arg)
+ return path.parent / f"{path.stem}.md"
+
+
+def _curl_cffi_available() -> bool:
+ """Return whether curl_cffi is importable."""
+ try:
+ import curl_cffi # noqa: F401
+ return True
+ except ImportError:
+ return False
+
+
+def _web_script_command(
+ url: str,
+ output_path: Path | None,
+ python_executable: str,
+ allow_node_fallback: bool,
+) -> tuple[str, list[str]]:
+ """Return the web backend script name and base command."""
+ host = urlparse(url).netloc.lower()
+ is_tls_sensitive = any(keyword in host for keyword in WECHAT_HOST_KEYWORDS)
+ node_backend = SOURCE_TO_MD_DIR / "web_to_md.cjs"
+
+ if (
+ allow_node_fallback
+ and is_tls_sensitive
+ and not _curl_cffi_available()
+ and node_backend.is_file()
+ and shutil.which("node")
+ ):
+ command = ["node", str(node_backend), url]
+ script_name = "web_to_md.cjs"
+ else:
+ command = [python_executable, str(SOURCE_TO_MD_DIR / "web_to_md.py"), url]
+ script_name = "web_to_md.py"
+
+ if output_path is not None:
+ command.extend(["-o", str(output_path)])
+ return script_name, command
+
+
+def build_conversion_command(
+ input_arg: str,
+ output_path: str | Path | None,
+ *,
+ forced_type: str | None = None,
+ extra_args: list[str] | None = None,
+ pdf_image_mode: str | None = None,
+ render_vector_figures: bool = False,
+ python_executable: str | None = None,
+ allow_node_web_fallback: bool = True,
+) -> ConversionCommand:
+ """Build the backend CLI command for one source-to-Markdown conversion."""
+ conversion_type = forced_type or detect_source_type(input_arg)
+ output = Path(output_path) if output_path is not None else None
+ extra = extra_args or []
+ python = python_executable or sys.executable
+
+ if conversion_type == "web":
+ if not is_url(input_arg):
+ raise ValueError("web conversion requires an http:// or https:// URL")
+ script_name, command = _web_script_command(
+ input_arg,
+ output,
+ python,
+ allow_node_web_fallback,
+ )
+ command.extend(extra)
+ return ConversionCommand(command, script_name, conversion_type, output)
+
+ if conversion_type in {"markdown", "text", "directory", "unknown"}:
+ raise ValueError(f"conversion type {conversion_type!r} has no backend command")
+
+ script_by_type = {
+ "pdf": "pdf_to_md.py",
+ "doc": "doc_to_md.py",
+ "excel": "excel_to_md.py",
+ "pptx": "ppt_to_md.py",
+ }
+ script_name = script_by_type.get(conversion_type)
+ if script_name is None:
+ raise ValueError(f"unsupported conversion type: {conversion_type}")
+ if output is None:
+ output = default_markdown_path(input_arg)
+
+ command = [
+ python,
+ str(SOURCE_TO_MD_DIR / script_name),
+ input_arg,
+ "-o",
+ str(output),
+ ]
+ if conversion_type == "pdf" and pdf_image_mode:
+ command.extend(["--images", pdf_image_mode])
+ if conversion_type == "pdf" and render_vector_figures:
+ command.append("--render-vector-figures")
+ command.extend(extra)
+ return ConversionCommand(command, script_name, conversion_type, output)
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.py
index ad3ba12c..cc691c93 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
@@ -38,6 +38,7 @@ if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
from console_encoding import configure_utf8_stdio # noqa: E402
+from _conversion_profile import write_conversion_profile_best_effort # noqa: E402
configure_utf8_stdio()
@@ -1412,17 +1413,39 @@ def convert_to_markdown(input_path: str, output_path: str | None = None) -> str:
desc = _FORMAT_DESC[suffix]
print(f"[INFO] Converting {desc}: {input_file.name}")
if suffix == ".docx":
- return _convert_docx(input_file, out_file)
- if suffix in (".html", ".htm"):
- return _convert_html(input_file, out_file)
- if suffix == ".epub":
- return _convert_epub(input_file, out_file)
- if suffix == ".ipynb":
- return _convert_ipynb(input_file, out_file)
+ markdown = _convert_docx(input_file, out_file)
+ elif suffix in (".html", ".htm"):
+ markdown = _convert_html(input_file, out_file)
+ elif suffix == ".epub":
+ markdown = _convert_epub(input_file, out_file)
+ elif suffix == ".ipynb":
+ markdown = _convert_ipynb(input_file, out_file)
+ else:
+ markdown = ""
+ if markdown:
+ profile_path = write_conversion_profile_best_effort(
+ input_path=str(input_file),
+ markdown_path=out_file,
+ converter="doc_to_md.py",
+ conversion_type=suffix.lstrip("."),
+ )
+ if profile_path:
+ print(f" Wrote conversion profile -> {profile_path}")
+ return markdown
_, format_desc = PANDOC_FORMATS[suffix]
print(f"[INFO] Converting {format_desc} via pandoc: {input_file.name}")
- return _convert_with_pandoc(input_file, out_file, suffix)
+ markdown = _convert_with_pandoc(input_file, out_file, suffix)
+ if markdown:
+ profile_path = write_conversion_profile_best_effort(
+ input_path=str(input_file),
+ markdown_path=out_file,
+ converter="doc_to_md.py",
+ conversion_type=suffix.lstrip("."),
+ )
+ if profile_path:
+ print(f" Wrote conversion profile -> {profile_path}")
+ return markdown
def main() -> None:
diff --git a/skills/ppt-master/scripts/source_to_md/excel_to_md.py b/skills/ppt-master/scripts/source_to_md/excel_to_md.py
index 42966a63..b14692b1 100644
--- a/skills/ppt-master/scripts/source_to_md/excel_to_md.py
+++ b/skills/ppt-master/scripts/source_to_md/excel_to_md.py
@@ -25,6 +25,7 @@ if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
from console_encoding import configure_utf8_stdio # noqa: E402
+from _conversion_profile import write_conversion_profile_best_effort # noqa: E402
configure_utf8_stdio()
@@ -337,7 +338,17 @@ def convert_to_markdown(
out_file.parent.mkdir(parents=True, exist_ok=True)
print(f"[INFO] Converting Excel workbook: {input_file.name}")
- return _convert_excel(input_file, out_file, max_rows=max_rows, max_cols=max_cols)
+ markdown = _convert_excel(input_file, out_file, max_rows=max_rows, max_cols=max_cols)
+ if markdown:
+ profile_path = write_conversion_profile_best_effort(
+ input_path=str(input_file),
+ markdown_path=out_file,
+ converter="excel_to_md.py",
+ conversion_type=suffix.lstrip("."),
+ )
+ if profile_path:
+ print(f" Wrote conversion profile -> {profile_path}")
+ return markdown
def main() -> None:
diff --git a/skills/ppt-master/scripts/source_to_md/pdf_to_md.py b/skills/ppt-master/scripts/source_to_md/pdf_to_md.py
index c0eb0881..d4081912 100644
--- a/skills/ppt-master/scripts/source_to_md/pdf_to_md.py
+++ b/skills/ppt-master/scripts/source_to_md/pdf_to_md.py
@@ -19,6 +19,7 @@ if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
from console_encoding import configure_utf8_stdio # noqa: E402
+from _conversion_profile import write_conversion_profile_best_effort # noqa: E402
configure_utf8_stdio()
@@ -1059,50 +1060,20 @@ def extract_pdf_to_markdown(
json.dumps(image_manifest, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
+ profile_path = write_conversion_profile_best_effort(
+ input_path=pdf_path,
+ markdown_path=output_path,
+ converter="pdf_to_md.py",
+ conversion_type="pdf",
+ asset_dir=img_dir,
+ )
print(f"[OK] Saved Markdown to: {output_path}")
+ if profile_path:
+ print(f" Wrote conversion profile -> {profile_path}")
return markdown_content
-def process_directory(
- input_dir: str,
- output_dir: str | None = None,
- images: str = "filtered",
- render_vector_figures: bool = False,
- vector_figure_dpi: int = VECTOR_FIGURE_DPI,
-) -> None:
- """Convert all PDFs in a directory to Markdown.
-
- Args:
- input_dir: Directory containing PDF files.
- output_dir: Optional output directory for Markdown files.
- images: Image extraction mode passed through to each file conversion.
- render_vector_figures: Rasterize large vector drawing regions as PNGs.
- vector_figure_dpi: DPI used for rendered vector figure PNGs.
- """
- input_path = Path(input_dir)
-
- if output_dir:
- output_path = Path(output_dir)
- else:
- output_path = input_path
-
- pdf_files = sorted(input_path.glob('*.pdf'))
-
- print(f"Found {len(pdf_files)} PDF files")
-
- for pdf_file in pdf_files:
- output_file = output_path / (pdf_file.stem + '.md')
- print(f"Processing: {pdf_file.name}")
- extract_pdf_to_markdown(
- str(pdf_file),
- str(output_file),
- images=images,
- render_vector_figures=render_vector_figures,
- vector_figure_dpi=vector_figure_dpi,
- )
-
-
def main() -> int:
"""Run the CLI entry point."""
parser = argparse.ArgumentParser(
@@ -1113,8 +1084,6 @@ Examples:
python pdf_to_md.py book.pdf # Convert a single file
python pdf_to_md.py book.pdf -o output.md # Specify output file
python pdf_to_md.py book.pdf --render-vector-figures
- python pdf_to_md.py ./pdfs # Convert all PDFs in directory
- python pdf_to_md.py ./pdfs -o ./markdown # Specify output directory
Structure detection features:
- Auto-detect heading levels (based on font size)
@@ -1126,8 +1095,8 @@ Structure detection features:
'''
)
- parser.add_argument('input', help='PDF file or directory containing PDFs')
- parser.add_argument('-o', '--output', help='Output file or directory')
+ parser.add_argument('input', help='PDF file')
+ parser.add_argument('-o', '--output', help='Output Markdown file')
parser.add_argument(
'--images',
choices=['all', 'filtered', 'none'],
@@ -1150,27 +1119,18 @@ Structure detection features:
input_path = Path(args.input)
- if input_path.is_file():
- output = args.output or str(input_path.with_suffix('.md'))
- extract_pdf_to_markdown(
- str(input_path),
- output,
- images=args.images,
- render_vector_figures=args.render_vector_figures,
- vector_figure_dpi=args.vector_figure_dpi,
- )
- elif input_path.is_dir():
- process_directory(
- str(input_path),
- args.output,
- images=args.images,
- render_vector_figures=args.render_vector_figures,
- vector_figure_dpi=args.vector_figure_dpi,
- )
- else:
- print(f"Error: File or directory not found: {args.input}")
+ if not input_path.is_file():
+ print(f"Error: PDF file not found: {args.input}")
return 1
+ output = args.output or str(input_path.with_suffix('.md'))
+ extract_pdf_to_markdown(
+ str(input_path),
+ output,
+ images=args.images,
+ render_vector_figures=args.render_vector_figures,
+ vector_figure_dpi=args.vector_figure_dpi,
+ )
return 0
diff --git a/skills/ppt-master/scripts/source_to_md/ppt_to_md.py b/skills/ppt-master/scripts/source_to_md/ppt_to_md.py
index 27960958..6bd79116 100644
--- a/skills/ppt-master/scripts/source_to_md/ppt_to_md.py
+++ b/skills/ppt-master/scripts/source_to_md/ppt_to_md.py
@@ -39,6 +39,7 @@ if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
from console_encoding import configure_utf8_stdio # noqa: E402
+from _conversion_profile import write_conversion_profile_best_effort # noqa: E402
from pptx import Presentation
from pptx.enum.action import PP_ACTION
@@ -814,8 +815,17 @@ def convert_presentation_to_markdown(
json.dumps(image_manifest, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
+ profile_path = write_conversion_profile_best_effort(
+ input_path=str(input_file),
+ markdown_path=out_file,
+ converter="ppt_to_md.py",
+ conversion_type=suffix.lstrip("."),
+ asset_dir=asset_dir,
+ )
print(f"[OK] Saved Markdown to: {out_file}")
+ if profile_path:
+ print(f" Wrote conversion profile -> {profile_path}")
if asset_dir_used:
media_files = [
path for path in asset_dir.iterdir()
@@ -832,30 +842,6 @@ def convert_presentation_to_markdown(
return markdown_content
-def process_directory(input_dir: str, output_dir: str | None = None) -> None:
- """Convert all supported PowerPoint files in a directory to Markdown."""
- input_path = Path(input_dir)
-
- if output_dir:
- output_path = Path(output_dir)
- else:
- output_path = input_path
-
- presentation_files = sorted(
- path for path in input_path.iterdir()
- if path.is_file() and path.suffix.lower() in SUPPORTED_FORMATS
- )
-
- print(f"Found {len(presentation_files)} PowerPoint files")
-
- for presentation_file in presentation_files:
- output_file = output_path / f"{presentation_file.stem}.md"
- print(f"Processing: {presentation_file.name}")
- result = convert_presentation_to_markdown(str(presentation_file), str(output_file))
- if not result:
- print(f"[WARN] Skipped failed file: {presentation_file.name}")
-
-
def main() -> None:
"""Run the CLI entry point."""
parser = argparse.ArgumentParser(
@@ -865,8 +851,6 @@ def main() -> None:
Examples:
python ppt_to_md.py slides.pptx
python ppt_to_md.py slides.pptx -o output.md
- python ppt_to_md.py ./decks
- python ppt_to_md.py ./decks -o ./markdown
python ppt_to_md.py deck.ppsx -o notes/deck.md
Supported formats:
@@ -875,22 +859,19 @@ Supported formats:
Legacy .ppt is not parsed directly. Resave it as .pptx or export it to PDF first.
""",
)
- parser.add_argument("input", help="Input PowerPoint file or directory")
- parser.add_argument("-o", "--output", help="Output Markdown file or directory path")
+ parser.add_argument("input", help="Input PowerPoint file")
+ parser.add_argument("-o", "--output", help="Output Markdown file")
args = parser.parse_args()
input_path = Path(args.input)
- if input_path.is_file():
- output = args.output or str(input_path.with_suffix(".md"))
- result = convert_presentation_to_markdown(str(input_path), output)
- sys.exit(0 if result else 1)
- if input_path.is_dir():
- process_directory(str(input_path), args.output)
- sys.exit(0)
+ if not input_path.is_file():
+ print(f"Error: PowerPoint file not found: {args.input}")
+ sys.exit(1)
- print(f"Error: File or directory not found: {args.input}")
- sys.exit(1)
+ output = args.output or str(input_path.with_suffix(".md"))
+ result = convert_presentation_to_markdown(str(input_path), output)
+ sys.exit(0 if result else 1)
if __name__ == "__main__":
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.py
index 7854b634..1c550a78 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
@@ -43,6 +43,7 @@ if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
from console_encoding import configure_utf8_stdio # noqa: E402
+from _conversion_profile import write_conversion_profile_best_effort # noqa: E402
configure_utf8_stdio()
@@ -869,8 +870,17 @@ def process_url(url: str, output_file: str | None = None) -> tuple[bool, str, st
with open(output_path, 'w', encoding='utf-8') as f:
f.write(full_content)
+ profile_path = write_conversion_profile_best_effort(
+ input_path=url,
+ markdown_path=output_path,
+ converter="web_to_md.py",
+ conversion_type="web",
+ asset_dir=image_dir,
+ )
print(f" [OK] Saved: {output_path}")
+ if profile_path:
+ print(f" [OK] Conversion profile: {profile_path}")
return True, url, None
except Exception as e: