agent-skills
A collection of AI agent skills and plugins for Hermes Agent — research, creative, productivity, devops, and more. Each skill is self-contained and tested.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/moonlight-lupin/agent-skills with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/moonlight-lupin/agent-skills'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/moonlight-lupin--agent-skills)HTML
<a href="/listings/moonlight-lupin--agent-skills"><img src="/api/listings/moonlight-lupin--agent-skills/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
One-command: install the whole catalog (`npx`)
npx skills add moonlight-lupin/agent-skills
Installs every skill into `.agents/skills/` (works for Cursor, Codex, Gemini CLI, Copilot, OpenCode, and more; Claude Code gets a symlinked copy) plus `.claude/skills/`, with a hash-pinned `skills-lock.json` so `npx skills update` can refresh later. Install one skill with `--skill <name>` — or omit it for an interactive pick-list.
Pick a skill from GitHub (`gh`)
# Install one skill by exact path (fastest, no tree scan) gh skill install moonlight-lupin/agent-skills creative/image-studio/SKILL.md # ...or by name into a specific agent's directory gh skill install moonlight-lupin/agent-skills creative/image-studio/SKILL.md --agent claude-code --scope user
Manual
git clone https://github.com/moonlight-lupin/agent-skills.git cd agent-skills
Each skill folder has a `SKILL.md` with setup and usage instructions — copy the ones you want into your agent's skills directory (e.g. `~/.claude/skills/`, `~/.cursor/skills/`, `~/.agents/skills/`).
> **Never commit credentials.** API keys, config files with secrets, and generated artifacts are all gitignored.
> **Spec compliance:** all skills validate against the [Agent Skills spec](https://agentskills.io/specification) (`npx skills-ref validate`). Author, version, and platform metadata live under `metadata:`.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
README.md · README · 191 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # Agent Skills
- [](https://github.com/moonlight-lupin/agent-skills/actions/workflows/test.yml)
- [](https://opensource.org/licenses/MIT)
- [](https://www.python.org/downloads/)
- A collection of AI agent skills built for [Hermes Agent](https://hermes-agent.nousresearch.com), organised by domain. Each skill is self-contained in its own folder — pick and choose which to install.
- > **Portability:** These skills are written for Hermes's tool architecture (`web_search`, `web_extract`, `terminal`, `delegate_task`, `cronjob`, etc.) and SKILL.md format. However, the workflows, prompts, and scripts are agent-agnostic — an AI agent on any platform (Claude Code, Codex, OpenCode, LangGraph, etc.) should be able to adapt them by mapping the tool names and adjusting the skill loader conventions to their own environment.
- ## Repository structure
- ```text
- agent_skills/
- ├── README.md ← you are here (repo-level)
- ├── LICENSE
- ├── creative/ ← image and video generation workflows
- │ ├── image-studio/ ← staged fal.ai image generation/editing/cleanup
- │ ├── clips-studio/ ← staged fal.ai short-video generation/animation/camera moves
- │ └── pexels-stock-photos/ ← free real-world stock photo search + download (Pexels API)
- ├── research/ ← source-grounded research, enrichment, and RAG skills
- │ ├── deep-research/ ← iterative research engine with structured evidence, source quality ranking, refute polarity, four-label evidence-basis discipline, deterministic validation gates, verbatim quote anchoring, per-round search budgets
- │ ├── entity-research/ ← cited entity/person background dossiers + sanctions signals
- │ ├── news-monitoring/ ← recurring news digests with cron delivery + multi-language
- │ ├── notebooklm-mode/ ← NotebookLM-style source vault + grounded answers
- │ ├── people-enrichment/ ← PDL person/company enrichment/search to styled .xlsx
- │ ├── library-rag/ ← Nemotron-3-Embed-1B + sqlite-vec semantic search engine
- │ └── endpoint-probe/ ← API/MCP surface discovery (REST, GraphQL, SOAP, JSON-RPC)
- ├── mlops/ ← model evaluation and ops skills
- │ ├── model-compare/ ← blind multi-model A/B comparison + embedding benchmark
- │ └── paired-agent-eval/ ← paired A/B pilot harness: matched task pairs, blinded defect scoring, behavioral text-variant batteries
- ├── web-scraping/ ← web data-extraction skills
- │ └── website-scraping/ ← recon → lightest-tool extraction → JSONL output
- ├── productivity/ ← personal / business-ops skills
- │ ├── fill-template/ ← bulk-fill Word/Excel templates from a data table (mail-merge)
- │ ├── travel-itinerary/ ← business-trip itineraries: parse → structure → export
- │ ├── decision-log/ ← ADR-style decision journal + superseding chains + cron reviews
- │ ├── scheduled-summary/ ← cron-driven cross-session digest for messaging platforms
- │ ├── file-organizer/ ← LLM-powered directory organizer: scan → propose → confirm → move
- │ ├── receipt-compiler/ ← phone-camera receipt photos → straightened B&W A4 expense-claim PDF
- │ ├── task-brief/ ← goal/done-when/constraints brief before substantial tasks; reusable prompts
- │ ├── marp-deck/ ← Marp Markdown decks → PPTX/PDF/HTML render
- │ └── pdf2epub/ ← text-layer PDF book → structured EPUB (cover, TOC nav, illustrations, endnotes; classifier calibration rules absorbed)
- ├── agent-ops/ ← agent infrastructure and maintenance skills
- │ ├── claude-plugin-converter/ ← convert Claude Code plugins → self-contained Hermes plugins
- │ ├── log-analyzer/ ← log pattern detection: error clusters, rate limits, timeouts
- │ ├── input-token-overheads/ ← audit input token cost, two scopes: per-turn prompt overhead + aggregate spend (cost accounting)
- │ ├── operator-brain/ ← 10-module behavioral stack (Fable 5 + 5.1): act, lead with outcome, ground claims, narrate long work
- │ └── hermes-onboarding/ ← 21-step customer onboarding: gateway, dashboard, memory, crons
- ├── software-development/ ← skill development, review, and methodology skills
- │ └── skill-quality-review/ ← batch skill audit: 9 checks, writing-for-agents levers, efficacy testing
- ├── devops/ ← infrastructure and system maintenance skills
- │ └── disk-triage/ ← triage survey → safe/ask buckets → execute → verify delta (renamed from disk-cleanup — bundled Hermes plugin now owns that name)
- └── plugins/ ← installable Hermes Agent plugins
- ├── skill-retrieval/ ← BM25 retrieval that injects the top-K relevant skills per turn
- ├── dev-pipeline/ ← five-stage development pipeline (grill/spec/test-evals/build/review-commit) with a pre_tool_call create-gate hook
- ├── skill-governance/ ← skill provenance + drift acks + advisory contrastive probes behind one composed hook surface (successor to the retired skill-manifest + contrastive-advisor plugins)
- └── lumen/ ← LLM wiki plugin: methodology + memory-fed curator
- ```
- New skills are added as folders under the relevant domain directory.
- ## Skills
- | Skill | Domain | What it does | Dependencies |
- |-------|--------|-------------|-------------|
- | [image-studio](creative/image-studio/) | creative | Staged fal.ai image gen/edit/upscale/cleanup with cost logging + `--dry-run` | pexels-stock-photos |
- | [clips-studio](creative/clips-studio/) | creative | Staged fal.ai short-video: text-to-video, animate still, camera moves | image-studio |
- | [pexels-stock-photos](creative/pexels-stock-photos/) | creative | Free real-world stock photos (Pexels API, 20k/month) with attribution handling | image-studio |
- | [deep-research](research/deep-research/) | research | Iterative research engine: structured evidence, source quality ranking (primary/secondary/tertiary), refute polarity, overview-first reports, four-label evidence-basis discipline ([VERIFIED]/[SOURCED]/[REASONED]/[ESTIMATED]), deterministic validation gates (claim-support, citations, structure), verbatim quote anchoring, per-round search budgets, provider-neutral search and page-reader fallbacks, referent disambiguation probe, firmware support-status triangulation recipe, provider head-to-head benchmarking, source families / shelf lives / money-figure bases, items × fields comparison mode and research recipes, checkable done-when tests, follow-up report revision, persistent citation DB scripts (absorbed source-tracker) | — |
- | [entity-research](research/entity-research/) | research | Cited company/person dossiers: ownership, adverse media, sanctions, litigation; optional cited organisation-evidence run (Exa Agent API) | deep-research |
- | [people-enrichment](research/people-enrichment/) | research | PDL person/company lookup → styled `.xlsx`; email-list enrichment (free triage, one lookup per domain); shared mailboxes never kept as a person's email | entity-research |
- | [library-rag](research/library-rag/) | research | Semantic search over personal library (Nemotron-3-Embed-1B + sqlite-vec), incremental + prune-missing | notebooklm-mode |
- | [notebooklm-mode](research/notebooklm-mode/) | research | Source-grounded Q&A from a source vault, strict or augmented grounding | library-rag, deep-research |
- | [news-monitoring](research/news-monitoring/) | research | Recurring news digests with cron delivery + multi-language + dedup | — |
- | [endpoint-probe](research/endpoint-probe/) | research | Discover API/MCP surfaces (REST, GraphQL, SOAP, JSON-RPC) — probe script + interpretation guide | website-scraping |
- | [model-compare](mlops/model-compare/) | mlops | Blind multi-model A/B comparison: simple, tools, coding, review modes + embedding benchmark; dated battery findings library | paired-agent-eval |
- | [paired-agent-eval](mlops/paired-agent-eval/) | mlops | Does tiered pipeline processing justify its cost: matched single-agent vs pipeline pairs, acceptance suites, blinded severity-weighted defect scoring; behavioral skill-text variant A/B batteries (operating methodology for the operator-brain text-variant evals) | model-compare |
- | [website-scraping](web-scraping/website-scraping/) | web-scraping | Recon → lightest extraction tool → JSONL + run manifest | — |
- | [fill-template](productivity/fill-template/) | productivity | Bulk-fill Word/Excel templates from a data table (mail-merge) | — |
- | [travel-itinerary](productivity/travel-itinerary/) | productivity | Business-trip itineraries from emails/PDFs → Markdown + `.ics` + chat variants | — |
- | [decision-log](productivity/decision-log/) | productivity | ADR-style decision journal with superseding chains + cron review reminders | — |
- | [scheduled-summary](productivity/scheduled-summary/) | productivity | Cron-driven cross-session digest — surfaces activity invisible on chat platforms | decision-log, news-monitoring |
- | [file-organizer](productivity/file-organizer/) | productivity | LLM-powered directory organizer: scan → propose structure → confirm → chunked moves | — |
- | [receipt-compiler](productivity/receipt-compiler/) | productivity | Phone-camera receipt photos → straightened B&W scans → A4 expense-claim PDF with confirmation gate | pdf |
- | [task-brief](productivity/task-brief/) | productivity | Goal/done-when/context/constraints/tooling brief compiled and confirmed before substantial work starts; reusable-prompt mode for recurring work | — |
- | [pdf2epub](productivity/pdf2epub/) | productivity | Text-layer PDF book → structured EPUB: cover, printed-TOC nav, inline illustrations, linked endnotes; classifier calibration rules absorbed into `references/calibration.md` | document-toolkit, opendataloader-pdf |
- | [marp-deck](productivity/marp-deck/) | productivity | Marp presentations: Markdown source of truth → PDF/PPTX/HTML, with themes, SVG components, PPTX import, and render tests | — |
- | [claude-plugin-converter](agent-ops/claude-plugin-converter/) | agent-ops | Two-phase converter: analyze Claude Code plugins → generate installable Hermes plugins | — |
- | [skill-quality-review](software-development/skill-quality-review/) | software-development | Batch skill audit: 9 automated checks, writing-for-agents levers, per-skill grep methodology, efficacy A/B testing, frontmatter/description fixes | — |
- | [log-analyzer](agent-ops/log-analyzer/) | agent-ops | Log pattern detection: error clusters, rate limits, timeout clusters, tool failures | scheduled-summary |
- | [input-token-overheads](agent-ops/input-token-overheads/) | agent-ops | Audit input token cost at two scopes: per-turn prompt overhead (tool schemas, skills index, system text, profile, memory — measured live, ranked, reduced) and aggregate spend/cost accounting across sessions, cron fires, and tool traffic (cache-aware interpretation, pre-checked config levers, scheduled delta checks) | — |
- | [operator-brain](agent-ops/operator-brain/) | agent-ops | 10-module behavioral stack from Anthropic's Fable 5 and Fable 5.1 guides: act, lead with outcome, ground every claim, narrate long work, stay surgical | — |
- | [hermes-onboarding](agent-ops/hermes-onboarding/) | agent-ops | 21-step customer onboarding: gateway, dashboard, memory, search, guardrails, maintenance crons | disk-triage, log-analyzer |
- | [disk-triage](devops/disk-triage/) | devops | Triage disk space: survey all mounts → safe/ask buckets → execute approved set → verify delta (renamed from disk-cleanup; the bundled Hermes `disk-cleanup` plugin owns that name) | — |
- | [dev-pipeline](plugins/dev-pipeline/) | plugins | Five-stage development pipeline: grill → spec → test-evals → build → review-commit, planned by S0-S3 complexity and reviewed by R0-R3 risk (T0-T3 review-tier aliases), with a review-lessons library and a pre_tool_call create-gate that blocks new software-development skills unless a single-use allow flag is consumed | skill-quality-review |
- | [skill-governance](plugins/skill-governance/) | plugins | Consolidated skill provenance and governance: manifest fingerprints + drift acks and advisory-only contrastive probes behind one composed hook surface, conservative `governance.records` join, non-destructive legacy state import, and one clearance Automation Blueprint (`/blueprint`-adopted, no self-installed cron; sole successor to the retired skill-manifest + contrastive-advisor plugins) | — |
- > **Related work:** [Odysseus](https://github.com/pewdiepie-archdaemon/odysseus) (PewDiePie's self-hosted AI workspace) ships similar features as a standalone web app — "Deep Research" and "Compare" — while `deep-research` and `model-compare` cover the same ground as pure-prompt workflows + stdlib scripts inside any agent's tool loop.
- ## Plugins
- Beyond skills, the repo ships installable [Hermes Agent](https://hermes-agent.nousresearch.com) plugins under `plugins/`.
- ### skill-retrieval
- A Hermes plugin that scales skill usage to large libraries. As a skill catalog grows past a few dozen entries, the per-turn `<available_skills>` block costs input tokens and buries the right skill in noise. This plugin replaces the full block with BM25 retrieval: each user turn is scored against a stdlib inverted index built from skill names and descriptions, and only the top-K most relevant skills are injected into the prompt (default K=6, configurable via `plugin.yaml`).
- - **Stdlib only** — no numpy/scipy; the index builds in milliseconds and retrieval is sub-millisecond for 128+ skills.
- - **Profile-aware discovery** — paths resolve through Hermes' own helpers (`get_hermes_home`, `get_skills_dir`), so named profiles, `skills.external_dirs`, trusted project-local skills, disabled lists, and platform/condition gates all match what the agent itself sees. The index cache is keyed per Hermes home, so multiplexed profiles never share an index.
- - **Windows-safe** — skill ids normalize to forward slashes; `$HERMES_HOME`-aware path resolution.
- - **Optional Jev rerank** — reranks the BM25 top-K with the Jev system-one judgment model (`api.typesafe.ai`) when `SKILL_RETRIEVAL_RERANK` is enabled and `TYPESAFE_API_KEY` is present (the legacy `TYPESAFE_KEY` name is accepted, from `os.environ`). Fail-soft: on timeout or error it logs and falls back to pure BM25. An A/B log (`rerank_ab_report.py`) records per-query decisions for trial review; it rotates past 5 MB; runs on a cron, no runtime dependency.
- - **Graceful degradation** — if Hermes core modules are unavailable, it falls back to a standalone loader; malformed configs never abort the index build. A/B logging and rerank never abort retrieval.
- Or install from the Hermes plugin catalog (pinned, version-tracked):
- ```bash
- hermes plugins install skill-retrieval
- ```
- Install by copying or symlinking `plugins/skill-retrieval/` into `~/.hermes/plugins/` (or your profile's `plugins/`), then restart the gateway. Tests: `python3 -m pytest plugins/skill-retrieval/tests/`.
- ### lumen
- A Hermes plugin that turns an agent's conversation history and memory into a maintained markdown wiki (Karpathy-style LLM wiki). Two skills: `lumen:wiki` (the methodology: OKF frontmatter, three-layer page layout, ingest/query/lint workflows) and `lumen:curator` (the `wiki_curator.py` script plus a read-only memory-source adapter layer — the Hermes conversation history via read-only SQLite, Mnemosyne via the `hermes` CLI export, plain JSON files, or none).
- - **Sessions-first by default** — the default memory source is the agent's own conversation history (read-only SQLite over `state.db`); `auto` prefers sessions, then Mnemosyne, then JSON files. The conversation record is treated as ground truth; memory stores hold derived notes.
- - **Cap-bounded curation** — batch ingest, update, and validate runs are capped per run, with per-page backups and atomic replace.
- - **Source attribution contract** — every generated line is `[source: id]` attributed; operator-authored text outside generated sections is preserved on update (verified through 7 review rounds with independent confirm reviewers).
- - **Stdlib + PyYAML only** — no network calls except the `hermes` CLI for memory export; adapters read exports, never provider internals.
- Install by copying or symlinking `plugins/lumen/` into `~/.hermes/plugins/` (or your profile's `plugins/`), enable it with `hermes plugins enable lumen` (user plugins are opt-in), then restart the gateway. Tests: `python3 -m pytest plugins/lumen/tests/`.
- ### dev-pipeline
- A Hermes plugin that guards skill creation and carries the development pipeline as five bundled stage skills (`dev-pipeline:orchestrator` → `dev-pipeline:grill` → `dev-pipeline:spec` → `dev-pipeline:test-evals` → `dev-pipeline:build` → `dev-pipeline:review-commit`), plus a `review-lessons` library split out of the review stage. A `pre_tool_call` gate blocks bare-name creation of new software-development skills unless a single-use `.allow-create` flag is consumed — the loop concepts that used to live in a standalone build-review-loop skill now ship as these bundled skills.
- Install by copying or symlinking `plugins/dev-pipeline/` into `~/.hermes/plugins/` (or your profile's `plugins/`), then restart the gateway. Tests: `python3 -m pytest plugins/dev-pipeline/tests/`.
- ### skill-governance
- A Hermes plugin that consolidates the provenance engine and the advisory edit-observation engine behind one composed hook surface (`on_skill_lifecycle`, `on_session_start`, `pre_tool_call`, `pre_llm_call`). It bundles the `contrastive-refinement` skill (`plugins/skill-governance/skills/contrastive-refinement/`, registered as `skill-governance:contrastive-refinement`): behavioral skill edits get one advisory reminder to run the probe cycle (fire ledger at `~/.hermes/skill-probes/fire-ledger.jsonl`). The manifest engine enforces `UPSTREAM_MANIFEST.md`: arrivals must have a manifest row, content changes in manifested skills must be re-acknowledged against a content fingerprint (`/skill-manifest-ack <name> <sha>`). `manifest.v1`/`advisor.v1` import legacy state by copy (destination-wins, sources never modified). v0.3.0 ships the clearance procedure as an adopted Automation Blueprint (`skill-governance:clearance`, daily `0 9 * * *`, delivery `origin`) registered through the public host surface — the plugin imports no private cron modules and writes no cron state; it replaces both legacy schedulers and preserves both clearance procedures verbatim. `governance.records` joins the two views conservatively — an acknowledged fingerprint never implies validated evidence.
- Install from the Hermes plugin catalog:
- ```bash
- hermes plugins install skill-governance
- ```
- Or copy/symlink `plugins/skill-governance/` into `~/.hermes/plugins/` (or your profile's `plugins/`), then restart the gateway. Migrate from the retired `skill-manifest`/`contrastive-advisor` plugins per the checklist in `plugins/skill-governance/README.md`. Tests: `python3 -m pytest plugins/skill-governance/tests/`.
- ## Conventions
- > Conventions: the *Dependencies* column on the Skills table lists pip/runtime requirements beyond Python stdlib; skills marked *evals* ship routing/output-contract fixtures under `evals/` (sample request → expected routing, required output fields, forbidden patterns), validated by `tests/test_routing_fixtures.py` — no live-model execution in CI. Plugins are tested separately (`plugins/<name>/tests/`) and tracked under Plugins above.
- ## Install
- ### One-command: install the whole catalog (`npx`)
- ```bash
- npx skills add moonlight-lupin/agent-skills
- ```
- Installs every skill into `.agents/skills/` (works for Cursor, Codex, Gemini CLI, Copilot, OpenCode, and more; Claude Code gets a symlinked copy) plus `.claude/skills/`, with a hash-pinned `skills-lock.json` so `npx skills update` can refresh later. Install one skill with `--skill <name>` — or omit it for an interactive pick-list.
- ### Pick a skill from GitHub (`gh`)
- ```bash
- # Install one skill by exact path (fastest, no tree scan)
- gh skill install moonlight-lupin/agent-skills creative/image-studio/SKILL.md
- # ...or by name into a specific agent's directory
- gh skill install moonlight-lupin/agent-skills creative/image-studio/SKILL.md --agent claude-code --scope user
- ```
- ### Manual
- ```bash
- git clone https://github.com/moonlight-lupin/agent-skills.git
- cd agent-skills
- ```
- Each skill folder has a `SKILL.md` with setup and usage instructions — copy the ones you want into your agent's skills directory (e.g. `~/.claude/skills/`, `~/.cursor/skills/`, `~/.agents/skills/`).
- > **Never commit credentials.** API keys, config files with secrets, and generated artifacts are all gitignored.
- > **Spec compliance:** all skills validate against the [Agent Skills spec](https://agentskills.io/specification) (`npx skills-ref validate`). Author, version, and platform metadata live under `metadata:`.
- ## License
- [MIT](LICENSE) — all skills in this repository are original works by moonlight-lupin and are covered by the MIT License.
productivity/marp-deck/scripts/md2pptx-officecli.py · Bundled script · 316 lines · 1 finding marked
- #!/usr/bin/env python3
- """md2pptx-officecli.py — build an editable PPTX from a Marp Markdown deck.
- Fallback path for machines without a full LibreOffice install (LibreOffice 24.2+
- removed the Impress HTML import filter, which breaks `marp --pptx-editable`).
- Parses the deck's Markdown structurally — headings, bullets, numbered lists,
- tables, blockquotes — and emits native PowerPoint text boxes, tables and shapes
- via the `officecli` CLI. Styling: reads the deck's own theme colours when the
- frontmatter defines `--dark`, `--light` and `--accent` CSS variables in a
- `:root` block; otherwise uses PowerPoint defaults.
- This is a fidelity-lost conversion by design: complex HTML components, SVG
- charts and background images are skipped (a placeholder line names them). The
- pixel-faithful render stays with `marp deck.md --pdf`. Keep both.
- Usage:
- python3 md2pptx-officecli.py deck.md output.pptx
- Requires:
- officecli on PATH — https://github.com/iOfficeAI/OfficeCLI
- curl -fsSL https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 20 on GitHub
- """
- import json
- import re
- import subprocess
- import sys
- CANVAS_W, CANVAS_H = 33.87, 19.05 # cm — officecli default 960x540pt
- MX = 1.4
- CW = CANVAS_W - 2 * MX
- # Fallback palette (near-neutral, readable on white)
- C_BG, C_INK, C_SOFT, C_FAINT = "FFFFFF", "1A1A1A", "444444", "8A8A8A"
- C_ACCENT, C_LINE, C_ONACC = "1F4E79", "D9D9D9", "FFFFFF"
- ops = []
- slide_n = 0
- def add(parent, type_, **props):
- parent = parent.replace("/slide[1]", f"/slide[{slide_n}]")
- ops.append({"command": "add", "parent": parent, "type": type_,
- "props": {k: str(v) for k, v in props.items()}})
- def st(path, **props):
- path = path.replace("/slide[1]", f"/slide[{slide_n}]")
- ops.append({"command": "set", "path": path,
- "props": {k: str(v) for k, v in props.items()}})
- def strip_md(text):
- text = re.sub(r"<[^>]+>", "", text) # inline HTML/strong tags
- text = re.sub(r"\*\*(.+?)\*\*", r"\1", text) # bold
- text = re.sub(r"\*(.+?)\*", r"\1", text) # italic
- text = re.sub(r"`(.+?)`", r"\1", text) # code
- text = re.sub(r"!\[.*?\]\(.*?\)", "[image]", text)
- text = re.sub(r"\[(.+?)\]\(.*?\)", r"\1", text) # links
- return text.strip()
- def parse_theme(md_text):
- """Pull --dark/--light/--accent from a :root block in the frontmatter style."""
- global C_BG, C_INK, C_SOFT, C_FAINT, C_ACCENT, C_LINE, C_ONACC
- root = re.search(r":root\s*\{(.*?)\}", md_text, re.S)
- if not root:
- return
- block = root.group(1)
- def var(name, default):
- m = re.search(rf"--{name}\s*:\s*#([0-9a-fA-F]{{6}})", block)
- return m.group(1).upper() if m else default
- dark = var("dark", "") # dark = background colour in Marp themes
- light = var("light", "")
- accent = var("accent", "")
- if light and dark:
- # Convention: --light is body/foreground, --dark is background
- C_BG = dark
- C_INK = light
- C_ONACC = dark if _luma(dark) > 0.5 else "FFFFFF"
- C_ONACC = "FFFFFF" if _luma(dark) < 0.5 else dark
- if accent:
- C_ACCENT = accent
- C_ONACC = "FFFFFF" if _luma(accent) < 0.5 else dark or "1A1A1A"
- m = re.search(r"--body\s*:\s*#([0-9a-fA-F]{6})", block)
- if m:
- C_SOFT = m.group(1).upper()
- def _luma(hex6):
- r, g, b = (int(hex6[i:i + 2], 16) for i in (0, 2, 4))
- return (0.299 * r + 0.587 * g + 0.114 * b) / 255
- def parse_deck(path):
- """Return list of slides; each = dict(kind, title, blocks[]).
- block = (btype, payload) with btype in h1/h2/h3/bullets/table/quote/par/peg/html."""
- md = open(path, encoding="utf-8").read()
- parse_theme(md)
- # Drop frontmatter (allow leading blank lines)
- md = re.sub(r"\A\s*---\n.*?\n---\n", "", md, count=1, flags=re.S)
- # Drop Marp directives
- md = re.sub(r"<!--_class:.*?-->", "", md)
- md = re.sub(r"<!--\s*_?class:.*?-->", "", md)
- md = re.sub(r"<!--.*?-->", "", md)
- slides = []
- for chunk in re.split(r"\n---+\n", md):
- lines = chunk.strip().splitlines()
- if not lines or all(not ln.strip() for ln in lines):
- continue
- slide = {"title": None, "subtitle": None, "blocks": []}
- i, buf = 0, lines
- while i < len(buf):
- ln = buf[i].rstrip()
- if not ln.strip():
- i += 1
- continue
- if ln.startswith("# ") and slide["title"] is None:
- slide["title"] = strip_md(ln[2:])
- elif ln.startswith("## "):
- t = strip_md(ln[3:])
- if slide["title"] is None:
- slide["title"] = t
- else:
- slide["blocks"].append(("h3", t))
- elif ln.startswith("### "):
- slide["blocks"].append(("h3", strip_md(ln[4:])))
- elif re.match(r"^- |\* ", ln):
- items = []
- while i < len(buf) and re.match(r"^\s*[-*] ", buf[i]):
- indent = len(buf[i]) - len(buf[i].lstrip())
- items.append((" " * (indent // 2)) + strip_md(re.sub(r"^\s*[-*] ", "", buf[i])))
- i += 1
- slide["blocks"].append(("bullets", items))
- continue
- elif re.match(r"^\d+\. ", ln):
- items = []
- while i < len(buf) and re.match(r"^\s*\d+\. ", buf[i]):
- items.append(strip_md(re.sub(r"^\s*\d+\. ", "", buf[i])))
- i += 1
- slide["blocks"].append(("numbers", items))
- continue
- elif ln.startswith("|"):
- rows = []
- while i < len(buf) and buf[i].strip().startswith("|"):
- cells = [strip_md(c.strip()) for c in buf[i].strip().strip("|").split("|")]
- if not re.match(r"^\s*\|[\s:|-]+\|?\s*$", buf[i]):
- rows.append(cells)
- i += 1
- if rows:
- slide["blocks"].append(("table", rows))
- continue
- elif ln.startswith(">"):
- quote = strip_md(ln.lstrip("> "))
- slide["blocks"].append(("quote", quote))
- elif ln.startswith("<"): # HTML block (peg-row, cols, rule divs…)
- html = []
- while i < len(buf) and buf[i].strip().startswith("<"):
- html.append(buf[i].strip())
- i += 1
- joined = " ".join(html)
- peg = re.search(r'class="peg"[^>]*>(\d+)<', joined) # header-tag rows (any theme)
- label = re.search(r'class="peg-label"[^>]*>([^<]+)<', joined)
- if peg and label:
- slide["blocks"].append(("peg", (peg.group(1), label.group(1))))
- elif "<strong>" in joined or "<div" in joined:
- txt = strip_md(re.sub(r"<br\s*/?>", "\n", joined))
- if txt:
- slide["blocks"].append(("box", txt))
- continue
- else:
- txt = strip_md(ln)
- if txt and not slide["subtitle"] and slide["title"] and not slide["blocks"]:
- slide["subtitle"] = txt
- elif txt:
- slide["blocks"].append(("par", txt))
- i += 1
- slides.append(slide)
- return slides
- def emit(slides):
- for s in slides:
- globals()["slide_n"] += 1
- y = 1.2
- # Background: light theme only (officecli renders text themes simply)
- add(f"/slide[{slide_n}]", "shape", x="0cm", y="0cm",
- width=f"{CANVAS_W}cm", height=f"{CANVAS_H}cm", fill=C_BG,
- line="none")
- title_y = 1.6
- if s["title"]:
- add(f"/slide[{slide_n}]", "shape", text=s["title"],
- x=f"{MX}cm", y=f"{title_y}cm", width=f"{CW}cm", height="1.5cm",
- font="Arial", size=28, bold="true", color=C_INK)
- y = title_y + 2.0
- if s["subtitle"]:
- add(f"/slide[{slide_n}]", "shape", text=s["subtitle"],
- x=f"{MX}cm", y=f"{y}cm", width=f"{CW}cm", height="1.0cm",
- font="Arial", size=15, color=C_SOFT)
- y += 1.5
- for btype, payload in s["blocks"]:
- if btype == "peg":
- num, label = payload
- add(f"/slide[{slide_n}]", "shape", text=num,
- x=f"{MX}cm", y=f"{y}cm", width="1.2cm", height="1.2cm",
- fill=C_BG, font="Consolas", size=13, bold="true",
- color=C_ACCENT, geometry="roundRect", line=C_LINE)
- add(f"/slide[{slide_n}]", "shape", text=label.upper(),
- x=f"{MX + 1.8}cm", y=f"{y + 0.25}cm", width="12cm",
- height="0.8cm", font="Consolas", size=10, bold="true",
- color=C_ACCENT)
- y += 1.8
- elif btype == "h3":
- add(f"/slide[{slide_n}]", "shape", text=payload.upper(),
- x=f"{MX}cm", y=f"{y}cm", width=f"{CW}cm", height="0.8cm",
- font="Consolas", size=11, bold="true", color=C_ACCENT)
- y += 1.2
- elif btype == "bullets":
- txt = "\n".join("· " + item for item in payload)
- h = max(1.2, 0.75 * len(payload) + 0.6)
- add(f"/slide[{slide_n}]", "shape", text=txt,
- x=f"{MX}cm", y=f"{y}cm", width=f"{CW}cm", height=f"{h}cm",
- font="Arial", size=14, color=C_SOFT, valign="top")
- y += h + 0.4
- elif btype == "numbers":
- txt = "\n".join(f"{i}. {item}" for i, item in enumerate(payload, 1))
- h = max(1.2, 0.75 * len(payload) + 0.6)
- add(f"/slide[{slide_n}]", "shape", text=txt,
- x=f"{MX}cm", y=f"{y}cm", width=f"{CW}cm", height=f"{h}cm",
- font="Arial", size=14, color=C_SOFT, valign="top")
- y += h + 0.4
- elif btype == "table":
- rows = payload
- n, c = len(rows), len(rows[0])
- colw = (CW - 0.4 * (c - 1)) / c
- add(f"/slide[{slide_n}]", "table", rows=n, cols=c,
- x=f"{MX}cm", y=f"{y}cm",
- colWidths=",".join(f"{colw:.2f}cm" for _ in range(c)),
- bandedRows="false")
- t = f"/slide[{slide_n}]/table[1]"
- for r, row in enumerate(rows, 1):
- st(f"{t}/tr[{r}]", height="0.85cm" if r == 1 else "1.1cm")
- for cix, val in enumerate(row, 1):
- if r == 1:
- st(f"{t}/tr[1]/tc[{cix}]", text=val, fill=C_BG,
- color=C_ACCENT, bold="true", font="Consolas",
- size=10)
- else:
- st(f"{t}/tr[{r}]/tc[{cix}]", text=val,
- fill="FFFFFF", color=C_SOFT, font="Arial",
- size=11, valign="middle")
- y += (0.85 if n else 0) + 1.1 * (n - 1) + 0.6
- elif btype == "quote":
- add(f"/slide[{slide_n}]", "shape", text=payload,
- x=f"{MX}cm", y=f"{y}cm", width=f"{CW}cm", height="1.6cm",
- font="Arial", size=12.5, color=C_INK, fill=C_BG,
- geometry="rect")
- add(f"/slide[{slide_n}]", "shape", x=f"{MX}cm", y=f"{y}cm",
- width="0.13cm", height="1.6cm", fill=C_ACCENT, line="none")
- y += 2.0
- elif btype == "par":
- h = 1.2 + 0.5 * (len(payload) // 110)
- add(f"/slide[{slide_n}]", "shape", text=payload,
- x=f"{MX}cm", y=f"{y}cm", width=f"{CW}cm", height=f"{h}cm",
- font="Arial", size=13, color=C_SOFT, valign="top")
- y += h + 0.3
- elif btype == "box":
- add(f"/slide[{slide_n}]", "shape", text=payload,
- x=f"{MX}cm", y=f"{y}cm", width=f"{CW}cm", height="2.0cm",
- font="Arial", size=12.5, color=C_SOFT, fill=C_BG,
- geometry="rect", line=C_LINE, margin="12pt,10pt,12pt,10pt")
- y += 2.4
- if y > 17.2:
- break # keep content on-canvas; overflow goes to next slide in a full rebuild
- def flush(out_path):
- payload = json.dumps(ops)
- r = subprocess.run(["officecli", "batch", out_path, "--commands", payload,
- "--json"], capture_output=True, text=True)
- try:
- data = json.loads(r.stdout)
- fails = [x for x in data.get("data", {}).get("results", [])
- if not x.get("success")]
- except Exception:
- fails = ["(unparseable output)"]
- if r.returncode != 0 or fails:
- print(f"officecli batch failed: {len(fails)} item(s)", file=sys.stderr)
- for f in fails[:4]:
- print(f, file=sys.stderr)
- sys.exit(1)
- print(f"officecli batch ok: {data.get('data', {}).get('summary', '')}")
- def main():
- if len(sys.argv) != 3:
- print(__doc__)
- sys.exit(2)
- src, out = sys.argv[1], sys.argv[2]
- subprocess.run(["officecli", "create", out], capture_output=True)
- # Pre-create slides one at a time (mixed slide-adds in one batch are unreliable)
- slides = parse_deck(src)
- for _ in slides:
- subprocess.run(["officecli", "add", out, "/", "--type", "slide"],
- capture_output=True)
- emit(slides)
- flush(out)
- subprocess.run(["officecli", "close", out], capture_output=True)
- print(f"Written {out} ({len(slides)} slides) — editable text boxes + tables.")
- if __name__ == "__main__":
- main()
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.