Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a934b52ea6 | ||
|
|
ac133efe4b | ||
|
|
f2d11ad9d3 | ||
|
|
ea7539ee43 | ||
|
|
059269c5e6 | ||
|
|
b0248a2e63 |
No files matched your search
@@ -101,7 +101,8 @@ CORS_MAX_AGE=600 # Preflight 요청 캐시 시간 (초)
|
||||
# ================================
|
||||
# Azure Blob Storage 설정
|
||||
# ================================
|
||||
AZURE_BLOB_SAS_TOKEN=your_sas_token # Azure Blob Storage SAS 토큰
|
||||
AZURE_BLOB_SAS_TOKEN=your_sas_token # 업로드·삭제용 SAS 토큰 (서버 내부 전용)
|
||||
AZURE_BLOB_PLAYBACK_SAS_TOKEN=your_readonly_sas_token # 재생 URL에 붙는 읽기 전용(sp=r) SAS 토큰
|
||||
AZURE_BLOB_BASE_URL=https://... # Azure Blob Storage 기본 URL
|
||||
|
||||
# ================================
|
||||
|
||||
+256
-71
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
from html import unescape
|
||||
@@ -11,6 +12,10 @@ from app.utils.logger import get_logger
|
||||
# 로거 설정
|
||||
logger = get_logger("pwscraper")
|
||||
|
||||
# 주소 동일 위치 판정용 키 패턴: '삼성로85길 26', '대치동 891-46'
|
||||
_ROAD_KEY = re.compile(r"([가-힣0-9]+(?:대로|로|길))\s*(\d+(?:-\d+)?)")
|
||||
_JIBUN_KEY = re.compile(r"([가-힣0-9]+(?:동|리|가|읍|면))\s*(\d+(?:-\d+)?)")
|
||||
|
||||
class NvMapPwScraper():
|
||||
# cls vars
|
||||
is_ready = False
|
||||
@@ -22,6 +27,9 @@ class NvMapPwScraper():
|
||||
_max_retry = 3
|
||||
_timeout = 30 # place id timeout threshold seconds
|
||||
_retry_delay_ms = 1500 # 검색 실패 후 재시도 전 대기시간 (네이버 요청 밀도 완화)
|
||||
_MIN_NAME_SCORE = 0.6 # 후보 선정 시 이름 유사도 하한 (미달이면 다른 업체로 간주)
|
||||
_TIE_MARGIN = 0.02 # 1·2위 후보의 종합 점수 차가 이 값 미만이면 모호하다고 보고 선정하지 않는다
|
||||
_last_search_conclusive = False # 마지막 _try_search 가 검색 응답을 받아 판단까지 마쳤는지(재시도 불필요 여부)
|
||||
|
||||
# UA·뷰포트·sec-ch-ua를 한 세트로 묶은 브라우저 프로필 후보군 (안티봇 핑거프린트 회피용)
|
||||
_UA_PROFILES = [
|
||||
@@ -325,6 +333,13 @@ if (originalQuery) {
|
||||
logger.debug(f"[DEBUG] pcmap frame content 추출 실패: {e}")
|
||||
return []
|
||||
|
||||
# 1차: iframe HTML에도 list 응답과 같은 __APOLLO_STATE__ 가 들어 있다 (주소 포함, 최대 70개)
|
||||
apollo_candidates = self._parse_list_candidates(html)
|
||||
if apollo_candidates:
|
||||
logger.debug(f"[DEBUG] iframe Apollo state 후보 {len(apollo_candidates)}개 추출")
|
||||
return apollo_candidates
|
||||
|
||||
# 2차: Apollo state가 없을 때만 정규식으로 id/name 쌍 추출 (주소 없음)
|
||||
# {"id":"11659052","name":"프레지던트 호텔",...} 형태의 JSON 쌍 추출
|
||||
pair_pattern = re.compile(
|
||||
r'"id"\s*:\s*"(\d{5,})"[^}]{0,200}?"name"\s*:\s*"([^"]{1,60})"'
|
||||
@@ -352,18 +367,36 @@ if (originalQuery) {
|
||||
return candidates
|
||||
|
||||
@staticmethod
|
||||
def _parse_allsearch_candidates(body: dict) -> list[dict]:
|
||||
"""allSearch 응답 JSON에서 후보 목록을 추출한다."""
|
||||
place_list = (((body.get("result") or {}).get("place") or {}).get("list")) or []
|
||||
def _parse_list_candidates(html: str) -> list[dict]:
|
||||
"""검색 결과 list 응답 HTML의 window.__APOLLO_STATE__ 에서 후보 목록을 추출한다.
|
||||
|
||||
roadAddress 에는 시·도가 포함된 fullAddress 를 채운다 (자동완성 항목의 도로명 주소와
|
||||
같은 형식이어야 주소 유사도 비교가 성립한다).
|
||||
"""
|
||||
marker = "window.__APOLLO_STATE__ ="
|
||||
idx = html.find(marker)
|
||||
if idx < 0:
|
||||
return []
|
||||
brace = html.find("{", idx)
|
||||
if brace < 0:
|
||||
return []
|
||||
try:
|
||||
state, _ = json.JSONDecoder().raw_decode(html[brace:])
|
||||
except ValueError:
|
||||
logger.warning("[NvMapPwScraper] __APOLLO_STATE__ JSON 파싱 실패")
|
||||
return []
|
||||
|
||||
return [
|
||||
{
|
||||
"title": p.get("name") or "",
|
||||
"place_url": f"https://map.naver.com/p/entry/place/{p['id']}",
|
||||
"roadAddress": p.get("roadAddress") or "",
|
||||
"address": p.get("address") or "",
|
||||
"title": item.get("name") or "",
|
||||
"place_url": f"https://map.naver.com/p/entry/place/{item['id']}",
|
||||
"roadAddress": item.get("fullAddress") or item.get("roadAddress") or "",
|
||||
"address": item.get("address") or "",
|
||||
}
|
||||
for p in place_list
|
||||
if p.get("id")
|
||||
for key, item in state.items()
|
||||
if key.startswith("PlaceListBusinessesItem:")
|
||||
and isinstance(item, dict)
|
||||
and item.get("id")
|
||||
]
|
||||
|
||||
def _select_best_candidate(self, candidates: list[dict], title: str, address: str) -> dict | None:
|
||||
@@ -384,22 +417,114 @@ if (originalQuery) {
|
||||
|
||||
return max(candidates, key=lambda c: c["_total_score"])
|
||||
|
||||
async def _capture_allsearch(self, url: str, timeout_s: float = 5.0) -> list[dict]:
|
||||
"""검색 페이지가 자연 발생시키는 allSearch API 응답을 캡처해 후보 목록으로 변환한다.
|
||||
@staticmethod
|
||||
def _address_keys(address: str) -> set[str]:
|
||||
"""주소에서 '도로명+번호' / '지번동+번호' 키를 추출한다 (예: '삼성로85길 26', '대치동 891-46').
|
||||
|
||||
pcmap iframe 렌더링을 기다릴 필요가 없어 경쟁 조건이 없고, 업체명 단독
|
||||
검색처럼 iframe 자체가 생성되지 않는 케이스에서도 동작한다.
|
||||
문자열 유사도는 같은 도로의 다른 번호(삼성로85길 11 vs 26)도 높게 평가하므로,
|
||||
동일 위치 판정은 이 키의 일치 여부로 한다.
|
||||
"""
|
||||
captured: list[dict] = []
|
||||
keys = set()
|
||||
for pattern in (_ROAD_KEY, _JIBUN_KEY):
|
||||
for m in pattern.finditer(address or ""):
|
||||
keys.add(f"{m.group(1)} {m.group(2)}")
|
||||
return keys
|
||||
|
||||
def _pick_verified_candidate(
|
||||
self, candidates: list[dict], title: str, address: str, jibun: str = ""
|
||||
) -> dict | None:
|
||||
"""후보를 점수화한 뒤 검증을 통과한 후보만 반환한다. 확신할 수 없으면 None (오선정 방지).
|
||||
|
||||
1. 이름 유사도가 하한(_MIN_NAME_SCORE) 미만이면 제외
|
||||
2. 선택 주소와 후보 주소의 '도로명+번호'/'지번+번호' 키가 하나도 겹치지 않으면 제외
|
||||
3. 남은 후보의 점수 차가 _TIE_MARGIN 미만이면 모호하므로 거부
|
||||
4. 주소로 검증할 수 없는 경우(선택 주소 없음 / 후보에 주소 없음)는
|
||||
이름이 정확히 일치하는 후보가 단 하나일 때만 허용
|
||||
"""
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
# 후보별 _name_score/_addr_score/_total_score 를 채운다 (반환값은 사용하지 않음)
|
||||
self._select_best_candidate(candidates, title, address)
|
||||
|
||||
eligible = [c for c in candidates if c["_name_score"] >= self._MIN_NAME_SCORE]
|
||||
if not eligible:
|
||||
top = max(candidates, key=lambda c: c["_name_score"])
|
||||
logger.warning(
|
||||
f"[AUTO-SELECT] 이름 유사도 하한({self._MIN_NAME_SCORE}) 미달: '{title}' "
|
||||
f"(후보 {len(candidates)}개, 최고 '{self._clean_title(top['title'])}' "
|
||||
f"name={top['_name_score']:.2f}, addr='{top.get('roadAddress') or top.get('address') or ''}')"
|
||||
)
|
||||
return None
|
||||
|
||||
wanted = self._address_keys(address) | self._address_keys(jibun)
|
||||
with_addr = [
|
||||
c for c in eligible
|
||||
if self._address_keys(c.get("roadAddress", "")) | self._address_keys(c.get("address", ""))
|
||||
]
|
||||
|
||||
if wanted and with_addr:
|
||||
pool = [
|
||||
c for c in with_addr
|
||||
if wanted & (self._address_keys(c.get("roadAddress", "")) | self._address_keys(c.get("address", "")))
|
||||
]
|
||||
if not pool:
|
||||
logger.warning(f"[AUTO-SELECT] 주소 불일치로 후보 {len(with_addr)}개 모두 제외: '{title}'")
|
||||
return None
|
||||
ranked = sorted(pool, key=lambda c: c["_total_score"], reverse=True)
|
||||
if len(ranked) > 1 and ranked[0]["_total_score"] - ranked[1]["_total_score"] < self._TIE_MARGIN:
|
||||
logger.warning(f"[AUTO-SELECT] 동점 후보 {len(ranked)}개로 선정 불가: '{title}'")
|
||||
return None
|
||||
return ranked[0]
|
||||
|
||||
exact = [c for c in eligible if c["_name_score"] == 1.0]
|
||||
if len(exact) == 1:
|
||||
return exact[0]
|
||||
logger.warning(f"[AUTO-SELECT] 주소 검증 불가 + 이름 정확 일치 후보 {len(exact)}개로 선정 불가: '{title}'")
|
||||
return None
|
||||
|
||||
def _select_and_log(
|
||||
self, candidates: list[dict], title: str, address: str, jibun: str, tag: str = ""
|
||||
) -> str | None:
|
||||
"""검증된 후보를 골라 로그를 남기고 place URL을 반환한다. 선정 불가면 None."""
|
||||
best = self._pick_verified_candidate(candidates, title, address, jibun)
|
||||
if not best:
|
||||
logger.warning(f"[AUTO-SELECT{tag}] 선정 불가 (후보 {len(candidates)}개): '{title}'")
|
||||
return None
|
||||
logger.info(
|
||||
f"[AUTO-SELECT{tag}] '{title}' → '{best['title']}' "
|
||||
f"(name={best['_name_score']:.2f}, addr={best['_addr_score']:.2f}) {best['place_url']}"
|
||||
)
|
||||
return best["place_url"]
|
||||
|
||||
async def _capture_list_candidates(self, url: str, timeout_s: float = 5.0) -> list[dict] | None:
|
||||
"""검색 페이지가 자연 발생시키는 list(pcmap.place.naver.com/*/list) 응답을 캡처해 후보 목록으로 변환한다.
|
||||
|
||||
네이버가 allSearch API를 제거하면서 검색 결과는 list 페이지 HTML의
|
||||
__APOLLO_STATE__ 로만 내려온다. 주소가 섞인 검색어는 주소 검색으로 처리되어
|
||||
장소 목록이 비므로 업체명만으로 검색해야 한다.
|
||||
|
||||
반환값: 후보 목록 / 응답은 받았으나 결과 0건이면 [] / list 응답을 받지 못했으면 None
|
||||
"""
|
||||
captured: list[list[dict]] = []
|
||||
|
||||
def on_response(resp):
|
||||
# GET 요청의 실제 응답만 캡처 (OPTIONS preflight 등 오탐 방지)
|
||||
if "allSearch" in resp.url and resp.request.method == "GET":
|
||||
# GET 200 응답만 캡처 (302 리다이렉트·OPTIONS preflight 오탐 방지)
|
||||
if (
|
||||
"pcmap.place.naver.com" in resp.url
|
||||
and "/list" in resp.url
|
||||
and resp.status == 200
|
||||
and resp.request.method == "GET"
|
||||
):
|
||||
async def _consume():
|
||||
try:
|
||||
captured.append(await resp.json())
|
||||
except Exception:
|
||||
pass
|
||||
html = await resp.text()
|
||||
except Exception as e:
|
||||
logger.warning(f"[NvMapPwScraper] list 응답 읽기 실패: {e}")
|
||||
return
|
||||
# Apollo state 마커가 없으면 목록 응답이 아니다 (차단 페이지 등)
|
||||
if "window.__APOLLO_STATE__" in html:
|
||||
captured.append(self._parse_list_candidates(html))
|
||||
asyncio.create_task(_consume())
|
||||
|
||||
self.page.on("response", on_response)
|
||||
@@ -411,53 +536,104 @@ if (originalQuery) {
|
||||
|
||||
deadline = time.monotonic() + timeout_s
|
||||
while time.monotonic() < deadline:
|
||||
if "/place/" in self.page.url or captured:
|
||||
# 비어 있지 않은 목록이 오거나 /place/ 로 이동하면 종료. 빈 목록만 받았다면
|
||||
# 뒤늦게 다른 업종 list 가 오는지 deadline 까지 기다린다.
|
||||
if "/place/" in self.page.url or any(captured):
|
||||
break
|
||||
await self.page.wait_for_timeout(200)
|
||||
finally:
|
||||
self.page.remove_listener("response", on_response)
|
||||
|
||||
if not captured:
|
||||
return []
|
||||
return self._parse_allsearch_candidates(captured[0])
|
||||
non_empty = next((c for c in captured if c), None)
|
||||
if non_empty is not None:
|
||||
return non_empty
|
||||
return [] if captured else None
|
||||
|
||||
async def _try_search(self, address: str, title: str) -> str | None:
|
||||
"""주어진 주소+업체명으로 검색해서 place URL을 반환한다. 실패 시 None."""
|
||||
encoded_query = parse.quote(f"{address} {title}".strip())
|
||||
@staticmethod
|
||||
def _region_hint(address: str) -> str:
|
||||
"""주소에서 검색어 앞에 붙일 시·군·구 이름을 추출한다 (예: '군산시', '영등포구'). 없으면 빈 문자열.
|
||||
|
||||
'서울특별시' 같은 광역 단위는 제외한다.
|
||||
"""
|
||||
for token in (address or "").split():
|
||||
if re.fullmatch(r"[가-힣]+(?:시|군|구)", token) and not token.endswith(
|
||||
("특별시", "광역시", "특별자치시")
|
||||
):
|
||||
return token
|
||||
return ""
|
||||
|
||||
async def _retry_with_region(self, address: str, title: str, jibun: str) -> str | None:
|
||||
"""업체명만 검색해 이름 불일치로 끝났을 때, 시·군·구를 붙여 한 번 더 검색한다.
|
||||
|
||||
업체명이 일반적이면 네이버가 다른 지역의 동종 업체만 돌려주는 경우가 있다
|
||||
(예: '선유도 리조트' → 서울 여의도의 다른 업체). 후보 검증은 그대로 적용된다.
|
||||
"""
|
||||
region = self._region_hint(address)
|
||||
if not region or region in title:
|
||||
return None
|
||||
query = f"{region} {title}"
|
||||
logger.info(f"[RETRY-REGION] 지역을 붙여 재검색: '{query}'")
|
||||
# 직전 검색 직후 바로 보내면 네이버가 list 응답을 주지 않는 경우가 있어 간격을 둔다
|
||||
await self.page.wait_for_timeout(self._retry_delay_ms)
|
||||
result = await self._try_search(address, title, jibun, query=query)
|
||||
if not result and not self._last_search_conclusive:
|
||||
# 응답 자체가 없으면 세션 단위 제한일 수 있다 → 컨텍스트를 새로 만들어 1회만 재시도
|
||||
logger.warning(f"[RETRY-REGION] 응답 없음 → 컨텍스트 재생성 후 재시도: '{query}'")
|
||||
await self.page.close()
|
||||
await self._recreate_context()
|
||||
await self.create_page()
|
||||
result = await self._try_search(address, title, jibun, query=query)
|
||||
if not result:
|
||||
# 응답 수신 여부로 '네이버가 응답을 안 줌'과 '응답은 왔으나 일치 업체 없음'을 구분한다
|
||||
state = "응답 수신, 일치 업체 없음" if self._last_search_conclusive else "응답 없음"
|
||||
logger.warning(f"[RETRY-REGION] 실패 ({state}): '{query}'")
|
||||
return result
|
||||
|
||||
async def _try_search(
|
||||
self, address: str, title: str, jibun: str = "", query: str | None = None
|
||||
) -> str | None:
|
||||
"""업체명으로 검색해 후보를 받고, 검증을 통과한 후보의 place URL을 반환한다. 실패 시 None.
|
||||
|
||||
검색어에는 주소를 넣지 않는다 (주소가 섞이면 네이버가 주소 검색으로 처리해 장소 목록이 비어 있음).
|
||||
query 가 주어지면 검색어로만 쓰이고, 이름 유사도 검증은 항상 title 기준이다.
|
||||
address/jibun 은 후보 검증(_pick_verified_candidate)에만 사용한다.
|
||||
|
||||
검색 응답을 받아 판단까지 마쳤다면(결과 0건 / 검증 실패 포함) _last_search_conclusive 를 True 로
|
||||
남긴다. 재시도해도 결과가 달라지지 않으므로 호출자가 재시도를 생략하는 데 사용한다.
|
||||
"""
|
||||
self._last_search_conclusive = False
|
||||
encoded_query = parse.quote(query or title)
|
||||
url = f"https://map.naver.com/p/search/{encoded_query}"
|
||||
|
||||
# 1순위: allSearch API 응답 캡처 (iframe 렌더링 대기 불필요, 업체명 단독 검색도 지원)
|
||||
candidates = await self._capture_allsearch(url)
|
||||
# 1순위: list 응답 캡처 (__APOLLO_STATE__ 파싱)
|
||||
candidates = await self._capture_list_candidates(url)
|
||||
if "/place/" in self.page.url:
|
||||
return self.page.url
|
||||
|
||||
if candidates:
|
||||
best = self._select_best_candidate(candidates, title, address)
|
||||
logger.info(
|
||||
f"[AUTO-SELECT] '{title}' → '{best['title']}' "
|
||||
f"(name={best['_name_score']:.2f}, addr={best['_addr_score']:.2f}) {best['place_url']}"
|
||||
)
|
||||
return best['place_url']
|
||||
if candidates is not None:
|
||||
self._last_search_conclusive = True
|
||||
if not candidates:
|
||||
logger.warning(f"[AUTO-SELECT] 검색 결과 0건: '{title}'")
|
||||
return None
|
||||
return self._select_and_log(candidates, title, address, jibun)
|
||||
|
||||
# 2순위(안전망): allSearch 캡처 실패 시 기존 iframe HTML 파싱 방식으로 폴백
|
||||
# ── 잠시 비활성화 ──
|
||||
# logger.warning("[FALLBACK] allSearch 캡처 실패 → iframe 파싱 방식 시도")
|
||||
# iframe_candidates = []
|
||||
# for _ in range(3): # 500ms × 3 = 최대 1.5초
|
||||
# if "/place/" in self.page.url:
|
||||
# return self.page.url
|
||||
# iframe_candidates = await self._extract_candidates_from_list_page()
|
||||
# if iframe_candidates:
|
||||
# break
|
||||
# await self.page.wait_for_timeout(500)
|
||||
#
|
||||
# if iframe_candidates:
|
||||
# best = self._select_best_candidate(iframe_candidates, title, address)
|
||||
# logger.info(
|
||||
# f"[AUTO-SELECT-IFRAME] '{title}' → '{best['title']}' "
|
||||
# f"(name={best['_name_score']:.2f}, addr={best['_addr_score']:.2f}) {best['place_url']}"
|
||||
# )
|
||||
# return best['place_url']
|
||||
# 2순위(안전망): list 응답을 받지 못했을 때 렌더된 iframe HTML 에서 후보 추출
|
||||
logger.warning(
|
||||
f"[FALLBACK] list 응답 캡처 실패 → iframe 파싱 방식 시도 "
|
||||
f"(query='{query or title}', page_url={self.page.url[:120]})"
|
||||
)
|
||||
iframe_candidates = []
|
||||
for _ in range(10): # 500ms × 10 = 최대 5초 (iframe 렌더링은 4~7초까지 걸릴 수 있음)
|
||||
if "/place/" in self.page.url:
|
||||
return self.page.url
|
||||
iframe_candidates = await self._extract_candidates_from_list_page()
|
||||
if iframe_candidates:
|
||||
break
|
||||
await self.page.wait_for_timeout(500)
|
||||
|
||||
if iframe_candidates:
|
||||
self._last_search_conclusive = True
|
||||
return self._select_and_log(iframe_candidates, title, address, jibun, "-IFRAME")
|
||||
|
||||
# isCorrectAnswer=true 로 강제 단일결과 재시도 (원본 로직 유지)
|
||||
correct_url = self.page.url.replace("?", "?isCorrectAnswer=true&")
|
||||
@@ -475,38 +651,47 @@ if (originalQuery) {
|
||||
|
||||
async def get_place_id_url(self, selected):
|
||||
title = self._clean_title(selected['title'])
|
||||
address = self._clean_title(selected.get('roadAddress', selected['address']))
|
||||
# roadAddress 가 빈 문자열/None 이면 지번 주소로 대체 (dict.get 기본값은 키가 있으면 적용되지 않음)
|
||||
jibun = self._clean_title(selected.get('address') or '')
|
||||
address = self._clean_title(selected.get('roadAddress') or selected.get('address') or '')
|
||||
|
||||
# 1차 시도: 원본 주소 + 업체명
|
||||
logger.debug(f"[DEBUG] 1차 시도 - address: {address}")
|
||||
result = await self._try_search(address, title)
|
||||
# 1차 시도: 업체명 검색 + 주소 검증으로 후보 선정
|
||||
logger.debug(f"[DEBUG] 1차 시도 - title: {title}, address: {address}")
|
||||
result = await self._try_search(address, title, jibun)
|
||||
if result:
|
||||
return result
|
||||
|
||||
# 2차 시도: 정제 주소 + 업체명
|
||||
refined = self._refine_address(address)
|
||||
if refined != address:
|
||||
await self.page.wait_for_timeout(self._retry_delay_ms)
|
||||
logger.info(f"[REFINE] 주소 정제: '{address}' → '{refined}'")
|
||||
result = await self._try_search(refined, title)
|
||||
if self._last_search_conclusive:
|
||||
result = await self._retry_with_region(address, title, jibun)
|
||||
if result:
|
||||
return result
|
||||
logger.warning(f"[NOT-FOUND] 검색 응답은 받았으나 일치하는 업체 없음 → 재시도 생략: '{title}'")
|
||||
return None
|
||||
|
||||
# 3차 시도: 업체명만으로 검색
|
||||
# 2차 시도: 일시적 실패 대비 재시도
|
||||
await self.page.wait_for_timeout(self._retry_delay_ms)
|
||||
logger.info(f"[RETRY] 업체명만으로 재시도: '{title}'")
|
||||
result = await self._try_search("", title)
|
||||
logger.info(f"[RETRY] 재시도: '{title}'")
|
||||
result = await self._try_search(address, title, jibun)
|
||||
if result:
|
||||
return result
|
||||
if self._last_search_conclusive:
|
||||
result = await self._retry_with_region(address, title, jibun)
|
||||
if result:
|
||||
return result
|
||||
logger.warning(f"[NOT-FOUND] 검색 응답은 받았으나 일치하는 업체 없음 → 재시도 생략: '{title}'")
|
||||
return None
|
||||
|
||||
# 1~3차 모두 실패 → 네이버 안티봇 차단 의심, 컨텍스트 재생성 후 원본 조건으로 1회 재시도
|
||||
logger.warning(f"[BLOCK-SUSPECTED] 3회 시도 모두 실패 → 컨텍스트 재생성 후 재시도: '{title}'")
|
||||
# 1~2차 모두 실패 → 네이버 안티봇 차단 의심, 컨텍스트 재생성 후 1회 재시도
|
||||
logger.warning(f"[BLOCK-SUSPECTED] 2회 시도 모두 실패 → 컨텍스트 재생성 후 재시도: '{title}'")
|
||||
await self.page.close()
|
||||
await self._recreate_context()
|
||||
await self.create_page()
|
||||
result = await self._try_search(address, title)
|
||||
result = await self._try_search(address, title, jibun)
|
||||
if result:
|
||||
return result
|
||||
if self._last_search_conclusive:
|
||||
result = await self._retry_with_region(address, title, jibun)
|
||||
if result:
|
||||
return result
|
||||
|
||||
logger.error(f"[ERROR] Not found url for {selected}")
|
||||
return None
|
||||
@@ -91,16 +91,20 @@ async def close_shared_blob_client() -> None:
|
||||
|
||||
|
||||
def to_playback_url(blob_url: str | None) -> str | None:
|
||||
"""DB에 저장된 SAS 미포함 공개 URL에 읽기용 SAS 토큰을 붙여 반환합니다.
|
||||
"""DB에 저장된 SAS 미포함 공개 URL에 읽기 전용 SAS 토큰을 붙여 반환합니다.
|
||||
|
||||
Azure Blob 익명(공개) 접근은 x-ms-version 헤더가 없어 Range 요청을 지원하지
|
||||
않는 구버전 API로 처리되어 브라우저에서 영상/오디오 seek이 동작하지 않는다.
|
||||
SAS 토큰(sv= 포함)을 붙이면 최신 API 버전으로 처리되어 Range/Accept-Ranges가
|
||||
정상 동작한다. DB에는 SAS 없는 URL을 그대로 저장하고, 응답 시점에만 붙인다.
|
||||
|
||||
이 URL은 API 응답으로 나가므로 재생용 토큰(AZURE_BLOB_PLAYBACK_SAS_TOKEN)만
|
||||
쓴다. 미설정이어도 쓰기 권한이 있는 업로드용 토큰으로 대체하지 않고 SAS 없는
|
||||
URL을 그대로 반환한다.
|
||||
"""
|
||||
if not blob_url:
|
||||
return blob_url
|
||||
sas_token = azure_blob_settings.AZURE_BLOB_SAS_TOKEN.strip("?'\"")
|
||||
sas_token = azure_blob_settings.AZURE_BLOB_PLAYBACK_SAS_TOKEN.strip("?'\"")
|
||||
if not sas_token:
|
||||
return blob_url
|
||||
separator = "&" if "?" in blob_url else "?"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import imageio_ffmpeg
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.utils.upload_blob_as_request import AzureBlobUploader
|
||||
@@ -54,7 +55,7 @@ async def extract_first_frame(video_path: str | Path) -> bytes | None:
|
||||
|
||||
try:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"ffmpeg",
|
||||
imageio_ffmpeg.get_ffmpeg_exe(),
|
||||
"-nostdin",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
|
||||
@@ -158,7 +158,11 @@ class AzureBlobSettings(BaseSettings):
|
||||
|
||||
AZURE_BLOB_SAS_TOKEN: str = Field(
|
||||
default="",
|
||||
description="Azure Blob Storage SAS 토큰",
|
||||
description="Azure Blob Storage 업로드·삭제용 SAS 토큰 (서버 내부 전용, 응답에 노출 금지)",
|
||||
)
|
||||
AZURE_BLOB_PLAYBACK_SAS_TOKEN: str = Field(
|
||||
default="",
|
||||
description="재생 URL에 붙여 응답으로 내보내는 읽기 전용(sp=r) SAS 토큰",
|
||||
)
|
||||
AZURE_BLOB_BASE_URL: str = Field(
|
||||
default="https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original",
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
# ffmpeg 운영 반영 가이드
|
||||
|
||||
## 1. 배경
|
||||
|
||||
- **증상**: 영상(썰박스 포함)은 정상적으로 만들어지는데 `poster_url`이 NULL로 저장됩니다. 로그에는 다음 경고가 남습니다.
|
||||
|
||||
```
|
||||
[video_poster] 첫 프레임 추출 중 오류가 발생했습니다 (... error=FileNotFoundError: [Errno 2] No such file or directory)
|
||||
```
|
||||
|
||||
- **원인**: 기능마다 다른 ffmpeg를 썼습니다.
|
||||
- 영상 합성(`generator/*/render.py`, `generator/media.py`)은 pip 패키지 `imageio-ffmpeg`에 들어 있는 ffmpeg를 씁니다. 그래서 별도 설치 없이 정상 동작합니다.
|
||||
- 포스터 추출(`app/utils/video_poster.py`)은 **시스템 PATH의 `ffmpeg`**를 썼습니다. 이미지에 시스템 ffmpeg가 없어서 실패했습니다.
|
||||
|
||||
- **이전에는 왜 됐나**: 컨테이너에 `docker exec`로 직접 설치해서 쓰다가, 컨테이너를 recreate하면서 사라진 것으로 추정됩니다.
|
||||
|
||||
- **영향 범위**: `uvicorn-app`, 그리고 같은 코드를 쓰는 `o2o-ssul-backend`입니다. 호출 위치는 `app/video/worker/video_task.py`와 `app/ssulbox/services/blob_service.py`입니다.
|
||||
|
||||
## 2. 변경 내용
|
||||
|
||||
`app/utils/video_poster.py`가 시스템 `ffmpeg` 대신 영상 합성과 같은 `imageio_ffmpeg.get_ffmpeg_exe()`를 사용하도록 바꿨습니다.
|
||||
|
||||
```diff
|
||||
+import imageio_ffmpeg
|
||||
...
|
||||
- "ffmpeg",
|
||||
+ imageio_ffmpeg.get_ffmpeg_exe(),
|
||||
```
|
||||
|
||||
- `imageio-ffmpeg>=0.5`는 `pyproject.toml`에 이미 의존성으로 들어 있습니다. **새 패키지도, Dockerfile 수정도, 이미지 재빌드도 필요 없습니다.**
|
||||
- 앱 코드의 ffmpeg 호출은 모두 `imageio_ffmpeg`를 쓰게 되어, 시스템 ffmpeg에 의존하는 곳이 없습니다.
|
||||
|
||||
> 이전 가이드의 `docker/gunicorn/Dockerfile`에 `apt-get install ffmpeg`를 추가하는 방법은 더 이상 필요하지 않습니다.
|
||||
|
||||
## 3. 반영 절차
|
||||
|
||||
이 변경은 코드만 바뀌므로 다음 배포에 포함하면 됩니다. 컨테이너가 호스트의 `/www/o2o-castad-backend`를 코드 경로로 쓰는 구성을 전제로 합니다(검증 명령의 작업 경로와 같습니다).
|
||||
|
||||
### 3-1. 사전 확인 (선택)
|
||||
|
||||
```bash
|
||||
# 영상 합성이 쓰는 ffmpeg가 컨테이너에 있는지 확인한다 (이 경로가 포스터 추출에도 쓰인다)
|
||||
docker exec uvicorn-app python -c "import imageio_ffmpeg; print(imageio_ffmpeg.get_ffmpeg_exe())"
|
||||
docker exec o2o-ssul-backend python -c "import imageio_ffmpeg; print(imageio_ffmpeg.get_ffmpeg_exe())"
|
||||
```
|
||||
|
||||
경로가 출력되면 준비된 것입니다. 오류가 나면 `imageio-ffmpeg`가 설치되지 않은 것이므로 `uv pip install .`로 의존성을 맞춰야 합니다.
|
||||
|
||||
### 3-2. 코드 반영
|
||||
|
||||
```bash
|
||||
cd /www/o2o-castad-backend
|
||||
git pull # video_poster.py 변경이 포함된 커밋
|
||||
grep -n "imageio_ffmpeg" app/utils/video_poster.py
|
||||
```
|
||||
|
||||
### 3-3. 컨테이너 재시작 (다운타임 발생, 점검 시간에 진행)
|
||||
|
||||
```bash
|
||||
cd compose
|
||||
docker compose up -d uvicorn-app o2o-ssul-backend
|
||||
```
|
||||
|
||||
- 기동할 때 `uv pip install`과 `playwright install`이 돌아서 서비스가 몇 분 동안 내려갑니다.
|
||||
- 이전에 `docker exec`로 설치해 둔 시스템 ffmpeg는 그대로 두어도 영향이 없습니다(앱이 더 이상 사용하지 않음).
|
||||
|
||||
## 4. 검증
|
||||
|
||||
### 4-1. 함수 단위 확인
|
||||
|
||||
시스템 ffmpeg가 아니라 `imageio_ffmpeg` 바이너리로 테스트 영상을 만들고 첫 프레임을 추출합니다.
|
||||
|
||||
```bash
|
||||
docker exec -i -w /www/o2o-castad-backend uvicorn-app python - <<'PY'
|
||||
import asyncio
|
||||
import subprocess
|
||||
|
||||
import imageio_ffmpeg
|
||||
|
||||
from app.utils.video_poster import extract_first_frame
|
||||
|
||||
subprocess.run(
|
||||
[imageio_ffmpeg.get_ffmpeg_exe(), "-loglevel", "error", "-y",
|
||||
"-f", "lavfi", "-i", "testsrc=size=320x240:rate=10", "-t", "1", "/tmp/poster_test.mp4"],
|
||||
check=True,
|
||||
)
|
||||
frame = asyncio.run(extract_first_frame("/tmp/poster_test.mp4"))
|
||||
print("OK" if frame and frame[:2] == b"\xff\xd8" else "FAIL")
|
||||
PY
|
||||
docker exec uvicorn-app rm -f /tmp/poster_test.mp4
|
||||
```
|
||||
|
||||
`OK`가 출력되어야 합니다(JPEG 시그니처 `FF D8` 확인).
|
||||
|
||||
### 4-2. 실제 영상 생성 후 확인
|
||||
|
||||
```bash
|
||||
docker logs --since 10m uvicorn-app 2>&1 | grep -E "video_poster|generate_ssul_poster"
|
||||
```
|
||||
|
||||
- 실제로 영상을 하나 생성한 뒤 `video.poster_url`(썰박스는 `ssul_content.poster_url`)이 NULL이 아닌지 확인합니다.
|
||||
- `video_poster ... FileNotFoundError` 로그가 더 이상 나오지 않아야 합니다.
|
||||
|
||||
## 5. 롤백
|
||||
|
||||
- 이전 커밋으로 되돌린 뒤(`git revert` 또는 이전 커밋으로 `git pull`) 3-3과 같이 컨테이너를 다시 띄웁니다.
|
||||
- 되돌리면 시스템 ffmpeg가 없는 이미지에서는 포스터 추출이 다시 실패합니다(`poster_url`이 NULL). 영상 생성 자체에는 영향이 없습니다.
|
||||
|
||||
## 6. 참고
|
||||
|
||||
- **기존 데이터**: 포스터 없이 저장된 기존 영상은 backfill을 따로 해야 합니다.
|
||||
Reference in new issue
Block a user