| name | code-diagram-generator |
| description | Use when user provides a project path and wants to generate code logic diagrams, architecture diagrams, flowcharts, or caller-callee relationship graphs. Triggers on mentions of "代码逻辑图", "网络结构图", "流程图", "架构图", "调用关系图", "可视化", "画出代码结构", "generate diagram from code", "visualize code". Especially designed for deep learning / machine learning projects — generates paper-style model architecture diagrams with layer-by-layer detail, plus call graphs, class diagrams, and sequence diagrams for peripheral code. Outputs high-resolution rendered SVG and PNG files. |
Code Diagram Generator
Overview
Scan a project directory, identify deep learning model definitions and general code logic, then generate two categories of diagrams:
- DL model architecture diagrams — paper-style block diagrams showing layer flow, tensor shapes, skip connections, and attention paths
- Code logic diagrams — call graphs, class diagrams, sequence diagrams, and data-flow diagrams
All diagrams are output as high-resolution SVG and PNG files, rendered via Mermaid CLI with enhanced quality settings.
Prerequisites Check & Auto-Setup
Before generating any diagrams, verify the rendering tools are available. If not, install them automatically:
Check Node.js:
node --version 2>&1
If missing, guide the user to install Node.js (https://nodejs.org/) — this can't be fully automated.
Check/Install mermaid-cli:
npx --yes @mermaid-js/mermaid-cli --version 2>&1
Verify Puppeteer/Chromium (mermaid-cli needs a headless browser):
echo "graph TD; A-->B" | npx -y @mermaid-js/mermaid-cli -o test_check.svg 2>&1
If this fails with a Puppeteer/chromium error, install chromium:
npx -y puppeteer browsers install chrome 2>&1
Once all checks pass, remove test_check.svg.
If any installation step fails, explain what's needed and offer to work with Mermaid text output only.
Core Workflow
Phase 1 — Scan & Classify
Scan the project directory recursively. Exclude build artifacts immediately:
target/ (Rust builds), node_modules/, __pycache__/, .git/, dist/, *.lock
logs/, *.log files
- Binary files:
.exe, .dll, .so, .dylib, .bin
DL model file detection — flag a file as "model definition" if it contains:
- PyTorch:
nn.Module, nn.Sequential, torch.nn, forward(
- TensorFlow/Keras:
tf.keras.Model, keras.Model, Sequential(, call(, create_model()
- JAX/Flax:
flax.linen, nn.Module (Flax), hk.Module
- ONNX:
.onnx files, onnx.load
- PaddlePaddle:
paddle.nn
- Generic: class names
Model, Net, Network, Architecture; MMoE/Custom model patterns
Training pipeline detection — flag as "training pipeline" if containing:
model.fit(), model.compile(), train_model(), create_dataset()
- TFRecord, DataLoader patterns
- Horovod, multi-GPU distribution logic
- Checkpoint/resume training patterns
Deduplication rule: If the project contains multiple subdirectories with identical structure (e.g., limit1/, limit2/, nolimit/ all with the same files), only analyze one representative copy. Mention the others in a note.
Phase 2 — Generate Mermaid Diagrams
Aesthetics Rules (APPLY TO ALL DIAGRAMS)
Every diagram MUST use these styling practices to ensure professional, readable output:
0. BILINGUAL LABELS (MANDATORY — 双语标注,强制执行)
Every node label, subgraph title, edge annotation, and note MUST include both English and Chinese. This makes diagrams accessible to Chinese-speaking teams while keeping English as backup for international readers.
Format: English text 中文释义
Examples:
node["Map Embedding 地图嵌入<br/>vocab=1.1M, dim=8"]
subgraph TOWER["MMoE Tower 多门混合专家塔"]
Note over S: Warmup Phase 预热阶段<br/>(discarded 不计入统计)
edge --> "Continue 继续"
- Keep the English part FIRST, Chinese annotation AFTER with a space separator
- For technical terms, use industry-standard Chinese translations (Embedding=嵌入, Attention=注意力, Inference=推理, Gate=门控)
- For subgraph titles, the Chinese annotation sits next to the English name on the same line
- Node labels with multi-line content should have the Chinese annotation on the same line as the English main label, separated by a space
1. Define a color palette with classDef:
Use consistent color groups across all diagrams. Choose warm+professional colors, NOT Mermaid's default pastels. Include font-size:24px in every classDef:
classDef core fill:#2b6cb0,stroke:#1a4971,color:#fff,stroke-width:2px,font-size:24px
classDef model fill:#c53030,stroke:#822727,color:#fff,stroke-width:2px,font-size:24px
classDef data fill:#2f855a,stroke:#1b4332,color:#fff,stroke-width:2px,font-size:24px
classDef external fill:#6b46c1,stroke:#44337a,color:#fff,stroke-width:2px,font-size:24px
classDef infra fill:#c05621,stroke:#7b341e,color:#fff,stroke-width:2px,font-size:24px
2. Node label formatting (concise, no overflow):
Node labels must fit inside their card boundaries. With bilingual text, content doubles — so labels MUST be short:
- Each
<br/> line MAX 30 characters (half-width count; a Chinese character counts as 2)
- Total lines per node MAX 3 (2 is ideal)
- Trade detail for readability: shorten long names, abbreviate common terms when space is tight
- Use ONE
<br/> separator at most — prefer a single-line format where possible: "English 中文"
Shortening techniques:
- "Attention" → "Attn", "Embedding" → "Emb", "Sequence" → "Seq", "Continuous" → "Cont"
- Drop redundant info that readers already know from context (parent subgraph labels provide grouping)
- Merge two verbose lines into one shorter one
Bad (too long, will overflow):
AVATAR_CONT["Avatar Continuous 玩家连续特征<br/>behavior stats 行为统计<br/>1d/3d/7d/30d windows"]
Good (short enough to fit):
AVATAR_CONT["Avatar Cont 玩家连续特征<br/>1d/3d/7d/30d windows"]
3. Edge styling:
- Add labels to edges only when they convey critical information
- Edge labels MUST also be bilingual:
"Data flow 数据流"
- Use dashed lines (
-.->) for background/async operations
- Use thick lines (
==>) only for the main/hot path
4. Subgraph styling:
- Every logical grouping gets a subgraph with a bilingual descriptive label
- Use soft tints (
#f0f4ff, #fff5f5, #f0fff4) for subgraph backgrounds
5. Layout direction:
- Call graphs and architecture overviews:
flowchart TB (top-bottom)
- Data flow pipelines:
flowchart LR (left-right)
- Sequence diagrams: always
sequenceDiagram with autonumber
6. Custom CSS file for large fonts + overflow protection 大字体 + 防裁剪 CSS:
Create a large-font.css file alongside the diagrams:
.node foreignObject, .edgeLabel foreignObject, .note foreignObject,
.cluster-label foreignObject, .actor foreignObject, .messageText foreignObject,
.labelText foreignObject, .loopText foreignObject, .rectText foreignObject {
overflow: visible !important;
}
.node foreignObject div {
font-size: 24px !important;
font-family: "Microsoft YaHei", "PingFang SC", "Noto Sans SC", "Segoe UI", sans-serif !important;
line-height: 1.4 !important;
word-break: break-word !important;
}
.edgeLabel foreignObject div {
font-size: 20px !important;
font-family: "Microsoft YaHei", "PingFang SC", "Noto Sans SC", "Segoe UI", sans-serif !important;
}
.cluster-label, .cluster text.cluster-label, g.cluster text {
font-size: 26px !important;
font-weight: bold !important;
}
.actor text, .actor-man text { font-size: 22px !important; }
.messageText, .messageText text { font-size: 22px !important; }
.note foreignObject div { font-size: 20px !important; }
.labelText, .labelText text, .loopText, .loopText text { font-size: 22px !important; }
text, tspan {
font-family: "Microsoft YaHei", "PingFang SC", "Noto Sans SC", "Segoe UI", sans-serif !important;
}
The overflow: visible on foreignObject elements is CRITICAL — without it, Mermaid's auto-computed foreignObject dimensions clip text when CSS enlarges the font. The word-break: break-word handles the rare case where a single unbroken word is wider than the container.
Pass this CSS to mermaid-cli via --cssFile large-font.css.
Category A: DL Model Architecture Diagrams
Use Mermaid flowchart TB with paper-quality layout.
Output format for model architecture:
flowchart TB
input["Input<br/>n_features"]
subgraph FEAT["Feature Extraction"]
direction TB
cont["Continuous Features"]
cate["Categorical → Embedding"]
seq["Sequence Features<br/>battle_map ×50"]
end
subgraph ENCODING["Feature Encoding"]
mha["Multi-Head Attention<br/>num_heads=2, key_dim=4"]
self_attn["Self-Attention<br/>on sequences"]
cross_attn["Cross-Attention<br/>map ↔ history"]
end
subgraph TOWER["MMoE Towers"]
shared["Shared Bottom<br/>Dense 1024 → 512 → {128,32,16}"]
experts["Expert Branches<br/>Dense 512 → 128 → 32 → 16"]
gates["Gating Networks<br/>Dense 128 → 32 → softmax(2)"]
end
subgraph HEAD["Output Heads"]
o1["output1<br/>Battle<br/>sigmoid"]
o2["output2<br/>Valid<br/>sigmoid"]
o3["output3<br/>Success<br/>sigmoid"]
o4["output4<br/>Battle<br/>sigmoid"]
end
input --> cont & cate & seq
seq --> mha & self_attn
cate --> cross_attn
mha & self_attn & cross_attn --> shared
shared --> experts
experts --> gates
cont & cate & gates --> HEAD
Key principles:
- Trace
forward() / create_model() execution order — NOT class attribute order
- Group operations into logical stages (Feature → Encoding → Tower → Head)
- Annotate key parameters:
num_heads, key_dim, layer sizes, activation functions
- Show skip connections and attention paths explicitly
- For repeated patterns (e.g., 50-length sequences), show one representative + "×50"
- Use
subgraph for grouping logical sections
Category B: Code Logic Diagrams
For non-model code, select the diagram type by code pattern:
| Pattern | Diagram | Syntax |
|---|
| Function calls across modules | Call Graph | flowchart TB |
| Classes with inheritance | Class Diagram | classDiagram |
| Request/event pipeline | Sequence Diagram | sequenceDiagram |
| State machine | State Diagram | stateDiagram-v2 |
| Data processing flow | Flowchart LR | flowchart LR |
Phase 3 — Render to SVG / PNG (HIGH QUALITY + LARGE FONTS)
Why this works (and CSS alone doesn't):
Mermaid computes <foreignObject> and <rect> dimensions at render time. CSS font-size applied after rendering can't change those baked-in sizes — text overflows even with overflow: visible. The fix: tell Mermaid's layout engine the font size before it computes geometry. Use a Mermaid config file with themeVariables.fontSize.
Step 0: Create Mermaid config file diagrams/mermaid-config.json:
{
"theme": "default",
"themeVariables": {
"fontSize": "24px",
"fontFamily": "\"Microsoft YaHei\", \"PingFang SC\", \"Noto Sans SC\", \"Segoe UI\", sans-serif"
},
"flowchart": {
"nodeSpacing": 80,
"rankSpacing": 90,
"padding": 30
},
"sequence": {
"messageFontSize": "22px",
"noteFontSize": "20px",
"actorFontSize": "22px",
"width": 240,
"height": 80,
"boxMargin": 20,
"messageMargin": 60
}
}
Step 1: Render all diagrams with config (one command):
$config = "diagrams/mermaid-config.json"
Get-ChildItem diagrams -Recurse -Filter *.mmd | ForEach-Object {
$outSvg = "$($_.DirectoryName)\$($_.BaseName).svg"
$outPng = "$($_.DirectoryName)\$($_.BaseName).png"
npx -y @mermaid-js/mermaid-cli -i $_.FullName -o $outSvg -b white -c $config --width 3840 --height 2880 --scale 4 --pdfFit 2>&1
npx -y @mermaid-js/mermaid-cli -i $_.FullName -o $outPng -b white -c $config --width 3840 --height 2880 --scale 4 --pdfFit 2>&1
}
Step 2: Apply CSS as supplementary layer (for edge labels, note boxes, and text that Mermaid config doesn't cover):
Still create large-font.css as described in Rule #6. But the PRIMARY mechanism is the Mermaid config file — CSS is supplementary overflow protection.
npx -y @mermaid-js/mermaid-cli -i input.mmd -o output.svg -c mermaid-config.json -b white --width 3840 --height 2880 --scale 4
Critical quality parameters:
themeVariables.fontSize: "24px": the KEY setting — makes Mermaid size containers correctly at layout time
flowchart.nodeSpacing: 80, rankSpacing: 90: extra spacing prevents node overlap with large text
--scale 4: NEVER use scale 1 — produces blurry images
--width 3840 --height 2880: extra-large canvas for complex diagrams
-b white: white background for readability
-c mermaid-config.json: REQUIRED — without this, containers are sized for 16px text and overflow is inevitable
Phase 4 — Organize Output
<project-path>/diagrams/
├── model/
│ ├── <name>_architecture.mmd
│ ├── <name>_architecture.svg
│ └── <name>_architecture.png
├── logic/
│ ├── <name>.mmd / .svg / .png
├── pipeline/
│ ├── <name>_pipeline.mmd / .svg / .png
└── README.md
Diagram Quality Checklist
Before declaring completion:
Quick Reference
Input: project directory path
Output: diagrams/{model,logic,pipeline}/ with .mmd, .svg, .png
Scan: exclude target/ node_modules/ logs/ *.lock
Labels: bilingual 双语 (English first 英文在前, 中文在后)
Render: --scale 4 --width 3840 --cssFile large-font.css
Style: classDef with font-size:28px, subgraphs, edge labels