Files
triviathang/backend/services/youtube_service.py
2025-12-22 14:47:25 -05:00

72 lines
1.8 KiB
Python

import re
import yt_dlp
def validate_youtube_url(url):
"""
Validate YouTube URL and extract video ID
Returns:
(bool, str): (is_valid, video_id or error_message)
"""
patterns = [
r'(?:youtube\.com\/watch\?v=|youtu\.be\/)([\w-]+)',
r'youtube\.com\/embed\/([\w-]+)',
r'youtube\.com\/v\/([\w-]+)'
]
for pattern in patterns:
match = re.search(pattern, url)
if match:
return True, match.group(1)
return False, "Invalid YouTube URL format"
def get_video_duration(url):
"""
Get video duration without downloading
Returns:
int: Duration in seconds, or None if failed
"""
try:
ydl_opts = {
'quiet': True,
'no_warnings': True,
'extract_flat': True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
return info.get('duration')
except Exception as e:
print(f"Error getting video duration: {e}")
return None
def validate_timestamps(start_time, end_time, video_duration=None):
"""
Validate timestamp range
Args:
start_time: Start time in seconds
end_time: End time in seconds
video_duration: Optional video duration for validation
Returns:
(bool, str): (is_valid, error_message if invalid)
"""
if start_time < 0:
return False, "Start time must be non-negative"
if end_time <= start_time:
return False, "End time must be greater than start time"
if end_time - start_time > 300: # 5 minutes
return False, "Clip duration cannot exceed 5 minutes"
if video_duration and end_time > video_duration:
return False, f"End time exceeds video duration ({video_duration}s)"
return True, None