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(image-search): prioritize quality-first sourcing with attribution checks

hugohe3928511fb1297
diff --git a/README.md b/README.md
index 7acc2098..a4521b1b 100644
--- a/README.md
+++ b/README.md
@@ -219,7 +219,7 @@ Two paths for non-user images, mixable per row in the same deck:
**A) AI generation** — `image_gen.py`. Copy `.env.example` to `.env`, set `IMAGE_BACKEND` plus the provider's `*_API_KEY` (`OPENAI_API_KEY`, `GEMINI_API_KEY`, etc.), and the pipeline calls it automatically. Run `python3 skills/ppt-master/scripts/image_gen.py --list-backends` for the full backend list. `gpt-image-2` is currently the best default.
-**B) Web image search** — `image_search.py`. **Zero-config**, no API key. Searches openly-licensed images across Openverse and Wikimedia Commons; defaults to CC0 / Public Domain so the deck stays clean. Falls back to CC BY / CC BY-SA only when nothing in the public domain matches — Executor then adds a small inline credit on those slides. Optional `PEXELS_API_KEY` / `PIXABAY_API_KEY` (both free) broaden the chain.
+**B) Web image search** — `image_search.py`. **Zero-config**, no API key. Searches openly-licensed images across Openverse and Wikimedia Commons; when `PEXELS_API_KEY` / `PIXABAY_API_KEY` (both free) are configured, the default provider chain also appends Pexels / Pixabay. The default is quality-first: CC0, Public Domain, Pexels / Pixabay no-attribution licenses, CC BY, and CC BY-SA are considered together, and Executor adds a small inline credit whenever the selected image requires attribution. Use `--strict-no-attribution` only when a slide cannot tolerate any credit line. Note: web image search is best treated as a fast fallback. Image quality, resolution, composition, and topic fit depend on the open image sources themselves, so results are usually less polished than user-provided high-resolution assets or AI-generated images. For high-impact covers, product shots, portraits, and branded scenes, prefer source images or AI generation.
> Full reference: [`image-generator.md`](./skills/ppt-master/references/image-generator.md) (AI) · [`image-searcher.md`](./skills/ppt-master/references/image-searcher.md) (web).
diff --git a/README_CN.md b/README_CN.md
index 14e059df..452b0a3c 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -223,7 +223,7 @@ AI 全程处理——内容分析、视觉设计、SVG 生成、PPTX 导出。
**A) AI 生图** — `image_gen.py`。`cp .env.example .env`,设置 `IMAGE_BACKEND` 和对应 `*_API_KEY`(`OPENAI_API_KEY`、`GEMINI_API_KEY` 等),流程会自动调用。`python3 skills/ppt-master/scripts/image_gen.py --list-backends` 查看完整后端清单。`gpt-image-2` 目前综合质量最佳。
-**B) 网络图片搜索** — `image_search.py`。**零配置**、无需 API Key。在 Openverse 和 Wikimedia Commons 中搜索开放许可可商用图片;默认只搜 CC0 / 公有领域以保持视觉干净。只有公有领域找不到合适图时才回落到 CC BY / CC BY-SA,并由 Executor 在该幻灯片自动添加小字署名。可选的 `PEXELS_API_KEY` / `PIXABAY_API_KEY`(都免费申请)能扩展搜索范围。
+**B) 网络图片搜索** — `image_search.py`。**零配置**、无需 API Key。在 Openverse 和 Wikimedia Commons 中搜索开放许可可商用图片;如果配置了 `PEXELS_API_KEY` / `PIXABAY_API_KEY`(都免费申请),默认搜索链会继续追加 Pexels / Pixabay。默认以图片质量和匹配度优先,直接把 CC0、公有领域、Pexels / Pixabay 免署名许可、CC BY、CC BY-SA 一起纳入候选;如果选中的图片需要署名,Executor 会在该幻灯片自动添加小字署名。只有明确不能出现署名时,才使用 `--strict-no-attribution` 限制为免署名图片。注意:网络搜索图片适合作为快速兜底,但画质、尺寸、构图和主题匹配度取决于开放图库本身,整体质量通常不如用户自带高清素材或 AI 生图;对视觉要求高的封面、产品图、人物图和品牌场景,建议优先提供原始图片或使用 AI 生图。
> 完整说明:[`image-generator.md`](./skills/ppt-master/references/image-generator.md)(AI)·[`image-searcher.md`](./skills/ppt-master/references/image-searcher.md)(网络)。
diff --git a/skills/ppt-master/references/executor-base.md b/skills/ppt-master/references/executor-base.md
index 4fde93d0..ed6c03d1 100644
--- a/skills/ppt-master/references/executor-base.md
+++ b/skills/ppt-master/references/executor-base.md
@@ -259,6 +259,8 @@ The credit text is **not** rendered by post-processing or export — it must be
Use `attribution_text` from the manifest entry as the **starting point**, then compress for the small-text constraint (drop URL, drop filename, keep "via Provider / License"). For CC0/PD images that landed in the `attribution-required` tier only because of upstream metadata quirks (rare), credits are still safe to render.
+`svg_quality_checker.py` treats missing CC BY / CC BY-SA inline attribution as an **error**. Fix the offending SVG before post-processing.
+
**The manifest is the single source of truth for credits.** Do not duplicate license info into speaker notes or any other artifact.
---
diff --git a/skills/ppt-master/references/image-searcher.md b/skills/ppt-master/references/image-searcher.md
index 887ac755..2dcfc5da 100644
--- a/skills/ppt-master/references/image-searcher.md
+++ b/skills/ppt-master/references/image-searcher.md
@@ -28,18 +28,18 @@ Every accepted image is classified into one of two tiers. Anything else is rejec
---
-## 2. Two-Stage Search Strategy
+## 2. Search Strategy
-Default: prefer no-attribution images so the deck stays visually clean. Fall back to attribution-required only when the public domain has no match.
+Default: quality-first across all allowed license tiers. Do not prefer CC0 / Public Domain over a better CC BY / CC BY-SA image; rely on the manifest's `license_tier` so Executor can add attribution only when needed.
```
-Stage 1: ALL providers, license filter = cc0,pdm,pexels,pixabay
- → first hit wins, done.
-Stage 2: ALL providers, license filter += cc by, cc by-sa
- → flag chosen item as attribution-required.
+Default: provider chain, license filter = cc0,pdm,pexels,pixabay,cc by,cc by-sa
+ → rank candidates across providers; first downloadable ranked hit wins.
+Strict: provider chain, license filter = cc0,pdm,pexels,pixabay
+ → fail if no no-attribution image can be downloaded.
```
-`--strict-no-attribution` skips Stage 2 and exits non-zero if Stage 1 finds nothing. Use when the deck cannot tolerate any on-slide credit (corporate template, full-bleed hero).
+`--strict-no-attribution` is opt-in. Use it only when the deck cannot tolerate any on-slide credit (corporate template, full-bleed hero).
---
@@ -102,7 +102,7 @@ python3 scripts/image_search.py "<query>" \
| `--purpose` | no | `""` | `background` / `hero` / `side` / `accent` |
| `--orientation` | no | `any` | `any` / `landscape` / `portrait` / `square` |
| `--provider` | no | (chain) | Pin one provider |
-| `--strict-no-attribution` | no | off | Skip Stage 2; refuse CC BY / CC BY-SA |
+| `--strict-no-attribution` | no | off | Restrict to no-attribution licenses; refuse CC BY / CC BY-SA |
| `--manifest` | no | (default) | Override manifest path |
**Pacing (mandatory)**: one search at a time. Wikimedia/Openverse expect identifying User-Agent and reasonable rate (~1 req/sec). Default pacing is fine.
@@ -125,7 +125,7 @@ Every successful download appends or replaces one entry keyed on `filename`:
"search_query": "executive boardroom meeting",
"orientation": "landscape",
"provider": "openverse",
- "stage": "no-attribution-only",
+ "stage": "all",
"title": "Untitled",
"author": "",
"source_page_url": "https://www.rawpixel.com/...",
@@ -155,7 +155,7 @@ Every successful download appends or replaces one entry keyed on `filename`:
| `license_tier` | Drives Executor's attribution decision. Only `no-attribution` / `attribution-required`. |
| `attribution_required` | Boolean alias of `license_tier == "attribution-required"`. |
| `attribution_text` | Pre-rendered canonical credit string. **Use as-is; do not regenerate.** |
-| `stage` | `no-attribution-only` or `all`. Useful for auditing fallbacks. |
+| `stage` | `all` by default, or `no-attribution-only` when strict mode is used. |
> Manifest is **idempotent on `filename`**. Rerunning the CLI replaces that entry; other entries are preserved.
@@ -237,6 +237,8 @@ Executor reads `image_sources.json` per slide that uses a Sourced image. For eac
Executor does not interpret raw license strings — `license_tier` is sufficient.
+`svg_quality_checker.py` verifies this handoff before post-processing: if an attribution-required image is referenced without visible `CC BY` / `CC BY-SA` credit text, the SVG fails the quality gate.
+
---
## 11. Task Completion Checkpoint
@@ -245,5 +247,6 @@ In addition to the shared checkpoint in [`image-base.md`](./image-base.md) §10:
- [ ] Every web row has a downloaded file at `project/images/<filename>` OR is marked `Needs-Manual`
- [ ] Each `Sourced` row has a manifest entry with valid `license_tier` and non-empty `attribution_text`
+- [ ] Any `attribution-required` image has visible inline credit text in the corresponding SVG
- [ ] `metadata_dimensions` warnings surfaced when downloaded preview is much smaller than upstream-claimed size
- [ ] `Needs-Manual` rows include the failure reason
diff --git a/skills/ppt-master/scripts/docs/image.md b/skills/ppt-master/scripts/docs/image.md
index 07da71c1..0cc71508 100644
--- a/skills/ppt-master/scripts/docs/image.md
+++ b/skills/ppt-master/scripts/docs/image.md
@@ -105,11 +105,10 @@ Providers (Openverse and Wikimedia work with no key; Pexels and Pixabay are opti
Default search chain (when `--provider` is unset): zero-config providers first, then keyed providers whose API key is set in the environment. Keyed providers without a key are silently skipped.
-Two-stage license filter:
+License filter:
-- **Stage 1 (default)**: search all providers with `cc0,pdm,pexels,pixabay` filter — no on-slide attribution needed.
-- **Stage 2 (fallback)**: re-run with `cc by, cc by-sa` added; the chosen image is flagged `attribution-required` so the Executor adds an inline credit on the slide.
-- `--strict-no-attribution` skips Stage 2 — useful for full-bleed hero images or templates that cannot host a credit element.
+- **Default**: search all providers with `cc0,pdm,pexels,pixabay,cc by,cc by-sa` allowed together. The chosen image may be `no-attribution` or `attribution-required`; Executor adds an inline credit only when needed.
+- `--strict-no-attribution` restricts the search to `cc0,pdm,pexels,pixabay` — useful for full-bleed hero images or templates that cannot host a credit element.
Pin a provider, refuse attribution, or override the manifest path:
@@ -119,7 +118,7 @@ python3 scripts/image_search.py "Olympics opening ceremony" \
--filename event.jpg --provider wikimedia \
--orientation landscape -o projects/demo/images
-# Strict mode — refuse CC BY / CC BY-SA, fail rather than fall back
+# Strict mode — refuse CC BY / CC BY-SA
python3 scripts/image_search.py "abstract gradient" \
--filename hero.jpg --strict-no-attribution \
-o projects/demo/images
diff --git a/skills/ppt-master/scripts/image_search.py b/skills/ppt-master/scripts/image_search.py
index f4f75c73..c67accec 100644
--- a/skills/ppt-master/scripts/image_search.py
+++ b/skills/ppt-master/scripts/image_search.py
@@ -7,21 +7,20 @@ single best match.
Workflow:
1. Build an :class:`ImageSearchRequest` from CLI args.
- 2. Two-stage license-tier search:
- - Stage 1: ask each provider for ``no-attribution-only`` matches
- (CC0, Public Domain, Pexels, Pixabay). If any provider returns
- candidates, pick the highest-scoring one and stop.
- - Stage 2 (only if stage 1 yielded nothing AND
- ``--strict-no-attribution`` was NOT set): retry with the ``all``
- filter, accepting CC BY / CC BY-SA. The chosen image is recorded
- with ``license_tier == "attribution-required"`` so the Executor
- knows to add an inline credit on the slide.
+ 2. Quality-first license search:
+ - Default: ask each provider for ``all`` allowed matches (CC0,
+ Public Domain, Pexels, Pixabay, CC BY, CC BY-SA), pick the
+ highest-scoring downloadable candidate, and record whether it
+ needs attribution.
+ - Strict mode: when ``--strict-no-attribution`` is set, ask only
+ for ``no-attribution-only`` matches and fail if none can be
+ downloaded.
3. Download the chosen image into ``--output``.
4. Append a record to ``image_sources.json`` (the single source of
truth for downstream credit rendering).
Examples:
- # Default: zero-config, prefers no-attribution images
+ # Default: zero-config, quality-first across allowed licenses
python3 scripts/image_search.py "offshore wind farm" \
--filename cover_bg.jpg --slide 01_cover \
--orientation landscape -o projects/demo/images
@@ -116,8 +115,8 @@ def _load_provider(name: str):
def _is_keyed_provider_unconfigured(provider_name: str, exc: Exception) -> bool:
- """Treat 'API key missing' as a non-fatal skip (so default fallback
- can keep going through the other providers)."""
+ """Treat 'API key missing' as a non-fatal skip so the default provider
+ chain can keep going."""
if provider_name not in KEYED_PROVIDERS:
return False
return "API_KEY" in str(exc)
@@ -147,7 +146,7 @@ def _try_provider(
return None
-def two_stage_search(
+def search_and_download(
providers: list[str],
request: ImageSearchRequest,
*,
@@ -156,55 +155,62 @@ def two_stage_search(
) -> tuple[Optional[AssetCandidate], Optional[str], Optional[str]]:
"""Find a candidate AND successfully download it.
- Iterates ``stages × providers × ranked candidates`` and returns the
- first candidate whose ``download_url`` actually transfers. A candidate
- that 403s, 404s, or otherwise fails to download is skipped and the
- next-best one is tried — so a single dead asset cannot fail the whole
- request.
+ Iterates ``filters × providers``, ranks all candidates returned in the
+ same filter globally, then returns the first candidate whose
+ ``download_url`` actually transfers. A candidate that 403s, 404s, or
+ otherwise fails to download is skipped and the next-best one is tried —
+ so a single dead asset cannot fail the whole request.
Returns ``(candidate, provider_name, stage)`` for the successfully
downloaded image, or ``(None, None, None)`` if every combination
failed.
"""
- stages: list[str] = ["no-attribution-only"]
- if not strict_no_attribution:
- stages.append("all")
+ license_filters: list[str] = (
+ ["no-attribution-only"] if strict_no_attribution else ["all"]
+ )
- for stage in stages:
+ for stage in license_filters:
+ ranked: list[tuple[float, str, AssetCandidate]] = []
for provider_name in providers:
print(f" -> trying {provider_name} ({stage}) ...", file=sys.stderr)
candidates = _try_provider(provider_name, request, stage)
if not candidates:
continue
- # Score and rank; drop candidates rejected by score_candidate
+ # Score candidates; drop candidates rejected by score_candidate
# (score == -inf — typically zero relevance against the query).
- scored = [(score_candidate(c, request), c) for c in candidates]
- ranked = [
- c for s, c in sorted(scored, key=lambda sc: sc[0], reverse=True)
- if s != float("-inf")
+ provider_ranked = [
+ (score_candidate(c, request), provider_name, c) for c in candidates
+ ]
+ provider_ranked = [
+ item for item in provider_ranked if item[0] != float("-inf")
]
- if not ranked:
+ if not provider_ranked:
print(
f" no candidate matched the query; trying next provider/stage",
file=sys.stderr,
)
continue
-
- for candidate in ranked:
- try:
- download_image(
- candidate.download_url,
- str(output_path),
- headers={"User-Agent": USER_AGENT},
- )
- return candidate, provider_name, stage
- except (requests.RequestException, OSError, RuntimeError, ValueError) as exc:
- print(
- f" download failed for {candidate.title!r}: {exc}",
- file=sys.stderr,
- )
- continue
+ ranked.extend(provider_ranked)
+
+ for _score, provider_name, candidate in sorted(
+ ranked,
+ key=lambda item: item[0],
+ reverse=True,
+ ):
+ try:
+ download_image(
+ candidate.download_url,
+ str(output_path),
+ headers={"User-Agent": USER_AGENT},
+ )
+ return candidate, provider_name, stage
+ except (requests.RequestException, OSError, RuntimeError, ValueError) as exc:
+ print(
+ f" download failed for {candidate.title!r}: {exc}",
+ file=sys.stderr,
+ )
+ continue
return None, None, None
@@ -392,8 +398,8 @@ def build_parser() -> argparse.ArgumentParser:
"--strict-no-attribution",
action="store_true",
help=(
- "Refuse CC BY / CC BY-SA results. If no CC0/Public Domain match is "
- "found, exit non-zero rather than falling back to attribution-required."
+ "Refuse CC BY / CC BY-SA results. If no attribution-free match is "
+ "downloadable, exit non-zero."
),
)
parser.add_argument(
@@ -436,7 +442,7 @@ def main(argv: Optional[list[str]] = None) -> int:
output_path = output_dir / args.filename
print(f"Searching providers: {', '.join(providers)}", file=sys.stderr)
- candidate, provider_name, stage = two_stage_search(
+ candidate, provider_name, stage = search_and_download(
providers,
request,
output_path=output_path,
@@ -446,8 +452,8 @@ def main(argv: Optional[list[str]] = None) -> int:
if candidate is None:
print(
"No acceptable candidates could be downloaded across all "
- "providers/stages. Try a shorter query, drop "
- "--strict-no-attribution, or set an API key for a keyed provider.",
+ "providers/filters. Try a shorter query, use default attribution "
+ "mode if strict mode is enabled, or set an API key for a keyed provider.",
file=sys.stderr,
)
return 1
diff --git a/skills/ppt-master/scripts/image_sources/provider_common.py b/skills/ppt-master/scripts/image_sources/provider_common.py
index 9039a795..f79d0875 100644
--- a/skills/ppt-master/scripts/image_sources/provider_common.py
+++ b/skills/ppt-master/scripts/image_sources/provider_common.py
@@ -367,11 +367,6 @@ def score_candidate(candidate: AssetCandidate, request: ImageSearchRequest) -> f
score = relevance * 10000.0
- # No-attribution preference is a tie-breaker, not a steamroller —
- # keeping it small lets a strongly-relevant CC BY beat an irrelevant CC0.
- if candidate.license_tier == LICENSE_TIER_NO_ATTRIBUTION:
- score += 500.0
-
candidate_orientation = normalize_orientation(candidate.width, candidate.height)
requested = (request.orientation or "").strip().lower()
if requested:
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index d3e18ae0..5f8d3f4e 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -12,6 +12,8 @@ Usage:
import sys
import re
+import json
+import html
from pathlib import Path
from typing import List, Dict, Tuple
from collections import defaultdict
@@ -65,6 +67,7 @@ class SVGQualityChecker:
'sizes': defaultdict(set),
}
self._lock_seen = False # True once we locate at least one spec_lock.md
+ self._source_manifest_cache: Dict[Path, Dict] = {}
def check_file(self, svg_file: str, expected_format: str = None) -> Dict:
"""
@@ -127,6 +130,9 @@ class SVGQualityChecker:
# 7. Check spec_lock drift (colors / font-family / font-size)
self._check_spec_lock_drift(content, svg_path, result)
+ # 8. Check web-sourced image attribution
+ self._check_sourced_image_attribution(content, svg_path, result)
+
# Determine pass/fail
result['passed'] = len(result['errors']) == 0
@@ -568,6 +574,70 @@ class SVGQualityChecker:
"(see drift summary for details)"
)
+ def _find_image_sources_manifest(self, svg_path: Path) -> Path | None:
+ """Locate image_sources.json for a project SVG.
+
+ Quality checks run primarily on <project>/svg_output/*.svg, but this
+ also supports SVGs checked from project root or svg_final.
+ """
+ bases = (svg_path.parent, svg_path.parent.parent, svg_path.parent.parent.parent)
+ for base in bases:
+ candidate = base / 'images' / 'image_sources.json'
+ if candidate.exists():
+ return candidate
+ return None
+
+ def _load_image_sources_manifest(self, svg_path: Path) -> Dict:
+ manifest_path = self._find_image_sources_manifest(svg_path)
+ if manifest_path is None:
+ return {}
+ if manifest_path in self._source_manifest_cache:
+ return self._source_manifest_cache[manifest_path]
+ try:
+ payload = json.loads(manifest_path.read_text(encoding='utf-8'))
+ except (OSError, json.JSONDecodeError):
+ payload = {}
+ self._source_manifest_cache[manifest_path] = payload
+ return payload
+
+ def _check_sourced_image_attribution(self, content: str, svg_path: Path, result: Dict):
+ """Require visible credit text for attribution-required web images.
+
+ image_search.py records the legal tier in images/image_sources.json;
+ Executor must render compact credit text into the SVG. This check
+ prevents a quality-first CC BY / CC BY-SA image from silently reaching
+ export without attribution.
+ """
+ manifest = self._load_image_sources_manifest(svg_path)
+ items = manifest.get('items') or []
+ if not items:
+ return
+
+ text_content = html.unescape(re.sub(r'<[^>]+>', ' ', content))
+ text_content = re.sub(r'\s+', ' ', text_content)
+ svg_stem = svg_path.stem
+
+ for item in items:
+ if not item.get('attribution_required') and item.get('license_tier') != 'attribution-required':
+ continue
+
+ filename = Path(str(item.get('filename') or '')).name
+ slide = str(item.get('slide') or '').strip()
+ referenced = bool(filename and filename in content)
+ same_slide = bool(slide and slide == svg_stem)
+ if not referenced and not same_slide:
+ continue
+
+ license_name = str(item.get('license_name') or '').upper()
+ license_token = 'CC BY-SA' if 'BY-SA' in license_name else 'CC BY'
+ has_credit = license_token in text_content.upper()
+ if not has_credit:
+ result['errors'].append(
+ f"Missing inline attribution for sourced image {filename or '(unknown)'} "
+ f"({license_token}). Add compact credit text per "
+ f"references/image-searcher.md §7."
+ )
+
@staticmethod
def _normalize_size(value: str) -> str:
"""Normalize a font-size value for comparison: lowercase, strip spaces,