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.
Okay, this sounds like a fantastic and very practical project! Automating media organization is a common desire, and leveraging an LLM for categorization based on existing structure is a clever approach.
Let's break down the overview from both a UX and technological perspective.
Project Name Idea:yt-sorter (or something similar)
I. User Experience (UX) Overview
Configuration:
The user manages a central configuration file (e.g., config.yaml or config.json) located in a standard place (e.g., ~/.config/yt-sorter/config.yaml or next to the script).
This file contains:
The root path to their local media folder (e.g., /mnt/media/youtube_archive).
A list of sources, each with:
url: The YouTube Channel or Playlist URL.
type: Explicitly 'channel' or 'playlist'.
last_synced: An ISO 8601 timestamp string (e.g., "2023-10-27T10:00:00Z"). Initially empty or a very old date for new sources.
Global download settings:
subtitle_langs: List of language codes (e.g., ["en", "en-US", "en*", "en-*"]).
yt_dlp_format: The format string (e.g., "bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4").
LLM settings (API key potentially handled via environment variables for security):
llm_model: Name of the model to use (e.g., "gpt-4", "claude-3-opus").
llm_enable_cache: true or false.
debug_log: true or false.
Standard Workflow Execution:
The user runs the command, e.g., yt-sorter run.
Phase 1: Checking Sources & Categorization
The CLI outputs status messages like "Checking source [Channel Name/Playlist Title]...".
It fetches metadata for videos newer than last_synced for each source.
It generates the file tree representation of the media folder.
For each new video, it calls the LLM (using cached results if possible) to get a suggested destination folder relative to the media root. It prints messages like "Categorizing '[Video Title]'...".
Phase 2: Verification
The CLI presents a list of videos found, along with their suggested destination folders. Example:
code
Found 5 new videos:
[1] Video Title A (Channel X) -> [Suggested: Category/SubCategoryA]
[2] Another Video (Playlist Y) -> [Suggested: Tech/SoftwareDev]
[3] Cooking Special (Channel Z) -> [Suggested: Hobbies/Cooking]
[4] Mis-categorized Vid? (Channel X) -> [Suggested: Entertainment/Clips]
[5] Yet Another Vid (Playlist Y) -> [Suggested: Tech/Hardware]
Options:
(d) Download All Approved (r <index>) Remove video (m <index>) Modify destination
(q) Quit
Enter command:
The user can:
Type d to proceed with downloading the current list.
Type r 1 4 to remove videos 1 and 4 from the download queue.
Type m 3 to modify the destination for video 3. This could trigger sub-options:
(r) Re-run LLM categorization
(s) Select folder manually (presents a list/tree of existing folders or allows typing a path)
(c) Cancel modification
Type q to exit without downloading.
Phase 3: Downloading
If the user proceeds with downloading, the CLI shows a progress display. This could be:
Overall progress (e.g., Downloading video 2 of 3...).
Current yt-dlp output for the active download.
Clear indicators of success, warnings (e.g., subtitles not found), or failures for each video.
Example:
code
Downloading 3 videos...
[1/3] Downloading 'Video Title A'... [yt-dlp output stream] -> Success (Saved to /mnt/media/youtube_archive/Category/SubCategoryA/Video Title A.mp4)
[2/3] Downloading 'Another Video'... [yt-dlp output stream] -> Warning: Subtitles 'en' not found. (Saved to /mnt/media/youtube_archive/Tech/SoftwareDev/Another Video.mp4)
[3/3] Downloading 'Cooking Special'... [yt-dlp output stream] -> ERROR: [yt-dlp error message]
Download Summary: 2 Succeeded (1 with warnings), 1 Failed.
Updating last_synced dates in config... Done.
Post-Download: The script updates the last_synced date in the config file for the sources from which videos were successfully processed (or attempted).
Ad-hoc Workflow Execution:
The user runs yt-sorter download <URL1> <URL2> ...
These URLs can be direct video links, channel links, or playlist links.
The script skips the config file's source list and last_synced checks.
It fetches metadata for all provided video URLs, or all videos within the provided channel/playlist URLs.
It proceeds directly to the Categorization -> Verification -> Downloading phases as described above (using the media folder structure from the config file for categorization context).
It does not update any last_synced dates in the config file upon completion.
II. Technological Approach Overview
Core Language/Framework: Python 3.x. Use a CLI framework like Typer or Click for easy command structure, argument parsing, and help messages.
Configuration: Use PyYAML for YAML parsing or Python's built-in json module. Store config in a user-specific location (appdirs library can help find appropriate paths like ~/.config/).
YouTube Interaction (yt-dlp):
Metadata Fetching: Use subprocess.run to execute yt-dlp. Key flags:
--flat-playlist: Avoids extracting info for every video in a large playlist initially. Get basic list first.
--print-json or -J: Output metadata for each video as a JSON object. Parse this JSON output in Python.
--dateafter YYYYMMDD: Filter videos uploaded after the last_synced date. Convert the ISO date from config to YYYYMMDD.
For channels, you might need to get the "uploads" playlist ID first or use yt-dlp's direct channel URL support.
Downloading: Use subprocess.run again, constructing the command dynamically based on config and verification choices:
Pass the specific video URL.
-o "/path/to/target/folder/%(title)s.%(ext)s": Set the output template, ensuring the filename is the video title and it goes to the correct categorized folder.
-f "...": Use the format string from config.
--embed-subs --write-auto-subs --sub-langs "...": Use subtitle settings from config.
Capture stdout and stderr to display progress and detect errors.
Folder Structure Representation:
Use Python's os.walk or pathlib.Path.rglob to traverse the specified media root directory.
Generate a simplified text representation. Options:
Limit depth or number of example files per folder if the structure is huge, to avoid exceeding LLM context limits.
Clarifying Questions:
Folder Structure Size: How large/deep is your existing folder structure? Could it potentially exceed LLM context limits if represented fully? (We might need strategies like summarizing or limiting depth if it's enormous).
LLM Choice: Do you have a preferred LLM provider/model in mind (OpenAI, Anthropic, Gemini, local model)? This affects API interaction and potential costs.
Handling Categorization Failures: What should happen if the LLM cannot determine a category or gives a nonsensical answer? Should it default to a specific 'unsorted' folder, or always require manual intervention during verification?
Duplicate Video Handling: How should the script behave if a video to be downloaded seems to already exist in the target folder (based on filename)? Skip, overwrite, rename? ( yt-dlp has options like --no-overwrites or --download-archive that might be relevant, but we're determining the path before download). A simple check os.path.exists before download is probably best.
last_synced Update Granularity: Should last_synced be updated for a source only if all its new videos are successfully downloaded, or after the attempt to download them (even if some fail)? Updating after the attempt seems more robust to prevent repeatedly trying failed downloads.
This overview should provide a solid foundation. Let me know your thoughts on the approach and answers to the clarifying questions, and we can then dive deeper into specific implementation details.
Okay, let's structure this CLI tool. We'll use Python with Typer for the CLI, PyYAML for config, subprocess for yt-dlp, rich for UI elements, and the openai library for LLM interaction (you can swap this for Anthropic or others).
[tool.poetry]
name = "yt-sorter"
version = "0.1.0"
description = "Automated YouTube downloader and sorter using yt-dlp and LLM categorization."
authors = ["Your Name <you@example.com>"]
readme = "README.md"
[tool.poetry.dependencies]
python = "^3.9" # Need zoneinfo or backports.zoneinfo
typer = {extras = ["all"], version = "^0.9.0"} # Includes rich
pyyaml = "^6.0"
openai = "^1.0.0" # Or anthropic, etc.
python-dotenv = "^1.0.0" # To load API keys from .env
appdirs = "^1.4.4" # To find user config directory
[tool.poetry.scripts]
yt-sorter = "yt_sorter.main:app"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
Install dependencies using Poetry: poetry install
We'll use .env file for the API key: Create a file named .env in the project root with OPENAI_API_KEY=your_api_key_here.
2. Example Configuration (example_config.yaml)
yaml
# Root directory for your media archive
media_root: "/path/to/your/youtube/archive"
# List of sources to sync regularly
sources:
- url: "https://www.youtube.com/channel/UC..."
type: "channel"
last_synced: "2023-01-01T00:00:00Z" # Use ISO 8601 format (UTC recommended)
- url: "https://www.youtube.com/playlist?list=PL..."
type: "playlist"
last_synced: null # Null or very old date means sync everything
# Global download settings
download:
# yt-dlp format string
format: "bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4"
# Subtitle languages (order matters for preference)
subtitle_langs:
- "en"
- "en-US"
- "en*" # Generic English variants
- "ja" # Example: Add Japanese
# LLM settings for categorization
llm:
# Model name (e.g., gpt-3.5-turbo, gpt-4, claude-3-opus-20240229)
model: "gpt-3.5-turbo"
# Enable LLM provider's caching (if supported) - often based on exact prompt
enable_cache: true
# Max depth for directory tree representation sent to LLM
max_tree_depth: 5
# Max example files per directory in the representation
max_files_per_dir: 3
# Enable verbose debug logging to console and potentially a file
debug_log: false
3. Core Logic Implementation
(Note: This is a conceptual implementation. Error handling, logging, and specific details might need refinement. We'll keep it moderately detailed.)
yt_sorter/utils.py
python
import os
import re
from pathlib import Path
from datetime import datetime, timezone, date
def get_config_path():
"""Gets the path to the configuration file."""
from appdirs import user_config_dir
config_dir = Path(user_config_dir("yt-sorter", "YourAppName")) # Replace YourAppName if desired
config_dir.mkdir(parents=True, exist_ok=True)
return config_dir / "config.yaml"
def generate_dir_tree(root_path: Path, max_depth: int, max_files_per_dir: int) -> str:
"""Generates a string representation of the directory tree."""
tree_lines = []
root_depth = len(root_path.parts)
for dirpath, dirnames, filenames in os.walk(root_path):
current_path = Path(dirpath)
depth = len(current_path.parts) - root_depth
if depth > max_depth:
# Prune deeper directories
dirnames[:] = []
continue
indent = " " * depth
tree_lines.append(f"{indent}{current_path.name}/")
# Limit number of files shown
files_to_show = sorted(filenames)[:max_files_per_dir]
file_indent = " " * (depth + 1)
for filename in files_to_show:
tree_lines.append(f"{file_indent}{filename}")
if len(filenames) > max_files_per_dir:
tree_lines.append(f"{file_indent}...")
return "\n".join(tree_lines)
def sanitize_filename(filename: str) -> str:
"""Removes or replaces characters invalid for filenames."""
# Remove characters invalid in most filesystems
sanitized = re.sub(r'[\\/*?:"<>|]', "", filename)
# Replace colons often found in titles (optional, depends on preference)
sanitized = sanitized.replace(":", " -")
# Trim leading/trailing whitespace
sanitized = sanitized.strip()
# Prevent empty filenames
if not sanitized:
sanitized = "untitled"
return sanitized
def format_datetime_for_yt_dlp(iso_datetime_str: str | None) -> str | None:
"""Converts ISO 8601 string to YYYYMMDD for yt-dlp --dateafter."""
if not iso_datetime_str:
return None
try:
dt = datetime.fromisoformat(iso_datetime_str.replace('Z', '+00:00'))
# Ensure it's aware for correct comparison if needed, though yt-dlp just needs date
dt_aware = dt.astimezone(timezone.utc)
return dt_aware.strftime('%Y%m%d')
except ValueError:
# Handle invalid format gracefully
return None # Or raise an error
def get_current_utc_iso_string() -> str:
"""Returns the current time in UTC ISO 8601 format."""
return datetime.now(timezone.utc).isoformat(timespec='seconds').replace('+00:00', 'Z')
yt_sorter/config.py
python
yt_sorter/youtube.py
python
yt_sorter/categorizer.py
python
yt_sorter/verification.py
python
yt_sorter/main.py
python
4. Running the Tool
Install:
Ensure you have Python (>=3.9 recommended) and Poetry installed.
Navigate to the yt-sorter project directory in your terminal.
Run poetry install.
Make sure yt-dlp is installed and accessible in your system's PATH (pip install -U yt-dlp or use your package manager).
Create the .env file with your OPENAI_API_KEY.
Configure:
Run poetry run yt-sorter create-config. This will tell you where the config.yaml file is created (usually ~/.config/yt-sorter/config.yaml on Linux/macOS).
Edit this config.yaml file:
Crucially, set media_root to your actual media archive path.
Add your channel/playlist URLs under sources. Set last_synced to an old date or null for the first run.
Adjust download and llm settings as needed.
Execute:
Standard Sync:poetry run yt-sorter run
Ad-hoc Download:poetry run yt-sorter download "URL1" "URL2"
Force Rescan:poetry run yt-sorter run --force-rescan
Skip Verification:poetry run yt-sorter run -y or poetry run yt-sorter download URL -y
Debug Mode: Set debug_log: true in config.yaml and run normally.
This provides a comprehensive starting point. Remember to test thoroughly, especially the LLM categorization and path handling. You might need to refine the LLM prompts, tree generation limits, or error handling based on your specific needs and observations.
Calculate a hash (e.g., SHA256) of this representation for caching purposes (optional but good).
LLM Interaction:
Use a client library for the chosen LLM service (e.g., openai, anthropic).
Prompt Construction:
code
You are an expert file organizer. Based on the following directory structure, determine the single best folder path for a video with the given title. The structure represents an archive of YouTube videos. Output only the relative folder path from the root, or "." if it belongs in the root (unlikely).
Existing Folder Structure:
---
[Insert Folder Structure Representation Here]
---
Video Title: "[Insert Video Title Here]"
Destination Folder Path:
Caching:
LLM Service Cache: Rely on the provider's built-in caching if available (often based on exact prompt matching).
Local Cache: Implement a simple Python dictionary or a file-based cache (e.g., using shelve or a JSON file) mapping (video_title, structure_representation_hash) to predicted_folder_path. Check this cache before calling the LLM API.
Verification UI:
Use standard Python print and input.
Libraries like rich can create much nicer tables and formatted output. inquirer or prompt_toolkit can create interactive menus/prompts for modification steps.
Download Progress & Error Handling:
Monitor the yt-dlp subprocess's output streams line by line.
Use rich.progress or tqdm for overall progress bars.
Parse yt-dlp output for known error patterns or success indicators. Log errors clearly. Handle subprocess exceptions (e.g., command not found).
Handle LLM API errors (rate limits, connection issues, invalid keys).
Handle file system errors (permissions, disk full).
State Management:
Load config at the start.
Build the list of videos to download/categorize in memory.
Allow modification of this in-memory list during verification.
Update the config file (last_synced dates) only after download attempts for a source are complete, writing back to the config file atomically if possible (write to temp file, then rename).
Ad-hoc Mode Logic: Use the CLI framework (Typer/Click) to detect if positional URL arguments are provided. If so, switch to the ad-hoc workflow, bypassing the config source loading and last_synced logic, but still loading other config values (media root, LLM settings, download settings).
import yaml
from pathlib import Path
from typing import Dict, Any, Optional
from .utils import get_config_path
DEFAULT_CONFIG = {
"media_root": None,
"sources": [],
"download": {
"format": "bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4",
"subtitle_langs": ["en", "en-US", "en*", "en-*"]
},
"llm": {
"model": "gpt-3.5-turbo",
"enable_cache": True,
"max_tree_depth": 5,
"max_files_per_dir": 3
},
"debug_log": False
}
def load_config() -> Dict[str, Any]:
"""Loads configuration from the YAML file."""
config_path = get_config_path()
if not config_path.exists():
print(f"Configuration file not found at {config_path}. Please create it.")
print("You can use 'yt-sorter create-config' to generate a default one.")
# Or create a default one automatically:
# save_config(DEFAULT_CONFIG)
# print(f"Default config file created at {config_path}. Please edit it.")
raise FileNotFoundError(f"Config file not found: {config_path}")
try:
with open(config_path, 'r', encoding='utf-8') as f:
user_config = yaml.safe_load(f)
# Simple merge strategy (user config overrides defaults)
config = DEFAULT_CONFIG.copy()
# Deep update for nested dictionaries
for key, value in user_config.items():
if isinstance(value, dict) and isinstance(config.get(key), dict):
config[key].update(value)
else:
config[key] = value
# Basic validation
if not config.get("media_root"):
raise ValueError("Config error: 'media_root' must be set.")
if not Path(config["media_root"]).is_dir():
raise ValueError(f"Config error: 'media_root' ({config['media_root']}) is not a valid directory.")
if not isinstance(config.get("sources"), list):
raise ValueError("Config error: 'sources' must be a list.")
# Ensure sources have required keys (add defaults if missing)
for i, source in enumerate(config["sources"]):
if not source.get("url") or not source.get("type"):
raise ValueError(f"Config error: Source #{i+1} is missing 'url' or 'type'.")
if source["type"] not in ["channel", "playlist"]:
raise ValueError(f"Config error: Source #{i+1} has invalid 'type': {source['type']}. Must be 'channel' or 'playlist'.")
if "last_synced" not in source:
source["last_synced"] = None # Default to sync all
return config
except (yaml.YAMLError, ValueError, FileNotFoundError) as e:
print(f"Error loading configuration: {e}")
raise # Re-raise to stop execution
def save_config(config_data: Dict[str, Any]):
"""Saves the configuration data back to the YAML file."""
config_path = get_config_path()
temp_path = config_path.with_suffix(".yaml.tmp")
try:
with open(temp_path, 'w', encoding='utf-8') as f:
yaml.dump(config_data, f, default_flow_style=False, sort_keys=False, allow_unicode=True)
# Atomic rename
os.replace(temp_path, config_path)
except (IOError, yaml.YAMLError) as e:
print(f"Error saving configuration to {config_path}: {e}")
if temp_path.exists():
os.remove(temp_path) # Clean up temp file
def create_default_config():
"""Creates a default config file if one doesn't exist."""
config_path = get_config_path()
if config_path.exists():
print(f"Configuration file already exists at {config_path}.")
return False
try:
# Ensure the directory exists first
config_path.parent.mkdir(parents=True, exist_ok=True)
save_config(DEFAULT_CONFIG)
print(f"Default configuration file created at: {config_path}")
print("Please review and edit it before running the main command.")
return True
except Exception as e:
print(f"Failed to create default config file: {e}")
return False
import subprocess
import json
import logging
from typing import List, Dict, Any, Optional
from pathlib import Path
from .utils import format_datetime_for_yt_dlp, sanitize_filename
logger = logging.getLogger(__name__)
def get_video_metadata(url: str, date_after_str: Optional[str] = None) -> List[Dict[str, Any]]:
"""Fetches metadata for videos from a URL (channel/playlist/single video) using yt-dlp."""
command = [
'yt-dlp',
'--print-json', # Output metadata as JSON lines
'--flat-playlist', # Don't extract info for every video in playlist initially (faster)
'--no-warnings',
'--ignore-errors', # Skip videos that cause errors (like private/deleted)
url
]
if date_after_str:
date_filter = format_datetime_for_yt_dlp(date_after_str)
if date_filter:
command.extend(['--dateafter', date_filter])
else:
logger.warning(f"Invalid date format for 'last_synced': {date_after_str}. Fetching all videos.")
logger.debug(f"Executing yt-dlp metadata command: {' '.join(command)}")
try:
process = subprocess.run(command, capture_output=True, text=True, check=True, encoding='utf-8')
videos = []
for line in process.stdout.strip().split('\n'):
if line:
try:
video_data = json.loads(line)
# Filter out entries that are not actual videos (e.g., playlist headers)
if video_data.get('_type', 'video') == 'video':
# Add useful fields if missing (yt-dlp might omit them with --flat-playlist)
if 'title' not in video_data: video_data['title'] = 'Unknown Title'
if 'webpage_url' not in video_data: video_data['webpage_url'] = video_data.get('url') # Fallback
if 'channel' not in video_data: video_data['channel'] = 'Unknown Channel'
if 'upload_date' not in video_data: video_data['upload_date'] = None # YYYYMMDD format if available
videos.append(video_data)
except json.JSONDecodeError:
logger.error(f"Failed to parse JSON line: {line[:100]}...") # Log snippet
logger.info(f"Found {len(videos)} potential videos for URL: {url}" + (f" after {date_after_str}" if date_after_str else ""))
return videos
except subprocess.CalledProcessError as e:
logger.error(f"yt-dlp metadata fetch failed for {url}. Return code: {e.returncode}")
logger.error(f"Stderr: {e.stderr}")
return []
except FileNotFoundError:
logger.critical("yt-dlp command not found. Make sure yt-dlp is installed and in your system's PATH.")
raise
except Exception as e:
logger.error(f"An unexpected error occurred during metadata fetch for {url}: {e}")
return []
def download_video(
video_info: Dict[str, Any],
target_dir: Path,
download_format: str,
subtitle_langs: List[str],
progress_hook=None # Optional hook for progress bars
) -> Dict[str, Any]:
"""Downloads a single video using yt-dlp."""
video_url = video_info.get('webpage_url') or video_info.get('url')
if not video_url:
return {"status": "error", "message": "Missing video URL"}
video_title = video_info.get('title', 'Unknown Title')
sanitized_title = sanitize_filename(video_title)
# yt-dlp handles the extension based on format, we just provide the name template
output_template = target_dir / f"{sanitized_title}.%(ext)s"
# Ensure target directory exists
target_dir.mkdir(parents=True, exist_ok=True)
command = [
'yt-dlp',
'-f', download_format,
'-o', str(output_template),
'--no-warnings',
'--ignore-errors', # Should ideally not hit this for a single video dl
# '--no-overwrites', # Prevent overwriting existing files
# '--download-archive', archive_file # Alternative way to track downloaded files
video_url
]
# Add subtitle options if requested
if subtitle_langs:
command.extend(['--embed-subs', '--write-auto-subs'])
# Join langs with comma for yt-dlp
sub_langs_str = ",".join(subtitle_langs)
command.extend(['--sub-langs', sub_langs_str])
logger.debug(f"Executing yt-dlp download command: {' '.join(command)}")
result = {"status": "pending", "message": "", "final_path": None}
try:
# Use Popen to potentially capture output line-by-line for progress later
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding='utf-8')
stdout_lines = []
stderr_lines = []
subtitle_warning = False
# Read output streams
while True:
output = process.stdout.readline() if process.stdout else None
if output == '' and process.poll() is not None:
break
if output:
line = output.strip()
stdout_lines.append(line)
logger.debug(f"[yt-dlp stdout] {line}")
# Example: Look for subtitle download status (might need refinement)
if "has no subtitles" in line.lower() or "requested format not available" in line.lower() :
if any(lang in line for lang in subtitle_langs): # Check if it's about our requested langs
subtitle_warning = True
if progress_hook:
progress_hook(line) # Pass line to progress display
# Capture stderr after process finishes
stderr_output = process.stderr.read() if process.stderr else ""
stderr_lines = stderr_output.strip().split('\n')
for line in stderr_lines:
logger.debug(f"[yt-dlp stderr] {line}")
retcode = process.poll()
if retcode == 0:
result["status"] = "success"
# Try to find the actual downloaded filename (yt-dlp might change extension)
# This is tricky, rely on yt-dlp's output or check the directory
# Simplest: Assume the first file matching the sanitized title is it.
potential_files = list(target_dir.glob(f"{sanitized_title}.*"))
if potential_files:
result["final_path"] = potential_files[0]
else:
# Fallback if glob fails (maybe yt-dlp used a different final name)
result["final_path"] = "Unknown path in " + str(target_dir)
if subtitle_warning:
result["message"] = "Downloaded successfully, but subtitles might be missing or in a different format."
result["status"] = "warning" # Indicate partial success
else:
result["message"] = f"Downloaded successfully to {result['final_path']}"
else:
result["status"] = "error"
result["message"] = f"yt-dlp download failed with return code {retcode}."
# Include some stderr for context
error_context = "\n".join(stderr_lines[-5:]) # Last 5 lines of stderr
result["message"] += f"\nError context:\n{error_context}"
logger.error(result["message"])
except FileNotFoundError:
logger.critical("yt-dlp command not found. Make sure yt-dlp is installed and in your system's PATH.")
result = {"status": "error", "message": "yt-dlp not found."}
# Don't raise here, let the main loop handle the error status
except Exception as e:
logger.error(f"An unexpected error occurred during download for {video_url}: {e}")
result = {"status": "error", "message": f"Unexpected error: {e}"}
return result
import os
import logging
from pathlib import Path
from typing import Dict, Optional, Tuple
from openai import OpenAI, RateLimitError, APIError # Use 'anthropic' for Claude etc.
from .utils import generate_dir_tree
logger = logging.getLogger(__name__)
# --- LLM Interaction ---
# Store API key in environment variable: OPENAI_API_KEY (or ANTHROPIC_API_KEY etc.)
# Load .env file if present
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass # python-dotenv not installed
# Initialize client (consider doing this only when needed)
try:
# Ensure API key is available
if not os.getenv("OPENAI_API_KEY"):
logger.warning("OPENAI_API_KEY environment variable not set. LLM categorization will fail.")
llm_client = None
else:
llm_client = OpenAI() # Add api_key=... if not using env var
except Exception as e:
logger.error(f"Failed to initialize OpenAI client: {e}")
llm_client = None
# Simple in-memory cache for LLM results during a single run
llm_cache: Dict[Tuple[str, str], str] = {}
def get_category_suggestion(
video_title: str,
media_root: Path,
llm_config: Dict,
cached_tree_str: Optional[str] = None
) -> str:
"""Gets a category suggestion from the LLM based on video title and directory structure."""
if not llm_client:
logger.error("LLM client not initialized. Cannot get category suggestion.")
return "." # Default to root/unsorted
model = llm_config.get("model", "gpt-3.5-turbo")
use_cache = llm_config.get("enable_cache", True)
max_depth = llm_config.get("max_tree_depth", 5)
max_files = llm_config.get("max_files_per_dir", 3)
# Generate or reuse directory tree string
if cached_tree_str is None:
dir_tree_str = generate_dir_tree(media_root, max_depth, max_files)
else:
dir_tree_str = cached_tree_str
# Use a tuple of (title, tree_structure) as cache key
cache_key = (video_title, dir_tree_str)
if use_cache and cache_key in llm_cache:
logger.debug(f"LLM Cache hit for title: '{video_title}'")
return llm_cache[cache_key]
prompt = f"""You are an expert file organizer. Based on the following directory structure of an existing YouTube video archive, determine the single best relative folder path for a new video with the given title.
Existing Folder Structure (relative to media root '{media_root.name}'):
---
{dir_tree_str}
---
Video Title: "{video_title}"
Output ONLY the relative folder path (e.g., "Category/SubCategory" or "Topic"). Use forward slashes (/) as separators. If no existing folder seems appropriate based *only* on the title and the structure provided, output "." to indicate it should go in the root or needs manual sorting. Do not invent new top-level categories unless the title strongly implies a completely new subject not covered by the structure. Prefer existing folders where possible.
Destination Folder Path:"""
logger.debug(f"Sending prompt to LLM (model: {model}) for title: '{video_title}'")
# logger.debug(f"Prompt content:\n{prompt}") # Uncomment for verbose debugging
try:
response = llm_client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "You are an expert file organizer."},
{"role": "user", "content": prompt}
],
temperature=0.2, # Lower temperature for more deterministic categorization
max_tokens=50 # Path shouldn't be too long
)
suggested_path = response.choices[0].message.content.strip()
# Basic cleaning of the LLM output
suggested_path = suggested_path.replace("\\", "/") # Ensure forward slashes
if suggested_path.startswith("/"):
suggested_path = suggested_path[1:]
if suggested_path.endswith("/"):
suggested_path = suggested_path[:-1]
# Remove potential quotes if LLM included them
suggested_path = suggested_path.strip('\'"')
logger.info(f"LLM suggested path for '{video_title}': '{suggested_path}'")
# Store in cache if caching enabled
if use_cache:
llm_cache[cache_key] = suggested_path
return suggested_path
except RateLimitError:
logger.warning("LLM rate limit exceeded. Please try again later.")
return "." # Fallback on error
except APIError as e:
logger.error(f"LLM API error: {e}")
return "." # Fallback on error
except Exception as e:
logger.error(f"An unexpected error occurred during LLM interaction: {e}")
return "." # Fallback on error
def clean_and_validate_path(suggested_path: str, media_root: Path) -> str:
"""Cleans the suggested path and performs basic validation."""
# Remove leading/trailing slashes/spaces
cleaned = suggested_path.strip('/\\ ')
# Prevent path traversal attacks (though LLM shouldn't generate '..')
if ".." in cleaned:
logger.warning(f"Invalid characters ('..') found in suggested path: '{suggested_path}'. Defaulting to root.")
return "."
# Optional: Check if the path contains invalid filesystem characters (beyond sanitizing the final filename)
# This depends on the OS, but generally avoid <>:"/\\|?*
# For simplicity, we might rely on `os.makedirs` to fail later if invalid chars exist in folder names.
# Do not create the directory here, just validate the path string format
# We could check if the path is *potentially* valid under media_root
# e.g., `(media_root / cleaned).resolve().is_relative_to(media_root.resolve())`
# but this might be overkill.
return cleaned # Return the cleaned relative path string
import typer
from rich.console import Console
from rich.table import Table
from typing import List, Dict, Any, Optional
from pathlib import Path
import time
from .categorizer import get_category_suggestion, clean_and_validate_path
console = Console()
def select_folder_manually(media_root: Path) -> Optional[str]:
"""Allows user to manually select or enter a folder path."""
console.print("\n[bold cyan]Select Destination Folder:[/bold cyan]")
existing_folders = sorted([p.relative_to(media_root) for p in media_root.rglob("*") if p.is_dir()])
existing_folders.insert(0, Path(".")) # Add root option
if not existing_folders:
console.print("[yellow]No existing subfolders found in media root.[/yellow]")
table = Table(title="Existing Folders", show_header=True, header_style="bold magenta")
table.add_column("Index", style="dim", width=5)
table.add_column("Relative Path")
for i, folder in enumerate(existing_folders):
table.add_row(str(i), str(folder))
console.print(table)
console.print("Enter the [bold]index[/bold] of the desired folder, or type a [bold]new relative path[/bold] (e.g., 'NewFolder/SubFolder'), or 'c' to cancel.")
while True:
choice = typer.prompt("Your choice").strip()
if choice.lower() == 'c':
return None
try:
# Try interpreting as index first
index = int(choice)
if 0 <= index < len(existing_folders):
return str(existing_folders[index])
else:
console.print("[red]Invalid index.[/red]")
except ValueError:
# Interpret as a new path string
new_path = clean_and_validate_path(choice, media_root) # Use clean path
if typer.confirm(f"Create or use path: '{new_path}'?"):
return new_path
# If user doesn't confirm, loop back to ask again
def run_verification(
videos_to_process: List[Dict[str, Any]],
config: Dict[str, Any],
cached_tree_str: str
) -> List[Dict[str, Any]]:
"""Interactive verification loop."""
if not videos_to_process:
console.print("[green]No new videos found or remaining to process.[/green]")
return []
media_root = Path(config["media_root"])
current_videos = list(videos_to_process) # Create a mutable copy
while True:
console.print("\n[bold yellow]--- Video Download Plan ---[/bold yellow]")
if not current_videos:
console.print("[green]No videos remaining in the plan.[/green]")
break
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Index", style="dim", width=5)
table.add_column("Video Title", style="cyan", no_wrap=False)
table.add_column("Source", style="blue", width=20)
table.add_column("Suggested Path", style="green", no_wrap=False)
for i, video_data in enumerate(current_videos):
title = video_data.get('title', 'Unknown Title')
source_info = video_data.get('_source_nickname', video_data.get('channel', 'Unknown')) # Add nickname if available
path = video_data.get('target_rel_path', '.')
table.add_row(str(i), title, source_info, path)
console.print(table)
console.print("\n[bold]Options:[/bold]")
console.print(" [d] Download Approved Videos")
console.print(" [r <index1> <index2>...] Remove video(s) by index")
console.print(" [m <index>] Modify destination for video by index")
console.print(" [q] Quit without downloading")
action = typer.prompt("Enter command").lower().strip()
parts = action.split()
command = parts[0]
try:
if command == 'd':
if not current_videos:
console.print("[yellow]No videos left to download.[/yellow]")
continue
console.print(f"[bold green]Proceeding with download for {len(current_videos)} videos...[/bold green]")
# Add a small delay for user to see the message
time.sleep(1)
return current_videos # Return the approved list
elif command == 'q':
console.print("[yellow]Quitting without download.[/yellow]")
return [] # Return empty list signifies cancellation
elif command == 'r':
if len(parts) < 2:
console.print("[red]Usage: r <index1> [index2] ...[/red]")
continue
indices_to_remove = sorted([int(i) for i in parts[1:]], reverse=True)
removed_count = 0
for index in indices_to_remove:
if 0 <= index < len(current_videos):
removed_video = current_videos.pop(index)
console.print(f"Removed: '{removed_video.get('title', 'Unknown Title')}'")
removed_count += 1
else:
console.print(f"[yellow]Invalid index skipped: {index}[/yellow]")
if removed_count == 0:
console.print("[yellow]No valid indices provided for removal.[/yellow]")
elif command == 'm':
if len(parts) != 2:
console.print("[red]Usage: m <index>[/red]")
continue
index_to_modify = int(parts[1])
if not (0 <= index_to_modify < len(current_videos)):
console.print("[red]Invalid index.[/red]")
continue
video_data = current_videos[index_to_modify]
console.print(f"\nModifying destination for: '[bold cyan]{video_data.get('title', 'Unknown Title')}[/bold cyan]'")
console.print("Current suggested path: ", video_data.get('target_rel_path', '.'))
console.print("Options: [r] Re-run LLM categorization, [s] Select folder manually, [c] Cancel modification")
mod_choice = typer.prompt("Modification choice").lower().strip()
new_path_str = None
if mod_choice == 'r':
console.print("Re-running LLM categorization...")
# Rerun LLM - pass cached tree string for efficiency
new_path_str = get_category_suggestion(
video_data['title'],
media_root,
config['llm'],
cached_tree_str=cached_tree_str
)
new_path_str = clean_and_validate_path(new_path_str, media_root)
console.print(f"LLM suggested new path: '{new_path_str}'")
elif mod_choice == 's':
selected_path = select_folder_manually(media_root)
if selected_path is not None:
new_path_str = selected_path
else:
console.print("Manual selection cancelled.")
elif mod_choice == 'c':
console.print("Modification cancelled.")
else:
console.print("[red]Invalid modification choice.[/red]")
# Update the path if a new one was determined
if new_path_str is not None:
video_data['target_rel_path'] = new_path_str
console.print(f"Updated path for index {index_to_modify} to: '{new_path_str}'")
else:
console.print("[red]Invalid command.[/red]")
except ValueError:
console.print("[red]Invalid index number provided.[/red]")
except Exception as e:
console.print(f"[bold red]An error occurred: {e}[/bold red]")
logger.exception("Error during verification loop:")
return [] # Should not be reached if loop breaks correctly
import typer
import logging
from pathlib import Path
from typing import List, Optional, Dict, Any
from rich.logging import RichHandler
from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn, TimeElapsedColumn, TaskProgressColumn
from rich.console import Console
import time
import os # For os.replace used in save_config
from . import config as cfg
from . import youtube as yt
from . import categorizer as cat
from . import verification as ver
from .utils import generate_dir_tree, get_current_utc_iso_string, sanitize_filename
# --- Setup Logging ---
logging.basicConfig(
level="INFO", format="%(message)s", datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True)]
)
logger = logging.getLogger(__name__)
console = Console()
# --- Typer App ---
app = typer.Typer(help="Automated YouTube downloader and sorter using yt-dlp and LLM categorization.")
# --- Helper for Download Process ---
def process_downloads(
videos_for_download: List[Dict[str, Any]],
config: Dict[str, Any],
update_sync_times: bool = False
) -> Dict[str, Dict[str, Any]]:
"""Handles the download loop with progress display."""
media_root = Path(config["media_root"])
download_settings = config["download"]
successful_downloads = {} # Store source_url -> latest_successful_video_info
failed_downloads = []
console.print(f"\n[bold blue]Starting download of {len(videos_for_download)} videos...[/bold blue]")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TaskProgressColumn(), # Percentage
TimeElapsedColumn(),
TextColumn("[bold green]{task.fields[status]}"), # Custom status field
console=console,
transient=False # Keep progress visible after completion
) as progress:
# Shared progress state for yt-dlp output
yt_dlp_output_lines = []
def progress_hook(line):
# Keep only last few lines of yt-dlp output if needed for display
yt_dlp_output_lines.append(line)
if len(yt_dlp_output_lines) > 3:
yt_dlp_output_lines.pop(0)
# Could potentially parse percentage here, but complex.
# For now, just show it's running.
download_task = progress.add_task("[yellow]Overall Progress", total=len(videos_for_download), status="")
for i, video_data in enumerate(videos_for_download):
title = video_data.get('title', 'Unknown Title')
rel_path_str = video_data.get('target_rel_path', '.')
target_dir = media_root / rel_path_str
sanitized_title = sanitize_filename(title)
# Expected final filename structure (yt-dlp might vary extension)
expected_filename_base = target_dir / sanitized_title
# Check if file potentially exists (basic check)
# Note: yt-dlp might use mkv, webm etc. depending on format.
# A more robust check would look for `expected_filename_base.*`
potential_files = list(target_dir.glob(f"{sanitized_title}.*"))
if potential_files:
progress.update(download_task, advance=1, status=f"[yellow]Skipped (Exists): {title[:40]}...")
logger.warning(f"Skipping download for '{title}': File already exists at {potential_files[0]}")
# Track success even if skipped, assuming existing file is intended
source_url = video_data.get('_source_url')
if source_url and update_sync_times:
# Use current video's info if newer than previously recorded for this source
if source_url not in successful_downloads or \
(video_data.get('upload_date') and successful_downloads[source_url].get('upload_date') and \
video_data['upload_date'] > successful_downloads[source_url]['upload_date']):
successful_downloads[source_url] = video_data
continue # Skip to next video
progress.update(download_task, status=f"[cyan]Downloading: {title[:40]}...")
yt_dlp_output_lines.clear() # Clear output for new download
result = yt.download_video(
video_info=video_data,
target_dir=target_dir,
download_format=download_settings["format"],
subtitle_langs=download_settings["subtitle_langs"],
progress_hook=progress_hook # Pass the hook
)
# Update progress bar based on result
if result["status"] == "success":
progress.update(download_task, advance=1, status=f"[green]Success: {title[:40]}...")
logger.info(f"Successfully downloaded '{title}' to {result.get('final_path', target_dir)}")
source_url = video_data.get('_source_url')
if source_url and update_sync_times:
# Record success for sync time update
if source_url not in successful_downloads or \
(video_data.get('upload_date') and successful_downloads[source_url].get('upload_date') and \
video_data['upload_date'] > successful_downloads[source_url]['upload_date']):
successful_downloads[source_url] = video_data
elif result["status"] == "warning":
progress.update(download_task, advance=1, status=f"[yellow]Warning: {title[:40]}...")
logger.warning(f"Download warning for '{title}': {result['message']}")
source_url = video_data.get('_source_url')
if source_url and update_sync_times:
# Treat warning as success for sync time update purpose
if source_url not in successful_downloads or \
(video_data.get('upload_date') and successful_downloads[source_url].get('upload_date') and \
video_data['upload_date'] > successful_downloads[source_url]['upload_date']):
successful_downloads[source_url] = video_data
else: # Error
progress.update(download_task, advance=1, status=f"[red]Failed: {title[:40]}...")
logger.error(f"Failed to download '{title}'. Reason: {result['message']}")
failed_downloads.append({"title": title, "reason": result['message']})
# Pause slightly between downloads? (Optional)
# time.sleep(0.5)
# Final status update for the overall task
final_status = f"[bold green]Completed {len(videos_for_download) - len(failed_downloads)}/{len(videos_for_download)}. Failures: {len(failed_downloads)}"
if not videos_for_download: final_status = "[bold blue]No downloads required."
progress.update(download_task, status=final_status, description="[bold]Download Summary")
if failed_downloads:
console.print("\n[bold red]--- Download Failures ---[/bold red]")
for failure in failed_downloads:
console.print(f"- {failure['title']}: {failure['reason']}")
return successful_downloads
# --- Main Commands ---
@app.command(name="create-config", help="Create a default configuration file if it doesn't exist.")
def create_config_command():
created = cfg.create_default_config()
if not created:
# Message already printed by the function
raise typer.Exit(code=1)
@app.command(help="Check sources, categorize new videos, verify, and download.")
def run(
ctx: typer.Context,
force_rescan: bool = typer.Option(False, "--force-rescan", "-f", help="Ignore last synced dates and check all videos from sources."),
skip_llm: bool = typer.Option(False, "--skip-llm", help="Skip LLM categorization (videos go to root '.')."),
yes: bool = typer.Option(False, "-y", "--yes", help="Skip verification and download all found videos immediately.")
):
"""Checks sources from config, finds new videos, categorizes, verifies, downloads."""
try:
config = cfg.load_config()
except Exception as e:
logger.critical(f"Failed to load configuration: {e}")
raise typer.Exit(code=1)
if config.get("debug_log", False):
logging.getLogger().setLevel(logging.DEBUG)
logger.debug("Debug logging enabled.")
media_root = Path(config["media_root"])
llm_config = config["llm"]
sources = config["sources"]
# Generate directory tree once
logger.info("Generating directory tree representation...")
dir_tree_str = generate_dir_tree(media_root, llm_config["max_tree_depth"], llm_config["max_files_per_dir"])
logger.debug(f"Directory tree generated (first 200 chars):\n{dir_tree_str[:200]}...")
videos_to_process: List[Dict[str, Any]] = []
source_sync_times_to_update: Dict[str, str] = {} # url -> new_sync_iso_string
logger.info("Checking sources from config file...")
for source in sources:
url = source["url"]
source_type = source["type"]
last_synced = None if force_rescan else source.get("last_synced")
console.print(f"Checking [blue]{source_type}[/blue]: [cyan]{url}[/cyan]" + (f" (since {last_synced})" if last_synced else " (full scan)"))
# Fetch metadata
try:
new_videos = yt.get_video_metadata(url, date_after_str=last_synced)
except Exception as e: # Catch potential yt-dlp not found etc.
logger.error(f"Could not process source {url}: {e}")
continue # Skip to next source
if not new_videos:
logger.debug(f"No new videos found for {url}")
# Mark source for sync time update even if no videos, signifies it was checked
source_sync_times_to_update[url] = get_current_utc_iso_string()
continue
# Find the timestamp of the latest video found for this source
latest_video_timestamp = last_synced or "1970-01-01T00:00:00Z" # Initialize for comparison
latest_upload_date_num = 0 # YYYYMMDD
# Process videos found for this source
for video_data in new_videos:
video_title = video_data.get('title', 'Unknown Title')
# Store source info for verification display & sync time update
video_data['_source_url'] = url
video_data['_source_nickname'] = url.split('/')[-1] # Simple nickname
# --- Categorization ---
if skip_llm:
suggested_rel_path = "."
else:
suggested_rel_path = cat.get_category_suggestion(
video_title,
media_root,
llm_config,
cached_tree_str=dir_tree_str # Pass cached tree
)
cleaned_path = cat.clean_and_validate_path(suggested_rel_path, media_root)
video_data['target_rel_path'] = cleaned_path
videos_to_process.append(video_data)
# Track latest video date/time for updating last_synced
# Use upload_date (YYYYMMDD) primarily if available, more reliable than scraped times
upload_date_str = video_data.get('upload_date') # YYYYMMDD
if upload_date_str:
try:
current_upload_date_num = int(upload_date_str)
if current_upload_date_num > latest_upload_date_num:
latest_upload_date_num = current_upload_date_num
# Construct a pseudo-ISO time for this date for comparison consistency
latest_video_timestamp = f"{upload_date_str[:4]}-{upload_date_str[4:6]}-{upload_date_str[6:]}T00:00:00Z"
except ValueError:
logger.warning(f"Could not parse upload_date '{upload_date_str}' for '{video_title}'")
# Record the potential new sync time based on the latest video found *from this batch*
# We update the actual config *after* successful downloads.
if latest_video_timestamp and (not last_synced or latest_video_timestamp > last_synced):
# Use the timestamp of the latest *processed* video as the new sync point
# Add a second to avoid re-fetching the exact same video next time if timestamps are identical
# This needs careful handling with date vs datetime. Using current time might be safer.
# Let's use the current time for simplicity and robustness.
source_sync_times_to_update[url] = get_current_utc_iso_string()
elif not new_videos: # If no videos found, still update sync time to now
source_sync_times_to_update[url] = get_current_utc_iso_string()
if not videos_to_process:
console.print("\n[green]No new videos found across all sources requiring processing.[/green]")
# Update sync times for sources that were checked but had no new videos
if source_sync_times_to_update:
logger.info("Updating last_synced times for checked sources...")
updated_count = 0
for i, source in enumerate(config["sources"]):
if source["url"] in source_sync_times_to_update:
if source.get("last_synced") != source_sync_times_to_update[source["url"]]:
config["sources"][i]["last_synced"] = source_sync_times_to_update[source["url"]]
updated_count += 1
if updated_count > 0:
cfg.save_config(config)
logger.info(f"Saved updated last_synced times for {updated_count} sources.")
else:
logger.info("No last_synced times needed updating.")
raise typer.Exit()
# --- Verification ---
if yes:
console.print(f"\n[yellow]-y/--yes flag used. Skipping verification for {len(videos_to_process)} videos.[/yellow]")
approved_videos = videos_to_process
else:
approved_videos = ver.run_verification(videos_to_process, config, dir_tree_str)
# --- Downloading ---
if approved_videos:
successful_downloads_by_source = process_downloads(
approved_videos,
config,
update_sync_times=True # Signal that sync times should be updated based on success
)
# --- Update Config last_synced ---
logger.info("Updating last_synced times in configuration...")
updated_count = 0
for i, source in enumerate(config["sources"]):
source_url = source["url"]
# Update if this source was successfully processed (even partially)
# Use the planned update time calculated earlier
if source_url in source_sync_times_to_update:
new_sync_time = source_sync_times_to_update[source_url]
if source.get("last_synced") != new_sync_time:
config["sources"][i]["last_synced"] = new_sync_time
updated_count += 1
if updated_count > 0:
cfg.save_config(config)
logger.info(f"Saved updated last_synced times for {updated_count} sources.")
else:
logger.info("No last_synced times needed updating based on download results.")
else:
console.print("\n[yellow]No videos approved for download.[/yellow]")
@app.command(name="download", help="Download and categorize specific YouTube URLs (ad-hoc).")
def adhoc_download(
ctx: typer.Context,
urls: List[str] = typer.Argument(..., help="One or more YouTube video, playlist, or channel URLs."),
skip_llm: bool = typer.Option(False, "--skip-llm", help="Skip LLM categorization (videos go to root '.')."),
yes: bool = typer.Option(False, "-y", "--yes", help="Skip verification and download all found videos immediately.")
):
"""Downloads and categorizes videos from provided URLs, bypassing config sources."""
try:
# Load config for settings (media_root, download, llm), but ignore sources
config = cfg.load_config()
except Exception as e:
logger.critical(f"Failed to load configuration: {e}")
raise typer.Exit(code=1)
if config.get("debug_log", False):
logging.getLogger().setLevel(logging.DEBUG)
logger.debug("Debug logging enabled.")
media_root = Path(config["media_root"])
llm_config = config["llm"]
logger.info("Generating directory tree representation...")
dir_tree_str = generate_dir_tree(media_root, llm_config["max_tree_depth"], llm_config["max_files_per_dir"])
videos_to_process: List[Dict[str, Any]] = []
logger.info("Fetching metadata for provided URLs...")
for url in urls:
console.print(f"Fetching metadata for: [cyan]{url}[/cyan]")
try:
# Fetch without date filter for ad-hoc
found_videos = yt.get_video_metadata(url, date_after_str=None)
except Exception as e:
logger.error(f"Could not process URL {url}: {e}")
continue
if not found_videos:
logger.warning(f"No videos found for URL: {url}")
continue
for video_data in found_videos:
video_title = video_data.get('title', 'Unknown Title')
video_data['_source_url'] = url # Track origin for display if needed
video_data['_source_nickname'] = url.split('/')[-1] if '/' in url else url[:20]
if skip_llm:
suggested_rel_path = "."
else:
suggested_rel_path = cat.get_category_suggestion(
video_title,
media_root,
llm_config,
cached_tree_str=dir_tree_str
)
cleaned_path = cat.clean_and_validate_path(suggested_rel_path, media_root)
video_data['target_rel_path'] = cleaned_path
videos_to_process.append(video_data)
if not videos_to_process:
console.print("\n[yellow]No videos found for any of the provided URLs.[/yellow]")
raise typer.Exit()
# --- Verification ---
if yes:
console.print(f"\n[yellow]-y/--yes flag used. Skipping verification for {len(videos_to_process)} videos.[/yellow]")
approved_videos = videos_to_process
else:
approved_videos = ver.run_verification(videos_to_process, config, dir_tree_str)
# --- Downloading ---
if approved_videos:
# Don't update sync times for ad-hoc downloads
process_downloads(approved_videos, config, update_sync_times=False)
else:
console.print("\n[yellow]No videos approved for download.[/yellow]")
# --- Entry Point ---
if __name__ == "__main__":
app()