[feat] solution/backend: 수집 뒤 콘텐츠 채울 때 캐치프레이즈·순환 문구 생성 — 숙박만
가게별 첫 화면 문구를 만드는 곳이 없어 모든 숙박이 공통 문구 10개를 돌려 썼다. - COPY 잡에 catchphrase 단계(prepare→generate→save→catchphrase→faq_fill), 숙박이 아니면 건너뜀 - prompts/catchphrase.py·gemini_text.generate_catchphrases: 캐치프레이즈 1 + 일반 20·계절 3×4·월 12·날씨 2×4. 문구마다 길이·상호명·ground_check(근거 없는 시설·수치) 검사 - fact tagline·catchphrases(lodging 스키마, allow_llm). 순환 문구는 사장님이 줄 단위로 고치게 글로 저장 (catchphrase_text: `봄 | ` · `9월 | ` · `비 | ` 머리) - site_payload: narrative.tagline·catchphrases 로 넘기고 이용정보 표(facts)에서는 뺀다 - 빌더 생성 화면 단계 문구, DATA_MODEL·GENERATION_FLOW 테스트 6건 추가. 관련 20개 파일 386 passed · 실패 102건은 main 과 목록이 같다(기존 실패) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a0b14dfca1
commit
ef0c44c5f2
13 files changed
+377
-8
No files matched your search
@@ -13,6 +13,7 @@ from services.llm import provider
|
||||
from services.llm.errors import LlmError
|
||||
from services.llm.errors import LlmInvalidOutput as GeminiInvalidOutput
|
||||
from services.llm.errors import LlmNotConfigured as GeminiNotConfigured
|
||||
from services.prompts import catchphrase as catchphrase_prompt
|
||||
from services.prompts.copy import RESPONSE_SCHEMA, build_prompt
|
||||
|
||||
|
||||
@@ -159,6 +160,90 @@ async def generate_copy(
|
||||
return result
|
||||
|
||||
|
||||
# ── 첫 화면 문구(generate_catchphrases) ─────────────────────────────────
|
||||
@dataclass
|
||||
class GeneratedCatchphrases:
|
||||
tagline: Optional[str] = None
|
||||
items: list[dict] = field(default_factory=list)
|
||||
rejected: list[tuple[str, str]] = field(default_factory=list)
|
||||
source: str = ""
|
||||
|
||||
|
||||
async def generate_catchphrases(
|
||||
place_name: str,
|
||||
facts: list[FactInput],
|
||||
*,
|
||||
records: Optional[list[str]] = None,
|
||||
model: Optional[str] = None,
|
||||
max_retries: int = 2,
|
||||
client: Optional[httpx.AsyncClient] = None,
|
||||
) -> GeneratedCatchphrases:
|
||||
"""고정 캐치프레이즈 하나와 순환 문구 모음 — 문구마다 소개문과 같은 근거 검사를 거친다."""
|
||||
llm = provider.active()
|
||||
if not llm.is_configured():
|
||||
raise GeminiNotConfigured(f"{llm.__name__.rsplit('.', 1)[-1].upper()}_API_KEY 가 설정되지 않았다")
|
||||
model = model or llm.DEFAULT_MODEL
|
||||
grounding = list(facts) + [FactInput(key="place_name", label="상호명", value=place_name)]
|
||||
prompt = catchphrase_prompt.build_prompt(place_name, facts, records)
|
||||
|
||||
owns_client = client is None
|
||||
client = client or httpx.AsyncClient(timeout=httpx.Timeout(120.0, connect=10.0))
|
||||
try:
|
||||
llm_result = await llm.generate(
|
||||
client, model, prompt=prompt, response_schema=catchphrase_prompt.RESPONSE_SCHEMA,
|
||||
temperature=0.7, max_retries=max_retries,
|
||||
)
|
||||
finally:
|
||||
if owns_client:
|
||||
await client.aclose()
|
||||
|
||||
parsed = llm_result.json or {}
|
||||
result = GeneratedCatchphrases(source=f"{llm.__name__.rsplit('.', 1)[-1]}:{model}")
|
||||
seen: set[str] = set()
|
||||
|
||||
def accept(text: object) -> Optional[str]:
|
||||
line = str(text or "").strip()
|
||||
if not line or line in seen:
|
||||
return None
|
||||
if not (catchphrase_prompt.MIN_LEN <= len(line) <= catchphrase_prompt.MAX_LEN):
|
||||
result.rejected.append((line, f"길이 {len(line)}자"))
|
||||
return None
|
||||
if place_name and place_name in line:
|
||||
result.rejected.append((line, "상호명 포함"))
|
||||
return None
|
||||
ok, reasons = ground_check(line, grounding)
|
||||
if not ok:
|
||||
result.rejected.append((line, " / ".join(reasons)))
|
||||
return None
|
||||
seen.add(line)
|
||||
return line
|
||||
|
||||
result.tagline = accept(parsed.get("tagline"))
|
||||
for text in (parsed.get("general") or [])[: catchphrase_prompt.COUNT_GENERAL]:
|
||||
if line := accept(text):
|
||||
result.items.append({"text": line, "kind": "general"})
|
||||
for row in parsed.get("season") or []:
|
||||
season = (row or {}).get("season")
|
||||
if season in catchphrase_prompt.SEASONS and (line := accept(row.get("text"))):
|
||||
result.items.append({"text": line, "kind": "season", "season": season})
|
||||
for row in parsed.get("month") or []:
|
||||
month = (row or {}).get("month")
|
||||
if isinstance(month, int) and 1 <= month <= 12 and (line := accept(row.get("text"))):
|
||||
result.items.append({"text": line, "kind": "month", "month": month})
|
||||
for row in parsed.get("weather") or []:
|
||||
weather = (row or {}).get("weather")
|
||||
if weather in catchphrase_prompt.WEATHERS and (line := accept(row.get("text"))):
|
||||
result.items.append({"text": line, "kind": "weather", "weather": weather})
|
||||
|
||||
usage = llm_result.usage
|
||||
LOG.i(
|
||||
f"[llm-text] '{place_name}' 첫 화면 문구 — 캐치프레이즈 {'O' if result.tagline else 'X'} · "
|
||||
f"순환 {len(result.items)}개 · 반려 {len(result.rejected)}건 · model={model} · "
|
||||
f"tokens in={usage.input_tokens} out={usage.output_tokens} · 약 ${llm.price(model, usage)}"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
# ── 요약(summarize_text) ──────────────────────────────────────────────────
|
||||
_SUMMARY_CACHE: dict[str, str] = {}
|
||||
_SUMMARY_CACHE_MAX = 500
|
||||
|
||||
Reference in new issue
Block a user