Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@ All notable changes to this project will be documented in this file.
`confidence` (0.5 when omitted) unless `confidence_thresholds` sets it.
`workflow_inputs` / `--workflow-inputs` fill the Workflow's other inputs
([#594](https://github.com/roboflow/roboflow-python/pull/594)).
- Label by Example:
`Project.autolabel("batch-id", model="gemini-4-argon-boxes", reference_examples=["image-id-1", "image-id-2"])`
and `roboflow autolabel start --reference-example image-id-1
--reference-example image-id-2` show the model up to 10 labeled images of
the project, with their boxes of the job's classes, before every image it
labels. `Project.autolabel_preview` and `roboflow autolabel preview` take
them too, and `roboflow autolabel models` marks the models that take them
(`takesReferenceExamples` in `Workspace.autolabel_models()`)
([#595](https://github.com/roboflow/roboflow-python/pull/595)).

### Changed

Expand Down
13 changes: 11 additions & 2 deletions CLI-COMMANDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -333,12 +333,15 @@ roboflow autolabel start -p my-actions --batch-id <video-batch-id> -m video-segm
--ontology '{"a person jumps": "jump"}' --model-options '{"sampleFps": 2}'
roboflow autolabel start -p my-project --batch-id <batch-id> -m vehicle-detector --model-type workflow \
--workflow-output predictions --class-mapping '{"car": "vehicle", "truck": "vehicle"}' --confidence 0.4
roboflow autolabel start -p my-project --batch-id <batch-id> -m gemini-4-argon-boxes \
--ontology '{"a green umbrella": "umbrella"}' --reference-example <image-id> --reference-example <image-id>
roboflow autolabel job <job-id>
roboflow autolabel job <job-id> -p other-workspace/my-project
```

`models` lists the catalog for the workspace (id, the project types each
model labels, availability, credits per image, default). `preview` runs one
model labels, availability, credits per image, default, and whether it takes
reference examples). `preview` runs one
image through a model for free so you can compare candidates before spending
credits. `start` creates the job and prints
`jobId` and `annotationJobId`; poll it with `job`. Pass the ontology either as
Expand All @@ -360,7 +363,11 @@ model whose project types in `models` include `keypoint-detection` (ex:
`gemini-4-argon-keypoints`), which places the keypoints of each class skeleton;
classes without a skeleton get no labels. With a trained keypoint model,
`--keypoint-confidence` sets the lowest confidence a keypoint needs to be saved
as visible (server default 0.6). Action-recognition projects
as visible (server default 0.6). `--reference-example`, repeated for up to 10
images, shows the model labeled images of the project as examples (Label by
Example): each must be in the project's dataset, not only in a batch or in
review, with a box of the job's classes, and only the models marked in the
`EXAMPLES` column of `models` take them. Action-recognition projects
label a batch of up to 50 videos with `-m video-segment` (it is not in
`models`): the ontology maps one action description to each class, and the
class must already exist in the project. `--model-options '{"sampleFps": n}'`
Expand Down Expand Up @@ -390,6 +397,8 @@ job = project.autolabel("batch-id", model="gpt-6-2-sol-boxes", ontology={"a cat"
size_filter={"minWidth": 20, "minHeight": 20})
job = project.autolabel("batch-id", model="vehicle-detector", model_type="workflow",
workflow_output="predictions", class_mapping={"car": "vehicle"})
job = project.autolabel("batch-id", model="gemini-4-argon-boxes", ontology={"a green umbrella": "umbrella"},
reference_examples=["image-id-1", "image-id-2"])
project.autolabel_job(job["jobId"])["status"]
```

Expand Down
20 changes: 19 additions & 1 deletion roboflow/adapters/rfapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1506,6 +1506,15 @@ def _autolabel_response(response):
return _json_response_or_raise(response)


def _reference_examples_payload(image_ids):
"""``referenceExamples``: each labeled image of the project the model sees, by its id."""
if image_ids is None:
return None
if isinstance(image_ids, str):
image_ids = [image_ids]
return [{"imageId": image_id} for image_id in image_ids]


def list_autolabel_models(api_key, workspace_url):
"""Fetch the foundation-model catalog for hosted auto-labeling.

Expand All @@ -1531,13 +1540,16 @@ def preview_autolabel(
image,
ontology=None,
confidence_threshold=None,
reference_examples=None,
):
"""Preview one image with a foundation model before starting a job.

Calls ``POST /:workspace/:project/autolabel/preview``. Free: no job is
created and no credits are spent. ``image`` is
``{"type": "url" | "base64", "value": ...}`` and ``ontology`` is keyed by
prompt: ``{"kitten": "cat"}`` labels prompt matches as class ``cat``.
``reference_examples`` lists the ids of labeled images of the project the
model sees as examples (Label by Example); see ``Project.autolabel``.
Returns
``{model, predictions, summary, blockErrors?}``.
"""
Expand All @@ -1546,6 +1558,8 @@ def preview_autolabel(
payload["ontology"] = ontology
if confidence_threshold is not None:
payload["confidenceThreshold"] = confidence_threshold
if reference_examples is not None:
payload["referenceExamples"] = _reference_examples_payload(reference_examples)
response = http.post(
f"{API_URL}/{workspace_url}/{project_url}/autolabel/preview",
params={"api_key": api_key},
Expand All @@ -1571,6 +1585,7 @@ def start_autolabel_job(
existing_annotations=None,
keypoint_confidence_threshold=None,
size_filter=None,
reference_examples=None,
workflow_id=None,
selected_output_name=None,
image_input_name=None,
Expand Down Expand Up @@ -1601,7 +1616,9 @@ class it maps to, and optionally ``imageInputName`` (the worker defaults
predicted keypoint needs to be saved as visible; the server default is
0.6. ``size_filter`` is sent as ``sizeFilter``: any of ``minWidth``,
``maxWidth``, ``minHeight`` and ``maxHeight`` in image pixels, e.g.
``{"minWidth": 20, "maxWidth": 400}``. Returns
``{"minWidth": 20, "maxWidth": 400}``. ``reference_examples`` lists the
ids of labeled images of the project the model sees as examples (Label by
Example), sent as ``referenceExamples``. Returns
``{jobId, annotationJobId, message}``.

Raises:
Expand All @@ -1618,6 +1635,7 @@ class it maps to, and optionally ``imageInputName`` (the worker defaults
"modelOptions": model_options,
"keypointConfidenceThreshold": keypoint_confidence_threshold,
"sizeFilter": size_filter,
"referenceExamples": _reference_examples_payload(reference_examples),
"workflowId": workflow_id,
"workspaceName": workspace_url if workflow_id is not None else None,
"selectedOutputName": selected_output_name,
Expand Down
23 changes: 21 additions & 2 deletions roboflow/cli/handlers/autolabel.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ def preview(
confidence: Annotated[
Optional[float], typer.Option("--confidence", help="Detection threshold from 0.0 to 1.0 (sam3 only)")
] = None,
reference_examples: Annotated[
Optional[list[str]],
typer.Option(
"--reference-example",
help="Label by Example: ID of a labeled image of the project the model sees as an example; repeat for "
"up to 10. Only models with EXAMPLES in 'autolabel models' take them",
),
] = None,
) -> None:
"""Preview one image with a foundation model. Free: no job is created. Not available for video-segment."""
args = ctx_to_args(ctx, project=project)
Expand All @@ -54,6 +62,7 @@ def preview(
image=resolved_image,
ontology=resolved_ontology,
confidence_threshold=confidence,
reference_examples=reference_examples,
),
)

Expand Down Expand Up @@ -183,6 +192,14 @@ def start(
"--workflow-image-input", help="Workflow jobs: the Workflow input that takes the image (default: image)"
),
] = None,
reference_examples: Annotated[
Optional[list[str]],
typer.Option(
"--reference-example",
help="Label by Example: ID of a labeled image of the project the model sees as an example; repeat for "
"up to 10. Only models with EXAMPLES in 'autolabel models' take them",
),
] = None,
) -> None:
"""Start a hosted auto-label job over a batch of images, or of videos with -m video-segment.

Expand Down Expand Up @@ -231,6 +248,7 @@ def start_job(key: str, workspace: str, proj: str) -> Any:
),
keypoint_confidence_threshold=keypoint_confidence,
size_filter=size_filter,
reference_examples=reference_examples,
**workflow,
)

Expand Down Expand Up @@ -372,13 +390,14 @@ def table(data: Any) -> str:
"default": "yes" if model.get("isDefault") else "",
"credits": model.get("creditsPerImage", ""),
"ontology": model.get("ontologyFormat", ""),
"examples": "yes" if model.get("takesReferenceExamples") else "",
}
for model in data.get("models", [])
]
return format_table(
rows,
columns=["id", "name", "project_types", "available", "default", "credits", "ontology"],
headers=["ID", "NAME", "PROJECT TYPES", "AVAILABLE", "DEFAULT", "CREDITS/IMAGE", "ONTOLOGY"],
columns=["id", "name", "project_types", "available", "default", "credits", "ontology", "examples"],
headers=["ID", "NAME", "PROJECT TYPES", "AVAILABLE", "DEFAULT", "CREDITS/IMAGE", "ONTOLOGY", "EXAMPLES"],
)

