"""생성 사이트 데모 — 실 DB 에 데이터가 갖춰진 사업장을 만들고 빌드해서 HTML 을 파일로 뽑는다. python scripts/demo_build.py (backend/ 에서 실행) ★ 실 DB(web4ai_db)에 데모 회사·계정·사업장을 만든다. 개발 DB 에서만 쓸 것. """ import asyncio, os, sys, uuid sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) os.environ["APP_ENV"] = "local" from httpx import ASGITransport, AsyncClient from sqlalchemy import text from sqlalchemy.ext.asyncio import create_async_engine from common.enums import FactStatus, MediaStatus, PlaceCategory, SourceType, UserRole, UserStatus from config.server_configs import main_db_config NAME = "핑크비치펜션" PHOTOS = [ ("외관", "https://picsum.photos/seed/pension-out/1200/800", "2층 목조 건물 외관과 앞마당 잔디"), ("A동 침실", "https://picsum.photos/seed/pension-bed/1200/800", "퀸 침대와 창밖으로 바다가 보이는 침실"), ("A동 거실", "https://picsum.photos/seed/pension-liv/1200/800", "소파와 원목 테이블이 있는 거실"), ("바비큐장", "https://picsum.photos/seed/pension-bbq/1200/800", "지붕이 있는 야외 바비큐 공간"), ("B동 복층", "https://picsum.photos/seed/pension-duo/1200/800", "계단으로 이어진 복층 구조의 객실"), ] PLACE_FACTS = { "check_in_time": "15:00", "check_out_time": "11:00", "cancel_policy": "이용 7일 전 100% 환불, 3일 전 50% 환불, 당일 취소 불가", "cooking_allowed": "true", "pet_allowed": "false", "smoking": "false", "parking": "true", "parking_capacity": "6", "wifi": "true", "bbq_available": "true", "bbq_fee": "20000", "breakfast": "false", "reception_hours": "09:00 - 21:00", "intro": "하조대 해변에서 도보 3분 거리에 있는 2개 동 규모의 펜션입니다. 모든 객실에서 바다가 보이며, 취사가 가능하고 야외 바비큐 공간을 갖추고 있습니다.", } UNITS = { "A동 스탠다드": {"room_type": "스탠다드", "standard_capacity": "2", "max_capacity": "4", "bed_type": "퀸 1", "has_kitchen": "true", "view": "오션뷰", "weekday_price": "150000"}, "B동 복층": {"room_type": "복층", "standard_capacity": "4", "max_capacity": "6", "bed_type": "퀸 1 + 싱글 2", "has_kitchen": "true", "view": "오션뷰", "weekday_price": "220000"}, } FAQS = [ ("체크인·체크아웃은 몇 시인가요?", "체크인은 15:00, 체크아웃은 11:00 입니다.", ["check_in_time", "check_out_time"]), ("반려동물과 함께 갈 수 있나요?", "반려동물 동반은 불가합니다.", ["pet_allowed"]), ("객실에서 취사가 가능한가요?", "취사가 가능하며 모든 객실에 주방이 있습니다.", ["cooking_allowed", "has_kitchen"]), ("바비큐를 이용하려면 얼마인가요?", "바비큐 이용료는 20,000원입니다.", ["bbq_available", "bbq_fee"]), ("주차는 가능한가요?", "주차가 가능하며 6대까지 주차할 수 있습니다.", ["parking", "parking_capacity"]), ] async def main(): pw = f":{main_db_config.write_pw}" if main_db_config.write_pw else "" dsn = f"postgresql+asyncpg://{main_db_config.write_id}{pw}@{main_db_config.write_host}:{main_db_config.write_port}/{main_db_config.name}" engine = create_async_engine(dsn) from router.v1.validator.dependencies import GetHashedPW uid, login = uuid.uuid4(), f"demo{uuid.uuid4().hex[:6]}" async with engine.begin() as c: await c.execute(text("INSERT INTO company.users (user_id,id,password,name,status,role,last_accessed_at) " "VALUES (:u,:i,:p,:n,:s,:r,now())"), {"u": uid, "i": login, "p": await GetHashedPW("pw1234"), "n": "데모", "s": UserStatus.ACTIVE.value, "r": UserRole.OWNER.value}) from router.router import app async with AsyncClient(transport=ASGITransport(app=app), base_url="http://demo") as cl: tok = (await cl.post("/v1/auth/login", json={"id": login, "password": "pw1234"})).json()["access_token"] h = {"Authorization": f"Bearer {tok}"} pid = (await cl.post("/v1/place", headers=h, json={"name": NAME, "category": PlaceCategory.LODGING.value})).json()["place"]["place_id"] await cl.post(f"/v1/place/{pid}/verify", headers=h, json={ "source": 2, "road_address": "강원특별자치도 양양군 현북면 하조대3길 11", "phone": "033-672-0000", "latitude": "38.0219217", "longitude": "128.7221449"}) print(f"사업장 등록·검증 완료 place_id={pid}") for k, v in PLACE_FACTS.items(): await cl.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v}) unit_ids = {} for order, (name, kv) in enumerate(UNITS.items()): u = (await cl.post(f"/v1/place/{pid}/unit", headers=h, json={"name": name, "sort_order": order})).json()["unit"] unit_ids[name] = u["unit_id"] for k, v in kv.items(): await cl.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v, "unit_id": u["unit_id"]}) async with engine.begin() as c: for order, (label, url, alt) in enumerate(PHOTOS): unit_id = None for n, i in unit_ids.items(): if label.startswith(n.split()[0]): unit_id = uuid.UUID(i) await c.execute( text("INSERT INTO place.media (media_id,place_id,unit_id,url,origin_url,source_type,status,label,alt_text,sort_order) " "VALUES (:m,:p,:u,:url,:url,:s,:st,:l,:a,:o)"), {"m": uuid.uuid4(), "p": uuid.UUID(pid), "u": unit_id, "url": url, "s": SourceType.OWNER.value, "st": MediaStatus.APPROVED.value, "l": label, "a": alt, "o": order}, ) for order, (q, a, keys) in enumerate(FAQS): await c.execute( text("INSERT INTO fact.faqs (faq_id,place_id,question,answer,source_fact_ids,generated_by,status,sort_order) " "VALUES (:f,:p,:q,:a,CAST(:k AS jsonb),:g,:st,:o)"), {"f": uuid.uuid4(), "p": uuid.UUID(pid), "q": q, "a": a, "k": __import__("json").dumps(keys), "g": SourceType.LLM.value, "st": FactStatus.VERIFIED.value, "o": order}, ) print(f"fact {len(PLACE_FACTS)}건 · 객실 {len(UNITS)}개 · 사진 {len(PHOTOS)}장 · FAQ {len(FAQS)}건 적재") job_id = (await cl.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"] from crud.job_crud import JobQueue from worker.handlers import build_handler from worker.runner import Worker await Worker("demo", JobQueue(), build_handler(), job_deadline_sec=120).process_one() job = (await cl.get(f"/v1/job/{job_id}", headers=h)).json()["job"] r = job.get("result") or {} print(f"\n빌드: {r.get('build_status')} · 게이트 {'통과' if r.get('gate',{}).get('passed') else '거부'}" f" · 고유콘텐츠 {r.get('unique_content_count')}건 · 발행 {r.get('published')}") if not r.get("gate", {}).get("passed"): print("게이트 사유:", r.get("gate")) return # ★ HTML 은 백엔드가 만들지 않는다. payload JSON 을 쓰는 것까지가 백엔드의 일이고, # 그걸 정적 페이지로 굽는 것은 solution/site 의 렌더러다(그게 방문자가 보는 유일한 페이지). print(f"\npayload: {r.get('payload_path')}") print(f"페이지: {r.get('routes')}개 · JSON-LD 노드 {len(r.get('mismatches') or []) == 0 and '검증 통과' or '불일치'}") print("정적 파일: solution/site/out/s// (렌더러가 굽는다)") await engine.dispose() asyncio.run(main())