{"repo": "aliqasim222/yolov8-ghost", "files": {"Ultralytics/utils/__init__.py": {"5d187e0a90b9261c0597a053f602dd387d4395a9": {"t": 1785595831.8621316, "n": 59046, "h": "08f2c8823eb61cc6", "c": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nimport contextlib\nimport importlib.metadata\nimport inspect\nimport json\nimport logging\nimport os\nimport platform\nimport re\nimport subprocess\nimport sys\nimport threading\nimport time\nimport warnings\nfrom pathlib import Path\nfrom threading import Lock\nfrom types import SimpleNamespace\nfrom typing import Union\nfrom urllib.parse import unquote\n\nimport cv2\nimport numpy as np\nimport torch\nimport tqdm\n\nfrom ultralytics import __version__\nfrom ultralytics.utils.patches import imread, imshow, imwrite, torch_load, torch_save # for patches\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\nARGV = sys.argv or [\"\", \"\"] # sometimes sys.argv = []\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[1] # YOLO\nASSETS = ROOT / \"assets\" # default images\nASSETS_URL = \"https://github.com/ultralytics/assets/releases/download/v0.0.0\" # assets GitHub URL\nDEFAULT_CFG_PATH = ROOT / \"cfg/default.yaml\"\nNUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLO 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\nMACOS_VERSION = platform.mac_ver()[0] if MACOS else None\nARM64 = platform.machine() in {\"arm64\", \"aarch64\"} # ARM64 booleans\nPYTHON_VERSION = platform.python_version()\nTORCH_VERSION = torch.__version__\nTORCHVISION_VERSION = importlib.metadata.version(\"torchvision\") # faster than importing torchvision\nIS_VSCODE = os.environ.get(\"TERM_PROGRAM\", False) == \"vscode\"\nRKNN_CHIPS = frozenset(\n {\n \"rk3588\",\n \"rk3576\",\n \"rk3566\",\n \"rk3568\",\n \"rk3562\",\n \"rv1103\",\n \"rv1106\",\n \"rv1103b\",\n \"rv1106b\",\n \"rk2118\",\n }\n) # Rockchip processors available for export\nHELP_MSG = \"\"\"\n Examples for running Ultralytics:\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(\"yolo11n.yaml\") # build a new model from scratch\n model = YOLO(\"yolo11n.pt\") # load a pretrained model (recommended for training)\n\n # Use the model\n results = model.train(data=\"coco8.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 Ultralytics 'yolo' CLI commands use the following syntax:\n\n yolo TASK MODE ARGS\n\n Where TASK (optional) is one of [detect, segment, classify, pose, obb]\n MODE (required) is one of [train, val, predict, export, track, benchmark]\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=coco8.yaml model=yolo11n.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=yolo11n-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=yolo11n.pt data=coco8.yaml batch=1 imgsz=640\n\n - Export a YOLO11n classification model to ONNX format at image size 224 by 128 (no TASK required)\n yolo export model=yolo11n-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 and Environment Variables\ntorch.set_printoptions(linewidth=320, precision=4, profile=\"default\")\nnp.set_printoptions(linewidth=320, formatter=dict(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[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\" # suppress verbose TF compiler warnings in Colab\nos.environ[\"TORCH_CPP_LOG_LEVEL\"] = \"ERROR\" # suppress \"NNPACK.cpp could not initialize NNPACK\" warnings\nos.environ[\"KINETO_LOG_LEVEL\"] = \"5\" # suppress verbose PyTorch profiler output when computing FLOPs\n\nif TQDM_RICH := str(os.getenv(\"YOLO_TQDM_RICH\", False)).lower() == \"true\":\n from tqdm import rich\n\n\nclass TQDM(rich.tqdm if TQDM_RICH else tqdm.tqdm):\n \"\"\"\n A custom TQDM progress bar class that extends the original tqdm functionality.\n\n This class modifies the behavior of the original tqdm progress bar based on global settings and provides\n additional customization options.\n\n Attributes:\n disable (bool): Whether to disable the progress bar. Determined by the global VERBOSE setting and\n any passed 'disable' argument.\n bar_format (str): The format string for the progress bar. Uses the global TQDM_BAR_FORMAT if not\n explicitly set.\n\n Methods:\n __init__: Initializes the TQDM object with custom settings.\n\n Examples:\n >>> from ultralytics.utils import TQDM\n >>> for i in TQDM(range(100)):\n ... # Your processing code here\n ... pass\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initializes a custom TQDM progress bar.\n\n This class extends the original tqdm class to provide customized behavior for Ultralytics projects.\n\n Args:\n *args (Any): Variable length argument list to be passed to the original tqdm constructor.\n **kwargs (Any): Arbitrary keyword arguments to be passed to the original tqdm constructor.\n\n Notes:\n - The progress bar is disabled if VERBOSE is False or if 'disable' is explicitly set to True in kwargs.\n - The default bar format is set to TQDM_BAR_FORMAT unless overridden in kwargs.\n\n Examples:\n >>> from ultralytics.utils import TQDM\n >>> for i in TQDM(range(100)):\n ... # Your code here\n ... pass\n \"\"\"\n warnings.filterwarnings(\"ignore\", category=tqdm.TqdmExperimentalWarning) # suppress tqdm.rich warning\n kwargs[\"disable\"] = not VERBOSE or kwargs.get(\"disable\", False)\n kwargs.setdefault(\"bar_format\", TQDM_BAR_FORMAT) # override default value if passed\n super().__init__(*args, **kwargs)\n\n def __iter__(self):\n \"\"\"Return self as iterator to satisfy Iterable interface.\"\"\"\n return super().__iter__()\n\n\nclass DataExportMixin:\n \"\"\"\n Mixin class for exporting validation metrics or prediction results in various formats.\n\n This class provides utilities to export performance metrics (e.g., mAP, precision, recall) or prediction results\n from classification, object detection, segmentation, or pose estimation tasks into various formats, Pandas DataFrame\n CSV, XML, HTML, JSON and SQLite (SQL)\n\n Methods:\n to_df(): Convert summary to a Pandas DataFrame.\n to_csv(): Export results as a CSV string.\n to_xml(): Export results as an XML string (requires `lxml`).\n to_html(): Export results as an HTML table.\n to_json(): Export results as a JSON string.\n tojson(): Deprecated alias for `to_json()`.\n to_sql(): Export results to an SQLite database.\n\n Examples:\n >>> model = YOLO(\"yolov8n.pt\")\n >>> results = model(\"image.jpg\")\n >>> df = results.to_df()\n >>> print(df)\n >>> csv_data = results.to_csv()\n >>> results.to_sql(table_name=\"yolo_results\")\n \"\"\"\n\n def to_df(self, normalize=False, decimals=5):\n \"\"\"\n Create a pandas DataFrame from the prediction results summary or validation metrics.\n\n Args:\n normalize (bool, optional): Normalize numerical values for easier comparison. Defaults to False.\n decimals (int, optional): Decimal places to round floats. Defaults to 5.\n\n Returns:\n (DataFrame): DataFrame containing the summary data.\n \"\"\"\n import pandas as pd # scope for faster 'import ultralytics'\n\n return pd.DataFrame(self.summary(normalize=normalize, decimals=decimals))\n\n def to_csv(self, normalize=False, decimals=5):\n \"\"\"\n Export results to CSV string format.\n\n Args:\n normalize (bool, optional): Normalize numeric values. Defaults to False.\n decimals (int, optional): Decimal precision. Defaults to 5.\n\n Returns:\n (str): CSV content as string.\n \"\"\"\n return self.to_df(normalize=normalize, decimals=decimals).to_csv()\n\n def to_xml(self, normalize=False, decimals=5):\n \"\"\"\n Export results to XML format.\n\n Args:\n normalize (bool, optional): Normalize numeric values. Defaults to False.\n decimals (int, optional): Decimal precision. Defaults to 5.\n\n Returns:\n (str): XML string.\n\n Note:\n Requires `lxml` package to be installed.\n \"\"\"\n from ultralytics.utils.checks import check_requirements\n\n check_requirements(\"lxml\")\n df = self.to_df(normalize=normalize, decimals=decimals)\n return '\\n