# Example Code Recipes & Notebook Migration Guide

Not every research workflow belongs in a locally executed Jupyter notebook: some tutorials run cleanly on a laptop CPU with synthetic or local data, while others require cloud GPUs (Google Colab), third-party cluster stacks (Ray, FiftyOne, SAHI), or legacy frameworks (Detectron2, YOLACT, SlowFast).

To keep **The Annolid Book** reliable and reproducible:

- **Runnable local tutorials** live as verified, self-contained `.ipynb` notebooks in the **Interactive Jupyter Notebooks** part of this book (every cell runs offline on synthetic demo data out of the box, or on your own video/CSV by changing a single path variable).
- **Cloud-GPU notebooks** remain directly launchable via one-click **Open in Colab** badges on [Running Annolid on Google Colab](Annolid_on_Google_Colab.md).
- **Non-runnable / external-framework / legacy examples** are distilled into copy-pasteable example code recipes right here, alongside their modern `annolid-run` and Python equivalents.

## Runnable Jupyter Book Notebooks

Open or download any of the five locally runnable notebooks included in this book:

| Notebook | What It Covers | Companion Guide |
| --- | --- | --- |
| [Extract Frames from a Video](../tutorials/Extract_frames_from_a_video.ipynb) | Video metadata, `uniform` / `kmeans` smart frame sampling, explicit frame indices, and batch folders | [Extracting Frames](extract_frames.md) |
| [Inter-Instance Distances & Kinematics](../tutorials/Annolid_post_processing_distances.ipynb) | Occlusion gap filling, IQR outlier filtering, path length, speed, pairwise distances, `TrackingResultsAnalyzer`, and `analyze_kinematics` | [Inter-Instance Distances](../tutorials/Calculate_distances_between_instances.md) |
| [Fix Left/Right Label Switches & Gaps](../tutorials/Annolid_post_processing_fix_left_right_switch.ipynb) | Arena midline swap repair, static landmark mode fill, rolling-window gap repair, and `evaluate_track_qc` audit | [Track QC & Reports](../tutorials/Reporting_and_track_qc.md) |
| [Mask Areas, Perimeters, IoU Merging & Batch Folders](../tutorials/Annolid_post_processing_masks_ious_and_areas.ipynb) | COCO RLE mask decoding, area/perimeter filtering, IoU-based overlap merging, and batch CSV folder cleanup | [COCO & Data Formats](../tutorials/COCO_and_data_formats.md) |
| [Digging Bout & ROI Overlap Analysis](../tutorials/Digging_Analysis_tutorial.ipynb) | Frame-to-timestamp conversion, smoothed `rat`–`cup` mask IoU bout detection, bout onset merging, and CSV export | [Behavior Scoring & Ethograms](../tutorials/Behavior_classification.md) |

---

## Example Code Recipes (Non-Runnable / External / Cloud Workflows)

The snippets below preserve the useful code patterns from historical `docs/tutorials/*.ipynb` notebooks that depend on private datasets, cloud GPUs, or third-party external libraries, paired with Annolid's current built-in workflows.

### 1. Cloud GPU Training & Sliced Inference (YOLO & SAHI)

For training **YOLO11 / YOLO26 / YOLOE** segmentation or pose models on cloud GPUs, prefer [Google Colab Studio](Annolid_on_Google_Colab.md) (`annolid-run colab`) or launch the official Colab notebooks directly. When detecting very small animals in wide high-resolution frames, combine Ultralytics weights with **SAHI** (Sliced Aided Hyper Inference):

```python
# Example pattern (requires: pip install sahi ultralytics torch)
from sahi import AutoDetectionModel
from sahi.predict import get_sliced_prediction

detection_model = AutoDetectionModel.from_pretrained(
    model_type="yolov8",
    model_path="/path/to/best.pt",
    confidence_threshold=0.3,
    device="cuda:0",  # or "cpu"
)

result = get_sliced_prediction(
    "/path/to/wide_arena_frame.png",
    detection_model,
    slice_height=512,
    slice_width=512,
    overlap_height_ratio=0.2,
    overlap_width_ratio=0.2,
)
print(f"Detected {len(result.object_prediction_list)} objects across slices.")
```

Modern built-in Annolid equivalent for training and inference:

