feat(ssulbox): 썰박스 생성 파이프라인 통합 및 콘텐츠 목록 UNION
This commit is contained in:
1 parent
8096837b13
commit
666c3bf6d1
77 files changed
+15912
-349
No files matched your search
@@ -12,11 +12,15 @@ from sqlalchemy import delete, insert, tuple_
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.like_cache import (
|
||||
CT_SSUL,
|
||||
CT_VIDEO,
|
||||
commit_dirty_processing,
|
||||
drain_dirty,
|
||||
is_user_liked,
|
||||
)
|
||||
from app.database.session import get_session
|
||||
# 썰박스 좋아요도 같은 Redis write-behind 큐 + **같은 테이블**(video_reaction)을
|
||||
# 쓰므로 여기서 함께 플러시한다. 큐가 하나라 스케줄러를 늘릴 필요가 없다.
|
||||
from app.video.models import VideoReaction
|
||||
from config import internal_settings
|
||||
|
||||
@@ -48,49 +52,68 @@ async def flush_reactions(
|
||||
detail="Invalid internal secret",
|
||||
)
|
||||
|
||||
pairs = await drain_dirty()
|
||||
if not pairs:
|
||||
entries = await drain_dirty()
|
||||
if not entries:
|
||||
logger.info("[REACTION_FLUSH] dirty 항목 없음, 종료")
|
||||
return {"flushed": 0, "adds": 0, "dels": 0}
|
||||
|
||||
logger.info(f"[REACTION_FLUSH] START - dirty 항목 {len(pairs)}건")
|
||||
logger.info(f"[REACTION_FLUSH] START - dirty 항목 {len(entries)}건")
|
||||
|
||||
# 두 종류가 **같은 테이블**(video_reaction)에 들어간다. 대상 컬럼만 다르다.
|
||||
# ADO2 는 video_id, 썰박스는 content_id 를 채운다(나머지는 NULL, CHECK 로 강제).
|
||||
id_col_of = {CT_VIDEO: "video_id", CT_SSUL: "content_id"}
|
||||
adds: list[dict] = []
|
||||
dels: list[tuple[int, str]] = []
|
||||
# (컬럼명, 대상 id, user_uuid) — 삭제는 컬럼이 달라 종류별로 묶어야 한다
|
||||
dels: dict[str, list[tuple[int, str]]] = {"video_id": [], "content_id": []}
|
||||
|
||||
# Redis 현재 상태 기준으로 add / delete 분류
|
||||
for video_id, user_uuid in pairs:
|
||||
liked = await is_user_liked(video_id, user_uuid)
|
||||
for ctype, content_id, user_uuid in entries:
|
||||
id_col = id_col_of.get(ctype)
|
||||
if id_col is None:
|
||||
# 알 수 없는 종류 — 건너뛴다(파서가 걸러주지만 방어)
|
||||
logger.warning(f"[REACTION_FLUSH] 알 수 없는 종류 무시 - ctype: {ctype}")
|
||||
continue
|
||||
liked = await is_user_liked(content_id, user_uuid, ctype=ctype)
|
||||
if liked:
|
||||
adds.append({"video_id": video_id, "user_uuid": user_uuid})
|
||||
adds.append({id_col: content_id, "user_uuid": user_uuid})
|
||||
else:
|
||||
dels.append((video_id, user_uuid))
|
||||
dels[id_col].append((content_id, user_uuid))
|
||||
|
||||
total_adds = len(adds)
|
||||
total_dels = sum(len(v) for v in dels.values())
|
||||
|
||||
try:
|
||||
# Bulk INSERT IGNORE — UniqueConstraint 보장으로 멱등 처리
|
||||
if adds:
|
||||
await session.execute(
|
||||
insert(VideoReaction).prefix_with("IGNORE").values(adds)
|
||||
)
|
||||
# 쓰기를 **하나의 트랜잭션**으로 묶는다.
|
||||
# 부분 반영이 나면 Redis processing SET 이 남아 다음 회차에 재시도되는데,
|
||||
# INSERT IGNORE + UNIQUE 로 멱등이라 중복 반영은 안전하다.
|
||||
#
|
||||
# ⚠️ adds 는 종류별로 키가 달라(video_id vs content_id) 한 번의
|
||||
# `values(adds)` 로 묶으면 안 된다 — SQLAlchEmy 가 첫 dict 의 키로
|
||||
# 컬럼 목록을 정하므로 다른 종류의 값이 누락된다. 종류별로 나눠 실행한다.
|
||||
for id_col in ("video_id", "content_id"):
|
||||
rows = [a for a in adds if id_col in a]
|
||||
if rows:
|
||||
await session.execute(
|
||||
insert(VideoReaction).prefix_with("IGNORE").values(rows)
|
||||
)
|
||||
|
||||
# Bulk DELETE
|
||||
if dels:
|
||||
await session.execute(
|
||||
delete(VideoReaction).where(
|
||||
tuple_(
|
||||
VideoReaction.video_id,
|
||||
VideoReaction.user_uuid,
|
||||
).in_(dels)
|
||||
if dels[id_col]:
|
||||
await session.execute(
|
||||
delete(VideoReaction).where(
|
||||
tuple_(
|
||||
getattr(VideoReaction, id_col),
|
||||
VideoReaction.user_uuid,
|
||||
).in_(dels[id_col])
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
await session.commit()
|
||||
await commit_dirty_processing()
|
||||
|
||||
logger.info(
|
||||
f"[REACTION_FLUSH] SUCCESS - adds: {len(adds)}, dels: {len(dels)}"
|
||||
f"[REACTION_FLUSH] SUCCESS - adds: {total_adds}, dels: {total_dels}"
|
||||
)
|
||||
return {"flushed": len(pairs), "adds": len(adds), "dels": len(dels)}
|
||||
return {"flushed": len(entries), "adds": total_adds, "dels": total_dels}
|
||||
|
||||
except Exception as e:
|
||||
await session.rollback()
|
||||
|
||||
@@ -13,12 +13,10 @@ Video API Router
|
||||
app.include_router(router)
|
||||
"""
|
||||
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
|
||||
from sqlalchemy import func, or_, select
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.session import get_session
|
||||
@@ -28,26 +26,26 @@ from app.user.models import User
|
||||
from app.utils.pagination import PaginatedResponse
|
||||
from app.home.models import Image, Project, MarketingIntel
|
||||
from app.home.api.routers.v1.home import _extract_region_from_address
|
||||
from app.utils.address_parser import SIDO_CITIES, SIDO_SEARCH_ALIASES
|
||||
from app.lyric.models import Lyric
|
||||
from app.song.models import Song, SongTimestamp
|
||||
from app.utils.creatomate import CreatomateService, LANGUAGE_FONT_MAP
|
||||
|
||||
from app.comment.models import Comment
|
||||
from app.database.like_cache import (
|
||||
backfill_user_set,
|
||||
bulk_is_user_liked,
|
||||
get_like_count,
|
||||
get_like_counts,
|
||||
is_user_liked,
|
||||
is_user_set_exists,
|
||||
mark_dirty,
|
||||
mset_like_counts,
|
||||
set_like_count,
|
||||
toggle_like_atomic,
|
||||
)
|
||||
from app.credit.exceptions import InsufficientCreditError
|
||||
from app.credit.services.credit_service import deduct_credit_for_job
|
||||
from app.ssulbox.constants import JOB_TYPE_VIDEO as CREDIT_JOB_TYPE_VIDEO
|
||||
from app.utils.logger import get_logger
|
||||
from app.video.models import Video, VideoReaction
|
||||
from app.video.services import unified_list
|
||||
|
||||
from app.video.schemas.video_schema import (
|
||||
DownloadVideoResponse,
|
||||
GenerateVideoResponse,
|
||||
@@ -64,6 +62,9 @@ from config import creatomate_settings
|
||||
|
||||
logger = get_logger("video")
|
||||
|
||||
#: 영상 1편 생성에 차감할 크레딧 (video_task.py 의 VIDEO_CREDIT_COST 와 동일해야 함)
|
||||
VIDEO_CREDIT_COST = 1
|
||||
|
||||
router = APIRouter(prefix="/video", tags=["Video"])
|
||||
|
||||
|
||||
@@ -113,12 +114,19 @@ curl -X GET "http://localhost:8000/video/generate/0694b716-dbff-7219-8000-d08cb5
|
||||
- Song의 song_result_url과 song_prompt가 있어야 영상 생성이 가능합니다.
|
||||
- creatomate_render_id를 사용하여 /status/{creatomate_render_id} 엔드포인트에서 생성 상태를 확인할 수 있습니다.
|
||||
- Video 테이블에 데이터가 저장되며, project_id, lyric_id, song_id가 자동으로 연결됩니다.
|
||||
|
||||
## 크레딧
|
||||
- **요청 시점에 크레딧 1이 선차감됩니다.** (완료 시점 차감에서 변경)
|
||||
- 생성이 실패하면 자동으로 환불됩니다.
|
||||
- 잔액이 부족하면 402를 반환하며, Video 행도 생성되지 않습니다.
|
||||
- 같은 task_id 로 재요청해도 중복 차감되지 않습니다.
|
||||
""",
|
||||
response_model=GenerateVideoResponse,
|
||||
responses={
|
||||
200: {"description": "영상 생성 요청 성공"},
|
||||
400: {"description": "Song의 음악 URL, 가사(song_prompt) 또는 이미지가 없음"},
|
||||
401: {"description": "인증 실패 (토큰 없음/만료)"},
|
||||
402: {"description": "크레딧 부족 (충전 필요)"},
|
||||
404: {"description": "Project, Lyric, Song 또는 Image를 찾을 수 없음"},
|
||||
500: {"description": "영상 생성 요청 실패"},
|
||||
},
|
||||
@@ -313,7 +321,11 @@ async def generate_video(
|
||||
f"timestamps: {len(song_timestamp_list)}"
|
||||
)
|
||||
|
||||
# ===== Video 테이블에 초기 데이터 저장 및 커밋 =====
|
||||
# ===== Video 테이블에 초기 데이터 저장 + 크레딧 선차감 (단일 트랜잭션) =====
|
||||
# 렌더 완료 후가 아니라 "시작 시점"에 차감한다. 사후차감이던 시절에는
|
||||
# 차감 전에 동시 요청이 들어오면 크레딧 1개로 영상 여러 개를 만들 수 있었다.
|
||||
# Video insert 와 차감을 한 트랜잭션으로 묶어 한 번만 커밋해야
|
||||
# "영상 행은 생겼는데 차감은 실패" 같은 반쪽 상태가 생기지 않는다.
|
||||
video = Video(
|
||||
project_id=project_id,
|
||||
lyric_id=lyric_id,
|
||||
@@ -323,6 +335,21 @@ async def generate_video(
|
||||
status="processing",
|
||||
)
|
||||
session.add(video)
|
||||
await session.flush() # video.id 확보 (커밋은 차감 후 한 번만)
|
||||
|
||||
# job_ref 로 task_id 를 쓴다 — ADO2 에는 영상 재생성 버튼이 없어
|
||||
# task_id 1건 = 생성 1건이기 때문이다.
|
||||
# 재생성 UI 를 추가한다면 이 키를 f"{task_id}:{video.id}" 로 바꿔야
|
||||
# 두 번째 생성이 공짜가 되지 않는다.
|
||||
await deduct_credit_for_job(
|
||||
session=session,
|
||||
user_uuid=current_user.user_uuid,
|
||||
amount=VIDEO_CREDIT_COST,
|
||||
job_type=CREDIT_JOB_TYPE_VIDEO,
|
||||
job_ref=task_id,
|
||||
reason="영상 생성",
|
||||
)
|
||||
|
||||
await session.commit()
|
||||
video_id = video.id
|
||||
stage1_time = time.perf_counter()
|
||||
@@ -334,6 +361,14 @@ async def generate_video(
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except InsufficientCreditError:
|
||||
# 크레딧 부족은 "요청 실패"가 아니라 402 로 올려야 프론트가 충전 화면으로 유도한다.
|
||||
# 아래 except Exception 이 삼켜 200(success=False)으로 내리면 안 되므로 먼저 잡는다.
|
||||
logger.info(
|
||||
f"[generate_video] INSUFFICIENT CREDIT - task_id: {task_id}, "
|
||||
f"user_uuid: {current_user.user_uuid}"
|
||||
)
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"[generate_video] DB EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
return GenerateVideoResponse(
|
||||
@@ -850,7 +885,7 @@ async def get_all_videos(
|
||||
store_name: str | None = Query(default=None, description="업체명 검색 (부분 일치)"),
|
||||
region: str | None = Query(default=None, description="지역명 검색 (부분 일치)"),
|
||||
) -> PaginatedResponse[VideoThumbnailItem]:
|
||||
"""전체 사용자의 완료된 영상 갤러리를 반환합니다."""
|
||||
"""전체 사용자의 완료된 콘텐츠(ADO2 영상 + 썰박스)를 반환합니다."""
|
||||
logger.info(
|
||||
f"[get_all_videos] START - page: {pagination.page}, page_size: {pagination.page_size}, "
|
||||
f"sort_by: {sort_by}, order: {order}, store_name: {store_name}, region: {region}"
|
||||
@@ -859,144 +894,31 @@ async def get_all_videos(
|
||||
try:
|
||||
offset = (pagination.page - 1) * pagination.page_size
|
||||
|
||||
where_clauses = [
|
||||
Video.status == "completed",
|
||||
Video.is_deleted == False, # noqa: E712
|
||||
Project.is_deleted == False, # noqa: E712
|
||||
Video.result_movie_url.is_not(None),
|
||||
]
|
||||
if store_name:
|
||||
where_clauses.append(Project.store_name.ilike(f"%{store_name}%"))
|
||||
if region:
|
||||
cities = SIDO_CITIES.get(region)
|
||||
if cities:
|
||||
aliases = SIDO_SEARCH_ALIASES.get(region, [region])
|
||||
where_clauses.append(
|
||||
or_(
|
||||
Project.region.in_(cities),
|
||||
*[Project.detail_region_info.ilike(f"%{a}%") for a in aliases],
|
||||
)
|
||||
)
|
||||
else:
|
||||
where_clauses.append(
|
||||
or_(
|
||||
Project.region.ilike(f"%{region}%"),
|
||||
Project.detail_region_info.ilike(f"%{region}%"),
|
||||
)
|
||||
)
|
||||
|
||||
count_q = (
|
||||
select(func.count(Video.id))
|
||||
.join(Project, Video.project_id == Project.id)
|
||||
.where(*where_clauses)
|
||||
items, total = await unified_list.fetch_gallery(
|
||||
session,
|
||||
offset=offset,
|
||||
limit=pagination.page_size,
|
||||
sort_by=sort_by,
|
||||
order=order,
|
||||
store_name=store_name,
|
||||
region=region,
|
||||
user_uuid=current_user.user_uuid if current_user else None,
|
||||
)
|
||||
total = (await session.execute(count_q)).scalar() or 0
|
||||
|
||||
comment_count_subq = (
|
||||
select(func.count(Comment.id))
|
||||
.where(
|
||||
Comment.video_id == Video.id,
|
||||
Comment.is_deleted == False, # noqa: E712
|
||||
)
|
||||
.correlate(Video)
|
||||
.scalar_subquery()
|
||||
)
|
||||
|
||||
# like_count 정렬은 Redis 대신 서브쿼리로 처리 (ORDER BY에만 사용)
|
||||
like_count_subq_for_sort = (
|
||||
select(func.count(VideoReaction.id))
|
||||
.where(VideoReaction.video_id == Video.id)
|
||||
.correlate(Video)
|
||||
.scalar_subquery()
|
||||
)
|
||||
sort_col_map = {
|
||||
"like_count": like_count_subq_for_sort,
|
||||
"comment_count": comment_count_subq,
|
||||
"created_at": Video.created_at,
|
||||
}
|
||||
sort_col = sort_col_map.get(sort_by, Video.created_at)
|
||||
order_clause = sort_col.asc() if order == "asc" else sort_col.desc()
|
||||
|
||||
list_q = (
|
||||
select(
|
||||
Video,
|
||||
Project,
|
||||
comment_count_subq.label("comment_count"),
|
||||
)
|
||||
.join(Project, Video.project_id == Project.id)
|
||||
.where(*where_clauses)
|
||||
.order_by(order_clause)
|
||||
.offset(offset)
|
||||
.limit(pagination.page_size)
|
||||
)
|
||||
rows = (await session.execute(list_q)).all()
|
||||
|
||||
video_ids = [v.id for v, p, _ in rows]
|
||||
|
||||
# Redis mget으로 like_count 일괄 조회
|
||||
like_count_map = await get_like_counts(video_ids)
|
||||
|
||||
# 카운트 캐시 미스 보정
|
||||
missing_ids = [vid for vid, cnt in like_count_map.items() if cnt is None]
|
||||
if missing_ids:
|
||||
db_counts = (await session.execute(
|
||||
select(VideoReaction.video_id, func.count(VideoReaction.id))
|
||||
.where(VideoReaction.video_id.in_(missing_ids))
|
||||
.group_by(VideoReaction.video_id)
|
||||
)).all()
|
||||
db_found_ids = set()
|
||||
batch = {}
|
||||
for vid, cnt in db_counts:
|
||||
batch[vid] = cnt
|
||||
like_count_map[vid] = cnt
|
||||
db_found_ids.add(vid)
|
||||
await mset_like_counts(batch)
|
||||
for vid in missing_ids:
|
||||
if vid not in db_found_ids:
|
||||
like_count_map[vid] = 0
|
||||
|
||||
# is_liked_by_me: Redis user-set 기준, cold-start 시 DB backfill
|
||||
liked_map: dict[int, bool] = {}
|
||||
if current_user:
|
||||
raw_liked = await bulk_is_user_liked(video_ids, current_user.user_uuid)
|
||||
|
||||
# user-set이 없는(None) 영상 중 count > 0인 것만 backfill 필요
|
||||
needs_backfill = [
|
||||
vid for vid, liked in raw_liked.items()
|
||||
if liked is None and like_count_map.get(vid, 0) > 0
|
||||
]
|
||||
if needs_backfill:
|
||||
reaction_rows = (await session.execute(
|
||||
select(VideoReaction.video_id, VideoReaction.user_uuid)
|
||||
.where(VideoReaction.video_id.in_(needs_backfill))
|
||||
)).all()
|
||||
user_map: dict[int, list[str]] = defaultdict(list)
|
||||
for vid, uuid in reaction_rows:
|
||||
user_map[vid].append(uuid)
|
||||
for vid in needs_backfill:
|
||||
await backfill_user_set(vid, user_map.get(vid, []))
|
||||
|
||||
# backfill 후 재조회
|
||||
updated = await bulk_is_user_liked(needs_backfill, current_user.user_uuid)
|
||||
raw_liked.update(updated)
|
||||
|
||||
liked_map = {vid: bool(liked) for vid, liked in raw_liked.items()}
|
||||
|
||||
items = [
|
||||
VideoThumbnailItem(
|
||||
video_id=v.id,
|
||||
store_name=p.store_name,
|
||||
result_movie_url=v.result_movie_url,
|
||||
created_at=v.created_at,
|
||||
like_count=like_count_map.get(v.id) or 0,
|
||||
is_liked_by_me=liked_map.get(v.id, False),
|
||||
comment_count=comment_count or 0,
|
||||
)
|
||||
for v, p, comment_count in rows
|
||||
]
|
||||
|
||||
response = PaginatedResponse.create(
|
||||
items=items,
|
||||
items=[
|
||||
VideoThumbnailItem(
|
||||
type=it.ctype,
|
||||
video_id=it.id,
|
||||
store_name=it.store_name,
|
||||
result_movie_url=it.movie_url,
|
||||
created_at=it.created_at,
|
||||
like_count=it.like_count,
|
||||
is_liked_by_me=it.is_liked_by_me,
|
||||
comment_count=it.comment_count,
|
||||
)
|
||||
for it in items
|
||||
],
|
||||
total=total,
|
||||
page=pagination.page,
|
||||
page_size=pagination.page_size,
|
||||
@@ -1009,6 +931,7 @@ async def get_all_videos(
|
||||
raise HTTPException(status_code=500, detail=f"갤러리 조회에 실패했습니다: {str(e)}")
|
||||
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{video_id}/like",
|
||||
summary="영상 좋아요 토글",
|
||||
|
||||
Reference in new issue
Block a user