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(tools): 修复PPT备注匹配与PNG状态污染问题,优化项目名解析
hugohe33217ed305363
diff --git a/tools/project_manager.py b/tools/project_manager.pyindex 304cb0d8..63543f72 100644--- a/tools/project_manager.py+++ b/tools/project_manager.py@@ -10,19 +10,16 @@ PPT Master - 项目管理工具python3 tools/project_manager.py info <project_path>"""-import osimport sys-import json-import refrom pathlib import Path-from datetime import datetimefrom typing import Dict, List, Optional, Tuple# 导入公共工具模块(必须成功)try:from project_utils import (CANVAS_FORMATS,- get_project_info,+ normalize_canvas_format,+ get_project_info as get_project_info_common,validate_project_structure,validate_svg_viewbox)@@ -37,7 +34,8 @@ except ImportError:try:from project_utils import (CANVAS_FORMATS,- get_project_info,+ normalize_canvas_format,+ get_project_info as get_project_info_common,validate_project_structure,validate_svg_viewbox)@@ -79,9 +77,18 @@ class ProjectManager:else:base_path = self.base_dir+ normalized_format = normalize_canvas_format(canvas_format)+ if normalized_format not in self.CANVAS_FORMATS:+ available = ', '.join(sorted(self.CANVAS_FORMATS.keys()))+ raise ValueError(+ f"不支持的画布格式: {canvas_format} "+ f"(可用: {available}; 常用别名: xhs -> xiaohongshu)"+ )+# 创建项目目录名: {project_name}_{format}_{YYYYMMDD}+ from datetime import datetimedate_str = datetime.now().strftime('%Y%m%d')- project_dir_name = f"{project_name}_{canvas_format}_{date_str}"+ project_dir_name = f"{project_name}_{normalized_format}_{date_str}"project_path = base_path / project_dir_nameif project_path.exists():@@ -94,10 +101,24 @@ class ProjectManager:(project_path / 'images').mkdir(exist_ok=True) # 图片资源(project_path / 'notes').mkdir(exist_ok=True) # 演讲备注(project_path / 'templates').mkdir(exist_ok=True) # 项目页面模板(可选)+ readme_path = project_path / 'README.md'+ readme_path.write_text(+ (+ f"# {project_name}\n\n"+ f"- 画布格式: {normalized_format}\n"+ f"- 创建日期: {date_str}\n\n"+ "## 目录\n\n"+ "- `svg_output/`: 原始 SVG 输出\n"+ "- `svg_final/`: 后处理后的 SVG\n"+ "- `images/`: 图片资源\n"+ "- `notes/`: 演讲备注\n"+ "- `templates/`: 项目模板\n"+ ),+ encoding='utf-8'+ )# 获取画布格式信息- canvas_info = self.CANVAS_FORMATS.get(- canvas_format, self.CANVAS_FORMATS['ppt169'])+ canvas_info = self.CANVAS_FORMATS[normalized_format]# 提示用户下一步操作 (不再自动创建空的设计规范文件)print(f"项目目录已创建: {project_path}")@@ -114,81 +135,19 @@ class ProjectManager:Returns:(是否有效, 错误列表, 警告列表)"""- project_path = Path(project_path)- errors = []- warnings = []-- # 检查目录是否存在- if not project_path.exists():- errors.append(f"项目目录不存在: {project_path}")- return False, errors, warnings-- if not project_path.is_dir():- errors.append(f"不是有效的目录: {project_path}")- return False, errors, warnings-- # 检查设计规范文件(核心必需文件)- spec_files = ['设计规范与内容大纲.md', 'design_specification.md', '设计规范.md']- has_spec = any((project_path / f).exists() for f in spec_files)- if not has_spec:- errors.append("缺少设计规范文件(建议文件名: 设计规范与内容大纲.md)")-- # 检查 svg_output 目录- svg_output = project_path / 'svg_output'- if not svg_output.exists():- errors.append("缺少 svg_output 目录")- else:- # 检查 SVG 文件- svg_files = list(svg_output.glob('*.svg'))- if len(svg_files) == 0:- warnings.append("svg_output 目录为空")- else:- # 验证 SVG 文件命名(支持两种格式)- # 格式1: slide_01_name.svg(英文项目)- # 格式2: 01_封面.svg 或 P01_封面.svg(中文项目)- for svg_file in svg_files:- if not re.match(r'^(slide_\d+_\w+|P?\d+_.+)\.svg$', svg_file.name):- warnings.append(- f"SVG 文件命名不规范: {svg_file.name} (建议: 01_名称.svg 或 slide_01_name.svg)")-- # 检查 viewBox- self._validate_svg_viewbox(svg_files, warnings)-- # 检查项目命名格式(支持所有画布格式)- dir_name = project_path.name- canvas_formats = '|'.join(self.CANVAS_FORMATS.keys())- pattern = rf'^.+_({canvas_formats})_\d{{8}}$'- if not re.match(pattern, dir_name, re.IGNORECASE):- warnings.append(- f"项目目录命名不规范: {dir_name} (建议: name_format_YYYYMMDD)")-- is_valid = len(errors) == 0- return is_valid, errors, warnings+ project_path_obj = Path(project_path)+ is_valid, errors, warnings = validate_project_structure(str(project_path_obj))++ if project_path_obj.exists() and project_path_obj.is_dir():+ info = get_project_info_common(str(project_path_obj))+ if info.get('svg_files'):+ svg_files = [project_path_obj / 'svg_output' / f for f in info['svg_files']]+ expected_format = info.get('format')+ if expected_format == 'unknown':+ expected_format = None+ warnings.extend(validate_svg_viewbox(svg_files, expected_format))- def _validate_svg_viewbox(self, svg_files: List[Path], warnings: List[str]):- """验证 SVG 文件的 viewBox 设置-- Args:- svg_files: SVG 文件列表- warnings: 警告列表(会被修改)- """- viewbox_pattern = re.compile(r'viewBox="([^"]+)"')- viewboxes = set()-- for svg_file in svg_files[:5]: # 只检查前5个文件- try:- with open(svg_file, 'r', encoding='utf-8') as f:- content = f.read(1000) # 只读取前1000字符- match = viewbox_pattern.search(content)- if match:- viewboxes.add(match.group(1))- else:- warnings.append(f"{svg_file.name}: 未找到 viewBox 属性")- except Exception as e:- warnings.append(f"{svg_file.name}: 读取失败 - {e}")-- if len(viewboxes) > 1:- warnings.append(f"检测到多个不同的 viewBox 设置: {viewboxes}")+ return is_valid, errors, warningsdef get_project_info(self, project_path: str) -> Dict:"""获取项目信息@@ -199,50 +158,17 @@ class ProjectManager:Returns:项目信息字典"""- project_path = Path(project_path)- info = {- 'name': project_path.name,- 'path': str(project_path),- 'exists': project_path.exists(),- 'svg_count': 0,- 'has_spec': False,- 'canvas_format': 'unknown',- 'create_date': 'unknown'+ shared = get_project_info_common(project_path)+ return {+ 'name': shared.get('name', Path(project_path).name),+ 'path': shared.get('path', str(project_path)),+ 'exists': shared.get('exists', False),+ 'svg_count': shared.get('svg_count', 0),+ 'has_spec': shared.get('has_spec', False),+ 'canvas_format': shared.get('format_name', '未知格式'),+ 'create_date': shared.get('date_formatted', '未知日期')}- if not project_path.exists():- return info-- # 统计 SVG 文件- svg_output = project_path / 'svg_output'- if svg_output.exists():- info['svg_count'] = len(list(svg_output.glob('*.svg')))-- # 检查设计规范- spec_files = ['设计规范与内容大纲.md', 'design_specification.md', '设计规范.md']- info['has_spec'] = any((project_path / f).exists() for f in spec_files)-- # 从目录名提取信息- dir_name = project_path.name-- # 提取画布格式- for fmt in self.CANVAS_FORMATS.keys():- if fmt in dir_name.lower():- info['canvas_format'] = self.CANVAS_FORMATS[fmt]['name']- break-- # 提取日期- date_match = re.search(r'_(\d{8})$', dir_name)- if date_match:- date_str = date_match.group(1)- try:- date_obj = datetime.strptime(date_str, '%Y%m%d')- info['create_date'] = date_obj.strftime('%Y-%m-%d')- except ValueError:- pass-- return info-def main():"""主函数"""diff --git a/tools/project_utils.py b/tools/project_utils.pyindex 41f01ca9..f8cccc24 100644--- a/tools/project_utils.py+++ b/tools/project_utils.py@@ -66,6 +66,22 @@ except ImportError:}}+CANVAS_FORMAT_ALIASES = {+ 'xhs': 'xiaohongshu',+ 'wechat_moment': 'moments',+ 'wechat-moment': 'moments',+ '朋友圈': 'moments',+ '小红书': 'xiaohongshu',+}+++def normalize_canvas_format(format_key: str) -> str:+ """标准化画布格式键名(支持常见别名)。"""+ if not format_key:+ return ''+ key = format_key.strip().lower()+ return CANVAS_FORMAT_ALIASES.get(key, key)+def parse_project_name(dir_name: str) -> Dict[str, str]:"""@@ -85,12 +101,7 @@ def parse_project_name(dir_name: str) -> Dict[str, str]:'date_formatted': '未知日期'}- # 提取画布格式- for fmt_key, fmt_info in CANVAS_FORMATS.items():- if fmt_key in dir_name.lower():- result['format'] = fmt_key- result['format_name'] = fmt_info['name']- break+ dir_name_lower = dir_name.lower()# 提取日期 (格式: _YYYYMMDD)date_match = re.search(r'_(\d{8})$', dir_name)@@ -103,11 +114,29 @@ def parse_project_name(dir_name: str) -> Dict[str, str]:except ValueError:pass- # 提取项目名称(去除格式和日期后缀)- name = dir_name- for fmt_key in CANVAS_FORMATS.keys():- name = re.sub(f'_{fmt_key}', '', name, flags=re.IGNORECASE)- name = re.sub(r'_\d{8}$', '', name)+ # 优先按标准格式解析: name_format_YYYYMMDD+ full_match = re.match(r'^(?P<name>.+)_(?P<format>[a-z0-9_-]+)_(?P<date>\d{8})$', dir_name_lower)+ if full_match:+ raw_format = full_match.group('format')+ normalized_format = normalize_canvas_format(raw_format)+ if normalized_format in CANVAS_FORMATS:+ result['format'] = normalized_format+ result['format_name'] = CANVAS_FORMATS[normalized_format]['name']+ result['name'] = dir_name[:len(full_match.group('name'))]+ return result++ # 兜底:只匹配末尾 `_format`,避免误删项目名内部片段+ sorted_formats = sorted(CANVAS_FORMATS.keys(), key=len, reverse=True)+ for fmt_key in sorted_formats:+ if re.search(rf'_{re.escape(fmt_key)}(?:_\d{{8}})?$', dir_name_lower):+ result['format'] = fmt_key+ result['format_name'] = CANVAS_FORMATS[fmt_key]['name']+ break++ # 提取项目名称(仅移除末尾日期和格式后缀)+ name = re.sub(r'_\d{8}$', '', dir_name)+ if result['format'] != 'unknown':+ name = re.sub(rf'_{re.escape(result["format"])}$', '', name, flags=re.IGNORECASE)result['name'] = namereturn resultdiff --git a/tools/svg_quality_checker.py b/tools/svg_quality_checker.pyindex c97081c5..2962beb8 100644--- a/tools/svg_quality_checker.py+++ b/tools/svg_quality_checker.py@@ -147,7 +147,7 @@ class SVGQualityChecker:# 裁剪 / 遮罩if '<clippath' in content_lower:result['errors'].append("检测到禁用的 <clipPath> 元素(PPT 不支持 SVG 裁剪路径)")- if '<mask' in content_lower and '<mask>' not in content_lower: # 排除纯文本 "mask"+ if '<mask' in content_lower:result['errors'].append("检测到禁用的 <mask> 元素(PPT 不支持 SVG 遮罩)")# 样式系统diff --git a/tools/svg_to_pptx.py b/tools/svg_to_pptx.pyindex 423722e2..546d2f22 100644--- a/tools/svg_to_pptx.py+++ b/tools/svg_to_pptx.py@@ -284,7 +284,7 @@ def find_notes_files(project_path: Path, svg_files: List[Path] = None) -> dict:svg_files: SVG 文件列表(用于按文件名匹配)Returns:- 字典,key 为 SVG 文件名(不含扩展名)或幻灯片编号,value 为备注内容+ 字典,key 为 SVG 文件名(不含扩展名),value 为备注内容"""notes_dir = project_path / 'notes'notes = {}@@ -293,11 +293,12 @@ def find_notes_files(project_path: Path, svg_files: List[Path] = None) -> dict:return notessvg_stems_mapping = {}-+ svg_index_mapping = {}if svg_files:for i, svg_path in enumerate(svg_files, 1):svg_stems_mapping[svg_path.stem] = i-+ svg_index_mapping[i] = svg_path.stem+# 收集所有 notes 文件信息for notes_file in notes_dir.glob('*.md'):try:@@ -311,11 +312,14 @@ def find_notes_files(project_path: Path, svg_files: List[Path] = None) -> dict:# 尝试提取序号(向后兼容 slide01.md 格式)match = re.search(r'slide[_]?(\d+)', stem)if match:- notes[int(match.group(1))] = content+ index = int(match.group(1))+ mapped_stem = svg_index_mapping.get(index)+ if mapped_stem:+ notes[mapped_stem] = content# 按文件名提取(覆盖向后兼容的格式)if stem in svg_stems_mapping:- notes[svg_stems_mapping[stem]] = content+ notes[stem] = contentexcept Exception:pass@@ -709,7 +713,7 @@ def create_pptx_with_native_svg(# 处理每个 SVG 文件success_count = 0- png_generated = False+ any_png_generated = Falsefor i, svg_path in enumerate(svg_files, 1):slide_num = i@@ -723,6 +727,7 @@ def create_pptx_with_native_svg(shutil.copy(svg_path, media_dir / svg_filename)# 兼容模式:生成 PNG 后备图片+ slide_has_png = Falseif use_compat_mode:png_path = media_dir / png_filenamepng_success = convert_svg_to_png(@@ -732,7 +737,8 @@ def create_pptx_with_native_svg(height=pixel_height)if png_success:- png_generated = True+ slide_has_png = True+ any_png_generated = Trueelse:# PNG 生成失败,降级为纯 SVGif verbose:@@ -750,7 +756,7 @@ def create_pptx_with_native_svg(transition=transition,transition_duration=transition_duration,auto_advance=auto_advance,- use_compat_mode=(use_compat_mode and png_generated)+ use_compat_mode=(use_compat_mode and slide_has_png))with open(slide_xml_path, 'w', encoding='utf-8') as f:f.write(slide_xml)@@ -764,16 +770,17 @@ def create_pptx_with_native_svg(png_filename=png_filename,svg_rid=svg_rid,svg_filename=svg_filename,- use_compat_mode=(use_compat_mode and png_generated)+ use_compat_mode=(use_compat_mode and slide_has_png))with open(rels_path, 'w', encoding='utf-8') as f:f.write(rels_xml)# 处理备注+ notes_content = ''if enable_notes:# 按文件名匹配(新逻辑)或按序号匹配(向后兼容)svg_stem = svg_path.stem- notes_content = notes.get(svg_stem, notes.get(i, '')) if notes else ''+ notes_content = notes.get(svg_stem, '') if notes else ''if notes_content:notes_text = markdown_to_plain_text(notes_content)else:@@ -806,8 +813,8 @@ def create_pptx_with_native_svg(f.write(slide_rels_content)if verbose:- mode_str = " (PNG+SVG)" if (use_compat_mode and png_generated) else " (SVG)"- has_notes = enable_notes and notes and (notes.get(svg_stem) or notes.get(i))+ mode_str = " (PNG+SVG)" if (use_compat_mode and slide_has_png) else " (SVG)"+ has_notes = enable_notes and bool(notes_content)notes_str = " +备注" if has_notes else ""print(f" [{i}/{len(svg_files)}] {svg_path.name}{mode_str}{notes_str}")@@ -826,7 +833,7 @@ def create_pptx_with_native_svg(types_to_add = []if 'Extension="svg"' not in content_types:types_to_add.append(' <Default Extension="svg" ContentType="image/svg+xml"/>')- if png_generated and 'Extension="png"' not in content_types:+ if any_png_generated and 'Extension="png"' not in content_types:types_to_add.append(' <Default Extension="png" ContentType="image/png"/>')if types_to_add:@@ -857,7 +864,7 @@ def create_pptx_with_native_svg(print()print(f"[完成] 已保存: {output_path}")print(f" 成功: {success_count}, 失败: {len(svg_files) - success_count}")- if use_compat_mode and png_generated:+ if use_compat_mode and any_png_generated:print(f" 模式: Office 兼容模式 (支持所有 Office 版本)")# 如果使用 svglib,给出升级提示if PNG_RENDERER == 'svglib' and renderer_hint: