범용 프롬프트 적용
This commit is contained in:
1 parent
8415e1c3a7
commit
04d8614919
18 files changed
+140
-85
No files matched your search
@@ -38,7 +38,7 @@ from app.utils.common import generate_task_id
|
||||
from app.utils.logger import get_logger
|
||||
from app.utils.nvMapScraper import NvMapScraper, GraphQLException, URLNotFoundException
|
||||
from app.utils.nvMapPwScraper import NvMapPwScraper
|
||||
from app.utils.prompts.prompts import marketing_prompt, restaurant_marketing_prompt
|
||||
from app.utils.prompts.prompts import marketing_prompt
|
||||
from app.utils.address_parser import extract_region_from_address
|
||||
from app.utils.autotag import autotag_images
|
||||
from config import MEDIA_ROOT
|
||||
@@ -56,7 +56,7 @@ router = APIRouter()
|
||||
|
||||
## 요청 파라미터
|
||||
- **query**: 검색어 (필수)
|
||||
- **category**: 카테고리 ("accommodation" | "restaurant", 기본값: 전체)
|
||||
- **category**: 카테고리
|
||||
|
||||
## 반환 정보
|
||||
- **query**: 검색어
|
||||
@@ -75,7 +75,7 @@ router = APIRouter()
|
||||
async def search_accommodation(
|
||||
query: str,
|
||||
) -> AccommodationSearchResponse:
|
||||
"""장소 자동완성 검색 (숙박/음식점 등)"""
|
||||
"""장소 자동완성 검색"""
|
||||
results = await naver_search_client.search_accommodation(
|
||||
query=query,
|
||||
display=10,
|
||||
@@ -94,39 +94,42 @@ def _extract_region_from_address(road_address: str | None, jibun_address: str |
|
||||
return extract_region_from_address(road_address, jibun_address)
|
||||
|
||||
|
||||
class _BizTypeOutput(BaseModel):
|
||||
biz_type: Literal["accommodation", "restaurant", "place"]
|
||||
class _IndustryOutput(BaseModel):
|
||||
industry: Literal["stay", "restaurant", "cafe", "salon", "clinic", "fitness", "academy", "attraction"]
|
||||
|
||||
|
||||
async def _resolve_biz_type(place_type: str | None, category: str) -> str:
|
||||
"""크롤링에서 감지된 place_type을 우선 사용하고, 없으면 AI 분류로 판단."""
|
||||
if place_type in ("accommodation", "restaurant"):
|
||||
return place_type
|
||||
if not category:
|
||||
return "place"
|
||||
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"다음은 네이버 지도의 업종 카테고리 값입니다: '{category}'\n"
|
||||
"이 업종이 숙박업(accommodation), 음식점(restaurant), 그 외(place) 중 어디에 해당하는지 분류하세요."
|
||||
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=_BizTypeOutput,
|
||||
output_format=_IndustryOutput,
|
||||
model="gpt-4o-mini",
|
||||
img_url=None,
|
||||
image_detail_high=False,
|
||||
)
|
||||
return result.biz_type
|
||||
return result.industry
|
||||
except Exception as e:
|
||||
logger.warning(f"[biz_type] AI 분류 실패, 기본값 place 반환: {e}")
|
||||
return "place"
|
||||
|
||||
|
||||
def _select_marketing_prompt(biz_type: str):
|
||||
if biz_type == "restaurant":
|
||||
return restaurant_marketing_prompt
|
||||
return marketing_prompt
|
||||
logger.warning(f"[industry] AI 분류 실패, 빈 값 반환: {e}")
|
||||
return ""
|
||||
|
||||
|
||||
@router.post(
|
||||
@@ -262,19 +265,19 @@ async def _crawling_logic(
|
||||
customer_name = scraper.base_info.get("name", "")
|
||||
category = scraper.base_info.get("category", "")
|
||||
region = _extract_region_from_address(road_address, jibun_address)
|
||||
biz_type = await _resolve_biz_type(scraper.place_type, category)
|
||||
industry = await _resolve_industry(category, customer_name)
|
||||
|
||||
processed_info = ProcessedInfo(
|
||||
customer_name=customer_name,
|
||||
region=region,
|
||||
detail_region_info=road_address or jibun_address or "",
|
||||
biz_type=biz_type,
|
||||
industry=industry,
|
||||
)
|
||||
|
||||
step2_elapsed = (time.perf_counter() - step2_start) * 1000
|
||||
logger.info(
|
||||
f"[crawling] Step 2 완료 - {customer_name}, {region}, "
|
||||
f"category={category!r}, place_type={scraper.place_type!r}, biz_type={biz_type} ({step2_elapsed:.1f}ms)"
|
||||
f"category={category!r}, place_type={scraper.place_type!r}, industry={industry!r} ({step2_elapsed:.1f}ms)"
|
||||
)
|
||||
|
||||
# ========== Step 3: ChatGPT 마케팅 분석 ==========
|
||||
@@ -288,15 +291,15 @@ async def _crawling_logic(
|
||||
"customer_name": customer_name,
|
||||
"region": region,
|
||||
"detail_region_info": road_address or "",
|
||||
"industry": industry, # 통합 프롬프트 내부 분기용 업종 enum
|
||||
}
|
||||
|
||||
# Step 3-2: GPT API 호출 → 구조화된 마케팅 분석 결과 반환
|
||||
selected_prompt = _select_marketing_prompt(biz_type)
|
||||
marketing_analysis = await chatgpt_service.generate_structured_output(
|
||||
selected_prompt, input_marketing_data
|
||||
marketing_prompt, input_marketing_data
|
||||
)
|
||||
|
||||
# Step 3-3: 분석 결과 DB 저장
|
||||
# Step 3-3: 분석 결과 DB 저장 (industry는 Project로 흐르므로 여기엔 미저장)
|
||||
marketing_intel = MarketingIntel(
|
||||
place_id=scraper.place_id,
|
||||
intel_result=marketing_analysis.model_dump(),
|
||||
@@ -352,7 +355,7 @@ async def _crawling_logic(
|
||||
"processed_info": processed_info,
|
||||
"marketing_analysis": marketing_analysis,
|
||||
"m_id": m_id,
|
||||
"biz_type": biz_type if 'biz_type' in locals() else "place",
|
||||
"industry": industry if 'industry' in locals() else "",
|
||||
}
|
||||
|
||||
|
||||
@@ -390,14 +393,19 @@ async def manual_marketing(
|
||||
# Step 2: GPT API 호출 → 마케팅 분석 결과 생성
|
||||
# place_id 없이 업체명+주소만으로 분석 (크롤링 없이 직접 입력된 경우)
|
||||
chatgpt_service = ChatgptService()
|
||||
# 요청에 industry가 있으면 사용, 없으면 업체명 기반 AI 분류
|
||||
industry = request_body.industry or await _resolve_industry(
|
||||
"", request_body.store_name
|
||||
)
|
||||
processed_info.industry = industry
|
||||
input_marketing_data = {
|
||||
"customer_name": request_body.store_name,
|
||||
"region": region,
|
||||
"detail_region_info": request_body.address,
|
||||
"industry": industry, # 통합 프롬프트 내부 분기용 업종 enum
|
||||
}
|
||||
selected_prompt = _select_marketing_prompt(request_body.biz_type)
|
||||
marketing_analysis = await chatgpt_service.generate_structured_output(
|
||||
selected_prompt, input_marketing_data
|
||||
marketing_prompt, input_marketing_data
|
||||
)
|
||||
|
||||
# Step 3: 분석 결과 DB 저장 (place_id=None — 네이버 장소와 연결되지 않음)
|
||||
@@ -431,7 +439,7 @@ async def manual_marketing(
|
||||
processed_info=processed_info,
|
||||
marketing_analysis=marketing_analysis,
|
||||
m_id=m_id,
|
||||
biz_type=request_body.biz_type,
|
||||
industry=industry,
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user