-
Notifications
You must be signed in to change notification settings - Fork 29
Add COCO annotation import/export support #679
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
4b1bbaa
Add COCO annotation import/export support
deanp70 79f15b0
Merge branch 'main' into coco_converter
deanp70 e68048a
Test: use the coco_converter branch of the annotation converter while…
kbolashev 4f830e4
Fix review comments
deanp70 eb2c643
Update setup.py
deanp70 15289ed
bump converter version
deanp70 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,198 @@ | ||
| import datetime | ||
| import json | ||
| from unittest.mock import patch | ||
|
|
||
| import pytest | ||
| from dagshub_annotation_converter.ir.image import ( | ||
| IRBBoxImageAnnotation, | ||
| CoordinateStyle, | ||
| ) | ||
|
|
||
| from dagshub.data_engine.annotation.importer import AnnotationImporter, AnnotationsNotFoundError | ||
| from dagshub.data_engine.annotation.metadata import MetadataAnnotations | ||
| from dagshub.data_engine.client.models import MetadataSelectFieldSchema | ||
| from dagshub.data_engine.dtypes import MetadataFieldType, ReservedTags | ||
| from dagshub.data_engine.model.datapoint import Datapoint | ||
| from dagshub.data_engine.model.query_result import QueryResult | ||
|
|
||
|
|
||
| # --- import --- | ||
|
|
||
|
|
||
| def test_import_coco_from_file(ds, tmp_path): | ||
| _write_coco(tmp_path, _make_coco_json()) | ||
| importer = AnnotationImporter(ds, "coco", tmp_path / "annotations.json", load_from="disk") | ||
| result = importer.import_annotations() | ||
|
|
||
| assert "image1.jpg" in result | ||
| assert len(result["image1.jpg"]) == 1 | ||
| assert isinstance(result["image1.jpg"][0], IRBBoxImageAnnotation) | ||
|
|
||
|
|
||
| def test_import_coco_nonexistent_raises(ds, tmp_path): | ||
| importer = AnnotationImporter(ds, "coco", tmp_path / "nope.json", load_from="disk") | ||
| with pytest.raises(AnnotationsNotFoundError): | ||
| importer.import_annotations() | ||
|
|
||
|
|
||
| def test_coco_convert_to_ls_tasks(ds, tmp_path, mock_dagshub_auth): | ||
| importer = AnnotationImporter(ds, "coco", tmp_path / "ann.json", load_from="disk") | ||
| bbox = IRBBoxImageAnnotation( | ||
| filename="test.jpg", categories={"cat": 1.0}, | ||
| top=0.1, left=0.1, width=0.2, height=0.2, | ||
| image_width=640, image_height=480, | ||
| coordinate_style=CoordinateStyle.NORMALIZED, | ||
| ) | ||
| tasks = importer.convert_to_ls_tasks({"test.jpg": [bbox]}) | ||
|
|
||
| assert "test.jpg" in tasks | ||
| task_json = json.loads(tasks["test.jpg"]) | ||
| assert "annotations" in task_json | ||
| assert len(task_json["annotations"]) > 0 | ||
|
|
||
|
|
||
| # --- _resolve_annotation_field --- | ||
|
|
||
|
|
||
| def test_resolve_explicit_field(ds): | ||
| qr = _make_qr(ds, [], ann_field="my_ann") | ||
| assert qr._resolve_annotation_field("explicit") == "explicit" | ||
|
|
||
|
|
||
| def test_resolve_auto_field(ds): | ||
| qr = _make_qr(ds, [], ann_field="my_ann") | ||
| assert qr._resolve_annotation_field(None) == "my_ann" | ||
|
|
||
|
|
||
| def test_resolve_no_fields_raises(ds): | ||
| qr = _make_qr(ds, [], ann_field=None) | ||
| with pytest.raises(ValueError, match="No annotation fields"): | ||
| qr._resolve_annotation_field(None) | ||
|
|
||
|
|
||
| def test_resolve_picks_alphabetically_first(ds): | ||
| fields = [] | ||
| for name in ["zebra_ann", "alpha_ann"]: | ||
| fields.append(MetadataSelectFieldSchema( | ||
| asOf=int(datetime.datetime.now().timestamp()), | ||
| autoGenerated=False, originalName=name, | ||
| multiple=False, valueType=MetadataFieldType.BLOB, | ||
| name=name, tags={ReservedTags.ANNOTATION.value}, | ||
| )) | ||
| qr = QueryResult(datasource=ds, _entries=[], fields=fields) | ||
| assert qr._resolve_annotation_field(None) == "alpha_ann" | ||
|
|
||
|
|
||
| # --- export_as_coco --- | ||
|
|
||
|
|
||
| def test_export_coco_bbox_coordinates(ds, tmp_path): | ||
| dp = Datapoint(datasource=ds, path="images/test.jpg", datapoint_id=0, metadata={}) | ||
| ann = IRBBoxImageAnnotation( | ||
| filename="images/test.jpg", categories={"cat": 1.0}, | ||
| top=20.0, left=10.0, width=30.0, height=40.0, | ||
| image_width=640, image_height=480, | ||
| coordinate_style=CoordinateStyle.DENORMALIZED, | ||
| ) | ||
| dp.metadata["ann"] = MetadataAnnotations(datapoint=dp, field="ann", annotations=[ann]) | ||
|
|
||
| qr = _make_qr(ds, [dp], ann_field="ann") | ||
| with patch.object(qr, "download_files"): | ||
| result = qr.export_as_coco(download_dir=tmp_path, annotation_field="ann") | ||
|
|
||
| coco = json.loads(result.read_text()) | ||
| assert coco["annotations"][0]["bbox"] == [10.0, 20.0, 30.0, 40.0] | ||
|
|
||
|
|
||
| def test_export_coco_no_annotations_raises(ds, tmp_path): | ||
| dp = Datapoint(datasource=ds, path="test.jpg", datapoint_id=0, metadata={}) | ||
| dp.metadata["ann"] = MetadataAnnotations(datapoint=dp, field="ann", annotations=[]) | ||
|
|
||
| qr = _make_qr(ds, [dp], ann_field="ann") | ||
| with pytest.raises(RuntimeError, match="No annotations found"): | ||
| qr.export_as_coco(download_dir=tmp_path, annotation_field="ann") | ||
|
|
||
|
|
||
| def test_export_coco_explicit_classes(ds, tmp_path): | ||
| dp = Datapoint(datasource=ds, path="images/test.jpg", datapoint_id=0, metadata={}) | ||
| dp.metadata["ann"] = MetadataAnnotations( | ||
| datapoint=dp, field="ann", annotations=[_make_image_bbox("images/test.jpg")] | ||
| ) | ||
|
|
||
| qr = _make_qr(ds, [dp], ann_field="ann") | ||
| with patch.object(qr, "download_files"): | ||
| result = qr.export_as_coco( | ||
| download_dir=tmp_path, annotation_field="ann", classes={1: "cat", 2: "dog"} | ||
| ) | ||
|
|
||
| coco = json.loads(result.read_text()) | ||
| assert "cat" in {c["name"] for c in coco["categories"]} | ||
|
|
||
|
|
||
| def test_export_coco_custom_filename(ds, tmp_path): | ||
| dp = Datapoint(datasource=ds, path="images/test.jpg", datapoint_id=0, metadata={}) | ||
| dp.metadata["ann"] = MetadataAnnotations( | ||
| datapoint=dp, field="ann", annotations=[_make_image_bbox("images/test.jpg")] | ||
| ) | ||
|
|
||
| qr = _make_qr(ds, [dp], ann_field="ann") | ||
| with patch.object(qr, "download_files"): | ||
| result = qr.export_as_coco( | ||
| download_dir=tmp_path, annotation_field="ann", output_filename="custom.json" | ||
| ) | ||
|
|
||
| assert result.name == "custom.json" | ||
|
|
||
|
|
||
| def test_export_coco_multiple_datapoints(ds, tmp_path): | ||
| dps = [] | ||
| for i, name in enumerate(["a.jpg", "b.jpg"]): | ||
| dp = Datapoint(datasource=ds, path=name, datapoint_id=i, metadata={}) | ||
| dp.metadata["ann"] = MetadataAnnotations( | ||
| datapoint=dp, field="ann", annotations=[_make_image_bbox(name)] | ||
| ) | ||
| dps.append(dp) | ||
|
|
||
| qr = _make_qr(ds, dps, ann_field="ann") | ||
| with patch.object(qr, "download_files"): | ||
| result = qr.export_as_coco(download_dir=tmp_path, annotation_field="ann") | ||
|
|
||
| coco = json.loads(result.read_text()) | ||
| assert len(coco["annotations"]) == 2 | ||
| assert len(coco["images"]) == 2 | ||
|
|
||
|
|
||
| # --- helpers --- | ||
|
|
||
|
|
||
| def _make_coco_json(): | ||
| return { | ||
| "categories": [{"id": 1, "name": "cat"}], | ||
| "images": [{"id": 1, "width": 640, "height": 480, "file_name": "image1.jpg"}], | ||
| "annotations": [{"id": 1, "image_id": 1, "category_id": 1, "bbox": [10, 20, 30, 40]}], | ||
| } | ||
|
|
||
|
|
||
| def _write_coco(tmp_path, coco): | ||
| (tmp_path / "annotations.json").write_text(json.dumps(coco)) | ||
|
|
||
|
|
||
| def _make_image_bbox(filename="test.jpg") -> IRBBoxImageAnnotation: | ||
| return IRBBoxImageAnnotation( | ||
| filename=filename, categories={"cat": 1.0}, | ||
| top=20.0, left=10.0, width=30.0, height=40.0, | ||
| image_width=640, image_height=480, | ||
| coordinate_style=CoordinateStyle.DENORMALIZED, | ||
| ) | ||
|
|
||
|
|
||
| def _make_qr(ds, datapoints, ann_field=None): | ||
| fields = [] | ||
| if ann_field: | ||
| fields.append(MetadataSelectFieldSchema( | ||
| asOf=int(datetime.datetime.now().timestamp()), | ||
| autoGenerated=False, originalName=ann_field, | ||
| multiple=False, valueType=MetadataFieldType.BLOB, | ||
| name=ann_field, tags={ReservedTags.ANNOTATION.value}, | ||
| )) | ||
| return QueryResult(datasource=ds, _entries=datapoints, fields=fields) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.