animebot / bot /thumbnail.py
luci18's picture
Re-upload fresh bot files
7cb306b verified
Raw History Blame Contribute Delete
7.66 kB
"""Thumbnail generation module for anime encoder bot."""
import logging
import subprocess
from pathlib import Path
from typing import Optional, List, Dict, Any
import random
logger = logging.getLogger(__name__)
class ThumbnailGenerator:
"""Generate thumbnails from video files."""
# Resolution presets
RESOLUTIONS = {
"1080p": (1920, 1080),
"720p": (1280, 720),
"480p": (854, 480),
"360p": (640, 360),
"240p": (427, 240),
"180p": (320, 180)
}
# Position presets for thumbnail extraction
POSITIONS = {
"start": "00:00:05",
"10%": "10%",
"25%": "25%",
"middle": "50%",
"75%": "75%",
"90%": "90%",
"end": "95%"
}
def __init__(self, ffmpeg_path: str = "ffmpeg"):
self.ffmpeg_path = ffmpeg_path
def generate_thumbnail(self, video_path: Path, output_path: Path,
time_offset: Optional[str] = None,
width: int = 1280, height: int = 720,
settings: Optional[Dict[str, Any]] = None) -> Optional[Path]:
"""Generate a thumbnail from video at specified time.
Args:
video_path: Path to input video
output_path: Path to save thumbnail
time_offset: Time position (e.g., "00:05:30" or percentage like "25%")
width: Thumbnail width
height: Thumbnail height
Returns:
Path to generated thumbnail or None if failed
"""
try:
# If no time specified, use 25% into the video
if not time_offset:
# Get video duration first
duration = self._get_duration(video_path)
if duration > 0:
# Use 25% mark or 5 minutes, whichever is smaller
target_time = min(duration * 0.25, 300)
time_offset = self._seconds_to_timecode(target_time)
else:
time_offset = "00:00:05"
# Ensure output directory exists
output_path.parent.mkdir(parents=True, exist_ok=True)
cmd = [
self.ffmpeg_path,
"-ss", time_offset,
"-i", str(video_path),
"-vframes", "1",
"-vf", f"scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:black",
"-q:v", "2",
"-y",
str(output_path)
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0 and output_path.exists():
logger.info(f"Thumbnail generated: {output_path}")
return output_path
else:
logger.error(f"Thumbnail generation failed: {result.stderr}")
return None
except Exception as e:
logger.error(f"Thumbnail generation error: {e}")
return None
def generate_multiple_thumbnails(self, video_path: Path,
output_dir: Path,
count: int = 5) -> List[Path]:
"""Generate multiple thumbnails at different timestamps.
Args:
video_path: Path to input video
output_dir: Directory to save thumbnails
count: Number of thumbnails to generate
Returns:
List of generated thumbnail paths
"""
thumbnails = []
try:
duration = self._get_duration(video_path)
if duration <= 0:
return thumbnails
# Generate thumbnails at evenly spaced intervals
# Skip first and last 10% to avoid intros/outros
start = duration * 0.1
end = duration * 0.9
step = (end - start) / count if count > 1 else (end - start)
for i in range(count):
timestamp = start + (step * i)
timecode = self._seconds_to_timecode(timestamp)
output_path = output_dir / f"thumb_{i+1:02d}.jpg"
thumb = self.generate_thumbnail(
video_path,
output_path,
time_offset=timecode,
width=320, # Smaller for preview
height=180
)
if thumb:
thumbnails.append(thumb)
return thumbnails
except Exception as e:
logger.error(f"Multiple thumbnail generation error: {e}")
return thumbnails
def generate_preview_gif(self, video_path: Path, output_path: Path,
duration: int = 3, fps: int = 2) -> Optional[Path]:
"""Generate a short preview GIF/animation.
Args:
video_path: Path to input video
output_path: Path to save GIF
duration: Duration of GIF in seconds
fps: Frames per second
Returns:
Path to generated GIF or None if failed
"""
try:
# Get a random position in the middle 60% of the video
video_duration = self._get_duration(video_path)
if video_duration > 0:
start_time = (video_duration * 0.2) + random.random() * (video_duration * 0.6)
start_timecode = self._seconds_to_timecode(start_time)
else:
start_timecode = "00:05:00"
output_path.parent.mkdir(parents=True, exist_ok=True)
cmd = [
self.ffmpeg_path,
"-ss", start_timecode,
"-t", str(duration),
"-i", str(video_path),
"-vf", f"fps={fps},scale=480:-1:flags=lanczos,split[s0][s1];[s0]palettegen=[s1]paletteuse",
"-loop", "0",
"-y",
str(output_path)
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0 and output_path.exists():
logger.info(f"Preview GIF generated: {output_path}")
return output_path
else:
logger.error(f"GIF generation failed: {result.stderr}")
return None
except Exception as e:
logger.error(f"GIF generation error: {e}")
return None
def _get_duration(self, video_path: Path) -> float:
"""Get video duration in seconds."""
try:
cmd = [
"ffprobe",
"-v", "error",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
str(video_path)
]
result = subprocess.run(cmd, capture_output=True, text=True)
return float(result.stdout.strip()) if result.returncode == 0 else 0.0
except Exception:
return 0.0
def _seconds_to_timecode(self, seconds: float) -> str:
"""Convert seconds to HH:MM:SS timecode."""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
# Global instance
thumbnail_generator = ThumbnailGenerator()