- server/: FastAPI 협상 엔진 (5라운드, Q-Table/UCB, 페르소나 계측, :53117) - frontend/: 데모 콘솔 (React+Tailwind → nginx, /api 프록시) - eval/·testdata/: 지표 8종 측정 하네스 + 재현 가능 테스트셋 - results/: 측정 증빙 (지표별 result+provenance, raw 원본 동결+SHA256) ① 86.0 · ② 76.0 · ③ 5.99% · ⑥ p95 3.61ms · ⑦ 611만/년 · ⑧ 91/100 · ⑨ 99.71 · ⑩ 97.99 - docker-compose.yml + run.sh: backend+frontend 일괄 기동 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0112XUWF4bc3gGrEt8vsYCzy
114 lines
4.1 KiB
Python
114 lines
4.1 KiB
Python
"""스크립트 포매터 — 평문 템플릿에 요청 데이터를 치환한다."""
|
|
|
|
import math
|
|
from typing import Any, Dict
|
|
|
|
from common.textutil import hide_unresolved_lines, safe_format
|
|
from router.v1.nego.protocol import NegotiationRequest
|
|
from services.cards.repository import CardScriptRepository
|
|
from services.negotiation.korean import number_to_korean
|
|
|
|
|
|
class ScriptFormatter:
|
|
"""평문 script 템플릿 치환 (Slate/editor_script 구조 없음 — 평문이 단일 정본)."""
|
|
|
|
def __init__(self, card_repository: CardScriptRepository = None):
|
|
self._repo = card_repository or CardScriptRepository()
|
|
self.card_scripts = self._load_card_scripts()
|
|
|
|
def reload(self):
|
|
self.card_scripts = self._load_card_scripts()
|
|
|
|
def _load_card_scripts(self) -> Dict[str, str]:
|
|
scripts = {}
|
|
for card in self._repo.find_all():
|
|
card_id = card.get("card_id")
|
|
content = card.get("script")
|
|
if card_id and content:
|
|
scripts[card_id] = content
|
|
return scripts
|
|
|
|
def format_script(self, script_identifier: str, request: NegotiationRequest) -> str:
|
|
"""
|
|
Args:
|
|
script_identifier: 템플릿 문자열 또는 카드 ID (예: "NC26-002")
|
|
"""
|
|
if not script_identifier:
|
|
return ""
|
|
|
|
context = self._build_context(request)
|
|
|
|
# 카드 ID면 템플릿 조회, 아니면 식별자 자체가 템플릿
|
|
template = self.card_scripts.get(script_identifier, script_identifier)
|
|
|
|
formatted = safe_format(template, context)
|
|
return hide_unresolved_lines(formatted, source=script_identifier[:30])
|
|
|
|
def _build_context(self, request: NegotiationRequest) -> Dict[str, Any]:
|
|
context = {}
|
|
|
|
def safe_format_number(val):
|
|
if isinstance(val, (int, float)):
|
|
return f"{val:,.0f}"
|
|
return str(val)
|
|
|
|
user_input_val = request.user_input
|
|
if user_input_val and self._is_number(user_input_val):
|
|
try:
|
|
context["price"] = f"{float(user_input_val):,.0f}"
|
|
except ValueError:
|
|
context["price"] = user_input_val
|
|
else:
|
|
context["price"] = str(user_input_val) if user_input_val is not None else ""
|
|
|
|
fields_to_map = [
|
|
"revenue", "partners", "anchor", "target", "initial", "input",
|
|
"iteration", "item_price", "deadline", "vat",
|
|
]
|
|
for field in fields_to_map:
|
|
val = getattr(request, field, None)
|
|
context[field] = safe_format_number(val) if val is not None else ""
|
|
|
|
# 1% 추가 협상 제안가
|
|
if request.input is not None:
|
|
context["offer_1pct"] = safe_format_number(math.floor(request.input * 0.99))
|
|
else:
|
|
context["offer_1pct"] = ""
|
|
|
|
context["dist"] = str(request.dist) if request.dist else ""
|
|
|
|
if request.card_data:
|
|
for k, v in request.card_data.model_dump().items():
|
|
if v is not None:
|
|
# 경쟁사 가격차는 최소 1% 표기
|
|
if k == "competitor_price_diff" and isinstance(v, (int, float)) and v < 1:
|
|
v = 1
|
|
context[k] = safe_format_number(v)
|
|
else:
|
|
context[k] = ""
|
|
|
|
# 할인율 (기존가 대비 현재 제안가)
|
|
if request.item_price is not None and request.input is not None and request.item_price > 1:
|
|
discount = ((request.item_price - request.input) / request.item_price) * 100
|
|
context["discount_rate"] = f"{discount:.1f}"
|
|
else:
|
|
context["discount_rate"] = "0.0"
|
|
|
|
# 한국어 가격 표기
|
|
if request.input is not None:
|
|
try:
|
|
context["input_kr"] = number_to_korean(int(request.input))
|
|
except Exception:
|
|
context["input_kr"] = str(request.input)
|
|
else:
|
|
context["input_kr"] = ""
|
|
|
|
return context
|
|
|
|
def _is_number(self, s) -> bool:
|
|
try:
|
|
float(s)
|
|
return True
|
|
except (ValueError, TypeError):
|
|
return False
|