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
Tools: 增强文件名过滤与控制台兼容性,更新文档
HugoHe7441fc91ed5b
diff --git a/tools/README.md b/tools/README.mdindex 7cccb7cc..5a2f5e50 100644--- a/tools/README.md+++ b/tools/README.md@@ -64,6 +64,7 @@ pip install PyMuPDF- 抓取网页内容并转换为 Markdown- 自动提取页面元数据(标题、日期、作者)- 自动下载图片并保存到 `_files/` 目录+- **自动清理文件名**(仅保留中英文数字下划线,兼容性极佳)- 智能识别主要内容区域(支持中文新闻/政府网站)- 支持批量处理多个 URL@@ -132,6 +133,33 @@ Node.js:---+### 0.6. rotate_images.py — 图片方向修正工具++处理从网页下载的图片 EXIF 方向信息丢失或错误的专用工具。++**功能**:++- **自动 EXIF 修正**: 识别并修复带有 EXIF Orientation 标签的图片+- **可视化旋转**: 生成 HTML 工具页面,点击即可旋转图片+- **自然排序**: 确保图片按文件名自然顺序排列+- **独立运行**: 不依赖爬虫脚本,可单独对任何目录使用++**用法**:++```bash+# 1. 自动修正(静默模式,仅修复 EXIF)+python3 tools/rotate_images.py auto projects/xxx_files++# 2. 生成可视化工具(先修复 EXIF,再生成网页)+python3 tools/rotate_images.py gen projects/xxx_files+# -> 生成 projects/image_orientation_tool.html,浏览器打开即可操作++# 3. 应用修正(根据网页生成的 JSON)+python3 tools/rotate_images.py fix fixes.json+```++---+### 1. project_utils.py — 项目工具公共模块提供项目信息解析、验证等公共功能,供其他工具复用。@@ -946,6 +974,32 @@ pip install Pillow numpy---+### 13. embed_icons.py — SVG 图标嵌入工具++将 SVG 文件中的图标占位符 (`<use ...>`) 替换为实际的图标路径数据,实现图标的“零依赖”嵌入。++**功能**:++- 扫描 `<use data-icon="...">` 占位符+- 从图标库(默认 `templates/icons/`)读取对应 SVG 图标+- 嵌入为 `<g>` 组并应用位置、大小和颜色+- 支持批量处理++**用法**:++```bash+# 处理单个文件+python3 tools/embed_icons.py output.svg++# 处理整个目录+python3 tools/embed_icons.py svg_output/*.svg++# 预览模式+python3 tools/embed_icons.py --dry-run svg_output/*.svg+```++---+## 工作流集成### 典型工作流程diff --git a/tools/batch_validate.py b/tools/batch_validate.pyindex b75f493c..ca012a54 100644--- a/tools/batch_validate.py+++ b/tools/batch_validate.py@@ -58,16 +58,16 @@ class BatchValidator:"""dir_path = Path(directory)if not dir_path.exists():- print(f"❌ 目录不存在: {directory}")+ print(f"[ERROR] 目录不存在: {directory}")return []- print(f"\n🔍 扫描目录: {directory}")+ print(f"\n[SCAN] 扫描目录: {directory}")print("=" * 80)projects = find_all_projects(directory)if not projects:- print(f"⚠️ 未找到任何项目")+ print(f"[WARN] 未找到任何项目")return []print(f"找到 {len(projects)} 个项目\n")@@ -122,13 +122,13 @@ class BatchValidator:# 更新统计if is_valid and not warnings and not svg_warnings:self.summary['valid'] += 1- status = "✅"+ status = "[OK]"elif errors:self.summary['has_errors'] += 1- status = "❌"+ status = "[ERROR]"else:self.summary['has_warnings'] += 1- status = "⚠️ "+ status = "[WARN]"if not info['has_readme']:self.summary['missing_readme'] += 1@@ -144,13 +144,13 @@ class BatchValidator:f" 格式: {info['format_name']} | SVG: {info['svg_count']} 个 | 日期: {info['date_formatted']}")if errors:- print(f" ❌ 错误 ({len(errors)}):")+ print(f" [ERROR] 错误 ({len(errors)}):")for error in errors:print(f" - {error}")if warnings or svg_warnings:all_warnings = warnings + svg_warnings- print(f" ⚠️ 警告 ({len(all_warnings)}):")+ print(f" [WARN] 警告 ({len(all_warnings)}):")for warning in all_warnings[:3]: # 只显示前3个警告print(f" - {warning}")if len(all_warnings) > 3:@@ -163,16 +163,16 @@ class BatchValidator:def print_summary(self):"""打印验证摘要"""print("\n" + "=" * 80)- print("📊 验证摘要")+ print("[Summary] 验证摘要")print("=" * 80)print(f"\n总项目数: {self.summary['total']}")print(- f" ✅ 完全合格: {self.summary['valid']} ({self._percentage(self.summary['valid'])}%)")+ f" [OK] 完全合格: {self.summary['valid']} ({self._percentage(self.summary['valid'])}%)")print(- f" ⚠️ 有警告: {self.summary['has_warnings']} ({self._percentage(self.summary['has_warnings'])}%)")+ f" [WARN] 有警告: {self.summary['has_warnings']} ({self._percentage(self.summary['has_warnings'])}%)")print(- f" ❌ 有错误: {self.summary['has_errors']} ({self._percentage(self.summary['has_errors'])}%)")+ f" [ERROR] 有错误: {self.summary['has_errors']} ({self._percentage(self.summary['has_errors'])}%)")print(f"\n常见问题:")print(f" 缺少 README.md: {self.summary['missing_readme']} 个项目")@@ -191,7 +191,7 @@ class BatchValidator:# 提供修复建议if self.summary['has_errors'] > 0 or self.summary['has_warnings'] > 0:- print(f"\n💡 修复建议:")+ print(f"\n[TIP] 修复建议:")if self.summary['missing_readme'] > 0:print(f" 1. 为缺少 README 的项目创建说明文档")@@ -224,8 +224,8 @@ class BatchValidator:f.write("=" * 80 + "\n\n")for result in self.results:- status = "✅ 合格" if result['is_valid'] and not result['warnings'] else \- "❌ 错误" if result['errors'] else "⚠️ 警告"+ status = "[OK] 合格" if result['is_valid'] and not result['warnings'] else \+ "[ERROR] 错误" if result['errors'] else "[WARN] 警告"f.write(f"{status} - {result['name']}\n")f.write(f"路径: {result['path']}\n")@@ -253,7 +253,7 @@ class BatchValidator:f.write(f"有警告: {self.summary['has_warnings']}\n")f.write(f"有错误: {self.summary['has_errors']}\n")- print(f"\n📄 验证报告已导出: {output_file}")+ print(f"\n[REPORT] 验证报告已导出: {output_file}")def main():@@ -284,7 +284,7 @@ def main():if Path(directory).exists():validator.validate_directory(directory)else:- print(f"⚠️ 跳过不存在的目录: {directory}\n")+ print(f"[WARN] 跳过不存在的目录: {directory}\n")# 打印摘要validator.print_summary()diff --git a/tools/embed_icons.py b/tools/embed_icons.pyindex 58521384..8a8deb0d 100644--- a/tools/embed_icons.py+++ b/tools/embed_icons.py@@ -241,7 +241,7 @@ def main():total_files += 1print()- print(f"📊 总计: {total_files} 个文件, {total_replaced} 个图标" ++ print(f"[Summary] 总计: {total_files} 个文件, {total_replaced} 个图标" +(" (预览)" if args.dry_run else " 已替换"))diff --git a/tools/generate_examples_index.py b/tools/generate_examples_index.pyindex a8d865a4..88ab776f 100644--- a/tools/generate_examples_index.py+++ b/tools/generate_examples_index.py@@ -35,16 +35,16 @@ def generate_examples_index(examples_dir: str = 'examples') -> str:examples_path = Path(examples_dir)if not examples_path.exists():- print(f"❌ 目录不存在: {examples_dir}")+ print(f"[ERROR] 目录不存在: {examples_dir}")return ""- print(f"🔍 扫描目录: {examples_dir}")+ print(f"[SCAN] 扫描目录: {examples_dir}")# 查找所有项目projects = find_all_projects(examples_dir)if not projects:- print("⚠️ 未找到任何项目")+ print("[WARN] 未找到任何项目")return ""print(f"找到 {len(projects)} 个项目")@@ -70,7 +70,7 @@ def generate_examples_index(examples_dir: str = 'examples') -> str:content.append(f"> 最后更新: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")# 概览统计- content.append("## 📊 概览\n")+ content.append("## [Stats] 概览\n")content.append(f"- **项目总数**: {len(projects_info)} 个")content.append(f"- **画布格式**: {len(by_format)} 种")@@ -85,13 +85,13 @@ def generate_examples_index(examples_dir: str = 'examples') -> str:content.append(f"- **{fmt_name}**: {count} 个项目")# 最近更新- content.append("\n## 🆕 最近更新\n")+ content.append("\n## [New] 最近更新\n")for info in projects_info[:5]:content.append(f"- **{info['name']}** ({info['format_name']}) - {info['date_formatted']}")# 按格式分类列表- content.append("\n## 📁 项目列表\n")+ content.append("\n## [List] 项目列表\n")# 定义格式显示顺序format_order = ['ppt169', 'ppt43', 'wechat',@@ -140,7 +140,7 @@ def generate_examples_index(examples_dir: str = 'examples') -> str:content.append(line)# 使用说明- content.append("\n## 📖 使用说明\n")+ content.append("\n## [Docs] 使用说明\n")content.append("### 预览项目\n")content.append("每个项目都包含以下文件:\n")content.append("- `README.md` - 项目说明文档")@@ -169,7 +169,7 @@ def generate_examples_index(examples_dir: str = 'examples') -> str:content.append("```\n")# 贡献指南- content.append("## 🤝 贡献示例项目\n")+ content.append("## [Contribute] 贡献示例项目\n")content.append("欢迎分享你的项目到 examples 目录!\n")content.append("### 项目要求\n")content.append("1. 遵循标准项目结构")@@ -185,7 +185,7 @@ def generate_examples_index(examples_dir: str = 'examples') -> str:content.append("4. 提交 Pull Request\n")# 相关资源- content.append("## 📚 相关资源\n")+ content.append("## [Resources] 相关资源\n")content.append("- [快速开始](../README.md)")content.append("- [工作流教程](../docs/workflow_tutorial.md)")content.append("- [设计规范](../docs/design_guidelines.md)")@@ -216,7 +216,7 @@ def main():content = generate_examples_index(examples_dir)if not content:- print("\n❌ 生成失败")+ print("\n[ERROR] 生成失败")sys.exit(1)# 写入文件@@ -226,7 +226,7 @@ def main():with open(output_file, 'w', encoding='utf-8') as f:f.write(content)- print(f"\n✅ 索引文件已生成: {output_file}")+ print(f"\n[OK] 索引文件已生成: {output_file}")print(f" 包含 {len(content.splitlines())} 行内容")# 显示统计信息@@ -234,7 +234,7 @@ def main():print(f" 索引了 {projects_count} 个项目")except Exception as e:- print(f"\n❌ 写入文件失败: {e}")+ print(f"\n[ERROR] 写入文件失败: {e}")sys.exit(1)diff --git a/tools/project_manager.py b/tools/project_manager.pyindex 6e45fe85..13cfc7c8 100644--- a/tools/project_manager.py+++ b/tools/project_manager.py@@ -99,7 +99,7 @@ class ProjectManager:# 创建设计规范与内容大纲spec_content = f"""# {project_name} - 设计规范与内容大纲-## 📋 项目信息+## [INFO] 项目信息| 项目 | 内容 ||------|------|@@ -113,7 +113,7 @@ class ProjectManager:----## 🎨 设计规范+## [DESIGN] 设计规范### 1. 画布设置@@ -158,14 +158,14 @@ class ProjectManager:### 5. 技术约束-- ✅ 使用 `<tspan>` 进行手动换行-- ❌ 禁止使用 `<foreignObject>`-- ✅ 背景使用 `<rect>` 元素-- ✅ 遵循 CRAP 设计原则(对齐、对比、重复、亲密性)+- [OK] 使用 `<tspan>` 进行手动换行+- [NO] 禁止使用 `<foreignObject>`+- [OK] 背景使用 `<rect>` 元素+- [OK] 遵循 CRAP 设计原则(对齐、对比、重复、亲密性)----## 📑 内容大纲+## [CONTENT] 内容大纲### Slide 01 - 封面**核心信息**: [主题]@@ -189,15 +189,15 @@ class ProjectManager:----## 📊 图片资源清单(如需要)+## [RESOURCE] 图片资源清单(如需要)| 文件名 | 尺寸 | 用途 | 使用页面 | 状态 ||--------|------|------|----------|------|-| cover_bg.png | {canvas_info['dimensions']} | 封面背景 | Slide 01 | ⏳ 待生成 |+| cover_bg.png | {canvas_info['dimensions']} | 封面背景 | Slide 01 | [待生成] |----## ✅ 设计检查清单+## [CHECK] 设计检查清单### 生成前- [ ] 内容符合页面容量@@ -393,12 +393,12 @@ def main():try:project_path = manager.init_project(project_name, canvas_format, base_dir=base_dir)- print(f"✅ 项目已创建: {project_path}")+ print(f"[OK] 项目已创建: {project_path}")print("\n下一步:")print("1. 编辑 设计规范与内容大纲.md")print("2. 将 SVG 文件放入 svg_output/ 目录")except Exception as e:- print(f"❌ 创建失败: {e}")+ print(f"[ERROR] 创建失败: {e}")sys.exit(1)elif command == 'validate':@@ -414,21 +414,21 @@ def main():print("=" * 60)if errors:- print("\n❌ 错误:")+ print("\n[ERROR] 错误:")for error in errors:print(f" - {error}")if warnings:- print("\n⚠️ 警告:")+ print("\n[WARN] 警告:")for warning in warnings:print(f" - {warning}")if is_valid and not warnings:- print("\n✅ 项目结构完整,没有问题")+ print("\n[OK] 项目结构完整,没有问题")elif is_valid:- print("\n✅ 项目结构有效,但有一些建议")+ print("\n[OK] 项目结构有效,但有一些建议")else:- print("\n❌ 项目结构无效,请修复错误")+ print("\n[ERROR] 项目结构无效,请修复错误")sys.exit(1)elif command == 'info':diff --git a/tools/rotate_images.py b/tools/rotate_images.pynew file mode 100644index 00000000..afdcd722--- /dev/null+++ b/tools/rotate_images.py@@ -0,0 +1,460 @@+#!/usr/bin/env python3+"""+PPT Master - 图片方向管理工具++提供可视化筛选图片方向、生成修正代码及批量旋转图片的功能。++用法:+ python3 tools/rotate_images.py gen <images_directory>+ python3 tools/rotate_images.py fix <fixes.json>+"""++import os+import sys+import json+import re+from pathlib import Path+from typing import List, Dict, Union, Any, Optional+from PIL import Image, ExifTags++class ImageRotator:+ """图片方向管理器"""++ def __init__(self):+ """初始化管理器"""+ pass++ @staticmethod+ def _natural_sort_key(s: Union[str, Path]) -> List[Union[int, str]]:+ """自然排序键生成器"""+ return [int(text) if text.isdigit() else text.lower()+ for text in re.split(r'(\d+)', str(s))]++ def auto_fix_exif(self, target_dir: Union[str, Path]) -> int:+ """自动修正目录下所有图片的 EXIF 方向++ Args:+ target_dir: 目标目录++ Returns:+ 修正的图片数量+ """+ target_path = Path(target_dir)+ if not target_path.exists():+ return 0++ print(f"[AUTO] 正在检查 EXIF 方向信息...")+ fixed_count = 0+ valid_exts = {'.jpg', '.jpeg', '.webp'} # PNG 通常不带旋转 EXIF++ # 预先收集文件列表,避免遍历时修改导致的问题+ files = [f for f in target_path.iterdir() if f.is_file() and f.suffix.lower() in valid_exts]++ for f in files:+ if self._fix_single_exif(f):+ fixed_count += 1++ if fixed_count > 0:+ print(f"[OK] 自动修正了 {fixed_count} 张图片的 EXIF 方向")+ else:+ print(f"[INFO] 没有发现需要 EXIF 修正的图片")++ return fixed_count++ def generate_html_tool(self, target_dir: str, output_filename: str = "image_orientation_tool.html") -> str:+ """生成图片筛选 HTML 工具++ 生成前会自动执行 EXIF 修正。+ """+ target_path = Path(target_dir).resolve()++ if not target_path.exists():+ raise FileNotFoundError(f"目录不存在: {target_path}")++ # 1. 先进行自动 EXIF 修正+ self.auto_fix_exif(target_path)++ # 2. 生成 HTML+ # 工具生成在父级目录 (projects/)+ project_root = target_path.parent+ html_output_path = project_root / output_filename++ # 收集图片+ images = []+ valid_exts = {'.jpg', '.jpeg', '.png', '.webp', '.bmp'}++ print(f"[SCAN] 正在扫描目录生成网页: {target_path}")++ files = sorted(target_path.iterdir(), key=lambda p: self._natural_sort_key(p.name))++ for f in files:+ if f.is_file() and f.suffix.lower() in valid_exts:+ try:+ rel_path = f.relative_to(project_root).as_posix()+ images.append(rel_path)+ except ValueError:+ print(f"[WARN] 警告: {f.name} 无法计算相对路径,已跳过")+ continue++ if not images:+ raise ValueError("未找到任何图片文件")++ json_data = json.dumps(images)++ # HTML 模板嵌入+ html_content = self._get_html_template().replace('__IMAGES__', json_data)++ with open(html_output_path, 'w', encoding='utf-8') as f:+ f.write(html_content)++ return str(html_output_path)++ def apply_fixes(self, json_source: Union[str, List[Dict]]) -> Dict[str, int]:+ """应用图片旋转修正"""+ tasks = []++ # 解析输入+ if isinstance(json_source, str):+ if json_source.endswith('.json') or os.path.exists(json_source):+ with open(json_source, 'r', encoding='utf-8') as f:+ tasks = json.load(f)+ else:+ try:+ tasks = json.loads(json_source)+ except json.JSONDecodeError:+ raise ValueError("输入无效:不是文件路径也不是有效的 JSON 字符串")+ elif isinstance(json_source, list):+ tasks = json_source++ print(f"[WORK] 开始处理 {len(tasks)} 个人工旋转任务...")+ print("=" * 60)++ cwd = Path(os.getcwd())+ project_root = cwd / 'projects'++ stats = {'total': len(tasks), 'success': 0}++ for task in tasks:+ rel_path = task.get('path')+ rotation = task.get('rotation')++ if not rel_path or rotation is None:+ continue++ target_file = project_root / rel_path++ # 容错:如果在当前目录找到了(非 projects/ 开头的情况)+ if not target_file.exists() and (cwd / rel_path).exists():+ target_file = cwd / rel_path++ if not target_file.exists():+ print(f"[SKIP] 文件未找到: {rel_path}")+ continue++ try:+ self._rotate_single_image(target_file, rotation)+ print(f"[OK] {target_file.name} 旋转 {rotation}°")+ stats['success'] += 1+ except Exception as e:+ print(f"[ERROR] {target_file.name}: {e}")++ return stats++ def _fix_single_exif(self, file_path: Path) -> bool:+ """检查并修正单张图片的 EXIF"""+ try:+ # 使用上下文管理器确保文件被正确关闭+ img = Image.open(file_path)+ orientation = self._get_exif_orientation(img)++ if orientation and orientation != 1:+ print(f" [EXIF] 修正: {file_path.name} (Orientation={orientation})")++ # 应用旋转+ fixed_img = self._apply_exif_orientation(img, orientation)++ # 移除具体的 Orientation tag,保留其他 EXIF+ exif_dict = img.info.get('exif')++ # 必须先关闭原文件才能覆盖保存 (Windows 特性)+ img.close()++ # 保存+ if exif_dict:+ fixed_img.save(file_path, quality=95, exif=exif_dict)+ else:+ fixed_img.save(file_path, quality=95)+ return True+ else:+ img.close()+ return False+ except Exception as e:+ print(f" [WARN] 读取EXIF失败 {file_path.name}: {e}")+ return False++ def _get_exif_orientation(self, img: Image.Image) -> Optional[int]:+ """获取 Orientation 值"""+ try:+ exif = img._getexif()+ if exif:+ for tag, value in exif.items():+ if ExifTags.TAGS.get(tag) == 'Orientation':+ return value+ except:+ pass+ return None++ def _apply_exif_orientation(self, img: Image.Image, orientation: int) -> Image.Image:+ """根据 Orientation 值旋转图片"""+ if orientation == 2:+ return img.transpose(Image.FLIP_LEFT_RIGHT)+ elif orientation == 3:+ return img.rotate(180, expand=True)+ elif orientation == 4:+ return img.transpose(Image.FLIP_TOP_BOTTOM)+ elif orientation == 5:+ return img.transpose(Image.FLIP_LEFT_RIGHT).rotate(270, expand=True)+ elif orientation == 6:+ return img.rotate(270, expand=True)+ elif orientation == 7:+ return img.transpose(Image.FLIP_LEFT_RIGHT).rotate(90, expand=True)+ elif orientation == 8:+ return img.rotate(90, expand=True)+ return img++ def _rotate_single_image(self, file_path: Path, rotation_deg: int):+ """人工旋转单张图片"""+ with Image.open(file_path) as img:+ pil_angle = (360 - rotation_deg) % 360+ rotated = img.rotate(pil_angle, expand=True)+ exif = img.info.get('exif')+ if exif:+ rotated.save(file_path, quality=95, exif=exif)+ else:+ rotated.save(file_path, quality=95)++ def _get_html_template(self) -> str:+ """获取 HTML 模板内容"""+ return """+<!DOCTYPE html>+<html lang="zh-CN">+<head>+ <meta charset="UTF-8">+ <title>图片方向筛选工具</title>+ <style>+ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; padding: 20px; background: #f0f2f5; color: #333; }+ .header {+ position: sticky; top: 0; background: rgba(255,255,255,0.95); padding: 20px;+ box-shadow: 0 4px 20px rgba(0,0,0,0.08); z-index: 100;+ border-radius: 12px; margin-bottom: 20px;+ backdrop-filter: blur(10px);+ display: flex; justify-content: space-between; align-items: center;+ }+ h2 { margin: 0; font-size: 1.5rem; color: #1a1a1a; }+ .instructions { color: #666; margin-top: 5px; font-size: 0.9rem; }++ .grid {+ display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));+ gap: 15px;+ }+ .card {+ background: white; border-radius: 12px; overflow: hidden;+ box-shadow: 0 2px 8px rgba(0,0,0,0.05); text-align: center;+ cursor: pointer; transition: all 0.2s ease;+ position: relative; border: 2px solid transparent;+ }+ .card:hover { transform: translateY(-4px); box-shadow: 0 8px 16px rgba(0,0,0,0.1); }+ .card.modified { border-color: #007bff; background: #f8fbff; }++ .img-wrapper {+ height: 180px; width: 100%; display: flex; align-items: center; justify-content: center;+ background: #e9ecef; overflow: hidden; position: relative;+ }+ img {+ max-width: 100%; max-height: 100%; object-fit: contain;+ transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);+ }++ .info { padding: 10px; font-size: 11px; color: #555; word-break: break-all; border-top: 1px solid #eee; }++ .badge {+ position: absolute; top: 10px; right: 10px;+ background: #007bff; color: white; padding: 4px 8px;+ border-radius: 20px; font-size: 11px; font-weight: bold;+ opacity: 0; transform: scale(0.8); transition: all 0.2s;+ box-shadow: 0 2px 4px rgba(0,0,0,0.2);+ }+ .card.modified .badge { opacity: 1; transform: scale(1); }++ .btn {+ background: #007bff; color: white; border: none; padding: 10px 24px;+ border-radius: 8px; font-weight: 600; cursor: pointer; transition: background 0.2s;+ }+ .btn:hover { background: #0056b3; }++ #output-modal {+ display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;+ background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center;+ }+ .modal-content {+ background: white; padding: 30px; border-radius: 16px; width: 80%; max-width: 600px;+ box-shadow: 0 10px 40px rgba(0,0,0,0.2);+ }+ textarea {+ width: 100%; height: 200px; padding: 10px; border: 1px solid #ddd; border-radius: 8px;+ font-family: inherit; resize: vertical; margin: 15px 0;+ background: #f8f9fa;+ }+ </style>+</head>+<body>++<div class="header">+ <div>+ <h2>图片方向修正</h2>+ <div class="instructions">点击图片旋转 (90° -> 180° -> 270° -> 0°)。自然顺序排列。</div>+ </div>+ <button class="btn" onclick="showCode()">生成修正代码</button>+</div>++<div class="grid" id="grid"></div>++<div id="output-modal" onclick="if(event.target===this)this.style.display='none'">+ <div class="modal-content">+ <h3>复制以下代码</h3>+ <p style="color:#666; font-size: 0.9em;">请将此 JSON 内容复制并发送给 AI 助手,或保存为 'fixes.json'。</p>+ <textarea id="output-area" readonly></textarea>+ <div style="text-align: right;">+ <button class="btn" onclick="document.getElementById('output-modal').style.display='none'">关闭</button>+ </div>+ </div>+</div>++<script>+ const images = __IMAGES__;+ const grid = document.getElementById('grid');++ images.forEach(src => {+ const card = document.createElement('div');+ card.className = 'card';+ card.setAttribute('data-rotation', 0);+ card.setAttribute('data-src', src);++ const filename = src.split('/').pop();++ card.innerHTML = `+ <div class="img-wrapper">+ <img src="${src}" alt="${filename}" loading="lazy">+ <div class="badge">0°</div>+ </div>+ <div class="info">${filename}</div>+ `;++ card.onclick = function() {+ let rot = parseInt(this.getAttribute('data-rotation'));+ rot = (rot + 90) % 360;+ this.setAttribute('data-rotation', rot);++ const img = this.querySelector('img');+ img.style.transform = `rotate(${rot}deg)`;++ const badge = this.querySelector('.badge');+ badge.innerText = rot + '°';++ if (rot > 0) {+ this.classList.add('modified');+ } else {+ this.classList.remove('modified');+ }+ };++ grid.appendChild(card);+ });++ function showCode() {+ const tasks = [];+ document.querySelectorAll('.card').forEach(card => {+ const rot = parseInt(card.getAttribute('data-rotation'));+ if (rot > 0) {+ tasks.push({+ path: card.getAttribute('data-src'),+ rotation: rot+ });+ }+ });++ const jsonStr = JSON.stringify(tasks, null, 2);+ const modal = document.getElementById('output-modal');+ const area = document.getElementById('output-area');++ modal.style.display = 'flex';+ area.value = jsonStr;+ area.select();+ try { document.execCommand('copy'); } catch(e){}+ }+</script>+</body>+</html>+"""++def main():+ """主函数"""+ if len(sys.argv) < 2:+ print(__doc__)+ sys.exit(1)++ command = sys.argv[1]+ rotator = ImageRotator()++ if command == 'gen':+ if len(sys.argv) < 3:+ print("[ERROR] 错误: 需要提供图片目录路径")+ print("用法: python3 tools/rotate_images.py gen <images_directory>")+ sys.exit(1)++ target_dir = sys.argv[2]+ try:+ output_path = rotator.generate_html_tool(target_dir)+ print(f"[OK] HTML 工具已创建: {output_path}")+ print(f"[LINK] 请在浏览器中打开: file:///{Path(output_path).as_posix()}")+ except Exception as e:+ print(f"[ERROR] 生成失败: {e}")+ sys.exit(1)++ elif command == 'fix':+ if len(sys.argv) < 3:+ print("[ERROR] 错误: 需要提供 fixes.json 路径")+ print("用法: python3 tools/rotate_images.py fix <fixes.json>")+ sys.exit(1)++ json_file = sys.argv[2]+ try:+ stats = rotator.apply_fixes(json_file)+ print(f"\n[DONE] 处理完成: 成功 {stats['success']} / 总计 {stats['total']}")+ except Exception as e:+ print(f"[ERROR] 执行失败: {e}")+ sys.exit(1)++ elif command == 'auto':+ if len(sys.argv) < 3:+ print("[ERROR] 错误: 需要提供图片目录路径")+ print("用法: python3 tools/rotate_images.py auto <images_directory>")+ sys.exit(1)++ target_dir = sys.argv[2]+ try:+ # 仅执行 EXIF 自动修复+ count = rotator.auto_fix_exif(Path(target_dir))+ if count == 0:+ print("[INFO] 未发现需要自动修复的图片")+ except Exception as e:+ print(f"[ERROR] 自动修复失败: {e}")+ sys.exit(1)++ else:+ print(f"[ERROR] 错误: 未知命令 '{command}'")+ print(__doc__)+ sys.exit(1)++if __name__ == '__main__':+ main()diff --git a/tools/svg_quality_checker.py b/tools/svg_quality_checker.pyindex f98458f9..d76a3849 100644--- a/tools/svg_quality_checker.py+++ b/tools/svg_quality_checker.py@@ -292,7 +292,7 @@ class SVGQualityChecker:dir_path = Path(directory)if not dir_path.exists():- print(f"❌ 目录不存在: {directory}")+ print(f"[ERROR] 目录不存在: {directory}")return []# 查找所有 SVG 文件@@ -305,10 +305,10 @@ class SVGQualityChecker:svg_files = sorted(svg_output.glob('*.svg'))if not svg_files:- print(f"⚠️ 未找到 SVG 文件")+ print(f"[WARN] 未找到 SVG 文件")return []- print(f"\n🔍 检查 {len(svg_files)} 个 SVG 文件...\n")+ print(f"\n[SCAN] 检查 {len(svg_files)} 个 SVG 文件...\n")for svg_file in svg_files:result = self.check_file(str(svg_file), expected_format)@@ -320,13 +320,13 @@ class SVGQualityChecker:"""打印单个文件的检查结果"""if result['passed']:if result['warnings']:- icon = "⚠️ "+ icon = "[WARN]"status = "通过(有警告)"else:- icon = "✅"+ icon = "[OK]"status = "通过"else:- icon = "❌"+ icon = "[ERROR]"status = "失败"print(f"{icon} {result['file']} - {status}")@@ -344,12 +344,12 @@ class SVGQualityChecker:# 显示错误if result['errors']:for error in result['errors']:- print(f" ❌ {error}")+ print(f" [ERROR] {error}")# 显示警告if result['warnings']:for warning in result['warnings'][:2]: # 只显示前2个警告- print(f" ⚠️ {warning}")+ print(f" [WARN] {warning}")if len(result['warnings']) > 2:print(f" ... 还有 {len(result['warnings']) - 2} 个警告")@@ -358,16 +358,16 @@ class SVGQualityChecker:def print_summary(self):"""打印检查摘要"""print("=" * 80)- print("📊 检查摘要")+ print("[SUMMARY] 检查摘要")print("=" * 80)print(f"\n总文件数: {self.summary['total']}")print(- f" ✅ 完全通过: {self.summary['passed']} ({self._percentage(self.summary['passed'])}%)")+ f" [OK] 完全通过: {self.summary['passed']} ({self._percentage(self.summary['passed'])}%)")print(- f" ⚠️ 有警告: {self.summary['warnings']} ({self._percentage(self.summary['warnings'])}%)")+ f" [WARN] 有警告: {self.summary['warnings']} ({self._percentage(self.summary['warnings'])}%)")print(- f" ❌ 有错误: {self.summary['errors']} ({self._percentage(self.summary['errors'])}%)")+ f" [ERROR] 有错误: {self.summary['errors']} ({self._percentage(self.summary['errors'])}%)")if self.issue_types:print(f"\n问题分类:")@@ -376,7 +376,7 @@ class SVGQualityChecker:# 修复建议if self.summary['errors'] > 0 or self.summary['warnings'] > 0:- print(f"\n💡 常见修复方法:")+ print(f"\n[TIP] 常见修复方法:")print(f" 1. viewBox 问题: 确保与画布格式一致(参考 docs/canvas_formats.md)")print(f" 2. foreignObject: 改用 <text> + <tspan> 进行手动换行")print(f" 3. 字体问题: 使用系统 UI 字体栈")@@ -395,7 +395,7 @@ class SVGQualityChecker:f.write("=" * 80 + "\n\n")for result in self.results:- status = "✅ 通过" if result['passed'] else "❌ 失败"+ status = "[OK] 通过" if result['passed'] else "[ERROR] 失败"f.write(f"{status} - {result['file']}\n")f.write(f"路径: {result.get('path', 'N/A')}\n")@@ -423,7 +423,7 @@ class SVGQualityChecker:f.write(f"有警告: {self.summary['warnings']}\n")f.write(f"有错误: {self.summary['errors']}\n")- print(f"\n📄 检查报告已导出: {output_file}")+ print(f"\n[REPORT] 检查报告已导出: {output_file}")def main():diff --git a/tools/web_to_md.cjs b/tools/web_to_md.cjsindex e59ddaff..062d229e 100644--- a/tools/web_to_md.cjs+++ b/tools/web_to_md.cjs@@ -507,8 +507,8 @@ function extractMetadata(parsed, url) {// ============ Sanitize Filename ============function sanitizeFilename(name) {return name- .replace(/[<>:"/\\|?*]/g, "").replace(/\s+/g, "_")+ .replace(/[^\u4e00-\u9fa5a-zA-Z0-9_]/g, "").replace(/_+/g, "_").substring(0, 80);}diff --git a/tools/web_to_md.py b/tools/web_to_md.pyindex b5150397..b37a2f3c 100644--- a/tools/web_to_md.py+++ b/tools/web_to_md.py@@ -103,10 +103,11 @@ def clean_title(title):def sanitize_filename(name):"""Sanitizes the filename for file system."""- # Remove invalid chars- clean = re.sub(r'[<>:"/\\|?*]', '', name)- # Replace whitespace- clean = re.sub(r'\s+', '_', clean)+ # Replace whitespace with underscore first+ clean = re.sub(r'\s+', '_', name)+ # Remove all except Chinese, English, Numbers, Underscore+ clean = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9_]', '', clean)+ # Collapse repeating underscoresclean = re.sub(r'_+', '_', clean)return clean[:80] # Truncate