From cd39691e6458caf3e6fa086b2e35dc13fb214fe5 Mon Sep 17 00:00:00 2001 From: Iuri de Silvio Date: Mon, 30 Nov 2026 15:00:41 +0100 Subject: [PATCH 1/7] Add size_filter to Auto Label and document the keypoint models Project.autolabel(size_filter=...) and `roboflow autolabel start --min-width/--max-width/--min-height/--max-height` send the API's sizeFilter, which drops labels whose box is outside those sizes. The Auto Label docs now cover the catalog's keypoint models (gemini-4-argon-keypoints, ...), which ignore keypoint_confidence_threshold, and use listed model ids in examples (gpt-6-astra-boxes is unlisted since GPT-6.2 Astra replaced it). `autolabel models` shows the project types each model labels. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 25 +++++++++++++++ CLI-COMMANDS.md | 27 ++++++++++++----- roboflow/adapters/rfapi.py | 20 +++++++----- roboflow/cli/handlers/autolabel.py | 35 ++++++++++++++++++--- roboflow/core/project.py | 47 +++++++++++++++++++++++------ roboflow/core/workspace.py | 23 ++++++++++---- tests/adapters/test_autolabel.py | 2 ++ tests/cli/test_autolabel_handler.py | 43 ++++++++++++++++++++++++++ tests/test_project_autolabel.py | 7 +++++ 9 files changed, 195 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c9eb066c..72f92938 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,31 @@ All notable changes to this project will be documented in this file. +## Unreleased + +### Added + +- `Project.autolabel(..., size_filter={"minWidth": 20, "maxWidth": 400})` and + `roboflow autolabel start --min-width 20 --max-width 400` (also + `--min-height`, `--max-height`) drop labels whose box is outside those sizes, + in image pixels. Each bound is optional and inclusive; a polygon, mask or + keypoint instance is measured by the box around it, and classification + projects ignore the filter. Sent as the API's `sizeFilter` + ([#PR](https://github.com/roboflow/roboflow-python/pull/PR)). +- `roboflow autolabel models` shows the project types each model labels, now + that the catalog has keypoint and classification models besides detection + and segmentation ones + ([#PR](https://github.com/roboflow/roboflow-python/pull/PR)). + +### Changed + +- The Auto Label docs cover keypoint-detection projects labeled by the + catalog's keypoint models (ex: `gemini-4-argon-keypoints`), which place each + class skeleton's keypoints and ignore `keypoint_confidence_threshold`, and + use current model ids in their examples: `gpt-6-astra-boxes` still runs but + is no longer listed by `Workspace.autolabel_models()` + ([#PR](https://github.com/roboflow/roboflow-python/pull/PR)). + ## 1.7.4 ### Added diff --git a/CLI-COMMANDS.md b/CLI-COMMANDS.md index a4712dfb..72f0ea16 100644 --- a/CLI-COMMANDS.md +++ b/CLI-COMMANDS.md @@ -320,10 +320,13 @@ project.accept_annotation_job_images( roboflow autolabel models roboflow autolabel preview -p my-project -m sam3-rle --image https://example.com/sample.jpg \ --class cat --class dog -roboflow autolabel start -p my-project --batch-id -m gpt-6-astra-boxes \ +roboflow autolabel start -p my-project --batch-id -m gpt-6-2-sol-boxes \ --ontology '{"a cat": "cat", "a dog": "dog"}' --confidence 0.5 --reviewer b@co.com roboflow autolabel start -p my-project --batch-id -m my-project/3 --model-type roboflow roboflow autolabel start -p my-project --batch-id -m sam3-rle --existing-annotations merge +roboflow autolabel start -p my-project --batch-id -m gpt-6-2-sol-boxes \ + --min-width 20 --min-height 20 --max-width 400 +roboflow autolabel start -p my-keypoints --batch-id -m gemini-4-argon-keypoints roboflow autolabel start -p my-keypoints --batch-id -m my-keypoints/2 --model-type roboflow \ --keypoint-confidence 0.7 roboflow autolabel start -p my-actions --batch-id -m video-segment \ @@ -332,9 +335,10 @@ roboflow autolabel job roboflow autolabel job -p other-workspace/my-project ``` -`models` lists the catalog for the workspace (id, availability, credits per -image, default). `preview` runs one image through a model for free so you can -compare candidates before spending credits. `start` creates the job and prints +`models` lists the catalog for the workspace (id, the project types each +model labels, availability, credits per image, default). `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 repeated `--class` flags or as `--ontology` JSON. The ontology is keyed by **prompt**, not by class: `'{"kitten": "cat", "tabby": "cat"}'` labels whatever @@ -346,9 +350,15 @@ what the job does with annotations already on the batch images: `replace` (the default) removes them, `preserve` keeps them and adds every prediction next to them, and `merge` keeps them and skips a prediction that overlaps an existing annotation of the same class (IoU of at least 0.5), so objects that are already -labeled aren't duplicated. Keypoint-detection projects are labeled 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 +labeled aren't duplicated. `--min-width`, `--max-width`, `--min-height` and +`--max-height` drop labels whose box is outside those sizes, in image pixels (a +label exactly at a limit is kept; classification projects ignore them). +Keypoint-detection projects are labeled with a trained keypoint model or with a +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 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}'` @@ -367,7 +377,8 @@ The same operations are available in Python: ```python models = workspace.autolabel_models()["models"] preview = project.autolabel_preview("sam3-rle", "sample.jpg", ontology={"cat": "cat"}) -job = project.autolabel("batch-id", model="gpt-6-astra-boxes", ontology={"a cat": "cat"}) +job = project.autolabel("batch-id", model="gpt-6-2-sol-boxes", ontology={"a cat": "cat"}, + size_filter={"minWidth": 20, "minHeight": 20}) project.autolabel_job(job["jobId"])["status"] ``` diff --git a/roboflow/adapters/rfapi.py b/roboflow/adapters/rfapi.py index fba5dec0..f78f5647 100644 --- a/roboflow/adapters/rfapi.py +++ b/roboflow/adapters/rfapi.py @@ -1510,9 +1510,10 @@ def list_autolabel_models(api_key, workspace_url): """Fetch the foundation-model catalog for hosted auto-labeling. Calls ``GET /:workspace/autolabel/models``. Returns ``{models: [...]}`` - where each entry carries ``id``, ``name``, ``guidance``, ``ontologyFormat``, - ``creditsPerImage``, ``isDefault`` and per-workspace ``available`` (with an - ``unavailableReason`` when the plan blocks a model). + where each entry carries ``id``, ``name``, ``labelType``, ``guidance``, + ``projectTypes``, ``ontologyFormat``, ``creditsPerImage``, ``isDefault`` + and per-workspace ``available`` (with an ``unavailableReason`` when the + plan blocks a model); ``Workspace.autolabel_models`` lists every field. """ response = http.get( f"{API_URL}/{workspace_url}/autolabel/models", @@ -1569,12 +1570,13 @@ def start_autolabel_job( model_options=None, existing_annotations=None, keypoint_confidence_threshold=None, + size_filter=None, ): """Start a hosted auto-label job over a batch. Calls ``POST /:workspace/:project/autolabel``. ``model_type`` is sent as-is: a catalog id from ``list_autolabel_models`` (for example - ``gpt-6-astra-boxes`` or ``sam3-rle``) or ``custom_roboflow`` with the + ``gpt-6-2-sol-boxes`` or ``sam3-rle``) or ``custom_roboflow`` with the Roboflow model id in ``model_options["modelId"]``, or ``video-segment`` to label a batch of videos in an action-recognition project (see ``Project.autolabel``). ``ontology`` is keyed by prompt: @@ -1584,9 +1586,12 @@ def start_autolabel_job( ``confidence_thresholds`` is omitted and defaults ``num_images_to_label`` to the whole batch. ``existing_annotations`` is ``"replace"`` (the server default), ``"preserve"`` or ``"merge"``; see ``Project.autolabel``. - ``keypoint_confidence_threshold`` (0-1, keypoint-detection projects only) - is the lowest confidence a predicted keypoint needs to be saved as - visible; the server default is 0.6. Returns + ``keypoint_confidence_threshold`` (0-1, keypoint-detection projects + labeled with a trained keypoint model) is the lowest confidence a + 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 ``{jobId, annotationJobId, message}``. Raises: @@ -1602,6 +1607,7 @@ def start_autolabel_job( "reviewerEmail": reviewer_email, "modelOptions": model_options, "keypointConfidenceThreshold": keypoint_confidence_threshold, + "sizeFilter": size_filter, } payload.update({key: value for key, value in optional.items() if value is not None}) payload.update(existing_annotations_flags(existing_annotations)) diff --git a/roboflow/cli/handlers/autolabel.py b/roboflow/cli/handlers/autolabel.py index 261303b1..b04ca6e3 100644 --- a/roboflow/cli/handlers/autolabel.py +++ b/roboflow/cli/handlers/autolabel.py @@ -130,16 +130,31 @@ def start( Optional[float], typer.Option( "--keypoint-confidence", - help="Keypoint projects: lowest confidence (0-1) a predicted keypoint needs to be saved as visible " - "(server default: 0.6)", + help="Keypoint projects labeled with a trained keypoint model (--model-type roboflow): lowest " + "confidence (0-1) a predicted keypoint needs to be saved as visible (server default: 0.6). " + "The keypoint models from 'autolabel models' ignore it", ), ] = None, + min_width: Annotated[ + Optional[float], typer.Option("--min-width", help="Drop labels whose box is narrower, in image pixels") + ] = None, + max_width: Annotated[ + Optional[float], typer.Option("--max-width", help="Drop labels whose box is wider, in image pixels") + ] = None, + min_height: Annotated[ + Optional[float], typer.Option("--min-height", help="Drop labels whose box is shorter, in image pixels") + ] = None, + max_height: Annotated[ + Optional[float], typer.Option("--max-height", help="Drop labels whose box is taller, in image pixels") + ] = None, ) -> None: """Start a hosted auto-label job over a batch of images, or of videos with -m video-segment.""" args = ctx_to_args(ctx, project=project) resolved_ontology = _parse_ontology(args, ontology, classes) resolved_thresholds = _parse_json_option(args, "--confidence-thresholds", confidence_thresholds) resolved_options = _parse_json_option(args, "--model-options", model_options) + bounds = {"minWidth": min_width, "maxWidth": max_width, "minHeight": min_height, "maxHeight": max_height} + size_filter = {key: value for key, value in bounds.items() if value is not None} or None from roboflow.util.autolabel_utils import resolve_model def start_job(key: str, workspace: str, proj: str) -> Any: @@ -163,6 +178,7 @@ def start_job(key: str, workspace: str, proj: str) -> Any: else ("preserve" if preserve_existing else None) ), keypoint_confidence_threshold=keypoint_confidence, + size_filter=size_filter, ) _project_command(args, start_job) @@ -280,6 +296,16 @@ def _project_command(args: Any, operation: Callable[[str, str, str], Any]) -> No _run(args, lambda: operation(api_key, workspace, project)) +def _project_types(model: dict) -> str: + """The project types a catalog entry labels; ``projectTypes: null`` means all but the excluded ones.""" + if "projectTypes" not in model: + return "" + if model["projectTypes"] is not None: + return ", ".join(model["projectTypes"]) + excluded = model.get("excludedProjectTypes") or [] + return f"all but {', '.join(excluded)}" if excluded else "all" + + def _models(args: Any) -> None: from roboflow.cli._table import format_table @@ -288,6 +314,7 @@ def table(data: Any) -> str: { "id": model.get("id", ""), "name": model.get("name", ""), + "project_types": _project_types(model), "available": "yes" if model.get("available", True) else "no", "default": "yes" if model.get("isDefault") else "", "credits": model.get("creditsPerImage", ""), @@ -297,8 +324,8 @@ def table(data: Any) -> str: ] return format_table( rows, - columns=["id", "name", "available", "default", "credits", "ontology"], - headers=["ID", "NAME", "AVAILABLE", "DEFAULT", "CREDITS/IMAGE", "ONTOLOGY"], + columns=["id", "name", "project_types", "available", "default", "credits", "ontology"], + headers=["ID", "NAME", "PROJECT TYPES", "AVAILABLE", "DEFAULT", "CREDITS/IMAGE", "ONTOLOGY"], ) _workspace_command(args, lambda key, workspace: _rfapi().list_autolabel_models(key, workspace), text=table) diff --git a/roboflow/core/project.py b/roboflow/core/project.py index e153b4ed..82a887e9 100644 --- a/roboflow/core/project.py +++ b/roboflow/core/project.py @@ -1394,7 +1394,7 @@ def autolabel_preview( Args: model: Foundation model id from ``Workspace.autolabel_models()`` - (e.g. ``"gpt-6-astra-boxes"``, ``"sam3-rle"``, ``"gemini-3-8-flash-boxes"``). + (e.g. ``"gpt-6-2-sol-boxes"``, ``"sam3-rle"``, ``"gemini-4-argon-keypoints"``). image: HTTPS URL, local file path, or base64-encoded image. ontology: ``{"text prompt": "class name"}`` -- keyed by prompt, so several prompts can share one class @@ -1402,13 +1402,14 @@ def autolabel_preview( names prompts each class with its own name. Defaults to the dataset's own classes. confidence_threshold: Detection threshold between 0.0 and 1.0 - (sam3 only; other models report fixed confidence). + (sam3 only; other models ignore it). Returns: Dict: ``{model, predictions, summary, blockErrors?}``. ``summary.byClass`` carries per-class counts and max confidence, and ``summary.classesWithNoDetections`` lists requested classes the model - did not find. + did not find. A keypoint model's predictions carry each instance's + ``keypoints``, named after the vertices of the project's class skeletons. """ return rfapi.preview_autolabel( self.__api_key, @@ -1435,9 +1436,17 @@ def autolabel( preserve_existing_annotations: Optional[bool] = None, existing_annotations: Optional[str] = None, keypoint_confidence_threshold: Optional[float] = None, + size_filter: Optional[Dict[str, float]] = None, ) -> Dict: """Start a hosted auto-label job over a batch of images, or of videos. + Keypoint-detection projects are labeled with a trained keypoint model + (``model_type="roboflow"``) or with a model from + ``Workspace.autolabel_models()`` whose ``projectTypes`` include + ``keypoint-detection`` (e.g. ``"gemini-4-argon-keypoints"``), which places + the keypoints of each class's skeleton. Classes without a skeleton in the + project get no labels, and a job where no class has one is refused. + Action-recognition projects label a batch of videos with ``model="video-segment"`` (not listed by ``Workspace.autolabel_models()``). The job labels every video in the batch (the server refuses a batch of @@ -1449,9 +1458,10 @@ def autolabel( Args: batch_id: Source batch containing the images (or videos) to auto-label. model: For ``model_type="foundational"``, a model id from - ``Workspace.autolabel_models()`` (e.g. ``"gpt-6-astra-boxes"``, - ``"sam3-rle"``, ``"sam3-polygon"``, ``"gemini-3-8-flash-boxes"``), - or ``"video-segment"`` on an action-recognition project. For + ``Workspace.autolabel_models()`` (e.g. ``"gpt-6-2-sol-boxes"``, + ``"gpt-6-1-terra-boxes"``, ``"sam3-rle"``, ``"sam3-polygon"``, + ``"gemini-4-argon-keypoints"``), or ``"video-segment"`` on an + action-recognition project. For ``model_type="roboflow"``, a Roboflow model id such as ``"project-slug/3"`` or ``"workspace-slug/model-id"``. model_type: ``"foundational"`` (hosted foundation model, sent as-is; @@ -1474,6 +1484,9 @@ class given by its own name the whole batch. confidence: Confidence threshold applied to every class (mirrors the UI slider). Ignored when ``confidence_thresholds`` is set. + When both are omitted, a model that lists a + ``defaultConfidenceThreshold`` in ``Workspace.autolabel_models()`` + starts every class at it. confidence_thresholds: Per-class threshold override, e.g. ``{"cat": 0.5, "dog": 0.6}``. run_nms: Whether to run non-max suppression (server default: True). @@ -1500,17 +1513,32 @@ class given by its own name 1, a predicted keypoint needs to be saved as visible; points below it are saved as not visible. The server default is 0.6. ``confidence`` / ``confidence_thresholds`` still decide which - instances are kept. + instances are kept. The keypoint models from + ``Workspace.autolabel_models()`` ignore it: they save a keypoint + they see as visible, one they mark hidden as occluded, and one + they cannot place as not visible. + size_filter: Drop detections whose box is outside these sizes, in + image pixels: any of ``minWidth``, ``maxWidth``, ``minHeight`` + and ``maxHeight``, each inclusive, e.g. + ``{"minWidth": 20, "maxWidth": 400}``. A polygon, mask or + keypoint instance is measured by the box around it. + Classification projects ignore it, and the server refuses a + minimum above its maximum (``INVALID_SIZE_FILTER``). Returns: Dict: ``{jobId, annotationJobId, message}``. Poll progress with ``autolabel_job(jobId)``. Example: - >>> job = project.autolabel("batch-id", model="gpt-6-astra-boxes", - ... ontology={"a cat": "cat", "a dog": "dog"}) + >>> job = project.autolabel("batch-id", model="gpt-6-2-sol-boxes", + ... ontology={"a cat": "cat", "a dog": "dog"}, + ... size_filter={"minWidth": 20, "minHeight": 20}) >>> project.autolabel_job(job["jobId"])["status"] + Place the class skeletons on a keypoint-detection project: + + >>> job = project.autolabel("batch-id", model="gemini-4-argon-keypoints") + Label a batch of videos in an action-recognition project: >>> job = project.autolabel("video-batch-id", model="video-segment", @@ -1543,6 +1571,7 @@ class given by its own name model_options=model_options, existing_annotations=existing_annotations, keypoint_confidence_threshold=keypoint_confidence_threshold, + size_filter=size_filter, ) def autolabel_job(self, job_id: str) -> Dict: diff --git a/roboflow/core/workspace.py b/roboflow/core/workspace.py index 1e76db13..60a8065d 100644 --- a/roboflow/core/workspace.py +++ b/roboflow/core/workspace.py @@ -1756,16 +1756,27 @@ def autolabel_models(self) -> dict: List the foundation models available for hosted auto-labeling in this workspace. Returns ``{models: [...]}``. Each entry's ``id`` (e.g. - ``gpt-6-astra-boxes``, ``sam3-rle``, ``gemini-3-8-flash-boxes``) is a valid - ``model`` for ``Project.autolabel`` and ``Project.autolabel_preview``. - Entries carry ``guidance`` on when to prefer each model, the - ``projectTypes`` they support, ``ontologyFormat``, ``creditsPerImage``, - ``isDefault``, and ``available`` with an ``unavailableReason`` when the - workspace plan blocks a model. + ``gpt-6-2-sol-boxes``, ``sam3-rle``, ``gemini-4-argon-keypoints``) is a valid + ``model`` for ``Project.autolabel`` and ``Project.autolabel_preview``; + an id in its ``aliases`` works too. Entries carry ``name``, + ``labelType`` (e.g. ``"Keypoint labels"``), ``guidance`` on when to + prefer each model, the ``projectTypes`` they label (``None`` means every + type but ``excludedProjectTypes``), ``multilabel`` on classification + 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. Example: >>> for m in ws.autolabel_models()["models"]: ... print(m["id"], m["available"]) + + The models that label a keypoint-detection project: + + >>> [m["id"] for m in ws.autolabel_models()["models"] + ... if "keypoint-detection" in (m["projectTypes"] or [])] """ return rfapi.list_autolabel_models(self.__api_key, self.url) diff --git a/tests/adapters/test_autolabel.py b/tests/adapters/test_autolabel.py index 0eccadae..98c2dd0c 100644 --- a/tests/adapters/test_autolabel.py +++ b/tests/adapters/test_autolabel.py @@ -83,6 +83,7 @@ def test_start_job_contract_full_payload(self, mock_post): model_options={"modelId": "proj/3"}, existing_annotations="merge", keypoint_confidence_threshold=0.7, + size_filter={"minWidth": 20, "maxWidth": 400}, ) self.assertEqual( mock_post.call_args.kwargs["json"], @@ -99,6 +100,7 @@ def test_start_job_contract_full_payload(self, mock_post): "preserveExistingAnnotations": True, "mergeExistingAnnotations": True, "keypointConfidenceThreshold": 0.7, + "sizeFilter": {"minWidth": 20, "maxWidth": 400}, }, ) diff --git a/tests/cli/test_autolabel_handler.py b/tests/cli/test_autolabel_handler.py index 0941c2ce..eb535626 100644 --- a/tests/cli/test_autolabel_handler.py +++ b/tests/cli/test_autolabel_handler.py @@ -45,6 +45,28 @@ def test_text_output_is_a_table(self, _resolve, mock_api): self.assertIn("gemini-3-8-flash-boxes", result.output) mock_api.assert_called_once_with("key", "ws") + @patch("roboflow.adapters.rfapi.list_autolabel_models") + @patch(_RESOLVE_WORKSPACE, return_value=("ws", "key")) + def test_table_shows_the_project_types_each_model_labels(self, _resolve, mock_api): + mock_api.return_value = { + "models": [ + {"id": "gemini-4-argon-keypoints", "projectTypes": ["keypoint-detection"]}, + { + "id": "sam3-rle", + "projectTypes": None, + "excludedProjectTypes": ["classification", "keypoint-detection"], + }, + {"id": "any-type-model", "projectTypes": None}, + ] + } + result = runner.invoke(app, ["autolabel", "models"]) + 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", return_value={"models": [{"id": "sam3-rle"}]}) @patch(_RESOLVE_WORKSPACE, return_value=("ws", "key")) def test_json_output(self, _resolve, _mock_api): @@ -200,6 +222,27 @@ def test_foundational_start(self, _resolve, mock_api): model_options={"outputFormat": "polygon"}, existing_annotations=None, keypoint_confidence_threshold=None, + size_filter=None, + ) + + @patch("roboflow.util.http.requests.post") + @patch(_RESOLVE_PROJECT, return_value=("key", "ws", "proj")) + def test_size_flags_send_only_the_bounds_given(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", "gpt-6-2-sol-boxes"] + + ["--min-width", "20", "--max-width", "400.5", "--min-height", "0"], + ) + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual( + mock_post.call_args.kwargs["json"], + { + "batchId": "batch-1", + "modelType": "gpt-6-2-sol-boxes", + "sizeFilter": {"minWidth": 20.0, "maxWidth": 400.5, "minHeight": 0.0}, + }, ) @patch("roboflow.util.http.requests.post") diff --git a/tests/test_project_autolabel.py b/tests/test_project_autolabel.py index 70dc8b4f..6ed295aa 100644 --- a/tests/test_project_autolabel.py +++ b/tests/test_project_autolabel.py @@ -33,8 +33,15 @@ def test_autolabel_foundational_passes_model_as_is(self, mock_start): model_options=None, existing_annotations=None, keypoint_confidence_threshold=None, + size_filter=None, ) + @patch("roboflow.adapters.rfapi.start_autolabel_job", return_value={"jobId": "job-1"}) + def test_autolabel_forwards_size_filter(self, mock_start): + self.project.autolabel("batch-1", "gpt-6-2-sol-boxes", size_filter={"minWidth": 20, "maxHeight": 300}) + + self.assertEqual(mock_start.call_args.kwargs["size_filter"], {"minWidth": 20, "maxHeight": 300}) + @patch("roboflow.adapters.rfapi.start_autolabel_job", return_value={"jobId": "job-1"}) def test_autolabel_forwards_existing_annotations(self, mock_start): self.project.autolabel("batch-1", "sam3-rle", existing_annotations="merge") From c5b1580fbe38d31c498401b99a2a1ff8d3e0e3fa Mon Sep 17 00:00:00 2001 From: Iuri de Silvio Date: Mon, 30 Nov 2026 15:10:01 +0100 Subject: [PATCH 2/7] Link the Auto Label changelog entries to #593 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72f92938..a2d3c2ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,11 +12,11 @@ All notable changes to this project will be documented in this file. in image pixels. Each bound is optional and inclusive; a polygon, mask or keypoint instance is measured by the box around it, and classification projects ignore the filter. Sent as the API's `sizeFilter` - ([#PR](https://github.com/roboflow/roboflow-python/pull/PR)). + ([#593](https://github.com/roboflow/roboflow-python/pull/593)). - `roboflow autolabel models` shows the project types each model labels, now that the catalog has keypoint and classification models besides detection and segmentation ones - ([#PR](https://github.com/roboflow/roboflow-python/pull/PR)). + ([#593](https://github.com/roboflow/roboflow-python/pull/593)). ### Changed @@ -25,7 +25,7 @@ All notable changes to this project will be documented in this file. class skeleton's keypoints and ignore `keypoint_confidence_threshold`, and use current model ids in their examples: `gpt-6-astra-boxes` still runs but is no longer listed by `Workspace.autolabel_models()` - ([#PR](https://github.com/roboflow/roboflow-python/pull/PR)). + ([#593](https://github.com/roboflow/roboflow-python/pull/593)). ## 1.7.4 From 9e4c6b8ebf78c52cd89c3ae02ffc5737956f26a5 Mon Sep 17 00:00:00 2001 From: Iuri de Silvio Date: Mon, 30 Nov 2026 19:25:54 +0100 Subject: [PATCH 3/7] Auto Label with a saved Workflow from the SDK and the CLI Project.autolabel(model="", model_type="workflow", workflow_output=..., class_mapping=...) and `roboflow autolabel start --model-type workflow --workflow-output ... --class-mapping ...` start the public route's saved-Workflow job (modelType "workflow"), which neither client could send before. The route requires workspaceName, selectedOutputName, classMapping and a numeric threshold for every class the mapping writes, and it does not fan defaultConfidence out for a Workflow job. So the adapter sends the route's workspace as workspaceName, and `confidence` (0.5 when omitted, the web app's start value) is fanned out over the mapped project classes unless confidence_thresholds is given. A Workflow job without an output or a class mapping, or a Workflow option on another model type, is a ValueError before any request: a catalog model's job would otherwise take a classMapping it was not meant to get. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 +++ CLI-COMMANDS.md | 13 ++++- roboflow/adapters/rfapi.py | 20 +++++++- roboflow/cli/handlers/autolabel.py | 65 +++++++++++++++++++++--- roboflow/core/project.py | 67 ++++++++++++++++++++++--- roboflow/util/autolabel_utils.py | 70 ++++++++++++++++++++++++-- tests/adapters/test_autolabel.py | 33 ++++++++++++ tests/cli/test_autolabel_handler.py | 71 ++++++++++++++++++++++++++ tests/test_project_autolabel.py | 42 ++++++++++++++++ tests/util/test_autolabel_utils.py | 78 ++++++++++++++++++++++++++++- 10 files changed, 448 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a2d3c2ca..25fb8a36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,14 @@ All notable changes to this project will be documented in this file. that the catalog has keypoint and classification models besides detection and segmentation ones ([#593](https://github.com/roboflow/roboflow-python/pull/593)). +- Auto Label with a saved Workflow: + `Project.autolabel("batch-id", model="vehicle-detector", model_type="workflow", workflow_output="predictions", class_mapping={"car": "vehicle"})` + and `roboflow autolabel start --model-type workflow --workflow-output + predictions --class-mapping '{"car": "vehicle"}'`. `model` is the + Workflow's URL, `class_mapping` maps each class it outputs to a project + class (classes left out are dropped), and every mapped class starts at + `confidence` (0.5 when omitted) unless `confidence_thresholds` sets it. + `workflow_inputs` / `--workflow-inputs` fill the Workflow's other inputs. ### Changed diff --git a/CLI-COMMANDS.md b/CLI-COMMANDS.md index 72f0ea16..4d28bf36 100644 --- a/CLI-COMMANDS.md +++ b/CLI-COMMANDS.md @@ -331,6 +331,8 @@ roboflow autolabel start -p my-keypoints --batch-id -m my-keypoints/2 --keypoint-confidence 0.7 roboflow autolabel start -p my-actions --batch-id -m video-segment \ --ontology '{"a person jumps": "jump"}' --model-options '{"sampleFps": 2}' +roboflow autolabel start -p my-project --batch-id -m vehicle-detector --model-type workflow \ + --workflow-output predictions --class-mapping '{"car": "vehicle", "truck": "vehicle"}' --confidence 0.4 roboflow autolabel job roboflow autolabel job -p other-workspace/my-project ``` @@ -368,7 +370,14 @@ unchanged (`preserved: true` in `job`). Video jobs do not take the image options (`--num-images`, `--confidence`, `--no-nms`, `--existing-annotations preserve|merge`, ...); the server refuses them. `job` shows video progress in `framesSampled` / `framesPlanned` and per -video in `videos`. `job` looks the id up in +video in `videos`. `--model-type workflow` labels the batch with the published +version of a saved Workflow: `-m` is its URL (from `roboflow workflow list`), `--workflow-output` +names the output that holds the predictions, and `--class-mapping` maps each +class the Workflow outputs to the project class it is saved as (classes left +out are dropped). Every mapped project class starts at `--confidence` (0.5 when +omitted), or set them one by one with `--confidence-thresholds`. Pass the +Workflow's other inputs with `--workflow-inputs` JSON, and its image input with +`--workflow-image-input` when it is not named `image`. `job` looks the id up in your default workspace, so when the job was started with a `workspace/project` shorthand pass the same `-p` to `job`. @@ -379,6 +388,8 @@ models = workspace.autolabel_models()["models"] preview = project.autolabel_preview("sam3-rle", "sample.jpg", ontology={"cat": "cat"}) job = project.autolabel("batch-id", model="gpt-6-2-sol-boxes", ontology={"a cat": "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"}) project.autolabel_job(job["jobId"])["status"] ``` diff --git a/roboflow/adapters/rfapi.py b/roboflow/adapters/rfapi.py index f78f5647..8f70cd37 100644 --- a/roboflow/adapters/rfapi.py +++ b/roboflow/adapters/rfapi.py @@ -1571,6 +1571,11 @@ def start_autolabel_job( existing_annotations=None, keypoint_confidence_threshold=None, size_filter=None, + workflow_id=None, + selected_output_name=None, + image_input_name=None, + input_values=None, + class_mapping=None, ): """Start a hosted auto-label job over a batch. @@ -1578,8 +1583,13 @@ def start_autolabel_job( as-is: a catalog id from ``list_autolabel_models`` (for example ``gpt-6-2-sol-boxes`` or ``sam3-rle``) or ``custom_roboflow`` with the Roboflow model id in ``model_options["modelId"]``, or ``video-segment`` - to label a batch of videos in an action-recognition project (see - ``Project.autolabel``). ``ontology`` is keyed by prompt: + to label a batch of videos in an action-recognition project, or + ``workflow`` to run the saved Workflow whose URL slug is ``workflow_id`` + (see ``Project.autolabel``). A Workflow job sends ``workspaceName`` (this + workspace), ``selectedOutputName``, ``classMapping`` (Workflow class to + project class) and ``confidenceThresholds`` with a threshold for every + class it maps to, and optionally ``imageInputName`` (the worker defaults + it to ``image``) and ``inputValues``. ``ontology`` is keyed by prompt: ``{"kitten": "cat"}`` labels prompt matches as class ``cat``. The backend fans ``default_confidence`` out across the ontology when @@ -1608,6 +1618,12 @@ def start_autolabel_job( "modelOptions": model_options, "keypointConfidenceThreshold": keypoint_confidence_threshold, "sizeFilter": size_filter, + "workflowId": workflow_id, + "workspaceName": workspace_url if workflow_id is not None else None, + "selectedOutputName": selected_output_name, + "imageInputName": image_input_name, + "inputValues": input_values, + "classMapping": class_mapping, } payload.update({key: value for key, value in optional.items() if value is not None}) payload.update(existing_annotations_flags(existing_annotations)) diff --git a/roboflow/cli/handlers/autolabel.py b/roboflow/cli/handlers/autolabel.py index b04ca6e3..dcfe5064 100644 --- a/roboflow/cli/handlers/autolabel.py +++ b/roboflow/cli/handlers/autolabel.py @@ -71,12 +71,17 @@ def start( "-m", "--model", help="Foundation model ID from 'autolabel models', a Roboflow model ID with --model-type roboflow, " + "a saved Workflow's URL (from 'workflow list') with --model-type workflow, " "or 'video-segment' for a batch of videos in an action-recognition project", ), ], model_type: Annotated[ str, - typer.Option("--model-type", help="'foundational' (hosted foundation model) or 'roboflow' (trained model)"), + typer.Option( + "--model-type", + help="'foundational' (hosted foundation model), 'roboflow' (trained model) or 'workflow' (saved " + "Workflow; needs --workflow-output and --class-mapping)", + ), ] = "foundational", classes: Annotated[ Optional[list[str]], @@ -94,11 +99,16 @@ def start( Optional[int], typer.Option("--num-images", help="Number of images to label (default: whole batch)") ] = None, confidence: Annotated[ - Optional[float], typer.Option("--confidence", help="Confidence threshold applied to every class") + Optional[float], + typer.Option("--confidence", help="Confidence threshold applied to every class (Workflow jobs: default 0.5)"), ] = None, confidence_thresholds: Annotated[ Optional[str], - typer.Option("--confidence-thresholds", help="JSON per-class thresholds, e.g. '{\"cat\": 0.5}'"), + typer.Option( + "--confidence-thresholds", + help="JSON per-class thresholds, e.g. '{\"cat\": 0.5}'. For a Workflow job, one for every project " + "class in --class-mapping", + ), ] = None, no_nms: Annotated[bool, typer.Option("--no-nms", help="Disable non-max suppression")] = False, reviewer: Annotated[ @@ -147,18 +157,60 @@ def start( max_height: Annotated[ Optional[float], typer.Option("--max-height", help="Drop labels whose box is taller, in image pixels") ] = None, + class_mapping: Annotated[ + Optional[str], + typer.Option( + "--class-mapping", + help="Workflow jobs: JSON object mapping each class the Workflow outputs to the project class it is " + 'saved as, e.g. \'{"car": "vehicle"}\', or @mapping.json. Classes left out are dropped', + ), + ] = None, + workflow_output: Annotated[ + Optional[str], + typer.Option("--workflow-output", help="Workflow jobs: the Workflow output that holds the predictions"), + ] = None, + workflow_inputs: Annotated[ + Optional[str], + typer.Option( + "--workflow-inputs", + help="Workflow jobs: JSON values for the Workflow's other inputs, e.g. '{\"confidence\": 0.3}', " + "or @inputs.json", + ), + ] = None, + workflow_image_input: Annotated[ + Optional[str], + typer.Option( + "--workflow-image-input", help="Workflow jobs: the Workflow input that takes the image (default: image)" + ), + ] = None, ) -> None: - """Start a hosted auto-label job over a batch of images, or of videos with -m video-segment.""" + """Start a hosted auto-label job over a batch of images, or of videos with -m video-segment. + + With --model-type workflow, a saved Workflow labels the images: -m is its URL, --workflow-output names the + output with the predictions and --class-mapping maps its classes to project classes. + """ args = ctx_to_args(ctx, project=project) resolved_ontology = _parse_ontology(args, ontology, classes) resolved_thresholds = _parse_json_option(args, "--confidence-thresholds", confidence_thresholds) resolved_options = _parse_json_option(args, "--model-options", model_options) + resolved_mapping = _parse_json_option(args, "--class-mapping", class_mapping) + resolved_inputs = _parse_json_option(args, "--workflow-inputs", workflow_inputs) bounds = {"minWidth": min_width, "maxWidth": max_width, "minHeight": min_height, "maxHeight": max_height} size_filter = {key: value for key, value in bounds.items() if value is not None} or None - from roboflow.util.autolabel_utils import resolve_model + from roboflow.util.autolabel_utils import resolve_model, resolve_workflow def start_job(key: str, workspace: str, proj: str) -> Any: wire_model_type, wire_options = resolve_model(model, model_type, resolved_options) + thresholds, workflow = resolve_workflow( + model, + model_type, + workflow_output=workflow_output, + class_mapping=resolved_mapping, + workflow_inputs=resolved_inputs, + workflow_image_input=workflow_image_input, + confidence=confidence, + confidence_thresholds=resolved_thresholds, + ) return _rfapi().start_autolabel_job( key, workspace, @@ -168,7 +220,7 @@ def start_job(key: str, workspace: str, proj: str) -> Any: ontology=resolved_ontology, num_images_to_label=num_images, default_confidence=confidence, - confidence_thresholds=resolved_thresholds, + confidence_thresholds=thresholds, run_nms=False if no_nms else None, reviewer_email=reviewer, model_options=wire_options, @@ -179,6 +231,7 @@ def start_job(key: str, workspace: str, proj: str) -> Any: ), keypoint_confidence_threshold=keypoint_confidence, size_filter=size_filter, + **workflow, ) _project_command(args, start_job) diff --git a/roboflow/core/project.py b/roboflow/core/project.py index 82a887e9..802cb3ce 100644 --- a/roboflow/core/project.py +++ b/roboflow/core/project.py @@ -5,7 +5,7 @@ import time import warnings from datetime import datetime -from typing import Dict, List, Optional, Union +from typing import Any, Dict, List, Optional, Union import filetype @@ -18,6 +18,7 @@ from roboflow.util.autolabel_utils import image_payload as _autolabel_image_payload from roboflow.util.autolabel_utils import ontology_payload as _autolabel_ontology_payload from roboflow.util.autolabel_utils import resolve_model as _resolve_autolabel_model +from roboflow.util.autolabel_utils import resolve_workflow as _resolve_autolabel_workflow from roboflow.util.general import Retry from roboflow.util.image_utils import load_labelmap from roboflow.util.search_utils import normalize_media_types @@ -1437,9 +1438,23 @@ def autolabel( existing_annotations: Optional[str] = None, keypoint_confidence_threshold: Optional[float] = None, size_filter: Optional[Dict[str, float]] = None, + class_mapping: Optional[Dict[str, str]] = None, + workflow_output: Optional[str] = None, + workflow_inputs: Optional[Dict[str, Any]] = None, + workflow_image_input: Optional[str] = None, ) -> Dict: """Start a hosted auto-label job over a batch of images, or of videos. + With ``model_type="workflow"``, a saved Workflow labels the batch: + ``model`` is its URL slug (the URL column of ``roboflow workflow list``, + the ``workflow_id`` in its deploy code). Name the Workflow output that + holds the predictions in ``workflow_output`` and map the classes it + outputs to project classes in ``class_mapping``; only mapped classes are + saved. ``ontology`` does not apply. Every project class the mapping + writes gets ``confidence`` (0.5 when omitted), or set them one by one + in ``confidence_thresholds``. The job runs the Workflow's published + version, not its draft. + Keypoint-detection projects are labeled with a trained keypoint model (``model_type="roboflow"``) or with a model from ``Workspace.autolabel_models()`` whose ``projectTypes`` include @@ -1463,10 +1478,12 @@ def autolabel( ``"gemini-4-argon-keypoints"``), or ``"video-segment"`` on an action-recognition project. For ``model_type="roboflow"``, a Roboflow model id such as - ``"project-slug/3"`` or ``"workspace-slug/model-id"``. + ``"project-slug/3"`` or ``"workspace-slug/model-id"``. For + ``model_type="workflow"``, the URL slug of a saved Workflow in + this workspace. model_type: ``"foundational"`` (hosted foundation model, sent as-is; - the backend resolves catalog ids) or ``"roboflow"`` (a - Roboflow-trained model). + the backend resolves catalog ids), ``"roboflow"`` (a + Roboflow-trained model) or ``"workflow"`` (a saved Workflow). ontology: ``{"text prompt": "class name"}`` -- keyed by prompt, not by class, so several prompts can collapse onto one output class (``{"kitten": "cat", "tabby": "cat"}`` labels both as ``cat``). @@ -1486,9 +1503,12 @@ class given by its own name the UI slider). Ignored when ``confidence_thresholds`` is set. When both are omitted, a model that lists a ``defaultConfidenceThreshold`` in ``Workspace.autolabel_models()`` - starts every class at it. + starts every class at it, and a Workflow job starts every + mapped class at 0.5. confidence_thresholds: Per-class threshold override, e.g. - ``{"cat": 0.5, "dog": 0.6}``. + ``{"cat": 0.5, "dog": 0.6}``. For a Workflow job, keyed by + project class, with an entry for every class + ``class_mapping`` maps to. run_nms: Whether to run non-max suppression (server default: True). reviewer_email: Reviewer for the resulting annotation job. Must be a workspace member; defaults to the workspace owner. @@ -1524,11 +1544,27 @@ class given by its own name keypoint instance is measured by the box around it. Classification projects ignore it, and the server refuses a minimum above its maximum (``INVALID_SIZE_FILTER``). + class_mapping: Workflow jobs only, required. Maps each class the + Workflow outputs to the project class it is saved as, e.g. + ``{"car": "vehicle", "truck": "vehicle"}``. Classes the + Workflow outputs that are not in it are dropped. + workflow_output: Workflow jobs only, required. The name of the + Workflow output that holds the predictions, e.g. + ``"predictions"``. + workflow_inputs: Workflow jobs only. Values for the Workflow's + 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"``). Returns: Dict: ``{jobId, annotationJobId, message}``. Poll progress with ``autolabel_job(jobId)``. + Raises: + ValueError: an unknown ``model_type``, a Workflow job without + ``workflow_output`` or ``class_mapping``, or a Workflow option + on another model type. + Example: >>> job = project.autolabel("batch-id", model="gpt-6-2-sol-boxes", ... ontology={"a cat": "cat", "a dog": "dog"}, @@ -1544,6 +1580,14 @@ class given by its own name >>> job = project.autolabel("video-batch-id", model="video-segment", ... ontology={"a person jumps": "jump"}, ... model_options={"sampleFps": 2}) + + Label with a saved Workflow, keeping two of its classes as ``vehicle``: + + >>> job = project.autolabel("batch-id", model="vehicle-detector", + ... model_type="workflow", + ... workflow_output="predictions", + ... class_mapping={"car": "vehicle", "truck": "vehicle"}, + ... confidence=0.4) """ if preserve_existing_annotations is not None: replacement = "preserve" if preserve_existing_annotations else "replace" @@ -1556,6 +1600,16 @@ class given by its own name if existing_annotations is None and preserve_existing_annotations: existing_annotations = "preserve" wire_model_type, model_options = _resolve_autolabel_model(model, model_type, model_options) + confidence_thresholds, workflow = _resolve_autolabel_workflow( + model, + model_type, + workflow_output=workflow_output, + class_mapping=class_mapping, + workflow_inputs=workflow_inputs, + workflow_image_input=workflow_image_input, + confidence=confidence, + confidence_thresholds=confidence_thresholds, + ) return rfapi.start_autolabel_job( self.__api_key, self.__workspace, @@ -1572,6 +1626,7 @@ class given by its own name existing_annotations=existing_annotations, keypoint_confidence_threshold=keypoint_confidence_threshold, size_filter=size_filter, + **workflow, ) def autolabel_job(self, job_id: str) -> Dict: diff --git a/roboflow/util/autolabel_utils.py b/roboflow/util/autolabel_utils.py index 40009171..e2ae26e7 100644 --- a/roboflow/util/autolabel_utils.py +++ b/roboflow/util/autolabel_utils.py @@ -7,8 +7,10 @@ import os from typing import Any, Dict, Iterable, Optional, Tuple, Union -MODEL_TYPES = ("foundational", "roboflow") +MODEL_TYPES = ("foundational", "roboflow", "workflow") EXISTING_ANNOTATIONS_MODES = ("replace", "preserve", "merge") +# The threshold the web app starts every mapped class at for a Workflow job. +WORKFLOW_DEFAULT_CONFIDENCE = 0.5 def image_payload(image: str) -> Dict[str, str]: @@ -98,10 +100,72 @@ def resolve_model( Foundation models are sent as-is (the backend resolves catalog ids such as ``gpt-6-astra-boxes``). Roboflow-trained models are sent as - ``custom_roboflow`` with the model id in ``modelOptions.modelId``. + ``custom_roboflow`` with the model id in ``modelOptions.modelId``. A saved + Workflow is sent as ``workflow``; ``resolve_workflow`` adds its fields. """ if model_type == "roboflow": return "custom_roboflow", {**(model_options or {}), "modelId": model} + if model_type == "workflow": + return "workflow", model_options if model_type == "foundational": return model, model_options - raise ValueError("model_type must be 'foundational' or 'roboflow'") + raise ValueError("model_type must be 'foundational', 'roboflow' or 'workflow'") + + +def resolve_workflow( + model: str, + model_type: str, + *, + workflow_output: Optional[str] = None, + class_mapping: Optional[Dict[str, str]] = None, + workflow_inputs: Optional[Dict[str, Any]] = None, + workflow_image_input: Optional[str] = None, + confidence: Optional[float] = None, + confidence_thresholds: Optional[Dict[str, float]] = None, +) -> Tuple[Optional[Dict[str, float]], Dict[str, Any]]: + """Resolve the saved-Workflow options of a job into ``start_autolabel_job`` arguments. + + For ``model_type="workflow"``, ``model`` is the Workflow's URL slug. The job + needs the Workflow output that holds the predictions and a ``class_mapping`` + from the classes the Workflow outputs to project classes; classes left out + are dropped. The API wants a threshold for every project class the mapping + writes and does not fan ``defaultConfidence`` out for a Workflow job, so + ``confidence`` (0.5 when omitted, as in the web app) is fanned out here + unless ``confidence_thresholds`` is given. + + Returns: + ``(confidence_thresholds, workflow_fields)``: the thresholds to send, and + the Workflow keyword arguments of ``start_autolabel_job`` (empty for + other model types). + + Raises: + ValueError: a Workflow job lacks ``workflow_output`` or ``class_mapping``, + or another model type got one of the Workflow options. + """ + options = { + "workflow_output": workflow_output, + "class_mapping": class_mapping, + "workflow_inputs": workflow_inputs, + "workflow_image_input": workflow_image_input, + } + if model_type != "workflow": + given = [name for name, value in options.items() if value is not None] + if given: + raise ValueError(f"{', '.join(given)} only apply to model_type='workflow'") + return confidence_thresholds, {} + if not workflow_output: + raise ValueError("model_type='workflow' needs workflow_output: the Workflow output that holds the predictions") + if not isinstance(class_mapping, dict) or not class_mapping: + raise ValueError( + "model_type='workflow' needs class_mapping: {workflow class: project class} for every class to keep" + ) + if confidence_thresholds is None: + threshold = WORKFLOW_DEFAULT_CONFIDENCE if confidence is None else confidence + confidence_thresholds = {target: threshold for target in class_mapping.values()} + return confidence_thresholds, { + "workflow_id": model, + "selected_output_name": workflow_output, + "image_input_name": workflow_image_input, + "input_values": workflow_inputs, + "class_mapping": dict(class_mapping), + } diff --git a/tests/adapters/test_autolabel.py b/tests/adapters/test_autolabel.py index 98c2dd0c..6b10197d 100644 --- a/tests/adapters/test_autolabel.py +++ b/tests/adapters/test_autolabel.py @@ -104,6 +104,39 @@ def test_start_job_contract_full_payload(self, mock_post): }, ) + @patch("roboflow.util.http.requests.post") + def test_start_workflow_job_contract(self, mock_post): + mock_post.return_value = _response({"jobId": "job-1"}) + + rfapi.start_autolabel_job( + "key", + "ws", + "proj", + batch_id="batch-1", + model_type="workflow", + confidence_thresholds={"vehicle": 0.5}, + workflow_id="vehicle-detector", + selected_output_name="predictions", + image_input_name="frame", + input_values={"confidence": 0.3}, + class_mapping={"car": "vehicle"}, + ) + # The start route requires workspaceName on a Workflow job; it is the route's own workspace. + self.assertEqual( + mock_post.call_args.kwargs["json"], + { + "batchId": "batch-1", + "modelType": "workflow", + "confidenceThresholds": {"vehicle": 0.5}, + "workflowId": "vehicle-detector", + "workspaceName": "ws", + "selectedOutputName": "predictions", + "imageInputName": "frame", + "inputValues": {"confidence": 0.3}, + "classMapping": {"car": "vehicle"}, + }, + ) + @patch("roboflow.util.http.requests.post") def test_unknown_existing_annotations_mode_is_rejected_before_the_request(self, mock_post): with self.assertRaises(ValueError): diff --git a/tests/cli/test_autolabel_handler.py b/tests/cli/test_autolabel_handler.py index eb535626..862e0172 100644 --- a/tests/cli/test_autolabel_handler.py +++ b/tests/cli/test_autolabel_handler.py @@ -331,6 +331,77 @@ def test_roboflow_model_type(self, _resolve, mock_api): self.assertEqual(kwargs["confidence_thresholds"], {"cat": 0.6}) self.assertIsNone(kwargs["run_nms"]) + @patch("roboflow.util.http.requests.post") + @patch(_RESOLVE_PROJECT, return_value=("key", "ws", "proj")) + def test_workflow_start_sends_the_workflow_job_body(self, _resolve, mock_post): + mock_post.return_value.status_code = 200 + mock_post.return_value.json.return_value = {"jobId": "job-1"} + with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as handle: + json.dump({"car": "vehicle", "truck": "vehicle", "person": "pedestrian"}, handle) + path = handle.name + try: + result = runner.invoke( + app, + ["autolabel", "start", "-p", "ws/proj", "--batch-id", "batch-1", "-m", "vehicle-detector"] + + ["--model-type", "workflow", "--workflow-output", "predictions", "--class-mapping", f"@{path}"] + + ["--workflow-inputs", '{"confidence": 0.3}', "--workflow-image-input", "frame"] + + ["--confidence-thresholds", '{"vehicle": 0.6, "pedestrian": 0.4}', "--min-width", "20"], + ) + finally: + os.unlink(path) + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual( + mock_post.call_args.kwargs["json"], + { + "batchId": "batch-1", + "modelType": "workflow", + "confidenceThresholds": {"vehicle": 0.6, "pedestrian": 0.4}, + "sizeFilter": {"minWidth": 20.0}, + "workflowId": "vehicle-detector", + "workspaceName": "ws", + "selectedOutputName": "predictions", + "imageInputName": "frame", + "inputValues": {"confidence": 0.3}, + "classMapping": {"car": "vehicle", "truck": "vehicle", "person": "pedestrian"}, + }, + ) + + @patch("roboflow.adapters.rfapi.start_autolabel_job", return_value={"jobId": "job-1"}) + @patch(_RESOLVE_PROJECT, return_value=("key", "ws", "proj")) + def test_workflow_confidence_covers_every_mapped_class(self, _resolve, mock_api): + result = runner.invoke( + app, + ["autolabel", "start", "-p", "ws/proj", "--batch-id", "batch-1", "-m", "vehicle-detector"] + + ["--model-type", "workflow", "--workflow-output", "predictions"] + + ["--class-mapping", '{"car": "vehicle", "person": "pedestrian"}', "--confidence", "0.35"], + ) + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual(mock_api.call_args.kwargs["confidence_thresholds"], {"vehicle": 0.35, "pedestrian": 0.35}) + + @patch("roboflow.util.http.requests.post") + @patch(_RESOLVE_PROJECT, return_value=("key", "ws", "proj")) + def test_workflow_without_an_output_is_an_error(self, _resolve, mock_post): + result = runner.invoke( + app, + ["autolabel", "start", "-p", "ws/proj", "--batch-id", "batch-1", "-m", "vehicle-detector"] + + ["--model-type", "workflow", "--class-mapping", '{"car": "vehicle"}'], + ) + self.assertEqual(result.exit_code, 1, result.output) + self.assertIn("workflow_output", result.output) + mock_post.assert_not_called() + + @patch("roboflow.util.http.requests.post") + @patch(_RESOLVE_PROJECT, return_value=("key", "ws", "proj")) + def test_workflow_flags_on_a_foundation_model_are_an_error(self, _resolve, mock_post): + result = runner.invoke( + app, + ["autolabel", "start", "-p", "ws/proj", "--batch-id", "batch-1", "-m", "gpt-6-2-sol-boxes"] + + ["--class-mapping", '{"car": "vehicle"}'], + ) + self.assertEqual(result.exit_code, 1, result.output) + self.assertIn("only apply to model_type='workflow'", result.output) + mock_post.assert_not_called() + @patch("roboflow.adapters.rfapi.start_autolabel_job") @patch(_RESOLVE_PROJECT, return_value=("key", "ws", "proj")) def test_unknown_model_type_is_an_error(self, _resolve, mock_api): diff --git a/tests/test_project_autolabel.py b/tests/test_project_autolabel.py index 6ed295aa..a57dada0 100644 --- a/tests/test_project_autolabel.py +++ b/tests/test_project_autolabel.py @@ -92,6 +92,48 @@ def test_autolabel_rejects_unknown_model_type(self): with self.assertRaises(ValueError): self.project.autolabel("batch-1", "sam3-rle", model_type="hosted") + @patch("roboflow.adapters.rfapi.start_autolabel_job", return_value={"jobId": "job-1"}) + def test_autolabel_workflow_sends_the_workflow_fields(self, mock_start): + self.project.autolabel( + "batch-1", + "vehicle-detector", + model_type="workflow", + workflow_output="predictions", + class_mapping={"car": "vehicle", "truck": "vehicle"}, + workflow_inputs={"confidence": 0.3}, + confidence=0.4, + existing_annotations="merge", + ) + + mock_start.assert_called_once_with( + self.rf.api_key, + WORKSPACE_NAME, + PROJECT_NAME, + batch_id="batch-1", + model_type="workflow", + ontology=None, + num_images_to_label=None, + default_confidence=0.4, + confidence_thresholds={"vehicle": 0.4}, + run_nms=None, + reviewer_email=None, + model_options=None, + existing_annotations="merge", + keypoint_confidence_threshold=None, + size_filter=None, + workflow_id="vehicle-detector", + selected_output_name="predictions", + image_input_name=None, + input_values={"confidence": 0.3}, + class_mapping={"car": "vehicle", "truck": "vehicle"}, + ) + + @patch("roboflow.adapters.rfapi.start_autolabel_job") + def test_autolabel_workflow_without_a_class_mapping_is_refused_before_the_request(self, mock_start): + with self.assertRaisesRegex(ValueError, "class_mapping"): + self.project.autolabel("batch-1", "vehicle-detector", model_type="workflow", workflow_output="predictions") + mock_start.assert_not_called() + @patch("roboflow.adapters.rfapi.preview_autolabel", return_value={"predictions": []}) def test_autolabel_preview_builds_image_payload(self, mock_preview): result = self.project.autolabel_preview( diff --git a/tests/util/test_autolabel_utils.py b/tests/util/test_autolabel_utils.py index b52c632a..cfcdd79c 100644 --- a/tests/util/test_autolabel_utils.py +++ b/tests/util/test_autolabel_utils.py @@ -6,7 +6,13 @@ import unittest from unittest.mock import patch -from roboflow.util.autolabel_utils import existing_annotations_flags, image_payload, ontology_payload, resolve_model +from roboflow.util.autolabel_utils import ( + existing_annotations_flags, + image_payload, + ontology_payload, + resolve_model, + resolve_workflow, +) class TestImagePayload(unittest.TestCase): @@ -110,11 +116,81 @@ def test_roboflow_model_rides_in_model_options(self): ) self.assertEqual(resolve_model("proj/3", "roboflow"), ("custom_roboflow", {"modelId": "proj/3"})) + def test_workflow_is_sent_as_the_workflow_model_type(self): + # The Workflow's slug rides in workflowId (resolve_workflow), not in modelType. + self.assertEqual(resolve_model("vehicle-detector", "workflow"), ("workflow", None)) + def test_unknown_model_type_raises(self): with self.assertRaises(ValueError): resolve_model("x", "hosted") +class TestResolveWorkflow(unittest.TestCase): + def test_other_model_types_get_no_workflow_fields(self): + self.assertEqual(resolve_workflow("sam3-rle", "foundational"), (None, {})) + self.assertEqual( + resolve_workflow("proj/3", "roboflow", confidence=0.4, confidence_thresholds={"cat": 0.6}), + ({"cat": 0.6}, {}), + ) + + def test_workflow_options_are_refused_on_other_model_types(self): + # A catalog id's job would otherwise take a classMapping the caller never meant for it. + with self.assertRaisesRegex(ValueError, "workflow_output, class_mapping only apply to model_type='workflow'"): + resolve_workflow("gpt-6-2-sol-boxes", "foundational", class_mapping={"car": "car"}, workflow_output="out") + + def test_workflow_fields_and_fanned_out_confidence(self): + thresholds, fields = resolve_workflow( + "vehicle-detector", + "workflow", + workflow_output="predictions", + class_mapping={"car": "vehicle", "truck": "vehicle", "person": "pedestrian"}, + workflow_inputs={"confidence": 0.3}, + workflow_image_input="frame", + confidence=0.4, + ) + self.assertEqual(thresholds, {"vehicle": 0.4, "pedestrian": 0.4}) + self.assertEqual( + fields, + { + "workflow_id": "vehicle-detector", + "selected_output_name": "predictions", + "image_input_name": "frame", + "input_values": {"confidence": 0.3}, + "class_mapping": {"car": "vehicle", "truck": "vehicle", "person": "pedestrian"}, + }, + ) + + def test_mapped_classes_start_at_the_web_app_default(self): + # The API refuses a Workflow job without a threshold for every mapped class, and fans out nothing itself. + thresholds, _ = resolve_workflow( + "vehicle-detector", "workflow", workflow_output="predictions", class_mapping={"car": "vehicle"} + ) + self.assertEqual(thresholds, {"vehicle": 0.5}) + + def test_explicit_thresholds_are_sent_as_given(self): + thresholds, _ = resolve_workflow( + "vehicle-detector", + "workflow", + workflow_output="predictions", + class_mapping={"car": "vehicle"}, + confidence=0.4, + confidence_thresholds={"vehicle": 0.7}, + ) + self.assertEqual(thresholds, {"vehicle": 0.7}) + + def test_workflow_needs_an_output(self): + with self.assertRaisesRegex(ValueError, "needs workflow_output"): + resolve_workflow("vehicle-detector", "workflow", class_mapping={"car": "vehicle"}) + + def test_workflow_needs_a_class_mapping(self): + for mapping in (None, {}, ["car"]): + with self.subTest(class_mapping=mapping): + with self.assertRaisesRegex(ValueError, "needs class_mapping"): + resolve_workflow( + "vehicle-detector", "workflow", workflow_output="predictions", class_mapping=mapping + ) + + class TestExistingAnnotationsFlags(unittest.TestCase): def test_replace_is_the_server_default_and_sends_nothing(self): self.assertEqual(existing_annotations_flags(None), {}) From 5980d33822981caf2f6f4468fbd54594b48c2777 Mon Sep 17 00:00:00 2001 From: Iuri de Silvio Date: Mon, 30 Nov 2026 19:35:06 +0100 Subject: [PATCH 4/7] Link the Auto Label Workflow changelog entry to #594 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 25fb8a36..a032c86a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,7 +24,8 @@ All notable changes to this project will be documented in this file. Workflow's URL, `class_mapping` maps each class it outputs to a project class (classes left out are dropped), and every mapped class starts at `confidence` (0.5 when omitted) unless `confidence_thresholds` sets it. - `workflow_inputs` / `--workflow-inputs` fill the Workflow's other inputs. + `workflow_inputs` / `--workflow-inputs` fill the Workflow's other inputs + ([#594](https://github.com/roboflow/roboflow-python/pull/594)). ### Changed From 88be3a9103cf8f1d539a893efac0318bdb427149 Mon Sep 17 00:00:00 2001 From: Iuri de Silvio Date: Wed, 2 Dec 2026 11:18:54 +0100 Subject: [PATCH 5/7] Run CI against main The PR now targets main; the retarget alone does not start the test workflow, which runs only for pull requests into main. Co-Authored-By: Claude Opus 5.5 From 482c1e5cd3c278458609819c267be6545d25d95b Mon Sep 17 00:00:00 2001 From: Iuri de Silvio Date: Thu, 3 Dec 2026 13:08:45 +0100 Subject: [PATCH 6/7] Label by Example in Project.autolabel and the CLI (#595) * Take Label by Example's reference examples in the SDK and the CLI Project.autolabel and autolabel_preview take reference_examples, the ids of labeled images of the project the model sees as examples, and the CLI takes --reference-example on start and preview. autolabel models marks the models that take them. Co-Authored-By: Claude Opus 5.5 * Link the Label by Example changelog entry to #595 Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++++ CLI-COMMANDS.md | 13 +++++++-- roboflow/adapters/rfapi.py | 20 +++++++++++++- roboflow/cli/handlers/autolabel.py | 23 +++++++++++++-- roboflow/core/project.py | 26 +++++++++++++++++ roboflow/core/workspace.py | 7 +++-- tests/adapters/test_autolabel.py | 26 +++++++++++++++++ tests/cli/test_autolabel_handler.py | 43 ++++++++++++++++++++++++++++- tests/test_project_autolabel.py | 15 ++++++++++ 9 files changed, 173 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a032c86a..42e8d19b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/CLI-COMMANDS.md b/CLI-COMMANDS.md index 4d28bf36..e1353a81 100644 --- a/CLI-COMMANDS.md +++ b/CLI-COMMANDS.md @@ -333,12 +333,15 @@ roboflow autolabel start -p my-actions --batch-id -m video-segm --ontology '{"a person jumps": "jump"}' --model-options '{"sampleFps": 2}' roboflow autolabel start -p my-project --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 -m gemini-4-argon-boxes \ + --ontology '{"a green umbrella": "umbrella"}' --reference-example --reference-example roboflow autolabel job roboflow autolabel job -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 @@ -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}'` @@ -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"] ``` diff --git a/roboflow/adapters/rfapi.py b/roboflow/adapters/rfapi.py index 8f70cd37..1ed75e3f 100644 --- a/roboflow/adapters/rfapi.py +++ b/roboflow/adapters/rfapi.py @@ -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. @@ -1531,6 +1540,7 @@ def preview_autolabel( image, ontology=None, confidence_threshold=None, + reference_examples=None, ): """Preview one image with a foundation model before starting a job. @@ -1538,6 +1548,8 @@ def preview_autolabel( 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?}``. """ @@ -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}, @@ -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, @@ -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: @@ -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, diff --git a/roboflow/cli/handlers/autolabel.py b/roboflow/cli/handlers/autolabel.py index dcfe5064..a43cfe78 100644 --- a/roboflow/cli/handlers/autolabel.py +++ b/roboflow/cli/handlers/autolabel.py @@ -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) @@ -54,6 +62,7 @@ def preview( image=resolved_image, ontology=resolved_ontology, confidence_threshold=confidence, + reference_examples=reference_examples, ), ) @@ -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. @@ -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, ) @@ -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) diff --git a/roboflow/core/project.py b/roboflow/core/project.py index 802cb3ce..bb51505b 100644 --- a/roboflow/core/project.py +++ b/roboflow/core/project.py @@ -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. @@ -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`` @@ -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( @@ -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. @@ -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 @@ -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", @@ -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, ) diff --git a/roboflow/core/workspace.py b/roboflow/core/workspace.py index 60a8065d..24a126cd 100644 --- a/roboflow/core/workspace.py +++ b/roboflow/core/workspace.py @@ -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"]: diff --git a/tests/adapters/test_autolabel.py b/tests/adapters/test_autolabel.py index 6b10197d..d0f01a87 100644 --- a/tests/adapters/test_autolabel.py +++ b/tests/adapters/test_autolabel.py @@ -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"}) diff --git a/tests/cli/test_autolabel_handler.py b/tests/cli/test_autolabel_handler.py index 862e0172..8268b82a 100644 --- a/tests/cli/test_autolabel_handler.py +++ b/tests/cli/test_autolabel_handler.py @@ -59,7 +59,8 @@ 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"]) @@ -67,6 +68,24 @@ def test_table_shows_the_project_types_each_model_labels(self, _resolve, mock_ap 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): @@ -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={}) @@ -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") @@ -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): diff --git a/tests/test_project_autolabel.py b/tests/test_project_autolabel.py index a57dada0..b048c375 100644 --- a/tests/test_project_autolabel.py +++ b/tests/test_project_autolabel.py @@ -34,6 +34,7 @@ def test_autolabel_foundational_passes_model_as_is(self, mock_start): existing_annotations=None, keypoint_confidence_threshold=None, size_filter=None, + reference_examples=None, ) @patch("roboflow.adapters.rfapi.start_autolabel_job", return_value={"jobId": "job-1"}) @@ -121,6 +122,7 @@ def test_autolabel_workflow_sends_the_workflow_fields(self, mock_start): existing_annotations="merge", keypoint_confidence_threshold=None, size_filter=None, + reference_examples=None, workflow_id="vehicle-detector", selected_output_name="predictions", image_input_name=None, @@ -152,8 +154,21 @@ def test_autolabel_preview_builds_image_payload(self, mock_preview): image={"type": "url", "value": "https://example.com/cat.jpg"}, ontology={"cat": "cat"}, confidence_threshold=0.3, + reference_examples=None, ) + @patch("roboflow.adapters.rfapi.preview_autolabel", return_value={"predictions": []}) + @patch("roboflow.adapters.rfapi.start_autolabel_job", return_value={"jobId": "job-1"}) + def test_autolabel_forwards_reference_examples(self, mock_start, mock_preview): + examples = ["image-1", "image-2"] + self.project.autolabel_preview( + "gemini-4-argon-boxes", "https://example.com/cat.jpg", reference_examples=examples + ) + self.project.autolabel("batch-1", "gemini-4-argon-boxes", reference_examples=examples) + + self.assertEqual(mock_preview.call_args.kwargs["reference_examples"], examples) + self.assertEqual(mock_start.call_args.kwargs["reference_examples"], examples) + @patch("roboflow.adapters.rfapi.get_autolabel_job", return_value={"status": "done"}) def test_autolabel_job_wrappers_delegate(self, mock_get): self.assertEqual(self.project.autolabel_job("job-1"), {"status": "done"}) From bc65444a1b0bb0eaed17b90524c34c9eeff8563c Mon Sep 17 00:00:00 2001 From: Iuri de Silvio Date: Thu, 3 Dec 2026 21:59:09 +0100 Subject: [PATCH 7/7] Move the Auto Label changelog entries to Unreleased 1.7.5 was released without #594 and #595, and the merge of main put their entries under it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f245d2a2..12c4382e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,24 +2,10 @@ All notable changes to this project will be documented in this file. -## 1.7.5 +## Unreleased ### Added -- Package custom OWLv2 checkpoints for upload with `Workspace.deploy_model()`. - See [Upload a custom OWLv2 model](docs/owlv2-upload.md) - ([#569](https://github.com/roboflow/roboflow-python/pull/569)). -- `Project.autolabel(..., size_filter={"minWidth": 20, "maxWidth": 400})` and - `roboflow autolabel start --min-width 20 --max-width 400` (also - `--min-height`, `--max-height`) drop labels whose box is outside those sizes, - in image pixels. Each bound is optional and inclusive; a polygon, mask or - keypoint instance is measured by the box around it, and classification - projects ignore the filter. Sent as the API's `sizeFilter` - ([#593](https://github.com/roboflow/roboflow-python/pull/593)). -- `roboflow autolabel models` shows the project types each model labels, now - that the catalog has keypoint and classification models besides detection - and segmentation ones - ([#593](https://github.com/roboflow/roboflow-python/pull/593)). - Auto Label with a saved Workflow: `Project.autolabel("batch-id", model="vehicle-detector", model_type="workflow", workflow_output="predictions", class_mapping={"car": "vehicle"})` and `roboflow autolabel start --model-type workflow --workflow-output @@ -39,6 +25,25 @@ All notable changes to this project will be documented in this file. (`takesReferenceExamples` in `Workspace.autolabel_models()`) ([#595](https://github.com/roboflow/roboflow-python/pull/595)). +## 1.7.5 + +### Added + +- Package custom OWLv2 checkpoints for upload with `Workspace.deploy_model()`. + See [Upload a custom OWLv2 model](docs/owlv2-upload.md) + ([#569](https://github.com/roboflow/roboflow-python/pull/569)). +- `Project.autolabel(..., size_filter={"minWidth": 20, "maxWidth": 400})` and + `roboflow autolabel start --min-width 20 --max-width 400` (also + `--min-height`, `--max-height`) drop labels whose box is outside those sizes, + in image pixels. Each bound is optional and inclusive; a polygon, mask or + keypoint instance is measured by the box around it, and classification + projects ignore the filter. Sent as the API's `sizeFilter` + ([#593](https://github.com/roboflow/roboflow-python/pull/593)). +- `roboflow autolabel models` shows the project types each model labels, now + that the catalog has keypoint and classification models besides detection + and segmentation ones + ([#593](https://github.com/roboflow/roboflow-python/pull/593)). + ### Changed - The Auto Label docs cover keypoint-detection projects labeled by the