File size: 11,959 Bytes
2cb6a22 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | import os
import asyncio
import tempfile
import subprocess
import shutil
from pathlib import Path
from telegram import Update, Message
from telegram.ext import (
Application,
CommandHandler,
MessageHandler,
filters,
ContextTypes,
)
from telegram.constants import ParseMode
# โโโ Configuration โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
BOT_TOKEN = os.environ.get("BOT_TOKEN", "YOUR_BOT_TOKEN_HERE")
SUPPORTED_AUDIO_EXTENSIONS = {
".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac",
".wma", ".opus", ".aiff", ".aif", ".mp4", ".mkv",
".webm", ".mov", ".avi", ".flv", ".ts", ".mts",
}
MAX_FILE_SIZE_MB = 200 # Telegram Bot API limit for downloads via getFile
# โโโ Helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def human_size(num_bytes: int) -> str:
for unit in ("B", "KB", "MB", "GB"):
if abs(num_bytes) < 1024:
return f"{num_bytes:.1f} {unit}"
num_bytes /= 1024
return f"{num_bytes:.1f} TB"
async def edit_or_reply(msg: Message, text: str, **kwargs) -> Message:
"""Edit an existing status message or reply if not possible."""
try:
return await msg.edit_text(text, **kwargs)
except Exception:
return await msg.reply_text(text, **kwargs)
def run_demucs(input_path: str, output_dir: str) -> tuple[str, str]:
"""
Run Demucs (htdemucs model) on *input_path*.
Returns (vocals_path, no_vocals_path) as absolute paths.
Raises RuntimeError on failure.
"""
cmd = [
"python", "-m", "demucs",
"--two-stems", "vocals", # produces vocals + no_vocals (instruments)
"-n", "htdemucs", # best quality model
"--mp3", # output as mp3 to keep files small
"-o", output_dir,
input_path,
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(result.stderr[-2000:] or "Demucs failed with no output")
stem_dir = Path(output_dir) / "htdemucs" / Path(input_path).stem
vocals = stem_dir / "vocals.mp3"
no_vocals = stem_dir / "no_vocals.mp3"
if not vocals.exists() or not no_vocals.exists():
raise RuntimeError(
f"Expected output files not found in {stem_dir}.\n"
f"Directory contents: {list(stem_dir.iterdir()) if stem_dir.exists() else 'dir missing'}"
)
return str(vocals), str(no_vocals)
def extract_audio_from_video(video_path: str, out_wav: str) -> None:
"""Extract audio track from a video file using ffmpeg."""
cmd = [
"ffmpeg", "-y", "-i", video_path,
"-vn", "-ar", "44100", "-ac", "2",
"-c:a", "pcm_s16le", out_wav,
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"ffmpeg audio extraction failed:\n{result.stderr[-1500:]}")
VIDEO_EXTENSIONS = {".mp4", ".mkv", ".webm", ".mov", ".avi", ".flv", ".ts", ".mts"}
# โโโ Command Handlers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
text = (
"๐ต *ู
ุฑุญุจุงู ุจู ูู ุจูุช ูุตู ุงูุตูุช!*\n\n"
"ุฃุฑุณู ูู ุฃู ู
ูู ุตูุชู ุฃู ููุฏูู ูุณุฃูุตู:\n"
" ๐ค *ุตูุช ุงูุบูุงุก / ุงูููุงู
* โ `vocals.mp3`\n"
" ๐ธ *ุงูู
ูุณููู / ุงูู
ุตุงุญุจุฉ* โ `no_vocals.mp3`\n\n"
"๐ *ุงูุงู
ุชุฏุงุฏุงุช ุงูู
ุฏุนูู
ุฉ:*\n"
"`mp3, wav, flac, ogg, m4a, aac, wma, opus, aiff,\n"
"mp4, mkv, webm, mov, avi, flv, ts, mts`\n\n"
f"โ ๏ธ ุงูุญุฏ ุงูุฃูุตู ูุญุฌู
ุงูู
ูู: *{MAX_FILE_SIZE_MB} MB*\n\n"
"ุงุณุชุฎุฏู
/help ูู
ุฒูุฏ ู
ู ุงูู
ุนููู
ุงุช."
)
await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
text = (
"๐ *ููู ุฃุณุชุฎุฏู
ุงูุจูุชุ*\n\n"
"1๏ธโฃ ุฃุฑุณู ู
ููุงู ุตูุชูุงู ุฃู ู
ูุทุน ููุฏูู.\n"
"2๏ธโฃ ุงูุชุธุฑ ููููุงู (ุงููุตู ูุฃุฎุฐ 1โ5 ุฏูุงุฆู ุญุณุจ ุทูู ุงูู
ูุทุน).\n"
"3๏ธโฃ ุณุชุตูู ู
ููุงู:\n"
" โข `vocals.mp3` โ ุงูุบูุงุก / ุงูููุงู
ููุท\n"
" โข `no_vocals.mp3` โ ุงูู
ูุณููู / ุงูู
ุตุงุญุจุฉ ููุท\n\n"
"๐ง *ุงููู
ูุฐุฌ ุงูู
ุณุชุฎุฏู
:* htdemucs (Meta AI)\n"
"๐ *ู
ูุงุญุธุฉ:* ุฌูุฏุฉ ุงููุตู ุชุนุชู
ุฏ ุนูู ูุถูุญ ุงูุตูุช ุงูุฃุตูู."
)
await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN)
# โโโ Core Processing โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
async def process_media(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = update.message
# Determine which type of media we received
file_obj = None
original_filename = "audio"
is_video = False
if message.audio:
file_obj = message.audio
original_filename = message.audio.file_name or "audio.mp3"
elif message.voice:
file_obj = message.voice
original_filename = "voice.ogg"
elif message.video:
file_obj = message.video
original_filename = message.video.file_name or "video.mp4"
is_video = True
elif message.video_note:
file_obj = message.video_note
original_filename = "video_note.mp4"
is_video = True
elif message.document:
file_obj = message.document
original_filename = message.document.file_name or "file"
ext = Path(original_filename).suffix.lower()
if ext not in SUPPORTED_AUDIO_EXTENSIONS:
await message.reply_text(
f"โ ุงูุงู
ุชุฏุงุฏ *{ext}* ุบูุฑ ู
ุฏุนูู
.\n\n"
"ุงูุงู
ุชุฏุงุฏุงุช ุงูู
ุฏุนูู
ุฉ:\n"
"`mp3, wav, flac, ogg, m4a, aac, wma, opus, aiff,\n"
"mp4, mkv, webm, mov, avi, flv, ts, mts`",
parse_mode=ParseMode.MARKDOWN,
)
return
if ext in VIDEO_EXTENSIONS:
is_video = True
else:
await message.reply_text(
"โ ๏ธ ุฃุฑุณู ู
ููุงู ุตูุชูุงู ุฃู ููุฏูู ู
ู ูุถูู.\n"
"ุงุณุชุฎุฏู
/help ูู
ุนุฑูุฉ ุงูุงู
ุชุฏุงุฏุงุช ุงูู
ุฏุนูู
ุฉ."
)
return
# Size check
if file_obj.file_size and file_obj.file_size > MAX_FILE_SIZE_MB * 1024 * 1024:
await message.reply_text(
f"โ ุญุฌู
ุงูู
ูู ({human_size(file_obj.file_size)}) ูุชุฌุงูุฒ ุงูุญุฏ ุงูู
ุณู
ูุญ "
f"({MAX_FILE_SIZE_MB} MB)."
)
return
status_msg = await message.reply_text("โฌ๏ธ ุฌุงุฑู ุชุญู
ูู ุงูู
ููโฆ")
with tempfile.TemporaryDirectory() as tmpdir:
try:
# โโ Download โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
tg_file = await context.bot.get_file(file_obj.file_id)
suffix = Path(original_filename).suffix or ".mp3"
input_path = os.path.join(tmpdir, f"input{suffix}")
await tg_file.download_to_drive(input_path)
await edit_or_reply(
status_msg,
"โ
ุชู
ุงูุชุญู
ูู.\n"
"๐ฌ ุฌุงุฑู ุงุณุชุฎุฑุงุฌ ุงูุตูุชโฆ" if is_video else
"โ
ุชู
ุงูุชุญู
ูู.\n๐ ุฌุงุฑู ูุตู ุงูุตูุช (ูุฏ ูุณุชุบุฑู ุจุถุน ุฏูุงุฆู)โฆ",
)
# โโ Extract audio from video if needed โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if is_video:
wav_path = os.path.join(tmpdir, "extracted.wav")
await asyncio.get_event_loop().run_in_executor(
None, extract_audio_from_video, input_path, wav_path
)
input_path = wav_path
await edit_or_reply(
status_msg,
"โ
ุชู
ุงุณุชุฎุฑุงุฌ ุงูุตูุช.\n๐ ุฌุงุฑู ูุตู ุงูุตูุช (ูุฏ ูุณุชุบุฑู ุจุถุน ุฏูุงุฆู)โฆ",
)
# โโ Run Demucs โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
output_dir = os.path.join(tmpdir, "out")
os.makedirs(output_dir, exist_ok=True)
vocals_path, no_vocals_path = await asyncio.get_event_loop().run_in_executor(
None, run_demucs, input_path, output_dir
)
await edit_or_reply(status_msg, "โ
ุชู
ุงููุตู!\n๐ค ุฌุงุฑู ุฅุฑุณุงู ุงูู
ููุงุชโฆ")
# โโ Send results โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
base = Path(original_filename).stem
with open(vocals_path, "rb") as f:
await message.reply_audio(
audio=f,
filename=f"{base}_vocals.mp3",
title=f"{base} โ ุตูุช ุงูุบูุงุก ๐ค",
caption="๐ค *ุตูุช ุงูุบูุงุก / ุงูููุงู
*",
parse_mode=ParseMode.MARKDOWN,
)
with open(no_vocals_path, "rb") as f:
await message.reply_audio(
audio=f,
filename=f"{base}_instrumental.mp3",
title=f"{base} โ ุงูู
ูุณููู ๐ธ",
caption="๐ธ *ุงูู
ูุณููู / ุงูู
ุตุงุญุจุฉ*",
parse_mode=ParseMode.MARKDOWN,
)
await edit_or_reply(status_msg, "โ
ุชู
ุงูุฅุฑุณุงู ุจูุฌุงุญ! ุฃุฑุณู ู
ููุงู ุขุฎุฑ ู
ุชู ุดุฆุช.")
except RuntimeError as exc:
await edit_or_reply(
status_msg,
f"โ *ุญุฏุซ ุฎุทุฃ ุฃุซูุงุก ุงูู
ุนุงูุฌุฉ:*\n`{str(exc)[:800]}`",
parse_mode=ParseMode.MARKDOWN,
)
except Exception as exc:
await edit_or_reply(
status_msg,
f"โ *ุฎุทุฃ ุบูุฑ ู
ุชููุน:*\n`{str(exc)[:800]}`",
parse_mode=ParseMode.MARKDOWN,
)
# โโโ Entry Point โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def main() -> None:
if BOT_TOKEN == "YOUR_BOT_TOKEN_HERE":
raise SystemExit(
"โ ุถุน ุชููู ุงูุจูุช ูู ู
ุชุบูุฑ ุงูุจูุฆุฉ BOT_TOKEN ุฃู ุนุฏูู ุงูุณุทุฑ ุงูุฃูู ู
ู ุงูููุฏ."
)
app = Application.builder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("help", help_command))
media_filter = (
filters.AUDIO
| filters.VOICE
| filters.VIDEO
| filters.VIDEO_NOTE
| filters.Document.ALL
)
app.add_handler(MessageHandler(media_filter, process_media))
print("๐ค ุงูุจูุช ูุนู
ู ุงูุขูโฆ ุงุถุบุท Ctrl+C ููุฅููุงู.")
app.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()
|