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

feat(svg): 完善 SVG 禁用功能黑名单验证机制

hugohe38842e898780f
diff --git a/AGENTS.md b/AGENTS.md
index 34a4f9f1..c23c80c4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,14 +8,14 @@ PPT Master 是一个 AI 驱动的多格式 SVG 内容生成系统,通过四角
## 角色与流程速查
-| 角色 | 文件 | 职责 |
-|------|------|------|
-| **Strategist** | `roles/Strategist.md` | 初次沟通、内容分析、设计规范编制 |
-| **Image_Generator** | `roles/Image_Generator.md` | AI 图片生成(条件触发) |
-| **Executor_General** | `roles/Executor_General.md` | 通用灵活风格 SVG 生成 |
-| **Executor_Consultant** | `roles/Executor_Consultant.md` | 一般咨询风格 SVG 生成 |
-| **Executor_Consultant_Top** | `roles/Executor_Consultant_Top.md` | 顶级咨询风格 SVG 生成(MBB 级) |
-| **Optimizer_CRAP** | `roles/Optimizer_CRAP.md` | CRAP 原则视觉优化(可选) |
+| 角色 | 文件 | 职责 |
+| --------------------------- | ---------------------------------- | -------------------------------- |
+| **Strategist** | `roles/Strategist.md` | 初次沟通、内容分析、设计规范编制 |
+| **Image_Generator** | `roles/Image_Generator.md` | AI 图片生成(条件触发) |
+| **Executor_General** | `roles/Executor_General.md` | 通用灵活风格 SVG 生成 |
+| **Executor_Consultant** | `roles/Executor_Consultant.md` | 一般咨询风格 SVG 生成 |
+| **Executor_Consultant_Top** | `roles/Executor_Consultant_Top.md` | 顶级咨询风格 SVG 生成(MBB 级) |
+| **Optimizer_CRAP** | `roles/Optimizer_CRAP.md` | CRAP 原则视觉优化(可选) |
### 工作流程
@@ -45,14 +45,14 @@ Optimizer_CRAP (可选)
**在执行任何阶段之前,必须先使用 `view_file` 工具阅读对应的角色定义文件:**
-| 阶段 | 必须阅读的文件 | 触发条件 |
-|------|---------------|----------|
-| 策略规划 | `roles/Strategist.md` | 用户提出新的PPT/内容生成需求 |
-| 图片生成 | `roles/Image_Generator.md` | 图片方式包含「C) AI 生成」(如 C、B+C、C+D) |
-| 通用风格执行 | `roles/Executor_General.md` | 用户选择「A) 通用灵活」设计风格 |
-| 咨询风格执行 | `roles/Executor_Consultant.md` | 用户选择「B) 一般咨询」设计风格 |
-| 顶级咨询执行 | `roles/Executor_Consultant_Top.md` | 用户选择「C) 顶级咨询」设计风格 |
-| 视觉优化 | `roles/Optimizer_CRAP.md` | 用户要求优化或主动建议优化 |
+| 阶段 | 必须阅读的文件 | 触发条件 |
+| ------------ | ---------------------------------- | -------------------------------------------- |
+| 策略规划 | `roles/Strategist.md` | 用户提出新的 PPT/内容生成需求 |
+| 图片生成 | `roles/Image_Generator.md` | 图片方式包含「C) AI 生成」(如 C、B+C、C+D) |
+| 通用风格执行 | `roles/Executor_General.md` | 用户选择「A) 通用灵活」设计风格 |
+| 咨询风格执行 | `roles/Executor_Consultant.md` | 用户选择「B) 一般咨询」设计风格 |
+| 顶级咨询执行 | `roles/Executor_Consultant_Top.md` | 用户选择「C) 顶级咨询」设计风格 |
+| 视觉优化 | `roles/Optimizer_CRAP.md` | 用户要求优化或主动建议优化 |
> ⚠️ **禁止跳过**:不得在未阅读角色定义文件的情况下直接执行该角色的任务。
@@ -129,10 +129,10 @@ Optimizer_CRAP (可选)
1. **画布格式** - 根据场景推荐(PPT/小红书/朋友圈等)
2. **页数范围** - 基于内容量给出建议
3. **目标受众与场景** - 给出初步判断
-4. **设计风格** - A) 通用灵活 B) 一般咨询 C) 顶级咨询(MBB级),给出推荐理由
+4. **设计风格** - A) 通用灵活 B) 一般咨询 C) 顶级咨询(MBB 级),给出推荐理由
5. **配色方案** - 给出主导色、辅助色、强调色的 HEX 色值
-6. **图标方式** - 四选一:A) Emoji B) AI生成 C) 内置图标库 D) 自定义路径
-7. **图片使用** - 四选一:A) 不使用 B) 用户提供 C) AI生成 D) 占位符预留
+6. **图标方式** - 四选一:A) Emoji B) AI 生成 C) 内置图标库 D) 自定义路径
+7. **图片使用** - 四选一:A) 不使用 B) 用户提供 C) AI 生成 D) 占位符预留
8. **字体方案** - 根据内容特征推荐字体组合(标题/正文/强调)
**策略师必须主动给出专业建议,而非仅提问。**
@@ -140,22 +140,40 @@ Optimizer_CRAP (可选)
### 2. SVG 技术约束(不可协商)
- **viewBox**: 必须与画布尺寸一致
-- **禁止 `<foreignObject>`**: 使用 `<tspan>` 手动换行
- **背景**: 使用 `<rect>` 元素
- **字体**: 使用《设计规范与内容大纲》中指定的字体方案(见 `docs/design_guidelines.md` 字体选择章节)
+#### 必须禁用的功能(黑名单)
+
+| 分类 | 禁用项 | 说明 |
+| --------------- | -------------------------------- | ----------------------- |
+| **裁剪 / 遮罩** | ❌ `clipPath` | PPT 不支持 SVG 裁剪路径 |
+| | ❌ `mask` | PPT 不支持 SVG 遮罩 |
+| **特效** | ❌ `filter`(所有 `fe*`) | 滤镜效果无法导出到 PPT |
+| **样式系统** | ❌ `<style>` | 内部样式表不兼容 |
+| | ❌ `class` / `id` 选择器 | 使用内联属性替代 |
+| | ❌ 外部 CSS | 禁止引用外部样式 |
+| **结构 / 嵌套** | ❌ `<foreignObject>` | 使用 `<tspan>` 手动换行 |
+| | ❌ `<symbol>` + `<use>` 复杂用法 | 简单 `<use>` 引用可用 |
+| **文本 / 字体** | ❌ `textPath` | 路径文本不兼容 |
+| | ❌ Web 字体(`@font-face`) | 使用系统字体栈 |
+| **动画 / 交互** | ❌ SMIL 动画(`<animate*>`) | SVG 动画不导出 |
+| | ❌ JS / 事件 | 禁止脚本和事件处理 |
+
+> 📌 **记忆口诀**:PPT 只认基础形状 + 内联样式 + 系统字体
+
### 3. PPT 兼容性规则(必须遵守)
为确保 SVG 导出到 PowerPoint 后效果一致,**必须遵守以下透明度规则**:
#### 禁止使用的写法
-| ❌ 禁止 | ✅ 正确替代 |
-|--------|-----------|
-| `fill="rgba(255,255,255,0.1)"` | `fill="#FFFFFF" fill-opacity="0.1"` |
-| `stroke="rgba(0,0,0,0.5)"` | `stroke="#000000" stroke-opacity="0.5"` |
-| `<g opacity="0.2">...</g>` | 每个子元素单独设置 `opacity` / `fill-opacity` / `stroke-opacity` |
-| `<image ... opacity="0.3"/>` | 图片后添加遮罩层 `<rect fill="背景色" opacity="0.7"/>` |
+| ❌ 禁止 | ✅ 正确替代 |
+| ------------------------------ | ---------------------------------------------------------------- |
+| `fill="rgba(255,255,255,0.1)"` | `fill="#FFFFFF" fill-opacity="0.1"` |
+| `stroke="rgba(0,0,0,0.5)"` | `stroke="#000000" stroke-opacity="0.5"` |
+| `<g opacity="0.2">...</g>` | 每个子元素单独设置 `opacity` / `fill-opacity` / `stroke-opacity` |
+| `<image ... opacity="0.3"/>` | 图片后添加遮罩层 `<rect fill="背景色" opacity="0.7"/>` |
#### 透明度正确写法示例
@@ -192,14 +210,14 @@ Optimizer_CRAP (可选)
### 4. 画布格式
-| 格式 | 尺寸 | viewBox |
-|------|------|---------|
-| PPT 16:9 | 1280×720 | `0 0 1280 720` |
-| PPT 4:3 | 1024×768 | `0 0 1024 768` |
-| 小红书 | 1242×1660 | `0 0 1242 1660` |
-| 朋友圈 | 1080×1080 | `0 0 1080 1080` |
-| Story | 1080×1920 | `0 0 1080 1920` |
-| 公众号头图 | 900×383 | `0 0 900 383` |
+| 格式 | 尺寸 | viewBox |
+| ---------- | --------- | --------------- |
+| PPT 16:9 | 1280×720 | `0 0 1280 720` |
+| PPT 4:3 | 1024×768 | `0 0 1024 768` |
+| 小红书 | 1242×1660 | `0 0 1242 1660` |
+| 朋友圈 | 1080×1080 | `0 0 1080 1080` |
+| Story | 1080×1920 | `0 0 1080 1920` |
+| 公众号头图 | 900×383 | `0 0 900 383` |
完整格式列表: [docs/canvas_formats.md](./docs/canvas_formats.md)
@@ -246,10 +264,10 @@ project/
生成 SVG 时确保:
- [ ] viewBox 与画布尺寸一致
-- [ ] 无 `<foreignObject>` 元素
- [ ] 使用 `<tspan>` 手动换行
- [ ] 颜色符合设计规范
-- [ ] **PPT 兼容**: 无 `rgba()`、无 `<g opacity>`、图片用遮罩层
+- [ ] **黑名单检查**: 无 `clipPath` / `mask` / `filter` / `<style>` / `class` / `foreignObject` / `textPath` / `animate*` / `script`
+- [ ] **PPT 兼容**: 无 `rgba()`、无 `<g opacity>`、图片用遮罩层、仅内联样式
- [ ] **对齐**: 元素沿网格线对齐
- [ ] **对比**: 建立清晰的视觉层级
- [ ] **重复**: 同类元素风格一致
@@ -257,31 +275,31 @@ 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 识别能力强 |
+| **简单表格** | `pdf_to_md.py` | 同上 |
+| **隐私敏感文档** | `pdf_to_md.py` | 同上(数据不出本机) |
+| **扫描版/图片 PDF** | MinerU | 需要 OCR |
+| **复杂多栏排版** | MinerU | 版面分析更准 |
+| **数学公式** | MinerU | AI 识别能力强 |
> **策略**: PyMuPDF 优先,MinerU 兜底。先运行 `pdf_to_md.py`,如结果乱码/空白再换 MinerU。
## 重要资源
-| 资源 | 路径 |
-|------|------|
-| 图表模板 | `templates/charts/` |
-| **图标库** | `templates/icons/` (640+ 图标) |
-| 设计指南 | `docs/design_guidelines.md` |
+| 资源 | 路径 |
+| ---------------- | --------------------------------------- |
+| 图表模板 | `templates/charts/` |
+| **图标库** | `templates/icons/` (640+ 图标) |
+| 设计指南 | `docs/design_guidelines.md` |
| **图片布局规范** | `docs/image_layout_spec.md` ⚠️ 强制执行 |
-| 画布格式 | `docs/canvas_formats.md` |
-| 图片嵌入 | `docs/svg_image_embedding.md` |
-| 工作流教程 | `docs/workflow_tutorial.md` |
-| 快速参考 | `docs/quick_reference.md` |
-| 示例项目 | `examples/` |
-| 工具说明 | `tools/README.md` |
+| 画布格式 | `docs/canvas_formats.md` |
+| 图片嵌入 | `docs/svg_image_embedding.md` |
+| 工作流教程 | `docs/workflow_tutorial.md` |
+| 快速参考 | `docs/quick_reference.md` |
+| 示例项目 | `examples/` |
+| 工具说明 | `tools/README.md` |
## AI 代理重要提示
@@ -296,10 +314,12 @@ project/
> ⚠️ **严重警告**:以下规则必须严格遵守,违反将导致流程混乱和质量问题。
1. **切换角色前必须阅读角色定义文件**
+
- 使用 `view_file` 工具阅读 `roles/[角色名].md`
- 不得在未阅读的情况下直接执行任务
2. **必须输出显式角色切换标记**
+
- 格式:`## 【角色切换:[角色名称]】`
- 包含阅读的文件和当前任务说明
@@ -312,8 +332,8 @@ project/
- 策略师的「初次沟通」是**强制要求**
- 策略师必须对八项确认问题**均给出专业建议**
- 通用风格与咨询风格在规范格式上有本质区别
-- 图标使用方式需在初次沟通中确认(Emoji / AI生成 / 内置库 / 自定义)
-- 图片使用方式需在初次沟通中确认(不使用 / 用户提供 / AI生成 / 占位符)
+- 图标使用方式需在初次沟通中确认(Emoji / AI 生成 / 内置库 / 自定义)
+- 图片使用方式需在初次沟通中确认(不使用 / 用户提供 / AI 生成 / 占位符)
- **图片生成流程**:如果图片方式**包含**「C) AI 生成」(如 C、B+C、C+D),**必须**先切换到 Image_Generator 角色,阅读角色定义,完成图片生成后再进入 Executor 阶段
### 后处理提示
diff --git a/tools/config.py b/tools/config.py
index b7165aa2..80c00831 100644
--- a/tools/config.py
+++ b/tools/config.py
@@ -345,7 +345,41 @@ LAYOUT_MARGINS = {
# ============================================================
SVG_CONSTRAINTS = {
- 'forbidden_elements': ['foreignObject', 'iframe', 'script'],
+ # 禁用元素 - PPT 不兼容
+ 'forbidden_elements': [
+ # 裁剪 / 遮罩
+ 'clipPath',
+ 'mask',
+ # 特效
+ 'filter',
+ # 样式系统
+ 'style',
+ # 结构 / 嵌套
+ 'foreignObject',
+ 'symbol', # 复杂用法不兼容
+ # 文本 / 字体
+ 'textPath',
+ # 动画 / 交互
+ 'animate',
+ 'animateMotion',
+ 'animateTransform',
+ 'animateColor',
+ 'set',
+ 'script',
+ # 其他
+ 'iframe',
+ ],
+ # 禁用属性
+ 'forbidden_attributes': [
+ 'class',
+ 'onclick', 'onload', 'onmouseover', 'onmouseout',
+ 'onfocus', 'onblur', 'onchange',
+ ],
+ # 禁用模式(正则匹配)
+ 'forbidden_patterns': [
+ r'@font-face', # Web 字体
+ r'rgba\s*\(', # rgba 颜色(PPT 不兼容)
+ ],
'max_file_size_kb': 500,
'warning_file_size_kb': 200,
'recommended_fonts': [
@@ -363,128 +397,128 @@ SVG_CONSTRAINTS = {
class Config:
"""配置管理器"""
-
+
@staticmethod
def get_canvas_format(format_key: str) -> Optional[Dict]:
"""
获取画布格式配置
-
+
Args:
format_key: 格式键名(如 'ppt169', 'xiaohongshu')
-
+
Returns:
格式配置字典,不存在则返回 None
"""
return CANVAS_FORMATS.get(format_key)
-
+
@staticmethod
def get_all_canvas_formats() -> Dict:
"""获取所有画布格式"""
return CANVAS_FORMATS.copy()
-
+
@staticmethod
def get_color_scheme(style: str) -> Optional[Dict]:
"""
获取配色方案
-
+
Args:
style: 风格名称(如 'consulting', 'general', 'tech')
-
+
Returns:
配色方案字典
"""
return DESIGN_COLORS.get(style)
-
+
@staticmethod
def get_industry_colors(industry: str) -> Optional[Dict]:
"""
获取行业配色
-
+
Args:
industry: 行业名称(如 'finance', 'healthcare')
-
+
Returns:
行业配色字典
"""
return INDUSTRY_COLORS.get(industry)
-
+
@staticmethod
def get_all_industries() -> List[str]:
"""获取所有行业列表"""
return list(INDUSTRY_COLORS.keys())
-
+
@staticmethod
def get_layout_margins(format_key: str) -> Optional[Dict]:
"""
获取布局边距配置
-
+
Args:
format_key: 格式键名
-
+
Returns:
边距配置字典
"""
return LAYOUT_MARGINS.get(format_key)
-
+
@staticmethod
def get_font(font_type: str = 'system_ui') -> str:
"""
获取字体声明
-
+
Args:
font_type: 字体类型('system_ui', 'sans_serif', 'monospace')
-
+
Returns:
字体声明字符串
"""
return FONTS.get(font_type, FONTS['system_ui'])
-
+
@staticmethod
def get_font_size(size_name: str) -> int:
"""
获取字体大小
-
+
Args:
size_name: 大小名称(如 'title', 'body', 'caption')
-
+
Returns:
字体大小(像素)
"""
return FONT_SIZES.get(size_name, FONT_SIZES['body'])
-
+
@staticmethod
def validate_svg_element(element_name: str) -> bool:
"""
验证 SVG 元素是否允许使用
-
+
Args:
element_name: 元素名称
-
+
Returns:
是否允许使用
"""
return element_name.lower() not in [e.lower() for e in SVG_CONSTRAINTS['forbidden_elements']]
-
+
@staticmethod
def get_project_path(subdir: str = '') -> Path:
"""
获取项目路径
-
+
Args:
subdir: 子目录名称
-
+
Returns:
完整路径
"""
if subdir:
return PROJECT_ROOT / subdir
return PROJECT_ROOT
-
+
@staticmethod
def export_config(output_file: str = 'config_export.json'):
"""
导出配置为 JSON 文件
-
+
Args:
output_file: 输出文件路径
"""
@@ -496,10 +530,10 @@ class Config:
'font_sizes': FONT_SIZES,
'svg_constraints': SVG_CONSTRAINTS
}
-
+
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(config_data, f, ensure_ascii=False, indent=2)
-
+
print(f"配置已导出到: {output_file}")
@@ -510,7 +544,7 @@ class Config:
def main():
"""命令行入口"""
import sys
-
+
if len(sys.argv) < 2:
print("PPT Master - 配置管理工具\n")
print("用法:")
@@ -520,28 +554,30 @@ def main():
print(" python3 tools/config.py export # 导出配置到 JSON")
print(" python3 tools/config.py format <key> # 查看指定画布格式")
return
-
+
command = sys.argv[1]
-
+
if command == 'list-formats':
print("\n📐 画布格式列表:\n")
for key, info in CANVAS_FORMATS.items():
- print(f" {key:15} | {info['name']:15} | {info['dimensions']:12} | {info['use_case']}")
-
+ print(
+ f" {key:15} | {info['name']:15} | {info['dimensions']:12} | {info['use_case']}")
+
elif command == 'list-colors':
print("\n🎨 配色方案列表:\n")
for key, info in DESIGN_COLORS.items():
print(f" {key:12} | {info['name']:15} | 主色: {info['primary']}")
-
+
elif command == 'list-industries':
print("\n🏢 行业配色列表:\n")
for key, info in INDUSTRY_COLORS.items():
print(f" {key:15} | {info['name']:15} | 主色: {info['primary']}")
-
+
elif command == 'export':
- output_file = sys.argv[2] if len(sys.argv) > 2 else 'config_export.json'
+ output_file = sys.argv[2] if len(
+ sys.argv) > 2 else 'config_export.json'
Config.export_config(output_file)
-
+
elif command == 'format' and len(sys.argv) > 2:
format_key = sys.argv[2]
info = Config.get_canvas_format(format_key)
@@ -552,11 +588,10 @@ def main():
else:
print(f"❌ 未找到格式: {format_key}")
print(f" 可用格式: {', '.join(CANVAS_FORMATS.keys())}")
-
+
else:
print(f"❌ 未知命令: {command}")
if __name__ == '__main__':
main()
-
diff --git a/tools/error_helper.py b/tools/error_helper.py
index ea6e66d5..90ce7c82 100644
--- a/tools/error_helper.py
+++ b/tools/error_helper.py
@@ -110,6 +110,87 @@ class ErrorHelper:
],
'severity': 'error'
},
+ 'clippath_detected': {
+ 'message': '检测到禁用的 <clipPath> 元素',
+ 'solutions': [
+ '移除 <clipPath> 元素',
+ 'PPT 不支持 SVG 裁剪路径',
+ '使用基础形状组合替代裁剪效果'
+ ],
+ 'severity': 'error'
+ },
+ 'mask_detected': {
+ 'message': '检测到禁用的 <mask> 元素',
+ 'solutions': [
+ '移除 <mask> 元素',
+ 'PPT 不支持 SVG 遮罩',
+ '使用不透明度(opacity/fill-opacity)替代'
+ ],
+ 'severity': 'error'
+ },
+ 'filter_detected': {
+ 'message': '检测到禁用的 <filter> 元素',
+ 'solutions': [
+ '移除 <filter> 及所有 fe* 滤镜元素',
+ '滤镜效果无法导出到 PPT',
+ '阴影效果可用多个偏移的浅色形状模拟'
+ ],
+ 'severity': 'error'
+ },
+ 'style_element_detected': {
+ 'message': '检测到禁用的 <style> 元素',
+ 'solutions': [
+ '移除 <style> 元素',
+ '将 CSS 样式转换为内联属性',
+ '例如: fill="#000" 而非 class="text-black"'
+ ],
+ 'severity': 'error'
+ },
+ 'class_attribute_detected': {
+ 'message': '检测到禁用的 class 属性',
+ 'solutions': [
+ '移除所有 class 属性',
+ '使用内联样式替代',
+ '例如: fill="#000" stroke="#333" 直接写在元素上'
+ ],
+ 'severity': 'error'
+ },
+ 'textpath_detected': {
+ 'message': '检测到禁用的 <textPath> 元素',
+ 'solutions': [
+ '移除 <textPath> 元素',
+ '路径文本不兼容 PPT',
+ '使用普通 <text> 元素并手动调整位置'
+ ],
+ 'severity': 'error'
+ },
+ 'webfont_detected': {
+ 'message': '检测到禁用的 Web 字体 (@font-face)',
+ 'solutions': [
+ '移除 @font-face 声明',
+ '使用系统字体栈',
+ 'font-family: system-ui, -apple-system, sans-serif'
+ ],
+ 'severity': 'error'
+ },
+ 'animation_detected': {
+ 'message': '检测到禁用的 SMIL 动画元素',
+ 'solutions': [
+ '移除所有 <animate>, <animateMotion>, <animateTransform> 等元素',
+ 'SVG 动画不会导出到 PPT',
+ '如需动画效果,在 PPT 中使用 PPT 原生动画'
+ ],
+ 'severity': 'error'
+ },
+ 'script_detected': {
+ 'message': '检测到禁用的 <script> 元素',
+ 'solutions': [
+ '移除 <script> 元素',
+ '禁止脚本和事件处理',
+ 'SVG 中的 JavaScript 不会在 PPT 中执行'
+ ],
+ 'severity': 'error'
+ },
'invalid_font': {
'message': '使用了非标准字体',
'solutions': [
diff --git a/tools/svg_quality_checker.py b/tools/svg_quality_checker.py
index f760fe54..f98458f9 100644
--- a/tools/svg_quality_checker.py
+++ b/tools/svg_quality_checker.py
@@ -27,7 +27,7 @@ except ImportError:
class SVGQualityChecker:
"""SVG 质量检查器"""
-
+
def __init__(self):
self.results = []
self.summary = {
@@ -37,20 +37,20 @@ class SVGQualityChecker:
'errors': 0
}
self.issue_types = defaultdict(int)
-
+
def check_file(self, svg_file: str, expected_format: str = None) -> Dict:
"""
检查单个 SVG 文件
-
+
Args:
svg_file: SVG 文件路径
expected_format: 期望的画布格式(如 'ppt169')
-
+
Returns:
检查结果字典
"""
svg_path = Path(svg_file)
-
+
if not svg_path.exists():
return {
'file': str(svg_file),
@@ -59,7 +59,7 @@ class SVGQualityChecker:
'warnings': [],
'passed': False
}
-
+
result = {
'file': svg_path.name,
'path': str(svg_path),
@@ -69,36 +69,36 @@ class SVGQualityChecker:
'info': {},
'passed': True
}
-
+
try:
with open(svg_path, 'r', encoding='utf-8') as f:
content = f.read()
-
+
# 1. 检查 viewBox
self._check_viewbox(content, result, expected_format)
-
+
# 2. 检查禁用元素
self._check_forbidden_elements(content, result)
-
+
# 3. 检查字体
self._check_fonts(content, result)
-
+
# 4. 检查 width/height 与 viewBox 一致性
self._check_dimensions(content, result)
-
+
# 5. 检查文本换行方式
self._check_text_elements(content, result)
-
+
# 6. 检查文件大小
self._check_file_size(svg_path, result)
-
+
# 判断是否通过
result['passed'] = len(result['errors']) == 0
-
+
except Exception as e:
result['errors'].append(f"读取文件失败: {e}")
result['passed'] = False
-
+
# 更新统计
self.summary['total'] += 1
if result['passed']:
@@ -108,29 +108,29 @@ class SVGQualityChecker:
self.summary['passed'] += 1
else:
self.summary['errors'] += 1
-
+
# 统计问题类型
for error in result['errors']:
self.issue_types[self._categorize_issue(error)] += 1
-
+
self.results.append(result)
return result
-
+
def _check_viewbox(self, content: str, result: Dict, expected_format: str = None):
"""检查 viewBox 属性"""
viewbox_match = re.search(r'viewBox="([^"]+)"', content)
-
+
if not viewbox_match:
result['errors'].append("缺少 viewBox 属性")
return
-
+
viewbox = viewbox_match.group(1)
result['info']['viewbox'] = viewbox
-
+
# 检查格式
if not re.match(r'0 0 \d+ \d+', viewbox):
result['warnings'].append(f"viewBox 格式异常: {viewbox}")
-
+
# 检查是否与期望格式匹配
if expected_format and expected_format in CANVAS_FORMATS:
expected_viewbox = CANVAS_FORMATS[expected_format]['viewbox']
@@ -138,50 +138,89 @@ class SVGQualityChecker:
result['errors'].append(
f"viewBox 不匹配: 期望 '{expected_viewbox}', 实际 '{viewbox}'"
)
-
+
def _check_forbidden_elements(self, content: str, result: Dict):
- """检查禁用元素"""
- # 检查 foreignObject
- if '<foreignObject' in content or '<foreignobject' in content.lower():
- result['errors'].append("检测到禁用的 <foreignObject> 元素")
-
- # 检查其他不推荐的元素
- if '<iframe' in content.lower():
+ """检查禁用元素(黑名单)"""
+ content_lower = content.lower()
+
+ # ============================================================
+ # 禁用元素黑名单 - PPT 不兼容
+ # ============================================================
+
+ # 裁剪 / 遮罩
+ if '<clippath' in content_lower:
+ result['errors'].append("检测到禁用的 <clipPath> 元素(PPT 不支持 SVG 裁剪路径)")
+ if '<mask' in content_lower and '<mask>' not in content_lower: # 排除纯文本 "mask"
+ result['errors'].append("检测到禁用的 <mask> 元素(PPT 不支持 SVG 遮罩)")
+
+ # 特效
+ if '<filter' in content_lower:
+ result['errors'].append("检测到禁用的 <filter> 元素(滤镜效果无法导出到 PPT)")
+
+ # 样式系统
+ if '<style' in content_lower:
+ result['errors'].append("检测到禁用的 <style> 元素(使用内联属性替代)")
+ if re.search(r'\bclass\s*=', content):
+ result['errors'].append("检测到禁用的 class 属性(使用内联样式替代)")
+
+ # 结构 / 嵌套
+ if '<foreignobject' in content_lower:
+ result['errors'].append(
+ "检测到禁用的 <foreignObject> 元素(使用 <tspan> 手动换行)")
+ if '<symbol' in content_lower:
+ result['warnings'].append("检测到 <symbol> 元素(复杂用法可能不兼容 PPT)")
+
+ # 文本 / 字体
+ if '<textpath' in content_lower:
+ result['errors'].append("检测到禁用的 <textPath> 元素(路径文本不兼容 PPT)")
+ if '@font-face' in content_lower:
+ result['errors'].append("检测到禁用的 @font-face(使用系统字体栈)")
+
+ # 动画 / 交互
+ if re.search(r'<animate', content_lower):
+ result['errors'].append("检测到禁用的 SMIL 动画元素 <animate*>(SVG 动画不导出)")
+ if '<script' in content_lower:
+ result['errors'].append("检测到禁用的 <script> 元素(禁止脚本和事件处理)")
+ if re.search(r'\bon\w+\s*=', content): # onclick, onload 等
+ result['errors'].append("检测到禁用的事件属性(如 onclick, onload)")
+
+ # 其他不推荐的元素
+ if '<iframe' in content_lower:
result['errors'].append("检测到 <iframe> 元素(不应出现在 SVG 中)")
-
- if '<script' in content.lower():
- result['warnings'].append("检测到 <script> 元素(可能影响安全性)")
-
+
def _check_fonts(self, content: str, result: Dict):
"""检查字体使用"""
# 查找 font-family 声明
- font_matches = re.findall(r'font-family[:\s]*["\']([^"\']+)["\']', content, re.IGNORECASE)
-
+ font_matches = re.findall(
+ r'font-family[:\s]*["\']([^"\']+)["\']', content, re.IGNORECASE)
+
if font_matches:
result['info']['fonts'] = list(set(font_matches))
-
+
# 检查是否使用了系统 UI 字体栈
- recommended_fonts = ['system-ui', '-apple-system', 'BlinkMacSystemFont', 'Segoe UI']
-
+ recommended_fonts = [
+ 'system-ui', '-apple-system', 'BlinkMacSystemFont', 'Segoe UI']
+
for font_family in font_matches:
- has_recommended = any(rec in font_family for rec in recommended_fonts)
-
+ has_recommended = any(
+ rec in font_family for rec in recommended_fonts)
+
if not has_recommended:
result['warnings'].append(
f"建议使用系统 UI 字体栈,当前: {font_family}"
)
break # 只警告一次
-
+
def _check_dimensions(self, content: str, result: Dict):
"""检查 width/height 与 viewBox 的一致性"""
width_match = re.search(r'width="(\d+)"', content)
height_match = re.search(r'height="(\d+)"', content)
-
+
if width_match and height_match:
width = width_match.group(1)
height = height_match.group(1)
result['info']['dimensions'] = f"{width}×{height}"
-
+
# 检查是否与 viewBox 一致
if 'viewbox' in result['info']:
viewbox_parts = result['info']['viewbox'].split()
@@ -192,30 +231,30 @@ class SVGQualityChecker:
f"width/height ({width}×{height}) 与 viewBox "
f"({vb_width}×{vb_height}) 不一致"
)
-
+
def _check_text_elements(self, content: str, result: Dict):
"""检查文本元素和换行方式"""
# 统计 text 和 tspan 元素
text_count = content.count('<text')
tspan_count = content.count('<tspan')
-
+
result['info']['text_elements'] = text_count
result['info']['tspan_elements'] = tspan_count
-
+
# 检查是否有过长的单行文本(可能需要换行)
text_matches = re.findall(r'<text[^>]*>([^<]{100,})</text>', content)
if text_matches:
result['warnings'].append(
f"检测到 {len(text_matches)} 个可能过长的单行文本(建议使用 tspan 换行)"
)
-
+
def _check_file_size(self, svg_path: Path, result: Dict):
"""检查文件大小"""
size_bytes = svg_path.stat().st_size
size_kb = size_bytes / 1024
-
+
result['info']['file_size'] = f"{size_kb:.1f} KB"
-
+
# 警告过大的文件
if size_kb > 500:
result['warnings'].append(
@@ -225,7 +264,7 @@ class SVGQualityChecker:
result['errors'].append(
f"文件过大 ({size_kb:.1f} KB),必须优化"
)
-
+
def _categorize_issue(self, error_msg: str) -> str:
"""分类问题类型"""
if 'viewBox' in error_msg:
@@ -238,43 +277,45 @@ class SVGQualityChecker:
return '文件大小'
else:
return '其他'
-
+
def check_directory(self, directory: str, expected_format: str = None) -> List[Dict]:
"""
检查目录下的所有 SVG 文件
-
+
Args:
directory: 目录路径
expected_format: 期望的画布格式
-
+
Returns:
检查结果列表
"""
dir_path = Path(directory)
-
+
if not dir_path.exists():
print(f"❌ 目录不存在: {directory}")
return []
-
+
# 查找所有 SVG 文件
if dir_path.is_file():
svg_files = [dir_path]
else:
- svg_output = dir_path / 'svg_output' if (dir_path / 'svg_output').exists() else dir_path
+ svg_output = dir_path / \
+ 'svg_output' if (
+ dir_path / 'svg_output').exists() else dir_path
svg_files = sorted(svg_output.glob('*.svg'))
-
+
if not svg_files:
print(f"⚠️ 未找到 SVG 文件")
return []
-
+
print(f"\n🔍 检查 {len(svg_files)} 个 SVG 文件...\n")
-
+
for svg_file in svg_files:
result = self.check_file(str(svg_file), expected_format)
self._print_result(result)
-
+
return self.results
-
+
def _print_result(self, result: Dict):
"""打印单个文件的检查结果"""
if result['passed']:
@@ -287,9 +328,9 @@ class SVGQualityChecker:
else:
icon = "❌"
status = "失败"
-
+
print(f"{icon} {result['file']} - {status}")
-
+
# 显示基本信息
if result['info']:
info_items = []
@@ -299,37 +340,40 @@ class SVGQualityChecker:
info_items.append(f"大小: {result['info']['file_size']}")
if info_items:
print(f" {' | '.join(info_items)}")
-
+
# 显示错误
if result['errors']:
for error in result['errors']:
print(f" ❌ {error}")
-
+
# 显示警告
if result['warnings']:
for warning in result['warnings'][:2]: # 只显示前2个警告
print(f" ⚠️ {warning}")
if len(result['warnings']) > 2:
print(f" ... 还有 {len(result['warnings']) - 2} 个警告")
-
+
print()
-
+
def print_summary(self):
"""打印检查摘要"""
print("=" * 80)
print("📊 检查摘要")
print("=" * 80)
-
+
print(f"\n总文件数: {self.summary['total']}")
- print(f" ✅ 完全通过: {self.summary['passed']} ({self._percentage(self.summary['passed'])}%)")
- print(f" ⚠️ 有警告: {self.summary['warnings']} ({self._percentage(self.summary['warnings'])}%)")
- print(f" ❌ 有错误: {self.summary['errors']} ({self._percentage(self.summary['errors'])}%)")
-
+ print(
+ f" ✅ 完全通过: {self.summary['passed']} ({self._percentage(self.summary['passed'])}%)")
+ print(
+ f" ⚠️ 有警告: {self.summary['warnings']} ({self._percentage(self.summary['warnings'])}%)")
+ print(
+ f" ❌ 有错误: {self.summary['errors']} ({self._percentage(self.summary['errors'])}%)")
+
if self.issue_types:
print(f"\n问题分类:")
for issue_type, count in sorted(self.issue_types.items(), key=lambda x: x[1], reverse=True):
print(f" {issue_type}: {count} 个")
-
+
# 修复建议
if self.summary['errors'] > 0 or self.summary['warnings'] > 0:
print(f"\n💡 常见修复方法:")
@@ -337,39 +381,39 @@ class SVGQualityChecker:
print(f" 2. foreignObject: 改用 <text> + <tspan> 进行手动换行")
print(f" 3. 字体问题: 使用系统 UI 字体栈")
print(f" 4. 文件过大: 移除不必要的元素,优化路径数据")
-
+
def _percentage(self, count: int) -> int:
"""计算百分比"""
if self.summary['total'] == 0:
return 0
return int(count / self.summary['total'] * 100)
-
+
def export_report(self, output_file: str = 'svg_quality_report.txt'):
"""导出检查报告"""
with open(output_file, 'w', encoding='utf-8') as f:
f.write("PPT Master SVG 质量检查报告\n")
f.write("=" * 80 + "\n\n")
-
+
for result in self.results:
status = "✅ 通过" if result['passed'] else "❌ 失败"
f.write(f"{status} - {result['file']}\n")
f.write(f"路径: {result.get('path', 'N/A')}\n")
-
+
if result['info']:
f.write(f"信息: {result['info']}\n")
-
+
if result['errors']:
f.write(f"\n错误:\n")
for error in result['errors']:
f.write(f" - {error}\n")
-
+
if result['warnings']:
f.write(f"\n警告:\n")
for warning in result['warnings']:
f.write(f" - {warning}\n")
-
+
f.write("\n" + "-" * 80 + "\n\n")
-
+
# 写入摘要
f.write("\n" + "=" * 80 + "\n")
f.write("检查摘要\n")
@@ -378,7 +422,7 @@ class SVGQualityChecker:
f.write(f"完全通过: {self.summary['passed']}\n")
f.write(f"有警告: {self.summary['warnings']}\n")
f.write(f"有错误: {self.summary['errors']}\n")
-
+
print(f"\n📄 检查报告已导出: {output_file}")
@@ -395,25 +439,25 @@ def main():
print(" python3 tools/svg_quality_checker.py examples/project/svg_output")
print(" python3 tools/svg_quality_checker.py examples/project")
sys.exit(0)
-
+
checker = SVGQualityChecker()
-
+
# 解析参数
target = sys.argv[1]
expected_format = None
-
+
if '--format' in sys.argv:
idx = sys.argv.index('--format')
if idx + 1 < len(sys.argv):
expected_format = sys.argv[idx + 1]
-
+
# 执行检查
if target == '--all':
# 检查所有示例项目
base_dir = sys.argv[2] if len(sys.argv) > 2 else 'examples'
from project_utils import find_all_projects
projects = find_all_projects(base_dir)
-
+
for project in projects:
print(f"\n{'=' * 80}")
print(f"检查项目: {project.name}")
@@ -421,10 +465,10 @@ def main():
checker.check_directory(str(project))
else:
checker.check_directory(target, expected_format)
-
+
# 打印摘要
checker.print_summary()
-
+
# 导出报告(如果指定)
if '--export' in sys.argv:
output_file = 'svg_quality_report.txt'
@@ -433,7 +477,7 @@ def main():
if idx + 1 < len(sys.argv):
output_file = sys.argv[idx + 1]
checker.export_report(output_file)
-
+
# 返回退出码
if checker.summary['errors'] > 0:
sys.exit(1)
@@ -443,4 +487,3 @@ def main():
if __name__ == '__main__':
main()
-