-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
97 lines (81 loc) · 3.54 KB
/
main.py
File metadata and controls
97 lines (81 loc) · 3.54 KB
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
import yt_dlp
import os
import re
from dotenv import load_dotenv
# --- KONFIGURASI ENV ---
load_dotenv()
# Ambil FFMPEG_PATH dari .env, dengan fallback ke path default
FFMPEG_LOCATION = os.getenv('FFMPEG_PATH')
if not FFMPEG_LOCATION:
# Fallback ke path default jika .env belum diset
FFMPEG_LOCATION = r"C:\ffmpeg\bin"
print(f"Peringatan: FFMPEG_PATH tidak ditemukan di .env. Menggunakan fallback: {FFMPEG_LOCATION}")
# --- FUNGSI UTILITAS ---
def to_camel_case(text: str) -> str:
"""Mengubah teks menjadi Camel Case (Setiap Kata Diawali Huruf Kapital)."""
words = text.split(" ")
return " ".join(word[:1].upper() + word[1:].lower() if word else "" for word in words)
def sanitize_filename(name: str) -> str:
"""Hilangkan karakter yang tidak valid untuk nama folder/file."""
return re.sub(r'[<>:"/\\|?*]', '', name)
# --- FUNGSI UTAMA ---
def youtube_to_mp3(url, base_output="downloads"):
with yt_dlp.YoutubeDL({'quiet': True}) as ydl:
try:
info = ydl.extract_info(url, download=False)
except Exception as e:
print(f"Gagal mengambil informasi video: {e}")
return
if isinstance(info, list) and info:
info = info[0]
elif not isinstance(info, dict):
print("ERROR: Struktur informasi video tidak terduga.")
return
title = info.get("title", "output")
artist = info.get("artist") or info.get("uploader") or info.get("channel") or "Unknown"
artist = sanitize_filename(artist)
output_path = os.path.join(base_output, artist)
os.makedirs(output_path, exist_ok=True)
ydl_opts = {
'format': 'bestaudio[ext=m4a]/bestaudio/best',
'outtmpl': f'{output_path}/%(title)s.%(ext)s',
'ffmpeg_location': FFMPEG_LOCATION,
'quiet': False,
'extractor_args': {'youtube': {'player_client': ['android']}},
'retries': 10,
'fragment_retries': 10,
'skip_unavailable_fragments': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
print(f"\nMengunduh dan mengonversi: {title} dari {artist}...")
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
download_info = ydl.extract_info(url, download=True)
if isinstance(download_info, list) and download_info:
download_info = download_info[0]
actual_title = download_info.get("title", title)
camel_title = to_camel_case(actual_title)
base_filename_pattern = sanitize_filename(actual_title)
mp3_files = [f for f in os.listdir(output_path)
if f.endswith('.mp3') and base_filename_pattern in f]
if mp3_files:
old_file = os.path.join(output_path, mp3_files[0])
new_file = os.path.join(output_path, f"{camel_title}.mp3")
if old_file != new_file:
os.rename(old_file, new_file)
print(f"File berhasil disimpan dan di-rename: {new_file}")
else:
print("Peringatan: File MP3 hasil konversi tidak ditemukan untuk di-rename.")
except yt_dlp.utils.DownloadError as e:
print(f"Gagal mengunduh: {e}")
print("Jika tetap gagal, coba update yt-dlp:")
print(" python -m pip install -U yt-dlp")
except Exception as e:
print(f"Terjadi kesalahan tak terduga: {e}")
if __name__ == "__main__":
url = input("Masukkan link YouTube: ")
youtube_to_mp3(url)