업체명+URL 검색 통합 및 요식업종 가하도록 추가
This commit is contained in:
1 parent
d1fe7fcd5f
commit
009b1a5d09
12 files changed
+136
-276
No files matched your search
@@ -2,7 +2,9 @@ import json
|
||||
import time
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
import aiofiles
|
||||
@@ -36,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
|
||||
from app.utils.prompts.prompts import marketing_prompt, restaurant_marketing_prompt
|
||||
from app.utils.address_parser import extract_region_from_address
|
||||
from app.utils.autotag import autotag_images
|
||||
from config import MEDIA_ROOT
|
||||
@@ -48,18 +50,19 @@ router = APIRouter()
|
||||
|
||||
@router.get(
|
||||
"/search/accommodation",
|
||||
summary="숙박/펜션 자동완성 검색",
|
||||
summary="장소 자동완성 검색 (숙박/음식점 등)",
|
||||
description="""
|
||||
네이버 지역 검색 API를 이용한 숙박/펜션 자동완성 검색입니다.
|
||||
네이버 지역 검색 API를 이용한 장소 자동완성 검색입니다.
|
||||
|
||||
## 요청 파라미터
|
||||
- **query**: 검색어 (필수)
|
||||
- **category**: 카테고리 ("accommodation" | "restaurant", 기본값: 전체)
|
||||
|
||||
## 반환 정보
|
||||
- **query**: 검색어
|
||||
- **count**: 검색 결과 수 (최대 10개)
|
||||
- **items**: 검색 결과 목록
|
||||
- **title**: 숙소명 (HTML 태그 포함 가능)
|
||||
- **title**: 장소명 (HTML 태그 포함 가능)
|
||||
- **address**: 지번 주소
|
||||
- **roadAddress**: 도로명 주소
|
||||
""",
|
||||
@@ -72,7 +75,7 @@ router = APIRouter()
|
||||
async def search_accommodation(
|
||||
query: str,
|
||||
) -> AccommodationSearchResponse:
|
||||
"""숙박/펜션 자동완성 검색"""
|
||||
"""장소 자동완성 검색 (숙박/음식점 등)"""
|
||||
results = await naver_search_client.search_accommodation(
|
||||
query=query,
|
||||
display=10,
|
||||
@@ -91,6 +94,41 @@ 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"]
|
||||
|
||||
|
||||
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"
|
||||
try:
|
||||
chatgpt = ChatgptService()
|
||||
prompt = (
|
||||
f"다음은 네이버 지도의 업종 카테고리 값입니다: '{category}'\n"
|
||||
"이 업종이 숙박업(accommodation), 음식점(restaurant), 그 외(place) 중 어디에 해당하는지 분류하세요."
|
||||
)
|
||||
result = await chatgpt._call_pydantic_output_chat_completion(
|
||||
prompt=prompt,
|
||||
output_format=_BizTypeOutput,
|
||||
model="gpt-4o-mini",
|
||||
img_url=None,
|
||||
image_detail_high=False,
|
||||
)
|
||||
return result.biz_type
|
||||
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
|
||||
|
||||
|
||||
@router.post(
|
||||
"/crawling",
|
||||
summary="네이버 지도 크롤링",
|
||||
@@ -222,17 +260,21 @@ async def _crawling_logic(
|
||||
road_address = scraper.base_info.get("roadAddress", "")
|
||||
jibun_address = scraper.base_info.get("address", "")
|
||||
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)
|
||||
|
||||
processed_info = ProcessedInfo(
|
||||
customer_name=customer_name,
|
||||
region=region,
|
||||
detail_region_info=road_address or jibun_address or "",
|
||||
biz_type=biz_type,
|
||||
)
|
||||
|
||||
step2_elapsed = (time.perf_counter() - step2_start) * 1000
|
||||
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}, biz_type={biz_type} ({step2_elapsed:.1f}ms)"
|
||||
)
|
||||
|
||||
# ========== Step 3: ChatGPT 마케팅 분석 ==========
|
||||
@@ -249,8 +291,9 @@ async def _crawling_logic(
|
||||
}
|
||||
|
||||
# Step 3-2: GPT API 호출 → 구조화된 마케팅 분석 결과 반환
|
||||
selected_prompt = _select_marketing_prompt(biz_type)
|
||||
marketing_analysis = await chatgpt_service.generate_structured_output(
|
||||
marketing_prompt, input_marketing_data
|
||||
selected_prompt, input_marketing_data
|
||||
)
|
||||
|
||||
# Step 3-3: 분석 결과 DB 저장
|
||||
@@ -308,7 +351,8 @@ async def _crawling_logic(
|
||||
"image_count": len(scraper.image_link_list) if scraper.image_link_list else 0,
|
||||
"processed_info": processed_info,
|
||||
"marketing_analysis": marketing_analysis,
|
||||
"m_id" : m_id
|
||||
"m_id": m_id,
|
||||
"biz_type": biz_type if 'biz_type' in locals() else "place",
|
||||
}
|
||||
|
||||
|
||||
@@ -351,8 +395,9 @@ async def manual_marketing(
|
||||
"region": region,
|
||||
"detail_region_info": request_body.address,
|
||||
}
|
||||
selected_prompt = _select_marketing_prompt(request_body.biz_type)
|
||||
marketing_analysis = await chatgpt_service.generate_structured_output(
|
||||
marketing_prompt, input_marketing_data
|
||||
selected_prompt, input_marketing_data
|
||||
)
|
||||
|
||||
# Step 3: 분석 결과 DB 저장 (place_id=None — 네이버 장소와 연결되지 않음)
|
||||
@@ -386,6 +431,7 @@ async def manual_marketing(
|
||||
processed_info=processed_info,
|
||||
marketing_analysis=marketing_analysis,
|
||||
m_id=m_id,
|
||||
biz_type=request_body.biz_type,
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user