> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mixpeek.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Review detections and improve a detector

> Review candidate detections, record verdicts as annotations, and turn them into YOLO training data.

Review candidate detections, record verdicts as annotations, and turn them into YOLO training data. Camera frames are cut into crops, verified examples label each crop, and a cluster shows the classes nobody has labeled yet.

> [card] [Jump to the manifest](#the-manifest)
>
> `annotations-improve-features.namespace.yaml`: apply it with one API call, then read the walkthrough below to change it.

## At a glance

| | |
| - | - |
| **Creates** | 1 namespace, 2 buckets, 2 collections, 2 retrievers, 1 taxonomy, 1 cluster |
| **Extractors** | [`image_extractor`](https://docs.mixpeek.com/docs/extract/extractors#image) v1 |
| **Daily spend budget** | 1 USD, set on the namespace. Queries are not capped. |
| **Sample data** | 12 objects, uploaded to `verified-objects`, `camera-frames` when you apply |

## How the pieces connect

Buckets hold what you upload, collections turn it into searchable documents, and retrievers answer queries over the collections.

```mermaid theme={null}
flowchart LR
  b0[("camera-frames")]
  b1[("verified-objects")]
  c2["frame-crops<br/>image_extractor v1"]
  c3["verified-set<br/>image_extractor v1"]
  r4{{"detection-review"}}
  r5{{"class-lookup"}}
  b0 --> c2
  b1 --> c3
  c2 --> r4
  c3 --> r5
```

## Deploy it

**1. Get the manifest**

```bash theme={null}
# Copy the manifest from the bottom of this page into annotations-improve-features.namespace.yaml
```

**2. Validate it**

Validate runs every check apply runs and creates nothing. Fix each entry in `errors`, then run it again.

```bash theme={null}
curl -X POST https://api.mixpeek.com/v1/manifest/validate \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -F "manifest_file=@annotations-improve-features.namespace.yaml"
```

**3. Apply it**

Apply creates every resource in one call. `wait_for_seed=true` also waits until the sample objects are processed, so the first query below has documents to return.

```bash theme={null}
curl -X POST "https://api.mixpeek.com/v1/manifest/apply?wait_for_seed=true" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -F "manifest_file=@annotations-improve-features.namespace.yaml"
```

The response lists each resource with its outcome in `resources`. Apply refuses a resource that already exists and rolls the whole apply back, so to apply the file again over this namespace add `?mode=create_missing`, which creates only what is missing.

## Run the first query

Look up the namespace id by name, then run `detection-review`. Check `status` and `warnings` along with `documents`: a run that times out still answers 200, with `status` `degraded`.

```bash cURL theme={null}
NAMESPACE_ID=$(curl -s https://api.mixpeek.com/v1/namespaces/annotations-improve-features \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" | jq -r .namespace_id)

curl -X POST https://api.mixpeek.com/v1/retrievers/detection-review/execute \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"inputs": {"query": "a car"}}' \
  | jq '{status, warnings, documents: [.documents[] | {document_id, score}]}'
```

```python Python theme={null}
import os, requests

AUTH = {"Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}"}
ns = requests.get("https://api.mixpeek.com/v1/namespaces/annotations-improve-features", headers=AUTH).json()

run = requests.post(
    "https://api.mixpeek.com/v1/retrievers/detection-review/execute",
    headers={**AUTH, "X-Namespace": ns["namespace_id"]},
    json={"inputs": {"query": "a car"}},
).json()

print(run["status"], run["warnings"])  # "completed" on a clean run
for doc in run["documents"]:
    print(doc["document_id"], doc["score"])
```

```javascript JavaScript theme={null}
const auth = { Authorization: `Bearer ${process.env.MIXPEEK_API_KEY}` };
const ns = await fetch("https://api.mixpeek.com/v1/namespaces/annotations-improve-features", { headers: auth }).then((r) => r.json());

const run = await fetch("https://api.mixpeek.com/v1/retrievers/detection-review/execute", {
  method: "POST",
  headers: { ...auth, "X-Namespace": ns.namespace_id, "Content-Type": "application/json" },
  body: JSON.stringify({"inputs": {"query": "a car"}}),
}).then((r) => r.json());

console.log(run.status, run.warnings); // "completed" on a clean run
for (const doc of run.documents) console.log(doc.document_id, doc.score);
```

## Add your own data

Each object you add to a bucket is processed by every collection that reads it. This adds one object to `camera-frames`. `NAMESPACE_ID` is the id from the namespace lookup above.

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/buckets/camera-frames/objects?auto_process=true" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"camera_id": "example", "blobs": [{"property": "image", "type": "image", "data": "https://example.com/photo.jpg"}]}'
```

```python Python theme={null}
import os, requests

HEADERS = {"Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}", "X-Namespace": os.environ["NAMESPACE_ID"]}

obj = requests.post(
    "https://api.mixpeek.com/v1/buckets/camera-frames/objects",
    params={"auto_process": "true"},
    headers=HEADERS,
    json={
        "camera_id": "example",
        "blobs": [
            {
                "property": "image",
                "type": "image",
                "data": "https://example.com/photo.jpg"
            }
        ]
    },
).json()
print(obj["object_id"], obj["status"])  # PENDING until processing finishes
```

```javascript JavaScript theme={null}
const headers = {
  Authorization: `Bearer ${process.env.MIXPEEK_API_KEY}`,
  "X-Namespace": process.env.NAMESPACE_ID,
  "Content-Type": "application/json",
};

const obj = await fetch("https://api.mixpeek.com/v1/buckets/camera-frames/objects?auto_process=true", {
  method: "POST",
  headers,
  body: JSON.stringify({
    "camera_id": "example",
    "blobs": [
      {
        "property": "image",
        "type": "image",
        "data": "https://example.com/photo.jpg"
      }
    ]
  }),
}).then((r) => r.json());
console.log(obj.object_id, obj.status); // PENDING until processing finishes
```

The object is `PENDING` until processing finishes, then `COMPLETED` or `FAILED`. [Buckets and objects](https://docs.mixpeek.com/docs/ingest/buckets.md) covers object states, retries and duplicates.

## Retrievers

### `detection-review`

The review queue: the crops that look most like a class you name, each with its frame, tile and camera.

**Stages:** [`feature_search`](https://docs.mixpeek.com/docs/retrieve/stages#feature-search)

**Searches:** `frame-crops`

| Input | Type | Required | Description |
| - | - | - | - |
| `query` | text | yes | The object class to review, in plain words, for example 'a car' |

### `class-lookup`

The taxonomy's matcher: the verified example closest to a crop's vector, if it scores at least min\_score.

**Stages:** [`feature_search`](https://docs.mixpeek.com/docs/retrieve/stages#feature-search)

**Searches:** `verified-set`

| Input | Type | Required | Description |
| - | - | - | - |
| `query_embedding` | array | yes | The crop's SigLIP vector, supplied by the taxonomy |

## Collections

Each collection runs one extractor over a bucket, or over another collection's documents.

> [accordion] frame-crops
>
> image\_extractor\@v1 over bucket camera-frames: each frame indexed whole (tile 0) and as 6 crops (tiles 1 to 6). Labeled by object-labeler; feeds detection-review and crop-groups.
>
> **Reads** bucket `camera-frames` with [`image_extractor`](https://docs.mixpeek.com/docs/extract/extractors#image) v1.
>
> **Inputs:** `image` ← `image`
>
> **Copied onto each document:** `camera_id`

> [accordion] verified-set
>
> image\_extractor\@v1 over bucket verified-objects. The examples object-labeler matches each crop against.
>
> **Reads** bucket `verified-objects` with [`image_extractor`](https://docs.mixpeek.com/docs/extract/extractors#image) v1.
>
> **Inputs:** `image` ← `image`
>
> **Copied onto each document:** `object_class`

## Also created

**[Taxonomies](https://docs.mixpeek.com/docs/enrich/taxonomies.md)**

* `object-labeler`: Copies object\_class from the closest verified example onto each crop.

**[Clusters](https://docs.mixpeek.com/docs/enrich/clusters.md)**

* `crop-groups`: Groups the crops by appearance, to find object classes the verified set does not cover yet.

## The manifest

Every resource above comes from this file. Change it and apply it again with `?mode=upsert` to update what exists. [Manifests](https://docs.mixpeek.com/docs/manage/manifests.md) documents each field.

```yaml annotations-improve-features.namespace.yaml expandable theme={null}
# annotations-improve-features: one manifest spins up the namespace a detection review loop runs in.
# Camera frames are cut into a 3 x 2 grid of crops; each crop is a candidate detection a person
# reviews through detection-review and records a verdict on with the annotations API. Verified
# examples (one image per object class) label every crop through the object-labeler taxonomy, and
# a cluster groups the crops to show classes nobody has labeled yet.
# The crops stand in for a detector's boxes. A YOLO model deployed as a custom extractor needs a
# dedicated deployment and is created through the API, so it is not declared here.
# Validate with POST /v1/manifest/validate, apply with POST /v1/manifest/apply.
# Applying a SECOND time, over a namespace this template already created: use
# POST /v1/manifest/apply?mode=create_missing, which creates what is missing and leaves
# what exists alone. The default, create_only, fails the WHOLE apply and rolls it back if
# any resource already exists. Use mode=upsert to also patch resources that have drifted from this file.
version: '1.0'
metadata:
  name: annotations-improve-features
  description: "Guide template annotations-improve-features: camera frames cut into crops for detection review, a verified example set that labels them, and a cluster that groups them."
namespaces:
  - name: annotations-improve-features
    description: "Everything below lives in this namespace."
    feature_extractors:
      - name: image_extractor
        version: v1
    # Payload indexes. detection-review filters on tile_index inside the vector search,
    # which needs an index on the field.
    payload_indexes:
      - field_name: tile_index
        type: integer
    # Daily spend budget, in dollars of what you are charged (1,000 credits a dollar).
    # New batches pause once the namespace has spent this much today; queries are not capped.
    # Raise it later on the namespace: PATCH /v1/namespaces/<id> {"spend_budget": {"daily_usd": N}}.
    budget:
      daily_usd: 1

buckets:
  - name: camera-frames
    namespace: annotations-improve-features
    description: "Frames to review: one camera image per object, with the camera that took it in camera_id. Upload files here or write objects through the API."
    schema:
      properties:
        image:
          type: image
          required: true
        camera_id:
          type: string
  - name: verified-objects
    namespace: annotations-improve-features
    description: "Verified examples: one image of one object, with its class in object_class. Add the crops your reviewers confirm here."
    schema:
      properties:
        image:
          type: image
          required: true
        object_class:
          type: string
          required: true

collections:
  - name: frame-crops
    namespace: annotations-improve-features
    description: "image_extractor@v1 over bucket camera-frames: each frame indexed whole (tile 0) and as 6 crops (tiles 1 to 6). Labeled by object-labeler; feeds detection-review and crop-groups."
    source:
      type: bucket
      bucket: camera-frames
    feature_extractor:
      name: image_extractor
      version: v1
      parameters:
        tile_grid:
          cols: 3
          rows: 2
      input_mappings:
        image: image
      field_passthrough:
        - source_path: camera_id
    taxonomy_applications:
      - taxonomy: object-labeler
    enabled: true
  - name: verified-set
    namespace: annotations-improve-features
    description: "image_extractor@v1 over bucket verified-objects. The examples object-labeler matches each crop against."
    source:
      type: bucket
      bucket: verified-objects
    feature_extractor:
      name: image_extractor
      version: v1
      input_mappings:
        image: image
      field_passthrough:
        - source_path: object_class
    enabled: true

retrievers:
  - name: detection-review
    namespace: annotations-improve-features
    description: "The review queue: the crops that look most like a class you name, each with its frame, tile and camera."
    collections:
      - frame-crops
    input_schema:
      query:
        type: text
        required: true
        description: "The object class to review, in plain words, for example 'a car'"
    stages:
      - stage_name: candidates
        stage_id: feature_search
        pre_filters:
          AND:
            - field: tile_index
              operator: gte
              value: 1
        parameters:
          searches:
            - feature_uri: "mixpeek://image_extractor@v1/google_siglip_base_v1"
              query:
                input_mode: text
                value: "{{INPUT.query}}"
              top_k: 20
          final_top_k: 20
    tags:
      - template:annotations-improve-features
  - name: class-lookup
    namespace: annotations-improve-features
    description: "The taxonomy's matcher: the verified example closest to a crop's vector, if it scores at least min_score."
    collections:
      - verified-set
    input_schema:
      query_embedding:
        type: array
        required: true
        description: "The crop's SigLIP vector, supplied by the taxonomy"
    stages:
      - stage_name: match
        stage_type: filter
        stage_id: feature_search
        parameters:
          searches:
            - feature_uri: "mixpeek://image_extractor@v1/google_siglip_base_v1"
              query:
                input_mode: vector
                value: "{{INPUT.query_embedding}}"
              top_k: 1
              min_score: 0.30
          final_top_k: 1
    tags:
      - template:annotations-improve-features

taxonomies:
  - name: object-labeler
    namespace: annotations-improve-features
    description: "Copies object_class from the closest verified example onto each crop."
    config:
      taxonomy_type: flat
      retriever: class-lookup
      input_mappings:
        # The crop's stored vector, read by its vector name.
        - input_key: query_embedding
          source_type: vector
          path: image_extractor_v1_embedding
      source_collection:
        collection: verified-set
        enrichment_fields:
          - field_path: object_class
            target_field: object_class
            merge_mode: replace

clusters:
  - name: crop-groups
    namespace: annotations-improve-features
    description: "Groups the crops by appearance, to find object classes the verified set does not cover yet."
    source_collections:
      - frame-crops
    cluster_type: vector
    vector_config:
      feature_uris:
        - mixpeek://image_extractor@v1/google_siglip_base_v1
      clustering_method: kmeans
      algorithm_params:
        n_clusters: 4

# Street photographs from Mixpeek's public sample sets. Six verified examples cover four
# classes (car, person, bicycle, truck); six street scenes from two cameras are the frames
# to review, cut into 42 crop documents.
seed:
  - bucket: verified-objects
    max_objects: 6
    objects:
      - blobs: {image: samples/starter/images/mustang-san-francisco.jpg}
        object_class: car
      - blobs: {image: samples/curation/images/day/muscle-cars-at-rundle-street.jpg}
        object_class: car
      - blobs: {image: samples/curation/images/day/new-york-street-fashion.jpg}
        object_class: person
      - blobs: {image: samples/curation/images/day/doorman-on-leadenhall-street.jpg}
        object_class: person
      - blobs: {image: samples/curation/images/night/man-on-a-bicycle-at-night.jpg}
        object_class: bicycle
      - blobs: {image: samples/curation/images/night/boston-firetruck-parked-on-a-street-at-night.jpg}
        object_class: truck
  - bucket: camera-frames
    max_objects: 6
    objects:
      - blobs: {image: samples/curation/images/day/people-crossing-street.jpg}
        camera_id: cam-downtown
      - blobs: {image: samples/curation/images/day/crossing-the-street.jpg}
        camera_id: cam-downtown
      - blobs: {image: samples/curation/images/day/driving-outside-flinders-street-railway-station.jpg}
        camera_id: cam-downtown
      - blobs: {image: samples/curation/images/night/colorful-urban-traffic-at-night.jpg}
        camera_id: cam-overpass
      - blobs: {image: samples/curation/images/night/new-york-city-center-street-at-night-time.jpg}
        camera_id: cam-overpass
      - blobs: {image: samples/starter/images/los-angeles-8th-st.jpg}
        camera_id: cam-overpass
acceptance:
  max_cost_usd: 0.25
  steps:
    - name: verified-set-indexed
      kind: documents
      collection: verified-set
      expect: {min_documents: 6}
    - name: frames-cut-into-crops
      kind: documents
      collection: frame-crops
      expect: {min_documents: 42}
    - name: review-queue-answers
      kind: query
      retriever: detection-review
      inputs: {query: a car}
      expect: {min_results: 1}
```

## Hand it to an agent

Paste this prompt into Claude Code, Cursor or another coding agent. To give the agent this whole page instead, use **Copy page** in the menu at the top of the page, or point it at the page's Markdown at `https://mixpeek.com/docs/templates/annotations-improve-features.md`.

```text Prompt theme={null}
Set up the Mixpeek "Review detections and improve a detector" template in my organization. My API key is in MIXPEEK_API_KEY.
1. Save the manifest at the bottom of https://mixpeek.com/docs/templates/annotations-improve-features as annotations-improve-features.namespace.yaml.
2. POST it to https://api.mixpeek.com/v1/manifest/validate as the multipart field manifest_file, with the header Authorization: Bearer $MIXPEEK_API_KEY. Fix every entry in errors and validate again.
3. POST the same file to https://api.mixpeek.com/v1/manifest/apply?wait_for_seed=true. Every entry in resources should be created.
4. GET https://api.mixpeek.com/v1/namespaces/annotations-improve-features and keep namespace_id. Send it as the X-Namespace header on every call below.
5. POST {"inputs": {"query": "a car"}} to https://api.mixpeek.com/v1/retrievers/detection-review/execute. Read documents, check that status is completed, and print warnings.
Reference for this template: https://mixpeek.com/docs/templates/annotations-improve-features.md
```

## How it works

A detector proposes regions, people confirm or correct them, and the corrections become training data for a better detector. Here a grid of crops stands in for the detector until you deploy your own.

1. `frame-crops` runs [`image_extractor`](https://docs.mixpeek.com/docs/extract/extractors#image) over each image in `camera-frames` with a 3 by 2 `tile_grid`. Each frame becomes 7 documents sharing a `frame_key` (`<object_id>:0`): `tile_index` 0 is the whole frame, and 1 to 6 are the crops, row by row, each a candidate detection with its own SigLIP vector.
2. `detection-review` is the review queue. You name a class in words, and it returns the 20 closest crops. A `pre_filters` entry `tile_index` `gte` `1`, backed by a payload index, keeps whole frames out.
3. `verified-set` embeds `verified-objects`, where each image shows one object and carries its class in `object_class`.
4. The `object-labeler` [taxonomy](https://docs.mixpeek.com/docs/enrich/taxonomies.md) runs on `frame-crops` as each crop is processed. `class-lookup` finds the closest verified example scoring at least 0.30, and the taxonomy copies its `object_class` onto the crop.
5. `crop-groups` is a k-means [cluster](https://docs.mixpeek.com/docs/enrich/clusters.md) over the crop vectors, with 4 groups. You run it to look for classes the verified set is missing.

Each crop is a fixed sixth of the frame, so a "car" crop is the sixth that holds a car. The scripts below turn `tile_index` into a normalized `[x0, y0, x1, y1]` box. A frame processed before the verified set was indexed comes out unlabeled; [Grow the verified set](#grow-the-verified-set) labels it again.

## Review detections

**1. Open the review queue**

Run `detection-review` for one class. Keep `retriever_id` and `execution_id`, so each annotation records the run it judges.

```bash cURL theme={null}
RUN=$(curl -s -X POST https://api.mixpeek.com/v1/retrievers/detection-review/execute \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"inputs": {"query": "a car"}}')

echo "$RUN" | jq '{status, warnings, retriever_id, execution_id,
  documents: [.documents[] | {document_id, collection_id, frame_key, tile_index, camera_id, object_class, score}]}'
```

`object_class`, when present, is the taxonomy's guess.

**2. Record a verdict**

Stats count labels by exact string, so keep to one vocabulary. This guide uses four:

| Label | Meaning | Becomes |
| - | - | - |
| `confirmed` | The region holds the class the queue asked for | A positive training example |
| `corrected` | The region holds a different class | A positive example of the right class |
| `false_positive` | The region holds no object of interest | A negative, with no label line |
| `missed` | An object the queue should have returned and did not | A positive example the detector lacked |

Annotate the first result. `target.region` is the crop's box and `target.rank` its queue position; the export reads the class and frame from `payload`. For `missed`, also set `target.expected` to `true`.

```bash cURL theme={null}
DOC=$(echo "$RUN" | jq -c '.documents[0]')
TILE=$(echo "$DOC" | jq -r .tile_index)
BBOX=$(jq -nc --argjson t "$TILE" '(($t - 1) % 3) as $c | (($t - 1) / 3 | floor) as $r | [$c / 3, $r / 2, ($c + 1) / 3, ($r + 1) / 2]')

curl -s -X POST https://api.mixpeek.com/v1/annotations \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --argjson doc "$DOC" --argjson run "$RUN" --argjson bbox "$BBOX" '{
    document_id: $doc.document_id,
    collection_id: $doc.collection_id,
    label: "confirmed",
    confidence: 1.0,
    payload: {predicted_class: "car", true_class: "car", frame_key: $doc.frame_key},
    target: {region: {page: 1, bbox: $bbox}, rank: 1},
    retriever_id: $run.retriever_id,
    execution_id: $run.execution_id
  }')" | jq '{annotation_id, label, target_kind}'
```

Fix a wrong verdict with `PATCH /v1/annotations/{annotation_id}`; earlier versions stay at `.../versions`.

**3. Record the rest of the queue in one call**

`POST /v1/annotations/bulk` takes up to 1,000 creates, and `results` reports each outcome, so retry only the failures. This marks results 2 and 3 of the run above:

```bash cURL theme={null}
BULK=$(echo "$RUN" | jq -c '
  def bbox($t): (($t - 1) % 3) as $c | (($t - 1) / 3 | floor) as $r | [$c / 3, $r / 2, ($c + 1) / 3, ($r + 1) / 2];
  {create: [
    (.documents[1] as $d | {document_id: $d.document_id, collection_id: $d.collection_id, label: "corrected",
      reasoning: "The vehicle is a truck.",
      payload: {predicted_class: "car", true_class: "truck", frame_key: $d.frame_key},
      target: {region: {page: 1, bbox: bbox($d.tile_index)}, rank: 2},
      retriever_id: .retriever_id, execution_id: .execution_id}),
    (.documents[2] as $d | {document_id: $d.document_id, collection_id: $d.collection_id, label: "false_positive",
      reasoning: "Road surface, no vehicle.",
      payload: {predicted_class: "car", frame_key: $d.frame_key},
      target: {region: {page: 1, bbox: bbox($d.tile_index)}, rank: 3},
      retriever_id: .retriever_id, execution_id: .execution_id})
  ]}')

curl -s -X POST https://api.mixpeek.com/v1/annotations/bulk \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d "$BULK" | jq '{created_count, failed_count, results}'
```

## Measure

`GET /v1/annotations/stats` counts annotations by label for one `collection_id`. The scripts below read it from `COLLECTION_ID`, exported here.

```bash cURL theme={null}
export COLLECTION_ID=$(echo "$RUN" | jq -r '.documents[0].collection_id')

curl -s "https://api.mixpeek.com/v1/annotations/stats?collection_id=$COLLECTION_ID" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  | jq '{total, by_label, confirmed_rate: ((.by_label.confirmed // 0) / ([.total, 1] | max))}'
```

The share of `confirmed` is the queue's precision for the classes you reviewed; many `corrected` point at confused classes (read their `payload.true_class`). Stats are cumulative. To compare periods or retrievers, `POST /v1/annotations/list` filters by `collection_id`, `label`, `retriever_id` and `actor_id`, and `as_of` returns the set as it stood at an instant.

## Export and fine-tune

Every `confirmed` and `corrected` annotation is a labeled box. This script writes them in the YOLO layout: `images/`, `labels/` and a `data.yaml` listing the classes.

```python export_yolo.py theme={null}
import os
import pathlib

import requests

API = "https://api.mixpeek.com"
HEADERS = {"Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}", "X-Namespace": os.environ["NAMESPACE_ID"]}
COLLECTION_ID = os.environ["COLLECTION_ID"]
OUT = pathlib.Path("dataset")

def annotations(label):
    """Every annotation with this label on the collection, 500 a page."""
    found, skip = [], 0
    while True:
        page = requests.post(
            f"{API}/v1/annotations/list",
            params={"skip": skip, "limit": 500},
            headers=HEADERS,
            json={"collection_id": COLLECTION_ID, "label": label},
        ).json()
        found += page["results"]
        skip += len(page["results"])
        if not page["results"] or skip >= page["total_count"]:
            return found

boxes = {}  # object_id -> [(class name, bbox)]
for ann in annotations("confirmed") + annotations("corrected"):
    region = (ann.get("target") or {}).get("region")
    payload = ann.get("payload") or {}
    name = payload.get("true_class")
    if not region or not name or "frame_key" not in payload:
        continue
    object_id = payload["frame_key"].split(":")[0]
    boxes.setdefault(object_id, []).append((name, region["bbox"]))

classes = sorted({name for rows in boxes.values() for name, _ in rows})
(OUT / "images").mkdir(parents=True, exist_ok=True)
(OUT / "labels").mkdir(parents=True, exist_ok=True)

for object_id, rows in boxes.items():
    obj = requests.get(
        f"{API}/v1/buckets/camera-frames/objects/{object_id}",
        params={"return_presigned_urls": "true"},
        headers=HEADERS,
    ).json()
    blob = next(b for b in obj["blobs"] if b["property"] == "image")
    (OUT / "images" / f"{object_id}.jpg").write_bytes(requests.get(blob["presigned_url"]).content)
    with open(OUT / "labels" / f"{object_id}.txt", "w") as f:
        for name, (x0, y0, x1, y1) in rows:
            f.write(f"{classes.index(name)} {(x0 + x1) / 2:.6f} {(y0 + y1) / 2:.6f} {x1 - x0:.6f} {y1 - y0:.6f}\n")

with open(OUT / "data.yaml", "w") as f:
    f.write(f"path: {OUT.resolve()}\ntrain: images\nval: images\nnames:\n")
    for i, name in enumerate(classes):
        f.write(f"  {i}: {name}\n")

print(f"{sum(len(r) for r in boxes.values())} boxes on {len(boxes)} frames, classes: {classes}")
```

```bash Run the export theme={null}
python export_yolo.py
```

Fine-tune on any machine with a GPU, for example with Ultralytics:

```python finetune.py theme={null}
from ultralytics import YOLO

model = YOLO("yolov8m.pt")
model.train(data="dataset/data.yaml", epochs=50, imgsz=640, batch=16, name="detector_v2")
model.export(format="torchscript")
```

> [!WARNING]
>
> `data.yaml` above trains and validates on the same images, which says nothing about accuracy. Hold out frames and set `val` to them before you trust a model.

## Put the corrections back

### Grow the verified set

Each `confirmed` or `corrected` crop is a verified example of its `true_class`. This script (it needs Pillow) cuts each crop out of its frame and adds it to `verified-objects`.

```python promote_verified.py theme={null}
import base64
import io
import os

import requests
from PIL import Image

API = "https://api.mixpeek.com"
HEADERS = {"Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}", "X-Namespace": os.environ["NAMESPACE_ID"]}
COLLECTION_ID = os.environ["COLLECTION_ID"]

for label in ("confirmed", "corrected"):
    page = requests.post(
        f"{API}/v1/annotations/list",
        params={"limit": 500},
        headers=HEADERS,
        json={"collection_id": COLLECTION_ID, "label": label},
    ).json()
    for ann in page["results"]:
        payload = ann.get("payload") or {}
        region = (ann.get("target") or {}).get("region")
        if not region or not payload.get("true_class") or "frame_key" not in payload:
            continue
        object_id = payload["frame_key"].split(":")[0]
        obj = requests.get(
            f"{API}/v1/buckets/camera-frames/objects/{object_id}",
            params={"return_presigned_urls": "true"},
            headers=HEADERS,
        ).json()
        blob = next(b for b in obj["blobs"] if b["property"] == "image")
        frame = Image.open(io.BytesIO(requests.get(blob["presigned_url"]).content)).convert("RGB")
        x0, y0, x1, y1 = region["bbox"]
        w, h = frame.size
        crop = frame.crop((int(x0 * w), int(y0 * h), int(x1 * w), int(y1 * h)))
        buf = io.BytesIO()
        crop.save(buf, format="JPEG", quality=90)
        created = requests.post(
            f"{API}/v1/buckets/verified-objects/objects",
            params={"auto_process": "true"},
            headers=HEADERS,
            json={
                "object_class": payload["true_class"],
                "blobs": [{
                    "property": "image",
                    "type": "image",
                    "data": "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode(),
                }],
            },
        ).json()
        print(payload["true_class"], created.get("object_id"), created.get("status"))
```

When the new examples are processed, apply `object-labeler` to `frame-crops` again with `reapply_all: true`, and poll the returned task until `COMPLETED`:

```bash cURL theme={null}
TAXONOMY_ID=$(curl -s https://api.mixpeek.com/v1/taxonomies/object-labeler \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" | jq -r .taxonomy_id)

curl -s -X POST https://api.mixpeek.com/v1/collections/frame-crops/apply-taxonomy \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d "{\"taxonomy_id\": \"$TAXONOMY_ID\", \"reapply_all\": true}" \
  | jq '{task_id, status, estimated_documents}'
```

Raise `min_score: 0.30` on `class-lookup` to label fewer crops with fewer mistakes. [Bootstrap a labeled dataset](https://docs.mixpeek.com/docs/templates/bootstrap-labeled-dataset.md) covers this matching loop.

### Deploy the fine-tuned detector

A trained detector runs as a [custom extractor](https://docs.mixpeek.com/docs/extract/custom-extractors.md), which needs a dedicated deployment; the [custom extractor quickstart](https://docs.mixpeek.com/docs/templates/custom-extractor-quickstart.md) walks through it. Once deployed:

1. Create a collection over `camera-frames` that runs it. A collection's extractor cannot change, so the detector gets its own collection beside `frame-crops`.
2. Point a copy of `detection-review` at it. If it writes a `confidence` per detection, a `pre_filters` entry `confidence` `lt` `0.7` (with a payload index) sends reviewers the least certain detections.
3. Annotate its results the same way, with `target.region` from the detector's own box.
4. Ship each retrained model as a new extractor version. The version is part of the feature URI, so two versions run side by side while you compare their review stats.

## Automate the loop

### Get a request on every verdict

A webhook calls your server on each annotation event, so it can count corrections toward the next retrain or run `promote_verified.py` without polling. Webhooks belong to the organization, so the call takes no `X-Namespace` header.

```bash cURL theme={null}
curl -s -X POST https://api.mixpeek.com/v1/organizations/webhooks \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "webhook_name": "detection-review-events",
    "event_types": ["annotation.created", "annotation.updated", "collection.documents.written"],
    "channels": [{"channel": "webhook", "configs": {"url": "https://your-app.example.com/webhooks/detections"}}]
  }' | jq '{webhook_id, event_types, is_active}'
```

`collection.documents.written` fires when a new detector version finishes processing frames. Add a `signing_secret` to `configs` and each delivery carries an `X-Mixpeek-Signature` header your server can verify.

### Find classes nobody has labeled

A `crop-groups` group whose members carry no `object_class` is a class missing from `verified-objects`. Run the cluster, then read its groups:

```bash cURL theme={null}
CLUSTER_ID=$(curl -s https://api.mixpeek.com/v1/clusters/crop-groups \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" | jq -r .cluster_id)

curl -s -X POST "https://api.mixpeek.com/v1/clusters/$CLUSTER_ID/execute" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{}' | jq '{task_id, status}'

# When the task is COMPLETED (GET /v1/tasks/{task_id}):
curl -s "https://api.mixpeek.com/v1/clusters/$CLUSTER_ID/groups" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  | jq '{run_id, total_groups, groups: [.groups[] | {cluster_id, label, member_count}]}'
```

Raise `n_clusters` in `crop-groups` as the frames grow:

```yaml crop-groups vector_config theme={null}
      algorithm_params:
        n_clusters: 8
```

To name a new class, add a few of the group's crops to `verified-objects` with an `object_class` and apply the taxonomy again. [Clusters](https://docs.mixpeek.com/docs/enrich/clusters.md) covers the other methods.

## Change it

Each change edits the manifest. Apply it again with `?mode=upsert`.

* **A finer grid.** `tile_grid` takes 1 to 4 columns and rows. A 4 x 3 grid makes 13 documents per frame, about twice the cost. Update the bbox math to the new grid, and apply to a new namespace, since the grid decides which documents exist.
* **Review one camera.** Add a second `pre_filters` entry on `camera_id`, with a `keyword` payload index on `camera_id`, for a queue per camera.
* **Rank frames, not crops.** Add a `group_by` stage on `frame_key` with `max_per_group: 1` after the search, to review each frame once by its best crop.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.