썸네일 선택 로직 및 필터링 추가

This commit is contained in:
skkim committed 2026-07-22 15:54:34 +09:00
1 parent 788e76ef76
commit 6090d500f9
6 files changed
+565 -6

No files matched your search

+112 -5
View File
@@ -273,6 +273,13 @@ AUDIO_TRACK = 2
SUBTITLE_TRACK = 3
KEYWORD_TRACK = 4
# 썸네일 컴포지션의 이미지 슬롯명 접미사 (8개 업종 템플릿 전수 확인, 예:
# "exterior_front-architecture_detail-wide_angle-slow_zoom_in-intro-core-9999").
# 일반 씬 이미지는 "-0001"~"-0030"류 4자리 순번을 쓰는 반면 썸네일만 "-9999"라
# 슬롯명 접미사만으로 안전하게 식별 가능(가로 템플릿처럼 썸네일 컴포지션이
# 없는 템플릿도 있음).
THUMBNAIL_SLOT_MARKER = "-9999"
def is_fixed_slot_name(name: str) -> bool:
"""이름이 '-fixed'로 끝나는 요소인지 판별합니다.
@@ -552,13 +559,79 @@ class CreatomateService:
count += 1
return count
def _slot_scores_with_fitness(
self,
pool_subset: list[dict],
slot: str,
thumbnail_fitness_map: dict | None,
) -> list[float]:
"""슬롯 점수에 썸네일 픽셀 적합도를 결합합니다.
썸네일 슬롯(-9999)에 한해 태그 점수에 적합도를 반영한다:
- reject(저해상도/극단 가로형) → 0점 (하드 배제)
- 정상 → 태그 점수 × 적합도 배율(0.25~1.0)
- 적합도 데이터 없음(헤더 확보/파싱 실패) → 태그 점수 그대로(중립).
다운로드 실패를 배제로 오판해 풀 전체가 날아가는 것을 막기 위함.
일반 씬 슬롯은 태그 점수를 그대로 반환한다.
"""
scores = self.calculate_image_slot_score_multi(pool_subset, slot)
if not thumbnail_fitness_map or not slot.endswith(THUMBNAIL_SLOT_MARKER):
return scores
adjusted = []
for item, score in zip(pool_subset, scores):
fitness = thumbnail_fitness_map.get(item.get("image_url"))
if fitness is None:
adjusted.append(score)
elif fitness["reject"]:
adjusted.append(0.0)
else:
adjusted.append(score * fitness["score"])
return adjusted
def rank_thumbnail_candidates(
self,
template: dict,
taged_image_list: list,
thumbnail_fitness_map: dict | None = None,
top_n: int = 3,
) -> dict[str, list[dict]]:
"""썸네일 슬롯별로 상위 후보(태그×픽셀 점수 내림차순)를 반환합니다.
비전 LLM 최종 선택(Phase 2)에 넘길 후보 압축용. 읽기 전용 — pool을
변형하지 않으며 배정도 하지 않는다. 점수 0 이하(픽셀 reject 포함)는
제외한다.
Returns:
{슬롯명: [pool item, ...]} — 슬롯당 최대 top_n개, 점수 내림차순.
후보가 없는 슬롯은 키 자체를 포함하지 않는다.
"""
component = self.parse_template_component_name(template["source"]["elements"])
thumbnail_slots = [
name for name, t in component.items()
if t == "image" and name.endswith(THUMBNAIL_SLOT_MARKER)
and not is_fixed_slot_name(name) and self.parse_slot_name_to_tag(name) is not None
]
result: dict[str, list[dict]] = {}
for slot in thumbnail_slots:
scores = self._slot_scores_with_fitness(taged_image_list, slot, thumbnail_fitness_map)
ranked = sorted(
range(len(scores)), key=lambda i: scores[i], reverse=True
)
candidates = [taged_image_list[i] for i in ranked if scores[i] > 0][:top_n]
if candidates:
result[slot] = candidates
return result
def template_matching_taged_image(
self,
template: dict,
taged_image_list: list, # [{"image_url": str, "image_tag": dict}] — 이미 마케팅 적합성 필터를 통과한 이미지만 전달할 것
music_url: str,
address: str,
duplicate: bool = False
duplicate: bool = False,
thumbnail_fitness_map: dict | None = None, # {image_url: {"score", "reject"}} — 썸네일 슬롯 픽셀 적합도
thumbnail_choice: dict | None = None, # {슬롯명: image_url} — 비전 LLM 최종 선택(있으면 결정론 최고점 대신 사용)
) -> tuple[dict, dict]:
"""템플릿 슬롯에 이미지를 배정합니다.
@@ -602,6 +675,40 @@ class CreatomateService:
]
text_slots = [(name, t) for name, t in template_component_data.items() if t == "text"]
# ── 썸네일 슬롯(-9999) 우선 배정 ─────────────────────────────────
# 썸네일은 영상에서 가장 노출이 큰 표면이므로 씬 슬롯과 다르게 취급한다:
# 1) 씬 슬롯이 pool에서 좋은 컷을 pop해 가기 전에 먼저 배정 (같은 태그
# 계열 씬 슬롯이 여러 개면 썸네일 차례에 적합 컷이 소진되는 문제 방지)
# 2) "상위 3장 가중 랜덤" 없이 결정론적 최고점 선택 — 랜덤 다양화가
# 저점수 컷(예: space_type 불일치 ×0.1 페널티 컷)을 확률적으로
# 썸네일에 앉히는 사고 방지
# duplicate(이미지 부족) 시에는 pop하지 않아 씬 커버리지를 깎지 않는다.
# thumbnail_choice(비전 LLM 최종 선택)가 해당 슬롯에 있으면 그 이미지를,
# 없으면(선택 실패/미제공) 결정론적 최고점 컷을 사용한다 — 폴백 안전.
thumbnail_choice = thumbnail_choice or {}
thumbnail_slots = [s for s in image_slots if s.endswith(THUMBNAIL_SLOT_MARKER)]
image_slots = [s for s in image_slots if not s.endswith(THUMBNAIL_SLOT_MARKER)]
for slot in thumbnail_slots:
if not pool:
logger.warning(f"[template_matching_taged_image] 이미지 풀 없음 — 썸네일 슬롯 배정 불가: {slot}")
break
scores = self._slot_scores_with_fitness(pool, slot, thumbnail_fitness_map)
chosen_url = thumbnail_choice.get(slot)
chosen_idx = next(
(i for i, item in enumerate(pool) if item["image_url"] == chosen_url), None
) if chosen_url else None
if chosen_idx is not None:
sel_idx, sel_source = chosen_idx, "vision"
else:
sel_idx, sel_source = max(range(len(scores)), key=lambda i: scores[i]), "결정론"
selected = pool[sel_idx] if duplicate else pool.pop(sel_idx)
modifications[slot] = selected["image_url"]
assigned[slot] = selected["image_tag"]
logger.info(
f"[template_matching_taged_image] 썸네일 배정({sel_source}) — slot: {slot}, "
f"score: {scores[sel_idx]:.3f}, url: {selected['image_url']}"
)
if not pool:
logger.warning("[template_matching_taged_image] 태그된 이미지가 없음 — 이미지 슬롯 배정 불가")
elif duplicate:
@@ -612,7 +719,7 @@ class CreatomateService:
def _best_slot_for_image(image: dict, slots: list) -> tuple[str | None, float]:
best_slot, best_score = None, -1.0
for slot in slots:
score = self.calculate_image_slot_score_multi([image], slot)[0]
score = self._slot_scores_with_fitness([image], slot, thumbnail_fitness_map)[0]
if score > best_score:
best_slot, best_score = slot, score
return best_slot, best_score
@@ -640,7 +747,7 @@ class CreatomateService:
# Step 2: 커버리지 배정 후 남은 슬롯은 pool 전체에서 최고점 이미지 배정 (재사용 불가피)
for slot in remaining_slots:
scores = self.calculate_image_slot_score_multi(pool, slot)
scores = self._slot_scores_with_fitness(pool, slot, thumbnail_fitness_map)
if not scores:
continue
best_idx = scores.index(max(scores))
@@ -650,7 +757,7 @@ class CreatomateService:
else:
# 이미지 충분(슬롯 수 <= 이미지 수): 난이도 우선 greedy 배정
# Step 1: 정렬용 사전 점수 계산 (최고 달성 점수가 낮을수록 배정이 어려운 슬롯)
prelim = {slot: self.calculate_image_slot_score_multi(pool, slot) for slot in image_slots}
prelim = {slot: self._slot_scores_with_fitness(pool, slot, thumbnail_fitness_map) for slot in image_slots}
ordered_slots = sorted(
image_slots,
key=lambda s: max(prelim[s]) if prelim[s] else 0.0
@@ -663,7 +770,7 @@ class CreatomateService:
logger.warning(f"[template_matching_taged_image] 이미지 풀 소진 — 남은 슬롯 배정 불가: {slot}")
break
# pop 후 인덱스 변동이 있으므로 현재 pool로 재계산 (사전 점수 재사용 금지)
scores = self.calculate_image_slot_score_multi(pool, slot)
scores = self._slot_scores_with_fitness(pool, slot, thumbnail_fitness_map)
if not scores:
continue