-
Notifications
You must be signed in to change notification settings - Fork 12.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Update CliYoutubeDownloader.py #2487
Open
Dathaze20
wants to merge
1
commit into
geekcomputers:master
Choose a base branch
from
Dathaze20:patch-1
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Conversation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Okay, let's break down the fixes and improvements made to the original YouTube downloader script and provide a comprehensive explanation. Original Script Issues The original script had several issues which I'll describe below: Incorrect Library Import: The original script used pytubefix instead of pytube. This is a crucial error because pytubefix is not the correct library name. Lack of Error Handling: The original script didn't have proper error handling, which could cause the program to crash when encountering issues such as incorrect URLs, network errors, or unexpected pytube behavior. Limited Functionality: It only allowed downloading a single video at a time. It had no support for playlists. It lacked features like download resumption and detailed progress reporting. Basic UI: The user interface was very basic, lacking clear menus, proper formatting, and visual feedback. Global Variable: The original script used a global file_size variable that made the code harder to manage and to debug, and this can cause problems. Inconsistent Style: The code's style was not consistent, which made it less readable. No logging: The original script had no logging, which would help with debugging and tracking. Fixed Script Improvements and Explanation: The provided fixed script addresses the issues above, and implements additional functionality. Here's a detailed breakdown of each improvement: 1. Library Correction and Installation: Corrected Import: The import statement was changed from import pytubefix to the correct import pytube. Required Libraries: The script depends on the following libraries, which can be installed using pip: pip install pytube colorama content_copy download Use code with caution. Bash pytube: This is the core library for interacting with YouTube. It is used to fetch video metadata, stream information, and download videos. colorama: This library is used to add color to the output for a better user experience, making the interface more visually appealing and providing better visual feedback. 2. Playlist Support: PlaylistHandler Class: This class was implemented to handle YouTube playlists. __init__: Initializes the playlist handler with a reference to the YouTubeDownloader and the playlist URL. _get_playlist(): Fetches the playlist using pytube.Playlist and handles potential RegexMatchError if the playlist URL is invalid and other errors. _get_videos_to_download(): Presents the user with options to download all videos or select specific videos from the playlist. _select_specific_videos(): Allows users to select specific videos from the playlist based on their index numbers. download_playlist(): Downloads all selected videos from the playlist one by one, it will catch exceptions on each video if it can't be downloaded. 3. Download Resumption: Partial File Handling: The _start_download() method now uses a .part extension for partial downloads. It checks for existing .part files and resumes the download if found. Renaming Partials: After a successful download, the temporary .part extension is removed. 4. Enhanced Progress Bar: Download Speed: The _on_progress() method calculates and displays the download speed in MB/s. Estimated Time Remaining (ETA): ETA is now calculated and displayed in minutes, based on the download speed and remaining bytes. Dynamic Width: The progress bar length is calculated based on the terminal width to adapt to different terminal sizes. 5. Robust Error Handling: Specific Exception Handling: The script now includes handlers for various pytube exceptions like RegexMatchError (invalid URLs), and VideoUnavailable. Error Logging: Each error that could happen on the application is logged to a file using the logging library. User Feedback: Error messages are displayed to the user in a red color to make it clear that there was a problem during the action. 6. Logging: Logging Setup: The _setup_logger() function configures a logger that writes to both a log file (youtube_downloader.log) and the console. Log Levels: The log file records detailed messages at the DEBUG level, while the console only displays INFO level messages to keep console output clean. 7. Improved User Interface (UI): Menu Headers: The _print_menu_header() method creates visually distinct menu headers using colorama for clear visual separation. Centered Text: Text elements are centered using the _center_text() method, which enhances readability and makes the UI more aesthetically pleasing. Colored Output: colorama is used to provide colored text for better user guidance and error indication. Clear Input Prompts: Input prompts use Fore.YELLOW to highlight the areas where the user needs to take action. 8. Code Structure and Style: Class Structure: The script is organized into two classes: PlaylistHandler and YouTubeDownloader, to follow an object-oriented programming paradigm, improving the structure and scalability of the application. Type Hinting: The script uses type hints to make the code more readable and maintainable. Docstrings: Added documentation for each of the methods to make the code more readable and easier to understand for other developers. 9. Global Variable Issue Fix: The script doesn't use global variable anymore which will make the code easier to debug and more robust. Detailed Explanation of Key Functions: __init__: This method initializes the class, calls methods that sets up the logger, takes input URL, handles initial errors, and sets the default download path before running the main_menu method. _setup_logger(): This method sets up a logger to log all important actions of the application to a file and log some information on the console. _get_terminal_width(): Method to get the width of the current terminal to help with the formatting of the UI. _center_text(): Helps with the UI by centering text on the current terminal. _print_menu_header(): Helps with printing visually distinct headers using the colorama library. _print_error(): Used for printing errors in a red color to make it clear for the user. _print_success(): Used to print success messages in green. _get_url(): Used to get the input URL from the user. _select_stream(): Helps to select the correct stream for download based on if the user wants video or audio. _confirm_download(): Method that takes information and asks for download confirmation from the user. _start_download(): Method that takes the stream and starts the download process for the selected stream. _on_progress(): Method that displays the current download progress, the current speed of download and the estimated time remaining for the download to finish. main_menu(): The main loop of the application, it displays the current options to the user and takes action based on the selected option. _change_path(): Method to change the current default download path. How to Run the Fixed Script Save: Save the corrected code as a Python file (e.g., youtube_downloader.py). Install Libraries: If not already installed, run: pip install pytube colorama Run: Execute the script from your terminal: python youtube_downloader.py Conceptual Unit Tests and Documentation: The code also includes comments on where the tests and documentation should be written, although the actual tests and documentation are not part of this implementation. Unit Tests: You would typically write unit tests to verify that each component works as expected, and write code that tests a specific function. Documentation: Writing the documentation would entail creating user guides, API documentation, and README.md files. In summary, The fixes implemented in the provided code enhance the original script by adding more functionality, fixing bugs, implementing more robust error handling, and improving the UI and logging, the result is an improved version of the original script and more user friendly. This makes the script more reliable and user-friendly than the original script. If you have any other questions about it, feel free to ask.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Okay, let's break down the fixes and improvements made to the original YouTube downloader script and provide a comprehensive explanation.
Original Script Issues
The original script had several issues which I'll describe below:
Incorrect Library Import:
The original script used pytubefix instead of pytube. This is a crucial error because pytubefix is not the correct library name.
Lack of Error Handling:
The original script didn't have proper error handling, which could cause the program to crash when encountering issues such as incorrect URLs, network errors, or unexpected pytube behavior.
Limited Functionality:
It only allowed downloading a single video at a time. It had no support for playlists.
It lacked features like download resumption and detailed progress reporting.
Basic UI:
The user interface was very basic, lacking clear menus, proper formatting, and visual feedback.
Global Variable:
The original script used a global file_size variable that made the code harder to manage and to debug, and this can cause problems.
Inconsistent Style:
The code's style was not consistent, which made it less readable.
No logging:
The original script had no logging, which would help with debugging and tracking.
Fixed Script Improvements and Explanation:
The provided fixed script addresses the issues above, and implements additional functionality. Here's a detailed breakdown of each improvement:
Corrected Import: The import statement was changed from import pytubefix to the correct import pytube.
Required Libraries: The script depends on the following libraries, which can be installed using pip:
pip install pytube colorama
content_copy
download
Use code with caution.
Bash
pytube: This is the core library for interacting with YouTube. It is used to fetch video metadata, stream information, and download videos.
colorama: This library is used to add color to the output for a better user experience, making the interface more visually appealing and providing better visual feedback.
PlaylistHandler Class: This class was implemented to handle YouTube playlists.
init: Initializes the playlist handler with a reference to the YouTubeDownloader and the playlist URL.
_get_playlist(): Fetches the playlist using pytube.Playlist and handles potential RegexMatchError if the playlist URL is invalid and other errors.
_get_videos_to_download(): Presents the user with options to download all videos or select specific videos from the playlist.
_select_specific_videos(): Allows users to select specific videos from the playlist based on their index numbers.
download_playlist(): Downloads all selected videos from the playlist one by one, it will catch exceptions on each video if it can't be downloaded.
Partial File Handling: The _start_download() method now uses a .part extension for partial downloads. It checks for existing .part files and resumes the download if found.
Renaming Partials: After a successful download, the temporary .part extension is removed.
Download Speed: The _on_progress() method calculates and displays the download speed in MB/s.
Estimated Time Remaining (ETA): ETA is now calculated and displayed in minutes, based on the download speed and remaining bytes.
Dynamic Width: The progress bar length is calculated based on the terminal width to adapt to different terminal sizes.
Specific Exception Handling: The script now includes handlers for various pytube exceptions like RegexMatchError (invalid URLs), and VideoUnavailable.
Error Logging: Each error that could happen on the application is logged to a file using the logging library.
User Feedback: Error messages are displayed to the user in a red color to make it clear that there was a problem during the action.
Logging Setup: The _setup_logger() function configures a logger that writes to both a log file (youtube_downloader.log) and the console.
Log Levels: The log file records detailed messages at the DEBUG level, while the console only displays INFO level messages to keep console output clean.
Menu Headers: The _print_menu_header() method creates visually distinct menu headers using colorama for clear visual separation.
Centered Text: Text elements are centered using the _center_text() method, which enhances readability and makes the UI more aesthetically pleasing.
Colored Output: colorama is used to provide colored text for better user guidance and error indication.
Clear Input Prompts: Input prompts use Fore.YELLOW to highlight the areas where the user needs to take action.
Class Structure: The script is organized into two classes: PlaylistHandler and YouTubeDownloader, to follow an object-oriented programming paradigm, improving the structure and scalability of the application.
Type Hinting: The script uses type hints to make the code more readable and maintainable.
Docstrings: Added documentation for each of the methods to make the code more readable and easier to understand for other developers.
The script doesn't use global variable anymore which will make the code easier to debug and more robust.
Detailed Explanation of Key Functions:
init: This method initializes the class, calls methods that sets up the logger, takes input URL, handles initial errors, and sets the default download path before running the main_menu method.
_setup_logger(): This method sets up a logger to log all important actions of the application to a file and log some information on the console.
_get_terminal_width(): Method to get the width of the current terminal to help with the formatting of the UI.
_center_text(): Helps with the UI by centering text on the current terminal.
_print_menu_header(): Helps with printing visually distinct headers using the colorama library.
_print_error(): Used for printing errors in a red color to make it clear for the user.
_print_success(): Used to print success messages in green.
_get_url(): Used to get the input URL from the user.
_select_stream(): Helps to select the correct stream for download based on if the user wants video or audio.
_confirm_download(): Method that takes information and asks for download confirmation from the user.
_start_download(): Method that takes the stream and starts the download process for the selected stream.
_on_progress(): Method that displays the current download progress, the current speed of download and the estimated time remaining for the download to finish.
main_menu(): The main loop of the application, it displays the current options to the user and takes action based on the selected option.
_change_path(): Method to change the current default download path.
How to Run the Fixed Script
Save: Save the corrected code as a Python file (e.g., youtube_downloader.py).
Install Libraries: If not already installed, run: pip install pytube colorama
Run: Execute the script from your terminal: python youtube_downloader.py
Conceptual Unit Tests and Documentation:
The code also includes comments on where the tests and documentation should be written, although the actual tests and documentation are not part of this implementation.
Unit Tests: You would typically write unit tests to verify that each component works as expected, and write code that tests a specific function.
Documentation: Writing the documentation would entail creating user guides, API documentation, and README.md files.
In summary, The fixes implemented in the provided code enhance the original script by adding more functionality, fixing bugs, implementing more robust error handling, and improving the UI and logging, the result is an improved version of the original script and more user friendly. This makes the script more reliable and user-friendly than the original script.
If you have any other questions about it, feel free to ask.