|
| 1 | +import yt_dlp |
| 2 | +import os |
| 3 | + |
| 4 | +def get_default_dir(): |
| 5 | + return os.path.join(os.path.expanduser('~'), "Downloads") |
| 6 | + |
| 7 | +def download_media(url, save_to=None, resolution=None): |
| 8 | + if not save_to: |
| 9 | + save_to = get_default_dir() |
| 10 | + |
| 11 | + if not os.path.exists(save_to): |
| 12 | + os.mkdir(save_to) |
| 13 | + |
| 14 | + ydl_opts = { |
| 15 | + 'outtmpl': os.path.join(save_to, '%(title)s.%(ext)s'), # Output path and filename template |
| 16 | + } |
| 17 | + |
| 18 | + try: |
| 19 | + with yt_dlp.YoutubeDL(ydl_opts) as ydl: |
| 20 | + info_dict = ydl.extract_info(url, download=True) |
| 21 | + formats = info_dict.get('formats', []) |
| 22 | + |
| 23 | + selected_format = None |
| 24 | + |
| 25 | + for format_item in formats: |
| 26 | + if 'height' in format_item: |
| 27 | + if resolution and f'{resolution}p' in format_item.get('format_note', '').lower(): |
| 28 | + selected_format = format_item |
| 29 | + break |
| 30 | + elif not resolution: |
| 31 | + selected_format = format_item |
| 32 | + |
| 33 | + if selected_format: |
| 34 | + print(f"Selected Resolution: {selected_format['format_note']}") |
| 35 | + ydl_opts['format'] = selected_format['format_id'] |
| 36 | + ydl.download([url]) |
| 37 | + downloaded_file_path = os.path.join(save_to, f"{info_dict.get('title')}.mp4") |
| 38 | + print(f"Download completed successfully. File saved to: {downloaded_file_path}") |
| 39 | + else: |
| 40 | + print("No suitable format found for the requested resolution.") |
| 41 | + |
| 42 | + print('\n------------------------------Video Info------------------------------\n') |
| 43 | + print(f"Title: {info_dict.get('title')}") |
| 44 | + print(f"Author: {info_dict.get('uploader')}") |
| 45 | + print(f"Views: {info_dict.get('view_count')}") |
| 46 | + print(f"Length: {info_dict.get('duration')} seconds") |
| 47 | + print(f"Description: {info_dict.get('description')}") |
| 48 | + print('------------------------------------------------------------------------\n') |
| 49 | + |
| 50 | + except Exception as e: |
| 51 | + print(f"An error occurred: {e}") |
| 52 | + |
| 53 | +def downloadMedia(): |
| 54 | + url = input("Enter URL Here: ") |
| 55 | + save_to = input("Save to (default is 'Downloads'): ").strip() |
| 56 | + resolution = input("Enter desired resolution (e.g., 360p, 720p): ").strip() |
| 57 | + download_media(url, save_to, resolution) |
| 58 | + |
| 59 | +downloadMedia() |
0 commit comments