255 lines
12 KiB
Python
255 lines
12 KiB
Python
#!/usr/bin/env python3
|
||
"""아웃바운드 소개서용 병원별 AI 답변 실측 러너.
|
||
|
||
병원 명단(pilot_clinics.json) × 질문 템플릿(question_template.json)을 한국어 5문항·영문 5문항으로 펼친다.
|
||
문장이 같은 질문(비브랜드)은 한 번만 질의하고, 답변 하나를 명단 전체에 대조한다.
|
||
|
||
엔진은 scripts/run_question_bank_openai.py · run_question_bank_en.py 의 클래스를 그대로 쓴다.
|
||
- openai: 한국어는 서울, 영문은 미국 뉴욕 위치 고정
|
||
- claude: openai 와 같은 위치 설정
|
||
- google_ai_overview: 한국어 gl=kr/hl=ko, 영문 gl=us/hl=en (SerpApi, 질문당 최대 2회 과금)
|
||
- perplexity: 위치 파라미터 없음. 질문 언어로만 구분
|
||
|
||
사용:
|
||
python3 docs/reports/outbound_webforai/run_outbound_probe.py --engine perplexity
|
||
python3 docs/reports/outbound_webforai/run_outbound_probe.py --summarize
|
||
"""
|
||
import argparse
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import re
|
||
import sys
|
||
import time
|
||
from urllib.parse import urlparse
|
||
|
||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(HERE)))
|
||
sys.path.insert(0, os.path.join(ROOT, "scripts"))
|
||
import run_question_bank_openai as base # noqa: E402
|
||
import run_question_bank_en as en # noqa: E402
|
||
|
||
ENGINES = ["openai", "perplexity", "claude", "google_ai_overview"]
|
||
LOC = {"kr": ("KR", "Seoul", "Asia/Seoul"), "en": ("US", "New York", "America/New_York")}
|
||
|
||
EXTRACT_PROMPT = """Below is an answer from an AI search engine. Do two things.
|
||
1. List the plastic surgery clinics / hospitals mentioned, in order of appearance, up to 10. Clinic names only: exclude platforms, apps, media, agencies, associations (e.g. Gangnam Unni, Babitalk, RealSelf, Reddit, Bookimed, Naver, KAPS are NOT clinics).
|
||
2. For each TARGET clinic below, give its 1-based position in that list, or null if it is not mentioned. Spelling variants, Korean/English names and aliases count as the same clinic.
|
||
|
||
TARGET clinics:
|
||
{roster}
|
||
|
||
Output JSON only:
|
||
{{"clinics": ["Clinic 1", ...], "targets": {{"<target name exactly as listed>": position or null, ...}}, "sentiment": {{"<target name>": "positive"|"neutral"|"negative"}}}}
|
||
(sentiment only for mentioned targets)
|
||
|
||
Answer:
|
||
"""
|
||
|
||
|
||
def load(name):
|
||
return json.load(open(os.path.join(HERE, name)))
|
||
|
||
|
||
def qid(lang, text):
|
||
return f"{lang}-" + hashlib.sha1(text.encode()).hexdigest()[:10]
|
||
|
||
|
||
def expand(clinics, template):
|
||
"""반환: (unique 질문 목록, 병원별 슬롯 → qid 매핑)."""
|
||
questions, plan = {}, {}
|
||
for c in clinics:
|
||
plan[c["name"]] = {}
|
||
for lang, slots in template.items():
|
||
for s in slots:
|
||
text = s["template"].format(**c)
|
||
q = qid(lang, text)
|
||
questions.setdefault(q, {"id": q, "lang": lang, "slot": s["slot"], "type": s["type"], "question": text})
|
||
plan[c["name"]][f"{lang}:{s['slot']}"] = q
|
||
return list(questions.values()), plan
|
||
|
||
|
||
def make_engine(engine, lang, model, no_cache=False):
|
||
country, city, tz = LOC[lang]
|
||
if engine == "openai":
|
||
if lang == "kr":
|
||
return base.OpenAIEngine(model or "gpt-4o", "web_search")
|
||
return en.OpenAIEngineLoc(model or "gpt-4o", "web_search", country, city, tz)
|
||
if engine == "claude":
|
||
# WebforAI 전용 키만 쓴다 (haewon 지시 2026-10-26). 다른 프로젝트의 ANTHROPIC_API_KEY 로 대체하지 않는다
|
||
key = os.environ.get("WEBFORAI_ANTHROPIC_API_KEY") or os.environ.get("CLAUDE_API_KEY")
|
||
if not key:
|
||
sys.exit("WebforAI 전용 Claude 키가 필요합니다 (.env 의 WEBFORAI_ANTHROPIC_API_KEY 또는 CLAUDE_API_KEY)")
|
||
os.environ["ANTHROPIC_API_KEY"] = key # base.ClaudeEngine 이 읽는 이름. 이 프로세스 안에서만 바뀐다
|
||
return base.ClaudeEngine(model or "claude-sonnet-5-5", 5,
|
||
{"type": "approximate", "country": country, "city": city, "timezone": tz})
|
||
if engine == "google_ai_overview":
|
||
return base.GoogleAIOverviewEngine(country=country.lower(), lang="ko" if lang == "kr" else "en",
|
||
no_cache=no_cache)
|
||
return base.PerplexityEngine(model or "sonar")
|
||
|
||
|
||
def extract(answer, clinics):
|
||
roster = "\n".join(f"- {c['name']} (also: {c['name_en']}, {', '.join(c['aliases'])})" for c in clinics)
|
||
resp = base.post_retry("https://api.openai.com/v1/responses",
|
||
{"model": "gpt-4o-mini", "input": EXTRACT_PROMPT.format(roster=roster) + answer[:9000]},
|
||
{"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"})
|
||
text, _ = base.openai_answer_text(resp)
|
||
m = re.search(r"\{.*\}", text or "", re.S)
|
||
try:
|
||
return json.loads(m.group(0)) if m else {"clinics": [], "targets": {}, "parse_error": (text or "")[:200]}
|
||
except json.JSONDecodeError:
|
||
return {"clinics": [], "targets": {}, "parse_error": text[:200]}
|
||
|
||
|
||
def out_path(engine, rep=1):
|
||
"""1회차는 기존 파일명을 그대로 쓴다. 2회차부터 _repN 접미사."""
|
||
return os.path.join(HERE, "results", f"probe_{engine}{'' if rep <= 1 else f'_rep{rep}'}.jsonl")
|
||
|
||
|
||
def load_done(engine, rep=1):
|
||
p = out_path(engine, rep)
|
||
if not os.path.exists(p):
|
||
return {}
|
||
return {r["id"]: r for r in (json.loads(x) for x in open(p) if x.strip())}
|
||
|
||
|
||
def run(engine, model, sleep, rep=1):
|
||
clinics, template = load("pilot_clinics.json"), load("question_template.json")
|
||
questions, _ = expand(clinics, template)
|
||
done = load_done(engine, rep)
|
||
todo = [q for q in questions if q["id"] not in done]
|
||
print(f"{engine} rep{rep}: {len(todo)} to run ({len(done)} done)", flush=True)
|
||
engines = {}
|
||
os.makedirs(os.path.dirname(out_path(engine, rep)), exist_ok=True)
|
||
with open(out_path(engine, rep), "a") as f:
|
||
for i, q in enumerate(todo, 1):
|
||
# 반복 회차는 SerpApi 1시간 캐시를 끄고 새로 조회한다
|
||
eng = engines.setdefault(q["lang"], make_engine(engine, q["lang"], model, no_cache=rep > 1))
|
||
t0 = time.time()
|
||
try:
|
||
answer, urls = eng.ask(q["question"])
|
||
ext = extract(answer, clinics) if answer else {"clinics": [], "targets": {}}
|
||
except Exception as e:
|
||
print(f" [{i}/{len(todo)}] {q['id']} ERROR {e}", flush=True)
|
||
time.sleep(5)
|
||
continue
|
||
row = {**q, "engine": engine, "rep": rep, "model": eng.model, "answer": answer, "urls": urls,
|
||
"meta": getattr(eng, "last_meta", {}), "measured_at": time.strftime("%Y-%m-%dT%H:%M:%S"), **ext}
|
||
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||
f.flush()
|
||
hits = {k: v for k, v in ext.get("targets", {}).items() if v}
|
||
print(f" [{i}/{len(todo)}] {q['lang']} {q['slot']} {q['question'][:40]} -> {hits} urls={len(urls)} ({time.time()-t0:.0f}s)", flush=True)
|
||
time.sleep(sleep)
|
||
|
||
|
||
def domain(u):
|
||
d = urlparse(u).netloc.lower()
|
||
return d[4:] if d.startswith("www.") else d
|
||
|
||
|
||
def address_rank(answer, keys):
|
||
"""SerpApi 는 AI 개요 목록의 제목(병원명)을 빼고 '위치: …' 본문만 준다. 고유 주소로 대조해 목록 순번을 낸다."""
|
||
for k in keys:
|
||
pos = answer.find(k)
|
||
if pos >= 0:
|
||
return max(1, len(re.findall(r"위치\s*:|Location\s*:", answer[:pos])))
|
||
return None
|
||
|
||
|
||
NO_INFO_RE = re.compile(r"찾을 수 없|확인되지 않|정보가 (?:없|부족)|알 수 없|couldn't find|could not find|no (?:reliable )?information|not able to find", re.I)
|
||
|
||
|
||
def judge(r, c, e):
|
||
"""답변 1개를 병원 1곳 기준으로 판정한다."""
|
||
own = set(c["domains"]) | set(c.get("hub_domains", []))
|
||
doms = [domain(u) for u in r.get("urls", [])]
|
||
rank = (r.get("targets") or {}).get(c["name"])
|
||
via = "name" if rank else None
|
||
if not rank and c.get("address_keys"):
|
||
rank = address_rank(r.get("answer", ""), c["address_keys"])
|
||
via = "address" if rank else None
|
||
# 병원명 질문(Q1)에 "이 병원은…"처럼 이름 없이 그 병원 이야기로 답하면 추출이 놓친다. 정보 없음 답변만 미언급으로 둔다
|
||
if not rank and r.get("slot") == "Q1" and r.get("answer") and not NO_INFO_RE.search(r["answer"][:400]):
|
||
rank, via = 1, "brand-answer"
|
||
others = [x for x in r.get("clinics", []) if isinstance(x, str)]
|
||
return {
|
||
"answered": bool(r.get("answer")),
|
||
"rank": rank,
|
||
"rank_via": via,
|
||
# Google 목록형 답변은 병원명이 빠져 와서, 이름이 하나도 없으면 미언급으로 단정하지 않는다
|
||
"unverifiable": e == "google_ai_overview" and bool(r.get("answer")) and not others and not rank,
|
||
"sentiment": (r.get("sentiment") or {}).get(c["name"]),
|
||
"own_cited": any(d == o or d.endswith("." + o) for d in doms for o in c["domains"]),
|
||
"hub_cited": any(d == o or d.endswith("." + o) for d in doms for o in c.get("hub_domains", [])),
|
||
"n_clinics": len(others),
|
||
"other_clinics": others,
|
||
"top_domains": sorted({d for d in doms if not any(d.endswith(o) for o in own)})[:8],
|
||
"measured_at": r.get("measured_at"),
|
||
}
|
||
|
||
|
||
def summarize():
|
||
"""병원별 10슬롯 × 엔진 매트릭스. 1회차 판정(기존 키) + 회차 집계(runs·valid·hits·cited)."""
|
||
clinics, template = load("pilot_clinics.json"), load("question_template.json")
|
||
questions, plan = expand(clinics, template)
|
||
qmap = {q["id"]: q for q in questions}
|
||
reps = {e: [d for d in (load_done(e, n) for n in (1, 2, 3)) if d] for e in ENGINES}
|
||
matrix = {}
|
||
for c in clinics:
|
||
per = {}
|
||
for key, q in plan[c["name"]].items():
|
||
cell = {"question": qmap[q]["question"], "engines": {}}
|
||
for e in ENGINES:
|
||
judged = [judge(d[q], c, e) for d in reps[e] if q in d]
|
||
if not judged:
|
||
continue
|
||
valid = [j for j in judged if j["answered"] and not j["unverifiable"]]
|
||
cell["engines"][e] = {**judged[0],
|
||
"runs": len(judged), "valid": len(valid),
|
||
"answered_runs": sum(j["answered"] for j in judged),
|
||
"hits": sum(bool(j["rank"]) for j in valid),
|
||
"cited_runs": sum(j["own_cited"] for j in judged),
|
||
"ranks": [j["rank"] for j in judged]}
|
||
per[key] = cell
|
||
matrix[c["name"]] = per
|
||
json.dump(matrix, open(os.path.join(HERE, "results", "matrix.json"), "w"), ensure_ascii=False, indent=1)
|
||
|
||
def mark(x):
|
||
if x is None:
|
||
return "-"
|
||
if not x["answered"]:
|
||
return "미노출"
|
||
if x["unverifiable"]:
|
||
return "확인 불가"
|
||
s = f"{x['rank']}위" + ("(주소)" if x["rank_via"] == "address" else "") if x["rank"] else "X"
|
||
return s + (" ·인용" if x["own_cited"] else "") + (" ·허브인용" if x["hub_cited"] else "")
|
||
lines = [f"# 아웃바운드 파일럿 AI 답변 실측 ({time.strftime('%Y-%m-%d')})", "",
|
||
"표기: N위 = 답변 속 병원 등장 순서, (주소) = 병원명 없이 주소로 확인, X = 언급 없음, "
|
||
"·인용 = 자사 홈페이지가 출처로 인용됨, ·허브인용 = 공식 답변 허브가 인용됨, 미노출 = Google AI 개요가 뜨지 않음, "
|
||
"확인 불가 = Google 목록형 답변이 병원명 없이 수집됨", ""]
|
||
for c in clinics:
|
||
lines += [f"## {c['name']}", "", "| 슬롯 | 질문 | " + " | ".join(ENGINES) + " |", "|---|---|" + "---|" * len(ENGINES)]
|
||
for key, cell in matrix[c["name"]].items():
|
||
lines.append(f"| {key} | {cell['question']} | " + " | ".join(mark(cell["engines"].get(e)) for e in ENGINES) + " |")
|
||
lines.append("")
|
||
open(os.path.join(HERE, "results", "matrix.md"), "w").write("\n".join(lines))
|
||
print("saved results/matrix.md, results/matrix.json")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--engine", choices=ENGINES)
|
||
ap.add_argument("--model", default=None)
|
||
ap.add_argument("--sleep", type=float, default=1.0)
|
||
ap.add_argument("--rep", type=int, default=1, help="반복 회차. 2 이상이면 별도 파일(_repN)에 기록한다")
|
||
ap.add_argument("--summarize", action="store_true")
|
||
a = ap.parse_args()
|
||
base.load_dotenv()
|
||
if a.summarize:
|
||
summarize()
|
||
elif a.engine:
|
||
run(a.engine, a.model, a.sleep, a.rep)
|
||
else:
|
||
ap.error("--engine 또는 --summarize 가 필요합니다")
|