Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04d8614919 | ||
|
|
8415e1c3a7 | ||
|
|
b908408b4a | ||
|
|
009b1a5d09 | ||
|
|
d1fe7fcd5f | ||
|
|
bea0fa0684 | ||
|
|
997927d42a |
No files matched your search
@@ -2,7 +2,9 @@ import json
|
|||||||
import time
|
import time
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional
|
from typing import Literal, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
from urllib.parse import unquote, urlparse
|
from urllib.parse import unquote, urlparse
|
||||||
|
|
||||||
import aiofiles
|
import aiofiles
|
||||||
@@ -48,18 +50,19 @@ router = APIRouter()
|
|||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/search/accommodation",
|
"/search/accommodation",
|
||||||
summary="숙박/펜션 자동완성 검색",
|
summary="장소 자동완성 검색 (숙박/음식점 등)",
|
||||||
description="""
|
description="""
|
||||||
네이버 지역 검색 API를 이용한 숙박/펜션 자동완성 검색입니다.
|
네이버 지역 검색 API를 이용한 장소 자동완성 검색입니다.
|
||||||
|
|
||||||
## 요청 파라미터
|
## 요청 파라미터
|
||||||
- **query**: 검색어 (필수)
|
- **query**: 검색어 (필수)
|
||||||
|
- **category**: 카테고리
|
||||||
|
|
||||||
## 반환 정보
|
## 반환 정보
|
||||||
- **query**: 검색어
|
- **query**: 검색어
|
||||||
- **count**: 검색 결과 수 (최대 10개)
|
- **count**: 검색 결과 수 (최대 10개)
|
||||||
- **items**: 검색 결과 목록
|
- **items**: 검색 결과 목록
|
||||||
- **title**: 숙소명 (HTML 태그 포함 가능)
|
- **title**: 장소명 (HTML 태그 포함 가능)
|
||||||
- **address**: 지번 주소
|
- **address**: 지번 주소
|
||||||
- **roadAddress**: 도로명 주소
|
- **roadAddress**: 도로명 주소
|
||||||
""",
|
""",
|
||||||
@@ -72,7 +75,7 @@ router = APIRouter()
|
|||||||
async def search_accommodation(
|
async def search_accommodation(
|
||||||
query: str,
|
query: str,
|
||||||
) -> AccommodationSearchResponse:
|
) -> AccommodationSearchResponse:
|
||||||
"""숙박/펜션 자동완성 검색"""
|
"""장소 자동완성 검색"""
|
||||||
results = await naver_search_client.search_accommodation(
|
results = await naver_search_client.search_accommodation(
|
||||||
query=query,
|
query=query,
|
||||||
display=10,
|
display=10,
|
||||||
@@ -91,6 +94,44 @@ def _extract_region_from_address(road_address: str | None, jibun_address: str |
|
|||||||
return extract_region_from_address(road_address, jibun_address)
|
return extract_region_from_address(road_address, jibun_address)
|
||||||
|
|
||||||
|
|
||||||
|
class _IndustryOutput(BaseModel):
|
||||||
|
industry: Literal["stay", "restaurant", "cafe", "salon", "clinic", "fitness", "academy", "attraction"]
|
||||||
|
|
||||||
|
|
||||||
|
async def _resolve_industry(category: str, customer_name: str = "") -> str:
|
||||||
|
"""업체를 통합 프롬프트의 8개 industry enum 중 하나로 AI 분류.
|
||||||
|
|
||||||
|
분류 근거는 카테고리를 우선 사용하고, 카테고리가 없으면 업체명으로 분류한다.
|
||||||
|
근거가 둘 다 없거나 분류 실패 시 빈 문자열 반환(프롬프트가 범용 처리).
|
||||||
|
"""
|
||||||
|
if category:
|
||||||
|
basis_label, basis_value = "네이버 지도 카테고리", category
|
||||||
|
elif customer_name:
|
||||||
|
basis_label, basis_value = "업체명", customer_name
|
||||||
|
else:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
chatgpt = ChatgptService()
|
||||||
|
prompt = (
|
||||||
|
f"{basis_label}: '{basis_value}'\n"
|
||||||
|
"위 정보를 바탕으로 이 업체를 다음 8개 업종 중 가장 적합한 하나로 분류하세요: "
|
||||||
|
"stay(숙박/펜션/호텔), restaurant(음식점), cafe(카페/디저트), "
|
||||||
|
"salon(미용실/네일/뷰티), clinic(병원/의원/치과), fitness(헬스/필라테스/요가), "
|
||||||
|
"academy(학원/교습소), attraction(관광/체험/액티비티)."
|
||||||
|
)
|
||||||
|
result = await chatgpt._call_pydantic_output_chat_completion(
|
||||||
|
prompt=prompt,
|
||||||
|
output_format=_IndustryOutput,
|
||||||
|
model="gpt-4o-mini",
|
||||||
|
img_url=None,
|
||||||
|
image_detail_high=False,
|
||||||
|
)
|
||||||
|
return result.industry
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[industry] AI 분류 실패, 빈 값 반환: {e}")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
"/crawling",
|
"/crawling",
|
||||||
summary="네이버 지도 크롤링",
|
summary="네이버 지도 크롤링",
|
||||||
@@ -222,17 +263,21 @@ async def _crawling_logic(
|
|||||||
road_address = scraper.base_info.get("roadAddress", "")
|
road_address = scraper.base_info.get("roadAddress", "")
|
||||||
jibun_address = scraper.base_info.get("address", "")
|
jibun_address = scraper.base_info.get("address", "")
|
||||||
customer_name = scraper.base_info.get("name", "")
|
customer_name = scraper.base_info.get("name", "")
|
||||||
|
category = scraper.base_info.get("category", "")
|
||||||
region = _extract_region_from_address(road_address, jibun_address)
|
region = _extract_region_from_address(road_address, jibun_address)
|
||||||
|
industry = await _resolve_industry(category, customer_name)
|
||||||
|
|
||||||
processed_info = ProcessedInfo(
|
processed_info = ProcessedInfo(
|
||||||
customer_name=customer_name,
|
customer_name=customer_name,
|
||||||
region=region,
|
region=region,
|
||||||
detail_region_info=road_address or jibun_address or "",
|
detail_region_info=road_address or jibun_address or "",
|
||||||
|
industry=industry,
|
||||||
)
|
)
|
||||||
|
|
||||||
step2_elapsed = (time.perf_counter() - step2_start) * 1000
|
step2_elapsed = (time.perf_counter() - step2_start) * 1000
|
||||||
logger.info(
|
logger.info(
|
||||||
f"[crawling] Step 2 완료 - {customer_name}, {region} ({step2_elapsed:.1f}ms)"
|
f"[crawling] Step 2 완료 - {customer_name}, {region}, "
|
||||||
|
f"category={category!r}, place_type={scraper.place_type!r}, industry={industry!r} ({step2_elapsed:.1f}ms)"
|
||||||
)
|
)
|
||||||
|
|
||||||
# ========== Step 3: ChatGPT 마케팅 분석 ==========
|
# ========== Step 3: ChatGPT 마케팅 분석 ==========
|
||||||
@@ -246,6 +291,7 @@ async def _crawling_logic(
|
|||||||
"customer_name": customer_name,
|
"customer_name": customer_name,
|
||||||
"region": region,
|
"region": region,
|
||||||
"detail_region_info": road_address or "",
|
"detail_region_info": road_address or "",
|
||||||
|
"industry": industry, # 통합 프롬프트 내부 분기용 업종 enum
|
||||||
}
|
}
|
||||||
|
|
||||||
# Step 3-2: GPT API 호출 → 구조화된 마케팅 분석 결과 반환
|
# Step 3-2: GPT API 호출 → 구조화된 마케팅 분석 결과 반환
|
||||||
@@ -253,7 +299,7 @@ async def _crawling_logic(
|
|||||||
marketing_prompt, input_marketing_data
|
marketing_prompt, input_marketing_data
|
||||||
)
|
)
|
||||||
|
|
||||||
# Step 3-3: 분석 결과 DB 저장
|
# Step 3-3: 분석 결과 DB 저장 (industry는 Project로 흐르므로 여기엔 미저장)
|
||||||
marketing_intel = MarketingIntel(
|
marketing_intel = MarketingIntel(
|
||||||
place_id=scraper.place_id,
|
place_id=scraper.place_id,
|
||||||
intel_result=marketing_analysis.model_dump(),
|
intel_result=marketing_analysis.model_dump(),
|
||||||
@@ -308,7 +354,8 @@ async def _crawling_logic(
|
|||||||
"image_count": len(scraper.image_link_list) if scraper.image_link_list else 0,
|
"image_count": len(scraper.image_link_list) if scraper.image_link_list else 0,
|
||||||
"processed_info": processed_info,
|
"processed_info": processed_info,
|
||||||
"marketing_analysis": marketing_analysis,
|
"marketing_analysis": marketing_analysis,
|
||||||
"m_id" : m_id
|
"m_id": m_id,
|
||||||
|
"industry": industry if 'industry' in locals() else "",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -346,10 +393,16 @@ async def manual_marketing(
|
|||||||
# Step 2: GPT API 호출 → 마케팅 분석 결과 생성
|
# Step 2: GPT API 호출 → 마케팅 분석 결과 생성
|
||||||
# place_id 없이 업체명+주소만으로 분석 (크롤링 없이 직접 입력된 경우)
|
# place_id 없이 업체명+주소만으로 분석 (크롤링 없이 직접 입력된 경우)
|
||||||
chatgpt_service = ChatgptService()
|
chatgpt_service = ChatgptService()
|
||||||
|
# 요청에 industry가 있으면 사용, 없으면 업체명 기반 AI 분류
|
||||||
|
industry = request_body.industry or await _resolve_industry(
|
||||||
|
"", request_body.store_name
|
||||||
|
)
|
||||||
|
processed_info.industry = industry
|
||||||
input_marketing_data = {
|
input_marketing_data = {
|
||||||
"customer_name": request_body.store_name,
|
"customer_name": request_body.store_name,
|
||||||
"region": region,
|
"region": region,
|
||||||
"detail_region_info": request_body.address,
|
"detail_region_info": request_body.address,
|
||||||
|
"industry": industry, # 통합 프롬프트 내부 분기용 업종 enum
|
||||||
}
|
}
|
||||||
marketing_analysis = await chatgpt_service.generate_structured_output(
|
marketing_analysis = await chatgpt_service.generate_structured_output(
|
||||||
marketing_prompt, input_marketing_data
|
marketing_prompt, input_marketing_data
|
||||||
@@ -386,6 +439,7 @@ async def manual_marketing(
|
|||||||
processed_info=processed_info,
|
processed_info=processed_info,
|
||||||
marketing_analysis=marketing_analysis,
|
marketing_analysis=marketing_analysis,
|
||||||
m_id=m_id,
|
m_id=m_id,
|
||||||
|
industry=industry,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -114,6 +114,13 @@ class Project(Base):
|
|||||||
comment="마케팅 인텔리전스 결과 정보 저장",
|
comment="마케팅 인텔리전스 결과 정보 저장",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
industry: Mapped[str] = mapped_column(
|
||||||
|
String(50),
|
||||||
|
nullable=True,
|
||||||
|
default="",
|
||||||
|
comment="업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction)",
|
||||||
|
)
|
||||||
|
|
||||||
language: Mapped[str] = mapped_column(
|
language: Mapped[str] = mapped_column(
|
||||||
String(50),
|
String(50),
|
||||||
nullable=False,
|
nullable=False,
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ class ProcessedInfo(BaseModel):
|
|||||||
customer_name: str = Field(..., description="고객명/가게명 (base_info.name)")
|
customer_name: str = Field(..., description="고객명/가게명 (base_info.name)")
|
||||||
region: str = Field(..., description="지역명 (roadAddress에서 추출한 시 이름)")
|
region: str = Field(..., description="지역명 (roadAddress에서 추출한 시 이름)")
|
||||||
detail_region_info: str = Field(..., description="상세 지역 정보 (roadAddress)")
|
detail_region_info: str = Field(..., description="상세 지역 정보 (roadAddress)")
|
||||||
|
industry: str = Field(default="", description="업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction)")
|
||||||
|
|
||||||
|
|
||||||
# class MarketingAnalysisDetail(BaseModel):
|
# class MarketingAnalysisDetail(BaseModel):
|
||||||
@@ -242,6 +243,7 @@ class CrawlingResponse(BaseModel):
|
|||||||
None, description="마케팅 분석 결과 . 실패 시 null"
|
None, description="마케팅 분석 결과 . 실패 시 null"
|
||||||
)
|
)
|
||||||
m_id : int = Field(..., description="마케팅 분석 결과 ID")
|
m_id : int = Field(..., description="마케팅 분석 결과 ID")
|
||||||
|
industry: str = Field(default="", description="업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction)")
|
||||||
|
|
||||||
|
|
||||||
class ManualMarketingRequest(BaseModel):
|
class ManualMarketingRequest(BaseModel):
|
||||||
@@ -258,6 +260,7 @@ class ManualMarketingRequest(BaseModel):
|
|||||||
|
|
||||||
store_name: str = Field(..., description="업체명 / 브랜드명")
|
store_name: str = Field(..., description="업체명 / 브랜드명")
|
||||||
address: str = Field(..., description="도로명 또는 지번 주소")
|
address: str = Field(..., description="도로명 또는 지번 주소")
|
||||||
|
industry: str = Field(default="", description="업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 비우면 업체명 기반 AI 분류")
|
||||||
|
|
||||||
|
|
||||||
class ErrorResponse(BaseModel):
|
class ErrorResponse(BaseModel):
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ class NaverSearchClient:
|
|||||||
display: int = 5,
|
display: int = 5,
|
||||||
) -> List[dict]:
|
) -> List[dict]:
|
||||||
"""
|
"""
|
||||||
숙박/펜션 검색
|
장소 검색 (숙박, 음식점 등)
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
query: 검색어
|
query: 검색어
|
||||||
@@ -41,8 +41,7 @@ class NaverSearchClient:
|
|||||||
Returns:
|
Returns:
|
||||||
검색 결과 리스트 (address, roadAddress, title)
|
검색 결과 리스트 (address, roadAddress, title)
|
||||||
"""
|
"""
|
||||||
# 숙박/펜션 카테고리 검색을 위해 쿼리에 키워드 추가
|
search_query = query
|
||||||
search_query = f"{query} 숙박"
|
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
"X-Naver-Client-Id": self.client_id,
|
"X-Naver-Client-Id": self.client_id,
|
||||||
|
|||||||
@@ -268,7 +268,7 @@ async def generate_lyric(
|
|||||||
# ========== Step 1: ChatGPT 서비스 초기화 및 프롬프트 생성 ==========
|
# ========== Step 1: ChatGPT 서비스 초기화 및 프롬프트 생성 ==========
|
||||||
step1_start = time.perf_counter()
|
step1_start = time.perf_counter()
|
||||||
logger.debug(f"[generate_lyric] Step 1: 서비스 초기화 및 프롬프트 생성...")
|
logger.debug(f"[generate_lyric] Step 1: 서비스 초기화 및 프롬프트 생성...")
|
||||||
|
|
||||||
timing_rules = {
|
timing_rules = {
|
||||||
"60s" : """
|
"60s" : """
|
||||||
8–12 lines
|
8–12 lines
|
||||||
@@ -286,8 +286,12 @@ async def generate_lyric(
|
|||||||
"marketing_intelligence_summary" : json.dumps(marketing_intel.intel_result, ensure_ascii = False),
|
"marketing_intelligence_summary" : json.dumps(marketing_intel.intel_result, ensure_ascii = False),
|
||||||
"language" : request_body.language,
|
"language" : request_body.language,
|
||||||
"timing_rules" : timing_rules["60s"], # 아직은 선택지 하나
|
"timing_rules" : timing_rules["60s"], # 아직은 선택지 하나
|
||||||
|
"industry": request_body.industry, # 크롤 응답에서 받아 전달된 업종 enum
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# 업종 분기는 프롬프트 내부 {industry}로 처리하므로 단일 프롬프트 사용
|
||||||
|
selected_lyric_prompt = lyric_prompt
|
||||||
|
|
||||||
step1_elapsed = (time.perf_counter() - step1_start) * 1000
|
step1_elapsed = (time.perf_counter() - step1_start) * 1000
|
||||||
#logger.debug(f"[generate_lyric] Step 1 완료 - 프롬프트 {len(prompt)}자 ({step1_elapsed:.1f}ms)")
|
#logger.debug(f"[generate_lyric] Step 1 완료 - 프롬프트 {len(prompt)}자 ({step1_elapsed:.1f}ms)")
|
||||||
|
|
||||||
@@ -313,7 +317,8 @@ async def generate_lyric(
|
|||||||
detail_region_info=request_body.detail_region_info,
|
detail_region_info=request_body.detail_region_info,
|
||||||
language=request_body.language,
|
language=request_body.language,
|
||||||
user_uuid=current_user.user_uuid,
|
user_uuid=current_user.user_uuid,
|
||||||
marketing_intelligence = request_body.m_id
|
marketing_intelligence=request_body.m_id,
|
||||||
|
industry=request_body.industry,
|
||||||
)
|
)
|
||||||
session.add(project)
|
session.add(project)
|
||||||
await session.commit()
|
await session.commit()
|
||||||
@@ -327,7 +332,7 @@ async def generate_lyric(
|
|||||||
step3_start = time.perf_counter()
|
step3_start = time.perf_counter()
|
||||||
logger.debug(f"[generate_lyric] Step 3: Lyric 저장 (processing)...")
|
logger.debug(f"[generate_lyric] Step 3: Lyric 저장 (processing)...")
|
||||||
|
|
||||||
estimated_prompt = lyric_prompt.build_prompt(lyric_input_data)
|
estimated_prompt = selected_lyric_prompt.build_prompt(lyric_input_data)
|
||||||
lyric = Lyric(
|
lyric = Lyric(
|
||||||
project_id=project.id,
|
project_id=project.id,
|
||||||
task_id=task_id,
|
task_id=task_id,
|
||||||
@@ -358,7 +363,7 @@ async def generate_lyric(
|
|||||||
background_tasks.add_task(
|
background_tasks.add_task(
|
||||||
generate_lyric_background,
|
generate_lyric_background,
|
||||||
task_id=task_id,
|
task_id=task_id,
|
||||||
prompt=lyric_prompt,
|
prompt=selected_lyric_prompt,
|
||||||
lyric_input_data=lyric_input_data,
|
lyric_input_data=lyric_input_data,
|
||||||
lyric_id=lyric.id,
|
lyric_id=lyric.id,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -76,6 +76,7 @@ class GenerateLyricRequest(BaseModel):
|
|||||||
description="영상 방향 (horizontal: 가로형, vertical: 세로형)",
|
description="영상 방향 (horizontal: 가로형, vertical: 세로형)",
|
||||||
),
|
),
|
||||||
m_id : Optional[int] = Field(None, description="마케팅 인텔리전스 ID 값")
|
m_id : Optional[int] = Field(None, description="마케팅 인텔리전스 ID 값")
|
||||||
|
industry: str = Field(default="", description="업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction)")
|
||||||
instrumental: bool = Field(default=False, description="BGM 전용 모드 (가사 생성 안 함)")
|
instrumental: bool = Field(default=False, description="BGM 전용 모드 (가사 생성 안 함)")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -186,13 +186,16 @@ async def generate_subtitle_background(
|
|||||||
|
|
||||||
store_address = project.detail_region_info
|
store_address = project.detail_region_info
|
||||||
customer_name = project.store_name
|
customer_name = project.store_name
|
||||||
logger.info(f"[generate_subtitle_background] customer_name: {customer_name}, store_address: {store_address}")
|
language = project.language or "Korean"
|
||||||
|
logger.info(f"[generate_subtitle_background] customer_name: {customer_name}, store_address: {store_address}, language: {language}")
|
||||||
|
|
||||||
generated_subtitles = await subtitle_generator.generate_subtitle_contents(
|
generated_subtitles = await subtitle_generator.generate_subtitle_contents(
|
||||||
marketing_intelligence=marketing_intelligence.intel_result,
|
marketing_intelligence=marketing_intelligence.intel_result,
|
||||||
pitching_label_list=pitchings,
|
pitching_label_list=pitchings,
|
||||||
customer_name=customer_name,
|
customer_name=customer_name,
|
||||||
detail_region_info=store_address,
|
detail_region_info=store_address,
|
||||||
|
language=language,
|
||||||
|
industry=project.industry,
|
||||||
)
|
)
|
||||||
pitching_output_list = generated_subtitles.pitching_results
|
pitching_output_list = generated_subtitles.pitching_results
|
||||||
|
|
||||||
|
|||||||
@@ -56,6 +56,8 @@ class SocialUploadResponse(BaseModel):
|
|||||||
platform: str = Field(..., description="플랫폼명")
|
platform: str = Field(..., description="플랫폼명")
|
||||||
status: str = Field(..., description="업로드 상태")
|
status: str = Field(..., description="업로드 상태")
|
||||||
message: str = Field(..., description="응답 메시지")
|
message: str = Field(..., description="응답 메시지")
|
||||||
|
scheduled_at: Optional[datetime] = Field(None, description="예약 시간 (예약 업로드 충돌 시 반환)")
|
||||||
|
|
||||||
|
|
||||||
model_config = ConfigDict(
|
model_config = ConfigDict(
|
||||||
json_schema_extra={
|
json_schema_extra={
|
||||||
@@ -65,6 +67,7 @@ class SocialUploadResponse(BaseModel):
|
|||||||
"platform": "youtube",
|
"platform": "youtube",
|
||||||
"status": "pending",
|
"status": "pending",
|
||||||
"message": "업로드 요청이 접수되었습니다.",
|
"message": "업로드 요청이 접수되었습니다.",
|
||||||
|
"scheduled_at": "2026-02-02T15:00:00",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -94,8 +94,10 @@ class SeoService:
|
|||||||
),
|
),
|
||||||
"language": project.language,
|
"language": project.language,
|
||||||
"target_keywords": hashtags,
|
"target_keywords": hashtags,
|
||||||
|
"industry": project.industry or "", # 크롤 시 분류해 Project에 저장한 업종 enum
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# 업종 분기는 프롬프트 내부 {industry}로 처리하므로 단일 프롬프트 사용
|
||||||
chatgpt = ChatgptService(timeout=180)
|
chatgpt = ChatgptService(timeout=180)
|
||||||
yt_seo_output = await chatgpt.generate_structured_output(yt_upload_prompt, yt_seo_input_data)
|
yt_seo_output = await chatgpt.generate_structured_output(yt_upload_prompt, yt_seo_input_data)
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from datetime import datetime
|
|||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from fastapi import BackgroundTasks, HTTPException, status
|
from fastapi import BackgroundTasks, HTTPException, status
|
||||||
from sqlalchemy import func, select
|
from sqlalchemy import func, or_, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from config import TIMEZONE
|
from config import TIMEZONE
|
||||||
@@ -90,12 +90,19 @@ class SocialUploadService:
|
|||||||
)
|
)
|
||||||
raise SocialAccountNotFoundError()
|
raise SocialAccountNotFoundError()
|
||||||
|
|
||||||
# 3. 진행 중인 업로드 확인 (pending 또는 uploading 상태만)
|
# 3. 중복 업로드 확인
|
||||||
|
now_kst_naive = datetime.now(TIMEZONE).replace(tzinfo=None)
|
||||||
|
|
||||||
|
# 3-1. 진행 중인 업로드 확인 (즉시 pending 또는 uploading)
|
||||||
in_progress_result = await session.execute(
|
in_progress_result = await session.execute(
|
||||||
select(SocialUpload).where(
|
select(SocialUpload).where(
|
||||||
SocialUpload.video_id == body.video_id,
|
SocialUpload.video_id == body.video_id,
|
||||||
SocialUpload.social_account_id == account.id,
|
SocialUpload.social_account_id == account.id,
|
||||||
SocialUpload.status.in_([UploadStatus.PENDING.value, UploadStatus.UPLOADING.value]),
|
SocialUpload.status.in_([UploadStatus.PENDING.value, UploadStatus.UPLOADING.value]),
|
||||||
|
or_(
|
||||||
|
SocialUpload.scheduled_at.is_(None),
|
||||||
|
SocialUpload.scheduled_at <= now_kst_naive,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
in_progress_upload = in_progress_result.scalar_one_or_none()
|
in_progress_upload = in_progress_result.scalar_one_or_none()
|
||||||
@@ -112,6 +119,32 @@ class SocialUploadService:
|
|||||||
message="이미 업로드가 진행 중입니다.",
|
message="이미 업로드가 진행 중입니다.",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 3-2. 미래 예약 업로드 확인
|
||||||
|
scheduled_result = await session.execute(
|
||||||
|
select(SocialUpload).where(
|
||||||
|
SocialUpload.video_id == body.video_id,
|
||||||
|
SocialUpload.social_account_id == account.id,
|
||||||
|
SocialUpload.status == UploadStatus.PENDING.value,
|
||||||
|
SocialUpload.scheduled_at.isnot(None),
|
||||||
|
SocialUpload.scheduled_at > now_kst_naive,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
scheduled_upload = scheduled_result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if scheduled_upload:
|
||||||
|
logger.info(
|
||||||
|
f"[UPLOAD_SERVICE] 예약된 업로드 존재 - "
|
||||||
|
f"upload_id: {scheduled_upload.id}, scheduled_at: {scheduled_upload.scheduled_at}"
|
||||||
|
)
|
||||||
|
return SocialUploadResponse(
|
||||||
|
success=False,
|
||||||
|
upload_id=scheduled_upload.id,
|
||||||
|
platform=account.platform,
|
||||||
|
status=scheduled_upload.status,
|
||||||
|
message="이미 예약된 업로드가 있습니다.",
|
||||||
|
scheduled_at=scheduled_upload.scheduled_at,
|
||||||
|
)
|
||||||
|
|
||||||
# 4. 업로드 순번 계산
|
# 4. 업로드 순번 계산
|
||||||
max_seq_result = await session.execute(
|
max_seq_result = await session.execute(
|
||||||
select(func.coalesce(func.max(SocialUpload.upload_seq), 0)).where(
|
select(func.coalesce(func.max(SocialUpload.upload_seq), 0)).where(
|
||||||
@@ -153,7 +186,6 @@ class SocialUploadService:
|
|||||||
)
|
)
|
||||||
|
|
||||||
# 6. 즉시 업로드이면 백그라운드 태스크 등록
|
# 6. 즉시 업로드이면 백그라운드 태스크 등록
|
||||||
now_kst_naive = datetime.now(TIMEZONE).replace(tzinfo=None)
|
|
||||||
is_scheduled = body.scheduled_at and body.scheduled_at > now_kst_naive
|
is_scheduled = body.scheduled_at and body.scheduled_at > now_kst_naive
|
||||||
if not is_scheduled:
|
if not is_scheduled:
|
||||||
background_tasks.add_task(process_social_upload, social_upload.id)
|
background_tasks.add_task(process_social_upload, social_upload.id)
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ class YouTubeUploader(BaseSocialUploader):
|
|||||||
body = {
|
body = {
|
||||||
"snippet": {
|
"snippet": {
|
||||||
"title": metadata.title,
|
"title": metadata.title,
|
||||||
"description": metadata.description or "",
|
"description": self._sanitize_description(metadata.description),
|
||||||
"tags": metadata.tags or [],
|
"tags": metadata.tags or [],
|
||||||
"categoryId": self._get_category_id(metadata),
|
"categoryId": self._get_category_id(metadata),
|
||||||
},
|
},
|
||||||
@@ -380,6 +380,12 @@ class YouTubeUploader(BaseSocialUploader):
|
|||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def _sanitize_description(self, description: str | None) -> str:
|
||||||
|
"""YouTube API가 거부하는 문자를 제거합니다. (<, > 포함 시 invalidVideoDescription 오류 발생)"""
|
||||||
|
if not description:
|
||||||
|
return ""
|
||||||
|
return description.replace("<", "").replace(">", "")
|
||||||
|
|
||||||
def _convert_privacy_status(self, privacy_status: PrivacyStatus) -> str:
|
def _convert_privacy_status(self, privacy_status: PrivacyStatus) -> str:
|
||||||
"""
|
"""
|
||||||
PrivacyStatus를 YouTube API 형식으로 변환
|
PrivacyStatus를 YouTube API 형식으로 변환
|
||||||
|
|||||||
@@ -1,3 +1,15 @@
|
|||||||
|
# 특별시/광역시/세종시: 하위 행정구역이 구(gu)이므로 별도 처리
|
||||||
|
METRO_SIDOS: dict[str, str] = {
|
||||||
|
"서울특별시": "서울시",
|
||||||
|
"부산광역시": "부산시",
|
||||||
|
"대구광역시": "대구시",
|
||||||
|
"인천광역시": "인천시",
|
||||||
|
"광주광역시": "광주시",
|
||||||
|
"대전광역시": "대전시",
|
||||||
|
"울산광역시": "울산시",
|
||||||
|
"세종특별시": "세종시",
|
||||||
|
}
|
||||||
|
|
||||||
SIDO_CITIES: dict[str, list[str]] = {
|
SIDO_CITIES: dict[str, list[str]] = {
|
||||||
"서울특별시": ["서울시"],
|
"서울특별시": ["서울시"],
|
||||||
"부산광역시": ["부산시"],
|
"부산광역시": ["부산시"],
|
||||||
@@ -61,6 +73,12 @@ def extract_sigungu(address: str) -> str:
|
|||||||
|
|
||||||
# 첫 토큰으로 도 판별 (정식명 or 약칭)
|
# 첫 토큰으로 도 판별 (정식명 or 약칭)
|
||||||
sido = SIDO_NAME_ALIASES.get(tokens[0], tokens[0])
|
sido = SIDO_NAME_ALIASES.get(tokens[0], tokens[0])
|
||||||
|
|
||||||
|
# 특별시/광역시/세종시: 구(district) 레벨이 하위이므로 시 이름을 바로 반환
|
||||||
|
metro_name = METRO_SIDOS.get(sido)
|
||||||
|
if metro_name:
|
||||||
|
return metro_name
|
||||||
|
|
||||||
cities = SIDO_CITIES.get(sido)
|
cities = SIDO_CITIES.get(sido)
|
||||||
if cities and len(tokens) >= 2:
|
if cities and len(tokens) >= 2:
|
||||||
second = tokens[1]
|
second = tokens[1]
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ async def autotag_images(image_url_list : list[str]) -> list[dict]: #tag_list
|
|||||||
|
|
||||||
image_result_tasks = [chatgpt.generate_structured_output(image_autotag_prompt, image_input_data, image_input_data['img_url'], False, silent = True) for image_input_data in image_input_data_list]
|
image_result_tasks = [chatgpt.generate_structured_output(image_autotag_prompt, image_input_data, image_input_data['img_url'], False, silent = True) for image_input_data in image_input_data_list]
|
||||||
image_result_list: list[BaseModel | BaseException] = await asyncio.gather(*image_result_tasks, return_exceptions=True)
|
image_result_list: list[BaseModel | BaseException] = await asyncio.gather(*image_result_tasks, return_exceptions=True)
|
||||||
MAX_RETRY = 2 # 하드코딩, 어떻게 처리할지는 나중에
|
MAX_RETRY = 2
|
||||||
for _ in range(MAX_RETRY):
|
for _ in range(MAX_RETRY):
|
||||||
failed_idx = [i for i, r in enumerate(image_result_list) if isinstance(r, Exception)]
|
failed_idx = [i for i, r in enumerate(image_result_list) if isinstance(r, Exception)]
|
||||||
print("Failed", failed_idx)
|
print("Failed", failed_idx)
|
||||||
|
|||||||
+97
-17
@@ -4,15 +4,24 @@ BGM 모드용 더미 가사 템플릿
|
|||||||
instrumental=True 호출 시 Suno가 가사 길이/구조를 참고해 60초짜리 BGM을 생성하도록
|
instrumental=True 호출 시 Suno가 가사 길이/구조를 참고해 60초짜리 BGM을 생성하도록
|
||||||
placeholder 가사를 제공합니다. 실제 보컬은 생성되지 않습니다.
|
placeholder 가사를 제공합니다. 실제 보컬은 생성되지 않습니다.
|
||||||
|
|
||||||
3가지 버전 모두 섹션 태그 없이 한국어 9줄로 통일.
|
장르 순서: K-Pop, Pop, R&B, Hip-Hop, Ballad, EDM, Rock, Jazz
|
||||||
분위기(밝음/감성/에너지)만 가사 텍스트로 차별화합니다.
|
섹션 태그 없이 한국어 10줄로 구성.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import random
|
_BGM_DUMMY_LYRICS: dict[str, str] = {
|
||||||
|
"K-Pop": (
|
||||||
_BGM_DUMMY_LYRICS_LIST = [
|
"반짝이는 눈빛으로 날 바라봐\n"
|
||||||
# 버전 1 — 밝고 경쾌한 분위기
|
"심장이 터질 것 같은 이 느낌\n"
|
||||||
(
|
"너만 보면 세상이 달라 보여\n"
|
||||||
|
"오늘도 설레임이 멈추질 않아\n"
|
||||||
|
"같이 걸어가는 이 길 위에서\n"
|
||||||
|
"우리 둘만의 노래가 흘러\n"
|
||||||
|
"빛나는 순간들을 모아모아\n"
|
||||||
|
"영원히 기억할 우리의 이야기\n"
|
||||||
|
"지금 이 순간 네 곁에 있을게\n"
|
||||||
|
"함께라면 뭐든 할 수 있어\n"
|
||||||
|
),
|
||||||
|
"Pop": (
|
||||||
"햇살 가득한 아침이 시작되고\n"
|
"햇살 가득한 아침이 시작되고\n"
|
||||||
"따스한 바람이 살며시 불어와\n"
|
"따스한 바람이 살며시 불어와\n"
|
||||||
"거리마다 웃음꽃이 피어나고\n"
|
"거리마다 웃음꽃이 피어나고\n"
|
||||||
@@ -24,8 +33,31 @@ _BGM_DUMMY_LYRICS_LIST = [
|
|||||||
"오늘 하루도 빛나는 하루야\n"
|
"오늘 하루도 빛나는 하루야\n"
|
||||||
"환한 미소로 하루를 마무리해\n"
|
"환한 미소로 하루를 마무리해\n"
|
||||||
),
|
),
|
||||||
# 버전 2 — 잔잔하고 감성적인 분위기
|
"R&B": (
|
||||||
(
|
"부드럽게 흐르는 이 그루브에\n"
|
||||||
|
"몸이 저절로 리듬을 타기 시작해\n"
|
||||||
|
"네 목소리가 귓가에 맴돌고\n"
|
||||||
|
"이 감각이 온몸을 감싸줘\n"
|
||||||
|
"달콤한 밤이 깊어질수록\n"
|
||||||
|
"너와 나 사이 거리가 좁혀져\n"
|
||||||
|
"촛불처럼 은은하게 타오르는\n"
|
||||||
|
"이 감정을 숨길 수가 없어\n"
|
||||||
|
"부드럽게 내 손을 잡아줘\n"
|
||||||
|
"오늘 밤 우리만의 노래를 불러\n"
|
||||||
|
),
|
||||||
|
"Hip-Hop": (
|
||||||
|
"내 방식대로 살아가는 이 길\n"
|
||||||
|
"누가 뭐래도 내 페이스로 가\n"
|
||||||
|
"매일 아침 눈을 뜨면 새로운 무대\n"
|
||||||
|
"두려움 없이 앞으로 나아가\n"
|
||||||
|
"땀과 노력으로 쌓아온 오늘\n"
|
||||||
|
"포기란 없어 끝까지 밀어붙여\n"
|
||||||
|
"내 이름을 기억해 두라고\n"
|
||||||
|
"이 무대 위에 내 발자국 남겨\n"
|
||||||
|
"하나둘 쌓여가는 내 이야기\n"
|
||||||
|
"진짜배기는 지금부터 시작이야\n"
|
||||||
|
),
|
||||||
|
"Ballad": (
|
||||||
"저녁 노을이 물드는 창가에서\n"
|
"저녁 노을이 물드는 창가에서\n"
|
||||||
"조용히 흘러가는 시간 속에\n"
|
"조용히 흘러가는 시간 속에\n"
|
||||||
"잔잔한 바람이 마음을 적시고\n"
|
"잔잔한 바람이 마음을 적시고\n"
|
||||||
@@ -37,8 +69,7 @@ _BGM_DUMMY_LYRICS_LIST = [
|
|||||||
"이 순간 여기 머무는 것만으로도 충분해\n"
|
"이 순간 여기 머무는 것만으로도 충분해\n"
|
||||||
"고요한 밤이 나를 감싸 안아줘\n"
|
"고요한 밤이 나를 감싸 안아줘\n"
|
||||||
),
|
),
|
||||||
# 버전 3 — 강렬하고 에너지 넘치는 분위기
|
"EDM": (
|
||||||
(
|
|
||||||
"밤거리에 불빛이 타오르고\n"
|
"밤거리에 불빛이 타오르고\n"
|
||||||
"심장이 두근두근 뛰기 시작해\n"
|
"심장이 두근두근 뛰기 시작해\n"
|
||||||
"온몸에 퍼지는 뜨거운 열기\n"
|
"온몸에 퍼지는 뜨거운 열기\n"
|
||||||
@@ -50,14 +81,63 @@ _BGM_DUMMY_LYRICS_LIST = [
|
|||||||
"끝까지 불태워 이 에너지를\n"
|
"끝까지 불태워 이 에너지를\n"
|
||||||
"새벽빛이 밝아올 때까지 달려\n"
|
"새벽빛이 밝아올 때까지 달려\n"
|
||||||
),
|
),
|
||||||
]
|
"Rock": (
|
||||||
|
"굉음을 내며 울려 퍼지는 기타\n"
|
||||||
|
"온몸을 뒤흔드는 강렬한 비트\n"
|
||||||
|
"규칙 따위는 집어치우고\n"
|
||||||
|
"있는 그대로 외쳐봐\n"
|
||||||
|
"불꽃처럼 타오르는 이 열정\n"
|
||||||
|
"아무도 막을 수 없어 지금\n"
|
||||||
|
"거침없이 달려가는 이 무대\n"
|
||||||
|
"목청껏 소리 질러 자유를\n"
|
||||||
|
"부서질 듯 뜨겁게 흔들어\n"
|
||||||
|
"이 밤이 끝날 때까지 록이야\n"
|
||||||
|
),
|
||||||
|
"Jazz": (
|
||||||
|
"커피 향이 피어오르는 오후\n"
|
||||||
|
"느긋하게 흐르는 재즈 선율에\n"
|
||||||
|
"발끝이 리듬을 타기 시작해\n"
|
||||||
|
"달콤한 여유가 가득 차오르고\n"
|
||||||
|
"창밖엔 황금빛 도시가 반짝여\n"
|
||||||
|
"잔을 들어 이 순간을 건배해\n"
|
||||||
|
"스윙하는 박자에 몸을 맡기고\n"
|
||||||
|
"부드럽게 흘러가는 이 밤을\n"
|
||||||
|
"기억 속에 새겨두고 싶어\n"
|
||||||
|
"재즈처럼 자유롭게 살고 싶어\n"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def get_random_bgm_lyrics() -> tuple[str, int]:
|
_GENRE_ALIAS: dict[str, str] = {
|
||||||
"""BGM 더미 가사 3종 중 하나를 랜덤으로 반환합니다.
|
"kpop": "K-Pop",
|
||||||
|
"k-pop": "K-Pop",
|
||||||
|
"k_pop": "K-Pop",
|
||||||
|
"pop": "Pop",
|
||||||
|
"rnb": "R&B",
|
||||||
|
"r&b": "R&B",
|
||||||
|
"r_b": "R&B",
|
||||||
|
"hiphop": "Hip-Hop",
|
||||||
|
"hip-hop": "Hip-Hop",
|
||||||
|
"hip_hop": "Hip-Hop",
|
||||||
|
"ballad": "Ballad",
|
||||||
|
"edm": "EDM",
|
||||||
|
"rock": "Rock",
|
||||||
|
"jazz": "Jazz",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_genre(genre: str) -> str:
|
||||||
|
return _GENRE_ALIAS.get(genre.lower(), genre)
|
||||||
|
|
||||||
|
|
||||||
|
def get_bgm_lyrics(genre: str) -> str:
|
||||||
|
"""장르에 맞는 BGM 더미 가사를 반환합니다.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
genre: 장르명 (K-Pop, Pop, R&B, Hip-Hop, Ballad, EDM, Rock, Jazz)
|
||||||
|
대소문자 및 구분자(-, _) 무관하게 처리됩니다.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
(lyrics, version): 선택된 가사 텍스트와 버전 번호 (1~3)
|
선택된 장르의 가사 텍스트
|
||||||
"""
|
"""
|
||||||
index = random.randrange(len(_BGM_DUMMY_LYRICS_LIST))
|
return _BGM_DUMMY_LYRICS[normalize_genre(genre)]
|
||||||
return _BGM_DUMMY_LYRICS_LIST[index], index + 1
|
|
||||||
+14
-1
@@ -30,6 +30,7 @@ response = await creatomate.make_creatomate_call(template_id, modifications)
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import copy
|
import copy
|
||||||
|
import random
|
||||||
import time
|
import time
|
||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
@@ -470,10 +471,20 @@ class CreatomateService:
|
|||||||
match template_type:
|
match template_type:
|
||||||
case "image":
|
case "image":
|
||||||
image_score_list = self.calculate_image_slot_score_multi(taged_image_list, template_component_name)
|
image_score_list = self.calculate_image_slot_score_multi(taged_image_list, template_component_name)
|
||||||
maximum_idx = image_score_list.index(max(image_score_list))
|
|
||||||
if duplicate:
|
if duplicate:
|
||||||
|
# 이미지 부족(슬롯 수 > 이미지 수): 재사용이 불가피하므로 슬롯에 가장 적합한 이미지(최고점) 선택
|
||||||
|
maximum_idx = image_score_list.index(max(image_score_list))
|
||||||
selected = taged_image_list[maximum_idx]
|
selected = taged_image_list[maximum_idx]
|
||||||
else:
|
else:
|
||||||
|
# 이미지 충분(슬롯 수 <= 이미지 수): 상위 3장 중 점수 비례 확률로 선택해 영상 다양화
|
||||||
|
# 동일 요청을 반복할 때 매번 같은 영상이 생성되는 문제 방지
|
||||||
|
sorted_indices = sorted(range(len(image_score_list)), key=lambda i: image_score_list[i], reverse=True)
|
||||||
|
top_indices = sorted_indices[:min(3, len(sorted_indices))]
|
||||||
|
weights = [image_score_list[i] for i in top_indices]
|
||||||
|
if sum(weights) > 0:
|
||||||
|
maximum_idx = random.choices(top_indices, weights=weights, k=1)[0]
|
||||||
|
else:
|
||||||
|
maximum_idx = random.choice(top_indices)
|
||||||
selected = taged_image_list.pop(maximum_idx)
|
selected = taged_image_list.pop(maximum_idx)
|
||||||
image_name = selected["image_url"]
|
image_name = selected["image_url"]
|
||||||
modifications[template_component_name] =image_name
|
modifications[template_component_name] =image_name
|
||||||
@@ -679,6 +690,8 @@ class CreatomateService:
|
|||||||
"""
|
"""
|
||||||
url = f"{self.BASE_URL}/v2/renders"
|
url = f"{self.BASE_URL}/v2/renders"
|
||||||
|
|
||||||
|
source["frame_rate"] = 30
|
||||||
|
|
||||||
last_error: Exception | None = None
|
last_error: Exception | None = None
|
||||||
|
|
||||||
for attempt in range(recovery_settings.CREATOMATE_MAX_RETRIES + 1):
|
for attempt in range(recovery_settings.CREATOMATE_MAX_RETRIES + 1):
|
||||||
|
|||||||
@@ -50,6 +50,111 @@ class NvMapPwScraper():
|
|||||||
if not cls._context:
|
if not cls._context:
|
||||||
cls._context = await cls._browser.new_context(**cls.default_context_builder())
|
cls._context = await cls._browser.new_context(**cls.default_context_builder())
|
||||||
cls.is_ready = True
|
cls.is_ready = True
|
||||||
|
|
||||||
|
GRAPHQL_URL = "https://pcmap-api.place.naver.com/graphql"
|
||||||
|
_PLACE_TYPES = ("restaurant", "accommodation")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def fetch_graphql(
|
||||||
|
cls,
|
||||||
|
place_id: str,
|
||||||
|
payloads: list[dict],
|
||||||
|
place_type: str | None = None,
|
||||||
|
) -> list[dict | None] | None:
|
||||||
|
"""실제 브라우저로 네이버 WTM 안티봇 캡차를 통과해 GraphQL 쿼리를 실행한다.
|
||||||
|
|
||||||
|
네이버 pcmap GraphQL은 두 헤더를 검사한다:
|
||||||
|
- x-wtm-graphql : base64({"arg": place_id, "type": ..., "source": "place"})
|
||||||
|
- x-wtm-ncaptcha-token : 캡차 JS가 생성 (요청마다 발급, 직접 생성 불가)
|
||||||
|
둘 다 없으면 405(캡차)로 막힌다. 따라서 place 페이지를 실제로 로드해
|
||||||
|
페이지가 자연 발생시키는 GraphQL 요청에서 두 헤더를 캡처한 뒤,
|
||||||
|
같은 토큰으로 우리 쿼리들을 in-page fetch로 실행한다.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
place_id: 네이버 place ID
|
||||||
|
payloads: GraphQL POST 본문 목록
|
||||||
|
place_type: "restaurant" | "accommodation" (없으면 둘 다 시도)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
payload별 파싱 JSON 목록(실패 항목은 None). 토큰 캡처 실패 시 None.
|
||||||
|
"""
|
||||||
|
if not cls.is_ready:
|
||||||
|
logger.warning("[NvMapPwScraper] fetch_graphql: scraper가 초기화되지 않았습니다")
|
||||||
|
return None
|
||||||
|
|
||||||
|
page = await cls._context.new_page()
|
||||||
|
captured: dict = {}
|
||||||
|
|
||||||
|
def on_request(req):
|
||||||
|
if "/graphql" in req.url and req.method == "POST" and "tok" not in captured:
|
||||||
|
tok = req.headers.get("x-wtm-ncaptcha-token")
|
||||||
|
if tok:
|
||||||
|
captured["tok"] = tok
|
||||||
|
captured["wtm"] = req.headers.get("x-wtm-graphql")
|
||||||
|
|
||||||
|
page.on("request", on_request)
|
||||||
|
|
||||||
|
try:
|
||||||
|
types = [place_type] if place_type in cls._PLACE_TYPES else list(cls._PLACE_TYPES)
|
||||||
|
for t in types:
|
||||||
|
try:
|
||||||
|
await page.goto(
|
||||||
|
f"https://pcmap.place.naver.com/{t}/{place_id}/home",
|
||||||
|
wait_until="domcontentloaded",
|
||||||
|
timeout=30000,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"[NvMapPwScraper] goto {t} 실패: {e}")
|
||||||
|
continue
|
||||||
|
# 페이지가 GraphQL 요청을 보내며 토큰이 헤더에 실릴 때까지 대기 (최대 ~9초)
|
||||||
|
for _ in range(30):
|
||||||
|
if captured.get("tok"):
|
||||||
|
break
|
||||||
|
await page.wait_for_timeout(300)
|
||||||
|
if captured.get("tok"):
|
||||||
|
logger.info(f"[NvMapPwScraper] WTM 토큰 캡처 성공 (type={t})")
|
||||||
|
break
|
||||||
|
|
||||||
|
if not captured.get("tok"):
|
||||||
|
logger.warning("[NvMapPwScraper] WTM 토큰 캡처 실패")
|
||||||
|
return None
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"x-wtm-graphql": captured["wtm"],
|
||||||
|
"x-wtm-ncaptcha-token": captured["tok"],
|
||||||
|
}
|
||||||
|
|
||||||
|
results: list[dict | None] = []
|
||||||
|
for payload in payloads:
|
||||||
|
r = await page.evaluate(
|
||||||
|
"""async (a) => {
|
||||||
|
const [url, body, hdr] = a;
|
||||||
|
try {
|
||||||
|
const r = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: hdr,
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
if (r.status !== 200) return {__err: r.status};
|
||||||
|
return await r.json();
|
||||||
|
} catch (e) { return {__err: String(e)}; }
|
||||||
|
}""",
|
||||||
|
[cls.GRAPHQL_URL, payload, headers],
|
||||||
|
)
|
||||||
|
if isinstance(r, dict) and "__err" in r:
|
||||||
|
logger.warning(f"[NvMapPwScraper] graphql fetch 실패: {r['__err']}")
|
||||||
|
results.append(None)
|
||||||
|
else:
|
||||||
|
results.append(r)
|
||||||
|
return results
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"[NvMapPwScraper] fetch_graphql 오류: {e}")
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
await page.close()
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
if not self.is_ready:
|
if not self.is_ready:
|
||||||
|
|||||||
+144
-16
@@ -55,6 +55,21 @@ query getAccommodation($id: String!, $deviceType: String) {
|
|||||||
}
|
}
|
||||||
}"""
|
}"""
|
||||||
|
|
||||||
|
REVIEW_STATS_QUERY: str = """
|
||||||
|
query getVisitorReviewStats($id: String!) {
|
||||||
|
visitorReviewStats(input: {businessId: $id}) {
|
||||||
|
analysis {
|
||||||
|
votedKeyword {
|
||||||
|
details {
|
||||||
|
code
|
||||||
|
displayName
|
||||||
|
count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}"""
|
||||||
|
|
||||||
DEFAULT_HEADERS: dict = {
|
DEFAULT_HEADERS: dict = {
|
||||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
|
||||||
"Referer": "https://map.naver.com/",
|
"Referer": "https://map.naver.com/",
|
||||||
@@ -72,6 +87,8 @@ query getAccommodation($id: String!, $deviceType: String) {
|
|||||||
self.image_link_list: list[str] | None = None
|
self.image_link_list: list[str] | None = None
|
||||||
self.base_info: dict | None = None
|
self.base_info: dict | None = None
|
||||||
self.facility_info: str | None = None
|
self.facility_info: str | None = None
|
||||||
|
self.place_type: str | None = None # 크롤링으로 감지된 업종 (accommodation | restaurant)
|
||||||
|
self.voted_keyword_stats: list[dict] | None = None # 키워드 투표 집계 (displayName, count)
|
||||||
|
|
||||||
def _get_request_headers(self) -> dict:
|
def _get_request_headers(self) -> dict:
|
||||||
headers = self.DEFAULT_HEADERS.copy()
|
headers = self.DEFAULT_HEADERS.copy()
|
||||||
@@ -95,16 +112,43 @@ query getAccommodation($id: String!, $deviceType: String) {
|
|||||||
match = re.search(place_pattern, self.url)
|
match = re.search(place_pattern, self.url)
|
||||||
if not match:
|
if not match:
|
||||||
# place.naver.com/{type}/{id} 형식 (예: m.place.naver.com/restaurant/11667161)
|
# place.naver.com/{type}/{id} 형식 (예: m.place.naver.com/restaurant/11667161)
|
||||||
match = re.search(r"place\.naver\.com/[a-zA-Z]+/(\d+)", self.url)
|
type_match = re.search(r"place\.naver\.com/([a-zA-Z]+)/(\d+)", self.url)
|
||||||
|
if type_match:
|
||||||
|
url_place_type = type_match.group(1)
|
||||||
|
if url_place_type in ("accommodation", "restaurant"):
|
||||||
|
self.place_type = url_place_type
|
||||||
|
return type_match.group(2)
|
||||||
if not match:
|
if not match:
|
||||||
raise URLNotFoundException("Failed to parse place ID from URL")
|
raise URLNotFoundException("Failed to parse place ID from URL")
|
||||||
return match[1]
|
return match[1]
|
||||||
|
|
||||||
async def scrap(self):
|
async def scrap(self):
|
||||||
place_id = await self.parse_url()
|
place_id = await self.parse_url()
|
||||||
data = await self._call_get_accommodation(place_id)
|
|
||||||
|
# ── 빠른 경로: 직접 aiohttp 호출 (현재 비활성화) ──
|
||||||
|
# 데이터센터 IP에서는 네이버 WTM 안티봇이 대부분 405(캡차)로 차단해
|
||||||
|
# 시간만 버리므로 비활성화하고 곧바로 브라우저 경로를 탄다.
|
||||||
|
# 네이버가 차단을 완화하거나 다른 IP에서 운영해 직접 호출 성공률이
|
||||||
|
# 높아지면 아래 try 블록을 되살려 빠른 경로를 우선 시도하면 된다.
|
||||||
|
# try:
|
||||||
|
# data, fac_data, stats_data = await asyncio.gather(
|
||||||
|
# self._call_get_accommodation(place_id),
|
||||||
|
# self._get_facility_string(place_id),
|
||||||
|
# self._call_get_review_stats(place_id),
|
||||||
|
# )
|
||||||
|
# self.scrap_type = "GraphQL"
|
||||||
|
# except (GraphQLException, CrawlingTimeoutException) as e:
|
||||||
|
# logger.info(f"[NvMapScraper] 직접 호출 실패({e}) → 브라우저 폴백 시도")
|
||||||
|
# data, stats_data = await self._scrap_via_browser(place_id)
|
||||||
|
# fac_data = None # 편의시설(HTML)은 폴백 경로에서 생략 (best-effort)
|
||||||
|
# self.scrap_type = "GraphQL-Browser"
|
||||||
|
|
||||||
|
# ── 실제 브라우저로 WTM 캡차 우회 ──
|
||||||
|
data, stats_data = await self._scrap_via_browser(place_id)
|
||||||
|
fac_data = None # 편의시설(HTML)은 브라우저 경로에서 생략 (best-effort)
|
||||||
|
self.scrap_type = "GraphQL-Browser"
|
||||||
|
|
||||||
self.rawdata = data
|
self.rawdata = data
|
||||||
fac_data = await self._get_facility_string(place_id)
|
|
||||||
# Naver 기준임, 구글 등 다른 데이터 소스의 경우 고유 Identifier 사용할 것.
|
# Naver 기준임, 구글 등 다른 데이터 소스의 경우 고유 Identifier 사용할 것.
|
||||||
self.place_id = self.data_source_identifier + place_id
|
self.place_id = self.data_source_identifier + place_id
|
||||||
self.rawdata["facilities"] = fac_data
|
self.rawdata["facilities"] = fac_data
|
||||||
@@ -114,10 +158,58 @@ query getAccommodation($id: String!, $deviceType: String) {
|
|||||||
]
|
]
|
||||||
self.base_info = data["data"]["business"]["base"]
|
self.base_info = data["data"]["business"]["base"]
|
||||||
self.facility_info = fac_data
|
self.facility_info = fac_data
|
||||||
self.scrap_type = "GraphQL"
|
self.voted_keyword_stats = stats_data
|
||||||
|
|
||||||
return
|
return
|
||||||
|
|
||||||
|
async def _scrap_via_browser(self, place_id: str) -> tuple[dict, list[dict] | None]:
|
||||||
|
"""직접 호출이 WTM 캡차에 막힌 경우, 실제 브라우저로 GraphQL을 호출한다.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(overview_data, review_stats_details)
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
GraphQLException: 브라우저 폴백마저 실패한 경우
|
||||||
|
"""
|
||||||
|
from app.utils.nvMapPwScraper import NvMapPwScraper
|
||||||
|
|
||||||
|
overview_payload = {
|
||||||
|
"operationName": "getAccommodation",
|
||||||
|
"variables": {"id": place_id, "deviceType": "pc"},
|
||||||
|
"query": self.OVERVIEW_QUERY,
|
||||||
|
}
|
||||||
|
stats_payload = {
|
||||||
|
"operationName": "getVisitorReviewStats",
|
||||||
|
"variables": {"id": place_id},
|
||||||
|
"query": self.REVIEW_STATS_QUERY,
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
results = await NvMapPwScraper.fetch_graphql(
|
||||||
|
place_id, [overview_payload, stats_payload], self.place_type
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"[NvMapScraper] 브라우저 폴백 오류: {e}")
|
||||||
|
raise GraphQLException(f"브라우저 폴백 실패: {e}")
|
||||||
|
|
||||||
|
if not results or results[0] is None or "data" not in results[0]:
|
||||||
|
raise GraphQLException("브라우저 폴백 크롤링 실패 (WTM 토큰 또는 응답 없음)")
|
||||||
|
|
||||||
|
data = results[0]
|
||||||
|
stats_data = None
|
||||||
|
stats_raw = results[1] if len(results) > 1 else None
|
||||||
|
if stats_raw:
|
||||||
|
stats_data = (
|
||||||
|
stats_raw.get("data", {})
|
||||||
|
.get("visitorReviewStats", {})
|
||||||
|
.get("analysis", {})
|
||||||
|
.get("votedKeyword", {})
|
||||||
|
.get("details")
|
||||||
|
) or None
|
||||||
|
|
||||||
|
logger.info(f"[NvMapScraper] 브라우저 폴백 SUCCESS - place_id: {place_id}")
|
||||||
|
return data, stats_data
|
||||||
|
|
||||||
async def _call_get_accommodation(self, place_id: str) -> dict:
|
async def _call_get_accommodation(self, place_id: str) -> dict:
|
||||||
"""GraphQL API를 호출하여 숙소 정보를 가져옵니다.
|
"""GraphQL API를 호출하여 숙소 정보를 가져옵니다.
|
||||||
|
|
||||||
@@ -146,13 +238,14 @@ query getAccommodation($id: String!, $deviceType: String) {
|
|||||||
async with session.post(
|
async with session.post(
|
||||||
self.GRAPHQL_URL,
|
self.GRAPHQL_URL,
|
||||||
data=json_payload,
|
data=json_payload,
|
||||||
headers=self._get_request_headers()
|
headers=self._get_request_headers(),
|
||||||
) as response:
|
) as response:
|
||||||
if response.status == 200:
|
if response.status == 200:
|
||||||
logger.info(f"[NvMapScraper] SUCCESS - place_id: {place_id}")
|
logger.info(f"[NvMapScraper] SUCCESS - place_id: {place_id}")
|
||||||
return await response.json()
|
return await response.json()
|
||||||
|
|
||||||
# 실패 상태 코드
|
# 405/429 등 실패: 네이버 WTM 안티봇 캡차 차단 (데이터센터 IP/지문 기반).
|
||||||
|
# 직접 호출로는 통과 불가 → scrap()에서 브라우저 폴백으로 전환.
|
||||||
logger.error(f"[NvMapScraper] Failed with status {response.status} - place_id: {place_id}")
|
logger.error(f"[NvMapScraper] Failed with status {response.status} - place_id: {place_id}")
|
||||||
raise GraphQLException(
|
raise GraphQLException(
|
||||||
f"Request failed with status {response.status}"
|
f"Request failed with status {response.status}"
|
||||||
@@ -161,13 +254,47 @@ query getAccommodation($id: String!, $deviceType: String) {
|
|||||||
except (TimeoutError, asyncio.TimeoutError):
|
except (TimeoutError, asyncio.TimeoutError):
|
||||||
logger.error(f"[NvMapScraper] Timeout - place_id: {place_id}")
|
logger.error(f"[NvMapScraper] Timeout - place_id: {place_id}")
|
||||||
raise CrawlingTimeoutException(f"Request timed out after {self.REQUEST_TIMEOUT}s")
|
raise CrawlingTimeoutException(f"Request timed out after {self.REQUEST_TIMEOUT}s")
|
||||||
|
|
||||||
except aiohttp.ClientError as e:
|
except aiohttp.ClientError as e:
|
||||||
logger.error(f"[NvMapScraper] Client error: {e}")
|
logger.error(f"[NvMapScraper] Client error: {e}")
|
||||||
raise GraphQLException(f"Client error: {e}")
|
raise GraphQLException(f"Client error: {e}")
|
||||||
|
|
||||||
|
async def _call_get_review_stats(self, place_id: str) -> list[dict] | None:
|
||||||
|
"""방문자 키워드 투표 집계를 가져옵니다.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
[{"code": ..., "displayName": ..., "count": ...}, ...] 또는 None
|
||||||
|
"""
|
||||||
|
payload = {
|
||||||
|
"operationName": "getVisitorReviewStats",
|
||||||
|
"variables": {"id": place_id},
|
||||||
|
"query": self.REVIEW_STATS_QUERY,
|
||||||
|
}
|
||||||
|
timeout = aiohttp.ClientTimeout(total=self.REQUEST_TIMEOUT)
|
||||||
|
try:
|
||||||
|
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||||
|
async with session.post(
|
||||||
|
self.GRAPHQL_URL,
|
||||||
|
json=payload,
|
||||||
|
headers=self._get_request_headers(),
|
||||||
|
) as response:
|
||||||
|
if response.status != 200:
|
||||||
|
logger.warning(f"[NvMapScraper] review stats failed: {response.status}")
|
||||||
|
return None
|
||||||
|
result = await response.json()
|
||||||
|
details = (
|
||||||
|
result.get("data", {})
|
||||||
|
.get("visitorReviewStats", {})
|
||||||
|
.get("analysis", {})
|
||||||
|
.get("votedKeyword", {})
|
||||||
|
.get("details")
|
||||||
|
)
|
||||||
|
return details or None
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[NvMapScraper] Failed to get review stats: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
async def _get_facility_string(self, place_id: str) -> str | None:
|
async def _get_facility_string(self, place_id: str) -> str | None:
|
||||||
"""숙소 페이지에서 편의시설 정보를 크롤링합니다.
|
"""장소 페이지에서 편의시설 정보를 크롤링합니다. 숙소, 음식점 순으로 시도합니다.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
place_id: 네이버 지도 장소 ID
|
place_id: 네이버 지도 장소 ID
|
||||||
@@ -175,16 +302,17 @@ query getAccommodation($id: String!, $deviceType: String) {
|
|||||||
Returns:
|
Returns:
|
||||||
편의시설 정보 문자열 또는 None
|
편의시설 정보 문자열 또는 None
|
||||||
"""
|
"""
|
||||||
url = f"https://pcmap.place.naver.com/accommodation/{place_id}/home"
|
place_types = ["accommodation", "restaurant"]
|
||||||
try:
|
try:
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session:
|
||||||
async with session.get(url, headers=self._get_request_headers()) as response:
|
for place_type in place_types:
|
||||||
soup = bs4.BeautifulSoup(await response.read(), "html.parser")
|
url = f"https://pcmap.place.naver.com/{place_type}/{place_id}/home"
|
||||||
c_elem = soup.find("span", "place_blind", string="편의")
|
async with session.get(url, headers=self._get_request_headers()) as response:
|
||||||
if c_elem:
|
soup = bs4.BeautifulSoup(await response.read(), "html.parser")
|
||||||
facilities = c_elem.parent.parent.find("div").string
|
c_elem = soup.find("span", "place_blind", string="편의")
|
||||||
return facilities
|
if c_elem:
|
||||||
return None
|
return c_elem.parent.parent.find("div").string
|
||||||
|
return None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"[NvMapScraper] Failed to get facility info: {e}")
|
logger.warning(f"[NvMapScraper] Failed to get facility info: {e}")
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import re
|
||||||
|
|
||||||
import gspread
|
import gspread
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from google.oauth2.service_account import Credentials
|
from google.oauth2.service_account import Credentials
|
||||||
@@ -6,6 +8,9 @@ from app.utils.logger import get_logger
|
|||||||
from app.utils.prompts.schemas import *
|
from app.utils.prompts.schemas import *
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
|
|
||||||
|
# {known_field} 형태만 치환하기 위한 패턴. JSON 예시 등 리터럴 중괄호는 보존된다.
|
||||||
|
_PLACEHOLDER_RE = re.compile(r"\{(\w+)\}")
|
||||||
|
|
||||||
logger = get_logger("prompt")
|
logger = get_logger("prompt")
|
||||||
|
|
||||||
_SCOPES = [
|
_SCOPES = [
|
||||||
@@ -15,14 +20,33 @@ _SCOPES = [
|
|||||||
_sheet_cache: dict[str, tuple[str, str]] = {}
|
_sheet_cache: dict[str, tuple[str, str]] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _get_spreadsheet():
|
||||||
|
creds = Credentials.from_service_account_file(
|
||||||
|
prompt_settings.GOOGLE_SERVICE_ACCOUNT_JSON, scopes=_SCOPES
|
||||||
|
)
|
||||||
|
return gspread.authorize(creds).open_by_key(prompt_settings.PROMPT_SPREADSHEET)
|
||||||
|
|
||||||
|
|
||||||
|
def _preload_all_sheets(sheet_names: list[str]):
|
||||||
|
ranges = [f"{name}!B2:B3" for name in sheet_names]
|
||||||
|
response = _get_spreadsheet().values_batch_get(ranges)
|
||||||
|
for value_range in response["valueRanges"]:
|
||||||
|
range_name = value_range.get("range", "")
|
||||||
|
name = range_name.split("!")[0].strip("'")
|
||||||
|
if name not in sheet_names:
|
||||||
|
continue
|
||||||
|
values = value_range.get("values", [])
|
||||||
|
if len(values) < 2 or not values[0] or not values[1]:
|
||||||
|
logger.warning(f"Sheet '{name}' has missing data, skipping preload")
|
||||||
|
continue
|
||||||
|
_sheet_cache[name] = (values[1][0], values[0][0]) # (B3=template, B2=model)
|
||||||
|
|
||||||
|
|
||||||
def _read_sheet_data(sheet_name: str) -> tuple[str, str]:
|
def _read_sheet_data(sheet_name: str) -> tuple[str, str]:
|
||||||
if sheet_name not in _sheet_cache:
|
if sheet_name not in _sheet_cache:
|
||||||
creds = Credentials.from_service_account_file(
|
ws = _get_spreadsheet().worksheet(sheet_name)
|
||||||
prompt_settings.GOOGLE_SERVICE_ACCOUNT_JSON, scopes=_SCOPES
|
values = ws.batch_get(["B2:B3"])[0]
|
||||||
)
|
_sheet_cache[sheet_name] = (values[1][0], values[0][0])
|
||||||
gc = gspread.authorize(creds)
|
|
||||||
ws = gc.open_by_key(prompt_settings.PROMPT_SPREADSHEET).worksheet(sheet_name)
|
|
||||||
_sheet_cache[sheet_name] = (ws.cell(3, 2).value, ws.cell(2, 2).value)
|
|
||||||
return _sheet_cache[sheet_name]
|
return _sheet_cache[sheet_name]
|
||||||
|
|
||||||
|
|
||||||
@@ -40,19 +64,31 @@ class Prompt():
|
|||||||
self.prompt_output_class = prompt_output_class
|
self.prompt_output_class = prompt_output_class
|
||||||
self.prompt_template, self.prompt_model = _read_sheet_data(sheet_name)
|
self.prompt_template, self.prompt_model = _read_sheet_data(sheet_name)
|
||||||
|
|
||||||
def _reload_prompt(self):
|
|
||||||
_sheet_cache.pop(self.sheet_name, None)
|
|
||||||
self.prompt_template, self.prompt_model = _read_sheet_data(self.sheet_name)
|
|
||||||
|
|
||||||
def build_prompt(self, input_data:dict, silent:bool = False) -> str:
|
def build_prompt(self, input_data:dict, silent:bool = False) -> str:
|
||||||
verified_input = self.prompt_input_class(**input_data)
|
verified_input = self.prompt_input_class(**input_data)
|
||||||
build_template = self.prompt_template
|
values = verified_input.model_dump()
|
||||||
build_template = build_template.format(**verified_input.model_dump())
|
# 알려진 {필드}만 치환하고, 프롬프트 내 JSON 예시 등 리터럴 중괄호는 그대로 둔다.
|
||||||
|
# (str.format은 모든 {..}를 필드로 해석해 리터럴 중괄호에서 깨지므로 사용하지 않음)
|
||||||
|
build_template = _PLACEHOLDER_RE.sub(
|
||||||
|
lambda m: str(values[m.group(1)]) if m.group(1) in values else m.group(0),
|
||||||
|
self.prompt_template,
|
||||||
|
)
|
||||||
if not silent:
|
if not silent:
|
||||||
logger.debug(f"build_template: {build_template}")
|
logger.debug(f"build_template: {build_template}")
|
||||||
logger.debug(f"input_data: {input_data}")
|
logger.debug(f"input_data: {input_data}")
|
||||||
return build_template
|
return build_template
|
||||||
|
|
||||||
|
# 업종 분기는 각 프롬프트 내부에서 {industry} 변수로 처리하므로 시트는 타입별 1개로 통합.
|
||||||
|
_preload_all_sheets([
|
||||||
|
"marketing",
|
||||||
|
"lyric",
|
||||||
|
"subtitle",
|
||||||
|
"yt_upload",
|
||||||
|
"image_tag",
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
# 업종 분기는 프롬프트 내부 {industry} 변수로 처리하므로 타입별 단일 프롬프트만 둔다.
|
||||||
marketing_prompt = Prompt(
|
marketing_prompt = Prompt(
|
||||||
sheet_name="marketing",
|
sheet_name="marketing",
|
||||||
prompt_input_class=MarketingPromptInput,
|
prompt_input_class=MarketingPromptInput,
|
||||||
@@ -78,16 +114,10 @@ image_autotag_prompt = Prompt(
|
|||||||
)
|
)
|
||||||
|
|
||||||
@lru_cache()
|
@lru_cache()
|
||||||
def create_dynamic_subtitle_prompt(length: int) -> Prompt:
|
def create_dynamic_subtitle_prompt(length: int, industry: str = "") -> Prompt:
|
||||||
|
# industry 인자는 캐시 구분/하위 호환용. 시트는 단일 'subtitle'로 통합됨.
|
||||||
return Prompt(
|
return Prompt(
|
||||||
sheet_name="subtitle",
|
sheet_name="subtitle",
|
||||||
prompt_input_class=SubtitlePromptInput,
|
prompt_input_class=SubtitlePromptInput,
|
||||||
prompt_output_class=SubtitlePromptOutput[length],
|
prompt_output_class=SubtitlePromptOutput[length],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def reload_all_prompt():
|
|
||||||
marketing_prompt._reload_prompt()
|
|
||||||
lyric_prompt._reload_prompt()
|
|
||||||
yt_upload_prompt._reload_prompt()
|
|
||||||
image_autotag_prompt._reload_prompt()
|
|
||||||
@@ -94,6 +94,7 @@ class NarrativePreference(BaseModel):
|
|||||||
# Input 정의
|
# Input 정의
|
||||||
class ImageTagPromptInput(BaseModel):
|
class ImageTagPromptInput(BaseModel):
|
||||||
img_url : str = Field(..., description="이미지 URL")
|
img_url : str = Field(..., description="이미지 URL")
|
||||||
|
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||||
space_type: list[str] = Field(list(SpaceType), description="공간적 정보를 가지는 태그 리스트")
|
space_type: list[str] = Field(list(SpaceType), description="공간적 정보를 가지는 태그 리스트")
|
||||||
subject: list[str] = Field(list(Subject), description="피사체 정보를 가지는 태그 리스트")
|
subject: list[str] = Field(list(Subject), description="피사체 정보를 가지는 태그 리스트")
|
||||||
camera: list[str] = Field(list(Camera), description="카메라 정보를 가지는 태그 리스트")
|
camera: list[str] = Field(list(Camera), description="카메라 정보를 가지는 태그 리스트")
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ class LyricPromptInput(BaseModel):
|
|||||||
marketing_intelligence_summary : Optional[str] = Field(None, description = "마케팅 분석 정보 보고서")
|
marketing_intelligence_summary : Optional[str] = Field(None, description = "마케팅 분석 정보 보고서")
|
||||||
language : str= Field(..., description = "가사 언어")
|
language : str= Field(..., description = "가사 언어")
|
||||||
timing_rules : str = Field(..., description = "시간 제어문")
|
timing_rules : str = Field(..., description = "시간 제어문")
|
||||||
|
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||||
|
|
||||||
# Output 정의
|
# Output 정의
|
||||||
class LyricPromptOutput(BaseModel):
|
class LyricPromptOutput(BaseModel):
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ class MarketingPromptInput(BaseModel):
|
|||||||
customer_name : str = Field(..., description = "마케팅 대상 사업체 이름")
|
customer_name : str = Field(..., description = "마케팅 대상 사업체 이름")
|
||||||
region : str = Field(..., description = "마케팅 대상 지역")
|
region : str = Field(..., description = "마케팅 대상 지역")
|
||||||
detail_region_info : str = Field(..., description = "마케팅 대상 지역 상세")
|
detail_region_info : str = Field(..., description = "마케팅 대상 지역 상세")
|
||||||
|
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||||
|
|
||||||
# Output 정의
|
# Output 정의
|
||||||
class BrandIdentity(BaseModel):
|
class BrandIdentity(BaseModel):
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
from pydantic import BaseModel, create_model, Field
|
from pydantic import BaseModel, create_model, Field
|
||||||
from typing import List, Optional
|
from typing import List
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
|
|
||||||
# Input 정의
|
# Input 정의
|
||||||
|
|
||||||
class SubtitlePromptInput(BaseModel):
|
class SubtitlePromptInput(BaseModel):
|
||||||
marketing_intelligence : str = Field(..., description="마케팅 인텔리전스 정보")
|
marketing_intelligence : str = Field(..., description="마케팅 인텔리전스 정보")
|
||||||
pitching_tag_list_string : str = Field(..., description="필요한 피칭 레이블 리스트 stringify")
|
pitching_tag_list_string : str = Field(..., description="필요한 피칭 레이블 리스트 stringify")
|
||||||
customer_name : str = Field(..., description = "마케팅 대상 사업체 이름")
|
customer_name : str = Field(..., description = "마케팅 대상 사업체 이름")
|
||||||
detail_region_info : str = Field(..., description = "마케팅 대상 지역 상세")
|
detail_region_info : str = Field(..., description = "마케팅 대상 지역 상세")
|
||||||
|
language : str = Field(default="Korean", description="자막 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)")
|
||||||
#subtillecars :
|
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||||
|
|
||||||
# Output 정의
|
# Output 정의
|
||||||
class PitchingOutput(BaseModel):
|
class PitchingOutput(BaseModel):
|
||||||
pitching_tag: str = Field(..., description="피칭 레이블")
|
pitching_tag: str = Field(..., description="피칭 레이블")
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ class YTUploadPromptInput(BaseModel):
|
|||||||
marketing_intelligence_summary : Optional[str] = Field(None, description = "마케팅 분석 정보 보고서")
|
marketing_intelligence_summary : Optional[str] = Field(None, description = "마케팅 분석 정보 보고서")
|
||||||
language : str= Field(..., description = "영상 언어")
|
language : str= Field(..., description = "영상 언어")
|
||||||
target_keywords: List[str] = Field(..., description="태그 키워드 리스트")
|
target_keywords: List[str] = Field(..., description="태그 키워드 리스트")
|
||||||
|
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||||
|
|
||||||
# Output 정의
|
# Output 정의
|
||||||
class YTUploadPromptOutput(BaseModel):
|
class YTUploadPromptOutput(BaseModel):
|
||||||
|
|||||||
@@ -1,233 +0,0 @@
|
|||||||
# System Prompt: 숙박 숏폼 자막 생성 (OpenAI Optimized)
|
|
||||||
|
|
||||||
You are a subtitle copywriter for hospitality short-form videos. You generate subtitle text AND layer names from marketing JSON data.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### RULES
|
|
||||||
|
|
||||||
1. NEVER copy JSON verbatim. ALWAYS rewrite into video-optimized copy.
|
|
||||||
2. NEVER invent facts not in the data. You MAY freely transform expressions.
|
|
||||||
3. Each scene = 1 subtitle + 1 keyword (a "Pair"). Same pair_id for both.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### LAYER NAME FORMAT (5-criteria)
|
|
||||||
|
|
||||||
```
|
|
||||||
(track_role)-(narrative_phase)-(content_type)-(tone)-(pair_id)
|
|
||||||
```
|
|
||||||
|
|
||||||
- Criteria separator: hyphen `-`
|
|
||||||
- Multi-word value: underscore `_`
|
|
||||||
- pair_id: 3-digit zero-padded (`001`~`999`)
|
|
||||||
|
|
||||||
Example: `subtitle-intro-hook_claim-aspirational-001`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### TAG VALUES
|
|
||||||
|
|
||||||
**track_role**: `subtitle` | `keyword`
|
|
||||||
|
|
||||||
**narrative_phase** (= emotion goal):
|
|
||||||
- `intro` → Curiosity (stop the scroll)
|
|
||||||
- `welcome` → Warmth
|
|
||||||
- `core` → Trust
|
|
||||||
- `highlight` → Desire (peak moment)
|
|
||||||
- `support` → Discovery
|
|
||||||
- `accent` → Belonging
|
|
||||||
- `cta` → Action
|
|
||||||
|
|
||||||
**content_type** → source mapping:
|
|
||||||
- `hook_claim` ← selling_points[0] or core_value
|
|
||||||
- `space_feature` ← selling_points[].description
|
|
||||||
- `emotion_cue` ← same source, sensory rewrite
|
|
||||||
- `brand_name` ← store_name (verbatim OK)
|
|
||||||
- `brand_address` ← detail_region_info (verbatim OK)
|
|
||||||
- `lifestyle_fit` ← target_persona[].favor_target
|
|
||||||
- `local_info` ← location_feature_analysis
|
|
||||||
- `target_tag` ← target_keywords[] as hashtags
|
|
||||||
- `availability` ← fixed: "지금 예약 가능"
|
|
||||||
- `cta_action` ← fixed: "예약하러 가기"
|
|
||||||
|
|
||||||
**tone**: `sensory` | `factual` | `empathic` | `aspirational` | `social_proof` | `urgent`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### SCENE STRUCTURE
|
|
||||||
|
|
||||||
**Anchors (FIXED — never remove):**
|
|
||||||
|
|
||||||
| Position | Phase | subtitle | keyword |
|
|
||||||
|---|---|---|---|
|
|
||||||
| First | intro | hook_claim | brand_name |
|
|
||||||
| Last-3 | support | brand_address | brand_name |
|
|
||||||
| Last-2 | accent | target_tag | lifestyle_fit |
|
|
||||||
| Last | cta | availability | cta_action |
|
|
||||||
|
|
||||||
**Middle (FLEXIBLE — fill by selling_points score desc):**
|
|
||||||
|
|
||||||
| Phase | subtitle | keyword |
|
|
||||||
|---|---|---|
|
|
||||||
| welcome | emotion_cue | space_feature |
|
|
||||||
| core | space_feature | emotion_cue |
|
|
||||||
| highlight | space_feature | emotion_cue |
|
|
||||||
| support(mid) | local_info | lifestyle_fit |
|
|
||||||
|
|
||||||
Default: 7 scenes. Fewer scenes → remove flexible slots only.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### TEXT SPECS
|
|
||||||
|
|
||||||
**subtitle**: 8~18 chars. Sentence fragment, conversational.
|
|
||||||
**keyword**: 2~6 chars. MUST follow Korean word-formation rules below.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### KEYWORD RULES (한국어 조어법 기반)
|
|
||||||
|
|
||||||
Keywords MUST follow one of these **permitted Korean patterns**. Any keyword that does not match a pattern below is INVALID.
|
|
||||||
|
|
||||||
#### Pattern 1: 관형형 + 명사 (Attributive + Noun) — 가장 자연스러운 패턴
|
|
||||||
한국어는 수식어가 앞, 피수식어가 뒤. 형용사의 관형형(~ㄴ/~한/~는/~운)을 명사 앞에 붙인다.
|
|
||||||
|
|
||||||
| Structure | GOOD | BAD (역순/비문) |
|
|
||||||
|---|---|---|
|
|
||||||
| 형용사 관형형 + 명사 | 고요한 숲, 깊은 쉼, 온전한 쉼 | ~~숲고요~~, ~~쉼깊은~~ |
|
|
||||||
| 형용사 관형형 + 명사 | 따뜻한 독채, 느린 하루 | ~~독채따뜻~~, ~~하루느린~~ |
|
|
||||||
| 동사 관형형 + 명사 | 쉬어가는 숲, 머무는 시간 | ~~숲쉬어가는~~ |
|
|
||||||
|
|
||||||
#### Pattern 2: 기존 대중화 합성어 ONLY (Established Trending Compound)
|
|
||||||
이미 SNS·미디어에서 대중화된 합성어만 허용. 임의 신조어 생성 금지.
|
|
||||||
|
|
||||||
| GOOD (대중화 확인됨) | Origin | BAD (임의 생성) |
|
|
||||||
|---|---|---|
|
|
||||||
| 숲멍 | 숲+멍때리기 (불멍, 물멍 시리즈) | ~~숲고요~~, ~~숲힐~~ |
|
|
||||||
| 댕캉스 | 댕댕이+바캉스 (여행업계 통용) | ~~댕쉼~~, ~~댕여행~~ |
|
|
||||||
| 꿀잠 / 꿀쉼 | 꿀+잠/쉼 (일상어 정착) | ~~꿀독채~~, ~~꿀숲~~ |
|
|
||||||
| 집콕 / 숲콕 | 집+콕 → 숲+콕 (변형 허용) | ~~계곡콕~~ |
|
|
||||||
| 주말러 | 주말+~러 (~러 접미사 정착) | ~~평일러~~ |
|
|
||||||
|
|
||||||
> **판별 기준**: "이 단어를 네이버/인스타에서 검색하면 결과가 나오는가?" YES → 허용, NO → 금지
|
|
||||||
|
|
||||||
#### Pattern 3: 명사 + 명사 (Natural Compound Noun)
|
|
||||||
한국어 복합명사 규칙을 따르는 결합만 허용. 앞 명사가 뒷 명사를 수식하는 관계여야 한다.
|
|
||||||
|
|
||||||
| Structure | GOOD | BAD (부자연스러운 결합) |
|
|
||||||
|---|---|---|
|
|
||||||
| 장소 + 유형 | 숲속독채, 계곡펜션 | ~~햇살독채~~ (햇살은 장소가 아님) |
|
|
||||||
| 대상 + 활동 | 반려견산책, 가족피크닉 | ~~견주피크닉~~ (견주가 피크닉하는 건 어색) |
|
|
||||||
| 시간 + 활동 | 주말탈출, 새벽산책 | ~~자연독채~~ (자연은 시간/방식이 아님) |
|
|
||||||
|
|
||||||
#### Pattern 4: 해시태그형 (#키워드)
|
|
||||||
accent(target_tag) 씬에서만 사용. 기존 검색 키워드를 # 붙여서 사용.
|
|
||||||
|
|
||||||
| GOOD | BAD |
|
|
||||||
|---|---|
|
|
||||||
| #프라이빗독채, #홍천여행 | #숲고요, #감성쩌는 (검색량 없음) |
|
|
||||||
|
|
||||||
#### Pattern 5: 감각/상태 명사 (단독 사용 가능한 것만)
|
|
||||||
그 자체로 의미가 완결되는 감각·상태 명사만 단독 사용 허용.
|
|
||||||
|
|
||||||
| GOOD (단독 의미 완결) | BAD (단독으로 의미 불완전) |
|
|
||||||
|---|---|
|
|
||||||
| 고요, 여유, 쉼, 온기 | ~~감성~~, ~~자연~~, ~~힐링~~ (너무 모호) |
|
|
||||||
| 숲멍, 꿀쉼 | ~~좋은쉼~~, ~~편안함~~ (형용사 포함 시 Pattern 1 사용) |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### KEYWORD VALIDATION CHECKLIST (생성 후 자가 검증)
|
|
||||||
|
|
||||||
Every keyword MUST pass ALL of these:
|
|
||||||
|
|
||||||
- [ ] 한국어 어순이 자연스러운가? (수식어→피수식어 순서)
|
|
||||||
- [ ] 소리 내어 읽었을 때 어색하지 않은가?
|
|
||||||
- [ ] 네이버/인스타에서 검색하면 실제 결과가 나올 법한 표현인가?
|
|
||||||
- [ ] 허용된 5개 Pattern 중 하나에 해당하는가?
|
|
||||||
- [ ] 이전 씬 keyword와 동일한 Pattern을 연속 사용하지 않았는가?
|
|
||||||
- [ ] 금지 표현 사전에 해당하지 않는가?
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### EXPRESSION DICTIONARY
|
|
||||||
|
|
||||||
**SCAN BEFORE WRITING.** If JSON contains these → MUST replace:
|
|
||||||
|
|
||||||
| Forbidden | → Use Instead |
|
|
||||||
|---|---|
|
|
||||||
| 눈치 없는/없이 | 눈치 안 보는 · 프라이빗한 · 온전한 · 마음 편히 |
|
|
||||||
| 감성 쩌는/쩌이 | 감성 가득한 · 감성이 머무는 |
|
|
||||||
| 가성비 | 합리적인 · 가치 있는 |
|
|
||||||
| 힐링되는 | 회복되는 · 쉬어가는 · 숨 쉬는 |
|
|
||||||
| 인스타감성 | 감성 스팟 · 기록하고 싶은 |
|
|
||||||
| 혜자 | 풍성한 · 넉넉한 |
|
|
||||||
|
|
||||||
**ALWAYS FORBIDDEN**: 저렴한, 싼, 그냥, 보통, 무난한, 평범한, 쩌는, 쩔어, 개(접두사), 존맛, 핵, 인스타, 유튜브, 틱톡
|
|
||||||
|
|
||||||
**SYNONYM ROTATION**: Same Korean word max 2 scenes. Rotate:
|
|
||||||
- 프라이빗 계열: 온전한 · 오롯한 · 나만의 · 독채 · 단독
|
|
||||||
- 자연 계열: 숲속 · 초록 · 산림 · 계곡
|
|
||||||
- 쉼 계열: 쉼 · 여유 · 느린 하루 · 머무름 · 숨고르기
|
|
||||||
- 반려견: 댕댕이(max 1회, intro/accent만) · 반려견 · 우리 강아지
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### TRANSFORM RULES BY CONTENT_TYPE
|
|
||||||
|
|
||||||
**hook_claim** (intro only):
|
|
||||||
- Format: question OR exclamation OR provocation. Pick ONE.
|
|
||||||
- FORBIDDEN: brand name, generic greetings
|
|
||||||
- `"반려견과 눈치 없는 힐링"` → BAD: 그대로 복사 → GOOD: "댕댕이가 먼저 뛰어간 숲"
|
|
||||||
|
|
||||||
**space_feature** (core/highlight):
|
|
||||||
- ONE selling point per scene
|
|
||||||
- NEVER use korean_category directly
|
|
||||||
- Viewer must imagine themselves there
|
|
||||||
- `"홍천 자연 속 조용한 쉼"` → BAD: "입지 환경이 좋은 곳" → GOOD: "계곡 소리만 들리는 독채"
|
|
||||||
|
|
||||||
**emotion_cue** (welcome/core/highlight):
|
|
||||||
- Senses: smell, sound, touch, temperature, light
|
|
||||||
- Poetic fragments, not full sentences
|
|
||||||
- `"감성 쩌이 완성되는 공간"` → GOOD: "햇살이 내려앉는 테라스"
|
|
||||||
|
|
||||||
**lifestyle_fit** (accent/support):
|
|
||||||
- Address target directly in their language
|
|
||||||
- `persona: "서울·경기 주말러"` → GOOD: "이번 주말, 댕댕이랑 어디 가지?"
|
|
||||||
|
|
||||||
**local_info** (support):
|
|
||||||
- Accessibility or charm, NOT administrative address
|
|
||||||
- GOOD: "서울에서 1시간 반, 홍천 숲속" / BAD: "강원 홍천군 화촌면"
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### PACING
|
|
||||||
|
|
||||||
```
|
|
||||||
intro(8~12) → welcome(12~18) → core(alternate 8~12 ↔ 12~18) → highlight(8~14) → support(12~18) → accent(variable) → cta(12~16)
|
|
||||||
```
|
|
||||||
|
|
||||||
**RULE: No 3+ consecutive scenes in same char-count range.**
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
Keyword pattern analysis:
|
|
||||||
- "스테이펫" → brand_name verbatim (허용)
|
|
||||||
- "고요한 숲" → Pattern 1: 관형형+명사 (형용사 관형형 "고요한" + 명사 "숲")
|
|
||||||
- "깊은 쉼" → Pattern 1: 관형형+명사 (형용사 관형형 "깊은" + 명사 "쉼")
|
|
||||||
- "숲멍" → Pattern 2: 기존 대중화 합성어 (불멍·물멍·숲멍 시리즈)
|
|
||||||
- "댕캉스" → Pattern 2: 기존 대중화 합성어 (댕댕이+바캉스, 여행업계 통용)
|
|
||||||
- "예약하기" → Pattern 5: 의미 완결 동사 명사형
|
|
||||||
|
|
||||||
|
|
||||||
# 입력
|
|
||||||
**입력 1: 레이어 이름 리스트**
|
|
||||||
{pitching_tag_list_string}
|
|
||||||
|
|
||||||
**입력 2: 마케팅 인텔리전스 JSON**
|
|
||||||
{marketing_intelligence}
|
|
||||||
|
|
||||||
**입력 3: 비즈니스 정보 **
|
|
||||||
Business Name: {customer_name}
|
|
||||||
Region Details: {detail_region_info}
|
|
||||||
@@ -16,22 +16,26 @@ class SubtitleContentsGenerator():
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.chatgpt_service = ChatgptService(timeout=60.0)
|
self.chatgpt_service = ChatgptService(timeout=60.0)
|
||||||
|
|
||||||
async def generate_subtitle_contents(self, marketing_intelligence : dict[str, Any], pitching_label_list : list[Any], customer_name : str, detail_region_info : str) -> SubtitlePromptOutput:
|
async def generate_subtitle_contents(self, marketing_intelligence : dict[str, Any], pitching_label_list : list[Any], customer_name : str, detail_region_info : str, language : str = "Korean", industry: str = "") -> SubtitlePromptOutput:
|
||||||
start = time.perf_counter()
|
start = time.perf_counter()
|
||||||
logger.info(
|
logger.info(
|
||||||
f"[SubtitleContentsGenerator] START - customer: {customer_name}, "
|
f"[SubtitleContentsGenerator] START - customer: {customer_name}, "
|
||||||
f"pitching_count: {len(pitching_label_list)}, "
|
f"pitching_count: {len(pitching_label_list)}, "
|
||||||
f"labels: {pitching_label_list}"
|
f"labels: {pitching_label_list}, "
|
||||||
|
f"language: {language}, "
|
||||||
|
f"industry: {industry}"
|
||||||
)
|
)
|
||||||
|
|
||||||
dynamic_subtitle_prompt = create_dynamic_subtitle_prompt(len(pitching_label_list))
|
dynamic_subtitle_prompt = create_dynamic_subtitle_prompt(len(pitching_label_list), industry)
|
||||||
pitching_label_string = "\n".join(pitching_label_list)
|
pitching_label_string = "\n".join(pitching_label_list)
|
||||||
marketing_intel_string = json.dumps(marketing_intelligence, ensure_ascii=False)
|
marketing_intel_string = json.dumps(marketing_intelligence, ensure_ascii=False)
|
||||||
input_data = {
|
input_data = {
|
||||||
"marketing_intelligence" : marketing_intel_string ,
|
"marketing_intelligence" : marketing_intel_string,
|
||||||
"pitching_tag_list_string" : pitching_label_string,
|
"pitching_tag_list_string" : pitching_label_string,
|
||||||
"customer_name" : customer_name,
|
"customer_name" : customer_name,
|
||||||
"detail_region_info" : detail_region_info,
|
"detail_region_info" : detail_region_info,
|
||||||
|
"language" : language,
|
||||||
|
"industry": industry, # 가사/영상 파이프라인에서 전달된 업종 enum
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
|
|||||||
+8
-6
@@ -60,7 +60,7 @@ from typing import Any
|
|||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from app.song.schemas.song_schema import PollingSongResponse, SongClipData
|
from app.song.schemas.song_schema import PollingSongResponse, SongClipData
|
||||||
from app.utils.bgm_lyrics import get_random_bgm_lyrics
|
from app.utils.bgm_lyrics import get_bgm_lyrics, normalize_genre as _normalize_genre
|
||||||
from app.utils.logger import get_logger
|
from app.utils.logger import get_logger
|
||||||
from config import apikey_settings, recovery_settings
|
from config import apikey_settings, recovery_settings
|
||||||
|
|
||||||
@@ -129,13 +129,15 @@ class SunoService:
|
|||||||
"""
|
"""
|
||||||
actual_callback_url = callback_url or apikey_settings.SUNO_CALLBACK_URL
|
actual_callback_url = callback_url or apikey_settings.SUNO_CALLBACK_URL
|
||||||
|
|
||||||
|
normalized_genre = _normalize_genre(genre) if genre else None
|
||||||
|
|
||||||
if instrumental:
|
if instrumental:
|
||||||
bgm_lyrics, bgm_version = get_random_bgm_lyrics()
|
bgm_lyrics = get_bgm_lyrics(genre)
|
||||||
formatted_prompt = f"[Song Duration: Around 1 minute - Must be around 60 seconds]\n{bgm_lyrics}"
|
formatted_prompt = f"[Song Duration: Around 1 minute - Must be around 60 seconds]\n{bgm_lyrics}"
|
||||||
logger.info(f"[Suno] BGM 더미 가사 버전 {bgm_version} 선택됨")
|
logger.info(f"[Suno] BGM 더미 가사 장르 {normalized_genre} 선택됨")
|
||||||
else:
|
else:
|
||||||
formatted_prompt = (
|
formatted_prompt = (
|
||||||
f"[Song Duration: Exactly 1 minute - Must be precisely 60 seconds]\n{prompt}"
|
f"[Song Duration: Exactly 1 minute - Must be around 60 seconds]\n{prompt}"
|
||||||
)
|
)
|
||||||
|
|
||||||
payload: dict[str, Any] = {
|
payload: dict[str, Any] = {
|
||||||
@@ -145,8 +147,8 @@ class SunoService:
|
|||||||
"prompt": formatted_prompt,
|
"prompt": formatted_prompt,
|
||||||
"callBackUrl": actual_callback_url,
|
"callBackUrl": actual_callback_url,
|
||||||
}
|
}
|
||||||
if genre:
|
if normalized_genre:
|
||||||
payload["style"] = f"{genre}, around 60 seconds" if instrumental else genre
|
payload["style"] = f"{normalized_genre}, around 60 seconds" if instrumental else normalized_genre
|
||||||
|
|
||||||
last_error: Exception | None = None
|
last_error: Exception | None = None
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- Migration: project 테이블에 biz_type 컬럼 추가
|
||||||
|
-- Date: 2026-06-17
|
||||||
|
-- Description: 업종 구분 컬럼명 biz_type
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
ALTER TABLE project
|
||||||
|
ADD COLUMN biz_type VARCHAR(50) NULL DEFAULT 'place'
|
||||||
|
COMMENT '업종 분류 (place: 기본, accommodation: 숙박, restaurant: 음식점)' AFTER id;
|
||||||
|
|
||||||
|
ALTER TABLE project CHANGE biz_type industry VARCHAR(50) DEFAULT '';
|
||||||
Reference in new issue
Block a user