```bash
# Train locally or dispatch to a Colab T4/L4/A100 GPU
annolid-run colab train yolo --data ./YOLO_dataset/data.yaml --weights yolo11s-seg.pt --gpu T4
annolid-run predict yolo_labelme --source /path/to/video.mp4 --weights /path/to/best.pt
```

### 2. Batch Video Inference & Distributed Worker Serving

Historical notebooks (`Annolid_video_batch_inference.ipynb` and `Annolid_inference_ray_cluster.ipynb`) demonstrated batch processing videos with `annolid.inference.predict.Segmentor` and serving frames over HTTP with Ray Serve. Modern Annolid projects can batch-process videos directly via `annolid-run` or wrap `Segmentor` inside a lightweight worker loop:

```python
# Modern batch CLI pattern (recommended — works with YOLO, Cutie, SAM3, pose models)
import subprocess
from pathlib import Path

for video in sorted(Path("/path/to/videos").glob("*.mp4")):
    subprocess.run(
        [
            "annolid-run",
            "predict",
            "yolo_labelme",
            "--source",
            str(video),
            "--weights",
            "/path/to/best.pt",
        ],
        check=True,
    )
```

Conceptual HTTP worker pattern (adapted from the legacy Ray Serve cluster example; requires `ray[serve]` + trained Detectron2 weights):

```python
# Example only — requires a trained Detectron2 checkpoint and Ray Serve 2.x
import cv2
import numpy as np
from ray import serve
from annolid.inference.predict import Segmentor


@serve.deployment(num_replicas=2)
class AnnolidFrameWorker:
    def __init__(self, dataset_dir: str, model_path: str):
        self.model = Segmentor(dataset_dir, model_path)

    async def __call__(self, request):
        payload = await request.body()
        buf = np.frombuffer(payload, dtype=np.uint8)
        frame = cv2.imdecode(buf, cv2.IMREAD_COLOR)
        return self.model.on_image(frame)
```

### 3. Model Evaluation (FiftyOne & Built-In Pose Evaluation)

To visually inspect COCO ground-truth vs. predicted masks in **FiftyOne** (adapted from `Annolid_model_evaluation.ipynb`, requires `pip install fiftyone` and a COCO dataset + trained model):

```python
# Example only — requires fiftyone + COCO validation dataset
import fiftyone

dataset = fiftyone.Dataset.from_dir(
    dataset_type=fiftyone.types.COCODetectionDataset,
    data_path="/path/to/my_coco_dataset/valid",
    labels_path="/path/to/my_coco_dataset/valid/annotations.json",
    label_types="segmentations",
)
# After attaching predictions to each sample under sample["predictions"]:
eval_results = dataset.evaluate_detections(
    "predictions",
    gt_field="ground_truth",
    eval_key="eval",
    compute_mAP=True,
)
eval_results.print_report()
```

Modern built-in Annolid alternatives (no external FiftyOne server required):

```bash
# Pose keypoint evaluation (PCK, OKS, RMSE, per-keypoint error tables)
annolid-run eval-pose ./gt_labelme ./pred_labelme --pose-schema ./pose_schema.json --output-dir ./pose_eval

# Track QC & prioritized manual review queue
annolid-run track-qc session_tracked.csv --expected-instances 2 --fps 30 --review-csv review_queue.csv
```

### 4. Video Embeddings & Natural-Language Behavior Search

The legacy `Annolid_Video_Embeddings.ipynb` notebook extracted backbone box-predictor `in_features` from a trained Detectron2 model to inspect clusters in TensorBoard Projector. Today, Annolid ships native, zero-PyTorch semantic frame search powered by **ONNX EmbeddingGemma 2**:

```bash
# Search hours of video using plain-English behavioral queries
annolid-run behavior-search /path/to/trial.mp4 \
  --query "mouse rearing near wall" \
  --stride 5 \
  --index-cache ./trial_eg2.npz \
  --json
```

See [Frame Search & Identity Repair](../tutorials/Frame_search_and_identity_repair.md) for GUI and Python usage.

### 5. Optical Flow & Supervised Video Behavior Classification

Historical research notebooks explored external optical-flow repos (**RAFT**, self-supervised optical flow) and **SlowFast** video clip classifiers (`pytorchvideo` / `fvcore`):

