Merge branch 'main' into feature-ssulbox
This commit is contained in:
commit
bb8b20a7a9
6 files changed
+1243
-228
No files matched your search
+103
-11
@@ -574,8 +574,15 @@ class CreatomateService:
|
||||
다운로드 실패를 배제로 오판해 풀 전체가 날아가는 것을 막기 위함.
|
||||
일반 씬 슬롯은 태그 점수를 그대로 반환한다.
|
||||
"""
|
||||
scores = self.calculate_image_slot_score_multi(pool_subset, slot)
|
||||
if not thumbnail_fitness_map or not slot.endswith(THUMBNAIL_SLOT_MARKER):
|
||||
is_thumbnail = slot.endswith(THUMBNAIL_SLOT_MARKER)
|
||||
if is_thumbnail and self.parse_slot_name_to_tag(slot) is None:
|
||||
# 슬롯명이 명명 규칙을 어겨 태그 매칭이 불가능한 썸네일 슬롯.
|
||||
# 태그 점수를 0으로 두면 pool 첫 컷이 뽑혀 사실상 무작위가 되므로
|
||||
# 전 이미지 중립(1.0)으로 두고 아래 픽셀 적합도만으로 순위를 가른다.
|
||||
scores = [1.0] * len(pool_subset)
|
||||
else:
|
||||
scores = self.calculate_image_slot_score_multi(pool_subset, slot)
|
||||
if not thumbnail_fitness_map or not is_thumbnail:
|
||||
return scores
|
||||
|
||||
adjusted = []
|
||||
@@ -589,6 +596,31 @@ class CreatomateService:
|
||||
adjusted.append(score * fitness["score"])
|
||||
return adjusted
|
||||
|
||||
def _collect_thumbnail_slots(self, template_component_data: dict) -> list[str]:
|
||||
"""배정 대상 썸네일 슬롯(-9999)을 수집합니다.
|
||||
|
||||
일반 씬 슬롯과 달리 슬롯명 파싱에 실패해도 제외하지 않는다. 썸네일은
|
||||
노출 면적이 가장 큰 표면이라, 미배정 시 modify_element가 템플릿 원본
|
||||
(샘플 이미지)을 그대로 남겨 완성 영상에 그대로 나가기 때문이다. 태그
|
||||
매칭이 불가능한 슬롯은 _slot_scores_with_fitness가 픽셀 적합도만으로
|
||||
고른다. 단 '-fixed' 고정 자산은 여기서도 제외한다.
|
||||
|
||||
파싱 실패는 템플릿 슬롯명 오타이므로 ERROR로 남겨 드러나게 한다
|
||||
(조용히 넘어가면 샘플 이미지가 나가도 아무도 알아채지 못한다).
|
||||
"""
|
||||
slots = [
|
||||
name for name, t in template_component_data.items()
|
||||
if t == "image" and name.endswith(THUMBNAIL_SLOT_MARKER)
|
||||
and not is_fixed_slot_name(name)
|
||||
]
|
||||
for name in slots:
|
||||
if self.parse_slot_name_to_tag(name) is None:
|
||||
logger.error(
|
||||
f"[_collect_thumbnail_slots] 썸네일 슬롯명이 명명 규칙 위반 — "
|
||||
f"'{name}' — 템플릿 슬롯명 수정 필요. 픽셀 적합도 기준으로 폴백 배정합니다."
|
||||
)
|
||||
return slots
|
||||
|
||||
def rank_thumbnail_candidates(
|
||||
self,
|
||||
template: dict,
|
||||
@@ -607,11 +639,7 @@ class CreatomateService:
|
||||
후보가 없는 슬롯은 키 자체를 포함하지 않는다.
|
||||
"""
|
||||
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
|
||||
]
|
||||
thumbnail_slots = self._collect_thumbnail_slots(component)
|
||||
result: dict[str, list[dict]] = {}
|
||||
for slot in thumbnail_slots:
|
||||
scores = self._slot_scores_with_fitness(taged_image_list, slot, thumbnail_fitness_map)
|
||||
@@ -669,9 +697,13 @@ class CreatomateService:
|
||||
# 않는 image 요소는 콘텐츠 슬롯이 아니므로 배정 대상에서 제외 — 그렇지
|
||||
# 않으면 파싱 실패로 0점 처리되어 "가장 까다로운 슬롯"으로 취급되고
|
||||
# 무작위 이미지로 덮어써진다.
|
||||
# 썸네일 슬롯(-9999)은 파싱 실패해도 배정해야 하므로 여기서 제외하고
|
||||
# _collect_thumbnail_slots가 별도로 수집한다.
|
||||
image_slots = [
|
||||
name for name, t in template_component_data.items()
|
||||
if t == "image" and not is_fixed_slot_name(name) and self.parse_slot_name_to_tag(name) is not None
|
||||
if t == "image" and not is_fixed_slot_name(name)
|
||||
and not name.endswith(THUMBNAIL_SLOT_MARKER)
|
||||
and self.parse_slot_name_to_tag(name) is not None
|
||||
]
|
||||
text_slots = [(name, t) for name, t in template_component_data.items() if t == "text"]
|
||||
|
||||
@@ -686,8 +718,7 @@ class CreatomateService:
|
||||
# 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)]
|
||||
thumbnail_slots = self._collect_thumbnail_slots(template_component_data)
|
||||
for slot in thumbnail_slots:
|
||||
if not pool:
|
||||
logger.warning(f"[template_matching_taged_image] 이미지 풀 없음 — 썸네일 슬롯 배정 불가: {slot}")
|
||||
@@ -885,7 +916,13 @@ class CreatomateService:
|
||||
"""슬롯 이름을 파싱하여 태그 딕셔너리를 반환합니다.
|
||||
|
||||
슬롯 이름 형식: {space_type}-{subject}-{camera}-{motion}-{narrative}
|
||||
파싱 실패 시 None을 반환합니다 (호출자가 해당 슬롯을 skip+log 처리).
|
||||
|
||||
위치 기반 파싱에 실패하면 토큰 위치를 무시한 대조로 한 번 더 시도한다
|
||||
(_parse_slot_name_loosely). 슬롯명 오타로 슬롯이 배정에서 빠지면
|
||||
modify_element가 템플릿 원본(샘플 이미지)을 그대로 남겨 완성 영상에
|
||||
그대로 나가기 때문이다.
|
||||
|
||||
둘 다 실패하면 None을 반환합니다 (호출자가 해당 슬롯을 skip+log 처리).
|
||||
"""
|
||||
try:
|
||||
tag_list = slot_name.split("-")
|
||||
@@ -907,9 +944,64 @@ class CreatomateService:
|
||||
}
|
||||
return tag_dict
|
||||
except (ValueError, IndexError) as e:
|
||||
loose = self._parse_slot_name_loosely(tag_list)
|
||||
if loose is not None:
|
||||
logger.warning(
|
||||
f"[parse_slot_name_to_tag] 슬롯명이 명명 규칙 위반: '{slot_name}' — {e} — "
|
||||
f"위치 무시 대조로 복구: { {k: v.value for k, v in loose.items()} } — 템플릿 슬롯명 수정 권장"
|
||||
)
|
||||
return loose
|
||||
logger.warning(f"[parse_slot_name_to_tag] 슬롯명 파싱 실패: '{slot_name}' — {e} — 슬롯 skip")
|
||||
return None
|
||||
|
||||
def _parse_slot_name_loosely(self, tag_list: list[str]) -> dict[str, StrEnum] | None:
|
||||
"""토큰 위치를 무시하고 각 enum에 대조해 태그를 복구합니다.
|
||||
|
||||
위치 기반 파싱이 실패했을 때만 호출한다. 토큰 하나는 한 카테고리에만
|
||||
쓰이며, 앞선 토큰부터 순서대로 소비한다(중복 후보가 있으면 앞선 것 채택
|
||||
— 위치 기반과 같은 값을 고르게 된다).
|
||||
|
||||
space_type/subject/narrative는 필수다. 이 셋을 못 채우면 슬롯명이 아닌
|
||||
것으로 보고 None을 반환한다(고정 자산·비규칙 요소가 배정 대상에 섞여
|
||||
무작위 이미지로 덮어써지는 것을 막기 위함). camera/motion은 선택이며
|
||||
못 찾으면 키 자체를 넣지 않는다 — 점수 계산은 태그 딕셔너리를 순회하므로
|
||||
없는 키는 자연히 가중치에서 빠진다.
|
||||
"""
|
||||
used: set[int] = set()
|
||||
|
||||
def take(converter) -> StrEnum | None:
|
||||
for idx, token in enumerate(tag_list):
|
||||
if idx in used:
|
||||
continue
|
||||
try:
|
||||
value = converter(token)
|
||||
except ValueError:
|
||||
continue
|
||||
if value is not None:
|
||||
used.add(idx)
|
||||
return value
|
||||
return None
|
||||
|
||||
space_type = take(SpaceType)
|
||||
subject = take(Subject)
|
||||
narrative = take(NarrativePhase)
|
||||
if space_type is None or subject is None or narrative is None:
|
||||
return None
|
||||
|
||||
camera = take(Camera)
|
||||
motion = take(lambda t: MOTION_TOKEN_NORMALIZATION.get(t) or MotionRecommended(t))
|
||||
|
||||
tag_dict: dict[str, StrEnum] = {
|
||||
"space_type": space_type,
|
||||
"subject": subject,
|
||||
"narrative_preference": narrative,
|
||||
}
|
||||
if camera is not None:
|
||||
tag_dict["camera"] = camera
|
||||
if motion is not None:
|
||||
tag_dict["motion_recommended"] = motion
|
||||
return tag_dict
|
||||
|
||||
def elements_connect_resource_blackbox(
|
||||
self,
|
||||
elements: list,
|
||||
|
||||
@@ -32,12 +32,17 @@ URL 경로 형식:
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import aiofiles
|
||||
import httpx
|
||||
from fastapi import UploadFile
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from config import azure_blob_settings
|
||||
@@ -45,6 +50,15 @@ from config import azure_blob_settings
|
||||
# 로거 설정
|
||||
logger = get_logger("blob")
|
||||
|
||||
|
||||
class BlobUploadTooLargeError(ValueError):
|
||||
"""스트리밍 중 파일 크기 상한을 초과했을 때 발생합니다."""
|
||||
|
||||
def __init__(self, max_size_bytes: int):
|
||||
self.max_size_bytes = max_size_bytes
|
||||
super().__init__(f"업로드 파일은 {max_size_bytes} bytes를 초과할 수 없습니다.")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (싱글톤 패턴)
|
||||
# =============================================================================
|
||||
@@ -100,6 +114,8 @@ class AzureBlobUploader:
|
||||
".gif": "image/gif",
|
||||
".webp": "image/webp",
|
||||
".bmp": "image/bmp",
|
||||
".heic": "image/heic",
|
||||
".heif": "image/heif",
|
||||
}
|
||||
|
||||
def __init__(self, user_uuid: str, task_id: str):
|
||||
@@ -111,7 +127,7 @@ class AzureBlobUploader:
|
||||
"""
|
||||
self._user_uuid = user_uuid
|
||||
self._task_id = task_id
|
||||
self._base_url = azure_blob_settings.AZURE_BLOB_BASE_URL
|
||||
self._base_url = azure_blob_settings.AZURE_BLOB_BASE_URL.rstrip("/")
|
||||
self._sas_token = azure_blob_settings.AZURE_BLOB_SAS_TOKEN
|
||||
self._last_public_url: str = ""
|
||||
|
||||
@@ -204,8 +220,12 @@ class AzureBlobUploader:
|
||||
logger.debug(f"[{log_prefix}] Starting upload... "
|
||||
f"(size: {size} bytes, timeout: {timeout}s)")
|
||||
|
||||
request_headers = {
|
||||
**headers,
|
||||
"x-ms-version": azure_blob_settings.AZURE_BLOB_API_VERSION,
|
||||
}
|
||||
response = await asyncio.wait_for(
|
||||
client.put(upload_url, content=file_content, headers=headers),
|
||||
client.put(upload_url, content=file_content, headers=request_headers),
|
||||
timeout=timeout,
|
||||
)
|
||||
upload_time = time.perf_counter()
|
||||
@@ -246,6 +266,170 @@ class AzureBlobUploader:
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _append_query(upload_url: str, **params: str) -> str:
|
||||
"""SAS 쿼리를 유지하며 Azure REST API 쿼리를 추가합니다."""
|
||||
separator = "&" if "?" in upload_url else "?"
|
||||
return f"{upload_url}{separator}{urlencode(params)}"
|
||||
|
||||
async def _delete_upload_url(self, upload_url: str, log_prefix: str) -> bool:
|
||||
"""실패한 업로드의 커밋/미커밋 Blob을 정리합니다."""
|
||||
try:
|
||||
client = await get_shared_blob_client()
|
||||
response = await client.delete(
|
||||
upload_url,
|
||||
headers={"x-ms-version": azure_blob_settings.AZURE_BLOB_API_VERSION},
|
||||
)
|
||||
if response.status_code in {202, 404}:
|
||||
return True
|
||||
logger.warning(
|
||||
f"[{log_prefix}] Blob cleanup failed - Status: "
|
||||
f"{response.status_code}, Response: {response.text[:500]}"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
f"[{log_prefix}] Blob cleanup error - {type(exc).__name__}: {exc}"
|
||||
)
|
||||
return False
|
||||
|
||||
async def _upload_stream(
|
||||
self,
|
||||
chunks: AsyncIterator[bytes],
|
||||
upload_url: str,
|
||||
content_type: str,
|
||||
timeout: float,
|
||||
log_prefix: str,
|
||||
*,
|
||||
max_size_bytes: int | None = None,
|
||||
expected_size_bytes: int | None = None,
|
||||
cleanup_blob_on_failure: bool = False,
|
||||
) -> bool:
|
||||
"""Azure Block Blob API로 비동기 청크 스트림을 업로드합니다.
|
||||
|
||||
각 블록만 메모리에 유지하므로 파일 전체 크기와 무관하게 메모리 사용량이
|
||||
일정합니다. 커밋 전 오류가 발생하면 업로드 대상 Blob 삭제를 시도합니다.
|
||||
"""
|
||||
block_ids: list[str] = []
|
||||
block_id_nonce = os.urandom(16)
|
||||
uploaded_size = 0
|
||||
start_time = time.perf_counter()
|
||||
|
||||
async def cleanup_failed_stream() -> None:
|
||||
# 기존 deterministic key는 미커밋 블록만 TTL 정리되게 두어 정상 Blob을 보존합니다.
|
||||
if cleanup_blob_on_failure:
|
||||
await self._delete_upload_url(upload_url, log_prefix)
|
||||
|
||||
try:
|
||||
client = await get_shared_blob_client()
|
||||
async with asyncio.timeout(timeout):
|
||||
async for chunk in chunks:
|
||||
if not chunk:
|
||||
continue
|
||||
|
||||
uploaded_size += len(chunk)
|
||||
if max_size_bytes is not None and uploaded_size > max_size_bytes:
|
||||
raise BlobUploadTooLargeError(max_size_bytes)
|
||||
|
||||
raw_block_id = block_id_nonce + len(block_ids).to_bytes(4, "big")
|
||||
block_id = base64.b64encode(raw_block_id).decode("ascii")
|
||||
block_url = self._append_query(
|
||||
upload_url,
|
||||
comp="block",
|
||||
blockid=block_id,
|
||||
)
|
||||
response = await client.put(
|
||||
block_url,
|
||||
content=chunk,
|
||||
headers={
|
||||
"Content-Type": "application/octet-stream",
|
||||
"x-ms-version": (
|
||||
azure_blob_settings.AZURE_BLOB_API_VERSION
|
||||
),
|
||||
},
|
||||
)
|
||||
if response.status_code != 201:
|
||||
logger.error(
|
||||
f"[{log_prefix}] Block upload failed - Status: "
|
||||
f"{response.status_code}, Response: {response.text[:500]}"
|
||||
)
|
||||
await cleanup_failed_stream()
|
||||
return False
|
||||
block_ids.append(block_id)
|
||||
|
||||
if uploaded_size == 0:
|
||||
logger.warning(f"[{log_prefix}] Empty upload stream")
|
||||
await cleanup_failed_stream()
|
||||
return False
|
||||
|
||||
if (
|
||||
expected_size_bytes is not None
|
||||
and uploaded_size != expected_size_bytes
|
||||
):
|
||||
logger.error(
|
||||
f"[{log_prefix}] Stream size changed - expected: "
|
||||
f"{expected_size_bytes}, actual: {uploaded_size}"
|
||||
)
|
||||
await cleanup_failed_stream()
|
||||
return False
|
||||
|
||||
block_list = "".join(
|
||||
f"<Latest>{block_id}</Latest>" for block_id in block_ids
|
||||
)
|
||||
commit_body = (
|
||||
f'<?xml version="1.0" encoding="utf-8"?>'
|
||||
f"<BlockList>{block_list}</BlockList>"
|
||||
).encode("utf-8")
|
||||
commit_url = self._append_query(upload_url, comp="blocklist")
|
||||
response = await client.put(
|
||||
commit_url,
|
||||
content=commit_body,
|
||||
headers={
|
||||
"Content-Type": "application/xml; charset=utf-8",
|
||||
"x-ms-blob-content-type": content_type,
|
||||
"x-ms-version": azure_blob_settings.AZURE_BLOB_API_VERSION,
|
||||
},
|
||||
)
|
||||
if response.status_code not in {200, 201}:
|
||||
logger.error(
|
||||
f"[{log_prefix}] Block list commit failed - Status: "
|
||||
f"{response.status_code}, Response: {response.text[:500]}"
|
||||
)
|
||||
await cleanup_failed_stream()
|
||||
return False
|
||||
|
||||
duration_ms = (time.perf_counter() - start_time) * 1000
|
||||
logger.info(
|
||||
f"[{log_prefix}] SUCCESS - blocks: {len(block_ids)}, "
|
||||
f"size: {uploaded_size} bytes, Duration: {duration_ms:.1f}ms"
|
||||
)
|
||||
return True
|
||||
|
||||
except BlobUploadTooLargeError:
|
||||
await cleanup_failed_stream()
|
||||
raise
|
||||
except asyncio.CancelledError:
|
||||
# 클라이언트 연결 종료 중에도 가능한 범위에서 staged block을 정리합니다.
|
||||
await asyncio.shield(cleanup_failed_stream())
|
||||
raise
|
||||
except TimeoutError:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(f"[{log_prefix}] TIMEOUT after {elapsed:.1f}s")
|
||||
except httpx.HTTPError as exc:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(
|
||||
f"[{log_prefix}] HTTP_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
except Exception as exc:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(
|
||||
f"[{log_prefix}] ERROR after {elapsed:.1f}s - "
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
|
||||
await cleanup_failed_stream()
|
||||
return False
|
||||
|
||||
async def _upload_file(
|
||||
self,
|
||||
file_path: str,
|
||||
@@ -273,17 +457,20 @@ class AzureBlobUploader:
|
||||
self._last_public_url = self._build_public_url(category, file_name)
|
||||
logger.debug(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
|
||||
async def iter_file() -> AsyncIterator[bytes]:
|
||||
async with aiofiles.open(file_path, "rb") as file:
|
||||
while chunk := await file.read(
|
||||
azure_blob_settings.AZURE_BLOB_UPLOAD_BLOCK_SIZE_BYTES
|
||||
):
|
||||
yield chunk
|
||||
|
||||
async with aiofiles.open(file_path, "rb") as file:
|
||||
file_content = await file.read()
|
||||
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
return await self._upload_stream(
|
||||
chunks=iter_file(),
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
content_type=content_type,
|
||||
timeout=timeout,
|
||||
log_prefix=log_prefix,
|
||||
expected_size_bytes=Path(file_path).stat().st_size,
|
||||
)
|
||||
|
||||
async def upload_music(self, file_path: str) -> bool:
|
||||
@@ -482,6 +669,51 @@ class AzureBlobUploader:
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
async def upload_image_stream(
|
||||
self,
|
||||
file: UploadFile,
|
||||
file_name: str,
|
||||
*,
|
||||
expected_size_bytes: int | None = None,
|
||||
max_size_bytes: int | None = None,
|
||||
) -> bool:
|
||||
"""FastAPI UploadFile을 Azure Block Blob으로 청크 업로드합니다."""
|
||||
extension = Path(file_name).suffix.lower()
|
||||
content_type = self.IMAGE_CONTENT_TYPES.get(extension, "image/jpeg")
|
||||
file_name = self._sanitize_filename(file_name)
|
||||
|
||||
upload_url = self._build_upload_url("image", file_name)
|
||||
self._last_public_url = self._build_public_url("image", file_name)
|
||||
log_prefix = "upload_image_stream"
|
||||
chunk_size = azure_blob_settings.AZURE_BLOB_UPLOAD_BLOCK_SIZE_BYTES
|
||||
max_size = (
|
||||
max_size_bytes
|
||||
if max_size_bytes is not None
|
||||
else azure_blob_settings.IMAGE_UPLOAD_MAX_FILE_SIZE_BYTES
|
||||
)
|
||||
|
||||
async def iter_upload() -> AsyncIterator[bytes]:
|
||||
await file.seek(0)
|
||||
while chunk := await file.read(chunk_size):
|
||||
yield chunk
|
||||
|
||||
return await self._upload_stream(
|
||||
chunks=iter_upload(),
|
||||
upload_url=upload_url,
|
||||
content_type=content_type,
|
||||
timeout=60.0,
|
||||
log_prefix=log_prefix,
|
||||
max_size_bytes=max_size,
|
||||
expected_size_bytes=expected_size_bytes,
|
||||
cleanup_blob_on_failure=True,
|
||||
)
|
||||
|
||||
async def delete_image(self, file_name: str) -> bool:
|
||||
"""이미지 Blob을 삭제합니다. DB 저장 실패 보상 처리용입니다."""
|
||||
sanitized_name = self._sanitize_filename(file_name)
|
||||
upload_url = self._build_upload_url("image", sanitized_name)
|
||||
return await self._delete_upload_url(upload_url, "delete_image")
|
||||
|
||||
|
||||
# 사용 예시:
|
||||
# import asyncio
|
||||
|
||||
Reference in new issue
Block a user