KaraokeVideoDownloader/setup_platform.py

288 lines
11 KiB
Python

#!/usr/bin/env python3
"""
Platform setup script for Karaoke Video Downloader.
This script helps users download the correct yt-dlp binary for their platform.
"""
import os
import platform
import sys
import urllib.request
import zipfile
import tarfile
from pathlib import Path
def detect_platform():
"""Detect the current platform and return platform info."""
system = platform.system().lower()
machine = platform.machine().lower()
if system == "windows":
return "windows", "yt-dlp.exe"
elif system == "darwin":
return "macos", "yt-dlp_macos"
elif system == "linux":
return "linux", "yt-dlp"
else:
return "unknown", "yt-dlp"
def get_download_url(platform_name):
"""Get the download URL for yt-dlp based on platform."""
base_url = "https://github.com/yt-dlp/yt-dlp/releases/latest/download"
if platform_name == "windows":
return f"{base_url}/yt-dlp.exe"
elif platform_name == "macos":
return f"{base_url}/yt-dlp_macos"
elif platform_name == "linux":
return f"{base_url}/yt-dlp"
else:
raise ValueError(f"Unsupported platform: {platform_name}")
def install_via_pip():
"""Install yt-dlp via pip."""
print("📦 Installing yt-dlp via pip...")
try:
import subprocess
result = subprocess.run([sys.executable, "-m", "pip", "install", "yt-dlp"],
capture_output=True, text=True, check=True)
print("✅ yt-dlp installed successfully via pip!")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Failed to install yt-dlp via pip: {e}")
return False
def check_ffmpeg():
"""Check if FFmpeg is installed and available."""
try:
import subprocess
result = subprocess.run(["ffmpeg", "-version"], capture_output=True, text=True, timeout=10)
return result.returncode == 0
except (subprocess.TimeoutExpired, FileNotFoundError):
return False
def install_ffmpeg():
"""Install FFmpeg based on platform."""
import subprocess
platform_name, _ = detect_platform()
print("🎬 Installing FFmpeg...")
if platform_name == "macos":
# Try using Homebrew first
try:
print("🍺 Attempting to install FFmpeg via Homebrew...")
result = subprocess.run(["brew", "install", "ffmpeg"],
capture_output=True, text=True, check=True)
print("✅ FFmpeg installed successfully via Homebrew!")
return True
except (subprocess.CalledProcessError, FileNotFoundError):
print("⚠️ Homebrew not found or failed. Trying alternative methods...")
# Try using MacPorts
try:
print("🍎 Attempting to install FFmpeg via MacPorts...")
result = subprocess.run(["sudo", "port", "install", "ffmpeg"],
capture_output=True, text=True, check=True)
print("✅ FFmpeg installed successfully via MacPorts!")
return True
except (subprocess.CalledProcessError, FileNotFoundError):
print("❌ Could not install FFmpeg automatically.")
print("Please install FFmpeg manually:")
print("1. Install Homebrew: https://brew.sh/")
print("2. Run: brew install ffmpeg")
print("3. Or download from: https://ffmpeg.org/download.html")
return False
elif platform_name == "linux":
try:
print("🐧 Attempting to install FFmpeg via package manager...")
# Try apt (Ubuntu/Debian)
try:
result = subprocess.run(["sudo", "apt", "update"], capture_output=True, text=True, check=True)
result = subprocess.run(["sudo", "apt", "install", "-y", "ffmpeg"],
capture_output=True, text=True, check=True)
print("✅ FFmpeg installed successfully via apt!")
return True
except subprocess.CalledProcessError:
# Try yum (CentOS/RHEL)
try:
result = subprocess.run(["sudo", "yum", "install", "-y", "ffmpeg"],
capture_output=True, text=True, check=True)
print("✅ FFmpeg installed successfully via yum!")
return True
except subprocess.CalledProcessError:
print("❌ Could not install FFmpeg automatically.")
print("Please install FFmpeg manually for your Linux distribution.")
return False
except FileNotFoundError:
print("❌ Could not install FFmpeg automatically.")
print("Please install FFmpeg manually for your Linux distribution.")
return False
elif platform_name == "windows":
print("❌ FFmpeg installation not automated for Windows.")
print("Please install FFmpeg manually:")
print("1. Download from: https://ffmpeg.org/download.html")
print("2. Extract to a folder and add to PATH")
print("3. Or use Chocolatey: choco install ffmpeg")
return False
return False
def download_file(url, destination):
"""Download a file from URL to destination."""
print(f"📥 Downloading from: {url}")
print(f"📁 Saving to: {destination}")
try:
urllib.request.urlretrieve(url, destination)
print("✅ Download completed successfully!")
return True
except Exception as e:
print(f"❌ Download failed: {e}")
return False
def make_executable(file_path):
"""Make a file executable (for Unix-like systems)."""
try:
os.chmod(file_path, 0o755)
print(f"🔧 Made {file_path} executable")
except Exception as e:
print(f"⚠️ Could not make file executable: {e}")
def main():
print("🎤 Karaoke Video Downloader - Platform Setup")
print("=" * 50)
# Detect platform
platform_name, binary_name = detect_platform()
print(f"🖥️ Detected platform: {platform_name}")
print(f"📦 Binary name: {binary_name}")
# Create downloader directory if it doesn't exist
downloader_dir = Path("downloader")
downloader_dir.mkdir(exist_ok=True)
# Check if binary already exists
binary_path = downloader_dir / binary_name
if binary_path.exists():
print(f"{binary_name} already exists in downloader/ directory")
response = input("Do you want to re-download it? (y/N): ").strip().lower()
if response != 'y':
print("Setup completed!")
return
# Offer installation options
print(f"\n🔧 Installation options for {platform_name}:")
print("1. Download binary file (recommended for most users)")
print("2. Install via pip (alternative method)")
choice = input("Choose installation method (1 or 2): ").strip()
if choice == "2":
# Install via pip
if install_via_pip():
print(f"\n✅ yt-dlp installed successfully!")
# Test the installation
print(f"\n🧪 Testing yt-dlp installation...")
try:
import subprocess
result = subprocess.run([sys.executable, "-m", "yt_dlp", "--version"],
capture_output=True, text=True, timeout=10)
if result.returncode == 0:
version = result.stdout.strip()
print(f"✅ yt-dlp is working! Version: {version}")
else:
print(f"⚠️ yt-dlp test failed: {result.stderr}")
except Exception as e:
print(f"⚠️ Could not test yt-dlp: {e}")
# Check and install FFmpeg
print(f"\n🎬 Checking FFmpeg installation...")
if check_ffmpeg():
print(f"✅ FFmpeg is already installed and working!")
else:
print(f"⚠️ FFmpeg not found. Installing...")
if install_ffmpeg():
print(f"✅ FFmpeg installed successfully!")
else:
print(f"⚠️ FFmpeg installation failed. The tool will still work but may be slower.")
print(f"\n🎉 Setup completed successfully!")
print(f"📦 yt-dlp installed via pip")
print(f"🖥️ Platform: {platform_name}")
print(f"\n🎉 You're ready to use the Karaoke Video Downloader!")
print(f"Run: python download_karaoke.py --help")
return
else:
print("❌ Pip installation failed. Trying binary download...")
# Download binary file
try:
download_url = get_download_url(platform_name)
except ValueError as e:
print(f"{e}")
print("Please manually download yt-dlp for your platform from:")
print("https://github.com/yt-dlp/yt-dlp/releases/latest")
return
# Download the binary
print(f"\n🚀 Downloading yt-dlp for {platform_name}...")
if download_file(download_url, binary_path):
# Make executable on Unix-like systems
if platform_name in ["macos", "linux"]:
make_executable(binary_path)
print(f"\n✅ yt-dlp binary downloaded successfully!")
print(f"📁 yt-dlp binary location: {binary_path}")
print(f"🖥️ Platform: {platform_name}")
# Test the binary
print(f"\n🧪 Testing yt-dlp installation...")
try:
import subprocess
result = subprocess.run([str(binary_path), "--version"],
capture_output=True, text=True, timeout=10)
if result.returncode == 0:
version = result.stdout.strip()
print(f"✅ yt-dlp is working! Version: {version}")
else:
print(f"⚠️ yt-dlp test failed: {result.stderr}")
except Exception as e:
print(f"⚠️ Could not test yt-dlp: {e}")
# Check and install FFmpeg
print(f"\n🎬 Checking FFmpeg installation...")
if check_ffmpeg():
print(f"✅ FFmpeg is already installed and working!")
else:
print(f"⚠️ FFmpeg not found. Installing...")
if install_ffmpeg():
print(f"✅ FFmpeg installed successfully!")
else:
print(f"⚠️ FFmpeg installation failed. The tool will still work but may be slower.")
print(f"\n🎉 Setup completed successfully!")
print(f"📁 yt-dlp binary location: {binary_path}")
print(f"🖥️ Platform: {platform_name}")
print(f"\n🎉 You're ready to use the Karaoke Video Downloader!")
print(f"Run: python download_karaoke.py --help")
else:
print(f"\n❌ Setup failed. Please manually download yt-dlp for {platform_name}")
print(f"Download URL: {download_url}")
print(f"Save to: {binary_path}")
if __name__ == "__main__":
main()