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"})