#!/usr/bin/env python3 """영문 질문뱅크 3엔진 비교 집계 (OpenAI / Perplexity / Google AI Overview). 뷰성형외과·JK성형외과·ID병원의 언급률과 순위를 엔진별·카테고리별로 낸다. C군(발견 질문)은 문항별 헤드투헤드 표를 따로 만든다. 사용: python3 scripts/compare_engines_en.py [--out ] """ 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()