chore: 1.0.0 release

This commit is contained in:
binaryify
2026-08-05 16:25:24 +08:00
commit 5b0d45bf1d
100 changed files with 11034 additions and 0 deletions
+155
View File
@@ -0,0 +1,155 @@
---
name: open-kimi-ppt
description: Create, edit, replicate, read, and export presentations. For every PPT task, the default deliverables are BOTH (1) a self-contained PPTD project folder containing the .pptd manifest plus pages/media dependencies and (2) a locally generated .pptx with embedded fonts and fade slide transitions. Use for any presentation, PowerPoint, PPT/PPTX, slide deck, PPTD, infographic, or poster task unless the user explicitly requests another format. Deliver with normal local file/folder links using absolute paths.
---
# Definition
open-kimi-ppt is a presentation creation and export skill built around Moonshot AI's PPTD format and browser-side PPTX writer. It defines a YAML-format intermediate DSL (`.pptd`) that abstracts OOXML and keeps each page self-contained.
**The default output is not PPTD-only.** Unless the user explicitly opts out, always produce both:
1. the complete editable PPTD project directory (`.pptd` + `pages/` + `media/` and other referenced dependencies);
2. the matching locally generated `.pptx`, with font embedding enabled and fade slide transitions applied by default.
Existing PPTX files may also be converted into PPTD for editing, after which both outputs are delivered again.
## The pptd format
The .pptd format is a simplified abstraction layer over OOXML that follows basic YAML syntax. This abstraction preserves the core content of OOXML (theme, page layout, element positions and definitions, etc.) while removing complex nesting logic such as Masters; every page is self-contained — what you see is what you get. Read reference/pptd.md for the complete definition of this DSL.
## PPT production workflow
### step1. Read the context thoroughly
Read **all files uploaded by the user**, the provided URLs, and the pptd format guide `reference/pptd.md` to fully understand the user's requirements.
### step2. Understand the user's requirements
Understand the user's requirements based on the context:
1. First determine the purpose of the request
- Create a PPT: create a new presentation (from scratch, or from an existing pptx template)
- Edit a PPT: edit the user's uploaded PPT (local modifications, single-page beautification, etc.)
- Replicate a PPT: replicate a presentation from a non-pptx format (images, PDF, etc.) into pptd format
2. Then determine the design direction
- Self-directed design: no preference, or only simple style constraints given; you need to fill in or create the design
- Design system: the user provides a complete and detailed design scheme covering all color, font, layout, and component specifications
- Use a template: a template is provided and must be used
- Style transfer: a style reference source is provided (images, web pages, etc.)
3. Then determine the input type
- Topic only: only a PPT topic direction or content requirements for the presentation are given, with no concrete content
- Full document: the user provides a complete document (paper, research report, press release, etc.)
- Outline: the user provides a page-by-page outline, speech script, or similar content
* When the "user input type" is [Full document] or [Outline] and it is not specified whether expansion is allowed: since a page-by-page outline, speech script, or user document can hardly support the full content of a presentation, prefer using search to expand with more relevant material, cases, etc., unless the user explicitly says not to expand
4. Page count
- If the user requests a specific page count, the user's requirement takes priority
- Page-by-page outline/script provided: match the number of pages in the outline/script
- When a complete and relatively structured document is provided / when only a topic is provided: decide the page count yourself based on the document content / search results
### step3. Generate the presentation based on the user's requirements
Before generating, first read `reference/pptd.md` to understand the pptd format definition and constraints.
#### Replicating a PPT
- Analyze the images to estimate element positions, fonts and sizes, etc., and **replicate 1:1 as closely as possible**.
- When an image contains elements that are hard to replicate directly and cannot be approximated with icons/shapes (e.g., photos, avatars), you may use tools such as bash or python to crop and screenshot the original image
#### Editing a PPT
- Convert the user's uploaded pptx file to .pptd format
- Review the converted pages (structure and key visual details). Read a few key pages individually afterwards.
- Locate the pages to edit, and be careful not to affect parts outside the intended scope.
> Conversion from pptx to pptd is not perfectly lossless. If the user later reports format errors, garbled content, etc., compare against the original pptx and repair the pptd with reference to the comparison
#### Generating a PPT
When generating a PPT, adopt different production approaches for different user [design directions]
##### Self-directed design
1. Read the design guide `reference/slides_categories.md`, and read the scenario document corresponding to the user's query
2. Produce the presentation based on the above
#### Generating content in other formats
- When the user explicitly asks for an infographic, poster, or a highly visual single-page design, read `reference/general-poster.md` and implement it as a single-page or few-page editable PPTD; when the user only asks for an image, still build it with PPTD first, then output the image via screenshot or rendering. Do not load this reference file for ordinary PPT requests.
##### Design system
1. Read the general constraints section of the `reference/slides_categories.md` guide, and read the scenario document corresponding to the user's query as the design foundation
2. Read the user-provided design system document as the presentation style. It is strictly forbidden to reference or mix in other design styles
3. Produce the presentation with reference to the above
##### Using a template
1. Convert the user's uploaded pptx file into pptd form
2. Review the converted pages to understand the template's visual style (color scheme, font style, element characteristics, layout characteristics, content density, etc.)
3. Identify page types; focus on reading special pages such as the cover, summary pages, and section dividers (single-page screenshots, .page files), extracting their page layouts, content structures, reusable components (icons, shapes, smartart, reusable body layout schemes, etc.), and element styles (e.g., whitespace/line/card separators, square/rounded corners, etc.)
4. Produce the presentation using the template
##### Style transfer
1. Analyze the reference file's visual style (color scheme, font style, element characteristics, layout characteristics, content density, etc.), page layouts, content structures, reusable components (icons, shapes, smartart, reusable body layout schemes, etc.), and element styles (e.g., whitespace/line/card separators, square/rounded corners, etc.).
- If the user provides a style reference URL, do not only read the text content; refer to and learn from the page's visual effect more to help understand the style
2. Produce the presentation using the reference file's style characteristics. You are encouraged to reuse illustrations, fonts, font-size hierarchies, elements, etc. from the original pdf/url
### step4. PPT validation
1. Validate the generated pptd against the format definition in `reference/pptd.md` (required fields, types, bounds, theme tokens, resource paths, etc.) and repair issues over multiple rounds
2. Visual review with exported page images — **required before PPTX export when the model supports image input (multimodal)**:
- Run `scripts/export_images.py`. It loads the deck into Kimi's public editor, chooses 导出 → 图片, downloads the images ZIP, unzips it, and stitches all pages into one overview image:
```bash
python3 ~/.agents/skills/open-kimi-ppt/scripts/export_images.py \
/abs/path/project/deck.pptd \
--output /abs/path/project/.qa-images
```
The script prints a JSON summary mapping each stitched label (`P1`…`Pn`, 1-based page order) to its `.page` file.
- Read the stitched overview image (`.qa-images/overview.jpg`) and check every page against this list:
1. 图片是否清晰、不变形(无拉伸、压缩、模糊)
2. 文字是否压在关键画面(人脸、产品主体、Logo 等)上
3. 元素坐标是否超出页面边界
4. 边界与配色对比是否足够(文字与背景、相邻色块之间)
5. 排版是否统一(对齐、间距、字号层级、页边距)
6. 文字是否可能溢出文本框(文本过长、行距过密、字号过大)
7. 内容是否被上层元素遮挡
- For any suspicious page, read its full-resolution image (`.qa-images/pages/<n>.jpeg`) to confirm the problem before editing.
- Fix issues in the corresponding `.page` file, then re-run `scripts/export_images.py --force` and review the new overview; repeat until every page passes.
- Do not export the PPTX until the visual review passes. `.qa-images/` is an intermediate QA artifact and may be deleted after delivery.
3. When the model cannot read images, fall back to a structural review of the generated pages (bounds, overflow-prone long text, contrast, hierarchy, layout density) over multiple rounds, and state that image-based visual QA was skipped.
### step5. PPT output and delivery
1. Always produce a self-contained project directory. Keep the `.pptd` manifest and every referenced dependency together; never deliver a standalone manifest without its referenced files. Use this layout unless an existing project already has a valid equivalent structure:
```text
deck/
deck.pptd
pages/
*.page
media/
* # when the deck has local media
deck.pptx # generated by default
```
2. Generate the `.pptx` by default after PPTD validation, even when the user only asks to create or edit a presentation. Skip PPTX export only when the user explicitly requests PPTD-only output or the environment cannot run the exporter; in the latter case, report the exact blocker and still deliver the complete PPTD project.
3. Deliver with normal clickable local links using absolute paths. In the final response, link all of the following:
- the project directory;
- the `.pptd` manifest;
- the `pages/` directory and `media/` directory when present;
- the generated `.pptx` file.
4. PPTX conversion: use `scripts/export_pptx.py`. It opens a temporary localhost SDK host, loads the `.pptd` into Kimi's public editor, invokes the same browser-side OOXML writer as the official Download tab, saves the resulting PPTX locally, and validates the ZIP/slide structure.
5. Default PPTX options:
- page transition: `fade` (淡入淡出), written to every slide after the official browser export;
- font embedding: enabled whenever the official writer exposes/supports it;
- these defaults may be explicitly overridden with `--transition none` or `--no-embed-fonts`.
6. Export command:
```bash
python3 ~/.agents/skills/open-kimi-ppt/scripts/export_pptx.py \
/abs/path/project/deck.pptd \
--output /abs/path/project/deck.pptx
```
A project directory may be passed instead of the manifest only when it contains exactly one `.pptd` file.
Existing output files are not overwritten unless `--force` is passed.
7. Local export requirements and boundaries:
- requires `python3`, PyYAML, `npm`, `agent-browser`, Chrome/Chromium, and network access to `www.kimi.com` plus `statics.moonshot.cn`; the image-based visual QA step additionally requires Pillow, auto-installed with `pip --user` when missing;
- before browser export, `export_pptx.py` checks `agent-browser --version`; when it is missing or below `0.33.2`, it installs `agent-browser@latest` globally with npm, then verifies the resulting version before continuing;
- the PPTD document itself is provided to the public editor iframe through the localhost SDK bridge, not uploaded to a server-side PPTX conversion endpoint;
- remote images, icons, or fonts referenced by the deck may still be fetched from their respective hosts;
- local PNG/JPEG/GIF/SVG files inside the PPTD project are supplied to the iframe as data URLs;
- do not claim PowerPoint/WPS/Keynote playback compatibility solely because ZIP validation succeeds.
8. After export, verify that the output exists and report the generated path. Confirm that every slide has exactly one root-level fade transition in valid CT_Slide order (`cSld`, optional `clrMapOvr`, `transition`, optional `timing/extLst`) and that the PPTX ZIP passes integrity checks. A byte-string search for `<p:fade>` is insufficient because Office ignores transitions nested inside `cSld`. For higher-risk decks, additionally inspect font parts and representative rendered/opened pages as appropriate.
9. When the user wants to open, edit, save, or export a PPTD project manually, start the local browser editor with `npx open-kimi-ppt-skills serve`. Ask the user to open `http://127.0.0.1:55173/` and authorize the complete PPTD project directory. Use a Chromium-based browser for writable access; folder-upload fallback is read-only. The local host only serves the editor shell, while the embedded public Kimi editor and remote assets still require network access.
10. After completing and delivering any presentation, always end the final response with a concise optional next step telling the user that they can run `npx open-kimi-ppt-skills serve` to view or edit the PPTD project, configure slide transition animations, and export PPTX manually. Keep this reminder in addition to, not instead of, the required project and file links.
+47
View File
@@ -0,0 +1,47 @@
# Font system
## Selection principles
1. Language matching: when the user's query is in Chinese or a Chinese PPT deliverable is requested, both Chinese and English fonts need to be specified; otherwise, only English fonts need to be set
2. Selection approach: it is recommended to prioritize highly readable fonts for body text, and to use stylized fonts plus special treatments (all caps, widened letter spacing, bold, italics, etc.) in titles or special pages to strengthen the style
3. The font combination must support the overall visual style positioning
4. Name consistency: **make sure font names are exactly identical, including capitalization and spaces, so that the model can use them correctly**
## Font list
### English fonts
| Font name | Font type | Style and characteristics | Suitable scenarios | Stylized font |
|---|---|---|---|---|
| Liter | Sans-serif | Modern neo-grotesque style; low contrast, balanced proportions, optimized for screens; clean and rational | Tech, product | No |
| HedvigLettersSans | Sans-serif | A "non-designer perspective" design; slightly irregular with a distinctive personality and strong brand character | Creative design, branding | No |
| Oranienbaum | Serif | Modern high-contrast serif; strongly geometric with elegant lines and a classical temperament | Culture, art, fashion | No |
| QuattrocentoSans | Sans-serif | Classic, elegant sans-serif; gentle, highly readable, clear at small sizes | Academic, corporate, education | No |
| SortsMillGoudy | Serif | Revival of the classical print style of Goudy Old Style; soft serifs, pleasant to read | Literature, humanities | No |
| Unna | Serif | Neoclassical serif with a pronounced vertical rhythm; elegant yet forceful | Literature, publishing, academia | Yes |
| Coda | Sans-serif | Rounded and friendly; soft curves, high openness | Business, friendly brand tone | Yes |
| Jersey15 | Sans-serif (sports style) | Sports jersey style; squared structure with a noticeable grid feel (supports English + digits only) | Sports, tech showcase pages | Yes |
| Jersey20Charted | Pixel font (grid shading) | Sports-number style with a shaded grid that reinforces an athletic texture (supports English + digits only) | Sports, mechanical, decorative showcase pages | Yes |
### Chinese fonts
| Font name | Font type | Style and characteristics | Suitable scenarios | Usage restriction |
|---|---|---|---|---|
| MiSans | Sans-serif (heiti) | Xiaomi system font; clean and modern, variable weights, excellent on-screen rendering (multilingual support) | Tech, corporate, product | No |
| Noto Sans SC | Sans-serif (heiti) | A branch of Source Han Sans; well-regulated structure, neutral style, extremely broad coverage. **Because it is so widely used, use it as little as possible** | Report-style | No |
| 思源宋体 | Serif (songti) | Source Han Serif; refined songti structure with stroke contrast; elegant reading experience (multilingual support) | Literature, design, formal presentations | No |
| 阿里妈妈刀隶体 | Calligraphy (clerical script) | Alimama DaoLi; clerical-script style with blade-like strokes; strength and archaic simplicity combined | China-chic, culture, art displays | No |
| 阿里妈妈东方大楷 | Calligraphy (regular script) | Alimama Dongfang Dakai; based on the Yan style of calligraphy; full and rounded, heavy and powerful | Culture, brand launches, guofeng (Chinese-style) themes | No |
| 阿里妈妈数黑体 | Sans-serif (heiti) | Alimama ShuHei; geometric heiti; uniform and regular with a strong commercial feel | Business, tech, e-commerce | No |
| 站酷文艺体 | Handwriting | Zcool WenYi; clean and fresh with a slight handwritten feel and a strong literary/artistic vibe | Light design, lifestyle | No |
| 飞波正点体 | Calligraphy (brush) | Feibo Zhengdian; brush-writing style with heavy strokes, full of power | Film posters, e-commerce, brand display | No |
| 得意黑 | Sans-serif (slanted heiti) | Smiley Sans; tall, slanted heiti combining humanist and geometric qualities with a strong modern feel. **Does not support a non-italic upright style** | Creative tech, brand display | No |
| 霞鹜新致宋 | Serif (songti) | LXGW XinZhiSong; based on IPAmj Mincho; bright, elegant, well-structured | Literature, classical style, print style | No |
### Mixed CJKLatin fonts
| Font name | Font type | Style and characteristics | Suitable scenarios | Usage restriction |
|---|---|---|---|---|
| 精品点阵体 | Pixel font | Jingpin Dianzhen; 9×9 dot-matrix pixel style with an extremely retro electronic feel | Games, tech, pixel art | Yes |
| LXGW Bright | Serif (fangsong/kaiti) | LXGW WenKai family; combines fangsong and kaiti characteristics; gentle and clear letterforms | Literature, education, humanities | No |
| ZCOOL KuaiLe | Handwriting (rounded) | ZCOOL KuaiLe; lively, cute, playful and cartoonish; youthful energy | Anime, children, entertainment | No |
@@ -0,0 +1,241 @@
# General Infographics and Posters
Use this guide only when the user explicitly requests an infographic, poster, or a highly visual single-page design. Do not load this guide for ordinary PPT requests.
This guide defines only the design decision process and quality baselines; it does not prescribe fixed color schemes, fonts, maps, timelines, grids, or page skeletons. Design independently based on the subject, audience, materials, and usage scenario; never copy a sample by default just because it is more detailed.
## Production Workflow
### 1. Understand the Subject and Communication Goals
First confirm:
- What this poster should make readers see, understand, remember, or do.
- The primary audience, viewing distance, display medium, and available reading time.
- The size, aspect ratio, colors, style, content, and output format explicitly requested by the user.
- The core relationship the material truly needs to express: time, space, process, contrast, hierarchy, object structure, or pure spirit/atmosphere conveyance.
- Whether the available images, data, and verifiable facts are sufficient to support the chosen form of expression.
### 2. Explore Different Directions First, Then Choose One
Before writing any `.page` file or placing elements, internally form 23 visual directions with substantive differences. They should differ in at least two of the following:
- Primary visual focus: image, typography, object, data, map/relationship diagram, or abstract graphics.
- Information structure: linear narrative, radial hub, local zoom, layered section, juxtaposed comparison, image matrix, or a single scene.
- Spatial organization: full-bleed, off-axis, symmetric, high-density, generous whitespace, or zoned structure.
At least one candidate direction should treat the entire canvas as one visual field, scene, or object relationship, rather than first splitting the content into containers of equal width and height. Cards may appear among the candidates, but must not automatically become the default just because the information has three or four items.
Before finalizing a direction, compare which primary visual medium best carries the content. Whenever people, artifacts, materials, environments, or event scenes are important evidence for the subject, actually examine at least 2 existing images, search results, generated images, proofs, or reference screenshots that differ substantively in composition or visual language; whenever process, hierarchy, system, propagation, causality, contrast, or spatial relationships are central, compare at least 2 editable vector or SmartArt-like figure drafts with clearly different structures. After comparing subject recognizability, thumbnail memorability, information capacity, compositional coexistence, and editability, choose photography/real-object imagery, generated images, custom vectors, structured figures, or a hybrid solution. Do not default to pure vectors just because PPTD vectors are easier to implement or because searching/generating assets takes time, and do not force in images unrelated to the content just to "have assets."
Choose one direction based on the subject's characteristics, the user's tone, asset quality, and the primary reading task. You don't need to deliver three designs, but don't start building the moment you see the first workable option.
Available grammars include but are not limited to typography-led, photography-led, object/section annotation, archival collage, data field, spatial map, or relationship diagram. These are angles for thinking, not templates that must be applied.
### 3. Write `style.md` in the Project
For a newly created poster/infographic, create a brief `style.md` in the PPTD project root before writing `.page` files. It is the design brief for the current task — not a new skill file, not a hard process gate, and not an extra deliverable.
Review the user's assets, actual image candidates, and the fonts available in `reference/fonts.md` before finalizing `style.md`. Keep the content short, specific, and actionable; it typically includes:
```markdown
# Style Brief
- Goal and audience:
- Output scenario and canvas:
- Core message in one sentence:
- Chosen visual concept/metaphor:
- Primary visual focus:
- Poster-level visual move (why this is not an ordinary content page):
- Visual DNA (background/material, typographic/geometric temperament, how images coexist with structured information):
- Primary visual medium and asset/SmartArt-like figure candidates compared, with reasons for the choice:
- Reading order and composition:
- Color scheme and each color's role:
- Chinese and English fonts, size hierarchy, and usage:
- Image selection, cropping, and treatment:
- Graphics/chart/connector language (if needed):
- Information density, whitespace, and alignment:
- Tropes to avoid:
```
- Explain why this direction was chosen, and record in one sentence the main reason the other directions were not chosen; also state which trope the chosen direction is most likely to degenerate into (for example, an ordinary technical report, a retro propaganda page, a commercial promotion, or a uniform card wall), so it can be checked against during screenshot review.
- When the user has already provided a complete design system, template, or strong style constraints, `style.md` only converts them into actionable decisions; do not invent new styles that conflict with the user's requirements.
- After viewing actual images or discovering asset limitations, you may update `style.md` once before refining the pages. Do not turn it into a lengthy process log.
- Creating a new `style.md` is not mandatory when making local edits to an existing artifact; it is only needed when redesigning the overall visual.
## Canvas Ratio and Orientation
Determine the output scenario and canvas first, then design the grid, font sizes, and content structure. Do not equate a poster with portrait orientation by default, and do not default to inheriting PPT's 16:9.
1. When the user explicitly specifies a size, orientation, or ratio, strictly use the user's requirement.
2. When the user has not specified, choose on your own based on the deployment scenario, information richness, primary reading order, and relationship structure.
3. When there is too much information, prioritize distilling, layering, or splitting into a few pages; do not cram everything into a single page with extremely small font sizes.
4. Once the canvas is chosen, compose directly for that ratio; do not build it in 16:9 first and then stretch or crop the whole thing into another ratio.
| Common ratio | PPTD reference size | Common scenarios |
|---|---:|---|
| 9:16 portrait | `[540, 960]` | Mobile reading, social media, vertical narrative |
| 3:4 portrait | `[720, 960]` | Print-like posters, person/object hero visuals |
| 1:1 square | `[720, 720]` | Social media, centered structures, moderate information volume |
| 4:3 landscape | `[720, 540]` | Higher-density text-image content, document embedding |
| 16:9 landscape | `[960, 540]` | Widescreen display, horizontal relationships and parallel multi-column layouts |
A PPTD canvas can use any `[width, height]`; the sizes in the table are references, not enumerated restrictions.
## Content Relationships and Graphic Selection
First state the page's core message in one sentence, then choose the graphic that best expresses it. Use a structure diagram only when the relationship itself is central; do not add maps, timelines, routes, flowcharts, matrices, or indexes just to look rich. Parallel relationships do not automatically equal cards: first consider groups of objects in the same scene, sequences of images/symbols, scale differences, spatial adjacency, color bands, rule lines, or typographic rhythm.
When the core message is process, hierarchy, system, propagation, causality, contrast, or spatial relationships, treat structured graphics (SmartArt-like figures), maps, routes, or method diagrams as primary visual material. The chosen structure diagram should occupy enough area and participate in the whole-page composition, implemented with editable PPTD elements where possible; generating native OOXML SmartArt objects is not required, but do not let it degenerate into a row of rounded boxes, generic icons, and thin arrows just for the sake of "editability." It can form one continuous visual field together with the main object, scene imagery, close-up details, and anchored captions.
| Core relationship | Possible expressions |
|---|---|
| Time evolution, stage changes | Timeline, milestones, before/after states |
| Paths, propagation, migration | Maps, routes, flows, or networks |
| Steps, mechanisms, methods | Process, swimlanes, inputprocessoutput |
| Differences between objects or viewpoints | Juxtaposed comparison, matrix, scale axis |
| Hierarchy, composition, systems | Tree hierarchy, architecture, layered section |
| Physical objects, products, paper method details | Object annotation, local zoom, visual anatomy |
| Multiple facts or samples | Image matrix, taxonomy map, data field |
| Emotion, ideas, attitudes | Single strong image, pure typographic composition, abstract form |
- When the user explicitly requests a "map," provide a geographic base or outline that can establish spatial relationships; do not pass off an abstract polyline as a map.
- For routes, propagation, and migration, choose on your own among a full-bleed map, a local locator, a radial network, land-sea layering, or multiple branch routes based on semantics; do not default to thin horizontal lines.
- For architecture diagrams, UML, and paper method figures, first ensure the nodes, interfaces, directions, grouping, and legends are correct before visual beautification.
## Design Freedom and Quality Baselines
- Colors, fonts, image treatment, and composition arise from the subject and `style.md`. Unless the user explicitly requests it, do not default to black-white-silver-gray, a single-point fluorescent accent, giant cropped type, archival micro-labels, or thin-line timelines.
- A poster should first establish one dominant visual grammar, with other elements serving it. Do not cram the hero image, giant type, map, timeline, icon matrix, and data charts in all at once just to seem "rich."
- Establish at least one visual memory point that remains recognizable in a full-page thumbnail or at a distance, carried by the hero image, giant type, a large object, a full-bleed color field, a scene, or the core relationship diagram. If the thumbnail shows only a title and a set of regular boxes, recompose.
- When producing multiple pieces on different subjects in succession, do not default to reusing the previous one's main composition, accent-color roles, image proportion, and linear graphics.
- Grids, whitespace, cards, collages, asymmetry, or full-bleed are all optional means, not the default correct answer. Avoid stuffing every category of content below the title into equal-width, equal-height rectangles with rounded corners, outlines, or shadows, forming a "three-card/four-card + CTA" slide or app-interface skeleton. Use containers only when the container itself has clear semantics and will not form a uniform card wall; otherwise prefer organizing content with layout zones, proportion, color blocks, rule lines, spatial adjacency, object groups, or typographic rhythm.
- A page may have very little text, or it may have several high-density modules; but the core message, primary visual focus, and reading path must be clear. Organize rich content primarily through scale hierarchy, local zooms, captions, and spatial relationships; do not disguise sparse content as rich with repeated cards or oversized padding, and do not compress a large number of facts into unreadably small text.
- Body text, annotations, legends, and sources must be readable in the actual output scenario. When there is too much information, cut, layer, or split pages; do not solve it with tiny font sizes.
- Data, facts, dates, locations, labels, units, and sources must stay faithful to the user's materials or verifiable information. For precise figures that cannot be confirmed, use qualitative statements, approximations, or omit them; do not fabricate statistics, coordinates, issue numbers, or publication details for an "archival feel."
### Few-shot: Multiple Complete Briefs and Anonymous Visual-Move Fragments
The following complete samples are used to expand the design moves, primary visual media, and risk awareness you can draw on; they are not fixed visual families, subject mappings, or templates awaiting selection. The concept name, visual DNA, colors, fonts, canvas, and composition of an actual brief must be re-derived from the current subject, assets, and reading relationships; you may recombine a few compatible moves across samples, or devise your own entirely — do not just pick the most similar label and copy the whole set.
#### Poster Editorial
```markdown
# Style Brief — Poster Editorial
- Goal and audience: designed for quick browsing and short dwell; make the subject memorable first, then let readers discover archival details.
- Output scenario and canvas: choose landscape or portrait based on the actual medium; do not take a 16:9 layout and crop it.
- Core message: string together the object, time, and context with one judgment that takes a position; do not use section-style empty titles.
- Visual concept: "a contemporary, editorially curated object archive"; calm, sharp, with print tension, without imitating a real magazine cover.
- Primary visual focus: choose only one of three as the protagonist — a high-contrast object image, an object silhouette, or giant type.
- Reading order and composition: use a rigorous grid with a clear dense-versus-sparse counterpoint; the title, exhibit item, and micro captions form three scales, but not every poster is required to have a route or timeline.
- Color: Editorial White `#F7F6F2` and Deep Black `#0B0B0B` carry the main relationship; silver-gray is used only for secondary information; choose at most one small-area accent from Signal Red `#F20505`, Fluoro Lime `#D6FF00`, or Acid Orange `#FF4A1C`.
- Fonts: the main title uses 得意黑/阿里妈妈数黑体 with HedvigLettersSans; the body uses MiSans/Liter; at most three font families, and the numbering font does not carry body text.
- Image treatment: prefer images with strong contours, close-ups, and room for bold cropping; they may be converted to black and white or desaturated, but keep the object's recognition points.
- Graphic language: use hairlines, short labels, and small nodes only when content relationships need them; maps must have a spatial base, and data charts must have real data.
- Information density: keep one clear visual breathing area; archival details may be dense, but body text and captions must be readable at the actual output size.
- Must avoid: rounded-card walls, evenly distributed accent colors, fake logos/issue numbers/archives, and stacking giant type, a map, a timeline, and an icon matrix all at once just to seem rich.
- Reason for choosing: when the subject needs to be highly memorable while retaining traceable details, this direction is superior to a generic commercial infographic.
```
#### Geometric Composition
```markdown
# Style Brief — Geometric Composition
- Visual concept: translate the core concept into tension among circles, squares, lines, proportions, and glyphs; do not use geometric blocks to decorate empty space.
- Primary visual focus: one geometric relationship or glyph composition occupying the main area, not multiple evenly distributed colored rectangles.
- Poster-level visual move: let the title pass through, embed into, or cut across the main geometry, so text and composition together become the image, instead of the title hovering above the content.
- Visual DNA: decide color roles and typographic temperament from the subject; establish order with proportion, axes, numbering, and scale, with factual information taking its place along the geometric relationships.
- Information organization: bind concept differences, proportions, stages, or a work index to shape relationships; secondary material is tucked into the edges or a narrow index band.
- Must avoid: evenly tiling primary colors, a children's-building-block feel, random circles and squares unrelated to the content, and degenerating the geometric composition into a colored card wall.
```
#### Material Evidence
```markdown
# Style Brief — Material Evidence
- Visual concept: treat materials, artifacts, surface traces, or the making process as evidence, letting tactile quality and provenance relationships tell the content together.
- Primary visual focus: a sufficiently large macro, scan, section, or artifact detail; other images relate to it as slices, sequences, or provenance evidence.
- Poster-level visual move: let the texture or object span the main extent of the canvas, with captions anchored directly to visible details; do not shrink high-quality assets into specimen cards.
- Visual DNA: extract color, grain, and line language from the actual object; fonts and labels serve the material's temperament; maps, genealogies, or processes appear only when relationships need them.
- Information organization: organize facts through source labels, local zooms, material genealogy, craft steps, or propagation paths, keeping one clear breathing area.
- Must avoid: uniform brown retro templates, travel souvenir albums, forged old archives, decorative seals, and a row of equally sized object cards.
```
#### Dark-Field Signals
```markdown
# Style Brief — Dark-Field Signals
- Visual concept: in a dark field, use localized light sources, trajectories, scales, or rhythmic signals to establish a sense of direction; black is space, not background fill.
- Primary visual focus: one brightly lit object, motion image, glowing trail, or high-contrast glyph form, with other elements building distance and speed around it.
- Poster-level visual move: let a signal line, path, or band of light cross the canvas and connect fact nodes, so the subject and direction of motion remain recognizable from a distance.
- Visual DNA: accent colors serve only nodes, directions, numbers, or warnings; numeric fonts, coordinates, and scanning elements must serve reading rather than create tech noise.
- Information organization: organize route, time, frequency, cohort, or status data along a common coordinate field; keep a stable high-contrast safe zone for body text.
- Must avoid: full-page neon, bloom effects, cyber dashboards, small gray text on black, and packing every data group into a glowing panel.
```
#### Scientific Observation
```markdown
# Style Brief — Scientific Observation
- Visual concept: treat the page as a verifiable observation field, using objects, sections, relationships, and scale to explain a mechanism, rather than presenting a popular-science column.
- Primary visual focus: a main specimen, an ecological section, a system relationship, or a local zoom; readers see the object first, then understand the mechanism along the annotations.
- Poster-level visual move: let scale, depth, hierarchy, flow direction, or causality run through the whole page, with imagery and legend sharing the same spatial coordinates.
- Visual DNA: colors distinguish objects, relationships, and risks; annotation lines, units, legends, sources, and confidence boundaries stay readable and checkable.
- Information organization: mechanisms, specimens, and evidence are organized through spatial adjacency and connecting relationships; use a small amount of comparison when necessary, and do not default to three-column cards.
- Must avoid: technical-report front pages, white dashboards, equal-width info boxes, decorative data, and unverifiable precise figures.
```
#### Dynamic Collage
```markdown
# Style Brief — Dynamic Collage
- Visual concept: use directional glyphs, cropped imagery, color bands, and event fragments to create a manifesto feel, with rhythm coming from content conflicts rather than decorative noise.
- Primary visual focus: one boldly cropped title, figure/object silhouette, or high-contrast image; do not let multiple assets compete evenly for attention.
- Poster-level visual move: interweave the title, imagery, and a diagonal or offset structure to form a direction and posture recognizable from a distance.
- Visual DNA: maintain one dominant contrast relationship; collage edges, numbering, event nodes, and short phrases share a unified logic of angle, weight, and spacing.
- Information organization: compress viewpoints, impacts, events, or stages into a few directional band sequences; body text returns to a stable grid to stay readable.
- Must avoid: promotional ads, price tags, meaningless torn paper, slogan stacking, too many angles, and enlarging all text at once.
```
#### Detachable Anonymous Move Fragments
The following provide only local compositional knowledge, not complete directions; do not name the fragments, and do not match subjects to them one by one. First state the current page's core message and dominant relationship, then adapt one or two of these moves as needed, or devise your own entirely:
- Let the title pass through, embed into, or cut across a main geometry that carries information; facts take their place along proportions, axes, numbering, or shape relationships — the geometry is not just space-filling decoration.
- Let objects, textures, macros, or sections span the main extent of the canvas, with captions anchored directly to visible details; other images form slice, sequence, or provenance relationships rather than shrinking into a row of specimen cards.
- Let routes, light bands, or motion trails cross the canvas and connect fact nodes while retaining the necessary geographic, scene, branch, and time information; paths can be formed by imagery, terrain, or spatial relationships rather than defaulting to thin-line charts.
- Let specimens, sections, scale, legends, and causal relationships share one continuous observation field; when immersion matters, preserve the continuity of the environment rather than degenerating into a "main image left + evidence box right" technical report.
- Interweave a recognizable title or object, cropped imagery, and a directional structure; events and viewpoints unfold along a unified rhythm, and avoid letting the title's recognizability drown in collage noise.
In an actual task, regenerate `style.md` from the subject, assets, and reading relationships, using a concept name unique to the current task. Do not first look through the fragments for the "most similar category," and do not write "selected the so-and-so family" in the brief. Keep one dominant visual grammar, with other moves only as compatible support; the final direction must explain why it suits the current content, rather than merely swapping the sample's subject text and accent color.
## Imagery, Copyright, and Authenticity
- Prefer images with a clear subject, usable room for cropping, and genuine semantic relevance to the content. Ensure objects and evidence are correct before stylizing.
- When relying on images to determine composition, actually view the candidate images before deciding subject placement, crop lines, and text safe areas; do not decide from keywords or imagination alone.
- Once a good enough candidate image has been found or generated, let it truly enter the main composition; do not swap specific people, artifacts, materials, or environments back into generic vector icons, silhouettes, or schematic stand-ins just to save implementation effort.
- When choosing photography or real-object imagery as the primary visual grammar, let key images occupy enough area on the canvas to create a memorable impression; do not shrink all high-quality assets into small circular images inside cards or decorative thumbnails. Multiple images can form an overall relationship through cropping, overlapping, matrixing, sequencing, or local zoom.
- When choosing custom vectors as the primary visual grammar, let contours, proportions, connections, scale, or annotations express the specific information of the current subject; do not pass off generic icons, default process boxes, or decorative geometry as content. Complex vector figures should likewise have a clear visual focus and a thumbnail memory point.
- When mixing imagery and vectors, define the division of labor clearly: imagery carries object evidence, materials, people, or environments; vectors carry relationships, paths, scale, legends, and annotations — and anchor them to each other within the same composition, rather than splitting into two unrelated blocks above and below.
- Use self-owned, licensed, officially citable, or generated images. Do not forge real magazines, institutions, brand logos, issue numbers, watermarks, or attribution.
- AI images must not pose as historical archives, scientific evidence, or real data. Label them "AI-generated illustration" when necessary.
## Editable Delivery and Verification
- Keep text, shapes, connectors, data labels, and legends as editable PPTD elements as much as possible; do not merge the entire infographic into a single bitmap.
- When the user only wants images such as PNG or JPG, still complete the editable source in PPTD first, then screenshot or render it to an image.
- Check out-of-bounds, overflow, overlap, and structural issues against the pptd format rules; visually review focus, reading order, contrast, font sizes, and image cropping.
- Look at the full-page overview first, then the details: the overview should reveal the subject and at least one visual memory point; if the main impression is a title, regular cards, and button-like color blocks, restructure first instead of only fine-tuning font sizes and spacing.
- After fixing problem pages, validate and review again, and only then package the PPTX or output images.
## Pre-Production Checklist
- Have you explored different directions based on the subject and written a specific, actionable `style.md` in the project?
- Do the canvas ratio and orientation fit the user's requirements, the deployment scenario, the content structure, and the reading order?
- Are the core message, primary visual focus, and dominant visual grammar clear?
- Did you actually compare hero-image or structure-diagram candidates before finalizing, and does the chosen asset/figure truly enter the main composition?
- Is there a poster-level visual move recognizable at thumbnail size, rather than an ordinary content page, card wall, or app interface?
- Do the map, timeline, routes, flowcharts, matrix, and index genuinely express core relationships, rather than serving as decoration or density filler?
- Do the colors, fonts, image treatment, composition, and graphic language come from the current subject, rather than defaulting to reusing the previous poster case?
- Are facts, data, dates, locations, units, captions, sources, and copyright boundaries complete and verifiable?
- Are body text, annotations, and legends readable at the actual output size, without relying on extremely small fonts to cram in information?
- Does the visual result in the screenshot truly match `style.md`, rather than merely passing the syntax check?
File diff suppressed because it is too large Load Diff
+258
View File
@@ -0,0 +1,258 @@
## Parameter Value Conventions
* The `adjustments` parameters are described in the order and quantity defined by OOXML
* Values generally range over [0, 100000], representing a percentage (100000 = 100%)
* Angle parameters are in units of 1/60000 of a degree in OOXML; conversion formula: `OOXML value = degrees × 60000` (for example, `16200000` = 270°)
* The parameter array must remain complete (intermediate values cannot be omitted), or be omitted entirely to use default values
* `-` indicates the shape has no adjustable parameters
---
## Basic Shapes
| shapeName | Description | adjustments parameters | Default values |
| --------- | --- | -------------- | ---- |
| rect | Rectangle | - | - |
| roundRect | Rounded rectangle | [corner radius] | [16667] |
| ellipse | Ellipse | - | - |
| triangle | Triangle | [horizontal position of apex] | [50000] |
| rtTriangle | Right triangle | - | - |
| parallelogram | Parallelogram | [slant offset] | [25000] |
| trapezoid | Trapezoid | [top edge inset] | [25000] |
| nonIsoscelesTrapezoid | Non-isosceles trapezoid | [left offset, right offset] | [25000, 25000] |
| diamond | Diamond | - | - |
| pentagon | Regular pentagon | [horizontal factor, vertical factor] | [105146, 110557] |
| hexagon | Hexagon | [inset offset, vertical factor] | [25000, 115470] |
| heptagon | Heptagon | [horizontal factor, vertical factor] | [102572, 105210] |
| octagon | Octagon | [corner cut size] | [29289] |
| decagon | Decagon | [vertical factor] | [105146] |
| dodecagon | Dodecagon | - | - |
| plus | Plus sign | [arm width ratio] | [25000] |
| homePlate | Five-sided arrow | [arrowhead tip offset] | [50000] |
| chevron | V-shaped arrow | [V tip offset] | [50000] |
| pie | Pie | [start angle°, end angle°] | [0, 16200000] |
| pieWedge | Pie wedge | - | - |
| arc | Arc | [start angle°, end angle°] | [16200000, 0] |
| chord | Chord | [start angle°, end angle°] | [2700000, 16200000] |
| blockArc | Block arc | [start angle°, end angle°, thickness] | [10800000, 0, 25000] |
| teardrop | Teardrop | [tail extension ratio] | [100000] |
| frame | Frame | [border thickness] | [12500] |
| halfFrame | Half frame | [horizontal thickness, vertical thickness] | [33333, 33333] |
| corner | Corner | [horizontal thickness, vertical thickness] | [50000, 50000] |
| diagStripe | Diagonal stripe | [stripe width] | [50000] |
| foldedCorner | Folded corner | - | - |
| donut | Donut | [ring width ratio] | [25000] |
| noSmoking | Prohibition symbol | [slash width] | [18750] |
| heart | Heart | - | - |
| lightningBolt | Lightning bolt | - | - |
| sun | Sun | [inner radius ratio of rays] | [25000] |
| moon | Moon | [crescent width] | [50000] |
| cloud | Cloud | - | - |
| smileyFace | Smiley face | [mouth curvature] | [4653] |
| bevel | Bevel | [bevel width] | [12500] |
| can | Cylinder | [elliptical lid height] | [25000] |
| cube | Cube | [perspective depth] | [25000] |
| funnel | Funnel | - | - |
| gear6 | Six-tooth gear | [tooth height, tooth width] | [15000, 3526] |
| gear9 | Nine-tooth gear | [tooth height, tooth width] | [10000, 1763] |
| plaque | Plaque | [corner radius] | [16667] |
| doubleWave | Double wave | [wave amplitude, horizontal offset] | [6250, 0] |
| wave | Wave | [wave amplitude, horizontal offset] | [12500, 0] |
| lineInv | Inverse line | - | - |
## Rectangle Variants
| shapeName | Description | adjustments parameters | Default values |
| --------- | --- | -------------- | ---- |
| round1Rect | Single-rounded-corner rectangle | [corner radius] | [16667] |
| round2DiagRect | Rectangle with two diagonally rounded corners | [corner 1 radius, corner 2 radius] | [16667, 0] |
| round2SameRect | Rectangle with two same-side rounded corners | [top corner radius, bottom corner radius] | [16667, 0] |
| snip1Rect | Single-cut-corner rectangle | [corner cut size] | [16667] |
| snip2DiagRect | Rectangle with two diagonally cut corners | [corner 1 cut size, corner 2 cut size] | [0, 16667] |
| snip2SameRect | Rectangle with two same-side cut corners | [top cut size, bottom cut size] | [16667, 0] |
| snipRoundRect | Rectangle with one rounded and one cut corner | [corner radius, corner cut size] | [16667, 16667] |
## Stars and Bursts
| shapeName | Description | adjustments parameters | Default values |
| --------- | --- | -------------- | ---- |
| star4 | 4-point star | [inner radius ratio] | [12500] |
| star5 | 5-point star | [inner radius ratio, horizontal factor, vertical factor] | [19098, 105146, 110557] |
| star6 | 6-point star | [inner radius ratio, horizontal factor] | [28868, 115470] |
| star7 | 7-point star | [inner radius ratio, horizontal factor, vertical factor] | [34601, 102572, 105210] |
| star8 | 8-point star | [inner radius ratio] | [37500] |
| star10 | 10-point star | [inner radius ratio, horizontal factor] | [42533, 105146] |
| star12 | 12-point star | [inner radius ratio] | [37500] |
| star16 | 16-point star | [inner radius ratio] | [37500] |
| star24 | 24-point star | [inner radius ratio] | [37500] |
| star32 | 32-point star | [inner radius ratio] | [37500] |
| irregularSeal1 | Burst 1 | - | - |
| irregularSeal2 | Burst 2 | - | - |
## Arrow Shapes
| shapeName | Description | adjustments parameters | Default values |
| --------- | --- | -------------- | ---- |
| rightArrow | Right arrow | [shaft width, arrowhead length] | [50000, 50000] |
| leftArrow | Left arrow | [shaft width, arrowhead length] | [50000, 50000] |
| upArrow | Up arrow | [shaft width, arrowhead length] | [50000, 50000] |
| downArrow | Down arrow | [shaft width, arrowhead length] | [50000, 50000] |
| leftRightArrow | Left-right arrow | [shaft width, arrowhead length] | [50000, 50000] |
| upDownArrow | Up-down arrow | [shaft width, up arrowhead length, shaft width, down arrowhead length] | [50000, 50000, 50000, 50000] |
| quadArrow | Quad arrow | [shaft width, arrowhead width, arrowhead length] | [22500, 22500, 22500] |
| leftRightUpArrow | Left-right-up arrow | [shaft width, arrowhead width, arrowhead length] | [25000, 25000, 25000] |
| leftUpArrow | Left-up arrow | [shaft width, arrowhead width, arrowhead length] | [25000, 25000, 25000] |
| bentArrow | Bent arrow | [shaft width, arrowhead width, arrowhead length, bend position] | [25000, 25000, 25000, 43750] |
| bentUpArrow | Bent up arrow | [shaft width, arrowhead width, arrowhead length] | [25000, 25000, 25000] |
| uturnArrow | U-turn arrow | [shaft width, arrowhead width, arrowhead length, bend radius, shaft length] | [25000, 25000, 25000, 43750, 75000] |
| circularArrow | Circular arrow | [arrowhead width, start angle°, end angle°, arc angle°, arrow tip width] | [12500, 1142319, 20457681, 10800000, 12500] |
| leftCircularArrow | Left circular arrow | [arrowhead width, start angle°, end angle°, arc angle°, arrow tip width] | [12500, -1142319, 1142319, 10800000, 12500] |
| leftRightCircularArrow | Left-right circular arrow | [arrowhead width, start angle°, end angle°, arc angle°, arrow tip width] | [12500, 1142319, 20457681, 11942319, 12500] |
| curvedRightArrow | Curved right arrow | [arrowhead width, curvature, arrowhead length] | [25000, 50000, 25000] |
| curvedLeftArrow | Curved left arrow | [arrowhead width, curvature, arrowhead length] | [25000, 50000, 25000] |
| curvedUpArrow | Curved up arrow | [arrowhead width, curvature, arrowhead length] | [25000, 50000, 25000] |
| curvedDownArrow | Curved down arrow | [arrowhead width, curvature, arrowhead length] | [25000, 50000, 25000] |
| stripedRightArrow | Striped right arrow | [shaft width, arrowhead length] | [50000, 50000] |
| notchedRightArrow | Notched right arrow | [shaft width, arrowhead length] | [50000, 50000] |
| swooshArrow | Swoosh arrow | [tail width, arrowhead length] | [25000, 16667] |
## Arrow Callouts
| shapeName | Description | adjustments parameters | Default values |
| --------- | --- | -------------- | ---- |
| rightArrowCallout | Right arrow callout | [shaft width, arrowhead width, arrowhead length, box width] | [25000, 25000, 25000, 64977] |
| leftArrowCallout | Left arrow callout | [shaft width, arrowhead width, arrowhead length, box width] | [25000, 25000, 25000, 64977] |
| upArrowCallout | Up arrow callout | [shaft width, arrowhead width, arrowhead length, box height] | [25000, 25000, 25000, 64977] |
| downArrowCallout | Down arrow callout | [shaft width, arrowhead width, arrowhead length, box height] | [25000, 25000, 25000, 64977] |
| leftRightArrowCallout | Left-right arrow callout | [shaft width, arrowhead width, arrowhead length, box width] | [25000, 25000, 25000, 48123] |
| upDownArrowCallout | Up-down arrow callout | [shaft width, arrowhead width, arrowhead length, box height] | [25000, 25000, 25000, 48123] |
| quadArrowCallout | Quad arrow callout | [shaft width, arrowhead width, arrowhead length, box size] | [18515, 18515, 18515, 48123] |
## Callouts
| shapeName | Description | adjustments parameters | Default values |
| --------- | --- | -------------- | ---- |
| wedgeRectCallout | Rectangle callout | [tip X offset, tip Y offset] | [-20833, 62500] |
| wedgeRoundRectCallout | Rounded rectangle callout | [tip X offset, tip Y offset, corner radius] | [-20833, 62500, 16667] |
| wedgeEllipseCallout | Ellipse callout | [tip X offset, tip Y offset] | [-20833, 62500] |
| cloudCallout | Cloud callout | [tip X offset, tip Y offset] | [-20833, 62500] |
| borderCallout1 | Line callout 1 | [callout line Y1, X1, Y2, X2] | [18750, -8333, 112500, -38333] |
| borderCallout2 | Line callout 2 | [line Y1, X1, knee point Y, X, end point Y, X] | [18750, -8333, 18750, -16667, 112500, -46667] |
| borderCallout3 | Line callout 3 | [line Y1, X1, knee point 1 Y, X, knee point 2 Y, X, end point Y, X] | [18750, -8333, 18750, -16667, 100000, -16667, 112963, -8333] |
| accentCallout1 | Accent line callout 1 | Same as borderCallout1 | [18750, -8333, 112500, -38333] |
| accentCallout2 | Accent line callout 2 | Same as borderCallout2 | [18750, -8333, 18750, -16667, 112500, -46667] |
| accentCallout3 | Accent line callout 3 | Same as borderCallout3 | [18750, -8333, 18750, -16667, 100000, -16667, 112963, -8333] |
| accentBorderCallout1 | Bordered accent line callout 1 | Same as borderCallout1 | [18750, -8333, 112500, -38333] |
| accentBorderCallout2 | Bordered accent line callout 2 | Same as borderCallout2 | [18750, -8333, 18750, -16667, 112500, -46667] |
| accentBorderCallout3 | Bordered accent line callout 3 | Same as borderCallout3 | [18750, -8333, 18750, -16667, 100000, -16667, 112963, -8333] |
| callout1 | Borderless callout 1 | Same as borderCallout1 | [18750, -8333, 112500, -38333] |
| callout2 | Borderless callout 2 | Same as borderCallout2 | [18750, -8333, 18750, -16667, 112500, -46667] |
| callout3 | Borderless callout 3 | Same as borderCallout3 | [18750, -8333, 18750, -16667, 100000, -16667, 112963, -8333] |
> **Callout tip offset note**: The X/Y offset values of callout shapes use the shape center as the origin, in units of a percentage of the shape's width/height. Negative values mean the tip is on the left side/above the shape.
## Brackets and Braces
| shapeName | Description | adjustments parameters | Default values |
| --------- | --- | -------------- | ---- |
| leftBrace | Left brace | [curvature, middle point position] | [8333, 50000] |
| rightBrace | Right brace | [curvature, middle point position] | [8333, 50000] |
| leftBracket | Left bracket | [curvature] | [8333] |
| rightBracket | Right bracket | [curvature] | [8333] |
| bracePair | Brace pair | [curvature] | [8333] |
| bracketPair | Bracket pair | [curvature] | [16667] |
## Ribbons
| shapeName | Description | adjustments parameters | Default values |
| --------- | --- | -------------- | ---- |
| ribbon | Down-curved ribbon | [fold height, ribbon curvature] | [16667, 50000] |
| ribbon2 | Up-curved ribbon | [fold height, ribbon curvature] | [16667, 50000] |
| ellipseRibbon | Curved-surface down ribbon | [curvature, middle height, fold height] | [25000, 50000, 12500] |
| ellipseRibbon2 | Curved-surface up ribbon | [curvature, middle height, fold height] | [25000, 50000, 12500] |
| leftRightRibbon | Left-right ribbon | [fold height, ribbon curvature, fold width] | [50000, 50000, 16667] |
## Scrolls
| shapeName | Description | adjustments parameters | Default values |
| --------- | --- | -------------- | ---- |
| horizontalScroll | Horizontal scroll | [scroll size] | [12500] |
| verticalScroll | Vertical scroll | [scroll size] | [12500] |
## Math Symbols
| shapeName | Description | adjustments parameters | Default values |
| --------- | --- | -------------- | ---- |
| mathPlus | Plus sign | [line thickness] | [23520] |
| mathMinus | Minus sign | [line thickness] | [23520] |
| mathMultiply | Multiplication sign | [line thickness] | [23520] |
| mathDivide | Division sign | [line thickness, dot spacing, dot size] | [23520, 5880, 11760] |
| mathEqual | Equal sign | [line thickness, line spacing] | [23520, 11760] |
| mathNotEqual | Not-equal sign | [line thickness, slash angle°, line spacing] | [23520, 6600000, 11760] |
## Chart Shapes
| shapeName | Description |
| --------- | --- |
| chartPlus | Chart plus |
| chartStar | Chart star |
| chartX | Chart X |
## Tab Shapes
| shapeName | Description |
| --------- | --- |
| cornerTabs | Corner tabs |
| squareTabs | Square tabs |
| plaqueTabs | Plaque tabs |
## Action Buttons
| shapeName | Description |
| --------- | --- |
| actionButtonBackPrevious | Back/Previous button |
| actionButtonBeginning | Beginning button |
| actionButtonBlank | Blank button |
| actionButtonDocument | Document button |
| actionButtonEnd | End button |
| actionButtonForwardNext | Forward/Next button |
| actionButtonHelp | Help button |
| actionButtonHome | Home button |
| actionButtonInformation | Information button |
| actionButtonMovie | Movie button |
| actionButtonReturn | Return button |
| actionButtonSound | Sound button |
## Flowchart Shapes
| shapeName | Description |
| --------- | --- |
| flowChartProcess | Flowchart: Process |
| flowChartAlternateProcess | Flowchart: Alternate process |
| flowChartDecision | Flowchart: Decision |
| flowChartDocument | Flowchart: Document |
| flowChartMultidocument | Flowchart: Multidocument |
| flowChartInputOutput | Flowchart: Data |
| flowChartPredefinedProcess | Flowchart: Predefined process |
| flowChartInternalStorage | Flowchart: Internal storage |
| flowChartManualInput | Flowchart: Manual input |
| flowChartManualOperation | Flowchart: Manual operation |
| flowChartPreparation | Flowchart: Preparation |
| flowChartDelay | Flowchart: Delay |
| flowChartTerminator | Flowchart: Terminator |
| flowChartConnector | Flowchart: Connector |
| flowChartOffpageConnector | Flowchart: Off-page connector |
| flowChartPunchedCard | Flowchart: Punched card |
| flowChartPunchedTape | Flowchart: Punched tape |
| flowChartCollate | Flowchart: Collate |
| flowChartSort | Flowchart: Sort |
| flowChartExtract | Flowchart: Extract |
| flowChartMerge | Flowchart: Merge |
| flowChartOr | Flowchart: Or |
| flowChartSummingJunction | Flowchart: Summing junction |
| flowChartOnlineStorage | Flowchart: Online storage |
| flowChartMagneticDisk | Flowchart: Magnetic disk |
| flowChartMagneticDrum | Flowchart: Magnetic drum |
| flowChartMagneticTape | Flowchart: Magnetic tape |
| flowChartOfflineStorage | Flowchart: Offline storage |
| flowChartDisplay | Flowchart: Display |
@@ -0,0 +1,34 @@
# PPT category guide
1. **Follow the general rules**: the general rules apply to all scenarios and all pages, and take effect together with the style guidance documents
2. **Determine the scenario**: choose the matching scenario based on the user's input
3. **Read the scenario document**: read the document for that scenario and design according to its expressive focus and approach
## step1. General rules
### Requirements
1. **Every page has a clear reader task**: what this page should make the reader understand, believe, decide, or do — think this through before designing.
2. **Paging has rhythm**: decide for yourself whether a table of contents or section dividers are needed; the reader should feel a change of rhythm as they flip through — some pages are taken in at a glance, others are worth stopping to read carefully.
3. **Use charts and shape combinations flexibly**: if a body of information can be expressed through a complex chart that goes beyond what the current chart syntax can express, you are encouraged to flexibly use shapes and other means to construct the expression.
4. **Master-level output**: every PPT is a carefully crafted work of art that could be entered into a competition; pay close attention to every detail of layout, typography, and color — details determine success or failure.
5. **Use image search/generation sensibly**: use image search/generation tools to obtain images and place them in suitable positions. But image abuse is strictly forbidden. If the user's uploaded files contain useful images, use them on suitable pages.
6. **Defer to the user and the subject**: user-specified templates, brand guidelines, color schemes, fonts, and style references take priority over this guide.
7. **Source attribution**: pages involving external facts and data must state the source, date or time period, and measurement basis. Source text should use an <a href="url"> hyperlink pointing to the original report or data page. When citing specific sources in footnotes, likewise use <a href="url"> hyperlinks to the original source to strengthen professional credibility.
### Strictly forbidden
- **Evidence boundaries**: do not fabricate data, citations, customer cases, experimental results, or sources; when material is missing, clearly mark it as a placeholder, an assumption, or to-be-supplied information.
- **Classic AI patterns**: it is strictly forbidden to use cards to build hierarchy or alignment (rounded rectangles, rectangular cards, cards with a colored side strip): lines, whitespace, and font-size contrast are better solutions; it is strictly forbidden to use the AI color scheme where red, purple, yellow, and green are all gathered on one page;
## step2. Scenario determination
Based on the user's input, analyze the presentation's audience and reader tasks, determine the scenario it belongs to, and read the corresponding style document.
> Choose one primary scenario. When truly necessary, you may add one auxiliary scenario, but the primary scenario must prevail.
| Scenario type | Typical queries | Reader task | Style document |
|---|---|---|---|
| Analysis & decision | Consulting, finance, industry research, strategy, market opportunities, business analysis, investment analysis | Compare options, form judgments, support decisions | `reference/slides_categories/analysis-decision.md` |
| Business proposal | Marketing plans, sales proposals, fundraising pitches, partnership/investment promotion, product proposals, business plans | Understand the value, believe in the plan, take action | `reference/slides_categories/business-plan.md` |
| Management reporting | Work reports, project retrospectives, quarterly summaries, OKR, management briefings | Grasp the current state, surface problems, confirm actions | `reference/slides_categories/management-report.md` |
| Academic research | Graduate research projects, thesis defenses, research projects, proposal reports, mid-term reports, final/concluding reports | Evaluate the problem, method, evidence, and contribution | `reference/slides_categories/academic-research.md` |
| Education & training / knowledge popularization | K-12 courseware, teaching demonstrations, vocational training, patient education, professional popular science | Understand, remember, apply, or act correctly | `reference/slides_categories/education-training.md` |
| Tech & engineering | Engineering plans, architecture reviews, R&D reports, AI / data / ops / security | See the structure, dependencies, metrics, and trade-offs clearly | `reference/slides_categories/tech-engineering.md` |
| Brand / creative showcase | Brand stories, design proposals, portfolios, cultural events | Build perception, leave a memory, form identification | `reference/slides_categories/brand-creative.md` |
@@ -0,0 +1,135 @@
# Academic Research
**Benchmark references**: presentation templates from universities such as MIT, ETH Zürich, Tsinghua University, and Peking University; LaTeX Beamer themes such as Metropolis, Focus, Blei, and Auriga; research figure plates from journals such as Nature, Science, Cell, and NEJM; and presentations at top academic conferences.
## Goals
### Narrative: capture the value in the first minute; keep progress visible at all times
Follow the narrative logic of research background, evidence gap, research question, experimental hypotheses, core evidence, conclusion, and contribution — letting the committee/advisor grasp the value within the first minute.
Through proper section planning, adding transition pages at key positions, building navigation bars into the body skeleton, and similar methods, keep the committee/advisor aware of the presentation's progress at all times.
### Visuals: simple but not cheap
Presentations in academic scenarios are often plain, but simplicity does not mean simplistic, much less cheap. Use appropriate, refined colors that are expected in spirit yet unexpected in choice, paired with meticulous layouts to build a premium feel.
1. **Keep a minimal style**: decorative elements and decorative images may only be used in areas such as the cover, section transition pages, closing pages, and page background images; strictly forbid using decorative images to fill body areas. Icons are not a cure-all for filling whitespace either — use them only when adding an icon brings a clear benefit.
2. **A premium feel is achieved through meticulous detail design**: a unified page skeleton, footnote markers for data sources and references, captions for figures and tables, proper page numbering, exquisitely designed font-size hierarchy and typefaces...
3. **Colors expected in spirit, unexpected in choice**:
- When the user precisely mentions a school/institution/organization/conference name/journal name, you may download the official logo, use the logo's primary color as the primary color, and insert the logo at reasonable positions. If you cannot obtain the logo, do not use the logo's primary color, to avoid deviation.
- Reject the most common palettes of this scenario:
* Medical research does not use hospital blue/medical green; turn instead to the hematoxylin purple #684765 and eosin pink #C9828B of pathology slides.
* Climate and earth sciences do not use environmental green and ocean blue; adopt rock-strata gray #334047, mineral ochre #B66A3C, and sulfur yellow #C2A33A instead.
- Unless the user explicitly requests it, do not use crude, simplistic black, white, or light-blue backgrounds; align toward more refined backgrounds, such as titanium gray #E7E8E5, archival paper #F1E9DA, or ivory paper #F7F3E8.
4. **High density at large font sizes**
- Academic presentations should maintain high density at appropriate font sizes while retaining some breathing room. Unlike the small font sizes and single line spacing of industry research and finance, academic-research body text should use larger font sizes (above 10) and suitable line spacing (around 1.2), unless the deliverable is a reading-type artifact such as an academic poster. At the same time, it should have the "fullness" of industry research and finance: leave some breathing room between regions, but keep the inside of each region full.
- Strictly forbid a region planned for 100px that ends up holding only 70px of content.
### Start from the research field; consider the visual focus
Academic presentations in different research fields have different emphases: think about what truly matters in that field, and decide what each page should focus on.
- Basic research and theoretical derivation: formulas, definitions, propositions, and proof steps are the focus; the rigorous, complete reasoning process occupies large areas.
- Computer science and engineering: system diagrams, code, run traces, ablation experiments, and performance curves form the page skeleton.
- Experimental research: research charts, images, and tables are the focus. Formulas, charts, tables, and images belonging to the same research conclusion should be as compact as possible.
- Empirical analysis: essentially also experimental research, but social-science work should be more narrative-driven than science-and-engineering work.
- Humanities/architecture/arts: archives, maps, manuscripts, image details, chronological threads, and textual evidence... Beyond academic rigor, there should also be brand-level refinement — go read `brand-creative.md` again.
- Use shapes, lines, and arrows as annotations to emphasize or explain chart and image content.
## Prohibitions
1. **No cards by default**: unless the user explicitly requests it, strictly forbid using rounded rectangles or rectangular cards to build hierarchy or alignment: line segments, whitespace, and font/size differences are better solutions.
2. **No evenly divided compositions**: unless no other layout is available, do not default to one-third splits, four-way splits, or 2×2 matrices — including three-part formulas such as "three columns + title + conclusion."
3. **No mediocre, common, or AI-typical color schemes**: strictly forbid any blue-and-white pairing, blue-purple gradients, cyan-purple neon, rainbow flares, glassmorphism cards, or glowing borders — unless the user explicitly requests them.
4. **No overly small font sizes**: unless the user requests it or the deliverable is a reading-type artifact (posters, etc.), body text must not use small font sizes.
5. **No whitespace inside regions**: strictly forbid any case where the content cannot fill its planned region. It is not enough for the text box to be full — the actual text content, as seen in a screenshot, must fill the region. Failure to fill is the most serious kind of crudeness; it feels like no care went into the layout at all.
## Visual References
### ETH Swiss Lab Posters
**Reference objects**: ETH Zürich official PowerPoint and LaTeX templates, Metropolis.
**Core visual**: like a set of Swiss research posters pinned to a lab wall. A strict grid, giant conclusions, large solid-color swatches, and full-bleed research images form strong proportions; the pages are quiet but not conservative.
**Type and grid**:
- Use a neutral sans-serif typeface; cover titles 6488 pt, page titles 3648 pt, body text 1619 pt, sources 911 pt.
- Use clearly asymmetric proportions, commonly 3:9, 4:8, or a full-page main image.
**Research figures**:
- The main figure occupies 60%75% of the page, with axes, error bars, legend, and source fully preserved.
- Photography, micrographs, and remote-sensing images may be laid out full-bleed; titles sit inside opaque color blocks rather than directly over complex imagery.
- Highlight only one result per page.
**Page grammar**:
1. Cover: a full-bleed image of the research setting or subject, paired with solid swatches of the primary color to build an asymmetric character.
2. Content pages: the flow advances horizontally along a twelve-column grid; **cards are strictly forbidden**.
3. Results pages: giant conclusion on the left, complete main figure on the right; on the next page, swap left and right.
4. Limitations page: a thick colored line cuts apart "proven" and "not yet certain."
5. Closing page: return to the cover's color-swatch proportions and answer the research questions one by one.
**Recurring motif**: asymmetric solid-color swatches, section numbers, page numbers, notes, reference footnote markers, and thin tick lines along the page edges.
**Prohibitions**: rounded cards, centered titles, soft shadows, blue-and-white business style, multi-colored charts, and enlarging the institution's emblem into a giant watermark.
### Tsinghua / MIT-Style Elite-University Defense
**Reference objects**: the official visual identity systems of Tsinghua University, MIT, and similar institutions; department defense templates; course handouts and research reports.
**Core visual**: the whole deck carries the orderliness of formal departmental defense materials. Identity is established through the school color, school name, or department emblem; everything else recedes behind the content. Pages are stable, precise, restrained; formulas, figures, and arguments always hold the visual center.
**Palette**:
- When the user explicitly mentions a school or institution, extract one primary color from the official emblem — never hard-code a color value from memory. On ordinary body pages, keep the school color within 3%8% of the area; section pages may use the school color across the entire page.
- Keep scientific color schemes on figures when they carry clear semantics; when they do not, use the school color, light and dark grays, and one necessary contrast color — do not add colors just to enrich the picture.
**Type and grid**:
- Chinese uses a neutral hei (sans-serif) typeface; English and formulas may pair with an academic serif or math typeface. Cover titles 4864 pt, page titles 3240 pt, body text 1721 pt, captions and sources 911 pt.
- Titles, body text, figure captions, and footnotes each keep their own fixed baselines.
- Body pages may set an extremely thin header or footer rule, with a short title, section name, and page number fixed in place — or a section navigation.
**Research content**:
- Formulas keep their numbering, conditions, and symbol explanations; key derivations may appear step by step, but each page must form a complete local argument.
- Tables preferably adopt the three-line table structure from papers, highlighting only the rows and columns directly relevant to the conclusion.
**Page grammar**:
1. Cover: small school or department emblem, title, author, advisor, department, and date; establish identity with a thin line in the school color — no giant watermarks.
2. Section pages: a full page of school color or a refined background color, holding only the section number, the title, and one research question. Pair with a decorative subtle-pattern background image to enrich the visual effect.
3. Summary page: answer item by item by research question, marking the corresponding evidence or section number after each item.
4. References page: use a font size slightly smaller than body text but larger than footnotes, and place the references in the official citation format, in columns or a single column.
5. Closing page: keep the school color, department emblem, and contact information, presenting only "Questions" or one final conclusion.
**Recurring motif**: the short school-color line, fixed title baseline, section name, page numbers, figure captions, and reference footnote markers.
**Prohibitions**: faking the school color from memory, enlarging the emblem to fill whitespace, semi-transparent emblem watermarks, blue gradient headers, repeating large color bands on every page, rounded info cards, figures without captions, and squeezing body text and figures for the sake of tradition.
### Humanities & Social Sciences Archival Special Issue
**Reference objects**: humanities and social-science academic monographs from university presses, twentieth-century academic journals, archival catalogues, and the vintage-print paper, layout, and image treatments in `brand-creative.md`. Absorb only the parts that serve the presentation of evidence.
**Core visual**: the whole deck reads like an archival research special issue typeset with contemporary layout. Warm paper tones, serif type, marginal annotations, document numbers, and thin separator lines form a stable skeleton; archives, maps, manuscripts, interviews, and statistical materials appear as evidence, not as decoration filling the picture.
**Palette**:
- Background: archival paper #F1E9DA; text: ink black #27231F; auxiliary information: old-paper gray #9B9489.
- Choose one accent color by theme: annotation vermilion #8C3B36 or binding ink green #355C52. Pick only one for the whole presentation, and keep it within 3%8% of the area on ordinary pages.
- Original archives and artworks may keep their original colors; figures, annotations, and navigation still obey the unified palette.
**Type and grid**:
- Chinese titles and body text preferably use a modern Song (serif) typeface or another clear serif; numbers, numbering, sources, and archival reference numbers may use sans-serif or monospaced fonts.
- Cover titles 4868 pt, page titles 3444 pt, body text 1720 pt, long quotations 2128 pt, figure notes and footnotes 911 pt; body line spacing 1.31.45.
- Commonly use unequal-width layouts of 4:8 or 5:7, reserving a narrow margin for dates, keywords, document numbers, or annotations. Rely on whitespace and thin lines to organize content — no vintage lace borders and no cards.
**Archives, quotations, and data**:
- Archive scans should preserve paper edges, page numbers, seals, and collection or accession numbers; when emphasis is needed, point out the evidence with thin boxes, leader lines, and magnified details.
- Label every archival image with author, title, date, holding institution, and reference number; label every interview excerpt with respondent number, time, and place.
- Statistical charts stay modern and clearly drawn, with no aged textures overlaid. Use the accent color only to highlight data series directly relevant to the argument.
- Long quotations excerpt only the passages that support the argument, with explanation and provenance beside them; avoid piling full-page stacks of original text.
**Page grammar**:
1. Cover: the title styled like the title page of an academic monograph, paired with an archive, map, or artwork detail occupying 35%50% of the picture; also place author, institution, date, and volume/issue-style metadata.
2. Research-question page: use a three-to-five-line abstract-style lead-in, with locations, dates, subjects, and material scope listed in the margin.
3. Literature-review page: organize the literature along time or divergences of opinion, connecting scholars, arguments, and response or engagement relationships with thin lines — do not build walls of author cards.
4. Archival-evidence page: a large original on the left; transcription, translation, interpretation, and provenance in order on the right; use the same numbers to connect original and analysis.
5. Empirical-analysis page: the main figure or table occupies two-thirds; the other side holds conclusions, variable descriptions, and limitations; quantitative material also follows the special-issue skeleton.
6. Map-and-time page: use one main map or one main timeline; the accent color marks only the places and events relevant to the argument.
7. Argument page: a clear judgment sentence at the top, with textual evidence, visual evidence, and the researcher's interpretation laid out in order below.
8. Conclusion page: answer the research questions with consecutively numbered short paragraphs, each attaching the corresponding archive number, figure number, or section number.
**Recurring motif**: book-page-style page numbers, thin footnote rules, running heads, archival reference numbers, section tabs, and a unified figure-caption format.
**Prohibitions**: casually tilted clip art, low-contrast body text, treating archival material as background texture, and historical photos without sources.
@@ -0,0 +1,36 @@
# Analysis & Decision
## Solid, compact content with extremely high-density layout
1. Unless the presentation is explicitly intended for on-stage presenting, treat it as a reading-type deck by default. Design the entire work around this goal, and demonstrate the standard of a top-tier research report or consulting firm.
2. Every page has enough depth: the core conclusion can be grasped quickly, while reading the full page takes 5 minutes.
3. Support cascades from conclusion to evidence: once the title states a judgment, the page should carry several self-standing supporting judgments that connect the conclusion to the evidence, each with one verifiable sentence of support.
4. Body-page titles are preferably declarative sentences ("Europe's electric heavy-truck batteries reach 48 GWh by 2030 — 16x growth in six years under a strong policy push"), but decide whether to use a declarative sentence based on the actual content.
## Make data and structured information the body of the argument
1. Data is the core support of the argument: search thoroughly around the topic to obtain real data, and present it fully through all kinds of charts and tables; the source of every piece of data must be stated — never fabricate data.
2. Charts come complete with axes, units, legends, sources, and measurement basis, so that a chart stands on its own apart from the body text.
3. Mark data inflection points and key values on charts and explain their meaning; accompany each chart with text stating the judgment it proves, the findings visible on it, the implications for the decision, and the source and boundaries.
4. Encourage using SmartArt shape combinations to present information; when structural relationships exist between pieces of content — sequence, comparison, cycle, causality, and so on — prefer making them visible with a structural diagram rather than describing them in text.
5. Encourage drawing and combining shapes to build complex charts and SmartArt, supported by text explanations — plain text alone is too flat.
## Key Requirements
1. Create a top-tier visual experience: every detail of typesetting, fonts, colors, and alignment must be treated with care; accept no defaults — details determine success or failure.
2. Unless explicitly requested, strictly forbid using rounded rectangles or rectangular cards to build hierarchy or alignment: line segments, whitespace, and font/size differences are better solutions.
3. A single basic chart must not occupy half or more of the width; encourage laying out multiple charts or other content on one page.
4. Unless no other layout is available, forbid evenly divided compositions; do not default to one-third splits, four-way splits, or 2×2 matrices — including three-part formulas such as "three columns + title + conclusion."
## Visual References
1. White background + single primary-color skeleton: pure white pages, with only one primary color throughout the deck (e.g., navy, ink green, or another color common in financial-consulting style) carrying the structural skeleton — title emphasis, table headers, navigation highlights, main chart series, and numbered markers — supported by a 23-step light-tint ladder of the same hue and neutral grays.
2. The title is the conclusion: each page's main title is a complete judgment sentence; the heading format (kicker → main title → subtitle, or title + conclusion-sentence subtitle) is fixed throughout; in typography, bold serif titles and sans-serif body text form two clearly divided roles, with a strictly consistent hierarchy.
3. If headers and footers exist, they must stay stable: section navigation always visible (current section highlighted; sections distinguished by navigation position, not by switching colors), a fixed "Source:" line + page number in the footer; every element keeps the same coordinates from page to page, so nothing jumps when flipping.
4. Density rhythm: body pages are packed at high density, with charts/tables/structural diagrams as the main body and text serving the evidence; covers, section pages, and conclusion pages use whitespace as breathing points.
5. Position discipline: conclusion → top title; evidence → charts/tables in the middle; interpretation → notes beside the chart or a sidebar; sources and measurement basis → the source line at the bottom; action recommendations → the closing page only. Every type of information sits in its own place, consistent throughout.
6. De-default charts: reassign all series colors to the primary-color ladder + grays; remove vertical gridlines (at most keep extremely light horizontal lines); data labels mark only key points and endpoints; actual vs. forecast is distinguished by solid vs. dashed/hatched; directly below each chart, place its source + measurement-basis note.
7. Mark key values directly on the chart: key totals with big-number callouts, inflection points/gaps/growth rates with arrows or leader lines + one-sentence annotations, ratings with Harvey balls or badges — placed right on the chart area, not piled into text paragraphs.
8. Table conventions: dark header with white text, extremely thin horizontal separators (no vertical lines or heavy borders), numbers right-aligned and text left-aligned, subject names in the first column bolded; large tables get an interpretation panel beside them.
9. Line and alignment discipline: all elements align to a unified left edge and invisible column lines; separation uses only extremely thin lines, emphasis uses only primary-color short bars or thick vertical bars, never thick frames; panels are square-cornered with no shadows; rounded corners are allowed only on small labels.
10. Clean surfaces: no shadows, no gradients, no textures, no glow effects, no default colors; the texture is achieved entirely through whitespace, alignment, a single-hue color scale, and line discipline.
@@ -0,0 +1,202 @@
# Brand / Creative Showcase
**Benchmark references**: top magazines such as Monocle, Wallpaper, and Vogue; international design agencies such as Pentagram; and outstanding brand annual reports, brand books, and creative proposals.
## Goals
### Identify the subject; build a deck whose subject is recognizable at a glance
If the presentation's subject is a specific brand, product, company, person, city, building, event, or IP, first extract the subject's identifying features:
- Extract visual identifiers such as icons and the brand concept from the user's uploaded reference materials.
- Search and visit official websites, officially published annual reports, creative manuals, and icons. Do not just read the text — rely more on referencing and studying the pages' visual effects to help understand the style.
Even if all text content were removed, the association with the subject should still be found through other visual features.
### Take the essence, discard the dross
Not every subject has an aesthetic aligned with top magazines like Monocle, Wallpaper, or Vogue. When extracting the subject's style, accurately identify which items may be referenced and which are prohibited. Designs that fail to meet the benchmark's standard must be explicitly forbidden. If the brand itself lacks design quality, you may keep only the brand's primary color as the theme or accent color, or keep icons as decoration.
### Build a top-tier visual experience
Use strong font-size contrast and extreme asymmetric layouts to build an exaggerated style and a top-tier visual experience. Reject every safe, mediocre, conservative option: better ugly than mediocre.
1. **Make extreme choices**: oversized type, giant images, intense whitespace, high-density multi-columns, a single vivid color, or heavy lines. Build an ultimate style: old-newspaper front page, Memphis, Constructivism, Swiss style...
2. **Vary the pages**: cover, opinion, data, and image pages each have different compositions. There is no need to strictly follow one identical "page skeleton," but the deck's consistency should still be recognizable through palette, typeface, font sizes, same-style decorative elements, and the same grid alignment.
3. **Have a visual rationale**: the visual language must come from the deck's subject, brand, industry, era, or material, and must help the audience understand the content.
## Prohibitions
1. **No cards by default**: unless the user explicitly requests it, strictly forbid using rounded rectangles or rectangular cards to build hierarchy or alignment: line segments, whitespace, and font/size differences are better solutions.
2. **No evenly divided compositions**: unless no other layout is available, do not default to one-third splits, four-way splits, or 2×2 matrices — including three-part formulas such as "three columns + title + conclusion."
3. **No mediocre, common, or AI-typical color schemes**: strictly forbid any blue-and-white pairing, blue-purple gradients, cyan-purple neon, rainbow flares, glassmorphism cards, or glowing borders — unless the user explicitly requests them.
4. **No elements that clash with the overall style**: no styles from outside the chosen style may appear, such as using rounded icons or rounded rectangles within a sharp style.
## Visual References
Visual references are only "references": they show you something good so you know what good looks like — they are not directly usable. You should design visuals according to the user's actual needs, not directly apply templates.
### Klein Blue Swiss Posters
**Core visual**: the whole deck reads like a set of modernist exhibition posters. Strict left alignment, a twelve-column grid, extreme font-size differences, giant numerals, and large areas of whitespace. The picture uses only paper white, near-black, and Klein blue.
**Palette**:
- Background: warm paper white #F7F5EF, roughly 70%85%.
- Text: near-black #101010.
- Accent: Klein blue #0038B8, occupying 5%12% on ordinary pages; section pages may use a blue block occupying 30%40% of the picture.
- Auxiliary gray: #D8D7D2, only for gridlines and secondary information.
- No gradients and no second accent color.
**Type**:
- Cover title: ultra-heavy sans-serif, 112136 pt, line height 0.850.95, and may be slightly cropped by the canvas edge.
- Content-page titles: 4864 pt.
- Body text: 1720 pt.
- Page numbers, sources, and labels: 911 pt, with widened letter spacing.
- Everything left-aligned, using a single sans-serif family only, building hierarchy through weight changes.
**Grid and geometry**:
- Left and right margins equal 5% of the canvas width; use a twelve-column grid.
- Main compositions use 2:8, 3:7, or full-page whitespace.
- Use only right-angle rectangles, true circles, 0.5 pt thin lines, and 4 pt thick lines.
- No rounded corners, shadows, outlined icons, or floating cards.
**Image treatment**:
- Product screenshots all go into a fixed 16:10 slot.
- Photography is uniformly high-contrast black and white; a blue color surface may only be overlaid locally.
- At most one main image per page; no photo collages.
**Page grammar**:
1. Cover: the title occupies the left 65%; a blue color surface running the full height sits on the right; at the top, only one line of 10 pt meta-information.
2. Section pages: the whole page holds only the section numeral and one title line; the numeral is 120 pt blue.
3. Opinion page: one 6488 pt conclusion, with a tiny annotation in the bottom-right corner.
4. Data page: a 110 pt numeral occupies the left third; a simplified chart sits on the right.
5. Architecture page: all nodes align to the twelve-column grid; connecting lines are uniformly 1 pt; only the core nodes are blue.
6. Closing page: return to the cover's blue color surface and giant title, closing the loop.
**Recurring motif**: a blue vertical line and a two-digit section number fixed at the top-left corner of every page.
**Prohibitions**: rounded cards, three evenly divided columns, colorful small icons, multi-colored charts, gradients, soft shadows, centered titles.
### Stencil-Printed Indie Magazine
**Core visual**: the whole deck feels like a hand-trimmed, scanned, and bound indie magazine. Heavy poster type, two-color overprinting, halftone images, cut-and-paste blocks, and slight tilts. Preserve paper and printing imperfections rather than chasing the slickness of a digital interface.
**Palette**:
- Paper: warm beige #F1E2C2.
- Primary ink: cobalt blue #1646B8.
- Second spot color: fluorescent pink #FF4F87.
- Text and rules: ink black #171512.
- Orange-yellow #F1A51B may appear on only one or two section pages, within 5% of the area.
- No transparent gradients; colors appear only as flats, overprints, and halftones.
**Type**:
- Cover title: ultra-heavy condensed poster type, 88120 pt, allowed to rotate -3 degrees and cross the canvas edge.
- Page titles: 4258 pt, may be reversed white on a black ground.
- Body text: 1417 pt, in a clear sans-serif or serif face.
- Annotations: 1012 pt monospaced, mimicking typewriter labels.
**Grid and geometry**:
- Use unequal-width two and three columns and cut-and-paste modules.
- Images and text blocks may rotate from -4 to +4 degrees.
- Main rules 23 pt; crop marks 0.75 pt.
- Color blocks stay right-angled; local overruns and mutual overlaps are allowed.
**Image treatment**:
- All photos are first converted to high-contrast black and white, then given either a blue or a pink halftone treatment.
- Halftone dot size stays consistent; color misregistration of 24 pixels is allowed.
- People and buildings may be cropped brutally, but never past the point of losing the recognizable subject.
- Never drop full-color photos in directly.
**Page grammar**:
1. Cover: the title occupies more than half the picture; at the bottom, a blue-and-pink duotone photo of a printing press or bookshop; a tilted small label is pasted at the top-right corner.
2. Contents page: five colored paper strips, each holding only a section number and a short title.
3. History page: the timeline looks like tickets clipped onto paper; years use 4056 pt bold type.
4. Craft page: five steps spread horizontally, each containing a halftone image, a number, and one line of explanation.
5. City-case page: one large image occupies 60%; text presses against the image's side like a newspaper sidebar.
6. Map page: the map stays as black line art; key cities are marked with solid pink circles.
7. Closing page: four large numbered circles present the action steps; a black manifesto line sits at the bottom.
**Recurring motif**: misregistered blue-and-pink overprinting, the crop line at the top-left corner, and a fixed volume/issue number.
**Prohibitions**: glassmorphism, soft shadows, slick gradients, refined rounded corners, full-color photography, business clip icons, and perfectly symmetrical grids.
### Brutalist Newspaper
**Core visual**: the whole deck reads like a special-edition newspaper about an industry turning point. Giant mastheads, narrow margins, unequal-width multi-columns, thick-and-thin rules, high-density body text, and black-and-white halftone photos. Red is used only for the most critical data and warnings.
**Palette**:
- Newsprint white: #F5F1E8.
- Ink black: #111111.
- News red: #C8102E, kept within 3%8% of a page's area.
- Sidebar paper yellow: #E7DDCA.
- Secondary text: #55514A.
- No blue-purple gradients and no colored status blocks.
**Type**:
- Masthead: ultra-heavy sans-serif, 72100 pt, all caps where supported or otherwise set as ultra-bold short text.
- Headlines: 4472 pt, tight leading.
- Body text: 1114 pt serif, line spacing 1.251.4.
- Data and labels: monospaced, 1014 pt.
- Pull quotes: 2840 pt serif italic or bold.
**Grid and geometry**:
- Margins are 3.5%4% of the canvas width.
- Content pages use three to five unequal-width columns.
- Lines come in four grades: 0.5 pt, 1 pt, 3 pt, and 5 pt.
- All modules are right-angled, organized by rules; no floating cards.
**Image treatment**:
- Photography is uniformly converted to high-contrast black-and-white halftone, keeping visible grain.
- Every image carries a 910 pt caption and source.
- You may mark an image with a red circle, red underline, or red stamp — choose only one of these mark types per page.
**Page grammar**:
1. Cover: a 5 pt red line at the top, a masthead spanning the full page below it; the main headline uses 8096 pt; three short news briefs at the bottom.
2. Overview page: four large numbers in a row, each 6488 pt, with three columns of observations below.
3. Ranking page: a black-and-white halftone photo in the left third; horizontal bar charts in the right two-thirds.
4. Cost page: a full-width server-room banner across the middle, with a line chart and a narrow annotation column below.
5. Policy page: a black-and-white landscape image at the top; below, a dense three-column table compares different regions.
6. Timeline page: one thick black main line with six red nodes; event descriptions distributed above and below.
7. Closing page: only one 64 pt conclusion and a red full stop.
**Recurring motif**: the top red line, the fixed masthead, black column rules, and edition information at the bottom-right corner.
**Prohibitions**: rounded corners, shadows, illustrated icons, colored cards, loose business layouts, default table styles, and unsourced data.
### Memphis Pop Posters
**Core visual**: the whole deck uses thick black outlines, giant poster type, checkerboards, lightning bolts, waves, dots, and geometric shapes that break the frame. The picture is lively while text areas stay clean — like a blend of eighties pop posters and contemporary youth-event visuals.
**Palette**:
- Background: cream white #FFF3D8.
- Ink: deep black-purple #151427.
- Fluorescent pink #FF3EA5.
- Bright yellow #FFD63D.
- Lake blue #05C7E8.
- Mint green #23D6A2.
- At most three high-saturation colors per page; deep black-purple must be used for outlines and body text to steady the picture.
**Type**:
- Cover title: ultra-heavy rounded or comic-style display type, 92128 pt, with a 35 pt dark outline and a hard-offset color block.
- Section words: 80110 pt, all caps where supported or a single giant character.
- Page titles: 3648 pt.
- Body text: 1518 pt neutral sans-serif; no script faces.
- Numbers: 72100 pt, in heavy black type.
**Grid and geometry**:
- Compositions are clearly asymmetric; main objects may rotate from -6 to +6 degrees.
- Geometric shapes use 35 pt dark outlines.
- Each page carries one geometric shape breaking the frame, occupying 20%40% of the picture.
- Decoration concentrates in corners and edges, never covering body text.
**Image treatment**:
- People are uniformly rendered as flat illustrations with thick black outlines or a high-saturation screen-print effect.
- Multi-person pages use a four-panel series, with busts of consistent size and viewing angle.
- Venue maps use hand-drawn icons, but route and schedule information stays clear.
**Page grammar**:
1. Cover: the title fills the upper half; crowd silhouettes and the stage sit at the bottom; checkerboards, lightning bolts, and dots occupy the four corners, while the center stays clear.
2. Section pages: one giant word or character, against a background of one frame-breaking circle and one wave.
3. Numbers page: four numbers in a row, each on a different background color, all with the same thick outline.
4. Lineup page: a four-person panel series in the upper half; names, styles, and set times in the lower half.
5. Venue map: a radial map in the center, with colored labels around it marking stages and facilities.
6. Schedule page: the timeline stays horizontal and regular, colors distinguish the stages, and decoration retreats to the edges.
7. Ticket-pricing page: three tiers as hard-edged poster blocks, prices 6480 pt, no floating shadows.
8. Closing page: a full-bleed sunset illustration with an 88 pt handwritten-feel line on top, repeating the cover's checkerboard corners.
**Recurring motif**: checkerboard at the top-right corner, pink lightning bolts, and thick black outlines — the checkerboard must appear on at least five pages.
**Prohibitions**: soft shadows, low-contrast text, all colors appearing at once, script body text, decoration covering data, and ordinary business icons.
@@ -0,0 +1,49 @@
# Business Proposal
## A clear storyline with strong persuasion
- The storyline of the whole deck is clear and builds step by step.
- If a page has a core claim, that most important sentence enjoys the visual privilege of being "marked."
- **Emotion has a curve**: the deck's emotion is not flat — from unease (the pain point) to hope (the solution) to belief (the evidence) to urge (the action).
- Make good use of data support: assist the proposal with data, tables, and charts at the right positions. Data must be truthful and reliable, with sources stated.
## Tell a more complete story through SmartArt structural diagrams
**SmartArt is the visualization of narrative: boldly use complex structural diagrams to present multi-layered relationships.**
- Decompose structures from information relationships — sequence, comparison, cycle, causality, and so on — and prefer making them visible with structural diagrams rather than describing them in text.
## Page turns have breathing room
- Encourage interspersing refined section pages and accent pages among the content pages to markedly elevate the reader's experience. Section pages may use images as backgrounds, covered by a gradient overlay.
- When the topic suits it, search for images generously and place well-chosen images at the right spots — one picture is worth a thousand words.
## Key Requirements
1. Create a top-tier visual experience: treat every detail of typesetting, fonts, and colors with care, crafting it like a work of art — details determine success or failure.
2. Unless the user explicitly requests it, **strictly forbid using rounded rectangles or rectangular cards** to build hierarchy or alignment: line segments, whitespace, and font/size differences are better solutions.
3. Unless no other layout is available, forbid evenly divided compositions; do not default to one-third splits, four-way splits, or 2×2 matrices — including three-part formulas such as "three columns + title + conclusion."
## Visual References
1. Type is attitude: display type (titles, manifesto lines, big numbers) and body type (body text, notes, sources) have a clear division of labor by family or weight; display type needs poster-level tension, daring extreme contrast in size, weight, and letter spacing — the title itself is a visual work.
2. Fonts and the color scheme must be matched and harmonious; reference each other when designing.
3. Rhythm and accent pages: rotate the page-type sequence, never two consecutive pages with the same skeleton; manifesto pages, section divider pages, and big-number hero pages handle emotional gear-shifts and visual emphasis.
4. Carefully designed layouts: page layouts are ingeniously designed, with beauty and soul — not just simple arrangements of text.
5. Corner and edge visuals: encourage building shapes into images that aid explanation, or crafting refined, purely decorative symbols out of shapes in empty areas.
6. De-default charts and tables: all series colors come from the brand palette; data labels mark only key points and sit directly beside the graphic; tables are separated only by thin horizontal lines — no heavy frames, no zebra striping.
7. Details are quality: pixel-level alignment and letter spacing that hold up under scrutiny at any magnification; the texture is achieved entirely through typesetting, alignment, color blocks, and line discipline — no defaults anywhere; detail is the dividing line between master and mediocrity.
8. Motifs and text/image separation: establish 25 recurring visual motifs throughout the deck (decorations, icons, and illustrations share one language) to form recognizability and an artistic signature.
### Color Palette Reference
**Colors expected in spirit, unexpected in choice**:
- When the user precisely mentions a company/product/brand name, prefer taking the brand's VI primary color as the structural primary color, and design a matching palette around it.
- Reject the most common, most mediocre formulaic palettes of each scenario (tech blue-purple gradients, hospital blue-and-white, festive bright-red-and-gold, real-estate sales-office gold-brown, green-leaf environmental style, etc.); reference palettes for some scenarios:
* Tech/AI/SaaS/entertainment roadshows: the launch-event color clash of ink black #141414 base + fluorescent yellow-green #C6F24E; or mist white #F2F4F7 base + indigo #2B3A8E + lime #A8E05F; or a dark-base clash of deep purple-black #1A1228 base + neon magenta #E91E8C + electric blue #2D9CDB.
* Consumer goods/F&B/food franchise recruitment: creamy apricot #F3D9A4 base + baking brown #6B4226 + brick red #A63A2E; or off-white #F6EFE2 base + ink green #1E3B33 + terracotta #C15F3C; or soil brown #4E3428 base + wheat gold #C9A227 + moss green #5D6B4F.
* Luxury/fashion/beauty: the editorial palette of ink black #0D0D0D base + ivory #F5F0E6 + burgundy #6D1F2C; or ivory #F5F0E6 base + ink black #0D0D0D + burgundy #6D1F2C; or the minimalist clash of cool white #F8F8F6 base + charcoal black #1A1A1A + cobalt blue #1F3A93.
* Medical/health products: warm white #F5F0E1 base + deep pine green #1F4A3D + apricot yellow #E8B54A; or warm white #F7F5F0 base + deep indigo #1B2A52 + mint #7FC7B5; or charcoal gray #333A42 base + coral pink #E8A09A + light beige #EFE9E0.
* Finance/legal/professional services: off-white #F7F3E8 base + ink green #123B2F + brass #B08D3E; or warm gray #C9C4BC base + ink black #1A1A2E + burgundy #7B2D43; or ink black #1C1C1C base + antique bronze #9C6B30 + parchment white #F4EDE1.
* Industry/construction/energy/logistics (heavy B2B industries): charcoal black #232323 base + safety orange #E8590C + steel gray #868E96; or sandy white #F3EDE0 base + deep petroleum teal #0F4C5C + warm copper #B5651D; or light gray #D9DDE3 base + midnight blue #101D42 + signal yellow #F5B700.
* Education/knowledge-payment products: warm white #FAF6EE base + ink purple #3D2C4F + cream yellow #F2C14E; or off-white #F5F1EA base + deep indigo #22315C + coral orange #F08A5D; or paper white #F7F3E8 base + pine green #2F5233 + apricot yellow #E8B54A.
- Align background colors toward something more textured, e.g.: ink black #141414, deep ink green #0E2A22, warm paper white #F7F3E8, mist gray #E9E7E2, deep wine red #3B1219.
@@ -0,0 +1,255 @@
# Education & Training
Scope: courseware, job-skill training, operation guides, teacher materials, study handbooks, public education, onboarding training, capability building, and knowledge popularization. The reader may be listening live or reading independently; their task is not merely to understand a page, but to form understanding they can retell, methods they can execute, and actions they can transfer.
> Core position: design the learning first, the pages second; complete the content skeleton first, the visual system second. Reference samples only provide design cues worth borrowing — they are not default templates, nor styles that must be replicated. Courseware should carry enough content to support learning; do not turn body content into posters or whitespace albums for the sake of a "premium feel."
## 1. Define the Learning Task First; Do Not Pick a Style First
Before production, write down the following information; if any of it is missing, fill it in with reasonable assumptions and mark it in the design document.
- **Learner:** age, level of expertise, prior knowledge, easily confused terms, accessibility needs.
- **Usage:** live projection, printed handouts, self-study reading, or mixed use; roughly how long each page stays in view.
- **Entry state:** what the learner does not know now, cannot do now, or is prone to getting wrong at which step.
- **Exit capability:** after the material, what the learner can explain, differentiate, judge, operate, check, or retell. Goals must be observable.
- **Material boundaries:** which parts are external facts, and which are team inferences, fictional exercises, illustrative data, or to-be-filled material.
- **Real task:** in what work, classroom, or life scenario the learner will next apply this method.
Do not first decide "use blue, use rounded corners, use some Sample" and then cram content into the pages. Every visual choice must be explainable as: it helped the learner see which relationship, remember which step, or complete which judgment.
## 2. General Prohibitions
The following are red lines running through the entire deck; they take effect before all layout and visual rules, and unless the user explicitly requests otherwise, none may be violated.
- **No cards by default:** unless the user explicitly requests it, strictly forbid using rounded rectangles or rectangular cards to build hierarchy or alignment. Line segments, whitespace, and font-size/weight differences are better solutions.
- **No evenly divided compositions:** unless no other layout is available, do not default to one-third splits, four-way splits, or 2×2 matrices — including formulaic patterns such as "title + three parallel blocks + conclusion."
- **No mediocre, common, or AI-typical color schemes:** unless the user explicitly requests them, strictly forbid blue-and-white pairings, blue-purple gradients, cyan-purple neon, rainbow flares, glassmorphism cards, and glowing borders.
- **No elements that clash with the overall style:** no styles from outside the chosen style may appear, such as using rounded icons or rounded rectangles within a sharp style.
## 3. The Teaching Loop: Every Chapter and Every Page Needs a Take-Away Action
The default learning path is: **orientation → comprehension → demonstration → practice → feedback → transfer**. Not every short material needs a separate page for each stage, but when a stage is missing, you must be able to say that the task itself does not call for it — not that the page ran out of space.
- **Orientation:** explain why this is worth learning, what the learner can do after completing it, and how it relates to the chapters before and after. Use a real problem or scenario instead of grand slogans.
- **Comprehension:** first give one core definition the learner can retell, then the boundaries, composition, counterexamples, or relationships. New terms must not appear only in figure captions.
- **Demonstration:** show the process and the intermediate judgments, not just the final answer; put the key forks, the basis for each choice, and the common misconceptions on the same reading path.
- **Practice:** specify the input, the actions, and the completion criteria. Practice scenarios may be fictional, but must be labeled "practice scenario / illustrative material."
- **Feedback:** explain why an answer is right or wrong, where the error lies, and how to check next time. Answer pages and question pages must be distinguishable at a glance.
- **Transfer:** connect to real use with checklists, templates, job-aid cards, or next-step actions; do not substitute a slogan for transfer.
Each page carries only one primary learning action:
- Concept pages get the learner to state clearly "what it is and where its boundaries lie."
- Method pages get the learner to know "when to use it and how to choose."
- Process pages get the learner to know "what to do first, what next, and how to check."
- Demonstration / case pages let the learner see the judgment process.
- Practice pages get the learner to act or make a choice.
- Feedback / review pages correct and distill principles.
Titles must foretell the page's takeaway. Prefer question sentences, conclusion sentences, or "action + object"; avoid mere section labels like "Background," "Overview," or "Related content." Put all key definitions, steps, and answer criteria into the material — do not rely on the presenter to fill them in live.
## 4. Default Density for Courseware: Full Content; Whitespace Has a Job
Courseware is not a poster, nor a full script shrunk down and plastered across pages. The default density is "medium, leaning full": the learner can spot the main object at a glance, and can also find, on the same page, the support needed to understand or act.
- Body pages usually have at least three layers: learning question / conclusion title → one main exhibit → one layer of explanation, task, check, or source.
- As a starting point, about 60% or more of a body page's main content area should be occupied by meaningful text, figures, tables, flows, or exercises; this is a density guardrail, not a hard ratio. Projection pages may reduce text and self-study pages may add explanation, but neither may use emptiness to mask insufficient content.
- Whitespace is for grouping, establishing reading order, and highlighting key points — it is not the page's main product. Except for covers, section openers, key manifestos, or closing pages, do not produce consecutive pages of "one sentence + a big blank."
- A page may have quiet areas, but only with an explicit reason: a pause, a transition, a memory anchor, or an emotional close. The reason should be writable into the page outline, not explained after the fact.
- High-density pages reduce decoration and add grouping and labels; low-density pages add retellable definitions, examples, check questions, or next steps — not random graphics.
- One set of courseware may have many page types, but the grid, the title anchor, the type hierarchy, the navigation position, and the color semantics stay stable. A unified system does not mean copying the same template onto every page.
Let density vary with the learning action:
| Page type | What it carries | Default density | What must be visible |
| --- | --- | --- | --- |
| Route / opening | Learning questions, goals, chapter relationships | Low to medium | Where we come from and where we are going |
| Core concept | Definitions, boundaries, main relationships | Medium | One definition and one intuitive anchor |
| Demonstration / case | Material, process, judgments, conclusion | Medium to high | The difference between evidence and interpretation |
| Practice / worksheet | Input, operations, completion criteria | Medium to high | What the learner must do right now |
| Feedback / review | Answers, reasons, error correction, principles | Medium | Why this judgment is made |
| Transfer / summary | Checklists, templates, resources, next steps | Medium | How to use this after leaving the material |
## 5. Division of Labor: Text, Graphics, Examples, and Exercises Do Not Impersonate Each Other
- Text explains meaning, boundaries, conditions, and the basis for judgments.
- Graphics reveal real relationships: flows for sequence, trees or nesting for hierarchy, parallel regions for comparison, one-way chains for causality, and cycles only where a genuine loop exists.
- Examples lower abstraction, but facts, results, and explanations must be layered; a case's teaching role is labeled first (demonstration, comparison, diagnosis, or transfer).
- Exercises test mastery; do not fill pages with irrelevant games.
One structural diagram expresses one primary relationship. Every connector needs a direction or a meaning; delete decorative arrows, meaningless rings, and nodes that exist only to fill the page. A key model is explained in full at first appearance, then keeps the same name, shape, color, and reading direction.
External facts, data, quotations, and method sources stay close to their corresponding exhibits, stating at least the source entity and the necessary measurement basis. Illustrative data, team inferences, and fictional material must be explicitly labeled. Without reliable data, use schematic structures or qualitative comparisons — never generate realistic-looking precise values.
Images are used only when "seeing works better than describing." An image may serve as observational evidence or establish a situation; purely decorative images must not crowd out the main learning object. The content of screenshots, photos, illustrations, and charts must be chosen fresh for each new topic — do not copy an object just because a reference sample used it.
## 6. Order of Visual Decisions: Samples Are a Reference Library, Not an Answer Key
Make visual decisions in this order:
1. Complete the learning objectives, the chapter path, and the page-by-page outline.
2. Select each page's main learning object and density tier — do not pick colors or motifs first.
3. Based on the topic, audience, scenario, and evidence types, write a one-page visual brief: temperament, grid, type hierarchy, color roles, graphic grammar, image strategy, component boundaries, headers/footers, and density.
4. When a reference sample is needed, extract only "explainable design decisions," then translate them into the current topic.
5. Form one main system plus several page-type variants; do not stitch together the motifs, fonts, cards, and colors of multiple samples.
### The Correct Way to Use Reference Samples
When you receive a Sample, template, or screenshot, first look at the page's actual visual effect (do not just extract the copy), then write a "reference extraction card" recording only:
- **Borrowable functions:** e.g., a stable grid, role color codes, step navigation, evidence zoning.
- **Borrowable tone:** e.g., restrained, friendly, rigorous, live-event feel, or public-communication feel.
- **Borrowable graphic grammar:** e.g., parallel modules, time paths, nested hierarchy, or photo frames.
- **Objects that cannot be inherited:** the sample's brands, photos, characters, specific copy, proprietary color values, and decorative motifs.
- **Applicable page types:** only note whether it suits concepts, cases, exercises, or steps — do not expand it into a whole-deck template.
One material borrows at most two or three mutually compatible features from a single reference sample; after borrowing, re-name the semantics of colors and components. Without a sample, still build the system yourself from the learning task. Sample 1 enjoys no default priority; it is only one reference direction for editorial-style courseware.
## 7. Reference Directions (Inspiration Only; New Directions May Be Generated)
These directions help you understand design choices quickly; they are not fixed palettes, font tables, or page templates. Take only the parts that fit the task.
### Direction A: Editorial Study Handbook (May Reference Sample 1)
- **Borrowable:** a clear titleexhibitexplanation hierarchy; a stable reading grid; few and explicit accent colors; cases, methods, and sources placed in their own zones; images separated from text.
- **Suits:** concept teaching, methodology, case reading, blended courses, and materials that require self-study.
- **No need to copy:** the blue-and-white palette, geometrically cropped images, capsule labels, fixed hairlines, large chapter whitespace, or any specific photo subject.
- **Density note:** body pages are mainly medium density; cases and exercises can be fuller; only opening and closing pages drop density noticeably.
### Direction B: Role / System Infographics
- **Borrowable:** stable color codes distinguishing roles or modules; nesting, sectors, matrices, or interlocking blocks expressing real relationships; action text kept tight against its owning module.
- **Suits:** multi-role collaboration, public education, system composition, division of responsibilities, and action maps.
- **No need to copy:** colorful collages, full-page color blocks, flat silhouettes, right-angled modules, or any specific color combinations.
- **Density note:** the smaller the module, the shorter its text; relationship-diagram pages keep the necessary gaps; role-action pages may be denser, but meaning must never ride on color alone.
### Direction C: Steps / Work Records
- **Borrowable:** a persistently visible progress cue; numbered steps; clear containers for photos, screenshots, or worksheets; layered actions, risks, and check items.
- **Suits:** operation guides, compliance, safety, job skills, and on-site training.
- **No need to copy:** file folders, paper textures, monospaced labels, fixed bottom stacks, or any skeuomorphic decoration.
- **Density note:** each step page answers at least "what to do, why, and how to check"; route and review pages are not emptied for decoration.
### Direction D: Evidence / Data Editorial (Build Your Own as Needed)
- **Borrowable:** making charts, tables, or screenshots the main exhibit; the title gives the learning question or conclusion first; side text explains the measurement basis, the observation points, and the next step.
- **Suits:** professional popular-science content, results interpretation, before-after comparison, research training, and courses needing evidence support.
- **No need to copy:** dashboard black backgrounds, rainbow charts, giant numbers, dense annotations, or industry-specific brand styles.
- **Density note:** data pages may be full, but each chart serves only one question; without data, do not force charts just to "look like a report."
If the topic fits none of these directions, establish a new reference direction and write down "what it helps the learner accomplish" — rather than adding more decorative rules to it.
## 8. Page Skeletons: Choose the Learning Action First, Then the Layout
Every page is written as a minimal closed loop of "title + main exhibit + support layer + action / check + source." The following page types are composable — not all must be used.
- **Learning route:** learning questions, chapter order, and exit capabilities; use short sentences and a path, not a long table of contents.
- **Concept page:** one definition + boundaries / composition + one intuitive example or structural diagram.
- **Method map:** the overall framework + current step / current module + a cue for what unfolds next.
- **Demonstration page:** input material + intermediate judgments + basis for choices + result; put the error-prone forks on the same path.
- **Case-evidence page:** a case-role label + factual material + interpretation + transferable judgments + source.
- **Comparison / error-prone page:** two approaches or states placed side by side on the same skeleton + judgment criteria + common mistakes.
- **Practice page:** task instructions + input / scenario + work area + completion criteria; do not hide the answer on the same page.
- **Feedback page:** the reference approach + reasons + error location + how to check next time; make clear that this is the answer or the feedback.
- **Transfer page:** checklists, templates, job-aid cards, resources, and next-step actions; avoid merely writing "apply what you learned."
A presentation version may move extended explanation into speaker notes, but the page must still keep the learning question, the main exhibit, the task / judgment criteria, and the necessary sources. A self-study version writes the definitions and conditions needed for understanding on the page itself.
## 9. Minimum Constraints for the Visual System
### Grid and Hierarchy
- First fix the main content area, the title anchor, the content's left axis, and the page-number / source position; then decide the page variants.
- Each page has only one first visual entry: the learning question or principle is seen first, the main exhibit second, the explanation / task / source third.
- Titles, body text, figure notes, and sources use the same type family or a clear two-family relationship; the Chinese fallback must genuinely work. Do not force in a font that does not support Chinese just to imitate a sample.
- Titles and body text establish hierarchy through size, weight, and position. Projection materials prioritize body-text readability; self-study materials may add explanation, but body text is never pressed down to footnote size.
- Ordinary body text reaches at least 4.5:1 contrast against the background; when contrast is insufficient, change the text color or background directly — do not patch it with shadows and strokes.
### Color
- Without brand guidelines, first choose a neutral background, one structural color, and one necessary semantic accent: few and stable colors are easier to learn from than many and lively ones.
- Every color carries a fixed meaning (chapter, role, state, focus, or link) and must not decorate randomly; always also encode with text, shape, position, or icons alongside color.
- A page is usually governed by a neutral background + one main structural color; add a second color family only when a genuine role / category mapping exists.
- Body text on dark grounds uses high-contrast light colors; body text on light grounds uses near-black. Small type never sits on high-saturation colors.
**Starting point when there is no sample (not a fixed style):** adopt a near-white or light-gray background, near-black body text, one structural accent color, and one low-frequency semantic color; build the title-and-body hierarchy with a neutral sans-serif; pair a fixed title left axis with a "main exhibit + explanation / task" layout; keep body pages medium-leaning-full, with only covers, section openers, and closing pages noticeably dropping density. Then adjust by topic, audience, and material evidence — do not treat this starting set as a new template.
### Cards, Components, and Graphics
- Cards are used only for grouping, carrying states, or forming operable regions; continuously stacking cards is not a default layout.
- Rounding, right angles, strokes, shadows, and capsules are all component grammar — once decided, stay consistent throughout; do not take one from each different Sample.
- Shadows, textures, gradients, and decorative icons are used only when they serve a hierarchical or situational function. Anything whose removal does not hurt understanding should be removed.
- Default Office charts, SmartArt, rainbow palettes, thick black table frames, and untuned bullet lists must be redone.
### Images and Charts
- Every image must state "what to see and why it needs to be seen"; evidence images, operation screenshots, and situational images are each labeled with their purpose.
- Charts carry "see the relationship," side text carries "how to interpret and what to do next"; do not repeat the chart's labels verbatim.
- Charts keep the necessary units, time range, legend, key labels, measurement basis, and source; delete non-essential gridlines, frames, and decoration.
- Tables use clear headers, horizontal separators, correct alignment, and the necessary focus rows; do not use full rows of high-saturation color or color alone to express states.
## 10. Model Execution Protocol
### 1. Content First
First write the learner, entry state, exit capability, usage, evidence boundaries, and practice tasks; then write the chapter path. Record at least, for every page:
> Chapter / page type / learning action / title / main exhibit / explanation or task / feedback or check / source / density tier
Check whether every chapter has comprehension, demonstration, application, feedback, and transfer; if not, first add the content or note why it does not apply.
### 2. Reference-Sample Extraction
If there is a Sample, template, or screenshot, finish the reference extraction card before writing the visual brief. The card must not directly copy the object layer (brands, photos, copy, proprietary color values, proprietary motifs); keep only the transferable structure, tone, and graphic relationships. Samples 1, 2, and 3 are all merely candidate references and must not become implicit defaults.
### 3. Visual Brief
The visual brief states at least:
- the audience and usage environment;
- the topic's temperament and density targets;
- one main grid and two to six page types;
- the hierarchy of title / body / source;
- the semantic division of colors and the contrast plan;
- the graphic grammars for flows, hierarchy, comparison, and evidence respectively;
- the usage boundaries for images, screenshots, and illustrations;
- the fixed positions of header, footer, page number, source, and navigation;
- which elements appear only on covers, section pages, or closing pages.
### 4. Page-by-Page Generation
- Write titles that foretell the learning takeaway.
- Choose the single main learning object.
- Complete the definitions, boundaries, labels, tasks, check criteria, and sources.
- Apply the grid, hierarchy, and components per the visual brief — do not copy a Sample page by page.
- Delete graphics, images, quotes, and repeated text that serve no teaching function.
- Check content and overflow first, then make visual fine-tuning; do not mask excessive content by shrinking font size.
### 5. Pre-Delivery Validation
Use the existing PPTD / PPTX validation and screenshot workflow to check overflow, overlap, truncation, garbled text, low contrast, missing page numbers, and missing sources. Review key pages individually at minimum; do not declare completion from thumbnails alone.
## 11. Delivery Acceptance and Reverse Checks
### Content and Teaching
- Reading only the titles, can you state the complete learning path — not a string of section names?
- With the title covered, can the main exhibit still say what it teaches and what to do?
- Does each page carry only one main learning action, and does the explanation truly lead to action?
- Do exercises specify input, actions, and completion criteria? Does feedback explain the reasons and the error-correction method?
- Are facts, illustrative material, inferences, and fictional material clearly distinguished? Does external evidence have sources and measurement basis?
- Do the same concepts, roles, steps, and states keep the same name, color, and shape throughout?
### Density and Visuals
- Do body pages have enough content to support learning, rather than big titles plus blanks? Do consecutive sparse pages have an explicit teaching reason?
- Does each page have one visual entry and one quiet area; are the title, charts, cards, and big images all competing for first attention at the same time?
- With color removed, are steps, roles, states, and categories still legible?
- With the reference sample's photos, color values, and motifs removed, is the courseware still a self-consistent system?
- Is there only one main visual grammar, while different learning actions may use different page types?
- Are images sharp, relevant, unstretched, with no text pressed over complex areas?
- Do charts, tables, and structural diagrams express real relationships, rather than filling the page?
### The Final Cut
Ask item by item: "If I delete this, what does the learner lose?" If the answer is only "the page will look emptier," delete it. What truly needs filling is not decoration, but definitions, examples, judgment criteria, exercises, feedback, or transfer actions.
@@ -0,0 +1,37 @@
# Management Reporting
## Clear and direct content; no empty talk
- A manager who flips through the whole deck reading only the page titles should grasp how the period went, why, and what is being asked — the title itself states a status or conclusion, such as "Q2 revenue reached 92% of target; the shortfall comes from North-region renewals," rather than a section label like "Business Performance Report."
- Open the first page and know how the period went overall: besides the title, the cover presents the single most critical status line of the whole deck — fulfillment rate of core metrics, a red/green/yellow traffic-light overview, or the biggest gap.
- Information is truthful and never fabricated: user-provided numbers and facts are neither exaggerated nor selectively clipped; any baseline that exists in the material travels alongside the results, and anything not in the material is not invented on the user's behalf; use numbers, charts, and tables flexibly to present key information.
- Professional wording that fits the user's identity: no layman's language, and no one-size-fits-all generic business-speak.
## Visualize information with structural diagrams
**Progress, data, responsibilities, risks, and dependencies are the core relationships of a management report — extract the various relationships from the content and express them with structural diagrams and frameworks.**
## Key Requirements
1. Create a top-tier visual experience: treat every detail of typesetting, fonts, and colors with care, crafting it like a work of art.
2. Unless the user explicitly requests it, **strictly forbid using rounded rectangles or rectangular cards** to build hierarchy or alignment: line segments, whitespace, and font/size differences are better solutions.
3. Unless no other layout is available, forbid evenly divided compositions; do not default to one-third splits, four-way splits, or 2×2 matrices — including three-part formulas such as "three columns + title + conclusion."
## Visual References
1. Fonts split into families: display type and body type have a clear division of labor (different weights of the same sans-serif family, or sans-serif titles paired with another family for body text); hierarchy is built on font-size and weight ratios; functional text such as numbering, labels, and footnotes is uniformly set small in caps / with added letter spacing; font sizes flex with content volume while the hierarchy ratios stay unchanged.
2. Fonts and the color scheme must be matched and harmonious; reference each other when designing.
3. Information-position discipline: conclusion/title → fixed title position; evidence (charts, numbered cards, photos) → a fixed area in the right column or lower half; measurement basis, sources, footnotes → small type in a fixed corner.
4. De-default charts: remove axes, grids, legend boxes, and default colors; reassign all series colors to same-family shades; bars are flat and rounded, with no stroke and no shadow; data labels keep only key points or move to the text column; key metrics are marked directly with big-number callouts; charts and interpretive text are strictly zoned — no overprinting, no interleaving.
5. Encourage using rich SmartArt to improve information efficiency and convey professionalism.
6. Unified corner radius and texture: all rectangular components (cards, panels, photos, bar tops) share one corner-radius scale with no mixing throughout the deck; flat, no drop shadows, no 3D, no gradient text; atmospheric layers such as grain or light flares, if used, stay low-intensity, fixed in position, and beneath the content.
7. Motifs run through the whole deck: establish 12 visual motifs (numbered badges, connecting dashed lines, decorative shapes, etc.) and reuse their variants across page types; when a page lacks a visual anchor, reuse a motif first instead of introducing new elements.
### Color Palette Reference
**Colors expected in spirit, unexpected in choice**:
- Reject the most common, most mediocre formulaic palettes of each scenario (Office default blue, tech blue-purple gradients, promotion-season red-and-gold, gray-blue template colors, etc.); suggested palettes for some scenarios:
* Operations/finance/board reporting: off-white #F7F3E8 base + ink green #123B2F + brass #B08D3E; or light stone #E7E2D8 base + deep navy #16283C + copper orange #C0652B; or ink black #1A1A2E base + brass #B08D3E + off-white #F7F3E8.
* Business operations review (retail/manufacturing/consumer/supply chain): warm white #F8F5EF base + wine red #5E1F2D + beige gold #D8C3A5; or off-white #F6EFE2 base + ink green #1E3B33 + terracotta #C15F3C; or light steel #C3CCD4 base + deep blue-gray #1F3240 + signal yellow #F0A202.
* Internet/tech/growth monthly reports: cool white #F4F7F6 base + graphite gray #2B2D42 + pine green #4C7A5A; or mist white #EDF1F7 base + deep indigo #1C2B5A + sky azure #4E9FE6; or ink black #101418 base + celadon green #3FA68C + cool white #F4F7F6.
* HR/administration/government-affairs reporting: warm white #FAF6EE base + ink purple #3D2C4F + cream yellow #F2C14E; or paper white #F7F3E8 base + pine green #2F5233 + apricot yellow #E8B54A; or off-white #F6F4EF base + deep navy #1B2A4A + silver gray #AEB4BC.
- Align background colors toward something more stable and restrained, e.g.: warm white #F7F3E8, light stone #ECEAE4, mist gray #E9E7E2; section/accent pages may use deep ink blue #16283C or ink black #1A1A2E.
@@ -0,0 +1,204 @@
# Tech & Engineering
Scope: sharing and presenting technical solutions, system architecture reviews, AI / data platform proposals, security design reviews, production incident retrospectives, technology selection, testing and validation, API / SDK documentation, and product technical training, among others.
Readers may be fellow engineers, but they may also be product partners or customers. The goal is for readers to understand how the system works, judge whether the solution is good, and see the trade-offs, risks, and next steps clearly.
## 1. Core Character
**Medium-to-high information density, with emphasis on technical explanation and on processes and mechanisms.** Pages are built around architectures, flows, sequences, data, comparisons, and real evidence; text explains the why, while visuals reveal the relationships.
- **Professional**: no empty talk of "high availability" or "high performance." Write out the metrics, environment, boundaries, dependencies, trade-offs, failure conditions, and recovery paths.
- **Concise**: a relationship one diagram can explain must not meander into an essay; nor may necessary assumptions, evidence, and limitations be omitted just to keep the layout clean.
- **Concrete**: architecture diagrams must show call directions, data flow, control flow, and trust or failure boundaries; code, configuration, and logs appear only when they genuinely support the argument.
- **Evidence first**: every page advances one judgment. The title gives the conclusion, the body gives the evidence, and it explains what the evidence means for the solution, the risks, or the next steps.
- **Restrained**: the wow factor comes from making a complex problem clear — not from glow, particles, walls of cards, and hollow "tech vibes."
## 2. General Prohibitions
The following are red lines running through the entire deck; they take effect before all layout and visual rules, and unless the user explicitly requests otherwise, none may be violated.
- **No cards by default**: unless the user explicitly requests it, strictly forbid using rounded rectangles or rectangular cards to build hierarchy or alignment. Line segments, whitespace, and font-size/weight differences are better solutions.
- **No evenly divided compositions**: unless no other layout is available, do not default to one-third splits, four-way splits, or 2×2 matrices — including formulaic patterns such as "title + three parallel blocks + conclusion."
- **No mediocre, common, or AI-typical color schemes**: unless the user explicitly requests them, strictly forbid blue-and-white pairings, blue-purple gradients, cyan-purple neon, rainbow flares, glassmorphism cards, and glowing borders.
- **No elements that clash with the overall style**: no styles from outside the chosen style may appear, such as using rounded icons or rounded rectangles within a sharp style.
## 3. How to Present Technical Content
### 3.1 Explain how the system works first
When first explaining a system or module, cover these first:
- inputs, outputs, and success criteria;
- the scope of the system and its external dependencies;
- the normal path, exception paths, and fallback paths;
- where data comes from, what processing it goes through, and where it ends up;
- which positions are the critical boundaries for performance, security, cost, or reliability.
### 3.2 Put design rationale and costs side by side
- Explain why A was chosen and B was not; the comparison dimensions must come from real goals.
- Write out the costs corresponding to the benefits, including performance, cost, complexity, team capability, vendor lock-in, observability, and migration risk.
- Give the conditions under which it works and the conditions under which it fails; do not present a local optimum as the universal optimum.
- Distinguish current state, target state, candidate options, hypothetical inference, and verified results.
- Launch plans specify validation gates, the gradual rollout method, rollback conditions, and recovery paths.
### 3.3 Evidence must be verifiable
- Metrics come with their source, time, version, test environment, load, sample, and measurement basis.
- Show P50 / P95 / P99, variability, outliers, or confidence intervals as the question demands — not just averages.
- Team inferences, illustrative data, and yet-to-be-verified assumptions must be explicitly labeled.
- When evidence is missing, use "to be filled in," "assumption," or a placeholder; never fabricate benchmarks, logs, cases, or failure causes.
- Explain terms and abbreviations at their first appearance, and keep naming consistent afterward.
## 4. Narrative Skeletons by Engineering Task
One primary scenario determines the whole deck's structure; other scenarios only supply necessary additions — never stack another visual language on top.
| Engineering task | What the reader must judge | Recommended narrative order |
|---|---|---|
| System architecture review | Whether boundaries, dependencies, bottlenecks, and the evolution path are sound | Goals and constraints → current state → problems → alternatives → target architecture → migration and validation |
| AI / data platform proposal | Whether the data, models, and service chain are trustworthy; how quality, latency, and cost are traded off | User tasks → data and model pipeline → core mechanisms → evaluation evidence → risk guardrails → launch loop |
| Security design review | Whether trust boundaries, attack paths, controls, and residual risk are clear | Assets and boundaries → threats → attack paths → controls → residual risk → monitoring and response |
| Production incident retrospective | What the impact was, how the failure happened, and whether the fixes can prevent recurrence | Impact summary → timeline → direct cause → systemic factors → fixes → prevention validation |
| Technology selection review | Which option better fits the goals, and which assumptions the conclusion is sensitive to | Goals and criteria → candidates → like-for-like comparison → trade-offs → recommendation → exit conditions |
| Testing / validation strategy | Whether risks are covered, and whether test layers and release gates suffice | Risk model → layered validation → environment and data → gates → coverage gaps → release decision |
| External tech talk | Why the core mechanism is valuable, whether the evidence is credible, and where the boundaries lie | Problem → mechanism → technical implementation → evidence → limitations → adoption path |
When no better structure fits, start from "decision summary → goals and constraints → current state / problems → mechanism / architecture → key evidence → alternatives and trade-offs → implementation / validation → risks and next steps," then trim and adapt to the scenario.
## 5. Page Rhythm and Information Density
- Default to medium-high density, but keep only one main judgment and one main evidence object per page.
- Alternate text-explanation pages and visual-evidence pages; avoid consecutive stacks of structurally identical bullet lists.
- For complex concepts, give the whole first, then expand layer by layer along stable coordinates; do not redraw the same architecture on every page.
- Show the normal path, exception paths, and migration path in layers; keep the unchanged parts and highlight only what changes.
- Accent pages prioritize key architectures, key comparisons, incident causality, or the final decision — do not manufacture climaxes with big-type slogans.
- Section transitions appear only when a genuine change of rhythm is needed; short materials are not force-fitted with tables of contents and section covers.
- End by returning to the decision, the validation results, or the next steps — never replace the conclusion with a lone "Thank you."
### Common page types
- **Concept / background page:** the necessary explanation paired with one main figure, whitespace spread around the main object.
- **Architecture / flow page:** graphics dominate; text keeps only the conclusion, the legend, and necessary side notes.
- **Comparison / selection page:** options compared on the same scale, dimensions, and coordinates.
- **Metrics / benchmark page:** charts lead; test conditions, baselines, and conclusions stay close to the chart.
- **Incident / timeline page:** chronological order is the main axis; impact, evidence, and handling stay close to their corresponding events.
- **Implementation / migration page:** phases, dependencies, gates, and rollback points are laid out according to their real relationships.
- **Appendix / sources page:** may be denser, but must stay scannable via columns, numbering, and stable line spacing.
## 6. Architecture Diagrams and Flowcharts
### 6.1 The relationship determines the graphic
| Relationship | Preferred graphic | Information that must be conveyed |
|---|---|---|
| System regions and boundaries | Nested or side-by-side right-angled regions | System scope, external dependencies, trust / failure boundaries |
| Calls and data flow | Node chains or networks with directional arrows | The two parties of each call, protocol / data, sync or async |
| Multi-role interaction | Sequence diagrams | Roles, message directions, waits, and exception branches |
| Deployment and failure domains | Topology diagrams | Regions / clusters / instances, redundancy, and isolation scope |
| State transitions | State machines | States, trigger conditions, transitions, and error states |
| Option comparison | Side-by-side topologies or matrices at the same scale | Identical evaluation dimensions, structural differences, and costs |
| Incident causality | Timeline + causal chain / fault tree | Events, evidence, direct causes, contributing factors, and control gaps |
| Validation coverage | Layered matrices or mapping diagrams | Risks, test layers, pass criteria, and coverage gaps |
### 6.2 Diagramming discipline
- Arrows must have direction and meaning; label the protocol, data, frequency, capacity, or trigger conditions where necessary.
- Distinguish data flow, control flow, and exception paths; redundant encoding with color, line style, and labels is allowed.
- External boundaries, internal modules, and critical paths use different but stable grammars.
- Connectors terminate at node edges and never cross through text; when there are too many crossings, rearrange, layer, or split the page.
- Bold the critical paths or use the accent color; other paths recede to neutral; no glow and no 3D arrows.
- For complex architectures, overview first, then zoom into details; keep naming, colors, and coordinate cues consistent.
- Legends explain only the encodings that cannot be labeled in place; anything that can sit beside its node or path is labeled directly.
## 7. Data Charts, Tables, Code, and Screenshots
### Data charts
- Trends use lines, comparisons use bars or side-by-side dot plots, composition uses stacks, latency distributions use histograms / box plots / quantile plots, and capacity-cost relationships may use scatter plots or sensitivity matrices.
- Remove default frames, 3D effects, gradients, heavy gridlines, and meaningless legends.
- Main series use the structural color or critical-path color; baselines and secondary series use grayscale.
- Key values, inflection points, and anomalies are labeled directly, with the "why" and the "what it means."
- Test environment, version, load, sample, units, and baseline appear alongside the chart.
### Tables
- Headers, grouping, status, numbers, and notes form clear hierarchy; default themes are not kept.
- Notes left-aligned, numbers aligned by decimal point or unit, and status columns fixed in position.
- Use thin separators and light group backgrounds; no thick outer frames, rainbow headers, or large red/green fills.
- Options are compared on the same dimensions; missing and non-comparable items are explicitly marked.
### Code, configuration, and screenshots
- Keep only the minimal excerpt that supports the argument, and first tell the reader what to look at.
- Code, interfaces, paths, and fields use monospaced fonts; syntax highlighting only accentuates the key lines or changes.
- For configuration comparison, prefer a minimal diff or a key-fields table; logs are timestamped, identify the source component, and have sensitive data redacted or anonymized.
- Crop screenshots tightly to the evidence boundary, keeping them right-angled rectangles; do not uniformly add device frames, rounded corners, or shadows.
- Side-by-side screenshots keep equal height and width, identical zoom, and the same baseline.
## 8. Visual System
### 8.1 Layout
- A title conveys the conclusion in one sentence, and its visual weight must not exceed the main evidence.
- Use stable safe margins and a title axis; ordinary pages prefer a single column, a left-right split, or text above and figure below.
- Architecture nodes land on a regular grid; pages of the same kind keep the same skeleton.
- Body content is organized by whitespace, alignment, and thin rules by default; cards are used only when content needs delimiting.
- Panels are used only for system scope, code, configuration, or key conclusions — mostly right-angled or minimally rounded, with thin strokes and light fills, and no generic shadows.
- Reading-type materials may keep the document name, section, page number, version, and confidentiality level; live-presented materials keep only the necessary identity information.
### 8.2 Colors and fonts
- Reviews, printing, and long-form reading usually use light backgrounds; dark-room launches may use a restrained dark background.
- When the brand has existing visual assets, inherit them first; without brand constraints, build the palette along the lines of "background color, structural color, critical-path color, status colors, neutrals."
- Each color carries a stable meaning throughout the deck; critical states are additionally distinguished by text, line style, or shape.
- Titles and body text prefer highly legible sans-serif faces; when a document feel is needed, titles may use a restrained serif.
- Code uses monospaced fonts; one deck usually uses no more than two body-type families.
- When content grows, first condense the text, split pages, or adjust the text-to-graphic ratio — only then shrink font size slightly.
### 8.3 Lines, icons, and effects
- Ordinary borders and auxiliary lines are thin and even; only critical paths get visibly bolder.
- Within one diagram, arrows, corners, endpoints, dash rhythms, and corner radii stay consistent.
- Technical structures prefer right angles or minimal rounding; circles and curves appear only when semantics require them.
- Architecture, flows, data, screenshots, and real product visuals take precedence over decorative illustration.
- Icons must come from one stroke system and serve identification; do not mix emoji, 3D, realistic, and system-default icons.
- Body surfaces stay clean: no noise, particles, grid-light effects, glassmorphism, or meaningless gradients.
## 9. Sample References
Samples are only for extracting mechanisms; wholesale replication is forbidden. Organize the Style first according to the current readers, evidence, brand, and usage; precise color values, fonts, covers, section pages, and footers are not inherited by default.
### Sample A: Warm Orange & Cool Blue — White-Base Engineering Document Style
- **Traits:** white background with black body text; the warm color carries titles and critical paths, the cool color carries nodes and structure; fixed header and page numbers; suited to reading and printing.
- **Borrowable:** the warm/cool semantic division, a stable document axis, reuse of architecture coordinates, and hierarchical distinction through boundaries / nodes / paths.
- **Good for reference:** architecture reviews, technical white papers, platform proposals, and materials that need to unfold the same architecture step by step.
- **Not inherited automatically:** the orange and blue color values, Inter, the gradient-arc cover, orange table headers, and the fixed header position.
### Sample B: Four-Color Flat — Engineering Walkthrough Style
- **Traits:** white background with dark-gray text, a few high-saturation semantic colors, flat structural diagrams, and solid-color section pages; suited to live walkthroughs and cross-role communication.
- **Borrowable:** semantic color coding, solid-color section pauses, text/graphic zoning, direct labeling, and equal-width comparison columns.
- **Good for reference:** product technical training, role collaboration, and talks balancing concepts and flows.
- **Not inherited automatically:** the fixed four colors, solid-per-chapter backgrounds, the dual-ended footer, and specific brand fonts.
### Sample C: White Base & Deep Ink Blue — Two-Color Short-Line Engineering Walkthrough
- **Traits:** deep ink-blue titles, short colored lines, and a white base forming a stable walkthrough skeleton; explanation pages alternate with evidence pages; visuals float directly on the white ground.
- **Borrowable:** the fixed title axis, weak navigation, alternation of explanation and evidence, and reduced container noise.
- **Good for reference:** live tech talks, building concepts step by step, and materials centered on screenshots and mechanism diagrams.
- **Not inherited automatically:** the orange/green section colors, diagonal section color blocks, the deep-purple ending, the fixed short-line sizes, and the font combination.
Do not write "choose Sample A / B / C" in the plan. If the result still clearly looks like a direct replica of some Sample once the text is hidden, keep adjusting — but do not break relationship expression and consistency just to be novel.
## 10. Pre-Delivery Checklist
- Are inputs, outputs, dependencies, boundaries, the normal path, exception paths, and fallback paths clear?
- Do key connectors have direction and meaning, and are current state, target state, assumptions, and verified results distinguished?
- Do metrics carry environment, version, sample, load, units, baseline, and time window?
- Does each page carry only one main judgment, and does the evidence truly support the title?
- Does the visual weight fall on the evidence, and are colors, shapes, line styles, and naming consistent?
- Are there unsourced data, default Office charts, walls of cards, decorative "tech vibes," or Sample replicas?
- Was technical evidence altered, weakened, or falsified for the sake of visual unity?
@@ -0,0 +1,175 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Open Kimi PPT Local Export</title>
<style>
html,
body,
iframe {
width: 100%;
height: 100%;
margin: 0;
border: 0;
}
#status {
position: fixed;
z-index: 10;
top: 8px;
left: 50%;
transform: translateX(-50%);
padding: 4px 10px;
border-radius: 6px;
background: rgb(0 0 0 / 72%);
color: white;
font: 12px/1.5 system-ui, sans-serif;
pointer-events: none;
}
</style>
</head>
<body>
<div id="status">starting</div>
<iframe id="editor" allow="fullscreen; clipboard-read; clipboard-write"></iframe>
<script type="module">
import {
i as connect,
r as WindowMessenger,
} from "https://statics.moonshot.cn/neo-design/assets/penpal-C4NjirZE.js";
const status = document.querySelector("#status");
const frame = document.querySelector("#editor");
const editorOrigin = "https://www.kimi.com";
const setStatus = (value) => {
status.textContent = value;
document.documentElement.dataset.deckStatus = value;
};
const normalizePath = (value) => {
if (typeof value !== "string") return "";
if (/^(?:data:image\/|https?:\/\/|blob:)/i.test(value)) return value;
let candidate = value.replace(/^file:\/\/+/, "").replaceAll("\\", "/");
try {
candidate = decodeURIComponent(candidate);
} catch {
// Preserve literal percent signs.
}
const parts = [];
for (const part of candidate.split("/")) {
if (!part || part === ".") continue;
if (part === "..") parts.pop();
else parts.push(part);
}
return parts.join("/");
};
const resolveImage = (requestedPath, imageMap) => {
if (/^(?:data:image\/|https?:\/\/|blob:)/i.test(requestedPath || "")) {
return requestedPath;
}
const normalized = normalizePath(requestedPath);
if (imageMap[normalized]) return imageMap[normalized];
const suffix = Object.keys(imageMap).find(
(path) => normalized.endsWith(`/${path}`) || path.endsWith(`/${normalized}`),
);
return suffix ? imageMap[suffix] : "";
};
try {
const payload = await fetch("./payload.json", { cache: "no-store" }).then((response) => {
if (!response.ok) throw new Error(`payload HTTP ${response.status}`);
return response.json();
});
const query = new URLSearchParams({
sdkMode: "ppt-editor",
pptPlatform: "open-kimi-ppt-local-export",
functional: JSON.stringify({
fullscreen: false,
present: false,
export: true,
close: false,
annotation: false,
feedback: false,
share: false,
versionHistory: false,
}),
sdkSaveMode: "external",
sdkImageMode: "external",
});
frame.addEventListener(
"load",
async () => {
setStatus("iframe-loaded");
try {
const messenger = new WindowMessenger({
remoteWindow: frame.contentWindow,
allowedOrigins: [editorOrigin],
});
const connection = connect({
messenger,
methods: {
close() {},
reenter() {},
toggleFullScreen(value) {
return value;
},
showFeedback() {},
sendPrompt() {},
showMessage() {},
hideMessage() {},
onSave(savePayload) {
return {
fileContent: savePayload?.fileContent,
lastModifiedTime: Date.now(),
};
},
getImages(imagePayload = {}) {
const paths = Array.isArray(imagePayload.filePath) ? imagePayload.filePath : [];
return paths.map((path) => resolveImage(path, payload.imageMap || {}));
},
setAnnotationMode() {},
setAnnotationCurrentPage() {},
upsertAnnotation() {},
removeAnnotation() {},
clearAnnotations() {},
},
});
const remote = await connection.promise;
window.exportRemote = remote;
await remote.setSlideConfig({
editable: true,
locale: "zh-CN",
theme: "light",
slideId: payload.id,
});
await remote.setPPTD(payload.id, {
pptdContent: payload.manifestContent,
pages: payload.pages,
pptdPath: payload.manifestPath,
basePath: "",
isCreate: true,
});
await remote.setEditable(true);
window.exportSlideStatus = await remote.getSlideStatus();
setStatus("ready");
} catch (error) {
window.exportHostError = String(error?.stack || error);
setStatus("error");
}
},
{ once: true },
);
frame.src = `${editorOrigin}/neo-ppt/?${query}`;
} catch (error) {
window.exportHostError = String(error?.stack || error);
setStatus("error");
}
</script>
</body>
</html>
@@ -0,0 +1,427 @@
#!/usr/bin/env python3
"""Export a PPTD project as page images through Kimi's public editor for visual QA.
Reuses the same localhost SDK host and agent-browser flow as export_pptx.py, but
chooses 图片 in the export dialog, captures the images ZIP, unzips it, and stitches
all pages into a single overview image that a multimodal model can review.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import uuid
import zipfile
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple
from export_pptx import (
HOST_TEMPLATE,
BrowserSession,
ExportError,
build_payload,
ensure_agent_browser,
find_download,
find_manifest,
log,
ref_by_name,
serve,
wait_for_export_dialog,
)
IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp"}
OVERVIEW_COLUMNS = 3
OVERVIEW_THUMB_WIDTH = 640
OVERVIEW_LABEL_HEIGHT = 32
OVERVIEW_GAP = 12
def ensure_pillow() -> Tuple[Any, Any, Any]:
try:
from PIL import Image, ImageDraw, ImageFont
return Image, ImageDraw, ImageFont
except ImportError:
log("Pillow is required for stitching; installing pillow with pip --user")
process = subprocess.run(
[sys.executable, "-m", "pip", "install", "--user", "pillow"],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=300,
)
if process.returncode != 0:
raise ExportError(f"failed to install Pillow:\n{process.stdout[-2000:]}")
from PIL import Image, ImageDraw, ImageFont
return Image, ImageDraw, ImageFont
def is_image_zip(path: Path) -> bool:
if not path.is_file() or path.name.endswith(".crdownload"):
return False
try:
with zipfile.ZipFile(path) as archive:
return any(
Path(name).suffix.lower() in IMAGE_SUFFIXES
for name in archive.namelist()
)
except (OSError, zipfile.BadZipFile):
return False
def page_sort_key(path: Path) -> Tuple[int, str]:
match = re.match(r"(\d+)", path.stem)
return (int(match.group(1)) if match else sys.maxsize, path.name)
def unzip_images(archive_path: Path, pages_dir: Path) -> List[Path]:
pages_dir.mkdir(parents=True, exist_ok=True)
images: List[Path] = []
with zipfile.ZipFile(archive_path) as archive:
for info in archive.infolist():
if info.is_dir() or Path(info.filename).suffix.lower() not in IMAGE_SUFFIXES:
continue
name = Path(info.filename).name
if not name:
continue
target = pages_dir / name
with archive.open(info) as source, target.open("wb") as out:
shutil.copyfileobj(source, out)
images.append(target)
images.sort(key=page_sort_key)
if not images:
raise ExportError(f"no page images found in: {archive_path}")
return images
def label_font(image_font: Any) -> Any:
try:
return image_font.load_default(size=18)
except TypeError: # older Pillow without the size argument
return image_font.load_default()
def stitch_overview(
images: Sequence[Path],
output: Path,
image_cls: Any,
draw_cls: Any,
image_font: Any,
) -> Path:
thumbs: List[Tuple[str, Any]] = []
for index, path in enumerate(images, start=1):
with image_cls.open(path) as opened:
frame = opened.convert("RGB")
ratio = OVERVIEW_THUMB_WIDTH / frame.width
thumb = frame.resize(
(OVERVIEW_THUMB_WIDTH, max(1, round(frame.height * ratio)))
)
thumbs.append((f"P{index}", thumb))
columns = OVERVIEW_COLUMNS
rows = math.ceil(len(thumbs) / columns)
cell_height = OVERVIEW_LABEL_HEIGHT + max(thumb.height for _, thumb in thumbs)
width = columns * OVERVIEW_THUMB_WIDTH + (columns + 1) * OVERVIEW_GAP
height = rows * cell_height + (rows + 1) * OVERVIEW_GAP
overview = image_cls.new("RGB", (width, height), "#e5e7eb")
draw = draw_cls.Draw(overview)
font = label_font(image_font)
for position, (label, thumb) in enumerate(thumbs):
column = position % columns
row = position // columns
x = OVERVIEW_GAP + column * (OVERVIEW_THUMB_WIDTH + OVERVIEW_GAP)
y = OVERVIEW_GAP + row * (cell_height + OVERVIEW_GAP)
draw.rectangle(
(x, y, x + OVERVIEW_THUMB_WIDTH, y + OVERVIEW_LABEL_HEIGHT - 4),
fill="#111827",
)
draw.text((x + 8, y + 5), label, fill="#ffffff", font=font)
overview.paste(thumb, (x, y + OVERVIEW_LABEL_HEIGHT))
overview.save(output, "JPEG", quality=85)
return output
OOPIF_URL_HINT = "kimi.com/neo-ppt"
# The export dialog's 图片 format option is a plain <div class="radio-group-item">
# without an ARIA role, so agent-browser's interactive snapshot never exposes it
# and cross-origin iframe rules block page-level eval. Clicking it requires CDP.
IMAGE_FORMAT_CLICK_JS = """
(() => {
const items = [...document.querySelectorAll('.radio-group-item')];
const pool = items.length
? items
: [...document.querySelectorAll('div,span,label,button')].filter(
(el) => el.children.length === 0
);
const target = pool.find((el) => el.textContent.trim() === '图片');
if (!target) return null;
target.click();
return 'clicked';
})()
""".strip()
ACTIVE_FORMAT_JS = """
(() => {
const active = document.querySelector('.radio-group-item.active');
return active ? active.textContent.trim() : null;
})()
""".strip()
def ensure_websocket() -> Any:
try:
import websocket
return websocket
except ImportError:
log("websocket-client is required for dialog automation; installing with pip --user")
process = subprocess.run(
[sys.executable, "-m", "pip", "install", "--user", "websocket-client"],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=300,
)
if process.returncode != 0:
raise ExportError(f"failed to install websocket-client:\n{process.stdout[-2000:]}")
import websocket
return websocket
def browser_cdp_url(browser: BrowserSession) -> str:
process = browser.run(["get", "cdp-url"], timeout=30)
match = re.search(r"ws://\S+", process.stdout)
if not match:
raise ExportError(
f"could not determine the browser CDP URL:\n{process.stdout[-500:]}"
)
return match.group(0)
def evaluate_in_iframe(cdp_url: str, url_hint: str, expression: str) -> Any:
websocket = ensure_websocket()
def call(socket: Any, request_id: int, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
socket.send(json.dumps({"id": request_id, "method": method, "params": params}))
while True:
message = json.loads(socket.recv())
if message.get("id") != request_id:
continue
if "error" in message:
raise ExportError(f"CDP {method} failed: {message['error']}")
return message.get("result", {})
# websocket-client honors http_proxy env vars; the CDP endpoint is local,
# so strip proxy settings instead of tunneling localhost through the proxy.
proxy_env = ("http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY", "all_proxy", "ALL_PROXY")
saved_proxy = {name: os.environ.pop(name) for name in proxy_env if name in os.environ}
try:
socket = websocket.create_connection(cdp_url, timeout=30, suppress_origin=True)
finally:
os.environ.update(saved_proxy)
try:
targets = call(socket, 1, "Target.getTargets", {}).get("targetInfos", [])
target = next(
(item for item in targets if url_hint in str(item.get("url", ""))), None
)
if target is None:
visible = ", ".join(
f"{item.get('type')}:{str(item.get('url', ''))[:80]}" for item in targets
)
raise ExportError(
f"no browser target matches {url_hint!r}; observed: {visible}"
)
attached = call(
socket,
2,
"Target.attachToTarget",
{"targetId": target["targetId"], "flatten": True},
)
session_id = attached["sessionId"]
socket.send(
json.dumps(
{
"id": 3,
"sessionId": session_id,
"method": "Runtime.evaluate",
"params": {"expression": expression, "returnByValue": True},
}
)
)
while True:
message = json.loads(socket.recv())
if message.get("id") != 3:
continue
if "error" in message:
raise ExportError(f"CDP Runtime.evaluate failed: {message['error']}")
result = message.get("result", {})
if result.get("exceptionDetails"):
details = result["exceptionDetails"]
raise ExportError(f"iframe script failed: {details.get('text')}")
return result.get("result", {}).get("value")
finally:
socket.close()
def select_image_format(browser: BrowserSession) -> None:
cdp_url = browser_cdp_url(browser)
value = evaluate_in_iframe(cdp_url, OOPIF_URL_HINT, IMAGE_FORMAT_CLICK_JS)
if value != "clicked":
raise ExportError("could not find the 图片 option in the export dialog")
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
active = evaluate_in_iframe(cdp_url, OOPIF_URL_HINT, ACTIVE_FORMAT_JS)
if active == "图片":
return
time.sleep(0.3)
raise ExportError(f"image format was not activated; active option: {active!r}")
def export_images(
source: Path,
output: Path,
keep_download: bool = False,
force: bool = False,
) -> Dict[str, Any]:
manifest = find_manifest(source)
payload = build_payload(manifest)
output = output.expanduser().resolve()
if output.exists() and any(output.iterdir()) and not force:
raise ExportError(
f"output directory already exists (pass --force to replace it): {output}"
)
agent_browser = ensure_agent_browser()
image_cls, draw_cls, image_font = ensure_pillow()
log(f"manifest: {manifest}")
with tempfile.TemporaryDirectory(prefix="open-kimi-ppt-images-") as temp_name:
temp_dir = Path(temp_name)
download_dir = temp_dir / "downloads"
download_dir.mkdir()
shutil.copy2(HOST_TEMPLATE, temp_dir / HOST_TEMPLATE.name)
(temp_dir / "payload.json").write_text(
json.dumps(payload, ensure_ascii=False), encoding="utf-8"
)
server, thread, url = serve(temp_dir)
session = f"open-kimi-ppt-images-{os.getpid()}-{uuid.uuid4().hex[:8]}"
browser = BrowserSession(agent_browser, session, temp_dir, download_dir)
try:
log("opening the public Kimi slide editor")
browser.open(url)
browser.run(
[
"wait",
"--fn",
'document.documentElement.dataset.deckStatus === "ready"',
],
timeout=120,
)
browser.run(["set", "viewport", "1280", "720"])
snapshot = browser.snapshot()
export_ref = ref_by_name(snapshot, "导出", "button")
browser.run(["click", f"@{export_ref}"])
dialog = wait_for_export_dialog(browser)
select_image_format(browser)
dialog = wait_for_export_dialog(browser)
download_ref = ref_by_name(dialog, "下载", "button")
log("rendering page images in the browser")
result = browser.run(
["download", f"@{download_ref}", str(temp_dir / "browser-output.zip")],
timeout=300,
check=False,
)
if result.returncode != 0:
log("download capture reported a timeout; checking browser output files")
downloaded = find_download(
(download_dir, temp_dir), timeout=240, accept=is_image_zip
)
finally:
browser.close()
server.shutdown()
server.server_close()
thread.join(timeout=2)
if output.exists():
shutil.rmtree(output)
output.mkdir(parents=True)
images = unzip_images(downloaded, output / "pages")
if keep_download:
shutil.copy2(downloaded, output / "browser-raw.zip")
overview = stitch_overview(
images, output / "overview.jpg", image_cls, draw_cls, image_font
)
page_paths = [entry["path"] for entry in payload["pages"]]
mapping = [
{
"index": index,
"image": f"pages/{path.name}",
"page": page_paths[index - 1] if index - 1 < len(page_paths) else None,
}
for index, path in enumerate(images, start=1)
]
return {
"pages": len(images),
"overview": str(overview),
"output": str(output),
"images": mapping,
}
def parse_args(argv: Optional[Sequence[str]] = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Export a PPTD project as page images via Kimi's public editor, unzip "
"them, and stitch an overview image for visual QA."
)
)
parser.add_argument("input", type=Path, help=".pptd manifest or project directory")
parser.add_argument(
"--output",
"-o",
type=Path,
help="output directory (default: <project>/.qa-images)",
)
parser.add_argument(
"--keep-browser-raw",
action="store_true",
help="also keep the downloaded images ZIP beside the overview",
)
parser.add_argument(
"--force",
action="store_true",
help="replace an existing output directory",
)
return parser.parse_args(argv)
def main(argv: Optional[Sequence[str]] = None) -> int:
args = parse_args(argv)
try:
manifest = find_manifest(args.input)
output = args.output or manifest.parent / ".qa-images"
summary = export_images(args.input, output, args.keep_browser_raw, args.force)
except (ExportError, OSError, subprocess.SubprocessError) as exc:
print(f"open-kimi-ppt image export failed: {exc}", file=sys.stderr)
return 1
print(json.dumps(summary, ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+662
View File
@@ -0,0 +1,662 @@
#!/usr/bin/env python3
"""Export a PPTD project through Kimi's public browser-side PPTX writer.
The script uses a temporary localhost SDK host and agent-browser. It never uploads
the PPTD project as a document. Referenced remote resources may still be fetched by
the official editor. Local image files are exposed to the iframe as data URLs.
"""
from __future__ import annotations
import argparse
import base64
import json
import mimetypes
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import threading
import time
import uuid
import zipfile
import xml.etree.ElementTree as ET
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
try:
import yaml
except ImportError as exc: # pragma: no cover - environment diagnostic
raise SystemExit(
"PyYAML is required. Install it with: python3 -m pip install --user pyyaml"
) from exc
SKILL_DIR = Path(__file__).resolve().parent.parent
HOST_TEMPLATE = Path(__file__).with_name("export_host.html")
IMAGE_MIME = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
}
MAX_IMAGE_BYTES = 20 * 1024 * 1024
MAX_EMBEDDED_MEDIA_BYTES = 200 * 1024 * 1024
PPTX_CONTENT_TYPE = (
"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"
)
FADE_TRANSITION_XML = (
'<p:transition spd="fast" advClick="1"><p:fade/></p:transition>'
)
MIN_AGENT_BROWSER_VERSION = (0, 33, 2)
class ExportError(RuntimeError):
pass
class QuietHandler(SimpleHTTPRequestHandler):
def log_message(self, _format: str, *_args: Any) -> None:
return
def log(message: str) -> None:
print(f"[open-kimi-ppt] {message}", file=sys.stderr, flush=True)
def parse_version(output: str) -> Tuple[int, int, int]:
match = re.search(r"(\d+)\.(\d+)\.(\d+)\b", output)
if not match:
raise ExportError(f"could not parse agent-browser version from: {output.strip()}")
return tuple(int(part) for part in match.groups())
def read_agent_browser_version(executable: str) -> Tuple[int, int, int]:
process = subprocess.run(
[executable, "--version"],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=30,
)
if process.returncode != 0:
raise ExportError(f"agent-browser --version failed:\n{process.stdout[-2000:]}")
return parse_version(process.stdout)
def ensure_agent_browser() -> str:
executable = shutil.which("agent-browser")
version = read_agent_browser_version(executable) if executable else None
if version is not None and version >= MIN_AGENT_BROWSER_VERSION:
log(f"agent-browser version: {'.'.join(map(str, version))}")
return executable
npm = shutil.which("npm")
if not npm:
reason = "not installed" if version is None else ".".join(map(str, version))
raise ExportError(
f"agent-browser {reason}; npm is required to install agent-browser@latest"
)
current = "not installed" if version is None else ".".join(map(str, version))
minimum = ".".join(map(str, MIN_AGENT_BROWSER_VERSION))
log(f"agent-browser {current} is below {minimum}; installing agent-browser@latest")
process = subprocess.run(
[npm, "install", "-g", "agent-browser@latest"],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=300,
)
if process.returncode != 0:
raise ExportError(f"failed to install agent-browser@latest:\n{process.stdout[-4000:]}")
executable = shutil.which("agent-browser")
if not executable:
raise ExportError("agent-browser@latest installed, but executable is not on PATH")
version = read_agent_browser_version(executable)
if version < MIN_AGENT_BROWSER_VERSION:
raise ExportError(
"agent-browser@latest is still below the required version "
f"{minimum}: {'.'.join(map(str, version))}"
)
log(f"agent-browser upgraded to {'.'.join(map(str, version))}")
return executable
def find_manifest(source: Path) -> Path:
source = source.expanduser().resolve()
if source.is_file():
if source.suffix.lower() != ".pptd":
raise ExportError(f"input must be a .pptd file or project directory: {source}")
return source
if not source.is_dir():
raise ExportError(f"input does not exist: {source}")
manifests = sorted(source.rglob("*.pptd"))
if not manifests:
raise ExportError(f"no .pptd manifest found under: {source}")
if len(manifests) > 1:
choices = "\n ".join(str(path) for path in manifests[:20])
raise ExportError(
"multiple .pptd manifests found; pass one manifest explicitly:\n " + choices
)
return manifests[0]
def read_yaml_mapping(path: Path) -> Tuple[str, Dict[str, Any]]:
text = path.read_text(encoding="utf-8")
try:
value = yaml.safe_load(text)
except yaml.YAMLError as exc:
raise ExportError(f"invalid YAML in {path}: {exc}") from exc
if not isinstance(value, dict):
raise ExportError(f"expected a YAML mapping in {path}")
return text, value
def safe_project_path(root: Path, relative: str) -> Path:
if not isinstance(relative, str) or not relative.strip():
raise ExportError("page path must be a non-empty string")
candidate = (root / relative).resolve()
try:
candidate.relative_to(root)
except ValueError as exc:
raise ExportError(f"project path escapes the PPTD directory: {relative}") from exc
return candidate
def build_image_map(root: Path) -> Dict[str, str]:
image_map: Dict[str, str] = {}
total = 0
for path in sorted(root.rglob("*")):
if not path.is_file() or path.suffix.lower() not in IMAGE_MIME:
continue
size = path.stat().st_size
if size > MAX_IMAGE_BYTES:
log(f"skip local image over 20 MiB: {path.relative_to(root)}")
continue
if total + size > MAX_EMBEDDED_MEDIA_BYTES:
raise ExportError(
"local image payload exceeds 200 MiB; reduce media size or use remote URLs"
)
data = base64.b64encode(path.read_bytes()).decode("ascii")
rel = path.relative_to(root).as_posix()
image_map[rel] = f"data:{IMAGE_MIME[path.suffix.lower()]};base64,{data}"
total += size
if image_map:
log(f"prepared {len(image_map)} local image resource(s), {total} bytes")
return image_map
def build_payload(manifest: Path) -> Dict[str, Any]:
manifest_text, manifest_data = read_yaml_mapping(manifest)
if manifest_data.get("version") != "v2":
raise ExportError("local PPTX export currently requires PPTD version: v2")
page_paths = manifest_data.get("pages")
if not isinstance(page_paths, list) or not page_paths:
raise ExportError("PPTD manifest must contain a non-empty pages list")
root = manifest.parent.resolve()
pages: List[Dict[str, str]] = []
for entry in page_paths:
page_path = safe_project_path(root, entry)
if not page_path.is_file():
raise ExportError(f"missing page file: {entry}")
page_text, page_data = read_yaml_mapping(page_path)
if not isinstance(page_data.get("elements"), list):
raise ExportError(f"page elements must be an array: {entry}")
pages.append({"path": str(entry), "content": page_text})
title = str(manifest_data.get("title") or manifest.stem)
return {
"id": f"local-export-{uuid.uuid4().hex}",
"title": title,
"manifestPath": manifest.name,
"manifestContent": manifest_text,
"pages": pages,
"imageMap": build_image_map(root),
}
def json_result(output: str) -> Dict[str, Any]:
for line in reversed(output.splitlines()):
line = line.strip()
if not line.startswith("{"):
continue
try:
value = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(value, dict):
return value
raise ExportError(f"agent-browser returned no JSON object:\n{output[-2000:]}")
class BrowserSession:
def __init__(self, executable: str, session: str, cwd: Path, download_dir: Path):
self.executable = executable
self.session = session
self.cwd = cwd
self.download_dir = download_dir
self.env = os.environ.copy()
self.env.setdefault("AGENT_BROWSER_DEFAULT_TIMEOUT", "60000")
self.env.setdefault("AGENT_BROWSER_IDLE_TIMEOUT_MS", "180000")
def run(
self,
args: Sequence[str],
*,
timeout: int = 90,
check: bool = True,
) -> subprocess.CompletedProcess[str]:
command = [self.executable, "--session", self.session, *args]
process = subprocess.run(
command,
cwd=self.cwd,
env=self.env,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=timeout,
)
if check and process.returncode != 0:
raise ExportError(
f"agent-browser command failed ({process.returncode}): "
f"{' '.join(args)}\n{process.stdout[-4000:]}"
)
return process
def open(self, url: str) -> None:
self.run(
["--download-path", str(self.download_dir), "open", url], timeout=90
)
def snapshot(self) -> Dict[str, Any]:
process = self.run(["snapshot", "-i", "-C", "--json"])
return json_result(process.stdout)
def close(self) -> None:
self.run(["close"], timeout=20, check=False)
def snapshot_data(snapshot: Dict[str, Any]) -> Dict[str, Any]:
data = snapshot.get("data")
if not isinstance(data, dict):
raise ExportError(f"invalid agent-browser snapshot: {snapshot}")
return data
def ref_by_name(snapshot: Dict[str, Any], name: str, role: Optional[str] = None) -> str:
refs = snapshot_data(snapshot).get("refs")
if not isinstance(refs, dict):
raise ExportError("snapshot contains no interactive refs")
matches = []
for ref, metadata in refs.items():
if not isinstance(metadata, dict) or metadata.get("name") != name:
continue
if role is not None and str(metadata.get("role", "")).lower() != role.lower():
continue
matches.append(ref)
if not matches:
raise ExportError(f"could not find {role or 'element'} named {name!r}")
return matches[-1]
def switch_state(snapshot: Dict[str, Any]) -> Optional[Tuple[str, bool, bool]]:
text = str(snapshot_data(snapshot).get("snapshot") or "")
match = re.search(r"switch \[(?P<attrs>[^\]]*?)ref=(?P<ref>e\d+)\]", text)
if not match:
return None
attrs = match.group("attrs")
return match.group("ref"), "checked=true" in attrs, "disabled" in attrs
def wait_for_export_dialog(browser: BrowserSession, timeout: float = 20.0) -> Dict[str, Any]:
deadline = time.monotonic() + timeout
last: Optional[Dict[str, Any]] = None
while time.monotonic() < deadline:
last = browser.snapshot()
try:
ref_by_name(last, "下载", "button")
return last
except ExportError:
time.sleep(0.35)
raise ExportError(f"export dialog did not become ready: {last}")
def is_pptx(path: Path) -> bool:
if not path.is_file() or path.name.endswith(".crdownload"):
return False
try:
with zipfile.ZipFile(path) as archive:
if "ppt/presentation.xml" not in archive.namelist():
return False
content_types = archive.read("[Content_Types].xml")
return PPTX_CONTENT_TYPE.encode("utf-8") in content_types
except (OSError, KeyError, zipfile.BadZipFile):
return False
def find_download(
search_roots: Iterable[Path],
timeout: float = 150.0,
accept: Callable[[Path], bool] = is_pptx,
) -> Path:
deadline = time.monotonic() + timeout
last_sizes: Dict[Path, int] = {}
stable: Dict[Path, int] = {}
while time.monotonic() < deadline:
candidates: List[Path] = []
for root in search_roots:
if not root.exists():
continue
candidates.extend(path for path in root.rglob("*") if path.is_file())
for path in sorted(candidates, key=lambda item: item.stat().st_mtime, reverse=True):
try:
size = path.stat().st_size
except OSError:
continue
if size == last_sizes.get(path) and size > 0:
stable[path] = stable.get(path, 0) + 1
else:
stable[path] = 0
last_sizes[path] = size
if stable[path] >= 1 and accept(path):
return path
time.sleep(0.5)
visible = "\n ".join(str(path) for path in last_sizes) or "(none)"
raise ExportError(f"timed out waiting for download; observed files:\n {visible}")
def replace_transition(slide_xml: bytes, transition: str) -> bytes:
text = slide_xml.decode("utf-8")
pattern = re.compile(
r"<p:transition\b[^>]*(?:/>|>.*?</p:transition>)", re.DOTALL
)
text = pattern.sub("", text)
if transition == "none":
return text.encode("utf-8")
# CT_Slide requires transition as a direct child after cSld/clrMapOvr and
# before timing/extLst. Searching for the first p:extLst is incorrect:
# shapes may contain their own nested extLst inside cSld, causing Office to
# ignore a transition inserted there.
color_map = re.search(
r"<p:clrMapOvr\b[^>]*(?:/>|>.*?</p:clrMapOvr>)", text, re.DOTALL
)
common_slide = re.search(
r"<p:cSld\b[^>]*(?:/>|>.*?</p:cSld>)", text, re.DOTALL
)
anchor = color_map or common_slide
if anchor is None:
raise ExportError("slide XML has no cSld/clrMapOvr insertion anchor")
position = anchor.end()
return (text[:position] + FADE_TRANSITION_XML + text[position:]).encode("utf-8")
def root_child_names(slide_xml: bytes) -> List[str]:
try:
root = ET.fromstring(slide_xml)
except ET.ParseError as exc:
raise ExportError(f"invalid slide XML: {exc}") from exc
return [child.tag.rsplit("}", 1)[-1] for child in root]
def has_direct_fade_transition(slide_xml: bytes) -> bool:
try:
root = ET.fromstring(slide_xml)
except ET.ParseError as exc:
raise ExportError(f"invalid slide XML: {exc}") from exc
transition = next(
(child for child in root if child.tag.rsplit("}", 1)[-1] == "transition"),
None,
)
if transition is None:
return False
return any(child.tag.rsplit("}", 1)[-1] == "fade" for child in transition)
def validate_transition_order(slide_xml: bytes, transition: str) -> None:
names = root_child_names(slide_xml)
transition_indexes = [index for index, name in enumerate(names) if name == "transition"]
if transition == "none":
if transition_indexes:
raise ExportError("transition=none left a root-level transition")
return
if len(transition_indexes) != 1 or not has_direct_fade_transition(slide_xml):
raise ExportError("slide does not contain exactly one root-level fade transition")
transition_index = transition_indexes[0]
for required_before in ("cSld", "clrMapOvr"):
if required_before in names and names.index(required_before) > transition_index:
raise ExportError(f"{required_before} appears after transition")
for required_after in ("timing", "extLst"):
if required_after in names and names.index(required_after) < transition_index:
raise ExportError(f"{required_after} appears before transition")
def patch_transitions(pptx: Path, transition: str) -> int:
temporary = pptx.with_name(f".{pptx.name}.{uuid.uuid4().hex}.tmp")
slide_count = 0
try:
with zipfile.ZipFile(pptx, "r") as source, zipfile.ZipFile(temporary, "w") as target:
target.comment = source.comment
for info in source.infolist():
data = source.read(info.filename)
if re.fullmatch(r"ppt/slides/slide\d+\.xml", info.filename):
data = replace_transition(data, transition)
slide_count += 1
target.writestr(info, data, compress_type=info.compress_type)
if slide_count == 0:
raise ExportError("exported PPTX contains no slide XML")
temporary.replace(pptx)
finally:
temporary.unlink(missing_ok=True)
return slide_count
def verify_output(pptx: Path, transition: str, expect_fonts: bool) -> Dict[str, Any]:
if not is_pptx(pptx):
raise ExportError(f"output is not a valid PPTX ZIP: {pptx}")
with zipfile.ZipFile(pptx) as archive:
broken = archive.testzip()
if broken:
raise ExportError(f"PPTX CRC check failed at: {broken}")
slide_names = [
name
for name in archive.namelist()
if re.fullmatch(r"ppt/slides/slide\d+\.xml", name)
]
slide_xml = {name: archive.read(name) for name in slide_names}
for data in slide_xml.values():
validate_transition_order(data, transition)
transition_hits = sum(has_direct_fade_transition(data) for data in slide_xml.values())
if transition == "fade" and transition_hits != len(slide_names):
raise ExportError("fade transition was not written to every slide")
fonts = [
name
for name in archive.namelist()
if name.startswith("ppt/fonts/") and not name.endswith("/")
]
if expect_fonts and not fonts:
log(
"warning: embed-fonts was enabled, but the official writer produced no font part"
)
return {
"slides": len(slide_names),
"fadeTransitions": transition_hits,
"fontParts": len(fonts),
"bytes": pptx.stat().st_size,
}
def serve(directory: Path) -> Tuple[ThreadingHTTPServer, threading.Thread, str]:
handler = lambda *args, **kwargs: QuietHandler( # noqa: E731
*args, directory=str(directory), **kwargs
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
host, port = server.server_address
return server, thread, f"http://{host}:{port}/export_host.html"
def export_pptx(
source: Path,
output: Path,
transition: str,
embed_fonts: bool,
keep_download: bool = False,
force: bool = False,
) -> Dict[str, Any]:
manifest = find_manifest(source)
payload = build_payload(manifest)
output = output.expanduser().resolve()
output.parent.mkdir(parents=True, exist_ok=True)
if output.exists() and not force:
raise ExportError(f"output already exists (pass --force to replace it): {output}")
agent_browser = ensure_agent_browser()
log(f"manifest: {manifest}")
log(
f"defaults: transition={transition}, embed_fonts={'on' if embed_fonts else 'off'}"
)
with tempfile.TemporaryDirectory(prefix="open-kimi-ppt-export-") as temp_name:
temp_dir = Path(temp_name)
download_dir = temp_dir / "downloads"
download_dir.mkdir()
shutil.copy2(HOST_TEMPLATE, temp_dir / HOST_TEMPLATE.name)
(temp_dir / "payload.json").write_text(
json.dumps(payload, ensure_ascii=False), encoding="utf-8"
)
server, thread, url = serve(temp_dir)
session = f"open-kimi-ppt-export-{os.getpid()}-{uuid.uuid4().hex[:8]}"
browser = BrowserSession(agent_browser, session, temp_dir, download_dir)
try:
log("opening the public Kimi slide editor")
browser.open(url)
browser.run(
[
"wait",
"--fn",
'document.documentElement.dataset.deckStatus === "ready"',
],
timeout=120,
)
browser.run(["set", "viewport", "1280", "720"])
snapshot = browser.snapshot()
export_ref = ref_by_name(snapshot, "导出", "button")
browser.run(["click", f"@{export_ref}"])
dialog = wait_for_export_dialog(browser)
state = switch_state(dialog)
if state is not None:
switch_ref, checked, disabled = state
if disabled and checked != embed_fonts:
log("warning: the official font switch is disabled for this deck")
elif checked != embed_fonts:
browser.run(["click", f"@{switch_ref}"])
dialog = wait_for_export_dialog(browser)
elif embed_fonts:
log("warning: the official export dialog exposed no font switch")
download_ref = ref_by_name(dialog, "下载", "button")
log("generating PPTX in the browser")
result = browser.run(
["download", f"@{download_ref}", str(temp_dir / "browser-output.pptx")],
timeout=180,
check=False,
)
if result.returncode != 0:
log("download capture reported a timeout; checking browser output files")
downloaded = find_download((download_dir, temp_dir), timeout=90)
shutil.copy2(downloaded, output)
if keep_download:
debug_copy = output.with_name(f"{output.stem}.browser-raw.pptx")
if debug_copy.exists() and not force:
raise ExportError(
f"raw debug output already exists (pass --force): {debug_copy}"
)
shutil.copy2(downloaded, debug_copy)
finally:
browser.close()
server.shutdown()
server.server_close()
thread.join(timeout=2)
slide_count = patch_transitions(output, transition)
summary = verify_output(output, transition, embed_fonts)
summary["transitionPatchedSlides"] = slide_count
summary["output"] = str(output)
return summary
def parse_args(argv: Optional[Sequence[str]] = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Export a PPTD project to PPTX using Kimi's public browser-side writer. "
"Defaults: fade transition and embedded fonts."
)
)
parser.add_argument("input", type=Path, help=".pptd manifest or project directory")
parser.add_argument("--output", "-o", type=Path, help="output .pptx path")
parser.add_argument(
"--transition",
choices=("fade", "none"),
default="fade",
help="slide transition written to every slide (default: fade)",
)
font_group = parser.add_mutually_exclusive_group()
font_group.add_argument(
"--embed-fonts",
dest="embed_fonts",
action="store_true",
default=True,
help="embed fonts when available (default)",
)
font_group.add_argument(
"--no-embed-fonts",
dest="embed_fonts",
action="store_false",
help="disable font embedding",
)
parser.add_argument(
"--keep-browser-raw",
action="store_true",
help="also keep the unpatched browser download beside the output",
)
parser.add_argument(
"--force",
action="store_true",
help="replace an existing output file",
)
return parser.parse_args(argv)
def main(argv: Optional[Sequence[str]] = None) -> int:
args = parse_args(argv)
try:
manifest = find_manifest(args.input)
output = args.output or manifest.with_suffix(".pptx")
summary = export_pptx(
args.input,
output,
args.transition,
args.embed_fonts,
args.keep_browser_raw,
args.force,
)
except (ExportError, OSError, subprocess.SubprocessError) as exc:
print(f"open-kimi-ppt export failed: {exc}", file=sys.stderr)
return 1
print(json.dumps(summary, ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,5 @@
version: v2
title: Open Kimi PPT Local Export Test
size: [960, 540]
pages:
- pages/01.page
@@ -0,0 +1,11 @@
pageType: content
background: {type: solid, color: "#F7F8FC"}
elements:
- elementId: title
elementType: text
bounds: [100, 180, 760, 120]
content:
align: [center, middle]
fontFamily: MiSans
text: |
<p><span style="font-size:42px;color:#171923;font-weight:700">本地导出验证</span></p>
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
import importlib.util
import sys
import tempfile
import unittest
import zipfile
from pathlib import Path
SCRIPTS_DIR = Path(__file__).resolve().parents[1] / "scripts"
sys.path.insert(0, str(SCRIPTS_DIR))
SPEC = importlib.util.spec_from_file_location("export_images", SCRIPTS_DIR / "export_images.py")
MODULE = importlib.util.module_from_spec(SPEC)
assert SPEC and SPEC.loader
SPEC.loader.exec_module(MODULE)
def make_images_zip(path: Path, names=("1.jpeg", "10.jpeg", "2.jpeg")) -> None:
# 1x1 white JPEG, the smallest valid payload Pillow can open.
import base64
pixel = base64.b64decode(
"/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////"
"////////////////////////////////////////////2wBDAf//////////////////"
"////////////////////////////////////////////wAARCAABAAEDASIAAhEBAxEB"
"/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/9oADAMB"
"AAIQAxAAAAGf/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABBQJ//8QAFBEBAAAA"
"AAAAAAAAAAAAAAAAAP/aAAgBAwEBPwF//8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgB"
"AgEBPwF//8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQAGPwJ//8QAFBABAAAAAAAA"
"AAAAAAAAAAAAAP/aAAgBAQABPyF//9oADAMBAAIAAwAAABCf/8QAFBEBAAAAAAAAAAAA"
"AAAAAAAAAP/aAAgBAwEPEBB//8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAgEPEBB/"
"/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxB//9k="
)
with zipfile.ZipFile(path, "w") as archive:
for name in names:
archive.writestr(name, pixel)
class ExportImagesTests(unittest.TestCase):
def test_page_sort_key_orders_numeric_stems(self):
paths = [Path("10.jpeg"), Path("2.jpeg"), Path("cover.jpeg"), Path("1.jpeg")]
ordered = sorted(paths, key=MODULE.page_sort_key)
self.assertEqual(
[path.name for path in ordered],
["1.jpeg", "2.jpeg", "10.jpeg", "cover.jpeg"],
)
def test_is_image_zip_accepts_image_entries_only(self):
with tempfile.TemporaryDirectory() as name:
root = Path(name)
good = root / "images.zip"
make_images_zip(good)
self.assertTrue(MODULE.is_image_zip(good))
bad = root / "text.zip"
with zipfile.ZipFile(bad, "w") as archive:
archive.writestr("readme.txt", "hello")
self.assertFalse(MODULE.is_image_zip(bad))
self.assertFalse(MODULE.is_image_zip(root / "missing.zip"))
def test_unzip_images_flattens_and_sorts(self):
with tempfile.TemporaryDirectory() as name:
root = Path(name)
archive_path = root / "images.zip"
make_images_zip(archive_path, names=("1.jpeg", "10.jpeg", "2.jpeg", "note.txt"))
images = MODULE.unzip_images(archive_path, root / "pages")
self.assertEqual(
[path.name for path in images], ["1.jpeg", "2.jpeg", "10.jpeg"]
)
def test_stitch_overview_grid(self):
try:
image_cls, draw_cls, image_font = MODULE.ensure_pillow()
except MODULE.ExportError:
self.skipTest("Pillow is not available")
with tempfile.TemporaryDirectory() as name:
root = Path(name)
images = []
for index in range(1, 5):
path = root / f"{index}.jpeg"
image = image_cls.new("RGB", (320, 180), (index * 40 % 255, 30, 60))
image.save(path, "JPEG")
images.append(path)
overview = MODULE.stitch_overview(
images, root / "overview.jpg", image_cls, draw_cls, image_font
)
self.assertTrue(overview.is_file())
with image_cls.open(overview) as result:
self.assertEqual(
result.width,
3 * MODULE.OVERVIEW_THUMB_WIDTH + 4 * MODULE.OVERVIEW_GAP,
)
rows = 2
cell = MODULE.OVERVIEW_LABEL_HEIGHT + 360
self.assertEqual(result.height, rows * cell + (rows + 1) * MODULE.OVERVIEW_GAP)
if __name__ == "__main__":
unittest.main()
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
import importlib.util
import tempfile
import unittest
import zipfile
from pathlib import Path
from unittest.mock import patch
SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "export_pptx.py"
SPEC = importlib.util.spec_from_file_location("export_pptx", SCRIPT)
MODULE = importlib.util.module_from_spec(SPEC)
assert SPEC and SPEC.loader
SPEC.loader.exec_module(MODULE)
class ExportPptxTests(unittest.TestCase):
def test_parse_agent_browser_version(self):
self.assertEqual(MODULE.parse_version("agent-browser 0.33.2"), (0, 33, 2))
self.assertEqual(MODULE.parse_version("v1.4.0-beta.1"), (1, 4, 0))
@patch.object(MODULE.subprocess, "run")
@patch.object(MODULE.shutil, "which")
def test_old_agent_browser_is_upgraded(self, which, run):
which.side_effect = ["/bin/agent-browser", "/bin/npm", "/bin/agent-browser"]
run.side_effect = [
MODULE.subprocess.CompletedProcess([], 0, "agent-browser 0.17.1\n"),
MODULE.subprocess.CompletedProcess([], 0, "changed 1 package\n"),
MODULE.subprocess.CompletedProcess([], 0, "agent-browser 0.33.2\n"),
]
self.assertEqual(MODULE.ensure_agent_browser(), "/bin/agent-browser")
self.assertEqual(run.call_args_list[1].args[0], [
"/bin/npm", "install", "-g", "agent-browser@latest"
])
def test_fade_is_inserted_before_timing(self):
source = (
b'<?xml version="1.0" encoding="UTF-8"?>'
b'<p:sld xmlns:p="urn:test"><p:cSld><p:spTree><p:extLst/>'
b'</p:spTree></p:cSld><p:clrMapOvr/><p:timing/><p:extLst/></p:sld>'
)
result_bytes = MODULE.replace_transition(source, "fade")
result = result_bytes.decode("utf-8")
self.assertIn("<p:transition", result)
self.assertIn("<p:fade/>", result)
self.assertGreater(result.index("<p:transition"), result.index("<p:clrMapOvr"))
self.assertLess(result.index("<p:transition"), result.index("<p:timing"))
MODULE.validate_transition_order(result_bytes, "fade")
def test_existing_transition_is_replaced_or_removed(self):
source = (
b'<p:sld xmlns:p="urn:test"><p:cSld/>'
b'<p:transition><p:wipe/></p:transition><p:extLst/></p:sld>'
)
faded = MODULE.replace_transition(source, "fade").decode("utf-8")
self.assertNotIn("p:wipe", faded)
self.assertEqual(faded.count("<p:transition"), 1)
MODULE.validate_transition_order(faded.encode("utf-8"), "fade")
cleared = MODULE.replace_transition(source, "none").decode("utf-8")
self.assertNotIn("p:transition", cleared)
MODULE.validate_transition_order(cleared.encode("utf-8"), "none")
def test_nested_transition_is_relocated_to_slide_root(self):
source = (
b'<p:sld xmlns:p="urn:test"><p:cSld><p:spTree>'
b'<p:transition><p:fade/></p:transition><p:extLst/>'
b'</p:spTree></p:cSld><p:clrMapOvr/><p:extLst/></p:sld>'
)
result = MODULE.replace_transition(source, "fade")
MODULE.validate_transition_order(result, "fade")
self.assertEqual(MODULE.root_child_names(result), [
"cSld", "clrMapOvr", "transition", "extLst"
])
def test_patch_transitions_preserves_a_valid_zip(self):
with tempfile.TemporaryDirectory() as name:
deck = Path(name) / "test.pptx"
with zipfile.ZipFile(deck, "w", zipfile.ZIP_DEFLATED) as archive:
archive.writestr(
"[Content_Types].xml",
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
'<Override PartName="/ppt/presentation.xml" '
f'ContentType="{MODULE.PPTX_CONTENT_TYPE}"/></Types>',
)
archive.writestr("ppt/presentation.xml", "<p:presentation xmlns:p=\"urn:test\"/>")
archive.writestr(
"ppt/slides/slide1.xml",
'<p:sld xmlns:p="urn:test"><p:cSld/></p:sld>',
)
self.assertEqual(MODULE.patch_transitions(deck, "fade"), 1)
with zipfile.ZipFile(deck) as archive:
self.assertIsNone(archive.testzip())
slide = archive.read("ppt/slides/slide1.xml")
self.assertIn(b"<p:fade/>", slide)
if __name__ == "__main__":
unittest.main()