File size: 11,908 Bytes
422e5df
e01ecae
422e5df
 
 
e01ecae
 
 
 
 
 
 
1e32418
e01ecae
 
 
 
 
 
 
 
 
 
 
 
 
422e5df
 
e01ecae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422e5df
 
e01ecae
 
 
422e5df
 
e01ecae
 
 
 
 
 
 
 
 
 
 
 
 
 
422e5df
 
e01ecae
 
 
 
 
422e5df
 
e01ecae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422e5df
e01ecae
 
422e5df
e01ecae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422e5df
 
e01ecae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422e5df
e01ecae
422e5df
e01ecae
 
 
 
 
 
 
 
422e5df
e01ecae
 
 
 
 
 
 
 
 
 
 
 
422e5df
e01ecae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422e5df
 
e01ecae
 
 
 
 
 
 
 
 
 
422e5df
 
e01ecae
 
 
 
 
 
 
 
 
 
422e5df
e01ecae
 
 
 
422e5df
 
e01ecae
422e5df
 
e01ecae
422e5df
e01ecae
 
 
422e5df
e01ecae
422e5df
e01ecae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422e5df
e01ecae
1e32418
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
from __future__ import unicode_literals
import yt_dlp
import os
import time
import shutil
import logging
import re
import tempfile
from pathlib import Path
from typing import Optional, Callable, Dict, Any, Union

# Configuration
MAX_FILE_SIZE = 40 * 1024 * 1024  # 40 MB
FILE_TOO_LARGE_MESSAGE = "The audio file exceeds the 40MB size limit. Please try a shorter video clip or select a lower quality option."
MAX_RETRIES = 3
RETRY_DELAY = 2  # seconds
DEFAULT_AUDIO_FORMAT = "mp3"
DEFAULT_AUDIO_QUALITY = "192"  # kbps
SUPPORTED_FORMATS = ["mp3", "m4a", "wav", "aac", "flac", "opus"]

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger("youtube_downloader")


class DownloadLogger:
    """Enhanced logger for yt-dlp with callback support"""
    
    def __init__(self, progress_callback: Optional[Callable[[str], None]] = None):
        self.progress_callback = progress_callback or (lambda x: None)
    
    def debug(self, msg: str) -> None:
        if msg.startswith('[download]'):
            # Extract progress information
            if '%' in msg:
                self.progress_callback(msg)
        logger.debug(msg)
    
    def warning(self, msg: str) -> None:
        logger.warning(msg)
    
    def error(self, msg: str) -> None:
        logger.error(msg)


class DownloadError(Exception):
    """Custom exception for download errors"""
    pass


def validate_url(url: str) -> bool:
    """Validate if the URL is a supported video platform URL"""
    video_platforms = [
        r'youtube\.com',
        r'youtu\.be',
        r'vimeo\.com',
        r'dailymotion\.com',
        r'twitch\.tv',
        r'soundcloud\.com',
        r'instagram\.com'
    ]
    
    pattern = '|'.join([f'({platform})' for platform in video_platforms])
    return bool(re.search(pattern, url, re.IGNORECASE))


def ensure_download_directory(directory: str) -> str:
    """Ensure download directory exists, create if it doesn't"""
    path = Path(directory)
    path.mkdir(parents=True, exist_ok=True)
    return str(path.absolute())


def get_download_options(
    output_dir: str = "./downloads/audio",
    audio_format: str = DEFAULT_AUDIO_FORMAT,
    audio_quality: str = DEFAULT_AUDIO_QUALITY,
    progress_callback: Optional[Callable[[str], None]] = None
) -> Dict[str, Any]:
    """
    Get yt-dlp download options with specified parameters
    
    Args:
        output_dir: Directory to save downloaded files
        audio_format: Audio format (mp3, m4a, wav, etc.)
        audio_quality: Audio quality in kbps
        progress_callback: Function to call with progress updates
        
    Returns:
        Dictionary of yt-dlp options
    """
    if audio_format not in SUPPORTED_FORMATS:
        logger.warning(f"Unsupported format '{audio_format}', falling back to {DEFAULT_AUDIO_FORMAT}")
        audio_format = DEFAULT_AUDIO_FORMAT
    
    # Ensure download directory exists
    output_dir = ensure_download_directory(output_dir)
    
    return {
        "format": "bestaudio/best",
        "postprocessors": [{
            "key": "FFmpegExtractAudio",
            "preferredcodec": audio_format,
            "preferredquality": audio_quality,
        }],
        "logger": DownloadLogger(progress_callback),
        "outtmpl": f"{output_dir}/%(title)s.%(ext)s",
        "noplaylist": True,
        "quiet": False,
        "no_warnings": False,
        "progress_hooks": [lambda d: download_progress_hook(d, progress_callback)],
        "overwrites": True,
    }


