Politrees commited on
Commit
d046d0e
·
verified ·
1 Parent(s): 0b79a93

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -64
app.py CHANGED
@@ -18,40 +18,7 @@ i18n = gr.I18n(
18
  )
19
 
20
  # ----------------------- HuggingFace Spaces Settings -----------------------
21
- MAX_WORKERS = min(2, multiprocessing.cpu_count()) # Limited CPU on HF Spaces
22
- CHUNK_SIZE = 1024 * 1024 * 5 # 5MB chunks
23
-
24
- def check_ffmpeg_installation():
25
- """Check FFmpeg installation and available codecs"""
26
- try:
27
- result = subprocess.run(
28
- ['ffmpeg', '-version'],
29
- capture_output=True,
30
- text=True,
31
- timeout=5
32
- )
33
- print("FFmpeg version info:")
34
- print(result.stdout.split('\n')[0])
35
-
36
- result = subprocess.run(
37
- ['ffmpeg', '-hide_banner', '-codecs'],
38
- capture_output=True,
39
- text=True,
40
- timeout=5
41
- )
42
-
43
- important_codecs = ['libx264', 'libmp3lame', 'aac', 'libvpx-vp9', 'libopus']
44
- available = []
45
- for codec in important_codecs:
46
- if codec in result.stdout:
47
- available.append(codec)
48
-
49
- print(f"Available important codecs: {', '.join(available)}")
50
- return True
51
-
52
- except Exception as e:
53
- print(f"FFmpeg check failed: {e}")
54
- return False
55
 
56
  # ----------------------- FFmpeg utils -----------------------
57
  def _run_ffmpeg(args):
@@ -209,7 +176,7 @@ def pil_format_for_ext(ext):
209
 
210
  # ----------------------- Optimized FFmpeg Processing -----------------------
211
  def run_ffmpeg_with_progress(params):
212
- """Run FFmpeg with progress display"""
213
  try:
