0
# Utilities and Configuration
1
2
Comprehensive utility functions for system checks, file downloads, configuration management, and dataset operations that support the core Ultralytics functionality.
3
4
## Capabilities
5
6
### System Checks
7
8
Validate system requirements, environment setup, and package dependencies.
9
10
```python { .api }
11
def checks(**kwargs):
12
"""
13
Perform comprehensive system and environment checks.
14
15
Parameters:
16
- verbose (bool): Enable verbose output (default: True)
17
- requirements (str): Path to requirements file to check
18
- exclude (list): List of requirements to exclude from checks
19
20
Returns:
21
bool: True if all checks pass
22
"""
23
```
24
25
**Usage Examples:**
26
27
```python
28
from ultralytics import checks
29
30
# Basic system checks
31
checks()
32
33
# Verbose system checks
34
checks(verbose=True)
35
36
# Check specific requirements file
37
checks(requirements="requirements.txt")
38
39
# Check with exclusions
40
checks(exclude=["opencv-python", "pillow"])
41
```
42
43
### File Downloads
44
45
Download models, datasets, and other assets with progress tracking and caching.
46
47
```python { .api }
48
def download(url, dir=None, unzip=True, delete=False, curl=False, threads=1, retry=3, **kwargs):
49
"""
50
Download files from URL with optional extraction and caching.
51
52
Parameters:
53
- url (str): URL to download from
54
- dir (str | Path): Directory to save file (default: current directory)
55
- unzip (bool): Extract ZIP files after download (default: True)
56
- delete (bool): Delete ZIP file after extraction (default: False)
57
- curl (bool): Use curl instead of urllib (default: False)
58
- threads (int): Number of download threads (default: 1)
59
- retry (int): Number of retry attempts (default: 3)
60
- **kwargs: Additional arguments
61
62
Returns:
63
Path: Path to downloaded file
64
"""
65
```
66
67
**Usage Examples:**
68
69
```python
70
from ultralytics import download
71
72
# Download model file
73
model_path = download("https://github.com/ultralytics/assets/releases/download/v0.0.0/yolo11n.pt")
74
75
# Download and extract dataset
76
dataset_path = download(
77
"https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip",
78
dir="datasets",
79
unzip=True,
80
delete=True
81
)
82
83
# Download with custom options
84
file_path = download(
85
"https://example.com/large_file.zip",
86
dir="downloads",
87
curl=True,
88
threads=4,
89
retry=5
90
)
91
```
92
93
### Settings Management
94
95
Global configuration management for Ultralytics package behavior.
96
97
```python { .api }
98
settings: SettingsManager
99
100
class SettingsManager:
101
def __init__(self):
102
self.yaml_file: Path # Path to settings YAML file
103
self._settings: dict # Internal settings dictionary
104
105
def __getitem__(self, key: str) -> Any: ...
106
def __setitem__(self, key: str, value: Any): ...
107
def update(self, *args, **kwargs): ...
108
def reset(self): ...
109
def save(self): ...
110
def load(self): ...
111
```
112
113
**Available Settings:**
114
- `datasets_dir`: Directory for datasets (default: './datasets')
115
- `weights_dir`: Directory for model weights (default: './weights')
116
- `runs_dir`: Directory for training runs (default: './runs')
117
- `uuid`: Unique user identifier
118
- `sync`: Enable analytics and crash reporting
119
- `api_key`: Ultralytics Hub API key
120
- `clearml`: Enable ClearML logging
121
- `comet`: Enable Comet logging
122
- `dvc`: Enable DVC logging
123
- `hub`: Enable Ultralytics Hub features
124
- `mlflow`: Enable MLflow logging
125
- `neptune`: Enable Neptune logging
126
- `raytune`: Enable Ray Tune hyperparameter tuning
127
- `tensorboard`: Enable TensorBoard logging
128
- `wandb`: Enable Weights & Biases logging
129
130
**Usage Examples:**
131
132
```python
133
from ultralytics import settings
134
135
# View current settings
136
print(settings)
137
138
# Get specific setting
139
datasets_dir = settings['datasets_dir']
140
print(f"Datasets directory: {datasets_dir}")
141
142
# Update settings
143
settings.update({'datasets_dir': '/data/datasets'})
144
settings['weights_dir'] = '/models/weights'
145
146
# Reset to defaults
147
settings.reset()
148
149
# Save settings
150
settings.save()
151
152
# Load settings from file
153
settings.load()
154
```
155
156
### Asset Management
157
158
Access to default assets and sample data for testing and examples.
159
160
```python { .api }
161
ASSETS: Path # Path to default assets directory
162
163
# Default assets include:
164
# - Sample images (bus.jpg, zidane.jpg, etc.)
165
# - Sample videos
166
# - Configuration files
167
# - Model architectures
168
```
169
170
**Usage Examples:**
171
172
```python
173
from ultralytics import ASSETS
174
175
# Use default sample image
176
sample_image = ASSETS / "bus.jpg"
177
results = model(sample_image)
178
179
# List available assets
180
print(list(ASSETS.glob("*")))
181
182
# Use in predictions when no source specified
183
results = model() # Automatically uses ASSETS
184
```
185
186
### Configuration Utilities
187
188
Load and manage YAML configuration files for datasets, models, and training.
189
190
```python { .api }
191
def yaml_load(file):
192
"""
193
Load YAML file safely.
194
195
Parameters:
196
- file (str | Path): Path to YAML file
197
198
Returns:
199
dict: Loaded YAML content
200
"""
201
202
def yaml_save(file, data):
203
"""
204
Save data to YAML file.
205
206
Parameters:
207
- file (str | Path): Path to save YAML file
208
- data (dict): Data to save
209
"""
210
211
def get_cfg(cfg=DEFAULT_CFG_DICT, overrides=None):
212
"""
213
Load and merge configuration from various sources.
214
215
Parameters:
216
- cfg (str | Path | dict): Base configuration
217
- overrides (dict): Configuration overrides
218
219
Returns:
220
dict: Merged configuration
221
"""
222
```
223
224
**Usage Examples:**
225
226
```python
227
from ultralytics.utils import yaml_load, yaml_save, get_cfg
228
229
# Load configuration file
230
config = yaml_load("config.yaml")
231
232
# Save configuration
233
yaml_save("new_config.yaml", {"epochs": 100, "batch_size": 16})
234
235
# Get merged configuration
236
cfg = get_cfg("yolo11n.yaml", {"epochs": 200, "imgsz": 1280})
237
```
238
239
### Environment Detection
240
241
Detect the current runtime environment and available resources.
242
243
```python { .api }
244
def is_colab() -> bool:
245
"""Check if running in Google Colab."""
246
247
def is_kaggle() -> bool:
248
"""Check if running in Kaggle environment."""
249
250
def is_jupyter() -> bool:
251
"""Check if running in Jupyter notebook."""
252
253
def is_docker() -> bool:
254
"""Check if running in Docker container."""
255
256
def is_pip_package(name: str) -> bool:
257
"""Check if package is installed via pip."""
258
259
def is_github_actions_ci() -> bool:
260
"""Check if running in GitHub Actions CI."""
261
```
262
263
**Usage Examples:**
264
265
```python
266
from ultralytics.utils import is_colab, is_kaggle, is_jupyter, is_docker
267
268
# Adapt behavior based on environment
269
if is_colab():
270
print("Running in Google Colab")
271
# Use Colab-specific settings
272
elif is_kaggle():
273
print("Running in Kaggle")
274
# Use Kaggle-specific settings
275
elif is_jupyter():
276
print("Running in Jupyter notebook")
277
# Enable inline plotting
278
elif is_docker():
279
print("Running in Docker container")
280
# Use containerized settings
281
```
282
283
### System Information
284
285
Get detailed information about the system, hardware, and software environment.
286
287
```python { .api }
288
def get_git_info() -> dict:
289
"""Get Git repository information."""
290
291
def get_cpu_info() -> dict:
292
"""Get CPU information."""
293
294
def get_gpu_info() -> dict:
295
"""Get GPU information."""
296
297
def get_environment_info() -> dict:
298
"""Get comprehensive environment information."""
299
300
def print_environment_info():
301
"""Print formatted environment information."""
302
```
303
304
**Usage Examples:**
305
306
```python
307
from ultralytics.utils import get_environment_info, print_environment_info
308
309
# Get environment info as dictionary
310
env_info = get_environment_info()
311
print(f"Python version: {env_info['python']}")
312
print(f"PyTorch version: {env_info['torch']}")
313
314
# Print formatted environment information
315
print_environment_info()
316
```
317
318
### Path and File Utilities
319
320
Utilities for working with file paths, directories, and file operations.
321
322
```python { .api }
323
def increment_path(path, exist_ok=False, sep='', mkdir=False):
324
"""
325
Increment file or directory path if it exists.
326
327
Parameters:
328
- path (str | Path): Path to increment
329
- exist_ok (bool): If True, return path as-is if it exists
330
- sep (str): Separator for incremented number
331
- mkdir (bool): Create directory if it doesn't exist
332
333
Returns:
334
Path: Incremented path
335
"""
336
337
def make_dirs(dir):
338
"""Create directories recursively."""
339
340
def clean_str(s):
341
"""Clean string for use in filenames."""
342
343
def file_size(path):
344
"""Get file size in MB."""
345
```
346
347
**Usage Examples:**
348
349
```python
350
from ultralytics.utils import increment_path, make_dirs, clean_str
351
352
# Increment path to avoid overwriting
353
save_dir = increment_path("runs/train/exp", mkdir=True) # runs/train/exp2
354
print(f"Saving to: {save_dir}")
355
356
# Create directories
357
make_dirs("data/images/train")
358
359
# Clean string for filename
360
clean_name = clean_str("My Model (v1.0)") # "My_Model_v1_0_"
361
```
362
363
### Logging and Debugging
364
365
Enhanced logging capabilities with context managers and debugging utilities.
366
367
```python { .api }
368
LOGGER: logging.Logger # Global logger instance
369
370
def set_logging(name=None, verbose=True):
371
"""Configure logging settings."""
372
373
class TryExcept:
374
"""Context manager for graceful exception handling."""
375
def __init__(self, msg=''):
376
self.msg = msg
377
378
def __enter__(self):
379
return self
380
381
def __exit__(self, exc_type, value, traceback):
382
if exc_type is not None:
383
LOGGER.warning(f'{self.msg}: {exc_type.__name__}: {value}')
384
return True
385
```
386
387
**Usage Examples:**
388
389
```python
390
from ultralytics.utils import LOGGER, set_logging, TryExcept
391
392
# Configure logging
393
set_logging(name='my_app', verbose=True)
394
395
# Use global logger
396
LOGGER.info("Starting training process")
397
LOGGER.warning("Low confidence detections")
398
LOGGER.error("Failed to load model")
399
400
# Graceful exception handling
401
with TryExcept("Loading model"):
402
model = YOLO("nonexistent_model.pt")
403
# If this fails, it logs a warning instead of crashing
404
```
405
406
### Callback System
407
408
Register and manage callback functions for various events.
409
410
```python { .api }
411
default_callbacks = {
412
'on_pretrain_routine_start': [],
413
'on_pretrain_routine_end': [],
414
'on_train_start': [],
415
'on_train_epoch_start': [],
416
'on_train_batch_start': [],
417
'on_optimizer_step': [],
418
'on_before_zero_grad': [],
419
'on_train_batch_end': [],
420
'on_train_epoch_end': [],
421
'on_val_start': [],
422
'on_val_batch_start': [],
423
'on_val_batch_end': [],
424
'on_val_end': [],
425
'on_fit_epoch_end': [],
426
'on_model_save': [],
427
'on_train_end': [],
428
'teardown': []
429
}
430
431
def add_integration_callbacks(instance):
432
"""Add integration callbacks for logging platforms."""
433
```
434
435
## Types
436
437
```python { .api }
438
from typing import Dict, Any, Optional, Union, List, Callable
439
from pathlib import Path
440
import logging
441
442
# Configuration types
443
ConfigDict = Dict[str, Any]
444
SettingsDict = Dict[str, Any]
445
446
# Environment detection types
447
EnvironmentInfo = Dict[str, str]
448
449
# Callback types
450
CallbackDict = Dict[str, List[Callable]]
451
CallbackFunction = Callable[..., None]
452
453
# Path and file types
454
PathLike = Union[str, Path]
455
456
# Logger type
457
Logger = logging.Logger
458
```