feat(ssulbox): 썰박스 생성 파이프라인 통합 및 콘텐츠 목록 UNION

This commit is contained in:
skkim committed 2026-08-11 11:03:03 +09:00
1 parent 8096837b13
commit 666c3bf6d1
77 files changed
+15912 -349

No files matched your search

+47 -24
View File
@@ -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()
+68 -145
View File
@@ -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="영상 좋아요 토글",
+48 -6
View File
@@ -1,7 +1,18 @@
from datetime import datetime
from typing import TYPE_CHECKING, List, Optional
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String, UniqueConstraint, func
from sqlalchemy import (
BigInteger,
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
String,
UniqueConstraint,
func,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database.session import Base
@@ -136,8 +147,11 @@ class Video(Base):
back_populates="videos",
)
# comment/video_reaction 이 video_id 와 content_id 두 FK 를 갖게 되어
# 어느 쪽으로 조인할지 명시해야 한다(없으면 AmbiguousForeignKeysError).
comments: Mapped[List["Comment"]] = relationship(
"Comment",
foreign_keys="Comment.video_id",
back_populates="video",
cascade="all, delete-orphan",
lazy="noload",
@@ -145,6 +159,7 @@ class Video(Base):
reactions: Mapped[List["VideoReaction"]] = relationship(
"VideoReaction",
foreign_keys="VideoReaction.video_id",
back_populates="video",
cascade="all, delete-orphan",
lazy="noload",
@@ -170,14 +185,30 @@ class VideoReaction(Base):
영상 반응 테이블
사용자가 영상에 반응(현재는 좋아요)을 남기면 생성, 다시 누르면 삭제(토글).
(user_uuid, video_id) 유니크 제약으로 1인 1회 보장.
향후 reaction_type 컬럼 추가로 다양한 반응 종류 확장 가능.
**ADO2 영상과 썰박스 콘텐츠를 모두 담는다.** 대상은 `video_id` 또는 `content_id`
중 **정확히 하나**만 채워지며 DB `CHECK` 로 강제한다.
1인 1회 보장은 유니크 두 개로 나눠서 한다. MySQL 은 NULL 을 서로 다른 값으로
취급하므로, 썰박스 행(video_id IS NULL)이 아무리 많아도
`uq_video_reaction_user_video` 에 걸리지 않는다 — 각자 자기 유니크만 지킨다.
"""
__tablename__ = "video_reaction"
__table_args__ = (
CheckConstraint(
"(video_id IS NULL) <> (content_id IS NULL)",
name="ck_video_reaction_one_target",
),
UniqueConstraint("user_uuid", "video_id", name="uq_video_reaction_user_video"),
UniqueConstraint(
"user_uuid", "content_id", name="uq_video_reaction_user_content"
),
Index("idx_video_reaction_video_id", "video_id"),
# 카운트 집계가 content_id 로 묶으므로 선행 컬럼 인덱스가 필요하다
# (유니크는 user_uuid 가 앞이라 이 용도로 못 쓴다).
Index("idx_video_reaction_content_id", "content_id"),
Index("idx_video_reaction_user_uuid", "user_uuid"),
{
"mysql_engine": "InnoDB",
@@ -189,11 +220,19 @@ class VideoReaction(Base):
id: Mapped[int] = mapped_column(
Integer, primary_key=True, autoincrement=True, comment="고유 식별자"
)
video_id: Mapped[int] = mapped_column(
# 대상은 아래 둘 중 **정확히 하나**만 채워진다 (ck_video_reaction_one_target).
video_id: Mapped[Optional[int]] = mapped_column(
Integer,
ForeignKey("video.id", ondelete="CASCADE"),
nullable=False,
comment="연결된 Video의 id",
nullable=True,
comment="ADO2 영상 id (썰박스 반응이면 NULL)",
)
content_id: Mapped[Optional[int]] = mapped_column(
# ssul_content.id 는 BIGINT 다. INT 로 두면 FK 타입 불일치(errno 3780).
BigInteger,
ForeignKey("ssul_content.id", ondelete="CASCADE"),
nullable=True,
comment="썰박스 콘텐츠 id (ADO2 반응이면 NULL)",
)
user_uuid: Mapped[str] = mapped_column(
String(36),
@@ -208,5 +247,8 @@ class VideoReaction(Base):
comment="반응 일시",
)
video: Mapped["Video"] = relationship("Video", back_populates="reactions")
# 썰박스 반응이면 None 이다. 접근하는 쪽에서 반드시 방어할 것.
video: Mapped[Optional["Video"]] = relationship(
"Video", foreign_keys=[video_id], back_populates="reactions"
)
user: Mapped["User"] = relationship("User", back_populates="video_reactions")
+23 -4
View File
@@ -5,7 +5,7 @@ Video API Schemas
"""
from datetime import datetime
from typing import Any, Dict, Optional
from typing import Any, Dict, Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
@@ -152,10 +152,22 @@ class VideoListItem(BaseModel):
}
"""
video_id: int = Field(..., description="영상 고유 ID")
# ⚠️ `video_id` 는 type 안에서만 유일하다 — `video.id` 와 `ssul_content.id` 는
# 각각 1부터 시작하는 독립 시퀀스다. 식별·삭제·상세 열기 모두
# **`(type, video_id)` 쌍**으로 다뤄야 한다.
# 특히 `DELETE /archive/videos/{id}` 는 `Video.id` 로 지우므로,
# 썰박스 항목의 id 를 그대로 넘기면 **엉뚱한 ADO2 영상이 삭제된다.**
type: Literal["video", "ssul"] = Field(
default="video",
description="콘텐츠 종류 (video: ADO2 영상, ssul: 썰박스)",
)
video_id: int = Field(..., description="콘텐츠 고유 ID (type 안에서만 유일)")
store_name: Optional[str] = Field(None, description="업체명")
region: Optional[str] = Field(None, description="지역명")
task_id: str = Field(..., description="작업 고유 식별자")
task_id: str = Field(
default="",
description="작업 고유 식별자 (ADO2 전용. 썰박스는 개념이 없어 빈 문자열)",
)
result_movie_url: Optional[str] = Field(None, description="영상 결과 URL")
created_at: Optional[datetime] = Field(None, description="생성 일시")
like_count: int = Field(0, description="좋아요 수")
@@ -169,7 +181,14 @@ class VideoThumbnailItem(BaseModel):
GET /video/all 응답의 개별 영상 정보
"""
video_id: int = Field(..., description="영상 고유 ID (상세 페이지 라우팅 키)")
# ⚠️ `video_id` 는 종류 안에서만 유일하다. `video.id` 와 `ssul_content.id` 가
# **둘 다 1부터 시작**하므로 식별자는 반드시 `(type, video_id)` 쌍으로 다뤄야 한다.
# 한 곳이라도 id 만 쓰면 다른 종류의 콘텐츠가 열린다.
type: Literal["video", "ssul"] = Field(
default="video",
description="콘텐츠 종류 (video: ADO2 영상, ssul: 썰박스). video_id 와 쌍으로 식별한다",
)
video_id: int = Field(..., description="콘텐츠 고유 ID (type 안에서만 유일)")
store_name: str = Field(..., description="업체명")
result_movie_url: str = Field(..., description="영상 URL — 프론트에서 <video> 태그 첫 프레임을 썸네일로 사용")
created_at: datetime = Field(..., description="생성 일시")
+468
View File
@@ -0,0 +1,468 @@
# -*- coding: utf-8 -*-
"""ADO2 영상 + 썰박스 콘텐츠 통합 목록.
`GET /video/all`(전체 갤러리)과 `GET /archive/videos/`(내 콘텐츠)가 두 종류를
**하나의 정렬·페이징된 목록**으로 내려주기 위한 공용 쿼리다.
**왜 프론트에서 못 합치나**: 정렬·검색·지역 필터·페이지네이션이 전부 서버사이드다.
두 API 를 각각 호출해 이어붙이면 1페이지에 ADO2 12개 + 썰박스 12개가 각자 안에서만
정렬된 채 섞이고 `total`/`has_next` 도 어긋난다.
**왜 테이블을 안 합치나**: `video` 는 `project_id`/`lyric_id`/`song_id` 가 NOT NULL 이고
소유자·업장명이 `project` 에 있다. 썰박스를 넣으려면 그 4개를 nullable 로 열고
`Video` 를 참조하는 코드 72곳을 전부 감사해야 한다(2026-07-30 조사).
여기 사는 이유: 두 엔드포인트(`app/video`, `app/archive`)가 함께 쓰는데 엔드포인트
소유가 video 쪽이라 여기 뒀다. `app/archive` 는 이미 `app.video.models` 를 import 한다.
## 성능 설계 — 카운트를 UNION 안에 넣지 않는다
UNION 은 양쪽 브랜치를 **먼저 구체화**하므로, select 목록에 상관 서브쿼리를 두면
페이지 12건이 아니라 **매칭된 전체 행**에 대해 평가된다. 그래서
`created_at` 정렬(기본)에서는 카운트를 빼고, 페이지가 확정된 뒤 그 12건만 집계한다.
좋아요·댓글 수로 **정렬할 때만** 어쩔 수 없이 브랜치 안에서 계산한다.
"""
from dataclasses import dataclass
from datetime import datetime
from typing import Literal, Optional
from sqlalchemy import Select, func, literal, or_, select, union_all
from sqlalchemy.ext.asyncio import AsyncSession
from app.comment.models import Comment
from app.database.like_cache import (
CT_SSUL,
CT_VIDEO,
backfill_user_set,
bulk_is_user_liked,
get_like_counts,
mset_like_counts,
)
from app.home.models import Project
from app.ssulbox.models import SsulContent
from app.utils.address_parser import SIDO_CITIES, SIDO_SEARCH_ALIASES
from app.video.models import Video, VideoReaction
ContentType = Literal["video", "ssul"]
#: 정렬 가능한 키. 그 외 값은 created_at 으로 떨어진다.
SORT_CREATED = "created_at"
SORT_LIKE = "like_count"
SORT_COMMENT = "comment_count"
@dataclass(slots=True)
class UnifiedItem:
"""통합 목록의 한 항목.
`id` 는 종류마다 **독립적인 시퀀스**다(`video.id` 와 `ssul_content.id` 모두 1부터
시작한다). 따라서 식별자는 반드시 `(ctype, id)` 쌍으로 다뤄야 한다 —
한 곳이라도 id 만 쓰면 다른 콘텐츠가 열린다.
"""
ctype: ContentType
id: int
store_name: str
region: Optional[str]
movie_url: str
created_at: datetime
#: ADO2 전용. 썰박스는 task_id 개념이 없어 빈 문자열이다
#: (`ssul_content` 는 task/content 를 한 테이블로 합쳤고 크레딧 앵커는 id 다).
task_id: str = ""
like_count: int = 0
comment_count: int = 0
is_liked_by_me: bool = False
# ──────────────────────────────────────────────
# 상관 서브쿼리 (정렬용)
# ──────────────────────────────────────────────
def _video_like_subq():
return (
select(func.count(VideoReaction.id))
.where(VideoReaction.video_id == Video.id)
.correlate(Video)
.scalar_subquery()
)
def _video_comment_subq():
return (
select(func.count(Comment.id))
.where(Comment.video_id == Video.id, Comment.is_deleted.is_(False))
.correlate(Video)
.scalar_subquery()
)
def _ssul_like_subq():
# 좋아요·댓글은 castad 테이블에 합쳤다(2026-07-30). 썰박스 행은 video_id 대신
# content_id 가 채워져 있다 — 테이블은 같고 컬럼만 다르다.
return (
select(func.count(VideoReaction.id))
.where(VideoReaction.content_id == SsulContent.id)
.correlate(SsulContent)
.scalar_subquery()
)
def _ssul_comment_subq():
return (
select(func.count(Comment.id))
.where(
Comment.content_id == SsulContent.id,
Comment.is_deleted.is_(False),
)
.correlate(SsulContent)
.scalar_subquery()
)
# ──────────────────────────────────────────────
# 필터
# ──────────────────────────────────────────────
def _region_clause(region_col, detail_col, region: str):
"""castad `/video/all` 과 **동일한 규칙**으로 지역을 거른다.
시/도 이름이면 그 안의 시·군 목록으로 매칭하고, 동시에 상세 주소를 별칭으로
부분 일치 검색한다. 이 두 경로를 맞추지 않으면 같은 검색어에 ADO2 는 나오고
썰박스는 안 나오는 비대칭이 생긴다.
"""
cities = SIDO_CITIES.get(region)
if cities:
aliases = SIDO_SEARCH_ALIASES.get(region, [region])
return or_(
region_col.in_(cities),
*[detail_col.ilike(f"%{a}%") for a in aliases],
)
return or_(
region_col.ilike(f"%{region}%"),
detail_col.ilike(f"%{region}%"),
)
def _video_where(store_name: Optional[str], region: Optional[str]) -> list:
clauses = [
Video.status == "completed",
Video.is_deleted.is_(False),
Project.is_deleted.is_(False),
Video.result_movie_url.is_not(None),
]
if store_name:
clauses.append(Project.store_name.ilike(f"%{store_name}%"))
if region:
clauses.append(
_region_clause(Project.region, Project.detail_region_info, region)
)
return clauses
def _ssul_where(store_name: Optional[str], region: Optional[str]) -> list:
clauses = [
SsulContent.status == "done",
SsulContent.is_deleted.is_(False),
SsulContent.video_url.is_not(None),
]
if store_name:
clauses.append(SsulContent.store_name.ilike(f"%{store_name}%"))
if region:
clauses.append(
_region_clause(
SsulContent.region, SsulContent.detail_region_info, region
)
)
return clauses
# ──────────────────────────────────────────────
# 브랜치
# ──────────────────────────────────────────────
def _video_branch(where: list, sort_by: str) -> Select:
cols = [
literal(CT_VIDEO).label("ctype"),
Video.id.label("cid"),
Project.store_name.label("store_name"),
Project.region.label("region"),
Video.result_movie_url.label("movie_url"),
Video.created_at.label("created_at"),
Video.task_id.label("task_id"),
]
if sort_by == SORT_LIKE:
cols.append(_video_like_subq().label("sort_value"))
elif sort_by == SORT_COMMENT:
cols.append(_video_comment_subq().label("sort_value"))
return select(*cols).join(Project, Video.project_id == Project.id).where(*where)
def _ssul_branch(where: list, sort_by: str) -> Select:
cols = [
literal(CT_SSUL).label("ctype"),
SsulContent.id.label("cid"),
SsulContent.store_name.label("store_name"),
SsulContent.region.label("region"),
SsulContent.video_url.label("movie_url"),
SsulContent.created_at.label("created_at"),
# UNION 은 컬럼 수·순서가 양쪽 같아야 한다. 썰박스에는 task_id 가 없다.
literal("").label("task_id"),
]
if sort_by == SORT_LIKE:
cols.append(_ssul_like_subq().label("sort_value"))
elif sort_by == SORT_COMMENT:
cols.append(_ssul_comment_subq().label("sort_value"))
return select(*cols).where(*where)
# ──────────────────────────────────────────────
# 페이지 확정 후 집계
# ──────────────────────────────────────────────
def _reaction_target(ctype: str):
"""반응 테이블에서 이 종류가 쓰는 대상 컬럼.
`comment` / `video_reaction` 은 두 종류를 함께 담고 `video_id` 또는 `content_id`
중 하나만 채운다(CHECK 로 강제). 어느 컬럼을 볼지만 갈아끼우면 된다.
"""
return VideoReaction.video_id if ctype == CT_VIDEO else VideoReaction.content_id
def _comment_target(ctype: str):
return Comment.video_id if ctype == CT_VIDEO else Comment.content_id
async def _like_counts_for(
session: AsyncSession, ctype: str, ids: list[int]
) -> dict[int, int]:
"""Redis 우선, 미스는 DB 로 보정하고 캐시에 채운다.
castad 기존 목록 로직과 동일한 절차다. 종류별 키 접두를 쓰므로
`video.id` 와 `ssul_content.id` 가 겹쳐도 섞이지 않는다.
"""
if not ids:
return {}
counts = await get_like_counts(ids, ctype=ctype)
missing = [cid for cid, cnt in counts.items() if cnt is None]
if missing:
col = _reaction_target(ctype)
stmt = (
select(col, func.count(VideoReaction.id))
.where(col.in_(missing))
.group_by(col)
)
found = {cid: cnt for cid, cnt in (await session.execute(stmt)).all()}
await mset_like_counts(found, ctype=ctype)
for cid in missing:
counts[cid] = found.get(cid, 0)
return {cid: (cnt or 0) for cid, cnt in counts.items()}
async def _comment_counts_for(
session: AsyncSession, ctype: str, ids: list[int]
) -> dict[int, int]:
"""페이지에 포함된 항목만 집계한다(UNION 안에서 계산하지 않는 이유는 모듈 docstring 참조)."""
if not ids:
return {}
col = _comment_target(ctype)
stmt = (
select(col, func.count(Comment.id))
.where(col.in_(ids), Comment.is_deleted.is_(False))
.group_by(col)
)
found = {cid: cnt for cid, cnt in (await session.execute(stmt)).all()}
return {cid: found.get(cid, 0) for cid in ids}
async def _liked_map_for(
session: AsyncSession,
ctype: str,
ids: list[int],
user_uuid: str,
like_counts: dict[int, int],
) -> dict[int, bool]:
"""Redis user-set 기준. cold-start 인 항목만 DB 에서 backfill 한다."""
if not ids:
return {}
raw = await bulk_is_user_liked(ids, user_uuid, ctype=ctype)
# user-set 키가 없고(None) 카운트가 0 보다 큰 것만 채우면 된다 —
# 좋아요가 0 이면 backfill 해도 결과가 같다.
needs = [cid for cid, liked in raw.items() if liked is None and like_counts.get(cid, 0) > 0]
if needs:
col = _reaction_target(ctype)
stmt = select(col, VideoReaction.user_uuid).where(col.in_(needs))
by_content: dict[int, list[str]] = {cid: [] for cid in needs}
for cid, uuid in (await session.execute(stmt)).all():
by_content[cid].append(uuid)
for cid in needs:
await backfill_user_set(cid, by_content[cid], ctype=ctype)
raw.update(await bulk_is_user_liked(needs, user_uuid, ctype=ctype))
return {cid: bool(liked) for cid, liked in raw.items()}
async def enrich(
session: AsyncSession,
items: list[UnifiedItem],
user_uuid: Optional[str],
) -> list[UnifiedItem]:
"""페이지에 실린 항목에만 좋아요·댓글 수와 내 좋아요 여부를 채운다."""
for ctype in (CT_VIDEO, CT_SSUL):
ids = [it.id for it in items if it.ctype == ctype]
if not ids:
continue
likes = await _like_counts_for(session, ctype, ids)
comments = await _comment_counts_for(session, ctype, ids)
liked = (
await _liked_map_for(session, ctype, ids, user_uuid, likes)
if user_uuid
else {}
)
for it in items:
if it.ctype != ctype:
continue
it.like_count = likes.get(it.id, 0)
it.comment_count = comments.get(it.id, 0)
it.is_liked_by_me = liked.get(it.id, False)
return items
# ──────────────────────────────────────────────
# 공개 API
# ──────────────────────────────────────────────
async def fetch_gallery(
session: AsyncSession,
*,
offset: int,
limit: int,
sort_by: str = SORT_CREATED,
order: str = "desc",
store_name: Optional[str] = None,
region: Optional[str] = None,
user_uuid: Optional[str] = None,
include_ssul: bool = True,
) -> tuple[list[UnifiedItem], int]:
"""전체 갤러리(`/video/all`). (항목, 전체 개수) 반환."""
v_where = _video_where(store_name, region)
s_where = _ssul_where(store_name, region)
# 전체 개수는 브랜치별로 센다 — UNION 을 만들어 세는 것보다 싸다.
total = (
await session.execute(
select(func.count(Video.id))
.join(Project, Video.project_id == Project.id)
.where(*v_where)
)
).scalar() or 0
if include_ssul:
total += (
await session.execute(
select(func.count(SsulContent.id)).where(*s_where)
)
).scalar() or 0
branches = [_video_branch(v_where, sort_by)]
if include_ssul:
branches.append(_ssul_branch(s_where, sort_by))
u = union_all(*branches).subquery() if len(branches) > 1 else branches[0].subquery()
sort_col = (
u.c.sort_value if sort_by in (SORT_LIKE, SORT_COMMENT) else u.c.created_at
)
order_by = [sort_col.asc() if order == "asc" else sort_col.desc()]
# 정렬 키가 같을 때 페이지 경계에서 순서가 흔들리면 같은 항목이 두 번 보이거나
# 아예 빠진다. 안정적인 2차 키를 반드시 둔다.
if sort_by in (SORT_LIKE, SORT_COMMENT):
order_by.append(u.c.created_at.desc())
order_by.extend([u.c.ctype.asc(), u.c.cid.desc()])
rows = (
await session.execute(
select(u).order_by(*order_by).offset(offset).limit(limit)
)
).all()
items = _to_items(rows)
await enrich(session, items, user_uuid)
return items, total
def _to_items(rows) -> list[UnifiedItem]:
return [
UnifiedItem(
ctype=r.ctype,
id=r.cid,
store_name=r.store_name or "",
region=r.region,
movie_url=r.movie_url,
created_at=r.created_at,
task_id=r.task_id or "",
)
for r in rows
]
async def fetch_my_contents(
session: AsyncSession,
*,
user_uuid: str,
offset: int,
limit: int,
) -> tuple[list[UnifiedItem], int]:
"""내 콘텐츠(`/archive/videos/`). (항목, 전체 개수) 반환.
갤러리와 다른 점 둘:
- 소유자로 거른다 (ADO2 는 `project.user_uuid`, 썰박스는 `ssul_content.user_uuid`)
- ADO2 는 **task_id 당 최신 1건만** 남긴다(같은 작업으로 여러 영상이 생길 수
있다). 썰박스는 task_id 개념이 없어 중복 제거가 필요 없다.
⚠️ **프론트는 반드시 `ctype` 으로 분기해야 한다.** 이 목록에는 삭제 버튼이 붙는데
`DELETE /archive/videos/{id}` 는 `Video.id` 로 지운다. 썰박스 항목의 id 를 그대로
넘기면 **id 가 겹치는 ADO2 영상이 삭제된다**(둘 다 1부터 시작하는 독립 시퀀스).
"""
# ADO2: task_id 별 최신 영상만 (기존 동작 보존)
latest_ids = (
select(func.max(Video.id).label("latest_id"))
.join(Project, Video.project_id == Project.id)
.where(
Project.user_uuid == user_uuid,
Video.status == "completed",
Video.is_deleted.is_(False),
Project.is_deleted.is_(False),
)
.group_by(Video.task_id)
.subquery()
)
v_where = [Video.id.in_(select(latest_ids.c.latest_id))]
s_where = [
SsulContent.user_uuid == user_uuid,
SsulContent.status == "done",
SsulContent.is_deleted.is_(False),
SsulContent.video_url.is_not(None),
]
total = ((await session.execute(
select(func.count(Video.id)).where(*v_where)
)).scalar() or 0) + ((await session.execute(
select(func.count(SsulContent.id)).where(*s_where)
)).scalar() or 0)
u = union_all(
_video_branch(v_where, SORT_CREATED),
_ssul_branch(s_where, SORT_CREATED),
).subquery()
rows = (
await session.execute(
select(u)
.order_by(u.c.created_at.desc(), u.c.ctype.asc(), u.c.cid.desc())
.offset(offset)
.limit(limit)
)
).all()
items = _to_items(rows)
await enrich(session, items, user_uuid)
return items, total
+1 -8
View File
@@ -1,13 +1,7 @@
import random
from typing import List
from fastapi import Request, status
from fastapi.exceptions import HTTPException
from sqlalchemy import Connection, text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import select, func
from app.database.session import AsyncSessionLocal
from app.home.models import Image, ImageTag, Project
from app.home.models import Image, ImageTag
# from app.lyric.schemas.lyrics_schema import (
# AttributeData,
@@ -837,7 +831,6 @@ logger = get_logger("video")
# status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
# detail="서비스 처리 중 오류가 발생했습니다.",
# )
from sqlalchemy.dialects import mysql
async def get_image_tags_by_task_id(task_id: str) -> list[dict]:
# print("taskid", task_id)
async with AsyncSessionLocal() as session:
+60 -15
View File
@@ -4,7 +4,6 @@ Video Background Tasks
영상 생성 관련 백그라운드 태스크를 정의합니다.
"""
import traceback
from pathlib import Path
import aiofiles
@@ -12,8 +11,9 @@ import httpx
from sqlalchemy import select
from sqlalchemy.exc import SQLAlchemyError
from app.credit.services.credit_service import refund_credit_for_job
from app.database.session import BackgroundSessionLocal
from app.user.services.credit import consume_credit
from app.ssulbox.constants import JOB_TYPE_VIDEO as CREDIT_JOB_TYPE_VIDEO
from app.video.models import Video
from app.utils.upload_blob_as_request import AzureBlobUploader
from app.utils.logger import get_logger
@@ -24,6 +24,57 @@ logger = get_logger("video")
# HTTP 요청 설정
REQUEST_TIMEOUT = 300.0 # 초 (영상은 용량이 크므로 5분)
#: 영상 1편 생성에 차감/환불할 크레딧 (generate_video 의 VIDEO_CREDIT_COST 와 동일해야 함)
VIDEO_CREDIT_COST = 1
async def _fail_and_refund(
task_id: str | None,
creatomate_render_id: str | None = None,
user_uuid: str | None = None,
*,
reason: str,
) -> None:
"""영상 실패 처리 + 선차감한 크레딧 환불.
크레딧은 generate_video 에서 선차감되므로 실패 시 돌려줘야 한다.
refund_credit_for_job 은 (job_type, job_ref) 기준 멱등이라 실패 콜백이
여러 번 와도 환불은 한 번만 일어난다. 차감 기록이 없으면(정책 전환 이전에
시작된 in-flight 영상) 아무것도 하지 않는다.
Args:
task_id: 프로젝트 task_id (크레딧 멱등 키이기도 하다)
creatomate_render_id: Creatomate 렌더 ID
user_uuid: 환불 대상 사용자. None 이면 환불을 건너뛴다
reason: 원장에 남길 사유
"""
if task_id:
await _update_video_status(
task_id, "failed", creatomate_render_id=creatomate_render_id
)
if not task_id or not user_uuid:
return
try:
async with BackgroundSessionLocal() as session:
await refund_credit_for_job(
session=session,
user_uuid=user_uuid,
amount=VIDEO_CREDIT_COST,
job_type=CREDIT_JOB_TYPE_VIDEO,
job_ref=task_id,
reason=reason,
)
await session.commit()
except Exception as e:
# 환불 실패로 실패 처리 자체가 막히면 안 된다. 로그를 남기고 넘어간다.
logger.error(
f"[_fail_and_refund] REFUND FAILED - task_id: {task_id}, "
f"user_uuid: {user_uuid}, error: {e}",
exc_info=True,
)
async def _update_video_status(
task_id: str,
@@ -156,24 +207,21 @@ async def download_and_upload_video_to_blob(
# Video 테이블 업데이트 (creatomate_render_id로 특정 Video 식별)
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()
# 크레딧은 generate_video 에서 이미 선차감했다. 여기서 차감하지 않는다.
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:
logger.error(f"[download_and_upload_video_to_blob] DOWNLOAD ERROR - task_id: {task_id}, error: {e}", exc_info=True)
await _update_video_status(task_id, "failed", creatomate_render_id=creatomate_render_id)
await _fail_and_refund(task_id, creatomate_render_id, user_uuid, reason="영상 다운로드 실패")
except SQLAlchemyError as e:
logger.error(f"[download_and_upload_video_to_blob] DB ERROR - task_id: {task_id}, error: {e}", exc_info=True)
await _update_video_status(task_id, "failed", creatomate_render_id=creatomate_render_id)
await _fail_and_refund(task_id, creatomate_render_id, user_uuid, reason="영상 저장 실패")
except Exception as e:
logger.error(f"[download_and_upload_video_to_blob] EXCEPTION - task_id: {task_id}, error: {e}", exc_info=True)
await _update_video_status(task_id, "failed", creatomate_render_id=creatomate_render_id)
await _fail_and_refund(task_id, creatomate_render_id, user_uuid, reason="영상 처리 실패")
finally:
# 임시 파일 삭제
@@ -270,18 +318,15 @@ async def download_and_upload_video_by_creatomate_render_id(
except httpx.HTTPError as e:
logger.error(f"[download_and_upload_video_by_creatomate_render_id] DOWNLOAD ERROR - creatomate_render_id: {creatomate_render_id}, error: {e}", exc_info=True)
if task_id:
await _update_video_status(task_id, "failed", creatomate_render_id=creatomate_render_id)
await _fail_and_refund(task_id, creatomate_render_id, user_uuid, reason="영상 다운로드 실패")
except SQLAlchemyError as e:
logger.error(f"[download_and_upload_video_by_creatomate_render_id] DB ERROR - creatomate_render_id: {creatomate_render_id}, error: {e}", exc_info=True)
if task_id:
await _update_video_status(task_id, "failed", creatomate_render_id=creatomate_render_id)
await _fail_and_refund(task_id, creatomate_render_id, user_uuid, reason="영상 저장 실패")
except Exception as e:
logger.error(f"[download_and_upload_video_by_creatomate_render_id] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}", exc_info=True)
if task_id:
await _update_video_status(task_id, "failed", creatomate_render_id=creatomate_render_id)
await _fail_and_refund(task_id, creatomate_render_id, user_uuid, reason="영상 처리 실패")
finally:
# 임시 파일 삭제