#!/usr/bin/env python3 """⑩ 실시간 페르소나 정확도 — 집계기 (2026-08-28 확정 설계). 계획서 산식 그대로: 정확도 = 1 − mean(시나리오별 mean(|실제 긴장도 − 예측 긴장도|)) (시나리오 = 협상 세션) 정의 (확정): - 실제 긴장도 (사후, 하네스 가격 기록으로 산출) = clip((제안가 − 목표가) / (초기제안가 − 목표가)) - 예측 긴장도 (서버 실시간 계측) = 단계 변수인 지표점수(1~99 정수)에서 역산한 추정치. 이 수치가 페르소나(저/중/고 3구간) 적용에 실제로 사용된다 — 계획서 "수치에 따라 페르소나 적용". 지표점수의 정수 양자화 때문에 실제값과 독립적인 오차가 존재한다 (측정 건전성 근거). 병합: (session_id, iteration) — 서버 로그의 신형 행(persona 필드 보유)만 사용, 중복 키는 최신 우선. 사용: python aggregate.py --details "../01_win_rate/본측정_20260828/detail_*.jsonl" """ import argparse import glob import json from collections import Counter from pathlib import Path HERE = Path(__file__).parent DEFAULT_TENSION = HERE.parent.parent / "server" / "data" / "tension_log.jsonl" def clip01(v: float) -> float: return max(0.0, min(1.0, v)) def load_predicted(path: str): """(session_id, iteration) → {predicted, persona}. 신형 행만, 중복은 최신 우선.""" pred = {} for line in Path(path).read_text(encoding="utf-8").splitlines(): if not line.strip(): continue r = json.loads(line) if "persona" not in r: # 구형(잠정 산식 시절) 행 제외 continue pred[(r["session_id"], r["iteration"])] = r return pred def actual_entries(detail_row: dict): """하네스 detail 한 건에서 (iteration, 실제 긴장도) 재구성 — 동적 스텝 진입(res_step == '가격협상') 시점의 제안가 기준.""" target = detail_row.get("target") initial = detail_row.get("initial_offer") if not target or not initial or float(initial) <= float(target): return None # 긴장도 정의 불가 (초기제안가 ≤ 목표가) out = [] k = 0 for rd in detail_row.get("rounds", []): if rd.get("res_step") == "가격협상" and rd.get("req_price") is not None: actual = clip01((float(rd["req_price"]) - float(target)) / (float(initial) - float(target))) out.append((k, actual)) k += 1 return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--tension-log", default=str(DEFAULT_TENSION)) ap.add_argument("--details", required=True, help="하네스 detail 파일 glob (예: '../01_win_rate/본측정_*/detail_*.jsonl')") ap.add_argument("--target", type=float, default=96.0) args = ap.parse_args() pred = load_predicted(args.tension_log) session_diffs = {} persona_counter = Counter() matched = missing = undefined_sessions = 0 detail_out = [] for path in sorted(glob.glob(args.details)): for line in Path(path).read_text(encoding="utf-8").splitlines(): if not line.strip(): continue row = json.loads(line) if str(row.get("outcome", "")).startswith("오류"): continue entries = actual_entries(row) if entries is None: undefined_sessions += 1 continue session = f"EVAL-{row['case_id']}" for k, actual in entries: p = pred.get((session, k)) if p is None: missing += 1 continue matched += 1 diff = abs(p["predicted"] - actual) session_diffs.setdefault(session, []).append(diff) persona_counter[p["persona"]] += 1 detail_out.append({"session_id": session, "iteration": k, "predicted": p["predicted"], "actual": round(actual, 4), "diff": round(diff, 4), "indicator": p.get("indicator"), "persona": p["persona"]}) session_means = {s: sum(d) / len(d) for s, d in session_diffs.items()} overall = (sum(session_means.values()) / len(session_means)) if session_means else None accuracy_pct = round(100 * (1 - overall), 2) if overall is not None else None out = { "산식": "1 − mean(시나리오별 mean(|실제 − 예측|)) — 계획서 원문 산식 (시나리오=세션)", "예측": "서버 실시간: 지표점수(1~99)→긴장도 역산 추정치 (페르소나 적용에 사용된 수치)", "실제": "사후: clip((제안가−목표가)/(초기제안가−목표가)) — 하네스 가격 기록 기준", "표본": {"세션": len(session_means), "매칭": matched, "미매칭": missing, "정의불가_세션(초기제안가≤목표가)": undefined_sessions}, "페르소나_적용분포": dict(persona_counter), "accuracy_pct": accuracy_pct, "target_pct": args.target, "verdict": ("PASS" if accuracy_pct is not None and accuracy_pct >= args.target else "FAIL"), } (HERE / "result.json").write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8") with open(HERE / "detail.jsonl", "w", encoding="utf-8") as f: for r in detail_out: f.write(json.dumps(r, ensure_ascii=False) + "\n") print(json.dumps(out, ensure_ascii=False, indent=1)) if __name__ == "__main__": main()