#!/usr/bin/env python3 """영문 헤드 키워드의 Google 일반 검색 순위 + AI Overview 를 한 번에 기록한다. run_question_bank_en.py 의 google_ai_overview 엔진은 AI Overview 만 남기고 일반 검색 결과를 버린다. 키워드("korea plastic surgery" 등)는 사람이 검색창에 치는 말이라 일반 검색 순위도 함께 봐야 하므로, 같은 engine=google 호출에서 organic_results 를 같이 저장한다. SerpApi 소모는 키워드당 1~2회로 같다. 사용: python3 scripts/run_keyword_serp_en.py \ --keywords docs/reports/viewclinic/06_competitor_benchmark/내부용/keyword/keyword_set_en.json \ --out docs/reports/viewclinic/06_competitor_benchmark/내부용/keyword/serp_google_us.jsonl """ import argparse, json, os, sys, time, urllib.parse sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import run_question_bank_openai as base # noqa: E402 import run_question_bank_en as en # noqa: E402 TRACK = {"VIEW": "viewplasticsurgery.com", "JK": "jkplastic.com", "ID": "idhospital.com"} def flatten(blocks, acc): """AI Overview text_blocks 트리에서 snippet 을 순서대로 모은다.""" for b in blocks or []: if not isinstance(b, dict): continue if b.get("snippet"): acc.append(b["snippet"]) for k in ("list", "text_blocks"): if isinstance(b.get(k), list): flatten(b[k], acc) return acc def serp(q, gl, hl, key): p = {"engine": "google", "q": q, "hl": hl, "gl": gl, "num": 20, "api_key": key} return base.get_retry("https://serpapi.com/search.json?" + urllib.parse.urlencode(p)) def ai_overview(r1, key): ao = r1.get("ai_overview") if isinstance(r1.get("ai_overview"), dict) else None if not ao: return "", [], 0 blocks, refs, extra = ao.get("text_blocks"), ao.get("references") or [], 0 if not blocks and ao.get("page_token"): p2 = {"engine": "google_ai_overview", "page_token": ao["page_token"], "api_key": key} r2 = base.get_retry("https://serpapi.com/search.json?" + urllib.parse.urlencode(p2)) extra = 1 ao2 = r2.get("ai_overview") if isinstance(r2.get("ai_overview"), dict) else r2 blocks, refs = ao2.get("text_blocks"), ao2.get("references") or refs text = " ".join(flatten(blocks, [])).strip() urls = list(dict.fromkeys(r["link"] for r in refs if isinstance(r, dict) and r.get("link"))) return text, urls, extra def main(): ap = argparse.ArgumentParser() ap.add_argument("--keywords", required=True) ap.add_argument("--out", required=True) ap.add_argument("--gl", default="us"); ap.add_argument("--hl", default="en") a = ap.parse_args() base.load_dotenv() key = os.environ.get("SERPAPI_API_KEY") or sys.exit("SERPAPI_API_KEY가 필요합니다 (.env)") done = set() if os.path.exists(a.out): done = {json.loads(l)["id"] for l in open(a.out) if l.strip()} used = 0 with open(a.out, "a") as f: for k in json.load(open(a.keywords)): if k["id"] in done: continue r1 = serp(k["question"], a.gl, a.hl, key); used += 1 if r1.get("error"): print(f" {k['id']} ERROR {r1['error']}", flush=True); continue organic = [{"position": o.get("position"), "link": o.get("link"), "title": o.get("title"), "domain": en.domain(o.get("link", ""))} for o in r1.get("organic_results", [])] ranks = {name: next((o["position"] for o in organic if dom in (o["domain"] or "")), None) for name, dom in TRACK.items()} text, urls, extra = ai_overview(r1, key); used += extra ext = en.extract_clinics(text) if text else {"clinics": [], "view_mentioned": False, "view_rank": None} row = {"id": k["id"], "keyword": k["question"], "gl": a.gl, "organic_ranks": ranks, "organic": organic, "ai_overview": bool(text), "answer": text, "urls": urls, "measured_at": time.strftime("%Y-%m-%dT%H:%M:%S"), **ext} f.write(json.dumps(row, ensure_ascii=False) + "\n"); f.flush() print(f" {k['id']} {k['question']!r} organic={ranks} ao={'O' if text else 'X'} " f"clinics={ext.get('clinics', [])[:5]}", flush=True) print(f"SerpApi 검색 {used}회 사용") if __name__ == "__main__": main()