214
  process = subprocess.Popen(
215
  ['ffmpeg'] + params,
@@ -222,14 +189,12 @@ def run_ffmpeg_with_progress(params):
222
  output = []
223
  for line in process.stdout:
224
  output.append(line)
225
- if 'time=' in line:
226
- print('.', end='', flush=True)
227
 
228
  process.wait()
229
 
230
  if process.returncode != 0:
231
- error_output = ''.join(output[-50:])
232
- print(f"FFmpeg error output:\n{error_output}")
233
  return False
234
 
235
  return True
@@ -242,7 +207,7 @@ def get_optimal_ffmpeg_params(input_file, output_file, conversion_type="audio"):
242
  """Get optimal FFmpeg parameters for conversion"""
243
  params = []
244
 
245
- params.extend(['-hide_banner', '-y'])
246
  params.extend(['-i', input_file])
247
 
248
  ext = os.path.splitext(output_file)[1].lower()[1:]
@@ -268,7 +233,6 @@ def get_optimal_ffmpeg_params(input_file, output_file, conversion_type="audio"):
268
  elif ext == 'wav':
269
  params.extend(['-codec:a', 'pcm_s16le'])
270
 
271
- # Format specification if needed
272
  if ff_format != ext:
273
  params.extend(['-f', ff_format])
274
 
@@ -328,7 +292,6 @@ def get_optimal_ffmpeg_params(input_file, output_file, conversion_type="audio"):
328
  else:
329
  params.extend(['-codec:a', 'copy'])
330
 
331
- # Format specification if needed
332
  if ff_format != ext:
333
  params.extend(['-f', ff_format])
334
 
@@ -340,7 +303,6 @@ def get_optimal_ffmpeg_params(input_file, output_file, conversion_type="audio"):
340
  def convert_audio_ffmpeg(input_file, output_file, output_ext):
341
  """Fast audio conversion via direct FFmpeg call"""
342
  if not os.path.exists(input_file):
343
- print(f"Input file does not exist: {input_file}")
344
  return False
345
 
346
  output_dir = os.path.dirname(output_file)
@@ -355,7 +317,6 @@ def convert_video_ffmpeg(input_file, output_file, conversion_type):
355
  conv_type = "video_to_audio" if conversion_type == "Video to Audio" else "video"
356
 
357
  if not os.path.exists(input_file):
358
- print(f"Input file does not exist: {input_file}")
359
  return False
360
 
361
  output_dir = os.path.dirname(output_file)
@@ -363,8 +324,6 @@ def convert_video_ffmpeg(input_file, output_file, conversion_type):
363
  os.makedirs(output_dir, exist_ok=True)
364
 
365
  params = get_optimal_ffmpeg_params(input_file, output_file, conv_type)
366
- print(f"FFmpeg command: ffmpeg {' '.join(params)}")
367
-
368
  return run_ffmpeg_with_progress(params)
369
 
370
  def merge_audio_files_ffmpeg(input_files, output_file, gap_duration):
@@ -377,6 +336,8 @@ def merge_audio_files_ffmpeg(input_files, output_file, gap_duration):
377
  f.write(f"file '{os.path.abspath(file)}'\n")
378
 
379
  params = [
 
 
380
  '-f', 'concat',
381
  '-safe', '0',
382
  '-i', list_file,
@@ -407,8 +368,7 @@ def convert_image_pillow(input_file, output_path, output_ext):
407
  img.save(output_path, format=pil_format)
408
 
409
  return True
410
- except Exception as e:
411
- print(f"Image conversion error: {e}")
412
  return False
413
 
414
  def process_file_parallel(args):
@@ -423,8 +383,7 @@ def process_file_parallel(args):
423
  else:
424
  success = False
425
  return output_path if success else None
426
- except Exception as e:
427
- print(f"Error processing {input_file}: {e}")
428
  return None
429
 
430
  def create_zip(files_to_zip, session_id):
@@ -443,10 +402,9 @@ def process_audio_files(files, output_ext, merge_files, gap_duration, progress=g
443
 
444
  session_id = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"
445
  os.makedirs(session_id, exist_ok=True)
446
-
447
  print(f"\nStarting audio session: {session_id}")
448
  print(f"Files to convert: {len(files)} to .{output_ext}")
449
- print(f"Using {MAX_WORKERS} threads")
450
 
451
  file_paths = [f if isinstance(f, str) else f.name for f in files]
452
 
@@ -505,10 +463,9 @@ def process_image_files(files, output_ext, progress=gr.Progress(track_tqdm=True)
505
 
506
  session_id = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"
507
  os.makedirs(session_id, exist_ok=True)
508
-
509
  print(f"\nStarting image session: {session_id}")
510
  print(f"Files to convert: {len(files)} to .{output_ext}")
511
- print(f"Using {MAX_WORKERS} threads")
512
 
513
  file_paths = [f if isinstance(f, str) else f.name for f in files]
514
  output_files = []
@@ -547,14 +504,14 @@ def process_video(input_video, conversion_type, output_ext, progress=gr.Progress
547
  input_path = input_video if isinstance(input_video, str) else input_video.name
548
  base_name = os.path.splitext(os.path.basename(input_path))[0]
549
  output_path = os.path.join(session_id, f"{base_name}.{output_ext}")
550
-
551
  print(f"\nStarting video session: {session_id}")
552
  print(f"Conversion type: {conversion_type}, Output: .{output_ext}")
553
 
 
554
  success = convert_video_ffmpeg(input_path, output_path, conversion_type)
555
 
556
  if success:
557
- print("Video processing complete!")
558
  return output_path
559
  else:
560
  raise gr.Error("Video processing failed. Please check the file format and try again.")
@@ -577,13 +534,6 @@ IMAGE_FORMATS = available_image_extensions()
577
 
578
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
579
  gr.HTML(i18n("title_app"))
580
-
581
- # System info
582
- gr.HTML(f"""
583
- <div style='text-align: center; color: #666; margin-bottom: 1rem;'>
584
- <p>CPU cores: {multiprocessing.cpu_count()} | Using {MAX_WORKERS} threads</p>
585
- </div>
586
- """)
587
 
588
  with gr.Tabs():
589
  # AUDIO TAB
@@ -670,5 +620,4 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
670
  )
671
 
672
  if __name__ == "__main__":
673
- check_ffmpeg_installation()
674
  demo.queue().launch(i18n=i18n, debug=True, show_error=True)
 
18
  )
19
 
20
  # ----------------------- HuggingFace Spaces Settings -----------------------
21
+ MAX_WORKERS = min(2, multiprocessing.cpu_count())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  # ----------------------- FFmpeg utils -----------------------
24
  def _run_ffmpeg(args):
 
176
 
177
  # ----------------------- Optimized FFmpeg Processing -----------------------
178
  def run_ffmpeg_with_progress(params):
179
+ """Run FFmpeg with minimal output"""
180
  try:
181
  process = subprocess.Popen(
182
  ['ffmpeg'] + params,
 
189
  output = []
190
  for line in process.stdout:
191
  output.append(line)
 
 
192
 
193
  process.wait()
194
 
195
  if process.returncode != 0:
196
+ error_output = ''.join(output[-20:]) # Only last 20 lines for debugging if error
197
+ print(f"FFmpeg error: {error_output}")
198
  return False
199
 
200
  return True
 
207
  """Get optimal FFmpeg parameters for conversion"""
208
  params = []
209
 
210
+ params.extend(['-hide_banner', '-y', '-loglevel', 'error']) # Minimize output
211
  params.extend(['-i', input_file])
212
 
213
  ext = os.path.splitext(output_file)[1].lower()[1:]
 
233
  elif ext == 'wav':
234
  params.extend(['-codec:a', 'pcm_s16le'])
235
 
 
236
  if ff_format != ext:
237
  params.extend(['-f', ff_format])
238
 
 
292
  else:
293
  params.extend(['-codec:a', 'copy'])
294
 
 
295
  if ff_format != ext:
296
  params.extend(['-f', ff_format])
297
 
 
303
  def convert_audio_ffmpeg(input_file, output_file, output_ext):
304
  """Fast audio conversion via direct FFmpeg call"""
305
  if not os.path.exists(input_file):
 
306
  return False
307
 
308
  output_dir = os.path.dirname(output_file)
 
317
  conv_type = "video_to_audio" if conversion_type == "Video to Audio" else "video"
318
 
319
  if not os.path.exists(input_file):
 
320
  return False
321
 
322
  output_dir = os.path.dirname(output_file)
 
324
  os.makedirs(output_dir, exist_ok=True)
325
 
326
  params = get_optimal_ffmpeg_params(input_file, output_file, conv_type)
 
 
327
  return run_ffmpeg_with_progress(params)
328
 
329
  def merge_audio_files_ffmpeg(input_files, output_file, gap_duration):
 
336
  f.write(f"file '{os.path.abspath(file)}'\n")
337
 
338
  params = [
339
+ '-hide_banner',
340
+ '-loglevel', 'error',
341
  '-f', 'concat',
342
  '-safe', '0',
343
  '-i', list_file,
 
368
  img.save(output_path, format=pil_format)
369
 
370
  return True
371
+ except Exception:
 
372
  return False
373
 
374
  def process_file_parallel(args):
 
383
  else:
384
  success = False
385
  return output_path if success else None
386
+ except Exception:
 
387
  return None
388
 
389
  def create_zip(files_to_zip, session_id):
 
402
 
403
  session_id = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"
404
  os.makedirs(session_id, exist_ok=True)
405
+
406
  print(f"\nStarting audio session: {session_id}")
407
  print(f"Files to convert: {len(files)} to .{output_ext}")
 
408
 
409
  file_paths = [f if isinstance(f, str) else f.name for f in files]
410
 
 
463
 
464
  session_id = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"
465
  os.makedirs(session_id, exist_ok=True)
466
+
467
  print(f"\nStarting image session: {session_id}")
468
  print(f"Files to convert: {len(files)} to .{output_ext}")
 
469
 
470
  file_paths = [f if isinstance(f, str) else f.name for f in files]
471
  output_files = []
 
504
  input_path = input_video if isinstance(input_video, str) else input_video.name
505
  base_name = os.path.splitext(os.path.basename(input_path))[0]
506
  output_path = os.path.join(session_id, f"{base_name}.{output_ext}")
507
+
508
  print(f"\nStarting video session: {session_id}")
509
  print(f"Conversion type: {conversion_type}, Output: .{output_ext}")
510
 
511
+ progress(0.5, "Processing...")
512
  success = convert_video_ffmpeg(input_path, output_path, conversion_type)
513
 
514
  if success:
 
515
  return output_path
516
  else:
517
  raise gr.Error("Video processing failed. Please check the file format and try again.")
 
534
 
535
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
536
  gr.HTML(i18n("title_app"))
 
 
 
 
 
 
 
537
 
538
  with gr.Tabs():
539
  # AUDIO TAB
 
620
  )
621
 
622
  if __name__ == "__main__":
 
623
  demo.queue().launch(i18n=i18n, debug=True, show_error=True)