작업트리에 커밋되지 않은 채 쌓여 있던 것과, 오늘 찾은 문제 셋을 함께 담는다. ## 1. 콘텐츠 생성 진행 상태 (작업트리에 있던 것) COPY 잡의 실제 단계를 DB에 기록하고 응답으로 내보낸다. 폴링 횟수로 진행률을 흉내 내던 것을 걷어냈다. 새로고침·재접속해도 jobId 로 이어서 본다. - services/copy_steps.py · services/job_progress.py · common/job_errors.py (신규) - postgres-init/migrations/0013_job_progress.sql + init.sql - 프론트: useGenerationJob · generationLabels (신규), Step5Generating·pollJob 배선, orval 모델 갱신(jobProgress · jobStep · jobStepStatus · jobStepReason) - docs/GENERATION_FLOW.md (신규) ## 2. 발행된 사이트만 색인한다 실측(2026-09-15): 디스크의 발행본 33곳 중 **15곳이 draft 인데 `index, follow`** 였고 사이트맵에도 올라가 있었다. 사장님이 발행 버튼을 누른 적 없는 사이트가 짓다 만 상태로 구글에 실려 있었다는 뜻이다. head.ts 가 robots 를 하드코딩하고 payload 의 `site.status` 를 보지 않았다. "색인을 막을 이유가 없다"는 주석은 굽는 것이 곧 발행이던 시절의 말인데, 지금은 빌더 미리보기만 눌러도 draft 로 구워진다. - seo/head.ts: PUBLISHED 일 때만 index, 아니면 `noindex, follow` - 사이트맵·`/s` 목록·llms.txt 에서도 함께 빠진다 — 그쪽은 구운 HTML 의 robots 를 읽어 거른다(seo/directory.ts readBakedNoindex). 규칙을 두 자리에 두지 않으려고 한 곳에 뒀다 ## 3. [새로 크롤링하고 사이트 생성하기] 를 뒤집지 않는다ba90a19의 중복 합치기가 **일부러 다시 만들려는 경우까지** 기존 사업장으로 끌고 갔다 — 새로 만들기를 눌렀는데 기존 에디터가 열린다(사장님 보고 2026-09-15). - Req_VerifyPlaceByUrl.reuse_existing (기본 True — 다른 호출자의 동작은 그대로) - place_service.verify_place_by_url: 끄면 이어붙이지 않는다. 다만 **비어 있는 중복 행은 계속 치운다** — 원래 막으려던 누적이 그것이고 빈 행은 잃을 것이 없다 - ensureServerPlace: 위저드는 새로 만들기 경로에서만 오므로 False 로 보낸다 ## 4. 발행본 파비콘 발행본에 파비콘 링크가 아예 없어 브라우저 탭에 기본 아이콘이 떴다. 파일은 오리진 루트의 공용 자산이라 사이트마다 복사하지 않고 루트 절대경로로 가리킨다. 검증: site vitest 84건 통과 · tsc(site·frontend) · eslint 통과. 백엔드 pytest 는 로컬 DB 비밀번호가 맞지 않아 돌리지 못했다(a5b8701과 같은 자리). 발행본 반영에는 전체 재굽기가 필요하다. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
328 lines
16 KiB
Python
328 lines
16 KiB
Python
"""소개문·FAQ 생성 — COPY 잡이 하는 일.
|
|
|
|
★ LLM 은 사실을 만들지 않는다. 문장만 쓴다.
|
|
- 입력은 **확보된 fact(노출 가능한 것)만**. 미검증 값으로 문장을 쓰면 그 문장도 미검증이다.
|
|
- 생성물은 `ground_check` 를 통과한 것만 저장한다(클라이언트가 이미 걸러 보내지만 근거를 다시 요구한다).
|
|
- 소개문·FAQ 는 **바로 노출값**이다(VERIFIED). 승인 단계를 두지 않는다 — 2026-09-10 결정.
|
|
게이트는 앞에 있다: 입력이 확인된 fact 뿐이고, 근거 없는 FAQ 는 저장조차 하지 않는다.
|
|
확인된 사실로 쓴 문장을 한 번 더 승인받게 하면 같은 사실을 두 번 승인하는 셈이고,
|
|
실제로는 그 화면이 닫힌 뒤에 문장이 도착해 발행본이 영영 빈칸이었다
|
|
(근거·실측: 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 dataclasses import dataclass
|
|
|
|
from common.category_schema import CategorySchema, 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 (
|
|
DBWRType,
|
|
ErrorType,
|
|
FactStatus,
|
|
PlaceCategory,
|
|
SourceType,
|
|
)
|
|
from common.logger import LOG
|
|
from common.models.gmodel import UserInfo
|
|
from common.utils.gtime import GTime
|
|
from config.server_configs import external_api_config
|
|
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 faq_fill, place_research
|
|
from services.external import gemini_text
|
|
from services.fact_service import FactService
|
|
from common.job_errors import PermanentJobError
|
|
|
|
_fact_crud = FactCRUD()
|
|
_faq_crud = FaqCRUD()
|
|
_place_crud = PlaceCRUD()
|
|
|
|
|
|
class CopyAborted(PermanentJobError):
|
|
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""
|
|
|
|
|
|
@dataclass
|
|
class CopyInputs:
|
|
place: places
|
|
schema: CategorySchema
|
|
grounded: list[gemini_text.FactInput]
|
|
records: list[str]
|
|
unit_summaries: list[dict]
|
|
catalog: FaqCatalog | None
|
|
known_fact_keys: set[str]
|
|
|
|
@property
|
|
def ungrounded(self) -> bool:
|
|
return not self.grounded and not self.unit_summaries
|
|
|
|
|
|
async def prepare_copy(place_id: str, owner_user_id: str) -> CopyInputs:
|
|
|
|
err, place = await DB_SESSION_MNG.execute_lambda(
|
|
places.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
|
|
)
|
|
if err != ErrorType.SUCCESS or place is None:
|
|
raise CopyAborted(f"사업장을 찾을 수 없다: {place_id}")
|
|
|
|
try:
|
|
schema = get_schema(PlaceCategory(place.category))
|
|
except (CategorySchemaError, ValueError) as ex:
|
|
raise CopyAborted(f"지원하지 않는 업종: {place.category}") from ex
|
|
|
|
# ★ 노출 가능한 fact 만 근거로 준다. 미검증 값으로 쓴 문장은 그 자체가 미검증이다.
|
|
pid = uuid.UUID(place_id)
|
|
f_err, fact_rows = await DB_SESSION_MNG.execute_lambda(
|
|
place_facts.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: _fact_crud.list_facts(s, pid, None, None, True, True),
|
|
)
|
|
if f_err != ErrorType.SUCCESS:
|
|
raise CopyAborted(f"fact 조회 실패: {f_err.name}")
|
|
|
|
grounded = [
|
|
gemini_text.FactInput(
|
|
key=r.key,
|
|
label=(schema.get(r.key).label if schema.get(r.key) else r.key),
|
|
value=r.value,
|
|
unit=r.unit,
|
|
)
|
|
for r in fact_rows
|
|
if r.unit_id is None and (r.value or "").strip()
|
|
]
|
|
# ★ 수집 원문도 근거로 넘긴다 — fact 가 아니라 place_channels.raw 에 박제된 글이다.
|
|
#
|
|
# 왜 필요한가: 소개 원문(TourAPI overview·네이버 description)에만 있는 정보가 있다.
|
|
# '전면 통창 실내 온수풀', '판교역에서 3분' 같은 것들인데, 이게 근거에 없으면
|
|
# ground_check 가 그 문장을 전부 반려해 소개문·FAQ 가 앙상해진다.
|
|
#
|
|
# 왜 fact 로 넣지 않는가: `intro` 는 allow_llm=True 라 LLM 의 출력 칸이다.
|
|
# 원문을 그 칸에 넣었더니 457자 원문이 발행본의 '숙소 소개' 를 차지했다(2026-08-31).
|
|
# 근거로만 쓰고 저장은 하지 않는다 — 원문은 화면에 나가지 않는다.
|
|
# ★ 확정 링크만 읽던 것을 **조사 근거까지** 읽게 넓혔다(2026-09-10).
|
|
# 업소 조사(`place_research`)는 남이 쓴 글이라 확정하지 않는다 — 공식 채널이 아니므로
|
|
# 발행본의 sameAs·푸터에 나가면 안 된다. 그런데 그것 때문에 여기서도 안 읽혀서,
|
|
# 조사해 온 재료가 소개문에 한 글자도 닿지 않았다. 확정 여부는 "화면에 채널로
|
|
# 내보낼 것인가" 의 판단이지 "근거로 읽을 것인가" 의 판단이 아니다.
|
|
# ★ 다만 아무 미확정 링크나 읽지는 않는다 — raw.kind 가 research 인 것만이다.
|
|
# 미확정 채널 URL 은 동명 업소일 수 있고(그게 확정 절차의 이유다), 조사 근거는
|
|
# 상호 대조를 통과한 것만 적재된다(`grounding/place_research.parse_items`).
|
|
records: list[str] = []
|
|
l_err, link_rows = await DB_SESSION_MNG.execute_lambda(
|
|
place_channels.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: _place_crud.list_links(s, pid, False),
|
|
)
|
|
if l_err == ErrorType.SUCCESS:
|
|
for link in (link_rows or []):
|
|
raw = link.raw if isinstance(link.raw, dict) else {}
|
|
if link.confirmed_at is None and raw.get("kind") != place_research.RAW_KIND:
|
|
continue
|
|
text = (raw.get("text") or "").strip()
|
|
if text:
|
|
# ★ fact 목록이 아니라 records 로 넘긴다. fact 자리에 넣으면 모델이 값 하나로
|
|
# 읽고 거의 쓰지 않는다(prompts/copy.build_prompt 머리주석의 실측).
|
|
records.append(text[:4000])
|
|
# ground_check 는 여전히 이 글을 근거로 인정해야 한다 — 근거 목록에도 남긴다.
|
|
grounded.append(gemini_text.FactInput(
|
|
key=f"source:{link.link_id}", label="수집 원문", value=text[:4000],
|
|
))
|
|
|
|
# 객실·메뉴 요약도 근거로 넘긴다 — "최대 4명" 같은 수치가 통과하려면 근거에 있어야 한다.
|
|
#
|
|
# ★ 근거 없음 판정보다 **먼저** 읽는다.
|
|
# 예전에는 사업장 fact 가 0건이면 여기까지 오지 못하고 되돌아갔다. 그런데 네이버에
|
|
# 요금표만 올라온 모텔은 사업장 fact 가 0건이고 객실 fact 만 있다 — 쓸 근거가 있는데도
|
|
# "근거 없음"으로 끝나 소개문·FAQ 가 영구히 생기지 않았다.
|
|
u_err, unit_rows = await DB_SESSION_MNG.execute_lambda(
|
|
place_units.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: _place_crud.list_units(s, pid),
|
|
)
|
|
unit_summaries = []
|
|
if u_err == ErrorType.SUCCESS:
|
|
by_unit: dict = {}
|
|
for r in fact_rows:
|
|
if r.unit_id and (r.value or "").strip():
|
|
by_unit.setdefault(str(r.unit_id), {})[r.key] = r.value
|
|
unit_summaries = [
|
|
{
|
|
"name": u.name,
|
|
"facts": by_unit.get(str(u.unit_id), {}),
|
|
# 스키마 라벨·단위를 같이 넘긴다 — 이게 없으면 프롬프트에 'weekday_price' 라는
|
|
# 날 key 가 그대로 실려 모델이 그 낱말로 문장을 쓴다.
|
|
"labels": {
|
|
key: {
|
|
"label": schema.get(key).label if schema.get(key) else key,
|
|
"unit": schema.get(key).unit if schema.get(key) else None,
|
|
}
|
|
for key in by_unit.get(str(u.unit_id), {})
|
|
},
|
|
}
|
|
for u in unit_rows
|
|
if by_unit.get(str(u.unit_id))
|
|
]
|
|
|
|
# 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()}
|
|
|
|
return CopyInputs(place, schema, grounded, records, unit_summaries, catalog, known_fact_keys)
|
|
|
|
|
|
async def generate_copy(inputs: CopyInputs) -> gemini_text.GeneratedCopy:
|
|
try:
|
|
return await gemini_text.generate_copy(
|
|
inputs.place.name,
|
|
PlaceCategory(inputs.place.category),
|
|
inputs.grounded,
|
|
unit_summaries=inputs.unit_summaries or None,
|
|
records=inputs.records or None,
|
|
suggested_questions=faq_fill.suggested_questions(inputs.catalog, inputs.known_fact_keys) if inputs.catalog else None,
|
|
max_faqs=faq_fill.FAQ_TARGET,
|
|
model=external_api_config.gemini_text_model,
|
|
)
|
|
except gemini_text.GeminiNotConfigured as ex:
|
|
raise CopyAborted(str(ex)) from ex
|
|
|
|
|
|
async def save_copy(inputs: CopyInputs, copy: gemini_text.GeneratedCopy | None) -> dict:
|
|
pid = inputs.place.place_id
|
|
place_id = str(pid)
|
|
schema = inputs.schema
|
|
now = GTime.UTC()
|
|
stat = {
|
|
"place_id": place_id,
|
|
"grounded_facts": len(inputs.grounded),
|
|
"intro": False,
|
|
"meta": False,
|
|
"faqs": 0,
|
|
"faq_fill": 0, # 목표 수를 채운 문의 안내 문항 수
|
|
# ★ 반려된 문장을 그대로 남긴다 — 소개문이 왜 안 나왔는지 운영자가 알아야 한다.
|
|
"rejected": [list(r) for r in (copy.rejected or [])][:20] if copy else [],
|
|
}
|
|
|
|
if copy is None:
|
|
# 키만 없는 경우에는 기존 생성물을 보존한다.
|
|
if inputs.ungrounded and inputs.catalog is not None:
|
|
await DB_SESSION_MNG.execute_lambda_claim(
|
|
place_faqs.DBType(), lambda s: _faq_crud.expire_generated(s, pid, now),
|
|
)
|
|
return stat
|
|
|
|
actor = UserInfo(
|
|
# ★ 잡이 쓰는 신원. user_id 는 **사업장 주인**이어야 한다 — FactService 가 이 값으로
|
|
# 사업장을 스코프하고(fact_service._load_place) verified_by 에도 그대로 박는다.
|
|
# 회사를 걷어내기 전에는 스코프가 company_id 였고 여기엔 요청자·검증자·랜덤 uuid 가
|
|
# 순서대로 들어갔다. 그 랜덤 uuid 가 이제는 "남의 사업장" 이 되어 조회가 0건이 된다.
|
|
user_id=str(inputs.place.owner_user_id),
|
|
id="generator",
|
|
role=1,
|
|
)
|
|
service = FactService(_fact_crud, _place_crud)
|
|
|
|
# 소개문·메타는 fact 로 들어간다 — FactService 가 allow_llm 을 다시 확인하고(뒷문 없음),
|
|
# LLM 출처라 후보가 아니라 노출값으로 앉힌다(upsert_fact 의 LLM 분기).
|
|
for key, text_value in (("intro", copy.intro), ("meta_description", copy.meta_description)):
|
|
if not (text_value or "").strip():
|
|
continue
|
|
if not (schema.get(key) and schema.get(key).allow_llm):
|
|
# 이 업종 스키마가 LLM 작성을 허용하지 않는 필드다. 조용히 건너뛴다.
|
|
continue
|
|
res = await service.upsert_fact(
|
|
actor, place_id,
|
|
Req_UpsertFact(
|
|
key=key, value=text_value.strip(),
|
|
source_type=SourceType.LLM, source_url=f"gemini:{external_api_config.gemini_text_model}",
|
|
),
|
|
)
|
|
if res.result.success:
|
|
stat["intro" if key == "intro" else "meta"] = True
|
|
else:
|
|
stat["rejected"].append([key, res.result.desc])
|
|
|
|
# 확인 안 된 기존 생성 FAQ 는 내리고 새로 넣는다. 사람이 확인한 FAQ 는 건드리지 않는다.
|
|
await DB_SESSION_MNG.execute_lambda_claim(
|
|
place_faqs.DBType(),
|
|
lambda s: _faq_crud.expire_generated(s, pid, now),
|
|
)
|
|
for order, faq in enumerate(copy.faqs or []):
|
|
if not faq.fact_keys:
|
|
# ★ 근거 없는 FAQ 는 저장하지 않는다.
|
|
stat["rejected"].append([faq.question, "근거 fact 없음"])
|
|
continue
|
|
row = place_faqs(
|
|
place_id=pid,
|
|
question=faq.question,
|
|
answer=faq.answer,
|
|
source_fact_ids=list(faq.fact_keys),
|
|
generated_by=SourceType.LLM.value,
|
|
# ★ 바로 노출한다 (2026-09-10 결정 — fact_service.upsert_fact 주석이 근거).
|
|
# 근거 fact 가 없으면 위에서 이미 버렸으므로, 여기 남은 것은 전부 확인된 사실로 쓴 문장이다.
|
|
status=FactStatus.VERIFIED.value,
|
|
sort_order=order,
|
|
)
|
|
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:
|
|
stat["faqs"] += 1
|
|
|
|
LOG.i(f"[copy] place={place_id} 소개문 {'O' if stat['intro'] else 'X'} · FAQ {stat['faqs']}건 · "
|
|
f"반려 {len(stat['rejected'])}건 (근거 fact {len(inputs.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
|