def download_progress_hook(d: Dict[str, Any], callback: Optional[Callable[[str], None]] = None) -> None:
    """
    Hook for tracking download progress
    
    Args:
        d: Download information dictionary
        callback: Function to call with progress updates
    """
    if callback is None:
        callback = lambda x: None
    
    if d['status'] == 'downloading':
        progress = d.get('_percent_str', 'unknown progress')
        speed = d.get('_speed_str', 'unknown speed')
        eta = d.get('_eta_str', 'unknown ETA')
        callback(f"Downloading: {progress} at {speed}, ETA: {eta}")
    
    elif d['status'] == 'finished':
        filename = os.path.basename(d['filename'])
        callback(f"Download complete: {filename}")
        logger.info(f"Download finished: {d['filename']}")


def estimate_file_size(info: Dict[str, Any]) -> int:
    """
    Better estimate file size from video info
    
    Args:
        info: Video information dictionary
        
    Returns:
        Estimated file size in bytes
    """
    # Try different fields that might contain size information
    filesize = info.get("filesize")
    if filesize is not None:
        return filesize
    
    filesize = info.get("filesize_approx")
    if filesize is not None:
        return filesize
    
    # If we have duration and a bitrate, we can estimate
    duration = info.get("duration")
    bitrate = info.get("abr") or info.get("tbr")
    
    if duration and bitrate:
        # Estimate using bitrate (kbps) * duration (seconds) / 8 (bits to bytes) * 1024 (to KB)
        return int(bitrate * duration * 128)  # 128 = 1024 / 8
    
    # Default to a reasonable upper limit if we can't determine
    return MAX_FILE_SIZE


def download_video_audio(
    url: str, 
    output_dir: str = "./downloads/audio",
    audio_format: str = DEFAULT_AUDIO_FORMAT,
    audio_quality: str = DEFAULT_AUDIO_QUALITY,
    progress_callback: Optional[Callable[[str], None]] = None
) -> Optional[str]:
    """
    Download audio from a video URL
    
    Args:
        url: URL of the video
        output_dir: Directory to save downloaded files
        audio_format: Audio format (mp3, m4a, wav, etc.)
        audio_quality: Audio quality in kbps
        progress_callback: Function to call with progress updates
        
    Returns:
        Path to the downloaded audio file or None if download failed
        
    Raises:
        DownloadError: If download fails after retries
    """
    if not validate_url(url):
        error_msg = f"Invalid or unsupported URL: {url}"
        logger.error(error_msg)
        raise DownloadError(error_msg)
    
    retries = 0
    while retries < MAX_RETRIES:
        try:
            if progress_callback:
                progress_callback(f"Starting download (attempt {retries + 1}/{MAX_RETRIES})...")
            
            ydl_opts = get_download_options(output_dir, audio_format, audio_quality, progress_callback)
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                logger.info(f"Downloading audio from: {url}")
                
                # Extract info first without downloading
                info = ydl.extract_info(url, download=False)
                
                # Better file size estimation
                estimated_size = estimate_file_size(info)
                if estimated_size > MAX_FILE_SIZE:
                    error_msg = f"{FILE_TOO_LARGE_MESSAGE} (Estimated: {estimated_size / 1024 / 1024:.1f}MB)"
                    logger.error(error_msg)
                    raise DownloadError(error_msg)
                
                # Now download
                ydl.download([url])
                
                # Get the filename - needs some extra handling due to extraction
                filename = ydl.prepare_filename(info)
                base_filename = os.path.splitext(filename)[0]
                final_filename = f"{base_filename}.{audio_format}"
                
                # Verify file exists and return path
                if os.path.exists(final_filename):
                    return final_filename
                else:
                    # Try to find the file with a different extension
                    for ext in SUPPORTED_FORMATS:
                        potential_file = f"{base_filename}.{ext}"
                        if os.path.exists(potential_file):
                            return potential_file
                
                # If we get here, something went wrong
                raise FileNotFoundError(f"Could not locate downloaded file for {url}")
                
        except yt_dlp.utils.DownloadError as e:
            retries += 1
            error_msg = f"Download error (Attempt {retries}/{MAX_RETRIES}): {str(e)}"
            logger.error(error_msg)
            if progress_callback:
                progress_callback(error_msg)
            
            if "HTTP Error 429" in str(e):
                # Rate limiting - wait longer
                time.sleep(RETRY_DELAY * 5)
            elif retries >= MAX_RETRIES:
                raise DownloadError(f"Failed to download after {MAX_RETRIES} attempts: {str(e)}")
            else:
                time.sleep(RETRY_DELAY)
        except Exception as e:
            retries += 1
            error_msg = f"Unexpected error (Attempt {retries}/{MAX_RETRIES}): {str(e)}"
            logger.error(error_msg)
            if progress_callback:
                progress_callback(error_msg)
            
            if retries >= MAX_RETRIES:
                raise DownloadError(f"Failed to download after {MAX_RETRIES} attempts: {str(e)}")
            time.sleep(RETRY_DELAY)
    
    return None


