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

269 lines
14 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.
"""
진단 보고서 장을 캡처 이미지 대신 PPTX 도형·텍스트로 그린다 (haewon이 PowerPoint에서 간격·크기를 직접 고칠 수 있게).
- 데이터: build_diagnosis_report.report_data (보고서 HTML 과 같은 수치·발췌)
- 문법: INFINITH v0.1 덱 14쪽. 다크 배경 위 흰 카드, 아이콘 스퀘어, 상태 배지, 인디고 본문
- 본문 영역: 헤더(eyebrow·제목) 아래 y 2.05 ~ 10.15 를 꽉 채운다
"""
from pptx.util import Inches
import build_diagnosis_report as report
import build_outbound_deck_v3 as v3
from build_outbound_deck_v3 import ACCENT, INDIGO, NAVY, RULE, SERIF, SLATE_500, SLATE_700, WHITE, logo, shadow, text
from ifd import MSO_ANCHOR, PP_ALIGN, _rect, em_width, lines_needed
X0, W, Y0, Y1 = v3.M, v3.W, 2.05, 10.15
LAV = "EFE6FF"
# 숫자·아이콘 글꼴: haewon이 v13 에서 Playfair Display Black 으로 통일
NUM = SERIF + " Black"
TONE = {"good": ("F3F0FF", "4A3A7C"), "warn": ("FFF6ED", "7C5C3A"), "crit": ("FFF0F0", "7C3A4B"), "info": ("EFF0FF", "3A3F7C")}
TRACK, BAR_OTHER = "EEF0F6", "9B8AD4"
def card(slide, x, y, w, h):
c = _rect(slide, x, y, w, h, fill=WHITE, line=None, radius=0.2)
shadow(c, 8)
return c
def icon(slide, x, y, label, size=0.62, tone=None):
fill, color = (TONE[tone][0], TONE[tone][1]) if tone else (LAV, ACCENT)
_rect(slide, x, y, size, size, fill=fill, line=None, radius=0.14)
text(slide, x, y, size, size, label, 20.0 if len(label) > 2 else 22.0, name=NUM, bold=True, color=color,
align=PP_ALIGN.CENTER, anchor=MSO_ANCHOR.MIDDLE)
def badge(slide, right, y, label, tone, size=20.0, h=0.5):
"""오른쪽 끝을 right 에 맞춘 상태 배지. 왼쪽 x 를 돌려준다."""
w = round(em_width(label) * size / 72 + 0.5, 2)
_rect(slide, right - w, y, w, h, fill=TONE[tone][0], line=None, radius=h / 2)
text(slide, right - w, y, w, h, label, size, bold=True, color=TONE[tone][1], align=PP_ALIGN.CENTER,
anchor=MSO_ANCHOR.MIDDLE)
return right - w
def fit(s, w, size, max_lines, where):
n = lines_needed(s, w, size)
assert n <= max_lines, f"{where}: {n}줄 (상한 {max_lines}줄) «{s[:30]}»"
return n
def clear_body(slide):
"""헤더·푸터는 두고 본문 영역(캡처 이미지·프레임)만 지운다."""
for sh in [sh for sh in slide.shapes if 1.9 <= sh.top / 914400 < 10.2]:
sh._element.getparent().remove(sh._element)
# ── 5 표지 (라이트) ──────────────────────────────────────────────────────────
def cover(slide, d):
card(slide, X0, Y0, W, Y1 - Y0)
lx, split = X0 + 0.8, X0 + 11.4
# 왼쪽 묶음을 세로 가운데에 두고 로고·병원명 간격을 좁힌다
stack = 0.5 + 0.55 + 0.5 + 0.2 + 1.45 + 0.2 + 0.5
y = Y0 + (Y1 - Y0 - stack) / 2
v3.brand_pair(slide, lx, y, 0.5, dark=False)
y += 0.5 + 0.55
text(slide, lx, y, 10.0, 0.5, "AI ANSWER CHECK · 맞춤 진단 보고서", 22.0, bold=True, color=ACCENT, spc=200)
y += 0.7
text(slide, lx, y, 10.2, 1.45, d["name"], 88.0, 1, "cover name", bold=True, color=NAVY)
y += 1.65
text(slide, lx, y, 10.2, 0.5, f"AI 답변 진단 보고서 · 측정 {v3.MEASURED}", 26.0, 1, "cover meta", color=SLATE_700)
_rect(slide, split, Y0 + 0.9, 0.03, Y1 - Y0 - 1.8, fill=RULE, line=None, radius=0)
stats = [("10", "환자 질문 (한국어 5 · 영어 5)"), ("4", "AI 답변엔진"), ("×3", "질문마다 3회 측정")]
sy = Y0 + (Y1 - Y0 - 3 * 2.05) / 2
for num, lab in stats:
text(slide, split + 0.8, sy, 5.5, 1.3, num, 80.0, name=NUM, bold=True, color=NAVY)
text(slide, split + 0.85, sy + 1.3, 5.5, 0.5, lab, 24.0, 1, "cover stat", bold=True, color=ACCENT)
sy += 2.05
# ── 6 요약 ──────────────────────────────────────────────────────────────────
def summary(slide, d):
gap, kh = 0.35, 3.55
kw = (W - gap * 3) / 4
kpis = [("Q1", "병원명을 포함한 질문", d["brand"], "병원을 알고 검색하는 환자"),
("KR", "국내 · 병원명 없는 질문", d["kr"], "언급된 답변 수"),
("EN", "해외 · 병원명 없는 질문", d["en"], "언급된 답변 수"),
("URL", "홈페이지 출처 인용", (d["own_src"], d["total"]), "전체 답변 중")]
kpis = [(ic, lab, ab, chip, report.ratio_tone(*ab)) for ic, lab, ab, chip in kpis]
for i, (ic, lab, (a, b), chip, tone) in enumerate(kpis):
x = X0 + i * (kw + gap)
card(slide, x, Y0, kw, kh)
icon(slide, x + 0.35, Y0 + 0.35, ic)
text(slide, x + 1.15, Y0 + 0.3, kw - 1.4, 0.75, lab, 24.0, 2, f"kpi {lab}", bold=True, color=INDIGO,
anchor=MSO_ANCHOR.MIDDLE, line_spacing=1.0)
num = f"{a}/{b}"
text(slide, x + 0.35, Y0 + 1.15, kw - 0.7, 1.4, num, 72.0, 1, f"kpi {num}", name=NUM, bold=True, color=NAVY)
bw = round(em_width(chip) * 20 / 72 + 0.5, 2)
badge(slide, x + 0.35 + bw, Y0 + 2.7, chip, tone)
fy = Y0 + kh + gap
card(slide, X0, fy, W, Y1 - fy)
icon(slide, X0 + 0.45, fy + 0.4, "!")
text(slide, X0 + 1.3, fy + 0.4, 8.0, 0.62, "핵심 발견", 28.0, bold=True, color=INDIGO, anchor=MSO_ANCHOR.MIDDLE)
badge(slide, X0 + W - 0.45, fy + 0.46, f"{d['q2_valid']}회 중 0회", "crit", 22.0)
# 글자 크기·위치는 haewon v13 6장 (본문 32 · 보조 24 한 줄)
kf = d["kf"]
fit(kf["finding"], W - 0.9, 32.0, 2, "finding")
text(slide, X0 + 0.45, fy + 1.3, W - 0.9, 1.24, kf["finding"], 32.0, 2, bold=True, color=INDIGO, line_spacing=1.15)
fit(kf["finding_sub"], W - 0.9, 24.0, 1, "finding sub")
text(slide, X0 + 0.45, fy + 2.69, W - 0.9, 0.43, kf["finding_sub"], 24.0, 1, color=SLATE_700)
# ── 7·8 질문별 결과 ─────────────────────────────────────────────────────────
def questions(slide, rows):
gx, gy = 0.4, 0.35
cw, ch = (W - gx * 2) / 3, (Y1 - Y0 - gy) / 2
for k in range(6):
x, y = X0 + (k % 3) * (cw + gx), Y0 + (k // 3) * (ch + gy)
card(slide, x, y, cw, ch)
ix, iw = x + 0.35, cw - 0.7
if k == 5:
icon(slide, ix, y + 0.3, "i")
text(slide, ix + 0.8, y + 0.3, iw - 0.8, 0.62, "읽는 법", 28.0, bold=True, color=INDIGO, anchor=MSO_ANCHOR.MIDDLE)
ly = y + 1.25
for sym, lab in [("●", "언급된 회차"), ("○", "언급되지 않은 회차"), ("·", "답변 없음 · 병원명 미수집")]:
text(slide, ix, ly, 0.5, 0.45, sym, 24.0, bold=True, color=ACCENT)
text(slide, ix + 0.55, ly, iw - 0.55, 0.45, lab, 24.0, 1, f"legend {lab}", color=INDIGO)
ly += 0.55
text(slide, ix, ly + 0.15, iw, 0.5, "숫자: 언급 횟수 / 판정 회차", 24.0, 1, "legend note",
color=SLATE_700, line_spacing=1.1)
continue
q = rows[k]
tone = "good" if q["eng_valid"] and q["eng_hit"] == q["eng_valid"] else ("crit" if q["eng_hit"] == 0 else "warn")
icon(slide, ix, y + 0.3, f"Q{q['i']}")
text(slide, ix + 0.8, y + 0.3, 2.6, 0.62, q["kind"], 28.0, bold=True, color=INDIGO, anchor=MSO_ANCHOR.MIDDLE)
badge(slide, ix + iw, y + 0.36, f"{q['eng_hit']}/{q['eng_valid']} 엔진 언급", tone)
fit(q["question"], iw, 24.0, 2, f"question Q{q['i']}")
text(slide, ix, y + 1.0, iw, 0.85, q["question"], 24.0, 2, bold=True, color=NAVY, line_spacing=1.05)
_rect(slide, ix, y + 1.9, iw, 0.015, fill=RULE, line=None, radius=0)
ry = y + 1.98
for lab, rs in q["engines"]:
valid = [r for r in rs if r != "na"]
text(slide, ix, ry, 2.6, 0.46, lab, 24.0, color=SLATE_700, anchor=MSO_ANCHOR.MIDDLE)
if not valid:
text(slide, ix + 2.6, ry, iw - 2.6, 0.46, "확인 불가", 24.0, color=SLATE_500, align=PP_ALIGN.RIGHT,
anchor=MSO_ANCHOR.MIDDLE)
else:
h = valid.count("hit")
t = TONE["good" if h == len(valid) else ("crit" if h == 0 else "warn")][1]
dots = "".join("●" if r == "hit" else ("○" if r == "miss" else "·") for r in rs)
text(slide, ix + 2.6, ry, 1.3, 0.46, dots, 24.0, bold=True, color=t, anchor=MSO_ANCHOR.MIDDLE, spc=150)
text(slide, ix + 3.9, ry, iw - 3.9, 0.46, f"{h}/{len(valid)}", 24.0, name=NUM, bold=True, color=t,
align=PP_ALIGN.RIGHT, anchor=MSO_ANCHOR.MIDDLE)
ry += 0.46
# ── 9·10 답변 원문 ──────────────────────────────────────────────────────────
def answer(slide, q, name):
card(slide, X0, Y0, W, Y1 - Y0)
ix, iw = X0 + 0.5, W - 1.0
icon(slide, ix, Y0 + 0.4, q["mono"], 0.7)
text(slide, ix + 0.9, Y0 + 0.4, 6.0, 0.7, q["engine"], 28.0, bold=True, color=INDIGO, anchor=MSO_ANCHOR.MIDDLE)
badge(slide, ix + iw, Y0 + 0.47, f"{name} 언급 없음", "crit", 22.0, 0.56)
meta = f"{q['loc']} · {q['date']} · {q['rep']}회차"
text(slide, ix + 3.4, Y0 + 0.4, 7.5, 0.7, meta, 24.0, 1, "answer meta", bold=True, color=ACCENT,
anchor=MSO_ANCHOR.MIDDLE)
qs = f"질문 {q['question']}"
fit(qs, iw, 28.0, 1, "answer question")
text(slide, ix, Y0 + 1.35, iw, 0.6, qs, 28.0, 1, bold=True, color=NAVY)
_rect(slide, ix, Y0 + 2.15, iw, 0.02, fill=RULE, line=None, radius=0)
segs = list(q["segments"])
# 카드를 채우는 가장 큰 글자 크기를 고른다 (줄 높이는 Pretendard 렌더 실측 1.2 × 줄간격 1.3).
# 24pt 로도 넘치면 글자를 더 줄이지 않고 뒤 문단부터 잘라 "…" 로 끝낸다
room = Y1 - 0.35 - (Y0 + 2.4)
def count(sg, size):
body = "".join(t for t, _ in sg)
return sum(max(1, lines_needed(p, iw - 0.3, size)) for p in body.split("\n"))
for size in (32.0, 30.0, 28.0, 26.0, 24.0):
lh = size / 72 * 1.2 * 1.3
if count(segs, size) * lh <= room:
break
else:
while count(segs, size) * lh > room:
body = "".join(t for t, _ in segs)
cut = body.rstrip(" …").rfind("\n")
assert cut > 0, "답변 발췌를 줄일 수 없습니다"
keep, out = 0, []
for t, m in segs:
if keep + len(t) <= cut:
out.append((t, m)); keep += len(t)
else:
out.append((t[:cut - keep], m)); break
segs = [x for x in out if x[0]] + [(" …", False)]
lines = count(segs, size)
_rect(slide, ix, Y0 + 2.45, 0.06, lines * lh - 0.1, fill=ACCENT, line=None, radius=0)
# 줄바꿈마다 문단을 나누고, 가린 병원명(A성형외과·○○○)은 보라 굵게
paras = [[]]
for t, m in segs:
for j, part in enumerate(t.split("\n")):
if j:
paras.append([])
if part:
paras[-1].append((part, m))
tb = v3._tb(slide, ix + 0.3, Y0 + 2.4, iw - 0.3, lines * lh + 0.2)
tf = tb.text_frame
for k, runs in enumerate(paras):
para = tf.paragraphs[0] if k == 0 else tf.add_paragraph()
para.line_spacing = 1.3
for t, m in runs:
v3.ifd._run(para, t, size, v3.SANS, m, False, ACCENT if m else INDIGO, None)
# ── 11 출처 ────────────────────────────────────────────────────────────────
def sources(slide, d):
card(slide, X0, Y0, W, Y1 - Y0)
ix, iw = X0 + 0.5, W - 1.0
icon(slide, ix, Y0 + 0.4, "S", 0.7)
text(slide, ix + 0.9, Y0 + 0.4, 8.0, 0.7, "출처별 인용 답변 수", 28.0, bold=True, color=INDIGO, anchor=MSO_ANCHOR.MIDDLE)
badge(slide, ix + iw, Y0 + 0.47, f"답변 {d['total']}건 기준", "info", 22.0, 0.56)
bars = [(f"{d['name']} 홈페이지", d["own_src"], True)] + [(lb, n, False) for lb, n in d["src"][:6]]
top = max(n for _, n, _ in bars)
lw, nw = 5.0, 1.0
tw = iw - lw - nw - 0.3
rh = (Y1 - 0.35 - (Y0 + 1.45)) / len(bars)
for k, (lb, n, own) in enumerate(bars):
ry = Y0 + 1.45 + k * rh
text(slide, ix, ry, lw, rh, lb, 28.0, 1, f"source {lb}", bold=own, color=ACCENT if own else INDIGO,
anchor=MSO_ANCHOR.MIDDLE)
_rect(slide, ix + lw, ry + rh / 2 - 0.19, tw, 0.38, fill=TRACK, line=None, radius=0.19)
_rect(slide, ix + lw, ry + rh / 2 - 0.19, max(0.38, tw * n / top), 0.38, fill=ACCENT if own else BAR_OTHER,
line=None, radius=0.19)
text(slide, ix + iw - nw, ry, nw, rh, str(n), 34.0, name=NUM, bold=True, color=ACCENT if own else NAVY,
align=PP_ALIGN.RIGHT, anchor=MSO_ANCHOR.MIDDLE)
# ── 12 홈페이지 점검 ────────────────────────────────────────────────────────
def site(slide, d):
gx, gy, cols = 0.4, 0.2, 3
rows = -(-len(d["site"]) // cols)
cw, ch = (W - gx * (cols - 1)) / cols, (Y1 - Y0 - gy * (rows - 1)) / rows
for k, (title, ok, ev) in enumerate(d["site"]):
x, y = X0 + (k % cols) * (cw + gx), Y0 + (k // cols) * (ch + gy)
card(slide, x, y, cw, ch)
ix, iw = x + 0.3, cw - 0.6
tone = "good" if ok else "crit"
icon(slide, ix, y + 0.18, "✓" if ok else "✕", 0.52, tone)
bx = badge(slide, ix + iw, y + 0.2, "충족" if ok else "미흡", tone, 20.0, 0.48)
text(slide, ix + 0.68, y + 0.18, bx - ix - 0.8, 0.52, title, 24.0, 1, f"site {title}", bold=True, color=INDIGO,
anchor=MSO_ANCHOR.MIDDLE)
n = fit(ev, iw, 20.0, 3, f"site ev {title}")
assert 0.72 + n * 0.37 <= ch, f"점검 근거가 카드를 넘습니다: {title}"
text(slide, ix, y + 0.72, iw, n * 0.37 + 0.1, ev, 20.0, 3, color=SLATE_700, line_spacing=1.12)
def build(prs, d):
"""소개서 5~12장(보고서 장)의 캡처 이미지를 네이티브 요소로 바꾼다."""
s = prs.slides
for i in range(4, 12):
clear_body(s[i])
cover(s[4], d)
summary(s[5], d)
questions(s[6], d["questions"]["kr"])
questions(s[7], d["questions"]["en"])
answer(s[8], d["quotes"][0], d["name"])
answer(s[9], d["quotes"][1], d["name"])
sources(s[10], d)
site(s[11], d)