feat(home): 이미지 업로드에 크기·개수 상한과 task 직렬화 락 도입

This commit is contained in:
skkim committed 2026-08-11 17:06:21 +09:00
1 parent 8096837b13
commit f87cd07d5e
5 files changed
+1112 -168

No files matched your search

+395 -154
View File
@@ -1,13 +1,14 @@
import asyncio
import json
import secrets
import time
from datetime import date
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Literal, Optional
from pydantic import BaseModel
from urllib.parse import unquote, urlparse
import aiofiles
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, status
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
@@ -25,14 +26,29 @@ from app.home.schemas.home_schema import (
CrawlingResponse,
ErrorResponse,
ImageUploadResponse,
ImageUploadResultItem,
ImageUrlItem,
ManualMarketingRequest,
ProcessedInfo,
# MarketingAnalysis,
)
from app.home.services.naver_search import naver_search_client
from app.utils.upload_blob_as_request import AzureBlobUploader
from app.home.services.image_upload import (
ALLOWED_IMAGE_EXTENSIONS,
BlobReferenceState,
ImageUploadLockTimeoutError,
assert_continuation_owner as _assert_continuation_owner,
compensate_failed_upload_blobs,
image_result_item as _image_result_item,
image_upload_task_lock,
inspect_upload_file as _inspect_upload_file,
is_valid_image_extension as _is_valid_image_extension,
normalize_continuation_task_id as _normalize_continuation_task_id,
validate_task_image_count,
)
from app.utils.upload_blob_as_request import (
AzureBlobUploader,
BlobUploadTooLargeError,
)
from app.utils.prompts.chatgpt_prompt import ChatgptService, ChatGPTResponseError
from app.utils.common import generate_task_id
from app.utils.logger import get_logger
@@ -43,13 +59,36 @@ from app.utils.address_parser import extract_region_from_address
from app.utils.autotag import autotag_images
from app.utils.image_filter import filter_marketing_images, assemble_images
from app.video.services.video import get_image_tags_by_task_id
from config import MEDIA_ROOT
from config import azure_blob_settings
logger = get_logger("home")
router = APIRouter()
async def _continuation_image_upload_lock(
task_id: Optional[str] = Form(default=None),
current_user: User = Depends(get_current_user),
) -> AsyncIterator[None]:
"""continuation 요청 전체를 task 단위로 직렬화하는 yield dependency입니다."""
# 인증 완료 자체가 lock 획득의 전제이며 endpoint와 dependency cache를 공유합니다.
del current_user
requested_task_id = task_id.strip() if task_id and task_id.strip() else None
if requested_task_id is None:
yield
return
normalized_task_id = _normalize_continuation_task_id(requested_task_id)
try:
async with image_upload_task_lock(normalized_task_id):
yield
except ImageUploadLockTimeoutError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="동일 이미지 작업이 처리 중입니다. 잠시 후 다시 시도해주세요.",
)
@router.get(
"/search/accommodation",
summary="장소 자동완성 검색 (숙박/음식점 등)",
@@ -92,13 +131,23 @@ async def search_accommodation(
)
def _extract_region_from_address(road_address: str | None, jibun_address: str | None = None) -> str:
def _extract_region_from_address(
road_address: str | None, jibun_address: str | None = None
) -> str:
return extract_region_from_address(road_address, jibun_address)
class _IndustryOutput(BaseModel):
industry: Literal[
"stay", "restaurant", "cafe", "salon", "clinic", "fitness", "academy", "attraction", "general"
"stay",
"restaurant",
"cafe",
"salon",
"clinic",
"fitness",
"academy",
"attraction",
"general",
]
@@ -164,10 +213,11 @@ async def _resolve_industry(category: str, customer_name: str = "") -> str:
tags=["Crawling"],
)
async def crawling(
request_body: CrawlingRequest,
session: AsyncSession = Depends(get_session)):
request_body: CrawlingRequest, session: AsyncSession = Depends(get_session)
):
return await _crawling_logic(request_body.url, session)
@router.post(
"/autocomplete",
summary="네이버 자동완성 크롤링",
@@ -200,14 +250,13 @@ async def crawling(
tags=["Crawling"],
)
async def autocomplete_crawling(
request_body: AutoCompleteRequest,
session: AsyncSession = Depends(get_session)):
request_body: AutoCompleteRequest, session: AsyncSession = Depends(get_session)
):
url = await _autocomplete_logic(request_body.model_dump())
return await _crawling_logic(url, session)
async def _crawling_logic(
url:str,
session: AsyncSession):
async def _crawling_logic(url: str, session: AsyncSession):
request_start = time.perf_counter()
logger.info("[crawling] ========== START ==========")
logger.info(f"[crawling] URL: {url[:80]}...")
@@ -318,14 +367,17 @@ async def _crawling_logic(
extra_pass_flags = await filter_marketing_images(
[img["original"] for img in extra_photo_urls], industry
)
except Exception as e:
except Exception:
# logger.error(f"[crawling] Step 3 FAILED - 이미지 필터링 중 오류: {e}")
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail="이미지 마케팅 적합성 필터링 중 오류가 발생했습니다.",
)
scraper.image_link_list = assemble_images(
owner_images, extra_photo_urls, extra_pass_flags, NvMapScraper.MAX_IMAGES
owner_images,
extra_photo_urls,
extra_pass_flags,
NvMapScraper.MAX_IMAGES,
)
passed_count = sum(extra_pass_flags)
step3_elapsed = (time.perf_counter() - step3_start) * 1000
@@ -335,7 +387,9 @@ async def _crawling_logic(
f"({step3_elapsed:.1f}ms)"
)
if not scraper.image_link_list:
logger.warning("[crawling] Step 3 - 필터링 후 사용 가능 이미지가 0장입니다.")
logger.warning(
"[crawling] Step 3 - 필터링 후 사용 가능 이미지가 0장입니다."
)
# ========== Step 4: ChatGPT 마케팅 분석 ==========
step4_start = time.perf_counter()
@@ -376,7 +430,9 @@ async def _crawling_logic(
await session.commit()
await session.refresh(marketing_intel)
m_id = marketing_intel.id
logger.debug(f"[MarketingPrompt] INSERT place_id={marketing_intel.place_id} id={marketing_intel.id}")
logger.debug(
f"[MarketingPrompt] INSERT place_id={marketing_intel.place_id} id={marketing_intel.id}"
)
step4_elapsed = (time.perf_counter() - step4_start) * 1000
logger.info(
@@ -419,17 +475,16 @@ async def _crawling_logic(
logger.info(f"[crawling] - Step 4 (GPT 분석): {step4_elapsed:.1f}ms")
return {
"status": gpt_status if 'gpt_status' in locals() else "completed",
"status": gpt_status if "gpt_status" in locals() else "completed",
"image_list": scraper.image_link_list,
"image_count": len(scraper.image_link_list) if scraper.image_link_list else 0,
"processed_info": processed_info,
"marketing_analysis": marketing_analysis,
"m_id": m_id,
"industry": industry if 'industry' in locals() else "",
"industry": industry if "industry" in locals() else "",
}
@router.post(
"/marketing",
summary="업체명+주소 직접 입력 마케팅 분석",
@@ -515,7 +570,7 @@ async def manual_marketing(
)
async def _autocomplete_logic(autocomplete_item:dict):
async def _autocomplete_logic(autocomplete_item: dict):
step1_start = time.perf_counter()
try:
async with NvMapPwScraper() as pw_scraper:
@@ -543,6 +598,7 @@ async def _autocomplete_logic(autocomplete_item:dict):
return new_url
def _extract_image_name(url: str, index: int) -> str:
"""URL에서 이미지 이름 추출 또는 기본 이름 생성"""
try:
@@ -555,30 +611,6 @@ def _extract_image_name(url: str, index: int) -> str:
return f"image_{index + 1:03d}"
ALLOWED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".heic", ".heif"}
def _is_valid_image_extension(filename: str | None) -> bool:
"""파일명의 확장자가 유효한 이미지 확장자인지 확인"""
if not filename:
return False
ext = Path(filename).suffix.lower()
return ext in ALLOWED_IMAGE_EXTENSIONS
def _get_file_extension(filename: str) -> str:
"""파일명에서 확장자 추출 (소문자)"""
return Path(filename).suffix.lower()
async def _save_upload_file(file: UploadFile, save_path: Path) -> None:
"""업로드 파일을 지정된 경로에 저장"""
save_path.parent.mkdir(parents=True, exist_ok=True)
async with aiofiles.open(save_path, "wb") as f:
content = await file.read()
await f.write(content)
IMAGES_JSON_EXAMPLE = """[
{"url": "https://naverbooking-phinf.pstatic.net/20240514_189/1715688030436xT14o_JPEG/1.jpg"},
{"url": "https://naverbooking-phinf.pstatic.net/20240514_48/1715688030574wTtQd_JPEG/2.jpg"},
@@ -587,12 +619,13 @@ IMAGES_JSON_EXAMPLE = """[
{"url": "https://naverbooking-phinf.pstatic.net/20240514_259/17156880311809wCnY_JPEG/5.jpg", "name": "외관"}
]"""
@router.post(
"/image/upload/blob",
summary="이미지 업로드 (Azure Blob Storage)",
description="""
이미지를 Azure Blob Storage에 업로드하고 새로운 task_id를 생성합니다.
바이너리 파일은 로컬 서버에 저장하지 않고 Azure Blob에 직접 업로드됩니다.
이미지를 Azure Blob Storage에 업로드하고 task_id를 생성하거나 기존 작업에 이어 붙입니다.
바이너리 파일은 로컬 서버 경로에 복사하지 않고 Azure Blob에 청크 업로드됩니다.
## 인증
**Bearer 토큰 필수** - `Authorization: Bearer {access_token}` 헤더를 포함해야 합니다.
@@ -603,8 +636,16 @@ multipart/form-data 형식으로 전송합니다.
## 요청 필드
- **images_json**: 외부 이미지 URL 목록 (JSON 문자열, 선택)
- **files**: 이미지 바이너리 파일 목록 (선택)
- **task_id**: 분할 업로드를 이어갈 기존 task_id (선택, UUID7)
- **finalize**: 누적 이미지 태깅 실행 여부 (기본값 true)
**주의**: images_json 또는 files 중 최소 하나는 반드시 전달해야 합니다.
**주의**:
- 기존 단일 요청은 `finalize=true` 기본값으로 이전과 동일하게 동작합니다.
- 분할 업로드 첫 요청은 `finalize=false`와 최소 1개 파일을 보내고, 응답 task_id를 다음 요청에 전달합니다.
- 중간 요청은 `task_id`와 `finalize=false`, 마지막 요청만 `finalize=true`로 보냅니다.
- 파일 1개는 최대 15 MiB, 한 요청의 파일 합계는 최대 20 MiB입니다.
- 한 task에는 기본 최대 100개의 이미지를 누적할 수 있습니다(서버 설정 가능).
- `finalize=true`일 때 해당 task_id에 누적된 전체 이미지를 한 번에 태깅합니다.
## 지원 이미지 확장자
jpg, jpeg, png, webp, heic, heif
@@ -632,6 +673,19 @@ curl -X POST "http://localhost:8000/image/upload/blob" \\
-H "Authorization: Bearer {access_token}" \\
-F 'images_json=[{"url":"https://example.com/image.jpg"}]' \\
-F "files=@/path/to/local_image.jpg"
# 분할 업로드 첫 요청 (응답의 task_id 보관)
curl -X POST "http://localhost:8000/image/upload/blob" \
-H "Authorization: Bearer {access_token}" \
-F "files=@/path/to/image1.jpg" \
-F "finalize=false"
# 분할 업로드 마지막 요청
curl -X POST "http://localhost:8000/image/upload/blob" \
-H "Authorization: Bearer {access_token}" \
-F "task_id={task_id}" \
-F "files=@/path/to/image2.jpg" \
-F "finalize=true"
```
## 반환 정보
@@ -645,14 +699,17 @@ curl -X POST "http://localhost:8000/image/upload/blob" \\
- **image_urls**: Image 테이블에 저장된 현재 task_id의 이미지 URL 목록
## 저장 경로
- 바이너리 파일: Azure Blob Storage ({BASE_URL}/{task_id}/image/{파일명})
- 바이너리 파일: Azure Blob Storage ({BASE_URL}/{user_uuid}/{task_id}/image/{파일명})
- URL 이미지: 외부 URL 그대로 Image 테이블에 저장
""",
response_model=ImageUploadResponse,
responses={
200: {"description": "이미지 업로드 성공"},
400: {"description": "이미지가 제공되지 않음", "model": ErrorResponse},
400: {"description": "입력 이미지가 유효하지 않음", "model": ErrorResponse},
401: {"description": "인증 실패 (토큰 없음/만료)"},
403: {"description": "continuation task 소유권 검증 실패"},
413: {"description": "파일 또는 요청 크기 제한 초과"},
502: {"description": "Azure Blob 업로드 실패"},
},
tags=["Image-Blob"],
openapi_extra={
@@ -675,11 +732,20 @@ async def upload_images_blob(
default=None,
description="이미지 바이너리 파일 목록",
),
task_id: Optional[str] = Form(
default=None,
description="분할 업로드를 이어갈 기존 task_id (UUID7)",
),
finalize: bool = Form(
default=True,
description="true일 때 누적 이미지 태깅을 실행해 업로드를 완료",
),
industry: str = Form(
default="",
description="업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction|general). 크롤링 응답의 industry 값을 그대로 전달",
),
current_user: User = Depends(get_current_user),
_upload_lock: None = Depends(_continuation_image_upload_lock),
) -> ImageUploadResponse:
"""이미지 업로드 (URL + Azure Blob Storage)
@@ -688,108 +754,249 @@ async def upload_images_blob(
- Stage 2: Azure Blob 업로드 (세션 없음)
- Stage 3: DB 저장 (새 세션으로 빠르게 처리)
"""
del _upload_lock
request_start = time.perf_counter()
requested_task_id = task_id.strip() if task_id and task_id.strip() else None
is_continuation = requested_task_id is not None
# task_id 생성
task_id = await generate_task_id()
logger.info(f"[upload_images_blob] START - task_id: {task_id}")
if requested_task_id:
task_id = _normalize_continuation_task_id(requested_task_id)
async with AsyncSessionLocal() as session:
existing_result = await session.execute(
select(Image)
.where(
Image.task_id == task_id,
Image.is_deleted.is_(False),
)
.order_by(Image.img_order, Image.id)
)
existing_images = list(existing_result.scalars().all())
_assert_continuation_owner(
existing_images,
current_user.user_uuid,
task_id,
)
else:
task_id = await generate_task_id()
existing_images = []
# ========== Stage 1: 입력 검증 및 파일 데이터 준비 (세션 없음) ==========
logger.info(
f"[upload_images_blob] START - task_id: {task_id}, "
f"continuation: {is_continuation}, finalize: {finalize}"
)
# ========== Stage 1: 입력 검증 (세션 없음, 파일 전체 메모리 적재 없음) ==========
has_images_json = images_json is not None and images_json.strip() != ""
has_files = files is not None and len(files) > 0
if not has_images_json and not has_files:
if not has_images_json and not has_files and not (is_continuation and finalize):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="images_json 또는 files 중 하나는 반드시 제공해야 합니다.",
)
# images_json 파싱
url_images: list[ImageUrlItem] = []
if has_images_json and images_json:
try:
parsed = json.loads(images_json)
if isinstance(parsed, list):
url_images = [ImageUrlItem(**item) for item in parsed if item]
if not isinstance(parsed, list):
raise ValueError("JSON 최상위 값은 배열이어야 합니다.")
url_images = [ImageUrlItem(**item) for item in parsed if item]
except (json.JSONDecodeError, TypeError, ValueError) as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"images_json 파싱 오류: {str(e)}",
)
# 유효한 파일만 필터링 및 파일 내용 미리 읽기
valid_files_data: list[tuple[str, str, bytes]] = [] # (original_name, ext, content)
skipped_files: list[str] = []
if has_files and files:
for f in files:
is_valid_ext = _is_valid_image_extension(f.filename)
is_not_empty = f.size is None or f.size > 0
is_real_file = f.filename and f.filename != "filename"
if f and is_real_file and is_valid_ext and is_not_empty:
# 파일 내용을 미리 읽어둠
content = await f.read()
ext = _get_file_extension(f.filename) # type: ignore[arg-type]
valid_files_data.append((f.filename or "image", ext, content))
else:
skipped_files.append(f.filename or "unknown")
if not url_images and not valid_files_data:
detail = (
f"유효한 이미지가 없습니다. "
f"지원 확장자: {', '.join(ALLOWED_IMAGE_EXTENSIONS)}. "
f"건너뛴 파일: {skipped_files}"
upload_files = files or []
declared_total_size = sum(
file.size for file in upload_files if file.size is not None and file.size > 0
)
max_request_size = azure_blob_settings.IMAGE_UPLOAD_MAX_REQUEST_SIZE_BYTES
if declared_total_size > max_request_size:
raise HTTPException(
status_code=status.HTTP_413_CONTENT_TOO_LARGE,
detail=(
"한 요청의 파일 합계가 최대 크기 "
f"{max_request_size // (1024 * 1024)} MiB를 초과합니다."
),
)
valid_files_data: list[tuple[UploadFile, str, str, int]] = []
skipped_files: list[str] = []
actual_total_size = 0
for file in upload_files:
is_real_file = bool(file.filename and file.filename != "filename")
if not is_real_file or not _is_valid_image_extension(file.filename):
skipped_files.append(file.filename or "unknown")
continue
original_name, extension, actual_size = await _inspect_upload_file(file)
actual_total_size += actual_size
if actual_total_size > max_request_size:
raise HTTPException(
status_code=status.HTTP_413_CONTENT_TOO_LARGE,
detail=(
"한 요청의 실제 파일 합계가 최대 크기 "
f"{max_request_size // (1024 * 1024)} MiB를 초과합니다."
),
)
valid_files_data.append((file, original_name, extension, actual_size))
provided_new_input = has_images_json or has_files
if provided_new_input and not url_images and not valid_files_data:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=detail,
detail=(
"유효한 이미지가 없습니다. "
f"지원 확장자: {', '.join(sorted(ALLOWED_IMAGE_EXTENSIONS))}. "
f"건너뛴 파일: {skipped_files}"
),
)
if not is_continuation and not finalize and not valid_files_data:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="분할 업로드의 첫 요청에는 소유권 확인용 이미지 파일이 필요합니다.",
)
validate_task_image_count(
existing_count=len(existing_images),
incoming_count=len(url_images) + len(valid_files_data),
)
stage1_time = time.perf_counter()
logger.info(
f"[upload_images_blob] Stage 1 done - urls: {len(url_images)}, "
f"files: {len(valid_files_data)}, "
f"files: {len(valid_files_data)}, bytes: {actual_total_size}, "
f"elapsed: {(stage1_time - request_start) * 1000:.1f}ms"
)
# ========== Stage 2: Azure Blob 업로드 (세션 없음) ==========
# 업로드 결과를 저장할 리스트 (나중에 DB에 저장)
blob_upload_results: list[tuple[str, str]] = [] # (img_name, blob_url)
img_order = len(url_images) # URL 이미지 다음 순서부터 시작
# ========== Stage 2: Azure Blob 청크 업로드 (세션 없음) ==========
# (원본명, 공개 URL, Azure 저장 파일명)
blob_upload_results: list[tuple[str, str, str]] = []
uploader: AzureBlobUploader | None = None
order_hint = max((image.img_order for image in existing_images), default=-1) + 1
order_hint += len(url_images)
async def cleanup_current_request_blobs() -> None:
if uploader is None:
return
for _, _, stored_name in blob_upload_results:
await uploader.delete_image(stored_name)
async def compensate_failed_db_write(
commit_started: bool,
error: BaseException,
) -> None:
"""DB 반영 여부가 불명확하면 Blob 보존을 우선합니다."""
if not blob_upload_results:
return
blob_urls = {blob_url for _, blob_url, _ in blob_upload_results}
reference_state = await compensate_failed_upload_blobs(
task_id=task_id,
blob_urls=blob_urls,
commit_started=commit_started,
cleanup=cleanup_current_request_blobs,
)
if not commit_started:
return
if reference_state == BlobReferenceState.NONE:
logger.warning(
f"[upload_images_blob] Commit failed and independent DB check "
f"confirmed no Blob references; cleaning up - task_id: {task_id}"
)
return
logger.error(
f"[upload_images_blob] Preserving Blob after ambiguous commit - "
f"task_id: {task_id}, reference_state: {reference_state}, "
f"error: {type(error).__name__}: {error}"
)
async def compensate_after_cancellation(
commit_started: bool,
error: asyncio.CancelledError,
) -> None:
compensation_task = asyncio.create_task(
compensate_failed_db_write(commit_started, error)
)
try:
await asyncio.shield(compensation_task)
except asyncio.CancelledError:
# 반복 취소가 와도 확인/정리가 끝나도록 하며, 실패 시에는 Blob을 보존합니다.
try:
await compensation_task
except BaseException as compensation_error:
logger.error(
f"[upload_images_blob] Cancellation compensation failed; "
f"preserving Blob - task_id: {task_id}, "
f"{type(compensation_error).__name__}: {compensation_error}"
)
if valid_files_data:
uploader = AzureBlobUploader(user_uuid=current_user.user_uuid, task_id=task_id)
total_files = len(valid_files_data)
for idx, (original_name, ext, file_content) in enumerate(valid_files_data):
name_without_ext = (
original_name.rsplit(".", 1)[0]
if "." in original_name
else original_name
for idx, (file, original_name, extension, actual_size) in enumerate(
valid_files_data
):
name_without_ext = Path(original_name).stem
unique_suffix = secrets.token_hex(4)
stored_name = (
f"{name_without_ext}_{order_hint + idx:03d}_{unique_suffix}{extension}"
)
filename = f"{name_without_ext}_{img_order:03d}{ext}"
logger.debug(
f"[upload_images_blob] Uploading file {idx + 1}/{total_files}: "
f"{filename} ({len(file_content)} bytes)"
f"{stored_name} ({actual_size} bytes)"
)
# Azure Blob Storage에 직접 업로드
upload_success = await uploader.upload_image_bytes(file_content, filename)
try:
upload_success = await uploader.upload_image_stream(
file,
stored_name,
expected_size_bytes=actual_size,
max_size_bytes=(
azure_blob_settings.IMAGE_UPLOAD_MAX_FILE_SIZE_BYTES
),
)
except BlobUploadTooLargeError as exc:
await cleanup_current_request_blobs()
raise HTTPException(
status_code=status.HTTP_413_CONTENT_TOO_LARGE,
detail=(
f"파일 '{original_name}'이 최대 크기 "
f"{exc.max_size_bytes // (1024 * 1024)} MiB를 초과합니다."
),
)
except asyncio.CancelledError:
await asyncio.shield(cleanup_current_request_blobs())
raise
if upload_success:
blob_url = uploader.public_url
blob_upload_results.append((original_name, blob_url))
img_order += 1
blob_upload_results.append(
(original_name, uploader.public_url, stored_name)
)
logger.debug(
f"[upload_images_blob] File {idx + 1}/{total_files} SUCCESS"
)
else:
skipped_files.append(filename)
skipped_files.append(stored_name)
logger.warning(
f"[upload_images_blob] File {idx + 1}/{total_files} FAILED"
)
if valid_files_data and not blob_upload_results and not url_images:
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail="Azure Blob Storage 이미지 업로드에 실패했습니다.",
)
if not is_continuation and not finalize and not blob_upload_results:
# URL row만 남으면 다음 요청에서 소유권을 증명할 수 없으므로 저장하지 않습니다.
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail="분할 업로드를 시작할 이미지 파일 업로드에 실패했습니다.",
)
stage2_time = time.perf_counter()
logger.info(
f"[upload_images_blob] Stage 2 done - blob uploads: "
@@ -799,15 +1006,49 @@ async def upload_images_blob(
# ========== Stage 3: DB 저장 (새 세션으로 빠르게 처리) ==========
logger.info("[upload_images_blob] Stage 3 starting - DB save...")
result_images: list[ImageUploadResultItem] = []
img_order = 0
all_images: list[Image] = []
commit_started = False
try:
async with AsyncSessionLocal() as session:
# URL 이미지 저장
# 같은 task의 append 요청을 직렬화해 img_order 충돌을 줄입니다.
locked_result = await session.execute(
select(Image)
.where(
Image.task_id == task_id,
Image.is_deleted.is_(False),
)
.order_by(Image.img_order, Image.id)
.with_for_update()
)
locked_images = list(locked_result.scalars().all())
if is_continuation:
_assert_continuation_owner(
locked_images,
current_user.user_uuid,
task_id,
)
elif locked_images:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="이미 사용 중인 task_id가 생성되었습니다. 다시 시도해주세요.",
)
validate_task_image_count(
existing_count=len(locked_images),
incoming_count=len(url_images) + len(blob_upload_results),
)
img_order = (
max(
(image.img_order for image in locked_images),
default=-1,
)
+ 1
)
new_images: list[Image] = []
for url_item in url_images:
img_name = url_item.name or _extract_image_name(url_item.url, img_order)
image = Image(
task_id=task_id,
img_name=img_name,
@@ -815,21 +1056,10 @@ async def upload_images_blob(
img_order=img_order,
)
session.add(image)
await session.flush()
result_images.append(
ImageUploadResultItem(
id=image.id,
img_name=img_name,
img_url=url_item.url,
img_order=img_order,
source="url",
)
)
new_images.append(image)
img_order += 1
# Blob 업로드 결과 저장
for img_name, blob_url in blob_upload_results:
for img_name, blob_url, _ in blob_upload_results:
image = Image(
task_id=task_id,
img_name=img_name,
@@ -837,28 +1067,31 @@ async def upload_images_blob(
img_order=img_order,
)
session.add(image)
await session.flush()
result_images.append(
ImageUploadResultItem(
id=image.id,
img_name=img_name,
img_url=blob_url,
img_order=img_order,
source="blob",
)
)
new_images.append(image)
img_order += 1
await session.flush()
all_images = sorted(
[*locked_images, *new_images],
key=lambda image: (image.img_order, image.id),
)
commit_started = True
await session.commit()
stage3_time = time.perf_counter()
logger.info(
f"[upload_images_blob] Stage 3 done - "
f"saved: {len(result_images)}, "
f"task total: {len(all_images)}, added: {len(new_images)}, "
f"elapsed: {(stage3_time - stage2_time) * 1000:.1f}ms"
)
except asyncio.CancelledError as e:
await compensate_after_cancellation(commit_started, e)
raise
except HTTPException as e:
await compensate_failed_db_write(commit_started, e)
raise
except SQLAlchemyError as e:
await compensate_failed_db_write(commit_started, e)
logger.error(f"[upload_images_blob] DB Error - task_id: {task_id}, error: {e}")
logger.exception("[upload_images_blob] DB 상세 오류:")
raise HTTPException(
@@ -866,6 +1099,7 @@ async def upload_images_blob(
detail="이미지 저장 중 데이터베이스 오류가 발생했습니다.",
)
except Exception as e:
await compensate_failed_db_write(commit_started, e)
logger.error(
f"[upload_images_blob] Stage 3 EXCEPTION - "
f"task_id: {task_id}, error: {type(e).__name__}: {e}"
@@ -876,24 +1110,31 @@ async def upload_images_blob(
detail="이미지 업로드 중 오류가 발생했습니다.",
)
result_images = [_image_result_item(image) for image in all_images]
saved_count = len(result_images)
image_urls = [img.img_url for img in result_images]
logger.info(f"[image_tagging] START - task_id: {task_id}")
await tagging_images(image_urls, industry=industry, clear_old_tags=True)
logger.info(f"[image_tagging] Done - task_id: {task_id}")
if finalize:
logger.info(f"[image_tagging] START - task_id: {task_id}")
await tagging_images(image_urls, industry=industry, clear_old_tags=True)
logger.info(f"[image_tagging] Done - task_id: {task_id}")
# 태깅 직후 영상 생성에 사용 가능한 이미지가 하나도 없으면 조기에 실패시킨다.
# (여기서 걸러지지 않으면 훨씬 나중인 영상 생성 단계에서야 슬롯 미배정으로 발견됨)
# marketing_acceptable 필터링은 크롤링 단계에서 이미 완료되었으므로 여기서는 재필터링하지 않는다.
taged_image_list = await get_image_tags_by_task_id(task_id)
logger.info(f"태깅된 이미지: {len(taged_image_list)}개 - task_id: {task_id}")
if not taged_image_list:
logger.error(f"[image_tagging] 영상 생성에 적합한 이미지가 없음 - task_id: {task_id}")
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="영상 생성에 적합한 이미지가 없습니다. 다른 이미지로 다시 업로드해주세요.",
)
# 마지막 분할 요청에서 누적된 전체 이미지의 적합성을 확인합니다.
taged_image_list = await get_image_tags_by_task_id(task_id)
logger.info(f"태깅된 이미지: {len(taged_image_list)}개 - task_id: {task_id}")
if not taged_image_list:
logger.error(
f"[image_tagging] 영상 생성에 적합한 이미지가 없음 - task_id: {task_id}"
)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=(
"영상 생성에 적합한 이미지가 없습니다. "
"다른 이미지로 다시 업로드해주세요."
),
)
else:
logger.info(f"[image_tagging] DEFERRED - task_id: {task_id}")
total_time = time.perf_counter() - request_start
logger.info(
@@ -903,9 +1144,9 @@ async def upload_images_blob(
return ImageUploadResponse(
task_id=task_id,
total_count=len(result_images),
url_count=len(url_images),
file_count=len(blob_upload_results),
total_count=saved_count,
url_count=sum(image.source == "url" for image in result_images),
file_count=sum(image.source == "blob" for image in result_images),
saved_count=saved_count,
images=result_images,
image_urls=image_urls,
@@ -913,10 +1154,8 @@ async def upload_images_blob(
async def tagging_images(
image_urls : list[str],
industry: str = "",
clear_old_tags : bool = False
) -> None:
image_urls: list[str], industry: str = "", clear_old_tags: bool = False
) -> None:
# 1. 조회
async with AsyncSessionLocal() as session:
stmt = (
@@ -938,9 +1177,11 @@ async def tagging_images(
session.add_all(new_imt)
null_imts = [imt for imt in image_tags if imt.img_tag is None] + new_imt
await session.commit()
if null_imts:
tag_datas = await autotag_images([img.img_url for img in null_imts], industry=industry)
tag_datas = await autotag_images(
[img.img_url for img in null_imts], industry=industry
)
# print(tag_datas)
async with AsyncSessionLocal() as session: