embedingHF commited on
Commit
e989bcf
·
verified ·
1 Parent(s): 6d86e61

Update converters/video_converter.py

Browse files
Files changed (1) hide show
  1. converters/video_converter.py +188 -48
converters/video_converter.py CHANGED
@@ -5,13 +5,17 @@ from typing import Callable, Dict, Any
5
  import shutil
6
  import traceback
7
 
8
- # Find ffmpeg
9
- ffmpeg_path = shutil.which('ffmpeg') or shutil.which('ffmpeg.exe')
 
 
10
  if not ffmpeg_path:
 
11
  common_paths = [
12
  r"C:\ffmpeg\bin\ffmpeg.exe",
13
  r"C:\Program Files\ffmpeg\bin\ffmpeg.exe",
14
  ]
 
15
  for path in common_paths:
16
  if os.path.exists(path):
17
  ffmpeg_path = path
@@ -19,84 +23,220 @@ if not ffmpeg_path:
19
 
20
 
21
  class VideoConverter:
 
 
 
 
 
 
 
 
 
 
22
  def __init__(self):
 
23
  self.ffmpeg_available = self._check_ffmpeg()
24
 
25
  def _check_ffmpeg(self):
26
- """Check if ffmpeg is installed"""
27
  if not ffmpeg_path or not os.path.exists(ffmpeg_path):
28
- print("⚠ FFmpeg not found. Video conversion will not work.")
 
 
29
  return False
 
30
  return True
31
 
32
- def convert(self, input_path: str, output_path: str,
33
- options: Dict[str, Any], progress_callback: Callable = None) -> bool:
34
- """Convert video files using ffmpeg"""
 
 
 
 
 
 
 
35
  try:
 
36
  if not self.ffmpeg_available:
37
- print("FFmpeg not available for video conversion")
38
  return False
39
 
40
  self._update_progress(progress_callback, 10)
41
 
42
- # Check input file
43
  if not os.path.exists(input_path):
44
- print(f"Input file not found: {input_path}")
45
- return False
46
 
47
- # Build ffmpeg command
48
- cmd = [ffmpeg_path, '-i', input_path, '-y']
49
 
50
- # Add quality settings
51
- quality_settings = options.get("quality_settings", {})
52
- crf_value = quality_settings.get("video", "23")
 
53
 
54
- # Output format specific settings
55
- output_ext = Path(output_path).suffix.lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- format_settings = {
58
- '.mp4': ['-c:v', 'libx264', '-preset', 'medium', '-crf', crf_value, '-c:a', 'aac', '-b:a', '128k'],
59
- '.avi': ['-c:v', 'libxvid', '-q:v', '4', '-c:a', 'mp3', '-b:a', '192k'],
60
- '.mkv': ['-c:v', 'libx264', '-crf', crf_value, '-c:a', 'aac'],
61
- '.mov': ['-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac'],
62
- '.webm': ['-c:v', 'libvpx-vp9', '-crf', crf_value, '-b:v', '0', '-c:a', 'libopus'],
63
- '.gif': ['-vf', 'fps=10,scale=320:-1:flags=lanczos', '-c:v', 'gif']
64
- }
65
 
66
- if output_ext in format_settings:
67
- cmd.extend(format_settings[output_ext])
68
 
69
- # Add AI enhancement
70
- if options.get("ai_enhancement", False):
71
- cmd.extend(['-vf', 'unsharp=5:5:1.0:5:5:0.0'])
 
 
 
 
72
 
