instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Write reusable docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from pathlib import Path
from typing import Any
import torch
import torch.nn as nn
from ultralytics.utils import IS_JETSON, LOGGER, is_jetson
from .base import BaseBackend
class PyTorchBackend(BaseBackend):
def __init__(
self,
weight: str | Path | nn.Module,
device: torch.device,
fp16: bool = False,
fuse: bool = True,
verbose: bool = True,
):
self.fuse = fuse
self.verbose = verbose
super().__init__(weight, device, fp16)
def load_model(self, weight: str | torch.nn.Module) -> None:
from ultralytics.nn.tasks import load_checkpoint
if isinstance(weight, torch.nn.Module):
if self.fuse and hasattr(weight, "fuse"):
if IS_JETSON and is_jetson(jetpack=5):
weight = weight.to(self.device)
weight = weight.fuse(verbose=self.verbose)
model = weight.to(self.device)
else:
model, _ = load_checkpoint(weight, device=self.device, fuse=self.fuse)
# Extract model attributes
if hasattr(model, "kpt_shape"):
self.kpt_shape = model.kpt_shape
self.stride = max(int(model.stride.max()), 32) if hasattr(model, "stride") else 32
self.names = model.module.names if hasattr(model, "module") else getattr(model, "names", {})
self.channels = model.yaml.get("channels", 3) if hasattr(model, "yaml") else 3
model.half() if self.fp16 else model.float()
for p in model.parameters():
p.requires_grad = False
self.model = model
self.end2end = getattr(model, "end2end", False)
def forward(
self, im: torch.Tensor, augment: bool = False, visualize: bool = False, embed: list | None = None, **kwargs: Any
) -> torch.Tensor | list[torch.Tensor]:
return self.model(im, augment=augment, visualize=visualize, embed=embed, **kwargs)
class TorchScriptBackend(BaseBackend):
def __init__(self, weight: str | Path, device: torch.device, fp16: bool = False):
super().__init__(weight, device, fp16)
def load_model(self, weight: str) -> None:
import json
import torchvision # noqa - required for TorchScript model deserialization
LOGGER.info(f"Loading {weight} for TorchScript inference...")
extra_files = {"config.txt": ""}
self.model = torch.jit.load(weight, _extra_files=extra_files, map_location=self.device)
self.model.half() if self.fp16 else self.model.float()
if extra_files["config.txt"]:
self.apply_metadata(json.loads(extra_files["config.txt"], object_hook=lambda x: dict(x.items())))
def forward(self, im: torch.Tensor) -> torch.Tensor | list[torch.Tensor]:
return self.model(im) | --- +++ @@ -14,6 +14,11 @@
class PyTorchBackend(BaseBackend):
+ """PyTorch inference backend for native model execution.
+
+ Loads and runs inference with native PyTorch models (.pt checkpoint files) or pre-loaded nn.Module
+ instances. Supports model layer fusion, FP16 precision, and NVIDIA Jetson compatibility.
+ """
def __init__(
self,
@@ -23,11 +28,25 @@ fuse: bool = True,
verbose: bool = True,
):
+ """Initialize the PyTorch backend.
+
+ Args:
+ weight (str | Path | nn.Module): Path to the .pt model file or a pre-loaded nn.Module instance.
+ device (torch.device): Device to run inference on (e.g., 'cpu', 'cuda:0').
+ fp16 (bool): Whether to use FP16 half-precision inference.
+ fuse (bool): Whether to fuse Conv2D + BatchNorm layers for optimization.
+ verbose (bool): Whether to print verbose model loading messages.
+ """
self.fuse = fuse
self.verbose = verbose
super().__init__(weight, device, fp16)
def load_model(self, weight: str | torch.nn.Module) -> None:
+ """Load a PyTorch model from a checkpoint file or nn.Module instance.
+
+ Args:
+ weight (str | torch.nn.Module): Path to the .pt checkpoint or a pre-loaded module.
+ """
from ultralytics.nn.tasks import load_checkpoint
if isinstance(weight, torch.nn.Module):
@@ -56,15 +75,44 @@ def forward(
self, im: torch.Tensor, augment: bool = False, visualize: bool = False, embed: list | None = None, **kwargs: Any
) -> torch.Tensor | list[torch.Tensor]:
+ """Run native PyTorch inference with support for augmentation, visualization, and embeddings.
+
+ Args:
+ im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1].
+ augment (bool): Whether to apply test-time augmentation.
+ visualize (bool): Whether to visualize intermediate feature maps.
+ embed (list | None): List of layer indices to extract embeddings from, or None.
+ **kwargs (Any): Additional keyword arguments passed to the model forward method.
+
+ Returns:
+ (torch.Tensor | list[torch.Tensor]): Model predictions as tensor(s).
+ """
return self.model(im, augment=augment, visualize=visualize, embed=embed, **kwargs)
class TorchScriptBackend(BaseBackend):
+ """PyTorch TorchScript inference backend for serialized model execution.
+
+ Loads and runs inference with TorchScript models (.torchscript files) created via torch.jit.trace or
+ torch.jit.script. Supports FP16 precision and embedded metadata extraction.
+ """
def __init__(self, weight: str | Path, device: torch.device, fp16: bool = False):
+ """Initialize the TorchScript backend.
+
+ Args:
+ weight (str | Path): Path to the .torchscript model file.
+ device (torch.device): Device to run inference on (e.g., 'cpu', 'cuda:0').
+ fp16 (bool): Whether to use FP16 half-precision inference.
+ """
super().__init__(weight, device, fp16)
def load_model(self, weight: str) -> None:
+ """Load a TorchScript model from a .torchscript file with optional embedded metadata.
+
+ Args:
+ weight (str): Path to the .torchscript model file.
+ """
import json
import torchvision # noqa - required for TorchScript model deserialization
@@ -78,4 +126,12 @@ self.apply_metadata(json.loads(extra_files["config.txt"], object_hook=lambda x: dict(x.items())))
def forward(self, im: torch.Tensor) -> torch.Tensor | list[torch.Tensor]:
- return self.model(im)+ """Run TorchScript inference.
+
+ Args:
+ im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1].
+
+ Returns:
+ (torch.Tensor | list[torch.Tensor]): Model predictions as tensor(s).
+ """
+ return self.model(im)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/pytorch.py |
Add docstrings for internal functions | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from collections import deque
from math import sqrt
from typing import Any
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
from ultralytics.utils.plotting import colors
class SpeedEstimator(BaseSolution):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.fps = self.CFG["fps"] # Video frame rate for time calculations
self.frame_count = 0 # Global frame counter
self.trk_frame_ids = {} # Track ID → first frame index
self.spd = {} # Final speed per object (km/h), once locked
self.trk_hist = {} # Track ID → deque of (time, position)
self.locked_ids = set() # Track IDs whose speed has been finalized
self.max_hist = self.CFG["max_hist"] # Required frame history before computing speed
self.meter_per_pixel = self.CFG["meter_per_pixel"] # Scene scale, depends on camera details
self.max_speed = self.CFG["max_speed"] # Maximum speed adjustment
def process(self, im0) -> SolutionResults:
self.frame_count += 1
self.extract_tracks(im0)
annotator = SolutionAnnotator(im0, line_width=self.line_width)
for box, track_id, _, _ in zip(self.boxes, self.track_ids, self.clss, self.confs):
self.store_tracking_history(track_id, box)
if track_id not in self.trk_hist: # Initialize history if new track found
self.trk_hist[track_id] = deque(maxlen=self.max_hist)
self.trk_frame_ids[track_id] = self.frame_count
if track_id not in self.locked_ids: # Update history until speed is locked
trk_hist = self.trk_hist[track_id]
trk_hist.append(self.track_line[-1])
# Compute and lock speed once enough history is collected
if len(trk_hist) == self.max_hist:
p0, p1 = trk_hist[0], trk_hist[-1] # First and last points of track
dt = (self.frame_count - self.trk_frame_ids[track_id]) / self.fps # Time in seconds
if dt > 0:
dx, dy = p1[0] - p0[0], p1[1] - p0[1] # Pixel displacement
pixel_distance = sqrt(dx * dx + dy * dy) # Calculate pixel distance
meters = pixel_distance * self.meter_per_pixel # Convert to meters
self.spd[track_id] = int(
min((meters / dt) * 3.6, self.max_speed)
) # Convert to km/h and store final speed
self.locked_ids.add(track_id) # Prevent further updates
self.trk_hist.pop(track_id, None) # Free memory
self.trk_frame_ids.pop(track_id, None) # Remove frame start reference
if track_id in self.spd:
speed_label = f"{self.spd[track_id]} km/h"
annotator.box_label(box, label=speed_label, color=colors(track_id, True)) # Draw bounding box
plot_im = annotator.result()
self.display_output(plot_im) # Display output with base class function
# Return results with processed image and tracking summary
return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids)) | --- +++ @@ -9,8 +9,43 @@
class SpeedEstimator(BaseSolution):
+ """A class to estimate the speed of objects in a real-time video stream based on their tracks.
+
+ This class extends the BaseSolution class and provides functionality for estimating object speeds using tracking
+ data in video streams. Speed is calculated based on pixel displacement over time and converted to real-world units
+ using a configurable meters-per-pixel scale factor.
+
+ Attributes:
+ fps (float): Video frame rate for time calculations.
+ frame_count (int): Global frame counter for tracking temporal information.
+ trk_frame_ids (dict): Maps track IDs to their first frame index.
+ spd (dict): Final speed per object in km/h once locked.
+ trk_hist (dict): Maps track IDs to deque of position history.
+ locked_ids (set): Track IDs whose speed has been finalized.
+ max_hist (int): Required frame history before computing speed.
+ meter_per_pixel (float): Real-world meters represented by one pixel for scene scale conversion.
+ max_speed (int): Maximum allowed object speed; values above this will be capped.
+
+ Methods:
+ process: Process input frames to estimate object speeds based on tracking data.
+ store_tracking_history: Store the tracking history for an object.
+ extract_tracks: Extract tracks from the current frame.
+ display_output: Display the output with annotations.
+
+ Examples:
+ Initialize speed estimator and process a frame
+ >>> estimator = SpeedEstimator(meter_per_pixel=0.04, max_speed=120)
+ >>> frame = cv2.imread("frame.jpg")
+ >>> results = estimator.process(frame)
+ >>> cv2.imshow("Speed Estimation", results.plot_im)
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the SpeedEstimator object with speed estimation parameters and data structures.
+
+ Args:
+ **kwargs (Any): Additional keyword arguments passed to the parent class.
+ """
super().__init__(**kwargs)
self.fps = self.CFG["fps"] # Video frame rate for time calculations
@@ -24,6 +59,20 @@ self.max_speed = self.CFG["max_speed"] # Maximum speed adjustment
def process(self, im0) -> SolutionResults:
+ """Process an input frame to estimate object speeds based on tracking data.
+
+ Args:
+ im0 (np.ndarray): Input image for processing with shape (H, W, C) in OpenCV BGR format.
+
+ Returns:
+ (SolutionResults): Contains processed image `plot_im` and `total_tracks` (number of tracked objects).
+
+ Examples:
+ Process a frame for speed estimation
+ >>> estimator = SpeedEstimator()
+ >>> image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
+ >>> results = estimator.process(image)
+ """
self.frame_count += 1
self.extract_tracks(im0)
annotator = SolutionAnnotator(im0, line_width=self.line_width)
@@ -62,4 +111,4 @@ self.display_output(plot_im) # Display output with base class function
# Return results with processed image and tracking summary
- return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids))+ return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids))
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/speed_estimation.py |
Add clean documentation to messy code | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from typing import Any
import numpy as np
from ..utils import LOGGER
from ..utils.ops import xywh2ltwh
from .basetrack import BaseTrack, TrackState
from .utils import matching
from .utils.kalman_filter import KalmanFilterXYAH
class STrack(BaseTrack):
shared_kalman = KalmanFilterXYAH()
def __init__(self, xywh: list[float], score: float, cls: Any):
super().__init__()
# xywh+idx or xywha+idx
assert len(xywh) in {5, 6}, f"expected 5 or 6 values but got {len(xywh)}"
self._tlwh = np.asarray(xywh2ltwh(xywh[:4]), dtype=np.float32)
self.kalman_filter = None
self.mean, self.covariance = None, None
self.is_activated = False
self.score = score
self.tracklet_len = 0
self.cls = cls
self.idx = xywh[-1]
self.angle = xywh[4] if len(xywh) == 6 else None
def predict(self):
mean_state = self.mean.copy()
if self.state != TrackState.Tracked:
mean_state[7] = 0
self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)
@staticmethod
def multi_predict(stracks: list[STrack]):
if len(stracks) <= 0:
return
multi_mean = np.asarray([st.mean.copy() for st in stracks])
multi_covariance = np.asarray([st.covariance for st in stracks])
for i, st in enumerate(stracks):
if st.state != TrackState.Tracked:
multi_mean[i][7] = 0
multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)
for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
stracks[i].mean = mean
stracks[i].covariance = cov
@staticmethod
def multi_gmc(stracks: list[STrack], H: np.ndarray = np.eye(2, 3)):
if stracks:
multi_mean = np.asarray([st.mean.copy() for st in stracks])
multi_covariance = np.asarray([st.covariance for st in stracks])
R = H[:2, :2]
R8x8 = np.kron(np.eye(4, dtype=float), R)
t = H[:2, 2]
for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
mean = R8x8.dot(mean)
mean[:2] += t
cov = R8x8.dot(cov).dot(R8x8.transpose())
stracks[i].mean = mean
stracks[i].covariance = cov
def activate(self, kalman_filter: KalmanFilterXYAH, frame_id: int):
self.kalman_filter = kalman_filter
self.track_id = self.next_id()
self.mean, self.covariance = self.kalman_filter.initiate(self.convert_coords(self._tlwh))
self.tracklet_len = 0
self.state = TrackState.Tracked
if frame_id == 1:
self.is_activated = True
self.frame_id = frame_id
self.start_frame = frame_id
def re_activate(self, new_track: STrack, frame_id: int, new_id: bool = False):
self.mean, self.covariance = self.kalman_filter.update(
self.mean, self.covariance, self.convert_coords(new_track.tlwh)
)
self.tracklet_len = 0
self.state = TrackState.Tracked
self.is_activated = True
self.frame_id = frame_id
if new_id:
self.track_id = self.next_id()
self.score = new_track.score
self.cls = new_track.cls
self.angle = new_track.angle
self.idx = new_track.idx
def update(self, new_track: STrack, frame_id: int):
self.frame_id = frame_id
self.tracklet_len += 1
new_tlwh = new_track.tlwh
self.mean, self.covariance = self.kalman_filter.update(
self.mean, self.covariance, self.convert_coords(new_tlwh)
)
self.state = TrackState.Tracked
self.is_activated = True
self.score = new_track.score
self.cls = new_track.cls
self.angle = new_track.angle
self.idx = new_track.idx
def convert_coords(self, tlwh: np.ndarray) -> np.ndarray:
return self.tlwh_to_xyah(tlwh)
@property
def tlwh(self) -> np.ndarray:
if self.mean is None:
return self._tlwh.copy()
ret = self.mean[:4].copy()
ret[2] *= ret[3]
ret[:2] -= ret[2:] / 2
return ret
@property
def xyxy(self) -> np.ndarray:
ret = self.tlwh.copy()
ret[2:] += ret[:2]
return ret
@staticmethod
def tlwh_to_xyah(tlwh: np.ndarray) -> np.ndarray:
ret = np.asarray(tlwh).copy()
ret[:2] += ret[2:] / 2
ret[2] /= ret[3]
return ret
@property
def xywh(self) -> np.ndarray:
ret = np.asarray(self.tlwh).copy()
ret[:2] += ret[2:] / 2
return ret
@property
def xywha(self) -> np.ndarray:
if self.angle is None:
LOGGER.warning("`angle` attr not found, returning `xywh` instead.")
return self.xywh
return np.concatenate([self.xywh, self.angle[None]])
@property
def result(self) -> list[float]:
coords = self.xyxy if self.angle is None else self.xywha
return [*coords.tolist(), self.track_id, self.score, self.cls, self.idx]
def __repr__(self) -> str:
return f"OT_{self.track_id}_({self.start_frame}-{self.end_frame})"
class BYTETracker:
def __init__(self, args, frame_rate: int = 30):
self.tracked_stracks: list[STrack] = []
self.lost_stracks: list[STrack] = []
self.removed_stracks: list[STrack] = []
self.frame_id = 0
self.args = args
self.max_time_lost = int(frame_rate / 30.0 * args.track_buffer)
self.kalman_filter = self.get_kalmanfilter()
self.reset_id()
def update(self, results, img: np.ndarray | None = None, feats: np.ndarray | None = None) -> np.ndarray:
self.frame_id += 1
activated_stracks = []
refind_stracks = []
lost_stracks = []
removed_stracks = []
scores = results.conf
remain_inds = scores >= self.args.track_high_thresh
inds_low = scores > self.args.track_low_thresh
inds_high = scores < self.args.track_high_thresh
inds_second = inds_low & inds_high
results_second = results[inds_second]
results = results[remain_inds]
feats_keep = feats_second = img
if feats is not None and len(feats):
feats_keep = feats[remain_inds]
feats_second = feats[inds_second]
detections = self.init_track(results, feats_keep)
# Add newly detected tracklets to tracked_stracks
unconfirmed = []
tracked_stracks: list[STrack] = []
for track in self.tracked_stracks:
if not track.is_activated:
unconfirmed.append(track)
else:
tracked_stracks.append(track)
# Step 2: First association, with high score detection boxes
strack_pool = self.joint_stracks(tracked_stracks, self.lost_stracks)
# Predict the current location with KF
self.multi_predict(strack_pool)
if hasattr(self, "gmc") and img is not None:
# use try-except here to bypass errors from gmc module
try:
warp = self.gmc.apply(img, results.xyxy)
except Exception:
warp = np.eye(2, 3)
STrack.multi_gmc(strack_pool, warp)
STrack.multi_gmc(unconfirmed, warp)
dists = self.get_dists(strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=self.args.match_thresh)
for itracked, idet in matches:
track = strack_pool[itracked]
det = detections[idet]
if track.state == TrackState.Tracked:
track.update(det, self.frame_id)
activated_stracks.append(track)
else:
track.re_activate(det, self.frame_id, new_id=False)
refind_stracks.append(track)
# Step 3: Second association, with low score detection boxes association the untrack to the low score detections
detections_second = self.init_track(results_second, feats_second)
r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
dists = matching.iou_distance(r_tracked_stracks, detections_second)
if self.args.fuse_score:
dists = matching.fuse_score(dists, detections_second)
matches, u_track, _u_detection_second = matching.linear_assignment(dists, thresh=0.5)
for itracked, idet in matches:
track = r_tracked_stracks[itracked]
det = detections_second[idet]
if track.state == TrackState.Tracked:
track.update(det, self.frame_id)
activated_stracks.append(track)
else:
track.re_activate(det, self.frame_id, new_id=False)
refind_stracks.append(track)
for it in u_track:
track = r_tracked_stracks[it]
if track.state != TrackState.Lost:
track.mark_lost()
lost_stracks.append(track)
# Deal with unconfirmed tracks, usually tracks with only one beginning frame
detections = [detections[i] for i in u_detection]
dists = self.get_dists(unconfirmed, detections)
matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
for itracked, idet in matches:
unconfirmed[itracked].update(detections[idet], self.frame_id)
activated_stracks.append(unconfirmed[itracked])
for it in u_unconfirmed:
track = unconfirmed[it]
track.mark_removed()
removed_stracks.append(track)
# Step 4: Init new stracks
for inew in u_detection:
track = detections[inew]
if track.score < self.args.new_track_thresh:
continue
track.activate(self.kalman_filter, self.frame_id)
activated_stracks.append(track)
# Step 5: Update state
for track in self.lost_stracks:
if self.frame_id - track.end_frame > self.max_time_lost:
track.mark_removed()
removed_stracks.append(track)
self.tracked_stracks = [t for t in self.tracked_stracks if t.state == TrackState.Tracked]
self.tracked_stracks = self.joint_stracks(self.tracked_stracks, activated_stracks)
self.tracked_stracks = self.joint_stracks(self.tracked_stracks, refind_stracks)
self.lost_stracks = self.sub_stracks(self.lost_stracks, self.tracked_stracks)
self.lost_stracks.extend(lost_stracks)
self.lost_stracks = self.sub_stracks(self.lost_stracks, self.removed_stracks)
self.tracked_stracks, self.lost_stracks = self.remove_duplicate_stracks(self.tracked_stracks, self.lost_stracks)
self.removed_stracks.extend(removed_stracks)
if len(self.removed_stracks) > 1000:
self.removed_stracks = self.removed_stracks[-1000:] # clip removed stracks to 1000 maximum
return np.asarray([x.result for x in self.tracked_stracks if x.is_activated], dtype=np.float32)
def get_kalmanfilter(self) -> KalmanFilterXYAH:
return KalmanFilterXYAH()
def init_track(self, results, img: np.ndarray | None = None) -> list[STrack]:
if len(results) == 0:
return []
bboxes = results.xywhr if hasattr(results, "xywhr") else results.xywh
bboxes = np.concatenate([bboxes, np.arange(len(bboxes)).reshape(-1, 1)], axis=-1)
return [STrack(xywh, s, c) for (xywh, s, c) in zip(bboxes, results.conf, results.cls)]
def get_dists(self, tracks: list[STrack], detections: list[STrack]) -> np.ndarray:
dists = matching.iou_distance(tracks, detections)
if self.args.fuse_score:
dists = matching.fuse_score(dists, detections)
return dists
def multi_predict(self, tracks: list[STrack]):
STrack.multi_predict(tracks)
@staticmethod
def reset_id():
STrack.reset_id()
def reset(self):
self.tracked_stracks: list[STrack] = []
self.lost_stracks: list[STrack] = []
self.removed_stracks: list[STrack] = []
self.frame_id = 0
self.kalman_filter = self.get_kalmanfilter()
self.reset_id()
@staticmethod
def joint_stracks(tlista: list[STrack], tlistb: list[STrack]) -> list[STrack]:
exists = {}
res = []
for t in tlista:
exists[t.track_id] = 1
res.append(t)
for t in tlistb:
tid = t.track_id
if not exists.get(tid, 0):
exists[tid] = 1
res.append(t)
return res
@staticmethod
def sub_stracks(tlista: list[STrack], tlistb: list[STrack]) -> list[STrack]:
track_ids_b = {t.track_id for t in tlistb}
return [t for t in tlista if t.track_id not in track_ids_b]
@staticmethod
def remove_duplicate_stracks(stracksa: list[STrack], stracksb: list[STrack]) -> tuple[list[STrack], list[STrack]]:
pdist = matching.iou_distance(stracksa, stracksb)
pairs = np.where(pdist < 0.15)
dupa, dupb = [], []
for p, q in zip(*pairs):
timep = stracksa[p].frame_id - stracksa[p].start_frame
timeq = stracksb[q].frame_id - stracksb[q].start_frame
if timep > timeq:
dupb.append(q)
else:
dupa.append(p)
resa = [t for i, t in enumerate(stracksa) if i not in dupa]
resb = [t for i, t in enumerate(stracksb) if i not in dupb]
return resa, resb | --- +++ @@ -14,10 +14,53 @@
class STrack(BaseTrack):
+ """Single object tracking representation that uses Kalman filtering for state estimation.
+
+ This class is responsible for storing all the information regarding individual tracklets and performs state updates
+ and predictions based on Kalman filter.
+
+ Attributes:
+ shared_kalman (KalmanFilterXYAH): Shared Kalman filter used across all STrack instances for prediction.
+ _tlwh (np.ndarray): Private attribute to store top-left corner coordinates and width and height of bounding box.
+ kalman_filter (KalmanFilterXYAH): Instance of Kalman filter used for this particular object track.
+ mean (np.ndarray): Mean state estimate vector.
+ covariance (np.ndarray): Covariance of state estimate.
+ is_activated (bool): Boolean flag indicating if the track has been activated.
+ score (float): Confidence score of the track.
+ tracklet_len (int): Length of the tracklet.
+ cls (Any): Class label for the object.
+ idx (int): Index or identifier for the object.
+ frame_id (int): Current frame ID.
+ start_frame (int): Frame where the object was first detected.
+ angle (float | None): Optional angle information for oriented bounding boxes.
+
+ Methods:
+ predict: Predict the next state of the object using Kalman filter.
+ multi_predict: Predict the next states for multiple tracks.
+ multi_gmc: Update multiple track states using a homography matrix.
+ activate: Activate a new tracklet.
+ re_activate: Reactivate a previously lost tracklet.
+ update: Update the state of a matched track.
+ convert_coords: Convert bounding box to x-y-aspect-height format.
+ tlwh_to_xyah: Convert tlwh bounding box to xyah format.
+
+ Examples:
+ Initialize and activate a new track
+ >>> track = STrack(xywh=[100, 200, 50, 80, 0], score=0.9, cls="person")
+ >>> track.activate(kalman_filter=KalmanFilterXYAH(), frame_id=1)
+ """
shared_kalman = KalmanFilterXYAH()
def __init__(self, xywh: list[float], score: float, cls: Any):
+ """Initialize a new STrack instance.
+
+ Args:
+ xywh (list[float]): Bounding box in `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)` format, where (x, y)
+ is the center, (w, h) are width and height, and `idx` is the detection index.
+ score (float): Confidence score of the detection.
+ cls (Any): Class label for the detected object.
+ """
super().__init__()
# xywh+idx or xywha+idx
assert len(xywh) in {5, 6}, f"expected 5 or 6 values but got {len(xywh)}"
@@ -33,6 +76,7 @@ self.angle = xywh[4] if len(xywh) == 6 else None
def predict(self):
+ """Predict the next state (mean and covariance) of the object using the Kalman filter."""
mean_state = self.mean.copy()
if self.state != TrackState.Tracked:
mean_state[7] = 0
@@ -40,6 +84,7 @@
@staticmethod
def multi_predict(stracks: list[STrack]):
+ """Perform multi-object predictive tracking using Kalman filter for the provided list of STrack instances."""
if len(stracks) <= 0:
return
multi_mean = np.asarray([st.mean.copy() for st in stracks])
@@ -54,6 +99,7 @@
@staticmethod
def multi_gmc(stracks: list[STrack], H: np.ndarray = np.eye(2, 3)):
+ """Update multiple track positions and covariances using a homography matrix."""
if stracks:
multi_mean = np.asarray([st.mean.copy() for st in stracks])
multi_covariance = np.asarray([st.covariance for st in stracks])
@@ -71,6 +117,7 @@ stracks[i].covariance = cov
def activate(self, kalman_filter: KalmanFilterXYAH, frame_id: int):
+ """Activate a new tracklet using the provided Kalman filter and initialize its state and covariance."""
self.kalman_filter = kalman_filter
self.track_id = self.next_id()
self.mean, self.covariance = self.kalman_filter.initiate(self.convert_coords(self._tlwh))
@@ -83,6 +130,7 @@ self.start_frame = frame_id
def re_activate(self, new_track: STrack, frame_id: int, new_id: bool = False):
+ """Reactivate a previously lost track using new detection data and update its state and attributes."""
self.mean, self.covariance = self.kalman_filter.update(
self.mean, self.covariance, self.convert_coords(new_track.tlwh)
)
@@ -98,6 +146,18 @@ self.idx = new_track.idx
def update(self, new_track: STrack, frame_id: int):
+ """Update the state of a matched track.
+
+ Args:
+ new_track (STrack): The new track containing updated information.
+ frame_id (int): The ID of the current frame.
+
+ Examples:
+ Update the state of a track with new detection information
+ >>> track = STrack([100, 200, 50, 80, 0], score=0.9, cls=0)
+ >>> new_track = STrack([105, 205, 55, 85, 0], score=0.95, cls=0)
+ >>> track.update(new_track, 2)
+ """
self.frame_id = frame_id
self.tracklet_len += 1
@@ -114,10 +174,12 @@ self.idx = new_track.idx
def convert_coords(self, tlwh: np.ndarray) -> np.ndarray:
+ """Convert a bounding box's top-left-width-height format to its x-y-aspect-height equivalent."""
return self.tlwh_to_xyah(tlwh)
@property
def tlwh(self) -> np.ndarray:
+ """Get the bounding box in top-left-width-height format from the current state estimate."""
if self.mean is None:
return self._tlwh.copy()
ret = self.mean[:4].copy()
@@ -127,12 +189,14 @@
@property
def xyxy(self) -> np.ndarray:
+ """Convert bounding box from (top left x, top left y, width, height) to (min x, min y, max x, max y) format."""
ret = self.tlwh.copy()
ret[2:] += ret[:2]
return ret
@staticmethod
def tlwh_to_xyah(tlwh: np.ndarray) -> np.ndarray:
+ """Convert bounding box from tlwh format to center-x-center-y-aspect-height (xyah) format."""
ret = np.asarray(tlwh).copy()
ret[:2] += ret[2:] / 2
ret[2] /= ret[3]
@@ -140,12 +204,14 @@
@property
def xywh(self) -> np.ndarray:
+ """Get the current position of the bounding box in (center x, center y, width, height) format."""
ret = np.asarray(self.tlwh).copy()
ret[:2] += ret[2:] / 2
return ret
@property
def xywha(self) -> np.ndarray:
+ """Get position in (center x, center y, width, height, angle) format, warning if angle is missing."""
if self.angle is None:
LOGGER.warning("`angle` attr not found, returning `xywh` instead.")
return self.xywh
@@ -153,16 +219,57 @@
@property
def result(self) -> list[float]:
+ """Get the current tracking results in the appropriate bounding box format."""
coords = self.xyxy if self.angle is None else self.xywha
return [*coords.tolist(), self.track_id, self.score, self.cls, self.idx]
def __repr__(self) -> str:
+ """Return a string representation of the STrack object including start frame, end frame, and track ID."""
return f"OT_{self.track_id}_({self.start_frame}-{self.end_frame})"
class BYTETracker:
+ """BYTETracker: A tracking algorithm built on top of YOLO for object detection and tracking.
+
+ This class encapsulates the functionality for initializing, updating, and managing the tracks for detected objects
+ in a video sequence. It maintains the state of tracked, lost, and removed tracks over frames, utilizes Kalman
+ filtering for predicting the new object locations, and performs data association.
+
+ Attributes:
+ tracked_stracks (list[STrack]): List of successfully activated tracks.
+ lost_stracks (list[STrack]): List of lost tracks.
+ removed_stracks (list[STrack]): List of removed tracks.
+ frame_id (int): The current frame ID.
+ args (Namespace): Command-line arguments.
+ max_time_lost (int): The maximum frames for a track to be considered as 'lost'.
+ kalman_filter (KalmanFilterXYAH): Kalman Filter object.
+
+ Methods:
+ update: Update object tracker with new detections.
+ get_kalmanfilter: Return a Kalman filter object for tracking bounding boxes.
+ init_track: Initialize object tracking with detections.
+ get_dists: Calculate the distance between tracks and detections.
+ multi_predict: Predict the location of tracks.
+ reset_id: Reset the ID counter of STrack.
+ reset: Reset the tracker by clearing all tracks.
+ joint_stracks: Combine two lists of stracks.
+ sub_stracks: Filter out the stracks present in the second list from the first list.
+ remove_duplicate_stracks: Remove duplicate stracks based on IoU.
+
+ Examples:
+ Initialize BYTETracker and update with detection results
+ >>> tracker = BYTETracker(args, frame_rate=30)
+ >>> results = yolo_model.detect(image)
+ >>> tracked_objects = tracker.update(results)
+ """
def __init__(self, args, frame_rate: int = 30):
+ """Initialize a BYTETracker instance for object tracking.
+
+ Args:
+ args (Namespace): Command-line arguments containing tracking parameters.
+ frame_rate (int): Frame rate of the video sequence.
+ """
self.tracked_stracks: list[STrack] = []
self.lost_stracks: list[STrack] = []
self.removed_stracks: list[STrack] = []
@@ -174,6 +281,7 @@ self.reset_id()
def update(self, results, img: np.ndarray | None = None, feats: np.ndarray | None = None) -> np.ndarray:
+ """Update the tracker with new detections and return the current list of tracked objects."""
self.frame_id += 1
activated_stracks = []
refind_stracks = []
@@ -287,9 +395,11 @@ return np.asarray([x.result for x in self.tracked_stracks if x.is_activated], dtype=np.float32)
def get_kalmanfilter(self) -> KalmanFilterXYAH:
+ """Return a Kalman filter object for tracking bounding boxes using KalmanFilterXYAH."""
return KalmanFilterXYAH()
def init_track(self, results, img: np.ndarray | None = None) -> list[STrack]:
+ """Initialize object tracking with given detections, scores, and class labels as STrack instances."""
if len(results) == 0:
return []
bboxes = results.xywhr if hasattr(results, "xywhr") else results.xywh
@@ -297,19 +407,23 @@ return [STrack(xywh, s, c) for (xywh, s, c) in zip(bboxes, results.conf, results.cls)]
def get_dists(self, tracks: list[STrack], detections: list[STrack]) -> np.ndarray:
+ """Calculate the distance between tracks and detections using IoU and optionally fuse scores."""
dists = matching.iou_distance(tracks, detections)
if self.args.fuse_score:
dists = matching.fuse_score(dists, detections)
return dists
def multi_predict(self, tracks: list[STrack]):
+ """Predict the next states for multiple tracks using Kalman filter."""
STrack.multi_predict(tracks)
@staticmethod
def reset_id():
+ """Reset the ID counter for STrack instances to ensure unique track IDs across tracking sessions."""
STrack.reset_id()
def reset(self):
+ """Reset the tracker by clearing all tracked, lost, and removed tracks and reinitializing the Kalman filter."""
self.tracked_stracks: list[STrack] = []
self.lost_stracks: list[STrack] = []
self.removed_stracks: list[STrack] = []
@@ -319,6 +433,7 @@
@staticmethod
def joint_stracks(tlista: list[STrack], tlistb: list[STrack]) -> list[STrack]:
+ """Combine two lists of STrack objects into a single list, ensuring no duplicates based on track IDs."""
exists = {}
res = []
for t in tlista:
@@ -333,11 +448,13 @@
@staticmethod
def sub_stracks(tlista: list[STrack], tlistb: list[STrack]) -> list[STrack]:
+ """Filter out the stracks present in the second list from the first list."""
track_ids_b = {t.track_id for t in tlistb}
return [t for t in tlista if t.track_id not in track_ids_b]
@staticmethod
def remove_duplicate_stracks(stracksa: list[STrack], stracksb: list[STrack]) -> tuple[list[STrack], list[STrack]]:
+ """Remove duplicate stracks from two lists based on Intersection over Union (IoU) distance."""
pdist = matching.iou_distance(stracksa, stracksb)
pairs = np.where(pdist < 0.15)
dupa, dupb = [], []
@@ -350,4 +467,4 @@ dupa.append(p)
resa = [t for i, t in enumerate(stracksa) if i not in dupa]
resb = [t for i, t in enumerate(stracksb) if i not in dupb]
- return resa, resb+ return resa, resb
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/trackers/byte_tracker.py |
Add docstrings to clarify complex logic | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from functools import partial
from pathlib import Path
import torch
from ultralytics.utils import YAML, IterableSimpleNamespace
from ultralytics.utils.checks import check_yaml
from .bot_sort import BOTSORT
from .byte_tracker import BYTETracker
# A mapping of tracker types to corresponding tracker classes
TRACKER_MAP = {"bytetrack": BYTETracker, "botsort": BOTSORT}
def on_predict_start(predictor: object, persist: bool = False) -> None:
if predictor.args.task == "classify":
raise ValueError("❌ Classification doesn't support 'mode=track'")
if hasattr(predictor, "trackers") and persist:
return
tracker = check_yaml(predictor.args.tracker)
cfg = IterableSimpleNamespace(**YAML.load(tracker))
if cfg.tracker_type not in {"bytetrack", "botsort"}:
raise AssertionError(f"Only 'bytetrack' and 'botsort' are supported for now, but got '{cfg.tracker_type}'")
predictor._feats = None # reset in case used earlier
if hasattr(predictor, "_hook"):
predictor._hook.remove()
if cfg.tracker_type == "botsort" and cfg.with_reid and cfg.model == "auto":
from ultralytics.nn.modules.head import Detect
if not (
isinstance(predictor.model.model, torch.nn.Module)
and isinstance(predictor.model.model.model[-1], Detect)
and not predictor.model.model.model[-1].end2end
):
cfg.model = "yolo26n-cls.pt"
else:
# Register hook to extract input of Detect layer
def pre_hook(module, input):
predictor._feats = list(input[0]) # unroll to new list to avoid mutation in forward
predictor._hook = predictor.model.model.model[-1].register_forward_pre_hook(pre_hook)
trackers = []
for _ in range(predictor.dataset.bs):
tracker = TRACKER_MAP[cfg.tracker_type](args=cfg, frame_rate=30)
trackers.append(tracker)
if predictor.dataset.mode != "stream": # only need one tracker for other modes
break
predictor.trackers = trackers
predictor.vid_path = [None] * predictor.dataset.bs # for determining when to reset tracker on new video
def on_predict_postprocess_end(predictor: object, persist: bool = False) -> None:
is_obb = predictor.args.task == "obb"
is_stream = predictor.dataset.mode == "stream"
for i, result in enumerate(predictor.results):
tracker = predictor.trackers[i if is_stream else 0]
vid_path = predictor.save_dir / Path(result.path).name
if not persist and predictor.vid_path[i if is_stream else 0] != vid_path:
tracker.reset()
predictor.vid_path[i if is_stream else 0] = vid_path
det = (result.obb if is_obb else result.boxes).cpu().numpy()
tracks = tracker.update(det, result.orig_img, getattr(result, "feats", None))
if len(tracks) == 0:
continue
idx = tracks[:, -1].astype(int)
predictor.results[i] = result[idx]
update_args = {"obb" if is_obb else "boxes": torch.as_tensor(tracks[:, :-1])}
predictor.results[i].update(**update_args)
def register_tracker(model: object, persist: bool) -> None:
model.add_callback("on_predict_start", partial(on_predict_start, persist=persist))
model.add_callback("on_predict_postprocess_end", partial(on_predict_postprocess_end, persist=persist)) | --- +++ @@ -16,6 +16,17 @@
def on_predict_start(predictor: object, persist: bool = False) -> None:
+ """Initialize trackers for object tracking during prediction.
+
+ Args:
+ predictor (ultralytics.engine.predictor.BasePredictor): The predictor object to initialize trackers for.
+ persist (bool, optional): Whether to persist the trackers if they already exist.
+
+ Examples:
+ Initialize trackers for a predictor object
+ >>> predictor = SomePredictorClass()
+ >>> on_predict_start(predictor, persist=True)
+ """
if predictor.args.task == "classify":
raise ValueError("❌ Classification doesn't support 'mode=track'")
@@ -58,6 +69,17 @@
def on_predict_postprocess_end(predictor: object, persist: bool = False) -> None:
+ """Postprocess detected boxes and update with object tracking.
+
+ Args:
+ predictor (object): The predictor object containing the predictions.
+ persist (bool, optional): Whether to persist the trackers if they already exist.
+
+ Examples:
+ Postprocess predictions and update with tracking
+ >>> predictor = YourPredictorClass()
+ >>> on_predict_postprocess_end(predictor, persist=True)
+ """
is_obb = predictor.args.task == "obb"
is_stream = predictor.dataset.mode == "stream"
for i, result in enumerate(predictor.results):
@@ -79,5 +101,16 @@
def register_tracker(model: object, persist: bool) -> None:
+ """Register tracking callbacks to the model for object tracking during prediction.
+
+ Args:
+ model (object): The model object to register tracking callbacks for.
+ persist (bool): Whether to persist the trackers if they already exist.
+
+ Examples:
+ Register tracking callbacks to a YOLO model
+ >>> model = YOLOModel()
+ >>> register_tracker(model, persist=True)
+ """
model.add_callback("on_predict_start", partial(on_predict_start, persist=persist))
- model.add_callback("on_predict_postprocess_end", partial(on_predict_postprocess_end, persist=persist))+ model.add_callback("on_predict_postprocess_end", partial(on_predict_postprocess_end, persist=persist))
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/trackers/track.py |
Add docstrings to make code maintainable | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from pathlib import Path
import torch
from ultralytics.utils import LOGGER
from ultralytics.utils.checks import check_requirements, is_rockchip
from .base import BaseBackend
class RKNNBackend(BaseBackend):
def load_model(self, weight: str | Path) -> None:
if not is_rockchip():
raise OSError("RKNN inference is only supported on Rockchip devices.")
LOGGER.info(f"Loading {weight} for RKNN inference...")
check_requirements("rknn-toolkit-lite2")
from rknnlite.api import RKNNLite
w = Path(weight)
if not w.is_file():
w = next(w.rglob("*.rknn"))
self.model = RKNNLite()
ret = self.model.load_rknn(str(w))
if ret != 0:
raise RuntimeError(f"Failed to load RKNN model: {ret}")
ret = self.model.init_runtime()
if ret != 0:
raise RuntimeError(f"Failed to init RKNN runtime: {ret}")
# Load metadata
metadata_file = w.parent / "metadata.yaml"
if metadata_file.exists():
from ultralytics.utils import YAML
self.apply_metadata(YAML.load(metadata_file))
def forward(self, im: torch.Tensor) -> list:
im = (im.cpu().numpy() * 255).astype("uint8")
im = im if isinstance(im, (list, tuple)) else [im]
return self.model.inference(inputs=im) | --- +++ @@ -13,8 +13,22 @@
class RKNNBackend(BaseBackend):
+ """Rockchip RKNN inference backend for Rockchip NPU hardware.
+
+ Loads and runs inference with RKNN models (.rknn files) using the RKNN-Toolkit-Lite2 runtime. Only supported on
+ Rockchip devices with NPU hardware (e.g., RK3588, RK3566).
+ """
def load_model(self, weight: str | Path) -> None:
+ """Load a Rockchip RKNN model from a .rknn file or model directory.
+
+ Args:
+ weight (str | Path): Path to the .rknn file or directory containing the model.
+
+ Raises:
+ OSError: If not running on a Rockchip device.
+ RuntimeError: If model loading or runtime initialization fails.
+ """
if not is_rockchip():
raise OSError("RKNN inference is only supported on Rockchip devices.")
@@ -43,6 +57,14 @@ self.apply_metadata(YAML.load(metadata_file))
def forward(self, im: torch.Tensor) -> list:
+ """Run inference on the Rockchip NPU.
+
+ Args:
+ im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1].
+
+ Returns:
+ (list): Model predictions as a list of output arrays.
+ """
im = (im.cpu().numpy() * 255).astype("uint8")
im = im if isinstance(im, (list, tuple)) else [im]
- return self.model.inference(inputs=im)+ return self.model.inference(inputs=im)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/rknn.py |
Add docstrings that explain inputs and outputs | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from typing import Any
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
from ultralytics.utils.plotting import colors
class QueueManager(BaseSolution):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.initialize_region()
self.counts = 0 # Queue counts information
self.rect_color = (255, 255, 255) # Rectangle color for visualization
self.region_length = len(self.region) # Store region length for further usage
def process(self, im0) -> SolutionResults:
self.counts = 0 # Reset counts every frame
self.extract_tracks(im0) # Extract tracks from the current frame
annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator
annotator.draw_region(reg_pts=self.region, color=self.rect_color, thickness=self.line_width * 2) # Draw region
for box, track_id, cls, conf in zip(self.boxes, self.track_ids, self.clss, self.confs):
# Draw bounding box and counting region
annotator.box_label(box, label=self.adjust_box_label(cls, conf, track_id), color=colors(track_id, True))
self.store_tracking_history(track_id, box) # Store track history
# Cache frequently accessed attributes
track_history = self.track_history.get(track_id, [])
# Store previous position of track and check if the object is inside the counting region
prev_position = None
if len(track_history) > 1:
prev_position = track_history[-2]
if self.region_length >= 3 and prev_position and self.r_s.contains(self.Point(self.track_line[-1])):
self.counts += 1
# Display queue counts
annotator.queue_counts_display(
f"Queue Counts : {self.counts}",
points=self.region,
region_color=self.rect_color,
txt_color=(104, 31, 17),
)
plot_im = annotator.result()
self.display_output(plot_im) # Display output with base class function
# Return a SolutionResults object with processed data
return SolutionResults(plot_im=plot_im, queue_count=self.counts, total_tracks=len(self.track_ids)) | --- +++ @@ -7,8 +7,37 @@
class QueueManager(BaseSolution):
+ """Manages queue counting in real-time video streams based on object tracks.
+
+ This class extends BaseSolution to provide functionality for tracking and counting objects within a specified region
+ in video frames.
+
+ Attributes:
+ counts (int): The current count of objects in the queue.
+ rect_color (tuple[int, int, int]): BGR color tuple for drawing the queue region rectangle.
+ region_length (int): The number of points defining the queue region.
+ track_line (list[tuple[int, int]]): List of track line coordinates.
+ track_history (dict[int, list[tuple[int, int]]]): Dictionary storing tracking history for each object.
+
+ Methods:
+ initialize_region: Initialize the queue region.
+ process: Process a single frame for queue management.
+ extract_tracks: Extract object tracks from the current frame.
+ store_tracking_history: Store the tracking history for an object.
+ display_output: Display the processed output.
+
+ Examples:
+ >>> cap = cv2.VideoCapture("path/to/video.mp4")
+ >>> queue_manager = QueueManager(region=[100, 100, 200, 200, 300, 300])
+ >>> while cap.isOpened():
+ ... success, im0 = cap.read()
+ ... if not success:
+ ... break
+ ... results = queue_manager.process(im0)
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the QueueManager with parameters for tracking and counting objects in a video stream."""
super().__init__(**kwargs)
self.initialize_region()
self.counts = 0 # Queue counts information
@@ -16,6 +45,20 @@ self.region_length = len(self.region) # Store region length for further usage
def process(self, im0) -> SolutionResults:
+ """Process queue management for a single frame of video.
+
+ Args:
+ im0 (np.ndarray): Input image for processing, typically a frame from a video stream.
+
+ Returns:
+ (SolutionResults): Contains processed image `im0`, 'queue_count' (int, number of objects in the queue) and
+ 'total_tracks' (int, total number of tracked objects).
+
+ Examples:
+ >>> queue_manager = QueueManager()
+ >>> frame = cv2.imread("frame.jpg")
+ >>> results = queue_manager.process(frame)
+ """
self.counts = 0 # Reset counts every frame
self.extract_tracks(im0) # Extract tracks from the current frame
annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator
@@ -47,4 +90,4 @@ self.display_output(plot_im) # Display output with base class function
# Return a SolutionResults object with processed data
- return SolutionResults(plot_im=plot_im, queue_count=self.counts, total_tracks=len(self.track_ids))+ return SolutionResults(plot_im=plot_im, queue_count=self.counts, total_tracks=len(self.track_ids))
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/queue_management.py |
Write docstrings including parameters and return values | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from typing import Any
import cv2
import numpy as np
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
from ultralytics.utils.plotting import colors
class TrackZone(BaseSolution):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
default_region = [(75, 75), (565, 75), (565, 285), (75, 285)]
self.region = cv2.convexHull(np.array(self.region or default_region, dtype=np.int32))
self.mask = None
def process(self, im0: np.ndarray) -> SolutionResults:
annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator
if self.mask is None: # Create a mask for the region
self.mask = np.zeros_like(im0[:, :, 0])
cv2.fillPoly(self.mask, [self.region], 255)
masked_frame = cv2.bitwise_and(im0, im0, mask=self.mask)
self.extract_tracks(masked_frame)
# Draw the region boundary
cv2.polylines(im0, [self.region], isClosed=True, color=(255, 255, 255), thickness=self.line_width * 2)
# Iterate over boxes, track ids, classes indexes list and draw bounding boxes
for box, track_id, cls, conf in zip(self.boxes, self.track_ids, self.clss, self.confs):
annotator.box_label(
box, label=self.adjust_box_label(cls, conf, track_id=track_id), color=colors(track_id, True)
)
plot_im = annotator.result()
self.display_output(plot_im) # Display output with base class function
# Return a SolutionResults
return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids)) | --- +++ @@ -10,14 +10,60 @@
class TrackZone(BaseSolution):
+ """A class to manage region-based object tracking in a video stream.
+
+ This class extends the BaseSolution class and provides functionality for tracking objects within a specific region
+ defined by a polygonal area. Objects outside the region are excluded from tracking.
+
+ Attributes:
+ region (np.ndarray): The polygonal region for tracking, represented as a convex hull of points.
+ line_width (int): Width of the lines used for drawing bounding boxes and region boundaries.
+ names (list[str]): List of class names that the model can detect.
+ boxes (list[np.ndarray]): Bounding boxes of tracked objects.
+ track_ids (list[int]): Unique identifiers for each tracked object.
+ clss (list[int]): Class indices of tracked objects.
+
+ Methods:
+ process: Process each frame of the video, applying region-based tracking.
+ extract_tracks: Extract tracking information from the input frame.
+ display_output: Display the processed output.
+
+ Examples:
+ >>> tracker = TrackZone()
+ >>> frame = cv2.imread("frame.jpg")
+ >>> results = tracker.process(frame)
+ >>> cv2.imshow("Tracked Frame", results.plot_im)
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the TrackZone class for tracking objects within a defined region in video streams.
+
+ Args:
+ **kwargs (Any): Additional keyword arguments passed to the parent class.
+ """
super().__init__(**kwargs)
default_region = [(75, 75), (565, 75), (565, 285), (75, 285)]
self.region = cv2.convexHull(np.array(self.region or default_region, dtype=np.int32))
self.mask = None
def process(self, im0: np.ndarray) -> SolutionResults:
+ """Process the input frame to track objects within a defined region.
+
+ This method initializes the annotator, creates a mask for the specified region, extracts tracks only from the
+ masked area, and updates tracking information. Objects outside the region are ignored.
+
+ Args:
+ im0 (np.ndarray): The input image or frame to be processed.
+
+ Returns:
+ (SolutionResults): Contains processed image `plot_im` and `total_tracks` (int) representing the total number
+ of tracked objects within the defined region.
+
+ Examples:
+ >>> tracker = TrackZone()
+ >>> frame = cv2.imread("path/to/image.jpg")
+ >>> results = tracker.process(frame)
+ """
annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator
if self.mask is None: # Create a mask for the region
@@ -39,4 +85,4 @@ self.display_output(plot_im) # Display output with base class function
# Return a SolutionResults
- return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids))+ return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids))
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/trackzone.py |
Add clean documentation to messy code | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import json
from time import time
from ultralytics.hub import HUB_WEB_ROOT, PREFIX, HUBTrainingSession
from ultralytics.utils import LOGGER, RANK, SETTINGS
from ultralytics.utils.events import events
def on_pretrain_routine_start(trainer):
if RANK in {-1, 0} and SETTINGS["hub"] is True and SETTINGS["api_key"] and trainer.hub_session is None:
trainer.hub_session = HUBTrainingSession.create_session(trainer.args.model, trainer.args)
def on_pretrain_routine_end(trainer):
if session := getattr(trainer, "hub_session", None):
# Start timer for upload rate limit
session.timers = {"metrics": time(), "ckpt": time()} # start timer for session rate limiting
def on_fit_epoch_end(trainer):
if session := getattr(trainer, "hub_session", None):
# Upload metrics after validation ends
all_plots = {
**trainer.label_loss_items(trainer.tloss, prefix="train"),
**trainer.metrics,
}
if trainer.epoch == 0:
from ultralytics.utils.torch_utils import model_info_for_loggers
all_plots = {**all_plots, **model_info_for_loggers(trainer)}
session.metrics_queue[trainer.epoch] = json.dumps(all_plots)
# If any metrics failed to upload previously, add them to the queue to attempt uploading again
if session.metrics_upload_failed_queue:
session.metrics_queue.update(session.metrics_upload_failed_queue)
if time() - session.timers["metrics"] > session.rate_limits["metrics"]:
session.upload_metrics()
session.timers["metrics"] = time() # reset timer
session.metrics_queue = {} # reset queue
def on_model_save(trainer):
if session := getattr(trainer, "hub_session", None):
# Upload checkpoints with rate limiting
is_best = trainer.best_fitness == trainer.fitness
if time() - session.timers["ckpt"] > session.rate_limits["ckpt"]:
LOGGER.info(f"{PREFIX}Uploading checkpoint {HUB_WEB_ROOT}/models/{session.model.id}")
session.upload_model(trainer.epoch, trainer.last, is_best)
session.timers["ckpt"] = time() # reset timer
def on_train_end(trainer):
if session := getattr(trainer, "hub_session", None):
# Upload final model and metrics with exponential standoff
LOGGER.info(f"{PREFIX}Syncing final model...")
session.upload_model(
trainer.epoch,
trainer.best,
map=trainer.metrics.get("metrics/mAP50-95(B)", 0),
final=True,
)
session.alive = False # stop heartbeats
LOGGER.info(f"{PREFIX}Done ✅\n{PREFIX}View model at {session.model_url} 🚀")
def on_train_start(trainer):
events(trainer.args, trainer.device)
def on_val_start(validator):
if not validator.training:
events(validator.args, validator.device)
def on_predict_start(predictor):
events(predictor.args, predictor.device)
def on_export_start(exporter):
events(exporter.args, exporter.device)
callbacks = (
{
"on_pretrain_routine_start": on_pretrain_routine_start,
"on_pretrain_routine_end": on_pretrain_routine_end,
"on_fit_epoch_end": on_fit_epoch_end,
"on_model_save": on_model_save,
"on_train_end": on_train_end,
"on_train_start": on_train_start,
"on_val_start": on_val_start,
"on_predict_start": on_predict_start,
"on_export_start": on_export_start,
}
if SETTINGS["hub"] is True
else {}
) | --- +++ @@ -9,17 +9,20 @@
def on_pretrain_routine_start(trainer):
+ """Create a remote Ultralytics HUB session to log local model training."""
if RANK in {-1, 0} and SETTINGS["hub"] is True and SETTINGS["api_key"] and trainer.hub_session is None:
trainer.hub_session = HUBTrainingSession.create_session(trainer.args.model, trainer.args)
def on_pretrain_routine_end(trainer):
+ """Initialize timers for upload rate limiting before training begins."""
if session := getattr(trainer, "hub_session", None):
# Start timer for upload rate limit
session.timers = {"metrics": time(), "ckpt": time()} # start timer for session rate limiting
def on_fit_epoch_end(trainer):
+ """Upload training progress metrics to Ultralytics HUB at the end of each epoch."""
if session := getattr(trainer, "hub_session", None):
# Upload metrics after validation ends
all_plots = {
@@ -44,6 +47,7 @@
def on_model_save(trainer):
+ """Upload model checkpoints to Ultralytics HUB with rate limiting."""
if session := getattr(trainer, "hub_session", None):
# Upload checkpoints with rate limiting
is_best = trainer.best_fitness == trainer.fitness
@@ -54,6 +58,7 @@
def on_train_end(trainer):
+ """Upload final model and metrics to Ultralytics HUB at the end of training."""
if session := getattr(trainer, "hub_session", None):
# Upload final model and metrics with exponential standoff
LOGGER.info(f"{PREFIX}Syncing final model...")
@@ -68,19 +73,23 @@
def on_train_start(trainer):
+ """Run events on train start."""
events(trainer.args, trainer.device)
def on_val_start(validator):
+ """Run events on validation start."""
if not validator.training:
events(validator.args, validator.device)
def on_predict_start(predictor):
+ """Run events on predict start."""
events(predictor.args, predictor.device)
def on_export_start(exporter):
+ """Run events on export start."""
events(exporter.args, exporter.device)
@@ -98,4 +107,4 @@ }
if SETTINGS["hub"] is True
else {}
-)+)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/callbacks/hub.py |
Add docstrings to improve collaboration | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from collections import OrderedDict
from typing import Any
import numpy as np
class TrackState:
New = 0
Tracked = 1
Lost = 2
Removed = 3
class BaseTrack:
_count = 0
def __init__(self):
self.track_id = 0
self.is_activated = False
self.state = TrackState.New
self.history = OrderedDict()
self.features = []
self.curr_feature = None
self.score = 0
self.start_frame = 0
self.frame_id = 0
self.time_since_update = 0
self.location = (np.inf, np.inf)
@property
def end_frame(self) -> int:
return self.frame_id
@staticmethod
def next_id() -> int:
BaseTrack._count += 1
return BaseTrack._count
def activate(self, *args: Any) -> None:
raise NotImplementedError
def predict(self) -> None:
raise NotImplementedError
def update(self, *args: Any, **kwargs: Any) -> None:
raise NotImplementedError
def mark_lost(self) -> None:
self.state = TrackState.Lost
def mark_removed(self) -> None:
self.state = TrackState.Removed
@staticmethod
def reset_id() -> None:
BaseTrack._count = 0 | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Module defines the base classes and structures for object tracking in YOLO."""
from collections import OrderedDict
from typing import Any
@@ -7,6 +8,19 @@
class TrackState:
+ """Enumeration class representing the possible states of an object being tracked.
+
+ Attributes:
+ New (int): State when the object is newly detected.
+ Tracked (int): State when the object is successfully tracked in subsequent frames.
+ Lost (int): State when the object is no longer tracked.
+ Removed (int): State when the object is removed from tracking.
+
+ Examples:
+ >>> state = TrackState.New
+ >>> if state == TrackState.New:
+ ... print("Object is newly detected.")
+ """
New = 0
Tracked = 1
@@ -15,10 +29,43 @@
class BaseTrack:
+ """Base class for object tracking, providing foundational attributes and methods.
+
+ Attributes:
+ _count (int): Class-level counter for unique track IDs.
+ track_id (int): Unique identifier for the track.
+ is_activated (bool): Flag indicating whether the track is currently active.
+ state (TrackState): Current state of the track.
+ history (OrderedDict): Ordered history of the track's states.
+ features (list): List of features extracted from the object for tracking.
+ curr_feature (Any): The current feature of the object being tracked.
+ score (float): The confidence score of the tracking.
+ start_frame (int): The frame number where tracking started.
+ frame_id (int): The most recent frame ID processed by the track.
+ time_since_update (int): Frames passed since the last update.
+ location (tuple): The location of the object in the context of multi-camera tracking.
+
+ Methods:
+ end_frame: Returns the ID of the last frame where the object was tracked.
+ next_id: Increments and returns the next global track ID.
+ activate: Abstract method to activate the track.
+ predict: Abstract method to predict the next state of the track.
+ update: Abstract method to update the track with new data.
+ mark_lost: Marks the track as lost.
+ mark_removed: Marks the track as removed.
+ reset_id: Resets the global track ID counter.
+
+ Examples:
+ Initialize a new track and mark it as lost:
+ >>> track = BaseTrack()
+ >>> track.mark_lost()
+ >>> print(track.state) # Output: 2 (TrackState.Lost)
+ """
_count = 0
def __init__(self):
+ """Initialize a new track with a unique ID and foundational tracking attributes."""
self.track_id = 0
self.is_activated = False
self.state = TrackState.New
@@ -33,28 +80,36 @@
@property
def end_frame(self) -> int:
+ """Return the ID of the most recent frame where the object was tracked."""
return self.frame_id
@staticmethod
def next_id() -> int:
+ """Increment and return the next unique global track ID for object tracking."""
BaseTrack._count += 1
return BaseTrack._count
def activate(self, *args: Any) -> None:
+ """Activate the track with provided arguments, initializing necessary attributes for tracking."""
raise NotImplementedError
def predict(self) -> None:
+ """Predict the next state of the track based on the current state and tracking model."""
raise NotImplementedError
def update(self, *args: Any, **kwargs: Any) -> None:
+ """Update the track with new observations and data, modifying its state and attributes accordingly."""
raise NotImplementedError
def mark_lost(self) -> None:
+ """Mark the track as lost by updating its state to TrackState.Lost."""
self.state = TrackState.Lost
def mark_removed(self) -> None:
+ """Mark the track as removed by setting its state to TrackState.Removed."""
self.state = TrackState.Removed
@staticmethod
def reset_id() -> None:
- BaseTrack._count = 0+ """Reset the global track ID counter to its initial value."""
+ BaseTrack._count = 0
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/trackers/basetrack.py |
Fully document this Python code with docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import ast
import json
import platform
import zipfile
from pathlib import Path
import numpy as np
import torch
from ultralytics.utils import LOGGER
from .base import BaseBackend
class TensorFlowBackend(BaseBackend):
def __init__(self, weight: str | Path, device: torch.device, fp16: bool = False, format: str = "saved_model"):
assert format in {"saved_model", "pb", "tflite", "edgetpu"}, f"Unsupported TensorFlow format: {format}."
self.format = format
super().__init__(weight, device, fp16)
def load_model(self, weight: str | Path) -> None:
import tensorflow as tf
if self.format == "saved_model":
LOGGER.info(f"Loading {weight} for TensorFlow SavedModel inference...")
self.model = tf.saved_model.load(weight)
# Load metadata
metadata_file = Path(weight) / "metadata.yaml"
if metadata_file.exists():
from ultralytics.utils import YAML
self.apply_metadata(YAML.load(metadata_file))
elif self.format == "pb":
LOGGER.info(f"Loading {weight} for TensorFlow GraphDef inference...")
from ultralytics.utils.export.tensorflow import gd_outputs
def wrap_frozen_graph(gd, inputs, outputs):
x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), [])
ge = x.graph.as_graph_element
return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))
gd = tf.Graph().as_graph_def()
with open(weight, "rb") as f:
gd.ParseFromString(f.read())
self.frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs=gd_outputs(gd))
# Try to find metadata
try:
metadata_file = next(
Path(weight).resolve().parent.rglob(f"{Path(weight).stem}_saved_model*/metadata.yaml")
)
from ultralytics.utils import YAML
self.apply_metadata(YAML.load(metadata_file))
except StopIteration:
pass
else: # tflite and edgetpu
try:
from tflite_runtime.interpreter import Interpreter, load_delegate
self.tf = None
except ImportError:
import tensorflow as tf
self.tf = tf
Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate
if self.format == "edgetpu":
device = self.device[3:] if str(self.device).startswith("tpu") else ":0"
LOGGER.info(f"Loading {weight} on device {device[1:]} for TensorFlow Lite Edge TPU inference...")
delegate = {"Linux": "libedgetpu.so.1", "Darwin": "libedgetpu.1.dylib", "Windows": "edgetpu.dll"}[
platform.system()
]
self.interpreter = Interpreter(
model_path=str(weight),
experimental_delegates=[load_delegate(delegate, options={"device": device})],
)
self.device = torch.device("cpu") # Edge TPU runs on CPU from PyTorch's perspective
else:
LOGGER.info(f"Loading {weight} for TensorFlow Lite inference...")
self.interpreter = Interpreter(model_path=weight)
self.interpreter.allocate_tensors()
self.input_details = self.interpreter.get_input_details()
self.output_details = self.interpreter.get_output_details()
# Load metadata
try:
with zipfile.ZipFile(weight, "r") as zf:
name = zf.namelist()[0]
contents = zf.read(name).decode("utf-8")
if name == "metadata.json":
self.apply_metadata(json.loads(contents))
else:
self.apply_metadata(ast.literal_eval(contents))
except (zipfile.BadZipFile, SyntaxError, ValueError, json.JSONDecodeError):
pass
def forward(self, im: torch.Tensor) -> list[np.ndarray]:
im = im.cpu().numpy()
if self.format == "saved_model":
y = self.model.serving_default(im)
if not isinstance(y, list):
y = [y]
elif self.format == "pb":
import tensorflow as tf
y = self.frozen_func(x=tf.constant(im))
else:
h, w = im.shape[1:3]
details = self.input_details[0]
is_int = details["dtype"] in {np.int8, np.int16}
if is_int:
scale, zero_point = details["quantization"]
im = (im / scale + zero_point).astype(details["dtype"])
self.interpreter.set_tensor(details["index"], im)
self.interpreter.invoke()
y = []
for output in self.output_details:
x = self.interpreter.get_tensor(output["index"])
if is_int:
scale, zero_point = output["quantization"]
x = (x.astype(np.float32) - zero_point) * scale
if x.ndim == 3:
# Denormalize xywh by image size
if x.shape[-1] == 6 or self.end2end:
x[:, :, [0, 2]] *= w
x[:, :, [1, 3]] *= h
if self.task == "pose":
x[:, :, 6::3] *= w
x[:, :, 7::3] *= h
else:
x[:, [0, 2]] *= w
x[:, [1, 3]] *= h
if self.task == "pose":
x[:, 5::3] *= w
x[:, 6::3] *= h
y.append(x)
if self.task == "segment": # segment with (det, proto) output order reversed
if len(y[1].shape) != 4:
y = list(reversed(y)) # should be y = (1, 116, 8400), (1, 160, 160, 32)
if y[1].shape[-1] == 6: # end-to-end model
y = [y[1]]
else:
y[1] = np.transpose(y[1], (0, 3, 1, 2)) # should be y = (1, 116, 8400), (1, 32, 160, 160)
return [x if isinstance(x, np.ndarray) else x.numpy() for x in y] | --- +++ @@ -17,13 +17,31 @@
class TensorFlowBackend(BaseBackend):
+ """Google TensorFlow inference backend supporting multiple serialization formats.
+
+ Loads and runs inference with Google TensorFlow models in SavedModel, GraphDef (.pb), TFLite (.tflite), and Edge TPU
+ formats. Handles quantized model dequantization and task-specific output formatting.
+ """
def __init__(self, weight: str | Path, device: torch.device, fp16: bool = False, format: str = "saved_model"):
+ """Initialize the Google TensorFlow backend.
+
+ Args:
+ weight (str | Path): Path to the SavedModel directory, .pb file, or .tflite file.
+ device (torch.device): Device to run inference on.
+ fp16 (bool): Whether to use FP16 half-precision inference.
+ format (str): Model format, one of "saved_model", "pb", "tflite", or "edgetpu".
+ """
assert format in {"saved_model", "pb", "tflite", "edgetpu"}, f"Unsupported TensorFlow format: {format}."
self.format = format
super().__init__(weight, device, fp16)
def load_model(self, weight: str | Path) -> None:
+ """Load a Google TensorFlow model in SavedModel, GraphDef, TFLite, or Edge TPU format.
+
+ Args:
+ weight (str | Path): Path to the model file or directory.
+ """
import tensorflow as tf
if self.format == "saved_model":
@@ -40,6 +58,7 @@ from ultralytics.utils.export.tensorflow import gd_outputs
def wrap_frozen_graph(gd, inputs, outputs):
+ """Wrap a TensorFlow frozen graph for inference by pruning to specified input/output nodes."""
x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), [])
ge = x.graph.as_graph_element
return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))
@@ -102,6 +121,14 @@ pass
def forward(self, im: torch.Tensor) -> list[np.ndarray]:
+ """Run Google TensorFlow inference with format-specific execution and output post-processing.
+
+ Args:
+ im (torch.Tensor): Input image tensor in BHWC format (converted from BCHW by AutoBackend).
+
+ Returns:
+ (list[np.ndarray]): Model predictions as a list of numpy arrays.
+ """
im = im.cpu().numpy()
if self.format == "saved_model":
y = self.model.serving_default(im)
@@ -153,4 +180,4 @@ y = [y[1]]
else:
y[1] = np.transpose(y[1], (0, 3, 1, 2)) # should be y = (1, 116, 8400), (1, 32, 160, 160)
- return [x if isinstance(x, np.ndarray) else x.numpy() for x in y]+ return [x if isinstance(x, np.ndarray) else x.numpy() for x in y]
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/tensorflow.py |
Generate docstrings for each module | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from collections.abc import Callable
from types import SimpleNamespace
from typing import Any
import cv2
import numpy as np
from ultralytics.utils import LOGGER, RANK, SETTINGS, TESTS_RUNNING, ops
from ultralytics.utils.metrics import ClassifyMetrics, DetMetrics, OBBMetrics, PoseMetrics, SegmentMetrics
try:
assert not TESTS_RUNNING # do not log pytest
assert SETTINGS["comet"] is True # verify integration is enabled
import comet_ml
assert hasattr(comet_ml, "__version__") # verify package is not directory
import os
from pathlib import Path
# Ensures certain logging functions only run for supported tasks
COMET_SUPPORTED_TASKS = ["detect", "segment"]
# Names of plots created by Ultralytics that are logged to Comet
CONFUSION_MATRIX_PLOT_NAMES = "confusion_matrix", "confusion_matrix_normalized"
EVALUATION_PLOT_NAMES = "F1_curve", "P_curve", "R_curve", "PR_curve"
LABEL_PLOT_NAMES = ["labels"]
SEGMENT_METRICS_PLOT_PREFIX = "Box", "Mask"
POSE_METRICS_PLOT_PREFIX = "Box", "Pose"
DETECTION_METRICS_PLOT_PREFIX = ["Box"]
RESULTS_TABLE_NAME = "results.csv"
ARGS_YAML_NAME = "args.yaml"
_comet_image_prediction_count = 0
except (ImportError, AssertionError):
comet_ml = None
def _get_comet_mode() -> str:
comet_mode = os.getenv("COMET_MODE")
if comet_mode is not None:
LOGGER.warning(
"The COMET_MODE environment variable is deprecated. "
"Please use COMET_START_ONLINE to set the Comet experiment mode. "
"To start an offline Comet experiment, use 'export COMET_START_ONLINE=0'. "
"If COMET_START_ONLINE is not set or is set to '1', an online Comet experiment will be created."
)
return comet_mode
return "online"
def _get_comet_model_name() -> str:
return os.getenv("COMET_MODEL_NAME", "Ultralytics")
def _get_eval_batch_logging_interval() -> int:
return int(os.getenv("COMET_EVAL_BATCH_LOGGING_INTERVAL", 1))
def _get_max_image_predictions_to_log() -> int:
return int(os.getenv("COMET_MAX_IMAGE_PREDICTIONS", 100))
def _scale_confidence_score(score: float) -> float:
scale = float(os.getenv("COMET_MAX_CONFIDENCE_SCORE", 100.0))
return score * scale
def _should_log_confusion_matrix() -> bool:
return os.getenv("COMET_EVAL_LOG_CONFUSION_MATRIX", "false").lower() == "true"
def _should_log_image_predictions() -> bool:
return os.getenv("COMET_EVAL_LOG_IMAGE_PREDICTIONS", "true").lower() == "true"
def _resume_or_create_experiment(args: SimpleNamespace) -> None:
if RANK not in {-1, 0}:
return
# Set environment variable (if not set by the user) to configure the Comet experiment's online mode under the hood.
# IF COMET_START_ONLINE is set by the user it will override COMET_MODE value.
if os.getenv("COMET_START_ONLINE") is None:
comet_mode = _get_comet_mode()
os.environ["COMET_START_ONLINE"] = "1" if comet_mode != "offline" else "0"
try:
_project_name = os.getenv("COMET_PROJECT_NAME", args.project)
experiment = comet_ml.start(project_name=_project_name)
experiment.log_parameters(vars(args))
experiment.log_others(
{
"eval_batch_logging_interval": _get_eval_batch_logging_interval(),
"log_confusion_matrix_on_eval": _should_log_confusion_matrix(),
"log_image_predictions": _should_log_image_predictions(),
"max_image_predictions": _get_max_image_predictions_to_log(),
}
)
experiment.log_other("Created from", "ultralytics")
except Exception as e:
LOGGER.warning(f"Comet installed but not initialized correctly, not logging this run. {e}")
def _fetch_trainer_metadata(trainer) -> dict:
curr_epoch = trainer.epoch + 1
train_num_steps_per_epoch = len(trainer.train_loader.dataset) // trainer.batch_size
curr_step = curr_epoch * train_num_steps_per_epoch
final_epoch = curr_epoch == trainer.epochs
save = trainer.args.save
save_period = trainer.args.save_period
save_interval = curr_epoch % save_period == 0
save_assets = save and save_period > 0 and save_interval and not final_epoch
return dict(curr_epoch=curr_epoch, curr_step=curr_step, save_assets=save_assets, final_epoch=final_epoch)
def _scale_bounding_box_to_original_image_shape(
box, resized_image_shape, original_image_shape, ratio_pad
) -> list[float]:
resized_image_height, resized_image_width = resized_image_shape
# Convert normalized xywh format predictions to xyxy in resized scale format
box = ops.xywhn2xyxy(box, h=resized_image_height, w=resized_image_width)
# Scale box predictions from resized image scale back to original image scale
box = ops.scale_boxes(resized_image_shape, box, original_image_shape, ratio_pad)
# Convert bounding box format from xyxy to xywh for Comet logging
box = ops.xyxy2xywh(box)
# Adjust xy center to correspond top-left corner
box[:2] -= box[2:] / 2
box = box.tolist()
return box
def _format_ground_truth_annotations_for_detection(img_idx, image_path, batch, class_name_map=None) -> dict | None:
indices = batch["batch_idx"] == img_idx
bboxes = batch["bboxes"][indices]
if len(bboxes) == 0:
LOGGER.debug(f"Comet Image: {image_path} has no bounding boxes labels")
return None
cls_labels = batch["cls"][indices].squeeze(1).tolist()
if class_name_map:
cls_labels = [str(class_name_map[label]) for label in cls_labels]
original_image_shape = batch["ori_shape"][img_idx]
resized_image_shape = batch["resized_shape"][img_idx]
ratio_pad = batch["ratio_pad"][img_idx]
data = []
for box, label in zip(bboxes, cls_labels):
box = _scale_bounding_box_to_original_image_shape(box, resized_image_shape, original_image_shape, ratio_pad)
data.append(
{
"boxes": [box],
"label": f"gt_{label}",
"score": _scale_confidence_score(1.0),
}
)
return {"name": "ground_truth", "data": data}
def _format_prediction_annotations(image_path, metadata, class_label_map=None, class_map=None) -> dict | None:
stem = image_path.stem
image_id = int(stem) if stem.isnumeric() else stem
predictions = metadata.get(image_id)
if not predictions:
LOGGER.debug(f"Comet Image: {image_path} has no bounding boxes predictions")
return None
# apply the mapping that was used to map the predicted classes when the JSON was created
if class_label_map and class_map:
class_label_map = {class_map[k]: v for k, v in class_label_map.items()}
try:
# import pycotools utilities to decompress annotations for various tasks, e.g. segmentation
from faster_coco_eval.core.mask import decode
except ImportError:
decode = None
data = []
for prediction in predictions:
boxes = prediction["bbox"]
score = _scale_confidence_score(prediction["score"])
cls_label = prediction["category_id"]
if class_label_map:
cls_label = str(class_label_map[cls_label])
annotation_data = {"boxes": [boxes], "label": cls_label, "score": score}
if decode is not None:
# do segmentation processing only if we are able to decode it
segments = prediction.get("segmentation", None)
if segments is not None:
segments = _extract_segmentation_annotation(segments, decode)
if segments is not None:
annotation_data["points"] = segments
data.append(annotation_data)
return {"name": "prediction", "data": data}
def _extract_segmentation_annotation(segmentation_raw: str, decode: Callable) -> list[list[Any]] | None:
try:
mask = decode(segmentation_raw)
contours, _ = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
annotations = [np.array(polygon).squeeze() for polygon in contours if len(polygon) >= 3]
return [annotation.ravel().tolist() for annotation in annotations]
except Exception as e:
LOGGER.warning(f"Comet Failed to extract segmentation annotation: {e}")
return None
def _fetch_annotations(img_idx, image_path, batch, prediction_metadata_map, class_label_map, class_map) -> list | None:
ground_truth_annotations = _format_ground_truth_annotations_for_detection(
img_idx, image_path, batch, class_label_map
)
prediction_annotations = _format_prediction_annotations(
image_path, prediction_metadata_map, class_label_map, class_map
)
annotations = [
annotation for annotation in [ground_truth_annotations, prediction_annotations] if annotation is not None
]
return [annotations] if annotations else None
def _create_prediction_metadata_map(model_predictions) -> dict:
pred_metadata_map = {}
for prediction in model_predictions:
pred_metadata_map.setdefault(prediction["image_id"], [])
pred_metadata_map[prediction["image_id"]].append(prediction)
return pred_metadata_map
def _log_confusion_matrix(experiment, trainer, curr_step, curr_epoch) -> None:
conf_mat = trainer.validator.confusion_matrix.matrix
names = [*list(trainer.data["names"].values()), "background"]
experiment.log_confusion_matrix(
matrix=conf_mat, labels=names, max_categories=len(names), epoch=curr_epoch, step=curr_step
)
def _log_images(experiment, image_paths, curr_step: int | None, annotations=None) -> None:
if annotations:
for image_path, annotation in zip(image_paths, annotations):
experiment.log_image(image_path, name=image_path.stem, step=curr_step, annotations=annotation)
else:
for image_path in image_paths:
experiment.log_image(image_path, name=image_path.stem, step=curr_step)
def _log_image_predictions(experiment, validator, curr_step) -> None:
global _comet_image_prediction_count
task = validator.args.task
if task not in COMET_SUPPORTED_TASKS:
return
jdict = validator.jdict
if not jdict:
return
predictions_metadata_map = _create_prediction_metadata_map(jdict)
dataloader = validator.dataloader
class_label_map = validator.names
class_map = getattr(validator, "class_map", None)
batch_logging_interval = _get_eval_batch_logging_interval()
max_image_predictions = _get_max_image_predictions_to_log()
for batch_idx, batch in enumerate(dataloader):
if (batch_idx + 1) % batch_logging_interval != 0:
continue
image_paths = batch["im_file"]
for img_idx, image_path in enumerate(image_paths):
if _comet_image_prediction_count >= max_image_predictions:
return
image_path = Path(image_path)
annotations = _fetch_annotations(
img_idx,
image_path,
batch,
predictions_metadata_map,
class_label_map,
class_map=class_map,
)
_log_images(
experiment,
[image_path],
curr_step,
annotations=annotations,
)
_comet_image_prediction_count += 1
def _log_plots(experiment, trainer) -> None:
plot_filenames = None
if isinstance(trainer.validator.metrics, SegmentMetrics):
plot_filenames = [
trainer.save_dir / f"{prefix}{plots}.png"
for plots in EVALUATION_PLOT_NAMES
for prefix in SEGMENT_METRICS_PLOT_PREFIX
]
elif isinstance(trainer.validator.metrics, PoseMetrics):
plot_filenames = [
trainer.save_dir / f"{prefix}{plots}.png"
for plots in EVALUATION_PLOT_NAMES
for prefix in POSE_METRICS_PLOT_PREFIX
]
elif isinstance(trainer.validator.metrics, (DetMetrics, OBBMetrics)):
plot_filenames = [
trainer.save_dir / f"{prefix}{plots}.png"
for plots in EVALUATION_PLOT_NAMES
for prefix in DETECTION_METRICS_PLOT_PREFIX
]
if plot_filenames is not None:
_log_images(experiment, plot_filenames, None)
confusion_matrix_filenames = [trainer.save_dir / f"{plots}.png" for plots in CONFUSION_MATRIX_PLOT_NAMES]
_log_images(experiment, confusion_matrix_filenames, None)
if not isinstance(trainer.validator.metrics, ClassifyMetrics):
label_plot_filenames = [trainer.save_dir / f"{labels}.jpg" for labels in LABEL_PLOT_NAMES]
_log_images(experiment, label_plot_filenames, None)
def _log_model(experiment, trainer) -> None:
model_name = _get_comet_model_name()
experiment.log_model(model_name, file_or_folder=str(trainer.best), file_name="best.pt", overwrite=True)
def _log_image_batches(experiment, trainer, curr_step: int) -> None:
_log_images(experiment, trainer.save_dir.glob("train_batch*.jpg"), curr_step)
_log_images(experiment, trainer.save_dir.glob("val_batch*.jpg"), curr_step)
def _log_asset(experiment, asset_path) -> None:
experiment.log_asset(asset_path)
def _log_table(experiment, table_path) -> None:
experiment.log_table(str(table_path))
def on_pretrain_routine_start(trainer) -> None:
_resume_or_create_experiment(trainer.args)
def on_train_epoch_end(trainer) -> None:
experiment = comet_ml.get_running_experiment()
if not experiment:
return
metadata = _fetch_trainer_metadata(trainer)
curr_epoch = metadata["curr_epoch"]
curr_step = metadata["curr_step"]
experiment.log_metrics(trainer.label_loss_items(trainer.tloss, prefix="train"), step=curr_step, epoch=curr_epoch)
def on_fit_epoch_end(trainer) -> None:
experiment = comet_ml.get_running_experiment()
if not experiment:
return
metadata = _fetch_trainer_metadata(trainer)
curr_epoch = metadata["curr_epoch"]
curr_step = metadata["curr_step"]
save_assets = metadata["save_assets"]
experiment.log_metrics(trainer.metrics, step=curr_step, epoch=curr_epoch)
experiment.log_metrics(trainer.lr, step=curr_step, epoch=curr_epoch)
if curr_epoch == 1:
from ultralytics.utils.torch_utils import model_info_for_loggers
experiment.log_metrics(model_info_for_loggers(trainer), step=curr_step, epoch=curr_epoch)
if not save_assets:
return
_log_model(experiment, trainer)
if _should_log_confusion_matrix():
_log_confusion_matrix(experiment, trainer, curr_step, curr_epoch)
if _should_log_image_predictions():
_log_image_predictions(experiment, trainer.validator, curr_step)
def on_train_end(trainer) -> None:
experiment = comet_ml.get_running_experiment()
if not experiment:
return
metadata = _fetch_trainer_metadata(trainer)
curr_epoch = metadata["curr_epoch"]
curr_step = metadata["curr_step"]
plots = trainer.args.plots
_log_model(experiment, trainer)
if plots:
_log_plots(experiment, trainer)
_log_confusion_matrix(experiment, trainer, curr_step, curr_epoch)
_log_image_predictions(experiment, trainer.validator, curr_step)
_log_image_batches(experiment, trainer, curr_step)
# log results table
table_path = trainer.save_dir / RESULTS_TABLE_NAME
if table_path.exists():
_log_table(experiment, table_path)
# log arguments YAML
args_path = trainer.save_dir / ARGS_YAML_NAME
if args_path.exists():
_log_asset(experiment, args_path)
experiment.end()
global _comet_image_prediction_count
_comet_image_prediction_count = 0
callbacks = (
{
"on_pretrain_routine_start": on_pretrain_routine_start,
"on_train_epoch_end": on_train_epoch_end,
"on_fit_epoch_end": on_fit_epoch_end,
"on_train_end": on_train_end,
}
if comet_ml
else {}
) | --- +++ @@ -42,6 +42,7 @@
def _get_comet_mode() -> str:
+ """Return the Comet mode from environment variables, defaulting to 'online'."""
comet_mode = os.getenv("COMET_MODE")
if comet_mode is not None:
LOGGER.warning(
@@ -56,31 +57,44 @@
def _get_comet_model_name() -> str:
+ """Return the Comet model name from environment variable or default to 'Ultralytics'."""
return os.getenv("COMET_MODEL_NAME", "Ultralytics")
def _get_eval_batch_logging_interval() -> int:
+ """Get the evaluation batch logging interval from environment variable or use default value 1."""
return int(os.getenv("COMET_EVAL_BATCH_LOGGING_INTERVAL", 1))
def _get_max_image_predictions_to_log() -> int:
+ """Get the maximum number of image predictions to log from environment variables."""
return int(os.getenv("COMET_MAX_IMAGE_PREDICTIONS", 100))
def _scale_confidence_score(score: float) -> float:
+ """Scale the confidence score by a factor specified in environment variable."""
scale = float(os.getenv("COMET_MAX_CONFIDENCE_SCORE", 100.0))
return score * scale
def _should_log_confusion_matrix() -> bool:
+ """Determine if the confusion matrix should be logged based on environment variable settings."""
return os.getenv("COMET_EVAL_LOG_CONFUSION_MATRIX", "false").lower() == "true"
def _should_log_image_predictions() -> bool:
+ """Determine whether to log image predictions based on environment variable."""
return os.getenv("COMET_EVAL_LOG_IMAGE_PREDICTIONS", "true").lower() == "true"
def _resume_or_create_experiment(args: SimpleNamespace) -> None:
+ """Resume CometML experiment or create a new experiment based on args.
+
+ Ensures that the experiment object is only created in a single process during distributed training.
+
+ Args:
+ args (SimpleNamespace): Training arguments containing project configuration and other parameters.
+ """
if RANK not in {-1, 0}:
return
@@ -109,6 +123,14 @@
def _fetch_trainer_metadata(trainer) -> dict:
+ """Return metadata for YOLO training including epoch and asset saving status.
+
+ Args:
+ trainer (ultralytics.engine.trainer.BaseTrainer): The YOLO trainer object containing training state and config.
+
+ Returns:
+ (dict): Dictionary containing current epoch, step, save assets flag, and final epoch flag.
+ """
curr_epoch = trainer.epoch + 1
train_num_steps_per_epoch = len(trainer.train_loader.dataset) // trainer.batch_size
@@ -126,6 +148,20 @@ def _scale_bounding_box_to_original_image_shape(
box, resized_image_shape, original_image_shape, ratio_pad
) -> list[float]:
+ """Scale bounding box from resized image coordinates to original image coordinates.
+
+ YOLO resizes images during training and the label values are normalized based on this resized shape. This function
+ rescales the bounding box labels to the original image shape.
+
+ Args:
+ box (torch.Tensor): Bounding box in normalized xywh format.
+ resized_image_shape (tuple): Shape of the resized image (height, width).
+ original_image_shape (tuple): Shape of the original image (height, width).
+ ratio_pad (tuple): Ratio and padding information for scaling.
+
+ Returns:
+ (list[float]): Scaled bounding box coordinates in xywh format with top-left corner adjustment.
+ """
resized_image_height, resized_image_width = resized_image_shape
# Convert normalized xywh format predictions to xyxy in resized scale format
@@ -142,6 +178,29 @@
def _format_ground_truth_annotations_for_detection(img_idx, image_path, batch, class_name_map=None) -> dict | None:
+ """Format ground truth annotations for object detection.
+
+ This function processes ground truth annotations from a batch of images for object detection tasks. It extracts
+ bounding boxes, class labels, and other metadata for a specific image in the batch, and formats them for
+ visualization or evaluation.
+
+ Args:
+ img_idx (int): Index of the image in the batch to process.
+ image_path (str | Path): Path to the image file.
+ batch (dict): Batch dictionary containing detection data with keys:
+ - 'batch_idx': Tensor of batch indices
+ - 'bboxes': Tensor of bounding boxes in normalized xywh format
+ - 'cls': Tensor of class labels
+ - 'ori_shape': Original image shapes
+ - 'resized_shape': Resized image shapes
+ - 'ratio_pad': Ratio and padding information
+ class_name_map (dict, optional): Mapping from class indices to class names.
+
+ Returns:
+ (dict | None): Formatted ground truth annotations with keys 'name' and 'data', where 'data' is a list of
+ annotation dicts each containing 'boxes', 'label', and 'score' keys. Returns None if no bounding boxes are
+ found for the image.
+ """
indices = batch["batch_idx"] == img_idx
bboxes = batch["bboxes"][indices]
if len(bboxes) == 0:
@@ -171,6 +230,17 @@
def _format_prediction_annotations(image_path, metadata, class_label_map=None, class_map=None) -> dict | None:
+ """Format YOLO predictions for object detection visualization.
+
+ Args:
+ image_path (Path): Path to the image file.
+ metadata (dict): Prediction metadata containing bounding boxes and class information.
+ class_label_map (dict, optional): Mapping from class indices to class names.
+ class_map (dict, optional): Additional class mapping for label conversion.
+
+ Returns:
+ (dict | None): Formatted prediction annotations or None if no predictions exist.
+ """
stem = image_path.stem
image_id = int(stem) if stem.isnumeric() else stem
@@ -212,6 +282,15 @@
def _extract_segmentation_annotation(segmentation_raw: str, decode: Callable) -> list[list[Any]] | None:
+ """Extract segmentation annotation from compressed segmentations as list of polygons.
+
+ Args:
+ segmentation_raw (str): Raw segmentation data in compressed format.
+ decode (Callable): Function to decode the compressed segmentation data.
+
+ Returns:
+ (list[list[Any]] | None): List of polygon points or None if extraction fails.
+ """
try:
mask = decode(segmentation_raw)
contours, _ = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
@@ -223,6 +302,19 @@
def _fetch_annotations(img_idx, image_path, batch, prediction_metadata_map, class_label_map, class_map) -> list | None:
+ """Join the ground truth and prediction annotations if they exist.
+
+ Args:
+ img_idx (int): Index of the image in the batch.
+ image_path (Path): Path to the image file.
+ batch (dict): Batch data containing ground truth annotations.
+ prediction_metadata_map (dict): Map of prediction metadata by image ID.
+ class_label_map (dict): Mapping from class indices to class names.
+ class_map (dict): Additional class mapping for label conversion.
+
+ Returns:
+ (list | None): List of annotation dictionaries or None if no annotations exist.
+ """
ground_truth_annotations = _format_ground_truth_annotations_for_detection(
img_idx, image_path, batch, class_label_map
)
@@ -237,6 +329,7 @@
def _create_prediction_metadata_map(model_predictions) -> dict:
+ """Create metadata map for model predictions by grouping them based on image ID."""
pred_metadata_map = {}
for prediction in model_predictions:
pred_metadata_map.setdefault(prediction["image_id"], [])
@@ -246,6 +339,7 @@
def _log_confusion_matrix(experiment, trainer, curr_step, curr_epoch) -> None:
+ """Log the confusion matrix to Comet experiment."""
conf_mat = trainer.validator.confusion_matrix.matrix
names = [*list(trainer.data["names"].values()), "background"]
experiment.log_confusion_matrix(
@@ -254,6 +348,18 @@
def _log_images(experiment, image_paths, curr_step: int | None, annotations=None) -> None:
+ """Log images to the experiment with optional annotations.
+
+ This function logs images to a Comet ML experiment, optionally including annotation data for visualization such as
+ bounding boxes or segmentation masks.
+
+ Args:
+ experiment (comet_ml.CometExperiment): The Comet ML experiment to log images to.
+ image_paths (list[Path]): List of paths to images that will be logged.
+ curr_step (int | None): Current training step/iteration for tracking in the experiment timeline.
+ annotations (list[list[dict]], optional): Nested list of annotation dictionaries for each image. Each annotation
+ contains visualization data like bounding boxes, labels, and confidence scores.
+ """
if annotations:
for image_path, annotation in zip(image_paths, annotations):
experiment.log_image(image_path, name=image_path.stem, step=curr_step, annotations=annotation)
@@ -264,6 +370,21 @@
def _log_image_predictions(experiment, validator, curr_step) -> None:
+ """Log image predictions to a Comet ML experiment during model validation.
+
+ This function processes validation data and formats both ground truth and prediction annotations for visualization
+ in the Comet dashboard. The function respects configured limits on the number of images to log.
+
+ Args:
+ experiment (comet_ml.CometExperiment): The Comet ML experiment to log to.
+ validator (BaseValidator): The validator instance containing validation data and predictions.
+ curr_step (int): The current training step for logging timeline.
+
+ Notes:
+ This function uses global state to track the number of logged predictions across calls.
+ It only logs predictions for supported tasks defined in COMET_SUPPORTED_TASKS.
+ The number of logged images is limited by the COMET_MAX_IMAGE_PREDICTIONS environment variable.
+ """
global _comet_image_prediction_count
task = validator.args.task
@@ -310,6 +431,21 @@
def _log_plots(experiment, trainer) -> None:
+ """Log evaluation plots and label plots for the experiment.
+
+ This function logs various evaluation plots and confusion matrices to the experiment tracking system. It handles
+ different types of metrics (SegmentMetrics, PoseMetrics, DetMetrics, OBBMetrics) and logs the appropriate plots for
+ each type.
+
+ Args:
+ experiment (comet_ml.CometExperiment): The Comet ML experiment to log plots to.
+ trainer (ultralytics.engine.trainer.BaseTrainer): The trainer object containing validation metrics and save
+ directory information.
+
+ Examples:
+ >>> from ultralytics.utils.callbacks.comet import _log_plots
+ >>> _log_plots(experiment, trainer)
+ """
plot_filenames = None
if isinstance(trainer.validator.metrics, SegmentMetrics):
plot_filenames = [
@@ -342,28 +478,49 @@
def _log_model(experiment, trainer) -> None:
+ """Log the best-trained model to Comet.ml."""
model_name = _get_comet_model_name()
experiment.log_model(model_name, file_or_folder=str(trainer.best), file_name="best.pt", overwrite=True)
def _log_image_batches(experiment, trainer, curr_step: int) -> None:
+ """Log samples of image batches for train and validation."""
_log_images(experiment, trainer.save_dir.glob("train_batch*.jpg"), curr_step)
_log_images(experiment, trainer.save_dir.glob("val_batch*.jpg"), curr_step)
def _log_asset(experiment, asset_path) -> None:
+ """Logs a specific asset file to the given experiment.
+
+ This function facilitates logging an asset, such as a file, to the provided
+ experiment. It enables integration with experiment tracking platforms.
+
+ Args:
+ experiment (comet_ml.CometExperiment): The experiment instance to which the asset will be logged.
+ asset_path (Path): The file path of the asset to log.
+ """
experiment.log_asset(asset_path)
def _log_table(experiment, table_path) -> None:
+ """Logs a table to the provided experiment.
+
+ This function is used to log a table file to the given experiment. The table is identified by its file path.
+
+ Args:
+ experiment (comet_ml.CometExperiment): The experiment object where the table file will be logged.
+ table_path (Path): The file path of the table to be logged.
+ """
experiment.log_table(str(table_path))
def on_pretrain_routine_start(trainer) -> None:
+ """Create or resume a CometML experiment at the start of a YOLO pre-training routine."""
_resume_or_create_experiment(trainer.args)
def on_train_epoch_end(trainer) -> None:
+ """Log metrics and save batch images at the end of training epochs."""
experiment = comet_ml.get_running_experiment()
if not experiment:
return
@@ -376,6 +533,23 @@
def on_fit_epoch_end(trainer) -> None:
+ """Log model assets at the end of each epoch during training.
+
+ This function is called at the end of each training epoch to log metrics, learning rates, and model information to a
+ Comet ML experiment. It also logs model assets, confusion matrices, and image predictions based on configuration
+ settings.
+
+ The function retrieves the current Comet ML experiment and logs various training metrics. If it's the first epoch,
+ it also logs model information. On specified save intervals, it logs the model, confusion matrix (if enabled), and
+ image predictions (if enabled).
+
+ Args:
+ trainer (BaseTrainer): The YOLO trainer object containing training state, metrics, and configuration.
+
+ Examples:
+ >>> # Inside a training loop
+ >>> on_fit_epoch_end(trainer) # Log metrics and assets to Comet ML
+ """
experiment = comet_ml.get_running_experiment()
if not experiment:
return
@@ -403,6 +577,7 @@
def on_train_end(trainer) -> None:
+ """Perform operations at the end of training."""
experiment = comet_ml.get_running_experiment()
if not experiment:
return
@@ -444,4 +619,4 @@ }
if comet_ml
else {}
-)+)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/callbacks/comet.py |
Help me comply with documentation standards | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import numpy as np
import scipy
from scipy.spatial.distance import cdist
from ultralytics.utils.metrics import batch_probiou, bbox_ioa
try:
import lap # for linear_assignment
assert lap.__version__ # verify package is not directory
except (ImportError, AssertionError, AttributeError):
from ultralytics.utils.checks import check_requirements
check_requirements("lap>=0.5.12") # https://github.com/gatagat/lap
import lap
def linear_assignment(cost_matrix: np.ndarray, thresh: float, use_lap: bool = True):
if cost_matrix.size == 0:
return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))
if use_lap:
# Use lap.lapjv
# https://github.com/gatagat/lap
_, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh)
matches = [[ix, mx] for ix, mx in enumerate(x) if mx >= 0]
unmatched_a = np.where(x < 0)[0]
unmatched_b = np.where(y < 0)[0]
else:
# Use scipy.optimize.linear_sum_assignment
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html
x, y = scipy.optimize.linear_sum_assignment(cost_matrix) # row x, col y
matches = np.asarray([[x[i], y[i]] for i in range(len(x)) if cost_matrix[x[i], y[i]] <= thresh])
if len(matches) == 0:
unmatched_a = list(np.arange(cost_matrix.shape[0]))
unmatched_b = list(np.arange(cost_matrix.shape[1]))
else:
unmatched_a = list(frozenset(np.arange(cost_matrix.shape[0])) - frozenset(matches[:, 0]))
unmatched_b = list(frozenset(np.arange(cost_matrix.shape[1])) - frozenset(matches[:, 1]))
return matches, unmatched_a, unmatched_b
def iou_distance(atracks: list, btracks: list) -> np.ndarray:
if (atracks and isinstance(atracks[0], np.ndarray)) or (btracks and isinstance(btracks[0], np.ndarray)):
atlbrs = atracks
btlbrs = btracks
else:
atlbrs = [track.xywha if track.angle is not None else track.xyxy for track in atracks]
btlbrs = [track.xywha if track.angle is not None else track.xyxy for track in btracks]
ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float32)
if len(atlbrs) and len(btlbrs):
if len(atlbrs[0]) == 5 and len(btlbrs[0]) == 5:
ious = batch_probiou(
np.ascontiguousarray(atlbrs, dtype=np.float32),
np.ascontiguousarray(btlbrs, dtype=np.float32),
).numpy()
else:
ious = bbox_ioa(
np.ascontiguousarray(atlbrs, dtype=np.float32),
np.ascontiguousarray(btlbrs, dtype=np.float32),
iou=True,
)
return 1 - ious # cost matrix
def embedding_distance(tracks: list, detections: list, metric: str = "cosine") -> np.ndarray:
cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float32)
if cost_matrix.size == 0:
return cost_matrix
det_features = np.asarray([track.curr_feat for track in detections], dtype=np.float32)
# for i, track in enumerate(tracks):
# cost_matrix[i, :] = np.maximum(0.0, cdist(track.smooth_feat.reshape(1,-1), det_features, metric))
track_features = np.asarray([track.smooth_feat for track in tracks], dtype=np.float32)
cost_matrix = np.maximum(0.0, cdist(track_features, det_features, metric)) # Normalized features
return cost_matrix
def fuse_score(cost_matrix: np.ndarray, detections: list) -> np.ndarray:
if cost_matrix.size == 0:
return cost_matrix
iou_sim = 1 - cost_matrix
det_scores = np.array([det.score for det in detections])
det_scores = det_scores[None].repeat(cost_matrix.shape[0], axis=0)
fuse_sim = iou_sim * det_scores
return 1 - fuse_sim # fuse_cost | --- +++ @@ -18,6 +18,24 @@
def linear_assignment(cost_matrix: np.ndarray, thresh: float, use_lap: bool = True):
+ """Perform linear assignment using either the scipy or lap.lapjv method.
+
+ Args:
+ cost_matrix (np.ndarray): The matrix containing cost values for assignments, with shape (N, M).
+ thresh (float): Threshold for considering an assignment valid.
+ use_lap (bool): Use lap.lapjv for the assignment. If False, scipy.optimize.linear_sum_assignment is used.
+
+ Returns:
+ matched_indices (list[list[int]] | np.ndarray): Matched indices of shape (K, 2), where K is the number of
+ matches.
+ unmatched_a (tuple | list | np.ndarray): Unmatched indices from the first set.
+ unmatched_b (tuple | list | np.ndarray): Unmatched indices from the second set.
+
+ Examples:
+ >>> cost_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ >>> thresh = 5.0
+ >>> matched_indices, unmatched_a, unmatched_b = linear_assignment(cost_matrix, thresh, use_lap=True)
+ """
if cost_matrix.size == 0:
return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))
@@ -44,6 +62,21 @@
def iou_distance(atracks: list, btracks: list) -> np.ndarray:
+ """Compute cost based on Intersection over Union (IoU) between tracks.
+
+ Args:
+ atracks (list[STrack] | list[np.ndarray]): List of tracks 'a' or bounding boxes.
+ btracks (list[STrack] | list[np.ndarray]): List of tracks 'b' or bounding boxes.
+
+ Returns:
+ (np.ndarray): Cost matrix computed based on IoU with shape (len(atracks), len(btracks)).
+
+ Examples:
+ Compute IoU distance between two sets of tracks
+ >>> atracks = [np.array([0, 0, 10, 10]), np.array([20, 20, 30, 30])]
+ >>> btracks = [np.array([5, 5, 15, 15]), np.array([25, 25, 35, 35])]
+ >>> cost_matrix = iou_distance(atracks, btracks)
+ """
if (atracks and isinstance(atracks[0], np.ndarray)) or (btracks and isinstance(btracks[0], np.ndarray)):
atlbrs = atracks
btlbrs = btracks
@@ -68,6 +101,23 @@
def embedding_distance(tracks: list, detections: list, metric: str = "cosine") -> np.ndarray:
+ """Compute distance between tracks and detections based on embeddings.
+
+ Args:
+ tracks (list[BOTrack]): List of tracks, where each track contains embedding features.
+ detections (list[BOTrack]): List of detections, where each detection contains embedding features.
+ metric (str): Metric for distance computation. Supported metrics include 'cosine', 'euclidean', etc.
+
+ Returns:
+ (np.ndarray): Cost matrix computed based on embeddings with shape (N, M), where N is the number of tracks and M
+ is the number of detections.
+
+ Examples:
+ Compute the embedding distance between tracks and detections using cosine metric
+ >>> tracks = [BOTrack(...), BOTrack(...)] # List of track objects with embedding features
+ >>> detections = [BOTrack(...), BOTrack(...)] # List of detection objects with embedding features
+ >>> cost_matrix = embedding_distance(tracks, detections, metric="cosine")
+ """
cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float32)
if cost_matrix.size == 0:
return cost_matrix
@@ -80,10 +130,25 @@
def fuse_score(cost_matrix: np.ndarray, detections: list) -> np.ndarray:
+ """Fuse cost matrix with detection scores to produce a single cost matrix.
+
+ Args:
+ cost_matrix (np.ndarray): The matrix containing cost values for assignments, with shape (N, M).
+ detections (list[BaseTrack]): List of detections, each containing a score attribute.
+
+ Returns:
+ (np.ndarray): Fused cost matrix with shape (N, M).
+
+ Examples:
+ Fuse a cost matrix with detection scores
+ >>> cost_matrix = np.random.rand(5, 10) # 5 tracks and 10 detections
+ >>> detections = [BaseTrack(score=np.random.rand()) for _ in range(10)]
+ >>> fused_matrix = fuse_score(cost_matrix, detections)
+ """
if cost_matrix.size == 0:
return cost_matrix
iou_sim = 1 - cost_matrix
det_scores = np.array([det.score for det in detections])
det_scores = det_scores[None].repeat(cost_matrix.shape[0], axis=0)
fuse_sim = iou_sim * det_scores
- return 1 - fuse_sim # fuse_cost+ return 1 - fuse_sim # fuse_cost
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/trackers/utils/matching.py |
Write proper docstrings for these functions | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import math
import numpy as np
import torch
import torch.nn as nn
__all__ = (
"CBAM",
"ChannelAttention",
"Concat",
"Conv",
"Conv2",
"ConvTranspose",
"DWConv",
"DWConvTranspose2d",
"Focus",
"GhostConv",
"Index",
"LightConv",
"RepConv",
"SpatialAttention",
)
def autopad(k, p=None, d=1): # kernel, padding, dilation
if d > 1:
k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
if p is None:
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
return p
class Conv(nn.Module):
default_act = nn.SiLU() # default activation
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
super().__init__()
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
self.bn = nn.BatchNorm2d(c2)
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
def forward(self, x):
return self.act(self.bn(self.conv(x)))
def forward_fuse(self, x):
return self.act(self.conv(x))
class Conv2(Conv):
def __init__(self, c1, c2, k=3, s=1, p=None, g=1, d=1, act=True):
super().__init__(c1, c2, k, s, p, g=g, d=d, act=act)
self.cv2 = nn.Conv2d(c1, c2, 1, s, autopad(1, p, d), groups=g, dilation=d, bias=False) # add 1x1 conv
def forward(self, x):
return self.act(self.bn(self.conv(x) + self.cv2(x)))
def forward_fuse(self, x):
return self.act(self.bn(self.conv(x)))
def fuse_convs(self):
w = torch.zeros_like(self.conv.weight.data)
i = [x // 2 for x in w.shape[2:]]
w[:, :, i[0] : i[0] + 1, i[1] : i[1] + 1] = self.cv2.weight.data.clone()
self.conv.weight.data += w
self.__delattr__("cv2")
self.forward = self.forward_fuse
class LightConv(nn.Module):
def __init__(self, c1, c2, k=1, act=nn.ReLU()):
super().__init__()
self.conv1 = Conv(c1, c2, 1, act=False)
self.conv2 = DWConv(c2, c2, k, act=act)
def forward(self, x):
return self.conv2(self.conv1(x))
class DWConv(Conv):
def __init__(self, c1, c2, k=1, s=1, d=1, act=True):
super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)
class DWConvTranspose2d(nn.ConvTranspose2d):
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0):
super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))
class ConvTranspose(nn.Module):
default_act = nn.SiLU() # default activation
def __init__(self, c1, c2, k=2, s=2, p=0, bn=True, act=True):
super().__init__()
self.conv_transpose = nn.ConvTranspose2d(c1, c2, k, s, p, bias=not bn)
self.bn = nn.BatchNorm2d(c2) if bn else nn.Identity()
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
def forward(self, x):
return self.act(self.bn(self.conv_transpose(x)))
def forward_fuse(self, x):
return self.act(self.conv_transpose(x))
class Focus(nn.Module):
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):
super().__init__()
self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act)
# self.contract = Contract(gain=2)
def forward(self, x):
return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))
# return self.conv(self.contract(x))
class GhostConv(nn.Module):
def __init__(self, c1, c2, k=1, s=1, g=1, act=True):
super().__init__()
c_ = c2 // 2 # hidden channels
self.cv1 = Conv(c1, c_, k, s, None, g, act=act)
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)
def forward(self, x):
y = self.cv1(x)
return torch.cat((y, self.cv2(y)), 1)
class RepConv(nn.Module):
default_act = nn.SiLU() # default activation
def __init__(self, c1, c2, k=3, s=1, p=1, g=1, d=1, act=True, bn=False, deploy=False):
super().__init__()
assert k == 3 and p == 1
self.g = g
self.c1 = c1
self.c2 = c2
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
self.bn = nn.BatchNorm2d(num_features=c1) if bn and c2 == c1 and s == 1 else None
self.conv1 = Conv(c1, c2, k, s, p=p, g=g, act=False)
self.conv2 = Conv(c1, c2, 1, s, p=(p - k // 2), g=g, act=False)
def forward_fuse(self, x):
return self.act(self.conv(x))
def forward(self, x):
id_out = 0 if self.bn is None else self.bn(x)
return self.act(self.conv1(x) + self.conv2(x) + id_out)
def get_equivalent_kernel_bias(self):
kernel3x3, bias3x3 = self._fuse_bn_tensor(self.conv1)
kernel1x1, bias1x1 = self._fuse_bn_tensor(self.conv2)
kernelid, biasid = self._fuse_bn_tensor(self.bn)
return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid
@staticmethod
def _pad_1x1_to_3x3_tensor(kernel1x1):
if kernel1x1 is None:
return 0
else:
return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])
def _fuse_bn_tensor(self, branch):
if branch is None:
return 0, 0
if isinstance(branch, Conv):
kernel = branch.conv.weight
running_mean = branch.bn.running_mean
running_var = branch.bn.running_var
gamma = branch.bn.weight
beta = branch.bn.bias
eps = branch.bn.eps
elif isinstance(branch, nn.BatchNorm2d):
if not hasattr(self, "id_tensor"):
input_dim = self.c1 // self.g
kernel_value = np.zeros((self.c1, input_dim, 3, 3), dtype=np.float32)
for i in range(self.c1):
kernel_value[i, i % input_dim, 1, 1] = 1
self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
kernel = self.id_tensor
running_mean = branch.running_mean
running_var = branch.running_var
gamma = branch.weight
beta = branch.bias
eps = branch.eps
std = (running_var + eps).sqrt()
t = (gamma / std).reshape(-1, 1, 1, 1)
return kernel * t, beta - running_mean * gamma / std
def fuse_convs(self):
if hasattr(self, "conv"):
return
kernel, bias = self.get_equivalent_kernel_bias()
self.conv = nn.Conv2d(
in_channels=self.conv1.conv.in_channels,
out_channels=self.conv1.conv.out_channels,
kernel_size=self.conv1.conv.kernel_size,
stride=self.conv1.conv.stride,
padding=self.conv1.conv.padding,
dilation=self.conv1.conv.dilation,
groups=self.conv1.conv.groups,
bias=True,
).requires_grad_(False)
self.conv.weight.data = kernel
self.conv.bias.data = bias
for para in self.parameters():
para.detach_()
self.__delattr__("conv1")
self.__delattr__("conv2")
if hasattr(self, "nm"):
self.__delattr__("nm")
if hasattr(self, "bn"):
self.__delattr__("bn")
if hasattr(self, "id_tensor"):
self.__delattr__("id_tensor")
class ChannelAttention(nn.Module):
def __init__(self, channels: int) -> None:
super().__init__()
self.pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Conv2d(channels, channels, 1, 1, 0, bias=True)
self.act = nn.Sigmoid()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * self.act(self.fc(self.pool(x)))
class SpatialAttention(nn.Module):
def __init__(self, kernel_size=7):
super().__init__()
assert kernel_size in {3, 7}, "kernel size must be 3 or 7"
padding = 3 if kernel_size == 7 else 1
self.cv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)
self.act = nn.Sigmoid()
def forward(self, x):
return x * self.act(self.cv1(torch.cat([torch.mean(x, 1, keepdim=True), torch.max(x, 1, keepdim=True)[0]], 1)))
class CBAM(nn.Module):
def __init__(self, c1, kernel_size=7):
super().__init__()
self.channel_attention = ChannelAttention(c1)
self.spatial_attention = SpatialAttention(kernel_size)
def forward(self, x):
return self.spatial_attention(self.channel_attention(x))
class Concat(nn.Module):
def __init__(self, dimension=1):
super().__init__()
self.d = dimension
def forward(self, x: list[torch.Tensor]):
return torch.cat(x, self.d)
class Index(nn.Module):
def __init__(self, index=0):
super().__init__()
self.index = index
def forward(self, x: list[torch.Tensor]):
return x[self.index] | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Convolution modules."""
from __future__ import annotations
@@ -27,6 +28,7 @@
def autopad(k, p=None, d=1): # kernel, padding, dilation
+ """Pad to 'same' shape outputs."""
if d > 1:
k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
if p is None:
@@ -35,35 +37,108 @@
class Conv(nn.Module):
+ """Standard convolution module with batch normalization and activation.
+
+ Attributes:
+ conv (nn.Conv2d): Convolutional layer.
+ bn (nn.BatchNorm2d): Batch normalization layer.
+ act (nn.Module): Activation function layer.
+ default_act (nn.Module): Default activation function (SiLU).
+ """
default_act = nn.SiLU() # default activation
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
+ """Initialize Conv layer with given parameters.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ k (int): Kernel size.
+ s (int): Stride.
+ p (int, optional): Padding.
+ g (int): Groups.
+ d (int): Dilation.
+ act (bool | nn.Module): Activation function.
+ """
super().__init__()
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
self.bn = nn.BatchNorm2d(c2)
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
def forward(self, x):
+ """Apply convolution, batch normalization and activation to input tensor.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor.
+ """
return self.act(self.bn(self.conv(x)))
def forward_fuse(self, x):
+ """Apply convolution and activation without batch normalization.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor.
+ """
return self.act(self.conv(x))
class Conv2(Conv):
+ """Simplified RepConv module with Conv fusing.
+
+ Attributes:
+ conv (nn.Conv2d): Main 3x3 convolutional layer.
+ cv2 (nn.Conv2d): Additional 1x1 convolutional layer.
+ bn (nn.BatchNorm2d): Batch normalization layer.
+ act (nn.Module): Activation function layer.
+ """
def __init__(self, c1, c2, k=3, s=1, p=None, g=1, d=1, act=True):
+ """Initialize Conv2 layer with given parameters.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ k (int): Kernel size.
+ s (int): Stride.
+ p (int, optional): Padding.
+ g (int): Groups.
+ d (int): Dilation.
+ act (bool | nn.Module): Activation function.
+ """
super().__init__(c1, c2, k, s, p, g=g, d=d, act=act)
self.cv2 = nn.Conv2d(c1, c2, 1, s, autopad(1, p, d), groups=g, dilation=d, bias=False) # add 1x1 conv
def forward(self, x):
+ """Apply convolution, batch normalization and activation to input tensor.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor.
+ """
return self.act(self.bn(self.conv(x) + self.cv2(x)))
def forward_fuse(self, x):
+ """Apply fused convolution, batch normalization and activation to input tensor.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor.
+ """
return self.act(self.bn(self.conv(x)))
def fuse_convs(self):
+ """Fuse parallel convolutions."""
w = torch.zeros_like(self.conv.weight.data)
i = [x // 2 for x in w.shape[2:]]
w[:, :, i[0] : i[0] + 1, i[1] : i[1] + 1] = self.cv2.weight.data.clone()
@@ -73,75 +148,241 @@
class LightConv(nn.Module):
+ """Light convolution module with 1x1 and depthwise convolutions.
+
+ This implementation is based on the PaddleDetection HGNetV2 backbone.
+
+ Attributes:
+ conv1 (Conv): 1x1 convolution layer.
+ conv2 (DWConv): Depthwise convolution layer.
+ """
def __init__(self, c1, c2, k=1, act=nn.ReLU()):
+ """Initialize LightConv layer with given parameters.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ k (int): Kernel size for depthwise convolution.
+ act (nn.Module): Activation function.
+ """
super().__init__()
self.conv1 = Conv(c1, c2, 1, act=False)
self.conv2 = DWConv(c2, c2, k, act=act)
def forward(self, x):
+ """Apply 2 convolutions to input tensor.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor.
+ """
return self.conv2(self.conv1(x))
class DWConv(Conv):
+ """Depth-wise convolution module."""
def __init__(self, c1, c2, k=1, s=1, d=1, act=True):
+ """Initialize depth-wise convolution with given parameters.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ k (int): Kernel size.
+ s (int): Stride.
+ d (int): Dilation.
+ act (bool | nn.Module): Activation function.
+ """
super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)
class DWConvTranspose2d(nn.ConvTranspose2d):
+ """Depth-wise transpose convolution module."""
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0):
+ """Initialize depth-wise transpose convolution with given parameters.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ k (int): Kernel size.
+ s (int): Stride.
+ p1 (int): Padding.
+ p2 (int): Output padding.
+ """
super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))
class ConvTranspose(nn.Module):
+ """Convolution transpose module with optional batch normalization and activation.
+
+ Attributes:
+ conv_transpose (nn.ConvTranspose2d): Transposed convolution layer.
+ bn (nn.BatchNorm2d | nn.Identity): Batch normalization layer.
+ act (nn.Module): Activation function layer.
+ default_act (nn.Module): Default activation function (SiLU).
+ """
default_act = nn.SiLU() # default activation
def __init__(self, c1, c2, k=2, s=2, p=0, bn=True, act=True):
+ """Initialize ConvTranspose layer with given parameters.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ k (int): Kernel size.
+ s (int): Stride.
+ p (int): Padding.
+ bn (bool): Use batch normalization.
+ act (bool | nn.Module): Activation function.
+ """
super().__init__()
self.conv_transpose = nn.ConvTranspose2d(c1, c2, k, s, p, bias=not bn)
self.bn = nn.BatchNorm2d(c2) if bn else nn.Identity()
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
def forward(self, x):
+ """Apply transposed convolution, batch normalization and activation to input.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor.
+ """
return self.act(self.bn(self.conv_transpose(x)))
def forward_fuse(self, x):
+ """Apply convolution transpose and activation to input.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor.
+ """
return self.act(self.conv_transpose(x))
class Focus(nn.Module):
+ """Focus module for concentrating feature information.
+
+ Slices input tensor into 4 parts and concatenates them in the channel dimension.
+
+ Attributes:
+ conv (Conv): Convolution layer.
+ """
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):
+ """Initialize Focus module with given parameters.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ k (int): Kernel size.
+ s (int): Stride.
+ p (int, optional): Padding.
+ g (int): Groups.
+ act (bool | nn.Module): Activation function.
+ """
super().__init__()
self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act)
# self.contract = Contract(gain=2)
def forward(self, x):
+ """Apply Focus operation and convolution to input tensor.
+
+ Input shape is (B, C, H, W) and output shape is (B, c2, H/2, W/2).
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor.
+ """
return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))
# return self.conv(self.contract(x))
class GhostConv(nn.Module):
+ """Ghost Convolution module.
+
+ Generates more features with fewer parameters by using cheap operations.
+
+ Attributes:
+ cv1 (Conv): Primary convolution.
+ cv2 (Conv): Cheap operation convolution.
+
+ References:
+ https://github.com/huawei-noah/Efficient-AI-Backbones
+ """
def __init__(self, c1, c2, k=1, s=1, g=1, act=True):
+ """Initialize Ghost Convolution module with given parameters.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ k (int): Kernel size.
+ s (int): Stride.
+ g (int): Groups.
+ act (bool | nn.Module): Activation function.
+ """
super().__init__()
c_ = c2 // 2 # hidden channels
self.cv1 = Conv(c1, c_, k, s, None, g, act=act)
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)
def forward(self, x):
+ """Apply Ghost Convolution to input tensor.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor with concatenated features.
+ """
y = self.cv1(x)
return torch.cat((y, self.cv2(y)), 1)
class RepConv(nn.Module):
+ """RepConv module with training and deploy modes.
+
+ This module is used in RT-DETR and can fuse convolutions during inference for efficiency.
+
+ Attributes:
+ conv1 (Conv): 3x3 convolution.
+ conv2 (Conv): 1x1 convolution.
+ bn (nn.BatchNorm2d, optional): Batch normalization for identity branch.
+ act (nn.Module): Activation function.
+ default_act (nn.Module): Default activation function (SiLU).
+
+ References:
+ https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py
+ """
default_act = nn.SiLU() # default activation
def __init__(self, c1, c2, k=3, s=1, p=1, g=1, d=1, act=True, bn=False, deploy=False):
+ """Initialize RepConv module with given parameters.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ k (int): Kernel size.
+ s (int): Stride.
+ p (int): Padding.
+ g (int): Groups.
+ d (int): Dilation.
+ act (bool | nn.Module): Activation function.
+ bn (bool): Use batch normalization for identity branch.
+ deploy (bool): Deploy mode for inference.
+ """
super().__init__()
assert k == 3 and p == 1
self.g = g
@@ -154,13 +395,35 @@ self.conv2 = Conv(c1, c2, 1, s, p=(p - k // 2), g=g, act=False)
def forward_fuse(self, x):
+ """Forward pass for deploy mode.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor.
+ """
return self.act(self.conv(x))
def forward(self, x):
+ """Forward pass for training mode.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor.
+ """
id_out = 0 if self.bn is None else self.bn(x)
return self.act(self.conv1(x) + self.conv2(x) + id_out)
def get_equivalent_kernel_bias(self):
+ """Calculate equivalent kernel and bias by fusing convolutions.
+
+ Returns:
+ (torch.Tensor): Equivalent kernel
+ (torch.Tensor): Equivalent bias
+ """
kernel3x3, bias3x3 = self._fuse_bn_tensor(self.conv1)
kernel1x1, bias1x1 = self._fuse_bn_tensor(self.conv2)
kernelid, biasid = self._fuse_bn_tensor(self.bn)
@@ -168,12 +431,29 @@
@staticmethod
def _pad_1x1_to_3x3_tensor(kernel1x1):
+ """Pad a 1x1 kernel to 3x3 size.
+
+ Args:
+ kernel1x1 (torch.Tensor): 1x1 convolution kernel.
+
+ Returns:
+ (torch.Tensor): Padded 3x3 kernel.
+ """
if kernel1x1 is None:
return 0
else:
return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])
def _fuse_bn_tensor(self, branch):
+ """Fuse batch normalization with convolution weights.
+
+ Args:
+ branch (Conv | nn.BatchNorm2d | None): Branch to fuse.
+
+ Returns:
+ kernel (torch.Tensor): Fused kernel.
+ bias (torch.Tensor): Fused bias.
+ """
if branch is None:
return 0, 0
if isinstance(branch, Conv):
@@ -201,6 +481,7 @@ return kernel * t, beta - running_mean * gamma / std
def fuse_convs(self):
+ """Fuse convolutions for inference by creating a single equivalent convolution."""
if hasattr(self, "conv"):
return
kernel, bias = self.get_equivalent_kernel_bias()
@@ -229,20 +510,58 @@
class ChannelAttention(nn.Module):
+ """Channel-attention module for feature recalibration.
+
+ Applies attention weights to channels based on global average pooling.
+
+ Attributes:
+ pool (nn.AdaptiveAvgPool2d): Global average pooling.
+ fc (nn.Conv2d): Fully connected layer implemented as 1x1 convolution.
+ act (nn.Sigmoid): Sigmoid activation for attention weights.
+
+ References:
+ https://github.com/open-mmlab/mmdetection/tree/v3.0.0rc1/configs/rtmdet
+ """
def __init__(self, channels: int) -> None:
+ """Initialize Channel-attention module.
+
+ Args:
+ channels (int): Number of input channels.
+ """
super().__init__()
self.pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Conv2d(channels, channels, 1, 1, 0, bias=True)
self.act = nn.Sigmoid()
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply channel attention to input tensor.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Channel-attended output tensor.
+ """
return x * self.act(self.fc(self.pool(x)))
class SpatialAttention(nn.Module):
+ """Spatial-attention module for feature recalibration.
+
+ Applies attention weights to spatial dimensions based on channel statistics.
+
+ Attributes:
+ cv1 (nn.Conv2d): Convolution layer for spatial attention.
+ act (nn.Sigmoid): Sigmoid activation for attention weights.
+ """
def __init__(self, kernel_size=7):
+ """Initialize Spatial-attention module.
+
+ Args:
+ kernel_size (int): Size of the convolutional kernel (3 or 7).
+ """
super().__init__()
assert kernel_size in {3, 7}, "kernel size must be 3 or 7"
padding = 3 if kernel_size == 7 else 1
@@ -250,35 +569,101 @@ self.act = nn.Sigmoid()
def forward(self, x):
+ """Apply spatial attention to input tensor.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Spatial-attended output tensor.
+ """
return x * self.act(self.cv1(torch.cat([torch.mean(x, 1, keepdim=True), torch.max(x, 1, keepdim=True)[0]], 1)))
class CBAM(nn.Module):
+ """Convolutional Block Attention Module.
+
+ Combines channel and spatial attention mechanisms for comprehensive feature refinement.
+
+ Attributes:
+ channel_attention (ChannelAttention): Channel attention module.
+ spatial_attention (SpatialAttention): Spatial attention module.
+ """
def __init__(self, c1, kernel_size=7):
+ """Initialize CBAM with given parameters.
+
+ Args:
+ c1 (int): Number of input channels.
+ kernel_size (int): Size of the convolutional kernel for spatial attention.
+ """
super().__init__()
self.channel_attention = ChannelAttention(c1)
self.spatial_attention = SpatialAttention(kernel_size)
def forward(self, x):
+ """Apply channel and spatial attention sequentially to input tensor.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Attended output tensor.
+ """
return self.spatial_attention(self.channel_attention(x))
class Concat(nn.Module):
+ """Concatenate a list of tensors along specified dimension.
+
+ Attributes:
+ d (int): Dimension along which to concatenate tensors.
+ """
def __init__(self, dimension=1):
+ """Initialize Concat module.
+
+ Args:
+ dimension (int): Dimension along which to concatenate tensors.
+ """
super().__init__()
self.d = dimension
def forward(self, x: list[torch.Tensor]):
+ """Concatenate input tensors along specified dimension.
+
+ Args:
+ x (list[torch.Tensor]): List of input tensors.
+
+ Returns:
+ (torch.Tensor): Concatenated tensor.
+ """
return torch.cat(x, self.d)
class Index(nn.Module):
+ """Returns a particular index of the input.
+
+ Attributes:
+ index (int): Index to select from input.
+ """
def __init__(self, index=0):
+ """Initialize Index module.
+
+ Args:
+ index (int): Index to select from input.
+ """
super().__init__()
self.index = index
def forward(self, x: list[torch.Tensor]):
- return x[self.index]+ """Select and return a particular index from input.
+
+ Args:
+ x (list[torch.Tensor]): List of input tensors.
+
+ Returns:
+ (torch.Tensor): Selected tensor.
+ """
+ return x[self.index]
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/modules/conv.py |
Add structured docstrings to improve clarity | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from typing import Any
import numpy as np
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
from ultralytics.utils.plotting import colors
class RegionCounter(BaseSolution):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.region_template = {
"name": "Default Region",
"polygon": None,
"counts": 0,
"region_color": (255, 255, 255),
"text_color": (0, 0, 0),
}
self.region_counts = {}
self.counting_regions = []
self.initialize_regions()
def add_region(
self,
name: str,
polygon_points: list[tuple],
region_color: tuple[int, int, int],
text_color: tuple[int, int, int],
) -> dict[str, Any]:
region = self.region_template.copy()
region.update(
{
"name": name,
"polygon": self.Polygon(polygon_points),
"region_color": region_color,
"text_color": text_color,
}
)
self.counting_regions.append(region)
return region
def initialize_regions(self):
if self.region is None:
self.initialize_region()
if not isinstance(self.region, dict): # Ensure self.region is initialized and structured as a dictionary
self.region = {"Region#01": self.region}
for i, (name, pts) in enumerate(self.region.items()):
region = self.add_region(name, pts, colors(i, True), (255, 255, 255))
region["prepared_polygon"] = self.prep(region["polygon"])
def process(self, im0: np.ndarray) -> SolutionResults:
self.extract_tracks(im0)
annotator = SolutionAnnotator(im0, line_width=self.line_width)
for box, cls, track_id, conf in zip(self.boxes, self.clss, self.track_ids, self.confs):
annotator.box_label(box, label=self.adjust_box_label(cls, conf, track_id), color=colors(track_id, True))
center = self.Point(((box[0] + box[2]) / 2, (box[1] + box[3]) / 2))
for region in self.counting_regions:
if region["prepared_polygon"].contains(center):
region["counts"] += 1
self.region_counts[region["name"]] = region["counts"]
# Display region counts
for region in self.counting_regions:
poly = region["polygon"]
pts = list(map(tuple, np.array(poly.exterior.coords, dtype=np.int32)))
(x1, y1), (x2, y2) = [(int(poly.centroid.x), int(poly.centroid.y))] * 2
annotator.draw_region(pts, region["region_color"], self.line_width * 2)
annotator.adaptive_label(
[x1, y1, x2, y2],
label=str(region["counts"]),
color=region["region_color"],
txt_color=region["text_color"],
margin=self.line_width * 4,
shape="rect",
)
region["counts"] = 0 # Reset for next frame
plot_im = annotator.result()
self.display_output(plot_im)
return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids), region_counts=self.region_counts) | --- +++ @@ -11,8 +11,34 @@
class RegionCounter(BaseSolution):
+ """A class for real-time counting of objects within user-defined regions in a video stream.
+
+ This class inherits from `BaseSolution` and provides functionality to define polygonal regions in a video frame,
+ track objects, and count those objects that pass through each defined region. Useful for applications requiring
+ counting in specified areas, such as monitoring zones or segmented sections.
+
+ Attributes:
+ region_template (dict): Template for creating new counting regions with default attributes including name,
+ polygon coordinates, and display colors.
+ counting_regions (list): List storing all defined regions, where each entry is based on `region_template` and
+ includes specific region settings like name, coordinates, and color.
+ region_counts (dict): Dictionary storing the count of objects for each named region.
+
+ Methods:
+ add_region: Add a new counting region with specified attributes.
+ process: Process video frames to count objects in each region.
+ initialize_regions: Initialize zones to count the objects in each one. Zones could be multiple as well.
+
+ Examples:
+ Initialize a RegionCounter and add a counting region
+ >>> counter = RegionCounter()
+ >>> counter.add_region("Zone1", [(100, 100), (200, 100), (200, 200), (100, 200)], (255, 0, 0), (255, 255, 255))
+ >>> results = counter.process(frame)
+ >>> print(f"Total tracks: {results.total_tracks}")
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the RegionCounter for real-time object counting in user-defined regions."""
super().__init__(**kwargs)
self.region_template = {
"name": "Default Region",
@@ -32,6 +58,17 @@ region_color: tuple[int, int, int],
text_color: tuple[int, int, int],
) -> dict[str, Any]:
+ """Add a new region to the counting list based on the provided template with specific attributes.
+
+ Args:
+ name (str): Name assigned to the new region.
+ polygon_points (list[tuple]): List of (x, y) coordinates defining the region's polygon.
+ region_color (tuple[int, int, int]): BGR color for region visualization.
+ text_color (tuple[int, int, int]): BGR color for the text within the region.
+
+ Returns:
+ (dict[str, Any]): Region information including name, polygon, and display colors.
+ """
region = self.region_template.copy()
region.update(
{
@@ -45,6 +82,7 @@ return region
def initialize_regions(self):
+ """Initialize regions from `self.region` only once."""
if self.region is None:
self.initialize_region()
if not isinstance(self.region, dict): # Ensure self.region is initialized and structured as a dictionary
@@ -54,6 +92,15 @@ region["prepared_polygon"] = self.prep(region["polygon"])
def process(self, im0: np.ndarray) -> SolutionResults:
+ """Process the input frame to detect and count objects within each defined region.
+
+ Args:
+ im0 (np.ndarray): Input image frame where objects and regions are annotated.
+
+ Returns:
+ (SolutionResults): Contains processed image `plot_im`, 'total_tracks' (int, total number of tracked
+ objects), and 'region_counts' (dict, counts of objects per region).
+ """
self.extract_tracks(im0)
annotator = SolutionAnnotator(im0, line_width=self.line_width)
@@ -83,4 +130,4 @@ plot_im = annotator.result()
self.display_output(plot_im)
- return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids), region_counts=self.region_counts)+ return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids), region_counts=self.region_counts)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/region_counter.py |
Auto-generate documentation strings for this file | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import numpy as np
import scipy.linalg
class KalmanFilterXYAH:
def __init__(self):
ndim, dt = 4, 1.0
# Create Kalman filter model matrices
self._motion_mat = np.eye(2 * ndim, 2 * ndim)
for i in range(ndim):
self._motion_mat[i, ndim + i] = dt
self._update_mat = np.eye(ndim, 2 * ndim)
# Motion and observation uncertainty are chosen relative to the current state estimate
self._std_weight_position = 1.0 / 20
self._std_weight_velocity = 1.0 / 160
def initiate(self, measurement: np.ndarray):
mean_pos = measurement
mean_vel = np.zeros_like(mean_pos)
mean = np.r_[mean_pos, mean_vel]
std = [
2 * self._std_weight_position * measurement[3],
2 * self._std_weight_position * measurement[3],
1e-2,
2 * self._std_weight_position * measurement[3],
10 * self._std_weight_velocity * measurement[3],
10 * self._std_weight_velocity * measurement[3],
1e-5,
10 * self._std_weight_velocity * measurement[3],
]
covariance = np.diag(np.square(std))
return mean, covariance
def predict(self, mean: np.ndarray, covariance: np.ndarray):
std_pos = [
self._std_weight_position * mean[3],
self._std_weight_position * mean[3],
1e-2,
self._std_weight_position * mean[3],
]
std_vel = [
self._std_weight_velocity * mean[3],
self._std_weight_velocity * mean[3],
1e-5,
self._std_weight_velocity * mean[3],
]
motion_cov = np.diag(np.square(np.r_[std_pos, std_vel]))
mean = np.dot(mean, self._motion_mat.T)
covariance = np.linalg.multi_dot((self._motion_mat, covariance, self._motion_mat.T)) + motion_cov
return mean, covariance
def project(self, mean: np.ndarray, covariance: np.ndarray):
std = [
self._std_weight_position * mean[3],
self._std_weight_position * mean[3],
1e-1,
self._std_weight_position * mean[3],
]
innovation_cov = np.diag(np.square(std))
mean = np.dot(self._update_mat, mean)
covariance = np.linalg.multi_dot((self._update_mat, covariance, self._update_mat.T))
return mean, covariance + innovation_cov
def multi_predict(self, mean: np.ndarray, covariance: np.ndarray):
std_pos = [
self._std_weight_position * mean[:, 3],
self._std_weight_position * mean[:, 3],
1e-2 * np.ones_like(mean[:, 3]),
self._std_weight_position * mean[:, 3],
]
std_vel = [
self._std_weight_velocity * mean[:, 3],
self._std_weight_velocity * mean[:, 3],
1e-5 * np.ones_like(mean[:, 3]),
self._std_weight_velocity * mean[:, 3],
]
sqr = np.square(np.r_[std_pos, std_vel]).T
motion_cov = [np.diag(sqr[i]) for i in range(len(mean))]
motion_cov = np.asarray(motion_cov)
mean = np.dot(mean, self._motion_mat.T)
left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2))
covariance = np.dot(left, self._motion_mat.T) + motion_cov
return mean, covariance
def update(self, mean: np.ndarray, covariance: np.ndarray, measurement: np.ndarray):
projected_mean, projected_cov = self.project(mean, covariance)
chol_factor, lower = scipy.linalg.cho_factor(projected_cov, lower=True, check_finite=False)
kalman_gain = scipy.linalg.cho_solve(
(chol_factor, lower), np.dot(covariance, self._update_mat.T).T, check_finite=False
).T
innovation = measurement - projected_mean
new_mean = mean + np.dot(innovation, kalman_gain.T)
new_covariance = covariance - np.linalg.multi_dot((kalman_gain, projected_cov, kalman_gain.T))
return new_mean, new_covariance
def gating_distance(
self,
mean: np.ndarray,
covariance: np.ndarray,
measurements: np.ndarray,
only_position: bool = False,
metric: str = "maha",
) -> np.ndarray:
mean, covariance = self.project(mean, covariance)
if only_position:
mean, covariance = mean[:2], covariance[:2, :2]
measurements = measurements[:, :2]
d = measurements - mean
if metric == "gaussian":
return np.sum(d * d, axis=1)
elif metric == "maha":
cholesky_factor = np.linalg.cholesky(covariance)
z = scipy.linalg.solve_triangular(cholesky_factor, d.T, lower=True, check_finite=False, overwrite_b=True)
return np.sum(z * z, axis=0) # square maha
else:
raise ValueError("Invalid distance metric")
class KalmanFilterXYWH(KalmanFilterXYAH):
def initiate(self, measurement: np.ndarray):
mean_pos = measurement
mean_vel = np.zeros_like(mean_pos)
mean = np.r_[mean_pos, mean_vel]
std = [
2 * self._std_weight_position * measurement[2],
2 * self._std_weight_position * measurement[3],
2 * self._std_weight_position * measurement[2],
2 * self._std_weight_position * measurement[3],
10 * self._std_weight_velocity * measurement[2],
10 * self._std_weight_velocity * measurement[3],
10 * self._std_weight_velocity * measurement[2],
10 * self._std_weight_velocity * measurement[3],
]
covariance = np.diag(np.square(std))
return mean, covariance
def predict(self, mean: np.ndarray, covariance: np.ndarray):
std_pos = [
self._std_weight_position * mean[2],
self._std_weight_position * mean[3],
self._std_weight_position * mean[2],
self._std_weight_position * mean[3],
]
std_vel = [
self._std_weight_velocity * mean[2],
self._std_weight_velocity * mean[3],
self._std_weight_velocity * mean[2],
self._std_weight_velocity * mean[3],
]
motion_cov = np.diag(np.square(np.r_[std_pos, std_vel]))
mean = np.dot(mean, self._motion_mat.T)
covariance = np.linalg.multi_dot((self._motion_mat, covariance, self._motion_mat.T)) + motion_cov
return mean, covariance
def project(self, mean: np.ndarray, covariance: np.ndarray):
std = [
self._std_weight_position * mean[2],
self._std_weight_position * mean[3],
self._std_weight_position * mean[2],
self._std_weight_position * mean[3],
]
innovation_cov = np.diag(np.square(std))
mean = np.dot(self._update_mat, mean)
covariance = np.linalg.multi_dot((self._update_mat, covariance, self._update_mat.T))
return mean, covariance + innovation_cov
def multi_predict(self, mean: np.ndarray, covariance: np.ndarray):
std_pos = [
self._std_weight_position * mean[:, 2],
self._std_weight_position * mean[:, 3],
self._std_weight_position * mean[:, 2],
self._std_weight_position * mean[:, 3],
]
std_vel = [
self._std_weight_velocity * mean[:, 2],
self._std_weight_velocity * mean[:, 3],
self._std_weight_velocity * mean[:, 2],
self._std_weight_velocity * mean[:, 3],
]
sqr = np.square(np.r_[std_pos, std_vel]).T
motion_cov = [np.diag(sqr[i]) for i in range(len(mean))]
motion_cov = np.asarray(motion_cov)
mean = np.dot(mean, self._motion_mat.T)
left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2))
covariance = np.dot(left, self._motion_mat.T) + motion_cov
return mean, covariance
def update(self, mean: np.ndarray, covariance: np.ndarray, measurement: np.ndarray):
return super().update(mean, covariance, measurement) | --- +++ @@ -5,8 +5,44 @@
class KalmanFilterXYAH:
+ """A KalmanFilterXYAH class for tracking bounding boxes in image space using a Kalman filter.
+
+ Implements a simple Kalman filter for tracking bounding boxes in image space. The 8-dimensional state space (x, y,
+ a, h, vx, vy, va, vh) contains the bounding box center position (x, y), aspect ratio a, height h, and their
+ respective velocities. Object motion follows a constant velocity model, and bounding box location (x, y, a, h) is
+ taken as a direct observation of the state space (linear observation model).
+
+ Attributes:
+ _motion_mat (np.ndarray): The motion matrix for the Kalman filter.
+ _update_mat (np.ndarray): The update matrix for the Kalman filter.
+ _std_weight_position (float): Standard deviation weight for position.
+ _std_weight_velocity (float): Standard deviation weight for velocity.
+
+ Methods:
+ initiate: Create a track from an unassociated measurement.
+ predict: Run the Kalman filter prediction step.
+ project: Project the state distribution to measurement space.
+ multi_predict: Run the Kalman filter prediction step (vectorized version).
+ update: Run the Kalman filter correction step.
+ gating_distance: Compute the gating distance between state distribution and measurements.
+
+ Examples:
+ Initialize the Kalman filter and create a track from a measurement
+ >>> kf = KalmanFilterXYAH()
+ >>> measurement = np.array([100, 200, 1.5, 50])
+ >>> mean, covariance = kf.initiate(measurement)
+ >>> print(mean)
+ >>> print(covariance)
+ """
def __init__(self):
+ """Initialize Kalman filter model matrices with motion and observation uncertainty weights.
+
+ The Kalman filter is initialized with an 8-dimensional state space (x, y, a, h, vx, vy, va, vh), where (x, y)
+ represents the bounding box center position, 'a' is the aspect ratio, 'h' is the height, and their respective
+ velocities are (vx, vy, va, vh). The filter uses a constant velocity model for object motion and a linear
+ observation model for bounding box location.
+ """
ndim, dt = 4, 1.0
# Create Kalman filter model matrices
@@ -20,6 +56,21 @@ self._std_weight_velocity = 1.0 / 160
def initiate(self, measurement: np.ndarray):
+ """Create a track from an unassociated measurement.
+
+ Args:
+ measurement (np.ndarray): Bounding box coordinates (x, y, a, h) with center position (x, y), aspect ratio a,
+ and height h.
+
+ Returns:
+ mean (np.ndarray): Mean vector (8-dimensional) of the new track. Unobserved velocities are initialized to 0.
+ covariance (np.ndarray): Covariance matrix (8x8 dimensional) of the new track.
+
+ Examples:
+ >>> kf = KalmanFilterXYAH()
+ >>> measurement = np.array([100, 50, 1.5, 200])
+ >>> mean, covariance = kf.initiate(measurement)
+ """
mean_pos = measurement
mean_vel = np.zeros_like(mean_pos)
mean = np.r_[mean_pos, mean_vel]
@@ -38,6 +89,23 @@ return mean, covariance
def predict(self, mean: np.ndarray, covariance: np.ndarray):
+ """Run Kalman filter prediction step.
+
+ Args:
+ mean (np.ndarray): The 8-dimensional mean vector of the object state at the previous time step.
+ covariance (np.ndarray): The 8x8-dimensional covariance matrix of the object state at the previous time
+ step.
+
+ Returns:
+ mean (np.ndarray): Mean vector of the predicted state.
+ covariance (np.ndarray): Covariance matrix of the predicted state.
+
+ Examples:
+ >>> kf = KalmanFilterXYAH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> predicted_mean, predicted_covariance = kf.predict(mean, covariance)
+ """
std_pos = [
self._std_weight_position * mean[3],
self._std_weight_position * mean[3],
@@ -58,6 +126,22 @@ return mean, covariance
def project(self, mean: np.ndarray, covariance: np.ndarray):
+ """Project state distribution to measurement space.
+
+ Args:
+ mean (np.ndarray): The state's mean vector (8 dimensional array).
+ covariance (np.ndarray): The state's covariance matrix (8x8 dimensional).
+
+ Returns:
+ mean (np.ndarray): Projected mean of the given state estimate.
+ covariance (np.ndarray): Projected covariance matrix of the given state estimate.
+
+ Examples:
+ >>> kf = KalmanFilterXYAH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> projected_mean, projected_covariance = kf.project(mean, covariance)
+ """
std = [
self._std_weight_position * mean[3],
self._std_weight_position * mean[3],
@@ -71,6 +155,22 @@ return mean, covariance + innovation_cov
def multi_predict(self, mean: np.ndarray, covariance: np.ndarray):
+ """Run Kalman filter prediction step for multiple object states (Vectorized version).
+
+ Args:
+ mean (np.ndarray): The Nx8 dimensional mean matrix of the object states at the previous time step.
+ covariance (np.ndarray): The Nx8x8 covariance matrix of the object states at the previous time step.
+
+ Returns:
+ mean (np.ndarray): Mean matrix of the predicted states with shape (N, 8).
+ covariance (np.ndarray): Covariance matrix of the predicted states with shape (N, 8, 8).
+
+ Examples:
+ >>> kf = KalmanFilterXYAH()
+ >>> mean = np.random.rand(10, 8) # 10 object states
+ >>> covariance = np.random.rand(10, 8, 8) # Covariance matrices for 10 object states
+ >>> predicted_mean, predicted_covariance = kf.multi_predict(mean, covariance)
+ """
std_pos = [
self._std_weight_position * mean[:, 3],
self._std_weight_position * mean[:, 3],
@@ -95,6 +195,25 @@ return mean, covariance
def update(self, mean: np.ndarray, covariance: np.ndarray, measurement: np.ndarray):
+ """Run Kalman filter correction step.
+
+ Args:
+ mean (np.ndarray): The predicted state's mean vector (8 dimensional).
+ covariance (np.ndarray): The state's covariance matrix (8x8 dimensional).
+ measurement (np.ndarray): The 4 dimensional measurement vector (x, y, a, h), where (x, y) is the center
+ position, a the aspect ratio, and h the height of the bounding box.
+
+ Returns:
+ new_mean (np.ndarray): Measurement-corrected state mean.
+ new_covariance (np.ndarray): Measurement-corrected state covariance.
+
+ Examples:
+ >>> kf = KalmanFilterXYAH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> measurement = np.array([1, 1, 1, 1])
+ >>> new_mean, new_covariance = kf.update(mean, covariance, measurement)
+ """
projected_mean, projected_cov = self.project(mean, covariance)
chol_factor, lower = scipy.linalg.cho_factor(projected_cov, lower=True, check_finite=False)
@@ -115,6 +234,33 @@ only_position: bool = False,
metric: str = "maha",
) -> np.ndarray:
+ """Compute gating distance between state distribution and measurements.
+
+ A suitable distance threshold can be obtained from `chi2inv95`. If `only_position` is False, the chi-square
+ distribution has 4 degrees of freedom, otherwise 2.
+
+ Args:
+ mean (np.ndarray): Mean vector over the state distribution (8 dimensional).
+ covariance (np.ndarray): Covariance of the state distribution (8x8 dimensional).
+ measurements (np.ndarray): An (N, 4) matrix of N measurements, each in format (x, y, a, h) where (x, y) is
+ the bounding box center position, a the aspect ratio, and h the height.
+ only_position (bool, optional): If True, distance computation is done with respect to box center position
+ only.
+ metric (str, optional): The metric to use for calculating the distance. Options are 'gaussian' for the
+ squared Euclidean distance and 'maha' for the squared Mahalanobis distance.
+
+ Returns:
+ (np.ndarray): Returns an array of length N, where the i-th element contains the squared distance between
+ (mean, covariance) and `measurements[i]`.
+
+ Examples:
+ Compute gating distance using Mahalanobis metric:
+ >>> kf = KalmanFilterXYAH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> measurements = np.array([[1, 1, 1, 1], [2, 2, 1, 1]])
+ >>> distances = kf.gating_distance(mean, covariance, measurements, only_position=False, metric="maha")
+ """
mean, covariance = self.project(mean, covariance)
if only_position:
mean, covariance = mean[:2], covariance[:2, :2]
@@ -132,8 +278,62 @@
class KalmanFilterXYWH(KalmanFilterXYAH):
+ """A KalmanFilterXYWH class for tracking bounding boxes in image space using a Kalman filter.
+
+ Implements a Kalman filter for tracking bounding boxes with state space (x, y, w, h, vx, vy, vw, vh), where (x, y)
+ is the center position, w is the width, h is the height, and vx, vy, vw, vh are their respective velocities. The
+ object motion follows a constant velocity model, and the bounding box location (x, y, w, h) is taken as a direct
+ observation of the state space (linear observation model).
+
+ Attributes:
+ _motion_mat (np.ndarray): The motion matrix for the Kalman filter.
+ _update_mat (np.ndarray): The update matrix for the Kalman filter.
+ _std_weight_position (float): Standard deviation weight for position.
+ _std_weight_velocity (float): Standard deviation weight for velocity.
+
+ Methods:
+ initiate: Create a track from an unassociated measurement.
+ predict: Run the Kalman filter prediction step.
+ project: Project the state distribution to measurement space.
+ multi_predict: Run the Kalman filter prediction step in a vectorized manner.
+ update: Run the Kalman filter correction step.
+
+ Examples:
+ Create a Kalman filter and initialize a track
+ >>> kf = KalmanFilterXYWH()
+ >>> measurement = np.array([100, 50, 20, 40])
+ >>> mean, covariance = kf.initiate(measurement)
+ >>> print(mean)
+ >>> print(covariance)
+ """
def initiate(self, measurement: np.ndarray):
+ """Create track from unassociated measurement.
+
+ Args:
+ measurement (np.ndarray): Bounding box coordinates (x, y, w, h) with center position (x, y), width, and
+ height.
+
+ Returns:
+ mean (np.ndarray): Mean vector (8 dimensional) of the new track. Unobserved velocities are initialized to 0.
+ covariance (np.ndarray): Covariance matrix (8x8 dimensional) of the new track.
+
+ Examples:
+ >>> kf = KalmanFilterXYWH()
+ >>> measurement = np.array([100, 50, 20, 40])
+ >>> mean, covariance = kf.initiate(measurement)
+ >>> print(mean)
+ [100. 50. 20. 40. 0. 0. 0. 0.]
+ >>> print(covariance)
+ [[ 4. 0. 0. 0. 0. 0. 0. 0. ]
+ [ 0. 16. 0. 0. 0. 0. 0. 0. ]
+ [ 0. 0. 4. 0. 0. 0. 0. 0. ]
+ [ 0. 0. 0. 16. 0. 0. 0. 0. ]
+ [ 0. 0. 0. 0. 1.5625 0. 0. 0. ]
+ [ 0. 0. 0. 0. 0. 6.25 0. 0. ]
+ [ 0. 0. 0. 0. 0. 0. 1.5625 0. ]
+ [ 0. 0. 0. 0. 0. 0. 0. 6.25 ]]
+ """
mean_pos = measurement
mean_vel = np.zeros_like(mean_pos)
mean = np.r_[mean_pos, mean_vel]
@@ -152,6 +352,23 @@ return mean, covariance
def predict(self, mean: np.ndarray, covariance: np.ndarray):
+ """Run Kalman filter prediction step.
+
+ Args:
+ mean (np.ndarray): The 8-dimensional mean vector of the object state at the previous time step.
+ covariance (np.ndarray): The 8x8-dimensional covariance matrix of the object state at the previous time
+ step.
+
+ Returns:
+ mean (np.ndarray): Mean vector of the predicted state.
+ covariance (np.ndarray): Covariance matrix of the predicted state.
+
+ Examples:
+ >>> kf = KalmanFilterXYWH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> predicted_mean, predicted_covariance = kf.predict(mean, covariance)
+ """
std_pos = [
self._std_weight_position * mean[2],
self._std_weight_position * mean[3],
@@ -172,6 +389,22 @@ return mean, covariance
def project(self, mean: np.ndarray, covariance: np.ndarray):
+ """Project state distribution to measurement space.
+
+ Args:
+ mean (np.ndarray): The state's mean vector (8 dimensional array).
+ covariance (np.ndarray): The state's covariance matrix (8x8 dimensional).
+
+ Returns:
+ mean (np.ndarray): Projected mean of the given state estimate.
+ covariance (np.ndarray): Projected covariance matrix of the given state estimate.
+
+ Examples:
+ >>> kf = KalmanFilterXYWH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> projected_mean, projected_cov = kf.project(mean, covariance)
+ """
std = [
self._std_weight_position * mean[2],
self._std_weight_position * mean[3],
@@ -185,6 +418,22 @@ return mean, covariance + innovation_cov
def multi_predict(self, mean: np.ndarray, covariance: np.ndarray):
+ """Run Kalman filter prediction step (Vectorized version).
+
+ Args:
+ mean (np.ndarray): The Nx8 dimensional mean matrix of the object states at the previous time step.
+ covariance (np.ndarray): The Nx8x8 covariance matrix of the object states at the previous time step.
+
+ Returns:
+ mean (np.ndarray): Mean matrix of the predicted states with shape (N, 8).
+ covariance (np.ndarray): Covariance matrix of the predicted states with shape (N, 8, 8).
+
+ Examples:
+ >>> mean = np.random.rand(5, 8) # 5 objects with 8-dimensional state vectors
+ >>> covariance = np.random.rand(5, 8, 8) # 5 objects with 8x8 covariance matrices
+ >>> kf = KalmanFilterXYWH()
+ >>> predicted_mean, predicted_covariance = kf.multi_predict(mean, covariance)
+ """
std_pos = [
self._std_weight_position * mean[:, 2],
self._std_weight_position * mean[:, 3],
@@ -209,4 +458,23 @@ return mean, covariance
def update(self, mean: np.ndarray, covariance: np.ndarray, measurement: np.ndarray):
- return super().update(mean, covariance, measurement)+ """Run Kalman filter correction step.
+
+ Args:
+ mean (np.ndarray): The predicted state's mean vector (8 dimensional).
+ covariance (np.ndarray): The state's covariance matrix (8x8 dimensional).
+ measurement (np.ndarray): The 4 dimensional measurement vector (x, y, w, h), where (x, y) is the center
+ position, w the width, and h the height of the bounding box.
+
+ Returns:
+ new_mean (np.ndarray): Measurement-corrected state mean.
+ new_covariance (np.ndarray): Measurement-corrected state covariance.
+
+ Examples:
+ >>> kf = KalmanFilterXYWH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> measurement = np.array([0.5, 0.5, 1.2, 1.2])
+ >>> new_mean, new_covariance = kf.update(mean, covariance, measurement)
+ """
+ return super().update(mean, covariance, measurement)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/trackers/utils/kalman_filter.py |
Help me write clear docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from pathlib import Path
import torch
from ultralytics.utils.checks import check_requirements
from .base import BaseBackend
class TritonBackend(BaseBackend):
def load_model(self, weight: str | Path) -> None:
check_requirements("tritonclient[all]")
from ultralytics.utils.triton import TritonRemoteModel
self.model = TritonRemoteModel(weight)
# Copy metadata from Triton model
if hasattr(self.model, "metadata"):
self.apply_metadata(self.model.metadata)
def forward(self, im: torch.Tensor) -> list:
return self.model(im.cpu().numpy()) | --- +++ @@ -12,8 +12,18 @@
class TritonBackend(BaseBackend):
+ """NVIDIA Triton Inference Server backend for remote model serving.
+
+ Connects to and runs inference with models hosted on an NVIDIA Triton Inference Server instance via HTTP or gRPC
+ protocols. The model is specified using a triton:// URL scheme.
+ """
def load_model(self, weight: str | Path) -> None:
+ """Connect to a remote model on an NVIDIA Triton Inference Server.
+
+ Args:
+ weight (str | Path): Triton model URL (e.g., 'http://localhost:8000/model_name').
+ """
check_requirements("tritonclient[all]")
from ultralytics.utils.triton import TritonRemoteModel
@@ -24,4 +34,12 @@ self.apply_metadata(self.model.metadata)
def forward(self, im: torch.Tensor) -> list:
- return self.model(im.cpu().numpy())+ """Run inference via the NVIDIA Triton Inference Server.
+
+ Args:
+ im (torch.Tensor): Input image tensor in BCHW format, normalized to [0, 1].
+
+ Returns:
+ (list): Model predictions as a list of numpy arrays from the Triton server.
+ """
+ return self.model(im.cpu().numpy())
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/backends/triton.py |
Document functions with detailed explanations | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from collections import deque
from typing import Any
import numpy as np
import torch
from ultralytics.utils.ops import xywh2xyxy
from ultralytics.utils.plotting import save_one_box
from .basetrack import TrackState
from .byte_tracker import BYTETracker, STrack
from .utils import matching
from .utils.gmc import GMC
from .utils.kalman_filter import KalmanFilterXYWH
class BOTrack(STrack):
shared_kalman = KalmanFilterXYWH()
def __init__(
self, xywh: np.ndarray, score: float, cls: int, feat: np.ndarray | None = None, feat_history: int = 50
):
super().__init__(xywh, score, cls)
self.smooth_feat = None
self.curr_feat = None
if feat is not None:
self.update_features(feat)
self.features = deque(maxlen=feat_history)
self.alpha = 0.9
def update_features(self, feat: np.ndarray) -> None:
feat /= np.linalg.norm(feat)
self.curr_feat = feat
if self.smooth_feat is None:
self.smooth_feat = feat
else:
self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat
self.features.append(feat)
self.smooth_feat /= np.linalg.norm(self.smooth_feat)
def predict(self) -> None:
mean_state = self.mean.copy()
if self.state != TrackState.Tracked:
mean_state[6] = 0
mean_state[7] = 0
self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)
def re_activate(self, new_track: BOTrack, frame_id: int, new_id: bool = False) -> None:
if new_track.curr_feat is not None:
self.update_features(new_track.curr_feat)
super().re_activate(new_track, frame_id, new_id)
def update(self, new_track: BOTrack, frame_id: int) -> None:
if new_track.curr_feat is not None:
self.update_features(new_track.curr_feat)
super().update(new_track, frame_id)
@property
def tlwh(self) -> np.ndarray:
if self.mean is None:
return self._tlwh.copy()
ret = self.mean[:4].copy()
ret[:2] -= ret[2:] / 2
return ret
@staticmethod
def multi_predict(stracks: list[BOTrack]) -> None:
if len(stracks) <= 0:
return
multi_mean = np.asarray([st.mean.copy() for st in stracks])
multi_covariance = np.asarray([st.covariance for st in stracks])
for i, st in enumerate(stracks):
if st.state != TrackState.Tracked:
multi_mean[i][6] = 0
multi_mean[i][7] = 0
multi_mean, multi_covariance = BOTrack.shared_kalman.multi_predict(multi_mean, multi_covariance)
for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
stracks[i].mean = mean
stracks[i].covariance = cov
def convert_coords(self, tlwh: np.ndarray) -> np.ndarray:
return self.tlwh_to_xywh(tlwh)
@staticmethod
def tlwh_to_xywh(tlwh: np.ndarray) -> np.ndarray:
ret = np.asarray(tlwh).copy()
ret[:2] += ret[2:] / 2
return ret
class BOTSORT(BYTETracker):
def __init__(self, args: Any, frame_rate: int = 30):
super().__init__(args, frame_rate)
self.gmc = GMC(method=args.gmc_method)
# ReID module
self.proximity_thresh = args.proximity_thresh
self.appearance_thresh = args.appearance_thresh
self.encoder = (
(lambda feats, s: [f.cpu().numpy() for f in feats]) # native features do not require any model
if args.with_reid and self.args.model == "auto"
else ReID(args.model)
if args.with_reid
else None
)
def get_kalmanfilter(self) -> KalmanFilterXYWH:
return KalmanFilterXYWH()
def init_track(self, results, img: np.ndarray | None = None) -> list[BOTrack]:
if len(results) == 0:
return []
bboxes = results.xywhr if hasattr(results, "xywhr") else results.xywh
bboxes = np.concatenate([bboxes, np.arange(len(bboxes)).reshape(-1, 1)], axis=-1)
if self.args.with_reid and self.encoder is not None:
features_keep = self.encoder(img, bboxes)
return [BOTrack(xywh, s, c, f) for (xywh, s, c, f) in zip(bboxes, results.conf, results.cls, features_keep)]
else:
return [BOTrack(xywh, s, c) for (xywh, s, c) in zip(bboxes, results.conf, results.cls)]
def get_dists(self, tracks: list[BOTrack], detections: list[BOTrack]) -> np.ndarray:
dists = matching.iou_distance(tracks, detections)
dists_mask = dists > (1 - self.proximity_thresh)
if self.args.fuse_score:
dists = matching.fuse_score(dists, detections)
if self.args.with_reid and self.encoder is not None:
emb_dists = matching.embedding_distance(tracks, detections) / 2.0
emb_dists[emb_dists > (1 - self.appearance_thresh)] = 1.0
emb_dists[dists_mask] = 1.0
dists = np.minimum(dists, emb_dists)
return dists
def multi_predict(self, tracks: list[BOTrack]) -> None:
BOTrack.multi_predict(tracks)
def reset(self) -> None:
super().reset()
self.gmc.reset_params()
class ReID:
def __init__(self, model: str):
from ultralytics import YOLO
self.model = YOLO(model)
self.model(embed=[len(self.model.model.model) - 2 if ".pt" in model else -1], verbose=False, save=False) # init
def __call__(self, img: np.ndarray, dets: np.ndarray) -> list[np.ndarray]:
feats = self.model.predictor(
[save_one_box(det, img, save=False) for det in xywh2xyxy(torch.from_numpy(dets[:, :4]))]
)
if len(feats) != dets.shape[0] and feats[0].shape[0] == dets.shape[0]:
feats = feats[0] # batched prediction with non-PyTorch backend
return [f.cpu().numpy() for f in feats] | --- +++ @@ -19,12 +19,53 @@
class BOTrack(STrack):
+ """An extended version of the STrack class for YOLO, adding object tracking features.
+
+ This class extends the STrack class to include additional functionalities for object tracking, such as feature
+ smoothing, Kalman filter prediction, and reactivation of tracks.
+
+ Attributes:
+ shared_kalman (KalmanFilterXYWH): A shared Kalman filter for all instances of BOTrack.
+ smooth_feat (np.ndarray): Smoothed feature vector.
+ curr_feat (np.ndarray): Current feature vector.
+ features (deque): A deque to store feature vectors with a maximum length defined by `feat_history`.
+ alpha (float): Smoothing factor for the exponential moving average of features.
+ mean (np.ndarray): The mean state of the Kalman filter.
+ covariance (np.ndarray): The covariance matrix of the Kalman filter.
+
+ Methods:
+ update_features: Update features vector and smooth it using exponential moving average.
+ predict: Predict the mean and covariance using Kalman filter.
+ re_activate: Reactivate a track with updated features and optionally new ID.
+ update: Update the track with new detection and frame ID.
+ tlwh: Property that gets the current position in tlwh format `(top left x, top left y, width, height)`.
+ multi_predict: Predict the mean and covariance of multiple object tracks using shared Kalman filter.
+ convert_coords: Convert tlwh bounding box coordinates to xywh format.
+ tlwh_to_xywh: Convert bounding box to xywh format `(center x, center y, width, height)`.
+
+ Examples:
+ Create a BOTrack instance and update its features
+ >>> bo_track = BOTrack(xywh=np.array([100, 50, 80, 40, 0]), score=0.9, cls=1, feat=np.random.rand(128))
+ >>> bo_track.predict()
+ >>> new_track = BOTrack(xywh=np.array([110, 60, 80, 40, 0]), score=0.85, cls=1, feat=np.random.rand(128))
+ >>> bo_track.update(new_track, frame_id=2)
+ """
shared_kalman = KalmanFilterXYWH()
def __init__(
self, xywh: np.ndarray, score: float, cls: int, feat: np.ndarray | None = None, feat_history: int = 50
):
+ """Initialize a BOTrack object with temporal parameters, such as feature history, alpha, and current features.
+
+ Args:
+ xywh (np.ndarray): Bounding box in `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)` format, where (x, y) is
+ the center, (w, h) are width and height, and `idx` is the detection index.
+ score (float): Confidence score of the detection.
+ cls (int): Class ID of the detected object.
+ feat (np.ndarray, optional): Feature vector associated with the detection.
+ feat_history (int): Maximum length of the feature history deque.
+ """
super().__init__(xywh, score, cls)
self.smooth_feat = None
@@ -35,6 +76,7 @@ self.alpha = 0.9
def update_features(self, feat: np.ndarray) -> None:
+ """Update the feature vector and apply exponential moving average smoothing."""
feat /= np.linalg.norm(feat)
self.curr_feat = feat
if self.smooth_feat is None:
@@ -45,6 +87,7 @@ self.smooth_feat /= np.linalg.norm(self.smooth_feat)
def predict(self) -> None:
+ """Predict the object's future state using the Kalman filter to update its mean and covariance."""
mean_state = self.mean.copy()
if self.state != TrackState.Tracked:
mean_state[6] = 0
@@ -53,17 +96,20 @@ self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)
def re_activate(self, new_track: BOTrack, frame_id: int, new_id: bool = False) -> None:
+ """Reactivate a track with updated features and optionally assign a new ID."""
if new_track.curr_feat is not None:
self.update_features(new_track.curr_feat)
super().re_activate(new_track, frame_id, new_id)
def update(self, new_track: BOTrack, frame_id: int) -> None:
+ """Update the track with new detection information and the current frame ID."""
if new_track.curr_feat is not None:
self.update_features(new_track.curr_feat)
super().update(new_track, frame_id)
@property
def tlwh(self) -> np.ndarray:
+ """Return the current bounding box position in `(top left x, top left y, width, height)` format."""
if self.mean is None:
return self._tlwh.copy()
ret = self.mean[:4].copy()
@@ -72,6 +118,7 @@
@staticmethod
def multi_predict(stracks: list[BOTrack]) -> None:
+ """Predict the mean and covariance for multiple object tracks using a shared Kalman filter."""
if len(stracks) <= 0:
return
multi_mean = np.asarray([st.mean.copy() for st in stracks])
@@ -86,18 +133,51 @@ stracks[i].covariance = cov
def convert_coords(self, tlwh: np.ndarray) -> np.ndarray:
+ """Convert tlwh bounding box coordinates to xywh format."""
return self.tlwh_to_xywh(tlwh)
@staticmethod
def tlwh_to_xywh(tlwh: np.ndarray) -> np.ndarray:
+ """Convert bounding box from tlwh (top-left-width-height) to xywh (center-x-center-y-width-height) format."""
ret = np.asarray(tlwh).copy()
ret[:2] += ret[2:] / 2
return ret
class BOTSORT(BYTETracker):
+ """An extended version of the BYTETracker class for YOLO, designed for object tracking with ReID and GMC algorithm.
+
+ Attributes:
+ proximity_thresh (float): Threshold for spatial proximity (IoU) between tracks and detections.
+ appearance_thresh (float): Threshold for appearance similarity (ReID embeddings) between tracks and detections.
+ encoder (Any): Object to handle ReID embeddings, set to None if ReID is not enabled.
+ gmc (GMC): An instance of the GMC algorithm for data association.
+ args (Any): Parsed command-line arguments containing tracking parameters.
+
+ Methods:
+ get_kalmanfilter: Return an instance of KalmanFilterXYWH for object tracking.
+ init_track: Initialize track with detection results and optional image for ReID.
+ get_dists: Get distances between tracks and detections using IoU and (optionally) ReID.
+ multi_predict: Predict the mean and covariance of multiple object tracks using a shared Kalman filter.
+ reset: Reset the BOTSORT tracker to its initial state.
+
+ Examples:
+ Initialize BOTSORT and process detections
+ >>> bot_sort = BOTSORT(args, frame_rate=30)
+ >>> bot_sort.init_track(results, img)
+ >>> bot_sort.multi_predict(tracks)
+
+ Notes:
+ The class is designed to work with a YOLO object detection model and supports ReID only if enabled via args.
+ """
def __init__(self, args: Any, frame_rate: int = 30):
+ """Initialize BOTSORT object with ReID module and GMC algorithm.
+
+ Args:
+ args (Any): Parsed command-line arguments containing tracking parameters.
+ frame_rate (int): Frame rate of the video being processed.
+ """
super().__init__(args, frame_rate)
self.gmc = GMC(method=args.gmc_method)
@@ -113,9 +193,11 @@ )
def get_kalmanfilter(self) -> KalmanFilterXYWH:
+ """Return an instance of KalmanFilterXYWH for predicting and updating object states in the tracking process."""
return KalmanFilterXYWH()
def init_track(self, results, img: np.ndarray | None = None) -> list[BOTrack]:
+ """Initialize object tracks using detection bounding boxes, scores, class labels, and optional ReID features."""
if len(results) == 0:
return []
bboxes = results.xywhr if hasattr(results, "xywhr") else results.xywh
@@ -127,6 +209,7 @@ return [BOTrack(xywh, s, c) for (xywh, s, c) in zip(bboxes, results.conf, results.cls)]
def get_dists(self, tracks: list[BOTrack], detections: list[BOTrack]) -> np.ndarray:
+ """Calculate distances between tracks and detections using IoU and optionally ReID embeddings."""
dists = matching.iou_distance(tracks, detections)
dists_mask = dists > (1 - self.proximity_thresh)
@@ -141,25 +224,34 @@ return dists
def multi_predict(self, tracks: list[BOTrack]) -> None:
+ """Predict the mean and covariance of multiple object tracks using a shared Kalman filter."""
BOTrack.multi_predict(tracks)
def reset(self) -> None:
+ """Reset the BOTSORT tracker to its initial state, clearing all tracked objects and internal states."""
super().reset()
self.gmc.reset_params()
class ReID:
+ """YOLO model as encoder for re-identification."""
def __init__(self, model: str):
+ """Initialize encoder for re-identification.
+
+ Args:
+ model (str): Path to the YOLO model for re-identification.
+ """
from ultralytics import YOLO
self.model = YOLO(model)
self.model(embed=[len(self.model.model.model) - 2 if ".pt" in model else -1], verbose=False, save=False) # init
def __call__(self, img: np.ndarray, dets: np.ndarray) -> list[np.ndarray]:
+ """Extract embeddings for detected objects."""
feats = self.model.predictor(
[save_one_box(det, img, save=False) for det in xywh2xyxy(torch.from_numpy(dets[:, :4]))]
)
if len(feats) != dets.shape[0] and feats[0].shape[0] == dets.shape[0]:
feats = feats[0] # batched prediction with non-PyTorch backend
- return [f.cpu().numpy() for f in feats]+ return [f.cpu().numpy() for f in feats]
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/trackers/bot_sort.py |
Write Python docstrings for this snippet | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from pathlib import Path
from ultralytics.utils import LOGGER, SETTINGS, TESTS_RUNNING, checks
try:
assert not TESTS_RUNNING # do not log pytest
assert SETTINGS["dvc"] is True # verify integration is enabled
import dvclive
assert checks.check_version("dvclive", "2.11.0", verbose=True)
import os
import re
# DVCLive logger instance
live = None
_processed_plots = {}
# `on_fit_epoch_end` is called on final validation (probably need to be fixed) for now this is the way we
# distinguish final evaluation of the best model vs last epoch validation
_training_epoch = False
except (ImportError, AssertionError, TypeError):
dvclive = None
def _log_images(path: Path, prefix: str = "") -> None:
if live:
name = path.name
# Group images by batch to enable sliders in UI
if m := re.search(r"_batch(\d+)", name):
ni = m[1]
new_stem = re.sub(r"_batch(\d+)", "_batch", path.stem)
name = (Path(new_stem) / ni).with_suffix(path.suffix)
live.log_image(os.path.join(prefix, name), path)
def _log_plots(plots: dict, prefix: str = "") -> None:
for name, params in plots.items():
timestamp = params["timestamp"]
if _processed_plots.get(name) != timestamp:
_log_images(name, prefix)
_processed_plots[name] = timestamp
def _log_confusion_matrix(validator) -> None:
targets = []
preds = []
matrix = validator.confusion_matrix.matrix
names = list(validator.names.values())
if validator.confusion_matrix.task == "detect":
names += ["background"]
for ti, pred in enumerate(matrix.T.astype(int)):
for pi, num in enumerate(pred):
targets.extend([names[ti]] * num)
preds.extend([names[pi]] * num)
live.log_sklearn_plot("confusion_matrix", targets, preds, name="cf.json", normalized=True)
def on_pretrain_routine_start(trainer) -> None:
try:
global live
live = dvclive.Live(save_dvc_exp=True, cache_images=True)
LOGGER.info("DVCLive is detected and auto logging is enabled (run 'yolo settings dvc=False' to disable).")
except Exception as e:
LOGGER.warning(f"DVCLive installed but not initialized correctly, not logging this run. {e}")
def on_pretrain_routine_end(trainer) -> None:
_log_plots(trainer.plots, "train")
def on_train_start(trainer) -> None:
if live:
live.log_params(trainer.args)
def on_train_epoch_start(trainer) -> None:
global _training_epoch
_training_epoch = True
def on_fit_epoch_end(trainer) -> None:
global _training_epoch
if live and _training_epoch:
all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr}
for metric, value in all_metrics.items():
live.log_metric(metric, value)
if trainer.epoch == 0:
from ultralytics.utils.torch_utils import model_info_for_loggers
for metric, value in model_info_for_loggers(trainer).items():
live.log_metric(metric, value, plot=False)
_log_plots(trainer.plots, "train")
_log_plots(trainer.validator.plots, "val")
live.next_step()
_training_epoch = False
def on_train_end(trainer) -> None:
if live:
# At the end log the best metrics. It runs validator on the best model internally.
all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr}
for metric, value in all_metrics.items():
live.log_metric(metric, value, plot=False)
_log_plots(trainer.plots, "val")
_log_plots(trainer.validator.plots, "val")
_log_confusion_matrix(trainer.validator)
if trainer.best.exists():
live.log_artifact(trainer.best, copy=True, type="model")
live.end()
callbacks = (
{
"on_pretrain_routine_start": on_pretrain_routine_start,
"on_pretrain_routine_end": on_pretrain_routine_end,
"on_train_start": on_train_start,
"on_train_epoch_start": on_train_epoch_start,
"on_fit_epoch_end": on_fit_epoch_end,
"on_train_end": on_train_end,
}
if dvclive
else {}
) | --- +++ @@ -27,6 +27,20 @@
def _log_images(path: Path, prefix: str = "") -> None:
+ """Log images at specified path with an optional prefix using DVCLive.
+
+ This function logs images found at the given path to DVCLive, organizing them by batch to enable slider
+ functionality in the UI. It processes image filenames to extract batch information and restructures the path
+ accordingly.
+
+ Args:
+ path (Path): Path to the image file to be logged.
+ prefix (str, optional): Optional prefix to add to the image name when logging.
+
+ Examples:
+ >>> from pathlib import Path
+ >>> _log_images(Path("runs/train/exp/val_batch0_pred.jpg"), prefix="validation")
+ """
if live:
name = path.name
@@ -40,6 +54,12 @@
def _log_plots(plots: dict, prefix: str = "") -> None:
+ """Log plot images for training progress if they have not been previously processed.
+
+ Args:
+ plots (dict): Dictionary containing plot information with timestamps.
+ prefix (str, optional): Optional prefix to add to the logged image paths.
+ """
for name, params in plots.items():
timestamp = params["timestamp"]
if _processed_plots.get(name) != timestamp:
@@ -48,6 +68,15 @@
def _log_confusion_matrix(validator) -> None:
+ """Log confusion matrix for a validator using DVCLive.
+
+ This function processes the confusion matrix from a validator object and logs it to DVCLive by converting the matrix
+ into lists of target and prediction labels.
+
+ Args:
+ validator (BaseValidator): The validator object containing the confusion matrix and class names. Must have
+ attributes confusion_matrix.matrix, confusion_matrix.task, and names.
+ """
targets = []
preds = []
matrix = validator.confusion_matrix.matrix
@@ -64,6 +93,7 @@
def on_pretrain_routine_start(trainer) -> None:
+ """Initialize DVCLive logger for training metadata during pre-training routine."""
try:
global live
live = dvclive.Live(save_dvc_exp=True, cache_images=True)
@@ -73,20 +103,36 @@
def on_pretrain_routine_end(trainer) -> None:
+ """Log plots related to the training process at the end of the pretraining routine."""
_log_plots(trainer.plots, "train")
def on_train_start(trainer) -> None:
+ """Log the training parameters if DVCLive logging is active."""
if live:
live.log_params(trainer.args)
def on_train_epoch_start(trainer) -> None:
+ """Set the global variable _training_epoch value to True at the start of each training epoch."""
global _training_epoch
_training_epoch = True
def on_fit_epoch_end(trainer) -> None:
+ """Log training metrics, model info, and advance to next step at the end of each fit epoch.
+
+ This function is called at the end of each fit epoch during training. It logs various metrics including training
+ loss items, validation metrics, and learning rates. On the first epoch, it also logs model
+ information. Additionally, it logs training and validation plots and advances the DVCLive step counter.
+
+ Args:
+ trainer (BaseTrainer): The trainer object containing training state, metrics, and plots.
+
+ Notes:
+ This function only performs logging operations when DVCLive logging is active and during a training epoch.
+ The global variable _training_epoch is used to track whether the current epoch is a training epoch.
+ """
global _training_epoch
if live and _training_epoch:
all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr}
@@ -107,6 +153,20 @@
def on_train_end(trainer) -> None:
+ """Log best metrics, plots, and confusion matrix at the end of training.
+
+ This function is called at the conclusion of the training process to log final metrics, visualizations, and model
+ artifacts if DVCLive logging is active. It captures the best model performance metrics, training plots, validation
+ plots, and confusion matrix for later analysis.
+
+ Args:
+ trainer (BaseTrainer): The trainer object containing training state, metrics, and validation results.
+
+ Examples:
+ >>> # Inside a custom training loop
+ >>> from ultralytics.utils.callbacks.dvc import on_train_end
+ >>> on_train_end(trainer) # Log final metrics and artifacts
+ """
if live:
# At the end log the best metrics. It runs validator on the best model internally.
all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics, **trainer.lr}
@@ -134,4 +194,4 @@ }
if dvclive
else {}
-)+)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/callbacks/dvc.py |
Generate consistent documentation across files | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from typing import Any
import cv2
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
from ultralytics.utils import LOGGER
from ultralytics.utils.plotting import colors
class ObjectBlurrer(BaseSolution):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
blur_ratio = self.CFG["blur_ratio"]
if blur_ratio < 0.1:
LOGGER.warning("blur ratio cannot be less than 0.1, updating it to default value 0.5")
blur_ratio = 0.5
self.blur_ratio = int(blur_ratio * 100)
def process(self, im0) -> SolutionResults:
self.extract_tracks(im0) # Extract tracks
annotator = SolutionAnnotator(im0, self.line_width)
# Iterate over bounding boxes and classes
for box, cls, conf in zip(self.boxes, self.clss, self.confs):
# Crop and blur the detected object
blur_obj = cv2.blur(
im0[int(box[1]) : int(box[3]), int(box[0]) : int(box[2])],
(self.blur_ratio, self.blur_ratio),
)
# Update the blurred area in the original image
im0[int(box[1]) : int(box[3]), int(box[0]) : int(box[2])] = blur_obj
annotator.box_label(
box, label=self.adjust_box_label(cls, conf), color=colors(cls, True)
) # Annotate bounding box
plot_im = annotator.result()
self.display_output(plot_im) # Display the output using the base class function
# Return a SolutionResults
return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids)) | --- +++ @@ -10,8 +10,35 @@
class ObjectBlurrer(BaseSolution):
+ """A class to manage the blurring of detected objects in a real-time video stream.
+
+ This class extends the BaseSolution class and provides functionality for blurring objects based on detected bounding
+ boxes. The blurred areas are updated directly in the input image, allowing for privacy preservation or other effects.
+
+ Attributes:
+ blur_ratio (int): The intensity of the blur effect applied to detected objects (higher values create more blur).
+ iou (float): Intersection over Union threshold for object detection.
+ conf (float): Confidence threshold for object detection.
+
+ Methods:
+ process: Apply a blurring effect to detected objects in the input image.
+ extract_tracks: Extract tracking information from detected objects.
+ display_output: Display the processed output image.
+
+ Examples:
+ >>> blurrer = ObjectBlurrer()
+ >>> frame = cv2.imread("frame.jpg")
+ >>> processed_results = blurrer.process(frame)
+ >>> print(f"Total blurred objects: {processed_results.total_tracks}")
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the ObjectBlurrer class for applying a blur effect to objects detected in video streams or images.
+
+ Args:
+ **kwargs (Any): Keyword arguments passed to the parent class and for configuration including:
+ - blur_ratio (float): Intensity of the blur effect (0.1-1.0, default=0.5).
+ """
super().__init__(**kwargs)
blur_ratio = self.CFG["blur_ratio"]
if blur_ratio < 0.1:
@@ -20,6 +47,25 @@ self.blur_ratio = int(blur_ratio * 100)
def process(self, im0) -> SolutionResults:
+ """Apply a blurring effect to detected objects in the input image.
+
+ This method extracts tracking information, applies blur to regions corresponding to detected objects, and
+ annotates the image with bounding boxes.
+
+ Args:
+ im0 (np.ndarray): The input image containing detected objects.
+
+ Returns:
+ (SolutionResults): Object containing the processed image and number of tracked objects.
+ - plot_im (np.ndarray): The annotated output image with blurred objects.
+ - total_tracks (int): The total number of tracked objects in the frame.
+
+ Examples:
+ >>> blurrer = ObjectBlurrer()
+ >>> frame = cv2.imread("image.jpg")
+ >>> results = blurrer.process(frame)
+ >>> print(f"Blurred {results.total_tracks} objects")
+ """
self.extract_tracks(im0) # Extract tracks
annotator = SolutionAnnotator(im0, self.line_width)
@@ -40,4 +86,4 @@ self.display_output(plot_im) # Display the output using the base class function
# Return a SolutionResults
- return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids))+ return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids))
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/object_blurrer.py |
Generate helpful docstrings for debugging | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from ultralytics.utils import LOGGER, SETTINGS, TESTS_RUNNING
try:
assert not TESTS_RUNNING # do not log pytest
assert SETTINGS["clearml"] is True # verify integration is enabled
import clearml
from clearml import Task
assert hasattr(clearml, "__version__") # verify package is not directory
except (ImportError, AssertionError):
clearml = None
def _log_debug_samples(files, title: str = "Debug Samples") -> None:
import re
if task := Task.current_task():
for f in files:
if f.exists():
it = re.search(r"_batch(\d+)", f.name)
iteration = int(it.groups()[0]) if it else 0
task.get_logger().report_image(
title=title, series=f.name.replace(it.group(), ""), local_path=str(f), iteration=iteration
)
def _log_plot(title: str, plot_path: str) -> None:
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
img = mpimg.imread(plot_path)
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect="auto", xticks=[], yticks=[]) # no ticks
ax.imshow(img)
Task.current_task().get_logger().report_matplotlib_figure(
title=title, series="", figure=fig, report_interactive=False
)
def on_pretrain_routine_start(trainer) -> None:
try:
if task := Task.current_task():
# WARNING: make sure the automatic pytorch and matplotlib bindings are disabled!
# We are logging these plots and model files manually in the integration
from clearml.binding.frameworks.pytorch_bind import PatchPyTorchModelIO
from clearml.binding.matplotlib_bind import PatchedMatplotlib
PatchPyTorchModelIO.update_current_task(None)
PatchedMatplotlib.update_current_task(None)
else:
task = Task.init(
project_name=trainer.args.project or "Ultralytics",
task_name=trainer.args.name,
tags=["Ultralytics"],
output_uri=True,
reuse_last_task_id=False,
auto_connect_frameworks={"pytorch": False, "matplotlib": False},
)
LOGGER.warning(
"ClearML Initialized a new task. If you want to run remotely, "
"please add clearml-init and connect your arguments before initializing YOLO."
)
task.connect(vars(trainer.args), name="General", ignore_remote_overrides=True)
except Exception as e:
LOGGER.warning(f"ClearML installed but not initialized correctly, not logging this run. {e}")
def on_train_epoch_end(trainer) -> None:
if task := Task.current_task():
# Log debug samples for first epoch only
if trainer.epoch == 1:
_log_debug_samples(sorted(trainer.save_dir.glob("train_batch*.jpg")), "Mosaic")
# Report the current training progress
for k, v in trainer.label_loss_items(trainer.tloss, prefix="train").items():
task.get_logger().report_scalar("train", k, v, iteration=trainer.epoch)
for k, v in trainer.lr.items():
task.get_logger().report_scalar("lr", k, v, iteration=trainer.epoch)
def on_fit_epoch_end(trainer) -> None:
if task := Task.current_task():
# Report epoch time and validation metrics
task.get_logger().report_scalar(
title="Epoch Time", series="Epoch Time", value=trainer.epoch_time, iteration=trainer.epoch
)
for k, v in trainer.metrics.items():
title = k.split("/")[0]
task.get_logger().report_scalar(title, k, v, iteration=trainer.epoch)
if trainer.epoch == 0:
from ultralytics.utils.torch_utils import model_info_for_loggers
for k, v in model_info_for_loggers(trainer).items():
task.get_logger().report_single_value(k, v)
def on_val_end(validator) -> None:
if Task.current_task():
# Log validation labels and predictions
_log_debug_samples(sorted(validator.save_dir.glob("val*.jpg")), "Validation")
def on_train_end(trainer) -> None:
if task := Task.current_task():
# Log final results, confusion matrix and PR plots
for f in [*trainer.plots.keys(), *trainer.validator.plots.keys()]:
if "batch" not in f.name:
_log_plot(title=f.stem, plot_path=f)
# Report final metrics
for k, v in trainer.validator.metrics.results_dict.items():
task.get_logger().report_single_value(k, v)
# Log the final model
task.update_output_model(model_path=str(trainer.best), model_name=trainer.args.name, auto_delete_file=False)
callbacks = (
{
"on_pretrain_routine_start": on_pretrain_routine_start,
"on_train_epoch_end": on_train_epoch_end,
"on_fit_epoch_end": on_fit_epoch_end,
"on_val_end": on_val_end,
"on_train_end": on_train_end,
}
if clearml
else {}
) | --- +++ @@ -15,6 +15,12 @@
def _log_debug_samples(files, title: str = "Debug Samples") -> None:
+ """Log files (images) as debug samples in the ClearML task.
+
+ Args:
+ files (list[Path]): A list of file paths in PosixPath format.
+ title (str): A title that groups together images with the same values.
+ """
import re
if task := Task.current_task():
@@ -28,6 +34,12 @@
def _log_plot(title: str, plot_path: str) -> None:
+ """Log an image as a plot in the plot section of ClearML.
+
+ Args:
+ title (str): The title of the plot.
+ plot_path (str | Path): The path to the saved image file.
+ """
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
@@ -42,6 +54,7 @@
def on_pretrain_routine_start(trainer) -> None:
+ """Initialize and connect ClearML task at the start of pretraining routine."""
try:
if task := Task.current_task():
# WARNING: make sure the automatic pytorch and matplotlib bindings are disabled!
@@ -70,6 +83,7 @@
def on_train_epoch_end(trainer) -> None:
+ """Log debug samples for the first epoch and report current training progress."""
if task := Task.current_task():
# Log debug samples for first epoch only
if trainer.epoch == 1:
@@ -82,6 +96,7 @@
def on_fit_epoch_end(trainer) -> None:
+ """Report model information and metrics to logger at the end of an epoch."""
if task := Task.current_task():
# Report epoch time and validation metrics
task.get_logger().report_scalar(
@@ -98,12 +113,14 @@
def on_val_end(validator) -> None:
+ """Log validation results including labels and predictions."""
if Task.current_task():
# Log validation labels and predictions
_log_debug_samples(sorted(validator.save_dir.glob("val*.jpg")), "Validation")
def on_train_end(trainer) -> None:
+ """Log final model and training results on training completion."""
if task := Task.current_task():
# Log final results, confusion matrix and PR plots
for f in [*trainer.plots.keys(), *trainer.validator.plots.keys()]:
@@ -126,4 +143,4 @@ }
if clearml
else {}
-)+)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/callbacks/clearml.py |
Help me add docstrings to my project | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import random
from typing import Any
from ultralytics.utils import LOGGER
from ultralytics.utils.checks import check_requirements
class GPUInfo:
def __init__(self):
self.pynvml: Any | None = None
self.nvml_available: bool = False
self.gpu_stats: list[dict[str, Any]] = []
try:
check_requirements("nvidia-ml-py>=12.0.0")
self.pynvml = __import__("pynvml")
self.pynvml.nvmlInit()
self.nvml_available = True
self.refresh_stats()
except Exception as e:
LOGGER.warning(f"Failed to initialize pynvml, GPU stats disabled: {e}")
def __del__(self):
self.shutdown()
def shutdown(self):
if self.nvml_available and self.pynvml:
try:
self.pynvml.nvmlShutdown()
except Exception:
pass
self.nvml_available = False
def refresh_stats(self):
self.gpu_stats = []
if not self.nvml_available or not self.pynvml:
return
try:
device_count = self.pynvml.nvmlDeviceGetCount()
self.gpu_stats.extend(self._get_device_stats(i) for i in range(device_count))
except Exception as e:
LOGGER.warning(f"Error during device query: {e}")
self.gpu_stats = []
def _get_device_stats(self, index: int) -> dict[str, Any]:
handle = self.pynvml.nvmlDeviceGetHandleByIndex(index)
memory = self.pynvml.nvmlDeviceGetMemoryInfo(handle)
util = self.pynvml.nvmlDeviceGetUtilizationRates(handle)
def safe_get(func, *args, default=-1, divisor=1):
try:
val = func(*args)
return val // divisor if divisor != 1 and isinstance(val, (int, float)) else val
except Exception:
return default
temp_type = getattr(self.pynvml, "NVML_TEMPERATURE_GPU", -1)
return {
"index": index,
"name": self.pynvml.nvmlDeviceGetName(handle),
"utilization": util.gpu if util else -1,
"memory_used": memory.used >> 20 if memory else -1, # Convert bytes to MiB
"memory_total": memory.total >> 20 if memory else -1,
"memory_free": memory.free >> 20 if memory else -1,
"temperature": safe_get(self.pynvml.nvmlDeviceGetTemperature, handle, temp_type),
"power_draw": safe_get(self.pynvml.nvmlDeviceGetPowerUsage, handle, divisor=1000), # Convert mW to W
"power_limit": safe_get(self.pynvml.nvmlDeviceGetEnforcedPowerLimit, handle, divisor=1000),
}
def print_status(self):
self.refresh_stats()
if not self.gpu_stats:
LOGGER.warning("No GPU stats available.")
return
stats = self.gpu_stats
name_len = max(len(gpu.get("name", "N/A")) for gpu in stats)
hdr = f"{'Idx':<3} {'Name':<{name_len}} {'Util':>6} {'Mem (MiB)':>15} {'Temp':>5} {'Pwr (W)':>10}"
LOGGER.info(f"\n--- GPU Status ---\n{hdr}\n{'-' * len(hdr)}")
for gpu in stats:
u = f"{gpu['utilization']:>5}%" if gpu["utilization"] >= 0 else " N/A "
m = f"{gpu['memory_used']:>6}/{gpu['memory_total']:<6}" if gpu["memory_used"] >= 0 else " N/A / N/A "
t = f"{gpu['temperature']}C" if gpu["temperature"] >= 0 else " N/A "
p = f"{gpu['power_draw']:>3}/{gpu['power_limit']:<3}" if gpu["power_draw"] >= 0 else " N/A "
LOGGER.info(f"{gpu.get('index'):<3d} {gpu.get('name', 'N/A'):<{name_len}} {u:>6} {m:>15} {t:>5} {p:>10}")
LOGGER.info(f"{'-' * len(hdr)}\n")
def select_idle_gpu(
self, count: int = 1, min_memory_fraction: float = 0, min_util_fraction: float = 0
) -> list[int]:
assert min_memory_fraction <= 1.0, f"min_memory_fraction must be <= 1.0, got {min_memory_fraction}"
assert min_util_fraction <= 1.0, f"min_util_fraction must be <= 1.0, got {min_util_fraction}"
criteria = (
f"free memory >= {min_memory_fraction * 100:.1f}% and free utilization >= {min_util_fraction * 100:.1f}%"
)
LOGGER.info(f"Searching for {count} idle GPUs with {criteria}...")
if count <= 0:
return []
self.refresh_stats()
if not self.gpu_stats:
LOGGER.warning("NVML stats unavailable.")
return []
# Filter and sort eligible GPUs
eligible_gpus = [
gpu
for gpu in self.gpu_stats
if gpu.get("memory_free", 0) / gpu.get("memory_total", 1) >= min_memory_fraction
and (100 - gpu.get("utilization", 100)) >= min_util_fraction * 100
]
# Random tiebreaker prevents race conditions when multiple processes start simultaneously
# and all GPUs appear equally idle (same utilization and free memory)
eligible_gpus.sort(key=lambda x: (x.get("utilization", 101), -x.get("memory_free", 0), random.random()))
# Select top 'count' indices
selected = [gpu["index"] for gpu in eligible_gpus[:count]]
if selected:
if len(selected) < count:
LOGGER.warning(f"Requested {count} GPUs but only {len(selected)} met the idle criteria.")
LOGGER.info(f"Selected idle CUDA devices {selected}")
else:
LOGGER.warning(f"No GPUs met criteria ({criteria}).")
return selected
if __name__ == "__main__":
required_free_mem_fraction = 0.2 # Require 20% free VRAM
required_free_util_fraction = 0.2 # Require 20% free utilization
num_gpus_to_select = 1
gpu_info = GPUInfo()
gpu_info.print_status()
if selected := gpu_info.select_idle_gpu(
count=num_gpus_to_select,
min_memory_fraction=required_free_mem_fraction,
min_util_fraction=required_free_util_fraction,
):
print(f"\n==> Using selected GPU indices: {selected}")
devices = [f"cuda:{idx}" for idx in selected]
print(f" Target devices: {devices}") | --- +++ @@ -10,8 +10,42 @@
class GPUInfo:
+ """Manages NVIDIA GPU information via pynvml with robust error handling.
+
+ Provides methods to query detailed GPU statistics (utilization, memory, temp, power) and select the most idle GPUs
+ based on configurable criteria. It safely handles the absence or initialization failure of the pynvml library by
+ logging warnings and disabling related features, preventing application crashes.
+
+ Includes fallback logic using `torch.cuda` for basic device counting if NVML is unavailable during GPU
+ selection. Manages NVML initialization and shutdown internally.
+
+ Attributes:
+ pynvml (module | None): The `pynvml` module if successfully imported and initialized, otherwise `None`.
+ nvml_available (bool): Indicates if `pynvml` is ready for use. True if import and `nvmlInit()` succeeded, False
+ otherwise.
+ gpu_stats (list[dict[str, Any]]): A list of dictionaries, each holding stats for one GPU, populated on
+ initialization and by `refresh_stats()`. Keys include: 'index', 'name', 'utilization' (%), 'memory_used' (MiB),
+ 'memory_total' (MiB), 'memory_free' (MiB), 'temperature' (C), 'power_draw' (W), 'power_limit' (W or 'N/A').
+ Empty if NVML is unavailable or queries fail.
+
+ Methods:
+ refresh_stats: Refresh the internal gpu_stats list by querying NVML.
+ print_status: Print GPU status in a compact table format using current stats.
+ select_idle_gpu: Select the most idle GPUs based on utilization and free memory.
+ shutdown: Shut down NVML if it was initialized.
+
+ Examples:
+ Initialize GPUInfo and print status
+ >>> gpu_info = GPUInfo()
+ >>> gpu_info.print_status()
+
+ Select idle GPUs with minimum memory requirements
+ >>> selected = gpu_info.select_idle_gpu(count=2, min_memory_fraction=0.2)
+ >>> print(f"Selected GPU indices: {selected}")
+ """
def __init__(self):
+ """Initialize GPUInfo, attempting to import and initialize pynvml."""
self.pynvml: Any | None = None
self.nvml_available: bool = False
self.gpu_stats: list[dict[str, Any]] = []
@@ -26,9 +60,11 @@ LOGGER.warning(f"Failed to initialize pynvml, GPU stats disabled: {e}")
def __del__(self):
+ """Ensure NVML is shut down when the object is garbage collected."""
self.shutdown()
def shutdown(self):
+ """Shut down NVML if it was initialized."""
if self.nvml_available and self.pynvml:
try:
self.pynvml.nvmlShutdown()
@@ -37,6 +73,7 @@ self.nvml_available = False
def refresh_stats(self):
+ """Refresh the internal gpu_stats list by querying NVML."""
self.gpu_stats = []
if not self.nvml_available or not self.pynvml:
return
@@ -49,6 +86,7 @@ self.gpu_stats = []
def _get_device_stats(self, index: int) -> dict[str, Any]:
+ """Get stats for a single GPU device."""
handle = self.pynvml.nvmlDeviceGetHandleByIndex(index)
memory = self.pynvml.nvmlDeviceGetMemoryInfo(handle)
util = self.pynvml.nvmlDeviceGetUtilizationRates(handle)
@@ -75,6 +113,7 @@ }
def print_status(self):
+ """Print GPU status in a compact table format using current stats."""
self.refresh_stats()
if not self.gpu_stats:
LOGGER.warning("No GPU stats available.")
@@ -98,6 +137,20 @@ def select_idle_gpu(
self, count: int = 1, min_memory_fraction: float = 0, min_util_fraction: float = 0
) -> list[int]:
+ """Select the most idle GPUs based on utilization and free memory.
+
+ Args:
+ count (int): The number of idle GPUs to select.
+ min_memory_fraction (float): Minimum free memory required as a fraction of total memory.
+ min_util_fraction (float): Minimum free utilization rate required from 0.0 - 1.0.
+
+ Returns:
+ (list[int]): Indices of the selected GPUs, sorted by idleness (lowest utilization first).
+
+ Notes:
+ Returns fewer than 'count' if not enough qualify or exist.
+ Returns empty list if NVML stats are unavailable or no GPUs meet the criteria.
+ """
assert min_memory_fraction <= 1.0, f"min_memory_fraction must be <= 1.0, got {min_memory_fraction}"
assert min_util_fraction <= 1.0, f"min_util_fraction must be <= 1.0, got {min_util_fraction}"
criteria = (
@@ -152,4 +205,4 @@ ):
print(f"\n==> Using selected GPU indices: {selected}")
devices = [f"cuda:{idx}" for idx in selected]
- print(f" Target devices: {devices}")+ print(f" Target devices: {devices}")
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/autodevice.py |
Write docstrings including parameters and return values | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import os
from pathlib import Path
from typing import Any
import numpy as np
from PIL import Image
from ultralytics.data.utils import IMG_FORMATS
from ultralytics.utils import LOGGER, TORCH_VERSION
from ultralytics.utils.checks import check_requirements
from ultralytics.utils.torch_utils import TORCH_2_4, select_device
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" # Avoid OpenMP conflict on some systems
class VisualAISearch:
def __init__(self, **kwargs: Any) -> None:
assert TORCH_2_4, f"VisualAISearch requires torch>=2.4 (found torch=={TORCH_VERSION})"
from ultralytics.nn.text_model import build_text_model
check_requirements("faiss-cpu")
self.faiss = __import__("faiss")
self.faiss_index = "faiss.index"
self.data_path_npy = "paths.npy"
self.data_dir = Path(kwargs.get("data", "images"))
self.device = select_device(kwargs.get("device", "cpu"))
if not self.data_dir.exists():
from ultralytics.utils import ASSETS_URL
LOGGER.warning(f"{self.data_dir} not found. Downloading images.zip from {ASSETS_URL}/images.zip")
from ultralytics.utils.downloads import safe_download
safe_download(url=f"{ASSETS_URL}/images.zip", unzip=True, retry=3)
self.data_dir = Path("images")
self.model = build_text_model("clip:ViT-B/32", device=self.device)
self.index = None
self.image_paths = []
self.load_or_build_index()
def extract_image_feature(self, path: Path) -> np.ndarray:
return self.model.encode_image(Image.open(path)).detach().cpu().numpy()
def extract_text_feature(self, text: str) -> np.ndarray:
return self.model.encode_text(self.model.tokenize([text])).detach().cpu().numpy()
def load_or_build_index(self) -> None:
# Check if the FAISS index and corresponding image paths already exist
if Path(self.faiss_index).exists() and Path(self.data_path_npy).exists():
LOGGER.info("Loading existing FAISS index...")
self.index = self.faiss.read_index(self.faiss_index) # Load the FAISS index from disk
self.image_paths = np.load(self.data_path_npy) # Load the saved image path list
return # Exit the function as the index is successfully loaded
# If the index doesn't exist, start building it from scratch
LOGGER.info("Building FAISS index from images...")
vectors = [] # List to store feature vectors of images
# Iterate over all image files in the data directory
for file in self.data_dir.iterdir():
# Skip files that are not valid image formats
if file.suffix.lower().lstrip(".") not in IMG_FORMATS:
continue
try:
# Extract feature vector for the image and add to the list
vectors.append(self.extract_image_feature(file))
self.image_paths.append(file.name) # Store the corresponding image name
except Exception as e:
LOGGER.warning(f"Skipping {file.name}: {e}")
# If no vectors were successfully created, raise an error
if not vectors:
raise RuntimeError("No image embeddings could be generated.")
vectors = np.vstack(vectors).astype("float32") # Stack all vectors into a NumPy array and convert to float32
self.faiss.normalize_L2(vectors) # Normalize vectors to unit length for cosine similarity
self.index = self.faiss.IndexFlatIP(vectors.shape[1]) # Create a new FAISS index using inner product
self.index.add(vectors) # Add the normalized vectors to the FAISS index
self.faiss.write_index(self.index, self.faiss_index) # Save the newly built FAISS index to disk
np.save(self.data_path_npy, np.array(self.image_paths)) # Save the list of image paths to disk
LOGGER.info(f"Indexed {len(self.image_paths)} images.")
def search(self, query: str, k: int = 30, similarity_thresh: float = 0.1) -> list[str]:
text_feat = self.extract_text_feature(query).astype("float32")
self.faiss.normalize_L2(text_feat)
D, index = self.index.search(text_feat, k)
results = [
(self.image_paths[i], float(D[0][idx])) for idx, i in enumerate(index[0]) if D[0][idx] >= similarity_thresh
]
results.sort(key=lambda x: x[1], reverse=True)
LOGGER.info("\nRanked Results:")
for name, score in results:
LOGGER.info(f" - {name} | Similarity: {score:.4f}")
return [r[0] for r in results]
def __call__(self, query: str) -> list[str]:
return self.search(query)
class SearchApp:
def __init__(self, data: str = "images", device: str | None = None) -> None:
check_requirements("flask>=3.0.1")
from flask import Flask, render_template, request
self.render_template = render_template
self.request = request
self.searcher = VisualAISearch(data=data, device=device)
self.app = Flask(
__name__,
template_folder="templates",
static_folder=Path(data).resolve(), # Absolute path to serve images
static_url_path="/images", # URL prefix for images
)
self.app.add_url_rule("/", view_func=self.index, methods=["GET", "POST"])
def index(self) -> str:
results = []
if self.request.method == "POST":
query = self.request.form.get("query", "").strip()
results = self.searcher(query)
return self.render_template("similarity-search.html", results=results)
def run(self, debug: bool = False) -> None:
self.app.run(debug=debug) | --- +++ @@ -18,8 +18,36 @@
class VisualAISearch:
+ """A semantic image search system that leverages OpenCLIP for generating high-quality image and text embeddings and
+ FAISS for fast similarity-based retrieval.
+
+ This class aligns image and text embeddings in a shared semantic space, enabling users to search large collections
+ of images using natural language queries with high accuracy and speed.
+
+ Attributes:
+ data (str): Directory containing images.
+ device (str): Computation device, e.g., 'cpu' or 'cuda'.
+ faiss_index (str): Path to the FAISS index file.
+ data_path_npy (str): Path to the numpy file storing image paths.
+ data_dir (Path): Path object for the data directory.
+ model: Loaded CLIP model.
+ index: FAISS index for similarity search.
+ image_paths (list[str]): List of image file paths.
+
+ Methods:
+ extract_image_feature: Extract CLIP embedding from an image.
+ extract_text_feature: Extract CLIP embedding from text.
+ load_or_build_index: Load existing FAISS index or build new one.
+ search: Perform semantic search for similar images.
+
+ Examples:
+ Initialize and search for images
+ >>> searcher = VisualAISearch(data="path/to/images", device="cuda")
+ >>> results = searcher.search("a cat sitting on a chair", k=10)
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the VisualAISearch class with FAISS index and CLIP model."""
assert TORCH_2_4, f"VisualAISearch requires torch>=2.4 (found torch=={TORCH_VERSION})"
from ultralytics.nn.text_model import build_text_model
@@ -48,12 +76,20 @@ self.load_or_build_index()
def extract_image_feature(self, path: Path) -> np.ndarray:
+ """Extract CLIP image embedding from the given image path."""
return self.model.encode_image(Image.open(path)).detach().cpu().numpy()
def extract_text_feature(self, text: str) -> np.ndarray:
+ """Extract CLIP text embedding from the given text query."""
return self.model.encode_text(self.model.tokenize([text])).detach().cpu().numpy()
def load_or_build_index(self) -> None:
+ """Load existing FAISS index or build a new one from image features.
+
+ Checks if FAISS index and image paths exist on disk. If found, loads them directly. Otherwise, builds a new
+ index by extracting features from all images in the data directory, normalizes the features, and saves both the
+ index and image paths for future use.
+ """
# Check if the FAISS index and corresponding image paths already exist
if Path(self.faiss_index).exists() and Path(self.data_path_npy).exists():
LOGGER.info("Loading existing FAISS index...")
@@ -92,6 +128,21 @@ LOGGER.info(f"Indexed {len(self.image_paths)} images.")
def search(self, query: str, k: int = 30, similarity_thresh: float = 0.1) -> list[str]:
+ """Return top-k semantically similar images to the given query.
+
+ Args:
+ query (str): Natural language text query to search for.
+ k (int, optional): Maximum number of results to return.
+ similarity_thresh (float, optional): Minimum similarity threshold for filtering results.
+
+ Returns:
+ (list[str]): List of image filenames ranked by similarity score.
+
+ Examples:
+ Search for images matching a query
+ >>> searcher = VisualAISearch(data="images")
+ >>> results = searcher.search("red car", k=5, similarity_thresh=0.2)
+ """
text_feat = self.extract_text_feature(query).astype("float32")
self.faiss.normalize_L2(text_feat)
@@ -108,12 +159,39 @@ return [r[0] for r in results]
def __call__(self, query: str) -> list[str]:
+ """Direct call interface for the search function."""
return self.search(query)
class SearchApp:
+ """A Flask-based web interface for semantic image search with natural language queries.
+
+ This class provides a clean, responsive frontend that enables users to input natural language queries and instantly
+ view the most relevant images retrieved from the indexed database.
+
+ Attributes:
+ render_template: Flask template rendering function.
+ request: Flask request object.
+ searcher (VisualAISearch): Instance of the VisualAISearch class.
+ app (Flask): Flask application instance.
+
+ Methods:
+ index: Process user queries and display search results.
+ run: Start the Flask web application.
+
+ Examples:
+ Start a search application
+ >>> app = SearchApp(data="path/to/images", device="cuda")
+ >>> app.run(debug=True)
+ """
def __init__(self, data: str = "images", device: str | None = None) -> None:
+ """Initialize the SearchApp with VisualAISearch backend.
+
+ Args:
+ data (str, optional): Path to directory containing images to index and search.
+ device (str, optional): Device to run inference on (e.g. 'cpu', 'cuda').
+ """
check_requirements("flask>=3.0.1")
from flask import Flask, render_template, request
@@ -129,6 +207,7 @@ self.app.add_url_rule("/", view_func=self.index, methods=["GET", "POST"])
def index(self) -> str:
+ """Process user query and display search results in the web interface."""
results = []
if self.request.method == "POST":
query = self.request.form.get("query", "").strip()
@@ -136,4 +215,5 @@ return self.render_template("similarity-search.html", results=results)
def run(self, debug: bool = False) -> None:
- self.app.run(debug=debug)+ """Start the Flask web application server."""
+ self.app.run(debug=debug)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/similarity_search.py |
Add verbose docstrings with examples | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import json
from typing import Any
import cv2
import numpy as np
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
from ultralytics.utils import LOGGER
from ultralytics.utils.checks import check_imshow
class ParkingPtsSelection:
def __init__(self) -> None:
try: # Check if tkinter is installed
import tkinter as tk
from tkinter import filedialog, messagebox
except ImportError: # Display error with recommendations
import platform
install_cmd = {
"Linux": "sudo apt install python3-tk (Debian/Ubuntu) | sudo dnf install python3-tkinter (Fedora) | "
"sudo pacman -S tk (Arch)",
"Windows": "reinstall Python and enable the checkbox `tcl/tk and IDLE` on **Optional Features** during installation",
"Darwin": "reinstall Python from https://www.python.org/downloads/macos/ or `brew install python-tk`",
}.get(platform.system(), "Unknown OS. Check your Python installation.")
LOGGER.warning(f" Tkinter is not configured or supported. Potential fix: {install_cmd}")
return
if not check_imshow(warn=True):
return
self.tk, self.filedialog, self.messagebox = tk, filedialog, messagebox
self.master = self.tk.Tk() # Reference to the main application window
self.master.title("Ultralytics Parking Zones Points Selector")
self.master.resizable(False, False)
self.canvas = self.tk.Canvas(self.master, bg="white") # Canvas widget for displaying images
self.canvas.pack(side=self.tk.BOTTOM)
self.image = None # Variable to store the loaded image
self.canvas_image = None # Reference to the image displayed on the canvas
self.canvas_max_width = None # Maximum allowed width for the canvas
self.canvas_max_height = None # Maximum allowed height for the canvas
self.rg_data = None # Data for region annotation management
self.current_box = None # Stores the currently selected bounding box
self.imgh = None # Height of the current image
self.imgw = None # Width of the current image
# Button frame with buttons
button_frame = self.tk.Frame(self.master)
button_frame.pack(side=self.tk.TOP)
for text, cmd in [
("Upload Image", self.upload_image),
("Remove Last Bounding Box", self.remove_last_bounding_box),
("Save", self.save_to_json),
]:
self.tk.Button(button_frame, text=text, command=cmd).pack(side=self.tk.LEFT)
self.initialize_properties()
self.master.mainloop()
def initialize_properties(self) -> None:
self.image = self.canvas_image = None
self.rg_data, self.current_box = [], []
self.imgw = self.imgh = 0
self.canvas_max_width, self.canvas_max_height = 1280, 720
def upload_image(self) -> None:
from PIL import Image, ImageTk # Scoped import because ImageTk requires tkinter package
file = self.filedialog.askopenfilename(filetypes=[("Image Files", "*.png *.jpg *.jpeg")])
if not file:
LOGGER.info("No image selected.")
return
self.image = Image.open(file)
self.imgw, self.imgh = self.image.size
aspect_ratio = self.imgw / self.imgh
canvas_width = (
min(self.canvas_max_width, self.imgw) if aspect_ratio > 1 else int(self.canvas_max_height * aspect_ratio)
)
canvas_height = (
min(self.canvas_max_height, self.imgh) if aspect_ratio <= 1 else int(canvas_width / aspect_ratio)
)
self.canvas.config(width=canvas_width, height=canvas_height)
self.canvas_image = ImageTk.PhotoImage(self.image.resize((canvas_width, canvas_height)))
self.canvas.create_image(0, 0, anchor=self.tk.NW, image=self.canvas_image)
self.canvas.bind("<Button-1>", self.on_canvas_click)
self.rg_data.clear(), self.current_box.clear()
def on_canvas_click(self, event) -> None:
self.current_box.append((event.x, event.y))
self.canvas.create_oval(event.x - 3, event.y - 3, event.x + 3, event.y + 3, fill="red")
if len(self.current_box) == 4:
self.rg_data.append(self.current_box.copy())
self.draw_box(self.current_box)
self.current_box.clear()
def draw_box(self, box: list[tuple[int, int]]) -> None:
for i in range(4):
self.canvas.create_line(box[i], box[(i + 1) % 4], fill="blue", width=2)
def remove_last_bounding_box(self) -> None:
if not self.rg_data:
self.messagebox.showwarning("Warning", "No bounding boxes to remove.")
return
self.rg_data.pop()
self.redraw_canvas()
def redraw_canvas(self) -> None:
self.canvas.delete("all")
self.canvas.create_image(0, 0, anchor=self.tk.NW, image=self.canvas_image)
for box in self.rg_data:
self.draw_box(box)
def save_to_json(self) -> None:
scale_w, scale_h = self.imgw / self.canvas.winfo_width(), self.imgh / self.canvas.winfo_height()
data = [{"points": [(int(x * scale_w), int(y * scale_h)) for x, y in box]} for box in self.rg_data]
from io import StringIO # Function level import, as it's only required to store coordinates
write_buffer = StringIO()
json.dump(data, write_buffer, indent=4)
with open("bounding_boxes.json", "w", encoding="utf-8") as f:
f.write(write_buffer.getvalue())
self.messagebox.showinfo("Success", "Bounding boxes saved to bounding_boxes.json")
class ParkingManagement(BaseSolution):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.json_file = self.CFG["json_file"] # Load parking regions JSON data
if not self.json_file:
LOGGER.warning("ParkingManagement requires `json_file` with parking region coordinates.")
raise ValueError("❌ JSON file path cannot be empty.")
with open(self.json_file, encoding="utf-8") as f:
self.json = json.load(f)
self.pr_info = {"Occupancy": 0, "Available": 0} # Dictionary for parking information
self.arc = (0, 0, 255) # Available region color
self.occ = (0, 255, 0) # Occupied region color
self.dc = (255, 0, 189) # Centroid color for each box
def process(self, im0: np.ndarray) -> SolutionResults:
self.extract_tracks(im0) # Extract tracks from im0
available_slots, occupied_slots = len(self.json), 0
annotator = SolutionAnnotator(im0, self.line_width) # Initialize annotator
for region in self.json:
# Convert points to a NumPy array with the correct dtype and reshape properly
region_polygon = np.array(region["points"], dtype=np.int32).reshape((-1, 1, 2))
region_occupied = False
for box, cls in zip(self.boxes, self.clss):
xc, yc = int((box[0] + box[2]) / 2), int((box[1] + box[3]) / 2)
inside_distance = cv2.pointPolygonTest(region_polygon, (xc, yc), False)
if inside_distance >= 0:
# cv2.circle(im0, (xc, yc), radius=self.line_width * 4, color=self.dc, thickness=-1)
annotator.display_objects_labels(
im0, self.model.names[int(cls)], (104, 31, 17), (255, 255, 255), xc, yc, 10
)
region_occupied = True
break
if region_occupied:
occupied_slots += 1
available_slots -= 1
# Plot regions
cv2.polylines(
im0, [region_polygon], isClosed=True, color=self.occ if region_occupied else self.arc, thickness=2
)
self.pr_info["Occupancy"], self.pr_info["Available"] = occupied_slots, available_slots
annotator.display_analytics(im0, self.pr_info, (104, 31, 17), (255, 255, 255), 10)
plot_im = annotator.result()
self.display_output(plot_im) # Display output with base class function
# Return SolutionResults
return SolutionResults(
plot_im=plot_im,
filled_slots=self.pr_info["Occupancy"],
available_slots=self.pr_info["Available"],
total_tracks=len(self.track_ids),
) | --- +++ @@ -14,8 +14,42 @@
class ParkingPtsSelection:
+ """A class for selecting and managing parking zone points on images using a Tkinter-based UI.
+
+ This class provides functionality to upload an image, select points to define parking zones, and save the selected
+ points to a JSON file. It uses Tkinter for the graphical user interface.
+
+ Attributes:
+ tk (module): The Tkinter module for GUI operations.
+ filedialog (module): Tkinter's filedialog module for file selection operations.
+ messagebox (module): Tkinter's messagebox module for displaying message boxes.
+ master (tk.Tk): The main Tkinter window.
+ canvas (tk.Canvas): The canvas widget for displaying the image and drawing bounding boxes.
+ image (PIL.Image.Image): The uploaded image.
+ canvas_image (ImageTk.PhotoImage): The image displayed on the canvas.
+ rg_data (list[list[tuple[int, int]]]): List of bounding boxes, each defined by 4 points.
+ current_box (list[tuple[int, int]]): Temporary storage for the points of the current bounding box.
+ imgw (int): Original width of the uploaded image.
+ imgh (int): Original height of the uploaded image.
+ canvas_max_width (int): Maximum width of the canvas.
+ canvas_max_height (int): Maximum height of the canvas.
+
+ Methods:
+ initialize_properties: Initialize properties for image, canvas, bounding boxes, and dimensions.
+ upload_image: Upload and display an image on the canvas, resizing it to fit within specified dimensions.
+ on_canvas_click: Handle mouse clicks to add points for bounding boxes on the canvas.
+ draw_box: Draw a bounding box on the canvas using the provided coordinates.
+ remove_last_bounding_box: Remove the last bounding box from the list and redraw the canvas.
+ redraw_canvas: Redraw the canvas with the image and all bounding boxes.
+ save_to_json: Save the selected parking zone points to a JSON file with scaled coordinates.
+
+ Examples:
+ >>> parking_selector = ParkingPtsSelection()
+ >>> # Use the GUI to upload an image, select parking zones, and save the data
+ """
def __init__(self) -> None:
+ """Initialize the ParkingPtsSelection class, setting up UI and properties for parking zone point selection."""
try: # Check if tkinter is installed
import tkinter as tk
from tkinter import filedialog, messagebox
@@ -67,12 +101,14 @@ self.master.mainloop()
def initialize_properties(self) -> None:
+ """Initialize properties for image, canvas, bounding boxes, and dimensions."""
self.image = self.canvas_image = None
self.rg_data, self.current_box = [], []
self.imgw = self.imgh = 0
self.canvas_max_width, self.canvas_max_height = 1280, 720
def upload_image(self) -> None:
+ """Upload and display an image on the canvas, resizing it to fit within specified dimensions."""
from PIL import Image, ImageTk # Scoped import because ImageTk requires tkinter package
file = self.filedialog.askopenfilename(filetypes=[("Image Files", "*.png *.jpg *.jpeg")])
@@ -98,6 +134,7 @@ self.rg_data.clear(), self.current_box.clear()
def on_canvas_click(self, event) -> None:
+ """Handle mouse clicks to add points for bounding boxes on the canvas."""
self.current_box.append((event.x, event.y))
self.canvas.create_oval(event.x - 3, event.y - 3, event.x + 3, event.y + 3, fill="red")
if len(self.current_box) == 4:
@@ -106,10 +143,12 @@ self.current_box.clear()
def draw_box(self, box: list[tuple[int, int]]) -> None:
+ """Draw a bounding box on the canvas using the provided coordinates."""
for i in range(4):
self.canvas.create_line(box[i], box[(i + 1) % 4], fill="blue", width=2)
def remove_last_bounding_box(self) -> None:
+ """Remove the last bounding box from the list and redraw the canvas."""
if not self.rg_data:
self.messagebox.showwarning("Warning", "No bounding boxes to remove.")
return
@@ -117,12 +156,14 @@ self.redraw_canvas()
def redraw_canvas(self) -> None:
+ """Redraw the canvas with the image and all bounding boxes."""
self.canvas.delete("all")
self.canvas.create_image(0, 0, anchor=self.tk.NW, image=self.canvas_image)
for box in self.rg_data:
self.draw_box(box)
def save_to_json(self) -> None:
+ """Save the selected parking zone points to a JSON file with scaled coordinates."""
scale_w, scale_h = self.imgw / self.canvas.winfo_width(), self.imgh / self.canvas.winfo_height()
data = [{"points": [(int(x * scale_w), int(y * scale_h)) for x, y in box]} for box in self.rg_data]
@@ -136,8 +177,31 @@
class ParkingManagement(BaseSolution):
+ """Manages parking occupancy and availability using YOLO model for real-time monitoring and visualization.
+
+ This class extends BaseSolution to provide functionality for parking lot management, including detection of occupied
+ spaces, visualization of parking regions, and display of occupancy statistics.
+
+ Attributes:
+ json_file (str): Path to the JSON file containing parking region details.
+ json (list[dict]): Loaded JSON data containing parking region information.
+ pr_info (dict[str, int]): Dictionary storing parking information (Occupancy and Available spaces).
+ arc (tuple[int, int, int]): BGR color tuple for available region visualization.
+ occ (tuple[int, int, int]): BGR color tuple for occupied region visualization.
+ dc (tuple[int, int, int]): BGR color tuple for centroid visualization of detected objects.
+
+ Methods:
+ process: Process the input image for parking lot management and visualization.
+
+ Examples:
+ >>> from ultralytics.solutions import ParkingManagement
+ >>> parking_manager = ParkingManagement(model="yolo26n.pt", json_file="parking_regions.json")
+ >>> print(f"Occupied spaces: {parking_manager.pr_info['Occupancy']}")
+ >>> print(f"Available spaces: {parking_manager.pr_info['Available']}")
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the parking management system with a YOLO model and visualization settings."""
super().__init__(**kwargs)
self.json_file = self.CFG["json_file"] # Load parking regions JSON data
@@ -155,6 +219,25 @@ self.dc = (255, 0, 189) # Centroid color for each box
def process(self, im0: np.ndarray) -> SolutionResults:
+ """Process the input image for parking lot management and visualization.
+
+ This function analyzes the input image, extracts tracks, and determines the occupancy status of parking regions
+ defined in the JSON file. It annotates the image with occupied and available parking spots, and updates the
+ parking information.
+
+ Args:
+ im0 (np.ndarray): The input inference image.
+
+ Returns:
+ (SolutionResults): Contains processed image `plot_im`, 'filled_slots' (number of occupied parking slots),
+ 'available_slots' (number of available parking slots), and 'total_tracks' (total number of
+ tracked objects).
+
+ Examples:
+ >>> parking_manager = ParkingManagement(json_file="parking_regions.json")
+ >>> image = cv2.imread("parking_lot.jpg")
+ >>> results = parking_manager.process(image)
+ """
self.extract_tracks(im0) # Extract tracks from im0
available_slots, occupied_slots = len(self.json), 0
annotator = SolutionAnnotator(im0, self.line_width) # Initialize annotator
@@ -194,4 +277,4 @@ filled_slots=self.pr_info["Occupancy"],
available_slots=self.pr_info["Available"],
total_tracks=len(self.track_ids),
- )+ )
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/parking_management.py |
Add detailed documentation for each class | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from collections import defaultdict
from typing import Any
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
from ultralytics.utils.plotting import colors
class ObjectCounter(BaseSolution):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.in_count = 0 # Counter for objects moving inward
self.out_count = 0 # Counter for objects moving outward
self.counted_ids = [] # List of IDs of objects that have been counted
self.classwise_count = defaultdict(lambda: {"IN": 0, "OUT": 0}) # Dictionary for counts, categorized by class
self.region_initialized = False # Flag indicating whether the region has been initialized
self.show_in = self.CFG["show_in"]
self.show_out = self.CFG["show_out"]
self.margin = self.line_width * 2 # Scales the background rectangle size to display counts properly
def count_objects(
self,
current_centroid: tuple[float, float],
track_id: int,
prev_position: tuple[float, float] | None,
cls: int,
) -> None:
if prev_position is None or track_id in self.counted_ids:
return
if len(self.region) == 2: # Linear region (defined as a line segment)
if self.r_s.intersects(self.LineString([prev_position, current_centroid])):
# Determine orientation of the region (vertical or horizontal)
if abs(self.region[0][0] - self.region[1][0]) < abs(self.region[0][1] - self.region[1][1]):
# Vertical region: Compare x-coordinates to determine direction
if current_centroid[0] > prev_position[0]: # Moving right
self.in_count += 1
self.classwise_count[self.names[cls]]["IN"] += 1
else: # Moving left
self.out_count += 1
self.classwise_count[self.names[cls]]["OUT"] += 1
# Horizontal region: Compare y-coordinates to determine direction
elif current_centroid[1] > prev_position[1]: # Moving downward
self.in_count += 1
self.classwise_count[self.names[cls]]["IN"] += 1
else: # Moving upward
self.out_count += 1
self.classwise_count[self.names[cls]]["OUT"] += 1
self.counted_ids.append(track_id)
elif len(self.region) > 2: # Polygonal region
if self.r_s.contains(self.Point(current_centroid)):
# Determine motion direction for vertical or horizontal polygons
region_width = max(p[0] for p in self.region) - min(p[0] for p in self.region)
region_height = max(p[1] for p in self.region) - min(p[1] for p in self.region)
if (region_width < region_height and current_centroid[0] > prev_position[0]) or (
region_width >= region_height and current_centroid[1] > prev_position[1]
): # Moving right or downward
self.in_count += 1
self.classwise_count[self.names[cls]]["IN"] += 1
else: # Moving left or upward
self.out_count += 1
self.classwise_count[self.names[cls]]["OUT"] += 1
self.counted_ids.append(track_id)
def display_counts(self, plot_im) -> None:
labels_dict = {
str.capitalize(key): f"{'IN ' + str(value['IN']) if self.show_in else ''} "
f"{'OUT ' + str(value['OUT']) if self.show_out else ''}".strip()
for key, value in self.classwise_count.items()
if (value["IN"] != 0 and self.show_in) or (value["OUT"] != 0 and self.show_out)
}
if labels_dict:
self.annotator.display_analytics(plot_im, labels_dict, (104, 31, 17), (255, 255, 255), self.margin)
def process(self, im0) -> SolutionResults:
if not self.region_initialized:
self.initialize_region()
self.region_initialized = True
self.extract_tracks(im0) # Extract tracks
self.annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator
self.annotator.draw_region(
reg_pts=self.region, color=(104, 0, 123), thickness=self.line_width * 2
) # Draw region
# Iterate over bounding boxes, track ids and classes index
for box, track_id, cls, conf in zip(self.boxes, self.track_ids, self.clss, self.confs):
# Draw bounding box and counting region
self.annotator.box_label(box, label=self.adjust_box_label(cls, conf, track_id), color=colors(cls, True))
self.store_tracking_history(track_id, box) # Store track history
# Store previous position of track for object counting
prev_position = None
if len(self.track_history[track_id]) > 1:
prev_position = self.track_history[track_id][-2]
self.count_objects(self.track_history[track_id][-1], track_id, prev_position, cls) # object counting
plot_im = self.annotator.result()
self.display_counts(plot_im) # Display the counts on the frame
self.display_output(plot_im) # Display output with base class function
# Return SolutionResults
return SolutionResults(
plot_im=plot_im,
in_count=self.in_count,
out_count=self.out_count,
classwise_count=dict(self.classwise_count),
total_tracks=len(self.track_ids),
) | --- +++ @@ -10,8 +10,35 @@
class ObjectCounter(BaseSolution):
+ """A class to manage the counting of objects in a real-time video stream based on their tracks.
+
+ This class extends the BaseSolution class and provides functionality for counting objects moving in and out of a
+ specified region in a video stream. It supports both polygonal and linear regions for counting.
+
+ Attributes:
+ in_count (int): Counter for objects moving inward.
+ out_count (int): Counter for objects moving outward.
+ counted_ids (list[int]): List of IDs of objects that have been counted.
+ classwise_count (dict[str, dict[str, int]]): Dictionary for counts, categorized by object class.
+ region_initialized (bool): Flag indicating whether the counting region has been initialized.
+ show_in (bool): Flag to control display of inward count.
+ show_out (bool): Flag to control display of outward count.
+ margin (int): Margin for background rectangle size to display counts properly.
+
+ Methods:
+ count_objects: Count objects within a polygonal or linear region based on their tracks.
+ display_counts: Display object counts on the frame.
+ process: Process input data and update counts.
+
+ Examples:
+ >>> counter = ObjectCounter()
+ >>> frame = cv2.imread("frame.jpg")
+ >>> results = counter.process(frame)
+ >>> print(f"Inward count: {counter.in_count}, Outward count: {counter.out_count}")
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the ObjectCounter class for real-time object counting in video streams."""
super().__init__(**kwargs)
self.in_count = 0 # Counter for objects moving inward
@@ -31,6 +58,23 @@ prev_position: tuple[float, float] | None,
cls: int,
) -> None:
+ """Count objects within a polygonal or linear region based on their tracks.
+
+ Args:
+ current_centroid (tuple[float, float]): Current centroid coordinates (x, y) in the current frame.
+ track_id (int): Unique identifier for the tracked object.
+ prev_position (tuple[float, float], optional): Last frame position coordinates (x, y) of the track.
+ cls (int): Class index for classwise count updates.
+
+ Examples:
+ >>> counter = ObjectCounter()
+ >>> track_line = {1: [100, 200], 2: [110, 210], 3: [120, 220]}
+ >>> box = [130, 230, 150, 250]
+ >>> track_id_num = 1
+ >>> previous_position = (120, 220)
+ >>> class_to_count = 0 # In COCO model, class 0 = person
+ >>> counter.count_objects((140, 240), track_id_num, previous_position, class_to_count)
+ """
if prev_position is None or track_id in self.counted_ids:
return
@@ -71,6 +115,16 @@ self.counted_ids.append(track_id)
def display_counts(self, plot_im) -> None:
+ """Display object counts on the input image or frame.
+
+ Args:
+ plot_im (np.ndarray): The image or frame to display counts on.
+
+ Examples:
+ >>> counter = ObjectCounter()
+ >>> frame = cv2.imread("image.jpg")
+ >>> counter.display_counts(frame)
+ """
labels_dict = {
str.capitalize(key): f"{'IN ' + str(value['IN']) if self.show_in else ''} "
f"{'OUT ' + str(value['OUT']) if self.show_out else ''}".strip()
@@ -81,6 +135,24 @@ self.annotator.display_analytics(plot_im, labels_dict, (104, 31, 17), (255, 255, 255), self.margin)
def process(self, im0) -> SolutionResults:
+ """Process input data (frames or object tracks) and update object counts.
+
+ This method initializes the counting region, extracts tracks, draws bounding boxes and regions, updates object
+ counts, and displays the results on the input image.
+
+ Args:
+ im0 (np.ndarray): The input image or frame to be processed.
+
+ Returns:
+ (SolutionResults): Contains processed image `im0`, 'in_count' (int, count of objects entering the region),
+ 'out_count' (int, count of objects exiting the region), 'classwise_count' (dict, per-class object
+ count), and 'total_tracks' (int, total number of tracked objects).
+
+ Examples:
+ >>> counter = ObjectCounter()
+ >>> frame = cv2.imread("path/to/image.jpg")
+ >>> results = counter.process(frame)
+ """
if not self.region_initialized:
self.initialize_region()
self.region_initialized = True
@@ -115,4 +187,4 @@ out_count=self.out_count,
classwise_count=dict(self.classwise_count),
total_tracks=len(self.track_ids),
- )+ )
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/object_counter.py |
Create documentation for each function signature | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from ultralytics.utils import LOGGER, SETTINGS, TESTS_RUNNING
try:
assert not TESTS_RUNNING # do not log pytest
assert SETTINGS["neptune"] is True # verify integration is enabled
import neptune
from neptune.types import File
assert hasattr(neptune, "__version__")
run = None # NeptuneAI experiment logger instance
except (ImportError, AssertionError):
neptune = None
def _log_scalars(scalars: dict, step: int = 0) -> None:
if run:
for k, v in scalars.items():
run[k].append(value=v, step=step)
def _log_images(imgs_dict: dict, group: str = "") -> None:
if run:
for k, v in imgs_dict.items():
run[f"{group}/{k}"].upload(File(v))
def _log_plot(title: str, plot_path: str) -> None:
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
img = mpimg.imread(plot_path)
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect="auto", xticks=[], yticks=[]) # no ticks
ax.imshow(img)
run[f"Plots/{title}"].upload(fig)
def on_pretrain_routine_start(trainer) -> None:
try:
global run
run = neptune.init_run(
project=trainer.args.project or "Ultralytics",
name=trainer.args.name,
tags=["Ultralytics"],
)
run["Configuration/Hyperparameters"] = {k: "" if v is None else v for k, v in vars(trainer.args).items()}
except Exception as e:
LOGGER.warning(f"NeptuneAI installed but not initialized correctly, not logging this run. {e}")
def on_train_epoch_end(trainer) -> None:
_log_scalars(trainer.label_loss_items(trainer.tloss, prefix="train"), trainer.epoch + 1)
_log_scalars(trainer.lr, trainer.epoch + 1)
if trainer.epoch == 1:
_log_images({f.stem: str(f) for f in trainer.save_dir.glob("train_batch*.jpg")}, "Mosaic")
def on_fit_epoch_end(trainer) -> None:
if run and trainer.epoch == 0:
from ultralytics.utils.torch_utils import model_info_for_loggers
run["Configuration/Model"] = model_info_for_loggers(trainer)
_log_scalars(trainer.metrics, trainer.epoch + 1)
def on_val_end(validator) -> None:
if run:
# Log val_labels and val_pred
_log_images({f.stem: str(f) for f in validator.save_dir.glob("val*.jpg")}, "Validation")
def on_train_end(trainer) -> None:
if run:
# Log final results, CM matrix + PR plots
for f in [*trainer.plots.keys(), *trainer.validator.plots.keys()]:
if "batch" not in f.name:
_log_plot(title=f.stem, plot_path=f)
# Log the final model
run[f"weights/{trainer.args.name or trainer.args.task}/{trainer.best.name}"].upload(File(str(trainer.best)))
callbacks = (
{
"on_pretrain_routine_start": on_pretrain_routine_start,
"on_train_epoch_end": on_train_epoch_end,
"on_fit_epoch_end": on_fit_epoch_end,
"on_val_end": on_val_end,
"on_train_end": on_train_end,
}
if neptune
else {}
) | --- +++ @@ -18,18 +18,42 @@
def _log_scalars(scalars: dict, step: int = 0) -> None:
+ """Log scalars to the NeptuneAI experiment logger.
+
+ Args:
+ scalars (dict): Dictionary of scalar values to log to NeptuneAI.
+ step (int, optional): The current step or iteration number for logging.
+
+ Examples:
+ >>> metrics = {"mAP": 0.85, "loss": 0.32}
+ >>> _log_scalars(metrics, step=100)
+ """
if run:
for k, v in scalars.items():
run[k].append(value=v, step=step)
def _log_images(imgs_dict: dict, group: str = "") -> None:
+ """Log images to the NeptuneAI experiment logger.
+
+ This function logs image data to Neptune.ai when a valid Neptune run is active. Images are organized under the
+ specified group name.
+
+ Args:
+ imgs_dict (dict): Dictionary of images to log, with keys as image names and values as image data.
+ group (str, optional): Group name to organize images under in the Neptune UI.
+
+ Examples:
+ >>> # Log validation images
+ >>> _log_images({"val_batch": img_tensor}, group="validation")
+ """
if run:
for k, v in imgs_dict.items():
run[f"{group}/{k}"].upload(File(v))
def _log_plot(title: str, plot_path: str) -> None:
+ """Log plots to the NeptuneAI experiment logger."""
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
@@ -41,6 +65,7 @@
def on_pretrain_routine_start(trainer) -> None:
+ """Initialize NeptuneAI run and log hyperparameters before training starts."""
try:
global run
run = neptune.init_run(
@@ -54,6 +79,7 @@
def on_train_epoch_end(trainer) -> None:
+ """Log training metrics and learning rate at the end of each training epoch."""
_log_scalars(trainer.label_loss_items(trainer.tloss, prefix="train"), trainer.epoch + 1)
_log_scalars(trainer.lr, trainer.epoch + 1)
if trainer.epoch == 1:
@@ -61,6 +87,7 @@
def on_fit_epoch_end(trainer) -> None:
+ """Log model info and validation metrics at the end of each fit epoch."""
if run and trainer.epoch == 0:
from ultralytics.utils.torch_utils import model_info_for_loggers
@@ -69,12 +96,14 @@
def on_val_end(validator) -> None:
+ """Log validation images at the end of validation."""
if run:
# Log val_labels and val_pred
_log_images({f.stem: str(f) for f in validator.save_dir.glob("val*.jpg")}, "Validation")
def on_train_end(trainer) -> None:
+ """Log final results, plots, and model weights at the end of training."""
if run:
# Log final results, CM matrix + PR plots
for f in [*trainer.plots.keys(), *trainer.validator.plots.keys()]:
@@ -94,4 +123,4 @@ }
if neptune
else {}
-)+)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/callbacks/neptune.py |
Add docstrings that explain inputs and outputs | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import torch
import torch.nn as nn
import torch.nn.functional as F
from ultralytics.utils.torch_utils import fuse_conv_and_bn
from .conv import Conv, DWConv, GhostConv, LightConv, RepConv, autopad
from .transformer import TransformerBlock
__all__ = (
"C1",
"C2",
"C2PSA",
"C3",
"C3TR",
"CIB",
"DFL",
"ELAN1",
"PSA",
"SPP",
"SPPELAN",
"SPPF",
"AConv",
"ADown",
"Attention",
"BNContrastiveHead",
"Bottleneck",
"BottleneckCSP",
"C2f",
"C2fAttn",
"C2fCIB",
"C2fPSA",
"C3Ghost",
"C3k2",
"C3x",
"CBFuse",
"CBLinear",
"ContrastiveHead",
"GhostBottleneck",
"HGBlock",
"HGStem",
"ImagePoolingAttn",
"Proto",
"RepC3",
"RepNCSPELAN4",
"RepVGGDW",
"ResNetLayer",
"SCDown",
"TorchVision",
)
class DFL(nn.Module):
def __init__(self, c1: int = 16):
super().__init__()
self.conv = nn.Conv2d(c1, 1, 1, bias=False).requires_grad_(False)
x = torch.arange(c1, dtype=torch.float)
self.conv.weight.data[:] = nn.Parameter(x.view(1, c1, 1, 1))
self.c1 = c1
def forward(self, x: torch.Tensor) -> torch.Tensor:
b, _, a = x.shape # batch, channels, anchors
return self.conv(x.view(b, 4, self.c1, a).transpose(2, 1).softmax(1)).view(b, 4, a)
# return self.conv(x.view(b, self.c1, 4, a).softmax(1)).view(b, 4, a)
class Proto(nn.Module):
def __init__(self, c1: int, c_: int = 256, c2: int = 32):
super().__init__()
self.cv1 = Conv(c1, c_, k=3)
self.upsample = nn.ConvTranspose2d(c_, c_, 2, 2, 0, bias=True) # nn.Upsample(scale_factor=2, mode='nearest')
self.cv2 = Conv(c_, c_, k=3)
self.cv3 = Conv(c_, c2)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.cv3(self.cv2(self.upsample(self.cv1(x))))
class HGStem(nn.Module):
def __init__(self, c1: int, cm: int, c2: int):
super().__init__()
self.stem1 = Conv(c1, cm, 3, 2, act=nn.ReLU())
self.stem2a = Conv(cm, cm // 2, 2, 1, 0, act=nn.ReLU())
self.stem2b = Conv(cm // 2, cm, 2, 1, 0, act=nn.ReLU())
self.stem3 = Conv(cm * 2, cm, 3, 2, act=nn.ReLU())
self.stem4 = Conv(cm, c2, 1, 1, act=nn.ReLU())
self.pool = nn.MaxPool2d(kernel_size=2, stride=1, padding=0, ceil_mode=True)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.stem1(x)
x = F.pad(x, [0, 1, 0, 1])
x2 = self.stem2a(x)
x2 = F.pad(x2, [0, 1, 0, 1])
x2 = self.stem2b(x2)
x1 = self.pool(x)
x = torch.cat([x1, x2], dim=1)
x = self.stem3(x)
x = self.stem4(x)
return x
class HGBlock(nn.Module):
def __init__(
self,
c1: int,
cm: int,
c2: int,
k: int = 3,
n: int = 6,
lightconv: bool = False,
shortcut: bool = False,
act: nn.Module = nn.ReLU(),
):
super().__init__()
block = LightConv if lightconv else Conv
self.m = nn.ModuleList(block(c1 if i == 0 else cm, cm, k=k, act=act) for i in range(n))
self.sc = Conv(c1 + n * cm, c2 // 2, 1, 1, act=act) # squeeze conv
self.ec = Conv(c2 // 2, c2, 1, 1, act=act) # excitation conv
self.add = shortcut and c1 == c2
def forward(self, x: torch.Tensor) -> torch.Tensor:
y = [x]
y.extend(m(y[-1]) for m in self.m)
y = self.ec(self.sc(torch.cat(y, 1)))
return y + x if self.add else y
class SPP(nn.Module):
def __init__(self, c1: int, c2: int, k: tuple[int, ...] = (5, 9, 13)):
super().__init__()
c_ = c1 // 2 # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.cv1(x)
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
class SPPF(nn.Module):
def __init__(self, c1: int, c2: int, k: int = 5, n: int = 3, shortcut: bool = False):
super().__init__()
c_ = c1 // 2 # hidden channels
self.cv1 = Conv(c1, c_, 1, 1, act=False)
self.cv2 = Conv(c_ * (n + 1), c2, 1, 1)
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
self.n = n
self.add = shortcut and c1 == c2
def forward(self, x: torch.Tensor) -> torch.Tensor:
y = [self.cv1(x)]
y.extend(self.m(y[-1]) for _ in range(getattr(self, "n", 3)))
y = self.cv2(torch.cat(y, 1))
return y + x if getattr(self, "add", False) else y
class C1(nn.Module):
def __init__(self, c1: int, c2: int, n: int = 1):
super().__init__()
self.cv1 = Conv(c1, c2, 1, 1)
self.m = nn.Sequential(*(Conv(c2, c2, 3) for _ in range(n)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
y = self.cv1(x)
return self.m(y) + y
class C2(nn.Module):
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
super().__init__()
self.c = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, 2 * self.c, 1, 1)
self.cv2 = Conv(2 * self.c, c2, 1) # optional act=FReLU(c2)
# self.attention = ChannelAttention(2 * self.c) # or SpatialAttention()
self.m = nn.Sequential(*(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
a, b = self.cv1(x).chunk(2, 1)
return self.cv2(torch.cat((self.m(a), b), 1))
class C2f(nn.Module):
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = False, g: int = 1, e: float = 0.5):
super().__init__()
self.c = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, 2 * self.c, 1, 1)
self.cv2 = Conv((2 + n) * self.c, c2, 1) # optional act=FReLU(c2)
self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
def forward(self, x: torch.Tensor) -> torch.Tensor:
y = list(self.cv1(x).chunk(2, 1))
y.extend(m(y[-1]) for m in self.m)
return self.cv2(torch.cat(y, 1))
def forward_split(self, x: torch.Tensor) -> torch.Tensor:
y = self.cv1(x).split((self.c, self.c), 1)
y = [y[0], y[1]]
y.extend(m(y[-1]) for m in self.m)
return self.cv2(torch.cat(y, 1))
class C3(nn.Module):
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c1, c_, 1, 1)
self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
class C3x(C3):
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
super().__init__(c1, c2, n, shortcut, g, e)
self.c_ = int(c2 * e)
self.m = nn.Sequential(*(Bottleneck(self.c_, self.c_, shortcut, g, k=((1, 3), (3, 1)), e=1) for _ in range(n)))
class RepC3(nn.Module):
def __init__(self, c1: int, c2: int, n: int = 3, e: float = 1.0):
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c1, c_, 1, 1)
self.m = nn.Sequential(*[RepConv(c_, c_) for _ in range(n)])
self.cv3 = Conv(c_, c2, 1, 1) if c_ != c2 else nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.cv3(self.m(self.cv1(x)) + self.cv2(x))
class C3TR(C3):
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e)
self.m = TransformerBlock(c_, c_, 4, n)
class C3Ghost(C3):
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e) # hidden channels
self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
class GhostBottleneck(nn.Module):
def __init__(self, c1: int, c2: int, k: int = 3, s: int = 1):
super().__init__()
c_ = c2 // 2
self.conv = nn.Sequential(
GhostConv(c1, c_, 1, 1), # pw
DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
GhostConv(c_, c2, 1, 1, act=False), # pw-linear
)
self.shortcut = (
nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.conv(x) + self.shortcut(x)
class Bottleneck(nn.Module):
def __init__(
self, c1: int, c2: int, shortcut: bool = True, g: int = 1, k: tuple[int, int] = (3, 3), e: float = 0.5
):
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, k[0], 1)
self.cv2 = Conv(c_, c2, k[1], 1, g=g)
self.add = shortcut and c1 == c2
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
class BottleneckCSP(nn.Module):
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
self.cv4 = Conv(2 * c_, c2, 1, 1)
self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
self.act = nn.SiLU()
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
y1 = self.cv3(self.m(self.cv1(x)))
y2 = self.cv2(x)
return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
class ResNetBlock(nn.Module):
def __init__(self, c1: int, c2: int, s: int = 1, e: int = 4):
super().__init__()
c3 = e * c2
self.cv1 = Conv(c1, c2, k=1, s=1, act=True)
self.cv2 = Conv(c2, c2, k=3, s=s, p=1, act=True)
self.cv3 = Conv(c2, c3, k=1, act=False)
self.shortcut = nn.Sequential(Conv(c1, c3, k=1, s=s, act=False)) if s != 1 or c1 != c3 else nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return F.relu(self.cv3(self.cv2(self.cv1(x))) + self.shortcut(x))
class ResNetLayer(nn.Module):
def __init__(self, c1: int, c2: int, s: int = 1, is_first: bool = False, n: int = 1, e: int = 4):
super().__init__()
self.is_first = is_first
if self.is_first:
self.layer = nn.Sequential(
Conv(c1, c2, k=7, s=2, p=3, act=True), nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
)
else:
blocks = [ResNetBlock(c1, c2, s, e=e)]
blocks.extend([ResNetBlock(e * c2, c2, 1, e=e) for _ in range(n - 1)])
self.layer = nn.Sequential(*blocks)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.layer(x)
class MaxSigmoidAttnBlock(nn.Module):
def __init__(self, c1: int, c2: int, nh: int = 1, ec: int = 128, gc: int = 512, scale: bool = False):
super().__init__()
self.nh = nh
self.hc = c2 // nh
self.ec = Conv(c1, ec, k=1, act=False) if c1 != ec else None
self.gl = nn.Linear(gc, ec)
self.bias = nn.Parameter(torch.zeros(nh))
self.proj_conv = Conv(c1, c2, k=3, s=1, act=False)
self.scale = nn.Parameter(torch.ones(1, nh, 1, 1)) if scale else 1.0
def forward(self, x: torch.Tensor, guide: torch.Tensor) -> torch.Tensor:
bs, _, h, w = x.shape
guide = self.gl(guide)
guide = guide.view(bs, guide.shape[1], self.nh, self.hc)
embed = self.ec(x) if self.ec is not None else x
embed = embed.view(bs, self.nh, self.hc, h, w)
aw = torch.einsum("bmchw,bnmc->bmhwn", embed, guide)
aw = aw.max(dim=-1)[0]
aw = aw / (self.hc**0.5)
aw = aw + self.bias[None, :, None, None]
aw = aw.sigmoid() * self.scale
x = self.proj_conv(x)
x = x.view(bs, self.nh, -1, h, w)
x = x * aw.unsqueeze(2)
return x.view(bs, -1, h, w)
class C2fAttn(nn.Module):
def __init__(
self,
c1: int,
c2: int,
n: int = 1,
ec: int = 128,
nh: int = 1,
gc: int = 512,
shortcut: bool = False,
g: int = 1,
e: float = 0.5,
):
super().__init__()
self.c = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, 2 * self.c, 1, 1)
self.cv2 = Conv((3 + n) * self.c, c2, 1) # optional act=FReLU(c2)
self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
self.attn = MaxSigmoidAttnBlock(self.c, self.c, gc=gc, ec=ec, nh=nh)
def forward(self, x: torch.Tensor, guide: torch.Tensor) -> torch.Tensor:
y = list(self.cv1(x).chunk(2, 1))
y.extend(m(y[-1]) for m in self.m)
y.append(self.attn(y[-1], guide))
return self.cv2(torch.cat(y, 1))
def forward_split(self, x: torch.Tensor, guide: torch.Tensor) -> torch.Tensor:
y = list(self.cv1(x).split((self.c, self.c), 1))
y.extend(m(y[-1]) for m in self.m)
y.append(self.attn(y[-1], guide))
return self.cv2(torch.cat(y, 1))
class ImagePoolingAttn(nn.Module):
def __init__(
self, ec: int = 256, ch: tuple[int, ...] = (), ct: int = 512, nh: int = 8, k: int = 3, scale: bool = False
):
super().__init__()
nf = len(ch)
self.query = nn.Sequential(nn.LayerNorm(ct), nn.Linear(ct, ec))
self.key = nn.Sequential(nn.LayerNorm(ec), nn.Linear(ec, ec))
self.value = nn.Sequential(nn.LayerNorm(ec), nn.Linear(ec, ec))
self.proj = nn.Linear(ec, ct)
self.scale = nn.Parameter(torch.tensor([0.0]), requires_grad=True) if scale else 1.0
self.projections = nn.ModuleList([nn.Conv2d(in_channels, ec, kernel_size=1) for in_channels in ch])
self.im_pools = nn.ModuleList([nn.AdaptiveMaxPool2d((k, k)) for _ in range(nf)])
self.ec = ec
self.nh = nh
self.nf = nf
self.hc = ec // nh
self.k = k
def forward(self, x: list[torch.Tensor], text: torch.Tensor) -> torch.Tensor:
bs = x[0].shape[0]
assert len(x) == self.nf
num_patches = self.k**2
x = [pool(proj(x)).view(bs, -1, num_patches) for (x, proj, pool) in zip(x, self.projections, self.im_pools)]
x = torch.cat(x, dim=-1).transpose(1, 2)
q = self.query(text)
k = self.key(x)
v = self.value(x)
# q = q.reshape(1, text.shape[1], self.nh, self.hc).repeat(bs, 1, 1, 1)
q = q.reshape(bs, -1, self.nh, self.hc)
k = k.reshape(bs, -1, self.nh, self.hc)
v = v.reshape(bs, -1, self.nh, self.hc)
aw = torch.einsum("bnmc,bkmc->bmnk", q, k)
aw = aw / (self.hc**0.5)
aw = F.softmax(aw, dim=-1)
x = torch.einsum("bmnk,bkmc->bnmc", aw, v)
x = self.proj(x.reshape(bs, -1, self.ec))
return x * self.scale + text
class ContrastiveHead(nn.Module):
def __init__(self):
super().__init__()
# NOTE: use -10.0 to keep the init cls loss consistency with other losses
self.bias = nn.Parameter(torch.tensor([-10.0]))
self.logit_scale = nn.Parameter(torch.ones([]) * torch.tensor(1 / 0.07).log())
def forward(self, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
x = F.normalize(x, dim=1, p=2)
w = F.normalize(w, dim=-1, p=2)
x = torch.einsum("bchw,bkc->bkhw", x, w)
return x * self.logit_scale.exp() + self.bias
class BNContrastiveHead(nn.Module):
def __init__(self, embed_dims: int):
super().__init__()
self.norm = nn.BatchNorm2d(embed_dims)
# NOTE: use -10.0 to keep the init cls loss consistency with other losses
self.bias = nn.Parameter(torch.tensor([-10.0]))
# use -1.0 is more stable
self.logit_scale = nn.Parameter(-1.0 * torch.ones([]))
def fuse(self):
del self.norm
del self.bias
del self.logit_scale
self.forward = self.forward_fuse
@staticmethod
def forward_fuse(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
return x
def forward(self, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
x = self.norm(x)
w = F.normalize(w, dim=-1, p=2)
x = torch.einsum("bchw,bkc->bkhw", x, w)
return x * self.logit_scale.exp() + self.bias
class RepBottleneck(Bottleneck):
def __init__(
self, c1: int, c2: int, shortcut: bool = True, g: int = 1, k: tuple[int, int] = (3, 3), e: float = 0.5
):
super().__init__(c1, c2, shortcut, g, k, e)
c_ = int(c2 * e) # hidden channels
self.cv1 = RepConv(c1, c_, k[0], 1)
class RepCSP(C3):
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e) # hidden channels
self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
class RepNCSPELAN4(nn.Module):
def __init__(self, c1: int, c2: int, c3: int, c4: int, n: int = 1):
super().__init__()
self.c = c3 // 2
self.cv1 = Conv(c1, c3, 1, 1)
self.cv2 = nn.Sequential(RepCSP(c3 // 2, c4, n), Conv(c4, c4, 3, 1))
self.cv3 = nn.Sequential(RepCSP(c4, c4, n), Conv(c4, c4, 3, 1))
self.cv4 = Conv(c3 + (2 * c4), c2, 1, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
y = list(self.cv1(x).chunk(2, 1))
y.extend((m(y[-1])) for m in [self.cv2, self.cv3])
return self.cv4(torch.cat(y, 1))
def forward_split(self, x: torch.Tensor) -> torch.Tensor:
y = list(self.cv1(x).split((self.c, self.c), 1))
y.extend(m(y[-1]) for m in [self.cv2, self.cv3])
return self.cv4(torch.cat(y, 1))
class ELAN1(RepNCSPELAN4):
def __init__(self, c1: int, c2: int, c3: int, c4: int):
super().__init__(c1, c2, c3, c4)
self.c = c3 // 2
self.cv1 = Conv(c1, c3, 1, 1)
self.cv2 = Conv(c3 // 2, c4, 3, 1)
self.cv3 = Conv(c4, c4, 3, 1)
self.cv4 = Conv(c3 + (2 * c4), c2, 1, 1)
class AConv(nn.Module):
def __init__(self, c1: int, c2: int):
super().__init__()
self.cv1 = Conv(c1, c2, 3, 2, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = torch.nn.functional.avg_pool2d(x, 2, 1, 0, False, True)
return self.cv1(x)
class ADown(nn.Module):
def __init__(self, c1: int, c2: int):
super().__init__()
self.c = c2 // 2
self.cv1 = Conv(c1 // 2, self.c, 3, 2, 1)
self.cv2 = Conv(c1 // 2, self.c, 1, 1, 0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = torch.nn.functional.avg_pool2d(x, 2, 1, 0, False, True)
x1, x2 = x.chunk(2, 1)
x1 = self.cv1(x1)
x2 = torch.nn.functional.max_pool2d(x2, 3, 2, 1)
x2 = self.cv2(x2)
return torch.cat((x1, x2), 1)
class SPPELAN(nn.Module):
def __init__(self, c1: int, c2: int, c3: int, k: int = 5):
super().__init__()
self.c = c3
self.cv1 = Conv(c1, c3, 1, 1)
self.cv2 = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
self.cv3 = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
self.cv4 = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
self.cv5 = Conv(4 * c3, c2, 1, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
y = [self.cv1(x)]
y.extend(m(y[-1]) for m in [self.cv2, self.cv3, self.cv4])
return self.cv5(torch.cat(y, 1))
class CBLinear(nn.Module):
def __init__(self, c1: int, c2s: list[int], k: int = 1, s: int = 1, p: int | None = None, g: int = 1):
super().__init__()
self.c2s = c2s
self.conv = nn.Conv2d(c1, sum(c2s), k, s, autopad(k, p), groups=g, bias=True)
def forward(self, x: torch.Tensor) -> list[torch.Tensor]:
return self.conv(x).split(self.c2s, dim=1)
class CBFuse(nn.Module):
def __init__(self, idx: list[int]):
super().__init__()
self.idx = idx
def forward(self, xs: list[torch.Tensor]) -> torch.Tensor:
target_size = xs[-1].shape[2:]
res = [F.interpolate(x[self.idx[i]], size=target_size, mode="nearest") for i, x in enumerate(xs[:-1])]
return torch.sum(torch.stack(res + xs[-1:]), dim=0)
class C3f(nn.Module):
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = False, g: int = 1, e: float = 0.5):
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c1, c_, 1, 1)
self.cv3 = Conv((2 + n) * c_, c2, 1) # optional act=FReLU(c2)
self.m = nn.ModuleList(Bottleneck(c_, c_, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
def forward(self, x: torch.Tensor) -> torch.Tensor:
y = [self.cv2(x), self.cv1(x)]
y.extend(m(y[-1]) for m in self.m)
return self.cv3(torch.cat(y, 1))
class C3k2(C2f):
def __init__(
self,
c1: int,
c2: int,
n: int = 1,
c3k: bool = False,
e: float = 0.5,
attn: bool = False,
g: int = 1,
shortcut: bool = True,
):
super().__init__(c1, c2, n, shortcut, g, e)
self.m = nn.ModuleList(
nn.Sequential(
Bottleneck(self.c, self.c, shortcut, g),
PSABlock(self.c, attn_ratio=0.5, num_heads=max(self.c // 64, 1)),
)
if attn
else C3k(self.c, self.c, 2, shortcut, g)
if c3k
else Bottleneck(self.c, self.c, shortcut, g)
for _ in range(n)
)
class C3k(C3):
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5, k: int = 3):
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e) # hidden channels
# self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
class RepVGGDW(torch.nn.Module):
def __init__(self, ed: int) -> None:
super().__init__()
self.conv = Conv(ed, ed, 7, 1, 3, g=ed, act=False)
self.conv1 = Conv(ed, ed, 3, 1, 1, g=ed, act=False)
self.dim = ed
self.act = nn.SiLU()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.act(self.conv(x) + self.conv1(x))
def forward_fuse(self, x: torch.Tensor) -> torch.Tensor:
return self.act(self.conv(x))
@torch.no_grad()
def fuse(self):
if not hasattr(self, "conv1"):
return # already fused
conv = fuse_conv_and_bn(self.conv.conv, self.conv.bn)
conv1 = fuse_conv_and_bn(self.conv1.conv, self.conv1.bn)
conv_w = conv.weight
conv_b = conv.bias
conv1_w = conv1.weight
conv1_b = conv1.bias
conv1_w = torch.nn.functional.pad(conv1_w, [2, 2, 2, 2])
final_conv_w = conv_w + conv1_w
final_conv_b = conv_b + conv1_b
conv.weight.data.copy_(final_conv_w)
conv.bias.data.copy_(final_conv_b)
self.conv = conv
del self.conv1
class CIB(nn.Module):
def __init__(self, c1: int, c2: int, shortcut: bool = True, e: float = 0.5, lk: bool = False):
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = nn.Sequential(
Conv(c1, c1, 3, g=c1),
Conv(c1, 2 * c_, 1),
RepVGGDW(2 * c_) if lk else Conv(2 * c_, 2 * c_, 3, g=2 * c_),
Conv(2 * c_, c2, 1),
Conv(c2, c2, 3, g=c2),
)
self.add = shortcut and c1 == c2
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x + self.cv1(x) if self.add else self.cv1(x)
class C2fCIB(C2f):
def __init__(
self, c1: int, c2: int, n: int = 1, shortcut: bool = False, lk: bool = False, g: int = 1, e: float = 0.5
):
super().__init__(c1, c2, n, shortcut, g, e)
self.m = nn.ModuleList(CIB(self.c, self.c, shortcut, e=1.0, lk=lk) for _ in range(n))
class Attention(nn.Module):
def __init__(self, dim: int, num_heads: int = 8, attn_ratio: float = 0.5):
super().__init__()
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.key_dim = int(self.head_dim * attn_ratio)
self.scale = self.key_dim**-0.5
nh_kd = self.key_dim * num_heads
h = dim + nh_kd * 2
self.qkv = Conv(dim, h, 1, act=False)
self.proj = Conv(dim, dim, 1, act=False)
self.pe = Conv(dim, dim, 3, 1, g=dim, act=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, C, H, W = x.shape
N = H * W
qkv = self.qkv(x)
q, k, v = qkv.view(B, self.num_heads, self.key_dim * 2 + self.head_dim, N).split(
[self.key_dim, self.key_dim, self.head_dim], dim=2
)
attn = (q.transpose(-2, -1) @ k) * self.scale
attn = attn.softmax(dim=-1)
x = (v @ attn.transpose(-2, -1)).view(B, C, H, W) + self.pe(v.reshape(B, C, H, W))
x = self.proj(x)
return x
class PSABlock(nn.Module):
def __init__(self, c: int, attn_ratio: float = 0.5, num_heads: int = 4, shortcut: bool = True) -> None:
super().__init__()
self.attn = Attention(c, attn_ratio=attn_ratio, num_heads=num_heads)
self.ffn = nn.Sequential(Conv(c, c * 2, 1), Conv(c * 2, c, 1, act=False))
self.add = shortcut
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = x + self.attn(x) if self.add else self.attn(x)
x = x + self.ffn(x) if self.add else self.ffn(x)
return x
class PSA(nn.Module):
def __init__(self, c1: int, c2: int, e: float = 0.5):
super().__init__()
assert c1 == c2
self.c = int(c1 * e)
self.cv1 = Conv(c1, 2 * self.c, 1, 1)
self.cv2 = Conv(2 * self.c, c1, 1)
self.attn = Attention(self.c, attn_ratio=0.5, num_heads=max(self.c // 64, 1))
self.ffn = nn.Sequential(Conv(self.c, self.c * 2, 1), Conv(self.c * 2, self.c, 1, act=False))
def forward(self, x: torch.Tensor) -> torch.Tensor:
a, b = self.cv1(x).split((self.c, self.c), dim=1)
b = b + self.attn(b)
b = b + self.ffn(b)
return self.cv2(torch.cat((a, b), 1))
class C2PSA(nn.Module):
def __init__(self, c1: int, c2: int, n: int = 1, e: float = 0.5):
super().__init__()
assert c1 == c2
self.c = int(c1 * e)
self.cv1 = Conv(c1, 2 * self.c, 1, 1)
self.cv2 = Conv(2 * self.c, c1, 1)
self.m = nn.Sequential(*(PSABlock(self.c, attn_ratio=0.5, num_heads=self.c // 64) for _ in range(n)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
a, b = self.cv1(x).split((self.c, self.c), dim=1)
b = self.m(b)
return self.cv2(torch.cat((a, b), 1))
class C2fPSA(C2f):
def __init__(self, c1: int, c2: int, n: int = 1, e: float = 0.5):
assert c1 == c2
super().__init__(c1, c2, n=n, e=e)
self.m = nn.ModuleList(PSABlock(self.c, attn_ratio=0.5, num_heads=max(self.c // 64, 1)) for _ in range(n))
class SCDown(nn.Module):
def __init__(self, c1: int, c2: int, k: int, s: int):
super().__init__()
self.cv1 = Conv(c1, c2, 1, 1)
self.cv2 = Conv(c2, c2, k=k, s=s, g=c2, act=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.cv2(self.cv1(x))
class TorchVision(nn.Module):
def __init__(
self, model: str, weights: str = "DEFAULT", unwrap: bool = True, truncate: int = 2, split: bool = False
):
import torchvision # scope for faster 'import ultralytics'
super().__init__()
if hasattr(torchvision.models, "get_model"):
self.m = torchvision.models.get_model(model, weights=weights)
else:
self.m = torchvision.models.__dict__[model](pretrained=bool(weights))
if unwrap:
layers = list(self.m.children())
if isinstance(layers[0], nn.Sequential): # Second-level for some models like EfficientNet, Swin
layers = [*list(layers[0].children()), *layers[1:]]
self.m = nn.Sequential(*(layers[:-truncate] if truncate else layers))
self.split = split
else:
self.split = False
self.m.head = self.m.heads = nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.split:
y = [x]
y.extend(m(y[-1]) for m in self.m)
else:
y = self.m(x)
return y
class AAttn(nn.Module):
def __init__(self, dim: int, num_heads: int, area: int = 1):
super().__init__()
self.area = area
self.num_heads = num_heads
self.head_dim = head_dim = dim // num_heads
all_head_dim = head_dim * self.num_heads
self.qkv = Conv(dim, all_head_dim * 3, 1, act=False)
self.proj = Conv(all_head_dim, dim, 1, act=False)
self.pe = Conv(all_head_dim, dim, 7, 1, 3, g=dim, act=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, C, H, W = x.shape
N = H * W
qkv = self.qkv(x).flatten(2).transpose(1, 2)
if self.area > 1:
qkv = qkv.reshape(B * self.area, N // self.area, C * 3)
B, N, _ = qkv.shape
q, k, v = (
qkv.view(B, N, self.num_heads, self.head_dim * 3)
.permute(0, 2, 3, 1)
.split([self.head_dim, self.head_dim, self.head_dim], dim=2)
)
attn = (q.transpose(-2, -1) @ k) * (self.head_dim**-0.5)
attn = attn.softmax(dim=-1)
x = v @ attn.transpose(-2, -1)
x = x.permute(0, 3, 1, 2)
v = v.permute(0, 3, 1, 2)
if self.area > 1:
x = x.reshape(B // self.area, N * self.area, C)
v = v.reshape(B // self.area, N * self.area, C)
B, N, _ = x.shape
x = x.reshape(B, H, W, C).permute(0, 3, 1, 2).contiguous()
v = v.reshape(B, H, W, C).permute(0, 3, 1, 2).contiguous()
x = x + self.pe(v)
return self.proj(x)
class ABlock(nn.Module):
def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 1.2, area: int = 1):
super().__init__()
self.attn = AAttn(dim, num_heads=num_heads, area=area)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = nn.Sequential(Conv(dim, mlp_hidden_dim, 1), Conv(mlp_hidden_dim, dim, 1, act=False))
self.apply(self._init_weights)
@staticmethod
def _init_weights(m: nn.Module):
if isinstance(m, nn.Conv2d):
nn.init.trunc_normal_(m.weight, std=0.02)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = x + self.attn(x)
return x + self.mlp(x)
class A2C2f(nn.Module):
def __init__(
self,
c1: int,
c2: int,
n: int = 1,
a2: bool = True,
area: int = 1,
residual: bool = False,
mlp_ratio: float = 2.0,
e: float = 0.5,
g: int = 1,
shortcut: bool = True,
):
super().__init__()
c_ = int(c2 * e) # hidden channels
assert c_ % 32 == 0, "Dimension of ABlock must be a multiple of 32."
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv((1 + n) * c_, c2, 1)
self.gamma = nn.Parameter(0.01 * torch.ones(c2), requires_grad=True) if a2 and residual else None
self.m = nn.ModuleList(
nn.Sequential(*(ABlock(c_, c_ // 32, mlp_ratio, area) for _ in range(2)))
if a2
else C3k(c_, c_, 2, shortcut, g)
for _ in range(n)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
y = [self.cv1(x)]
y.extend(m(y[-1]) for m in self.m)
y = self.cv2(torch.cat(y, 1))
if self.gamma is not None:
return x + self.gamma.view(-1, self.gamma.shape[0], 1, 1) * y
return y
class SwiGLUFFN(nn.Module):
def __init__(self, gc: int, ec: int, e: int = 4) -> None:
super().__init__()
self.w12 = nn.Linear(gc, e * ec)
self.w3 = nn.Linear(e * ec // 2, ec)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x12 = self.w12(x)
x1, x2 = x12.chunk(2, dim=-1)
hidden = F.silu(x1) * x2
return self.w3(hidden)
class Residual(nn.Module):
def __init__(self, m: nn.Module) -> None:
super().__init__()
self.m = m
nn.init.zeros_(self.m.w3.bias)
# For models with l scale, please change the initialization to
# nn.init.constant_(self.m.w3.weight, 1e-6)
nn.init.zeros_(self.m.w3.weight)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x + self.m(x)
class SAVPE(nn.Module):
def __init__(self, ch: list[int], c3: int, embed: int):
super().__init__()
self.cv1 = nn.ModuleList(
nn.Sequential(
Conv(x, c3, 3), Conv(c3, c3, 3), nn.Upsample(scale_factor=i * 2) if i in {1, 2} else nn.Identity()
)
for i, x in enumerate(ch)
)
self.cv2 = nn.ModuleList(
nn.Sequential(Conv(x, c3, 1), nn.Upsample(scale_factor=i * 2) if i in {1, 2} else nn.Identity())
for i, x in enumerate(ch)
)
self.c = 16
self.cv3 = nn.Conv2d(3 * c3, embed, 1)
self.cv4 = nn.Conv2d(3 * c3, self.c, 3, padding=1)
self.cv5 = nn.Conv2d(1, self.c, 3, padding=1)
self.cv6 = nn.Sequential(Conv(2 * self.c, self.c, 3), nn.Conv2d(self.c, self.c, 3, padding=1))
def forward(self, x: list[torch.Tensor], vp: torch.Tensor) -> torch.Tensor:
y = [self.cv2[i](xi) for i, xi in enumerate(x)]
y = self.cv4(torch.cat(y, dim=1))
x = [self.cv1[i](xi) for i, xi in enumerate(x)]
x = self.cv3(torch.cat(x, dim=1))
B, C, H, W = x.shape
Q = vp.shape[1]
x = x.view(B, C, -1)
y = y.reshape(B, 1, self.c, H, W).expand(-1, Q, -1, -1, -1).reshape(B * Q, self.c, H, W)
vp = vp.reshape(B, Q, 1, H, W).reshape(B * Q, 1, H, W)
y = self.cv6(torch.cat((y, self.cv5(vp)), dim=1))
y = y.reshape(B, Q, self.c, -1)
vp = vp.reshape(B, Q, 1, -1)
score = y * vp + torch.logical_not(vp) * torch.finfo(y.dtype).min
score = F.softmax(score, dim=-1).to(y.dtype)
aggregated = score.transpose(-2, -3) @ x.reshape(B, self.c, C // self.c, -1).transpose(-1, -2)
return F.normalize(aggregated.transpose(-2, -3).reshape(B, Q, -1), dim=-1, p=2)
class Proto26(Proto):
def __init__(self, ch: tuple = (), c_: int = 256, c2: int = 32, nc: int = 80):
super().__init__(c_, c_, c2)
self.feat_refine = nn.ModuleList(Conv(x, ch[0], k=1) for x in ch[1:])
self.feat_fuse = Conv(ch[0], c_, k=3)
self.semseg = nn.Sequential(Conv(ch[0], c_, k=3), Conv(c_, c_, k=3), nn.Conv2d(c_, nc, 1))
def forward(self, x: torch.Tensor, return_semseg: bool = True) -> torch.Tensor:
feat = x[0]
for i, f in enumerate(self.feat_refine):
up_feat = f(x[i + 1])
up_feat = F.interpolate(up_feat, size=feat.shape[2:], mode="nearest")
feat = feat + up_feat
p = super().forward(self.feat_fuse(feat))
if self.training and return_semseg:
semseg = self.semseg(feat)
return (p, semseg)
return p
def fuse(self):
self.semseg = None
class RealNVP(nn.Module):
@staticmethod
def nets():
return nn.Sequential(nn.Linear(2, 64), nn.SiLU(), nn.Linear(64, 64), nn.SiLU(), nn.Linear(64, 2), nn.Tanh())
@staticmethod
def nett():
return nn.Sequential(nn.Linear(2, 64), nn.SiLU(), nn.Linear(64, 64), nn.SiLU(), nn.Linear(64, 2))
@property
def prior(self):
return torch.distributions.MultivariateNormal(self.loc, self.cov)
def __init__(self):
super().__init__()
self.register_buffer("loc", torch.zeros(2))
self.register_buffer("cov", torch.eye(2))
self.register_buffer("mask", torch.tensor([[0, 1], [1, 0]] * 3, dtype=torch.float32))
self.s = torch.nn.ModuleList([self.nets() for _ in range(len(self.mask))])
self.t = torch.nn.ModuleList([self.nett() for _ in range(len(self.mask))])
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight, gain=0.01)
def backward_p(self, x):
log_det_jacob, z = x.new_zeros(x.shape[0]), x
for i in reversed(range(len(self.t))):
z_ = self.mask[i] * z
s = self.s[i](z_) * (1 - self.mask[i])
t = self.t[i](z_) * (1 - self.mask[i])
z = (1 - self.mask[i]) * (z - t) * torch.exp(-s) + z_
log_det_jacob -= s.sum(dim=1)
return z, log_det_jacob
def log_prob(self, x):
if x.dtype == torch.float32 and self.s[0][0].weight.dtype != torch.float32:
self.float()
z, log_det = self.backward_p(x)
return self.prior.log_prob(z) + log_det | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Block modules."""
from __future__ import annotations
@@ -55,8 +56,17 @@
class DFL(nn.Module):
+ """Integral module of Distribution Focal Loss (DFL).
+
+ Proposed in Generalized Focal Loss https://ieeexplore.ieee.org/document/9792391
+ """
def __init__(self, c1: int = 16):
+ """Initialize a convolutional layer with a given number of input channels.
+
+ Args:
+ c1 (int): Number of input channels.
+ """
super().__init__()
self.conv = nn.Conv2d(c1, 1, 1, bias=False).requires_grad_(False)
x = torch.arange(c1, dtype=torch.float)
@@ -64,14 +74,23 @@ self.c1 = c1
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply the DFL module to input tensor and return transformed output."""
b, _, a = x.shape # batch, channels, anchors
return self.conv(x.view(b, 4, self.c1, a).transpose(2, 1).softmax(1)).view(b, 4, a)
# return self.conv(x.view(b, self.c1, 4, a).softmax(1)).view(b, 4, a)
class Proto(nn.Module):
+ """Ultralytics YOLO models mask Proto module for segmentation models."""
def __init__(self, c1: int, c_: int = 256, c2: int = 32):
+ """Initialize the Ultralytics YOLO models mask Proto module with specified number of protos and masks.
+
+ Args:
+ c1 (int): Input channels.
+ c_ (int): Intermediate channels.
+ c2 (int): Output channels (number of protos).
+ """
super().__init__()
self.cv1 = Conv(c1, c_, k=3)
self.upsample = nn.ConvTranspose2d(c_, c_, 2, 2, 0, bias=True) # nn.Upsample(scale_factor=2, mode='nearest')
@@ -79,12 +98,24 @@ self.cv3 = Conv(c_, c2)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Perform a forward pass through layers using an upsampled input image."""
return self.cv3(self.cv2(self.upsample(self.cv1(x))))
class HGStem(nn.Module):
+ """StemBlock of PPHGNetV2 with 5 convolutions and one maxpool2d.
+
+ https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py
+ """
def __init__(self, c1: int, cm: int, c2: int):
+ """Initialize the StemBlock of PPHGNetV2.
+
+ Args:
+ c1 (int): Input channels.
+ cm (int): Middle channels.
+ c2 (int): Output channels.
+ """
super().__init__()
self.stem1 = Conv(c1, cm, 3, 2, act=nn.ReLU())
self.stem2a = Conv(cm, cm // 2, 2, 1, 0, act=nn.ReLU())
@@ -94,6 +125,7 @@ self.pool = nn.MaxPool2d(kernel_size=2, stride=1, padding=0, ceil_mode=True)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass of a PPHGNetV2 backbone layer."""
x = self.stem1(x)
x = F.pad(x, [0, 1, 0, 1])
x2 = self.stem2a(x)
@@ -107,6 +139,10 @@
class HGBlock(nn.Module):
+ """HG_Block of PPHGNetV2 with 2 convolutions and LightConv.
+
+ https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py
+ """
def __init__(
self,
@@ -119,6 +155,18 @@ shortcut: bool = False,
act: nn.Module = nn.ReLU(),
):
+ """Initialize HGBlock with specified parameters.
+
+ Args:
+ c1 (int): Input channels.
+ cm (int): Middle channels.
+ c2 (int): Output channels.
+ k (int): Kernel size.
+ n (int): Number of LightConv or Conv blocks.
+ lightconv (bool): Whether to use LightConv.
+ shortcut (bool): Whether to use shortcut connection.
+ act (nn.Module): Activation function.
+ """
super().__init__()
block = LightConv if lightconv else Conv
self.m = nn.ModuleList(block(c1 if i == 0 else cm, cm, k=k, act=act) for i in range(n))
@@ -127,6 +175,7 @@ self.add = shortcut and c1 == c2
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass of a PPHGNetV2 backbone layer."""
y = [x]
y.extend(m(y[-1]) for m in self.m)
y = self.ec(self.sc(torch.cat(y, 1)))
@@ -134,8 +183,16 @@
class SPP(nn.Module):
+ """Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729."""
def __init__(self, c1: int, c2: int, k: tuple[int, ...] = (5, 9, 13)):
+ """Initialize the SPP layer with input/output channels and pooling kernel sizes.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ k (tuple): Kernel sizes for max pooling.
+ """
super().__init__()
c_ = c1 // 2 # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
@@ -143,13 +200,27 @@ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass of the SPP layer, performing spatial pyramid pooling."""
x = self.cv1(x)
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
class SPPF(nn.Module):
+ """Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher."""
def __init__(self, c1: int, c2: int, k: int = 5, n: int = 3, shortcut: bool = False):
+ """Initialize the SPPF layer with given input/output channels and kernel size.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ k (int): Kernel size.
+ n (int): Number of pooling iterations.
+ shortcut (bool): Whether to use shortcut connection.
+
+ Notes:
+ This module is equivalent to SPP(k=(5, 9, 13)).
+ """
super().__init__()
c_ = c1 // 2 # hidden channels
self.cv1 = Conv(c1, c_, 1, 1, act=False)
@@ -159,6 +230,7 @@ self.add = shortcut and c1 == c2
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply sequential pooling operations to input and return concatenated feature maps."""
y = [self.cv1(x)]
y.extend(self.m(y[-1]) for _ in range(getattr(self, "n", 3)))
y = self.cv2(torch.cat(y, 1))
@@ -166,20 +238,40 @@
class C1(nn.Module):
+ """CSP Bottleneck with 1 convolution."""
def __init__(self, c1: int, c2: int, n: int = 1):
+ """Initialize the CSP Bottleneck with 1 convolution.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of convolutions.
+ """
super().__init__()
self.cv1 = Conv(c1, c2, 1, 1)
self.m = nn.Sequential(*(Conv(c2, c2, 3) for _ in range(n)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply convolution and residual connection to input tensor."""
y = self.cv1(x)
return self.m(y) + y
class C2(nn.Module):
+ """CSP Bottleneck with 2 convolutions."""
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
+ """Initialize a CSP Bottleneck with 2 convolutions.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of Bottleneck blocks.
+ shortcut (bool): Whether to use shortcut connections.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__()
self.c = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, 2 * self.c, 1, 1)
@@ -188,13 +280,25 @@ self.m = nn.Sequential(*(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through the CSP bottleneck with 2 convolutions."""
a, b = self.cv1(x).chunk(2, 1)
return self.cv2(torch.cat((self.m(a), b), 1))
class C2f(nn.Module):
+ """Faster Implementation of CSP Bottleneck with 2 convolutions."""
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = False, g: int = 1, e: float = 0.5):
+ """Initialize a CSP bottleneck with 2 convolutions.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of Bottleneck blocks.
+ shortcut (bool): Whether to use shortcut connections.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__()
self.c = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, 2 * self.c, 1, 1)
@@ -202,11 +306,13 @@ self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through C2f layer."""
y = list(self.cv1(x).chunk(2, 1))
y.extend(m(y[-1]) for m in self.m)
return self.cv2(torch.cat(y, 1))
def forward_split(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass using split() instead of chunk()."""
y = self.cv1(x).split((self.c, self.c), 1)
y = [y[0], y[1]]
y.extend(m(y[-1]) for m in self.m)
@@ -214,8 +320,19 @@
class C3(nn.Module):
+ """CSP Bottleneck with 3 convolutions."""
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
+ """Initialize the CSP Bottleneck with 3 convolutions.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of Bottleneck blocks.
+ shortcut (bool): Whether to use shortcut connections.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
@@ -224,20 +341,41 @@ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through the CSP bottleneck with 3 convolutions."""
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
class C3x(C3):
+ """C3 module with cross-convolutions."""
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
+ """Initialize C3 module with cross-convolutions.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of Bottleneck blocks.
+ shortcut (bool): Whether to use shortcut connections.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__(c1, c2, n, shortcut, g, e)
self.c_ = int(c2 * e)
self.m = nn.Sequential(*(Bottleneck(self.c_, self.c_, shortcut, g, k=((1, 3), (3, 1)), e=1) for _ in range(n)))
class RepC3(nn.Module):
+ """Rep C3."""
def __init__(self, c1: int, c2: int, n: int = 3, e: float = 1.0):
+ """Initialize RepC3 module with RepConv blocks.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of RepConv blocks.
+ e (float): Expansion ratio.
+ """
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
@@ -246,28 +384,60 @@ self.cv3 = Conv(c_, c2, 1, 1) if c_ != c2 else nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass of RepC3 module."""
return self.cv3(self.m(self.cv1(x)) + self.cv2(x))
class C3TR(C3):
+ """C3 module with TransformerBlock()."""
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
+ """Initialize C3 module with TransformerBlock.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of Transformer blocks.
+ shortcut (bool): Whether to use shortcut connections.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e)
self.m = TransformerBlock(c_, c_, 4, n)
class C3Ghost(C3):
+ """C3 module with GhostBottleneck()."""
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
+ """Initialize C3 module with GhostBottleneck.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of Ghost bottleneck blocks.
+ shortcut (bool): Whether to use shortcut connections.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e) # hidden channels
self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
class GhostBottleneck(nn.Module):
+ """Ghost Bottleneck https://github.com/huawei-noah/Efficient-AI-Backbones."""
def __init__(self, c1: int, c2: int, k: int = 3, s: int = 1):
+ """Initialize Ghost Bottleneck module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ k (int): Kernel size.
+ s (int): Stride.
+ """
super().__init__()
c_ = c2 // 2
self.conv = nn.Sequential(
@@ -280,14 +450,26 @@ )
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply skip connection and addition to input tensor."""
return self.conv(x) + self.shortcut(x)
class Bottleneck(nn.Module):
+ """Standard bottleneck."""
def __init__(
self, c1: int, c2: int, shortcut: bool = True, g: int = 1, k: tuple[int, int] = (3, 3), e: float = 0.5
):
+ """Initialize a standard bottleneck module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ shortcut (bool): Whether to use shortcut connection.
+ g (int): Groups for convolutions.
+ k (tuple): Kernel sizes for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, k[0], 1)
@@ -295,12 +477,24 @@ self.add = shortcut and c1 == c2
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply bottleneck with optional shortcut connection."""
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
class BottleneckCSP(nn.Module):
+ """CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks."""
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
+ """Initialize CSP Bottleneck.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of Bottleneck blocks.
+ shortcut (bool): Whether to use shortcut connections.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
@@ -312,14 +506,24 @@ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply CSP bottleneck with 4 convolutions."""
y1 = self.cv3(self.m(self.cv1(x)))
y2 = self.cv2(x)
return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
class ResNetBlock(nn.Module):
+ """ResNet block with standard convolution layers."""
def __init__(self, c1: int, c2: int, s: int = 1, e: int = 4):
+ """Initialize ResNet block.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ s (int): Stride.
+ e (int): Expansion ratio.
+ """
super().__init__()
c3 = e * c2
self.cv1 = Conv(c1, c2, k=1, s=1, act=True)
@@ -328,12 +532,24 @@ self.shortcut = nn.Sequential(Conv(c1, c3, k=1, s=s, act=False)) if s != 1 or c1 != c3 else nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through the ResNet block."""
return F.relu(self.cv3(self.cv2(self.cv1(x))) + self.shortcut(x))
class ResNetLayer(nn.Module):
+ """ResNet layer with multiple ResNet blocks."""
def __init__(self, c1: int, c2: int, s: int = 1, is_first: bool = False, n: int = 1, e: int = 4):
+ """Initialize ResNet layer.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ s (int): Stride.
+ is_first (bool): Whether this is the first layer.
+ n (int): Number of ResNet blocks.
+ e (int): Expansion ratio.
+ """
super().__init__()
self.is_first = is_first
@@ -347,12 +563,24 @@ self.layer = nn.Sequential(*blocks)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through the ResNet layer."""
return self.layer(x)
class MaxSigmoidAttnBlock(nn.Module):
+ """Max Sigmoid attention block."""
def __init__(self, c1: int, c2: int, nh: int = 1, ec: int = 128, gc: int = 512, scale: bool = False):
+ """Initialize MaxSigmoidAttnBlock.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ nh (int): Number of heads.
+ ec (int): Embedding channels.
+ gc (int): Guide channels.
+ scale (bool): Whether to use learnable scale parameter.
+ """
super().__init__()
self.nh = nh
self.hc = c2 // nh
@@ -363,6 +591,15 @@ self.scale = nn.Parameter(torch.ones(1, nh, 1, 1)) if scale else 1.0
def forward(self, x: torch.Tensor, guide: torch.Tensor) -> torch.Tensor:
+ """Forward pass of MaxSigmoidAttnBlock.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+ guide (torch.Tensor): Guide tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor after attention.
+ """
bs, _, h, w = x.shape
guide = self.gl(guide)
@@ -383,6 +620,7 @@
class C2fAttn(nn.Module):
+ """C2f module with an additional attn module."""
def __init__(
self,
@@ -396,6 +634,19 @@ g: int = 1,
e: float = 0.5,
):
+ """Initialize C2f module with attention mechanism.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of Bottleneck blocks.
+ ec (int): Embedding channels for attention.
+ nh (int): Number of heads for attention.
+ gc (int): Guide channels for attention.
+ shortcut (bool): Whether to use shortcut connections.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__()
self.c = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, 2 * self.c, 1, 1)
@@ -404,12 +655,30 @@ self.attn = MaxSigmoidAttnBlock(self.c, self.c, gc=gc, ec=ec, nh=nh)
def forward(self, x: torch.Tensor, guide: torch.Tensor) -> torch.Tensor:
+ """Forward pass through C2f layer with attention.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+ guide (torch.Tensor): Guide tensor for attention.
+
+ Returns:
+ (torch.Tensor): Output tensor after processing.
+ """
y = list(self.cv1(x).chunk(2, 1))
y.extend(m(y[-1]) for m in self.m)
y.append(self.attn(y[-1], guide))
return self.cv2(torch.cat(y, 1))
def forward_split(self, x: torch.Tensor, guide: torch.Tensor) -> torch.Tensor:
+ """Forward pass using split() instead of chunk().
+
+ Args:
+ x (torch.Tensor): Input tensor.
+ guide (torch.Tensor): Guide tensor for attention.
+
+ Returns:
+ (torch.Tensor): Output tensor after processing.
+ """
y = list(self.cv1(x).split((self.c, self.c), 1))
y.extend(m(y[-1]) for m in self.m)
y.append(self.attn(y[-1], guide))
@@ -417,10 +686,21 @@
class ImagePoolingAttn(nn.Module):
+ """ImagePoolingAttn: Enhance the text embeddings with image-aware information."""
def __init__(
self, ec: int = 256, ch: tuple[int, ...] = (), ct: int = 512, nh: int = 8, k: int = 3, scale: bool = False
):
+ """Initialize ImagePoolingAttn module.
+
+ Args:
+ ec (int): Embedding channels.
+ ch (tuple): Channel dimensions for feature maps.
+ ct (int): Channel dimension for text embeddings.
+ nh (int): Number of attention heads.
+ k (int): Kernel size for pooling.
+ scale (bool): Whether to use learnable scale parameter.
+ """
super().__init__()
nf = len(ch)
@@ -438,6 +718,15 @@ self.k = k
def forward(self, x: list[torch.Tensor], text: torch.Tensor) -> torch.Tensor:
+ """Forward pass of ImagePoolingAttn.
+
+ Args:
+ x (list[torch.Tensor]): List of input feature maps.
+ text (torch.Tensor): Text embeddings.
+
+ Returns:
+ (torch.Tensor): Enhanced text embeddings.
+ """
bs = x[0].shape[0]
assert len(x) == self.nf
num_patches = self.k**2
@@ -462,14 +751,25 @@
class ContrastiveHead(nn.Module):
+ """Implements contrastive learning head for region-text similarity in vision-language models."""
def __init__(self):
+ """Initialize ContrastiveHead with region-text similarity parameters."""
super().__init__()
# NOTE: use -10.0 to keep the init cls loss consistency with other losses
self.bias = nn.Parameter(torch.tensor([-10.0]))
self.logit_scale = nn.Parameter(torch.ones([]) * torch.tensor(1 / 0.07).log())
def forward(self, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
+ """Forward function of contrastive learning.
+
+ Args:
+ x (torch.Tensor): Image features.
+ w (torch.Tensor): Text features.
+
+ Returns:
+ (torch.Tensor): Similarity scores.
+ """
x = F.normalize(x, dim=1, p=2)
w = F.normalize(w, dim=-1, p=2)
x = torch.einsum("bchw,bkc->bkhw", x, w)
@@ -477,8 +777,18 @@
class BNContrastiveHead(nn.Module):
+ """Batch Norm Contrastive Head using batch norm instead of l2-normalization.
+
+ Args:
+ embed_dims (int): Embed dimensions of text and image features.
+ """
def __init__(self, embed_dims: int):
+ """Initialize BNContrastiveHead.
+
+ Args:
+ embed_dims (int): Embedding dimensions for features.
+ """
super().__init__()
self.norm = nn.BatchNorm2d(embed_dims)
# NOTE: use -10.0 to keep the init cls loss consistency with other losses
@@ -487,6 +797,7 @@ self.logit_scale = nn.Parameter(-1.0 * torch.ones([]))
def fuse(self):
+ """Fuse the batch normalization layer in the BNContrastiveHead module."""
del self.norm
del self.bias
del self.logit_scale
@@ -494,9 +805,19 @@
@staticmethod
def forward_fuse(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
+ """Passes image features through unchanged after fusing."""
return x
def forward(self, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
+ """Forward function of contrastive learning with batch normalization.
+
+ Args:
+ x (torch.Tensor): Image features.
+ w (torch.Tensor): Text features.
+
+ Returns:
+ (torch.Tensor): Similarity scores.
+ """
x = self.norm(x)
w = F.normalize(w, dim=-1, p=2)
@@ -505,26 +826,58 @@
class RepBottleneck(Bottleneck):
+ """Rep bottleneck."""
def __init__(
self, c1: int, c2: int, shortcut: bool = True, g: int = 1, k: tuple[int, int] = (3, 3), e: float = 0.5
):
+ """Initialize RepBottleneck.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ shortcut (bool): Whether to use shortcut connection.
+ g (int): Groups for convolutions.
+ k (tuple): Kernel sizes for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__(c1, c2, shortcut, g, k, e)
c_ = int(c2 * e) # hidden channels
self.cv1 = RepConv(c1, c_, k[0], 1)
class RepCSP(C3):
+ """Repeatable Cross Stage Partial Network (RepCSP) module for efficient feature extraction."""
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
+ """Initialize RepCSP layer.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of RepBottleneck blocks.
+ shortcut (bool): Whether to use shortcut connections.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e) # hidden channels
self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
class RepNCSPELAN4(nn.Module):
+ """CSP-ELAN."""
def __init__(self, c1: int, c2: int, c3: int, c4: int, n: int = 1):
+ """Initialize CSP-ELAN layer.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ c3 (int): Intermediate channels.
+ c4 (int): Intermediate channels for RepCSP.
+ n (int): Number of RepCSP blocks.
+ """
super().__init__()
self.c = c3 // 2
self.cv1 = Conv(c1, c3, 1, 1)
@@ -533,19 +886,30 @@ self.cv4 = Conv(c3 + (2 * c4), c2, 1, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through RepNCSPELAN4 layer."""
y = list(self.cv1(x).chunk(2, 1))
y.extend((m(y[-1])) for m in [self.cv2, self.cv3])
return self.cv4(torch.cat(y, 1))
def forward_split(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass using split() instead of chunk()."""
y = list(self.cv1(x).split((self.c, self.c), 1))
y.extend(m(y[-1]) for m in [self.cv2, self.cv3])
return self.cv4(torch.cat(y, 1))
class ELAN1(RepNCSPELAN4):
+ """ELAN1 module with 4 convolutions."""
def __init__(self, c1: int, c2: int, c3: int, c4: int):
+ """Initialize ELAN1 layer.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ c3 (int): Intermediate channels.
+ c4 (int): Intermediate channels for convolutions.
+ """
super().__init__(c1, c2, c3, c4)
self.c = c3 // 2
self.cv1 = Conv(c1, c3, 1, 1)
@@ -555,25 +919,41 @@
class AConv(nn.Module):
+ """AConv."""
def __init__(self, c1: int, c2: int):
+ """Initialize AConv module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ """
super().__init__()
self.cv1 = Conv(c1, c2, 3, 2, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through AConv layer."""
x = torch.nn.functional.avg_pool2d(x, 2, 1, 0, False, True)
return self.cv1(x)
class ADown(nn.Module):
+ """ADown."""
def __init__(self, c1: int, c2: int):
+ """Initialize ADown module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ """
super().__init__()
self.c = c2 // 2
self.cv1 = Conv(c1 // 2, self.c, 3, 2, 1)
self.cv2 = Conv(c1 // 2, self.c, 1, 1, 0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through ADown layer."""
x = torch.nn.functional.avg_pool2d(x, 2, 1, 0, False, True)
x1, x2 = x.chunk(2, 1)
x1 = self.cv1(x1)
@@ -583,8 +963,17 @@
class SPPELAN(nn.Module):
+ """SPP-ELAN."""
def __init__(self, c1: int, c2: int, c3: int, k: int = 5):
+ """Initialize SPP-ELAN block.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ c3 (int): Intermediate channels.
+ k (int): Kernel size for max pooling.
+ """
super().__init__()
self.c = c3
self.cv1 = Conv(c1, c3, 1, 1)
@@ -594,37 +983,75 @@ self.cv5 = Conv(4 * c3, c2, 1, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through SPPELAN layer."""
y = [self.cv1(x)]
y.extend(m(y[-1]) for m in [self.cv2, self.cv3, self.cv4])
return self.cv5(torch.cat(y, 1))
class CBLinear(nn.Module):
+ """CBLinear."""
def __init__(self, c1: int, c2s: list[int], k: int = 1, s: int = 1, p: int | None = None, g: int = 1):
+ """Initialize CBLinear module.
+
+ Args:
+ c1 (int): Input channels.
+ c2s (list[int]): List of output channel sizes.
+ k (int): Kernel size.
+ s (int): Stride.
+ p (int | None): Padding.
+ g (int): Groups.
+ """
super().__init__()
self.c2s = c2s
self.conv = nn.Conv2d(c1, sum(c2s), k, s, autopad(k, p), groups=g, bias=True)
def forward(self, x: torch.Tensor) -> list[torch.Tensor]:
+ """Forward pass through CBLinear layer."""
return self.conv(x).split(self.c2s, dim=1)
class CBFuse(nn.Module):
+ """CBFuse."""
def __init__(self, idx: list[int]):
+ """Initialize CBFuse module.
+
+ Args:
+ idx (list[int]): Indices for feature selection.
+ """
super().__init__()
self.idx = idx
def forward(self, xs: list[torch.Tensor]) -> torch.Tensor:
+ """Forward pass through CBFuse layer.
+
+ Args:
+ xs (list[torch.Tensor]): List of input tensors.
+
+ Returns:
+ (torch.Tensor): Fused output tensor.
+ """
target_size = xs[-1].shape[2:]
res = [F.interpolate(x[self.idx[i]], size=target_size, mode="nearest") for i, x in enumerate(xs[:-1])]
return torch.sum(torch.stack(res + xs[-1:]), dim=0)
class C3f(nn.Module):
+ """Faster Implementation of CSP Bottleneck with 3 convolutions."""
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = False, g: int = 1, e: float = 0.5):
+ """Initialize CSP bottleneck layer with three convolutions.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of Bottleneck blocks.
+ shortcut (bool): Whether to use shortcut connections.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
@@ -633,12 +1060,14 @@ self.m = nn.ModuleList(Bottleneck(c_, c_, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through C3f layer."""
y = [self.cv2(x), self.cv1(x)]
y.extend(m(y[-1]) for m in self.m)
return self.cv3(torch.cat(y, 1))
class C3k2(C2f):
+ """Faster Implementation of CSP Bottleneck with 2 convolutions."""
def __init__(
self,
@@ -651,6 +1080,18 @@ g: int = 1,
shortcut: bool = True,
):
+ """Initialize C3k2 module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of blocks.
+ c3k (bool): Whether to use C3k blocks.
+ e (float): Expansion ratio.
+ attn (bool): Whether to use attention blocks.
+ g (int): Groups for convolutions.
+ shortcut (bool): Whether to use shortcut connections.
+ """
super().__init__(c1, c2, n, shortcut, g, e)
self.m = nn.ModuleList(
nn.Sequential(
@@ -666,8 +1107,20 @@
class C3k(C3):
+ """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks."""
def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5, k: int = 3):
+ """Initialize C3k module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of Bottleneck blocks.
+ shortcut (bool): Whether to use shortcut connections.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ k (int): Kernel size.
+ """
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e) # hidden channels
# self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
@@ -675,8 +1128,14 @@
class RepVGGDW(torch.nn.Module):
+ """RepVGGDW is a class that represents a depth-wise convolutional block in RepVGG architecture."""
def __init__(self, ed: int) -> None:
+ """Initialize RepVGGDW module.
+
+ Args:
+ ed (int): Input and output channels.
+ """
super().__init__()
self.conv = Conv(ed, ed, 7, 1, 3, g=ed, act=False)
self.conv1 = Conv(ed, ed, 3, 1, 1, g=ed, act=False)
@@ -684,13 +1143,33 @@ self.act = nn.SiLU()
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Perform a forward pass of the RepVGGDW block.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor after applying the depth-wise convolution.
+ """
return self.act(self.conv(x) + self.conv1(x))
def forward_fuse(self, x: torch.Tensor) -> torch.Tensor:
+ """Perform a forward pass of the fused RepVGGDW block.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor after applying the depth-wise convolution.
+ """
return self.act(self.conv(x))
@torch.no_grad()
def fuse(self):
+ """Fuse the convolutional layers in the RepVGGDW block.
+
+ This method fuses the convolutional layers and updates the weights and biases accordingly.
+ """
if not hasattr(self, "conv1"):
return # already fused
conv = fuse_conv_and_bn(self.conv.conv, self.conv.bn)
@@ -714,8 +1193,26 @@
class CIB(nn.Module):
+ """Compact Inverted Block (CIB) module.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ shortcut (bool, optional): Whether to add a shortcut connection. Defaults to True.
+ e (float, optional): Scaling factor for the hidden channels. Defaults to 0.5.
+ lk (bool, optional): Whether to use RepVGGDW for the third convolutional layer. Defaults to False.
+ """
def __init__(self, c1: int, c2: int, shortcut: bool = True, e: float = 0.5, lk: bool = False):
+ """Initialize the CIB module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ shortcut (bool): Whether to use shortcut connection.
+ e (float): Expansion ratio.
+ lk (bool): Whether to use RepVGGDW.
+ """
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = nn.Sequential(
@@ -729,21 +1226,74 @@ self.add = shortcut and c1 == c2
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass of the CIB module.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor.
+ """
return x + self.cv1(x) if self.add else self.cv1(x)
class C2fCIB(C2f):
+ """C2fCIB class represents a convolutional block with C2f and CIB modules.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ n (int, optional): Number of CIB modules to stack. Defaults to 1.
+ shortcut (bool, optional): Whether to use shortcut connection. Defaults to False.
+ lk (bool, optional): Whether to use large kernel. Defaults to False.
+ g (int, optional): Number of groups for grouped convolution. Defaults to 1.
+ e (float, optional): Expansion ratio for CIB modules. Defaults to 0.5.
+ """
def __init__(
self, c1: int, c2: int, n: int = 1, shortcut: bool = False, lk: bool = False, g: int = 1, e: float = 0.5
):
+ """Initialize C2fCIB module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of CIB modules.
+ shortcut (bool): Whether to use shortcut connection.
+ lk (bool): Whether to use large kernel.
+ g (int): Groups for convolutions.
+ e (float): Expansion ratio.
+ """
super().__init__(c1, c2, n, shortcut, g, e)
self.m = nn.ModuleList(CIB(self.c, self.c, shortcut, e=1.0, lk=lk) for _ in range(n))
class Attention(nn.Module):
+ """Attention module that performs self-attention on the input tensor.
+
+ Args:
+ dim (int): The input tensor dimension.
+ num_heads (int): The number of attention heads.
+ attn_ratio (float): The ratio of the attention key dimension to the head dimension.
+
+ Attributes:
+ num_heads (int): The number of attention heads.
+ head_dim (int): The dimension of each attention head.
+ key_dim (int): The dimension of the attention key.
+ scale (float): The scaling factor for the attention scores.
+ qkv (Conv): Convolutional layer for computing the query, key, and value.
+ proj (Conv): Convolutional layer for projecting the attended values.
+ pe (Conv): Convolutional layer for positional encoding.
+ """
def __init__(self, dim: int, num_heads: int = 8, attn_ratio: float = 0.5):
+ """Initialize multi-head attention module.
+
+ Args:
+ dim (int): Input dimension.
+ num_heads (int): Number of attention heads.
+ attn_ratio (float): Attention ratio for key dimension.
+ """
super().__init__()
self.num_heads = num_heads
self.head_dim = dim // num_heads
@@ -756,6 +1306,14 @@ self.pe = Conv(dim, dim, 3, 1, g=dim, act=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass of the Attention module.
+
+ Args:
+ x (torch.Tensor): The input tensor.
+
+ Returns:
+ (torch.Tensor): The output tensor after self-attention.
+ """
B, C, H, W = x.shape
N = H * W
qkv = self.qkv(x)
@@ -771,8 +1329,35 @@
class PSABlock(nn.Module):
+ """PSABlock class implementing a Position-Sensitive Attention block for neural networks.
+
+ This class encapsulates the functionality for applying multi-head attention and feed-forward neural network layers
+ with optional shortcut connections.
+
+ Attributes:
+ attn (Attention): Multi-head attention module.
+ ffn (nn.Sequential): Feed-forward neural network module.
+ add (bool): Flag indicating whether to add shortcut connections.
+
+ Methods:
+ forward: Performs a forward pass through the PSABlock, applying attention and feed-forward layers.
+
+ Examples:
+ Create a PSABlock and perform a forward pass
+ >>> psablock = PSABlock(c=128, attn_ratio=0.5, num_heads=4, shortcut=True)
+ >>> input_tensor = torch.randn(1, 128, 32, 32)
+ >>> output_tensor = psablock(input_tensor)
+ """
def __init__(self, c: int, attn_ratio: float = 0.5, num_heads: int = 4, shortcut: bool = True) -> None:
+ """Initialize the PSABlock.
+
+ Args:
+ c (int): Input and output channels.
+ attn_ratio (float): Attention ratio for key dimension.
+ num_heads (int): Number of attention heads.
+ shortcut (bool): Whether to use shortcut connections.
+ """
super().__init__()
self.attn = Attention(c, attn_ratio=attn_ratio, num_heads=num_heads)
@@ -780,14 +1365,50 @@ self.add = shortcut
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Execute a forward pass through PSABlock.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor after attention and feed-forward processing.
+ """
x = x + self.attn(x) if self.add else self.attn(x)
x = x + self.ffn(x) if self.add else self.ffn(x)
return x
class PSA(nn.Module):
+ """PSA class for implementing Position-Sensitive Attention in neural networks.
+
+ This class encapsulates the functionality for applying position-sensitive attention and feed-forward networks to
+ input tensors, enhancing feature extraction and processing capabilities.
+
+ Attributes:
+ c (int): Number of hidden channels after applying the initial convolution.
+ cv1 (Conv): 1x1 convolution layer to reduce the number of input channels to 2*c.
+ cv2 (Conv): 1x1 convolution layer to reduce the number of output channels to c1.
+ attn (Attention): Attention module for position-sensitive attention.
+ ffn (nn.Sequential): Feed-forward network for further processing.
+
+ Methods:
+ forward: Applies position-sensitive attention and feed-forward network to the input tensor.
+
+ Examples:
+ Create a PSA module and apply it to an input tensor
+ >>> psa = PSA(c1=128, c2=128, e=0.5)
+ >>> input_tensor = torch.randn(1, 128, 64, 64)
+ >>> output_tensor = psa.forward(input_tensor)
+ """
def __init__(self, c1: int, c2: int, e: float = 0.5):
+ """Initialize PSA module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ e (float): Expansion ratio.
+ """
super().__init__()
assert c1 == c2
self.c = int(c1 * e)
@@ -798,6 +1419,14 @@ self.ffn = nn.Sequential(Conv(self.c, self.c * 2, 1), Conv(self.c * 2, self.c, 1, act=False))
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Execute forward pass in PSA module.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor after attention and feed-forward processing.
+ """
a, b = self.cv1(x).split((self.c, self.c), dim=1)
b = b + self.attn(b)
b = b + self.ffn(b)
@@ -805,8 +1434,38 @@
class C2PSA(nn.Module):
+ """C2PSA module with attention mechanism for enhanced feature extraction and processing.
+
+ This module implements a convolutional block with attention mechanisms to enhance feature extraction and processing
+ capabilities. It includes a series of PSABlock modules for self-attention and feed-forward operations.
+
+ Attributes:
+ c (int): Number of hidden channels.
+ cv1 (Conv): 1x1 convolution layer to reduce the number of input channels to 2*c.
+ cv2 (Conv): 1x1 convolution layer to reduce the number of output channels to c1.
+ m (nn.Sequential): Sequential container of PSABlock modules for attention and feed-forward operations.
+
+ Methods:
+ forward: Performs a forward pass through the C2PSA module, applying attention and feed-forward operations.
+
+ Examples:
+ >>> c2psa = C2PSA(c1=256, c2=256, n=3, e=0.5)
+ >>> input_tensor = torch.randn(1, 256, 64, 64)
+ >>> output_tensor = c2psa(input_tensor)
+
+ Notes:
+ This module essentially is the same as PSA module, but refactored to allow stacking more PSABlock modules.
+ """
def __init__(self, c1: int, c2: int, n: int = 1, e: float = 0.5):
+ """Initialize C2PSA module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of PSABlock modules.
+ e (float): Expansion ratio.
+ """
super().__init__()
assert c1 == c2
self.c = int(c1 * e)
@@ -816,35 +1475,135 @@ self.m = nn.Sequential(*(PSABlock(self.c, attn_ratio=0.5, num_heads=self.c // 64) for _ in range(n)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Process the input tensor through a series of PSA blocks.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor after processing.
+ """
a, b = self.cv1(x).split((self.c, self.c), dim=1)
b = self.m(b)
return self.cv2(torch.cat((a, b), 1))
class C2fPSA(C2f):
+ """C2fPSA module with enhanced feature extraction using PSA blocks.
+
+ This class extends the C2f module by incorporating PSA blocks for improved attention mechanisms and feature
+ extraction.
+
+ Attributes:
+ c (int): Number of hidden channels.
+ cv1 (Conv): 1x1 convolution layer to reduce the number of input channels to 2*c.
+ cv2 (Conv): 1x1 convolution layer to reduce the number of output channels to c2.
+ m (nn.ModuleList): List of PSABlock modules for feature extraction.
+
+ Methods:
+ forward: Performs a forward pass through the C2fPSA module.
+ forward_split: Performs a forward pass using split() instead of chunk().
+
+ Examples:
+ >>> import torch
+ >>> from ultralytics.nn.modules.block import C2fPSA
+ >>> model = C2fPSA(c1=64, c2=64, n=3, e=0.5)
+ >>> x = torch.randn(1, 64, 128, 128)
+ >>> output = model(x)
+ >>> print(output.shape)
+ """
def __init__(self, c1: int, c2: int, n: int = 1, e: float = 0.5):
+ """Initialize C2fPSA module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ n (int): Number of PSABlock modules.
+ e (float): Expansion ratio.
+ """
assert c1 == c2
super().__init__(c1, c2, n=n, e=e)
self.m = nn.ModuleList(PSABlock(self.c, attn_ratio=0.5, num_heads=max(self.c // 64, 1)) for _ in range(n))
class SCDown(nn.Module):
+ """SCDown module for downsampling with separable convolutions.
+
+ This module performs downsampling using a combination of pointwise and depthwise convolutions, which helps in
+ efficiently reducing the spatial dimensions of the input tensor while maintaining the channel information.
+
+ Attributes:
+ cv1 (Conv): Pointwise convolution layer that reduces the number of channels.
+ cv2 (Conv): Depthwise convolution layer that performs spatial downsampling.
+
+ Methods:
+ forward: Applies the SCDown module to the input tensor.
+
+ Examples:
+ >>> import torch
+ >>> from ultralytics.nn.modules.block import SCDown
+ >>> model = SCDown(c1=64, c2=128, k=3, s=2)
+ >>> x = torch.randn(1, 64, 128, 128)
+ >>> y = model(x)
+ >>> print(y.shape)
+ torch.Size([1, 128, 64, 64])
+ """
def __init__(self, c1: int, c2: int, k: int, s: int):
+ """Initialize SCDown module.
+
+ Args:
+ c1 (int): Input channels.
+ c2 (int): Output channels.
+ k (int): Kernel size.
+ s (int): Stride.
+ """
super().__init__()
self.cv1 = Conv(c1, c2, 1, 1)
self.cv2 = Conv(c2, c2, k=k, s=s, g=c2, act=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply convolution and downsampling to the input tensor.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Downsampled output tensor.
+ """
return self.cv2(self.cv1(x))
class TorchVision(nn.Module):
+ """TorchVision module to allow loading any torchvision model.
+
+ This class provides a way to load a model from the torchvision library, optionally load pre-trained weights, and
+ customize the model by truncating or unwrapping layers.
+
+ Args:
+ model (str): Name of the torchvision model to load.
+ weights (str, optional): Pre-trained weights to load. Default is "DEFAULT".
+ unwrap (bool, optional): Unwraps the model to a sequential containing all but the last `truncate` layers.
+ truncate (int, optional): Number of layers to truncate from the end if `unwrap` is True. Default is 2.
+ split (bool, optional): Returns output from intermediate child modules as list. Default is False.
+
+ Attributes:
+ m (nn.Module): The loaded torchvision model, possibly truncated and unwrapped.
+ """
def __init__(
self, model: str, weights: str = "DEFAULT", unwrap: bool = True, truncate: int = 2, split: bool = False
):
+ """Load the model and weights from torchvision.
+
+ Args:
+ model (str): Name of the torchvision model to load.
+ weights (str): Pre-trained weights to load.
+ unwrap (bool): Whether to unwrap the model.
+ truncate (int): Number of layers to truncate.
+ split (bool): Whether to split the output.
+ """
import torchvision # scope for faster 'import ultralytics'
super().__init__()
@@ -863,6 +1622,14 @@ self.m.head = self.m.heads = nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through the model.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor | list[torch.Tensor]): Output tensor or list of tensors.
+ """
if self.split:
y = [x]
y.extend(m(y[-1]) for m in self.m)
@@ -872,8 +1639,38 @@
class AAttn(nn.Module):
+ """Area-attention module for YOLO models, providing efficient attention mechanisms.
+
+ This module implements an area-based attention mechanism that processes input features in a spatially-aware manner,
+ making it particularly effective for object detection tasks.
+
+ Attributes:
+ area (int): Number of areas the feature map is divided into.
+ num_heads (int): Number of heads into which the attention mechanism is divided.
+ head_dim (int): Dimension of each attention head.
+ qkv (Conv): Convolution layer for computing query, key and value tensors.
+ proj (Conv): Projection convolution layer.
+ pe (Conv): Position encoding convolution layer.
+
+ Methods:
+ forward: Applies area-attention to input tensor.
+
+ Examples:
+ >>> attn = AAttn(dim=256, num_heads=8, area=4)
+ >>> x = torch.randn(1, 256, 32, 32)
+ >>> output = attn(x)
+ >>> print(output.shape)
+ torch.Size([1, 256, 32, 32])
+ """
def __init__(self, dim: int, num_heads: int, area: int = 1):
+ """Initialize an Area-attention module for YOLO models.
+
+ Args:
+ dim (int): Number of hidden channels.
+ num_heads (int): Number of heads into which the attention mechanism is divided.
+ area (int): Number of areas the feature map is divided into.
+ """
super().__init__()
self.area = area
@@ -886,6 +1683,14 @@ self.pe = Conv(all_head_dim, dim, 7, 1, 3, g=dim, act=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Process the input tensor through the area-attention.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor after area-attention.
+ """
B, C, H, W = x.shape
N = H * W
@@ -917,8 +1722,37 @@
class ABlock(nn.Module):
+ """Area-attention block module for efficient feature extraction in YOLO models.
+
+ This module implements an area-attention mechanism combined with a feed-forward network for processing feature maps.
+ It uses a novel area-based attention approach that is more efficient than traditional self-attention while
+ maintaining effectiveness.
+
+ Attributes:
+ attn (AAttn): Area-attention module for processing spatial features.
+ mlp (nn.Sequential): Multi-layer perceptron for feature transformation.
+
+ Methods:
+ _init_weights: Initializes module weights using truncated normal distribution.
+ forward: Applies area-attention and feed-forward processing to input tensor.
+
+ Examples:
+ >>> block = ABlock(dim=256, num_heads=8, mlp_ratio=1.2, area=1)
+ >>> x = torch.randn(1, 256, 32, 32)
+ >>> output = block(x)
+ >>> print(output.shape)
+ torch.Size([1, 256, 32, 32])
+ """
def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 1.2, area: int = 1):
+ """Initialize an Area-attention block module.
+
+ Args:
+ dim (int): Number of input channels.
+ num_heads (int): Number of heads into which the attention mechanism is divided.
+ mlp_ratio (float): Expansion ratio for MLP hidden dimension.
+ area (int): Number of areas the feature map is divided into.
+ """
super().__init__()
self.attn = AAttn(dim, num_heads=num_heads, area=area)
@@ -929,17 +1763,51 @@
@staticmethod
def _init_weights(m: nn.Module):
+ """Initialize weights using a truncated normal distribution.
+
+ Args:
+ m (nn.Module): Module to initialize.
+ """
if isinstance(m, nn.Conv2d):
nn.init.trunc_normal_(m.weight, std=0.02)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through ABlock.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor after area-attention and feed-forward processing.
+ """
x = x + self.attn(x)
return x + self.mlp(x)
class A2C2f(nn.Module):
+ """Area-Attention C2f module for enhanced feature extraction with area-based attention mechanisms.
+
+ This module extends the C2f architecture by incorporating area-attention and ABlock layers for improved feature
+ processing. It supports both area-attention and standard convolution modes.
+
+ Attributes:
+ cv1 (Conv): Initial 1x1 convolution layer that reduces input channels to hidden channels.
+ cv2 (Conv): Final 1x1 convolution layer that processes concatenated features.
+ gamma (nn.Parameter | None): Learnable parameter for residual scaling when using area attention.
+ m (nn.ModuleList): List of either ABlock or C3k modules for feature processing.
+
+ Methods:
+ forward: Processes input through area-attention or standard convolution pathway.
+
+ Examples:
+ >>> m = A2C2f(512, 512, n=1, a2=True, area=1)
+ >>> x = torch.randn(1, 512, 32, 32)
+ >>> output = m(x)
+ >>> print(output.shape)
+ torch.Size([1, 512, 32, 32])
+ """
def __init__(
self,
@@ -954,6 +1822,20 @@ g: int = 1,
shortcut: bool = True,
):
+ """Initialize Area-Attention C2f module.
+
+ Args:
+ c1 (int): Number of input channels.
+ c2 (int): Number of output channels.
+ n (int): Number of ABlock or C3k modules to stack.
+ a2 (bool): Whether to use area attention blocks. If False, uses C3k blocks instead.
+ area (int): Number of areas the feature map is divided into.
+ residual (bool): Whether to use residual connections with learnable gamma parameter.
+ mlp_ratio (float): Expansion ratio for MLP hidden dimension.
+ e (float): Channel expansion ratio for hidden channels.
+ g (int): Number of groups for grouped convolutions.
+ shortcut (bool): Whether to use shortcut connections in C3k blocks.
+ """
super().__init__()
c_ = int(c2 * e) # hidden channels
assert c_ % 32 == 0, "Dimension of ABlock must be a multiple of 32."
@@ -970,6 +1852,14 @@ )
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass through A2C2f layer.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+
+ Returns:
+ (torch.Tensor): Output tensor after processing.
+ """
y = [self.cv1(x)]
y.extend(m(y[-1]) for m in self.m)
y = self.cv2(torch.cat(y, 1))
@@ -979,13 +1869,22 @@
class SwiGLUFFN(nn.Module):
+ """SwiGLU Feed-Forward Network for transformer-based architectures."""
def __init__(self, gc: int, ec: int, e: int = 4) -> None:
+ """Initialize SwiGLU FFN with input dimension, output dimension, and expansion factor.
+
+ Args:
+ gc (int): Guide channels.
+ ec (int): Embedding channels.
+ e (int): Expansion factor.
+ """
super().__init__()
self.w12 = nn.Linear(gc, e * ec)
self.w3 = nn.Linear(e * ec // 2, ec)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply SwiGLU transformation to input features."""
x12 = self.w12(x)
x1, x2 = x12.chunk(2, dim=-1)
hidden = F.silu(x1) * x2
@@ -993,8 +1892,14 @@
class Residual(nn.Module):
+ """Residual connection wrapper for neural network modules."""
def __init__(self, m: nn.Module) -> None:
+ """Initialize residual module with the wrapped module.
+
+ Args:
+ m (nn.Module): Module to wrap with residual connection.
+ """
super().__init__()
self.m = m
nn.init.zeros_(self.m.w3.bias)
@@ -1003,12 +1908,21 @@ nn.init.zeros_(self.m.w3.weight)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply residual connection to input features."""
return x + self.m(x)
class SAVPE(nn.Module):
+ """Spatial-Aware Visual Prompt Embedding module for feature enhancement."""
def __init__(self, ch: list[int], c3: int, embed: int):
+ """Initialize SAVPE module with channels, intermediate channels, and embedding dimension.
+
+ Args:
+ ch (list[int]): List of input channel dimensions.
+ c3 (int): Intermediate channels.
+ embed (int): Embedding dimension.
+ """
super().__init__()
self.cv1 = nn.ModuleList(
nn.Sequential(
@@ -1029,6 +1943,7 @@ self.cv6 = nn.Sequential(Conv(2 * self.c, self.c, 3), nn.Conv2d(self.c, self.c, 3, padding=1))
def forward(self, x: list[torch.Tensor], vp: torch.Tensor) -> torch.Tensor:
+ """Process input features and visual prompts to generate enhanced embeddings."""
y = [self.cv2[i](xi) for i, xi in enumerate(x)]
y = self.cv4(torch.cat(y, dim=1))
@@ -1057,14 +1972,24 @@
class Proto26(Proto):
+ """Ultralytics YOLO26 models mask Proto module for segmentation models."""
def __init__(self, ch: tuple = (), c_: int = 256, c2: int = 32, nc: int = 80):
+ """Initialize the Ultralytics YOLO models mask Proto module with specified number of protos and masks.
+
+ Args:
+ ch (tuple): Tuple of channel sizes from backbone feature maps.
+ c_ (int): Intermediate channels.
+ c2 (int): Output channels (number of protos).
+ nc (int): Number of classes for semantic segmentation.
+ """
super().__init__(c_, c_, c2)
self.feat_refine = nn.ModuleList(Conv(x, ch[0], k=1) for x in ch[1:])
self.feat_fuse = Conv(ch[0], c_, k=3)
self.semseg = nn.Sequential(Conv(ch[0], c_, k=3), Conv(c_, c_, k=3), nn.Conv2d(c_, nc, 1))
def forward(self, x: torch.Tensor, return_semseg: bool = True) -> torch.Tensor:
+ """Perform a forward pass by fusing multi-scale feature maps and generating proto masks."""
feat = x[0]
for i, f in enumerate(self.feat_refine):
up_feat = f(x[i + 1])
@@ -1077,21 +2002,31 @@ return p
def fuse(self):
+ """Fuse the model for inference by removing the semantic segmentation head."""
self.semseg = None
class RealNVP(nn.Module):
+ """RealNVP: a flow-based generative model.
+
+ References:
+ https://arxiv.org/abs/1605.08803
+ https://github.com/open-mmlab/mmpose/blob/main/mmpose/models/utils/realnvp.py
+ """
@staticmethod
def nets():
+ """Get the scale model in a single invertible mapping."""
return nn.Sequential(nn.Linear(2, 64), nn.SiLU(), nn.Linear(64, 64), nn.SiLU(), nn.Linear(64, 2), nn.Tanh())
@staticmethod
def nett():
+ """Get the translation model in a single invertible mapping."""
return nn.Sequential(nn.Linear(2, 64), nn.SiLU(), nn.Linear(64, 64), nn.SiLU(), nn.Linear(64, 2))
@property
def prior(self):
+ """The prior distribution."""
return torch.distributions.MultivariateNormal(self.loc, self.cov)
def __init__(self):
@@ -1106,11 +2041,15 @@ self.init_weights()
def init_weights(self):
+ """Initialize model weights."""
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight, gain=0.01)
def backward_p(self, x):
+ """Apply mapping from the data space to the latent space and calculate the log determinant of the Jacobian
+ matrix.
+ """
log_det_jacob, z = x.new_zeros(x.shape[0]), x
for i in reversed(range(len(self.t))):
z_ = self.mask[i] * z
@@ -1121,7 +2060,8 @@ return z, log_det_jacob
def log_prob(self, x):
+ """Calculate the log probability of given sample in data space."""
if x.dtype == torch.float32 and self.s[0][0].weight.dtype != torch.float32:
self.float()
z, log_det = self.backward_p(x)
- return self.prior.log_prob(z) + log_det+ return self.prior.log_prob(z) + log_det
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/nn/modules/block.py |
Add well-formatted docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import copy
import cv2
import numpy as np
from ultralytics.utils import LOGGER
class GMC:
def __init__(self, method: str = "sparseOptFlow", downscale: int = 2) -> None:
super().__init__()
self.method = method
self.downscale = max(1, downscale)
if self.method == "orb":
self.detector = cv2.FastFeatureDetector_create(20)
self.extractor = cv2.ORB_create()
self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING)
elif self.method == "sift":
self.detector = cv2.SIFT_create(nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20)
self.extractor = cv2.SIFT_create(nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20)
self.matcher = cv2.BFMatcher(cv2.NORM_L2)
elif self.method == "ecc":
number_of_iterations = 5000
termination_eps = 1e-6
self.warp_mode = cv2.MOTION_EUCLIDEAN
self.criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, number_of_iterations, termination_eps)
elif self.method == "sparseOptFlow":
self.feature_params = dict(
maxCorners=1000, qualityLevel=0.01, minDistance=1, blockSize=3, useHarrisDetector=False, k=0.04
)
elif self.method in {"none", "None", None}:
self.method = None
else:
raise ValueError(f"Unknown GMC method: {method}")
self.prevFrame = None
self.prevKeyPoints = None
self.prevDescriptors = None
self.initializedFirstFrame = False
def apply(self, raw_frame: np.ndarray, detections: list | None = None) -> np.ndarray:
if self.method in {"orb", "sift"}:
return self.apply_features(raw_frame, detections)
elif self.method == "ecc":
return self.apply_ecc(raw_frame)
elif self.method == "sparseOptFlow":
return self.apply_sparseoptflow(raw_frame)
else:
return np.eye(2, 3)
def apply_ecc(self, raw_frame: np.ndarray) -> np.ndarray:
height, width, c = raw_frame.shape
frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame
H = np.eye(2, 3, dtype=np.float32)
# Downscale image for computational efficiency
if self.downscale > 1.0:
frame = cv2.GaussianBlur(frame, (3, 3), 1.5)
frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))
# Handle first frame initialization
if not self.initializedFirstFrame:
self.prevFrame = frame.copy()
self.initializedFirstFrame = True
return H
# Run the ECC algorithm to find transformation matrix
try:
(_, H) = cv2.findTransformECC(self.prevFrame, frame, H, self.warp_mode, self.criteria, None, 1)
except Exception as e:
LOGGER.warning(f"findTransformECC failed; using identity warp. {e}")
return H
def apply_features(self, raw_frame: np.ndarray, detections: list | None = None) -> np.ndarray:
height, width, c = raw_frame.shape
frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame
H = np.eye(2, 3)
# Downscale image for computational efficiency
if self.downscale > 1.0:
frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))
width = width // self.downscale
height = height // self.downscale
# Create mask for keypoint detection, excluding border regions
mask = np.zeros_like(frame)
mask[int(0.02 * height) : int(0.98 * height), int(0.02 * width) : int(0.98 * width)] = 255
# Exclude detection regions from mask to avoid tracking detected objects
if detections is not None:
for det in detections:
tlbr = (det[:4] / self.downscale).astype(np.int_)
mask[tlbr[1] : tlbr[3], tlbr[0] : tlbr[2]] = 0
# Find keypoints and compute descriptors
keypoints = self.detector.detect(frame, mask)
keypoints, descriptors = self.extractor.compute(frame, keypoints)
# Handle first frame initialization
if not self.initializedFirstFrame:
self.prevFrame = frame.copy()
self.prevKeyPoints = copy.copy(keypoints)
self.prevDescriptors = copy.copy(descriptors)
self.initializedFirstFrame = True
return H
# Match descriptors between previous and current frame
knnMatches = self.matcher.knnMatch(self.prevDescriptors, descriptors, 2)
# Filter matches based on spatial distance constraints
matches = []
spatialDistances = []
maxSpatialDistance = 0.25 * np.array([width, height])
# Handle empty matches case
if len(knnMatches) == 0:
self.prevFrame = frame.copy()
self.prevKeyPoints = copy.copy(keypoints)
self.prevDescriptors = copy.copy(descriptors)
return H
# Apply Lowe's ratio test and spatial distance filtering
for m, n in knnMatches:
if m.distance < 0.9 * n.distance:
prevKeyPointLocation = self.prevKeyPoints[m.queryIdx].pt
currKeyPointLocation = keypoints[m.trainIdx].pt
spatialDistance = (
prevKeyPointLocation[0] - currKeyPointLocation[0],
prevKeyPointLocation[1] - currKeyPointLocation[1],
)
if (np.abs(spatialDistance[0]) < maxSpatialDistance[0]) and (
np.abs(spatialDistance[1]) < maxSpatialDistance[1]
):
spatialDistances.append(spatialDistance)
matches.append(m)
# Filter outliers using statistical analysis
meanSpatialDistances = np.mean(spatialDistances, 0)
stdSpatialDistances = np.std(spatialDistances, 0)
inliers = (spatialDistances - meanSpatialDistances) < 2.5 * stdSpatialDistances
# Extract good matches and corresponding points
goodMatches = []
prevPoints = []
currPoints = []
for i in range(len(matches)):
if inliers[i, 0] and inliers[i, 1]:
goodMatches.append(matches[i])
prevPoints.append(self.prevKeyPoints[matches[i].queryIdx].pt)
currPoints.append(keypoints[matches[i].trainIdx].pt)
prevPoints = np.array(prevPoints)
currPoints = np.array(currPoints)
# Estimate transformation matrix using RANSAC
if prevPoints.shape[0] > 4:
H, inliers = cv2.estimateAffinePartial2D(prevPoints, currPoints, cv2.RANSAC)
# Scale translation components back to original resolution
if self.downscale > 1.0:
H[0, 2] *= self.downscale
H[1, 2] *= self.downscale
else:
LOGGER.warning("not enough matching points")
# Store current frame data for next iteration
self.prevFrame = frame.copy()
self.prevKeyPoints = copy.copy(keypoints)
self.prevDescriptors = copy.copy(descriptors)
return H
def apply_sparseoptflow(self, raw_frame: np.ndarray) -> np.ndarray:
height, width, c = raw_frame.shape
frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame
H = np.eye(2, 3)
# Downscale image for computational efficiency
if self.downscale > 1.0:
frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))
# Find good features to track
keypoints = cv2.goodFeaturesToTrack(frame, mask=None, **self.feature_params)
# Handle first frame initialization
if not self.initializedFirstFrame or self.prevKeyPoints is None:
self.prevFrame = frame.copy()
self.prevKeyPoints = copy.copy(keypoints)
self.initializedFirstFrame = True
return H
# Calculate optical flow using Lucas-Kanade method
matchedKeypoints, status, _ = cv2.calcOpticalFlowPyrLK(self.prevFrame, frame, self.prevKeyPoints, None)
# Extract successfully tracked points
prevPoints = []
currPoints = []
for i in range(len(status)):
if status[i]:
prevPoints.append(self.prevKeyPoints[i])
currPoints.append(matchedKeypoints[i])
prevPoints = np.array(prevPoints)
currPoints = np.array(currPoints)
# Estimate transformation matrix using RANSAC
if (prevPoints.shape[0] > 4) and (prevPoints.shape[0] == currPoints.shape[0]):
H, _ = cv2.estimateAffinePartial2D(prevPoints, currPoints, cv2.RANSAC)
# Scale translation components back to original resolution
if self.downscale > 1.0:
H[0, 2] *= self.downscale
H[1, 2] *= self.downscale
else:
LOGGER.warning("not enough matching points")
# Store current frame data for next iteration
self.prevFrame = frame.copy()
self.prevKeyPoints = copy.copy(keypoints)
return H
def reset_params(self) -> None:
self.prevFrame = None
self.prevKeyPoints = None
self.prevDescriptors = None
self.initializedFirstFrame = False | --- +++ @@ -11,8 +11,42 @@
class GMC:
+ """Generalized Motion Compensation (GMC) class for tracking and object detection in video frames.
+
+ This class provides methods for tracking and detecting objects based on several tracking algorithms including ORB,
+ SIFT, ECC, and Sparse Optical Flow. It also supports downscaling of frames for computational efficiency.
+
+ Attributes:
+ method (str | None): The tracking method to use. Options include 'orb', 'sift', 'ecc', 'sparseOptFlow', None.
+ downscale (int): Factor by which to downscale the frames for processing.
+ prevFrame (np.ndarray | None): Previous frame for tracking.
+ prevKeyPoints (tuple | np.ndarray | None): Keypoints from the previous frame.
+ prevDescriptors (np.ndarray | None): Descriptors from the previous frame.
+ initializedFirstFrame (bool): Flag indicating if the first frame has been processed.
+
+ Methods:
+ apply: Apply the chosen method to a raw frame and optionally use provided detections.
+ apply_ecc: Apply the ECC algorithm to a raw frame.
+ apply_features: Apply feature-based methods like ORB or SIFT to a raw frame.
+ apply_sparseoptflow: Apply the Sparse Optical Flow method to a raw frame.
+ reset_params: Reset the internal parameters of the GMC object.
+
+ Examples:
+ Create a GMC object and apply it to a frame
+ >>> gmc = GMC(method="sparseOptFlow", downscale=2)
+ >>> frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
+ >>> warp = gmc.apply(frame)
+ >>> print(warp.shape)
+ (2, 3)
+ """
def __init__(self, method: str = "sparseOptFlow", downscale: int = 2) -> None:
+ """Initialize a Generalized Motion Compensation (GMC) object with tracking method and downscale factor.
+
+ Args:
+ method (str): The tracking method to use. Options include 'orb', 'sift', 'ecc', 'sparseOptFlow', 'none'.
+ downscale (int): Downscale factor for processing frames.
+ """
super().__init__()
self.method = method
@@ -50,6 +84,22 @@ self.initializedFirstFrame = False
def apply(self, raw_frame: np.ndarray, detections: list | None = None) -> np.ndarray:
+ """Estimate a 2×3 motion compensation warp for a frame.
+
+ Args:
+ raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).
+ detections (list, optional): List of detections to be used in the processing.
+
+ Returns:
+ (np.ndarray): Transformation matrix with shape (2, 3).
+
+ Examples:
+ >>> gmc = GMC(method="sparseOptFlow")
+ >>> raw_frame = np.random.rand(480, 640, 3)
+ >>> transformation_matrix = gmc.apply(raw_frame)
+ >>> print(transformation_matrix.shape)
+ (2, 3)
+ """
if self.method in {"orb", "sift"}:
return self.apply_features(raw_frame, detections)
elif self.method == "ecc":
@@ -60,6 +110,21 @@ return np.eye(2, 3)
def apply_ecc(self, raw_frame: np.ndarray) -> np.ndarray:
+ """Apply the ECC (Enhanced Correlation Coefficient) algorithm to a raw frame for motion compensation.
+
+ Args:
+ raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).
+
+ Returns:
+ (np.ndarray): Transformation matrix with shape (2, 3).
+
+ Examples:
+ >>> gmc = GMC(method="ecc")
+ >>> processed_frame = gmc.apply_ecc(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
+ >>> print(processed_frame)
+ [[1. 0. 0.]
+ [0. 1. 0.]]
+ """
height, width, c = raw_frame.shape
frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame
H = np.eye(2, 3, dtype=np.float32)
@@ -84,6 +149,22 @@ return H
def apply_features(self, raw_frame: np.ndarray, detections: list | None = None) -> np.ndarray:
+ """Apply feature-based methods like ORB or SIFT to a raw frame.
+
+ Args:
+ raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).
+ detections (list, optional): List of detections to be used in the processing.
+
+ Returns:
+ (np.ndarray): Transformation matrix with shape (2, 3).
+
+ Examples:
+ >>> gmc = GMC(method="orb")
+ >>> raw_frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
+ >>> transformation_matrix = gmc.apply_features(raw_frame)
+ >>> print(transformation_matrix.shape)
+ (2, 3)
+ """
height, width, c = raw_frame.shape
frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame
H = np.eye(2, 3)
@@ -185,6 +266,21 @@ return H
def apply_sparseoptflow(self, raw_frame: np.ndarray) -> np.ndarray:
+ """Apply Sparse Optical Flow method to a raw frame.
+
+ Args:
+ raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).
+
+ Returns:
+ (np.ndarray): Transformation matrix with shape (2, 3).
+
+ Examples:
+ >>> gmc = GMC()
+ >>> result = gmc.apply_sparseoptflow(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
+ >>> print(result)
+ [[1. 0. 0.]
+ [0. 1. 0.]]
+ """
height, width, c = raw_frame.shape
frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame
H = np.eye(2, 3)
@@ -236,7 +332,8 @@ return H
def reset_params(self) -> None:
+ """Reset the internal parameters including previous frame, keypoints, and descriptors."""
self.prevFrame = None
self.prevKeyPoints = None
self.prevDescriptors = None
- self.initializedFirstFrame = False+ self.initializedFirstFrame = False
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/trackers/utils/gmc.py |
Write docstrings describing functionality | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import glob
import os
import platform
import re
import shutil
import time
from copy import deepcopy
from pathlib import Path
import numpy as np
import torch.cuda
from ultralytics import YOLO, YOLOWorld
from ultralytics.cfg import TASK2DATA, TASK2METRIC
from ultralytics.engine.exporter import export_formats
from ultralytics.utils import ARM64, ASSETS, ASSETS_URL, IS_JETSON, LINUX, LOGGER, MACOS, TQDM, WEIGHTS_DIR, YAML
from ultralytics.utils.checks import IS_PYTHON_3_13, check_imgsz, check_requirements, check_yolo, is_rockchip
from ultralytics.utils.downloads import safe_download
from ultralytics.utils.files import file_size
from ultralytics.utils.torch_utils import get_cpu_info, select_device
def benchmark(
model=WEIGHTS_DIR / "yolo26n.pt",
data=None,
imgsz=160,
half=False,
int8=False,
device="cpu",
verbose=False,
eps=1e-3,
format="",
**kwargs,
):
imgsz = check_imgsz(imgsz)
assert imgsz[0] == imgsz[1] if isinstance(imgsz, list) else True, "benchmark() only supports square imgsz."
import polars as pl # scope for faster 'import ultralytics'
pl.Config.set_tbl_cols(-1) # Show all columns
pl.Config.set_tbl_rows(-1) # Show all rows
pl.Config.set_tbl_width_chars(-1) # No width limit
pl.Config.set_tbl_hide_column_data_types(True) # Hide data types
pl.Config.set_tbl_hide_dataframe_shape(True) # Hide shape info
pl.Config.set_tbl_formatting("ASCII_BORDERS_ONLY_CONDENSED")
device = select_device(device, verbose=False)
if isinstance(model, (str, Path)):
model = YOLO(model)
data = data or TASK2DATA[model.task] # task to dataset, i.e. coco8.yaml for task=detect
key = TASK2METRIC[model.task] # task to metric, i.e. metrics/mAP50-95(B) for task=detect
y = []
t0 = time.time()
format_arg = format.lower()
if format_arg:
formats = frozenset(export_formats()["Argument"])
assert format in formats, f"Expected format to be one of {formats}, but got '{format_arg}'."
for name, format, suffix, cpu, gpu, _ in zip(*export_formats().values()):
emoji, filename = "❌", None # export defaults
try:
if format_arg and format_arg != format:
continue
# Checks
if format == "pb":
assert model.task != "obb", "TensorFlow GraphDef not supported for OBB task"
elif format == "tfjs":
# tensorflowjs pulls in tensorflow-decision-forests which requires protobuf>=6,
# but tensorflow<=2.19 requires protobuf<6, causing an irreconcilable import error
assert False, "TF.js export disabled due to protobuf version conflict in tensorflowjs"
elif format == "edgetpu":
assert LINUX and not ARM64, "Edge TPU export only supported on non-aarch64 Linux"
elif format in {"coreml", "tfjs"}:
assert MACOS or (LINUX and not ARM64), (
"CoreML and TF.js export only supported on macOS and non-aarch64 Linux"
)
if format == "coreml":
assert not IS_PYTHON_3_13, "CoreML not supported on Python 3.13"
if format in {"saved_model", "pb", "tflite", "edgetpu", "tfjs"}:
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 TensorFlow exports not supported by onnx2tf yet"
# assert not IS_PYTHON_MINIMUM_3_12, "TFLite exports not supported on Python>=3.12 yet"
if format == "paddle":
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 Paddle exports not supported yet"
assert model.task != "obb", "Paddle OBB bug https://github.com/PaddlePaddle/Paddle/issues/72024"
assert (LINUX and not IS_JETSON) or MACOS, "Windows and Jetson Paddle exports not supported yet"
if format == "mnn":
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 MNN exports not supported yet"
if format == "ncnn":
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 NCNN exports not supported yet"
if format == "imx":
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 IMX exports not supported"
assert model.task in {"detect", "classify", "pose", "segment"}, (
"IMX export is only supported for detection, classification, pose estimation and segmentation tasks"
)
assert "C2f" in model.__str__(), "IMX only supported for YOLOv8n and YOLO11n"
if format == "rknn":
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 RKNN exports not supported yet"
assert LINUX, "RKNN only supported on Linux"
assert not is_rockchip(), "RKNN Inference only supported on Rockchip devices"
if format == "executorch":
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 ExecuTorch exports not supported yet"
if "cpu" in device.type:
assert cpu, "inference not supported on CPU"
if "cuda" in device.type:
assert gpu, "inference not supported on GPU"
# Export
if format == "-":
filename = model.pt_path or model.ckpt_path or model.model_name
exported_model = deepcopy(model) # PyTorch format
else:
filename = deepcopy(model).export(
imgsz=imgsz, format=format, half=half, int8=int8, data=data, device=device, verbose=False, **kwargs
)
exported_model = YOLO(filename, task=model.task)
assert suffix in str(filename), "export failed"
emoji = "❎" # indicates export succeeded
# Predict
assert model.task != "pose" or format != "pb", "GraphDef Pose inference is not supported"
assert format not in {"edgetpu", "tfjs"}, "inference not supported"
assert format != "coreml" or platform.system() == "Darwin", "inference only supported on macOS>=10.13"
exported_model.predict(ASSETS / "bus.jpg", imgsz=imgsz, device=device, half=half, verbose=False)
# Validate
results = exported_model.val(
data=data,
batch=1,
imgsz=imgsz,
plots=False,
device=device,
half=half,
int8=int8,
verbose=False,
conf=0.001, # all the pre-set benchmark mAP values are based on conf=0.001
)
metric, speed = results.results_dict[key], results.speed["inference"]
fps = round(1000 / (speed + eps), 2) # frames per second
y.append([name, "✅", round(file_size(filename), 1), round(metric, 4), round(speed, 2), fps])
except Exception as e:
if verbose:
assert type(e) is AssertionError, f"Benchmark failure for {name}: {e}"
LOGGER.error(f"Benchmark failure for {name}: {e}")
y.append([name, emoji, round(file_size(filename), 1), None, None, None]) # mAP, t_inference
# Print results
check_yolo(device=device) # print system info
df = pl.DataFrame(y, schema=["Format", "Status❔", "Size (MB)", key, "Inference time (ms/im)", "FPS"], orient="row")
df = df.with_row_index(" ", offset=1) # add index info
df_display = df.with_columns(pl.all().cast(pl.String).fill_null("-"))
name = model.model_name
dt = time.time() - t0
legend = "Benchmarks legend: - ✅ Success - ❎ Export passed but validation failed - ❌️ Export failed"
s = f"\nBenchmarks complete for {name} on {data} at imgsz={imgsz} ({dt:.2f}s)\n{legend}\n{df_display}\n"
LOGGER.info(s)
with open("benchmarks.log", "a", errors="ignore", encoding="utf-8") as f:
f.write(s)
if verbose and isinstance(verbose, float):
metrics = df[key].to_numpy() # values to compare to floor
floor = verbose # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
assert all(x > floor for x in metrics if not np.isnan(x)), f"Benchmark failure: metric(s) < floor {floor}"
return df_display
class RF100Benchmark:
def __init__(self):
self.ds_names = []
self.ds_cfg_list = []
self.rf = None
self.val_metrics = ["class", "images", "targets", "precision", "recall", "map50", "map95"]
def set_key(self, api_key: str):
check_requirements("roboflow")
from roboflow import Roboflow
self.rf = Roboflow(api_key=api_key)
def parse_dataset(self, ds_link_txt: str = "datasets_links.txt"):
(shutil.rmtree("rf-100"), os.mkdir("rf-100")) if os.path.exists("rf-100") else os.mkdir("rf-100")
os.chdir("rf-100")
os.mkdir("ultralytics-benchmarks")
safe_download(f"{ASSETS_URL}/datasets_links.txt")
with open(ds_link_txt, encoding="utf-8") as file:
for line in file:
try:
_, _url, workspace, project, version = re.split("/+", line.strip())
self.ds_names.append(project)
proj_version = f"{project}-{version}"
if not Path(proj_version).exists():
self.rf.workspace(workspace).project(project).version(version).download("yolov8")
else:
LOGGER.info("Dataset already downloaded.")
self.ds_cfg_list.append(Path.cwd() / proj_version / "data.yaml")
except Exception:
continue
return self.ds_names, self.ds_cfg_list
@staticmethod
def fix_yaml(path: Path):
yaml_data = YAML.load(path)
yaml_data["train"] = "train/images"
yaml_data["val"] = "valid/images"
YAML.dump(yaml_data, path)
def evaluate(self, yaml_path: str, val_log_file: str, eval_log_file: str, list_ind: int):
skip_symbols = ["🚀", "⚠️", "💡", "❌"]
class_names = YAML.load(yaml_path)["names"]
with open(val_log_file, encoding="utf-8") as f:
lines = f.readlines()
eval_lines = []
for line in lines:
if any(symbol in line for symbol in skip_symbols):
continue
entries = line.split(" ")
entries = list(filter(lambda val: val != "", entries))
entries = [e.strip("\n") for e in entries]
eval_lines.extend(
{
"class": entries[0],
"images": entries[1],
"targets": entries[2],
"precision": entries[3],
"recall": entries[4],
"map50": entries[5],
"map95": entries[6],
}
for e in entries
if e in class_names or (e == "all" and "(AP)" not in entries and "(AR)" not in entries)
)
map_val = 0.0
if len(eval_lines) > 1:
LOGGER.info("Multiple dicts found")
for lst in eval_lines:
if lst["class"] == "all":
map_val = lst["map50"]
else:
LOGGER.info("Single dict found")
map_val = next(res["map50"] for res in eval_lines)
with open(eval_log_file, "a", encoding="utf-8") as f:
f.write(f"{self.ds_names[list_ind]}: {map_val}\n")
return float(map_val)
class ProfileModels:
def __init__(
self,
paths: list[str],
num_timed_runs: int = 100,
num_warmup_runs: int = 10,
min_time: float = 60,
imgsz: int = 640,
half: bool = True,
trt: bool = True,
device: torch.device | str | None = None,
):
self.paths = paths
self.num_timed_runs = num_timed_runs
self.num_warmup_runs = num_warmup_runs
self.min_time = min_time
self.imgsz = imgsz
self.half = half
self.trt = trt # run TensorRT profiling
self.device = device if isinstance(device, torch.device) else select_device(device)
def run(self):
files = self.get_files()
if not files:
LOGGER.warning("No matching *.pt or *.onnx files found.")
return []
table_rows = []
output = []
for file in files:
engine_file = file.with_suffix(".engine")
if file.suffix in {".pt", ".yaml", ".yml"}:
model = YOLO(str(file))
model.fuse() # to report correct params and GFLOPs in model.info()
model_info = model.info(imgsz=self.imgsz)
if self.trt and self.device.type != "cpu" and not engine_file.is_file():
engine_file = model.export(
format="engine",
half=self.half,
imgsz=self.imgsz,
device=self.device,
verbose=False,
)
onnx_file = model.export(
format="onnx",
imgsz=self.imgsz,
device=self.device,
verbose=False,
)
elif file.suffix == ".onnx":
model_info = self.get_onnx_model_info(file)
onnx_file = file
else:
continue
t_engine = self.profile_tensorrt_model(str(engine_file))
t_onnx = self.profile_onnx_model(str(onnx_file))
table_rows.append(self.generate_table_row(file.stem, t_onnx, t_engine, model_info))
output.append(self.generate_results_dict(file.stem, t_onnx, t_engine, model_info))
self.print_table(table_rows)
return output
def get_files(self):
files = []
for path in self.paths:
path = Path(path)
if path.is_dir():
extensions = ["*.pt", "*.onnx", "*.yaml"]
files.extend([file for ext in extensions for file in glob.glob(str(path / ext))])
elif path.suffix in {".pt", ".yaml", ".yml"}: # add non-existing
files.append(str(path))
else:
files.extend(glob.glob(str(path)))
LOGGER.info(f"Profiling: {sorted(files)}")
return [Path(file) for file in sorted(files)]
@staticmethod
def get_onnx_model_info(onnx_file: str):
return 0.0, 0.0, 0.0, 0.0 # return (num_layers, num_params, num_gradients, num_flops)
@staticmethod
def iterative_sigma_clipping(data: np.ndarray, sigma: float = 2, max_iters: int = 3):
data = np.array(data)
for _ in range(max_iters):
mean, std = np.mean(data), np.std(data)
clipped_data = data[(data > mean - sigma * std) & (data < mean + sigma * std)]
if len(clipped_data) == len(data):
break
data = clipped_data
return data
def profile_tensorrt_model(self, engine_file: str, eps: float = 1e-3):
if not self.trt or not Path(engine_file).is_file():
return 0.0, 0.0
# Model and input
model = YOLO(engine_file)
input_data = np.zeros((self.imgsz, self.imgsz, 3), dtype=np.uint8) # use uint8 for Classify
# Warmup runs
elapsed = 0.0
for _ in range(3):
start_time = time.time()
for _ in range(self.num_warmup_runs):
model(input_data, imgsz=self.imgsz, verbose=False)
elapsed = time.time() - start_time
# Compute number of runs as higher of min_time or num_timed_runs
num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs * 50)
# Timed runs
run_times = []
for _ in TQDM(range(num_runs), desc=engine_file):
results = model(input_data, imgsz=self.imgsz, verbose=False)
run_times.append(results[0].speed["inference"]) # Convert to milliseconds
run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=3) # sigma clipping
return np.mean(run_times), np.std(run_times)
@staticmethod
def check_dynamic(tensor_shape):
return not all(isinstance(dim, int) and dim >= 0 for dim in tensor_shape)
def profile_onnx_model(self, onnx_file: str, eps: float = 1e-3):
check_requirements([("onnxruntime", "onnxruntime-gpu")]) # either package meets requirements
import onnxruntime as ort
# Session with either 'TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'
sess_options = ort.SessionOptions()
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
sess_options.intra_op_num_threads = 8 # Limit the number of threads
sess = ort.InferenceSession(onnx_file, sess_options, providers=["CPUExecutionProvider"])
input_data_dict = {}
for input_tensor in sess.get_inputs():
input_type = input_tensor.type
if self.check_dynamic(input_tensor.shape):
if len(input_tensor.shape) != 4 and self.check_dynamic(input_tensor.shape[1:]):
raise ValueError(f"Unsupported dynamic shape {input_tensor.shape} of {input_tensor.name}")
input_shape = (
(1, 3, self.imgsz, self.imgsz) if len(input_tensor.shape) == 4 else (1, *input_tensor.shape[1:])
)
else:
input_shape = input_tensor.shape
# Mapping ONNX datatype to numpy datatype
if "float16" in input_type:
input_dtype = np.float16
elif "float" in input_type:
input_dtype = np.float32
elif "double" in input_type:
input_dtype = np.float64
elif "int64" in input_type:
input_dtype = np.int64
elif "int32" in input_type:
input_dtype = np.int32
else:
raise ValueError(f"Unsupported ONNX datatype {input_type}")
input_data = np.random.rand(*input_shape).astype(input_dtype)
input_name = input_tensor.name
input_data_dict[input_name] = input_data
output_name = sess.get_outputs()[0].name
# Warmup runs
elapsed = 0.0
for _ in range(3):
start_time = time.time()
for _ in range(self.num_warmup_runs):
sess.run([output_name], input_data_dict)
elapsed = time.time() - start_time
# Compute number of runs as higher of min_time or num_timed_runs
num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs)
# Timed runs
run_times = []
for _ in TQDM(range(num_runs), desc=onnx_file):
start_time = time.time()
sess.run([output_name], input_data_dict)
run_times.append((time.time() - start_time) * 1000) # Convert to milliseconds
run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=5) # sigma clipping
return np.mean(run_times), np.std(run_times)
def generate_table_row(
self,
model_name: str,
t_onnx: tuple[float, float],
t_engine: tuple[float, float],
model_info: tuple[float, float, float, float],
):
_layers, params, _gradients, flops = model_info
return (
f"| {model_name:18s} | {self.imgsz} | - | {t_onnx[0]:.1f}±{t_onnx[1]:.1f} ms | {t_engine[0]:.1f}±"
f"{t_engine[1]:.1f} ms | {params / 1e6:.1f} | {flops:.1f} |"
)
@staticmethod
def generate_results_dict(
model_name: str,
t_onnx: tuple[float, float],
t_engine: tuple[float, float],
model_info: tuple[float, float, float, float],
):
_layers, params, _gradients, flops = model_info
return {
"model/name": model_name,
"model/parameters": params,
"model/GFLOPs": round(flops, 3),
"model/speed_ONNX(ms)": round(t_onnx[0], 3),
"model/speed_TensorRT(ms)": round(t_engine[0], 3),
}
@staticmethod
def print_table(table_rows: list[str]):
gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "GPU"
headers = [
"Model",
"size<br><sup>(pixels)",
"mAP<sup>val<br>50-95",
f"Speed<br><sup>CPU ({get_cpu_info()}) ONNX<br>(ms)",
f"Speed<br><sup>{gpu} TensorRT<br>(ms)",
"params<br><sup>(M)",
"FLOPs<br><sup>(B)",
]
header = "|" + "|".join(f" {h} " for h in headers) + "|"
separator = "|" + "|".join("-" * (len(h) + 2) for h in headers) + "|"
LOGGER.info(f"\n\n{header}")
LOGGER.info(separator)
for row in table_rows:
LOGGER.info(row) | --- +++ @@ -1,4 +1,32 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""
+Benchmark YOLO model formats for speed and accuracy.
+
+Usage:
+ from ultralytics.utils.benchmarks import ProfileModels, benchmark
+ ProfileModels(['yolo26n.yaml', 'yolov8s.yaml']).run()
+ benchmark(model='yolo26n.pt', imgsz=160)
+
+Format | `format=argument` | Model
+--- | --- | ---
+PyTorch | - | yolo26n.pt
+TorchScript | `torchscript` | yolo26n.torchscript
+ONNX | `onnx` | yolo26n.onnx
+OpenVINO | `openvino` | yolo26n_openvino_model/
+TensorRT | `engine` | yolo26n.engine
+CoreML | `coreml` | yolo26n.mlpackage
+TensorFlow SavedModel | `saved_model` | yolo26n_saved_model/
+TensorFlow GraphDef | `pb` | yolo26n.pb
+TensorFlow Lite | `tflite` | yolo26n.tflite
+TensorFlow Edge TPU | `edgetpu` | yolo26n_edgetpu.tflite
+TensorFlow.js | `tfjs` | yolo26n_web_model/
+PaddlePaddle | `paddle` | yolo26n_paddle_model/
+MNN | `mnn` | yolo26n.mnn
+NCNN | `ncnn` | yolo26n_ncnn_model/
+IMX | `imx` | yolo26n_imx_model/
+RKNN | `rknn` | yolo26n_rknn_model/
+ExecuTorch | `executorch` | yolo26n_executorch_model/
+"""
from __future__ import annotations
@@ -36,6 +64,29 @@ format="",
**kwargs,
):
+ """Benchmark a YOLO model across different formats for speed and accuracy.
+
+ Args:
+ model (str | Path): Path to the model file or directory.
+ data (str | None): Dataset to evaluate on, inherited from TASK2DATA if not passed.
+ imgsz (int): Image size for the benchmark.
+ half (bool): Use half-precision for the model if True.
+ int8 (bool): Use int8-precision for the model if True.
+ device (str): Device to run the benchmark on, either 'cpu' or 'cuda'.
+ verbose (bool | float): If True or a float, assert benchmarks pass with given metric.
+ eps (float): Epsilon value for divide by zero prevention.
+ format (str): Export format for benchmarking. If not supplied all formats are benchmarked.
+ **kwargs (Any): Additional keyword arguments for exporter.
+
+ Returns:
+ (polars.DataFrame): A Polars DataFrame with benchmark results for each format, including file size, metric, and
+ inference time.
+
+ Examples:
+ Benchmark a YOLO model with default settings:
+ >>> from ultralytics.utils.benchmarks import benchmark
+ >>> benchmark(model="yolo26n.pt", imgsz=640)
+ """
imgsz = check_imgsz(imgsz)
assert imgsz[0] == imgsz[1] if isinstance(imgsz, list) else True, "benchmark() only supports square imgsz."
@@ -172,20 +223,60 @@
class RF100Benchmark:
+ """Benchmark YOLO model performance on the RF100 dataset collection.
+
+ This class provides functionality to download, process, and evaluate YOLO models on the RF100 datasets.
+
+ Attributes:
+ ds_names (list[str]): Names of datasets used for benchmarking.
+ ds_cfg_list (list[Path]): List of paths to dataset configuration files.
+ rf (Roboflow | None): Roboflow instance for accessing datasets.
+ val_metrics (list[str]): Metrics used for validation.
+
+ Methods:
+ set_key: Set Roboflow API key for accessing datasets.
+ parse_dataset: Parse dataset links and download datasets.
+ fix_yaml: Fix train and validation paths in YAML files.
+ evaluate: Evaluate model performance on validation results.
+ """
def __init__(self):
+ """Initialize the RF100Benchmark class for benchmarking YOLO model performance on RF100 datasets."""
self.ds_names = []
self.ds_cfg_list = []
self.rf = None
self.val_metrics = ["class", "images", "targets", "precision", "recall", "map50", "map95"]
def set_key(self, api_key: str):
+ """Set Roboflow API key for processing.
+
+ Args:
+ api_key (str): The API key.
+
+ Examples:
+ Set the Roboflow API key for accessing datasets:
+ >>> benchmark = RF100Benchmark()
+ >>> benchmark.set_key("your_roboflow_api_key")
+ """
check_requirements("roboflow")
from roboflow import Roboflow
self.rf = Roboflow(api_key=api_key)
def parse_dataset(self, ds_link_txt: str = "datasets_links.txt"):
+ """Parse dataset links and download datasets.
+
+ Args:
+ ds_link_txt (str): Path to the file containing dataset links.
+
+ Returns:
+ (tuple[list[str], list[Path]]): List of dataset names and list of paths to dataset configuration files.
+
+ Examples:
+ >>> benchmark = RF100Benchmark()
+ >>> benchmark.set_key("api_key")
+ >>> benchmark.parse_dataset("datasets_links.txt")
+ """
(shutil.rmtree("rf-100"), os.mkdir("rf-100")) if os.path.exists("rf-100") else os.mkdir("rf-100")
os.chdir("rf-100")
os.mkdir("ultralytics-benchmarks")
@@ -209,12 +300,29 @@
@staticmethod
def fix_yaml(path: Path):
+ """Fix the train and validation paths in a given YAML file."""
yaml_data = YAML.load(path)
yaml_data["train"] = "train/images"
yaml_data["val"] = "valid/images"
YAML.dump(yaml_data, path)
def evaluate(self, yaml_path: str, val_log_file: str, eval_log_file: str, list_ind: int):
+ """Evaluate model performance on validation results.
+
+ Args:
+ yaml_path (str): Path to the YAML configuration file.
+ val_log_file (str): Path to the validation log file.
+ eval_log_file (str): Path to the evaluation log file.
+ list_ind (int): Index of the current dataset in the list.
+
+ Returns:
+ (float): The mean average precision (mAP) value for the evaluated model.
+
+ Examples:
+ Evaluate a model on a specific dataset
+ >>> benchmark = RF100Benchmark()
+ >>> benchmark.evaluate("path/to/data.yaml", "path/to/val_log.txt", "path/to/eval_log.txt", 0)
+ """
skip_symbols = ["🚀", "⚠️", "💡", "❌"]
class_names = YAML.load(yaml_path)["names"]
with open(val_log_file, encoding="utf-8") as f:
@@ -256,6 +364,37 @@
class ProfileModels:
+ """ProfileModels class for profiling different models on ONNX and TensorRT.
+
+ This class profiles the performance of different models, returning results such as model speed and FLOPs.
+
+ Attributes:
+ paths (list[str]): Paths of the models to profile.
+ num_timed_runs (int): Number of timed runs for the profiling.
+ num_warmup_runs (int): Number of warmup runs before profiling.
+ min_time (float): Minimum number of seconds to profile for.
+ imgsz (int): Image size used in the models.
+ half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
+ trt (bool): Flag to indicate whether to profile using TensorRT.
+ device (torch.device): Device used for profiling.
+
+ Methods:
+ run: Profile YOLO models for speed and accuracy across various formats.
+ get_files: Get all relevant model files.
+ get_onnx_model_info: Extract metadata from an ONNX model.
+ iterative_sigma_clipping: Apply sigma clipping to remove outliers.
+ profile_tensorrt_model: Profile a TensorRT model.
+ profile_onnx_model: Profile an ONNX model.
+ generate_table_row: Generate a table row with model metrics.
+ generate_results_dict: Generate a dictionary of profiling results.
+ print_table: Print a formatted table of results.
+
+ Examples:
+ Profile models and print results
+ >>> from ultralytics.utils.benchmarks import ProfileModels
+ >>> profiler = ProfileModels(["yolo26n.yaml", "yolov8s.yaml"], imgsz=640)
+ >>> profiler.run()
+ """
def __init__(
self,
@@ -268,6 +407,21 @@ trt: bool = True,
device: torch.device | str | None = None,
):
+ """Initialize the ProfileModels class for profiling models.
+
+ Args:
+ paths (list[str]): List of paths of the models to be profiled.
+ num_timed_runs (int): Number of timed runs for the profiling.
+ num_warmup_runs (int): Number of warmup runs before the actual profiling starts.
+ min_time (float): Minimum time in seconds for profiling a model.
+ imgsz (int): Size of the image used during profiling.
+ half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
+ trt (bool): Flag to indicate whether to profile using TensorRT.
+ device (torch.device | str | None): Device used for profiling. If None, it is determined automatically.
+
+ Notes:
+ FP16 'half' argument option removed for ONNX as slower on CPU than FP32.
+ """
self.paths = paths
self.num_timed_runs = num_timed_runs
self.num_warmup_runs = num_warmup_runs
@@ -278,6 +432,17 @@ self.device = device if isinstance(device, torch.device) else select_device(device)
def run(self):
+ """Profile YOLO models for speed and accuracy across various formats including ONNX and TensorRT.
+
+ Returns:
+ (list[dict]): List of dictionaries containing profiling results for each model.
+
+ Examples:
+ Profile models and print results
+ >>> from ultralytics.utils.benchmarks import ProfileModels
+ >>> profiler = ProfileModels(["yolo26n.yaml", "yolo11s.yaml"])
+ >>> results = profiler.run()
+ """
files = self.get_files()
if not files:
@@ -321,6 +486,11 @@ return output
def get_files(self):
+ """Return a list of paths for all relevant model files given by the user.
+
+ Returns:
+ (list[Path]): List of Path objects for the model files.
+ """
files = []
for path in self.paths:
path = Path(path)
@@ -337,10 +507,21 @@
@staticmethod
def get_onnx_model_info(onnx_file: str):
+ """Extract metadata from an ONNX model file including layers, parameters, gradients, and FLOPs."""
return 0.0, 0.0, 0.0, 0.0 # return (num_layers, num_params, num_gradients, num_flops)
@staticmethod
def iterative_sigma_clipping(data: np.ndarray, sigma: float = 2, max_iters: int = 3):
+ """Apply iterative sigma clipping to data to remove outliers.
+
+ Args:
+ data (np.ndarray): Input data array.
+ sigma (float): Number of standard deviations to use for clipping.
+ max_iters (int): Maximum number of iterations for the clipping process.
+
+ Returns:
+ (np.ndarray): Clipped data array with outliers removed.
+ """
data = np.array(data)
for _ in range(max_iters):
mean, std = np.mean(data), np.std(data)
@@ -351,6 +532,15 @@ return data
def profile_tensorrt_model(self, engine_file: str, eps: float = 1e-3):
+ """Profile YOLO model performance with TensorRT, measuring average run time and standard deviation.
+
+ Args:
+ engine_file (str): Path to the TensorRT engine file.
+ eps (float): Small epsilon value to prevent division by zero.
+
+ Returns:
+ (tuple[float, float]): Mean and standard deviation of inference time in milliseconds.
+ """
if not self.trt or not Path(engine_file).is_file():
return 0.0, 0.0
@@ -380,9 +570,19 @@
@staticmethod
def check_dynamic(tensor_shape):
+ """Check whether the tensor shape in the ONNX model is dynamic."""
return not all(isinstance(dim, int) and dim >= 0 for dim in tensor_shape)
def profile_onnx_model(self, onnx_file: str, eps: float = 1e-3):
+ """Profile an ONNX model, measuring average inference time and standard deviation across multiple runs.
+
+ Args:
+ onnx_file (str): Path to the ONNX model file.
+ eps (float): Small epsilon value to prevent division by zero.
+
+ Returns:
+ (tuple[float, float]): Mean and standard deviation of inference time in milliseconds.
+ """
check_requirements([("onnxruntime", "onnxruntime-gpu")]) # either package meets requirements
import onnxruntime as ort
@@ -452,6 +652,17 @@ t_engine: tuple[float, float],
model_info: tuple[float, float, float, float],
):
+ """Generate a table row string with model performance metrics.
+
+ Args:
+ model_name (str): Name of the model.
+ t_onnx (tuple): ONNX model inference time statistics (mean, std).
+ t_engine (tuple): TensorRT engine inference time statistics (mean, std).
+ model_info (tuple): Model information (layers, params, gradients, flops).
+
+ Returns:
+ (str): Formatted table row string with model metrics.
+ """
_layers, params, _gradients, flops = model_info
return (
f"| {model_name:18s} | {self.imgsz} | - | {t_onnx[0]:.1f}±{t_onnx[1]:.1f} ms | {t_engine[0]:.1f}±"
@@ -465,6 +676,17 @@ t_engine: tuple[float, float],
model_info: tuple[float, float, float, float],
):
+ """Generate a dictionary of profiling results.
+
+ Args:
+ model_name (str): Name of the model.
+ t_onnx (tuple): ONNX model inference time statistics (mean, std).
+ t_engine (tuple): TensorRT engine inference time statistics (mean, std).
+ model_info (tuple): Model information (layers, params, gradients, flops).
+
+ Returns:
+ (dict): Dictionary containing profiling results.
+ """
_layers, params, _gradients, flops = model_info
return {
"model/name": model_name,
@@ -476,6 +698,11 @@
@staticmethod
def print_table(table_rows: list[str]):
+ """Print a formatted table of model profiling results.
+
+ Args:
+ table_rows (list[str]): List of formatted table row strings.
+ """
gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "GPU"
headers = [
"Model",
@@ -492,4 +719,4 @@ LOGGER.info(f"\n\n{header}")
LOGGER.info(separator)
for row in table_rows:
- LOGGER.info(row)+ LOGGER.info(row)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/benchmarks.py |
Write docstrings describing functionality | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import contextlib
import importlib.metadata
import inspect
import json
import logging
import os
import platform
import re
import socket
import sys
import threading
import time
import warnings
from functools import lru_cache
from pathlib import Path
from threading import Lock
from types import SimpleNamespace
from urllib.parse import unquote
import cv2
import numpy as np
import torch
from ultralytics import __version__
from ultralytics.utils.git import GitRepo
from ultralytics.utils.patches import imread, imshow, imwrite, torch_save # for patches
from ultralytics.utils.tqdm import TQDM # noqa
# PyTorch Multi-GPU DDP Constants
RANK = int(os.getenv("RANK", -1))
LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
# Other Constants
ARGV = sys.argv or ["", ""] # sometimes sys.argv = []
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1] # YOLO
ASSETS = ROOT / "assets" # default images
ASSETS_URL = "https://github.com/ultralytics/assets/releases/download/v0.0.0" # assets GitHub URL
DEFAULT_CFG_PATH = ROOT / "cfg/default.yaml"
NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLO multiprocessing threads
AUTOINSTALL = str(os.getenv("YOLO_AUTOINSTALL", True)).lower() == "true" # global auto-install mode
VERBOSE = str(os.getenv("YOLO_VERBOSE", True)).lower() == "true" # global verbose mode
LOGGING_NAME = "ultralytics"
MACOS, LINUX, WINDOWS = (platform.system() == x for x in ["Darwin", "Linux", "Windows"]) # environment booleans
MACOS_VERSION = platform.mac_ver()[0] if MACOS else None
NOT_MACOS14 = not (MACOS and MACOS_VERSION.startswith("14."))
ARM64 = platform.machine() in {"arm64", "aarch64"} # ARM64 booleans
PYTHON_VERSION = platform.python_version()
TORCH_VERSION = str(torch.__version__) # Normalize torch.__version__ (PyTorch>1.9 returns TorchVersion objects)
TORCHVISION_VERSION = importlib.metadata.version("torchvision") # faster than importing torchvision
IS_VSCODE = os.environ.get("TERM_PROGRAM", False) == "vscode"
RKNN_CHIPS = frozenset(
{
"rk3588",
"rk3576",
"rk3566",
"rk3568",
"rk3562",
"rv1103",
"rv1106",
"rv1103b",
"rv1106b",
"rk2118",
"rv1126b",
}
) # Rockchip processors available for export
HELP_MSG = """
Examples for running Ultralytics:
1. Install the ultralytics package:
pip install ultralytics
2. Use the Python SDK:
from ultralytics import YOLO
# Load a model
model = YOLO("yolo26n.yaml") # build a new model from scratch
model = YOLO("yolo26n.pt") # load a pretrained model (recommended for training)
# Use the model
results = model.train(data="coco8.yaml", epochs=3) # train the model
results = model.val() # evaluate model performance on the validation set
results = model("https://ultralytics.com/images/bus.jpg") # predict on an image
success = model.export(format="onnx") # export the model to ONNX format
3. Use the command line interface (CLI):
Ultralytics 'yolo' CLI commands use the following syntax:
yolo TASK MODE ARGS
Where TASK (optional) is one of [detect, segment, classify, pose, obb]
MODE (required) is one of [train, val, predict, export, track, benchmark]
ARGS (optional) are any number of custom "arg=value" pairs like "imgsz=320" that override defaults.
See all ARGS at https://docs.ultralytics.com/usage/cfg or with "yolo cfg"
- Train a detection model for 10 epochs with an initial learning_rate of 0.01
yolo detect train data=coco8.yaml model=yolo26n.pt epochs=10 lr0=0.01
- Predict a YouTube video using a pretrained segmentation model at image size 320:
yolo segment predict model=yolo26n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320
- Val a pretrained detection model at batch-size 1 and image size 640:
yolo detect val model=yolo26n.pt data=coco8.yaml batch=1 imgsz=640
- Export a YOLO26n classification model to ONNX format at image size 224 by 128 (no TASK required)
yolo export model=yolo26n-cls.pt format=onnx imgsz=224,128
- Run special commands:
yolo help
yolo checks
yolo version
yolo settings
yolo copy-cfg
yolo cfg
Docs: https://docs.ultralytics.com
Community: https://community.ultralytics.com
GitHub: https://github.com/ultralytics/ultralytics
"""
# Settings and Environment Variables
torch.set_printoptions(linewidth=320, precision=4, profile="default")
np.set_printoptions(linewidth=320, formatter=dict(float_kind="{:11.5g}".format)) # format short g, %precision=5
cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
os.environ["NUMEXPR_MAX_THREADS"] = str(NUM_THREADS) # NumExpr max threads
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # suppress verbose TF compiler warnings in Colab
os.environ["TORCH_CPP_LOG_LEVEL"] = "ERROR" # suppress "NNPACK.cpp could not initialize NNPACK" warnings
os.environ["KINETO_LOG_LEVEL"] = "5" # suppress verbose PyTorch profiler output when computing FLOPs
# Centralized warning suppression
warnings.filterwarnings("ignore", message="torch.distributed.reduce_op is deprecated") # PyTorch deprecation
warnings.filterwarnings("ignore", message="The figure layout has changed to tight") # matplotlib>=3.7.2
warnings.filterwarnings("ignore", category=FutureWarning, module="timm") # mobileclip timm.layers deprecation
warnings.filterwarnings("ignore", category=torch.jit.TracerWarning) # ONNX/TorchScript export tracer warnings
warnings.filterwarnings("ignore", category=UserWarning, message=".*prim::Constant.*") # ONNX shape warning
warnings.filterwarnings("ignore", category=DeprecationWarning, module="coremltools") # CoreML np.bool deprecation
logging.getLogger("coremltools").setLevel(logging.ERROR) # Suppress native binary load failures on non-macOS
# Precompiled type tuples for faster isinstance() checks
FLOAT_OR_INT = (float, int)
STR_OR_PATH = (str, Path)
class DataExportMixin:
def to_df(self, normalize=False, decimals=5):
import polars as pl # scope for faster 'import ultralytics'
return pl.DataFrame(self.summary(normalize=normalize, decimals=decimals))
def to_csv(self, normalize=False, decimals=5):
import polars as pl
df = self.to_df(normalize=normalize, decimals=decimals)
try:
return df.write_csv()
except Exception:
# Minimal string conversion for any remaining complex types
def _to_str_simple(v):
if v is None:
return ""
elif isinstance(v, (dict, list, tuple, set)):
return repr(v)
else:
return str(v)
df_str = df.select(
[pl.col(c).map_elements(_to_str_simple, return_dtype=pl.String).alias(c) for c in df.columns]
)
return df_str.write_csv()
def to_json(self, normalize=False, decimals=5):
return self.to_df(normalize=normalize, decimals=decimals).write_json()
class SimpleClass:
def __str__(self):
attr = []
for a in dir(self):
v = getattr(self, a)
if not callable(v) and not a.startswith("_"):
if isinstance(v, SimpleClass):
# Display only the module and class name for subclasses
s = f"{a}: {v.__module__}.{v.__class__.__name__} object"
else:
s = f"{a}: {v!r}"
attr.append(s)
return f"{self.__module__}.{self.__class__.__name__} object with attributes:\n\n" + "\n".join(attr)
def __repr__(self):
return self.__str__()
def __getattr__(self, attr):
name = self.__class__.__name__
raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")
class IterableSimpleNamespace(SimpleNamespace):
def __iter__(self):
return iter(vars(self).items())
def __str__(self):
return "\n".join(f"{k}={v}" for k, v in vars(self).items())
def __getattr__(self, attr):
name = self.__class__.__name__
raise AttributeError(
f"""
'{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics
'default.yaml' file.\nPlease update your code with 'pip install -U ultralytics' and if necessary replace
{DEFAULT_CFG_PATH} with the latest version from
https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml
"""
)
def get(self, key, default=None):
return getattr(self, key, default)
def plt_settings(rcparams=None, backend="Agg"):
if rcparams is None:
rcparams = {"font.size": 11}
def decorator(func):
def wrapper(*args, **kwargs):
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
# Prepend Arial Unicode for non-Latin text (CJK, Arabic, etc.); matplotlib falls back if missing
if "font.sans-serif" not in rcparams and not wrapper._fonts_registered:
from matplotlib import font_manager
# Register any fonts in Ultralytics config dir (e.g. Arial.Unicode.ttf) with matplotlib
known = {f.fname for f in font_manager.fontManager.ttflist}
for f in USER_CONFIG_DIR.glob("*.ttf"):
if str(f) not in known:
font_manager.fontManager.addfont(str(f))
wrapper._fonts_registered = True
rc = (
rcparams
if "font.sans-serif" in rcparams
else {**rcparams, "font.sans-serif": ["Arial Unicode MS", *plt.rcParams.get("font.sans-serif", [])]}
)
original_backend = plt.get_backend()
switch = backend.lower() != original_backend.lower()
if switch:
plt.close("all") # auto-close()ing of figures upon backend switching is deprecated since 3.8
plt.switch_backend(backend)
# Plot with backend and always revert to original backend
try:
with plt.rc_context(rc):
result = func(*args, **kwargs)
finally:
if switch:
plt.close("all")
plt.switch_backend(original_backend)
return result
wrapper._fonts_registered = False
return wrapper
return decorator
def set_logging(name="LOGGING_NAME", verbose=True):
level = logging.INFO if verbose and RANK in {-1, 0} else logging.ERROR # rank in world for Multi-GPU trainings
class PrefixFormatter(logging.Formatter):
def format(self, record):
# Apply prefixes based on log level
if record.levelno == logging.WARNING:
prefix = "WARNING" if WINDOWS else "WARNING ⚠️"
record.msg = f"{prefix} {record.msg}"
elif record.levelno == logging.ERROR:
prefix = "ERROR" if WINDOWS else "ERROR ❌"
record.msg = f"{prefix} {record.msg}"
# Handle emojis in message based on platform
formatted_message = super().format(record)
return emojis(formatted_message)
formatter = PrefixFormatter("%(message)s")
# Handle Windows UTF-8 encoding issues
if WINDOWS and hasattr(sys.stdout, "encoding") and sys.stdout.encoding != "utf-8":
with contextlib.suppress(Exception):
# Attempt to reconfigure stdout to use UTF-8 encoding if possible
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
# For environments where reconfigure is not available, wrap stdout in a TextIOWrapper
elif hasattr(sys.stdout, "buffer"):
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
# Create and configure the StreamHandler with the appropriate formatter and level
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
stream_handler.setLevel(level)
# Set up the logger
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(stream_handler)
logger.propagate = False
return logger
# Set logger
LOGGER = set_logging(LOGGING_NAME, verbose=VERBOSE) # define globally (used in train.py, val.py, predict.py, etc.)
logging.getLogger("sentry_sdk").setLevel(logging.CRITICAL + 1)
def emojis(string=""):
return string.encode().decode("ascii", "ignore") if WINDOWS else string
class ThreadingLocked:
def __init__(self):
self.lock = threading.Lock()
def __call__(self, f):
from functools import wraps
@wraps(f)
def decorated(*args, **kwargs):
with self.lock:
return f(*args, **kwargs)
return decorated
class YAML:
_instance = None
@classmethod
def _get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
import yaml
self.yaml = yaml
# Use C-based implementation if available for better performance
try:
self.SafeLoader = yaml.CSafeLoader
self.SafeDumper = yaml.CSafeDumper
except (AttributeError, ImportError):
self.SafeLoader = yaml.SafeLoader
self.SafeDumper = yaml.SafeDumper
@classmethod
def save(cls, file="data.yaml", data=None, header=""):
instance = cls._get_instance()
if data is None:
data = {}
# Create parent directories if needed
file = Path(file)
file.parent.mkdir(parents=True, exist_ok=True)
# Convert non-serializable objects to strings
valid_types = int, float, str, bool, list, tuple, dict, type(None)
for k, v in data.items():
if not isinstance(v, valid_types):
data[k] = str(v)
# Write YAML file
with open(file, "w", errors="ignore", encoding="utf-8") as f:
if header:
f.write(header)
instance.yaml.dump(data, f, sort_keys=False, allow_unicode=True, Dumper=instance.SafeDumper)
@classmethod
def load(cls, file="data.yaml", append_filename=False):
instance = cls._get_instance()
assert str(file).endswith((".yaml", ".yml")), f"Not a YAML file: {file}"
# Read file content
with open(file, errors="ignore", encoding="utf-8") as f:
s = f.read()
# Try loading YAML with fallback for problematic characters
try:
data = instance.yaml.load(s, Loader=instance.SafeLoader) or {}
except Exception as e:
# Remove problematic characters and retry
s = re.sub(r"[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+", "", s)
try:
data = instance.yaml.load(s, Loader=instance.SafeLoader) or {}
except Exception:
raise ValueError(
f"YAML syntax error in '{file}': {e}\nVerify YAML with https://ray.run/tools/yaml-formatter"
) from None
# Check for accidental user-error None strings (should be 'null' in YAML)
if "None" in data.values():
data = {k: None if v == "None" else v for k, v in data.items()}
if append_filename:
data["yaml_file"] = str(file)
return data
@classmethod
def print(cls, yaml_file):
instance = cls._get_instance()
# Load file if path provided
yaml_dict = cls.load(yaml_file) if isinstance(yaml_file, (str, Path)) else yaml_file
# Use -1 for unlimited width in C implementation
dump = instance.yaml.dump(yaml_dict, sort_keys=False, allow_unicode=True, width=-1, Dumper=instance.SafeDumper)
LOGGER.info(f"Printing '{colorstr('bold', 'black', yaml_file)}'\n\n{dump}")
# Default configuration
DEFAULT_CFG_DICT = YAML.load(DEFAULT_CFG_PATH)
DEFAULT_CFG_KEYS = DEFAULT_CFG_DICT.keys()
DEFAULT_CFG = IterableSimpleNamespace(**DEFAULT_CFG_DICT)
def read_device_model() -> str:
return platform.release().lower()
def is_ubuntu() -> bool:
try:
with open("/etc/os-release") as f:
return "ID=ubuntu" in f.read()
except FileNotFoundError:
return False
def is_debian(codenames: list[str] | None | str = None) -> list[bool] | bool:
try:
with open("/etc/os-release") as f:
content = f.read()
if codenames is None:
return "ID=debian" in content
if isinstance(codenames, str):
codenames = [codenames]
return [
f"VERSION_CODENAME={codename}" in content if codename else "ID=debian" in content
for codename in codenames
]
except FileNotFoundError:
return [False] * len(codenames) if codenames else False
def is_colab():
return "COLAB_RELEASE_TAG" in os.environ or "COLAB_BACKEND_VERSION" in os.environ
def is_kaggle():
return os.environ.get("PWD") == "/kaggle/working" and os.environ.get("KAGGLE_URL_BASE") == "https://www.kaggle.com"
def is_jupyter():
return IS_COLAB or IS_KAGGLE
def is_runpod():
return "RUNPOD_POD_ID" in os.environ
def is_docker() -> bool:
try:
return os.path.exists("/.dockerenv")
except Exception:
return False
def is_raspberrypi() -> bool:
return "rpi" in DEVICE_MODEL
@lru_cache(maxsize=3)
def is_jetson(jetpack=None) -> bool:
jetson = "tegra" in DEVICE_MODEL
if jetson and jetpack:
try:
content = open("/etc/nv_tegra_release").read()
version_map = {4: "R32", 5: "R35", 6: "R36", 7: "R38"} # JetPack to L4T major version mapping
return jetpack in version_map and version_map[jetpack] in content
except Exception:
return False
return jetson
def is_dgx() -> bool:
try:
with open("/etc/dgx-release") as f:
return "DGX" in f.read()
except FileNotFoundError:
return False
def is_online() -> bool:
if str(os.getenv("YOLO_OFFLINE", "")).lower() == "true":
return False
for host in ("one.one.one.one", "dns.google"):
try:
socket.getaddrinfo(host, 0, socket.AF_UNSPEC, 0, 0, socket.AI_ADDRCONFIG)
return True
except OSError:
continue
return False
def is_pip_package(filepath: str = __name__) -> bool:
import importlib.util
# Get the spec for the module
spec = importlib.util.find_spec(filepath)
# Return whether the spec is not None and the origin is not None (indicating it is a package)
return spec is not None and spec.origin is not None
def is_dir_writeable(dir_path: str | Path) -> bool:
return os.access(str(dir_path), os.W_OK)
def is_pytest_running():
return ("PYTEST_CURRENT_TEST" in os.environ) or ("pytest" in sys.modules) or ("pytest" in Path(ARGV[0]).stem)
def is_github_action_running() -> bool:
return "GITHUB_ACTIONS" in os.environ and "GITHUB_WORKFLOW" in os.environ and "RUNNER_OS" in os.environ
def get_default_args(func):
signature = inspect.signature(func)
return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}
def get_ubuntu_version():
if is_ubuntu():
try:
with open("/etc/os-release") as f:
return re.search(r'VERSION_ID="(\d+\.\d+)"', f.read())[1]
except (FileNotFoundError, AttributeError):
return None
def get_user_config_dir(sub_dir="Ultralytics"):
if env_dir := os.getenv("YOLO_CONFIG_DIR"):
p = Path(env_dir).expanduser() / sub_dir
elif LINUX:
p = Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config")) / sub_dir
elif WINDOWS:
p = Path.home() / "AppData" / "Roaming" / sub_dir
elif MACOS:
p = Path.home() / "Library" / "Application Support" / sub_dir
else:
raise ValueError(f"Unsupported operating system: {platform.system()}")
if p.exists(): # already created → trust it
return p
if is_dir_writeable(p.parent): # create if possible
p.mkdir(parents=True, exist_ok=True)
return p
# Fallbacks for Docker, GCP/AWS functions where only /tmp is writable
for alt in [Path("/tmp") / sub_dir, Path.cwd() / sub_dir]:
if alt.exists():
return alt
if is_dir_writeable(alt.parent):
alt.mkdir(parents=True, exist_ok=True)
LOGGER.warning(
f"user config directory '{p}' is not writable, using '{alt}'. Set YOLO_CONFIG_DIR to override."
)
return alt
# Last fallback → CWD
p = Path.cwd() / sub_dir
p.mkdir(parents=True, exist_ok=True)
return p
# Define constants (required below)
DEVICE_MODEL = read_device_model() # is_jetson() and is_raspberrypi() depend on this constant
ONLINE = is_online()
IS_COLAB = is_colab()
IS_KAGGLE = is_kaggle()
IS_DOCKER = is_docker()
IS_JETSON = is_jetson()
IS_JUPYTER = is_jupyter()
IS_PIP_PACKAGE = is_pip_package()
IS_RASPBERRYPI = is_raspberrypi()
IS_DEBIAN, IS_DEBIAN_BOOKWORM, IS_DEBIAN_TRIXIE = is_debian([None, "bookworm", "trixie"])
IS_UBUNTU = is_ubuntu()
GIT = GitRepo()
USER_CONFIG_DIR = get_user_config_dir() # Ultralytics settings dir
SETTINGS_FILE = USER_CONFIG_DIR / "settings.json"
def colorstr(*input):
*args, string = input if len(input) > 1 else ("blue", "bold", input[0]) # color arguments, string
colors = {
"black": "\033[30m", # basic colors
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"magenta": "\033[35m",
"cyan": "\033[36m",
"white": "\033[37m",
"bright_black": "\033[90m", # bright colors
"bright_red": "\033[91m",
"bright_green": "\033[92m",
"bright_yellow": "\033[93m",
"bright_blue": "\033[94m",
"bright_magenta": "\033[95m",
"bright_cyan": "\033[96m",
"bright_white": "\033[97m",
"end": "\033[0m", # misc
"bold": "\033[1m",
"underline": "\033[4m",
}
return "".join(colors[x] for x in args) + f"{string}" + colors["end"]
def remove_colorstr(input_string):
ansi_escape = re.compile(r"\x1B\[[0-9;]*[A-Za-z]")
return ansi_escape.sub("", input_string)
class TryExcept(contextlib.ContextDecorator):
def __init__(self, msg="", verbose=True):
self.msg = msg
self.verbose = verbose
def __enter__(self):
pass
def __exit__(self, exc_type, value, traceback):
if self.verbose and value:
LOGGER.warning(f"{self.msg}{': ' if self.msg else ''}{value}")
return True
class Retry(contextlib.ContextDecorator):
def __init__(self, times=3, delay=2):
self.times = times
self.delay = delay
self._attempts = 0
def __call__(self, func):
def wrapped_func(*args, **kwargs):
self._attempts = 0
while self._attempts < self.times:
try:
return func(*args, **kwargs)
except Exception as e:
self._attempts += 1
LOGGER.warning(f"Retry {self._attempts}/{self.times} failed: {e}")
if self._attempts >= self.times:
raise e
time.sleep(self.delay * (2**self._attempts)) # exponential backoff delay
return wrapped_func
def threaded(func):
def wrapper(*args, **kwargs):
if kwargs.pop("threaded", True): # run in thread
thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
thread.start()
return thread
else:
return func(*args, **kwargs)
return wrapper
def set_sentry():
if (
not SETTINGS["sync"]
or RANK not in {-1, 0}
or Path(ARGV[0]).name != "yolo"
or TESTS_RUNNING
or not ONLINE
or not IS_PIP_PACKAGE
or GIT.is_repo
):
return
# If sentry_sdk package is not installed then return and do not use Sentry
try:
import sentry_sdk
except ImportError:
return
def before_send(event, hint):
if "exc_info" in hint:
exc_type, exc_value, _ = hint["exc_info"]
if exc_type in {KeyboardInterrupt, FileNotFoundError} or "out of memory" in str(exc_value):
return None # do not send event
event["tags"] = {
"sys_argv": ARGV[0],
"sys_argv_name": Path(ARGV[0]).name,
"install": "git" if GIT.is_repo else "pip" if IS_PIP_PACKAGE else "other",
"os": ENVIRONMENT,
}
return event
sentry_sdk.init(
dsn="https://888e5a0778212e1d0314c37d4b9aae5d@o4504521589325824.ingest.us.sentry.io/4504521592406016",
debug=False,
auto_enabling_integrations=False,
traces_sample_rate=1.0,
release=__version__,
environment="runpod" if is_runpod() else "production",
before_send=before_send,
ignore_errors=[KeyboardInterrupt, FileNotFoundError],
)
sentry_sdk.set_user({"id": SETTINGS["uuid"]}) # SHA-256 anonymized UUID hash
class JSONDict(dict):
def __init__(self, file_path: str | Path = "data.json"):
super().__init__()
self.file_path = Path(file_path)
self.lock = Lock()
self._load()
def _load(self):
try:
if self.file_path.exists():
with open(self.file_path) as f:
# Use the base dict update to avoid persisting during reads
super().update(json.load(f))
except json.JSONDecodeError:
LOGGER.warning(f"Error decoding JSON from {self.file_path}. Starting with an empty dictionary.")
except Exception as e:
LOGGER.error(f"Error reading from {self.file_path}: {e}")
def _save(self):
try:
self.file_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.file_path, "w", encoding="utf-8") as f:
json.dump(dict(self), f, indent=2, default=self._json_default)
except Exception as e:
LOGGER.error(f"Error writing to {self.file_path}: {e}")
@staticmethod
def _json_default(obj):
if isinstance(obj, Path):
return str(obj)
raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
def __setitem__(self, key, value):
with self.lock:
super().__setitem__(key, value)
self._save()
def __delitem__(self, key):
with self.lock:
super().__delitem__(key)
self._save()
def __str__(self):
contents = json.dumps(dict(self), indent=2, ensure_ascii=False, default=self._json_default)
return f'JSONDict("{self.file_path}"):\n{contents}'
def update(self, *args, **kwargs):
with self.lock:
super().update(*args, **kwargs)
self._save()
def clear(self):
with self.lock:
super().clear()
self._save()
class SettingsManager(JSONDict):
def __init__(self, file=SETTINGS_FILE, version="0.0.6"):
import hashlib
import uuid
from ultralytics.utils.torch_utils import torch_distributed_zero_first
root = GIT.root or Path()
datasets_root = (root.parent if GIT.root and is_dir_writeable(root.parent) else root).resolve()
self.file = Path(file)
self.version = version
self.defaults = {
"settings_version": version, # Settings schema version
"datasets_dir": str(datasets_root / "datasets"), # Datasets directory
"weights_dir": str(root / "weights"), # Model weights directory
"runs_dir": str(root / "runs"), # Experiment runs directory
"uuid": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(), # SHA-256 anonymized UUID hash
"sync": True, # Enable synchronization
"api_key": "", # Ultralytics API Key
"openai_api_key": "", # OpenAI API Key
"clearml": True, # ClearML integration
"comet": True, # Comet integration
"dvc": True, # DVC integration
"hub": True, # Ultralytics HUB integration
"mlflow": True, # MLflow integration
"neptune": True, # Neptune integration
"raytune": True, # Ray Tune integration
"tensorboard": False, # TensorBoard logging
"wandb": False, # Weights & Biases logging
"vscode_msg": True, # VSCode message
"openvino_msg": True, # OpenVINO export on Intel CPU message
}
self.help_msg = (
f"\nView Ultralytics Settings with 'yolo settings' or at '{self.file}'"
"\nUpdate Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. "
"For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings."
)
with torch_distributed_zero_first(LOCAL_RANK):
super().__init__(self.file)
if not self.file.exists() or not self: # Check if file doesn't exist or is empty
LOGGER.info(f"Creating new Ultralytics Settings v{version} file ✅ {self.help_msg}")
self.reset()
self._validate_settings()
def _validate_settings(self):
correct_keys = frozenset(self.keys()) == frozenset(self.defaults.keys())
correct_types = all(isinstance(self.get(k), type(v)) for k, v in self.defaults.items())
correct_version = self.get("settings_version", "") == self.version
if not (correct_keys and correct_types and correct_version):
LOGGER.warning(
"Ultralytics settings reset to default values. This may be due to a possible problem "
f"with your settings or a recent ultralytics package update. {self.help_msg}"
)
self.reset()
if self.get("datasets_dir") == self.get("runs_dir"):
LOGGER.warning(
f"Ultralytics setting 'datasets_dir: {self.get('datasets_dir')}' "
f"must be different than 'runs_dir: {self.get('runs_dir')}'. "
f"Please change one to avoid possible issues during training. {self.help_msg}"
)
def __setitem__(self, key, value):
self.update({key: value})
def update(self, *args, **kwargs):
for arg in args:
if isinstance(arg, dict):
kwargs.update(arg)
for k, v in kwargs.items():
if k not in self.defaults:
raise KeyError(f"No Ultralytics setting '{k}'. {self.help_msg}")
t = type(self.defaults[k])
if not isinstance(v, t):
raise TypeError(
f"Ultralytics setting '{k}' must be '{t.__name__}' type, not '{type(v).__name__}'. {self.help_msg}"
)
super().update(*args, **kwargs)
def reset(self):
self.clear()
self.update(self.defaults)
def deprecation_warn(arg, new_arg=None):
msg = f"'{arg}' is deprecated and will be removed in the future."
if new_arg is not None:
msg += f" Use '{new_arg}' instead."
LOGGER.warning(msg)
def clean_url(url):
url = Path(url).as_posix().replace(":/", "://") # Pathlib turns :// -> :/, as_posix() for Windows
return unquote(url).split("?", 1)[0] # '%2F' to '/', split https://url.com/file.txt?auth
def url2file(url):
return Path(clean_url(url)).name
def vscode_msg(ext="ultralytics.ultralytics-snippets") -> str:
path = (USER_CONFIG_DIR.parents[2] if WINDOWS else USER_CONFIG_DIR.parents[1]) / ".vscode/extensions"
obs_file = path / ".obsolete" # file tracks uninstalled extensions, while source directory remains
installed = any(path.glob(f"{ext}*")) and ext not in (obs_file.read_text("utf-8") if obs_file.exists() else "")
url = "https://docs.ultralytics.com/integrations/vscode"
return "" if installed else f"{colorstr('VS Code:')} view Ultralytics VS Code Extension ⚡ at {url}"
# Run below code on utils init ------------------------------------------------------------------------------------
# Check first-install steps
PREFIX = colorstr("Ultralytics: ")
SETTINGS = SettingsManager() # initialize settings
PERSISTENT_CACHE = JSONDict(USER_CONFIG_DIR / "persistent_cache.json") # initialize persistent cache
DATASETS_DIR = Path(SETTINGS["datasets_dir"]) # global datasets directory
WEIGHTS_DIR = Path(SETTINGS["weights_dir"]) # global weights directory
RUNS_DIR = Path(SETTINGS["runs_dir"]) # global runs directory
ENVIRONMENT = (
"Colab"
if IS_COLAB
else "Kaggle"
if IS_KAGGLE
else "Jupyter"
if IS_JUPYTER
else "Docker"
if IS_DOCKER
else platform.system()
)
TESTS_RUNNING = is_pytest_running() or is_github_action_running()
set_sentry()
# Apply monkey patches
torch.save = torch_save
if WINDOWS:
# Apply cv2 patches for non-ASCII and non-UTF characters in image paths
cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow | --- +++ @@ -149,13 +149,50 @@
class DataExportMixin:
+ """Mixin class for exporting validation metrics or prediction results in various formats.
+
+ This class provides utilities to export performance metrics (e.g., mAP, precision, recall) or prediction results
+ from classification, object detection, segmentation, or pose estimation tasks into various formats: Polars
+ DataFrame, CSV, and JSON.
+
+ Methods:
+ to_df: Convert summary to a Polars DataFrame.
+ to_csv: Export results as a CSV string.
+ to_json: Export results as a JSON string.
+ tojson: Deprecated alias for `to_json()`.
+
+ Examples:
+ >>> model = YOLO("yolo26n.pt")
+ >>> results = model("image.jpg")
+ >>> df = results.to_df()
+ >>> print(df)
+ >>> csv_data = results.to_csv()
+ """
def to_df(self, normalize=False, decimals=5):
+ """Create a Polars DataFrame from the prediction results summary or validation metrics.
+
+ Args:
+ normalize (bool, optional): Normalize numerical values for easier comparison.
+ decimals (int, optional): Decimal places to round floats.
+
+ Returns:
+ (polars.DataFrame): Polars DataFrame containing the summary data.
+ """
import polars as pl # scope for faster 'import ultralytics'
return pl.DataFrame(self.summary(normalize=normalize, decimals=decimals))
def to_csv(self, normalize=False, decimals=5):
+ """Export results or metrics to CSV string format.
+
+ Args:
+ normalize (bool, optional): Normalize numeric values.
+ decimals (int, optional): Decimal precision.
+
+ Returns:
+ (str): CSV content as string.
+ """
import polars as pl
df = self.to_df(normalize=normalize, decimals=decimals)
@@ -178,12 +215,49 @@ return df_str.write_csv()
def to_json(self, normalize=False, decimals=5):
+ """Export results to JSON format.
+
+ Args:
+ normalize (bool, optional): Normalize numeric values.
+ decimals (int, optional): Decimal precision.
+
+ Returns:
+ (str): JSON-formatted string of the results.
+ """
return self.to_df(normalize=normalize, decimals=decimals).write_json()
class SimpleClass:
+ """A simple base class for creating objects with string representations of their attributes.
+
+ This class provides a foundation for creating objects that can be easily printed or represented as strings, showing
+ all their non-callable attributes. It's useful for debugging and introspection of object states.
+
+ Methods:
+ __str__: Return a human-readable string representation of the object.
+ __repr__: Return a machine-readable string representation of the object.
+ __getattr__: Provide a custom attribute access error message with helpful information.
+
+ Examples:
+ >>> class MyClass(SimpleClass):
+ ... def __init__(self):
+ ... self.x = 10
+ ... self.y = "hello"
+ >>> obj = MyClass()
+ >>> print(obj)
+ __main__.MyClass object with attributes:
+
+ x: 10
+ y: 'hello'
+
+ Notes:
+ - This class is designed to be subclassed. It provides a convenient way to inspect object attributes.
+ - The string representation includes the module and class name of the object.
+ - Callable attributes and attributes starting with an underscore are excluded from the string representation.
+ """
def __str__(self):
+ """Return a human-readable string representation of the object."""
attr = []
for a in dir(self):
v = getattr(self, a)
@@ -197,22 +271,59 @@ return f"{self.__module__}.{self.__class__.__name__} object with attributes:\n\n" + "\n".join(attr)
def __repr__(self):
+ """Return a machine-readable string representation of the object."""
return self.__str__()
def __getattr__(self, attr):
+ """Provide a custom attribute access error message with helpful information."""
name = self.__class__.__name__
raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")
class IterableSimpleNamespace(SimpleNamespace):
+ """An iterable SimpleNamespace class that provides enhanced functionality for attribute access and iteration.
+
+ This class extends the SimpleNamespace class with additional methods for iteration, string representation, and
+ attribute access. It is designed to be used as a convenient container for storing and accessing configuration
+ parameters.
+
+ Methods:
+ __iter__: Return an iterator of key-value pairs from the namespace's attributes.
+ __str__: Return a human-readable string representation of the object.
+ __getattr__: Provide a custom attribute access error message with helpful information.
+ get: Retrieve the value of a specified key, or a default value if the key doesn't exist.
+
+ Examples:
+ >>> cfg = IterableSimpleNamespace(a=1, b=2, c=3)
+ >>> for k, v in cfg:
+ ... print(f"{k}: {v}")
+ a: 1
+ b: 2
+ c: 3
+ >>> print(cfg)
+ a=1
+ b=2
+ c=3
+ >>> cfg.get("b")
+ 2
+ >>> cfg.get("d", "default")
+ 'default'
+
+ Notes:
+ This class is particularly useful for storing configuration parameters in a more accessible
+ and iterable format compared to a standard dictionary.
+ """
def __iter__(self):
+ """Return an iterator of key-value pairs from the namespace's attributes."""
return iter(vars(self).items())
def __str__(self):
+ """Return a human-readable string representation of the object."""
return "\n".join(f"{k}={v}" for k, v in vars(self).items())
def __getattr__(self, attr):
+ """Provide a custom attribute access error message with helpful information."""
name = self.__class__.__name__
raise AttributeError(
f"""
@@ -224,16 +335,40 @@ )
def get(self, key, default=None):
+ """Return the value of the specified key if it exists; otherwise, return the default value."""
return getattr(self, key, default)
def plt_settings(rcparams=None, backend="Agg"):
+ """Decorator to temporarily set rc parameters and the backend for a plotting function.
+
+ Args:
+ rcparams (dict, optional): Dictionary of rc parameters to set.
+ backend (str, optional): Name of the backend to use.
+
+ Returns:
+ (Callable): Decorated function with temporarily set rc parameters and backend.
+
+ Examples:
+ >>> @plt_settings({"font.size": 12})
+ ... def plot_function():
+ ... plt.figure()
+ ... plt.plot([1, 2, 3])
+ ... plt.show()
+
+ >>> with plt_settings({"font.size": 12}):
+ ... plt.figure()
+ ... plt.plot([1, 2, 3])
+ ... plt.show()
+ """
if rcparams is None:
rcparams = {"font.size": 11}
def decorator(func):
+ """Decorator to apply temporary rc parameters and backend to a function."""
def wrapper(*args, **kwargs):
+ """Set rc parameters and backend, call the original function, and restore the settings."""
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
# Prepend Arial Unicode for non-Latin text (CJK, Arabic, etc.); matplotlib falls back if missing
@@ -275,10 +410,35 @@
def set_logging(name="LOGGING_NAME", verbose=True):
+ """Set up logging with UTF-8 encoding and configurable verbosity.
+
+ This function configures logging for the Ultralytics library, setting the appropriate logging level and formatter
+ based on the verbosity flag and the current process rank. It handles special cases for Windows environments where
+ UTF-8 encoding might not be the default.
+
+ Args:
+ name (str): Name of the logger.
+ verbose (bool): Flag to set logging level to INFO if True, ERROR otherwise.
+
+ Returns:
+ (logging.Logger): Configured logger object.
+
+ Examples:
+ >>> set_logging(name="ultralytics", verbose=True)
+ >>> logger = logging.getLogger("ultralytics")
+ >>> logger.info("This is an info message")
+
+ Notes:
+ - On Windows, this function attempts to reconfigure stdout to use UTF-8 encoding if possible.
+ - If reconfiguration is not possible, it falls back to a custom formatter that handles non-UTF-8 environments.
+ - The function sets up a StreamHandler with the appropriate formatter and level.
+ - The logger's propagate flag is set to False to prevent duplicate logging in parent loggers.
+ """
level = logging.INFO if verbose and RANK in {-1, 0} else logging.ERROR # rank in world for Multi-GPU trainings
class PrefixFormatter(logging.Formatter):
def format(self, record):
+ """Format log records with prefixes based on level."""
# Apply prefixes based on log level
if record.levelno == logging.WARNING:
prefix = "WARNING" if WINDOWS else "WARNING ⚠️"
@@ -324,19 +484,37 @@
def emojis(string=""):
+ """Return platform-dependent emoji-safe version of string."""
return string.encode().decode("ascii", "ignore") if WINDOWS else string
class ThreadingLocked:
+ """A decorator class for ensuring thread-safe execution of a function or method.
+
+ This class can be used as a decorator to make sure that if the decorated function is called from multiple threads,
+ only one thread at a time will be able to execute the function.
+
+ Attributes:
+ lock (threading.Lock): A lock object used to manage access to the decorated function.
+
+ Examples:
+ >>> from ultralytics.utils import ThreadingLocked
+ >>> @ThreadingLocked()
+ ... def my_function():
+ ... # Your code here
+ """
def __init__(self):
+ """Initialize the decorator class with a threading lock."""
self.lock = threading.Lock()
def __call__(self, f):
+ """Run thread-safe execution of function or method."""
from functools import wraps
@wraps(f)
def decorated(*args, **kwargs):
+ """Apply thread-safety to the decorated function or method."""
with self.lock:
return f(*args, **kwargs)
@@ -344,16 +522,43 @@
class YAML:
+ """YAML utility class for efficient file operations with automatic C-implementation detection.
+
+ This class provides optimized YAML loading and saving operations using PyYAML's fastest available implementation
+ (C-based when possible). It implements a singleton pattern with lazy initialization, allowing direct class method
+ usage without explicit instantiation. The class handles file path creation, validation, and character encoding
+ issues automatically.
+
+ The implementation prioritizes performance through:
+ - Automatic C-based loader/dumper selection when available
+ - Singleton pattern to reuse the same instance
+ - Lazy initialization to defer import costs until needed
+ - Fallback mechanisms for handling problematic YAML content
+
+ Attributes:
+ _instance: Internal singleton instance storage.
+ yaml: Reference to the PyYAML module.
+ SafeLoader: Best available YAML loader (CSafeLoader if available).
+ SafeDumper: Best available YAML dumper (CSafeDumper if available).
+
+ Examples:
+ >>> data = YAML.load("config.yaml")
+ >>> data["new_value"] = 123
+ >>> YAML.save("updated_config.yaml", data)
+ >>> YAML.print(data)
+ """
_instance = None
@classmethod
def _get_instance(cls):
+ """Initialize singleton instance on first use."""
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
+ """Initialize with optimal YAML implementation (C-based when available)."""
import yaml
self.yaml = yaml
@@ -367,6 +572,13 @@
@classmethod
def save(cls, file="data.yaml", data=None, header=""):
+ """Save Python object as YAML file.
+
+ Args:
+ file (str | Path): Path to save YAML file.
+ data (dict | None): Dict or compatible object to save.
+ header (str): Optional string to add at file beginning.
+ """
instance = cls._get_instance()
if data is None:
data = {}
@@ -389,6 +601,15 @@
@classmethod
def load(cls, file="data.yaml", append_filename=False):
+ """Load YAML file to Python object with robust error handling.
+
+ Args:
+ file (str | Path): Path to YAML file.
+ append_filename (bool): Whether to add filename to returned dict.
+
+ Returns:
+ (dict): Loaded YAML content.
+ """
instance = cls._get_instance()
assert str(file).endswith((".yaml", ".yml")), f"Not a YAML file: {file}"
@@ -419,6 +640,11 @@
@classmethod
def print(cls, yaml_file):
+ """Pretty print YAML file or object to console.
+
+ Args:
+ yaml_file (str | Path | dict): Path to YAML file or dict to print.
+ """
instance = cls._get_instance()
# Load file if path provided
@@ -437,10 +663,20 @@
def read_device_model() -> str:
+ """Read the device model information from the system.
+
+ Returns:
+ (str): Platform release string in lowercase, used to identify device models like Jetson or Raspberry Pi.
+ """
return platform.release().lower()
def is_ubuntu() -> bool:
+ """Check if the OS is Ubuntu.
+
+ Returns:
+ (bool): True if OS is Ubuntu, False otherwise.
+ """
try:
with open("/etc/os-release") as f:
return "ID=ubuntu" in f.read()
@@ -449,6 +685,16 @@
def is_debian(codenames: list[str] | None | str = None) -> list[bool] | bool:
+ """Check if the OS is Debian.
+
+ Args:
+ codenames (list[str] | None | str): Specific Debian codename to check for (e.g., 'buster', 'bullseye'). If None,
+ only checks for Debian.
+
+ Returns:
+ (list[bool] | bool): List of booleans indicating if OS matches each Debian codename, or a single boolean if no
+ codenames provided.
+ """
try:
with open("/etc/os-release") as f:
content = f.read()
@@ -465,22 +711,51 @@
def is_colab():
+ """Check if the current script is running inside a Google Colab notebook.
+
+ Returns:
+ (bool): True if running inside a Colab notebook, False otherwise.
+ """
return "COLAB_RELEASE_TAG" in os.environ or "COLAB_BACKEND_VERSION" in os.environ
def is_kaggle():
+ """Check if the current script is running inside a Kaggle kernel.
+
+ Returns:
+ (bool): True if running inside a Kaggle kernel, False otherwise.
+ """
return os.environ.get("PWD") == "/kaggle/working" and os.environ.get("KAGGLE_URL_BASE") == "https://www.kaggle.com"
def is_jupyter():
+ """Check if the current script is running inside a Jupyter Notebook.
+
+ Returns:
+ (bool): True if running inside a Jupyter Notebook, False otherwise.
+
+ Notes:
+ - Only works on Colab and Kaggle, other environments like Jupyterlab and Paperspace are not reliably detectable.
+ - "get_ipython" in globals() method suffers false positives when IPython package installed manually.
+ """
return IS_COLAB or IS_KAGGLE
def is_runpod():
+ """Check if the current script is running inside a RunPod container.
+
+ Returns:
+ (bool): True if running in RunPod, False otherwise.
+ """
return "RUNPOD_POD_ID" in os.environ
def is_docker() -> bool:
+ """Determine if the script is running inside a Docker container.
+
+ Returns:
+ (bool): True if the script is running inside a Docker container, False otherwise.
+ """
try:
return os.path.exists("/.dockerenv")
except Exception:
@@ -488,11 +763,24 @@
def is_raspberrypi() -> bool:
+ """Determine if the Python environment is running on a Raspberry Pi.
+
+ Returns:
+ (bool): True if running on a Raspberry Pi, False otherwise.
+ """
return "rpi" in DEVICE_MODEL
@lru_cache(maxsize=3)
def is_jetson(jetpack=None) -> bool:
+ """Determine if the Python environment is running on an NVIDIA Jetson device.
+
+ Args:
+ jetpack (int | None): If specified, check for specific JetPack version (4, 5, 6).
+
+ Returns:
+ (bool): True if running on an NVIDIA Jetson device, False otherwise.
+ """
jetson = "tegra" in DEVICE_MODEL
if jetson and jetpack:
try:
@@ -505,6 +793,11 @@
def is_dgx() -> bool:
+ """Check if the current script is running inside a DGX (NVIDIA Data Center GPU), DGX-Ready or DGX Spark system.
+
+ Returns:
+ (bool): True if running in a DGX or DGX-Ready or DGX Spark system, False otherwise.
+ """
try:
with open("/etc/dgx-release") as f:
return "DGX" in f.read()
@@ -513,6 +806,11 @@
def is_online() -> bool:
+ """Fast online check using DNS (v4/v6) resolution (Cloudflare + Google).
+
+ Returns:
+ (bool): True if connection is successful, False otherwise.
+ """
if str(os.getenv("YOLO_OFFLINE", "")).lower() == "true":
return False
@@ -526,6 +824,14 @@
def is_pip_package(filepath: str = __name__) -> bool:
+ """Determine if the file at the given filepath is part of a pip package.
+
+ Args:
+ filepath (str): The filepath to check.
+
+ Returns:
+ (bool): True if the file is part of a pip package, False otherwise.
+ """
import importlib.util
# Get the spec for the module
@@ -536,23 +842,54 @@
def is_dir_writeable(dir_path: str | Path) -> bool:
+ """Check if a directory is writable.
+
+ Args:
+ dir_path (str | Path): The path to the directory.
+
+ Returns:
+ (bool): True if the directory is writable, False otherwise.
+ """
return os.access(str(dir_path), os.W_OK)
def is_pytest_running():
+ """Determine whether pytest is currently running or not.
+
+ Returns:
+ (bool): True if pytest is running, False otherwise.
+ """
return ("PYTEST_CURRENT_TEST" in os.environ) or ("pytest" in sys.modules) or ("pytest" in Path(ARGV[0]).stem)
def is_github_action_running() -> bool:
+ """Determine if the current environment is a GitHub Actions runner.
+
+ Returns:
+ (bool): True if the current environment is a GitHub Actions runner, False otherwise.
+ """
return "GITHUB_ACTIONS" in os.environ and "GITHUB_WORKFLOW" in os.environ and "RUNNER_OS" in os.environ
def get_default_args(func):
+ """Return a dictionary of default arguments for a function.
+
+ Args:
+ func (callable): The function to inspect.
+
+ Returns:
+ (dict): A dictionary where each key is a parameter name, and each value is the default value of that parameter.
+ """
signature = inspect.signature(func)
return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}
def get_ubuntu_version():
+ """Retrieve the Ubuntu version if the OS is Ubuntu.
+
+ Returns:
+ (str): Ubuntu version or None if not an Ubuntu OS.
+ """
if is_ubuntu():
try:
with open("/etc/os-release") as f:
@@ -562,6 +899,14 @@
def get_user_config_dir(sub_dir="Ultralytics"):
+ """Return a writable config dir, preferring YOLO_CONFIG_DIR and being OS-aware.
+
+ Args:
+ sub_dir (str): The name of the subdirectory to create.
+
+ Returns:
+ (Path): The path to the user config directory.
+ """
if env_dir := os.getenv("YOLO_CONFIG_DIR"):
p = Path(env_dir).expanduser() / sub_dir
elif LINUX:
@@ -614,6 +959,35 @@
def colorstr(*input):
+ r"""Color a string based on the provided color and style arguments using ANSI escape codes.
+
+ This function can be called in two ways:
+ - colorstr('color', 'style', 'your string')
+ - colorstr('your string')
+
+ In the second form, 'blue' and 'bold' will be applied by default.
+
+ Args:
+ *input (str | Path): A sequence of strings where the first n-1 strings are color and style arguments, and the
+ last string is the one to be colored.
+
+ Returns:
+ (str): The input string wrapped with ANSI escape codes for the specified color and style.
+
+ Examples:
+ >>> colorstr("blue", "bold", "hello world")
+ "\033[34m\033[1mhello world\033[0m"
+
+ Notes:
+ Supported Colors and Styles:
+ - Basic Colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
+ - Bright Colors: 'bright_black', 'bright_red', 'bright_green', 'bright_yellow',
+ 'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white'
+ - Misc: 'end', 'bold', 'underline'
+
+ References:
+ https://en.wikipedia.org/wiki/ANSI_escape_code
+ """
*args, string = input if len(input) > 1 else ("blue", "bold", input[0]) # color arguments, string
colors = {
"black": "\033[30m", # basic colors
@@ -640,35 +1014,91 @@
def remove_colorstr(input_string):
+ """Remove ANSI escape codes from a string, effectively un-coloring it.
+
+ Args:
+ input_string (str): The string to remove color and style from.
+
+ Returns:
+ (str): A new string with all ANSI escape codes removed.
+
+ Examples:
+ >>> remove_colorstr(colorstr("blue", "bold", "hello world"))
+ "hello world"
+ """
ansi_escape = re.compile(r"\x1B\[[0-9;]*[A-Za-z]")
return ansi_escape.sub("", input_string)
class TryExcept(contextlib.ContextDecorator):
+ """Ultralytics TryExcept class for handling exceptions gracefully.
+
+ This class can be used as a decorator or context manager to catch exceptions and optionally print warning messages.
+ It allows code to continue execution even when exceptions occur, which is useful for non-critical operations.
+
+ Attributes:
+ msg (str): Optional message to display when an exception occurs.
+ verbose (bool): Whether to print the exception message.
+
+ Examples:
+ As a decorator:
+ >>> @TryExcept(msg="Error occurred in func", verbose=True)
+ ... def func():
+ ... # Function logic here
+ ... pass
+
+ As a context manager:
+ >>> with TryExcept(msg="Error occurred in block", verbose=True):
+ ... # Code block here
+ ... pass
+ """
def __init__(self, msg="", verbose=True):
+ """Initialize TryExcept class with optional message and verbosity settings."""
self.msg = msg
self.verbose = verbose
def __enter__(self):
+ """Execute when entering TryExcept context, initialize instance."""
pass
def __exit__(self, exc_type, value, traceback):
+ """Define behavior when exiting a 'with' block, print error message if necessary."""
if self.verbose and value:
LOGGER.warning(f"{self.msg}{': ' if self.msg else ''}{value}")
return True
class Retry(contextlib.ContextDecorator):
+ """Retry class for function execution with exponential backoff.
+
+ This decorator can be used to retry a function on exceptions, up to a specified number of times with an
+ exponentially increasing delay between retries. It's useful for handling transient failures in network operations or
+ other unreliable processes.
+
+ Attributes:
+ times (int): Maximum number of retry attempts.
+ delay (int): Initial delay between retries in seconds.
+
+ Examples:
+ Example usage as a decorator:
+ >>> @Retry(times=3, delay=2)
+ ... def test_func():
+ ... # Replace with function logic that may raise exceptions
+ ... return True
+ """
def __init__(self, times=3, delay=2):
+ """Initialize Retry class with specified number of retries and delay."""
self.times = times
self.delay = delay
self._attempts = 0
def __call__(self, func):
+ """Decorator implementation for Retry with exponential backoff."""
def wrapped_func(*args, **kwargs):
+ """Apply retries to the decorated function or method."""
self._attempts = 0
while self._attempts < self.times:
try:
@@ -684,8 +1114,29 @@
def threaded(func):
+ """Multi-thread a target function by default and return the thread or function result.
+
+ This decorator provides flexible execution of the target function, either in a separate thread or synchronously. By
+ default, the function runs in a thread, but this can be controlled via the 'threaded=False' keyword argument which
+ is removed from kwargs before calling the function.
+
+ Args:
+ func (callable): The function to be potentially executed in a separate thread.
+
+ Returns:
+ (callable): A wrapper function that either returns a daemon thread or the direct function result.
+
+ Examples:
+ >>> @threaded
+ ... def process_data(data):
+ ... return data
+ >>>
+ >>> thread = process_data(my_data) # Runs in background thread
+ >>> result = process_data(my_data, threaded=False) # Runs synchronously, returns function result
+ """
def wrapper(*args, **kwargs):
+ """Multi-thread a given function based on 'threaded' kwarg and return the thread or function result."""
if kwargs.pop("threaded", True): # run in thread
thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
thread.start()
@@ -697,6 +1148,21 @@
def set_sentry():
+ """Initialize the Sentry SDK for error tracking and reporting.
+
+ Only used if sentry_sdk package is installed and sync=True in settings. Run 'yolo settings' to see and update
+ settings.
+
+ Conditions required to send errors (ALL conditions must be met or no errors will be reported):
+ - sentry_sdk package is installed
+ - sync=True in YOLO settings
+ - pytest is not running
+ - running in a pip package installation
+ - running in a non-git directory
+ - running with rank -1 or 0
+ - online environment
+ - CLI used to run package (checked with 'yolo' as the name of the main CLI command)
+ """
if (
not SETTINGS["sync"]
or RANK not in {-1, 0}
@@ -714,6 +1180,15 @@ return
def before_send(event, hint):
+ """Modify the event before sending it to Sentry based on specific exception types and messages.
+
+ Args:
+ event (dict): The event dictionary containing information about the error.
+ hint (dict): A dictionary containing additional information about the error.
+
+ Returns:
+ (dict | None): The modified event or None if the event should not be sent to Sentry.
+ """
if "exc_info" in hint:
exc_type, exc_value, _ = hint["exc_info"]
if exc_type in {KeyboardInterrupt, FileNotFoundError} or "out of memory" in str(exc_value):
@@ -741,14 +1216,42 @@
class JSONDict(dict):
+ """A dictionary-like class that provides JSON persistence for its contents.
+
+ This class extends the built-in dictionary to automatically save its contents to a JSON file whenever they are
+ modified. It ensures thread-safe operations using a lock and handles JSON serialization of Path objects.
+
+ Attributes:
+ file_path (Path): The path to the JSON file used for persistence.
+ lock (threading.Lock): A lock object to ensure thread-safe operations.
+
+ Methods:
+ _load: Load the data from the JSON file into the dictionary.
+ _save: Save the current state of the dictionary to the JSON file.
+ __setitem__: Store a key-value pair and persist it to disk.
+ __delitem__: Remove an item and update the persistent storage.
+ update: Update the dictionary and persist changes.
+ clear: Clear all entries and update the persistent storage.
+
+ Examples:
+ >>> json_dict = JSONDict("data.json")
+ >>> json_dict["key"] = "value"
+ >>> print(json_dict["key"])
+ value
+ >>> del json_dict["key"]
+ >>> json_dict.update({"new_key": "new_value"})
+ >>> json_dict.clear()
+ """
def __init__(self, file_path: str | Path = "data.json"):
+ """Initialize a JSONDict object with a specified file path for JSON persistence."""
super().__init__()
self.file_path = Path(file_path)
self.lock = Lock()
self._load()
def _load(self):
+ """Load the data from the JSON file into the dictionary."""
try:
if self.file_path.exists():
with open(self.file_path) as f:
@@ -760,6 +1263,7 @@ LOGGER.error(f"Error reading from {self.file_path}: {e}")
def _save(self):
+ """Save the current state of the dictionary to the JSON file."""
try:
self.file_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.file_path, "w", encoding="utf-8") as f:
@@ -769,38 +1273,69 @@
@staticmethod
def _json_default(obj):
+ """Handle JSON serialization of Path objects."""
if isinstance(obj, Path):
return str(obj)
raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
def __setitem__(self, key, value):
+ """Store a key-value pair and persist to disk."""
with self.lock:
super().__setitem__(key, value)
self._save()
def __delitem__(self, key):
+ """Remove an item and update the persistent storage."""
with self.lock:
super().__delitem__(key)
self._save()
def __str__(self):
+ """Return a pretty-printed JSON string representation of the dictionary."""
contents = json.dumps(dict(self), indent=2, ensure_ascii=False, default=self._json_default)
return f'JSONDict("{self.file_path}"):\n{contents}'
def update(self, *args, **kwargs):
+ """Update the dictionary and persist changes."""
with self.lock:
super().update(*args, **kwargs)
self._save()
def clear(self):
+ """Clear all entries and update the persistent storage."""
with self.lock:
super().clear()
self._save()
class SettingsManager(JSONDict):
+ """SettingsManager class for managing and persisting Ultralytics settings.
+
+ This class extends JSONDict to provide JSON persistence for settings, ensuring thread-safe operations and default
+ values. It validates settings on initialization and provides methods to update or reset settings. The settings
+ include directories for datasets, weights, and runs, as well as various integration flags.
+
+ Attributes:
+ file (Path): The path to the JSON file used for persistence.
+ version (str): The version of the settings schema.
+ defaults (dict): A dictionary containing default settings.
+ help_msg (str): A help message for users on how to view and update settings.
+
+ Methods:
+ _validate_settings: Validate the current settings and reset if necessary.
+ update: Update settings, validating keys and types.
+ reset: Reset the settings to default and save them.
+
+ Examples:
+ Initialize and update settings:
+ >>> settings = SettingsManager()
+ >>> settings.update(runs_dir="/new/runs/dir")
+ >>> print(settings["runs_dir"])
+ /new/runs/dir
+ """
def __init__(self, file=SETTINGS_FILE, version="0.0.6"):
+ """Initialize the SettingsManager with default settings and load user settings."""
import hashlib
import uuid
@@ -849,6 +1384,7 @@ self._validate_settings()
def _validate_settings(self):
+ """Validate the current settings and reset if necessary."""
correct_keys = frozenset(self.keys()) == frozenset(self.defaults.keys())
correct_types = all(isinstance(self.get(k), type(v)) for k, v in self.defaults.items())
correct_version = self.get("settings_version", "") == self.version
@@ -868,9 +1404,11 @@ )
def __setitem__(self, key, value):
+ """Update one key: value pair."""
self.update({key: value})
def update(self, *args, **kwargs):
+ """Update settings, validating keys and types."""
for arg in args:
if isinstance(arg, dict):
kwargs.update(arg)
@@ -885,11 +1423,13 @@ super().update(*args, **kwargs)
def reset(self):
+ """Reset the settings to default and save them."""
self.clear()
self.update(self.defaults)
def deprecation_warn(arg, new_arg=None):
+ """Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument."""
msg = f"'{arg}' is deprecated and will be removed in the future."
if new_arg is not None:
msg += f" Use '{new_arg}' instead."
@@ -897,15 +1437,18 @@
def clean_url(url):
+ """Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt."""
url = Path(url).as_posix().replace(":/", "://") # Pathlib turns :// -> :/, as_posix() for Windows
return unquote(url).split("?", 1)[0] # '%2F' to '/', split https://url.com/file.txt?auth
def url2file(url):
+ """Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt."""
return Path(clean_url(url)).name
def vscode_msg(ext="ultralytics.ultralytics-snippets") -> str:
+ """Display a message to install Ultralytics-Snippets for VS Code if not already installed."""
path = (USER_CONFIG_DIR.parents[2] if WINDOWS else USER_CONFIG_DIR.parents[1]) / ".vscode/extensions"
obs_file = path / ".obsolete" # file tracks uninstalled extensions, while source directory remains
installed = any(path.glob(f"{ext}*")) and ext not in (obs_file.read_text("utf-8") if obs_file.exists() else "")
@@ -940,4 +1483,4 @@ torch.save = torch_save
if WINDOWS:
# Apply cv2 patches for non-ASCII and non-UTF characters in image paths
- cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow+ cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/__init__.py |
Write docstrings including parameters and return values | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import math
from collections import Counter, defaultdict
from functools import lru_cache
from typing import Any
import cv2
import numpy as np
from ultralytics import YOLO
from ultralytics.solutions.config import SolutionConfig
from ultralytics.utils import ASSETS_URL, LOGGER, ops
from ultralytics.utils.checks import check_imshow, check_requirements
from ultralytics.utils.plotting import Annotator
class BaseSolution:
def __init__(self, is_cli: bool = False, **kwargs: Any) -> None:
self.CFG = vars(SolutionConfig().update(**kwargs))
self.LOGGER = LOGGER # Store logger object to be used in multiple solution classes
check_requirements("shapely>=2.0.0")
from shapely.geometry import LineString, Point, Polygon
from shapely.prepared import prep
self.LineString = LineString
self.Polygon = Polygon
self.Point = Point
self.prep = prep
self.annotator = None # Initialize annotator
self.tracks = None
self.track_data = None
self.boxes = []
self.clss = []
self.track_ids = []
self.track_line = None
self.masks = None
self.r_s = None
self.frame_no = -1 # Only for logging
self.LOGGER.info(f"Ultralytics Solutions: ✅ {self.CFG}")
self.region = self.CFG["region"] # Store region data for other classes usage
self.line_width = self.CFG["line_width"]
# Load Model and store additional information (classes, show_conf, show_label)
if self.CFG["model"] is None:
self.CFG["model"] = "yolo26n.pt"
self.model = YOLO(self.CFG["model"])
self.names = self.model.names
self.classes = self.CFG["classes"]
self.show_conf = self.CFG["show_conf"]
self.show_labels = self.CFG["show_labels"]
self.device = self.CFG["device"]
self.track_add_args = { # Tracker additional arguments for advance configuration
k: self.CFG[k] for k in {"iou", "conf", "device", "max_det", "half", "tracker"}
} # verbose must be passed to track method; setting it False in YOLO still logs the track information.
if is_cli and self.CFG["source"] is None:
d_s = "solutions_ci_demo.mp4" if "-pose" not in self.CFG["model"] else "solution_ci_pose_demo.mp4"
self.LOGGER.warning(f"source not provided. using default source {ASSETS_URL}/{d_s}")
from ultralytics.utils.downloads import safe_download
safe_download(f"{ASSETS_URL}/{d_s}") # download source from ultralytics assets
self.CFG["source"] = d_s # set default source
# Initialize environment and region setup
self.env_check = check_imshow(warn=True)
self.track_history = defaultdict(list)
self.profilers = (
ops.Profile(device=self.device), # track
ops.Profile(device=self.device), # solution
)
def adjust_box_label(self, cls: int, conf: float, track_id: int | None = None) -> str | None:
name = ("" if track_id is None else f"{track_id} ") + self.names[cls]
return (f"{name} {conf:.2f}" if self.show_conf else name) if self.show_labels else None
def extract_tracks(self, im0: np.ndarray) -> None:
with self.profilers[0]:
self.tracks = self.model.track(
source=im0, persist=True, classes=self.classes, verbose=False, **self.track_add_args
)[0]
is_obb = self.tracks.obb is not None
self.track_data = self.tracks.obb if is_obb else self.tracks.boxes # Extract tracks for OBB or object detection
if self.track_data and self.track_data.is_track:
self.boxes = (self.track_data.xyxyxyxy if is_obb else self.track_data.xyxy).cpu()
self.clss = self.track_data.cls.cpu().tolist()
self.track_ids = self.track_data.id.int().cpu().tolist()
self.confs = self.track_data.conf.cpu().tolist()
else:
self.LOGGER.warning("No tracks found.")
self.boxes, self.clss, self.track_ids, self.confs = [], [], [], []
def store_tracking_history(self, track_id: int, box) -> None:
# Store tracking history
self.track_line = self.track_history[track_id]
self.track_line.append(tuple(box.mean(dim=0)) if box.numel() > 4 else (box[:4:2].mean(), box[1:4:2].mean()))
if len(self.track_line) > 30:
self.track_line.pop(0)
def initialize_region(self) -> None:
if self.region is None:
self.region = [(10, 200), (540, 200), (540, 180), (10, 180)]
self.r_s = (
self.Polygon(self.region) if len(self.region) >= 3 else self.LineString(self.region)
) # region or line
def display_output(self, plot_im: np.ndarray) -> None:
if self.CFG.get("show") and self.env_check:
cv2.imshow("Ultralytics Solutions", plot_im)
if cv2.waitKey(1) & 0xFF == ord("q"):
cv2.destroyAllWindows() # Closes current frame window
return
def process(self, *args: Any, **kwargs: Any):
def __call__(self, *args: Any, **kwargs: Any):
with self.profilers[1]:
result = self.process(*args, **kwargs) # Call the subclass-specific process method
track_or_predict = "predict" if type(self).__name__ == "ObjectCropper" else "track"
track_or_predict_speed = self.profilers[0].dt * 1e3
solution_speed = (self.profilers[1].dt - self.profilers[0].dt) * 1e3 # solution time = process - track
result.speed = {track_or_predict: track_or_predict_speed, "solution": solution_speed}
if self.CFG["verbose"]:
self.frame_no += 1
counts = Counter(self.clss) # Only for logging.
LOGGER.info(
f"{self.frame_no}: {result.plot_im.shape[0]}x{result.plot_im.shape[1]} {solution_speed:.1f}ms,"
f" {', '.join([f'{v} {self.names[k]}' for k, v in counts.items()])}\n"
f"Speed: {track_or_predict_speed:.1f}ms {track_or_predict}, "
f"{solution_speed:.1f}ms solution per image at shape "
f"(1, {getattr(self.model, 'channels', 3)}, {result.plot_im.shape[0]}, {result.plot_im.shape[1]})\n"
)
return result
class SolutionAnnotator(Annotator):
def __init__(
self,
im: np.ndarray,
line_width: int | None = None,
font_size: int | None = None,
font: str = "Arial.ttf",
pil: bool = False,
example: str = "abc",
):
super().__init__(im, line_width, font_size, font, pil, example)
def draw_region(
self,
reg_pts: list[tuple[int, int]] | None = None,
color: tuple[int, int, int] = (0, 255, 0),
thickness: int = 5,
):
cv2.polylines(self.im, [np.array(reg_pts, dtype=np.int32)], isClosed=True, color=color, thickness=thickness)
# Draw small circles at the corner points
for point in reg_pts:
cv2.circle(self.im, (point[0], point[1]), thickness * 2, color, -1) # -1 fills the circle
def queue_counts_display(
self,
label: str,
points: list[tuple[int, int]] | None = None,
region_color: tuple[int, int, int] = (255, 255, 255),
txt_color: tuple[int, int, int] = (0, 0, 0),
):
x_values = [point[0] for point in points]
y_values = [point[1] for point in points]
center_x = sum(x_values) // len(points)
center_y = sum(y_values) // len(points)
text_size = cv2.getTextSize(label, 0, fontScale=self.sf, thickness=self.tf)[0]
text_width = text_size[0]
text_height = text_size[1]
rect_width = text_width + 20
rect_height = text_height + 20
rect_top_left = (center_x - rect_width // 2, center_y - rect_height // 2)
rect_bottom_right = (center_x + rect_width // 2, center_y + rect_height // 2)
cv2.rectangle(self.im, rect_top_left, rect_bottom_right, region_color, -1)
text_x = center_x - text_width // 2
text_y = center_y + text_height // 2
# Draw text
cv2.putText(
self.im,
label,
(text_x, text_y),
0,
fontScale=self.sf,
color=txt_color,
thickness=self.tf,
lineType=cv2.LINE_AA,
)
def display_analytics(
self,
im0: np.ndarray,
text: dict[str, Any],
txt_color: tuple[int, int, int],
bg_color: tuple[int, int, int],
margin: int,
):
horizontal_gap = int(im0.shape[1] * 0.02)
vertical_gap = int(im0.shape[0] * 0.01)
text_y_offset = 0
for label, value in text.items():
txt = f"{label}: {value}"
text_size = cv2.getTextSize(txt, 0, self.sf, self.tf)[0]
if text_size[0] < 5 or text_size[1] < 5:
text_size = (5, 5)
text_x = im0.shape[1] - text_size[0] - margin * 2 - horizontal_gap
text_y = text_y_offset + text_size[1] + margin * 2 + vertical_gap
rect_x1 = text_x - margin * 2
rect_y1 = text_y - text_size[1] - margin * 2
rect_x2 = text_x + text_size[0] + margin * 2
rect_y2 = text_y + margin * 2
cv2.rectangle(im0, (rect_x1, rect_y1), (rect_x2, rect_y2), bg_color, -1)
cv2.putText(im0, txt, (text_x, text_y), 0, self.sf, txt_color, self.tf, lineType=cv2.LINE_AA)
text_y_offset = rect_y2
@staticmethod
def _point_xy(point: Any) -> tuple[float, float]:
if hasattr(point, "detach"): # torch.Tensor
point = point.detach()
if hasattr(point, "cpu"): # torch.Tensor
point = point.cpu()
if hasattr(point, "numpy"): # torch.Tensor
point = point.numpy()
if hasattr(point, "tolist"): # numpy / torch
point = point.tolist()
return float(point[0]), float(point[1])
@staticmethod
@lru_cache(maxsize=256)
def _estimate_pose_angle_cached(a: tuple[float, float], b: tuple[float, float], c: tuple[float, float]) -> float:
radians = math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0])
angle = abs(radians * 180.0 / math.pi)
return angle if angle <= 180.0 else (360 - angle)
@staticmethod
def estimate_pose_angle(a: Any, b: Any, c: Any) -> float:
a_xy, b_xy, c_xy = (
SolutionAnnotator._point_xy(a),
SolutionAnnotator._point_xy(b),
SolutionAnnotator._point_xy(c),
)
return SolutionAnnotator._estimate_pose_angle_cached(a_xy, b_xy, c_xy)
def draw_specific_kpts(
self,
keypoints: list[list[float]],
indices: list[int] | None = None,
radius: int = 2,
conf_thresh: float = 0.25,
) -> np.ndarray:
indices = indices or [2, 5, 7]
points = [(int(k[0]), int(k[1])) for i, k in enumerate(keypoints) if i in indices and k[2] >= conf_thresh]
# Draw lines between consecutive points
for start, end in zip(points[:-1], points[1:]):
cv2.line(self.im, start, end, (0, 255, 0), 2, lineType=cv2.LINE_AA)
# Draw circles for keypoints
for pt in points:
cv2.circle(self.im, pt, radius, (0, 0, 255), -1, lineType=cv2.LINE_AA)
return self.im
def plot_workout_information(
self,
display_text: str,
position: tuple[int, int],
color: tuple[int, int, int] = (104, 31, 17),
txt_color: tuple[int, int, int] = (255, 255, 255),
) -> int:
(text_width, text_height), _ = cv2.getTextSize(display_text, 0, fontScale=self.sf, thickness=self.tf)
# Draw background rectangle
cv2.rectangle(
self.im,
(position[0], position[1] - text_height - 5),
(position[0] + text_width + 10, position[1] - text_height - 5 + text_height + 10 + self.tf),
color,
-1,
)
# Draw text
cv2.putText(self.im, display_text, position, 0, self.sf, txt_color, self.tf)
return text_height
def plot_angle_and_count_and_stage(
self,
angle_text: str,
count_text: str,
stage_text: str,
center_kpt: list[int],
color: tuple[int, int, int] = (104, 31, 17),
txt_color: tuple[int, int, int] = (255, 255, 255),
):
# Format text
angle_text, count_text, stage_text = f" {angle_text:.2f}", f"Steps : {count_text}", f" {stage_text}"
# Draw angle, count and stage text
angle_height = self.plot_workout_information(
angle_text, (int(center_kpt[0]), int(center_kpt[1])), color, txt_color
)
count_height = self.plot_workout_information(
count_text, (int(center_kpt[0]), int(center_kpt[1]) + angle_height + 20), color, txt_color
)
self.plot_workout_information(
stage_text, (int(center_kpt[0]), int(center_kpt[1]) + angle_height + count_height + 40), color, txt_color
)
def plot_distance_and_line(
self,
pixels_distance: float,
centroids: list[tuple[int, int]],
line_color: tuple[int, int, int] = (104, 31, 17),
centroid_color: tuple[int, int, int] = (255, 0, 255),
):
# Get the text size
text = f"Pixels Distance: {pixels_distance:.2f}"
(text_width_m, text_height_m), _ = cv2.getTextSize(text, 0, self.sf, self.tf)
# Define corners with 10-pixel margin and draw rectangle
cv2.rectangle(self.im, (15, 25), (15 + text_width_m + 20, 25 + text_height_m + 20), line_color, -1)
# Calculate the position for the text with a 10-pixel margin and draw text
text_position = (25, 25 + text_height_m + 10)
cv2.putText(
self.im,
text,
text_position,
0,
self.sf,
(255, 255, 255),
self.tf,
cv2.LINE_AA,
)
cv2.line(self.im, centroids[0], centroids[1], line_color, 3)
cv2.circle(self.im, centroids[0], 6, centroid_color, -1)
cv2.circle(self.im, centroids[1], 6, centroid_color, -1)
def display_objects_labels(
self,
im0: np.ndarray,
text: str,
txt_color: tuple[int, int, int],
bg_color: tuple[int, int, int],
x_center: float,
y_center: float,
margin: int,
):
text_size = cv2.getTextSize(text, 0, fontScale=self.sf, thickness=self.tf)[0]
text_x = x_center - text_size[0] // 2
text_y = y_center + text_size[1] // 2
rect_x1 = text_x - margin
rect_y1 = text_y - text_size[1] - margin
rect_x2 = text_x + text_size[0] + margin
rect_y2 = text_y + margin
cv2.rectangle(
im0,
(int(rect_x1), int(rect_y1)),
(int(rect_x2), int(rect_y2)),
tuple(map(int, bg_color)), # Ensure color values are int
-1,
)
cv2.putText(
im0,
text,
(int(text_x), int(text_y)),
0,
self.sf,
tuple(map(int, txt_color)), # Ensure color values are int
self.tf,
lineType=cv2.LINE_AA,
)
def sweep_annotator(
self,
line_x: int = 0,
line_y: int = 0,
label: str | None = None,
color: tuple[int, int, int] = (221, 0, 186),
txt_color: tuple[int, int, int] = (255, 255, 255),
):
# Draw the sweep line
cv2.line(self.im, (line_x, 0), (line_x, line_y), color, self.tf * 2)
# Draw label, if provided
if label:
(text_width, text_height), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, self.sf, self.tf)
cv2.rectangle(
self.im,
(line_x - text_width // 2 - 10, line_y // 2 - text_height // 2 - 10),
(line_x + text_width // 2 + 10, line_y // 2 + text_height // 2 + 10),
color,
-1,
)
cv2.putText(
self.im,
label,
(line_x - text_width // 2, line_y // 2 + text_height // 2),
cv2.FONT_HERSHEY_SIMPLEX,
self.sf,
txt_color,
self.tf,
)
def visioneye(
self,
box: list[float],
center_point: tuple[int, int],
color: tuple[int, int, int] = (235, 219, 11),
pin_color: tuple[int, int, int] = (255, 0, 255),
):
center_bbox = int((box[0] + box[2]) / 2), int((box[1] + box[3]) / 2)
cv2.circle(self.im, center_point, self.tf * 2, pin_color, -1)
cv2.circle(self.im, center_bbox, self.tf * 2, color, -1)
cv2.line(self.im, center_point, center_bbox, color, self.tf)
def adaptive_label(
self,
box: tuple[float, float, float, float],
label: str = "",
color: tuple[int, int, int] = (128, 128, 128),
txt_color: tuple[int, int, int] = (255, 255, 255),
shape: str = "rect",
margin: int = 5,
):
if shape == "circle" and len(label) > 3:
LOGGER.warning(f"Length of label is {len(label)}, only first 3 letters will be used for circle annotation.")
label = label[:3]
x_center, y_center = int((box[0] + box[2]) / 2), int((box[1] + box[3]) / 2) # Bounding-box center
text_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, self.sf - 0.15, self.tf)[0] # Get size of the text
text_x, text_y = x_center - text_size[0] // 2, y_center + text_size[1] // 2 # Calculate top-left corner of text
if shape == "circle":
cv2.circle(
self.im,
(x_center, y_center),
int(((text_size[0] ** 2 + text_size[1] ** 2) ** 0.5) / 2) + margin, # Calculate the radius
color,
-1,
)
else:
cv2.rectangle(
self.im,
(text_x - margin, text_y - text_size[1] - margin), # Calculate coordinates of the rectangle
(text_x + text_size[0] + margin, text_y + margin), # Calculate coordinates of the rectangle
color,
-1,
)
# Draw the text on top of the rectangle
cv2.putText(
self.im,
label,
(text_x, text_y), # Calculate top-left corner of the text
cv2.FONT_HERSHEY_SIMPLEX,
self.sf - 0.15,
self.get_txt_color(color, txt_color),
self.tf,
lineType=cv2.LINE_AA,
)
class SolutionResults:
def __init__(self, **kwargs):
self.plot_im = None
self.in_count = 0
self.out_count = 0
self.classwise_count = {}
self.queue_count = 0
self.workout_count = 0
self.workout_angle = 0.0
self.workout_stage = None
self.pixels_distance = 0.0
self.available_slots = 0
self.filled_slots = 0
self.email_sent = False
self.total_tracks = 0
self.region_counts = {}
self.speed_dict = {} # for speed estimation
self.total_crop_objects = 0
self.speed = {}
# Override with user-defined values
self.__dict__.update(kwargs)
def __str__(self) -> str:
attrs = {
k: v
for k, v in self.__dict__.items()
if k != "plot_im" and v not in [None, {}, 0, 0.0, False] # Exclude `plot_im` explicitly
}
return ", ".join(f"{k}={v}" for k, v in attrs.items()) | --- +++ @@ -18,8 +18,66 @@
class BaseSolution:
+ """A base class for managing Ultralytics Solutions.
+
+ This class provides core functionality for various Ultralytics Solutions, including model loading, object tracking,
+ and region initialization. It serves as the foundation for implementing specific computer vision solutions such as
+ object counting, pose estimation, and analytics.
+
+ Attributes:
+ LineString: Class for creating line string geometries from shapely.
+ Polygon: Class for creating polygon geometries from shapely.
+ Point: Class for creating point geometries from shapely.
+ prep: Prepared geometry function from shapely for optimized spatial operations.
+ CFG (dict[str, Any]): Configuration dictionary loaded from YAML file and updated with kwargs.
+ LOGGER: Logger instance for solution-specific logging.
+ annotator: Annotator instance for drawing on images.
+ tracks: YOLO tracking results from the latest inference.
+ track_data: Extracted tracking data (boxes or OBB) from tracks.
+ boxes (list): Bounding box coordinates from tracking results.
+ clss (list[int]): Class indices from tracking results.
+ track_ids (list[int]): Track IDs from tracking results.
+ confs (list[float]): Confidence scores from tracking results.
+ track_line: Current track line for storing tracking history.
+ masks: Segmentation masks from tracking results.
+ r_s: Region or line geometry object for spatial operations.
+ frame_no (int): Current frame number for logging purposes.
+ region (list[tuple[int, int]]): List of coordinate tuples defining region of interest.
+ line_width (int): Width of lines used in visualizations.
+ model (YOLO): Loaded YOLO model instance.
+ names (dict[int, str]): Dictionary mapping class indices to class names.
+ classes (list[int]): List of class indices to track.
+ show_conf (bool): Flag to show confidence scores in annotations.
+ show_labels (bool): Flag to show class labels in annotations.
+ device (str): Device for model inference.
+ track_add_args (dict[str, Any]): Additional arguments for tracking configuration.
+ env_check (bool): Flag indicating whether environment supports image display.
+ track_history (defaultdict): Dictionary storing tracking history for each object.
+ profilers (tuple): Profiler instances for performance monitoring.
+
+ Methods:
+ adjust_box_label: Generate formatted label for bounding box.
+ extract_tracks: Apply object tracking and extract tracks from input image.
+ store_tracking_history: Store object tracking history for given track ID and bounding box.
+ initialize_region: Initialize counting region and line segment based on configuration.
+ display_output: Display processing results including frames or saved results.
+ process: Process method to be implemented by each Solution subclass.
+
+ Examples:
+ >>> solution = BaseSolution(model="yolo26n.pt", region=[(0, 0), (100, 0), (100, 100), (0, 100)])
+ >>> solution.initialize_region()
+ >>> image = cv2.imread("image.jpg")
+ >>> solution.extract_tracks(image)
+ >>> solution.display_output(image)
+ """
def __init__(self, is_cli: bool = False, **kwargs: Any) -> None:
+ """Initialize the BaseSolution class with configuration settings and YOLO model.
+
+ Args:
+ is_cli (bool): Enable CLI mode if set to True.
+ **kwargs (Any): Additional configuration parameters that override defaults.
+ """
self.CFG = vars(SolutionConfig().update(**kwargs))
self.LOGGER = LOGGER # Store logger object to be used in multiple solution classes
@@ -78,10 +136,34 @@ )
def adjust_box_label(self, cls: int, conf: float, track_id: int | None = None) -> str | None:
+ """Generate a formatted label for a bounding box.
+
+ This method constructs a label string for a bounding box using the class index and confidence score. Optionally
+ includes the track ID if provided. The label format adapts based on the display settings defined in
+ `self.show_conf` and `self.show_labels`.
+
+ Args:
+ cls (int): The class index of the detected object.
+ conf (float): The confidence score of the detection.
+ track_id (int, optional): The unique identifier for the tracked object.
+
+ Returns:
+ (str | None): The formatted label string if `self.show_labels` is True; otherwise, None.
+ """
name = ("" if track_id is None else f"{track_id} ") + self.names[cls]
return (f"{name} {conf:.2f}" if self.show_conf else name) if self.show_labels else None
def extract_tracks(self, im0: np.ndarray) -> None:
+ """Apply object tracking and extract tracks from an input image or frame.
+
+ Args:
+ im0 (np.ndarray): The input image or frame.
+
+ Examples:
+ >>> solution = BaseSolution()
+ >>> frame = cv2.imread("path/to/image.jpg")
+ >>> solution.extract_tracks(frame)
+ """
with self.profilers[0]:
self.tracks = self.model.track(
source=im0, persist=True, classes=self.classes, verbose=False, **self.track_add_args
@@ -99,6 +181,19 @@ self.boxes, self.clss, self.track_ids, self.confs = [], [], [], []
def store_tracking_history(self, track_id: int, box) -> None:
+ """Store the tracking history of an object.
+
+ This method updates the tracking history for a given object by appending the center point of its bounding box to
+ the track line. It maintains a maximum of 30 points in the tracking history.
+
+ Args:
+ track_id (int): The unique identifier for the tracked object.
+ box (list[float]): The bounding box coordinates of the object in the format [x1, y1, x2, y2].
+
+ Examples:
+ >>> solution = BaseSolution()
+ >>> solution.store_tracking_history(1, [100, 200, 300, 400])
+ """
# Store tracking history
self.track_line = self.track_history[track_id]
self.track_line.append(tuple(box.mean(dim=0)) if box.numel() > 4 else (box[:4:2].mean(), box[1:4:2].mean()))
@@ -106,6 +201,7 @@ self.track_line.pop(0)
def initialize_region(self) -> None:
+ """Initialize the counting region and line segment based on configuration settings."""
if self.region is None:
self.region = [(10, 200), (540, 200), (540, 180), (10, 180)]
self.r_s = (
@@ -113,6 +209,25 @@ ) # region or line
def display_output(self, plot_im: np.ndarray) -> None:
+ """Display the results of the processing, which could involve showing frames, printing counts, or saving
+ results.
+
+ This method is responsible for visualizing the output of the object detection and tracking process. It displays
+ the processed frame with annotations, and allows for user interaction to close the display.
+
+ Args:
+ plot_im (np.ndarray): The image or frame that has been processed and annotated.
+
+ Examples:
+ >>> solution = BaseSolution()
+ >>> frame = cv2.imread("path/to/image.jpg")
+ >>> solution.display_output(frame)
+
+ Notes:
+ - This method will only display output if the 'show' configuration is set to True and the environment
+ supports image display.
+ - The display can be closed by pressing the 'q' key.
+ """
if self.CFG.get("show") and self.env_check:
cv2.imshow("Ultralytics Solutions", plot_im)
if cv2.waitKey(1) & 0xFF == ord("q"):
@@ -120,8 +235,10 @@ return
def process(self, *args: Any, **kwargs: Any):
+ """Process method should be implemented by each Solution subclass."""
def __call__(self, *args: Any, **kwargs: Any):
+ """Allow instances to be called like a function with flexible arguments."""
with self.profilers[1]:
result = self.process(*args, **kwargs) # Call the subclass-specific process method
track_or_predict = "predict" if type(self).__name__ == "ObjectCropper" else "track"
@@ -142,6 +259,41 @@
class SolutionAnnotator(Annotator):
+ """A specialized annotator class for visualizing and analyzing computer vision tasks.
+
+ This class extends the base Annotator class, providing additional methods for drawing regions, centroids, tracking
+ trails, and visual annotations for Ultralytics Solutions. It offers comprehensive visualization capabilities for
+ various computer vision applications including object detection, tracking, pose estimation, and analytics.
+
+ Attributes:
+ im (np.ndarray): The image being annotated.
+ line_width (int): Thickness of lines used in annotations.
+ font_size (int): Size of the font used for text annotations.
+ font (str): Path to the font file used for text rendering.
+ pil (bool): Whether to use PIL for text rendering.
+ example (str): Example text used to detect non-ASCII labels for PIL rendering.
+
+ Methods:
+ draw_region: Draw a region using specified points, colors, and thickness.
+ queue_counts_display: Display queue counts in the specified region.
+ display_analytics: Display overall statistics for parking lot management.
+ estimate_pose_angle: Calculate the angle between three points in an object pose.
+ draw_specific_kpts: Draw specific keypoints on the image.
+ plot_workout_information: Draw a labeled text box on the image.
+ plot_angle_and_count_and_stage: Visualize angle, step count, and stage for workout monitoring.
+ plot_distance_and_line: Display the distance between centroids and connect them with a line.
+ display_objects_labels: Annotate bounding boxes with object class labels.
+ sweep_annotator: Visualize a vertical sweep line and optional label.
+ visioneye: Map and connect object centroids to a visual "eye" point.
+ adaptive_label: Draw a circular or rectangle background shape label in center of a bounding box.
+
+ Examples:
+ >>> annotator = SolutionAnnotator(image)
+ >>> annotator.draw_region([(0, 0), (100, 100)], color=(0, 255, 0), thickness=5)
+ >>> annotator.display_analytics(
+ ... image, text={"Available Spots": 5}, txt_color=(0, 0, 0), bg_color=(255, 255, 255), margin=10
+ ... )
+ """
def __init__(
self,
@@ -152,6 +304,16 @@ pil: bool = False,
example: str = "abc",
):
+ """Initialize the SolutionAnnotator class with an image for annotation.
+
+ Args:
+ im (np.ndarray): The image to be annotated.
+ line_width (int, optional): Line thickness for drawing on the image.
+ font_size (int, optional): Font size for text annotations.
+ font (str): Path to the font file.
+ pil (bool): Indicates whether to use PIL for rendering text.
+ example (str): Example text used to detect non-ASCII labels for PIL rendering.
+ """
super().__init__(im, line_width, font_size, font, pil, example)
def draw_region(
@@ -160,6 +322,13 @@ color: tuple[int, int, int] = (0, 255, 0),
thickness: int = 5,
):
+ """Draw a region or line on the image.
+
+ Args:
+ reg_pts (list[tuple[int, int]], optional): Region points (for line 2 points, for region 4+ points).
+ color (tuple[int, int, int]): BGR color value for the region (OpenCV format).
+ thickness (int): Line thickness for drawing the region.
+ """
cv2.polylines(self.im, [np.array(reg_pts, dtype=np.int32)], isClosed=True, color=color, thickness=thickness)
# Draw small circles at the corner points
@@ -173,6 +342,14 @@ region_color: tuple[int, int, int] = (255, 255, 255),
txt_color: tuple[int, int, int] = (0, 0, 0),
):
+ """Display queue counts on an image centered at the points with customizable font size and colors.
+
+ Args:
+ label (str): Queue counts label.
+ points (list[tuple[int, int]], optional): Region points for center point calculation to display text.
+ region_color (tuple[int, int, int]): BGR queue region color (OpenCV format).
+ txt_color (tuple[int, int, int]): BGR text color (OpenCV format).
+ """
x_values = [point[0] for point in points]
y_values = [point[1] for point in points]
center_x = sum(x_values) // len(points)
@@ -211,6 +388,15 @@ bg_color: tuple[int, int, int],
margin: int,
):
+ """Display overall statistics for Solutions (e.g., parking management and object counting).
+
+ Args:
+ im0 (np.ndarray): Inference image.
+ text (dict[str, Any]): Labels dictionary.
+ txt_color (tuple[int, int, int]): Text color (BGR, OpenCV format).
+ bg_color (tuple[int, int, int]): Background color (BGR, OpenCV format).
+ margin (int): Gap between text and rectangle for better display.
+ """
horizontal_gap = int(im0.shape[1] * 0.02)
vertical_gap = int(im0.shape[0] * 0.01)
text_y_offset = 0
@@ -231,6 +417,7 @@
@staticmethod
def _point_xy(point: Any) -> tuple[float, float]:
+ """Convert a keypoint-like object to an (x, y) tuple of floats."""
if hasattr(point, "detach"): # torch.Tensor
point = point.detach()
if hasattr(point, "cpu"): # torch.Tensor
@@ -244,12 +431,23 @@ @staticmethod
@lru_cache(maxsize=256)
def _estimate_pose_angle_cached(a: tuple[float, float], b: tuple[float, float], c: tuple[float, float]) -> float:
+ """Calculate the angle between three points for workout monitoring (cached)."""
radians = math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0])
angle = abs(radians * 180.0 / math.pi)
return angle if angle <= 180.0 else (360 - angle)
@staticmethod
def estimate_pose_angle(a: Any, b: Any, c: Any) -> float:
+ """Calculate the angle between three points for workout monitoring.
+
+ Args:
+ a (Any): The coordinates of the first point (e.g. list/tuple/NumPy array/torch tensor).
+ b (Any): The coordinates of the second point (vertex).
+ c (Any): The coordinates of the third point.
+
+ Returns:
+ (float): The angle in degrees between the three points.
+ """
a_xy, b_xy, c_xy = (
SolutionAnnotator._point_xy(a),
SolutionAnnotator._point_xy(b),
@@ -264,6 +462,21 @@ radius: int = 2,
conf_thresh: float = 0.25,
) -> np.ndarray:
+ """Draw specific keypoints for gym steps counting.
+
+ Args:
+ keypoints (list[list[float]]): Keypoints data to be plotted, each in format [x, y, confidence].
+ indices (list[int], optional): Keypoint indices to be plotted.
+ radius (int): Keypoint radius.
+ conf_thresh (float): Confidence threshold for keypoints.
+
+ Returns:
+ (np.ndarray): Image with drawn keypoints.
+
+ Notes:
+ Keypoint format: [x, y] or [x, y, confidence].
+ Modifies self.im in-place.
+ """
indices = indices or [2, 5, 7]
points = [(int(k[0]), int(k[1])) for i, k in enumerate(keypoints) if i in indices and k[2] >= conf_thresh]
@@ -284,6 +497,17 @@ color: tuple[int, int, int] = (104, 31, 17),
txt_color: tuple[int, int, int] = (255, 255, 255),
) -> int:
+ """Draw workout text with a background on the image.
+
+ Args:
+ display_text (str): The text to be displayed.
+ position (tuple[int, int]): Coordinates (x, y) on the image where the text will be placed.
+ color (tuple[int, int, int]): Text background color.
+ txt_color (tuple[int, int, int]): Text foreground color.
+
+ Returns:
+ (int): The height of the text.
+ """
(text_width, text_height), _ = cv2.getTextSize(display_text, 0, fontScale=self.sf, thickness=self.tf)
# Draw background rectangle
@@ -308,6 +532,16 @@ color: tuple[int, int, int] = (104, 31, 17),
txt_color: tuple[int, int, int] = (255, 255, 255),
):
+ """Plot the pose angle, count value, and step stage for workout monitoring.
+
+ Args:
+ angle_text (str): Angle value for workout monitoring.
+ count_text (str): Counts value for workout monitoring.
+ stage_text (str): Stage decision for workout monitoring.
+ center_kpt (list[int]): Centroid pose index for workout monitoring.
+ color (tuple[int, int, int]): Text background color.
+ txt_color (tuple[int, int, int]): Text foreground color.
+ """
# Format text
angle_text, count_text, stage_text = f" {angle_text:.2f}", f"Steps : {count_text}", f" {stage_text}"
@@ -329,6 +563,14 @@ line_color: tuple[int, int, int] = (104, 31, 17),
centroid_color: tuple[int, int, int] = (255, 0, 255),
):
+ """Plot the distance and line between two centroids on the frame.
+
+ Args:
+ pixels_distance (float): Pixel distance between two bounding-box centroids.
+ centroids (list[tuple[int, int]]): Bounding box centroids data.
+ line_color (tuple[int, int, int]): Distance line color.
+ centroid_color (tuple[int, int, int]): Bounding box centroid color.
+ """
# Get the text size
text = f"Pixels Distance: {pixels_distance:.2f}"
(text_width_m, text_height_m), _ = cv2.getTextSize(text, 0, self.sf, self.tf)
@@ -363,6 +605,17 @@ y_center: float,
margin: int,
):
+ """Display the bounding boxes labels in parking management app.
+
+ Args:
+ im0 (np.ndarray): Inference image.
+ text (str): Object/class name.
+ txt_color (tuple[int, int, int]): Display color for text foreground.
+ bg_color (tuple[int, int, int]): Display color for text background.
+ x_center (float): The x position center point for bounding box.
+ y_center (float): The y position center point for bounding box.
+ margin (int): The gap between text and rectangle for better display.
+ """
text_size = cv2.getTextSize(text, 0, fontScale=self.sf, thickness=self.tf)[0]
text_x = x_center - text_size[0] // 2
text_y = y_center + text_size[1] // 2
@@ -398,6 +651,15 @@ color: tuple[int, int, int] = (221, 0, 186),
txt_color: tuple[int, int, int] = (255, 255, 255),
):
+ """Draw a sweep annotation line and an optional label.
+
+ Args:
+ line_x (int): The x-coordinate of the sweep line.
+ line_y (int): The y-coordinate limit of the sweep line.
+ label (str, optional): Text label to be drawn in center of sweep line. If None, no label is drawn.
+ color (tuple[int, int, int]): BGR color for the line and label background (OpenCV format).
+ txt_color (tuple[int, int, int]): BGR color for the label text (OpenCV format).
+ """
# Draw the sweep line
cv2.line(self.im, (line_x, 0), (line_x, line_y), color, self.tf * 2)
@@ -428,6 +690,14 @@ color: tuple[int, int, int] = (235, 219, 11),
pin_color: tuple[int, int, int] = (255, 0, 255),
):
+ """Perform pinpoint human-vision eye mapping and plotting.
+
+ Args:
+ box (list[float]): Bounding box coordinates in format [x1, y1, x2, y2].
+ center_point (tuple[int, int]): Center point for vision eye view.
+ color (tuple[int, int, int]): Object centroid and line color.
+ pin_color (tuple[int, int, int]): Visioneye point color.
+ """
center_bbox = int((box[0] + box[2]) / 2), int((box[1] + box[3]) / 2)
cv2.circle(self.im, center_point, self.tf * 2, pin_color, -1)
cv2.circle(self.im, center_bbox, self.tf * 2, color, -1)
@@ -442,6 +712,16 @@ shape: str = "rect",
margin: int = 5,
):
+ """Draw a label with a background rectangle or circle centered within a given bounding box.
+
+ Args:
+ box (tuple[float, float, float, float]): The bounding box coordinates (x1, y1, x2, y2).
+ label (str): The text label to be displayed.
+ color (tuple[int, int, int]): The background color of the rectangle (B, G, R).
+ txt_color (tuple[int, int, int]): The color of the text (B, G, R).
+ shape (str): Label shape. Options: "circle" or "rect".
+ margin (int): The margin between the text and the rectangle border.
+ """
if shape == "circle" and len(label) > 3:
LOGGER.warning(f"Length of label is {len(label)}, only first 3 letters will be used for circle annotation.")
label = label[:3]
@@ -481,8 +761,38 @@
class SolutionResults:
+ """A class to encapsulate the results of Ultralytics Solutions.
+
+ This class is designed to store and manage various outputs generated by the solution pipeline, including counts,
+ angles, workout stages, and other analytics data. It provides a structured way to access and manipulate results from
+ different computer vision solutions such as object counting, pose estimation, and tracking analytics.
+
+ Attributes:
+ plot_im (np.ndarray): Processed image with counts, blurred, or other effects from solutions.
+ in_count (int): The total number of "in" counts in a video stream.
+ out_count (int): The total number of "out" counts in a video stream.
+ classwise_count (dict[str, int]): A dictionary containing counts of objects categorized by class.
+ queue_count (int): The count of objects in a queue or waiting area.
+ workout_count (int): The count of workout repetitions.
+ workout_angle (float): The angle calculated during a workout exercise.
+ workout_stage (str): The current stage of the workout.
+ pixels_distance (float): The calculated distance in pixels between two points or objects.
+ available_slots (int): The number of available slots in a monitored area.
+ filled_slots (int): The number of filled slots in a monitored area.
+ email_sent (bool): A flag indicating whether an email notification was sent.
+ total_tracks (int): The total number of tracked objects.
+ region_counts (dict[str, int]): The count of objects within a specific region.
+ speed_dict (dict[str, float]): A dictionary containing speed information for tracked objects.
+ total_crop_objects (int): Total number of cropped objects using ObjectCropper class.
+ speed (dict[str, float]): Performance timing information for tracking and solution processing.
+ """
def __init__(self, **kwargs):
+ """Initialize a SolutionResults object with default or user-specified values.
+
+ Args:
+ **kwargs (Any): Optional arguments to override default attribute values.
+ """
self.plot_im = None
self.in_count = 0
self.out_count = 0
@@ -505,9 +815,14 @@ self.__dict__.update(kwargs)
def __str__(self) -> str:
+ """Return a formatted string representation of the SolutionResults object.
+
+ Returns:
+ (str): A string representation listing non-null attributes.
+ """
attrs = {
k: v
for k, v in self.__dict__.items()
if k != "plot_im" and v not in [None, {}, 0, 0.0, False] # Exclude `plot_im` explicitly
}
- return ", ".join(f"{k}={v}" for k, v in attrs.items())+ return ", ".join(f"{k}={v}" for k, v in attrs.items())
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/solutions.py |
Add docstrings to improve readability | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from typing import Any
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
from ultralytics.utils import LOGGER
from ultralytics.utils.plotting import colors
class SecurityAlarm(BaseSolution):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.email_sent = False
self.records = self.CFG["records"]
self.server = None
self.to_email = ""
self.from_email = ""
def authenticate(self, from_email: str, password: str, to_email: str) -> None:
import smtplib
self.server = smtplib.SMTP("smtp.gmail.com", 587)
self.server.starttls()
self.server.login(from_email, password)
self.to_email = to_email
self.from_email = from_email
def send_email(self, im0, records: int = 5) -> None:
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import cv2
img_bytes = cv2.imencode(".jpg", im0)[1].tobytes() # Encode the image as JPEG
# Create the email
message = MIMEMultipart()
message["From"] = self.from_email
message["To"] = self.to_email
message["Subject"] = "Security Alert"
# Add the text message body
message_body = f"Ultralytics alert: {records} object(s) detected."
message.attach(MIMEText(message_body))
# Attach the image
image_attachment = MIMEImage(img_bytes, name="ultralytics.jpg")
message.attach(image_attachment)
# Send the email
try:
self.server.send_message(message)
LOGGER.info("Email sent successfully!")
except Exception as e:
LOGGER.error(f"Failed to send email: {e}")
def process(self, im0) -> SolutionResults:
self.extract_tracks(im0) # Extract tracks
annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator
# Iterate over bounding boxes and classes index
for box, cls in zip(self.boxes, self.clss):
# Draw bounding box
annotator.box_label(box, label=self.names[cls], color=colors(cls, True))
total_det = len(self.clss)
if total_det >= self.records and not self.email_sent: # Only send email if not sent before
self.send_email(im0, total_det)
self.email_sent = True
plot_im = annotator.result()
self.display_output(plot_im) # Display output with base class function
# Return a SolutionResults
return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids), email_sent=self.email_sent) | --- +++ @@ -8,8 +8,37 @@
class SecurityAlarm(BaseSolution):
+ """A class to manage security alarm functionalities for real-time monitoring.
+
+ This class extends the BaseSolution class and provides features to monitor objects in a frame, send email
+ notifications when specific thresholds are exceeded for total detections, and annotate the output frame for
+ visualization.
+
+ Attributes:
+ email_sent (bool): Flag to track if an email has already been sent for the current event.
+ records (int): Threshold for the number of detected objects to trigger an alert.
+ server (smtplib.SMTP): SMTP server connection for sending email alerts.
+ to_email (str): Recipient's email address for alerts.
+ from_email (str): Sender's email address for alerts.
+
+ Methods:
+ authenticate: Set up email server authentication for sending alerts.
+ send_email: Send an email notification with details and an image attachment.
+ process: Monitor the frame, process detections, and trigger alerts if thresholds are crossed.
+
+ Examples:
+ >>> security = SecurityAlarm()
+ >>> security.authenticate("abc@gmail.com", "1111222233334444", "xyz@gmail.com")
+ >>> frame = cv2.imread("frame.jpg")
+ >>> results = security.process(frame)
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the SecurityAlarm class with parameters for real-time object monitoring.
+
+ Args:
+ **kwargs (Any): Additional keyword arguments passed to the parent class.
+ """
super().__init__(**kwargs)
self.email_sent = False
self.records = self.CFG["records"]
@@ -18,6 +47,19 @@ self.from_email = ""
def authenticate(self, from_email: str, password: str, to_email: str) -> None:
+ """Authenticate the email server for sending alert notifications.
+
+ This method initializes a secure connection with the SMTP server and logs in using the provided credentials.
+
+ Args:
+ from_email (str): Sender's email address.
+ password (str): Password for the sender's email account.
+ to_email (str): Recipient's email address.
+
+ Examples:
+ >>> alarm = SecurityAlarm()
+ >>> alarm.authenticate("sender@example.com", "password123", "recipient@example.com")
+ """
import smtplib
self.server = smtplib.SMTP("smtp.gmail.com", 587)
@@ -27,6 +69,20 @@ self.from_email = from_email
def send_email(self, im0, records: int = 5) -> None:
+ """Send an email notification with an image attachment indicating the number of objects detected.
+
+ This method encodes the input image, composes the email message with details about the detection, and sends it
+ to the specified recipient.
+
+ Args:
+ im0 (np.ndarray): The input image or frame to be attached to the email.
+ records (int, optional): The number of detected objects to be included in the email message.
+
+ Examples:
+ >>> alarm = SecurityAlarm()
+ >>> frame = cv2.imread("path/to/image.jpg")
+ >>> alarm.send_email(frame, records=10)
+ """
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
@@ -57,6 +113,24 @@ LOGGER.error(f"Failed to send email: {e}")
def process(self, im0) -> SolutionResults:
+ """Monitor the frame, process object detections, and trigger alerts if thresholds are met.
+
+ This method processes the input frame, extracts detections, annotates the frame with bounding boxes, and sends
+ an email notification if the number of detected objects meets or exceeds the specified threshold and an alert
+ has not already been sent.
+
+ Args:
+ im0 (np.ndarray): The input image or frame to be processed and annotated.
+
+ Returns:
+ (SolutionResults): Contains processed image `plot_im`, 'total_tracks' (total number of tracked objects) and
+ 'email_sent' (whether an email alert was triggered).
+
+ Examples:
+ >>> alarm = SecurityAlarm()
+ >>> frame = cv2.imread("path/to/image.jpg")
+ >>> results = alarm.process(frame)
+ """
self.extract_tracks(im0) # Extract tracks
annotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotator
@@ -74,4 +148,4 @@ self.display_output(plot_im) # Display output with base class function
# Return a SolutionResults
- return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids), email_sent=self.email_sent)+ return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids), email_sent=self.email_sent)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/security_alarm.py |
Add well-formatted docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from collections import defaultdict
from copy import deepcopy
# Trainer callbacks ----------------------------------------------------------------------------------------------------
def on_pretrain_routine_start(trainer):
pass
def on_pretrain_routine_end(trainer):
pass
def on_train_start(trainer):
pass
def on_train_epoch_start(trainer):
pass
def on_train_batch_start(trainer):
pass
def optimizer_step(trainer):
pass
def on_before_zero_grad(trainer):
pass
def on_train_batch_end(trainer):
pass
def on_train_epoch_end(trainer):
pass
def on_fit_epoch_end(trainer):
pass
def on_model_save(trainer):
pass
def on_train_end(trainer):
pass
def on_params_update(trainer):
pass
def teardown(trainer):
pass
# Validator callbacks --------------------------------------------------------------------------------------------------
def on_val_start(validator):
pass
def on_val_batch_start(validator):
pass
def on_val_batch_end(validator):
pass
def on_val_end(validator):
pass
# Predictor callbacks --------------------------------------------------------------------------------------------------
def on_predict_start(predictor):
pass
def on_predict_batch_start(predictor):
pass
def on_predict_batch_end(predictor):
pass
def on_predict_postprocess_end(predictor):
pass
def on_predict_end(predictor):
pass
# Exporter callbacks ---------------------------------------------------------------------------------------------------
def on_export_start(exporter):
pass
def on_export_end(exporter):
pass
default_callbacks = {
# Run in trainer
"on_pretrain_routine_start": [on_pretrain_routine_start],
"on_pretrain_routine_end": [on_pretrain_routine_end],
"on_train_start": [on_train_start],
"on_train_epoch_start": [on_train_epoch_start],
"on_train_batch_start": [on_train_batch_start],
"optimizer_step": [optimizer_step],
"on_before_zero_grad": [on_before_zero_grad],
"on_train_batch_end": [on_train_batch_end],
"on_train_epoch_end": [on_train_epoch_end],
"on_fit_epoch_end": [on_fit_epoch_end], # fit = train + val
"on_model_save": [on_model_save],
"on_train_end": [on_train_end],
"on_params_update": [on_params_update],
"teardown": [teardown],
# Run in validator
"on_val_start": [on_val_start],
"on_val_batch_start": [on_val_batch_start],
"on_val_batch_end": [on_val_batch_end],
"on_val_end": [on_val_end],
# Run in predictor
"on_predict_start": [on_predict_start],
"on_predict_batch_start": [on_predict_batch_start],
"on_predict_postprocess_end": [on_predict_postprocess_end],
"on_predict_batch_end": [on_predict_batch_end],
"on_predict_end": [on_predict_end],
# Run in exporter
"on_export_start": [on_export_start],
"on_export_end": [on_export_end],
}
def get_default_callbacks():
return defaultdict(list, deepcopy(default_callbacks))
def add_integration_callbacks(instance):
from .hub import callbacks as hub_cb
from .platform import callbacks as platform_cb
# Load Ultralytics callbacks
callbacks_list = [hub_cb, platform_cb]
# Load training callbacks
if "Trainer" in instance.__class__.__name__:
from .clearml import callbacks as clear_cb
from .comet import callbacks as comet_cb
from .dvc import callbacks as dvc_cb
from .mlflow import callbacks as mlflow_cb
from .neptune import callbacks as neptune_cb
from .raytune import callbacks as tune_cb
from .tensorboard import callbacks as tb_cb
from .wb import callbacks as wb_cb
callbacks_list.extend([clear_cb, comet_cb, dvc_cb, mlflow_cb, neptune_cb, tune_cb, tb_cb, wb_cb])
# Add the callbacks to the callbacks dictionary
for callbacks in callbacks_list:
for k, v in callbacks.items():
if v not in instance.callbacks[k]:
instance.callbacks[k].append(v) | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Base callbacks for Ultralytics training, validation, prediction, and export processes."""
from collections import defaultdict
from copy import deepcopy
@@ -7,58 +8,72 @@
def on_pretrain_routine_start(trainer):
+ """Called before the pretraining routine starts."""
pass
def on_pretrain_routine_end(trainer):
+ """Called after the pretraining routine ends."""
pass
def on_train_start(trainer):
+ """Called when the training starts."""
pass
def on_train_epoch_start(trainer):
+ """Called at the start of each training epoch."""
pass
def on_train_batch_start(trainer):
+ """Called at the start of each training batch."""
pass
def optimizer_step(trainer):
+ """Called when the optimizer takes a step."""
pass
def on_before_zero_grad(trainer):
+ """Called before the gradients are set to zero."""
pass
def on_train_batch_end(trainer):
+ """Called at the end of each training batch."""
pass
def on_train_epoch_end(trainer):
+ """Called at the end of each training epoch."""
pass
def on_fit_epoch_end(trainer):
+ """Called at the end of each fit epoch (train + val)."""
pass
def on_model_save(trainer):
+ """Called when the model is saved."""
pass
def on_train_end(trainer):
+ """Called when the training ends."""
pass
def on_params_update(trainer):
+ """Called when the model parameters are updated."""
pass
def teardown(trainer):
+ """Called during the teardown of the training process."""
pass
@@ -66,18 +81,22 @@
def on_val_start(validator):
+ """Called when the validation starts."""
pass
def on_val_batch_start(validator):
+ """Called at the start of each validation batch."""
pass
def on_val_batch_end(validator):
+ """Called at the end of each validation batch."""
pass
def on_val_end(validator):
+ """Called when the validation ends."""
pass
@@ -85,22 +104,27 @@
def on_predict_start(predictor):
+ """Called when the prediction starts."""
pass
def on_predict_batch_start(predictor):
+ """Called at the start of each prediction batch."""
pass
def on_predict_batch_end(predictor):
+ """Called at the end of each prediction batch."""
pass
def on_predict_postprocess_end(predictor):
+ """Called after the post-processing of the prediction ends."""
pass
def on_predict_end(predictor):
+ """Called when the prediction ends."""
pass
@@ -108,10 +132,12 @@
def on_export_start(exporter):
+ """Called when the model export starts."""
pass
def on_export_end(exporter):
+ """Called when the model export ends."""
pass
@@ -149,10 +175,38 @@
def get_default_callbacks():
+ """Get the default callbacks for Ultralytics training, validation, prediction, and export processes.
+
+ Returns:
+ (dict): Dictionary of default callbacks for various training events. Each key represents an event during the
+ training process, and the corresponding value is a list of callback functions executed when that
+ event occurs.
+
+ Examples:
+ >>> callbacks = get_default_callbacks()
+ >>> print(list(callbacks.keys())) # show all available callback events
+ ['on_pretrain_routine_start', 'on_pretrain_routine_end', ...]
+ """
return defaultdict(list, deepcopy(default_callbacks))
def add_integration_callbacks(instance):
+ """Add integration callbacks to the instance's callbacks dictionary.
+
+ This function loads and adds various integration callbacks to the provided instance. The specific callbacks added
+ depend on the type of instance provided. All instances receive HUB callbacks, while Trainer instances also receive
+ additional callbacks for various integrations like ClearML, Comet, DVC, MLflow, Neptune, Ray Tune, TensorBoard, and
+ Weights & Biases.
+
+ Args:
+ instance (Trainer | Predictor | Validator | Exporter): The object instance to which callbacks will be added. The
+ type of instance determines which callbacks are loaded.
+
+ Examples:
+ >>> from ultralytics.engine.trainer import BaseTrainer
+ >>> trainer = BaseTrainer()
+ >>> add_integration_callbacks(trainer)
+ """
from .hub import callbacks as hub_cb
from .platform import callbacks as platform_cb
@@ -176,4 +230,4 @@ for callbacks in callbacks_list:
for k, v in callbacks.items():
if v not in instance.callbacks[k]:
- instance.callbacks[k].append(v)+ instance.callbacks[k].append(v)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/callbacks/base.py |
Write documentation strings for class attributes | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from typing import Any
from ultralytics.solutions.solutions import BaseSolution, SolutionAnnotator, SolutionResults
from ultralytics.utils.plotting import colors
class VisionEye(BaseSolution):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
# Set the vision point where the system will view objects and draw tracks
self.vision_point = self.CFG["vision_point"]
def process(self, im0) -> SolutionResults:
self.extract_tracks(im0) # Extract tracks (bounding boxes, classes, and masks)
annotator = SolutionAnnotator(im0, self.line_width)
for cls, t_id, box, conf in zip(self.clss, self.track_ids, self.boxes, self.confs):
# Annotate the image with bounding boxes, labels, and vision mapping
annotator.box_label(box, label=self.adjust_box_label(cls, conf, t_id), color=colors(int(t_id), True))
annotator.visioneye(box, self.vision_point)
plot_im = annotator.result()
self.display_output(plot_im) # Display the annotated output using the base class function
# Return a SolutionResults object with the annotated image and tracking statistics
return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids)) | --- +++ @@ -7,13 +7,51 @@
class VisionEye(BaseSolution):
+ """A class to manage object detection and vision mapping in images or video streams.
+
+ This class extends the BaseSolution class and provides functionality for detecting objects, mapping vision points,
+ and annotating results with bounding boxes and labels.
+
+ Attributes:
+ vision_point (tuple[int, int]): Coordinates (x, y) where vision will view objects and draw tracks.
+
+ Methods:
+ process: Process the input image to detect objects, annotate them, and apply vision mapping.
+
+ Examples:
+ >>> vision_eye = VisionEye()
+ >>> frame = cv2.imread("frame.jpg")
+ >>> results = vision_eye.process(frame)
+ >>> print(f"Total detected instances: {results.total_tracks}")
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the VisionEye class for detecting objects and applying vision mapping.
+
+ Args:
+ **kwargs (Any): Keyword arguments passed to the parent class and for configuring vision_point.
+ """
super().__init__(**kwargs)
# Set the vision point where the system will view objects and draw tracks
self.vision_point = self.CFG["vision_point"]
def process(self, im0) -> SolutionResults:
+ """Perform object detection, vision mapping, and annotation on the input image.
+
+ Args:
+ im0 (np.ndarray): The input image for detection and annotation.
+
+ Returns:
+ (SolutionResults): Object containing the annotated image and tracking statistics.
+ - plot_im: Annotated output image with bounding boxes and vision mapping
+ - total_tracks: Number of tracked objects in the frame
+
+ Examples:
+ >>> vision_eye = VisionEye()
+ >>> frame = cv2.imread("image.jpg")
+ >>> results = vision_eye.process(frame)
+ >>> print(f"Detected {results.total_tracks} objects")
+ """
self.extract_tracks(im0) # Extract tracks (bounding boxes, classes, and masks)
annotator = SolutionAnnotator(im0, self.line_width)
@@ -26,4 +64,4 @@ self.display_output(plot_im) # Display the annotated output using the base class function
# Return a SolutionResults object with the annotated image and tracking statistics
- return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids))+ return SolutionResults(plot_im=plot_im, total_tracks=len(self.track_ids))
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/vision_eye.py |
Generate consistent documentation across files | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import io
import os
from typing import Any
import cv2
import torch
from ultralytics import YOLO
from ultralytics.utils import LOGGER
from ultralytics.utils.checks import check_requirements
from ultralytics.utils.downloads import GITHUB_ASSETS_STEMS
torch.classes.__path__ = [] # Torch module __path__._path issue: https://github.com/datalab-to/marker/issues/442
class Inference:
def __init__(self, **kwargs: Any) -> None:
check_requirements("streamlit>=1.29.0") # scope imports for faster ultralytics package load speeds
import streamlit as st
self.st = st # Reference to the Streamlit module
self.source = None # Video source selection (webcam or video file)
self.img_file_names = [] # List of image file names
self.enable_trk = False # Flag to toggle object tracking
self.conf = 0.25 # Confidence threshold for detection
self.iou = 0.45 # Intersection-over-Union (IoU) threshold for non-maximum suppression
self.org_frame = None # Container for the original frame display
self.ann_frame = None # Container for the annotated frame display
self.vid_file_name = None # Video file name or webcam index
self.selected_ind: list[int] = [] # List of selected class indices for detection
self.model = None # YOLO model instance
self.temp_dict = {"model": None, **kwargs}
self.model_path = None # Model file path
if self.temp_dict["model"] is not None:
self.model_path = self.temp_dict["model"]
LOGGER.info(f"Ultralytics Solutions: ✅ {self.temp_dict}")
def web_ui(self) -> None:
menu_style_cfg = """<style>MainMenu {visibility: hidden;}</style>""" # Hide main menu style
# Main title of streamlit application
main_title_cfg = """<div><h1 style="color:#111F68; text-align:center; font-size:40px; margin-top:-50px;
font-family: 'Archivo', sans-serif; margin-bottom:20px;">Ultralytics YOLO Streamlit Application</h1></div>"""
# Subtitle of streamlit application
sub_title_cfg = """<div><h5 style="color:#042AFF; text-align:center; font-family: 'Archivo', sans-serif;
margin-top:-15px; margin-bottom:50px;">Experience real-time object detection on your webcam, videos, and images
with the power of Ultralytics YOLO! 🚀</h5></div>"""
# Set html page configuration and append custom HTML
self.st.set_page_config(page_title="Ultralytics Streamlit App", layout="wide")
self.st.markdown(menu_style_cfg, unsafe_allow_html=True)
self.st.markdown(main_title_cfg, unsafe_allow_html=True)
self.st.markdown(sub_title_cfg, unsafe_allow_html=True)
def sidebar(self) -> None:
with self.st.sidebar: # Add Ultralytics LOGO
logo = "https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralytics_Logotype_Original.svg"
self.st.image(logo, width=250)
self.st.sidebar.title("User Configuration") # Add elements to vertical setting menu
self.source = self.st.sidebar.selectbox(
"Source",
("webcam", "video", "image"),
) # Add source selection dropdown
if self.source in ["webcam", "video"]:
self.enable_trk = self.st.sidebar.radio("Enable Tracking", ("Yes", "No")) == "Yes" # Enable object tracking
self.conf = float(
self.st.sidebar.slider("Confidence Threshold", 0.0, 1.0, self.conf, 0.01)
) # Slider for confidence
self.iou = float(self.st.sidebar.slider("IoU Threshold", 0.0, 1.0, self.iou, 0.01)) # Slider for NMS threshold
if self.source != "image": # Only create columns for video/webcam
col1, col2 = self.st.columns(2) # Create two columns for displaying frames
self.org_frame = col1.empty() # Container for original frame
self.ann_frame = col2.empty() # Container for annotated frame
def source_upload(self) -> None:
from ultralytics.data.utils import IMG_FORMATS, VID_FORMATS # scope import
self.vid_file_name = ""
if self.source == "video":
vid_file = self.st.sidebar.file_uploader("Upload Video File", type=VID_FORMATS)
if vid_file is not None:
g = io.BytesIO(vid_file.read()) # BytesIO Object
with open("ultralytics.mp4", "wb") as out: # Open temporary file as bytes
out.write(g.read()) # Read bytes into file
self.vid_file_name = "ultralytics.mp4"
elif self.source == "webcam":
self.vid_file_name = 0 # Use webcam index 0
elif self.source == "image":
import tempfile # scope import
if imgfiles := self.st.sidebar.file_uploader(
"Upload Image Files", type=IMG_FORMATS, accept_multiple_files=True
):
for imgfile in imgfiles: # Save each uploaded image to a temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{imgfile.name.split('.')[-1]}") as tf:
tf.write(imgfile.read())
self.img_file_names.append({"path": tf.name, "name": imgfile.name})
def configure(self) -> None:
# Add dropdown menu for model selection
M_ORD, T_ORD = ["yolo11n", "yolo11s", "yolo11m", "yolo11l", "yolo11x"], ["", "-seg", "-pose", "-obb", "-cls"]
available_models = sorted(
[
x.replace("yolo", "YOLO")
for x in GITHUB_ASSETS_STEMS
if any(x.startswith(b) for b in M_ORD) and "grayscale" not in x
],
key=lambda x: (M_ORD.index(x[:7].lower()), T_ORD.index(x[7:].lower() or "")),
)
if self.model_path: # Insert user provided custom model in available_models
available_models.insert(0, self.model_path)
selected_model = self.st.sidebar.selectbox("Model", available_models)
with self.st.spinner("Model is downloading..."):
if selected_model.endswith((".pt", ".onnx", ".torchscript", ".mlpackage", ".engine")) or any(
fmt in selected_model for fmt in ("openvino_model", "rknn_model")
):
model_path = selected_model
else:
model_path = f"{selected_model.lower()}.pt" # Default to .pt if no model provided during function call.
self.model = YOLO(model_path) # Load the YOLO model
class_names = list(self.model.names.values()) # Convert dictionary to list of class names
self.st.success("Model loaded successfully!")
# Multiselect box with class names and get indices of selected classes
selected_classes = self.st.sidebar.multiselect("Classes", class_names, default=class_names[:3])
self.selected_ind = [class_names.index(option) for option in selected_classes]
if not isinstance(self.selected_ind, list): # Ensure selected_options is a list
self.selected_ind = list(self.selected_ind)
def image_inference(self) -> None:
for img_info in self.img_file_names:
img_path = img_info["path"]
image = cv2.imread(img_path) # Load and display the original image
if image is not None:
self.st.markdown(f"#### Processed: {img_info['name']}")
col1, col2 = self.st.columns(2)
with col1:
self.st.image(image, channels="BGR", caption="Original Image")
results = self.model(image, conf=self.conf, iou=self.iou, classes=self.selected_ind)
annotated_image = results[0].plot()
with col2:
self.st.image(annotated_image, channels="BGR", caption="Predicted Image")
try: # Clean up temporary file
os.unlink(img_path)
except FileNotFoundError:
pass # File doesn't exist, ignore
else:
self.st.error("Could not load the uploaded image.")
def inference(self) -> None:
self.web_ui() # Initialize the web interface
self.sidebar() # Create the sidebar
self.source_upload() # Upload the video source
self.configure() # Configure the app
if self.st.sidebar.button("Start"):
if self.source == "image":
if self.img_file_names:
self.image_inference()
else:
self.st.info("Please upload an image file to perform inference.")
return
stop_button = self.st.sidebar.button("Stop") # Button to stop the inference
cap = cv2.VideoCapture(self.vid_file_name) # Capture the video
if not cap.isOpened():
self.st.error("Could not open webcam or video source.")
return
while cap.isOpened():
success, frame = cap.read()
if not success:
self.st.warning("Failed to read frame from webcam. Please verify the webcam is connected properly.")
break
# Process frame with model
if self.enable_trk:
results = self.model.track(
frame, conf=self.conf, iou=self.iou, classes=self.selected_ind, persist=True
)
else:
results = self.model(frame, conf=self.conf, iou=self.iou, classes=self.selected_ind)
annotated_frame = results[0].plot() # Add annotations on frame
if stop_button:
cap.release() # Release the capture
self.st.stop() # Stop streamlit app
self.org_frame.image(frame, channels="BGR", caption="Original Frame") # Display original frame
self.ann_frame.image(annotated_frame, channels="BGR", caption="Predicted Frame") # Display processed
cap.release() # Release the capture
cv2.destroyAllWindows() # Destroy all OpenCV windows
if __name__ == "__main__":
import sys # Import the sys module for accessing command-line arguments
# Check if a model name is provided as a command-line argument
args = len(sys.argv)
model = sys.argv[1] if args > 1 else None # Assign first argument as the model name if provided
# Create an instance of the Inference class and run inference
Inference(model=model).inference() | --- +++ @@ -16,8 +16,48 @@
class Inference:
+ """A class to perform object detection, image classification, image segmentation and pose estimation inference.
+
+ This class provides functionalities for loading models, configuring settings, uploading video files, and performing
+ real-time inference using Streamlit and Ultralytics YOLO models.
+
+ Attributes:
+ st (module): Streamlit module for UI creation.
+ temp_dict (dict): Temporary dictionary to store the model path and other configuration.
+ model_path (str): Path to the loaded model.
+ model (YOLO): The YOLO model instance.
+ source (str): Selected video source (webcam or video file).
+ enable_trk (bool): Enable tracking option.
+ conf (float): Confidence threshold for detection.
+ iou (float): IoU threshold for non-maximum suppression.
+ org_frame (Any): Container for the original frame to be displayed.
+ ann_frame (Any): Container for the annotated frame to be displayed.
+ vid_file_name (str | int): Name of the uploaded video file or webcam index.
+ selected_ind (list[int]): List of selected class indices for detection.
+
+ Methods:
+ web_ui: Set up the Streamlit web interface with custom HTML elements.
+ sidebar: Configure the Streamlit sidebar for model and inference settings.
+ source_upload: Handle video file uploads through the Streamlit interface.
+ configure: Configure the model and load selected classes for inference.
+ inference: Perform real-time object detection inference.
+
+ Examples:
+ Create an Inference instance with a custom model
+ >>> inf = Inference(model="path/to/model.pt")
+ >>> inf.inference()
+
+ Create an Inference instance with default settings
+ >>> inf = Inference()
+ >>> inf.inference()
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the Inference class, checking Streamlit requirements and setting up the model path.
+
+ Args:
+ **kwargs (Any): Additional keyword arguments for model configuration.
+ """
check_requirements("streamlit>=1.29.0") # scope imports for faster ultralytics package load speeds
import streamlit as st
@@ -41,6 +81,7 @@ LOGGER.info(f"Ultralytics Solutions: ✅ {self.temp_dict}")
def web_ui(self) -> None:
+ """Set up the Streamlit web interface with custom HTML elements."""
menu_style_cfg = """<style>MainMenu {visibility: hidden;}</style>""" # Hide main menu style
# Main title of streamlit application
@@ -59,6 +100,7 @@ self.st.markdown(sub_title_cfg, unsafe_allow_html=True)
def sidebar(self) -> None:
+ """Configure the Streamlit sidebar for model and inference settings."""
with self.st.sidebar: # Add Ultralytics LOGO
logo = "https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralytics_Logotype_Original.svg"
self.st.image(logo, width=250)
@@ -81,6 +123,7 @@ self.ann_frame = col2.empty() # Container for annotated frame
def source_upload(self) -> None:
+ """Handle video file uploads through the Streamlit interface."""
from ultralytics.data.utils import IMG_FORMATS, VID_FORMATS # scope import
self.vid_file_name = ""
@@ -105,6 +148,7 @@ self.img_file_names.append({"path": tf.name, "name": imgfile.name})
def configure(self) -> None:
+ """Configure the model and load selected classes for inference."""
# Add dropdown menu for model selection
M_ORD, T_ORD = ["yolo11n", "yolo11s", "yolo11m", "yolo11l", "yolo11x"], ["", "-seg", "-pose", "-obb", "-cls"]
available_models = sorted(
@@ -138,6 +182,7 @@ self.selected_ind = list(self.selected_ind)
def image_inference(self) -> None:
+ """Perform inference on uploaded images."""
for img_info in self.img_file_names:
img_path = img_info["path"]
image = cv2.imread(img_path) # Load and display the original image
@@ -158,6 +203,7 @@ self.st.error("Could not load the uploaded image.")
def inference(self) -> None:
+ """Perform real-time object detection inference on video or webcam feed."""
self.web_ui() # Initialize the web interface
self.sidebar() # Create the sidebar
self.source_upload() # Upload the video source
@@ -211,4 +257,4 @@ args = len(sys.argv)
model = sys.argv[1] if args > 1 else None # Assign first argument as the model name if provided
# Create an instance of the Inference class and run inference
- Inference(model=model).inference()+ Inference(model=model).inference()
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/streamlit_inference.py |
Add documentation for all methods | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from ultralytics.utils import LOGGER, RUNS_DIR, SETTINGS, TESTS_RUNNING, colorstr
try:
import os
assert not TESTS_RUNNING or "test_mlflow" in os.environ.get("PYTEST_CURRENT_TEST", "") # do not log pytest
assert SETTINGS["mlflow"] is True # verify integration is enabled
import mlflow
assert hasattr(mlflow, "__version__") # verify package is not directory
from pathlib import Path
PREFIX = colorstr("MLflow: ")
except (ImportError, AssertionError):
mlflow = None
def sanitize_dict(x: dict) -> dict:
return {k.replace("(", "").replace(")", ""): float(v) for k, v in x.items()}
def on_pretrain_routine_end(trainer):
global mlflow
uri = os.environ.get("MLFLOW_TRACKING_URI") or str(RUNS_DIR / "mlflow")
LOGGER.debug(f"{PREFIX} tracking uri: {uri}")
mlflow.set_tracking_uri(uri)
# Set experiment and run names
experiment_name = os.environ.get("MLFLOW_EXPERIMENT_NAME") or trainer.args.project or "/Shared/Ultralytics"
run_name = os.environ.get("MLFLOW_RUN") or trainer.args.name
mlflow.set_experiment(experiment_name)
mlflow.autolog()
try:
active_run = mlflow.active_run() or mlflow.start_run(run_name=run_name)
LOGGER.info(f"{PREFIX}logging run_id({active_run.info.run_id}) to {uri}")
if Path(uri).is_dir():
LOGGER.info(f"{PREFIX}view at http://127.0.0.1:5000 with 'mlflow server --backend-store-uri {uri}'")
LOGGER.info(f"{PREFIX}disable with 'yolo settings mlflow=False'")
mlflow.log_params(dict(trainer.args))
except Exception as e:
LOGGER.warning(f"{PREFIX}Failed to initialize: {e}")
LOGGER.warning(f"{PREFIX}Not tracking this run")
def on_train_epoch_end(trainer):
if mlflow:
mlflow.log_metrics(
metrics={
**sanitize_dict(trainer.lr),
**sanitize_dict(trainer.label_loss_items(trainer.tloss, prefix="train")),
},
step=trainer.epoch,
)
def on_fit_epoch_end(trainer):
if mlflow:
mlflow.log_metrics(metrics=sanitize_dict(trainer.metrics), step=trainer.epoch)
def on_train_end(trainer):
if not mlflow:
return
mlflow.log_artifact(str(trainer.best.parent)) # log save_dir/weights directory with best.pt and last.pt
for f in trainer.save_dir.glob("*"): # log all other files in save_dir
if f.suffix in {".png", ".jpg", ".csv", ".pt", ".yaml"}:
mlflow.log_artifact(str(f))
keep_run_active = os.environ.get("MLFLOW_KEEP_RUN_ACTIVE", "False").lower() == "true"
if keep_run_active:
LOGGER.info(f"{PREFIX}mlflow run still alive, remember to close it using mlflow.end_run()")
else:
mlflow.end_run()
LOGGER.debug(f"{PREFIX}mlflow run ended")
LOGGER.info(
f"{PREFIX}results logged to {mlflow.get_tracking_uri()}\n{PREFIX}disable with 'yolo settings mlflow=False'"
)
callbacks = (
{
"on_pretrain_routine_end": on_pretrain_routine_end,
"on_train_epoch_end": on_train_epoch_end,
"on_fit_epoch_end": on_fit_epoch_end,
"on_train_end": on_train_end,
}
if mlflow
else {}
) | --- +++ @@ -1,4 +1,25 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""
+MLflow Logging for Ultralytics YOLO.
+
+This module enables MLflow logging for Ultralytics YOLO. It logs metrics, parameters, and model artifacts.
+For setting up, a tracking URI should be specified. The logging can be customized using environment variables.
+
+Commands:
+ 1. To set a project name:
+ `export MLFLOW_EXPERIMENT_NAME=<your_experiment_name>` or use the project=<project> argument
+
+ 2. To set a run name:
+ `export MLFLOW_RUN=<your_run_name>` or use the name=<name> argument
+
+ 3. To start a local MLflow server:
+ mlflow server --backend-store-uri runs/mlflow
+ It will by default start a local server at http://127.0.0.1:5000.
+ To specify a different URI, set the MLFLOW_TRACKING_URI environment variable.
+
+ 4. To kill all running MLflow server instances:
+ ps aux | grep 'mlflow' | grep -v 'grep' | awk '{print $2}' | xargs kill -9
+"""
from ultralytics.utils import LOGGER, RUNS_DIR, SETTINGS, TESTS_RUNNING, colorstr
@@ -19,10 +40,26 @@
def sanitize_dict(x: dict) -> dict:
+ """Sanitize dictionary keys by removing parentheses and converting values to floats."""
return {k.replace("(", "").replace(")", ""): float(v) for k, v in x.items()}
def on_pretrain_routine_end(trainer):
+ """Log training parameters to MLflow at the end of the pretraining routine.
+
+ This function sets up MLflow logging based on environment variables and trainer arguments. It sets the tracking URI,
+ experiment name, and run name, then starts the MLflow run if not already active. It finally logs the parameters from
+ the trainer.
+
+ Args:
+ trainer (ultralytics.engine.trainer.BaseTrainer): The training object with arguments and parameters to log.
+
+ Notes:
+ MLFLOW_TRACKING_URI: The URI for MLflow tracking. If not set, defaults to 'runs/mlflow'.
+ MLFLOW_EXPERIMENT_NAME: The name of the MLflow experiment. If not set, defaults to trainer.args.project.
+ MLFLOW_RUN: The name of the MLflow run. If not set, defaults to trainer.args.name.
+ MLFLOW_KEEP_RUN_ACTIVE: Boolean indicating whether to keep the MLflow run active after training ends.
+ """
global mlflow
uri = os.environ.get("MLFLOW_TRACKING_URI") or str(RUNS_DIR / "mlflow")
@@ -48,6 +85,7 @@
def on_train_epoch_end(trainer):
+ """Log training metrics at the end of each train epoch to MLflow."""
if mlflow:
mlflow.log_metrics(
metrics={
@@ -59,11 +97,13 @@
def on_fit_epoch_end(trainer):
+ """Log training metrics at the end of each fit epoch to MLflow."""
if mlflow:
mlflow.log_metrics(metrics=sanitize_dict(trainer.metrics), step=trainer.epoch)
def on_train_end(trainer):
+ """Log model artifacts at the end of training."""
if not mlflow:
return
mlflow.log_artifact(str(trainer.best.parent)) # log save_dir/weights directory with best.pt and last.pt
@@ -91,4 +131,4 @@ }
if mlflow
else {}
-)+)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/callbacks/mlflow.py |
Generate docstrings with parameter types | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import os
from copy import deepcopy
import numpy as np
import torch
from ultralytics.utils import DEFAULT_CFG, LOGGER, colorstr
from ultralytics.utils.torch_utils import autocast, profile_ops
def check_train_batch_size(
model: torch.nn.Module,
imgsz: int = 640,
amp: bool = True,
batch: int | float = -1,
max_num_obj: int = 1,
) -> int:
with autocast(enabled=amp):
return autobatch(
deepcopy(model).train(), imgsz, fraction=batch if 0.0 < batch < 1.0 else 0.6, max_num_obj=max_num_obj
)
def autobatch(
model: torch.nn.Module,
imgsz: int = 640,
fraction: float = 0.60,
batch_size: int = DEFAULT_CFG.batch,
max_num_obj: int = 1,
) -> int:
# Check device
prefix = colorstr("AutoBatch: ")
LOGGER.info(f"{prefix}Computing optimal batch size for imgsz={imgsz} at {fraction * 100}% CUDA memory utilization.")
device = next(model.parameters()).device # get model device
if device.type in {"cpu", "mps"}:
LOGGER.warning(f"{prefix}intended for CUDA devices, using default batch-size {batch_size}")
return batch_size
if torch.backends.cudnn.benchmark:
LOGGER.warning(f"{prefix}Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}")
return batch_size
# Inspect CUDA memory
gb = 1 << 30 # bytes to GiB (1024 ** 3)
d = f"CUDA:{os.getenv('CUDA_VISIBLE_DEVICES', '0').strip()[0]}" # 'CUDA:0'
properties = torch.cuda.get_device_properties(device) # device properties
t = properties.total_memory / gb # GiB total
r = torch.cuda.memory_reserved(device) / gb # GiB reserved
a = torch.cuda.memory_allocated(device) / gb # GiB allocated
f = t - (r + a) # GiB free
LOGGER.info(f"{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free")
# Profile batch sizes
batch_sizes = [1, 2, 4, 8, 16] if t < 16 else [1, 2, 4, 8, 16, 32, 64]
ch = model.yaml.get("channels", 3)
try:
img = [torch.empty(b, ch, imgsz, imgsz) for b in batch_sizes]
results = profile_ops(img, model, n=1, device=device, max_num_obj=max_num_obj)
# Fit a solution
xy = [
[x, y[2]]
for i, (x, y) in enumerate(zip(batch_sizes, results))
if y # valid result
and isinstance(y[2], (int, float)) # is numeric
and 0 < y[2] < t # between 0 and GPU limit
and (i == 0 or not results[i - 1] or y[2] > results[i - 1][2]) # first item or increasing memory
]
fit_x, fit_y = zip(*xy) if xy else ([], [])
p = np.polyfit(fit_x, fit_y, deg=1) # first-degree polynomial fit in log space
b = int((round(f * fraction) - p[1]) / p[0]) # y intercept (optimal batch size)
if None in results: # some sizes failed
i = results.index(None) # first fail index
if b >= batch_sizes[i]: # y intercept above failure point
b = batch_sizes[max(i - 1, 0)] # select prior safe point
if b < 1 or b > 1024: # b outside of safe range
LOGGER.warning(f"{prefix}batch={b} outside safe range, using default batch-size {batch_size}.")
b = batch_size
fraction = (np.polyval(p, b) + r + a) / t # predicted fraction
LOGGER.info(f"{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅")
return b
except Exception as e:
LOGGER.warning(f"{prefix}error detected: {e}, using default batch-size {batch_size}.")
return batch_size
finally:
torch.cuda.empty_cache() | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Functions for estimating the best YOLO batch size to use a fraction of the available CUDA memory in PyTorch."""
from __future__ import annotations
@@ -19,6 +20,22 @@ batch: int | float = -1,
max_num_obj: int = 1,
) -> int:
+ """Compute optimal YOLO training batch size using the autobatch() function.
+
+ Args:
+ model (torch.nn.Module): YOLO model to check batch size for.
+ imgsz (int, optional): Image size used for training.
+ amp (bool, optional): Use automatic mixed precision if True.
+ batch (int | float, optional): Fraction of GPU memory to use. If -1, use default.
+ max_num_obj (int, optional): The maximum number of objects from dataset.
+
+ Returns:
+ (int): Optimal batch size computed using the autobatch() function.
+
+ Notes:
+ If 0.0 < batch < 1.0, it's used as the fraction of GPU memory to use.
+ Otherwise, a default fraction of 0.6 is used.
+ """
with autocast(enabled=amp):
return autobatch(
deepcopy(model).train(), imgsz, fraction=batch if 0.0 < batch < 1.0 else 0.6, max_num_obj=max_num_obj
@@ -32,6 +49,18 @@ batch_size: int = DEFAULT_CFG.batch,
max_num_obj: int = 1,
) -> int:
+ """Automatically estimate the best YOLO batch size to use a fraction of the available CUDA memory.
+
+ Args:
+ model (torch.nn.Module): YOLO model to compute batch size for.
+ imgsz (int, optional): The image size used as input for the YOLO model.
+ fraction (float, optional): The fraction of available CUDA memory to use.
+ batch_size (int, optional): The default batch size to use if an error is detected.
+ max_num_obj (int, optional): The maximum number of objects from dataset.
+
+ Returns:
+ (int): The optimal batch size.
+ """
# Check device
prefix = colorstr("AutoBatch: ")
LOGGER.info(f"{prefix}Computing optimal batch size for imgsz={imgsz} at {fraction * 100}% CUDA memory utilization.")
@@ -87,4 +116,4 @@ LOGGER.warning(f"{prefix}error detected: {e}, using default batch-size {batch_size}.")
return batch_size
finally:
- torch.cuda.empty_cache()+ torch.cuda.empty_cache()
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/autobatch.py |
Write docstrings for backend logic | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import functools
import gc
import math
import os
import random
import time
from contextlib import contextmanager
from copy import deepcopy
from datetime import datetime
from pathlib import Path
from typing import Any
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from ultralytics import __version__
from ultralytics.utils import (
DEFAULT_CFG_DICT,
DEFAULT_CFG_KEYS,
LOGGER,
NUM_THREADS,
PYTHON_VERSION,
TORCH_VERSION,
TORCHVISION_VERSION,
WINDOWS,
colorstr,
)
from ultralytics.utils.checks import check_version
from ultralytics.utils.cpu import CPUInfo
from ultralytics.utils.patches import torch_load
# Version checks (all default to version>=min_version)
TORCH_1_9 = check_version(TORCH_VERSION, "1.9.0")
TORCH_1_10 = check_version(TORCH_VERSION, "1.10.0")
TORCH_1_11 = check_version(TORCH_VERSION, "1.11.0")
TORCH_1_13 = check_version(TORCH_VERSION, "1.13.0")
TORCH_2_0 = check_version(TORCH_VERSION, "2.0.0")
TORCH_2_1 = check_version(TORCH_VERSION, "2.1.0")
TORCH_2_3 = check_version(TORCH_VERSION, "2.3.0")
TORCH_2_4 = check_version(TORCH_VERSION, "2.4.0")
TORCH_2_8 = check_version(TORCH_VERSION, "2.8.0")
TORCH_2_9 = check_version(TORCH_VERSION, "2.9.0")
TORCH_2_10 = check_version(TORCH_VERSION, "2.10.0")
TORCHVISION_0_10 = check_version(TORCHVISION_VERSION, "0.10.0")
TORCHVISION_0_11 = check_version(TORCHVISION_VERSION, "0.11.0")
TORCHVISION_0_13 = check_version(TORCHVISION_VERSION, "0.13.0")
TORCHVISION_0_18 = check_version(TORCHVISION_VERSION, "0.18.0")
if WINDOWS and check_version(TORCH_VERSION, "==2.4.0"): # reject version 2.4.0 on Windows
LOGGER.warning(
"Known issue with torch==2.4.0 on Windows with CPU, recommend upgrading to torch>=2.4.1 to resolve "
"https://github.com/ultralytics/ultralytics/issues/15049"
)
@contextmanager
def torch_distributed_zero_first(local_rank: int):
initialized = dist.is_available() and dist.is_initialized()
use_ids = initialized and dist.get_backend() == "nccl"
if initialized and local_rank not in {-1, 0}:
dist.barrier(device_ids=[local_rank]) if use_ids else dist.barrier()
yield
if initialized and local_rank == 0:
dist.barrier(device_ids=[local_rank]) if use_ids else dist.barrier()
def smart_inference_mode():
def decorate(fn):
if TORCH_1_9 and torch.is_inference_mode_enabled():
return fn # already in inference_mode, act as a pass-through
else:
return (torch.inference_mode if TORCH_1_10 else torch.no_grad)()(fn)
return decorate
def autocast(enabled: bool, device: str = "cuda"):
if TORCH_1_13:
return torch.amp.autocast(device, enabled=enabled)
else:
return torch.cuda.amp.autocast(enabled)
@functools.lru_cache
def get_cpu_info():
from ultralytics.utils import PERSISTENT_CACHE # avoid circular import error
if "cpu_info" not in PERSISTENT_CACHE:
try:
PERSISTENT_CACHE["cpu_info"] = CPUInfo.name()
except Exception:
pass
return PERSISTENT_CACHE.get("cpu_info", "unknown")
@functools.lru_cache
def get_gpu_info(index):
properties = torch.cuda.get_device_properties(index)
return f"{properties.name}, {properties.total_memory / (1 << 20):.0f}MiB"
def select_device(device="", newline=False, verbose=True):
if isinstance(device, torch.device) or str(device).startswith(("tpu", "intel", "vulkan")):
return device
s = f"Ultralytics {__version__} 🚀 Python-{PYTHON_VERSION} torch-{TORCH_VERSION} "
device = str(device).lower()
for remove in "cuda:", "none", "(", ")", "[", "]", "'", " ":
device = device.replace(remove, "") # to string, 'cuda:0' -> '0' and '(0, 1)' -> '0,1'
# Huawei Ascend NPU
if device.startswith("npu"):
try:
import torch_npu # noqa
except ImportError:
raise ValueError(f"Invalid NPU 'device={device}'. Install 'torch_npu' at https://github.com/Ascend/pytorch")
if not hasattr(torch, "npu") or not torch.npu.is_available():
raise ValueError(f"Invalid NPU 'device={device}' requested. Ascend NPU is not available.")
# Parse 'npu' or 'npu:N' (multi-NPU not yet supported)
suffix = device[3:]
if suffix == "":
idx = 0
elif suffix.startswith(":") and suffix[1:].isdigit():
idx = int(suffix[1:])
else:
raise ValueError(f"Invalid NPU 'device={device}' format. Use 'npu' or 'npu:0'.")
n = torch.npu.device_count()
if idx >= n:
raise ValueError(f"Invalid NPU 'device={device}' requested. Only {n} NPU(s) available.")
torch.npu.set_device(idx)
if verbose:
LOGGER.info(f"{s}NPU:{idx} ({torch.npu.get_device_name(idx)})\n")
return torch.device(f"npu:{idx}")
# Auto-select GPUs
if "-1" in device:
from ultralytics.utils.autodevice import GPUInfo
# Replace each -1 with a selected GPU or remove it
parts = device.split(",")
selected = GPUInfo().select_idle_gpu(count=parts.count("-1"), min_memory_fraction=0.2)
for i in range(len(parts)):
if parts[i] == "-1":
parts[i] = str(selected.pop(0)) if selected else ""
device = ",".join(p for p in parts if p)
cpu = device == "cpu"
mps = device in {"mps", "mps:0"} # Apple Metal Performance Shaders (MPS)
if cpu or mps:
os.environ["CUDA_VISIBLE_DEVICES"] = "" # force torch.cuda.is_available() = False
elif device: # non-cpu device requested
if device == "cuda":
device = "0"
if "," in device:
device = ",".join([x for x in device.split(",") if x]) # remove sequential commas, i.e. "0,,1" -> "0,1"
visible = os.environ.get("CUDA_VISIBLE_DEVICES", None)
os.environ["CUDA_VISIBLE_DEVICES"] = device # set environment variable - must be before assert is_available()
if not (torch.cuda.is_available() and torch.cuda.device_count() >= len(device.split(","))):
LOGGER.info(s)
install = (
"See https://pytorch.org/get-started/locally/ for up-to-date torch install instructions if no "
"CUDA devices are seen by torch.\n"
if torch.cuda.device_count() == 0
else ""
)
raise ValueError(
f"Invalid CUDA 'device={device}' requested."
f" Use 'device=cpu' or pass valid CUDA device(s) if available,"
f" i.e. 'device=0' or 'device=0,1,2,3' for Multi-GPU.\n"
f"\ntorch.cuda.is_available(): {torch.cuda.is_available()}"
f"\ntorch.cuda.device_count(): {torch.cuda.device_count()}"
f"\nos.environ['CUDA_VISIBLE_DEVICES']: {visible}\n"
f"{install}"
)
if not cpu and not mps and torch.cuda.is_available(): # prefer GPU if available
devices = device.split(",") if device else "0" # i.e. "0,1" -> ["0", "1"]
space = " " * len(s)
for i, d in enumerate(devices):
s += f"{'' if i == 0 else space}CUDA:{d} ({get_gpu_info(i)})\n" # bytes to MB
arg = "cuda:0"
elif mps and TORCH_2_0 and torch.backends.mps.is_available():
# Prefer MPS if available
s += f"MPS ({get_cpu_info()})\n"
arg = "mps"
else: # revert to CPU
s += f"CPU ({get_cpu_info()})\n"
arg = "cpu"
if arg in {"cpu", "mps"}:
torch.set_num_threads(NUM_THREADS) # reset OMP_NUM_THREADS for cpu training
if verbose:
LOGGER.info(s if newline else s.rstrip())
return torch.device(arg)
def time_sync():
if torch.cuda.is_available():
torch.cuda.synchronize()
return time.time()
def fuse_conv_and_bn(conv, bn):
# Compute fused weights
w_conv = conv.weight.view(conv.out_channels, -1)
w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
conv.weight.data = torch.mm(w_bn, w_conv).view(conv.weight.shape)
# Compute fused bias
b_conv = torch.zeros(conv.out_channels, device=conv.weight.device) if conv.bias is None else conv.bias
b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
fused_bias = torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn
if conv.bias is None:
conv.register_parameter("bias", nn.Parameter(fused_bias))
else:
conv.bias.data = fused_bias
return conv.requires_grad_(False)
def fuse_deconv_and_bn(deconv, bn):
# Compute fused weights
w_deconv = deconv.weight.view(deconv.out_channels, -1)
w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
deconv.weight.data = torch.mm(w_bn, w_deconv).view(deconv.weight.shape)
# Compute fused bias
b_conv = torch.zeros(deconv.out_channels, device=deconv.weight.device) if deconv.bias is None else deconv.bias
b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
fused_bias = torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn
if deconv.bias is None:
deconv.register_parameter("bias", nn.Parameter(fused_bias))
else:
deconv.bias.data = fused_bias
return deconv.requires_grad_(False)
def model_info(model, detailed=False, verbose=True, imgsz=640):
if not verbose:
return
n_p = get_num_params(model) # number of parameters
n_g = get_num_gradients(model) # number of gradients
layers = __import__("collections").OrderedDict((n, m) for n, m in model.named_modules() if len(m._modules) == 0)
n_l = len(layers) # number of layers
if detailed:
h = f"{'layer':>5}{'name':>40}{'type':>20}{'gradient':>10}{'parameters':>12}{'shape':>20}{'mu':>10}{'sigma':>10}"
LOGGER.info(h)
for i, (mn, m) in enumerate(layers.items()):
mn = mn.replace("module_list.", "")
mt = m.__class__.__name__
if len(m._parameters):
for pn, p in m.named_parameters():
LOGGER.info(
f"{i:>5g}{f'{mn}.{pn}':>40}{mt:>20}{p.requires_grad!r:>10}{p.numel():>12g}{list(p.shape)!s:>20}{p.mean():>10.3g}{p.std():>10.3g}{str(p.dtype).replace('torch.', ''):>15}"
)
else: # layers with no learnable params
LOGGER.info(f"{i:>5g}{mn:>40}{mt:>20}{False!r:>10}{0:>12g}{[]!s:>20}{'-':>10}{'-':>10}{'-':>15}")
flops = get_flops(model, imgsz) # imgsz may be int or list, i.e. imgsz=640 or imgsz=[640, 320]
fused = " (fused)" if getattr(model, "is_fused", lambda: False)() else ""
fs = f", {flops:.1f} GFLOPs" if flops else ""
yaml_file = getattr(model, "yaml_file", "") or getattr(model, "yaml", {}).get("yaml_file", "")
model_name = Path(yaml_file).stem.replace("yolo", "YOLO") or "Model"
LOGGER.info(f"{model_name} summary{fused}: {n_l:,} layers, {n_p:,} parameters, {n_g:,} gradients{fs}")
return n_l, n_p, n_g, flops
def get_num_params(model):
return sum(x.numel() for x in model.parameters())
def get_num_gradients(model):
return sum(x.numel() for x in model.parameters() if x.requires_grad)
def model_info_for_loggers(trainer):
if trainer.args.profile: # profile ONNX and TensorRT times
from ultralytics.utils.benchmarks import ProfileModels
results = ProfileModels([trainer.last], device=trainer.device).run()[0]
results.pop("model/name")
else: # only return PyTorch times from most recent validation
results = {
"model/parameters": get_num_params(trainer.model),
"model/GFLOPs": round(get_flops(trainer.model), 3),
}
results["model/speed_PyTorch(ms)"] = round(trainer.validator.speed["inference"], 3)
return results
def get_flops(model, imgsz=640):
try:
import thop
except ImportError:
thop = None # conda support without 'ultralytics-thop' installed
if not thop:
return 0.0 # if not installed return 0.0 GFLOPs
try:
model = unwrap_model(model)
p = next(model.parameters())
if not isinstance(imgsz, list):
imgsz = [imgsz, imgsz] # expand if int/float
try:
# Method 1: Use stride-based input tensor
stride = max(int(model.stride.max()), 32) if hasattr(model, "stride") else 32 # max stride
im = torch.empty((1, p.shape[1], stride, stride), device=p.device) # input image in BCHW format
flops = thop.profile(deepcopy(model), inputs=[im], verbose=False)[0] / 1e9 * 2 # stride GFLOPs
return flops * imgsz[0] / stride * imgsz[1] / stride # imgsz GFLOPs
except Exception:
# Method 2: Use actual image size (required for RTDETR models)
im = torch.empty((1, p.shape[1], *imgsz), device=p.device) # input image in BCHW format
return thop.profile(deepcopy(model), inputs=[im], verbose=False)[0] / 1e9 * 2 # imgsz GFLOPs
except Exception:
return 0.0
def get_flops_with_torch_profiler(model, imgsz=640):
if not TORCH_2_0: # torch profiler implemented in torch>=2.0
return 0.0
model = unwrap_model(model)
p = next(model.parameters())
if not isinstance(imgsz, list):
imgsz = [imgsz, imgsz] # expand if int/float
try:
# Use stride size for input tensor
stride = (max(int(model.stride.max()), 32) if hasattr(model, "stride") else 32) * 2 # max stride
im = torch.empty((1, p.shape[1], stride, stride), device=p.device) # input image in BCHW format
with torch.profiler.profile(with_flops=True) as prof:
model(im)
flops = sum(x.flops for x in prof.key_averages()) / 1e9
flops = flops * imgsz[0] / stride * imgsz[1] / stride # 640x640 GFLOPs
except Exception:
# Use actual image size for input tensor (i.e. required for RTDETR models)
im = torch.empty((1, p.shape[1], *imgsz), device=p.device) # input image in BCHW format
with torch.profiler.profile(with_flops=True) as prof:
model(im)
flops = sum(x.flops for x in prof.key_averages()) / 1e9
return flops
def initialize_weights(model):
for m in model.modules():
t = type(m)
if t is nn.Conv2d:
pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif t is nn.BatchNorm2d:
m.eps = 1e-3
m.momentum = 0.03
elif t in {nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU}:
m.inplace = True
def scale_img(img, ratio=1.0, same_shape=False, gs=32):
if ratio == 1.0:
return img
h, w = img.shape[2:]
s = (int(h * ratio), int(w * ratio)) # new size
img = F.interpolate(img, size=s, mode="bilinear", align_corners=False) # resize
if not same_shape: # pad/crop img
h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w))
return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
def copy_attr(a, b, include=(), exclude=()):
for k, v in b.__dict__.items():
if (len(include) and k not in include) or k.startswith("_") or k in exclude:
continue
else:
setattr(a, k, v)
def intersect_dicts(da, db, exclude=()):
return {k: v for k, v in da.items() if k in db and all(x not in k for x in exclude) and v.shape == db[k].shape}
def is_parallel(model):
return isinstance(model, (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel))
def unwrap_model(m: nn.Module) -> nn.Module:
while True:
if hasattr(m, "_orig_mod") and isinstance(m._orig_mod, nn.Module):
m = m._orig_mod
elif hasattr(m, "module") and isinstance(m.module, nn.Module):
m = m.module
else:
return m
def one_cycle(y1=0.0, y2=1.0, steps=100):
return lambda x: max((1 - math.cos(x * math.pi / steps)) / 2, 0) * (y2 - y1) + y1
def init_seeds(seed=0, deterministic=False):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # for Multi-GPU, exception safe
# torch.backends.cudnn.benchmark = True # AutoBatch problem https://github.com/ultralytics/yolov5/issues/9287
if deterministic:
if TORCH_2_0:
torch.use_deterministic_algorithms(True, warn_only=True) # warn if deterministic is not possible
torch.backends.cudnn.deterministic = True
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
os.environ["PYTHONHASHSEED"] = str(seed)
else:
LOGGER.warning("Upgrade to torch>=2.0.0 for deterministic training.")
else:
unset_deterministic()
def unset_deterministic():
torch.use_deterministic_algorithms(False)
torch.backends.cudnn.deterministic = False
os.environ.pop("CUBLAS_WORKSPACE_CONFIG", None)
os.environ.pop("PYTHONHASHSEED", None)
class ModelEMA:
def __init__(self, model, decay=0.9999, tau=2000, updates=0):
self.ema = deepcopy(unwrap_model(model)).eval() # FP32 EMA
self.updates = updates # number of EMA updates
self.decay = lambda x: decay * (1 - math.exp(-x / tau)) # decay exponential ramp (to help early epochs)
for p in self.ema.parameters():
p.requires_grad_(False)
self.enabled = True
def update(self, model):
if self.enabled:
self.updates += 1
d = self.decay(self.updates)
msd = unwrap_model(model).state_dict() # model state_dict
for k, v in self.ema.state_dict().items():
if v.dtype.is_floating_point: # true for FP16 and FP32
v *= d
v += (1 - d) * msd[k].detach()
# assert v.dtype == msd[k].dtype == torch.float32, f'{k}: EMA {v.dtype}, model {msd[k].dtype}'
def update_attr(self, model, include=(), exclude=("process_group", "reducer")):
if self.enabled:
copy_attr(self.ema, model, include, exclude)
def strip_optimizer(f: str | Path = "best.pt", s: str = "", updates: dict[str, Any] | None = None) -> dict[str, Any]:
try:
x = torch_load(f, map_location=torch.device("cpu"))
assert isinstance(x, dict), "checkpoint is not a Python dictionary"
assert "model" in x, "'model' missing from checkpoint"
except Exception as e:
LOGGER.warning(f"Skipping {f}, not a valid Ultralytics model: {e}")
return {}
metadata = {
"date": datetime.now().isoformat(),
"version": __version__,
"license": "AGPL-3.0 License (https://ultralytics.com/license)",
"docs": "https://docs.ultralytics.com",
}
# Update model
if x.get("ema"):
x["model"] = x["ema"] # replace model with EMA
if hasattr(x["model"], "args"):
x["model"].args = dict(x["model"].args) # convert from IterableSimpleNamespace to dict
if hasattr(x["model"], "criterion"):
x["model"].criterion = None # strip loss criterion
x["model"].half() # to FP16
for p in x["model"].parameters():
p.requires_grad = False
# Update other keys
args = {**DEFAULT_CFG_DICT, **x.get("train_args", {})} # combine args
for k in "optimizer", "best_fitness", "ema", "updates", "scaler": # keys
x[k] = None
x["epoch"] = -1
x["train_args"] = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS} # strip non-default keys
# x['model'].args = x['train_args']
# Save
combined = {**metadata, **x, **(updates or {})}
torch.save(combined, s or f) # combine dicts (prefer to the right)
mb = os.path.getsize(s or f) / 1e6 # file size
LOGGER.info(f"Optimizer stripped from {f},{f' saved as {s},' if s else ''} {mb:.1f}MB")
return combined
def convert_optimizer_state_dict_to_fp16(state_dict):
for state in state_dict["state"].values():
for k, v in state.items():
if k != "step" and isinstance(v, torch.Tensor) and v.dtype is torch.float32:
state[k] = v.half()
return state_dict
@contextmanager
def cuda_memory_usage(device=None):
cuda_info = dict(memory=0)
if torch.cuda.is_available():
torch.cuda.empty_cache()
try:
yield cuda_info
finally:
cuda_info["memory"] = torch.cuda.memory_reserved(device)
else:
yield cuda_info
def profile_ops(input, ops, n=10, device=None, max_num_obj=0):
try:
import thop
except ImportError:
thop = None # conda support without 'ultralytics-thop' installed
results = []
if not isinstance(device, torch.device):
device = select_device(device)
LOGGER.info(
f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}"
f"{'input':>24s}{'output':>24s}"
)
gc.collect() # attempt to free unused memory
torch.cuda.empty_cache()
for x in input if isinstance(input, list) else [input]:
x = x.to(device)
x.requires_grad = True
for m in ops if isinstance(ops, list) else [ops]:
m = m.to(device) if hasattr(m, "to") else m # device
m = m.half() if hasattr(m, "half") and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m
tf, tb, t = 0, 0, [0, 0, 0] # dt forward, backward
try:
flops = thop.profile(deepcopy(m), inputs=[x], verbose=False)[0] / 1e9 * 2 if thop else 0 # GFLOPs
except Exception:
flops = 0
try:
mem = 0
for _ in range(n):
with cuda_memory_usage(device) as cuda_info:
t[0] = time_sync()
y = m(x)
t[1] = time_sync()
try:
(sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward()
t[2] = time_sync()
except Exception: # no backward method
# print(e) # for debug
t[2] = float("nan")
mem += cuda_info["memory"] / 1e9 # (GB)
tf += (t[1] - t[0]) * 1000 / n # ms per op forward
tb += (t[2] - t[1]) * 1000 / n # ms per op backward
if max_num_obj: # simulate training with predictions per image grid (for AutoBatch)
with cuda_memory_usage(device) as cuda_info:
torch.randn(
x.shape[0],
max_num_obj,
int(sum((x.shape[-1] / s) * (x.shape[-2] / s) for s in m.stride.tolist())),
device=device,
dtype=torch.float32,
)
mem += cuda_info["memory"] / 1e9 # (GB)
s_in, s_out = (tuple(x.shape) if isinstance(x, torch.Tensor) else "list" for x in (x, y)) # shapes
p = sum(x.numel() for x in m.parameters()) if isinstance(m, nn.Module) else 0 # parameters
LOGGER.info(f"{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{s_in!s:>24s}{s_out!s:>24s}")
results.append([p, flops, mem, tf, tb, s_in, s_out])
except Exception as e:
LOGGER.info(e)
results.append(None)
finally:
gc.collect() # attempt to free unused memory
torch.cuda.empty_cache()
return results
class EarlyStopping:
def __init__(self, patience=50):
self.best_fitness = 0.0 # i.e. mAP
self.best_epoch = 0
self.patience = patience or float("inf") # epochs to wait after fitness stops improving to stop
self.possible_stop = False # possible stop may occur next epoch
def __call__(self, epoch, fitness):
if fitness is None: # check if fitness=None (happens when val=False)
return False
if fitness > self.best_fitness or self.best_fitness == 0: # allow for early zero-fitness stage of training
self.best_epoch = epoch
self.best_fitness = fitness
delta = epoch - self.best_epoch # epochs without improvement
self.possible_stop = delta >= (self.patience - 1) # possible stop may occur next epoch
stop = delta >= self.patience # stop training if patience exceeded
if stop:
prefix = colorstr("EarlyStopping: ")
LOGGER.info(
f"{prefix}Training stopped early as no improvement observed in last {self.patience} epochs. "
f"Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\n"
f"To update EarlyStopping(patience={self.patience}) pass a new patience value, "
f"i.e. `patience=300` or use `patience=0` to disable EarlyStopping."
)
return stop
def attempt_compile(
model: torch.nn.Module,
device: torch.device,
imgsz: int = 640,
use_autocast: bool = False,
warmup: bool = False,
mode: bool | str = "default",
) -> torch.nn.Module:
if not hasattr(torch, "compile") or not mode:
return model
if mode is True:
mode = "default"
prefix = colorstr("compile:")
LOGGER.info(f"{prefix} starting torch.compile with '{mode}' mode...")
if mode == "max-autotune":
LOGGER.warning(f"{prefix} mode='{mode}' not recommended, using mode='max-autotune-no-cudagraphs' instead")
mode = "max-autotune-no-cudagraphs"
t0 = time.perf_counter()
try:
model = torch.compile(model, mode=mode, backend="inductor")
except Exception as e:
LOGGER.warning(f"{prefix} torch.compile failed, continuing uncompiled: {e}")
return model
t_compile = time.perf_counter() - t0
t_warm = 0.0
if warmup:
# Use a single dummy tensor to build the graph shape state and reduce first-iteration latency
dummy = torch.zeros(1, 3, imgsz, imgsz, device=device)
if use_autocast and device.type == "cuda":
dummy = dummy.half()
t1 = time.perf_counter()
with torch.inference_mode():
if use_autocast and device.type in {"cuda", "mps"}:
with torch.autocast(device.type):
_ = model(dummy)
else:
_ = model(dummy)
if device.type == "cuda":
torch.cuda.synchronize(device)
t_warm = time.perf_counter() - t1
total = t_compile + t_warm
if warmup:
LOGGER.info(f"{prefix} complete in {total:.1f}s (compile {t_compile:.1f}s + warmup {t_warm:.1f}s)")
else:
LOGGER.info(f"{prefix} compile complete in {t_compile:.1f}s (no warmup)")
return model | --- +++ @@ -61,6 +61,7 @@
@contextmanager
def torch_distributed_zero_first(local_rank: int):
+ """Ensure all processes in distributed training wait for the local master (rank 0) to complete a task first."""
initialized = dist.is_available() and dist.is_initialized()
use_ids = initialized and dist.get_backend() == "nccl"
@@ -72,8 +73,10 @@
def smart_inference_mode():
+ """Apply torch.inference_mode() decorator if torch>=1.10.0, else torch.no_grad() decorator."""
def decorate(fn):
+ """Apply appropriate torch decorator for inference mode based on torch version."""
if TORCH_1_9 and torch.is_inference_mode_enabled():
return fn # already in inference_mode, act as a pass-through
else:
@@ -83,6 +86,27 @@
def autocast(enabled: bool, device: str = "cuda"):
+ """Get the appropriate autocast context manager based on PyTorch version and AMP setting.
+
+ This function returns a context manager for automatic mixed precision (AMP) training that is compatible with both
+ older and newer versions of PyTorch. It handles the differences in the autocast API between PyTorch versions.
+
+ Args:
+ enabled (bool): Whether to enable automatic mixed precision.
+ device (str, optional): The device to use for autocast.
+
+ Returns:
+ (torch.amp.autocast): The appropriate autocast context manager.
+
+ Examples:
+ >>> with autocast(enabled=True):
+ ... # Your mixed precision operations here
+ ... pass
+
+ Notes:
+ - For PyTorch versions 1.13 and newer, it uses `torch.amp.autocast`.
+ - For older versions, it uses `torch.cuda.amp.autocast`.
+ """
if TORCH_1_13:
return torch.amp.autocast(device, enabled=enabled)
else:
@@ -91,6 +115,7 @@
@functools.lru_cache
def get_cpu_info():
+ """Return a string with system CPU information, i.e. 'Apple M2'."""
from ultralytics.utils import PERSISTENT_CACHE # avoid circular import error
if "cpu_info" not in PERSISTENT_CACHE:
@@ -103,11 +128,38 @@
@functools.lru_cache
def get_gpu_info(index):
+ """Return a string with system GPU information, i.e. 'Tesla T4, 15102MiB'."""
properties = torch.cuda.get_device_properties(index)
return f"{properties.name}, {properties.total_memory / (1 << 20):.0f}MiB"
def select_device(device="", newline=False, verbose=True):
+ """Select the appropriate PyTorch device based on the provided arguments.
+
+ The function takes a string specifying the device or a torch.device object and returns a torch.device object
+ representing the selected device. The function also validates the number of available devices and raises an
+ exception if the requested device(s) are not available.
+
+ Args:
+ device (str | torch.device, optional): Device string or torch.device object. Options include 'cpu', 'cuda', '0',
+ '0,1,2,3', 'mps', 'npu', 'npu:0', or '-1' for auto-select. Defaults to auto-selecting the first available
+ GPU, or CPU if no GPU is available.
+ newline (bool, optional): If True, adds a newline at the end of the log string.
+ verbose (bool, optional): If True, logs the device information.
+
+ Returns:
+ (torch.device): Selected device.
+
+ Examples:
+ >>> select_device("cuda:0")
+ device(type='cuda', index=0)
+
+ >>> select_device("cpu")
+ device(type='cpu')
+
+ Notes:
+ Sets the 'CUDA_VISIBLE_DEVICES' environment variable for specifying which GPUs to use.
+ """
if isinstance(device, torch.device) or str(device).startswith(("tpu", "intel", "vulkan")):
return device
@@ -207,12 +259,27 @@
def time_sync():
+ """Return PyTorch-accurate time."""
if torch.cuda.is_available():
torch.cuda.synchronize()
return time.time()
def fuse_conv_and_bn(conv, bn):
+ """Fuse Conv2d and BatchNorm2d layers for inference optimization.
+
+ Args:
+ conv (nn.Conv2d): Convolutional layer to fuse.
+ bn (nn.BatchNorm2d): Batch normalization layer to fuse.
+
+ Returns:
+ (nn.Conv2d): The fused convolutional layer with gradients disabled.
+
+ Examples:
+ >>> conv = nn.Conv2d(3, 16, 3)
+ >>> bn = nn.BatchNorm2d(16)
+ >>> fused_conv = fuse_conv_and_bn(conv, bn)
+ """
# Compute fused weights
w_conv = conv.weight.view(conv.out_channels, -1)
w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
@@ -232,6 +299,20 @@
def fuse_deconv_and_bn(deconv, bn):
+ """Fuse ConvTranspose2d and BatchNorm2d layers for inference optimization.
+
+ Args:
+ deconv (nn.ConvTranspose2d): Transposed convolutional layer to fuse.
+ bn (nn.BatchNorm2d): Batch normalization layer to fuse.
+
+ Returns:
+ (nn.ConvTranspose2d): The fused transposed convolutional layer with gradients disabled.
+
+ Examples:
+ >>> deconv = nn.ConvTranspose2d(16, 3, 3)
+ >>> bn = nn.BatchNorm2d(3)
+ >>> fused_deconv = fuse_deconv_and_bn(deconv, bn)
+ """
# Compute fused weights
w_deconv = deconv.weight.view(deconv.out_channels, -1)
w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
@@ -251,6 +332,21 @@
def model_info(model, detailed=False, verbose=True, imgsz=640):
+ """Print and return detailed model information layer by layer.
+
+ Args:
+ model (nn.Module): Model to analyze.
+ detailed (bool, optional): Whether to print detailed layer information.
+ verbose (bool, optional): Whether to print model information.
+ imgsz (int | list, optional): Input image size.
+
+ Returns:
+ (tuple): Tuple containing:
+ - n_l (int): Number of layers.
+ - n_p (int): Number of parameters.
+ - n_g (int): Number of gradients.
+ - flops (float): GFLOPs.
+ """
if not verbose:
return
n_p = get_num_params(model) # number of parameters
@@ -281,14 +377,34 @@
def get_num_params(model):
+ """Return the total number of parameters in a YOLO model."""
return sum(x.numel() for x in model.parameters())
def get_num_gradients(model):
+ """Return the total number of parameters with gradients in a YOLO model."""
return sum(x.numel() for x in model.parameters() if x.requires_grad)
def model_info_for_loggers(trainer):
+ """Return model info dict with useful model information.
+
+ Args:
+ trainer (ultralytics.engine.trainer.BaseTrainer): The trainer object containing model and validation data.
+
+ Returns:
+ (dict): Dictionary containing model parameters, GFLOPs, and inference speeds.
+
+ Examples:
+ YOLOv8n info for loggers
+ >>> results = {
+ ... "model/parameters": 3151904,
+ ... "model/GFLOPs": 8.746,
+ ... "model/speed_ONNX(ms)": 41.244,
+ ... "model/speed_TensorRT(ms)": 3.211,
+ ... "model/speed_PyTorch(ms)": 18.755,
+ ...}
+ """
if trainer.args.profile: # profile ONNX and TensorRT times
from ultralytics.utils.benchmarks import ProfileModels
@@ -304,6 +420,18 @@
def get_flops(model, imgsz=640):
+ """Calculate FLOPs (floating point operations) for a model in GFLOPs.
+
+ Attempts two calculation methods: first with a stride-based tensor for efficiency, then falls back to full image
+ size if needed (e.g., for RTDETR models). Returns 0.0 if thop library is unavailable or calculation fails.
+
+ Args:
+ model (nn.Module): The model to calculate FLOPs for.
+ imgsz (int | list, optional): Input image size.
+
+ Returns:
+ (float): The model's GFLOPs (billions of floating point operations).
+ """
try:
import thop
except ImportError:
@@ -332,6 +460,15 @@
def get_flops_with_torch_profiler(model, imgsz=640):
+ """Compute model FLOPs using torch profiler (alternative to thop package, but 2-10x slower).
+
+ Args:
+ model (nn.Module): The model to calculate FLOPs for.
+ imgsz (int | list, optional): Input image size.
+
+ Returns:
+ (float): The model's GFLOPs (billions of floating point operations).
+ """
if not TORCH_2_0: # torch profiler implemented in torch>=2.0
return 0.0
model = unwrap_model(model)
@@ -356,6 +493,7 @@
def initialize_weights(model):
+ """Initialize model weights, biases, and module settings to default values."""
for m in model.modules():
t = type(m)
if t is nn.Conv2d:
@@ -368,6 +506,17 @@
def scale_img(img, ratio=1.0, same_shape=False, gs=32):
+ """Scale and pad an image tensor, optionally maintaining aspect ratio and padding to gs multiple.
+
+ Args:
+ img (torch.Tensor): Input image tensor.
+ ratio (float, optional): Scaling ratio.
+ same_shape (bool, optional): Whether to maintain the same shape.
+ gs (int, optional): Grid size for padding.
+
+ Returns:
+ (torch.Tensor): Scaled and padded image tensor.
+ """
if ratio == 1.0:
return img
h, w = img.shape[2:]
@@ -379,6 +528,14 @@
def copy_attr(a, b, include=(), exclude=()):
+ """Copy attributes from object 'b' to object 'a', with options to include/exclude certain attributes.
+
+ Args:
+ a (Any): Destination object to copy attributes to.
+ b (Any): Source object to copy attributes from.
+ include (tuple, optional): Attributes to include. If empty, all attributes are included.
+ exclude (tuple, optional): Attributes to exclude.
+ """
for k, v in b.__dict__.items():
if (len(include) and k not in include) or k.startswith("_") or k in exclude:
continue
@@ -387,14 +544,41 @@
def intersect_dicts(da, db, exclude=()):
+ """Return a dictionary of intersecting keys with matching shapes, excluding 'exclude' keys, using da values.
+
+ Args:
+ da (dict): First dictionary.
+ db (dict): Second dictionary.
+ exclude (tuple, optional): Keys to exclude.
+
+ Returns:
+ (dict): Dictionary of intersecting keys with matching shapes.
+ """
return {k: v for k, v in da.items() if k in db and all(x not in k for x in exclude) and v.shape == db[k].shape}
def is_parallel(model):
+ """Return True if model is of type DP or DDP.
+
+ Args:
+ model (nn.Module): Model to check.
+
+ Returns:
+ (bool): True if model is DataParallel or DistributedDataParallel.
+ """
return isinstance(model, (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel))
def unwrap_model(m: nn.Module) -> nn.Module:
+ """Unwrap compiled and parallel models to get the base model.
+
+ Args:
+ m (nn.Module): A model that may be wrapped by torch.compile (._orig_mod) or parallel wrappers such as
+ DataParallel/DistributedDataParallel (.module).
+
+ Returns:
+ (nn.Module): The unwrapped base model without compile or parallel wrappers.
+ """
while True:
if hasattr(m, "_orig_mod") and isinstance(m._orig_mod, nn.Module):
m = m._orig_mod
@@ -405,10 +589,26 @@
def one_cycle(y1=0.0, y2=1.0, steps=100):
+ """Return a lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf.
+
+ Args:
+ y1 (float, optional): Initial value.
+ y2 (float, optional): Final value.
+ steps (int, optional): Number of steps.
+
+ Returns:
+ (function): Lambda function for computing the sinusoidal ramp.
+ """
return lambda x: max((1 - math.cos(x * math.pi / steps)) / 2, 0) * (y2 - y1) + y1
def init_seeds(seed=0, deterministic=False):
+ """Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html.
+
+ Args:
+ seed (int, optional): Random seed.
+ deterministic (bool, optional): Whether to set deterministic algorithms.
+ """
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
@@ -428,6 +628,7 @@
def unset_deterministic():
+ """Unset all the configurations applied for deterministic training."""
torch.use_deterministic_algorithms(False)
torch.backends.cudnn.deterministic = False
os.environ.pop("CUBLAS_WORKSPACE_CONFIG", None)
@@ -435,8 +636,33 @@
class ModelEMA:
+ """Updated Exponential Moving Average (EMA) implementation.
+
+ Keeps a moving average of everything in the model state_dict (parameters and buffers). For EMA details see
+ References.
+
+ To disable EMA set the `enabled` attribute to `False`.
+
+ Attributes:
+ ema (nn.Module): Copy of the model in evaluation mode.
+ updates (int): Number of EMA updates.
+ decay (function): Decay function that determines the EMA weight.
+ enabled (bool): Whether EMA is enabled.
+
+ References:
+ - https://github.com/rwightman/pytorch-image-models
+ - https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
+ """
def __init__(self, model, decay=0.9999, tau=2000, updates=0):
+ """Initialize EMA for 'model' with given arguments.
+
+ Args:
+ model (nn.Module): Model to create EMA for.
+ decay (float, optional): Maximum EMA decay rate.
+ tau (int, optional): EMA decay time constant.
+ updates (int, optional): Initial number of updates.
+ """
self.ema = deepcopy(unwrap_model(model)).eval() # FP32 EMA
self.updates = updates # number of EMA updates
self.decay = lambda x: decay * (1 - math.exp(-x / tau)) # decay exponential ramp (to help early epochs)
@@ -445,6 +671,11 @@ self.enabled = True
def update(self, model):
+ """Update EMA parameters.
+
+ Args:
+ model (nn.Module): Model to update EMA from.
+ """
if self.enabled:
self.updates += 1
d = self.decay(self.updates)
@@ -457,11 +688,35 @@ # assert v.dtype == msd[k].dtype == torch.float32, f'{k}: EMA {v.dtype}, model {msd[k].dtype}'
def update_attr(self, model, include=(), exclude=("process_group", "reducer")):
+ """Copy attributes from model to EMA, with options to include/exclude certain attributes.
+
+ Args:
+ model (nn.Module): Model to copy attributes from.
+ include (tuple, optional): Attributes to include.
+ exclude (tuple, optional): Attributes to exclude.
+ """
if self.enabled:
copy_attr(self.ema, model, include, exclude)
def strip_optimizer(f: str | Path = "best.pt", s: str = "", updates: dict[str, Any] | None = None) -> dict[str, Any]:
+ """Strip optimizer from 'f' to finalize training, optionally save as 's'.
+
+ Args:
+ f (str | Path): File path to model to strip the optimizer from.
+ s (str, optional): File path to save the model with stripped optimizer to. If not provided, 'f' will be
+ overwritten.
+ updates (dict, optional): A dictionary of updates to overlay onto the checkpoint before saving.
+
+ Returns:
+ (dict): The combined checkpoint dictionary.
+
+ Examples:
+ >>> from pathlib import Path
+ >>> from ultralytics.utils.torch_utils import strip_optimizer
+ >>> for f in Path("path/to/model/checkpoints").rglob("*.pt"):
+ ... strip_optimizer(f)
+ """
try:
x = torch_load(f, map_location=torch.device("cpu"))
assert isinstance(x, dict), "checkpoint is not a Python dictionary"
@@ -505,6 +760,14 @@
def convert_optimizer_state_dict_to_fp16(state_dict):
+ """Convert the state_dict of a given optimizer to FP16, focusing on the 'state' key for tensor conversions.
+
+ Args:
+ state_dict (dict): Optimizer state dictionary.
+
+ Returns:
+ (dict): Converted optimizer state dictionary with FP16 tensors.
+ """
for state in state_dict["state"].values():
for k, v in state.items():
if k != "step" and isinstance(v, torch.Tensor) and v.dtype is torch.float32:
@@ -515,6 +778,18 @@
@contextmanager
def cuda_memory_usage(device=None):
+ """Monitor and manage CUDA memory usage.
+
+ This function checks if CUDA is available and, if so, empties the CUDA cache to free up unused memory. It then
+ yields a dictionary containing memory usage information, which can be updated by the caller. Finally, it updates the
+ dictionary with the amount of memory reserved by CUDA on the specified device.
+
+ Args:
+ device (torch.device, optional): The CUDA device to query memory usage for.
+
+ Yields:
+ (dict): A dictionary with a key 'memory' initialized to 0, which will be updated with the reserved memory.
+ """
cuda_info = dict(memory=0)
if torch.cuda.is_available():
torch.cuda.empty_cache()
@@ -527,6 +802,25 @@
def profile_ops(input, ops, n=10, device=None, max_num_obj=0):
+ """Ultralytics speed, memory and FLOPs profiler.
+
+ Args:
+ input (torch.Tensor | list): Input tensor(s) to profile.
+ ops (nn.Module | list): Model or list of operations to profile.
+ n (int, optional): Number of iterations to average.
+ device (str | torch.device, optional): Device to profile on.
+ max_num_obj (int, optional): Maximum number of objects for simulation.
+
+ Returns:
+ (list): Profile results for each operation.
+
+ Examples:
+ >>> from ultralytics.utils.torch_utils import profile_ops
+ >>> input = torch.randn(16, 3, 640, 640)
+ >>> m1 = lambda x: x * torch.sigmoid(x)
+ >>> m2 = nn.SiLU()
+ >>> profile_ops(input, [m1, m2], n=100) # profile over 100 iterations
+ """
try:
import thop
except ImportError:
@@ -593,14 +887,36 @@
class EarlyStopping:
+ """Early stopping class that stops training when a specified number of epochs have passed without improvement.
+
+ Attributes:
+ best_fitness (float): Best fitness value observed.
+ best_epoch (int): Epoch where best fitness was observed.
+ patience (int): Number of epochs to wait after fitness stops improving before stopping.
+ possible_stop (bool): Flag indicating if stopping may occur next epoch.
+ """
def __init__(self, patience=50):
+ """Initialize early stopping object.
+
+ Args:
+ patience (int, optional): Number of epochs to wait after fitness stops improving before stopping.
+ """
self.best_fitness = 0.0 # i.e. mAP
self.best_epoch = 0
self.patience = patience or float("inf") # epochs to wait after fitness stops improving to stop
self.possible_stop = False # possible stop may occur next epoch
def __call__(self, epoch, fitness):
+ """Check whether to stop training.
+
+ Args:
+ epoch (int): Current epoch of training.
+ fitness (float): Fitness value of current epoch.
+
+ Returns:
+ (bool): True if training should stop, False otherwise.
+ """
if fitness is None: # check if fitness=None (happens when val=False)
return False
@@ -629,6 +945,34 @@ warmup: bool = False,
mode: bool | str = "default",
) -> torch.nn.Module:
+ """Compile a model with torch.compile and optionally warm up the graph to reduce first-iteration latency.
+
+ This utility attempts to compile the provided model using the inductor backend. If compilation is unavailable or
+ fails, the original model is returned unchanged. An optional warmup performs a single forward pass on a dummy input
+ to prime the compiled graph and measure compile/warmup time.
+
+ Args:
+ model (torch.nn.Module): Model to compile.
+ device (torch.device): Inference device used for warmup and autocast decisions.
+ imgsz (int, optional): Square input size to create a dummy tensor with shape (1, 3, imgsz, imgsz) for warmup.
+ use_autocast (bool, optional): Whether to run warmup under autocast on CUDA or MPS devices.
+ warmup (bool, optional): Whether to execute a single dummy forward pass to warm up the compiled model.
+ mode (bool | str, optional): torch.compile mode. True → "default", False → no compile, or a string like
+ "default", "reduce-overhead", "max-autotune-no-cudagraphs".
+
+ Returns:
+ (torch.nn.Module): Compiled model if compilation succeeds, otherwise the original unmodified model.
+
+ Examples:
+ >>> device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
+ >>> # Try to compile and warm up a model with a 640x640 input
+ >>> model = attempt_compile(model, device=device, imgsz=640, use_autocast=True, warmup=True)
+
+ Notes:
+ - If the current PyTorch build does not provide torch.compile, the function returns the input model immediately.
+ - Warmup runs under torch.inference_mode and may use torch.autocast for CUDA/MPS to align compute precision.
+ - CUDA devices are synchronized after warmup to account for asynchronous kernel execution.
+ """
if not hasattr(torch, "compile") or not mode:
return model
@@ -669,4 +1013,4 @@ LOGGER.info(f"{prefix} complete in {total:.1f}s (compile {t_compile:.1f}s + warmup {t_warm:.1f}s)")
else:
LOGGER.info(f"{prefix} compile complete in {t_compile:.1f}s (no warmup)")
- return model+ return model
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/torch_utils.py |
Document helper functions with docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import os
import shutil
import sys
import tempfile
from typing import TYPE_CHECKING
from . import USER_CONFIG_DIR
from .torch_utils import TORCH_1_9
if TYPE_CHECKING:
from ultralytics.engine.trainer import BaseTrainer
def find_free_network_port() -> int:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1] # port
def generate_ddp_file(trainer: BaseTrainer) -> str:
module, name = f"{trainer.__class__.__module__}.{trainer.__class__.__name__}".rsplit(".", 1)
# Serialize augmentations to JSON-safe dicts to avoid NameError in DDP subprocess
overrides = vars(trainer.args).copy()
if overrides.get("augmentations") is not None:
import albumentations as A
overrides["augmentations"] = [A.to_dict(t) for t in overrides["augmentations"]]
content = f"""
# Ultralytics Multi-GPU training temp file (should be automatically deleted after use)
from pathlib import Path, PosixPath # For model arguments stored as Path instead of str
overrides = {overrides}
if __name__ == "__main__":
from {module} import {name}
from ultralytics.utils import DEFAULT_CFG_DICT
# Deserialize augmentations from dicts back to Albumentations transform objects
if overrides.get("augmentations") is not None:
import albumentations as A
overrides["augmentations"] = [A.from_dict(t) for t in overrides["augmentations"]]
cfg = DEFAULT_CFG_DICT.copy()
cfg.update(save_dir='') # handle the extra key 'save_dir'
trainer = {name}(cfg=cfg, overrides=overrides)
trainer.args.model = "{getattr(trainer.hub_session, "model_url", trainer.args.model)}"
results = trainer.train()
"""
(USER_CONFIG_DIR / "DDP").mkdir(exist_ok=True)
with tempfile.NamedTemporaryFile(
prefix="_temp_",
suffix=f"{id(trainer)}.py",
mode="w+",
encoding="utf-8",
dir=USER_CONFIG_DIR / "DDP",
delete=False,
) as file:
file.write(content)
return file.name
def generate_ddp_command(trainer: BaseTrainer) -> tuple[list[str], str]:
import __main__ # noqa local import to avoid https://github.com/Lightning-AI/pytorch-lightning/issues/15218
if not trainer.resume:
shutil.rmtree(trainer.save_dir) # remove the save_dir
file = generate_ddp_file(trainer)
dist_cmd = "torch.distributed.run" if TORCH_1_9 else "torch.distributed.launch"
port = find_free_network_port()
cmd = [
sys.executable,
"-m",
dist_cmd,
"--nproc_per_node",
f"{trainer.world_size}",
"--master_port",
f"{port}",
file,
]
return cmd, file
def ddp_cleanup(trainer: BaseTrainer, file: str) -> None:
if f"{id(trainer)}.py" in file: # if temp_file suffix in file
os.remove(file) | --- +++ @@ -16,6 +16,14 @@
def find_free_network_port() -> int:
+ """Find a free port on localhost.
+
+ It is useful in single-node training when we don't want to connect to a real main node but have to set the
+ `MASTER_PORT` environment variable.
+
+ Returns:
+ (int): The available network port number.
+ """
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
@@ -24,6 +32,25 @@
def generate_ddp_file(trainer: BaseTrainer) -> str:
+ """Generate a DDP (Distributed Data Parallel) file for multi-GPU training.
+
+ This function creates a temporary Python file that enables distributed training across multiple GPUs. The file
+ contains the necessary configuration to initialize the trainer in a distributed environment.
+
+ Args:
+ trainer (ultralytics.engine.trainer.BaseTrainer): The trainer containing training configuration and arguments.
+ Must have args attribute and be a class instance.
+
+ Returns:
+ (str): Path to the generated temporary DDP file.
+
+ Notes:
+ The generated file is saved in the USER_CONFIG_DIR/DDP directory and includes:
+ - Trainer class import
+ - Configuration overrides from the trainer arguments
+ - Model path configuration
+ - Training initialization code
+ """
module, name = f"{trainer.__class__.__module__}.{trainer.__class__.__name__}".rsplit(".", 1)
# Serialize augmentations to JSON-safe dicts to avoid NameError in DDP subprocess
@@ -67,6 +94,15 @@
def generate_ddp_command(trainer: BaseTrainer) -> tuple[list[str], str]:
+ """Generate command for distributed training.
+
+ Args:
+ trainer (ultralytics.engine.trainer.BaseTrainer): The trainer containing configuration for distributed training.
+
+ Returns:
+ cmd (list[str]): The command to execute for distributed training.
+ file (str): Path to the temporary file created for DDP training.
+ """
import __main__ # noqa local import to avoid https://github.com/Lightning-AI/pytorch-lightning/issues/15218
if not trainer.resume:
@@ -88,5 +124,19 @@
def ddp_cleanup(trainer: BaseTrainer, file: str) -> None:
+ """Delete temporary file if created during distributed data parallel (DDP) training.
+
+ This function checks if the provided file contains the trainer's ID in its name, indicating it was created as a
+ temporary file for DDP training, and deletes it if so.
+
+ Args:
+ trainer (ultralytics.engine.trainer.BaseTrainer): The trainer used for distributed training.
+ file (str): Path to the file that might need to be deleted.
+
+ Examples:
+ >>> trainer = YOLOTrainer()
+ >>> file = "/tmp/ddp_temp_123456789.py"
+ >>> ddp_cleanup(trainer, file)
+ """
if f"{id(trainer)}.py" in file: # if temp_file suffix in file
- os.remove(file)+ os.remove(file)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/dist.py |
Generate consistent documentation across files | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import contextlib
import math
import re
import time
import cv2
import numpy as np
import torch
import torch.nn.functional as F
from ultralytics.utils import NOT_MACOS14
class Profile(contextlib.ContextDecorator):
def __init__(self, t: float = 0.0, device: torch.device | None = None):
self.t = t
self.device = device
self.cuda = bool(device and str(device).startswith("cuda"))
def __enter__(self):
self.start = self.time()
return self
def __exit__(self, type, value, traceback):
self.dt = self.time() - self.start # delta-time
self.t += self.dt # accumulate dt
def __str__(self):
return f"Elapsed time is {self.t} s"
def time(self):
if self.cuda:
torch.cuda.synchronize(self.device)
return time.perf_counter()
def segment2box(segment, width: int = 640, height: int = 640):
x, y = segment.T # segment xy
# Clip coordinates if 3 out of 4 sides are outside the image
if np.array([x.min() < 0, y.min() < 0, x.max() > width, y.max() > height]).sum() >= 3:
x = x.clip(0, width)
y = y.clip(0, height)
inside = (x > 0) & (y > 0) & (x < width) & (y < height)
x = x[inside]
y = y[inside]
return (
np.array([x.min(), y.min(), x.max(), y.max()], dtype=segment.dtype)
if any(x)
else np.zeros(4, dtype=segment.dtype)
) # xyxy
def scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None, padding: bool = True, xywh: bool = False):
if ratio_pad is None: # calculate from img0_shape
gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
pad_x = round((img1_shape[1] - img0_shape[1] * gain) / 2 - 0.1)
pad_y = round((img1_shape[0] - img0_shape[0] * gain) / 2 - 0.1)
else:
gain = ratio_pad[0][0]
pad_x, pad_y = ratio_pad[1]
if padding:
boxes[..., 0] -= pad_x # x padding
boxes[..., 1] -= pad_y # y padding
if not xywh:
boxes[..., 2] -= pad_x # x padding
boxes[..., 3] -= pad_y # y padding
boxes[..., :4] /= gain
return boxes if xywh else clip_boxes(boxes, img0_shape)
def make_divisible(x: int, divisor):
if isinstance(divisor, torch.Tensor):
divisor = int(divisor.max()) # to int
return math.ceil(x / divisor) * divisor
def clip_boxes(boxes, shape):
h, w = shape[:2] # supports both HWC or HW shapes
if isinstance(boxes, torch.Tensor): # faster individually
if NOT_MACOS14:
boxes[..., 0].clamp_(0, w) # x1
boxes[..., 1].clamp_(0, h) # y1
boxes[..., 2].clamp_(0, w) # x2
boxes[..., 3].clamp_(0, h) # y2
else: # Apple macOS14 MPS bug https://github.com/ultralytics/ultralytics/pull/21878
boxes[..., 0] = boxes[..., 0].clamp(0, w)
boxes[..., 1] = boxes[..., 1].clamp(0, h)
boxes[..., 2] = boxes[..., 2].clamp(0, w)
boxes[..., 3] = boxes[..., 3].clamp(0, h)
else: # np.array (faster grouped)
boxes[..., [0, 2]] = boxes[..., [0, 2]].clip(0, w) # x1, x2
boxes[..., [1, 3]] = boxes[..., [1, 3]].clip(0, h) # y1, y2
return boxes
def clip_coords(coords, shape):
h, w = shape[:2] # supports both HWC or HW shapes
if isinstance(coords, torch.Tensor):
if NOT_MACOS14:
coords[..., 0].clamp_(0, w) # x
coords[..., 1].clamp_(0, h) # y
else: # Apple macOS14 MPS bug https://github.com/ultralytics/ultralytics/pull/21878
coords[..., 0] = coords[..., 0].clamp(0, w)
coords[..., 1] = coords[..., 1].clamp(0, h)
else: # np.array
coords[..., 0] = coords[..., 0].clip(0, w) # x
coords[..., 1] = coords[..., 1].clip(0, h) # y
return coords
def xyxy2xywh(x):
assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}"
y = empty_like(x) # faster than clone/copy
x1, y1, x2, y2 = x[..., 0], x[..., 1], x[..., 2], x[..., 3]
y[..., 0] = (x1 + x2) / 2 # x center
y[..., 1] = (y1 + y2) / 2 # y center
y[..., 2] = x2 - x1 # width
y[..., 3] = y2 - y1 # height
return y
def xywh2xyxy(x):
assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}"
y = empty_like(x) # faster than clone/copy
xy = x[..., :2] # centers
wh = x[..., 2:] / 2 # half width-height
y[..., :2] = xy - wh # top left xy
y[..., 2:] = xy + wh # bottom right xy
return y
def xywhn2xyxy(x, w: int = 640, h: int = 640, padw: int = 0, padh: int = 0):
assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}"
y = empty_like(x) # faster than clone/copy
xc, yc, xw, xh = x[..., 0], x[..., 1], x[..., 2], x[..., 3]
half_w, half_h = xw / 2, xh / 2
y[..., 0] = w * (xc - half_w) + padw # top left x
y[..., 1] = h * (yc - half_h) + padh # top left y
y[..., 2] = w * (xc + half_w) + padw # bottom right x
y[..., 3] = h * (yc + half_h) + padh # bottom right y
return y
def xyxy2xywhn(x, w: int = 640, h: int = 640, clip: bool = False, eps: float = 0.0):
if clip:
x = clip_boxes(x, (h - eps, w - eps))
assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}"
y = empty_like(x) # faster than clone/copy
x1, y1, x2, y2 = x[..., 0], x[..., 1], x[..., 2], x[..., 3]
y[..., 0] = ((x1 + x2) / 2) / w # x center
y[..., 1] = ((y1 + y2) / 2) / h # y center
y[..., 2] = (x2 - x1) / w # width
y[..., 3] = (y2 - y1) / h # height
return y
def xywh2ltwh(x):
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[..., 0] = x[..., 0] - x[..., 2] / 2 # top left x
y[..., 1] = x[..., 1] - x[..., 3] / 2 # top left y
return y
def xyxy2ltwh(x):
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[..., 2] = x[..., 2] - x[..., 0] # width
y[..., 3] = x[..., 3] - x[..., 1] # height
return y
def ltwh2xywh(x):
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[..., 0] = x[..., 0] + x[..., 2] / 2 # center x
y[..., 1] = x[..., 1] + x[..., 3] / 2 # center y
return y
def xyxyxyxy2xywhr(x):
is_torch = isinstance(x, torch.Tensor)
points = x.cpu().numpy() if is_torch else x
points = points.reshape(len(x), -1, 2)
rboxes = []
for pts in points:
# NOTE: Use cv2.minAreaRect to get accurate xywhr,
# especially some objects are cut off by augmentations in dataloader.
(cx, cy), (w, h), angle = cv2.minAreaRect(pts)
# convert angle to radian and normalize to [-pi/4, 3pi/4)
theta = angle / 180 * np.pi
if w < h:
w, h = h, w
theta += np.pi / 2
while theta >= 3 * np.pi / 4:
theta -= np.pi
while theta < -np.pi / 4:
theta += np.pi
rboxes.append([cx, cy, w, h, theta])
return torch.tensor(rboxes, device=x.device, dtype=x.dtype) if is_torch else np.asarray(rboxes)
def xywhr2xyxyxyxy(x):
cos, sin, cat, stack = (
(torch.cos, torch.sin, torch.cat, torch.stack)
if isinstance(x, torch.Tensor)
else (np.cos, np.sin, np.concatenate, np.stack)
)
ctr = x[..., :2]
w, h, angle = (x[..., i : i + 1] for i in range(2, 5))
cos_value, sin_value = cos(angle), sin(angle)
vec1 = [w / 2 * cos_value, w / 2 * sin_value]
vec2 = [-h / 2 * sin_value, h / 2 * cos_value]
vec1 = cat(vec1, -1)
vec2 = cat(vec2, -1)
pt1 = ctr + vec1 + vec2
pt2 = ctr + vec1 - vec2
pt3 = ctr - vec1 - vec2
pt4 = ctr - vec1 + vec2
return stack([pt1, pt2, pt3, pt4], -2)
def ltwh2xyxy(x):
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[..., 2] = x[..., 2] + x[..., 0] # x2
y[..., 3] = x[..., 3] + x[..., 1] # y2
return y
def segments2boxes(segments):
boxes = []
for s in segments:
x, y = s.T # segment xy
boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy
return xyxy2xywh(np.array(boxes)) # cls, xywh
def resample_segments(segments, n: int = 1000):
for i, s in enumerate(segments):
if len(s) == n:
continue
s = np.concatenate((s, s[0:1, :]), axis=0)
x = np.linspace(0, len(s) - 1, n - len(s) if len(s) < n else n)
xp = np.arange(len(s))
x = np.insert(x, np.searchsorted(x, xp), xp) if len(s) < n else x
segments[i] = (
np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)], dtype=np.float32).reshape(2, -1).T
) # segment xy
return segments
def crop_mask(masks: torch.Tensor, boxes: torch.Tensor) -> torch.Tensor:
if boxes.device != masks.device:
boxes = boxes.to(masks.device)
n, h, w = masks.shape
if n < 50 and not masks.is_cuda: # faster for fewer masks (predict)
for i, (x1, y1, x2, y2) in enumerate(boxes.round().int()):
masks[i, :y1] = 0
masks[i, y2:] = 0
masks[i, :, :x1] = 0
masks[i, :, x2:] = 0
return masks
else: # faster for more masks (val)
x1, y1, x2, y2 = torch.chunk(boxes[:, :, None], 4, 1) # x1 shape(n,1,1)
r = torch.arange(w, device=masks.device, dtype=x1.dtype)[None, None, :] # rows shape(1,1,w)
c = torch.arange(h, device=masks.device, dtype=x1.dtype)[None, :, None] # cols shape(1,h,1)
return masks * ((r >= x1) * (r < x2) * (c >= y1) * (c < y2))
def process_mask(protos, masks_in, bboxes, shape, upsample: bool = False):
c, mh, mw = protos.shape # CHW
masks = (masks_in @ protos.float().view(c, -1)).view(-1, mh, mw) # NHW
width_ratio = mw / shape[1]
height_ratio = mh / shape[0]
ratios = torch.tensor([[width_ratio, height_ratio, width_ratio, height_ratio]], device=bboxes.device)
masks = crop_mask(masks, boxes=bboxes * ratios) # NHW
if upsample:
masks = F.interpolate(masks[None], shape, mode="bilinear")[0] # NHW
return masks.gt_(0.0).byte()
def process_mask_native(protos, masks_in, bboxes, shape):
c, mh, mw = protos.shape # CHW
masks = (masks_in @ protos.float().view(c, -1)).view(-1, mh, mw)
masks = scale_masks(masks[None], shape)[0] # NHW
masks = crop_mask(masks, bboxes) # NHW
return masks.gt_(0.0).byte()
def scale_masks(
masks: torch.Tensor,
shape: tuple[int, int],
ratio_pad: tuple[tuple[int, int], tuple[int, int]] | None = None,
padding: bool = True,
) -> torch.Tensor:
im1_h, im1_w = masks.shape[2:]
im0_h, im0_w = shape[:2]
if im1_h == im0_h and im1_w == im0_w:
return masks
if ratio_pad is None: # calculate from im0_shape
gain = min(im1_h / im0_h, im1_w / im0_w) # gain = old / new
pad_w, pad_h = (im1_w - im0_w * gain), (im1_h - im0_h * gain) # wh padding
if padding:
pad_w /= 2
pad_h /= 2
else:
pad_w, pad_h = ratio_pad[1]
top, left = (round(pad_h - 0.1), round(pad_w - 0.1)) if padding else (0, 0)
bottom = im1_h - round(pad_h + 0.1)
right = im1_w - round(pad_w + 0.1)
return F.interpolate(masks[..., top:bottom, left:right].float(), shape, mode="bilinear") # NCHW masks
def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None, normalize: bool = False, padding: bool = True):
img0_h, img0_w = img0_shape[:2] # supports both HWC or HW shapes
if ratio_pad is None: # calculate from img0_shape
img1_h, img1_w = img1_shape[:2] # supports both HWC or HW shapes
gain = min(img1_h / img0_h, img1_w / img0_w) # gain = old / new
pad = (img1_w - img0_w * gain) / 2, (img1_h - img0_h * gain) / 2 # wh padding
else:
gain = ratio_pad[0][0]
pad = ratio_pad[1]
if padding:
coords[..., 0] -= pad[0] # x padding
coords[..., 1] -= pad[1] # y padding
coords[..., 0] /= gain
coords[..., 1] /= gain
coords = clip_coords(coords, img0_shape)
if normalize:
coords[..., 0] /= img0_w # width
coords[..., 1] /= img0_h # height
return coords
def regularize_rboxes(rboxes):
x, y, w, h, t = rboxes.unbind(dim=-1)
# Swap edge if t >= pi/2 while not being symmetrically opposite
swap = t % math.pi >= math.pi / 2
w_ = torch.where(swap, h, w)
h_ = torch.where(swap, w, h)
t = t % (math.pi / 2)
return torch.stack([x, y, w_, h_, t], dim=-1) # regularized boxes
def masks2segments(masks: np.ndarray | torch.Tensor, strategy: str = "all") -> list[np.ndarray]:
from ultralytics.data.converter import merge_multi_segment
masks = masks.astype("uint8") if isinstance(masks, np.ndarray) else masks.byte().cpu().numpy()
segments = []
for x in np.ascontiguousarray(masks):
c = cv2.findContours(x, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
if c:
if strategy == "all": # merge and concatenate all segments
c = (
np.concatenate(merge_multi_segment([x.reshape(-1, 2) for x in c]))
if len(c) > 1
else c[0].reshape(-1, 2)
)
elif strategy == "largest": # select largest segment
c = np.array(c[np.array([len(x) for x in c]).argmax()]).reshape(-1, 2)
else:
c = np.zeros((0, 2)) # no segments found
segments.append(c.astype("float32"))
return segments
def convert_torch2numpy_batch(batch: torch.Tensor) -> np.ndarray:
return (batch.permute(0, 2, 3, 1).contiguous() * 255).clamp(0, 255).byte().cpu().numpy()
def clean_str(s):
return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨`><+]", repl="_", string=s)
def empty_like(x):
return torch.empty_like(x, dtype=x.dtype) if isinstance(x, torch.Tensor) else np.empty_like(x, dtype=x.dtype) | --- +++ @@ -16,30 +16,74 @@
class Profile(contextlib.ContextDecorator):
+ """Ultralytics Profile class for timing code execution.
+
+ Use as a decorator with @Profile() or as a context manager with 'with Profile():'. Provides accurate timing
+ measurements with CUDA synchronization support for GPU operations.
+
+ Attributes:
+ t (float): Accumulated time in seconds.
+ device (torch.device): Device used for model inference.
+ cuda (bool): Whether CUDA is being used for timing synchronization.
+
+ Examples:
+ Use as a context manager to time code execution
+ >>> with Profile(device=device) as dt:
+ ... pass # slow operation here
+ >>> print(dt) # prints "Elapsed time is 9.5367431640625e-07 s"
+
+ Use as a decorator to time function execution
+ >>> @Profile()
+ ... def slow_function():
+ ... time.sleep(0.1)
+ """
def __init__(self, t: float = 0.0, device: torch.device | None = None):
+ """Initialize the Profile class.
+
+ Args:
+ t (float): Initial accumulated time in seconds.
+ device (torch.device, optional): Device used for model inference to enable CUDA synchronization.
+ """
self.t = t
self.device = device
self.cuda = bool(device and str(device).startswith("cuda"))
def __enter__(self):
+ """Start timing."""
self.start = self.time()
return self
def __exit__(self, type, value, traceback):
+ """Stop timing."""
self.dt = self.time() - self.start # delta-time
self.t += self.dt # accumulate dt
def __str__(self):
+ """Return a human-readable string representing the accumulated elapsed time."""
return f"Elapsed time is {self.t} s"
def time(self):
+ """Get current time with CUDA synchronization if applicable."""
if self.cuda:
torch.cuda.synchronize(self.device)
return time.perf_counter()
def segment2box(segment, width: int = 640, height: int = 640):
+ """Convert segment coordinates to bounding box coordinates.
+
+ Converts a single segment label to a box label by finding the minimum and maximum x and y coordinates. Applies
+ inside-image constraint and clips coordinates when necessary.
+
+ Args:
+ segment (np.ndarray): Segment coordinates in format (N, 2) where N is number of points.
+ width (int): Width of the image in pixels.
+ height (int): Height of the image in pixels.
+
+ Returns:
+ (np.ndarray): Bounding box coordinates in xyxy format [x1, y1, x2, y2].
+ """
x, y = segment.T # segment xy
# Clip coordinates if 3 out of 4 sides are outside the image
if np.array([x.min() < 0, y.min() < 0, x.max() > width, y.max() > height]).sum() >= 3:
@@ -56,6 +100,22 @@
def scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None, padding: bool = True, xywh: bool = False):
+ """Rescale bounding boxes from one image shape to another.
+
+ Rescales bounding boxes from img1_shape to img0_shape, accounting for padding and aspect ratio changes. Supports
+ both xyxy and xywh box formats.
+
+ Args:
+ img1_shape (tuple): Shape of the source image (height, width).
+ boxes (torch.Tensor): Bounding boxes to rescale in format (N, 4).
+ img0_shape (tuple): Shape of the target image (height, width).
+ ratio_pad (tuple, optional): Tuple of (ratio, pad) for scaling. If None, calculated from image shapes.
+ padding (bool): Whether boxes are based on YOLO-style augmented images with padding.
+ xywh (bool): Whether box format is xywh (True) or xyxy (False).
+
+ Returns:
+ (torch.Tensor): Rescaled bounding boxes in the same format as input.
+ """
if ratio_pad is None: # calculate from img0_shape
gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
pad_x = round((img1_shape[1] - img0_shape[1] * gain) / 2 - 0.1)
@@ -75,12 +135,30 @@
def make_divisible(x: int, divisor):
+ """Return the nearest number that is divisible by the given divisor.
+
+ Args:
+ x (int): The number to make divisible.
+ divisor (int | torch.Tensor): The divisor.
+
+ Returns:
+ (int): The nearest number divisible by the divisor.
+ """
if isinstance(divisor, torch.Tensor):
divisor = int(divisor.max()) # to int
return math.ceil(x / divisor) * divisor
def clip_boxes(boxes, shape):
+ """Clip bounding boxes to image boundaries.
+
+ Args:
+ boxes (torch.Tensor | np.ndarray): Bounding boxes to clip.
+ shape (tuple): Image shape as HWC or HW (supports both).
+
+ Returns:
+ (torch.Tensor | np.ndarray): Clipped bounding boxes.
+ """
h, w = shape[:2] # supports both HWC or HW shapes
if isinstance(boxes, torch.Tensor): # faster individually
if NOT_MACOS14:
@@ -100,6 +178,15 @@
def clip_coords(coords, shape):
+ """Clip line coordinates to image boundaries.
+
+ Args:
+ coords (torch.Tensor | np.ndarray): Line coordinates to clip.
+ shape (tuple): Image shape as HWC or HW (supports both).
+
+ Returns:
+ (torch.Tensor | np.ndarray): Clipped coordinates.
+ """
h, w = shape[:2] # supports both HWC or HW shapes
if isinstance(coords, torch.Tensor):
if NOT_MACOS14:
@@ -115,6 +202,15 @@
def xyxy2xywh(x):
+ """Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height) format where (x1, y1) is
+ the top-left corner and (x2, y2) is the bottom-right corner.
+
+ Args:
+ x (np.ndarray | torch.Tensor): Input bounding box coordinates in (x1, y1, x2, y2) format.
+
+ Returns:
+ (np.ndarray | torch.Tensor): Bounding box coordinates in (x, y, width, height) format.
+ """
assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}"
y = empty_like(x) # faster than clone/copy
x1, y1, x2, y2 = x[..., 0], x[..., 1], x[..., 2], x[..., 3]
@@ -126,6 +222,15 @@
def xywh2xyxy(x):
+ """Convert bounding box coordinates from (x, y, width, height) format to (x1, y1, x2, y2) format where (x1, y1) is
+ the top-left corner and (x2, y2) is the bottom-right corner. Note: ops per 2 channels faster than per channel.
+
+ Args:
+ x (np.ndarray | torch.Tensor): Input bounding box coordinates in (x, y, width, height) format.
+
+ Returns:
+ (np.ndarray | torch.Tensor): Bounding box coordinates in (x1, y1, x2, y2) format.
+ """
assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}"
y = empty_like(x) # faster than clone/copy
xy = x[..., :2] # centers
@@ -136,6 +241,18 @@
def xywhn2xyxy(x, w: int = 640, h: int = 640, padw: int = 0, padh: int = 0):
+ """Convert normalized bounding box coordinates to pixel coordinates.
+
+ Args:
+ x (np.ndarray | torch.Tensor): Normalized bounding box coordinates in (x, y, w, h) format.
+ w (int): Image width in pixels.
+ h (int): Image height in pixels.
+ padw (int): Padding width in pixels.
+ padh (int): Padding height in pixels.
+
+ Returns:
+ (np.ndarray | torch.Tensor): Bounding box coordinates in (x1, y1, x2, y2) format.
+ """
assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}"
y = empty_like(x) # faster than clone/copy
xc, yc, xw, xh = x[..., 0], x[..., 1], x[..., 2], x[..., 3]
@@ -148,6 +265,19 @@
def xyxy2xywhn(x, w: int = 640, h: int = 640, clip: bool = False, eps: float = 0.0):
+ """Convert bounding box coordinates from (x1, y1, x2, y2) format to normalized (x, y, width, height) format. x, y,
+ width and height are normalized to image dimensions.
+
+ Args:
+ x (np.ndarray | torch.Tensor): Input bounding box coordinates in (x1, y1, x2, y2) format.
+ w (int): Image width in pixels.
+ h (int): Image height in pixels.
+ clip (bool): Whether to clip boxes to image boundaries.
+ eps (float): Minimum value for box width and height.
+
+ Returns:
+ (np.ndarray | torch.Tensor): Normalized bounding box coordinates in (x, y, width, height) format.
+ """
if clip:
x = clip_boxes(x, (h - eps, w - eps))
assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}"
@@ -161,6 +291,14 @@
def xywh2ltwh(x):
+ """Convert bounding box format from [x, y, w, h] to [x1, y1, w, h] where x1, y1 are top-left coordinates.
+
+ Args:
+ x (np.ndarray | torch.Tensor): Input bounding box coordinates in xywh format.
+
+ Returns:
+ (np.ndarray | torch.Tensor): Bounding box coordinates in ltwh format.
+ """
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[..., 0] = x[..., 0] - x[..., 2] / 2 # top left x
y[..., 1] = x[..., 1] - x[..., 3] / 2 # top left y
@@ -168,6 +306,14 @@
def xyxy2ltwh(x):
+ """Convert bounding boxes from [x1, y1, x2, y2] to [x1, y1, w, h] format.
+
+ Args:
+ x (np.ndarray | torch.Tensor): Input bounding box coordinates in xyxy format.
+
+ Returns:
+ (np.ndarray | torch.Tensor): Bounding box coordinates in ltwh format.
+ """
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[..., 2] = x[..., 2] - x[..., 0] # width
y[..., 3] = x[..., 3] - x[..., 1] # height
@@ -175,6 +321,14 @@
def ltwh2xywh(x):
+ """Convert bounding boxes from [x1, y1, w, h] to [x, y, w, h] where xy1=top-left, xy=center.
+
+ Args:
+ x (np.ndarray | torch.Tensor): Input bounding box coordinates.
+
+ Returns:
+ (np.ndarray | torch.Tensor): Bounding box coordinates in xywh format.
+ """
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[..., 0] = x[..., 0] + x[..., 2] / 2 # center x
y[..., 1] = x[..., 1] + x[..., 3] / 2 # center y
@@ -182,6 +336,15 @@
def xyxyxyxy2xywhr(x):
+ """Convert batched Oriented Bounding Boxes (OBB) from [xy1, xy2, xy3, xy4] to [xywh, rotation] format.
+
+ Args:
+ x (np.ndarray | torch.Tensor): Input box corners with shape (N, 8) in [xy1, xy2, xy3, xy4] format.
+
+ Returns:
+ (np.ndarray | torch.Tensor): Converted data in [cx, cy, w, h, rotation] format with shape (N, 5). Rotation
+ values are in radians from [-pi/4, 3pi/4).
+ """
is_torch = isinstance(x, torch.Tensor)
points = x.cpu().numpy() if is_torch else x
points = points.reshape(len(x), -1, 2)
@@ -204,6 +367,15 @@
def xywhr2xyxyxyxy(x):
+ """Convert batched Oriented Bounding Boxes (OBB) from [xywh, rotation] to [xy1, xy2, xy3, xy4] format.
+
+ Args:
+ x (np.ndarray | torch.Tensor): Boxes in [cx, cy, w, h, rotation] format with shape (N, 5) or (B, N, 5). Rotation
+ values should be in radians from [-pi/4, 3pi/4).
+
+ Returns:
+ (np.ndarray | torch.Tensor): Converted corner points with shape (N, 4, 2) or (B, N, 4, 2).
+ """
cos, sin, cat, stack = (
(torch.cos, torch.sin, torch.cat, torch.stack)
if isinstance(x, torch.Tensor)
@@ -225,6 +397,14 @@
def ltwh2xyxy(x):
+ """Convert bounding box from [x1, y1, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right.
+
+ Args:
+ x (np.ndarray | torch.Tensor): Input bounding box coordinates.
+
+ Returns:
+ (np.ndarray | torch.Tensor): Bounding box coordinates in xyxy format.
+ """
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[..., 2] = x[..., 2] + x[..., 0] # x2
y[..., 3] = x[..., 3] + x[..., 1] # y2
@@ -232,6 +412,14 @@
def segments2boxes(segments):
+ """Convert segment coordinates to bounding box labels in xywh format.
+
+ Args:
+ segments (list): List of segments where each segment is a list of points, each point is [x, y] coordinates.
+
+ Returns:
+ (np.ndarray): Bounding box coordinates in xywh format.
+ """
boxes = []
for s in segments:
x, y = s.T # segment xy
@@ -240,6 +428,15 @@
def resample_segments(segments, n: int = 1000):
+ """Resample segments to n points each using linear interpolation.
+
+ Args:
+ segments (list): List of (N, 2) arrays where N is the number of points in each segment.
+ n (int): Number of points to resample each segment to.
+
+ Returns:
+ (list): Resampled segments with n points each.
+ """
for i, s in enumerate(segments):
if len(s) == n:
continue
@@ -254,6 +451,15 @@
def crop_mask(masks: torch.Tensor, boxes: torch.Tensor) -> torch.Tensor:
+ """Crop masks to bounding box regions.
+
+ Args:
+ masks (torch.Tensor): Masks with shape (N, H, W).
+ boxes (torch.Tensor): Bounding box coordinates with shape (N, 4) in xyxy pixel format.
+
+ Returns:
+ (torch.Tensor): Cropped masks.
+ """
if boxes.device != masks.device:
boxes = boxes.to(masks.device)
n, h, w = masks.shape
@@ -272,6 +478,19 @@
def process_mask(protos, masks_in, bboxes, shape, upsample: bool = False):
+ """Apply masks to bounding boxes using mask head output.
+
+ Args:
+ protos (torch.Tensor): Mask prototypes with shape (mask_dim, mask_h, mask_w).
+ masks_in (torch.Tensor): Mask coefficients with shape (N, mask_dim) where N is number of masks after NMS.
+ bboxes (torch.Tensor): Bounding boxes with shape (N, 4) where N is number of masks after NMS.
+ shape (tuple): Input image size as (height, width).
+ upsample (bool): Whether to upsample masks to original image size.
+
+ Returns:
+ (torch.Tensor): A binary mask tensor of shape [n, h, w], where n is the number of masks after NMS, and h and w
+ are the height and width of the input image. The mask is applied to the bounding boxes.
+ """
c, mh, mw = protos.shape # CHW
masks = (masks_in @ protos.float().view(c, -1)).view(-1, mh, mw) # NHW
@@ -286,6 +505,17 @@
def process_mask_native(protos, masks_in, bboxes, shape):
+ """Apply masks to bounding boxes using mask head output with native upsampling.
+
+ Args:
+ protos (torch.Tensor): Mask prototypes with shape (mask_dim, mask_h, mask_w).
+ masks_in (torch.Tensor): Mask coefficients with shape (N, mask_dim) where N is number of masks after NMS.
+ bboxes (torch.Tensor): Bounding boxes with shape (N, 4) where N is number of masks after NMS.
+ shape (tuple): Input image size as (height, width).
+
+ Returns:
+ (torch.Tensor): Binary mask tensor with shape (N, H, W).
+ """
c, mh, mw = protos.shape # CHW
masks = (masks_in @ protos.float().view(c, -1)).view(-1, mh, mw)
masks = scale_masks(masks[None], shape)[0] # NHW
@@ -299,6 +529,17 @@ ratio_pad: tuple[tuple[int, int], tuple[int, int]] | None = None,
padding: bool = True,
) -> torch.Tensor:
+ """Rescale segment masks to target shape.
+
+ Args:
+ masks (torch.Tensor): Masks with shape (N, C, H, W).
+ shape (tuple[int, int]): Target height and width as (height, width).
+ ratio_pad (tuple, optional): Ratio and padding values as ((ratio_h, ratio_w), (pad_w, pad_h)).
+ padding (bool): Whether masks are based on YOLO-style augmented images with padding.
+
+ Returns:
+ (torch.Tensor): Rescaled masks.
+ """
im1_h, im1_w = masks.shape[2:]
im0_h, im0_w = shape[:2]
if im1_h == im0_h and im1_w == im0_w:
@@ -319,6 +560,19 @@
def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None, normalize: bool = False, padding: bool = True):
+ """Rescale segment coordinates from img1_shape to img0_shape.
+
+ Args:
+ img1_shape (tuple): Source image shape as HWC or HW (supports both).
+ coords (torch.Tensor): Coordinates to scale with shape (N, 2).
+ img0_shape (tuple): Image 0 shape as HWC or HW (supports both).
+ ratio_pad (tuple, optional): Ratio and padding values as ((ratio_h, ratio_w), (pad_w, pad_h)).
+ normalize (bool): Whether to normalize coordinates to range [0, 1].
+ padding (bool): Whether coordinates are based on YOLO-style augmented images with padding.
+
+ Returns:
+ (torch.Tensor): Scaled coordinates.
+ """
img0_h, img0_w = img0_shape[:2] # supports both HWC or HW shapes
if ratio_pad is None: # calculate from img0_shape
img1_h, img1_w = img1_shape[:2] # supports both HWC or HW shapes
@@ -341,6 +595,14 @@
def regularize_rboxes(rboxes):
+ """Regularize rotated bounding boxes to range [0, pi/2).
+
+ Args:
+ rboxes (torch.Tensor): Input rotated boxes with shape (N, 5) in xywhr format.
+
+ Returns:
+ (torch.Tensor): Regularized rotated boxes.
+ """
x, y, w, h, t = rboxes.unbind(dim=-1)
# Swap edge if t >= pi/2 while not being symmetrically opposite
swap = t % math.pi >= math.pi / 2
@@ -351,6 +613,15 @@
def masks2segments(masks: np.ndarray | torch.Tensor, strategy: str = "all") -> list[np.ndarray]:
+ """Convert masks to segments using contour detection.
+
+ Args:
+ masks (np.ndarray | torch.Tensor): Binary masks with shape (N, H, W).
+ strategy (str): Segmentation strategy, either 'all' or 'largest'.
+
+ Returns:
+ (list): List of segment masks as float32 arrays.
+ """
from ultralytics.data.converter import merge_multi_segment
masks = masks.astype("uint8") if isinstance(masks, np.ndarray) else masks.byte().cpu().numpy()
@@ -373,12 +644,29 @@
def convert_torch2numpy_batch(batch: torch.Tensor) -> np.ndarray:
+ """Convert a batch of FP32 torch tensors to NumPy uint8 arrays, changing from BCHW to BHWC layout.
+
+ Args:
+ batch (torch.Tensor): Input tensor batch with shape (Batch, Channels, Height, Width) and dtype torch.float32.
+
+ Returns:
+ (np.ndarray): Output NumPy array batch with shape (Batch, Height, Width, Channels) and dtype uint8.
+ """
return (batch.permute(0, 2, 3, 1).contiguous() * 255).clamp(0, 255).byte().cpu().numpy()
def clean_str(s):
+ """Clean a string by replacing special characters with '_' character.
+
+ Args:
+ s (str): A string needing special characters replaced.
+
+ Returns:
+ (str): A string with special characters replaced by an underscore _.
+ """
return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨`><+]", repl="_", string=s)
def empty_like(x):
- return torch.empty_like(x, dtype=x.dtype) if isinstance(x, torch.Tensor) else np.empty_like(x, dtype=x.dtype)+ """Create empty torch.Tensor or np.ndarray with same shape and dtype as input."""
+ return torch.empty_like(x, dtype=x.dtype) if isinstance(x, torch.Tensor) else np.empty_like(x, dtype=x.dtype)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/ops.py |
Add structured docstrings to improve clarity | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from pathlib import Path
from typing import Any
from ultralytics.solutions.solutions import BaseSolution, SolutionResults
from ultralytics.utils.plotting import save_one_box
class ObjectCropper(BaseSolution):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.crop_dir = self.CFG["crop_dir"] # Directory for storing cropped detections
Path(self.crop_dir).mkdir(parents=True, exist_ok=True)
if self.CFG["show"]:
self.LOGGER.warning(f"show=True is not supported for ObjectCropper; saving crops to '{self.crop_dir}'.")
self.CFG["show"] = False
self.crop_idx = 0 # Initialize counter for total cropped objects
self.iou = self.CFG["iou"]
self.conf = self.CFG["conf"]
def process(self, im0) -> SolutionResults:
with self.profilers[0]:
results = self.model.predict(
im0,
classes=self.classes,
conf=self.conf,
iou=self.iou,
device=self.CFG["device"],
verbose=False,
)[0]
self.clss = results.boxes.cls.tolist() # required for logging only.
for box in results.boxes:
self.crop_idx += 1
save_one_box(
box.xyxy,
im0,
file=Path(self.crop_dir) / f"crop_{self.crop_idx}.jpg",
BGR=True,
)
# Return SolutionResults
return SolutionResults(plot_im=im0, total_crop_objects=self.crop_idx) | --- +++ @@ -8,8 +8,34 @@
class ObjectCropper(BaseSolution):
+ """A class to manage the cropping of detected objects in a real-time video stream or images.
+
+ This class extends the BaseSolution class and provides functionality for cropping objects based on detected bounding
+ boxes. The cropped images are saved to a specified directory for further analysis or usage.
+
+ Attributes:
+ crop_dir (str): Directory where cropped object images are stored.
+ crop_idx (int): Counter for the total number of cropped objects.
+ iou (float): IoU (Intersection over Union) threshold for non-maximum suppression.
+ conf (float): Confidence threshold for filtering detections.
+
+ Methods:
+ process: Crop detected objects from the input image and save them to the output directory.
+
+ Examples:
+ >>> cropper = ObjectCropper()
+ >>> frame = cv2.imread("frame.jpg")
+ >>> processed_results = cropper.process(frame)
+ >>> print(f"Total cropped objects: {cropper.crop_idx}")
+ """
def __init__(self, **kwargs: Any) -> None:
+ """Initialize the ObjectCropper class for cropping objects from detected bounding boxes.
+
+ Args:
+ **kwargs (Any): Keyword arguments passed to the parent class and used for configuration including:
+ - crop_dir (str): Path to the directory for saving cropped object images.
+ """
super().__init__(**kwargs)
self.crop_dir = self.CFG["crop_dir"] # Directory for storing cropped detections
@@ -22,6 +48,21 @@ self.conf = self.CFG["conf"]
def process(self, im0) -> SolutionResults:
+ """Crop detected objects from the input image and save them as separate images.
+
+ Args:
+ im0 (np.ndarray): The input image containing detected objects.
+
+ Returns:
+ (SolutionResults): A SolutionResults object containing the total number of cropped objects and processed
+ image.
+
+ Examples:
+ >>> cropper = ObjectCropper()
+ >>> frame = cv2.imread("image.jpg")
+ >>> results = cropper.process(frame)
+ >>> print(f"Total cropped objects: {results.total_crop_objects}")
+ """
with self.profilers[0]:
results = self.model.predict(
im0,
@@ -43,4 +84,4 @@ )
# Return SolutionResults
- return SolutionResults(plot_im=im0, total_crop_objects=self.crop_idx)+ return SolutionResults(plot_im=im0, total_crop_objects=self.crop_idx)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/solutions/object_cropper.py |
Generate descriptive docstrings automatically | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import os
import sys
import time
from functools import lru_cache
from typing import IO, Any
@lru_cache(maxsize=1)
def is_noninteractive_console() -> bool:
return "GITHUB_ACTIONS" in os.environ or "RUNPOD_POD_ID" in os.environ
class TQDM:
# Constants
MIN_RATE_CALC_INTERVAL = 0.01 # Minimum time interval for rate calculation
RATE_SMOOTHING_FACTOR = 0.3 # Factor for exponential smoothing of rates
MAX_SMOOTHED_RATE = 1000000 # Maximum rate to apply smoothing to
NONINTERACTIVE_MIN_INTERVAL = 60.0 # Minimum interval for non-interactive environments
def __init__(
self,
iterable: Any = None,
desc: str | None = None,
total: int | None = None,
leave: bool = True,
file: IO[str] | None = None,
mininterval: float = 0.1,
disable: bool | None = None,
unit: str = "it",
unit_scale: bool = True,
unit_divisor: int = 1000,
bar_format: str | None = None, # kept for API compatibility; not used for formatting
initial: int = 0,
**kwargs,
) -> None:
# Disable if not verbose
if disable is None:
try:
from ultralytics.utils import LOGGER, VERBOSE
disable = not VERBOSE or LOGGER.getEffectiveLevel() > 20
except ImportError:
disable = False
self.iterable = iterable
self.desc = desc or ""
self.total = total or (len(iterable) if hasattr(iterable, "__len__") else None) or None # prevent total=0
self.disable = disable
self.unit = unit
self.unit_scale = unit_scale
self.unit_divisor = unit_divisor
self.leave = leave
self.noninteractive = is_noninteractive_console()
self.mininterval = max(mininterval, self.NONINTERACTIVE_MIN_INTERVAL) if self.noninteractive else mininterval
self.initial = initial
# Kept for API compatibility (unused for f-string formatting)
self.bar_format = bar_format
self.file = file or sys.stdout
# Internal state
self.n = self.initial
self.last_print_n = self.initial
self.last_print_t = time.time()
self.start_t = time.time()
self.last_rate = 0.0
self.closed = False
self.is_bytes = unit_scale and unit in {"B", "bytes"}
self.scales = (
[(1073741824, "GB/s"), (1048576, "MB/s"), (1024, "KB/s")]
if self.is_bytes
else [(1e9, f"G{self.unit}/s"), (1e6, f"M{self.unit}/s"), (1e3, f"K{self.unit}/s")]
)
if not self.disable and self.total and not self.noninteractive:
self._display()
def _format_rate(self, rate: float) -> str:
if rate <= 0:
return ""
inv_rate = 1 / rate if rate else None
# Use s/it format when inv_rate > 1 (i.e., rate < 1 it/s) for better readability
if inv_rate and inv_rate > 1:
return f"{inv_rate:.1f}s/B" if self.is_bytes else f"{inv_rate:.1f}s/{self.unit}"
# Use it/s format for fast iterations
fallback = f"{rate:.1f}B/s" if self.is_bytes else f"{rate:.1f}{self.unit}/s"
return next((f"{rate / t:.1f}{u}" for t, u in self.scales if rate >= t), fallback)
def _format_num(self, num: int | float) -> str:
if not self.unit_scale or not self.is_bytes:
return str(num)
for unit in ("", "K", "M", "G", "T"):
if abs(num) < self.unit_divisor:
return f"{num:3.1f}{unit}B" if unit else f"{num:.0f}B"
num /= self.unit_divisor
return f"{num:.1f}PB"
@staticmethod
def _format_time(seconds: float) -> str:
if seconds < 60:
return f"{seconds:.1f}s"
elif seconds < 3600:
return f"{int(seconds // 60)}:{seconds % 60:02.0f}"
else:
h, m = int(seconds // 3600), int((seconds % 3600) // 60)
return f"{h}:{m:02d}:{seconds % 60:02.0f}"
def _generate_bar(self, width: int = 12) -> str:
if self.total is None:
return "━" * width if self.closed else "─" * width
frac = min(1.0, self.n / self.total)
filled = int(frac * width)
bar = "━" * filled + "─" * (width - filled)
if filled < width and frac * width - filled > 0.5:
bar = f"{bar[:filled]}╸{bar[filled + 1 :]}"
return bar
def _should_update(self, dt: float, dn: int) -> bool:
if self.noninteractive:
return False
return (self.total is not None and self.n >= self.total) or (dt >= self.mininterval)
def _display(self, final: bool = False) -> None:
if self.disable or (self.closed and not final):
return
current_time = time.time()
dt = current_time - self.last_print_t
dn = self.n - self.last_print_n
if not final and not self._should_update(dt, dn):
return
# Calculate rate (avoid crazy numbers)
if dt > self.MIN_RATE_CALC_INTERVAL:
rate = dn / dt if dt else 0.0
# Smooth rate for reasonable values, use raw rate for very high values
if rate < self.MAX_SMOOTHED_RATE:
self.last_rate = self.RATE_SMOOTHING_FACTOR * rate + (1 - self.RATE_SMOOTHING_FACTOR) * self.last_rate
rate = self.last_rate
else:
rate = self.last_rate
# At completion, use overall rate
if self.total and self.n >= self.total:
overall_elapsed = current_time - self.start_t
if overall_elapsed > 0:
rate = self.n / overall_elapsed
# Update counters
self.last_print_n = self.n
self.last_print_t = current_time
elapsed = current_time - self.start_t
# Remaining time
remaining_str = ""
if self.total and 0 < self.n < self.total and elapsed > 0:
est_rate = rate or (self.n / elapsed)
remaining_str = f"<{self._format_time((self.total - self.n) / est_rate)}"
# Numbers and percent
if self.total:
percent = (self.n / self.total) * 100
n_str = self._format_num(self.n)
t_str = self._format_num(self.total)
if self.is_bytes and n_str[-2] == t_str[-2]: # Collapse suffix only when identical (e.g. "5.4/5.4MB")
n_str = n_str.rstrip("KMGTPB")
else:
percent = 0.0
n_str, t_str = self._format_num(self.n), "?"
elapsed_str = self._format_time(elapsed)
rate_str = self._format_rate(rate) or (self._format_rate(self.n / elapsed) if elapsed > 0 else "")
bar = self._generate_bar()
# Compose progress line via f-strings (two shapes: with/without total)
if self.total:
if self.is_bytes and self.n >= self.total:
# Completed bytes: show only final size
progress_str = f"{self.desc}: {percent:.0f}% {bar} {t_str} {rate_str} {elapsed_str}"
else:
progress_str = (
f"{self.desc}: {percent:.0f}% {bar} {n_str}/{t_str} {rate_str} {elapsed_str}{remaining_str}"
)
else:
progress_str = f"{self.desc}: {bar} {n_str} {rate_str} {elapsed_str}"
# Write to output
try:
if self.noninteractive:
# In non-interactive environments, avoid carriage return which creates empty lines
self.file.write(progress_str)
else:
# In interactive terminals, use carriage return and clear line for updating display
self.file.write(f"\r\033[K{progress_str}")
self.file.flush()
except Exception:
pass
def update(self, n: int = 1) -> None:
if not self.disable and not self.closed:
self.n += n
self._display()
def set_description(self, desc: str | None) -> None:
self.desc = desc or ""
if not self.disable:
self._display()
def set_postfix(self, **kwargs: Any) -> None:
if kwargs:
postfix = ", ".join(f"{k}={v}" for k, v in kwargs.items())
base_desc = self.desc.split(" | ")[0] if " | " in self.desc else self.desc
self.set_description(f"{base_desc} | {postfix}")
def close(self) -> None:
if self.closed:
return
self.closed = True
if not self.disable:
# Final display
if self.total and self.n >= self.total:
self.n = self.total
if self.n != self.last_print_n: # Skip if 100% already shown
self._display(final=True)
else:
self._display(final=True)
# Cleanup
if self.leave:
self.file.write("\n")
else:
self.file.write("\r\033[K")
try:
self.file.flush()
except Exception:
pass
def __enter__(self) -> TQDM:
return self
def __exit__(self, *args: Any) -> None:
self.close()
def __iter__(self) -> Any:
if self.iterable is None:
raise TypeError("'NoneType' object is not iterable")
try:
for item in self.iterable:
yield item
self.update(1)
finally:
self.close()
def __del__(self) -> None:
try:
self.close()
except Exception:
pass
def refresh(self) -> None:
if not self.disable:
self._display()
def clear(self) -> None:
if not self.disable:
try:
self.file.write("\r\033[K")
self.file.flush()
except Exception:
pass
@staticmethod
def write(s: str, file: IO[str] | None = None, end: str = "\n") -> None:
file = file or sys.stdout
try:
file.write(s + end)
file.flush()
except Exception:
pass
if __name__ == "__main__":
import time
print("1. Basic progress bar with known total:")
for i in TQDM(range(3), desc="Known total"):
time.sleep(0.05)
print("\n2. Manual updates with known total:")
pbar = TQDM(total=300, desc="Manual updates", unit="files")
for i in range(300):
time.sleep(0.03)
pbar.update(1)
if i % 10 == 9:
pbar.set_description(f"Processing batch {i // 10 + 1}")
pbar.close()
print("\n3. Progress bar with unknown total:")
pbar = TQDM(desc="Unknown total", unit="items")
for i in range(25):
time.sleep(0.08)
pbar.update(1)
if i % 5 == 4:
pbar.set_postfix(processed=i + 1, status="OK")
pbar.close()
print("\n4. Context manager with unknown total:")
with TQDM(desc="Processing stream", unit="B", unit_scale=True, unit_divisor=1024) as pbar:
for i in range(30):
time.sleep(0.1)
pbar.update(1024 * 1024 * i) # Simulate processing MB of data
print("\n5. Iterator with unknown length:")
def data_stream():
import random
for i in range(random.randint(10, 20)):
yield f"data_chunk_{i}"
for chunk in TQDM(data_stream(), desc="Stream processing", unit="chunks"):
time.sleep(0.1)
print("\n6. File processing simulation (unknown size):")
def process_files():
return [f"file_{i}.txt" for i in range(18)]
pbar = TQDM(desc="Scanning files", unit="files")
files = process_files()
for i, filename in enumerate(files):
time.sleep(0.06)
pbar.update(1)
pbar.set_description(f"Processing {filename}")
pbar.close() | --- +++ @@ -11,10 +11,65 @@
@lru_cache(maxsize=1)
def is_noninteractive_console() -> bool:
+ """Check for known non-interactive console environments."""
return "GITHUB_ACTIONS" in os.environ or "RUNPOD_POD_ID" in os.environ
class TQDM:
+ """Lightweight zero-dependency progress bar for Ultralytics.
+
+ Provides clean, rich-style progress bars suitable for various environments including Weights & Biases, console
+ outputs, and other logging systems. Features zero external dependencies, clean single-line output, rich-style
+ progress bars with Unicode block characters, context manager support, iterator protocol support, and dynamic
+ description updates.
+
+ Attributes:
+ iterable (Any): Iterable to wrap with progress bar.
+ desc (str): Prefix description for the progress bar.
+ total (int | None): Expected number of iterations.
+ disable (bool): Whether to disable the progress bar.
+ unit (str): String for units of iteration.
+ unit_scale (bool): Auto-scale units flag.
+ unit_divisor (int): Divisor for unit scaling.
+ leave (bool): Whether to leave the progress bar after completion.
+ mininterval (float): Minimum time interval between updates.
+ initial (int): Initial counter value.
+ n (int): Current iteration count.
+ closed (bool): Whether the progress bar is closed.
+ bar_format (str | None): Custom bar format string.
+ file (IO[str]): Output file stream.
+
+ Methods:
+ update: Update progress by n steps.
+ set_description: Set or update the description.
+ set_postfix: Set postfix for the progress bar.
+ close: Close the progress bar and clean up.
+ refresh: Refresh the progress bar display.
+ clear: Clear the progress bar from display.
+ write: Write a message without breaking the progress bar.
+
+ Examples:
+ Basic usage with iterator:
+ >>> for i in TQDM(range(100)):
+ ... time.sleep(0.01)
+
+ With custom description:
+ >>> pbar = TQDM(range(100), desc="Processing")
+ >>> for i in pbar:
+ ... pbar.set_description(f"Processing item {i}")
+
+ Context manager usage:
+ >>> with TQDM(total=100, unit="B", unit_scale=True) as pbar:
+ ... for i in range(100):
+ ... pbar.update(1)
+
+ Manual updates:
+ >>> pbar = TQDM(total=100, desc="Training")
+ >>> for epoch in range(100):
+ ... # Do work
+ ... pbar.update(1)
+ >>> pbar.close()
+ """
# Constants
MIN_RATE_CALC_INTERVAL = 0.01 # Minimum time interval for rate calculation
@@ -38,6 +93,23 @@ initial: int = 0,
**kwargs,
) -> None:
+ """Initialize the TQDM progress bar with specified configuration options.
+
+ Args:
+ iterable (Any, optional): Iterable to wrap with progress bar.
+ desc (str, optional): Prefix description for the progress bar.
+ total (int, optional): Expected number of iterations.
+ leave (bool, optional): Whether to leave the progress bar after completion.
+ file (IO[str], optional): Output file stream for progress display.
+ mininterval (float, optional): Minimum time interval between updates (default 0.1s, 60s in GitHub Actions).
+ disable (bool, optional): Whether to disable the progress bar. Auto-detected if None.
+ unit (str, optional): String for units of iteration (default "it" for items).
+ unit_scale (bool, optional): Auto-scale units for bytes/data units.
+ unit_divisor (int, optional): Divisor for unit scaling (default 1000).
+ bar_format (str, optional): Custom bar format string.
+ initial (int, optional): Initial counter value.
+ **kwargs (Any): Additional keyword arguments for compatibility (ignored).
+ """
# Disable if not verbose
if disable is None:
try:
@@ -82,6 +154,7 @@ self._display()
def _format_rate(self, rate: float) -> str:
+ """Format rate with units, switching between it/s and s/it for readability."""
if rate <= 0:
return ""
@@ -96,6 +169,7 @@ return next((f"{rate / t:.1f}{u}" for t, u in self.scales if rate >= t), fallback)
def _format_num(self, num: int | float) -> str:
+ """Format number with optional unit scaling."""
if not self.unit_scale or not self.is_bytes:
return str(num)
@@ -107,6 +181,7 @@
@staticmethod
def _format_time(seconds: float) -> str:
+ """Format time duration."""
if seconds < 60:
return f"{seconds:.1f}s"
elif seconds < 3600:
@@ -116,6 +191,7 @@ return f"{h}:{m:02d}:{seconds % 60:02.0f}"
def _generate_bar(self, width: int = 12) -> str:
+ """Generate progress bar."""
if self.total is None:
return "━" * width if self.closed else "─" * width
@@ -127,11 +203,13 @@ return bar
def _should_update(self, dt: float, dn: int) -> bool:
+ """Check if display should update."""
if self.noninteractive:
return False
return (self.total is not None and self.n >= self.total) or (dt >= self.mininterval)
def _display(self, final: bool = False) -> None:
+ """Display progress bar."""
if self.disable or (self.closed and not final):
return
@@ -210,22 +288,26 @@ pass
def update(self, n: int = 1) -> None:
+ """Update progress by n steps."""
if not self.disable and not self.closed:
self.n += n
self._display()
def set_description(self, desc: str | None) -> None:
+ """Set description."""
self.desc = desc or ""
if not self.disable:
self._display()
def set_postfix(self, **kwargs: Any) -> None:
+ """Set postfix (appends to description)."""
if kwargs:
postfix = ", ".join(f"{k}={v}" for k, v in kwargs.items())
base_desc = self.desc.split(" | ")[0] if " | " in self.desc else self.desc
self.set_description(f"{base_desc} | {postfix}")
def close(self) -> None:
+ """Close progress bar."""
if self.closed:
return
@@ -252,12 +334,15 @@ pass
def __enter__(self) -> TQDM:
+ """Enter context manager."""
return self
def __exit__(self, *args: Any) -> None:
+ """Exit context manager and close progress bar."""
self.close()
def __iter__(self) -> Any:
+ """Iterate over the wrapped iterable with progress updates."""
if self.iterable is None:
raise TypeError("'NoneType' object is not iterable")
@@ -269,16 +354,19 @@ self.close()
def __del__(self) -> None:
+ """Destructor to ensure cleanup."""
try:
self.close()
except Exception:
pass
def refresh(self) -> None:
+ """Refresh display."""
if not self.disable:
self._display()
def clear(self) -> None:
+ """Clear progress bar."""
if not self.disable:
try:
self.file.write("\r\033[K")
@@ -288,6 +376,7 @@
@staticmethod
def write(s: str, file: IO[str] | None = None, end: str = "\n") -> None:
+ """Static method to write without breaking progress bar."""
file = file or sys.stdout
try:
file.write(s + end)
@@ -330,6 +419,7 @@ print("\n5. Iterator with unknown length:")
def data_stream():
+ """Simulate a data stream of unknown length."""
import random
for i in range(random.randint(10, 20)):
@@ -341,6 +431,7 @@ print("\n6. File processing simulation (unknown size):")
def process_files():
+ """Simulate processing files of unknown count."""
return [f"file_{i}.txt" for i in range(18)]
pbar = TQDM(desc="Scanning files", unit="files")
@@ -349,4 +440,4 @@ time.sleep(0.06)
pbar.update(1)
pbar.set_description(f"Processing {filename}")
- pbar.close()+ pbar.close()
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/tqdm.py |
Add docstrings for utility scripts | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import torch
import torch.nn as nn
from . import LOGGER
from .metrics import bbox_iou, probiou
from .ops import xywh2xyxy, xywhr2xyxyxyxy, xyxy2xywh
from .torch_utils import TORCH_1_11
class TaskAlignedAssigner(nn.Module):
def __init__(
self,
topk: int = 13,
num_classes: int = 80,
alpha: float = 1.0,
beta: float = 6.0,
stride: list = [8, 16, 32],
eps: float = 1e-9,
topk2=None,
):
super().__init__()
self.topk = topk
self.topk2 = topk2 or topk
self.num_classes = num_classes
self.alpha = alpha
self.beta = beta
self.stride = stride
self.stride_val = self.stride[1] if len(self.stride) > 1 else self.stride[0]
self.eps = eps
@torch.no_grad()
def forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt):
self.bs = pd_scores.shape[0]
self.n_max_boxes = gt_bboxes.shape[1]
device = gt_bboxes.device
if self.n_max_boxes == 0:
return (
torch.full_like(pd_scores[..., 0], self.num_classes),
torch.zeros_like(pd_bboxes),
torch.zeros_like(pd_scores),
torch.zeros_like(pd_scores[..., 0]),
torch.zeros_like(pd_scores[..., 0]),
)
try:
return self._forward(pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt)
except RuntimeError as e:
if "out of memory" in str(e).lower():
# Move tensors to CPU, compute, then move back to original device
LOGGER.warning("CUDA OutOfMemoryError in TaskAlignedAssigner, using CPU")
cpu_tensors = [t.cpu() for t in (pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt)]
result = self._forward(*cpu_tensors)
return tuple(t.to(device) for t in result)
raise
def _forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt):
mask_pos, align_metric, overlaps = self.get_pos_mask(
pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt
)
target_gt_idx, fg_mask, mask_pos = self.select_highest_overlaps(
mask_pos, overlaps, self.n_max_boxes, align_metric
)
# Assigned target
target_labels, target_bboxes, target_scores = self.get_targets(gt_labels, gt_bboxes, target_gt_idx, fg_mask)
# Normalize
align_metric *= mask_pos
pos_align_metrics = align_metric.amax(dim=-1, keepdim=True) # b, max_num_obj
pos_overlaps = (overlaps * mask_pos).amax(dim=-1, keepdim=True) # b, max_num_obj
norm_align_metric = (align_metric * pos_overlaps / (pos_align_metrics + self.eps)).amax(-2).unsqueeze(-1)
target_scores = target_scores * norm_align_metric
return target_labels, target_bboxes, target_scores, fg_mask.bool(), target_gt_idx
def get_pos_mask(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt):
mask_in_gts = self.select_candidates_in_gts(anc_points, gt_bboxes, mask_gt)
# Get anchor_align metric, (b, max_num_obj, h*w)
align_metric, overlaps = self.get_box_metrics(pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_in_gts * mask_gt)
# Get topk_metric mask, (b, max_num_obj, h*w)
mask_topk = self.select_topk_candidates(align_metric, topk_mask=mask_gt.expand(-1, -1, self.topk).bool())
# Merge all mask to a final mask, (b, max_num_obj, h*w)
mask_pos = mask_topk * mask_in_gts * mask_gt
return mask_pos, align_metric, overlaps
def get_box_metrics(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_gt):
na = pd_bboxes.shape[-2]
mask_gt = mask_gt.bool() # b, max_num_obj, h*w
overlaps = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_bboxes.dtype, device=pd_bboxes.device)
bbox_scores = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_scores.dtype, device=pd_scores.device)
ind = torch.zeros([2, self.bs, self.n_max_boxes], dtype=torch.long) # 2, b, max_num_obj
ind[0] = torch.arange(end=self.bs).view(-1, 1).expand(-1, self.n_max_boxes) # b, max_num_obj
ind[1] = gt_labels.squeeze(-1) # b, max_num_obj
# Get the scores of each grid for each gt cls
bbox_scores[mask_gt] = pd_scores[ind[0], :, ind[1]][mask_gt] # b, max_num_obj, h*w
# (b, max_num_obj, 1, 4), (b, 1, h*w, 4)
pd_boxes = pd_bboxes.unsqueeze(1).expand(-1, self.n_max_boxes, -1, -1)[mask_gt]
gt_boxes = gt_bboxes.unsqueeze(2).expand(-1, -1, na, -1)[mask_gt]
overlaps[mask_gt] = self.iou_calculation(gt_boxes, pd_boxes)
align_metric = bbox_scores.pow(self.alpha) * overlaps.pow(self.beta)
return align_metric, overlaps
def iou_calculation(self, gt_bboxes, pd_bboxes):
return bbox_iou(gt_bboxes, pd_bboxes, xywh=False, CIoU=True).squeeze(-1).clamp_(0)
def select_topk_candidates(self, metrics, topk_mask=None):
# (b, max_num_obj, topk)
topk_metrics, topk_idxs = torch.topk(metrics, self.topk, dim=-1, largest=True)
if topk_mask is None:
topk_mask = (topk_metrics.max(-1, keepdim=True)[0] > self.eps).expand_as(topk_idxs)
# (b, max_num_obj, topk)
topk_idxs.masked_fill_(~topk_mask, 0)
# (b, max_num_obj, topk, h*w) -> (b, max_num_obj, h*w)
count_tensor = torch.zeros(metrics.shape, dtype=torch.int8, device=topk_idxs.device)
ones = torch.ones_like(topk_idxs[:, :, :1], dtype=torch.int8, device=topk_idxs.device)
for k in range(self.topk):
# Expand topk_idxs for each value of k and add 1 at the specified positions
count_tensor.scatter_add_(-1, topk_idxs[:, :, k : k + 1], ones)
# Filter invalid bboxes
count_tensor.masked_fill_(count_tensor > 1, 0)
return count_tensor.to(metrics.dtype)
def get_targets(self, gt_labels, gt_bboxes, target_gt_idx, fg_mask):
# Assigned target labels, (b, 1)
batch_ind = torch.arange(end=self.bs, dtype=torch.int64, device=gt_labels.device)[..., None]
target_gt_idx = target_gt_idx + batch_ind * self.n_max_boxes # (b, h*w)
target_labels = gt_labels.long().flatten()[target_gt_idx] # (b, h*w)
# Assigned target boxes, (b, max_num_obj, 4) -> (b, h*w, 4)
target_bboxes = gt_bboxes.view(-1, gt_bboxes.shape[-1])[target_gt_idx]
# Assigned target scores
target_labels.clamp_(0)
# 10x faster than F.one_hot()
target_scores = torch.zeros(
(target_labels.shape[0], target_labels.shape[1], self.num_classes),
dtype=torch.int64,
device=target_labels.device,
) # (b, h*w, 80)
target_scores.scatter_(2, target_labels.unsqueeze(-1), 1)
fg_scores_mask = fg_mask[:, :, None].repeat(1, 1, self.num_classes) # (b, h*w, 80)
target_scores = torch.where(fg_scores_mask > 0, target_scores, 0)
return target_labels, target_bboxes, target_scores
def select_candidates_in_gts(self, xy_centers, gt_bboxes, mask_gt, eps=1e-9):
gt_bboxes_xywh = xyxy2xywh(gt_bboxes)
wh_mask = gt_bboxes_xywh[..., 2:] < self.stride[0] # the smallest stride
gt_bboxes_xywh[..., 2:] = torch.where(
(wh_mask * mask_gt).bool(),
torch.tensor(self.stride_val, dtype=gt_bboxes_xywh.dtype, device=gt_bboxes_xywh.device),
gt_bboxes_xywh[..., 2:],
)
gt_bboxes = xywh2xyxy(gt_bboxes_xywh)
n_anchors = xy_centers.shape[0]
bs, n_boxes, _ = gt_bboxes.shape
lt, rb = gt_bboxes.view(-1, 1, 4).chunk(2, 2) # left-top, right-bottom
bbox_deltas = torch.cat((xy_centers[None] - lt, rb - xy_centers[None]), dim=2).view(bs, n_boxes, n_anchors, -1)
return bbox_deltas.amin(3).gt_(eps)
def select_highest_overlaps(self, mask_pos, overlaps, n_max_boxes, align_metric):
# Convert (b, n_max_boxes, h*w) -> (b, h*w)
fg_mask = mask_pos.sum(-2)
if fg_mask.max() > 1: # one anchor is assigned to multiple gt_bboxes
mask_multi_gts = (fg_mask.unsqueeze(1) > 1).expand(-1, n_max_boxes, -1) # (b, n_max_boxes, h*w)
max_overlaps_idx = overlaps.argmax(1) # (b, h*w)
is_max_overlaps = torch.zeros(mask_pos.shape, dtype=mask_pos.dtype, device=mask_pos.device)
is_max_overlaps.scatter_(1, max_overlaps_idx.unsqueeze(1), 1)
mask_pos = torch.where(mask_multi_gts, is_max_overlaps, mask_pos).float() # (b, n_max_boxes, h*w)
fg_mask = mask_pos.sum(-2)
if self.topk2 != self.topk:
align_metric = align_metric * mask_pos # update overlaps
max_overlaps_idx = torch.topk(align_metric, self.topk2, dim=-1, largest=True).indices # (b, n_max_boxes)
topk_idx = torch.zeros(mask_pos.shape, dtype=mask_pos.dtype, device=mask_pos.device) # update mask_pos
topk_idx.scatter_(-1, max_overlaps_idx, 1.0)
mask_pos *= topk_idx
fg_mask = mask_pos.sum(-2)
# Find each grid serve which gt(index)
target_gt_idx = mask_pos.argmax(-2) # (b, h*w)
return target_gt_idx, fg_mask, mask_pos
class RotatedTaskAlignedAssigner(TaskAlignedAssigner):
def iou_calculation(self, gt_bboxes, pd_bboxes):
return probiou(gt_bboxes, pd_bboxes).squeeze(-1).clamp_(0)
def select_candidates_in_gts(self, xy_centers, gt_bboxes, mask_gt):
wh_mask = gt_bboxes[..., 2:4] < self.stride[0]
gt_bboxes[..., 2:4] = torch.where(
(wh_mask * mask_gt).bool(),
torch.tensor(self.stride_val, dtype=gt_bboxes.dtype, device=gt_bboxes.device),
gt_bboxes[..., 2:4],
)
# (b, n_boxes, 5) --> (b, n_boxes, 4, 2)
corners = xywhr2xyxyxyxy(gt_bboxes)
# (b, n_boxes, 1, 2)
a, b, _, d = corners.split(1, dim=-2)
ab = b - a
ad = d - a
# (b, n_boxes, h*w, 2)
ap = xy_centers - a
norm_ab = (ab * ab).sum(dim=-1)
norm_ad = (ad * ad).sum(dim=-1)
ap_dot_ab = (ap * ab).sum(dim=-1)
ap_dot_ad = (ap * ad).sum(dim=-1)
return (ap_dot_ab >= 0) & (ap_dot_ab <= norm_ab) & (ap_dot_ad >= 0) & (ap_dot_ad <= norm_ad) # is_in_box
def make_anchors(feats, strides, grid_cell_offset=0.5):
anchor_points, stride_tensor = [], []
assert feats is not None
dtype, device = feats[0].dtype, feats[0].device
for i in range(len(feats)): # use len(feats) to avoid TracerWarning from iterating over strides tensor
stride = strides[i]
h, w = feats[i].shape[2:] if isinstance(feats, list) else (int(feats[i][0]), int(feats[i][1]))
sx = torch.arange(end=w, device=device, dtype=dtype) + grid_cell_offset # shift x
sy = torch.arange(end=h, device=device, dtype=dtype) + grid_cell_offset # shift y
sy, sx = torch.meshgrid(sy, sx, indexing="ij") if TORCH_1_11 else torch.meshgrid(sy, sx)
anchor_points.append(torch.stack((sx, sy), -1).view(-1, 2))
stride_tensor.append(torch.full((h * w, 1), stride, dtype=dtype, device=device))
return torch.cat(anchor_points), torch.cat(stride_tensor)
def dist2bbox(distance, anchor_points, xywh=True, dim=-1):
lt, rb = distance.chunk(2, dim)
x1y1 = anchor_points - lt
x2y2 = anchor_points + rb
if xywh:
c_xy = (x1y1 + x2y2) / 2
wh = x2y2 - x1y1
return torch.cat([c_xy, wh], dim) # xywh bbox
return torch.cat((x1y1, x2y2), dim) # xyxy bbox
def bbox2dist(anchor_points: torch.Tensor, bbox: torch.Tensor, reg_max: int | None = None) -> torch.Tensor:
x1y1, x2y2 = bbox.chunk(2, -1)
dist = torch.cat((anchor_points - x1y1, x2y2 - anchor_points), -1)
if reg_max is not None:
dist = dist.clamp_(0, reg_max - 0.01) # dist (lt, rb)
return dist
def dist2rbox(pred_dist, pred_angle, anchor_points, dim=-1):
lt, rb = pred_dist.split(2, dim=dim)
cos, sin = torch.cos(pred_angle), torch.sin(pred_angle)
# (bs, h*w, 1)
xf, yf = ((rb - lt) / 2).split(1, dim=dim)
x, y = xf * cos - yf * sin, xf * sin + yf * cos
xy = torch.cat([x, y], dim=dim) + anchor_points
return torch.cat([xy, lt + rb], dim=dim)
def rbox2dist(
target_bboxes: torch.Tensor,
anchor_points: torch.Tensor,
target_angle: torch.Tensor,
dim: int = -1,
reg_max: int | None = None,
):
xy, wh = target_bboxes.split(2, dim=dim)
offset = xy - anchor_points # (bs, h*w, 2)
offset_x, offset_y = offset.split(1, dim=dim)
cos, sin = torch.cos(target_angle), torch.sin(target_angle)
xf = offset_x * cos + offset_y * sin
yf = -offset_x * sin + offset_y * cos
w, h = wh.split(1, dim=dim)
target_l = w / 2 - xf
target_t = h / 2 - yf
target_r = w / 2 + xf
target_b = h / 2 + yf
dist = torch.cat([target_l, target_t, target_r, target_b], dim=dim)
if reg_max is not None:
dist = dist.clamp_(0, reg_max - 0.01)
return dist | --- +++ @@ -12,6 +12,21 @@
class TaskAlignedAssigner(nn.Module):
+ """A task-aligned assigner for object detection.
+
+ This class assigns ground-truth (gt) objects to anchors based on the task-aligned metric, which combines both
+ classification and localization information.
+
+ Attributes:
+ topk (int): The number of top candidates to consider.
+ topk2 (int): Secondary topk value for additional filtering.
+ num_classes (int): The number of object classes.
+ alpha (float): The alpha parameter for the classification component of the task-aligned metric.
+ beta (float): The beta parameter for the localization component of the task-aligned metric.
+ stride (list): List of stride values for different feature levels.
+ stride_val (int): The stride value used for select_candidates_in_gts.
+ eps (float): A small value to prevent division by zero.
+ """
def __init__(
self,
@@ -23,6 +38,17 @@ eps: float = 1e-9,
topk2=None,
):
+ """Initialize a TaskAlignedAssigner object with customizable hyperparameters.
+
+ Args:
+ topk (int, optional): The number of top candidates to consider.
+ num_classes (int, optional): The number of object classes.
+ alpha (float, optional): The alpha parameter for the classification component of the task-aligned metric.
+ beta (float, optional): The beta parameter for the localization component of the task-aligned metric.
+ stride (list, optional): List of stride values for different feature levels.
+ eps (float, optional): A small value to prevent division by zero.
+ topk2 (int, optional): Secondary topk value for additional filtering.
+ """
super().__init__()
self.topk = topk
self.topk2 = topk2 or topk
@@ -35,6 +61,26 @@
@torch.no_grad()
def forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt):
+ """Compute the task-aligned assignment.
+
+ Args:
+ pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes).
+ pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4).
+ anc_points (torch.Tensor): Anchor points with shape (num_total_anchors, 2).
+ gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1).
+ gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4).
+ mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, 1).
+
+ Returns:
+ target_labels (torch.Tensor): Target labels with shape (bs, num_total_anchors).
+ target_bboxes (torch.Tensor): Target bounding boxes with shape (bs, num_total_anchors, 4).
+ target_scores (torch.Tensor): Target scores with shape (bs, num_total_anchors, num_classes).
+ fg_mask (torch.Tensor): Foreground mask with shape (bs, num_total_anchors).
+ target_gt_idx (torch.Tensor): Target ground truth indices with shape (bs, num_total_anchors).
+
+ References:
+ https://github.com/Nioolek/PPYOLOE_pytorch/blob/master/ppyoloe/assigner/tal_assigner.py
+ """
self.bs = pd_scores.shape[0]
self.n_max_boxes = gt_bboxes.shape[1]
device = gt_bboxes.device
@@ -60,6 +106,23 @@ raise
def _forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt):
+ """Compute the task-aligned assignment.
+
+ Args:
+ pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes).
+ pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4).
+ anc_points (torch.Tensor): Anchor points with shape (num_total_anchors, 2).
+ gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1).
+ gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4).
+ mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, 1).
+
+ Returns:
+ target_labels (torch.Tensor): Target labels with shape (bs, num_total_anchors).
+ target_bboxes (torch.Tensor): Target bounding boxes with shape (bs, num_total_anchors, 4).
+ target_scores (torch.Tensor): Target scores with shape (bs, num_total_anchors, num_classes).
+ fg_mask (torch.Tensor): Foreground mask with shape (bs, num_total_anchors).
+ target_gt_idx (torch.Tensor): Target ground truth indices with shape (bs, num_total_anchors).
+ """
mask_pos, align_metric, overlaps = self.get_pos_mask(
pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt
)
@@ -81,6 +144,21 @@ return target_labels, target_bboxes, target_scores, fg_mask.bool(), target_gt_idx
def get_pos_mask(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt):
+ """Get positive mask for each ground truth box.
+
+ Args:
+ pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes).
+ pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4).
+ gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1).
+ gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4).
+ anc_points (torch.Tensor): Anchor points with shape (num_total_anchors, 2).
+ mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, 1).
+
+ Returns:
+ mask_pos (torch.Tensor): Positive mask with shape (bs, max_num_obj, h*w).
+ align_metric (torch.Tensor): Alignment metric with shape (bs, max_num_obj, h*w).
+ overlaps (torch.Tensor): Overlaps between predicted vs ground truth boxes with shape (bs, max_num_obj, h*w).
+ """
mask_in_gts = self.select_candidates_in_gts(anc_points, gt_bboxes, mask_gt)
# Get anchor_align metric, (b, max_num_obj, h*w)
align_metric, overlaps = self.get_box_metrics(pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_in_gts * mask_gt)
@@ -92,6 +170,19 @@ return mask_pos, align_metric, overlaps
def get_box_metrics(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_gt):
+ """Compute alignment metric given predicted and ground truth bounding boxes.
+
+ Args:
+ pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes).
+ pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4).
+ gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1).
+ gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4).
+ mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, h*w).
+
+ Returns:
+ align_metric (torch.Tensor): Alignment metric combining classification and localization.
+ overlaps (torch.Tensor): IoU overlaps between predicted and ground truth boxes.
+ """
na = pd_bboxes.shape[-2]
mask_gt = mask_gt.bool() # b, max_num_obj, h*w
overlaps = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_bboxes.dtype, device=pd_bboxes.device)
@@ -112,9 +203,30 @@ return align_metric, overlaps
def iou_calculation(self, gt_bboxes, pd_bboxes):
+ """Calculate IoU for horizontal bounding boxes.
+
+ Args:
+ gt_bboxes (torch.Tensor): Ground truth boxes.
+ pd_bboxes (torch.Tensor): Predicted boxes.
+
+ Returns:
+ (torch.Tensor): IoU values between each pair of boxes.
+ """
return bbox_iou(gt_bboxes, pd_bboxes, xywh=False, CIoU=True).squeeze(-1).clamp_(0)
def select_topk_candidates(self, metrics, topk_mask=None):
+ """Select the top-k candidates based on the given metrics.
+
+ Args:
+ metrics (torch.Tensor): A tensor of shape (b, max_num_obj, h*w), where b is the batch size, max_num_obj is
+ the maximum number of objects, and h*w represents the total number of anchor points.
+ topk_mask (torch.Tensor, optional): An optional boolean tensor of shape (b, max_num_obj, topk), where topk
+ is the number of top candidates to consider. If not provided, the top-k values are automatically
+ computed based on the given metrics.
+
+ Returns:
+ (torch.Tensor): A tensor of shape (b, max_num_obj, h*w) containing the selected top-k candidates.
+ """
# (b, max_num_obj, topk)
topk_metrics, topk_idxs = torch.topk(metrics, self.topk, dim=-1, largest=True)
if topk_mask is None:
@@ -134,6 +246,22 @@ return count_tensor.to(metrics.dtype)
def get_targets(self, gt_labels, gt_bboxes, target_gt_idx, fg_mask):
+ """Compute target labels, target bounding boxes, and target scores for the positive anchor points.
+
+ Args:
+ gt_labels (torch.Tensor): Ground truth labels of shape (b, max_num_obj, 1), where b is the batch size and
+ max_num_obj is the maximum number of objects.
+ gt_bboxes (torch.Tensor): Ground truth bounding boxes of shape (b, max_num_obj, 4).
+ target_gt_idx (torch.Tensor): Indices of the assigned ground truth objects for positive anchor points, with
+ shape (b, h*w), where h*w is the total number of anchor points.
+ fg_mask (torch.Tensor): A boolean tensor of shape (b, h*w) indicating the positive (foreground) anchor
+ points.
+
+ Returns:
+ target_labels (torch.Tensor): Target labels for positive anchor points with shape (b, h*w).
+ target_bboxes (torch.Tensor): Target bounding boxes for positive anchor points with shape (b, h*w, 4).
+ target_scores (torch.Tensor): Target scores for positive anchor points with shape (b, h*w, num_classes).
+ """
# Assigned target labels, (b, 1)
batch_ind = torch.arange(end=self.bs, dtype=torch.int64, device=gt_labels.device)[..., None]
target_gt_idx = target_gt_idx + batch_ind * self.n_max_boxes # (b, h*w)
@@ -159,6 +287,21 @@ return target_labels, target_bboxes, target_scores
def select_candidates_in_gts(self, xy_centers, gt_bboxes, mask_gt, eps=1e-9):
+ """Select positive anchor centers within ground truth bounding boxes.
+
+ Args:
+ xy_centers (torch.Tensor): Anchor center coordinates, shape (h*w, 2).
+ gt_bboxes (torch.Tensor): Ground truth bounding boxes, shape (b, n_boxes, 4).
+ mask_gt (torch.Tensor): Mask for valid ground truth boxes, shape (b, n_boxes, 1).
+ eps (float, optional): Small value for numerical stability.
+
+ Returns:
+ (torch.Tensor): Boolean mask of positive anchors, shape (b, n_boxes, h*w).
+
+ Notes:
+ - b: batch size, n_boxes: number of ground truth boxes, h: height, w: width.
+ - Bounding box format: [x_min, y_min, x_max, y_max].
+ """
gt_bboxes_xywh = xyxy2xywh(gt_bboxes)
wh_mask = gt_bboxes_xywh[..., 2:] < self.stride[0] # the smallest stride
gt_bboxes_xywh[..., 2:] = torch.where(
@@ -175,6 +318,19 @@ return bbox_deltas.amin(3).gt_(eps)
def select_highest_overlaps(self, mask_pos, overlaps, n_max_boxes, align_metric):
+ """Select anchor boxes with highest IoU when assigned to multiple ground truths.
+
+ Args:
+ mask_pos (torch.Tensor): Positive mask, shape (b, n_max_boxes, h*w).
+ overlaps (torch.Tensor): IoU overlaps, shape (b, n_max_boxes, h*w).
+ n_max_boxes (int): Maximum number of ground truth boxes.
+ align_metric (torch.Tensor): Alignment metric for selecting best matches.
+
+ Returns:
+ target_gt_idx (torch.Tensor): Indices of assigned ground truths, shape (b, h*w).
+ fg_mask (torch.Tensor): Foreground mask, shape (b, h*w).
+ mask_pos (torch.Tensor): Updated positive mask, shape (b, n_max_boxes, h*w).
+ """
# Convert (b, n_max_boxes, h*w) -> (b, h*w)
fg_mask = mask_pos.sum(-2)
if fg_mask.max() > 1: # one anchor is assigned to multiple gt_bboxes
@@ -200,11 +356,23 @@
class RotatedTaskAlignedAssigner(TaskAlignedAssigner):
+ """Assigns ground-truth objects to rotated bounding boxes using a task-aligned metric."""
def iou_calculation(self, gt_bboxes, pd_bboxes):
+ """Calculate IoU for rotated bounding boxes."""
return probiou(gt_bboxes, pd_bboxes).squeeze(-1).clamp_(0)
def select_candidates_in_gts(self, xy_centers, gt_bboxes, mask_gt):
+ """Select the positive anchor center in gt for rotated bounding boxes.
+
+ Args:
+ xy_centers (torch.Tensor): Anchor center coordinates with shape (h*w, 2).
+ gt_bboxes (torch.Tensor): Ground truth bounding boxes with shape (b, n_boxes, 5).
+ mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (b, n_boxes, 1).
+
+ Returns:
+ (torch.Tensor): Boolean mask of positive anchors with shape (b, n_boxes, h*w).
+ """
wh_mask = gt_bboxes[..., 2:4] < self.stride[0]
gt_bboxes[..., 2:4] = torch.where(
(wh_mask * mask_gt).bool(),
@@ -229,6 +397,7 @@
def make_anchors(feats, strides, grid_cell_offset=0.5):
+ """Generate anchors from features."""
anchor_points, stride_tensor = [], []
assert feats is not None
dtype, device = feats[0].dtype, feats[0].device
@@ -244,6 +413,7 @@
def dist2bbox(distance, anchor_points, xywh=True, dim=-1):
+ """Transform distance(ltrb) to box(xywh or xyxy)."""
lt, rb = distance.chunk(2, dim)
x1y1 = anchor_points - lt
x2y2 = anchor_points + rb
@@ -255,6 +425,7 @@
def bbox2dist(anchor_points: torch.Tensor, bbox: torch.Tensor, reg_max: int | None = None) -> torch.Tensor:
+ """Transform bbox(xyxy) to dist(ltrb)."""
x1y1, x2y2 = bbox.chunk(2, -1)
dist = torch.cat((anchor_points - x1y1, x2y2 - anchor_points), -1)
if reg_max is not None:
@@ -263,6 +434,17 @@
def dist2rbox(pred_dist, pred_angle, anchor_points, dim=-1):
+ """Decode predicted rotated bounding box coordinates from anchor points and distribution.
+
+ Args:
+ pred_dist (torch.Tensor): Predicted rotated distance with shape (bs, h*w, 4).
+ pred_angle (torch.Tensor): Predicted angle with shape (bs, h*w, 1).
+ anchor_points (torch.Tensor): Anchor points with shape (h*w, 2).
+ dim (int, optional): Dimension along which to split.
+
+ Returns:
+ (torch.Tensor): Predicted rotated bounding boxes with shape (bs, h*w, 4).
+ """
lt, rb = pred_dist.split(2, dim=dim)
cos, sin = torch.cos(pred_angle), torch.sin(pred_angle)
# (bs, h*w, 1)
@@ -279,6 +461,18 @@ dim: int = -1,
reg_max: int | None = None,
):
+ """Transform rotated bounding box (xywh) to distance (ltrb). This is the inverse of dist2rbox.
+
+ Args:
+ target_bboxes (torch.Tensor): Target rotated bounding boxes with shape (bs, h*w, 4), format [x, y, w, h].
+ anchor_points (torch.Tensor): Anchor points with shape (h*w, 2).
+ target_angle (torch.Tensor): Target angle with shape (bs, h*w, 1).
+ dim (int, optional): Dimension along which to split.
+ reg_max (int, optional): Maximum regression value for clamping.
+
+ Returns:
+ (torch.Tensor): Rotated distance with shape (bs, h*w, 4), format [l, t, r, b].
+ """
xy, wh = target_bboxes.split(2, dim=dim)
offset = xy - anchor_points # (bs, h*w, 2)
offset_x, offset_y = offset.split(1, dim=dim)
@@ -296,4 +490,4 @@ if reg_max is not None:
dist = dist.clamp_(0, reg_max - 0.01)
- return dist+ return dist
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/tal.py |
Help me comply with documentation standards | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import math
from collections.abc import Callable
from pathlib import Path
from typing import Any
import cv2
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont
from PIL import __version__ as pil_version
from ultralytics.utils import IS_COLAB, IS_KAGGLE, LOGGER, TryExcept, ops, plt_settings, threaded
from ultralytics.utils.checks import check_font, check_version, is_ascii
from ultralytics.utils.files import increment_path
class Colors:
def __init__(self):
hexs = (
"042AFF",
"0BDBEB",
"F3F3F3",
"00DFB7",
"111F68",
"FF6FDD",
"FF444F",
"CCED00",
"00F344",
"BD00FF",
"00B4FF",
"DD00BA",
"00FFFF",
"26C000",
"01FFB3",
"7D24FF",
"7B0068",
"FF1B6C",
"FC6D2F",
"A2FF0B",
)
self.palette = [self.hex2rgb(f"#{c}") for c in hexs]
self.n = len(self.palette)
self.pose_palette = np.array(
[
[255, 128, 0],
[255, 153, 51],
[255, 178, 102],
[230, 230, 0],
[255, 153, 255],
[153, 204, 255],
[255, 102, 255],
[255, 51, 255],
[102, 178, 255],
[51, 153, 255],
[255, 153, 153],
[255, 102, 102],
[255, 51, 51],
[153, 255, 153],
[102, 255, 102],
[51, 255, 51],
[0, 255, 0],
[0, 0, 255],
[255, 0, 0],
[255, 255, 255],
],
dtype=np.uint8,
)
def __call__(self, i: int | torch.Tensor, bgr: bool = False) -> tuple:
c = self.palette[int(i) % self.n]
return (c[2], c[1], c[0]) if bgr else c
@staticmethod
def hex2rgb(h: str) -> tuple:
return tuple(int(h[1 + i : 1 + i + 2], 16) for i in (0, 2, 4))
colors = Colors() # create instance for 'from utils.plots import colors'
class Annotator:
def __init__(
self,
im,
line_width: int | None = None,
font_size: int | None = None,
font: str = "Arial.ttf",
pil: bool = False,
example: str = "abc",
):
non_ascii = not is_ascii(example) # non-latin labels, i.e. asian, arabic, cyrillic
input_is_pil = isinstance(im, Image.Image)
self.pil = pil or non_ascii or input_is_pil
self.lw = line_width or max(round(sum(im.size if input_is_pil else im.shape) / 2 * 0.003), 2)
if not input_is_pil:
if im.shape[2] == 1: # handle grayscale
im = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR)
elif im.shape[2] == 2: # handle 2-channel images
im = np.ascontiguousarray(np.dstack((im, np.zeros_like(im[..., :1]))))
elif im.shape[2] > 3: # multispectral
im = np.ascontiguousarray(im[..., :3])
if self.pil: # use PIL
self.im = im if input_is_pil else Image.fromarray(im) # stay in BGR since color palette is in BGR
if self.im.mode not in {"RGB", "RGBA"}: # multispectral
self.im = self.im.convert("RGB")
self.draw = ImageDraw.Draw(self.im, "RGBA")
try:
font = check_font("Arial.Unicode.ttf" if non_ascii else font)
size = font_size or max(round(sum(self.im.size) / 2 * 0.035), 12)
self.font = ImageFont.truetype(str(font), size)
except Exception:
self.font = ImageFont.load_default()
# Deprecation fix for w, h = getsize(string) -> _, _, w, h = getbox(string)
if check_version(pil_version, "9.2.0"):
self.font.getsize = lambda x: self.font.getbbox(x)[2:4] # text width, height
else: # use cv2
assert im.data.contiguous, "Image not contiguous. Apply np.ascontiguousarray(im) to Annotator input images."
self.im = im if im.flags.writeable else im.copy()
self.tf = max(self.lw - 1, 1) # font thickness
self.sf = self.lw / 3 # font scale
# Pose
self.skeleton = [
[16, 14],
[14, 12],
[17, 15],
[15, 13],
[12, 13],
[6, 12],
[7, 13],
[6, 7],
[6, 8],
[7, 9],
[8, 10],
[9, 11],
[2, 3],
[1, 2],
[1, 3],
[2, 4],
[3, 5],
[4, 6],
[5, 7],
]
self.limb_color = colors.pose_palette[[9, 9, 9, 9, 7, 7, 7, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16]]
self.kpt_color = colors.pose_palette[[16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9]]
self.dark_colors = {
(235, 219, 11),
(243, 243, 243),
(183, 223, 0),
(221, 111, 255),
(0, 237, 204),
(68, 243, 0),
(255, 255, 0),
(179, 255, 1),
(11, 255, 162),
}
self.light_colors = {
(255, 42, 4),
(79, 68, 255),
(255, 0, 189),
(255, 180, 0),
(186, 0, 221),
(0, 192, 38),
(255, 36, 125),
(104, 0, 123),
(108, 27, 255),
(47, 109, 252),
(104, 31, 17),
}
def get_txt_color(self, color: tuple = (128, 128, 128), txt_color: tuple = (255, 255, 255)) -> tuple:
if color in self.dark_colors:
return 104, 31, 17
elif color in self.light_colors:
return 255, 255, 255
else:
return txt_color
def box_label(self, box, label: str = "", color: tuple = (128, 128, 128), txt_color: tuple = (255, 255, 255)):
txt_color = self.get_txt_color(color, txt_color)
if isinstance(box, torch.Tensor):
box = box.tolist()
multi_points = isinstance(box[0], list) # multiple points with shape (n, 2)
p1 = [int(b) for b in box[0]] if multi_points else (int(box[0]), int(box[1]))
if self.pil:
self.draw.polygon(
[tuple(b) for b in box], width=self.lw, outline=color
) if multi_points else self.draw.rectangle(box, width=self.lw, outline=color)
if label:
w, h = self.font.getsize(label) # text width, height
outside = p1[1] >= h # label fits outside box
if p1[0] > self.im.size[0] - w: # size is (w, h), check if label extend beyond right side of image
p1 = self.im.size[0] - w, p1[1]
self.draw.rectangle(
(p1[0], p1[1] - h if outside else p1[1], p1[0] + w + 1, p1[1] + 1 if outside else p1[1] + h + 1),
fill=color,
)
# self.draw.text([box[0], box[1]], label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0
self.draw.text((p1[0], p1[1] - h if outside else p1[1]), label, fill=txt_color, font=self.font)
else: # cv2
cv2.polylines(
self.im, [np.asarray(box, dtype=int)], True, color, self.lw
) if multi_points else cv2.rectangle(
self.im, p1, (int(box[2]), int(box[3])), color, thickness=self.lw, lineType=cv2.LINE_AA
)
if label:
w, h = cv2.getTextSize(label, 0, fontScale=self.sf, thickness=self.tf)[0] # text width, height
h += 3 # add pixels to pad text
outside = p1[1] >= h # label fits outside box
if p1[0] > self.im.shape[1] - w: # shape is (h, w), check if label extend beyond right side of image
p1 = self.im.shape[1] - w, p1[1]
p2 = p1[0] + w, p1[1] - h if outside else p1[1] + h
cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled
cv2.putText(
self.im,
label,
(p1[0], p1[1] - 2 if outside else p1[1] + h - 1),
0,
self.sf,
txt_color,
thickness=self.tf,
lineType=cv2.LINE_AA,
)
def masks(self, masks, colors, im_gpu: torch.Tensor = None, alpha: float = 0.5, retina_masks: bool = False):
if self.pil:
# Convert to numpy first
self.im = np.asarray(self.im).copy()
if im_gpu is None:
assert isinstance(masks, np.ndarray), "`masks` must be a np.ndarray if `im_gpu` is not provided."
overlay = self.im.copy()
for i, mask in enumerate(masks):
overlay[mask.astype(bool)] = colors[i]
self.im = cv2.addWeighted(self.im, 1 - alpha, overlay, alpha, 0)
else:
assert isinstance(masks, torch.Tensor), "'masks' must be a torch.Tensor if 'im_gpu' is provided."
if len(masks) == 0:
self.im[:] = im_gpu.permute(1, 2, 0).contiguous().cpu().numpy() * 255
return
if im_gpu.device != masks.device:
im_gpu = im_gpu.to(masks.device)
ih, iw = self.im.shape[:2]
if not retina_masks:
# Use scale_masks to properly remove padding and upsample, convert bool to float first
masks = ops.scale_masks(masks[None].float(), (ih, iw))[0] > 0.5
# Convert original BGR image to RGB tensor
im_gpu = (
torch.from_numpy(self.im).to(masks.device).permute(2, 0, 1).flip(0).contiguous().float() / 255.0
)
colors = torch.tensor(colors, device=masks.device, dtype=torch.float32) / 255.0 # shape(n,3)
colors = colors[:, None, None] # shape(n,1,1,3)
masks = masks.unsqueeze(3) # shape(n,h,w,1)
masks_color = masks * (colors * alpha) # shape(n,h,w,3)
inv_alpha_masks = (1 - masks * alpha).cumprod(0) # shape(n,h,w,1)
mcs = masks_color.max(dim=0).values # shape(h,w,3)
im_gpu = im_gpu.flip(dims=[0]).permute(1, 2, 0).contiguous() # shape(h,w,3)
im_gpu = im_gpu * inv_alpha_masks[-1] + mcs
self.im[:] = (im_gpu * 255).byte().cpu().numpy()
if self.pil:
# Convert im back to PIL and update draw
self.fromarray(self.im)
def kpts(
self,
kpts,
shape: tuple = (640, 640),
radius: int | None = None,
kpt_line: bool = True,
conf_thres: float = 0.25,
kpt_color: tuple | None = None,
):
radius = radius if radius is not None else self.lw
if self.pil:
# Convert to numpy first
self.im = np.asarray(self.im).copy()
nkpt, ndim = kpts.shape
is_pose = nkpt == 17 and ndim in {2, 3}
kpt_line &= is_pose # `kpt_line=True` for now only supports human pose plotting
for i, k in enumerate(kpts):
color_k = kpt_color or (self.kpt_color[i].tolist() if is_pose else colors(i))
x_coord, y_coord = k[0], k[1]
if x_coord % shape[1] != 0 and y_coord % shape[0] != 0:
if len(k) == 3:
conf = k[2]
if conf < conf_thres:
continue
cv2.circle(self.im, (int(x_coord), int(y_coord)), radius, color_k, -1, lineType=cv2.LINE_AA)
if kpt_line:
ndim = kpts.shape[-1]
for i, sk in enumerate(self.skeleton):
pos1 = (int(kpts[(sk[0] - 1), 0]), int(kpts[(sk[0] - 1), 1]))
pos2 = (int(kpts[(sk[1] - 1), 0]), int(kpts[(sk[1] - 1), 1]))
if ndim == 3:
conf1 = kpts[(sk[0] - 1), 2]
conf2 = kpts[(sk[1] - 1), 2]
if conf1 < conf_thres or conf2 < conf_thres:
continue
if pos1[0] % shape[1] == 0 or pos1[1] % shape[0] == 0 or pos1[0] < 0 or pos1[1] < 0:
continue
if pos2[0] % shape[1] == 0 or pos2[1] % shape[0] == 0 or pos2[0] < 0 or pos2[1] < 0:
continue
cv2.line(
self.im,
pos1,
pos2,
kpt_color or self.limb_color[i].tolist(),
thickness=int(np.ceil(self.lw / 2)),
lineType=cv2.LINE_AA,
)
if self.pil:
# Convert im back to PIL and update draw
self.fromarray(self.im)
def rectangle(self, xy, fill=None, outline=None, width: int = 1):
self.draw.rectangle(xy, fill, outline, width)
def text(self, xy, text: str, txt_color: tuple = (255, 255, 255), anchor: str = "top", box_color: tuple = ()):
if self.pil:
w, h = self.font.getsize(text)
if anchor == "bottom": # start y from font bottom
xy[1] += 1 - h
for line in text.split("\n"):
if box_color:
# Draw rectangle for each line
w, h = self.font.getsize(line)
self.draw.rectangle((xy[0], xy[1], xy[0] + w + 1, xy[1] + h + 1), fill=box_color)
self.draw.text(xy, line, fill=txt_color, font=self.font)
xy[1] += h
else:
if box_color:
w, h = cv2.getTextSize(text, 0, fontScale=self.sf, thickness=self.tf)[0]
h += 3 # add pixels to pad text
outside = xy[1] >= h # label fits outside box
p2 = xy[0] + w, xy[1] - h if outside else xy[1] + h
cv2.rectangle(self.im, xy, p2, box_color, -1, cv2.LINE_AA) # filled
cv2.putText(self.im, text, xy, 0, self.sf, txt_color, thickness=self.tf, lineType=cv2.LINE_AA)
def fromarray(self, im):
self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)
self.draw = ImageDraw.Draw(self.im)
def result(self, pil=False):
im = np.asarray(self.im) # self.im is in BGR
return Image.fromarray(im[..., ::-1]) if pil else im
def show(self, title: str | None = None):
im = Image.fromarray(np.asarray(self.im)[..., ::-1]) # Convert BGR NumPy array to RGB PIL Image
if IS_COLAB or IS_KAGGLE: # cannot use IS_JUPYTER as it runs for all IPython environments
try:
display(im) # noqa - display() function only available in ipython environments
except ImportError as e:
LOGGER.warning(f"Unable to display image in Jupyter notebooks: {e}")
else:
im.show(title=title)
def save(self, filename: str = "image.jpg"):
cv2.imwrite(filename, np.asarray(self.im))
@staticmethod
def get_bbox_dimension(bbox: tuple | list):
x_min, y_min, x_max, y_max = bbox
width = x_max - x_min
height = y_max - y_min
return width, height, width * height
@TryExcept()
@plt_settings()
def plot_labels(boxes, cls, names=(), save_dir=Path(""), on_plot=None):
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
import polars
from matplotlib.colors import LinearSegmentedColormap
# Plot dataset labels
LOGGER.info(f"Plotting labels to {save_dir / 'labels.jpg'}... ")
nc = int(cls.max() + 1) # number of classes
boxes = boxes[:1000000] # limit to 1M boxes
x = polars.DataFrame(boxes, schema=["x", "y", "width", "height"])
# Matplotlib labels
subplot_3_4_color = LinearSegmentedColormap.from_list("white_blue", ["white", "blue"])
ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
y = ax[0].hist(cls, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
for i in range(nc):
y[2].patches[i].set_color([x / 255 for x in colors(i)])
ax[0].set_ylabel("instances")
if 0 < len(names) < 30:
ax[0].set_xticks(range(len(names)))
ax[0].set_xticklabels(list(names.values()), rotation=90, fontsize=10)
ax[0].bar_label(y[2])
else:
ax[0].set_xlabel("classes")
boxes = np.column_stack([0.5 - boxes[:, 2:4] / 2, 0.5 + boxes[:, 2:4] / 2]) * 1000
img = Image.fromarray(np.ones((1000, 1000, 3), dtype=np.uint8) * 255)
for class_id, box in zip(cls[:500], boxes[:500]):
ImageDraw.Draw(img).rectangle(box.tolist(), width=1, outline=colors(class_id)) # plot
ax[1].imshow(img)
ax[1].axis("off")
ax[2].hist2d(x["x"], x["y"], bins=50, cmap=subplot_3_4_color)
ax[2].set_xlabel("x")
ax[2].set_ylabel("y")
ax[3].hist2d(x["width"], x["height"], bins=50, cmap=subplot_3_4_color)
ax[3].set_xlabel("width")
ax[3].set_ylabel("height")
for a in {0, 1, 2, 3}:
for s in {"top", "right", "left", "bottom"}:
ax[a].spines[s].set_visible(False)
fname = save_dir / "labels.jpg"
plt.savefig(fname, dpi=200)
plt.close()
if on_plot:
on_plot(fname)
def save_one_box(
xyxy,
im,
file: Path = Path("im.jpg"),
gain: float = 1.02,
pad: int = 10,
square: bool = False,
BGR: bool = False,
save: bool = True,
):
if not isinstance(xyxy, torch.Tensor): # may be list
xyxy = torch.stack(xyxy)
b = ops.xyxy2xywh(xyxy.view(-1, 4)) # boxes
if square:
b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square
b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad
xyxy = ops.xywh2xyxy(b).long()
xyxy = ops.clip_boxes(xyxy, im.shape)
grayscale = im.shape[2] == 1 # grayscale image
crop = im[int(xyxy[0, 1]) : int(xyxy[0, 3]), int(xyxy[0, 0]) : int(xyxy[0, 2]), :: (1 if BGR or grayscale else -1)]
if save:
file.parent.mkdir(parents=True, exist_ok=True) # make directory
f = str(increment_path(file).with_suffix(".jpg"))
# cv2.imwrite(f, crop) # save BGR, https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue
crop = crop.squeeze(-1) if grayscale else crop[..., ::-1] if BGR else crop
Image.fromarray(crop).save(f, quality=95, subsampling=0) # save RGB
return crop
@threaded
def plot_images(
labels: dict[str, Any],
images: torch.Tensor | np.ndarray = np.zeros((0, 3, 640, 640), dtype=np.float32),
paths: list[str] | None = None,
fname: str = "images.jpg",
names: dict[int, str] | None = None,
on_plot: Callable | None = None,
max_size: int = 1920,
max_subplots: int = 16,
save: bool = True,
conf_thres: float = 0.25,
) -> np.ndarray | None:
for k in {"cls", "bboxes", "conf", "masks", "keypoints", "batch_idx", "images"}:
if k not in labels:
continue
if k == "cls" and labels[k].ndim == 2:
labels[k] = labels[k].squeeze(1) # squeeze if shape is (n, 1)
if isinstance(labels[k], torch.Tensor):
labels[k] = labels[k].cpu().numpy()
cls = labels.get("cls", np.zeros(0, dtype=np.int64))
batch_idx = labels.get("batch_idx", np.zeros(cls.shape, dtype=np.int64))
bboxes = labels.get("bboxes", np.zeros(0, dtype=np.float32))
confs = labels.get("conf", None)
masks = labels.get("masks", np.zeros(0, dtype=np.uint8))
kpts = labels.get("keypoints", np.zeros(0, dtype=np.float32))
images = labels.get("img", images) # default to input images
if len(images) and isinstance(images, torch.Tensor):
images = images.cpu().float().numpy()
# Handle 2-ch and n-ch images
c = images.shape[1]
if c == 2:
zero = np.zeros_like(images[:, :1])
images = np.concatenate((images, zero), axis=1) # pad 2-ch with a black channel
elif c > 3:
images = images[:, :3] # crop multispectral images to first 3 channels
bs, _, h, w = images.shape # batch size, _, height, width
bs = min(bs, max_subplots) # limit plot images
ns = np.ceil(bs**0.5) # number of subplots (square)
if np.max(images[0]) <= 1:
images *= 255 # de-normalise (optional)
# Build Image
mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
for i in range(bs):
x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
mosaic[y : y + h, x : x + w, :] = images[i].transpose(1, 2, 0)
# Resize (optional)
scale = max_size / ns / max(h, w)
if scale < 1:
h = math.ceil(scale * h)
w = math.ceil(scale * w)
mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))
# Annotate
fs = int((h + w) * ns * 0.01) # font size
fs = max(fs, 18) # ensure that the font size is large enough to be easily readable.
annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=str(names))
for i in range(bs):
x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders
if paths:
annotator.text([x + 5, y + 5], text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames
if len(cls) > 0:
idx = batch_idx == i
classes = cls[idx].astype("int")
labels = confs is None
conf = confs[idx] if confs is not None else None # check for confidence presence (label vs pred)
if len(bboxes):
boxes = bboxes[idx]
if len(boxes):
if boxes[:, :4].max() <= 1.1: # if normalized with tolerance 0.1
boxes[..., [0, 2]] *= w # scale to pixels
boxes[..., [1, 3]] *= h
elif scale < 1: # absolute coords need scale if image scales
boxes[..., :4] *= scale
boxes[..., 0] += x
boxes[..., 1] += y
is_obb = boxes.shape[-1] == 5 # xywhr
boxes = ops.xywhr2xyxyxyxy(boxes) if is_obb else ops.xywh2xyxy(boxes)
for j, box in enumerate(boxes.astype(np.int64).tolist()):
c = classes[j]
color = colors(c)
c = names.get(c, c) if names else c
if labels or conf[j] > conf_thres:
label = f"{c}" if labels else f"{c} {conf[j]:.1f}"
annotator.box_label(box, label, color=color)
elif len(classes):
for c in classes:
color = colors(c)
c = names.get(c, c) if names else c
label = f"{c}" if labels else f"{c} {conf[0]:.1f}"
annotator.text([x, y], label, txt_color=color, box_color=(64, 64, 64, 128))
# Plot keypoints
if len(kpts):
kpts_ = kpts[idx].copy()
if len(kpts_):
if kpts_[..., 0].max() <= 1.01 or kpts_[..., 1].max() <= 1.01: # if normalized with tolerance .01
kpts_[..., 0] *= w # scale to pixels
kpts_[..., 1] *= h
elif scale < 1: # absolute coords need scale if image scales
kpts_ *= scale
kpts_[..., 0] += x
kpts_[..., 1] += y
for j in range(len(kpts_)):
if labels or conf[j] > conf_thres:
annotator.kpts(kpts_[j], conf_thres=conf_thres)
# Plot masks
if len(masks):
if idx.shape[0] == masks.shape[0] and masks.max() <= 1: # overlap_mask=False
image_masks = masks[idx]
else: # overlap_mask=True
image_masks = masks[[i]] # (1, 640, 640)
nl = idx.sum()
index = np.arange(1, nl + 1).reshape((nl, 1, 1))
image_masks = (image_masks == index).astype(np.float32)
im = np.asarray(annotator.im).copy()
for j in range(len(image_masks)):
if labels or conf[j] > conf_thres:
color = colors(classes[j])
mh, mw = image_masks[j].shape
if mh != h or mw != w:
mask = image_masks[j].astype(np.uint8)
mask = cv2.resize(mask, (w, h))
mask = mask.astype(bool)
else:
mask = image_masks[j].astype(bool)
try:
im[y : y + h, x : x + w, :][mask] = (
im[y : y + h, x : x + w, :][mask] * 0.4 + np.array(color) * 0.6
)
except Exception:
pass
annotator.fromarray(im)
if not save:
return np.asarray(annotator.im)
annotator.im.save(fname) # save
if on_plot:
on_plot(fname)
@plt_settings()
def plot_results(file: str = "path/to/results.csv", dir: str = "", on_plot: Callable | None = None):
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
import polars as pl
from scipy.ndimage import gaussian_filter1d
save_dir = Path(file).parent if file else Path(dir)
files = list(save_dir.glob("results*.csv"))
assert len(files), f"No results.csv files found in {save_dir.resolve()}, nothing to plot."
loss_keys, metric_keys = [], []
for i, f in enumerate(files):
try:
data = pl.read_csv(f, infer_schema_length=None)
if i == 0:
for c in data.columns:
if "loss" in c:
loss_keys.append(c)
elif "metric" in c:
metric_keys.append(c)
loss_mid, metric_mid = len(loss_keys) // 2, len(metric_keys) // 2
columns = (
loss_keys[:loss_mid] + metric_keys[:metric_mid] + loss_keys[loss_mid:] + metric_keys[metric_mid:]
)
fig, ax = plt.subplots(2, len(columns) // 2, figsize=(len(columns) + 2, 6), tight_layout=True)
ax = ax.ravel()
x = data.select(data.columns[0]).to_numpy().flatten()
for i, j in enumerate(columns):
y = data.select(j).to_numpy().flatten().astype("float")
ax[i].plot(x, y, marker=".", label=f.stem, linewidth=2, markersize=8) # actual results
ax[i].plot(x, gaussian_filter1d(y, sigma=3), ":", label="smooth", linewidth=2) # smoothing line
ax[i].set_title(j, fontsize=12)
except Exception as e:
LOGGER.error(f"Plotting error for {f}: {e}")
ax[1].legend()
fname = save_dir / "results.png"
fig.savefig(fname, dpi=200)
plt.close()
if on_plot:
on_plot(fname)
def plt_color_scatter(v, f, bins: int = 20, cmap: str = "viridis", alpha: float = 0.8, edgecolors: str = "none"):
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
# Calculate 2D histogram and corresponding colors
hist, xedges, yedges = np.histogram2d(v, f, bins=bins)
colors = [
hist[
min(np.digitize(v[i], xedges, right=True) - 1, hist.shape[0] - 1),
min(np.digitize(f[i], yedges, right=True) - 1, hist.shape[1] - 1),
]
for i in range(len(v))
]
# Scatter plot
plt.scatter(v, f, c=colors, cmap=cmap, alpha=alpha, edgecolors=edgecolors)
@plt_settings()
def plot_tune_results(csv_file: str = "tune_results.csv", exclude_zero_fitness_points: bool = True):
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
import polars as pl
from scipy.ndimage import gaussian_filter1d
def _save_one_file(file):
plt.savefig(file, dpi=200)
plt.close()
LOGGER.info(f"Saved {file}")
# Scatter plots for each hyperparameter
csv_file = Path(csv_file)
data = pl.read_csv(csv_file, infer_schema_length=None)
num_metrics_columns = 1
keys = [x.strip() for x in data.columns][num_metrics_columns:]
x = data.to_numpy()
fitness = x[:, 0] # fitness
if exclude_zero_fitness_points:
mask = fitness > 0 # exclude zero-fitness points
x, fitness = x[mask], fitness[mask]
if len(fitness) == 0:
LOGGER.warning("No valid fitness values to plot (all iterations may have failed)")
return
# Iterative sigma rejection on lower bound only
for _ in range(3): # max 3 iterations
mean, std = fitness.mean(), fitness.std()
lower_bound = mean - 3 * std
mask = fitness >= lower_bound
if mask.all(): # no more outliers
break
x, fitness = x[mask], fitness[mask]
j = np.argmax(fitness) # max fitness index
n = math.ceil(len(keys) ** 0.5) # columns and rows in plot
plt.figure(figsize=(10, 10), tight_layout=True)
for i, k in enumerate(keys):
v = x[:, i + num_metrics_columns]
mu = v[j] # best single result
plt.subplot(n, n, i + 1)
plt_color_scatter(v, fitness, cmap="viridis", alpha=0.8, edgecolors="none")
plt.plot(mu, fitness.max(), "k+", markersize=15)
plt.title(f"{k} = {mu:.3g}", fontdict={"size": 9}) # limit to 40 characters
plt.tick_params(axis="both", labelsize=8) # Set axis label size to 8
if i % n != 0:
plt.yticks([])
_save_one_file(csv_file.with_name("tune_scatter_plots.png"))
# Fitness vs iteration
x = range(1, len(fitness) + 1)
plt.figure(figsize=(10, 6), tight_layout=True)
plt.plot(x, fitness, marker="o", linestyle="none", label="fitness")
plt.plot(x, gaussian_filter1d(fitness, sigma=3), ":", label="smoothed", linewidth=2) # smoothing line
plt.title("Fitness vs Iteration")
plt.xlabel("Iteration")
plt.ylabel("Fitness")
plt.grid(True)
plt.legend()
_save_one_file(csv_file.with_name("tune_fitness.png"))
@plt_settings()
def feature_visualization(x, module_type: str, stage: int, n: int = 32, save_dir: Path = Path("runs/detect/exp")):
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
for m in {"Detect", "Segment", "Pose", "Classify", "OBB", "RTDETRDecoder"}: # all model heads
if m in module_type:
return
if isinstance(x, torch.Tensor):
_, channels, height, width = x.shape # batch, channels, height, width
if height > 1 and width > 1:
f = save_dir / f"stage{stage}_{module_type.rsplit('.', 1)[-1]}_features.png" # filename
blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels
n = min(n, channels) # number of plots
_, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols
ax = ax.ravel()
plt.subplots_adjust(wspace=0.05, hspace=0.05)
for i in range(n):
ax[i].imshow(blocks[i].squeeze()) # cmap='gray'
ax[i].axis("off")
LOGGER.info(f"Saving {f}... ({n}/{channels})")
plt.savefig(f, dpi=300, bbox_inches="tight")
plt.close()
np.save(str(f.with_suffix(".npy")), x[0].cpu().numpy()) # npy save | --- +++ @@ -19,8 +19,80 @@
class Colors:
+ """Ultralytics color palette for visualization and plotting.
+
+ This class provides methods to work with the Ultralytics color palette, including converting hex color codes to RGB
+ values and accessing predefined color schemes for object detection and pose estimation.
+
+ ## Ultralytics Color Palette
+
+ | Index | Color | HEX | RGB |
+ |-------|-------------------------------------------------------------------|-----------|-------------------|
+ | 0 | <i class="fa-solid fa-square fa-2xl" style="color: #042aff;"></i> | `#042aff` | (4, 42, 255) |
+ | 1 | <i class="fa-solid fa-square fa-2xl" style="color: #0bdbeb;"></i> | `#0bdbeb` | (11, 219, 235) |
+ | 2 | <i class="fa-solid fa-square fa-2xl" style="color: #f3f3f3;"></i> | `#f3f3f3` | (243, 243, 243) |
+ | 3 | <i class="fa-solid fa-square fa-2xl" style="color: #00dfb7;"></i> | `#00dfb7` | (0, 223, 183) |
+ | 4 | <i class="fa-solid fa-square fa-2xl" style="color: #111f68;"></i> | `#111f68` | (17, 31, 104) |
+ | 5 | <i class="fa-solid fa-square fa-2xl" style="color: #ff6fdd;"></i> | `#ff6fdd` | (255, 111, 221) |
+ | 6 | <i class="fa-solid fa-square fa-2xl" style="color: #ff444f;"></i> | `#ff444f` | (255, 68, 79) |
+ | 7 | <i class="fa-solid fa-square fa-2xl" style="color: #cced00;"></i> | `#cced00` | (204, 237, 0) |
+ | 8 | <i class="fa-solid fa-square fa-2xl" style="color: #00f344;"></i> | `#00f344` | (0, 243, 68) |
+ | 9 | <i class="fa-solid fa-square fa-2xl" style="color: #bd00ff;"></i> | `#bd00ff` | (189, 0, 255) |
+ | 10 | <i class="fa-solid fa-square fa-2xl" style="color: #00b4ff;"></i> | `#00b4ff` | (0, 180, 255) |
+ | 11 | <i class="fa-solid fa-square fa-2xl" style="color: #dd00ba;"></i> | `#dd00ba` | (221, 0, 186) |
+ | 12 | <i class="fa-solid fa-square fa-2xl" style="color: #00ffff;"></i> | `#00ffff` | (0, 255, 255) |
+ | 13 | <i class="fa-solid fa-square fa-2xl" style="color: #26c000;"></i> | `#26c000` | (38, 192, 0) |
+ | 14 | <i class="fa-solid fa-square fa-2xl" style="color: #01ffb3;"></i> | `#01ffb3` | (1, 255, 179) |
+ | 15 | <i class="fa-solid fa-square fa-2xl" style="color: #7d24ff;"></i> | `#7d24ff` | (125, 36, 255) |
+ | 16 | <i class="fa-solid fa-square fa-2xl" style="color: #7b0068;"></i> | `#7b0068` | (123, 0, 104) |
+ | 17 | <i class="fa-solid fa-square fa-2xl" style="color: #ff1b6c;"></i> | `#ff1b6c` | (255, 27, 108) |
+ | 18 | <i class="fa-solid fa-square fa-2xl" style="color: #fc6d2f;"></i> | `#fc6d2f` | (252, 109, 47) |
+ | 19 | <i class="fa-solid fa-square fa-2xl" style="color: #a2ff0b;"></i> | `#a2ff0b` | (162, 255, 11) |
+
+ ## Pose Color Palette
+
+ | Index | Color | HEX | RGB |
+ |-------|-------------------------------------------------------------------|-----------|-------------------|
+ | 0 | <i class="fa-solid fa-square fa-2xl" style="color: #ff8000;"></i> | `#ff8000` | (255, 128, 0) |
+ | 1 | <i class="fa-solid fa-square fa-2xl" style="color: #ff9933;"></i> | `#ff9933` | (255, 153, 51) |
+ | 2 | <i class="fa-solid fa-square fa-2xl" style="color: #ffb266;"></i> | `#ffb266` | (255, 178, 102) |
+ | 3 | <i class="fa-solid fa-square fa-2xl" style="color: #e6e600;"></i> | `#e6e600` | (230, 230, 0) |
+ | 4 | <i class="fa-solid fa-square fa-2xl" style="color: #ff99ff;"></i> | `#ff99ff` | (255, 153, 255) |
+ | 5 | <i class="fa-solid fa-square fa-2xl" style="color: #99ccff;"></i> | `#99ccff` | (153, 204, 255) |
+ | 6 | <i class="fa-solid fa-square fa-2xl" style="color: #ff66ff;"></i> | `#ff66ff` | (255, 102, 255) |
+ | 7 | <i class="fa-solid fa-square fa-2xl" style="color: #ff33ff;"></i> | `#ff33ff` | (255, 51, 255) |
+ | 8 | <i class="fa-solid fa-square fa-2xl" style="color: #66b2ff;"></i> | `#66b2ff` | (102, 178, 255) |
+ | 9 | <i class="fa-solid fa-square fa-2xl" style="color: #3399ff;"></i> | `#3399ff` | (51, 153, 255) |
+ | 10 | <i class="fa-solid fa-square fa-2xl" style="color: #ff9999;"></i> | `#ff9999` | (255, 153, 153) |
+ | 11 | <i class="fa-solid fa-square fa-2xl" style="color: #ff6666;"></i> | `#ff6666` | (255, 102, 102) |
+ | 12 | <i class="fa-solid fa-square fa-2xl" style="color: #ff3333;"></i> | `#ff3333` | (255, 51, 51) |
+ | 13 | <i class="fa-solid fa-square fa-2xl" style="color: #99ff99;"></i> | `#99ff99` | (153, 255, 153) |
+ | 14 | <i class="fa-solid fa-square fa-2xl" style="color: #66ff66;"></i> | `#66ff66` | (102, 255, 102) |
+ | 15 | <i class="fa-solid fa-square fa-2xl" style="color: #33ff33;"></i> | `#33ff33` | (51, 255, 51) |
+ | 16 | <i class="fa-solid fa-square fa-2xl" style="color: #00ff00;"></i> | `#00ff00` | (0, 255, 0) |
+ | 17 | <i class="fa-solid fa-square fa-2xl" style="color: #0000ff;"></i> | `#0000ff` | (0, 0, 255) |
+ | 18 | <i class="fa-solid fa-square fa-2xl" style="color: #ff0000;"></i> | `#ff0000` | (255, 0, 0) |
+ | 19 | <i class="fa-solid fa-square fa-2xl" style="color: #ffffff;"></i> | `#ffffff` | (255, 255, 255) |
+
+ !!! note "Ultralytics Brand Colors"
+
+ For Ultralytics brand colors see [https://www.ultralytics.com/brand](https://www.ultralytics.com/brand).
+ Please use the official Ultralytics colors for all marketing materials.
+
+ Attributes:
+ palette (list[tuple]): List of RGB color tuples for general use.
+ n (int): The number of colors in the palette.
+ pose_palette (np.ndarray): A specific color palette array for pose estimation with dtype np.uint8.
+
+ Examples:
+ >>> from ultralytics.utils.plotting import Colors
+ >>> colors = Colors()
+ >>> colors(5, True) # Returns BGR format: (221, 111, 255)
+ >>> colors(5, False) # Returns RGB format: (255, 111, 221)
+ """
def __init__(self):
+ """Initialize colors as hex = matplotlib.colors.TABLEAU_COLORS.values()."""
hexs = (
"042AFF",
"0BDBEB",
@@ -72,11 +144,21 @@ )
def __call__(self, i: int | torch.Tensor, bgr: bool = False) -> tuple:
+ """Return a color from the palette by index.
+
+ Args:
+ i (int | torch.Tensor): Color index.
+ bgr (bool, optional): Whether to return BGR format instead of RGB.
+
+ Returns:
+ (tuple): RGB or BGR color tuple.
+ """
c = self.palette[int(i) % self.n]
return (c[2], c[1], c[0]) if bgr else c
@staticmethod
def hex2rgb(h: str) -> tuple:
+ """Convert hex color codes to RGB values (i.e. default PIL order)."""
return tuple(int(h[1 + i : 1 + i + 2], 16) for i in (0, 2, 4))
@@ -84,6 +166,25 @@
class Annotator:
+ """Ultralytics Annotator for train/val mosaics and JPGs and predictions annotations.
+
+ Attributes:
+ im (Image.Image | np.ndarray): The image to annotate.
+ pil (bool): Whether to use PIL or cv2 for drawing annotations.
+ font (ImageFont.truetype | ImageFont.load_default): Font used for text annotations.
+ lw (int): Line width for drawing.
+ skeleton (list[list[int]]): Skeleton structure for keypoints.
+ limb_color (np.ndarray): Color palette for limbs.
+ kpt_color (np.ndarray): Color palette for keypoints.
+ dark_colors (set): Set of colors considered dark for text contrast.
+ light_colors (set): Set of colors considered light for text contrast.
+
+ Examples:
+ >>> from ultralytics.utils.plotting import Annotator
+ >>> im0 = cv2.imread("test.png")
+ >>> annotator = Annotator(im0, line_width=10)
+ >>> annotator.box_label([10, 10, 100, 100], "person", (255, 0, 0))
+ """
def __init__(
self,
@@ -94,6 +195,7 @@ pil: bool = False,
example: str = "abc",
):
+ """Initialize the Annotator class with image and line width along with color palette for keypoints and limbs."""
non_ascii = not is_ascii(example) # non-latin labels, i.e. asian, arabic, cyrillic
input_is_pil = isinstance(im, Image.Image)
self.pil = pil or non_ascii or input_is_pil
@@ -175,6 +277,21 @@ }
def get_txt_color(self, color: tuple = (128, 128, 128), txt_color: tuple = (255, 255, 255)) -> tuple:
+ """Assign text color based on background color.
+
+ Args:
+ color (tuple, optional): The background color of the rectangle for text.
+ txt_color (tuple, optional): The fallback color of the text.
+
+ Returns:
+ (tuple): Text color for label.
+
+ Examples:
+ >>> from ultralytics.utils.plotting import Annotator
+ >>> im0 = cv2.imread("test.png")
+ >>> annotator = Annotator(im0, line_width=10)
+ >>> annotator.get_txt_color(color=(104, 31, 17)) # return (255, 255, 255)
+ """
if color in self.dark_colors:
return 104, 31, 17
elif color in self.light_colors:
@@ -183,6 +300,20 @@ return txt_color
def box_label(self, box, label: str = "", color: tuple = (128, 128, 128), txt_color: tuple = (255, 255, 255)):
+ """Draw a bounding box on an image with a given label.
+
+ Args:
+ box (tuple): The bounding box coordinates (x1, y1, x2, y2).
+ label (str, optional): The text label to be displayed.
+ color (tuple, optional): The background color of the rectangle.
+ txt_color (tuple, optional): The color of the text.
+
+ Examples:
+ >>> from ultralytics.utils.plotting import Annotator
+ >>> im0 = cv2.imread("test.png")
+ >>> annotator = Annotator(im0, line_width=10)
+ >>> annotator.box_label(box=[10, 20, 30, 40], label="person")
+ """
txt_color = self.get_txt_color(color, txt_color)
if isinstance(box, torch.Tensor):
box = box.tolist()
@@ -230,6 +361,15 @@ )
def masks(self, masks, colors, im_gpu: torch.Tensor = None, alpha: float = 0.5, retina_masks: bool = False):
+ """Plot masks on image.
+
+ Args:
+ masks (torch.Tensor | np.ndarray): Predicted masks with shape [n, h, w].
+ colors (list[list[int]]): Colors for predicted masks, [[r, g, b] * n].
+ im_gpu (torch.Tensor | None): Image on GPU with shape [3, h, w], range [0, 1].
+ alpha (float, optional): Mask transparency: 0.0 fully transparent, 1.0 opaque.
+ retina_masks (bool, optional): Whether to use high resolution masks or not.
+ """
if self.pil:
# Convert to numpy first
self.im = np.asarray(self.im).copy()
@@ -279,6 +419,21 @@ conf_thres: float = 0.25,
kpt_color: tuple | None = None,
):
+ """Plot keypoints on the image.
+
+ Args:
+ kpts (torch.Tensor): Keypoints, shape [17, 3] (x, y, confidence).
+ shape (tuple, optional): Image shape (h, w).
+ radius (int, optional): Keypoint radius.
+ kpt_line (bool, optional): Draw lines between keypoints.
+ conf_thres (float, optional): Confidence threshold.
+ kpt_color (tuple, optional): Keypoint color.
+
+ Notes:
+ - `kpt_line=True` currently only supports human pose plotting.
+ - Modifies self.im in-place.
+ - If self.pil is True, converts image to numpy array and back to PIL.
+ """
radius = radius if radius is not None else self.lw
if self.pil:
# Convert to numpy first
@@ -323,9 +478,19 @@ self.fromarray(self.im)
def rectangle(self, xy, fill=None, outline=None, width: int = 1):
+ """Add rectangle to image (PIL-only)."""
self.draw.rectangle(xy, fill, outline, width)
def text(self, xy, text: str, txt_color: tuple = (255, 255, 255), anchor: str = "top", box_color: tuple = ()):
+ """Add text to an image using PIL or cv2.
+
+ Args:
+ xy (list[int]): Top-left coordinates for text placement.
+ text (str): Text to be drawn.
+ txt_color (tuple, optional): Text color.
+ anchor (str, optional): Text anchor position ('top' or 'bottom').
+ box_color (tuple, optional): Box background color with optional alpha.
+ """
if self.pil:
w, h = self.font.getsize(text)
if anchor == "bottom": # start y from font bottom
@@ -347,14 +512,17 @@ cv2.putText(self.im, text, xy, 0, self.sf, txt_color, thickness=self.tf, lineType=cv2.LINE_AA)
def fromarray(self, im):
+ """Update `self.im` from a NumPy array or PIL image."""
self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)
self.draw = ImageDraw.Draw(self.im)
def result(self, pil=False):
+ """Return annotated image as array or PIL image."""
im = np.asarray(self.im) # self.im is in BGR
return Image.fromarray(im[..., ::-1]) if pil else im
def show(self, title: str | None = None):
+ """Show the annotated image."""
im = Image.fromarray(np.asarray(self.im)[..., ::-1]) # Convert BGR NumPy array to RGB PIL Image
if IS_COLAB or IS_KAGGLE: # cannot use IS_JUPYTER as it runs for all IPython environments
try:
@@ -365,10 +533,27 @@ im.show(title=title)
def save(self, filename: str = "image.jpg"):
+ """Save the annotated image to 'filename'."""
cv2.imwrite(filename, np.asarray(self.im))
@staticmethod
def get_bbox_dimension(bbox: tuple | list):
+ """Calculate the dimensions and area of a bounding box.
+
+ Args:
+ bbox (tuple | list): Bounding box coordinates in the format (x_min, y_min, x_max, y_max).
+
+ Returns:
+ width (float): Width of the bounding box.
+ height (float): Height of the bounding box.
+ area (float): Area enclosed by the bounding box.
+
+ Examples:
+ >>> from ultralytics.utils.plotting import Annotator
+ >>> im0 = cv2.imread("test.png")
+ >>> annotator = Annotator(im0, line_width=10)
+ >>> annotator.get_bbox_dimension(bbox=[10, 20, 30, 40])
+ """
x_min, y_min, x_max, y_max = bbox
width = x_max - x_min
height = y_max - y_min
@@ -378,6 +563,15 @@ @TryExcept()
@plt_settings()
def plot_labels(boxes, cls, names=(), save_dir=Path(""), on_plot=None):
+ """Plot training labels including class histograms and box statistics.
+
+ Args:
+ boxes (np.ndarray): Bounding box coordinates in format [x, y, width, height].
+ cls (np.ndarray): Class indices.
+ names (dict, optional): Dictionary mapping class indices to class names.
+ save_dir (Path, optional): Directory to save the plot.
+ on_plot (Callable, optional): Function to call after plot is saved.
+ """
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
import polars
from matplotlib.colors import LinearSegmentedColormap
@@ -435,6 +629,31 @@ BGR: bool = False,
save: bool = True,
):
+ """Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop.
+
+ This function takes a bounding box and an image, and then saves a cropped portion of the image according to the
+ bounding box. Optionally, the crop can be squared, and the function allows for gain and padding adjustments to the
+ bounding box.
+
+ Args:
+ xyxy (torch.Tensor | list): A tensor or list representing the bounding box in xyxy format.
+ im (np.ndarray): The input image.
+ file (Path, optional): The path where the cropped image will be saved.
+ gain (float, optional): A multiplicative factor to increase the size of the bounding box.
+ pad (int, optional): The number of pixels to add to the width and height of the bounding box.
+ square (bool, optional): If True, the bounding box will be transformed into a square.
+ BGR (bool, optional): If True, the image will be returned in BGR format, otherwise in RGB.
+ save (bool, optional): If True, the cropped image will be saved to disk.
+
+ Returns:
+ (np.ndarray): The cropped image.
+
+ Examples:
+ >>> from ultralytics.utils.plotting import save_one_box
+ >>> xyxy = [50, 50, 150, 150]
+ >>> im = cv2.imread("image.jpg")
+ >>> cropped_im = save_one_box(xyxy, im, file="cropped.jpg", square=True)
+ """
if not isinstance(xyxy, torch.Tensor): # may be list
xyxy = torch.stack(xyxy)
b = ops.xyxy2xywh(xyxy.view(-1, 4)) # boxes
@@ -467,6 +686,34 @@ save: bool = True,
conf_thres: float = 0.25,
) -> np.ndarray | None:
+ """Plot image grid with labels, bounding boxes, masks, and keypoints.
+
+ Args:
+ labels (dict[str, Any]): Dictionary containing detection data with keys like 'cls', 'bboxes', 'conf', 'masks',
+ 'keypoints', 'batch_idx', 'img'.
+ images (torch.Tensor | np.ndarray): Batch of images to plot. Shape: (batch_size, channels, height, width).
+ paths (list[str] | None): List of file paths for each image in the batch.
+ fname (str): Output filename for the plotted image grid.
+ names (dict[int, str] | None): Dictionary mapping class indices to class names.
+ on_plot (Callable | None): Callback function to be called after saving the plot.
+ max_size (int): Maximum size of the output image grid.
+ max_subplots (int): Maximum number of subplots in the image grid.
+ save (bool): Whether to save the plotted image grid to a file.
+ conf_thres (float): Confidence threshold for displaying detections.
+
+ Returns:
+ (np.ndarray | None): Plotted image grid as a numpy array if save is False, None otherwise.
+
+ Notes:
+ This function supports both tensor and numpy array inputs. It will automatically
+ convert tensor inputs to numpy arrays for processing.
+
+ Channel Support:
+ - 1 channel: Grayscale
+ - 2 channels: Third channel added as zeros
+ - 3 channels: Used as-is (standard RGB)
+ - 4+ channels: Cropped to first 3 channels
+ """
for k in {"cls", "bboxes", "conf", "masks", "keypoints", "batch_idx", "images"}:
if k not in labels:
continue
@@ -607,6 +854,19 @@
@plt_settings()
def plot_results(file: str = "path/to/results.csv", dir: str = "", on_plot: Callable | None = None):
+ """Plot training results from a results CSV file. The function supports various types of data including
+ segmentation, pose estimation, and classification. Plots are saved as 'results.png' in the directory where the
+ CSV is located.
+
+ Args:
+ file (str, optional): Path to the CSV file containing the training results.
+ dir (str, optional): Directory where the CSV file is located if 'file' is not provided.
+ on_plot (Callable, optional): Callback function to be executed after plotting. Takes filename as an argument.
+
+ Examples:
+ >>> from ultralytics.utils.plotting import plot_results
+ >>> plot_results("path/to/results.csv")
+ """
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
import polars as pl
from scipy.ndimage import gaussian_filter1d
@@ -648,6 +908,21 @@
def plt_color_scatter(v, f, bins: int = 20, cmap: str = "viridis", alpha: float = 0.8, edgecolors: str = "none"):
+ """Plot a scatter plot with points colored based on a 2D histogram.
+
+ Args:
+ v (array-like): Values for the x-axis.
+ f (array-like): Values for the y-axis.
+ bins (int, optional): Number of bins for the histogram.
+ cmap (str, optional): Colormap for the scatter plot.
+ alpha (float, optional): Alpha for the scatter plot.
+ edgecolors (str, optional): Edge colors for the scatter plot.
+
+ Examples:
+ >>> v = np.random.rand(100)
+ >>> f = np.random.rand(100)
+ >>> plt_color_scatter(v, f)
+ """
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
# Calculate 2D histogram and corresponding colors
@@ -666,11 +941,23 @@
@plt_settings()
def plot_tune_results(csv_file: str = "tune_results.csv", exclude_zero_fitness_points: bool = True):
+ """Plot the evolution results stored in a 'tune_results.csv' file. The function generates a scatter plot for each
+ key in the CSV, color-coded based on fitness scores. The best-performing configurations are highlighted on
+ the plots.
+
+ Args:
+ csv_file (str, optional): Path to the CSV file containing the tuning results.
+ exclude_zero_fitness_points (bool, optional): Don't include points with zero fitness in tuning plots.
+
+ Examples:
+ >>> plot_tune_results("path/to/tune_results.csv")
+ """
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
import polars as pl
from scipy.ndimage import gaussian_filter1d
def _save_one_file(file):
+ """Save one matplotlib plot to 'file'."""
plt.savefig(file, dpi=200)
plt.close()
LOGGER.info(f"Saved {file}")
@@ -726,6 +1013,15 @@
@plt_settings()
def feature_visualization(x, module_type: str, stage: int, n: int = 32, save_dir: Path = Path("runs/detect/exp")):
+ """Visualize feature maps of a given model module during inference.
+
+ Args:
+ x (torch.Tensor): Features to be visualized.
+ module_type (str): Module type.
+ stage (int): Module stage within the model.
+ n (int, optional): Maximum number of feature maps to plot.
+ save_dir (Path, optional): Directory to save results.
+ """
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
for m in {"Detect", "Segment", "Pose", "Classify", "OBB", "RTDETRDecoder"}: # all model heads
@@ -748,4 +1044,4 @@ LOGGER.info(f"Saving {f}... ({n}/{channels})")
plt.savefig(f, dpi=300, bbox_inches="tight")
plt.close()
- np.save(str(f.with_suffix(".npy")), x[0].cpu().numpy()) # npy save+ np.save(str(f.with_suffix(".npy")), x[0].cpu().numpy()) # npy save
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/plotting.py |
Help me add docstrings to my project | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import sys
import time
import torch
from ultralytics.utils import LOGGER
from ultralytics.utils.metrics import batch_probiou, box_iou
from ultralytics.utils.ops import xywh2xyxy
def non_max_suppression(
prediction,
conf_thres: float = 0.25,
iou_thres: float = 0.45,
classes=None,
agnostic: bool = False,
multi_label: bool = False,
labels=(),
max_det: int = 300,
nc: int = 0, # number of classes (optional)
max_time_img: float = 0.05,
max_nms: int = 30000,
max_wh: int = 7680,
rotated: bool = False,
end2end: bool = False,
return_idxs: bool = False,
):
# Checks
assert 0 <= conf_thres <= 1, f"Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0"
assert 0 <= iou_thres <= 1, f"Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0"
if isinstance(prediction, (list, tuple)): # YOLOv8 model in validation model, output = (inference_out, loss_out)
prediction = prediction[0] # select only inference output
if classes is not None:
classes = torch.tensor(classes, device=prediction.device)
if prediction.shape[-1] == 6 or end2end: # end-to-end model (BNC, i.e. 1,300,6)
output = [pred[pred[:, 4] > conf_thres][:max_det] for pred in prediction]
if classes is not None:
output = [pred[(pred[:, 5:6] == classes).any(1)] for pred in output]
return output
bs = prediction.shape[0] # batch size (BCN, i.e. 1,84,6300)
nc = nc or (prediction.shape[1] - 4) # number of classes
extra = prediction.shape[1] - nc - 4 # number of extra info
mi = 4 + nc # mask start index
xc = prediction[:, 4:mi].amax(1) > conf_thres # candidates
xinds = torch.arange(prediction.shape[-1], device=prediction.device).expand(bs, -1)[..., None] # to track idxs
# Settings
# min_wh = 2 # (pixels) minimum box width and height
time_limit = 2.0 + max_time_img * bs # seconds to quit after
multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
prediction = prediction.transpose(-1, -2) # shape(1,84,6300) to shape(1,6300,84)
if not rotated:
prediction[..., :4] = xywh2xyxy(prediction[..., :4]) # xywh to xyxy
t = time.time()
output = [torch.zeros((0, 6 + extra), device=prediction.device)] * bs
keepi = [torch.zeros((0, 1), device=prediction.device)] * bs # to store the kept idxs
for xi, (x, xk) in enumerate(zip(prediction, xinds)): # image index, (preds, preds indices)
# Apply constraints
# x[((x[:, 2:4] < min_wh) | (x[:, 2:4] > max_wh)).any(1), 4] = 0 # width-height
filt = xc[xi] # confidence
x = x[filt]
if return_idxs:
xk = xk[filt]
# Cat apriori labels if autolabelling
if labels and len(labels[xi]) and not rotated:
lb = labels[xi]
v = torch.zeros((len(lb), nc + extra + 4), device=x.device)
v[:, :4] = xywh2xyxy(lb[:, 1:5]) # box
v[range(len(lb)), lb[:, 0].long() + 4] = 1.0 # cls
x = torch.cat((x, v), 0)
# If none remain process next image
if not x.shape[0]:
continue
# Detections matrix nx6 (xyxy, conf, cls)
box, cls, mask = x.split((4, nc, extra), 1)
if multi_label:
i, j = torch.where(cls > conf_thres)
x = torch.cat((box[i], x[i, 4 + j, None], j[:, None].float(), mask[i]), 1)
if return_idxs:
xk = xk[i]
else: # best class only
conf, j = cls.max(1, keepdim=True)
filt = conf.view(-1) > conf_thres
x = torch.cat((box, conf, j.float(), mask), 1)[filt]
if return_idxs:
xk = xk[filt]
# Filter by class
if classes is not None:
filt = (x[:, 5:6] == classes).any(1)
x = x[filt]
if return_idxs:
xk = xk[filt]
# Check shape
n = x.shape[0] # number of boxes
if not n: # no boxes
continue
if n > max_nms: # excess boxes
filt = x[:, 4].argsort(descending=True)[:max_nms] # sort by confidence and remove excess boxes
x = x[filt]
if return_idxs:
xk = xk[filt]
c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
scores = x[:, 4] # scores
if rotated:
boxes = torch.cat((x[:, :2] + c, x[:, 2:4], x[:, -1:]), dim=-1) # xywhr
i = TorchNMS.fast_nms(boxes, scores, iou_thres, iou_func=batch_probiou)
else:
boxes = x[:, :4] + c # boxes (offset by class)
# Speed strategy: torchvision for val or already loaded (faster), TorchNMS for predict (lower latency)
if "torchvision" in sys.modules:
import torchvision # scope as slow import
i = torchvision.ops.nms(boxes, scores, iou_thres)
else:
i = TorchNMS.nms(boxes, scores, iou_thres)
i = i[:max_det] # limit detections
output[xi] = x[i]
if return_idxs:
keepi[xi] = xk[i].view(-1)
if (time.time() - t) > time_limit:
LOGGER.warning(f"NMS time limit {time_limit:.3f}s exceeded")
break # time limit exceeded
return (output, keepi) if return_idxs else output
class TorchNMS:
@staticmethod
def fast_nms(
boxes: torch.Tensor,
scores: torch.Tensor,
iou_threshold: float,
use_triu: bool = True,
iou_func=box_iou,
exit_early: bool = True,
) -> torch.Tensor:
if boxes.numel() == 0 and exit_early:
return torch.empty((0,), dtype=torch.int64, device=boxes.device)
sorted_idx = torch.argsort(scores, descending=True)
boxes = boxes[sorted_idx]
ious = iou_func(boxes, boxes)
if use_triu:
ious = ious.triu_(diagonal=1)
# NOTE: handle the case when len(boxes) hence exportable by eliminating if-else condition
pick = torch.nonzero((ious >= iou_threshold).sum(0) <= 0).squeeze_(-1)
else:
n = boxes.shape[0]
row_idx = torch.arange(n, device=boxes.device).view(-1, 1).expand(-1, n)
col_idx = torch.arange(n, device=boxes.device).view(1, -1).expand(n, -1)
upper_mask = row_idx < col_idx
ious = ious * upper_mask
# Zeroing these scores ensures the additional indices would not affect the final results
scores_ = scores[sorted_idx]
scores_[~((ious >= iou_threshold).sum(0) <= 0)] = 0
scores[sorted_idx] = scores_ # update original tensor for NMSModel
# NOTE: return indices with fixed length to avoid TFLite reshape error
pick = torch.topk(scores_, scores_.shape[0]).indices
return sorted_idx[pick]
@staticmethod
def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torch.Tensor:
if boxes.numel() == 0:
return torch.empty((0,), dtype=torch.int64, device=boxes.device)
# Pre-allocate and extract coordinates once
x1, y1, x2, y2 = boxes.unbind(1)
areas = (x2 - x1) * (y2 - y1)
# Sort by scores descending
order = scores.argsort(0, descending=True)
# Pre-allocate keep list with maximum possible size
keep = torch.zeros(order.numel(), dtype=torch.int64, device=boxes.device)
keep_idx = 0
while order.numel() > 0:
i = order[0]
keep[keep_idx] = i
keep_idx += 1
if order.numel() == 1:
break
# Vectorized IoU calculation for remaining boxes
rest = order[1:]
xx1 = torch.maximum(x1[i], x1[rest])
yy1 = torch.maximum(y1[i], y1[rest])
xx2 = torch.minimum(x2[i], x2[rest])
yy2 = torch.minimum(y2[i], y2[rest])
# Fast intersection and IoU
w = (xx2 - xx1).clamp_(min=0)
h = (yy2 - yy1).clamp_(min=0)
inter = w * h
# Early exit: skip IoU calculation if no intersection
if inter.sum() == 0:
# No overlaps with current box, keep all remaining boxes
order = rest
continue
iou = inter / (areas[i] + areas[rest] - inter)
# Keep boxes with IoU <= threshold
order = rest[iou <= iou_threshold]
return keep[:keep_idx]
@staticmethod
def batched_nms(
boxes: torch.Tensor,
scores: torch.Tensor,
idxs: torch.Tensor,
iou_threshold: float,
use_fast_nms: bool = False,
) -> torch.Tensor:
if boxes.numel() == 0:
return torch.empty((0,), dtype=torch.int64, device=boxes.device)
# Strategy: offset boxes by class index to prevent cross-class suppression
max_coordinate = boxes.max()
offsets = idxs.to(boxes) * (max_coordinate + 1)
boxes_for_nms = boxes + offsets[:, None]
return (
TorchNMS.fast_nms(boxes_for_nms, scores, iou_threshold)
if use_fast_nms
else TorchNMS.nms(boxes_for_nms, scores, iou_threshold)
) | --- +++ @@ -27,6 +27,34 @@ end2end: bool = False,
return_idxs: bool = False,
):
+ """Perform non-maximum suppression (NMS) on prediction results.
+
+ Applies NMS to filter overlapping bounding boxes based on confidence and IoU thresholds. Supports multiple detection
+ formats including standard boxes, rotated boxes, and masks.
+
+ Args:
+ prediction (torch.Tensor): Predictions with shape (batch_size, num_classes + 4 + num_masks, num_boxes)
+ containing boxes, classes, and optional masks.
+ conf_thres (float): Confidence threshold for filtering detections. Valid values are between 0.0 and 1.0.
+ iou_thres (float): IoU threshold for NMS filtering. Valid values are between 0.0 and 1.0.
+ classes (list[int], optional): List of class indices to consider. If None, all classes are considered.
+ agnostic (bool): Whether to perform class-agnostic NMS.
+ multi_label (bool): Whether each box can have multiple labels.
+ labels (list[torch.Tensor]): A priori labels for each image.
+ max_det (int): Maximum number of detections to keep per image.
+ nc (int): Number of classes. Indices after this are considered masks.
+ max_time_img (float): Maximum time in seconds for processing one image.
+ max_nms (int): Maximum number of boxes for NMS.
+ max_wh (int): Maximum box width and height in pixels.
+ rotated (bool): Whether to handle Oriented Bounding Boxes (OBB).
+ end2end (bool): Whether the model is end-to-end and doesn't require NMS.
+ return_idxs (bool): Whether to return the indices of kept detections.
+
+ Returns:
+ (list[torch.Tensor] | tuple[list[torch.Tensor], list[torch.Tensor]]): List of detections per image with shape
+ (num_boxes, 6 + num_masks) containing (x1, y1, x2, y2, confidence, class, mask1, mask2, ...). If
+ return_idxs=True, returns a tuple of (output, keepi) where keepi contains indices of kept detections.
+ """
# Checks
assert 0 <= conf_thres <= 1, f"Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0"
assert 0 <= iou_thres <= 1, f"Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0"
@@ -139,6 +167,22 @@
class TorchNMS:
+ """Ultralytics custom NMS implementation optimized for YOLO.
+
+ This class provides static methods for performing non-maximum suppression (NMS) operations on bounding boxes,
+ including standard NMS, fast NMS, and batched NMS for multi-class scenarios.
+
+ Methods:
+ fast_nms: Fast-NMS using upper triangular matrix operations.
+ nms: Optimized NMS with early termination that matches torchvision behavior exactly.
+ batched_nms: Batched NMS for class-aware suppression.
+
+ Examples:
+ Perform standard NMS on boxes and scores
+ >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
+ >>> scores = torch.tensor([0.9, 0.8])
+ >>> keep = TorchNMS.nms(boxes, scores, 0.5)
+ """
@staticmethod
def fast_nms(
@@ -149,6 +193,25 @@ iou_func=box_iou,
exit_early: bool = True,
) -> torch.Tensor:
+ """Fast-NMS implementation from https://arxiv.org/pdf/1904.02689 using upper triangular matrix operations.
+
+ Args:
+ boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
+ scores (torch.Tensor): Confidence scores with shape (N,).
+ iou_threshold (float): IoU threshold for suppression.
+ use_triu (bool): Whether to use torch.triu operator for upper triangular matrix operations.
+ iou_func (callable): Function to compute IoU between boxes.
+ exit_early (bool): Whether to exit early if there are no boxes.
+
+ Returns:
+ (torch.Tensor): Indices of boxes to keep after NMS.
+
+ Examples:
+ Apply NMS to a set of boxes
+ >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
+ >>> scores = torch.tensor([0.9, 0.8])
+ >>> keep = TorchNMS.fast_nms(boxes, scores, 0.5)
+ """
if boxes.numel() == 0 and exit_early:
return torch.empty((0,), dtype=torch.int64, device=boxes.device)
@@ -175,6 +238,22 @@
@staticmethod
def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torch.Tensor:
+ """Optimized NMS with early termination that matches torchvision behavior exactly.
+
+ Args:
+ boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
+ scores (torch.Tensor): Confidence scores with shape (N,).
+ iou_threshold (float): IoU threshold for suppression.
+
+ Returns:
+ (torch.Tensor): Indices of boxes to keep after NMS.
+
+ Examples:
+ Apply NMS to a set of boxes
+ >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
+ >>> scores = torch.tensor([0.9, 0.8])
+ >>> keep = TorchNMS.nms(boxes, scores, 0.5)
+ """
if boxes.numel() == 0:
return torch.empty((0,), dtype=torch.int64, device=boxes.device)
@@ -225,6 +304,25 @@ iou_threshold: float,
use_fast_nms: bool = False,
) -> torch.Tensor:
+ """Batched NMS for class-aware suppression.
+
+ Args:
+ boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
+ scores (torch.Tensor): Confidence scores with shape (N,).
+ idxs (torch.Tensor): Class indices with shape (N,).
+ iou_threshold (float): IoU threshold for suppression.
+ use_fast_nms (bool): Whether to use the Fast-NMS implementation.
+
+ Returns:
+ (torch.Tensor): Indices of boxes to keep after NMS.
+
+ Examples:
+ Apply batched NMS across multiple classes
+ >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
+ >>> scores = torch.tensor([0.9, 0.8])
+ >>> idxs = torch.tensor([0, 1])
+ >>> keep = TorchNMS.batched_nms(boxes, scores, idxs, 0.5)
+ """
if boxes.numel() == 0:
return torch.empty((0,), dtype=torch.int64, device=boxes.device)
@@ -237,4 +335,4 @@ TorchNMS.fast_nms(boxes_for_nms, scores, iou_threshold)
if use_fast_nms
else TorchNMS.nms(boxes_for_nms, scores, iou_threshold)
- )+ )
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/nms.py |
Generate consistent documentation across files | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import contextlib
import glob
import os
import shutil
import tempfile
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
class WorkingDirectory(contextlib.ContextDecorator):
def __init__(self, new_dir: str | Path):
self.dir = new_dir # new dir
self.cwd = Path.cwd().resolve() # current dir
def __enter__(self):
os.chdir(self.dir)
def __exit__(self, exc_type, exc_val, exc_tb):
os.chdir(self.cwd)
@contextmanager
def spaces_in_path(path: str | Path):
# If path has spaces, replace them with underscores
if " " in str(path):
string = isinstance(path, str) # input type
path = Path(path)
# Create a temporary directory and construct the new path
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir) / path.name.replace(" ", "_")
# Copy file/directory
if path.is_dir():
shutil.copytree(path, tmp_path)
elif path.is_file():
tmp_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, tmp_path)
try:
# Yield the temporary path
yield str(tmp_path) if string else tmp_path
finally:
# Copy file/directory back
if tmp_path.is_dir():
shutil.copytree(tmp_path, path, dirs_exist_ok=True)
elif tmp_path.is_file():
shutil.copy2(tmp_path, path) # Copy back the file
else:
# If there are no spaces, just yield the original path
yield path
def increment_path(path: str | Path, exist_ok: bool = False, sep: str = "", mkdir: bool = False) -> Path:
path = Path(path) # os-agnostic
if path.exists() and not exist_ok:
path, suffix = (path.with_suffix(""), path.suffix) if path.is_file() else (path, "")
# Method 1
for n in range(2, 9999):
p = f"{path}{sep}{n}{suffix}" # increment path
if not os.path.exists(p):
break
path = Path(p)
if mkdir:
path.mkdir(parents=True, exist_ok=True) # make directory
return path
def file_age(path: str | Path = __file__) -> int:
dt = datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime) # delta
return dt.days # + dt.seconds / 86400 # fractional days
def file_date(path: str | Path = __file__) -> str:
t = datetime.fromtimestamp(Path(path).stat().st_mtime)
return f"{t.year}-{t.month}-{t.day}"
def file_size(path: str | Path) -> float:
if isinstance(path, (str, Path)):
mb = 1 << 20 # bytes to MiB (1024 ** 2)
path = Path(path)
if path.is_file():
return path.stat().st_size / mb
elif path.is_dir():
return sum(f.stat().st_size for f in path.glob("**/*") if f.is_file()) / mb
return 0.0
def get_latest_run(search_dir: str = ".") -> str:
last_list = glob.glob(f"{search_dir}/**/last*.pt", recursive=True)
return max(last_list, key=os.path.getctime) if last_list else ""
def update_models(model_names: tuple = ("yolo26n.pt",), source_dir: Path = Path("."), update_names: bool = False):
from ultralytics import YOLO
from ultralytics.nn.autobackend import default_class_names
from ultralytics.utils import LOGGER
target_dir = source_dir / "updated_models"
target_dir.mkdir(parents=True, exist_ok=True) # Ensure target directory exists
for model_name in model_names:
model_path = source_dir / model_name
LOGGER.info(f"Loading model from {model_path}")
# Load model
model = YOLO(model_path)
model.half()
if update_names: # update model names from a dataset YAML
model.model.names = default_class_names("coco8.yaml")
# Define new save path
save_path = target_dir / model_name
# Save model using model.save()
LOGGER.info(f"Re-saving {model_name} model to {save_path}")
model.save(save_path) | --- +++ @@ -13,20 +13,64 @@
class WorkingDirectory(contextlib.ContextDecorator):
+ """A context manager and decorator for temporarily changing the working directory.
+
+ This class allows for the temporary change of the working directory using a context manager or decorator. It ensures
+ that the original working directory is restored after the context or decorated function completes.
+
+ Attributes:
+ dir (Path | str): The new directory to switch to.
+ cwd (Path): The original current working directory before the switch.
+
+ Methods:
+ __enter__: Changes the current directory to the specified directory.
+ __exit__: Restores the original working directory on context exit.
+
+ Examples:
+ Using as a context manager:
+ >>> with WorkingDirectory("/path/to/new/dir"):
+ ... # Perform operations in the new directory
+ ... pass
+
+ Using as a decorator:
+ >>> @WorkingDirectory("/path/to/new/dir")
+ ... def some_function():
+ ... # Perform operations in the new directory
+ ... pass
+ """
def __init__(self, new_dir: str | Path):
+ """Initialize the WorkingDirectory context manager with the target directory."""
self.dir = new_dir # new dir
self.cwd = Path.cwd().resolve() # current dir
def __enter__(self):
+ """Change the current working directory to the specified directory upon entering the context."""
os.chdir(self.dir)
def __exit__(self, exc_type, exc_val, exc_tb):
+ """Restore the original working directory when exiting the context."""
os.chdir(self.cwd)
@contextmanager
def spaces_in_path(path: str | Path):
+ """Context manager to handle paths with spaces in their names.
+
+ If a path contains spaces, it replaces them with underscores, copies the file/directory to the new path, executes
+ the context code block, then copies the file/directory back to its original location.
+
+ Args:
+ path (str | Path): The original path that may contain spaces.
+
+ Yields:
+ (Path | str): Temporary path with any spaces replaced by underscores.
+
+ Examples:
+ >>> with spaces_in_path("/path/with spaces") as new_path:
+ ... # Your code here
+ ... pass
+ """
# If path has spaces, replace them with underscores
if " " in str(path):
string = isinstance(path, str) # input type
@@ -60,6 +104,35 @@
def increment_path(path: str | Path, exist_ok: bool = False, sep: str = "", mkdir: bool = False) -> Path:
+ """Increment a file or directory path, i.e., runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
+
+ If the path exists and `exist_ok` is not True, the path will be incremented by appending a number and `sep` to the
+ end of the path. If the path is a file, the file extension will be preserved. If the path is a directory, the number
+ will be appended directly to the end of the path.
+
+ Args:
+ path (str | Path): Path to increment.
+ exist_ok (bool, optional): If True, the path will not be incremented and returned as-is.
+ sep (str, optional): Separator to use between the path and the incrementation number.
+ mkdir (bool, optional): Create a directory if it does not exist.
+
+ Returns:
+ (Path): Incremented path.
+
+ Examples:
+ Increment a directory path:
+ >>> from pathlib import Path
+ >>> path = Path("runs/exp")
+ >>> new_path = increment_path(path)
+ >>> print(new_path)
+ runs/exp2
+
+ Increment a file path:
+ >>> path = Path("runs/exp/results.txt")
+ >>> new_path = increment_path(path)
+ >>> print(new_path)
+ runs/exp/results2.txt
+ """
path = Path(path) # os-agnostic
if path.exists() and not exist_ok:
path, suffix = (path.with_suffix(""), path.suffix) if path.is_file() else (path, "")
@@ -78,16 +151,19 @@
def file_age(path: str | Path = __file__) -> int:
+ """Return days since the last modification of the specified file."""
dt = datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime) # delta
return dt.days # + dt.seconds / 86400 # fractional days
def file_date(path: str | Path = __file__) -> str:
+ """Return the file modification date in 'YYYY-M-D' format."""
t = datetime.fromtimestamp(Path(path).stat().st_mtime)
return f"{t.year}-{t.month}-{t.day}"
def file_size(path: str | Path) -> float:
+ """Return the size of a file or directory in mebibytes (MiB)."""
if isinstance(path, (str, Path)):
mb = 1 << 20 # bytes to MiB (1024 ** 2)
path = Path(path)
@@ -99,11 +175,25 @@
def get_latest_run(search_dir: str = ".") -> str:
+ """Return the path to the most recent 'last.pt' file in the specified directory for resuming training."""
last_list = glob.glob(f"{search_dir}/**/last*.pt", recursive=True)
return max(last_list, key=os.path.getctime) if last_list else ""
def update_models(model_names: tuple = ("yolo26n.pt",), source_dir: Path = Path("."), update_names: bool = False):
+ """Update and re-save specified YOLO models in an 'updated_models' subdirectory.
+
+ Args:
+ model_names (tuple, optional): Model filenames to update.
+ source_dir (Path, optional): Directory containing models and target subdirectory.
+ update_names (bool, optional): Update model names from a data YAML.
+
+ Examples:
+ Update specified YOLO models and save them in 'updated_models' subdirectory:
+ >>> from ultralytics.utils.files import update_models
+ >>> model_names = ("yolo26n.pt", "yolo11s.pt")
+ >>> update_models(model_names, source_dir=Path("/models"), update_names=True)
+ """
from ultralytics import YOLO
from ultralytics.nn.autobackend import default_class_names
from ultralytics.utils import LOGGER
@@ -126,4 +216,4 @@
# Save model using model.save()
LOGGER.info(f"Re-saving {model_name} model to {save_path}")
- model.save(save_path)+ model.save(save_path)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/files.py |
Write docstrings describing functionality | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import os
import platform
import re
import socket
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from time import time
from ultralytics.utils import ENVIRONMENT, GIT, LOGGER, PYTHON_VERSION, RANK, SETTINGS, TESTS_RUNNING, Retry, colorstr
PREFIX = colorstr("Platform: ")
# Configurable platform URL for debugging (e.g. ULTRALYTICS_PLATFORM_URL=http://localhost:3000)
PLATFORM_URL = os.getenv("ULTRALYTICS_PLATFORM_URL", "https://platform.ultralytics.com").rstrip("/")
PLATFORM_API_URL = f"{PLATFORM_URL}/api/webhooks"
def slugify(text):
if not text:
return text
return re.sub(r"-+", "-", re.sub(r"[^a-z0-9\s-]", "", str(text).lower()).replace(" ", "-")).strip("-")[:128]
try:
assert not TESTS_RUNNING # do not log pytest
assert SETTINGS.get("platform", False) is True or os.getenv("ULTRALYTICS_API_KEY") or SETTINGS.get("api_key")
_api_key = os.getenv("ULTRALYTICS_API_KEY") or SETTINGS.get("api_key")
assert _api_key # verify API key is present
import requests
from ultralytics.utils.logger import ConsoleLogger, SystemLogger
from ultralytics.utils.torch_utils import model_info_for_loggers
_executor = ThreadPoolExecutor(max_workers=10) # Bounded thread pool for async operations
except (AssertionError, ImportError):
_api_key = None
def resolve_platform_uri(uri, hard=True):
import requests
path = uri[5:] # Remove "ul://"
parts = path.split("/")
api_key = os.getenv("ULTRALYTICS_API_KEY") or SETTINGS.get("api_key")
if not api_key:
raise ValueError(f"ULTRALYTICS_API_KEY required for '{uri}'. Get key at {PLATFORM_URL}/settings")
base = PLATFORM_API_URL
headers = {"Authorization": f"Bearer {api_key}"}
# ul://username/datasets/slug
if len(parts) == 3 and parts[1] == "datasets":
username, _, slug = parts
url = f"{base}/datasets/{username}/{slug}/export"
# ul://username/project/model
elif len(parts) == 3:
username, project, model = parts
url = f"{base}/models/{username}/{project}/{model}/download"
else:
raise ValueError(f"Invalid platform URI: {uri}. Use ul://user/datasets/name or ul://user/project/model")
try:
timeout = 3600 if "/datasets/" in url else 90 # NDJSON generation can be slow for large datasets
r = requests.head(url, headers=headers, allow_redirects=False, timeout=timeout)
# Handle redirect responses (301, 302, 303, 307, 308)
if 300 <= r.status_code < 400 and "location" in r.headers:
return r.headers["location"] # Return signed URL
# Handle error responses
if r.status_code == 401:
raise ValueError(f"Invalid ULTRALYTICS_API_KEY for '{uri}'")
if r.status_code == 403:
raise PermissionError(f"Access denied for '{uri}'. Check dataset/model visibility settings.")
if r.status_code == 404:
if hard:
raise FileNotFoundError(f"Not found on platform: {uri}")
LOGGER.warning(f"Not found on platform: {uri}")
return None
if r.status_code == 409:
raise RuntimeError(f"Resource not ready: {uri}. Dataset may still be processing.")
# Unexpected response
r.raise_for_status()
raise RuntimeError(f"Unexpected response from platform for '{uri}': {r.status_code}")
except requests.exceptions.RequestException as e:
if hard:
raise ConnectionError(f"Failed to resolve {uri}: {e}") from e
LOGGER.warning(f"Failed to resolve {uri}: {e}")
return None
def _interp_plot(plot, n=101):
import numpy as np
if not plot.get("x") or not plot.get("y"):
return plot # No interpolation needed (e.g., confusion_matrix)
x, y = np.array(plot["x"]), np.array(plot["y"])
if len(x) <= n:
return plot # Already small enough
# New x values (101 points gives clean 0.01 increments: 0, 0.01, 0.02, ..., 1.0)
x_new = np.linspace(x[0], x[-1], n)
# Interpolate y values (handle both 1D and 2D arrays)
if y.ndim == 1:
y_new = np.interp(x_new, x, y)
else:
y_new = np.array([np.interp(x_new, x, yi) for yi in y])
# Also interpolate ap if present (for PR curves)
result = {**plot, "x": x_new.tolist(), "y": y_new.tolist()}
if "ap" in plot:
result["ap"] = plot["ap"] # Keep AP values as-is (per-class scalars)
return result
def _send(event, data, project, name, model_id=None, retry=2):
payload = {"event": event, "project": project, "name": name, "data": data}
if model_id:
payload["modelId"] = model_id
@Retry(times=retry, delay=1)
def post():
r = requests.post(
f"{PLATFORM_API_URL}/training/metrics",
json=payload,
headers={"Authorization": f"Bearer {_api_key}"},
timeout=30,
)
if 400 <= r.status_code < 500 and r.status_code not in {408, 429}:
LOGGER.warning(f"{PREFIX}Failed to send {event}: {r.status_code} {r.reason}")
return None # Don't retry client errors (except 408 timeout, 429 rate limit)
r.raise_for_status()
return r.json()
try:
return post()
except Exception as e:
LOGGER.debug(f"{PREFIX}Failed to send {event}: {e}")
return None
def _send_async(event, data, project, name, model_id=None):
_executor.submit(_send, event, data, project, name, model_id)
def _upload_model(model_path, project, name, progress=False, retry=1, model_id=None):
from ultralytics.utils.uploads import safe_upload
model_path = Path(model_path)
if not model_path.exists():
LOGGER.warning(f"{PREFIX}Model file not found: {model_path}")
return None
# Get signed upload URL from Platform (server sanitizes filename for storage safety)
@Retry(times=3, delay=2)
def get_signed_url():
payload = {"project": project, "name": name, "filename": model_path.name}
if model_id:
payload["modelId"] = model_id # Direct lookup avoids slug mismatch from auto-increment
r = requests.post(
f"{PLATFORM_API_URL}/models/upload",
json=payload,
headers={"Authorization": f"Bearer {_api_key}"},
timeout=30,
)
r.raise_for_status()
return r.json()
try:
data = get_signed_url()
except Exception as e:
LOGGER.warning(f"{PREFIX}Failed to get upload URL: {e}")
return None
# Upload to GCS using safe_upload with retry logic and optional progress bar
if safe_upload(file=model_path, url=data["uploadUrl"], retry=retry, progress=progress):
return data.get("gcsPath")
return None
def _upload_model_async(model_path, project, name, model_id=None):
_executor.submit(_upload_model, model_path, project, name, model_id=model_id)
def _get_environment_info():
import shutil
import psutil
import torch
from ultralytics import __version__
from ultralytics.utils.torch_utils import get_cpu_info, get_gpu_info
# Get RAM and disk totals
memory = psutil.virtual_memory()
disk_usage = shutil.disk_usage("/")
env = {
"ultralyticsVersion": __version__,
"hostname": socket.gethostname(),
"os": platform.platform(),
"environment": ENVIRONMENT,
"pythonVersion": PYTHON_VERSION,
"pythonExecutable": sys.executable,
"cpuCount": os.cpu_count() or 0,
"cpu": get_cpu_info(),
"command": " ".join(sys.argv),
"totalRamGb": round(memory.total / (1 << 30), 1), # Total RAM in GB
"totalDiskGb": round(disk_usage.total / (1 << 30), 1), # Total disk in GB
}
# Git info using cached GIT singleton (no subprocess calls)
try:
if GIT.is_repo:
if GIT.origin:
env["gitRepository"] = GIT.origin
if GIT.branch:
env["gitBranch"] = GIT.branch
if GIT.commit:
env["gitCommit"] = GIT.commit[:12] # Short hash
except Exception:
pass
# GPU info
try:
if torch.cuda.is_available():
env["gpuCount"] = torch.cuda.device_count()
env["gpuType"] = get_gpu_info(0) if torch.cuda.device_count() > 0 else None
except Exception:
pass
return env
def _get_project_name(trainer):
raw = str(trainer.args.project)
parts = raw.split("/", 1)
project = f"{parts[0]}/{slugify(parts[1])}" if len(parts) == 2 else slugify(raw)
return project, slugify(str(trainer.args.name or "train"))
def on_pretrain_routine_start(trainer):
if RANK not in {-1, 0} or not trainer.args.project:
return
project, name = _get_project_name(trainer)
LOGGER.info(f"{PREFIX}Streaming training metrics to Platform")
# Single dict for all platform callback state (like trainer.hub_session for HUB callbacks)
ctx = {"model_id": None, "last_upload": time(), "cancelled": False, "console_logger": None, "system_logger": None}
trainer.platform = ctx
# Create callback to send console output to Platform
def send_console_output(content, line_count, chunk_id):
_send_async(
"console_output",
{"chunkId": chunk_id, "content": content, "lineCount": line_count},
project,
name,
ctx["model_id"],
)
# Start console capture with batching (5 lines or 5 seconds)
ctx["console_logger"] = ConsoleLogger(batch_size=5, flush_interval=5.0, on_flush=send_console_output)
ctx["console_logger"].start_capture()
# Collect environment info (W&B-style metadata)
environment = _get_environment_info()
# Build trainArgs - callback runs before get_dataset() so args.data is still original (e.g., ul:// URIs)
# Note: model_info is sent later in on_fit_epoch_end (epoch 0) when the model is actually loaded
train_args = {k: str(v) for k, v in vars(trainer.args).items()}
# Send synchronously to get modelId for subsequent webhooks (critical, more retries)
response = _send(
"training_started",
{
"trainArgs": train_args,
"epochs": trainer.epochs,
"device": str(trainer.device),
"environment": environment,
},
project,
name,
retry=4,
)
if response and response.get("modelId"):
ctx["model_id"] = response["modelId"]
# Server returns actual slug (may differ from requested name due to auto-increment, e.g. "train" → "train-2")
if response.get("modelSlug"):
ctx["model_slug"] = response["modelSlug"]
url = f"{PLATFORM_URL}/{project}/{ctx['model_slug']}"
LOGGER.info(f"{PREFIX}View model at {url}")
# Check for immediate cancellation (cancelled before training started)
# Note: trainer.stop is set in on_pretrain_routine_end (after _setup_train resets it)
if response.get("cancelled"):
ctx["cancelled"] = True
else:
LOGGER.warning(f"{PREFIX}Failed to register training session - metrics may not sync to Platform")
def on_pretrain_routine_end(trainer):
ctx = getattr(trainer, "platform", None)
if ctx and ctx["cancelled"]:
LOGGER.info(f"{PREFIX}Training cancelled from Platform before starting ✅")
trainer.stop = True
def on_fit_epoch_end(trainer):
ctx = getattr(trainer, "platform", None)
if not ctx or RANK not in {-1, 0} or not trainer.args.project:
return
project, name = _get_project_name(trainer)
metrics = {**trainer.label_loss_items(trainer.tloss, prefix="train"), **trainer.metrics}
if trainer.optimizer and trainer.optimizer.param_groups:
metrics["lr"] = trainer.optimizer.param_groups[0]["lr"]
# Extract model info at epoch 0 (sent as separate field, not in metrics)
model_info = None
if trainer.epoch == 0:
try:
info = model_info_for_loggers(trainer)
model_info = {
"parameters": info.get("model/parameters", 0),
"gflops": info.get("model/GFLOPs", 0),
"speedMs": info.get("model/speed_PyTorch(ms)", 0),
}
except Exception:
pass
# Get system metrics (cache SystemLogger in platform context for efficiency)
system = {}
try:
if not ctx["system_logger"]:
ctx["system_logger"] = SystemLogger()
system = ctx["system_logger"].get_metrics(rates=True)
except Exception:
pass
payload = {
"epoch": trainer.epoch,
"metrics": metrics,
"system": system,
"fitness": trainer.fitness,
"best_fitness": trainer.best_fitness,
}
if model_info:
payload["modelInfo"] = model_info
def _send_and_check_cancel():
response = _send("epoch_end", payload, project, name, ctx["model_id"], retry=1)
if response and response.get("cancelled"):
LOGGER.info(f"{PREFIX}Training cancelled from Platform ✅")
trainer.stop = True
ctx["cancelled"] = True
_executor.submit(_send_and_check_cancel)
def on_model_save(trainer):
ctx = getattr(trainer, "platform", None)
if not ctx or RANK not in {-1, 0} or not trainer.args.project:
return
# Rate limit to every 15 minutes (900 seconds)
if time() - ctx["last_upload"] < 900:
return
model_path = trainer.best if trainer.best and Path(trainer.best).exists() else trainer.last
if not model_path:
return
project, name = _get_project_name(trainer)
_upload_model_async(model_path, project, name, model_id=ctx["model_id"])
ctx["last_upload"] = time()
def on_train_end(trainer):
ctx = getattr(trainer, "platform", None)
if not ctx or RANK not in {-1, 0} or not trainer.args.project:
return
project, name = _get_project_name(trainer)
if ctx["cancelled"]:
LOGGER.info(f"{PREFIX}Uploading partial results for cancelled training")
# Stop console capture
if ctx["console_logger"]:
ctx["console_logger"].stop_capture()
ctx["console_logger"] = None
# Upload best model (blocking with progress bar to ensure it completes)
gcs_path = None
model_size = None
if trainer.best and Path(trainer.best).exists():
model_size = Path(trainer.best).stat().st_size
gcs_path = _upload_model(trainer.best, project, name, progress=True, retry=3, model_id=ctx["model_id"])
if not gcs_path:
LOGGER.warning(f"{PREFIX}Model will not be available for download on Platform (upload failed)")
# Collect plots from trainer and validator, deduplicating by type
plots_by_type = {}
for info in getattr(trainer, "plots", {}).values():
if info.get("data") and info["data"].get("type"):
plots_by_type[info["data"]["type"]] = info["data"]
for info in getattr(getattr(trainer, "validator", None), "plots", {}).values():
if info.get("data") and info["data"].get("type"):
plots_by_type.setdefault(info["data"]["type"], info["data"]) # Don't overwrite trainer plots
plots = [_interp_plot(p) for p in plots_by_type.values()] # Interpolate curves to reduce size
# Get class names
names = getattr(getattr(trainer, "validator", None), "names", None) or (trainer.data or {}).get("names")
class_names = list(names.values()) if isinstance(names, dict) else list(names) if names else None
_send(
"training_complete",
{
"results": {
"metrics": {**trainer.metrics, "fitness": trainer.fitness},
"bestEpoch": getattr(trainer, "best_epoch", trainer.epoch),
"bestFitness": trainer.best_fitness,
"modelPath": gcs_path, # Only send GCS path, not local path
"modelSize": model_size,
},
"classNames": class_names,
"plots": plots,
},
project,
name,
ctx["model_id"],
retry=4, # Critical, more retries
)
url = f"{PLATFORM_URL}/{project}/{ctx.get('model_slug', name)}"
LOGGER.info(f"{PREFIX}View results at {url}")
callbacks = (
{
"on_pretrain_routine_start": on_pretrain_routine_start,
"on_pretrain_routine_end": on_pretrain_routine_end,
"on_fit_epoch_end": on_fit_epoch_end,
"on_model_save": on_model_save,
"on_train_end": on_train_end,
}
if _api_key
else {}
) | --- +++ @@ -19,6 +19,7 @@
def slugify(text):
+ """Convert text to URL-safe slug (e.g., 'My Project 1' -> 'my-project-1')."""
if not text:
return text
return re.sub(r"-+", "-", re.sub(r"[^a-z0-9\s-]", "", str(text).lower()).replace(" ", "-")).strip("-")[:128]
@@ -42,6 +43,26 @@
def resolve_platform_uri(uri, hard=True):
+ """Resolve ul:// URIs to signed URLs by authenticating with Ultralytics Platform.
+
+ Formats:
+ ul://username/datasets/slug -> Returns signed URL to NDJSON file
+ ul://username/project/model -> Returns signed URL to .pt file
+
+ Args:
+ uri (str): Platform URI starting with "ul://".
+ hard (bool): Whether to raise an error if resolution fails.
+
+ Returns:
+ (str | None): Signed URL on success, None if not found and hard=False.
+
+ Raises:
+ ValueError: If API key is missing/invalid or URI format is wrong.
+ PermissionError: If access is denied.
+ RuntimeError: If resource is not ready (e.g., dataset still processing).
+ FileNotFoundError: If resource not found and hard=True.
+ ConnectionError: If network request fails and hard=True.
+ """
import requests
path = uri[5:] # Remove "ul://"
@@ -100,6 +121,7 @@
def _interp_plot(plot, n=101):
+ """Interpolate plot curve data to n points to reduce storage size."""
import numpy as np
if not plot.get("x") or not plot.get("y"):
@@ -127,6 +149,7 @@
def _send(event, data, project, name, model_id=None, retry=2):
+ """Send event to Platform endpoint with retry logic."""
payload = {"event": event, "project": project, "name": name, "data": data}
if model_id:
payload["modelId"] = model_id
@@ -153,10 +176,12 @@
def _send_async(event, data, project, name, model_id=None):
+ """Send event asynchronously using bounded thread pool."""
_executor.submit(_send, event, data, project, name, model_id)
def _upload_model(model_path, project, name, progress=False, retry=1, model_id=None):
+ """Upload model checkpoint to Platform via signed URL."""
from ultralytics.utils.uploads import safe_upload
model_path = Path(model_path)
@@ -192,10 +217,12 @@
def _upload_model_async(model_path, project, name, model_id=None):
+ """Upload model asynchronously using bounded thread pool."""
_executor.submit(_upload_model, model_path, project, name, model_id=model_id)
def _get_environment_info():
+ """Collect comprehensive environment info using existing ultralytics utilities."""
import shutil
import psutil
@@ -246,6 +273,7 @@
def _get_project_name(trainer):
+ """Get slugified project and name from trainer args."""
raw = str(trainer.args.project)
parts = raw.split("/", 1)
project = f"{parts[0]}/{slugify(parts[1])}" if len(parts) == 2 else slugify(raw)
@@ -253,6 +281,7 @@
def on_pretrain_routine_start(trainer):
+ """Initialize Platform logging at training start."""
if RANK not in {-1, 0} or not trainer.args.project:
return
@@ -265,6 +294,7 @@
# Create callback to send console output to Platform
def send_console_output(content, line_count, chunk_id):
+ """Send batched console output to Platform webhook."""
_send_async(
"console_output",
{"chunkId": chunk_id, "content": content, "lineCount": line_count},
@@ -313,6 +343,7 @@
def on_pretrain_routine_end(trainer):
+ """Apply pre-start cancellation after _setup_train resets trainer.stop."""
ctx = getattr(trainer, "platform", None)
if ctx and ctx["cancelled"]:
LOGGER.info(f"{PREFIX}Training cancelled from Platform before starting ✅")
@@ -320,6 +351,7 @@
def on_fit_epoch_end(trainer):
+ """Log training and system metrics at epoch end."""
ctx = getattr(trainer, "platform", None)
if not ctx or RANK not in {-1, 0} or not trainer.args.project:
return
@@ -363,6 +395,7 @@ payload["modelInfo"] = model_info
def _send_and_check_cancel():
+ """Send epoch_end and check response for cancellation (runs in background thread)."""
response = _send("epoch_end", payload, project, name, ctx["model_id"], retry=1)
if response and response.get("cancelled"):
LOGGER.info(f"{PREFIX}Training cancelled from Platform ✅")
@@ -373,6 +406,7 @@
def on_model_save(trainer):
+ """Upload model checkpoint (rate limited to every 15 min)."""
ctx = getattr(trainer, "platform", None)
if not ctx or RANK not in {-1, 0} or not trainer.args.project:
return
@@ -391,6 +425,7 @@
def on_train_end(trainer):
+ """Log final results, upload best model, and send validation plot data."""
ctx = getattr(trainer, "platform", None)
if not ctx or RANK not in {-1, 0} or not trainer.args.project:
return
@@ -460,4 +495,4 @@ }
if _api_key
else {}
-)+)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/callbacks/platform.py |
Generate docstrings for this script | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import platform
import re
import subprocess
import sys
from pathlib import Path
class CPUInfo:
@staticmethod
def name() -> str:
try:
if sys.platform == "darwin":
# Query macOS sysctl for the CPU brand string
s = subprocess.run(
["sysctl", "-n", "machdep.cpu.brand_string"], capture_output=True, text=True
).stdout.strip()
if s:
return CPUInfo._clean(s)
elif sys.platform.startswith("linux"):
# Parse /proc/cpuinfo for the first "model name" entry
p = Path("/proc/cpuinfo")
if p.exists():
for line in p.read_text(errors="ignore").splitlines():
if "model name" in line:
return CPUInfo._clean(line.split(":", 1)[1])
elif sys.platform.startswith("win"):
try:
import winreg as wr
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") as k:
val, _ = wr.QueryValueEx(k, "ProcessorNameString")
if val:
return CPUInfo._clean(val)
except Exception:
# Fall through to generic platform fallbacks on Windows registry access failure
pass
# Generic platform fallbacks
s = platform.processor() or getattr(platform.uname(), "processor", "") or platform.machine()
return CPUInfo._clean(s or "Unknown CPU")
except Exception:
# Ensure a string is always returned even on unexpected failures
s = platform.processor() or platform.machine() or ""
return CPUInfo._clean(s or "Unknown CPU")
@staticmethod
def _clean(s: str) -> str:
s = re.sub(r"\s+", " ", s.strip())
s = s.replace("(TM)", "").replace("(tm)", "").replace("(R)", "").replace("(r)", "").strip()
if m := re.search(r"(Intel.*?i\d[\w-]*) CPU @ ([\d.]+GHz)", s, re.I):
return f"{m.group(1)} {m.group(2)}"
if m := re.search(r"(AMD.*?Ryzen.*?[\w-]*) CPU @ ([\d.]+GHz)", s, re.I):
return f"{m.group(1)} {m.group(2)}"
return s
def __str__(self) -> str:
return self.name()
if __name__ == "__main__":
print(CPUInfo.name()) | --- +++ @@ -10,9 +10,27 @@
class CPUInfo:
+ """Provide cross-platform CPU brand and model information.
+
+ Query platform-specific sources to retrieve a human-readable CPU descriptor and normalize it for consistent
+ presentation across macOS, Linux, and Windows. If platform-specific probing fails, generic platform identifiers are
+ used to ensure a stable string is always returned.
+
+ Methods:
+ name: Return the normalized CPU name using platform-specific sources with robust fallbacks.
+ _clean: Normalize and prettify common vendor brand strings and frequency patterns.
+ __str__: Return the normalized CPU name for string contexts.
+
+ Examples:
+ >>> CPUInfo.name()
+ 'Apple M4 Pro'
+ >>> str(CPUInfo())
+ 'Intel Core i7-9750H 2.60GHz'
+ """
@staticmethod
def name() -> str:
+ """Return a normalized CPU model string from platform-specific sources."""
try:
if sys.platform == "darwin":
# Query macOS sysctl for the CPU brand string
@@ -49,6 +67,7 @@
@staticmethod
def _clean(s: str) -> str:
+ """Normalize and prettify a raw CPU descriptor string."""
s = re.sub(r"\s+", " ", s.strip())
s = s.replace("(TM)", "").replace("(tm)", "").replace("(R)", "").replace("(r)", "").strip()
if m := re.search(r"(Intel.*?i\d[\w-]*) CPU @ ([\d.]+GHz)", s, re.I):
@@ -58,8 +77,9 @@ return s
def __str__(self) -> str:
+ """Return the normalized CPU name."""
return self.name()
if __name__ == "__main__":
- print(CPUInfo.name())+ print(CPUInfo.name())
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/cpu.py |
Add verbose docstrings with examples | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from ultralytics.utils import emojis
class HUBModelError(Exception):
def __init__(self, message: str = "Model not found. Please check model URL and try again."):
super().__init__(emojis(message)) | --- +++ @@ -4,6 +4,32 @@
class HUBModelError(Exception):
+ """Exception raised when a model cannot be found or retrieved from Ultralytics HUB.
+
+ This custom exception is used specifically for handling errors related to model fetching in Ultralytics YOLO. The
+ error message is processed to include emojis for better user experience.
+
+ Attributes:
+ message (str): The error message displayed when the exception is raised.
+
+ Methods:
+ __init__: Initialize the HUBModelError with a custom message.
+
+ Examples:
+ >>> try:
+ ... # Code that might fail to find a model
+ ... raise HUBModelError("Custom model not found message")
+ ... except HUBModelError as e:
+ ... print(e) # Displays the emoji-enhanced error message
+ """
def __init__(self, message: str = "Model not found. Please check model URL and try again."):
- super().__init__(emojis(message))+ """Initialize a HUBModelError exception.
+
+ This exception is raised when a requested model is not found or cannot be retrieved from Ultralytics HUB. The
+ message is processed to include emojis for better user experience.
+
+ Args:
+ message (str, optional): The error message to display when the exception is raised.
+ """
+ super().__init__(emojis(message))
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/errors.py |
Add docstrings to my Python code | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import json
import random
import time
from pathlib import Path
from threading import Thread
from urllib.request import Request, urlopen
from ultralytics import SETTINGS, __version__
from ultralytics.utils import ARGV, ENVIRONMENT, GIT, IS_PIP_PACKAGE, ONLINE, PYTHON_VERSION, RANK, TESTS_RUNNING
from ultralytics.utils.downloads import GITHUB_ASSETS_NAMES
from ultralytics.utils.torch_utils import get_cpu_info
def _post(url: str, data: dict, timeout: float = 5.0) -> None:
try:
body = json.dumps(data, separators=(",", ":")).encode() # compact JSON
req = Request(url, data=body, headers={"Content-Type": "application/json"})
urlopen(req, timeout=timeout).close()
except Exception:
pass
class Events:
url = "https://www.google-analytics.com/mp/collect?measurement_id=G-X8NCJYTQXM&api_secret=QLQrATrNSwGRFRLE-cbHJw"
def __init__(self) -> None:
self.events = [] # pending events
self.rate_limit = 30.0 # rate limit (seconds)
self.t = 0.0 # last send timestamp (seconds)
self.metadata = {
"cli": Path(ARGV[0]).name == "yolo",
"install": "git" if GIT.is_repo else "pip" if IS_PIP_PACKAGE else "other",
"python": PYTHON_VERSION.rsplit(".", 1)[0], # i.e. 3.13
"CPU": get_cpu_info(),
# "GPU": get_gpu_info(index=0) if cuda else None,
"version": __version__,
"env": ENVIRONMENT,
"session_id": round(random.random() * 1e15),
"engagement_time_msec": 1000,
}
self.enabled = (
SETTINGS["sync"]
and RANK in {-1, 0}
and not TESTS_RUNNING
and ONLINE
and (IS_PIP_PACKAGE or GIT.origin == "https://github.com/ultralytics/ultralytics.git")
)
def __call__(self, cfg, device=None) -> None:
if not self.enabled:
# Events disabled, do nothing
return
# Attempt to enqueue a new event
if len(self.events) < 25: # Queue limited to 25 events to bound memory and traffic
params = {
**self.metadata,
"task": cfg.task,
"model": cfg.model if cfg.model in GITHUB_ASSETS_NAMES else "custom",
"device": str(device),
}
if cfg.mode == "export":
params["format"] = cfg.format
self.events.append({"name": cfg.mode, "params": params})
# Check rate limit and return early if under limit
t = time.time()
if (t - self.t) < self.rate_limit:
return
# Overrate limit: send a snapshot of queued events in a background thread
payload_events = list(self.events) # snapshot to avoid race with queue reset
Thread(
target=_post,
args=(self.url, {"client_id": SETTINGS["uuid"], "events": payload_events}), # SHA-256 anonymized
daemon=True,
).start()
# Reset queue and rate limit timer
self.events = []
self.t = t
events = Events() | --- +++ @@ -14,6 +14,7 @@
def _post(url: str, data: dict, timeout: float = 5.0) -> None:
+ """Send a one-shot JSON POST request."""
try:
body = json.dumps(data, separators=(",", ":")).encode() # compact JSON
req = Request(url, data=body, headers={"Content-Type": "application/json"})
@@ -23,10 +24,29 @@
class Events:
+ """Collect and send anonymous usage analytics with rate-limiting.
+
+ Event collection and transmission are enabled when sync is enabled in settings, the current process is rank -1 or 0,
+ tests are not running, the environment is online, and the installation source is either pip or the official
+ Ultralytics GitHub repository.
+
+ Attributes:
+ url (str): Measurement Protocol endpoint for receiving anonymous events.
+ events (list[dict]): In-memory queue of event payloads awaiting transmission.
+ rate_limit (float): Minimum time in seconds between POST requests.
+ t (float): Timestamp of the last transmission in seconds since the epoch.
+ metadata (dict): Static metadata describing runtime, installation source, and environment.
+ enabled (bool): Flag indicating whether analytics collection is active.
+
+ Methods:
+ __init__: Initialize the event queue, rate limiter, and runtime metadata.
+ __call__: Queue an event and trigger a non-blocking send when the rate limit elapses.
+ """
url = "https://www.google-analytics.com/mp/collect?measurement_id=G-X8NCJYTQXM&api_secret=QLQrATrNSwGRFRLE-cbHJw"
def __init__(self) -> None:
+ """Initialize the Events instance with queue, rate limiter, and environment metadata."""
self.events = [] # pending events
self.rate_limit = 30.0 # rate limit (seconds)
self.t = 0.0 # last send timestamp (seconds)
@@ -50,6 +70,12 @@ )
def __call__(self, cfg, device=None) -> None:
+ """Queue an event and flush the queue asynchronously when the rate limit elapses.
+
+ Args:
+ cfg (IterableSimpleNamespace): The configuration object containing mode and task information.
+ device (torch.device | str, optional): The device type (e.g., 'cpu', 'cuda').
+ """
if not self.enabled:
# Events disabled, do nothing
return
@@ -84,4 +110,4 @@ self.t = t
-events = Events()+events = Events()
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/events.py |
Generate consistent documentation across files | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import ast
import functools
import glob
import inspect
import math
import os
import platform
import re
import shutil
import subprocess
import sys
import time
from importlib import metadata
from pathlib import Path
from types import SimpleNamespace
import cv2
import numpy as np
import torch
from ultralytics.utils import (
ARM64,
ASSETS,
ASSETS_URL,
AUTOINSTALL,
GIT,
IS_COLAB,
IS_DOCKER,
IS_JETSON,
IS_KAGGLE,
IS_PIP_PACKAGE,
LINUX,
LOGGER,
MACOS,
ONLINE,
PYTHON_VERSION,
RKNN_CHIPS,
ROOT,
TORCH_VERSION,
TORCHVISION_VERSION,
USER_CONFIG_DIR,
WINDOWS,
Retry,
ThreadingLocked,
TryExcept,
clean_url,
colorstr,
downloads,
is_github_action_running,
url2file,
)
def parse_requirements(file_path=ROOT.parent / "requirements.txt", package=""):
if package:
requires = [x for x in metadata.distribution(package).requires if "extra == " not in x]
else:
requires = Path(file_path).read_text().splitlines()
requirements = []
for line in requires:
line = line.strip()
if line and not line.startswith("#"):
line = line.partition("#")[0].strip() # ignore inline comments
if match := re.match(r"([a-zA-Z0-9-_]+)\s*([<>!=~]+.*)?", line):
requirements.append(SimpleNamespace(name=match[1], specifier=match[2].strip() if match[2] else ""))
return requirements
def get_distribution_name(import_name: str) -> str:
for dist in metadata.distributions():
top_level = (dist.read_text("top_level.txt") or "").split()
if import_name in top_level:
return dist.metadata["Name"]
return import_name
@functools.lru_cache
def parse_version(version="0.0.0") -> tuple:
try:
return tuple(map(int, re.findall(r"\d+", version)[:3])) # '2.0.1+cpu' -> (2, 0, 1)
except Exception as e:
LOGGER.warning(f"failure for parse_version({version}), returning (0, 0, 0): {e}")
return 0, 0, 0
def is_ascii(s) -> bool:
return all(ord(c) < 128 for c in str(s))
def check_imgsz(imgsz, stride=32, min_dim=1, max_dim=2, floor=0):
# Convert stride to integer if it is a tensor
stride = int(stride.max() if isinstance(stride, torch.Tensor) else stride)
# Convert image size to list if it is an integer
if isinstance(imgsz, int):
imgsz = [imgsz]
elif isinstance(imgsz, (list, tuple)):
imgsz = list(imgsz)
elif isinstance(imgsz, str): # i.e. '640' or '[640,640]'
imgsz = [int(imgsz)] if imgsz.isnumeric() else ast.literal_eval(imgsz)
else:
raise TypeError(
f"'imgsz={imgsz}' is of invalid type {type(imgsz).__name__}. "
f"Valid imgsz types are int i.e. 'imgsz=640' or list i.e. 'imgsz=[640,640]'"
)
# Apply max_dim
if len(imgsz) > max_dim:
msg = (
"'train' and 'val' imgsz must be an integer, while 'predict' and 'export' imgsz may be a [h, w] list "
"or an integer, i.e. 'yolo export imgsz=640,480' or 'yolo export imgsz=640'"
)
if max_dim != 1:
raise ValueError(f"imgsz={imgsz} is not a valid image size. {msg}")
LOGGER.warning(f"updating to 'imgsz={max(imgsz)}'. {msg}")
imgsz = [max(imgsz)]
# Make image size a multiple of the stride
sz = [max(math.ceil(x / stride) * stride, floor) for x in imgsz]
# Print warning message if image size was updated
if sz != imgsz:
LOGGER.warning(f"imgsz={imgsz} must be multiple of max stride {stride}, updating to {sz}")
# Add missing dimensions if necessary
sz = [sz[0], sz[0]] if min_dim == 2 and len(sz) == 1 else sz[0] if min_dim == 1 and len(sz) == 1 else sz
return sz
@functools.lru_cache
def check_uv():
try:
return subprocess.run(["uv", "-V"], capture_output=True).returncode == 0
except FileNotFoundError:
return False
@functools.lru_cache
def check_version(
current: str = "0.0.0",
required: str = "0.0.0",
name: str = "version",
hard: bool = False,
verbose: bool = False,
msg: str = "",
) -> bool:
if not current: # if current is '' or None
LOGGER.warning(f"invalid check_version({current}, {required}) requested, please check values.")
return True
elif not current[0].isdigit(): # current is package name rather than version string, i.e. current='ultralytics'
try:
name = current # assigned package name to 'name' arg
current = metadata.version(current) # get version string from package name
except metadata.PackageNotFoundError as e:
if hard:
raise ModuleNotFoundError(f"{current} package is required but not installed") from e
else:
return False
if not required: # if required is '' or None
return True
if "sys_platform" in required and ( # i.e. required='<2.4.0,>=1.8.0; sys_platform == "win32"'
(WINDOWS and "win32" not in required)
or (LINUX and "linux" not in required)
or (MACOS and "macos" not in required and "darwin" not in required)
):
return True
op = ""
version = ""
result = True
c = parse_version(current) # '1.2.3' -> (1, 2, 3)
for r in required.strip(",").split(","):
op, version = re.match(r"([^0-9]*)([\d.]+)", r).groups() # split '>=22.04' -> ('>=', '22.04')
if not op:
op = ">=" # assume >= if no op passed
v = parse_version(version) # '1.2.3' -> (1, 2, 3)
if op == "==" and c != v:
result = False
elif op == "!=" and c == v:
result = False
elif op == ">=" and not (c >= v):
result = False
elif op == "<=" and not (c <= v):
result = False
elif op == ">" and not (c > v):
result = False
elif op == "<" and not (c < v):
result = False
if not result:
warning = f"{name}{required} is required, but {name}=={current} is currently installed {msg}"
if hard:
raise ModuleNotFoundError(warning) # assert version requirements met
if verbose:
LOGGER.warning(warning)
return result
def check_latest_pypi_version(package_name="ultralytics"):
import requests # scoped as slow import
try:
requests.packages.urllib3.disable_warnings() # Disable the InsecureRequestWarning
response = requests.get(f"https://pypi.org/pypi/{package_name}/json", timeout=3)
if response.status_code == 200:
return response.json()["info"]["version"]
except Exception:
return None
def check_pip_update_available():
if ONLINE and IS_PIP_PACKAGE:
try:
from ultralytics import __version__
latest = check_latest_pypi_version()
if check_version(__version__, f"<{latest}"): # check if current version is < latest version
LOGGER.info(
f"New https://pypi.org/project/ultralytics/{latest} available 😃 "
f"Update with 'pip install -U ultralytics'"
)
return True
except Exception:
pass
return False
@ThreadingLocked()
@functools.lru_cache
def check_font(font="Arial.ttf"):
from matplotlib import font_manager # scope for faster 'import ultralytics'
# Check USER_CONFIG_DIR
name = Path(font).name
file = USER_CONFIG_DIR / name
if file.exists():
return file
# Check system fonts
matches = [s for s in font_manager.findSystemFonts() if font in s]
if any(matches):
return matches[0]
# Download to USER_CONFIG_DIR if missing
url = f"{ASSETS_URL}/{name}"
if downloads.is_url(url, check=True):
downloads.safe_download(url=url, file=file)
return file
def check_python(minimum: str = "3.8.0", hard: bool = True, verbose: bool = False) -> bool:
return check_version(PYTHON_VERSION, minimum, name="Python", hard=hard, verbose=verbose)
@TryExcept()
def check_apt_requirements(requirements):
prefix = colorstr("red", "bold", "apt requirements:")
# Check which packages are missing
missing_packages = []
for package in requirements:
try:
# Use dpkg -l to check if package is installed
result = subprocess.run(["dpkg", "-l", package], capture_output=True, text=True, check=False)
# Check if package is installed (look for "ii" status)
if result.returncode != 0 or not any(
line.startswith("ii") and package in line for line in result.stdout.splitlines()
):
missing_packages.append(package)
except Exception:
# If check fails, assume package is not installed
missing_packages.append(package)
# Install missing packages if any
if missing_packages:
LOGGER.info(
f"{prefix} Ultralytics requirement{'s' * (len(missing_packages) > 1)} {missing_packages} not found, attempting AutoUpdate..."
)
# Optionally update package list first
cmd = (["sudo"] if is_sudo_available() else []) + ["apt", "update"]
result = subprocess.run(cmd, check=True, capture_output=True, text=True)
# Build and run the install command
cmd = (["sudo"] if is_sudo_available() else []) + ["apt", "install", "-y"] + missing_packages
result = subprocess.run(cmd, check=True, capture_output=True, text=True)
LOGGER.info(f"{prefix} AutoUpdate success ✅")
LOGGER.warning(f"{prefix} {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n")
@TryExcept()
def check_requirements(requirements=ROOT.parent / "requirements.txt", exclude=(), install=True, cmds=""):
prefix = colorstr("red", "bold", "requirements:")
if os.environ.get("ULTRALYTICS_SKIP_REQUIREMENTS_CHECKS", "0") == "1":
LOGGER.info(f"{prefix} ULTRALYTICS_SKIP_REQUIREMENTS_CHECKS=1 detected, skipping requirements check.")
return True
if isinstance(requirements, Path): # requirements.txt file
file = requirements.resolve()
assert file.exists(), f"{prefix} {file} not found, check failed."
requirements = [f"{x.name}{x.specifier}" for x in parse_requirements(file) if x.name not in exclude]
elif isinstance(requirements, str):
requirements = [requirements]
pkgs = []
for r in requirements:
candidates = r if isinstance(r, (list, tuple)) else [r]
satisfied = False
for candidate in candidates:
r_stripped = candidate.rpartition("/")[-1].replace(".git", "") # replace git+https://org/repo.git -> 'repo'
match = re.match(r"([a-zA-Z0-9-_]+)([<>!=~]+.*)?", r_stripped)
name, required = match[1], match[2].strip() if match[2] else ""
try:
if check_version(metadata.version(name), required):
satisfied = True
break
except (AssertionError, metadata.PackageNotFoundError):
continue
if not satisfied:
pkg = candidates[0]
if "git+" in pkg: # strip version constraints from git URLs for pip
url, sep, marker = pkg.partition(";")
pkg = re.sub(r"[<>!=~]+.*$", "", url) + sep + marker
pkgs.append(pkg)
@Retry(times=2, delay=1)
def attempt_install(packages, commands, use_uv):
if use_uv:
# Use --python to explicitly target current interpreter (venv or system)
# This ensures correct installation when VIRTUAL_ENV env var isn't set
return subprocess.check_output(
f'uv pip install --no-cache-dir --python "{sys.executable}" {packages} {commands} '
f"--index-strategy=unsafe-best-match --break-system-packages",
shell=True,
stderr=subprocess.STDOUT,
text=True,
)
return subprocess.check_output(
f"pip install --no-cache-dir {packages} {commands}", shell=True, stderr=subprocess.STDOUT, text=True
)
s = " ".join(f'"{x}"' for x in pkgs) # console string
if s:
if install and AUTOINSTALL: # check environment variable
# Note uv fails on arm64 macOS and Raspberry Pi runners
n = len(pkgs) # number of packages updates
LOGGER.info(f"{prefix} Ultralytics requirement{'s' * (n > 1)} {pkgs} not found, attempting AutoUpdate...")
try:
t = time.time()
assert ONLINE, "AutoUpdate skipped (offline)"
use_uv = not ARM64 and check_uv() # uv fails on ARM64
LOGGER.info(attempt_install(s, cmds, use_uv=use_uv))
dt = time.time() - t
LOGGER.info(f"{prefix} AutoUpdate success ✅ {dt:.1f}s")
LOGGER.warning(
f"{prefix} {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"
)
except Exception as e:
msg = f"{prefix} ❌ {e}"
if hasattr(e, "output") and e.output:
msg += f"\n{e.output}"
LOGGER.warning(msg)
return False
else:
return False
return True
def check_executorch_requirements():
# BUG executorch build on arm64 Docker requires packaging>=22.0 https://github.com/pypa/setuptools/issues/4483
if LINUX and ARM64 and IS_DOCKER:
check_requirements("packaging>=22.0")
check_requirements("executorch", cmds=f"torch=={TORCH_VERSION.split('+')[0]}")
# Pin numpy to avoid coremltools errors with numpy>=2.4.0, must be separate
check_requirements("numpy<=2.3.5")
def check_tensorrt(min_version: str = "7.0.0"):
if LINUX:
cuda_version = torch.version.cuda.split(".")[0]
check_requirements(f"tensorrt-cu{cuda_version}>={min_version},!=10.1.0")
def check_torchvision():
compatibility_table = {
"2.10": ["0.25"],
"2.9": ["0.24"],
"2.8": ["0.23"],
"2.7": ["0.22"],
"2.6": ["0.21"],
"2.5": ["0.20"],
"2.4": ["0.19"],
"2.3": ["0.18"],
"2.2": ["0.17"],
"2.1": ["0.16"],
"2.0": ["0.15"],
"1.13": ["0.14"],
"1.12": ["0.13"],
}
# Check major and minor versions
v_torch = ".".join(TORCH_VERSION.split("+", 1)[0].split(".")[:2])
if v_torch in compatibility_table:
compatible_versions = compatibility_table[v_torch]
v_torchvision = ".".join(TORCHVISION_VERSION.split("+", 1)[0].split(".")[:2])
if all(v_torchvision != v for v in compatible_versions):
LOGGER.warning(
f"torchvision=={v_torchvision} is incompatible with torch=={v_torch}.\n"
f"Run 'pip install torchvision=={compatible_versions[0]}' to fix torchvision or "
"'pip install -U torch torchvision' to update both.\n"
"For a full compatibility table see https://github.com/pytorch/vision#installation"
)
def check_suffix(file="yolo26n.pt", suffix=".pt", msg=""):
if file and suffix:
if isinstance(suffix, str):
suffix = {suffix}
for f in file if isinstance(file, (list, tuple)) else [file]:
if s := str(f).rpartition(".")[-1].lower().strip(): # file suffix
assert f".{s}" in suffix, f"{msg}{f} acceptable suffix is {suffix}, not .{s}"
def check_yolov5u_filename(file: str, verbose: bool = True) -> str:
if "yolov3" in file or "yolov5" in file:
if "u.yaml" in file:
file = file.replace("u.yaml", ".yaml") # i.e. yolov5nu.yaml -> yolov5n.yaml
elif ".pt" in file and "u" not in file:
original_file = file
file = re.sub(r"(.*yolov5([nsmlx]))\.pt", "\\1u.pt", file) # i.e. yolov5n.pt -> yolov5nu.pt
file = re.sub(r"(.*yolov5([nsmlx])6)\.pt", "\\1u.pt", file) # i.e. yolov5n6.pt -> yolov5n6u.pt
file = re.sub(r"(.*yolov3(|-tiny|-spp))\.pt", "\\1u.pt", file) # i.e. yolov3-spp.pt -> yolov3-sppu.pt
if file != original_file and verbose:
LOGGER.info(
f"PRO TIP 💡 Replace 'model={original_file}' with new 'model={file}'.\nYOLOv5 'u' models are "
f"trained with https://github.com/ultralytics/ultralytics and feature improved performance vs "
f"standard YOLOv5 models trained with https://github.com/ultralytics/yolov5.\n"
)
return file
def check_model_file_from_stem(model: str = "yolo11n") -> str | Path:
path = Path(model)
if not path.suffix and path.stem in downloads.GITHUB_ASSETS_STEMS:
return path.with_suffix(".pt") # add suffix, i.e. yolo26n -> yolo26n.pt
return model
def check_file(file, suffix="", download=True, download_dir=".", hard=True):
check_suffix(file, suffix) # optional
file = str(file).strip() # convert to string and strip spaces
file = check_yolov5u_filename(file) # yolov5n -> yolov5nu
if (
not file
or ("://" not in file and Path(file).exists()) # '://' check required in Windows Python<3.10
or file.lower().startswith("grpc://")
): # file exists or gRPC Triton images
return file
elif download and file.lower().startswith("ul://"): # Ultralytics Platform URI
from ultralytics.utils.callbacks.platform import resolve_platform_uri
url = resolve_platform_uri(file, hard=hard) # Convert to signed HTTPS URL
if url is None:
return [] # Not found, soft fail (consistent with file search behavior)
# Use URI path for unique directory structure: ul://user/project/model -> user/project/model/filename.pt
uri_path = file[5:] # Remove "ul://"
local_file = Path(download_dir) / uri_path / url2file(url)
# Always re-download NDJSON datasets (cheap, ensures fresh data after updates)
if local_file.suffix == ".ndjson":
local_file.unlink(missing_ok=True)
if local_file.exists():
LOGGER.info(f"Found {clean_url(url)} locally at {local_file}")
else:
local_file.parent.mkdir(parents=True, exist_ok=True)
downloads.safe_download(url=url, file=local_file, unzip=False)
return str(local_file)
elif download and file.lower().startswith(
("https://", "http://", "rtsp://", "rtmp://", "tcp://", "gs://")
): # download
if file.startswith("gs://"):
file = "https://storage.googleapis.com/" + file[5:] # convert gs:// to public HTTPS URL
url = file # warning: Pathlib turns :// -> :/
file = Path(download_dir) / url2file(file) # '%2F' to '/', split https://url.com/file.txt?auth
if file.exists():
LOGGER.info(f"Found {clean_url(url)} locally at {file}") # file already exists
else:
downloads.safe_download(url=url, file=file, unzip=False)
return str(file)
else: # search
files = glob.glob(str(ROOT / "**" / file), recursive=True) or glob.glob(str(ROOT.parent / file)) # find file
if not files and hard:
raise FileNotFoundError(f"'{file}' does not exist")
elif len(files) > 1 and hard:
raise FileNotFoundError(f"Multiple files match '{file}', specify exact path: {files}")
return files[0] if len(files) else [] # return file
def check_yaml(file, suffix=(".yaml", ".yml"), hard=True):
return check_file(file, suffix, hard=hard)
def check_is_path_safe(basedir: Path | str, path: Path | str) -> bool:
base_dir_resolved = Path(basedir).resolve()
path_resolved = Path(path).resolve()
return path_resolved.exists() and path_resolved.parts[: len(base_dir_resolved.parts)] == base_dir_resolved.parts
@functools.lru_cache
def check_imshow(warn=False):
try:
if LINUX:
assert not IS_COLAB and not IS_KAGGLE
assert "DISPLAY" in os.environ, "The DISPLAY environment variable isn't set."
cv2.imshow("test", np.zeros((8, 8, 3), dtype=np.uint8)) # show a small 8-pixel image
cv2.waitKey(1)
cv2.destroyAllWindows()
cv2.waitKey(1)
return True
except Exception as e:
if warn:
LOGGER.warning(f"Environment does not support cv2.imshow() or PIL Image.show()\n{e}")
return False
def check_yolo(verbose=True, device=""):
import psutil # scoped as slow import
from ultralytics.utils.torch_utils import select_device
if IS_COLAB:
shutil.rmtree("sample_data", ignore_errors=True) # remove colab /sample_data directory
if verbose:
# System info
gib = 1 << 30 # bytes per GiB
ram = psutil.virtual_memory().total
total, _used, free = shutil.disk_usage("/")
s = f"({os.cpu_count()} CPUs, {ram / gib:.1f} GB RAM, {(total - free) / gib:.1f}/{total / gib:.1f} GB disk)"
try:
from IPython import display
display.clear_output() # clear display if notebook
except ImportError:
pass
else:
s = ""
if GIT.is_repo:
check_multiple_install() # check conflicting installation if using local clone
select_device(device=device, newline=False)
LOGGER.info(f"Setup complete ✅ {s}")
def collect_system_info():
import psutil # scoped as slow import
from ultralytics.utils import ENVIRONMENT # scope to avoid circular import
from ultralytics.utils.torch_utils import get_cpu_info, get_gpu_info
gib = 1 << 30 # bytes per GiB
cuda = torch.cuda.is_available()
check_yolo()
total, _, free = shutil.disk_usage("/")
info_dict = {
"OS": platform.platform(),
"Environment": ENVIRONMENT,
"Python": PYTHON_VERSION,
"Install": "git" if GIT.is_repo else "pip" if IS_PIP_PACKAGE else "other",
"Path": str(ROOT),
"RAM": f"{psutil.virtual_memory().total / gib:.2f} GB",
"Disk": f"{(total - free) / gib:.1f}/{total / gib:.1f} GB",
"CPU": get_cpu_info(),
"CPU count": os.cpu_count(),
"GPU": get_gpu_info(index=0) if cuda else None,
"GPU count": torch.cuda.device_count() if cuda else None,
"CUDA": torch.version.cuda if cuda else None,
}
LOGGER.info("\n" + "\n".join(f"{k:<23}{v}" for k, v in info_dict.items()) + "\n")
package_info = {}
for r in parse_requirements(package=get_distribution_name("ultralytics")):
try:
current = metadata.version(r.name)
is_met = "✅ " if check_version(current, str(r.specifier), name=r.name, hard=True) else "❌ "
except metadata.PackageNotFoundError:
current = "(not installed)"
is_met = "❌ "
package_info[r.name] = f"{is_met}{current}{r.specifier}"
LOGGER.info(f"{r.name:<23}{package_info[r.name]}")
info_dict["Package Info"] = package_info
if is_github_action_running():
github_info = {
"RUNNER_OS": os.getenv("RUNNER_OS"),
"GITHUB_EVENT_NAME": os.getenv("GITHUB_EVENT_NAME"),
"GITHUB_WORKFLOW": os.getenv("GITHUB_WORKFLOW"),
"GITHUB_ACTOR": os.getenv("GITHUB_ACTOR"),
"GITHUB_REPOSITORY": os.getenv("GITHUB_REPOSITORY"),
"GITHUB_REPOSITORY_OWNER": os.getenv("GITHUB_REPOSITORY_OWNER"),
}
LOGGER.info("\n" + "\n".join(f"{k}: {v}" for k, v in github_info.items()))
info_dict["GitHub Info"] = github_info
return info_dict
def check_amp(model):
from ultralytics.utils.torch_utils import autocast
device = next(model.parameters()).device # get model device
prefix = colorstr("AMP: ")
if device.type in {"cpu", "mps"}:
return False # AMP only used on CUDA devices
else:
# GPUs that have issues with AMP
pattern = re.compile(
r"(nvidia|geforce|quadro|tesla).*?(1660|1650|1630|t400|t550|t600|t1000|t1200|t2000|k40m)", re.IGNORECASE
)
gpu = torch.cuda.get_device_name(device)
if bool(pattern.search(gpu)):
LOGGER.warning(
f"{prefix}checks failed ❌. AMP training on {gpu} GPU may cause "
f"NaN losses or zero-mAP results, so AMP will be disabled during training."
)
return False
def amp_allclose(m, im):
batch = [im] * 8
imgsz = max(256, int(model.stride.max() * 4)) # max stride P5-32 and P6-64
a = m(batch, imgsz=imgsz, device=device, verbose=False)[0].boxes.data # FP32 inference
with autocast(enabled=True):
b = m(batch, imgsz=imgsz, device=device, verbose=False)[0].boxes.data # AMP inference
del m
return a.shape == b.shape and torch.allclose(a, b.float(), atol=0.5) # close to 0.5 absolute tolerance
im = ASSETS / "bus.jpg" # image to check
LOGGER.info(f"{prefix}running Automatic Mixed Precision (AMP) checks...")
warning_msg = "Setting 'amp=True'. If you experience zero-mAP or NaN losses you can disable AMP with amp=False."
try:
from ultralytics import YOLO
assert amp_allclose(YOLO("yolo26n.pt"), im)
LOGGER.info(f"{prefix}checks passed ✅")
except ConnectionError:
LOGGER.warning(f"{prefix}checks skipped. Offline and unable to download YOLO26n for AMP checks. {warning_msg}")
except (AttributeError, ModuleNotFoundError):
LOGGER.warning(
f"{prefix}checks skipped. "
f"Unable to load YOLO26n for AMP checks due to possible Ultralytics package modifications. {warning_msg}"
)
except AssertionError:
LOGGER.error(
f"{prefix}checks failed. Anomalies were detected with AMP on your system that may lead to "
f"NaN losses or zero-mAP results, so AMP will be disabled during training."
)
return False
return True
def check_multiple_install():
import sys
try:
result = subprocess.run([sys.executable, "-m", "pip", "show", "ultralytics"], capture_output=True, text=True)
install_msg = (
f"Install your local copy in editable mode with 'pip install -e {ROOT.parent}' to avoid "
"issues. See https://docs.ultralytics.com/quickstart/"
)
if result.returncode != 0:
if "not found" in result.stderr.lower(): # Package not pip-installed but locally imported
LOGGER.warning(f"Ultralytics not found via pip but importing from: {ROOT}. {install_msg}")
return
yolo_path = (Path(re.findall(r"location:\s+(.+)", result.stdout, flags=re.I)[-1]) / "ultralytics").resolve()
if not yolo_path.samefile(ROOT.resolve()):
LOGGER.warning(
f"Multiple Ultralytics installations detected. The `yolo` command uses: {yolo_path}, "
f"but current session imports from: {ROOT}. This may cause version conflicts. {install_msg}"
)
except Exception:
return
def print_args(args: dict | None = None, show_file=True, show_func=False):
def strip_auth(v):
return clean_url(v) if (isinstance(v, str) and v.startswith("http") and len(v) > 100) else v
x = inspect.currentframe().f_back # previous frame
file, _, func, _, _ = inspect.getframeinfo(x)
if args is None: # get args automatically
args, _, _, frm = inspect.getargvalues(x)
args = {k: v for k, v in frm.items() if k in args}
try:
file = Path(file).resolve().relative_to(ROOT).with_suffix("")
except ValueError:
file = Path(file).stem
s = (f"{file}: " if show_file else "") + (f"{func}: " if show_func else "")
LOGGER.info(colorstr(s) + ", ".join(f"{k}={strip_auth(v)}" for k, v in sorted(args.items())))
def cuda_device_count() -> int:
if IS_JETSON:
# NVIDIA Jetson does not fully support nvidia-smi and therefore use PyTorch instead
return torch.cuda.device_count()
else:
try:
# Run the nvidia-smi command and capture its output
output = subprocess.check_output(
["nvidia-smi", "--query-gpu=count", "--format=csv,noheader,nounits"], encoding="utf-8"
)
# Take the first line and strip any leading/trailing white space
first_line = output.strip().split("\n", 1)[0]
return int(first_line)
except (subprocess.CalledProcessError, FileNotFoundError, ValueError):
# If the command fails, nvidia-smi is not found, or output is not an integer, assume no GPUs are available
return 0
def cuda_is_available() -> bool:
return cuda_device_count() > 0
def is_rockchip():
if LINUX and ARM64:
try:
with open("/proc/device-tree/compatible") as f:
dev_str = f.read()
*_, soc = dev_str.split(",")
if soc.replace("\x00", "").split("-", 1)[0] in RKNN_CHIPS:
return True
except OSError:
return False
else:
return False
def is_intel():
from ultralytics.utils.torch_utils import get_cpu_info
# Check CPU
if "intel" in get_cpu_info().lower():
return True
# Check GPU via xpu-smi
try:
result = subprocess.run(["xpu-smi", "discovery"], capture_output=True, text=True, timeout=5)
return "intel" in result.stdout.lower()
except Exception: # broad clause to capture all Intel GPU exception types
return False
def is_sudo_available() -> bool:
if WINDOWS:
return False
cmd = "sudo --version"
return subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
# Run checks and define constants
check_python("3.8", hard=False, verbose=True) # check python version
check_torchvision() # check torch-torchvision compatibility
# Define constants
IS_PYTHON_3_8 = PYTHON_VERSION.startswith("3.8")
IS_PYTHON_3_9 = PYTHON_VERSION.startswith("3.9")
IS_PYTHON_3_10 = PYTHON_VERSION.startswith("3.10")
IS_PYTHON_3_12 = PYTHON_VERSION.startswith("3.12")
IS_PYTHON_3_13 = PYTHON_VERSION.startswith("3.13")
IS_PYTHON_MINIMUM_3_9 = check_python("3.9", hard=False)
IS_PYTHON_MINIMUM_3_10 = check_python("3.10", hard=False)
IS_PYTHON_MINIMUM_3_12 = check_python("3.12", hard=False) | --- +++ @@ -56,6 +56,20 @@
def parse_requirements(file_path=ROOT.parent / "requirements.txt", package=""):
+ """Parse a requirements.txt file, ignoring lines that start with '#' and any text after '#'.
+
+ Args:
+ file_path (Path): Path to the requirements.txt file.
+ package (str, optional): Python package to use instead of requirements.txt file.
+
+ Returns:
+ requirements (list[SimpleNamespace]): List of parsed requirements as SimpleNamespace objects with `name` and
+ `specifier` attributes.
+
+ Examples:
+ >>> from ultralytics.utils.checks import parse_requirements
+ >>> parse_requirements(package="ultralytics")
+ """
if package:
requires = [x for x in metadata.distribution(package).requires if "extra == " not in x]
else:
@@ -73,6 +87,7 @@
def get_distribution_name(import_name: str) -> str:
+ """Get the pip distribution name for a given import name (e.g., 'cv2' -> 'opencv-python-headless')."""
for dist in metadata.distributions():
top_level = (dist.read_text("top_level.txt") or "").split()
if import_name in top_level:
@@ -82,6 +97,14 @@
@functools.lru_cache
def parse_version(version="0.0.0") -> tuple:
+ """Convert a version string to a tuple of integers, ignoring any extra non-numeric string attached to the version.
+
+ Args:
+ version (str): Version string, i.e. '2.0.1+cpu'
+
+ Returns:
+ (tuple): Tuple of integers representing the numeric part of the version, i.e. (2, 0, 1)
+ """
try:
return tuple(map(int, re.findall(r"\d+", version)[:3])) # '2.0.1+cpu' -> (2, 0, 1)
except Exception as e:
@@ -90,10 +113,31 @@
def is_ascii(s) -> bool:
+ """Check if a string is composed of only ASCII characters.
+
+ Args:
+ s (str | list | tuple | dict): Input to be checked (all are converted to string for checking).
+
+ Returns:
+ (bool): True if the string is composed only of ASCII characters, False otherwise.
+ """
return all(ord(c) < 128 for c in str(s))
def check_imgsz(imgsz, stride=32, min_dim=1, max_dim=2, floor=0):
+ """Verify image size is a multiple of the given stride in each dimension. If the image size is not a multiple of the
+ stride, update it to the nearest multiple of the stride that is greater than or equal to the given floor value.
+
+ Args:
+ imgsz (int | list[int]): Image size.
+ stride (int): Stride value.
+ min_dim (int): Minimum number of dimensions.
+ max_dim (int): Maximum number of dimensions.
+ floor (int): Minimum allowed value for image size.
+
+ Returns:
+ (list[int] | int): Updated image size.
+ """
# Convert stride to integer if it is a tensor
stride = int(stride.max() if isinstance(stride, torch.Tensor) else stride)
@@ -135,6 +179,7 @@
@functools.lru_cache
def check_uv():
+ """Check if uv package manager is installed and can run successfully."""
try:
return subprocess.run(["uv", "-V"], capture_output=True).returncode == 0
except FileNotFoundError:
@@ -150,6 +195,32 @@ verbose: bool = False,
msg: str = "",
) -> bool:
+ """Check current version against the required version or range.
+
+ Args:
+ current (str): Current version or package name to get version from.
+ required (str): Required version or range (in pip-style format).
+ name (str): Name to be used in warning message.
+ hard (bool): If True, raise a ModuleNotFoundError if the requirement is not met.
+ verbose (bool): If True, print warning message if requirement is not met.
+ msg (str): Extra message to display if verbose.
+
+ Returns:
+ (bool): True if requirement is met, False otherwise.
+
+ Examples:
+ Check if current version is exactly 22.04
+ >>> check_version(current="22.04", required="==22.04")
+
+ Check if current version is greater than or equal to 22.04
+ >>> check_version(current="22.10", required="22.04") # assumes '>=' inequality if none passed
+
+ Check if current version is less than or equal to 22.04
+ >>> check_version(current="22.04", required="<=22.04")
+
+ Check if current version is between 20.04 (inclusive) and 22.04 (exclusive)
+ >>> check_version(current="21.10", required=">20.04,<22.04")
+ """
if not current: # if current is '' or None
LOGGER.warning(f"invalid check_version({current}, {required}) requested, please check values.")
return True
@@ -204,6 +275,14 @@
def check_latest_pypi_version(package_name="ultralytics"):
+ """Return the latest version of a PyPI package without downloading or installing it.
+
+ Args:
+ package_name (str): The name of the package to find the latest version for.
+
+ Returns:
+ (str | None): The latest version of the package, or None if unavailable.
+ """
import requests # scoped as slow import
try:
@@ -216,6 +295,11 @@
def check_pip_update_available():
+ """Check if a new version of the ultralytics package is available on PyPI.
+
+ Returns:
+ (bool): True if an update is available, False otherwise.
+ """
if ONLINE and IS_PIP_PACKAGE:
try:
from ultralytics import __version__
@@ -235,6 +319,14 @@ @ThreadingLocked()
@functools.lru_cache
def check_font(font="Arial.ttf"):
+ """Find font locally or download to user's configuration directory if it does not already exist.
+
+ Args:
+ font (str): Path or name of font.
+
+ Returns:
+ (Path | str): Resolved font file path.
+ """
from matplotlib import font_manager # scope for faster 'import ultralytics'
# Check USER_CONFIG_DIR
@@ -256,11 +348,26 @@
def check_python(minimum: str = "3.8.0", hard: bool = True, verbose: bool = False) -> bool:
+ """Check current python version against the required minimum version.
+
+ Args:
+ minimum (str): Required minimum version of python.
+ hard (bool): If True, raise a ModuleNotFoundError if the requirement is not met.
+ verbose (bool): If True, print warning message if requirement is not met.
+
+ Returns:
+ (bool): Whether the installed Python version meets the minimum constraints.
+ """
return check_version(PYTHON_VERSION, minimum, name="Python", hard=hard, verbose=verbose)
@TryExcept()
def check_apt_requirements(requirements):
+ """Check if apt packages are installed and install missing ones.
+
+ Args:
+ requirements (list[str]): List of apt package names to check and install.
+ """
prefix = colorstr("red", "bold", "apt requirements:")
# Check which packages are missing
missing_packages = []
@@ -296,6 +403,31 @@
@TryExcept()
def check_requirements(requirements=ROOT.parent / "requirements.txt", exclude=(), install=True, cmds=""):
+ """Check if installed dependencies meet Ultralytics YOLO models requirements and attempt to auto-update if needed.
+
+ Args:
+ requirements (Path | str | list[str|tuple] | tuple[str]): Path to a requirements.txt file, a single package
+ requirement as a string, a list of package requirements as strings, or a list containing strings and tuples
+ of interchangeable packages.
+ exclude (tuple): Tuple of package names to exclude from checking.
+ install (bool): If True, attempt to auto-update packages that don't meet requirements.
+ cmds (str): Additional commands to pass to the pip install command when auto-updating.
+
+ Examples:
+ >>> from ultralytics.utils.checks import check_requirements
+
+ Check a requirements.txt file
+ >>> check_requirements("path/to/requirements.txt")
+
+ Check a single package
+ >>> check_requirements("ultralytics>=8.3.200", cmds="--index-url https://download.pytorch.org/whl/cpu")
+
+ Check multiple packages
+ >>> check_requirements(["numpy", "ultralytics"])
+
+ Check with interchangeable packages
+ >>> check_requirements([("onnxruntime", "onnxruntime-gpu"), "numpy"])
+ """
prefix = colorstr("red", "bold", "requirements:")
if os.environ.get("ULTRALYTICS_SKIP_REQUIREMENTS_CHECKS", "0") == "1":
@@ -334,6 +466,7 @@
@Retry(times=2, delay=1)
def attempt_install(packages, commands, use_uv):
+ """Attempt package installation with uv if available, falling back to pip."""
if use_uv:
# Use --python to explicitly target current interpreter (venv or system)
# This ensures correct installation when VIRTUAL_ENV env var isn't set
@@ -377,6 +510,7 @@
def check_executorch_requirements():
+ """Check and install ExecuTorch requirements including platform-specific dependencies."""
# BUG executorch build on arm64 Docker requires packaging>=22.0 https://github.com/pypa/setuptools/issues/4483
if LINUX and ARM64 and IS_DOCKER:
check_requirements("packaging>=22.0")
@@ -387,12 +521,22 @@
def check_tensorrt(min_version: str = "7.0.0"):
+ """Check and install TensorRT requirements including platform-specific dependencies.
+
+ Args:
+ min_version (str): Minimum supported TensorRT version (default: "7.0.0").
+ """
if LINUX:
cuda_version = torch.version.cuda.split(".")[0]
check_requirements(f"tensorrt-cu{cuda_version}>={min_version},!=10.1.0")
def check_torchvision():
+ """Check the installed versions of PyTorch and Torchvision to ensure they're compatible.
+
+ This function checks the installed versions of PyTorch and Torchvision, and warns if they're incompatible according
+ to the compatibility table based on: https://github.com/pytorch/vision#installation.
+ """
compatibility_table = {
"2.10": ["0.25"],
"2.9": ["0.24"],
@@ -424,6 +568,13 @@
def check_suffix(file="yolo26n.pt", suffix=".pt", msg=""):
+ """Check file(s) for acceptable suffix.
+
+ Args:
+ file (str | list[str]): File or list of files to check.
+ suffix (str | tuple): Acceptable suffix or tuple of suffixes.
+ msg (str): Additional message to display in case of error.
+ """
if file and suffix:
if isinstance(suffix, str):
suffix = {suffix}
@@ -433,6 +584,15 @@
def check_yolov5u_filename(file: str, verbose: bool = True) -> str:
+ """Replace legacy YOLOv5 filenames with updated YOLOv5u filenames.
+
+ Args:
+ file (str): Filename to check and potentially update.
+ verbose (bool): Whether to print information about the replacement.
+
+ Returns:
+ (str): Updated filename.
+ """
if "yolov3" in file or "yolov5" in file:
if "u.yaml" in file:
file = file.replace("u.yaml", ".yaml") # i.e. yolov5nu.yaml -> yolov5n.yaml
@@ -451,6 +611,14 @@
def check_model_file_from_stem(model: str = "yolo11n") -> str | Path:
+ """Return a model filename from a valid model stem.
+
+ Args:
+ model (str): Model stem to check.
+
+ Returns:
+ (str | Path): Model filename with appropriate suffix.
+ """
path = Path(model)
if not path.suffix and path.stem in downloads.GITHUB_ASSETS_STEMS:
return path.with_suffix(".pt") # add suffix, i.e. yolo26n -> yolo26n.pt
@@ -458,6 +626,18 @@
def check_file(file, suffix="", download=True, download_dir=".", hard=True):
+ """Search/download file (if necessary), check suffix (if provided), and return path.
+
+ Args:
+ file (str): File name or path, URL, platform URI (ul://), or GCS path (gs://).
+ suffix (str | tuple): Acceptable suffix or tuple of suffixes to validate against the file.
+ download (bool): Whether to download the file if it doesn't exist locally.
+ download_dir (str): Directory to download the file to.
+ hard (bool): Whether to raise an error if the file is not found.
+
+ Returns:
+ (str | list): Path to the file, or an empty list if not found.
+ """
check_suffix(file, suffix) # optional
file = str(file).strip() # convert to string and strip spaces
file = check_yolov5u_filename(file) # yolov5n -> yolov5nu
@@ -507,10 +687,29 @@
def check_yaml(file, suffix=(".yaml", ".yml"), hard=True):
+ """Search/download YAML file (if necessary) and return path, checking suffix.
+
+ Args:
+ file (str | Path): File name or path.
+ suffix (tuple): Tuple of acceptable YAML file suffixes.
+ hard (bool): Whether to raise an error if the file is not found or multiple files are found.
+
+ Returns:
+ (str): Path to the YAML file.
+ """
return check_file(file, suffix, hard=hard)
def check_is_path_safe(basedir: Path | str, path: Path | str) -> bool:
+ """Check if the resolved path is under the intended directory to prevent path traversal.
+
+ Args:
+ basedir (Path | str): The intended directory.
+ path (Path | str): The path to check.
+
+ Returns:
+ (bool): True if the path is safe, False otherwise.
+ """
base_dir_resolved = Path(basedir).resolve()
path_resolved = Path(path).resolve()
@@ -519,6 +718,14 @@
@functools.lru_cache
def check_imshow(warn=False):
+ """Check if environment supports image displays.
+
+ Args:
+ warn (bool): Whether to warn if environment doesn't support image displays.
+
+ Returns:
+ (bool): True if environment supports image displays, False otherwise.
+ """
try:
if LINUX:
assert not IS_COLAB and not IS_KAGGLE
@@ -535,6 +742,12 @@
def check_yolo(verbose=True, device=""):
+ """Print a human-readable YOLO software and hardware summary.
+
+ Args:
+ verbose (bool): Whether to print verbose information.
+ device (str | torch.device): Device to use for YOLO.
+ """
import psutil # scoped as slow import
from ultralytics.utils.torch_utils import select_device
@@ -565,6 +778,11 @@
def collect_system_info():
+ """Collect and print relevant system information including OS, Python, RAM, CPU, and CUDA.
+
+ Returns:
+ (dict): Dictionary containing system information.
+ """
import psutil # scoped as slow import
from ultralytics.utils import ENVIRONMENT # scope to avoid circular import
@@ -620,6 +838,23 @@
def check_amp(model):
+ """Check the PyTorch Automatic Mixed Precision (AMP) functionality of a YOLO model.
+
+ If the checks fail, it means there are anomalies with AMP on the system that may cause NaN losses or zero-mAP
+ results, so AMP will be disabled during training.
+
+ Args:
+ model (torch.nn.Module): A YOLO model instance.
+
+ Returns:
+ (bool): Returns True if the AMP functionality works correctly with YOLO model, else False.
+
+ Examples:
+ >>> from ultralytics import YOLO
+ >>> from ultralytics.utils.checks import check_amp
+ >>> model = YOLO("yolo26n.pt").model.cuda()
+ >>> check_amp(model)
+ """
from ultralytics.utils.torch_utils import autocast
device = next(model.parameters()).device # get model device
@@ -641,6 +876,7 @@ return False
def amp_allclose(m, im):
+ """All close FP32 vs AMP results."""
batch = [im] * 8
imgsz = max(256, int(model.stride.max() * 4)) # max stride P5-32 and P6-64
a = m(batch, imgsz=imgsz, device=device, verbose=False)[0].boxes.data # FP32 inference
@@ -674,6 +910,7 @@
def check_multiple_install():
+ """Check if there are multiple Ultralytics installations."""
import sys
try:
@@ -697,8 +934,16 @@
def print_args(args: dict | None = None, show_file=True, show_func=False):
+ """Print function arguments (optional args dict).
+
+ Args:
+ args (dict, optional): Arguments to print.
+ show_file (bool): Whether to show the file name.
+ show_func (bool): Whether to show the function name.
+ """
def strip_auth(v):
+ """Clean longer Ultralytics HUB URLs by stripping potential authentication information."""
return clean_url(v) if (isinstance(v, str) and v.startswith("http") and len(v) > 100) else v
x = inspect.currentframe().f_back # previous frame
@@ -715,6 +960,11 @@
def cuda_device_count() -> int:
+ """Get the number of NVIDIA GPUs available in the environment.
+
+ Returns:
+ (int): The number of NVIDIA GPUs available.
+ """
if IS_JETSON:
# NVIDIA Jetson does not fully support nvidia-smi and therefore use PyTorch instead
return torch.cuda.device_count()
@@ -735,10 +985,20 @@
def cuda_is_available() -> bool:
+ """Check if CUDA is available in the environment.
+
+ Returns:
+ (bool): True if one or more NVIDIA GPUs are available, False otherwise.
+ """
return cuda_device_count() > 0
def is_rockchip():
+ """Check if the current environment is running on a Rockchip SoC.
+
+ Returns:
+ (bool): True if running on a Rockchip SoC, False otherwise.
+ """
if LINUX and ARM64:
try:
with open("/proc/device-tree/compatible") as f:
@@ -753,6 +1013,11 @@
def is_intel():
+ """Check if the system has Intel hardware (CPU or GPU).
+
+ Returns:
+ (bool): True if Intel hardware is detected, False otherwise.
+ """
from ultralytics.utils.torch_utils import get_cpu_info
# Check CPU
@@ -768,6 +1033,11 @@
def is_sudo_available() -> bool:
+ """Check if the sudo command is available in the environment.
+
+ Returns:
+ (bool): True if the sudo command is available, False otherwise.
+ """
if WINDOWS:
return False
cmd = "sudo --version"
@@ -787,4 +1057,4 @@
IS_PYTHON_MINIMUM_3_9 = check_python("3.9", hard=False)
IS_PYTHON_MINIMUM_3_10 = check_python("3.10", hard=False)
-IS_PYTHON_MINIMUM_3_12 = check_python("3.12", hard=False)+IS_PYTHON_MINIMUM_3_12 = check_python("3.12", hard=False)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/checks.py |
Add detailed docstrings explaining each function | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from ultralytics.utils import SETTINGS, TESTS_RUNNING
from ultralytics.utils.torch_utils import model_info_for_loggers
try:
assert not TESTS_RUNNING # do not log pytest
assert SETTINGS["wandb"] is True # verify integration is enabled
import wandb as wb
assert hasattr(wb, "__version__") # verify package is not directory
_processed_plots = {}
except (ImportError, AssertionError):
wb = None
def _custom_table(x, y, classes, title="Precision Recall Curve", x_title="Recall", y_title="Precision"):
import polars as pl # scope for faster 'import ultralytics'
import polars.selectors as cs
df = pl.DataFrame({"class": classes, "y": y, "x": x}).with_columns(cs.numeric().round(3))
data = df.select(["class", "y", "x"]).rows()
fields = {"x": "x", "y": "y", "class": "class"}
string_fields = {"title": title, "x-axis-title": x_title, "y-axis-title": y_title}
return wb.plot_table(
"wandb/area-under-curve/v0",
wb.Table(data=data, columns=["class", "y", "x"]),
fields=fields,
string_fields=string_fields,
)
def _plot_curve(
x,
y,
names=None,
id="precision-recall",
title="Precision Recall Curve",
x_title="Recall",
y_title="Precision",
num_x=100,
only_mean=False,
):
import numpy as np
# Create new x
if names is None:
names = []
x_new = np.linspace(x[0], x[-1], num_x).round(5)
# Create arrays for logging
x_log = x_new.tolist()
y_log = np.interp(x_new, x, np.mean(y, axis=0)).round(3).tolist()
if only_mean:
table = wb.Table(data=list(zip(x_log, y_log)), columns=[x_title, y_title])
wb.run.log({title: wb.plot.line(table, x_title, y_title, title=title)})
else:
classes = ["mean"] * len(x_log)
for i, yi in enumerate(y):
x_log.extend(x_new) # add new x
y_log.extend(np.interp(x_new, x, yi)) # interpolate y to new x
classes.extend([names[i]] * len(x_new)) # add class names
wb.log({id: _custom_table(x_log, y_log, classes, title, x_title, y_title)}, commit=False)
def _log_plots(plots, step):
for name, params in plots.copy().items(): # shallow copy to prevent plots dict changing during iteration
timestamp = params["timestamp"]
if _processed_plots.get(name) != timestamp:
wb.run.log({name.stem: wb.Image(str(name))}, step=step)
_processed_plots[name] = timestamp
def on_pretrain_routine_start(trainer):
if not wb.run:
from datetime import datetime
name = str(trainer.args.name).replace("/", "-").replace(" ", "_")
wb.init(
project=str(trainer.args.project).replace("/", "-") if trainer.args.project else "Ultralytics",
name=name,
config=vars(trainer.args),
id=f"{name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}", # add unique id
dir=str(trainer.save_dir),
)
def on_fit_epoch_end(trainer):
_log_plots(trainer.plots, step=trainer.epoch + 1)
_log_plots(trainer.validator.plots, step=trainer.epoch + 1)
if trainer.epoch == 0:
wb.run.log(model_info_for_loggers(trainer), step=trainer.epoch + 1)
wb.run.log(trainer.metrics, step=trainer.epoch + 1, commit=True) # commit forces sync
def on_train_epoch_end(trainer):
wb.run.log(trainer.label_loss_items(trainer.tloss, prefix="train"), step=trainer.epoch + 1)
wb.run.log(trainer.lr, step=trainer.epoch + 1)
if trainer.epoch == 1:
_log_plots(trainer.plots, step=trainer.epoch + 1)
def on_train_end(trainer):
_log_plots(trainer.validator.plots, step=trainer.epoch + 1)
_log_plots(trainer.plots, step=trainer.epoch + 1)
art = wb.Artifact(type="model", name=f"run_{wb.run.id}_model")
if trainer.best.exists():
art.add_file(trainer.best)
wb.run.log_artifact(art, aliases=["best"])
# Check if we actually have plots to save
if trainer.args.plots and hasattr(trainer.validator.metrics, "curves_results"):
for curve_name, curve_values in zip(trainer.validator.metrics.curves, trainer.validator.metrics.curves_results):
x, y, x_title, y_title = curve_values
_plot_curve(
x,
y,
names=list(trainer.validator.metrics.names.values()),
id=f"curves/{curve_name}",
title=curve_name,
x_title=x_title,
y_title=y_title,
)
wb.run.finish() # required or run continues on dashboard
callbacks = (
{
"on_pretrain_routine_start": on_pretrain_routine_start,
"on_train_epoch_end": on_train_epoch_end,
"on_fit_epoch_end": on_fit_epoch_end,
"on_train_end": on_train_end,
}
if wb
else {}
) | --- +++ @@ -16,6 +16,23 @@
def _custom_table(x, y, classes, title="Precision Recall Curve", x_title="Recall", y_title="Precision"):
+ """Create and log a custom metric visualization table.
+
+ This function crafts a custom metric visualization that mimics the behavior of the default wandb precision-recall
+ curve while allowing for enhanced customization. The visual metric is useful for monitoring model performance across
+ different classes.
+
+ Args:
+ x (list): Values for the x-axis; expected to have length N.
+ y (list): Corresponding values for the y-axis; also expected to have length N.
+ classes (list): Labels identifying the class of each point; length N.
+ title (str, optional): Title for the plot.
+ x_title (str, optional): Label for the x-axis.
+ y_title (str, optional): Label for the y-axis.
+
+ Returns:
+ (wandb.Object): A wandb object suitable for logging, showcasing the crafted metric visualization.
+ """
import polars as pl # scope for faster 'import ultralytics'
import polars.selectors as cs
@@ -43,6 +60,25 @@ num_x=100,
only_mean=False,
):
+ """Log a metric curve visualization.
+
+ This function generates a metric curve based on input data and logs the visualization to wandb. The curve can
+ represent aggregated data (mean) or individual class data, depending on the 'only_mean' flag.
+
+ Args:
+ x (np.ndarray): Data points for the x-axis with length N.
+ y (np.ndarray): Corresponding data points for the y-axis with shape (C, N), where C is the number of classes.
+ names (list, optional): Names of the classes corresponding to the y-axis data; length C.
+ id (str, optional): Unique identifier for the logged data in wandb.
+ title (str, optional): Title for the visualization plot.
+ x_title (str, optional): Label for the x-axis.
+ y_title (str, optional): Label for the y-axis.
+ num_x (int, optional): Number of interpolated data points for visualization.
+ only_mean (bool, optional): Flag to indicate if only the mean curve should be plotted.
+
+ Notes:
+ The function leverages the '_custom_table' function to generate the actual visualization.
+ """
import numpy as np
# Create new x
@@ -67,6 +103,21 @@
def _log_plots(plots, step):
+ """Log plots to WandB at a specific step if they haven't been logged already.
+
+ This function checks each plot in the input dictionary against previously processed plots and logs new or updated
+ plots to WandB at the specified step.
+
+ Args:
+ plots (dict): Dictionary of plots to log, where keys are plot names and values are dictionaries containing plot
+ metadata including timestamps.
+ step (int): The step/epoch at which to log the plots in the WandB run.
+
+ Notes:
+ The function uses a shallow copy of the plots dictionary to prevent modification during iteration.
+ Plots are identified by their stem name (filename without extension).
+ Each plot is logged as a WandB Image object.
+ """
for name, params in plots.copy().items(): # shallow copy to prevent plots dict changing during iteration
timestamp = params["timestamp"]
if _processed_plots.get(name) != timestamp:
@@ -75,6 +126,7 @@
def on_pretrain_routine_start(trainer):
+ """Initialize and start wandb project if module is present."""
if not wb.run:
from datetime import datetime
@@ -89,6 +141,7 @@
def on_fit_epoch_end(trainer):
+ """Log training metrics and model information at the end of an epoch."""
_log_plots(trainer.plots, step=trainer.epoch + 1)
_log_plots(trainer.validator.plots, step=trainer.epoch + 1)
if trainer.epoch == 0:
@@ -97,6 +150,7 @@
def on_train_epoch_end(trainer):
+ """Log metrics and save images at the end of each training epoch."""
wb.run.log(trainer.label_loss_items(trainer.tloss, prefix="train"), step=trainer.epoch + 1)
wb.run.log(trainer.lr, step=trainer.epoch + 1)
if trainer.epoch == 1:
@@ -104,6 +158,7 @@
def on_train_end(trainer):
+ """Save the best model as an artifact and log final plots at the end of training."""
_log_plots(trainer.validator.plots, step=trainer.epoch + 1)
_log_plots(trainer.plots, step=trainer.epoch + 1)
art = wb.Artifact(type="model", name=f"run_{wb.run.id}_model")
@@ -135,4 +190,4 @@ }
if wb
else {}
-)+)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/callbacks/wb.py |
Add docstrings that explain logic | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from ultralytics.utils import LOGGER, SETTINGS, TESTS_RUNNING, colorstr, torch_utils
from ultralytics.utils.torch_utils import smart_inference_mode
try:
assert not TESTS_RUNNING # do not log pytest
assert SETTINGS["tensorboard"] is True # verify integration is enabled
WRITER = None # TensorBoard SummaryWriter instance
PREFIX = colorstr("TensorBoard: ")
# Imports below only required if TensorBoard enabled
from copy import deepcopy
import torch
from torch.utils.tensorboard import SummaryWriter
except (ImportError, AssertionError, TypeError, AttributeError):
# TypeError for handling 'Descriptors cannot not be created directly.' protobuf errors in Windows
# AttributeError: module 'tensorflow' has no attribute 'io' if 'tensorflow' not installed
SummaryWriter = None
def _log_scalars(scalars: dict, step: int = 0) -> None:
if WRITER:
for k, v in scalars.items():
WRITER.add_scalar(k, v, step)
@smart_inference_mode()
def _log_tensorboard_graph(trainer) -> None:
# Input image
imgsz = trainer.args.imgsz
imgsz = (imgsz, imgsz) if isinstance(imgsz, int) else imgsz
p = next(trainer.model.parameters()) # for device, type
im = torch.zeros((1, 3, *imgsz), device=p.device, dtype=p.dtype) # input image (must be zeros, not empty)
# Try simple method first (YOLO)
try:
trainer.model.eval() # place in .eval() mode to avoid BatchNorm statistics changes
WRITER.add_graph(torch.jit.trace(torch_utils.unwrap_model(trainer.model), im, strict=False), [])
LOGGER.info(f"{PREFIX}model graph visualization added ✅")
return
except Exception as e1:
# Fallback to TorchScript export steps (RTDETR)
try:
model = deepcopy(torch_utils.unwrap_model(trainer.model))
model.eval()
model = model.fuse(verbose=False)
for m in model.modules():
if hasattr(m, "export"): # Detect, RTDETRDecoder (Segment and Pose use Detect base class)
m.export = True
m.format = "torchscript"
model(im) # dry run
WRITER.add_graph(torch.jit.trace(model, im, strict=False), [])
LOGGER.info(f"{PREFIX}model graph visualization added ✅")
except Exception as e2:
LOGGER.warning(f"{PREFIX}TensorBoard graph visualization failure: {e1} -> {e2}")
def on_pretrain_routine_start(trainer) -> None:
if SummaryWriter:
try:
global WRITER
WRITER = SummaryWriter(str(trainer.save_dir))
LOGGER.info(f"{PREFIX}Start with 'tensorboard --logdir {trainer.save_dir}', view at http://localhost:6006/")
except Exception as e:
LOGGER.warning(f"{PREFIX}TensorBoard not initialized correctly, not logging this run. {e}")
def on_train_start(trainer) -> None:
if WRITER:
_log_tensorboard_graph(trainer)
def on_train_epoch_end(trainer) -> None:
_log_scalars(trainer.label_loss_items(trainer.tloss, prefix="train"), trainer.epoch + 1)
_log_scalars(trainer.lr, trainer.epoch + 1)
def on_fit_epoch_end(trainer) -> None:
_log_scalars(trainer.metrics, trainer.epoch + 1)
callbacks = (
{
"on_pretrain_routine_start": on_pretrain_routine_start,
"on_train_start": on_train_start,
"on_fit_epoch_end": on_fit_epoch_end,
"on_train_epoch_end": on_train_epoch_end,
}
if SummaryWriter
else {}
) | --- +++ @@ -22,6 +22,18 @@
def _log_scalars(scalars: dict, step: int = 0) -> None:
+ """Log scalar values to TensorBoard.
+
+ Args:
+ scalars (dict): Dictionary of scalar values to log to TensorBoard. Keys are scalar names and values are the
+ corresponding scalar values.
+ step (int): Global step value to record with the scalar values. Used for x-axis in TensorBoard graphs.
+
+ Examples:
+ Log training metrics
+ >>> metrics = {"loss": 0.5, "accuracy": 0.95}
+ >>> _log_scalars(metrics, step=100)
+ """
if WRITER:
for k, v in scalars.items():
WRITER.add_scalar(k, v, step)
@@ -29,6 +41,21 @@
@smart_inference_mode()
def _log_tensorboard_graph(trainer) -> None:
+ """Log model graph to TensorBoard.
+
+ This function attempts to visualize the model architecture in TensorBoard by tracing the model with a dummy input
+ tensor. It first tries a simple method suitable for YOLO models, and if that fails, falls back to a more complex
+ approach for models like RTDETR that may require special handling.
+
+ Args:
+ trainer (ultralytics.engine.trainer.BaseTrainer): The trainer object containing the model to visualize. Must
+ have attributes model and args with imgsz.
+
+ Notes:
+ This function requires TensorBoard integration to be enabled and the global WRITER to be initialized.
+ It handles potential warnings from the PyTorch JIT tracer and attempts to gracefully handle different
+ model architectures.
+ """
# Input image
imgsz = trainer.args.imgsz
imgsz = (imgsz, imgsz) if isinstance(imgsz, int) else imgsz
@@ -59,6 +86,7 @@
def on_pretrain_routine_start(trainer) -> None:
+ """Initialize TensorBoard logging with SummaryWriter."""
if SummaryWriter:
try:
global WRITER
@@ -69,16 +97,19 @@
def on_train_start(trainer) -> None:
+ """Log TensorBoard graph."""
if WRITER:
_log_tensorboard_graph(trainer)
def on_train_epoch_end(trainer) -> None:
+ """Log scalar statistics at the end of a training epoch."""
_log_scalars(trainer.label_loss_items(trainer.tloss, prefix="train"), trainer.epoch + 1)
_log_scalars(trainer.lr, trainer.epoch + 1)
def on_fit_epoch_end(trainer) -> None:
+ """Log epoch metrics at end of training epoch."""
_log_scalars(trainer.metrics, trainer.epoch + 1)
@@ -91,4 +122,4 @@ }
if SummaryWriter
else {}
-)+)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/callbacks/tensorboard.py |
Write docstrings describing each step | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import ast
from urllib.parse import urlsplit
import numpy as np
class TritonRemoteModel:
def __init__(self, url: str, endpoint: str = "", scheme: str = ""):
if not endpoint and not scheme: # Parse all args from URL string
splits = urlsplit(url)
endpoint = splits.path.strip("/").split("/", 1)[0]
scheme = splits.scheme
url = splits.netloc
self.endpoint = endpoint
self.url = url
# Choose the Triton client based on the communication scheme
if scheme == "http":
import tritonclient.http as client
self.triton_client = client.InferenceServerClient(url=self.url, verbose=False, ssl=False)
config = self.triton_client.get_model_config(endpoint)
else:
import tritonclient.grpc as client
self.triton_client = client.InferenceServerClient(url=self.url, verbose=False, ssl=False)
config = self.triton_client.get_model_config(endpoint, as_json=True)["config"]
# Sort output names alphabetically, i.e. 'output0', 'output1', etc.
config["output"] = sorted(config["output"], key=lambda x: x.get("name"))
# Define model attributes
type_map = {"TYPE_FP32": np.float32, "TYPE_FP16": np.float16, "TYPE_UINT8": np.uint8}
self.InferRequestedOutput = client.InferRequestedOutput
self.InferInput = client.InferInput
self.input_formats = [x["data_type"] for x in config["input"]]
self.np_input_formats = [type_map[x] for x in self.input_formats]
self.input_names = [x["name"] for x in config["input"]]
self.output_names = [x["name"] for x in config["output"]]
self.metadata = ast.literal_eval(config.get("parameters", {}).get("metadata", {}).get("string_value", "None"))
def __call__(self, *inputs: np.ndarray) -> list[np.ndarray]:
infer_inputs = []
input_format = inputs[0].dtype
for i, x in enumerate(inputs):
if x.dtype != self.np_input_formats[i]:
x = x.astype(self.np_input_formats[i])
infer_input = self.InferInput(self.input_names[i], [*x.shape], self.input_formats[i].replace("TYPE_", ""))
infer_input.set_data_from_numpy(x)
infer_inputs.append(infer_input)
infer_outputs = [self.InferRequestedOutput(output_name) for output_name in self.output_names]
outputs = self.triton_client.infer(model_name=self.endpoint, inputs=infer_inputs, outputs=infer_outputs)
return [outputs.as_numpy(output_name).astype(input_format) for output_name in self.output_names] | --- +++ @@ -9,8 +9,45 @@
class TritonRemoteModel:
+ """Client for interacting with a remote Triton Inference Server model.
+
+ This class provides a convenient interface for sending inference requests to a Triton Inference Server and
+ processing the responses. Supports both HTTP and gRPC communication protocols.
+
+ Attributes:
+ endpoint (str): The name of the model on the Triton server.
+ url (str): The URL of the Triton server.
+ triton_client: The Triton client (either HTTP or gRPC).
+ InferInput: The input class for the Triton client.
+ InferRequestedOutput: The output request class for the Triton client.
+ input_formats (list[str]): The data types of the model inputs.
+ np_input_formats (list[type]): The numpy data types of the model inputs.
+ input_names (list[str]): The names of the model inputs.
+ output_names (list[str]): The names of the model outputs.
+ metadata: The metadata associated with the model.
+
+ Methods:
+ __call__: Call the model with the given inputs and return the outputs.
+
+ Examples:
+ Initialize a Triton client with HTTP
+ >>> model = TritonRemoteModel(url="localhost:8000", endpoint="yolov8", scheme="http")
+
+ Make inference with numpy arrays
+ >>> outputs = model(np.random.rand(1, 3, 640, 640).astype(np.float32))
+ """
def __init__(self, url: str, endpoint: str = "", scheme: str = ""):
+ """Initialize the TritonRemoteModel for interacting with a remote Triton Inference Server.
+
+ Arguments may be provided individually or parsed from a collective 'url' argument of the form
+ <scheme>://<netloc>/<endpoint>/<task_name>
+
+ Args:
+ url (str): The URL of the Triton server.
+ endpoint (str, optional): The name of the model on the Triton server.
+ scheme (str, optional): The communication scheme ('http' or 'grpc').
+ """
if not endpoint and not scheme: # Parse all args from URL string
splits = urlsplit(url)
endpoint = splits.path.strip("/").split("/", 1)[0]
@@ -46,6 +83,20 @@ self.metadata = ast.literal_eval(config.get("parameters", {}).get("metadata", {}).get("string_value", "None"))
def __call__(self, *inputs: np.ndarray) -> list[np.ndarray]:
+ """Call the model with the given inputs and return inference results.
+
+ Args:
+ *inputs (np.ndarray): Input data to the model. Each array should match the expected shape and type for the
+ corresponding model input.
+
+ Returns:
+ (list[np.ndarray]): Model outputs cast to the dtype of the first input. Each element in the list corresponds
+ to one of the model's output tensors.
+
+ Examples:
+ >>> model = TritonRemoteModel(url="localhost:8000", endpoint="yolov8", scheme="http")
+ >>> outputs = model(np.random.rand(1, 3, 640, 640).astype(np.float32))
+ """
infer_inputs = []
input_format = inputs[0].dtype
for i, x in enumerate(inputs):
@@ -58,4 +109,4 @@ infer_outputs = [self.InferRequestedOutput(output_name) for output_name in self.output_names]
outputs = self.triton_client.infer(model_name=self.endpoint, inputs=infer_inputs, outputs=infer_outputs)
- return [outputs.as_numpy(output_name).astype(input_format) for output_name in self.output_names]+ return [outputs.as_numpy(output_name).astype(input_format) for output_name in self.output_names]
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/triton.py |
Write docstrings that follow conventions | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import re
import shutil
import subprocess
from itertools import repeat
from multiprocessing.pool import ThreadPool
from pathlib import Path
from urllib import parse, request
from ultralytics.utils import ASSETS_URL, LOGGER, TQDM, checks, clean_url, emojis, is_online, url2file
# Define Ultralytics GitHub assets maintained at https://github.com/ultralytics/assets
GITHUB_ASSETS_REPO = "ultralytics/assets"
GITHUB_ASSETS_NAMES = frozenset(
[f"yolov8{k}{suffix}.pt" for k in "nsmlx" for suffix in ("", "-cls", "-seg", "-pose", "-obb", "-oiv7")]
+ [f"yolo11{k}{suffix}.pt" for k in "nsmlx" for suffix in ("", "-cls", "-seg", "-pose", "-obb")]
+ [f"yolo12{k}{suffix}.pt" for k in "nsmlx" for suffix in ("",)] # detect models only currently
+ [f"yolo26{k}{suffix}.pt" for k in "nsmlx" for suffix in ("", "-cls", "-seg", "-pose", "-obb")]
+ [f"yolov5{k}{resolution}u.pt" for k in "nsmlx" for resolution in ("", "6")]
+ [f"yolov3{k}u.pt" for k in ("", "-spp", "-tiny")]
+ [f"yolov8{k}-world.pt" for k in "smlx"]
+ [f"yolov8{k}-worldv2.pt" for k in "smlx"]
+ [f"yoloe-v8{k}{suffix}.pt" for k in "sml" for suffix in ("-seg", "-seg-pf")]
+ [f"yoloe-11{k}{suffix}.pt" for k in "sml" for suffix in ("-seg", "-seg-pf")]
+ [f"yoloe-26{k}{suffix}.pt" for k in "nsmlx" for suffix in ("-seg", "-seg-pf")]
+ [f"yolov9{k}.pt" for k in "tsmce"]
+ [f"yolov10{k}.pt" for k in "nsmblx"]
+ [f"yolo_nas_{k}.pt" for k in "sml"]
+ [f"sam_{k}.pt" for k in "bl"]
+ [f"sam2_{k}.pt" for k in "blst"]
+ [f"sam2.1_{k}.pt" for k in "blst"]
+ [f"FastSAM-{k}.pt" for k in "sx"]
+ [f"rtdetr-{k}.pt" for k in "lx"]
+ [
"mobile_sam.pt",
"mobileclip_blt.ts",
"yolo11n-grayscale.pt",
"calibration_image_sample_data_20x128x128x3_float32.npy.zip",
]
)
GITHUB_ASSETS_STEMS = frozenset(k.rpartition(".")[0] for k in GITHUB_ASSETS_NAMES)
def is_url(url: str | Path, check: bool = False) -> bool:
try:
url = str(url)
result = parse.urlparse(url)
if not (result.scheme and result.netloc):
return False
if check:
r = request.urlopen(request.Request(url, method="HEAD"), timeout=3)
return 200 <= r.getcode() < 400
return True
except Exception:
return False
def delete_dsstore(path: str | Path, files_to_delete: tuple[str, ...] = (".DS_Store", "__MACOSX")) -> None:
for file in files_to_delete:
matches = list(Path(path).rglob(file))
LOGGER.info(f"Deleting {file} files: {matches}")
for f in matches:
f.unlink()
def zip_directory(
directory: str | Path,
compress: bool = True,
exclude: tuple[str, ...] = (".DS_Store", "__MACOSX"),
progress: bool = True,
) -> Path:
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
delete_dsstore(directory)
directory = Path(directory)
if not directory.is_dir():
raise FileNotFoundError(f"Directory '{directory}' does not exist.")
# Zip with progress bar
files = [f for f in directory.rglob("*") if f.is_file() and all(x not in f.name for x in exclude)] # files to zip
zip_file = directory.with_suffix(".zip")
compression = ZIP_DEFLATED if compress else ZIP_STORED
with ZipFile(zip_file, "w", compression) as f:
for file in TQDM(files, desc=f"Zipping {directory} to {zip_file}...", unit="files", disable=not progress):
f.write(file, file.relative_to(directory))
return zip_file # return path to zip file
def unzip_file(
file: str | Path,
path: str | Path | None = None,
exclude: tuple[str, ...] = (".DS_Store", "__MACOSX"),
exist_ok: bool = False,
progress: bool = True,
) -> Path:
from zipfile import BadZipFile, ZipFile, is_zipfile
if not (Path(file).exists() and is_zipfile(file)):
raise BadZipFile(f"File '{file}' does not exist or is a bad zip file.")
if path is None:
path = Path(file).parent # default path
# Unzip the file contents
with ZipFile(file) as zipObj:
files = [f for f in zipObj.namelist() if all(x not in f for x in exclude)]
top_level_dirs = {Path(f).parts[0] for f in files}
# Decide to unzip directly or unzip into a directory
unzip_as_dir = len(top_level_dirs) == 1 # (len(files) > 1 and not files[0].endswith("/"))
if unzip_as_dir:
# Zip has 1 top-level directory
extract_path = path # i.e. ../datasets
path = Path(path) / next(iter(top_level_dirs)) # i.e. extract coco8/ dir to ../datasets/
else:
# Zip has multiple files at top level
path = extract_path = Path(path) / Path(file).stem # i.e. extract multiple files to ../datasets/coco8/
# Check if destination directory already exists and contains files
if path.exists() and any(path.iterdir()) and not exist_ok:
# If it exists and is not empty, return the path without unzipping
LOGGER.warning(f"Skipping {file} unzip as destination directory {path} is not empty.")
return path
for f in TQDM(files, desc=f"Unzipping {file} to {Path(path).resolve()}...", unit="files", disable=not progress):
# Ensure the file is within the extract_path to avoid path traversal security vulnerability
if ".." in Path(f).parts:
LOGGER.warning(f"Potentially insecure file path: {f}, skipping extraction.")
continue
zipObj.extract(f, extract_path)
return path # return unzip dir
def check_disk_space(
file_bytes: int,
path: str | Path = Path.cwd(),
sf: float = 1.5,
hard: bool = True,
) -> bool:
_total, _used, free = shutil.disk_usage(path) # bytes
if file_bytes * sf < free:
return True # sufficient space
def fmt_bytes(b):
return f"{b / (1 << 20):.1f} MB" if b < (1 << 30) else f"{b / (1 << 30):.3f} GB"
# Insufficient space
text = (
f"Insufficient free disk space {fmt_bytes(free)} < {fmt_bytes(int(file_bytes * sf))} required, "
f"Please free {fmt_bytes(int(file_bytes * sf - free))} additional disk space and try again."
)
if hard:
raise MemoryError(text)
LOGGER.warning(text)
return False
def get_google_drive_file_info(link: str) -> tuple[str, str | None]:
import requests # scoped as slow import
file_id = link.split("/d/")[1].split("/view", 1)[0]
drive_url = f"https://drive.google.com/uc?export=download&id={file_id}"
filename = None
# Start session
with requests.Session() as session:
response = session.get(drive_url, stream=True)
if "quota exceeded" in str(response.content.lower()):
raise ConnectionError(
emojis(
f"❌ Google Drive file download quota exceeded. "
f"Please try again later or download this file manually at {link}."
)
)
for k, v in response.cookies.items():
if k.startswith("download_warning"):
drive_url += f"&confirm={v}" # v is token
if cd := response.headers.get("content-disposition"):
filename = re.findall('filename="(.+)"', cd)[0]
return drive_url, filename
def safe_download(
url: str | Path,
file: str | Path | None = None,
dir: str | Path | None = None,
unzip: bool = True,
delete: bool = False,
curl: bool = False,
retry: int = 3,
min_bytes: float = 1e0,
exist_ok: bool = False,
progress: bool = True,
) -> Path | str:
gdrive = url.startswith("https://drive.google.com/") # check if the URL is a Google Drive link
if gdrive:
url, file = get_google_drive_file_info(url)
url = url.replace(" ", "%20") # encode spaces for curl/urllib compatibility
f = Path(dir or ".") / (file or url2file(url)) # URL converted to filename
if "://" not in str(url) and Path(url).is_file(): # URL exists ('://' check required in Windows Python<3.10)
f = Path(url) # filename
elif not f.is_file(): # URL and file do not exist
uri = (url if gdrive else clean_url(url)).replace(ASSETS_URL, "https://ultralytics.com/assets") # clean
desc = f"Downloading {uri} to '{f}'"
f.parent.mkdir(parents=True, exist_ok=True) # make directory if missing
curl_installed = shutil.which("curl")
for i in range(retry + 1):
try:
if (curl or i > 0) and curl_installed: # curl download with retry, continue
s = "sS" * (not progress) # silent
r = subprocess.run(["curl", "-#", f"-{s}L", url, "-o", f, "--retry", "3", "-C", "-"]).returncode
assert r == 0, f"Curl return value {r}"
expected_size = None # Can't get size with curl
else: # urllib download
with request.urlopen(url) as response:
expected_size = int(response.getheader("Content-Length", 0))
if i == 0 and expected_size > 1048576:
check_disk_space(expected_size, path=f.parent)
buffer_size = max(8192, min(1048576, expected_size // 1000)) if expected_size else 8192
with TQDM(
total=expected_size,
desc=desc,
disable=not progress,
unit="B",
unit_scale=True,
unit_divisor=1024,
) as pbar:
with open(f, "wb") as f_opened:
while True:
data = response.read(buffer_size)
if not data:
break
f_opened.write(data)
pbar.update(len(data))
if f.exists():
file_size = f.stat().st_size
if file_size > min_bytes:
# Check if download is complete (only if we have expected_size)
if expected_size and file_size != expected_size:
LOGGER.warning(
f"Partial download: {file_size}/{expected_size} bytes ({file_size / expected_size * 100:.1f}%)"
)
else:
break # success
f.unlink() # remove partial downloads
except MemoryError:
raise # Re-raise immediately - no point retrying if insufficient disk space
except Exception as e:
if i == 0 and not is_online():
raise ConnectionError(emojis(f"❌ Download failure for {uri}. Environment may be offline.")) from e
elif i >= retry:
raise ConnectionError(emojis(f"❌ Download failure for {uri}. Retry limit reached. {e}")) from e
LOGGER.warning(f"Download failure, retrying {i + 1}/{retry} {uri}... {e}")
if unzip and f.exists() and f.suffix in {"", ".zip", ".tar", ".gz"}:
from zipfile import is_zipfile
unzip_dir = (dir or f.parent).resolve() # unzip to dir if provided else unzip in place
if is_zipfile(f):
unzip_dir = unzip_file(file=f, path=unzip_dir, exist_ok=exist_ok, progress=progress) # unzip
elif f.suffix in {".tar", ".gz"}:
LOGGER.info(f"Unzipping {f} to {unzip_dir}...")
subprocess.run(["tar", "xf" if f.suffix == ".tar" else "xfz", f, "--directory", unzip_dir], check=True)
if delete:
f.unlink() # remove zip
return unzip_dir
return f
def get_github_assets(
repo: str = "ultralytics/assets",
version: str = "latest",
retry: bool = False,
) -> tuple[str, list[str]]:
import requests # scoped as slow import
if version != "latest":
version = f"tags/{version}" # i.e. tags/v6.2
url = f"https://api.github.com/repos/{repo}/releases/{version}"
r = requests.get(url) # github api
if r.status_code != 200 and r.reason != "rate limit exceeded" and retry: # failed and not 403 rate limit exceeded
r = requests.get(url) # try again
if r.status_code != 200:
LOGGER.warning(f"GitHub assets check failure for {url}: {r.status_code} {r.reason}")
return "", []
data = r.json()
return data["tag_name"], [x["name"] for x in data["assets"]] # tag, assets i.e. ['yolo26n.pt', 'yolo11s.pt', ...]
def attempt_download_asset(
file: str | Path,
repo: str = "ultralytics/assets",
release: str = "v8.4.0",
**kwargs,
) -> str:
from ultralytics.utils import SETTINGS # scoped for circular import
# YOLOv3/5u updates
file = str(file)
file = checks.check_yolov5u_filename(file)
file = Path(file.strip().replace("'", ""))
if file.exists():
return str(file)
elif (SETTINGS["weights_dir"] / file).exists():
return str(SETTINGS["weights_dir"] / file)
else:
# URL specified
name = Path(parse.unquote(str(file))).name # decode '%2F' to '/' etc.
download_url = f"https://github.com/{repo}/releases/download"
if str(file).startswith(("http:/", "https:/")): # download
url = str(file).replace(":/", "://") # Pathlib turns :// -> :/
file = url2file(name) # parse authentication https://url.com/file.txt?auth...
if Path(file).is_file():
LOGGER.info(f"Found {clean_url(url)} locally at {file}") # file already exists
else:
safe_download(url=url, file=file, min_bytes=1e5, **kwargs)
elif repo == GITHUB_ASSETS_REPO and name in GITHUB_ASSETS_NAMES:
safe_download(url=f"{download_url}/{release}/{name}", file=file, min_bytes=1e5, **kwargs)
else:
tag, assets = get_github_assets(repo, release)
if not assets:
tag, assets = get_github_assets(repo) # latest release
if name in assets:
safe_download(url=f"{download_url}/{tag}/{name}", file=file, min_bytes=1e5, **kwargs)
return str(file)
def download(
url: str | list[str] | Path,
dir: Path = Path.cwd(),
unzip: bool = True,
delete: bool = False,
curl: bool = False,
threads: int = 1,
retry: int = 3,
exist_ok: bool = False,
) -> None:
dir = Path(dir)
dir.mkdir(parents=True, exist_ok=True) # make directory
urls = [url] if isinstance(url, (str, Path)) else url
if threads > 1:
LOGGER.info(f"Downloading {len(urls)} file(s) with {threads} threads to {dir}...")
with ThreadPool(threads) as pool:
pool.map(
lambda x: safe_download(
url=x[0],
dir=x[1],
unzip=unzip,
delete=delete,
curl=curl,
retry=retry,
exist_ok=exist_ok,
progress=True,
),
zip(urls, repeat(dir)),
)
pool.close()
pool.join()
else:
for u in urls:
safe_download(url=u, dir=dir, unzip=unzip, delete=delete, curl=curl, retry=retry, exist_ok=exist_ok) | --- +++ @@ -45,6 +45,19 @@
def is_url(url: str | Path, check: bool = False) -> bool:
+ """Validate if the given string is a URL and optionally check if the URL exists online.
+
+ Args:
+ url (str | Path): The string to be validated as a URL.
+ check (bool, optional): If True, performs an additional check to see if the URL exists online.
+
+ Returns:
+ (bool): True for a valid URL. If 'check' is True, also returns True if the URL exists online.
+
+ Examples:
+ >>> valid = is_url("https://www.example.com")
+ >>> valid_and_exists = is_url("https://www.example.com", check=True)
+ """
try:
url = str(url)
result = parse.urlparse(url)
@@ -59,6 +72,20 @@
def delete_dsstore(path: str | Path, files_to_delete: tuple[str, ...] = (".DS_Store", "__MACOSX")) -> None:
+ """Delete all specified system files in a directory.
+
+ Args:
+ path (str | Path): The directory path where the files should be deleted.
+ files_to_delete (tuple[str, ...]): The files to be deleted.
+
+ Examples:
+ >>> from ultralytics.utils.downloads import delete_dsstore
+ >>> delete_dsstore("path/to/dir")
+
+ Notes:
+ ".DS_Store" files are created by the Apple operating system and contain metadata about folders and files. They
+ are hidden system files and can cause issues when transferring files between different operating systems.
+ """
for file in files_to_delete:
matches = list(Path(path).rglob(file))
LOGGER.info(f"Deleting {file} files: {matches}")
@@ -72,6 +99,23 @@ exclude: tuple[str, ...] = (".DS_Store", "__MACOSX"),
progress: bool = True,
) -> Path:
+ """Zip the contents of a directory, excluding specified files.
+
+ The resulting zip file is named after the directory and placed alongside it.
+
+ Args:
+ directory (str | Path): The path to the directory to be zipped.
+ compress (bool): Whether to compress the files while zipping.
+ exclude (tuple[str, ...], optional): A tuple of filename strings to be excluded.
+ progress (bool, optional): Whether to display a progress bar.
+
+ Returns:
+ (Path): The path to the resulting zip file.
+
+ Examples:
+ >>> from ultralytics.utils.downloads import zip_directory
+ >>> file = zip_directory("path/to/dir")
+ """
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
delete_dsstore(directory)
@@ -97,6 +141,29 @@ exist_ok: bool = False,
progress: bool = True,
) -> Path:
+ """Unzip a *.zip file to the specified path, excluding specified files.
+
+ If the zipfile does not contain a single top-level directory, the function will create a new directory with the same
+ name as the zipfile (without the extension) to extract its contents. If a path is not provided, the function will
+ use the parent directory of the zipfile as the default path.
+
+ Args:
+ file (str | Path): The path to the zipfile to be extracted.
+ path (str | Path, optional): The path to extract the zipfile to.
+ exclude (tuple[str, ...], optional): A tuple of filename strings to be excluded.
+ exist_ok (bool, optional): Whether to overwrite existing contents if they exist.
+ progress (bool, optional): Whether to display a progress bar.
+
+ Returns:
+ (Path): The path to the directory where the zipfile was extracted.
+
+ Raises:
+ BadZipFile: If the provided file does not exist or is not a valid zipfile.
+
+ Examples:
+ >>> from ultralytics.utils.downloads import unzip_file
+ >>> directory = unzip_file("path/to/file.zip")
+ """
from zipfile import BadZipFile, ZipFile, is_zipfile
if not (Path(file).exists() and is_zipfile(file)):
@@ -141,6 +208,17 @@ sf: float = 1.5,
hard: bool = True,
) -> bool:
+ """Check if there is sufficient disk space to download and store a file.
+
+ Args:
+ file_bytes (int): The file size in bytes.
+ path (str | Path, optional): The path or drive to check the available free space on.
+ sf (float, optional): Safety factor, the multiplier for the required free space.
+ hard (bool, optional): Whether to throw an error or not on insufficient disk space.
+
+ Returns:
+ (bool): True if there is sufficient disk space, False otherwise.
+ """
_total, _used, free = shutil.disk_usage(path) # bytes
if file_bytes * sf < free:
return True # sufficient space
@@ -160,6 +238,20 @@
def get_google_drive_file_info(link: str) -> tuple[str, str | None]:
+ """Retrieve the direct download link and filename for a shareable Google Drive file link.
+
+ Args:
+ link (str): The shareable link of the Google Drive file.
+
+ Returns:
+ url (str): Direct download URL for the Google Drive file.
+ filename (str | None): Original filename of the Google Drive file. If filename extraction fails, returns None.
+
+ Examples:
+ >>> from ultralytics.utils.downloads import get_google_drive_file_info
+ >>> link = "https://drive.google.com/file/d/1cqT-cJgANNrhIHCrEufUYhQ4RqiWG_lJ/view?usp=drive_link"
+ >>> url, filename = get_google_drive_file_info(link)
+ """
import requests # scoped as slow import
file_id = link.split("/d/")[1].split("/view", 1)[0]
@@ -196,6 +288,32 @@ exist_ok: bool = False,
progress: bool = True,
) -> Path | str:
+ """Download files from a URL with options for retrying, unzipping, and deleting the downloaded file. Enhanced with
+ robust partial download detection using Content-Length validation.
+
+ Args:
+ url (str | Path): The URL of the file to be downloaded.
+ file (str | Path, optional): The filename of the downloaded file. If not provided, the file will be saved with
+ the same name as the URL.
+ dir (str | Path, optional): The directory to save the downloaded file. If not provided, the file will be saved
+ in the current working directory.
+ unzip (bool, optional): Whether to unzip the downloaded file.
+ delete (bool, optional): Whether to delete the downloaded file after unzipping.
+ curl (bool, optional): Whether to use curl command line tool for downloading.
+ retry (int, optional): The number of times to retry the download in case of failure.
+ min_bytes (float, optional): The minimum number of bytes that the downloaded file should have, to be considered
+ a successful download.
+ exist_ok (bool, optional): Whether to overwrite existing contents during unzipping.
+ progress (bool, optional): Whether to display a progress bar during the download.
+
+ Returns:
+ (Path | str): The path to the downloaded file or extracted directory.
+
+ Examples:
+ >>> from ultralytics.utils.downloads import safe_download
+ >>> link = "https://ultralytics.com/assets/bus.jpg"
+ >>> path = safe_download(link)
+ """
gdrive = url.startswith("https://drive.google.com/") # check if the URL is a Google Drive link
if gdrive:
url, file = get_google_drive_file_info(url)
@@ -278,6 +396,22 @@ version: str = "latest",
retry: bool = False,
) -> tuple[str, list[str]]:
+ """Retrieve the specified version's tag and assets from a GitHub repository.
+
+ If the version is not specified, the function fetches the latest release assets.
+
+ Args:
+ repo (str, optional): The GitHub repository in the format 'owner/repo'.
+ version (str, optional): The release version to fetch assets from.
+ retry (bool, optional): Flag to retry the request in case of a failure.
+
+ Returns:
+ tag (str): The release tag.
+ assets (list[str]): A list of asset names.
+
+ Examples:
+ >>> tag, assets = get_github_assets(repo="ultralytics/assets", version="latest")
+ """
import requests # scoped as slow import
if version != "latest":
@@ -299,6 +433,20 @@ release: str = "v8.4.0",
**kwargs,
) -> str:
+ """Attempt to download a file from GitHub release assets if it is not found locally.
+
+ Args:
+ file (str | Path): The filename or file path to be downloaded.
+ repo (str, optional): The GitHub repository in the format 'owner/repo'.
+ release (str, optional): The specific release version to be downloaded.
+ **kwargs (Any): Additional keyword arguments for the download process.
+
+ Returns:
+ (str): The path to the downloaded file.
+
+ Examples:
+ >>> file_path = attempt_download_asset("yolo26n.pt", repo="ultralytics/assets", release="latest")
+ """
from ultralytics.utils import SETTINGS # scoped for circular import
# YOLOv3/5u updates
@@ -344,6 +492,23 @@ retry: int = 3,
exist_ok: bool = False,
) -> None:
+ """Download files from specified URLs to a given directory.
+
+ Supports concurrent downloads if multiple threads are specified.
+
+ Args:
+ url (str | list[str] | Path): The URL or list of URLs of the files to be downloaded.
+ dir (Path, optional): The directory where the files will be saved.
+ unzip (bool, optional): Flag to unzip the files after downloading.
+ delete (bool, optional): Flag to delete the zip files after extraction.
+ curl (bool, optional): Flag to use curl for downloading.
+ threads (int, optional): Number of threads to use for concurrent downloads.
+ retry (int, optional): Number of retries in case of download failure.
+ exist_ok (bool, optional): Whether to overwrite existing contents during unzipping.
+
+ Examples:
+ >>> download("https://ultralytics.com/assets/example.zip", dir="path/to/dir", unzip=True)
+ """
dir = Path(dir)
dir.mkdir(parents=True, exist_ok=True) # make directory
urls = [url] if isinstance(url, (str, Path)) else url
@@ -367,4 +532,4 @@ pool.join()
else:
for u in urls:
- safe_download(url=u, dir=dir, unzip=unzip, delete=delete, curl=curl, retry=retry, exist_ok=exist_ok)+ safe_download(url=u, dir=dir, unzip=unzip, delete=delete, curl=curl, retry=retry, exist_ok=exist_ok)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/downloads.py |
Add standardized docstrings across the file | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from ultralytics.cfg import TASK2DATA, TASK2METRIC, get_cfg, get_save_dir
from ultralytics.utils import DEFAULT_CFG, DEFAULT_CFG_DICT, LOGGER, NUM_THREADS, checks, colorstr
def run_ray_tune(
model,
space: dict | None = None,
grace_period: int = 10,
gpu_per_trial: int | None = None,
max_samples: int = 10,
**train_args,
):
LOGGER.info("💡 Learn about RayTune at https://docs.ultralytics.com/integrations/ray-tune")
try:
checks.check_requirements("ray[tune]")
import ray
from ray import tune
from ray.air import RunConfig
from ray.tune.schedulers import ASHAScheduler
except ImportError:
raise ModuleNotFoundError('Ray Tune required but not found. To install run: pip install "ray[tune]"')
try:
import wandb
assert hasattr(wandb, "__version__")
except (ImportError, AssertionError):
wandb = False
checks.check_version(ray.__version__, ">=2.0.0", "ray")
default_space = {
# 'optimizer': tune.choice(['SGD', 'Adam', 'AdamW', 'NAdam', 'RAdam', 'RMSProp']),
"lr0": tune.uniform(1e-5, 1e-1),
"lrf": tune.uniform(0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
"momentum": tune.uniform(0.6, 0.98), # SGD momentum/Adam beta1
"weight_decay": tune.uniform(0.0, 0.001), # optimizer weight decay
"warmup_epochs": tune.uniform(0.0, 5.0), # warmup epochs (fractions ok)
"warmup_momentum": tune.uniform(0.0, 0.95), # warmup initial momentum
"box": tune.uniform(0.02, 0.2), # box loss gain
"cls": tune.uniform(0.2, 4.0), # cls loss gain (scale with pixels)
"hsv_h": tune.uniform(0.0, 0.1), # image HSV-Hue augmentation (fraction)
"hsv_s": tune.uniform(0.0, 0.9), # image HSV-Saturation augmentation (fraction)
"hsv_v": tune.uniform(0.0, 0.9), # image HSV-Value augmentation (fraction)
"degrees": tune.uniform(0.0, 45.0), # image rotation (+/- deg)
"translate": tune.uniform(0.0, 0.9), # image translation (+/- fraction)
"scale": tune.uniform(0.0, 0.9), # image scale (+/- gain)
"shear": tune.uniform(0.0, 10.0), # image shear (+/- deg)
"perspective": tune.uniform(0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
"flipud": tune.uniform(0.0, 1.0), # image flip up-down (probability)
"fliplr": tune.uniform(0.0, 1.0), # image flip left-right (probability)
"bgr": tune.uniform(0.0, 1.0), # swap RGB↔BGR channels (probability)
"mosaic": tune.uniform(0.0, 1.0), # image mosaic (probability)
"mixup": tune.uniform(0.0, 1.0), # image mixup (probability)
"cutmix": tune.uniform(0.0, 1.0), # image cutmix (probability)
"copy_paste": tune.uniform(0.0, 1.0), # segment copy-paste (probability)
}
# Put the model in ray store
task = model.task
model_in_store = ray.put(model)
base_name = train_args.get("name", "tune")
def _tune(config):
model_to_train = ray.get(model_in_store) # get the model from ray store for tuning
model_to_train.trainer = None
model_to_train.reset_callbacks()
config.update(train_args)
# Set trial-specific name for W&B logging
try:
trial_id = tune.get_trial_id() # Get current trial ID (e.g., "2c2fc_00000")
trial_suffix = trial_id.split("_")[-1] if "_" in trial_id else trial_id
config["name"] = f"{base_name}_{trial_suffix}"
except Exception:
# Not in Ray Tune context or error getting trial ID, use base name
config["name"] = base_name
results = model_to_train.train(**config)
return results.results_dict
# Get search space
if not space and not train_args.get("resume"):
space = default_space
LOGGER.warning("Search space not provided, using default search space.")
# Get dataset
data = train_args.get("data", TASK2DATA[task])
space["data"] = data
if "data" not in train_args:
LOGGER.warning(f'Data not provided, using default "data={data}".')
# Define the trainable function with allocated resources
trainable_with_resources = tune.with_resources(_tune, {"cpu": NUM_THREADS, "gpu": gpu_per_trial or 0})
# Define the ASHA scheduler for hyperparameter search
asha_scheduler = ASHAScheduler(
time_attr="epoch",
metric=TASK2METRIC[task],
mode="max",
max_t=train_args.get("epochs") or DEFAULT_CFG_DICT["epochs"] or 100,
grace_period=grace_period,
reduction_factor=3,
)
# Create the Ray Tune hyperparameter search tuner
tune_dir = get_save_dir(
get_cfg(
DEFAULT_CFG,
{**train_args, **{"exist_ok": train_args.pop("resume", False)}}, # resume w/ same tune_dir
),
name=train_args.pop("name", "tune"), # runs/{task}/{tune_dir}
) # must be absolute dir
tune_dir.mkdir(parents=True, exist_ok=True)
if tune.Tuner.can_restore(tune_dir):
LOGGER.info(f"{colorstr('Tuner: ')} Resuming tuning run {tune_dir}...")
tuner = tune.Tuner.restore(str(tune_dir), trainable=trainable_with_resources, resume_errored=True)
else:
tuner = tune.Tuner(
trainable_with_resources,
param_space=space,
tune_config=tune.TuneConfig(
scheduler=asha_scheduler,
num_samples=max_samples,
trial_name_creator=lambda trial: f"{trial.trainable_name}_{trial.trial_id}",
trial_dirname_creator=lambda trial: f"{trial.trainable_name}_{trial.trial_id}",
),
run_config=RunConfig(storage_path=tune_dir.parent, name=tune_dir.name),
)
# Run the hyperparameter search
tuner.fit()
# Get the results of the hyperparameter search
results = tuner.get_results()
# Shut down Ray to clean up workers
ray.shutdown()
return results | --- +++ @@ -14,6 +14,26 @@ max_samples: int = 10,
**train_args,
):
+ """Run hyperparameter tuning using Ray Tune.
+
+ Args:
+ model (YOLO): Model to run the tuner on.
+ space (dict, optional): The hyperparameter search space. If not provided, uses default space.
+ grace_period (int, optional): The grace period in epochs of the ASHA scheduler.
+ gpu_per_trial (int, optional): The number of GPUs to allocate per trial.
+ max_samples (int, optional): The maximum number of trials to run.
+ **train_args (Any): Additional arguments to pass to the `train()` method.
+
+ Returns:
+ (ray.tune.ResultGrid): A ResultGrid containing the results of the hyperparameter search.
+
+ Examples:
+ >>> from ultralytics import YOLO
+ >>> model = YOLO("yolo26n.pt") # Load a YOLO26n model
+
+ Start tuning hyperparameters for YOLO26n training on the COCO8 dataset
+ >>> result_grid = model.tune(data="coco8.yaml", use_ray=True)
+ """
LOGGER.info("💡 Learn about RayTune at https://docs.ultralytics.com/integrations/ray-tune")
try:
checks.check_requirements("ray[tune]")
@@ -66,6 +86,7 @@ base_name = train_args.get("name", "tune")
def _tune(config):
+ """Train the YOLO model with the specified hyperparameters and return results."""
model_to_train = ray.get(model_in_store) # get the model from ray store for tuning
model_to_train.trainer = None
model_to_train.reset_callbacks()
@@ -141,4 +162,4 @@ # Shut down Ray to clean up workers
ray.shutdown()
- return results+ return results
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/tuner.py |
Write proper docstrings for these functions | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import json
from pathlib import Path
import torch
from ultralytics.utils import IS_JETSON, LOGGER
from ultralytics.utils.torch_utils import TORCH_2_4
def torch2onnx(
torch_model: torch.nn.Module,
im: torch.Tensor,
onnx_file: str,
opset: int = 14,
input_names: list[str] = ["images"],
output_names: list[str] = ["output0"],
dynamic: bool | dict = False,
) -> None:
kwargs = {"dynamo": False} if TORCH_2_4 else {}
torch.onnx.export(
torch_model,
im,
onnx_file,
verbose=False,
opset_version=opset,
do_constant_folding=True, # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False
input_names=input_names,
output_names=output_names,
dynamic_axes=dynamic or None,
**kwargs,
)
def onnx2engine(
onnx_file: str,
engine_file: str | None = None,
workspace: int | None = None,
half: bool = False,
int8: bool = False,
dynamic: bool = False,
shape: tuple[int, int, int, int] = (1, 3, 640, 640),
dla: int | None = None,
dataset=None,
metadata: dict | None = None,
verbose: bool = False,
prefix: str = "",
) -> None:
import tensorrt as trt
engine_file = engine_file or Path(onnx_file).with_suffix(".engine")
logger = trt.Logger(trt.Logger.INFO)
if verbose:
logger.min_severity = trt.Logger.Severity.VERBOSE
# Engine builder
builder = trt.Builder(logger)
config = builder.create_builder_config()
workspace_bytes = int((workspace or 0) * (1 << 30))
is_trt10 = int(trt.__version__.split(".", 1)[0]) >= 10 # is TensorRT >= 10
if is_trt10 and workspace_bytes > 0:
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace_bytes)
elif workspace_bytes > 0: # TensorRT versions 7, 8
config.max_workspace_size = workspace_bytes
flag = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
network = builder.create_network(flag)
half = builder.platform_has_fast_fp16 and half
int8 = builder.platform_has_fast_int8 and int8
# Optionally switch to DLA if enabled
if dla is not None:
if not IS_JETSON:
raise ValueError("DLA is only available on NVIDIA Jetson devices")
LOGGER.info(f"{prefix} enabling DLA on core {dla}...")
if not half and not int8:
raise ValueError(
"DLA requires either 'half=True' (FP16) or 'int8=True' (INT8) to be enabled. Please enable one of them and try again."
)
config.default_device_type = trt.DeviceType.DLA
config.DLA_core = int(dla)
config.set_flag(trt.BuilderFlag.GPU_FALLBACK)
# Read ONNX file
parser = trt.OnnxParser(network, logger)
if not parser.parse_from_file(onnx_file):
raise RuntimeError(f"failed to load ONNX file: {onnx_file}")
# Network inputs
inputs = [network.get_input(i) for i in range(network.num_inputs)]
outputs = [network.get_output(i) for i in range(network.num_outputs)]
for inp in inputs:
LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}')
for out in outputs:
LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}')
if dynamic:
profile = builder.create_optimization_profile()
min_shape = (1, shape[1], 32, 32) # minimum input shape
max_shape = (*shape[:2], *(int(max(2, workspace or 2) * d) for d in shape[2:])) # max input shape
for inp in inputs:
profile.set_shape(inp.name, min=min_shape, opt=shape, max=max_shape)
config.add_optimization_profile(profile)
if int8 and not is_trt10: # deprecated in TensorRT 10, causes internal errors
config.set_calibration_profile(profile)
LOGGER.info(f"{prefix} building {'INT8' if int8 else 'FP' + ('16' if half else '32')} engine as {engine_file}")
if int8:
config.set_flag(trt.BuilderFlag.INT8)
config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
class EngineCalibrator(trt.IInt8Calibrator):
def __init__(
self,
dataset, # ultralytics.data.build.InfiniteDataLoader
cache: str = "",
) -> None:
trt.IInt8Calibrator.__init__(self)
self.dataset = dataset
self.data_iter = iter(dataset)
self.algo = (
trt.CalibrationAlgoType.ENTROPY_CALIBRATION_2 # DLA quantization needs ENTROPY_CALIBRATION_2
if dla is not None
else trt.CalibrationAlgoType.MINMAX_CALIBRATION
)
self.batch = dataset.batch_size
self.cache = Path(cache)
def get_algorithm(self) -> trt.CalibrationAlgoType:
return self.algo
def get_batch_size(self) -> int:
return self.batch or 1
def get_batch(self, names) -> list[int] | None:
try:
im0s = next(self.data_iter)["img"] / 255.0
im0s = im0s.to("cuda") if im0s.device.type == "cpu" else im0s
return [int(im0s.data_ptr())]
except StopIteration:
# Return None to signal to TensorRT there is no calibration data remaining
return None
def read_calibration_cache(self) -> bytes | None:
if self.cache.exists() and self.cache.suffix == ".cache":
return self.cache.read_bytes()
def write_calibration_cache(self, cache: bytes) -> None:
_ = self.cache.write_bytes(cache)
# Load dataset w/ builder (for batching) and calibrate
config.int8_calibrator = EngineCalibrator(
dataset=dataset,
cache=str(Path(onnx_file).with_suffix(".cache")),
)
elif half:
config.set_flag(trt.BuilderFlag.FP16)
# Write file
if is_trt10:
# TensorRT 10+ returns bytes directly, not a context manager
engine = builder.build_serialized_network(network, config)
if engine is None:
raise RuntimeError("TensorRT engine build failed, check logs for errors")
with open(engine_file, "wb") as t:
if metadata is not None:
meta = json.dumps(metadata)
t.write(len(meta).to_bytes(4, byteorder="little", signed=True))
t.write(meta.encode())
t.write(engine)
else:
with builder.build_engine(network, config) as engine, open(engine_file, "wb") as t:
if metadata is not None:
meta = json.dumps(metadata)
t.write(len(meta).to_bytes(4, byteorder="little", signed=True))
t.write(meta.encode())
t.write(engine.serialize()) | --- +++ @@ -20,6 +20,20 @@ output_names: list[str] = ["output0"],
dynamic: bool | dict = False,
) -> None:
+ """Export a PyTorch model to ONNX format.
+
+ Args:
+ torch_model (torch.nn.Module): The PyTorch model to export.
+ im (torch.Tensor): Example input tensor for the model.
+ onnx_file (str): Path to save the exported ONNX file.
+ opset (int): ONNX opset version to use for export.
+ input_names (list[str]): List of input tensor names.
+ output_names (list[str]): List of output tensor names.
+ dynamic (bool | dict, optional): Whether to enable dynamic axes.
+
+ Notes:
+ Setting `do_constant_folding=True` may cause issues with DNN inference for torch>=1.12.
+ """
kwargs = {"dynamo": False} if TORCH_2_4 else {}
torch.onnx.export(
torch_model,
@@ -49,6 +63,31 @@ verbose: bool = False,
prefix: str = "",
) -> None:
+ """Export a YOLO model to TensorRT engine format.
+
+ Args:
+ onnx_file (str): Path to the ONNX file to be converted.
+ engine_file (str | None): Path to save the generated TensorRT engine file.
+ workspace (int | None): Workspace size in GB for TensorRT.
+ half (bool, optional): Enable FP16 precision.
+ int8 (bool, optional): Enable INT8 precision.
+ dynamic (bool, optional): Enable dynamic input shapes.
+ shape (tuple[int, int, int, int], optional): Input shape (batch, channels, height, width).
+ dla (int | None): DLA core to use (Jetson devices only).
+ dataset (ultralytics.data.build.InfiniteDataLoader, optional): Dataset for INT8 calibration.
+ metadata (dict | None): Metadata to include in the engine file.
+ verbose (bool, optional): Enable verbose logging.
+ prefix (str, optional): Prefix for log messages.
+
+ Raises:
+ ValueError: If DLA is enabled on non-Jetson devices or required precision is not set.
+ RuntimeError: If the ONNX file cannot be parsed.
+
+ Notes:
+ TensorRT version compatibility is handled for workspace size and engine building.
+ INT8 calibration requires a dataset and generates a calibration cache.
+ Metadata is serialized and written to the engine file if provided.
+ """
import tensorrt as trt
engine_file = engine_file or Path(onnx_file).with_suffix(".engine")
@@ -113,12 +152,32 @@ config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
class EngineCalibrator(trt.IInt8Calibrator):
+ """Custom INT8 calibrator for TensorRT engine optimization.
+
+ This calibrator provides the necessary interface for TensorRT to perform INT8 quantization calibration using
+ a dataset. It handles batch generation, caching, and calibration algorithm selection.
+
+ Attributes:
+ dataset: Dataset for calibration.
+ data_iter: Iterator over the calibration dataset.
+ algo (trt.CalibrationAlgoType): Calibration algorithm type.
+ batch (int): Batch size for calibration.
+ cache (Path): Path to save the calibration cache.
+
+ Methods:
+ get_algorithm: Get the calibration algorithm to use.
+ get_batch_size: Get the batch size to use for calibration.
+ get_batch: Get the next batch to use for calibration.
+ read_calibration_cache: Use existing cache instead of calibrating again.
+ write_calibration_cache: Write calibration cache to disk.
+ """
def __init__(
self,
dataset, # ultralytics.data.build.InfiniteDataLoader
cache: str = "",
) -> None:
+ """Initialize the INT8 calibrator with dataset and cache path."""
trt.IInt8Calibrator.__init__(self)
self.dataset = dataset
self.data_iter = iter(dataset)
@@ -131,12 +190,15 @@ self.cache = Path(cache)
def get_algorithm(self) -> trt.CalibrationAlgoType:
+ """Get the calibration algorithm to use."""
return self.algo
def get_batch_size(self) -> int:
+ """Get the batch size to use for calibration."""
return self.batch or 1
def get_batch(self, names) -> list[int] | None:
+ """Get the next batch to use for calibration, as a list of device memory pointers."""
try:
im0s = next(self.data_iter)["img"] / 255.0
im0s = im0s.to("cuda") if im0s.device.type == "cpu" else im0s
@@ -146,10 +208,12 @@ return None
def read_calibration_cache(self) -> bytes | None:
+ """Use existing cache instead of calibrating again, otherwise, implicitly return None."""
if self.cache.exists() and self.cache.suffix == ".cache":
return self.cache.read_bytes()
def write_calibration_cache(self, cache: bytes) -> None:
+ """Write calibration cache to disk."""
_ = self.cache.write_bytes(cache)
# Load dataset w/ builder (for batching) and calibrate
@@ -179,4 +243,4 @@ meta = json.dumps(metadata)
t.write(len(meta).to_bytes(4, byteorder="little", signed=True))
t.write(meta.encode())
- t.write(engine.serialize())+ t.write(engine.serialize())
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/export/engine.py |
Add detailed documentation for each class | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from functools import partial
from pathlib import Path
import numpy as np
import torch
from ultralytics.nn.modules import Detect, Pose, Pose26
from ultralytics.utils import LOGGER
from ultralytics.utils.downloads import attempt_download_asset
from ultralytics.utils.files import spaces_in_path
from ultralytics.utils.tal import make_anchors
def tf_wrapper(model: torch.nn.Module) -> torch.nn.Module:
for m in model.modules():
if not isinstance(m, Detect):
continue
import types
m._get_decode_boxes = types.MethodType(_tf_decode_boxes, m)
if isinstance(m, Pose):
m.kpts_decode = types.MethodType(partial(_tf_kpts_decode, is_pose26=type(m) is Pose26), m)
return model
def _tf_decode_boxes(self, x: dict[str, torch.Tensor]) -> torch.Tensor:
shape = x["feats"][0].shape # BCHW
boxes = x["boxes"]
if self.format != "imx" and (self.dynamic or self.shape != shape):
self.anchors, self.strides = (a.transpose(0, 1) for a in make_anchors(x["feats"], self.stride, 0.5))
self.shape = shape
grid_h, grid_w = shape[2:4]
grid_size = torch.tensor([grid_w, grid_h, grid_w, grid_h], device=boxes.device).reshape(1, 4, 1)
norm = self.strides / (self.stride[0] * grid_size)
dbox = self.decode_bboxes(self.dfl(boxes) * norm, self.anchors.unsqueeze(0) * norm[:, :2])
return dbox
def _tf_kpts_decode(self, kpts: torch.Tensor, is_pose26: bool = False) -> torch.Tensor:
ndim = self.kpt_shape[1]
bs = kpts.shape[0]
# Precompute normalization factor to increase numerical stability
y = kpts.view(bs, *self.kpt_shape, -1)
grid_h, grid_w = self.shape[2:4]
grid_size = torch.tensor([grid_w, grid_h], device=y.device).reshape(1, 2, 1)
norm = self.strides / (self.stride[0] * grid_size)
a = ((y[:, :, :2] + self.anchors) if is_pose26 else (y[:, :, :2] * 2.0 + (self.anchors - 0.5))) * norm
if ndim == 3:
a = torch.cat((a, y[:, :, 2:3].sigmoid()), 2)
return a.view(bs, self.nk, -1)
def onnx2saved_model(
onnx_file: str,
output_dir: Path,
int8: bool = False,
images: np.ndarray = None,
disable_group_convolution: bool = False,
prefix="",
):
# Pre-download calibration file to fix https://github.com/PINTO0309/onnx2tf/issues/545
onnx2tf_file = Path("calibration_image_sample_data_20x128x128x3_float32.npy")
if not onnx2tf_file.exists():
attempt_download_asset(f"{onnx2tf_file}.zip", unzip=True, delete=True)
np_data = None
if int8:
tmp_file = output_dir / "tmp_tflite_int8_calibration_images.npy" # int8 calibration images file
if images is not None:
output_dir.mkdir(parents=True, exist_ok=True)
np.save(str(tmp_file), images) # BHWC
np_data = [["images", tmp_file, [[[[0, 0, 0]]]], [[[[255, 255, 255]]]]]]
# Patch onnx.helper for onnx_graphsurgeon compatibility with ONNX>=1.17
# The float32_to_bfloat16 function was removed in ONNX 1.17, but onnx_graphsurgeon still uses it
import onnx.helper
if not hasattr(onnx.helper, "float32_to_bfloat16"):
import struct
def float32_to_bfloat16(fval):
ival = struct.unpack("=I", struct.pack("=f", fval))[0]
return ival >> 16
onnx.helper.float32_to_bfloat16 = float32_to_bfloat16
import onnx2tf # scoped for after ONNX export for reduced conflict during import
LOGGER.info(f"{prefix} starting TFLite export with onnx2tf {onnx2tf.__version__}...")
keras_model = onnx2tf.convert(
input_onnx_file_path=onnx_file,
output_folder_path=str(output_dir),
not_use_onnxsim=True,
verbosity="error", # note INT8-FP16 activation bug https://github.com/ultralytics/ultralytics/issues/15873
output_integer_quantized_tflite=int8,
custom_input_op_name_np_data_path=np_data,
enable_batchmatmul_unfold=True and not int8, # fix lower no. of detected objects on GPU delegate
output_signaturedefs=True, # fix error with Attention block group convolution
disable_group_convolution=disable_group_convolution, # fix error with group convolution
)
# Remove/rename TFLite models
if int8:
tmp_file.unlink(missing_ok=True)
for file in output_dir.rglob("*_dynamic_range_quant.tflite"):
file.rename(file.with_name(file.stem.replace("_dynamic_range_quant", "_int8") + file.suffix))
for file in output_dir.rglob("*_integer_quant_with_int16_act.tflite"):
file.unlink() # delete extra fp16 activation TFLite files
return keras_model
def keras2pb(keras_model, file: Path, prefix=""):
import tensorflow as tf
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
LOGGER.info(f"\n{prefix} starting export with tensorflow {tf.__version__}...")
m = tf.function(lambda x: keras_model(x)) # full model
m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
frozen_func = convert_variables_to_constants_v2(m)
frozen_func.graph.as_graph_def()
tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(file.parent), name=file.name, as_text=False)
def tflite2edgetpu(tflite_file: str | Path, output_dir: str | Path, prefix: str = ""):
import subprocess
cmd = (
"edgetpu_compiler "
f'--out_dir "{output_dir}" '
"--show_operations "
"--search_delegate "
"--delegate_search_step 30 "
"--timeout_sec 180 "
f'"{tflite_file}"'
)
LOGGER.info(f"{prefix} running '{cmd}'")
subprocess.run(cmd, shell=True)
def pb2tfjs(pb_file: str, output_dir: str, half: bool = False, int8: bool = False, prefix: str = ""):
import subprocess
import tensorflow as tf
import tensorflowjs as tfjs
LOGGER.info(f"\n{prefix} starting export with tensorflowjs {tfjs.__version__}...")
gd = tf.Graph().as_graph_def() # TF GraphDef
with open(pb_file, "rb") as file:
gd.ParseFromString(file.read())
outputs = ",".join(gd_outputs(gd))
LOGGER.info(f"\n{prefix} output node names: {outputs}")
quantization = "--quantize_float16" if half else "--quantize_uint8" if int8 else ""
with spaces_in_path(pb_file) as fpb_, spaces_in_path(output_dir) as f_: # exporter cannot handle spaces in paths
cmd = (
"tensorflowjs_converter "
f'--input_format=tf_frozen_model {quantization} --output_node_names={outputs} "{fpb_}" "{f_}"'
)
LOGGER.info(f"{prefix} running '{cmd}'")
subprocess.run(cmd, shell=True)
if " " in output_dir:
LOGGER.warning(f"{prefix} your model may not work correctly with spaces in path '{output_dir}'.")
def gd_outputs(gd):
name_list, input_list = [], []
for node in gd.node: # tensorflow.core.framework.node_def_pb2.NodeDef
name_list.append(node.name)
input_list.extend(node.input)
return sorted(f"{x}:0" for x in list(set(name_list) - set(input_list)) if not x.startswith("NoOp")) | --- +++ @@ -16,6 +16,7 @@
def tf_wrapper(model: torch.nn.Module) -> torch.nn.Module:
+ """A wrapper for TensorFlow export compatibility (TF-specific handling is now in head modules)."""
for m in model.modules():
if not isinstance(m, Detect):
continue
@@ -28,6 +29,7 @@
def _tf_decode_boxes(self, x: dict[str, torch.Tensor]) -> torch.Tensor:
+ """Decode bounding boxes for TensorFlow export."""
shape = x["feats"][0].shape # BCHW
boxes = x["boxes"]
if self.format != "imx" and (self.dynamic or self.shape != shape):
@@ -41,6 +43,7 @@
def _tf_kpts_decode(self, kpts: torch.Tensor, is_pose26: bool = False) -> torch.Tensor:
+ """Decode keypoints for TensorFlow export."""
ndim = self.kpt_shape[1]
bs = kpts.shape[0]
# Precompute normalization factor to increase numerical stability
@@ -62,6 +65,23 @@ disable_group_convolution: bool = False,
prefix="",
):
+ """Convert an ONNX model to TensorFlow SavedModel format using onnx2tf.
+
+ Args:
+ onnx_file (str): ONNX file path.
+ output_dir (Path): Output directory path for the SavedModel.
+ int8 (bool, optional): Enable INT8 quantization. Defaults to False.
+ images (np.ndarray, optional): Calibration images for INT8 quantization in BHWC format.
+ disable_group_convolution (bool, optional): Disable group convolution optimization. Defaults to False.
+ prefix (str, optional): Logging prefix. Defaults to "".
+
+ Returns:
+ (keras.Model): Converted Keras model.
+
+ Notes:
+ - Requires onnx2tf package. Downloads calibration data if INT8 quantization is enabled.
+ - Removes temporary files and renames quantized models after conversion.
+ """
# Pre-download calibration file to fix https://github.com/PINTO0309/onnx2tf/issues/545
onnx2tf_file = Path("calibration_image_sample_data_20x128x128x3_float32.npy")
if not onnx2tf_file.exists():
@@ -82,6 +102,7 @@ import struct
def float32_to_bfloat16(fval):
+ """Convert float32 to bfloat16 (truncates lower 16 bits of mantissa)."""
ival = struct.unpack("=I", struct.pack("=f", fval))[0]
return ival >> 16
@@ -113,6 +134,16 @@
def keras2pb(keras_model, file: Path, prefix=""):
+ """Convert a Keras model to TensorFlow GraphDef (.pb) format.
+
+ Args:
+ keras_model (keras.Model): Keras model to convert to frozen graph format.
+ file (Path): Output file path (suffix will be changed to .pb).
+ prefix (str, optional): Logging prefix. Defaults to "".
+
+ Notes:
+ Creates a frozen graph by converting variables to constants for inference optimization.
+ """
import tensorflow as tf
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
@@ -125,6 +156,17 @@
def tflite2edgetpu(tflite_file: str | Path, output_dir: str | Path, prefix: str = ""):
+ """Convert a TensorFlow Lite model to Edge TPU format using the Edge TPU compiler.
+
+ Args:
+ tflite_file (str | Path): Path to the input TensorFlow Lite (.tflite) model file.
+ output_dir (str | Path): Output directory path for the compiled Edge TPU model.
+ prefix (str, optional): Logging prefix. Defaults to "".
+
+ Notes:
+ Requires the Edge TPU compiler to be installed. The function compiles the TFLite model
+ for optimal performance on Google's Edge TPU hardware accelerator.
+ """
import subprocess
cmd = (
@@ -141,6 +183,19 @@
def pb2tfjs(pb_file: str, output_dir: str, half: bool = False, int8: bool = False, prefix: str = ""):
+ """Convert a TensorFlow GraphDef (.pb) model to TensorFlow.js format.
+
+ Args:
+ pb_file (str): Path to the input TensorFlow GraphDef (.pb) model file.
+ output_dir (str): Output directory path for the converted TensorFlow.js model.
+ half (bool, optional): Enable FP16 quantization. Defaults to False.
+ int8 (bool, optional): Enable INT8 quantization. Defaults to False.
+ prefix (str, optional): Logging prefix. Defaults to "".
+
+ Notes:
+ Requires tensorflowjs package. Uses tensorflowjs_converter command-line tool for conversion.
+ Handles spaces in file paths and warns if output directory contains spaces.
+ """
import subprocess
import tensorflow as tf
@@ -168,8 +223,9 @@
def gd_outputs(gd):
+ """Return TensorFlow GraphDef model output node names."""
name_list, input_list = [], []
for node in gd.node: # tensorflow.core.framework.node_def_pb2.NodeDef
name_list.append(node.name)
input_list.extend(node.input)
- return sorted(f"{x}:0" for x in list(set(name_list) - set(input_list)) if not x.startswith("NoOp"))+ return sorted(f"{x}:0" for x in list(set(name_list) - set(input_list)) if not x.startswith("NoOp"))
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/export/tensorflow.py |
Write Python docstrings for this snippet | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import subprocess
import sys
import types
from pathlib import Path
from shutil import which
import numpy as np
import torch
from ultralytics.nn.modules import Detect, Pose, Segment
from ultralytics.utils import LOGGER, WINDOWS
from ultralytics.utils.patches import onnx_export_patch
from ultralytics.utils.tal import make_anchors
from ultralytics.utils.torch_utils import copy_attr
# Configuration for Model Compression Toolkit (MCT) quantization
MCT_CONFIG = {
"YOLO11": {
"detect": {
"layer_names": ["sub", "mul_2", "add_14", "cat_19"],
"weights_memory": 2585350.2439,
"n_layers": {238, 239},
},
"pose": {
"layer_names": ["sub", "mul_2", "add_14", "cat_21", "cat_22", "mul_4", "add_15"],
"weights_memory": 2437771.67,
"n_layers": {257, 258},
},
"classify": {"layer_names": [], "weights_memory": np.inf, "n_layers": {112}},
"segment": {
"layer_names": ["sub", "mul_2", "add_14", "cat_21"],
"weights_memory": 2466604.8,
"n_layers": {265, 266},
},
},
"YOLOv8": {
"detect": {
"layer_names": ["sub", "mul", "add_6", "cat_15"],
"weights_memory": 2550540.8,
"n_layers": {168, 169},
},
"pose": {
"layer_names": ["add_7", "mul_2", "cat_17", "mul", "sub", "add_6", "cat_18"],
"weights_memory": 2482451.85,
"n_layers": {187, 188},
},
"classify": {"layer_names": [], "weights_memory": np.inf, "n_layers": {73}},
"segment": {
"layer_names": ["sub", "mul", "add_6", "cat_17"],
"weights_memory": 2580060.0,
"n_layers": {195, 196},
},
},
}
class FXModel(torch.nn.Module):
def __init__(self, model, imgsz=(640, 640)):
super().__init__()
copy_attr(self, model)
# Explicitly set `model` since `copy_attr` somehow does not copy it.
self.model = model.model
self.imgsz = imgsz
def forward(self, x):
y = [] # outputs
for m in self.model:
if m.f != -1: # if not from previous layer
# from earlier layers
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]
if isinstance(m, Detect):
m._inference = types.MethodType(_inference, m) # bind method to Detect
m.anchors, m.strides = (
x.transpose(0, 1)
for x in make_anchors(
torch.cat([s / m.stride.unsqueeze(-1) for s in self.imgsz], dim=1), m.stride, 0.5
)
)
if type(m) is Pose:
m.forward = types.MethodType(pose_forward, m) # bind method to Pose
if type(m) is Segment:
m.forward = types.MethodType(segment_forward, m) # bind method to Segment
x = m(x) # run
y.append(x) # save output
return x
def _inference(self, x: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
dbox = self.decode_bboxes(self.dfl(x["boxes"]), self.anchors.unsqueeze(0)) * self.strides
return dbox.transpose(1, 2), x["scores"].sigmoid().permute(0, 2, 1)
def pose_forward(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
bs = x[0].shape[0] # batch size
nk_out = getattr(self, "nk_output", self.nk)
kpt = torch.cat([self.cv4[i](x[i]).view(bs, nk_out, -1) for i in range(self.nl)], -1)
# If using Pose26 with 5 dims, convert to 3 dims for export
if hasattr(self, "nk_output") and self.nk_output != self.nk:
spatial = kpt.shape[-1]
kpt = kpt.view(bs, self.kpt_shape[0], self.kpt_shape[1] + 2, spatial)
kpt = kpt[:, :, :-2, :] # Remove sigma_x, sigma_y
kpt = kpt.view(bs, self.nk, spatial)
x = Detect.forward(self, x)
pred_kpt = self.kpts_decode(kpt)
return *x, pred_kpt.permute(0, 2, 1)
def segment_forward(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
p = self.proto(x[0]) # mask protos
bs = p.shape[0] # batch size
mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients
x = Detect.forward(self, x)
return *x, mc.transpose(1, 2), p
class NMSWrapper(torch.nn.Module):
def __init__(
self,
model: torch.nn.Module,
score_threshold: float = 0.001,
iou_threshold: float = 0.7,
max_detections: int = 300,
task: str = "detect",
):
super().__init__()
self.model = model
self.score_threshold = score_threshold
self.iou_threshold = iou_threshold
self.max_detections = max_detections
self.task = task
def forward(self, images):
from edgemdt_cl.pytorch.nms.nms_with_indices import multiclass_nms_with_indices
# model inference
outputs = self.model(images)
boxes, scores = outputs[0], outputs[1]
nms_outputs = multiclass_nms_with_indices(
boxes=boxes,
scores=scores,
score_threshold=self.score_threshold,
iou_threshold=self.iou_threshold,
max_detections=self.max_detections,
)
if self.task == "pose":
kpts = outputs[2] # (bs, max_detections, kpts 17*3)
out_kpts = torch.gather(kpts, 1, nms_outputs.indices.unsqueeze(-1).expand(-1, -1, kpts.size(-1)))
return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, out_kpts
if self.task == "segment":
mc, proto = outputs[2], outputs[3]
out_mc = torch.gather(mc, 1, nms_outputs.indices.unsqueeze(-1).expand(-1, -1, mc.size(-1)))
return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, out_mc, proto
return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, nms_outputs.n_valid
def torch2imx(
model: torch.nn.Module,
file: Path | str,
conf: float,
iou: float,
max_det: int,
metadata: dict | None = None,
gptq: bool = False,
dataset=None,
prefix: str = "",
):
import model_compression_toolkit as mct
import onnx
from edgemdt_tpc import get_target_platform_capabilities
LOGGER.info(f"\n{prefix} starting export with model_compression_toolkit {mct.__version__}...")
def representative_dataset_gen(dataloader=dataset):
for batch in dataloader:
img = batch["img"]
img = img / 255.0
yield [img]
# NOTE: need tpc_version to be "4.0" for IMX500 Pose estimation models
tpc = get_target_platform_capabilities(tpc_version="4.0", device_type="imx500")
bit_cfg = mct.core.BitWidthConfig()
mct_config = MCT_CONFIG["YOLO11" if "C2PSA" in model.__str__() else "YOLOv8"][model.task]
# Check if the model has the expected number of layers
if len(list(model.modules())) not in mct_config["n_layers"]:
raise ValueError("IMX export only supported for YOLOv8n and YOLO11n models.")
for layer_name in mct_config["layer_names"]:
bit_cfg.set_manual_activation_bit_width([mct.core.common.network_editors.NodeNameFilter(layer_name)], 16)
config = mct.core.CoreConfig(
mixed_precision_config=mct.core.MixedPrecisionQuantizationConfig(num_of_images=10),
quantization_config=mct.core.QuantizationConfig(concat_threshold_update=True),
bit_width_config=bit_cfg,
)
resource_utilization = mct.core.ResourceUtilization(weights_memory=mct_config["weights_memory"])
quant_model = (
mct.gptq.pytorch_gradient_post_training_quantization( # Perform Gradient-Based Post Training Quantization
model=model,
representative_data_gen=representative_dataset_gen,
target_resource_utilization=resource_utilization,
gptq_config=mct.gptq.get_pytorch_gptq_config(
n_epochs=1000, use_hessian_based_weights=False, use_hessian_sample_attention=False
),
core_config=config,
target_platform_capabilities=tpc,
)[0]
if gptq
else mct.ptq.pytorch_post_training_quantization( # Perform post training quantization
in_module=model,
representative_data_gen=representative_dataset_gen,
target_resource_utilization=resource_utilization,
core_config=config,
target_platform_capabilities=tpc,
)[0]
)
if model.task != "classify":
quant_model = NMSWrapper(
model=quant_model,
score_threshold=conf or 0.001,
iou_threshold=iou,
max_detections=max_det,
task=model.task,
)
f = Path(str(file).replace(file.suffix, "_imx_model"))
f.mkdir(exist_ok=True)
onnx_model = f / Path(str(file.name).replace(file.suffix, "_imx.onnx")) # js dir
with onnx_export_patch():
mct.exporter.pytorch_export_model(
model=quant_model, save_model_path=onnx_model, repr_dataset=representative_dataset_gen
)
model_onnx = onnx.load(onnx_model) # load onnx model
for k, v in metadata.items():
meta = model_onnx.metadata_props.add()
meta.key, meta.value = k, str(v)
onnx.save(model_onnx, onnx_model)
# Find imxconv-pt binary - check venv bin directory first, then PATH
bin_dir = Path(sys.executable).parent
imxconv = bin_dir / ("imxconv-pt.exe" if WINDOWS else "imxconv-pt")
if not imxconv.exists():
imxconv = which("imxconv-pt") # fallback to PATH
if not imxconv:
raise FileNotFoundError("imxconv-pt not found. Install with: pip install imx500-converter[pt]")
subprocess.run(
[str(imxconv), "-i", str(onnx_model), "-o", str(f), "--no-input-persistency", "--overwrite-output"],
check=True,
)
# Needed for imx models.
with open(f / "labels.txt", "w", encoding="utf-8") as file:
file.writelines([f"{name}\n" for _, name in model.names.items()])
return f | --- +++ @@ -59,8 +59,24 @@
class FXModel(torch.nn.Module):
+ """A custom model class for torch.fx compatibility.
+
+ This class extends `torch.nn.Module` and is designed to ensure compatibility with torch.fx for tracing and graph
+ manipulation. It copies attributes from an existing model and explicitly sets the model attribute to ensure proper
+ copying.
+
+ Attributes:
+ model (nn.Module): The original model's layers.
+ imgsz (tuple[int, int]): The input image size (height, width).
+ """
def __init__(self, model, imgsz=(640, 640)):
+ """Initialize the FXModel.
+
+ Args:
+ model (nn.Module): The original model to wrap for torch.fx compatibility.
+ imgsz (tuple[int, int]): The input image size (height, width). Default is (640, 640).
+ """
super().__init__()
copy_attr(self, model)
# Explicitly set `model` since `copy_attr` somehow does not copy it.
@@ -68,6 +84,17 @@ self.imgsz = imgsz
def forward(self, x):
+ """Forward pass through the model.
+
+ This method performs the forward pass through the model, handling the dependencies between layers and saving
+ intermediate outputs.
+
+ Args:
+ x (torch.Tensor): The input tensor to the model.
+
+ Returns:
+ (torch.Tensor): The output tensor from the model.
+ """
y = [] # outputs
for m in self.model:
if m.f != -1: # if not from previous layer
@@ -91,11 +118,13 @@
def _inference(self, x: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Decode boxes and cls scores for imx object detection."""
dbox = self.decode_bboxes(self.dfl(x["boxes"]), self.anchors.unsqueeze(0)) * self.strides
return dbox.transpose(1, 2), x["scores"].sigmoid().permute(0, 2, 1)
def pose_forward(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Forward pass for imx pose estimation, including keypoint decoding."""
bs = x[0].shape[0] # batch size
nk_out = getattr(self, "nk_output", self.nk)
kpt = torch.cat([self.cv4[i](x[i]).view(bs, nk_out, -1) for i in range(self.nl)], -1)
@@ -112,6 +141,7 @@
def segment_forward(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Forward pass for imx segmentation."""
p = self.proto(x[0]) # mask protos
bs = p.shape[0] # batch size
mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients
@@ -120,6 +150,7 @@
class NMSWrapper(torch.nn.Module):
+ """Wrap PyTorch Module with multiclass_nms layer from edge-mdt-cl."""
def __init__(
self,
@@ -129,6 +160,15 @@ max_detections: int = 300,
task: str = "detect",
):
+ """Initialize NMSWrapper with PyTorch Module and NMS parameters.
+
+ Args:
+ model (torch.nn.Module): Model instance.
+ score_threshold (float): Score threshold for non-maximum suppression.
+ iou_threshold (float): Intersection over union threshold for non-maximum suppression.
+ max_detections (int): The number of detections to return.
+ task (str): Task type, one of 'detect', 'pose', or 'segment'.
+ """
super().__init__()
self.model = model
self.score_threshold = score_threshold
@@ -137,6 +177,7 @@ self.task = task
def forward(self, images):
+ """Forward pass with model inference and NMS post-processing."""
from edgemdt_cl.pytorch.nms.nms_with_indices import multiclass_nms_with_indices
# model inference
@@ -171,6 +212,40 @@ dataset=None,
prefix: str = "",
):
+ """Export YOLO model to IMX format for deployment on Sony IMX500 devices.
+
+ This function quantizes a YOLO model using Model Compression Toolkit (MCT) and exports it to IMX format compatible
+ with Sony IMX500 edge devices. It supports both YOLOv8n and YOLO11n models for detection, segmentation, pose
+ estimation, and classification tasks.
+
+ Args:
+ model (torch.nn.Module): The YOLO model to export. Must be YOLOv8n or YOLO11n.
+ file (Path | str): Output file path for the exported model.
+ conf (float): Confidence threshold for NMS post-processing.
+ iou (float): IoU threshold for NMS post-processing.
+ max_det (int): Maximum number of detections to return.
+ metadata (dict | None, optional): Metadata to embed in the ONNX model. Defaults to None.
+ gptq (bool, optional): Whether to use Gradient-Based Post Training Quantization. If False, uses standard Post
+ Training Quantization. Defaults to False.
+ dataset (optional): Representative dataset for quantization calibration. Defaults to None.
+ prefix (str, optional): Logging prefix string. Defaults to "".
+
+ Returns:
+ (Path): Path to the exported IMX model directory.
+
+ Raises:
+ ValueError: If the model is not a supported YOLOv8n or YOLO11n variant.
+
+ Examples:
+ >>> from ultralytics import YOLO
+ >>> model = YOLO("yolo11n.pt")
+ >>> path = torch2imx(model, "model.imx", conf=0.25, iou=0.7, max_det=300)
+
+ Notes:
+ - Requires model_compression_toolkit, onnx, edgemdt_tpc, and edge-mdt-cl packages
+ - Only supports YOLOv8n and YOLO11n models (detection, segmentation, pose, and classification tasks)
+ - Output includes quantized ONNX model, IMX binary, and labels.txt file
+ """
import model_compression_toolkit as mct
import onnx
from edgemdt_tpc import get_target_platform_capabilities
@@ -267,4 +342,4 @@ with open(f / "labels.txt", "w", encoding="utf-8") as file:
file.writelines([f"{name}\n" for _, name in model.names.items()])
- return f+ return f
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/export/imx.py |
Please document this code using docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from functools import partial
from pathlib import Path
import torch
from ultralytics.nn.modules import Pose, Pose26
from ultralytics.utils import LOGGER, YAML
def executorch_wrapper(model: torch.nn.Module) -> torch.nn.Module:
import types
for m in model.modules():
if not isinstance(m, Pose):
continue
m.kpts_decode = types.MethodType(partial(_executorch_kpts_decode, is_pose26=type(m) is Pose26), m)
return model
def _executorch_kpts_decode(self, kpts: torch.Tensor, is_pose26: bool = False) -> torch.Tensor:
ndim = self.kpt_shape[1]
bs = kpts.shape[0]
y = kpts.view(bs, *self.kpt_shape, -1)
# XNNPACK requires explicit dim matching for broadcasting, expand 2D tensors to 4D.
anchors = self.anchors[None, None]
strides = self.strides[None, None]
a = ((y[:, :, :2] + anchors) if is_pose26 else (y[:, :, :2] * 2.0 + (anchors - 0.5))) * strides
if ndim == 3:
a = torch.cat((a, y[:, :, 2:3].sigmoid()), 2)
return a.view(bs, self.nk, -1)
def torch2executorch(
model: torch.nn.Module,
file: Path | str,
sample_input: torch.Tensor,
metadata: dict | None = None,
prefix: str = "",
) -> str:
from executorch import version as executorch_version
from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner
from executorch.exir import to_edge_transform_and_lower
LOGGER.info(f"\n{prefix} starting export with ExecuTorch {executorch_version.__version__}...")
file = Path(file)
output_dir = Path(str(file).replace(file.suffix, "_executorch_model"))
output_dir.mkdir(parents=True, exist_ok=True)
pte_file = output_dir / file.with_suffix(".pte").name
et_program = to_edge_transform_and_lower(
torch.export.export(model, (sample_input,)),
partitioner=[XnnpackPartitioner()],
).to_executorch()
pte_file.write_bytes(et_program.buffer)
if metadata is not None:
YAML.save(output_dir / "metadata.yaml", metadata)
return str(output_dir) | --- +++ @@ -12,6 +12,7 @@
def executorch_wrapper(model: torch.nn.Module) -> torch.nn.Module:
+ """Apply ExecuTorch-specific model patches required for export/runtime compatibility."""
import types
for m in model.modules():
@@ -22,6 +23,7 @@
def _executorch_kpts_decode(self, kpts: torch.Tensor, is_pose26: bool = False) -> torch.Tensor:
+ """Decode pose keypoints for ExecuTorch export with XNNPACK-safe broadcasting."""
ndim = self.kpt_shape[1]
bs = kpts.shape[0]
y = kpts.view(bs, *self.kpt_shape, -1)
@@ -42,6 +44,18 @@ metadata: dict | None = None,
prefix: str = "",
) -> str:
+ """Export a PyTorch model to ExecuTorch format.
+
+ Args:
+ model (torch.nn.Module): The PyTorch model to export.
+ file (Path | str): Source model file path used to derive output names.
+ sample_input (torch.Tensor): Example input tensor for tracing/export.
+ metadata (dict | None, optional): Optional metadata to save as YAML.
+ prefix (str, optional): Prefix for log messages.
+
+ Returns:
+ (str): Path to the exported ExecuTorch model directory.
+ """
from executorch import version as executorch_version
from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner
from executorch.exir import to_edge_transform_and_lower
@@ -62,4 +76,4 @@ if metadata is not None:
YAML.save(output_dir / "metadata.yaml", metadata)
- return str(output_dir)+ return str(output_dir)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/export/executorch.py |
Add docstrings to improve readability | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import time
from contextlib import contextmanager
from copy import copy
from pathlib import Path
from typing import Any
import cv2
import numpy as np
import torch
from PIL import Image
# OpenCV Multilanguage-friendly functions ------------------------------------------------------------------------------
_imshow = cv2.imshow # copy to avoid recursion errors
def imread(filename: str, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None:
file_bytes = np.fromfile(filename, np.uint8)
if filename.endswith((".tiff", ".tif")):
success, frames = cv2.imdecodemulti(file_bytes, cv2.IMREAD_UNCHANGED)
if success:
# Handle multi-frame TIFFs and color images
return frames[0] if len(frames) == 1 and frames[0].ndim == 3 else np.stack(frames, axis=2)
return None
else:
im = cv2.imdecode(file_bytes, flags)
# Fallback for formats OpenCV imdecode may not support (AVIF, HEIC)
if im is None and filename.lower().endswith((".avif", ".heic")):
im = _imread_pil(filename, flags)
return im[..., None] if im is not None and im.ndim == 2 else im # Always ensure 3 dimensions
# PIL patches ---------------------------------------------------------------------------------------------------------
_image_open = Image.open # copy to avoid recursion errors
_pil_plugins_registered = False
def image_open(filename, *args, **kwargs):
global _pil_plugins_registered
if _pil_plugins_registered:
return _image_open(filename, *args, **kwargs)
try:
return _image_open(filename, *args, **kwargs)
except Exception:
from ultralytics.utils.checks import check_requirements
check_requirements("pi-heif")
from pi_heif import register_heif_opener
register_heif_opener()
_pil_plugins_registered = True
return _image_open(filename, *args, **kwargs)
Image.open = image_open # apply patch
def _imread_pil(filename: str, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None:
try:
with Image.open(filename) as img:
if flags == cv2.IMREAD_GRAYSCALE:
return np.asarray(img.convert("L"))
return cv2.cvtColor(np.asarray(img.convert("RGB")), cv2.COLOR_RGB2BGR)
except Exception:
return None
def imwrite(filename: str, img: np.ndarray, params: list[int] | None = None) -> bool:
try:
cv2.imencode(Path(filename).suffix, img, params)[1].tofile(filename)
return True
except Exception:
return False
def imshow(winname: str, mat: np.ndarray) -> None:
_imshow(winname.encode("unicode_escape").decode(), mat)
# PyTorch functions ----------------------------------------------------------------------------------------------------
_torch_save = torch.save
def torch_load(*args, **kwargs):
from ultralytics.utils.torch_utils import TORCH_1_13
if TORCH_1_13 and "weights_only" not in kwargs:
kwargs["weights_only"] = False
return torch.load(*args, **kwargs)
def torch_save(*args, **kwargs):
for i in range(4): # 3 retries
try:
return _torch_save(*args, **kwargs)
except RuntimeError as e: # Unable to save, possibly waiting for device to flush or antivirus scan
if i == 3:
raise e
time.sleep((2**i) / 2) # Exponential backoff: 0.5s, 1.0s, 2.0s
@contextmanager
def arange_patch(args):
if args.dynamic and args.half and args.format == "onnx":
func = torch.arange
def arange(*args, dtype=None, **kwargs):
return func(*args, **kwargs).to(dtype) # cast to dtype instead of passing dtype
torch.arange = arange # patch
yield
torch.arange = func # unpatch
else:
yield
@contextmanager
def onnx_export_patch():
from ultralytics.utils.torch_utils import TORCH_2_9
if TORCH_2_9:
func = torch.onnx.export
def torch_export(*args, **kwargs):
return func(*args, **kwargs, dynamo=False)
torch.onnx.export = torch_export # patch
yield
torch.onnx.export = func # unpatch
else:
yield
@contextmanager
def override_configs(args, overrides: dict[str, Any] | None = None):
if overrides:
original_args = copy(args)
for key, value in overrides.items():
setattr(args, key, value)
try:
yield args
finally:
args.__dict__.update(original_args.__dict__)
else:
yield args | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Monkey patches to update/extend functionality of existing functions."""
from __future__ import annotations
@@ -18,6 +19,19 @@
def imread(filename: str, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None:
+ """Read an image from a file with multilanguage filename support.
+
+ Args:
+ filename (str): Path to the file to read.
+ flags (int, optional): Flag that can take values of cv2.IMREAD_*. Controls how the image is read.
+
+ Returns:
+ (np.ndarray | None): The read image array, or None if reading fails.
+
+ Examples:
+ >>> img = imread("path/to/image.jpg")
+ >>> img = imread("path/to/image.jpg", cv2.IMREAD_GRAYSCALE)
+ """
file_bytes = np.fromfile(filename, np.uint8)
if filename.endswith((".tiff", ".tif")):
success, frames = cv2.imdecodemulti(file_bytes, cv2.IMREAD_UNCHANGED)
@@ -39,6 +53,20 @@
def image_open(filename, *args, **kwargs):
+ """Open an image with PIL, lazily registering the HEIF plugin on first failure.
+
+ This monkey-patches PIL.Image.open to add HEIC/HEIF support via pi-heif (lightweight, decode-only), avoiding the
+ ~800ms startup cost of importing the package unless actually needed. AVIF is supported natively by Pillow 12+ and
+ does not require a plugin.
+
+ Args:
+ filename (str): Path to the image file.
+ *args (Any): Additional positional arguments passed to PIL.Image.open.
+ **kwargs (Any): Additional keyword arguments passed to PIL.Image.open.
+
+ Returns:
+ (PIL.Image.Image): The opened PIL image.
+ """
global _pil_plugins_registered
if _pil_plugins_registered:
return _image_open(filename, *args, **kwargs)
@@ -59,6 +87,15 @@
def _imread_pil(filename: str, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None:
+ """Read an image using PIL as fallback for formats not supported by OpenCV.
+
+ Args:
+ filename (str): Path to the file to read.
+ flags (int, optional): OpenCV imread flags (used to determine grayscale conversion).
+
+ Returns:
+ (np.ndarray | None): The read image array in BGR format, or None if reading fails.
+ """
try:
with Image.open(filename) as img:
if flags == cv2.IMREAD_GRAYSCALE:
@@ -69,6 +106,23 @@
def imwrite(filename: str, img: np.ndarray, params: list[int] | None = None) -> bool:
+ """Write an image to a file with multilanguage filename support.
+
+ Args:
+ filename (str): Path to the file to write.
+ img (np.ndarray): Image to write.
+ params (list[int], optional): Additional parameters for image encoding.
+
+ Returns:
+ (bool): True if the file was written successfully, False otherwise.
+
+ Examples:
+ >>> import numpy as np
+ >>> img = np.zeros((100, 100, 3), dtype=np.uint8) # Create a black image
+ >>> success = imwrite("output.jpg", img) # Write image to file
+ >>> print(success)
+ True
+ """
try:
cv2.imencode(Path(filename).suffix, img, params)[1].tofile(filename)
return True
@@ -77,6 +131,22 @@
def imshow(winname: str, mat: np.ndarray) -> None:
+ """Display an image in the specified window with multilanguage window name support.
+
+ This function is a wrapper around OpenCV's imshow function that displays an image in a named window. It handles
+ multilanguage window names by encoding them properly for OpenCV compatibility.
+
+ Args:
+ winname (str): Name of the window where the image will be displayed. If a window with this name already exists,
+ the image will be displayed in that window.
+ mat (np.ndarray): Image to be shown. Should be a valid numpy array representing an image.
+
+ Examples:
+ >>> import numpy as np
+ >>> img = np.zeros((300, 300, 3), dtype=np.uint8) # Create a black image
+ >>> img[:100, :100] = [255, 0, 0] # Add a blue square
+ >>> imshow("Example Window", img) # Display the image
+ """
_imshow(winname.encode("unicode_escape").decode(), mat)
@@ -85,6 +155,21 @@
def torch_load(*args, **kwargs):
+ """Load a PyTorch model with updated arguments to avoid warnings.
+
+ This function wraps torch.load and adds the 'weights_only' argument for PyTorch 1.13.0+ to prevent warnings.
+
+ Args:
+ *args (Any): Variable length argument list to pass to torch.load.
+ **kwargs (Any): Arbitrary keyword arguments to pass to torch.load.
+
+ Returns:
+ (Any): The loaded PyTorch object.
+
+ Notes:
+ For PyTorch versions 1.13 and above, this function automatically sets `weights_only=False` if the argument is
+ not provided, to avoid deprecation warnings.
+ """
from ultralytics.utils.torch_utils import TORCH_1_13
if TORCH_1_13 and "weights_only" not in kwargs:
@@ -94,6 +179,19 @@
def torch_save(*args, **kwargs):
+ """Save PyTorch objects with retry mechanism for robustness.
+
+ This function wraps torch.save with 3 retries and exponential backoff in case of save failures, which can occur due
+ to device flushing delays or antivirus scanning.
+
+ Args:
+ *args (Any): Positional arguments to pass to torch.save.
+ **kwargs (Any): Keyword arguments to pass to torch.save.
+
+ Examples:
+ >>> model = torch.nn.Linear(10, 1)
+ >>> torch_save(model.state_dict(), "model.pt")
+ """
for i in range(4): # 3 retries
try:
return _torch_save(*args, **kwargs)
@@ -105,10 +203,15 @@
@contextmanager
def arange_patch(args):
+ """Workaround for ONNX torch.arange incompatibility with FP16.
+
+ https://github.com/pytorch/pytorch/issues/148041.
+ """
if args.dynamic and args.half and args.format == "onnx":
func = torch.arange
def arange(*args, dtype=None, **kwargs):
+ """Wrap torch.arange to cast dtype after creation instead of passing it directly."""
return func(*args, **kwargs).to(dtype) # cast to dtype instead of passing dtype
torch.arange = arange # patch
@@ -120,12 +223,14 @@
@contextmanager
def onnx_export_patch():
+ """Workaround for ONNX export issues in PyTorch 2.9+ with Dynamo enabled."""
from ultralytics.utils.torch_utils import TORCH_2_9
if TORCH_2_9:
func = torch.onnx.export
def torch_export(*args, **kwargs):
+ """Export model to ONNX format with Dynamo disabled for compatibility."""
return func(*args, **kwargs, dynamo=False)
torch.onnx.export = torch_export # patch
@@ -137,6 +242,15 @@
@contextmanager
def override_configs(args, overrides: dict[str, Any] | None = None):
+ """Context manager to temporarily override configurations in args.
+
+ Args:
+ args (IterableSimpleNamespace): Original configuration arguments.
+ overrides (dict[str, Any] | None): Dictionary of overrides to apply.
+
+ Yields:
+ (IterableSimpleNamespace): Configuration arguments with overrides applied.
+ """
if overrides:
original_args = copy(args)
for key, value in overrides.items():
@@ -146,4 +260,4 @@ finally:
args.__dict__.update(original_args.__dict__)
else:
- yield args+ yield args
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/patches.py |
Write docstrings including parameters and return values | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import os
from pathlib import Path
from time import sleep
from ultralytics.utils import LOGGER, TQDM
class _ProgressReader:
def __init__(self, file_path, pbar):
self.file = open(file_path, "rb")
self.pbar = pbar
self._size = os.path.getsize(file_path)
def read(self, size=-1):
data = self.file.read(size)
if data and self.pbar:
self.pbar.update(len(data))
return data
def __len__(self):
return self._size
def close(self):
self.file.close()
def safe_upload(
file: str | Path,
url: str,
headers: dict | None = None,
retry: int = 2,
timeout: int = 600,
progress: bool = False,
) -> bool:
import requests
file = Path(file)
if not file.exists():
raise FileNotFoundError(f"File not found: {file}")
file_size = file.stat().st_size
desc = f"Uploading {file.name}"
# Prepare headers (Content-Length set automatically from file size)
upload_headers = {"Content-Type": "application/octet-stream"}
if headers:
upload_headers.update(headers)
last_error = None
for attempt in range(retry + 1):
pbar = None
reader = None
try:
if progress:
pbar = TQDM(total=file_size, desc=desc, unit="B", unit_scale=True, unit_divisor=1024)
reader = _ProgressReader(file, pbar)
r = requests.put(url, data=reader, headers=upload_headers, timeout=timeout)
r.raise_for_status()
reader.close()
reader = None # Prevent double-close in finally
if pbar:
pbar.close()
pbar = None
LOGGER.info(f"Uploaded {file.name} ✅")
return True
except requests.exceptions.HTTPError as e:
status = e.response.status_code if e.response is not None else 0
if 400 <= status < 500 and status not in {408, 429}:
LOGGER.warning(f"{desc} failed: {status} {getattr(e.response, 'reason', '')}")
return False
last_error = f"HTTP {status}"
except Exception as e:
last_error = str(e)
finally:
if reader:
reader.close()
if pbar:
pbar.close()
if attempt < retry:
wait_time = 2 ** (attempt + 1)
LOGGER.warning(f"{desc} failed ({last_error}), retrying {attempt + 1}/{retry} in {wait_time}s...")
sleep(wait_time)
LOGGER.warning(f"{desc} failed after {retry + 1} attempts: {last_error}")
return False | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Upload utilities for Ultralytics, mirroring downloads.py patterns."""
from __future__ import annotations
@@ -10,6 +11,7 @@
class _ProgressReader:
+ """File wrapper that reports read progress for upload monitoring."""
def __init__(self, file_path, pbar):
self.file = open(file_path, "rb")
@@ -17,15 +19,18 @@ self._size = os.path.getsize(file_path)
def read(self, size=-1):
+ """Read data and update progress bar."""
data = self.file.read(size)
if data and self.pbar:
self.pbar.update(len(data))
return data
def __len__(self):
+ """Return file size for Content-Length header."""
return self._size
def close(self):
+ """Close the file."""
self.file.close()
@@ -37,6 +42,23 @@ timeout: int = 600,
progress: bool = False,
) -> bool:
+ """Upload a file to a URL with retry logic and optional progress bar.
+
+ Args:
+ file (str | Path): Path to the file to upload.
+ url (str): The URL endpoint to upload the file to (e.g., signed GCS URL).
+ headers (dict, optional): Additional headers to include in the request.
+ retry (int, optional): Number of retry attempts on failure (default: 2 for 3 total attempts).
+ timeout (int, optional): Request timeout in seconds.
+ progress (bool, optional): Whether to display a progress bar during upload.
+
+ Returns:
+ (bool): True if upload succeeded, False otherwise.
+
+ Examples:
+ >>> from ultralytics.utils.uploads import safe_upload
+ >>> success = safe_upload("model.pt", "https://storage.googleapis.com/...", progress=True)
+ """
import requests
file = Path(file)
@@ -90,4 +112,4 @@ sleep(wait_time)
LOGGER.warning(f"{desc} failed after {retry + 1} attempts: {last_error}")
- return False+ return False
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/uploads.py |
Add professional docstrings to my codebase | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import math
import warnings
from collections import defaultdict
from pathlib import Path
from typing import Any
import numpy as np
import torch
from ultralytics.utils import LOGGER, DataExportMixin, SimpleClass, TryExcept, checks, plt_settings
OKS_SIGMA = (
np.array(
[0.26, 0.25, 0.25, 0.35, 0.35, 0.79, 0.79, 0.72, 0.72, 0.62, 0.62, 1.07, 1.07, 0.87, 0.87, 0.89, 0.89],
dtype=np.float32,
)
/ 10.0
)
RLE_WEIGHT = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.2, 1.2, 1.5, 1.5, 1.0, 1.0, 1.2, 1.2, 1.5, 1.5])
def bbox_ioa(box1: np.ndarray, box2: np.ndarray, iou: bool = False, eps: float = 1e-7) -> np.ndarray:
# Get the coordinates of bounding boxes
b1_x1, b1_y1, b1_x2, b1_y2 = box1.T
b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
# Intersection area
inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * (
np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)
).clip(0)
# Box2 area
area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)
if iou:
box1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)
area = area + box1_area[:, None] - inter_area
# Intersection over box2 area
return inter_area / (area + eps)
def box_iou(box1: torch.Tensor, box2: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:
# NOTE: Need .float() to get accurate iou values
# inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
(a1, a2), (b1, b2) = box1.float().unsqueeze(1).chunk(2, 2), box2.float().unsqueeze(0).chunk(2, 2)
inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp_(0).prod(2)
# IoU = inter / (area1 + area2 - inter)
return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)
def bbox_iou(
box1: torch.Tensor,
box2: torch.Tensor,
xywh: bool = True,
GIoU: bool = False,
DIoU: bool = False,
CIoU: bool = False,
eps: float = 1e-7,
) -> torch.Tensor:
# Get the coordinates of bounding boxes
if xywh: # transform from xywh to xyxy
(x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
else: # x1, y1, x2, y2 = box1
b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
# Intersection area
inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * (
b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)
).clamp_(0)
# Union Area
union = w1 * h1 + w2 * h2 - inter + eps
# IoU
iou = inter / union
if CIoU or DIoU or GIoU:
cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
c2 = cw.pow(2) + ch.pow(2) + eps # convex diagonal squared
rho2 = (
(b2_x1 + b2_x2 - b1_x1 - b1_x2).pow(2) + (b2_y1 + b2_y2 - b1_y1 - b1_y2).pow(2)
) / 4 # center dist**2
if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2)
with torch.no_grad():
alpha = v / (v - iou + (1 + eps))
return iou - (rho2 / c2 + v * alpha) # CIoU
return iou - rho2 / c2 # DIoU
c_area = cw * ch + eps # convex area
return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
return iou # IoU
def mask_iou(mask1: torch.Tensor, mask2: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:
intersection = torch.matmul(mask1, mask2.T).clamp_(0)
union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection
return intersection / (union + eps)
def kpt_iou(
kpt1: torch.Tensor, kpt2: torch.Tensor, area: torch.Tensor, sigma: list[float], eps: float = 1e-7
) -> torch.Tensor:
d = (kpt1[:, None, :, 0] - kpt2[..., 0]).pow(2) + (kpt1[:, None, :, 1] - kpt2[..., 1]).pow(2) # (N, M, 17)
sigma = torch.tensor(sigma, device=kpt1.device, dtype=kpt1.dtype) # (17, )
kpt_mask = kpt1[..., 2] != 0 # (N, 17)
e = d / ((2 * sigma).pow(2) * (area[:, None, None] + eps) * 2) # from cocoeval
# e = d / ((area[None, :, None] + eps) * sigma) ** 2 / 2 # from formula
return ((-e).exp() * kpt_mask[:, None]).sum(-1) / (kpt_mask.sum(-1)[:, None] + eps)
def _get_covariance_matrix(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
# Gaussian bounding boxes, ignore the center points (the first two columns) because they are not needed here.
gbbs = torch.cat((boxes[:, 2:4].pow(2) / 12, boxes[:, 4:]), dim=-1)
a, b, c = gbbs.split(1, dim=-1)
cos = c.cos()
sin = c.sin()
cos2 = cos.pow(2)
sin2 = sin.pow(2)
return a * cos2 + b * sin2, a * sin2 + b * cos2, (a - b) * cos * sin
def probiou(obb1: torch.Tensor, obb2: torch.Tensor, CIoU: bool = False, eps: float = 1e-7) -> torch.Tensor:
x1, y1 = obb1[..., :2].split(1, dim=-1)
x2, y2 = obb2[..., :2].split(1, dim=-1)
a1, b1, c1 = _get_covariance_matrix(obb1)
a2, b2, c2 = _get_covariance_matrix(obb2)
t1 = (
((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)
) * 0.25
t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5
t3 = (
((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2))
/ (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps)
+ eps
).log() * 0.5
bd = (t1 + t2 + t3).clamp(eps, 100.0)
hd = (1.0 - (-bd).exp() + eps).sqrt()
iou = 1 - hd
if CIoU: # only include the wh aspect ratio part
w1, h1 = obb1[..., 2:4].split(1, dim=-1)
w2, h2 = obb2[..., 2:4].split(1, dim=-1)
v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2)
with torch.no_grad():
alpha = v / (v - iou + (1 + eps))
return iou - v * alpha # CIoU
return iou
def batch_probiou(obb1: torch.Tensor | np.ndarray, obb2: torch.Tensor | np.ndarray, eps: float = 1e-7) -> torch.Tensor:
obb1 = torch.from_numpy(obb1) if isinstance(obb1, np.ndarray) else obb1
obb2 = torch.from_numpy(obb2) if isinstance(obb2, np.ndarray) else obb2
x1, y1 = obb1[..., :2].split(1, dim=-1)
x2, y2 = (x.squeeze(-1)[None] for x in obb2[..., :2].split(1, dim=-1))
a1, b1, c1 = _get_covariance_matrix(obb1)
a2, b2, c2 = (x.squeeze(-1)[None] for x in _get_covariance_matrix(obb2))
t1 = (
((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)
) * 0.25
t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5
t3 = (
((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2))
/ (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps)
+ eps
).log() * 0.5
bd = (t1 + t2 + t3).clamp(eps, 100.0)
hd = (1.0 - (-bd).exp() + eps).sqrt()
return 1 - hd
def smooth_bce(eps: float = 0.1) -> tuple[float, float]:
return 1.0 - 0.5 * eps, 0.5 * eps
class ConfusionMatrix(DataExportMixin):
def __init__(self, names: dict[int, str] = {}, task: str = "detect", save_matches: bool = False):
self.task = task
self.nc = len(names) # number of classes
self.matrix = np.zeros((self.nc, self.nc)) if self.task == "classify" else np.zeros((self.nc + 1, self.nc + 1))
self.names = names # name of classes
self.matches = {} if save_matches else None
def _append_matches(self, mtype: str, batch: dict[str, Any], idx: int) -> None:
if self.matches is None:
return
for k, v in batch.items():
if k in {"bboxes", "cls", "conf", "keypoints"}:
self.matches[mtype][k] += v[[idx]]
elif k == "masks":
# NOTE: masks.max() > 1.0 means overlap_mask=True with (1, H, W) shape
self.matches[mtype][k] += [v[0] == idx + 1] if v.max() > 1.0 else [v[idx]]
def process_cls_preds(self, preds: list[torch.Tensor], targets: list[torch.Tensor]) -> None:
preds, targets = torch.cat(preds)[:, 0], torch.cat(targets)
for p, t in zip(preds.cpu().numpy(), targets.cpu().numpy()):
self.matrix[p][t] += 1
def process_batch(
self,
detections: dict[str, torch.Tensor],
batch: dict[str, Any],
conf: float = 0.25,
iou_thres: float = 0.45,
) -> None:
gt_cls, gt_bboxes = batch["cls"], batch["bboxes"]
if self.matches is not None: # only if visualization is enabled
self.matches = {k: defaultdict(list) for k in {"TP", "FP", "FN", "GT"}}
for i in range(gt_cls.shape[0]):
self._append_matches("GT", batch, i) # store GT
is_obb = gt_bboxes.shape[1] == 5 # check if boxes contains angle for OBB
conf = 0.25 if conf in {None, 0.01 if is_obb else 0.001} else conf # apply 0.25 if default val conf is passed
no_pred = detections["cls"].shape[0] == 0
if gt_cls.shape[0] == 0: # Check if labels is empty
if not no_pred:
detections = {k: detections[k][detections["conf"] > conf] for k in detections}
detection_classes = detections["cls"].int().tolist()
for i, dc in enumerate(detection_classes):
self.matrix[dc, self.nc] += 1 # FP
self._append_matches("FP", detections, i)
return
if no_pred:
gt_classes = gt_cls.int().tolist()
for i, gc in enumerate(gt_classes):
self.matrix[self.nc, gc] += 1 # FN
self._append_matches("FN", batch, i)
return
detections = {k: detections[k][detections["conf"] > conf] for k in detections}
gt_classes = gt_cls.int().tolist()
detection_classes = detections["cls"].int().tolist()
bboxes = detections["bboxes"]
iou = batch_probiou(gt_bboxes, bboxes) if is_obb else box_iou(gt_bboxes, bboxes)
x = torch.where(iou > iou_thres)
if x[0].shape[0]:
matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
if x[0].shape[0] > 1:
matches = matches[matches[:, 2].argsort()[::-1]]
matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
matches = matches[matches[:, 2].argsort()[::-1]]
matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
else:
matches = np.zeros((0, 3))
n = matches.shape[0] > 0
m0, m1, _ = matches.transpose().astype(int)
for i, gc in enumerate(gt_classes):
j = m0 == i
if n and sum(j) == 1:
dc = detection_classes[m1[j].item()]
self.matrix[dc, gc] += 1 # TP if class is correct else both an FP and an FN
if dc == gc:
self._append_matches("TP", detections, m1[j].item())
else:
self._append_matches("FP", detections, m1[j].item())
self._append_matches("FN", batch, i)
else:
self.matrix[self.nc, gc] += 1 # FN
self._append_matches("FN", batch, i)
for i, dc in enumerate(detection_classes):
if not any(m1 == i):
self.matrix[dc, self.nc] += 1 # FP
self._append_matches("FP", detections, i)
def matrix(self):
return self.matrix
def tp_fp(self) -> tuple[np.ndarray, np.ndarray]:
tp = self.matrix.diagonal() # true positives
fp = self.matrix.sum(1) - tp # false positives
# fn = self.matrix.sum(0) - tp # false negatives (missed detections)
return (tp, fp) if self.task == "classify" else (tp[:-1], fp[:-1]) # remove background class if task=detect
def plot_matches(self, img: torch.Tensor, im_file: str, save_dir: Path) -> None:
if not self.matches:
return
from .ops import xyxy2xywh
from .plotting import plot_images
# Create batch of 4 (GT, TP, FP, FN)
labels = defaultdict(list)
for i, mtype in enumerate(["GT", "FP", "TP", "FN"]):
mbatch = self.matches[mtype]
if "conf" not in mbatch:
mbatch["conf"] = torch.tensor([1.0] * len(mbatch["bboxes"]), device=img.device)
mbatch["batch_idx"] = torch.ones(len(mbatch["bboxes"]), device=img.device) * i
for k in mbatch.keys():
labels[k] += mbatch[k]
labels = {k: torch.stack(v, 0) if len(v) else torch.empty(0) for k, v in labels.items()}
if self.task != "obb" and labels["bboxes"].shape[0]:
labels["bboxes"] = xyxy2xywh(labels["bboxes"])
(save_dir / "visualizations").mkdir(parents=True, exist_ok=True)
plot_images(
labels,
img.repeat(4, 1, 1, 1),
paths=["Ground Truth", "False Positives", "True Positives", "False Negatives"],
fname=save_dir / "visualizations" / Path(im_file).name,
names=self.names,
max_subplots=4,
conf_thres=0.001,
)
@TryExcept(msg="ConfusionMatrix plot failure")
@plt_settings()
def plot(self, normalize: bool = True, save_dir: str = "", on_plot=None):
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1) # normalize columns
array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
fig, ax = plt.subplots(1, 1, figsize=(12, 9))
names, n = list(self.names.values()), self.nc
if self.nc >= 100: # downsample for large class count
k = max(2, self.nc // 60) # step size for downsampling, always > 1
keep_idx = slice(None, None, k) # create slice instead of array
names = names[keep_idx] # slice class names
array = array[keep_idx, :][:, keep_idx] # slice matrix rows and cols
n = (self.nc + k - 1) // k # number of retained classes
nc = n if self.task == "classify" else n + 1 # adjust for background if needed
ticklabels = "auto"
if 0 < nc < 99:
ticklabels = names if self.task == "classify" else [*names, "background"]
xy_ticks = np.arange(len(ticklabels)) if ticklabels != "auto" else np.arange(nc)
tick_fontsize = max(6, 15 - 0.1 * nc) # Minimum size is 6
label_fontsize = max(6, 12 - 0.1 * nc)
title_fontsize = max(6, 12 - 0.1 * nc)
btm = max(0.1, 0.25 - 0.001 * nc) # Minimum value is 0.1
with warnings.catch_warnings():
warnings.simplefilter("ignore") # suppress empty matrix RuntimeWarning: All-NaN slice encountered
im = ax.imshow(array, cmap="Blues", vmin=0.0, interpolation="none")
ax.xaxis.set_label_position("bottom")
if nc < 30: # Add score for each cell of confusion matrix
color_threshold = 0.45 * (1 if normalize else np.nanmax(array)) # text color threshold
for i, row in enumerate(array[:nc]):
for j, val in enumerate(row[:nc]):
val = array[i, j]
if np.isnan(val):
continue
ax.text(
j,
i,
f"{val:.2f}" if normalize else f"{int(val)}",
ha="center",
va="center",
fontsize=10,
color="white" if val > color_threshold else "black",
)
cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.05)
title = "Confusion Matrix" + " Normalized" * normalize
ax.set_xlabel("True", fontsize=label_fontsize, labelpad=10)
ax.set_ylabel("Predicted", fontsize=label_fontsize, labelpad=10)
ax.set_title(title, fontsize=title_fontsize, pad=20)
ax.set_xticks(xy_ticks)
ax.set_yticks(xy_ticks)
ax.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False)
ax.tick_params(axis="y", left=True, right=False, labelleft=True, labelright=False)
if ticklabels != "auto":
ax.set_xticklabels(ticklabels, fontsize=tick_fontsize, rotation=90, ha="center")
ax.set_yticklabels(ticklabels, fontsize=tick_fontsize)
for s in {"left", "right", "bottom", "top", "outline"}:
if s != "outline":
ax.spines[s].set_visible(False) # Confusion matrix plot don't have outline
cbar.ax.spines[s].set_visible(False)
fig.subplots_adjust(left=0, right=0.84, top=0.94, bottom=btm) # Adjust layout to ensure equal margins
plot_fname = Path(save_dir) / f"{title.lower().replace(' ', '_')}.png"
fig.savefig(plot_fname, dpi=250)
plt.close(fig)
if on_plot:
on_plot(plot_fname, {"type": "confusion_matrix", "matrix": self.matrix.tolist()})
def print(self):
for i in range(self.matrix.shape[0]):
LOGGER.info(" ".join(map(str, self.matrix[i])))
def summary(self, normalize: bool = False, decimals: int = 5) -> list[dict[str, float]]:
import re
names = list(self.names.values()) if self.task == "classify" else [*list(self.names.values()), "background"]
clean_names, seen = [], set()
for name in names:
clean_name = re.sub(r"[^a-zA-Z0-9_]", "_", name)
original_clean = clean_name
counter = 1
while clean_name.lower() in seen:
clean_name = f"{original_clean}_{counter}"
counter += 1
seen.add(clean_name.lower())
clean_names.append(clean_name)
array = (self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1)).round(decimals)
return [
dict({"Predicted": clean_names[i]}, **{clean_names[j]: array[i, j] for j in range(len(clean_names))})
for i in range(len(clean_names))
]
def smooth(y: np.ndarray, f: float = 0.05) -> np.ndarray:
nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
p = np.ones(nf // 2) # ones padding
yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
return np.convolve(yp, np.ones(nf) / nf, mode="valid") # y-smoothed
@plt_settings()
def plot_pr_curve(
px: np.ndarray,
py: np.ndarray,
ap: np.ndarray,
save_dir: Path = Path("pr_curve.png"),
names: dict[int, str] = {},
on_plot=None,
):
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
py = np.stack(py, axis=1)
if 0 < len(names) < 21: # display per-class legend if < 21 classes
for i, y in enumerate(py.T):
ax.plot(px, y, linewidth=1, label=f"{names[i]} {ap[i, 0]:.3f}") # plot(recall, precision)
else:
ax.plot(px, py, linewidth=1, color="gray") # plot(recall, precision)
ax.plot(px, py.mean(1), linewidth=3, color="blue", label=f"all classes {ap[:, 0].mean():.3f} mAP@0.5")
ax.set_xlabel("Recall")
ax.set_ylabel("Precision")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
ax.set_title("Precision-Recall Curve")
fig.savefig(save_dir, dpi=250)
plt.close(fig)
if on_plot:
# Pass PR curve data for interactive plotting (class names stored at model level)
# Transpose py to match other curves: y[class][point] format
on_plot(save_dir, {"type": "pr_curve", "x": px.tolist(), "y": py.T.tolist(), "ap": ap.tolist()})
@plt_settings()
def plot_mc_curve(
px: np.ndarray,
py: np.ndarray,
save_dir: Path = Path("mc_curve.png"),
names: dict[int, str] = {},
xlabel: str = "Confidence",
ylabel: str = "Metric",
on_plot=None,
):
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
if 0 < len(names) < 21: # display per-class legend if < 21 classes
for i, y in enumerate(py):
ax.plot(px, y, linewidth=1, label=f"{names[i]}") # plot(confidence, metric)
else:
ax.plot(px, py.T, linewidth=1, color="gray") # plot(confidence, metric)
y = smooth(py.mean(0), 0.1)
ax.plot(px, y, linewidth=3, color="blue", label=f"all classes {y.max():.2f} at {px[y.argmax()]:.3f}")
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
ax.set_title(f"{ylabel}-Confidence Curve")
fig.savefig(save_dir, dpi=250)
plt.close(fig)
if on_plot:
# Pass metric-confidence curve data for interactive plotting (class names stored at model level)
on_plot(save_dir, {"type": f"{ylabel.lower()}_curve", "x": px.tolist(), "y": py.tolist()})
def compute_ap(recall: list[float], precision: list[float]) -> tuple[float, np.ndarray, np.ndarray]:
# Append sentinel values to beginning and end
mrec = np.concatenate(([0.0], recall, [1.0]))
mpre = np.concatenate(([1.0], precision, [0.0]))
# Compute the precision envelope
mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
# Integrate area under curve
method = "interp" # methods: 'continuous', 'interp'
if method == "interp":
x = np.linspace(0, 1, 101) # 101-point interp (COCO)
func = np.trapezoid if checks.check_version(np.__version__, ">=2.0") else np.trapz # np.trapz deprecated
ap = func(np.interp(x, mrec, mpre), x) # integrate
else: # 'continuous'
i = np.where(mrec[1:] != mrec[:-1])[0] # points where x-axis (recall) changes
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
return ap, mpre, mrec
def ap_per_class(
tp: np.ndarray,
conf: np.ndarray,
pred_cls: np.ndarray,
target_cls: np.ndarray,
plot: bool = False,
on_plot=None,
save_dir: Path = Path(),
names: dict[int, str] = {},
eps: float = 1e-16,
prefix: str = "",
) -> tuple:
# Sort by objectness
i = np.argsort(-conf)
tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
# Find unique classes
unique_classes, nt = np.unique(target_cls, return_counts=True)
nc = unique_classes.shape[0] # number of classes, number of detections
# Create Precision-Recall curve and compute AP for each class
x, prec_values = np.linspace(0, 1, 1000), []
# Average precision, precision and recall curves
ap, p_curve, r_curve = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
for ci, c in enumerate(unique_classes):
i = pred_cls == c
n_l = nt[ci] # number of labels
n_p = i.sum() # number of predictions
if n_p == 0 or n_l == 0:
continue
# Accumulate FPs and TPs
fpc = (1 - tp[i]).cumsum(0)
tpc = tp[i].cumsum(0)
# Recall
recall = tpc / (n_l + eps) # recall curve
r_curve[ci] = np.interp(-x, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
# Precision
precision = tpc / (tpc + fpc) # precision curve
p_curve[ci] = np.interp(-x, -conf[i], precision[:, 0], left=1) # p at pr_score
# AP from recall-precision curve
for j in range(tp.shape[1]):
ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
if j == 0:
prec_values.append(np.interp(x, mrec, mpre)) # precision at mAP@0.5
prec_values = np.array(prec_values) if prec_values else np.zeros((1, 1000)) # (nc, 1000)
# Compute F1 (harmonic mean of precision and recall)
f1_curve = 2 * p_curve * r_curve / (p_curve + r_curve + eps)
names = {i: names[k] for i, k in enumerate(unique_classes) if k in names} # dict: only classes that have data
if plot:
plot_pr_curve(x, prec_values, ap, save_dir / f"{prefix}PR_curve.png", names, on_plot=on_plot)
plot_mc_curve(x, f1_curve, save_dir / f"{prefix}F1_curve.png", names, ylabel="F1", on_plot=on_plot)
plot_mc_curve(x, p_curve, save_dir / f"{prefix}P_curve.png", names, ylabel="Precision", on_plot=on_plot)
plot_mc_curve(x, r_curve, save_dir / f"{prefix}R_curve.png", names, ylabel="Recall", on_plot=on_plot)
i = smooth(f1_curve.mean(0), 0.1).argmax() # max F1 index
p, r, f1 = p_curve[:, i], r_curve[:, i], f1_curve[:, i] # max-F1 precision, recall, F1 values
tp = (r * nt).round() # true positives
fp = (tp / (p + eps) - tp).round() # false positives
return tp, fp, p, r, f1, ap, unique_classes.astype(int), p_curve, r_curve, f1_curve, x, prec_values
class Metric(SimpleClass):
def __init__(self) -> None:
self.p = [] # (nc, )
self.r = [] # (nc, )
self.f1 = [] # (nc, )
self.all_ap = [] # (nc, 10)
self.ap_class_index = [] # (nc, )
self.nc = 0
@property
def ap50(self) -> np.ndarray | list:
return self.all_ap[:, 0] if len(self.all_ap) else []
@property
def ap(self) -> np.ndarray | list:
return self.all_ap.mean(1) if len(self.all_ap) else []
@property
def mp(self) -> float:
return self.p.mean() if len(self.p) else 0.0
@property
def mr(self) -> float:
return self.r.mean() if len(self.r) else 0.0
@property
def map50(self) -> float:
return self.all_ap[:, 0].mean() if len(self.all_ap) else 0.0
@property
def map75(self) -> float:
return self.all_ap[:, 5].mean() if len(self.all_ap) else 0.0
@property
def map(self) -> float:
return self.all_ap.mean() if len(self.all_ap) else 0.0
def mean_results(self) -> list[float]:
return [self.mp, self.mr, self.map50, self.map]
def class_result(self, i: int) -> tuple[float, float, float, float]:
return self.p[i], self.r[i], self.ap50[i], self.ap[i]
@property
def maps(self) -> np.ndarray:
maps = np.zeros(self.nc) + self.map
for i, c in enumerate(self.ap_class_index):
maps[c] = self.ap[i]
return maps
def fitness(self) -> float:
w = [0.0, 0.0, 0.0, 1.0] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
return float((np.nan_to_num(np.array(self.mean_results())) * w).sum())
def update(self, results: tuple):
(
self.p,
self.r,
self.f1,
self.all_ap,
self.ap_class_index,
self.p_curve,
self.r_curve,
self.f1_curve,
self.px,
self.prec_values,
) = results
@property
def curves(self) -> list:
return []
@property
def curves_results(self) -> list[list]:
return [
[self.px, self.prec_values, "Recall", "Precision"],
[self.px, self.f1_curve, "Confidence", "F1"],
[self.px, self.p_curve, "Confidence", "Precision"],
[self.px, self.r_curve, "Confidence", "Recall"],
]
class DetMetrics(SimpleClass, DataExportMixin):
def __init__(self, names: dict[int, str] = {}) -> None:
self.names = names
self.box = Metric()
self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
self.stats = dict(tp=[], conf=[], pred_cls=[], target_cls=[], target_img=[])
self.nt_per_class = None
self.nt_per_image = None
def update_stats(self, stat: dict[str, Any]) -> None:
for k in self.stats.keys():
self.stats[k].append(stat[k])
def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
stats = {k: np.concatenate(v, 0) for k, v in self.stats.items()} # to numpy
if not stats:
return stats
results = ap_per_class(
stats["tp"],
stats["conf"],
stats["pred_cls"],
stats["target_cls"],
plot=plot,
save_dir=save_dir,
names=self.names,
on_plot=on_plot,
prefix="Box",
)[2:]
self.box.nc = len(self.names)
self.box.update(results)
self.nt_per_class = np.bincount(stats["target_cls"].astype(int), minlength=len(self.names))
self.nt_per_image = np.bincount(stats["target_img"].astype(int), minlength=len(self.names))
return stats
def clear_stats(self):
for v in self.stats.values():
v.clear()
@property
def keys(self) -> list[str]:
return ["metrics/precision(B)", "metrics/recall(B)", "metrics/mAP50(B)", "metrics/mAP50-95(B)"]
def mean_results(self) -> list[float]:
return self.box.mean_results()
def class_result(self, i: int) -> tuple[float, float, float, float]:
return self.box.class_result(i)
@property
def maps(self) -> np.ndarray:
return self.box.maps
@property
def fitness(self) -> float:
return self.box.fitness()
@property
def ap_class_index(self) -> list:
return self.box.ap_class_index
@property
def results_dict(self) -> dict[str, float]:
keys = [*self.keys, "fitness"]
values = ((float(x) if hasattr(x, "item") else x) for x in ([*self.mean_results(), self.fitness]))
return dict(zip(keys, values))
@property
def curves(self) -> list[str]:
return ["Precision-Recall(B)", "F1-Confidence(B)", "Precision-Confidence(B)", "Recall-Confidence(B)"]
@property
def curves_results(self) -> list[list]:
return self.box.curves_results
def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
per_class = {
"Box-P": self.box.p,
"Box-R": self.box.r,
"Box-F1": self.box.f1,
}
return [
{
"Class": self.names[self.ap_class_index[i]],
"Images": self.nt_per_image[self.ap_class_index[i]],
"Instances": self.nt_per_class[self.ap_class_index[i]],
**{k: round(v[i], decimals) for k, v in per_class.items()},
"mAP50": round(self.class_result(i)[2], decimals),
"mAP50-95": round(self.class_result(i)[3], decimals),
}
for i in range(len(per_class["Box-P"]))
]
class SegmentMetrics(DetMetrics):
def __init__(self, names: dict[int, str] = {}) -> None:
DetMetrics.__init__(self, names)
self.seg = Metric()
self.stats["tp_m"] = [] # add additional stats for masks
def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
stats = DetMetrics.process(self, save_dir, plot, on_plot=on_plot) # process box stats
results_mask = ap_per_class(
stats["tp_m"],
stats["conf"],
stats["pred_cls"],
stats["target_cls"],
plot=plot,
on_plot=on_plot,
save_dir=save_dir,
names=self.names,
prefix="Mask",
)[2:]
self.seg.nc = len(self.names)
self.seg.update(results_mask)
return stats
@property
def keys(self) -> list[str]:
return [
*DetMetrics.keys.fget(self),
"metrics/precision(M)",
"metrics/recall(M)",
"metrics/mAP50(M)",
"metrics/mAP50-95(M)",
]
def mean_results(self) -> list[float]:
return DetMetrics.mean_results(self) + self.seg.mean_results()
def class_result(self, i: int) -> list[float]:
return DetMetrics.class_result(self, i) + self.seg.class_result(i)
@property
def maps(self) -> np.ndarray:
return DetMetrics.maps.fget(self) + self.seg.maps
@property
def fitness(self) -> float:
return self.seg.fitness() + DetMetrics.fitness.fget(self)
@property
def curves(self) -> list[str]:
return [
*DetMetrics.curves.fget(self),
"Precision-Recall(M)",
"F1-Confidence(M)",
"Precision-Confidence(M)",
"Recall-Confidence(M)",
]
@property
def curves_results(self) -> list[list]:
return DetMetrics.curves_results.fget(self) + self.seg.curves_results
def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
per_class = {
"Mask-P": self.seg.p,
"Mask-R": self.seg.r,
"Mask-F1": self.seg.f1,
}
summary = DetMetrics.summary(self, normalize, decimals) # get box summary
for i, s in enumerate(summary):
s.update({**{k: round(v[i], decimals) for k, v in per_class.items()}})
return summary
class PoseMetrics(DetMetrics):
def __init__(self, names: dict[int, str] = {}) -> None:
super().__init__(names)
self.pose = Metric()
self.stats["tp_p"] = [] # add additional stats for pose
def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
stats = DetMetrics.process(self, save_dir, plot, on_plot=on_plot) # process box stats
results_pose = ap_per_class(
stats["tp_p"],
stats["conf"],
stats["pred_cls"],
stats["target_cls"],
plot=plot,
on_plot=on_plot,
save_dir=save_dir,
names=self.names,
prefix="Pose",
)[2:]
self.pose.nc = len(self.names)
self.pose.update(results_pose)
return stats
@property
def keys(self) -> list[str]:
return [
*DetMetrics.keys.fget(self),
"metrics/precision(P)",
"metrics/recall(P)",
"metrics/mAP50(P)",
"metrics/mAP50-95(P)",
]
def mean_results(self) -> list[float]:
return DetMetrics.mean_results(self) + self.pose.mean_results()
def class_result(self, i: int) -> list[float]:
return DetMetrics.class_result(self, i) + self.pose.class_result(i)
@property
def maps(self) -> np.ndarray:
return DetMetrics.maps.fget(self) + self.pose.maps
@property
def fitness(self) -> float:
return self.pose.fitness() + DetMetrics.fitness.fget(self)
@property
def curves(self) -> list[str]:
return [
*DetMetrics.curves.fget(self),
"Precision-Recall(B)",
"F1-Confidence(B)",
"Precision-Confidence(B)",
"Recall-Confidence(B)",
"Precision-Recall(P)",
"F1-Confidence(P)",
"Precision-Confidence(P)",
"Recall-Confidence(P)",
]
@property
def curves_results(self) -> list[list]:
return DetMetrics.curves_results.fget(self) + self.pose.curves_results
def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
per_class = {
"Pose-P": self.pose.p,
"Pose-R": self.pose.r,
"Pose-F1": self.pose.f1,
}
summary = DetMetrics.summary(self, normalize, decimals) # get box summary
for i, s in enumerate(summary):
s.update({**{k: round(v[i], decimals) for k, v in per_class.items()}})
return summary
class ClassifyMetrics(SimpleClass, DataExportMixin):
def __init__(self) -> None:
self.top1 = 0
self.top5 = 0
self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
def process(self, targets: torch.Tensor, pred: torch.Tensor):
pred, targets = torch.cat(pred), torch.cat(targets)
correct = (targets[:, None] == pred).float()
acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
self.top1, self.top5 = acc.mean(0).tolist()
@property
def fitness(self) -> float:
return (self.top1 + self.top5) / 2
@property
def results_dict(self) -> dict[str, float]:
return dict(zip([*self.keys, "fitness"], [self.top1, self.top5, self.fitness]))
@property
def keys(self) -> list[str]:
return ["metrics/accuracy_top1", "metrics/accuracy_top5"]
@property
def curves(self) -> list:
return []
@property
def curves_results(self) -> list:
return []
def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, float]]:
return [{"top1_acc": round(self.top1, decimals), "top5_acc": round(self.top5, decimals)}]
class OBBMetrics(DetMetrics):
def __init__(self, names: dict[int, str] = {}) -> None:
DetMetrics.__init__(self, names) | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Model validation metrics."""
from __future__ import annotations
@@ -24,6 +25,17 @@
def bbox_ioa(box1: np.ndarray, box2: np.ndarray, iou: bool = False, eps: float = 1e-7) -> np.ndarray:
+ """Calculate the intersection over box2 area given box1 and box2.
+
+ Args:
+ box1 (np.ndarray): A numpy array of shape (N, 4) representing N bounding boxes in x1y1x2y2 format.
+ box2 (np.ndarray): A numpy array of shape (M, 4) representing M bounding boxes in x1y1x2y2 format.
+ iou (bool, optional): Calculate the standard IoU if True else return inter_area/box2_area.
+ eps (float, optional): A small value to avoid division by zero.
+
+ Returns:
+ (np.ndarray): A numpy array of shape (N, M) representing the intersection over box2 area.
+ """
# Get the coordinates of bounding boxes
b1_x1, b1_y1, b1_x2, b1_y2 = box1.T
b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
@@ -44,6 +56,19 @@
def box_iou(box1: torch.Tensor, box2: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:
+ """Calculate intersection-over-union (IoU) of boxes.
+
+ Args:
+ box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes in (x1, y1, x2, y2) format.
+ box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes in (x1, y1, x2, y2) format.
+ eps (float, optional): A small value to avoid division by zero.
+
+ Returns:
+ (torch.Tensor): An NxM tensor containing the pairwise IoU values for every element in box1 and box2.
+
+ References:
+ https://github.com/pytorch/vision/blob/main/torchvision/ops/boxes.py
+ """
# NOTE: Need .float() to get accurate iou values
# inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
(a1, a2), (b1, b2) = box1.float().unsqueeze(1).chunk(2, 2), box2.float().unsqueeze(0).chunk(2, 2)
@@ -62,6 +87,25 @@ CIoU: bool = False,
eps: float = 1e-7,
) -> torch.Tensor:
+ """Calculate the Intersection over Union (IoU) between bounding boxes.
+
+ This function supports various shapes for `box1` and `box2` as long as the last dimension is 4. For instance, you
+ may pass tensors shaped like (4,), (N, 4), (B, N, 4), or (B, N, 1, 4). Internally, the code will split the last
+ dimension into (x, y, w, h) if `xywh=True`, or (x1, y1, x2, y2) if `xywh=False`.
+
+ Args:
+ box1 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4.
+ box2 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4.
+ xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in (x1, y1,
+ x2, y2) format.
+ GIoU (bool, optional): If True, calculate Generalized IoU.
+ DIoU (bool, optional): If True, calculate Distance IoU.
+ CIoU (bool, optional): If True, calculate Complete IoU.
+ eps (float, optional): A small value to avoid division by zero.
+
+ Returns:
+ (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
+ """
# Get the coordinates of bounding boxes
if xywh: # transform from xywh to xyxy
(x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
@@ -104,6 +148,18 @@
def mask_iou(mask1: torch.Tensor, mask2: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:
+ """Calculate masks IoU.
+
+ Args:
+ mask1 (torch.Tensor): A tensor of shape (N, n) where N is the number of ground truth objects and n is the
+ product of image width and height.
+ mask2 (torch.Tensor): A tensor of shape (M, n) where M is the number of predicted objects and n is the product
+ of image width and height.
+ eps (float, optional): A small value to avoid division by zero.
+
+ Returns:
+ (torch.Tensor): A tensor of shape (N, M) representing masks IoU.
+ """
intersection = torch.matmul(mask1, mask2.T).clamp_(0)
union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection
return intersection / (union + eps)
@@ -112,6 +168,18 @@ def kpt_iou(
kpt1: torch.Tensor, kpt2: torch.Tensor, area: torch.Tensor, sigma: list[float], eps: float = 1e-7
) -> torch.Tensor:
+ """Calculate Object Keypoint Similarity (OKS).
+
+ Args:
+ kpt1 (torch.Tensor): A tensor of shape (N, 17, 3) representing ground truth keypoints.
+ kpt2 (torch.Tensor): A tensor of shape (M, 17, 3) representing predicted keypoints.
+ area (torch.Tensor): A tensor of shape (N,) representing areas from ground truth.
+ sigma (list[float]): A list containing 17 values representing keypoint scales.
+ eps (float, optional): A small value to avoid division by zero.
+
+ Returns:
+ (torch.Tensor): A tensor of shape (N, M) representing keypoint similarities.
+ """
d = (kpt1[:, None, :, 0] - kpt2[..., 0]).pow(2) + (kpt1[:, None, :, 1] - kpt2[..., 1]).pow(2) # (N, M, 17)
sigma = torch.tensor(sigma, device=kpt1.device, dtype=kpt1.dtype) # (17, )
kpt_mask = kpt1[..., 2] != 0 # (N, 17)
@@ -121,6 +189,15 @@
def _get_covariance_matrix(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Generate covariance matrix from oriented bounding boxes.
+
+ Args:
+ boxes (torch.Tensor): A tensor of shape (N, 5) representing rotated bounding boxes, with xywhr format.
+
+ Returns:
+ (tuple[torch.Tensor, torch.Tensor, torch.Tensor]): Covariance matrix components (a, b, c) where the covariance
+ matrix is [[a, c], [c, b]], each of shape (N, 1).
+ """
# Gaussian bounding boxes, ignore the center points (the first two columns) because they are not needed here.
gbbs = torch.cat((boxes[:, 2:4].pow(2) / 12, boxes[:, 4:]), dim=-1)
a, b, c = gbbs.split(1, dim=-1)
@@ -132,6 +209,23 @@
def probiou(obb1: torch.Tensor, obb2: torch.Tensor, CIoU: bool = False, eps: float = 1e-7) -> torch.Tensor:
+ """Calculate probabilistic IoU between oriented bounding boxes.
+
+ Args:
+ obb1 (torch.Tensor): Ground truth OBBs, shape (N, 5), format xywhr.
+ obb2 (torch.Tensor): Predicted OBBs, shape (N, 5), format xywhr.
+ CIoU (bool, optional): If True, calculate CIoU.
+ eps (float, optional): Small value to avoid division by zero.
+
+ Returns:
+ (torch.Tensor): OBB similarities, shape (N,).
+
+ Notes:
+ OBB format: [center_x, center_y, width, height, rotation_angle].
+
+ References:
+ https://arxiv.org/pdf/2106.06072v1.pdf
+ """
x1, y1 = obb1[..., :2].split(1, dim=-1)
x2, y2 = obb2[..., :2].split(1, dim=-1)
a1, b1, c1 = _get_covariance_matrix(obb1)
@@ -160,6 +254,19 @@
def batch_probiou(obb1: torch.Tensor | np.ndarray, obb2: torch.Tensor | np.ndarray, eps: float = 1e-7) -> torch.Tensor:
+ """Calculate the probabilistic IoU between oriented bounding boxes.
+
+ Args:
+ obb1 (torch.Tensor | np.ndarray): A tensor of shape (N, 5) representing ground truth obbs, with xywhr format.
+ obb2 (torch.Tensor | np.ndarray): A tensor of shape (M, 5) representing predicted obbs, with xywhr format.
+ eps (float, optional): A small value to avoid division by zero.
+
+ Returns:
+ (torch.Tensor): A tensor of shape (N, M) representing obb similarities.
+
+ References:
+ https://arxiv.org/pdf/2106.06072v1.pdf
+ """
obb1 = torch.from_numpy(obb1) if isinstance(obb1, np.ndarray) else obb1
obb2 = torch.from_numpy(obb2) if isinstance(obb2, np.ndarray) else obb2
@@ -183,12 +290,40 @@
def smooth_bce(eps: float = 0.1) -> tuple[float, float]:
+ """Compute smoothed positive and negative Binary Cross-Entropy targets.
+
+ Args:
+ eps (float, optional): The epsilon value for label smoothing.
+
+ Returns:
+ pos (float): Positive label smoothing BCE target.
+ neg (float): Negative label smoothing BCE target.
+
+ References:
+ https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
+ """
return 1.0 - 0.5 * eps, 0.5 * eps
class ConfusionMatrix(DataExportMixin):
+ """A class for calculating and updating a confusion matrix for object detection and classification tasks.
+
+ Attributes:
+ task (str): The type of task, either 'detect' or 'classify'.
+ matrix (np.ndarray): The confusion matrix, with dimensions depending on the task.
+ nc (int): The number of classes.
+ names (dict[int, str]): The names of the classes, used as labels on the plot.
+ matches (dict | None): Contains the indices of ground truths and predictions categorized into TP, FP and FN.
+ """
def __init__(self, names: dict[int, str] = {}, task: str = "detect", save_matches: bool = False):
+ """Initialize a ConfusionMatrix instance.
+
+ Args:
+ names (dict[int, str], optional): Names of classes, used as labels on the plot.
+ task (str, optional): Type of task, either 'detect' or 'classify'.
+ save_matches (bool, optional): Save the indices of GTs, TPs, FPs, FNs for visualization.
+ """
self.task = task
self.nc = len(names) # number of classes
self.matrix = np.zeros((self.nc, self.nc)) if self.task == "classify" else np.zeros((self.nc + 1, self.nc + 1))
@@ -196,6 +331,21 @@ self.matches = {} if save_matches else None
def _append_matches(self, mtype: str, batch: dict[str, Any], idx: int) -> None:
+ """Append the matches to TP, FP, FN or GT list for the last batch.
+
+ This method updates the matches dictionary by appending specific batch data to the appropriate match type (True
+ Positive, False Positive, or False Negative).
+
+ Args:
+ mtype (str): Match type identifier ('TP', 'FP', 'FN' or 'GT').
+ batch (dict[str, Any]): Batch data containing detection results with keys like 'bboxes', 'cls', 'conf',
+ 'keypoints', 'masks'.
+ idx (int): Index of the specific detection to append from the batch.
+
+ Notes:
+ For masks, handles both overlap and non-overlap cases. When masks.max() > 1.0, it indicates
+ overlap_mask=True with shape (1, H, W), otherwise uses direct indexing.
+ """
if self.matches is None:
return
for k, v in batch.items():
@@ -206,6 +356,12 @@ self.matches[mtype][k] += [v[0] == idx + 1] if v.max() > 1.0 else [v[idx]]
def process_cls_preds(self, preds: list[torch.Tensor], targets: list[torch.Tensor]) -> None:
+ """Update confusion matrix for classification task.
+
+ Args:
+ preds (list[torch.Tensor]): Predicted class labels.
+ targets (list[torch.Tensor]): Ground truth class labels.
+ """
preds, targets = torch.cat(preds)[:, 0], torch.cat(targets)
for p, t in zip(preds.cpu().numpy(), targets.cpu().numpy()):
self.matrix[p][t] += 1
@@ -217,6 +373,17 @@ conf: float = 0.25,
iou_thres: float = 0.45,
) -> None:
+ """Update confusion matrix for object detection task.
+
+ Args:
+ detections (dict[str, torch.Tensor]): Dictionary containing detected bounding boxes and their associated
+ information. Should contain 'cls', 'conf', and 'bboxes' keys, where 'bboxes' can be Array[N, 4] for
+ regular boxes or Array[N, 5] for OBB with angle.
+ batch (dict[str, Any]): Batch dictionary containing ground truth data with 'bboxes' (Array[M, 4]| Array[M,
+ 5]) and 'cls' (Array[M]) keys, where M is the number of ground truth objects.
+ conf (float, optional): Confidence threshold for detections.
+ iou_thres (float, optional): IoU threshold for matching detections to ground truth.
+ """
gt_cls, gt_bboxes = batch["cls"], batch["bboxes"]
if self.matches is not None: # only if visualization is enabled
self.matches = {k: defaultdict(list) for k in {"TP", "FP", "FN", "GT"}}
@@ -279,15 +446,29 @@ self._append_matches("FP", detections, i)
def matrix(self):
+ """Return the confusion matrix."""
return self.matrix
def tp_fp(self) -> tuple[np.ndarray, np.ndarray]:
+ """Return true positives and false positives.
+
+ Returns:
+ tp (np.ndarray): True positives.
+ fp (np.ndarray): False positives.
+ """
tp = self.matrix.diagonal() # true positives
fp = self.matrix.sum(1) - tp # false positives
# fn = self.matrix.sum(0) - tp # false negatives (missed detections)
return (tp, fp) if self.task == "classify" else (tp[:-1], fp[:-1]) # remove background class if task=detect
def plot_matches(self, img: torch.Tensor, im_file: str, save_dir: Path) -> None:
+ """Plot grid of GT, TP, FP, FN for each image.
+
+ Args:
+ img (torch.Tensor): Image to plot onto.
+ im_file (str): Image filename to save visualizations.
+ save_dir (Path): Location to save the visualizations to.
+ """
if not self.matches:
return
from .ops import xyxy2xywh
@@ -320,6 +501,13 @@ @TryExcept(msg="ConfusionMatrix plot failure")
@plt_settings()
def plot(self, normalize: bool = True, save_dir: str = "", on_plot=None):
+ """Plot the confusion matrix using matplotlib and save it to a file.
+
+ Args:
+ normalize (bool, optional): Whether to normalize the confusion matrix.
+ save_dir (str, optional): Directory where the plot will be saved.
+ on_plot (callable, optional): An optional callback to pass plots path and data when they are rendered.
+ """
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1) # normalize columns
@@ -386,10 +574,28 @@ on_plot(plot_fname, {"type": "confusion_matrix", "matrix": self.matrix.tolist()})
def print(self):
+ """Print the confusion matrix to the console."""
for i in range(self.matrix.shape[0]):
LOGGER.info(" ".join(map(str, self.matrix[i])))
def summary(self, normalize: bool = False, decimals: int = 5) -> list[dict[str, float]]:
+ """Generate a summarized representation of the confusion matrix as a list of dictionaries, with optional
+ normalization. This is useful for exporting the matrix to various formats such as CSV, XML, HTML, JSON,
+ or SQL.
+
+ Args:
+ normalize (bool): Whether to normalize the confusion matrix values.
+ decimals (int): Number of decimal places to round the output values to.
+
+ Returns:
+ (list[dict[str, float]]): A list of dictionaries, each representing one predicted class with corresponding
+ values for all actual classes.
+
+ Examples:
+ >>> results = model.val(data="coco8.yaml", plots=True)
+ >>> cm_dict = results.confusion_matrix.summary(normalize=True, decimals=5)
+ >>> print(cm_dict)
+ """
import re
names = list(self.names.values()) if self.task == "classify" else [*list(self.names.values()), "background"]
@@ -411,6 +617,7 @@
def smooth(y: np.ndarray, f: float = 0.05) -> np.ndarray:
+ """Box filter of fraction f."""
nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
p = np.ones(nf // 2) # ones padding
yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
@@ -426,6 +633,16 @@ names: dict[int, str] = {},
on_plot=None,
):
+ """Plot precision-recall curve.
+
+ Args:
+ px (np.ndarray): X values for the PR curve.
+ py (np.ndarray): Y values for the PR curve.
+ ap (np.ndarray): Average precision values.
+ save_dir (Path, optional): Path to save the plot.
+ names (dict[int, str], optional): Dictionary mapping class indices to class names.
+ on_plot (callable, optional): Function to call after plot is saved.
+ """
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
@@ -462,6 +679,17 @@ ylabel: str = "Metric",
on_plot=None,
):
+ """Plot metric-confidence curve.
+
+ Args:
+ px (np.ndarray): X values for the metric-confidence curve.
+ py (np.ndarray): Y values for the metric-confidence curve.
+ save_dir (Path, optional): Path to save the plot.
+ names (dict[int, str], optional): Dictionary mapping class indices to class names.
+ xlabel (str, optional): X-axis label.
+ ylabel (str, optional): Y-axis label.
+ on_plot (callable, optional): Function to call after plot is saved.
+ """
import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
@@ -488,6 +716,17 @@
def compute_ap(recall: list[float], precision: list[float]) -> tuple[float, np.ndarray, np.ndarray]:
+ """Compute the average precision (AP) given the recall and precision curves.
+
+ Args:
+ recall (list[float]): The recall curve.
+ precision (list[float]): The precision curve.
+
+ Returns:
+ ap (float): Average precision.
+ mpre (np.ndarray): Precision envelope curve.
+ mrec (np.ndarray): Modified recall curve with sentinel values added at the beginning and end.
+ """
# Append sentinel values to beginning and end
mrec = np.concatenate(([0.0], recall, [1.0]))
mpre = np.concatenate(([1.0], precision, [0.0]))
@@ -520,6 +759,34 @@ eps: float = 1e-16,
prefix: str = "",
) -> tuple:
+ """Compute the average precision per class for object detection evaluation.
+
+ Args:
+ tp (np.ndarray): Binary array indicating whether the detection is correct (True) or not (False).
+ conf (np.ndarray): Array of confidence scores of the detections.
+ pred_cls (np.ndarray): Array of predicted classes of the detections.
+ target_cls (np.ndarray): Array of true classes of the targets.
+ plot (bool, optional): Whether to plot PR curves or not.
+ on_plot (callable, optional): A callback to pass plots path and data when they are rendered.
+ save_dir (Path, optional): Directory to save the PR curves.
+ names (dict[int, str], optional): Dictionary of class names to plot PR curves.
+ eps (float, optional): A small value to avoid division by zero.
+ prefix (str, optional): A prefix string for saving the plot files.
+
+ Returns:
+ tp (np.ndarray): True positive counts at threshold given by max F1 metric for each class.
+ fp (np.ndarray): False positive counts at threshold given by max F1 metric for each class.
+ p (np.ndarray): Precision values at threshold given by max F1 metric for each class.
+ r (np.ndarray): Recall values at threshold given by max F1 metric for each class.
+ f1 (np.ndarray): F1-score values at threshold given by max F1 metric for each class.
+ ap (np.ndarray): Average precision for each class at different IoU thresholds.
+ unique_classes (np.ndarray): An array of unique classes that have data.
+ p_curve (np.ndarray): Precision curves for each class.
+ r_curve (np.ndarray): Recall curves for each class.
+ f1_curve (np.ndarray): F1-score curves for each class.
+ x (np.ndarray): X-axis values for the curves.
+ prec_values (np.ndarray): Precision values at mAP@0.5 for each class.
+ """
# Sort by objectness
i = np.argsort(-conf)
tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
@@ -577,8 +844,35 @@
class Metric(SimpleClass):
+ """Class for computing evaluation metrics for Ultralytics YOLO models.
+
+ Attributes:
+ p (list): Precision for each class. Shape: (nc,).
+ r (list): Recall for each class. Shape: (nc,).
+ f1 (list): F1 score for each class. Shape: (nc,).
+ all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).
+ ap_class_index (list): Index of class for each AP score. Shape: (nc,).
+ nc (int): Number of classes.
+
+ Methods:
+ ap50: AP at IoU threshold of 0.5 for all classes.
+ ap: AP at IoU thresholds from 0.5 to 0.95 for all classes.
+ mp: Mean precision of all classes.
+ mr: Mean recall of all classes.
+ map50: Mean AP at IoU threshold of 0.5 for all classes.
+ map75: Mean AP at IoU threshold of 0.75 for all classes.
+ map: Mean AP at IoU thresholds from 0.5 to 0.95 for all classes.
+ mean_results: Mean of results, returns mp, mr, map50, map.
+ class_result: Class-aware result, returns p[i], r[i], ap50[i], ap[i].
+ maps: mAP of each class.
+ fitness: Model fitness as a weighted combination of metrics.
+ update: Update metric attributes with new evaluation results.
+ curves: Provides a list of curves for accessing specific metrics like precision, recall, F1, etc.
+ curves_results: Provide a list of results for accessing specific metrics like precision, recall, F1, etc.
+ """
def __init__(self) -> None:
+ """Initialize a Metric instance for computing evaluation metrics for the YOLO model."""
self.p = [] # (nc, )
self.r = [] # (nc, )
self.f1 = [] # (nc, )
@@ -588,50 +882,104 @@
@property
def ap50(self) -> np.ndarray | list:
+ """Return the Average Precision (AP) at an IoU threshold of 0.5 for all classes.
+
+ Returns:
+ (np.ndarray | list): Array of shape (nc,) with AP50 values per class, or an empty list if not available.
+ """
return self.all_ap[:, 0] if len(self.all_ap) else []
@property
def ap(self) -> np.ndarray | list:
+ """Return the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes.
+
+ Returns:
+ (np.ndarray | list): Array of shape (nc,) with AP50-95 values per class, or an empty list if not available.
+ """
return self.all_ap.mean(1) if len(self.all_ap) else []
@property
def mp(self) -> float:
+ """Return the Mean Precision of all classes.
+
+ Returns:
+ (float): The mean precision of all classes.
+ """
return self.p.mean() if len(self.p) else 0.0
@property
def mr(self) -> float:
+ """Return the Mean Recall of all classes.
+
+ Returns:
+ (float): The mean recall of all classes.
+ """
return self.r.mean() if len(self.r) else 0.0
@property
def map50(self) -> float:
+ """Return the mean Average Precision (mAP) at an IoU threshold of 0.5.
+
+ Returns:
+ (float): The mAP at an IoU threshold of 0.5.
+ """
return self.all_ap[:, 0].mean() if len(self.all_ap) else 0.0
@property
def map75(self) -> float:
+ """Return the mean Average Precision (mAP) at an IoU threshold of 0.75.
+
+ Returns:
+ (float): The mAP at an IoU threshold of 0.75.
+ """
return self.all_ap[:, 5].mean() if len(self.all_ap) else 0.0
@property
def map(self) -> float:
+ """Return the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
+
+ Returns:
+ (float): The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
+ """
return self.all_ap.mean() if len(self.all_ap) else 0.0
def mean_results(self) -> list[float]:
+ """Return mean of results, mp, mr, map50, map."""
return [self.mp, self.mr, self.map50, self.map]
def class_result(self, i: int) -> tuple[float, float, float, float]:
+ """Return class-aware result, p[i], r[i], ap50[i], ap[i]."""
return self.p[i], self.r[i], self.ap50[i], self.ap[i]
@property
def maps(self) -> np.ndarray:
+ """Return mAP of each class."""
maps = np.zeros(self.nc) + self.map
for i, c in enumerate(self.ap_class_index):
maps[c] = self.ap[i]
return maps
def fitness(self) -> float:
+ """Return model fitness as a weighted combination of metrics."""
w = [0.0, 0.0, 0.0, 1.0] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
return float((np.nan_to_num(np.array(self.mean_results())) * w).sum())
def update(self, results: tuple):
+ """Update the evaluation metrics with a new set of results.
+
+ Args:
+ results (tuple): A tuple containing evaluation metrics:
+ - p (list): Precision for each class.
+ - r (list): Recall for each class.
+ - f1 (list): F1 score for each class.
+ - all_ap (list): AP scores for all classes and all IoU thresholds.
+ - ap_class_index (list): Index of class for each AP score.
+ - p_curve (list): Precision curve for each class.
+ - r_curve (list): Recall curve for each class.
+ - f1_curve (list): F1 curve for each class.
+ - px (list): X values for the curves.
+ - prec_values (list): Precision values for each class.
+ """
(
self.p,
self.r,
@@ -647,10 +995,12 @@
@property
def curves(self) -> list:
+ """Return a list of curves for accessing specific metrics curves."""
return []
@property
def curves_results(self) -> list[list]:
+ """Return a list of curves results for accessing specific metrics curves."""
return [
[self.px, self.prec_values, "Recall", "Precision"],
[self.px, self.f1_curve, "Confidence", "F1"],
@@ -660,8 +1010,39 @@
class DetMetrics(SimpleClass, DataExportMixin):
+ """Utility class for computing detection metrics such as precision, recall, and mean average precision (mAP).
+
+ Attributes:
+ names (dict[int, str]): A dictionary of class names.
+ box (Metric): An instance of the Metric class for storing detection results.
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
+ target classes, and target images.
+ nt_per_class: Number of targets per class.
+ nt_per_image: Number of targets per image.
+
+ Methods:
+ update_stats: Update statistics by appending new values to existing stat collections.
+ process: Process predicted results for object detection and update metrics.
+ clear_stats: Clear the stored statistics.
+ keys: Return a list of keys for accessing specific metrics.
+ mean_results: Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.
+ class_result: Return the result of evaluating the performance of an object detection model on a specific class.
+ maps: Return mean Average Precision (mAP) scores per class.
+ fitness: Return the fitness of box object.
+ ap_class_index: Return the average precision index per class.
+ results_dict: Return dictionary of computed performance metrics and statistics.
+ curves: Return a list of curves for accessing specific metrics curves.
+ curves_results: Return a list of computed performance metrics and statistics.
+ summary: Generate a summarized representation of per-class detection metrics as a list of dictionaries.
+ """
def __init__(self, names: dict[int, str] = {}) -> None:
+ """Initialize a DetMetrics instance with class names.
+
+ Args:
+ names (dict[int, str], optional): Dictionary of class names.
+ """
self.names = names
self.box = Metric()
self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
@@ -670,10 +1051,26 @@ self.nt_per_image = None
def update_stats(self, stat: dict[str, Any]) -> None:
+ """Update statistics by appending new values to existing stat collections.
+
+ Args:
+ stat (dict[str, Any]): Dictionary containing new statistical values to append. Keys should match existing
+ keys in self.stats.
+ """
for k in self.stats.keys():
self.stats[k].append(stat[k])
def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
+ """Process predicted results for object detection and update metrics.
+
+ Args:
+ save_dir (Path): Directory to save plots. Defaults to Path(".").
+ plot (bool): Whether to plot precision-recall curves. Defaults to False.
+ on_plot (callable, optional): Function to call after plots are generated. Defaults to None.
+
+ Returns:
+ (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
+ """
stats = {k: np.concatenate(v, 0) for k, v in self.stats.items()} # to numpy
if not stats:
return stats
@@ -695,46 +1092,72 @@ return stats
def clear_stats(self):
+ """Clear the stored statistics."""
for v in self.stats.values():
v.clear()
@property
def keys(self) -> list[str]:
+ """Return a list of keys for accessing specific metrics."""
return ["metrics/precision(B)", "metrics/recall(B)", "metrics/mAP50(B)", "metrics/mAP50-95(B)"]
def mean_results(self) -> list[float]:
+ """Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95."""
return self.box.mean_results()
def class_result(self, i: int) -> tuple[float, float, float, float]:
+ """Return the result of evaluating the performance of an object detection model on a specific class."""
return self.box.class_result(i)
@property
def maps(self) -> np.ndarray:
+ """Return mean Average Precision (mAP) scores per class."""
return self.box.maps
@property
def fitness(self) -> float:
+ """Return the fitness of box object."""
return self.box.fitness()
@property
def ap_class_index(self) -> list:
+ """Return the average precision index per class."""
return self.box.ap_class_index
@property
def results_dict(self) -> dict[str, float]:
+ """Return dictionary of computed performance metrics and statistics."""
keys = [*self.keys, "fitness"]
values = ((float(x) if hasattr(x, "item") else x) for x in ([*self.mean_results(), self.fitness]))
return dict(zip(keys, values))
@property
def curves(self) -> list[str]:
+ """Return a list of curves for accessing specific metrics curves."""
return ["Precision-Recall(B)", "F1-Confidence(B)", "Precision-Confidence(B)", "Recall-Confidence(B)"]
@property
def curves_results(self) -> list[list]:
+ """Return a list of computed performance metrics and statistics."""
return self.box.curves_results
def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
+ """Generate a summarized representation of per-class detection metrics as a list of dictionaries. Includes
+ shared scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class.
+
+ Args:
+ normalize (bool): For Detect metrics, everything is normalized by default [0-1].
+ decimals (int): Number of decimal places to round the metrics values to.
+
+ Returns:
+ (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
+ values.
+
+ Examples:
+ >>> results = model.val(data="coco8.yaml")
+ >>> detection_summary = results.summary()
+ >>> print(detection_summary)
+ """
per_class = {
"Box-P": self.box.p,
"Box-R": self.box.r,
@@ -754,13 +1177,51 @@
class SegmentMetrics(DetMetrics):
+ """Calculate and aggregate detection and segmentation metrics over a given set of classes.
+
+ Attributes:
+ names (dict[int, str]): Dictionary of class names.
+ box (Metric): An instance of the Metric class for storing detection results.
+ seg (Metric): An instance of the Metric class to calculate mask segmentation metrics.
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
+ target classes, and target images.
+ nt_per_class: Number of targets per class.
+ nt_per_image: Number of targets per image.
+
+ Methods:
+ process: Process the detection and segmentation metrics over the given set of predictions.
+ keys: Return a list of keys for accessing metrics.
+ mean_results: Return the mean metrics for bounding box and segmentation results.
+ class_result: Return classification results for a specified class index.
+ maps: Return mAP scores for object detection and segmentation models.
+ fitness: Return the fitness score for both segmentation and bounding box models.
+ curves: Return a list of curves for accessing specific metrics curves.
+ curves_results: Provide a list of computed performance metrics and statistics.
+ summary: Generate a summarized representation of per-class segmentation metrics as a list of dictionaries.
+ """
def __init__(self, names: dict[int, str] = {}) -> None:
+ """Initialize a SegmentMetrics instance with class names.
+
+ Args:
+ names (dict[int, str], optional): Dictionary of class names.
+ """
DetMetrics.__init__(self, names)
self.seg = Metric()
self.stats["tp_m"] = [] # add additional stats for masks
def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
+ """Process the detection and segmentation metrics over the given set of predictions.
+
+ Args:
+ save_dir (Path): Directory to save plots. Defaults to Path(".").
+ plot (bool): Whether to plot precision-recall curves. Defaults to False.
+ on_plot (callable, optional): Function to call after plots are generated. Defaults to None.
+
+ Returns:
+ (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
+ """
stats = DetMetrics.process(self, save_dir, plot, on_plot=on_plot) # process box stats
results_mask = ap_per_class(
stats["tp_m"],
@@ -779,6 +1240,7 @@
@property
def keys(self) -> list[str]:
+ """Return a list of keys for accessing metrics."""
return [
*DetMetrics.keys.fget(self),
"metrics/precision(M)",
@@ -788,21 +1250,26 @@ ]
def mean_results(self) -> list[float]:
+ """Return the mean metrics for bounding box and segmentation results."""
return DetMetrics.mean_results(self) + self.seg.mean_results()
def class_result(self, i: int) -> list[float]:
+ """Return classification results for a specified class index."""
return DetMetrics.class_result(self, i) + self.seg.class_result(i)
@property
def maps(self) -> np.ndarray:
+ """Return mAP scores for object detection and segmentation models."""
return DetMetrics.maps.fget(self) + self.seg.maps
@property
def fitness(self) -> float:
+ """Return the fitness score for both segmentation and bounding box models."""
return self.seg.fitness() + DetMetrics.fitness.fget(self)
@property
def curves(self) -> list[str]:
+ """Return a list of curves for accessing specific metrics curves."""
return [
*DetMetrics.curves.fget(self),
"Precision-Recall(M)",
@@ -813,9 +1280,27 @@
@property
def curves_results(self) -> list[list]:
+ """Return a list of computed performance metrics and statistics."""
return DetMetrics.curves_results.fget(self) + self.seg.curves_results
def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
+ """Generate a summarized representation of per-class segmentation metrics as a list of dictionaries. Includes
+ both box and mask scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for
+ each class.
+
+ Args:
+ normalize (bool): For Segment metrics, everything is normalized by default [0-1].
+ decimals (int): Number of decimal places to round the metrics values to.
+
+ Returns:
+ (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
+ values.
+
+ Examples:
+ >>> results = model.val(data="coco8-seg.yaml")
+ >>> seg_summary = results.summary(decimals=4)
+ >>> print(seg_summary)
+ """
per_class = {
"Mask-P": self.seg.p,
"Mask-R": self.seg.r,
@@ -828,13 +1313,51 @@
class PoseMetrics(DetMetrics):
+ """Calculate and aggregate detection and pose metrics over a given set of classes.
+
+ Attributes:
+ names (dict[int, str]): Dictionary of class names.
+ pose (Metric): An instance of the Metric class to calculate pose metrics.
+ box (Metric): An instance of the Metric class for storing detection results.
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
+ target classes, and target images.
+ nt_per_class: Number of targets per class.
+ nt_per_image: Number of targets per image.
+
+ Methods:
+ process: Process the detection and pose metrics over the given set of predictions.
+ keys: Return a list of keys for accessing metrics.
+ mean_results: Return the mean results of box and pose.
+ class_result: Return the class-wise detection results for a specific class i.
+ maps: Return the mean average precision (mAP) per class for both box and pose detections.
+ fitness: Return combined fitness score for pose and box detection.
+ curves: Return a list of curves for accessing specific metrics curves.
+ curves_results: Provide a list of computed performance metrics and statistics.
+ summary: Generate a summarized representation of per-class pose metrics as a list of dictionaries.
+ """
def __init__(self, names: dict[int, str] = {}) -> None:
+ """Initialize the PoseMetrics class with class names.
+
+ Args:
+ names (dict[int, str], optional): Dictionary of class names.
+ """
super().__init__(names)
self.pose = Metric()
self.stats["tp_p"] = [] # add additional stats for pose
def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
+ """Process the detection and pose metrics over the given set of predictions.
+
+ Args:
+ save_dir (Path): Directory to save plots. Defaults to Path(".").
+ plot (bool): Whether to plot precision-recall curves. Defaults to False.
+ on_plot (callable, optional): Function to call after plots are generated.
+
+ Returns:
+ (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
+ """
stats = DetMetrics.process(self, save_dir, plot, on_plot=on_plot) # process box stats
results_pose = ap_per_class(
stats["tp_p"],
@@ -853,6 +1376,7 @@
@property
def keys(self) -> list[str]:
+ """Return a list of evaluation metric keys."""
return [
*DetMetrics.keys.fget(self),
"metrics/precision(P)",
@@ -862,21 +1386,26 @@ ]
def mean_results(self) -> list[float]:
+ """Return the mean results of box and pose."""
return DetMetrics.mean_results(self) + self.pose.mean_results()
def class_result(self, i: int) -> list[float]:
+ """Return the class-wise detection results for a specific class i."""
return DetMetrics.class_result(self, i) + self.pose.class_result(i)
@property
def maps(self) -> np.ndarray:
+ """Return the mean average precision (mAP) per class for both box and pose detections."""
return DetMetrics.maps.fget(self) + self.pose.maps
@property
def fitness(self) -> float:
+ """Return combined fitness score for pose and box detection."""
return self.pose.fitness() + DetMetrics.fitness.fget(self)
@property
def curves(self) -> list[str]:
+ """Return a list of curves for accessing specific metrics curves."""
return [
*DetMetrics.curves.fget(self),
"Precision-Recall(B)",
@@ -891,9 +1420,26 @@
@property
def curves_results(self) -> list[list]:
+ """Return a list of computed performance metrics and statistics."""
return DetMetrics.curves_results.fget(self) + self.pose.curves_results
def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
+ """Generate a summarized representation of per-class pose metrics as a list of dictionaries. Includes both box
+ and pose scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class.
+
+ Args:
+ normalize (bool): For Pose metrics, everything is normalized by default [0-1].
+ decimals (int): Number of decimal places to round the metrics values to.
+
+ Returns:
+ (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
+ values.
+
+ Examples:
+ >>> results = model.val(data="coco8-pose.yaml")
+ >>> pose_summary = results.summary(decimals=4)
+ >>> print(pose_summary)
+ """
per_class = {
"Pose-P": self.pose.p,
"Pose-R": self.pose.r,
@@ -906,13 +1452,36 @@
class ClassifyMetrics(SimpleClass, DataExportMixin):
+ """Class for computing classification metrics including top-1 and top-5 accuracy.
+
+ Attributes:
+ top1 (float): The top-1 accuracy.
+ top5 (float): The top-5 accuracy.
+ speed (dict[str, float]): A dictionary containing the time taken for each step in the pipeline.
+
+ Methods:
+ process: Process target classes and predicted classes to compute metrics.
+ fitness: Return mean of top-1 and top-5 accuracies as fitness score.
+ results_dict: Return a dictionary with model's performance metrics and fitness score.
+ keys: Return a list of keys for the results_dict property.
+ curves: Return a list of curves for accessing specific metrics curves.
+ curves_results: Provide a list of computed performance metrics and statistics.
+ summary: Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy).
+ """
def __init__(self) -> None:
+ """Initialize a ClassifyMetrics instance."""
self.top1 = 0
self.top5 = 0
self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
def process(self, targets: torch.Tensor, pred: torch.Tensor):
+ """Process target classes and predicted classes to compute metrics.
+
+ Args:
+ targets (torch.Tensor): Target classes.
+ pred (torch.Tensor): Predicted classes.
+ """
pred, targets = torch.cat(pred), torch.cat(targets)
correct = (targets[:, None] == pred).float()
acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
@@ -920,29 +1489,67 @@
@property
def fitness(self) -> float:
+ """Return mean of top-1 and top-5 accuracies as fitness score."""
return (self.top1 + self.top5) / 2
@property
def results_dict(self) -> dict[str, float]:
+ """Return a dictionary with model's performance metrics and fitness score."""
return dict(zip([*self.keys, "fitness"], [self.top1, self.top5, self.fitness]))
@property
def keys(self) -> list[str]:
+ """Return a list of keys for the results_dict property."""
return ["metrics/accuracy_top1", "metrics/accuracy_top5"]
@property
def curves(self) -> list:
+ """Return a list of curves for accessing specific metrics curves."""
return []
@property
def curves_results(self) -> list:
+ """Return a list of curves results for accessing specific metrics curves."""
return []
def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, float]]:
+ """Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy).
+
+ Args:
+ normalize (bool): For Classify metrics, everything is normalized by default [0-1].
+ decimals (int): Number of decimal places to round the metrics values to.
+
+ Returns:
+ (list[dict[str, float]]): A list with one dictionary containing Top-1 and Top-5 classification accuracy.
+
+ Examples:
+ >>> results = model.val(data="imagenet10")
+ >>> classify_summary = results.summary(decimals=4)
+ >>> print(classify_summary)
+ """
return [{"top1_acc": round(self.top1, decimals), "top5_acc": round(self.top5, decimals)}]
class OBBMetrics(DetMetrics):
+ """Metrics for evaluating oriented bounding box (OBB) detection.
+
+ Attributes:
+ names (dict[int, str]): Dictionary of class names.
+ box (Metric): An instance of the Metric class for storing detection results.
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
+ target classes, and target images.
+ nt_per_class: Number of targets per class.
+ nt_per_image: Number of targets per image.
+
+ References:
+ https://arxiv.org/pdf/2106.06072.pdf
+ """
def __init__(self, names: dict[int, str] = {}) -> None:
- DetMetrics.__init__(self, names)+ """Initialize an OBBMetrics instance with class names.
+
+ Args:
+ names (dict[int, str], optional): Dictionary of class names.
+ """
+ DetMetrics.__init__(self, names)
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/metrics.py |
Add clean documentation to messy code | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from collections import abc
from itertools import repeat
from numbers import Number
import numpy as np
from .ops import ltwh2xywh, ltwh2xyxy, resample_segments, xywh2ltwh, xywh2xyxy, xyxy2ltwh, xyxy2xywh
def _ntuple(n):
def parse(x):
return x if isinstance(x, abc.Iterable) else tuple(repeat(x, n))
return parse
to_2tuple = _ntuple(2)
to_4tuple = _ntuple(4)
# `xyxy` means left top and right bottom
# `xywh` means center x, center y and width, height(YOLO format)
# `ltwh` means left top and width, height(COCO format)
_formats = ["xyxy", "xywh", "ltwh"]
__all__ = ("Bboxes", "Instances") # tuple or list
class Bboxes:
def __init__(self, bboxes: np.ndarray, format: str = "xyxy") -> None:
assert format in _formats, f"Invalid bounding box format: {format}, format must be one of {_formats}"
bboxes = bboxes[None, :] if bboxes.ndim == 1 else bboxes
assert bboxes.ndim == 2
assert bboxes.shape[1] == 4
self.bboxes = bboxes
self.format = format
def convert(self, format: str) -> None:
assert format in _formats, f"Invalid bounding box format: {format}, format must be one of {_formats}"
if self.format == format:
return
elif self.format == "xyxy":
func = xyxy2xywh if format == "xywh" else xyxy2ltwh
elif self.format == "xywh":
func = xywh2xyxy if format == "xyxy" else xywh2ltwh
else:
func = ltwh2xyxy if format == "xyxy" else ltwh2xywh
self.bboxes = func(self.bboxes)
self.format = format
def areas(self) -> np.ndarray:
return (
(self.bboxes[:, 2] - self.bboxes[:, 0]) * (self.bboxes[:, 3] - self.bboxes[:, 1]) # format xyxy
if self.format == "xyxy"
else self.bboxes[:, 3] * self.bboxes[:, 2] # format xywh or ltwh
)
def mul(self, scale: int | tuple | list) -> None:
if isinstance(scale, Number):
scale = to_4tuple(scale)
assert isinstance(scale, (tuple, list))
assert len(scale) == 4
self.bboxes[:, 0] *= scale[0]
self.bboxes[:, 1] *= scale[1]
self.bboxes[:, 2] *= scale[2]
self.bboxes[:, 3] *= scale[3]
def add(self, offset: int | tuple | list) -> None:
if isinstance(offset, Number):
offset = to_4tuple(offset)
assert isinstance(offset, (tuple, list))
assert len(offset) == 4
self.bboxes[:, 0] += offset[0]
self.bboxes[:, 1] += offset[1]
self.bboxes[:, 2] += offset[2]
self.bboxes[:, 3] += offset[3]
def __len__(self) -> int:
return len(self.bboxes)
@classmethod
def concatenate(cls, boxes_list: list[Bboxes], axis: int = 0) -> Bboxes:
assert isinstance(boxes_list, (list, tuple))
if not boxes_list:
return cls(np.empty(0))
assert all(isinstance(box, Bboxes) for box in boxes_list)
if len(boxes_list) == 1:
return boxes_list[0]
return cls(np.concatenate([b.bboxes for b in boxes_list], axis=axis))
def __getitem__(self, index: int | np.ndarray | slice) -> Bboxes:
if isinstance(index, int):
return Bboxes(self.bboxes[index].reshape(1, -1))
b = self.bboxes[index]
assert b.ndim == 2, f"Indexing on Bboxes with {index} failed to return a matrix!"
return Bboxes(b)
class Instances:
def __init__(
self,
bboxes: np.ndarray,
segments: np.ndarray = None,
keypoints: np.ndarray = None,
bbox_format: str = "xywh",
normalized: bool = True,
) -> None:
self._bboxes = Bboxes(bboxes=bboxes, format=bbox_format)
self.keypoints = keypoints
self.normalized = normalized
self.segments = segments
def convert_bbox(self, format: str) -> None:
self._bboxes.convert(format=format)
@property
def bbox_areas(self) -> np.ndarray:
return self._bboxes.areas()
def scale(self, scale_w: float, scale_h: float, bbox_only: bool = False):
self._bboxes.mul(scale=(scale_w, scale_h, scale_w, scale_h))
if bbox_only:
return
self.segments[..., 0] *= scale_w
self.segments[..., 1] *= scale_h
if self.keypoints is not None:
self.keypoints[..., 0] *= scale_w
self.keypoints[..., 1] *= scale_h
def denormalize(self, w: int, h: int) -> None:
if not self.normalized:
return
self._bboxes.mul(scale=(w, h, w, h))
self.segments[..., 0] *= w
self.segments[..., 1] *= h
if self.keypoints is not None:
self.keypoints[..., 0] *= w
self.keypoints[..., 1] *= h
self.normalized = False
def normalize(self, w: int, h: int) -> None:
if self.normalized:
return
self._bboxes.mul(scale=(1 / w, 1 / h, 1 / w, 1 / h))
self.segments[..., 0] /= w
self.segments[..., 1] /= h
if self.keypoints is not None:
self.keypoints[..., 0] /= w
self.keypoints[..., 1] /= h
self.normalized = True
def add_padding(self, padw: int, padh: int) -> None:
assert not self.normalized, "you should add padding with absolute coordinates."
self._bboxes.add(offset=(padw, padh, padw, padh))
self.segments[..., 0] += padw
self.segments[..., 1] += padh
if self.keypoints is not None:
self.keypoints[..., 0] += padw
self.keypoints[..., 1] += padh
def __getitem__(self, index: int | np.ndarray | slice) -> Instances:
segments = self.segments[index] if len(self.segments) else self.segments
keypoints = self.keypoints[index] if self.keypoints is not None else None
bboxes = self.bboxes[index]
bbox_format = self._bboxes.format
return Instances(
bboxes=bboxes,
segments=segments,
keypoints=keypoints,
bbox_format=bbox_format,
normalized=self.normalized,
)
def flipud(self, h: int) -> None:
if self._bboxes.format == "xyxy":
y1 = self.bboxes[:, 1].copy()
y2 = self.bboxes[:, 3].copy()
self.bboxes[:, 1] = h - y2
self.bboxes[:, 3] = h - y1
else:
self.bboxes[:, 1] = h - self.bboxes[:, 1]
self.segments[..., 1] = h - self.segments[..., 1]
if self.keypoints is not None:
self.keypoints[..., 1] = h - self.keypoints[..., 1]
def fliplr(self, w: int) -> None:
if self._bboxes.format == "xyxy":
x1 = self.bboxes[:, 0].copy()
x2 = self.bboxes[:, 2].copy()
self.bboxes[:, 0] = w - x2
self.bboxes[:, 2] = w - x1
else:
self.bboxes[:, 0] = w - self.bboxes[:, 0]
self.segments[..., 0] = w - self.segments[..., 0]
if self.keypoints is not None:
self.keypoints[..., 0] = w - self.keypoints[..., 0]
def clip(self, w: int, h: int) -> None:
ori_format = self._bboxes.format
self.convert_bbox(format="xyxy")
self.bboxes[:, [0, 2]] = self.bboxes[:, [0, 2]].clip(0, w)
self.bboxes[:, [1, 3]] = self.bboxes[:, [1, 3]].clip(0, h)
if ori_format != "xyxy":
self.convert_bbox(format=ori_format)
self.segments[..., 0] = self.segments[..., 0].clip(0, w)
self.segments[..., 1] = self.segments[..., 1].clip(0, h)
if self.keypoints is not None:
# Set out of bounds visibility to zero
self.keypoints[..., 2][
(self.keypoints[..., 0] < 0)
| (self.keypoints[..., 0] > w)
| (self.keypoints[..., 1] < 0)
| (self.keypoints[..., 1] > h)
] = 0.0
self.keypoints[..., 0] = self.keypoints[..., 0].clip(0, w)
self.keypoints[..., 1] = self.keypoints[..., 1].clip(0, h)
def remove_zero_area_boxes(self) -> np.ndarray:
good = self.bbox_areas > 0
if not all(good):
self._bboxes = self._bboxes[good]
if self.segments is not None and len(self.segments):
self.segments = self.segments[good]
if self.keypoints is not None:
self.keypoints = self.keypoints[good]
return good
def update(self, bboxes: np.ndarray, segments: np.ndarray = None, keypoints: np.ndarray = None):
self._bboxes = Bboxes(bboxes, format=self._bboxes.format)
if segments is not None:
self.segments = segments
if keypoints is not None:
self.keypoints = keypoints
def __len__(self) -> int:
return len(self.bboxes)
@classmethod
def concatenate(cls, instances_list: list[Instances], axis=0) -> Instances:
assert isinstance(instances_list, (list, tuple))
if not instances_list:
return cls(np.empty(0))
assert all(isinstance(instance, Instances) for instance in instances_list)
if len(instances_list) == 1:
return instances_list[0]
use_keypoint = instances_list[0].keypoints is not None
bbox_format = instances_list[0]._bboxes.format
normalized = instances_list[0].normalized
cat_boxes = np.concatenate([ins.bboxes for ins in instances_list], axis=axis)
seg_len = [b.segments.shape[1] for b in instances_list]
if len(frozenset(seg_len)) > 1: # resample segments if there's different length
max_len = max(seg_len)
cat_segments = np.concatenate(
[
resample_segments(list(b.segments), max_len)
if len(b.segments)
else np.zeros((0, max_len, 2), dtype=np.float32) # re-generating empty segments
for b in instances_list
],
axis=axis,
)
else:
cat_segments = np.concatenate([b.segments for b in instances_list], axis=axis)
cat_keypoints = np.concatenate([b.keypoints for b in instances_list], axis=axis) if use_keypoint else None
return cls(cat_boxes, cat_segments, cat_keypoints, bbox_format, normalized)
@property
def bboxes(self) -> np.ndarray:
return self._bboxes.bboxes
def __repr__(self) -> str:
# Map private to public names and include direct attributes
attr_map = {"_bboxes": "bboxes"}
parts = []
for key, value in self.__dict__.items():
name = attr_map.get(key, key)
if name == "bboxes":
value = self.bboxes # Use the property
if value is not None:
parts.append(f"{name}={value!r}")
return "Instances({})".format("\n".join(parts)) | --- +++ @@ -12,8 +12,10 @@
def _ntuple(n):
+ """Create a function that converts input to n-tuple by repeating singleton values."""
def parse(x):
+ """Parse input to return n-tuple by repeating singleton values n times."""
return x if isinstance(x, abc.Iterable) else tuple(repeat(x, n))
return parse
@@ -31,8 +33,39 @@
class Bboxes:
+ """A class for handling bounding boxes in multiple formats.
+
+ The class supports various bounding box formats like 'xyxy', 'xywh', and 'ltwh' and provides methods for format
+ conversion, scaling, and area calculation. Bounding box data should be provided as numpy arrays.
+
+ Attributes:
+ bboxes (np.ndarray): The bounding boxes stored in a 2D numpy array with shape (N, 4).
+ format (str): The format of the bounding boxes ('xyxy', 'xywh', or 'ltwh').
+
+ Methods:
+ convert: Convert bounding box format from one type to another.
+ areas: Calculate the area of bounding boxes.
+ mul: Multiply bounding box coordinates by scale factor(s).
+ add: Add offset to bounding box coordinates.
+ concatenate: Concatenate multiple Bboxes objects.
+
+ Examples:
+ Create bounding boxes in YOLO format
+ >>> bboxes = Bboxes(np.array([[100, 50, 150, 100]]), format="xywh")
+ >>> bboxes.convert("xyxy")
+ >>> print(bboxes.areas())
+
+ Notes:
+ This class does not handle normalization or denormalization of bounding boxes.
+ """
def __init__(self, bboxes: np.ndarray, format: str = "xyxy") -> None:
+ """Initialize the Bboxes class with bounding box data in a specified format.
+
+ Args:
+ bboxes (np.ndarray): Array of bounding boxes with shape (N, 4) or (4,).
+ format (str): Format of the bounding boxes, one of 'xyxy', 'xywh', or 'ltwh'.
+ """
assert format in _formats, f"Invalid bounding box format: {format}, format must be one of {_formats}"
bboxes = bboxes[None, :] if bboxes.ndim == 1 else bboxes
assert bboxes.ndim == 2
@@ -41,6 +74,11 @@ self.format = format
def convert(self, format: str) -> None:
+ """Convert bounding box format from one type to another.
+
+ Args:
+ format (str): Target format for conversion, one of 'xyxy', 'xywh', or 'ltwh'.
+ """
assert format in _formats, f"Invalid bounding box format: {format}, format must be one of {_formats}"
if self.format == format:
return
@@ -54,6 +92,7 @@ self.format = format
def areas(self) -> np.ndarray:
+ """Calculate the area of bounding boxes."""
return (
(self.bboxes[:, 2] - self.bboxes[:, 0]) * (self.bboxes[:, 3] - self.bboxes[:, 1]) # format xyxy
if self.format == "xyxy"
@@ -61,6 +100,12 @@ )
def mul(self, scale: int | tuple | list) -> None:
+ """Multiply bounding box coordinates by scale factor(s).
+
+ Args:
+ scale (int | tuple | list): Scale factor(s) for four coordinates. If int, the same scale is applied to all
+ coordinates.
+ """
if isinstance(scale, Number):
scale = to_4tuple(scale)
assert isinstance(scale, (tuple, list))
@@ -71,6 +116,12 @@ self.bboxes[:, 3] *= scale[3]
def add(self, offset: int | tuple | list) -> None:
+ """Add offset to bounding box coordinates.
+
+ Args:
+ offset (int | tuple | list): Offset(s) for four coordinates. If int, the same offset is applied to all
+ coordinates.
+ """
if isinstance(offset, Number):
offset = to_4tuple(offset)
assert isinstance(offset, (tuple, list))
@@ -81,10 +132,23 @@ self.bboxes[:, 3] += offset[3]
def __len__(self) -> int:
+ """Return the number of bounding boxes."""
return len(self.bboxes)
@classmethod
def concatenate(cls, boxes_list: list[Bboxes], axis: int = 0) -> Bboxes:
+ """Concatenate a list of Bboxes objects into a single Bboxes object.
+
+ Args:
+ boxes_list (list[Bboxes]): A list of Bboxes objects to concatenate.
+ axis (int, optional): The axis along which to concatenate the bounding boxes.
+
+ Returns:
+ (Bboxes): A new Bboxes object containing the concatenated bounding boxes.
+
+ Notes:
+ The input should be a list or tuple of Bboxes objects.
+ """
assert isinstance(boxes_list, (list, tuple))
if not boxes_list:
return cls(np.empty(0))
@@ -95,6 +159,18 @@ return cls(np.concatenate([b.bboxes for b in boxes_list], axis=axis))
def __getitem__(self, index: int | np.ndarray | slice) -> Bboxes:
+ """Retrieve a specific bounding box or a set of bounding boxes using indexing.
+
+ Args:
+ index (int | slice | np.ndarray): The index, slice, or boolean array to select the desired bounding boxes.
+
+ Returns:
+ (Bboxes): A new Bboxes object containing the selected bounding boxes.
+
+ Notes:
+ When using boolean indexing, make sure to provide a boolean array with the same length as the number of
+ bounding boxes.
+ """
if isinstance(index, int):
return Bboxes(self.bboxes[index].reshape(1, -1))
b = self.bboxes[index]
@@ -103,6 +179,39 @@
class Instances:
+ """Container for bounding boxes, segments, and keypoints of detected objects in an image.
+
+ This class provides a unified interface for handling different types of object annotations including bounding boxes,
+ segmentation masks, and keypoints. It supports various operations like scaling, normalization, clipping, and format
+ conversion.
+
+ Attributes:
+ _bboxes (Bboxes): Internal object for handling bounding box operations.
+ keypoints (np.ndarray): Keypoints with shape (N, 17, 3) in format (x, y, visible).
+ normalized (bool): Flag indicating whether the bounding box coordinates are normalized.
+ segments (np.ndarray): Segments array with shape (N, M, 2) after resampling.
+
+ Methods:
+ convert_bbox: Convert bounding box format.
+ scale: Scale coordinates by given factors.
+ denormalize: Convert normalized coordinates to absolute coordinates.
+ normalize: Convert absolute coordinates to normalized coordinates.
+ add_padding: Add padding to coordinates.
+ flipud: Flip coordinates vertically.
+ fliplr: Flip coordinates horizontally.
+ clip: Clip coordinates to stay within image boundaries.
+ remove_zero_area_boxes: Remove boxes with zero area.
+ update: Update instance variables.
+ concatenate: Concatenate multiple Instances objects.
+
+ Examples:
+ Create instances with bounding boxes and segments
+ >>> instances = Instances(
+ ... bboxes=np.array([[10, 10, 30, 30], [20, 20, 40, 40]]),
+ ... segments=[np.array([[5, 5], [10, 10]]), np.array([[15, 15], [20, 20]])],
+ ... keypoints=np.array([[[5, 5, 1], [10, 10, 1]], [[15, 15, 1], [20, 20, 1]]]),
+ ... )
+ """
def __init__(
self,
@@ -112,19 +221,41 @@ bbox_format: str = "xywh",
normalized: bool = True,
) -> None:
+ """Initialize the Instances object with bounding boxes, segments, and keypoints.
+
+ Args:
+ bboxes (np.ndarray): Bounding boxes with shape (N, 4).
+ segments (np.ndarray, optional): Segmentation masks.
+ keypoints (np.ndarray, optional): Keypoints with shape (N, 17, 3) in format (x, y, visible).
+ bbox_format (str): Format of bboxes.
+ normalized (bool): Whether the coordinates are normalized.
+ """
self._bboxes = Bboxes(bboxes=bboxes, format=bbox_format)
self.keypoints = keypoints
self.normalized = normalized
self.segments = segments
def convert_bbox(self, format: str) -> None:
+ """Convert bounding box format.
+
+ Args:
+ format (str): Target format for conversion, one of 'xyxy', 'xywh', or 'ltwh'.
+ """
self._bboxes.convert(format=format)
@property
def bbox_areas(self) -> np.ndarray:
+ """Calculate the area of bounding boxes."""
return self._bboxes.areas()
def scale(self, scale_w: float, scale_h: float, bbox_only: bool = False):
+ """Scale coordinates by given factors.
+
+ Args:
+ scale_w (float): Scale factor for width.
+ scale_h (float): Scale factor for height.
+ bbox_only (bool, optional): Whether to scale only bounding boxes.
+ """
self._bboxes.mul(scale=(scale_w, scale_h, scale_w, scale_h))
if bbox_only:
return
@@ -135,6 +266,12 @@ self.keypoints[..., 1] *= scale_h
def denormalize(self, w: int, h: int) -> None:
+ """Convert normalized coordinates to absolute coordinates.
+
+ Args:
+ w (int): Image width.
+ h (int): Image height.
+ """
if not self.normalized:
return
self._bboxes.mul(scale=(w, h, w, h))
@@ -146,6 +283,12 @@ self.normalized = False
def normalize(self, w: int, h: int) -> None:
+ """Convert absolute coordinates to normalized coordinates.
+
+ Args:
+ w (int): Image width.
+ h (int): Image height.
+ """
if self.normalized:
return
self._bboxes.mul(scale=(1 / w, 1 / h, 1 / w, 1 / h))
@@ -157,6 +300,12 @@ self.normalized = True
def add_padding(self, padw: int, padh: int) -> None:
+ """Add padding to coordinates.
+
+ Args:
+ padw (int): Padding width.
+ padh (int): Padding height.
+ """
assert not self.normalized, "you should add padding with absolute coordinates."
self._bboxes.add(offset=(padw, padh, padw, padh))
self.segments[..., 0] += padw
@@ -166,6 +315,18 @@ self.keypoints[..., 1] += padh
def __getitem__(self, index: int | np.ndarray | slice) -> Instances:
+ """Retrieve a specific instance or a set of instances using indexing.
+
+ Args:
+ index (int | slice | np.ndarray): The index, slice, or boolean array to select the desired instances.
+
+ Returns:
+ (Instances): A new Instances object containing the selected boxes, segments, and keypoints if present.
+
+ Notes:
+ When using boolean indexing, make sure to provide a boolean array with the same length as the number of
+ instances.
+ """
segments = self.segments[index] if len(self.segments) else self.segments
keypoints = self.keypoints[index] if self.keypoints is not None else None
bboxes = self.bboxes[index]
@@ -179,6 +340,11 @@ )
def flipud(self, h: int) -> None:
+ """Flip coordinates vertically.
+
+ Args:
+ h (int): Image height.
+ """
if self._bboxes.format == "xyxy":
y1 = self.bboxes[:, 1].copy()
y2 = self.bboxes[:, 3].copy()
@@ -191,6 +357,11 @@ self.keypoints[..., 1] = h - self.keypoints[..., 1]
def fliplr(self, w: int) -> None:
+ """Flip coordinates horizontally.
+
+ Args:
+ w (int): Image width.
+ """
if self._bboxes.format == "xyxy":
x1 = self.bboxes[:, 0].copy()
x2 = self.bboxes[:, 2].copy()
@@ -203,6 +374,12 @@ self.keypoints[..., 0] = w - self.keypoints[..., 0]
def clip(self, w: int, h: int) -> None:
+ """Clip coordinates to stay within image boundaries.
+
+ Args:
+ w (int): Image width.
+ h (int): Image height.
+ """
ori_format = self._bboxes.format
self.convert_bbox(format="xyxy")
self.bboxes[:, [0, 2]] = self.bboxes[:, [0, 2]].clip(0, w)
@@ -223,6 +400,11 @@ self.keypoints[..., 1] = self.keypoints[..., 1].clip(0, h)
def remove_zero_area_boxes(self) -> np.ndarray:
+ """Remove zero-area boxes, i.e. after clipping some boxes may have zero width or height.
+
+ Returns:
+ (np.ndarray): Boolean array indicating which boxes were kept.
+ """
good = self.bbox_areas > 0
if not all(good):
self._bboxes = self._bboxes[good]
@@ -233,6 +415,13 @@ return good
def update(self, bboxes: np.ndarray, segments: np.ndarray = None, keypoints: np.ndarray = None):
+ """Update instance variables.
+
+ Args:
+ bboxes (np.ndarray): New bounding boxes.
+ segments (np.ndarray, optional): New segments.
+ keypoints (np.ndarray, optional): New keypoints.
+ """
self._bboxes = Bboxes(bboxes, format=self._bboxes.format)
if segments is not None:
self.segments = segments
@@ -240,10 +429,25 @@ self.keypoints = keypoints
def __len__(self) -> int:
+ """Return the number of instances."""
return len(self.bboxes)
@classmethod
def concatenate(cls, instances_list: list[Instances], axis=0) -> Instances:
+ """Concatenate a list of Instances objects into a single Instances object.
+
+ Args:
+ instances_list (list[Instances]): A list of Instances objects to concatenate.
+ axis (int, optional): The axis along which the arrays will be concatenated.
+
+ Returns:
+ (Instances): A new Instances object containing the concatenated bounding boxes, segments, and keypoints if
+ present.
+
+ Notes:
+ The `Instances` objects in the list should have the same properties, such as the format of the bounding
+ boxes, whether keypoints are present, and if the coordinates are normalized.
+ """
assert isinstance(instances_list, (list, tuple))
if not instances_list:
return cls(np.empty(0))
@@ -276,9 +480,11 @@
@property
def bboxes(self) -> np.ndarray:
+ """Return bounding boxes."""
return self._bboxes.bboxes
def __repr__(self) -> str:
+ """Return a string representation of the Instances object."""
# Map private to public names and include direct attributes
attr_map = {"_bboxes": "bboxes"}
parts = []
@@ -288,4 +494,4 @@ value = self.bboxes # Use the property
if value is not None:
parts.append(f"{name}={value!r}")
- return "Instances({})".format("\n".join(parts))+ return "Instances({})".format("\n".join(parts))
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/instance.py |
Add docstrings to clarify complex logic | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import math
from typing import Any
import torch
import torch.nn as nn
import torch.nn.functional as F
from ultralytics.utils.metrics import OKS_SIGMA, RLE_WEIGHT
from ultralytics.utils.ops import crop_mask, xywh2xyxy, xyxy2xywh
from ultralytics.utils.tal import RotatedTaskAlignedAssigner, TaskAlignedAssigner, dist2bbox, dist2rbox, make_anchors
from ultralytics.utils.torch_utils import autocast
from .metrics import bbox_iou, probiou
from .tal import bbox2dist, rbox2dist
class VarifocalLoss(nn.Module):
def __init__(self, gamma: float = 2.0, alpha: float = 0.75):
super().__init__()
self.gamma = gamma
self.alpha = alpha
def forward(self, pred_score: torch.Tensor, gt_score: torch.Tensor, label: torch.Tensor) -> torch.Tensor:
weight = self.alpha * pred_score.sigmoid().pow(self.gamma) * (1 - label) + gt_score * label
with autocast(enabled=False):
loss = (
(F.binary_cross_entropy_with_logits(pred_score.float(), gt_score.float(), reduction="none") * weight)
.mean(1)
.sum()
)
return loss
class FocalLoss(nn.Module):
def __init__(self, gamma: float = 1.5, alpha: float = 0.25):
super().__init__()
self.gamma = gamma
self.alpha = torch.tensor(alpha)
def forward(self, pred: torch.Tensor, label: torch.Tensor) -> torch.Tensor:
loss = F.binary_cross_entropy_with_logits(pred, label, reduction="none")
# p_t = torch.exp(-loss)
# loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
# TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
pred_prob = pred.sigmoid() # prob from logits
p_t = label * pred_prob + (1 - label) * (1 - pred_prob)
modulating_factor = (1.0 - p_t) ** self.gamma
loss *= modulating_factor
if (self.alpha > 0).any():
self.alpha = self.alpha.to(device=pred.device, dtype=pred.dtype)
alpha_factor = label * self.alpha + (1 - label) * (1 - self.alpha)
loss *= alpha_factor
return loss.mean(1).sum()
class DFLoss(nn.Module):
def __init__(self, reg_max: int = 16) -> None:
super().__init__()
self.reg_max = reg_max
def __call__(self, pred_dist: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
target = target.clamp_(0, self.reg_max - 1 - 0.01)
tl = target.long() # target left
tr = tl + 1 # target right
wl = tr - target # weight left
wr = 1 - wl # weight right
return (
F.cross_entropy(pred_dist, tl.view(-1), reduction="none").view(tl.shape) * wl
+ F.cross_entropy(pred_dist, tr.view(-1), reduction="none").view(tl.shape) * wr
).mean(-1, keepdim=True)
class BboxLoss(nn.Module):
def __init__(self, reg_max: int = 16):
super().__init__()
self.dfl_loss = DFLoss(reg_max) if reg_max > 1 else None
def forward(
self,
pred_dist: torch.Tensor,
pred_bboxes: torch.Tensor,
anchor_points: torch.Tensor,
target_bboxes: torch.Tensor,
target_scores: torch.Tensor,
target_scores_sum: torch.Tensor,
fg_mask: torch.Tensor,
imgsz: torch.Tensor,
stride: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
weight = target_scores.sum(-1)[fg_mask].unsqueeze(-1)
iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, CIoU=True)
loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum
# DFL loss
if self.dfl_loss:
target_ltrb = bbox2dist(anchor_points, target_bboxes, self.dfl_loss.reg_max - 1)
loss_dfl = self.dfl_loss(pred_dist[fg_mask].view(-1, self.dfl_loss.reg_max), target_ltrb[fg_mask]) * weight
loss_dfl = loss_dfl.sum() / target_scores_sum
else:
target_ltrb = bbox2dist(anchor_points, target_bboxes)
# normalize ltrb by image size
target_ltrb = target_ltrb * stride
target_ltrb[..., 0::2] /= imgsz[1]
target_ltrb[..., 1::2] /= imgsz[0]
pred_dist = pred_dist * stride
pred_dist[..., 0::2] /= imgsz[1]
pred_dist[..., 1::2] /= imgsz[0]
loss_dfl = (
F.l1_loss(pred_dist[fg_mask], target_ltrb[fg_mask], reduction="none").mean(-1, keepdim=True) * weight
)
loss_dfl = loss_dfl.sum() / target_scores_sum
return loss_iou, loss_dfl
class RLELoss(nn.Module):
def __init__(self, use_target_weight: bool = True, size_average: bool = True, residual: bool = True):
super().__init__()
self.size_average = size_average
self.use_target_weight = use_target_weight
self.residual = residual
def forward(
self, sigma: torch.Tensor, log_phi: torch.Tensor, error: torch.Tensor, target_weight: torch.Tensor = None
) -> torch.Tensor:
log_sigma = torch.log(sigma)
loss = log_sigma - log_phi.unsqueeze(1)
if self.residual:
loss += torch.log(sigma * 2) + torch.abs(error)
if self.use_target_weight:
assert target_weight is not None, "'target_weight' should not be None when 'use_target_weight' is True."
if target_weight.dim() == 1:
target_weight = target_weight.unsqueeze(1)
loss *= target_weight
if self.size_average:
loss /= len(loss)
return loss.sum()
class RotatedBboxLoss(BboxLoss):
def __init__(self, reg_max: int):
super().__init__(reg_max)
def forward(
self,
pred_dist: torch.Tensor,
pred_bboxes: torch.Tensor,
anchor_points: torch.Tensor,
target_bboxes: torch.Tensor,
target_scores: torch.Tensor,
target_scores_sum: torch.Tensor,
fg_mask: torch.Tensor,
imgsz: torch.Tensor,
stride: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
weight = target_scores.sum(-1)[fg_mask].unsqueeze(-1)
iou = probiou(pred_bboxes[fg_mask], target_bboxes[fg_mask])
loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum
# DFL loss
if self.dfl_loss:
target_ltrb = rbox2dist(
target_bboxes[..., :4], anchor_points, target_bboxes[..., 4:5], reg_max=self.dfl_loss.reg_max - 1
)
loss_dfl = self.dfl_loss(pred_dist[fg_mask].view(-1, self.dfl_loss.reg_max), target_ltrb[fg_mask]) * weight
loss_dfl = loss_dfl.sum() / target_scores_sum
else:
target_ltrb = rbox2dist(target_bboxes[..., :4], anchor_points, target_bboxes[..., 4:5])
target_ltrb = target_ltrb * stride
target_ltrb[..., 0::2] /= imgsz[1]
target_ltrb[..., 1::2] /= imgsz[0]
pred_dist = pred_dist * stride
pred_dist[..., 0::2] /= imgsz[1]
pred_dist[..., 1::2] /= imgsz[0]
loss_dfl = (
F.l1_loss(pred_dist[fg_mask], target_ltrb[fg_mask], reduction="none").mean(-1, keepdim=True) * weight
)
loss_dfl = loss_dfl.sum() / target_scores_sum
return loss_iou, loss_dfl
class MultiChannelDiceLoss(nn.Module):
def __init__(self, smooth: float = 1e-6, reduction: str = "mean"):
super().__init__()
self.smooth = smooth
self.reduction = reduction
def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
assert pred.size() == target.size(), "the size of predict and target must be equal."
pred = pred.sigmoid()
intersection = (pred * target).sum(dim=(2, 3))
union = pred.sum(dim=(2, 3)) + target.sum(dim=(2, 3))
dice = (2.0 * intersection + self.smooth) / (union + self.smooth)
dice_loss = 1.0 - dice
dice_loss = dice_loss.mean(dim=1)
if self.reduction == "mean":
return dice_loss.mean()
elif self.reduction == "sum":
return dice_loss.sum()
else:
return dice_loss
class BCEDiceLoss(nn.Module):
def __init__(self, weight_bce: float = 0.5, weight_dice: float = 0.5):
super().__init__()
self.weight_bce = weight_bce
self.weight_dice = weight_dice
self.bce = nn.BCEWithLogitsLoss()
self.dice = MultiChannelDiceLoss(smooth=1)
def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
_, _, mask_h, mask_w = pred.shape
if tuple(target.shape[-2:]) != (mask_h, mask_w): # downsample to the same size as pred
target = F.interpolate(target, (mask_h, mask_w), mode="nearest")
return self.weight_bce * self.bce(pred, target) + self.weight_dice * self.dice(pred, target)
class KeypointLoss(nn.Module):
def __init__(self, sigmas: torch.Tensor) -> None:
super().__init__()
self.sigmas = sigmas
def forward(
self, pred_kpts: torch.Tensor, gt_kpts: torch.Tensor, kpt_mask: torch.Tensor, area: torch.Tensor
) -> torch.Tensor:
d = (pred_kpts[..., 0] - gt_kpts[..., 0]).pow(2) + (pred_kpts[..., 1] - gt_kpts[..., 1]).pow(2)
kpt_loss_factor = kpt_mask.shape[1] / (torch.sum(kpt_mask != 0, dim=1) + 1e-9)
# e = d / (2 * (area * self.sigmas) ** 2 + 1e-9) # from formula
e = d / ((2 * self.sigmas).pow(2) * (area + 1e-9) * 2) # from cocoeval
return (kpt_loss_factor.view(-1, 1) * ((1 - torch.exp(-e)) * kpt_mask)).mean()
class v8DetectionLoss:
def __init__(self, model, tal_topk: int = 10, tal_topk2: int | None = None): # model must be de-paralleled
device = next(model.parameters()).device # get model device
h = model.args # hyperparameters
m = model.model[-1] # Detect() module
self.bce = nn.BCEWithLogitsLoss(reduction="none")
self.hyp = h
self.stride = m.stride # model strides
self.nc = m.nc # number of classes
self.no = m.nc + m.reg_max * 4
self.reg_max = m.reg_max
self.device = device
self.use_dfl = m.reg_max > 1
self.assigner = TaskAlignedAssigner(
topk=tal_topk,
num_classes=self.nc,
alpha=0.5,
beta=6.0,
stride=self.stride.tolist(),
topk2=tal_topk2,
)
self.bbox_loss = BboxLoss(m.reg_max).to(device)
self.proj = torch.arange(m.reg_max, dtype=torch.float, device=device)
def preprocess(self, targets: torch.Tensor, batch_size: int, scale_tensor: torch.Tensor) -> torch.Tensor:
nl, ne = targets.shape
if nl == 0:
out = torch.zeros(batch_size, 0, ne - 1, device=self.device)
else:
i = targets[:, 0] # image index
_, counts = i.unique(return_counts=True)
counts = counts.to(dtype=torch.int32)
out = torch.zeros(batch_size, counts.max(), ne - 1, device=self.device)
for j in range(batch_size):
matches = i == j
if n := matches.sum():
out[j, :n] = targets[matches, 1:]
out[..., 1:5] = xywh2xyxy(out[..., 1:5].mul_(scale_tensor))
return out
def bbox_decode(self, anchor_points: torch.Tensor, pred_dist: torch.Tensor) -> torch.Tensor:
if self.use_dfl:
b, a, c = pred_dist.shape # batch, anchors, channels
pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype))
# pred_dist = pred_dist.view(b, a, c // 4, 4).transpose(2,3).softmax(3).matmul(self.proj.type(pred_dist.dtype))
# pred_dist = (pred_dist.view(b, a, c // 4, 4).softmax(2) * self.proj.type(pred_dist.dtype).view(1, 1, -1, 1)).sum(2)
return dist2bbox(pred_dist, anchor_points, xywh=False)
def get_assigned_targets_and_loss(self, preds: dict[str, torch.Tensor], batch: dict[str, Any]) -> tuple:
loss = torch.zeros(3, device=self.device) # box, cls, dfl
pred_distri, pred_scores = (
preds["boxes"].permute(0, 2, 1).contiguous(),
preds["scores"].permute(0, 2, 1).contiguous(),
)
anchor_points, stride_tensor = make_anchors(preds["feats"], self.stride, 0.5)
dtype = pred_scores.dtype
batch_size = pred_scores.shape[0]
imgsz = torch.tensor(preds["feats"][0].shape[2:], device=self.device, dtype=dtype) * self.stride[0]
# Targets
targets = torch.cat((batch["batch_idx"].view(-1, 1), batch["cls"].view(-1, 1), batch["bboxes"]), 1)
targets = self.preprocess(targets.to(self.device), batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])
gt_labels, gt_bboxes = targets.split((1, 4), 2) # cls, xyxy
mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0.0)
# Pboxes
pred_bboxes = self.bbox_decode(anchor_points, pred_distri) # xyxy, (b, h*w, 4)
_, target_bboxes, target_scores, fg_mask, target_gt_idx = self.assigner(
pred_scores.detach().sigmoid(),
(pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype),
anchor_points * stride_tensor,
gt_labels,
gt_bboxes,
mask_gt,
)
target_scores_sum = max(target_scores.sum(), 1)
# Cls loss
loss[1] = self.bce(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum # BCE
# Bbox loss
if fg_mask.sum():
loss[0], loss[2] = self.bbox_loss(
pred_distri,
pred_bboxes,
anchor_points,
target_bboxes / stride_tensor,
target_scores,
target_scores_sum,
fg_mask,
imgsz,
stride_tensor,
)
loss[0] *= self.hyp.box # box gain
loss[1] *= self.hyp.cls # cls gain
loss[2] *= self.hyp.dfl # dfl gain
return (
(fg_mask, target_gt_idx, target_bboxes, anchor_points, stride_tensor),
loss,
loss.detach(),
) # loss(box, cls, dfl)
def parse_output(
self, preds: dict[str, torch.Tensor] | tuple[torch.Tensor, dict[str, torch.Tensor]]
) -> torch.Tensor:
return preds[1] if isinstance(preds, tuple) else preds
def __call__(
self,
preds: dict[str, torch.Tensor] | tuple[torch.Tensor, dict[str, torch.Tensor]],
batch: dict[str, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor]:
return self.loss(self.parse_output(preds), batch)
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
batch_size = preds["boxes"].shape[0]
loss, loss_detach = self.get_assigned_targets_and_loss(preds, batch)[1:]
return loss * batch_size, loss_detach
class v8SegmentationLoss(v8DetectionLoss):
def __init__(self, model, tal_topk: int = 10, tal_topk2: int | None = None): # model must be de-paralleled
super().__init__(model, tal_topk, tal_topk2)
self.overlap = model.args.overlap_mask
self.bcedice_loss = BCEDiceLoss(weight_bce=0.5, weight_dice=0.5)
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
pred_masks, proto = preds["mask_coefficient"].permute(0, 2, 1).contiguous(), preds["proto"]
loss = torch.zeros(5, device=self.device) # box, seg, cls, dfl, semseg
if isinstance(proto, tuple) and len(proto) == 2:
proto, pred_semseg = proto
else:
pred_semseg = None
(fg_mask, target_gt_idx, target_bboxes, _, _), det_loss, _ = self.get_assigned_targets_and_loss(preds, batch)
# NOTE: re-assign index for consistency for now. Need to be removed in the future.
loss[0], loss[2], loss[3] = det_loss[0], det_loss[1], det_loss[2]
batch_size, _, mask_h, mask_w = proto.shape # batch size, number of masks, mask height, mask width
if fg_mask.sum():
# Masks loss
masks = batch["masks"].to(self.device).float()
if tuple(masks.shape[-2:]) != (mask_h, mask_w): # downsample
# masks = F.interpolate(masks[None], (mask_h, mask_w), mode="nearest")[0]
proto = F.interpolate(proto, masks.shape[-2:], mode="bilinear", align_corners=False)
imgsz = (
torch.tensor(preds["feats"][0].shape[2:], device=self.device, dtype=pred_masks.dtype) * self.stride[0]
)
loss[1] = self.calculate_segmentation_loss(
fg_mask,
masks,
target_gt_idx,
target_bboxes,
batch["batch_idx"].view(-1, 1),
proto,
pred_masks,
imgsz,
)
if pred_semseg is not None:
sem_masks = batch["sem_masks"].to(self.device) # NxHxW
sem_masks = F.one_hot(sem_masks.long(), num_classes=self.nc).permute(0, 3, 1, 2).float() # NxCxHxW
if self.overlap:
mask_zero = masks == 0 # NxHxW
sem_masks[mask_zero.unsqueeze(1).expand_as(sem_masks)] = 0
else:
batch_idx = batch["batch_idx"].view(-1) # [total_instances]
for i in range(batch_size):
instance_mask_i = masks[batch_idx == i] # [num_instances_i, H, W]
if len(instance_mask_i) == 0:
continue
sem_masks[i, :, instance_mask_i.sum(dim=0) == 0] = 0
loss[4] = self.bcedice_loss(pred_semseg, sem_masks)
loss[4] *= self.hyp.box # seg gain
# WARNING: lines below prevent Multi-GPU DDP 'unused gradient' PyTorch errors, do not remove
else:
loss[1] += (proto * 0).sum() + (pred_masks * 0).sum() # inf sums may lead to nan loss
if pred_semseg is not None:
loss[4] += (pred_semseg * 0).sum()
loss[1] *= self.hyp.box # seg gain
return loss * batch_size, loss.detach() # loss(box, seg, cls, dfl, semseg)
@staticmethod
def single_mask_loss(
gt_mask: torch.Tensor, pred: torch.Tensor, proto: torch.Tensor, xyxy: torch.Tensor, area: torch.Tensor
) -> torch.Tensor:
pred_mask = torch.einsum("in,nhw->ihw", pred, proto) # (n, 32) @ (32, 80, 80) -> (n, 80, 80)
loss = F.binary_cross_entropy_with_logits(pred_mask, gt_mask, reduction="none")
return (crop_mask(loss, xyxy).mean(dim=(1, 2)) / area).sum()
def calculate_segmentation_loss(
self,
fg_mask: torch.Tensor,
masks: torch.Tensor,
target_gt_idx: torch.Tensor,
target_bboxes: torch.Tensor,
batch_idx: torch.Tensor,
proto: torch.Tensor,
pred_masks: torch.Tensor,
imgsz: torch.Tensor,
) -> torch.Tensor:
_, _, mask_h, mask_w = proto.shape
loss = 0
# Normalize to 0-1
target_bboxes_normalized = target_bboxes / imgsz[[1, 0, 1, 0]]
# Areas of target bboxes
marea = xyxy2xywh(target_bboxes_normalized)[..., 2:].prod(2)
# Normalize to mask size
mxyxy = target_bboxes_normalized * torch.tensor([mask_w, mask_h, mask_w, mask_h], device=proto.device)
for i, single_i in enumerate(zip(fg_mask, target_gt_idx, pred_masks, proto, mxyxy, marea, masks)):
fg_mask_i, target_gt_idx_i, pred_masks_i, proto_i, mxyxy_i, marea_i, masks_i = single_i
if fg_mask_i.any():
mask_idx = target_gt_idx_i[fg_mask_i]
if self.overlap:
gt_mask = masks_i == (mask_idx + 1).view(-1, 1, 1)
gt_mask = gt_mask.float()
else:
gt_mask = masks[batch_idx.view(-1) == i][mask_idx]
loss += self.single_mask_loss(
gt_mask, pred_masks_i[fg_mask_i], proto_i, mxyxy_i[fg_mask_i], marea_i[fg_mask_i]
)
# WARNING: lines below prevents Multi-GPU DDP 'unused gradient' PyTorch errors, do not remove
else:
loss += (proto * 0).sum() + (pred_masks * 0).sum() # inf sums may lead to nan loss
return loss / fg_mask.sum()
class v8PoseLoss(v8DetectionLoss):
def __init__(self, model, tal_topk: int = 10, tal_topk2: int = 10): # model must be de-paralleled
super().__init__(model, tal_topk, tal_topk2)
self.kpt_shape = model.model[-1].kpt_shape
self.bce_pose = nn.BCEWithLogitsLoss()
is_pose = self.kpt_shape == [17, 3]
nkpt = self.kpt_shape[0] # number of keypoints
sigmas = torch.from_numpy(OKS_SIGMA).to(self.device) if is_pose else torch.ones(nkpt, device=self.device) / nkpt
self.keypoint_loss = KeypointLoss(sigmas=sigmas)
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
pred_kpts = preds["kpts"].permute(0, 2, 1).contiguous()
loss = torch.zeros(5, device=self.device) # box, kpt_location, kpt_visibility, cls, dfl
(fg_mask, target_gt_idx, target_bboxes, anchor_points, stride_tensor), det_loss, _ = (
self.get_assigned_targets_and_loss(preds, batch)
)
# NOTE: re-assign index for consistency for now. Need to be removed in the future.
loss[0], loss[3], loss[4] = det_loss[0], det_loss[1], det_loss[2]
batch_size = pred_kpts.shape[0]
imgsz = torch.tensor(preds["feats"][0].shape[2:], device=self.device, dtype=pred_kpts.dtype) * self.stride[0]
# Pboxes
pred_kpts = self.kpts_decode(anchor_points, pred_kpts.view(batch_size, -1, *self.kpt_shape)) # (b, h*w, 17, 3)
# Keypoint loss
if fg_mask.sum():
keypoints = batch["keypoints"].to(self.device).float().clone()
keypoints[..., 0] *= imgsz[1]
keypoints[..., 1] *= imgsz[0]
loss[1], loss[2] = self.calculate_keypoints_loss(
fg_mask,
target_gt_idx,
keypoints,
batch["batch_idx"].view(-1, 1),
stride_tensor,
target_bboxes,
pred_kpts,
)
loss[1] *= self.hyp.pose # pose gain
loss[2] *= self.hyp.kobj # kobj gain
return loss * batch_size, loss.detach() # loss(box, pose, kobj, cls, dfl)
@staticmethod
def kpts_decode(anchor_points: torch.Tensor, pred_kpts: torch.Tensor) -> torch.Tensor:
y = pred_kpts.clone()
y[..., :2] *= 2.0
y[..., 0] += anchor_points[:, [0]] - 0.5
y[..., 1] += anchor_points[:, [1]] - 0.5
return y
def _select_target_keypoints(
self,
keypoints: torch.Tensor,
batch_idx: torch.Tensor,
target_gt_idx: torch.Tensor,
masks: torch.Tensor,
) -> torch.Tensor:
batch_idx = batch_idx.flatten()
batch_size = len(masks)
# Find the maximum number of keypoints in a single image
max_kpts = torch.unique(batch_idx, return_counts=True)[1].max()
# Create a tensor to hold batched keypoints
batched_keypoints = torch.zeros(
(batch_size, max_kpts, keypoints.shape[1], keypoints.shape[2]), device=keypoints.device
)
# TODO: any idea how to vectorize this?
# Fill batched_keypoints with keypoints based on batch_idx
for i in range(batch_size):
keypoints_i = keypoints[batch_idx == i]
batched_keypoints[i, : keypoints_i.shape[0]] = keypoints_i
# Expand dimensions of target_gt_idx to match the shape of batched_keypoints
target_gt_idx_expanded = target_gt_idx.unsqueeze(-1).unsqueeze(-1)
# Use target_gt_idx_expanded to select keypoints from batched_keypoints
selected_keypoints = batched_keypoints.gather(
1, target_gt_idx_expanded.expand(-1, -1, keypoints.shape[1], keypoints.shape[2])
)
return selected_keypoints
def calculate_keypoints_loss(
self,
masks: torch.Tensor,
target_gt_idx: torch.Tensor,
keypoints: torch.Tensor,
batch_idx: torch.Tensor,
stride_tensor: torch.Tensor,
target_bboxes: torch.Tensor,
pred_kpts: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
# Select target keypoints using helper method
selected_keypoints = self._select_target_keypoints(keypoints, batch_idx, target_gt_idx, masks)
# Divide coordinates by stride
selected_keypoints[..., :2] /= stride_tensor.view(1, -1, 1, 1)
kpts_loss = 0
kpts_obj_loss = 0
if masks.any():
target_bboxes /= stride_tensor
gt_kpt = selected_keypoints[masks]
area = xyxy2xywh(target_bboxes[masks])[:, 2:].prod(1, keepdim=True)
pred_kpt = pred_kpts[masks]
kpt_mask = gt_kpt[..., 2] != 0 if gt_kpt.shape[-1] == 3 else torch.full_like(gt_kpt[..., 0], True)
kpts_loss = self.keypoint_loss(pred_kpt, gt_kpt, kpt_mask, area) # pose loss
if pred_kpt.shape[-1] == 3:
kpts_obj_loss = self.bce_pose(pred_kpt[..., 2], kpt_mask.float()) # keypoint obj loss
return kpts_loss, kpts_obj_loss
class PoseLoss26(v8PoseLoss):
def __init__(self, model, tal_topk: int = 10, tal_topk2: int | None = None): # model must be de-paralleled
super().__init__(model, tal_topk, tal_topk2)
is_pose = self.kpt_shape == [17, 3]
nkpt = self.kpt_shape[0] # number of keypoints
self.rle_loss = None
self.flow_model = model.model[-1].flow_model if hasattr(model.model[-1], "flow_model") else None
if self.flow_model is not None:
self.rle_loss = RLELoss(use_target_weight=True).to(self.device)
self.target_weights = (
torch.from_numpy(RLE_WEIGHT).to(self.device) if is_pose else torch.ones(nkpt, device=self.device)
)
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
pred_kpts = preds["kpts"].permute(0, 2, 1).contiguous()
loss = torch.zeros(
6 if self.rle_loss else 5, device=self.device
) # box, kpt_location, kpt_visibility, cls, dfl[, rle]
(fg_mask, target_gt_idx, target_bboxes, anchor_points, stride_tensor), det_loss, _ = (
self.get_assigned_targets_and_loss(preds, batch)
)
# NOTE: re-assign index for consistency for now. Need to be removed in the future.
loss[0], loss[3], loss[4] = det_loss[0], det_loss[1], det_loss[2]
batch_size = pred_kpts.shape[0]
imgsz = torch.tensor(preds["feats"][0].shape[2:], device=self.device, dtype=pred_kpts.dtype) * self.stride[0]
pred_kpts = pred_kpts.view(batch_size, -1, *self.kpt_shape) # (b, h*w, 17, 3)
if self.rle_loss and preds.get("kpts_sigma", None) is not None:
pred_sigma = preds["kpts_sigma"].permute(0, 2, 1).contiguous()
pred_sigma = pred_sigma.view(batch_size, -1, self.kpt_shape[0], 2) # (b, h*w, 17, 2)
pred_kpts = torch.cat([pred_kpts, pred_sigma], dim=-1) # (b, h*w, 17, 5)
pred_kpts = self.kpts_decode(anchor_points, pred_kpts)
# Keypoint loss
if fg_mask.sum():
keypoints = batch["keypoints"].to(self.device).float().clone()
keypoints[..., 0] *= imgsz[1]
keypoints[..., 1] *= imgsz[0]
keypoints_loss = self.calculate_keypoints_loss(
fg_mask,
target_gt_idx,
keypoints,
batch["batch_idx"].view(-1, 1),
stride_tensor,
target_bboxes,
pred_kpts,
)
loss[1] = keypoints_loss[0]
loss[2] = keypoints_loss[1]
if self.rle_loss is not None:
loss[5] = keypoints_loss[2]
loss[1] *= self.hyp.pose # pose gain
loss[2] *= self.hyp.kobj # kobj gain
if self.rle_loss is not None:
loss[5] *= self.hyp.rle # rle gain
return loss * batch_size, loss.detach() # loss(box, kpt_location, kpt_visibility, cls, dfl[, rle])
@staticmethod
def kpts_decode(anchor_points: torch.Tensor, pred_kpts: torch.Tensor) -> torch.Tensor:
y = pred_kpts.clone()
y[..., 0] += anchor_points[:, [0]]
y[..., 1] += anchor_points[:, [1]]
return y
def calculate_rle_loss(self, pred_kpt: torch.Tensor, gt_kpt: torch.Tensor, kpt_mask: torch.Tensor) -> torch.Tensor:
pred_kpt_visible = pred_kpt[kpt_mask]
gt_kpt_visible = gt_kpt[kpt_mask]
pred_coords = pred_kpt_visible[:, 0:2]
pred_sigma = pred_kpt_visible[:, -2:]
gt_coords = gt_kpt_visible[:, 0:2]
target_weights = self.target_weights.unsqueeze(0).repeat(kpt_mask.shape[0], 1)
target_weights = target_weights[kpt_mask]
pred_sigma = pred_sigma.sigmoid()
error = (pred_coords - gt_coords) / (pred_sigma + 1e-9)
# Filter out NaN and Inf values to prevent MultivariateNormal validation errors
valid_mask = ~(torch.isnan(error) | torch.isinf(error)).any(dim=-1)
if not valid_mask.any():
return torch.tensor(0.0, device=pred_kpt.device)
error = error[valid_mask]
error = error.clamp(-100, 100) # Prevent numerical instability
pred_sigma = pred_sigma[valid_mask]
target_weights = target_weights[valid_mask]
log_phi = self.flow_model.log_prob(error)
return self.rle_loss(pred_sigma, log_phi, error, target_weights)
def calculate_keypoints_loss(
self,
masks: torch.Tensor,
target_gt_idx: torch.Tensor,
keypoints: torch.Tensor,
batch_idx: torch.Tensor,
stride_tensor: torch.Tensor,
target_bboxes: torch.Tensor,
pred_kpts: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
# Select target keypoints using inherited helper method
selected_keypoints = self._select_target_keypoints(keypoints, batch_idx, target_gt_idx, masks)
# Divide coordinates by stride
selected_keypoints[..., :2] /= stride_tensor.view(1, -1, 1, 1)
kpts_loss = 0
kpts_obj_loss = 0
rle_loss = 0
if masks.any():
target_bboxes /= stride_tensor
gt_kpt = selected_keypoints[masks]
area = xyxy2xywh(target_bboxes[masks])[:, 2:].prod(1, keepdim=True)
pred_kpt = pred_kpts[masks]
kpt_mask = gt_kpt[..., 2] != 0 if gt_kpt.shape[-1] == 3 else torch.full_like(gt_kpt[..., 0], True)
kpts_loss = self.keypoint_loss(pred_kpt, gt_kpt, kpt_mask, area) # pose loss
if self.rle_loss is not None and (pred_kpt.shape[-1] == 4 or pred_kpt.shape[-1] == 5):
rle_loss = self.calculate_rle_loss(pred_kpt, gt_kpt, kpt_mask)
rle_loss = rle_loss.clamp(min=0)
if pred_kpt.shape[-1] == 3 or pred_kpt.shape[-1] == 5:
kpts_obj_loss = self.bce_pose(pred_kpt[..., 2], kpt_mask.float()) # keypoint obj loss
return kpts_loss, kpts_obj_loss, rle_loss
class v8ClassificationLoss:
def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
preds = preds[1] if isinstance(preds, (list, tuple)) else preds
loss = F.cross_entropy(preds, batch["cls"], reduction="mean")
return loss, loss.detach()
class v8OBBLoss(v8DetectionLoss):
def __init__(self, model, tal_topk=10, tal_topk2: int | None = None):
super().__init__(model, tal_topk=tal_topk)
self.assigner = RotatedTaskAlignedAssigner(
topk=tal_topk,
num_classes=self.nc,
alpha=0.5,
beta=6.0,
stride=self.stride.tolist(),
topk2=tal_topk2,
)
self.bbox_loss = RotatedBboxLoss(self.reg_max).to(self.device)
def preprocess(self, targets: torch.Tensor, batch_size: int, scale_tensor: torch.Tensor) -> torch.Tensor:
if targets.shape[0] == 0:
out = torch.zeros(batch_size, 0, 6, device=self.device)
else:
i = targets[:, 0] # image index
_, counts = i.unique(return_counts=True)
counts = counts.to(dtype=torch.int32)
out = torch.zeros(batch_size, counts.max(), 6, device=self.device)
for j in range(batch_size):
matches = i == j
if n := matches.sum():
bboxes = targets[matches, 2:]
bboxes[..., :4].mul_(scale_tensor)
out[j, :n] = torch.cat([targets[matches, 1:2], bboxes], dim=-1)
return out
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
loss = torch.zeros(4, device=self.device) # box, cls, dfl, angle
pred_distri, pred_scores, pred_angle = (
preds["boxes"].permute(0, 2, 1).contiguous(),
preds["scores"].permute(0, 2, 1).contiguous(),
preds["angle"].permute(0, 2, 1).contiguous(),
)
anchor_points, stride_tensor = make_anchors(preds["feats"], self.stride, 0.5)
batch_size = pred_angle.shape[0] # batch size
dtype = pred_scores.dtype
imgsz = torch.tensor(preds["feats"][0].shape[2:], device=self.device, dtype=dtype) * self.stride[0]
# targets
try:
batch_idx = batch["batch_idx"].view(-1, 1)
targets = torch.cat((batch_idx, batch["cls"].view(-1, 1), batch["bboxes"].view(-1, 5)), 1)
rw, rh = targets[:, 4] * float(imgsz[1]), targets[:, 5] * float(imgsz[0])
targets = targets[(rw >= 2) & (rh >= 2)] # filter rboxes of tiny size to stabilize training
targets = self.preprocess(targets.to(self.device), batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])
gt_labels, gt_bboxes = targets.split((1, 5), 2) # cls, xywhr
mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0.0)
except RuntimeError as e:
raise TypeError(
"ERROR ❌ OBB dataset incorrectly formatted or not a OBB dataset.\n"
"This error can occur when incorrectly training a 'OBB' model on a 'detect' dataset, "
"i.e. 'yolo train model=yolo26n-obb.pt data=dota8.yaml'.\nVerify your dataset is a "
"correctly formatted 'OBB' dataset using 'data=dota8.yaml' "
"as an example.\nSee https://docs.ultralytics.com/datasets/obb/ for help."
) from e
# Pboxes
pred_bboxes = self.bbox_decode(anchor_points, pred_distri, pred_angle) # xyxy, (b, h*w, 4)
bboxes_for_assigner = pred_bboxes.clone().detach()
# Only the first four elements need to be scaled
bboxes_for_assigner[..., :4] *= stride_tensor
_, target_bboxes, target_scores, fg_mask, _ = self.assigner(
pred_scores.detach().sigmoid(),
bboxes_for_assigner.type(gt_bboxes.dtype),
anchor_points * stride_tensor,
gt_labels,
gt_bboxes,
mask_gt,
)
target_scores_sum = max(target_scores.sum(), 1)
# Cls loss
# loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum # VFL way
loss[1] = self.bce(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum # BCE
# Bbox loss
if fg_mask.sum():
target_bboxes[..., :4] /= stride_tensor
loss[0], loss[2] = self.bbox_loss(
pred_distri,
pred_bboxes,
anchor_points,
target_bboxes,
target_scores,
target_scores_sum,
fg_mask,
imgsz,
stride_tensor,
)
weight = target_scores.sum(-1)[fg_mask]
loss[3] = self.calculate_angle_loss(
pred_bboxes, target_bboxes, fg_mask, weight, target_scores_sum
) # angle loss
else:
loss[0] += (pred_angle * 0).sum()
loss[0] *= self.hyp.box # box gain
loss[1] *= self.hyp.cls # cls gain
loss[2] *= self.hyp.dfl # dfl gain
loss[3] *= self.hyp.angle # angle gain
return loss * batch_size, loss.detach() # loss(box, cls, dfl, angle)
def bbox_decode(
self, anchor_points: torch.Tensor, pred_dist: torch.Tensor, pred_angle: torch.Tensor
) -> torch.Tensor:
if self.use_dfl:
b, a, c = pred_dist.shape # batch, anchors, channels
pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype))
return torch.cat((dist2rbox(pred_dist, pred_angle, anchor_points), pred_angle), dim=-1)
def calculate_angle_loss(self, pred_bboxes, target_bboxes, fg_mask, weight, target_scores_sum, lambda_val=3):
w_gt = target_bboxes[..., 2]
h_gt = target_bboxes[..., 3]
pred_theta = pred_bboxes[..., 4]
target_theta = target_bboxes[..., 4]
log_ar = torch.log((w_gt + 1e-9) / (h_gt + 1e-9))
scale_weight = torch.exp(-(log_ar**2) / (lambda_val**2))
delta_theta = pred_theta - target_theta
delta_theta_wrapped = delta_theta - torch.round(delta_theta / math.pi) * math.pi
ang_loss = torch.sin(2 * delta_theta_wrapped[fg_mask]) ** 2
ang_loss = scale_weight[fg_mask] * ang_loss
ang_loss = ang_loss * weight
return ang_loss.sum() / target_scores_sum
class E2EDetectLoss:
def __init__(self, model):
self.one2many = v8DetectionLoss(model, tal_topk=10)
self.one2one = v8DetectionLoss(model, tal_topk=1)
def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
preds = preds[1] if isinstance(preds, tuple) else preds
one2many = preds["one2many"]
loss_one2many = self.one2many(one2many, batch)
one2one = preds["one2one"]
loss_one2one = self.one2one(one2one, batch)
return loss_one2many[0] + loss_one2one[0], loss_one2many[1] + loss_one2one[1]
class E2ELoss:
def __init__(self, model, loss_fn=v8DetectionLoss):
self.one2many = loss_fn(model, tal_topk=10)
self.one2one = loss_fn(model, tal_topk=7, tal_topk2=1)
self.updates = 0
self.total = 1.0
# init gain
self.o2m = 0.8
self.o2o = self.total - self.o2m
self.o2m_copy = self.o2m
# final gain
self.final_o2m = 0.1
def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
preds = self.one2many.parse_output(preds)
one2many, one2one = preds["one2many"], preds["one2one"]
loss_one2many = self.one2many.loss(one2many, batch)
loss_one2one = self.one2one.loss(one2one, batch)
return loss_one2many[0] * self.o2m + loss_one2one[0] * self.o2o, loss_one2one[1]
def update(self) -> None:
self.updates += 1
self.o2m = self.decay(self.updates)
self.o2o = max(self.total - self.o2m, 0)
def decay(self, x) -> float:
return max(1 - x / max(self.one2one.hyp.epochs - 1, 1), 0) * (self.o2m_copy - self.final_o2m) + self.final_o2m
class TVPDetectLoss:
def __init__(self, model, tal_topk=10, tal_topk2: int | None = None):
self.vp_criterion = v8DetectionLoss(model, tal_topk, tal_topk2)
# NOTE: store following info as it's changeable in __call__
self.hyp = self.vp_criterion.hyp
self.ori_nc = self.vp_criterion.nc
self.ori_no = self.vp_criterion.no
self.ori_reg_max = self.vp_criterion.reg_max
def parse_output(self, preds) -> dict[str, torch.Tensor]:
return self.vp_criterion.parse_output(preds)
def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
return self.loss(self.parse_output(preds), batch)
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
if self.ori_nc == preds["scores"].shape[1]:
loss = torch.zeros(3, device=self.vp_criterion.device, requires_grad=True)
return loss, loss.detach()
preds["scores"] = self._get_vp_features(preds)
vp_loss = self.vp_criterion(preds, batch)
box_loss = vp_loss[0][1]
return box_loss, vp_loss[1]
def _get_vp_features(self, preds: dict[str, torch.Tensor]) -> list[torch.Tensor]:
scores = preds["scores"]
vnc = scores.shape[1]
self.vp_criterion.nc = vnc
self.vp_criterion.no = vnc + self.vp_criterion.reg_max * 4
self.vp_criterion.assigner.num_classes = vnc
return scores
class TVPSegmentLoss(TVPDetectLoss):
def __init__(self, model, tal_topk=10):
super().__init__(model)
self.vp_criterion = v8SegmentationLoss(model, tal_topk)
self.hyp = self.vp_criterion.hyp
def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
return self.loss(self.parse_output(preds), batch)
def loss(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
if self.ori_nc == preds["scores"].shape[1]:
loss = torch.zeros(4, device=self.vp_criterion.device, requires_grad=True)
return loss, loss.detach()
preds["scores"] = self._get_vp_features(preds)
vp_loss = self.vp_criterion(preds, batch)
cls_loss = vp_loss[0][2]
return cls_loss, vp_loss[1] | --- +++ @@ -19,13 +19,27 @@
class VarifocalLoss(nn.Module):
+ """Varifocal loss by Zhang et al.
+
+ Implements the Varifocal Loss function for addressing class imbalance in object detection by focusing on
+ hard-to-classify examples and balancing positive/negative samples.
+
+ Attributes:
+ gamma (float): The focusing parameter that controls how much the loss focuses on hard-to-classify examples.
+ alpha (float): The balancing factor used to address class imbalance.
+
+ References:
+ https://arxiv.org/abs/2008.13367
+ """
def __init__(self, gamma: float = 2.0, alpha: float = 0.75):
+ """Initialize the VarifocalLoss class with focusing and balancing parameters."""
super().__init__()
self.gamma = gamma
self.alpha = alpha
def forward(self, pred_score: torch.Tensor, gt_score: torch.Tensor, label: torch.Tensor) -> torch.Tensor:
+ """Compute varifocal loss between predictions and ground truth."""
weight = self.alpha * pred_score.sigmoid().pow(self.gamma) * (1 - label) + gt_score * label
with autocast(enabled=False):
loss = (
@@ -37,13 +51,24 @@
class FocalLoss(nn.Module):
+ """Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5).
+
+ Implements the Focal Loss function for addressing class imbalance by down-weighting easy examples and focusing on
+ hard negatives during training.
+
+ Attributes:
+ gamma (float): The focusing parameter that controls how much the loss focuses on hard-to-classify examples.
+ alpha (torch.Tensor): The balancing factor used to address class imbalance.
+ """
def __init__(self, gamma: float = 1.5, alpha: float = 0.25):
+ """Initialize FocalLoss class with focusing and balancing parameters."""
super().__init__()
self.gamma = gamma
self.alpha = torch.tensor(alpha)
def forward(self, pred: torch.Tensor, label: torch.Tensor) -> torch.Tensor:
+ """Calculate focal loss with modulating factors for class imbalance."""
loss = F.binary_cross_entropy_with_logits(pred, label, reduction="none")
# p_t = torch.exp(-loss)
# loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
@@ -61,12 +86,15 @@
class DFLoss(nn.Module):
+ """Criterion class for computing Distribution Focal Loss (DFL)."""
def __init__(self, reg_max: int = 16) -> None:
+ """Initialize the DFL module with regularization maximum."""
super().__init__()
self.reg_max = reg_max
def __call__(self, pred_dist: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
+ """Return sum of left and right DFL losses from https://ieeexplore.ieee.org/document/9792391."""
target = target.clamp_(0, self.reg_max - 1 - 0.01)
tl = target.long() # target left
tr = tl + 1 # target right
@@ -79,8 +107,10 @@
class BboxLoss(nn.Module):
+ """Criterion class for computing training losses for bounding boxes."""
def __init__(self, reg_max: int = 16):
+ """Initialize the BboxLoss module with regularization maximum and DFL settings."""
super().__init__()
self.dfl_loss = DFLoss(reg_max) if reg_max > 1 else None
@@ -96,6 +126,7 @@ imgsz: torch.Tensor,
stride: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
+ """Compute IoU and DFL losses for bounding boxes."""
weight = target_scores.sum(-1)[fg_mask].unsqueeze(-1)
iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, CIoU=True)
loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum
@@ -123,8 +154,26 @@
class RLELoss(nn.Module):
+ """Residual Log-Likelihood Estimation Loss.
+
+ Attributes:
+ size_average (bool): Option to average the loss by the batch_size.
+ use_target_weight (bool): Option to use weighted loss.
+ residual (bool): Option to add L1 loss and let the flow learn the residual error distribution.
+
+ References:
+ https://arxiv.org/abs/2107.11291
+ https://github.com/open-mmlab/mmpose/blob/main/mmpose/models/losses/regression_loss.py
+ """
def __init__(self, use_target_weight: bool = True, size_average: bool = True, residual: bool = True):
+ """Initialize RLELoss with target weight and residual options.
+
+ Args:
+ use_target_weight (bool): Whether to use target weights for loss calculation.
+ size_average (bool): Whether to average the loss over elements.
+ residual (bool): Whether to include residual log-likelihood term.
+ """
super().__init__()
self.size_average = size_average
self.use_target_weight = use_target_weight
@@ -133,6 +182,13 @@ def forward(
self, sigma: torch.Tensor, log_phi: torch.Tensor, error: torch.Tensor, target_weight: torch.Tensor = None
) -> torch.Tensor:
+ """
+ Args:
+ sigma (torch.Tensor): Output sigma, shape (N, D).
+ log_phi (torch.Tensor): Output log_phi, shape (N).
+ error (torch.Tensor): Error, shape (N, D).
+ target_weight (torch.Tensor): Weights across different joint types, shape (N).
+ """
log_sigma = torch.log(sigma)
loss = log_sigma - log_phi.unsqueeze(1)
@@ -152,8 +208,10 @@
class RotatedBboxLoss(BboxLoss):
+ """Criterion class for computing training losses for rotated bounding boxes."""
def __init__(self, reg_max: int):
+ """Initialize the RotatedBboxLoss module with regularization maximum and DFL settings."""
super().__init__(reg_max)
def forward(
@@ -168,6 +226,7 @@ imgsz: torch.Tensor,
stride: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
+ """Compute IoU and DFL losses for rotated bounding boxes."""
weight = target_scores.sum(-1)[fg_mask].unsqueeze(-1)
iou = probiou(pred_bboxes[fg_mask], target_bboxes[fg_mask])
loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum
@@ -196,13 +255,21 @@
class MultiChannelDiceLoss(nn.Module):
+ """Criterion class for computing multi-channel Dice losses."""
def __init__(self, smooth: float = 1e-6, reduction: str = "mean"):
+ """Initialize MultiChannelDiceLoss with smoothing and reduction options.
+
+ Args:
+ smooth (float): Smoothing factor to avoid division by zero.
+ reduction (str): Reduction method ('mean', 'sum', or 'none').
+ """
super().__init__()
self.smooth = smooth
self.reduction = reduction
def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
+ """Calculate multi-channel Dice loss between predictions and targets."""
assert pred.size() == target.size(), "the size of predict and target must be equal."
pred = pred.sigmoid()
@@ -221,8 +288,15 @@
class BCEDiceLoss(nn.Module):
+ """Criterion class for computing combined BCE and Dice losses."""
def __init__(self, weight_bce: float = 0.5, weight_dice: float = 0.5):
+ """Initialize BCEDiceLoss with BCE and Dice weight factors.
+
+ Args:
+ weight_bce (float): Weight factor for BCE loss component.
+ weight_dice (float): Weight factor for Dice loss component.
+ """
super().__init__()
self.weight_bce = weight_bce
self.weight_dice = weight_dice
@@ -230,6 +304,7 @@ self.dice = MultiChannelDiceLoss(smooth=1)
def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
+ """Calculate combined BCE and Dice loss between predictions and targets."""
_, _, mask_h, mask_w = pred.shape
if tuple(target.shape[-2:]) != (mask_h, mask_w): # downsample to the same size as pred
target = F.interpolate(target, (mask_h, mask_w), mode="nearest")
@@ -237,14 +312,17 @@
class KeypointLoss(nn.Module):
+ """Criterion class for computing keypoint losses."""
def __init__(self, sigmas: torch.Tensor) -> None:
+ """Initialize the KeypointLoss class with keypoint sigmas."""
super().__init__()
self.sigmas = sigmas
def forward(
self, pred_kpts: torch.Tensor, gt_kpts: torch.Tensor, kpt_mask: torch.Tensor, area: torch.Tensor
) -> torch.Tensor:
+ """Calculate keypoint loss factor and Euclidean distance loss for keypoints."""
d = (pred_kpts[..., 0] - gt_kpts[..., 0]).pow(2) + (pred_kpts[..., 1] - gt_kpts[..., 1]).pow(2)
kpt_loss_factor = kpt_mask.shape[1] / (torch.sum(kpt_mask != 0, dim=1) + 1e-9)
# e = d / (2 * (area * self.sigmas) ** 2 + 1e-9) # from formula
@@ -253,8 +331,10 @@
class v8DetectionLoss:
+ """Criterion class for computing training losses for YOLOv8 object detection."""
def __init__(self, model, tal_topk: int = 10, tal_topk2: int | None = None): # model must be de-paralleled
+ """Initialize v8DetectionLoss with model parameters and task-aligned assignment settings."""
device = next(model.parameters()).device # get model device
h = model.args # hyperparameters
@@ -281,6 +361,7 @@ self.proj = torch.arange(m.reg_max, dtype=torch.float, device=device)
def preprocess(self, targets: torch.Tensor, batch_size: int, scale_tensor: torch.Tensor) -> torch.Tensor:
+ """Preprocess targets by converting to tensor format and scaling coordinates."""
nl, ne = targets.shape
if nl == 0:
out = torch.zeros(batch_size, 0, ne - 1, device=self.device)
@@ -297,6 +378,7 @@ return out
def bbox_decode(self, anchor_points: torch.Tensor, pred_dist: torch.Tensor) -> torch.Tensor:
+ """Decode predicted object bounding box coordinates from anchor points and distribution."""
if self.use_dfl:
b, a, c = pred_dist.shape # batch, anchors, channels
pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype))
@@ -305,6 +387,9 @@ return dist2bbox(pred_dist, anchor_points, xywh=False)
def get_assigned_targets_and_loss(self, preds: dict[str, torch.Tensor], batch: dict[str, Any]) -> tuple:
+ """Calculate the sum of the loss for box, cls and dfl multiplied by batch size and return foreground mask and
+ target indices.
+ """
loss = torch.zeros(3, device=self.device) # box, cls, dfl
pred_distri, pred_scores = (
preds["boxes"].permute(0, 2, 1).contiguous(),
@@ -365,6 +450,7 @@ def parse_output(
self, preds: dict[str, torch.Tensor] | tuple[torch.Tensor, dict[str, torch.Tensor]]
) -> torch.Tensor:
+ """Parse model predictions to extract features."""
return preds[1] if isinstance(preds, tuple) else preds
def __call__(
@@ -372,22 +458,27 @@ preds: dict[str, torch.Tensor] | tuple[torch.Tensor, dict[str, torch.Tensor]],
batch: dict[str, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate the sum of the loss for box, cls and dfl multiplied by batch size."""
return self.loss(self.parse_output(preds), batch)
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate detection loss using assigned targets."""
batch_size = preds["boxes"].shape[0]
loss, loss_detach = self.get_assigned_targets_and_loss(preds, batch)[1:]
return loss * batch_size, loss_detach
class v8SegmentationLoss(v8DetectionLoss):
+ """Criterion class for computing training losses for YOLOv8 segmentation."""
def __init__(self, model, tal_topk: int = 10, tal_topk2: int | None = None): # model must be de-paralleled
+ """Initialize the v8SegmentationLoss class with model parameters and mask overlap setting."""
super().__init__(model, tal_topk, tal_topk2)
self.overlap = model.args.overlap_mask
self.bcedice_loss = BCEDiceLoss(weight_bce=0.5, weight_dice=0.5)
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate and return the combined loss for detection and segmentation."""
pred_masks, proto = preds["mask_coefficient"].permute(0, 2, 1).contiguous(), preds["proto"]
loss = torch.zeros(5, device=self.device) # box, seg, cls, dfl, semseg
if isinstance(proto, tuple) and len(proto) == 2:
@@ -450,6 +541,22 @@ def single_mask_loss(
gt_mask: torch.Tensor, pred: torch.Tensor, proto: torch.Tensor, xyxy: torch.Tensor, area: torch.Tensor
) -> torch.Tensor:
+ """Compute the instance segmentation loss for a single image.
+
+ Args:
+ gt_mask (torch.Tensor): Ground truth mask of shape (N, H, W), where N is the number of objects.
+ pred (torch.Tensor): Predicted mask coefficients of shape (N, 32).
+ proto (torch.Tensor): Prototype masks of shape (32, H, W).
+ xyxy (torch.Tensor): Ground truth bounding boxes in xyxy format, normalized to [0, 1], of shape (N, 4).
+ area (torch.Tensor): Area of each ground truth bounding box of shape (N,).
+
+ Returns:
+ (torch.Tensor): The calculated mask loss for a single image.
+
+ Notes:
+ The function uses the equation pred_mask = torch.einsum('in,nhw->ihw', pred, proto) to produce the
+ predicted masks from the prototype masks and predicted mask coefficients.
+ """
pred_mask = torch.einsum("in,nhw->ihw", pred, proto) # (n, 32) @ (32, 80, 80) -> (n, 80, 80)
loss = F.binary_cross_entropy_with_logits(pred_mask, gt_mask, reduction="none")
return (crop_mask(loss, xyxy).mean(dim=(1, 2)) / area).sum()
@@ -465,6 +572,26 @@ pred_masks: torch.Tensor,
imgsz: torch.Tensor,
) -> torch.Tensor:
+ """Calculate the loss for instance segmentation.
+
+ Args:
+ fg_mask (torch.Tensor): A binary tensor of shape (BS, N_anchors) indicating which anchors are positive.
+ masks (torch.Tensor): Ground truth masks of shape (BS, H, W) if `overlap` is False, otherwise (BS, ?, H, W).
+ target_gt_idx (torch.Tensor): Indexes of ground truth objects for each anchor of shape (BS, N_anchors).
+ target_bboxes (torch.Tensor): Ground truth bounding boxes for each anchor of shape (BS, N_anchors, 4).
+ batch_idx (torch.Tensor): Batch indices of shape (N_labels_in_batch, 1).
+ proto (torch.Tensor): Prototype masks of shape (BS, 32, H, W).
+ pred_masks (torch.Tensor): Predicted masks for each anchor of shape (BS, N_anchors, 32).
+ imgsz (torch.Tensor): Size of the input image as a tensor of shape (2), i.e., (H, W).
+
+ Returns:
+ (torch.Tensor): The calculated loss for instance segmentation.
+
+ Notes:
+ The batch loss can be computed for improved speed at higher memory usage.
+ For example, pred_mask can be computed as follows:
+ pred_mask = torch.einsum('in,nhw->ihw', pred, proto) # (i, 32) @ (32, 160, 160) -> (i, 160, 160)
+ """
_, _, mask_h, mask_w = proto.shape
loss = 0
@@ -499,8 +626,10 @@
class v8PoseLoss(v8DetectionLoss):
+ """Criterion class for computing training losses for YOLOv8 pose estimation."""
def __init__(self, model, tal_topk: int = 10, tal_topk2: int = 10): # model must be de-paralleled
+ """Initialize v8PoseLoss with model parameters and keypoint-specific loss functions."""
super().__init__(model, tal_topk, tal_topk2)
self.kpt_shape = model.model[-1].kpt_shape
self.bce_pose = nn.BCEWithLogitsLoss()
@@ -510,6 +639,7 @@ self.keypoint_loss = KeypointLoss(sigmas=sigmas)
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate the total loss and detach it for pose estimation."""
pred_kpts = preds["kpts"].permute(0, 2, 1).contiguous()
loss = torch.zeros(5, device=self.device) # box, kpt_location, kpt_visibility, cls, dfl
(fg_mask, target_gt_idx, target_bboxes, anchor_points, stride_tensor), det_loss, _ = (
@@ -547,6 +677,7 @@
@staticmethod
def kpts_decode(anchor_points: torch.Tensor, pred_kpts: torch.Tensor) -> torch.Tensor:
+ """Decode predicted keypoints to image coordinates."""
y = pred_kpts.clone()
y[..., :2] *= 2.0
y[..., 0] += anchor_points[:, [0]] - 0.5
@@ -560,6 +691,17 @@ target_gt_idx: torch.Tensor,
masks: torch.Tensor,
) -> torch.Tensor:
+ """Select target keypoints for each anchor based on batch index and target ground truth index.
+
+ Args:
+ keypoints (torch.Tensor): Ground truth keypoints, shape (N_kpts_in_batch, N_kpts_per_object, kpts_dim).
+ batch_idx (torch.Tensor): Batch index tensor for keypoints, shape (N_kpts_in_batch, 1).
+ target_gt_idx (torch.Tensor): Index tensor mapping anchors to ground truth objects, shape (BS, N_anchors).
+ masks (torch.Tensor): Binary mask tensor indicating object presence, shape (BS, N_anchors).
+
+ Returns:
+ (torch.Tensor): Selected keypoints tensor, shape (BS, N_anchors, N_kpts_per_object, kpts_dim).
+ """
batch_idx = batch_idx.flatten()
batch_size = len(masks)
@@ -597,6 +739,25 @@ target_bboxes: torch.Tensor,
pred_kpts: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate the keypoints loss for the model.
+
+ This function calculates the keypoints loss and keypoints object loss for a given batch. The keypoints loss is
+ based on the difference between the predicted keypoints and ground truth keypoints. The keypoints object loss is
+ a binary classification loss that classifies whether a keypoint is present or not.
+
+ Args:
+ masks (torch.Tensor): Binary mask tensor indicating object presence, shape (BS, N_anchors).
+ target_gt_idx (torch.Tensor): Index tensor mapping anchors to ground truth objects, shape (BS, N_anchors).
+ keypoints (torch.Tensor): Ground truth keypoints, shape (N_kpts_in_batch, N_kpts_per_object, kpts_dim).
+ batch_idx (torch.Tensor): Batch index tensor for keypoints, shape (N_kpts_in_batch, 1).
+ stride_tensor (torch.Tensor): Stride tensor for anchors, shape (N_anchors, 1).
+ target_bboxes (torch.Tensor): Ground truth boxes in (x1, y1, x2, y2) format, shape (BS, N_anchors, 4).
+ pred_kpts (torch.Tensor): Predicted keypoints, shape (BS, N_anchors, N_kpts_per_object, kpts_dim).
+
+ Returns:
+ kpts_loss (torch.Tensor): The keypoints loss.
+ kpts_obj_loss (torch.Tensor): The keypoints object loss.
+ """
# Select target keypoints using helper method
selected_keypoints = self._select_target_keypoints(keypoints, batch_idx, target_gt_idx, masks)
@@ -621,8 +782,10 @@
class PoseLoss26(v8PoseLoss):
+ """Criterion class for computing training losses for YOLOv8 pose estimation with RLE loss support."""
def __init__(self, model, tal_topk: int = 10, tal_topk2: int | None = None): # model must be de-paralleled
+ """Initialize PoseLoss26 with model parameters and keypoint-specific loss functions including RLE loss."""
super().__init__(model, tal_topk, tal_topk2)
is_pose = self.kpt_shape == [17, 3]
nkpt = self.kpt_shape[0] # number of keypoints
@@ -635,6 +798,7 @@ )
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate the total loss and detach it for pose estimation."""
pred_kpts = preds["kpts"].permute(0, 2, 1).contiguous()
loss = torch.zeros(
6 if self.rle_loss else 5, device=self.device
@@ -686,12 +850,23 @@
@staticmethod
def kpts_decode(anchor_points: torch.Tensor, pred_kpts: torch.Tensor) -> torch.Tensor:
+ """Decode predicted keypoints to image coordinates."""
y = pred_kpts.clone()
y[..., 0] += anchor_points[:, [0]]
y[..., 1] += anchor_points[:, [1]]
return y
def calculate_rle_loss(self, pred_kpt: torch.Tensor, gt_kpt: torch.Tensor, kpt_mask: torch.Tensor) -> torch.Tensor:
+ """Calculate the RLE (Residual Log-likelihood Estimation) loss for keypoints.
+
+ Args:
+ pred_kpt (torch.Tensor): Predicted kpts with sigma, shape (N, num_keypoints, kpts_dim) where kpts_dim >= 4.
+ gt_kpt (torch.Tensor): Ground truth keypoints, shape (N, num_keypoints, kpts_dim).
+ kpt_mask (torch.Tensor): Mask for valid keypoints, shape (N, num_keypoints).
+
+ Returns:
+ (torch.Tensor): The RLE loss.
+ """
pred_kpt_visible = pred_kpt[kpt_mask]
gt_kpt_visible = gt_kpt[kpt_mask]
pred_coords = pred_kpt_visible[:, 0:2]
@@ -728,6 +903,26 @@ target_bboxes: torch.Tensor,
pred_kpts: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Calculate the keypoints loss for the model.
+
+ This function calculates the keypoints loss and keypoints object loss for a given batch. The keypoints loss is
+ based on the difference between the predicted keypoints and ground truth keypoints. The keypoints object loss is
+ a binary classification loss that classifies whether a keypoint is present or not.
+
+ Args:
+ masks (torch.Tensor): Binary mask tensor indicating object presence, shape (BS, N_anchors).
+ target_gt_idx (torch.Tensor): Index tensor mapping anchors to ground truth objects, shape (BS, N_anchors).
+ keypoints (torch.Tensor): Ground truth keypoints, shape (N_kpts_in_batch, N_kpts_per_object, kpts_dim).
+ batch_idx (torch.Tensor): Batch index tensor for keypoints, shape (N_kpts_in_batch, 1).
+ stride_tensor (torch.Tensor): Stride tensor for anchors, shape (N_anchors, 1).
+ target_bboxes (torch.Tensor): Ground truth boxes in (x1, y1, x2, y2) format, shape (BS, N_anchors, 4).
+ pred_kpts (torch.Tensor): Predicted keypoints, shape (BS, N_anchors, N_kpts_per_object, kpts_dim).
+
+ Returns:
+ kpts_loss (torch.Tensor): The keypoints loss.
+ kpts_obj_loss (torch.Tensor): The keypoints object loss.
+ rle_loss (torch.Tensor): The RLE loss.
+ """
# Select target keypoints using inherited helper method
selected_keypoints = self._select_target_keypoints(keypoints, batch_idx, target_gt_idx, masks)
@@ -756,16 +951,20 @@
class v8ClassificationLoss:
+ """Criterion class for computing training losses for classification."""
def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Compute the classification loss between predictions and true labels."""
preds = preds[1] if isinstance(preds, (list, tuple)) else preds
loss = F.cross_entropy(preds, batch["cls"], reduction="mean")
return loss, loss.detach()
class v8OBBLoss(v8DetectionLoss):
+ """Calculates losses for object detection, classification, and box distribution in rotated YOLO models."""
def __init__(self, model, tal_topk=10, tal_topk2: int | None = None):
+ """Initialize v8OBBLoss with model, assigner, and rotated bbox loss; model must be de-paralleled."""
super().__init__(model, tal_topk=tal_topk)
self.assigner = RotatedTaskAlignedAssigner(
topk=tal_topk,
@@ -778,6 +977,7 @@ self.bbox_loss = RotatedBboxLoss(self.reg_max).to(self.device)
def preprocess(self, targets: torch.Tensor, batch_size: int, scale_tensor: torch.Tensor) -> torch.Tensor:
+ """Preprocess targets for oriented bounding box detection."""
if targets.shape[0] == 0:
out = torch.zeros(batch_size, 0, 6, device=self.device)
else:
@@ -794,6 +994,7 @@ return out
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate and return the loss for oriented bounding box detection."""
loss = torch.zeros(4, device=self.device) # box, cls, dfl, angle
pred_distri, pred_scores, pred_angle = (
preds["boxes"].permute(0, 2, 1).contiguous(),
@@ -876,12 +1077,35 @@ def bbox_decode(
self, anchor_points: torch.Tensor, pred_dist: torch.Tensor, pred_angle: torch.Tensor
) -> torch.Tensor:
+ """Decode predicted object bounding box coordinates from anchor points and distribution.
+
+ Args:
+ anchor_points (torch.Tensor): Anchor points, (h*w, 2).
+ pred_dist (torch.Tensor): Predicted rotated distance, (bs, h*w, 4).
+ pred_angle (torch.Tensor): Predicted angle, (bs, h*w, 1).
+
+ Returns:
+ (torch.Tensor): Predicted rotated bounding boxes with angles, (bs, h*w, 5).
+ """
if self.use_dfl:
b, a, c = pred_dist.shape # batch, anchors, channels
pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype))
return torch.cat((dist2rbox(pred_dist, pred_angle, anchor_points), pred_angle), dim=-1)
def calculate_angle_loss(self, pred_bboxes, target_bboxes, fg_mask, weight, target_scores_sum, lambda_val=3):
+ """Calculate oriented angle loss.
+
+ Args:
+ pred_bboxes (torch.Tensor): Predicted bounding boxes with shape [N, 5] (x, y, w, h, theta).
+ target_bboxes (torch.Tensor): Target bounding boxes with shape [N, 5] (x, y, w, h, theta).
+ fg_mask (torch.Tensor): Foreground mask indicating valid predictions.
+ weight (torch.Tensor): Loss weights for each prediction.
+ target_scores_sum (torch.Tensor): Sum of target scores for normalization.
+ lambda_val (int): Controls the sensitivity to aspect ratio.
+
+ Returns:
+ (torch.Tensor): The calculated angle loss.
+ """
w_gt = target_bboxes[..., 2]
h_gt = target_bboxes[..., 3]
pred_theta = pred_bboxes[..., 4]
@@ -901,12 +1125,15 @@
class E2EDetectLoss:
+ """Criterion class for computing training losses for end-to-end detection."""
def __init__(self, model):
+ """Initialize E2EDetectLoss with one-to-many and one-to-one detection losses using the provided model."""
self.one2many = v8DetectionLoss(model, tal_topk=10)
self.one2one = v8DetectionLoss(model, tal_topk=1)
def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate the sum of the loss for box, cls and dfl multiplied by batch size."""
preds = preds[1] if isinstance(preds, tuple) else preds
one2many = preds["one2many"]
loss_one2many = self.one2many(one2many, batch)
@@ -916,8 +1143,10 @@
class E2ELoss:
+ """Criterion class for computing training losses for end-to-end detection."""
def __init__(self, model, loss_fn=v8DetectionLoss):
+ """Initialize E2ELoss with one-to-many and one-to-one detection losses using the provided model."""
self.one2many = loss_fn(model, tal_topk=10)
self.one2one = loss_fn(model, tal_topk=7, tal_topk2=1)
self.updates = 0
@@ -930,6 +1159,7 @@ self.final_o2m = 0.1
def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate the sum of the loss for box, cls and dfl multiplied by batch size."""
preds = self.one2many.parse_output(preds)
one2many, one2one = preds["one2many"], preds["one2one"]
loss_one2many = self.one2many.loss(one2many, batch)
@@ -937,17 +1167,21 @@ return loss_one2many[0] * self.o2m + loss_one2one[0] * self.o2o, loss_one2one[1]
def update(self) -> None:
+ """Update the weights for one-to-many and one-to-one losses based on the decay schedule."""
self.updates += 1
self.o2m = self.decay(self.updates)
self.o2o = max(self.total - self.o2m, 0)
def decay(self, x) -> float:
+ """Calculate the decayed weight for one-to-many loss based on the current update step."""
return max(1 - x / max(self.one2one.hyp.epochs - 1, 1), 0) * (self.o2m_copy - self.final_o2m) + self.final_o2m
class TVPDetectLoss:
+ """Criterion class for computing training losses for text-visual prompt detection."""
def __init__(self, model, tal_topk=10, tal_topk2: int | None = None):
+ """Initialize TVPDetectLoss with task-prompt and visual-prompt criteria using the provided model."""
self.vp_criterion = v8DetectionLoss(model, tal_topk, tal_topk2)
# NOTE: store following info as it's changeable in __call__
self.hyp = self.vp_criterion.hyp
@@ -956,12 +1190,15 @@ self.ori_reg_max = self.vp_criterion.reg_max
def parse_output(self, preds) -> dict[str, torch.Tensor]:
+ """Parse model predictions to extract features."""
return self.vp_criterion.parse_output(preds)
def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate the loss for text-visual prompt detection."""
return self.loss(self.parse_output(preds), batch)
def loss(self, preds: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate the loss for text-visual prompt detection."""
if self.ori_nc == preds["scores"].shape[1]:
loss = torch.zeros(3, device=self.vp_criterion.device, requires_grad=True)
return loss, loss.detach()
@@ -972,6 +1209,7 @@ return box_loss, vp_loss[1]
def _get_vp_features(self, preds: dict[str, torch.Tensor]) -> list[torch.Tensor]:
+ """Extract visual-prompt features from the model output."""
scores = preds["scores"]
vnc = scores.shape[1]
@@ -982,16 +1220,20 @@
class TVPSegmentLoss(TVPDetectLoss):
+ """Criterion class for computing training losses for text-visual prompt segmentation."""
def __init__(self, model, tal_topk=10):
+ """Initialize TVPSegmentLoss with task-prompt and visual-prompt criteria using the provided model."""
super().__init__(model)
self.vp_criterion = v8SegmentationLoss(model, tal_topk)
self.hyp = self.vp_criterion.hyp
def __call__(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate the loss for text-visual prompt segmentation."""
return self.loss(self.parse_output(preds), batch)
def loss(self, preds: Any, batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Calculate the loss for text-visual prompt segmentation."""
if self.ori_nc == preds["scores"].shape[1]:
loss = torch.zeros(4, device=self.vp_criterion.device, requires_grad=True)
return loss, loss.detach()
@@ -999,4 +1241,4 @@ preds["scores"] = self._get_vp_features(preds)
vp_loss = self.vp_criterion(preds, batch)
cls_loss = vp_loss[0][2]
- return cls_loss, vp_loss[1]+ return cls_loss, vp_loss[1]
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/loss.py |
Improve documentation using docstrings |
import os.path
import socket # noqa: F401
import typing
import warnings
from urllib3.exceptions import (
ClosedPoolError,
ConnectTimeoutError,
LocationValueError,
MaxRetryError,
NewConnectionError,
ProtocolError,
ReadTimeoutError,
ResponseError,
)
from urllib3.exceptions import HTTPError as _HTTPError
from urllib3.exceptions import InvalidHeader as _InvalidHeader
from urllib3.exceptions import ProxyError as _ProxyError
from urllib3.exceptions import SSLError as _SSLError
from urllib3.poolmanager import PoolManager, proxy_from_url
from urllib3.util import Timeout as TimeoutSauce
from urllib3.util import parse_url
from urllib3.util.retry import Retry
from .auth import _basic_auth_str
from .compat import basestring, urlparse
from .cookies import extract_cookies_to_jar
from .exceptions import (
ConnectionError,
ConnectTimeout,
InvalidHeader,
InvalidProxyURL,
InvalidSchema,
InvalidURL,
ProxyError,
ReadTimeout,
RetryError,
SSLError,
)
from .models import Response
from .structures import CaseInsensitiveDict
from .utils import (
DEFAULT_CA_BUNDLE_PATH,
extract_zipped_paths,
get_auth_from_url,
get_encoding_from_headers,
prepend_scheme_if_needed,
select_proxy,
urldefragauth,
)
try:
from urllib3.contrib.socks import SOCKSProxyManager
except ImportError:
def SOCKSProxyManager(*args, **kwargs):
raise InvalidSchema("Missing dependencies for SOCKS support.")
if typing.TYPE_CHECKING:
from .models import PreparedRequest
DEFAULT_POOLBLOCK = False
DEFAULT_POOLSIZE = 10
DEFAULT_RETRIES = 0
DEFAULT_POOL_TIMEOUT = None
def _urllib3_request_context(
request: "PreparedRequest",
verify: "bool | str | None",
client_cert: "tuple[str, str] | str | None",
poolmanager: "PoolManager",
) -> "(dict[str, typing.Any], dict[str, typing.Any])":
host_params = {}
pool_kwargs = {}
parsed_request_url = urlparse(request.url)
scheme = parsed_request_url.scheme.lower()
port = parsed_request_url.port
cert_reqs = "CERT_REQUIRED"
if verify is False:
cert_reqs = "CERT_NONE"
elif isinstance(verify, str):
if not os.path.isdir(verify):
pool_kwargs["ca_certs"] = verify
else:
pool_kwargs["ca_cert_dir"] = verify
pool_kwargs["cert_reqs"] = cert_reqs
if client_cert is not None:
if isinstance(client_cert, tuple) and len(client_cert) == 2:
pool_kwargs["cert_file"] = client_cert[0]
pool_kwargs["key_file"] = client_cert[1]
else:
# According to our docs, we allow users to specify just the client
# cert path
pool_kwargs["cert_file"] = client_cert
host_params = {
"scheme": scheme,
"host": parsed_request_url.hostname,
"port": port,
}
return host_params, pool_kwargs
class BaseAdapter:
def __init__(self):
super().__init__()
def send(
self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
):
raise NotImplementedError
def close(self):
raise NotImplementedError
class HTTPAdapter(BaseAdapter):
__attrs__ = [
"max_retries",
"config",
"_pool_connections",
"_pool_maxsize",
"_pool_block",
]
def __init__(
self,
pool_connections=DEFAULT_POOLSIZE,
pool_maxsize=DEFAULT_POOLSIZE,
max_retries=DEFAULT_RETRIES,
pool_block=DEFAULT_POOLBLOCK,
):
if max_retries == DEFAULT_RETRIES:
self.max_retries = Retry(0, read=False)
else:
self.max_retries = Retry.from_int(max_retries)
self.config = {}
self.proxy_manager = {}
super().__init__()
self._pool_connections = pool_connections
self._pool_maxsize = pool_maxsize
self._pool_block = pool_block
self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
def __getstate__(self):
return {attr: getattr(self, attr, None) for attr in self.__attrs__}
def __setstate__(self, state):
# Can't handle by adding 'proxy_manager' to self.__attrs__ because
# self.poolmanager uses a lambda function, which isn't pickleable.
self.proxy_manager = {}
self.config = {}
for attr, value in state.items():
setattr(self, attr, value)
self.init_poolmanager(
self._pool_connections, self._pool_maxsize, block=self._pool_block
)
def init_poolmanager(
self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs
):
# save these values for pickling
self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block
self.poolmanager = PoolManager(
num_pools=connections,
maxsize=maxsize,
block=block,
**pool_kwargs,
)
def proxy_manager_for(self, proxy, **proxy_kwargs):
if proxy in self.proxy_manager:
manager = self.proxy_manager[proxy]
elif proxy.lower().startswith("socks"):
username, password = get_auth_from_url(proxy)
manager = self.proxy_manager[proxy] = SOCKSProxyManager(
proxy,
username=username,
password=password,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs,
)
else:
proxy_headers = self.proxy_headers(proxy)
manager = self.proxy_manager[proxy] = proxy_from_url(
proxy,
proxy_headers=proxy_headers,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs,
)
return manager
def cert_verify(self, conn, url, verify, cert):
if url.lower().startswith("https") and verify:
cert_loc = None
# Allow self-specified cert location.
if verify is not True:
cert_loc = verify
if not cert_loc:
cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)
if not cert_loc or not os.path.exists(cert_loc):
raise OSError(
f"Could not find a suitable TLS CA certificate bundle, "
f"invalid path: {cert_loc}"
)
conn.cert_reqs = "CERT_REQUIRED"
if not os.path.isdir(cert_loc):
conn.ca_certs = cert_loc
else:
conn.ca_cert_dir = cert_loc
else:
conn.cert_reqs = "CERT_NONE"
conn.ca_certs = None
conn.ca_cert_dir = None
if cert:
if not isinstance(cert, basestring):
conn.cert_file = cert[0]
conn.key_file = cert[1]
else:
conn.cert_file = cert
conn.key_file = None
if conn.cert_file and not os.path.exists(conn.cert_file):
raise OSError(
f"Could not find the TLS certificate file, "
f"invalid path: {conn.cert_file}"
)
if conn.key_file and not os.path.exists(conn.key_file):
raise OSError(
f"Could not find the TLS key file, invalid path: {conn.key_file}"
)
def build_response(self, req, resp):
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
response.status_code = getattr(resp, "status", None)
# Make headers case-insensitive.
response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))
# Set encoding.
response.encoding = get_encoding_from_headers(response.headers)
response.raw = resp
response.reason = response.raw.reason
if isinstance(req.url, bytes):
response.url = req.url.decode("utf-8")
else:
response.url = req.url
# Add new cookies from the server.
extract_cookies_to_jar(response.cookies, req, resp)
# Give the Response some context.
response.request = req
response.connection = self
return response
def build_connection_pool_key_attributes(self, request, verify, cert=None):
return _urllib3_request_context(request, verify, cert, self.poolmanager)
def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):
proxy = select_proxy(request.url, proxies)
try:
host_params, pool_kwargs = self.build_connection_pool_key_attributes(
request,
verify,
cert,
)
except ValueError as e:
raise InvalidURL(e, request=request)
if proxy:
proxy = prepend_scheme_if_needed(proxy, "http")
proxy_url = parse_url(proxy)
if not proxy_url.host:
raise InvalidProxyURL(
"Please check proxy URL. It is malformed "
"and could be missing the host."
)
proxy_manager = self.proxy_manager_for(proxy)
conn = proxy_manager.connection_from_host(
**host_params, pool_kwargs=pool_kwargs
)
else:
# Only scheme should be lower case
conn = self.poolmanager.connection_from_host(
**host_params, pool_kwargs=pool_kwargs
)
return conn
def get_connection(self, url, proxies=None):
warnings.warn(
(
"`get_connection` has been deprecated in favor of "
"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses "
"will need to migrate for Requests>=2.32.2. Please see "
"https://github.com/psf/requests/pull/6710 for more details."
),
DeprecationWarning,
)
proxy = select_proxy(url, proxies)
if proxy:
proxy = prepend_scheme_if_needed(proxy, "http")
proxy_url = parse_url(proxy)
if not proxy_url.host:
raise InvalidProxyURL(
"Please check proxy URL. It is malformed "
"and could be missing the host."
)
proxy_manager = self.proxy_manager_for(proxy)
conn = proxy_manager.connection_from_url(url)
else:
# Only scheme should be lower case
parsed = urlparse(url)
url = parsed.geturl()
conn = self.poolmanager.connection_from_url(url)
return conn
def close(self):
self.poolmanager.clear()
for proxy in self.proxy_manager.values():
proxy.clear()
def request_url(self, request, proxies):
proxy = select_proxy(request.url, proxies)
scheme = urlparse(request.url).scheme
is_proxied_http_request = proxy and scheme != "https"
using_socks_proxy = False
if proxy:
proxy_scheme = urlparse(proxy).scheme.lower()
using_socks_proxy = proxy_scheme.startswith("socks")
url = request.path_url
if url.startswith("//"): # Don't confuse urllib3
url = f"/{url.lstrip('/')}"
if is_proxied_http_request and not using_socks_proxy:
url = urldefragauth(request.url)
return url
def add_headers(self, request, **kwargs):
pass
def proxy_headers(self, proxy):
headers = {}
username, password = get_auth_from_url(proxy)
if username:
headers["Proxy-Authorization"] = _basic_auth_str(username, password)
return headers
def send(
self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
):
try:
conn = self.get_connection_with_tls_context(
request, verify, proxies=proxies, cert=cert
)
except LocationValueError as e:
raise InvalidURL(e, request=request)
self.cert_verify(conn, request.url, verify, cert)
url = self.request_url(request, proxies)
self.add_headers(
request,
stream=stream,
timeout=timeout,
verify=verify,
cert=cert,
proxies=proxies,
)
chunked = not (request.body is None or "Content-Length" in request.headers)
if isinstance(timeout, tuple):
try:
connect, read = timeout
timeout = TimeoutSauce(connect=connect, read=read)
except ValueError:
raise ValueError(
f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, "
f"or a single float to set both timeouts to the same value."
)
elif isinstance(timeout, TimeoutSauce):
pass
else:
timeout = TimeoutSauce(connect=timeout, read=timeout)
try:
resp = conn.urlopen(
method=request.method,
url=url,
body=request.body,
headers=request.headers,
redirect=False,
assert_same_host=False,
preload_content=False,
decode_content=False,
retries=self.max_retries,
timeout=timeout,
chunked=chunked,
)
except (ProtocolError, OSError) as err:
raise ConnectionError(err, request=request)
except MaxRetryError as e:
if isinstance(e.reason, ConnectTimeoutError):
# TODO: Remove this in 3.0.0: see #2811
if not isinstance(e.reason, NewConnectionError):
raise ConnectTimeout(e, request=request)
if isinstance(e.reason, ResponseError):
raise RetryError(e, request=request)
if isinstance(e.reason, _ProxyError):
raise ProxyError(e, request=request)
if isinstance(e.reason, _SSLError):
# This branch is for urllib3 v1.22 and later.
raise SSLError(e, request=request)
raise ConnectionError(e, request=request)
except ClosedPoolError as e:
raise ConnectionError(e, request=request)
except _ProxyError as e:
raise ProxyError(e)
except (_SSLError, _HTTPError) as e:
if isinstance(e, _SSLError):
# This branch is for urllib3 versions earlier than v1.22
raise SSLError(e, request=request)
elif isinstance(e, ReadTimeoutError):
raise ReadTimeout(e, request=request)
elif isinstance(e, _InvalidHeader):
raise InvalidHeader(e, request=request)
else:
raise
return self.build_response(request, resp) | --- +++ @@ -1,3 +1,10 @@+"""
+requests.adapters
+~~~~~~~~~~~~~~~~~
+
+This module contains the transport adapters that Requests uses to define
+and maintain connections.
+"""
import os.path
import socket # noqa: F401
@@ -106,6 +113,7 @@
class BaseAdapter:
+ """The Base Transport Adapter"""
def __init__(self):
super().__init__()
@@ -113,13 +121,53 @@ def send(
self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
):
+ """Sends PreparedRequest object. Returns Response object.
+
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
+ :param stream: (optional) Whether to stream the request content.
+ :param timeout: (optional) How long to wait for the server to send
+ data before giving up, as a float, or a :ref:`(connect timeout,
+ read timeout) <timeouts>` tuple.
+ :type timeout: float or tuple
+ :param verify: (optional) Either a boolean, in which case it controls whether we verify
+ the server's TLS certificate, or a string, in which case it must be a path
+ to a CA bundle to use
+ :param cert: (optional) Any user-provided SSL certificate to be trusted.
+ :param proxies: (optional) The proxies dictionary to apply to the request.
+ """
raise NotImplementedError
def close(self):
+ """Cleans up adapter specific items."""
raise NotImplementedError
class HTTPAdapter(BaseAdapter):
+ """The built-in HTTP Adapter for urllib3.
+
+ Provides a general-case interface for Requests sessions to contact HTTP and
+ HTTPS urls by implementing the Transport Adapter interface. This class will
+ usually be created by the :class:`Session <Session>` class under the
+ covers.
+
+ :param pool_connections: The number of urllib3 connection pools to cache.
+ :param pool_maxsize: The maximum number of connections to save in the pool.
+ :param max_retries: The maximum number of retries each connection
+ should attempt. Note, this applies only to failed DNS lookups, socket
+ connections and connection timeouts, never to requests where data has
+ made it to the server. By default, Requests does not retry failed
+ connections. If you need granular control over the conditions under
+ which we retry a request, import urllib3's ``Retry`` class and pass
+ that instead.
+ :param pool_block: Whether the connection pool should block for connections.
+
+ Usage::
+
+ >>> import requests
+ >>> s = requests.Session()
+ >>> a = requests.adapters.HTTPAdapter(max_retries=3)
+ >>> s.mount('http://', a)
+ """
__attrs__ = [
"max_retries",
@@ -170,6 +218,17 @@ def init_poolmanager(
self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs
):
+ """Initializes a urllib3 PoolManager.
+
+ This method should not be called from user code, and is only
+ exposed for use when subclassing the
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
+
+ :param connections: The number of urllib3 connection pools to cache.
+ :param maxsize: The maximum number of connections to save in the pool.
+ :param block: Block when no free connections are available.
+ :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
+ """
# save these values for pickling
self._pool_connections = connections
self._pool_maxsize = maxsize
@@ -183,6 +242,17 @@ )
def proxy_manager_for(self, proxy, **proxy_kwargs):
+ """Return urllib3 ProxyManager for the given proxy.
+
+ This method should not be called from user code, and is only
+ exposed for use when subclassing the
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
+
+ :param proxy: The proxy to return a urllib3 ProxyManager for.
+ :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
+ :returns: ProxyManager
+ :rtype: urllib3.ProxyManager
+ """
if proxy in self.proxy_manager:
manager = self.proxy_manager[proxy]
elif proxy.lower().startswith("socks"):
@@ -210,6 +280,17 @@ return manager
def cert_verify(self, conn, url, verify, cert):
+ """Verify a SSL certificate. This method should not be called from user
+ code, and is only exposed for use when subclassing the
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
+
+ :param conn: The urllib3 connection object associated with the cert.
+ :param url: The requested URL.
+ :param verify: Either a boolean, in which case it controls whether we verify
+ the server's TLS certificate, or a string, in which case it must be a path
+ to a CA bundle to use
+ :param cert: The SSL certificate to verify.
+ """
if url.lower().startswith("https") and verify:
cert_loc = None
@@ -255,6 +336,15 @@ )
def build_response(self, req, resp):
+ """Builds a :class:`Response <requests.Response>` object from a urllib3
+ response. This should not be called from user code, and is only exposed
+ for use when subclassing the
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
+
+ :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
+ :param resp: The urllib3 response object.
+ :rtype: requests.Response
+ """
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
@@ -283,9 +373,75 @@ return response
def build_connection_pool_key_attributes(self, request, verify, cert=None):
+ """Build the PoolKey attributes used by urllib3 to return a connection.
+
+ This looks at the PreparedRequest, the user-specified verify value,
+ and the value of the cert parameter to determine what PoolKey values
+ to use to select a connection from a given urllib3 Connection Pool.
+
+ The SSL related pool key arguments are not consistently set. As of
+ this writing, use the following to determine what keys may be in that
+ dictionary:
+
+ * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the
+ default Requests SSL Context
+ * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but
+ ``"cert_reqs"`` will be set
+ * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)
+ ``"ca_certs"`` will be set if the string is not a directory recognized
+ by :py:func:`os.path.isdir`, otherwise ``"ca_cert_dir"`` will be
+ set.
+ * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If
+ ``"cert"`` is a tuple with a second item, ``"key_file"`` will also
+ be present
+
+ To override these settings, one may subclass this class, call this
+ method and use the above logic to change parameters as desired. For
+ example, if one wishes to use a custom :py:class:`ssl.SSLContext` one
+ must both set ``"ssl_context"`` and based on what else they require,
+ alter the other keys to ensure the desired behaviour.
+
+ :param request:
+ The PreparedReqest being sent over the connection.
+ :type request:
+ :class:`~requests.models.PreparedRequest`
+ :param verify:
+ Either a boolean, in which case it controls whether
+ we verify the server's TLS certificate, or a string, in which case it
+ must be a path to a CA bundle to use.
+ :param cert:
+ (optional) Any user-provided SSL certificate for client
+ authentication (a.k.a., mTLS). This may be a string (i.e., just
+ the path to a file which holds both certificate and key) or a
+ tuple of length 2 with the certificate file path and key file
+ path.
+ :returns:
+ A tuple of two dictionaries. The first is the "host parameters"
+ portion of the Pool Key including scheme, hostname, and port. The
+ second is a dictionary of SSLContext related parameters.
+ """
return _urllib3_request_context(request, verify, cert, self.poolmanager)
def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):
+ """Returns a urllib3 connection for the given request and TLS settings.
+ This should not be called from user code, and is only exposed for use
+ when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
+
+ :param request:
+ The :class:`PreparedRequest <PreparedRequest>` object to be sent
+ over the connection.
+ :param verify:
+ Either a boolean, in which case it controls whether we verify the
+ server's TLS certificate, or a string, in which case it must be a
+ path to a CA bundle to use.
+ :param proxies:
+ (optional) The proxies dictionary to apply to the request.
+ :param cert:
+ (optional) Any user-provided SSL certificate to be used for client
+ authentication (a.k.a., mTLS).
+ :rtype:
+ urllib3.ConnectionPool
+ """
proxy = select_proxy(request.url, proxies)
try:
host_params, pool_kwargs = self.build_connection_pool_key_attributes(
@@ -316,6 +472,17 @@ return conn
def get_connection(self, url, proxies=None):
+ """DEPRECATED: Users should move to `get_connection_with_tls_context`
+ for all subclasses of HTTPAdapter using Requests>=2.32.2.
+
+ Returns a urllib3 connection for the given URL. This should not be
+ called from user code, and is only exposed for use when subclassing the
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
+
+ :param url: The URL to connect to.
+ :param proxies: (optional) A Requests-style dictionary of proxies used on this request.
+ :rtype: urllib3.ConnectionPool
+ """
warnings.warn(
(
"`get_connection` has been deprecated in favor of "
@@ -346,11 +513,29 @@ return conn
def close(self):
+ """Disposes of any internal state.
+
+ Currently, this closes the PoolManager and any active ProxyManager,
+ which closes any pooled connections.
+ """
self.poolmanager.clear()
for proxy in self.proxy_manager.values():
proxy.clear()
def request_url(self, request, proxies):
+ """Obtain the url to use when making the final request.
+
+ If the message is being sent through a HTTP proxy, the full URL has to
+ be used. Otherwise, we should only use the path portion of the URL.
+
+ This should not be called from user code, and is only exposed for use
+ when subclassing the
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
+
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
+ :rtype: str
+ """
proxy = select_proxy(request.url, proxies)
scheme = urlparse(request.url).scheme
@@ -370,9 +555,32 @@ return url
def add_headers(self, request, **kwargs):
+ """Add any headers needed by the connection. As of v2.0 this does
+ nothing by default, but is left for overriding by users that subclass
+ the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
+
+ This should not be called from user code, and is only exposed for use
+ when subclassing the
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
+
+ :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
+ :param kwargs: The keyword arguments from the call to send().
+ """
pass
def proxy_headers(self, proxy):
+ """Returns a dictionary of the headers to add to any request sent
+ through a proxy. This works with urllib3 magic to ensure that they are
+ correctly sent to the proxy, rather than in a tunnelled request if
+ CONNECT is being used.
+
+ This should not be called from user code, and is only exposed for use
+ when subclassing the
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
+
+ :param proxy: The url of the proxy being used for this request.
+ :rtype: dict
+ """
headers = {}
username, password = get_auth_from_url(proxy)
@@ -384,6 +592,21 @@ def send(
self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
):
+ """Sends PreparedRequest object. Returns Response object.
+
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
+ :param stream: (optional) Whether to stream the request content.
+ :param timeout: (optional) How long to wait for the server to send
+ data before giving up, as a float, or a :ref:`(connect timeout,
+ read timeout) <timeouts>` tuple.
+ :type timeout: float or tuple or urllib3 Timeout object
+ :param verify: (optional) Either a boolean, in which case it controls whether
+ we verify the server's TLS certificate, or a string, in which case it
+ must be a path to a CA bundle to use
+ :param cert: (optional) Any user-provided SSL certificate to be trusted.
+ :param proxies: (optional) The proxies dictionary to apply to the request.
+ :rtype: requests.Response
+ """
try:
conn = self.get_connection_with_tls_context(
@@ -472,4 +695,4 @@ else:
raise
- return self.build_response(request, resp)+ return self.build_response(request, resp)
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/adapters.py |
Document functions with clear intent |
import hashlib
import os
import re
import threading
import time
import warnings
from base64 import b64encode
from ._internal_utils import to_native_string
from .compat import basestring, str, urlparse
from .cookies import extract_cookies_to_jar
from .utils import parse_dict_header
CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded"
CONTENT_TYPE_MULTI_PART = "multipart/form-data"
def _basic_auth_str(username, password):
# "I want us to put a big-ol' comment on top of it that
# says that this behaviour is dumb but we need to preserve
# it because people are relying on it."
# - Lukasa
#
# These are here solely to maintain backwards compatibility
# for things like ints. This will be removed in 3.0.0.
if not isinstance(username, basestring):
warnings.warn(
"Non-string usernames will no longer be supported in Requests "
f"3.0.0. Please convert the object you've passed in ({username!r}) to "
"a string or bytes object in the near future to avoid "
"problems.",
category=DeprecationWarning,
)
username = str(username)
if not isinstance(password, basestring):
warnings.warn(
"Non-string passwords will no longer be supported in Requests "
f"3.0.0. Please convert the object you've passed in ({type(password)!r}) to "
"a string or bytes object in the near future to avoid "
"problems.",
category=DeprecationWarning,
)
password = str(password)
# -- End Removal --
if isinstance(username, str):
username = username.encode("latin1")
if isinstance(password, str):
password = password.encode("latin1")
authstr = "Basic " + to_native_string(
b64encode(b":".join((username, password))).strip()
)
return authstr
class AuthBase:
def __call__(self, r):
raise NotImplementedError("Auth hooks must be callable.")
class HTTPBasicAuth(AuthBase):
def __init__(self, username, password):
self.username = username
self.password = password
def __eq__(self, other):
return all(
[
self.username == getattr(other, "username", None),
self.password == getattr(other, "password", None),
]
)
def __ne__(self, other):
return not self == other
def __call__(self, r):
r.headers["Authorization"] = _basic_auth_str(self.username, self.password)
return r
class HTTPProxyAuth(HTTPBasicAuth):
def __call__(self, r):
r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password)
return r
class HTTPDigestAuth(AuthBase):
def __init__(self, username, password):
self.username = username
self.password = password
# Keep state in per-thread local storage
self._thread_local = threading.local()
def init_per_thread_state(self):
# Ensure state is initialized just once per-thread
if not hasattr(self._thread_local, "init"):
self._thread_local.init = True
self._thread_local.last_nonce = ""
self._thread_local.nonce_count = 0
self._thread_local.chal = {}
self._thread_local.pos = None
self._thread_local.num_401_calls = None
def build_digest_header(self, method, url):
realm = self._thread_local.chal["realm"]
nonce = self._thread_local.chal["nonce"]
qop = self._thread_local.chal.get("qop")
algorithm = self._thread_local.chal.get("algorithm")
opaque = self._thread_local.chal.get("opaque")
hash_utf8 = None
if algorithm is None:
_algorithm = "MD5"
else:
_algorithm = algorithm.upper()
# lambdas assume digest modules are imported at the top level
if _algorithm == "MD5" or _algorithm == "MD5-SESS":
def md5_utf8(x):
if isinstance(x, str):
x = x.encode("utf-8")
return hashlib.md5(x).hexdigest()
hash_utf8 = md5_utf8
elif _algorithm == "SHA":
def sha_utf8(x):
if isinstance(x, str):
x = x.encode("utf-8")
return hashlib.sha1(x).hexdigest()
hash_utf8 = sha_utf8
elif _algorithm == "SHA-256":
def sha256_utf8(x):
if isinstance(x, str):
x = x.encode("utf-8")
return hashlib.sha256(x).hexdigest()
hash_utf8 = sha256_utf8
elif _algorithm == "SHA-512":
def sha512_utf8(x):
if isinstance(x, str):
x = x.encode("utf-8")
return hashlib.sha512(x).hexdigest()
hash_utf8 = sha512_utf8
KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731
if hash_utf8 is None:
return None
# XXX not implemented yet
entdig = None
p_parsed = urlparse(url)
#: path is request-uri defined in RFC 2616 which should not be empty
path = p_parsed.path or "/"
if p_parsed.query:
path += f"?{p_parsed.query}"
A1 = f"{self.username}:{realm}:{self.password}"
A2 = f"{method}:{path}"
HA1 = hash_utf8(A1)
HA2 = hash_utf8(A2)
if nonce == self._thread_local.last_nonce:
self._thread_local.nonce_count += 1
else:
self._thread_local.nonce_count = 1
ncvalue = f"{self._thread_local.nonce_count:08x}"
s = str(self._thread_local.nonce_count).encode("utf-8")
s += nonce.encode("utf-8")
s += time.ctime().encode("utf-8")
s += os.urandom(8)
cnonce = hashlib.sha1(s).hexdigest()[:16]
if _algorithm == "MD5-SESS":
HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}")
if not qop:
respdig = KD(HA1, f"{nonce}:{HA2}")
elif qop == "auth" or "auth" in qop.split(","):
noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}"
respdig = KD(HA1, noncebit)
else:
# XXX handle auth-int.
return None
self._thread_local.last_nonce = nonce
# XXX should the partial digests be encoded too?
base = (
f'username="{self.username}", realm="{realm}", nonce="{nonce}", '
f'uri="{path}", response="{respdig}"'
)
if opaque:
base += f', opaque="{opaque}"'
if algorithm:
base += f', algorithm="{algorithm}"'
if entdig:
base += f', digest="{entdig}"'
if qop:
base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"'
return f"Digest {base}"
def handle_redirect(self, r, **kwargs):
if r.is_redirect:
self._thread_local.num_401_calls = 1
def handle_401(self, r, **kwargs):
# If response is not 4xx, do not auth
# See https://github.com/psf/requests/issues/3772
if not 400 <= r.status_code < 500:
self._thread_local.num_401_calls = 1
return r
if self._thread_local.pos is not None:
# Rewind the file position indicator of the body to where
# it was to resend the request.
r.request.body.seek(self._thread_local.pos)
s_auth = r.headers.get("www-authenticate", "")
if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2:
self._thread_local.num_401_calls += 1
pat = re.compile(r"digest ", flags=re.IGNORECASE)
self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1))
# Consume content and release the original connection
# to allow our new request to reuse the same one.
r.content
r.close()
prep = r.request.copy()
extract_cookies_to_jar(prep._cookies, r.request, r.raw)
prep.prepare_cookies(prep._cookies)
prep.headers["Authorization"] = self.build_digest_header(
prep.method, prep.url
)
_r = r.connection.send(prep, **kwargs)
_r.history.append(r)
_r.request = prep
return _r
self._thread_local.num_401_calls = 1
return r
def __call__(self, r):
# Initialize per-thread state, if needed
self.init_per_thread_state()
# If we have a saved nonce, skip the 401
if self._thread_local.last_nonce:
r.headers["Authorization"] = self.build_digest_header(r.method, r.url)
try:
self._thread_local.pos = r.body.tell()
except AttributeError:
# In the case of HTTPDigestAuth being reused and the body of
# the previous request was a file-like object, pos has the
# file position of the previous body. Ensure it's set to
# None.
self._thread_local.pos = None
r.register_hook("response", self.handle_401)
r.register_hook("response", self.handle_redirect)
self._thread_local.num_401_calls = 1
return r
def __eq__(self, other):
return all(
[
self.username == getattr(other, "username", None),
self.password == getattr(other, "password", None),
]
)
def __ne__(self, other):
return not self == other | --- +++ @@ -1,3 +1,9 @@+"""
+requests.auth
+~~~~~~~~~~~~~
+
+This module contains the authentication handlers for Requests.
+"""
import hashlib
import os
@@ -17,6 +23,7 @@
def _basic_auth_str(username, password):
+ """Returns a Basic Auth string."""
# "I want us to put a big-ol' comment on top of it that
# says that this behaviour is dumb but we need to preserve
@@ -60,12 +67,14 @@
class AuthBase:
+ """Base class that all auth implementations derive from"""
def __call__(self, r):
raise NotImplementedError("Auth hooks must be callable.")
class HTTPBasicAuth(AuthBase):
+ """Attaches HTTP Basic Authentication to the given Request object."""
def __init__(self, username, password):
self.username = username
@@ -88,6 +97,7 @@
class HTTPProxyAuth(HTTPBasicAuth):
+ """Attaches HTTP Proxy Authentication to a given Request object."""
def __call__(self, r):
r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password)
@@ -95,6 +105,7 @@
class HTTPDigestAuth(AuthBase):
+ """Attaches HTTP Digest Authentication to the given Request object."""
def __init__(self, username, password):
self.username = username
@@ -113,6 +124,9 @@ self._thread_local.num_401_calls = None
def build_digest_header(self, method, url):
+ """
+ :rtype: str
+ """
realm = self._thread_local.chal["realm"]
nonce = self._thread_local.chal["nonce"]
@@ -220,10 +234,16 @@ return f"Digest {base}"
def handle_redirect(self, r, **kwargs):
+ """Reset num_401_calls counter on redirects."""
if r.is_redirect:
self._thread_local.num_401_calls = 1
def handle_401(self, r, **kwargs):
+ """
+ Takes the given response and tries digest-auth, if needed.
+
+ :rtype: requests.Response
+ """
# If response is not 4xx, do not auth
# See https://github.com/psf/requests/issues/3772
@@ -291,4 +311,4 @@ )
def __ne__(self, other):
- return not self == other+ return not self == other
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/auth.py |
Create Google-style docstrings for my code |
import datetime
# Import encoding now, to avoid implicit import later.
# Implicit import within threads may cause LookupError when standard library is in a ZIP,
# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.
import encodings.idna # noqa: F401
from io import UnsupportedOperation
from urllib3.exceptions import (
DecodeError,
LocationParseError,
ProtocolError,
ReadTimeoutError,
SSLError,
)
from urllib3.fields import RequestField
from urllib3.filepost import encode_multipart_formdata
from urllib3.util import parse_url
from ._internal_utils import to_native_string, unicode_is_ascii
from .auth import HTTPBasicAuth
from .compat import (
Callable,
JSONDecodeError,
Mapping,
basestring,
builtin_str,
chardet,
cookielib,
urlencode,
urlsplit,
urlunparse,
)
from .compat import json as complexjson
from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header
from .exceptions import (
ChunkedEncodingError,
ConnectionError,
ContentDecodingError,
HTTPError,
InvalidJSONError,
InvalidURL,
MissingSchema,
StreamConsumedError,
)
from .exceptions import JSONDecodeError as RequestsJSONDecodeError
from .exceptions import SSLError as RequestsSSLError
from .hooks import default_hooks
from .status_codes import codes
from .structures import CaseInsensitiveDict
from .utils import (
check_header_validity,
get_auth_from_url,
guess_filename,
guess_json_utf,
iter_slices,
parse_header_links,
requote_uri,
stream_decode_response_unicode,
super_len,
to_key_val_list,
)
#: The set of HTTP status codes that indicate an automatically
#: processable redirect.
REDIRECT_STATI = (
codes.moved, # 301
codes.found, # 302
codes.other, # 303
codes.temporary_redirect, # 307
codes.permanent_redirect, # 308
)
DEFAULT_REDIRECT_LIMIT = 30
CONTENT_CHUNK_SIZE = 10 * 1024
ITER_CHUNK_SIZE = 512
class RequestEncodingMixin:
@property
def path_url(self):
url = []
p = urlsplit(self.url)
path = p.path
if not path:
path = "/"
url.append(path)
query = p.query
if query:
url.append("?")
url.append(query)
return "".join(url)
@staticmethod
def _encode_params(data):
if isinstance(data, (str, bytes)):
return data
elif hasattr(data, "read"):
return data
elif hasattr(data, "__iter__"):
result = []
for k, vs in to_key_val_list(data):
if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):
vs = [vs]
for v in vs:
if v is not None:
result.append(
(
k.encode("utf-8") if isinstance(k, str) else k,
v.encode("utf-8") if isinstance(v, str) else v,
)
)
return urlencode(result, doseq=True)
else:
return data
@staticmethod
def _encode_files(files, data):
if not files:
raise ValueError("Files must be provided.")
elif isinstance(data, basestring):
raise ValueError("Data must not be a string.")
new_fields = []
fields = to_key_val_list(data or {})
files = to_key_val_list(files or {})
for field, val in fields:
if isinstance(val, basestring) or not hasattr(val, "__iter__"):
val = [val]
for v in val:
if v is not None:
# Don't call str() on bytestrings: in Py3 it all goes wrong.
if not isinstance(v, bytes):
v = str(v)
new_fields.append(
(
field.decode("utf-8")
if isinstance(field, bytes)
else field,
v.encode("utf-8") if isinstance(v, str) else v,
)
)
for k, v in files:
# support for explicit filename
ft = None
fh = None
if isinstance(v, (tuple, list)):
if len(v) == 2:
fn, fp = v
elif len(v) == 3:
fn, fp, ft = v
else:
fn, fp, ft, fh = v
else:
fn = guess_filename(v) or k
fp = v
if isinstance(fp, (str, bytes, bytearray)):
fdata = fp
elif hasattr(fp, "read"):
fdata = fp.read()
elif fp is None:
continue
else:
fdata = fp
rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)
rf.make_multipart(content_type=ft)
new_fields.append(rf)
body, content_type = encode_multipart_formdata(new_fields)
return body, content_type
class RequestHooksMixin:
def register_hook(self, event, hook):
if event not in self.hooks:
raise ValueError(f'Unsupported event specified, with event name "{event}"')
if isinstance(hook, Callable):
self.hooks[event].append(hook)
elif hasattr(hook, "__iter__"):
self.hooks[event].extend(h for h in hook if isinstance(h, Callable))
def deregister_hook(self, event, hook):
try:
self.hooks[event].remove(hook)
return True
except ValueError:
return False
class Request(RequestHooksMixin):
def __init__(
self,
method=None,
url=None,
headers=None,
files=None,
data=None,
params=None,
auth=None,
cookies=None,
hooks=None,
json=None,
):
# Default empty dicts for dict params.
data = [] if data is None else data
files = [] if files is None else files
headers = {} if headers is None else headers
params = {} if params is None else params
hooks = {} if hooks is None else hooks
self.hooks = default_hooks()
for k, v in list(hooks.items()):
self.register_hook(event=k, hook=v)
self.method = method
self.url = url
self.headers = headers
self.files = files
self.data = data
self.json = json
self.params = params
self.auth = auth
self.cookies = cookies
def __repr__(self):
return f"<Request [{self.method}]>"
def prepare(self):
p = PreparedRequest()
p.prepare(
method=self.method,
url=self.url,
headers=self.headers,
files=self.files,
data=self.data,
json=self.json,
params=self.params,
auth=self.auth,
cookies=self.cookies,
hooks=self.hooks,
)
return p
class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
def __init__(self):
#: HTTP verb to send to the server.
self.method = None
#: HTTP URL to send the request to.
self.url = None
#: dictionary of HTTP headers.
self.headers = None
# The `CookieJar` used to create the Cookie header will be stored here
# after prepare_cookies is called
self._cookies = None
#: request body to send to the server.
self.body = None
#: dictionary of callback hooks, for internal usage.
self.hooks = default_hooks()
#: integer denoting starting position of a readable file-like body.
self._body_position = None
def prepare(
self,
method=None,
url=None,
headers=None,
files=None,
data=None,
params=None,
auth=None,
cookies=None,
hooks=None,
json=None,
):
self.prepare_method(method)
self.prepare_url(url, params)
self.prepare_headers(headers)
self.prepare_cookies(cookies)
self.prepare_body(data, files, json)
self.prepare_auth(auth, url)
# Note that prepare_auth must be last to enable authentication schemes
# such as OAuth to work on a fully prepared request.
# This MUST go after prepare_auth. Authenticators could add a hook
self.prepare_hooks(hooks)
def __repr__(self):
return f"<PreparedRequest [{self.method}]>"
def copy(self):
p = PreparedRequest()
p.method = self.method
p.url = self.url
p.headers = self.headers.copy() if self.headers is not None else None
p._cookies = _copy_cookie_jar(self._cookies)
p.body = self.body
p.hooks = self.hooks
p._body_position = self._body_position
return p
def prepare_method(self, method):
self.method = method
if self.method is not None:
self.method = to_native_string(self.method.upper())
@staticmethod
def _get_idna_encoded_host(host):
import idna
try:
host = idna.encode(host, uts46=True).decode("utf-8")
except idna.IDNAError:
raise UnicodeError
return host
def prepare_url(self, url, params):
#: Accept objects that have string representations.
#: We're unable to blindly call unicode/str functions
#: as this will include the bytestring indicator (b'')
#: on python 3.x.
#: https://github.com/psf/requests/pull/2238
if isinstance(url, bytes):
url = url.decode("utf8")
else:
url = str(url)
# Remove leading whitespaces from url
url = url.lstrip()
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ":" in url and not url.lower().startswith("http"):
self.url = url
return
# Support for unicode domain names and paths.
try:
scheme, auth, host, port, path, query, fragment = parse_url(url)
except LocationParseError as e:
raise InvalidURL(*e.args)
if not scheme:
raise MissingSchema(
f"Invalid URL {url!r}: No scheme supplied. "
f"Perhaps you meant https://{url}?"
)
if not host:
raise InvalidURL(f"Invalid URL {url!r}: No host supplied")
# In general, we want to try IDNA encoding the hostname if the string contains
# non-ASCII characters. This allows users to automatically get the correct IDNA
# behaviour. For strings containing only ASCII characters, we need to also verify
# it doesn't start with a wildcard (*), before allowing the unencoded hostname.
if not unicode_is_ascii(host):
try:
host = self._get_idna_encoded_host(host)
except UnicodeError:
raise InvalidURL("URL has an invalid label.")
elif host.startswith(("*", ".")):
raise InvalidURL("URL has an invalid label.")
# Carefully reconstruct the network location
netloc = auth or ""
if netloc:
netloc += "@"
netloc += host
if port:
netloc += f":{port}"
# Bare domains aren't valid URLs.
if not path:
path = "/"
if isinstance(params, (str, bytes)):
params = to_native_string(params)
enc_params = self._encode_params(params)
if enc_params:
if query:
query = f"{query}&{enc_params}"
else:
query = enc_params
url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
self.url = url
def prepare_headers(self, headers):
self.headers = CaseInsensitiveDict()
if headers:
for header in headers.items():
# Raise exception on invalid header value.
check_header_validity(header)
name, value = header
self.headers[to_native_string(name)] = value
def prepare_body(self, data, files, json=None):
# Check if file, fo, generator, iterator.
# If not, run through normal process.
# Nottin' on you.
body = None
content_type = None
if not data and json is not None:
# urllib3 requires a bytes-like body. Python 2's json.dumps
# provides this natively, but Python 3 gives a Unicode string.
content_type = "application/json"
try:
body = complexjson.dumps(json, allow_nan=False)
except ValueError as ve:
raise InvalidJSONError(ve, request=self)
if not isinstance(body, bytes):
body = body.encode("utf-8")
is_stream = all(
[
hasattr(data, "__iter__"),
not isinstance(data, (basestring, list, tuple, Mapping)),
]
)
if is_stream:
try:
length = super_len(data)
except (TypeError, AttributeError, UnsupportedOperation):
length = None
body = data
if getattr(body, "tell", None) is not None:
# Record the current file position before reading.
# This will allow us to rewind a file in the event
# of a redirect.
try:
self._body_position = body.tell()
except OSError:
# This differentiates from None, allowing us to catch
# a failed `tell()` later when trying to rewind the body
self._body_position = object()
if files:
raise NotImplementedError(
"Streamed bodies and files are mutually exclusive."
)
if length:
self.headers["Content-Length"] = builtin_str(length)
else:
self.headers["Transfer-Encoding"] = "chunked"
else:
# Multi-part file uploads.
if files:
(body, content_type) = self._encode_files(files, data)
else:
if data:
body = self._encode_params(data)
if isinstance(data, basestring) or hasattr(data, "read"):
content_type = None
else:
content_type = "application/x-www-form-urlencoded"
self.prepare_content_length(body)
# Add content-type if it wasn't explicitly provided.
if content_type and ("content-type" not in self.headers):
self.headers["Content-Type"] = content_type
self.body = body
def prepare_content_length(self, body):
if body is not None:
length = super_len(body)
if length:
# If length exists, set it. Otherwise, we fallback
# to Transfer-Encoding: chunked.
self.headers["Content-Length"] = builtin_str(length)
elif (
self.method not in ("GET", "HEAD")
and self.headers.get("Content-Length") is None
):
# Set Content-Length to 0 for methods that can have a body
# but don't provide one. (i.e. not GET or HEAD)
self.headers["Content-Length"] = "0"
def prepare_auth(self, auth, url=""):
# If no Auth is explicitly provided, extract it from the URL first.
if auth is None:
url_auth = get_auth_from_url(self.url)
auth = url_auth if any(url_auth) else None
if auth:
if isinstance(auth, tuple) and len(auth) == 2:
# special-case basic HTTP auth
auth = HTTPBasicAuth(*auth)
# Allow auth to make its changes.
r = auth(self)
# Update self to reflect the auth changes.
self.__dict__.update(r.__dict__)
# Recompute Content-Length
self.prepare_content_length(self.body)
def prepare_cookies(self, cookies):
if isinstance(cookies, cookielib.CookieJar):
self._cookies = cookies
else:
self._cookies = cookiejar_from_dict(cookies)
cookie_header = get_cookie_header(self._cookies, self)
if cookie_header is not None:
self.headers["Cookie"] = cookie_header
def prepare_hooks(self, hooks):
# hooks can be passed as None to the prepare method and to this
# method. To prevent iterating over None, simply use an empty list
# if hooks is False-y
hooks = hooks or []
for event in hooks:
self.register_hook(event, hooks[event])
class Response:
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
def __init__(self):
self._content = False
self._content_consumed = False
self._next = None
#: Integer Code of responded HTTP Status, e.g. 404 or 200.
self.status_code = None
#: Case-insensitive Dictionary of Response Headers.
#: For example, ``headers['content-encoding']`` will return the
#: value of a ``'Content-Encoding'`` response header.
self.headers = CaseInsensitiveDict()
#: File-like object representation of response (for advanced usage).
#: Use of ``raw`` requires that ``stream=True`` be set on the request.
#: This requirement does not apply for use internally to Requests.
self.raw = None
#: Final URL location of Response.
self.url = None
#: Encoding to decode with when accessing r.text.
self.encoding = None
#: A list of :class:`Response <Response>` objects from
#: the history of the Request. Any redirect responses will end
#: up here. The list is sorted from the oldest to the most recent request.
self.history = []
#: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
self.reason = None
#: A CookieJar of Cookies the server sent back.
self.cookies = cookiejar_from_dict({})
#: The amount of time elapsed between sending the request
#: and the arrival of the response (as a timedelta).
#: This property specifically measures the time taken between sending
#: the first byte of the request and finishing parsing the headers. It
#: is therefore unaffected by consuming the response content or the
#: value of the ``stream`` keyword argument.
self.elapsed = datetime.timedelta(0)
#: The :class:`PreparedRequest <PreparedRequest>` object to which this
#: is a response.
self.request = None
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def __getstate__(self):
# Consume everything; accessing the content attribute makes
# sure the content has been fully read.
if not self._content_consumed:
self.content
return {attr: getattr(self, attr, None) for attr in self.__attrs__}
def __setstate__(self, state):
for name, value in state.items():
setattr(self, name, value)
# pickled objects do not have .raw
setattr(self, "_content_consumed", True)
setattr(self, "raw", None)
def __repr__(self):
return f"<Response [{self.status_code}]>"
def __bool__(self):
return self.ok
def __nonzero__(self):
return self.ok
def __iter__(self):
return self.iter_content(128)
@property
def ok(self):
try:
self.raise_for_status()
except HTTPError:
return False
return True
@property
def is_redirect(self):
return "location" in self.headers and self.status_code in REDIRECT_STATI
@property
def is_permanent_redirect(self):
return "location" in self.headers and self.status_code in (
codes.moved_permanently,
codes.permanent_redirect,
)
@property
def next(self):
return self._next
@property
def apparent_encoding(self):
if chardet is not None:
return chardet.detect(self.content)["encoding"]
else:
# If no character detection library is available, we'll fall back
# to a standard Python utf-8 str.
return "utf-8"
def iter_content(self, chunk_size=1, decode_unicode=False):
def generate():
# Special case for urllib3.
if hasattr(self.raw, "stream"):
try:
yield from self.raw.stream(chunk_size, decode_content=True)
except ProtocolError as e:
raise ChunkedEncodingError(e)
except DecodeError as e:
raise ContentDecodingError(e)
except ReadTimeoutError as e:
raise ConnectionError(e)
except SSLError as e:
raise RequestsSSLError(e)
else:
# Standard file-like object.
while True:
chunk = self.raw.read(chunk_size)
if not chunk:
break
yield chunk
self._content_consumed = True
if self._content_consumed and isinstance(self._content, bool):
raise StreamConsumedError()
elif chunk_size is not None and not isinstance(chunk_size, int):
raise TypeError(
f"chunk_size must be an int, it is instead a {type(chunk_size)}."
)
# simulate reading small chunks of the content
reused_chunks = iter_slices(self._content, chunk_size)
stream_chunks = generate()
chunks = reused_chunks if self._content_consumed else stream_chunks
if decode_unicode:
chunks = stream_decode_response_unicode(chunks, self)
return chunks
def iter_lines(
self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None
):
pending = None
for chunk in self.iter_content(
chunk_size=chunk_size, decode_unicode=decode_unicode
):
if pending is not None:
chunk = pending + chunk
if delimiter:
lines = chunk.split(delimiter)
else:
lines = chunk.splitlines()
if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
pending = lines.pop()
else:
pending = None
yield from lines
if pending is not None:
yield pending
@property
def content(self):
if self._content is False:
# Read the contents.
if self._content_consumed:
raise RuntimeError("The content for this response was already consumed")
if self.status_code == 0 or self.raw is None:
self._content = None
else:
self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b""
self._content_consumed = True
# don't need to release the connection; that's been handled by urllib3
# since we exhausted the data.
return self._content
@property
def text(self):
# Try charset from content-type
content = None
encoding = self.encoding
if not self.content:
return ""
# Fallback to auto-detected encoding.
if self.encoding is None:
encoding = self.apparent_encoding
# Decode unicode from given encoding.
try:
content = str(self.content, encoding, errors="replace")
except (LookupError, TypeError):
# A LookupError is raised if the encoding was not found which could
# indicate a misspelling or similar mistake.
#
# A TypeError can be raised if encoding is None
#
# So we try blindly encoding.
content = str(self.content, errors="replace")
return content
def json(self, **kwargs):
if not self.encoding and self.content and len(self.content) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
# UTF-8, -16 or -32. Detect which one to use; If the detection or
# decoding fails, fall back to `self.text` (using charset_normalizer to make
# a best guess).
encoding = guess_json_utf(self.content)
if encoding is not None:
try:
return complexjson.loads(self.content.decode(encoding), **kwargs)
except UnicodeDecodeError:
# Wrong UTF codec detected; usually because it's not UTF-8
# but some other 8-bit codec. This is an RFC violation,
# and the server didn't bother to tell us what codec *was*
# used.
pass
except JSONDecodeError as e:
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
try:
return complexjson.loads(self.text, **kwargs)
except JSONDecodeError as e:
# Catch JSON-related errors and raise as requests.JSONDecodeError
# This aliases json.JSONDecodeError and simplejson.JSONDecodeError
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
@property
def links(self):
header = self.headers.get("link")
resolved_links = {}
if header:
links = parse_header_links(header)
for link in links:
key = link.get("rel") or link.get("url")
resolved_links[key] = link
return resolved_links
def raise_for_status(self):
http_error_msg = ""
if isinstance(self.reason, bytes):
# We attempt to decode utf-8 first because some servers
# choose to localize their reason strings. If the string
# isn't utf-8, we fall back to iso-8859-1 for all other
# encodings. (See PR #3538)
try:
reason = self.reason.decode("utf-8")
except UnicodeDecodeError:
reason = self.reason.decode("iso-8859-1")
else:
reason = self.reason
if 400 <= self.status_code < 500:
http_error_msg = (
f"{self.status_code} Client Error: {reason} for url: {self.url}"
)
elif 500 <= self.status_code < 600:
http_error_msg = (
f"{self.status_code} Server Error: {reason} for url: {self.url}"
)
if http_error_msg:
raise HTTPError(http_error_msg, response=self)
def close(self):
if not self._content_consumed:
self.raw.close()
release_conn = getattr(self.raw, "release_conn", None)
if release_conn is not None:
release_conn() | --- +++ @@ -1,3 +1,9 @@+"""
+requests.models
+~~~~~~~~~~~~~~~
+
+This module contains the primary objects that power Requests.
+"""
import datetime
@@ -80,6 +86,7 @@ class RequestEncodingMixin:
@property
def path_url(self):
+ """Build the path URL to use."""
url = []
@@ -100,6 +107,12 @@
@staticmethod
def _encode_params(data):
+ """Encode parameters in a piece of data.
+
+ Will successfully encode parameters when passed as a dict or a list of
+ 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
+ if parameters are supplied as a dict.
+ """
if isinstance(data, (str, bytes)):
return data
@@ -124,6 +137,14 @@
@staticmethod
def _encode_files(files, data):
+ """Build the body for a multipart/form-data request.
+
+ Will successfully encode files when passed as a dict or a list of
+ tuples. Order is retained if data is a list of tuples but arbitrary
+ if parameters are supplied as a dict.
+ The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
+ or 4-tuples (filename, fileobj, contentype, custom_headers).
+ """
if not files:
raise ValueError("Files must be provided.")
elif isinstance(data, basestring):
@@ -186,6 +207,7 @@
class RequestHooksMixin:
def register_hook(self, event, hook):
+ """Properly register a hook."""
if event not in self.hooks:
raise ValueError(f'Unsupported event specified, with event name "{event}"')
@@ -196,6 +218,9 @@ self.hooks[event].extend(h for h in hook if isinstance(h, Callable))
def deregister_hook(self, event, hook):
+ """Deregister a previously registered hook.
+ Returns True if the hook existed, False if not.
+ """
try:
self.hooks[event].remove(hook)
@@ -205,6 +230,32 @@
class Request(RequestHooksMixin):
+ """A user-created :class:`Request <Request>` object.
+
+ Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.
+
+ :param method: HTTP method to use.
+ :param url: URL to send.
+ :param headers: dictionary of headers to send.
+ :param files: dictionary of {filename: fileobject} files to multipart upload.
+ :param data: the body to attach to the request. If a dictionary or
+ list of tuples ``[(key, value)]`` is provided, form-encoding will
+ take place.
+ :param json: json for the body to attach to the request (if files or data is not specified).
+ :param params: URL parameters to append to the URL. If a dictionary or
+ list of tuples ``[(key, value)]`` is provided, form-encoding will
+ take place.
+ :param auth: Auth handler or (user, pass) tuple.
+ :param cookies: dictionary or CookieJar of cookies to attach to this request.
+ :param hooks: dictionary of callback hooks, for internal usage.
+
+ Usage::
+
+ >>> import requests
+ >>> req = requests.Request('GET', 'https://httpbin.org/get')
+ >>> req.prepare()
+ <PreparedRequest [GET]>
+ """
def __init__(
self,
@@ -244,6 +295,7 @@ return f"<Request [{self.method}]>"
def prepare(self):
+ """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""
p = PreparedRequest()
p.prepare(
method=self.method,
@@ -261,6 +313,25 @@
class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
+ """The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
+ containing the exact bytes that will be sent to the server.
+
+ Instances are generated from a :class:`Request <Request>` object, and
+ should not be instantiated manually; doing so may produce undesirable
+ effects.
+
+ Usage::
+
+ >>> import requests
+ >>> req = requests.Request('GET', 'https://httpbin.org/get')
+ >>> r = req.prepare()
+ >>> r
+ <PreparedRequest [GET]>
+
+ >>> s = requests.Session()
+ >>> s.send(r)
+ <Response [200]>
+ """
def __init__(self):
#: HTTP verb to send to the server.
@@ -292,6 +363,7 @@ hooks=None,
json=None,
):
+ """Prepares the entire request with the given parameters."""
self.prepare_method(method)
self.prepare_url(url, params)
@@ -321,6 +393,7 @@ return p
def prepare_method(self, method):
+ """Prepares the given HTTP method."""
self.method = method
if self.method is not None:
self.method = to_native_string(self.method.upper())
@@ -336,6 +409,7 @@ return host
def prepare_url(self, url, params):
+ """Prepares the given HTTP URL."""
#: Accept objects that have string representations.
#: We're unable to blindly call unicode/str functions
#: as this will include the bytestring indicator (b'')
@@ -409,6 +483,7 @@ self.url = url
def prepare_headers(self, headers):
+ """Prepares the given HTTP headers."""
self.headers = CaseInsensitiveDict()
if headers:
@@ -419,6 +494,7 @@ self.headers[to_native_string(name)] = value
def prepare_body(self, data, files, json=None):
+ """Prepares the given HTTP body data."""
# Check if file, fo, generator, iterator.
# If not, run through normal process.
@@ -496,6 +572,7 @@ self.body = body
def prepare_content_length(self, body):
+ """Prepare Content-Length header based on request method and body"""
if body is not None:
length = super_len(body)
if length:
@@ -511,6 +588,7 @@ self.headers["Content-Length"] = "0"
def prepare_auth(self, auth, url=""):
+ """Prepares the given HTTP auth data."""
# If no Auth is explicitly provided, extract it from the URL first.
if auth is None:
@@ -532,6 +610,16 @@ self.prepare_content_length(self.body)
def prepare_cookies(self, cookies):
+ """Prepares the given HTTP cookie data.
+
+ This function eventually generates a ``Cookie`` header from the
+ given cookies using cookielib. Due to cookielib's design, the header
+ will not be regenerated if it already exists, meaning this function
+ can only be called once for the life of the
+ :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
+ to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
+ header is removed beforehand.
+ """
if isinstance(cookies, cookielib.CookieJar):
self._cookies = cookies
else:
@@ -542,6 +630,7 @@ self.headers["Cookie"] = cookie_header
def prepare_hooks(self, hooks):
+ """Prepares the given hooks."""
# hooks can be passed as None to the prepare method and to this
# method. To prevent iterating over None, simply use an empty list
# if hooks is False-y
@@ -551,6 +640,9 @@
class Response:
+ """The :class:`Response <Response>` object, which contains a
+ server's response to an HTTP request.
+ """
__attrs__ = [
"_content",
@@ -638,16 +730,38 @@ return f"<Response [{self.status_code}]>"
def __bool__(self):
+ """Returns True if :attr:`status_code` is less than 400.
+
+ This attribute checks if the status code of the response is between
+ 400 and 600 to see if there was a client error or a server error. If
+ the status code, is between 200 and 400, this will return True. This
+ is **not** a check to see if the response code is ``200 OK``.
+ """
return self.ok
def __nonzero__(self):
+ """Returns True if :attr:`status_code` is less than 400.
+
+ This attribute checks if the status code of the response is between
+ 400 and 600 to see if there was a client error or a server error. If
+ the status code, is between 200 and 400, this will return True. This
+ is **not** a check to see if the response code is ``200 OK``.
+ """
return self.ok
def __iter__(self):
+ """Allows you to use a response as an iterator."""
return self.iter_content(128)
@property
def ok(self):
+ """Returns True if :attr:`status_code` is less than 400, False if not.
+
+ This attribute checks if the status code of the response is between
+ 400 and 600 to see if there was a client error or a server error. If
+ the status code is between 200 and 400, this will return True. This
+ is **not** a check to see if the response code is ``200 OK``.
+ """
try:
self.raise_for_status()
except HTTPError:
@@ -656,10 +770,14 @@
@property
def is_redirect(self):
+ """True if this Response is a well-formed HTTP redirect that could have
+ been processed automatically (by :meth:`Session.resolve_redirects`).
+ """
return "location" in self.headers and self.status_code in REDIRECT_STATI
@property
def is_permanent_redirect(self):
+ """True if this Response one of the permanent versions of redirect."""
return "location" in self.headers and self.status_code in (
codes.moved_permanently,
codes.permanent_redirect,
@@ -667,10 +785,12 @@
@property
def next(self):
+ """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
return self._next
@property
def apparent_encoding(self):
+ """The apparent encoding, provided by the charset_normalizer or chardet libraries."""
if chardet is not None:
return chardet.detect(self.content)["encoding"]
else:
@@ -679,6 +799,21 @@ return "utf-8"
def iter_content(self, chunk_size=1, decode_unicode=False):
+ """Iterates over the response data. When stream=True is set on the
+ request, this avoids reading the content at once into memory for
+ large responses. The chunk size is the number of bytes it should
+ read into memory. This is not necessarily the length of each item
+ returned as decoding can take place.
+
+ chunk_size must be of type int or None. A value of None will
+ function differently depending on the value of `stream`.
+ stream=True will read data as it arrives in whatever size the
+ chunks are received. If stream=False, data is returned as
+ a single chunk.
+
+ If decode_unicode is True, content will be decoded using the best
+ available encoding based on the response.
+ """
def generate():
# Special case for urllib3.
@@ -724,6 +859,12 @@ def iter_lines(
self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None
):
+ """Iterates over the response data, one line at a time. When
+ stream=True is set on the request, this avoids reading the
+ content at once into memory for large responses.
+
+ .. note:: This method is not reentrant safe.
+ """
pending = None
@@ -750,6 +891,7 @@
@property
def content(self):
+ """Content of the response, in bytes."""
if self._content is False:
# Read the contents.
@@ -768,6 +910,16 @@
@property
def text(self):
+ """Content of the response, in unicode.
+
+ If Response.encoding is None, encoding will be guessed using
+ ``charset_normalizer`` or ``chardet``.
+
+ The encoding of the response content is determined based solely on HTTP
+ headers, following RFC 2616 to the letter. If you can take advantage of
+ non-HTTP knowledge to make a better guess at the encoding, you should
+ set ``r.encoding`` appropriately before accessing this property.
+ """
# Try charset from content-type
content = None
@@ -795,6 +947,14 @@ return content
def json(self, **kwargs):
+ r"""Decodes the JSON response body (if any) as a Python object.
+
+ This may return a dictionary, list, etc. depending on what is in the response.
+
+ :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
+ :raises requests.exceptions.JSONDecodeError: If the response body does not
+ contain valid json.
+ """
if not self.encoding and self.content and len(self.content) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
@@ -823,6 +983,7 @@
@property
def links(self):
+ """Returns the parsed header links of the response, if any."""
header = self.headers.get("link")
@@ -838,6 +999,7 @@ return resolved_links
def raise_for_status(self):
+ """Raises :class:`HTTPError`, if one occurred."""
http_error_msg = ""
if isinstance(self.reason, bytes):
@@ -866,9 +1028,14 @@ raise HTTPError(http_error_msg, response=self)
def close(self):
+ """Releases the connection back to the pool. Once this method has been
+ called the underlying ``raw`` object must not be accessed again.
+
+ *Note: Should not normally need to be called explicitly.*
+ """
if not self._content_consumed:
self.raw.close()
release_conn = getattr(self.raw, "release_conn", None)
if release_conn is not None:
- release_conn()+ release_conn()
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/models.py |
Replace inline comments with docstrings |
from . import sessions
def request(method, url, **kwargs):
# By using the 'with' statement we are sure the session is closed, thus we
# avoid leaving sockets open which can trigger a ResourceWarning in some
# cases, and look like a memory leak in others.
with sessions.Session() as session:
return session.request(method=method, url=url, **kwargs)
def get(url, params=None, **kwargs):
return request("get", url, params=params, **kwargs)
def options(url, **kwargs):
return request("options", url, **kwargs)
def head(url, **kwargs):
kwargs.setdefault("allow_redirects", False)
return request("head", url, **kwargs)
def post(url, data=None, json=None, **kwargs):
return request("post", url, data=data, json=json, **kwargs)
def put(url, data=None, **kwargs):
return request("put", url, data=data, **kwargs)
def patch(url, data=None, **kwargs):
return request("patch", url, data=data, **kwargs)
def delete(url, **kwargs):
return request("delete", url, **kwargs) | --- +++ @@ -1,8 +1,56 @@+"""
+requests.api
+~~~~~~~~~~~~
+
+This module implements the Requests API.
+
+:copyright: (c) 2012 by Kenneth Reitz.
+:license: Apache2, see LICENSE for more details.
+"""
from . import sessions
def request(method, url, **kwargs):
+ """Constructs and sends a :class:`Request <Request>`.
+
+ :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
+ :param url: URL for the new :class:`Request` object.
+ :param params: (optional) Dictionary, list of tuples or bytes to send
+ in the query string for the :class:`Request`.
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
+ object to send in the body of the :class:`Request`.
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
+ :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
+ :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
+ :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
+ ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
+ or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string
+ defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
+ to add for the file.
+ :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
+ :param timeout: (optional) How many seconds to wait for the server to send data
+ before giving up, as a float, or a :ref:`(connect timeout, read
+ timeout) <timeouts>` tuple.
+ :type timeout: float or tuple
+ :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
+ :type allow_redirects: bool
+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
+ :param verify: (optional) Either a boolean, in which case it controls whether we verify
+ the server's TLS certificate, or a string, in which case it must be a path
+ to a CA bundle to use. Defaults to ``True``.
+ :param stream: (optional) if ``False``, the response content will be immediately downloaded.
+ :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
+ :return: :class:`Response <Response>` object
+ :rtype: requests.Response
+
+ Usage::
+
+ >>> import requests
+ >>> req = requests.request('GET', 'https://httpbin.org/get')
+ >>> req
+ <Response [200]>
+ """
# By using the 'with' statement we are sure the session is closed, thus we
# avoid leaving sockets open which can trigger a ResourceWarning in some
@@ -12,36 +60,98 @@
def get(url, params=None, **kwargs):
+ r"""Sends a GET request.
+
+ :param url: URL for the new :class:`Request` object.
+ :param params: (optional) Dictionary, list of tuples or bytes to send
+ in the query string for the :class:`Request`.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :return: :class:`Response <Response>` object
+ :rtype: requests.Response
+ """
return request("get", url, params=params, **kwargs)
def options(url, **kwargs):
+ r"""Sends an OPTIONS request.
+
+ :param url: URL for the new :class:`Request` object.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :return: :class:`Response <Response>` object
+ :rtype: requests.Response
+ """
return request("options", url, **kwargs)
def head(url, **kwargs):
+ r"""Sends a HEAD request.
+
+ :param url: URL for the new :class:`Request` object.
+ :param \*\*kwargs: Optional arguments that ``request`` takes. If
+ `allow_redirects` is not provided, it will be set to `False` (as
+ opposed to the default :meth:`request` behavior).
+ :return: :class:`Response <Response>` object
+ :rtype: requests.Response
+ """
kwargs.setdefault("allow_redirects", False)
return request("head", url, **kwargs)
def post(url, data=None, json=None, **kwargs):
+ r"""Sends a POST request.
+
+ :param url: URL for the new :class:`Request` object.
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
+ object to send in the body of the :class:`Request`.
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :return: :class:`Response <Response>` object
+ :rtype: requests.Response
+ """
return request("post", url, data=data, json=json, **kwargs)
def put(url, data=None, **kwargs):
+ r"""Sends a PUT request.
+
+ :param url: URL for the new :class:`Request` object.
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
+ object to send in the body of the :class:`Request`.
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :return: :class:`Response <Response>` object
+ :rtype: requests.Response
+ """
return request("put", url, data=data, **kwargs)
def patch(url, data=None, **kwargs):
+ r"""Sends a PATCH request.
+
+ :param url: URL for the new :class:`Request` object.
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
+ object to send in the body of the :class:`Request`.
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :return: :class:`Response <Response>` object
+ :rtype: requests.Response
+ """
return request("patch", url, data=data, **kwargs)
def delete(url, **kwargs):
+ r"""Sends a DELETE request.
- return request("delete", url, **kwargs)+ :param url: URL for the new :class:`Request` object.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :return: :class:`Response <Response>` object
+ :rtype: requests.Response
+ """
+
+ return request("delete", url, **kwargs)
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/api.py |
Add docstrings that explain logic |
import json
import platform
import ssl
import sys
import idna
import urllib3
from . import __version__ as requests_version
try:
import charset_normalizer
except ImportError:
charset_normalizer = None
try:
import chardet
except ImportError:
chardet = None
try:
from urllib3.contrib import pyopenssl
except ImportError:
pyopenssl = None
OpenSSL = None
cryptography = None
else:
import cryptography
import OpenSSL
def _implementation():
implementation = platform.python_implementation()
if implementation == "CPython":
implementation_version = platform.python_version()
elif implementation == "PyPy":
pypy = sys.pypy_version_info
implementation_version = f"{pypy.major}.{pypy.minor}.{pypy.micro}"
if sys.pypy_version_info.releaselevel != "final":
implementation_version = "".join(
[implementation_version, sys.pypy_version_info.releaselevel]
)
elif implementation == "Jython":
implementation_version = platform.python_version() # Complete Guess
elif implementation == "IronPython":
implementation_version = platform.python_version() # Complete Guess
else:
implementation_version = "Unknown"
return {"name": implementation, "version": implementation_version}
def info():
try:
platform_info = {
"system": platform.system(),
"release": platform.release(),
}
except OSError:
platform_info = {
"system": "Unknown",
"release": "Unknown",
}
implementation_info = _implementation()
urllib3_info = {"version": urllib3.__version__}
charset_normalizer_info = {"version": None}
chardet_info = {"version": None}
if charset_normalizer:
charset_normalizer_info = {"version": charset_normalizer.__version__}
if chardet:
chardet_info = {"version": chardet.__version__}
pyopenssl_info = {
"version": None,
"openssl_version": "",
}
if OpenSSL:
pyopenssl_info = {
"version": OpenSSL.__version__,
"openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}",
}
cryptography_info = {
"version": getattr(cryptography, "__version__", ""),
}
idna_info = {
"version": getattr(idna, "__version__", ""),
}
system_ssl = ssl.OPENSSL_VERSION_NUMBER
system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""}
return {
"platform": platform_info,
"implementation": implementation_info,
"system_ssl": system_ssl_info,
"using_pyopenssl": pyopenssl is not None,
"using_charset_normalizer": chardet is None,
"pyOpenSSL": pyopenssl_info,
"urllib3": urllib3_info,
"chardet": chardet_info,
"charset_normalizer": charset_normalizer_info,
"cryptography": cryptography_info,
"idna": idna_info,
"requests": {
"version": requests_version,
},
}
def main():
print(json.dumps(info(), sort_keys=True, indent=2))
if __name__ == "__main__":
main() | --- +++ @@ -1,3 +1,4 @@+"""Module containing bug report helper(s)."""
import json
import platform
@@ -31,6 +32,16 @@
def _implementation():
+ """Return a dict with the Python implementation and version.
+
+ Provide both the name and the version of the Python implementation
+ currently running. For example, on CPython 3.10.3 it will return
+ {'name': 'CPython', 'version': '3.10.3'}.
+
+ This function works best on CPython and PyPy: in particular, it probably
+ doesn't work for Jython or IronPython. Future investigation should be done
+ to work out the correct shape of the code for those platforms.
+ """
implementation = platform.python_implementation()
if implementation == "CPython":
@@ -53,6 +64,7 @@
def info():
+ """Generate information for a bug report."""
try:
platform_info = {
"system": platform.system(),
@@ -111,8 +123,9 @@
def main():
+ """Pretty-print the bug information as JSON."""
print(json.dumps(info(), sort_keys=True, indent=2))
if __name__ == "__main__":
- main()+ main()
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/help.py |
Add standardized docstrings across the file |
import codecs
import contextlib
import io
import os
import re
import socket
import struct
import sys
import tempfile
import warnings
import zipfile
from collections import OrderedDict
from urllib3.util import make_headers, parse_url
from . import certs
from .__version__ import __version__
# to_native_string is unused here, but imported here for backwards compatibility
from ._internal_utils import ( # noqa: F401
_HEADER_VALIDATORS_BYTE,
_HEADER_VALIDATORS_STR,
HEADER_VALIDATORS,
to_native_string,
)
from .compat import (
Mapping,
basestring,
bytes,
getproxies,
getproxies_environment,
integer_types,
is_urllib3_1,
proxy_bypass,
proxy_bypass_environment,
quote,
str,
unquote,
urlparse,
urlunparse,
)
from .compat import parse_http_list as _parse_list_header
from .cookies import cookiejar_from_dict
from .exceptions import (
FileModeWarning,
InvalidHeader,
InvalidURL,
UnrewindableBodyError,
)
from .structures import CaseInsensitiveDict
NETRC_FILES = (".netrc", "_netrc")
DEFAULT_CA_BUNDLE_PATH = certs.where()
DEFAULT_PORTS = {"http": 80, "https": 443}
# Ensure that ', ' is used to preserve previous delimiter behavior.
DEFAULT_ACCEPT_ENCODING = ", ".join(
re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])
)
if sys.platform == "win32":
# provide a proxy_bypass version on Windows without DNS lookups
def proxy_bypass_registry(host):
try:
import winreg
except ImportError:
return False
try:
internetSettings = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",
)
# ProxyEnable could be REG_SZ or REG_DWORD, normalizing it
proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0])
# ProxyOverride is almost always a string
proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0]
except (OSError, ValueError):
return False
if not proxyEnable or not proxyOverride:
return False
# make a check value list from the registry entry: replace the
# '<local>' string by the localhost entry and the corresponding
# canonical entry.
proxyOverride = proxyOverride.split(";")
# filter out empty strings to avoid re.match return true in the following code.
proxyOverride = filter(None, proxyOverride)
# now check if we match one of the registry values.
for test in proxyOverride:
if test == "<local>":
if "." not in host:
return True
test = test.replace(".", r"\.") # mask dots
test = test.replace("*", r".*") # change glob sequence
test = test.replace("?", r".") # change glob char
if re.match(test, host, re.I):
return True
return False
def proxy_bypass(host): # noqa
if getproxies_environment():
return proxy_bypass_environment(host)
else:
return proxy_bypass_registry(host)
def dict_to_sequence(d):
if hasattr(d, "items"):
d = d.items()
return d
def super_len(o):
total_length = None
current_position = 0
if not is_urllib3_1 and isinstance(o, str):
# urllib3 2.x+ treats all strings as utf-8 instead
# of latin-1 (iso-8859-1) like http.client.
o = o.encode("utf-8")
if hasattr(o, "__len__"):
total_length = len(o)
elif hasattr(o, "len"):
total_length = o.len
elif hasattr(o, "fileno"):
try:
fileno = o.fileno()
except (io.UnsupportedOperation, AttributeError):
# AttributeError is a surprising exception, seeing as how we've just checked
# that `hasattr(o, 'fileno')`. It happens for objects obtained via
# `Tarfile.extractfile()`, per issue 5229.
pass
else:
total_length = os.fstat(fileno).st_size
# Having used fstat to determine the file length, we need to
# confirm that this file was opened up in binary mode.
if "b" not in o.mode:
warnings.warn(
(
"Requests has determined the content-length for this "
"request using the binary size of the file: however, the "
"file has been opened in text mode (i.e. without the 'b' "
"flag in the mode). This may lead to an incorrect "
"content-length. In Requests 3.0, support will be removed "
"for files in text mode."
),
FileModeWarning,
)
if hasattr(o, "tell"):
try:
current_position = o.tell()
except OSError:
# This can happen in some weird situations, such as when the file
# is actually a special file descriptor like stdin. In this
# instance, we don't know what the length is, so set it to zero and
# let requests chunk it instead.
if total_length is not None:
current_position = total_length
else:
if hasattr(o, "seek") and total_length is None:
# StringIO and BytesIO have seek but no usable fileno
try:
# seek to end of file
o.seek(0, 2)
total_length = o.tell()
# seek back to current position to support
# partially read file-like objects
o.seek(current_position or 0)
except OSError:
total_length = 0
if total_length is None:
total_length = 0
return max(0, total_length - current_position)
def get_netrc_auth(url, raise_errors=False):
netrc_file = os.environ.get("NETRC")
if netrc_file is not None:
netrc_locations = (netrc_file,)
else:
netrc_locations = (f"~/{f}" for f in NETRC_FILES)
try:
from netrc import NetrcParseError, netrc
netrc_path = None
for f in netrc_locations:
loc = os.path.expanduser(f)
if os.path.exists(loc):
netrc_path = loc
break
# Abort early if there isn't one.
if netrc_path is None:
return
ri = urlparse(url)
host = ri.hostname
try:
_netrc = netrc(netrc_path).authenticators(host)
if _netrc and any(_netrc):
# Return with login / password
login_i = 0 if _netrc[0] else 1
return (_netrc[login_i], _netrc[2])
except (NetrcParseError, OSError):
# If there was a parsing error or a permissions issue reading the file,
# we'll just skip netrc auth unless explicitly asked to raise errors.
if raise_errors:
raise
# App Engine hackiness.
except (ImportError, AttributeError):
pass
def guess_filename(obj):
name = getattr(obj, "name", None)
if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">":
return os.path.basename(name)
def extract_zipped_paths(path):
if os.path.exists(path):
# this is already a valid path, no need to do anything further
return path
# find the first valid part of the provided path and treat that as a zip archive
# assume the rest of the path is the name of a member in the archive
archive, member = os.path.split(path)
while archive and not os.path.exists(archive):
archive, prefix = os.path.split(archive)
if not prefix:
# If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),
# we _can_ end up in an infinite loop on a rare corner case affecting a small number of users
break
member = "/".join([prefix, member])
if not zipfile.is_zipfile(archive):
return path
zip_file = zipfile.ZipFile(archive)
if member not in zip_file.namelist():
return path
# we have a valid zip archive and a valid member of that archive
tmp = tempfile.gettempdir()
extracted_path = os.path.join(tmp, member.split("/")[-1])
if not os.path.exists(extracted_path):
# use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition
with atomic_open(extracted_path) as file_handler:
file_handler.write(zip_file.read(member))
return extracted_path
@contextlib.contextmanager
def atomic_open(filename):
tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))
try:
with os.fdopen(tmp_descriptor, "wb") as tmp_handler:
yield tmp_handler
os.replace(tmp_name, filename)
except BaseException:
os.remove(tmp_name)
raise
def from_key_val_list(value):
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError("cannot encode objects that are not 2-tuples")
return OrderedDict(value)
def to_key_val_list(value):
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError("cannot encode objects that are not 2-tuples")
if isinstance(value, Mapping):
value = value.items()
return list(value)
# From mitsuhiko/werkzeug (used with permission).
def parse_list_header(value):
result = []
for item in _parse_list_header(value):
if item[:1] == item[-1:] == '"':
item = unquote_header_value(item[1:-1])
result.append(item)
return result
# From mitsuhiko/werkzeug (used with permission).
def parse_dict_header(value):
result = {}
for item in _parse_list_header(value):
if "=" not in item:
result[item] = None
continue
name, value = item.split("=", 1)
if value[:1] == value[-1:] == '"':
value = unquote_header_value(value[1:-1])
result[name] = value
return result
# From mitsuhiko/werkzeug (used with permission).
def unquote_header_value(value, is_filename=False):
if value and value[0] == value[-1] == '"':
# this is not the real unquoting, but fixing this so that the
# RFC is met will result in bugs with internet explorer and
# probably some other browsers as well. IE for example is
# uploading files with "C:\foo\bar.txt" as filename
value = value[1:-1]
# if this is a filename and the starting characters look like
# a UNC path, then just return the value without quotes. Using the
# replace sequence below on a UNC path has the effect of turning
# the leading double slash into a single slash and then
# _fix_ie_filename() doesn't work correctly. See #458.
if not is_filename or value[:2] != "\\\\":
return value.replace("\\\\", "\\").replace('\\"', '"')
return value
def dict_from_cookiejar(cj):
cookie_dict = {cookie.name: cookie.value for cookie in cj}
return cookie_dict
def add_dict_to_cookiejar(cj, cookie_dict):
return cookiejar_from_dict(cookie_dict, cj)
def get_encodings_from_content(content):
warnings.warn(
(
"In requests 3.0, get_encodings_from_content will be removed. For "
"more information, please see the discussion on issue #2266. (This"
" warning should only appear once.)"
),
DeprecationWarning,
)
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
return (
charset_re.findall(content)
+ pragma_re.findall(content)
+ xml_re.findall(content)
)
def _parse_content_type_header(header):
tokens = header.split(";")
content_type, params = tokens[0].strip(), tokens[1:]
params_dict = {}
items_to_strip = "\"' "
for param in params:
param = param.strip()
if param:
key, value = param, True
index_of_equals = param.find("=")
if index_of_equals != -1:
key = param[:index_of_equals].strip(items_to_strip)
value = param[index_of_equals + 1 :].strip(items_to_strip)
params_dict[key.lower()] = value
return content_type, params_dict
def get_encoding_from_headers(headers):
content_type = headers.get("content-type")
if not content_type:
return None
content_type, params = _parse_content_type_header(content_type)
if "charset" in params:
return params["charset"].strip("'\"")
if "text" in content_type:
return "ISO-8859-1"
if "application/json" in content_type:
# Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset
return "utf-8"
def stream_decode_response_unicode(iterator, r):
if r.encoding is None:
yield from iterator
return
decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace")
for chunk in iterator:
rv = decoder.decode(chunk)
if rv:
yield rv
rv = decoder.decode(b"", final=True)
if rv:
yield rv
def iter_slices(string, slice_length):
pos = 0
if slice_length is None or slice_length <= 0:
slice_length = len(string)
while pos < len(string):
yield string[pos : pos + slice_length]
pos += slice_length
def get_unicode_from_response(r):
warnings.warn(
(
"In requests 3.0, get_unicode_from_response will be removed. For "
"more information, please see the discussion on issue #2266. (This"
" warning should only appear once.)"
),
DeprecationWarning,
)
tried_encodings = []
# Try charset from content-type
encoding = get_encoding_from_headers(r.headers)
if encoding:
try:
return str(r.content, encoding)
except UnicodeError:
tried_encodings.append(encoding)
# Fall back:
try:
return str(r.content, encoding, errors="replace")
except TypeError:
return r.content
# The unreserved URI characters (RFC 3986)
UNRESERVED_SET = frozenset(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"
)
def unquote_unreserved(uri):
parts = uri.split("%")
for i in range(1, len(parts)):
h = parts[i][0:2]
if len(h) == 2 and h.isalnum():
try:
c = chr(int(h, 16))
except ValueError:
raise InvalidURL(f"Invalid percent-escape sequence: '{h}'")
if c in UNRESERVED_SET:
parts[i] = c + parts[i][2:]
else:
parts[i] = f"%{parts[i]}"
else:
parts[i] = f"%{parts[i]}"
return "".join(parts)
def requote_uri(uri):
safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
safe_without_percent = "!#$&'()*+,/:;=?@[]~"
try:
# Unquote only the unreserved characters
# Then quote only illegal characters (do not quote reserved,
# unreserved, or '%')
return quote(unquote_unreserved(uri), safe=safe_with_percent)
except InvalidURL:
# We couldn't unquote the given URI, so let's try quoting it, but
# there may be unquoted '%'s in the URI. We need to make sure they're
# properly quoted so they do not cause issues elsewhere.
return quote(uri, safe=safe_without_percent)
def address_in_network(ip, net):
ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0]
netaddr, bits = net.split("/")
netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]
network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask
return (ipaddr & netmask) == (network & netmask)
def dotted_netmask(mask):
bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1
return socket.inet_ntoa(struct.pack(">I", bits))
def is_ipv4_address(string_ip):
try:
socket.inet_aton(string_ip)
except OSError:
return False
return True
def is_valid_cidr(string_network):
if string_network.count("/") == 1:
try:
mask = int(string_network.split("/")[1])
except ValueError:
return False
if mask < 1 or mask > 32:
return False
try:
socket.inet_aton(string_network.split("/")[0])
except OSError:
return False
else:
return False
return True
@contextlib.contextmanager
def set_environ(env_name, value):
value_changed = value is not None
if value_changed:
old_value = os.environ.get(env_name)
os.environ[env_name] = value
try:
yield
finally:
if value_changed:
if old_value is None:
del os.environ[env_name]
else:
os.environ[env_name] = old_value
def should_bypass_proxies(url, no_proxy):
# Prioritize lowercase environment variables over uppercase
# to keep a consistent behaviour with other http projects (curl, wget).
def get_proxy(key):
return os.environ.get(key) or os.environ.get(key.upper())
# First check whether no_proxy is defined. If it is, check that the URL
# we're getting isn't in the no_proxy list.
no_proxy_arg = no_proxy
if no_proxy is None:
no_proxy = get_proxy("no_proxy")
parsed = urlparse(url)
if parsed.hostname is None:
# URLs don't always have hostnames, e.g. file:/// urls.
return True
if no_proxy:
# We need to check whether we match here. We need to see if we match
# the end of the hostname, both with and without the port.
no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host)
if is_ipv4_address(parsed.hostname):
for proxy_ip in no_proxy:
if is_valid_cidr(proxy_ip):
if address_in_network(parsed.hostname, proxy_ip):
return True
elif parsed.hostname == proxy_ip:
# If no_proxy ip was defined in plain IP notation instead of cidr notation &
# matches the IP of the index
return True
else:
host_with_port = parsed.hostname
if parsed.port:
host_with_port += f":{parsed.port}"
for host in no_proxy:
if parsed.hostname.endswith(host) or host_with_port.endswith(host):
# The URL does match something in no_proxy, so we don't want
# to apply the proxies on this URL.
return True
with set_environ("no_proxy", no_proxy_arg):
# parsed.hostname can be `None` in cases such as a file URI.
try:
bypass = proxy_bypass(parsed.hostname)
except (TypeError, socket.gaierror):
bypass = False
if bypass:
return True
return False
def get_environ_proxies(url, no_proxy=None):
if should_bypass_proxies(url, no_proxy=no_proxy):
return {}
else:
return getproxies()
def select_proxy(url, proxies):
proxies = proxies or {}
urlparts = urlparse(url)
if urlparts.hostname is None:
return proxies.get(urlparts.scheme, proxies.get("all"))
proxy_keys = [
urlparts.scheme + "://" + urlparts.hostname,
urlparts.scheme,
"all://" + urlparts.hostname,
"all",
]
proxy = None
for proxy_key in proxy_keys:
if proxy_key in proxies:
proxy = proxies[proxy_key]
break
return proxy
def resolve_proxies(request, proxies, trust_env=True):
proxies = proxies if proxies is not None else {}
url = request.url
scheme = urlparse(url).scheme
no_proxy = proxies.get("no_proxy")
new_proxies = proxies.copy()
if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):
environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)
proxy = environ_proxies.get(scheme, environ_proxies.get("all"))
if proxy:
new_proxies.setdefault(scheme, proxy)
return new_proxies
def default_user_agent(name="python-requests"):
return f"{name}/{__version__}"
def default_headers():
return CaseInsensitiveDict(
{
"User-Agent": default_user_agent(),
"Accept-Encoding": DEFAULT_ACCEPT_ENCODING,
"Accept": "*/*",
"Connection": "keep-alive",
}
)
def parse_header_links(value):
links = []
replace_chars = " '\""
value = value.strip(replace_chars)
if not value:
return links
for val in re.split(", *<", value):
try:
url, params = val.split(";", 1)
except ValueError:
url, params = val, ""
link = {"url": url.strip("<> '\"")}
for param in params.split(";"):
try:
key, value = param.split("=")
except ValueError:
break
link[key.strip(replace_chars)] = value.strip(replace_chars)
links.append(link)
return links
# Null bytes; no need to recreate these on each call to guess_json_utf
_null = "\x00".encode("ascii") # encoding to ASCII for Python 3
_null2 = _null * 2
_null3 = _null * 3
def guess_json_utf(data):
# JSON always starts with two ASCII characters, so detection is as
# easy as counting the nulls and from their location and count
# determine the encoding. Also detect a BOM, if present.
sample = data[:4]
if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
return "utf-32" # BOM included
if sample[:3] == codecs.BOM_UTF8:
return "utf-8-sig" # BOM included, MS style (discouraged)
if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
return "utf-16" # BOM included
nullcount = sample.count(_null)
if nullcount == 0:
return "utf-8"
if nullcount == 2:
if sample[::2] == _null2: # 1st and 3rd are null
return "utf-16-be"
if sample[1::2] == _null2: # 2nd and 4th are null
return "utf-16-le"
# Did not detect 2 valid UTF-16 ascii-range characters
if nullcount == 3:
if sample[:3] == _null3:
return "utf-32-be"
if sample[1:] == _null3:
return "utf-32-le"
# Did not detect a valid UTF-32 ascii-range character
return None
def prepend_scheme_if_needed(url, new_scheme):
parsed = parse_url(url)
scheme, auth, host, port, path, query, fragment = parsed
# A defect in urlparse determines that there isn't a netloc present in some
# urls. We previously assumed parsing was overly cautious, and swapped the
# netloc and path. Due to a lack of tests on the original defect, this is
# maintained with parse_url for backwards compatibility.
netloc = parsed.netloc
if not netloc:
netloc, path = path, netloc
if auth:
# parse_url doesn't provide the netloc with auth
# so we'll add it ourselves.
netloc = "@".join([auth, netloc])
if scheme is None:
scheme = new_scheme
if path is None:
path = ""
return urlunparse((scheme, netloc, path, "", query, fragment))
def get_auth_from_url(url):
parsed = urlparse(url)
try:
auth = (unquote(parsed.username), unquote(parsed.password))
except (AttributeError, TypeError):
auth = ("", "")
return auth
def check_header_validity(header):
name, value = header
_validate_header_part(header, name, 0)
_validate_header_part(header, value, 1)
def _validate_header_part(header, header_part, header_validator_index):
if isinstance(header_part, str):
validator = _HEADER_VALIDATORS_STR[header_validator_index]
elif isinstance(header_part, bytes):
validator = _HEADER_VALIDATORS_BYTE[header_validator_index]
else:
raise InvalidHeader(
f"Header part ({header_part!r}) from {header} "
f"must be of type str or bytes, not {type(header_part)}"
)
if not validator.match(header_part):
header_kind = "name" if header_validator_index == 0 else "value"
raise InvalidHeader(
f"Invalid leading whitespace, reserved character(s), or return "
f"character(s) in header {header_kind}: {header_part!r}"
)
def urldefragauth(url):
scheme, netloc, path, params, query, fragment = urlparse(url)
# see func:`prepend_scheme_if_needed`
if not netloc:
netloc, path = path, netloc
netloc = netloc.rsplit("@", 1)[-1]
return urlunparse((scheme, netloc, path, params, query, ""))
def rewind_body(prepared_request):
body_seek = getattr(prepared_request.body, "seek", None)
if body_seek is not None and isinstance(
prepared_request._body_position, integer_types
):
try:
body_seek(prepared_request._body_position)
except OSError:
raise UnrewindableBodyError(
"An error occurred when rewinding request body for redirect."
)
else:
raise UnrewindableBodyError("Unable to rewind request body for redirect.") | --- +++ @@ -1,3 +1,10 @@+"""
+requests.utils
+~~~~~~~~~~~~~~
+
+This module provides utility functions that are used within Requests
+that are also useful for external consumption.
+"""
import codecs
import contextlib
@@ -104,6 +111,11 @@ return False
def proxy_bypass(host): # noqa
+ """Return True, if the host should be bypassed.
+
+ Checks proxy settings gathered from the environment, if specified,
+ or the registry.
+ """
if getproxies_environment():
return proxy_bypass_environment(host)
else:
@@ -111,6 +123,7 @@
def dict_to_sequence(d):
+ """Returns an internal sequence dictionary update."""
if hasattr(d, "items"):
d = d.items()
@@ -190,6 +203,7 @@
def get_netrc_auth(url, raise_errors=False):
+ """Returns the Requests tuple auth for a given url from netrc."""
netrc_file = os.environ.get("NETRC")
if netrc_file is not None:
@@ -233,12 +247,17 @@
def guess_filename(obj):
+ """Tries to guess the filename of the given object."""
name = getattr(obj, "name", None)
if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">":
return os.path.basename(name)
def extract_zipped_paths(path):
+ """Replace nonexistent paths that look like they refer to a member of a zip
+ archive with the location of an extracted copy of the target, or else
+ just return the provided path unchanged.
+ """
if os.path.exists(path):
# this is already a valid path, no need to do anything further
return path
@@ -273,6 +292,7 @@
@contextlib.contextmanager
def atomic_open(filename):
+ """Write a file to the disk in an atomic fashion"""
tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))
try:
with os.fdopen(tmp_descriptor, "wb") as tmp_handler:
@@ -284,6 +304,23 @@
def from_key_val_list(value):
+ """Take an object and test to see if it can be represented as a
+ dictionary. Unless it can not be represented as such, return an
+ OrderedDict, e.g.,
+
+ ::
+
+ >>> from_key_val_list([('key', 'val')])
+ OrderedDict([('key', 'val')])
+ >>> from_key_val_list('string')
+ Traceback (most recent call last):
+ ...
+ ValueError: cannot encode objects that are not 2-tuples
+ >>> from_key_val_list({'key': 'val'})
+ OrderedDict([('key', 'val')])
+
+ :rtype: OrderedDict
+ """
if value is None:
return None
@@ -294,6 +331,22 @@
def to_key_val_list(value):
+ """Take an object and test to see if it can be represented as a
+ dictionary. If it can be, return a list of tuples, e.g.,
+
+ ::
+
+ >>> to_key_val_list([('key', 'val')])
+ [('key', 'val')]
+ >>> to_key_val_list({'key': 'val'})
+ [('key', 'val')]
+ >>> to_key_val_list('string')
+ Traceback (most recent call last):
+ ...
+ ValueError: cannot encode objects that are not 2-tuples
+
+ :rtype: list
+ """
if value is None:
return None
@@ -308,6 +361,28 @@
# From mitsuhiko/werkzeug (used with permission).
def parse_list_header(value):
+ """Parse lists as described by RFC 2068 Section 2.
+
+ In particular, parse comma-separated lists where the elements of
+ the list may include quoted-strings. A quoted-string could
+ contain a comma. A non-quoted string could have quotes in the
+ middle. Quotes are removed automatically after parsing.
+
+ It basically works like :func:`parse_set_header` just that items
+ may appear multiple times and case sensitivity is preserved.
+
+ The return value is a standard :class:`list`:
+
+ >>> parse_list_header('token, "quoted value"')
+ ['token', 'quoted value']
+
+ To create a header from the :class:`list` again, use the
+ :func:`dump_header` function.
+
+ :param value: a string with a list header.
+ :return: :class:`list`
+ :rtype: list
+ """
result = []
for item in _parse_list_header(value):
if item[:1] == item[-1:] == '"':
@@ -318,6 +393,27 @@
# From mitsuhiko/werkzeug (used with permission).
def parse_dict_header(value):
+ """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
+ convert them into a python dict:
+
+ >>> d = parse_dict_header('foo="is a fish", bar="as well"')
+ >>> type(d) is dict
+ True
+ >>> sorted(d.items())
+ [('bar', 'as well'), ('foo', 'is a fish')]
+
+ If there is no value for a key it will be `None`:
+
+ >>> parse_dict_header('key_without_value')
+ {'key_without_value': None}
+
+ To create a header from the :class:`dict` again, use the
+ :func:`dump_header` function.
+
+ :param value: a string with a dict header.
+ :return: :class:`dict`
+ :rtype: dict
+ """
result = {}
for item in _parse_list_header(value):
if "=" not in item:
@@ -332,6 +428,13 @@
# From mitsuhiko/werkzeug (used with permission).
def unquote_header_value(value, is_filename=False):
+ r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
+ This does not use the real unquoting but what browsers are actually
+ using for quoting.
+
+ :param value: the header value to unquote.
+ :rtype: str
+ """
if value and value[0] == value[-1] == '"':
# this is not the real unquoting, but fixing this so that the
# RFC is met will result in bugs with internet explorer and
@@ -350,17 +453,32 @@
def dict_from_cookiejar(cj):
+ """Returns a key/value dictionary from a CookieJar.
+
+ :param cj: CookieJar object to extract cookies from.
+ :rtype: dict
+ """
cookie_dict = {cookie.name: cookie.value for cookie in cj}
return cookie_dict
def add_dict_to_cookiejar(cj, cookie_dict):
+ """Returns a CookieJar from a key/value dictionary.
+
+ :param cj: CookieJar to insert cookies into.
+ :param cookie_dict: Dict of key/values to insert into CookieJar.
+ :rtype: CookieJar
+ """
return cookiejar_from_dict(cookie_dict, cj)
def get_encodings_from_content(content):
+ """Returns encodings from given content string.
+
+ :param content: bytestring to extract encodings from.
+ """
warnings.warn(
(
"In requests 3.0, get_encodings_from_content will be removed. For "
@@ -382,6 +500,12 @@
def _parse_content_type_header(header):
+ """Returns content type and parameters from given header
+
+ :param header: string
+ :return: tuple containing content type and dictionary of
+ parameters
+ """
tokens = header.split(";")
content_type, params = tokens[0].strip(), tokens[1:]
@@ -401,6 +525,11 @@
def get_encoding_from_headers(headers):
+ """Returns encodings from given HTTP Header Dict.
+
+ :param headers: dictionary to extract encoding from.
+ :rtype: str
+ """
content_type = headers.get("content-type")
@@ -421,6 +550,7 @@
def stream_decode_response_unicode(iterator, r):
+ """Stream decodes an iterator."""
if r.encoding is None:
yield from iterator
@@ -437,6 +567,7 @@
def iter_slices(string, slice_length):
+ """Iterate over slices of a string."""
pos = 0
if slice_length is None or slice_length <= 0:
slice_length = len(string)
@@ -446,6 +577,17 @@
def get_unicode_from_response(r):
+ """Returns the requested content back in unicode.
+
+ :param r: Response object to get unicode content from.
+
+ Tried:
+
+ 1. charset from content-type
+ 2. fall back and replace all unicode characters
+
+ :rtype: str
+ """
warnings.warn(
(
"In requests 3.0, get_unicode_from_response will be removed. For "
@@ -480,6 +622,11 @@
def unquote_unreserved(uri):
+ """Un-escape any percent-escape sequences in a URI that are unreserved
+ characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
+
+ :rtype: str
+ """
parts = uri.split("%")
for i in range(1, len(parts)):
h = parts[i][0:2]
@@ -499,6 +646,13 @@
def requote_uri(uri):
+ """Re-quote the given URI.
+
+ This function passes the given URI through an unquote/quote cycle to
+ ensure that it is fully and consistently quoted.
+
+ :rtype: str
+ """
safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
safe_without_percent = "!#$&'()*+,/:;=?@[]~"
try:
@@ -514,6 +668,13 @@
def address_in_network(ip, net):
+ """This function allows you to check if an IP belongs to a network subnet
+
+ Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
+ returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
+
+ :rtype: bool
+ """
ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0]
netaddr, bits = net.split("/")
netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]
@@ -522,11 +683,20 @@
def dotted_netmask(mask):
+ """Converts mask from /xx format to xxx.xxx.xxx.xxx
+
+ Example: if mask is 24 function returns 255.255.255.0
+
+ :rtype: str
+ """
bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1
return socket.inet_ntoa(struct.pack(">I", bits))
def is_ipv4_address(string_ip):
+ """
+ :rtype: bool
+ """
try:
socket.inet_aton(string_ip)
except OSError:
@@ -535,6 +705,11 @@
def is_valid_cidr(string_network):
+ """
+ Very simple check of the cidr format in no_proxy variable.
+
+ :rtype: bool
+ """
if string_network.count("/") == 1:
try:
mask = int(string_network.split("/")[1])
@@ -555,6 +730,12 @@
@contextlib.contextmanager
def set_environ(env_name, value):
+ """Set the environment variable 'env_name' to 'value'
+
+ Save previous value, yield, and then restore the previous value stored in
+ the environment variable 'env_name'.
+
+ If 'value' is None, do nothing"""
value_changed = value is not None
if value_changed:
old_value = os.environ.get(env_name)
@@ -570,6 +751,11 @@
def should_bypass_proxies(url, no_proxy):
+ """
+ Returns whether we should bypass proxies or not.
+
+ :rtype: bool
+ """
# Prioritize lowercase environment variables over uppercase
# to keep a consistent behaviour with other http projects (curl, wget).
@@ -626,6 +812,11 @@
def get_environ_proxies(url, no_proxy=None):
+ """
+ Return a dict of environment proxies.
+
+ :rtype: dict
+ """
if should_bypass_proxies(url, no_proxy=no_proxy):
return {}
else:
@@ -633,6 +824,11 @@
def select_proxy(url, proxies):
+ """Select a proxy for the url, if applicable.
+
+ :param url: The url being for the request
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
+ """
proxies = proxies or {}
urlparts = urlparse(url)
if urlparts.hostname is None:
@@ -654,6 +850,16 @@
def resolve_proxies(request, proxies, trust_env=True):
+ """This method takes proxy information from a request and configuration
+ input to resolve a mapping of target proxies. This will consider settings
+ such as NO_PROXY to strip proxy configurations.
+
+ :param request: Request or PreparedRequest
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
+ :param trust_env: Boolean declaring whether to trust environment configs
+
+ :rtype: dict
+ """
proxies = proxies if proxies is not None else {}
url = request.url
scheme = urlparse(url).scheme
@@ -671,10 +877,18 @@
def default_user_agent(name="python-requests"):
+ """
+ Return a string representing the default user agent.
+
+ :rtype: str
+ """
return f"{name}/{__version__}"
def default_headers():
+ """
+ :rtype: requests.structures.CaseInsensitiveDict
+ """
return CaseInsensitiveDict(
{
"User-Agent": default_user_agent(),
@@ -686,6 +900,12 @@
def parse_header_links(value):
+ """Return a list of parsed link headers proxies.
+
+ i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
+
+ :rtype: list
+ """
links = []
@@ -723,6 +943,9 @@
def guess_json_utf(data):
+ """
+ :rtype: str
+ """
# JSON always starts with two ASCII characters, so detection is as
# easy as counting the nulls and from their location and count
# determine the encoding. Also detect a BOM, if present.
@@ -752,6 +975,11 @@
def prepend_scheme_if_needed(url, new_scheme):
+ """Given a URL that may or may not have a scheme, prepend the given scheme.
+ Does not replace a present scheme with the one provided as an argument.
+
+ :rtype: str
+ """
parsed = parse_url(url)
scheme, auth, host, port, path, query, fragment = parsed
@@ -776,6 +1004,11 @@
def get_auth_from_url(url):
+ """Given a url with authentication components, extract them into a tuple of
+ username,password.
+
+ :rtype: (str,str)
+ """
parsed = urlparse(url)
try:
@@ -787,6 +1020,11 @@
def check_header_validity(header):
+ """Verifies that header parts don't contain leading whitespace
+ reserved characters, or return characters.
+
+ :param header: tuple, in the format (name, value).
+ """
name, value = header
_validate_header_part(header, name, 0)
_validate_header_part(header, value, 1)
@@ -812,6 +1050,11 @@
def urldefragauth(url):
+ """
+ Given a url remove the fragment and the authentication part.
+
+ :rtype: str
+ """
scheme, netloc, path, params, query, fragment = urlparse(url)
# see func:`prepend_scheme_if_needed`
@@ -824,6 +1067,9 @@
def rewind_body(prepared_request):
+ """Move file pointer back to its recorded starting position
+ so it can be read again on redirect.
+ """
body_seek = getattr(prepared_request.body, "seek", None)
if body_seek is not None and isinstance(
prepared_request._body_position, integer_types
@@ -835,4 +1081,4 @@ "An error occurred when rewinding request body for redirect."
)
else:
- raise UnrewindableBodyError("Unable to rewind request body for redirect.")+ raise UnrewindableBodyError("Unable to rewind request body for redirect.")
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/utils.py |
Document functions with detailed explanations |
import os
import sys
import time
from collections import OrderedDict
from datetime import timedelta
from ._internal_utils import to_native_string
from .adapters import HTTPAdapter
from .auth import _basic_auth_str
from .compat import Mapping, cookielib, urljoin, urlparse
from .cookies import (
RequestsCookieJar,
cookiejar_from_dict,
extract_cookies_to_jar,
merge_cookies,
)
from .exceptions import (
ChunkedEncodingError,
ContentDecodingError,
InvalidSchema,
TooManyRedirects,
)
from .hooks import default_hooks, dispatch_hook
# formerly defined here, reexposed here for backward compatibility
from .models import ( # noqa: F401
DEFAULT_REDIRECT_LIMIT,
REDIRECT_STATI,
PreparedRequest,
Request,
)
from .status_codes import codes
from .structures import CaseInsensitiveDict
from .utils import ( # noqa: F401
DEFAULT_PORTS,
default_headers,
get_auth_from_url,
get_environ_proxies,
get_netrc_auth,
requote_uri,
resolve_proxies,
rewind_body,
should_bypass_proxies,
to_key_val_list,
)
# Preferred clock, based on which one is more accurate on a given system.
if sys.platform == "win32":
preferred_clock = time.perf_counter
else:
preferred_clock = time.time
def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
if session_setting is None:
return request_setting
if request_setting is None:
return session_setting
# Bypass if not a dictionary (e.g. verify)
if not (
isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)
):
return request_setting
merged_setting = dict_class(to_key_val_list(session_setting))
merged_setting.update(to_key_val_list(request_setting))
# Remove keys that are set to None. Extract keys first to avoid altering
# the dictionary during iteration.
none_keys = [k for (k, v) in merged_setting.items() if v is None]
for key in none_keys:
del merged_setting[key]
return merged_setting
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
if session_hooks is None or session_hooks.get("response") == []:
return request_hooks
if request_hooks is None or request_hooks.get("response") == []:
return session_hooks
return merge_setting(request_hooks, session_hooks, dict_class)
class SessionRedirectMixin:
def get_redirect_target(self, resp):
# Due to the nature of how requests processes redirects this method will
# be called at least once upon the original response and at least twice
# on each subsequent redirect response (if any).
# If a custom mixin is used to handle this logic, it may be advantageous
# to cache the redirect location onto the response object as a private
# attribute.
if resp.is_redirect:
location = resp.headers["location"]
# Currently the underlying http module on py3 decode headers
# in latin1, but empirical evidence suggests that latin1 is very
# rarely used with non-ASCII characters in HTTP headers.
# It is more likely to get UTF8 header rather than latin1.
# This causes incorrect handling of UTF8 encoded location headers.
# To solve this, we re-encode the location in latin1.
location = location.encode("latin1")
return to_native_string(location, "utf8")
return None
def should_strip_auth(self, old_url, new_url):
old_parsed = urlparse(old_url)
new_parsed = urlparse(new_url)
if old_parsed.hostname != new_parsed.hostname:
return True
# Special case: allow http -> https redirect when using the standard
# ports. This isn't specified by RFC 7235, but is kept to avoid
# breaking backwards compatibility with older versions of requests
# that allowed any redirects on the same host.
if (
old_parsed.scheme == "http"
and old_parsed.port in (80, None)
and new_parsed.scheme == "https"
and new_parsed.port in (443, None)
):
return False
# Handle default port usage corresponding to scheme.
changed_port = old_parsed.port != new_parsed.port
changed_scheme = old_parsed.scheme != new_parsed.scheme
default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)
if (
not changed_scheme
and old_parsed.port in default_port
and new_parsed.port in default_port
):
return False
# Standard case: root URI must match
return changed_port or changed_scheme
def resolve_redirects(
self,
resp,
req,
stream=False,
timeout=None,
verify=True,
cert=None,
proxies=None,
yield_requests=False,
**adapter_kwargs,
):
hist = [] # keep track of history
url = self.get_redirect_target(resp)
previous_fragment = urlparse(req.url).fragment
while url:
prepared_request = req.copy()
# Update history and keep track of redirects.
# resp.history must ignore the original request in this loop
hist.append(resp)
resp.history = hist[1:]
try:
resp.content # Consume socket so it can be released
except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
resp.raw.read(decode_content=False)
if len(resp.history) >= self.max_redirects:
raise TooManyRedirects(
f"Exceeded {self.max_redirects} redirects.", response=resp
)
# Release the connection back into the pool.
resp.close()
# Handle redirection without scheme (see: RFC 1808 Section 4)
if url.startswith("//"):
parsed_rurl = urlparse(resp.url)
url = ":".join([to_native_string(parsed_rurl.scheme), url])
# Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)
parsed = urlparse(url)
if parsed.fragment == "" and previous_fragment:
parsed = parsed._replace(fragment=previous_fragment)
elif parsed.fragment:
previous_fragment = parsed.fragment
url = parsed.geturl()
# Facilitate relative 'location' headers, as allowed by RFC 7231.
# (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
# Compliant with RFC3986, we percent encode the url.
if not parsed.netloc:
url = urljoin(resp.url, requote_uri(url))
else:
url = requote_uri(url)
prepared_request.url = to_native_string(url)
self.rebuild_method(prepared_request, resp)
# https://github.com/psf/requests/issues/1084
if resp.status_code not in (
codes.temporary_redirect,
codes.permanent_redirect,
):
# https://github.com/psf/requests/issues/3490
purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding")
for header in purged_headers:
prepared_request.headers.pop(header, None)
prepared_request.body = None
headers = prepared_request.headers
headers.pop("Cookie", None)
# Extract any cookies sent on the response to the cookiejar
# in the new request. Because we've mutated our copied prepared
# request, use the old one that we haven't yet touched.
extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)
merge_cookies(prepared_request._cookies, self.cookies)
prepared_request.prepare_cookies(prepared_request._cookies)
# Rebuild auth and proxy information.
proxies = self.rebuild_proxies(prepared_request, proxies)
self.rebuild_auth(prepared_request, resp)
# A failed tell() sets `_body_position` to `object()`. This non-None
# value ensures `rewindable` will be True, allowing us to raise an
# UnrewindableBodyError, instead of hanging the connection.
rewindable = prepared_request._body_position is not None and (
"Content-Length" in headers or "Transfer-Encoding" in headers
)
# Attempt to rewind consumed file-like object.
if rewindable:
rewind_body(prepared_request)
# Override the original request.
req = prepared_request
if yield_requests:
yield req
else:
resp = self.send(
req,
stream=stream,
timeout=timeout,
verify=verify,
cert=cert,
proxies=proxies,
allow_redirects=False,
**adapter_kwargs,
)
extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
# extract redirect url, if any, for the next loop
url = self.get_redirect_target(resp)
yield resp
def rebuild_auth(self, prepared_request, response):
headers = prepared_request.headers
url = prepared_request.url
if "Authorization" in headers and self.should_strip_auth(
response.request.url, url
):
# If we get redirected to a new host, we should strip out any
# authentication headers.
del headers["Authorization"]
# .netrc might have more auth for us on our new host.
new_auth = get_netrc_auth(url) if self.trust_env else None
if new_auth is not None:
prepared_request.prepare_auth(new_auth)
def rebuild_proxies(self, prepared_request, proxies):
headers = prepared_request.headers
scheme = urlparse(prepared_request.url).scheme
new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)
if "Proxy-Authorization" in headers:
del headers["Proxy-Authorization"]
try:
username, password = get_auth_from_url(new_proxies[scheme])
except KeyError:
username, password = None, None
# urllib3 handles proxy authorization for us in the standard adapter.
# Avoid appending this to TLS tunneled requests where it may be leaked.
if not scheme.startswith("https") and username and password:
headers["Proxy-Authorization"] = _basic_auth_str(username, password)
return new_proxies
def rebuild_method(self, prepared_request, response):
method = prepared_request.method
# https://tools.ietf.org/html/rfc7231#section-6.4.4
if response.status_code == codes.see_other and method != "HEAD":
method = "GET"
# Do what the browsers do, despite standards...
# First, turn 302s into GETs.
if response.status_code == codes.found and method != "HEAD":
method = "GET"
# Second, if a POST is responded to with a 301, turn it into a GET.
# This bizarre behaviour is explained in Issue 1704.
if response.status_code == codes.moved and method == "POST":
method = "GET"
prepared_request.method = method
class Session(SessionRedirectMixin):
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
def __init__(self):
#: A case-insensitive dictionary of headers to be sent on each
#: :class:`Request <Request>` sent from this
#: :class:`Session <Session>`.
self.headers = default_headers()
#: Default Authentication tuple or object to attach to
#: :class:`Request <Request>`.
self.auth = None
#: Dictionary mapping protocol or protocol and host to the URL of the proxy
#: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
#: be used on each :class:`Request <Request>`.
self.proxies = {}
#: Event-handling hooks.
self.hooks = default_hooks()
#: Dictionary of querystring data to attach to each
#: :class:`Request <Request>`. The dictionary values may be lists for
#: representing multivalued query parameters.
self.params = {}
#: Stream response content default.
self.stream = False
#: SSL Verification default.
#: Defaults to `True`, requiring requests to verify the TLS certificate at the
#: remote end.
#: If verify is set to `False`, requests will accept any TLS certificate
#: presented by the server, and will ignore hostname mismatches and/or
#: expired certificates, which will make your application vulnerable to
#: man-in-the-middle (MitM) attacks.
#: Only set this to `False` for testing.
#: If verify is set to a string, it must be the path to a CA bundle file
#: that will be used to verify the TLS certificate.
self.verify = True
#: SSL client certificate default, if String, path to ssl client
#: cert file (.pem). If Tuple, ('cert', 'key') pair.
self.cert = None
#: Maximum number of redirects allowed. If the request exceeds this
#: limit, a :class:`TooManyRedirects` exception is raised.
#: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
#: 30.
self.max_redirects = DEFAULT_REDIRECT_LIMIT
#: Trust environment settings for proxy configuration, default
#: authentication and similar.
self.trust_env = True
#: A CookieJar containing all currently outstanding cookies set on this
#: session. By default it is a
#: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
#: may be any other ``cookielib.CookieJar`` compatible object.
self.cookies = cookiejar_from_dict({})
# Default connection adapters.
self.adapters = OrderedDict()
self.mount("https://", HTTPAdapter())
self.mount("http://", HTTPAdapter())
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def prepare_request(self, request):
cookies = request.cookies or {}
# Bootstrap CookieJar.
if not isinstance(cookies, cookielib.CookieJar):
cookies = cookiejar_from_dict(cookies)
# Merge with session cookies
merged_cookies = merge_cookies(
merge_cookies(RequestsCookieJar(), self.cookies), cookies
)
# Set environment's basic authentication if not explicitly set.
auth = request.auth
if self.trust_env and not auth and not self.auth:
auth = get_netrc_auth(request.url)
p = PreparedRequest()
p.prepare(
method=request.method.upper(),
url=request.url,
files=request.files,
data=request.data,
json=request.json,
headers=merge_setting(
request.headers, self.headers, dict_class=CaseInsensitiveDict
),
params=merge_setting(request.params, self.params),
auth=merge_setting(auth, self.auth),
cookies=merged_cookies,
hooks=merge_hooks(request.hooks, self.hooks),
)
return p
def request(
self,
method,
url,
params=None,
data=None,
headers=None,
cookies=None,
files=None,
auth=None,
timeout=None,
allow_redirects=True,
proxies=None,
hooks=None,
stream=None,
verify=None,
cert=None,
json=None,
):
# Create the Request.
req = Request(
method=method.upper(),
url=url,
headers=headers,
files=files,
data=data or {},
json=json,
params=params or {},
auth=auth,
cookies=cookies,
hooks=hooks,
)
prep = self.prepare_request(req)
proxies = proxies or {}
settings = self.merge_environment_settings(
prep.url, proxies, stream, verify, cert
)
# Send the request.
send_kwargs = {
"timeout": timeout,
"allow_redirects": allow_redirects,
}
send_kwargs.update(settings)
resp = self.send(prep, **send_kwargs)
return resp
def get(self, url, **kwargs):
kwargs.setdefault("allow_redirects", True)
return self.request("GET", url, **kwargs)
def options(self, url, **kwargs):
kwargs.setdefault("allow_redirects", True)
return self.request("OPTIONS", url, **kwargs)
def head(self, url, **kwargs):
kwargs.setdefault("allow_redirects", False)
return self.request("HEAD", url, **kwargs)
def post(self, url, data=None, json=None, **kwargs):
return self.request("POST", url, data=data, json=json, **kwargs)
def put(self, url, data=None, **kwargs):
return self.request("PUT", url, data=data, **kwargs)
def patch(self, url, data=None, **kwargs):
return self.request("PATCH", url, data=data, **kwargs)
def delete(self, url, **kwargs):
return self.request("DELETE", url, **kwargs)
def send(self, request, **kwargs):
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault("stream", self.stream)
kwargs.setdefault("verify", self.verify)
kwargs.setdefault("cert", self.cert)
if "proxies" not in kwargs:
kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env)
# It's possible that users might accidentally send a Request object.
# Guard against that specific failure case.
if isinstance(request, Request):
raise ValueError("You can only send PreparedRequests.")
# Set up variables needed for resolve_redirects and dispatching of hooks
allow_redirects = kwargs.pop("allow_redirects", True)
stream = kwargs.get("stream")
hooks = request.hooks
# Get the appropriate adapter to use
adapter = self.get_adapter(url=request.url)
# Start time (approximately) of the request
start = preferred_clock()
# Send the request
r = adapter.send(request, **kwargs)
# Total elapsed time of the request (approximately)
elapsed = preferred_clock() - start
r.elapsed = timedelta(seconds=elapsed)
# Response manipulation hooks
r = dispatch_hook("response", hooks, r, **kwargs)
# Persist cookies
if r.history:
# If the hooks create history then we want those cookies too
for resp in r.history:
extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
extract_cookies_to_jar(self.cookies, request, r.raw)
# Resolve redirects if allowed.
if allow_redirects:
# Redirect resolving generator.
gen = self.resolve_redirects(r, request, **kwargs)
history = [resp for resp in gen]
else:
history = []
# Shuffle things around if there's history.
if history:
# Insert the first (original) request at the start
history.insert(0, r)
# Get the last request made
r = history.pop()
r.history = history
# If redirects aren't being followed, store the response on the Request for Response.next().
if not allow_redirects:
try:
r._next = next(
self.resolve_redirects(r, request, yield_requests=True, **kwargs)
)
except StopIteration:
pass
if not stream:
r.content
return r
def merge_environment_settings(self, url, proxies, stream, verify, cert):
# Gather clues from the surrounding environment.
if self.trust_env:
# Set environment's proxies.
no_proxy = proxies.get("no_proxy") if proxies is not None else None
env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
for k, v in env_proxies.items():
proxies.setdefault(k, v)
# Look for requests environment configuration
# and be compatible with cURL.
if verify is True or verify is None:
verify = (
os.environ.get("REQUESTS_CA_BUNDLE")
or os.environ.get("CURL_CA_BUNDLE")
or verify
)
# Merge all the kwargs.
proxies = merge_setting(proxies, self.proxies)
stream = merge_setting(stream, self.stream)
verify = merge_setting(verify, self.verify)
cert = merge_setting(cert, self.cert)
return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}
def get_adapter(self, url):
for prefix, adapter in self.adapters.items():
if url.lower().startswith(prefix.lower()):
return adapter
# Nothing matches :-/
raise InvalidSchema(f"No connection adapters were found for {url!r}")
def close(self):
for v in self.adapters.values():
v.close()
def mount(self, prefix, adapter):
self.adapters[prefix] = adapter
keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
for key in keys_to_move:
self.adapters[key] = self.adapters.pop(key)
def __getstate__(self):
state = {attr: getattr(self, attr, None) for attr in self.__attrs__}
return state
def __setstate__(self, state):
for attr, value in state.items():
setattr(self, attr, value)
def session():
return Session() | --- +++ @@ -1,3 +1,10 @@+"""
+requests.sessions
+~~~~~~~~~~~~~~~~~
+
+This module provides a Session object to manage and persist settings across
+requests (cookies, auth, proxies).
+"""
import os
import sys
@@ -53,6 +60,10 @@
def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
+ """Determines appropriate setting for a given request, taking into account
+ the explicit setting on that request, and the setting in the session. If a
+ setting is a dictionary, they will be merged together using `dict_class`
+ """
if session_setting is None:
return request_setting
@@ -79,6 +90,11 @@
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
+ """Properly merges both requests and session hooks.
+
+ This is necessary because when request_hooks == {'response': []}, the
+ merge breaks Session hooks entirely.
+ """
if session_hooks is None or session_hooks.get("response") == []:
return request_hooks
@@ -90,6 +106,7 @@
class SessionRedirectMixin:
def get_redirect_target(self, resp):
+ """Receives a Response. Returns a redirect URI or ``None``"""
# Due to the nature of how requests processes redirects this method will
# be called at least once upon the original response and at least twice
# on each subsequent redirect response (if any).
@@ -109,6 +126,7 @@ return None
def should_strip_auth(self, old_url, new_url):
+ """Decide whether Authorization header should be removed when redirecting"""
old_parsed = urlparse(old_url)
new_parsed = urlparse(new_url)
if old_parsed.hostname != new_parsed.hostname:
@@ -151,6 +169,7 @@ yield_requests=False,
**adapter_kwargs,
):
+ """Receives a Response. Returns a generator of Responses or Requests."""
hist = [] # keep track of history
@@ -262,6 +281,10 @@ yield resp
def rebuild_auth(self, prepared_request, response):
+ """When being redirected we may want to strip authentication from the
+ request to avoid leaking credentials. This method intelligently removes
+ and reapplies authentication where possible to avoid credential loss.
+ """
headers = prepared_request.headers
url = prepared_request.url
@@ -278,6 +301,17 @@ prepared_request.prepare_auth(new_auth)
def rebuild_proxies(self, prepared_request, proxies):
+ """This method re-evaluates the proxy configuration by considering the
+ environment variables. If we are redirected to a URL covered by
+ NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
+ proxy keys for this URL (in case they were stripped by a previous
+ redirect).
+
+ This method also replaces the Proxy-Authorization header where
+ necessary.
+
+ :rtype: dict
+ """
headers = prepared_request.headers
scheme = urlparse(prepared_request.url).scheme
new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)
@@ -298,6 +332,9 @@ return new_proxies
def rebuild_method(self, prepared_request, response):
+ """When being redirected we may want to change the method of the request
+ based on certain specs or browser behavior.
+ """
method = prepared_request.method
# https://tools.ietf.org/html/rfc7231#section-6.4.4
@@ -318,6 +355,23 @@
class Session(SessionRedirectMixin):
+ """A Requests session.
+
+ Provides cookie persistence, connection-pooling, and configuration.
+
+ Basic Usage::
+
+ >>> import requests
+ >>> s = requests.Session()
+ >>> s.get('https://httpbin.org/get')
+ <Response [200]>
+
+ Or as a context manager::
+
+ >>> with requests.Session() as s:
+ ... s.get('https://httpbin.org/get')
+ <Response [200]>
+ """
__attrs__ = [
"headers",
@@ -404,6 +458,15 @@ self.close()
def prepare_request(self, request):
+ """Constructs a :class:`PreparedRequest <PreparedRequest>` for
+ transmission and returns it. The :class:`PreparedRequest` has settings
+ merged from the :class:`Request <Request>` instance and those of the
+ :class:`Session`.
+
+ :param request: :class:`Request` instance to prepare with this
+ session's settings.
+ :rtype: requests.PreparedRequest
+ """
cookies = request.cookies or {}
# Bootstrap CookieJar.
@@ -456,6 +519,49 @@ cert=None,
json=None,
):
+ """Constructs a :class:`Request <Request>`, prepares it and sends it.
+ Returns :class:`Response <Response>` object.
+
+ :param method: method for the new :class:`Request` object.
+ :param url: URL for the new :class:`Request` object.
+ :param params: (optional) Dictionary or bytes to be sent in the query
+ string for the :class:`Request`.
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
+ object to send in the body of the :class:`Request`.
+ :param json: (optional) json to send in the body of the
+ :class:`Request`.
+ :param headers: (optional) Dictionary of HTTP Headers to send with the
+ :class:`Request`.
+ :param cookies: (optional) Dict or CookieJar object to send with the
+ :class:`Request`.
+ :param files: (optional) Dictionary of ``'filename': file-like-objects``
+ for multipart encoding upload.
+ :param auth: (optional) Auth tuple or callable to enable
+ Basic/Digest/Custom HTTP Auth.
+ :param timeout: (optional) How many seconds to wait for the server to send
+ data before giving up, as a float, or a :ref:`(connect timeout,
+ read timeout) <timeouts>` tuple.
+ :type timeout: float or tuple
+ :param allow_redirects: (optional) Set to True by default.
+ :type allow_redirects: bool
+ :param proxies: (optional) Dictionary mapping protocol or protocol and
+ hostname to the URL of the proxy.
+ :param hooks: (optional) Dictionary mapping hook name to one event or
+ list of events, event must be callable.
+ :param stream: (optional) whether to immediately download the response
+ content. Defaults to ``False``.
+ :param verify: (optional) Either a boolean, in which case it controls whether we verify
+ the server's TLS certificate, or a string, in which case it must be a path
+ to a CA bundle to use. Defaults to ``True``. When set to
+ ``False``, requests will accept any TLS certificate presented by
+ the server, and will ignore hostname mismatches and/or expired
+ certificates, which will make your application vulnerable to
+ man-in-the-middle (MitM) attacks. Setting verify to ``False``
+ may be useful during local development or testing.
+ :param cert: (optional) if String, path to ssl client cert file (.pem).
+ If Tuple, ('cert', 'key') pair.
+ :rtype: requests.Response
+ """
# Create the Request.
req = Request(
method=method.upper(),
@@ -488,37 +594,90 @@ return resp
def get(self, url, **kwargs):
+ r"""Sends a GET request. Returns :class:`Response` object.
+
+ :param url: URL for the new :class:`Request` object.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :rtype: requests.Response
+ """
kwargs.setdefault("allow_redirects", True)
return self.request("GET", url, **kwargs)
def options(self, url, **kwargs):
+ r"""Sends a OPTIONS request. Returns :class:`Response` object.
+
+ :param url: URL for the new :class:`Request` object.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :rtype: requests.Response
+ """
kwargs.setdefault("allow_redirects", True)
return self.request("OPTIONS", url, **kwargs)
def head(self, url, **kwargs):
+ r"""Sends a HEAD request. Returns :class:`Response` object.
+
+ :param url: URL for the new :class:`Request` object.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :rtype: requests.Response
+ """
kwargs.setdefault("allow_redirects", False)
return self.request("HEAD", url, **kwargs)
def post(self, url, data=None, json=None, **kwargs):
+ r"""Sends a POST request. Returns :class:`Response` object.
+
+ :param url: URL for the new :class:`Request` object.
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
+ object to send in the body of the :class:`Request`.
+ :param json: (optional) json to send in the body of the :class:`Request`.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :rtype: requests.Response
+ """
return self.request("POST", url, data=data, json=json, **kwargs)
def put(self, url, data=None, **kwargs):
+ r"""Sends a PUT request. Returns :class:`Response` object.
+
+ :param url: URL for the new :class:`Request` object.
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
+ object to send in the body of the :class:`Request`.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :rtype: requests.Response
+ """
return self.request("PUT", url, data=data, **kwargs)
def patch(self, url, data=None, **kwargs):
+ r"""Sends a PATCH request. Returns :class:`Response` object.
+
+ :param url: URL for the new :class:`Request` object.
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
+ object to send in the body of the :class:`Request`.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :rtype: requests.Response
+ """
return self.request("PATCH", url, data=data, **kwargs)
def delete(self, url, **kwargs):
+ r"""Sends a DELETE request. Returns :class:`Response` object.
+
+ :param url: URL for the new :class:`Request` object.
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
+ :rtype: requests.Response
+ """
return self.request("DELETE", url, **kwargs)
def send(self, request, **kwargs):
+ """Send a given PreparedRequest.
+
+ :rtype: requests.Response
+ """
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault("stream", self.stream)
@@ -592,6 +751,11 @@ return r
def merge_environment_settings(self, url, proxies, stream, verify, cert):
+ """
+ Check the environment and merge it with some settings.
+
+ :rtype: dict
+ """
# Gather clues from the surrounding environment.
if self.trust_env:
# Set environment's proxies.
@@ -618,6 +782,11 @@ return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}
def get_adapter(self, url):
+ """
+ Returns the appropriate connection adapter for the given URL.
+
+ :rtype: requests.adapters.BaseAdapter
+ """
for prefix, adapter in self.adapters.items():
if url.lower().startswith(prefix.lower()):
return adapter
@@ -626,10 +795,15 @@ raise InvalidSchema(f"No connection adapters were found for {url!r}")
def close(self):
+ """Closes all adapters and as such the session"""
for v in self.adapters.values():
v.close()
def mount(self, prefix, adapter):
+ """Registers a connection adapter to a prefix.
+
+ Adapters are sorted in descending order by prefix length.
+ """
self.adapters[prefix] = adapter
keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
@@ -646,4 +820,15 @@
def session():
- return Session()+ """
+ Returns a :class:`Session` for context-management.
+
+ .. deprecated:: 1.0.0
+
+ This method has been deprecated since version 1.0.0 and is only kept for
+ backwards compatibility. New code should use :class:`~requests.sessions.Session`
+ to create a session. This may be removed at a future date.
+
+ :rtype: Session
+ """
+ return Session()
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/sessions.py |
Can you add docstrings to this Python file? |
import calendar
import copy
import time
from ._internal_utils import to_native_string
from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse
try:
import threading
except ImportError:
import dummy_threading as threading
class MockRequest:
def __init__(self, request):
self._r = request
self._new_headers = {}
self.type = urlparse(self._r.url).scheme
def get_type(self):
return self.type
def get_host(self):
return urlparse(self._r.url).netloc
def get_origin_req_host(self):
return self.get_host()
def get_full_url(self):
# Only return the response's URL if the user hadn't set the Host
# header
if not self._r.headers.get("Host"):
return self._r.url
# If they did set it, retrieve it and reconstruct the expected domain
host = to_native_string(self._r.headers["Host"], encoding="utf-8")
parsed = urlparse(self._r.url)
# Reconstruct the URL as we expect it
return urlunparse(
[
parsed.scheme,
host,
parsed.path,
parsed.params,
parsed.query,
parsed.fragment,
]
)
def is_unverifiable(self):
return True
def has_header(self, name):
return name in self._r.headers or name in self._new_headers
def get_header(self, name, default=None):
return self._r.headers.get(name, self._new_headers.get(name, default))
def add_header(self, key, val):
raise NotImplementedError(
"Cookie headers should be added with add_unredirected_header()"
)
def add_unredirected_header(self, name, value):
self._new_headers[name] = value
def get_new_headers(self):
return self._new_headers
@property
def unverifiable(self):
return self.is_unverifiable()
@property
def origin_req_host(self):
return self.get_origin_req_host()
@property
def host(self):
return self.get_host()
class MockResponse:
def __init__(self, headers):
self._headers = headers
def info(self):
return self._headers
def getheaders(self, name):
self._headers.getheaders(name)
def extract_cookies_to_jar(jar, request, response):
if not (hasattr(response, "_original_response") and response._original_response):
return
# the _original_response field is the wrapped httplib.HTTPResponse object,
req = MockRequest(request)
# pull out the HTTPMessage with the headers and put it in the mock:
res = MockResponse(response._original_response.msg)
jar.extract_cookies(res, req)
def get_cookie_header(jar, request):
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get("Cookie")
def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
clearables = []
for cookie in cookiejar:
if cookie.name != name:
continue
if domain is not None and domain != cookie.domain:
continue
if path is not None and path != cookie.path:
continue
clearables.append((cookie.domain, cookie.path, cookie.name))
for domain, path, name in clearables:
cookiejar.clear(domain, path, name)
class CookieConflictError(RuntimeError):
class RequestsCookieJar(cookielib.CookieJar, MutableMapping):
def get(self, name, default=None, domain=None, path=None):
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default
def set(self, name, value, **kwargs):
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(
self, name, domain=kwargs.get("domain"), path=kwargs.get("path")
)
return
if isinstance(value, Morsel):
c = morsel_to_cookie(value)
else:
c = create_cookie(name, value, **kwargs)
self.set_cookie(c)
return c
def iterkeys(self):
for cookie in iter(self):
yield cookie.name
def keys(self):
return list(self.iterkeys())
def itervalues(self):
for cookie in iter(self):
yield cookie.value
def values(self):
return list(self.itervalues())
def iteritems(self):
for cookie in iter(self):
yield cookie.name, cookie.value
def items(self):
return list(self.iteritems())
def list_domains(self):
domains = []
for cookie in iter(self):
if cookie.domain not in domains:
domains.append(cookie.domain)
return domains
def list_paths(self):
paths = []
for cookie in iter(self):
if cookie.path not in paths:
paths.append(cookie.path)
return paths
def multiple_domains(self):
domains = []
for cookie in iter(self):
if cookie.domain is not None and cookie.domain in domains:
return True
domains.append(cookie.domain)
return False # there is only one domain in jar
def get_dict(self, domain=None, path=None):
dictionary = {}
for cookie in iter(self):
if (domain is None or cookie.domain == domain) and (
path is None or cookie.path == path
):
dictionary[cookie.name] = cookie.value
return dictionary
def __contains__(self, name):
try:
return super().__contains__(name)
except CookieConflictError:
return True
def __getitem__(self, name):
return self._find_no_duplicates(name)
def __setitem__(self, name, value):
self.set(name, value)
def __delitem__(self, name):
remove_cookie_by_name(self, name)
def set_cookie(self, cookie, *args, **kwargs):
if (
hasattr(cookie.value, "startswith")
and cookie.value.startswith('"')
and cookie.value.endswith('"')
):
cookie.value = cookie.value.replace('\\"', "")
return super().set_cookie(cookie, *args, **kwargs)
def update(self, other):
if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super().update(other)
def _find(self, name, domain=None, path=None):
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
return cookie.value
raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
def _find_no_duplicates(self, name, domain=None, path=None):
toReturn = None
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
if toReturn is not None:
# if there are multiple cookies that meet passed in criteria
raise CookieConflictError(
f"There are multiple cookies with name, {name!r}"
)
# we will eventually return this as long as no cookie conflict
toReturn = cookie.value
if toReturn:
return toReturn
raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
def __getstate__(self):
state = self.__dict__.copy()
# remove the unpickleable RLock object
state.pop("_cookies_lock")
return state
def __setstate__(self, state):
self.__dict__.update(state)
if "_cookies_lock" not in self.__dict__:
self._cookies_lock = threading.RLock()
def copy(self):
new_cj = RequestsCookieJar()
new_cj.set_policy(self.get_policy())
new_cj.update(self)
return new_cj
def get_policy(self):
return self._policy
def _copy_cookie_jar(jar):
if jar is None:
return None
if hasattr(jar, "copy"):
# We're dealing with an instance of RequestsCookieJar
return jar.copy()
# We're dealing with a generic CookieJar instance
new_jar = copy.copy(jar)
new_jar.clear()
for cookie in jar:
new_jar.set_cookie(copy.copy(cookie))
return new_jar
def create_cookie(name, value, **kwargs):
result = {
"version": 0,
"name": name,
"value": value,
"port": None,
"domain": "",
"path": "/",
"secure": False,
"expires": None,
"discard": True,
"comment": None,
"comment_url": None,
"rest": {"HttpOnly": None},
"rfc2109": False,
}
badargs = set(kwargs) - set(result)
if badargs:
raise TypeError(
f"create_cookie() got unexpected keyword arguments: {list(badargs)}"
)
result.update(kwargs)
result["port_specified"] = bool(result["port"])
result["domain_specified"] = bool(result["domain"])
result["domain_initial_dot"] = result["domain"].startswith(".")
result["path_specified"] = bool(result["path"])
return cookielib.Cookie(**result)
def morsel_to_cookie(morsel):
expires = None
if morsel["max-age"]:
try:
expires = int(time.time() + int(morsel["max-age"]))
except ValueError:
raise TypeError(f"max-age: {morsel['max-age']} must be integer")
elif morsel["expires"]:
time_template = "%a, %d-%b-%Y %H:%M:%S GMT"
expires = calendar.timegm(time.strptime(morsel["expires"], time_template))
return create_cookie(
comment=morsel["comment"],
comment_url=bool(morsel["comment"]),
discard=False,
domain=morsel["domain"],
expires=expires,
name=morsel.key,
path=morsel["path"],
port=None,
rest={"HttpOnly": morsel["httponly"]},
rfc2109=False,
secure=bool(morsel["secure"]),
value=morsel.value,
version=morsel["version"] or 0,
)
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
if cookiejar is None:
cookiejar = RequestsCookieJar()
if cookie_dict is not None:
names_from_jar = [cookie.name for cookie in cookiejar]
for name in cookie_dict:
if overwrite or (name not in names_from_jar):
cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
return cookiejar
def merge_cookies(cookiejar, cookies):
if not isinstance(cookiejar, cookielib.CookieJar):
raise ValueError("You can only merge into CookieJar")
if isinstance(cookies, dict):
cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)
elif isinstance(cookies, cookielib.CookieJar):
try:
cookiejar.update(cookies)
except AttributeError:
for cookie_in_jar in cookies:
cookiejar.set_cookie(cookie_in_jar)
return cookiejar | --- +++ @@ -1,3 +1,11 @@+"""
+requests.cookies
+~~~~~~~~~~~~~~~~
+
+Compatibility code to be able to use `http.cookiejar.CookieJar` with requests.
+
+requests.utils imports from here, so be careful with imports.
+"""
import calendar
import copy
@@ -13,6 +21,16 @@
class MockRequest:
+ """Wraps a `requests.Request` to mimic a `urllib2.Request`.
+
+ The code in `http.cookiejar.CookieJar` expects this interface in order to correctly
+ manage cookie policies, i.e., determine whether a cookie can be set, given the
+ domains of the request and the cookie.
+
+ The original request object is read-only. The client is responsible for collecting
+ the new headers via `get_new_headers()` and interpreting them appropriately. You
+ probably want `get_cookie_header`, defined below.
+ """
def __init__(self, request):
self._r = request
@@ -58,6 +76,7 @@ return self._r.headers.get(name, self._new_headers.get(name, default))
def add_header(self, key, val):
+ """cookiejar has no legitimate use for this method; add it back if you find one."""
raise NotImplementedError(
"Cookie headers should be added with add_unredirected_header()"
)
@@ -82,8 +101,17 @@
class MockResponse:
+ """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
+
+ ...what? Basically, expose the parsed HTTP headers from the server response
+ the way `http.cookiejar` expects to see them.
+ """
def __init__(self, headers):
+ """Make a MockResponse for `cookiejar` to read.
+
+ :param headers: a httplib.HTTPMessage or analogous carrying the headers
+ """
self._headers = headers
def info(self):
@@ -94,6 +122,12 @@
def extract_cookies_to_jar(jar, request, response):
+ """Extract the cookies from the response into a CookieJar.
+
+ :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)
+ :param request: our own requests.Request object
+ :param response: urllib3.HTTPResponse object
+ """
if not (hasattr(response, "_original_response") and response._original_response):
return
# the _original_response field is the wrapped httplib.HTTPResponse object,
@@ -104,12 +138,21 @@
def get_cookie_header(jar, request):
+ """
+ Produce an appropriate Cookie header string to be sent with `request`, or None.
+
+ :rtype: str
+ """
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get("Cookie")
def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
+ """Unsets a cookie by name, by default over all domains and paths.
+
+ Wraps CookieJar.clear(), is O(n).
+ """
clearables = []
for cookie in cookiejar:
if cookie.name != name:
@@ -125,17 +168,46 @@
class CookieConflictError(RuntimeError):
+ """There are two cookies that meet the criteria specified in the cookie jar.
+ Use .get and .set and include domain and path args in order to be more specific.
+ """
class RequestsCookieJar(cookielib.CookieJar, MutableMapping):
+ """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict
+ interface.
+
+ This is the CookieJar we create by default for requests and sessions that
+ don't specify one, since some clients may expect response.cookies and
+ session.cookies to support dict operations.
+
+ Requests does not use the dict interface internally; it's just for
+ compatibility with external client code. All requests code should work
+ out of the box with externally provided instances of ``CookieJar``, e.g.
+ ``LWPCookieJar`` and ``FileCookieJar``.
+
+ Unlike a regular CookieJar, this class is pickleable.
+
+ .. warning:: dictionary operations that are normally O(1) may be O(n).
+ """
def get(self, name, default=None, domain=None, path=None):
+ """Dict-like get() that also supports optional domain and path args in
+ order to resolve naming collisions from using one cookie jar over
+ multiple domains.
+
+ .. warning:: operation is O(n), not O(1).
+ """
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default
def set(self, name, value, **kwargs):
+ """Dict-like set() that also supports optional domain and path args in
+ order to resolve naming collisions from using one cookie jar over
+ multiple domains.
+ """
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(
@@ -151,27 +223,59 @@ return c
def iterkeys(self):
+ """Dict-like iterkeys() that returns an iterator of names of cookies
+ from the jar.
+
+ .. seealso:: itervalues() and iteritems().
+ """
for cookie in iter(self):
yield cookie.name
def keys(self):
+ """Dict-like keys() that returns a list of names of cookies from the
+ jar.
+
+ .. seealso:: values() and items().
+ """
return list(self.iterkeys())
def itervalues(self):
+ """Dict-like itervalues() that returns an iterator of values of cookies
+ from the jar.
+
+ .. seealso:: iterkeys() and iteritems().
+ """
for cookie in iter(self):
yield cookie.value
def values(self):
+ """Dict-like values() that returns a list of values of cookies from the
+ jar.
+
+ .. seealso:: keys() and items().
+ """
return list(self.itervalues())
def iteritems(self):
+ """Dict-like iteritems() that returns an iterator of name-value tuples
+ from the jar.
+
+ .. seealso:: iterkeys() and itervalues().
+ """
for cookie in iter(self):
yield cookie.name, cookie.value
def items(self):
+ """Dict-like items() that returns a list of name-value tuples from the
+ jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
+ vanilla python dict of key value pairs.
+
+ .. seealso:: keys() and values().
+ """
return list(self.iteritems())
def list_domains(self):
+ """Utility method to list all the domains in the jar."""
domains = []
for cookie in iter(self):
if cookie.domain not in domains:
@@ -179,6 +283,7 @@ return domains
def list_paths(self):
+ """Utility method to list all the paths in the jar."""
paths = []
for cookie in iter(self):
if cookie.path not in paths:
@@ -186,6 +291,11 @@ return paths
def multiple_domains(self):
+ """Returns True if there are multiple domains in the jar.
+ Returns False otherwise.
+
+ :rtype: bool
+ """
domains = []
for cookie in iter(self):
if cookie.domain is not None and cookie.domain in domains:
@@ -194,6 +304,12 @@ return False # there is only one domain in jar
def get_dict(self, domain=None, path=None):
+ """Takes as an argument an optional domain and path and returns a plain
+ old Python dict of name-value pairs of cookies that meet the
+ requirements.
+
+ :rtype: dict
+ """
dictionary = {}
for cookie in iter(self):
if (domain is None or cookie.domain == domain) and (
@@ -209,12 +325,25 @@ return True
def __getitem__(self, name):
+ """Dict-like __getitem__() for compatibility with client code. Throws
+ exception if there are more than one cookie with name. In that case,
+ use the more explicit get() method instead.
+
+ .. warning:: operation is O(n), not O(1).
+ """
return self._find_no_duplicates(name)
def __setitem__(self, name, value):
+ """Dict-like __setitem__ for compatibility with client code. Throws
+ exception if there is already a cookie of that name in the jar. In that
+ case, use the more explicit set() method instead.
+ """
self.set(name, value)
def __delitem__(self, name):
+ """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s
+ ``remove_cookie_by_name()``.
+ """
remove_cookie_by_name(self, name)
def set_cookie(self, cookie, *args, **kwargs):
@@ -227,6 +356,7 @@ return super().set_cookie(cookie, *args, **kwargs)
def update(self, other):
+ """Updates this jar with cookies from another CookieJar or dict-like"""
if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
@@ -234,6 +364,17 @@ super().update(other)
def _find(self, name, domain=None, path=None):
+ """Requests uses this method internally to get cookie values.
+
+ If there are conflicting cookies, _find arbitrarily chooses one.
+ See _find_no_duplicates if you want an exception thrown if there are
+ conflicting cookies.
+
+ :param name: a string containing name of cookie
+ :param domain: (optional) string containing domain of cookie
+ :param path: (optional) string containing path of cookie
+ :return: cookie.value
+ """
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
@@ -243,6 +384,17 @@ raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
def _find_no_duplicates(self, name, domain=None, path=None):
+ """Both ``__get_item__`` and ``get`` call this function: it's never
+ used elsewhere in Requests.
+
+ :param name: a string containing name of cookie
+ :param domain: (optional) string containing domain of cookie
+ :param path: (optional) string containing path of cookie
+ :raises KeyError: if cookie is not found
+ :raises CookieConflictError: if there are multiple cookies
+ that match name and optionally domain and path
+ :return: cookie.value
+ """
toReturn = None
for cookie in iter(self):
if cookie.name == name:
@@ -261,23 +413,27 @@ raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
def __getstate__(self):
+ """Unlike a normal CookieJar, this class is pickleable."""
state = self.__dict__.copy()
# remove the unpickleable RLock object
state.pop("_cookies_lock")
return state
def __setstate__(self, state):
+ """Unlike a normal CookieJar, this class is pickleable."""
self.__dict__.update(state)
if "_cookies_lock" not in self.__dict__:
self._cookies_lock = threading.RLock()
def copy(self):
+ """Return a copy of this RequestsCookieJar."""
new_cj = RequestsCookieJar()
new_cj.set_policy(self.get_policy())
new_cj.update(self)
return new_cj
def get_policy(self):
+ """Return the CookiePolicy instance used."""
return self._policy
@@ -297,6 +453,11 @@
def create_cookie(name, value, **kwargs):
+ """Make a cookie from underspecified parameters.
+
+ By default, the pair of `name` and `value` will be set for the domain ''
+ and sent on every request (this is sometimes called a "supercookie").
+ """
result = {
"version": 0,
"name": name,
@@ -329,6 +490,7 @@
def morsel_to_cookie(morsel):
+ """Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel["max-age"]:
@@ -357,6 +519,14 @@
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
+ """Returns a CookieJar from a key/value dictionary.
+
+ :param cookie_dict: Dict of key/values to insert into CookieJar.
+ :param cookiejar: (optional) A cookiejar to add the cookies to.
+ :param overwrite: (optional) If False, will not replace cookies
+ already in the jar with new ones.
+ :rtype: CookieJar
+ """
if cookiejar is None:
cookiejar = RequestsCookieJar()
@@ -370,6 +540,12 @@
def merge_cookies(cookiejar, cookies):
+ """Add cookies to cookiejar and returns a merged CookieJar.
+
+ :param cookiejar: CookieJar object to add the cookies to.
+ :param cookies: Dictionary or CookieJar object to be added.
+ :rtype: CookieJar
+ """
if not isinstance(cookiejar, cookielib.CookieJar):
raise ValueError("You can only merge into CookieJar")
@@ -382,4 +558,4 @@ for cookie_in_jar in cookies:
cookiejar.set_cookie(cookie_in_jar)
- return cookiejar+ return cookiejar
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/cookies.py |
Create docstrings for all classes and functions |
import re
from .compat import builtin_str
_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")
_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$")
_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$")
_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*$|^$")
_HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR)
_HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE)
HEADER_VALIDATORS = {
bytes: _HEADER_VALIDATORS_BYTE,
str: _HEADER_VALIDATORS_STR,
}
def to_native_string(string, encoding="ascii"):
if isinstance(string, builtin_str):
out = string
else:
out = string.decode(encoding)
return out
def unicode_is_ascii(u_string):
assert isinstance(u_string, str)
try:
u_string.encode("ascii")
return True
except UnicodeEncodeError:
return False | --- +++ @@ -1,3 +1,10 @@+"""
+requests._internal_utils
+~~~~~~~~~~~~~~
+
+Provides utility functions that are consumed internally by Requests
+which depend on extremely few external helpers (such as compat)
+"""
import re
@@ -17,6 +24,10 @@
def to_native_string(string, encoding="ascii"):
+ """Given a string object, regardless of type, returns a representation of
+ that string in the native string type, encoding and decoding where
+ necessary. This assumes ASCII unless told otherwise.
+ """
if isinstance(string, builtin_str):
out = string
else:
@@ -26,9 +37,15 @@
def unicode_is_ascii(u_string):
+ """Determine if unicode string only contains ASCII characters.
+
+ :param str u_string: unicode string to check. Must be unicode
+ and not Python 2 `str`.
+ :rtype: bool
+ """
assert isinstance(u_string, str)
try:
u_string.encode("ascii")
return True
except UnicodeEncodeError:
- return False+ return False
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/_internal_utils.py |
Write proper docstrings for these functions |
import importlib
import sys
# -------
# urllib3
# -------
from urllib3 import __version__ as urllib3_version
# Detect which major version of urllib3 is being used.
try:
is_urllib3_1 = int(urllib3_version.split(".")[0]) == 1
except (TypeError, AttributeError):
# If we can't discern a version, prefer old functionality.
is_urllib3_1 = True
# -------------------
# Character Detection
# -------------------
def _resolve_char_detection():
chardet = None
for lib in ("chardet", "charset_normalizer"):
if chardet is None:
try:
chardet = importlib.import_module(lib)
except ImportError:
pass
return chardet
chardet = _resolve_char_detection()
# -------
# Pythons
# -------
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = _ver[0] == 2
#: Python 3.x?
is_py3 = _ver[0] == 3
# json/simplejson module import resolution
has_simplejson = False
try:
import simplejson as json
has_simplejson = True
except ImportError:
import json
if has_simplejson:
from simplejson import JSONDecodeError
else:
from json import JSONDecodeError
# Keep OrderedDict for backwards compatibility.
from collections import OrderedDict
from collections.abc import Callable, Mapping, MutableMapping
from http import cookiejar as cookielib
from http.cookies import Morsel
from io import StringIO
# --------------
# Legacy Imports
# --------------
from urllib.parse import (
quote,
quote_plus,
unquote,
unquote_plus,
urldefrag,
urlencode,
urljoin,
urlparse,
urlsplit,
urlunparse,
)
from urllib.request import (
getproxies,
getproxies_environment,
parse_http_list,
proxy_bypass,
proxy_bypass_environment,
)
builtin_str = str
str = str
bytes = bytes
basestring = (str, bytes)
numeric_types = (int, float)
integer_types = (int,) | --- +++ @@ -1,3 +1,11 @@+"""
+requests.compat
+~~~~~~~~~~~~~~~
+
+This module previously handled import compatibility issues
+between Python 2 and Python 3. It remains for backwards
+compatibility until the next major version.
+"""
import importlib
import sys
@@ -20,6 +28,7 @@
def _resolve_char_detection():
+ """Find supported character detection libraries."""
chardet = None
for lib in ("chardet", "charset_normalizer"):
if chardet is None:
@@ -94,4 +103,4 @@ bytes = bytes
basestring = (str, bytes)
numeric_types = (int, float)
-integer_types = (int,)+integer_types = (int,)
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/compat.py |
Generate NumPy-style docstrings |
from collections import OrderedDict
from .compat import Mapping, MutableMapping
class CaseInsensitiveDict(MutableMapping):
def __init__(self, data=None, **kwargs):
self._store = OrderedDict()
if data is None:
data = {}
self.update(data, **kwargs)
def __setitem__(self, key, value):
# Use the lowercased key for lookups, but store the actual
# key alongside the value.
self._store[key.lower()] = (key, value)
def __getitem__(self, key):
return self._store[key.lower()][1]
def __delitem__(self, key):
del self._store[key.lower()]
def __iter__(self):
return (casedkey for casedkey, mappedvalue in self._store.values())
def __len__(self):
return len(self._store)
def lower_items(self):
return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
def __eq__(self, other):
if isinstance(other, Mapping):
other = CaseInsensitiveDict(other)
else:
return NotImplemented
# Compare insensitively
return dict(self.lower_items()) == dict(other.lower_items())
# Copy is required
def copy(self):
return CaseInsensitiveDict(self._store.values())
def __repr__(self):
return str(dict(self.items()))
class LookupDict(dict):
def __init__(self, name=None):
self.name = name
super().__init__()
def __repr__(self):
return f"<lookup '{self.name}'>"
def __getitem__(self, key):
# We allow fall-through here, so values default to None
return self.__dict__.get(key, None)
def get(self, key, default=None):
return self.__dict__.get(key, default) | --- +++ @@ -1,3 +1,9 @@+"""
+requests.structures
+~~~~~~~~~~~~~~~~~~~
+
+Data structures that power Requests.
+"""
from collections import OrderedDict
@@ -5,6 +11,31 @@
class CaseInsensitiveDict(MutableMapping):
+ """A case-insensitive ``dict``-like object.
+
+ Implements all methods and operations of
+ ``MutableMapping`` as well as dict's ``copy``. Also
+ provides ``lower_items``.
+
+ All keys are expected to be strings. The structure remembers the
+ case of the last key to be set, and ``iter(instance)``,
+ ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
+ will contain case-sensitive keys. However, querying and contains
+ testing is case insensitive::
+
+ cid = CaseInsensitiveDict()
+ cid['Accept'] = 'application/json'
+ cid['aCCEPT'] == 'application/json' # True
+ list(cid) == ['Accept'] # True
+
+ For example, ``headers['content-encoding']`` will return the
+ value of a ``'Content-Encoding'`` response header, regardless
+ of how the header name was originally stored.
+
+ If the constructor, ``.update``, or equality comparison
+ operations are given keys that have equal ``.lower()``s, the
+ behavior is undefined.
+ """
def __init__(self, data=None, **kwargs):
self._store = OrderedDict()
@@ -30,6 +61,7 @@ return len(self._store)
def lower_items(self):
+ """Like iteritems(), but with all lowercase keys."""
return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
def __eq__(self, other):
@@ -49,6 +81,7 @@
class LookupDict(dict):
+ """Dictionary lookup object."""
def __init__(self, name=None):
self.name = name
@@ -63,4 +96,4 @@ return self.__dict__.get(key, None)
def get(self, key, default=None):
- return self.__dict__.get(key, default)+ return self.__dict__.get(key, default)
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/structures.py |
Add docstrings that explain purpose and usage | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import logging
import shutil
import sys
import threading
import time
from datetime import datetime
from pathlib import Path
from ultralytics.utils import LOGGER, MACOS, RANK
from ultralytics.utils.checks import check_requirements
class ConsoleLogger:
def __init__(self, destination=None, batch_size=1, flush_interval=5.0, on_flush=None):
self.destination = destination
self.is_api = isinstance(destination, str) and destination.startswith(("http://", "https://"))
if destination is not None and not self.is_api:
self.destination = Path(destination)
# Batching configuration
self.batch_size = max(1, batch_size)
self.flush_interval = flush_interval
self.on_flush = on_flush
# Console capture state
self.original_stdout = sys.stdout
self.original_stderr = sys.stderr
self.active = False
self._log_handler = None # Track handler for cleanup
# Buffer for batching
self.buffer = []
self.buffer_lock = threading.Lock()
self.flush_thread = None
self.chunk_id = 0
# Deduplication state
self.last_line = ""
self.last_time = 0.0
self.last_progress_line = "" # Track progress sequence key for deduplication
self.last_was_progress = False # Track if last line was a progress bar
def start_capture(self):
if self.active or RANK not in {-1, 0}:
return
self.active = True
sys.stdout = self._ConsoleCapture(self.original_stdout, self._queue_log)
sys.stderr = self._ConsoleCapture(self.original_stderr, self._queue_log)
# Hook Ultralytics logger
try:
self._log_handler = self._LogHandler(self._queue_log)
logging.getLogger("ultralytics").addHandler(self._log_handler)
except Exception:
pass
# Start background flush thread for batched mode
if self.batch_size > 1:
self.flush_thread = threading.Thread(target=self._flush_worker, daemon=True)
self.flush_thread.start()
def stop_capture(self):
if not self.active:
return
self.active = False
sys.stdout = self.original_stdout
sys.stderr = self.original_stderr
# Remove logging handler to prevent memory leak
if self._log_handler:
try:
logging.getLogger("ultralytics").removeHandler(self._log_handler)
except Exception:
pass
self._log_handler = None
# Final flush
self._flush_buffer()
def _queue_log(self, text):
if not self.active:
return
current_time = time.time()
# Handle carriage returns and process lines
if "\r" in text:
text = text.split("\r")[-1]
lines = text.split("\n")
if lines and lines[-1] == "":
lines.pop()
for line in lines:
line = line.rstrip()
# Skip lines with only thin progress bars (partial progress)
if "─" in line: # Has thin lines but no thick lines
continue
# Only show 100% completion lines for progress bars
if " ━━" in line:
is_complete = "100%" in line
# Skip ALL non-complete progress lines
if not is_complete:
continue
# Extract sequence key to deduplicate multiple 100% lines for same sequence
parts = line.split()
seq_key = ""
if parts:
# Check for epoch pattern (X/Y at start)
if "/" in parts[0] and parts[0].replace("/", "").isdigit():
seq_key = parts[0] # e.g., "1/3"
elif parts[0] == "Class" and len(parts) > 1:
seq_key = f"{parts[0]}_{parts[1]}" # e.g., "Class_train:" or "Class_val:"
elif parts[0] in ("train:", "val:"):
seq_key = parts[0] # Phase identifier
# Skip if we already showed 100% for this sequence
if seq_key and self.last_progress_line == f"{seq_key}:done":
continue
# Mark this sequence as done
if seq_key:
self.last_progress_line = f"{seq_key}:done"
self.last_was_progress = True
else:
# Skip empty line after progress bar
if not line and self.last_was_progress:
self.last_was_progress = False
continue
self.last_was_progress = False
# General deduplication
if line == self.last_line and current_time - self.last_time < 0.1:
continue
self.last_line = line
self.last_time = current_time
# Add timestamp if needed
if not line.startswith("[20"):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{timestamp}] {line}"
# Add to buffer and check if flush needed
should_flush = False
with self.buffer_lock:
self.buffer.append(line)
if len(self.buffer) >= self.batch_size:
should_flush = True
# Flush outside lock to avoid deadlock
if should_flush:
self._flush_buffer()
def _flush_worker(self):
while self.active:
time.sleep(self.flush_interval)
if self.active:
self._flush_buffer()
def _flush_buffer(self):
with self.buffer_lock:
if not self.buffer:
return
lines = self.buffer.copy()
self.buffer.clear()
self.chunk_id += 1
chunk_id = self.chunk_id # Capture under lock to avoid race
content = "\n".join(lines)
line_count = len(lines)
# Call custom callback if provided
if self.on_flush:
try:
self.on_flush(content, line_count, chunk_id)
except Exception:
pass # Silently ignore callback errors to avoid flooding stderr
# Write to destination (file or API)
if self.destination is not None:
self._write_destination(content)
def _write_destination(self, content):
try:
if self.is_api:
import requests
payload = {"timestamp": datetime.now().isoformat(), "message": content}
requests.post(str(self.destination), json=payload, timeout=5)
else:
self.destination.parent.mkdir(parents=True, exist_ok=True)
with self.destination.open("a", encoding="utf-8") as f:
f.write(content + "\n")
except Exception as e:
print(f"Console logger write error: {e}", file=self.original_stderr)
class _ConsoleCapture:
__slots__ = ("callback", "original")
def __init__(self, original, callback):
self.original = original
self.callback = callback
def write(self, text):
self.original.write(text)
self.callback(text)
def flush(self):
self.original.flush()
class _LogHandler(logging.Handler):
__slots__ = ("callback",)
def __init__(self, callback):
super().__init__()
self.callback = callback
def emit(self, record):
self.callback(self.format(record) + "\n")
class SystemLogger:
def __init__(self):
import psutil # scoped as slow import
self.pynvml = None
self.nvidia_initialized = self._init_nvidia()
self.net_start = psutil.net_io_counters()
self.disk_start = psutil.disk_io_counters()
# For rate calculation
self._prev_net = self.net_start
self._prev_disk = self.disk_start
self._prev_time = time.time()
def _init_nvidia(self):
if MACOS:
return False
try:
check_requirements("nvidia-ml-py>=12.0.0")
self.pynvml = __import__("pynvml")
self.pynvml.nvmlInit()
return True
except Exception as e:
import torch
if torch.cuda.is_available():
LOGGER.warning(f"SystemLogger NVML init failed: {e}")
return False
def get_metrics(self, rates=False):
import psutil # scoped as slow import
net = psutil.net_io_counters()
disk = psutil.disk_io_counters()
memory = psutil.virtual_memory()
disk_usage = shutil.disk_usage("/")
now = time.time()
metrics = {
"cpu": round(psutil.cpu_percent(), 3),
"ram": round(memory.percent, 3),
"gpus": {},
}
# Calculate elapsed time since last call
elapsed = max(0.1, now - self._prev_time) # Avoid division by zero
if rates:
# Calculate MB/s rates from delta since last call
metrics["disk"] = {
"read_mbs": round(max(0, (disk.read_bytes - self._prev_disk.read_bytes) / (1 << 20) / elapsed), 3),
"write_mbs": round(max(0, (disk.write_bytes - self._prev_disk.write_bytes) / (1 << 20) / elapsed), 3),
"used_gb": round(disk_usage.used / (1 << 30), 3),
}
metrics["network"] = {
"recv_mbs": round(max(0, (net.bytes_recv - self._prev_net.bytes_recv) / (1 << 20) / elapsed), 3),
"sent_mbs": round(max(0, (net.bytes_sent - self._prev_net.bytes_sent) / (1 << 20) / elapsed), 3),
}
else:
# Cumulative MB since initialization (original behavior)
metrics["disk"] = {
"read_mb": round((disk.read_bytes - self.disk_start.read_bytes) / (1 << 20), 3),
"write_mb": round((disk.write_bytes - self.disk_start.write_bytes) / (1 << 20), 3),
"used_gb": round(disk_usage.used / (1 << 30), 3),
}
metrics["network"] = {
"recv_mb": round((net.bytes_recv - self.net_start.bytes_recv) / (1 << 20), 3),
"sent_mb": round((net.bytes_sent - self.net_start.bytes_sent) / (1 << 20), 3),
}
# Always update previous values for accurate rate calculation on next call
self._prev_net = net
self._prev_disk = disk
self._prev_time = now
# Add GPU metrics (NVIDIA only)
if self.nvidia_initialized:
metrics["gpus"].update(self._get_nvidia_metrics())
return metrics
def _get_nvidia_metrics(self):
gpus = {}
if not self.nvidia_initialized or not self.pynvml:
return gpus
try:
device_count = self.pynvml.nvmlDeviceGetCount()
for i in range(device_count):
handle = self.pynvml.nvmlDeviceGetHandleByIndex(i)
util = self.pynvml.nvmlDeviceGetUtilizationRates(handle)
memory = self.pynvml.nvmlDeviceGetMemoryInfo(handle)
temp = self.pynvml.nvmlDeviceGetTemperature(handle, self.pynvml.NVML_TEMPERATURE_GPU)
power = self.pynvml.nvmlDeviceGetPowerUsage(handle) // 1000
gpus[str(i)] = {
"usage": round(util.gpu, 3),
"memory": round((memory.used / memory.total) * 100, 3),
"temp": temp,
"power": power,
}
except Exception:
pass
return gpus
if __name__ == "__main__":
print("SystemLogger Real-time Metrics Monitor")
print("Press Ctrl+C to stop\n")
logger = SystemLogger()
try:
while True:
metrics = logger.get_metrics()
# Clear screen (works on most terminals)
print("\033[H\033[J", end="")
# Display system metrics
print(f"CPU: {metrics['cpu']:5.1f}%")
print(f"RAM: {metrics['ram']:5.1f}%")
print(f"Disk Read: {metrics['disk']['read_mb']:8.1f} MB")
print(f"Disk Write: {metrics['disk']['write_mb']:7.1f} MB")
print(f"Disk Used: {metrics['disk']['used_gb']:8.1f} GB")
print(f"Net Recv: {metrics['network']['recv_mb']:9.1f} MB")
print(f"Net Sent: {metrics['network']['sent_mb']:9.1f} MB")
# Display GPU metrics if available
if metrics["gpus"]:
print("\nGPU Metrics:")
for gpu_id, gpu_data in metrics["gpus"].items():
print(
f" GPU {gpu_id}: {gpu_data['usage']:3}% | "
f"Mem: {gpu_data['memory']:5.1f}% | "
f"Temp: {gpu_data['temp']:2}°C | "
f"Power: {gpu_data['power']:3}W"
)
else:
print("\nGPU: No NVIDIA GPUs detected")
time.sleep(1)
except KeyboardInterrupt:
print("\n\nStopped monitoring.") | --- +++ @@ -13,8 +13,44 @@
class ConsoleLogger:
+ """Console output capture with batched streaming to file, API, or custom callback.
+
+ Captures stdout/stderr output and streams it with intelligent deduplication and configurable batching.
+
+ Attributes:
+ destination (str | Path | None): Target destination for streaming (URL, Path, or None for callback-only).
+ batch_size (int): Number of lines to batch before flushing (default: 1 for immediate).
+ flush_interval (float): Seconds between automatic flushes (default: 5.0).
+ on_flush (callable | None): Optional callback function called with batched content on flush.
+ active (bool): Whether console capture is currently active.
+
+ Examples:
+ File logging (immediate):
+ >>> logger = ConsoleLogger("training.log")
+ >>> logger.start_capture()
+ >>> print("This will be logged")
+ >>> logger.stop_capture()
+
+ API streaming with batching:
+ >>> logger = ConsoleLogger("https://api.example.com/logs", batch_size=10)
+ >>> logger.start_capture()
+
+ Custom callback with batching:
+ >>> def my_handler(content, line_count, chunk_id):
+ ... print(f"Received {line_count} lines")
+ >>> logger = ConsoleLogger(on_flush=my_handler, batch_size=5)
+ >>> logger.start_capture()
+ """
def __init__(self, destination=None, batch_size=1, flush_interval=5.0, on_flush=None):
+ """Initialize console logger with optional batching.
+
+ Args:
+ destination (str | Path | None): API endpoint URL (http/https), local file path, or None.
+ batch_size (int): Lines to accumulate before flush (1 = immediate, higher = batched).
+ flush_interval (float): Max seconds between flushes when batching.
+ on_flush (callable | None): Callback(content: str, line_count: int, chunk_id: int) for custom handling.
+ """
self.destination = destination
self.is_api = isinstance(destination, str) and destination.startswith(("http://", "https://"))
if destination is not None and not self.is_api:
@@ -44,6 +80,11 @@ self.last_was_progress = False # Track if last line was a progress bar
def start_capture(self):
+ """Start capturing console output and redirect stdout/stderr.
+
+ Notes:
+ In DDP training, only activates on rank 0/-1 to prevent duplicate logging.
+ """
if self.active or RANK not in {-1, 0}:
return
@@ -64,6 +105,7 @@ self.flush_thread.start()
def stop_capture(self):
+ """Stop capturing console output and flush remaining buffer."""
if not self.active:
return
@@ -83,6 +125,7 @@ self._flush_buffer()
def _queue_log(self, text):
+ """Queue console text with deduplication and timestamp processing."""
if not self.active:
return
@@ -163,12 +206,14 @@ self._flush_buffer()
def _flush_worker(self):
+ """Background worker that flushes buffer periodically."""
while self.active:
time.sleep(self.flush_interval)
if self.active:
self._flush_buffer()
def _flush_buffer(self):
+ """Flush buffered lines to destination and/or callback."""
with self.buffer_lock:
if not self.buffer:
return
@@ -192,6 +237,7 @@ self._write_destination(content)
def _write_destination(self, content):
+ """Write content to file or API destination."""
try:
if self.is_api:
import requests
@@ -206,35 +252,70 @@ print(f"Console logger write error: {e}", file=self.original_stderr)
class _ConsoleCapture:
+ """Lightweight stdout/stderr capture."""
__slots__ = ("callback", "original")
def __init__(self, original, callback):
+ """Initialize a stream wrapper that redirects writes to a callback while preserving the original."""
self.original = original
self.callback = callback
def write(self, text):
+ """Write text to the original stream and forward it to the capture callback."""
self.original.write(text)
self.callback(text)
def flush(self):
+ """Flush the wrapped stream to propagate buffered output promptly during console capture."""
self.original.flush()
class _LogHandler(logging.Handler):
+ """Lightweight logging handler."""
__slots__ = ("callback",)
def __init__(self, callback):
+ """Initialize a lightweight logging.Handler that forwards log records to the provided callback."""
super().__init__()
self.callback = callback
def emit(self, record):
+ """Format and forward LogRecord messages to the capture callback for unified log streaming."""
self.callback(self.format(record) + "\n")
class SystemLogger:
+ """Log dynamic system metrics for training monitoring.
+
+ Captures real-time system metrics including CPU, RAM, disk I/O, network I/O, and NVIDIA GPU statistics for training
+ performance monitoring and analysis.
+
+ Attributes:
+ pynvml: NVIDIA pynvml module instance if successfully imported, None otherwise.
+ nvidia_initialized (bool): Whether NVIDIA GPU monitoring is available and initialized.
+ net_start: Initial network I/O counters for calculating cumulative usage.
+ disk_start: Initial disk I/O counters for calculating cumulative usage.
+
+ Examples:
+ Basic usage:
+ >>> logger = SystemLogger()
+ >>> metrics = logger.get_metrics()
+ >>> print(f"CPU: {metrics['cpu']}%, RAM: {metrics['ram']}%")
+ >>> if metrics["gpus"]:
+ ... gpu0 = metrics["gpus"]["0"]
+ ... print(f"GPU0: {gpu0['usage']}% usage, {gpu0['temp']}°C")
+
+ Training loop integration:
+ >>> system_logger = SystemLogger()
+ >>> for epoch in range(epochs):
+ ... # Training code here
+ ... metrics = system_logger.get_metrics()
+ ... # Log to database/file
+ """
def __init__(self):
+ """Initialize the system logger."""
import psutil # scoped as slow import
self.pynvml = None
@@ -248,6 +329,7 @@ self._prev_time = time.time()
def _init_nvidia(self):
+ """Initialize NVIDIA GPU monitoring with pynvml."""
if MACOS:
return False
@@ -264,6 +346,49 @@ return False
def get_metrics(self, rates=False):
+ """Get current system metrics including CPU, RAM, disk, network, and GPU usage.
+
+ Collects comprehensive system metrics including CPU usage, RAM usage, disk I/O statistics, network I/O
+ statistics, and GPU metrics (if available).
+
+ Example output (rates=False, default):
+ ```python
+ {
+ "cpu": 45.2,
+ "ram": 78.9,
+ "disk": {"read_mb": 156.7, "write_mb": 89.3, "used_gb": 256.8},
+ "network": {"recv_mb": 157.2, "sent_mb": 89.1},
+ "gpus": {
+ "0": {"usage": 95.6, "memory": 85.4, "temp": 72, "power": 285},
+ "1": {"usage": 94.1, "memory": 82.7, "temp": 70, "power": 278},
+ },
+ }
+ ```
+
+ Example output (rates=True):
+ ```python
+ {
+ "cpu": 45.2,
+ "ram": 78.9,
+ "disk": {"read_mbs": 12.5, "write_mbs": 8.3, "used_gb": 256.8},
+ "network": {"recv_mbs": 5.2, "sent_mbs": 1.1},
+ "gpus": {
+ "0": {"usage": 95.6, "memory": 85.4, "temp": 72, "power": 285},
+ },
+ }
+ ```
+
+ Args:
+ rates (bool): If True, return disk/network as MB/s rates instead of cumulative MB.
+
+ Returns:
+ (dict): Metrics dictionary with cpu, ram, disk, network, and gpus keys.
+
+ Examples:
+ >>> logger = SystemLogger()
+ >>> logger.get_metrics()["cpu"] # CPU percentage
+ >>> logger.get_metrics(rates=True)["network"]["recv_mbs"] # MB/s download rate
+ """
import psutil # scoped as slow import
net = psutil.net_io_counters()
@@ -316,6 +441,7 @@ return metrics
def _get_nvidia_metrics(self):
+ """Get NVIDIA GPU metrics including utilization, memory, temperature, and power."""
gpus = {}
if not self.nvidia_initialized or not self.pynvml:
return gpus
@@ -377,4 +503,4 @@ time.sleep(1)
except KeyboardInterrupt:
- print("\n\nStopped monitoring.")+ print("\n\nStopped monitoring.")
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/logger.py |
Auto-generate documentation strings for this file |
HOOKS = ["response"]
def default_hooks():
return {event: [] for event in HOOKS}
# TODO: response is the only one
def dispatch_hook(key, hooks, hook_data, **kwargs):
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, "__call__"):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **kwargs)
if _hook_data is not None:
hook_data = _hook_data
return hook_data | --- +++ @@ -1,3 +1,14 @@+"""
+requests.hooks
+~~~~~~~~~~~~~~
+
+This module provides the capabilities for the Requests hooks system.
+
+Available hooks:
+
+``response``:
+ The response generated from a Request.
+"""
HOOKS = ["response"]
@@ -10,6 +21,7 @@
def dispatch_hook(key, hooks, hook_data, **kwargs):
+ """Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
@@ -19,4 +31,4 @@ _hook_data = hook(hook_data, **kwargs)
if _hook_data is not None:
hook_data = _hook_data
- return hook_data+ return hook_data
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/hooks.py |
Add docstrings to my Python code |
from urllib3.exceptions import HTTPError as BaseHTTPError
from .compat import JSONDecodeError as CompatJSONDecodeError
class RequestException(IOError):
def __init__(self, *args, **kwargs):
response = kwargs.pop("response", None)
self.response = response
self.request = kwargs.pop("request", None)
if response is not None and not self.request and hasattr(response, "request"):
self.request = self.response.request
super().__init__(*args, **kwargs)
class InvalidJSONError(RequestException):
class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):
def __init__(self, *args, **kwargs):
CompatJSONDecodeError.__init__(self, *args)
InvalidJSONError.__init__(self, *self.args, **kwargs)
def __reduce__(self):
return CompatJSONDecodeError.__reduce__(self)
class HTTPError(RequestException):
class ConnectionError(RequestException):
class ProxyError(ConnectionError):
class SSLError(ConnectionError):
class Timeout(RequestException):
class ConnectTimeout(ConnectionError, Timeout):
class ReadTimeout(Timeout):
class URLRequired(RequestException):
class TooManyRedirects(RequestException):
class MissingSchema(RequestException, ValueError):
class InvalidSchema(RequestException, ValueError):
class InvalidURL(RequestException, ValueError):
class InvalidHeader(RequestException, ValueError):
class InvalidProxyURL(InvalidURL):
class ChunkedEncodingError(RequestException):
class ContentDecodingError(RequestException, BaseHTTPError):
class StreamConsumedError(RequestException, TypeError):
class RetryError(RequestException):
class UnrewindableBodyError(RequestException):
# Warnings
class RequestsWarning(Warning):
class FileModeWarning(RequestsWarning, DeprecationWarning):
class RequestsDependencyWarning(RequestsWarning): | --- +++ @@ -1,3 +1,9 @@+"""
+requests.exceptions
+~~~~~~~~~~~~~~~~~~~
+
+This module contains the set of Requests' exceptions.
+"""
from urllib3.exceptions import HTTPError as BaseHTTPError
@@ -5,8 +11,12 @@
class RequestException(IOError):
+ """There was an ambiguous exception that occurred while handling your
+ request.
+ """
def __init__(self, *args, **kwargs):
+ """Initialize RequestException with `request` and `response` objects."""
response = kwargs.pop("response", None)
self.response = response
self.request = kwargs.pop("request", None)
@@ -16,82 +26,127 @@
class InvalidJSONError(RequestException):
+ """A JSON error occurred."""
class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):
+ """Couldn't decode the text into json"""
def __init__(self, *args, **kwargs):
+ """
+ Construct the JSONDecodeError instance first with all
+ args. Then use it's args to construct the IOError so that
+ the json specific args aren't used as IOError specific args
+ and the error message from JSONDecodeError is preserved.
+ """
CompatJSONDecodeError.__init__(self, *args)
InvalidJSONError.__init__(self, *self.args, **kwargs)
def __reduce__(self):
+ """
+ The __reduce__ method called when pickling the object must
+ be the one from the JSONDecodeError (be it json/simplejson)
+ as it expects all the arguments for instantiation, not just
+ one like the IOError, and the MRO would by default call the
+ __reduce__ method from the IOError due to the inheritance order.
+ """
return CompatJSONDecodeError.__reduce__(self)
class HTTPError(RequestException):
+ """An HTTP error occurred."""
class ConnectionError(RequestException):
+ """A Connection error occurred."""
class ProxyError(ConnectionError):
+ """A proxy error occurred."""
class SSLError(ConnectionError):
+ """An SSL error occurred."""
class Timeout(RequestException):
+ """The request timed out.
+
+ Catching this error will catch both
+ :exc:`~requests.exceptions.ConnectTimeout` and
+ :exc:`~requests.exceptions.ReadTimeout` errors.
+ """
class ConnectTimeout(ConnectionError, Timeout):
+ """The request timed out while trying to connect to the remote server.
+
+ Requests that produced this error are safe to retry.
+ """
class ReadTimeout(Timeout):
+ """The server did not send any data in the allotted amount of time."""
class URLRequired(RequestException):
+ """A valid URL is required to make a request."""
class TooManyRedirects(RequestException):
+ """Too many redirects."""
class MissingSchema(RequestException, ValueError):
+ """The URL scheme (e.g. http or https) is missing."""
class InvalidSchema(RequestException, ValueError):
+ """The URL scheme provided is either invalid or unsupported."""
class InvalidURL(RequestException, ValueError):
+ """The URL provided was somehow invalid."""
class InvalidHeader(RequestException, ValueError):
+ """The header value provided was somehow invalid."""
class InvalidProxyURL(InvalidURL):
+ """The proxy URL provided is invalid."""
class ChunkedEncodingError(RequestException):
+ """The server declared chunked encoding but sent an invalid chunk."""
class ContentDecodingError(RequestException, BaseHTTPError):
+ """Failed to decode response content."""
class StreamConsumedError(RequestException, TypeError):
+ """The content for this response was already consumed."""
class RetryError(RequestException):
+ """Custom retries logic failed"""
class UnrewindableBodyError(RequestException):
+ """Requests encountered an error when trying to rewind a body."""
# Warnings
class RequestsWarning(Warning):
+ """Base warning for Requests."""
class FileModeWarning(RequestsWarning, DeprecationWarning):
+ """A file was opened in text mode, but Requests determined its binary length."""
-class RequestsDependencyWarning(RequestsWarning):+class RequestsDependencyWarning(RequestsWarning):
+ """An imported dependency doesn't match the expected version range."""
| https://raw.githubusercontent.com/psf/requests/HEAD/src/requests/exceptions.py |
Auto-generate documentation strings for this file | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from functools import cached_property
from pathlib import Path
class GitRepo:
def __init__(self, path: Path = Path(__file__).resolve()):
self.root = self._find_root(path)
self.gitdir = self._gitdir(self.root) if self.root else None
@staticmethod
def _find_root(p: Path) -> Path | None:
return next((d for d in [p, *list(p.parents)] if (d / ".git").exists()), None)
@staticmethod
def _gitdir(root: Path) -> Path | None:
g = root / ".git"
if g.is_dir():
return g
if g.is_file():
t = g.read_text(errors="ignore").strip()
if t.startswith("gitdir:"):
return (root / t.split(":", 1)[1].strip()).resolve()
return None
@staticmethod
def _read(p: Path | None) -> str | None:
return p.read_text(errors="ignore").strip() if p and p.exists() else None
@cached_property
def head(self) -> str | None:
return self._read(self.gitdir / "HEAD" if self.gitdir else None)
def _ref_commit(self, ref: str) -> str | None:
rf = self.gitdir / ref
if s := self._read(rf):
return s
pf = self.gitdir / "packed-refs"
b = pf.read_bytes().splitlines() if pf.exists() else []
tgt = ref.encode()
for line in b:
if line[:1] in (b"#", b"^") or b" " not in line:
continue
sha, name = line.split(b" ", 1)
if name.strip() == tgt:
return sha.decode()
return None
@property
def is_repo(self) -> bool:
return self.gitdir is not None
@cached_property
def branch(self) -> str | None:
if not self.is_repo or not self.head or not self.head.startswith("ref: "):
return None
ref = self.head[5:].strip()
return ref[len("refs/heads/") :] if ref.startswith("refs/heads/") else ref
@cached_property
def commit(self) -> str | None:
if not self.is_repo or not self.head:
return None
return self._ref_commit(self.head[5:].strip()) if self.head.startswith("ref: ") else self.head
@cached_property
def origin(self) -> str | None:
if not self.is_repo:
return None
cfg = self.gitdir / "config"
remote, url = None, None
for s in (self._read(cfg) or "").splitlines():
t = s.strip()
if t.startswith("[") and t.endswith("]"):
remote = t.lower()
elif t.lower().startswith("url =") and remote == '[remote "origin"]':
url = t.split("=", 1)[1].strip()
break
return url
if __name__ == "__main__":
import time
g = GitRepo()
if g.is_repo:
t0 = time.perf_counter()
print(f"repo={g.root}\nbranch={g.branch}\ncommit={g.commit}\norigin={g.origin}")
dt = (time.perf_counter() - t0) * 1000
print(f"\n⏱️ Profiling: total {dt:.3f} ms") | --- +++ @@ -7,17 +7,53 @@
class GitRepo:
+ """Represent a local Git repository and expose branch, commit, and remote metadata.
+
+ This class discovers the repository root by searching for a .git entry from the given path upward, resolves the
+ actual .git directory (including worktrees), and reads Git metadata directly from on-disk files. It does not invoke
+ the git binary and therefore works in restricted environments. All metadata properties are resolved lazily and
+ cached; construct a new instance to refresh state.
+
+ Attributes:
+ root (Path | None): Repository root directory containing the .git entry; None if not in a repository.
+ gitdir (Path | None): Resolved .git directory path; handles worktrees; None if unresolved.
+ head (str | None): Raw contents of HEAD; a SHA for detached HEAD or "ref: <refname>" for branch heads.
+ is_repo (bool): Whether the provided path resides inside a Git repository.
+ branch (str | None): Current branch name when HEAD points to a branch; None for detached HEAD or non-repo.
+ commit (str | None): Current commit SHA for HEAD; None if not determinable.
+ origin (str | None): URL of the "origin" remote as read from gitdir/config; None if unset or unavailable.
+
+ Examples:
+ Initialize from the current working directory and read metadata
+ >>> from pathlib import Path
+ >>> repo = GitRepo(Path.cwd())
+ >>> repo.is_repo
+ True
+ >>> repo.branch, repo.commit[:7], repo.origin
+ ('main', '1a2b3c4', 'https://example.com/owner/repo.git')
+
+ Notes:
+ - Resolves metadata by reading files: HEAD, packed-refs, and config; no subprocess calls are used.
+ - Caches properties on first access using cached_property; recreate the object to reflect repository changes.
+ """
def __init__(self, path: Path = Path(__file__).resolve()):
+ """Initialize a Git repository context by discovering the repository root from a starting path.
+
+ Args:
+ path (Path, optional): File or directory path used as the starting point to locate the repository root.
+ """
self.root = self._find_root(path)
self.gitdir = self._gitdir(self.root) if self.root else None
@staticmethod
def _find_root(p: Path) -> Path | None:
+ """Return repo root or None."""
return next((d for d in [p, *list(p.parents)] if (d / ".git").exists()), None)
@staticmethod
def _gitdir(root: Path) -> Path | None:
+ """Resolve actual .git directory (handles worktrees)."""
g = root / ".git"
if g.is_dir():
return g
@@ -29,13 +65,16 @@
@staticmethod
def _read(p: Path | None) -> str | None:
+ """Read and strip file if exists."""
return p.read_text(errors="ignore").strip() if p and p.exists() else None
@cached_property
def head(self) -> str | None:
+ """HEAD file contents."""
return self._read(self.gitdir / "HEAD" if self.gitdir else None)
def _ref_commit(self, ref: str) -> str | None:
+ """Commit for ref (handles packed-refs)."""
rf = self.gitdir / ref
if s := self._read(rf):
return s
@@ -52,10 +91,12 @@
@property
def is_repo(self) -> bool:
+ """True if inside a git repo."""
return self.gitdir is not None
@cached_property
def branch(self) -> str | None:
+ """Current branch or None."""
if not self.is_repo or not self.head or not self.head.startswith("ref: "):
return None
ref = self.head[5:].strip()
@@ -63,12 +104,14 @@
@cached_property
def commit(self) -> str | None:
+ """Current commit SHA or None."""
if not self.is_repo or not self.head:
return None
return self._ref_commit(self.head[5:].strip()) if self.head.startswith("ref: ") else self.head
@cached_property
def origin(self) -> str | None:
+ """Origin URL or None."""
if not self.is_repo:
return None
cfg = self.gitdir / "config"
@@ -91,4 +134,4 @@ t0 = time.perf_counter()
print(f"repo={g.root}\nbranch={g.branch}\ncommit={g.commit}\norigin={g.origin}")
dt = (time.perf_counter() - t0) * 1000
- print(f"\n⏱️ Profiling: total {dt:.3f} ms")+ print(f"\n⏱️ Profiling: total {dt:.3f} ms")
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/utils/git.py |
Create documentation for each function signature | #!/usr/bin/env python3
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import List, Dict, Optional
import json
import sqlite3
class ChatMessage(BaseModel):
message: str
user_id: Optional[str] = None
class AIResponse(BaseModel):
response: str
workflows: List[Dict] = []
suggestions: List[str] = []
confidence: float = 0.0
class WorkflowAssistant:
def __init__(self, db_path: str = "workflows.db"):
self.db_path = db_path
self.conversation_history = {}
def get_db_connection(self):
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
return conn
def search_workflows_intelligent(self, query: str, limit: int = 5) -> List[Dict]:
conn = self.get_db_connection()
# Extract keywords and intent from query
keywords = self.extract_keywords(query)
intent = self.detect_intent(query)
# Build search query
search_terms = []
for keyword in keywords:
search_terms.append(
f"name LIKE '%{keyword}%' OR description LIKE '%{keyword}%'"
)
where_clause = " OR ".join(search_terms) if search_terms else "1=1"
# Add intent-based filtering
if intent == "automation":
where_clause += (
" AND (trigger_type = 'Scheduled' OR trigger_type = 'Complex')"
)
elif intent == "integration":
where_clause += " AND trigger_type = ?"
params.append('Webhook')
elif intent == "manual":
where_clause += " AND trigger_type = 'Manual'"
query_sql = f"""
SELECT * FROM workflows
WHERE {where_clause}
ORDER BY
CASE WHEN active = 1 THEN 1 ELSE 2 END,
node_count DESC
LIMIT ?
"""
cursor = conn.execute(query_sql)
workflows = []
for row in cursor.fetchall():
workflow = dict(row)
workflow["integrations"] = json.loads(workflow["integrations"] or "[]")
workflow["tags"] = json.loads(workflow["tags"] or "[]")
workflows.append(workflow)
conn.close()
return workflows
def extract_keywords(self, query: str) -> List[str]:
# Common automation terms
automation_terms = {
"email": ["email", "gmail", "mail"],
"social": ["twitter", "facebook", "instagram", "linkedin", "social"],
"data": ["data", "database", "spreadsheet", "csv", "excel"],
"ai": ["ai", "openai", "chatgpt", "artificial", "intelligence"],
"notification": ["notification", "alert", "slack", "telegram", "discord"],
"automation": ["automation", "workflow", "process", "automate"],
"integration": ["integration", "connect", "sync", "api"],
}
query_lower = query.lower()
keywords = []
for category, terms in automation_terms.items():
for term in terms:
if term in query_lower:
keywords.append(term)
# Extract specific service names
services = [
"slack",
"telegram",
"openai",
"google",
"microsoft",
"shopify",
"airtable",
]
for service in services:
if service in query_lower:
keywords.append(service)
return list(set(keywords))
def detect_intent(self, query: str) -> str:
query_lower = query.lower()
if any(
word in query_lower
for word in ["automate", "schedule", "recurring", "daily", "weekly"]
):
return "automation"
elif any(
word in query_lower for word in ["connect", "integrate", "sync", "webhook"]
):
return "integration"
elif any(
word in query_lower for word in ["manual", "trigger", "button", "click"]
):
return "manual"
elif any(
word in query_lower for word in ["ai", "chat", "assistant", "intelligent"]
):
return "ai"
else:
return "general"
def generate_response(self, query: str, workflows: List[Dict]) -> str:
if not workflows:
return "I couldn't find any workflows matching your request. Try searching for specific services like 'Slack', 'OpenAI', or 'Email automation'."
# Analyze workflow patterns
trigger_types = [w["trigger_type"] for w in workflows]
integrations = []
for w in workflows:
integrations.extend(w["integrations"])
common_integrations = list(set(integrations))[:3]
most_common_trigger = max(set(trigger_types), key=trigger_types.count)
# Generate contextual response
response_parts = []
if len(workflows) == 1:
workflow = workflows[0]
response_parts.append(f"I found a perfect match: **{workflow['name']}**")
response_parts.append(
f"This is a {workflow['trigger_type'].lower()} workflow that {workflow['description'].lower()}"
)
else:
response_parts.append(f"I found {len(workflows)} relevant workflows:")
for i, workflow in enumerate(workflows[:3], 1):
response_parts.append(
f"{i}. **{workflow['name']}** - {workflow['description']}"
)
if common_integrations:
response_parts.append(
f"\nThese workflows commonly use: {', '.join(common_integrations)}"
)
if most_common_trigger != "all":
response_parts.append(
f"Most are {most_common_trigger.lower()} triggered workflows."
)
return "\n".join(response_parts)
def get_suggestions(self, query: str) -> List[str]:
suggestions = []
if "email" in query.lower():
suggestions.extend(
[
"Email automation workflows",
"Gmail integration examples",
"Email notification systems",
]
)
elif "ai" in query.lower() or "openai" in query.lower():
suggestions.extend(
[
"AI-powered workflows",
"OpenAI integration examples",
"Chatbot automation",
]
)
elif "social" in query.lower():
suggestions.extend(
[
"Social media automation",
"Twitter integration workflows",
"LinkedIn automation",
]
)
else:
suggestions.extend(
[
"Popular automation patterns",
"Webhook-triggered workflows",
"Scheduled automation examples",
]
)
return suggestions[:3]
def calculate_confidence(self, query: str, workflows: List[Dict]) -> float:
if not workflows:
return 0.0
# Base confidence on number of matches and relevance
base_confidence = min(len(workflows) / 5.0, 1.0)
# Boost confidence for exact matches
query_lower = query.lower()
exact_matches = 0
for workflow in workflows:
if any(word in workflow["name"].lower() for word in query_lower.split()):
exact_matches += 1
if exact_matches > 0:
base_confidence += 0.2
return min(base_confidence, 1.0)
# Initialize assistant
assistant = WorkflowAssistant()
# FastAPI app for AI Assistant
ai_app = FastAPI(title="N8N AI Assistant", version="1.0.0")
@ai_app.post("/chat", response_model=AIResponse)
async def chat_with_assistant(message: ChatMessage):
try:
# Search for relevant workflows
workflows = assistant.search_workflows_intelligent(message.message, limit=5)
# Generate response
response_text = assistant.generate_response(message.message, workflows)
# Get suggestions
suggestions = assistant.get_suggestions(message.message)
# Calculate confidence
confidence = assistant.calculate_confidence(message.message, workflows)
return AIResponse(
response=response_text,
workflows=workflows,
suggestions=suggestions,
confidence=confidence,
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Assistant error: {str(e)}")
@ai_app.get("/chat/interface")
async def chat_interface():
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N8N AI Assistant</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.chat-container {
width: 90%;
max-width: 800px;
height: 80vh;
background: white;
border-radius: 20px;
box-shadow: 0 20px 40px rgba(0,0,0,0.1);
display: flex;
flex-direction: column;
overflow: hidden;
}
.chat-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
text-align: center;
}
.chat-header h1 {
font-size: 24px;
margin-bottom: 5px;
}
.chat-messages {
flex: 1;
padding: 20px;
overflow-y: auto;
background: #f8f9fa;
}
.message {
margin-bottom: 15px;
display: flex;
align-items: flex-start;
}
.message.user {
justify-content: flex-end;
}
.message.assistant {
justify-content: flex-start;
}
.message-content {
max-width: 70%;
padding: 15px 20px;
border-radius: 20px;
word-wrap: break-word;
}
.message.user .message-content {
background: #667eea;
color: white;
border-bottom-right-radius: 5px;
}
.message.assistant .message-content {
background: white;
color: #333;
border: 1px solid #e9ecef;
border-bottom-left-radius: 5px;
}
.workflow-card {
background: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 10px;
padding: 15px;
margin: 10px 0;
}
.workflow-title {
font-weight: bold;
color: #667eea;
margin-bottom: 5px;
}
.workflow-description {
color: #666;
font-size: 14px;
margin-bottom: 10px;
}
.workflow-meta {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.meta-tag {
background: #e9ecef;
padding: 4px 8px;
border-radius: 12px;
font-size: 12px;
color: #666;
}
.suggestions {
margin-top: 10px;
}
.suggestion {
background: #e3f2fd;
color: #1976d2;
padding: 8px 12px;
border-radius: 15px;
margin: 5px 5px 5px 0;
display: inline-block;
cursor: pointer;
font-size: 14px;
transition: all 0.3s ease;
}
.suggestion:hover {
background: #1976d2;
color: white;
}
.chat-input {
padding: 20px;
background: white;
border-top: 1px solid #e9ecef;
display: flex;
gap: 10px;
}
.chat-input input {
flex: 1;
padding: 15px;
border: 2px solid #e9ecef;
border-radius: 25px;
font-size: 16px;
outline: none;
transition: border-color 0.3s ease;
}
.chat-input input:focus {
border-color: #667eea;
}
.send-btn {
background: #667eea;
color: white;
border: none;
border-radius: 50%;
width: 50px;
height: 50px;
cursor: pointer;
font-size: 18px;
transition: all 0.3s ease;
}
.send-btn:hover {
background: #5a6fd8;
transform: scale(1.05);
}
.typing {
color: #666;
font-style: italic;
}
</style>
</head>
<body>
<div class="chat-container">
<div class="chat-header">
<h1>🤖 N8N AI Assistant</h1>
<p>Ask me about workflows and automation</p>
</div>
<div class="chat-messages" id="chatMessages">
<div class="message assistant">
<div class="message-content">
👋 Hi! I'm your N8N workflow assistant. I can help you find workflows for:
<div class="suggestions">
<span class="suggestion" onclick="sendMessage('Show me email automation workflows')">Email automation</span>
<span class="suggestion" onclick="sendMessage('Find AI-powered workflows')">AI workflows</span>
<span class="suggestion" onclick="sendMessage('Show me Slack integrations')">Slack integrations</span>
<span class="suggestion" onclick="sendMessage('Find webhook workflows')">Webhook workflows</span>
</div>
</div>
</div>
</div>
<div class="chat-input">
<input type="text" id="messageInput" placeholder="Ask about workflows..." onkeypress="handleKeyPress(event)">
<button class="send-btn" onclick="sendMessage()">➤</button>
</div>
</div>
<script>
async function sendMessage(message = null) {
const input = document.getElementById('messageInput');
const messageText = message || input.value.trim();
if (!messageText) return;
// Add user message
addMessage(messageText, 'user');
input.value = '';
// Show typing indicator
const typingId = addMessage('Thinking...', 'assistant', true);
try {
const response = await fetch('/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: messageText })
});
const data = await response.json();
// Remove typing indicator
document.getElementById(typingId).remove();
// Add assistant response
addAssistantMessage(data);
} catch (error) {
document.getElementById(typingId).remove();
addMessage('Sorry, I encountered an error. Please try again.', 'assistant');
}
}
function addMessage(text, sender, isTyping = false) {
const messagesContainer = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
const messageId = 'msg_' + Date.now();
messageDiv.id = messageId;
messageDiv.className = `message ${sender}`;
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
if (isTyping) {
contentDiv.className += ' typing';
}
contentDiv.textContent = text;
messageDiv.appendChild(contentDiv);
messagesContainer.appendChild(messageDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
return messageId;
}
function addAssistantMessage(data) {
const messagesContainer = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.className = 'message assistant';
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
// Add response text
contentDiv.innerHTML = data.response.replace(/\\*\\*(.*?)\\*\\*/g, '<strong>$1</strong>');
// Add workflow cards
if (data.workflows && data.workflows.length > 0) {
data.workflows.forEach(workflow => {
const workflowCard = document.createElement('div');
workflowCard.className = 'workflow-card';
workflowCard.innerHTML = `
<div class="workflow-title">${workflow.name}</div>
<div class="workflow-description">${workflow.description}</div>
<div class="workflow-meta">
<span class="meta-tag">${workflow.trigger_type}</span>
<span class="meta-tag">${workflow.complexity}</span>
<span class="meta-tag">${workflow.node_count} nodes</span>
${workflow.active ? '<span class="meta-tag" style="background: #d4edda; color: #155724;">Active</span>' : ''}
</div>
`;
contentDiv.appendChild(workflowCard);
});
}
// Add suggestions
if (data.suggestions && data.suggestions.length > 0) {
const suggestionsDiv = document.createElement('div');
suggestionsDiv.className = 'suggestions';
data.suggestions.forEach(suggestion => {
const suggestionSpan = document.createElement('span');
suggestionSpan.className = 'suggestion';
suggestionSpan.textContent = suggestion;
suggestionSpan.onclick = () => sendMessage(suggestion);
suggestionsDiv.appendChild(suggestionSpan);
});
contentDiv.appendChild(suggestionsDiv);
}
messageDiv.appendChild(contentDiv);
messagesContainer.appendChild(messageDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
function handleKeyPress(event) {
if (event.key === 'Enter') {
sendMessage();
}
}
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
uvicorn.run(ai_app, host="127.0.0.1", port=8001) | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+AI Assistant for N8N Workflow Discovery
+Intelligent chat interface for finding and understanding workflows.
+"""
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
@@ -31,6 +35,7 @@ return conn
def search_workflows_intelligent(self, query: str, limit: int = 5) -> List[Dict]:
+ """Intelligent workflow search based on natural language query."""
conn = self.get_db_connection()
# Extract keywords and intent from query
@@ -78,6 +83,7 @@ return workflows
def extract_keywords(self, query: str) -> List[str]:
+ """Extract relevant keywords from user query."""
# Common automation terms
automation_terms = {
"email": ["email", "gmail", "mail"],
@@ -114,6 +120,7 @@ return list(set(keywords))
def detect_intent(self, query: str) -> str:
+ """Detect user intent from query."""
query_lower = query.lower()
if any(
@@ -137,6 +144,7 @@ return "general"
def generate_response(self, query: str, workflows: List[Dict]) -> str:
+ """Generate natural language response based on query and workflows."""
if not workflows:
return "I couldn't find any workflows matching your request. Try searching for specific services like 'Slack', 'OpenAI', or 'Email automation'."
@@ -179,6 +187,7 @@ return "\n".join(response_parts)
def get_suggestions(self, query: str) -> List[str]:
+ """Generate helpful suggestions based on query."""
suggestions = []
if "email" in query.lower():
@@ -217,6 +226,7 @@ return suggestions[:3]
def calculate_confidence(self, query: str, workflows: List[Dict]) -> float:
+ """Calculate confidence score for the response."""
if not workflows:
return 0.0
@@ -245,6 +255,7 @@
@ai_app.post("/chat", response_model=AIResponse)
async def chat_with_assistant(message: ChatMessage):
+ """Chat with the AI assistant to discover workflows."""
try:
# Search for relevant workflows
workflows = assistant.search_workflows_intelligent(message.message, limit=5)
@@ -271,6 +282,7 @@
@ai_app.get("/chat/interface")
async def chat_interface():
+ """Get the chat interface HTML."""
html_content = """
<!DOCTYPE html>
<html lang="en">
@@ -577,4 +589,4 @@ if __name__ == "__main__":
import uvicorn
- uvicorn.run(ai_app, host="127.0.0.1", port=8001)+ uvicorn.run(ai_app, host="127.0.0.1", port=8001)
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/src/ai_assistant.py |
Add minimal docstrings for each function | #!/usr/bin/env python3
from fastapi import FastAPI, HTTPException, Query, BackgroundTasks, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from pydantic import BaseModel, field_validator
from typing import Optional, List, Dict, Any
import json
import os
import re
import urllib.parse
from pathlib import Path
import uvicorn
import time
from collections import defaultdict
from workflow_db import WorkflowDatabase
# Initialize FastAPI app
app = FastAPI(
title="N8N Workflow Documentation API",
description="Fast API for browsing and searching workflow documentation",
version="2.0.0",
)
# Security: Rate limiting storage
rate_limit_storage = defaultdict(list)
MAX_REQUESTS_PER_MINUTE = 60 # Configure as needed
# Add middleware for performance
app.add_middleware(GZipMiddleware, minimum_size=1000)
# Security: Configure CORS properly - restrict origins in production
# For local development, you can use localhost
# For production, replace with your actual domain
ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://localhost:8000",
"http://localhost:8080",
"https://zie619.github.io", # GitHub Pages
"https://n8n-workflows-1-xxgm.onrender.com", # Community deployment
]
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS, # Security fix: Restrict origins
allow_credentials=True,
allow_methods=["GET", "POST"], # Security fix: Only allow needed methods
allow_headers=["Content-Type", "Authorization"], # Security fix: Restrict headers
)
# Initialize database
db = WorkflowDatabase()
# Security: Helper function for rate limiting
def check_rate_limit(client_ip: str) -> bool:
current_time = time.time()
# Clean old entries
rate_limit_storage[client_ip] = [
timestamp
for timestamp in rate_limit_storage[client_ip]
if current_time - timestamp < 60
]
# Check rate limit
if len(rate_limit_storage[client_ip]) >= MAX_REQUESTS_PER_MINUTE:
return False
# Add current request
rate_limit_storage[client_ip].append(current_time)
return True
# Security: Helper function to validate and sanitize filenames
def validate_filename(filename: str) -> bool:
# Decode URL encoding multiple times to catch encoded traversal attempts
decoded = filename
for _ in range(3): # Decode up to 3 times to catch nested encodings
try:
decoded = urllib.parse.unquote(decoded, errors="strict")
except:
return False # Invalid encoding
# Check for path traversal patterns
dangerous_patterns = [
"..", # Parent directory
"..\\", # Windows parent directory
"../", # Unix parent directory
"\\", # Backslash (Windows path separator)
"/", # Forward slash (Unix path separator)
"\x00", # Null byte
"\n",
"\r", # Newlines
"~", # Home directory
":", # Drive letter or stream (Windows)
"|",
"<",
">", # Shell redirection
"*",
"?", # Wildcards
"$", # Variable expansion
";",
"&", # Command separators
]
for pattern in dangerous_patterns:
if pattern in decoded:
return False
# Check for absolute paths
if decoded.startswith("/") or decoded.startswith("\\"):
return False
# Check for Windows drive letters
if len(decoded) >= 2 and decoded[1] == ":":
return False
# Only allow alphanumeric, dash, underscore, and .json extension
if not re.match(r"^[a-zA-Z0-9_\-]+\.json$", decoded):
return False
# Additional check: filename should end with .json
if not decoded.endswith(".json"):
return False
return True
# Startup function to verify database
@app.on_event("startup")
async def startup_event():
try:
stats = db.get_stats()
if stats["total"] == 0:
print("⚠️ Warning: No workflows found in database. Run indexing first.")
else:
print(f"✅ Database connected: {stats['total']} workflows indexed")
except Exception as e:
print(f"❌ Database connection failed: {e}")
raise
# Response models
class WorkflowSummary(BaseModel):
id: Optional[int] = None
filename: str
name: str
active: bool
description: str = ""
trigger_type: str = "Manual"
complexity: str = "low"
node_count: int = 0
integrations: List[str] = []
tags: List[str] = []
created_at: Optional[str] = None
updated_at: Optional[str] = None
class Config:
# Allow conversion of int to bool for active field
validate_assignment = True
@field_validator("active", mode="before")
@classmethod
def convert_active(cls, v):
if isinstance(v, int):
return bool(v)
return v
class SearchResponse(BaseModel):
workflows: List[WorkflowSummary]
total: int
page: int
per_page: int
pages: int
query: str
filters: Dict[str, Any]
class StatsResponse(BaseModel):
total: int
active: int
inactive: int
triggers: Dict[str, int]
complexity: Dict[str, int]
total_nodes: int
unique_integrations: int
last_indexed: str
@app.get("/")
async def root():
static_dir = Path("static")
index_file = static_dir / "index.html"
if not index_file.exists():
return HTMLResponse(
"""
<html><body>
<h1>Setup Required</h1>
<p>Static files not found. Please ensure the static directory exists with index.html</p>
<p>Current directory: """
+ str(Path.cwd())
+ """</p>
</body></html>
"""
)
return FileResponse(str(index_file))
@app.get("/health")
async def health_check():
return {"status": "healthy", "message": "N8N Workflow API is running"}
@app.get("/api/stats", response_model=StatsResponse)
async def get_stats():
try:
stats = db.get_stats()
return StatsResponse(**stats)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching stats: {str(e)}")
@app.get("/api/workflows", response_model=SearchResponse)
async def search_workflows(
q: str = Query("", description="Search query"),
trigger: str = Query("all", description="Filter by trigger type"),
complexity: str = Query("all", description="Filter by complexity"),
active_only: bool = Query(False, description="Show only active workflows"),
page: int = Query(1, ge=1, description="Page number"),
per_page: int = Query(20, ge=1, le=100, description="Items per page"),
):
try:
offset = (page - 1) * per_page
workflows, total = db.search_workflows(
query=q,
trigger_filter=trigger,
complexity_filter=complexity,
active_only=active_only,
limit=per_page,
offset=offset,
)
# Convert to Pydantic models with error handling
workflow_summaries = []
for workflow in workflows:
try:
# Remove extra fields that aren't in the model
clean_workflow = {
"id": workflow.get("id"),
"filename": workflow.get("filename", ""),
"name": workflow.get("name", ""),
"active": workflow.get("active", False),
"description": workflow.get("description", ""),
"trigger_type": workflow.get("trigger_type", "Manual"),
"complexity": workflow.get("complexity", "low"),
"node_count": workflow.get("node_count", 0),
"integrations": workflow.get("integrations", []),
"tags": workflow.get("tags", []),
"created_at": workflow.get("created_at"),
"updated_at": workflow.get("updated_at"),
}
workflow_summaries.append(WorkflowSummary(**clean_workflow))
except Exception as e:
print(
f"Error converting workflow {workflow.get('filename', 'unknown')}: {e}"
)
# Continue with other workflows instead of failing completely
continue
pages = (total + per_page - 1) // per_page # Ceiling division
return SearchResponse(
workflows=workflow_summaries,
total=total,
page=page,
per_page=per_page,
pages=pages,
query=q,
filters={
"trigger": trigger,
"complexity": complexity,
"active_only": active_only,
},
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error searching workflows: {str(e)}"
)
@app.get("/api/workflows/{filename}")
async def get_workflow_detail(filename: str, request: Request):
try:
# Security: Validate filename to prevent path traversal
if not validate_filename(filename):
print(f"Security: Blocked path traversal attempt for filename: {filename}")
raise HTTPException(status_code=400, detail="Invalid filename format")
# Security: Rate limiting
client_ip = request.client.host if request.client else "unknown"
if not check_rate_limit(client_ip):
raise HTTPException(
status_code=429, detail="Rate limit exceeded. Please try again later."
)
# Get workflow metadata from database
workflows, _ = db.search_workflows(f'filename:"{filename}"', limit=1)
if not workflows:
raise HTTPException(
status_code=404, detail="Workflow not found in database"
)
workflow_meta = workflows[0]
# Load raw JSON from file with security checks
workflows_path = Path("workflows").resolve()
# Find the file safely
matching_file = None
for subdir in workflows_path.iterdir():
if subdir.is_dir():
target_file = subdir / filename
if target_file.exists() and target_file.is_file():
# Verify the file is actually within workflows directory
try:
target_file.resolve().relative_to(workflows_path)
matching_file = target_file
break
except ValueError:
print(
f"Security: Blocked access to file outside workflows: {target_file}"
)
continue
if not matching_file:
print(f"Warning: File {filename} not found in workflows directory")
raise HTTPException(
status_code=404,
detail=f"Workflow file '{filename}' not found on filesystem",
)
with open(matching_file, "r", encoding="utf-8") as f:
raw_json = json.load(f)
return {"metadata": workflow_meta, "raw_json": raw_json}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error loading workflow: {str(e)}")
@app.get("/api/workflows/{filename}/download")
async def download_workflow(filename: str, request: Request):
try:
# Security: Validate filename to prevent path traversal
if not validate_filename(filename):
print(f"Security: Blocked path traversal attempt for filename: {filename}")
raise HTTPException(status_code=400, detail="Invalid filename format")
# Security: Rate limiting
client_ip = request.client.host if request.client else "unknown"
if not check_rate_limit(client_ip):
raise HTTPException(
status_code=429, detail="Rate limit exceeded. Please try again later."
)
# Only search within the workflows directory
workflows_path = Path("workflows").resolve() # Get absolute path
# Find the file safely
json_files = []
for subdir in workflows_path.iterdir():
if subdir.is_dir():
target_file = subdir / filename
if target_file.exists() and target_file.is_file():
# Verify the file is actually within workflows directory (defense in depth)
try:
target_file.resolve().relative_to(workflows_path)
json_files.append(target_file)
except ValueError:
# File is outside workflows directory
print(
f"Security: Blocked access to file outside workflows: {target_file}"
)
continue
if not json_files:
print(f"File {filename} not found in workflows directory")
raise HTTPException(
status_code=404, detail=f"Workflow file '{filename}' not found"
)
file_path = json_files[0]
# Final security check: Ensure file is within workflows directory
try:
file_path.resolve().relative_to(workflows_path)
except ValueError:
print(
f"Security: Blocked final attempt to access file outside workflows: {file_path}"
)
raise HTTPException(status_code=403, detail="Access denied")
return FileResponse(
str(file_path), media_type="application/json", filename=filename
)
except HTTPException:
raise
except Exception as e:
print(f"Error downloading workflow {filename}: {str(e)}")
raise HTTPException(
status_code=500, detail=f"Error downloading workflow: {str(e)}"
)
@app.get("/api/workflows/{filename}/diagram")
async def get_workflow_diagram(filename: str, request: Request):
try:
# Security: Validate filename to prevent path traversal
if not validate_filename(filename):
print(f"Security: Blocked path traversal attempt for filename: {filename}")
raise HTTPException(status_code=400, detail="Invalid filename format")
# Security: Rate limiting
client_ip = request.client.host if request.client else "unknown"
if not check_rate_limit(client_ip):
raise HTTPException(
status_code=429, detail="Rate limit exceeded. Please try again later."
)
# Only search within the workflows directory
workflows_path = Path("workflows").resolve()
# Find the file safely
matching_file = None
for subdir in workflows_path.iterdir():
if subdir.is_dir():
target_file = subdir / filename
if target_file.exists() and target_file.is_file():
# Verify the file is actually within workflows directory
try:
target_file.resolve().relative_to(workflows_path)
matching_file = target_file
break
except ValueError:
print(
f"Security: Blocked access to file outside workflows: {target_file}"
)
continue
if not matching_file:
print(f"Warning: File {filename} not found in workflows directory")
raise HTTPException(
status_code=404,
detail=f"Workflow file '{filename}' not found on filesystem",
)
with open(matching_file, "r", encoding="utf-8") as f:
data = json.load(f)
nodes = data.get("nodes", [])
connections = data.get("connections", {})
# Generate Mermaid diagram
diagram = generate_mermaid_diagram(nodes, connections)
return {"diagram": diagram}
except HTTPException:
raise
except json.JSONDecodeError as e:
print(f"Error parsing JSON in {filename}: {str(e)}")
raise HTTPException(
status_code=400, detail=f"Invalid JSON in workflow file: {str(e)}"
)
except Exception as e:
print(f"Error generating diagram for {filename}: {str(e)}")
raise HTTPException(
status_code=500, detail=f"Error generating diagram: {str(e)}"
)
def generate_mermaid_diagram(nodes: List[Dict], connections: Dict) -> str:
if not nodes:
return "graph TD\n EmptyWorkflow[No nodes found in workflow]"
# Create mapping for node names to ensure valid mermaid IDs
mermaid_ids = {}
for i, node in enumerate(nodes):
node_id = f"node{i}"
node_name = node.get("name", f"Node {i}")
mermaid_ids[node_name] = node_id
# Start building the mermaid diagram
mermaid_code = ["graph TD"]
# Add nodes with styling
for node in nodes:
node_name = node.get("name", "Unnamed")
node_id = mermaid_ids[node_name]
node_type = node.get("type", "").replace("n8n-nodes-base.", "")
# Determine node style based on type
style = ""
if any(x in node_type.lower() for x in ["trigger", "webhook", "cron"]):
style = "fill:#b3e0ff,stroke:#0066cc" # Blue for triggers
elif any(x in node_type.lower() for x in ["if", "switch"]):
style = "fill:#ffffb3,stroke:#e6e600" # Yellow for conditional nodes
elif any(x in node_type.lower() for x in ["function", "code"]):
style = "fill:#d9b3ff,stroke:#6600cc" # Purple for code nodes
elif "error" in node_type.lower():
style = "fill:#ffb3b3,stroke:#cc0000" # Red for error handlers
else:
style = "fill:#d9d9d9,stroke:#666666" # Gray for other nodes
# Add node with label (escaping special characters)
clean_name = node_name.replace('"', "'")
clean_type = node_type.replace('"', "'")
label = f"{clean_name}<br>({clean_type})"
mermaid_code.append(f' {node_id}["{label}"]')
mermaid_code.append(f" style {node_id} {style}")
# Add connections between nodes
for source_name, source_connections in connections.items():
if source_name not in mermaid_ids:
continue
if isinstance(source_connections, dict) and "main" in source_connections:
main_connections = source_connections["main"]
for i, output_connections in enumerate(main_connections):
if not isinstance(output_connections, list):
continue
for connection in output_connections:
if not isinstance(connection, dict) or "node" not in connection:
continue
target_name = connection["node"]
if target_name not in mermaid_ids:
continue
# Add arrow with output index if multiple outputs
label = f" -->|{i}| " if len(main_connections) > 1 else " --> "
mermaid_code.append(
f" {mermaid_ids[source_name]}{label}{mermaid_ids[target_name]}"
)
# Format the final mermaid diagram code
return "\n".join(mermaid_code)
@app.post("/api/reindex")
async def reindex_workflows(
background_tasks: BackgroundTasks,
request: Request,
force: bool = False,
admin_token: Optional[str] = Query(None, description="Admin authentication token"),
):
# Security: Rate limiting
client_ip = request.client.host if request.client else "unknown"
if not check_rate_limit(client_ip):
raise HTTPException(
status_code=429, detail="Rate limit exceeded. Please try again later."
)
# Security: Basic authentication check
# In production, use proper authentication (JWT, OAuth, etc.)
# For now, check for environment variable or disable endpoint
expected_token = os.environ.get("ADMIN_TOKEN", None)
if not expected_token:
# If no token is configured, disable the endpoint for security
raise HTTPException(
status_code=503,
detail="Reindexing endpoint is disabled. Set ADMIN_TOKEN environment variable to enable.",
)
if admin_token != expected_token:
print(f"Security: Unauthorized reindex attempt from {client_ip}")
raise HTTPException(status_code=401, detail="Invalid authentication token")
def run_indexing():
try:
db.index_all_workflows(force_reindex=force)
print(f"Reindexing completed successfully (requested by {client_ip})")
except Exception as e:
print(f"Error during reindexing: {e}")
background_tasks.add_task(run_indexing)
return {"message": "Reindexing started in background", "requested_by": client_ip}
@app.get("/api/integrations")
async def get_integrations():
try:
stats = db.get_stats()
# For now, return basic info. Could be enhanced to return detailed integration stats
return {"integrations": [], "count": stats["unique_integrations"]}
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error fetching integrations: {str(e)}"
)
@app.get("/api/categories")
async def get_categories():
try:
# Try to load from the generated unique categories file
categories_file = Path("context/unique_categories.json")
if categories_file.exists():
with open(categories_file, "r", encoding="utf-8") as f:
categories = json.load(f)
return {"categories": categories}
else:
# Fallback: extract categories from search_categories.json
search_categories_file = Path("context/search_categories.json")
if search_categories_file.exists():
with open(search_categories_file, "r", encoding="utf-8") as f:
search_data = json.load(f)
unique_categories = set()
for item in search_data:
if item.get("category"):
unique_categories.add(item["category"])
else:
unique_categories.add("Uncategorized")
categories = sorted(list(unique_categories))
return {"categories": categories}
else:
# Last resort: return basic categories
return {"categories": ["Uncategorized"]}
except Exception as e:
print(f"Error loading categories: {e}")
raise HTTPException(
status_code=500, detail=f"Error fetching categories: {str(e)}"
)
@app.get("/api/category-mappings")
async def get_category_mappings():
try:
search_categories_file = Path("context/search_categories.json")
if not search_categories_file.exists():
return {"mappings": {}}
with open(search_categories_file, "r", encoding="utf-8") as f:
search_data = json.load(f)
# Convert to a simple filename -> category mapping
mappings = {}
for item in search_data:
filename = item.get("filename")
category = item.get("category") or "Uncategorized"
if filename:
mappings[filename] = category
return {"mappings": mappings}
except Exception as e:
print(f"Error loading category mappings: {e}")
raise HTTPException(
status_code=500, detail=f"Error fetching category mappings: {str(e)}"
)
@app.get("/api/workflows/category/{category}", response_model=SearchResponse)
async def search_workflows_by_category(
category: str,
page: int = Query(1, ge=1, description="Page number"),
per_page: int = Query(20, ge=1, le=100, description="Items per page"),
):
try:
offset = (page - 1) * per_page
workflows, total = db.search_by_category(
category=category, limit=per_page, offset=offset
)
# Convert to Pydantic models with error handling
workflow_summaries = []
for workflow in workflows:
try:
clean_workflow = {
"id": workflow.get("id"),
"filename": workflow.get("filename", ""),
"name": workflow.get("name", ""),
"active": workflow.get("active", False),
"description": workflow.get("description", ""),
"trigger_type": workflow.get("trigger_type", "Manual"),
"complexity": workflow.get("complexity", "low"),
"node_count": workflow.get("node_count", 0),
"integrations": workflow.get("integrations", []),
"tags": workflow.get("tags", []),
"created_at": workflow.get("created_at"),
"updated_at": workflow.get("updated_at"),
}
workflow_summaries.append(WorkflowSummary(**clean_workflow))
except Exception as e:
print(
f"Error converting workflow {workflow.get('filename', 'unknown')}: {e}"
)
continue
pages = (total + per_page - 1) // per_page
return SearchResponse(
workflows=workflow_summaries,
total=total,
page=page,
per_page=per_page,
pages=pages,
query=f"category:{category}",
filters={"category": category},
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error searching by category: {str(e)}"
)
# Custom exception handler for better error responses
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
return JSONResponse(
status_code=500, content={"detail": f"Internal server error: {str(exc)}"}
)
# Mount static files AFTER all routes are defined
static_dir = Path("static")
if static_dir.exists():
app.mount("/static", StaticFiles(directory="static"), name="static")
print(f"✅ Static files mounted from {static_dir.absolute()}")
else:
print(f"❌ Warning: Static directory not found at {static_dir.absolute()}")
def create_static_directory():
static_dir = Path("static")
static_dir.mkdir(exist_ok=True)
return static_dir
def run_server(host: str = "127.0.0.1", port: int = 8000, reload: bool = False):
# Ensure static directory exists
create_static_directory()
# Debug: Check database connectivity
try:
stats = db.get_stats()
print(f"✅ Database connected: {stats['total']} workflows found")
if stats["total"] == 0:
print("🔄 Database is empty. Indexing workflows...")
db.index_all_workflows()
stats = db.get_stats()
except Exception as e:
print(f"❌ Database error: {e}")
print("🔄 Attempting to create and index database...")
try:
db.index_all_workflows()
stats = db.get_stats()
print(f"✅ Database created: {stats['total']} workflows indexed")
except Exception as e2:
print(f"❌ Failed to create database: {e2}")
stats = {"total": 0}
# Debug: Check static files
static_path = Path("static")
if static_path.exists():
files = list(static_path.glob("*"))
print(f"✅ Static files found: {[f.name for f in files]}")
else:
print(f"❌ Static directory not found at: {static_path.absolute()}")
print("🚀 Starting N8N Workflow Documentation API")
print(f"📊 Database contains {stats['total']} workflows")
print(f"🌐 Server will be available at: http://{host}:{port}")
print(f"📁 Static files at: http://{host}:{port}/static/")
uvicorn.run(
"api_server:app",
host=host,
port=port,
reload=reload,
access_log=True, # Enable access logs for debugging
log_level="info",
)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="N8N Workflow Documentation API Server"
)
parser.add_argument("--host", default="127.0.0.1", help="Host to bind to")
parser.add_argument("--port", type=int, default=8000, help="Port to bind to")
parser.add_argument(
"--reload", action="store_true", help="Enable auto-reload for development"
)
args = parser.parse_args()
run_server(host=args.host, port=args.port, reload=args.reload) | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+FastAPI Server for N8N Workflow Documentation
+High-performance API with sub-100ms response times.
+"""
from fastapi import FastAPI, HTTPException, Query, BackgroundTasks, Request
from fastapi.staticfiles import StaticFiles
@@ -57,6 +61,7 @@
# Security: Helper function for rate limiting
def check_rate_limit(client_ip: str) -> bool:
+ """Check if client has exceeded rate limit."""
current_time = time.time()
# Clean old entries
rate_limit_storage[client_ip] = [
@@ -74,6 +79,10 @@
# Security: Helper function to validate and sanitize filenames
def validate_filename(filename: str) -> bool:
+ """
+ Validate filename to prevent path traversal attacks.
+ Returns True if filename is safe, False otherwise.
+ """
# Decode URL encoding multiple times to catch encoded traversal attempts
decoded = filename
for _ in range(3): # Decode up to 3 times to catch nested encodings
@@ -130,6 +139,7 @@ # Startup function to verify database
@app.on_event("startup")
async def startup_event():
+ """Verify database connectivity on startup."""
try:
stats = db.get_stats()
if stats["total"] == 0:
@@ -191,6 +201,7 @@
@app.get("/")
async def root():
+ """Serve the main documentation page."""
static_dir = Path("static")
index_file = static_dir / "index.html"
if not index_file.exists():
@@ -210,11 +221,13 @@
@app.get("/health")
async def health_check():
+ """Health check endpoint."""
return {"status": "healthy", "message": "N8N Workflow API is running"}
@app.get("/api/stats", response_model=StatsResponse)
async def get_stats():
+ """Get workflow database statistics."""
try:
stats = db.get_stats()
return StatsResponse(**stats)
@@ -231,6 +244,7 @@ page: int = Query(1, ge=1, description="Page number"),
per_page: int = Query(20, ge=1, le=100, description="Items per page"),
):
+ """Search and filter workflows with pagination."""
try:
offset = (page - 1) * per_page
@@ -293,6 +307,7 @@
@app.get("/api/workflows/{filename}")
async def get_workflow_detail(filename: str, request: Request):
+ """Get detailed workflow information including raw JSON."""
try:
# Security: Validate filename to prevent path traversal
if not validate_filename(filename):
@@ -354,6 +369,7 @@
@app.get("/api/workflows/{filename}/download")
async def download_workflow(filename: str, request: Request):
+ """Download workflow JSON file with security validation."""
try:
# Security: Validate filename to prevent path traversal
if not validate_filename(filename):
@@ -418,6 +434,7 @@
@app.get("/api/workflows/{filename}/diagram")
async def get_workflow_diagram(filename: str, request: Request):
+ """Get Mermaid diagram code for workflow visualization."""
try:
# Security: Validate filename to prevent path traversal
if not validate_filename(filename):
@@ -483,6 +500,7 @@
def generate_mermaid_diagram(nodes: List[Dict], connections: Dict) -> str:
+ """Generate Mermaid.js flowchart code from workflow nodes and connections."""
if not nodes:
return "graph TD\n EmptyWorkflow[No nodes found in workflow]"
@@ -559,6 +577,7 @@ force: bool = False,
admin_token: Optional[str] = Query(None, description="Admin authentication token"),
):
+ """Trigger workflow reindexing in the background (requires authentication)."""
# Security: Rate limiting
client_ip = request.client.host if request.client else "unknown"
if not check_rate_limit(client_ip):
@@ -596,6 +615,7 @@
@app.get("/api/integrations")
async def get_integrations():
+ """Get list of all unique integrations."""
try:
stats = db.get_stats()
# For now, return basic info. Could be enhanced to return detailed integration stats
@@ -608,6 +628,7 @@
@app.get("/api/categories")
async def get_categories():
+ """Get available workflow categories for filtering."""
try:
# Try to load from the generated unique categories file
categories_file = Path("context/unique_categories.json")
@@ -644,6 +665,7 @@
@app.get("/api/category-mappings")
async def get_category_mappings():
+ """Get filename to category mappings for client-side filtering."""
try:
search_categories_file = Path("context/search_categories.json")
if not search_categories_file.exists():
@@ -675,6 +697,7 @@ page: int = Query(1, ge=1, description="Page number"),
per_page: int = Query(20, ge=1, le=100, description="Items per page"),
):
+ """Search workflows by service category (messaging, database, ai_ml, etc.)."""
try:
offset = (page - 1) * per_page
@@ -742,12 +765,14 @@
def create_static_directory():
+ """Create static directory if it doesn't exist."""
static_dir = Path("static")
static_dir.mkdir(exist_ok=True)
return static_dir
def run_server(host: str = "127.0.0.1", port: int = 8000, reload: bool = False):
+ """Run the FastAPI server."""
# Ensure static directory exists
create_static_directory()
@@ -807,4 +832,4 @@
args = parser.parse_args()
- run_server(host=args.host, port=args.port, reload=args.reload)+ run_server(host=args.host, port=args.port, reload=args.reload)
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/api_server.py |
Write docstrings that follow conventions | #!/usr/bin/env python3
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, EmailStr
from typing import List, Optional
import sqlite3
import hashlib
import secrets
import jwt
from datetime import datetime, timedelta
import os
# Configuration - Use environment variables for security
SECRET_KEY = os.environ.get("JWT_SECRET_KEY", secrets.token_urlsafe(32))
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# Security
security = HTTPBearer()
class User(BaseModel):
id: Optional[int] = None
username: str
email: EmailStr
full_name: str
role: str = "user"
active: bool = True
created_at: Optional[str] = None
class UserCreate(BaseModel):
username: str
email: EmailStr
full_name: str
password: str
role: str = "user"
class UserLogin(BaseModel):
username: str
password: str
class UserUpdate(BaseModel):
full_name: Optional[str] = None
email: Optional[EmailStr] = None
role: Optional[str] = None
active: Optional[bool] = None
class Token(BaseModel):
access_token: str
token_type: str
expires_in: int
class UserManager:
def __init__(self, db_path: str = "users.db"):
self.db_path = db_path
self.init_database()
def init_database(self):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
full_name TEXT NOT NULL,
password_hash TEXT NOT NULL,
role TEXT DEFAULT 'user',
active BOOLEAN DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_login TIMESTAMP
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
token_hash TEXT UNIQUE NOT NULL,
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id)
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_permissions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
resource TEXT NOT NULL,
action TEXT NOT NULL,
granted BOOLEAN DEFAULT 1,
FOREIGN KEY (user_id) REFERENCES users (id)
)
""")
conn.commit()
conn.close()
# Create default admin user if none exists
self.create_default_admin()
def create_default_admin(self):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM users WHERE role = 'admin'")
admin_count = cursor.fetchone()[0]
if admin_count == 0:
# Use environment variable or generate secure random password
admin_password = os.environ.get("ADMIN_PASSWORD", secrets.token_urlsafe(16))
password_hash = self.hash_password(admin_password)
cursor.execute(
"""
INSERT INTO users (username, email, full_name, password_hash, role)
VALUES (?, ?, ?, ?, ?)
""",
(
"admin",
"admin@n8n-workflows.com",
"System Administrator",
password_hash,
"admin",
),
)
conn.commit()
# Only print password if it was auto-generated (not from env)
if "ADMIN_PASSWORD" not in os.environ:
print(f"Default admin user created: admin/{admin_password}")
print(
"WARNING: Please change this password immediately after first login!"
)
else:
print("Default admin user created with environment-configured password")
conn.close()
def hash_password(self, password: str) -> str:
return hashlib.sha256(password.encode()).hexdigest()
def verify_password(self, password: str, hashed: str) -> bool:
return self.hash_password(password) == hashed
def create_user(self, user_data: UserCreate) -> User:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
try:
# Check if username or email already exists
cursor.execute(
"SELECT COUNT(*) FROM users WHERE username = ? OR email = ?",
(user_data.username, user_data.email),
)
if cursor.fetchone()[0] > 0:
raise ValueError("Username or email already exists")
password_hash = self.hash_password(user_data.password)
cursor.execute(
"""
INSERT INTO users (username, email, full_name, password_hash, role)
VALUES (?, ?, ?, ?, ?)
""",
(
user_data.username,
user_data.email,
user_data.full_name,
password_hash,
user_data.role,
),
)
user_id = cursor.lastrowid
conn.commit()
return User(
id=user_id,
username=user_data.username,
email=user_data.email,
full_name=user_data.full_name,
role=user_data.role,
active=True,
created_at=datetime.now().isoformat(),
)
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
def authenticate_user(self, username: str, password: str) -> Optional[User]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT id, username, email, full_name, password_hash, role, active
FROM users WHERE username = ? AND active = 1
""",
(username,),
)
row = cursor.fetchone()
conn.close()
if row and self.verify_password(password, row[4]):
return User(
id=row[0],
username=row[1],
email=row[2],
full_name=row[3],
role=row[5],
active=bool(row[6]),
)
return None
def create_access_token(self, user: User) -> str:
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode = {
"sub": str(user.id),
"username": user.username,
"role": user.role,
"exp": expire,
}
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def verify_token(self, token: str) -> Optional[User]:
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id = payload.get("sub")
username = payload.get("username")
role = payload.get("role")
if user_id is None or username is None:
return None
return User(id=int(user_id), username=username, role=role)
except jwt.PyJWTError:
return None
def get_user_by_id(self, user_id: int) -> Optional[User]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT id, username, email, full_name, role, active, created_at
FROM users WHERE id = ?
""",
(user_id,),
)
row = cursor.fetchone()
conn.close()
if row:
return User(
id=row[0],
username=row[1],
email=row[2],
full_name=row[3],
role=row[4],
active=bool(row[5]),
created_at=row[6],
)
return None
def get_all_users(self) -> List[User]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
SELECT id, username, email, full_name, role, active, created_at
FROM users ORDER BY created_at DESC
""")
users = []
for row in cursor.fetchall():
users.append(
User(
id=row[0],
username=row[1],
email=row[2],
full_name=row[3],
role=row[4],
active=bool(row[5]),
created_at=row[6],
)
)
conn.close()
return users
def update_user(self, user_id: int, update_data: UserUpdate) -> Optional[User]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
try:
# Build update query dynamically
updates = []
params = []
if update_data.full_name is not None:
updates.append("full_name = ?")
params.append(update_data.full_name)
if update_data.email is not None:
updates.append("email = ?")
params.append(update_data.email)
if update_data.role is not None:
updates.append("role = ?")
params.append(update_data.role)
if update_data.active is not None:
updates.append("active = ?")
params.append(update_data.active)
if not updates:
return self.get_user_by_id(user_id)
params.append(user_id)
query = f"UPDATE users SET {', '.join(updates)} WHERE id = ?"
cursor.execute(query, params)
conn.commit()
return self.get_user_by_id(user_id)
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
def delete_user(self, user_id: int) -> bool:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
try:
cursor.execute("UPDATE users SET active = 0 WHERE id = ?", (user_id,))
conn.commit()
return cursor.rowcount > 0
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
# Initialize user manager
user_manager = UserManager()
# FastAPI app for User Management
user_app = FastAPI(title="N8N User Management", version="1.0.0")
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
) -> User:
token = credentials.credentials
user = user_manager.verify_token(token)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return user
def require_admin(current_user: User = Depends(get_current_user)) -> User:
if current_user.role != "admin":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required"
)
return current_user
@user_app.post("/auth/register", response_model=User)
async def register_user(user_data: UserCreate):
try:
user = user_manager.create_user(user_data)
return user
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@user_app.post("/auth/login", response_model=Token)
async def login_user(login_data: UserLogin):
user = user_manager.authenticate_user(login_data.username, login_data.password)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = user_manager.create_access_token(user)
return Token(
access_token=access_token,
token_type="bearer",
expires_in=ACCESS_TOKEN_EXPIRE_MINUTES * 60,
)
@user_app.get("/auth/me", response_model=User)
async def get_current_user_info(current_user: User = Depends(get_current_user)):
return current_user
@user_app.get("/users", response_model=List[User])
async def get_all_users(admin: User = Depends(require_admin)):
return user_manager.get_all_users()
@user_app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int, current_user: User = Depends(get_current_user)):
# Users can only view their own profile unless they're admin
if current_user.id != user_id and current_user.role != "admin":
raise HTTPException(status_code=403, detail="Access denied")
user = user_manager.get_user_by_id(user_id)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user
@user_app.put("/users/{user_id}", response_model=User)
async def update_user(
user_id: int,
update_data: UserUpdate,
current_user: User = Depends(get_current_user),
):
# Users can only update their own profile unless they're admin
if current_user.id != user_id and current_user.role != "admin":
raise HTTPException(status_code=403, detail="Access denied")
# Non-admin users cannot change roles
if current_user.role != "admin" and update_data.role is not None:
raise HTTPException(status_code=403, detail="Cannot change role")
user = user_manager.update_user(user_id, update_data)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user
@user_app.delete("/users/{user_id}")
async def delete_user(user_id: int, admin: User = Depends(require_admin)):
success = user_manager.delete_user(user_id)
if not success:
raise HTTPException(status_code=404, detail="User not found")
return {"message": "User deleted successfully"}
@user_app.get("/auth/dashboard")
async def get_auth_dashboard():
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N8N User Management</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
color: #333;
}
.dashboard {
max-width: 1000px;
margin: 0 auto;
padding: 20px;
}
.header {
background: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
text-align: center;
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}
.header h1 {
font-size: 32px;
margin-bottom: 10px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.auth-section {
background: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.auth-tabs {
display: flex;
margin-bottom: 20px;
border-bottom: 2px solid #e9ecef;
}
.tab {
padding: 15px 30px;
cursor: pointer;
border-bottom: 3px solid transparent;
transition: all 0.3s ease;
}
.tab.active {
border-bottom-color: #667eea;
color: #667eea;
font-weight: bold;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: #333;
}
.form-group input {
width: 100%;
padding: 12px;
border: 2px solid #e9ecef;
border-radius: 8px;
font-size: 16px;
transition: border-color 0.3s ease;
}
.form-group input:focus {
outline: none;
border-color: #667eea;
}
.btn {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
transition: all 0.3s ease;
text-decoration: none;
display: inline-block;
text-align: center;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5a6fd8;
}
.btn-secondary {
background: #f8f9fa;
color: #666;
border: 1px solid #e9ecef;
}
.btn-secondary:hover {
background: #e9ecef;
}
.user-list {
background: white;
padding: 30px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.user-card {
background: #f8f9fa;
padding: 20px;
border-radius: 10px;
margin-bottom: 15px;
display: flex;
justify-content: space-between;
align-items: center;
}
.user-info h3 {
margin-bottom: 5px;
color: #333;
}
.user-info p {
color: #666;
font-size: 14px;
}
.user-role {
background: #667eea;
color: white;
padding: 4px 12px;
border-radius: 15px;
font-size: 12px;
font-weight: bold;
}
.user-role.admin {
background: #dc3545;
}
.status-indicator {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 8px;
}
.status-online {
background: #28a745;
}
.status-offline {
background: #dc3545;
}
.message {
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
display: none;
}
.message.success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.message.error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
</style>
</head>
<body>
<div class="dashboard">
<div class="header">
<h1>👥 N8N User Management</h1>
<p>Manage users, roles, and access control for your workflow platform</p>
</div>
<div class="auth-section">
<div class="auth-tabs">
<div class="tab active" onclick="showTab('login')">Login</div>
<div class="tab" onclick="showTab('register')">Register</div>
</div>
<div id="message" class="message"></div>
<div id="login" class="tab-content active">
<h2>Login to Your Account</h2>
<form id="loginForm">
<div class="form-group">
<label for="loginUsername">Username</label>
<input type="text" id="loginUsername" required>
</div>
<div class="form-group">
<label for="loginPassword">Password</label>
<input type="password" id="loginPassword" required>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
<div id="register" class="tab-content">
<h2>Create New Account</h2>
<form id="registerForm">
<div class="form-group">
<label for="regUsername">Username</label>
<input type="text" id="regUsername" required>
</div>
<div class="form-group">
<label for="regEmail">Email</label>
<input type="email" id="regEmail" required>
</div>
<div class="form-group">
<label for="regFullName">Full Name</label>
<input type="text" id="regFullName" required>
</div>
<div class="form-group">
<label for="regPassword">Password</label>
<input type="password" id="regPassword" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
<div class="user-list" id="userList" style="display: none;">
<h2>User Management</h2>
<div id="usersContainer">
<div class="loading">Loading users...</div>
</div>
</div>
</div>
<script>
let currentUser = null;
let authToken = null;
function showTab(tabName) {
// Hide all tabs
document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
// Show selected tab
event.target.classList.add('active');
document.getElementById(tabName).classList.add('active');
}
function showMessage(message, type) {
const messageDiv = document.getElementById('message');
messageDiv.textContent = message;
messageDiv.className = `message ${type}`;
messageDiv.style.display = 'block';
setTimeout(() => {
messageDiv.style.display = 'none';
}, 5000);
}
async function login(username, password) {
try {
const response = await fetch('/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({username, password})
});
if (response.ok) {
const data = await response.json();
authToken = data.access_token;
currentUser = await getCurrentUser();
showMessage('Login successful!', 'success');
loadUsers();
} else {
const error = await response.json();
showMessage(error.detail || 'Login failed', 'error');
}
} catch (error) {
showMessage('Login error: ' + error.message, 'error');
}
}
async function register(username, email, fullName, password) {
try {
const response = await fetch('/auth/register', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({username, email, full_name: fullName, password, role: 'user'})
});
if (response.ok) {
showMessage('Registration successful! Please login.', 'success');
showTab('login');
} else {
const error = await response.json();
showMessage(error.detail || 'Registration failed', 'error');
}
} catch (error) {
showMessage('Registration error: ' + error.message, 'error');
}
}
async function getCurrentUser() {
if (!authToken) return null;
try {
const response = await fetch('/auth/me', {
headers: {'Authorization': `Bearer ${authToken}`}
});
if (response.ok) {
return await response.json();
}
} catch (error) {
console.error('Error getting current user:', error);
}
return null;
}
async function loadUsers() {
if (!authToken) return;
try {
const response = await fetch('/users', {
headers: {'Authorization': `Bearer ${authToken}`}
});
if (response.ok) {
const users = await response.json();
displayUsers(users);
document.getElementById('userList').style.display = 'block';
} else {
showMessage('Failed to load users', 'error');
}
} catch (error) {
showMessage('Error loading users: ' + error.message, 'error');
}
}
function displayUsers(users) {
const container = document.getElementById('usersContainer');
container.innerHTML = users.map(user => `
<div class="user-card">
<div class="user-info">
<h3>${user.full_name}</h3>
<p>@${user.username} • ${user.email}</p>
</div>
<div>
<span class="user-role ${user.role}">${user.role.toUpperCase()}</span>
<span class="status-indicator ${user.active ? 'status-online' : 'status-offline'}"></span>
</div>
</div>
`).join('');
}
// Event listeners
document.getElementById('loginForm').addEventListener('submit', (e) => {
e.preventDefault();
const username = document.getElementById('loginUsername').value;
const password = document.getElementById('loginPassword').value;
login(username, password);
});
document.getElementById('registerForm').addEventListener('submit', (e) => {
e.preventDefault();
const username = document.getElementById('regUsername').value;
const email = document.getElementById('regEmail').value;
const fullName = document.getElementById('regFullName').value;
const password = document.getElementById('regPassword').value;
register(username, email, fullName, password);
});
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
uvicorn.run(user_app, host="127.0.0.1", port=8004) | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+User Management System for N8N Workflows
+Multi-user access control and authentication.
+"""
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
@@ -63,6 +67,7 @@ self.init_database()
def init_database(self):
+ """Initialize user database."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -109,6 +114,7 @@ self.create_default_admin()
def create_default_admin(self):
+ """Create default admin user if none exists."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -147,12 +153,15 @@ conn.close()
def hash_password(self, password: str) -> str:
+ """Hash password using SHA-256."""
return hashlib.sha256(password.encode()).hexdigest()
def verify_password(self, password: str, hashed: str) -> bool:
+ """Verify password against hash."""
return self.hash_password(password) == hashed
def create_user(self, user_data: UserCreate) -> User:
+ """Create a new user."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -201,6 +210,7 @@ conn.close()
def authenticate_user(self, username: str, password: str) -> Optional[User]:
+ """Authenticate user and return user data."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -228,6 +238,7 @@ return None
def create_access_token(self, user: User) -> str:
+ """Create JWT access token."""
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode = {
"sub": str(user.id),
@@ -238,6 +249,7 @@ return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def verify_token(self, token: str) -> Optional[User]:
+ """Verify JWT token and return user data."""
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id = payload.get("sub")
@@ -252,6 +264,7 @@ return None
def get_user_by_id(self, user_id: int) -> Optional[User]:
+ """Get user by ID."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -280,6 +293,7 @@ return None
def get_all_users(self) -> List[User]:
+ """Get all users."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -306,6 +320,7 @@ return users
def update_user(self, user_id: int, update_data: UserUpdate) -> Optional[User]:
+ """Update user data."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -348,6 +363,7 @@ conn.close()
def delete_user(self, user_id: int) -> bool:
+ """Delete user (soft delete by setting active=False)."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -372,6 +388,7 @@ def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
) -> User:
+ """Get current authenticated user."""
token = credentials.credentials
user = user_manager.verify_token(token)
@@ -386,6 +403,7 @@
def require_admin(current_user: User = Depends(get_current_user)) -> User:
+ """Require admin role."""
if current_user.role != "admin":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required"
@@ -395,6 +413,7 @@
@user_app.post("/auth/register", response_model=User)
async def register_user(user_data: UserCreate):
+ """Register a new user."""
try:
user = user_manager.create_user(user_data)
return user
@@ -406,6 +425,7 @@
@user_app.post("/auth/login", response_model=Token)
async def login_user(login_data: UserLogin):
+ """Login user and return access token."""
user = user_manager.authenticate_user(login_data.username, login_data.password)
if user is None:
@@ -426,16 +446,19 @@
@user_app.get("/auth/me", response_model=User)
async def get_current_user_info(current_user: User = Depends(get_current_user)):
+ """Get current user information."""
return current_user
@user_app.get("/users", response_model=List[User])
async def get_all_users(admin: User = Depends(require_admin)):
+ """Get all users (admin only)."""
return user_manager.get_all_users()
@user_app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int, current_user: User = Depends(get_current_user)):
+ """Get user by ID."""
# Users can only view their own profile unless they're admin
if current_user.id != user_id and current_user.role != "admin":
raise HTTPException(status_code=403, detail="Access denied")
@@ -453,6 +476,7 @@ update_data: UserUpdate,
current_user: User = Depends(get_current_user),
):
+ """Update user data."""
# Users can only update their own profile unless they're admin
if current_user.id != user_id and current_user.role != "admin":
raise HTTPException(status_code=403, detail="Access denied")
@@ -470,6 +494,7 @@
@user_app.delete("/users/{user_id}")
async def delete_user(user_id: int, admin: User = Depends(require_admin)):
+ """Delete user (admin only)."""
success = user_manager.delete_user(user_id)
if not success:
raise HTTPException(status_code=404, detail="User not found")
@@ -479,6 +504,7 @@
@user_app.get("/auth/dashboard")
async def get_auth_dashboard():
+ """Get authentication dashboard HTML."""
html_content = """
<!DOCTYPE html>
<html lang="en">
@@ -864,4 +890,4 @@ if __name__ == "__main__":
import uvicorn
- uvicorn.run(user_app, host="127.0.0.1", port=8004)+ uvicorn.run(user_app, host="127.0.0.1", port=8004)
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/src/user_management.py |
Generate NumPy-style docstrings | #!/usr/bin/env python3
import sqlite3
import json
from datetime import datetime
from typing import Dict, List, Optional
from dataclasses import dataclass
@dataclass
class WorkflowRating:
workflow_id: str
user_id: str
rating: int # 1-5 stars
review: Optional[str] = None
helpful_votes: int = 0
created_at: datetime = None
updated_at: datetime = None
@dataclass
class WorkflowStats:
workflow_id: str
total_ratings: int
average_rating: float
total_reviews: int
total_views: int
total_downloads: int
last_updated: datetime
class CommunityFeatures:
def __init__(self, db_path: str = "workflows.db"):
self.db_path = db_path
self.init_community_tables()
def init_community_tables(self):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Workflow ratings and reviews
cursor.execute("""
CREATE TABLE IF NOT EXISTS workflow_ratings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
workflow_id TEXT NOT NULL,
user_id TEXT NOT NULL,
rating INTEGER CHECK(rating >= 1 AND rating <= 5),
review TEXT,
helpful_votes INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(workflow_id, user_id)
)
""")
# Workflow usage statistics
cursor.execute("""
CREATE TABLE IF NOT EXISTS workflow_stats (
workflow_id TEXT PRIMARY KEY,
total_ratings INTEGER DEFAULT 0,
average_rating REAL DEFAULT 0.0,
total_reviews INTEGER DEFAULT 0,
total_views INTEGER DEFAULT 0,
total_downloads INTEGER DEFAULT 0,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# User profiles
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_profiles (
user_id TEXT PRIMARY KEY,
username TEXT,
display_name TEXT,
email TEXT,
avatar_url TEXT,
bio TEXT,
github_url TEXT,
website_url TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Workflow collections (user favorites)
cursor.execute("""
CREATE TABLE IF NOT EXISTS workflow_collections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
collection_name TEXT NOT NULL,
workflow_ids TEXT, -- JSON array of workflow IDs
is_public BOOLEAN DEFAULT FALSE,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Workflow comments
cursor.execute("""
CREATE TABLE IF NOT EXISTS workflow_comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
workflow_id TEXT NOT NULL,
user_id TEXT NOT NULL,
parent_id INTEGER, -- For threaded comments
comment TEXT NOT NULL,
helpful_votes INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()
def add_rating(
self, workflow_id: str, user_id: str, rating: int, review: str = None
) -> bool:
if not (1 <= rating <= 5):
raise ValueError("Rating must be between 1 and 5")
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
try:
# Insert or update rating
cursor.execute(
"""
INSERT OR REPLACE INTO workflow_ratings
(workflow_id, user_id, rating, review, updated_at)
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
""",
(workflow_id, user_id, rating, review),
)
# Update workflow statistics
self._update_workflow_stats(workflow_id)
conn.commit()
return True
except Exception as e:
print(f"Error adding rating: {e}")
return False
finally:
conn.close()
def get_workflow_ratings(
self, workflow_id: str, limit: int = 10
) -> List[WorkflowRating]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT workflow_id, user_id, rating, review, helpful_votes, created_at, updated_at
FROM workflow_ratings
WHERE workflow_id = ?
ORDER BY helpful_votes DESC, created_at DESC
LIMIT ?
""",
(workflow_id, limit),
)
ratings = []
for row in cursor.fetchall():
ratings.append(
WorkflowRating(
workflow_id=row[0],
user_id=row[1],
rating=row[2],
review=row[3],
helpful_votes=row[4],
created_at=datetime.fromisoformat(row[5]) if row[5] else None,
updated_at=datetime.fromisoformat(row[6]) if row[6] else None,
)
)
conn.close()
return ratings
def get_workflow_stats(self, workflow_id: str) -> Optional[WorkflowStats]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT workflow_id, total_ratings, average_rating, total_reviews,
total_views, total_downloads, last_updated
FROM workflow_stats
WHERE workflow_id = ?
""",
(workflow_id,),
)
row = cursor.fetchone()
conn.close()
if row:
return WorkflowStats(
workflow_id=row[0],
total_ratings=row[1],
average_rating=row[2],
total_reviews=row[3],
total_views=row[4],
total_downloads=row[5],
last_updated=datetime.fromisoformat(row[6]) if row[6] else None,
)
return None
def increment_view(self, workflow_id: str):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
INSERT OR IGNORE INTO workflow_stats (workflow_id, total_views)
VALUES (?, 1)
""",
(workflow_id,),
)
cursor.execute(
"""
UPDATE workflow_stats
SET total_views = total_views + 1, last_updated = CURRENT_TIMESTAMP
WHERE workflow_id = ?
""",
(workflow_id,),
)
conn.commit()
conn.close()
def increment_download(self, workflow_id: str):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
INSERT OR IGNORE INTO workflow_stats (workflow_id, total_downloads)
VALUES (?, 1)
""",
(workflow_id,),
)
cursor.execute(
"""
UPDATE workflow_stats
SET total_downloads = total_downloads + 1, last_updated = CURRENT_TIMESTAMP
WHERE workflow_id = ?
""",
(workflow_id,),
)
conn.commit()
conn.close()
def get_top_rated_workflows(self, limit: int = 10) -> List[Dict]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT w.filename, w.name, w.description, ws.average_rating, ws.total_ratings
FROM workflows w
JOIN workflow_stats ws ON w.filename = ws.workflow_id
WHERE ws.total_ratings >= 3
ORDER BY ws.average_rating DESC, ws.total_ratings DESC
LIMIT ?
""",
(limit,),
)
results = []
for row in cursor.fetchall():
results.append(
{
"filename": row[0],
"name": row[1],
"description": row[2],
"average_rating": row[3],
"total_ratings": row[4],
}
)
conn.close()
return results
def get_most_popular_workflows(self, limit: int = 10) -> List[Dict]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT w.filename, w.name, w.description, ws.total_views, ws.total_downloads
FROM workflows w
LEFT JOIN workflow_stats ws ON w.filename = ws.workflow_id
ORDER BY (ws.total_views + ws.total_downloads) DESC
LIMIT ?
""",
(limit,),
)
results = []
for row in cursor.fetchall():
results.append(
{
"filename": row[0],
"name": row[1],
"description": row[2],
"total_views": row[3] or 0,
"total_downloads": row[4] or 0,
}
)
conn.close()
return results
def create_collection(
self,
user_id: str,
collection_name: str,
workflow_ids: List[str],
is_public: bool = False,
description: str = None,
) -> bool:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
try:
cursor.execute(
"""
INSERT INTO workflow_collections
(user_id, collection_name, workflow_ids, is_public, description)
VALUES (?, ?, ?, ?, ?)
""",
(
user_id,
collection_name,
json.dumps(workflow_ids),
is_public,
description,
),
)
conn.commit()
return True
except Exception as e:
print(f"Error creating collection: {e}")
return False
finally:
conn.close()
def get_user_collections(self, user_id: str) -> List[Dict]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT id, collection_name, workflow_ids, is_public, description, created_at
FROM workflow_collections
WHERE user_id = ?
ORDER BY created_at DESC
""",
(user_id,),
)
collections = []
for row in cursor.fetchall():
collections.append(
{
"id": row[0],
"name": row[1],
"workflow_ids": json.loads(row[2]) if row[2] else [],
"is_public": bool(row[3]),
"description": row[4],
"created_at": row[5],
}
)
conn.close()
return collections
def _update_workflow_stats(self, workflow_id: str):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Calculate new statistics
cursor.execute(
"""
SELECT COUNT(*), AVG(rating), COUNT(CASE WHEN review IS NOT NULL THEN 1 END)
FROM workflow_ratings
WHERE workflow_id = ?
""",
(workflow_id,),
)
total_ratings, avg_rating, total_reviews = cursor.fetchone()
# Update or insert statistics
cursor.execute(
"""
INSERT OR REPLACE INTO workflow_stats
(workflow_id, total_ratings, average_rating, total_reviews, last_updated)
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
""",
(workflow_id, total_ratings or 0, avg_rating or 0.0, total_reviews or 0),
)
conn.commit()
conn.close()
# Example usage and API endpoints
def create_community_api_endpoints(app):
community = CommunityFeatures()
@app.post("/api/workflows/{workflow_id}/rate")
async def rate_workflow(workflow_id: str, rating_data: dict):
try:
success = community.add_rating(
workflow_id=workflow_id,
user_id=rating_data.get("user_id", "anonymous"),
rating=rating_data["rating"],
review=rating_data.get("review"),
)
return {"success": success}
except Exception as e:
return {"error": str(e)}
@app.get("/api/workflows/{workflow_id}/ratings")
async def get_workflow_ratings(workflow_id: str, limit: int = 10):
ratings = community.get_workflow_ratings(workflow_id, limit)
return {"ratings": ratings}
@app.get("/api/workflows/{workflow_id}/stats")
async def get_workflow_stats(workflow_id: str):
stats = community.get_workflow_stats(workflow_id)
return {"stats": stats}
@app.get("/api/workflows/top-rated")
async def get_top_rated_workflows(limit: int = 10):
workflows = community.get_top_rated_workflows(limit)
return {"workflows": workflows}
@app.get("/api/workflows/most-popular")
async def get_most_popular_workflows(limit: int = 10):
workflows = community.get_most_popular_workflows(limit)
return {"workflows": workflows}
@app.post("/api/workflows/{workflow_id}/view")
async def track_workflow_view(workflow_id: str):
community.increment_view(workflow_id)
return {"success": True}
@app.post("/api/workflows/{workflow_id}/download")
async def track_workflow_download(workflow_id: str):
community.increment_download(workflow_id)
return {"success": True}
if __name__ == "__main__":
# Initialize community features
community = CommunityFeatures()
print("✅ Community features initialized successfully!")
# Example: Add a rating
# community.add_rating("example-workflow.json", "user123", 5, "Great workflow!")
# Example: Get top-rated workflows
top_workflows = community.get_top_rated_workflows(5)
print(f"📊 Top rated workflows: {len(top_workflows)}") | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Community Features Module for n8n Workflows Repository
+Implements rating, review, and social features
+"""
import sqlite3
import json
@@ -9,6 +13,7 @@
@dataclass
class WorkflowRating:
+ """Workflow rating data structure"""
workflow_id: str
user_id: str
@@ -21,6 +26,7 @@
@dataclass
class WorkflowStats:
+ """Workflow statistics"""
workflow_id: str
total_ratings: int
@@ -32,12 +38,15 @@
class CommunityFeatures:
+ """Community features manager for workflow repository"""
def __init__(self, db_path: str = "workflows.db"):
+ """Initialize community features with database connection"""
self.db_path = db_path
self.init_community_tables()
def init_community_tables(self):
+ """Initialize community feature database tables"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -119,6 +128,7 @@ def add_rating(
self, workflow_id: str, user_id: str, rating: int, review: str = None
) -> bool:
+ """Add or update a workflow rating and review"""
if not (1 <= rating <= 5):
raise ValueError("Rating must be between 1 and 5")
@@ -151,6 +161,7 @@ def get_workflow_ratings(
self, workflow_id: str, limit: int = 10
) -> List[WorkflowRating]:
+ """Get ratings and reviews for a workflow"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -183,6 +194,7 @@ return ratings
def get_workflow_stats(self, workflow_id: str) -> Optional[WorkflowStats]:
+ """Get comprehensive statistics for a workflow"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -212,6 +224,7 @@ return None
def increment_view(self, workflow_id: str):
+ """Increment view count for a workflow"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -236,6 +249,7 @@ conn.close()
def increment_download(self, workflow_id: str):
+ """Increment download count for a workflow"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -260,6 +274,7 @@ conn.close()
def get_top_rated_workflows(self, limit: int = 10) -> List[Dict]:
+ """Get top-rated workflows"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -291,6 +306,7 @@ return results
def get_most_popular_workflows(self, limit: int = 10) -> List[Dict]:
+ """Get most popular workflows by views and downloads"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -328,6 +344,7 @@ is_public: bool = False,
description: str = None,
) -> bool:
+ """Create a workflow collection"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -357,6 +374,7 @@ conn.close()
def get_user_collections(self, user_id: str) -> List[Dict]:
+ """Get collections for a user"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -387,6 +405,7 @@ return collections
def _update_workflow_stats(self, workflow_id: str):
+ """Update workflow statistics after rating changes"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -418,10 +437,12 @@
# Example usage and API endpoints
def create_community_api_endpoints(app):
+ """Add community feature endpoints to FastAPI app"""
community = CommunityFeatures()
@app.post("/api/workflows/{workflow_id}/rate")
async def rate_workflow(workflow_id: str, rating_data: dict):
+ """Rate a workflow"""
try:
success = community.add_rating(
workflow_id=workflow_id,
@@ -435,31 +456,37 @@
@app.get("/api/workflows/{workflow_id}/ratings")
async def get_workflow_ratings(workflow_id: str, limit: int = 10):
+ """Get workflow ratings and reviews"""
ratings = community.get_workflow_ratings(workflow_id, limit)
return {"ratings": ratings}
@app.get("/api/workflows/{workflow_id}/stats")
async def get_workflow_stats(workflow_id: str):
+ """Get workflow statistics"""
stats = community.get_workflow_stats(workflow_id)
return {"stats": stats}
@app.get("/api/workflows/top-rated")
async def get_top_rated_workflows(limit: int = 10):
+ """Get top-rated workflows"""
workflows = community.get_top_rated_workflows(limit)
return {"workflows": workflows}
@app.get("/api/workflows/most-popular")
async def get_most_popular_workflows(limit: int = 10):
+ """Get most popular workflows"""
workflows = community.get_most_popular_workflows(limit)
return {"workflows": workflows}
@app.post("/api/workflows/{workflow_id}/view")
async def track_workflow_view(workflow_id: str):
+ """Track workflow view"""
community.increment_view(workflow_id)
return {"success": True}
@app.post("/api/workflows/{workflow_id}/download")
async def track_workflow_download(workflow_id: str):
+ """Track workflow download"""
community.increment_download(workflow_id)
return {"success": True}
@@ -474,4 +501,4 @@
# Example: Get top-rated workflows
top_workflows = community.get_top_rated_workflows(5)
- print(f"📊 Top rated workflows: {len(top_workflows)}")+ print(f"📊 Top rated workflows: {len(top_workflows)}")
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/src/community_features.py |
Expand my code with proper documentation strings | #!/usr/bin/env python3
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import List, Dict, Any
import sqlite3
import json
from datetime import datetime
from collections import Counter, defaultdict
class AnalyticsResponse(BaseModel):
overview: Dict[str, Any]
trends: Dict[str, Any]
patterns: Dict[str, Any]
recommendations: List[str]
generated_at: str
class WorkflowAnalytics:
def __init__(self, db_path: str = "workflows.db"):
self.db_path = db_path
def get_db_connection(self):
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
return conn
def get_workflow_analytics(self) -> Dict[str, Any]:
conn = self.get_db_connection()
# Basic statistics
cursor = conn.execute("SELECT COUNT(*) as total FROM workflows")
total_workflows = cursor.fetchone()["total"]
cursor = conn.execute(
"SELECT COUNT(*) as active FROM workflows WHERE active = 1"
)
active_workflows = cursor.fetchone()["active"]
# Trigger type distribution
cursor = conn.execute("""
SELECT trigger_type, COUNT(*) as count
FROM workflows
GROUP BY trigger_type
ORDER BY count DESC
""")
trigger_distribution = {
row["trigger_type"]: row["count"] for row in cursor.fetchall()
}
# Complexity distribution
cursor = conn.execute("""
SELECT complexity, COUNT(*) as count
FROM workflows
GROUP BY complexity
ORDER BY count DESC
""")
complexity_distribution = {
row["complexity"]: row["count"] for row in cursor.fetchall()
}
# Node count statistics
cursor = conn.execute("""
SELECT
AVG(node_count) as avg_nodes,
MIN(node_count) as min_nodes,
MAX(node_count) as max_nodes,
COUNT(*) as total
FROM workflows
""")
node_stats = dict(cursor.fetchone())
# Integration analysis
cursor = conn.execute(
"SELECT integrations FROM workflows WHERE integrations IS NOT NULL"
)
all_integrations = []
for row in cursor.fetchall():
integrations = json.loads(row["integrations"] or "[]")
all_integrations.extend(integrations)
integration_counts = Counter(all_integrations)
top_integrations = dict(integration_counts.most_common(10))
# Workflow patterns
patterns = self.analyze_workflow_patterns(conn)
# Recommendations
recommendations = self.generate_recommendations(
total_workflows,
active_workflows,
trigger_distribution,
complexity_distribution,
top_integrations,
)
conn.close()
return {
"overview": {
"total_workflows": total_workflows,
"active_workflows": active_workflows,
"activation_rate": round((active_workflows / total_workflows) * 100, 2)
if total_workflows > 0
else 0,
"unique_integrations": len(integration_counts),
"avg_nodes_per_workflow": round(node_stats["avg_nodes"], 2),
"most_complex_workflow": node_stats["max_nodes"],
},
"distributions": {
"trigger_types": trigger_distribution,
"complexity_levels": complexity_distribution,
"top_integrations": top_integrations,
},
"patterns": patterns,
"recommendations": recommendations,
"generated_at": datetime.now().isoformat(),
}
def analyze_workflow_patterns(self, conn) -> Dict[str, Any]:
# Integration co-occurrence analysis
cursor = conn.execute("""
SELECT name, integrations, trigger_type, complexity, node_count
FROM workflows
WHERE integrations IS NOT NULL
""")
integration_pairs = defaultdict(int)
service_categories = defaultdict(int)
for row in cursor.fetchall():
integrations = json.loads(row["integrations"] or "[]")
# Count service categories
for integration in integrations:
category = self.categorize_service(integration)
service_categories[category] += 1
# Find integration pairs
for i in range(len(integrations)):
for j in range(i + 1, len(integrations)):
pair = tuple(sorted([integrations[i], integrations[j]]))
integration_pairs[pair] += 1
# Most common integration pairs
top_pairs = dict(Counter(integration_pairs).most_common(5))
# Workflow complexity patterns
cursor = conn.execute("""
SELECT
trigger_type,
complexity,
AVG(node_count) as avg_nodes,
COUNT(*) as count
FROM workflows
GROUP BY trigger_type, complexity
ORDER BY count DESC
""")
complexity_patterns = []
for row in cursor.fetchall():
complexity_patterns.append(
{
"trigger_type": row["trigger_type"],
"complexity": row["complexity"],
"avg_nodes": round(row["avg_nodes"], 2),
"frequency": row["count"],
}
)
return {
"integration_pairs": top_pairs,
"service_categories": dict(service_categories),
"complexity_patterns": complexity_patterns[:10],
}
def categorize_service(self, service: str) -> str:
service_lower = service.lower()
if any(
word in service_lower
for word in ["slack", "telegram", "discord", "whatsapp"]
):
return "Communication"
elif any(word in service_lower for word in ["openai", "ai", "chat", "gpt"]):
return "AI/ML"
elif any(word in service_lower for word in ["google", "microsoft", "office"]):
return "Productivity"
elif any(
word in service_lower for word in ["shopify", "woocommerce", "stripe"]
):
return "E-commerce"
elif any(word in service_lower for word in ["airtable", "notion", "database"]):
return "Data Management"
elif any(
word in service_lower for word in ["twitter", "facebook", "instagram"]
):
return "Social Media"
else:
return "Other"
def generate_recommendations(
self,
total: int,
active: int,
triggers: Dict,
complexity: Dict,
integrations: Dict,
) -> List[str]:
recommendations = []
# Activation rate recommendations
activation_rate = (active / total) * 100 if total > 0 else 0
if activation_rate < 20:
recommendations.append(
f"Low activation rate ({activation_rate:.1f}%). Consider reviewing inactive workflows "
"and updating them for current use cases."
)
elif activation_rate > 80:
recommendations.append(
f"High activation rate ({activation_rate:.1f}%)! Your workflows are well-maintained. "
"Consider documenting successful patterns for team sharing."
)
# Trigger type recommendations
webhook_count = triggers.get("Webhook", 0)
scheduled_count = triggers.get("Scheduled", 0)
if webhook_count > scheduled_count * 2:
recommendations.append(
"You have many webhook-triggered workflows. Consider adding scheduled workflows "
"for data synchronization and maintenance tasks."
)
elif scheduled_count > webhook_count * 2:
recommendations.append(
"You have many scheduled workflows. Consider adding webhook-triggered workflows "
"for real-time integrations and event-driven automation."
)
# Integration recommendations
if "OpenAI" in integrations and integrations["OpenAI"] > 5:
recommendations.append(
"You're using OpenAI extensively. Consider creating AI workflow templates "
"for common use cases like content generation and data analysis."
)
if "Slack" in integrations and "Telegram" in integrations:
recommendations.append(
"You're using multiple communication platforms. Consider creating unified "
"notification workflows that can send to multiple channels."
)
# Complexity recommendations
high_complexity = complexity.get("high", 0)
if high_complexity > total * 0.3:
recommendations.append(
"You have many high-complexity workflows. Consider breaking them down into "
"smaller, reusable components for better maintainability."
)
return recommendations
def get_trend_analysis(self, days: int = 30) -> Dict[str, Any]:
# In a real implementation, this would analyze historical data
return {
"workflow_growth": {
"daily_average": 2.3,
"growth_rate": 15.2,
"trend": "increasing",
},
"popular_integrations": {
"trending_up": ["OpenAI", "Slack", "Google Sheets"],
"trending_down": ["Twitter", "Facebook"],
"stable": ["Telegram", "Airtable"],
},
"complexity_trends": {
"average_nodes": 12.5,
"complexity_increase": 8.3,
"automation_maturity": "intermediate",
},
}
def get_usage_insights(self) -> Dict[str, Any]:
conn = self.get_db_connection()
# Active vs inactive analysis
cursor = conn.execute("""
SELECT
trigger_type,
complexity,
COUNT(*) as total,
SUM(active) as active_count
FROM workflows
GROUP BY trigger_type, complexity
""")
usage_patterns = []
for row in cursor.fetchall():
activation_rate = (
(row["active_count"] / row["total"]) * 100 if row["total"] > 0 else 0
)
usage_patterns.append(
{
"trigger_type": row["trigger_type"],
"complexity": row["complexity"],
"total_workflows": row["total"],
"active_workflows": row["active_count"],
"activation_rate": round(activation_rate, 2),
}
)
# Most effective patterns
effective_patterns = sorted(
usage_patterns, key=lambda x: x["activation_rate"], reverse=True
)[:5]
conn.close()
return {
"usage_patterns": usage_patterns,
"most_effective_patterns": effective_patterns,
"insights": [
"Webhook-triggered workflows have higher activation rates",
"Medium complexity workflows are most commonly used",
"AI-powered workflows show increasing adoption",
"Communication integrations are most popular",
],
}
# Initialize analytics engine
analytics_engine = WorkflowAnalytics()
# FastAPI app for Analytics
analytics_app = FastAPI(title="N8N Analytics Engine", version="1.0.0")
@analytics_app.get("/analytics/overview", response_model=AnalyticsResponse)
async def get_analytics_overview():
try:
analytics_data = analytics_engine.get_workflow_analytics()
trends = analytics_engine.get_trend_analysis()
insights = analytics_engine.get_usage_insights()
return AnalyticsResponse(
overview=analytics_data["overview"],
trends=trends,
patterns=analytics_data["patterns"],
recommendations=analytics_data["recommendations"],
generated_at=analytics_data["generated_at"],
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Analytics error: {str(e)}")
@analytics_app.get("/analytics/trends")
async def get_trend_analysis(days: int = Query(30, ge=1, le=365)):
try:
return analytics_engine.get_trend_analysis(days)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Trend analysis error: {str(e)}")
@analytics_app.get("/analytics/insights")
async def get_usage_insights():
try:
return analytics_engine.get_usage_insights()
except Exception as e:
raise HTTPException(status_code=500, detail=f"Insights error: {str(e)}")
@analytics_app.get("/analytics/dashboard")
async def get_analytics_dashboard():
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N8N Analytics Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f8f9fa;
color: #333;
}
.dashboard {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
text-align: center;
}
.header h1 {
font-size: 32px;
margin-bottom: 10px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.stat-card {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
text-align: center;
}
.stat-number {
font-size: 36px;
font-weight: bold;
color: #667eea;
margin-bottom: 10px;
}
.stat-label {
color: #666;
font-size: 16px;
}
.chart-container {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin-bottom: 30px;
}
.chart-title {
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
color: #333;
}
.recommendations {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.recommendation {
background: #e3f2fd;
padding: 15px;
border-radius: 10px;
margin-bottom: 10px;
border-left: 4px solid #2196f3;
}
.loading {
text-align: center;
padding: 40px;
color: #666;
}
</style>
</head>
<body>
<div class="dashboard">
<div class="header">
<h1>📊 N8N Analytics Dashboard</h1>
<p>Comprehensive insights into your workflow ecosystem</p>
</div>
<div class="stats-grid" id="statsGrid">
<div class="loading">Loading analytics...</div>
</div>
<div class="chart-container">
<div class="chart-title">Workflow Distribution</div>
<canvas id="triggerChart" width="400" height="200"></canvas>
</div>
<div class="chart-container">
<div class="chart-title">Integration Usage</div>
<canvas id="integrationChart" width="400" height="200"></canvas>
</div>
<div class="recommendations" id="recommendations">
<div class="chart-title">Recommendations</div>
<div class="loading">Loading recommendations...</div>
</div>
</div>
<script>
async function loadAnalytics() {
try {
const response = await fetch('/analytics/overview');
const data = await response.json();
// Update stats
updateStats(data.overview);
// Create charts
createTriggerChart(data.patterns.distributions?.trigger_types || {});
createIntegrationChart(data.patterns.distributions?.top_integrations || {});
// Update recommendations
updateRecommendations(data.recommendations);
} catch (error) {
console.error('Error loading analytics:', error);
document.getElementById('statsGrid').innerHTML =
'<div class="loading">Error loading analytics. Please try again.</div>';
}
}
function updateStats(overview) {
const statsGrid = document.getElementById('statsGrid');
statsGrid.innerHTML = `
<div class="stat-card">
<div class="stat-number">${overview.total_workflows?.toLocaleString() || 0}</div>
<div class="stat-label">Total Workflows</div>
</div>
<div class="stat-card">
<div class="stat-number">${overview.active_workflows?.toLocaleString() || 0}</div>
<div class="stat-label">Active Workflows</div>
</div>
<div class="stat-card">
<div class="stat-number">${overview.activation_rate || 0}%</div>
<div class="stat-label">Activation Rate</div>
</div>
<div class="stat-card">
<div class="stat-number">${overview.unique_integrations || 0}</div>
<div class="stat-label">Unique Integrations</div>
</div>
`;
}
function createTriggerChart(triggerData) {
const ctx = document.getElementById('triggerChart').getContext('2d');
new Chart(ctx, {
type: 'doughnut',
data: {
labels: Object.keys(triggerData),
datasets: [{
data: Object.values(triggerData),
backgroundColor: [
'#667eea',
'#764ba2',
'#f093fb',
'#f5576c',
'#4facfe'
]
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom'
}
}
}
});
}
function createIntegrationChart(integrationData) {
const ctx = document.getElementById('integrationChart').getContext('2d');
const labels = Object.keys(integrationData).slice(0, 10);
const data = Object.values(integrationData).slice(0, 10);
new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Usage Count',
data: data,
backgroundColor: '#667eea'
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
function updateRecommendations(recommendations) {
const container = document.getElementById('recommendations');
if (recommendations && recommendations.length > 0) {
container.innerHTML = `
<div class="chart-title">Recommendations</div>
${recommendations.map(rec => `
<div class="recommendation">${rec}</div>
`).join('')}
`;
} else {
container.innerHTML = '<div class="chart-title">Recommendations</div><div class="loading">No recommendations available</div>';
}
}
// Load analytics on page load
loadAnalytics();
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
uvicorn.run(analytics_app, host="127.0.0.1", port=8002) | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Advanced Analytics Engine for N8N Workflows
+Provides insights, patterns, and usage analytics.
+"""
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import HTMLResponse
@@ -28,6 +32,7 @@ return conn
def get_workflow_analytics(self) -> Dict[str, Any]:
+ """Get comprehensive workflow analytics."""
conn = self.get_db_connection()
# Basic statistics
@@ -120,6 +125,7 @@ }
def analyze_workflow_patterns(self, conn) -> Dict[str, Any]:
+ """Analyze common workflow patterns and relationships."""
# Integration co-occurrence analysis
cursor = conn.execute("""
SELECT name, integrations, trigger_type, complexity, node_count
@@ -177,6 +183,7 @@ }
def categorize_service(self, service: str) -> str:
+ """Categorize a service into a broader category."""
service_lower = service.lower()
if any(
@@ -209,6 +216,7 @@ complexity: Dict,
integrations: Dict,
) -> List[str]:
+ """Generate actionable recommendations based on analytics."""
recommendations = []
# Activation rate recommendations
@@ -263,6 +271,7 @@ return recommendations
def get_trend_analysis(self, days: int = 30) -> Dict[str, Any]:
+ """Analyze trends over time (simulated for demo)."""
# In a real implementation, this would analyze historical data
return {
"workflow_growth": {
@@ -283,6 +292,7 @@ }
def get_usage_insights(self) -> Dict[str, Any]:
+ """Get usage insights and patterns."""
conn = self.get_db_connection()
# Active vs inactive analysis
@@ -339,6 +349,7 @@
@analytics_app.get("/analytics/overview", response_model=AnalyticsResponse)
async def get_analytics_overview():
+ """Get comprehensive analytics overview."""
try:
analytics_data = analytics_engine.get_workflow_analytics()
trends = analytics_engine.get_trend_analysis()
@@ -357,6 +368,7 @@
@analytics_app.get("/analytics/trends")
async def get_trend_analysis(days: int = Query(30, ge=1, le=365)):
+ """Get trend analysis for specified period."""
try:
return analytics_engine.get_trend_analysis(days)
except Exception as e:
@@ -365,6 +377,7 @@
@analytics_app.get("/analytics/insights")
async def get_usage_insights():
+ """Get usage insights and patterns."""
try:
return analytics_engine.get_usage_insights()
except Exception as e:
@@ -373,6 +386,7 @@
@analytics_app.get("/analytics/dashboard")
async def get_analytics_dashboard():
+ """Get analytics dashboard HTML."""
html_content = """
<!DOCTYPE html>
<html lang="en">
@@ -613,4 +627,4 @@ if __name__ == "__main__":
import uvicorn
- uvicorn.run(analytics_app, host="127.0.0.1", port=8002)+ uvicorn.run(analytics_app, host="127.0.0.1", port=8002)
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/src/analytics_engine.py |
Add docstrings that explain inputs and outputs | #!/usr/bin/env python3
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
from typing import List, Dict, Any
import httpx
from datetime import datetime
class IntegrationConfig(BaseModel):
name: str
api_key: str
base_url: str
enabled: bool = True
class WebhookPayload(BaseModel):
event: str
data: Dict[str, Any]
timestamp: str = Field(default_factory=lambda: datetime.now().isoformat())
class IntegrationHub:
def __init__(self):
self.integrations = {}
self.webhook_endpoints = {}
def register_integration(self, config: IntegrationConfig):
self.integrations[config.name] = config
async def sync_with_github(self, repo: str, token: str) -> Dict[str, Any]:
try:
async with httpx.AsyncClient() as client:
headers = {"Authorization": f"token {token}"}
# Get repository contents
response = await client.get(
f"https://api.github.com/repos/{repo}/contents/workflows",
headers=headers,
)
if response.status_code == 200:
files = response.json()
workflow_files = [f for f in files if f["name"].endswith(".json")]
return {
"status": "success",
"repository": repo,
"workflow_files": len(workflow_files),
"files": [f["name"] for f in workflow_files],
}
else:
return {"status": "error", "message": "Failed to access repository"}
except Exception as e:
return {"status": "error", "message": str(e)}
async def sync_with_slack(self, webhook_url: str, message: str) -> Dict[str, Any]:
try:
async with httpx.AsyncClient() as client:
payload = {
"text": message,
"username": "N8N Workflows Bot",
"icon_emoji": ":robot_face:",
}
response = await client.post(webhook_url, json=payload)
if response.status_code == 200:
return {
"status": "success",
"message": "Notification sent to Slack",
}
else:
return {"status": "error", "message": "Failed to send to Slack"}
except Exception as e:
return {"status": "error", "message": str(e)}
async def sync_with_discord(self, webhook_url: str, message: str) -> Dict[str, Any]:
try:
async with httpx.AsyncClient() as client:
payload = {"content": message, "username": "N8N Workflows Bot"}
response = await client.post(webhook_url, json=payload)
if response.status_code == 204:
return {
"status": "success",
"message": "Notification sent to Discord",
}
else:
return {"status": "error", "message": "Failed to send to Discord"}
except Exception as e:
return {"status": "error", "message": str(e)}
async def export_to_airtable(
self, base_id: str, table_name: str, api_key: str, workflows: List[Dict]
) -> Dict[str, Any]:
try:
async with httpx.AsyncClient() as client:
headers = {"Authorization": f"Bearer {api_key}"}
records = []
for workflow in workflows:
record = {
"fields": {
"Name": workflow.get("name", ""),
"Description": workflow.get("description", ""),
"Trigger Type": workflow.get("trigger_type", ""),
"Complexity": workflow.get("complexity", ""),
"Node Count": workflow.get("node_count", 0),
"Active": workflow.get("active", False),
"Integrations": ", ".join(workflow.get("integrations", [])),
"Last Updated": datetime.now().isoformat(),
}
}
records.append(record)
# Create records in batches
batch_size = 10
created_records = 0
for i in range(0, len(records), batch_size):
batch = records[i : i + batch_size]
response = await client.post(
f"https://api.airtable.com/v0/{base_id}/{table_name}",
headers=headers,
json={"records": batch},
)
if response.status_code == 200:
created_records += len(batch)
else:
return {
"status": "error",
"message": f"Failed to create records: {response.text}",
}
return {
"status": "success",
"message": f"Exported {created_records} workflows to Airtable",
}
except Exception as e:
return {"status": "error", "message": str(e)}
async def sync_with_notion(
self, database_id: str, token: str, workflows: List[Dict]
) -> Dict[str, Any]:
try:
async with httpx.AsyncClient() as client:
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"Notion-Version": "2022-06-28",
}
created_pages = 0
for workflow in workflows:
page_data = {
"parent": {"database_id": database_id},
"properties": {
"Name": {
"title": [
{"text": {"content": workflow.get("name", "")}}
]
},
"Description": {
"rich_text": [
{
"text": {
"content": workflow.get("description", "")
}
}
]
},
"Trigger Type": {
"select": {"name": workflow.get("trigger_type", "")}
},
"Complexity": {
"select": {"name": workflow.get("complexity", "")}
},
"Node Count": {"number": workflow.get("node_count", 0)},
"Active": {"checkbox": workflow.get("active", False)},
"Integrations": {
"multi_select": [
{"name": integration}
for integration in workflow.get("integrations", [])
]
},
},
}
response = await client.post(
"https://api.notion.com/v1/pages",
headers=headers,
json=page_data,
)
if response.status_code == 200:
created_pages += 1
else:
return {
"status": "error",
"message": f"Failed to create page: {response.text}",
}
return {
"status": "success",
"message": f"Synced {created_pages} workflows to Notion",
}
except Exception as e:
return {"status": "error", "message": str(e)}
def register_webhook(self, endpoint: str, handler):
self.webhook_endpoints[endpoint] = handler
async def handle_webhook(self, endpoint: str, payload: WebhookPayload):
if endpoint in self.webhook_endpoints:
return await self.webhook_endpoints[endpoint](payload)
else:
return {"status": "error", "message": "Webhook endpoint not found"}
# Initialize integration hub
integration_hub = IntegrationHub()
# FastAPI app for Integration Hub
integration_app = FastAPI(title="N8N Integration Hub", version="1.0.0")
@integration_app.post("/integrations/github/sync")
async def sync_github(repo: str, token: str):
try:
result = await integration_hub.sync_with_github(repo, token)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.post("/integrations/slack/notify")
async def notify_slack(webhook_url: str, message: str):
try:
result = await integration_hub.sync_with_slack(webhook_url, message)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.post("/integrations/discord/notify")
async def notify_discord(webhook_url: str, message: str):
try:
result = await integration_hub.sync_with_discord(webhook_url, message)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.post("/integrations/airtable/export")
async def export_airtable(
base_id: str, table_name: str, api_key: str, workflows: List[Dict]
):
try:
result = await integration_hub.export_to_airtable(
base_id, table_name, api_key, workflows
)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.post("/integrations/notion/sync")
async def sync_notion(database_id: str, token: str, workflows: List[Dict]):
try:
result = await integration_hub.sync_with_notion(database_id, token, workflows)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.post("/webhooks/{endpoint}")
async def handle_webhook_endpoint(endpoint: str, payload: WebhookPayload):
try:
result = await integration_hub.handle_webhook(endpoint, payload)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.get("/integrations/status")
async def get_integration_status():
return {
"integrations": list(integration_hub.integrations.keys()),
"webhook_endpoints": list(integration_hub.webhook_endpoints.keys()),
"status": "operational",
}
@integration_app.get("/integrations/dashboard")
async def get_integration_dashboard():
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N8N Integration Hub</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
color: #333;
}
.dashboard {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.header {
background: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
text-align: center;
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}
.header h1 {
font-size: 32px;
margin-bottom: 10px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.integrations-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.integration-card {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
transition: transform 0.3s ease;
}
.integration-card:hover {
transform: translateY(-5px);
}
.integration-icon {
font-size: 48px;
margin-bottom: 15px;
}
.integration-title {
font-size: 20px;
font-weight: bold;
margin-bottom: 10px;
color: #333;
}
.integration-description {
color: #666;
margin-bottom: 20px;
line-height: 1.5;
}
.integration-actions {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.action-btn {
padding: 10px 20px;
border: none;
border-radius: 25px;
cursor: pointer;
font-size: 14px;
transition: all 0.3s ease;
text-decoration: none;
display: inline-block;
text-align: center;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5a6fd8;
}
.btn-secondary {
background: #f8f9fa;
color: #666;
border: 1px solid #e9ecef;
}
.btn-secondary:hover {
background: #e9ecef;
}
.status-indicator {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 8px;
}
.status-online {
background: #28a745;
}
.status-offline {
background: #dc3545;
}
.webhook-section {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
margin-bottom: 30px;
}
.webhook-endpoint {
background: #f8f9fa;
padding: 15px;
border-radius: 10px;
margin: 10px 0;
font-family: monospace;
border-left: 4px solid #667eea;
}
</style>
</head>
<body>
<div class="dashboard">
<div class="header">
<h1>🔗 N8N Integration Hub</h1>
<p>Connect your workflows with external platforms and services</p>
</div>
<div class="integrations-grid">
<div class="integration-card">
<div class="integration-icon">🐙</div>
<div class="integration-title">GitHub</div>
<div class="integration-description">
Sync your workflows with GitHub repositories.
Version control and collaborate on workflow development.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="syncGitHub()">Sync Repository</button>
<button class="action-btn btn-secondary" onclick="showGitHubConfig()">Configure</button>
</div>
</div>
<div class="integration-card">
<div class="integration-icon">💬</div>
<div class="integration-title">Slack</div>
<div class="integration-description">
Send notifications and workflow updates to Slack channels.
Keep your team informed about automation activities.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="testSlack()">Test Notification</button>
<button class="action-btn btn-secondary" onclick="showSlackConfig()">Configure</button>
</div>
</div>
<div class="integration-card">
<div class="integration-icon">🎮</div>
<div class="integration-title">Discord</div>
<div class="integration-description">
Integrate with Discord servers for workflow notifications.
Perfect for gaming communities and developer teams.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="testDiscord()">Test Notification</button>
<button class="action-btn btn-secondary" onclick="showDiscordConfig()">Configure</button>
</div>
</div>
<div class="integration-card">
<div class="integration-icon">📊</div>
<div class="integration-title">Airtable</div>
<div class="integration-description">
Export workflow data to Airtable for project management.
Create databases of your automation workflows.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="exportAirtable()">Export Data</button>
<button class="action-btn btn-secondary" onclick="showAirtableConfig()">Configure</button>
</div>
</div>
<div class="integration-card">
<div class="integration-icon">📝</div>
<div class="integration-title">Notion</div>
<div class="integration-description">
Sync workflows with Notion databases for documentation.
Create comprehensive workflow documentation.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="syncNotion()">Sync Database</button>
<button class="action-btn btn-secondary" onclick="showNotionConfig()">Configure</button>
</div>
</div>
<div class="integration-card">
<div class="integration-icon">🔗</div>
<div class="integration-title">Webhooks</div>
<div class="integration-description">
Create custom webhook endpoints for external integrations.
Receive data from any service that supports webhooks.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="createWebhook()">Create Webhook</button>
<button class="action-btn btn-secondary" onclick="showWebhookDocs()">Documentation</button>
</div>
</div>
</div>
<div class="webhook-section">
<h2>🔗 Webhook Endpoints</h2>
<p>Available webhook endpoints for external integrations:</p>
<div class="webhook-endpoint">
POST /webhooks/workflow-update<br>
<small>Receive notifications when workflows are updated</small>
</div>
<div class="webhook-endpoint">
POST /webhooks/workflow-execution<br>
<small>Receive notifications when workflows are executed</small>
</div>
<div class="webhook-endpoint">
POST /webhooks/error-report<br>
<small>Receive error reports from workflow executions</small>
</div>
</div>
</div>
<script>
async function syncGitHub() {
const repo = prompt('Enter GitHub repository (owner/repo):');
const token = prompt('Enter GitHub token:');
if (repo && token) {
try {
const response = await fetch('/integrations/github/sync', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({repo, token})
});
const result = await response.json();
alert(result.message || 'GitHub sync completed');
} catch (error) {
alert('Error syncing with GitHub: ' + error.message);
}
}
}
async function testSlack() {
const webhook = prompt('Enter Slack webhook URL:');
const message = 'Test notification from N8N Integration Hub';
if (webhook) {
try {
const response = await fetch('/integrations/slack/notify', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({webhook_url: webhook, message})
});
const result = await response.json();
alert(result.message || 'Slack notification sent');
} catch (error) {
alert('Error sending to Slack: ' + error.message);
}
}
}
async function testDiscord() {
const webhook = prompt('Enter Discord webhook URL:');
const message = 'Test notification from N8N Integration Hub';
if (webhook) {
try {
const response = await fetch('/integrations/discord/notify', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({webhook_url: webhook, message})
});
const result = await response.json();
alert(result.message || 'Discord notification sent');
} catch (error) {
alert('Error sending to Discord: ' + error.message);
}
}
}
function showGitHubConfig() {
alert('GitHub Configuration:\\n\\n1. Create a GitHub token with repo access\\n2. Use format: owner/repository\\n3. Ensure workflows are in /workflows directory');
}
function showSlackConfig() {
alert('Slack Configuration:\\n\\n1. Go to Slack App Directory\\n2. Add "Incoming Webhooks" app\\n3. Create webhook URL\\n4. Use the URL for notifications');
}
function showDiscordConfig() {
alert('Discord Configuration:\\n\\n1. Go to Server Settings\\n2. Navigate to Integrations\\n3. Create Webhook\\n4. Copy webhook URL');
}
function showAirtableConfig() {
alert('Airtable Configuration:\\n\\n1. Create a new Airtable base\\n2. Get API key from account settings\\n3. Get base ID from API documentation\\n4. Configure table structure');
}
function showNotionConfig() {
alert('Notion Configuration:\\n\\n1. Create a Notion integration\\n2. Get integration token\\n3. Create database with proper schema\\n4. Share database with integration');
}
function createWebhook() {
alert('Webhook Creation:\\n\\n1. Choose endpoint name\\n2. Configure payload structure\\n3. Set up authentication\\n4. Test webhook endpoint');
}
function showWebhookDocs() {
alert('Webhook Documentation:\\n\\nAvailable at: /docs\\n\\nEndpoints:\\n- POST /webhooks/{endpoint}\\n- Payload: {event, data, timestamp}\\n- Response: {status, message}');
}
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
uvicorn.run(integration_app, host="127.0.0.1", port=8003) | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Integration Hub for N8N Workflows
+Connect with external platforms and services.
+"""
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
@@ -27,9 +31,11 @@ self.webhook_endpoints = {}
def register_integration(self, config: IntegrationConfig):
+ """Register a new integration."""
self.integrations[config.name] = config
async def sync_with_github(self, repo: str, token: str) -> Dict[str, Any]:
+ """Sync workflows with GitHub repository."""
try:
async with httpx.AsyncClient() as client:
headers = {"Authorization": f"token {token}"}
@@ -57,6 +63,7 @@ return {"status": "error", "message": str(e)}
async def sync_with_slack(self, webhook_url: str, message: str) -> Dict[str, Any]:
+ """Send notification to Slack."""
try:
async with httpx.AsyncClient() as client:
payload = {
@@ -79,6 +86,7 @@ return {"status": "error", "message": str(e)}
async def sync_with_discord(self, webhook_url: str, message: str) -> Dict[str, Any]:
+ """Send notification to Discord."""
try:
async with httpx.AsyncClient() as client:
payload = {"content": message, "username": "N8N Workflows Bot"}
@@ -99,6 +107,7 @@ async def export_to_airtable(
self, base_id: str, table_name: str, api_key: str, workflows: List[Dict]
) -> Dict[str, Any]:
+ """Export workflows to Airtable."""
try:
async with httpx.AsyncClient() as client:
headers = {"Authorization": f"Bearer {api_key}"}
@@ -151,6 +160,7 @@ async def sync_with_notion(
self, database_id: str, token: str, workflows: List[Dict]
) -> Dict[str, Any]:
+ """Sync workflows with Notion database."""
try:
async with httpx.AsyncClient() as client:
headers = {
@@ -219,9 +229,11 @@ return {"status": "error", "message": str(e)}
def register_webhook(self, endpoint: str, handler):
+ """Register a webhook endpoint."""
self.webhook_endpoints[endpoint] = handler
async def handle_webhook(self, endpoint: str, payload: WebhookPayload):
+ """Handle incoming webhook."""
if endpoint in self.webhook_endpoints:
return await self.webhook_endpoints[endpoint](payload)
else:
@@ -237,6 +249,7 @@
@integration_app.post("/integrations/github/sync")
async def sync_github(repo: str, token: str):
+ """Sync workflows with GitHub repository."""
try:
result = await integration_hub.sync_with_github(repo, token)
return result
@@ -246,6 +259,7 @@
@integration_app.post("/integrations/slack/notify")
async def notify_slack(webhook_url: str, message: str):
+ """Send notification to Slack."""
try:
result = await integration_hub.sync_with_slack(webhook_url, message)
return result
@@ -255,6 +269,7 @@
@integration_app.post("/integrations/discord/notify")
async def notify_discord(webhook_url: str, message: str):
+ """Send notification to Discord."""
try:
result = await integration_hub.sync_with_discord(webhook_url, message)
return result
@@ -266,6 +281,7 @@ async def export_airtable(
base_id: str, table_name: str, api_key: str, workflows: List[Dict]
):
+ """Export workflows to Airtable."""
try:
result = await integration_hub.export_to_airtable(
base_id, table_name, api_key, workflows
@@ -277,6 +293,7 @@
@integration_app.post("/integrations/notion/sync")
async def sync_notion(database_id: str, token: str, workflows: List[Dict]):
+ """Sync workflows with Notion database."""
try:
result = await integration_hub.sync_with_notion(database_id, token, workflows)
return result
@@ -286,6 +303,7 @@
@integration_app.post("/webhooks/{endpoint}")
async def handle_webhook_endpoint(endpoint: str, payload: WebhookPayload):
+ """Handle incoming webhook."""
try:
result = await integration_hub.handle_webhook(endpoint, payload)
return result
@@ -295,6 +313,7 @@
@integration_app.get("/integrations/status")
async def get_integration_status():
+ """Get status of all integrations."""
return {
"integrations": list(integration_hub.integrations.keys()),
"webhook_endpoints": list(integration_hub.webhook_endpoints.keys()),
@@ -304,6 +323,7 @@
@integration_app.get("/integrations/dashboard")
async def get_integration_dashboard():
+ """Get integration dashboard HTML."""
html_content = """
<!DOCTYPE html>
<html lang="en">
@@ -631,4 +651,4 @@ if __name__ == "__main__":
import uvicorn
- uvicorn.run(integration_app, host="127.0.0.1", port=8003)+ uvicorn.run(integration_app, host="127.0.0.1", port=8003)
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/src/integration_hub.py |
Add professional docstrings to my codebase | #!/usr/bin/env python3
import os
import re
import sys
from pathlib import Path
from datetime import datetime
# Add the parent directory to path for imports
sys.path.append(str(Path(__file__).parent.parent))
from workflow_db import WorkflowDatabase
def get_current_stats():
db_path = "database/workflows.db"
if not os.path.exists(db_path):
print("Database not found. Run workflow indexing first.")
return None
db = WorkflowDatabase(db_path)
stats = db.get_stats()
# Get categories count
categories = db.get_service_categories()
return {
"total_workflows": stats["total"],
"active_workflows": stats["active"],
"inactive_workflows": stats["inactive"],
"total_nodes": stats["total_nodes"],
"unique_integrations": stats["unique_integrations"],
"categories_count": len(get_category_list(categories)),
"triggers": stats["triggers"],
"complexity": stats["complexity"],
"last_updated": datetime.now().strftime("%Y-%m-%d"),
}
def get_category_list(categories):
formatted_categories = set()
# Map technical categories to display names
category_mapping = {
"messaging": "Communication & Messaging",
"email": "Communication & Messaging",
"cloud_storage": "Cloud Storage & File Management",
"database": "Data Processing & Analysis",
"project_management": "Project Management",
"ai_ml": "AI Agent Development",
"social_media": "Social Media Management",
"ecommerce": "E-commerce & Retail",
"analytics": "Data Processing & Analysis",
"calendar_tasks": "Project Management",
"forms": "Data Processing & Analysis",
"development": "Technical Infrastructure & DevOps",
}
for category_key in categories.keys():
display_name = category_mapping.get(
category_key, category_key.replace("_", " ").title()
)
formatted_categories.add(display_name)
# Add categories from the create_categories.py system
additional_categories = [
"Business Process Automation",
"Web Scraping & Data Extraction",
"Marketing & Advertising Automation",
"Creative Content & Video Automation",
"Creative Design Automation",
"CRM & Sales",
"Financial & Accounting",
]
for cat in additional_categories:
formatted_categories.add(cat)
return sorted(list(formatted_categories))
def update_readme_stats(stats):
readme_path = "README.md"
if not os.path.exists(readme_path):
print("README.md not found")
return False
with open(readme_path, "r", encoding="utf-8") as f:
content = f.read()
# Define replacement patterns and their new values
replacements = [
# Main collection description
(
r"A professionally organized collection of \*\*[\d,]+\s+n8n workflows\*\*",
f"A professionally organized collection of **{stats['total_workflows']:,} n8n workflows**",
),
# Total workflows in various contexts
(
r"- \*\*[\d,]+\s+workflows\*\* with meaningful",
f"- **{stats['total_workflows']:,} workflows** with meaningful",
),
# Statistics section
(
r"- \*\*Total Workflows\*\*: [\d,]+",
f"- **Total Workflows**: {stats['total_workflows']:,}",
),
(
r"- \*\*Active Workflows\*\*: [\d,]+ \([\d.]+%",
f"- **Active Workflows**: {stats['active_workflows']:,} ({(stats['active_workflows'] / stats['total_workflows'] * 100):.1f}%",
),
(
r"- \*\*Total Nodes\*\*: [\d,]+ \(avg [\d.]+ nodes",
f"- **Total Nodes**: {stats['total_nodes']:,} (avg {(stats['total_nodes'] / stats['total_workflows']):.1f} nodes",
),
(
r"- \*\*Unique Integrations\*\*: [\d,]+ different",
f"- **Unique Integrations**: {stats['unique_integrations']:,} different",
),
# Update complexity/trigger distribution
(
r"- \*\*Complex\*\*: [\d,]+ workflows \([\d.]+%\)",
f"- **Complex**: {stats['triggers'].get('Complex', 0):,} workflows ({(stats['triggers'].get('Complex', 0) / stats['total_workflows'] * 100):.1f}%)",
),
(
r"- \*\*Webhook\*\*: [\d,]+ workflows \([\d.]+%\)",
f"- **Webhook**: {stats['triggers'].get('Webhook', 0):,} workflows ({(stats['triggers'].get('Webhook', 0) / stats['total_workflows'] * 100):.1f}%)",
),
(
r"- \*\*Manual\*\*: [\d,]+ workflows \([\d.]+%\)",
f"- **Manual**: {stats['triggers'].get('Manual', 0):,} workflows ({(stats['triggers'].get('Manual', 0) / stats['total_workflows'] * 100):.1f}%)",
),
(
r"- \*\*Scheduled\*\*: [\d,]+ workflows \([\d.]+%\)",
f"- **Scheduled**: {stats['triggers'].get('Scheduled', 0):,} workflows ({(stats['triggers'].get('Scheduled', 0) / stats['total_workflows'] * 100):.1f}%)",
),
# Update total in current collection stats
(
r"\*\*Total Workflows\*\*: [\d,]+ automation",
f"**Total Workflows**: {stats['total_workflows']:,} automation",
),
(
r"\*\*Active Workflows\*\*: [\d,]+ \([\d.]+% active",
f"**Active Workflows**: {stats['active_workflows']:,} ({(stats['active_workflows'] / stats['total_workflows'] * 100):.1f}% active",
),
(
r"\*\*Total Nodes\*\*: [\d,]+ \(avg [\d.]+ nodes",
f"**Total Nodes**: {stats['total_nodes']:,} (avg {(stats['total_nodes'] / stats['total_workflows']):.1f} nodes",
),
(
r"\*\*Unique Integrations\*\*: [\d,]+ different",
f"**Unique Integrations**: {stats['unique_integrations']:,} different",
),
# Categories count
(
r"Our system automatically categorizes workflows into [\d]+ service categories",
f"Our system automatically categorizes workflows into {stats['categories_count']} service categories",
),
# Update any "2000+" references
(r"2000\+", f"{stats['total_workflows']:,}+"),
(r"2,000\+", f"{stats['total_workflows']:,}+"),
# Search across X workflows
(
r"Search across [\d,]+ workflows",
f"Search across {stats['total_workflows']:,} workflows",
),
# Instant search across X workflows
(
r"Instant search across [\d,]+ workflows",
f"Instant search across {stats['total_workflows']:,} workflows",
),
]
# Apply all replacements
updated_content = content
replacements_made = 0
for pattern, replacement in replacements:
old_content = updated_content
updated_content = re.sub(pattern, replacement, updated_content)
if updated_content != old_content:
replacements_made += 1
# Write back to file
with open(readme_path, "w", encoding="utf-8") as f:
f.write(updated_content)
print("README.md updated with current statistics:")
print(f" - Total workflows: {stats['total_workflows']:,}")
print(f" - Active workflows: {stats['active_workflows']:,}")
print(f" - Total nodes: {stats['total_nodes']:,}")
print(f" - Unique integrations: {stats['unique_integrations']:,}")
print(f" - Categories: {stats['categories_count']}")
print(f" - Replacements made: {replacements_made}")
return True
def main():
try:
print("Getting current workflow statistics...")
stats = get_current_stats()
if not stats:
print("Failed to get statistics")
sys.exit(1)
print("Updating README.md...")
success = update_readme_stats(stats)
if success:
print("README.md successfully updated with latest statistics!")
else:
print("Failed to update README.md")
sys.exit(1)
except Exception as e:
print(f"Error updating README stats: {e}")
sys.exit(1)
if __name__ == "__main__":
main() | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Update README.md with current workflow statistics
+Replaces hardcoded numbers with live data from the database.
+"""
import os
import re
@@ -13,6 +17,7 @@
def get_current_stats():
+ """Get current workflow statistics from the database."""
db_path = "database/workflows.db"
if not os.path.exists(db_path):
@@ -39,6 +44,7 @@
def get_category_list(categories):
+ """Get formatted list of all categories (same logic as search index)."""
formatted_categories = set()
# Map technical categories to display names
@@ -81,6 +87,7 @@
def update_readme_stats(stats):
+ """Update README.md with current statistics."""
readme_path = "README.md"
if not os.path.exists(readme_path):
@@ -199,6 +206,7 @@
def main():
+ """Main function to update README statistics."""
try:
print("Getting current workflow statistics...")
stats = get_current_stats()
@@ -222,4 +230,4 @@
if __name__ == "__main__":
- main()+ main()
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/scripts/update_readme_stats.py |
Please document this code using docstrings | #!/usr/bin/env python3
import json
import os
import sys
from pathlib import Path
from typing import Dict, List, Any
# Add the parent directory to path for imports
sys.path.append(str(Path(__file__).parent.parent))
from workflow_db import WorkflowDatabase
def generate_static_search_index(db_path: str, output_dir: str) -> Dict[str, Any]:
# Initialize database
db = WorkflowDatabase(db_path)
# Get all workflows
workflows, total = db.search_workflows(limit=10000) # Get all workflows
# Get statistics
stats = db.get_stats()
# Get categories from service mapping
categories = db.get_service_categories()
# Load existing categories from create_categories.py system
existing_categories = load_existing_categories()
# Create simplified workflow data for search
search_workflows = []
for workflow in workflows:
# Create searchable text combining multiple fields
searchable_text = " ".join(
[
workflow["name"],
workflow["description"],
workflow["filename"],
" ".join(workflow["integrations"]),
" ".join(workflow["tags"]) if workflow["tags"] else "",
]
).lower()
# Use existing category from create_categories.py system, fallback to integration-based
category = get_workflow_category(
workflow["filename"],
existing_categories,
workflow["integrations"],
categories,
)
search_workflow = {
"id": workflow["filename"].replace(".json", ""),
"name": workflow["name"],
"description": workflow["description"],
"filename": workflow["filename"],
"active": workflow["active"],
"trigger_type": workflow["trigger_type"],
"complexity": workflow["complexity"],
"node_count": workflow["node_count"],
"integrations": workflow["integrations"],
"tags": workflow["tags"],
"category": category,
"searchable_text": searchable_text,
"download_url": f"https://raw.githubusercontent.com/Zie619/n8n-workflows/main/workflows/{extract_folder_from_filename(workflow['filename'])}/{workflow['filename']}",
}
search_workflows.append(search_workflow)
# Create comprehensive search index
search_index = {
"version": "1.0",
"generated_at": stats.get("last_indexed", ""),
"stats": {
"total_workflows": stats["total"],
"active_workflows": stats["active"],
"inactive_workflows": stats["inactive"],
"total_nodes": stats["total_nodes"],
"unique_integrations": stats["unique_integrations"],
"categories": len(get_category_list(categories)),
"triggers": stats["triggers"],
"complexity": stats["complexity"],
},
"categories": get_category_list(categories),
"integrations": get_popular_integrations(workflows),
"workflows": search_workflows,
}
return search_index
def load_existing_categories() -> Dict[str, str]:
try:
with open("context/search_categories.json", "r", encoding="utf-8") as f:
categories_data = json.load(f)
# Convert to filename -> category mapping
category_mapping = {}
for item in categories_data:
if item.get("category"):
category_mapping[item["filename"]] = item["category"]
return category_mapping
except FileNotFoundError:
print(
"Warning: search_categories.json not found, using integration-based categorization"
)
return {}
def get_workflow_category(
filename: str,
existing_categories: Dict[str, str],
integrations: List[str],
service_categories: Dict[str, List[str]],
) -> str:
# First priority: Use existing category from create_categories.py system
if filename in existing_categories:
return existing_categories[filename]
# Fallback: Use integration-based categorization
return determine_category(integrations, service_categories)
def determine_category(
integrations: List[str], categories: Dict[str, List[str]]
) -> str:
if not integrations:
return "Uncategorized"
# Check each category for matching integrations
for category, services in categories.items():
for integration in integrations:
if integration in services:
return format_category_name(category)
return "Uncategorized"
def format_category_name(category_key: str) -> str:
category_mapping = {
"messaging": "Communication & Messaging",
"email": "Communication & Messaging",
"cloud_storage": "Cloud Storage & File Management",
"database": "Data Processing & Analysis",
"project_management": "Project Management",
"ai_ml": "AI Agent Development",
"social_media": "Social Media Management",
"ecommerce": "E-commerce & Retail",
"analytics": "Data Processing & Analysis",
"calendar_tasks": "Project Management",
"forms": "Data Processing & Analysis",
"development": "Technical Infrastructure & DevOps",
}
return category_mapping.get(category_key, category_key.replace("_", " ").title())
def get_category_list(categories: Dict[str, List[str]]) -> List[str]:
formatted_categories = set()
for category_key in categories.keys():
formatted_categories.add(format_category_name(category_key))
# Add categories from the create_categories.py system
additional_categories = [
"Business Process Automation",
"Web Scraping & Data Extraction",
"Marketing & Advertising Automation",
"Creative Content & Video Automation",
"Creative Design Automation",
"CRM & Sales",
"Financial & Accounting",
]
for cat in additional_categories:
formatted_categories.add(cat)
return sorted(list(formatted_categories))
def get_popular_integrations(workflows: List[Dict]) -> List[Dict[str, Any]]:
integration_counts = {}
for workflow in workflows:
for integration in workflow["integrations"]:
integration_counts[integration] = integration_counts.get(integration, 0) + 1
# Sort by count and take top 50
sorted_integrations = sorted(
integration_counts.items(), key=lambda x: x[1], reverse=True
)[:50]
return [{"name": name, "count": count} for name, count in sorted_integrations]
def extract_folder_from_filename(filename: str) -> str:
# Most workflows follow pattern: ID_Service_Purpose_Trigger.json
# Extract the service name as folder
parts = filename.replace(".json", "").split("_")
if len(parts) >= 2:
return parts[1].capitalize() # Second part is usually the service
return "Misc"
def save_search_index(search_index: Dict[str, Any], output_dir: str):
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Save complete index
with open(
os.path.join(output_dir, "search-index.json"), "w", encoding="utf-8"
) as f:
json.dump(search_index, f, indent=2, ensure_ascii=False)
# Save stats only (for quick loading)
with open(os.path.join(output_dir, "stats.json"), "w", encoding="utf-8") as f:
json.dump(search_index["stats"], f, indent=2, ensure_ascii=False)
# Save categories only
with open(os.path.join(output_dir, "categories.json"), "w", encoding="utf-8") as f:
json.dump(search_index["categories"], f, indent=2, ensure_ascii=False)
# Save integrations only
with open(
os.path.join(output_dir, "integrations.json"), "w", encoding="utf-8"
) as f:
json.dump(search_index["integrations"], f, indent=2, ensure_ascii=False)
print("Search index generated successfully:")
print(f" {search_index['stats']['total_workflows']} workflows indexed")
print(f" {len(search_index['categories'])} categories")
print(f" {len(search_index['integrations'])} popular integrations")
print(f" Files saved to: {output_dir}")
def main():
# Paths
db_path = "database/workflows.db"
output_dir = "docs/api"
# Check if database exists
if not os.path.exists(db_path):
print(f"Database not found: {db_path}")
print("Run 'python run.py --reindex' first to create the database")
sys.exit(1)
try:
print("Generating static search index...")
search_index = generate_static_search_index(db_path, output_dir)
save_search_index(search_index, output_dir)
print("Static search index ready for GitHub Pages!")
except Exception as e:
print(f"Error generating search index: {e}")
sys.exit(1)
if __name__ == "__main__":
main() | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Generate Static Search Index for GitHub Pages
+Creates a lightweight JSON index for client-side search functionality.
+"""
import json
import os
@@ -13,6 +17,7 @@
def generate_static_search_index(db_path: str, output_dir: str) -> Dict[str, Any]:
+ """Generate a static search index for client-side searching."""
# Initialize database
db = WorkflowDatabase(db_path)
@@ -91,6 +96,7 @@
def load_existing_categories() -> Dict[str, str]:
+ """Load existing categories from search_categories.json created by create_categories.py."""
try:
with open("context/search_categories.json", "r", encoding="utf-8") as f:
categories_data = json.load(f)
@@ -115,6 +121,7 @@ integrations: List[str],
service_categories: Dict[str, List[str]],
) -> str:
+ """Get category for workflow, preferring existing assignment over integration-based."""
# First priority: Use existing category from create_categories.py system
if filename in existing_categories:
@@ -127,6 +134,7 @@ def determine_category(
integrations: List[str], categories: Dict[str, List[str]]
) -> str:
+ """Determine the category for a workflow based on its integrations."""
if not integrations:
return "Uncategorized"
@@ -140,6 +148,7 @@
def format_category_name(category_key: str) -> str:
+ """Format category key to display name."""
category_mapping = {
"messaging": "Communication & Messaging",
"email": "Communication & Messaging",
@@ -158,6 +167,7 @@
def get_category_list(categories: Dict[str, List[str]]) -> List[str]:
+ """Get formatted list of all categories."""
formatted_categories = set()
for category_key in categories.keys():
formatted_categories.add(format_category_name(category_key))
@@ -180,6 +190,7 @@
def get_popular_integrations(workflows: List[Dict]) -> List[Dict[str, Any]]:
+ """Get list of popular integrations with counts."""
integration_counts = {}
for workflow in workflows:
@@ -195,6 +206,7 @@
def extract_folder_from_filename(filename: str) -> str:
+ """Extract folder name from workflow filename."""
# Most workflows follow pattern: ID_Service_Purpose_Trigger.json
# Extract the service name as folder
parts = filename.replace(".json", "").split("_")
@@ -204,6 +216,7 @@
def save_search_index(search_index: Dict[str, Any], output_dir: str):
+ """Save the search index to multiple formats for different uses."""
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
@@ -236,6 +249,7 @@
def main():
+ """Main function to generate search index."""
# Paths
db_path = "database/workflows.db"
@@ -260,4 +274,4 @@
if __name__ == "__main__":
- main()+ main()
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/scripts/generate_search_index.py |
Add detailed docstrings explaining each function | #!/usr/bin/env python3
import sys
import os
import argparse
def print_banner():
print("🚀 n8n-workflows Advanced Search Engine")
print("=" * 50)
def check_requirements() -> bool:
missing_deps = []
try:
import sqlite3
except ImportError:
missing_deps.append("sqlite3")
try:
import uvicorn
except ImportError:
missing_deps.append("uvicorn")
try:
import fastapi
except ImportError:
missing_deps.append("fastapi")
if missing_deps:
print(f"❌ Missing dependencies: {', '.join(missing_deps)}")
print("💡 Install with: pip install -r requirements.txt")
return False
print("✅ Dependencies verified")
return True
def setup_directories():
directories = ["database", "static", "workflows"]
for directory in directories:
os.makedirs(directory, exist_ok=True)
print("✅ Directories verified")
def setup_database(force_reindex: bool = False, skip_index: bool = False) -> str:
from workflow_db import WorkflowDatabase
db_path = "database/workflows.db"
print(f"🔄 Setting up database: {db_path}")
db = WorkflowDatabase(db_path)
# Skip indexing in CI mode or if explicitly requested
if skip_index:
print("⏭️ Skipping workflow indexing (CI mode)")
stats = db.get_stats()
print(f"✅ Database ready: {stats['total']} workflows")
return db_path
# Check if database has data or force reindex
stats = db.get_stats()
if stats["total"] == 0 or force_reindex:
print("📚 Indexing workflows...")
index_stats = db.index_all_workflows(force_reindex=True)
print(f"✅ Indexed {index_stats['processed']} workflows")
# Show final stats
final_stats = db.get_stats()
print(f"📊 Database contains {final_stats['total']} workflows")
else:
print(f"✅ Database ready: {stats['total']} workflows")
return db_path
def start_server(host: str = "127.0.0.1", port: int = 8000, reload: bool = False):
print(f"🌐 Starting server at http://{host}:{port}")
print(f"📊 API Documentation: http://{host}:{port}/docs")
print(f"🔍 Workflow Search: http://{host}:{port}/api/workflows")
print()
print("Press Ctrl+C to stop the server")
print("-" * 50)
# Configure database path
os.environ["WORKFLOW_DB_PATH"] = "database/workflows.db"
# Start uvicorn with better configuration
import uvicorn
uvicorn.run(
"api_server:app",
host=host,
port=port,
reload=reload,
log_level="info",
access_log=False, # Reduce log noise
)
def main():
sys.stdout.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="N8N Workflows Search Engine",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python run.py # Start with default settings
python run.py --port 3000 # Start on port 3000
python run.py --host 0.0.0.0 # Accept external connections
python run.py --reindex # Force database reindexing
python run.py --dev # Development mode with auto-reload
""",
)
parser.add_argument(
"--host", default="127.0.0.1", help="Host to bind to (default: 127.0.0.1)"
)
parser.add_argument(
"--port", type=int, default=8000, help="Port to bind to (default: 8000)"
)
parser.add_argument(
"--reindex", action="store_true", help="Force database reindexing"
)
parser.add_argument(
"--dev", action="store_true", help="Development mode with auto-reload"
)
parser.add_argument(
"--skip-index",
action="store_true",
help="Skip workflow indexing (useful for CI/testing)",
)
args = parser.parse_args()
# Also check environment variable for CI mode
ci_mode = os.environ.get("CI", "").lower() in ("true", "1", "yes")
skip_index = args.skip_index or ci_mode
print_banner()
# Check dependencies
if not check_requirements():
sys.exit(1)
# Setup directories
setup_directories()
# Setup database
try:
setup_database(force_reindex=args.reindex, skip_index=skip_index)
except Exception as e:
print(f"❌ Database setup error: {e}")
sys.exit(1)
# Start server
try:
start_server(host=args.host, port=args.port, reload=args.dev)
except KeyboardInterrupt:
print("\n👋 Server stopped!")
except Exception as e:
print(f"❌ Server error: {e}")
sys.exit(1)
if __name__ == "__main__":
main() | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+🚀 N8N Workflows Search Engine Launcher
+Start the advanced search system with optimized performance.
+"""
import sys
import os
@@ -6,11 +10,13 @@
def print_banner():
+ """Print application banner."""
print("🚀 n8n-workflows Advanced Search Engine")
print("=" * 50)
def check_requirements() -> bool:
+ """Check if required dependencies are installed."""
missing_deps = []
try:
@@ -38,6 +44,7 @@
def setup_directories():
+ """Create necessary directories."""
directories = ["database", "static", "workflows"]
for directory in directories:
@@ -47,6 +54,7 @@
def setup_database(force_reindex: bool = False, skip_index: bool = False) -> str:
+ """Setup and initialize the database."""
from workflow_db import WorkflowDatabase
db_path = "database/workflows.db"
@@ -78,6 +86,7 @@
def start_server(host: str = "127.0.0.1", port: int = 8000, reload: bool = False):
+ """Start the FastAPI server."""
print(f"🌐 Starting server at http://{host}:{port}")
print(f"📊 API Documentation: http://{host}:{port}/docs")
print(f"🔍 Workflow Search: http://{host}:{port}/api/workflows")
@@ -102,6 +111,7 @@
def main():
+ """Main entry point with command line arguments."""
sys.stdout.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="N8N Workflows Search Engine",
@@ -167,4 +177,4 @@
if __name__ == "__main__":
- main()+ main()
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/run.py |
Document this script properly | #!/usr/bin/env python3
import json
from datetime import datetime
from pathlib import Path
import re
def update_html_timestamp(html_file: str):
file_path = Path(html_file)
if not file_path.exists():
print(f"Warning: {html_file} not found")
return False
# Read the HTML file
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# Get current month and year
current_date = datetime.now().strftime("%B %Y")
# Replace the hardcoded timestamp
# Look for pattern like "Last updated: Month Year"
pattern = r'(<p class="footer-meta">Last updated:)\s*([^<]+)'
replacement = f"\\1 {current_date}"
updated_content = re.sub(pattern, replacement, content)
# Also add a meta tag with the exact timestamp for better tracking
if '<meta name="last-updated"' not in updated_content:
timestamp_meta = (
f' <meta name="last-updated" content="{datetime.now().isoformat()}">\n'
)
updated_content = updated_content.replace("</head>", f"{timestamp_meta}</head>")
# Write back the updated content
with open(file_path, "w", encoding="utf-8") as f:
f.write(updated_content)
print(f"✅ Updated timestamp in {html_file} to: {current_date}")
return True
def update_api_timestamp(api_dir: str):
api_path = Path(api_dir)
if not api_path.exists():
api_path.mkdir(parents=True, exist_ok=True)
# Create or update a metadata file with current timestamp
metadata = {
"last_updated": datetime.now().isoformat(),
"last_updated_readable": datetime.now().strftime("%B %d, %Y at %H:%M UTC"),
"version": "2.0.1",
"deployment_type": "github_pages",
}
metadata_file = api_path / "metadata.json"
with open(metadata_file, "w", encoding="utf-8") as f:
json.dump(metadata, f, indent=2)
print(f"✅ Created metadata file: {metadata_file}")
# Update stats.json if it exists
stats_file = api_path / "stats.json"
if stats_file.exists():
with open(stats_file, "r", encoding="utf-8") as f:
stats = json.load(f)
stats["last_updated"] = datetime.now().isoformat()
with open(stats_file, "w", encoding="utf-8") as f:
json.dump(stats, f, indent=2)
print(f"✅ Updated stats file: {stats_file}")
return True
def create_github_pages_config():
# Create/update _config.yml for Jekyll (GitHub Pages)
config_content = """# GitHub Pages Configuration
theme: null
title: N8N Workflows Repository
description: Browse and search 2000+ n8n workflow automation templates
baseurl: "/n8n-workflows"
url: "https://zie619.github.io"
# Build settings
markdown: kramdown
exclude:
- workflows/
- scripts/
- src/
- "*.py"
- requirements.txt
- Dockerfile
- docker-compose.yml
- k8s/
- helm/
- Documentation/
- context/
- database/
- static/
- templates/
- .github/
- .devcontainer/
"""
config_file = Path("docs/_config.yml")
with open(config_file, "w", encoding="utf-8") as f:
f.write(config_content)
print(f"✅ Created Jekyll config: {config_file}")
# Create .nojekyll file to bypass Jekyll processing (for pure HTML/JS site)
nojekyll_file = Path("docs/.nojekyll")
nojekyll_file.touch()
print(f"✅ Created .nojekyll file: {nojekyll_file}")
# Create a simple 404.html page
error_page_content = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 - Page Not Found</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.container {
text-align: center;
padding: 2rem;
}
h1 { font-size: 6rem; margin: 0; }
p { font-size: 1.5rem; margin: 1rem 0; }
a {
display: inline-block;
margin-top: 2rem;
padding: 1rem 2rem;
background: white;
color: #667eea;
text-decoration: none;
border-radius: 5px;
transition: transform 0.2s;
}
a:hover { transform: scale(1.05); }
</style>
</head>
<body>
<div class="container">
<h1>404</h1>
<p>Page not found</p>
<p>The n8n workflows repository has been updated.</p>
<a href="/n8n-workflows/">Go to Homepage</a>
</div>
</body>
</html>"""
error_file = Path("docs/404.html")
with open(error_file, "w", encoding="utf-8") as f:
f.write(error_page_content)
print(f"✅ Created 404 page: {error_file}")
def verify_github_pages_structure():
required_files = [
"docs/index.html",
"docs/css/styles.css",
"docs/js/app.js",
"docs/js/search.js",
"docs/api/search-index.json",
"docs/api/stats.json",
"docs/api/categories.json",
"docs/api/integrations.json",
]
missing_files = []
for file_path in required_files:
if not Path(file_path).exists():
missing_files.append(file_path)
print(f"❌ Missing: {file_path}")
else:
print(f"✅ Found: {file_path}")
if missing_files:
print(f"\n⚠️ Warning: {len(missing_files)} required files are missing")
print("Run the following commands to generate them:")
print(" python workflow_db.py --index --force")
print(" python create_categories.py")
print(" python scripts/generate_search_index.py")
return False
print("\n✅ All required files present for GitHub Pages deployment")
return True
def fix_base_url_references():
# Update index.html to use relative paths
index_file = Path("docs/index.html")
if index_file.exists():
with open(index_file, "r", encoding="utf-8") as f:
content = f.read()
# Replace absolute paths with relative ones
replacements = [
('href="/css/', 'href="css/'),
('src="/js/', 'src="js/'),
('href="/api/', 'href="api/'),
('fetch("/api/', 'fetch("api/'),
("fetch('/api/", "fetch('api/"),
]
for old, new in replacements:
content = content.replace(old, new)
with open(index_file, "w", encoding="utf-8") as f:
f.write(content)
print("✅ Fixed URL references in index.html")
# Update JavaScript files
js_files = ["docs/js/app.js", "docs/js/search.js"]
for js_file in js_files:
js_path = Path(js_file)
if js_path.exists():
with open(js_path, "r", encoding="utf-8") as f:
content = f.read()
# Fix API endpoint references
content = content.replace("fetch('/api/", "fetch('api/")
content = content.replace('fetch("/api/', 'fetch("api/')
content = content.replace("'/api/", "'api/")
content = content.replace('"/api/', '"api/')
with open(js_path, "w", encoding="utf-8") as f:
f.write(content)
print(f"✅ Fixed URL references in {js_file}")
def main():
print("🔧 GitHub Pages Update Script")
print("=" * 50)
# Step 1: Update timestamps
print("\n📅 Updating timestamps...")
update_html_timestamp("docs/index.html")
update_api_timestamp("docs/api")
# Step 2: Create GitHub Pages configuration
print("\n⚙️ Creating GitHub Pages configuration...")
create_github_pages_config()
# Step 3: Fix URL references
print("\n🔗 Fixing URL references...")
fix_base_url_references()
# Step 4: Verify structure
print("\n✔️ Verifying deployment structure...")
if verify_github_pages_structure():
print("\n✨ GitHub Pages setup complete!")
print("\nDeployment will be available at:")
print(" https://zie619.github.io/n8n-workflows/")
print(
"\nNote: It may take a few minutes for changes to appear after pushing to GitHub."
)
else:
print("\n⚠️ Some files are missing. Please generate them first.")
if __name__ == "__main__":
main() | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Update GitHub Pages Files
+Fixes the hardcoded timestamp and ensures proper deployment.
+Addresses Issues #115 and #129.
+"""
import json
from datetime import datetime
@@ -7,6 +12,7 @@
def update_html_timestamp(html_file: str):
+ """Update the timestamp in the HTML file to current date."""
file_path = Path(html_file)
if not file_path.exists():
@@ -43,6 +49,7 @@
def update_api_timestamp(api_dir: str):
+ """Update timestamp in API JSON files."""
api_path = Path(api_dir)
if not api_path.exists():
@@ -79,6 +86,7 @@
def create_github_pages_config():
+ """Create necessary GitHub Pages configuration files."""
# Create/update _config.yml for Jekyll (GitHub Pages)
config_content = """# GitHub Pages Configuration
@@ -173,6 +181,7 @@
def verify_github_pages_structure():
+ """Verify that all necessary files exist for GitHub Pages deployment."""
required_files = [
"docs/index.html",
@@ -206,6 +215,7 @@
def fix_base_url_references():
+ """Fix any hardcoded URLs to use relative paths for GitHub Pages."""
# Update index.html to use relative paths
index_file = Path("docs/index.html")
@@ -249,6 +259,7 @@
def main():
+ """Main function to update GitHub Pages deployment."""
print("🔧 GitHub Pages Update Script")
print("=" * 50)
@@ -280,4 +291,4 @@
if __name__ == "__main__":
- main()+ main()
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/scripts/update_github_pages.py |
Add return value explanations in docstrings | #!/usr/bin/env python3
import sqlite3
import json
import os
import datetime
import hashlib
from typing import Dict, List, Any, Optional, Tuple
from pathlib import Path
class WorkflowDatabase:
def __init__(self, db_path: str = None):
# Use environment variable if no path provided
if db_path is None:
db_path = os.environ.get("WORKFLOW_DB_PATH", "workflows.db")
self.db_path = db_path
self.workflows_dir = "workflows"
self.init_database()
def init_database(self):
conn = sqlite3.connect(self.db_path)
conn.execute("PRAGMA journal_mode=WAL") # Write-ahead logging for performance
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA cache_size=10000")
conn.execute("PRAGMA temp_store=MEMORY")
# Create main workflows table
conn.execute("""
CREATE TABLE IF NOT EXISTS workflows (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
workflow_id TEXT,
active BOOLEAN DEFAULT 0,
description TEXT,
trigger_type TEXT,
complexity TEXT,
node_count INTEGER DEFAULT 0,
integrations TEXT, -- JSON array
tags TEXT, -- JSON array
created_at TEXT,
updated_at TEXT,
file_hash TEXT,
file_size INTEGER,
analyzed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Create FTS5 table for full-text search
conn.execute("""
CREATE VIRTUAL TABLE IF NOT EXISTS workflows_fts USING fts5(
filename,
name,
description,
integrations,
tags,
content=workflows,
content_rowid=id
)
""")
# Create indexes for fast filtering
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_trigger_type ON workflows(trigger_type)"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_complexity ON workflows(complexity)"
)
conn.execute("CREATE INDEX IF NOT EXISTS idx_active ON workflows(active)")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_node_count ON workflows(node_count)"
)
conn.execute("CREATE INDEX IF NOT EXISTS idx_filename ON workflows(filename)")
# Create triggers to keep FTS table in sync
conn.execute("""
CREATE TRIGGER IF NOT EXISTS workflows_ai AFTER INSERT ON workflows BEGIN
INSERT INTO workflows_fts(rowid, filename, name, description, integrations, tags)
VALUES (new.id, new.filename, new.name, new.description, new.integrations, new.tags);
END
""")
conn.execute("""
CREATE TRIGGER IF NOT EXISTS workflows_ad AFTER DELETE ON workflows BEGIN
INSERT INTO workflows_fts(workflows_fts, rowid, filename, name, description, integrations, tags)
VALUES ('delete', old.id, old.filename, old.name, old.description, old.integrations, old.tags);
END
""")
conn.execute("""
CREATE TRIGGER IF NOT EXISTS workflows_au AFTER UPDATE ON workflows BEGIN
INSERT INTO workflows_fts(workflows_fts, rowid, filename, name, description, integrations, tags)
VALUES ('delete', old.id, old.filename, old.name, old.description, old.integrations, old.tags);
INSERT INTO workflows_fts(rowid, filename, name, description, integrations, tags)
VALUES (new.id, new.filename, new.name, new.description, new.integrations, new.tags);
END
""")
conn.commit()
conn.close()
def get_file_hash(self, file_path: str) -> str:
hash_md5 = hashlib.md5()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def format_workflow_name(self, filename: str) -> str:
# Remove .json extension
name = filename.replace(".json", "")
# Split by underscores
parts = name.split("_")
# Skip the first part if it's just a number
if len(parts) > 1 and parts[0].isdigit():
parts = parts[1:]
# Convert parts to title case and join with spaces
readable_parts = []
for part in parts:
# Special handling for common terms
if part.lower() == "http":
readable_parts.append("HTTP")
elif part.lower() == "api":
readable_parts.append("API")
elif part.lower() == "webhook":
readable_parts.append("Webhook")
elif part.lower() == "automation":
readable_parts.append("Automation")
elif part.lower() == "automate":
readable_parts.append("Automate")
elif part.lower() == "scheduled":
readable_parts.append("Scheduled")
elif part.lower() == "triggered":
readable_parts.append("Triggered")
elif part.lower() == "manual":
readable_parts.append("Manual")
else:
# Capitalize first letter
readable_parts.append(part.capitalize())
return " ".join(readable_parts)
def analyze_workflow_file(self, file_path: str) -> Optional[Dict[str, Any]]:
try:
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
except (json.JSONDecodeError, UnicodeDecodeError) as e:
print(f"Error reading {file_path}: {str(e)}")
return None
filename = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
file_hash = self.get_file_hash(file_path)
# Extract basic metadata
workflow = {
"filename": filename,
"name": self.format_workflow_name(filename),
"workflow_id": data.get("id", ""),
"active": data.get("active", False),
"nodes": data.get("nodes", []),
"connections": data.get("connections", {}),
"tags": data.get("tags", []),
"created_at": data.get("createdAt", ""),
"updated_at": data.get("updatedAt", ""),
"file_hash": file_hash,
"file_size": file_size,
}
# Use JSON name if available and meaningful, otherwise use formatted filename
json_name = data.get("name", "").strip()
if (
json_name
and json_name != filename.replace(".json", "")
and not json_name.startswith("My workflow")
):
workflow["name"] = json_name
# If no meaningful JSON name, use formatted filename (already set above)
# Analyze nodes
node_count = len(workflow["nodes"])
workflow["node_count"] = node_count
# Determine complexity
if node_count <= 5:
complexity = "low"
elif node_count <= 15:
complexity = "medium"
else:
complexity = "high"
workflow["complexity"] = complexity
# Find trigger type and integrations
trigger_type, integrations = self.analyze_nodes(workflow["nodes"])
workflow["trigger_type"] = trigger_type
workflow["integrations"] = list(integrations)
# Use JSON description if available, otherwise generate one
json_description = data.get("description", "").strip()
if json_description:
workflow["description"] = json_description
else:
workflow["description"] = self.generate_description(
workflow, trigger_type, integrations
)
return workflow
def analyze_nodes(self, nodes: List[Dict]) -> Tuple[str, set]:
trigger_type = "Manual"
integrations = set()
# Enhanced service mapping for better recognition
service_mappings = {
# Messaging & Communication
"telegram": "Telegram",
"telegramTrigger": "Telegram",
"discord": "Discord",
"slack": "Slack",
"whatsapp": "WhatsApp",
"mattermost": "Mattermost",
"teams": "Microsoft Teams",
"rocketchat": "Rocket.Chat",
# Email
"gmail": "Gmail",
"mailjet": "Mailjet",
"emailreadimap": "Email (IMAP)",
"emailsendsmt": "Email (SMTP)",
"outlook": "Outlook",
# Cloud Storage
"googledrive": "Google Drive",
"googledocs": "Google Docs",
"googlesheets": "Google Sheets",
"dropbox": "Dropbox",
"onedrive": "OneDrive",
"box": "Box",
# Databases
"postgres": "PostgreSQL",
"mysql": "MySQL",
"mongodb": "MongoDB",
"redis": "Redis",
"airtable": "Airtable",
"notion": "Notion",
# Project Management
"jira": "Jira",
"github": "GitHub",
"gitlab": "GitLab",
"trello": "Trello",
"asana": "Asana",
"mondaycom": "Monday.com",
# AI/ML Services
"openai": "OpenAI",
"anthropic": "Anthropic",
"huggingface": "Hugging Face",
# Social Media
"linkedin": "LinkedIn",
"twitter": "Twitter/X",
"facebook": "Facebook",
"instagram": "Instagram",
# E-commerce
"shopify": "Shopify",
"stripe": "Stripe",
"paypal": "PayPal",
# Analytics
"googleanalytics": "Google Analytics",
"mixpanel": "Mixpanel",
# Calendar & Tasks
"googlecalendar": "Google Calendar",
"googletasks": "Google Tasks",
"cal": "Cal.com",
"calendly": "Calendly",
# Forms & Surveys
"typeform": "Typeform",
"googleforms": "Google Forms",
"form": "Form Trigger",
# Development Tools
"webhook": "Webhook",
"httpRequest": "HTTP Request",
"graphql": "GraphQL",
"sse": "Server-Sent Events",
# Utility nodes (exclude from integrations)
"set": None,
"function": None,
"code": None,
"if": None,
"switch": None,
"merge": None,
"split": None,
"stickynote": None,
"stickyNote": None,
"wait": None,
"schedule": None,
"cron": None,
"manual": None,
"stopanderror": None,
"noop": None,
"noOp": None,
"error": None,
"limit": None,
"aggregate": None,
"summarize": None,
"filter": None,
"sort": None,
"removeDuplicates": None,
"dateTime": None,
"extractFromFile": None,
"convertToFile": None,
"readBinaryFile": None,
"readBinaryFiles": None,
"executionData": None,
"executeWorkflow": None,
"executeCommand": None,
"respondToWebhook": None,
}
for node in nodes:
node_type = node.get("type", "")
node_name = node.get("name", "").lower()
# Determine trigger type
if "webhook" in node_type.lower() or "webhook" in node_name:
trigger_type = "Webhook"
elif "cron" in node_type.lower() or "schedule" in node_type.lower():
trigger_type = "Scheduled"
elif "trigger" in node_type.lower() and trigger_type == "Manual":
if "manual" not in node_type.lower():
trigger_type = "Webhook"
# Extract integrations with enhanced mapping
service_name = None
# Handle n8n-nodes-base nodes
if node_type.startswith("n8n-nodes-base."):
raw_service = node_type.replace("n8n-nodes-base.", "").lower()
raw_service = raw_service.replace("trigger", "")
service_name = service_mappings.get(
raw_service, raw_service.title() if raw_service else None
)
# Handle @n8n/ namespaced nodes
elif node_type.startswith("@n8n/"):
raw_service = (
node_type.split(".")[-1].lower()
if "." in node_type
else node_type.lower()
)
raw_service = raw_service.replace("trigger", "")
service_name = service_mappings.get(
raw_service, raw_service.title() if raw_service else None
)
# Handle custom nodes
elif "-" in node_type or "@" in node_type:
# Try to extract service name from custom node names like "n8n-nodes-youtube-transcription-kasha.youtubeTranscripter"
parts = node_type.lower().split(".")
for part in parts:
if "youtube" in part:
service_name = "YouTube"
break
elif "telegram" in part:
service_name = "Telegram"
break
elif "discord" in part:
service_name = "Discord"
break
elif "calcslive" in part:
service_name = "CalcsLive"
break
# Also check node names for service hints (but avoid false positives)
for service_key, service_value in service_mappings.items():
if service_key in node_name and service_value:
# Avoid false positive: "cal" in calcslive-related terms should not match "Cal.com"
if service_key == "cal" and any(
term in node_name.lower()
for term in ["calcslive", "calc", "calculation"]
):
continue
service_name = service_value
break
# Add to integrations if valid service found
if service_name and service_name not in ["None", None]:
integrations.add(service_name)
# Determine if complex based on node variety and count
if len(nodes) > 10 and len(integrations) > 3:
trigger_type = "Complex"
return trigger_type, integrations
def generate_description(
self, workflow: Dict, trigger_type: str, integrations: set
) -> str:
name = workflow["name"]
node_count = workflow["node_count"]
# Start with trigger description
trigger_descriptions = {
"Webhook": "Webhook-triggered automation that",
"Scheduled": "Scheduled automation that",
"Complex": "Complex multi-step automation that",
}
desc = trigger_descriptions.get(trigger_type, "Manual workflow that")
# Add functionality based on name and integrations
if integrations:
main_services = list(integrations)[:3]
if len(main_services) == 1:
desc += f" integrates with {main_services[0]}"
elif len(main_services) == 2:
desc += f" connects {main_services[0]} and {main_services[1]}"
else:
desc += f" orchestrates {', '.join(main_services[:-1])}, and {main_services[-1]}"
# Add workflow purpose hints from name
name_lower = name.lower()
if "create" in name_lower:
desc += " to create new records"
elif "update" in name_lower:
desc += " to update existing data"
elif "sync" in name_lower:
desc += " to synchronize data"
elif "notification" in name_lower or "alert" in name_lower:
desc += " for notifications and alerts"
elif "backup" in name_lower:
desc += " for data backup operations"
elif "monitor" in name_lower:
desc += " for monitoring and reporting"
else:
desc += " for data processing"
desc += f". Uses {node_count} nodes"
if len(integrations) > 3:
desc += f" and integrates with {len(integrations)} services"
return desc + "."
def index_all_workflows(self, force_reindex: bool = False) -> Dict[str, int]:
if not os.path.exists(self.workflows_dir):
print(f"Warning: Workflows directory '{self.workflows_dir}' not found.")
return {"processed": 0, "skipped": 0, "errors": 0}
workflows_path = Path(self.workflows_dir)
json_files = [str(p) for p in workflows_path.rglob("*.json")]
if not json_files:
print(f"Warning: No JSON files found in '{self.workflows_dir}' directory.")
return {"processed": 0, "skipped": 0, "errors": 0}
print(f"Indexing {len(json_files)} workflow files...")
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
stats = {"processed": 0, "skipped": 0, "errors": 0}
for file_path in json_files:
filename = os.path.basename(file_path)
try:
# Check if file needs to be reprocessed
if not force_reindex:
current_hash = self.get_file_hash(file_path)
cursor = conn.execute(
"SELECT file_hash FROM workflows WHERE filename = ?",
(filename,),
)
row = cursor.fetchone()
if row and row["file_hash"] == current_hash:
stats["skipped"] += 1
continue
# Analyze workflow
workflow_data = self.analyze_workflow_file(file_path)
if not workflow_data:
stats["errors"] += 1
continue
# Insert or update in database
conn.execute(
"""
INSERT OR REPLACE INTO workflows (
filename, name, workflow_id, active, description, trigger_type,
complexity, node_count, integrations, tags, created_at, updated_at,
file_hash, file_size, analyzed_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
""",
(
workflow_data["filename"],
workflow_data["name"],
workflow_data["workflow_id"],
workflow_data["active"],
workflow_data["description"],
workflow_data["trigger_type"],
workflow_data["complexity"],
workflow_data["node_count"],
json.dumps(workflow_data["integrations"]),
json.dumps(workflow_data["tags"]),
workflow_data["created_at"],
workflow_data["updated_at"],
workflow_data["file_hash"],
workflow_data["file_size"],
),
)
stats["processed"] += 1
except Exception as e:
print(f"Error processing {file_path}: {str(e)}")
stats["errors"] += 1
continue
conn.commit()
conn.close()
print(
f"✅ Indexing complete: {stats['processed']} processed, {stats['skipped']} skipped, {stats['errors']} errors"
)
return stats
def search_workflows(
self,
query: str = "",
trigger_filter: str = "all",
complexity_filter: str = "all",
active_only: bool = False,
limit: int = 50,
offset: int = 0,
) -> Tuple[List[Dict], int]:
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
# Build WHERE clause
where_conditions = []
params = []
if active_only:
where_conditions.append("w.active = 1")
if trigger_filter != "all":
where_conditions.append("w.trigger_type = ?")
params.append(trigger_filter)
if complexity_filter != "all":
where_conditions.append("w.complexity = ?")
params.append(complexity_filter)
# Use FTS search if query provided
if query.strip():
# FTS search with ranking
base_query = """
SELECT w.*, rank
FROM workflows_fts fts
JOIN workflows w ON w.id = fts.rowid
WHERE workflows_fts MATCH ?
"""
params.insert(0, query)
else:
# Regular query without FTS
base_query = """
SELECT w.*, 0 as rank
FROM workflows w
WHERE 1=1
"""
if where_conditions:
base_query += " AND " + " AND ".join(where_conditions)
# Count total results
count_query = f"SELECT COUNT(*) as total FROM ({base_query}) t"
cursor = conn.execute(count_query, params)
total = cursor.fetchone()["total"]
# Get paginated results
if query.strip():
base_query += " ORDER BY rank"
else:
base_query += " ORDER BY w.analyzed_at DESC"
base_query += f" LIMIT {limit} OFFSET {offset}"
cursor = conn.execute(base_query, params)
rows = cursor.fetchall()
# Convert to dictionaries and parse JSON fields
results = []
for row in rows:
workflow = dict(row)
workflow["integrations"] = json.loads(workflow["integrations"] or "[]")
# Parse tags and convert dict tags to strings
raw_tags = json.loads(workflow["tags"] or "[]")
clean_tags = []
for tag in raw_tags:
if isinstance(tag, dict):
# Extract name from tag dict if available
clean_tags.append(tag.get("name", str(tag.get("id", "tag"))))
else:
clean_tags.append(str(tag))
workflow["tags"] = clean_tags
results.append(workflow)
conn.close()
return results, total
def get_stats(self) -> Dict[str, Any]:
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
# Basic counts
cursor = conn.execute("SELECT COUNT(*) as total FROM workflows")
total = cursor.fetchone()["total"]
cursor = conn.execute(
"SELECT COUNT(*) as active FROM workflows WHERE active = 1"
)
active = cursor.fetchone()["active"]
# Trigger type breakdown
cursor = conn.execute("""
SELECT trigger_type, COUNT(*) as count
FROM workflows
GROUP BY trigger_type
""")
triggers = {row["trigger_type"]: row["count"] for row in cursor.fetchall()}
# Complexity breakdown
cursor = conn.execute("""
SELECT complexity, COUNT(*) as count
FROM workflows
GROUP BY complexity
""")
complexity = {row["complexity"]: row["count"] for row in cursor.fetchall()}
# Node stats
cursor = conn.execute("SELECT SUM(node_count) as total_nodes FROM workflows")
total_nodes = cursor.fetchone()["total_nodes"] or 0
# Unique integrations count
cursor = conn.execute(
"SELECT integrations FROM workflows WHERE integrations != '[]'"
)
all_integrations = set()
for row in cursor.fetchall():
integrations = json.loads(row["integrations"])
all_integrations.update(integrations)
conn.close()
return {
"total": total,
"active": active,
"inactive": total - active,
"triggers": triggers,
"complexity": complexity,
"total_nodes": total_nodes,
"unique_integrations": len(all_integrations),
"last_indexed": datetime.datetime.now().isoformat(),
}
def get_service_categories(self) -> Dict[str, List[str]]:
return {
"messaging": [
"Telegram",
"Discord",
"Slack",
"WhatsApp",
"Mattermost",
"Microsoft Teams",
"Rocket.Chat",
],
"email": ["Gmail", "Mailjet", "Email (IMAP)", "Email (SMTP)", "Outlook"],
"cloud_storage": [
"Google Drive",
"Google Docs",
"Google Sheets",
"Dropbox",
"OneDrive",
"Box",
],
"database": [
"PostgreSQL",
"MySQL",
"MongoDB",
"Redis",
"Airtable",
"Notion",
],
"project_management": [
"Jira",
"GitHub",
"GitLab",
"Trello",
"Asana",
"Monday.com",
],
"ai_ml": ["OpenAI", "Anthropic", "Hugging Face", "CalcsLive"],
"social_media": ["LinkedIn", "Twitter/X", "Facebook", "Instagram"],
"ecommerce": ["Shopify", "Stripe", "PayPal"],
"analytics": ["Google Analytics", "Mixpanel"],
"calendar_tasks": [
"Google Calendar",
"Google Tasks",
"Cal.com",
"Calendly",
],
"forms": ["Typeform", "Google Forms", "Form Trigger"],
"development": [
"Webhook",
"HTTP Request",
"GraphQL",
"Server-Sent Events",
"YouTube",
],
}
def search_by_category(
self, category: str, limit: int = 50, offset: int = 0
) -> Tuple[List[Dict], int]:
categories = self.get_service_categories()
if category not in categories:
return [], 0
services = categories[category]
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
# Build OR conditions for all services in category
service_conditions = []
params = []
for service in services:
service_conditions.append("integrations LIKE ?")
params.append(f'%"{service}"%')
where_clause = " OR ".join(service_conditions)
# Count total results
count_query = f"SELECT COUNT(*) as total FROM workflows WHERE {where_clause}"
cursor = conn.execute(count_query, params)
total = cursor.fetchone()["total"]
# Get paginated results
query = f"""
SELECT * FROM workflows
WHERE {where_clause}
ORDER BY analyzed_at DESC
LIMIT {limit} OFFSET {offset}
"""
cursor = conn.execute(query, params)
rows = cursor.fetchall()
# Convert to dictionaries and parse JSON fields
results = []
for row in rows:
workflow = dict(row)
workflow["integrations"] = json.loads(workflow["integrations"] or "[]")
raw_tags = json.loads(workflow["tags"] or "[]")
clean_tags = []
for tag in raw_tags:
if isinstance(tag, dict):
clean_tags.append(tag.get("name", str(tag.get("id", "tag"))))
else:
clean_tags.append(str(tag))
workflow["tags"] = clean_tags
results.append(workflow)
conn.close()
return results, total
def main():
import argparse
parser = argparse.ArgumentParser(description="N8N Workflow Database")
parser.add_argument("--index", action="store_true", help="Index all workflows")
parser.add_argument("--force", action="store_true", help="Force reindex all files")
parser.add_argument("--search", help="Search workflows")
parser.add_argument("--stats", action="store_true", help="Show database statistics")
args = parser.parse_args()
db = WorkflowDatabase()
if args.index:
stats = db.index_all_workflows(force_reindex=args.force)
print(f"Indexed {stats['processed']} workflows")
elif args.search:
results, total = db.search_workflows(args.search, limit=10)
print(f"Found {total} workflows:")
for workflow in results:
print(
f" - {workflow['name']} ({workflow['trigger_type']}, {workflow['node_count']} nodes)"
)
elif args.stats:
stats = db.get_stats()
print("Database Statistics:")
print(f" Total workflows: {stats['total']}")
print(f" Active: {stats['active']}")
print(f" Total nodes: {stats['total_nodes']}")
print(f" Unique integrations: {stats['unique_integrations']}")
print(f" Trigger types: {stats['triggers']}")
else:
parser.print_help()
if __name__ == "__main__":
main() | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Fast N8N Workflow Database
+SQLite-based workflow indexer and search engine for instant performance.
+"""
import sqlite3
import json
@@ -10,6 +14,7 @@
class WorkflowDatabase:
+ """High-performance SQLite database for workflow metadata and search."""
def __init__(self, db_path: str = None):
# Use environment variable if no path provided
@@ -20,6 +25,7 @@ self.init_database()
def init_database(self):
+ """Initialize SQLite database with optimized schema and indexes."""
conn = sqlite3.connect(self.db_path)
conn.execute("PRAGMA journal_mode=WAL") # Write-ahead logging for performance
conn.execute("PRAGMA synchronous=NORMAL")
@@ -102,6 +108,7 @@ conn.close()
def get_file_hash(self, file_path: str) -> str:
+ """Get MD5 hash of file for change detection."""
hash_md5 = hashlib.md5()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
@@ -109,6 +116,7 @@ return hash_md5.hexdigest()
def format_workflow_name(self, filename: str) -> str:
+ """Convert filename to readable workflow name."""
# Remove .json extension
name = filename.replace(".json", "")
@@ -146,6 +154,7 @@ return " ".join(readable_parts)
def analyze_workflow_file(self, file_path: str) -> Optional[Dict[str, Any]]:
+ """Analyze a single workflow file and extract metadata."""
try:
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
@@ -212,6 +221,7 @@ return workflow
def analyze_nodes(self, nodes: List[Dict]) -> Tuple[str, set]:
+ """Analyze nodes to determine trigger type and integrations."""
trigger_type = "Manual"
integrations = set()
@@ -397,6 +407,7 @@ def generate_description(
self, workflow: Dict, trigger_type: str, integrations: set
) -> str:
+ """Generate a descriptive summary of the workflow."""
name = workflow["name"]
node_count = workflow["node_count"]
@@ -442,6 +453,7 @@ return desc + "."
def index_all_workflows(self, force_reindex: bool = False) -> Dict[str, int]:
+ """Index all workflow files. Only reprocesses changed files unless force_reindex=True."""
if not os.path.exists(self.workflows_dir):
print(f"Warning: Workflows directory '{self.workflows_dir}' not found.")
return {"processed": 0, "skipped": 0, "errors": 0}
@@ -533,6 +545,7 @@ limit: int = 50,
offset: int = 0,
) -> Tuple[List[Dict], int]:
+ """Fast search with filters and pagination."""
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
@@ -611,6 +624,7 @@ return results, total
def get_stats(self) -> Dict[str, Any]:
+ """Get database statistics."""
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
@@ -666,6 +680,7 @@ }
def get_service_categories(self) -> Dict[str, List[str]]:
+ """Get service categories for enhanced filtering."""
return {
"messaging": [
"Telegram",
@@ -724,6 +739,7 @@ def search_by_category(
self, category: str, limit: int = 50, offset: int = 0
) -> Tuple[List[Dict], int]:
+ """Search workflows by service category."""
categories = self.get_service_categories()
if category not in categories:
return [], 0
@@ -777,6 +793,7 @@
def main():
+ """Command-line interface for workflow database."""
import argparse
parser = argparse.ArgumentParser(description="N8N Workflow Database")
@@ -815,4 +832,4 @@
if __name__ == "__main__":
- main()+ main()
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/workflow_db.py |
Help me write clear docstrings | #!/usr/bin/env python3
import sqlite3
import time
from datetime import datetime
from typing import Dict, List, Optional
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from pydantic import BaseModel
import uvicorn
# Import community features
from community_features import CommunityFeatures, create_community_api_endpoints
class WorkflowSearchRequest(BaseModel):
query: str
categories: Optional[List[str]] = None
trigger_types: Optional[List[str]] = None
complexity_levels: Optional[List[str]] = None
integrations: Optional[List[str]] = None
min_rating: Optional[float] = None
limit: int = 20
offset: int = 0
class WorkflowRecommendationRequest(BaseModel):
user_interests: List[str]
viewed_workflows: Optional[List[str]] = None
preferred_complexity: Optional[str] = None
limit: int = 10
class AnalyticsRequest(BaseModel):
date_range: str # "7d", "30d", "90d", "1y"
metrics: List[str] # ["views", "downloads", "ratings", "searches"]
class EnhancedAPI:
def __init__(self, db_path: str = "workflows.db"):
self.db_path = db_path
self.community = CommunityFeatures(db_path)
self.app = FastAPI(
title="N8N Workflows Enhanced API",
description="Advanced API for n8n workflows repository with community features",
version="2.0.0",
)
self._setup_middleware()
self._setup_routes()
def _setup_middleware(self):
# CORS middleware
self.app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Gzip compression
self.app.add_middleware(GZipMiddleware, minimum_size=1000)
def _setup_routes(self):
# Core workflow endpoints
@self.app.get("/api/v2/workflows")
async def get_workflows_enhanced(
search: Optional[str] = Query(None),
category: Optional[str] = Query(None),
trigger_type: Optional[str] = Query(None),
complexity: Optional[str] = Query(None),
integration: Optional[str] = Query(None),
min_rating: Optional[float] = Query(None),
sort_by: str = Query("name"),
sort_order: str = Query("asc"),
limit: int = Query(20, le=100),
offset: int = Query(0, ge=0),
):
start_time = time.time()
try:
workflows = self._search_workflows_enhanced(
search=search,
category=category,
trigger_type=trigger_type,
complexity=complexity,
integration=integration,
min_rating=min_rating,
sort_by=sort_by,
sort_order=sort_order,
limit=limit,
offset=offset,
)
response_time = (time.time() - start_time) * 1000
return {
"workflows": workflows,
"total": len(workflows),
"limit": limit,
"offset": offset,
"response_time_ms": round(response_time, 2),
"timestamp": datetime.now().isoformat(),
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.post("/api/v2/workflows/search")
async def advanced_workflow_search(request: WorkflowSearchRequest):
start_time = time.time()
try:
results = self._advanced_search(request)
response_time = (time.time() - start_time) * 1000
return {
"results": results,
"total": len(results),
"query": request.dict(),
"response_time_ms": round(response_time, 2),
"timestamp": datetime.now().isoformat(),
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.get("/api/v2/workflows/{workflow_id}")
async def get_workflow_enhanced(
workflow_id: str,
include_stats: bool = Query(True),
include_ratings: bool = Query(True),
include_related: bool = Query(True),
):
try:
workflow_data = self._get_workflow_details(
workflow_id, include_stats, include_ratings, include_related
)
if not workflow_data:
raise HTTPException(status_code=404, detail="Workflow not found")
return workflow_data
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Recommendation endpoints
@self.app.post("/api/v2/recommendations")
async def get_workflow_recommendations(request: WorkflowRecommendationRequest):
try:
recommendations = self._get_recommendations(request)
return {
"recommendations": recommendations,
"user_profile": request.dict(),
"timestamp": datetime.now().isoformat(),
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.get("/api/v2/recommendations/trending")
async def get_trending_workflows(limit: int = Query(10, le=50)):
try:
trending = self._get_trending_workflows(limit)
return {
"trending": trending,
"limit": limit,
"timestamp": datetime.now().isoformat(),
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Analytics endpoints
@self.app.get("/api/v2/analytics/overview")
async def get_analytics_overview():
try:
overview = self._get_analytics_overview()
return overview
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.post("/api/v2/analytics/custom")
async def get_custom_analytics(request: AnalyticsRequest):
try:
analytics = self._get_custom_analytics(request)
return analytics
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Performance monitoring
@self.app.get("/api/v2/health")
async def health_check():
try:
health_data = self._get_health_status()
return health_data
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Add community endpoints
create_community_api_endpoints(self.app)
def _search_workflows_enhanced(self, **kwargs) -> List[Dict]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Build dynamic query
query_parts = ["SELECT w.*, ws.average_rating, ws.total_ratings"]
query_parts.append("FROM workflows w")
query_parts.append("LEFT JOIN workflow_stats ws ON w.filename = ws.workflow_id")
conditions = []
params = []
# Apply filters
if kwargs.get("search"):
conditions.append(
"(w.name LIKE ? OR w.description LIKE ? OR w.integrations LIKE ?)"
)
search_term = f"%{kwargs['search']}%"
params.extend([search_term, search_term, search_term])
if kwargs.get("category"):
conditions.append("w.category = ?")
params.append(kwargs["category"])
if kwargs.get("trigger_type"):
conditions.append("w.trigger_type = ?")
params.append(kwargs["trigger_type"])
if kwargs.get("complexity"):
conditions.append("w.complexity = ?")
params.append(kwargs["complexity"])
if kwargs.get("integration"):
conditions.append("w.integrations LIKE ?")
params.append(f"%{kwargs['integration']}%")
if kwargs.get("min_rating"):
conditions.append("ws.average_rating >= ?")
params.append(kwargs["min_rating"])
# Add conditions to query
if conditions:
query_parts.append("WHERE " + " AND ".join(conditions))
# Add sorting
sort_by = kwargs.get("sort_by", "name")
sort_order = kwargs.get("sort_order", "asc").upper()
query_parts.append(f"ORDER BY {sort_by} {sort_order}")
# Add pagination
query_parts.append("LIMIT ? OFFSET ?")
params.extend([kwargs.get("limit", 20), kwargs.get("offset", 0)])
# Execute query
query = " ".join(query_parts)
cursor.execute(query, params)
workflows = []
for row in cursor.fetchall():
workflows.append(
{
"filename": row[0],
"name": row[1],
"workflow_id": row[2],
"active": bool(row[3]),
"description": row[4],
"trigger_type": row[5],
"complexity": row[6],
"node_count": row[7],
"integrations": row[8],
"tags": row[9],
"created_at": row[10],
"updated_at": row[11],
"file_hash": row[12],
"file_size": row[13],
"analyzed_at": row[14],
"average_rating": row[15],
"total_ratings": row[16],
}
)
conn.close()
return workflows
def _advanced_search(self, request: WorkflowSearchRequest) -> List[Dict]:
# Implementation for advanced search logic
# This would include semantic search, fuzzy matching, etc.
return self._search_workflows_enhanced(
search=request.query,
category=request.categories[0] if request.categories else None,
trigger_type=request.trigger_types[0] if request.trigger_types else None,
complexity=request.complexity_levels[0]
if request.complexity_levels
else None,
limit=request.limit,
offset=request.offset,
)
def _get_workflow_details(
self,
workflow_id: str,
include_stats: bool,
include_ratings: bool,
include_related: bool,
) -> Dict:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Get basic workflow data
cursor.execute("SELECT * FROM workflows WHERE filename = ?", (workflow_id,))
workflow_row = cursor.fetchone()
if not workflow_row:
conn.close()
return None
workflow_data = {
"filename": workflow_row[0],
"name": workflow_row[1],
"workflow_id": workflow_row[2],
"active": bool(workflow_row[3]),
"description": workflow_row[4],
"trigger_type": workflow_row[5],
"complexity": workflow_row[6],
"node_count": workflow_row[7],
"integrations": workflow_row[8],
"tags": workflow_row[9],
"created_at": workflow_row[10],
"updated_at": workflow_row[11],
"file_hash": workflow_row[12],
"file_size": workflow_row[13],
"analyzed_at": workflow_row[14],
}
# Add statistics if requested
if include_stats:
stats = self.community.get_workflow_stats(workflow_id)
workflow_data["stats"] = stats.__dict__ if stats else None
# Add ratings if requested
if include_ratings:
ratings = self.community.get_workflow_ratings(workflow_id, 5)
workflow_data["ratings"] = [rating.__dict__ for rating in ratings]
# Add related workflows if requested
if include_related:
related = self._get_related_workflows(workflow_id)
workflow_data["related_workflows"] = related
conn.close()
return workflow_data
def _get_recommendations(
self, request: WorkflowRecommendationRequest
) -> List[Dict]:
# Implementation for recommendation algorithm
# This would use collaborative filtering, content-based filtering, etc.
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Simple recommendation based on user interests
recommendations = []
for interest in request.user_interests:
cursor.execute(
"""
SELECT * FROM workflows
WHERE integrations LIKE ? OR name LIKE ? OR description LIKE ?
LIMIT 5
""",
(f"%{interest}%", f"%{interest}%", f"%{interest}%"),
)
for row in cursor.fetchall():
recommendations.append(
{
"filename": row[0],
"name": row[1],
"description": row[4],
"reason": f"Matches your interest in {interest}",
}
)
conn.close()
return recommendations[: request.limit]
def _get_trending_workflows(self, limit: int) -> List[Dict]:
return self.community.get_most_popular_workflows(limit)
def _get_analytics_overview(self) -> Dict:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Total workflows
cursor.execute("SELECT COUNT(*) FROM workflows")
total_workflows = cursor.fetchone()[0]
# Active workflows
cursor.execute("SELECT COUNT(*) FROM workflows WHERE active = 1")
active_workflows = cursor.fetchone()[0]
# Categories
cursor.execute("SELECT category, COUNT(*) FROM workflows GROUP BY category")
categories = dict(cursor.fetchall())
# Integrations
cursor.execute("SELECT COUNT(DISTINCT integrations) FROM workflows")
unique_integrations = cursor.fetchone()[0]
conn.close()
return {
"total_workflows": total_workflows,
"active_workflows": active_workflows,
"categories": categories,
"unique_integrations": unique_integrations,
"timestamp": datetime.now().isoformat(),
}
def _get_custom_analytics(self, request: AnalyticsRequest) -> Dict:
# Implementation for custom analytics
return {
"date_range": request.date_range,
"metrics": request.metrics,
"data": {}, # Placeholder for actual analytics data
"timestamp": datetime.now().isoformat(),
}
def _get_health_status(self) -> Dict:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Database health
cursor.execute("SELECT COUNT(*) FROM workflows")
total_workflows = cursor.fetchone()[0]
# Performance test
start_time = time.time()
cursor.execute("SELECT COUNT(*) FROM workflows WHERE active = 1")
active_count = cursor.fetchone()[0]
query_time = (time.time() - start_time) * 1000
conn.close()
return {
"status": "healthy",
"database": {
"total_workflows": total_workflows,
"active_workflows": active_count,
"connection_status": "connected",
},
"performance": {
"query_time_ms": round(query_time, 2),
"response_time_target": "<100ms",
"status": "good" if query_time < 100 else "slow",
},
"timestamp": datetime.now().isoformat(),
}
def _get_related_workflows(self, workflow_id: str, limit: int = 5) -> List[Dict]:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Get current workflow details
cursor.execute(
"SELECT integrations, category FROM workflows WHERE filename = ?",
(workflow_id,),
)
current_workflow = cursor.fetchone()
if not current_workflow:
conn.close()
return []
current_integrations = current_workflow[0] or ""
current_category = current_workflow[1] or ""
# Find related workflows
cursor.execute(
"""
SELECT filename, name, description FROM workflows
WHERE filename != ?
AND (integrations LIKE ? OR category = ?)
LIMIT ?
""",
(workflow_id, f"%{current_integrations[:50]}%", current_category, limit),
)
related = []
for row in cursor.fetchall():
related.append({"filename": row[0], "name": row[1], "description": row[2]})
conn.close()
return related
def run(self, host: str = "127.0.0.1", port: int = 8000, debug: bool = False):
uvicorn.run(
self.app, host=host, port=port, log_level="debug" if debug else "info"
)
if __name__ == "__main__":
# Initialize and run enhanced API
api = EnhancedAPI()
print("🚀 Starting Enhanced N8N Workflows API...")
print(
"📊 Features: Advanced search, recommendations, analytics, community features"
)
print("🌐 API Documentation: http://127.0.0.1:8000/docs")
api.run(debug=True) | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Enhanced API Module for n8n Workflows Repository
+Advanced features, analytics, and performance optimizations
+"""
import sqlite3
import time
@@ -15,6 +19,7 @@
class WorkflowSearchRequest(BaseModel):
+ """Workflow search request model"""
query: str
categories: Optional[List[str]] = None
@@ -27,6 +32,7 @@
class WorkflowRecommendationRequest(BaseModel):
+ """Workflow recommendation request model"""
user_interests: List[str]
viewed_workflows: Optional[List[str]] = None
@@ -35,14 +41,17 @@
class AnalyticsRequest(BaseModel):
+ """Analytics request model"""
date_range: str # "7d", "30d", "90d", "1y"
metrics: List[str] # ["views", "downloads", "ratings", "searches"]
class EnhancedAPI:
+ """Enhanced API with advanced features"""
def __init__(self, db_path: str = "workflows.db"):
+ """Initialize enhanced API"""
self.db_path = db_path
self.community = CommunityFeatures(db_path)
self.app = FastAPI(
@@ -54,6 +63,7 @@ self._setup_routes()
def _setup_middleware(self):
+ """Setup middleware for performance and security"""
# CORS middleware
self.app.add_middleware(
CORSMiddleware,
@@ -67,6 +77,7 @@ self.app.add_middleware(GZipMiddleware, minimum_size=1000)
def _setup_routes(self):
+ """Setup API routes"""
# Core workflow endpoints
@self.app.get("/api/v2/workflows")
@@ -82,6 +93,7 @@ limit: int = Query(20, le=100),
offset: int = Query(0, ge=0),
):
+ """Enhanced workflow search with multiple filters"""
start_time = time.time()
try:
@@ -114,6 +126,7 @@
@self.app.post("/api/v2/workflows/search")
async def advanced_workflow_search(request: WorkflowSearchRequest):
+ """Advanced workflow search with complex queries"""
start_time = time.time()
try:
@@ -138,6 +151,7 @@ include_ratings: bool = Query(True),
include_related: bool = Query(True),
):
+ """Get detailed workflow information"""
try:
workflow_data = self._get_workflow_details(
workflow_id, include_stats, include_ratings, include_related
@@ -154,6 +168,7 @@ # Recommendation endpoints
@self.app.post("/api/v2/recommendations")
async def get_workflow_recommendations(request: WorkflowRecommendationRequest):
+ """Get personalized workflow recommendations"""
try:
recommendations = self._get_recommendations(request)
return {
@@ -167,6 +182,7 @@
@self.app.get("/api/v2/recommendations/trending")
async def get_trending_workflows(limit: int = Query(10, le=50)):
+ """Get trending workflows based on recent activity"""
try:
trending = self._get_trending_workflows(limit)
return {
@@ -181,6 +197,7 @@ # Analytics endpoints
@self.app.get("/api/v2/analytics/overview")
async def get_analytics_overview():
+ """Get analytics overview"""
try:
overview = self._get_analytics_overview()
return overview
@@ -190,6 +207,7 @@
@self.app.post("/api/v2/analytics/custom")
async def get_custom_analytics(request: AnalyticsRequest):
+ """Get custom analytics data"""
try:
analytics = self._get_custom_analytics(request)
return analytics
@@ -200,6 +218,7 @@ # Performance monitoring
@self.app.get("/api/v2/health")
async def health_check():
+ """Health check with performance metrics"""
try:
health_data = self._get_health_status()
return health_data
@@ -211,6 +230,7 @@ create_community_api_endpoints(self.app)
def _search_workflows_enhanced(self, **kwargs) -> List[Dict]:
+ """Enhanced workflow search with multiple filters"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -295,6 +315,7 @@ return workflows
def _advanced_search(self, request: WorkflowSearchRequest) -> List[Dict]:
+ """Advanced search with complex queries"""
# Implementation for advanced search logic
# This would include semantic search, fuzzy matching, etc.
return self._search_workflows_enhanced(
@@ -315,6 +336,7 @@ include_ratings: bool,
include_related: bool,
) -> Dict:
+ """Get detailed workflow information"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -365,6 +387,7 @@ def _get_recommendations(
self, request: WorkflowRecommendationRequest
) -> List[Dict]:
+ """Get personalized workflow recommendations"""
# Implementation for recommendation algorithm
# This would use collaborative filtering, content-based filtering, etc.
conn = sqlite3.connect(self.db_path)
@@ -396,9 +419,11 @@ return recommendations[: request.limit]
def _get_trending_workflows(self, limit: int) -> List[Dict]:
+ """Get trending workflows based on recent activity"""
return self.community.get_most_popular_workflows(limit)
def _get_analytics_overview(self) -> Dict:
+ """Get analytics overview"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -429,6 +454,7 @@ }
def _get_custom_analytics(self, request: AnalyticsRequest) -> Dict:
+ """Get custom analytics data"""
# Implementation for custom analytics
return {
"date_range": request.date_range,
@@ -438,6 +464,7 @@ }
def _get_health_status(self) -> Dict:
+ """Get health status and performance metrics"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -469,6 +496,7 @@ }
def _get_related_workflows(self, workflow_id: str, limit: int = 5) -> List[Dict]:
+ """Get related workflows based on similar integrations or categories"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
@@ -505,6 +533,7 @@ return related
def run(self, host: str = "127.0.0.1", port: int = 8000, debug: bool = False):
+ """Run the enhanced API server"""
uvicorn.run(
self.app, host=host, port=port, log_level="debug" if debug else "info"
)
@@ -519,4 +548,4 @@ )
print("🌐 API Documentation: http://127.0.0.1:8000/docs")
- api.run(debug=True)+ api.run(debug=True)
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/src/enhanced_api.py |
Add docstrings for production code | #!/usr/bin/env python3
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import List, Dict, Any
import asyncio
import time
import psutil
from datetime import datetime, timedelta
import json
import threading
import queue
import os
class PerformanceMetrics(BaseModel):
timestamp: str
cpu_usage: float
memory_usage: float
disk_usage: float
network_io: Dict[str, int]
api_response_times: Dict[str, float]
active_connections: int
database_size: int
workflow_executions: int
error_rate: float
class Alert(BaseModel):
id: str
type: str
severity: str
message: str
timestamp: str
resolved: bool = False
class PerformanceMonitor:
def __init__(self, db_path: str = "workflows.db"):
self.db_path = db_path
self.metrics_history = []
self.alerts = []
self.websocket_connections = []
self.monitoring_active = False
self.metrics_queue = queue.Queue()
def start_monitoring(self):
if not self.monitoring_active:
self.monitoring_active = True
monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
monitor_thread.start()
def _monitor_loop(self):
while self.monitoring_active:
try:
metrics = self._collect_metrics()
self.metrics_history.append(metrics)
# Keep only last 1000 metrics
if len(self.metrics_history) > 1000:
self.metrics_history = self.metrics_history[-1000:]
# Check for alerts
self._check_alerts(metrics)
# Send to websocket connections
self._broadcast_metrics(metrics)
time.sleep(5) # Collect metrics every 5 seconds
except Exception as e:
print(f"Monitoring error: {e}")
time.sleep(10)
def _collect_metrics(self) -> PerformanceMetrics:
# CPU and Memory
cpu_usage = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
memory_usage = memory.percent
# Disk usage
disk = psutil.disk_usage("/")
disk_usage = (disk.used / disk.total) * 100
# Network I/O
network = psutil.net_io_counters()
network_io = {
"bytes_sent": network.bytes_sent,
"bytes_recv": network.bytes_recv,
"packets_sent": network.packets_sent,
"packets_recv": network.packets_recv,
}
# API response times (simulated)
api_response_times = {
"/api/stats": self._measure_api_time("/api/stats"),
"/api/workflows": self._measure_api_time("/api/workflows"),
"/api/search": self._measure_api_time("/api/workflows?q=test"),
}
# Active connections
active_connections = len(psutil.net_connections())
# Database size
try:
db_size = (
os.path.getsize(self.db_path) if os.path.exists(self.db_path) else 0
)
except:
db_size = 0
# Workflow executions (simulated)
workflow_executions = self._get_workflow_executions()
# Error rate (simulated)
error_rate = self._calculate_error_rate()
return PerformanceMetrics(
timestamp=datetime.now().isoformat(),
cpu_usage=cpu_usage,
memory_usage=memory_usage,
disk_usage=disk_usage,
network_io=network_io,
api_response_times=api_response_times,
active_connections=active_connections,
database_size=db_size,
workflow_executions=workflow_executions,
error_rate=error_rate,
)
def _measure_api_time(self, endpoint: str) -> float:
# In a real implementation, this would make actual HTTP requests
import random
return round(random.uniform(10, 100), 2)
def _get_workflow_executions(self) -> int:
# In a real implementation, this would query execution logs
import random
return random.randint(0, 50)
def _calculate_error_rate(self) -> float:
# In a real implementation, this would analyze error logs
import random
return round(random.uniform(0, 5), 2)
def _check_alerts(self, metrics: PerformanceMetrics):
# CPU alert
if metrics.cpu_usage > 80:
self._create_alert(
"high_cpu", "warning", f"High CPU usage: {metrics.cpu_usage}%"
)
# Memory alert
if metrics.memory_usage > 85:
self._create_alert(
"high_memory", "warning", f"High memory usage: {metrics.memory_usage}%"
)
# Disk alert
if metrics.disk_usage > 90:
self._create_alert(
"high_disk", "critical", f"High disk usage: {metrics.disk_usage}%"
)
# API response time alert
for endpoint, response_time in metrics.api_response_times.items():
if response_time > 1000: # 1 second
self._create_alert(
"slow_api",
"warning",
f"Slow API response: {endpoint} ({response_time}ms)",
)
# Error rate alert
if metrics.error_rate > 10:
self._create_alert(
"high_error_rate", "critical", f"High error rate: {metrics.error_rate}%"
)
def _create_alert(self, alert_type: str, severity: str, message: str):
alert = Alert(
id=f"{alert_type}_{int(time.time())}",
type=alert_type,
severity=severity,
message=message,
timestamp=datetime.now().isoformat(),
)
# Check if similar alert already exists
existing_alert = next(
(a for a in self.alerts if a.type == alert_type and not a.resolved), None
)
if not existing_alert:
self.alerts.append(alert)
self._broadcast_alert(alert)
def _broadcast_metrics(self, metrics: PerformanceMetrics):
if self.websocket_connections:
message = {"type": "metrics", "data": metrics.dict()}
self._broadcast_to_websockets(message)
def _broadcast_alert(self, alert: Alert):
message = {"type": "alert", "data": alert.dict()}
self._broadcast_to_websockets(message)
def _broadcast_to_websockets(self, message: dict):
disconnected = []
for websocket in self.websocket_connections:
try:
asyncio.create_task(websocket.send_text(json.dumps(message)))
except:
disconnected.append(websocket)
# Remove disconnected connections
for ws in disconnected:
self.websocket_connections.remove(ws)
def get_metrics_summary(self) -> Dict[str, Any]:
if not self.metrics_history:
return {"message": "No metrics available"}
latest = self.metrics_history[-1]
avg_cpu = sum(m.cpu_usage for m in self.metrics_history[-10:]) / min(
10, len(self.metrics_history)
)
avg_memory = sum(m.memory_usage for m in self.metrics_history[-10:]) / min(
10, len(self.metrics_history)
)
return {
"current": latest.dict(),
"averages": {
"cpu_usage": round(avg_cpu, 2),
"memory_usage": round(avg_memory, 2),
},
"alerts": [alert.dict() for alert in self.alerts[-10:]],
"status": "healthy"
if latest.cpu_usage < 80 and latest.memory_usage < 85
else "warning",
}
def get_historical_metrics(self, hours: int = 24) -> List[Dict]:
cutoff_time = datetime.now() - timedelta(hours=hours)
cutoff_timestamp = cutoff_time.isoformat()
return [
metrics.dict()
for metrics in self.metrics_history
if metrics.timestamp >= cutoff_timestamp
]
def resolve_alert(self, alert_id: str) -> bool:
for alert in self.alerts:
if alert.id == alert_id:
alert.resolved = True
return True
return False
# Initialize performance monitor
performance_monitor = PerformanceMonitor()
performance_monitor.start_monitoring()
# FastAPI app for Performance Monitoring
monitor_app = FastAPI(title="N8N Performance Monitor", version="1.0.0")
@monitor_app.get("/monitor/metrics")
async def get_current_metrics():
return performance_monitor.get_metrics_summary()
@monitor_app.get("/monitor/history")
async def get_historical_metrics(hours: int = 24):
return performance_monitor.get_historical_metrics(hours)
@monitor_app.get("/monitor/alerts")
async def get_alerts():
return [alert.dict() for alert in performance_monitor.alerts if not alert.resolved]
@monitor_app.post("/monitor/alerts/{alert_id}/resolve")
async def resolve_alert(alert_id: str):
success = performance_monitor.resolve_alert(alert_id)
if success:
return {"message": "Alert resolved"}
else:
return {"message": "Alert not found"}
@monitor_app.websocket("/monitor/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
performance_monitor.websocket_connections.append(websocket)
try:
while True:
# Keep connection alive
await websocket.receive_text()
except WebSocketDisconnect:
performance_monitor.websocket_connections.remove(websocket)
@monitor_app.get("/monitor/dashboard")
async def get_monitoring_dashboard():
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N8N Performance Monitor</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f8f9fa;
color: #333;
}
.dashboard {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
text-align: center;
}
.header h1 {
font-size: 32px;
margin-bottom: 10px;
}
.metrics-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.metric-card {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
text-align: center;
}
.metric-value {
font-size: 36px;
font-weight: bold;
margin-bottom: 10px;
}
.metric-value.cpu { color: #667eea; }
.metric-value.memory { color: #28a745; }
.metric-value.disk { color: #ffc107; }
.metric-value.network { color: #17a2b8; }
.metric-label {
color: #666;
font-size: 16px;
}
.status-indicator {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
margin-right: 8px;
}
.status-healthy { background: #28a745; }
.status-warning { background: #ffc107; }
.status-critical { background: #dc3545; }
.chart-container {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
margin-bottom: 30px;
}
.chart-title {
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
color: #333;
}
.alerts-section {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.alert {
background: #f8f9fa;
padding: 15px;
border-radius: 10px;
margin-bottom: 10px;
border-left: 4px solid #667eea;
}
.alert.warning {
border-left-color: #ffc107;
background: #fff3cd;
}
.alert.critical {
border-left-color: #dc3545;
background: #f8d7da;
}
.alert-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 5px;
}
.alert-type {
font-weight: bold;
color: #333;
}
.alert-severity {
padding: 4px 8px;
border-radius: 12px;
font-size: 12px;
font-weight: bold;
text-transform: uppercase;
}
.severity-warning {
background: #ffc107;
color: #856404;
}
.severity-critical {
background: #dc3545;
color: white;
}
.alert-message {
color: #666;
font-size: 14px;
}
.alert-timestamp {
color: #999;
font-size: 12px;
margin-top: 5px;
}
.resolve-btn {
background: #28a745;
color: white;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
}
.resolve-btn:hover {
background: #218838;
}
</style>
</head>
<body>
<div class="dashboard">
<div class="header">
<h1>📊 N8N Performance Monitor</h1>
<p>Real-time system monitoring and alerting</p>
<div id="connectionStatus">
<span class="status-indicator" id="statusIndicator"></span>
<span id="statusText">Connecting...</span>
</div>
</div>
<div class="metrics-grid" id="metricsGrid">
<div class="loading">Loading metrics...</div>
</div>
<div class="chart-container">
<div class="chart-title">CPU & Memory Usage</div>
<canvas id="performanceChart" width="400" height="200"></canvas>
</div>
<div class="chart-container">
<div class="chart-title">API Response Times</div>
<canvas id="apiChart" width="400" height="200"></canvas>
</div>
<div class="alerts-section">
<div class="chart-title">Active Alerts</div>
<div id="alertsContainer">
<div class="loading">Loading alerts...</div>
</div>
</div>
</div>
<script>
let ws = null;
let performanceChart = null;
let apiChart = null;
let metricsData = [];
function connectWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/monitor/ws`;
ws = new WebSocket(wsUrl);
ws.onopen = function() {
updateConnectionStatus(true);
loadInitialData();
};
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.type === 'metrics') {
updateMetrics(data.data);
updateCharts(data.data);
} else if (data.type === 'alert') {
addAlert(data.data);
}
};
ws.onclose = function() {
updateConnectionStatus(false);
setTimeout(connectWebSocket, 5000);
};
ws.onerror = function() {
updateConnectionStatus(false);
};
}
function updateConnectionStatus(connected) {
const indicator = document.getElementById('statusIndicator');
const text = document.getElementById('statusText');
if (connected) {
indicator.className = 'status-indicator status-healthy';
text.textContent = 'Connected';
} else {
indicator.className = 'status-indicator status-critical';
text.textContent = 'Disconnected';
}
}
async function loadInitialData() {
try {
// Load current metrics
const metricsResponse = await fetch('/monitor/metrics');
const metrics = await metricsResponse.json();
updateMetrics(metrics.current);
// Load alerts
const alertsResponse = await fetch('/monitor/alerts');
const alerts = await alertsResponse.json();
displayAlerts(alerts);
} catch (error) {
console.error('Error loading initial data:', error);
}
}
function updateMetrics(metrics) {
const grid = document.getElementById('metricsGrid');
grid.innerHTML = `
<div class="metric-card">
<div class="metric-value cpu">${metrics.cpu_usage?.toFixed(1) || 0}%</div>
<div class="metric-label">CPU Usage</div>
</div>
<div class="metric-card">
<div class="metric-value memory">${metrics.memory_usage?.toFixed(1) || 0}%</div>
<div class="metric-label">Memory Usage</div>
</div>
<div class="metric-card">
<div class="metric-value disk">${metrics.disk_usage?.toFixed(1) || 0}%</div>
<div class="metric-label">Disk Usage</div>
</div>
<div class="metric-card">
<div class="metric-value network">${metrics.active_connections || 0}</div>
<div class="metric-label">Active Connections</div>
</div>
`;
metricsData.push(metrics);
if (metricsData.length > 20) {
metricsData = metricsData.slice(-20);
}
}
function updateCharts(metrics) {
if (!performanceChart) {
initPerformanceChart();
}
if (!apiChart) {
initApiChart();
}
// Update performance chart
const labels = metricsData.map((_, i) => i);
performanceChart.data.labels = labels;
performanceChart.data.datasets[0].data = metricsData.map(m => m.cpu_usage);
performanceChart.data.datasets[1].data = metricsData.map(m => m.memory_usage);
performanceChart.update();
// Update API chart
if (metrics.api_response_times) {
const endpoints = Object.keys(metrics.api_response_times);
const times = Object.values(metrics.api_response_times);
apiChart.data.labels = endpoints;
apiChart.data.datasets[0].data = times;
apiChart.update();
}
}
function initPerformanceChart() {
const ctx = document.getElementById('performanceChart').getContext('2d');
performanceChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'CPU Usage (%)',
data: [],
borderColor: '#667eea',
backgroundColor: 'rgba(102, 126, 234, 0.1)',
tension: 0.4
}, {
label: 'Memory Usage (%)',
data: [],
borderColor: '#28a745',
backgroundColor: 'rgba(40, 167, 69, 0.1)',
tension: 0.4
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true,
max: 100
}
}
}
});
}
function initApiChart() {
const ctx = document.getElementById('apiChart').getContext('2d');
apiChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: 'Response Time (ms)',
data: [],
backgroundColor: '#667eea'
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
function displayAlerts(alerts) {
const container = document.getElementById('alertsContainer');
if (alerts.length === 0) {
container.innerHTML = '<div class="loading">No active alerts</div>';
return;
}
container.innerHTML = alerts.map(alert => `
<div class="alert ${alert.severity}">
<div class="alert-header">
<span class="alert-type">${alert.type.replace('_', ' ').toUpperCase()}</span>
<span class="alert-severity severity-${alert.severity}">${alert.severity}</span>
</div>
<div class="alert-message">${alert.message}</div>
<div class="alert-timestamp">${new Date(alert.timestamp).toLocaleString()}</div>
<button class="resolve-btn" onclick="resolveAlert('${alert.id}')">Resolve</button>
</div>
`).join('');
}
function addAlert(alert) {
const container = document.getElementById('alertsContainer');
const alertHtml = `
<div class="alert ${alert.severity}">
<div class="alert-header">
<span class="alert-type">${alert.type.replace('_', ' ').toUpperCase()}</span>
<span class="alert-severity severity-${alert.severity}">${alert.severity}</span>
</div>
<div class="alert-message">${alert.message}</div>
<div class="alert-timestamp">${new Date(alert.timestamp).toLocaleString()}</div>
<button class="resolve-btn" onclick="resolveAlert('${alert.id}')">Resolve</button>
</div>
`;
container.insertAdjacentHTML('afterbegin', alertHtml);
}
async function resolveAlert(alertId) {
try {
const response = await fetch(`/monitor/alerts/${alertId}/resolve`, {
method: 'POST'
});
if (response.ok) {
// Remove alert from UI
const alertElement = document.querySelector(`[onclick="resolveAlert('${alertId}')"]`).closest('.alert');
alertElement.remove();
}
} catch (error) {
console.error('Error resolving alert:', error);
}
}
// Initialize dashboard
connectWebSocket();
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
uvicorn.run(monitor_app, host="127.0.0.1", port=8005) | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Performance Monitoring System for N8N Workflows
+Real-time metrics, monitoring, and alerting.
+"""
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
@@ -46,12 +50,14 @@ self.metrics_queue = queue.Queue()
def start_monitoring(self):
+ """Start performance monitoring in background thread."""
if not self.monitoring_active:
self.monitoring_active = True
monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
monitor_thread.start()
def _monitor_loop(self):
+ """Main monitoring loop."""
while self.monitoring_active:
try:
metrics = self._collect_metrics()
@@ -74,6 +80,7 @@ time.sleep(10)
def _collect_metrics(self) -> PerformanceMetrics:
+ """Collect current system metrics."""
# CPU and Memory
cpu_usage = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
@@ -130,24 +137,28 @@ )
def _measure_api_time(self, endpoint: str) -> float:
+ """Measure API response time (simulated)."""
# In a real implementation, this would make actual HTTP requests
import random
return round(random.uniform(10, 100), 2)
def _get_workflow_executions(self) -> int:
+ """Get number of workflow executions (simulated)."""
# In a real implementation, this would query execution logs
import random
return random.randint(0, 50)
def _calculate_error_rate(self) -> float:
+ """Calculate error rate (simulated)."""
# In a real implementation, this would analyze error logs
import random
return round(random.uniform(0, 5), 2)
def _check_alerts(self, metrics: PerformanceMetrics):
+ """Check metrics against alert thresholds."""
# CPU alert
if metrics.cpu_usage > 80:
self._create_alert(
@@ -182,6 +193,7 @@ )
def _create_alert(self, alert_type: str, severity: str, message: str):
+ """Create a new alert."""
alert = Alert(
id=f"{alert_type}_{int(time.time())}",
type=alert_type,
@@ -199,15 +211,18 @@ self._broadcast_alert(alert)
def _broadcast_metrics(self, metrics: PerformanceMetrics):
+ """Broadcast metrics to all websocket connections."""
if self.websocket_connections:
message = {"type": "metrics", "data": metrics.dict()}
self._broadcast_to_websockets(message)
def _broadcast_alert(self, alert: Alert):
+ """Broadcast alert to all websocket connections."""
message = {"type": "alert", "data": alert.dict()}
self._broadcast_to_websockets(message)
def _broadcast_to_websockets(self, message: dict):
+ """Broadcast message to all websocket connections."""
disconnected = []
for websocket in self.websocket_connections:
try:
@@ -220,6 +235,7 @@ self.websocket_connections.remove(ws)
def get_metrics_summary(self) -> Dict[str, Any]:
+ """Get performance metrics summary."""
if not self.metrics_history:
return {"message": "No metrics available"}
@@ -244,6 +260,7 @@ }
def get_historical_metrics(self, hours: int = 24) -> List[Dict]:
+ """Get historical metrics for specified hours."""
cutoff_time = datetime.now() - timedelta(hours=hours)
cutoff_timestamp = cutoff_time.isoformat()
@@ -254,6 +271,7 @@ ]
def resolve_alert(self, alert_id: str) -> bool:
+ """Resolve an alert."""
for alert in self.alerts:
if alert.id == alert_id:
alert.resolved = True
@@ -271,21 +289,25 @@
@monitor_app.get("/monitor/metrics")
async def get_current_metrics():
+ """Get current performance metrics."""
return performance_monitor.get_metrics_summary()
@monitor_app.get("/monitor/history")
async def get_historical_metrics(hours: int = 24):
+ """Get historical performance metrics."""
return performance_monitor.get_historical_metrics(hours)
@monitor_app.get("/monitor/alerts")
async def get_alerts():
+ """Get current alerts."""
return [alert.dict() for alert in performance_monitor.alerts if not alert.resolved]
@monitor_app.post("/monitor/alerts/{alert_id}/resolve")
async def resolve_alert(alert_id: str):
+ """Resolve an alert."""
success = performance_monitor.resolve_alert(alert_id)
if success:
return {"message": "Alert resolved"}
@@ -295,6 +317,7 @@
@monitor_app.websocket("/monitor/ws")
async def websocket_endpoint(websocket: WebSocket):
+ """WebSocket endpoint for real-time metrics."""
await websocket.accept()
performance_monitor.websocket_connections.append(websocket)
@@ -308,6 +331,7 @@
@monitor_app.get("/monitor/dashboard")
async def get_monitoring_dashboard():
+ """Get performance monitoring dashboard HTML."""
html_content = """
<!DOCTYPE html>
<html lang="en">
@@ -731,4 +755,4 @@ if __name__ == "__main__":
import uvicorn
- uvicorn.run(monitor_app, host="127.0.0.1", port=8005)+ uvicorn.run(monitor_app, host="127.0.0.1", port=8005)
| https://raw.githubusercontent.com/Zie619/n8n-workflows/HEAD/src/performance_monitor.py |
Add professional docstrings to my codebase | # Copyright 2024 X.AI Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
import logging
import re
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Sequence, Tuple, Union
import haiku as hk
import jax
import jax.experimental.maps
import jax.numpy as jnp
from jax import config, tree_util
from jax.experimental.shard_map import shard_map
from jax.lax import with_sharding_constraint as pjit_sharding_constraint
from jax.sharding import PartitionSpec
from jax.sharding import PartitionSpec as P
config.update("jax_spmd_mode", "allow_all")
logger = logging.getLogger(__name__)
rank_logger = logging.getLogger("rank")
@dataclass
class QuantizedWeight8bit:
weight: jnp.array
scales: jnp.array
@property
def shape(self):
return self.weight.shape
tree_util.register_pytree_node(
QuantizedWeight8bit,
lambda qw: ([qw.weight, qw.scales], ()),
lambda _, children: QuantizedWeight8bit(children[0], children[1]),
)
class TrainingState(NamedTuple):
params: hk.Params
def _match(qs, ks):
# compile regexes and force complete match
qts = tuple(map(lambda x: re.compile(x + "$"), qs))
for i in range(len(ks) - len(qs) + 1):
matches = [x.match(y) for x, y in zip(qts, ks[i:])]
if matches and all(matches):
return True
return False
def with_sharding_constraint(x, constraint):
if jax.experimental.maps.thread_resources.env.physical_mesh.empty:
return x
else:
return pjit_sharding_constraint(x, constraint)
def cast_bfloat16(x):
if x.dtype.kind == "f":
return x.astype(jnp.bfloat16)
else:
return x
def ffn_size(emb_size, widening_factor):
_ffn_size = int(widening_factor * emb_size) * 2 // 3
_ffn_size = _ffn_size + (8 - _ffn_size) % 8 # ensure it's a multiple of 8
logger.debug(f"emd_size: {emb_size} adjusted ffn_size: {_ffn_size}")
return _ffn_size
def apply_rules(rules):
def _apply_rules(path, value):
del value # Unused.
path_list = [str(i.key).split("/") for i in path if isinstance(i, jax.tree_util.DictKey)]
flattened_path = jax.tree_util.tree_flatten(path_list)[0]
for rule, replacement in rules:
if _match(rule, flattened_path):
if isinstance(replacement, PartitionSpec):
if "layer_stack" in flattened_path:
replacement = PartitionSpec(None, *replacement)
rank_logger.debug(f"Apply {replacement} to {flattened_path} with rule {rule}")
return replacement
rank_logger.info(f"{flattened_path} no matching found!")
return None
return _apply_rules
TRANSFORMER_PARTITION_RULES = [
# attention
(("multi_head_attention", "(query|key|value)", "w"), P("data", "model")),
(("multi_head_attention", "(query|key|value)", "b"), P(None)),
(("multi_head_attention", "linear", "w"), P("model", "data")),
(("multi_head_attention", "linear", "b"), P(None)),
# mlp
((r"decoder_layer_[0-9]+", "linear", "w"), P("data", "model")),
((r"decoder_layer_[0-9]+", "linear", "b"), P(None)),
((r"decoder_layer_[0-9]+", "linear_v", "w"), P("data", "model")),
((r"decoder_layer_[0-9]+", "linear_v", "b"), P(None)),
(
(r"decoder_layer_[0-9]+", "linear_1", "w"),
P(
"model",
"data",
),
),
((r"decoder_layer_[0-9]+", "linear_1", "b"), P(None)),
# layer norms
((r"decoder_layer_[0-9]+", "layer_norm", "offset"), P(None)),
((r"decoder_layer_[0-9]+", "layer_norm", "scale"), P(None)),
((r"decoder_layer_[0-9]+", "layer_norm_1", "offset"), P(None)),
((r"decoder_layer_[0-9]+", "layer_norm_1", "scale"), P(None)),
# rms norms
((r"decoder_layer_[0-9]+", "rms_norm", "scale"), P(None)),
((r"decoder_layer_[0-9]+", "rms_norm_1", "scale"), P(None)),
((r"decoder_layer_[0-9]+", "rms_norm_2", "scale"), P(None)),
((r"decoder_layer_[0-9]+", "rms_norm_3", "scale"), P(None)),
# router
(("router", "w"), P("data")),
# moe mlp
(("moe", "linear", "w"), P(None, "data", "model")),
(("moe", "linear", "b"), P(None)),
(("moe", "linear_v", "w"), P(None, "data", "model")),
(("moe", "linear_v", "b"), P(None)),
(("moe", "linear_1", "w"), P(None, "model", "data")),
(("moe", "linear_1", "b"), P(None)),
# layer norms
(("moe", "layer_norm", "offset"), P(None)),
(("moe", "layer_norm", "scale"), P(None)),
(("moe", "layer_norm_1", "offset"), P(None)),
(("moe", "layer_norm_1", "scale"), P(None)),
# rms norms
(("moe", "rms_norm", "scale"), P(None)),
(("moe", "rms_norm_1", "scale"), P(None)),
(("moe", "rms_norm_2", "scale"), P(None)),
(("moe", "rms_norm_3", "scale"), P(None)),
]
LM_PARTITION_RULES = [
# Embedding layer.
(
("language_model", "positional_embeddings"),
P(None, ("data", "model")),
),
(
("language_model", "in_out_embed", "embeddings"),
P(None, ("data", "model")),
),
# Final RMSNorm.
(("language_model", "rms_norm"), P(None)),
]
TOP_K = 8
class KVMemory(NamedTuple):
k: Optional[jax.Array]
v: Optional[jax.Array]
step: Optional[jax.Array]
def init_layer_memories(
batch_size: int,
sequence_len: int,
num_kv_heads: int,
key_size: int,
num_layers: int,
step: Optional[jax.Array] = None,
dtype=jnp.bfloat16,
):
return [
KVMemory(
k=jnp.zeros((batch_size, sequence_len, num_kv_heads, key_size), dtype=dtype),
v=jnp.zeros((batch_size, sequence_len, num_kv_heads, key_size), dtype=dtype),
step=step,
)
for _ in range(num_layers)
]
class Memory(NamedTuple):
# Self-attention key/value cache.
layers: List[KVMemory]
class Router(hk.Module):
def __init__(
self,
num_selected_experts: int,
data_axis: Union[str, Tuple[str, ...]] = "data",
model_axis: Union[str, Tuple[str, ...]] = "model",
shard_activations: bool = False,
mesh: Any = None,
name: str = "router",
):
super().__init__(name)
self.shard_activations = shard_activations
self.data_axis = data_axis
self.model_axis = model_axis
self.mesh = mesh
self.num_selected_experts = num_selected_experts
def compute_routing_prob(
self, inputs: jax.Array, padding_mask: Optional[jax.Array], num_experts: int
):
return self._compute_routing_prob(inputs, padding_mask, num_experts)
@hk.transparent
def _compute_routing_prob(
self,
inputs: jax.Array,
padding_mask: Optional[jax.Array],
num_experts: int,
):
# Using fp32 for the routing prob computation.
inputs = jax.lax.convert_element_type(inputs, jnp.float32)
# [batch_size, seq_len, num_experts]
routing_logits = self._router_weights(inputs, num_experts, sharding=P("data"))
assert routing_logits.dtype == jnp.float32
routing_probs = jax.nn.softmax(routing_logits)
if padding_mask is not None:
routing_probs *= padding_mask
return routing_probs, routing_logits, 0
@hk.transparent
def _router_weights(
self,
x: jax.Array,
num_experts: int,
sharding: Optional[P] = None,
):
fprop_dtype = x.dtype
if not x.shape:
raise ValueError("Input must not be scalar.")
input_size = self.input_size = x.shape[-1]
w = hk.get_parameter(
"w", [input_size, num_experts], jnp.float32, init=hk.initializers.Constant(0)
)
if sharding:
w = with_sharding_constraint(w, sharding)
out = jnp.dot(x, w.astype(fprop_dtype))
return out
class MoELayer(hk.Module):
def __init__(
self,
num_experts: int,
layer_fn: Callable,
router: Router,
mesh: Any = None,
shard_activations: bool = False,
data_axis: Union[str, Tuple[str, ...]] = "data",
model_axis: Union[str, Tuple[str, ...]] = "model",
name: Optional[str] = "moe",
):
super().__init__(name)
self.num_experts = num_experts
self.layer_fn = layer_fn
self.router = router
self.mesh = mesh
self.shard_activations = shard_activations
self.data_axis = data_axis
self.model_axis = model_axis
@hk.transparent
def _inference_call(self, inputs: jax.Array, padding_mask: Optional[jax.Array] = None):
routing_probs, _, _ = self.router.compute_routing_prob(
inputs, padding_mask, self.num_experts
)
expert_gate, expert_index = jax.lax.top_k(routing_probs, k=self.router.num_selected_experts)
tmp = jnp.reshape(inputs, (inputs.shape[0] * inputs.shape[1], inputs.shape[2]))
broad_inputs = jnp.tile(tmp[:, jnp.newaxis, :], (1, self.router.num_selected_experts, 1))
broad_inputs = jnp.reshape(
broad_inputs, (broad_inputs.shape[0] * broad_inputs.shape[1], broad_inputs.shape[2])
)
init_fn, _ = hk.transform(self.layer_fn)
vmapped_init_fn = jax.vmap(init_fn, in_axes=0, out_axes=0)
lifted_init_fn = hk.experimental.transparent_lift(vmapped_init_fn)
# Fetch the vmapped params of the DenseBlock.
params = lifted_init_fn(
jax.random.split(jax.random.PRNGKey(1), self.num_experts),
jnp.zeros((self.num_experts, 1, 1, inputs.shape[-1])),
)
# Index and prob are in the shape [m, 2] indicating which token assigned to which experts.
# b: num_expert
# m: token or sequence dim
# k: input embed dim
# n: output embed dim
# e: the number of experts chosen for each token
@functools.partial(
shard_map,
mesh=self.mesh,
in_specs=(
P(self.data_axis, None),
P(None, None, self.model_axis),
P(None, None, self.model_axis),
P(None),
P(None),
),
out_specs=P(self.data_axis, self.model_axis),
check_rep=False,
)
def moe_slow_matmul1(input, weight, scales, index, prob):
weight = weight * scales
one_hot_indices = jax.nn.one_hot(index.reshape(-1), 8, axis=0)
all_expert_output = jnp.einsum("mk,bkn->bmn", input, weight)
output = jnp.einsum("bm,bmn->mn", one_hot_indices, all_expert_output)
return output
@functools.partial(
shard_map,
mesh=self.mesh,
in_specs=(
P(self.data_axis, self.model_axis),
P(None, self.model_axis, None),
P(None, self.model_axis, None),
P(None),
P(None),
),
out_specs=P(self.data_axis, None),
check_rep=False,
)
def moe_slow_matmul2(input, weight, scales, index, prob):
weight = weight * scales
one_hot_indices = jax.nn.one_hot(index.reshape(-1), 8, axis=0)
all_expert_output = jnp.einsum("mk,bkn->bmn", input, weight)
output = jnp.einsum("bm,bmn->mn", one_hot_indices, all_expert_output)
return jax.lax.psum(output, axis_name="model")
if hasattr(params["linear"]["w"], "scales"):
x = moe_slow_matmul1(
broad_inputs,
params["linear_v"]["w"].weight,
params["linear_v"]["w"].scales,
expert_index,
expert_gate,
)
y = moe_slow_matmul1(
broad_inputs,
params["linear"]["w"].weight,
params["linear"]["w"].scales,
expert_index,
expert_gate,
)
y = jax.nn.gelu(y)
out = moe_slow_matmul2(
x * y,
params["linear_1"]["w"].weight,
params["linear_1"]["w"].scales,
expert_index,
expert_gate,
)
out = jnp.reshape(
out,
[
inputs.shape[0],
inputs.shape[1],
self.router.num_selected_experts,
out.shape[-1],
],
)
out = expert_gate[:, :, :, None].astype(jnp.bfloat16) * out
out = jnp.sum(out, axis=2)
out = out.astype(jnp.bfloat16)
else:
# This is only here so that we can construct a valid init_fn with this code.
return inputs
return out
def __call__(self, inputs: jax.Array, padding_mask: jax.Array):
return self._inference_call(inputs)
class MHAOutput(NamedTuple):
embeddings: jax.Array
memory: Any
class DecoderOutput(NamedTuple):
embeddings: jax.Array
memory: Any
class TransformerOutput(NamedTuple):
embeddings: jax.Array
memory: Any
@dataclass
class TransformerConfig:
emb_size: int
key_size: int
num_q_heads: int
num_kv_heads: int
num_layers: int
vocab_size: int = 128 * 1024
widening_factor: float = 4.0
attn_output_multiplier: float = 1.0
name: Optional[str] = None
num_experts: int = -1
capacity_factor: float = 1.0
num_selected_experts: int = 1
init_scale: float = 1.0
shard_activations: bool = False
# Used for activation sharding.
data_axis: Union[str, Tuple[str, ...]] = "data"
model_axis: Union[str, Tuple[str, ...]] = "model"
def __post_init__(self):
if isinstance(self.data_axis, list):
self.data_axis = tuple(self.data_axis)
if isinstance(self.model_axis, list):
self.model_axis = tuple(self.model_axis)
def partition_rules(self):
return TRANSFORMER_PARTITION_RULES
def make(self, mesh=None) -> "Transformer":
data_axis = tuple(self.data_axis) if isinstance(self.data_axis, list) else self.data_axis
model_axis = (
tuple(self.model_axis) if isinstance(self.model_axis, list) else self.model_axis
)
return Transformer(
num_q_heads=self.num_q_heads,
num_kv_heads=self.num_kv_heads,
widening_factor=self.widening_factor,
key_size=self.key_size,
init_scale=self.init_scale,
mesh=mesh,
attn_output_multiplier=self.attn_output_multiplier,
shard_activations=self.shard_activations,
num_layers=self.num_layers,
num_experts=self.num_experts,
num_selected_experts=self.num_selected_experts,
data_axis=data_axis,
model_axis=model_axis,
)
def get_memory_sharding(self):
return Memory(
layers=[
KVMemory(
k=P(self.data_axis, self.model_axis),
v=P(self.data_axis, self.model_axis),
step=P(self.data_axis),
)
for _ in range(self.num_layers)
],
)
def hk_rms_norm(
x: jax.Array,
fixed_scale=False,
sharding=P(None),
) -> jax.Array:
ln = RMSNorm(axis=-1, create_scale=not fixed_scale, sharding=sharding)
return ln(x)
def make_attention_mask(
query_input: jax.Array,
key_input: jax.Array,
pairwise_fn: Callable[..., Any] = jnp.multiply,
dtype: Any = jnp.bfloat16,
):
mask = pairwise_fn(jnp.expand_dims(query_input, axis=-1), jnp.expand_dims(key_input, axis=-2))
mask = jnp.expand_dims(mask, axis=-3)
return mask.astype(dtype)
class Linear(hk.Linear):
def __init__(
self,
output_size: int,
with_bias: bool = True,
sharding: Optional[P] = None,
mesh: Any = None,
name: Optional[str] = None,
shard_axis: int = 0,
):
super().__init__(
output_size=output_size,
with_bias=with_bias,
name=name,
)
self.sharding = sharding
self.mesh = mesh
self.shard_axis = shard_axis
def __call__(
self,
inputs: jax.Array,
) -> jax.Array:
fprop_dtype = inputs.dtype
if not inputs.shape:
raise ValueError("Input must not be scalar.")
input_size = self.input_size = inputs.shape[-1]
output_size = self.output_size
w = hk.get_parameter(
"w", [input_size, output_size], jnp.float32, init=hk.initializers.Constant(0)
)
if hasattr(w, "scales"):
shape = inputs.shape
inputs = jnp.reshape(inputs, (-1, shape[-1]))
@functools.partial(
shard_map,
mesh=self.mesh,
in_specs=(self.sharding, self.sharding),
out_specs=self.sharding,
check_rep=False,
)
def mul(w, s):
return w.astype(s.dtype) * s
w = mul(w.weight, w.scales)
out = jnp.dot(inputs, w.astype(fprop_dtype))
if self.with_bias:
b = hk.get_parameter(
"b", [self.output_size], jnp.float32, init=hk.initializers.Constant(0)
)
b = jnp.broadcast_to(b, out.shape)
out = out + b.astype(fprop_dtype)
return out
class RMSNorm(hk.RMSNorm):
def __init__(
self,
axis: Union[int, Sequence[int], slice],
eps: float = 1e-5,
name: Optional[str] = None,
create_scale: bool = True,
sharding: Optional[P] = None,
):
super().__init__(axis, eps, create_scale=create_scale, name=name)
self.sharding = sharding
def __call__(self, inputs: jax.Array):
fprop_dtype = inputs.dtype
param_shape = (inputs.shape[-1],)
if self.create_scale:
scale = hk.get_parameter(
"scale",
param_shape,
dtype=jnp.float32,
init=hk.initializers.Constant(0),
)
if self.sharding:
scale = with_sharding_constraint(scale, self.sharding)
scale = jnp.broadcast_to(scale.astype(jnp.float32), inputs.shape)
else:
scale = 1.0
inputs = inputs.astype(jnp.float32)
scale = scale.astype(jnp.float32)
mean_squared = jnp.mean(jnp.square(inputs), axis=[-1], keepdims=True)
mean_squared = jnp.broadcast_to(mean_squared, inputs.shape)
normed_inputs = inputs * jax.lax.rsqrt(mean_squared + self.eps)
outputs = scale * normed_inputs
return outputs.astype(fprop_dtype)
def rotate_half(
x: jax.Array,
) -> jax.Array:
x1, x2 = jnp.split(x, 2, axis=-1)
return jnp.concatenate((-x2, x1), axis=-1)
class RotaryEmbedding(hk.Module):
def __init__(
self,
dim: int,
name: Optional[str] = None,
base_exponent: int = 10000,
):
super().__init__(name)
self.dim = dim
self.base_exponent = base_exponent
assert self.dim % 2 == 0
def __call__(
self,
x: jax.Array,
seq_dim: int,
offset: jax.Array,
const_position: Optional[int] = None,
t: Optional[jax.Array] = None,
) -> jax.Array:
fprop_dtype = x.dtype
# Compute the per-dimension frequencies
exponents = jnp.arange(0, self.dim, 2, dtype=jnp.float32)
inv_freq = jnp.asarray(
1.0 / (self.base_exponent ** (exponents / self.dim)), dtype=jnp.float32
)
if jnp.shape(offset) == ():
# Offset can be a scalar or one offset per batch element.
offset = jnp.expand_dims(offset, 0)
# Compute the per element phase (to pass into sin and cos)
if const_position:
t = const_position * jnp.ones(
(
1,
x.shape[seq_dim],
),
dtype=jnp.float32,
)
elif t is None:
t = jnp.arange(x.shape[seq_dim], dtype=jnp.float32) + jnp.expand_dims(offset, -1)
phase = jnp.einsum("bi,j->bij", t, inv_freq)
phase = jnp.tile(phase, reps=(1, 2))[:, :, None, :]
x = x * jnp.cos(phase) + rotate_half(x) * jnp.sin(phase)
x = x.astype(fprop_dtype)
return x
class MultiHeadAttention(hk.Module):
def __init__(
self,
num_q_heads: int,
num_kv_heads: int,
key_size: int,
*,
with_bias: bool = True,
value_size: Optional[int] = None,
model_size: Optional[int] = None,
attn_output_multiplier: 1.0,
data_axis: Union[str, Tuple[str, ...]] = "data",
model_axis: Union[str, Tuple[str, ...]] = "model",
name: Optional[str] = None,
):
super().__init__(name=name)
self.num_q_heads = num_q_heads
self.num_kv_heads = num_kv_heads
self.key_size = key_size
self.value_size = value_size or key_size
self.model_size = model_size or key_size * num_q_heads
self.data_axis = data_axis
self.model_axis = model_axis
self.attn_output_multiplier = attn_output_multiplier
self.with_bias = with_bias
def __call__(
self,
query: jax.Array,
key: Optional[jax.Array],
value: Optional[jax.Array],
mask: Optional[jax.Array] = None,
kv_memory: Optional[KVMemory] = None,
mesh: Any = None,
) -> MHAOutput:
# In shape hints below, we suppress the leading dims [...] for brevity.
# Hence e.g. [A, B] should be read in every case as [..., A, B].
sequence_length = query.shape[1]
projection = self._linear_projection
use_memory = False
if kv_memory is not None:
if kv_memory.k is None:
assert kv_memory.v is None
assert key is not None
assert value is not None
else:
assert kv_memory.v is not None
use_memory = True
else:
assert key is not None
assert value is not None
# Check that the keys and values have consistent batch size and sequence length.
if not use_memory:
assert key.shape[:2] == value.shape[:2], f"key/value shape: {key.shape}/{value.shape}"
if mask is not None:
assert mask.ndim == 4
assert mask.shape[0] in {
1,
query.shape[0],
}, f"mask/query shape: {mask.shape}/{query.shape}"
if not use_memory:
assert key.shape[0] in {
1,
query.shape[0],
}, f"key/query shape: {key.shape}/{query.shape}"
assert mask.shape[1] == 1
assert mask.shape[2] in {
1,
query.shape[1],
}, f"mask/query shape: {mask.shape}/{query.shape}"
if not use_memory:
assert mask.shape[3] in {
1,
key.shape[1],
}, f"mask/query shape: {mask.shape}/{key.shape}"
# Compute key/query/values (overload K/Q/V to denote the respective sizes).
assert self.num_q_heads % self.num_kv_heads == 0
query_heads = projection(
query,
self.key_size,
self.num_q_heads,
name="query",
sharding=P("data", "model"),
mesh=mesh,
) # [B, T', H, Q=K]
new_memory = None
key_heads = projection(
key,
self.key_size,
self.num_kv_heads,
name="key",
sharding=P("data", "model"),
mesh=mesh,
) # [B, T, H, K]
value_heads = projection(
value,
self.value_size,
self.num_kv_heads,
name="value",
sharding=P("data", "model"),
mesh=mesh,
) # [B, T, H, V]
rotate = RotaryEmbedding(dim=self.key_size, base_exponent=int(1e4))
key_heads = rotate(key_heads, seq_dim=1, offset=(kv_memory.step if kv_memory else 0))
query_heads = rotate(query_heads, seq_dim=1, offset=(kv_memory.step if kv_memory else 0))
@functools.partial(jax.vmap)
def update_into(mem, start, update):
return jax.lax.dynamic_update_slice_in_dim(mem, update, start, axis=0)
if kv_memory:
if mesh is not None:
@functools.partial(
shard_map,
mesh=mesh,
in_specs=(
P("data", None, "model"),
P("data"),
P("data", None, "model"),
),
out_specs=P("data", None, "model"),
check_rep=False,
)
def update_into_shmap(mems, starts, updates):
return update_into(mems, starts, updates)
key_heads = update_into_shmap(kv_memory.k, kv_memory.step, key_heads)
value_heads = update_into_shmap(kv_memory.v, kv_memory.step, value_heads)
else:
key_heads = update_into(kv_memory.k, kv_memory.step, key_heads)
value_heads = update_into(kv_memory.v, kv_memory.step, value_heads)
new_step = kv_memory.step + sequence_length
memory_mask = jnp.arange(kv_memory.k.shape[1]) < new_step[:, None]
memory_mask = memory_mask[:, None, None, :] # [B, H, T, T]
if mask is not None:
mask = memory_mask * mask
else:
mask = memory_mask
new_memory = KVMemory(
k=key_heads,
v=value_heads,
step=new_step,
)
# Add separate dimension for grouped query heads.
query_heads = with_sharding_constraint(query_heads, P(self.data_axis, None, "model", None))
key_heads = with_sharding_constraint(key_heads, P(self.data_axis, None, "model", None))
value_heads = with_sharding_constraint(value_heads, P(self.data_axis, None, "model", None))
b, t, h, d = query_heads.shape
_, _, kv_h, _ = key_heads.shape
assert h % kv_h == 0, f"query_heads {h} must be a multiple of kv_heads {kv_h}"
query_heads = jnp.reshape(query_heads, (b, t, kv_h, h // kv_h, d))
query_heads = with_sharding_constraint(
query_heads, P(self.data_axis, None, "model", None, None)
)
# Compute attention weights.
# Attention softmax is always carried out in fp32.
attn_logits = jnp.einsum("...thHd,...Thd->...hHtT", query_heads, key_heads).astype(
jnp.float32
)
attn_logits *= self.attn_output_multiplier
max_attn_val = jnp.array(30.0, dtype=attn_logits.dtype)
attn_logits = max_attn_val * jnp.tanh(attn_logits / max_attn_val)
mask = mask[:, :, None, :, :]
if mask is not None:
if mask.ndim != attn_logits.ndim:
raise ValueError(
f"Mask dimensionality {mask.ndim} must match logits dimensionality "
f"{attn_logits.ndim} for {mask.shape}/{attn_logits.shape}."
)
attn_logits = jnp.where(mask, attn_logits, -1e30)
attn_weights = jax.nn.softmax(attn_logits).astype(query.dtype) # [H, T', T]
# Weight the values by the attention and flatten the head vectors.
attn = jnp.einsum("...hHtT,...Thd->...thHd", attn_weights, value_heads)
attn = with_sharding_constraint(attn, P(self.data_axis, None, "model", None, None))
leading_dims = attn.shape[:2]
attn = jnp.reshape(attn, (*leading_dims, -1)) # [T', H*V]
attn = with_sharding_constraint(attn, P(self.data_axis, None, "model"))
# Apply another projection to get the final embeddings.
final_projection = Linear(
self.model_size,
with_bias=False,
sharding=P("model", "data"),
mesh=mesh,
)
return MHAOutput(final_projection(attn), new_memory)
@hk.transparent
def _linear_projection(
self,
x: jax.Array,
head_size: int,
num_heads: int,
sharding: Optional[P] = None,
name: Optional[str] = None,
mesh: Any = None,
) -> jax.Array:
y = Linear(
num_heads * head_size,
with_bias=False,
name=name,
sharding=sharding,
mesh=mesh,
)(x)
*leading_dims, _ = x.shape
return y.reshape((*leading_dims, num_heads, head_size))
@dataclass
class MHABlock(hk.Module):
num_q_heads: int
num_kv_heads: int
key_size: int
attn_output_multiplier: float = 1.0
mesh: Any = None
data_axis: Union[str, Tuple[str, ...]] = "data"
model_axis: Union[str, Tuple[str, ...]] = "model"
@hk.transparent
def __call__(
self,
inputs: jax.Array, # [B, T, D]
mask: jax.Array, # [B, 1, T, T] or [B, 1, 1, T] or B[1, 1, 1, 1]
layer_memory: Optional[KVMemory],
) -> MHAOutput:
_, _, model_size = inputs.shape
assert mask.ndim == 4, f"shape: {mask.shape}"
assert mask.shape[2] in {1, inputs.shape[1]}, str(mask.shape)
assert mask.shape[3] in {1, inputs.shape[1]}, str(mask.shape)
side_input = inputs
def attn_block(query, key, value, mask, memory) -> MHAOutput:
return MultiHeadAttention(
num_q_heads=self.num_q_heads,
num_kv_heads=self.num_kv_heads,
key_size=self.key_size,
model_size=model_size,
data_axis=self.data_axis,
model_axis=self.model_axis,
attn_output_multiplier=self.attn_output_multiplier,
)(
query,
key,
value,
mask,
memory,
mesh=self.mesh,
)
attn_output = attn_block(inputs, side_input, side_input, mask, layer_memory)
h_attn = attn_output.embeddings
return attn_output._replace(embeddings=h_attn)
@dataclass
class DenseBlock(hk.Module):
num_q_heads: int
num_kv_heads: int
key_size: int
widening_factor: float = 4.0
sharding_constraint: bool = False
mesh: Any = None
@hk.transparent
def __call__(
self,
inputs: jax.Array, # [B, T, D]
) -> jax.Array: # [B, T, D]
_, _, model_size = inputs.shape
h_v = Linear(
ffn_size(
model_size,
self.widening_factor,
),
with_bias=False,
mesh=self.mesh,
sharding=P("data", "model"),
name="linear_v",
)(inputs)
h_w1 = jax.nn.gelu(
Linear(
ffn_size(
model_size,
self.widening_factor,
),
with_bias=False,
mesh=self.mesh,
sharding=P("data", "model"),
)(inputs)
)
h_dense = Linear(
model_size,
with_bias=False,
sharding=P("model", "data"),
mesh=self.mesh,
shard_axis=1,
)(h_w1 * h_v)
return h_dense
@dataclass
class DecoderLayer(hk.Module):
num_q_heads: int
num_kv_heads: int
key_size: int
num_layers: int
# MoE.
num_experts: int
layer_index: Optional[int] = None
num_selected_experts: int = 1
widening_factor: float = 4.0
name: Optional[str] = None
data_axis: Union[str, Tuple[str, ...]] = "data"
model_axis: Union[str, Tuple[str, ...]] = "model"
shard_activations: bool = False
attn_output_multiplier: float = 1.0
mesh: Any = None
def __call__(
self,
inputs: jax.Array, # [B, T, D]
mask: jax.Array, # [B, 1, T, T] or [B, 1, 1, T]
padding_mask: Optional[jax.Array],
layer_memory: Optional[KVMemory],
) -> DecoderOutput:
def layer_norm(x):
return hk_rms_norm(x)
if self.shard_activations:
sharding = P(self.data_axis, None, self.model_axis)
else:
sharding = P(self.data_axis, None)
h = with_sharding_constraint(inputs, sharding)
attn_output = MHABlock(
num_q_heads=self.num_q_heads,
num_kv_heads=self.num_kv_heads,
key_size=self.key_size,
attn_output_multiplier=self.attn_output_multiplier,
mesh=self.mesh,
data_axis=self.data_axis,
model_axis=self.model_axis,
)(layer_norm(h), mask, layer_memory)
h_attn = attn_output.embeddings
h_attn = layer_norm(h_attn)
h += h_attn
h = with_sharding_constraint(h, sharding)
def base_dense_block(h):
h = DenseBlock(
num_q_heads=self.num_q_heads,
num_kv_heads=self.num_kv_heads,
key_size=self.key_size,
widening_factor=self.widening_factor,
sharding_constraint=False,
mesh=self.mesh,
)(h)
return h
if self.num_experts > 1:
rank_logger.debug("Using MoE!")
router = Router(
num_selected_experts=self.num_selected_experts,
shard_activations=self.shard_activations,
data_axis=self.data_axis,
model_axis=self.model_axis,
mesh=self.mesh,
)
h_dense = MoELayer(
num_experts=self.num_experts,
mesh=self.mesh,
layer_fn=base_dense_block,
router=router,
shard_activations=self.shard_activations,
data_axis=self.data_axis,
model_axis=self.model_axis,
)(layer_norm(h), padding_mask)
else:
h_dense = base_dense_block(layer_norm(h))
h_dense = layer_norm(h_dense)
h += h_dense
h = with_sharding_constraint(h, sharding)
return DecoderOutput(
embeddings=h,
memory=attn_output.memory,
)
class LanguageModelOutput(NamedTuple):
logits: jax.Array
model_state: Any
class InOutEmbed(hk.Embed):
def __init__(
self,
vocab_size: Optional[int] = None,
embed_dim: Optional[int] = None,
sharding: Optional[P] = None,
name: Optional[str] = None,
):
super().__init__(
vocab_size=vocab_size,
embed_dim=embed_dim,
name=name,
)
self.sharding = sharding
@property
def embeddings(self):
embed_mat = hk.get_parameter(
"embeddings",
[self.vocab_size, self.embed_dim],
dtype=jnp.float32,
init=hk.initializers.Constant(0),
)
if self.sharding:
embed_mat = with_sharding_constraint(embed_mat, self.sharding)
return embed_mat
def decode(
self,
inputs: jax.Array,
) -> jax.Array:
return jnp.dot(inputs, self.embeddings.T.astype(inputs.dtype))
@dataclass
class LanguageModelConfig:
model: Optional[TransformerConfig]
vocab_size: int
pad_token: int
eos_token: int
sequence_len: int
model_size: int = 0
embedding_init_scale: float = 1.0
embedding_multiplier_scale: float = 1.0
output_multiplier_scale: float = 1.0
name: Optional[str] = None
fprop_dtype: Any = jnp.bfloat16
model_type: Optional[str] = None
init_scale_override: Optional[float] = None
shard_embeddings: bool = True
_initialized = False
def initialize(self):
# We cannot specify [] as a default value (it is mutable), hence None.
model_config = self.model
assert self.init_scale_override is None, (
"Overriding model initialize scale is supported only for predefined models."
)
if self.model_size == 0:
self.model_size = model_config.emb_size
assert self.model is not None, "Model could not be initialized."
self._initialized = True
return self
def make(self, *args, **kwargs):
if not self._initialized:
logger.warning(
f"LanguageModel {self.name} is not initialized. Initializing for one replica."
)
self.initialize()
return LanguageModel(
model=self.model.make(*args, **kwargs),
config=self,
fprop_dtype=self.fprop_dtype,
mesh=kwargs.get("mesh", None),
)
def partition_rules(self):
return LM_PARTITION_RULES + self.model.partition_rules()
def layer_norm(x, model):
return hk_rms_norm(x)
@dataclass
class LanguageModel(hk.Module):
model: "Transformer"
config: LanguageModelConfig
fprop_dtype: Any = jnp.bfloat16
name: Optional[str] = None
mesh: Any = None
def __call__(
self,
tokens: jax.Array,
memory: Optional[Memory] = None,
*,
batch: Dict[str, jax.Array] = {},
last_hid_only: bool = False,
length: Optional[jax.Array] = None,
) -> LanguageModelOutput:
del batch # Unused.
config = self.config
input_mask = jnp.greater(tokens, config.pad_token)
# Embed the input tokens and positions.
in_out_embed = InOutEmbed(
self.config.vocab_size,
embed_dim=self.config.model_size,
sharding=P(None, ("data", "model")),
)
input_embeddings = in_out_embed(tokens).astype(config.fprop_dtype)
input_embeddings = with_sharding_constraint(
input_embeddings, P("data", None, self.model.model_axis)
)
input_embeddings *= config.embedding_multiplier_scale
model_output = self.model(
input_embeddings,
input_mask,
memory=memory,
) # [B, T, D]
embeddings, model_state = model_output.embeddings, model_output.memory
if self.model.shard_activations:
embeddings = with_sharding_constraint(
embeddings, P("data", None, self.model.model_axis)
)
else:
embeddings = with_sharding_constraint(embeddings, P("data", None))
rank_logger.debug(f"Final embedding shape: {embeddings.shape}")
embeddings = layer_norm(embeddings, self.model)
assert embeddings.dtype == self.fprop_dtype
if last_hid_only:
last_step = jnp.maximum(jnp.sum(input_mask.astype(jnp.int32), axis=1) - 1, 0)
last_hid = jax.vmap(lambda x, i: x[i], in_axes=0, out_axes=0)(embeddings, last_step)
return last_hid
if length is not None:
last_step = jnp.maximum(length.astype(jnp.int32) - 1, 0)
embeddings = jax.vmap(lambda x, i: x[i], in_axes=0, out_axes=0)(embeddings, last_step)
embeddings = jnp.expand_dims(embeddings, axis=1)
# Decode the embeddings (here, we use tied weights).
rank_logger.info(embeddings.shape)
out = in_out_embed.decode(embeddings)
rank_logger.info(out.shape)
out *= config.output_multiplier_scale
if self.model.shard_activations:
out = with_sharding_constraint(out, P("data", None, self.model.model_axis))
else:
out = with_sharding_constraint(out, P("data", None))
return LanguageModelOutput(
logits=out,
model_state=model_state,
)
def init_memory(self, batch_size: int, seq_len: int, dtype=jnp.bfloat16):
return self.model.init_memory(batch_size=batch_size, sequence_len=seq_len, dtype=dtype)
def prefill_memory(self, prompts, memory):
# Pad to the left and right align?
# Basically assume prompt is already padded
model_output = self(prompts, memory=memory)
return model_output.logits, model_output.model_state
@dataclass
class Transformer(hk.Module):
num_q_heads: int
num_kv_heads: int
key_size: int
widening_factor: float
init_scale: float
mesh: Any
attn_output_multiplier: float
shard_activations: bool
num_layers: int
# MoE
num_experts: int
num_selected_experts: int
name: Optional[str] = None
# Used for activation sharding
data_axis: Union[str, Tuple[str, ...]] = "data"
model_axis: Union[str, Tuple[str, ...]] = "model"
def init_memory(self, batch_size: int, sequence_len: int, dtype=jnp.bfloat16):
return Memory(
layers=init_layer_memories(
batch_size,
sequence_len,
self.num_kv_heads,
self.key_size,
self.num_layers,
step=jnp.zeros(batch_size, dtype=jnp.int32),
dtype=dtype,
),
)
def __call__(
self,
embeddings: jax.Array, # [B, T, D]
mask: jax.Array, # [B, T]
memory: Optional[Memory],
) -> TransformerOutput:
fprop_dtype = embeddings.dtype
_, seq_len, model_size = embeddings.shape
padding_mask = mask.copy()
mask = mask[:, None, None, :] # [B, H=1, T'=1, T]
# Compute causal mask for autoregressive sequence modelling.
causal_mask = jnp.tril(jnp.ones((1, 1, seq_len, seq_len))).astype(
fprop_dtype
) # [B=1, H=1, T, T]
mask = mask * causal_mask # [B, H=1, T, T]
h = embeddings
kv_memories = []
def block(
h,
mask,
padding_mask,
memory,
layer_index: Optional[int] = None,
widening_factor: Optional[int] = None,
name: Optional[str] = None,
) -> DecoderOutput:
return DecoderLayer(
num_q_heads=self.num_q_heads,
num_kv_heads=self.num_kv_heads,
key_size=self.key_size,
widening_factor=widening_factor or self.widening_factor,
num_layers=self.num_layers,
mesh=self.mesh,
data_axis=self.data_axis,
model_axis=self.model_axis,
attn_output_multiplier=self.attn_output_multiplier,
shard_activations=self.shard_activations,
# MoE.
num_experts=self.num_experts,
num_selected_experts=self.num_selected_experts,
name=name,
layer_index=layer_index,
)(
h,
mask,
padding_mask,
memory,
)
for i in range(self.num_layers):
decoder_output = block(
h,
mask,
padding_mask,
memory.layers[i] if memory else None,
layer_index=i,
name=f"decoder_layer_{i}",
)
h, new_kv_memory = (
decoder_output.embeddings,
decoder_output.memory,
)
kv_memories.append(new_kv_memory)
return TransformerOutput(
embeddings=h,
memory=Memory(layers=kv_memories),
) | --- +++ @@ -52,11 +52,13 @@
class TrainingState(NamedTuple):
+ """Container for the training state."""
params: hk.Params
def _match(qs, ks):
+ """Return True if regexes in qs match any window of strings in tuple ks."""
# compile regexes and force complete match
qts = tuple(map(lambda x: re.compile(x + "$"), qs))
for i in range(len(ks) - len(qs) + 1):
@@ -399,6 +401,7 @@
class MHAOutput(NamedTuple):
+ """Outputs of the multi-head attention operation."""
embeddings: jax.Array
memory: Any
@@ -488,6 +491,7 @@ fixed_scale=False,
sharding=P(None),
) -> jax.Array:
+ """Applies a unique LayerNorm to x with default settings."""
ln = RMSNorm(axis=-1, create_scale=not fixed_scale, sharding=sharding)
return ln(x)
@@ -498,6 +502,21 @@ pairwise_fn: Callable[..., Any] = jnp.multiply,
dtype: Any = jnp.bfloat16,
):
+ """Mask-making helper for attention weights.
+
+ In case of 1d inputs (i.e., `[batch..., len_q]`, `[batch..., len_kv]`, the
+ attention weights will be `[batch..., heads, len_q, len_kv]` and this
+ function will produce `[batch..., 1, len_q, len_kv]`.
+
+ Args:
+ query_input: a batched, flat input of query_length size
+ key_input: a batched, flat input of key_length size
+ pairwise_fn: broadcasting elementwise comparison function
+ dtype: mask return dtype
+
+ Returns:
+ A `[batch..., 1, len_q, len_kv]` shaped mask for 1d attention.
+ """
mask = pairwise_fn(jnp.expand_dims(query_input, axis=-1), jnp.expand_dims(key_input, axis=-2))
mask = jnp.expand_dims(mask, axis=-3)
return mask.astype(dtype)
@@ -526,6 +545,7 @@ self,
inputs: jax.Array,
) -> jax.Array:
+ """Computes a linear transform of the input."""
fprop_dtype = inputs.dtype
if not inputs.shape:
@@ -607,11 +627,19 @@ def rotate_half(
x: jax.Array,
) -> jax.Array:
+ """Obtain the rotated counterpart of each feature"""
x1, x2 = jnp.split(x, 2, axis=-1)
return jnp.concatenate((-x2, x1), axis=-1)
class RotaryEmbedding(hk.Module):
+ """Applies rotary embeddings (RoPE) to the input sequence tensor,
+ as described in https://arxiv.org/abs/2104.09864.
+
+ Attributes:
+ dim (int): Dimensionality of the feature vectors
+ base_exponent (int): Base exponent to compute embeddings from
+ """
def __init__(
self,
@@ -885,6 +913,7 @@
@dataclass
class MHABlock(hk.Module):
+ """A MHA Block"""
num_q_heads: int
num_kv_heads: int
@@ -980,6 +1009,7 @@
@dataclass
class DecoderLayer(hk.Module):
+ """A transformer stack."""
num_q_heads: int
num_kv_heads: int
@@ -1004,6 +1034,7 @@ padding_mask: Optional[jax.Array],
layer_memory: Optional[KVMemory],
) -> DecoderOutput:
+ """Transforms input embedding sequences to output embedding sequences."""
def layer_norm(x):
return hk_rms_norm(x)
@@ -1077,6 +1108,7 @@
class InOutEmbed(hk.Embed):
+ """Module for embedding tokens in a low-dimensional space."""
def __init__(
self,
@@ -1113,6 +1145,7 @@
@dataclass
class LanguageModelConfig:
+ """An autoregressive transformer-based language model."""
model: Optional[TransformerConfig]
vocab_size: int
@@ -1167,6 +1200,7 @@
@dataclass
class LanguageModel(hk.Module):
+ """An autoregressive transformer-based language model."""
model: "Transformer"
config: LanguageModelConfig
@@ -1183,6 +1217,7 @@ last_hid_only: bool = False,
length: Optional[jax.Array] = None,
) -> LanguageModelOutput:
+ """Forward pass, producing a sequence of logits."""
del batch # Unused.
config = self.config
@@ -1255,6 +1290,7 @@
@dataclass
class Transformer(hk.Module):
+ """A transformer stack."""
num_q_heads: int
num_kv_heads: int
@@ -1293,6 +1329,7 @@ mask: jax.Array, # [B, T]
memory: Optional[Memory],
) -> TransformerOutput:
+ """Transforms input embedding sequences to output embedding sequences."""
fprop_dtype = embeddings.dtype
_, seq_len, model_size = embeddings.shape
@@ -1358,4 +1395,4 @@ return TransformerOutput(
embeddings=h,
memory=Memory(layers=kv_memories),
- )+ )
| https://raw.githubusercontent.com/xai-org/grok-1/HEAD/model.py |
Create docstrings for all classes and functions | # Copyright 2024 X.AI Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import bisect
import functools
import logging
import math
import re
from dataclasses import dataclass
from typing import Any, Callable, NamedTuple, Optional, Tuple
import haiku as hk
import jax
import jax.experimental.pjit as pjit
import jax.numpy as jnp
import numpy as np
import sentencepiece
from jax.experimental import mesh_utils
from jax.sharding import PartitionSpec as P
from jax.typing import ArrayLike
import checkpoint as xai_checkpoint
from model import (
LanguageModelConfig,
LanguageModelOutput,
TrainingState,
apply_rules,
Memory,
KVMemory,
)
logger = logging.getLogger(__name__)
rank_logger = logging.getLogger("rank")
TOP_K = 8
class SampleSettings(NamedTuple):
temperature: ArrayLike
nucleus_p: ArrayLike
mask: ArrayLike
# Whether a given batch element is actively used. [B]
active: ArrayLike
class SampleOutput(NamedTuple):
token_id: ArrayLike
prob: ArrayLike
top_k_token_ids: ArrayLike
top_k_probs: ArrayLike
def insert_slice(memory: Memory, slice, length, i):
slice = Memory(
layers=[
KVMemory(layer.k, layer.v, step=jnp.array([length]))
for layer in slice.layers
],
)
return jax.tree_map(lambda m, u: jax.lax.dynamic_update_index_in_dim(m, u[0], i, axis=0),
memory, slice)
def pad_to_size(x, size):
if x.shape[0] > size:
# Left truncate if the context is too long.
x = x[-size:]
return np.pad(x, [0, size - x.shape[0]], mode="constant", constant_values=0)
def top_p_filter(logits: jax.Array, top_p: jax.Array) -> jax.Array:
assert logits.ndim == top_p.ndim, f"Expected {logits.ndim} equal {top_p.ndim}"
sorted_logits = jax.lax.sort(logits, is_stable=False)
sorted_probs = jax.nn.softmax(sorted_logits)
threshold_idx = jnp.argmax(jnp.cumsum(sorted_probs, -1) >= 1 - top_p, axis=-1)
threshold_largest_logits = jnp.take_along_axis(
sorted_logits, threshold_idx[..., jnp.newaxis], axis=-1
)
assert threshold_largest_logits.shape == logits.shape[:-1] + (1,)
mask = logits >= threshold_largest_logits
# Set unused logits to -inf.
logits = jnp.where(mask, logits, -1e10)
return logits
def sample_token(
rngs: jax.random.PRNGKey,
lm_outputs: LanguageModelOutput,
settings: SampleSettings,
) -> SampleOutput:
# Expand the settings shape to match the logit shape.
settings = SampleSettings(
temperature=jnp.expand_dims(settings.temperature, (1, 2)), # Input [B], output [B, 1, 1].
nucleus_p=jnp.expand_dims(settings.nucleus_p, (1, 2)), # Input [B], output [B, 1, 1].
mask=jnp.expand_dims(settings.mask, 1), # Input [B, V], output [B, 1, V].
active=settings.active, # [B].
)
logits = lm_outputs.logits / settings.temperature.astype(lm_outputs.logits.dtype)
# Mask out all disallowed tokens by assigning them a near-zero probability.
logits = jnp.where(settings.mask, logits, -1e10)
# Mask out all tokens that don't fall into the p-th percentile.
logits = top_p_filter(logits, settings.nucleus_p.astype(logits.dtype))
new_token = jax.vmap(jax.random.categorical)(rngs, logits)
probabilities = jax.nn.softmax(logits)
token_prob = jnp.take_along_axis(probabilities, jnp.expand_dims(new_token, 1), axis=2)
token_prob = jnp.squeeze(token_prob, 1)
# Gather the top-k tokens and probabilities.
top_k_probs, top_k_token_ids = jax.lax.top_k(probabilities, TOP_K)
top_k_probs = jnp.squeeze(top_k_probs, 1)
top_k_token_ids = jnp.squeeze(top_k_token_ids, 1)
return SampleOutput(
new_token,
token_prob,
top_k_token_ids,
top_k_probs,
)
@dataclass
class ModelRunner:
model: LanguageModelConfig
bs_per_device: float = 2.0
load_rename_rules: Optional[list[tuple[str, str]]] = None
load_exclude_rules: Optional[list[str]] = None
rng_seed: int = 42 # Initial rng seed.
transform_forward: bool = False
checkpoint_path: str = ""
def make_forward_fn(self, mesh: Any):
def forward(tokens):
out = self.model.make(mesh=mesh)(tokens)
return out, None
if self.transform_forward:
forward = hk.transform(forward)
return forward
def initialize(
self,
init_data,
local_mesh_config: tuple[int, int],
between_hosts_config: tuple[int, int],
):
num_replicas = math.prod(between_hosts_config)
self.model.initialize()
self.model.fprop_dtype = jnp.bfloat16
num_local_gpus = len(jax.local_devices())
# Calculate the global batch size from the local batch size.
self.batch_size = int(self.bs_per_device * num_local_gpus * num_replicas)
# Calculate the batch size per host from the global batch size.
self.local_batch_size = self.batch_size // jax.process_count()
self.local_mesh_config = local_mesh_config
self.between_hosts_config = between_hosts_config
rank_logger.info(
f"Initializing mesh for {self.local_mesh_config=} {self.between_hosts_config=}..."
)
self.mesh = make_mesh(self.local_mesh_config, self.between_hosts_config)
self.forward = self.make_forward_fn(mesh=self.mesh)
self.logits_fn = hk.transform(lambda tokens: self.forward(tokens)[0])
self.eval_forward = self.make_forward_fn(mesh=self.mesh)
self.logits_eval_fn = hk.transform(lambda tokens: self.eval_forward(tokens)[0])
if self.transform_forward:
self.state_sharding = self.get_state_sharding(init_data)
rank_logger.info(f"State sharding type: {type(self.state_sharding)}")
self.init_fn = pjit.pjit(self.init, out_shardings=self.state_sharding)
def init(self, rng: jax.Array, data) -> TrainingState:
assert self.transform_forward
rng, init_rng = jax.random.split(rng)
params = self.forward.init(init_rng, data["inputs"])
return TrainingState(params=params)
def get_state_sharding(self, init_data):
assert self.transform_forward
rng = jax.random.PRNGKey(self.rng_seed)
rank_logger.info(f"partition rules: {self.model.partition_rules}")
with self.mesh:
shapes = jax.eval_shape(self.init, rng, init_data)
sharding = jax.tree_util.tree_map_with_path(
apply_rules(self.model.partition_rules()),
shapes,
)
return sharding
def load_or_init(
self,
init_data: Any,
from_checkpoint: bool = True,
init_fn: Optional[Callable] = None,
):
rng = jax.random.PRNGKey(self.rng_seed)
if not self.checkpoint_path or not from_checkpoint:
rank_logger.info("Initializing model...")
with self.mesh:
if init_fn is not None:
state = init_fn(rng, init_data)
else:
assert self.transform_forward
state = self.init_fn(rng, init_data)
rank_logger.info("Model state is newly initialized.")
else:
with self.mesh:
if init_fn:
state_shapes = jax.eval_shape(init_fn, rng, init_data)
else:
assert self.transform_forward
state_shapes = jax.eval_shape(self.init_fn, rng, init_data)
init_state = None
state = xai_checkpoint.restore(
checkpoint_path=self.checkpoint_path,
state_shapes=state_shapes,
mesh=self.mesh,
between_hosts_config=self.between_hosts_config,
state_sharding=self.state_sharding,
init_state=init_state,
params_only=True,
)
del init_state
return state
@dataclass
class Request:
prompt: str
temperature: float
nucleus_p: float
rng_seed: int
max_len: int
@dataclass
class InferenceRunner:
name: str
runner: Any
load: str
tokenizer_path: str = "/tmp/xai_data/tokenizer.model"
local_mesh_config: Tuple[int, int] = (1, 1)
between_hosts_config: Tuple[int, int] = (1, 1)
pad_sizes: tuple[int] = (1024,)
def get_pad_bucket(self, size):
i = bisect.bisect_left(self.pad_sizes, size)
return self.pad_sizes[min(i, len(self.pad_sizes) - 1)]
def initialize(self):
runner = self.runner
self.runner.transform_forward = True
dummy_data = dict(
inputs=np.zeros((1, 256), dtype=np.int32),
targets=np.zeros((1, 256), dtype=np.int32),
)
runner.initialize(
dummy_data,
local_mesh_config=self.local_mesh_config,
between_hosts_config=self.between_hosts_config,
)
self.tokenizer = sentencepiece.SentencePieceProcessor(model_file=self.tokenizer_path)
max_len = runner.model.sequence_len
self.vocab_size = self.runner.model.vocab_size
params = runner.load_or_init(dummy_data)
self.params = params
def pad_to_max_len(x):
if len(x.shape) > 1:
pad_width = max_len - x.shape[1]
return jnp.pad(x, [(0, 0), (0, pad_width), (0, 0), (0, 0)])
else:
return x
@functools.lru_cache
def lm():
return runner.model.make(mesh=runner.mesh)
def hk_forward(
tokens,
memory=None,
length=None,
active=None,
) -> LanguageModelOutput:
if memory is not None:
assert active is not None
layers = []
for l in memory.layers:
# Reset steps to 0 for inactive requests to avoid unnecessary computations.
step = jnp.where(active, l.step, jnp.zeros_like(l.step))
layers.append(l._replace(step=step))
memory = memory._replace(layers=layers)
return lm()(tokens, memory, length=length)
def hk_sample_step(rngs, last_output: SampleOutput, memory, settings):
rngs, rngs_ = jax.vmap(jax.random.split, out_axes=1)(rngs)
lm_outputs = hk_forward(last_output.token_id, memory=memory, active=settings.active)
sample_result = sample_token(rngs_, lm_outputs, settings)
return rngs, sample_result, lm_outputs.model_state
def hk_new_memory(batch_size, sequence_len):
return lm().init_memory(batch_size, sequence_len)
def hk_prefill_memory(
rngs,
memory,
settings,
last_output,
prompt,
length,
rng_seed,
new_settings,
i,
):
rng = jax.random.PRNGKey(seed=rng_seed)
rng, rng_ = jax.random.split(rng)
# Allocate new memory for this sample. The memory length is equal to the length of the
# prompt.
slice = hk_new_memory(1, prompt.shape[0])
# Move the settings for this individual batch entry into the joint settings tensor.
settings = jax.tree_map(
lambda o, v: jax.lax.dynamic_update_index_in_dim(o, v, i, axis=0),
settings,
new_settings,
)
# Get the settings for the batch entry from the joint settings tensor.
settings_slice = jax.tree_map(lambda t: jnp.expand_dims(t[i], axis=0), settings)
# Process the first n-1 tokens of the prompt.
lm_outputs = hk_forward(
jnp.expand_dims(prompt, 0),
memory=slice,
length=jnp.expand_dims(length, 0),
active=settings_slice.active,
)
# The forward pass doesn't correctly set the `step` counter inside the memory. Manually
# override it so `hk_forward` uses the correct context length in the next call.
slice = lm_outputs.model_state
slice = slice._replace(
layers=[l._replace(step=jnp.array([length])) for l in slice.layers]
)
# Sample the actual output token.
rng_ = jnp.expand_dims(rng_, 0)
new_output = sample_token(rng_, lm_outputs, settings_slice)
# Update the KV cache/memory.
slice = jax.tree_map(pad_to_max_len, slice)
memory = insert_slice(memory, slice, length, i)
rng = jnp.expand_dims(rng, 0)
rngs = jax.lax.dynamic_update_index_in_dim(rngs, rng, i, axis=0)
# Move the network outputs for this batch entry into the joint output tensor.
last_output = jax.tree_util.tree_map(
lambda last, new: jax.lax.dynamic_update_index_in_dim(last, new, i, axis=0),
last_output,
new_output,
)
return rngs, last_output, memory, settings
sample_step_ = hk.without_apply_rng(hk.transform(hk_sample_step))
prefill_memory_ = hk.without_apply_rng(hk.transform(hk_prefill_memory))
new_memory_ = hk.without_apply_rng(hk.transform(hk_new_memory))
forward_ = hk.without_apply_rng(hk.transform(hk_forward))
rng = jax.random.PRNGKey(42)
dummy_tokens = jnp.zeros((1, max_len), jnp.int32)
with runner.mesh:
shapes = jax.eval_shape(forward_.init, rng, dummy_tokens)
self.params_sharding = jax.tree_util.tree_map_with_path(
apply_rules(runner.model.partition_rules()),
shapes,
)
ds = P("data")
ms = runner.model.model.get_memory_sharding()
self.sample_step = pjit.pjit(
sample_step_.apply,
in_shardings=(self.params_sharding, None, ds, ms, None),
out_shardings=(None, ds, ms),
donate_argnums=3,
)
self.prefill_memory = pjit.pjit(
functools.partial(prefill_memory_.apply),
in_shardings=(
self.params_sharding,
None,
ms,
None,
ds,
None,
None,
None,
None,
None,
),
out_shardings=(None, ds, ms, None),
donate_argnums=(2,),
)
self.new_memory = pjit.pjit(
new_memory_.apply,
static_argnums=(1, 2),
out_shardings=ms,
)
def run(self):
runner = self.runner
mesh = runner.mesh
max_len = runner.model.sequence_len
batch_size = runner.batch_size
params = self.params
rngs = jax.random.split(jax.random.PRNGKey(1), batch_size)
with mesh:
memory = self.new_memory(params, batch_size, max_len)
settings = SampleSettings(
temperature=np.zeros((batch_size,), dtype=np.float32),
nucleus_p=np.zeros((batch_size,), dtype=np.float32),
mask=np.ones((batch_size, self.vocab_size), dtype=np.int32),
active=np.zeros((batch_size), dtype=np.int32),
)
last_output = SampleOutput(
token_id=np.zeros((batch_size, 1), dtype=np.int32),
prob=np.zeros((batch_size, 1), dtype=jnp.bfloat16),
top_k_token_ids=np.zeros((batch_size, TOP_K), dtype=np.int32),
top_k_probs=np.zeros((batch_size, TOP_K), dtype=jnp.bfloat16),
)
prompt = np.array([300, 400, 500, 600, 600, 700, 800])
new_settings = SampleSettings(
temperature=np.float32(1),
nucleus_p=np.float32(1),
mask=np.ones((self.vocab_size,), dtype=np.int32),
active=np.zeros((), dtype=np.int32),
)
rng_seed = np.uint64(1)
for size in self.pad_sizes:
if size > runner.model.sequence_len:
break
logger.info("Precompile {}".format(size))
prompt_len = len(prompt)
prompt = pad_to_size(prompt, size)
rngs, last_output, memory, settings = self.prefill_memory(
params,
rngs,
memory,
settings,
last_output,
prompt,
prompt_len,
rng_seed,
new_settings,
0,
)
with runner.mesh:
logger.info("Compiling...")
rngs, last_output, memory = self.sample_step(
params, rngs, last_output, memory, settings
)
logger.info("Done compiling.")
all_tokens = []
free_slots = list(range(batch_size))
requests = [None] * batch_size
first_output = [None] * batch_size
jax.tree_map(lambda x: x.copy_to_host_async(), last_output)
prev_token = last_output
step = 0
total_num_tokens = 0
total_num_sequences = 0
with mesh:
while True:
while free_slots:
request: Optional[Request] = yield
tokens = self.tokenizer.encode(request.prompt)
temperature = request.temperature
nucleus_p = request.nucleus_p
rng_seed = request.rng_seed
i = free_slots.pop()
prompt = np.array(tokens, dtype=np.int32)
prompt_len = len(prompt)
prompt = pad_to_size(prompt, self.get_pad_bucket(prompt.shape[0]))
# All tokens are allowed.
mask = np.ones((self.vocab_size,), dtype=np.int32)
new_settings = SampleSettings(
temperature=np.float32(temperature),
nucleus_p=np.float32(nucleus_p),
mask=mask,
active=np.ones((), dtype=np.int32),
)
rng_seed = np.uint64(rng_seed)
rngs, last_output, memory, settings = self.prefill_memory(
params,
rngs,
memory,
settings,
last_output,
prompt,
prompt_len,
rng_seed,
new_settings,
i,
)
jax.tree_map(lambda x: x.copy_to_host_async(), last_output)
first_output[i] = last_output
requests[i] = request
total_num_sequences += 1
rngs, last_output, memory = self.sample_step(
params, rngs, last_output, memory, settings
)
total_num_tokens += batch_size - len(free_slots)
# prev_token should already be on the host.
prev_token = jax.tree_map(np.array, prev_token)
for i in range(batch_size):
if requests[i] is not None:
if first_output[i] is not None:
first_output_i = jax.tree_map(np.array, first_output[i])
all_tokens.append(int(first_output_i.token_id[i][0]))
first_output[i] = None
continue
all_tokens.append(int(prev_token.token_id[i][0]))
cont = len(all_tokens) < requests[i].max_len
if not cont:
output_str = self.tokenizer.decode(all_tokens)
requests[i] = None
free_slots.append(i)
all_tokens = []
settings = settings._replace(active=settings.active.at[i].set(0))
yield output_str
jax.tree_map(lambda x: x.copy_to_host_async(), last_output)
prev_token = last_output
step += 1
def make_mesh(
local_mesh_config: tuple[int, ...], between_hosts_config: tuple[int, ...]
) -> jax.sharding.Mesh:
assert len(local_mesh_config) == 2
assert len(between_hosts_config) == 2
rank_logger.info("Detected %s devices in mesh", jax.device_count())
device_mesh = mesh_utils.create_hybrid_device_mesh(
local_mesh_config,
between_hosts_config,
devices=jax.devices(),
process_is_granule=True,
)
rank_logger.debug(re.sub("\n+", "\n", f"Job device mesh is:\n{device_mesh}"))
return jax.sharding.Mesh(device_mesh, ("data", "model"))
def sample_from_model(server, prompt, max_len, temperature):
next(server)
inp = Request(
prompt=prompt,
temperature=temperature,
nucleus_p=1.0,
rng_seed=42,
max_len=max_len,
)
return server.send(inp) | --- +++ @@ -82,6 +82,7 @@
def top_p_filter(logits: jax.Array, top_p: jax.Array) -> jax.Array:
+ """Performs nucleus filtering on logits."""
assert logits.ndim == top_p.ndim, f"Expected {logits.ndim} equal {top_p.ndim}"
sorted_logits = jax.lax.sort(logits, is_stable=False)
sorted_probs = jax.nn.softmax(sorted_logits)
@@ -439,6 +440,7 @@ )
def run(self):
+ """Generator that accepts prompts."""
runner = self.runner
mesh = runner.mesh
max_len = runner.model.sequence_len
@@ -600,4 +602,4 @@ rng_seed=42,
max_len=max_len,
)
- return server.send(inp)+ return server.send(inp)
| https://raw.githubusercontent.com/xai-org/grok-1/HEAD/runners.py |
Write reusable docstrings | import hashlib
import logging
from typing import Any, Optional
from embedchain.config.add_config import ChunkerConfig
from embedchain.helpers.json_serializable import JSONSerializable
from embedchain.models.data_type import DataType
logger = logging.getLogger(__name__)
class BaseChunker(JSONSerializable):
def __init__(self, text_splitter):
self.text_splitter = text_splitter
self.data_type = None
def create_chunks(
self,
loader,
src,
app_id=None,
config: Optional[ChunkerConfig] = None,
**kwargs: Optional[dict[str, Any]],
):
documents = []
chunk_ids = []
id_map = {}
min_chunk_size = config.min_chunk_size if config is not None else 1
logger.info(f"Skipping chunks smaller than {min_chunk_size} characters")
data_result = loader.load_data(src, **kwargs)
data_records = data_result["data"]
doc_id = data_result["doc_id"]
# Prefix app_id in the document id if app_id is not None to
# distinguish between different documents stored in the same
# elasticsearch or opensearch index
doc_id = f"{app_id}--{doc_id}" if app_id is not None else doc_id
metadatas = []
for data in data_records:
content = data["content"]
metadata = data["meta_data"]
# add data type to meta data to allow query using data type
metadata["data_type"] = self.data_type.value
metadata["doc_id"] = doc_id
# TODO: Currently defaulting to the src as the url. This is done intentianally since some
# of the data types like 'gmail' loader doesn't have the url in the meta data.
url = metadata.get("url", src)
chunks = self.get_chunks(content)
for chunk in chunks:
chunk_id = hashlib.sha256((chunk + url).encode()).hexdigest()
chunk_id = f"{app_id}--{chunk_id}" if app_id is not None else chunk_id
if id_map.get(chunk_id) is None and len(chunk) >= min_chunk_size:
id_map[chunk_id] = True
chunk_ids.append(chunk_id)
documents.append(chunk)
metadatas.append(metadata)
return {
"documents": documents,
"ids": chunk_ids,
"metadatas": metadatas,
"doc_id": doc_id,
}
def get_chunks(self, content):
return self.text_splitter.split_text(content)
def set_data_type(self, data_type: DataType):
self.data_type = data_type
# TODO: This should be done during initialization. This means it has to be done in the child classes.
@staticmethod
def get_word_count(documents) -> int:
return sum(len(document.split(" ")) for document in documents) | --- +++ @@ -11,6 +11,7 @@
class BaseChunker(JSONSerializable):
def __init__(self, text_splitter):
+ """Initialize the chunker."""
self.text_splitter = text_splitter
self.data_type = None
@@ -22,6 +23,15 @@ config: Optional[ChunkerConfig] = None,
**kwargs: Optional[dict[str, Any]],
):
+ """
+ Loads data and chunks it.
+
+ :param loader: The loader whose `load_data` method is used to create
+ the raw data.
+ :param src: The data to be handled by the loader. Can be a URL for
+ remote sources or local content for local loaders.
+ :param app_id: App id used to generate the doc_id.
+ """
documents = []
chunk_ids = []
id_map = {}
@@ -64,13 +74,21 @@ }
def get_chunks(self, content):
+ """
+ Returns chunks using text splitter instance.
+
+ Override in child class if custom logic.
+ """
return self.text_splitter.split_text(content)
def set_data_type(self, data_type: DataType):
+ """
+ set the data type of chunker
+ """
self.data_type = data_type
# TODO: This should be done during initialization. This means it has to be done in the child classes.
@staticmethod
def get_word_count(documents) -> int:
- return sum(len(document.split(" ")) for document in documents)+ return sum(len(document.split(" ")) for document in documents)
| https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/chunkers/base_chunker.py |
Document functions with clear intent | import builtins
import logging
from collections.abc import Callable
from importlib import import_module
from typing import Optional
from embedchain.config.base_config import BaseConfig
from embedchain.helpers.json_serializable import register_deserializable
@register_deserializable
class ChunkerConfig(BaseConfig):
def __init__(
self,
chunk_size: Optional[int] = 2000,
chunk_overlap: Optional[int] = 0,
length_function: Optional[Callable[[str], int]] = None,
min_chunk_size: Optional[int] = 0,
):
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
self.min_chunk_size = min_chunk_size
if self.min_chunk_size >= self.chunk_size:
raise ValueError(f"min_chunk_size {min_chunk_size} should be less than chunk_size {chunk_size}")
if self.min_chunk_size < self.chunk_overlap:
logging.warning(
f"min_chunk_size {min_chunk_size} should be greater than chunk_overlap {chunk_overlap}, otherwise it is redundant." # noqa:E501
)
if isinstance(length_function, str):
self.length_function = self.load_func(length_function)
else:
self.length_function = length_function if length_function else len
@staticmethod
def load_func(dotpath: str):
if "." not in dotpath:
return getattr(builtins, dotpath)
else:
module_, func = dotpath.rsplit(".", maxsplit=1)
m = import_module(module_)
return getattr(m, func)
@register_deserializable
class LoaderConfig(BaseConfig):
def __init__(self):
pass
@register_deserializable
class AddConfig(BaseConfig):
def __init__(
self,
chunker: Optional[ChunkerConfig] = None,
loader: Optional[LoaderConfig] = None,
):
self.loader = loader
self.chunker = chunker | --- +++ @@ -10,6 +10,9 @@
@register_deserializable
class ChunkerConfig(BaseConfig):
+ """
+ Config for the chunker used in `add` method
+ """
def __init__(
self,
@@ -45,6 +48,9 @@
@register_deserializable
class LoaderConfig(BaseConfig):
+ """
+ Config for the loader used in `add` method
+ """
def __init__(self):
pass
@@ -52,11 +58,22 @@
@register_deserializable
class AddConfig(BaseConfig):
+ """
+ Config for the `add` method.
+ """
def __init__(
self,
chunker: Optional[ChunkerConfig] = None,
loader: Optional[LoaderConfig] = None,
):
+ """
+ Initializes a configuration class instance for the `add` method.
+
+ :param chunker: Chunker config, defaults to None
+ :type chunker: Optional[ChunkerConfig], optional
+ :param loader: Loader config, defaults to None
+ :type loader: Optional[LoaderConfig], optional
+ """
self.loader = loader
- self.chunker = chunker+ self.chunker = chunker
| https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/config/add_config.py |
Add docstrings to improve readability | from abc import ABC, abstractmethod
from embedchain.utils.evaluation import EvalData
class BaseMetric(ABC):
def __init__(self, name: str = "base_metric"):
self.name = name
@abstractmethod
def evaluate(self, dataset: list[EvalData]):
raise NotImplementedError() | --- +++ @@ -4,10 +4,26 @@
class BaseMetric(ABC):
+ """Base class for a metric.
+
+ This class provides a common interface for all metrics.
+ """
def __init__(self, name: str = "base_metric"):
+ """
+ Initialize the BaseMetric.
+ """
self.name = name
@abstractmethod
def evaluate(self, dataset: list[EvalData]):
- raise NotImplementedError()+ """
+ Abstract method to evaluate the dataset.
+
+ This method should be implemented by subclasses to perform the actual
+ evaluation on the dataset.
+
+ :param dataset: dataset to evaluate
+ :type dataset: list[EvalData]
+ """
+ raise NotImplementedError()
| https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/evaluation/base.py |
Add docstrings explaining edge cases | import concurrent.futures
import logging
import os
from string import Template
from typing import Optional
import numpy as np
from openai import OpenAI
from tqdm import tqdm
from embedchain.config.evaluation.base import AnswerRelevanceConfig
from embedchain.evaluation.base import BaseMetric
from embedchain.utils.evaluation import EvalData, EvalMetric
logger = logging.getLogger(__name__)
class AnswerRelevance(BaseMetric):
def __init__(self, config: Optional[AnswerRelevanceConfig] = AnswerRelevanceConfig()):
super().__init__(name=EvalMetric.ANSWER_RELEVANCY.value)
self.config = config
api_key = self.config.api_key or os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("API key not found. Set 'OPENAI_API_KEY' or pass it in the config.")
self.client = OpenAI(api_key=api_key)
def _generate_prompt(self, data: EvalData) -> str:
return Template(self.config.prompt).substitute(
num_gen_questions=self.config.num_gen_questions, answer=data.answer
)
def _generate_questions(self, prompt: str) -> list[str]:
response = self.client.chat.completions.create(
model=self.config.model,
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content.strip().split("\n")
def _generate_embedding(self, question: str) -> np.ndarray:
response = self.client.embeddings.create(
input=question,
model=self.config.embedder,
)
return np.array(response.data[0].embedding)
def _compute_similarity(self, original: np.ndarray, generated: np.ndarray) -> float:
original = original.reshape(1, -1)
norm = np.linalg.norm(original) * np.linalg.norm(generated, axis=1)
return np.dot(generated, original.T).flatten() / norm
def _compute_score(self, data: EvalData) -> float:
prompt = self._generate_prompt(data)
generated_questions = self._generate_questions(prompt)
original_embedding = self._generate_embedding(data.question)
generated_embeddings = np.array([self._generate_embedding(q) for q in generated_questions])
similarities = self._compute_similarity(original_embedding, generated_embeddings)
return np.mean(similarities)
def evaluate(self, dataset: list[EvalData]) -> float:
results = []
with concurrent.futures.ThreadPoolExecutor() as executor:
future_to_data = {executor.submit(self._compute_score, data): data for data in dataset}
for future in tqdm(
concurrent.futures.as_completed(future_to_data), total=len(dataset), desc="Evaluating Answer Relevancy"
):
data = future_to_data[future]
try:
results.append(future.result())
except Exception as e:
logger.error(f"Error evaluating answer relevancy for {data}: {e}")
return np.mean(results) if results else 0.0 | --- +++ @@ -16,6 +16,9 @@
class AnswerRelevance(BaseMetric):
+ """
+ Metric for evaluating the relevance of answers.
+ """
def __init__(self, config: Optional[AnswerRelevanceConfig] = AnswerRelevanceConfig()):
super().__init__(name=EvalMetric.ANSWER_RELEVANCY.value)
@@ -26,11 +29,17 @@ self.client = OpenAI(api_key=api_key)
def _generate_prompt(self, data: EvalData) -> str:
+ """
+ Generates a prompt based on the provided data.
+ """
return Template(self.config.prompt).substitute(
num_gen_questions=self.config.num_gen_questions, answer=data.answer
)
def _generate_questions(self, prompt: str) -> list[str]:
+ """
+ Generates questions from the prompt.
+ """
response = self.client.chat.completions.create(
model=self.config.model,
messages=[{"role": "user", "content": prompt}],
@@ -38,6 +47,9 @@ return response.choices[0].message.content.strip().split("\n")
def _generate_embedding(self, question: str) -> np.ndarray:
+ """
+ Generates the embedding for a question.
+ """
response = self.client.embeddings.create(
input=question,
model=self.config.embedder,
@@ -45,11 +57,17 @@ return np.array(response.data[0].embedding)
def _compute_similarity(self, original: np.ndarray, generated: np.ndarray) -> float:
+ """
+ Computes the cosine similarity between two embeddings.
+ """
original = original.reshape(1, -1)
norm = np.linalg.norm(original) * np.linalg.norm(generated, axis=1)
return np.dot(generated, original.T).flatten() / norm
def _compute_score(self, data: EvalData) -> float:
+ """
+ Computes the relevance score for a given data item.
+ """
prompt = self._generate_prompt(data)
generated_questions = self._generate_questions(prompt)
original_embedding = self._generate_embedding(data.question)
@@ -58,6 +76,9 @@ return np.mean(similarities)
def evaluate(self, dataset: list[EvalData]) -> float:
+ """
+ Evaluates the dataset and returns the average answer relevance score.
+ """
results = []
with concurrent.futures.ThreadPoolExecutor() as executor:
@@ -71,4 +92,4 @@ except Exception as e:
logger.error(f"Error evaluating answer relevancy for {data}: {e}")
- return np.mean(results) if results else 0.0+ return np.mean(results) if results else 0.0
| https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/evaluation/metrics/answer_relevancy.py |
Add standardized docstrings across the file | import json
import logging
import re
from pathlib import Path
from string import Template
from typing import Any, Dict, Mapping, Optional, Union
import httpx
from embedchain.config.base_config import BaseConfig
from embedchain.helpers.json_serializable import register_deserializable
logger = logging.getLogger(__name__)
DEFAULT_PROMPT = """
You are a Q&A expert system. Your responses must always be rooted in the context provided for each query. Here are some guidelines to follow:
1. Refrain from explicitly mentioning the context provided in your response.
2. The context should silently guide your answers without being directly acknowledged.
3. Do not use phrases such as 'According to the context provided', 'Based on the context, ...' etc.
Context information:
----------------------
$context
----------------------
Query: $query
Answer:
""" # noqa:E501
DEFAULT_PROMPT_WITH_HISTORY = """
You are a Q&A expert system. Your responses must always be rooted in the context provided for each query. You are also provided with the conversation history with the user. Make sure to use relevant context from conversation history as needed.
Here are some guidelines to follow:
1. Refrain from explicitly mentioning the context provided in your response.
2. The context should silently guide your answers without being directly acknowledged.
3. Do not use phrases such as 'According to the context provided', 'Based on the context, ...' etc.
Context information:
----------------------
$context
----------------------
Conversation history:
----------------------
$history
----------------------
Query: $query
Answer:
""" # noqa:E501
DEFAULT_PROMPT_WITH_MEM0_MEMORY = """
You are an expert at answering questions based on provided memories. You are also provided with the context and conversation history of the user. Make sure to use relevant context from conversation history and context as needed.
Here are some guidelines to follow:
1. Refrain from explicitly mentioning the context provided in your response.
2. Take into consideration the conversation history and context provided.
3. Do not use phrases such as 'According to the context provided', 'Based on the context, ...' etc.
Striclty return the query exactly as it is if it is not a question or if no relevant information is found.
Context information:
----------------------
$context
----------------------
Conversation history:
----------------------
$history
----------------------
Memories/Preferences:
----------------------
$memories
----------------------
Query: $query
Answer:
""" # noqa:E501
DOCS_SITE_DEFAULT_PROMPT = """
You are an expert AI assistant for developer support product. Your responses must always be rooted in the context provided for each query. Wherever possible, give complete code snippet. Dont make up any code snippet on your own.
Here are some guidelines to follow:
1. Refrain from explicitly mentioning the context provided in your response.
2. The context should silently guide your answers without being directly acknowledged.
3. Do not use phrases such as 'According to the context provided', 'Based on the context, ...' etc.
Context information:
----------------------
$context
----------------------
Query: $query
Answer:
""" # noqa:E501
DEFAULT_PROMPT_TEMPLATE = Template(DEFAULT_PROMPT)
DEFAULT_PROMPT_WITH_HISTORY_TEMPLATE = Template(DEFAULT_PROMPT_WITH_HISTORY)
DEFAULT_PROMPT_WITH_MEM0_MEMORY_TEMPLATE = Template(DEFAULT_PROMPT_WITH_MEM0_MEMORY)
DOCS_SITE_PROMPT_TEMPLATE = Template(DOCS_SITE_DEFAULT_PROMPT)
query_re = re.compile(r"\$\{*query\}*")
context_re = re.compile(r"\$\{*context\}*")
history_re = re.compile(r"\$\{*history\}*")
@register_deserializable
class BaseLlmConfig(BaseConfig):
def __init__(
self,
number_documents: int = 3,
template: Optional[Template] = None,
prompt: Optional[Template] = None,
model: Optional[str] = None,
temperature: float = 0,
max_tokens: int = 1000,
top_p: float = 1,
stream: bool = False,
online: bool = False,
token_usage: bool = False,
deployment_name: Optional[str] = None,
system_prompt: Optional[str] = None,
where: dict[str, Any] = None,
query_type: Optional[str] = None,
callbacks: Optional[list] = None,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
endpoint: Optional[str] = None,
model_kwargs: Optional[dict[str, Any]] = None,
http_client_proxies: Optional[Union[Dict, str]] = None,
http_async_client_proxies: Optional[Union[Dict, str]] = None,
local: Optional[bool] = False,
default_headers: Optional[Mapping[str, str]] = None,
api_version: Optional[str] = None,
):
if template is not None:
logger.warning(
"The `template` argument is deprecated and will be removed in a future version. "
+ "Please use `prompt` instead."
)
if prompt is None:
prompt = template
if prompt is None:
prompt = DEFAULT_PROMPT_TEMPLATE
self.number_documents = number_documents
self.temperature = temperature
self.max_tokens = max_tokens
self.model = model
self.top_p = top_p
self.online = online
self.token_usage = token_usage
self.deployment_name = deployment_name
self.system_prompt = system_prompt
self.query_type = query_type
self.callbacks = callbacks
self.api_key = api_key
self.base_url = base_url
self.endpoint = endpoint
self.model_kwargs = model_kwargs
self.http_client = httpx.Client(proxies=http_client_proxies) if http_client_proxies else None
self.http_async_client = (
httpx.AsyncClient(proxies=http_async_client_proxies) if http_async_client_proxies else None
)
self.local = local
self.default_headers = default_headers
self.online = online
self.api_version = api_version
if token_usage:
f = Path(__file__).resolve().parent.parent / "model_prices_and_context_window.json"
self.model_pricing_map = json.load(f.open())
if isinstance(prompt, str):
prompt = Template(prompt)
if self.validate_prompt(prompt):
self.prompt = prompt
else:
raise ValueError("The 'prompt' should have 'query' and 'context' keys and potentially 'history' (if used).")
if not isinstance(stream, bool):
raise ValueError("`stream` should be bool")
self.stream = stream
self.where = where
@staticmethod
def validate_prompt(prompt: Template) -> Optional[re.Match[str]]:
return re.search(query_re, prompt.template) and re.search(context_re, prompt.template)
@staticmethod
def _validate_prompt_history(prompt: Template) -> Optional[re.Match[str]]:
return re.search(history_re, prompt.template) | --- +++ @@ -109,6 +109,9 @@
@register_deserializable
class BaseLlmConfig(BaseConfig):
+ """
+ Config for the `query` method.
+ """
def __init__(
self,
@@ -137,6 +140,65 @@ default_headers: Optional[Mapping[str, str]] = None,
api_version: Optional[str] = None,
):
+ """
+ Initializes a configuration class instance for the LLM.
+
+ Takes the place of the former `QueryConfig` or `ChatConfig`.
+
+ :param number_documents: Number of documents to pull from the database as
+ context, defaults to 1
+ :type number_documents: int, optional
+ :param template: The `Template` instance to use as a template for
+ prompt, defaults to None (deprecated)
+ :type template: Optional[Template], optional
+ :param prompt: The `Template` instance to use as a template for
+ prompt, defaults to None
+ :type prompt: Optional[Template], optional
+ :param model: Controls the OpenAI model used, defaults to None
+ :type model: Optional[str], optional
+ :param temperature: Controls the randomness of the model's output.
+ Higher values (closer to 1) make output more random, lower values make it more deterministic, defaults to 0
+ :type temperature: float, optional
+ :param max_tokens: Controls how many tokens are generated, defaults to 1000
+ :type max_tokens: int, optional
+ :param top_p: Controls the diversity of words. Higher values (closer to 1) make word selection more diverse,
+ defaults to 1
+ :type top_p: float, optional
+ :param stream: Control if response is streamed back to user, defaults to False
+ :type stream: bool, optional
+ :param online: Controls whether to use internet for answering query, defaults to False
+ :type online: bool, optional
+ :param token_usage: Controls whether to return token usage in response, defaults to False
+ :type token_usage: bool, optional
+ :param deployment_name: t.b.a., defaults to None
+ :type deployment_name: Optional[str], optional
+ :param system_prompt: System prompt string, defaults to None
+ :type system_prompt: Optional[str], optional
+ :param where: A dictionary of key-value pairs to filter the database results., defaults to None
+ :type where: dict[str, Any], optional
+ :param api_key: The api key of the custom endpoint, defaults to None
+ :type api_key: Optional[str], optional
+ :param endpoint: The api url of the custom endpoint, defaults to None
+ :type endpoint: Optional[str], optional
+ :param model_kwargs: A dictionary of key-value pairs to pass to the model, defaults to None
+ :type model_kwargs: Optional[Dict[str, Any]], optional
+ :param callbacks: Langchain callback functions to use, defaults to None
+ :type callbacks: Optional[list], optional
+ :param query_type: The type of query to use, defaults to None
+ :type query_type: Optional[str], optional
+ :param http_client_proxies: The proxy server settings used to create self.http_client, defaults to None
+ :type http_client_proxies: Optional[Dict | str], optional
+ :param http_async_client_proxies: The proxy server settings for async calls used to create
+ self.http_async_client, defaults to None
+ :type http_async_client_proxies: Optional[Dict | str], optional
+ :param local: If True, the model will be run locally, defaults to False (for huggingface provider)
+ :type local: Optional[bool], optional
+ :param default_headers: Set additional HTTP headers to be sent with requests to OpenAI
+ :type default_headers: Optional[Mapping[str, str]], optional
+ :raises ValueError: If the template is not valid as template should
+ contain $context and $query (and optionally $history)
+ :raises ValueError: Stream is not boolean
+ """
if template is not None:
logger.warning(
"The `template` argument is deprecated and will be removed in a future version. "
@@ -191,8 +253,24 @@
@staticmethod
def validate_prompt(prompt: Template) -> Optional[re.Match[str]]:
+ """
+ validate the prompt
+
+ :param prompt: the prompt to validate
+ :type prompt: Template
+ :return: valid (true) or invalid (false)
+ :rtype: Optional[re.Match[str]]
+ """
return re.search(query_re, prompt.template) and re.search(context_re, prompt.template)
@staticmethod
def _validate_prompt_history(prompt: Template) -> Optional[re.Match[str]]:
- return re.search(history_re, prompt.template)+ """
+ validate the prompt with history
+
+ :param prompt: the prompt to validate
+ :type prompt: Template
+ :return: valid (true) or invalid (false)
+ :rtype: Optional[re.Match[str]]
+ """
+ return re.search(history_re, prompt.template)
| https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/config/llm/base.py |
Can you add docstrings to this Python file? | from typing import Any
from embedchain.helpers.json_serializable import JSONSerializable
class BaseConfig(JSONSerializable):
def __init__(self):
pass
def as_dict(self) -> dict[str, Any]:
return vars(self) | --- +++ @@ -4,9 +4,18 @@
class BaseConfig(JSONSerializable):
+ """
+ Base config.
+ """
def __init__(self):
+ """Initializes a configuration class for a class."""
pass
def as_dict(self) -> dict[str, Any]:
- return vars(self)+ """Return config object as a dict
+
+ :return: config object as dict
+ :rtype: dict[str, Any]
+ """
+ return vars(self)
| https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/config/base_config.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.