_workspace_command(args, lambda key, workspace: _rfapi().list_autolabel_models(key, workspace), text=table)
26 changes: 26 additions & 0 deletions roboflow/core/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -1384,6 +1384,7 @@ def autolabel_preview(
image: str,
ontology: Optional[_AutolabelOntology] = None,
confidence_threshold: Optional[float] = None,
reference_examples: Optional[List[str]] = None,
) -> Dict:
"""Preview one image with a foundation model before starting an auto-label job.

Expand All @@ -1404,6 +1405,9 @@ def autolabel_preview(
dataset's own classes.
confidence_threshold: Detection threshold between 0.0 and 1.0
(sam3 only; other models ignore it).
reference_examples: Label by Example: ids of labeled images of this
project the model sees as examples, as ``Project.autolabel``
takes them, to check them on a sample before the job.

Returns:
Dict: ``{model, predictions, summary, blockErrors?}``. ``summary.byClass``
Expand All @@ -1420,6 +1424,7 @@ def autolabel_preview(
image=_autolabel_image_payload(image),
ontology=_autolabel_ontology_payload(ontology),
confidence_threshold=confidence_threshold,
reference_examples=reference_examples,
)

def autolabel(
Expand All @@ -1442,6 +1447,7 @@ def autolabel(
workflow_output: Optional[str] = None,
workflow_inputs: Optional[Dict[str, Any]] = None,
workflow_image_input: Optional[str] = None,
reference_examples: Optional[List[str]] = None,
) -> Dict:
"""Start a hosted auto-label job over a batch of images, or of videos.

