codex-ppt
Runtime home override.
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
Codex PPT Skill
一个面向 Codex 的 PPT 生成 skill,也可在 Claude Code、OpenClaw、Hermes Agent 等支持 SKILL.md 的 agent 中使用;在这些非 Codex 环境中通常需要配置 gpt-image-2.5-flare、第三方生图 API 或 OpenAI 兼容格式的生图接口。它把文章、报告、论文、课程笔记等内容转换成“整页图片式”的演示文稿:先规划大纲和视觉风格,再生成每页幻灯片图片,最后用本地脚本组装为 .pptx。
https://github.com/user-attachments/assets/ad0fa884-87e4-4528-8030-f2dd0211693c
赞助
温馨提示
[!TIP] 本 skill 负责从文章、报告、大纲或想法生成图片式 PPT,适合强视觉表达,但页面元素本身不可直接编辑。如果你需要进一步转换成可编辑 PPT,可以在生成完成后尝试使用 image-to-editable-ppt-skill 进行转换。
关于
codex-ppt和image-to-editable-ppt这两个技能的详细介绍,参见 skill_duo_intro.pdf。该 PPT 由codex-pptskill 生成,提示词为:“请分别阅读 Codex PPT和 Image to Editable PPT 这两个技能的内容,然后用 Codex PPT 帮我做一个PPT吧,20页,每个技能的介绍10页。”另外,关于这个 PPT Skill 设计和调优的实践经验,可以看这篇文章:2000 个 GitHub Star 换来的经验:好的 AI Skill 是调出来的,不是写出来的。
[!NOTE] 想查看更多用户用这个 skill 做出的 PPT 效果,可以前往置顶 Issue 的案例展示区:欢迎分享 codex-ppt 使用案例和 PPT 效果。
这个 skill 主要给大家提供一个还不错的 PPT 生成流程。为了尽量通用,它的流程设计会稍微复杂一些;复杂也会带来不稳定性或者冗余性。比如它同时兼容 Codex 内置生图和 API/CLI fallback 生图,也会兼容有无子 agent 可用这两种情况,但大部分人日常使用时其实只会固定走其中一条路线。
建议大家在走通自己常用的路线之后,让 AI 帮你改一下这个 skill,把你的偏好固定下来,省得每次都重新选择。比如固定使用内置生图或固定使用某个 API,固定是否使用子 agent,固定常用输出目录、风格、页数节奏等。
另外,如果你在做 PPT 的过程中遇到了自己喜欢的版式或排版,无论是这个 skill 做出来的,还是从别的地方找到的 PPT 风格图片,都可以让 AI 保存到你的个人风格库(~/.codex-ppt-skill/references/)里,逐步沉淀自己的风格。个人风格库存放在 skill 安装目录之外,更新或重装 skill 都不会丢失。Skills 本质上是非常个性化的流程,鼓励大家在使用这个 skill 的基础上,按自己的偏好持续调优,让它更适配自己的工作流。
关于 skills 如何设计和使用,可以参考 good-skill-design.pptx。这个 PPT 也是用本 skill 做的,采用的是手绘技术解释风;内容基于 Claude 在设计 skills 方面的最佳实践文章 The Complete Guide to Building Skills for Claude。祝大家玩得愉快!
特点
- 多 agent 可用:支持 Codex、Claude Code、OpenClaw、Hermes Agent 等支持
SKILL.md的环境;最推荐在 Codex 中使用,优先走内置生图和编辑图能力。 - 第三方生图供应商接入:支持 OpenAI 兼容接口、AtlasCloud、
base URL和自定义模型名配置,方便通过 API/CLI fallback 使用gpt-image-2.5-flare或兼容模型。 - 稳定的阶段化流程:先确认大纲、页数、视觉风格、生图后端和样张,再进入整套生成,降低一次生成完整 PPT 时的返工和偏航。
- 不是无脑生成:会先引导你确认
outline.md、每页要点、风格方向和样张效果,再按确认后的方案继续。 - 低门槛输入:文章、报告、论文、课程笔记、Markdown、大纲、PDF、Word 等材料都可以作为起点。
- 内置 12 种 PPT 风格参考:包括清爽专业、科研答辩、党政红、教学课件、电子墨水杂志、手绘技术解释、仪表盘、麦肯锡等;不会写提示词也可以先从内置风格开始,尤其推荐手绘技术解释风。
- 支持自定义风格复刻:可以上传喜欢的图片、PDF 或 PPT/PPTX,让 agent 先分析配色、版式、字体和视觉元素,再按该风格生成新 PPT。
- 可沉淀个人风格库:生成满意后,可以把当前风格保存到个人风格库(
~/.codex-ppt-skill/references/),下次直接复用;风格库存放在 skill 安装目录之外,更新 skill 不会丢失,同名时个人风格优先于内置风格。 - 多 agent 并发生成:样张确认后,支持一个子 agent 负责一页,并对文字清晰度、风格一致性和内容完整性做自检,发现问题及时返修。
- 支持指定图片插入:可以要求某一页必须放入论文原图、实验结果图、截图、架构图等素材,并让页面围绕这些图片适配主题和版式。
- 自动生成演讲稿:会生成
speech.md,并在组装 PPTX 时写入每页备注,方便直接演示或二次修改。
生成效果
下面是一套技术分享 PPT 的生成效果示例。每页都是由 gpt-image-2 生成的完整 16:9 幻灯片图片,再由本地脚本组装为 PPTX。

