Spaces:
Running on Zero
Running on Zero
Download main.py from codebydante/twisted_audio: direct link, hf CLI and curl.
- Browser
- Download file 8.74 kB
-
https://huggingface.co/spaces/codebydante/twisted_audio/resolve/main/main.py
- Command line
-
hf download hf://spaces/codebydante/twisted_audio/main.py
-
curl -L -o main.py https://huggingface.co/spaces/codebydante/twisted_audio/resolve/main/main.py
8.74 kB
| import asyncio | |
| import os | |
| import sys | |
| import time | |
| import logging | |
| import subprocess | |
| from aiohttp import web | |
| from pyrogram import Client, filters, idle | |
| from pyrogram.types import ( | |
| InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery, Message | |
| ) | |
| from pyrogram.errors import MessageNotModified | |
| # Configuraciones y DB | |
| from config import API_ID, API_HASH, BOT_TOKEN, DOWNLOAD_DIR | |
| from database import get_config | |
| from firebase_service import save_user_config_fb | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| # --- WEB SERVER (Página Fantasma - Minimalista) --- | |
| async def handle_health(request): | |
| html = """ | |
| <!DOCTYPE html> | |
| <html lang="es"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>MP3 Extractor | Stealth</title> | |
| <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;900&display=swap" rel="stylesheet"> | |
| <style> | |
| body { margin: 0; padding: 0; background: #000; color: #fff; font-family: 'Outfit', sans-serif; height: 100vh; display: flex; align-items: center; justify-content: center; overflow: hidden; } | |
| .glow { position: absolute; width: 400px; height: 400px; background: radial-gradient(circle, rgba(255,255,255,0.05) 0%, transparent 70%); animation: pulse 4s infinite alternate; } | |
| @keyframes pulse { from { transform: scale(1); opacity: 0.3; } to { transform: scale(1.5); opacity: 0.1; } } | |
| .content { text-align: center; z-index: 10; cursor: pointer; } | |
| h1 { font-size: 3rem; font-weight: 900; letter-spacing: -0.05em; margin-bottom: 0.5rem; } | |
| p { font-size: 0.9rem; letter-spacing: 0.4em; text-transform: uppercase; opacity: 0.4; } | |
| </style> | |
| </head> | |
| <body onclick="location.href='https://t.me/SmartVideoSplitterBot'"> | |
| <div class="glow"></div> | |
| <div class="content"> | |
| <h1>MP3 EXTRACTOR</h1> | |
| <p>System Status: Active</p> | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| return web.Response(text=html, content_type='text/html') | |
| async def start_web_server(): | |
| try: | |
| app_web = web.Application() | |
| app_web.router.add_get('/', handle_health) | |
| runner = web.AppRunner(app_web) | |
| await runner.setup() | |
| port = int(os.environ.get("WEB_PORT", 8080)) | |
| site = web.TCPSite(runner, '0.0.0.0', port) | |
| await site.start() | |
| logger.info(f"Web server running on port {port}") | |
| except Exception as e: | |
| logger.warning(f"Web server exception ignored: {e}") | |
| # --- PYROGRAM CLIENT --- | |
| WORKDIR = "sessions" | |
| if not os.path.exists(WORKDIR): os.makedirs(WORKDIR) | |
| # WORKDIR = "sessions" | |
| app = Client("brody_base_bot_v2", api_id=int(API_ID), api_hash=API_HASH, bot_token=BOT_TOKEN, workers=100, in_memory=True) | |
| # --- LÓGICA DE EXTRACCIÓN MP3 --- | |
| SEM_EXTRACT = asyncio.Semaphore(1) # Máximo 1 proceso FFmpeg (Mejor estabilidad en CPU limitada) | |
| USER_PROCESSING_LOCKS = {} | |
| async def extract_audio_task(client, message, msg_status): | |
| chat_id = message.chat.id | |
| if chat_id not in USER_PROCESSING_LOCKS: | |
| USER_PROCESSING_LOCKS[chat_id] = asyncio.Lock() | |
| async with USER_PROCESSING_LOCKS[chat_id]: | |
| async with SEM_EXTRACT: | |
| try: | |
| await msg_status.edit("⬇️ **Descargando...**") | |
| from tools_media import fast_download, get_meta, get_thumb | |
| job_dir = os.path.join(DOWNLOAD_DIR, f"mp3_{chat_id}_{int(time.time())}") | |
| os.makedirs(job_dir, exist_ok=True) | |
| media = message.document or message.video | |
| orig_name = getattr(media, "file_name", None) | |
| if not orig_name: | |
| orig_name = f"vid_{int(time.time())}.mp4" | |
| logger.info(f"[DEBUG] Media details: type={type(media)}, file_name={getattr(media, 'file_name', None)}") | |
| logger.info(f"[DEBUG] Resolved orig_name: {orig_name}") | |
| logger.info(f"[DEBUG] job_dir: {job_dir}") | |
| input_path = os.path.join(job_dir, orig_name) | |
| path = await fast_download(client, message, input_path, msg_status, "Descargando") | |
| if not path: | |
| await msg_status.edit("❌ Error al descargar."); return | |
| # Mejorado: Detectar info y extraer carátula | |
| await msg_status.edit("🔍 **Analizando...**") | |
| w, h, dur = await get_meta(path) | |
| thumb_path = await get_thumb(path, chat_id, int(time.time()), duration=dur) | |
| output_mp3 = os.path.join(job_dir, os.path.splitext(orig_name)[0] + ".mp3") | |
| await msg_status.edit("⚡ **Extrayendo Audio (Turbo)...**") | |
| # Comando optimizado | |
| cmd = [ | |
| "ffmpeg", "-i", path, "-vn", | |
| "-acodec", "libmp3lame", "-q:a", "2", | |
| "-map_metadata", "0", | |
| "-threads", "0", | |
| "-y", output_mp3 | |
| ] | |
| proc = await asyncio.create_subprocess_exec( | |
| *cmd, | |
| stdout=asyncio.subprocess.PIPE, | |
| stderr=asyncio.subprocess.PIPE | |
| ) | |
| stdout, stderr = await proc.communicate() | |
| if not os.path.exists(output_mp3) or os.path.getsize(output_mp3) < 1000: | |
| err_msg = stderr.decode()[-200:] if stderr else "Error desconocido" | |
| logger.error(f"FFmpeg Error: {err_msg}") | |
| await msg_status.edit(f"❌ Fallo en la extracción.\n`{err_msg}`") | |
| return | |
| # Enviar con CARÁTULA y METADATOS | |
| await msg_status.edit("📤 **Enviando MP3 Premium...**") | |
| from tools_media import progreso | |
| await client.send_audio( | |
| chat_id, output_mp3, | |
| thumb=thumb_path, | |
| duration=dur, | |
| performer="Brody Extractor", | |
| title=os.path.splitext(orig_name)[0], | |
| caption=f"🎵 **Audio Extraído**\n🎬 `{orig_name}`", | |
| progress=progreso, progress_args=(msg_status, [time.time(), 0], "Subiendo") | |
| ) | |
| await msg_status.delete() | |
| # Limpieza | |
| if thumb_path and os.path.exists(thumb_path): os.remove(thumb_path) | |
| import shutil; shutil.rmtree(job_dir, ignore_errors=True) | |
| except Exception as e: | |
| await msg_status.edit(f"❌ Error: {e}") | |
| # --- MENÚS --- | |
| async def send_panel(client, chat_id, message_id=None): | |
| kb = InlineKeyboardMarkup([[InlineKeyboardButton("🎯 Sistema de Extracción Activo", callback_data="none")]]) | |
| txt = "🎧 **Extractor MP3 PRO**\n\nEnvía cualquier video o archivo y extraeré su audio al instante.\n\n✅ **Estado**: En línea y procesando." | |
| if message_id: await client.edit_message_text(chat_id, message_id, txt, reply_markup=kb) | |
| else: await client.send_message(chat_id, txt, reply_markup=kb) | |
| async def start_cmd(c, m): await send_panel(c, m.chat.id) | |
| async def media_handler(c, m): | |
| if m.document and not m.document.mime_type.startswith("video"): return | |
| msg_status = await m.reply("⏳ **En cola...** Esperando turno.") | |
| asyncio.create_task(extract_audio_task(c, m, msg_status)) | |
| async def help_cmd(c, m): | |
| await m.reply( | |
| "🎧 **Twisted Audio Help**\n\n" | |
| "Este bot extrae el audio de tus videos automáticamente.\n\n" | |
| "✅ **Cómo usar**: Solo envíame un video o un archivo de video.\n" | |
| "✅ **Calidad**: MP3 Premium con carátula y metadatos.\n" | |
| "✅ **Cola**: Si envías varios, los procesaré uno por uno en orden." | |
| ) | |
| async def main(): | |
| await start_web_server(); await app.start() | |
| try: | |
| from pyrogram.types import BotCommand | |
| await app.set_bot_commands([ | |
| BotCommand("start", "⚙️ Panel Principal"), | |
| BotCommand("help", "❓ Ayuda e Instrucciones") | |
| ]) | |
| except: pass | |
| await idle(); await app.stop() | |
| if __name__ == "__main__": app.run(main()) |