luci18 commited on
Commit
10a4525
·
verified ·
1 Parent(s): 03d30e6

Clean bot folder

Browse files
Files changed (1) hide show
  1. bot/thumbnail.py +0 -213
bot/thumbnail.py DELETED
@@ -1,213 +0,0 @@
1
- """Thumbnail generation module for anime encoder bot."""
2
- import logging
3
- import subprocess
4
- from pathlib import Path
5
- from typing import Optional, List, Dict, Any
6
- import random
7
-
8
- logger = logging.getLogger(__name__)
9
-
10
-
11
- class ThumbnailGenerator:
12
- """Generate thumbnails from video files."""
13
-
14
- # Resolution presets
15
- RESOLUTIONS = {
16
- "1080p": (1920, 1080),
17
- "720p": (1280, 720),
18
- "480p": (854, 480),
19
- "360p": (640, 360),
20
- "240p": (427, 240),
21
- "180p": (320, 180)
22
- }
23
-
24
- # Position presets for thumbnail extraction
25
- POSITIONS = {
26
- "start": "00:00:05",
27
- "10%": "10%",
28
- "25%": "25%",
29
- "middle": "50%",
30
- "75%": "75%",
31
- "90%": "90%",
32
- "end": "95%"
33
- }
34
-
35
- def __init__(self, ffmpeg_path: str = "ffmpeg"):
36
- self.ffmpeg_path = ffmpeg_path
37
-
38
- def generate_thumbnail(self, video_path: Path, output_path: Path,
39
- time_offset: Optional[str] = None,
40
- width: int = 1280, height: int = 720,
41
- settings: Optional[Dict[str, Any]] = None) -> Optional[Path]:
42
- """Generate a thumbnail from video at specified time.
43
-
44
- Args:
45
- video_path: Path to input video
46
- output_path: Path to save thumbnail
47
- time_offset: Time position (e.g., "00:05:30" or percentage like "25%")
48
- width: Thumbnail width
49
- height: Thumbnail height
50
-
51
- Returns:
52
- Path to generated thumbnail or None if failed
53
- """
54
- try:
55
- # If no time specified, use 25% into the video
56
- if not time_offset:
57
- # Get video duration first
58
- duration = self._get_duration(video_path)
59
- if duration > 0:
60
- # Use 25% mark or 5 minutes, whichever is smaller
61
- target_time = min(duration * 0.25, 300)
62
- time_offset = self._seconds_to_timecode(target_time)
63
- else:
64
- time_offset = "00:00:05"
65
-
66
- # Ensure output directory exists
67
- output_path.parent.mkdir(parents=True, exist_ok=True)
68
-
69
- cmd = [
70
- self.ffmpeg_path,
71
- "-ss", time_offset,
72
- "-i", str(video_path),
73
- "-vframes", "1",
74
- "-vf", f"scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:black",
75
- "-q:v", "2",
76
- "-y",
77
- str(output_path)
78
- ]
79
-
80
- result = subprocess.run(cmd, capture_output=True, text=True)
81
-
82
- if result.returncode == 0 and output_path.exists():
83
- logger.info(f"Thumbnail generated: {output_path}")
84
- return output_path
85
- else:
86
- logger.error(f"Thumbnail generation failed: {result.stderr}")
87
- return None
88
-
89
- except Exception as e:
90
- logger.error(f"Thumbnail generation error: {e}")
91
- return None
92
-
93
- def generate_multiple_thumbnails(self, video_path: Path,
94
- output_dir: Path,
95
- count: int = 5) -> List[Path]:
96
- """Generate multiple thumbnails at different timestamps.
97
-
98
- Args:
99
- video_path: Path to input video
100
- output_dir: Directory to save thumbnails
101
- count: Number of thumbnails to generate
102
-
103
- Returns:
104
- List of generated thumbnail paths
105
- """
106
- thumbnails = []
107
-
108
- try:
109
- duration = self._get_duration(video_path)
110
- if duration <= 0:
111
- return thumbnails
112
-
113
- # Generate thumbnails at evenly spaced intervals
114
- # Skip first and last 10% to avoid intros/outros
115
- start = duration * 0.1
116
- end = duration * 0.9
117
- step = (end - start) / count if count > 1 else (end - start)
118
-
119
- for i in range(count):
120
- timestamp = start + (step * i)
121
- timecode = self._seconds_to_timecode(timestamp)
122
-
123
- output_path = output_dir / f"thumb_{i+1:02d}.jpg"
124
-
125
- thumb = self.generate_thumbnail(
126
- video_path,
127
- output_path,
128
- time_offset=timecode,
129
- width=320, # Smaller for preview
130
- height=180
131
- )
132
- if thumb:
133
- thumbnails.append(thumb)
134
-
135
- return thumbnails
136
-
137
- except Exception as e:
138
- logger.error(f"Multiple thumbnail generation error: {e}")
139
- return thumbnails
140
-
141
- def generate_preview_gif(self, video_path: Path, output_path: Path,
142
- duration: int = 3, fps: int = 2) -> Optional[Path]:
143
- """Generate a short preview GIF/animation.
144
-
145
- Args:
146
- video_path: Path to input video
147
- output_path: Path to save GIF
148
- duration: Duration of GIF in seconds
149
- fps: Frames per second
150
-
151
- Returns:
152
- Path to generated GIF or None if failed
153
- """
154
- try:
155
- # Get a random position in the middle 60% of the video
156
- video_duration = self._get_duration(video_path)
157
- if video_duration > 0:
158
- start_time = (video_duration * 0.2) + random.random() * (video_duration * 0.6)
159
- start_timecode = self._seconds_to_timecode(start_time)
160
- else:
161
- start_timecode = "00:05:00"
162
-
163
- output_path.parent.mkdir(parents=True, exist_ok=True)
164
-
165
- cmd = [
166
- self.ffmpeg_path,
167
- "-ss", start_timecode,
168
- "-t", str(duration),
169
- "-i", str(video_path),
170
- "-vf", f"fps={fps},scale=480:-1:flags=lanczos,split[s0][s1];[s0]palettegen=[s1]paletteuse",
171
- "-loop", "0",
172
- "-y",
173
- str(output_path)
174
- ]
175
-
176
- result = subprocess.run(cmd, capture_output=True, text=True)
177
-
178
- if result.returncode == 0 and output_path.exists():
179
- logger.info(f"Preview GIF generated: {output_path}")
180
- return output_path
181
- else:
182
- logger.error(f"GIF generation failed: {result.stderr}")
183
- return None
184
-
185
- except Exception as e:
186
- logger.error(f"GIF generation error: {e}")
187
- return None
188
-
189
- def _get_duration(self, video_path: Path) -> float:
190
- """Get video duration in seconds."""
191
- try:
192
- cmd = [
193
- "ffprobe",
194
- "-v", "error",
195
- "-show_entries", "format=duration",
196
- "-of", "default=noprint_wrappers=1:nokey=1",
197
- str(video_path)
198
- ]
199
- result = subprocess.run(cmd, capture_output=True, text=True)
200
- return float(result.stdout.strip()) if result.returncode == 0 else 0.0
201
- except Exception:
202
- return 0.0
203
-
204
- def _seconds_to_timecode(self, seconds: float) -> str:
205
- """Convert seconds to HH:MM:SS timecode."""
206
- hours = int(seconds // 3600)
207
- minutes = int((seconds % 3600) // 60)
208
- secs = int(seconds % 60)
209
- return f"{hours:02d}:{minutes:02d}:{secs:02d}"
210
-
211
-
212
- # Global instance
213
- thumbnail_generator = ThumbnailGenerator()