```python
# Example pattern (adapted from SlowFast tutorial; requires pytorchvideo + fvcore + pyav)
import torch

model = torch.hub.load("facebookresearch/pytorchvideo", "slowfast_r50", pretrained=True)
model = model.eval().to("cuda" if torch.cuda.is_available() else "cpu")
```

For day-to-day lab work, Annolid now builds these capabilities directly into the main package:

- **Mask-scoped Farnebäck optical flow & freezing bouts**: see [Freezing & Dense Motion Assays](../tutorials/Freezing_and%20motion_assays.md).
- **Polygon/pose Temporal Convolutional Network (TCN) classifiers & 1-second VLM ethogram labeling**: see [Behavior Scoring & Ethograms](../tutorials/Behavior_classification.md) and [TCN Behavior Classification](../tutorials/TCN_behavior_classification.md).

### 6. Zero-Shot Masking Prototypes & Legacy Detectron2 / YOLACT Reference

Earlier prototype notebooks (`zero_shot_object_detection_and_tracking_with_grounding_dino.ipynb`, `automatic_mask_generator_example.ipynb`, `yolov8_tracking_tutorial.ipynb`, `Follow_Anything.ipynb`) cloned external repositories in Colab. Today, Annolid integrates **SAM AI-Polygons**, **Grounding DINO → SAM text prompts**, **SAM3**, **Cutie**, **INSID3**, and **YOLO11/YOLO26** natively inside the desktop GUI and `annolid-run`.

For labs maintaining legacy **Detectron2** Mask R-CNN or **PointRend** datasets (`Annolid_on_Detectron2_Tutorial.ipynb`, `PointRend_in_Detectron2_Tutorial.ipynb`), the core dataset-registration pattern is:

```python
# Example only — requires detectron2 installed in a compatible CUDA/PyTorch environment
from detectron2.config import get_cfg
from detectron2.data.datasets import register_coco_instances
from detectron2.engine import DefaultPredictor
from detectron2 import model_zoo

register_coco_instances("annolid_train", {}, "/path/to/train/annotations.json", "/path/to/train")
register_coco_instances("annolid_val", {}, "/path/to/valid/annotations.json", "/path/to/valid")

cfg = get_cfg()
cfg.merge_from_file(
    model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
)
cfg.MODEL.WEIGHTS = "/path/to/model_final.pth"
cfg.MODEL.ROI_HEADS.NUM_CLASSES = 2
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
predictor = DefaultPredictor(cfg)
```

```{tip}
**Migrating off Detectron2 or YOLACT (`Train_networks_tutorial_v1.0.1.ipynb`)?** Export your LabelMe or COCO annotations directly to YOLO format via **`File → Convert Labelme to YOLO format`** (or `annolid-run index-to-yolo`), or track directly from a single seed frame with [Cutie](tracking_with_Cutie.md) or [SAM3](../tutorials/SAM3_video_tracking.md).
```

---

## Complete Migration Index (`docs/tutorials/*.ipynb`)

Every historical notebook in `docs/tutorials/` is preserved at its original GitHub path for backward compatibility with external links and Colab badges, and mapped to its current home below:

