|
| 1 | +""" |
| 2 | +YouTube Video Downloader (Robust Version) |
| 3 | +- Download video or audio using pytube |
| 4 | +- Handles common YouTube errors and retry mechanism |
| 5 | +""" |
| 6 | + |
| 7 | +import os |
| 8 | +import time |
| 9 | + |
| 10 | +try: |
| 11 | + from pytube import YouTube |
| 12 | +except ImportError: |
| 13 | + print("pytube not installed. Install it with 'pip install pytube'") |
| 14 | + exit() |
| 15 | + |
| 16 | +# Downloads folder in current directory |
| 17 | +DOWNLOAD_FOLDER = os.path.join(os.getcwd(), "downloads") |
| 18 | +os.makedirs(DOWNLOAD_FOLDER, exist_ok=True) |
| 19 | + |
| 20 | +def fetch_video(url, retries=3): |
| 21 | + """ |
| 22 | + Fetch YouTube object with retry mechanism |
| 23 | + """ |
| 24 | + for attempt in range(retries): |
| 25 | + try: |
| 26 | + yt = YouTube(url) |
| 27 | + return yt |
| 28 | + except Exception as e: |
| 29 | + print(f"⚠️ Attempt {attempt+1} failed: {e}") |
| 30 | + time.sleep(1) |
| 31 | + print("❌ Failed to fetch video info. Check URL or update pytube.") |
| 32 | + return None |
| 33 | + |
| 34 | +def download_video(url): |
| 35 | + yt = fetch_video(url) |
| 36 | + if not yt: |
| 37 | + return |
| 38 | + print(f"\n🎥 Video Title: {yt.title}") |
| 39 | + choice = input("Download as (v)ideo or (a)udio? [v/a]: ").strip().lower() |
| 40 | + |
| 41 | + if choice == "v": |
| 42 | + try: |
| 43 | + stream = yt.streams.get_highest_resolution() |
| 44 | + print(f"Downloading video to {DOWNLOAD_FOLDER} ...") |
| 45 | + stream.download(DOWNLOAD_FOLDER) |
| 46 | + print("✅ Video downloaded successfully!") |
| 47 | + except Exception as e: |
| 48 | + print("❌ Download failed:", e) |
| 49 | + elif choice == "a": |
| 50 | + try: |
| 51 | + stream = yt.streams.filter(only_audio=True).first() |
| 52 | + out_file = stream.download(DOWNLOAD_FOLDER) |
| 53 | + base, ext = os.path.splitext(out_file) |
| 54 | + new_file = base + ".mp3" |
| 55 | + os.rename(out_file, new_file) |
| 56 | + print(f"✅ Audio downloaded successfully as {new_file}") |
| 57 | + except Exception as e: |
| 58 | + print("❌ Audio download failed:", e) |
| 59 | + else: |
| 60 | + print("Invalid choice. Cancelled.") |
| 61 | + |
| 62 | +def main(): |
| 63 | + print("\n📥 YouTube Video Downloader") |
| 64 | + while True: |
| 65 | + print("\nMenu:") |
| 66 | + print("1️⃣ Download YouTube Video/Audio") |
| 67 | + print("2️⃣ Exit") |
| 68 | + choice = input("Choose an option (1-2): ").strip() |
| 69 | + if choice == "1": |
| 70 | + url = input("Enter YouTube video URL: ").strip() |
| 71 | + if url: |
| 72 | + download_video(url) |
| 73 | + else: |
| 74 | + print("URL cannot be empty.") |
| 75 | + elif choice == "2": |
| 76 | + print("Goodbye! 🎬") |
| 77 | + break |
| 78 | + else: |
| 79 | + print("Invalid option. Try again.") |
| 80 | + |
| 81 | +if __name__ == "__main__": |
| 82 | + main() |
0 commit comments