Here is the Python code that accomplishes the tasks you've described. It uses yt_dlp to download subtitles from YouTube videos and channels, splits subtitles into chunks based on the token limit of the AI API, sends them to the AI API for processing, and handles re-summarization if needed.
Please make sure you have the necessary libraries installed:
pip install yt_dlp requests
Now, here's the code:
import yt_dlp
import requests
import argparse
import sys
import re
import math
import json
# Constants for AI API
AI_API_ENDPOINT = 'https://api.example.com/v1/ai' # Replace with actual endpoint
DEFAULT_AI_MODEL = 'gpt-4o-mini'
AI_API_TOKEN_LIMIT = 4000 # Adjust based on the actual token limit of the AI model
CHARS_PER_TOKEN = 4 # Approximate number of characters per token
def download_subtitles(video_url):
ydl_opts = {
'skip_download': True,
'writesubtitles': True,
'writeautomaticsub': True,
'subtitleslangs': ['en'],
'outtmpl': '%(id)s.%(ext)s',
'subtitlesformat': 'vtt',
}
subtitles = ''
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(video_url, download=False)
if 'subtitles' in info and 'en' in info['subtitles']:
subtitles_url = info['subtitles']['en'][-1]['url']
elif 'automatic_captions' in info and 'en' in info['automatic_captions']:
subtitles_url = info['automatic_captions']['en'][-1]['url']
else:
print(f"No subtitles found for video: {video_url}")
return ''
response = requests.get(subtitles_url)
if response.status_code == 200:
subtitles = response.text
else:
print(f"Failed to download subtitles for video: {video_url}")
return subtitles
def get_recent_videos(channel_url, n=1):
ydl_opts = {
'skip_download': True,
'extract_flat': True,
}
video_urls = []
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(channel_url, download=False)
if 'entries' in info:
entries = info['entries']
for entry in entries[:n]:
video_id = entry.get('id')
if video_id:
video_urls.append(f'https://www.youtube.com/watch?v={video_id}')
return video_urls
def split_subtitles_into_chunks(subtitles, max_chars):
# Remove VTT formatting
subtitles_text = re.sub(r'^.*-->.*$', '', subtitles, flags=re.MULTILINE)
subtitles_text = re.sub(r'<[^>]+>', '', subtitles_text)
subtitles_text = subtitles_text.strip()
# Split into chunks
chunks = []
total_chars = len(subtitles_text)
num_chunks = math.ceil(total_chars / max_chars)
chunk_size = math.ceil(total_chars / num_chunks)
for i in range(0, total_chars, chunk_size):
chunks.append(subtitles_text[i:i+chunk_size])
return chunks
def call_ai_api(text, model=DEFAULT_AI_MODEL):
# Replace with actual API call
headers = {
'Authorization': 'Bearer YOUR_API_KEY', # Replace with actual API key
'Content-Type': 'application/json',
}
payload = {
'model': model,
'prompt': text,
}
response = requests.post(AI_API_ENDPOINT, headers=headers, json=payload)
if response.status_code == 200:
result = response.json()
return result.get('response', '')
else:
print(f"AI API call failed with status code {response.status_code}")
return ''
def process_subtitles(subtitles, ai_model, re_summarize_model=None):
max_chars = AI_API_TOKEN_LIMIT * CHARS_PER_TOKEN
chunks = split_subtitles_into_chunks(subtitles, max_chars)
summaries = []
for chunk in chunks:
summary = call_ai_api(chunk, model=ai_model)
summaries.append(summary)
if len(summaries) > 1 and re_summarize_model:
combined_summary = ' '.join(summaries)
final_summary = call_ai_api(combined_summary, model=re_summarize_model)
return final_summary
else:
return summaries[0] if summaries else ''
def main():
parser = argparse.ArgumentParser(description='Process YouTube videos/channels and summarize subtitles.')
parser.add_argument('urls', nargs='+', help='YouTube video or channel URLs')
parser.add_argument('-n', '--number', type=int, default=1, help='Number of recent videos to process from a channel (default: 1)')
parser.add_argument('-m', '--model', default=DEFAULT_AI_MODEL, help='AI model to use for processing (default: gpt-4o-mini)')
parser.add_argument('-r', '--re_summarize_model', default=None, help='AI model to use for re-summarization if needed')
args = parser.parse_args()
ai_model = args.model
re_summarize_model = args.re_summarize_model
number_of_videos = args.number
for url in args.urls:
if 'watch?v=' in url or 'youtu.be/' in url:
# It's a video URL
print(f"Processing video URL: {url}")
subtitles = download_subtitles(url)
if subtitles:
summary = process_subtitles(subtitles, ai_model, re_summarize_model)
print(f"Summary for video {url}:\n{summary}\n")
else:
# Assume it's a channel URL
print(f"Processing channel URL: {url}")
video_urls = get_recent_videos(url, n=number_of_videos)
for video_url in video_urls:
print(f"Processing video URL from channel: {video_url}")
subtitles = download_subtitles(video_url)
if subtitles:
summary = process_subtitles(subtitles, ai_model, re_summarize_model)
print(f"Summary for video {video_url}:\n{summary}\n")
if __name__ == '__main__':
main()
Instructions to Run the Code:
- Save the code in a file, e.g.,
youtube_processor.py.
- Replace
'https://api.example.com/v1/ai' with the actual AI API endpoint.
- Replace
'YOUR_API_KEY' with your actual API key for the AI service.
- Adjust
AI_API_TOKEN_LIMIT and CHARS_PER_TOKEN based on the actual limits of the AI model you're using.
- Run the script from the command line.
Example Usage:
python youtube_processor.py https://www.youtube.com/watch?v=VIDEO_ID -m your-ai-model -r your-re-summarize-model
Command-Line Arguments:
urls: One or more YouTube video or channel URLs.
-n, --number: Number of recent videos to process from a channel (default is 1).
-m, --model: AI model to use for processing (default is gpt-4o-mini).
-r, --re_summarize_model: AI model to use for re-summarization if needed.
Notes:
- The script handles both video URLs and channel URLs.
- Subtitles are downloaded using
yt_dlp, and it will use either provided subtitles or auto-generated ones.
- Subtitles are cleaned of VTT formatting before processing.
- The script splits subtitles into chunks based on the token limit of the AI API.
- If multiple chunks are processed, and a re-summarization model is provided, it will combine the summaries and re-summarize them.
- Replace the placeholder AI API call in
call_ai_api function with the actual API call to the AI service you're using.
Disclaimer:
- Be mindful of the terms of service of YouTube and the AI API provider.
- Ensure you have the rights and permissions to download and process subtitles from YouTube videos.
- Handle API keys securely and do not expose them in code shared publicly.