이미지 크롤링 로직 변경 및 자막 이미지 매칭 보완

This commit is contained in:
skkim committed 2026-07-03 11:46:32 +09:00
1 parent 04d8614919
commit 46449a7a3f
20 files changed
+1828 -1116

No files matched your search

+182 -37
View File
@@ -35,6 +35,8 @@ class NvMapScraper:
GRAPHQL_URL: str = "https://pcmap-api.place.naver.com/graphql"
REQUEST_TIMEOUT = 120 # 초
data_source_identifier = "nv"
SUPPLEMENT_THRESHOLD = 30 # 업체 사진이 이 수 미만일 때 방문자 사진으로 보충
MAX_IMAGES = 50 # 업체+방문자 사진 합산 최대 장수
OVERVIEW_QUERY: str = """
query getAccommodation($id: String!, $deviceType: String) {
business: placeDetail(input: {id: $id, isNx: true, deviceType: $deviceType}) {
@@ -51,7 +53,15 @@ query getAccommodation($id: String!, $deviceType: String) {
visitorReviewsTotal
}
images { images { origin url } }
cpImages(source: [ugcImage]) { images { origin url } }
}
}"""
PHOTO_VIEWER_QUERY: str = """
query getPhotoViewerItems($input: PhotoViewerInput) {
photoViewer(input: $input) {
photos {
originalUrl
}
}
}"""
@@ -84,10 +94,11 @@ query getVisitorReviewStats($id: String!) {
)
self.scrap_type: str | None = None
self.rawdata: dict | None = None
self.image_link_list: list[str] | None = None
self.image_link_list: list[dict] | None = None # [{"preview": str, "original": str}]
self.owner_images: list[dict] | None = None # 업체 등록 사진 (마케팅 필터 제외 대상)
self.extra_photo_urls: list[dict] | None = None # 방문자/AI View 보충 사진 (마케팅 필터 대상)
self.base_info: dict | 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:
@@ -96,6 +107,62 @@ query getVisitorReviewStats($id: String!) {
headers["Cookie"] = self.cookies
return headers
_GIF_PATTERN = re.compile(r"\.gif(?:/|$)", re.IGNORECASE)
@classmethod
def _is_gif_url(cls, url: str) -> bool:
"""URL의 확장자가 gif인지 확인한다.
네이버 CDN은 리사이즈 파라미터를 확장자 뒤에 경로 세그먼트로 붙인다
(예: ".../3982000924.gif/500x500") — endswith(".gif")로는 잡히지 않으므로
경로 세그먼트 단위로 ".gif" 뒤에 "/" 또는 문자열 끝이 오는지 검사한다.
"""
return bool(cls._GIF_PATTERN.search(url))
@staticmethod
def _extract_origins(image_node: dict) -> list[dict]:
"""GraphQL 이미지 노드({ images: [{origin, url}, ...] })에서 {preview, original} 목록을 추출한다.
origin = 원본(업로드용), url = CDN 리사이즈(미리보기용)
"""
items = image_node.get("images") or []
return [
{"preview": item.get("url") or item["origin"], "original": item["origin"]}
for item in items
if item.get("origin") and not NvMapScraper._is_gif_url(item["origin"])
]
@staticmethod
def _extract_photo_viewer_urls(photo_viewer_raw: dict | None) -> list[dict]:
"""getPhotoViewerItems 응답에서 {preview, original} 목록을 추출한다.
photoViewer는 썸네일 필드가 없으므로 preview = original 동일하게 사용.
"""
photos = ((photo_viewer_raw or {}).get("data") or {}).get("photoViewer") or {}
items = photos.get("photos") or []
return [
{"preview": p["originalUrl"], "original": p["originalUrl"]}
for p in items
if p.get("originalUrl") and not NvMapScraper._is_gif_url(p["originalUrl"])
]
@staticmethod
def _dedup_by_original(images: list[dict]) -> list[dict]:
"""{"preview","original"} dict 리스트를 original URL 기준으로 순서를 유지한 채 중복 제거한다."""
seen: set[str] = set()
result = []
for img in images:
original = img.get("original")
if original and original not in seen:
seen.add(original)
result.append(img)
return result
@staticmethod
def _interleave(a: list, b: list) -> list:
"""두 리스트를 1:1 교차 병합한다. 남은 항목은 뒤에 붙인다."""
result = [x for pair in zip(a, b) for x in pair]
longer = a[len(b):] if len(a) > len(b) else b[len(a):]
return result + longer
async def parse_url(self) -> str:
"""URL에서 place ID를 추출합니다. 단축 URL인 경우 실제 URL로 변환합니다."""
place_pattern = r"/place/(\d+)"
@@ -114,9 +181,6 @@ query getVisitorReviewStats($id: String!) {
# place.naver.com/{type}/{id} 형식 (예: m.place.naver.com/restaurant/11667161)
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:
raise URLNotFoundException("Failed to parse place ID from URL")
@@ -144,7 +208,7 @@ query getVisitorReviewStats($id: String!) {
# self.scrap_type = "GraphQL-Browser"
# ── 실제 브라우저로 WTM 캡차 우회 ──
data, stats_data = await self._scrap_via_browser(place_id)
data, stats_data, extra_photo_urls = await self._scrap_via_browser(place_id)
fac_data = None # 편의시설(HTML)은 브라우저 경로에서 생략 (best-effort)
self.scrap_type = "GraphQL-Browser"
@@ -152,21 +216,41 @@ query getVisitorReviewStats($id: String!) {
# Naver 기준임, 구글 등 다른 데이터 소스의 경우 고유 Identifier 사용할 것.
self.place_id = self.data_source_identifier + place_id
self.rawdata["facilities"] = fac_data
self.image_link_list = [
nv_image["origin"]
for nv_image in data["data"]["business"]["images"]["images"]
]
business = data["data"]["business"]
# 업체 등록 이미지 (마케팅 적합성 필터 제외 대상 — 자체 dedup)
self.owner_images = self._dedup_by_original(self._extract_origins(business.get("images") or {}))
# 방문자/AI View 보충 사진 (마케팅 적합성 필터 대상). owner에 이미 있는 원본은 제외.
owner_originals = {img["original"] for img in self.owner_images}
self.extra_photo_urls = self._dedup_by_original(
[img for img in extra_photo_urls if img["original"] not in owner_originals]
)
# 업체 사진이 임계값 미만이면 내부/외부/리뷰 사진으로 보충
# (필터링 없는 기본 조립. 마케팅 적합성 필터를 적용하려면 호출측에서
# owner_images / extra_photo_urls를 직접 사용해 image_filter.assemble_images로 재조립할 것.)
if len(self.owner_images) < self.SUPPLEMENT_THRESHOLD:
combined = self._dedup_by_original(self.owner_images + self.extra_photo_urls)
logger.info(
f"[NvMapScraper] 업체 사진 {len(self.owner_images)}장 < {self.SUPPLEMENT_THRESHOLD}장 "
f"→ 보충 사진 {len(self.extra_photo_urls)}장 추가 (합산 {len(combined)}장, 상한 {self.MAX_IMAGES}장)"
)
else:
combined = self.owner_images
self.image_link_list = combined[: self.MAX_IMAGES]
self.base_info = data["data"]["business"]["base"]
self.facility_info = fac_data
self.voted_keyword_stats = stats_data
return
async def _scrap_via_browser(self, place_id: str) -> tuple[dict, list[dict] | None]:
async def _scrap_via_browser(self, place_id: str) -> tuple[dict, list[dict] | None, list[str]]:
"""직접 호출이 WTM 캡차에 막힌 경우, 실제 브라우저로 GraphQL을 호출한다.
Returns:
(overview_data, review_stats_details)
(overview_data, review_stats_details, extra_photo_urls)
Raises:
GraphQLException: 브라우저 폴백마저 실패한 경우
@@ -183,32 +267,97 @@ query getVisitorReviewStats($id: String!) {
"variables": {"id": place_id},
"query": self.REVIEW_STATS_QUERY,
}
interior_payload = {
"operationName": "getPhotoViewerItems",
"variables": {
"input": {
"businessId": place_id,
"cursors": [{"id": "aiView"}],
"filter": "AI View",
"subFilter": "INTERIOR",
"dateRange": "",
"excludeAuthorIds": [],
"excludeClipIds": [],
"excludeSection": [],
}
},
"query": self.PHOTO_VIEWER_QUERY,
}
exterior_payload = {
"operationName": "getPhotoViewerItems",
"variables": {
"input": {
"businessId": place_id,
"cursors": [{"id": "aiView"}],
"filter": "AI View",
"subFilter": "EXTERIOR",
"dateRange": "",
"excludeAuthorIds": [],
"excludeClipIds": [],
"excludeSection": [],
}
},
"query": self.PHOTO_VIEWER_QUERY,
}
review_payload = {
"operationName": "getPhotoViewerItems",
"variables": {
"input": {
"businessId": place_id,
"cursors": [{"id": "placeReview"}],
"dateRange": "",
"excludeAuthorIds": [],
"excludeClipIds": [],
"excludeSection": [],
}
},
"query": self.PHOTO_VIEWER_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}")
payloads = [overview_payload, stats_payload, interior_payload, exterior_payload, review_payload]
MAX_RETRY = 3
results = None
last_error: Exception | None = None
for attempt in range(1, MAX_RETRY + 1):
try:
results = await NvMapPwScraper.fetch_graphql(place_id, payloads)
except Exception as e:
last_error = e
logger.warning(f"[NvMapScraper] 브라우저 폴백 시도 {attempt}/{MAX_RETRY} 오류: {e}")
if attempt < MAX_RETRY:
await asyncio.sleep(1)
continue
if results and results[0] is not None and "data" in results[0]:
break
logger.warning(f"[NvMapScraper] 브라우저 폴백 시도 {attempt}/{MAX_RETRY} 실패(405 등), 재시도")
results = None
if attempt < MAX_RETRY:
await asyncio.sleep(1)
if not results or results[0] is None or "data" not in results[0]:
if last_error:
raise GraphQLException(f"브라우저 폴백 실패: {last_error}")
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
_vrs = (stats_raw.get("data") or {}).get("visitorReviewStats") or {}
_analysis = _vrs.get("analysis") or {}
_voted = _analysis.get("votedKeyword") or {}
stats_data = _voted.get("details") or None
interior_urls = self._extract_photo_viewer_urls(results[2] if len(results) > 2 else None)
exterior_urls = self._extract_photo_viewer_urls(results[3] if len(results) > 3 else None)
review_urls = self._extract_photo_viewer_urls(results[4] if len(results) > 4 else None)
extra_photo_urls = self._interleave(interior_urls, exterior_urls) + review_urls
logger.info(
f"[NvMapScraper] 보충 이미지 - 내부:{len(interior_urls)} 외부:{len(exterior_urls)} 리뷰:{len(review_urls)}"
)
logger.info(f"[NvMapScraper] 브라우저 폴백 SUCCESS - place_id: {place_id}")
return data, stats_data
return data, stats_data, extra_photo_urls
async def _call_get_accommodation(self, place_id: str) -> dict:
"""GraphQL API를 호출하여 숙소 정보를 가져옵니다.
@@ -281,14 +430,10 @@ query getVisitorReviewStats($id: String!) {
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
_vrs = (result.get("data") or {}).get("visitorReviewStats") or {}
_analysis = _vrs.get("analysis") or {}
_voted = _analysis.get("votedKeyword") or {}
return _voted.get("details") or None
except Exception as e:
logger.warning(f"[NvMapScraper] Failed to get review stats: {e}")
return None
@@ -302,7 +447,7 @@ query getVisitorReviewStats($id: String!) {
Returns:
편의시설 정보 문자열 또는 None
"""
place_types = ["accommodation", "restaurant"]
place_types = ["place", "accommodation", "restaurant"]
try:
async with aiohttp.ClientSession() as session:
for place_type in place_types: