feat(measure): 네이버 AI 브리핑을 질문 뱅크 실측 엔진으로 추가
네이버 AI 브리핑은 공식 API가 없어 지금까지 답변 노출을 재지 못했다. SerpApi naver_ai_overview(제3자 SERP API)로 조회하는 엔진을 붙였다(haewon 결정 2026-09-15). search.naver.com robots.txt 가 수집을 금지하므로 고객 리포트·랜딩에는 넣지 않고 내부 측정까지만 반영했다. 고객 노출은 법무 확인 뒤에 따로 한다. - run_question_bank_openai.py: --engine naver_briefing, --device, --no-cache(반복 측정 시 1시간 캐시 무시). 브리핑이 없는 문항은 answer 를 비우고 briefing=false 로 기록. 인용 출처(sources) 보관 - monthly_ai_measure.py: 기본 엔진 3개(키 없으면 네이버 건너뜀), supporter_builds.report.naverBriefing(노출률·언급·출처 상위, legalReviewed=false) - sentiment_qb.py: 빈 답변은 판정 API를 부르지 않고 미언급 처리 - merge_qb_results.py: NAVER 열·브리핑 없음 표시, 측정일을 생성일이 아닌 엔진별 실제 날짜로 - export_qb_excel.py: 네이버 열·NAVER상세 시트, --out 으로 기존 파일 보존. TOP50 점수는 기존 정의(ChatGPT+Perplexity, 만점 840) 유지 실측(뷰성형외과, 모바일, 2026-09-15): 브리핑 노출 119/120, 브랜드 질문 언급 36/36, 논브랜드 1/84. 인용 출처는 네이버 블로그 87·카페 51·굿닥 23·뷰 공식 20 순. SerpApi 123회, 감성 판정 $0.37. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
eaf60a9cf0
commit
5faf867b05
12 files changed
+827
-207
No files matched your search
@@ -1,11 +1,17 @@
|
||||
#!/usr/bin/env python3
|
||||
"""뷰성형외과 Question Bank 120문항 답변엔진 실측 러너 (OpenAI / Perplexity).
|
||||
"""뷰성형외과 Question Bank 120문항 답변엔진 실측 러너 (OpenAI / Perplexity / 네이버 AI 브리핑).
|
||||
|
||||
측정 방식:
|
||||
- openai: Responses API + web_search 도구 (서울 위치 고정)
|
||||
- perplexity: chat/completions, model=sonar (자체 웹검색 내장)
|
||||
- openai: Responses API + web_search 도구 (서울 위치 고정)
|
||||
- perplexity: chat/completions, model=sonar (자체 웹검색 내장)
|
||||
- naver_briefing: SerpApi naver_ai_overview (제3자 SERP API). 네이버는 공식 API가 없다.
|
||||
ChatGPT 소비자 UI 자동 조회는 약관 위반이므로 쓰지 않는다.
|
||||
|
||||
naver_briefing 은 haewon 결정(2026-09-15)으로 넣었다. search.naver.com robots.txt 가 모든 봇과
|
||||
AI·RAG 목적 수집을 금지하고 있어, 결과를 고객 리포트에 쓰기 전에 법무 확인이 필요하다.
|
||||
브리핑이 뜨지 않는 질문은 answer 를 비우고 briefing=false 로 기록한다(그것도 결과다).
|
||||
SerpApi 는 같은 파라미터를 1시간 캐시한다. 반복 측정은 --no-cache 로 새로 조회한다(검색 1회씩 과금).
|
||||
|
||||
각 질문을 원문 그대로 1회 질의하고, 답변에서 언급된 병원명 상위 5개를
|
||||
후처리 모델(OpenAI gpt-4o-mini, 없으면 Gemini 2.5 Flash)로 추출해 JSONL 기록.
|
||||
재실행 시 완료된 문항은 건너뛴다.
|
||||
@@ -14,6 +20,7 @@ ChatGPT 소비자 UI 자동 조회는 약관 위반이므로 쓰지 않는다.
|
||||
python3 scripts/run_question_bank_openai.py --engine perplexity
|
||||
OPENAI_API_KEY=... python3 scripts/run_question_bank_openai.py --engine openai
|
||||
python3 scripts/run_question_bank_openai.py --engine openai --summarize
|
||||
SERPAPI_API_KEY=... python3 scripts/run_question_bank_openai.py --engine naver_briefing --device mobile --limit 5
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
@@ -23,6 +30,7 @@ import ssl
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
@@ -62,6 +70,28 @@ def post(url, payload, headers, timeout=180):
|
||||
return json.loads(r.read())
|
||||
|
||||
|
||||
def get_retry(url, tries=4, timeout=120):
|
||||
for i in range(tries):
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(url), timeout=timeout, context=SSL_CTX) as r:
|
||||
return json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read().decode(errors="replace")
|
||||
if e.code in (429, 500, 502, 503) and i < tries - 1:
|
||||
time.sleep(15 * (i + 1))
|
||||
continue
|
||||
# 결과 없음도 4xx 본문으로 올 수 있어 JSON 이면 그대로 돌려준다
|
||||
try:
|
||||
return json.loads(body)
|
||||
except json.JSONDecodeError:
|
||||
raise RuntimeError(f"HTTP {e.code}: {body[:500]}") from e
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
if i < tries - 1:
|
||||
time.sleep(10)
|
||||
continue
|
||||
raise
|
||||
|
||||
|
||||
def post_retry(url, payload, headers, tries=4):
|
||||
for i in range(tries):
|
||||
try:
|
||||
@@ -146,6 +176,41 @@ class PerplexityEngine:
|
||||
return text, urls
|
||||
|
||||
|
||||
class NaverBriefingEngine:
|
||||
"""SerpApi naver_ai_overview. 반환 (answer, urls). 브리핑이 없으면 ("", []) 와 self.last_meta.briefing=False."""
|
||||
name = "naver_briefing"
|
||||
|
||||
def __init__(self, device, no_cache):
|
||||
self.key = os.environ.get("SERPAPI_API_KEY")
|
||||
if not self.key:
|
||||
sys.exit("SERPAPI_API_KEY가 필요합니다 (.env). serpapi.com 가입 후 대시보드의 API Key")
|
||||
self.device = device
|
||||
self.no_cache = no_cache
|
||||
self.model = f"serpapi:naver_ai_overview:{device}"
|
||||
self.last_meta = {}
|
||||
|
||||
def ask(self, question):
|
||||
params = {"engine": "naver_ai_overview", "query": question, "device": self.device, "api_key": self.key}
|
||||
if self.no_cache:
|
||||
params["no_cache"] = "true"
|
||||
resp = get_retry("https://serpapi.com/search.json?" + urllib.parse.urlencode(params))
|
||||
ov = resp.get("ai_overview") if isinstance(resp.get("ai_overview"), dict) else resp
|
||||
text = (ov.get("markdown") or "").strip()
|
||||
if not text:
|
||||
text = "\n".join(b.get("snippet", "") for b in ov.get("text_blocks") or [] if isinstance(b, dict)).strip()
|
||||
refs = [r for r in ov.get("references") or [] if isinstance(r, dict)]
|
||||
urls = [r["link"] for r in refs if r.get("link")]
|
||||
self.last_meta = {
|
||||
"briefing": bool(text),
|
||||
"device": self.device,
|
||||
"sources": [{"title": r.get("title"), "source": r.get("source"), "link": r.get("link")} for r in refs][:10],
|
||||
"serpapi_id": (resp.get("search_metadata") or {}).get("id"),
|
||||
}
|
||||
if not text and resp.get("error"):
|
||||
self.last_meta["no_briefing_reason"] = str(resp["error"])[:200]
|
||||
return text, urls
|
||||
|
||||
|
||||
# ---------- extraction ----------
|
||||
|
||||
def extract_clinics(answer):
|
||||
@@ -200,7 +265,8 @@ def summarize(engine):
|
||||
print(f"{engine}: 결과 없음")
|
||||
return
|
||||
label = {"openai": "OpenAI 웹검색(Responses API + web_search, 서울 고정)",
|
||||
"perplexity": "Perplexity API (sonar)"}[engine]
|
||||
"perplexity": "Perplexity API (sonar)",
|
||||
"naver_briefing": "네이버 AI 브리핑 (SerpApi naver_ai_overview, 제3자 SERP API)"}[engine]
|
||||
qs = json.load(open(QUESTIONS))
|
||||
freq, mentioned = {}, 0
|
||||
lines = [f"# 뷰성형외과 Question Bank 실측 결과: {engine}", "",
|
||||
@@ -225,6 +291,8 @@ def summarize(engine):
|
||||
f"{rank if rank else '-'} | {', '.join(clinics) if clinics else '(병원 언급 없음)'} |")
|
||||
lines += ["", "## 집계", "",
|
||||
f"- 뷰성형외과 언급: {mentioned}/{len(done)}문항 ({mentioned*100//max(len(done),1)}%)",
|
||||
*([f"- AI 브리핑 노출: {sum(1 for r in done.values() if r.get('briefing'))}/{len(done)}문항 "
|
||||
"(브리핑이 없으면 언급 없음으로 센다)"] if engine == "naver_briefing" else []),
|
||||
"", "### 병원별 언급 빈도 (상위 15)", "",
|
||||
"| 병원 | 언급 질문 수 | 1순위 등장 수 |", "|---|---|---|"]
|
||||
for name, (cnt, first) in sorted(freq.items(), key=lambda x: -x[1][0])[:15]:
|
||||
@@ -236,7 +304,9 @@ def summarize(engine):
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--engine", choices=["openai", "perplexity"], default="openai")
|
||||
ap.add_argument("--engine", choices=["openai", "perplexity", "naver_briefing"], default="openai")
|
||||
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)
|
||||
ap.add_argument("--search-tool", default="web_search")
|
||||
ap.add_argument("--limit", type=int, default=0)
|
||||
@@ -251,6 +321,8 @@ def main():
|
||||
|
||||
if args.engine == "openai":
|
||||
eng = OpenAIEngine(args.model or "gpt-4o", args.search_tool)
|
||||
elif args.engine == "naver_briefing":
|
||||
eng = NaverBriefingEngine(args.device, args.no_cache)
|
||||
else:
|
||||
eng = PerplexityEngine(args.model or "sonar")
|
||||
|
||||
@@ -271,6 +343,7 @@ def main():
|
||||
row = {"id": q["id"], "question": q["question"], "prior": q["prior"],
|
||||
"engine": args.engine, "model": eng.model,
|
||||
"answer": answer, "citations": urls[:10], **ext,
|
||||
**getattr(eng, "last_meta", {}),
|
||||
"ts": time.strftime("%Y-%m-%dT%H:%M:%S")}
|
||||
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
f.flush()
|
||||
|
||||
Reference in new issue
Block a user