asdas1241 commited on
Commit
7ade725
verified
1 Parent(s): 6f39470

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -37
app.py CHANGED
@@ -1,7 +1,7 @@
1
  import os
2
  import subprocess
3
  import logging
4
- from typing import Optional
5
  from fastapi import FastAPI, HTTPException
6
  import gradio as gr
7
 
@@ -16,6 +16,10 @@ FFMPEG_PATH = "./ffmpeg"
16
  # Crear directorios
17
  os.makedirs(UPLOAD_DIR, exist_ok=True)
18
 
 
 
 
 
19
  def sanitize_filename(filename: str) -> str:
20
  """Limpiar y validar nombre de archivo para prevenir riesgos de seguridad."""
21
  return ''.join(c for c in filename if c.isalnum() or c in ('.', '_', '-')).rstrip()
@@ -39,30 +43,49 @@ def make_ffmpeg_executable(ffmpeg_path: str):
39
  logger.error(f"Error al configurar permisos de FFmpeg: {e}")
40
  raise
41
 
42
- def convert_video_to_mp4(input_file: str, output_dir: str) -> str:
43
- """Convertir video a formato MP4 con configuraciones optimizadas."""
44
  try:
45
- # Generar nombre de archivo 煤nico
46
  output_filename = ensure_unique_filename(
47
  output_dir,
48
- os.path.basename(input_file).rsplit('.', 1)[0] + "_converted.mp4"
49
  )
50
  output_file = os.path.join(output_dir, output_filename)
51
 
