Files
o2o-infinith-demo/docs/reports/outbound_webforai/run_outbound_probe.py
T

346 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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 reextract(engine, rep=1):
"""앞선 병원 명단으로 추출한 답변을, 나중에 추가한 병원 기준으로 다시 추출한다.
비브랜드 질문은 답변을 다시 쓰므로 새 병원의 targets 가 없으면 '언급 없음'으로 잘못 판정된다.
이미 있는 병원의 targets·sentiment 와 clinics 목록은 바꾸지 않고 새 병원 키만 더한다."""
clinics, template = load("pilot_clinics.json"), load("question_template.json")
_, plan = expand(clinics, template)
rows = [json.loads(x) for x in open(out_path(engine, rep)) if x.strip()] if os.path.exists(out_path(engine, rep)) else []
changed = 0
for r in rows:
missing = [c for c in clinics if r["id"] in plan[c["name"]].values()
and c["name"] not in (r.get("targets") or {})]
if not missing or not r.get("answer"):
continue
ext = extract(r["answer"], missing)
if "parse_error" in ext:
print(f" {r['id']} 추출 실패: {ext['parse_error'][:80]}", flush=True)
continue
names = {c["name"] for c in missing}
r.setdefault("targets", {}).update({k: v for k, v in ext.get("targets", {}).items() if k in names})
r.setdefault("sentiment", {}).update({k: v for k, v in (ext.get("sentiment") or {}).items() if k in names})
r["reextracted"] = sorted(set(r.get("reextracted", [])) | names)
changed += 1
tmp = out_path(engine, rep) + ".tmp"
with open(tmp, "w") as f:
f.writelines(json.dumps(r, ensure_ascii=False) + "\n" for r in rows)
os.replace(tmp, out_path(engine, rep))
print(f"{engine} rep{rep}: {changed}건 재추출", flush=True)
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)
# 병원명 질문에 "그 이름의 병원을 특정할 정보가 없다"고 답한 경우. 병원을 설명하면서 "논란은 확인되지 않았다"고 쓴 답변은 잡지 않는다
NO_CLINIC_RE = re.compile(r"(?:isn['’]t|not) enough reliable(?:,? clinic-specific)?(?: public)? (?:information|evidence)|"
r"couldn['’]t find reliable information (?:about|on) a clinic", re.I)
CORE_SUFFIX_KO = re.compile(r"(?:성형외과의원|성형외과|의원|병원)$")
CORE_SUFFIX_EN = re.compile(r"\s*(?:Plastic Surgery(?: Clinic| Center| Hospital)?|Hospital|Clinic)$", re.I)
def name_terms(c):
"""답변 원문에서 이 병원을 가리키는 표기: 정식명·영문명·별칭·주소 키와 접미어를 뗀 핵심 이름."""
terms = [c["name"], c.get("name_en", ""), *c.get("aliases", []), *c.get("address_keys", [])]
terms += [CORE_SUFFIX_KO.sub("", c["name"]), CORE_SUFFIX_EN.sub("", c.get("name_en", ""))]
return [t.strip() for t in terms if t and len(t.strip()) >= 2]
def contains(answer, t):
"""대소문자 무시 부분 일치. 영문·숫자로 시작하는 표기는 앞에 단어 경계를 요구한다
("H Plastic Surgery" 가 "Sketch Plastic Surgery" 끝부분에 걸리는 오판 방지, 2026-11-18)"""
if re.match(r"[A-Za-z0-9]", t):
return bool(re.search(r"(?<![A-Za-z0-9])" + re.escape(t), answer, re.I))
return t.lower() in answer.lower()
def named_in(answer, c):
"""짧은 표기(3자 이하, 예: ID·JK)는 대소문자를 지키고 단어 경계로, 나머지는 대소문자 무시 부분 일치로 찾는다."""
for t in name_terms(c):
if len(t) <= 3:
if re.search(r"(?<![A-Za-z0-9])" + re.escape(t) + r"(?![A-Za-z0-9])", answer):
return True
elif contains(answer, t):
return True
return False
COMMON_EN = {"Grand", "Opera", "Star", "Mind", "Note", "Nana", "Seoul", "Eight"}
def named_strict(answer, c):
"""추출기가 놓친 언급을 찾을 때 쓰는 엄격한 대조: 정식명·영문명·별칭(대소문자 무시)과,
5자 이상이고 일반 단어가 아닌 영문 핵심 이름(예: GLOVI)을 대소문자·단어 경계까지 맞춰 찾는다 (2026-11-03)"""
if any(t and contains(answer, t) for t in [c["name"], c.get("name_en", ""), *c.get("aliases", [])]):
return True
core = CORE_SUFFIX_EN.sub("", c.get("name_en", "")).strip()
return (len(core) >= 5 and core.title() not in COMMON_EN and core not in COMMON_EN
and bool(re.search(r"(?<![A-Za-z0-9])" + re.escape(core) + r"(?![A-Za-z0-9])", answer)))
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"])
# 추출기가 지역명 등으로 다른 병원을 이 병원으로 잡는 경우가 있다 (예: "UE Plastic Surgery (Apgujeong)" →
# 압구정서울성형외과). 답변 원문에 이 병원 표기가 없으면 추출 결과를 쓰지 않는다 (2026-11-03)
if rank and not named_in(r.get("answer", ""), c):
rank = None
via = "name" if rank else None
# 병원명 질문(Q1)은 질문에 이름이 있어 "정보가 충분하지 않다" 답변에도 이름이 나온다. 그런 답변은 언급으로 세지 않는다
# (2026-11-18 watchdog: Perplexity "There isn't enough reliable public information…" 을 언급으로 집계)
if rank and r.get("slot") == "Q1" and NO_CLINIC_RE.search(r.get("answer", "")[:300]):
rank, via = None, None
# 반대로 추출기가 놓친 언급 (예: "Other known names: Banobagi, GLOVI, ..." 를 None 으로 둠). 원문에 정식 표기가 있으면 언급이다
# 병원명 질문(Q1)은 질문에 이름이 들어 있어 "정보를 찾지 못했다" 답변에도 이름이 나오므로 제외한다
if not rank and r.get("slot") != "Q1" and r.get("answer") and named_strict(r["answer"], c):
rank, via = len([x for x in r.get("clinics", []) if isinstance(x, str)]) + 1, "text"
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])
and not NO_CLINIC_RE.search(r["answer"][:300])):
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")
ap.add_argument("--reextract", action="store_true", help="기존 답변에 새로 추가한 병원 기준 추출을 더한다")
a = ap.parse_args()
base.load_dotenv()
if a.summarize:
summarize()
elif a.engine and a.reextract:
reextract(a.engine, a.rep)
elif a.engine:
run(a.engine, a.model, a.sleep, a.rep)
else:
ap.error("--engine 또는 --summarize 가 필요합니다")