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: add zero-config web image search with license-tier filtering

hugohe340bc8803273f
diff --git a/skills/ppt-master/scripts/image_search.py b/skills/ppt-master/scripts/image_search.py
new file mode 100644
index 00000000..75ff3f8b
--- /dev/null
+++ b/skills/ppt-master/scripts/image_search.py
@@ -0,0 +1,497 @@
+#!/usr/bin/env python3
+"""Web image search CLI.
+
+Sister tool to ``image_gen.py``: instead of generating an image from a
+prompt, this searches openly-licensed image providers and downloads a
+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.
+ 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
+ python3 scripts/image_search.py "offshore wind farm" \
+ --filename cover_bg.jpg --slide 01_cover \
+ --orientation landscape -o projects/demo/images
+
+ # Strict mode: refuse anything that would require attribution
+ python3 scripts/image_search.py "abstract gradient" \
+ --filename hero.jpg --strict-no-attribution \
+ -o projects/demo/images
+
+ # Pin a specific provider (useful when an API key is set)
+ python3 scripts/image_search.py "executive meeting" \
+ --filename team.jpg --provider pexels \
+ --orientation landscape -o projects/demo/images
+"""
+
+from __future__ import annotations
+
+import argparse
+import importlib
+import json
+import os
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Optional
+
+import requests
+
+# Make sibling modules importable when this script is invoked directly.
+_SCRIPTS_DIR = Path(__file__).resolve().parent
+if str(_SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(_SCRIPTS_DIR))
+
+from image_backends.backend_common import download_image # noqa: E402
+from image_sources.provider_common import ( # noqa: E402
+ AssetCandidate,
+ ImageSearchRequest,
+ USER_AGENT,
+ build_attribution_text,
+ ensure_json_parent,
+ score_candidate,
+)
+
+
+# ---------------------------------------------------------------------------
+# Provider registry
+# ---------------------------------------------------------------------------
+
+PROVIDER_MODULES: dict[str, str] = {
+ "openverse": "image_sources.provider_openverse",
+ "wikimedia": "image_sources.provider_wikimedia",
+ "pexels": "image_sources.provider_pexels",
+ "pixabay": "image_sources.provider_pixabay",
+}
+
+# Providers that work without configuration. ``image_search.py`` defaults
+# to these so a fresh clone can search immediately.
+ZERO_CONFIG_PROVIDERS: tuple[str, ...] = ("openverse", "wikimedia")
+KEYED_PROVIDERS: tuple[str, ...] = ("pexels", "pixabay")
+ALL_PROVIDERS: tuple[str, ...] = ZERO_CONFIG_PROVIDERS + KEYED_PROVIDERS
+
+ORIENTATION_CHOICES = ("any", "landscape", "portrait", "square")
+
+
+# ---------------------------------------------------------------------------
+# .env loading (lightweight; matches image_gen.py behavior)
+# ---------------------------------------------------------------------------
+
+
+def _load_dotenv_if_available() -> None:
+ """Best-effort .env loading: cwd then repo root. Silently no-op if
+ python-dotenv isn't installed or no file is found."""
+ try:
+ from dotenv import load_dotenv # type: ignore
+ except ImportError:
+ return
+ cwd_env = Path.cwd() / ".env"
+ if cwd_env.is_file():
+ load_dotenv(cwd_env, override=False)
+ repo_env = _SCRIPTS_DIR.parent.parent.parent / ".env"
+ if repo_env.is_file():
+ load_dotenv(repo_env, override=False)
+
+
+# ---------------------------------------------------------------------------
+# Provider dispatch
+# ---------------------------------------------------------------------------
+
+
+def _load_provider(name: str):
+ return importlib.import_module(PROVIDER_MODULES[name])
+
+
+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)."""
+ if provider_name not in KEYED_PROVIDERS:
+ return False
+ return "API_KEY" in str(exc)
+
+
+def _try_provider(
+ name: str,
+ request: ImageSearchRequest,
+ license_tier_filter: str,
+) -> Optional[list[AssetCandidate]]:
+ """Run one provider; print and swallow recoverable errors, return None
+ so the dispatcher can try the next provider."""
+ try:
+ module = _load_provider(name)
+ return module.search(request, license_tier_filter=license_tier_filter)
+ except RuntimeError as exc:
+ if _is_keyed_provider_unconfigured(name, exc):
+ print(
+ f" [{name}] skipped: {exc}",
+ file=sys.stderr,
+ )
+ else:
+ print(f" [{name}] error: {exc}", file=sys.stderr)
+ return None
+ except (requests.RequestException, ValueError) as exc:
+ print(f" [{name}] error: {exc}", file=sys.stderr)
+ return None
+
+
+def two_stage_search(
+ providers: list[str],
+ request: ImageSearchRequest,
+ *,
+ output_path: Path,
+ strict_no_attribution: bool,
+) -> 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.
+
+ 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")
+
+ for stage in stages:
+ 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
+
+ ranked = sorted(
+ candidates,
+ key=lambda c: score_candidate(c, request),
+ reverse=True,
+ )
+
+ 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
+
+ return None, None, None
+
+
+# ---------------------------------------------------------------------------
+# Manifest
+# ---------------------------------------------------------------------------
+
+
+def default_manifest_path(output_dir: str) -> Path:
+ return Path(output_dir) / "image_sources.json"
+
+
+def _measure_actual_image(path: Path) -> Optional[tuple[int, int]]:
+ """Return ``(width, height)`` of the file actually saved at ``path``.
+
+ Upstream metadata (``candidate.width``/``height``) describes the
+ original image on the provider's server, which may differ from what
+ we are allowed to download — for example, second-tier sources
+ aggregated by Openverse (rawpixel etc.) often only expose a
+ 1024px-wide preview. The Executor needs to know what is actually on
+ disk for layout purposes; this function provides that ground truth.
+
+ Returns ``None`` if Pillow is unavailable or the file is unreadable.
+ """
+ try:
+ from PIL import Image # type: ignore
+ except ImportError:
+ return None
+ try:
+ with Image.open(path) as im:
+ return int(im.width), int(im.height)
+ except (OSError, ValueError):
+ return None
+
+
+def _candidate_to_manifest_item(
+ candidate: AssetCandidate,
+ args: argparse.Namespace,
+ *,
+ provider_name: str,
+ stage: str,
+ actual_dimensions: Optional[tuple[int, int]] = None,
+) -> dict:
+ """Build the manifest entry.
+
+ ``width`` / ``height`` reflect the file actually saved to disk
+ (measured by Pillow after download). The upstream-claimed dimensions
+ are only kept under ``metadata_dimensions`` when they disagree with
+ reality, which is the only case where this distinction matters.
+ """
+ if actual_dimensions is not None:
+ width, height = actual_dimensions
+ else:
+ width, height = candidate.width, candidate.height
+
+ item = {
+ "filename": args.filename,
+ "slide": args.slide,
+ "purpose": args.purpose,
+ "search_query": args.query,
+ "orientation": args.orientation,
+ "provider": provider_name,
+ "stage": stage,
+ "title": candidate.title,
+ "author": candidate.author,
+ "source_page_url": candidate.source_page_url,
+ "download_url": candidate.download_url,
+ "license_name": candidate.license_name,
+ "license_url": candidate.license_url,
+ "license_tier": candidate.license_tier,
+ "attribution_required": candidate.license_tier == "attribution-required",
+ "width": width,
+ "height": height,
+ "attribution_text": build_attribution_text(args.filename, candidate),
+ "status": "sourced",
+ }
+
+ # Only carry upstream-claimed dimensions when they differ — this flags
+ # cases where the provider returned a preview rather than the original.
+ if (
+ actual_dimensions is not None
+ and candidate.width
+ and candidate.height
+ and (candidate.width, candidate.height) != actual_dimensions
+ ):
+ item["metadata_dimensions"] = {
+ "width": candidate.width,
+ "height": candidate.height,
+ "note": "upstream-reported size; actual downloaded file is smaller (likely a preview)",
+ }
+
+ return item
+
+
+def _read_existing_manifest(path: Path) -> dict:
+ if not path.exists():
+ return {}
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ print(
+ f" warning: existing manifest at {path} is unreadable, "
+ f"starting fresh ({exc})",
+ file=sys.stderr,
+ )
+ return {}
+
+
+def write_sources_manifest(path: Path, item: dict) -> Path:
+ """Append ``item`` to the manifest at ``path``, replacing any prior
+ entry that targets the same filename."""
+ manifest_path = ensure_json_parent(path)
+ payload = _read_existing_manifest(manifest_path)
+
+ items: list[dict] = list(payload.get("items") or [])
+ items = [i for i in items if i.get("filename") != item["filename"]]
+ items.append(item)
+
+ payload["items"] = items
+ payload["generated_at"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+ payload.setdefault(
+ "license_verification",
+ "provider metadata used; manual review recommended for external delivery",
+ )
+
+ manifest_path.write_text(
+ json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
+ encoding="utf-8",
+ )
+ return manifest_path
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Search openly-licensed web images and download a single best match. "
+ "Sister to image_gen.py."
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ parser.add_argument("query", help="Search query (2-5 keywords work best).")
+ parser.add_argument(
+ "--filename",
+ required=True,
+ help="Local filename for the chosen image (e.g. cover_bg.jpg).",
+ )
+ parser.add_argument(
+ "-o",
+ "--output",
+ default=".",
+ help="Output directory. Manifest defaults to <output>/image_sources.json.",
+ )
+ parser.add_argument(
+ "--provider",
+ choices=ALL_PROVIDERS,
+ default=None,
+ help=(
+ "Pin one provider. Default: try zero-config providers (openverse, "
+ "wikimedia) plus any keyed provider whose API key is set."
+ ),
+ )
+ parser.add_argument(
+ "--orientation",
+ choices=ORIENTATION_CHOICES,
+ default="any",
+ help="Preferred orientation.",
+ )
+ parser.add_argument(
+ "--purpose",
+ default="",
+ help="Purpose tag stored in the manifest (e.g. background, hero, side).",
+ )
+ parser.add_argument(
+ "--slide",
+ default="",
+ help="Slide identifier the image belongs to (e.g. 01_cover).",
+ )
+ parser.add_argument(
+ "--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."
+ ),
+ )
+ parser.add_argument(
+ "--manifest",
+ default=None,
+ help="Override manifest path. Defaults to <output>/image_sources.json.",
+ )
+ return parser
+
+
+def _default_provider_chain() -> list[str]:
+ """Zero-config providers first; add keyed providers only if their key
+ is configured. This is the search order when ``--provider`` is unset."""
+ chain: list[str] = list(ZERO_CONFIG_PROVIDERS)
+ if os.environ.get("PEXELS_API_KEY"):
+ chain.append("pexels")
+ if os.environ.get("PIXABAY_API_KEY"):
+ chain.append("pixabay")
+ return chain
+
+
+def main(argv: Optional[list[str]] = None) -> int:
+ _load_dotenv_if_available()
+
+ parser = build_parser()
+ args = parser.parse_args(argv)
+
+ request = ImageSearchRequest(
+ query=args.query,
+ purpose=args.purpose,
+ orientation="" if args.orientation == "any" else args.orientation,
+ filename=args.filename,
+ slide=args.slide,
+ )
+
+ providers = [args.provider] if args.provider else _default_provider_chain()
+
+ output_dir = Path(args.output)
+ output_dir.mkdir(parents=True, exist_ok=True)
+ output_path = output_dir / args.filename
+
+ print(f"Searching providers: {', '.join(providers)}", file=sys.stderr)
+ candidate, provider_name, stage = two_stage_search(
+ providers,
+ request,
+ output_path=output_path,
+ strict_no_attribution=args.strict_no_attribution,
+ )
+
+ 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.",
+ file=sys.stderr,
+ )
+ return 1
+
+ print(
+ f" picked: {candidate.title!r} from {provider_name} "
+ f"({candidate.license_name or 'no license string'}, "
+ f"{candidate.license_tier})",
+ file=sys.stderr,
+ )
+
+ # Measure what was actually written to disk; upstream metadata can be
+ # off (e.g. Openverse aggregates rawpixel which only exposes previews).
+ actual_dimensions = _measure_actual_image(output_path)
+ if (
+ actual_dimensions is not None
+ and candidate.width
+ and candidate.height
+ and actual_dimensions[0] * actual_dimensions[1]
+ < 0.5 * candidate.width * candidate.height
+ ):
+ print(
+ f"\n[!] Downloaded image is much smaller than upstream metadata "
+ f"({actual_dimensions[0]}x{actual_dimensions[1]} vs "
+ f"{candidate.width}x{candidate.height}). The provider likely "
+ f"only exposes a preview here. Layout based on the manifest's "
+ f"width/height will be accurate; the metadata_dimensions field "
+ f"is preserved for reference.",
+ file=sys.stderr,
+ )
+
+ item = _candidate_to_manifest_item(
+ candidate,
+ args,
+ provider_name=provider_name,
+ stage=stage,
+ actual_dimensions=actual_dimensions,
+ )
+ manifest_path = Path(args.manifest) if args.manifest else default_manifest_path(args.output)
+ write_sources_manifest(manifest_path, item)
+ print(f" manifest: {manifest_path}", file=sys.stderr)
+
+ if candidate.license_tier == "attribution-required":
+ print(
+ "\n[!] This image requires on-slide attribution. "
+ "Executor should add a small credit element to the slide using "
+ "the 'attribution_text' field in the manifest.",
+ file=sys.stderr,
+ )
+
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/image_sources/__init__.py b/skills/ppt-master/scripts/image_sources/__init__.py
new file mode 100644
index 00000000..e4f47c78
--- /dev/null
+++ b/skills/ppt-master/scripts/image_sources/__init__.py
@@ -0,0 +1,9 @@
+"""Web image source providers for PPT Master.
+
+Each ``provider_<name>.py`` module exposes a ``search(request, *,
+license_tier_filter)`` function returning a list of ``AssetCandidate``
+objects, plus a ``parse_results(payload)`` helper. ``image_search.py``
+dispatches to them by name.
+"""
+
+from __future__ import annotations
diff --git a/skills/ppt-master/scripts/image_sources/provider_common.py b/skills/ppt-master/scripts/image_sources/provider_common.py
new file mode 100644
index 00000000..0ea0801a
--- /dev/null
+++ b/skills/ppt-master/scripts/image_sources/provider_common.py
@@ -0,0 +1,396 @@
+"""Shared primitives for web image providers.
+
+This module is the single home for everything that all four providers
+(Openverse / Wikimedia / Pexels / Pixabay) need:
+
+- License tier classification (the central abstraction of this module)
+- Search request / asset candidate dataclasses
+- Query simplification for keyword-based image APIs
+- Candidate scoring
+- Attribution text builder
+- Small helpers (orientation, json path, etc.)
+
+Provider-specific code (API URLs, payload shape, parse_results) lives in
+the corresponding provider_<name>.py module and only imports from here.
+"""
+
+from __future__ import annotations
+
+import sys
+
+if __name__ == "__main__" and any(arg in {"-h", "--help", "help"} for arg in sys.argv[1:]):
+ print(__doc__)
+ print("This is an internal helper module used by image_search.py and the four web image providers.")
+ raise SystemExit(0)
+
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Optional
+
+
+# ---------------------------------------------------------------------------
+# Project-wide constants
+# ---------------------------------------------------------------------------
+
+USER_AGENT = "PPTMaster/1.0 (https://github.com/hugohe3/ppt-master)"
+
+
+# ---------------------------------------------------------------------------
+# License tier classification
+# ---------------------------------------------------------------------------
+#
+# Every accepted candidate is classified into exactly one of two tiers:
+#
+# "no-attribution" -> No on-slide credit needed (CC0, PD, Pexels,
+# Pixabay). Default search target.
+# "attribution-required" -> CC BY / CC BY-SA. Executor must add an
+# inline credit text element on the slide.
+#
+# Anything else (CC BY-NC, CC BY-ND, all-rights-reserved, unknown) returns
+# None and the candidate is rejected outright.
+
+LICENSE_TIER_NO_ATTRIBUTION = "no-attribution"
+LICENSE_TIER_ATTRIBUTION_REQUIRED = "attribution-required"
+
+# Tokens that mark a license as "no attribution required".
+NO_ATTRIBUTION_TOKENS: tuple[str, ...] = (
+ "cc0",
+ "public domain",
+ "publicdomain",
+ "creativecommons.org/publicdomain/",
+ "pexels license",
+ "pixabay content license",
+ "pixabay license",
+)
+
+# Tokens that mark a license as "attribution required".
+ATTRIBUTION_REQUIRED_TOKENS: tuple[str, ...] = (
+ "cc by",
+ "cc-by",
+ "by-sa",
+ "by sa",
+ "creativecommons.org/licenses/by/",
+ "creativecommons.org/licenses/by-sa/",
+)
+
+# Tokens that disqualify a candidate entirely.
+REJECTED_TOKENS: tuple[str, ...] = (
+ "by-nc",
+ "by nc",
+ "noncommercial",
+ "non-commercial",
+ "by-nd",
+ "by nd",
+ "no derivatives",
+ "noderivatives",
+ "all rights reserved",
+)
+
+
+# Canonical display forms for license names. Different providers report
+# the same license with different capitalization (Openverse: "cc0",
+# Wikimedia: "Public domain"); the Executor renders these as on-slide
+# text, so a normalized form prevents inconsistent credits.
+_LICENSE_NAME_CANON: dict[str, str] = {
+ "cc0": "CC0",
+ "cc 0": "CC0",
+ "public domain": "Public Domain",
+ "publicdomain": "Public Domain",
+ "pdm": "Public Domain",
+ "pexels license": "Pexels License",
+ "pixabay content license": "Pixabay Content License",
+ "pixabay license": "Pixabay Content License",
+}
+
+# CC license short-name pattern used to canonicalize "cc by 4.0" → "CC BY 4.0".
+_CC_PATTERN = re.compile(
+ r"^\s*cc[\s-]+(by(?:[\s-]+(?:sa|nc|nd))*)\s*([0-9.]*)\s*$",
+ re.IGNORECASE,
+)
+
+
+def normalize_license_name(name: str) -> str:
+ """Return a canonical display form for a license name.
+
+ Maps common aliases to a consistent capitalization so the on-slide
+ credit text written by the Executor is uniform across providers.
+ Unknown inputs are returned trimmed but otherwise unchanged.
+ """
+ if not name:
+ return ""
+ key = name.strip().lower()
+ if not key:
+ return ""
+
+ if key in _LICENSE_NAME_CANON:
+ return _LICENSE_NAME_CANON[key]
+
+ cc_match = _CC_PATTERN.match(key)
+ if cc_match:
+ suffix_raw, version = cc_match.group(1), cc_match.group(2)
+ suffix = suffix_raw.replace(" ", "-").upper()
+ return f"CC {suffix} {version}".strip()
+
+ return name.strip()
+
+
+def classify_license(
+ license_name: str,
+ license_url: str = "",
+ provider: str = "",
+) -> Optional[str]:
+ """Classify a license string into one of the two tiers, or reject it.
+
+ Returns:
+ ``"no-attribution"`` / ``"attribution-required"`` / ``None``.
+
+ The provider hint lets us treat Pexels and Pixabay's own licenses as
+ ``no-attribution`` even when the upstream API only returns a short
+ label like ``"Pexels"``.
+ """
+ text = " ".join(
+ part.strip().lower()
+ for part in (license_name or "", license_url or "")
+ if part
+ )
+ provider_key = (provider or "").strip().lower()
+
+ if not text and not provider_key:
+ return None
+
+ if any(token in text for token in REJECTED_TOKENS):
+ return None
+
+ if any(token in text for token in NO_ATTRIBUTION_TOKENS):
+ return LICENSE_TIER_NO_ATTRIBUTION
+
+ # Provider-default fallback: pexels / pixabay items often arrive with a
+ # bare "Pexels" / "Pixabay" license string. Their site-wide license is
+ # "free for commercial use, no attribution required".
+ #
+ # Guard: require the license text to actually mention the provider name,
+ # so an empty / missing license field never silently passes as no-attribution.
+ if (
+ provider_key in {"pexels", "pixabay"}
+ and provider_key in text
+ and not any(token in text for token in ATTRIBUTION_REQUIRED_TOKENS)
+ ):
+ return LICENSE_TIER_NO_ATTRIBUTION
+
+ if any(token in text for token in ATTRIBUTION_REQUIRED_TOKENS):
+ return LICENSE_TIER_ATTRIBUTION_REQUIRED
+
+ return None # unknown license -> reject
+
+
+# ---------------------------------------------------------------------------
+# Dataclasses
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class ImageSearchRequest:
+ """A single image search intent passed to a provider."""
+
+ query: str
+ purpose: str = ""
+ orientation: str = "" # "landscape" / "portrait" / "square" / ""
+ min_width: int = 0
+ min_height: int = 0
+ filename: str = ""
+ slide: str = ""
+
+
+@dataclass
+class AssetCandidate:
+ """One ranked candidate returned by a provider's parse_results."""
+
+ provider: str
+ title: str
+ asset_id: str = ""
+ source_page_url: str = ""
+ license_name: str = ""
+ license_url: str = ""
+ license_tier: str = "" # one of LICENSE_TIER_* constants
+ width: int = 0
+ height: int = 0
+ download_url: str = ""
+ author: str = ""
+ raw: Any = field(default=None)
+
+
+# ---------------------------------------------------------------------------
+# Query simplification
+# ---------------------------------------------------------------------------
+#
+# Web image APIs do keyword matching against image metadata, not semantic
+# search. Long, descriptive queries with brand names, HEX codes, and
+# composition notes return zero results. We progressively trim the query
+# down to the most concrete nouns.
+
+_NOISE_WORDS = frozenset({
+ # Brand / product names
+ "claude", "openai", "gpt", "gemini", "copilot", "chatgpt", "midjourney",
+ "stable", "diffusion", "dall-e", "cursor", "anthropic", "microsoft",
+ "google", "apple", "meta", "nvidia", "tesla",
+ # Generic filler
+ "using", "with", "from", "that", "this", "have", "been", "will",
+ "into", "more", "also", "very", "some", "than", "them", "other",
+})
+
+# Words that look generic but are actually useful when they ARE the
+# subject of the deck (e.g. a deck about AI). We only drop them when
+# there are still other concrete nouns left.
+_SOFT_NOISE_WORDS = frozenset({
+ "ai", "code", "software", "system", "digital", "platform", "solution",
+ "application", "interface", "framework", "algorithm", "api", "sdk",
+ "assistant", "tool", "service", "technology", "tech", "program",
+})
+
+
+def simplify_query(query: str, max_words: int = 4) -> str:
+ """Trim a verbose query into a short keyword phrase.
+
+ Strategy:
+ 1. Strip HEX color codes and parenthetical asides.
+ 2. Drop hard-noise words (brand names, generic filler).
+ 3. Drop soft-noise words ONLY if concrete nouns remain.
+ 4. If the result would be empty, return the original query
+ (fail-open: better an over-broad search than zero results).
+ 5. Cap at ``max_words`` words.
+ """
+ cleaned = re.sub(r"#[0-9a-fA-F]{3,8}", "", query)
+ cleaned = re.sub(r"\([^)]*\)", "", cleaned)
+ words = [w for w in cleaned.split() if len(w) > 2]
+
+ after_hard = [w for w in words if w.lower() not in _NOISE_WORDS]
+ after_soft = [w for w in after_hard if w.lower() not in _SOFT_NOISE_WORDS]
+
+ # Only drop soft-noise if there are still concrete nouns left.
+ filtered = after_soft if after_soft else after_hard
+
+ if not filtered:
+ # Everything got filtered. Fail open: return the original query.
+ return query.strip()
+
+ return " ".join(filtered[:max_words])
+
+
+def build_query_progression(query: str) -> list[str]:
+ """Return a list of progressively simpler queries to try in order.
+
+ Stops as soon as one of them yields candidates upstream. Duplicates
+ are dropped while preserving order.
+ """
+ seen: set[str] = set()
+ out: list[str] = []
+ for candidate in (query, simplify_query(query, max_words=4), simplify_query(query, max_words=3)):
+ candidate = candidate.strip()
+ if candidate and candidate not in seen:
+ seen.add(candidate)
+ out.append(candidate)
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Scoring
+# ---------------------------------------------------------------------------
+
+
+def normalize_orientation(width: int, height: int) -> str:
+ if width <= 0 or height <= 0:
+ return "unknown"
+ if width > height:
+ return "landscape"
+ if height > width:
+ return "portrait"
+ return "square"
+
+
+def score_candidate(candidate: AssetCandidate, request: ImageSearchRequest) -> float:
+ """Score a candidate against a request. Higher is better; -inf rejects."""
+ if not candidate.license_tier:
+ return float("-inf")
+
+ score = 10000.0
+
+ # Strongly prefer no-attribution candidates so the deck stays clean
+ # even when both tiers are returned in the same search.
+ if candidate.license_tier == LICENSE_TIER_NO_ATTRIBUTION:
+ score += 5000.0
+
+ candidate_orientation = normalize_orientation(candidate.width, candidate.height)
+ requested = (request.orientation or "").strip().lower()
+ if requested:
+ if candidate_orientation == requested:
+ score += 1000.0
+ else:
+ score -= 250.0
+
+ if request.min_width and candidate.width < request.min_width:
+ score -= 500.0
+ if request.min_height and candidate.height < request.min_height:
+ score -= 500.0
+
+ # Larger images score higher, capped to avoid runaway dominance.
+ pixel_score = max(candidate.width, 0) * max(candidate.height, 0) / 1000.0
+ score += min(pixel_score, 5000.0)
+ return score
+
+
+# ---------------------------------------------------------------------------
+# Attribution text
+# ---------------------------------------------------------------------------
+
+
+PROVIDER_DISPLAY_NAMES: dict[str, str] = {
+ "openverse": "Openverse",
+ "wikimedia": "Wikimedia Commons",
+ "pexels": "Pexels",
+ "pixabay": "Pixabay",
+}
+
+
+def build_attribution_text(filename: str, candidate: AssetCandidate) -> str:
+ """Render the canonical attribution string for the manifest.
+
+ Format:
+ ``filename — "title" by author, via Provider, license: name (url)``
+
+ Empty fields are gracefully omitted. The text is intended for use by
+ the Executor when generating in-SVG credit elements; it is not meant
+ to be machine-parsed downstream.
+ """
+ provider_name = PROVIDER_DISPLAY_NAMES.get(
+ candidate.provider, candidate.provider or "unknown"
+ )
+
+ parts: list[str] = [filename or candidate.download_url or "image"]
+ middle: list[str] = []
+ if candidate.title:
+ middle.append(f'"{candidate.title}"')
+ if candidate.author:
+ middle.append(f"by {candidate.author}")
+ middle.append(f"via {provider_name}")
+ parts.append(" ".join(middle))
+
+ license_part = candidate.license_name or candidate.license_url
+ if license_part:
+ if candidate.license_url and candidate.license_name:
+ license_part = f"{candidate.license_name} ({candidate.license_url})"
+ parts.append(f"license: {license_part}")
+
+ return " — ".join(parts)
+
+
+# ---------------------------------------------------------------------------
+# Small helpers
+# ---------------------------------------------------------------------------
+
+
+def ensure_json_parent(path: str | Path) -> Path:
+ """Make sure the parent directory of ``path`` exists; return as Path."""
+ p = Path(path)
+ p.parent.mkdir(parents=True, exist_ok=True)
+ return p
diff --git a/skills/ppt-master/scripts/image_sources/provider_openverse.py b/skills/ppt-master/scripts/image_sources/provider_openverse.py
new file mode 100644
index 00000000..6941d5e8
--- /dev/null
+++ b/skills/ppt-master/scripts/image_sources/provider_openverse.py
@@ -0,0 +1,119 @@
+"""Openverse provider.
+
+Zero-config (no API key required). Indexes openly licensed images across
+Wikimedia, Flickr, museums, and other sources.
+
+API docs: https://api.openverse.org/v1/
+"""
+
+from __future__ import annotations
+
+import sys
+
+if __name__ == "__main__" and any(arg in {"-h", "--help", "help"} for arg in sys.argv[1:]):
+ print(__doc__)
+ raise SystemExit(0)
+
+import requests
+
+from image_sources.provider_common import (
+ AssetCandidate,
+ ImageSearchRequest,
+ USER_AGENT,
+ build_query_progression,
+ classify_license,
+ normalize_license_name,
+)
+
+
+API_URL = "https://api.openverse.org/v1/images/"
+DEFAULT_PAGE_SIZE = 20
+DEFAULT_TIMEOUT = 30
+
+# Map our orientation vocabulary to Openverse's ``aspect_ratio`` parameter.
+_ASPECT_MAP = {"landscape": "wide", "portrait": "tall", "square": "square"}
+
+# Openverse license param values. ``cc0,pdm`` covers our "no-attribution" tier;
+# adding ``by,by-sa`` opens the "attribution-required" tier.
+_LICENSE_PARAM = {
+ "no-attribution-only": "cc0,pdm",
+ "all": "by,by-sa,cc0,pdm",
+}
+
+
+def parse_results(payload: dict) -> list[AssetCandidate]:
+ """Translate an Openverse search payload into a list of candidates."""
+ candidates: list[AssetCandidate] = []
+ for item in payload.get("results", []) or []:
+ license_name = (item.get("license") or "").strip()
+ license_url = (item.get("license_url") or "").strip()
+ tier = classify_license(license_name, license_url, provider="openverse")
+ if not tier:
+ continue
+
+ download_url = (item.get("url") or item.get("thumbnail") or "").strip()
+ if not download_url:
+ continue
+
+ candidates.append(
+ AssetCandidate(
+ provider="openverse",
+ title=(item.get("title") or "").strip() or "Untitled",
+ asset_id=str(item.get("id") or ""),
+ source_page_url=(
+ item.get("foreign_landing_url") or item.get("detail_url") or ""
+ ).strip(),
+ license_name=normalize_license_name(license_name),
+ license_url=license_url,
+ license_tier=tier,
+ width=int(item.get("width") or 0),
+ height=int(item.get("height") or 0),
+ download_url=download_url,
+ author=(item.get("creator") or "").strip(),
+ raw=item,
+ )
+ )
+ return candidates
+
+
+def search(
+ request: ImageSearchRequest,
+ *,
+ license_tier_filter: str = "no-attribution-only",
+ page_size: int = DEFAULT_PAGE_SIZE,
+ timeout: int = DEFAULT_TIMEOUT,
+) -> list[AssetCandidate]:
+ """Search Openverse for candidates matching ``request``.
+
+ ``license_tier_filter`` is one of ``"no-attribution-only"`` or ``"all"``.
+ Returns the candidates from the first non-empty query in the
+ progression — caller is responsible for picking the best one via
+ ``score_candidate``.
+ """
+ if license_tier_filter not in _LICENSE_PARAM:
+ raise ValueError(f"unsupported license_tier_filter: {license_tier_filter!r}")
+
+ orientation = (request.orientation or "").strip().lower()
+
+ for query in build_query_progression(request.query):
+ params: dict[str, str | int] = {
+ "q": query,
+ "page_size": page_size,
+ "license": _LICENSE_PARAM[license_tier_filter],
+ "size": "large",
+ }
+ if orientation in _ASPECT_MAP:
+ params["aspect_ratio"] = _ASPECT_MAP[orientation]
+
+ response = requests.get(
+ API_URL,
+ params=params,
+ headers={"User-Agent": USER_AGENT, "Accept": "application/json"},
+ timeout=timeout,
+ )
+ response.raise_for_status()
+ candidates = parse_results(response.json())
+ if candidates:
+ return candidates
+
+ return []
diff --git a/skills/ppt-master/scripts/image_sources/provider_pexels.py b/skills/ppt-master/scripts/image_sources/provider_pexels.py
new file mode 100644
index 00000000..a3fd045a
--- /dev/null
+++ b/skills/ppt-master/scripts/image_sources/provider_pexels.py
@@ -0,0 +1,124 @@
+"""Pexels provider.
+
+Requires ``PEXELS_API_KEY`` in the environment. Pexels's site-wide license
+allows commercial use without attribution, so all returned candidates are
+classified as ``no-attribution``.
+
+API docs: https://www.pexels.com/api/documentation/
+"""
+
+from __future__ import annotations
+
+import sys
+
+if __name__ == "__main__" and any(arg in {"-h", "--help", "help"} for arg in sys.argv[1:]):
+ print(__doc__)
+ raise SystemExit(0)
+
+import os
+
+import requests
+
+from image_sources.provider_common import (
+ AssetCandidate,
+ ImageSearchRequest,
+ LICENSE_TIER_NO_ATTRIBUTION,
+ USER_AGENT,
+ build_query_progression,
+ normalize_license_name,
+)
+
+
+API_URL = "https://api.pexels.com/v1/search"
+DEFAULT_PAGE_SIZE = 20
+DEFAULT_TIMEOUT = 30
+
+_ORIENTATION_MAP = {
+ "landscape": "landscape",
+ "portrait": "portrait",
+ "square": "square",
+}
+
+
+def _require_api_key() -> str:
+ key = (os.environ.get("PEXELS_API_KEY") or "").strip()
+ if not key:
+ raise RuntimeError(
+ "PEXELS_API_KEY is not set. Add it to your environment or .env file. "
+ "Get one at https://www.pexels.com/api/"
+ )
+ return key
+
+
+def parse_results(payload: dict) -> list[AssetCandidate]:
+ """Translate a Pexels response into candidates."""
+ candidates: list[AssetCandidate] = []
+ for item in payload.get("photos", []) or []:
+ src = item.get("src") or {}
+ download_url = (src.get("large2x") or src.get("large") or src.get("original") or "").strip()
+ if not download_url:
+ continue
+
+ candidates.append(
+ AssetCandidate(
+ provider="pexels",
+ title=(item.get("alt") or "").strip() or "Pexels photo",
+ asset_id=str(item.get("id") or ""),
+ source_page_url=(item.get("url") or "").strip(),
+ license_name=normalize_license_name("Pexels License"),
+ license_url="https://www.pexels.com/license/",
+ license_tier=LICENSE_TIER_NO_ATTRIBUTION,
+ width=int(item.get("width") or 0),
+ height=int(item.get("height") or 0),
+ download_url=download_url,
+ author=(item.get("photographer") or "").strip(),
+ raw=item,
+ )
+ )
+ return candidates
+
+
+def search(
+ request: ImageSearchRequest,
+ *,
+ license_tier_filter: str = "no-attribution-only",
+ page_size: int = DEFAULT_PAGE_SIZE,
+ timeout: int = DEFAULT_TIMEOUT,
+) -> list[AssetCandidate]:
+ """Search Pexels for candidates.
+
+ Pexels images are uniformly ``no-attribution``, so the ``"all"`` filter
+ behaves identically to ``"no-attribution-only"``. Both are accepted to
+ keep the dispatcher simple.
+ """
+ if license_tier_filter not in {"no-attribution-only", "all"}:
+ raise ValueError(f"unsupported license_tier_filter: {license_tier_filter!r}")
+
+ api_key = _require_api_key()
+ orientation = (request.orientation or "").strip().lower()
+
+ for query in build_query_progression(request.query):
+ params: dict[str, str | int] = {
+ "query": query,
+ "per_page": page_size,
+ "size": "large",
+ }
+ if orientation in _ORIENTATION_MAP:
+ params["orientation"] = _ORIENTATION_MAP[orientation]
+
+ response = requests.get(
+ API_URL,
+ params=params,
+ headers={
+ "Authorization": api_key,
+ "User-Agent": USER_AGENT,
+ "Accept": "application/json",
+ },
+ timeout=timeout,
+ )
+ response.raise_for_status()
+ candidates = parse_results(response.json())
+ if candidates:
+ return candidates
+
+ return []
diff --git a/skills/ppt-master/scripts/image_sources/provider_pixabay.py b/skills/ppt-master/scripts/image_sources/provider_pixabay.py
new file mode 100644
index 00000000..0ec3706a
--- /dev/null
+++ b/skills/ppt-master/scripts/image_sources/provider_pixabay.py
@@ -0,0 +1,129 @@
+"""Pixabay provider.
+
+Requires ``PIXABAY_API_KEY`` in the environment. Pixabay's Content License
+allows commercial use without attribution, so all returned candidates are
+classified as ``no-attribution``.
+
+API docs: https://pixabay.com/api/docs/
+"""
+
+from __future__ import annotations
+
+import sys
+
+if __name__ == "__main__" and any(arg in {"-h", "--help", "help"} for arg in sys.argv[1:]):
+ print(__doc__)
+ raise SystemExit(0)
+
+import os
+
+import requests
+
+from image_sources.provider_common import (
+ AssetCandidate,
+ ImageSearchRequest,
+ LICENSE_TIER_NO_ATTRIBUTION,
+ USER_AGENT,
+ build_query_progression,
+ normalize_license_name,
+)
+
+
+API_URL = "https://pixabay.com/api/"
+DEFAULT_PAGE_SIZE = 20
+DEFAULT_TIMEOUT = 30
+
+# Pixabay uses ``horizontal`` / ``vertical`` rather than landscape/portrait,
+# and has no ``square`` value (it falls back to ``all``).
+_ORIENTATION_MAP = {
+ "landscape": "horizontal",
+ "portrait": "vertical",
+}
+
+
+def _require_api_key() -> str:
+ key = (os.environ.get("PIXABAY_API_KEY") or "").strip()
+ if not key:
+ raise RuntimeError(
+ "PIXABAY_API_KEY is not set. Add it to your environment or .env file. "
+ "Get one at https://pixabay.com/api/docs/"
+ )
+ return key
+
+
+def parse_results(payload: dict) -> list[AssetCandidate]:
+ """Translate a Pixabay response into candidates."""
+ candidates: list[AssetCandidate] = []
+ for item in payload.get("hits", []) or []:
+ download_url = (
+ item.get("largeImageURL")
+ or item.get("webformatURL")
+ or item.get("previewURL")
+ or ""
+ ).strip()
+ if not download_url:
+ continue
+
+ candidates.append(
+ AssetCandidate(
+ provider="pixabay",
+ title=(item.get("tags") or "").strip() or "Pixabay image",
+ asset_id=str(item.get("id") or ""),
+ source_page_url=(item.get("pageURL") or "").strip(),
+ license_name=normalize_license_name("Pixabay Content License"),
+ license_url="https://pixabay.com/service/license-summary/",
+ license_tier=LICENSE_TIER_NO_ATTRIBUTION,
+ width=int(item.get("imageWidth") or 0),
+ height=int(item.get("imageHeight") or 0),
+ download_url=download_url,
+ author=(item.get("user") or "").strip(),
+ raw=item,
+ )
+ )
+ return candidates
+
+
+def search(
+ request: ImageSearchRequest,
+ *,
+ license_tier_filter: str = "no-attribution-only",
+ page_size: int = DEFAULT_PAGE_SIZE,
+ timeout: int = DEFAULT_TIMEOUT,
+) -> list[AssetCandidate]:
+ """Search Pixabay for candidates.
+
+ Pixabay images are uniformly ``no-attribution``, so the ``"all"`` filter
+ behaves identically to ``"no-attribution-only"``.
+ """
+ if license_tier_filter not in {"no-attribution-only", "all"}:
+ raise ValueError(f"unsupported license_tier_filter: {license_tier_filter!r}")
+
+ api_key = _require_api_key()
+ orientation = (request.orientation or "").strip().lower()
+
+ for query in build_query_progression(request.query):
+ params: dict[str, str | int] = {
+ "key": api_key,
+ "q": query,
+ "image_type": "photo",
+ "per_page": page_size,
+ "safesearch": "true",
+ }
+ if orientation in _ORIENTATION_MAP:
+ params["orientation"] = _ORIENTATION_MAP[orientation]
+
+ response = requests.get(
+ API_URL,
+ params=params,
+ headers={
+ "User-Agent": USER_AGENT,
+ "Accept": "application/json",
+ },
+ timeout=timeout,
+ )
+ response.raise_for_status()
+ candidates = parse_results(response.json())
+ if candidates:
+ return candidates
+
+ return []
diff --git a/skills/ppt-master/scripts/image_sources/provider_wikimedia.py b/skills/ppt-master/scripts/image_sources/provider_wikimedia.py
new file mode 100644
index 00000000..c507a056
--- /dev/null
+++ b/skills/ppt-master/scripts/image_sources/provider_wikimedia.py
@@ -0,0 +1,196 @@
+"""Wikimedia Commons provider.
+
+Zero-config (no API key required). Strong on educational, scientific,
+geographic, and historical imagery; weaker on contemporary stock-style
+photography and people.
+
+Uses the MediaWiki API's ``generator=search`` mode to combine fulltext
+search with imageinfo/extmetadata in a single round trip.
+
+API docs: https://www.mediawiki.org/wiki/API:Search
+"""
+
+from __future__ import annotations
+
+import sys
+
+if __name__ == "__main__" and any(arg in {"-h", "--help", "help"} for arg in sys.argv[1:]):
+ print(__doc__)
+ raise SystemExit(0)
+
+import html
+import re
+
+import requests
+
+from image_sources.provider_common import (
+ AssetCandidate,
+ ImageSearchRequest,
+ USER_AGENT,
+ build_query_progression,
+ classify_license,
+ normalize_license_name,
+ normalize_orientation,
+)
+
+
+API_URL = "https://commons.wikimedia.org/w/api.php"
+DEFAULT_SEARCH_LIMIT = 20
+DEFAULT_TIMEOUT = 30
+
+# File extensions we are willing to embed in a deck. SVG/GIF/audio etc. are
+# excluded — Wikimedia returns these freely from a generic search.
+_ACCEPTED_EXTENSIONS = frozenset({".jpg", ".jpeg", ".png", ".webp", ".tiff", ".tif"})
+
+_TAG_RE = re.compile(r"<[^>]+>")
+_WS_RE = re.compile(r"\s+")
+
+
+def _strip_html(value: str) -> str:
+ """Wikimedia's extmetadata fields contain inline HTML markup. Flatten it."""
+ if not value:
+ return ""
+ text = html.unescape(str(value))
+ text = _TAG_RE.sub(" ", text)
+ text = _WS_RE.sub(" ", text)
+ return text.strip()
+
+
+def _ext_value(extmetadata: dict, key: str) -> str:
+ """Pull ``extmetadata[key].value`` and strip HTML."""
+ entry = extmetadata.get(key) or {}
+ if isinstance(entry, dict):
+ return _strip_html(entry.get("value", ""))
+ return _strip_html(entry)
+
+
+def _accept_extension(title: str) -> bool:
+ """Drop non-image files (svg/gif/audio/video) by extension."""
+ lower = (title or "").lower()
+ return any(lower.endswith(ext) for ext in _ACCEPTED_EXTENSIONS)
+
+
+def _page_label(title: str) -> str:
+ """``File:Some_image.jpg`` → ``Some_image.jpg``."""
+ clean = _strip_html(title)
+ if clean.lower().startswith("file:"):
+ return clean.split(":", 1)[1].strip()
+ return clean
+
+
+def parse_results(payload: dict) -> list[AssetCandidate]:
+ """Translate a MediaWiki ``query`` payload into a list of candidates."""
+ candidates: list[AssetCandidate] = []
+ pages = ((payload.get("query") or {}).get("pages") or {})
+
+ for page in pages.values():
+ title = page.get("title") or ""
+ if not _accept_extension(title):
+ continue
+
+ info_list = page.get("imageinfo") or []
+ if not info_list:
+ continue
+ info = info_list[0]
+ extmetadata = info.get("extmetadata") or {}
+
+ license_name = (
+ _ext_value(extmetadata, "LicenseShortName")
+ or _ext_value(extmetadata, "License")
+ )
+ license_url = _ext_value(extmetadata, "LicenseUrl")
+ tier = classify_license(license_name, license_url, provider="wikimedia")
+ if not tier:
+ continue
+
+ download_url = (info.get("url") or "").strip()
+ if not download_url:
+ continue
+
+ candidates.append(
+ AssetCandidate(
+ provider="wikimedia",
+ title=_page_label(title) or "Untitled",
+ asset_id=str(page.get("pageid") or ""),
+ source_page_url=(info.get("descriptionurl") or "").strip(),
+ license_name=normalize_license_name(license_name),
+ license_url=license_url,
+ license_tier=tier,
+ width=int(info.get("width") or 0),
+ height=int(info.get("height") or 0),
+ download_url=download_url,
+ author=_ext_value(extmetadata, "Artist"),
+ raw=page,
+ )
+ )
+
+ return candidates
+
+
+def _filter_by_orientation(
+ candidates: list[AssetCandidate], orientation: str
+) -> list[AssetCandidate]:
+ """Wikimedia API has no orientation parameter; filter client-side."""
+ if not orientation or orientation == "any":
+ return candidates
+ matching = [
+ c for c in candidates if normalize_orientation(c.width, c.height) == orientation
+ ]
+ # Fall back to the unfiltered list if orientation pruning leaves nothing —
+ # better an off-orientation match than no image at all.
+ return matching or candidates
+
+
+def search(
+ request: ImageSearchRequest,
+ *,
+ license_tier_filter: str = "no-attribution-only",
+ search_limit: int = DEFAULT_SEARCH_LIMIT,
+ timeout: int = DEFAULT_TIMEOUT,
+) -> list[AssetCandidate]:
+ """Search Wikimedia Commons for candidates.
+
+ Wikimedia returns license info via ``extmetadata`` rather than as a
+ request parameter, so the ``license_tier_filter`` does its work in
+ ``parse_results`` (and is honored implicitly because tier classification
+ happens there). Returning candidates from the first non-empty query.
+ """
+ if license_tier_filter not in {"no-attribution-only", "all"}:
+ raise ValueError(f"unsupported license_tier_filter: {license_tier_filter!r}")
+
+ orientation = (request.orientation or "").strip().lower()
+
+ for query in build_query_progression(request.query):
+ params = {
+ "action": "query",
+ "format": "json",
+ "generator": "search",
+ "gsrnamespace": "6", # File: namespace
+ "gsrsearch": f"{query} filetype:bitmap",
+ "gsrlimit": search_limit,
+ "prop": "imageinfo",
+ "iiprop": "url|size|extmetadata|mime",
+ "iiextmetadatafilter": (
+ "LicenseShortName|License|LicenseUrl|Artist"
+ ),
+ }
+
+ response = requests.get(
+ API_URL,
+ params=params,
+ headers={"User-Agent": USER_AGENT, "Accept": "application/json"},
+ timeout=timeout,
+ )
+ response.raise_for_status()
+ all_candidates = parse_results(response.json())
+
+ if license_tier_filter == "no-attribution-only":
+ all_candidates = [
+ c for c in all_candidates if c.license_tier == "no-attribution"
+ ]
+
+ all_candidates = _filter_by_orientation(all_candidates, orientation)
+ if all_candidates:
+ return all_candidates
+
+ return []