feat(music-lab): pipeline 영상·썸네일 생성

This commit is contained in:
2026-05-07 16:53:57 +09:00
parent e33a2310af
commit 68dec2e53d
3 changed files with 172 additions and 0 deletions

View File

@@ -0,0 +1,51 @@
"""썸네일 생성 — 영상 5초 프레임 추출 + 텍스트 오버레이."""
import os
import subprocess
import logging
from PIL import Image, ImageDraw, ImageFont
from . import storage
logger = logging.getLogger("music-lab.thumb")
THUMB_TIMEOUT_S = 60
class ThumbGenerationError(Exception):
pass
def generate(*, pipeline_id: int, video_path: str,
track_title: str = "", overlay_text: bool = True) -> dict:
out_path = os.path.join(storage.pipeline_dir(pipeline_id), "thumbnail.jpg")
cmd = ["ffmpeg", "-y", "-i", video_path,
"-ss", "00:00:05", "-vframes", "1", "-q:v", "2", out_path]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=THUMB_TIMEOUT_S)
if result.returncode != 0:
raise ThumbGenerationError(f"ffmpeg 썸네일 실패: {result.stderr[:300]}")
if overlay_text and track_title:
_overlay_title(out_path, track_title)
return {"url": storage.media_url(pipeline_id, "thumbnail.jpg"), "used_fallback": False}
def _overlay_title(path: str, title: str) -> None:
try:
with Image.open(path) as src:
img = src.convert("RGB")
try:
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 80)
except OSError:
font = ImageFont.load_default()
draw = ImageDraw.Draw(img)
# 하단 30% 영역에 검정 반투명 박스 + 흰 글씨
w, h = img.size
box_h = int(h * 0.3)
with Image.new("RGBA", (w, box_h), (0, 0, 0, 160)) as overlay:
img.paste(overlay, (0, h - box_h), overlay)
bbox = draw.textbbox((0, 0), title, font=font)
tw = bbox[2] - bbox[0]
draw.text(((w - tw) // 2, h - box_h + 30), title, fill=(255, 255, 255), font=font)
img.save(path, "JPEG", quality=92)
except Exception as e:
logger.warning("썸네일 오버레이 실패: %s", e)

View File

@@ -0,0 +1,55 @@
"""영상 비주얼 생성 — visualizer/슬라이드쇼 스타일."""
import os
import subprocess
import logging
from . import storage
logger = logging.getLogger("music-lab.video")
VIDEO_TIMEOUT_S = 300 # 5분
class VideoGenerationError(Exception):
pass
def generate(*, pipeline_id: int, audio_path: str, cover_path: str,
genre: str, duration_sec: int, resolution: str = "1920x1080",
style: str = "visualizer") -> dict:
"""영상 생성. 성공 시 mp4 저장 + URL 반환. 실패 시 예외."""
w, h = resolution.split("x")
out_path = os.path.join(storage.pipeline_dir(pipeline_id), "video.mp4")
if style == "visualizer":
cmd = _build_visualizer_cmd(audio_path, cover_path, out_path, w, h)
else:
# 차후: 슬라이드쇼 등 다른 스타일 — 현재는 visualizer 폴백
cmd = _build_visualizer_cmd(audio_path, cover_path, out_path, w, h)
logger.info("ffmpeg 실행: %s", " ".join(cmd))
result = subprocess.run(cmd, capture_output=True, text=True, timeout=VIDEO_TIMEOUT_S)
if result.returncode != 0:
raise VideoGenerationError(f"ffmpeg 실패: {result.stderr[:500]}")
return {
"url": storage.media_url(pipeline_id, "video.mp4"),
"used_fallback": False,
"duration_sec": duration_sec,
}
def _build_visualizer_cmd(audio: str, bg: str, out: str, w: str, h: str) -> list:
return [
"ffmpeg", "-y",
"-loop", "1", "-i", bg,
"-i", audio,
"-filter_complex",
f"[0:v]scale={w}:{h}[bg];"
f"[1:a]showwaves=s={w}x200:mode=cline:colors=0xFF4444@0.8[wave];"
f"[bg][wave]overlay=0:({h}-200)[out]",
"-map", "[out]", "-map", "1:a",
"-c:v", "libx264", "-preset", "fast", "-crf", "23",
"-c:a", "aac", "-b:a", "192k",
"-shortest", out,
]