""" 병원별 아웃바운드 메일 본문(HTML)과 본문 상단 이미지(소개서 4장 PNG)를 만든다. - 흐름: ① 문제 제기 → ② 진단(표) → ③ 원인 → ④ 개선 → ⑤ 8주 후 → 미팅 요청 - 수치·출처·점검 항목은 build_diagnosis_report.report_data 에서 가져온다 (소개서·보고서와 같은 값) - 효과는 약속하지 않는다: "인용할 수 있는 근거가 생긴다", "다시 측정해 보여 드린다" 까지만 쓴다 - 서명은 넣지 않는다 (발송인이 직접 추가) python3 docs/reports/outbound_webforai/build_mail_drafts.py <출력 json> --clinics=<병원>,<병원>,... [--images=<소개서 폴더>,<이미지 폴더>] [--roadmap=<이미지 폴더>] - 메일 이미지용 소개서는 소개서 폴더에서 병원별 가장 높은 버전(WebforAI_소개서_{병원}_v{N}_*.pptx)을 고른다 """ import json import os import re import subprocess import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import build_diagnosis_report as report # noqa: E402 import run_outbound_probe as probe # noqa: E402 # 문제 제기에 쓰는 환자 질문 (핵심 발견 질문을 환자 말투로) ASK = {"kr:Q2": "“강남 {proc} 잘하는 곳 추천해줘”", "kr:Q3": "“강남 성형외과 추천해줘”", "en:Q4": "“English-speaking plastic surgeon in Seoul”"} # 원인 설명에 쓸 홈페이지 점검 항목 (우선순위 순, 미흡한 것 중 앞의 3개) CAUSE_ORDER = ["병원 정보 구조화", "자주 묻는 질문(FAQ)", "비교 표", "의료진 구조화", "영문 사이트 연결", "페이지 제목(H1)"] CAUSE_PLAIN = {"병원 정보 구조화": "병원 기본 정보", "자주 묻는 질문(FAQ)": "자주 묻는 질문", "비교 표": "비용·회복 정리표", "의료진 구조화": "의료진 정보", "영문 사이트 연결": "영문 사이트 연결", "페이지 제목(H1)": "페이지 제목"} MEANING = {"brand": "병원을 이미 아는 환자에게는 정확히 안내되고 있습니다", ("kr", "good"): "새로 병원을 찾는 국내 환자에게도 자주 소개됩니다", ("kr", "warn"): "새로 병원을 찾는 국내 환자에게는 절반 이하로 소개됩니다", ("kr", "crit"): "새로 병원을 찾는 국내 환자에게는 거의 소개되지 않습니다", ("en", "good"): "해외 환자에게는 자주 소개됩니다", ("en", "warn"): "해외 환자에게는 절반 이하로 소개됩니다", ("en", "crit"): "해외 환자에게도 거의 소개되지 않습니다"} def question_label(topic): """핵심 발견 질문 이름: '강남 성형외과 추천' → '… 추천 질문', '강남 코성형 병원' → '… 추천 질문'""" return topic + (" 질문" if topic.endswith("추천") else " 추천 질문") def body(d, clinic): """친절하고 간결한 본문. 세부 수치는 이미지(핵심 발견·로드맵)와 첨부 PDF 가 맡는다.""" name, kf = d["name"], d["kf"] neun, reul = report.josa(name, "은", "는"), report.josa(name, "을", "를") lang, qno = kf["slot"].split(":Q") ask = (ASK[kf["slot"]].format(proc=clinic["procedure_ko"]) if kf["slot"] in ASK else f"“{d['questions'][lang][int(qno) - 1]['question']}”") who = "해외 환자" if kf["slot"].startswith("en") else "환자" fails = [t for t, ok, _ in d["site"] if not ok] causes = [CAUSE_PLAIN.get(t, t) for t in CAUSE_ORDER if t in fails][:3] (bh, bv), (kh, kv), (eh, ev) = d["brand"], d["kr"], d["en"] tk, te = report.ratio_tone(kh, kv), report.ratio_tone(eh, ev) if tk == "crit" and te == "crit": nb = f"병원명 없이 물으면 국내 {kv}번 중 {kh}번, 해외 {ev}번 중 {eh}번만 소개됩니다." elif te == "good" and tk == "crit": nb = f"병원명 없이 물으면 해외 질문에서는 {ev}번 중 {eh}번 소개되지만, 국내 질문에서는 {kv}번 중 {kh}번에 그칩니다." else: nb = f"병원명 없이 물으면 국내 {kv}번 중 {kh}번, 해외 {ev}번 중 {eh}번 소개됩니다." return f"""

