report.py
"""응답·검사 결과를 JSONL·CSV·HTML로 저장한다."""
import csv
from html import escape
import json
from pathlib import Path
CHECKS = ("format", "source_ids", "retrieval", "expected_sources",
"required_info", "forbidden_text", "followup")
def report_row(record):
response = record.get("actual_response") or {}
trace = record.get("trace", {})
row = {"question_id": record["question_id"], "question": record["question"],
"answer": response.get("answer", ""), "as_of": trace.get("as_of", ""),
"sources": ",".join(response.get("sources", [])),
"retrieved": ",".join(dict.fromkeys(x["document_id"] for x in trace.get("candidates", []))),
"execution_mode": record["execution_mode"], "human_review": record["human_review"],
"error": json.dumps(record["error"], ensure_ascii=False) if record["error"] else ""}
for key in CHECKS:
flag = record["checks"].get(key)
row[key] = "PASS" if flag is True else "FAIL" if flag is False else "N/A"
return row
def write_report(records, output):
output = Path(output)
output.mkdir(parents=True, exist_ok=True)
(output / "results.jsonl").write_text("".join(
json.dumps(row, ensure_ascii=False) + "\n" for row in records), encoding="utf-8")
rows = [report_row(record) for record in records]
fields = (list(rows[0]) if rows else ["question_id", "question", *CHECKS])
def csv_cell(value):
text = str(value)
return "'" + text if text.startswith(("=", "+", "-", "@", "\t", "\r")) else text
with (output / "checks.csv").open("w", encoding="utf-8-sig", newline="") as stream:
writer = csv.DictWriter(stream, fieldnames=fields)
writer.writeheader()
writer.writerows({key: csv_cell(row[key]) for key in fields} for row in rows)
sections = []
for row in rows:
table = "".join("<tr><th>" + escape(key) + "</th><td>" + escape(str(row[key]))
+ "</td></tr>" for key in fields if key not in {"question_id", "question"})
sections.append("<section><h2>" + escape(row["question_id"] + " · " + row["question"])
+ "</h2><table>" + table + "</table></section>")
mode = ", ".join(sorted({record["execution_mode"] for record in records})) or "empty"
html = ("<!doctype html><html lang='ko'><meta charset='utf-8'>"
"<meta name='viewport' content='width=device-width,initial-scale=1'>"
"<title>질문 확인표</title><style>body{max-width:960px;margin:40px auto;padding:24px;"
"font:17px/1.7 sans-serif;color:#172b45}table{border-collapse:collapse;width:100%}"
"th,td{border:1px solid #ccd;padding:10px;overflow-wrap:anywhere;text-align:left}"
"section{margin:40px 0}th{width:170px;background:#f3f7fa}</style><h1>질문 확인표</h1>"
"<p>실행 경로: " + escape(mode) + " · 사람 확인 PENDING은 미검토 상태입니다.</p>"
+ "".join(sections) + "</html>")
(output / "checks.html").write_text(html, encoding="utf-8")