Metadata-Version: 2.4
Name: acmenra-yolo
Version: 0.1.0.0
Summary: Ultralytics YOLO backend plugin for acmenra-cv
Author-email: "acmenra.studio" <hello@acmenra.ru>
License: AGPL-3.0-or-later
Project-URL: Homepage, https://acmenra.studio
Project-URL: Documentation, https://github.com/Acmenra/acmenra-yolo#readme
Project-URL: Repository, https://github.com/Acmenra/acmenra-yolo
Keywords: acmenra-cv,yolo,ultralytics,computer-vision,object-detection,backend-plugin
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: acmenra-cv>=0.3.0.0
Requires-Dist: ultralytics>=8.0.0
Requires-Dist: torch>=1.8.0
Requires-Dist: opencv-python>=4.5.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Dynamic: license-file

# 🚀 acmenra-yolo

> **Official Ultralytics YOLO backend plugin for acmenra-cv**

[![PyPI](https://img.shields.io/pypi/v/acmenra-yolo.svg)](https://pypi.org/project/acmenra-yolo/)
[![Python](https://img.shields.io/pypi/pyversions/acmenra-yolo.svg)](https://pypi.org/project/acmenra-yolo/)
[![License](https://img.shields.io/pypi/l/acmenra-yolo.svg)](https://pypi.org/project/acmenra-yolo/)

```bash
# Install the YOLO plugin (automatically pulls acmenra-cv >= 0.3.0.0)
pip install acmenra-yolo
```

---

## 📦 Overview

**acmenra-yolo** is an official plugin package for [`acmenra-cv`](https://pypi.org/project/acmenra-cv/) that provides seamless integration with [Ultralytics YOLO](https://github.com/ultralytics/ultralytics) models. It extends the core framework with a concrete `Backend` implementation, enabling object detection, instance segmentation, and oriented bounding box (OBB) tasks using state-of-the-art YOLO architectures (v8/v11).

This package is part of the modular `acmenra-cv` ecosystem, designed to keep the core framework lightweight. By separating YOLO support into a dedicated package, users who work with custom models or other inference engines (OpenVINO, TensorRT, etc.) can avoid pulling in heavy dependencies like `ultralytics` and `torch`.

| Feature | Description |
|---------|-------------|
| **Full Task Support** | Detection, segmentation, and OBB in a single unified backend. |
| **Native Tracking** | Leverages YOLO's built-in BoT-SORT tracker for persistent object IDs. |
| **High-Quality Masks** | Optional `refined` mode for smoother segmentation boundaries (`retina_masks`). |
| **Timing Metrics** | Extracts preprocess, prediction, and postprocess timings from YOLO's speed dictionary. |
| **Hardware Acceleration** | Supports CPU, CUDA, MPS, TensorRT, and more via `DeviceType` enum. |
| **Seamless Integration** | Returns standard `acmenra_cv.Result` containers, fully compatible with `Tracker` and `Drawer`. |

---

## ✨ Key Features

### 🔹 Unified YOLO Integration
- **Backend-Agnostic Contract**: Implements the `acmenra_cv.Backend` interface perfectly.
- **Strict Validation**: All parameters (`iou`, `imgsz`, `half`, `refined`) are strictly typed and range-validated via property setters.
- **Automatic Task Routing**: Intelligently processes `boxes`, `masks`, or `obb` outputs based on the model's task type.

### 🔹 Performance & Quality
- **Refined Mask Generation**: Toggle `refined=True` to generate masks at full model resolution for smoother boundaries (at a ~20-30% speed cost).
- **Zero-Crash Design**: Inherits robust frame validation and graceful degradation from the core `acmenra-cv` architecture.
- **Optimized Conversions**: Direct, vectorized conversion from YOLO tensors to normalized `acmenra_cv` spatial primitives (`Box`, `Polygon`, `Obb`).

### 🔹 ADAS & Tracking Ready
- **Persistent IDs**: Native support for YOLO's tracking mode (`track=True`) for multi-object tracking across frames.
- **Temporal Consistency**: Outputs are immediately compatible with `acmenra_cv.Tracker` for trajectory smoothing and zone analysis.

---

## 💡 Quick Start

```python
from enum import Enum
import numpy as np

# 1. Import core components and the YOLO plugin
from acmenra_cv import DeviceType, TaskType, Tracker
from acmenra_yolo import YOLOBackend
from ultralytics import YOLO

# 2. Define your categories
class CocoClass(Enum):
    PERSON = 0
    CAR = 2

# 3. Initialize the YOLO model
model = YOLO("yolov8n-seg.pt")

# 4. Create the backend-agnostic inference engine
backend = YOLOBackend(
    model=model,
    device=DeviceType.MPS,       # or CPU, CUDA_0, TENSORRT, etc.
    category=CocoClass,          # Enum CLASS for label mapping
    task_type=TaskType.SEGMENT,
    threshold=0.35,
    iou=0.7,
    imgsz=640,
    half=False,
    refined=True                 # Enable high-quality mask generation
)

# 5. Use with Tracker (decoupled inference and tracking logic)
tracker = Tracker(id=0, backend=backend, max_length=30)

# 6. Process a frame
frame = np.zeros((1080, 1920, 3), dtype=np.uint8)  # Replace with your BGR frame
tracked_objects = tracker.track(frame, enable_tracking=True)

# 7. Access results
for obj in tracked_objects:
    print(f"ID: {obj.id}, Class: {obj.instance.label.name}, Conf: {obj.instance.conf:.2f}")
    # Access spatial data: obj.instance.box, obj.instance.polygon, obj.instance.obb
```

---

## 🧩 API Documentation

### 🔷 [acmenra_yolo](acmenra_yolo) / [yolo_backend.py](acmenra_yolo/yolo_backend.py)

> <details><summary><code>class YOLOBackend</code> - YOLO-specific inference backend using Ultralytics YOLO models.</summary><p>
>
> Concrete implementation of the `acmenra_cv.Backend` contract for YOLO models. Handles detection, segmentation, and OBB tasks with optimized processing for YOLO's output format.
>
> #### ⚙️ Properties (Strictly Validated)
> * 🟢 `model`: [YOLO](#yolo_backendpy) - Gets/sets the Ultralytics YOLO model instance. Triggers state refresh on change.
> * 🟢 `iou`: [float](#yolo_backendpy) - IoU threshold for NMS `[0.0, 1.0]`.
> * 🟢 `imgsz`: [int](#yolo_backendpy) - Inference image size in pixels (must be `> 0`, ideally multiple of 32).
> * 🟢 `half`: [bool](#yolo_backendpy) - FP16 inference flag (CUDA only).
> * 🟢 `refined`: [bool](#yolo_backendpy) - High-quality mask generation flag (maps to `retina_masks`).
>
> #### 🚀 Methods
> * 🔴 `predict()`: [Result](#yolo_backendpy) - Performs YOLO inference and converts results to normalized `Instance` objects. Supports detection, segmentation, and OBB modes. Accepts `max_det`, `track`, and `verbose` parameters. Automatically applies `retina_masks` based on `self.refined`. **Needs tests**.
> * 🔴 `_process_bbox_results()`: [List[Instance]](#yolo_backendpy) - _Private method_ processing YOLO bounding box results into `Instance` objects. **Needs tests**.
> * 🔴 `_process_obb_results()`: [List[Instance]](#yolo_backendpy) - _Private method_ processing YOLO OBB results into `Instance` objects with normalized coordinates. **Needs tests**.
> * 🔴 `_process_seg_results()`: [List[Instance]](#yolo_backendpy) - _Private method_ processing YOLO segmentation results into `Instance` objects with polygon masks. **Needs tests**.
> * 🔴 `normalize_xywhr()`: [list[float]](#yolo_backendpy) - _Static method_ explicitly normalizing `[cx, cy, w, h, angle_rad]` from pixels to `[0.0, 1.0]`. Angle remains in radians.
>
> </p></details>

---

## 📋 Requirements

**Core dependencies** (automatically installed):
```txt
acmenra-cv>=0.3.0.0
ultralytics>=8.0.0
torch>=1.8.0
opencv-python>=4.5.0
```

**Development dependencies**:
```txt
pytest>=7.0.0
black>=23.0.0
mypy>=1.0.0
```

---

## 🧪 Testing

The plugin includes comprehensive test suites with **DDT (Data-Driven Testing)** and extensive mocks to avoid downloading real weights during CI/CD:

```bash
# Run all plugin tests
pytest tests/

# Run specific backend tests
pytest tests/inference/backends/
```

Test coverage includes:
- ✅ Type validation (positive and negative paths for all properties)
- ✅ Range validation (boundary conditions for `iou`, `imgsz`, etc.)
- ✅ Edge cases (empty detections, OBB without tracking, extreme resolutions)
- ✅ Seamless integration with `acmenra_cv.Result` and `acmenra_cv.Tracker`

---

## 🔐 License

This project is licensed under the **GNU Affero General Public License v3 or later (AGPL-3.0-or-later)**, matching the core `acmenra-cv` framework.  
See the [LICENSE](LICENSE) file for details.

---

## 🌐 Links

- **PyPI**: https://pypi.org/project/acmenra-yolo/
- **Core Framework**: https://pypi.org/project/acmenra-cv/
- **Source**: https://github.com/Acmenra/acmenra-yolo
- **Documentation**: https://github.com/Acmenra/acmenra-yolo#readme
- **Issues**: https://github.com/Acmenra/acmenra-yolo/issues

---

> **acmenra.studio** — Building reliable vision systems for the edge.  
> *Every millisecond and frame buffer counts.* 🚀
