이미지 크롤링 로직 변경 및 자막 이미지 매칭 보완
This commit is contained in:
1 parent
4d8462651a
commit
b8be2a355a
16 files changed
+212
-74
No files matched your search
@@ -36,7 +36,7 @@ async def autotag_images(image_url_list : list[str], industry: str = "") -> list
|
||||
MAX_RETRY = 2
|
||||
for _ in range(MAX_RETRY):
|
||||
failed_idx = [i for i, r in enumerate(image_result_list) if isinstance(r, Exception)]
|
||||
print("Failed", failed_idx)
|
||||
# print("Failed", failed_idx)
|
||||
if not failed_idx:
|
||||
break
|
||||
retried = await asyncio.gather(
|
||||
@@ -46,5 +46,5 @@ async def autotag_images(image_url_list : list[str], industry: str = "") -> list
|
||||
for i, result in zip(failed_idx, retried):
|
||||
image_result_list[i] = result
|
||||
|
||||
print("Failed", failed_idx)
|
||||
# print("Failed", failed_idx)
|
||||
return image_result_list
|
||||
+45
-9
@@ -895,6 +895,20 @@ class CreatomateService:
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
@staticmethod
|
||||
def _entrance_transition_offset(elem: dict) -> float:
|
||||
"""요소의 entrance transition(transition=true, time==0) duration 합을 반환합니다.
|
||||
|
||||
순차 배치 시 이 값만큼 이전 요소와 겹치도록 시작점이 앞당겨집니다.
|
||||
"""
|
||||
offset = 0.0
|
||||
for animation in elem.get("animations", []):
|
||||
if "reversed" in animation:
|
||||
continue
|
||||
if "transition" in animation and animation["transition"] and animation.get("time", 0) == 0:
|
||||
offset += animation["duration"]
|
||||
return offset
|
||||
|
||||
def calc_scene_duration(self, template: dict) -> float:
|
||||
"""템플릿의 전체 장면 duration을 계산합니다."""
|
||||
total_template_duration = 0.0
|
||||
@@ -908,15 +922,7 @@ class CreatomateService:
|
||||
if elem["track"] not in track_maximum_duration:
|
||||
continue
|
||||
if "time" not in elem or elem["time"] == 0: # elem is auto / 만약 마지막 elem이 auto인데 그 앞에 time이 있는 elem 일 시 버그 발생 확률 있음
|
||||
track_maximum_duration[elem["track"]] += elem["duration"]
|
||||
|
||||
if "animations" not in elem:
|
||||
continue
|
||||
for animation in elem["animations"]:
|
||||
if "reversed" in animation:
|
||||
continue
|
||||
if "transition" in animation and animation["transition"] and animation.get("time", 0) == 0:
|
||||
track_maximum_duration[elem["track"]] -= animation["duration"]
|
||||
track_maximum_duration[elem["track"]] += elem["duration"] - self._entrance_transition_offset(elem)
|
||||
else:
|
||||
track_maximum_duration[elem["track"]] = max(track_maximum_duration[elem["track"]], elem["time"] + elem["duration"])
|
||||
|
||||
@@ -928,6 +934,36 @@ class CreatomateService:
|
||||
|
||||
return total_template_duration
|
||||
|
||||
def calc_track_time_ranges(self, template: dict, track: int) -> list[tuple[str, float, float]]:
|
||||
"""최상위 요소 중 지정 track의 (name, start, end) 시간 범위를 계산합니다.
|
||||
|
||||
Creatomate 규칙에 따라 `time`이 없거나 0인 요소는 같은 트랙의 이전 요소 뒤에
|
||||
순차 배치되며, entrance transition duration만큼 이전 요소와 겹치도록
|
||||
시작점을 앞당깁니다(calc_scene_duration의 차감 규칙과 동치).
|
||||
`time`이 명시된 요소는 해당 시각에서 시작하고, 커서는 그 요소의 끝으로 이동합니다.
|
||||
"""
|
||||
ranges: list[tuple[str, float, float]] = []
|
||||
cursor = 0.0
|
||||
for elem in template["source"]["elements"]:
|
||||
try:
|
||||
if elem.get("track") != track:
|
||||
continue
|
||||
duration = elem["duration"]
|
||||
|
||||
if "time" not in elem or elem["time"] == 0: # 순차 배치(auto)
|
||||
start = max(0.0, cursor - self._entrance_transition_offset(elem))
|
||||
else:
|
||||
start = elem["time"]
|
||||
|
||||
end = start + duration
|
||||
cursor = end
|
||||
ranges.append((elem.get("name", ""), start, end))
|
||||
except Exception as e:
|
||||
logger.debug(traceback.format_exc())
|
||||
logger.error(f"[calc_track_time_ranges] Error processing element: {elem}, {e}")
|
||||
|
||||
return ranges
|
||||
|
||||
def extend_template_duration(self, template: dict, target_duration: float) -> dict:
|
||||
"""템플릿의 duration을 target_duration으로 확장합니다."""
|
||||
# template["duration"] = target_duration + 0.5 # 늘린것보단 짧게
|
||||
|
||||
@@ -81,7 +81,7 @@ async def filter_marketing_images(image_url_list: list[str], industry: str = "")
|
||||
failed_idx = [i for i, r in enumerate(results) if isinstance(r, Exception)]
|
||||
if not failed_idx:
|
||||
break
|
||||
logger.warning(f"[image_filter] 재시도 대상 인덱스: {failed_idx}")
|
||||
# logger.warning(f"[image_filter] 재시도 대상 인덱스: {failed_idx}")
|
||||
retried = await asyncio.gather(
|
||||
*[_call(image_url_list[i]) for i in failed_idx], return_exceptions=True
|
||||
)
|
||||
@@ -89,10 +89,10 @@ async def filter_marketing_images(image_url_list: list[str], industry: str = "")
|
||||
results[i] = result
|
||||
|
||||
final_failed = [i for i, r in enumerate(results) if isinstance(r, Exception)]
|
||||
if final_failed:
|
||||
logger.warning(
|
||||
f"[image_filter] {len(final_failed)}건 최종 실패 → 보수적으로 제외 처리: {final_failed}"
|
||||
)
|
||||
# if final_failed:
|
||||
# logger.warning(
|
||||
# f"[image_filter] {len(final_failed)}건 최종 실패 → 보수적으로 제외 처리: {final_failed}"
|
||||
# )
|
||||
|
||||
return [
|
||||
(not isinstance(r, Exception)) and r.marketing_acceptable
|
||||
|
||||
@@ -52,6 +52,12 @@ query getAccommodation($id: String!, $deviceType: String) {
|
||||
conveniences
|
||||
visitorReviewsTotal
|
||||
}
|
||||
menus {
|
||||
name
|
||||
price
|
||||
description
|
||||
recommend
|
||||
}
|
||||
images { images { origin url } }
|
||||
}
|
||||
}"""
|
||||
@@ -100,6 +106,7 @@ query getVisitorReviewStats($id: String!) {
|
||||
self.base_info: dict | None = None
|
||||
self.facility_info: str | None = None
|
||||
self.voted_keyword_stats: list[dict] | None = None # 키워드 투표 집계 (displayName, count)
|
||||
self.menu_info: list[dict] | None = None # 메뉴 목록 (name, price, description, recommend)
|
||||
|
||||
def _get_request_headers(self) -> dict:
|
||||
headers = self.DEFAULT_HEADERS.copy()
|
||||
@@ -209,7 +216,8 @@ query getVisitorReviewStats($id: String!) {
|
||||
|
||||
# ── 실제 브라우저로 WTM 캡차 우회 ──
|
||||
data, stats_data, extra_photo_urls = await self._scrap_via_browser(place_id)
|
||||
fac_data = None # 편의시설(HTML)은 브라우저 경로에서 생략 (best-effort)
|
||||
# 편의시설은 HTML 페이지 파싱이라 GraphQL(WTM) 차단과 별개로 직접 시도 (best-effort, 실패 시 None)
|
||||
fac_data = await self._get_facility_string(place_id)
|
||||
self.scrap_type = "GraphQL-Browser"
|
||||
|
||||
self.rawdata = data
|
||||
@@ -243,6 +251,7 @@ query getVisitorReviewStats($id: String!) {
|
||||
self.base_info = data["data"]["business"]["base"]
|
||||
self.facility_info = fac_data
|
||||
self.voted_keyword_stats = stats_data
|
||||
self.menu_info = business.get("menus") or None
|
||||
|
||||
return
|
||||
|
||||
|
||||
@@ -149,17 +149,17 @@ class ChatgptService:
|
||||
logger.info(f"[ChatgptService({self.model_type})] Retrying request...")
|
||||
continue
|
||||
# Response 디버그 로깅
|
||||
logger.debug(f"[ChatgptService({self.model_type})] attempt: {attempt}")
|
||||
logger.debug(f"[ChatgptService({self.model_type})] Response ID: {response.id}")
|
||||
logger.debug(f"[ChatgptService({self.model_type})] Response finish_reason: {response.id}")
|
||||
logger.debug(f"[ChatgptService({self.model_type})] Response model: {response.model}")
|
||||
# logger.debug(f"[ChatgptService({self.model_type})] attempt: {attempt}")
|
||||
# logger.debug(f"[ChatgptService({self.model_type})] Response ID: {response.id}")
|
||||
# logger.debug(f"[ChatgptService({self.model_type})] Response finish_reason: {response.id}")
|
||||
# logger.debug(f"[ChatgptService({self.model_type})] Response model: {response.model}")
|
||||
|
||||
choice = response.choices[0]
|
||||
finish_reason = choice.finish_reason
|
||||
|
||||
if finish_reason == "stop":
|
||||
output_text = choice.message.content or ""
|
||||
logger.debug(f"[ChatgptService({self.model_type})] Response output_text: {output_text[:200]}..." if len(output_text) > 200 else f"[ChatgptService] Response output_text: {output_text}")
|
||||
# output_text = choice.message.content or ""
|
||||
# logger.debug(f"[ChatgptService({self.model_type})] Response output_text: {output_text[:200]}..." if len(output_text) > 200 else f"[ChatgptService] Response output_text: {output_text}")
|
||||
return choice.message.parsed
|
||||
|
||||
elif finish_reason == "length":
|
||||
|
||||
@@ -116,7 +116,7 @@ class ImageTagPromptInput(BaseModel):
|
||||
"""이미지 태깅 프롬프트에 전달되는 입력 스키마.
|
||||
분석할 이미지 URL과 업종 정보, LLM이 선택 가능한 태그 후보 리스트를 포함."""
|
||||
img_url : str = Field(..., description="이미지 URL")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction|general). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
space_type: list[str] = Field(list(SpaceType), description="공간적 정보를 가지는 태그 리스트")
|
||||
subject: list[str] = Field(list(Subject), description="피사체 정보를 가지는 태그 리스트")
|
||||
camera: list[str] = Field(list(Camera), description="카메라 정보를 가지는 태그 리스트")
|
||||
|
||||
@@ -12,7 +12,7 @@ class LyricPromptInput(BaseModel):
|
||||
language : str= Field(..., description = "가사 언어")
|
||||
genre : str = Field(default="", description = "지정된 음악 장르 (kpop|pop|ballad|hip-hop|rnb|edm|jazz|rock). 비어있으면 GPT가 무드에 맞는 장르를 자유롭게 추천")
|
||||
exclude_genre : str = Field(default="", description = "재생성 시 직전에 사용된 장르. genre가 비어있는 경우(자동 선택) 이 장르는 추천에서 제외")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction|general). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
|
||||
# Output 정의
|
||||
class LyricPromptOutput(BaseModel):
|
||||
|
||||
@@ -6,7 +6,12 @@ class MarketingPromptInput(BaseModel):
|
||||
customer_name : str = Field(..., description = "마케팅 대상 사업체 이름")
|
||||
region : str = Field(..., description = "마케팅 대상 지역")
|
||||
detail_region_info : str = Field(..., description = "마케팅 대상 지역 상세")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction|general). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
category : str = Field(default="", description = "네이버 지도 원본 카테고리 텍스트 (예: 펜션, 한식). industry 모듈 선택에는 관여하지 않고 세부 묘사의 참고 정보로만 사용")
|
||||
facility_info : str = Field(default="", description = "편의시설 정보 (네이버 지도 크롤링, 없으면 빈 문자열)")
|
||||
voted_keywords : str = Field(default="", description = "방문자 키워드 투표 상위 5개 (쉼표 구분, 없으면 빈 문자열)")
|
||||
# 메뉴 전달은 잠정 보류 (사이드 메뉴가 분석에 과도한 영향을 주는 문제). 재도입 시 주석 해제.
|
||||
# menu_info : str = Field(default="", description = "메뉴/상품 목록 (네이버 지도 크롤링, 쉼표 구분, 없으면 빈 문자열). 실제 판매 품목 기반 셀링포인트 작성에 사용")
|
||||
|
||||
# Output 정의
|
||||
class BrandIdentity(BaseModel):
|
||||
|
||||
@@ -10,7 +10,7 @@ class SubtitlePromptInput(BaseModel):
|
||||
customer_name : str = Field(..., description = "마케팅 대상 사업체 이름")
|
||||
detail_region_info : str = Field(..., description = "마케팅 대상 지역 상세")
|
||||
language : str = Field(default="Korean", description="자막 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction|general). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
|
||||
# Output 정의
|
||||
class PitchingOutput(BaseModel):
|
||||
|
||||
@@ -8,7 +8,7 @@ class YTUploadPromptInput(BaseModel):
|
||||
marketing_intelligence_summary : Optional[str] = Field(None, description = "마케팅 분석 정보 보고서")
|
||||
language : str= Field(..., description = "영상 언어")
|
||||
target_keywords: List[str] = Field(..., description="태그 키워드 리스트")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction|general). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
|
||||
# Output 정의
|
||||
class YTUploadPromptOutput(BaseModel):
|
||||
|
||||
Reference in new issue
Block a user