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): ...
--- +++ @@ -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 compati...
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)...
--- +++ @@ -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 i...
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 Kalm...
--- +++ @@ -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. ...
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...
--- +++ @@ -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,...
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): ...
--- +++ @@ -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). + ""...
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: ...
--- +++ @@ -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: + c...
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, ...
--- +++ @@ -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 ...
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 R...
--- +++ @@ -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_sess...
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 ...
--- +++ @@ -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 ...
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(BaseBack...
--- +++ @@ -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 d...
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...
--- +++ @@ -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 t...
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...
--- +++ @@ -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). + ...
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", ...
--- +++ @@ -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) ...
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(BaseSoluti...
--- +++ @@ -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 o...
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): ...
--- +++ @@ -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 boundi...
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) -> Non...
--- +++ @@ -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 s...
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 TrackSta...
--- +++ @@ -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 reactivati...
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 ...
--- +++ @@ -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 imag...
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): ...
--- +++ @@ -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 ...
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 h...
--- +++ @@ -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...
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 ...
--- +++ @@ -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 init...
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 ultralytic...
--- +++ @@ -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 s...
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.u...
--- +++ @@ -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 Tkint...
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 ObjectCo...
--- +++ @@ -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 ...
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 a...
--- +++ @@ -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. + + E...
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 .transforme...
--- +++ @@ -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.ie...
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__() s...
--- +++ @@ -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 supp...
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 ultral...
--- +++ @@ -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='yolo26...
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 l...
--- +++ @@ -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, segm...
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 S...
--- +++ @@ -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 com...
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 __ini...
--- +++ @@ -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...
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_pretrai...
--- +++ @@ -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): + "...
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: ...
--- +++ @@ -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...
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 ...
--- +++ @@ -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 S...
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 Tru...
--- +++ @@ -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 cu...
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_bat...
--- +++ @@ -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 = ...
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 An...
--- +++ @@ -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_ba...
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 Bas...
--- +++ @@ -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...
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)...
--- +++ @@ -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 operatio...
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) ...
--- +++ @@ -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...
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_I...
--- +++ @@ -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. + ...
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(n...
--- +++ @@ -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: + to...
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...
--- +++ @@ -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 estim...
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...
--- +++ @@ -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...
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...
--- +++ @@ -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 ...
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, TEST...
--- +++ @@ -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_...
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": # Quer...
--- +++ @@ -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...
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...
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...
--- +++ @@ -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"}) @@ -2...
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 f...
--- +++ @@ -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): Py...
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 im...
--- +++ @@ -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 + ...
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 # v...
--- +++ @@ -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)...
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 a...
--- +++ @@ -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 pro...
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...
--- +++ @@ -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 additio...
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: ...
--- +++ @@ -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,...
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: tor...
--- +++ @@ -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. + o...
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 ...
--- +++ @@ -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_decod...
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 LO...
--- +++ @@ -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 se...
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) -> to...
--- +++ @@ -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...
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-frien...
--- +++ @@ -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: + """Re...
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") ...
--- +++ @@ -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...
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, T...
--- +++ @@ -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 intersec...
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 _nt...
--- +++ @@ -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)) ...
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, xywh2x...
--- +++ @@ -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...
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 HTTPEr...
--- +++ @@ -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...
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 = "app...
--- +++ @@ -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 t...
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 ...
--- +++ @@ -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...
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: r...
--- +++ @@ -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...
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 pyopen...
--- +++ @@ -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 exam...
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 unus...
--- +++ @@ -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 + """Retur...
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, ...
--- +++ @@ -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): + """...
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._...
--- +++ @@ -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.Req...
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 = (_V...
--- +++ @@ -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...
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 funct...
--- +++ @@ -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(): + ...
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, k...
--- +++ @@ -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 + ...
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 ConsoleLogge...
--- +++ @@ -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 de...
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 ...
--- +++ @@ -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): +...
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("reques...
--- +++ @@ -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 ...
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._g...
--- +++ @@ -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 met...
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)...
--- +++ @@ -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_workflo...
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 fro...
--- +++ @@ -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 ...
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 imp...
--- +++ @@ -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_data...
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 ...
--- +++ @@ -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...
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...
--- +++ @@ -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_analytic...
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 ena...
--- +++ @@ -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...
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" ...
--- +++ @@ -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 = "d...
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: s...
--- +++ @@ -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]: + """Gener...
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: ...
--- +++ @@ -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") ...
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(...
--- +++ @@ -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...
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 No...
--- +++ @@ -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.""" ...
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 ...
--- +++ @@ -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 ...
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 imp...
--- +++ @@ -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(...
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, s...
--- +++ @@ -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: ...
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, s...
--- +++ @@ -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.sof...
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 _...
--- +++ @@ -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...
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): ...
--- +++ @@ -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` me...
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 @abstractmeth...
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.eval...
--- +++ @@ -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 @@ ...
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...
--- +++ @@ -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, ): + ...
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 + +...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/embedchain/embedchain/config/base_config.py