Merge branch 'main' into feature/crawler
This commit is contained in:
commit
dd3ad86715
160 files changed
+111240
-202
No files matched your search
@@ -29,7 +29,16 @@ from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
from crud.site_crud import SiteCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from services import azure_static, indexnow, publish_gate, render_report, site_payload, site_thumbnail, song_service
|
||||
from services import (
|
||||
azure_static,
|
||||
indexnow,
|
||||
publish_gate,
|
||||
render_report,
|
||||
seo_keywords,
|
||||
site_payload,
|
||||
site_thumbnail,
|
||||
song_service,
|
||||
)
|
||||
from services.local_content_service import LocalContentService
|
||||
from services.site_payload import emit_payload
|
||||
from services.snapshot import build_snapshot
|
||||
@@ -157,6 +166,19 @@ async def run_build(job: dict) -> dict:
|
||||
|
||||
snapshot = await build_snapshot(place)
|
||||
|
||||
# ★ 메타 태그용 검색 키워드(SiteOntology). **스냅샷에 싣는다** — payload 는 스냅샷만 보고 만들고,
|
||||
# "이 버전에 어떤 키워드가 나갔나" 가 site_versions.snapshot 에 남는다(services/seo_keywords 머리주석).
|
||||
# ★ 실패해도 빌드는 계속한다. 주변 정보·노래와 같은 규칙이다 — 키워드 없이 예전 제목·메타로 나간다.
|
||||
# ★ 재빌드(publish=False)에도 부른다. 로컬 임베딩이라 비용이 없고, 재빌드한 버전과 발행한 버전의
|
||||
# 제목이 갈리면 "눌러 본 것과 나간 것이 다르다" 가 된다.
|
||||
seo: dict | None = None
|
||||
try:
|
||||
seo = await seo_keywords.fetch(place_id, snapshot)
|
||||
except Exception as ex: # noqa: BLE001 — 키워드 실패가 발행을 죽이면 안 된다
|
||||
LOG.w(f"[build] place={place_id} 검색 키워드 실패(키워드 없이 발행): {type(ex).__name__}: {ex}")
|
||||
if seo:
|
||||
snapshot["seo"] = seo
|
||||
|
||||
v_err, version_no = await DB_SESSION_MNG.execute_lambda(
|
||||
site_versions.DBType(), DBWRType.DB_READ.value, lambda s: _site_crud.next_version_no(s, site.site_id)
|
||||
)
|
||||
@@ -180,6 +202,9 @@ async def run_build(job: dict) -> dict:
|
||||
# 잡 결과에 남긴다 — "노래가 왜 없나" 를 잡 하나만 열어 보면 알 수 있어야 한다.
|
||||
if song_result is not None:
|
||||
result["song"] = song_result
|
||||
# "제목이 왜 예전 그대로인가" 도 같다 — 키워드가 실렸으면 잡 결과에 보인다(없으면 로그의 [seo] 줄).
|
||||
if seo is not None:
|
||||
result["seo"] = seo
|
||||
now = GTime.UTC()
|
||||
|
||||
async def _fail(reason: str, gate: publish_gate.GateResult | None = None, extra: dict | None = None):
|
||||
|
||||
@@ -9,11 +9,15 @@
|
||||
실제로는 그 화면이 닫힌 뒤에 문장이 도착해 발행본이 영영 빈칸이었다
|
||||
(근거·실측: services/fact_service.upsert_fact · docs/DECISIONS.md 7절).
|
||||
- 사장님이 고친 문장(CORRECTED)은 재생성이 덮지 않는다. 그 잠금은 그대로다.
|
||||
- FAQ 가 목표 수(20)에 모자라면 업종 카탈로그에서 겹치지 않는 공통 질문을 **문의 안내** 답으로 채운다
|
||||
(services/faq_fill · common/faq_catalog). 답에 값·가능 여부를 적지 않으므로 사실을 만들지 않는다.
|
||||
★ fact 가 0건이어도(또는 API 키가 없어도) 채운다 — 그때는 LLM 을 부르지 않고 채우기만 한다.
|
||||
"""
|
||||
import uuid
|
||||
|
||||
from common.category_schema import CategorySchemaError, get_schema
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.faq_catalog import FaqCatalog, find_catalog
|
||||
from common.database.model.models import place_facts, place_faqs, place_channels, places, place_units
|
||||
from common.enums import (
|
||||
PUBLISHABLE_FACT_STATUSES,
|
||||
@@ -31,7 +35,7 @@ from crud.fact_crud import FactCRUD
|
||||
from crud.faq_crud import FaqCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from router.v1.fact.protocol import Req_UpsertFact
|
||||
from services import place_research
|
||||
from services import faq_fill, place_research
|
||||
from services.external import gemini_text
|
||||
from services.fact_service import FactService
|
||||
|
||||
@@ -50,9 +54,6 @@ async def run_copy(job: dict) -> dict:
|
||||
place_id = payload["place_id"]
|
||||
owner_user_id = payload["owner_user_id"]
|
||||
|
||||
if not gemini_text.is_configured():
|
||||
raise CopyAborted("GEMINI_API_KEY 미설정 — 소개문·FAQ 를 생성할 수 없다")
|
||||
|
||||
err, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
@@ -159,9 +160,33 @@ async def run_copy(job: dict) -> dict:
|
||||
if by_unit.get(str(u.unit_id))
|
||||
]
|
||||
|
||||
if not grounded and not unit_summaries:
|
||||
# 근거가 없으면 아무것도 쓰지 않는다 — 유료 호출조차 하지 않는다.
|
||||
return {"place_id": place_id, "intro": False, "faqs": 0, "note": "근거로 쓸 확인된 fact 가 없다"}
|
||||
# FAQ 채우기에 쓸 업종 카탈로그. 없으면(카페·음식점·호텔) 채우지 않는다.
|
||||
catalog = find_catalog(place.category, place.external_category)
|
||||
# 사업장·객실 fact 를 가리지 않는다 — "기준 인원" 은 객실 fact 로 답한다.
|
||||
known_fact_keys = {r.key for r in fact_rows if (r.value or "").strip()}
|
||||
|
||||
# ── LLM 을 부르지 않는 경우 ── 근거가 없거나(환각·유료 호출 방지) 키가 없을 때.
|
||||
# ★ 그래도 카탈로그가 있으면 FAQ 는 문의 안내로 20개를 채운다 — fact 가 0건이어도 20개(DECISIONS 8절).
|
||||
ungrounded = not grounded and not unit_summaries
|
||||
if ungrounded or not gemini_text.is_configured():
|
||||
note = "근거로 쓸 확인된 fact 가 없다" if ungrounded else "GEMINI_API_KEY 미설정"
|
||||
if catalog is None:
|
||||
if not ungrounded:
|
||||
raise CopyAborted(f"{note} — 소개문·FAQ 를 생성할 수 없다")
|
||||
return {"place_id": place_id, "intro": False, "faqs": 0, "faq_fill": 0, "note": note}
|
||||
if ungrounded:
|
||||
# 근거가 사라졌으니 예전 생성분도 근거가 없다 — 내리고 새로 채운다.
|
||||
# 키만 없는 경우는 내리지 않는다: 멀쩡한 생성 FAQ 가 키 설정 하나 때문에 사라지면 안 된다.
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
place_faqs.DBType(),
|
||||
lambda s: _faq_crud.expire_generated(s, pid, GTime.UTC()),
|
||||
)
|
||||
filled = await _fill_faqs(pid, catalog, known_fact_keys, place.phone)
|
||||
LOG.i(f"[copy] place={place_id} LLM 호출 없음({note}) · 문의 안내 채움 {filled}건")
|
||||
return {
|
||||
"place_id": place_id, "grounded_facts": len(grounded), "intro": False, "meta": False,
|
||||
"faqs": 0, "faq_fill": filled, "rejected": [], "note": note,
|
||||
}
|
||||
|
||||
try:
|
||||
copy = await gemini_text.generate_copy(
|
||||
@@ -170,6 +195,8 @@ async def run_copy(job: dict) -> dict:
|
||||
grounded,
|
||||
unit_summaries=unit_summaries or None,
|
||||
records=records or None,
|
||||
suggested_questions=faq_fill.suggested_questions(catalog, known_fact_keys) if catalog else None,
|
||||
max_faqs=faq_fill.FAQ_TARGET,
|
||||
model=external_api_config.gemini_text_model,
|
||||
)
|
||||
except gemini_text.GeminiNotConfigured as ex:
|
||||
@@ -182,6 +209,7 @@ async def run_copy(job: dict) -> dict:
|
||||
"intro": False,
|
||||
"meta": False,
|
||||
"faqs": 0,
|
||||
"faq_fill": 0, # 목표 수를 채운 문의 안내 문항 수
|
||||
# ★ 반려된 문장을 그대로 남긴다 — 소개문이 왜 안 나왔는지 운영자가 알아야 한다.
|
||||
"rejected": [list(r) for r in (copy.rejected or [])][:20],
|
||||
}
|
||||
@@ -245,6 +273,53 @@ async def run_copy(job: dict) -> dict:
|
||||
if run_err == ErrorType.SUCCESS:
|
||||
stat["faqs"] += 1
|
||||
|
||||
# ── 목표 수 채우기 ── 생성분이 모자라면 카탈로그의 겹치지 않는 공통 질문을 문의 안내로 채운다.
|
||||
if catalog is not None:
|
||||
stat["faq_fill"] = await _fill_faqs(pid, catalog, known_fact_keys, place.phone)
|
||||
|
||||
LOG.i(f"[copy] place={place_id} 소개문 {'O' if stat['intro'] else 'X'} · FAQ {stat['faqs']}건 · "
|
||||
f"반려 {len(stat['rejected'])}건 (근거 fact {len(grounded)}개)")
|
||||
f"문의 안내 채움 {stat['faq_fill']}건 · 반려 {len(stat['rejected'])}건 (근거 fact {len(grounded)}개)")
|
||||
return stat
|
||||
|
||||
|
||||
async def _fill_faqs(pid: uuid.UUID, catalog: FaqCatalog, known_fact_keys: set[str], phone: str | None) -> int:
|
||||
"""노출 중인 FAQ 가 목표 수에 모자란 만큼 문의 안내 문항을 넣는다. 넣은 건수를 돌려준다.
|
||||
|
||||
★ 기존 FAQ 는 **노출 중인 것 전부**로 센다 — 방금 넣은 생성분만이 아니라 재생성이 남긴
|
||||
사장님 입력·정정분까지. 그래야 사장님이 이미 답한 주제에 문의 안내가 겹쳐 붙지 않는다.
|
||||
★ 바로 노출값(VERIFIED)으로 넣는다. 답이 주장을 하지 않아 확인할 대상이 없다 —
|
||||
대신 JSON-LD · llms.txt · 고유 콘텐츠 계수에서는 빠진다(shared selectAnsweredFaqs)."""
|
||||
l_err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_faqs.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _faq_crud.list_faqs(s, pid, True),
|
||||
)
|
||||
if l_err != ErrorType.SUCCESS:
|
||||
LOG.e_no_callstack(f"[copy] FAQ 채우기 건너뜀 — 목록 조회 실패 place={pid} {l_err.name}")
|
||||
return 0
|
||||
|
||||
picks = faq_fill.pick_fill_faqs(
|
||||
catalog,
|
||||
[faq_fill.ExistingFaq(r.question, r.source_fact_ids) for r in rows],
|
||||
known_fact_keys,
|
||||
phone,
|
||||
)
|
||||
next_order = max((r.sort_order for r in rows), default=-1) + 1
|
||||
added = 0
|
||||
for offset, pick in enumerate(picks):
|
||||
row = place_faqs(
|
||||
place_id=pid,
|
||||
question=pick.question,
|
||||
answer=pick.answer,
|
||||
source_fact_ids=None,
|
||||
generated_by=SourceType.TEMPLATE.value,
|
||||
status=FactStatus.VERIFIED.value,
|
||||
sort_order=next_order + offset,
|
||||
)
|
||||
run_err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_faqs.DBType()],
|
||||
[lambda s, r=row: _faq_crud.add_faq(s, r)],
|
||||
)
|
||||
if run_err == ErrorType.SUCCESS:
|
||||
added += 1
|
||||
return added
|
||||
+2
-1
@@ -98,6 +98,7 @@ async def generate_copy(
|
||||
*,
|
||||
unit_summaries: Optional[list[dict]] = None,
|
||||
records: Optional[list[str]] = None,
|
||||
suggested_questions: Optional[list[str]] = None,
|
||||
max_faqs: int = 8,
|
||||
model: str = DEFAULT_TEXT_MODEL,
|
||||
max_retries: int = 2,
|
||||
@@ -126,7 +127,7 @@ async def generate_copy(
|
||||
|
||||
body = {
|
||||
"contents": [{"role": "user", "parts": [{
|
||||
"text": build_prompt(place_name, category, facts, max_faqs, unit_grounding, records)
|
||||
"text": build_prompt(place_name, category, facts, max_faqs, unit_grounding, records, suggested_questions)
|
||||
}]}],
|
||||
"generationConfig": {
|
||||
"responseMimeType": "application/json",
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""SiteOntology(o2o-site-ontology) 클라이언트 — 이 가게에 맞는 검색 키워드를 받아 온다.
|
||||
|
||||
SiteOntology 는 펜션 SEO/AEO 키워드 사전(pgvector)을 들고, 업체 프로필에 맞는 단어를 골라 주는
|
||||
사내 서비스다. 여기서는 창구 두 개만 쓴다(실측 2026-09-14, 로컬 :3100).
|
||||
|
||||
POST /v1/merchants/publish {externalId, name, industryId, regionId, description, profile, generate:false}
|
||||
→ 201 {merchant, generation: "skipped"} 업체를 저장만 한다. 키워드는 주지 않는다
|
||||
POST /v1/match {query: <externalId>, limit}
|
||||
→ 201 {resolved, lanes, matches[], byLane[], excluded[]} 저장된 프로필로 추천한다
|
||||
|
||||
★ 두 번 부르는 이유: "프로필을 주면 키워드를 돌려주는" 창구가 한 번에는 없다. match 는 query 문자열만
|
||||
받고, externalId 를 넣으면 저장된 업체로 해석해 그 프로필로 추천한다. 그래서 먼저 publish 로 프로필을
|
||||
이번 빌드의 스냅샷 값으로 맞춘다.
|
||||
★ generate:false 를 반드시 보낸다. 빠뜨리면 SiteOntology 가 LLM 키워드 생성을 큐에 넣는다 —
|
||||
그 결과는 우리가 쓰지 않는 창구(/seo)로만 나가고, 로컬은 mock LLM 이라 가짜 단어가 사전에 쌓인다.
|
||||
★ regionId 가 SiteOntology 의 region 표에 없으면 **500** 이다(외래키 위반, 실측). 그 표는 적재한 데이터셋에
|
||||
따라 달라서(군산만 / 전국 54개) 우리가 알 수 없다 — 500 이면 regionId 를 비워 한 번 더 보낸다.
|
||||
지역이 비면 유형 추천에서 "군산" 이 빠져 품질이 떨어지지만(실측: 1위가 `독채펜션`), 없는 것보다 낫고
|
||||
지역 없는 단어는 호출측 거르기(seo_keywords)가 제목에서 뺀다.
|
||||
★ externalId 가 해석되지 않으면 match 는 에러가 아니라 **입력 문자열 자체로 검색한 결과**를 201 로 준다
|
||||
(실측: "no-such-place-id" → `나운동 숙소`·`선유도 숙소 예약 언제 해야 하나요`). 그걸 쓰면 남의 동네 단어가
|
||||
나간다 — resolved 가 우리 externalId 가 아니면 실패로 본다.
|
||||
★ 실패는 발행을 막지 않는다. 여기서는 SiteOntologyError 로 올리고, 호출측이 잡아 키워드 없이 굽는다.
|
||||
"""
|
||||
|
||||
import httpx
|
||||
|
||||
from common.logger import LOG
|
||||
from config.server_configs import external_api_config
|
||||
|
||||
# 로컬 임베딩 모델이라 호출당 1~2초다. 넉넉히 잡되 발행 잡 데드라인(900s)을 잡아먹지 않게 끊는다.
|
||||
TIMEOUT_SEC = 15.0
|
||||
# 거르기(seo_keywords)에서 절반 넘게 떨어진다(실측: 10건 → 4건). 메타 태그 10개를 채우려면 넉넉히 받는다.
|
||||
DEFAULT_LIMIT = 40
|
||||
|
||||
PUBLISH_PATH = "/v1/merchants/publish"
|
||||
MATCH_PATH = "/v1/match"
|
||||
|
||||
|
||||
class SiteOntologyError(RuntimeError):
|
||||
"""SiteOntology 호출 실패(네트워크·타임아웃·4xx/5xx·업체 미해석). 발행은 계속된다."""
|
||||
|
||||
|
||||
def base_url() -> str:
|
||||
return (external_api_config.site_ontology_url or "").strip().rstrip("/")
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
return bool(base_url())
|
||||
|
||||
|
||||
async def _post(client: httpx.AsyncClient, path: str, body: dict) -> dict:
|
||||
res = await client.post(f"{base_url()}{path}", json=body)
|
||||
if res.status_code >= 400:
|
||||
raise SiteOntologyError(f"{path} HTTP {res.status_code}: {res.text[:200]}")
|
||||
try:
|
||||
data = res.json()
|
||||
except ValueError as ex:
|
||||
raise SiteOntologyError(f"{path} 응답이 JSON 이 아니다: {res.text[:200]}") from ex
|
||||
if not isinstance(data, dict):
|
||||
raise SiteOntologyError(f"{path} 응답 모양이 다르다: {type(data).__name__}")
|
||||
return data
|
||||
|
||||
|
||||
async def match_for_merchant(merchant: dict, limit: int = DEFAULT_LIMIT) -> dict:
|
||||
"""업체를 저장하고, 그 업체로 해석된 추천 결과(/v1/match 응답)를 돌려준다.
|
||||
|
||||
merchant 는 publish 요청 본문이다(generate 는 여기서 붙인다). 실패하면 SiteOntologyError."""
|
||||
body = {**merchant, "generate": False}
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=TIMEOUT_SEC) as client:
|
||||
try:
|
||||
await _post(client, PUBLISH_PATH, body)
|
||||
except SiteOntologyError as ex:
|
||||
if not body.get("regionId"):
|
||||
raise
|
||||
LOG.w(f"[site-ontology] regionId={body['regionId']} 로 저장하지 못했다 — 지역 없이 다시 보낸다: {ex}")
|
||||
body = {**body, "regionId": None}
|
||||
await _post(client, PUBLISH_PATH, body)
|
||||
result = await _post(client, MATCH_PATH, {"query": merchant["externalId"], "limit": limit})
|
||||
except httpx.HTTPError as ex:
|
||||
raise SiteOntologyError(f"{type(ex).__name__}: {ex}") from ex
|
||||
|
||||
resolved = result.get("resolved") or {}
|
||||
if resolved.get("externalId") != merchant["externalId"]:
|
||||
raise SiteOntologyError(f"업체가 해석되지 않았다 — externalId={merchant['externalId']}")
|
||||
return result
|
||||
@@ -276,6 +276,12 @@ class FactService:
|
||||
res.result.SetResult(ErrorType.FACT_INVALID_KEY)
|
||||
return res
|
||||
|
||||
# 규칙 4 — TEMPLATE 은 FAQ 문의 안내 전용 출처다(services/faq_fill). fact 에는 쓸 수 없다.
|
||||
# OWNER 도 자동 수집도 아니라서, 막지 않으면 아래 분기에서 사람 입력처럼 바로 노출값이 된다.
|
||||
if req.source_type == SourceType.TEMPLATE:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
|
||||
pid = uuid.UUID(place_id)
|
||||
pub_err, published = await DB_SESSION_MNG.execute_lambda(
|
||||
place_facts.DBType(),
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""FAQ 목표 수 채우기 — 생성된 FAQ 가 모자라면 카탈로그에서 겹치지 않는 공통 질문을 고른다.
|
||||
|
||||
순수 함수만 둔다(DB·네트워크 없음). 무엇이 왜 골렸는지를 이 파일만 읽고 답할 수 있어야 한다.
|
||||
|
||||
고르는 규칙 (카탈로그 순서 = 우선순위)
|
||||
1. 답할 fact 가 있는 질문은 고르지 않는다 — 그건 LLM 이 fact 로 답할 자리다.
|
||||
"주차할 수 있나요?" 에 parking=true 가 있는데 "문의 부탁드립니다" 가 붙으면 아는 것을 숨긴 셈이다.
|
||||
2. 기존 FAQ 가 이미 다룬 주제는 고르지 않는다. 기존 FAQ 에는 LLM 생성분 · 사장님 입력 · 정정분이 모두 든다.
|
||||
- 근거 fact key 가 겹치면 같은 주제다. LLM 은 "주차 및 와이파이" 처럼 두 주제를 한 문항에 묶고
|
||||
근거에 [parking, wifi] 를 적는다 — 낱말 대조만으로는 둘 중 하나를 놓친다.
|
||||
- 질문에 카탈로그 키워드가 들어 있으면 같은 주제다(사장님 입력은 근거 key 가 없다).
|
||||
3. 공통 답은 문의 안내뿐이다. 값·가능 여부를 적지 않는다(common/faq_catalog 머리주석).
|
||||
"""
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable, Optional
|
||||
|
||||
from common.faq_catalog import FaqCatalog
|
||||
|
||||
# ★ 사이트에 싣는 FAQ 목표 수. 생성 상한(max_faqs)도 이 값을 쓴다.
|
||||
FAQ_TARGET = 20
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExistingFaq:
|
||||
question: str
|
||||
source_fact_ids: Optional[list] = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FillFaq:
|
||||
catalog_id: str
|
||||
question: str
|
||||
answer: str
|
||||
|
||||
|
||||
def _compact(text: str) -> str:
|
||||
return re.sub(r"\s+", "", text or "").lower()
|
||||
|
||||
|
||||
def _base_key(key: str) -> str:
|
||||
"""객실 근거는 "A동:max_capacity" 로 적힌다 — 주제 비교에는 key 만 쓴다."""
|
||||
return str(key).rsplit(":", 1)[-1]
|
||||
|
||||
|
||||
def _with_topic_particle(topic: str) -> str:
|
||||
"""주제 뒤에 은/는 을 붙인다. 받침이 있으면 '은'."""
|
||||
last = topic.strip()[-1:]
|
||||
if "가" <= last <= "힣":
|
||||
return topic + ("은" if (ord(last) - ord("가")) % 28 else "는")
|
||||
return topic + "은(는)"
|
||||
|
||||
|
||||
def fallback_answer(catalog: FaqCatalog, index: int, topic: str, phone: Optional[str]) -> str:
|
||||
"""문의 안내 문구. 문구를 번갈아 써서 스무 줄이 전부 같은 문장이 되지 않게 한다."""
|
||||
phone = (phone or "").strip()
|
||||
templates = catalog.fallback_with_contact if phone else catalog.fallback_without_contact
|
||||
template = templates[index % len(templates)]
|
||||
return template.format(topic=_with_topic_particle(topic), contact=f"전화({phone})")
|
||||
|
||||
|
||||
def pick_fill_faqs(
|
||||
catalog: FaqCatalog,
|
||||
existing: Iterable[ExistingFaq],
|
||||
fact_keys: Iterable[str],
|
||||
phone: Optional[str] = None,
|
||||
target: int = FAQ_TARGET,
|
||||
) -> list[FillFaq]:
|
||||
"""목표 수까지 모자란 만큼 카탈로그 질문을 고른다. 모자라지 않으면 빈 목록."""
|
||||
existing = list(existing)
|
||||
need = target - len(existing)
|
||||
if need <= 0:
|
||||
return []
|
||||
|
||||
asked = [_compact(faq.question) for faq in existing]
|
||||
covered_keys = {_base_key(k) for faq in existing for k in (faq.source_fact_ids or [])}
|
||||
known_keys = {_base_key(k) for k in fact_keys}
|
||||
|
||||
picked: list[FillFaq] = []
|
||||
for item in catalog.items:
|
||||
if len(picked) >= need:
|
||||
break
|
||||
if known_keys.intersection(item.fact_keys):
|
||||
continue # 규칙 1
|
||||
if covered_keys.intersection(item.fact_keys):
|
||||
continue # 규칙 2 — 근거 key
|
||||
if any(keyword in question for keyword in item.keywords for question in asked):
|
||||
continue # 규칙 2 — 질문 낱말
|
||||
answer = fallback_answer(catalog, len(picked), item.topic, phone)
|
||||
picked.append(FillFaq(item.id, item.question, answer))
|
||||
return picked
|
||||
|
||||
|
||||
def suggested_questions(catalog: FaqCatalog, fact_keys: Iterable[str]) -> list[str]:
|
||||
"""fact 로 답할 수 있는 카탈로그 질문 — 프롬프트에 실어 LLM 이 이 질문들부터 쓰게 한다.
|
||||
채우기(규칙 1)가 이 질문들을 건너뛰므로, LLM 이 안 쓰면 그 주제는 비게 된다."""
|
||||
known = {_base_key(k) for k in fact_keys}
|
||||
return [item.question for item in catalog.items if known.intersection(item.fact_keys)]
|
||||
@@ -904,22 +904,21 @@ class PlaceService:
|
||||
async def start_copy(self, user_info: UserInfo, place_id: str, req: Req_StartCopy) -> Res_StartCopy:
|
||||
"""소개문·FAQ 생성을 큐에 넣는다.
|
||||
|
||||
★ 근거로 쓸 확인된 fact 가 없으면 잡을 만들지 않는다 —
|
||||
근거 없이 문장을 쓰면 그게 환각이고, 유료 호출만 낭비된다."""
|
||||
★ 근거로 쓸 확인된 fact 가 없으면 LLM 은 부르지 않는다 —
|
||||
근거 없이 문장을 쓰면 그게 환각이고, 유료 호출만 낭비된다.
|
||||
★ 그래도 FAQ 카탈로그가 있는 업종(펜션)이면 잡을 만든다 — fact 가 0건이어도 FAQ 는
|
||||
문의 안내로 20개를 채운다(DECISIONS.md 8절). 그 경로는 LLM 을 안 쓰므로 API 키도 필요 없다."""
|
||||
from common.database.model.models import place_facts as facts_model
|
||||
from common.faq_catalog import find_catalog
|
||||
from crud.fact_crud import FactCRUD
|
||||
from services.external import gemini_text
|
||||
|
||||
res = Res_StartCopy()
|
||||
err_type, _place = await self._load(user_info, place_id)
|
||||
err_type, place = await self._load(user_info, place_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
if not gemini_text.is_configured():
|
||||
res.result.SetResult(ErrorType.GENERATOR_NOT_CONFIGURED)
|
||||
return res
|
||||
|
||||
crud = FactCRUD()
|
||||
f_err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
facts_model.DBType(),
|
||||
@@ -930,9 +929,15 @@ class PlaceService:
|
||||
res.result.SetResult(f_err)
|
||||
return res
|
||||
res.grounded_facts = sum(1 for r in rows if r.unit_id is None and (r.value or "").strip())
|
||||
if res.grounded_facts == 0:
|
||||
# 객실 fact 만 있어도 LLM 이 쓴다(copy_service 의 unit_summaries) — 키 검사는 그 기준으로 한다.
|
||||
needs_llm = any((r.value or "").strip() for r in rows)
|
||||
if not needs_llm and find_catalog(place.category, place.external_category) is None:
|
||||
# 쓸 근거도, 채울 공통 질문도 없다(카페·음식점·호텔).
|
||||
res.result.SetResult(ErrorType.FAQ_UNGROUNDED)
|
||||
return res
|
||||
if needs_llm and not gemini_text.is_configured():
|
||||
res.result.SetResult(ErrorType.GENERATOR_NOT_CONFIGURED)
|
||||
return res
|
||||
|
||||
job_id, created = await enqueue_job(
|
||||
self.queue, JobType.COPY,
|
||||
|
||||
@@ -56,6 +56,7 @@ def build_prompt(
|
||||
max_faqs: int,
|
||||
unit_facts: Optional[Sequence[FactLike]] = None,
|
||||
records: Optional[Sequence[str]] = None,
|
||||
suggested_questions: Optional[Sequence[str]] = None,
|
||||
) -> str:
|
||||
"""소개문·메타·FAQ 생성 프롬프트.
|
||||
|
||||
@@ -79,6 +80,14 @@ def build_prompt(
|
||||
"업소에 대해 확인된 기록(출처가 있는 글):",
|
||||
*(f"- {line}" for line in records),
|
||||
])
|
||||
if suggested_questions:
|
||||
# 업종 카탈로그 중 위 사실로 답할 수 있는 질문들(services/faq_fill.suggested_questions).
|
||||
# ★ 채우기는 fact 가 있는 질문을 건너뛴다 — 여기서 모델이 안 쓰면 그 주제는 비어 버린다.
|
||||
sections.extend([
|
||||
"",
|
||||
"FAQ 로 먼저 쓸 질문(위 사실로 답할 수 있는 것):",
|
||||
*(f"- {q}" for q in suggested_questions),
|
||||
])
|
||||
sections.extend([
|
||||
"",
|
||||
"출력:",
|
||||
@@ -96,6 +105,9 @@ def build_prompt(
|
||||
"- false·불가·없음 값을 가능하다고 표현하지 않는다.",
|
||||
"- 홍보성·평가성 표현을 쓰지 않는다.",
|
||||
"- 근거 없는 FAQ는 만들지 않는다.",
|
||||
# ★ 실측(2026-09-14, 로컬): 노출 중인 생성 FAQ 4건 중 3건이 "체크인 및 체크아웃" 처럼 두 주제를 묶었다.
|
||||
# 묶으면 문항 수는 그대로인데 다룬 주제가 줄고, 채우기의 겹침 판정도 두 주제를 함께 지운다.
|
||||
"- FAQ 한 문항에는 주제 하나만 묻는다(예: 체크인과 체크아웃을 한 문항에 묶지 않는다).",
|
||||
"- 한국어 존댓말을 사용한다.",
|
||||
])
|
||||
return "\n".join(sections)
|
||||
@@ -6,6 +6,8 @@
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
|
||||
from common.enums import SourceType
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AuditCheck:
|
||||
@@ -31,7 +33,8 @@ def _check(id, group, label, points, passed, detail, recommendation=None, partia
|
||||
def evaluate(snapshot: dict, *, verified: bool, site=None, version=None, ai_checks: list | None = None) -> dict:
|
||||
place = snapshot.get("place") or {}
|
||||
facts = snapshot.get("facts") or []
|
||||
faqs = snapshot.get("faqs") or []
|
||||
# 문의 안내(TEMPLATE)는 답이 아니다 — "질문형 FAQ" 에 세면 채우기만으로 만점이 난다.
|
||||
faqs = [q for q in (snapshot.get("faqs") or []) if q.get("generated_by") != SourceType.TEMPLATE.value]
|
||||
media = snapshot.get("media") or []
|
||||
built = bool(version and getattr(version, "built_at", None))
|
||||
unique_count = int(getattr(version, "unique_content_count", 0) or 0) if version else 0
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
"""발행 사이트 메타 태그용 검색 키워드 — SiteOntology 추천을 이 가게의 확인된 자료로 한 번 더 거른다.
|
||||
|
||||
스냅샷 → 업체 프로필(build_merchant) → SiteOntology publish + match → 거르기(select)
|
||||
→ snapshot["seo"] → payload.seo → <meta name="keywords"> · <title> 의 업종어 자리
|
||||
|
||||
★ 스냅샷에 싣는다(site_versions.snapshot). payload 는 스냅샷만 보고 만든다는 원칙(site_payload 머리주석)을
|
||||
그대로 지키고, "이 버전에 어떤 키워드가 나갔나" 가 발행 기록으로 남는다. SiteOntology 쪽에는 남기지 않는다.
|
||||
★ 숙박만 부른다. SiteOntology 사전은 펜션 키워드뿐이다(2026-09-14 기준 industry=stay.pension).
|
||||
다른 업종으로 부르면 펜션 단어가 카페 사이트의 메타 태그에 붙는다.
|
||||
|
||||
★ 거르기 규칙은 하나다 — **키워드의 모든 낱말이 이 가게의 확인된 자료에 있어야 한다.**
|
||||
SiteOntology 의 사실 필터는 수용 인원과 일부 시설(바베큐·수영장·스파…)만 본다. 실측(2026-09-14, 스테이머뭄
|
||||
프로필)에서 `군산 독채 마당 펜션`·`군산 독채 복층 펜션` 이 status=ok 로 왔다 — 마당·복층은 확인된 적이 없다.
|
||||
사전에는 `선유도 독채펜션`(다른 권역)·`군산 펜션 최저가`(가격 주장)도 있다. 낱말 대조 하나로 셋이 함께 걸린다.
|
||||
메타 태그와 제목은 AI 검색이 그대로 읽는 자리라, 확인 안 된 시설을 광고하는 단어는 지어낸 문장과 같다
|
||||
(solution/site/src/seo/meta.ts 머리주석 — description 은 지어내지 않는다).
|
||||
"자료" 는 상호·소개문·주소·확인된 시설/객실 fact·발행되는 주변 관광지다. 미확인(unverified)은 자료가 아니다.
|
||||
"""
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from common.enums import LocalContentType, PlaceCategory
|
||||
from common.logger import LOG
|
||||
from services.external import site_ontology
|
||||
from services.site_payload import _parse_address_parts
|
||||
|
||||
LODGING_INDUSTRY = "stay.pension"
|
||||
MAX_KEYWORDS = 10
|
||||
MAX_NEARBY = 8
|
||||
|
||||
# ★ SiteOntology 의 시설 어휘(match.rules.ts AMENITY_SYNONYMS)로 옮긴다 — 저쪽이 이 낱말로 보유 시설을 판정한다.
|
||||
# 값이 "true" 면 있음 → features, "false" 면 **없음** → 어디에도 넣지 않는다(그래야 저쪽이 그 시설 키워드를 배제한다),
|
||||
# fact 가 아예 없으면 **모름** → unverified(저쪽이 배제하지 않고 보류한다 — 없음과 모름은 다르다).
|
||||
_AMENITY_FACTS = {
|
||||
"bbq_available": "바베큐",
|
||||
"parking": "주차",
|
||||
"pet_allowed": "애견동반",
|
||||
"breakfast": "조식",
|
||||
}
|
||||
# 사장님이 확인한 글자 그대로 싣는 fact(객실 단위 포함). "독채"·"오션뷰" 같은 유형·전망어가 여기서 온다.
|
||||
_FEATURE_TEXT_KEYS = ("room_type", "building_scale", "facilities", "view")
|
||||
_CAPACITY_KEYS = ("max_capacity", "accommodation_capacity")
|
||||
|
||||
# (ISO 3166-2 시·도, 시·군) → SiteOntology region 키(data/regions.json 54개).
|
||||
# ★ 시·도를 함께 본다 — 고성군은 강원과 경남에 둘 다 있다.
|
||||
# ★ 을왕리(kr.incheon.yeongjong)는 넣지 않는다. 행정구역으로는 인천 중구인데 중구 전체를 을왕리로 보낼 수 없다.
|
||||
_REGION_KEYS = {
|
||||
("KR-41", "가평군"): "kr.gyeonggi.gapyeong", ("KR-41", "양평군"): "kr.gyeonggi.yangpyeong",
|
||||
("KR-41", "포천시"): "kr.gyeonggi.pocheon", ("KR-41", "파주시"): "kr.gyeonggi.paju",
|
||||
("KR-28", "강화군"): "kr.incheon.ganghwa",
|
||||
("KR-42", "춘천시"): "kr.gangwon.chuncheon", ("KR-42", "홍천군"): "kr.gangwon.hongcheon",
|
||||
("KR-42", "인제군"): "kr.gangwon.inje", ("KR-42", "평창군"): "kr.gangwon.pyeongchang",
|
||||
("KR-42", "정선군"): "kr.gangwon.jeongseon", ("KR-42", "강릉시"): "kr.gangwon.gangneung",
|
||||
("KR-42", "속초시"): "kr.gangwon.sokcho", ("KR-42", "양양군"): "kr.gangwon.yangyang",
|
||||
("KR-42", "고성군"): "kr.gangwon.goseong", ("KR-42", "동해시"): "kr.gangwon.donghae",
|
||||
("KR-42", "삼척시"): "kr.gangwon.samcheok", ("KR-42", "태백시"): "kr.gangwon.taebaek",
|
||||
("KR-43", "단양군"): "kr.chungbuk.danyang", ("KR-43", "제천시"): "kr.chungbuk.jecheon",
|
||||
("KR-43", "충주시"): "kr.chungbuk.chungju", ("KR-43", "괴산군"): "kr.chungbuk.goesan",
|
||||
("KR-44", "태안군"): "kr.chungnam.taean", ("KR-44", "보령시"): "kr.chungnam.boryeong",
|
||||
("KR-44", "서산시"): "kr.chungnam.seosan", ("KR-44", "공주시"): "kr.chungnam.gongju",
|
||||
("KR-44", "부여군"): "kr.chungnam.buyeo",
|
||||
("KR-45", "군산시"): "kr.jeonbuk.gunsan", ("KR-45", "부안군"): "kr.jeonbuk.buan",
|
||||
("KR-45", "전주시"): "kr.jeonbuk.jeonju", ("KR-45", "무주군"): "kr.jeonbuk.muju",
|
||||
("KR-45", "남원시"): "kr.jeonbuk.namwon",
|
||||
("KR-46", "여수시"): "kr.jeonnam.yeosu", ("KR-46", "순천시"): "kr.jeonnam.suncheon",
|
||||
("KR-46", "담양군"): "kr.jeonnam.damyang", ("KR-46", "구례군"): "kr.jeonnam.gurye",
|
||||
("KR-46", "해남군"): "kr.jeonnam.haenam", ("KR-46", "완도군"): "kr.jeonnam.wando",
|
||||
("KR-46", "보성군"): "kr.jeonnam.boseong",
|
||||
("KR-47", "경주시"): "kr.gyeongbuk.gyeongju", ("KR-47", "포항시"): "kr.gyeongbuk.pohang",
|
||||
("KR-47", "안동시"): "kr.gyeongbuk.andong", ("KR-47", "영덕군"): "kr.gyeongbuk.yeongdeok",
|
||||
("KR-47", "울진군"): "kr.gyeongbuk.uljin", ("KR-47", "문경시"): "kr.gyeongbuk.mungyeong",
|
||||
("KR-48", "거제시"): "kr.gyeongnam.geoje", ("KR-48", "통영시"): "kr.gyeongnam.tongyeong",
|
||||
("KR-48", "남해군"): "kr.gyeongnam.namhae", ("KR-48", "하동군"): "kr.gyeongnam.hadong",
|
||||
("KR-48", "사천시"): "kr.gyeongnam.sacheon", ("KR-48", "산청군"): "kr.gyeongnam.sancheong",
|
||||
("KR-26", "기장군"): "kr.busan.gijang",
|
||||
("KR-49", "제주시"): "kr.jeju.jejusi", ("KR-49", "서귀포시"): "kr.jeju.seogwipo",
|
||||
}
|
||||
|
||||
# 자료에 없어도 되는 낱말 — 업종어와 "근처" 류. 무엇을 주장하지 않는다.
|
||||
_GENERIC_WORDS = frozenset({"펜션", "숙소", "숙박", "스테이", "근처", "가까운", "주변", "인근", "예약", "추천"})
|
||||
# "독채펜션"·"감성숙소" 처럼 붙여 쓴 업종어는 떼고 앞부분만 자료와 대조한다.
|
||||
_GENERIC_SUFFIXES = ("펜션", "숙소", "스테이")
|
||||
# 제목에는 싣지 않는 낱말. `스테이,머뭄 · 군산 독채펜션 예약` 은 검색어로는 맞아도 가게 이름 옆에서는 광고 문구다.
|
||||
_TITLE_BLOCKED_WORDS = frozenset({"예약", "추천"})
|
||||
# 한 글자 낱말("봄"·"뷰")은 소개문 어딘가에 우연히 들어 있어 대조가 무의미하다 — 통과시키지 않는다.
|
||||
_MIN_CORE_LEN = 2
|
||||
|
||||
_NON_WORD = re.compile(r"[^\w]")
|
||||
|
||||
|
||||
def _text(value) -> str:
|
||||
return str(value).strip() if value is not None else ""
|
||||
|
||||
|
||||
def _compact(text: str) -> str:
|
||||
"""대조용 표기 — 공백·구두점을 지우고 소문자로. "스테이,머뭄" 과 "스테이 머뭄" 이 같아진다."""
|
||||
return _NON_WORD.sub("", unicodedata.normalize("NFKC", text or "").lower())
|
||||
|
||||
|
||||
def _number(value) -> int | None:
|
||||
try:
|
||||
return int(float(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def region_key(*addresses: str | None) -> str | None:
|
||||
"""주소 → SiteOntology region 키. 표에 없으면 None(지어내지 않는다)."""
|
||||
parts = _parse_address_parts(*addresses)
|
||||
locality = (parts.get("addressLocality") or "").split()
|
||||
if not locality:
|
||||
return None
|
||||
return _REGION_KEYS.get((parts["addressRegionCode"], locality[0]))
|
||||
|
||||
|
||||
def _locality_word(*addresses: str | None) -> str:
|
||||
"""사람이 검색창에 치는 시·군 이름 — "군산시" → "군산". 제목 키워드가 이 낱말을 품어야 한다."""
|
||||
locality = (_parse_address_parts(*addresses).get("addressLocality") or "").split()
|
||||
if not locality:
|
||||
return ""
|
||||
word = locality[0]
|
||||
return word[:-1] if len(word) > 2 and word.endswith(("시", "군", "구")) else word
|
||||
|
||||
|
||||
def build_merchant(place_id: str, snapshot: dict) -> dict | None:
|
||||
"""스냅샷 → SiteOntology publish 요청 본문. 숙박이 아니거나 상호가 없으면 None.
|
||||
|
||||
★ 스냅샷만 읽는다 — 스냅샷에는 노출 가능한 값(VERIFIED/CORRECTED fact · 발행 창 안의 지역 정보)만 있다.
|
||||
미검증 fact 를 프로필에 실으면 그걸 근거로 고른 키워드가 메타 태그로 나간다."""
|
||||
place = (snapshot or {}).get("place") or {}
|
||||
if _number(place.get("category")) != PlaceCategory.LODGING.value:
|
||||
return None
|
||||
name = _text(place.get("name"))
|
||||
if not name:
|
||||
return None
|
||||
|
||||
values: dict[str, list[str]] = {}
|
||||
for fact in (snapshot or {}).get("facts") or []:
|
||||
if not isinstance(fact, dict):
|
||||
continue
|
||||
value = _text(fact.get("value"))
|
||||
if value:
|
||||
values.setdefault(_text(fact.get("key")), []).append(value)
|
||||
|
||||
features: list[str] = []
|
||||
unverified: list[str] = []
|
||||
for key, label in _AMENITY_FACTS.items():
|
||||
found = values.get(key)
|
||||
if not found:
|
||||
unverified.append(label)
|
||||
elif "true" in found:
|
||||
features.append(label)
|
||||
for key in _FEATURE_TEXT_KEYS:
|
||||
for value in values.get(key, []):
|
||||
if value not in features:
|
||||
features.append(value)
|
||||
|
||||
capacities = [n for key in _CAPACITY_KEYS for n in map(_number, values.get(key, [])) if n]
|
||||
intro = next(iter(values.get("intro", [])), "")
|
||||
description = next((p.strip() for p in intro.split("\n") if p.strip()), "")
|
||||
|
||||
nearby: list[str] = []
|
||||
for row in ((snapshot or {}).get("local") or {}).get("contents") or []:
|
||||
if not isinstance(row, dict) or row.get("content_type") != LocalContentType.ATTRACTION.value:
|
||||
continue
|
||||
attraction = _text((row.get("body") or {}).get("name")) or _text(row.get("title"))
|
||||
if attraction and attraction not in nearby:
|
||||
nearby.append(attraction)
|
||||
if len(nearby) >= MAX_NEARBY:
|
||||
break
|
||||
|
||||
road_address, address = place.get("road_address"), place.get("address")
|
||||
profile = {
|
||||
"address": _text(road_address) or _text(address),
|
||||
"capacity": {"max": max(capacities)} if capacities else None,
|
||||
"features": features,
|
||||
"nearby": nearby,
|
||||
"unverified": unverified,
|
||||
}
|
||||
return {
|
||||
"externalId": place_id,
|
||||
"name": name,
|
||||
"industryId": LODGING_INDUSTRY,
|
||||
"regionId": region_key(road_address, address),
|
||||
"description": description,
|
||||
"profile": {key: value for key, value in profile.items() if value},
|
||||
}
|
||||
|
||||
|
||||
def _evidence(merchant: dict) -> str:
|
||||
"""이 가게의 확인된 자료를 한 덩어리로. 키워드 낱말은 여기에 들어 있어야 한다."""
|
||||
profile = merchant.get("profile") or {}
|
||||
parts = [
|
||||
merchant.get("name"), merchant.get("description"), profile.get("address"),
|
||||
*(profile.get("features") or []), *(profile.get("nearby") or []),
|
||||
]
|
||||
return _compact(" ".join(_text(p) for p in parts if p))
|
||||
|
||||
|
||||
def _supported(keyword: str, evidence: str) -> bool:
|
||||
"""모든 낱말이 자료에 있고, **자료로 확인한 낱말이 하나는 있어야** 한다.
|
||||
|
||||
★ 뒤 조건이 없으면 `숙소` 처럼 업종어뿐인 단어가 "주장하는 게 없다" 는 이유로 통과한다 —
|
||||
실측(2026-09-14, 실제 발행 한 바퀴)에서 메타 10칸 중 한 칸이 `숙소` 였다. 어느 가게에나 붙는 단어라
|
||||
이 가게를 설명하지 못한다."""
|
||||
specific = False
|
||||
for word in keyword.split():
|
||||
if word in _GENERIC_WORDS:
|
||||
continue
|
||||
core = next((word[: -len(s)] for s in _GENERIC_SUFFIXES if word.endswith(s) and len(word) > len(s)), word)
|
||||
core = _compact(core)
|
||||
if len(core) < _MIN_CORE_LEN or core not in evidence:
|
||||
return False
|
||||
specific = True
|
||||
return specific
|
||||
|
||||
|
||||
def _is_question(item: dict) -> bool:
|
||||
canonical = _text(item.get("canonical"))
|
||||
return item.get("category") == "질문형" or "?" in canonical or canonical.endswith(("요", "까"))
|
||||
|
||||
|
||||
def _usable(item, evidence: str) -> str | None:
|
||||
"""메타 태그에 실어도 되는 추천이면 그 표기를, 아니면 None."""
|
||||
if not isinstance(item, dict) or item.get("status") != "ok" or _is_question(item):
|
||||
return None
|
||||
canonical = _text(item.get("canonical"))
|
||||
return canonical if canonical and _supported(canonical, evidence) else None
|
||||
|
||||
|
||||
def _title_keyword(result: dict, evidence: str, locality: str) -> str | None:
|
||||
"""제목 업종어 자리에 넣을 대표 키워드 — 유형 레인에서 고른다.
|
||||
|
||||
★ SiteOntology 설계상 "한 페이지의 주력 키워드는 1개, 유형 레인 1위가 메인 페이지 주력" 이다.
|
||||
다만 1위가 `군산 펜션 독채`(시설) 이고 2위가 `군산 독채펜션`(코어) 인 식으로 오므로 코어를 앞에 둔다.
|
||||
★ 시·군 이름을 품어야 한다. `독채펜션` 만 남으면 지금 제목(`… 군산시 숙소`)보다 지역 신호가 약해진다."""
|
||||
lane = next(
|
||||
(l for l in result.get("byLane") or [] if isinstance(l, dict) and l.get("key") == "type"),
|
||||
{},
|
||||
)
|
||||
items = [i for i in lane.get("items") or [] if isinstance(i, dict)]
|
||||
for item in sorted(items, key=lambda i: i.get("category") != "코어"):
|
||||
canonical = _usable(item, evidence)
|
||||
if not canonical or _TITLE_BLOCKED_WORDS.intersection(canonical.split()):
|
||||
continue
|
||||
if locality and locality not in canonical:
|
||||
continue
|
||||
return canonical
|
||||
return None
|
||||
|
||||
|
||||
def select(result: dict, merchant: dict) -> dict:
|
||||
"""/v1/match 응답 → {keywords, titleKeyword?}. 순위는 SiteOntology 의 융합 순위를 그대로 따른다."""
|
||||
evidence = _evidence(merchant)
|
||||
keywords: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for item in result.get("matches") or []:
|
||||
canonical = _usable(item, evidence)
|
||||
if not canonical or _compact(canonical) in seen:
|
||||
continue
|
||||
seen.add(_compact(canonical))
|
||||
keywords.append(canonical)
|
||||
if len(keywords) >= MAX_KEYWORDS:
|
||||
break
|
||||
|
||||
seo: dict = {"keywords": keywords}
|
||||
title = _title_keyword(result, evidence, _locality_word((merchant.get("profile") or {}).get("address")))
|
||||
if title:
|
||||
seo["titleKeyword"] = title
|
||||
return seo
|
||||
|
||||
|
||||
async def fetch(place_id: str, snapshot: dict) -> dict | None:
|
||||
"""스냅샷에 실을 seo 값. 못 만들면 None — 예외를 올리지 않는다(키워드는 발행을 막지 않는다)."""
|
||||
if not site_ontology.is_configured():
|
||||
return None
|
||||
merchant = build_merchant(place_id, snapshot)
|
||||
if merchant is None:
|
||||
return None
|
||||
try:
|
||||
result = await site_ontology.match_for_merchant(merchant)
|
||||
except site_ontology.SiteOntologyError as ex:
|
||||
LOG.w(f"[seo] place={place_id} SiteOntology 실패 — 키워드 없이 발행: {ex}")
|
||||
return None
|
||||
|
||||
seo = select(result, merchant)
|
||||
LOG.i(
|
||||
f"[seo] place={place_id} 추천 {len(result.get('matches') or [])}건 → 메타 {len(seo['keywords'])}건"
|
||||
f" · 제목 {seo.get('titleKeyword') or '(기존 제목)'}"
|
||||
)
|
||||
if not seo["keywords"] and "titleKeyword" not in seo:
|
||||
return None
|
||||
return seo
|
||||
@@ -986,9 +986,26 @@ def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
||||
],
|
||||
"narrative": narrative,
|
||||
"theme": theme,
|
||||
# ★ 검색 키워드(SiteOntology). 스냅샷에 있을 때만 싣는다 — 옛 스냅샷·SiteOntology 가 꺼진 빌드에는 없고,
|
||||
# 그때 렌더러는 제목·메타를 예전 그대로 굽는다(solution/site/src/seo/meta.ts).
|
||||
**_seo_entry(snapshot.get("seo")),
|
||||
}
|
||||
|
||||
|
||||
def _seo_entry(value) -> dict:
|
||||
"""스냅샷의 seo(services/seo_keywords) → payload 의 `seo`. 없으면 키 자체를 만들지 않는다.
|
||||
|
||||
★ 여기서 다시 거르지 않는다 — 이 가게 자료로 거르는 곳은 seo_keywords 한 곳이다. 모양만 확인한다.
|
||||
★ 빈 seo 를 만들지 않는다. 빈 배열은 '받았는데 비었다' 로 읽힌다(itineraries 와 같은 규칙)."""
|
||||
if not isinstance(value, dict):
|
||||
return {}
|
||||
keywords = [_text(k) for k in value.get("keywords") or [] if _text(k)]
|
||||
title = _text(value.get("titleKeyword"))
|
||||
if not keywords and not title:
|
||||
return {}
|
||||
return {"seo": {"keywords": keywords, **({"titleKeyword": title} if title else {})}}
|
||||
|
||||
|
||||
def _as_float(value):
|
||||
try:
|
||||
return float(value) if value not in (None, "") else None
|
||||
|
||||
@@ -253,7 +253,7 @@ async def _local_contents(place) -> dict:
|
||||
.order_by(area_contents.content_type.asc(), area_contents.collected_at.desc())
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
area_contents.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, query)
|
||||
area_contents.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, query, raise_error=False)
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
# ★ 지역 정보가 없다고 발행을 막지 않는다 — 사업장의 사실이 아니라 곁들이는 정보다.
|
||||
@@ -278,7 +278,7 @@ async def _local_contents(place) -> dict:
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
area_contents.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: DB_SESSION_MNG.execute(s, shared_q),
|
||||
lambda s: DB_SESSION_MNG.execute(s, shared_q, raise_error=False),
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
LOG.w(f"[snapshot] 주변 정보 조회 실패 place={place_id}: {err.name}")
|
||||
@@ -354,7 +354,7 @@ async def _site_places(place_id) -> dict:
|
||||
.limit(1)
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
site_sections.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, q)
|
||||
site_sections.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, q, raise_error=False)
|
||||
)
|
||||
if err != ErrorType.SUCCESS or not rows:
|
||||
return {}
|
||||
@@ -407,9 +407,16 @@ def _iso(value) -> str | None:
|
||||
|
||||
|
||||
async def _select(query) -> list:
|
||||
"""조회 실패는 **빈 목록**이다 — 미리보기·발행이 조각 하나 때문에 통째로 죽지 않게.
|
||||
|
||||
★ raise_error=False 가 핵심이다 (2026-09-14). 이 함수는 원래 실패를 [] 로 삼키도록
|
||||
썼는데, DB 계층이 기본값 raise_error=True 로 **예외를 던져** 그 처리가 실행될 기회조차
|
||||
없었다. 실측: place_songs 테이블이 없던 동안 미리보기가 통째로 HTTP 500 이었다 —
|
||||
노래 한 칸이 빠진 화면 대신 아무것도 못 보는 화면이 나갔다.
|
||||
"""
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_facts.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: DB_SESSION_MNG.execute(s, query),
|
||||
lambda s: DB_SESSION_MNG.execute(s, query, raise_error=False),
|
||||
)
|
||||
return list(rows) if err == ErrorType.SUCCESS else []
|
||||
Reference in new issue
Block a user