|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Build SerpApi engine parameter data for MCP usage.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import html |
| 7 | +import json |
| 8 | +from pathlib import Path |
| 9 | +from urllib.request import Request, urlopen |
| 10 | + |
| 11 | +from bs4 import BeautifulSoup |
| 12 | +from markdownify import markdownify |
| 13 | + |
| 14 | +PLAYGROUND_URL = "https://serpapi.com/playground" |
| 15 | +EXCLUDED_ENGINES = { |
| 16 | + "google_scholar_profiles", |
| 17 | + "google_light_fast", |
| 18 | + "google_lens_image_sources", |
| 19 | +} |
| 20 | +PARAM_KEEP_KEYS = {"html", "type", "options", "required"} |
| 21 | +OUTPUT_DIR = Path("engines") |
| 22 | +TIMEOUT_SECONDS = 30 |
| 23 | +USER_AGENT = "Mozilla/5.0" |
| 24 | + |
| 25 | + |
| 26 | +def html_to_markdown(value: str) -> str: |
| 27 | + """Convert HTML to markdown, normalizing whitespace.""" |
| 28 | + md = markdownify(html.unescape(value), strip=["a"]) |
| 29 | + return " ".join(md.split()) |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | +def normalize_options(options: list[object]) -> list[object]: |
| 34 | + """Normalize option values, simplifying [value, label] pairs where possible.""" |
| 35 | + normalized = [] |
| 36 | + for option in options: |
| 37 | + if isinstance(option, list) and option: |
| 38 | + value = option[0] |
| 39 | + label = option[1] if len(option) > 1 else None |
| 40 | + if label is not None and (isinstance(value, (int, float)) or (isinstance(value, str) and value.isdigit())) and value != label: |
| 41 | + normalized.append(option) |
| 42 | + else: |
| 43 | + normalized.append(value) |
| 44 | + else: |
| 45 | + normalized.append(option) |
| 46 | + return normalized |
| 47 | + |
| 48 | + |
| 49 | +def fetch_props(url: str) -> dict[str, object]: |
| 50 | + """Fetch playground HTML and extract React props.""" |
| 51 | + req = Request(url, headers={"User-Agent": USER_AGENT}) |
| 52 | + with urlopen(req, timeout=TIMEOUT_SECONDS) as resp: |
| 53 | + page_html = resp.read().decode("utf-8", errors="ignore") |
| 54 | + soup = BeautifulSoup(page_html, "html.parser") |
| 55 | + node = soup.find(attrs={"data-react-props": True}) |
| 56 | + if not node: |
| 57 | + raise RuntimeError("Failed to locate data-react-props in playground HTML.") |
| 58 | + return json.loads(html.unescape(node["data-react-props"])) |
| 59 | + |
| 60 | + |
| 61 | +def normalize_engine(engine: str, payload: dict[str, object]) -> dict[str, object]: |
| 62 | + """Normalize engine payload, extracting relevant parameter metadata.""" |
| 63 | + normalized_params: dict[str, dict[str, object]] = {} |
| 64 | + common_params: dict[str, dict[str, object]] = {} |
| 65 | + if isinstance(payload, dict): |
| 66 | + for group_name, group in payload.items(): |
| 67 | + if not isinstance(group, dict): |
| 68 | + continue |
| 69 | + if not isinstance(params := group.get("parameters"), dict): |
| 70 | + continue |
| 71 | + for param_name, param in params.items(): |
| 72 | + if not isinstance(param, dict): |
| 73 | + continue |
| 74 | + filtered = {k: v for k, v in param.items() if k in PARAM_KEEP_KEYS} |
| 75 | + if isinstance(options := filtered.get("options"), list): |
| 76 | + filtered["options"] = normalize_options(options) |
| 77 | + if isinstance(html_value := filtered.pop("html", None), str): |
| 78 | + filtered["description"] = html_to_markdown(html_value) |
| 79 | + if filtered: |
| 80 | + filtered["group"] = group_name |
| 81 | + if group_name == "serpapi_parameters": |
| 82 | + common_params[param_name] = filtered |
| 83 | + else: |
| 84 | + normalized_params[param_name] = filtered |
| 85 | + |
| 86 | + return {"engine": engine, "params": normalized_params, "common_params": common_params} |
| 87 | + |
| 88 | + |
| 89 | +def main() -> int: |
| 90 | + """Main entry point: fetch playground data and generate engine files.""" |
| 91 | + props = fetch_props(PLAYGROUND_URL) |
| 92 | + if not isinstance(params := props.get("parameters"), dict): |
| 93 | + raise RuntimeError("Playground props missing 'parameters' map.") |
| 94 | + |
| 95 | + OUTPUT_DIR.mkdir(parents=True, exist_ok=True) |
| 96 | + engines = [] |
| 97 | + |
| 98 | + for engine, payload in sorted(params.items()): |
| 99 | + if not isinstance(engine, str) or engine in EXCLUDED_ENGINES: |
| 100 | + continue |
| 101 | + if not isinstance(payload, dict): |
| 102 | + continue |
| 103 | + (OUTPUT_DIR / f"{engine}.json").write_text( |
| 104 | + json.dumps(normalize_engine(engine, payload), indent=2), encoding="utf-8" |
| 105 | + ) |
| 106 | + engines.append(engine) |
| 107 | + |
| 108 | + print(f"Wrote {len(engines)} engine files to {OUTPUT_DIR}") |
| 109 | + return 0 |
| 110 | + |
| 111 | + |
| 112 | +if __name__ == "__main__": |
| 113 | + raise SystemExit(main()) |
0 commit comments