Expand Down Expand Up @@ -1555,6 +1561,19 @@ class given by its own name
other inputs, by input name, e.g. ``{"confidence": 0.3}``.
workflow_image_input: Workflow jobs only. The Workflow input that
takes the image (server default: ``"image"``).
reference_examples: Label by Example: ids of up to 10 labeled
images of this project, which the model sees with their boxes
of the job's classes before every image it labels, e.g.
``["image-id-1", "image-id-2"]`` (the ``id`` of an image from
``search(class_name="umbrella", in_dataset=True)``). Each must be
in the project's dataset, not only in a batch or in review, and
have at least one box of those classes. Only the models with
``takesReferenceExamples`` in ``Workspace.autolabel_models()``
take them, on object- and keypoint-detection projects. The
server refuses an image the project does not have
(``REFERENCE_EXAMPLE_NOT_FOUND``), and examples for any other
model or with more than one prompt for a class in ``ontology``
(``INVALID_REFERENCE_EXAMPLES``).

Returns:
Dict: ``{jobId, annotationJobId, message}``. Poll progress with
Expand All @@ -1575,6 +1594,12 @@ class given by its own name

>>> job = project.autolabel("batch-id", model="gemini-4-argon-keypoints")

Show the model labeled images of the project (Label by Example):

>>> job = project.autolabel("batch-id", model="gemini-4-argon-boxes",
... ontology={"a green umbrella": "umbrella"},
... reference_examples=["image-id-1", "image-id-2"])

Label a batch of videos in an action-recognition project:

>>> job = project.autolabel("video-batch-id", model="video-segment",
Expand Down Expand Up @@ -1626,6 +1651,7 @@ class given by its own name
existing_annotations=existing_annotations,
keypoint_confidence_threshold=keypoint_confidence_threshold,
size_filter=size_filter,
reference_examples=reference_examples,
**workflow,
)

Expand Down
7 changes: 4 additions & 3 deletions roboflow/core/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1765,9 +1765,10 @@ def autolabel_models(self) -> dict:
models (which label mode they take), ``outputFormat``,
``ontologyFormat``, ``fixedConfidence``, ``defaultConfidenceThreshold``
when a job starts at one, ``minClasses`` / ``maxClasses`` when the
model limits the class count, ``creditsPerImage``, ``isDefault``, and
``available`` with an ``unavailableReason`` when the workspace plan
blocks a model.
model limits the class count, ``creditsPerImage``, ``isDefault``,
``takesReferenceExamples`` when the model takes labeled examples (the
``reference_examples`` of ``Project.autolabel``), and ``available``
with an ``unavailableReason`` when the workspace plan blocks a model.

Example:
>>> for m in ws.autolabel_models()["models"]:
Expand Down
26 changes: 26 additions & 0 deletions tests/adapters/test_autolabel.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,32 @@ def test_start_job_contract_full_payload(self, mock_post):
},
)

@patch("roboflow.util.http.requests.post")
def test_reference_examples_are_sent_as_image_ids(self, mock_post):
mock_post.return_value = _response({"jobId": "job-1"})
image = {"type": "url", "value": "https://example.com/cat.jpg"}