| Source Notebook (`docs/tutorials/`) | Classification | Current Destination |
| --- | --- | --- |
| `Extract_frames_from_a_video.ipynb` | Runnable Book Notebook | [Extract Frames from a Video](../tutorials/Extract_frames_from_a_video.ipynb) |
| `Annolid_post_processing_distances.ipynb` | Runnable Book Notebook | [Inter-Instance Distances & Kinematics](../tutorials/Annolid_post_processing_distances.ipynb) |
| `Annolid_post_processing_fix_left_right_switch.ipynb` | Runnable Book Notebook | [Fix Left/Right Label Switches & Gaps](../tutorials/Annolid_post_processing_fix_left_right_switch.ipynb) |
| `Annolid_post_processinng_masks_ious_and_areas.ipynb` | Runnable Book Notebook | [Mask Areas, Perimeters, IoU Merging & Batch Folders](../tutorials/Annolid_post_processing_masks_ious_and_areas.ipynb) |
| `Annolid_batch_post_processinng_tracking_csv_for_masks_ious_and_areas.ipynb` | Runnable Book Notebook (consolidated) | [Mask Areas, Perimeters, IoU Merging & Batch Folders](../tutorials/Annolid_post_processing_masks_ious_and_areas.ipynb) |
| `Digging_Analysis_tutorial.ipynb` | Runnable Book Notebook | [Digging Bout & ROI Overlap Analysis](../tutorials/Digging_Analysis_tutorial.ipynb) |
| `Annolid_Colab_Train_and_Inference.ipynb` | Active Colab GPU Notebook | [Google Colab Guide](Annolid_on_Google_Colab.md) · [Open in Colab](https://colab.research.google.com/github/healthonrails/annolid/blob/main/docs/tutorials/Annolid_Colab_Train_and_Inference.ipynb) |
| `Annolid_Instance_Segmentation_on_YOLO_Tutorial.ipynb` | Active Colab GPU Notebook | [Google Colab Guide](Annolid_on_Google_Colab.md) · [Open in Colab](https://colab.research.google.com/github/healthonrails/annolid/blob/main/docs/tutorials/Annolid_Instance_Segmentation_on_YOLO_Tutorial.ipynb) |
| `Annolid_Pose_Estimation_on_YOLO_Tutorial.ipynb` | Active Colab GPU Notebook | [Google Colab Guide](Annolid_on_Google_Colab.md) · [Open in Colab](https://colab.research.google.com/github/healthonrails/annolid/blob/main/docs/tutorials/Annolid_Pose_Estimation_on_YOLO_Tutorial.ipynb) |
| `YOLO_SAHI_inference_for_ultralytics.ipynb` | Active Colab GPU Notebook / Example | Recipe 1 above · [Open in Colab](https://colab.research.google.com/github/healthonrails/annolid/blob/main/docs/tutorials/YOLO_SAHI_inference_for_ultralytics.ipynb) |
| `Annolid_video_batch_inference.ipynb` | Example Code Recipe (Cloud/Legacy) | Recipe 2 above · [Power-User CLI](Expert_mode_CLI_tools.md) |
| `Annolid_inference_ray_cluster.ipynb` | Example Code Recipe (Cluster) | Recipe 2 above |
| `Annolid_model_evaluation.ipynb` | Example Code Recipe (FiftyOne) | Recipe 3 above · [Track QC & Reports](../tutorials/Reporting_and_track_qc.md) |
| `Annolid_Video_Embeddings.ipynb` | Example Code Recipe / Superseded | Recipe 4 above · [Frame Search & Identity Repair](../tutorials/Frame_search_and_identity_repair.md) |
| `RAFT_optical_flow.ipynb` | Example Code Recipe / Superseded | Recipe 5 above · [Freezing & Dense Motion Assays](../tutorials/Freezing_and%20motion_assays.md) |
| `Self_supervised_optical_flow_estimation.ipynb` | Example Code Recipe / Research | Recipe 5 above · [Freezing & Dense Motion Assays](../tutorials/Freezing_and%20motion_assays.md) |
| `Annolid_behavior_video_classification_on_slowfast.ipynb` | Example Code Recipe / Superseded | Recipe 5 above · [TCN Behavior Classification](../tutorials/TCN_behavior_classification.md) |
| `zero_shot_object_detection_and_tracking_with_grounding_dino.ipynb` | Example Code Recipe / Integrated | Recipe 6 above · [Labeling Instances](labelling_images.md) & [SAM3](../tutorials/SAM3_video_tracking.md) |
| `automatic_mask_generator_example.ipynb` | Example Code Recipe / Integrated | Recipe 6 above · [Labeling Instances](labelling_images.md) |
| `yolov8_tracking_tutorial.ipynb` | Example Code Recipe / Integrated | Recipe 6 above · [Model Training](model_training.md) |
| `Follow_Anything.ipynb` | Example Code Recipe (External) | Recipe 6 above · [Realtime & Multi-Camera](../tutorials/Realtime_and_multicamera.md) |
| `Annolid_on_Detectron2_Tutorial.ipynb` | Legacy Colab / Example Code | Recipe 6 above · [Google Colab Guide](Annolid_on_Google_Colab.md) |
| `PointRend_in_Detectron2_Tutorial.ipynb` | Legacy Example Code | Recipe 6 above · [Model Training](model_training.md) |
| `Train_networks_tutorial_v1.0.1.ipynb` | Legacy Example Code (YOLACT) | Recipe 6 above · [Model Training](model_training.md) |
