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

This commit is contained in:
skkim committed 2026-07-06 16:23:16 +09:00
1 parent 4d8462651a
commit b8be2a355a
16 files changed
+212 -74

No files matched your search

+103 -31
View File
@@ -9,7 +9,12 @@ from sqlalchemy import select
from app.database.session import BackgroundSessionLocal
from app.home.models import Project, MarketingIntel
from app.utils.subtitles import SubtitleContentsGenerator
from app.utils.creatomate import CreatomateService
from app.utils.creatomate import (
CreatomateService,
SCENE_TRACK,
SUBTITLE_TRACK,
KEYWORD_TRACK,
)
from app.utils.logger import get_logger
from app.video.services.video import get_image_tags_by_task_id
from app.utils.prompts.schemas.image import NARRATIVE_PHASE_LABEL
@@ -121,6 +126,8 @@ async def generate_creative_assets_background(
pitchings_with_context = _build_pitching_list_with_image_context(
pitching_label_list=pitchings_raw,
assigned_image_tags=assigned_image_tags,
template=template,
creatomate_service=creatomate_service,
)
subtitle_generator = SubtitleContentsGenerator()
@@ -134,8 +141,9 @@ async def generate_creative_assets_background(
)
pitching_output_list = generated_subtitles.pitching_results
# LLM이 pitching_tag에 " | 화면: ..." 컨텍스트 접미를 그대로 되돌려줄 수 있으므로 제거
subtitle_modifications = {
pitching_output.pitching_tag: pitching_output.pitching_data
pitching_output.pitching_tag.split(IMAGE_CONTEXT_SEP)[0].strip(): pitching_output.pitching_data
for pitching_output in pitching_output_list
}
logger.info(f"[generate_creative_assets_background] subtitle_modifications: {subtitle_modifications}")
@@ -170,49 +178,113 @@ async def generate_creative_assets_background(
logger.error(f"[generate_creative_assets_background] 모든 재시도 실패 - task_id: {task_id}")
# 이미지 컨텍스트 접미 구분자 — 생성(_context_for_label)과 제거(subtitle_modifications) 양쪽에서 사용
IMAGE_CONTEXT_SEP = " | "
def _merge_unique(tags: list[dict], key: str) -> list:
"""태그들의 key 리스트를 순서 유지하며 중복 제거해 병합합니다."""
return list(dict.fromkeys(item for tag in tags for item in tag.get(key, [])))
def _aggregate_tags_by_composition(
template: dict,
assigned_image_tags: dict[str, dict],
creatomate_service: CreatomateService,
) -> dict[str, dict]:
"""SCENE_TRACK 최상위 컴포지션별로 배정된 이미지 태그를 집계합니다.
컴포지션 하위 leaf image가 여러 개면(다중 이미지 씬) space_type/subject를
순서 유지 중복 제거로 병합합니다. 배정된 태그가 없는 컴포지션(CTA 등)은
결과에 포함하지 않습니다.
"""
comp_tags: dict[str, dict] = {}
for elem in template["source"]["elements"]:
if elem.get("track") != SCENE_TRACK or not elem.get("name"):
continue
name_to_type = creatomate_service.parse_template_component_name([elem])
leaf_tags = [
assigned_image_tags[name]
for name, elem_type in name_to_type.items()
if elem_type == "image" and name in assigned_image_tags
]
if not leaf_tags:
continue
comp_tags[elem["name"]] = {
"space_type": _merge_unique(leaf_tags, "space_type"),
"subject": _merge_unique(leaf_tags, "subject"),
}
return comp_tags
def _context_for_label(
text_range: tuple[float, float],
scene_ranges: list[tuple[str, float, float]],
comp_tags: dict[str, dict],
) -> str:
"""텍스트 재생 구간과 시간 겹침이 최대인 씬의 이미지 컨텍스트 접미를 만듭니다.
태그가 배정된 컴포지션 중 겹침이 최대인 씬을 선택하며(동률 시 이른 시작 우선),
겹치는 씬이 없으면 빈 문자열을 반환합니다.
"""
text_start, text_end = text_range
candidates = [
(min(text_end, comp_end) - max(text_start, comp_start), -comp_start, comp_name)
for comp_name, comp_start, comp_end in scene_ranges
if comp_name in comp_tags
]
candidates = [c for c in candidates if c[0] > 0]
if not candidates:
return ""
best_comp = max(candidates)[2]
tag = comp_tags[best_comp]
space_types = tag.get("space_type", [])
subjects = tag.get("subject", [])
space_str = "/".join(space_types[:2]) if space_types else "?"
subject_str = subjects[0] if subjects else "?"
# 컴포지션명 형식: {space_type}-{subject}-{camera}-{motion}-{narrative_phase}
comp_tokens = best_comp.split("-")
phase = comp_tokens[4] if len(comp_tokens) >= 5 else ""
phase_str = NARRATIVE_PHASE_LABEL.get(phase, phase)
return f"{IMAGE_CONTEXT_SEP}화면: {space_str} / {subject_str} / {phase_str} 단계"
def _build_pitching_list_with_image_context(
pitching_label_list: list[str],
assigned_image_tags: dict[str, dict],
template: dict,
creatomate_service: CreatomateService,
) -> list[str]:
"""pitching 레이블 리스트에 배정 이미지 컨텍스트를 포함하여 반환합니다.
슬롯명(`bedroom-furniture-tight_crop-slow_zoom_in-welcome`)의 5번째 토큰과
pitching 레이어명(`subtitle-welcome-emotion_cue-empathic-001`)의 2번째 토큰이
동일한 narrative_phase이므로 시간 겹침 계산 없이 phase로 직접 매칭합니다.
텍스트 레이어(SUBTITLE/KEYWORD_TRACK)와 이미지 컴포지션(SCENE_TRACK)의
시간 범위를 계산해, 각 텍스트가 재생되는 동안 화면에 가장 오래 보이는
(시간 겹침이 최대인) 컴포지션의 이미지 태그를 컨텍스트로 붙입니다.
narrative_phase 토큰 매칭과 달리 phase 이름이 어긋나거나(자막 outro vs
이미지 accent) 같은 phase에 씬이 여러 개여도 올바른 짝을 찾습니다.
겹치는 씬이 없거나 해당 씬에 배정된 이미지가 없으면(CTA 등) 컨텍스트를
생략합니다. 렌더 시 extend_template_duration은 전 트랙 균등 배율이므로
원본 템플릿 기준 겹침 관계는 스케일 후에도 유지됩니다.
출력 예시:
"subtitle-welcome-emotion_cue-empathic-001 | 화면: lobby / furniture / 진입(welcome) 단계"
"""
# narrative_phase → 해당 phase에 배정된 image_tag 매핑 구성
# 슬롯명 형식: {space_type}-{subject}-{camera}-{motion}-{narrative_phase}
phase_to_tag: dict[str, dict] = {}
for slot_name, tag in assigned_image_tags.items():
tokens = slot_name.split("-")
if len(tokens) >= 5:
phase = tokens[4]
# 같은 phase에 슬롯이 여러 개면 첫 번째만 사용
if phase not in phase_to_tag:
phase_to_tag[phase] = tag
if not phase_to_tag:
comp_tags = _aggregate_tags_by_composition(template, assigned_image_tags, creatomate_service)
if not comp_tags:
return pitching_label_list
scene_ranges = creatomate_service.calc_track_time_ranges(template, SCENE_TRACK)
text_ranges: dict[str, tuple[float, float]] = {}
for track in (SUBTITLE_TRACK, KEYWORD_TRACK):
for name, start, end in creatomate_service.calc_track_time_ranges(template, track):
text_ranges[name] = (start, end)
result = []
for label in pitching_label_list:
# pitching 레이어명 형식: {track_role}-{narrative_phase}-{content_type}-{tone}-{pair_id}
tokens = label.split("-")
context_str = ""
if len(tokens) >= 2:
phase = tokens[1]
tag = phase_to_tag.get(phase)
if tag:
space_types = tag.get("space_type", [])
subjects = tag.get("subject", [])
space_str = "/".join(space_types[:2]) if space_types else "?"
subject_str = subjects[0] if subjects else "?"
phase_str = NARRATIVE_PHASE_LABEL.get(phase, phase)
context_str = f" | 화면: {space_str} / {subject_str} / {phase_str} 단계"
text_range = text_ranges.get(label)
context_str = _context_for_label(text_range, scene_ranges, comp_tags) if text_range else ""
result.append(label + context_str)
return result