안녕하세요. {name} 마케팅 담당자님께 전달 부탁드립니다.

(주)AI오투오 전략마케팅본부 감해원입니다.

요즘 {who}들은 {ask}처럼 AI에게 먼저 병원을 묻습니다. 저희가 같은 질문을 ChatGPT·Claude·Perplexity에 각 3번씩 해 보니, 추천 목록에 {name}{neun} 아직 들어 있지 않았습니다.

진단 결과 요약

제안드리는 방향

기존 홈페이지는 그대로 두고, 진료·회복·비용 정보를 국문·영문 공식 답변 허브에 정리해 드립니다. AI가 병원 이름을 모르고 한 질문에도 {name}{reul} 포함해서 답변할 수 있도록 근거를 갖추는 것이 목표입니다. 8주 뒤 같은 질문으로 다시 측정해 변화를 보여 드리겠습니다.

자세한 결과는 첨부한 진단 결과에 담았습니다.
30분 정도 시간을 내주시면 직접 설명 드리겠습니다. 편하신 일정으로 회신 부탁드립니다.

감사합니다.

""" MAIL_HERO = "AI 추천 목록에는 아직 없었습니다." # 소개서의 "한 번도 언급되지 않았습니다." 를 메일용으로 순화 def latest_deck(deck_dir, name): """소개서 폴더에서 이 병원의 가장 높은 버전 소개서. 같은 버전이 둘이면 멈춘다.""" rx = re.compile(r"WebforAI_소개서_" + re.escape(name) + r"_v(\d+)_.*\.pptx$") found = [(int(m.group(1)), f) for f in os.listdir(deck_dir) if not f.startswith("~$") and (m := rx.match(f))] assert found, f"소개서 없음: {name} ({deck_dir})" top = max(v for v, _ in found) files = [f for v, f in found if v == top] assert len(files) == 1, f"같은 버전 소개서가 여럿입니다: {files}" return os.path.join(deck_dir, files[0]) def images(clinics, deck_dir, img_dir): """소개서 4장(핵심 발견)을 메일 본문용 PNG(가로 1600px)로 뽑는다. 메일용은 강조 문장을 순화하고 쪽 번호(03 · Key Finding)를 뺀다. 소개서 원본은 건드리지 않는다.""" from pptx import Presentation import tempfile os.makedirs(img_dir, exist_ok=True) tmp = tempfile.mkdtemp() for name in clinics: out = os.path.join(img_dir, f"{name}_핵심발견") assert not os.path.exists(out + ".png"), f"이미 있습니다: {out}.png" deck = latest_deck(deck_dir, name) print("소개서:", os.path.basename(deck)) prs = Presentation(deck) s4 = prs.slides[3] hero = next(sh for sh in s4.shapes if sh.name == "TextBox 2") assert hero.text_frame.paragraphs[2].runs[0].text == "한 번도 언급되지 않았습니다." hero.text_frame.paragraphs[2].runs[0].text = MAIL_HERO for sh in [sh for sh in s4.shapes if sh.name == "TextBox 5"]: # 쪽 번호 sh._element.getparent().remove(sh._element) # 4장만 남긴다 ids = prs.slides._sldIdLst for i, sld in reversed(list(enumerate(list(ids)))): if i != 3: prs.part.drop_rel(sld.rId); ids.remove(sld) pptx = os.path.join(tmp, f"{name}.pptx") prs.save(pptx) prof = "file://" + os.path.join(tmp, "lo_profile") subprocess.run(["soffice", f"-env:UserInstallation={prof}", "--headless", "--convert-to", "pdf", "--outdir", tmp, pptx], check=True, capture_output=True) subprocess.run(["pdftoppm", "-png", "-singlefile", "-scale-to-x", "1600", "-scale-to-y", "-1", os.path.join(tmp, f"{name}.pdf"), out], check=True) print(out + ".png") # ── AI Discovery 로드맵 이미지 (핵심 발견 → 질의 유형 → 응답 점수 → 개선 제안 → 기대 효과) ───────── TONE_CSS = {"good": ("#F3F0FF", "#4A3A7C", "#9B8AD4"), "warn": ("#FFF6ED", "#7C5C3A", "#D4A872"), "crit": ("#FFF0F0", "#7C3A4B", "#D4889A")} ROADMAP_CSS = """ *{box-sizing:border-box;margin:0;padding:0} body{width:1600px;height:900px;background:#0A1128;font-family:'Pretendard Variable',Pretendard,sans-serif;color:#1D0024; padding:56px 56px 48px;word-break:keep-all} .top{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:34px} .eyebrow{color:#D8B4FE;font-size:20px;font-weight:700;letter-spacing:.2em} h1{color:#fff;font-size:46px;font-weight:800;margin-top:10px;letter-spacing:-.01em} h1 em{font-style:normal;color:#D8B4FE} .logos{display:flex;align-items:center;gap:18px;margin-top:6px} .logos img{height:26px} .logos .bar{width:2px;height:28px;background:#2E3A63} .flow{display:grid;grid-template-columns:repeat(5,1fr);gap:22px;position:relative} .flow:before{content:"";position:absolute;left:40px;right:40px;top:44px;height:3px;background:#2E3A63;z-index:0} .card{position:relative;z-index:1;background:#fff;border-radius:18px;padding:26px 24px 24px;height:620px; box-shadow:4px 6px 16px rgba(0,0,0,.18)} .card.key{outline:3px solid #6C5CE7} .no{width:40px;height:40px;border-radius:12px;background:#EFE6FF;color:#6C5CE7;font:900 20px 'Playfair Display'; display:flex;align-items:center;justify-content:center} .key .no{background:#6C5CE7;color:#fff} .t{font-size:30px;font-weight:800;color:#0A1128;margin-top:16px} .en{font:700 17px 'Playfair Display';color:#6C5CE7;margin-top:2px} .body{margin-top:20px;border-top:1.5px dashed #D5DAE6;padding-top:20px;font-size:22px;line-height:1.45} .big{font:900 96px/1 'Playfair Display';color:#7C3A4B} .big small{font-size:44px;color:#98A2B3} .strong{font-weight:800;font-size:24px;margin:14px 0 10px;color:#0A1128} ul{list-style:none} li{margin-bottom:14px;padding-left:22px;position:relative} li:before{content:"";position:absolute;left:2px;top:12px;width:9px;height:9px;border-radius:50%;background:#6C5CE7} li b{color:#0A1128} ul.kv li b{display:block} .row{margin-bottom:22px} .rh{display:flex;justify-content:space-between;align-items:baseline} .lab{font-size:20px;font-weight:700;color:#334155} .track{height:12px;background:#EEF0F6;border-radius:6px;margin-top:6px;overflow:hidden} .fill{height:100%;border-radius:6px} .num{font:900 26px 'Playfair Display'} .num small{font-size:17px;color:#98A2B3} .foot{color:#B8C0D6;font-size:17px;margin-top:22px} """ def roadmap_html(d, logos): import html as H name, kf = d["name"], d["kf"] (bh, bv), (kh, kv), (eh, ev) = d["brand"], d["kr"], d["en"] fails = [t for t, ok, _ in d["site"] if not ok] causes = [t for t in CAUSE_ORDER if t in fails][:3] def bar(label, a, b): _, fg, dot = TONE_CSS[report.ratio_tone(a, b)] w = max(4, round(a / b * 100)) if b else 0 return ('
%s
%d/%d
' '
' % (label, fg, a, b, w, dot)) steps = [ ("01", "핵심 발견", "Key Finding", '
0/%d

%s

' '

AI 추천 목록에 %s%s 아직 포함되지 않았습니다.

' % (kf["valid"], H.escape(question_label(kf["topic"])), H.escape(name), report.josa(name, "은", "는"))), ("02", "질의 유형", "Query Types", ''), ("03", "응답 점수", "Answer Score", bar("병원명 질문", bh, bv) + bar("국내 탐색", kh, kv) + bar("해외 탐색", eh, ev) + bar("홈페이지 인용", d["own_src"], d["total"]) + bar("홈페이지 점검", d["site_ok"], len(d["site"]))), ("04", "개선 제안", "Action", ''), ("05", "기대 효과", "Outcome", '' % (H.escape(name), report.josa(name, "을", "를"))), ] cards = "".join('
%s
%s
%s
' '
%s
' % (" key" if i == 0 else "", no, t, en, b) for i, (no, t, en, b) in enumerate(steps)) return ('' '' '' '' '
AI DISCOVERY · %s

AI 답변 진단에서 개선까지

' '
' '
%s
' '
측정 %s · 질문 10개 × AI 답변엔진 4종 × 3회 · 응답 점수는 판정 가능한 답변 중 언급·인용 횟수, 홈페이지 점검은 12개 항목 중 충족 수
' '' % (ROADMAP_CSS, H.escape(name), logos[0], logos[1], cards, d["measured"])) def roadmap_images(names, img_dir): from playwright.sync_api import sync_playwright a = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets") logos = [report.b64(f"{a}/infinith_white.png"), report.b64(f"{a}/webforai_white.png")] clinics = probe.load("pilot_clinics.json") _, plan = probe.expand(clinics, probe.load("question_template.json")) os.makedirs(img_dir, exist_ok=True) with sync_playwright() as p: b = p.chromium.launch() pg = b.new_page(viewport={"width": 1600, "height": 900}, device_scale_factor=1) for name in names: out = os.path.join(img_dir, f"{name}_AI_Discovery_로드맵.png") assert not os.path.exists(out), f"이미 있습니다: {out}" c = next(x for x in clinics if x["name"] == name) page = roadmap_html(report.report_data(c, plan), logos) banned = ["브릿지", "bridge", "서포터즈", "장악", "주입", "노출", "보장", "반드시", "—"] assert not [w for w in banned if w in page], name pg.set_content(page, wait_until="networkidle") pg.evaluate("document.fonts.ready") pg.screenshot(path=out, clip={"x": 0, "y": 0, "width": 1600, "height": 900}) print(out) b.close() def main(out_json, names): clinics = probe.load("pilot_clinics.json") _, plan = probe.expand(clinics, probe.load("question_template.json")) res = {} for name in names: c = next(x for x in clinics if x["name"] == name) b = body(report.report_data(c, plan), c) banned = ["브릿지", "bridge", "doorway", "서포터즈", "장악", "주입", "노출", "—", "보장", "반드시"] assert not [w for w in banned if w in b], f"{name}: 금지어 {[w for w in banned if w in b]}" res[name] = b json.dump(res, open(out_json, "w"), ensure_ascii=False, indent=1) print(out_json) if __name__ == "__main__": opts = dict(a[2:].split("=", 1) for a in sys.argv[2:]) names = opts["clinics"].split(",") main(sys.argv[1], names) if "images" in opts: images(names, *opts["images"].split(",")) if "roadmap" in opts: roadmap_images(names, opts["roadmap"])