-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
75 lines (64 loc) · 2.61 KB
/
main.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
import logging
import os
from pytube import YouTube
import yt_dlp
import util
import subprocess
# https://www.gyan.dev/ffmpeg/builds/
'''
WHEN MAKING THIS A LIB, THIS NEEDS TO BE PUT INTO THE FOLDER LOCALLY
'''
MUSIC_PATH = r'C:\Users\forea\Documents\dj\playlists\general'
FFMPEG_PATH = r'C:\Program Files\ffmpeg-7.0.1-essentials_build\bin' # Update this path to the directory where ffmpeg.exe and ffprobe.exe are located
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def convert_to_mp3(input_file, output_file):
try:
subprocess.run([os.path.join(FFMPEG_PATH, 'ffmpeg'), '-i', input_file, '-q:a', '0', '-map', 'a', output_file], check=True)
os.remove(input_file) # Remove the original file after conversion
logging.info(f"Converted {input_file} to {output_file}")
except Exception as e:
logging.error(f"Failed to convert {input_file} to MP3: {e}")
def download_audio_pytube(youtube_url):
try:
yt = YouTube(youtube_url)
audio_stream = yt.streams.filter(only_audio=True).first()
temp_file = audio_stream.download(output_path=MUSIC_PATH, filename_prefix='temp_')
output_file = os.path.join(MUSIC_PATH, f"{yt.title}.mp3")
convert_to_mp3(temp_file, output_file)
logging.info(f"Downloaded with pytube: {youtube_url}")
except Exception as e:
logging.error(f"pytube failed for {youtube_url}: {e}")
return False
return True
def download_audio_ytdlp(youtube_url):
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': f'{MUSIC_PATH}/temp_%(title)s.%(ext)s',
'ffmpeg_location': FFMPEG_PATH,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([youtube_url])
logging.info(f"Downloaded with yt-dlp: {youtube_url}")
except Exception as e:
logging.error(f"yt-dlp failed for {youtube_url}: {e}")
return False
return True
def extract_urls_from_channel(channel):
return [post[-1] for post in util.scrapetube_util(channel)]
def main():
channel = 'https://www.youtube.com/channel/UC-mj9Bjuk5_V7W8Zl4SC09Q'
content = extract_urls_from_channel(channel)
for url in content:
logging.info(f"DOWNLOADING URL {url}")
if not download_audio_pytube(url):
if not download_audio_ytdlp(url):
logging.error(f"Both methods failed for {url}")
logging.info("MAIN METHOD COMPLETED")
if __name__ == "__main__":
main()