Merge branch 'main' into feature/crawler
This commit is contained in:
commit
dd3ad86715
160 files changed
+111240
-202
No files matched your search
@@ -280,7 +280,12 @@ class place_facts(MainTableMixin, MAIN_BASE):
|
||||
|
||||
|
||||
class place_faqs(MainTableMixin, MAIN_BASE):
|
||||
"""FAQ. ★ 확보된 fact 만 근거로 쓴다 — source_fact_ids 가 비면 발행 게이트가 반려한다."""
|
||||
"""FAQ. 출처(generated_by)가 셋이고, 근거를 요구하는 정도가 다르다.
|
||||
|
||||
LLM 확보된 fact 로 쓴 문장 — source_fact_ids 에 근거 key 가 있다(없으면 저장하지 않는다)
|
||||
OWNER 사장님이 쓰거나 고친 문장 — 사람이 곧 출처라 근거 key 가 없을 수 있다
|
||||
TEMPLATE 목표 수를 채운 공통 질문 + 문의 안내 답(services/faq_fill) — 주장이 없어 근거도 없다.
|
||||
★ 화면에는 나가지만 FAQPage JSON-LD · llms.txt · 고유 콘텐츠 계수에서는 빠진다."""
|
||||
|
||||
__tablename__ = "place_faqs"
|
||||
|
||||
@@ -288,8 +293,8 @@ class place_faqs(MainTableMixin, MAIN_BASE):
|
||||
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
|
||||
question = Column(String(500), nullable=False)
|
||||
answer = Column(Text, nullable=False)
|
||||
source_fact_ids = Column(JSONB, nullable=True) # ★ 근거 fact_id 배열. 비면 반려
|
||||
generated_by = Column(SmallInteger, nullable=False) # SourceType — LLM | OWNER
|
||||
source_fact_ids = Column(JSONB, nullable=True) # 근거 fact key 배열 — LLM 생성분만 채운다
|
||||
generated_by = Column(SmallInteger, nullable=False) # SourceType — LLM | OWNER | TEMPLATE
|
||||
status = Column(SmallInteger, nullable=False, server_default=text("1"), default=FactStatus.UNVERIFIED.value)
|
||||
sort_order = Column(Integer, nullable=False, server_default=text("0"), default=0)
|
||||
|
||||
|
||||
@@ -206,13 +206,14 @@ class PlaceStatus(CodeEnum):
|
||||
|
||||
|
||||
class SourceType(CodeEnum):
|
||||
"""facts.source_type / media.source_type / place_aliases.source_type 공용 코드값.
|
||||
"""facts.source_type / media.source_type / place_aliases.source_type / place_faqs.generated_by 공용 코드값.
|
||||
값이 어디서 왔는지 — 모든 사실은 출처를 갖는다."""
|
||||
|
||||
OWNER = 1 # 사장님이 직접 입력·업로드
|
||||
API = 2 # 공식 API (카카오 로컬 · TourAPI · Open-Meteo · Perplexity)
|
||||
CRAWL = 3 # 크롤링
|
||||
LLM = 4 # LLM 생성 — ★ 사실이 아니라 문장에만 쓴다
|
||||
OWNER = 1 # 사장님이 직접 입력·업로드
|
||||
API = 2 # 공식 API (카카오 로컬 · TourAPI · Open-Meteo · Perplexity)
|
||||
CRAWL = 3 # 크롤링
|
||||
LLM = 4 # LLM 생성 — ★ 사실이 아니라 문장에만 쓴다
|
||||
TEMPLATE = 5 # FAQ 목표 수를 채운 공통 질문 + 문의 안내(services/faq_fill) — ★ FAQ 전용. fact 에는 못 쓴다
|
||||
|
||||
|
||||
class FactStatus(CodeEnum):
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""FAQ 질문 카탈로그 — 생성된 FAQ 가 목표 수에 모자랄 때 채울 업종 공통 질문.
|
||||
|
||||
★ 왜 필요한가
|
||||
COPY 잡은 확인된 fact 로만 FAQ 를 쓴다. 실측(2026-09-14, 로컬): 스테이머뭄 fact 8건,
|
||||
산하연 풀빌라 4건 — 그 근거로는 FAQ 가 4~8개에서 끝난다. 20개를 채우려면 근거 밖의 문항이 필요하다.
|
||||
|
||||
★ 공통 **답**은 주장을 하지 않는다 — "…은 숙소로 문의 부탁드립니다" 뿐이다.
|
||||
예전 업종 시드 FAQ 에는 "숯과 그릴 세트(25,000원)" 같은 가공의 값이 있었고, 사장님이 팔지도 않는
|
||||
조건이 사이트에 나갔다(frontend canvas/variants/faq/useFaqList.ts). 공통 답에 값·가능 여부를 적으면
|
||||
같은 사고다. 문의 안내만 쓴다.
|
||||
|
||||
resources/*.json 을 최초 사용 시 로드·검증한다. fact_keys 는 업종 스키마에 있는 key 여야 한다 —
|
||||
오타가 난 key 는 영영 "fact 없음" 으로 읽혀, 답이 있는 질문에 문의 안내가 붙는다.
|
||||
"""
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from common.category_schema import get_schema
|
||||
from common.enums import PlaceCategory
|
||||
|
||||
_RESOURCE_DIR = Path(__file__).parent / "resources"
|
||||
|
||||
_catalogs: list | None = None
|
||||
|
||||
|
||||
class FaqCatalogError(RuntimeError):
|
||||
"""카탈로그 리소스 로드/검증 실패."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CatalogItem:
|
||||
id: str
|
||||
question: str
|
||||
topic: str # 공통 답변 문구에 들어갈 주제("반려동물 동반 가능 여부")
|
||||
fact_keys: tuple[str, ...] # 이 질문에 답할 수 있는 fact. 하나라도 있으면 공통 답으로 채우지 않는다
|
||||
keywords: tuple[str, ...] # 기존 FAQ 질문에 이 낱말이 있으면 같은 주제로 본다(공백 없이 비교)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FaqCatalog:
|
||||
name: str
|
||||
label: str
|
||||
category: PlaceCategory
|
||||
exclude_external_categories: tuple[str, ...]
|
||||
fallback_with_contact: tuple[str, ...]
|
||||
fallback_without_contact: tuple[str, ...]
|
||||
items: tuple[CatalogItem, ...]
|
||||
|
||||
def applies_to(self, category: int, external_category: str | None) -> bool:
|
||||
"""업종 코드가 같고, 외부 분류가 제외 목록에 걸리지 않으면 이 카탈로그를 쓴다.
|
||||
|
||||
★ 외부 분류가 비어 있으면 **쓴다.** 스테이머뭄처럼 네이버 분류가 없는 펜션이 있다.
|
||||
호텔은 분류가 "호텔" 로 오므로 제외 목록이 막는다 — 호텔에 바비큐·픽업 문항이 붙으면 안 된다."""
|
||||
if category != self.category.value:
|
||||
return False
|
||||
label = external_category or ""
|
||||
return not any(word in label for word in self.exclude_external_categories)
|
||||
|
||||
|
||||
def _strings(value, source: str, name: str, *, allow_empty: bool = False) -> tuple[str, ...]:
|
||||
if not isinstance(value, list) or (not value and not allow_empty):
|
||||
raise FaqCatalogError(f"{source}: '{name}' 은 비어 있지 않은 목록이어야 함")
|
||||
if not all(isinstance(v, str) and v for v in value):
|
||||
raise FaqCatalogError(f"{source}: '{name}' 에 문자열이 아닌 값 — {value}")
|
||||
return tuple(value)
|
||||
|
||||
|
||||
def _parse(doc: dict, source: str) -> FaqCatalog:
|
||||
try:
|
||||
category = PlaceCategory(doc.get("category"))
|
||||
except ValueError as ex:
|
||||
raise FaqCatalogError(f"{source}: PlaceCategory 에 없는 category={doc.get('category')}") from ex
|
||||
schema = get_schema(category)
|
||||
|
||||
answers = doc.get("fallback_answers") or {}
|
||||
with_contact = _strings(answers.get("with_contact"), source, "with_contact")
|
||||
without_contact = _strings(answers.get("without_contact"), source, "without_contact")
|
||||
for text in with_contact + without_contact:
|
||||
if "{topic}" not in text:
|
||||
raise FaqCatalogError(f"{source}: 공통 답변에 {{topic}} 이 없음 — {text}")
|
||||
if not all("{contact}" in text for text in with_contact):
|
||||
raise FaqCatalogError(f"{source}: with_contact 답변에 {{contact}} 가 없음")
|
||||
|
||||
items: list[CatalogItem] = []
|
||||
seen: set[str] = set()
|
||||
for row in doc.get("items") or []:
|
||||
for name in ("id", "question", "topic"):
|
||||
if not isinstance(row.get(name), str) or not row[name].strip():
|
||||
raise FaqCatalogError(f"{source}: 항목 '{name}' 이 비었음 — {row}")
|
||||
if row["id"] in seen:
|
||||
raise FaqCatalogError(f"{source}: id 중복 — {row['id']}")
|
||||
seen.add(row["id"])
|
||||
fact_keys = _strings(row.get("fact_keys"), source, f"{row['id']}.fact_keys", allow_empty=True)
|
||||
unknown = [k for k in fact_keys if not schema.has(k)]
|
||||
if unknown:
|
||||
raise FaqCatalogError(f"{source}: {row['id']} 의 fact_keys 가 업종 스키마에 없음 — {unknown}")
|
||||
keywords = _strings(row.get("keywords"), source, f"{row['id']}.keywords")
|
||||
if any(" " in k for k in keywords):
|
||||
raise FaqCatalogError(f"{source}: {row['id']} 의 keywords 에 공백 — 질문은 공백을 지우고 비교한다")
|
||||
items.append(CatalogItem(row["id"], row["question"], row["topic"], fact_keys,
|
||||
tuple(k.lower() for k in keywords)))
|
||||
if not items:
|
||||
raise FaqCatalogError(f"{source}: items 가 비었음")
|
||||
|
||||
return FaqCatalog(
|
||||
name=str(doc.get("name") or source),
|
||||
label=str(doc.get("label") or ""),
|
||||
category=category,
|
||||
exclude_external_categories=_strings(
|
||||
doc.get("exclude_external_categories") or [], source, "exclude_external_categories", allow_empty=True),
|
||||
fallback_with_contact=with_contact,
|
||||
fallback_without_contact=without_contact,
|
||||
items=tuple(items),
|
||||
)
|
||||
|
||||
|
||||
def load_catalogs() -> list[FaqCatalog]:
|
||||
"""리소스 디렉터리 전체 로드 + 검증. 최초 1회(멱등)."""
|
||||
global _catalogs
|
||||
if _catalogs is None:
|
||||
loaded = []
|
||||
for path in sorted(_RESOURCE_DIR.glob("*.json")):
|
||||
try:
|
||||
doc = json.loads(path.read_text(encoding="utf-8"))
|
||||
except Exception as ex:
|
||||
raise FaqCatalogError(f"카탈로그 파일 로드 실패: {path}: {ex}") from ex
|
||||
loaded.append(_parse(doc, path.name))
|
||||
_catalogs = loaded
|
||||
return list(_catalogs)
|
||||
|
||||
|
||||
def find_catalog(category: int, external_category: str | None) -> FaqCatalog | None:
|
||||
"""이 사업장에 쓸 카탈로그. 없으면 None — 채우지 않는다(카페·음식점은 아직 목록이 없다)."""
|
||||
return next((c for c in load_catalogs() if c.applies_to(category, external_category)), None)
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"name": "pension",
|
||||
"label": "펜션",
|
||||
"category": 1,
|
||||
"exclude_external_categories": ["호텔", "모텔", "리조트"],
|
||||
"fallback_answers": {
|
||||
"with_contact": [
|
||||
"{topic} {contact}로 문의해 주시면 안내해 드립니다.",
|
||||
"{topic} {contact}로 연락 주시면 자세히 알려 드립니다.",
|
||||
"{topic} 예약 전에 {contact}로 확인해 주세요."
|
||||
],
|
||||
"without_contact": [
|
||||
"{topic} 예약 전에 숙소로 직접 문의 부탁드립니다.",
|
||||
"{topic} 숙소에 문의해 주시면 안내해 드립니다.",
|
||||
"{topic} 이용 전에 숙소로 확인 부탁드립니다."
|
||||
]
|
||||
},
|
||||
"items": [
|
||||
{"id": "check_in", "question": "체크인은 몇 시부터인가요?", "topic": "체크인 시간", "fact_keys": ["check_in_time"], "keywords": ["체크인", "입실시간"]},
|
||||
{"id": "check_out", "question": "체크아웃은 몇 시까지인가요?", "topic": "체크아웃 시간", "fact_keys": ["check_out_time"], "keywords": ["체크아웃", "퇴실시간"]},
|
||||
{"id": "late_check_in", "question": "늦은 시간에 도착해도 입실할 수 있나요?", "topic": "늦은 시간 입실 가능 여부", "fact_keys": ["reception_hours"], "keywords": ["늦은시간", "늦게도착", "늦게입실", "늦은입실", "밤늦게"]},
|
||||
{"id": "luggage", "question": "입실 전이나 퇴실 후에 짐을 맡길 수 있나요?", "topic": "짐 보관 가능 여부", "fact_keys": [], "keywords": ["짐보관", "짐을맡", "짐맡"]},
|
||||
{"id": "checkout_cleaning", "question": "퇴실할 때 설거지나 분리수거를 해야 하나요?", "topic": "퇴실 시 정리 방법", "fact_keys": [], "keywords": ["설거지", "분리수거", "퇴실청소", "뒷정리"]},
|
||||
{"id": "cancel", "question": "예약을 취소하면 환불은 어떻게 되나요?", "topic": "취소·환불 규정", "fact_keys": ["cancel_policy"], "keywords": ["취소", "환불"]},
|
||||
{"id": "weekday_weekend_price", "question": "평일과 주말 요금이 다른가요?", "topic": "평일·주말 요금", "fact_keys": ["weekday_price", "weekend_price"], "keywords": ["평일", "주말요금"]},
|
||||
{"id": "peak_price", "question": "성수기 요금이 따로 있나요?", "topic": "성수기 요금", "fact_keys": ["peak_price"], "keywords": ["성수기"]},
|
||||
{"id": "deposit", "question": "보증금이 있나요?", "topic": "보증금 여부", "fact_keys": [], "keywords": ["보증금"]},
|
||||
{"id": "extra_costs", "question": "숙박 요금 외에 추가로 드는 비용이 있나요?", "topic": "숙박 요금 외 추가 비용", "fact_keys": ["extra_person_fee", "bbq_fee"], "keywords": ["추가비용", "추가로드는", "별도요금"]},
|
||||
{"id": "capacity", "question": "기준 인원과 최대 인원은 몇 명인가요?", "topic": "기준 인원과 최대 인원", "fact_keys": ["standard_capacity", "max_capacity"], "keywords": ["기준인원", "최대인원"]},
|
||||
{"id": "extra_person", "question": "인원을 추가하면 요금이 얼마인가요?", "topic": "인원 추가 요금", "fact_keys": ["extra_person_fee"], "keywords": ["인원추가", "추가인원", "인원을추가"]},
|
||||
{"id": "pet", "question": "반려동물과 함께 묵을 수 있나요?", "topic": "반려동물 동반 가능 여부", "fact_keys": ["pet_allowed"], "keywords": ["반려", "애견", "강아지"]},
|
||||
{"id": "baby", "question": "아기와 함께 가도 되나요? 유아용품이 있나요?", "topic": "유아 동반과 유아용품", "fact_keys": ["baby_amenities"], "keywords": ["아기", "유아"]},
|
||||
{"id": "room_types", "question": "어떤 객실(동)이 있나요?", "topic": "객실 구성", "fact_keys": ["room_type", "total_rooms", "building_scale"], "keywords": ["객실종류", "어떤객실", "객실구성"]},
|
||||
{"id": "bed", "question": "침대는 어떻게 구성되어 있나요?", "topic": "침대 구성", "fact_keys": ["bed_type"], "keywords": ["침대", "침구"]},
|
||||
{"id": "bathroom", "question": "객실에 욕실은 몇 개인가요?", "topic": "욕실 구성", "fact_keys": ["bathroom_count", "has_bathroom"], "keywords": ["욕실", "화장실"]},
|
||||
{"id": "toiletries", "question": "수건과 세면도구가 준비되어 있나요?", "topic": "수건·세면도구 제공 여부", "fact_keys": ["has_toiletries"], "keywords": ["수건", "세면도구", "어메니티"]},
|
||||
{"id": "aircon", "question": "냉난방이 되나요?", "topic": "냉난방 시설", "fact_keys": ["has_aircon"], "keywords": ["냉난방", "에어컨", "난방"]},
|
||||
{"id": "wifi", "question": "와이파이를 쓸 수 있나요?", "topic": "와이파이 이용 여부", "fact_keys": ["wifi", "has_internet"], "keywords": ["와이파이", "인터넷", "wifi"]},
|
||||
{"id": "view", "question": "객실에서 어떤 풍경이 보이나요?", "topic": "객실 전망", "fact_keys": ["view"], "keywords": ["풍경", "전망"]},
|
||||
{"id": "cooking", "question": "객실에서 요리할 수 있나요?", "topic": "객실 내 취사 가능 여부", "fact_keys": ["cooking_allowed", "has_kitchen"], "keywords": ["취사", "요리", "조리"]},
|
||||
{"id": "bbq", "question": "바비큐를 할 수 있나요?", "topic": "바비큐 이용 가능 여부", "fact_keys": ["bbq_available"], "keywords": ["바비큐", "바베큐"]},
|
||||
{"id": "bbq_fee", "question": "바비큐 요금과 제공되는 준비물은 무엇인가요?", "topic": "바비큐 요금과 준비물", "fact_keys": ["bbq_fee"], "keywords": ["바비큐요금", "바베큐요금", "바비큐비용", "숯"]},
|
||||
{"id": "breakfast", "question": "조식이 제공되나요?", "topic": "조식 제공 여부", "fact_keys": ["breakfast"], "keywords": ["조식", "아침식사"]},
|
||||
{"id": "pool", "question": "수영장이 있나요? 온수로 이용할 수 있나요?", "topic": "수영장·온수 이용 여부", "fact_keys": [], "keywords": ["수영장", "온수풀", "풀장"]},
|
||||
{"id": "smoking", "question": "흡연할 수 있는 곳이 있나요?", "topic": "흡연 가능 구역", "fact_keys": ["smoking"], "keywords": ["흡연", "담배"]},
|
||||
{"id": "parking", "question": "주차할 수 있나요? 몇 대까지 가능한가요?", "topic": "주차 가능 여부", "fact_keys": ["parking", "parking_capacity"], "keywords": ["주차"]},
|
||||
{"id": "pickup", "question": "대중교통으로 가면 픽업이 되나요?", "topic": "픽업 서비스", "fact_keys": ["pickup_service"], "keywords": ["픽업", "대중교통", "셔틀"]},
|
||||
{"id": "nearby", "question": "근처에 편의점이나 마트가 있나요?", "topic": "주변 편의시설", "fact_keys": [], "keywords": ["편의점", "마트"]}
|
||||
]
|
||||
}
|
||||
@@ -136,6 +136,9 @@ class ExternalApiConfig(BaseSettings):
|
||||
# ★ 콜백은 쓰지 않고 폴링한다 — 우리 백엔드는 로컬·사내망이라 Suno 가 부를 수 있는 주소가 아니다.
|
||||
# 그래도 API 가 필수로 요구하는 필드라 값을 들고 있는다(services/external/suno.py 주석).
|
||||
suno_callback_url: str = Field("", validation_alias="SUNO_CALLBACK_URL")
|
||||
# 발행 사이트 메타 키워드(keywords · 제목)를 받아 오는 사내 서비스(o2o-site-ontology). 비면 그 단계만
|
||||
# 건너뛴다 — 제목·메타가 예전 그대로 나간다(services/seo_keywords).
|
||||
site_ontology_url: str = Field("", validation_alias="SITE_ONTOLOGY_URL")
|
||||
|
||||
|
||||
# .env 를 요청마다 다시 읽지 않는다. 새 코드는 Depends(get_*) 로 주입받는다.
|
||||
|
||||
@@ -220,9 +220,11 @@ def fake_renderer(monkeypatch, tmp_path_factory):
|
||||
for unit in payload.get("units") or []:
|
||||
facts.extend(unit.get("facts") or [])
|
||||
count += sum(1 for f in facts if f.get("type") == "text" and long(f.get("value")))
|
||||
# 문의 안내(sourceType=TEMPLATE)는 모든 가게에 같은 문구라 고유 콘텐츠가 아니다.
|
||||
count += sum(
|
||||
1 for q in payload.get("faqs") or []
|
||||
if str(q.get("question") or "").strip() and long(q.get("answer"))
|
||||
if q.get("sourceType") != 5
|
||||
and str(q.get("question") or "").strip() and long(q.get("answer"))
|
||||
)
|
||||
count += sum(1 for m in payload.get("media") or [] if long(m.get("alt")))
|
||||
return count
|
||||
|
||||
@@ -89,7 +89,9 @@ class FaqCRUD(IFaqCRUD):
|
||||
.where(
|
||||
place_faqs.place_id == place_id,
|
||||
place_faqs.deleted == False, # noqa: E712
|
||||
place_faqs.generated_by == SourceType.LLM.value,
|
||||
# 목표 수를 채운 공통 질문(TEMPLATE)도 자동 산출물이다 — 재생성마다 다시 고른다.
|
||||
# 안 내리면 fact 가 새로 생겨 LLM 이 답한 주제에 옛 문의 안내가 겹쳐 남는다.
|
||||
place_faqs.generated_by.in_((SourceType.LLM.value, SourceType.TEMPLATE.value)),
|
||||
# 이미 내려간 것(EXPIRED)과 사장님이 반려한 것(REJECTED)은 그대로 둔다 —
|
||||
# 반려는 판단의 기록이라 재생성이 지울 이유가 없다.
|
||||
place_faqs.status.not_in((FactStatus.EXPIRED.value, FactStatus.REJECTED.value)),
|
||||
|
||||
@@ -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 []
|
||||
@@ -52,7 +52,8 @@ async def _place_with_facts(client, h, n_verified=5):
|
||||
async def _faq_rows(db_engine, pid):
|
||||
async with db_engine.begin() as c:
|
||||
return (await c.execute(
|
||||
text("SELECT question, answer, source_fact_ids, status FROM place_faqs WHERE place_id = :p ORDER BY sort_order"),
|
||||
text("SELECT question, answer, source_fact_ids, status, generated_by FROM place_faqs "
|
||||
"WHERE place_id = :p ORDER BY sort_order"),
|
||||
{"p": uuid.UUID(pid)},
|
||||
)).all()
|
||||
|
||||
@@ -86,22 +87,29 @@ async def test_copy_generates_intro_and_faq_as_published(auth_headers, client, d
|
||||
assert intro[0]["source_type"] == SourceType.LLM.value
|
||||
|
||||
|
||||
async def test_copy_refuses_without_verified_facts(auth_headers, client, monkeypatch):
|
||||
"""검증: 확인된 fact 가 하나도 없는 사업장에서 생성을 시도한다.
|
||||
기대결과: FAQ_UNGROUNDED — ★ 잡을 만들지 않는다. 근거 없이 쓰면 환각이고 유료 호출만 낭비다."""
|
||||
async def _must_not_call_llm(*args, **kwargs):
|
||||
raise AssertionError("★ 근거 없이 LLM 을 불렀다")
|
||||
|
||||
|
||||
async def test_copy_refuses_without_facts_when_no_catalog(auth_headers, client, monkeypatch):
|
||||
"""검증: 확인된 fact 가 하나도 없는 **호텔**(펜션 카탈로그 제외 대상)에서 생성을 시도한다.
|
||||
기대결과: FAQ_UNGROUNDED — ★ 잡을 만들지 않는다. 쓸 근거도, 채울 공통 질문도 없다."""
|
||||
monkeypatch.setattr(gemini_text, "is_configured", lambda: True)
|
||||
h = await auth_headers("u1")
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "빈펜션", "category": 1})).json()["place"]["place_id"]
|
||||
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "빈주소"})
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "빈호텔", "category": 1})).json()["place"]["place_id"]
|
||||
await client.post(f"/v1/place/{pid}/verify", headers=h,
|
||||
json={"source": 2, "road_address": "빈호텔주소", "category_name": "호텔"})
|
||||
|
||||
r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
||||
assert r.json()["result"]["code"] == ErrorType.FAQ_UNGROUNDED.value
|
||||
|
||||
|
||||
async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client, monkeypatch):
|
||||
"""검증: 크롤링으로 들어온 미검증 fact 만 있는 사업장.
|
||||
기대결과: 근거로 안 쳐서 FAQ_UNGROUNDED — 미검증 값으로 쓴 문장도 미검증이다."""
|
||||
async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client, db_engine, monkeypatch):
|
||||
"""검증: 크롤링으로 들어온 미검증 fact 만 있는 펜션.
|
||||
기대결과: ★ 근거 0건으로 친다 — LLM 을 부르지 않는다(미검증 값으로 쓴 문장도 미검증이다).
|
||||
FAQ 는 문의 안내로 20개를 채우고, 미검증인 체크인도 '답이 있는 주제' 로 치지 않는다."""
|
||||
monkeypatch.setattr(gemini_text, "is_configured", lambda: True)
|
||||
monkeypatch.setattr(gemini_text, "generate_copy", _must_not_call_llm)
|
||||
h = await auth_headers("u1")
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "미검증펜션", "category": 1})).json()["place"]["place_id"]
|
||||
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "미검증주소"})
|
||||
@@ -109,8 +117,36 @@ async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client,
|
||||
"key": "check_in_time", "value": "15:00",
|
||||
"source_type": SourceType.CRAWL.value, "source_url": "https://ota.test/1"})
|
||||
|
||||
r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
||||
assert r.json()["result"]["code"] == ErrorType.FAQ_UNGROUNDED.value
|
||||
body = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()
|
||||
assert body["result"]["success"] is True and body["grounded_facts"] == 0
|
||||
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
|
||||
job = (await client.get(f"/v1/job/{body['job_id']}", headers=h)).json()["job"]
|
||||
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
|
||||
assert job["result"]["faqs"] == 0 and job["result"]["faq_fill"] == 20
|
||||
|
||||
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
|
||||
assert len(live) == 20 and all(r[4] == SourceType.TEMPLATE.value for r in live)
|
||||
assert any("체크인" in r[0] for r in live)
|
||||
|
||||
|
||||
async def test_zero_facts_still_fill_twenty_without_api_key(auth_headers, client, db_engine, monkeypatch):
|
||||
"""검증: fact 0건 · GEMINI 키 없음인 펜션(분류 없음 — 스테이머뭄처럼).
|
||||
기대결과: ★ 잡이 만들어지고 FAQ 가 정확히 20건 — 채우기는 LLM 을 안 쓰므로 키가 필요 없다."""
|
||||
monkeypatch.setattr(gemini_text, "is_configured", lambda: False)
|
||||
monkeypatch.setattr(gemini_text, "generate_copy", _must_not_call_llm)
|
||||
h = await auth_headers("u1")
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "무근거펜션", "category": 1})).json()["place"]["place_id"]
|
||||
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "무근거주소"})
|
||||
|
||||
body = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()
|
||||
assert body["result"]["success"] is True, body["result"]
|
||||
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
|
||||
job = (await client.get(f"/v1/job/{body['job_id']}", headers=h)).json()["job"]
|
||||
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
|
||||
assert job["result"]["faq_fill"] == 20
|
||||
|
||||
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
|
||||
assert len(live) == 20 and len({r[0] for r in live}) == 20
|
||||
|
||||
|
||||
async def test_faq_without_grounding_is_dropped(auth_headers, client, db_engine, monkeypatch):
|
||||
@@ -128,7 +164,10 @@ async def test_faq_without_grounding_is_dropped(auth_headers, client, db_engine,
|
||||
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
||||
assert job["result"]["faqs"] == 1
|
||||
assert any("수영장" in str(r) for r in job["result"]["rejected"])
|
||||
assert len(await _faq_rows(db_engine, pid)) == 1
|
||||
rows = await _faq_rows(db_engine, pid)
|
||||
assert len([r for r in rows if r[4] == SourceType.LLM.value]) == 1
|
||||
# 채우기가 넣은 문의 안내에도 '수영장 있나요?' 의 거짓 답("네 있습니다")은 없다.
|
||||
assert not any("있습니다" in r[1] for r in rows if r[4] == SourceType.TEMPLATE.value)
|
||||
|
||||
|
||||
async def test_rejected_sentences_are_reported(auth_headers, client, monkeypatch):
|
||||
@@ -161,9 +200,10 @@ async def test_regeneration_keeps_faq_the_owner_corrected(auth_headers, client,
|
||||
# 사장님이 문구를 고쳐 승인 — 잠긴 상태(CORRECTED)가 되고 책임 주체가 사람으로 넘어온다.
|
||||
async with db_engine.begin() as c:
|
||||
await c.execute(
|
||||
text("UPDATE place_faqs SET status = :s, generated_by = :g, question = :q WHERE place_id = :p"),
|
||||
text("UPDATE place_faqs SET status = :s, generated_by = :g, question = :q "
|
||||
"WHERE place_id = :p AND generated_by = :llm"),
|
||||
{"s": FactStatus.CORRECTED.value, "g": SourceType.OWNER.value,
|
||||
"q": "체크인 시간이 어떻게 되나요?", "p": uuid.UUID(pid)},
|
||||
"q": "체크인 시간이 어떻게 되나요?", "p": uuid.UUID(pid), "llm": SourceType.LLM.value},
|
||||
)
|
||||
|
||||
_patch(monkeypatch, _copy(faqs=[gemini_text.GeneratedFaq("새 질문?", "새 답변", ["check_in_time"])]))
|
||||
@@ -177,6 +217,55 @@ async def test_regeneration_keeps_faq_the_owner_corrected(auth_headers, client,
|
||||
assert any(r[0] == "새 질문?" and r[3] == FactStatus.VERIFIED.value for r in rows)
|
||||
|
||||
|
||||
_PUBLISHABLE = (FactStatus.VERIFIED.value, FactStatus.CORRECTED.value)
|
||||
|
||||
|
||||
async def test_copy_fills_faqs_to_target_without_duplicates(auth_headers, client, db_engine, monkeypatch):
|
||||
"""검증: 생성된 FAQ 가 1건뿐이고, 사장님이 직접 쓴 FAQ 가 1건 있다.
|
||||
기대결과: 노출 중 FAQ 가 정확히 20건 —
|
||||
· 모자란 만큼은 문의 안내(TEMPLATE)로 채운다
|
||||
· fact 로 답할 수 있는 주제(체크인·체크아웃·취소·취사·반려동물)에는 문의 안내를 붙이지 않는다
|
||||
· 사장님이 이미 쓴 주제(보증금)도 다시 넣지 않는다"""
|
||||
_patch(monkeypatch, _copy())
|
||||
h = await auth_headers("u1")
|
||||
pid = await _place_with_facts(client, h)
|
||||
owner = await client.post(f"/v1/place/{pid}/faq", headers=h, json={"question": "보증금이 있나요?", "answer": "없습니다."})
|
||||
assert owner.json()["result"]["success"] is True
|
||||
|
||||
job_id = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()["job_id"]
|
||||
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
|
||||
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
||||
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
|
||||
assert job["result"]["faqs"] == 1
|
||||
assert job["result"]["faq_fill"] == 18
|
||||
|
||||
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
|
||||
assert len(live) == 20
|
||||
assert len({r[0] for r in live}) == 20, "같은 질문이 두 번 들어갔다"
|
||||
|
||||
fills = [r for r in live if r[4] == SourceType.TEMPLATE.value]
|
||||
assert len(fills) == 18
|
||||
fill_text = " ".join(r[0] for r in fills)
|
||||
for topic in ("체크인", "체크아웃", "취소", "요리", "반려동물", "보증금"):
|
||||
assert topic not in fill_text, f"★ 이미 답이 있는 주제 '{topic}' 에 문의 안내가 붙었다"
|
||||
assert all("문의" in r[1] or "확인" in r[1] for r in fills), "문의 안내가 아닌 답이 섞였다"
|
||||
|
||||
|
||||
async def test_regeneration_replaces_fill_faqs(auth_headers, client, db_engine, monkeypatch):
|
||||
"""검증: 생성을 두 번 돌린다.
|
||||
기대결과: 노출 중 FAQ 는 여전히 20건 — 옛 문의 안내는 내려가고 다시 고른다(쌓이지 않는다)."""
|
||||
_patch(monkeypatch, _copy())
|
||||
h = await auth_headers("u1")
|
||||
pid = await _place_with_facts(client, h)
|
||||
for _ in range(2):
|
||||
await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
||||
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
|
||||
|
||||
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
|
||||
assert len(live) == 20
|
||||
assert len({r[0] for r in live}) == 20
|
||||
|
||||
|
||||
async def test_copy_requires_api_key(auth_headers, client, monkeypatch):
|
||||
"""검증: GEMINI_API_KEY 없이 생성을 시도한다.
|
||||
기대결과: GENERATOR_NOT_CONFIGURED — 잡을 만들지 않는다."""
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""FAQ 목표 수 채우기 — ★ 공통 답은 문의 안내뿐이고, 이미 다룬 주제는 다시 넣지 않는다.
|
||||
|
||||
이 기능이 절대 하면 안 되는 것:
|
||||
- 공통 답에 값·가능 여부를 적는 것 (가게마다 다르다 — 틀리면 예약 클레임)
|
||||
- fact 로 답할 수 있는 질문에 "문의 부탁드립니다" 를 붙이는 것 (아는 것을 숨긴다)
|
||||
- 기존 FAQ 와 같은 주제를 다시 넣는 것
|
||||
"""
|
||||
import re
|
||||
|
||||
from common.enums import ErrorType, PlaceCategory
|
||||
from common.faq_catalog import find_catalog
|
||||
from services import faq_fill
|
||||
from services.faq_fill import ExistingFaq
|
||||
|
||||
|
||||
def _pension():
|
||||
catalog = find_catalog(PlaceCategory.LODGING.value, "펜션")
|
||||
assert catalog is not None
|
||||
return catalog
|
||||
|
||||
|
||||
def _ids(picks):
|
||||
return {p.catalog_id for p in picks}
|
||||
|
||||
|
||||
def test_pension_catalog_has_thirty_questions():
|
||||
"""검증: 카탈로그 로드. fact_keys 가 업종 스키마에 없으면 로더가 예외를 던진다."""
|
||||
catalog = _pension()
|
||||
assert len(catalog.items) == 30
|
||||
assert len({item.id for item in catalog.items}) == 30
|
||||
|
||||
|
||||
def test_catalog_scope():
|
||||
"""검증: 호텔·카페에는 펜션 질문을 붙이지 않는다. 분류가 비어 있는 숙박업(스테이머뭄)에는 붙인다."""
|
||||
assert find_catalog(PlaceCategory.LODGING.value, "호텔") is None
|
||||
assert find_catalog(PlaceCategory.CAFE.value, None) is None
|
||||
assert find_catalog(PlaceCategory.LODGING.value, None) is not None
|
||||
|
||||
|
||||
def test_fills_only_the_shortfall():
|
||||
"""검증: 기존 FAQ 5건(카탈로그와 무관한 질문). 기대결과: 15건만 고른다. 20건이면 0건."""
|
||||
catalog = _pension()
|
||||
picks = faq_fill.pick_fill_faqs(catalog, [ExistingFaq(f"기타 질문 {i}") for i in range(5)], set())
|
||||
assert len(picks) == 15 and len(_ids(picks)) == 15
|
||||
assert faq_fill.pick_fill_faqs(catalog, [ExistingFaq(f"질문 {i}") for i in range(20)], set()) == []
|
||||
|
||||
|
||||
def test_skips_topics_answerable_by_facts():
|
||||
"""검증: 체크인·반려동물 fact 가 있다(객실 fact 는 'A동:max_capacity' 로 적힌다).
|
||||
기대결과: 그 질문들은 문의 안내로 채우지 않는다 — LLM 이 fact 로 답할 자리다."""
|
||||
picks = faq_fill.pick_fill_faqs(_pension(), [], {"check_in_time", "pet_allowed", "A동:max_capacity"}, target=30)
|
||||
assert not _ids(picks) & {"check_in", "pet", "capacity"}
|
||||
|
||||
|
||||
def test_skips_topics_already_asked_by_keyword():
|
||||
"""검증: 사장님이 근거 key 없이 쓴 FAQ 가 있다. 기대결과: 질문 낱말로 같은 주제를 알아본다."""
|
||||
existing = [ExistingFaq("반려견 데려가도 되나요?"), ExistingFaq("주차 되나요?")]
|
||||
picks = faq_fill.pick_fill_faqs(_pension(), existing, set(), target=30)
|
||||
assert not _ids(picks) & {"pet", "parking"}
|
||||
|
||||
|
||||
def test_skips_topics_covered_by_source_fact_keys():
|
||||
"""검증: LLM FAQ 의 질문에는 키워드가 없지만 근거 key 가 [wifi, A동:max_capacity] 다.
|
||||
기대결과: 와이파이·인원 질문을 넣지 않는다 — LLM 은 두 주제를 한 문항에 묶기도 한다."""
|
||||
existing = [ExistingFaq("편의 안내가 궁금해요", ["wifi", "A동:max_capacity"])]
|
||||
picks = faq_fill.pick_fill_faqs(_pension(), existing, set(), target=30)
|
||||
assert not _ids(picks) & {"wifi", "capacity"}
|
||||
|
||||
|
||||
def test_answers_are_inquiry_only():
|
||||
"""검증: 공통 답 문구.
|
||||
기대결과: ★ 연락처가 없으면 숫자가 하나도 없다(가격·시각을 지어내지 않는다). 연락처가 있으면 그 번호만 들어간다."""
|
||||
catalog = _pension()
|
||||
for pick in faq_fill.pick_fill_faqs(catalog, [], set(), target=30):
|
||||
assert not re.search(r"\d", pick.answer), pick.answer
|
||||
assert "숙소" in pick.answer
|
||||
for pick in faq_fill.pick_fill_faqs(catalog, [], set(), phone="010-1234-5678", target=30):
|
||||
assert "전화(010-1234-5678)로" in pick.answer
|
||||
assert not re.search(r"\d", pick.answer.replace("010-1234-5678", "")), pick.answer
|
||||
|
||||
|
||||
def test_answer_particle_and_rotation():
|
||||
"""검증: 주제 뒤 조사(은/는)와 문구 돌려쓰기."""
|
||||
catalog = _pension()
|
||||
assert faq_fill.fallback_answer(catalog, 0, "보증금 여부", None).startswith("보증금 여부는 ")
|
||||
assert faq_fill.fallback_answer(catalog, 0, "주변 편의시설", None).startswith("주변 편의시설은 ")
|
||||
assert len({faq_fill.fallback_answer(catalog, i, "주제", None) for i in range(3)}) == 3
|
||||
|
||||
|
||||
def test_suggested_questions_are_the_answerable_ones():
|
||||
"""검증: 프롬프트에 실을 질문 = fact 로 답할 수 있는 카탈로그 질문."""
|
||||
questions = faq_fill.suggested_questions(_pension(), {"parking", "check_out_time"})
|
||||
assert questions == ["체크아웃은 몇 시까지인가요?", "주차할 수 있나요? 몇 대까지 가능한가요?"]
|
||||
|
||||
|
||||
async def test_template_source_cannot_write_fact(auth_headers, client):
|
||||
"""검증: fact 를 TEMPLATE 출처로 쓴다.
|
||||
기대결과: INVALID_REQUEST_DATA — 막지 않으면 사람 입력처럼 바로 노출값이 된다(fact_service 규칙 4)."""
|
||||
h = await auth_headers("u1")
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "틀펜션", "category": 1})).json()["place"]["place_id"]
|
||||
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "틀주소"})
|
||||
r = await client.post(f"/v1/place/{pid}/fact", headers=h, json={
|
||||
"key": "check_in_time", "value": "15:00", "source_type": 5, "source_url": "template:test"})
|
||||
assert r.json()["result"]["code"] == ErrorType.INVALID_REQUEST_DATA.value
|
||||
@@ -0,0 +1,321 @@
|
||||
"""발행 사이트 메타 태그 키워드(SiteOntology).
|
||||
|
||||
이 경로가 절대 하면 안 되는 것:
|
||||
- 이 가게 자료에 없는 낱말이 든 키워드를 메타 태그·제목에 싣는 것
|
||||
(확인 안 된 시설 · 다른 권역 · 가격 주장)
|
||||
- SiteOntology 실패로 발행을 막는 것 — 키워드는 곁들이다
|
||||
- 해석되지 않은 업체의 추천(입력 문자열로 검색한 결과)을 쓰는 것
|
||||
- 숙박이 아닌 업종에 펜션 키워드를 붙이는 것
|
||||
|
||||
★ MATCH 의 matches 1~10 · byLane 은 실제 응답에서 옮겼다 — 2026-09-14 로컬 SiteOntology(:3100) 에
|
||||
스테이머뭄 프로필(features 독채·프라이빗, audiences 커플·가족, nearby 말랭이마을·동국사)을 보낸 결과.
|
||||
11~13 은 같은 사전에 실제로 있는 단어로, 거르기 규칙을 보려고 붙였다.
|
||||
"""
|
||||
import json
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import JobStatus, LocalContentType, MediaStatus, PlaceCategory, SiteStatus, SourceType
|
||||
from crud.job_crud import JobQueue
|
||||
from services import seo_keywords
|
||||
from services.external import site_ontology
|
||||
from worker.handlers import build_handler
|
||||
from worker.runner import Worker
|
||||
|
||||
|
||||
def _kw(canonical, category, intent="local", status="ok"):
|
||||
return {"canonical": canonical, "category": category, "intent": intent, "kind": "keyword", "status": status}
|
||||
|
||||
|
||||
MATCH = {
|
||||
"mode": "fusion",
|
||||
"matches": [
|
||||
_kw("군산 펜션 독채", "시설"),
|
||||
_kw("군산 독채펜션", "코어"),
|
||||
_kw("군산 독채 마당 펜션", "롱테일"),
|
||||
_kw("군산 독채 복층 펜션", "롱테일"),
|
||||
_kw("군산 커플 프라이빗 펜션", "롱테일"),
|
||||
_kw("군산 독채펜션 예약", "코어", intent="transactional"),
|
||||
_kw("군산에 독채 펜션 있나요", "질문형", intent="informational"),
|
||||
_kw("군산 가족 독채펜션", "동반자"),
|
||||
_kw("말랭이마을 근처 숙소", "관광지"),
|
||||
_kw("군산 프라이빗한 독채", "분위기"),
|
||||
_kw("선유도 독채펜션", "권역"),
|
||||
_kw("군산 펜션 최저가", "의도", intent="transactional"),
|
||||
_kw("군산 주차 펜션", "시설", status="hold"),
|
||||
],
|
||||
"byLane": [
|
||||
{"key": "type", "label": "유형", "items": [
|
||||
_kw("군산 펜션 독채", "시설"),
|
||||
_kw("군산 독채펜션", "코어"),
|
||||
_kw("군산 독채 마당 펜션", "롱테일"),
|
||||
]},
|
||||
{"key": "place", "label": "위치", "items": [_kw("말랭이마을 근처 숙소", "관광지")]},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _fact(key, value, unit_id=None):
|
||||
return {"key": key, "value": value, "scope": "unit" if unit_id else "place", "unit_id": unit_id, "status": 3}
|
||||
|
||||
|
||||
def _snapshot(**place):
|
||||
return {
|
||||
"place": {
|
||||
"name": "스테이,머뭄", "category": PlaceCategory.LODGING.value,
|
||||
"road_address": "전북특별자치도 군산시 절골길 18", "address": None, **place,
|
||||
},
|
||||
"facts": [
|
||||
_fact("intro", "군산 원도심 말랭이마을 옆 독채 스테이.\n두 번째 문단은 싣지 않는다."),
|
||||
_fact("bbq_available", "false"),
|
||||
_fact("parking", "true"),
|
||||
_fact("room_type", "독채", unit_id="u1"),
|
||||
_fact("max_capacity", "4", unit_id="u1"),
|
||||
_fact("max_capacity", "2", unit_id="u2"),
|
||||
],
|
||||
"local": {"contents": [
|
||||
{"content_type": LocalContentType.ATTRACTION.value, "title": "말랭이마을", "body": {"name": "말랭이마을"}},
|
||||
{"content_type": LocalContentType.RESTAURANT.value, "title": "이성당", "body": {"name": "이성당"}},
|
||||
{"content_type": LocalContentType.ATTRACTION.value, "title": "동국사", "body": {}},
|
||||
]},
|
||||
}
|
||||
|
||||
|
||||
# ── 요청 만들기 ─────────────────────────────────────────────────────────────
|
||||
def test_스냅샷으로_업체_프로필을_만든다():
|
||||
"""검증: 확인된 fact·지역 정보가 든 숙박 스냅샷.
|
||||
기대결과: 있음(true)은 features, 모름(fact 없음)은 unverified, 없음(false)은 어디에도 없다."""
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
|
||||
assert merchant == {
|
||||
"externalId": "place-1",
|
||||
"name": "스테이,머뭄",
|
||||
"industryId": "stay.pension",
|
||||
"regionId": "kr.jeonbuk.gunsan",
|
||||
"description": "군산 원도심 말랭이마을 옆 독채 스테이.",
|
||||
"profile": {
|
||||
"address": "전북특별자치도 군산시 절골길 18",
|
||||
"capacity": {"max": 4},
|
||||
"features": ["주차", "독채"],
|
||||
# 음식점(이성당)은 주변 관광지가 아니다.
|
||||
"nearby": ["말랭이마을", "동국사"],
|
||||
# ★ 바베큐는 false(없음)라 여기 없다 — 넣으면 SiteOntology 가 배제 대신 보류한다.
|
||||
"unverified": ["애견동반", "조식"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_숙박이_아니면_부르지_않는다():
|
||||
assert seo_keywords.build_merchant("place-1", _snapshot(category=PlaceCategory.CAFE.value)) is None
|
||||
|
||||
|
||||
def test_표에_없는_지역은_지역을_비운다():
|
||||
"""검증: SiteOntology 지역 표(54개)에 없는 시·군.
|
||||
기대결과: 지어내지 않고 None — 없는 키를 보내면 SiteOntology 가 500 이다."""
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot(road_address="서울특별시 강남구 테헤란로 1"))
|
||||
assert merchant["regionId"] is None
|
||||
|
||||
|
||||
def test_같은_이름의_시군은_시도로_가른다():
|
||||
assert seo_keywords.region_key("강원특별자치도 고성군 토성면 1") == "kr.gangwon.goseong"
|
||||
assert seo_keywords.region_key("경상남도 고성군 고성읍 1") is None
|
||||
|
||||
|
||||
# ── 거르기 ─────────────────────────────────────────────────────────────────
|
||||
def test_자료가_뒷받침하는_키워드만_남긴다():
|
||||
"""검증: 실제 추천 결과를 이 가게 자료(주차·독채·원도심·말랭이마을·동국사)로 거른다.
|
||||
기대결과: 마당·복층·커플·가족·프라이빗(확인 안 됨), 선유도(다른 권역), 최저가(가격 주장),
|
||||
질문형, 보류(hold)가 모두 빠진다. 순위는 SiteOntology 순서 그대로."""
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
seo = seo_keywords.select(MATCH, merchant)
|
||||
|
||||
assert seo["keywords"] == ["군산 펜션 독채", "군산 독채펜션", "군산 독채펜션 예약", "말랭이마을 근처 숙소"]
|
||||
|
||||
|
||||
def test_제목_키워드는_유형_레인의_코어를_고른다():
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
assert seo_keywords.select(MATCH, merchant)["titleKeyword"] == "군산 독채펜션"
|
||||
|
||||
|
||||
def test_제목에는_예약_추천과_지역_없는_단어를_쓰지_않는다():
|
||||
"""검증: 유형 레인 코어가 `… 예약` 이고, 지역명이 없는 태그가 섞였다.
|
||||
기대결과: 둘을 건너뛰고 `군산 펜션 독채` — 상호 옆에서 광고 문구가 되거나 지역 신호를 잃지 않는다."""
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
result = {"matches": [], "byLane": [{"key": "type", "items": [
|
||||
_kw("군산 독채펜션 예약", "코어", intent="transactional"),
|
||||
_kw("독채펜션", "태그"),
|
||||
_kw("군산 펜션 독채", "시설"),
|
||||
]}]}
|
||||
assert seo_keywords.select(result, merchant) == {"keywords": [], "titleKeyword": "군산 펜션 독채"}
|
||||
|
||||
|
||||
def test_업종어뿐인_단어는_싣지_않는다():
|
||||
"""검증: 낱말이 전부 업종어·"근처" 류인 추천(실측: 실제 발행에서 `숙소` 가 메타 한 칸을 차지했다).
|
||||
기대결과: 뺀다 — 어느 가게에나 붙는 단어라 이 가게를 설명하지 못한다. 자료 낱말이 섞이면 남긴다."""
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
result = {"matches": [_kw("숙소", "태그"), _kw("펜션 예약", "의도"), _kw("원도심", "태그")], "byLane": []}
|
||||
assert seo_keywords.select(result, merchant)["keywords"] == ["원도심"]
|
||||
|
||||
|
||||
def test_표기만_다른_중복은_하나로():
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
result = {"matches": [_kw("군산 독채펜션", "코어"), _kw("군산 독채 펜션", "태그")], "byLane": []}
|
||||
assert seo_keywords.select(result, merchant)["keywords"] == ["군산 독채펜션"]
|
||||
|
||||
|
||||
# ── 클라이언트 ────────────────────────────────────────────────────────────
|
||||
def _response(status, body, url):
|
||||
return httpx.Response(status, json=body, request=httpx.Request("POST", url))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ontology_url(monkeypatch):
|
||||
monkeypatch.setattr(site_ontology.external_api_config, "site_ontology_url", "http://onto.test/")
|
||||
|
||||
|
||||
def _fake_ontology(sent, *, reject_region=False, resolve=True):
|
||||
async def fake_post(self, url, json=None, **kwargs):
|
||||
sent.append((url, json))
|
||||
if url.endswith(site_ontology.PUBLISH_PATH):
|
||||
if reject_region and json.get("regionId"):
|
||||
# 실측: region 표에 없는 키 → 외래키 위반 → 500
|
||||
return _response(500, {"statusCode": 500, "message": "Internal server error"}, url)
|
||||
return _response(201, {"merchant": {"external_id": json["externalId"]}, "generation": "skipped"}, url)
|
||||
resolved = {"externalId": json["query"]} if resolve else None
|
||||
return _response(201, {**MATCH, "resolved": resolved}, url)
|
||||
|
||||
return fake_post
|
||||
|
||||
|
||||
async def test_업체를_저장한_뒤_그_업체로_추천을_받는다(ontology_url, monkeypatch):
|
||||
sent = []
|
||||
monkeypatch.setattr(httpx.AsyncClient, "post", _fake_ontology(sent))
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
|
||||
await site_ontology.match_for_merchant(merchant)
|
||||
|
||||
assert [url for url, _ in sent] == ["http://onto.test/v1/merchants/publish", "http://onto.test/v1/match"]
|
||||
# ★ generate:false 가 빠지면 SiteOntology 가 LLM 키워드 생성을 큐에 넣는다.
|
||||
assert sent[0][1] == {**merchant, "generate": False}
|
||||
assert sent[1][1] == {"query": "place-1", "limit": site_ontology.DEFAULT_LIMIT}
|
||||
|
||||
|
||||
async def test_지역_키가_거절되면_지역_없이_다시_보낸다(ontology_url, monkeypatch):
|
||||
sent = []
|
||||
monkeypatch.setattr(httpx.AsyncClient, "post", _fake_ontology(sent, reject_region=True))
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
|
||||
await site_ontology.match_for_merchant(merchant)
|
||||
|
||||
publishes = [body for url, body in sent if url.endswith(site_ontology.PUBLISH_PATH)]
|
||||
assert [b["regionId"] for b in publishes] == ["kr.jeonbuk.gunsan", None]
|
||||
assert sent[-1][0].endswith(site_ontology.MATCH_PATH)
|
||||
|
||||
|
||||
async def test_업체가_해석되지_않은_추천은_쓰지_않는다(ontology_url, monkeypatch):
|
||||
"""검증: match 가 resolved=null 로 201 을 준다(입력 문자열로 검색한 결과).
|
||||
기대결과: 실패로 본다 — 그 결과는 남의 동네 단어다(실측: `나운동 숙소`)."""
|
||||
monkeypatch.setattr(httpx.AsyncClient, "post", _fake_ontology([], resolve=False))
|
||||
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||
|
||||
with pytest.raises(site_ontology.SiteOntologyError):
|
||||
await site_ontology.match_for_merchant(merchant)
|
||||
assert await seo_keywords.fetch("place-1", _snapshot()) is None
|
||||
|
||||
|
||||
async def test_주소가_비면_부르지_않는다(monkeypatch):
|
||||
monkeypatch.setattr(site_ontology.external_api_config, "site_ontology_url", "")
|
||||
|
||||
async def boom(self, url, json=None, **kwargs):
|
||||
raise AssertionError("설정이 비었는데 SiteOntology 를 불렀다")
|
||||
|
||||
monkeypatch.setattr(httpx.AsyncClient, "post", boom)
|
||||
assert await seo_keywords.fetch("place-1", _snapshot()) is None
|
||||
|
||||
|
||||
async def test_연결이_안_되면_예외를_올리지_않는다(ontology_url, monkeypatch):
|
||||
async def refused(self, url, json=None, **kwargs):
|
||||
raise httpx.ConnectError("connection refused", request=httpx.Request("POST", url))
|
||||
|
||||
monkeypatch.setattr(httpx.AsyncClient, "post", refused)
|
||||
assert await seo_keywords.fetch("place-1", _snapshot()) is None
|
||||
|
||||
|
||||
# ── 발행 한 바퀴 ───────────────────────────────────────────────────────────
|
||||
REQUIRED = {
|
||||
"check_in_time": "15:00", "check_out_time": "11:00",
|
||||
"cancel_policy": "이용 7일 전 100% 환불, 3일 전 50% 환불",
|
||||
"cooking_allowed": "true", "pet_allowed": "false",
|
||||
}
|
||||
|
||||
|
||||
async def _published_place(client, h, db_engine):
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "하조대독채", "category": 1})).json()["place"]["place_id"]
|
||||
await client.post(f"/v1/place/{pid}/verify", headers=h, json={
|
||||
"source": 2, "road_address": f"강원특별자치도 양양군 현북면 하조대3길 {uuid.uuid4().hex[:3]}",
|
||||
"phone": "033-672-0000", "latitude": "38.0219217", "longitude": "128.7221449",
|
||||
})
|
||||
for k, v in {**REQUIRED, "intro": "하조대 해변 도보 3분 거리의 독채 펜션입니다.", "facilities": "독채"}.items():
|
||||
await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v})
|
||||
async with db_engine.begin() as c:
|
||||
await c.execute(
|
||||
text("INSERT INTO place_photos (media_id, place_id, url, origin_url, source_type, status, alt_text, label, sort_order) "
|
||||
"VALUES (:m,:p,:u,:u,:s,:st,:a,:l,0)"),
|
||||
{"m": uuid.uuid4(), "p": uuid.UUID(pid), "u": f"https://cdn.test/{uuid.uuid4().hex[:6]}.jpg",
|
||||
"s": SourceType.CRAWL.value, "st": MediaStatus.APPROVED.value, "a": "2층 목조 건물 외관", "l": "외관"},
|
||||
)
|
||||
return pid
|
||||
|
||||
|
||||
async def _build(client, h, pid) -> dict:
|
||||
job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"]
|
||||
assert await Worker("w", JobQueue(), build_handler(), job_deadline_sec=60).process_one() is True
|
||||
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
||||
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
|
||||
return job["result"]
|
||||
|
||||
|
||||
async def test_발행_payload_에_키워드가_실린다(auth_headers, client, db_engine, ontology_url, monkeypatch):
|
||||
"""검증: SiteOntology 가 켜진 채로 숙박 사업장을 발행한다.
|
||||
기대결과: 스냅샷으로 만든 프로필이 나가고, 거른 키워드가 payload.seo 로 실린다."""
|
||||
h = await auth_headers("u1")
|
||||
pid = await _published_place(client, h, db_engine)
|
||||
sent = []
|
||||
|
||||
async def fake_match(merchant, limit=site_ontology.DEFAULT_LIMIT):
|
||||
sent.append(merchant)
|
||||
return {"resolved": {"externalId": merchant["externalId"]},
|
||||
"matches": [_kw("양양 독채펜션", "코어"), _kw("양양 독채 마당 펜션", "롱테일")],
|
||||
"byLane": [{"key": "type", "items": [_kw("양양 독채펜션", "코어")]}]}
|
||||
|
||||
monkeypatch.setattr(site_ontology, "match_for_merchant", fake_match)
|
||||
r = await _build(client, h, pid)
|
||||
|
||||
assert r["published"] is True
|
||||
assert sent[0]["externalId"] == pid
|
||||
assert sent[0]["regionId"] == "kr.gangwon.yangyang"
|
||||
assert "독채" in sent[0]["profile"]["features"]
|
||||
payload = json.loads(open(r["payload_path"], encoding="utf-8").read())
|
||||
assert payload["seo"] == {"keywords": ["양양 독채펜션"], "titleKeyword": "양양 독채펜션"}
|
||||
assert r["seo"] == payload["seo"]
|
||||
|
||||
|
||||
async def test_SiteOntology_가_죽어도_발행된다(auth_headers, client, db_engine, ontology_url, monkeypatch):
|
||||
h = await auth_headers("u1")
|
||||
pid = await _published_place(client, h, db_engine)
|
||||
|
||||
async def down(merchant, limit=site_ontology.DEFAULT_LIMIT):
|
||||
raise site_ontology.SiteOntologyError("ConnectError: connection refused")
|
||||
|
||||
monkeypatch.setattr(site_ontology, "match_for_merchant", down)
|
||||
r = await _build(client, h, pid)
|
||||
|
||||
assert r["published"] is True
|
||||
assert "seo" not in r
|
||||
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()
|
||||
assert site["site"]["status"] == SiteStatus.PUBLISHED.value
|
||||
payload = json.loads(open(r["payload_path"], encoding="utf-8").read())
|
||||
assert "seo" not in payload
|
||||
Reference in new issue
Block a user