Refactor yaml2pptx.py from a 1,245-line monolithic script into a modular architecture with clear separation of concerns. The entry point is now 127 lines, with business logic distributed across focused modules. Architecture: - core/: Domain models (elements, template, presentation) - loaders/: YAML loading and validation - renderers/: PPTX and HTML rendering - preview/: Flask preview server - utils.py: Shared utilities Key improvements: - Element abstraction layer using dataclass with validation - Renderer logic built into generator classes - Single-direction dependencies (no circular imports) - Each module 150-300 lines for better readability - Backward compatible CLI interface Documentation: - README.md: User-facing usage guide - README_DEV.md: Developer documentation OpenSpec: - Archive refactor-yaml2pptx-modular change (63/70 tasks complete) - Sync 5 delta specs to main specs (2 new + 3 updated)
53 lines
2.8 KiB
Markdown
53 lines
2.8 KiB
Markdown
## Why
|
||
|
||
yaml2pptx.py 脚本已增长到 1,245 行,包含了 YAML 解析、模板系统、元素渲染、PPTX 生成、HTML 预览等多个功能模块。单文件结构导致代码难以阅读、维护和扩展,对开发者和 LLM 工具都不友好。需要将其重构为模块化结构,同时引入元素抽象层,为未来添加新元素类型和渲染器奠定基础。
|
||
|
||
## What Changes
|
||
|
||
- 将 yaml2pptx.py 拆分为多个功能模块文件,按 core/loaders/renderers/preview 四层架构组织
|
||
- 引入元素抽象层,使用 dataclass 定义元素数据类(TextElement, ImageElement, ShapeElement, TableElement)
|
||
- 在元素创建时进行验证(`__post_init__` 方法)
|
||
- 重构 PPTX 生成器,将渲染器内置在 PptxGenerator 类中
|
||
- 重构 HTML 渲染器,作为独立的 HtmlRenderer 类用于预览功能
|
||
- 保持 yaml2pptx.py 作为单一入口点,所有依赖声明保留在入口脚本的 `/// script` 头部
|
||
- 保持向后兼容:`uv run yaml2pptx.py` 的使用方式不变
|
||
|
||
## Capabilities
|
||
|
||
### New Capabilities
|
||
|
||
- `modular-architecture`: 模块化代码架构,将单文件脚本拆分为 core(核心领域模型)、loaders(加载器)、renderers(渲染器)、preview(预览服务)四层结构,每个模块职责清晰,文件大小控制在 150-300 行
|
||
- `element-abstraction`: 元素抽象层,定义统一的元素接口和数据类,支持元素验证和未来扩展新元素类型
|
||
|
||
### Modified Capabilities
|
||
|
||
- `element-rendering`: 从函数式渲染改为基于元素数据类的面向对象渲染,引入元素抽象层和创建时验证
|
||
- `pptx-generation`: 重构为内置渲染器的架构,PptxGenerator 类内部包含 PPTX 渲染逻辑,通过元素类型分发到对应的渲染方法
|
||
- `html-rendering`: 从内联函数重构为独立的 HtmlRenderer 类,与 PptxRenderer 共享元素抽象层
|
||
|
||
## Impact
|
||
|
||
**代码结构**:
|
||
- yaml2pptx.py:从 1,245 行缩减为约 100 行(仅保留 CLI 和 main 函数)
|
||
- 新增文件:
|
||
- core/elements.py(元素数据类)
|
||
- core/template.py(Template 类)
|
||
- core/presentation.py(Presentation 类)
|
||
- loaders/yaml_loader.py(YAML 加载和验证)
|
||
- renderers/pptx_renderer.py(PptxGenerator)
|
||
- renderers/html_renderer.py(HtmlRenderer)
|
||
- preview/server.py(Flask 服务器和文件监听)
|
||
- utils.py(工具函数)
|
||
|
||
**导入路径**:
|
||
- 内部导入路径会发生变化(如 `from core.elements import TextElement`)
|
||
- 外部使用方式不变(`uv run yaml2pptx.py input.yaml output.pptx`)
|
||
|
||
**依赖管理**:
|
||
- 所有依赖保持在 yaml2pptx.py 的 `/// script` 头部
|
||
- 预览功能的依赖(flask, watchdog)不再可选,统一在入口声明
|
||
|
||
**测试和验证**:
|
||
- 需要验证所有现有功能在重构后仍正常工作
|
||
- 需要测试 YAML 解析、模板渲染、PPTX 生成、HTML 预览等完整流程
|