73
- # Create output directory
74
- Path(output_path).parent.mkdir(parents=True, exist_ok=True)
75
- cmd.append(output_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
  self._update_progress(progress_callback, 50)
78
 
 
 
 
79
  # Run ffmpeg
80
- result = subprocess.run(cmd, capture_output=True, text=True)
 
 
 
 
 
81
 
82
- self._update_progress(progress_callback, 100)
 
 
 
 
 
83
 
84
- if result.returncode == 0:
85
- print(f"✓ Successfully converted: {os.path.basename(input_path)} → {output_ext}")
86
- return True
87
- else:
88
- print(f"FFmpeg error: {result.stderr[:200]}")
89
  return False
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  except Exception as e:
92
- print(f"Video conversion error for {input_path}: {str(e)}")
 
 
 
 
93
  traceback.print_exc()
 
94
  return False
95
 
96
- def _update_progress(self, callback, value):
97
- """Safely update progress"""
98
- if callback is not None:
99
- try:
 
 
 
 
 
100
  callback(value)
101
- except Exception:
102
- pass
 
 
 
 
 
5
  import shutil
6
  import traceback
7
 
8
+
9
+ # Find FFmpeg
10
+ ffmpeg_path = shutil.which("ffmpeg") or shutil.which("ffmpeg.exe")
11
+
12
  if not ffmpeg_path:
13
+
14
  common_paths = [
15
  r"C:\ffmpeg\bin\ffmpeg.exe",
16
  r"C:\Program Files\ffmpeg\bin\ffmpeg.exe",
17
  ]
18
+
19
  for path in common_paths:
20
  if os.path.exists(path):
21
  ffmpeg_path = path
 
23
 
24
 
25
  class VideoConverter:
26
+
27
+ SUPPORTED_FORMATS = {
28
+ ".mp4",
29
+ ".avi",
30
+ ".mkv",
31
+ ".mov",
32
+ ".webm",
33
+ ".gif"
34
+ }
35
+
36
  def __init__(self):
37
+
38
  self.ffmpeg_available = self._check_ffmpeg()
39
 
40
  def _check_ffmpeg(self):
41
+
42
  if not ffmpeg_path or not os.path.exists(ffmpeg_path):
43
+
44
+ print("⚠ FFmpeg not found")
45
+
46
  return False
47
+
48
  return True
49
 
50
+ def convert(
51
+ self,
52
+ input_path: str,
53
+ output_path: str,
54
+ options: Dict[str, Any] | None = None,
55
+ progress_callback: Callable = None
56
+ ) -> bool:
57
+
58
+ options = options or {}
59
+
60
  try:
61
+
62
  if not self.ffmpeg_available:
63
+ print("FFmpeg not available")
64
  return False
65
 
66
  self._update_progress(progress_callback, 10)
67
 
68
+ # Validate input
69
  if not os.path.exists(input_path):
70
+ raise FileNotFoundError(input_path)
 
71
 
72
+ input_ext = Path(input_path).suffix.lower()
73
+ output_ext = Path(output_path).suffix.lower()
74
 
75
+ if output_ext not in self.SUPPORTED_FORMATS:
76
+ raise ValueError(
77
+ f"Unsupported format: {output_ext}"
78
+ )
79
 
80
+ # Create output directory
81
+ Path(output_path).parent.mkdir(
82
+ parents=True,
83
+ exist_ok=True
84
+ )
85
+
86
+ self._update_progress(progress_callback, 20)
87
+
88
+ # Quality settings
89
+ quality_settings = options.get(
90
+ "quality_settings",
91
+ {}
92
+ )
93
+
94
+ crf_value = str(
95
+ quality_settings.get("video", "23")
96
+ )
97
+
98
+ # Base command
99
+ cmd = [
100
+ ffmpeg_path,
101
+ "-y",
102
+ "-i",
103
+ input_path
104
+ ]
105
+
106
+ # Video filters
107
+ video_filters = []
108
+
109
+ # AI enhancement
110
+ if options.get("ai_enhancement", False):
111
 
112
+ video_filters.append(
113
+ "unsharp=5:5:1.0:5:5:0.0"
114
+ )
 
 
 
 
 
115
 
116
+ # Format settings
117
+ if output_ext == ".mp4":
118
 
119
+ cmd.extend([
120
+ "-c:v", "libx264",
121
+ "-preset", "medium",
122
+ "-crf", crf_value,
123
+ "-c:a", "aac",
124
+ "-b:a", "128k"
125
+ ])
126
 
127
+ elif output_ext == ".avi":
128
+
129
+ cmd.extend([
130
+ "-c:v", "libxvid",
131
+ "-q:v", "4",
132
+ "-c:a", "mp3",
133
+ "-b:a", "192k"
134
+ ])
135
+
136
+ elif output_ext == ".mkv":
137
+
138
+ cmd.extend([
139
+ "-c:v", "libx264",
140
+ "-crf", crf_value,
141
+ "-c:a", "aac"
142
+ ])
143
+
144
+ elif output_ext == ".mov":
145
+
146
+ cmd.extend([
147
+ "-c:v", "libx264",
148
+ "-pix_fmt", "yuv420p",
149
+ "-c:a", "aac"
150
+ ])
151
+
152
+ elif output_ext == ".webm":
153
+
154
+ cmd.extend([
155
+ "-c:v", "libvpx-vp9",
156
+ "-crf", crf_value,
157
+ "-b:v", "0",
158
+ "-c:a", "libopus"
159
+ ])
160
+
161
+ elif output_ext == ".gif":
162
+
163
+ video_filters.append(
164
+ "fps=10,scale=320:-1:flags=lanczos"
165
+ )
166
+
167
+ cmd.extend([
168
+ "-loop", "0"
169
+ ])
170
+
171
+ # Apply filters safely
172
+ if video_filters:
173
+
174
+ cmd.extend([
175
+ "-vf",
176
+ ",".join(video_filters)
177
+ ])
178
 
179
  self._update_progress(progress_callback, 50)
180
 
181
+ # Output path
182
+ cmd.append(output_path)
183
+
184
  # Run ffmpeg
185
+ result = subprocess.run(
186
+ cmd,
187
+ capture_output=True,
188
+ text=True,
189
+ timeout=600
190
+ )
191
 
192
+ self._update_progress(progress_callback, 90)
193
+
194
+ if result.returncode != 0:
195
+
196
+ print("FFmpeg Error:")
197
+ print(result.stderr[:500])
198
 
 
 
 
 
 
199
  return False
200
 
201
+ self._update_progress(progress_callback, 100)
202
+
203
+ print(
204
+ f"✓ Converted: "
205
+ f"{os.path.basename(input_path)} "
206
+ f"→ {output_ext}"
207
+ )
208
+
209
+ return True
210
+
211
+ except subprocess.TimeoutExpired:
212
+
213
+ print("Video conversion timed out")
214
+
215
+ return False
216
+
217
  except Exception as e:
218
+
219
+ print(
220
+ f"Video conversion error: {e}"
221
+ )
222
+
223
  traceback.print_exc()
224
+
225
  return False
226
 
227
+ def _update_progress(
228
+ self,
229
+ callback,
230
+ value
231
+ ):
232
+
233
+ try:
234
+
235
+ if callback:
236
  callback(value)
237
+
238
+ except Exception as e:
239
+
240
+ print(
241
+ f"Progress callback error: {e}"
242
+ )