I want to build a CLI tool that automates the process of downloading videos from a list of youtube channels and playlists and then sorts them into the right folder on my computer. Essentially its job is to look for new videos from the provided source list, figure out which folder in my local media folder each respective video belongs in, and finally downloads + places those videos into those respective folders.
I already have a folder structure where I've organized hundreds of videos manually. It's a nested folder structure of different custom categories I've defined, where each folder is a category. Most of the videos I've already downloaded (several hundred) use the same title as the YouTube source. The idea is we can use an LLM to perform the categorization by passing in a file tree structure of the existing folders and file names within them. Ideally we would use the LLM service's caching function for cost optimization.
It should use a config file which lets me specify the sources (channels and playlists) we should download from. Each source should have a 'last synced date' parameter to track when that source was last checked and downloaded from. This is to make it easy for me to add new sources over time and prevent the script from checking videos from before the last synced date. The script should use the yt-dlp package to manage downloads/metadata from youtube (that's what I use right now for manually downloading stuff). Because many of the videos I'm downloading are in foreign languages I should be able to specify the subtitle languages I want downloaded and attached to every video that gets downloaded. The config file should also let me enable debug logging.
For reference, here's the command I currently use for downloading these videos (note that this command embeds subtitles too):
Functionally I should be able to run the CLI command and the script will begin checking the sources from the config file, finding videos that were added or uploaded past the last sync date and getting the metadata for them. It will then use the metadata (the video's title) to figure out which folder each new video should go into. Importantly it shouldn't start downloading the videos yet because it should allow me to verify that I'm happy with the videos to download list as well as their designated folders. This verification step should let me make modifications to videos that I'm not happy with, such as removing videos from being downloaded or changing the designated folder (either by re-running the LLM categorization process or by manually selecting a folder myself). Finally, when I'm satisfied, the script should begin downloading videos. A progress UI should be present that lets me see the status of the downloads (including errors, such as if some downloads fail or if subtitles can't be found for example)
Lastly, the CLI should have an override that lets me directly provide a bunch of youtube video, channel, or playlist links which should be used as sources instead of the sources provided in the config file. This is to make it easy for me to download ad-hoc videos I find that aren't in the usual channels/playlists present in the config file.
Assistant
User
code it
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Give me an overview of how this script would work, from a UX and technological standpoint. Feel free to ask clarifying questions if necessary. When we're both satisfied, we can begin the technical implementation.
Below is an overview of how the tool could work from both the user experience (UX) and the technology/architecture perspectives. Let me know if I’ve captured everything you need or if you’d like to dive deeper into any part.
User Experience (UX) Flow
Launching the CLI:
The user runs the command (e.g., video-downloader [command-options]) from a terminal.
There is an option to run in “config mode” (using your pre-defined sources) or with an override flag (e.g., --override) which allows passing a list of ad-hoc YouTube links (channels, playlists, or videos).
Configuration Loading:
On startup (unless override is active), the tool reads a configuration file (likely in JSON, YAML, or INI format) that contains:
A list of sources (channels and playlists).
A “last synced date” for each source to filter out previously processed videos.
Subtitle language preferences.
A debug logging flag.
Pre-Download Processing:
For every provided source from the config file, the tool uses yt-dlp to fetch metadata for the videos.
Only videos with upload dates after the “last synced date” are considered.
The metadata (especially the video’s title) is collected for further processing.
Categorization Using an LLM:
The tool scans your local media folder structure (and possibly reads a “file tree” with existing folder and file names).
For each new video, the video’s title and possibly additional metadata is passed to an LLM service to suggest the “best fit” category (folder).
Caching: The LLM service’s caching mechanism can be used to avoid re-categorizing titles that have already been processed (based on an LLM service cache key for a given video title and folder tree snapshot).
The LLM returns a recommended local folder/category.
Verification Step:
Interactive Review: Before downloads begin, the tool presents an interactive summary:
A list of candidate videos with their metadata.
The suggested destination folder for each video.
The user may:
Approve: Continue with downloading the listed videos.
Remove: Exclude certain videos.
Modify: Change the designated folder — either trigger a re-categorization via the LLM on that video or manually select a folder from your pre-defined file tree.
This “dry-run” or “verification mode” ensures no unwanted downloads occur.
Downloading Process:
After the user confirms, the tool starts the download process:
For each video, it calls yt-dlp with your custom command-line parameters (e.g., downloading subtitles and embedding them).
Uses a progress UI (such as using Python’s rich or tqdm libraries) to visually indicate progress, and log any errors (for issues like missing subtitles, download failures, etc.).
Each downloaded video is then moved into the specified local folder.
Post-Download Updates:
After successful downloads, the “last synced date” for each source in the config is updated accordingly.
Summary reports (and logs in debug mode) are provided to the user.
Override Mode:
When the CLI override flag is used with a list of video/channel/playlist links, the process bypasses the config file sources.
The tool fetches the metadata for these ad-hoc sources, optionally asks for categorization if the video isn’t already present, then performs the download as above.
Technological and Architectural Components
Configuration Management:
File Format: Use a human-editable file (YAML/JSON/INI) to store sources, last sync dates, subtitle options, etc.
Parsing: A configuration parser reads this file on startup.
Source Handling and Metadata Extraction:
yt-dlp Integration: Use the Python API or subprocess calls to yt-dlp to:
Filtering: Logic to skip videos older than the last sync date.
Local File Tree Analysis:
File System Scanning: Walk through your media folder structure to build a representation (e.g., dict or tree) of categories and current video file names.
Data Preparation: This file tree is used as context for the LLM’s decision-making process.
LLM Integration for Categorization:
Prompting: Build a prompt that includes the new video’s title and a snapshot of your current folder structure/list.
Caching: Utilize the LLM service’s caching (or implement your own caching layer) so that repeated requests for the same title/folder structure are not re-sent—minimizing cost.
Processing Results: Parse the LLM output to determine the recommended folder.
User Verification Interface:
Interactive CLI UI: Implement an interactive prompt or use a text-based UI library (such as Python’s curses, prompt_toolkit, or even inquirer) so users can:
Review videos and folder assignments.
Edit or remove items from the download list.
Decision Persistence: Allow users to save their modifications which will then be used for the download step.
Downloading and Progress Reporting:
Download Calls: For each confirmed video, call yt-dlp with the preset download options (including video format and subtitles).
Progress UI: Show a progress bar, status messages, and capture errors as they happen.
Clarifying Questions
LLM Service Details:
Which LLM service are you planning to use (e.g., OpenAI’s GPT models via an API)?
Do you have any specific requirements in terms of prompt engineering or caching mechanism for this service?
Programming Language and Libraries:
Do you prefer the tool to be built in Python (recommended given yt-dlp integration and ample CLI libraries), or is there another preferred language?
CLI UI Requirements:
Would you prefer a simple console prompt for verification (like a yes/no menu with list editing) or a more polished interface (using libraries like prompt_toolkit or rich for an enhanced experience)?
Error Handling and Logging:
Do you have preferences on how and where errors should be logged (e.g., text file, console-only, etc.)?
Local Folder Mapping:
Besides matching the video title to a folder name, do you require any additional logic for determining which folder the video belongs in (e.g., based on metadata, content-tags, etc.)?
Ad-hoc Override Mode:
Should the override mode incorporate the same categorization step (if the ad-hoc video is new) or should it default to a specific folder if not explicitly set?
Once we nail down these details, we can start diving into the actual technical implementation step-by-step. Let me know your thoughts!
Below is an example of a complete Python script that implements the envisioned CLI tool. (Note that for brevity and demonstration purposes, the integration with an actual LLM service has been simulated with a dummy categorization function and an in‑memory cache; in a production system you would replace that with your preferred LLM API and caching layer.) You can adjust or extend this code as needed.
Note:
• This example uses the following libraries:
‣ Click for CLI argument parsing.
‣ yt-dlp (which can be installed via pip) for fetching metadata and downloading videos.
‣ rich for a progress display and colored logging.
• The config file is expected to be in JSON format. (You can easily switch to YAML if preferred.)
• The code uses a dummy LLM “categorizer” which simply looks for matches between video titles and known folder names. Replace it with your actual LLM integration once you’re ready.
Before running, install dependencies:
bash
pip install click yt-dlp rich
Below is the full code:
python
#!/usr/bin/env python
import os
import sys
import json
import datetime
import subprocess
from pathlib import Path
from typing import List, Dict, Any
import click
from yt_dlp import YoutubeDL
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn
# Global console for pretty printing/logs:
console = Console()
#######################
# CONFIGURATION MANAGEMENT
#######################
CONFIG_PATH_DEFAULT = "config.json"
def load_config(config_path: str) -> Dict[str, Any]:
"""Load configuration from a JSON file."""
if not os.path.exists(config_path):
console.print(f"[red]Config file not found at {config_path}.[/red]")
sys.exit(1)
with open(config_path, "r") as fp:
config = json.load(fp)
return config
def save_config(config: Dict[str, Any], config_path: str):
"""Save configuration to a JSON file."""
with open(config_path, "w") as fp:
json.dump(config, fp, indent=4)
#######################
# LOCAL MEDIA FOLDER SCAN
#######################
def scan_media_folder(media_folder: str) -> List[str]:
"""
Scans the media folder and returns a list of folder names.
We assume that direct subdirectories under media_folder are our categories.
"""
if not os.path.isdir(media_folder):
console.print(f"[red]Media folder {media_folder} does not exist.[/red]")
sys.exit(1)
folders = [f.name for f in Path(media_folder).iterdir() if f.is_dir()]
return folders
#######################
# DUMMY LLM CATEGORIZATION (with caching)
#######################
# For demonstration, we use an in-memory cache. In a production environment,
# you might store the cache results on disk or use your LLM provider's caching.
CATEGORY_CACHE = {}
def categorize_video(title: str, available_categories: List[str]) -> str:
"""
Dummy categorization function that “simulates” LLM-categorization.
It first checks a global cache. Otherwise, it does a simple match
between the video title and available category names.
"""
if title in CATEGORY_CACHE:
return CATEGORY_CACHE[title]
# Naive matching: if any category name is found inside the title (case-insensitive),
# return that category. Otherwise, return a "Misc" folder.
for category in available_categories:
if category.lower() in title.lower():
CATEGORY_CACHE[title] = category
return category
# Default to a "Misc" category.
CATEGORY_CACHE[title] = "Misc"
return "Misc"
#######################
# FETCH VIDEOS METADATA VIA yt-dlp
#######################
def fetch_videos_metadata(source_url: str, last_synced_str: str) -> List[Dict[str, Any]]:
"""
Uses yt-dlp to fetch video metadata from a channel or playlist URL.
It filters out videos that precede last_synced.
Returns a list of metadata dicts.
"""
console.print(f"Fetching metadata for {source_url}", style="blue")
# Reload the date from string (assume format is ISO 8601)
last_synced = datetime.datetime.fromisoformat(last_synced_str) if last_synced_str else None
ydl_opts = {
"quiet": True,
"skip_download": True,
"extract_flat": True, # Extract metadata without deep extraction
"dump_single_json": True,
}
try:
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(source_url, download=False)
except Exception as e:
console.print(f"[red]Error fetching metadata for {source_url}: {e}[/red]")
return []
# If the URL points to a playlist or a channel, the "entries" key contains videos.
entries = []
if "entries" in info:
entries = info["entries"]
else:
entries = [info]
# Filter new videos by comparing upload dates if possible.
new_videos = []
for entry in entries:
# Some videos might be None.
if entry is None:
continue
# Get upload date if available. Note: some videos might not have an upload date.
# yt-dlp sometimes provides "upload_date" in YYYYMMDD format.
upload_date = entry.get("upload_date")
if upload_date:
try:
video_date = datetime.datetime.strptime(upload_date, "%Y%m%d")
except Exception:
video_date = None
else:
video_date = None
if last_synced and video_date and video_date <= last_synced:
continue
# If there's no upload date, we assume it's new.
new_videos.append({
"id": entry.get("id"),
"title": entry.get("title") or "untitled",
"url": entry.get("url") or entry.get("webpage_url", source_url),
"upload_date": upload_date,
"source": source_url,
})
return new_videos
#######################
# DOWNLOAD VIDEO VIA yt-dlp
#######################
def download_video(video_url: str, output_folder: str, subtitles: str, debug: bool = False):
"""
Downloads a single video to the designated output folder using yt-dlp.
The subtitles are embedded via commandline options.
"""
# Ensure the output folder exists
os.makedirs(output_folder, exist_ok=True)
# Build the output template.
output_template = os.path.join(output_folder, "%(title)s.%(ext)s")
command = [
"yt-dlp",
"-f",
"bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4",
"--embed-subs",
"--write-auto-subs",
"--sub-langs",
subtitles,
"-o",
output_template,
video_url,
]
if debug:
console.print("[blue]Running command:[/blue] " + " ".join(command))
try:
subprocess.run(command, check=True)
except subprocess.CalledProcessError as e:
console.print(f"[red]Download failed for {video_url}: {e}[/red]")
#######################
# INTERACTIVE VERIFICATION
#######################
def verify_candidates(candidates: List[Dict[str, Any]], available_categories: List[str]) -> List[Dict[str, Any]]:
"""
Presents a list of candidate videos with a suggested folder.
Allows the user to remove or modify entries interactively.
"""
console.print("\n[bold]Video Candidates for Download:[/bold]")
for idx, video in enumerate(candidates):
console.print(f"{idx + 1}. [green]{video['title']}[/green] -> [yellow]{video['destination']}[/yellow]")
console.print("\nEnter the numbers of any videos you want to remove (comma-separated), or press Enter to keep all:")
user_input = input("> ").strip()
remove_indices = []
if user_input:
try:
remove_indices = [int(i) - 1 for i in user_input.split(",") if i.strip().isdigit()]
except Exception:
console.print("[red]Invalid input. Continuing with all videos.[/red]")
# Remove videos (in reverse order so the indices remain valid)
for idx in sorted(remove_indices, reverse=True):
if 0 <= idx < len(candidates):
removed = candidates.pop(idx)
console.print(f"Removed: [green]{removed['title']}[/green]")
# Optionally, allow manual override of a destination folder
console.print("\nWould you like to modify any destination folders? Enter in the format: [video number]:[new folder] (comma separated for many) e.g., 2:Music,3:Documentaries. Press Enter to continue.")
user_input = input("> ").strip()
if user_input:
modifications = user_input.split(",")
for mod in modifications:
try:
idx_str, new_folder = mod.split(":", 1)
idx = int(idx_str) - 1
# Validate provided folder from available_categories or warn user.
if new_folder not in available_categories:
console.print(f"[yellow]Warning: Folder '{new_folder}' is not one of the current categories. It will be created.[/yellow]")
if 0 <= idx < len(candidates):
old_folder = candidates[idx]["destination"]
candidates[idx]["destination"] = new_folder
console.print(f"Changed [green]{candidates[idx]['title']}[/green] from '{old_folder}' to '{new_folder}'")
except Exception as e:
console.print(f"[red]Skipping invalid modification '{mod}': {e}[/red]")
return candidates
#######################
# MAIN FUNCTION
#######################
@click.command()
@click.option(
"--config",
default=CONFIG_PATH_DEFAULT,
help="Path to configuration file (default: config.json)",
)
@click.option(
"--override",
multiple=True,
help="Override mode. Provide one or multiple YouTube URLs to download directly.",
)
def main(config, override):
"""
CLI Tool for automating YouTube video downloads and organizing them into folders.
It checks for new videos from configured sources, categorizes them using an LLM,
presents an interactive verification, and downloads the videos accordingly.
"""
# Load configuration if not in override mode
if not override:
cfg = load_config(config)
sources = cfg.get("sources", [])
subtitles = cfg.get("subtitle_languages", "en,en-US,en*,en-*")
debug = cfg.get("debug", False)
media_folder = cfg.get("media_folder")
if not media_folder:
console.print("[red]The configuration must specify a 'media_folder'.[/red]")
sys.exit(1)
else:
# In override mode, use command-line provided URLs.
sources = [{"url": url, "last_synced": ""} for url in override]
# Use default subtitle languages (you may adjust as needed)
subtitles = "en,en-US,en*,en-*"
debug = False
# In override mode, require a media_folder via env var or config.
media_folder = os.environ.get("MEDIA_FOLDER")
if not media_folder:
console.print("[red]In override mode, please provide a media folder via the 'MEDIA_FOLDER' environment variable.[/red]")
sys.exit(1)
# Get current local categories by scanning the media folder.
available_categories = scan_media_folder(media_folder)
# Add "Misc" as a possible (default) category.
if "Misc" not in available_categories:
available_categories.append("Misc")
# For each source, fetch videos metadata
candidate_videos = []
for source in sources:
source_url = source.get("url")
last_synced_str = source.get("last_synced", "")
new_videos = fetch_videos_metadata(source_url, last_synced_str)
console.print(f"Found {len(new_videos)} new videos in {source_url}", style="blue")
for video in new_videos:
# Determine a suggested destination folder via our dummy LLM categorizer.
suggested_category = categorize_video(video["title"], available_categories)
video["destination"] = suggested_category
candidate_videos.append(video)
# If no candidates, exit.
if not candidate_videos:
console.print("[green]No new videos to download.[/green]")
sys.exit(0)
# Run an interactive verification step.
candidate_videos = verify_candidates(candidate_videos, available_categories)
if not candidate_videos:
console.print("[yellow]No videos selected for download. Exiting.[/yellow]")
sys.exit(0)
# Confirm with the user before commencing downloads.
console.print("\nReady to download the following videos:")
for vid in candidate_videos:
console.print(f"- [green]{vid['title']}[/green] -> [yellow]{vid['destination']}[/yellow]")
console.print("Proceed with download? (y/n)")
answer = input("> ").strip().lower()
if answer != "y":
console.print("[red]Download cancelled by user.[/red]")
sys.exit(0)
# Start downloading with progress UI.
console.print("\n[bold]Starting Downloads...[/bold]")
with Progress(
SpinnerColumn(),
"[progress.description]{task.description}",
BarColumn(),
"[progress.percentage]{task.percentage:>3.0f}%",
transient=True,
) as progress:
download_task = progress.add_task("Downloading videos...", total=len(candidate_videos))
for video in candidate_videos:
# Compute destination folder path by combining media_folder and the designated category.
dest_folder = os.path.join(media_folder, video["destination"])
progress.console.log(f"Downloading: {video['title']} to folder: {dest_folder}")
download_video(video["url"], dest_folder, subtitles, debug=debug)
progress.advance(download_task)
console.print("[green]All downloads completed![/green]")
# Update the "last_synced" parameter for each source in the config (if not in override mode)
if not override:
now_iso = datetime.datetime.now().isoformat()
for source in cfg.get("sources", []):
# For simplicity, set it to now. In a more exact implementation you might store the
# upload date of the newest video processed.
source["last_synced"] = now_iso
# Save the config back.
save_config(cfg, config)
console.print(f"[blue]Config file '{config}' updated with new last_synced values.[/blue]")
if __name__ == "__main__":
main()
Overview of What the Code Does
Configuration Management:
The script loads a JSON config file (by default config.json) that stores your YouTube sources, subtitle languages, debug flag, and the root media folder. (If running in override mode, the script requires that you supply a media folder via the MEDIA_FOLDER environment variable.)
Local Media Folder Scanning:
It scans the local media directory for subdirectories (representing your video categories) and adds a default “Misc” folder if needed.
Fetching Metadata:
For each source (channel/playlist), the script calls yt-dlp (using its Python API) to extract video metadata and filters out videos that were uploaded before the source’s "last_synced" date.
Categorization:
Each new video is “categorized” by a dummy LLM function that uses simple text matching. The result is cached in the in‑memory dictionary CATEGORY_CACHE.
Interactive Verification:
The candidate videos (with their suggested destination folders) are then displayed to the user. The user can remove entries or manually change destination folders via an interactive CLI prompt.
Downloading:
After confirmation, the script downloads the videos via a subprocess call to the yt-dlp executable (using your preferred command-line options) into the designated folders. A Rich‑powered progress bar displays the download progress.
Updating Config:
Once downloads complete, the script updates each source’s “last_synced” date in the config file (if not in override mode) and then writes the changes back to disk.
Override Mode:
If one or more YouTube URLs are provided using the --override option, those URLs are processed directly (bypassing the config-sourced list).
How to Run the Script
Place your configuration in a file named config.json (or another file and pass its path via the --config parameter). For example, a minimal config.json might look like:
This code should serve as a solid starting point that meets your requirements. Feel free to ask if you need further modifications or additional features. Happy coding!