backend api 추가

This commit is contained in:
jaehwang committed 2026-09-08 13:00:23 +09:00
1 parent 2d4201ce9e
commit f008ed4010
15 files changed
+1501 -5

No files matched your search

+163
View File
@@ -0,0 +1,163 @@
"""/api/f1 — 포스터 한 장 → 8초 숏폼"""
import io
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
from PIL import Image
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from models.pipeline_state import PosterAliveState
from pipelines import poster_alive
from pipelines.artifact import load_image
from pipelines.runner import AWAITING_REVIEW, FAILED, QUEUED, RUNNING, reset_from
from routers.view import motion_elements, poster_alive_view
from services.motion import plan_motion
from tables.task import PosterAliveTask
from utils.database import get_session
router = APIRouter(prefix="/api/f1", tags=["f1"])
ACCEPTED_TYPES = {"image/jpeg", "image/png", "image/webp", "image/gif"}
MAX_UPLOAD_BYTES = 30 * 1024 * 1024
NARRATION_COUNT = 3
NARRATION_MAX_CHARS = 40
class NarrationBody(BaseModel):
narration: list[str]
class MetadataBody(BaseModel):
event_name: str
date_text: str = ""
place: str
keywords: list[str] | None = None
class ApproveBody(BaseModel):
# 검수 화면에서 사람이 모션을 더하거나 뺀 결과. None이면 그대로 간다
motions: list[str] | None = None
async def find_task(session: AsyncSession, task_id: str) -> PosterAliveTask:
task = await session.get(PosterAliveTask, task_id)
if task is None:
raise HTTPException(404, "잡을 찾을 수 없습니다")
return task
async def rewrite_motion_plan(task: PosterAliveTask, motions: list[str]) -> None:
"""고른 모션으로 프롬프트를 다시 쓴다. 바뀐 게 없으면 건드리지 않는다"""
chosen = [key.strip() for key in motions if key.strip()]
if sorted(chosen) == sorted(motion_elements(task.motion_plan) or []):
return
plan = await plan_motion(await load_image(task.poster_url), force_motions=chosen)
task.motion_plan = plan.model_dump()
@router.post("/jobs")
async def create(poster: UploadFile = File(...), name: str = Form(""),
auto: bool = Form(False),
session: AsyncSession = Depends(get_session)):
if poster.content_type not in ACCEPTED_TYPES:
raise HTTPException(415, f"지원 형식: JPG/PNG/WEBP/GIF (받은 것: {poster.content_type})")
raw = await poster.read()
if len(raw) > MAX_UPLOAD_BYTES:
raise HTTPException(413, "30MB 이하만 올릴 수 있습니다")
try:
Image.open(io.BytesIO(raw)).verify()
except Exception:
raise HTTPException(422, "이미지 파일을 열 수 없습니다")
task = await poster_alive.create_task(session, name.strip() or "이름 없는 행사", raw,
skip_review=auto)
return {"id": task.id, "ahead": 0}
@router.get("/jobs")
async def list_jobs(session: AsyncSession = Depends(get_session)):
found = await session.scalars(
select(PosterAliveTask).order_by(PosterAliveTask.created_at.desc()))
return [poster_alive_view(task) for task in found]
@router.get("/jobs/{task_id}")
async def get_job(task_id: str, session: AsyncSession = Depends(get_session)):
return poster_alive_view(await find_task(session, task_id))
@router.put("/jobs/{task_id}/narration")
async def edit_narration(task_id: str, body: NarrationBody,
session: AsyncSession = Depends(get_session)):
task = await find_task(session, task_id)
if task.status != AWAITING_REVIEW:
raise HTTPException(409, "나레이션은 검수 대기 상태에서만 고칠 수 있습니다")
lines = [line.strip() for line in body.narration]
if len(lines) != NARRATION_COUNT or any(
not line or len(line) > NARRATION_MAX_CHARS for line in lines):
raise HTTPException(422, f"나레이션은 {NARRATION_MAX_CHARS}자 이내 "
f"{NARRATION_COUNT}문장이어야 합니다")
task.narration_lines = lines
await session.commit()
return poster_alive_view(task)
@router.put("/jobs/{task_id}/metadata")
async def edit_metadata(task_id: str, body: MetadataBody,
session: AsyncSession = Depends(get_session)):
"""VLM이 연도나 지명을 잘못 읽어도 아카이브에는 사실이 남게 한다"""
task = await find_task(session, task_id)
if task.status != AWAITING_REVIEW:
raise HTTPException(409, "메타태그는 검수 대기 상태에서만 고칠 수 있습니다")
if not body.event_name.strip() or not body.place.strip():
raise HTTPException(422, "행사명과 장소는 비울 수 없습니다")
metadata = dict(task.poster_metadata or {})
metadata["event_name"] = body.event_name.strip()
metadata["date_text"] = body.date_text.strip()
metadata["place"] = body.place.strip()
if body.keywords is not None:
metadata["keywords"] = [word.strip() for word in body.keywords if word.strip()]
task.poster_metadata = metadata
await session.commit()
return poster_alive_view(task)
@router.post("/jobs/{task_id}/approve")
async def approve(task_id: str, body: ApproveBody | None = None,
session: AsyncSession = Depends(get_session)):
task = await find_task(session, task_id)
if task.status != AWAITING_REVIEW:
raise HTTPException(409, f"검수 대기 상태가 아닙니다: {task.status}")
if body and body.motions is not None:
await rewrite_motion_plan(task, body.motions)
task.status = QUEUED
await session.commit()
return {"id": task.id, "ahead": 0}
@router.post("/jobs/{task_id}/retry")
async def retry(task_id: str, body: ApproveBody | None = None,
session: AsyncSession = Depends(get_session)):
task = await find_task(session, task_id)
if task.status != FAILED:
raise HTTPException(409, f"실패 상태가 아닙니다: {task.status}")
if body and body.motions is not None:
await rewrite_motion_plan(task, body.motions)
reset_from(task, task.error_stage or PosterAliveState.DETECT.value)
task.status = QUEUED
task.error_stage = None
task.error_detail = None
await session.commit()
return {"id": task.id, "ahead": 0}
@router.delete("/jobs/{task_id}")
async def delete(task_id: str, session: AsyncSession = Depends(get_session)):
task = await find_task(session, task_id)
if task.status == RUNNING:
raise HTTPException(409, "진행 중인 작업은 삭제할 수 없습니다. 끝난 뒤 지워주세요")
await session.delete(task)
await session.commit()
return {"id": task_id, "removed": True}
+159
View File
@@ -0,0 +1,159 @@
"""/api/playreel — 공연 상품페이지 → 30초 롱컷"""
import re
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from models.pipeline_state import PlayreelState
from pipelines import playreel
from pipelines.gate import (REVERSIBLE_GATES, PlayreelGate, apply_playreel_edits,
previous_gate, resume_stage)
from pipelines.runner import AWAITING_REVIEW, FAILED, QUEUED, RUNNING, reset_from
from routers.view import playreel_view
from tables.task import PlayreelTask
from utils.database import get_session
router = APIRouter(prefix="/api/playreel", tags=["playreel"])
# 프론트 parseGoodsId와 같은 규칙. 프론트 검사는 입력 도중의 안내이고 판정은 여기서 한다
GOODS_ID_PATTERNS = (
r"tickets\.interpark\.com/goods/(\d{5,})",
r"nol\.interpark\.com/[^?]*?(\d{8,})",
r"[?&]goodsCode=(\d{5,})",
r"^(\d{8,})$",
)
SLUG_PATTERN = re.compile(r"[a-z0-9_]+")
def parse_goods_id(url: str) -> str | None:
for pattern in GOODS_ID_PATTERNS:
found = re.search(pattern, (url or "").strip(), re.I)
if found:
return found.group(1)
return None
class CreateBody(BaseModel):
url: str
# 하이브리드 합성이 작품별 좌표를 요구한다. 검증된 작품을 다시 돌릴 때 지정한다
slug: str | None = None
class ApproveBody(BaseModel):
gate: str | None = None
edits: dict | None = None
async def find_task(session: AsyncSession, task_id: str) -> PlayreelTask:
task = await session.get(PlayreelTask, task_id)
if task is None:
raise HTTPException(404, "playreel 잡을 찾을 수 없습니다")
return task
@router.post("/jobs")
async def create(body: CreateBody, session: AsyncSession = Depends(get_session)):
goods_id = parse_goods_id(body.url)
if not goods_id:
raise HTTPException(400, "지원하지 않는 주소입니다. 공연 상품페이지 주소를 넣어 주세요.")
slug = (body.slug or "").strip() or f"g{goods_id}"
if not SLUG_PATTERN.fullmatch(slug):
raise HTTPException(400, "slug는 영문 소문자·숫자·밑줄만 씁니다")
task = await playreel.create_task(session, body.url.strip(), goods_id, slug)
return {"id": task.id}
@router.get("/jobs")
async def list_jobs(session: AsyncSession = Depends(get_session)):
found = await session.scalars(
select(PlayreelTask).order_by(PlayreelTask.created_at.desc()))
return [playreel_view(task) for task in found]
@router.get("/jobs/{task_id}")
async def get_job(task_id: str, session: AsyncSession = Depends(get_session)):
return playreel_view(await find_task(session, task_id))
@router.post("/jobs/{task_id}/approve")
async def approve(task_id: str, body: ApproveBody | None = None,
session: AsyncSession = Depends(get_session)):
"""게이트 승인. edits가 없으면 검수 기본값 그대로 간다"""
task = await find_task(session, task_id)
if task.status != AWAITING_REVIEW:
raise HTTPException(409, "지금은 승인할 수 있는 상태가 아닙니다")
if body and body.gate and body.gate != task.gate:
raise HTTPException(409, f"게이트가 어긋납니다: 화면 {body.gate} / 서버 {task.gate}")
if body and body.edits:
apply_playreel_edits(task, task.gate, body.edits)
task.status = QUEUED
task.gate = None
await session.commit()
return playreel_view(task)
@router.post("/jobs/{task_id}/back")
async def back(task_id: str, session: AsyncSession = Depends(get_session)):
"""직전 게이트로. 크레딧을 이미 쓴 지점 뒤로는 되돌리지 않는다"""
task = await find_task(session, task_id)
if task.status != AWAITING_REVIEW or not task.gate:
raise HTTPException(409, "되돌릴 수 있는 상태가 아닙니다")
# 프론트가 버튼을 숨기는 것에 기대면 14크레딧을 쓴 뒤 되돌아가 다시 태우는 길이 열린다
if PlayreelGate(task.gate) not in REVERSIBLE_GATES:
raise HTTPException(409, "이 단계에서는 되돌릴 수 없습니다. "
"영상을 다시 만들려면 '다시 만들기'를 쓰세요.")
previous = previous_gate(PlayreelGate(task.gate))
reset_from(task, resume_stage(previous))
task.status = AWAITING_REVIEW
task.gate = previous.value
await session.commit()
return playreel_view(task)
@router.post("/jobs/{task_id}/retry")
async def retry(task_id: str, session: AsyncSession = Depends(get_session)):
"""실패 재시도와 클립 재생성. i2v를 다시 돌리면 크레딧이 다시 든다"""
task = await find_task(session, task_id)
restart = (PlayreelState.I2V.value if task.gate == PlayreelGate.CLIP_CONFIRM
else task.error_stage or PlayreelState.FETCH.value)
reset_from(task, restart)
task.status = QUEUED
task.gate = None
task.error_stage = None
task.error_detail = None
await session.commit()
return playreel_view(task)
@router.post("/jobs/{task_id}/force")
async def force(task_id: str, session: AsyncSession = Depends(get_session)):
"""게이트 실패를 알고도 진행"""
task = await find_task(session, task_id)
if task.status not in (FAILED, AWAITING_REVIEW):
raise HTTPException(409, "지금은 진행할 수 있는 상태가 아닙니다")
task.status = QUEUED
task.gate = None
task.error_stage = None
task.error_detail = None
await session.commit()
return playreel_view(task)
@router.delete("/jobs/{task_id}")
async def delete(task_id: str, session: AsyncSession = Depends(get_session)):
task = await find_task(session, task_id)
if task.status == RUNNING:
raise HTTPException(409, "진행 중인 작업은 삭제할 수 없습니다. 끝난 뒤 지워주세요")
await session.delete(task)
await session.commit()
return {"id": task_id, "removed": True}
@router.get("/voices/{voice_id}/sample")
async def voice_sample(voice_id: str):
raise HTTPException(404, "보이스 샘플이 아직 준비되지 않았습니다")
+73
View File
@@ -0,0 +1,73 @@
"""잡 행을 프론트가 그리는 모양으로 옮김
필드는 web/lib/api.ts 의 Job, web/lib/playreel.ts 의 PlayreelJob 과 맞춤
"""
from models.motion import MotionPlan
from models.pipeline_state import PlayreelState, PosterAliveState, initial_timings
from pipelines.gate import build_review
from tables.task import PlayreelTask, PosterAliveTask
def current_stage(task) -> str | None:
return next((key for key, entry in (task.stage_timings or {}).items()
if entry["status"] == "running"), None)
def error_view(task) -> dict | None:
if not task.error_stage:
return None
return {"stage": task.error_stage, "detail": task.error_detail or ""}
def motion_elements(motion_plan: dict | None) -> list[str] | None:
if not motion_plan:
return None
return [item.motion for item in MotionPlan.model_validate(motion_plan).kept]
def base_view(task, state_type) -> dict:
return {
"id": task.id,
"name": task.name,
"status": task.status,
"stage": current_stage(task),
"stages": task.stage_timings or initial_timings(state_type),
"error": error_view(task),
"created_at": task.created_at.timestamp(),
"credits_used": task.credits_used,
"queue_size": 0,
}
def poster_alive_view(task: PosterAliveTask) -> dict:
return {
**base_view(task, PosterAliveState),
"kind": "f1",
"narration": task.narration_lines,
"motion_elements": motion_elements(task.motion_plan),
"metadata": task.poster_metadata,
"template_id": None,
"poster_size": [task.poster_width, task.poster_height],
"low_res": task.is_low_resolution,
"artifacts": {key: url for key, url in (
("video", task.video_url),
("thumbnail", task.thumbnail_url),
("check_jpg", task.detect_check_url),
) if url},
}
def playreel_view(task: PlayreelTask) -> dict:
return {
**base_view(task, PlayreelState),
"kind": "playreel",
"source": {"url": task.source_url, "goods_id": task.goods_id, "slug": task.slug},
"gate": task.gate,
"review": build_review(task, task.gate) if task.gate else None,
"version": task.version,
"narration": [line["text"] for line in task.narration_lines or []] or None,
"metadata": None,
"artifacts": {key: url for key, url in (
("video", task.video_url),
("thumbnail", task.analysis_grid_url),
) if url},
}