feat: 영문 질문뱅크 러너에 Claude·Google AI Overview 엔진과 반복 회차를 추가하고 엔진별 비교 집계와 실측 결과를 넣는다
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e4cbc64517
commit
81b6ad06b6
9 files changed
+805
-12
No files matched your search
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
"""영문 질문뱅크 3엔진 비교 집계 (OpenAI / Perplexity / Google AI Overview).
|
||||
|
||||
뷰성형외과·JK성형외과·ID병원의 언급률과 순위를 엔진별·카테고리별로 낸다.
|
||||
C군(발견 질문)은 문항별 헤드투헤드 표를 따로 만든다.
|
||||
|
||||
사용: python3 scripts/compare_engines_en.py [--out <md경로>]
|
||||
"""
|
||||
import argparse, ast, collections, json, os
|
||||
from urllib.parse import urlparse
|
||||
|
||||
DIR = "docs/reports/viewclinic/05_global_en"
|
||||
ENGINES = [("openai", "OpenAI"), ("perplexity", "Perplexity"), ("google_ai_overview", "Google AI Overview")]
|
||||
|
||||
|
||||
def norm(name):
|
||||
l = (name or "").lower()
|
||||
if "view" in l:
|
||||
return "뷰"
|
||||
if l.startswith("jk") or "jk plastic" in l:
|
||||
return "JK"
|
||||
if "id hospital" in l or l.strip() in ("id", "id hospital"):
|
||||
return "ID"
|
||||
return None
|
||||
|
||||
|
||||
def load(eng):
|
||||
p = f"{DIR}/qb_en_{eng}_results.jsonl"
|
||||
if not os.path.exists(p):
|
||||
return []
|
||||
return [json.loads(l) for l in open(p, encoding="utf-8")]
|
||||
|
||||
|
||||
def clinics_of(d):
|
||||
c = d.get("clinics") or []
|
||||
if isinstance(c, str):
|
||||
try:
|
||||
c = ast.literal_eval(c)
|
||||
except Exception:
|
||||
c = []
|
||||
return c
|
||||
|
||||
|
||||
def urls_of(d):
|
||||
u = d.get("urls") or []
|
||||
if isinstance(u, str):
|
||||
try:
|
||||
u = ast.literal_eval(u)
|
||||
except Exception:
|
||||
u = []
|
||||
return u
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--out")
|
||||
a = ap.parse_args()
|
||||
|
||||
data = {e: load(e) for e, _ in ENGINES}
|
||||
qtext = {}
|
||||
qb = json.load(open(f"{DIR}/question_bank_en.json"))
|
||||
items = qb if isinstance(qb, list) else qb.get("questions") or qb.get("items")
|
||||
for q in items:
|
||||
qtext[q["id"]] = q["question"]
|
||||
|
||||
L = []
|
||||
L.append("## 엔진별 언급률\n")
|
||||
L.append("| 엔진 | 문항 | 뷰 언급 | 뷰 1위 | JK 언급 | ID 언급 |")
|
||||
L.append("|---|---|---|---|---|---|")
|
||||
for eng, label in ENGINES:
|
||||
rows = data[eng]
|
||||
if not rows:
|
||||
L.append(f"| {label} | 미실측 | - | - | - | - |")
|
||||
continue
|
||||
cnt = collections.Counter(); first = 0
|
||||
for d in rows:
|
||||
seen = set()
|
||||
for i, c in enumerate(clinics_of(d)):
|
||||
k = norm(c)
|
||||
if k and k not in seen:
|
||||
seen.add(k); cnt[k] += 1
|
||||
if k == "뷰" and i == 0:
|
||||
first += 1
|
||||
n = len(rows)
|
||||
L.append(f"| {label} | {n} | {cnt['뷰']} ({cnt['뷰']/n*100:.0f}%) | {first} | "
|
||||
f"{cnt['JK']} ({cnt['JK']/n*100:.0f}%) | {cnt['ID']} ({cnt['ID']/n*100:.0f}%) |")
|
||||
|
||||
L.append("\n## 발견 질문(C군) 문항별 헤드투헤드\n")
|
||||
head = "| 문항 | 질문 | " + " | ".join(l for _, l in ENGINES) + " |"
|
||||
L.append(head)
|
||||
L.append("|---|---|" + "---|" * len(ENGINES))
|
||||
byq = {}
|
||||
for eng, _ in ENGINES:
|
||||
for d in data[eng]:
|
||||
if d.get("cat") != "C":
|
||||
continue
|
||||
m = {}
|
||||
for i, c in enumerate(clinics_of(d)):
|
||||
k = norm(c)
|
||||
if k and k not in m:
|
||||
m[k] = i + 1
|
||||
byq.setdefault(d["id"], {})[eng] = m
|
||||
|
||||
def fmt(m):
|
||||
if m is None:
|
||||
return "미실측"
|
||||
if not m:
|
||||
return "없음"
|
||||
return ", ".join(f"{k}({v})" for k, v in sorted(m.items(), key=lambda x: x[1]))
|
||||
|
||||
tot = collections.Counter()
|
||||
for qid in sorted(byq):
|
||||
cells = [fmt(byq[qid].get(e)) for e, _ in ENGINES]
|
||||
for k in ("뷰", "JK", "ID"):
|
||||
if any(k in (byq[qid].get(e) or {}) for e, _ in ENGINES):
|
||||
tot[k] += 1
|
||||
L.append(f"| {qid} | {qtext.get(qid,'')[:52]} | " + " | ".join(cells) + " |")
|
||||
L.append(f"\nC군 {len(byq)}문항 중 한 엔진 이상 등장: 뷰 {tot['뷰']}, JK {tot['JK']}, ID {tot['ID']}\n")
|
||||
|
||||
L.append("## 엔진별 인용 도메인 상위 10 (C군)\n")
|
||||
for eng, label in ENGINES:
|
||||
dom = collections.Counter()
|
||||
for d in data[eng]:
|
||||
if d.get("cat") != "C":
|
||||
continue
|
||||
for h in {urlparse(u).netloc.replace("www.", "") for u in urls_of(d) if u}:
|
||||
dom[h] += 1
|
||||
if not dom:
|
||||
L.append(f"**{label}**: 미실측\n")
|
||||
continue
|
||||
L.append(f"**{label}**: " + ", ".join(f"{h}({c})" for h, c in dom.most_common(10)) + "\n")
|
||||
|
||||
out = "\n".join(L)
|
||||
print(out)
|
||||
if a.out:
|
||||
open(a.out, "w", encoding="utf-8").write(out)
|
||||
print(f"\n저장: {a.out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -73,13 +73,15 @@ def domain(u):
|
||||
return u
|
||||
|
||||
|
||||
def out_path(d, engine):
|
||||
return os.path.join(d, f"qb_en_{engine}_results.jsonl")
|
||||
def out_path(d, engine, rep=1):
|
||||
"""rep=1 은 기존 파일명을 그대로 쓴다(기존 실측 보존). rep>=2 는 _repN 접미사."""
|
||||
suffix = "" if rep <= 1 else f"_rep{rep}"
|
||||
return os.path.join(d, f"qb_en_{engine}{suffix}_results.jsonl")
|
||||
|
||||
|
||||
def load_done(d, engine):
|
||||
def load_done(d, engine, rep=1):
|
||||
done = {}
|
||||
p = out_path(d, engine)
|
||||
p = out_path(d, engine, rep)
|
||||
if os.path.exists(p):
|
||||
for line in open(p):
|
||||
if line.strip():
|
||||
@@ -87,8 +89,8 @@ def load_done(d, engine):
|
||||
return done
|
||||
|
||||
|
||||
def summarize(d, engine, qfile):
|
||||
done = load_done(d, engine)
|
||||
def summarize(d, engine, qfile, rep=1):
|
||||
done = load_done(d, engine, rep)
|
||||
qs = json.load(open(qfile))
|
||||
cats = {"A": "Brand", "B": "Travel & logistics", "C": "Recommendation & comparison", "D": "Procedure info",
|
||||
"E": "Pricing", "F": "Safety & trust", "G": "Aftercare & remote follow-up"}
|
||||
@@ -136,7 +138,9 @@ def summarize(d, engine, qfile):
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--engine", choices=["openai", "perplexity"], default="perplexity")
|
||||
ap.add_argument("--engine", choices=["openai", "perplexity", "claude", "google_ai_overview"], default="perplexity")
|
||||
ap.add_argument("--rep", type=int, default=1, help="반복 회차. 2 이상이면 별도 파일(_repN)에 기록한다")
|
||||
ap.add_argument("--search-max-uses", type=int, default=5, help="claude 전용: 한 질문당 최대 웹검색 횟수")
|
||||
ap.add_argument("--model", default=None)
|
||||
ap.add_argument("--search-tool", default="web_search")
|
||||
ap.add_argument("--country", default="US"); ap.add_argument("--city", default="New York"); ap.add_argument("--tz", default="America/New_York")
|
||||
@@ -148,14 +152,21 @@ def main():
|
||||
base.load_dotenv()
|
||||
if a.summarize:
|
||||
summarize(a.dir, a.engine, a.questions); return
|
||||
eng = OpenAIEngineLoc(a.model or "gpt-4o", a.search_tool, a.country, a.city, a.tz) if a.engine == "openai" \
|
||||
else base.PerplexityEngine(a.model or "sonar")
|
||||
if a.engine == "openai":
|
||||
eng = OpenAIEngineLoc(a.model or "gpt-4o", a.search_tool, a.country, a.city, a.tz)
|
||||
elif a.engine == "google_ai_overview":
|
||||
eng = base.GoogleAIOverviewEngine(country=(a.country or "US").lower(), lang="en")
|
||||
elif a.engine == "claude":
|
||||
eng = base.ClaudeEngine(a.model or "claude-sonnet-5", a.search_max_uses,
|
||||
{"type": "approximate", "country": a.country, "city": a.city, "timezone": a.tz})
|
||||
else:
|
||||
eng = base.PerplexityEngine(a.model or "sonar")
|
||||
os.makedirs(a.dir, exist_ok=True)
|
||||
qs = json.load(open(a.questions)); done = load_done(a.dir, a.engine)
|
||||
qs = json.load(open(a.questions)); done = load_done(a.dir, a.engine, a.rep)
|
||||
todo = [q for q in qs if q["id"] not in done]
|
||||
if a.limit: todo = todo[:a.limit]
|
||||
print(f"{eng.name}: {len(todo)} to run ({len(done)} done)", flush=True)
|
||||
with open(out_path(a.dir, a.engine), "a") as f:
|
||||
with open(out_path(a.dir, a.engine, a.rep), "a") as f:
|
||||
for i, q in enumerate(todo, 1):
|
||||
t0 = time.time()
|
||||
try:
|
||||
|
||||
@@ -176,6 +176,119 @@ class PerplexityEngine:
|
||||
return text, urls
|
||||
|
||||
|
||||
class ClaudeEngine:
|
||||
"""Claude Messages API + web_search 서버 도구.
|
||||
|
||||
OpenAI web_search / Perplexity sonar 와 같은 층위의 '검색을 하는 답변엔진'이다.
|
||||
공식 API 이며, 2026-09-18 확인 기준 결과의 분석·저장을 금지하는 조항이 없다
|
||||
(Gemini API 추가 약관의 Grounded Results 조항과 대비).
|
||||
"""
|
||||
name = "claude"
|
||||
|
||||
def __init__(self, model, max_uses=5, user_location=None):
|
||||
self.key = os.environ.get("ANTHROPIC_API_KEY")
|
||||
if not self.key:
|
||||
sys.exit("ANTHROPIC_API_KEY가 필요합니다 (.env)")
|
||||
self.model = model
|
||||
self.max_uses = max_uses
|
||||
self.loc = user_location
|
||||
|
||||
def ask(self, question):
|
||||
tool = {"type": "web_search_20250305", "name": "web_search", "max_uses": self.max_uses}
|
||||
if self.loc:
|
||||
tool["user_location"] = self.loc
|
||||
msgs = [{"role": "user", "content": question}]
|
||||
texts, urls = [], []
|
||||
# 검색이 길면 stop_reason=pause_turn 으로 끊긴다. 받은 그대로 되돌려 이어 붙인다.
|
||||
for _ in range(4):
|
||||
resp = post_retry("https://api.anthropic.com/v1/messages",
|
||||
{"model": self.model, "max_tokens": 2048,
|
||||
"messages": msgs, "tools": [tool]},
|
||||
{"x-api-key": self.key, "anthropic-version": "2023-06-01"})
|
||||
content = resp.get("content") or []
|
||||
for blk in content:
|
||||
t = blk.get("type")
|
||||
if t == "text":
|
||||
texts.append(blk.get("text", ""))
|
||||
for c in blk.get("citations") or []:
|
||||
if c.get("url"):
|
||||
urls.append(c["url"])
|
||||
elif t == "web_search_tool_result":
|
||||
body = blk.get("content")
|
||||
if isinstance(body, list):
|
||||
for r in body:
|
||||
if isinstance(r, dict) and r.get("url"):
|
||||
urls.append(r["url"])
|
||||
if resp.get("stop_reason") != "pause_turn":
|
||||
break
|
||||
msgs = msgs + [{"role": "assistant", "content": content}]
|
||||
seen, out = set(), []
|
||||
for u in urls:
|
||||
if u not in seen:
|
||||
seen.add(u); out.append(u)
|
||||
return "\n".join(texts).strip(), out
|
||||
|
||||
|
||||
class GoogleAIOverviewEngine:
|
||||
"""SerpApi google_ai_overview. Google 검색의 AI Overview 답변을 받는다.
|
||||
|
||||
2단계다. engine=google 이 page_token 만 주고, engine=google_ai_overview 로 본문을 다시 받는다.
|
||||
따라서 질문 1개당 SerpApi 검색을 2회 소모한다.
|
||||
|
||||
주의: 이 경로는 Gemini API 가 아니라 제3자 수집이다. SerpApi 의 스크래핑 책임 인수
|
||||
(Legal Shield)는 Free·Starter·Developer 플랜에 적용되지 않는다. 2026-09-18 확인 기준
|
||||
이 계정은 Free Plan 이므로 수집 책임은 우리에게 있다. 법무 검토 대상.
|
||||
"""
|
||||
name = "google_ai_overview"
|
||||
|
||||
def __init__(self, country="us", lang="en", no_cache=False):
|
||||
self.key = os.environ.get("SERPAPI_API_KEY")
|
||||
if not self.key:
|
||||
sys.exit("SERPAPI_API_KEY가 필요합니다 (.env). serpapi.com 대시보드의 API Key")
|
||||
self.gl, self.hl, self.no_cache = country, lang, no_cache
|
||||
self.model = f"serpapi:google_ai_overview:{country}"
|
||||
self.last_meta = {}
|
||||
|
||||
@staticmethod
|
||||
def _flatten(blocks, acc):
|
||||
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):
|
||||
GoogleAIOverviewEngine._flatten(b[k], acc)
|
||||
return acc
|
||||
|
||||
def ask(self, question):
|
||||
p1 = {"engine": "google", "q": question, "hl": self.hl, "gl": self.gl, "api_key": self.key}
|
||||
if self.no_cache:
|
||||
p1["no_cache"] = "true"
|
||||
r1 = get_retry("https://serpapi.com/search.json?" + urllib.parse.urlencode(p1))
|
||||
ao = r1.get("ai_overview") if isinstance(r1.get("ai_overview"), dict) else None
|
||||
if not ao:
|
||||
self.last_meta = {"overview": False, "reason": "AI Overview 미노출"}
|
||||
return "", []
|
||||
blocks, refs = ao.get("text_blocks"), ao.get("references") or []
|
||||
token = ao.get("page_token")
|
||||
if not blocks and token:
|
||||
p2 = {"engine": "google_ai_overview", "page_token": token, "api_key": self.key}
|
||||
r2 = get_retry("https://serpapi.com/search.json?" + urllib.parse.urlencode(p2))
|
||||
ao2 = r2.get("ai_overview") if isinstance(r2.get("ai_overview"), dict) else r2
|
||||
blocks = ao2.get("text_blocks")
|
||||
refs = ao2.get("references") or refs
|
||||
text = " ".join(self._flatten(blocks, [])).strip()
|
||||
urls = [r["link"] for r in refs if isinstance(r, dict) and r.get("link")]
|
||||
seen, out = set(), []
|
||||
for u in urls:
|
||||
if u not in seen:
|
||||
seen.add(u); out.append(u)
|
||||
self.last_meta = {"overview": bool(text), "gl": self.gl,
|
||||
"sources": [{"source": r.get("source"), "link": r.get("link")} for r in refs][:10]}
|
||||
return text, out
|
||||
|
||||
|
||||
class NaverBriefingEngine:
|
||||
"""SerpApi naver_ai_overview. 반환 (answer, urls). 브리핑이 없으면 ("", []) 와 self.last_meta.briefing=False."""
|
||||
name = "naver_briefing"
|
||||
@@ -266,6 +379,8 @@ def summarize(engine):
|
||||
return
|
||||
label = {"openai": "OpenAI 웹검색(Responses API + web_search, 서울 고정)",
|
||||
"perplexity": "Perplexity API (sonar)",
|
||||
"claude": "Claude Messages API + web_search 서버 도구",
|
||||
"google_ai_overview": "Google AI Overview (SerpApi google_ai_overview, 제3자 SERP API)",
|
||||
"naver_briefing": "네이버 AI 브리핑 (SerpApi naver_ai_overview, 제3자 SERP API)"}[engine]
|
||||
qs = json.load(open(QUESTIONS))
|
||||
freq, mentioned = {}, 0
|
||||
@@ -304,7 +419,8 @@ def summarize(engine):
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--engine", choices=["openai", "perplexity", "naver_briefing"], default="openai")
|
||||
ap.add_argument("--engine", choices=["openai", "perplexity", "claude", "google_ai_overview", "naver_briefing"], default="openai")
|
||||
ap.add_argument("--search-max-uses", type=int, default=5, help="claude 전용: 한 질문당 최대 웹검색 횟수")
|
||||
ap.add_argument("--device", choices=["mobile", "desktop"], default="mobile", help="naver_briefing 전용")
|
||||
ap.add_argument("--no-cache", action="store_true", help="naver_briefing 반복 측정 시 SerpApi 캐시 무시")
|
||||
ap.add_argument("--model", default=None)
|
||||
@@ -321,6 +437,10 @@ def main():
|
||||
|
||||
if args.engine == "openai":
|
||||
eng = OpenAIEngine(args.model or "gpt-4o", args.search_tool)
|
||||
elif args.engine == "claude":
|
||||
eng = ClaudeEngine(args.model or "claude-sonnet-5", args.search_max_uses)
|
||||
elif args.engine == "google_ai_overview":
|
||||
eng = GoogleAIOverviewEngine(no_cache=args.no_cache)
|
||||
elif args.engine == "naver_briefing":
|
||||
eng = NaverBriefingEngine(args.device, args.no_cache)
|
||||
else:
|
||||
|
||||
Reference in new issue
Block a user