def delete_download(path: str) -> bool:
    """
    Delete a downloaded file or directory
    
    Args:
        path: Path to file or directory to delete
        
    Returns:
        True if deletion was successful, False otherwise
    """
    try:
        if not path or not os.path.exists(path):
            logger.warning(f"Path does not exist: {path}")
            return False
        
        if os.path.isfile(path):
            os.remove(path)
            logger.info(f"File deleted: {path}")
        elif os.path.isdir(path):
            shutil.rmtree(path)
            logger.info(f"Directory deleted: {path}")
        else:
            logger.warning(f"Path is neither a file nor a directory: {path}")
            return False
        return True
    except PermissionError:
        logger.error(f"Permission denied: Unable to delete {path}")
    except FileNotFoundError:
        logger.error(f"File or directory not found: {path}")
    except Exception as e:
        logger.error(f"Error deleting {path}: {str(e)}")
    return False


def trim_audio_file(input_file: str, max_duration_seconds: int = 600) -> str:
    """
    Trim an audio file to a maximum duration to reduce file size
    
    Args:
        input_file: Path to input audio file
        max_duration_seconds: Maximum duration in seconds
        
    Returns:
        Path to trimmed file
    """
    try:
        import ffmpeg
        
        # Create output filename
        file_dir = os.path.dirname(input_file)
        file_name, file_ext = os.path.splitext(os.path.basename(input_file))
        output_file = os.path.join(file_dir, f"{file_name}_trimmed{file_ext}")
        
        # Trim using ffmpeg
        ffmpeg.input(input_file).output(
            output_file, t=str(max_duration_seconds), acodec='copy'
        ).run(quiet=True, overwrite_output=True)
        
        logger.info(f"Trimmed {input_file} to {max_duration_seconds} seconds")
        return output_file
    except Exception as e:
        logger.error(f"Error trimming audio: {str(e)}")
        return input_file  # Return original if trimming fails


def get_video_info(url: str) -> Dict[str, Any]:
    """
    Get information about a video without downloading
    
    Args:
        url: URL of the video
        
    Returns:
        Dictionary of video information
    """
    try:
        with yt_dlp.YoutubeDL({"quiet": True}) as ydl:
            info = ydl.extract_info(url, download=False)
            return info
    except Exception as e:
        logger.error(f"Error getting video info: {str(e)}")
        raise DownloadError(f"Could not retrieve video information: {str(e)}")