import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog
from tkinter.ttk import Progressbar
import threading
import os
import subprocess
import json
import queue
import sys
# Ensure yt_dlp is installed
try:
import yt_dlp
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", "yt-dlp"])
import yt_dlp
# Configuration file path (placed in user's home directory)
CONFIG_FILE = os.path.join(os.path.expanduser("~"), ".video_downloader_config.json")
CONFIG_DEFAULTS = {
"last_directory": os.path.expanduser("~")
}
# Queue for thread-safe GUI updates
progress_queue = queue.Queue()
def load_config():
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, 'r') as f:
config = json.load(f)
return config
except json.JSONDecodeError:
return CONFIG_DEFAULTS.copy()
else:
return CONFIG_DEFAULTS.copy()
def save_config(config):
try:
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f)
except Exception as e:
messagebox.showerror("Error", f"Failed to save config: {e}")
def load_last_directory():
config = load_config()
return config.get("last_directory", CONFIG_DEFAULTS["last_directory"])
def save_last_directory(directory):
config = load_config()
config["last_directory"] = directory
save_config(config)
# Hook function for yt-dlp to report progress
def yt_dlp_hook(d):
if d['status'] == 'downloading':
downloaded = d.get('downloaded_bytes', d.get('downloaded', 0))
total = d.get('total_bytes', d.get('total_bytes_estimate', 0))
eta = d.get('eta', 0)
progress_percent = (downloaded / total) * 100 if total else 0
progress_queue.put(('progress', progress_percent))
progress_queue.put(('eta', eta))
elif d['status'] == 'finished':
progress_queue.put(('done', None))
def download_video(url, download_path, file_name):
ydl_opts = {
'outtmpl': os.path.join(download_path, f"{file_name}.%(ext)s"),
'progress_hooks': [yt_dlp_hook],
'format': 'best'
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
progress_queue.put(('finished', "Download completed successfully!"))
except Exception as e:
progress_queue.put(('error', str(e)))
def start_download():
url = url_entry.get().strip()
if not url:
messagebox.showerror("Error", "Please enter a valid URL.")
return
# Optional: Add more URL validation here
initial_dir = load_last_directory()
download_path = filedialog.askdirectory(initialdir=initial_dir, title="Select Download Directory")
if not download_path:
return
save_last_directory(download_path)
file_name = simpledialog.askstring("File Name", "Enter name for the downloaded file:")
if not file_name:
return
# Reset progress bar and labels
progress['value'] = 0
time_label.config(text="Time remaining: N/A")
# Disable download button to prevent multiple downloads
download_button.config(state=tk.DISABLED)
# Start download in a separate thread
thread = threading.Thread(target=download_video, args=(url, download_path, file_name), daemon=True)
thread.start()
# Start monitoring the queue
root.after(100, process_queue)
def process_queue():
try:
while True:
item = progress_queue.get_nowait()
if item[0] == 'progress':
progress['value'] = item[1]
elif item[0] == 'eta':
time_label.config(text=f"Time remaining: {item[1]}s")
elif item[0] == 'done':
pass # You can handle intermediate done states if necessary
elif item[0] == 'finished':
messagebox.showinfo("Success", item[1])
download_button.config(state=tk.NORMAL)
progress['value'] = 100
time_label.config(text="Time remaining: 0s")
elif item[0] == 'error':
messagebox.showerror("Download Error", item[1])
download_button.config(state=tk.NORMAL)
except queue.Empty:
pass
else:
root.after(100, process_queue)
# Continue checking if the thread is still running
if download_button['state'] == tk.DISABLED:
root.after(100, process_queue)
else:
return
def paste_from_clipboard():
try:
clipboard_content = root.clipboard_get()
url_entry.delete(0, tk.END)
url_entry.insert(0, clipboard_content)
except tk.TclError:
messagebox.showerror("Error", "No valid data in clipboard.")
# Setting up the GUI
root = tk.Tk()
root.title("Video Downloader")
root.geometry("600x200")
root.resizable(False, False)
# URL Input Frame
tk.Label(root, text="Enter Video URL:").pack(pady=10)
input_frame = tk.Frame(root)
input_frame.pack(pady=5)
url_entry = tk.Entry(input_frame, width=60)
url_entry.pack(side=tk.LEFT, padx=10)
paste_button = tk.Button(input_frame, text="Paste from Clipboard", command=paste_from_clipboard)
paste_button.pack(side=tk.RIGHT)
# Download Button
download_button = tk.Button(root, text="Download", command=start_download, width=20)
download_button.pack(pady=10)
# Progress Bar and ETA Label
progress = Progressbar(root, orient="horizontal", length=500, mode="determinate")
progress.pack(pady=10)
time_label = tk.Label(root, text="Time remaining: N/A")
time_label.pack(pady=5)
# Start the GUI loop
root.mainloop()