Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

feat(svg_position_calculator): integrate chart coordinate review into executor pipeline

hugohe3f26556a1d57c
diff --git a/skills/ppt-master/references/executor-base.md b/skills/ppt-master/references/executor-base.md
index 5264f4f5..b915b011 100644
--- a/skills/ppt-master/references/executor-base.md
+++ b/skills/ppt-master/references/executor-base.md
@@ -85,7 +85,7 @@ Before drawing each page, look up its entry in `page_rhythm` (key format `P<NN>`
- **Generation rhythm**: First lock the global design context, then generate pages sequentially one by one in the same continuous context; grouped page batches (for example, 5 pages at a time) are not allowed
- **Phased batch generation** (recommended):
1. **Visual Construction Phase**: Generate all SVG pages continuously in sequential page order, ensuring high consistency in design style and layout coordinates (Visual Consistency)
- 2. **Quality Check Gate** (mandatory between phases): run `python3 scripts/svg_quality_checker.py <project_path>` against `svg_output/`. Any `error` (banned SVG features, viewBox mismatch, spec_lock color / font / size drift, non-PPT-safe font stack, etc.) MUST be fixed on the offending page before entering the Logic Construction Phase — re-generate that page and re-run the check. `warning` entries should be reviewed and fixed when straightforward; otherwise acknowledge and release. Do NOT defer this check to after `finalize_svg.py` — finalize rewrites SVG and some violations get masked.
+ 2. **Quality Check Gate** (mandatory between phases): first run `python3 scripts/svg_quality_checker.py <project_path>` against `svg_output/`. Any `error` (banned SVG features, viewBox mismatch, spec_lock color / font / size drift, non-PPT-safe font stack, etc.) MUST be fixed on the offending page before entering the Logic Construction Phase — re-generate that page and re-run the check. `warning` entries should be reviewed and fixed when straightforward; otherwise acknowledge and release. After the SVG quality checker passes, run the chart coordinate review in §5.1 for pages containing chart types supported by `svg_position_calculator.py`. Do NOT defer these checks to after `finalize_svg.py` — finalize rewrites SVG and some violations get masked.
3. **Logic Construction Phase**: After SVGs pass the quality gate, batch-generate speaker notes to ensure narrative coherence (Narrative Continuity)
- **Technical specifications**: See [shared-standards.md](shared-standards.md) for SVG technical constraints and PPT compatibility rules
- **Visual depth — through restraint, not abundance**: Layered depth comes from rhythm (flat vs lifted, dense vs spacious), not from applying shadows everywhere. Use shadow on at most 2–3 genuinely floating elements per page (cards on photos, primary CTA, overlays); keep section panels, peer-grid cards, dividers, and body-text containers flat. Reach for typography weight, spacing, accent bars, and subtle background tints **before** adding shadow. See shared-standards.md §6 for full rules including single-light-source and elevation tiers.
@@ -191,6 +191,48 @@ When the Design Spec includes a **VII. Visualization Reference List**, read the
> Visualization templates: `templates/charts/` (70 types). Index: `templates/charts/charts_index.json`
+### 5.1 Chart Coordinate Review (After SVG Quality Checker)
+
+> For pages containing chart types supported by `svg_position_calculator.py`, run the calculator **after** `svg_quality_checker.py` passes and **before** entering the Logic Construction Phase. The goal is to compare calculated chart coordinates against the coordinates already present in the generated SVG. Do NOT apply this requirement to every visualization; it only applies to calculator-supported chart types.
+
+**Workflow for chart pages after `svg_quality_checker.py` passes:**
+
+1. **Confirm the chart type is supported** — run this review only for chart types exposed by the calculator: `bar`, `pie` / `donut`, `radar`, `line` / `area` / `scatter`, and `grid`. Area charts do **not** have a separate calculator mode; use `calc line` for the upper boundary points, then close the filled area to the plot area's bottom baseline (`y_max`) in the SVG. Other visualizations (timeline, process, framework diagrams, maps, pictograms, etc.) are governed by normal visual/spec review unless they can be explicitly modeled by one of these calculator modes.
+
+2. **Identify the chart plot area** — read it from the SVG layout or derive it from the existing chart frame. The plot area is the data drawing rectangle only; it excludes title, legend, axis labels, footnotes, and surrounding annotations.
+
+ Recommended SVG marker when generating chart pages:
+ ```xml
+ <!-- chart-plot-area: x_min,y_min,x_max,y_max -->
+ ```
+
+3. **Calculate the expected coordinates** — run the calculator for the chart type and manually compare the output with the SVG's existing mark coordinates:
+ ```bash
+ # Bar chart
+ python3 scripts/svg_position_calculator.py calc bar \
+ --data "Label1:Value1,Label2:Value2" --area "x_min,y_min,x_max,y_max" --bar-width 120
+
+ # Line / area chart
+ python3 scripts/svg_position_calculator.py calc line \
+ --data "x1:y1,x2:y2,..." --area "x_min,y_min,x_max,y_max" --y-range "0,max"
+
+ # Pie / donut chart
+ python3 scripts/svg_position_calculator.py calc pie \
+ --data "Slice1:Value1,Slice2:Value2" --center "cx,cy" --radius 200
+
+ # Grid layout (KPI cards, multi-column)
+ python3 scripts/svg_position_calculator.py calc grid --rows 2 --cols 2 --area "50,150,1230,670"
+ ```
+
+ For an area chart, use the line output as the top boundary. The filled SVG path should close to the plot area's bottom edge:
+ ```svg
+ M first_x,first_y ... L last_x,last_y L last_x,y_max L first_x,y_max Z
+ ```
+
+4. **If coordinates differ** — manually update the SVG attributes from the calculator output, then rerun `svg_quality_checker.py` and repeat this coordinate review. Do NOT use regex or bulk text replacement to rewrite SVG coordinates automatically.
+
+**Why this matters**: AI models routinely introduce 10–50 px coordinate errors when mentally mapping data values to SVG pixel positions. These errors compound across bars, lines, and grid cells, producing charts where data proportions are visually wrong. The calculator eliminates this class of error entirely.
+
---
## 6. Image Handling
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 48e99e7b..71f3c7d4 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -84,19 +84,34 @@ Checks include:
## `svg_position_calculator.py`
-Analyze or pre-calculate chart coordinates.
+Analyze and review supported chart coordinates after SVG generation.
-Common commands:
+Use this after `svg_quality_checker.py` passes, and only for chart types supported by this script: `bar`, `pie` / `donut`, `radar`, `line` / `area` / `scatter`, and `grid`. Area charts do not have a separate calculator mode: use `calc line` for the upper boundary points, then close the filled region to the plot area's bottom baseline (`y_max`) in the SVG.
+
+### Calculate expected coordinates
+
+```bash
+python3 scripts/svg_position_calculator.py calc bar --data "A:185,B:142" --area "130,155,1200,480" --bar-width 120
+python3 scripts/svg_position_calculator.py calc line --data "0:50,10:80,20:120" --area "120,120,1200,600" --y-range "0,150"
+python3 scripts/svg_position_calculator.py calc pie --data "A:35,B:25,C:20" --center "420,400" --radius 200
+python3 scripts/svg_position_calculator.py calc grid --rows 2 --cols 3 --area "50,150,1230,670"
+```
+
+For an area chart, use the line output as the top boundary:
+
+```svg
+M first_x,first_y ... L last_x,last_y L last_x,y_max L first_x,y_max Z
+```
+
+Manually compare the calculator output with the coordinates already present in the generated SVG. If coordinates differ, update the SVG from the `calc` output, rerun `svg_quality_checker.py`, then repeat the coordinate review. The tool intentionally does not rewrite SVG files automatically.
+
+### Analyze (inspect existing SVG)
```bash
python3 scripts/svg_position_calculator.py analyze <svg_file>
-python3 scripts/svg_position_calculator.py interactive
-python3 scripts/svg_position_calculator.py calc bar --data "East:185,South:142"
-python3 scripts/svg_position_calculator.py calc pie --data "A:35,B:25,C:20"
-python3 scripts/svg_position_calculator.py from-json config.json
```
-Use this when chart geometry needs to be verified before or after AI generation.
+Use this after SVG generation to inspect existing SVG geometry when manual comparison needs more context.
## Advanced Standalone Tools
diff --git a/skills/ppt-master/scripts/svg_position_calculator.py b/skills/ppt-master/scripts/svg_position_calculator.py
index 00dfd5e3..c6db31a9 100644
--- a/skills/ppt-master/scripts/svg_position_calculator.py
+++ b/skills/ppt-master/scripts/svg_position_calculator.py
@@ -851,18 +851,14 @@ class SVGPositionValidator:
def _extract_attribute(self, content: str, element_id: str, attr: str) -> Optional[float]:
"""Extract attribute value from SVG content"""
- # Find element containing the ID
- pattern = rf'id="{element_id}"[^>]*{attr}="([^"]+)"'
+ pattern = rf'<[^>]*(?<![\w:-])id\s*=\s*([\'"]){re.escape(element_id)}\1[^>]*>'
match = re.search(pattern, content)
-
- if not match:
- # Try reverse order
- pattern = rf'{attr}="([^"]+)"[^>]*id="{element_id}"'
- match = re.search(pattern, content)
-
if match:
+ value = extract_attr(match.group(0), attr)
+ if value is None:
+ return None
try:
- return float(match.group(1))
+ return float(value)
except ValueError:
return None
@@ -888,26 +884,36 @@ class SVGPositionValidator:
positions = {}
# Extract rect elements
- rect_pattern = r'<rect[^>]*(?:id="([^"]*)")?[^>]*x="([^"]*)"[^>]*y="([^"]*)"[^>]*(?:width="([^"]*)")?[^>]*(?:height="([^"]*)")?'
- for match in re.finditer(rect_pattern, svg_content):
- id_val = match.group(1) or f"rect_{len(positions)}"
- positions[id_val] = {
- 'x': float(match.group(2)) if match.group(2) else 0,
- 'y': float(match.group(3)) if match.group(3) else 0,
- }
- if match.group(4):
- positions[id_val]['width'] = float(match.group(4))
- if match.group(5):
- positions[id_val]['height'] = float(match.group(5))
+ for match in re.finditer(r'<rect[^>]*/?>', svg_content):
+ elem = match.group(0)
+ x = extract_attr(elem, 'x')
+ y = extract_attr(elem, 'y')
+ if x is None or y is None:
+ continue
+ id_val = extract_attr(elem, 'id') or f"rect_{len(positions)}"
+ try:
+ positions[id_val] = {'x': float(x), 'y': float(y)}
+ width = extract_attr(elem, 'width')
+ height = extract_attr(elem, 'height')
+ if width is not None:
+ positions[id_val]['width'] = float(width)
+ if height is not None:
+ positions[id_val]['height'] = float(height)
+ except ValueError:
+ continue
# Extract circle elements
- circle_pattern = r'<circle[^>]*(?:id="([^"]*)")?[^>]*cx="([^"]*)"[^>]*cy="([^"]*)"'
- for match in re.finditer(circle_pattern, svg_content):
- id_val = match.group(1) or f"circle_{len(positions)}"
- positions[id_val] = {
- 'cx': float(match.group(2)),
- 'cy': float(match.group(3)),
- }
+ for match in re.finditer(r'<circle[^>]*/?>', svg_content):
+ elem = match.group(0)
+ cx = extract_attr(elem, 'cx')
+ cy = extract_attr(elem, 'cy')
+ if cx is None or cy is None:
+ continue
+ id_val = extract_attr(elem, 'id') or f"circle_{len(positions)}"
+ try:
+ positions[id_val] = {'cx': float(cx), 'cy': float(cy)}
+ except ValueError:
+ continue
return positions
@@ -935,7 +941,8 @@ class SVGPositionValidator:
)
lines.append("")
- lines.append(f"Passed: {passed_count}/{len(results)} ({passed_count/len(results)*100:.1f}%)")
+ pct = passed_count / len(results) * 100 if results else 0
+ lines.append(f"Passed: {passed_count}/{len(results)} ({pct:.1f}%)")
return "\n".join(lines)
@@ -987,9 +994,9 @@ def parse_tuple(s: str) -> Tuple[float, ...]:
def extract_attr(element: str, attr_name: str) -> Optional[str]:
"""Extract attribute value from element string (attribute order independent)"""
- pattern = rf'{attr_name}="([^"]*)"'
+ pattern = rf'(?<![\w:-]){re.escape(attr_name)}\s*=\s*([\'"])(.*?)\1'
match = re.search(pattern, element)
- return match.group(1) if match else None
+ return match.group(2) if match else None
def analyze_svg_file(svg_file: str) -> None:
@@ -1365,6 +1372,7 @@ Common commands:
# validate subcommand
validate_parser = subparsers.add_parser('validate', help='Validate SVG')
validate_parser.add_argument('svg_file', help='SVG file path')
+ validate_parser.add_argument('--expected', help='Expected coordinates JSON file')
validate_parser.add_argument('--extract', action='store_true', help='Extract all position information')
validate_parser.add_argument('--tolerance', type=float, default=1.0, help='Tolerance (pixels)')
@@ -1466,8 +1474,18 @@ Common commands:
print(f"{element_id}:")
for attr, value in attrs.items():
print(f" {attr}: {value}")
+ elif args.expected:
+ import json
+ expected_path = Path(args.expected)
+ if not expected_path.exists():
+ print(f"[Error] Expected coordinates file does not exist: {args.expected}")
+ return
+ with open(expected_path, 'r', encoding='utf-8') as f:
+ expected_coords = json.load(f)
+ results = validator.validate_from_file(args.svg_file, expected_coords)
+ print(validator.format_results(results))
else:
- print("Validation mode requires an expected coordinates file; use --extract to extract coordinates first")
+ print("Validation mode requires --expected <json_file>; use --extract to extract coordinates first")
elif args.command == 'analyze':
analyze_svg_file(args.svg_file)