Spaces:
Build error
Build error
Update download.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596from __future__ import unicode_literalsimport yt_dlp as youtube_dlimport osimport timeimport osimport shutilMAX_FILE_SIZE = 100 * 1024 * 1024 # 100 MBFILE_TOO_LARGE_MESSAGE = "The audio file is too large for the current size and rate limits using Whisper. If you used a YouTube link, please try a shorter video clip. If you uploaded an audio file, try trimming or compressing the audio to under 100 MB."max_retries = 3delay = 2class MyLogger(object):def __init__(self, external_logger=lambda x: None):self.external_logger = external_loggerdef debug(self, msg):print("[debug]: ", msg)self.external_logger(msg)def warning(self, msg):print("[warning]: ", msg)def error(self, msg):print("[error]: ", msg)def my_hook(d):print("hook", d["status"])if d["status"] == "finished":print("Done downloading, now converting ...")def get_ydl_opts(external_logger=lambda x: None):return {"format": "bestaudio/best","postprocessors": [{"key": "FFmpegExtractAudio","preferredcodec": "mp3","preferredquality": "192", # set the preferred bitrate to 192kbps}],"logger": MyLogger(external_logger),"outtmpl": "./downloads/audio/%(title)s.%(ext)s", # Set the output filename directly"progress_hooks": [my_hook],}def download_video_audio(url, external_logger=lambda x: None):retries = 0while retries < max_retries:try:ydl_opts = get_ydl_opts(external_logger)with youtube_dl.YoutubeDL(ydl_opts) as ydl:print("Going to download ", url)info = ydl.extract_info(url, download=False)filesize = info.get("filesize", 0)if filesize > MAX_FILE_SIZE:raise Exception(FILE_TOO_LARGE_MESSAGE)filename = ydl.prepare_filename(info)res = ydl.download([url])print("youtube-dl result :", res)mp3_filename = os.path.splitext(filename)[0] + '.mp3'print('mp3 file name - ', mp3_filename)return mp3_filenameexcept Exception as e:retries += 1print(f"An error occurred during downloading (Attempt {retries}/{max_retries}):",str(e),)if retries >= max_retries:raise etime.sleep(delay)def delete_download(path):try:if os.path.isfile(path):os.remove(path)print(f"File {path} has been deleted.")elif os.path.isdir(path):shutil.rmtree(path)print(f"Directory {path} and its contents have been deleted.")else:print(f"The path {path} is neither a file nor a directory.")except PermissionError:print(f"Permission denied: Unable to delete {path}.")except FileNotFoundError:print(f"File or directory not found: {path}")except Exception as e:print(f"An error occurred while trying to delete {path}: {str(e)}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376from __future__ import unicode_literalsimport yt_dlpimport osimport timeimport shutilimport loggingimport reimport tempfilefrom pathlib import Pathfrom typing import Optional, Callable, Dict, Any, Union# ConfigurationMAX_FILE_SIZE = 40 * 1024 * 1024 # 40 MB (increased from your original 100MB)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 = 3RETRY_DELAY = 2 # secondsDEFAULT_AUDIO_FORMAT = "mp3"DEFAULT_AUDIO_QUALITY = "192" # kbpsSUPPORTED_FORMATS = ["mp3", "m4a", "wav", "aac", "flac", "opus"]# Setup logginglogging.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 informationif '%' 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"""passdef 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 parametersArgs:output_dir: Directory to save downloaded filesaudio_format: Audio format (mp3, m4a, wav, etc.)audio_quality: Audio quality in kbpsprogress_callback: Function to call with progress updatesReturns: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 existsoutput_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 progressArgs:d: Download information dictionarycallback: Function to call with progress updates"""if callback is None:callback = lambda x: Noneif 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 infoArgs:info: Video information dictionaryReturns:Estimated file size in bytes"""# Try different fields that might contain size informationfilesize = info.get("filesize")if filesize is not None:return filesizefilesize = info.get("filesize_approx")if filesize is not None:return filesize# If we have duration and a bitrate, we can estimateduration = 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 determinereturn MAX_FILE_SIZEdef 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 URLArgs:url: URL of the videooutput_dir: Directory to save downloaded filesaudio_format: Audio format (mp3, m4a, wav, etc.)audio_quality: Audio quality in kbpsprogress_callback: Function to call with progress updatesReturns:Path to the downloaded audio file or None if download failedRaises: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 = 0while 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 downloadinginfo = ydl.extract_info(url, download=False)# Better file size estimationestimated_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 downloadydl.download([url])# Get the filename - needs some extra handling due to extractionfilename = ydl.prepare_filename(info)base_filename = os.path.splitext(filename)[0]final_filename = f"{base_filename}.{audio_format}"# Verify file exists and return pathif os.path.exists(final_filename):return final_filenameelse:# Try to find the file with a different extensionfor 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 wrongraise FileNotFoundError(f"Could not locate downloaded file for {url}")except yt_dlp.utils.DownloadError as e:retries += 1error_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 longertime.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 += 1error_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 Nonedef delete_download(path: str) -> bool:"""Delete a downloaded file or directoryArgs:path: Path to file or directory to deleteReturns: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 Falseif 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 Falsereturn Trueexcept 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 Falsedef trim_audio_file(input_file: str, max_duration_seconds: int = 600) -> str:"""Trim an audio file to a maximum duration to reduce file sizeArgs:input_file: Path to input audio filemax_duration_seconds: Maximum duration in secondsReturns:Path to trimmed file"""try:import ffmpeg# Create output filenamefile_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 ffmpegffmpeg.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_fileexcept Exception as e:logger.error(f"Error trimming audio: {str(e)}")return input_file # Return original if trimming failsdef get_video_info(url: str) -> Dict[str, Any]:"""Get information about a video without downloadingArgs:url: URL of the videoReturns:Dictionary of video information"""try:with yt_dlp.YoutubeDL({"quiet": True}) as ydl:info = ydl.extract_info(url, download=False)return infoexcept Exception as e:logger.error(f"Error getting video info: {str(e)}")raise DownloadError(f"Could not retrieve video information: {str(e)}")# Example usageif __name__ == "__main__":# Example progress callbackdef print_progress(msg):print(msg)try:# Example: Download audio from a YouTube URLurl = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"audio_path = download_video_audio(url,output_dir="./downloads",audio_format="mp3",progress_callback=print_progress)print(f"Downloaded to: {audio_path}")# Clean upif audio_path:delete_download(audio_path)except DownloadError as e:print(f"Download failed: {e}")
download.py+341-61