rfapi.preview_autolabel(
"key", "ws", "proj", model_type="gemini-4-argon-boxes", image=image, reference_examples=["img-1", "img-2"]
)
self.assertEqual(
mock_post.call_args.kwargs["json"],
{
"modelType": "gemini-4-argon-boxes",
"image": image,
"referenceExamples": [{"imageId": "img-1"}, {"imageId": "img-2"}],
},
)

# One id on its own is one example, not one per character.
rfapi.start_autolabel_job(
"key", "ws", "proj", batch_id="batch-1", model_type="gemini-4-argon-boxes", reference_examples="img-1"
)
self.assertEqual(
mock_post.call_args.kwargs["json"],
{"batchId": "batch-1", "modelType": "gemini-4-argon-boxes", "referenceExamples": [{"imageId": "img-1"}]},
)

@patch("roboflow.util.http.requests.post")
def test_start_workflow_job_contract(self, mock_post):
mock_post.return_value = _response({"jobId": "job-1"})
Expand Down
43 changes: 42 additions & 1 deletion tests/cli/test_autolabel_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,33 @@ def test_table_shows_the_project_types_each_model_labels(self, _resolve, mock_ap
{"id": "any-type-model", "projectTypes": None},
]
}
result = runner.invoke(app, ["autolabel", "models"])
# Wide enough that no cell is cut to fit the terminal.
result = runner.invoke(app, ["autolabel", "models"], env={"COLUMNS": "200"})
self.assertEqual(result.exit_code, 0, result.output)
lines = {line.split()[0]: line for line in result.output.splitlines() if line.strip()}
self.assertIn("PROJECT TYPES", lines["ID"])
self.assertIn("keypoint-detection", lines["gemini-4-argon-keypoints"])
self.assertIn("all but classification, keypoint-detection", lines["sam3-rle"])
self.assertIn(" all ", lines["any-type-model"])

@patch("roboflow.adapters.rfapi.list_autolabel_models")
@patch(_RESOLVE_WORKSPACE, return_value=("ws", "key"))
def test_table_marks_the_models_that_take_reference_examples(self, _resolve, mock_api):
mock_api.return_value = {
"models": [
{"id": "gemini-4-argon-boxes", "takesReferenceExamples": True},
{"id": "sam3-rle", "takesReferenceExamples": False},
]
}
result = runner.invoke(app, ["autolabel", "models"])
self.assertEqual(result.exit_code, 0, result.output)
rows = [line for line in result.output.splitlines() if line.strip()]
start = rows[0].index("EXAMPLES")
self.assertEqual(
{row.split()[0]: row[start:].strip() for row in rows[2:]},
{"gemini-4-argon-boxes": "yes", "sam3-rle": ""},
)

@patch("roboflow.adapters.rfapi.list_autolabel_models", return_value={"models": [{"id": "sam3-rle"}]})
@patch(_RESOLVE_WORKSPACE, return_value=("ws", "key"))
def test_json_output(self, _resolve, _mock_api):
Expand Down Expand Up @@ -117,6 +136,7 @@ def test_classes_become_identity_ontology(self, _resolve, mock_api):
image={"type": "url", "value": "https://example.com/cat.jpg"},
ontology={"cat": "cat", "dog": "dog"},
confidence_threshold=0.4,
reference_examples=None,
)

@patch("roboflow.adapters.rfapi.preview_autolabel", return_value={})
Expand Down Expand Up @@ -223,6 +243,7 @@ def test_foundational_start(self, _resolve, mock_api):
existing_annotations=None,
keypoint_confidence_threshold=None,
size_filter=None,
reference_examples=None,
)

@patch("roboflow.util.http.requests.post")
Expand All @@ -245,6 +266,26 @@ def test_size_flags_send_only_the_bounds_given(self, _resolve, mock_post):
},
)

@patch("roboflow.util.http.requests.post")
@patch(_RESOLVE_PROJECT, return_value=("key", "ws", "proj"))
def test_reference_example_flags_send_the_image_ids(self, _resolve, mock_post):
mock_post.return_value.status_code = 200
mock_post.return_value.json.return_value = {"jobId": "job-1"}
result = runner.invoke(
app,
["autolabel", "start", "-p", "ws/proj", "--batch-id", "batch-1", "-m", "gemini-4-argon-boxes"]
+ ["--reference-example", "img-1", "--reference-example", "img-2"],
)
self.assertEqual(result.exit_code, 0, result.output)
self.assertEqual(
mock_post.call_args.kwargs["json"],
{
"batchId": "batch-1",
"modelType": "gemini-4-argon-boxes",
"referenceExamples": [{"imageId": "img-1"}, {"imageId": "img-2"}],
},
)

@patch("roboflow.util.http.requests.post")
@patch(_RESOLVE_PROJECT, return_value=("key", "ws", "proj"))
def test_video_segment_start_sends_only_the_video_fields(self, _resolve, mock_post):
Expand Down
Loading