#!/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": {{"": position or null, ...}}, "sentiment": {{"": "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"(?= 5 and core.title() not in COMMON_EN and core not in COMMON_EN and bool(re.search(r"(?