code it
- 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.
code it
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's start building the technical implementation. We'll break this down into several parts.
Part 1: Project Setup, Configuration, and Basic CLI Structure
First, we'll set up the project structure, define the configuration file format, create functions to load/save it, and establish the basic command-line interface using argparse.
1. Project Structure:
Create a directory for your project, let's call it youtube_sync. Inside it, create the following files:
youtube_sync/
├── youtube_sync.py # Main script
├── config.yaml # Default configuration file
└── requirements.txt # Python dependencies
2. requirements.txt:
Add the necessary libraries. We'll add more as we implement features.
PyYAML
yt-dlp
python-dotenv # Good practice for API keys
# We'll add openai, inquirer, tqdm later
Install them: pip install -r requirements.txt
3. config.yaml (Example):
Create an initial config.yaml file.
# --- General Settings ---
debug: true
# Absolute path to your main media folder
media_root: /path/to/your/videos # !!! CHANGE THIS !!!
# Subtitle languages for yt-dlp
subtitle_languages: ["en", "en-US", "en*", "en-*"]
# Base yt-dlp command options (excluding subtitles, output path)
yt_dlp_options:
- "-f"
- "bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio/best" # More robust format selection
- "--embed-metadata" # Good to have metadata in the file
- "--embed-thumbnail" # Nice to have thumbnails
# Subtitle options will be added dynamically based on subtitle_languages
# Output path will be added dynamically
# --- LLM Settings (Placeholder) ---
llm_provider: openai # Or other providers later
llm_model: gpt-3.5-turbo # Or your preferred model
# You might store the API key in a .env file or environment variable
# llm_api_key: YOUR_API_KEY # Better to use environment variables
# --- Sources ---
sources:
- id: ltt_channel # Unique identifier for internal tracking
type: channel
url: https://www.youtube.com/c/LinusTechTips # Example
# Use ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ)
last_synced: 2023-01-01T00:00:00Z # Start from beginning for first run
# Default category if LLM fails or skips
default_category: "Tech Reviews/Linus Tech Tips"
- id: kurz_playlist # Unique identifier
type: playlist
url: https://www.youtube.com/playlist?list=PLFs4vir_WsTwEd-6JVSPxS-_p2YEePzAN # Example
last_synced: 2023-10-01T00:00:00Z
default_category: "Science/Kurzgesagt"
# Add more channels and playlists here
Key Changes/Additions to Config:
id: Added a unique ID for each source. This makes it easier to update the correct source's last_synced date later.default_category: Renamed from category for clarity. This is the fallback.yt_dlp_options: Refined format selection slightly. We'll dynamically add subtitle and output options later.llm_ settings: Added placeholders for LLM configuration.4. youtube_sync.py (Initial Structure):
Explanation:
DEFAULT_CONFIG_FILE and DATE_FORMAT.load_config: Reads the YAML file, performs basic validation (checks for media_root, sources), resolves media_root to an absolute path, and handles errors.save_config: Writes the (potentially modified) config dictionary back to the YAML file. Includes error handling.run_sync (Placeholder):
--override-sources by creating temporary source dictionaries.last_synced.last_synced date string into a timezone-aware datetime object.last_synced in the config only for sources defined in the config file that had successful downloads. It uses the current time for now, but we can refine this later.main:
argparse for the sync command and its options.categorize command.debug flag in the config.sync).if __name__ == "__main__":: Standard Python entry point.Next Steps:
fetch_new_videos_metadata: Use yt-dlp via subprocess to get video details (title, URL, upload date) newer than last_synced.media_root.inquirer to create the interactive step.yt-dlp via subprocess to download the approved videos to the correct locations with specified options and subtitles.last_synced Update: Make the update logic more robust (e.g., use the latest video upload date from the batch).categorize command: Add the logic for manual categorization.Let me know when you're ready to move on to Part 2: Fetching Video Metadata with yt-dlp.
import argparse
import logging
import os
import sys
import yaml
from datetime import datetime, timezone
from pathlib import Path
# --- Constants ---
DEFAULT_CONFIG_FILE = "config.yaml"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ" # ISO 8601 format for UTC
# --- Logging Setup ---
log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
log_handler = logging.StreamHandler(sys.stdout)
log_handler.setFormatter(log_formatter)
logger = logging.getLogger(__name__)
logger.addHandler(log_handler)
logger.setLevel(logging.INFO) # Default level
# --- Configuration Handling ---
def load_config(config_path):
"""Loads configuration from a YAML file."""
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
logger.info(f"Configuration loaded from {config_path}")
# Basic Validation (can be expanded)
if 'media_root' not in config or not config['media_root']:
raise ValueError("Missing or empty 'media_root' in config.")
if 'sources' not in config or not isinstance(config['sources'], list):
raise ValueError("'sources' section is missing or not a list in config.")
if not config['sources']:
logger.warning("No sources defined in the configuration.")
# Ensure media_root is an absolute path
config['media_root'] = str(Path(config['media_root']).resolve())
if not os.path.isdir(config['media_root']):
logger.warning(f"Media root directory '{config['media_root']}' does not exist. It might be created later.")
return config
except FileNotFoundError:
logger.error(f"Configuration file not found: {config_path}")
sys.exit(1)
except yaml.YAMLError as e:
logger.error(f"Error parsing configuration file {config_path}: {e}")
sys.exit(1)
except ValueError as e:
logger.error(f"Configuration error: {e}")
sys.exit(1)
except Exception as e:
logger.error(f"An unexpected error occurred loading config: {e}")
sys.exit(1)
def save_config(config, config_path):
"""Saves the configuration back to the YAML file."""
try:
with open(config_path, 'w', encoding='utf-8') as f:
yaml.dump(config, f, default_flow_style=False, sort_keys=False)
logger.debug(f"Configuration saved to {config_path}")
except Exception as e:
logger.error(f"Failed to save configuration to {config_path}: {e}")
# Don't exit here, as the download might have finished,
# but warn the user strongly.
logger.warning("!!! FAILED TO SAVE CONFIGURATION. 'last_synced' dates are NOT updated. !!!")
# --- Main Sync Logic (Placeholder) ---
def run_sync(config, override_sources=None, no_verify=False):
"""Main function to perform the sync process."""
logger.info("Starting sync process...")
media_root = config['media_root']
sources_to_process = []
if override_sources:
logger.info(f"Overriding sources with provided URLs: {override_sources}")
# Create temporary source entries for overrides
# We need to figure out if a URL is a channel, playlist, or video
# For now, let's assume they need manual categorization or a default
for i, url in enumerate(override_sources):
sources_to_process.append({
'id': f"override_{i}",
'type': 'unknown', # We'll need yt-dlp to determine type later
'url': url,
'last_synced': "1970-01-01T00:00:00Z", # Check everything for overrides
'default_category': "Downloaded/Overrides" # Sensible default
})
else:
logger.info("Using sources from configuration file.")
sources_to_process = config.get('sources', [])
if not sources_to_process:
logger.warning("No sources configured. Exiting.")
return
# --- Stage 1: Fetch New Video Metadata ---
all_new_videos = []
for source in sources_to_process:
logger.info(f"Checking source: {source.get('id', source['url'])}")
try:
# Parse last_synced date safely
last_synced_dt = datetime.strptime(source['last_synced'], DATE_FORMAT).replace(tzinfo=timezone.utc)
logger.debug(f"Last synced date for {source.get('id', source['url'])}: {last_synced_dt}")
# --- Call yt-dlp to get video list (Implementation in Part 2) ---
# new_videos = fetch_new_videos_metadata(source['url'], last_synced_dt)
new_videos = [] # Placeholder
if new_videos:
logger.info(f"Found {len(new_videos)} new video(s) for {source.get('id', source['url'])}.")
# Add source info to each video for later reference
for video in new_videos:
video['source_id'] = source['id']
video['default_category'] = source['default_category']
all_new_videos.extend(new_videos)
else:
logger.info(f"No new videos found for {source.get('id', source['url'])} since {source['last_synced']}.")
except ValueError:
logger.error(f"Invalid date format for 'last_synced' in source {source.get('id', 'N/A')}: {source['last_synced']}")
continue # Skip this source
except Exception as e:
logger.error(f"Error processing source {source.get('id', source['url'])}: {e}")
continue # Skip this source
if not all_new_videos:
logger.info("No new videos found across all sources. Sync complete.")
return
logger.info(f"Total new videos found: {len(all_new_videos)}")
# --- Stage 2: Categorize Videos (LLM) (Implementation in Part 3) ---
# categorized_videos = categorize_videos_with_llm(all_new_videos, config, media_root)
categorized_videos = [] # Placeholder - Add dummy data for now
for i, video in enumerate(all_new_videos):
video['proposed_category'] = f"Category/Placeholder_{i}" # Dummy category
categorized_videos.append(video)
# --- Stage 3: Verification Step (Implementation in Part 4) ---
if no_verify:
logger.info("Skipping verification step (--no-verify specified).")
approved_videos = categorized_videos # Approve all
else:
logger.info("Starting verification step...")
# approved_videos = run_verification_ui(categorized_videos, media_root)
approved_videos = categorized_videos # Placeholder - Assume all approved for now
if not approved_videos:
logger.info("No videos approved for download. Sync complete.")
return
logger.info(f"{len(approved_videos)} video(s) approved for download.")
# --- Stage 4: Download Videos (Implementation in Part 5) ---
# download_approved_videos(approved_videos, config)
download_success_count = len(approved_videos) # Placeholder
download_fail_count = 0 # Placeholder
# --- Stage 5: Update Config `last_synced` ---
# Only update if downloads were attempted (even if some failed)
# Determine the timestamp *before* starting the sync or after all checks?
# Using the time *before* checks ensures we don't miss videos uploaded during the sync.
# Let's refine this - the *latest* upload date of downloaded videos per source is better.
# For now, let's just update with the current time if successful downloads happened for a source.
logger.info("Updating 'last_synced' dates in configuration...")
current_sync_time_str = datetime.now(timezone.utc).strftime(DATE_FORMAT)
updated_sources_in_config = False
# Track which sources had successful downloads to update their sync time
sources_with_downloads = set(video['source_id'] for video in approved_videos if 'source_id' in video) # Filter out overrides if they don't have IDs matching config
if not override_sources: # Only update config sources, not overrides
for source_config in config.get('sources', []):
source_id = source_config.get('id')
if source_id and source_id in sources_with_downloads:
source_config['last_synced'] = current_sync_time_str
logger.debug(f"Updating last_synced for source ID '{source_id}' to {current_sync_time_str}")
updated_sources_in_config = True
if updated_sources_in_config:
# Save the modified config object back to the file
save_config(config, args.config) # Use the path from args
else:
logger.info("No configuration sources required updating.")
else:
logger.info("Running with override sources, configuration file's 'last_synced' dates not updated.")
logger.info(f"Sync process finished. {download_success_count} video(s) downloaded, {download_fail_count} failed.")
# --- Argument Parsing ---
def main():
parser = argparse.ArgumentParser(description="Automate downloading and sorting YouTube videos.")
# Subparsers for different commands (sync, categorize)
subparsers = parser.add_subparsers(dest='command', help='Available commands')
parser.add_argument('--config', default=DEFAULT_CONFIG_FILE, help=f'Path to configuration file (default: {DEFAULT_CONFIG_FILE})')
# --- Sync Command ---
parser_sync = subparsers.add_parser('sync', help='Check sources, categorize, verify, and download new videos.')
parser_sync.add_argument('--override-sources', nargs='+', help='Space-separated list of YouTube URLs to process instead of config sources.')
parser_sync.add_argument('--no-verify', action='store_true', help='Skip the interactive verification step and download directly.')
# --- Categorize Command (Placeholder) ---
parser_categorize = subparsers.add_parser('categorize', help='Manually suggest a category for a given video title (uses LLM).')
parser_categorize.add_argument('video_title', help='The title of the video to categorize.')
# parser_categorize.add_argument('--category', help='Manually specify the category instead of using LLM.') # Optional addition
args = parser.parse_args()
# --- Execute ---
config = load_config(args.config)
# Set logging level based on config
if config.get('debug', False):
logger.setLevel(logging.DEBUG)
logger.debug("Debug logging enabled.")
if args.command == 'sync':
run_sync(config, args.override_sources, args.no_verify)
elif args.command == 'categorize':
logger.info(f"Manual categorization for title: '{args.video_title}'")
# --- Call categorization function (Implementation in Part 3) ---
# result_category = run_manual_categorization(args.video_title, config)
# logger.info(f"Suggested category: {result_category}")
print("Manual categorization command not fully implemented yet.")
else:
parser.print_help()
if __name__ == "__main__":
main()