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): best-match-only default, review copies, manual replace

hugohe30d06ff2dac46
diff --git a/skills/ppt-master/scripts/image_search.py b/skills/ppt-master/scripts/image_search.py
index c4d6785d..eb5497fa 100644
--- a/skills/ppt-master/scripts/image_search.py
+++ b/skills/ppt-master/scripts/image_search.py
@@ -199,12 +199,38 @@ def _validate_downloaded_quality(path: Path) -> bool:
return True # unreadable image; let downstream handle it
+def _write_review_copy(
+ src: Path, dest_dir: Path, name: str, max_side: int = 1024
+) -> Optional[Path]:
+ """Write a downscaled JPEG review copy of ``src`` into ``dest_dir``.
+
+ The placed / promoted asset is always the full-resolution original; this
+ bounded copy exists only so the agent can Read a sanely-sized image to
+ confirm suitability regardless of how large the source is. Best-effort —
+ returns None (non-fatal) if Pillow or the source is unavailable.
+ """
+ try:
+ from PIL import Image # type: ignore
+ except ImportError:
+ return None
+ try:
+ dest_dir.mkdir(parents=True, exist_ok=True)
+ review_path = dest_dir / f"{Path(name).stem}.jpg"
+ with Image.open(src) as im:
+ im = im.convert("RGB")
+ im.thumbnail((max_side, max_side))
+ im.save(review_path, "JPEG", quality=85)
+ return review_path
+ except (OSError, ValueError):
+ return None
+
+
def _save_candidates_pool(
ranked: list[tuple[float, str, AssetCandidate]],
output_dir: Path,
stem: str,
selected_filename: str,
- max_candidates: int = 8,
+ max_candidates: int = 4,
) -> None:
"""Download top-N candidates into ``candidates/<stem>/`` and write
a ``candidates.json`` manifest for manual review."""
@@ -232,10 +258,12 @@ def _save_candidates_pool(
continue
idx += 1
actual_dim = _measure_actual_image(cand_path)
+ review_path = _write_review_copy(cand_path, cand_dir / "review", cand_filename)
pool.append({
"rank": idx,
"score": round(score, 2),
"filename": cand_filename,
+ "review": f"review/{review_path.name}" if review_path else None,
"provider": provider_name,
"title": candidate.title,
"author": candidate.author,
@@ -245,6 +273,7 @@ def _save_candidates_pool(
"license_url": candidate.license_url,
"license_tier": candidate.license_tier,
"attribution_required": candidate.license_tier == "attribution-required",
+ "attribution_text": build_attribution_text(selected_filename, candidate),
"width": actual_dim[0] if actual_dim else candidate.width,
"height": actual_dim[1] if actual_dim else candidate.height,
})
@@ -270,13 +299,15 @@ def search_and_download(
*,
output_path: Path,
strict_no_attribution: bool,
- save_candidates: bool = True,
- max_candidates: int = 8,
+ save_candidates: bool = False,
+ max_candidates: int = 4,
) -> tuple[Optional[AssetCandidate], Optional[str], Optional[str]]:
"""Find a candidate AND successfully download it.
- When ``save_candidates`` is True (default), the top-N candidates are
- also saved to ``candidates/<stem>/`` for manual review.
+ By default only the best match is downloaded. When ``save_candidates``
+ is True (opt-in), the top-N candidates are also saved to
+ ``candidates/<stem>/`` so the agent can review and ``--promote`` a
+ better fit when the best match does not pass visual confirmation.
Returns ``(candidate, provider_name, stage)`` for the successfully
downloaded image, or ``(None, None, None)`` if every combination
@@ -332,6 +363,11 @@ def search_and_download(
if not _validate_downloaded_quality(output_path):
output_path.unlink(missing_ok=True)
continue
+ review = _write_review_copy(
+ output_path, output_path.parent / ".review", output_path.name
+ )
+ if review is not None:
+ print(f" review copy: {review}", file=sys.stderr)
return candidate, provider_name, stage
except (requests.RequestException, OSError, RuntimeError, ValueError) as exc:
print(
@@ -520,6 +556,9 @@ def promote_candidate(
shutil.copy2(str(src_path), str(dst_path))
print(f" promoted: {candidate_filename} → {target_filename}", file=sys.stderr)
+ review = _write_review_copy(dst_path, output_dir / ".review", target_filename)
+ if review is not None:
+ print(f" review copy: {review}", file=sys.stderr)
# Update candidates.json
meta["selected"] = candidate_filename
@@ -546,6 +585,23 @@ def promote_candidate(
item["license_url"] = entry.get("license_url", "")
item["license_tier"] = entry["license_tier"]
item["attribution_required"] = entry.get("attribution_required", False)
+ # Recompute the credit from the promoted candidate — never carry the
+ # replaced image's attribution_text (wrong author/title/source).
+ item["attribution_text"] = build_attribution_text(
+ target_filename,
+ AssetCandidate(
+ provider=entry.get("provider", ""),
+ title=entry.get("title", ""),
+ source_page_url=entry.get("source_page_url", ""),
+ license_name=entry.get("license_name", ""),
+ license_url=entry.get("license_url", ""),
+ license_tier=entry.get("license_tier", ""),
+ width=w,
+ height=h,
+ download_url=entry.get("download_url", ""),
+ author=entry.get("author", ""),
+ ),
+ )
item["width"] = w
item["height"] = h
item.pop("metadata_dimensions", None)
@@ -560,6 +616,82 @@ def promote_candidate(
return 0
+# ---------------------------------------------------------------------------
+# Manual URL replacement (model-agnostic)
+# ---------------------------------------------------------------------------
+
+
+def fetch_url_replace(
+ output_dir: Path,
+ target_filename: str,
+ url: str,
+ manifest_path: Optional[Path] = None,
+ *,
+ slide: str = "",
+ purpose: str = "",
+ search_query: str = "",
+ orientation: str = "",
+) -> int:
+ """Download a user-supplied image URL into the target and record it.
+
+ The model-agnostic manual path: when an automated best match is not
+ suitable (or the running model cannot see images at all), a human finds a
+ good image, passes its URL, and it replaces the target. License is unknown
+ for an arbitrary URL, so the manifest marks it ``manual`` and notes that
+ verifying usage rights is the user's responsibility.
+ """
+ output_dir.mkdir(parents=True, exist_ok=True)
+ dst_path = output_dir / target_filename
+ try:
+ download_image(url, str(dst_path), headers={"User-Agent": USER_AGENT})
+ except (requests.RequestException, OSError, RuntimeError, ValueError) as exc:
+ print(f"Error: failed to download {url}: {exc}", file=sys.stderr)
+ return 1
+ if not dst_path.exists():
+ print(f"Error: download produced no file at {dst_path}", file=sys.stderr)
+ return 1
+
+ print(f" fetched: {url} -> {target_filename}", file=sys.stderr)
+ review = _write_review_copy(dst_path, output_dir / ".review", target_filename)
+ if review is not None:
+ print(f" review copy: {review}", file=sys.stderr)
+
+ actual_dim = _measure_actual_image(dst_path)
+ mpath = manifest_path or default_manifest_path(str(output_dir))
+ # Inherit page context (which slide / purpose / query this image serves)
+ # from the entry being replaced; override only source / license / size /
+ # status so the audit trail survives a manual swap.
+ prior = next(
+ (i for i in _read_existing_manifest(mpath).get("items", [])
+ if i.get("filename") == target_filename),
+ {},
+ )
+ item = {
+ "filename": target_filename,
+ "slide": prior.get("slide") or slide,
+ "purpose": prior.get("purpose") or purpose,
+ "search_query": prior.get("search_query") or search_query,
+ "orientation": prior.get("orientation") or orientation,
+ "provider": "manual",
+ "title": "",
+ "author": "",
+ "source_page_url": url,
+ "download_url": url,
+ "license_name": "unverified — user-supplied URL",
+ "license_url": "",
+ "license_tier": "manual",
+ "attribution_required": False,
+ "width": actual_dim[0] if actual_dim else 0,
+ "height": actual_dim[1] if actual_dim else 0,
+ "attribution_text": "",
+ "status": "manual",
+ "note": "Manually supplied image URL; verifying usage rights is the user's responsibility.",
+ }
+ written = write_sources_manifest(mpath, item)
+ print(f" manifest updated: {written}", file=sys.stderr)
+ return 0
+
+
# ---------------------------------------------------------------------------
# Batch mode (`--batch image_queries.json`)
# ---------------------------------------------------------------------------
@@ -819,7 +951,8 @@ def build_parser() -> argparse.ArgumentParser:
default=None,
help=(
"Local filename for the chosen image (e.g. cover_bg.jpg). "
- "Required for single-query and --promote modes; ignored in --batch."
+ "Required for single-query, --promote, and --from-url modes; "
+ "ignored in --batch."
),
)
parser.add_argument(
@@ -900,15 +1033,20 @@ def build_parser() -> argparse.ArgumentParser:
),
)
parser.add_argument(
- "--no-candidates",
+ "--save-candidates",
action="store_true",
- help="Disable candidate pool saving (only download the best match).",
+ help=(
+ "Opt-in: also save a small candidate pool to candidates/<stem>/ "
+ "(with downscaled review copies) so a better fit can be promoted "
+ "when the best match fails visual confirmation. Default: only the "
+ "best match is downloaded."
+ ),
)
parser.add_argument(
"--max-candidates",
type=int,
- default=8,
- help="Max number of candidates to save (default: 8).",
+ default=4,
+ help="Max candidates to save when --save-candidates is set (default: 4).",
)
parser.add_argument(
"--promote",
@@ -919,6 +1057,16 @@ def build_parser() -> argparse.ArgumentParser:
"Example: --promote candidate_03.jpg --filename 05_wulong.jpg -o images/"
),
)
+ parser.add_argument(
+ "--from-url",
+ default=None,
+ metavar="URL",
+ help=(
+ "Manual replacement: download a user-supplied image URL into "
+ "--filename and record it (license marked 'manual'). Works without "
+ "a multimodal model. Example: --from-url https://… --filename team.jpg -o images/"
+ ),
+ )
return parser
@@ -953,6 +1101,21 @@ def main(argv: Optional[list[str]] = None) -> int:
manifest_path=Path(args.manifest) if args.manifest else None,
)
+ # --- Manual URL replacement ---
+ if args.from_url:
+ if not args.filename:
+ parser.error("--filename is required with --from-url")
+ return fetch_url_replace(
+ output_dir,
+ args.filename,
+ args.from_url,
+ manifest_path=Path(args.manifest) if args.manifest else None,
+ slide=args.slide,
+ purpose=args.purpose,
+ search_query=args.query or "",
+ orientation="" if args.orientation == "any" else args.orientation,
+ )
+
# --- Batch mode ---
if args.batch:
if not os.path.isfile(args.batch):
@@ -978,7 +1141,7 @@ def main(argv: Optional[list[str]] = None) -> int:
output_dir=batch_output_dir,
sources_manifest_path=sources_manifest_path,
concurrency=_resolve_search_concurrency(args.concurrency),
- save_candidates=not args.no_candidates,
+ save_candidates=args.save_candidates,
max_candidates=args.max_candidates,
default_provider=args.provider,
default_strict=args.strict_no_attribution,
@@ -995,7 +1158,7 @@ def main(argv: Optional[list[str]] = None) -> int:
# --- Single-query search mode ---
if not args.query:
- parser.error("query is required unless --batch or --promote is used")
+ parser.error("query is required unless --batch, --promote, or --from-url is used")
if not args.filename:
parser.error("--filename is required in single-query mode")
@@ -1020,7 +1183,7 @@ def main(argv: Optional[list[str]] = None) -> int:
request,
output_path=output_path,
strict_no_attribution=args.strict_no_attribution,
- save_candidates=not args.no_candidates,
+ save_candidates=args.save_candidates,
max_candidates=args.max_candidates,
)