Compare commits

...
Author SHA1 Message Date
skkim 1e3da98c6a Merge branch 'main' into feature-credit 2026-04-28 14:48:31 +09:00
dhlim 1137174398 image retagging 2026-04-28 05:45:01 +00:00
skkim 6492d23bc1 크레딧 기능 추가 2026-04-28 14:34:19 +09:00
HyeongBaeYang bb9832f4ce test commit . 2026-04-20 10:08:24 +09:00
skkim 7202376123 대시보드 예외처리 변경 2026-04-09 08:41:16 +09:00
14 changed files with 172 additions and 19 deletions

No files matched your search

+2
View File
@@ -276,3 +276,5 @@ fastapi run main.py
│◀───────────────│ │ │ │◀───────────────│ │ │
│ │ │ │ │ │ │ │
``` ```
testAc
+4 -1
View File
@@ -314,7 +314,10 @@ def add_exception_handlers(app: FastAPI):
@app.exception_handler(DashboardException) @app.exception_handler(DashboardException)
def dashboard_exception_handler(request: Request, exc: DashboardException) -> Response: def dashboard_exception_handler(request: Request, exc: DashboardException) -> Response:
logger.debug(f"Handled DashboardException: {exc.__class__.__name__} - {exc.message}") if exc.status_code < 500:
logger.warning(f"Handled DashboardException: {exc.__class__.__name__} - {exc.message}")
else:
logger.error(f"Handled DashboardException: {exc.__class__.__name__} - {exc.message}")
return JSONResponse( return JSONResponse(
status_code=exc.status_code, status_code=exc.status_code,
content={ content={
+20 -16
View File
@@ -751,7 +751,7 @@ async def upload_images_blob(
image_urls = [img.img_url for img in result_images] image_urls = [img.img_url for img in result_images]
logger.info(f"[image_tagging] START - task_id: {task_id}") logger.info(f"[image_tagging] START - task_id: {task_id}")
await tag_images_if_not_exist(image_urls) await tagging_images(image_urls, clear_old_tags=True)
logger.info(f"[image_tagging] Done - task_id: {task_id}") logger.info(f"[image_tagging] Done - task_id: {task_id}")
total_time = time.perf_counter() - request_start total_time = time.perf_counter() - request_start
@@ -771,8 +771,9 @@ async def upload_images_blob(
) )
async def tag_images_if_not_exist( async def tagging_images(
image_urls : list[str] image_urls : list[str],
clear_old_tags : bool = False
) -> None: ) -> None:
# 1. 조회 # 1. 조회
async with AsyncSessionLocal() as session: async with AsyncSessionLocal() as session:
@@ -784,21 +785,24 @@ async def tag_images_if_not_exist(
image_tags_query_results = await session.execute(stmt) image_tags_query_results = await session.execute(stmt)
image_tags = image_tags_query_results.scalars().all() image_tags = image_tags_query_results.scalars().all()
existing_urls = {tag.img_url for tag in image_tags} existing_urls = {tag.img_url for tag in image_tags}
new_tags = [ new_imt = [
ImageTag(img_url=url, img_tag=None) ImageTag(img_url=url, img_tag=None)
for url in image_urls for url in image_urls
if url not in existing_urls if url not in existing_urls
] ]
session.add_all(new_tags) if clear_old_tags:
for tag in image_tags:
null_tags = [tag for tag in image_tags if tag.img_tag is None] + new_tags tag.img_tag = None
session.add_all(new_imt)
if null_tags: null_imts = [imt for imt in image_tags if imt.img_tag is None] + new_imt
tag_datas = await autotag_images([img.img_url for img in null_tags])
print(tag_datas)
for tag, tag_data in zip(null_tags, tag_datas):
tag.img_tag = tag_data.model_dump(mode="json")
await session.commit() await session.commit()
if null_imts:
tag_datas = await autotag_images([img.img_url for img in null_imts])
print(tag_datas)
async with AsyncSessionLocal() as session:
for tag, tag_data in zip(null_imts, tag_datas):
tag.img_tag = tag_data.model_dump(mode="json")
session.add(tag)
await session.commit()
+15
View File
@@ -240,6 +240,21 @@ async def generate_lyric(
request_start = time.perf_counter() request_start = time.perf_counter()
task_id = request_body.task_id task_id = request_body.task_id
user = (await session.execute(
select(User).where(User.user_uuid == current_user.user_uuid)
)).scalar_one()
if user.credits <= 0:
logger.info(
f"크레딧 부족, user_uuid: {current_user.user_uuid}, credits: {current_user.credits}"
)
return GenerateLyricResponse(
success=False,
task_id=task_id,
lyric=None,
language=request_body.language,
error_message="No credits remaining.",
)
logger.info(f"[generate_lyric] ========== START ==========") logger.info(f"[generate_lyric] ========== START ==========")
logger.info( logger.info(
+16
View File
@@ -103,6 +103,22 @@ async def generate_song(
from app.database.session import AsyncSessionLocal from app.database.session import AsyncSessionLocal
request_start = time.perf_counter() request_start = time.perf_counter()
async with AsyncSessionLocal() as session:
user = (await session.execute(
select(User).where(User.user_uuid == current_user.user_uuid)
)).scalar_one()
if user.credits <= 0:
logger.info(f"크레딧 부족, user_uuid: {current_user.user_uuid}, credits: {user.credits}")
return GenerateSongResponse(
success=False,
task_id=task_id,
song_id=None,
message="No credits remaining.",
error_message="No credits remaining.",
)
logger.info( logger.info(
f"[generate_song] START - task_id: {task_id}, " f"[generate_song] START - task_id: {task_id}, "
f"genre: {request_body.genre}, language: {request_body.language}" f"genre: {request_body.genre}, language: {request_body.language}"
+17
View File
@@ -23,6 +23,7 @@ logger = logging.getLogger(__name__)
from app.user.dependencies import get_current_user from app.user.dependencies import get_current_user
from app.user.models import RefreshToken, User from app.user.models import RefreshToken, User
from app.user.schemas.user_schema import ( from app.user.schemas.user_schema import (
CreditResponse,
KakaoCodeRequest, KakaoCodeRequest,
KakaoLoginResponse, KakaoLoginResponse,
LoginResponse, LoginResponse,
@@ -353,6 +354,22 @@ async def get_me(
return UserResponse.model_validate(current_user) return UserResponse.model_validate(current_user)
@router.get(
"/me/credits",
response_model=CreditResponse,
summary="잔여 크레딧 조회",
description="현재 로그인한 사용자의 잔여 영상 생성 크레딧을 반환합니다.",
responses={
200: {"description": "조회 성공"},
401: {"description": "인증 실패 (토큰 없음/만료)"},
},
)
async def get_my_credits(
current_user: User = Depends(get_current_user),
) -> CreditResponse:
return CreditResponse(credits=current_user.credits)
# ============================================================================= # =============================================================================
# 테스트용 엔드포인트 (DEBUG 모드에서만 main.py에서 라우터가 등록됨) # 테스트용 엔드포인트 (DEBUG 모드에서만 main.py에서 라우터가 등록됨)
# ============================================================================= # =============================================================================
+8
View File
@@ -216,6 +216,14 @@ class User(Base):
comment="마지막 로그인 일시", comment="마지막 로그인 일시",
) )
credits: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=3,
server_default="3",
comment="잔여 영상 생성 크레딧",
)
created_at: Mapped[datetime] = mapped_column( created_at: Mapped[datetime] = mapped_column(
DateTime, DateTime,
nullable=False, nullable=False,
+16
View File
@@ -160,6 +160,22 @@ class LoginResponse(BaseModel):
} }
} }
# =============================================================================
# 크레딧 스키마
# =============================================================================
class CreditResponse(BaseModel):
"""잔여 크레딧 응답"""
credits: int = Field(..., description="영상 생성 크레딧")
model_config = {
"json_schema_extra": {
"example": {
"credits": 3
}
}
}
# ============================================================================= # =============================================================================
# 내부 사용 스키마 (카카오 API 응답 파싱) # 내부 사용 스키마 (카카오 API 응답 파싱)
+18
View File
@@ -0,0 +1,18 @@
from sqlalchemy import update
from sqlalchemy.ext.asyncio import AsyncSession
from app.user.models import User
async def consume_credit(user_uuid, session: AsyncSession) -> bool:
"""atomic UPDATE로 1크레딧 차감.
WHERE credits > 0 조건으로 음수 차감 방지 + PostgreSQL 행 락.
차감 성공 여부 반환.
"""
result = await session.execute(
update(User)
.where(User.user_uuid == user_uuid, User.credits > 0)
.values(credits=User.credits - 1)
)
return result.rowcount > 0
+4
View File
@@ -19,12 +19,16 @@ Note:
import os import os
import time import time
import re
from typing import Any, Optional, Type from typing import Any, Optional, Type
from sqlalchemy import select from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
def normalize_location(name: str) -> str:
return re.sub(r'(특별시|광역시|특별자치시|특별자치도|시|군|구|도)$', '', name)
def _generate_uuid7_string() -> str: def _generate_uuid7_string() -> str:
"""UUID7 문자열을 생성합니다. """UUID7 문자열을 생성합니다.
+18
View File
@@ -38,6 +38,8 @@ import httpx
from app.utils.logger import get_logger from app.utils.logger import get_logger
from app.utils.prompts.schemas.image import SpaceType,Subject,Camera,MotionRecommended,NarrativePhase from app.utils.prompts.schemas.image import SpaceType,Subject,Camera,MotionRecommended,NarrativePhase
from app.utils.common import normalize_location
from config import apikey_settings, creatomate_settings, recovery_settings from config import apikey_settings, creatomate_settings, recovery_settings
# 로거 설정 # 로거 설정
@@ -866,3 +868,19 @@ class CreatomateService:
logger.error("this template does not have same amount of keyword and subtitle.") logger.error("this template does not have same amount of keyword and subtitle.")
pitching_list = keyword_list + subtitle_list pitching_list = keyword_list + subtitle_list
return pitching_list return pitching_list
def make_thumbnail_modification(self, brand_name : str, region : str, brand_concept : str, category_definition : str, target_keywords : list[str]):
len_keywords = len(target_keywords) if len(target_keywords) < 3 else 3
hashtaged_target_keywords = [f"#{tk}" for tk in target_keywords[len_keywords]]
mod_dict = {
"thumb-hashtag-primary" : ' '.join(hashtaged_target_keywords),
"thumb-brand-wordmark" : brand_name,
"thumb-subheadline-selling_point" : f"{brand_name} · {normalize_location(region)}",
"thumb-headline-hook_claim-aspirational" : brand_concept,
"thumb-badge-category" : category_definition,
}
return mod_dict
+22 -2
View File
@@ -230,12 +230,21 @@ async def generate_video(
) )
project_id = project.id project_id = project.id
store_address = project.detail_region_info store_address = project.detail_region_info
# customer_name = project.store_name brand_name = project.store_name
region = project.region
marketing_result = await session.execute( marketing_result = await session.execute(
select(MarketingIntel).where(MarketingIntel.id == project.marketing_intelligence) select(MarketingIntel).where(MarketingIntel.id == project.marketing_intelligence)
) )
marketing_intelligence = marketing_result.scalar_one_or_none() marketing_intelligence : MarketingIntel = marketing_result.scalar_one_or_none()
category_definition= marketing_intelligence.intel_result["market_positioning"]["category_definition"]
target_keywords=marketing_intelligence.intel_result["target_keywords"]
brand_concept = ""
for sp in marketing_intelligence.intel_result["selling_points"]:
if "concept" in sp["english_category"].lower():
brand_concept = sp["description"]
# ===== 결과 처리: Lyric ===== # ===== 결과 처리: Lyric =====
lyric = lyric_result.scalar_one_or_none() lyric = lyric_result.scalar_one_or_none()
@@ -368,6 +377,17 @@ async def generate_video(
subtitle_modifications = marketing_intelligence.subtitle subtitle_modifications = marketing_intelligence.subtitle
modifications.update(subtitle_modifications) modifications.update(subtitle_modifications)
# revert thumbnail scene
# thumbnail_modifications = creatomate_service.make_thumbnail_modification(
# brand_name =brand_name,
# region = region,
# brand_concept = brand_concept,
# category_definition= category_definition,
# target_keywords=target_keywords)
# modifications.update(thumbnail_modifications)
# 6-3. elements 수정 # 6-3. elements 수정
new_elements = creatomate_service.modify_element( new_elements = creatomate_service.modify_element(
template["source"]["elements"], template["source"]["elements"],
+7
View File
@@ -13,6 +13,7 @@ from sqlalchemy import select
from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.exc import SQLAlchemyError
from app.database.session import BackgroundSessionLocal from app.database.session import BackgroundSessionLocal
from app.user.services.credit import consume_credit
from app.video.models import Video from app.video.models import Video
from app.utils.upload_blob_as_request import AzureBlobUploader from app.utils.upload_blob_as_request import AzureBlobUploader
from app.utils.logger import get_logger from app.utils.logger import get_logger
@@ -154,6 +155,12 @@ async def download_and_upload_video_to_blob(
# Video 테이블 업데이트 (creatomate_render_id로 특정 Video 식별) # Video 테이블 업데이트 (creatomate_render_id로 특정 Video 식별)
await _update_video_status(task_id, "completed", blob_url, creatomate_render_id) await _update_video_status(task_id, "completed", blob_url, creatomate_render_id)
# 영상 생성 완료 시 크레딧 1 차감 (credits > 0 조건으로 음수 방지)
async with BackgroundSessionLocal() as session:
await consume_credit(user_uuid, session)
await session.commit()
logger.info(f"[download_and_upload_video_to_blob] SUCCESS - task_id: {task_id}, creatomate_render_id: {creatomate_render_id}") logger.info(f"[download_and_upload_video_to_blob] SUCCESS - task_id: {task_id}, creatomate_render_id: {creatomate_render_id}")
except httpx.HTTPError as e: except httpx.HTTPError as e:
@@ -0,0 +1,5 @@
-- 2026-04-28: 사용자 크레딧 시스템 도입
-- 실행 방법: psql -U <user> -d <dbname> -f 2026_04_28_add_user_credits.sql
ALTER TABLE `user`
ADD COLUMN credits INT NOT NULL DEFAULT 3 COMMENT '영상 생성 크레딧';