File size: 15,536 Bytes
a10e62e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 | """
Creative Tool REST API Endpoints
Provides async video/audio processing endpoints using FFmpeg:
- Video trimming, format conversion, thumbnail generation
- Audio extraction, volume normalization
- Async job processing with progress tracking
- File management endpoints
All endpoints require AUTONOMOUS maturity level (file safety).
"""
import logging
from typing import Optional, List
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks, Query
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from core.database import get_db
from core.creative.ffmpeg_service import FFmpegService
from core.models import FFmpegJob, User
from core.security_dependencies import get_current_user
logger = logging.getLogger(__name__)
# Create router
router = APIRouter(prefix="/creative", tags=["creative", "media"])
# ============================================================================
# Request/Response Models
# ============================================================================
class TrimVideoRequest(BaseModel):
"""Video trimming request."""
input_path: str = Field(..., description="Source video file path")
output_path: str = Field(..., description="Output video file path")
start_time: str = Field(..., description="Start timestamp (HH:MM:SS)")
duration: str = Field(..., description="Duration to trim (HH:MM:SS or seconds)")
class ConvertFormatRequest(BaseModel):
"""Format conversion request."""
input_path: str = Field(..., description="Source video file path")
output_path: str = Field(..., description="Output video file path")
format: str = Field(..., description="Target format (mp4, webm, mov, avi)")
quality: str = Field(default="medium", description="Quality preset (low, medium, high)")
class GenerateThumbnailRequest(BaseModel):
"""Thumbnail generation request."""
video_path: str = Field(..., description="Source video file path")
thumbnail_path: str = Field(..., description="Output thumbnail file path")
timestamp: str = Field(default="00:00:01", description="Timestamp to capture (HH:MM:SS)")
class ExtractAudioRequest(BaseModel):
"""Audio extraction request."""
video_path: str = Field(..., description="Source video file path")
audio_path: str = Field(..., description="Output audio file path")
format: str = Field(default="mp3", description="Audio format (mp3, m4a, wav, flac)")
class NormalizeAudioRequest(BaseModel):
"""Audio normalization request."""
input_path: str = Field(..., description="Source audio file path")
output_path: str = Field(..., description="Output audio file path")
target_lufs: float = Field(default=-16.0, description="Target loudness in LUFS")
class JobResponse(BaseModel):
"""Job submission response."""
job_id: str
status: str
message: str = "Job submitted successfully"
class JobStatusResponse(BaseModel):
"""Job status response."""
job_id: str
status: str
progress: int
operation: str
input_path: Optional[str]
output_path: Optional[str]
created_at: Optional[str]
started_at: Optional[str]
completed_at: Optional[str]
error: Optional[str]
result: Optional[dict]
class JobListResponse(BaseModel):
"""Job list response."""
jobs: List[JobStatusResponse]
total: int
class FileListResponse(BaseModel):
"""File list response."""
directory: str
files: List[str]
total: int
class FileUploadResponse(BaseModel):
"""File upload response."""
success: bool
message: str
file_path: Optional[str]
# ============================================================================
# Helper Functions
# ============================================================================
def get_ffmpeg_service() -> FFmpegService:
"""Get FFmpeg service instance."""
try:
return FFmpegService()
except RuntimeError as e:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=f"FFmpeg service not available: {str(e)}"
)
def check_autonomous_maturity(user: User) -> None:
"""
Check if user has AUTONOMOUS maturity level.
Raises HTTPException if maturity level is insufficient.
"""
# TODO: Integrate with agent maturity system
# For now, all authenticated users can access (will be enforced at tool level)
pass
# ============================================================================
# Video Endpoints
# ============================================================================
@router.post("/video/trim", response_model=JobResponse)
async def trim_video(
request: TrimVideoRequest,
background_tasks: BackgroundTasks,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""
Trim video to specified start time and duration.
**AUTONOMOUS maturity required** (file safety).
- Returns immediately with job_id
- Processing happens in background
- Check job status via GET /creative/jobs/{job_id}
"""
service = get_ffmpeg_service()
# Validate paths
try:
service.validate_path(request.input_path)
service.validate_path(request.output_path)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Path validation failed: {str(e)}"
)
# Submit job
result = await service.trim_video(
input_path=request.input_path,
output_path=request.output_path,
start_time=request.start_time,
duration=request.duration
)
# Update user_id in job
job = db.query(FFmpegJob).filter(FFmpegJob.id == result["job_id"]).first()
if job:
job.user_id = current_user.id
db.commit()
return JobResponse(
job_id=result["job_id"],
status=result["status"],
message="Video trimming job submitted successfully"
)
@router.post("/video/convert", response_model=JobResponse)
async def convert_format(
request: ConvertFormatRequest,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""
Convert video to different format.
**AUTONOMOUS maturity required** (file safety).
Supported formats: mp4, webm, mov, avi
Quality presets: low, medium, high
"""
service = get_ffmpeg_service()
try:
service.validate_path(request.input_path)
service.validate_path(request.output_path)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Path validation failed: {str(e)}"
)
result = await service.convert_format(
input_path=request.input_path,
output_path=request.output_path,
format=request.format,
quality=request.quality
)
job = db.query(FFmpegJob).filter(FFmpegJob.id == result["job_id"]).first()
if job:
job.user_id = current_user.id
db.commit()
return JobResponse(
job_id=result["job_id"],
status=result["status"],
message=f"Format conversion to {request.format} submitted successfully"
)
@router.post("/video/thumbnail", response_model=JobResponse)
async def generate_thumbnail(
request: GenerateThumbnailRequest,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""
Generate thumbnail from video at specified timestamp.
**AUTONOMOUS maturity required** (file safety).
Output format: JPEG
Default timestamp: 00:00:01
"""
service = get_ffmpeg_service()
try:
service.validate_path(request.video_path)
service.validate_path(request.thumbnail_path)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Path validation failed: {str(e)}"
)
result = await service.generate_thumbnail(
video_path=request.video_path,
thumbnail_path=request.thumbnail_path,
timestamp=request.timestamp
)
job = db.query(FFmpegJob).filter(FFmpegJob.id == result["job_id"]).first()
if job:
job.user_id = current_user.id
db.commit()
return JobResponse(
job_id=result["job_id"],
status=result["status"],
message="Thumbnail generation job submitted successfully"
)
# ============================================================================
# Audio Endpoints
# ============================================================================
@router.post("/audio/extract", response_model=JobResponse)
async def extract_audio(
request: ExtractAudioRequest,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""
Extract audio track from video file.
**AUTONOMOUS maturity required** (file safety).
Supported formats: mp3, m4a, wav, flac
"""
service = get_ffmpeg_service()
try:
service.validate_path(request.video_path)
service.validate_path(request.audio_path)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Path validation failed: {str(e)}"
)
result = await service.extract_audio(
video_path=request.video_path,
audio_path=request.audio_path,
format=request.format
)
job = db.query(FFmpegJob).filter(FFmpegJob.id == result["job_id"]).first()
if job:
job.user_id = current_user.id
db.commit()
return JobResponse(
job_id=result["job_id"],
status=result["status"],
message=f"Audio extraction to {request.format} submitted successfully"
)
@router.post("/audio/normalize", response_model=JobResponse)
async def normalize_audio(
request: NormalizeAudioRequest,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""
Normalize audio volume to EBU R128 standard.
**AUTONOMOUS maturity required** (file safety).
Default target: -16.0 LUFS (EBU R128 standard)
"""
service = get_ffmpeg_service()
try:
service.validate_path(request.input_path)
service.validate_path(request.output_path)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Path validation failed: {str(e)}"
)
result = await service.normalize_audio(
input_path=request.input_path,
output_path=request.output_path,
target_lufs=request.target_lufs
)
job = db.query(FFmpegJob).filter(FFmpegJob.id == result["job_id"]).first()
if job:
job.user_id = current_user.id
db.commit()
return JobResponse(
job_id=result["job_id"],
status=result["status"],
message=f"Audio normalization to {request.target_lufs} LUFS submitted successfully"
)
# ============================================================================
# Job Status Endpoints
# ============================================================================
@router.get("/jobs/{job_id}", response_model=JobStatusResponse)
async def get_job_status(
job_id: str,
current_user: User = Depends(get_current_user)
):
"""
Get job status and progress.
Returns current status, progress percentage, timestamps, and result/error.
"""
service = get_ffmpeg_service()
status = await service.get_job_status(job_id)
if not status:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Job {job_id} not found"
)
# Verify user owns this job
# job = db.query(FFmpegJob).filter(FFmpegJob.id == job_id).first()
# if job and job.user_id != current_user.id:
# raise HTTPException(
# status_code=status.HTTP_403_FORBIDDEN,
# detail="Access denied to this job"
# )
return JobStatusResponse(**status)
@router.get("/jobs", response_model=JobListResponse)
async def list_user_jobs(
status_filter: Optional[str] = None,
limit: int = Query(default=50, ge=1, le=100),
current_user: User = Depends(get_current_user)
):
"""
List user's FFmpeg jobs.
Query parameters:
- status: Filter by status (pending, running, completed, failed)
- limit: Maximum number of jobs to return (default: 50)
"""
service = get_ffmpeg_service()
if status_filter and status_filter not in ["pending", "running", "completed", "failed"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid status filter. Use: pending, running, completed, failed"
)
jobs = await service.list_user_jobs(
user_id=current_user.id,
status=status_filter,
limit=limit
)
return JobListResponse(jobs=jobs, total=len(jobs))
# ============================================================================
# File Management Endpoints
# ============================================================================
@router.get("/files", response_model=FileListResponse)
async def list_files(
directory: str = "./data/media",
current_user: User = Depends(get_current_user)
):
"""
List files in allowed directory.
Returns list of files available for processing.
"""
import os
service = get_ffmpeg_service()
# Validate directory
if not service.validate_path(directory):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Directory outside allowed paths: {directory}"
)
if not os.path.exists(directory):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Directory not found: {directory}"
)
# List files
try:
files = [
f for f in os.listdir(directory)
if os.path.isfile(os.path.join(directory, f))
and not f.startswith(".") # Skip hidden files
]
except PermissionError:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Permission denied accessing directory: {directory}"
)
return FileListResponse(directory=directory, files=files, total=len(files))
@router.delete("/files/{file_path:path}", response_model=dict)
async def delete_file(
file_path: str,
current_user: User = Depends(get_current_user)
):
"""
Delete file from allowed directory.
**AUTONOMOUS maturity required** (destructive operation).
"""
import os
service = get_ffmpeg_service()
# Validate path
if not service.validate_path(file_path):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"File path outside allowed directories: {file_path}"
)
if not os.path.exists(file_path):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"File not found: {file_path}"
)
try:
os.remove(file_path)
logger.info("File deleted via creative API", file_path=file_path, user_id=current_user.id)
return {"success": True, "message": f"File deleted: {file_path}"}
except PermissionError:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Permission denied deleting file: {file_path}"
)
|