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(tools): 添加 PDF 转 Markdown 本地转换工具
hugohe3990ccebf7cef
diff --git a/AGENTS.md b/AGENTS.mdindex e4754054..320ce99b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -206,6 +206,9 @@ Optimizer_CRAP (可选)## 常用命令```bash+# PDF 转 Markdown(优先使用,本地快速)+python3 tools/pdf_to_md.py <PDF文件>+# 初始化项目python3 tools/project_manager.py init <名称> --format ppt169@@ -252,6 +255,19 @@ project/- [ ] **重复**: 同类元素风格一致- [ ] **亲密性**: 相关内容空间聚合+## PDF 转 Markdown 工具选择++| 场景 | 推荐工具 | 命令 |+|------|----------|------|+| **原生 PDF**(Word/LaTeX 导出) | `pdf_to_md.py` | `python3 tools/pdf_to_md.py <文件>` |+| **简单表格** | `pdf_to_md.py` | 同上 |+| **隐私敏感文档** | `pdf_to_md.py` | 同上(数据不出本机) |+| **扫描版/图片 PDF** | MinerU | 需要 OCR |+| **复杂多栏排版** | MinerU | 版面分析更准 |+| **数学公式** | MinerU | AI 识别能力强 |++> **策略**: PyMuPDF 优先,MinerU 兜底。先运行 `pdf_to_md.py`,如结果乱码/空白再换 MinerU。+## 重要资源| 资源 | 路径 |diff --git a/README.md b/README.mdindex 70902901..3fa12abf 100644--- a/README.md+++ b/README.md@@ -199,13 +199,15 @@ graph TDclassDef external fill:#eee,stroke:#999,stroke-width:1px,stroke-dasharray: 5 5;%% 流程入口- RawDoc([原始参考资料 PDF/Word]) --> Mineru+ RawDoc([原始参考资料 PDF/Word]) --> PDFConvert{PDF 类型?}%% 准备阶段subgraph Preparation [准备阶段 Resources Prep]- Mineru[Mineru 智能转换工具]:::tool+ PDFConvert -- 原生 PDF --> PyMuPDF[pdf_to_md.py 本地转换]:::tool+ PDFConvert -- 扫描版/复杂排版 --> Mineru[MinerU 云端 AI 转换]:::tool- Mineru -- 提取文本与结构 --> MD([基础 Markdown 文档]):::artifact+ PyMuPDF -- 提取文本与结构 --> MD([基础 Markdown 文档]):::artifact+ Mineru -- 提取文本与结构 --> MD%% 图片处理流程subgraph ImageFlow [图片资源]@@ -426,11 +428,11 @@ graph TD| 步骤 | 说明 ||------|------|- | 📄 **文档转换** | 使用 [MinerU](https://github.com/opendatalab/MinerU) 将 PDF/Word 转换为 Markdown。MinerU 是一个开源的智能文档转换工具,可保留文档结构、提取表格和公式 |+ | 📄 **文档转换** | **优先使用** `python3 tools/pdf_to_md.py <PDF文件>` 进行本地转换(快速、免费、隐私安全)。如遇扫描版 PDF、复杂多栏排版或数学公式,改用 [MinerU](https://github.com/opendatalab/MinerU) 云端 AI 转换 || 🖼️ **图片资源** | 将必须包含的图片存入项目的 `images/` 文件夹,并在 Markdown 中添加图片描述说明 || 🔣 **图标资源** | 如需自定义图标,可从 [SVG Repo](https://www.svgrepo.com/) 下载,或使用项目内置的 640+ 图标库(`templates/icons/`) |- > 💡 **提示**:MinerU 支持 CPU/GPU 环境,兼容 Windows/Linux/Mac,可自动识别公式并转换为 LaTeX+ > 💡 **PDF 转换策略**: PyMuPDF 优先(本地秒级),MinerU 兜底(云端 AI)。详见 [工具使用指南](./tools/README.md)2. **初始沟通(八项确认)**与 Strategist 进行范围确认,Strategist 会对以下八项给出专业建议:diff --git a/README_EN.md b/README_EN.mdindex ad98872d..819755d9 100644--- a/README_EN.md+++ b/README_EN.md@@ -8,7 +8,7 @@ English | [中文](./README.md)An AI-powered intelligent visual content generation system that transforms source documents into high-quality SVG content through collaboration of multiple professional roles, **supporting presentations, social media, marketing posters, and various other formats**.-> 🎴 **Online Examples**: [Slides Gallery](https://notes.36sjs.com/pages/ppt/slides-library.html) - View actual generated results+> 🎴 **Online Examples**: [GitHub Pages Online Preview](https://hugohe3.github.io/ppt-master/) - View actual generated results> 🎬 **Quick Demo**: [YouTube](https://www.youtube.com/watch?v=jM2fHmvMwx0) | [Bilibili](https://www.bilibili.com/video/BV1iUmQBtEGH/) - Watch video demonstrations@@ -46,7 +46,7 @@ An AI-powered intelligent visual content generation system that transforms sourc```User: I have a Q3 quarterly report that needs to be made into a PPT-AI (Strategist role): Sure, before we begin I need to complete seven confirmations...+AI (Strategist role): Sure, before we begin I need to complete eight confirmations...1. Canvas format: [Recommended] PPT 16:92. Page count: [Recommended] 8-10 pages...@@ -199,13 +199,15 @@ graph TDclassDef external fill:#eee,stroke:#999,stroke-width:1px,stroke-dasharray: 5 5;%% Entry Point- RawDoc([Raw Reference Materials PDF/Word]) --> Mineru+ RawDoc([Raw Reference Materials PDF/Word]) --> PDFConvert{PDF Type?}%% Preparation Stagesubgraph Preparation [Preparation Stage - Resources Prep]- Mineru[MinerU Intelligent Conversion Tool]:::tool+ PDFConvert -- Native PDF --> PyMuPDF[pdf_to_md.py Local Conversion]:::tool+ PDFConvert -- Scanned/Complex Layout --> Mineru[MinerU Cloud AI Conversion]:::tool- Mineru -- Extract Text & Structure --> MD([Basic Markdown Document]):::artifact+ PyMuPDF -- Extract Text & Structure --> MD([Basic Markdown Document]):::artifact+ Mineru -- Extract Text & Structure --> MD%% Image Processing Flowsubgraph ImageFlow [Image Resources]@@ -229,7 +231,7 @@ graph TDStrategist[Role 1 Strategist: Content & Specifications]:::role%% Interactive Confirmation- Strategist -.-> Confirm1[Interactive Confirmation: 7 Key Elements]:::userAction+ Strategist -.-> Confirm1[Interactive Confirmation: 8 Key Elements]:::userActionConfirm1 -- Confirm Scope --> Strategist%% Notes@@ -293,7 +295,7 @@ graph TD**Core Capabilities**:-- **Initial Communication (Seven Confirmations)**: Must complete the following confirmations before analyzing content, providing professional recommendations:+- **Initial Communication (Eight Confirmations)**: Must complete the following confirmations before analyzing content, providing professional recommendations:1. 📐 **Canvas Format**: Recommend the most suitable format based on usage scenario (PPT/Xiaohongshu/WeChat Moments, etc.)2. 📊 **Page Count**: Suggest reasonable page range based on content volume and complexity3. 🎯 **Target Audience & Scenario**: Pre-judge target audience and usage scenario based on document characteristics@@ -301,6 +303,7 @@ graph TD5. 🎨 **Color Scheme**: Provide specific HEX values for primary, secondary, and accent colors6. 🔣 **Icon Method**: A) Emoji B) AI Generated C) Built-in Icon Library D) Custom Path7. 🖼️ **Image Usage**: A) No images B) User provided C) AI Generated D) Placeholder reserved+ 8. 📝 **Font Scheme**: Recommend font combinations based on content characteristics (Title/Body/Emphasis)- **Intelligent Deconstruction**: Break down and reorganize source documents into clear page sequences- **Color Scheme**: Propose complete color scheme (primary, secondary, base tones)- **Layout Planning**: Plan page sequences and recommend layout solutions@@ -317,7 +320,7 @@ graph TD**Responsibility**: AI image generation (conditionally triggered)**Output**: Image files + optimized prompts-**Trigger Condition**: Only called when user selects "C) AI Generated" for image method in Strategist's seven confirmations+**Trigger Condition**: Only called when user selects "C) AI Generated" for image method in Strategist's eight confirmations**Workflow Position**: After Strategist, before Executor (sequential, not parallel)@@ -433,14 +436,14 @@ graph TD| Step | Description ||------|------|- | 📄 **Document Conversion** | Use [MinerU](https://github.com/opendatalab/MinerU) to convert PDF/Word to Markdown. MinerU is an open-source intelligent document conversion tool that preserves document structure, extracts tables and formulas |+ | 📄 **Document Conversion** | **Prefer** `python3 tools/pdf_to_md.py <PDF_file>` for local conversion (fast, free, privacy-safe). For scanned PDFs, complex multi-column layouts, or math formulas, use [MinerU](https://github.com/opendatalab/MinerU) cloud AI conversion || 🖼️ **Image Resources** | Store required images in the project's `images/` folder and add image descriptions in the Markdown || 🔣 **Icon Resources** | For custom icons, download from [SVG Repo](https://www.svgrepo.com/), or use the built-in 640+ icon library (`templates/icons/`) |- > 💡 **Tip**: MinerU supports CPU/GPU environments, compatible with Windows/Linux/Mac, can automatically recognize formulas and convert to LaTeX+ > 💡 **PDF Conversion Strategy**: PyMuPDF first (local, instant), MinerU as fallback (cloud AI). See [Tools Usage Guide](./tools/README.md)-2. **Initial Communication (Seven Confirmations)**- Conduct scope confirmation with Strategist, who will provide professional recommendations on these seven items:+2. **Initial Communication (Eight Confirmations)**+ Conduct scope confirmation with Strategist, who will provide professional recommendations on these eight items:1. **Canvas Format**: PPT/Xiaohongshu/WeChat Moments/Story, etc. (recommend based on usage scenario)2. **Page Count**: Suggest reasonable page count based on content volume analysis@@ -449,6 +452,7 @@ graph TD5. **Color Scheme**: Primary, secondary, accent colors (provide specific HEX values)6. **Icon Method**: A) Emoji B) AI Generated C) Built-in Icon Library D) Custom Path7. **Image Usage**: A) No images B) User provided C) AI Generated D) Placeholder reserved+ 8. **Font Scheme**: Recommend font combinations based on content characteristics (Title/Body/Emphasis)💡 Strategist will not only ask questions but also proactively provide professional recommendations for your reference or confirmation@@ -482,7 +486,7 @@ graph TD```User: I have a market analysis report that needs to be made into a presentation-Strategist: Before I start analyzing your content, I need to complete seven confirmations:+Strategist: Before I start analyzing your content, I need to complete eight confirmations:1. Canvas Format: [Recommended] PPT 16:9 (1280×720), suitable for business presentation scenarios@@ -564,7 +568,7 @@ I will analyze page 2 and apply CRAP principles:- **ViewBox**: Matches canvas size- **Background**: Defined using `<rect>` element- **Text**: `<foreignObject>` disabled, use `<tspan>` for manual line breaks-- **Fonts**: Prefer system UI font stack+- **Fonts**: Use the font scheme specified in the Design Specification (see [Font Selection](./docs/design_guidelines.md#font-selection))### PPT Compatibility Rules (Must Follow)@@ -784,7 +788,7 @@ A:<details><summary><b>Q: When is Image_Generator used?</b></summary>-A: Image_Generator is only triggered when you select "C) AI Generated" for the image method during Strategist's seven confirmations. It generates optimized prompts and images before the Executor phase, so Executor can directly reference the generated images.+A: Image_Generator is only triggered when you select "C) AI Generated" for the image method during Strategist's eight confirmations. It generates optimized prompts and images before the Executor phase, so Executor can directly reference the generated images.</details>diff --git a/tools/README.md b/tools/README.mdindex a8fc085f..ea12f863 100644--- a/tools/README.md+++ b/tools/README.md@@ -4,6 +4,55 @@## 工具列表+### 0. pdf_to_md.py — PDF 转 Markdown 工具(推荐首选)++使用 PyMuPDF 将 PDF 文档转换为 Markdown 格式,本地运行、快速、免费。++**功能**:++- 提取 PDF 文本内容并转换为 Markdown+- 自动提取表格并转换为 Markdown 表格+- 自动提取图片并保存到 `images/` 目录+- 支持批量处理目录下的所有 PDF++**用法**:++```bash+# 转换单个文件+python3 tools/pdf_to_md.py book.pdf++# 指定输出文件+python3 tools/pdf_to_md.py book.pdf -o output.md++# 转换目录下所有 PDF+python3 tools/pdf_to_md.py ./pdfs++# 指定输出目录+python3 tools/pdf_to_md.py ./pdfs -o ./markdown+```++**何时使用 pdf_to_md.py vs MinerU**:++| 场景 | 推荐工具 | 原因 |+|------|----------|------|+| **原生 PDF**(Word/LaTeX 导出) | `pdf_to_md.py` | 本地、秒级、免费 |+| **简单表格** | `pdf_to_md.py` | 已支持表格提取 |+| **隐私敏感文档** | `pdf_to_md.py` | 数据不出本机 |+| **扫描版/图片 PDF** | MinerU | 需要 OCR |+| **复杂多栏排版** | MinerU | 版面分析更准 |+| **数学公式** | MinerU | AI 识别能力强 |+| **乱码 PDF**(编码丢失) | MinerU | 视觉识别兜底 |++> **策略**: PyMuPDF 优先,MinerU 兜底。先运行 `pdf_to_md.py`,如结果乱码/空白/排版错乱再换 MinerU。++**依赖**:++```bash+pip install PyMuPDF+```++---+### 1. project_utils.py — 项目工具公共模块提供项目信息解析、验证等公共功能,供其他工具复用。diff --git a/tools/pdf_to_md.py b/tools/pdf_to_md.pynew file mode 100644index 00000000..bf6d26d6--- /dev/null+++ b/tools/pdf_to_md.py@@ -0,0 +1,221 @@+#!/usr/bin/env python3+"""+PDF 转 Markdown 工具+使用 PyMuPDF 提取 PDF 文本内容并转换为 Markdown 格式+"""++import fitz # PyMuPDF+import argparse+import os+import re+from pathlib import Path+++def clean_text(text: str) -> str:+ """清理提取的文本"""+ # 移除多余的空白行+ lines = text.split('\n')+ cleaned_lines = []+ prev_empty = False++ for line in lines:+ line = line.rstrip()+ is_empty = len(line.strip()) == 0++ if is_empty:+ if not prev_empty:+ cleaned_lines.append('')+ prev_empty = True+ else:+ cleaned_lines.append(line)+ prev_empty = False++ return '\n'.join(cleaned_lines)+++def extract_pdf_to_markdown(pdf_path: str, output_path: str = None) -> str:+ """+ 从 PDF 提取文本、图片和表格并转换为 Markdown+ """+ try:+ doc = fitz.open(pdf_path)+ except Exception as e:+ print(f"❌ 无法打开 PDF 文件: {e}")+ return ""++ filename = Path(pdf_path).stem+ title = re.sub(r'^\d+-', '', filename).strip()++ markdown_content = f"# {title}\n\n"++ # 准备图片保存目录+ img_dir = None+ rel_img_dir = "images"+ if output_path:+ output_path = Path(output_path)+ img_dir = output_path.parent / rel_img_dir+ if not img_dir.exists():+ img_dir.mkdir(parents=True, exist_ok=True)++ img_count = 0++ for page_num, page in enumerate(doc, 1):+ # 1. 查找表格+ try:+ tabs = page.find_tables()+ except Exception:+ tabs = []++ tab_rects = [fitz.Rect(t.bbox) for t in tabs]++ # 收集页面素有元素: (y0, type, content)+ # type: 0=text, 1=image, 2=table+ page_elements = []++ # 添加表格到列表+ for tab in tabs:+ page_elements.append({+ "y0": tab.bbox[1],+ "type": 2,+ "content": tab.to_markdown()+ })+ print(f" ✓ 发现表格: P{page_num}")++ # 获取所有文本和图片块+ blocks = page.get_text("dict")["blocks"]++ for block in blocks:+ block_rect = fitz.Rect(block["bbox"])++ # 检查块是否在某个表格区域内+ is_in_table = False+ for tab_rect in tab_rects:+ # 如果重叠面积超过 60%,认为该块属于表格,跳过(避免内容重复)+ # 使用 intersect 计算交集+ intersect = block_rect & tab_rect+ if intersect.get_area() > 0.6 * block_rect.get_area():+ is_in_table = True+ break++ if is_in_table:+ continue++ if block["type"] == 0: # 文本块+ text = ""+ for line in block["lines"]:+ for span in line["spans"]:+ text += span["text"]+ text += "\n"++ cleaned = clean_text(text)+ if cleaned:+ page_elements.append({+ "y0": block["bbox"][1],+ "type": 0,+ "content": cleaned+ })++ elif block["type"] == 1: # 图片块+ page_elements.append({+ "y0": block["bbox"][1],+ "type": 1,+ "content": block # 暂存 block 数据后续处理+ })++ # 按垂直位置(y0)排序,还原页面阅读顺序+ page_elements.sort(key=lambda x: x["y0"])++ # 生成 Markdown 内容+ for el in page_elements:+ if el["type"] == 0: # Text+ markdown_content += el["content"] + "\n\n"++ elif el["type"] == 2: # Table+ markdown_content += el["content"] + "\n\n"++ elif el["type"] == 1: # Image+ if img_dir:+ block = el["content"]+ ext = block["ext"]+ image_data = block["image"]+ safe_filename = filename.replace(" ", "_")+ image_name = f"{safe_filename}_p{page_num}_{img_count}.{ext}"+ image_path = img_dir / image_name++ try:+ with open(image_path, "wb") as f:+ f.write(image_data)++ markdown_content += f"\n\n"+ img_count += 1+ print(f" ✓ 提取图片: {image_name}")+ except Exception as e:+ print(f" ⚠️ 图片保存失败: {e}")++ doc.close()++ # 移除末尾多余的换行+ markdown_content = markdown_content.strip() + "\n"++ if output_path:+ os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True)+ with open(output_path, 'w', encoding='utf-8') as f:+ f.write(markdown_content)+ print(f"✓ 保存 Markdown 到: {output_path}")++ return markdown_content+++def process_directory(input_dir: str, output_dir: str = None):+ """处理目录下的所有 PDF 文件"""+ 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"找到 {len(pdf_files)} 个 PDF 文件")++ for pdf_file in pdf_files:+ output_file = output_path / (pdf_file.stem + '.md')+ print(f"处理: {pdf_file.name}")+ extract_pdf_to_markdown(str(pdf_file), str(output_file))+++def main():+ parser = argparse.ArgumentParser(+ description='PDF 转 Markdown 工具',+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog='''+示例:+ python pdf_to_md.py book.pdf # 转换单个文件+ python pdf_to_md.py book.pdf -o output.md # 指定输出文件+ python pdf_to_md.py ./pdfs # 转换目录下所有 PDF+ python pdf_to_md.py ./pdfs -o ./markdown # 指定输出目录+'''+ )++ parser.add_argument('input', help='PDF 文件或包含 PDF 的目录')+ parser.add_argument('-o', '--output', help='输出文件或目录')++ args = parser.parse_args()++ 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)+ elif input_path.is_dir():+ process_directory(str(input_path), args.output)+ else:+ print(f"错误: 找不到文件或目录: {args.input}")+ return 1++ return 0+++if __name__ == '__main__':+ exit(main())