-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathytmp3.py
162 lines (136 loc) · 5.31 KB
/
ytmp3.py
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
import os
import logging
from yt_dlp import YoutubeDL
DOWNLOAD_FOLDER = os.path.join(os.getcwd(), "downloads")
os.makedirs(DOWNLOAD_FOLDER, exist_ok=True)
errors = [] # List to capture errors
def setup_logging(hidden, log_file):
"""
Set up logging based on the provided options.
:param hidden: If True, suppress all output except errors.
:param log_file: Path to the log file (if provided).
"""
log_level = logging.ERROR if hidden else logging.DEBUG
logging.basicConfig(
level=log_level,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[logging.StreamHandler()]
)
if log_file:
file_handler = logging.FileHandler(log_file, encoding="utf-8")
file_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
logging.getLogger().addHandler(file_handler)
def download_audio(video_url):
"""
Download audio as MP3 from a given YouTube URL.
:param video_url: The URL of the YouTube video.
"""
ydl_opts = {
"format": "bestaudio/best",
"retries": 3,
"verbose": False,
"outtmpl": os.path.join(DOWNLOAD_FOLDER, "%(title)s.%(ext)s"),
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3",
"preferredquality": "192",
}
],
}
with YoutubeDL(ydl_opts) as ydl:
try:
ydl.download([video_url])
logging.info(f"Downloaded: {video_url}")
except Exception as e:
logging.error(f"Failed to download {video_url}: {e}")
errors.append(f"Failed to download {video_url}: {e}") # Capture the error
def process_video(link):
"""
Process a single video link and download its audio.
:param link: The original YouTube link.
"""
if "music.youtube.com" in link:
link = link.replace("music.youtube.com", "www.youtube.com")
logging.info(f"Downloading the original video: {link}")
download_audio(link)
def download_from_file(link_file):
"""
Download audio from a file containing YouTube links.
:param link_file: Path to the file containing the YouTube links (one per line).
"""
if not os.path.exists(link_file):
logging.error(f"File '{link_file}' does not exist.")
errors.append(f"File '{link_file}' does not exist.")
return
with open(link_file, "r", encoding="utf-8") as file:
links = [line.strip() for line in file if line.strip()]
if not links:
logging.error("No links found in the file.")
errors.append("No links found in the file.")
return
for link in links:
process_video(link)
def inline_download(video_url):
"""
Allow inline downloading of a single YouTube link.
:param video_url: The URL of the YouTube video.
"""
logging.info(f"Downloading audio for the provided link: {video_url}")
process_video(video_url)
def done_menu():
"""
Display a menu after the download is complete, offering the user to either return to the main menu or exit.
This will also show errors that occurred during the process.
"""
global errors # Use the global errors list to display them
while True:
if errors:
print("\nErrors that occurred during the download process:")
for error in errors:
print(f"- {error}")
print("\nDone! What would you like to do next?")
print("1. Return to the main menu")
print("2. Exit the program")
choice = input("Enter the number of your choice: ")
if choice == '1':
return True # Return to the main menu by returning to the main loop
elif choice == '2':
print("Exiting the downloader. Goodbye!")
return False # Exit the program
else:
print("Invalid choice. Please try again.")
def main():
"""
CLI-like interface for the user to choose how to download content.
"""
print("Welcome to the YouTube Audio Downloader!")
while True:
print("\nPlease choose an option:")
print("1. Download from a file containing YouTube links.")
print("2. Download a single YouTube video by providing the URL.")
print("3. Exit.")
choice = input("Enter the number of your choice: ")
if choice == '1':
file_path = input("Enter the path to the file containing YouTube links: ")
logging_level = input("Enable hidden logging (only errors)? (y/n): ").strip().lower()
hidden = logging_level == 'y'
setup_logging(hidden, None)
download_from_file(file_path)
if not done_menu(): # If the user chooses to exit
break
elif choice == '2':
video_url = input("Enter the YouTube video URL: ")
logging_level = input("Enable hidden logging (only errors)? (y/n): ").strip().lower()
hidden = logging_level == 'y'
setup_logging(hidden, None)
inline_download(video_url)
if not done_menu(): # If the user chooses to exit
break
elif choice == '3':
print("Exiting the downloader. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()