blob 이미지 업로드 완료

This commit is contained in:
bluebamus committed 2025-12-26 15:25:13 +09:00
1 parent 6917a76d60
commit 12e6f7357c
8 files changed
+756 -447

No files matched your search

+214 -243
View File
@@ -20,6 +20,7 @@ from app.home.schemas.home_schema import (
MarketingAnalysis,
ProcessedInfo,
)
from app.utils.upload_blob_as_request import AzureBlobUploader
from app.utils.chatgpt_prompt import ChatgptService
from app.utils.common import generate_task_id
from app.utils.nvMapScraper import NvMapScraper
@@ -178,10 +179,11 @@ IMAGES_JSON_EXAMPLE = """[
@router.post(
"/image/{task_id}/upload",
"/image/upload/server/{task_id}",
include_in_schema=False,
summary="이미지 업로드",
description="""
task_id에 연결된 이미지를 업로드합니다.
task_id에 연결된 이미지를 서버에 업로드합니다.
## 요청 방식
multipart/form-data 형식으로 전송합니다.
@@ -218,12 +220,12 @@ jpg, jpeg, png, webp, heic, heif
### 2. cURL로 테스트
```bash
# 바이너리 파일만 업로드
curl -X POST "http://localhost:8000/image/test-task-001/upload" \\
curl -X POST "http://localhost:8000/image/upload/server/test-task-001" \\
-F "files=@/path/to/image1.jpg" \\
-F "files=@/path/to/image2.png"
# URL + 바이너리 파일 동시 업로드
curl -X POST "http://localhost:8000/image/test-task-001/upload" \\
curl -X POST "http://localhost:8000/image/upload/server/test-task-001" \\
-F 'images_json=[{"url":"https://example.com/image.jpg"}]' \\
-F "files=@/path/to/local_image.jpg"
```
@@ -232,7 +234,7 @@ curl -X POST "http://localhost:8000/image/test-task-001/upload" \\
```python
import requests
url = "http://localhost:8000/image/test-task-001/upload"
url = "http://localhost:8000/image/upload/server/test-task-001"
files = [
("files", ("image1.jpg", open("image1.jpg", "rb"), "image/jpeg")),
("files", ("image2.png", open("image2.png", "rb"), "image/png")),
@@ -252,7 +254,7 @@ print(response.json())
- **images**: 업로드된 이미지 목록
## 저장 경로
- 바이너리 파일: /media/{날짜}/{uuid7}/{파일명}
- 바이너리 파일: /media/image/{날짜}/{uuid7}/{파일명}
""",
response_model=ImageUploadResponse,
responses={
@@ -285,7 +287,9 @@ async def upload_images(
if has_files and files:
for idx, f in enumerate(files):
print(f"[upload_images] file[{idx}]: filename={f.filename}, size={f.size}, content_type={f.content_type}")
print(
f"[upload_images] file[{idx}]: filename={f.filename}, size={f.size}, content_type={f.content_type}"
)
if not has_images_json and not has_files:
raise HTTPException(
@@ -312,16 +316,24 @@ async def upload_images(
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 # size가 None이면 아직 읽지 않은 것
is_real_file = f.filename and f.filename != "filename" # Swagger 빈 파일 체크
print(f"[upload_images] Checking file: {f.filename}, size={f.size}, is_valid_ext={is_valid_ext}, is_real_file={is_real_file}")
is_not_empty = (
f.size is None or f.size > 0
) # size가 None이면 아직 읽지 않은 것
is_real_file = (
f.filename and f.filename != "filename"
) # Swagger 빈 파일 체크
print(
f"[upload_images] Checking file: {f.filename}, size={f.size}, is_valid_ext={is_valid_ext}, is_real_file={is_real_file}"
)
if f and is_real_file and is_valid_ext and is_not_empty:
valid_files.append(f)
else:
skipped_files.append(f.filename or "unknown")
print(f"[upload_images] valid_files count: {len(valid_files)}, skipped: {skipped_files}")
print(
f"[upload_images] valid_files count: {len(valid_files)}, skipped: {skipped_files}"
)
# 유효한 데이터가 하나도 없으면 에러
if not url_images and not valid_files:
@@ -358,7 +370,7 @@ async def upload_images(
)
img_order += 1
# 2. 바이너리 파일 저장
# 2. 바이너리 파일을 media에 저장
if valid_files:
today = date.today().strftime("%Y-%m-%d")
# 한 번의 요청에서 업로드된 모든 이미지는 같은 폴더에 저장
@@ -371,22 +383,27 @@ async def upload_images(
original_name = file.filename or "image"
ext = _get_file_extension(file.filename) # type: ignore[arg-type]
# 파일명에서 확장자 제거 후 순서 추가
name_without_ext = original_name.rsplit(".", 1)[0] if "." in original_name else original_name
name_without_ext = (
original_name.rsplit(".", 1)[0]
if "." in original_name
else original_name
)
filename = f"{name_without_ext}_{img_order:03d}{ext}"
save_path = upload_dir / filename
# 파일 저장
# media에 파일 저장
await _save_upload_file(file, save_path)
# 이미지 URL 생성
# media 기준 URL 생성
img_url = f"/media/image/{today}/{batch_uuid}/{filename}"
img_name = file.filename or filename
print(f"[upload_images] File saved to media - path: {save_path}, url: {img_url}")
image = Image(
task_id=task_id,
img_name=img_name,
img_url=img_url,
img_url=img_url, # Media URL을 DB에 저장
img_order=img_order,
)
session.add(image)
@@ -403,7 +420,8 @@ async def upload_images(
)
img_order += 1
print(f"[upload_images] Committing {len(result_images)} images to database...")
saved_count = len(result_images)
print(f"[upload_images] Committing {saved_count} images to database...")
await session.commit()
print("[upload_images] Commit successful!")
@@ -412,263 +430,216 @@ async def upload_images(
total_count=len(result_images),
url_count=len(url_images),
file_count=len(valid_files),
saved_count=saved_count,
images=result_images,
)
# @router.post(
# "/generate",
# summary="기본 영상 생성 요청",
# description="""
# 고객 정보만 받아 영상 생성 작업을 시작합니다. (이미지 없음)
@router.post(
"/image/upload/blob/{task_id}",
summary="이미지 업로드 (Azure Blob)",
description="""
task_id에 연결된 이미지를 Azure Blob Storage에 업로드합니다.
# ## 요청 필드
# - **customer_name**: 고객명/가게명 (필수)
# - **region**: 지역명 (필수)
# - **detail_region_info**: 상세 지역 정보 (선택)
# - **attribute**: 음악 속성 정보 (genre, vocal, tempo, mood)
## 요청 방식
multipart/form-data 형식으로 전송합니다.
# ## 반환 정보
# - **task_id**: 작업 고유 식별자 (UUID7)
# - **status**: 작업 상태
# - **message**: 응답 메시지
# """,
# response_model=GenerateResponse,
# response_description="생성 작업 시작 결과",
# tags=["generate"],
# )
# async def generate(
# request_body: GenerateRequest,
# background_tasks: BackgroundTasks,
# session: AsyncSession = Depends(get_session),
# ):
# """기본 영상 생성 요청 처리 (이미지 없음)"""
# # UUID7 생성 및 중복 검사
# while True:
# task_id = str(uuid7())
# existing = await session.execute(
# select(Project).where(Project.task_id == task_id)
# )
# if existing.scalar_one_or_none() is None:
# break
## 요청 필드
- **images_json**: 외부 이미지 URL 목록 (JSON 문자열, 선택)
- **files**: 이미지 바이너리 파일 목록 (선택)
# # Project 생성 (이미지 없음)
# project = Project(
# store_name=request_body.customer_name,
# region=request_body.region,
# task_id=task_id,
# detail_region_info=json.dumps(
# {
# "detail": request_body.detail_region_info,
# "attribute": request_body.attribute.model_dump(),
# },
# ensure_ascii=False,
# ),
# )
# session.add(project)
# await session.commit()
# await session.refresh(project)
**주의**: images_json 또는 files 중 최소 하나는 반드시 전달해야 합니다.
# background_tasks.add_task(task_process, request_body, task_id, project.id)
## 지원 이미지 확장자
jpg, jpeg, png, webp, heic, heif
# return {
# "task_id": task_id,
# "status": "processing",
# "message": "생성 작업이 시작되었습니다.",
# }
## images_json 예시
```json
[
{"url": "https://example.com/image1.jpg"},
{"url": "https://example.com/image2.jpg", "name": "외관"}
]
```
## 바이너리 파일 업로드 테스트 방법
# @router.post(
# "/generate/urls",
# summary="URL 기반 영상 생성 요청",
# description="""
# 고객 정보와 이미지 URL을 받아 영상 생성 작업을 시작합니다.
### cURL로 테스트
```bash
# 바이너리 파일만 업로드
curl -X POST "http://localhost:8000/image/upload/blob/test-task-001" \\
-F "files=@/path/to/image1.jpg" \\
-F "files=@/path/to/image2.png"
# ## 요청 필드
# - **customer_name**: 고객명/가게명 (필수)
# - **region**: 지역명 (필수)
# - **detail_region_info**: 상세 지역 정보 (선택)
# - **attribute**: 음악 속성 정보 (genre, vocal, tempo, mood)
# - **images**: 이미지 URL 목록 (필수)
# URL + 바이너리 파일 동시 업로드
curl -X POST "http://localhost:8000/image/upload/blob/test-task-001" \\
-F 'images_json=[{"url":"https://example.com/image.jpg"}]' \\
-F "files=@/path/to/local_image.jpg"
```
# ## 반환 정보
# - **task_id**: 작업 고유 식별자 (UUID7)
# - **status**: 작업 상태
# - **message**: 응답 메시지
# """,
# response_model=GenerateResponse,
# response_description="생성 작업 시작 결과",
# tags=["generate"],
# )
# async def generate_urls(
# request_body: GenerateUrlsRequest,
# session: AsyncSession = Depends(get_session),
# ):
# """URL 기반 영상 생성 요청 처리"""
# # UUID7 생성 및 중복 검사
# while True:
# task_id = str(uuid7())
# existing = await session.execute(
# select(Project).where(Project.task_id == task_id)
# )
# if existing.scalar_one_or_none() is None:
# break
## 반환 정보
- **task_id**: 작업 고유 식별자
- **total_count**: 총 업로드된 이미지 개수
- **url_count**: URL로 등록된 이미지 개수
- **file_count**: 파일로 업로드된 이미지 개수 (Blob에 저장됨)
- **images**: 업로드된 이미지 목록
# # Project 생성 (이미지 정보 제외)
# project = Project(
# store_name=request_body.customer_name,
# region=request_body.region,
# task_id=task_id,
# detail_region_info=json.dumps(
# {
# "detail": request_body.detail_region_info,
# "attribute": request_body.attribute.model_dump(),
# },
# ensure_ascii=False,
# ),
# )
# session.add(project)
## 저장 경로
- 바이너리 파일: Azure Blob Storage ({task_id}/{파일명})
""",
response_model=ImageUploadResponse,
responses={
200: {"description": "이미지 업로드 성공"},
400: {"description": "이미지가 제공되지 않음", "model": ErrorResponse},
},
tags=["image"],
)
async def upload_images_blob(
task_id: str,
images_json: Optional[str] = Form(
default=None,
description="외부 이미지 URL 목록 (JSON 문자열)",
example=IMAGES_JSON_EXAMPLE,
),
files: Optional[list[UploadFile]] = File(
default=None, description="이미지 바이너리 파일 목록"
),
session: AsyncSession = Depends(get_session),
) -> ImageUploadResponse:
"""이미지 업로드 (URL + Azure Blob Storage)"""
print(f"[upload_images_blob] START - task_id: {task_id}")
# # Image 레코드 생성 (독립 테이블, task_id로 연결)
# for idx, img_item in enumerate(request_body.images):
# # name이 있으면 사용, 없으면 URL에서 추출
# img_name = img_item.name or _extract_image_name(img_item.url, idx)
# image = Image(
# task_id=task_id,
# img_name=img_name,
# img_url=img_item.url,
# img_order=idx,
# )
# session.add(image)
# 1. 진입 검증
has_images_json = images_json is not None and images_json.strip() != ""
has_files = files is not None and len(files) > 0
# await session.commit()
if not has_images_json and not has_files:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="images_json 또는 files 중 하나는 반드시 제공해야 합니다.",
)
# return {
# "task_id": task_id,
# "status": "processing",
# "message": "생성 작업이 시작되었습니다.",
# }
# 2. images_json 파싱
url_images: list[ImageUrlItem] = []
if has_images_json:
try:
parsed = json.loads(images_json)
if isinstance(parsed, list):
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)}",
)
# 3. 유효한 파일만 필터링
valid_files: list[UploadFile] = []
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"
# 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)
if f and is_real_file and is_valid_ext and is_not_empty:
valid_files.append(f)
else:
skipped_files.append(f.filename or "unknown")
print(f"[upload_images_blob] valid_files: {len(valid_files)}, url_images: {len(url_images)}")
# def _get_file_extension(filename: str | None) -> str:
# """파일명에서 확장자 추출"""
# if not filename:
# return ".jpg"
# ext = Path(filename).suffix.lower()
# return ext if ext else ".jpg"
if not url_images and not valid_files:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"유효한 이미지가 없습니다. 지원 확장자: {', '.join(ALLOWED_IMAGE_EXTENSIONS)}. 건너뛴 파일: {skipped_files}",
)
result_images: list[ImageUploadResultItem] = []
img_order = 0
# @router.post(
# "/generate/upload",
# summary="파일 업로드 기반 영상 생성 요청",
# description="""
# 고객 정보와 이미지 파일을 받아 영상 생성 작업을 시작합니다.
# 1. URL 이미지 저장
for url_item in url_images:
img_name = url_item.name or _extract_image_name(url_item.url, img_order)
# ## 요청 필드 (multipart/form-data)
# - **customer_name**: 고객명/가게명 (필수)
# - **region**: 지역명 (필수)
# - **detail_region_info**: 상세 지역 정보 (선택)
# - **attribute**: 음악 속성 정보 JSON 문자열 (필수)
# - **images**: 이미지 파일 목록 (필수, 복수 파일)
image = Image(
task_id=task_id,
img_name=img_name,
img_url=url_item.url,
img_order=img_order,
)
session.add(image)
await session.flush()
print(f"[upload_images_blob] URL saved - id: {image.id}, img_name: {img_name}")
# ## 반환 정보
# - **task_id**: 작업 고유 식별자 (UUID7)
# - **status**: 작업 상태
# - **message**: 응답 메시지
# - **uploaded_count**: 업로드된 이미지 개수
# """,
# response_model=GenerateUploadResponse,
# response_description="생성 작업 시작 결과",
# tags=["generate"],
# )
# async def generate_upload(
# customer_name: str = Form(..., description="고객명/가게명"),
# region: str = Form(..., description="지역명"),
# attribute: str = Form(..., description="음악 속성 정보 (JSON 문자열)"),
# images: list[UploadFile] = File(..., description="이미지 파일 목록"),
# detail_region_info: str | None = Form(None, description="상세 지역 정보"),
# session: AsyncSession = Depends(get_session),
# ):
# """파일 업로드 기반 영상 생성 요청 처리"""
# # attribute JSON 파싱 및 검증
# try:
# attribute_dict = json.loads(attribute)
# attribute_info = AttributeInfo(**attribute_dict)
# except json.JSONDecodeError:
# raise HTTPException(
# status_code=400, detail="attribute는 유효한 JSON 형식이어야 합니다."
# )
# except Exception as e:
# raise HTTPException(status_code=400, detail=f"attribute 검증 실패: {e}")
result_images.append(
ImageUploadResultItem(
id=image.id,
img_name=img_name,
img_url=url_item.url,
img_order=img_order,
source="url",
)
)
img_order += 1
# # 이미지 파일 검증
# if not images:
# raise HTTPException(
# status_code=400, detail="최소 1개 이상의 이미지 파일이 필요합니다."
# )
# 2. 바이너리 파일을 Azure Blob Storage에 직접 업로드 (media 저장 없음)
if valid_files:
uploader = AzureBlobUploader(task_id=task_id)
# # UUID7 생성 및 중복 검사
# while True:
# task_id = str(uuid7())
# existing = await session.execute(
# select(Project).where(Project.task_id == task_id)
# )
# if existing.scalar_one_or_none() is None:
# break
for file in valid_files:
original_name = file.filename or "image"
ext = _get_file_extension(file.filename) # type: ignore[arg-type]
name_without_ext = (
original_name.rsplit(".", 1)[0]
if "." in original_name
else original_name
)
filename = f"{name_without_ext}_{img_order:03d}{ext}"
# # 저장 경로 생성: media/날짜/task_id/
# today = date.today().strftime("%Y%m%d")
# upload_dir = MEDIA_ROOT / today / task_id
# 파일 내용 읽기
file_content = await file.read()
print(f"[upload_images_blob] Uploading {filename} ({len(file_content)} bytes) to Blob...")
# # Project 생성 (이미지 정보 제외)
# project = Project(
# store_name=customer_name,
# region=region,
# task_id=task_id,
# detail_region_info=json.dumps(
# {
# "detail": detail_region_info,
# "attribute": attribute_info.model_dump(),
# },
# ensure_ascii=False,
# ),
# )
# session.add(project)
# Azure Blob Storage에 직접 업로드
upload_success = await uploader.upload_image_bytes(file_content, filename)
# # 이미지 파일 저장 및 Image 레코드 생성
# for idx, file in enumerate(images):
# # 각 이미지에 고유 UUID7 생성
# img_uuid = str(uuid7())
# ext = _get_file_extension(file.filename)
# filename = f"{img_uuid}{ext}"
# save_path = upload_dir / filename
if upload_success:
blob_url = uploader.public_url
img_name = file.filename or filename
# # 파일 저장
# await _save_upload_file(file, save_path)
image = Image(
task_id=task_id,
img_name=img_name,
img_url=blob_url,
img_order=img_order,
)
session.add(image)
await session.flush()
print(f"[upload_images_blob] Blob saved - id: {image.id}, blob_url: {blob_url}")
# # Image 레코드 생성 (독립 테이블, task_id로 연결)
# img_url = f"/media/{today}/{task_id}/{filename}"
# image = Image(
# task_id=task_id,
# img_name=file.filename or filename,
# img_url=img_url,
# img_order=idx,
# )
# session.add(image)
result_images.append(
ImageUploadResultItem(
id=image.id,
img_name=img_name,
img_url=blob_url,
img_order=img_order,
source="blob",
)
)
img_order += 1
else:
print(f"[upload_images_blob] Failed to upload {filename}")
skipped_files.append(filename)
# await session.commit()
saved_count = len(result_images)
print(f"[upload_images_blob] Committing {saved_count} images...")
await session.commit()
print(f"[upload_images_blob] Done! saved_count: {saved_count}")
# return {
# "task_id": task_id,
# "status": "processing",
# "message": "생성 작업이 시작되었습니다.",
# "uploaded_count": len(images),
# }
return ImageUploadResponse(
task_id=task_id,
total_count=len(result_images),
url_count=len(url_images),
file_count=len(valid_files) - len(skipped_files),
saved_count=saved_count,
images=result_images,
)