52
- # Comando FFmpeg con configuraciones optimizadas
53
- ffmpeg_command = [
54
- FFMPEG_PATH,
55
- '-i', input_file,
56
- '-vf', 'fps=24', # Cambiar la tasa de fotogramas
57
- '-c:v', 'libx264', # Codificador de video
58
- '-c:a', 'libfdk_aac', # Codificador de audio
59
- '-profile:a', 'aac_he_v2', # Perfil de audio
60
- '-crf', '28', # Tasa de compresi贸n
61
- '-b:a', '32k', # Tasa de bits de audio
62
- '-preset', 'slow', # Preajuste de codificaci贸n
63
- '-movflags', '+faststart', # Web optimization
64
- output_file
65
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  # Ejecutar conversi贸n
68
  result = subprocess.run(
@@ -71,28 +94,28 @@ def convert_video_to_mp4(input_file: str, output_dir: str) -> str:
71
  capture_output=True,
72
  text=True
73
  )
74
- logger.info(f"Video convertido exitosamente: {output_file}")
75
  return output_file
76
 
77
  except subprocess.CalledProcessError as e:
78
  logger.error(f"Error de conversi贸n de FFmpeg: {e.stderr}")
79
- raise HTTPException(status_code=500, detail=f"Fallo en la conversi贸n de video: {e.stderr}")
80
  except Exception as e:
81
  logger.error(f"Error inesperado durante la conversi贸n: {e}")
82
- raise HTTPException(status_code=500, detail="Error inesperado durante la conversi贸n de video")
83
 
84
- def process_video(file_path: str) -> str:
85
- """Procesar el video completo."""
86
- return convert_video_to_mp4(file_path, UPLOAD_DIR)
87
 
88
- def gradio_interface(video: Optional[str]) -> Optional[str]:
89
- """Interfaz de Gradio para conversi贸n de video."""
90
- if not video:
91
- raise gr.Error("No se ha subido ning煤n video. Por favor, sube un video.")
92
 
93
  try:
94
- converted_video = process_video(video)
95
- return converted_video
96
  except Exception as e:
97
  raise gr.Error(f"Conversi贸n fallida: {str(e)}")
98
 
@@ -102,14 +125,29 @@ make_ffmpeg_executable(FFMPEG_PATH)
102
  # Crear aplicaci贸n FastAPI
103
  app = FastAPI()
104
 
105
- # Modificaci贸n de la interfaz de Gradio
106
  iface = gr.Interface(
107
  fn=gradio_interface,
108
- inputs=gr.Video(label="Subir Video"), # Eliminar los argumentos 'type' y 'sources'
109
- outputs=gr.File(label="Descargar MP4 Convertido"),
110
- title="馃帴 Convertidor de Video",
111
- description="Convierte videos a formato MP4 optimizado con configuraciones est谩ndar",
112
- theme="huggingface"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  )
114
 
115
  # Lanzar interfaz de Gradio
 
1
  import os
2
  import subprocess
3
  import logging
4
+ from typing import Optional, List
5
  from fastapi import FastAPI, HTTPException
6
  import gradio as gr
7
 
 
16
  # Crear directorios
17
  os.makedirs(UPLOAD_DIR, exist_ok=True)
18
 
19
+ # Definir formatos de video y audio soportados
20
+ VIDEO_FORMATS = ['.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv', '.wmv']
21
+ AUDIO_FORMATS = ['.mp3', '.wav', '.aac', '.flac', '.ogg', '.m4a', '.wma']
22
+
23
  def sanitize_filename(filename: str) -> str:
24
  """Limpiar y validar nombre de archivo para prevenir riesgos de seguridad."""
25
  return ''.join(c for c in filename if c.isalnum() or c in ('.', '_', '-')).rstrip()
 
43
  logger.error(f"Error al configurar permisos de FFmpeg: {e}")
44
  raise
45
 
46
+ def convert_media(input_file: str, output_dir: str, output_format: str = 'mp4') -> str:
47
+ """Convertir archivos multimedia con configuraciones optimizadas."""
48
  try:
49
+ base_name = os.path.basename(input_file)
50
  output_filename = ensure_unique_filename(
51
  output_dir,
52
+ f"{os.path.splitext(base_name)[0]}_converted.{output_format}"
53
  )
54
  output_file = os.path.join(output_dir, output_filename)
55
 
56
+ # Determinar comandos seg煤n sea video o audio
57
+ input_extension = os.path.splitext(input_file)[1].lower()
58
+
59
+ if input_extension in VIDEO_FORMATS:
60
+ # Configuraciones de conversi贸n de video
61
+ ffmpeg_command = [
62
+ FFMPEG_PATH,
63
+ '-i', input_file,
64
+ '-vf', 'fps=24', # Cambiar la tasa de fotogramas
65
+ '-c:v', 'libx264', # Codificador de video
66
+ '-c:a', 'libfdk_aac', # Codificador de audio
67
+ '-profile:a', 'aac_he_v2', # Perfil de audio
68
+ '-crf', '28', # Tasa de compresi贸n
69
+ '-b:a', '28k', # Tasa de bits de audio
70
+ '-preset', 'slow', # Preajuste de codificaci贸n
71
+ '-movflags', '+faststart', # Web optimization
72
+ output_file
73
+ ]
74
+ elif input_extension in AUDIO_FORMATS:
75
+ # Configuraciones de conversi贸n de audio
76
+ ffmpeg_command = [
77
+ FFMPEG_PATH,
78
+ '-i', input_file,
79
+ '-vn', # Ignorar video
80
+ '-c:a', 'libfdk_aac', # Codificador seg煤n formato
81
+ -'profile:a', 'aac_he_v2',
82
+ '-b:a', '48k', # Calidad de audio alta
83
+ '-ar', '44100', # Frecuencia de muestreo
84
+ '-preset', 'slow',
85
+ output_file
86
+ ]
87
+ else:
88
+ raise ValueError(f"Formato no soportado: {input_extension}")
89
 
90
  # Ejecutar conversi贸n
91
  result = subprocess.run(
 
94
  capture_output=True,
95
  text=True
96
  )
97
+ logger.info(f"Medio convertido exitosamente: {output_file}")
98
  return output_file
99
 
100
  except subprocess.CalledProcessError as e:
101
  logger.error(f"Error de conversi贸n de FFmpeg: {e.stderr}")
102
+ raise HTTPException(status_code=500, detail=f"Fallo en la conversi贸n de medio: {e.stderr}")
103
  except Exception as e:
104
  logger.error(f"Error inesperado durante la conversi贸n: {e}")
105
+ raise HTTPException(status_code=500, detail="Error inesperado durante la conversi贸n")
106
 
107
+ def process_media(file_path: str, output_format: str = 'mp4') -> str:
108
+ """Procesar medio completo."""
109
+ return convert_media(file_path, UPLOAD_DIR, output_format)
110
 
111
+ def gradio_interface(media: Optional[str], output_format: str) -> Optional[str]:
112
+ """Interfaz de Gradio para conversi贸n de medios."""
113
+ if not media:
114
+ raise gr.Error("No se ha subido ning煤n medio. Por favor, sube un archivo.")
115
 
116
  try:
117
+ converted_media = process_media(media, output_format)
118
+ return converted_media
119
  except Exception as e:
120
  raise gr.Error(f"Conversi贸n fallida: {str(e)}")
121
 
 
125
  # Crear aplicaci贸n FastAPI
126
  app = FastAPI()
127
 
128
+ # Configurar interfaz de Gradio
129
  iface = gr.Interface(
130
  fn=gradio_interface,
131
+ inputs=[
132
+ gr.File(
133
+ label="Subir Archivo",
134
+ type="filepath",
135
+ file_count="single",
136
+ file_types=VIDEO_FORMATS + AUDIO_FORMATS
137
+ ),
138
+ gr.Dropdown(
139
+ label="Formato de Salida",
140
+ choices=['ts', 'mp4', 'mp3', 'wav', 'avi', 'mkv', 'flac'],
141
+ value='mp4'
142
+ )
143
+ ],
144
+ outputs=gr.File(
145
+ label="Descargar Archivo Convertido",
146
+ type="file"
147
+ ),
148
+ title="馃帴馃幍 Convertidor Universal de Medios",
149
+ description="Convierte videos y audios a m煤ltiples formatos con configuraciones optimizadas",
150
+ theme="huggingface" # Tema de HuggingFace
151
  )
152
 
153
  # Lanzar interfaz de Gradio