Spaces:
Sleeping
Sleeping
Delete app_main.py
Browse files- app_main.py +0 -171
app_main.py
DELETED
|
@@ -1,171 +0,0 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import os
|
| 3 |
-
import subprocess
|
| 4 |
-
import time
|
| 5 |
-
import logging
|
| 6 |
-
import psutil
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
|
| 9 |
-
# Configuración de logging
|
| 10 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 11 |
-
logger = logging.getLogger(__name__)
|
| 12 |
-
|
| 13 |
-
# Configuración de rutas
|
| 14 |
-
FFMPEG_PATH = os.path.join(os.getcwd(), "ffmpeg.exe")
|
| 15 |
-
UPLOADS_DIR = os.path.join(os.getcwd(), "uploads")
|
| 16 |
-
|
| 17 |
-
# Crear directorio de uploads si no existe
|
| 18 |
-
os.makedirs(UPLOADS_DIR, exist_ok=True)
|
| 19 |
-
|
| 20 |
-
# Formatos soportados
|
| 21 |
-
VIDEO_FORMATS = ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm', '.m4v']
|
| 22 |
-
AUDIO_FORMATS = ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a', '.wma']
|
| 23 |
-
SUPPORTED_FORMATS = VIDEO_FORMATS + AUDIO_FORMATS
|
| 24 |
-
|
| 25 |
-
# Presets de compresión
|
| 26 |
-
COMPRESSION_PRESETS = {
|
| 27 |
-
"Compresión Rápida": {
|
| 28 |
-
"video": "-c:v libx264 -preset ultrafast -crf 28",
|
| 29 |
-
"audio": "-c:a aac -b:a 128k"
|
| 30 |
-
},
|
| 31 |
-
"Compresión Media": {
|
| 32 |
-
"video": "-c:v libx264 -preset medium -crf 23",
|
| 33 |
-
"audio": "-c:a aac -b:a 128k"
|
| 34 |
-
},
|
| 35 |
-
"Compresión Alta": {
|
| 36 |
-
"video": "-c:v libx264 -preset slow -crf 20",
|
| 37 |
-
"audio": "-c:a aac -b:a 192k"
|
| 38 |
-
},
|
| 39 |
-
"Compresión Máxima": {
|
| 40 |
-
"video": "-c:v libx264 -preset veryslow -crf 18",
|
| 41 |
-
"audio": "-c:a aac -b:a 256k"
|
| 42 |
-
}
|
| 43 |
-
}
|
| 44 |
-
|
| 45 |
-
def compress_media(file_path, preset="Compresión Alta", progress=gr.Progress()):
|
| 46 |
-
"""Comprimir archivo de media usando FFmpeg"""
|
| 47 |
-
try:
|
| 48 |
-
if not os.path.exists(file_path):
|
| 49 |
-
return None, "Error: Archivo no encontrado"
|
| 50 |
-
|
| 51 |
-
file_ext = Path(file_path).suffix.lower()
|
| 52 |
-
if file_ext not in SUPPORTED_FORMATS:
|
| 53 |
-
return None, f"Error: Formato {file_ext} no soportado"
|
| 54 |
-
|
| 55 |
-
# Generar nombre de archivo de salida
|
| 56 |
-
base_name = Path(file_path).stem
|
| 57 |
-
output_path = os.path.join(UPLOADS_DIR, f"{base_name}_compressed{file_ext}")
|
| 58 |
-
|
| 59 |
-
# Obtener configuración del preset
|
| 60 |
-
preset_config = COMPRESSION_PRESETS.get(preset, COMPRESSION_PRESETS["Compresión Alta"])
|
| 61 |
-
|
| 62 |
-
# Construir comando FFmpeg
|
| 63 |
-
cmd = [
|
| 64 |
-
FFMPEG_PATH,
|
| 65 |
-
"-i", file_path,
|
| 66 |
-
"-y", # Sobrescribir archivo de salida
|
| 67 |
-
]
|
| 68 |
-
|
| 69 |
-
# Agregar configuración según el tipo de archivo
|
| 70 |
-
if file_ext in VIDEO_FORMATS:
|
| 71 |
-
cmd.extend(preset_config["video"].split())
|
| 72 |
-
cmd.extend(preset_config["audio"].split())
|
| 73 |
-
else: # Audio
|
| 74 |
-
cmd.extend(preset_config["audio"].split())
|
| 75 |
-
|
| 76 |
-
cmd.append(output_path)
|
| 77 |
-
|
| 78 |
-
logger.info(f"Ejecutando comando: {' '.join(cmd)}")
|
| 79 |
-
|
| 80 |
-
# Ejecutar FFmpeg
|
| 81 |
-
process = subprocess.Popen(
|
| 82 |
-
cmd,
|
| 83 |
-
stdout=subprocess.PIPE,
|
| 84 |
-
stderr=subprocess.PIPE,
|
| 85 |
-
text=True
|
| 86 |
-
)
|
| 87 |
-
|
| 88 |
-
# Simular progreso
|
| 89 |
-
for i in progress.tqdm(range(100), desc="Comprimiendo..."):
|
| 90 |
-
time.sleep(0.1)
|
| 91 |
-
if process.poll() is not None:
|
| 92 |
-
break
|
| 93 |
-
|
| 94 |
-
stdout, stderr = process.communicate()
|
| 95 |
-
|
| 96 |
-
if process.returncode != 0:
|
| 97 |
-
logger.error(f"Error en FFmpeg: {stderr}")
|
| 98 |
-
return None, f"Error durante compresión: {stderr[:200]}"
|
| 99 |
-
|
| 100 |
-
if not os.path.exists(output_path):
|
| 101 |
-
return None, "Error: No se pudo crear el archivo comprimido"
|
| 102 |
-
|
| 103 |
-
# Calcular ratio de compresión
|
| 104 |
-
original_size = os.path.getsize(file_path)
|
| 105 |
-
compressed_size = os.path.getsize(output_path)
|
| 106 |
-
compression_ratio = (1 - compressed_size / original_size) * 100
|
| 107 |
-
|
| 108 |
-
logger.info(f"Compresión completada. Ratio: {compression_ratio:.1f}%")
|
| 109 |
-
|
| 110 |
-
return output_path, f"Compresión exitosa! Reducción: {compression_ratio:.1f}%"
|
| 111 |
-
|
| 112 |
-
except Exception as e:
|
| 113 |
-
logger.error(f"Error en compress_media: {str(e)}")
|
| 114 |
-
return None, f"Error durante compresión: {str(e)}"
|
| 115 |
-
|
| 116 |
-
def run_app():
|
| 117 |
-
"""Ejecutar la aplicación Gradio"""
|
| 118 |
-
|
| 119 |
-
# Verificar que FFmpeg existe
|
| 120 |
-
if not os.path.exists(FFMPEG_PATH):
|
| 121 |
-
print(f"Error: FFmpeg no encontrado en {FFMPEG_PATH}")
|
| 122 |
-
return
|
| 123 |
-
|
| 124 |
-
with gr.Blocks(title="Compresor de Video y Audio", theme=gr.themes.Soft()) as iface:
|
| 125 |
-
gr.Markdown("# 🎬 Compresor de Video y Audio")
|
| 126 |
-
gr.Markdown("Comprime tus archivos de video y audio de forma eficiente")
|
| 127 |
-
|
| 128 |
-
with gr.Row():
|
| 129 |
-
with gr.Column():
|
| 130 |
-
file_input = gr.File(
|
| 131 |
-
label="Seleccionar archivo",
|
| 132 |
-
file_types=SUPPORTED_FORMATS
|
| 133 |
-
)
|
| 134 |
-
|
| 135 |
-
preset_dropdown = gr.Dropdown(
|
| 136 |
-
choices=list(COMPRESSION_PRESETS.keys()),
|
| 137 |
-
value="Compresión Alta",
|
| 138 |
-
label="Nivel de compresión"
|
| 139 |
-
)
|
| 140 |
-
|
| 141 |
-
compress_btn = gr.Button("🚀 Comprimir", variant="primary")
|
| 142 |
-
|
| 143 |
-
with gr.Column():
|
| 144 |
-
output_file = gr.File(label="Archivo comprimido")
|
| 145 |
-
status_text = gr.Textbox(label="Estado", interactive=False)
|
| 146 |
-
|
| 147 |
-
# Información sobre formatos soportados
|
| 148 |
-
gr.Markdown(
|
| 149 |
-
f"**Formatos soportados:**\n"
|
| 150 |
-
f"- Video: {', '.join(VIDEO_FORMATS)}\n"
|
| 151 |
-
f"- Audio: {', '.join(AUDIO_FORMATS)}"
|
| 152 |
-
)
|
| 153 |
-
|
| 154 |
-
# Evento de compresión
|
| 155 |
-
compress_btn.click(
|
| 156 |
-
fn=compress_media,
|
| 157 |
-
inputs=[file_input, preset_dropdown],
|
| 158 |
-
outputs=[output_file, status_text]
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
-
# Lanzar interfaz
|
| 162 |
-
iface.launch(
|
| 163 |
-
share=False,
|
| 164 |
-
server_name="127.0.0.1",
|
| 165 |
-
server_port=7862,
|
| 166 |
-
show_error=True,
|
| 167 |
-
inbrowser=True
|
| 168 |
-
)
|
| 169 |
-
|
| 170 |
-
if __name__ == "__main__":
|
| 171 |
-
run_app()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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