Spaces:
Runtime error
Runtime error
Update utils.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140import os, zipfile, shutil, subprocess, shlex, sys # noqafrom urllib.parse import urlparseimport reimport loggingdef load_file_from_url(url: str,model_dir: str,file_name: str | None = None,overwrite: bool = False,progress: bool = True,) -> str:"""Download a file from `url` into `model_dir`,using the file present if possible.Returns the path to the downloaded file."""os.makedirs(model_dir, exist_ok=True)if not file_name:parts = urlparse(url)file_name = os.path.basename(parts.path)cached_file = os.path.abspath(os.path.join(model_dir, file_name))# Overwriteif os.path.exists(cached_file):if overwrite or os.path.getsize(cached_file) == 0:remove_files(cached_file)# Downloadif not os.path.exists(cached_file):logger.info(f'Downloading: "{url}" to {cached_file}\n')from torch.hub import download_url_to_filedownload_url_to_file(url, cached_file, progress=progress)else:logger.debug(cached_file)return cached_filedef friendly_name(file: str):if file.startswith("http"):file = urlparse(file).pathfile = os.path.basename(file)model_name, extension = os.path.splitext(file)return model_name, extensiondef download_manager(url: str,path: str,extension: str = "",overwrite: bool = False,progress: bool = True,):url = url.strip()name, ext = friendly_name(url)name += ext if not extension else f".{extension}"if url.startswith("http"):filename = load_file_from_url(url=url,model_dir=path,file_name=name,overwrite=overwrite,progress=progress,)else:filename = pathreturn filenamedef remove_files(file_list):if isinstance(file_list, str):file_list = [file_list]for file in file_list:if os.path.exists(file):os.remove(file)def remove_directory_contents(directory_path):"""Removes all files and subdirectories within a directory.Parameters:directory_path (str): Path to the directory whosecontents need to be removed."""if os.path.exists(directory_path):for filename in os.listdir(directory_path):file_path = os.path.join(directory_path, filename)try:if os.path.isfile(file_path):os.remove(file_path)elif os.path.isdir(file_path):shutil.rmtree(file_path)except Exception as e:logger.error(f"Failed to delete {file_path}. Reason: {e}")logger.info(f"Content in '{directory_path}' removed.")else:logger.error(f"Directory '{directory_path}' does not exist.")# Create directory if not existsdef create_directories(directory_path):if isinstance(directory_path, str):directory_path = [directory_path]for one_dir_path in directory_path:if not os.path.exists(one_dir_path):os.makedirs(one_dir_path)logger.debug(f"Directory '{one_dir_path}' created.")def setup_logger(name_log):logger = logging.getLogger(name_log)logger.setLevel(logging.INFO)_default_handler = logging.StreamHandler() # Set sys.stderr as stream._default_handler.flush = sys.stderr.flushlogger.addHandler(_default_handler)logger.propagate = Falsehandlers = logger.handlersfor handler in handlers:formatter = logging.Formatter("[%(levelname)s] >> %(message)s")handler.setFormatter(formatter)# logger.handlersreturn loggerlogger = setup_logger("ss")logger.setLevel(logging.INFO)
utils.py+140