Spaces:
Paused
Paused
Update app.py
Browse files
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 |
|
|
@@ -20,6 +20,16 @@ os.makedirs(UPLOAD_DIR, exist_ok=True)
|
|
| 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,20 +53,21 @@ def make_ffmpeg_executable(ffmpeg_path: str):
|
|
| 43 |
logger.error(f"Error al configurar permisos de FFmpeg: {e}")
|
| 44 |
raise
|
| 45 |
|
| 46 |
-
def convert_media(input_file: str, output_dir: 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.{
|
| 53 |
)
|
| 54 |
output_file = os.path.join(output_dir, output_filename)
|
| 55 |
|
| 56 |
-
|
| 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,
|
|
@@ -71,21 +82,19 @@ def convert_media(input_file: str, output_dir: str, output_format: str = 'mp4')
|
|
| 71 |
'-movflags', '+faststart', # Web optimization
|
| 72 |
output_file
|
| 73 |
]
|
| 74 |
-
elif
|
| 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
|
| 81 |
-
-
|
| 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(
|
| 89 |
|
| 90 |
# Ejecutar conversi贸n
|
| 91 |
result = subprocess.run(
|
|
@@ -104,17 +113,17 @@ def convert_media(input_file: str, output_dir: str, output_format: str = 'mp4')
|
|
| 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
|
| 108 |
"""Procesar medio completo."""
|
| 109 |
-
return convert_media(file_path, UPLOAD_DIR
|
| 110 |
|
| 111 |
-
def gradio_interface(media: 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
|
| 118 |
return converted_media
|
| 119 |
except Exception as e:
|
| 120 |
raise gr.Error(f"Conversi贸n fallida: {str(e)}")
|
|
@@ -128,24 +137,17 @@ app = FastAPI()
|
|
| 128 |
# Configurar interfaz de Gradio
|
| 129 |
iface = gr.Interface(
|
| 130 |
fn=gradio_interface,
|
| 131 |
-
inputs=
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
),
|
| 136 |
-
gr.Dropdown(
|
| 137 |
-
label="Formato de Salida",
|
| 138 |
-
choices=['mp4', 'mp3', 'wav', 'avi', 'mkv', 'flac'],
|
| 139 |
-
value='mp4'
|
| 140 |
-
)
|
| 141 |
-
],
|
| 142 |
outputs=gr.File(
|
| 143 |
label="Descargar Archivo Convertido",
|
| 144 |
-
type="filepath"
|
| 145 |
),
|
| 146 |
-
title="馃帴馃幍 Convertidor Universal
|
| 147 |
-
description="Convierte videos y audios a
|
| 148 |
-
theme="huggingface"
|
| 149 |
)
|
| 150 |
|
| 151 |
# Lanzar interfaz de Gradio
|
|
|
|
| 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 |
|
|
|
|
| 20 |
VIDEO_FORMATS = ['.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv', '.wmv']
|
| 21 |
AUDIO_FORMATS = ['.mp3', '.wav', '.aac', '.flac', '.ogg', '.m4a', '.wma']
|
| 22 |
|
| 23 |
+
def detect_media_type(file_path: str) -> str:
|
| 24 |
+
"""Detectar si el archivo es de audio o video."""
|
| 25 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 26 |
+
if ext in VIDEO_FORMATS:
|
| 27 |
+
return 'video'
|
| 28 |
+
elif ext in AUDIO_FORMATS:
|
| 29 |
+
return 'audio'
|
| 30 |
+
else:
|
| 31 |
+
return 'unsupported'
|
| 32 |
+
|
| 33 |
def sanitize_filename(filename: str) -> str:
|
| 34 |
"""Limpiar y validar nombre de archivo para prevenir riesgos de seguridad."""
|
| 35 |
return ''.join(c for c in filename if c.isalnum() or c in ('.', '_', '-')).rstrip()
|
|
|
|
| 53 |
logger.error(f"Error al configurar permisos de FFmpeg: {e}")
|
| 54 |
raise
|
| 55 |
|
| 56 |
+
def convert_media(input_file: str, output_dir: str) -> str:
|
| 57 |
"""Convertir archivos multimedia con configuraciones optimizadas."""
|
| 58 |
try:
|
| 59 |
+
media_type = detect_media_type(input_file)
|
| 60 |
base_name = os.path.basename(input_file)
|
| 61 |
+
|
| 62 |
+
# Elegir extensi贸n de salida seg煤n el tipo de medio
|
| 63 |
+
output_extension = 'mp4' if media_type == 'video' else 'm4a'
|
| 64 |
output_filename = ensure_unique_filename(
|
| 65 |
output_dir,
|
| 66 |
+
f"{os.path.splitext(base_name)[0]}_converted.{output_extension}"
|
| 67 |
)
|
| 68 |
output_file = os.path.join(output_dir, output_filename)
|
| 69 |
|
| 70 |
+
if media_type == 'video':
|
|
|
|
|
|
|
|
|
|
| 71 |
# Configuraciones de conversi贸n de video
|
| 72 |
ffmpeg_command = [
|
| 73 |
FFMPEG_PATH,
|
|
|
|
| 82 |
'-movflags', '+faststart', # Web optimization
|
| 83 |
output_file
|
| 84 |
]
|
| 85 |
+
elif media_type == 'audio':
|
| 86 |
# Configuraciones de conversi贸n de audio
|
| 87 |
ffmpeg_command = [
|
| 88 |
FFMPEG_PATH,
|
| 89 |
'-i', input_file,
|
| 90 |
'-vn', # Ignorar video
|
| 91 |
+
'-c:a', 'libfdk_aac', # Codificador AAC para M4A
|
| 92 |
+
'-b:a', '192k', # Calidad de audio alta
|
|
|
|
| 93 |
'-ar', '44100', # Frecuencia de muestreo
|
|
|
|
| 94 |
output_file
|
| 95 |
]
|
| 96 |
else:
|
| 97 |
+
raise ValueError("Formato no soportado")
|
| 98 |
|
| 99 |
# Ejecutar conversi贸n
|
| 100 |
result = subprocess.run(
|
|
|
|
| 113 |
logger.error(f"Error inesperado durante la conversi贸n: {e}")
|
| 114 |
raise HTTPException(status_code=500, detail="Error inesperado durante la conversi贸n")
|
| 115 |
|
| 116 |
+
def process_media(file_path: str) -> str:
|
| 117 |
"""Procesar medio completo."""
|
| 118 |
+
return convert_media(file_path, UPLOAD_DIR)
|
| 119 |
|
| 120 |
+
def gradio_interface(media: Optional[str]) -> Optional[str]:
|
| 121 |
"""Interfaz de Gradio para conversi贸n de medios."""
|
| 122 |
if not media:
|
| 123 |
raise gr.Error("No se ha subido ning煤n medio. Por favor, sube un archivo.")
|
| 124 |
|
| 125 |
try:
|
| 126 |
+
converted_media = process_media(media)
|
| 127 |
return converted_media
|
| 128 |
except Exception as e:
|
| 129 |
raise gr.Error(f"Conversi贸n fallida: {str(e)}")
|
|
|
|
| 137 |
# Configurar interfaz de Gradio
|
| 138 |
iface = gr.Interface(
|
| 139 |
fn=gradio_interface,
|
| 140 |
+
inputs=gr.File(
|
| 141 |
+
label="Subir Archivo",
|
| 142 |
+
type="filepath"
|
| 143 |
+
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
outputs=gr.File(
|
| 145 |
label="Descargar Archivo Convertido",
|
| 146 |
+
type="filepath"
|
| 147 |
),
|
| 148 |
+
title="馃帴馃幍 Convertidor Universal",
|
| 149 |
+
description="Convierte videos a MP4 y audios a M4A con configuraciones optimizadas",
|
| 150 |
+
theme="huggingface"
|
| 151 |
)
|
| 152 |
|
| 153 |
# Lanzar interfaz de Gradio
|