1 line
34 KiB
JSON
1 line
34 KiB
JSON
{"repo": "aszhl/yolo", "files": {"utils/__init__.py": {"374d0b29fec99026618c72e8f663885b52e33182": {"t": 1785595837.1232305, "n": 33688, "h": "7dca94e6ecde2340", "c": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport inspect\nimport logging.config\nimport os\nimport platform\nimport re\nimport subprocess\nimport sys\nimport threading\nimport urllib\nimport uuid\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom typing import Union\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport yaml\nfrom tqdm import tqdm as tqdm_original\n\nfrom ultralytics import __version__\n\n# PyTorch Multi-GPU DDP Constants\nRANK = int(os.getenv('RANK', -1))\nLOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html\n\n# Other Constants\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[1] # YOLO\nASSETS = ROOT / 'assets' # default images\nDEFAULT_CFG_PATH = ROOT / 'cfg/default.yaml'\nNUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads\nAUTOINSTALL = str(os.getenv('YOLO_AUTOINSTALL', True)).lower() == 'true' # global auto-install mode\nVERBOSE = str(os.getenv('YOLO_VERBOSE', True)).lower() == 'true' # global verbose mode\nTQDM_BAR_FORMAT = '{l_bar}{bar:10}{r_bar}' if VERBOSE else None # tqdm bar format\nLOGGING_NAME = 'ultralytics'\nMACOS, LINUX, WINDOWS = (platform.system() == x for x in ['Darwin', 'Linux', 'Windows']) # environment booleans\nARM64 = platform.machine() in ('arm64', 'aarch64') # ARM64 booleans\nHELP_MSG = \\\n \"\"\"\n Usage examples for running YOLOv8:\n\n 1. Install the ultralytics package:\n\n pip install ultralytics\n\n 2. Use the Python SDK:\n\n from ultralytics import YOLO\n\n # Load a model\n model = YOLO('yolov8n.yaml') # build a new model from scratch\n model = YOLO(\"yolov8n.pt\") # load a pretrained model (recommended for training)\n\n # Use the model\n results = model.train(data=\"coco128.yaml\", epochs=3) # train the model\n results = model.val() # evaluate model performance on the validation set\n results = model('https://ultralytics.com/images/bus.jpg') # predict on an image\n success = model.export(format='onnx') # export the model to ONNX format\n\n 3. Use the command line interface (CLI):\n\n YOLOv8 'yolo' CLI commands use the following syntax:\n\n yolo TASK MODE ARGS\n\n Where TASK (optional) is one of [detect, segment, classify]\n MODE (required) is one of [train, val, predict, export]\n ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.\n See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg'\n\n - Train a detection model for 10 epochs with an initial learning_rate of 0.01\n yolo detect train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01\n\n - Predict a YouTube video using a pretrained segmentation model at image size 320:\n yolo segment predict model=yolov8n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320\n\n - Val a pretrained detection model at batch-size 1 and image size 640:\n yolo detect val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640\n\n - Export a YOLOv8n classification model to ONNX format at image size 224 by 128 (no TASK required)\n yolo export model=yolov8n-cls.pt format=onnx imgsz=224,128\n\n - Run special commands:\n yolo help\n yolo checks\n yolo version\n yolo settings\n yolo copy-cfg\n yolo cfg\n\n Docs: https://docs.ultralytics.com\n Community: https://community.ultralytics.com\n GitHub: https://github.com/ultralytics/ultralytics\n \"\"\"\n\n# Settings\ntorch.set_printoptions(linewidth=320, precision=4, profile='default')\nnp.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5\ncv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)\nos.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS) # NumExpr max threads\nos.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' # for deterministic training\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # suppress verbose TF compiler warnings in Colab\n\n\nclass TQDM(tqdm_original):\n \"\"\"\n Custom Ultralytics tqdm class with different default arguments.\n\n Args:\n *args (list): Positional arguments passed to original tqdm.\n **kwargs (dict): Keyword arguments, with custom defaults applied.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initialize custom Ultralytics tqdm class with different default arguments.\"\"\"\n # Set new default values (these can still be overridden when calling TQDM)\n kwargs['disable'] = not VERBOSE or kwargs.get('disable', False) # logical 'and' with default value if passed\n kwargs.setdefault('bar_format', TQDM_BAR_FORMAT) # override default value if passed\n super().__init__(*args, **kwargs)\n\n\nclass SimpleClass:\n \"\"\"Ultralytics SimpleClass is a base class providing helpful string representation, error reporting, and attribute\n access methods for easier debugging and usage.\n \"\"\"\n\n def __str__(self):\n \"\"\"Return a human-readable string representation of the object.\"\"\"\n attr = []\n for a in dir(self):\n v = getattr(self, a)\n if not callable(v) and not a.startswith('_'):\n if isinstance(v, SimpleClass):\n # Display only the module and class name for subclasses\n s = f'{a}: {v.__module__}.{v.__class__.__name__} object'\n else:\n s = f'{a}: {repr(v)}'\n attr.append(s)\n return f'{self.__module__}.{self.__class__.__name__} object with attributes:\\n\\n' + '\\n'.join(attr)\n\n def __repr__(self):\n \"\"\"Return a machine-readable string representation of the object.\"\"\"\n return self.__str__()\n\n def __getattr__(self, attr):\n \"\"\"Custom attribute access error message with helpful information.\"\"\"\n name = self.__class__.__name__\n raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n\n\nclass IterableSimpleNamespace(SimpleNamespace):\n \"\"\"Ultralytics IterableSimpleNamespace is an extension class of SimpleNamespace that adds iterable functionality and\n enables usage with dict() and for loops.\n \"\"\"\n\n def __iter__(self):\n \"\"\"Return an iterator of key-value pairs from the namespace's attributes.\"\"\"\n return iter(vars(self).items())\n\n def __str__(self):\n \"\"\"Return a human-readable string representation of the object.\"\"\"\n return '\\n'.join(f'{k}={v}' for k, v in vars(self).items())\n\n def __getattr__(self, attr):\n \"\"\"Custom attribute access error message with helpful information.\"\"\"\n name = self.__class__.__name__\n raise AttributeError(f\"\"\"\n '{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics\n 'default.yaml' file.\\nPlease update your code with 'pip install -U ultralytics' and if necessary replace\n {DEFAULT_CFG_PATH} with the latest version from\n https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml\n \"\"\")\n\n def get(self, key, default=None):\n \"\"\"Return the value of the specified key if it exists; otherwise, return the default value.\"\"\"\n return getattr(self, key, default)\n\n\ndef plt_settings(rcparams=None, backend='Agg'):\n \"\"\"\n Decorator to temporarily set rc parameters and the backend for a plotting function.\n\n Example:\n decorator: @plt_settings({\"font.size\": 12})\n context manager: with plt_settings({\"font.size\": 12}):\n\n Args:\n rcparams (dict): Dictionary of rc parameters to set.\n backend (str, optional): Name of the backend to use. Defaults to 'Agg'.\n\n Returns:\n (Callable): Decorated function with temporarily set rc parameters and backend. This decorator can be\n applied to any function that needs to have specific matplotlib rc parameters and backend for its execution.\n \"\"\"\n\n if rcparams is None:\n rcparams = {'font.size': 11, 'font.family': 'SimHei', 'axes.unicode_minus': False}\n\n def decorator(func):\n \"\"\"Decorator to apply temporary rc parameters and backend to a function.\"\"\"\n\n def wrapper(*args, **kwargs):\n \"\"\"Sets rc parameters and backend, calls the original function, and restores the settings.\"\"\"\n original_backend = plt.get_backend()\n if backend != original_backend:\n plt.close('all') # auto-close()ing of figures upon backend switching is deprecated since 3.8\n plt.switch_backend(backend)\n\n with plt.rc_context(rcparams):\n result = func(*args, **kwargs)\n\n if backend != original_backend:\n plt.close('all')\n plt.switch_backend(original_backend)\n return result\n\n return wrapper\n\n return decorator\n\n\ndef set_logging(name=LOGGING_NAME, verbose=True):\n \"\"\"Sets up logging for the given name.\"\"\"\n rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings\n level = logging.INFO if verbose and rank in {-1, 0} else logging.ERROR\n logging.config.dictConfig({\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n name: {\n 'format': '%(message)s'}},\n 'handlers': {\n name: {\n 'class': 'logging.StreamHandler',\n 'formatter': name,\n 'level': level}},\n 'loggers': {\n name: {\n 'level': level,\n 'handlers': [name],\n 'propagate': False}}})\n\n\ndef emojis(string=''):\n \"\"\"Return platform-dependent emoji-safe version of string.\"\"\"\n return string.encode().decode('ascii', 'ignore') if WINDOWS else string\n\n\nclass EmojiFilter(logging.Filter):\n \"\"\"\n A custom logging filter class for removing emojis in log messages.\n\n This filter is particularly useful for ensuring compatibility with Windows terminals that may not support the\n display of emojis in log messages.\n \"\"\"\n\n def filter(self, record):\n \"\"\"Filter logs by emoji unicode characters on windows.\"\"\"\n record.msg = emojis(record.msg)\n return super().filter(record)\n\n\n# Set logger\nset_logging(LOGGING_NAME, verbose=VERBOSE) # run before defining LOGGER\nLOGGER = logging.getLogger(LOGGING_NAME) # define globally (used in train.py, val.py, detect.py, etc.)\nif WINDOWS: # emoji-safe logging\n LOGGER.addFilter(EmojiFilter())\nfor logger in 'sentry_sdk', 'urllib3.connectionpool':\n logging.getLogger(logger).setLevel(logging.CRITICAL)\n\n\nclass ThreadingLocked:\n \"\"\"\n A decorator class for ensuring thread-safe execution of a function or method. This class can be used as a decorator\n to make sure that if the decorated function is called from multiple threads, only one thread at a time will be able\n to execute the function.\n\n Attributes:\n lock (threading.Lock): A lock object used to manage access to the decorated function.\n\n Example:\n ```python\n from ultralytics.utils import ThreadingLocked\n\n @ThreadingLocked()\n def my_function():\n # Your code here\n pass\n ```\n \"\"\"\n\n def __init__(self):\n \"\"\"Initializes the decorator class for thread-safe execution of a function or method.\"\"\"\n self.lock = threading.Lock()\n\n def __call__(self, f):\n \"\"\"Run thread-safe execution of function or method.\"\"\"\n from functools import wraps\n\n @wraps(f)\n def decorated(*args, **kwargs):\n \"\"\"Applies thread-safety to the decorated function or method.\"\"\"\n with self.lock:\n return f(*args, **kwargs)\n\n return decorated\n\n\ndef yaml_save(file='data.yaml', data=None, header=''):\n \"\"\"\n Save YAML data to a file.\n\n Args:\n file (str, optional): File name. Default is 'data.yaml'.\n data (dict): Data to save in YAML format.\n header (str, optional): YAML header to add.\n\n Returns:\n (None): Data is saved to the specified file.\n \"\"\"\n if data is None:\n data = {}\n file = Path(file)\n if not file.parent.exists():\n # Create parent directories if they don't exist\n file.parent.mkdir(parents=True, exist_ok=True)\n\n # Convert Path objects to strings\n valid_types = int, float, str, bool, list, tuple, dict, type(None)\n for k, v in data.items():\n if not isinstance(v, valid_types):\n data[k] = str(v)\n\n # Dump data to file in YAML format\n with open(file, 'w', errors='ignore', encoding='utf-8') as f:\n if header:\n f.write(header)\n yaml.safe_dump(data, f, sort_keys=False, allow_unicode=True)\n\n\ndef yaml_load(file='data.yaml', append_filename=False):\n \"\"\"\n Load YAML data from a file.\n\n Args:\n file (str, optional): File name. Default is 'data.yaml'.\n append_filename (bool): Add the YAML filename to the YAML dictionary. Default is False.\n\n Returns:\n (dict): YAML data and file name.\n \"\"\"\n assert Path(file).suffix in ('.yaml', '.yml'), f'Attempting to load non-YAML file {file} with yaml_load()'\n with open(file, errors='ignore', encoding='utf-8') as f:\n s = f.read() # string\n\n # Remove special characters\n if not s.isprintable():\n s = re.sub(r'[^\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\U00010000-\\U0010ffff]+', '', s)\n\n # Add YAML filename to dict and return\n data = yaml.safe_load(s) or {} # always return a dict (yaml.safe_load() may return None for empty files)\n if append_filename:\n data['yaml_file'] = str(file)\n return data\n\n\ndef yaml_print(yaml_file: Union[str, Path, dict]) -> None:\n \"\"\"\n Pretty prints a YAML file or a YAML-formatted dictionary.\n\n Args:\n yaml_file: The file path of the YAML file or a YAML-formatted dictionary.\n\n Returns:\n None\n \"\"\"\n yaml_dict = yaml_load(yaml_file) if isinstance(yaml_file, (str, Path)) else yaml_file\n dump = yaml.dump(yaml_dict, sort_keys=False, allow_unicode=True)\n LOGGER.info(f\"Printing '{colorstr('bold', 'black', yaml_file)}'\\n\\n{dump}\")\n\n\n# Default configuration\nDEFAULT_CFG_DICT = yaml_load(DEFAULT_CFG_PATH)\nfor k, v in DEFAULT_CFG_DICT.items():\n if isinstance(v, str) and v.lower() == 'none':\n DEFAULT_CFG_DICT[k] = None\nDEFAULT_CFG_KEYS = DEFAULT_CFG_DICT.keys()\nDEFAULT_CFG = IterableSimpleNamespace(**DEFAULT_CFG_DICT)\n\n\ndef is_ubuntu() -> bool:\n \"\"\"\n Check if the OS is Ubuntu.\n\n Returns:\n (bool): True if OS is Ubuntu, False otherwise.\n \"\"\"\n with contextlib.suppress(FileNotFoundError):\n with open('/etc/os-release') as f:\n return 'ID=ubuntu' in f.read()\n return False\n\n\ndef is_colab():\n \"\"\"\n Check if the current script is running inside a Google Colab notebook.\n\n Returns:\n (bool): True if running inside a Colab notebook, False otherwise.\n \"\"\"\n return 'COLAB_RELEASE_TAG' in os.environ or 'COLAB_BACKEND_VERSION' in os.environ\n\n\ndef is_kaggle():\n \"\"\"\n Check if the current script is running inside a Kaggle kernel.\n\n Returns:\n (bool): True if running inside a Kaggle kernel, False otherwise.\n \"\"\"\n return os.environ.get('PWD') == '/kaggle/working' and os.environ.get('KAGGLE_URL_BASE') == 'https://www.kaggle.com'\n\n\ndef is_jupyter():\n \"\"\"\n Check if the current script is running inside a Jupyter Notebook. Verified on Colab, Jupyterlab, Kaggle, Paperspace.\n\n Returns:\n (bool): True if running inside a Jupyter Notebook, False otherwise.\n \"\"\"\n with contextlib.suppress(Exception):\n from IPython import get_ipython\n return get_ipython() is not None\n return False\n\n\ndef is_docker() -> bool:\n \"\"\"\n Determine if the script is running inside a Docker container.\n\n Returns:\n (bool): True if the script is running inside a Docker container, False otherwise.\n \"\"\"\n file = Path('/proc/self/cgroup')\n if file.exists():\n with open(file) as f:\n return 'docker' in f.read()\n else:\n return False\n\n\ndef is_online() -> bool:\n \"\"\"\n Check internet connectivity by attempting to connect to a known online host.\n\n Returns:\n (bool): True if connection is successful, False otherwise.\n \"\"\"\n import socket\n\n for host in '1.1.1.1', '8.8.8.8', '223.5.5.5': # Cloudflare, Google, AliDNS:\n try:\n test_connection = socket.create_connection(address=(host, 53), timeout=2)\n except (socket.timeout, socket.gaierror, OSError):\n continue\n else:\n # If the connection was successful, close it to avoid a ResourceWarning\n test_connection.close()\n return True\n return False\n\n\nONLINE = is_online()\n\n\ndef is_pip_package(filepath: str = __name__) -> bool:\n \"\"\"\n Determines if the file at the given filepath is part of a pip package.\n\n Args:\n filepath (str): The filepath to check.\n\n Returns:\n (bool): True if the file is part of a pip package, False otherwise.\n \"\"\"\n import importlib.util\n\n # Get the spec for the module\n spec = importlib.util.find_spec(filepath)\n\n # Return whether the spec is not None and the origin is not None (indicating it is a package)\n return spec is not None and spec.origin is not None\n\n\ndef is_dir_writeable(dir_path: Union[str, Path]) -> bool:\n \"\"\"\n Check if a directory is writeable.\n\n Args:\n dir_path (str | Path): The path to the directory.\n\n Returns:\n (bool): True if the directory is writeable, False otherwise.\n \"\"\"\n return os.access(str(dir_path), os.W_OK)\n\n\ndef is_pytest_running():\n \"\"\"\n Determines whether pytest is currently running or not.\n\n Returns:\n (bool): True if pytest is running, False otherwise.\n \"\"\"\n return ('PYTEST_CURRENT_TEST' in os.environ) or ('pytest' in sys.modules) or ('pytest' in Path(sys.argv[0]).stem)\n\n\ndef is_github_actions_ci() -> bool:\n \"\"\"\n Determine if the current environment is a GitHub Actions CI Python runner.\n\n Returns:\n (bool): True if the current environment is a GitHub Actions CI Python runner, False otherwise.\n \"\"\"\n return 'GITHUB_ACTIONS' in os.environ and 'RUNNER_OS' in os.environ and 'RUNNER_TOOL_CACHE' in os.environ\n\n\ndef is_git_dir():\n \"\"\"\n Determines whether the current file is part of a git repository. If the current file is not part of a git\n repository, returns None.\n\n Returns:\n (bool): True if current file is part of a git repository.\n \"\"\"\n return get_git_dir() is not None\n\n\ndef get_git_dir():\n \"\"\"\n Determines whether the current file is part of a git repository and if so, returns the repository root directory. If\n the current file is not part of a git repository, returns None.\n\n Returns:\n (Path | None): Git root directory if found or None if not found.\n \"\"\"\n for d in Path(__file__).parents:\n if (d / '.git').is_dir():\n return d\n\n\ndef get_git_origin_url():\n \"\"\"\n Retrieves the origin URL of a git repository.\n\n Returns:\n (str | None): The origin URL of the git repository or None if not git directory.\n \"\"\"\n if is_git_dir():\n with contextlib.suppress(subprocess.CalledProcessError):\n origin = subprocess.check_output(['git', 'config', '--get', 'remote.origin.url'])\n return origin.decode().strip()\n\n\ndef get_git_branch():\n \"\"\"\n Returns the current git branch name. If not in a git repository, returns None.\n\n Returns:\n (str | None): The current git branch name or None if not a git directory.\n \"\"\"\n if is_git_dir():\n with contextlib.suppress(subprocess.CalledProcessError):\n origin = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])\n return origin.decode().strip()\n\n\ndef get_default_args(func):\n \"\"\"\n Returns a dictionary of default arguments for a function.\n\n Args:\n func (callable): The function to inspect.\n\n Returns:\n (dict): A dictionary where each key is a parameter name, and each value is the default value of that parameter.\n \"\"\"\n signature = inspect.signature(func)\n return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}\n\n\ndef get_ubuntu_version():\n \"\"\"\n Retrieve the Ubuntu version if the OS is Ubuntu.\n\n Returns:\n (str): Ubuntu version or None if not an Ubuntu OS.\n \"\"\"\n if is_ubuntu():\n with contextlib.suppress(FileNotFoundError, AttributeError):\n with open('/etc/os-release') as f:\n return re.search(r'VERSION_ID=\"(\\d+\\.\\d+)\"', f.read())[1]\n\n\ndef get_user_config_dir(sub_dir='Ultralytics'):\n \"\"\"\n Get the user config directory.\n\n Args:\n sub_dir (str): The name of the subdirectory to create.\n\n Returns:\n (Path): The path to the user config directory.\n \"\"\"\n # Return the appropriate config directory for each operating system\n if WINDOWS:\n path = Path.home() / 'AppData' / 'Roaming' / sub_dir\n elif MACOS: # macOS\n path = Path.home() / 'Library' / 'Application Support' / sub_dir\n elif LINUX:\n path = Path.home() / '.config' / sub_dir\n else:\n raise ValueError(f'Unsupported operating system: {platform.system()}')\n\n # GCP and AWS lambda fix, only /tmp is writeable\n if not is_dir_writeable(path.parent):\n LOGGER.warning(f\"WARNING ⚠️ user config directory '{path}' is not writeable, defaulting to '/tmp' or CWD.\"\n 'Alternatively you can define a YOLO_CONFIG_DIR environment variable for this path.')\n path = Path('/tmp') / sub_dir if is_dir_writeable('/tmp') else Path().cwd() / sub_dir\n\n # Create the subdirectory if it does not exist\n path.mkdir(parents=True, exist_ok=True)\n\n return path\n\n\nUSER_CONFIG_DIR = Path(os.getenv('YOLO_CONFIG_DIR') or get_user_config_dir()) # Ultralytics settings dir\nSETTINGS_YAML = USER_CONFIG_DIR / 'settings.yaml'\n\n\ndef colorstr(*input):\n \"\"\"\n Colors a string based on the provided color and style arguments. Utilizes ANSI escape codes.\n See https://en.wikipedia.org/wiki/ANSI_escape_code for more details.\n\n This function can be called in two ways:\n - colorstr('color', 'style', 'your string')\n - colorstr('your string')\n\n In the second form, 'blue' and 'bold' will be applied by default.\n\n Args:\n *input (str): A sequence of strings where the first n-1 strings are color and style arguments,\n and the last string is the one to be colored.\n\n Supported Colors and Styles:\n Basic Colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'\n Bright Colors: 'bright_black', 'bright_red', 'bright_green', 'bright_yellow',\n 'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white'\n Misc: 'end', 'bold', 'underline'\n\n Returns:\n (str): The input string wrapped with ANSI escape codes for the specified color and style.\n\n Examples:\n >>> colorstr('blue', 'bold', 'hello world')\n >>> '\\033[34m\\033[1mhello world\\033[0m'\n \"\"\"\n *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string\n colors = {\n 'black': '\\033[30m', # basic colors\n 'red': '\\033[31m',\n 'green': '\\033[32m',\n 'yellow': '\\033[33m',\n 'blue': '\\033[34m',\n 'magenta': '\\033[35m',\n 'cyan': '\\033[36m',\n 'white': '\\033[37m',\n 'bright_black': '\\033[90m', # bright colors\n 'bright_red': '\\033[91m',\n 'bright_green': '\\033[92m',\n 'bright_yellow': '\\033[93m',\n 'bright_blue': '\\033[94m',\n 'bright_magenta': '\\033[95m',\n 'bright_cyan': '\\033[96m',\n 'bright_white': '\\033[97m',\n 'end': '\\033[0m', # misc\n 'bold': '\\033[1m',\n 'underline': '\\033[4m'}\n return ''.join(colors[x] for x in args) + f'{string}' + colors['end']\n\n\ndef remove_colorstr(input_string):\n \"\"\"\n Removes ANSI escape codes from a string, effectively un-coloring it.\n\n Args:\n input_string (str): The string to remove color and style from.\n\n Returns:\n (str): A new string with all ANSI escape codes removed.\n\n Examples:\n >>> remove_colorstr(colorstr('blue', 'bold', 'hello world'))\n >>> 'hello world'\n \"\"\"\n ansi_escape = re.compile(r'\\x1B\\[[0-9;]*[A-Za-z]')\n return ansi_escape.sub('', input_string)\n\n\nclass TryExcept(contextlib.ContextDecorator):\n \"\"\"\n YOLOv8 TryExcept class.\n\n Use as @TryExcept() decorator or 'with TryExcept():' context manager.\n \"\"\"\n\n def __init__(self, msg='', verbose=True):\n \"\"\"Initialize TryExcept class with optional message and verbosity settings.\"\"\"\n self.msg = msg\n self.verbose = verbose\n\n def __enter__(self):\n \"\"\"Executes when entering TryExcept context, initializes instance.\"\"\"\n pass\n\n def __exit__(self, exc_type, value, traceback):\n \"\"\"Defines behavior when exiting a 'with' block, prints error message if necessary.\"\"\"\n if self.verbose and value:\n print(emojis(f\"{self.msg}{': ' if self.msg else ''}{value}\"))\n return True\n\n\ndef threaded(func):\n \"\"\"\n Multi-threads a target function and returns thread.\n\n Use as @threaded decorator.\n \"\"\"\n\n def wrapper(*args, **kwargs):\n \"\"\"Multi-threads a given function and returns the thread.\"\"\"\n thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)\n thread.start()\n return thread\n\n return wrapper\n\n\ndef set_sentry():\n \"\"\"\n Initialize the Sentry SDK for error tracking and reporting. Only used if sentry_sdk package is installed and\n sync=True in settings. Run 'yolo settings' to see and update settings YAML file.\n\n Conditions required to send errors (ALL conditions must be met or no errors will be reported):\n - sentry_sdk package is installed\n - sync=True in YOLO settings\n - pytest is not running\n - running in a pip package installation\n - running in a non-git directory\n - running with rank -1 or 0\n - online environment\n - CLI used to run package (checked with 'yolo' as the name of the main CLI command)\n\n The function also configures Sentry SDK to ignore KeyboardInterrupt and FileNotFoundError\n exceptions and to exclude events with 'out of memory' in their exception message.\n\n Additionally, the function sets custom tags and user information for Sentry events.\n \"\"\"\n\n def before_send(event, hint):\n \"\"\"\n Modify the event before sending it to Sentry based on specific exception types and messages.\n\n Args:\n event (dict): The event dictionary containing information about the error.\n hint (dict): A dictionary containing additional information about the error.\n\n Returns:\n dict: The modified event or None if the event should not be sent to Sentry.\n \"\"\"\n if 'exc_info' in hint:\n exc_type, exc_value, tb = hint['exc_info']\n if exc_type in (KeyboardInterrupt, FileNotFoundError) \\\n or 'out of memory' in str(exc_value):\n return None # do not send event\n\n event['tags'] = {\n 'sys_argv': sys.argv[0],\n 'sys_argv_name': Path(sys.argv[0]).name,\n 'install': 'git' if is_git_dir() else 'pip' if is_pip_package() else 'other',\n 'os': ENVIRONMENT}\n return event\n\n if SETTINGS['sync'] and \\\n RANK in (-1, 0) and \\\n Path(sys.argv[0]).name == 'yolo' and \\\n not TESTS_RUNNING and \\\n ONLINE and \\\n is_pip_package() and \\\n not is_git_dir():\n\n # If sentry_sdk package is not installed then return and do not use Sentry\n try:\n import sentry_sdk # noqa\n except ImportError:\n return\n\n sentry_sdk.init(\n dsn='https://5ff1556b71594bfea135ff0203a0d290@o4504521589325824.ingest.sentry.io/4504521592406016',\n debug=False,\n traces_sample_rate=1.0,\n release=__version__,\n environment='production', # 'dev' or 'production'\n before_send=before_send,\n ignore_errors=[KeyboardInterrupt, FileNotFoundError])\n sentry_sdk.set_user({'id': SETTINGS['uuid']}) # SHA-256 anonymized UUID hash\n\n\nclass SettingsManager(dict):\n \"\"\"\n Manages Ultralytics settings stored in a YAML file.\n\n Args:\n file (str | Path): Path to the Ultralytics settings YAML file. Default is USER_CONFIG_DIR / 'settings.yaml'.\n version (str): Settings version. In case of local version mismatch, new default settings will be saved.\n \"\"\"\n\n def __init__(self, file=SETTINGS_YAML, version='0.0.4'):\n \"\"\"Initialize the SettingsManager with default settings, load and validate current settings from the YAML\n file.\n \"\"\"\n import copy\n import hashlib\n\n from ultralytics.utils.checks import check_version\n from ultralytics.utils.torch_utils import torch_distributed_zero_first\n\n git_dir = get_git_dir()\n root = git_dir or Path()\n datasets_root = (root.parent if git_dir and is_dir_writeable(root.parent) else root).resolve()\n\n self.file = Path(file)\n self.version = version\n self.defaults = {\n 'settings_version': version,\n 'datasets_dir': str(datasets_root / 'datasets'),\n 'weights_dir': str(root / 'weights'),\n 'runs_dir': str(root / 'runs'),\n 'uuid': hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(),\n 'sync': True,\n 'api_key': '',\n 'clearml': True, # integrations\n 'comet': True,\n 'dvc': True,\n 'hub': True,\n 'mlflow': True,\n 'neptune': True,\n 'raytune': True,\n 'tensorboard': True,\n 'wandb': True}\n\n super().__init__(copy.deepcopy(self.defaults))\n\n with torch_distributed_zero_first(RANK):\n if not self.file.exists():\n self.save()\n\n self.load()\n correct_keys = self.keys() == self.defaults.keys()\n correct_types = all(type(a) is type(b) for a, b in zip(self.values(), self.defaults.values()))\n correct_version = check_version(self['settings_version'], self.version)\n if not (correct_keys and correct_types and correct_version):\n LOGGER.warning(\n 'WARNING ⚠️ Ultralytics settings reset to default values. This may be due to a possible problem '\n 'with your settings or a recent ultralytics package update. '\n f\"\\nView settings with 'yolo settings' or at '{self.file}'\"\n \"\\nUpdate settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'.\")\n self.reset()\n\n def load(self):\n \"\"\"Loads settings from the YAML file.\"\"\"\n super().update(yaml_load(self.file))\n\n def save(self):\n \"\"\"Saves the current settings to the YAML file.\"\"\"\n yaml_save(self.file, dict(self))\n\n def update(self, *args, **kwargs):\n \"\"\"Updates a setting value in the current settings.\"\"\"\n super().update(*args, **kwargs)\n self.save()\n\n def reset(self):\n \"\"\"Resets the settings to default and saves them.\"\"\"\n self.clear()\n self.update(self.defaults)\n self.save()\n\n\ndef deprecation_warn(arg, new_arg, version=None):\n \"\"\"Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument.\"\"\"\n if not version:\n version = float(__version__[:3]) + 0.2 # deprecate after 2nd major release\n LOGGER.warning(f\"WARNING ⚠️ '{arg}' is deprecated and will be removed in 'ultralytics {version}' in the future. \"\n f\"Please use '{new_arg}' instead.\")\n\n\ndef clean_url(url):\n \"\"\"Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt.\"\"\"\n url = Path(url).as_posix().replace(':/', '://') # Pathlib turns :// -> :/, as_posix() for Windows\n return urllib.parse.unquote(url).split('?')[0] # '%2F' to '/', split https://url.com/file.txt?auth\n\n\ndef url2file(url):\n \"\"\"Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt.\"\"\"\n return Path(clean_url(url)).name\n\n\n# Run below code on utils init ------------------------------------------------------------------------------------\n\n# Check first-install steps\nPREFIX = colorstr('Ultralytics: ')\nSETTINGS = SettingsManager() # initialize settings\nDATASETS_DIR = Path(SETTINGS['datasets_dir']) # global datasets directory\nWEIGHTS_DIR = Path(SETTINGS['weights_dir']) # global weights directory\nRUNS_DIR = Path(SETTINGS['runs_dir']) # global runs directory\nENVIRONMENT = 'Colab' if is_colab() else 'Kaggle' if is_kaggle() else 'Jupyter' if is_jupyter() else \\\n 'Docker' if is_docker() else platform.system()\nTESTS_RUNNING = is_pytest_running() or is_github_actions_ci()\nset_sentry()\n\n# Apply monkey patches\nfrom .patches import imread, imshow, imwrite, torch_save\n\ntorch.save = torch_save\nif WINDOWS:\n # Apply cv2 patches for non-ASCII and non-UTF characters in image paths\n cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow\n"}}}} |