下面是一套论文答辩风案例,来源于论文 Attention Is All You Need。它展示了如何在指定页中插入论文原始图片作为输入素材,例如模型架构图、attention 模块图和 attention 可视化图,并围绕这些图片生成统一风格的 PPT(见 Issue #14)。

风格示例
以下是已生成预览图的风格,示例图均由 gpt-image-2 生成,用于帮助用户在开始制作前选择视觉方向。
| 清爽专业风 | 创意杂志风 |
|---|---|
![]() | ![]() |
| 电子墨水杂志风 | 数据仪表盘风 |
![]() | ![]() |
| 复古扁平插画风 | 手绘技术解释风 |
![]() | ![]() |
| 手绘白板风 | 温暖手工风 |
![]() | ![]() |
| 科研答辩风 | 麦肯锡风格 |
![]() | ![]() |
| 党政红风格 | 教学课件风 |
![]() | ![]() |
输出结构
每个 PPT 会生成一个独立项目目录:
{基础目录}/{PPT名称}/ # 当前 PPT 的独立项目目录
├── origin_image/ # 正式幻灯片图片目录,只放最终采用的页面
│ ├── slide_01.png # 第 1 页幻灯片图片
│ ├── slide_02.png # 第 2 页幻灯片图片
│ └── ... # 后续页面图片,按页码顺序命名
├── outline.md # 经确认的 PPT 大纲、页数、每页标题和要点
├── speech.md # 演讲稿,会写入 PPT 每页备注
└── {PPT名称}.pptx # 最终组装生成的 PowerPoint 文件
你可以在 origin_image/ 里查看每一页最终采用的幻灯片图片,文件会按 slide_01.png、slide_02.png 这样的顺序排列。想预览整套 PPT 的视觉效果,或只挑某一页继续修改时,直接看这里最方便。
speech.md 是配套演讲稿。生成 .pptx 时,这些内容会自动写入每页 PPT 的备注区,你可以在 PowerPoint 里直接查看、修改,或演示时作为讲稿使用。
适用场景
- 技术文章转分享 PPT
- 论文或报告转演示稿
- 课程笔记转课件
- 科研项目申报、中期检查、结题验收和论文答辩
- 商业汇报、产品介绍、调研总结
- 需要强视觉统一性的图片式演示文稿
安装
一句话安装
【推荐】可以直接把下面这句话发给你的 Agent,让它帮你安装:
请帮我安装这个 codex-ppt skill,链接是:https://github.com/ningzimu/codex-ppt-skill
手动安装到 Codex
如需手动安装到 Codex,可以使用 skills CLI 安装到 Codex 的全局 skills 目录:
npx -y skills@latest add ningzimu/codex-ppt-skill \
--skill codex-ppt \
--agent codex \
--global
安装完成后,重启 Codex 让新 skill 生效。
也可以从 GitHub Releases 下载 codex-ppt-skill-v*.zip,解压后把其中的 codex-ppt 文件夹放到 ~/.codex/skills/codex-ppt,然后重启 Codex。
如果你是在本地开发这个仓库,也可以把 skill 目录链接到 Codex skills 目录,方便实时调试修改:
mkdir -p ~/.codex/skills
ln -s /path/to/codex-ppt-skill/skills/codex-ppt ~/.codex/skills/codex-ppt
OpenClaw
可以通过 ClawHub 安装:
openclaw skills install codex-ppt
ClawHub 页面:clawhub.ai/ningzimu/codex-ppt
如果使用 OpenClaw 的 skill allowlist,需要把 codex-ppt 加入允许列表。
Claude Code、Hermes Agent
这些 agent 都可以读取 SKILL.md 形式的 skill。也可以使用 skills CLI 安装:
# Claude Code
npx -y skills@latest add ningzimu/codex-ppt-skill \
--skill codex-ppt \
--agent claude-code \
--global
# Hermes Agent
npx -y skills@latest add ningzimu/codex-ppt-skill \
--skill codex-ppt \
--agent hermes-agent \
--global
常见目标目录是:Claude Code 使用 ~/.claude/skills/codex-ppt,Hermes Agent 使用 ~/.hermes/skills/codex-ppt。
如果你是在本地开发这个仓库,也可以用软链接替代复制,方便实时调试修改。
更新
重新执行一遍上面对应的安装命令即可覆盖为最新版本,也可以直接让 agent 帮你更新:
请帮我更新 codex-ppt skill 到最新版本,仓库是
// HOW IT'S BUILT
// FILES
41 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
skills/codex-ppt/SKILL.md10 KB1cbcd9a82532upstream ↗
--- name: codex-ppt description: Generate visually unified image-based PPT/PPTX decks from articles, reports, papers, notes, or outlines. metadata: openclaw: requires: bins: - python3 primaryEnv: OPENAI_API_KEY envVars: - name: OPENAI_API_KEY required: false description: API key for CLI fallback. - name: OPENAI_BASE_URL required: false description: API base URL. - name: CODEX_PPT_IMAGE_MODEL required: false description: Image model, defaults to gpt-image-2.5-flare. - name: CODEX_PPT_HOME required: false description: Runtime home override. homepage: https://github.com/ningzimu/codex-ppt-skill --- # Codex PPT ## Overview This skill creates image-based PowerPoint decks from source material. Each slide is a complete 16:9 generated image. Final images are assembled into `.pptx` with `scripts/assemble_ppt.py`. Use this when the user wants a visually unified presentation and accepts full-slide image pages. Do not use it when every textbox, chart, or shape must remain separately editable. Prefer the built-in image generation/editing tool. Use `scripts/image_gen.py` only when the built-in backend is unavailable, lacks a required capability, or the user explicitly asks for API/CLI mode. ## Hard Constraints - Read the relevant `Reference Map` files before each phase. This file is the orchestration contract; detailed rules live in `docs/` and worker prompts in `prompts/`. - Respect approval gates. Do not create final `deck_spec.json`, `speech.md`, prompt jobs, slide images, or `.pptx` before the approvals in `docs/workflow-gates-and-progress.md`. - After the user approves the sample slide and authorizes full-deck generation, every remaining slide image job must be dispatched to a slide subagent whenever subagents are available. - The main agent owns orchestration, prompt jobs, state recording, QA, speaker notes, and assembly. Do not silently replace available slide subagents with sequential production. - Every final `origin_image/slide_XX.png` must be generated by the selected image backend: built-in image generation/editing tool or `scripts/image_gen.py`. - Local drawing, Pillow, SVG, HTML/CSS/canvas screenshots, python-pptx/PptxGenJS layouts, and manual overlays are failure modes, not fallbacks. - The selected image backend must stay fixed after backend confirmation. Do not let subagents switch backend for convenience. - After sample approval, record how the approved sample was generated and pass that exact method to every slide subagent. - Slide dispatch and result state must be recorded with the bundled scripts. Chat messages alone do not make a slide dispatched or complete. - If a required subagent, image backend, or required-image path is unavailable, stop and report a blocker with the slide id and evidence. Do not create a lower-quality replacement. ## Visible Progress For non-trivial decks, keep a user-visible checklist with one active step. Canonical completion evidence is in `docs/workflow-gates-and-progress.md`. Default visible steps: 1. Prepare source, outline, style, and backend decisions. 2. Generate and approve one sample slide. 3. Prepare slide jobs and slide state. 4. Dispatch slide subagents. 5. Record generated slide results. 6. QA, repair, notes, and PPT assembly. Do not mark a step complete from chat alone; use real files or script-recorded state. ## Default Workflow 1. Understand the source content. - Identify topic, audience, goal, page count, style/brand constraints, and sections to include or exclude. - If no page count is specified, choose a practical count. Typical decks are 8-12 slides. 2. Plan the deck outline. - Before writing or updating `outline.md`, read `docs/workflow-gates-and-progress.md` and `docs/outline-style-and-sample.md`. - Draft slide roles and required source images. Ask for confirmation, then stop before style, backend, sample, or downstream artifacts until approved. 3. Confirm a unified visual style. - Before offering style options or using files from `references/`, read `docs/outline-style-and-sample.md`. - Offer 2-3 concrete style directions, recommend one, wait for confirmation, then keep one visual identity while varying layouts by page role. 4. Confirm the image backend. - Before generating any slide image, read `docs/backend-selection.md`. - Check whether a built-in image tool is callable, state what you checked, name the backend, explain fallback status, and wait for confirmation. - If CLI/API fallback is selected, read `docs/cli-api-fallback.md`. Read `docs/image-model-configuration.md` only after config errors or explicit API-setting requests. 5. Generate one sample slide for approval. - Before generating or approving the sample slide, read `docs/outline-style-and-sample.md`. - Generate exactly one representative sample after outline, style, and backend are confirmed. Do not generate the full deck until approved. - After approval, record `sample_generation_method` in `deck_spec.json` so jobs and subagents inherit the same path. 6. Create the project directory. - Before initializing folders or assembling files, read `docs/project-assembly-and-reporting.md`. - If no destination is specified, use the current working directory or the source file directory. 7. Prepare user-supplied assets. - Before using paper figures, charts, screenshots, logos, or other required assets, read `docs/user-supplied-assets.md`. - Treat required assets as strict inputs and confirm slide-to-asset mapping before generation. 8. Generate all slide images. - Before full-deck image generation, read `docs/slide-generation-and-subagents.md`. - Create per-slide jobs with `scripts/prepare_slide_prompts.py` or saved `prompts/slide_XX.json` files. - Every final image must come from the selected backend and be recorded with bundled state scripts. 9. Dispatch slide subagents. - Before dispatching or replacing slide workers, read `docs/slide-generation-and-subagents.md` and `prompts/slide-worker.md`. - Use one subagent per remaining slide job whenever possible. If required subagents cannot be spawned, stop and report a blocker unless the user changes the workflow. 10. Quality check and repair. - Before QA or assembly, read `docs/project-assembly-and-reporting.md`. - Inspect every slide before assembly: text, outline match, truncation, style, unwanted page numbers, overlaps, and required assets. - Regenerate severe failures with a tighter prompt. Use backend editing for localized issues when available. - For CLI/API fallback edit commands, read `docs/cli-api-fallback.md`. Replace the final slide only after validating the edited output. 11. Write speaker notes and assemble the PPT. - Before writing `speech.md` or running assembly, read `docs/project-assembly-and-reporting.md`. - Make sure `outline.md` reflects the final confirmed deck outline. Use `speech.md` headings that map to `Slide N`. - Before assembly, ensure `slide_jobs.json` shows generated slides as `recorded` and approved samples as `accepted`. If any slide is `pending`, `dispatched`, or `blocked`, stop. 12. Report the result. - Use the final report checklist in `docs/project-assembly-and-reporting.md`. - Include paths, slide count, backend used, recorded-result status, and any limitations or blockers. 13. Save reusable styles. - If asked to save the current deck style or a supplied image/PDF/PPT/PPTX style, read `docs/style-library.md`. - If the final deck used a custom or adapted style, proactively offer to save it in the final report, per `docs/project-assembly-and-reporting.md`. User custom styles are stored in `${CODEX_PPT_HOME:-~/.codex-ppt-skill}/references/`, outside the skill install. ## Subagent Dispatch Slide subagents are mandatory after sample approval whenever the runtime can spawn them. The main agent prepares jobs and records state; each worker handles exactly one `prompts/slide_XX.json` job and returns only selected image path, backend, and QA note. Use `docs/slide-generation-and-subagents.md` for dispatch, commands, result recording, blockers, and backend provenance. Use `prompts/slide-worker.md` as the handoff template. Subagents must not edit `outline.md`, `deck_spec.json`, other slide jobs, `origin_image/`, `speech.md`, or the final `.pptx`. The parent records outputs and assembles. ## Acceptance Criteria - Output is a valid `.pptx`. - Each expected final slide image exists under `origin_image/slide_XX.png`. - Every final slide image was generated by the confirmed backend and recorded through `record_slide_result.py`, except an approved sample marked accepted by run state. - `outline.md` reflects the approved deck outline. - `speech.md` exists when speaker notes are expected, and assembly writes those notes into the PPT. - `slide_jobs.json` and `slide_run_state.json` reflect the final state. - Required source images are visibly represented, or a blocker is reported. - If blocked, the final response identifies phase, slide id, evidence path, and unfinished reason; do not call the deck complete. ## Reference Map - `docs/workflow-gates-and-progress.md`: approval gates, progress, completion evidence. - `docs/backend-selection.md`: backend decision rules and confirmation text. - `docs/outline-style-and-sample.md`: outline, style, sample rules, prompt examples. - `docs/user-supplied-assets.md`: strict handling for required source assets. - `docs/slide-generation-and-subagents.md`: jobs, dispatch, result recording, blockers, provenance. - `docs/cli-api-fallback.md`: fallback runtime, generation/edit commands, image limits, troubleshooting. - `docs/image-model-configuration.md`: API key, base URL, model, `.env`; read only when config is needed. - `docs/project-assembly-and-reporting.md`: project directory, notes, assembly, final report, prompting principles. - `prompts/slide-worker.md`: slide subagent handoff template. - `references/*.md`: built-in visual style references. User custom styles live in `${CODEX_PPT_HOME:-~/.codex-ppt-skill}/references/` and take priority over built-in styles with the same name. ## Documentation and Updates For source, docs, install, config, and examples, see [ningzimu/codex-ppt-skill](https://github.com/ningzimu/codex-ppt-skill).skills/codex-ppt/scripts/assemble_ppt.py14 KBa56a7822cc4bupstream ↗
#!/usr/bin/env python3 """ PPT 组装脚本 将一个目录中的幻灯片图片组装成 PowerPoint 演示文稿。 每张图片会被插入为一页幻灯片,充满整个页面。 """ import argparse import os import re import sys import tempfile from typing import Dict, List, Optional, Tuple def dependency_hint() -> str: runtime_home = os.path.expanduser(os.environ.get("CODEX_PPT_HOME", "~/.codex-ppt-skill")) python = os.path.join( runtime_home, ".venv", "Scripts" if os.name == "nt" else "bin", "python.exe" if os.name == "nt" else "python", ) runtime_script = os.path.join( os.path.dirname(os.path.abspath(__file__)), "codex_ppt_runtime.py", ) return ( f"请运行: python3 {runtime_script} bootstrap\n" f"或直接运行: {python} -m pip install -r " f"{os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'requirements.txt')}" ) def get_slide_images(ppt_project_dir: str) -> List[str]: """ 获取幻灯片图片文件列表,按页码排序 Args: ppt_project_dir: PPT 项目目录(包含 origin_image 子目录) Returns: 按顺序排列的图片文件路径列表 """ # 从 origin_image 子目录读取 origin_image_dir = os.path.join(ppt_project_dir, "origin_image") if not os.path.exists(origin_image_dir): print(f"错误:origin_image 目录不存在: {origin_image_dir}") return [] print(f"从 origin_image 目录读取图片: {origin_image_dir}") # 支持的图片格式 image_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.bmp'} # 只获取正式幻灯片图片,避免 sample_slide.png、草稿图或参考图被误装入 PPT。 slide_name_pattern = re.compile(r"^slide_(\d+)\.(png|jpe?g|gif|bmp)$", re.IGNORECASE) image_files = [] for file in os.listdir(origin_image_dir): file_path = os.path.join(origin_image_dir, file) if os.path.isfile(file_path): ext = os.path.splitext(file)[1].lower() if ext in image_extensions and slide_name_pattern.match(file): image_files.append(file_path) def slide_sort_key(path: str) -> Tuple[int, str]: filename = os.path.basename(path) stem = os.path.splitext(filename)[0] return (int(re.search(r"^slide_(\d+)", stem).group(1)), filename.lower()) # 按页码排序,避免 slide_10 排在 slide_2 前面。 # 同页码多文件时按文件名稳定排序。 image_files.sort(key=slide_sort_key) return image_files def load_speaker_notes(ppt_project_dir: str) -> Dict[int, str]: """ 从 speech.md 读取每页演讲备注。 支持以下标题格式: - ## Slide 1: 标题 - ### Slide 1: 标题 - ## 第 1 页:标题 """ speech_path = os.path.join(ppt_project_dir, "speech.md") if not os.path.exists(speech_path): return {} with open(speech_path, "r", encoding="utf-8") as f: content = f.read() notes: Dict[int, str] = {} current_slide: Optional[int] = None current_lines: List[str] = [] heading_pattern = re.compile(r"^#{2,4}\s*(?:Slide\s*(\d+)|第\s*(\d+)\s*页)\b.*$", re.IGNORECASE) def flush_current() -> None: if current_slide is None: return text = "\n".join(current_lines).strip() if text: notes[current_slide] = text for line in content.splitlines(): match = heading_pattern.match(line.strip()) if match: flush_current() current_slide = int(match.group(1) or match.group(2)) current_lines = [] continue if current_slide is not None: current_lines.append(line) flush_current() return notes def compress_image_if_needed( image_path: str, max_size_mb: float = 2.0, quality_step: int = 5 ) -> Optional[str]: """ 如果图片超过指定大小,压缩图片并返回临时文件路径 Args: image_path: 原始图片路径 max_size_mb: 最大文件大小(MB) quality_step: 每次降低的质量步进 Returns: str: 如果需要压缩,返回临时文件路径;否则返回 None """ max_size_bytes = max_size_mb * 1024 * 1024 # 检查原始文件大小 file_size = os.path.getsize(image_path) if file_size <= max_size_bytes: # 不需要压缩 return None print(f" 图片大小 {file_size / 1024 / 1024:.2f}MB,需要压缩...") try: from PIL import Image # 打开图片 img = Image.open(image_path) # 转换 RGBA 到 RGB(如果需要保存为 JPEG) if img.mode in ('RGBA', 'LA', 'P'): background = Image.new('RGB', img.size, (255, 255, 255)) if img.mode == 'P': img = img.convert('RGBA') background.paste(img, mask=img.split()[-1] if img.mode in ('RGBA', 'LA') else None) img = background # 创建临时文件 temp_fd, temp_path = tempfile.mkstemp(suffix='.jpg') os.close(temp_fd) # 从高质量开始尝试压缩 quality = 95 while quality > 20: img.save(temp_path, 'JPEG', quality=quality, optimize=True) compressed_size = os.path.getsize(temp_path) if compressed_size <= max_size_bytes: print(f" 压缩成功: {compressed_size / 1024 / 1024:.2f}MB (质量: {quality})") return temp_path quality -= quality_step # 如果还是太大,尝试调整尺寸 print(f" 质量压缩不足,尝试缩小尺寸...") scale = 0.9 while scale > 0.3: new_width = int(img.width * scale) new_height = int(img.height * scale) resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS) resized_img.save(temp_path, 'JPEG', quality=85, optimize=True) compressed_size = os.path.getsize(temp_path) if compressed_size <= max_size_bytes: print(f" 压缩成功: {compressed_size / 1024 / 1024:.2f}MB (缩放: {scale:.0%})") return temp_path scale -= 0.1 # 实在压不下去了,返回最后的结果 print(f" 警告:无法压缩到 {max_size_mb}MB 以下,使用最小尺寸版本") return temp_path except ImportError: print("错误:未安装 Pillow 库") print(dependency_hint()) return None except Exception as e: print(f" 警告:图片压缩失败: {e}") if 'temp_path' in locals() and os.path.exists(temp_path): os.remove(temp_path) return None def create_presentation( image_files: List[str], output_path: str, aspect_ratio: str = "16:9", speaker_notes: Optional[Dict[int, str]] = None, ) -> bool: """ 创建 PowerPoint 演示文稿 Args: image_files: 幻灯片图片文件列表 output_path: 输出 PPT 文件路径 aspect_ratio: 幻灯片宽高比(16:9 或 4:3) Returns: bool: 成功返回 True,失败返回 False """ try: try: from pptx import Presentation from pptx.util import Inches except ImportError: print("错误:未安装 python-pptx 库") print(dependency_hint()) return False # 创建演示文稿 prs = Presentation() # 设置幻灯片尺寸 if aspect_ratio == "16:9": prs.slide_width = Inches(10) prs.slide_height = Inches(5.625) elif aspect_ratio == "4:3": prs.slide_width = Inches(10) prs.slide_height = Inches(7.5) else: print(f"警告:不支持的宽高比 {aspect_ratio},使用默认值 16:9") prs.slide_width = Inches(10) prs.slide_height = Inches(5.625) speaker_notes = speaker_notes or {} # 添加每一页幻灯片 temp_files_to_cleanup = [] for i, image_path in enumerate(image_files, 1): if not os.path.exists(image_path): print(f"警告:图片文件不存在: {image_path}") continue # 压缩图片(如果需要) compressed_path = compress_image_if_needed(image_path, max_size_mb=2.0) # 使用压缩后的图片或原图 image_to_use = compressed_path if compressed_path else image_path # 记录临时文件以便后续清理 if compressed_path: temp_files_to_cleanup.append(compressed_path) # 使用空白布局(索引 6) blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) # 将图片添加到幻灯片,充满整个页面 slide.shapes.add_picture( image_to_use, left=0, top=0, width=prs.slide_width, height=prs.slide_height ) note_text = speaker_notes.get(i) if note_text: notes_frame = slide.notes_slide.notes_text_frame notes_frame.clear() notes_frame.text = note_text print(f"✓ 已添加第 {i} 页: {os.path.basename(image_path)}") # 确保输出目录存在 output_dir = os.path.dirname(output_path) if output_dir and not os.path.exists(output_dir): os.makedirs(output_dir) # 保存演示文稿 prs.save(output_path) print(f"\n✓ PPT 文件已保存: {output_path}") print(f" 总页数: {len(image_files)}") if speaker_notes: matched_notes = sum(1 for i in range(1, len(image_files) + 1) if speaker_notes.get(i)) print(f" 已写入备注: {matched_notes}/{len(image_files)} 页") # 清理临时文件 for temp_file in temp_files_to_cleanup: try: if os.path.exists(temp_file): os.remove(temp_file) except Exception as e: print(f"警告:清理临时文件失败 {temp_file}: {e}") return True except Exception as e: print(f"错误:创建 PPT 失败: {e}") import traceback traceback.print_exc() # 即使失败也要清理临时文件 if 'temp_files_to_cleanup' in locals(): for temp_file in temp_files_to_cleanup: try: if os.path.exists(temp_file): os.remove(temp_file) except: pass return False def main(): parser = argparse.ArgumentParser( description='将幻灯片图片组装成 PowerPoint 演示文稿', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=''' 示例用法: # 基本用法 # 会在 /path/to/base/ 下查找 MyPresentation/ 文件夹 # 从 MyPresentation/origin_image/ 读取图片 # 将 PPT 保存为 MyPresentation/MyPresentation.pptx python assemble_ppt.py /path/to/base/ MyPresentation.pptx # 指定 4:3 宽高比 python assemble_ppt.py /path/to/base/ MyPresentation.pptx --aspect-ratio 4:3 # 只初始化目录,不生成 PPT python assemble_ppt.py /path/to/base/ MyPresentation.pptx --init 文件夹结构要求: /path/to/base/MyPresentation/ ├── origin_image/ │ ├── slide_01.png │ ├── slide_02.png │ └── ... ├── speech.md (可选,将写入 PPT 备注) └── MyPresentation.pptx (将在此生成) 注意: - 图片文件必须放在 origin_image 子目录中 - 只会读取 slide_01.png、slide_02.png 这类正式图片,其他图片会被忽略 - 图片文件按页码排序 - 建议图片文件命名为: slide_01.png, slide_02.png, ... - 每张图片会充满整个幻灯片页面 - 如果项目目录下存在 speech.md,会按 Slide N 标题写入每页备注 ''' ) parser.add_argument('base_dir', help='基础目录(PPT 项目文件夹的父目录)') parser.add_argument('output', help='输出 PPT 文件名 (.pptx)') parser.add_argument('--aspect-ratio', '--ar', choices=['16:9', '4:3'], default='16:9', help='幻灯片宽高比 (默认: 16:9)') parser.add_argument('--init', action='store_true', help='只创建 PPT 项目目录和 origin_image 子目录,不生成 PPT') args = parser.parse_args() # 确保输出文件有 .pptx 扩展名 output_filename = args.output if not output_filename.lower().endswith('.pptx'): output_filename += '.pptx' # 获取 PPT 名称(不含扩展名) ppt_name = os.path.splitext(os.path.basename(output_filename))[0] # 构建 PPT 项目目录 ppt_project_dir = os.path.join(args.base_dir, ppt_name) origin_image_dir = os.path.join(ppt_project_dir, "origin_image") if args.init: os.makedirs(origin_image_dir, exist_ok=True) print(f"✓ PPT 项目目录已准备好: {ppt_project_dir}") print(f"✓ 幻灯片图片目录已准备好: {origin_image_dir}") sys.exit(0) if not os.path.exists(ppt_project_dir): print(f"错误:PPT 项目目录不存在: {ppt_project_dir}") print("如需初始化目录,请添加 --init 参数") sys.exit(1) if not os.path.exists(origin_image_dir): print(f"错误:origin_image 目录不存在: {origin_image_dir}") print("如需初始化目录,请添加 --init 参数") sys.exit(1) # 设置输出路径 output_path = os.path.join(ppt_project_dir, output_filename) # 获取幻灯片图片 print(f"正在扫描 PPT 项目目录: {ppt_project_dir}") image_files = get_slide_images(ppt_project_dir) if not image_files: print("错误:未找到任何图片文件") print("支持的格式: .png, .jpg, .jpeg, .gif, .bmp") print(f"\n请将幻灯片图片放置在: {origin_image_dir}/") sys.exit(1) print(f"找到 {len(image_files)} 张幻灯片图片\n") speaker_notes = load_speaker_notes(ppt_project_dir) if speaker_notes: print(f"找到 {len(speaker_notes)} 页备注: {os.path.join(ppt_project_dir, 'speech.md')}\n") # 创建演示文稿 print(f"正在创建 PPT (宽高比: {args.aspect_ratio})...") print("-" * 50) success = create_presentation(image_files, output_path, args.aspect_ratio, speaker_notes) sys.exit(0 if success else 1) if __name__ == '__main__': main()skills/codex-ppt/scripts/codex_ppt_runtime.py8.5 KB4cae03e35414upstream ↗
#!/usr/bin/env python3 """Manage the cross-agent runtime for codex-ppt. The runtime lives outside any specific agent installation so Codex, Claude Code, OpenClaw, Hermes Agent, and other local agents can share one virtual environment and one API configuration. """ from __future__ import annotations import argparse import json import os from pathlib import Path import stat import subprocess import sys from typing import Dict, Iterable, Optional import urllib.error import urllib.parse import urllib.request import venv DEFAULT_RUNTIME_HOME = "~/.codex-ppt-skill" DEFAULT_MODEL = "gpt-image-2.5-flare" ENV_FIELDS = ("OPENAI_API_KEY", "OPENAI_BASE_URL", "CODEX_PPT_IMAGE_MODEL") def _runtime_home() -> Path: return Path(os.getenv("CODEX_PPT_HOME", DEFAULT_RUNTIME_HOME)).expanduser() def _skill_root() -> Path: return Path(__file__).resolve().parents[1] def _venv_python(home: Path) -> Path: if os.name == "nt": return home / ".venv" / "Scripts" / "python.exe" return home / ".venv" / "bin" / "python" def _env_path(home: Path) -> Path: return home / ".env" def _requirements_path() -> Path: return _skill_root() / "requirements.txt" def _die(message: str, code: int = 1) -> None: print(f"Error: {message}", file=sys.stderr) raise SystemExit(code) def _mask_secret(value: str) -> str: if not value: return "" if len(value) <= 8: return "****" return f"{value[:4]}...{value[-4:]}" def _parse_env_file(path: Path) -> Dict[str, str]: if not path.exists(): return {} values: Dict[str, str] = {} for raw in path.read_text(encoding="utf-8").splitlines(): line = raw.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) key = key.strip() value = value.strip().strip('"').strip("'") if key: values[key] = value return values def _quote_env_value(value: str) -> str: if not value: return "" if any(ch.isspace() for ch in value) or "#" in value or '"' in value: return json.dumps(value) return value def _write_env_file(path: Path, values: Dict[str, str]) -> None: path.parent.mkdir(parents=True, exist_ok=True) lines = [ "# codex-ppt shared runtime configuration", "# Used by Codex, Claude Code, OpenClaw, Hermes Agent, and other local agents.", ] for key in ENV_FIELDS: value = values.get(key, "") if value: lines.append(f"{key}={_quote_env_value(value)}") lines.append("") path.write_text("\n".join(lines), encoding="utf-8") try: path.chmod(stat.S_IRUSR | stat.S_IWUSR) except OSError: pass def _load_env_values(home: Path) -> Dict[str, str]: values = _parse_env_file(_env_path(home)) for key in ENV_FIELDS: if os.getenv(key): values[key] = os.environ[key] return values def _ensure_dirs(home: Path) -> None: for child in (home, home / "cache", home / "logs"): child.mkdir(parents=True, exist_ok=True) def _bootstrap(args: argparse.Namespace) -> int: home = _runtime_home() _ensure_dirs(home) python = _venv_python(home) if not python.exists(): print(f"Creating virtual environment: {home / '.venv'}") venv.EnvBuilder(with_pip=True, clear=False).create(home / ".venv") else: print(f"Virtual environment already exists: {home / '.venv'}") requirements = _requirements_path() if not requirements.exists(): _die(f"requirements.txt not found: {requirements}") cmd = [str(python), "-m", "pip", "install", "-r", str(requirements)] if args.upgrade: cmd.insert(4, "-U") print(f"Installing dependencies from: {requirements}") subprocess.run(cmd, check=True) print(f"Runtime ready: {home}") return 0 def _config(args: argparse.Namespace) -> int: home = _runtime_home() _ensure_dirs(home) env_file = _env_path(home) values = _parse_env_file(env_file) if args.api_key: values["OPENAI_API_KEY"] = args.api_key if args.base_url is not None: values["OPENAI_BASE_URL"] = args.base_url.strip() if args.model is not None: values["CODEX_PPT_IMAGE_MODEL"] = args.model.strip() if args.clear_base_url: values.pop("OPENAI_BASE_URL", None) _write_env_file(env_file, values) print(f"Wrote {env_file}") for key in ENV_FIELDS: value = values.get(key, "") if key == "OPENAI_API_KEY": value = _mask_secret(value) print(f"{key}={value or '<unset>'}") return 0 def _check_python_imports(python: Path) -> bool: if not python.exists(): print(f"venv: missing ({python})") return False code = "import openai, PIL, pptx; print('imports ok')" proc = subprocess.run( [str(python), "-c", code], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, ) if proc.returncode != 0: print("dependencies: missing or broken") if proc.stderr.strip(): print(proc.stderr.strip()) return False print("dependencies: ok") return True def _models_request(base_url: str, api_key: str, timeout: int) -> bool: endpoint = base_url.rstrip("/") + "/models" req = urllib.request.Request( endpoint, headers={"Authorization": f"Bearer {api_key}"}, method="GET", ) try: with urllib.request.urlopen(req, timeout=timeout) as resp: print(f"models endpoint: HTTP {resp.status}") return 200 <= resp.status < 300 except urllib.error.HTTPError as exc: body = exc.read(800).decode("utf-8", "replace") print(f"models endpoint: HTTP {exc.code}") if body: print(body) return False except Exception as exc: print(f"models endpoint: {exc.__class__.__name__}: {exc}") return False def _is_atlascloud_base_url(base_url: str) -> bool: hostname = urllib.parse.urlparse(base_url).hostname or "" return "atlascloud.ai" in hostname.lower() def _doctor(args: argparse.Namespace) -> int: home = _runtime_home() env_file = _env_path(home) print(f"runtime home: {home}") print(f"env file: {env_file} ({'exists' if env_file.exists() else 'missing'})") print(f"venv python: {_venv_python(home)}") ok = True ok = _check_python_imports(_venv_python(home)) and ok values = _load_env_values(home) api_key = values.get("OPENAI_API_KEY", "") base_url = values.get("OPENAI_BASE_URL", "https://api.openai.com/v1") model = values.get("CODEX_PPT_IMAGE_MODEL", DEFAULT_MODEL) print(f"OPENAI_API_KEY={'set (' + _mask_secret(api_key) + ')' if api_key else '<unset>'}") print(f"OPENAI_BASE_URL={base_url}") print(f"CODEX_PPT_IMAGE_MODEL={model}") if "gpt-image-" not in model: print("model check: warning, model name should contain 'gpt-image-'") ok = False else: print("model check: ok") if args.check_api: if not api_key: print("api check: skipped, OPENAI_API_KEY is unset") ok = False elif _is_atlascloud_base_url(base_url): print("api check: AtlasCloud provider detected; skipping /models probe") else: ok = _models_request(base_url, api_key, args.timeout) and ok return 0 if ok else 1 def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Manage the codex-ppt shared runtime") subparsers = parser.add_subparsers(dest="command", required=True) bootstrap = subparsers.add_parser("bootstrap", help="Create shared venv and install deps") bootstrap.add_argument("--upgrade", action="store_true") bootstrap.set_defaults(func=_bootstrap) config = subparsers.add_parser("config", help="Write or update shared .env") config.add_argument("--api-key") config.add_argument("--base-url") config.add_argument("--clear-base-url", action="store_true") config.add_argument("--model") config.set_defaults(func=_config) doctor = subparsers.add_parser("doctor", help="Check runtime and optional API access") doctor.add_argument("--check-api", action="store_true") doctor.add_argument("--timeout", type=int, default=30) doctor.set_defaults(func=_doctor) return parser def main(argv: Optional[Iterable[str]] = None) -> int: parser = _build_parser() args = parser.parse_args(list(argv) if argv is not None else None) return args.func(args) if __name__ == "__main__": raise SystemExit(main())skills/codex-ppt/scripts/image_gen.py34 KB4b7403ba1cadupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/scripts/image_providers/__init__.py188 B9c678c0c93d6upstream ↗
"""Image API providers for the codex-ppt fallback CLI.""" from .base import ImageProvider from .factory import create_image_provider __all__ = ["ImageProvider", "create_image_provider"]skills/codex-ppt/scripts/image_providers/atlascloud.py8.1 KB4a14ed5018cfupstream ↗
from __future__ import annotations import asyncio import base64 import json import mimetypes from pathlib import Path import sys import time from typing import Any, Callable, Dict, List, Optional from urllib.parse import urlparse from urllib.request import Request, urlopen as default_urlopen from .base import ImageProvider UrlOpen = Callable[..., Any] USER_AGENT = "codex-ppt-skill/0.1 (+https://github.com/ningzimu/codex-ppt-skill)" class AtlasCloudImageProvider(ImageProvider): _FINISHED_STATUSES = {"completed", "succeeded"} _FAILED_STATUSES = {"failed"} def __init__( self, *, api_key: Optional[str], base_url: Optional[str], urlopen: UrlOpen = default_urlopen, sleep: Callable[[float], None] = time.sleep, poll_interval: float = 2.0, max_polls: int = 120, ) -> None: self.api_key = api_key self.model_base_url = _model_base_url(base_url) self._urlopen = urlopen self._sleep = sleep self.poll_interval = poll_interval self.max_polls = max_polls def generate(self, payload: Dict[str, Any]) -> List[str]: count = int(payload.get("n", 1)) outputs: List[str] = [] for _ in range(count): outputs.extend(self._submit_and_collect(payload, operation="text-to-image")) return outputs def edit( self, payload: Dict[str, Any], image_paths: List[Path], mask_path: Optional[Path], ) -> List[str]: if mask_path is not None: raise ValueError("AtlasCloud image edit does not support --mask.") count = int(payload.get("n", 1)) edit_payload = dict(payload) edit_payload["images"] = [_image_to_data_url(path) for path in image_paths] outputs: List[str] = [] for _ in range(count): outputs.extend(self._submit_and_collect(edit_payload, operation="edit")) return outputs async def generate_batch( self, payload: Dict[str, Any], *, attempts: int, job_label: str, ) -> List[str]: last_exc: Optional[Exception] = None for attempt in range(1, attempts + 1): try: return await asyncio.to_thread(self.generate, payload) except Exception as exc: last_exc = exc if attempt == attempts: raise sleep_s = min(60.0, 2.0**attempt) print( f"{job_label} attempt {attempt}/{attempts} failed ({exc.__class__.__name__}); retrying in {sleep_s:.1f}s", file=sys.stderr, ) await asyncio.sleep(sleep_s) raise last_exc or RuntimeError("unknown error") def _submit_and_collect(self, payload: Dict[str, Any], *, operation: str) -> List[str]: request_payload = self._atlas_payload(payload, operation=operation) submitted = self._request_json( "POST", f"{self.model_base_url}/generateImage", request_payload, ) prediction_id = _prediction_id(submitted) if not prediction_id: raise RuntimeError("AtlasCloud response did not include a prediction id.") result_url = _prediction_result_url(submitted) or f"{self.model_base_url}/result/{prediction_id}" result = self._poll_prediction(result_url) outputs = result.get("outputs") if not isinstance(outputs, list) or not outputs: raise RuntimeError("AtlasCloud prediction completed without outputs.") return [self._output_to_b64(str(output)) for output in outputs] def _poll_prediction(self, url: str) -> Dict[str, Any]: last: Dict[str, Any] = {} for _ in range(self.max_polls): last = self._request_json("GET", url) status = str(last.get("status", "")).lower() if status in self._FINISHED_STATUSES: return last if status in self._FAILED_STATUSES: raise RuntimeError(f"AtlasCloud prediction failed: {last}") self._sleep(self.poll_interval) raise TimeoutError(f"AtlasCloud prediction timed out: {last}") def _atlas_payload(self, payload: Dict[str, Any], *, operation: str) -> Dict[str, Any]: output_format = payload.get("output_format") if output_format not in (None, "png", "jpeg"): raise ValueError("AtlasCloud supports output_format png or jpeg.") body: Dict[str, Any] = { "model": atlascloud_model_for_operation( str(payload.get("model", "gpt-image-2")), operation, ), "prompt": payload["prompt"], "enable_sync_mode": False, "enable_base64_output": True, } for key in ("size", "quality", "output_format"): value = payload.get(key) if value is not None and value != "auto": body[key] = value if operation == "edit": body["images"] = payload["images"] return body def _request_json( self, method: str, url: str, payload: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: data = json.dumps(payload).encode("utf-8") if payload is not None else None headers = { "Authorization": f"Bearer {self.api_key}", "Accept": "application/json", "User-Agent": USER_AGENT, } if payload is not None: headers["Content-Type"] = "application/json" request = Request(url, data=data, headers=headers, method=method) with self._urlopen(request, timeout=60) as response: parsed = json.loads(response.read().decode("utf-8")) if not isinstance(parsed, dict): raise RuntimeError(f"Unexpected AtlasCloud response: {parsed}") code = parsed.get("code") if code is not None and code not in (0, 200, "0", "200"): raise RuntimeError(f"AtlasCloud API error: {parsed}") data_obj = parsed.get("data", parsed) if not isinstance(data_obj, dict): raise RuntimeError(f"Unexpected AtlasCloud response data: {parsed}") return data_obj def _output_to_b64(self, value: str) -> str: if value.startswith("data:") and "," in value: return value.split(",", 1)[1] parsed = urlparse(value) if parsed.scheme in {"http", "https"}: request = Request(value, headers={"User-Agent": USER_AGENT}, method="GET") with self._urlopen(request, timeout=60) as response: return base64.b64encode(response.read()).decode("ascii") return value def _model_base_url(base_url: Optional[str]) -> str: if not base_url: return "https://api.atlascloud.ai/api/v1/model" parsed = urlparse(base_url) origin = f"{parsed.scheme}://{parsed.netloc}" if parsed.scheme and parsed.netloc else "" path = parsed.path.rstrip("/") marker = "/api/v1/model" if marker in path: prefix = path[: path.index(marker) + len(marker)] return f"{origin}{prefix}" if origin: return f"{origin}{marker}" return base_url.rstrip("/") def atlascloud_model_for_operation(model: str, operation: str) -> str: suffix = "edit" if operation == "edit" else "text-to-image" base = model.rstrip("/") for existing_suffix in ("/text-to-image", "/edit"): if base.endswith(existing_suffix): base = base[: -len(existing_suffix)] break if "/" not in base: base = f"openai/{base}" return f"{base}/{suffix}" def _prediction_id(data: Dict[str, Any]) -> Optional[str]: value = data.get("id") or data.get("prediction_id") return str(value) if value else None def _prediction_result_url(data: Dict[str, Any]) -> Optional[str]: urls = data.get("urls") if not isinstance(urls, dict): return None value = urls.get("get") return str(value) if value else None def _image_to_data_url(path: Path) -> str: mime = mimetypes.guess_type(str(path))[0] or "application/octet-stream" encoded = base64.b64encode(path.read_bytes()).decode("ascii") return f"data:{mime};base64,{encoded}"skills/codex-ppt/scripts/image_providers/base.py887 B1438bb6896e4upstream ↗
from __future__ import annotations from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Dict, List, Optional class ImageProvider(ABC): """Common API shape used by image_gen.py command handlers.""" @abstractmethod def generate(self, payload: Dict[str, Any]) -> List[str]: """Generate images and return base64-encoded image payloads.""" @abstractmethod def edit( self, payload: Dict[str, Any], image_paths: List[Path], mask_path: Optional[Path], ) -> List[str]: """Edit input images and return base64-encoded image payloads.""" @abstractmethod async def generate_batch( self, payload: Dict[str, Any], *, attempts: int, job_label: str, ) -> List[str]: """Generate one batch job with provider-specific retry behavior."""skills/codex-ppt/scripts/image_providers/factory.py734 Bbcf59bbc1ac7upstream ↗
from __future__ import annotations from typing import Optional from urllib.parse import urlparse from .atlascloud import AtlasCloudImageProvider from .base import ImageProvider from .openai_compatible import OpenAICompatibleImageProvider def create_image_provider(*, api_key: Optional[str], base_url: Optional[str]) -> ImageProvider: if _is_atlascloud_base_url(base_url): return AtlasCloudImageProvider(api_key=api_key, base_url=base_url) return OpenAICompatibleImageProvider(api_key=api_key, base_url=base_url) def _is_atlascloud_base_url(base_url: Optional[str]) -> bool: if not base_url: return False hostname = urlparse(base_url).hostname or "" return "atlascloud.ai" in hostname.lower()skills/codex-ppt/scripts/image_providers/openai_compatible.py7.3 KB2184a79074afupstream ↗
from __future__ import annotations import asyncio import os from pathlib import Path import re import sys from typing import Any, Callable, Dict, List, Optional from .base import ImageProvider ClientFactory = Callable[[], Any] DEFAULT_RUNTIME_HOME = "~/.codex-ppt-skill" def _runtime_home() -> Path: return Path(os.getenv("CODEX_PPT_HOME", DEFAULT_RUNTIME_HOME)).expanduser() def _runtime_python_path() -> str: home = _runtime_home() if os.name == "nt": return str(home / ".venv" / "Scripts" / "python.exe") return str(home / ".venv" / "bin" / "python") def _skill_root() -> Path: return Path(__file__).resolve().parents[2] def _dependency_hint(package: str, *, upgrade: bool = False) -> str: package_arg = f"-U {package}" if upgrade else package runtime_python = _runtime_python_path() requirements = _skill_root() / "requirements.txt" return ( "Install codex-ppt dependencies in the shared runtime first, for example " f"`python3 {_skill_root() / 'scripts' / 'codex_ppt_runtime.py'} bootstrap`, " f"or install {package} directly with `{runtime_python} -m pip install " f"{package_arg}`. Requirements file: `{requirements}`." ) def _extract_retry_after_seconds(exc: Exception) -> Optional[float]: for attr in ("retry_after", "retry_after_seconds"): val = getattr(exc, attr, None) if isinstance(val, (int, float)) and val >= 0: return float(val) msg = str(exc) m = re.search(r"retry[- ]after[:= ]+([0-9]+(?:\\.[0-9]+)?)", msg, re.IGNORECASE) if m: try: return float(m.group(1)) except Exception: return None return None def _is_rate_limit_error(exc: Exception) -> bool: name = exc.__class__.__name__.lower() if "ratelimit" in name or "rate_limit" in name: return True msg = str(exc).lower() return "429" in msg or "rate limit" in msg or "too many requests" in msg def _is_transient_error(exc: Exception) -> bool: if _is_rate_limit_error(exc): return True name = exc.__class__.__name__.lower() if "timeout" in name or "timedout" in name or "tempor" in name: return True msg = str(exc).lower() return "timeout" in msg or "timed out" in msg or "connection reset" in msg async def _generate_one_with_retries( client: Any, payload: Dict[str, Any], *, attempts: int, job_label: str, ) -> Any: last_exc: Optional[Exception] = None for attempt in range(1, attempts + 1): try: return await client.images.generate(**payload) except Exception as exc: last_exc = exc if not _is_transient_error(exc): raise if attempt == attempts: raise sleep_s = _extract_retry_after_seconds(exc) if sleep_s is None: sleep_s = min(60.0, 2.0**attempt) print( f"{job_label} attempt {attempt}/{attempts} failed ({exc.__class__.__name__}); retrying in {sleep_s:.1f}s", file=sys.stderr, ) await asyncio.sleep(sleep_s) raise last_exc or RuntimeError("unknown error") class OpenAICompatibleImageProvider(ImageProvider): def __init__( self, *, api_key: Optional[str], base_url: Optional[str], client_factory: Optional[ClientFactory] = None, async_client_factory: Optional[ClientFactory] = None, ) -> None: self.api_key = api_key self.base_url = base_url self._client_factory = client_factory self._async_client_factory = async_client_factory self._async_client: Optional[Any] = None def generate(self, payload: Dict[str, Any]) -> List[str]: result = self._create_client().images.generate(**payload) return [item.b64_json for item in result.data] def edit( self, payload: Dict[str, Any], image_paths: List[Path], mask_path: Optional[Path], ) -> List[str]: with _open_files(image_paths) as image_files, _open_mask(mask_path) as mask_file: request = dict(payload) request["image"] = image_files if len(image_files) > 1 else image_files[0] if mask_file is not None: request["mask"] = mask_file result = self._create_client().images.edit(**request) return [item.b64_json for item in result.data] async def generate_batch( self, payload: Dict[str, Any], *, attempts: int, job_label: str, ) -> List[str]: result = await _generate_one_with_retries( self._create_async_client(), payload, attempts=attempts, job_label=job_label, ) return [item.b64_json for item in result.data] def _create_client(self) -> Any: if self._client_factory is not None: return self._client_factory() try: from openai import OpenAI except ImportError as exc: raise RuntimeError( f"openai SDK not installed in the active environment. {_dependency_hint('openai')}" ) from exc return OpenAI(api_key=self.api_key, base_url=self.base_url) def _create_async_client(self) -> Any: if self._async_client is not None: return self._async_client if self._async_client_factory is not None: self._async_client = self._async_client_factory() return self._async_client try: from openai import AsyncOpenAI except ImportError as exc: try: import openai as _openai # noqa: F401 except ImportError: raise RuntimeError( f"openai SDK not installed in the active environment. {_dependency_hint('openai')}" ) from exc raise RuntimeError( "AsyncOpenAI not available in this openai SDK version. " f"{_dependency_hint('openai', upgrade=True)}" ) from exc self._async_client = AsyncOpenAI(api_key=self.api_key, base_url=self.base_url) return self._async_client def _open_files(paths: List[Path]): return _FileBundle(paths) def _open_mask(mask_path: Optional[Path]): if mask_path is None: return _NullContext() return _SingleFile(mask_path) class _NullContext: def __enter__(self): return None def __exit__(self, exc_type, exc, tb): return False class _SingleFile: def __init__(self, path: Path): self._path = path self._handle = None def __enter__(self): self._handle = self._path.open("rb") return self._handle def __exit__(self, exc_type, exc, tb): if self._handle: try: self._handle.close() except Exception: pass return False class _FileBundle: def __init__(self, paths: List[Path]): self._paths = paths self._handles: List[object] = [] def __enter__(self): self._handles = [p.open("rb") for p in self._paths] return self._handles def __exit__(self, exc_type, exc, tb): for handle in self._handles: try: handle.close() except Exception: pass return Falseskills/codex-ppt/scripts/prepare_slide_prompts.py20 KB1cf3e681db41upstream ↗
#!/usr/bin/env python3 """Prepare per-slide image generation jobs for codex-ppt. This script is deterministic. It does not call an image model. It turns a structured deck spec into one self-contained JSON job file per slide. """ from __future__ import annotations import argparse import json from pathlib import Path import re import sys from typing import Any, Dict, Iterable, List, Optional from slide_run_state import ( DEFAULT_MAX_CONCURRENT_SLIDES, now_iso, rel_to_deck, save_jobs, set_run_status, ) def _die(message: str) -> None: print(f"Error: {message}", file=sys.stderr) raise SystemExit(1) def _read_json(path: Path) -> Dict[str, Any]: if not path.exists(): _die(f"Spec file not found: {path}") try: data = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError as exc: _die(f"Invalid JSON in {path}: {exc}") if not isinstance(data, dict): _die("Deck spec must be a JSON object.") return data def _as_list(value: Any) -> List[Any]: if value is None: return [] if isinstance(value, list): return value return [value] def _string_list(value: Any) -> List[str]: return [str(item).strip() for item in _as_list(value) if str(item).strip()] _MARKDOWN_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)") def _parse_markdown_image(value: str) -> Optional[Dict[str, str]]: match = _MARKDOWN_IMAGE_RE.search(value) if not match: return None alt_text = match.group(1).strip() path = match.group(2).strip() description = value[: match.start()].strip(" \t\n\r:-;") role_parts = [part for part in [description, alt_text] if part] return { "path": path, "role": " — ".join(role_parts) if role_parts else "reference image", } def _resolve_image_path(path: str, *, base_dir: Path) -> str: path = path.strip() if not path: return path if re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*:", path): return path candidate = Path(path) if candidate.is_absolute(): return str(candidate) return str((base_dir / candidate).resolve()) def _normalize_input_image(entry: Any, *, slide_number: int, image_index: int, base_dir: Path) -> Dict[str, Any]: if isinstance(entry, dict): image = dict(entry) raw_path = image.get("path") or image.get("attachment") or image.get("markdown") if isinstance(raw_path, str): parsed = _parse_markdown_image(raw_path) if parsed: image["path"] = parsed["path"] image.setdefault("role", parsed["role"]) if isinstance(image.get("path"), str): image["path"] = _resolve_image_path(image["path"], base_dir=base_dir) return image if isinstance(entry, str): parsed = _parse_markdown_image(entry) if not parsed: _die( f"Slide {slide_number}: required_images entry {image_index} must be an " "object or a Markdown image reference like ." ) lowered = entry.lower() fidelity = "" if "strict input asset" in lowered: fidelity = "strict input asset; preserve the supplied image content" return { "path": _resolve_image_path(parsed["path"], base_dir=base_dir), "role": parsed["role"], "fidelity": fidelity, } _die(f"Slide {slide_number}: required_images entry {image_index} has unsupported type.") def _slide_images(slide: Dict[str, Any], *, slide_number: int, base_dir: Path) -> List[Dict[str, Any]]: images: List[Dict[str, Any]] = [] for index, image in enumerate(_as_list(slide.get("required_images") or slide.get("input_images")), start=1): images.append(_normalize_input_image(image, slide_number=slide_number, image_index=index, base_dir=base_dir)) return images def _sample_generation_method(spec: Dict[str, Any], *, base_dir: Path) -> Optional[Dict[str, Any]]: method = spec.get("sample_generation_method") or spec.get("image_generation_method") if method is None: return None if not isinstance(method, dict): _die("sample_generation_method must be an object when present.") method = dict(method) for key in ("approved_sample_path", "sample_slide_path", "sample_output_path"): if isinstance(method.get(key), str): method[key] = _resolve_image_path(method[key], base_dir=base_dir) return method def _method_backend_label(method: Optional[Dict[str, Any]]) -> Optional[str]: if not method: return None for key in ("backend_used", "selected_backend", "backend", "tool_name"): value = method.get(key) if isinstance(value, str) and value.strip(): return value.strip() return None def _format_block(title: str, value: Any) -> str: if value is None or value == "" or value == [] or value == {}: return "" if isinstance(value, (dict, list)): body = json.dumps(value, ensure_ascii=False, indent=2) else: body = str(value).strip() return f"## {title}\n{body}\n" def _format_input_images(images: Iterable[Dict[str, Any]]) -> str: lines: List[str] = [] for idx, image in enumerate(images, start=1): path = str(image.get("path") or image.get("attachment") or "").strip() role = str(image.get("role") or "reference image").strip() fidelity = str(image.get("fidelity") or image.get("constraints") or "").strip() if not path: _die(f"Input image {idx} is missing path or attachment.") if fidelity: lines.append(f"- Image {idx}: {path} — {role}; {fidelity}") else: lines.append(f"- Image {idx}: {path} — {role}") return "\n".join(lines) def _slide_number(slide: Dict[str, Any], fallback: int) -> int: raw = slide.get("number", fallback) try: number = int(raw) except (TypeError, ValueError): _die(f"Invalid slide number: {raw}") if number <= 0: _die(f"Slide number must be positive: {number}") return number def _build_prompt( *, deck: Dict[str, Any], slide: Dict[str, Any], number: int, global_style_reference: Optional[Dict[str, Any]], base_dir: Path, ) -> str: title = str(slide.get("title") or f"Slide {number}").strip() style = deck.get("style", {}) images: List[Dict[str, Any]] = [] if global_style_reference: images.append(global_style_reference) images.extend(_slide_images(slide, slide_number=number, base_dir=base_dir)) required_background = { key: value for key, value in { "deck_context": deck.get("deck_context"), "slide_local_context": slide.get("local_context"), }.items() if value not in (None, "", [], {}) } prompt_parts = [ "# Codex PPT Slide Image Prompt\n", _format_block("Canvas", { "type": "16:9 full-slide PowerPoint image", "language": deck.get("language", "Chinese"), "slide_number": number, "render_slide_number": False, }), _format_block("Deck Goal", deck.get("goal")), _format_block("Required Background", required_background), _format_block("Global Style", style), ] if images: prompt_parts.append("## Input Images\n") prompt_parts.append(_format_input_images(images)) prompt_parts.append("\n") prompt_parts.extend( [ _format_block("Slide", { "number": number, "title": title, "role": slide.get("role"), "intent": slide.get("intent"), }), _format_block("Text", { "title": title, "key_points": _string_list(slide.get("key_points")), "speaker_focus": slide.get("speaker_focus"), }), _format_block("Layout", slide.get("layout")), _format_block("Visual Elements", slide.get("visual_elements")), _format_block("Source Image Rules", slide.get("source_image_rules")), _format_block("Constraints", _string_list(slide.get("constraints"))), ] ) if global_style_reference: prompt_parts.append( "## Style Reference Rule\n" "Use Image 1 as the approved sample-slide style reference. Match its palette, " "typography mood, density, texture, and overall visual identity. Do not copy " "its exact layout unless this slide's layout explicitly asks for it.\n" ) if images: prompt_parts.append( "## Input Image Handling Rules\n" "For any input image marked as a strict input asset, include it visibly and " "preserve its content. Do not redraw, replace, relabel, or invent a similar " "figure. Scale and crop only as needed for composition while keeping the " "important labels, arrows, data, and relationships recognizable.\n" ) prompt_parts.append( "## Universal Constraints\n" "- The final image itself must contain the title and key points.\n" "- Render Chinese text exactly and legibly; avoid garbled characters.\n" "- Keep the confirmed deck style consistent while varying layout by slide role.\n" "- No watermark, unrelated logo, or extra slide number.\n" ) return "\n".join(part for part in prompt_parts if part) def _job_images( slide: Dict[str, Any], *, number: int, global_style_reference: Optional[Dict[str, Any]], base_dir: Path, ) -> List[Dict[str, Any]]: images: List[Dict[str, Any]] = [] if global_style_reference: images.append(global_style_reference) images.extend(_slide_images(slide, slide_number=number, base_dir=base_dir)) return images def _write_template(path: Path) -> None: template = { "deck_name": "example-deck", "language": "Chinese", "goal": "Explain the core idea of the source article.", "deck_context": { "source_summary": "Short source-wide summary that workers may need when a slide refers to the broader article.", "core_claim": "The central thesis that should stay consistent across the deck.", "canonical_terms": ["Term one", "Term two", "Term three"], }, "selected_image_backend": "built-in image tool", "max_concurrent_slides": 6, "sample_generation_method": { "backend_used": "built-in image tool", "tool_name": "image_gen", "mode": "generate", "prompt_source": "the approved sample slide job prompt", "size": "16:9 landscape, 2560x1440 target", "quality": "medium", "approved_sample_path": "/absolute/path/to/approved-sample-slide.png", "input_context_preparation": "view_image local required images before built-in generation", "handoff_rule": "Subagents must use this same backend/tool/mode; return a blocker if unavailable.", }, "style": { "name": "手绘技术解释风", "visual_direction": "clean hand-drawn technical explainer", "color_palette": "white background, black marker lines, pale yellow highlights", "typography": "large readable Chinese headings, compact handwritten annotations", }, "approved_style_reference": { "path": "/absolute/path/to/approved-sample-slide.png", "role": "approved sample slide style reference", "fidelity": "match style only; do not copy layout or content", }, "slides": [ { "number": 1, "title": "Cover", "role": "cover", "intent": "Open the talk", "key_points": ["Point one", "Point two"], "local_context": { "required_background": "Facts, lists, definitions, comparisons, or prior-slide references this slide needs to be self-contained.", }, "layout": {"composition": "large title with one supporting visual"}, "visual_elements": {"main_visual": "topic-specific hand-drawn metaphor"}, "constraints": ["Keep text sparse"], "sample_approved": True, }, { "number": 2, "title": "Evidence", "role": "data evidence", "intent": "Explain a supplied result figure", "key_points": ["Preserve the original figure", "Add two callouts"], "required_images": [ { "path": "/absolute/path/to/result_01.png", "role": "strict input asset and main evidence figure", "fidelity": "preserve data, axes, labels, legends, colors, and values", }, "strict input asset and comparison chart\n\n", ], "layout": {"composition": "source figure left, explanation cards right"}, }, ], } path.write_text(json.dumps(template, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--spec", help="Deck spec JSON file.") parser.add_argument("--out-dir", help="Deck project directory.") parser.add_argument("--write-template", help="Write an example deck spec JSON and exit.") parser.add_argument( "--selected-backend", help="Confirmed image backend label, such as `built-in image tool` or `scripts/image_gen.py`.", ) parser.add_argument( "--max-concurrent-slides", type=int, default=None, help=f"Maximum slide subagents to dispatch at once. Defaults to {DEFAULT_MAX_CONCURRENT_SLIDES}.", ) parser.add_argument("--force", action="store_true", help="Overwrite existing prompt files.") args = parser.parse_args() if args.write_template: _write_template(Path(args.write_template)) return 0 if not args.spec or not args.out_dir: _die("Use --spec and --out-dir, or --write-template.") spec_path = Path(args.spec) spec = _read_json(spec_path) spec_dir = spec_path.resolve().parent slides = spec.get("slides") if not isinstance(slides, list) or not slides: _die("Deck spec must include a non-empty slides array.") numbered_slides: List[tuple[int, Dict[str, Any], int]] = [] seen_slide_numbers: Dict[int, int] = {} for fallback, slide in enumerate(slides, start=1): if not isinstance(slide, dict): _die(f"Slide entry {fallback} must be an object.") number = _slide_number(slide, fallback) if number in seen_slide_numbers: _die( f"Duplicate slide number {number}: slide entries " f"{seen_slide_numbers[number]} and {fallback} would both write slide_{number:02d}.json." ) seen_slide_numbers[number] = fallback numbered_slides.append((fallback, slide, number)) out_dir = Path(args.out_dir) prompts_dir = out_dir / "prompts" prompts_dir.mkdir(parents=True, exist_ok=True) (out_dir / "origin_image").mkdir(parents=True, exist_ok=True) global_style_reference = spec.get("approved_style_reference") if global_style_reference is not None and not isinstance(global_style_reference, dict): _die("approved_style_reference must be an object when present.") if global_style_reference and isinstance(global_style_reference.get("path"), str): global_style_reference = dict(global_style_reference) global_style_reference["path"] = _resolve_image_path(global_style_reference["path"], base_dir=spec_dir) sample_generation_method = _sample_generation_method(spec, base_dir=spec_dir) max_concurrent_slides = args.max_concurrent_slides if max_concurrent_slides is None: max_concurrent_slides = int(spec.get("max_concurrent_slides", DEFAULT_MAX_CONCURRENT_SLIDES)) if max_concurrent_slides < 1: _die("max_concurrent_slides must be >= 1.") selected_backend = ( args.selected_backend or spec.get("selected_image_backend") or spec.get("image_backend") or _method_backend_label(sample_generation_method) ) slide_job_entries: List[Dict[str, Any]] = [] for fallback, slide, number in numbered_slides: use_style_reference = bool(slide.get("use_approved_style_reference", True)) slide_style_reference = global_style_reference if use_style_reference else None prompt = _build_prompt( deck=spec, slide=slide, number=number, global_style_reference=slide_style_reference, base_dir=spec_dir, ) images = _job_images(slide, number=number, global_style_reference=slide_style_reference, base_dir=spec_dir) job = { "slide": number, "title": slide.get("title", f"Slide {number}"), "prompt": prompt, "out": f"slide_{number:02d}.png", "input_images": images, "requires_context_images": bool(images), "expected_backend": selected_backend, "sample_generation_method": sample_generation_method, "generation_contract": { "must_use_selected_image_backend": True, "must_match_sample_generation_method": bool(sample_generation_method), "forbidden_final_image_methods": [ "local drawing/rendering scripts", "Pillow-generated slides", "SVG/HTML/CSS/canvas screenshots", "python-pptx/PptxGenJS/native PPT layout screenshots", "manually composited text/image overlays", ], "must_return": ["backend_used", "selected_source", "qa_note"], }, } prompt_path = prompts_dir / f"slide_{number:02d}.json" if prompt_path.exists() and not args.force: _die(f"Slide job file already exists: {prompt_path} (use --force)") prompt_path.write_text(json.dumps(job, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") slide_id = f"slide_{number:02d}" final_image = out_dir / "origin_image" / f"{slide_id}.png" sample_approved = bool(slide.get("sample_approved") or slide.get("approved_sample")) status = "accepted" if sample_approved and final_image.exists() else "pending" slide_job_entries.append( { "slide_id": slide_id, "number": number, "title": slide.get("title", f"Slide {number}"), "job": rel_to_deck(out_dir, prompt_path), "out": rel_to_deck(out_dir, final_image), "input_images": images, "requires_context_images": bool(images), "status": status, "dispatch": None, "result": { "final_image": rel_to_deck(out_dir, final_image), "accepted_sample": True, } if status == "accepted" else None, "blocker": None, } ) slide_jobs = { "run_status": "jobs_prepared", "deck_name": spec.get("deck_name"), "selected_backend": selected_backend, "sample_generation_method": sample_generation_method, "max_concurrent_slides": max_concurrent_slides, "slides": slide_job_entries, "updated_at": now_iso(), } save_jobs(out_dir, slide_jobs) set_run_status(out_dir, "jobs_prepared", "prepared slide prompt jobs") print(f"Wrote {len(slides)} slide job file(s) to {prompts_dir}") print(f"Wrote slide job state to {out_dir / 'slide_jobs.json'}") return 0 if __name__ == "__main__": raise SystemExit(main())skills/codex-ppt/scripts/record_slide_blocker.py1.4 KBc5098f752976upstream ↗
#!/usr/bin/env python3 """Record a blocker that prevents a codex-ppt slide job from completing.""" from __future__ import annotations import argparse from slide_run_state import ( deck_dir_from_target, find_slide, locked_jobs, now_iso, set_run_status, update_jobs_run_status, ) def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("deck", help="Deck directory or slide_jobs.json") parser.add_argument("--slide", required=True, help="slide_01 or 1") parser.add_argument("--reason", required=True) parser.add_argument("--agent-id") args = parser.parse_args() deck_dir = deck_dir_from_target(args.deck) with locked_jobs(deck_dir) as jobs: slide = find_slide(jobs, args.slide) if slide.get("status") in {"recorded", "accepted"}: raise SystemExit(f"{slide['slide_id']} is already complete; refusing to mark it blocked.") slide["blocker"] = { "agent_id": args.agent_id, "reason": args.reason, "blocked_at": now_iso(), } slide["status"] = "blocked" update_jobs_run_status(jobs) jobs["run_status"] = "blocked" slide_id = slide["slide_id"] set_run_status(deck_dir, "blocked", f"{slide_id}: {args.reason}") print(f"{slide_id} -> blocked") return 0 if __name__ == "__main__": raise SystemExit(main())skills/codex-ppt/scripts/record_slide_dispatch.py2.3 KB4dd529e8f634upstream ↗
#!/usr/bin/env python3 """Record that a codex-ppt slide job was dispatched to a subagent.""" from __future__ import annotations import argparse from pathlib import Path from slide_run_state import ( deck_dir_from_target, find_slide, locked_jobs, now_iso, rel_to_deck, resolve_deck_path, set_run_status, sha256_file, update_jobs_run_status, ) def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("deck", help="Deck directory or slide_jobs.json") parser.add_argument("--slide", required=True, help="slide_01 or 1") parser.add_argument("--agent-id", required=True) parser.add_argument("--agent-nickname") parser.add_argument("--prompt-file", help="Prompt file path. Defaults to the job file in slide_jobs.json.") args = parser.parse_args() deck_dir = deck_dir_from_target(args.deck) with locked_jobs(deck_dir) as jobs: slide = find_slide(jobs, args.slide) if slide.get("status") != "pending": raise SystemExit(f"{slide['slide_id']} must be pending before dispatch; got {slide.get('status')}") prompt_ref = args.prompt_file or slide.get("job") if not prompt_ref: raise SystemExit(f"{slide['slide_id']} has no prompt job path.") prompt_path = resolve_deck_path(deck_dir, prompt_ref) try: prompt_path.relative_to(deck_dir) except ValueError as exc: raise SystemExit(f"Prompt file must live inside deck dir: {prompt_path}") from exc if not prompt_path.exists(): raise SystemExit(f"Prompt file does not exist: {prompt_path}") slide["dispatch"] = { "agent_id": args.agent_id, "agent_nickname": args.agent_nickname, "prompt": rel_to_deck(deck_dir, prompt_path), "prompt_sha256": sha256_file(prompt_path), "dispatched_at": now_iso(), } slide["status"] = "dispatched" update_jobs_run_status(jobs) run_status = jobs.get("run_status") if run_status == "slides_dispatched": set_run_status(deck_dir, "slides_dispatched", "all slide jobs dispatched") print(f"{slide['slide_id']} -> dispatched") return 0 if __name__ == "__main__": raise SystemExit(main())skills/codex-ppt/scripts/record_slide_result.py6.6 KBe0d8d622f319upstream ↗
#!/usr/bin/env python3 """Record and copy a codex-ppt slide image generated by a subagent.""" from __future__ import annotations import argparse import json import re import shutil from pathlib import Path from slide_run_state import ( deck_dir_from_target, ensure_file, find_slide, locked_jobs, now_iso, rel_to_deck, resolve_deck_path, set_run_status, sha256_file, update_jobs_run_status, ) FORBIDDEN_BACKEND_TERMS = ( "pillow", "html", "svg", "canvas", "python-pptx", "pptxgenjs", "manual", "script render", ) def _validate_backend(backend: str) -> str: value = backend.strip() if not value: raise SystemExit("--backend-used must not be empty") lowered = value.lower() for term in FORBIDDEN_BACKEND_TERMS: if term in lowered: raise SystemExit(f"Forbidden backend for final slide image: {backend}") if "image" not in lowered and "built-in" not in lowered: raise SystemExit( "--backend-used must name the selected image backend, such as " "`built-in image tool` or `scripts/image_gen.py`." ) return value def _backend_family(value: str) -> str: lowered = value.lower() if "image_gen.py" in lowered or "scripts/image_gen" in lowered: return "cli-api-fallback" if "cli" in lowered or "api" in lowered or "fallback" in lowered: return "cli-api-fallback" if "built-in" in lowered or "builtin" in lowered or "image_generate" in lowered: return "built-in-image-tool" if "image_gen" in lowered: return "built-in-image-tool" return "" def _normalized_backend_label(value: str) -> str: return re.sub(r"[^a-z0-9]+", "", value.lower()) def _method_backend_labels(method: object) -> list[str]: if not isinstance(method, dict): return [] labels: list[str] = [] for key in ("backend_used", "selected_backend", "backend", "tool_name"): value = method.get(key) if isinstance(value, str) and value.strip(): labels.append(value.strip()) return labels def _load_prompt_job(deck_dir: Path, slide: dict) -> dict: job_ref = slide.get("job") if not isinstance(job_ref, str) or not job_ref.strip(): return {} path = resolve_deck_path(deck_dir, job_ref) if not path.exists(): return {} data = json.loads(path.read_text(encoding="utf-8")) return data if isinstance(data, dict) else {} def _expected_backend_labels(jobs: dict, slide: dict, prompt_job: dict) -> list[str]: labels: list[str] = [] for value in (jobs.get("selected_backend"), prompt_job.get("expected_backend")): if isinstance(value, str) and value.strip(): labels.append(value.strip()) labels.extend(_method_backend_labels(jobs.get("sample_generation_method"))) labels.extend(_method_backend_labels(prompt_job.get("sample_generation_method"))) unique_labels: list[str] = [] for label in labels: if label not in unique_labels: unique_labels.append(label) return unique_labels def _matched_expected_backend(backend_used: str, expected_labels: list[str]) -> str | None: if not expected_labels: return None used_normalized = _normalized_backend_label(backend_used) used_family = _backend_family(backend_used) for label in expected_labels: if _normalized_backend_label(label) == used_normalized: return label expected_family = _backend_family(label) if expected_family and expected_family == used_family: return label raise SystemExit( "Backend mismatch: worker reported " f"`{backend_used}`, but slide job expects one of: {', '.join(expected_labels)}" ) def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("deck", help="Deck directory or slide_jobs.json") parser.add_argument("--slide", required=True, help="slide_01 or 1") parser.add_argument("--agent-id", required=True) parser.add_argument("--backend-used", required=True) parser.add_argument("--selected-source", required=True, help="Generated image selected by the worker.") parser.add_argument("--qa-note", required=True) args = parser.parse_args() deck_dir = deck_dir_from_target(args.deck) with locked_jobs(deck_dir) as jobs: slide = find_slide(jobs, args.slide) if slide.get("status") != "dispatched": raise SystemExit(f"{slide['slide_id']} must be dispatched before result recording; got {slide.get('status')}") dispatch = slide.get("dispatch") or {} if dispatch.get("agent_id") != args.agent_id: raise SystemExit( f"Agent id mismatch for {slide['slide_id']}: dispatch={dispatch.get('agent_id')} result={args.agent_id}" ) backend_used = _validate_backend(args.backend_used) prompt_job = _load_prompt_job(deck_dir, slide) expected_backend_labels = _expected_backend_labels(jobs, slide, prompt_job) matched_expected_backend = _matched_expected_backend(backend_used, expected_backend_labels) source = ensure_file(Path(args.selected_source).expanduser().resolve(), "selected source image") out_ref = slide.get("out") or f"origin_image/{slide['slide_id']}.png" target = resolve_deck_path(deck_dir, out_ref) try: target.relative_to(deck_dir) except ValueError as exc: raise SystemExit(f"Final slide image must live inside deck dir: {target}") from exc target.parent.mkdir(parents=True, exist_ok=True) if source != target: shutil.copy2(source, target) slide["result"] = { "agent_id": args.agent_id, "backend_used": backend_used, "selected_source": str(source), "selected_source_sha256": sha256_file(source), "final_image": rel_to_deck(deck_dir, target), "final_image_sha256": sha256_file(target), "expected_backend": matched_expected_backend, "expected_backend_labels": expected_backend_labels, "sample_generation_method_matched": bool(matched_expected_backend), "qa_note": args.qa_note, "recorded_at": now_iso(), } slide["status"] = "recorded" update_jobs_run_status(jobs) run_status = jobs.get("run_status") slide_id = slide["slide_id"] if run_status == "slides_recorded": set_run_status(deck_dir, "slides_recorded", "all slide images recorded") print(json.dumps({"slide_id": slide_id, "status": "recorded"}, ensure_ascii=False)) return 0 if __name__ == "__main__": raise SystemExit(main())skills/codex-ppt/scripts/remove_chroma_key.py14 KB5311f287b080upstream ↗
#!/usr/bin/env python3 """Remove a solid chroma-key background from a codex-ppt slide image. This helper supports the CLI/API transparent fallback workflow: generate an image on a flat key color, then convert that key color to alpha. """ from __future__ import annotations import argparse from io import BytesIO from pathlib import Path import re from statistics import median import sys from typing import Tuple Color = Tuple[int, int, int] KEY_DOMINANCE_THRESHOLD = 16.0 ALPHA_NOISE_FLOOR = 8 DEFAULT_RUNTIME_HOME = "~/.codex-ppt-skill" def _die(message: str, code: int = 1) -> None: print(f"Error: {message}", file=sys.stderr) raise SystemExit(code) def _dependency_hint(package: str) -> str: home = Path(os.getenv("CODEX_PPT_HOME", DEFAULT_RUNTIME_HOME)).expanduser() if os.name == "nt": python = home / ".venv" / "Scripts" / "python.exe" else: python = home / ".venv" / "bin" / "python" skill_root = Path(__file__).resolve().parents[1] return ( "Install codex-ppt dependencies in the shared runtime first, for example " f"`python3 {skill_root / 'scripts' / 'codex_ppt_runtime.py'} bootstrap`, " f"or install {package} directly with `{python} -m pip install {package}`." ) def _load_pillow(): try: from PIL import Image, ImageFilter except ImportError: _die(f"Pillow is required for chroma-key removal. {_dependency_hint('pillow')}") return Image, ImageFilter def _parse_key_color(raw: str) -> Color: value = raw.strip() match = re.fullmatch(r"#?([0-9a-fA-F]{6})", value) if not match: _die("key color must be a hex RGB value like #00ff00.") hex_value = match.group(1) return ( int(hex_value[0:2], 16), int(hex_value[2:4], 16), int(hex_value[4:6], 16), ) def _validate_args(args: argparse.Namespace) -> None: if args.tolerance < 0 or args.tolerance > 255: _die("--tolerance must be between 0 and 255.") if args.transparent_threshold < 0 or args.transparent_threshold > 255: _die("--transparent-threshold must be between 0 and 255.") if args.opaque_threshold < 0 or args.opaque_threshold > 255: _die("--opaque-threshold must be between 0 and 255.") if args.soft_matte and args.transparent_threshold >= args.opaque_threshold: _die("--transparent-threshold must be lower than --opaque-threshold.") if args.edge_feather < 0 or args.edge_feather > 64: _die("--edge-feather must be between 0 and 64.") if args.edge_contract < 0 or args.edge_contract > 16: _die("--edge-contract must be between 0 and 16.") src = Path(args.input) if not src.exists(): _die(f"Input image not found: {src}") out = Path(args.out) if out.exists() and not args.force: _die(f"Output already exists: {out} (use --force to overwrite)") if out.suffix.lower() not in {".png", ".webp"}: _die("--out must end in .png or .webp so the alpha channel is preserved.") def _channel_distance(a: Color, b: Color) -> int: return max(abs(a[0] - b[0]), abs(a[1] - b[1]), abs(a[2] - b[2])) def _clamp_channel(value: float) -> int: return max(0, min(255, int(round(value)))) def _smoothstep(value: float) -> float: value = max(0.0, min(1.0, value)) return value * value * (3.0 - 2.0 * value) def _soft_alpha(distance: int, transparent_threshold: float, opaque_threshold: float) -> int: if distance <= transparent_threshold: return 0 if distance >= opaque_threshold: return 255 ratio = (float(distance) - transparent_threshold) / ( opaque_threshold - transparent_threshold ) return _clamp_channel(255.0 * _smoothstep(ratio)) def _dominance_alpha(rgb: Color, key: Color) -> int: spill_channels = _spill_channels(key) if not spill_channels: return 255 channels = [float(value) for value in rgb] non_spill = [idx for idx in range(3) if idx not in spill_channels] key_strength = ( min(channels[idx] for idx in spill_channels) if len(spill_channels) > 1 else channels[spill_channels[0]] ) non_key_strength = max((channels[idx] for idx in non_spill), default=0.0) dominance = key_strength - non_key_strength if dominance <= 0: return 255 denominator = max(1.0, float(max(key)) - non_key_strength) alpha = 1.0 - min(1.0, dominance / denominator) return _clamp_channel(alpha * 255.0) def _spill_channels(key: Color) -> list[int]: key_max = max(key) if key_max < 128: return [] return [idx for idx, value in enumerate(key) if value >= key_max - 16 and value >= 128] def _key_channel_dominance(rgb: Color, key: Color) -> float: spill_channels = _spill_channels(key) if not spill_channels: return 0.0 channels = [float(value) for value in rgb] non_spill = [idx for idx in range(3) if idx not in spill_channels] key_strength = ( min(channels[idx] for idx in spill_channels) if len(spill_channels) > 1 else channels[spill_channels[0]] ) non_key_strength = max((channels[idx] for idx in non_spill), default=0.0) return key_strength - non_key_strength def _looks_key_colored(rgb: Color, key: Color, distance: int) -> bool: if distance <= 32: return True spill_channels = _spill_channels(key) if not spill_channels: return True return _key_channel_dominance(rgb, key) >= KEY_DOMINANCE_THRESHOLD def _cleanup_spill(rgb: Color, key: Color, alpha: int = 255) -> Color: if alpha >= 252: return rgb spill_channels = _spill_channels(key) if not spill_channels: return rgb channels = [float(value) for value in rgb] non_spill = [idx for idx in range(3) if idx not in spill_channels] if non_spill: anchor = max(channels[idx] for idx in non_spill) cap = max(0.0, anchor - 1.0) for idx in spill_channels: if channels[idx] > cap: channels[idx] = cap return ( _clamp_channel(channels[0]), _clamp_channel(channels[1]), _clamp_channel(channels[2]), ) def _apply_alpha_to_image( image, *, key: Color, tolerance: int, spill_cleanup: bool, soft_matte: bool, transparent_threshold: float, opaque_threshold: float, ) -> int: pixels = image.load() width, height = image.size transparent = 0 for y in range(height): for x in range(width): red, green, blue, alpha = pixels[x, y] rgb = (red, green, blue) distance = _channel_distance(rgb, key) key_like = _looks_key_colored(rgb, key, distance) output_alpha = ( min( _soft_alpha(distance, transparent_threshold, opaque_threshold), _dominance_alpha(rgb, key), ) if soft_matte and key_like else (0 if distance <= tolerance else 255) ) output_alpha = int(round(output_alpha * (alpha / 255.0))) if 0 < output_alpha <= ALPHA_NOISE_FLOOR: output_alpha = 0 if output_alpha == 0: pixels[x, y] = (0, 0, 0, 0) transparent += 1 continue if spill_cleanup and key_like: red, green, blue = _cleanup_spill(rgb, key, output_alpha) pixels[x, y] = (red, green, blue, output_alpha) return transparent def _contract_alpha(image, pixels: int): if pixels == 0: return image _, ImageFilter = _load_pillow() alpha = image.getchannel("A") for _ in range(pixels): alpha = alpha.filter(ImageFilter.MinFilter(3)) image.putalpha(alpha) return image def _apply_edge_feather(image, radius: float): if radius == 0: return image _, ImageFilter = _load_pillow() alpha = image.getchannel("A") alpha = alpha.filter(ImageFilter.GaussianBlur(radius=radius)) image.putalpha(alpha) return image def _encode_image(image, output_format: str) -> bytes: out = BytesIO() image.save(out, format=output_format.upper()) return out.getvalue() def _alpha_counts(image) -> tuple[int, int, int]: pixels = image.load() width, height = image.size total = 0 transparent = 0 partial = 0 for y in range(height): for x in range(width): alpha = pixels[x, y][3] total += 1 if alpha == 0: transparent += 1 elif alpha < 255: partial += 1 return total, transparent, partial def _sample_border_key(image, mode: str) -> Color: width, height = image.size pixels = image.load() samples: list[Color] = [] if mode == "corners": patch = max(1, min(width, height, 12)) boxes = [ (0, 0, patch, patch), (width - patch, 0, width, patch), (0, height - patch, patch, height), (width - patch, height - patch, width, height), ] for left, top, right, bottom in boxes: for y in range(top, bottom): for x in range(left, right): red, green, blue = pixels[x, y][:3] samples.append((red, green, blue)) else: band = max(1, min(width, height, 6)) step = max(1, min(width, height) // 256) for x in range(0, width, step): for y in range(band): red, green, blue = pixels[x, y][:3] samples.append((red, green, blue)) red, green, blue = pixels[x, height - 1 - y][:3] samples.append((red, green, blue)) for y in range(0, height, step): for x in range(band): red, green, blue = pixels[x, y][:3] samples.append((red, green, blue)) red, green, blue = pixels[width - 1 - x, y][:3] samples.append((red, green, blue)) if not samples: _die("Could not sample background key color from image border.") return ( int(round(median(sample[0] for sample in samples))), int(round(median(sample[1] for sample in samples))), int(round(median(sample[2] for sample in samples))), ) def _remove_chroma_key(args: argparse.Namespace) -> None: Image, _ = _load_pillow() src = Path(args.input) out = Path(args.out) with Image.open(src) as image: rgba = image.convert("RGBA") key = ( _sample_border_key(rgba, args.auto_key) if args.auto_key != "none" else _parse_key_color(args.key_color) ) transparent = _apply_alpha_to_image( rgba, key=key, tolerance=args.tolerance, spill_cleanup=args.spill_cleanup, soft_matte=args.soft_matte, transparent_threshold=args.transparent_threshold, opaque_threshold=args.opaque_threshold, ) rgba = _contract_alpha(rgba, args.edge_contract) rgba = _apply_edge_feather(rgba, args.edge_feather) total, transparent_after, partial_after = _alpha_counts(rgba) out.parent.mkdir(parents=True, exist_ok=True) output_format = "PNG" if out.suffix.lower() == ".png" else "WEBP" out.write_bytes(_encode_image(rgba, output_format)) print(f"Wrote {out}") print(f"Key color: #{key[0]:02x}{key[1]:02x}{key[2]:02x}") print(f"Transparent pixels: {transparent_after}/{total}") print(f"Partially transparent pixels: {partial_after}/{total}") if transparent == 0: print("Warning: no pixels matched the key color before feathering.", file=sys.stderr) def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Remove a solid chroma-key background and write an image with alpha." ) parser.add_argument("--input", required=True, help="Input image path.") parser.add_argument("--out", required=True, help="Output .png or .webp path.") parser.add_argument( "--key-color", default="#00ff00", help="Hex RGB key color to remove, for example #00ff00.", ) parser.add_argument( "--tolerance", type=int, default=12, help="Hard-key per-channel tolerance for matching the key color, 0-255.", ) parser.add_argument( "--auto-key", choices=["none", "corners", "border"], default="none", help="Sample the key color from image corners or border instead of --key-color.", ) parser.add_argument( "--soft-matte", action="store_true", help="Use a smooth alpha ramp between transparent and opaque thresholds.", ) parser.add_argument( "--transparent-threshold", type=float, default=12.0, help="Soft-matte distance at or below which pixels become fully transparent.", ) parser.add_argument( "--opaque-threshold", type=float, default=96.0, help="Soft-matte distance at or above which pixels become fully opaque.", ) parser.add_argument( "--edge-feather", type=float, default=0.0, help="Optional alpha blur radius for softened edges, 0-64.", ) parser.add_argument( "--edge-contract", type=int, default=0, help="Shrink the visible alpha matte by this many pixels before feathering.", ) parser.add_argument( "--spill-cleanup", dest="spill_cleanup", action="store_true", help="Reduce obvious key-color spill on opaque pixels.", ) parser.add_argument( "--despill", dest="spill_cleanup", action="store_true", help="Alias for --spill-cleanup; decontaminate key-color edge spill.", ) parser.add_argument("--force", action="store_true", help="Overwrite an existing output file.") return parser def main() -> None: parser = _build_parser() args = parser.parse_args() _validate_args(args) _remove_chroma_key(args) if __name__ == "__main__": main()skills/codex-ppt/scripts/slide_job_status.py2.3 KB09ee4104178eupstream ↗
#!/usr/bin/env python3 """Print codex-ppt slide generation job status.""" from __future__ import annotations import argparse import json from collections import Counter, defaultdict from slide_run_state import ( active_slides, deck_dir_from_target, dispatch_slots_available, dispatchable_slides, load_jobs, load_run_state, max_concurrent_slides, slide_ids, ) def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("deck", help="Deck directory or slide_jobs.json") parser.add_argument("--json", action="store_true") args = parser.parse_args() deck_dir = deck_dir_from_target(args.deck) jobs = load_jobs(deck_dir) state = load_run_state(deck_dir) by_status = defaultdict(list) for slide in jobs.get("slides", []): by_status[slide.get("status", "unknown")].append(slide.get("slide_id")) summary = { "deck_dir": str(deck_dir), "run_status": state.get("status"), "slide_count": len(jobs.get("slides", [])), "selected_backend": jobs.get("selected_backend"), "max_concurrent_slides": max_concurrent_slides(jobs), "active_dispatches": slide_ids(active_slides(jobs)), "dispatch_slots_available": dispatch_slots_available(jobs), "dispatchable_slides": slide_ids(dispatchable_slides(jobs)), "counts": dict(Counter(slide.get("status", "unknown") for slide in jobs.get("slides", []))), "slides": dict(sorted(by_status.items())), } if args.json: print(json.dumps(summary, ensure_ascii=False, indent=2)) return 0 print(f"deck_dir={summary['deck_dir']}") print(f"run_status={summary['run_status']}") print(f"selected_backend={summary['selected_backend'] or '-'}") print(f"max_concurrent_slides={summary['max_concurrent_slides']}") print(f"active_dispatches={', '.join(summary['active_dispatches']) if summary['active_dispatches'] else '-'}") print(f"dispatch_slots_available={summary['dispatch_slots_available']}") print(f"dispatchable_slides={', '.join(summary['dispatchable_slides']) if summary['dispatchable_slides'] else '-'}") for status, slides in summary["slides"].items(): print(f"{status}: {', '.join(slides) if slides else '-'}") return 0 if __name__ == "__main__": raise SystemExit(main())skills/codex-ppt/scripts/slide_run_state.py6.4 KBdc1f5d21573fupstream ↗
#!/usr/bin/env python3 """State helpers for codex-ppt slide generation runs.""" from __future__ import annotations import hashlib import json import os import tempfile from contextlib import contextmanager from datetime import datetime, timezone from pathlib import Path from typing import Any, Dict, Iterable, List from filelock import FileLock ACTIVE_SLIDE_STATUSES = {"dispatched"} DISPATCHABLE_SLIDE_STATUSES = {"pending"} TERMINAL_SLIDE_STATUSES = {"recorded", "accepted", "blocked"} DEFAULT_MAX_CONCURRENT_SLIDES = 6 def now_iso() -> str: return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") def read_json(path: Path, default: Any = None) -> Any: path = Path(path) if not path.exists(): if default is not None: return default raise FileNotFoundError(path) return json.loads(path.read_text(encoding="utf-8")) def write_json(path: Path, data: Any) -> None: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) body = json.dumps(data, ensure_ascii=False, indent=2) + "\n" fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(body) handle.flush() os.fsync(handle.fileno()) os.replace(temp_name, path) finally: if os.path.exists(temp_name): os.unlink(temp_name) @contextmanager def locked_json(path: Path, default: Any = None): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) lock_path = path.with_name(f".{path.name}.lock") with FileLock(str(lock_path)): data = read_json(path, default=default) try: yield data except Exception: raise else: write_json(path, data) def sha256_file(path: Path) -> str: digest = hashlib.sha256() with Path(path).open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def deck_dir_from_target(target: str) -> Path: path = Path(target).expanduser().resolve() if path.is_dir(): return path if path.name == "slide_jobs.json": return path.parent raise ValueError(f"Expected deck directory or slide_jobs.json: {target}") def slide_jobs_path(deck_dir: Path) -> Path: return Path(deck_dir) / "slide_jobs.json" def run_state_path(deck_dir: Path) -> Path: return Path(deck_dir) / "slide_run_state.json" def load_jobs(deck_dir: Path) -> Dict[str, Any]: return read_json(slide_jobs_path(deck_dir)) def save_jobs(deck_dir: Path, jobs: Dict[str, Any]) -> None: write_json(slide_jobs_path(deck_dir), jobs) def locked_jobs(deck_dir: Path): return locked_json(slide_jobs_path(deck_dir)) def load_run_state(deck_dir: Path) -> Dict[str, Any]: return read_json(run_state_path(deck_dir), default={"status": "created", "history": []}) def save_run_state(deck_dir: Path, state: Dict[str, Any]) -> None: write_json(run_state_path(deck_dir), state) def locked_run_state(deck_dir: Path) -> Any: return locked_json(run_state_path(deck_dir), default={"status": "created", "history": []}) def set_run_status(deck_dir: Path, status: str, note: str | None = None) -> Dict[str, Any]: with locked_run_state(deck_dir) as state: if state.get("status") != status: state.setdefault("history", []).append( {"from": state.get("status"), "to": status, "at": now_iso(), "note": note} ) state["status"] = status state["updated_at"] = now_iso() return state def normalize_slide_id(value: Any) -> str: text = str(value).strip() if text.startswith("slide_"): suffix = text.removeprefix("slide_") if suffix.isdigit(): return f"slide_{int(suffix):02d}" if text.isdigit(): return f"slide_{int(text):02d}" raise ValueError(f"Invalid slide id: {value}") def find_slide(jobs: Dict[str, Any], slide: Any) -> Dict[str, Any]: slide_id = normalize_slide_id(slide) for entry in jobs.get("slides", []): if entry.get("slide_id") == slide_id or str(entry.get("number")) == str(slide): return entry raise KeyError(f"Slide not found in slide_jobs.json: {slide_id}") def resolve_deck_path(deck_dir: Path, value: str) -> Path: path = Path(value) if not path.is_absolute(): path = Path(deck_dir) / path return path.resolve() def rel_to_deck(deck_dir: Path, value: Path) -> str: return Path(value).resolve().relative_to(Path(deck_dir).resolve()).as_posix() def ensure_file(path: Path, label: str) -> Path: path = Path(path) if not path.exists() or not path.is_file(): raise FileNotFoundError(f"Missing {label}: {path}") return path def active_slides(jobs: Dict[str, Any]) -> List[Dict[str, Any]]: return [slide for slide in jobs.get("slides", []) if slide.get("status") in ACTIVE_SLIDE_STATUSES] def dispatchable_slides(jobs: Dict[str, Any]) -> List[Dict[str, Any]]: return [slide for slide in jobs.get("slides", []) if slide.get("status") in DISPATCHABLE_SLIDE_STATUSES] def max_concurrent_slides(jobs: Dict[str, Any]) -> int: value = jobs.get("max_concurrent_slides", DEFAULT_MAX_CONCURRENT_SLIDES) try: value = int(value) except (TypeError, ValueError) as exc: raise ValueError(f"Invalid max_concurrent_slides: {value}") from exc if value < 1: raise ValueError("max_concurrent_slides must be >= 1") return value def dispatch_slots_available(jobs: Dict[str, Any]) -> int: return max(0, max_concurrent_slides(jobs) - len(active_slides(jobs))) def update_jobs_run_status(jobs: Dict[str, Any]) -> None: slides = jobs.get("slides", []) if slides and all(slide.get("status") in {"dispatched", "recorded", "accepted"} for slide in slides): jobs["run_status"] = "slides_dispatched" if slides and all(slide.get("status") in {"recorded", "accepted"} for slide in slides): jobs["run_status"] = "slides_recorded" if slides and all(slide.get("status") in TERMINAL_SLIDE_STATUSES for slide in slides): if any(slide.get("status") == "blocked" for slide in slides): jobs["run_status"] = "blocked" jobs["updated_at"] = now_iso() def slide_ids(slides: Iterable[Dict[str, Any]]) -> List[str]: return [str(slide.get("slide_id")) for slide in slides]skills/codex-ppt/references/党政红风格.md8.5 KB2cb18463cae2upstream ↗
# 党政红风格 **适用场景:** - 党政机关工作汇报、专题学习与会议材料 - 政策宣讲、党建活动、年度总结与重点工作部署 - 国企、事业单位和公共服务机构的正式汇报 **GPT-Image-2 风格 Brief:** ```json { "type": "16:9 full-slide PowerPoint image", "style_name": "党政红风格", "best_for": "党政机关、国企和事业单位的工作汇报、政策宣讲、党建学习、年度总结与重点工作部署", "visual_direction": "solemn, authoritative, and optimistic Chinese public-sector presentation with a recognizable Chinese-red identity, restrained gold accents, strong Chinese typography, and a visual expression shaped by the subject rather than a fixed ceremonial layout", "canvas": { "aspect_ratio": "16:9", "background": "choose red, warm ivory, a restrained gradient, a relevant photograph, or a subtle abstract treatment according to the page role and subject; any landscape, architecture, ribbon, skyline, or cultural motif is optional and must serve the content rather than become a default background", "composition": "formal and balanced with a prominent title hierarchy and disciplined alignment; allow centered, asymmetric, image-led, modular, or spacious compositions when they better express the content", "density": "medium information density with controlled whitespace, clear reading order, and enough supporting text or evidence to make each page useful" }, "color_palette": { "primary": "Chinese red #C41E3A for main titles, structural emphasis, and key labels", "secondary": "deep red #9E1530 for contrast and warm ivory #FFF9F2 for the main canvas", "accent": "restrained matte gold #D6A84B and warm amber #E9A11B for icons, connectors, and small title ornaments", "neutral": "ink black #262626, dark gray #4A4A4A, pale warm gray #F3EEE7", "rule": "use Chinese red to establish authority and gold as a restrained accent. Balance red, warm ivory, and neutral space according to page role; avoid glitter, glossy gradients, and festive red-and-gold decoration" }, "typography": { "title": "large bold Microsoft YaHei or Source Han Sans style Chinese sans-serif, visually strong, dignified, and immediately noticeable", "body": "Microsoft YaHei or Source Han Sans style Chinese sans-serif, concise, highly readable, and aligned to a strict grid", "labels": "bold white or dark-red text on restrained red or pale-gold blocks", "text_quality": "all Chinese text must be exact, fully legible, non-garbled, and suitable for formal government reporting" }, "title_system": { "consistency_rule": "Keep the title hierarchy, typeface, weight, color logic, and spacing consistent across slides of the same page type.", "cover": "Use a prominent, dignified title treatment that may be centered, offset, or integrated with a relevant visual according to the composition.", "section_divider": "Use a concise title and a clear transition in scale, color, whitespace, or imagery without requiring a fixed navigation bar or ornament.", "content_slide": "Keep the page topic immediately recognizable, but align the title with the composition and information structure; centered and left-aligned treatments are both valid.", "flexibility": "Treat the title system as a hierarchy and consistency rule, not a fixed arrangement. Do not require a navigation strip, centered title, gold separator, numbering style, or identical decoration on every slide." }, "layout_patterns": [ "cover or opener with a dominant title and a subject-relevant photographic, illustrative, architectural, landscape, or abstract visual", "section divider with a concise statement and a clear transition created through scale, whitespace, color, or imagery", "content explanation organized around the most important relationship, argument, process, comparison, or evidence", "work deployment or policy interpretation page whose modules, sequence, and emphasis follow the source content", "achievement or data page combining key figures, charts, images, and evidence-based captions as needed", "summary or closing page that reinforces the central message with a strong but restrained visual conclusion" ], "layout_usage_rule": "Keep the red-led identity, typography, and formal tone consistent while varying title placement, background treatment, imagery, information structure, and whitespace by page purpose. Do not force every slide into the same grid, module count, title position, or decorative motif; use lighter backgrounds when they improve readability.", "layout_blueprints": [ { "name": "封面 / 开场", "sections": [ {"position": "primary visual field", "count": 1, "labels": ["prominent title and concise supporting information"]}, {"position": "supporting field", "count": 1, "labels": ["optional subject-relevant photograph, illustration, architecture, landscape, or abstract visual"]} ] }, { "name": "信息阐释 / 工作部署", "sections": [ {"position": "title zone", "count": 1, "labels": ["clear page topic or guiding statement"]}, {"position": "main content field", "count": 1, "labels": ["the dominant argument, relationship, process, comparison, or evidence structure"]}, {"position": "supporting field", "count": 1, "labels": ["supporting text, data, images, or callouts selected according to the source"]} ] }, { "name": "成果 / 总结", "sections": [ {"position": "primary message field", "count": 1, "labels": ["central conclusion, achievement, or call to action"]}, {"position": "evidence field", "count": 1, "labels": ["figures, chart, comparison, documentary image, or concise supporting points as appropriate"]} ] } ], "visual_elements": { "allowed": "content-relevant photography, illustrations, landscapes, architecture, skylines, public-service scenes, people, abstract ribbons or color fields, restrained red-and-gold accents, formal information modules, simple icons, clean charts, and subtle cultural motifs; none of these elements is mandatory", "avoid": "repeating the same landmark or ornament without content justification, invented or inaccurate official marks, excessive ceremonial decoration, thick shadows, glossy 3D text, glitter, festival or wedding motifs, cartoon styling, unrelated stock imagery, and decorative elements that compete with the message" }, "image_treatment": { "photos": "use relevant and credible documentary, landscape, architectural, public-service, or institutional imagery; it may be full-bleed, cropped, framed, or integrated with a restrained red treatment, but avoid heavy filters that obscure the subject", "screenshots": "place inside clean warm-white frames with short source labels and no ornamental clutter", "charts": "use red as the primary series, gold for one key highlight, and neutral gray for comparison; keep labels direct and readable", "illustrations": "choose a flat, graphic, painterly, or restrained symbolic treatment according to the subject; do not impose a fixed landmark, ribbon, skyline, or landscape motif", "official_symbols": "use a party emblem, national emblem, flag, seal, or other official symbol only when the content genuinely requires it and an accurate, authorized source asset is available; never invent, approximate, or redesign official symbols" }, "rendering_constraints": [ "The slide must look like a formal Chinese government or public-sector report, not a festival poster or commercial advertisement.", "Use large, dignified Chinese sans-serif typography resembling Microsoft YaHei or Source Han Sans.", "Follow a consistent title system across slides of the same page type, while allowing cover, section-divider, and content-slide variants.", "Let the page role and source content determine title placement, background, imagery, module count, and composition.", "Do not force a navigation strip, centered title, gold separator, landscape, Great Wall, skyline, ribbon, or other specific motif onto every slide.", "Use Chinese red #C41E3A as the main red and gold as a restrained supporting accent.", "Keep gold restrained and matte; do not use glossy metallic or embossed 3D text.", "Use exact readable Chinese text and a clear top-to-bottom or left-to-right hierarchy.", "Do not invent, approximate, or redesign official marks, government logos, party emblems, national emblems, seals, flags, or institutional names.", "No watermark and no unrelated logo." ] } ```skills/codex-ppt/references/创意杂志风.md3.3 KB359f5d363b37upstream ↗
# 创意杂志风 **适用场景:** - 创意提案 - 品牌展示 - 设计作品集 - 文化活动 - 时尚发布 - 艺术展览 - 创意工作室介绍 **GPT-Image-2 风格 Brief:** ```json { "type": "16:9 full-slide PowerPoint image", "style_name": "创意杂志风", "best_for": "需要强视觉记忆点、品牌个性或传播感的分享型演示", "visual_direction": "high-end editorial magazine spread, bold asymmetry, art-directed composition, graphic tension, premium creative layout", "canvas": { "aspect_ratio": "16:9", "background": "white, black, or deep charcoal with intentional negative space", "composition": "asymmetric editorial layout with a large headline, image/collage zone, and 2-3 supporting text blocks", "density": "strong contrast between dense editorial blocks and open whitespace" }, "color_palette": { "base": "black, white, and gray", "accent": "one vivid accent such as neon pink #FF006E, lemon yellow #FFED00, or electric cyan #00F5FF", "support": "optional lavender, coral, or muted fashion tones", "rule": "use one dominant accent color consistently; do not make the palette chaotic" }, "typography": { "title": "oversized bold display sans-serif or editorial serif, can occupy 25-45% of the slide", "body": "small clean sans-serif blocks with strong alignment", "emphasis": "keywords may use accent color, rotated labels, vertical text, or extreme scale contrast", "text_quality": "Chinese headline and key points must be exact and readable" }, "layout_patterns": [ "oversized headline on one side with collage or abstract image block on the other", "diagonal color block cutting across the slide", "magazine cover style with title, subtitle, and three feature teasers", "editorial grid with one large image crop and small annotation labels" ], "layout_usage_rule": "Use layout_blueprints as candidate starting points only. Choose and adapt the composition according to each slide's semantic role; avoid repeating the same blueprint on adjacent slides unless it is a deliberate repeated sequence.", "layout_blueprints": [ { "name": "editorial hero spread", "sections": [ {"position": "left 45%", "count": 1, "labels": ["oversized headline"]}, {"position": "right 55%", "count": 1, "labels": ["collage or abstract image zone"]}, {"position": "bottom-left", "count": 3, "labels": ["feature teaser 1", "feature teaser 2", "feature teaser 3"]} ] }, { "name": "cover story grid", "sections": [ {"position": "top", "count": 1, "labels": ["large cover title"]}, {"position": "center", "count": 2, "labels": ["main visual block", "accent typography block"]}, {"position": "right edge", "count": 3, "labels": ["short editorial callouts"]} ] } ], "visual_elements": { "allowed": "bold geometric blocks, cropped photography zones, halftone texture, thin rules, torn-paper collage edges, accent stickers, abstract shapes", "avoid": "generic corporate icons, overly symmetrical layout, low-contrast text, too many accent colors" }, "rendering_constraints": [ "The slide should feel designed, not templated.", "Maintain legibility despite bold composition.", "No watermark, no unrelated logo, no slide number unless explicitly requested." ] } ```skills/codex-ppt/references/复古扁平插画风.md3.3 KB4c917c0b759aupstream ↗
# 复古扁平插画风 **适用场景:** - 文化创意项目展示 - 品牌故事讲述 - 旅游景点介绍 - 复古产品发布 - 艺术设计作品集 - 创意活动宣传 - 生活方式类演示 **GPT-Image-2 风格 Brief:** ```json { "type": "16:9 full-slide PowerPoint image", "style_name": "复古扁平插画风", "best_for": "文化创意、品牌故事、生活方式、城市旅游和带叙事感的主题演示", "visual_direction": "retro flat vector illustration slide, cream paper texture, monoline black outlines, vintage palette, playful handcrafted design", "canvas": { "aspect_ratio": "16:9", "background": "cream/off-white paper #F5F3E8 with subtle grain", "composition": "panoramic illustration band plus structured content cards or labels", "density": "moderate, decorative but still clear" }, "color_palette": { "base": "cream background and dark slate text #34495E", "vintage_colors": "coral red #FF6B6B, mint green #95E1D3, mustard yellow #F9CA24, burnt orange #E17055, slate blue #6C7A89", "line": "uniform black or deep charcoal outline", "rule": "flat fills only, no glossy 3D, no heavy gradients" }, "typography": { "title": "bold retro serif or chunky vintage display type", "body": "geometric sans-serif, clear and friendly", "labels": "small badge labels with outlined shapes", "text_quality": "Chinese text must be exact and readable" }, "layout_patterns": [ "top panoramic flat illustration with bottom content cards", "central retro title with three outlined icon cards", "2.5D simplified scene with callout labels", "vintage poster composition adapted to presentation readability" ], "layout_usage_rule": "Use layout_blueprints as candidate starting points only. Choose and adapt the composition according to each slide's semantic role; avoid repeating the same blueprint on adjacent slides unless it is a deliberate repeated sequence.", "layout_blueprints": [ { "name": "panoramic illustration plus cards", "sections": [ {"position": "top third", "count": 1, "labels": ["panoramic flat vector illustration"]}, {"position": "middle", "count": 1, "labels": ["large retro title"]}, {"position": "bottom", "count": 3, "labels": ["outlined content card 1", "outlined content card 2", "outlined content card 3"]} ] }, { "name": "retro poster diagram", "sections": [ {"position": "center", "count": 1, "labels": ["main simplified scene or object"]}, {"position": "around center", "count": 4, "labels": ["callout label", "badge", "mini icon", "decorative note"]}, {"position": "bottom-right", "count": 1, "labels": ["summary plaque"]} ] } ], "visual_elements": { "allowed": "flat vector scenes, 2-3px monoline outlines, simplified buildings, plants, clouds, badges, dotted textures, small geometric decorations", "avoid": "photorealism, complex shadows, neon palette, overly detailed linework, unreadable decorative type" }, "rendering_constraints": [ "The slide should feel like a polished retro illustration system, not a random cartoon.", "Maintain consistent outline weight across objects.", "No watermark, no unrelated logo, no slide number unless explicitly requested." ] } ```skills/codex-ppt/references/手绘技术解释风.md4.7 KB6de85645910dupstream ↗
# 手绘技术解释风 **适用场景:** - 中文技术文章配图 - 技术概念解释 - 课程课件 - 知识卡片 - 产品机制说明 - AI / 软件工程主题分享 - 需要降低理解门槛的复杂概念 **GPT-Image-2 风格 Brief:** ```json { "type": "16:9 full-slide PowerPoint image", "style_name": "手绘技术解释风", "best_for": "中文技术文章、课程课件、复杂概念解释、知识卡片和软件工程/AI 主题的低压力说明图", "visual_direction": "clean Chinese handdrawn technical explainer, near-white paper background, thin sketch lines, light pencil hatching, small precise central diagram, restrained pastel markers, lots of whitespace, calm educational tone", "canvas": { "aspect_ratio": "16:9", "background": "near-white paper #FCFBF7, not yellow, no full-page border", "composition": "small central explanatory diagram with sparse labels, surrounding whitespace, short title and minimal visible text", "density": "low to moderate; one core idea per slide; avoid dense whiteboard clutter" }, "color_palette": { "line": "soft graphite #2F3437 or dark gray ink, thin and slightly irregular", "accent": "pale blue #BFD7F1, sage green #CFE2D1, light peach #F4C7B8, pale lavender #D8C7EF", "background": "near-white, clean, not kraft, not cream-heavy", "rule": "pastel marks are used for emphasis only; keep the page calm and airy" }, "typography": { "title": "restrained handwritten Chinese title, medium-large but not poster-sized", "body": "short handwritten Chinese labels, few words per label, easy to inspect", "emphasis": "light underline, small bracket, soft marker highlight, or tiny note tag", "text_quality": "Chinese text must be exact, sparse, and readable; avoid long paragraphs" }, "layout_patterns": [ "central concept diagram with 3-4 short surrounding labels", "before-after explanation with two small sketch panels", "flow diagram with 3 steps and minimal arrows", "mental model page with one metaphor object and short annotations", "matrix or decision guide with sparse handwritten notes", "summary page with one small character or object and three takeaway labels" ], "layout_usage_rule": "Use layout_blueprints as candidate starting points only. Choose and adapt the composition according to each slide's semantic role; keep visual DNA stable while varying archetypes such as metaphor, process, comparison, matrix, and summary. Avoid repeating the same blueprint on adjacent slides unless it is a deliberate repeated sequence.", "layout_blueprints": [ { "name": "small central concept map", "sections": [ {"position": "top-left", "count": 1, "labels": ["short handwritten title"]}, {"position": "center", "count": 1, "labels": ["small precise concept diagram"]}, {"position": "around center", "count": 4, "labels": ["label 1", "label 2", "label 3", "label 4"]}, {"position": "bottom-right", "count": 1, "labels": ["one-sentence takeaway"]} ] }, { "name": "technical before-after", "sections": [ {"position": "top", "count": 1, "labels": ["short page title"]}, {"position": "left", "count": 1, "labels": ["before sketch panel"]}, {"position": "right", "count": 1, "labels": ["after sketch panel"]}, {"position": "between panels", "count": 1, "labels": ["thin handdrawn arrow"]}, {"position": "bottom", "count": 3, "labels": ["why it matters", "tradeoff", "next step"]} ] }, { "name": "one idea teaching card", "sections": [ {"position": "center-left", "count": 1, "labels": ["metaphor object or tiny engineer/reader character"]}, {"position": "center-right", "count": 3, "labels": ["core idea", "common mistake", "useful rule"]}, {"position": "background", "count": 1, "labels": ["very light pencil hatching and pastel highlight"]} ] } ], "visual_elements": { "allowed": "thin handdrawn arrows, small diagrams, pencil hatching, pastel marker blocks, bracket notes, simple software/AI icons, tiny engineer or reader character at most once", "avoid": "messy whiteboard frame, marker tray, large cartoon characters, dense handwriting, yellowed paper, decorative stickers, poster-scale title, full-page border, digital UI cards" }, "rendering_constraints": [ "The slide should feel like a calm handdrawn technical article illustration, not a brainstorming whiteboard.", "Keep the central drawing small and precise with generous empty space.", "Use minimal Chinese text and make every visible word correct.", "No watermark, no unrelated logo, no slide number unless explicitly requested." ] } ```skills/codex-ppt/references/手绘白板风.md3.3 KB8676c824cb77upstream ↗
# 手绘白板风 **适用场景:** - 教学讲解 - 培训课程 - 头脑风暴 - 概念说明 - 技术分享 - 内部研讨 **GPT-Image-2 风格 Brief:** ```json { "type": "16:9 full-slide PowerPoint image", "style_name": "手绘白板风", "best_for": "概念解释、技术分享、培训课程和需要亲和力的思路拆解", "visual_direction": "realistic whiteboard explanation slide, marker handwriting, sketched diagrams, friendly teaching atmosphere, authentic whiteboard details", "canvas": { "aspect_ratio": "16:9", "background": "warm off-white whiteboard surface #FAFAF5 with subtle marker smudges", "composition": "freeform but organized whiteboard layout with title, three concept blocks, arrows, and small doodle illustrations", "density": "moderate, readable, brainstorming feel without chaos" }, "color_palette": { "primary": "black marker for main text", "accent": "red #E74C3C, blue #3498DB, orange #F39C12 marker annotations", "support": "green #27AE60, purple #9B59B6, yellow sticky note #FFF9C4", "rule": "colors should look like real marker ink, not digital neon" }, "typography": { "title": "large neat handwritten Chinese marker style", "body": "clear handwritten marker text, slightly irregular but readable", "emphasis": "circle, underline, boxed words, sticky-note comments", "text_quality": "Chinese handwriting must remain accurate and legible" }, "layout_patterns": [ "three hand-drawn boxes connected by arrows", "central concept bubble with surrounding notes", "simple process diagram with sketches and annotations", "left explanation list plus right hand-drawn diagram" ], "layout_usage_rule": "Use layout_blueprints as candidate starting points only. Choose and adapt the composition according to each slide's semantic role; avoid repeating the same blueprint on adjacent slides unless it is a deliberate repeated sequence.", "layout_blueprints": [ { "name": "whiteboard process diagram", "sections": [ {"position": "top-left", "count": 1, "labels": ["handwritten title"]}, {"position": "center", "count": 3, "labels": ["step 1 box", "step 2 box", "step 3 box"]}, {"position": "between boxes", "count": 2, "labels": ["hand-drawn arrow", "hand-drawn arrow"]}, {"position": "right edge", "count": 1, "labels": ["sticky-note takeaway"]} ] }, { "name": "concept map", "sections": [ {"position": "center", "count": 1, "labels": ["main concept bubble"]}, {"position": "around center", "count": 4, "labels": ["supporting idea", "risk note", "example sketch", "action item"]}, {"position": "bottom", "count": 1, "labels": ["underlined summary"]} ] } ], "visual_elements": { "allowed": "whiteboard frame, marker tray, colored markers, arrows, boxes, clouds, sticky notes, doodle icons, underlines, circled keywords", "avoid": "messy illegible handwriting, childish clutter, photoreal people, digital UI cards" }, "rendering_constraints": [ "The slide should look like a real whiteboard captured cleanly for a presentation.", "Keep all Chinese text readable despite handwritten style.", "No watermark, no unrelated logo, no slide number unless explicitly requested." ] } ```skills/codex-ppt/references/教学课件风.md9.7 KB1d3496edd98cupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/references/数据仪表盘风.md3.4 KB78441a2c7179upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/references/清爽专业风.md4.4 KB9dcd764c39e1upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/references/温暖手工风.md3.3 KB80b3292456b8upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/references/电子墨水杂志风.md4.6 KB62ba3f02b102upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/references/科研答辩风.md9.1 KBa17c5e4542d6upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/references/麦肯锡风格.md15 KBdecb48064f37upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/.clawhubignore162 B2ce1a57fb224upstream ↗
.DS_Store .venv/ __pycache__/ *.pyc *.pyo *.pyd .pytest_cache/ .mypy_cache/ .env output/ temp/ test_output/ examples/ *.png *.jpg *.jpeg *.gif *.bmp *.pptx *.pdfskills/codex-ppt/docs/backend-selection.md3.5 KB955bf463dbbdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/docs/cli-api-fallback.md5.0 KB3c68cbac31cfupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/docs/image-model-configuration.md3.5 KB4db90da059f3upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/docs/outline-style-and-sample.md9.3 KBfda7518843d5upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/docs/project-assembly-and-reporting.md8.3 KB83d8213af233upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/docs/slide-generation-and-subagents.md14 KB684b7c7c1c1eupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/docs/style-library.md6.4 KBcca07d251890upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/docs/user-supplied-assets.md3.0 KB6ce0f1ab8e25upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/docs/workflow-gates-and-progress.md2.5 KB83d9530a807eupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/prompts/slide-worker.md2.6 KB5da582801df2upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/codex-ppt/requirements.txt65 Be55acc710a7dupstream ↗
python-pptx>=1.0.2 Pillow>=10.0.0 openai>=2.0.0 filelock>=3.16.0README.mdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
Plain-text copy, no login: /skill-bundles/ningzimu-codex-ppt-skill-skills-codex-ppt.md











