From 71d5b695442ef36c1a574b2c7b6a956b5d6f2667 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Thu, 20 Oct 2022 02:29:14 -0700 Subject: [PATCH 01/21] Added files for the image embedder implementation and a simple test --- mediapipe/python/BUILD | 1 + .../tasks/python/components/containers/BUILD | 18 ++ .../components/containers/embeddings.py | 246 +++++++++++++++ .../python/components/containers/rect.py | 141 +++++++++ mediapipe/tasks/python/components/proto/BUILD | 28 ++ .../tasks/python/components/proto/__init__.py | 13 + .../components/proto/embedder_options.py | 72 +++++ mediapipe/tasks/python/test/vision/BUILD | 19 ++ .../python/test/vision/image_embedder_test.py | 98 ++++++ mediapipe/tasks/python/vision/BUILD | 19 ++ .../tasks/python/vision/image_embedder.py | 288 ++++++++++++++++++ 11 files changed, 943 insertions(+) create mode 100644 mediapipe/tasks/python/components/containers/embeddings.py create mode 100644 mediapipe/tasks/python/components/containers/rect.py create mode 100644 mediapipe/tasks/python/components/proto/BUILD create mode 100644 mediapipe/tasks/python/components/proto/__init__.py create mode 100644 mediapipe/tasks/python/components/proto/embedder_options.py create mode 100644 mediapipe/tasks/python/test/vision/image_embedder_test.py create mode 100644 mediapipe/tasks/python/vision/image_embedder.py diff --git a/mediapipe/python/BUILD b/mediapipe/python/BUILD index 2911e2fd..3df0e279 100644 --- a/mediapipe/python/BUILD +++ b/mediapipe/python/BUILD @@ -88,6 +88,7 @@ cc_library( name = "builtin_task_graphs", deps = [ "//mediapipe/tasks/cc/vision/object_detector:object_detector_graph", + "//mediapipe/tasks/cc/vision/image_embedder:image_embedder_graph", ], ) diff --git a/mediapipe/tasks/python/components/containers/BUILD b/mediapipe/tasks/python/components/containers/BUILD index 8dd9fcd6..cb123562 100644 --- a/mediapipe/tasks/python/components/containers/BUILD +++ b/mediapipe/tasks/python/components/containers/BUILD @@ -27,6 +27,15 @@ py_library( ], ) +py_library( + name = "rect", + srcs = ["rect.py"], + deps = [ + "//mediapipe/framework/formats:rect_py_pb2", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) + py_library( name = "category", srcs = ["category.py"], @@ -47,3 +56,12 @@ py_library( "//mediapipe/tasks/python/core:optional_dependencies", ], ) + +py_library( + name = "embeddings", + srcs = ["embeddings.py"], + deps = [ + "//mediapipe/tasks/cc/components/containers/proto:embeddings_py_pb2", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) diff --git a/mediapipe/tasks/python/components/containers/embeddings.py b/mediapipe/tasks/python/components/containers/embeddings.py new file mode 100644 index 00000000..21f53670 --- /dev/null +++ b/mediapipe/tasks/python/components/containers/embeddings.py @@ -0,0 +1,246 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Embeddings data class.""" + +import dataclasses +from typing import Any, Optional, List + +import numpy as np +from mediapipe.tasks.cc.components.containers.proto import embeddings_pb2 +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + +_FloatEmbeddingProto = embeddings_pb2.FloatEmbedding +_QuantizedEmbeddingProto = embeddings_pb2.QuantizedEmbedding +_EmbeddingEntryProto = embeddings_pb2.EmbeddingEntry +_EmbeddingsProto = embeddings_pb2.Embeddings +_EmbeddingResultProto = embeddings_pb2.EmbeddingResult + + +@dataclasses.dataclass +class FloatEmbedding: + """Defines a dense floating-point embedding. + + Attributes: + values: A NumPy array indicating the raw output of the embedding layer. + """ + + values: np.ndarray + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _FloatEmbeddingProto: + """Generates a FloatEmbedding protobuf object.""" + return _FloatEmbeddingProto(values=self.values) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, pb2_obj: _FloatEmbeddingProto) -> 'FloatEmbedding': + """Creates a `FloatEmbedding` object from the given protobuf object.""" + return FloatEmbedding(values=np.array(pb2_obj.value_float, dtype=float)) + + def __eq__(self, other: Any) -> bool: + """Checks if this object is equal to the given object. + Args: + other: The object to be compared with. + Returns: + True if the objects are equal. + """ + if not isinstance(other, FloatEmbedding): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class QuantizedEmbedding: + """Defines a dense scalar-quantized embedding. + + Attributes: + values: A NumPy array indicating the raw output of the embedding layer. + """ + + values: np.ndarray + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _QuantizedEmbeddingProto: + """Generates a QuantizedEmbedding protobuf object.""" + return _QuantizedEmbeddingProto(values=self.values) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, pb2_obj: _QuantizedEmbeddingProto) -> 'QuantizedEmbedding': + """Creates a `QuantizedEmbedding` object from the given protobuf object.""" + return QuantizedEmbedding( + values=np.array(bytearray(pb2_obj.value_string), dtype=np.uint8)) + + def __eq__(self, other: Any) -> bool: + """Checks if this object is equal to the given object. + Args: + other: The object to be compared with. + Returns: + True if the objects are equal. + """ + if not isinstance(other, QuantizedEmbedding): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class EmbeddingEntry: + """Floating-point or scalar-quantized embedding with an optional timestamp. + + Attributes: + embedding: The actual embedding, either floating-point or scalar-quantized. + timestamp_ms: The optional timestamp (in milliseconds) associated to the + embedding entry. This is useful for time series use cases, e.g. audio + embedding. + """ + + embedding: np.ndarray + timestamp_ms: Optional[int] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _EmbeddingEntryProto: + """Generates a EmbeddingEntry protobuf object.""" + + if self.embedding.dtype == float: + return _EmbeddingEntryProto(float_embedding=self.embedding) + + elif self.embedding.dtype == np.uint8: + return _EmbeddingEntryProto(quantized_embedding=bytes(self.embedding)) + + else: + raise ValueError("Invalid dtype. Only float and np.uint8 are supported.") + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, pb2_obj: _EmbeddingEntryProto) -> 'EmbeddingEntry': + """Creates a `EmbeddingEntry` object from the given protobuf object.""" + + if pb2_obj.float_embedding: + return EmbeddingEntry( + embedding=np.array(pb2_obj.float_embedding.values, dtype=float)) + + elif pb2_obj.quantized_embedding: + return EmbeddingEntry( + embedding=np.array(bytearray(pb2_obj.quantized_embedding.values), + dtype=np.uint8)) + + else: + raise ValueError("Either float_embedding or quantized_embedding must " + "exist.") + + def __eq__(self, other: Any) -> bool: + """Checks if this object is equal to the given object. + Args: + other: The object to be compared with. + Returns: + True if the objects are equal. + """ + if not isinstance(other, EmbeddingEntry): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class Embeddings: + """Embeddings for a given embedder head. + Attributes: + entries: A list of `ClassificationEntry` objects. + head_index: The index of the embedder head that produced this embedding. + This is useful for multi-head models. + head_name: The name of the embedder head, which is the corresponding tensor + metadata name (if any). This is useful for multi-head models. + """ + + entries: List[EmbeddingEntry] + head_index: int + head_name: str + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _EmbeddingsProto: + """Generates a Embeddings protobuf object.""" + return _EmbeddingsProto( + entries=[entry.to_pb2() for entry in self.entries], + head_index=self.head_index, + head_name=self.head_name) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _EmbeddingsProto) -> 'Embeddings': + """Creates a `Embeddings` object from the given protobuf object.""" + return Embeddings( + entries=[ + EmbeddingEntry.create_from_pb2(entry) + for entry in pb2_obj.entries + ], + head_index=pb2_obj.head_index, + head_name=pb2_obj.head_name) + + def __eq__(self, other: Any) -> bool: + """Checks if this object is equal to the given object. + Args: + other: The object to be compared with. + Returns: + True if the objects are equal. + """ + if not isinstance(other, Embeddings): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class EmbeddingResult: + """Contains one set of results per embedder head. + Attributes: + embeddings: A list of `Embeddings` objects. + """ + + embeddings: List[Embeddings] + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _EmbeddingResultProto: + """Generates a EmbeddingResult protobuf object.""" + return _EmbeddingResultProto( + embeddings=[ + embedding.to_pb2() for embedding in self.embeddings + ]) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, pb2_obj: _EmbeddingResultProto) -> 'EmbeddingResult': + """Creates a `EmbeddingResult` object from the given protobuf object.""" + return EmbeddingResult( + embeddings=[ + Embeddings.create_from_pb2(embedding) + for embedding in pb2_obj.embeddings + ]) + + def __eq__(self, other: Any) -> bool: + """Checks if this object is equal to the given object. + Args: + other: The object to be compared with. + Returns: + True if the objects are equal. + """ + if not isinstance(other, EmbeddingResult): + return False + + return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/components/containers/rect.py b/mediapipe/tasks/python/components/containers/rect.py new file mode 100644 index 00000000..aadb404d --- /dev/null +++ b/mediapipe/tasks/python/components/containers/rect.py @@ -0,0 +1,141 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Rect data class.""" + +import dataclasses +from typing import Any, Optional + +from mediapipe.framework.formats import rect_pb2 +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + +_RectProto = rect_pb2.Rect +_NormalizedRectProto = rect_pb2.NormalizedRect + + +@dataclasses.dataclass +class Rect: + """A rectangle with rotation in image coordinates. + + Attributes: + x_center : The X coordinate of the top-left corner, in pixels. + y_center : The Y coordinate of the top-left corner, in pixels. + width: The width of the rectangle, in pixels. + height: The height of the rectangle, in pixels. + rotation: Rotation angle is clockwise in radians. + rect_id: Optional unique id to help associate different rectangles to each + other. + """ + + x_center: int + y_center: int + width: int + height: int + rotation: Optional[float] = 0.0 + rect_id: Optional[int] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _RectProto: + """Generates a Rect protobuf object.""" + return _RectProto( + x_center=self.x_center, + y_center=self.y_center, + width=self.width, + height=self.height, + ) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _RectProto) -> 'Rect': + """Creates a `Rect` object from the given protobuf object.""" + return Rect( + x_center=pb2_obj.x_center, + y_center=pb2_obj.y_center, + width=pb2_obj.width, + height=pb2_obj.height) + + def __eq__(self, other: Any) -> bool: + """Checks if this object is equal to the given object. + + Args: + other: The object to be compared with. + + Returns: + True if the objects are equal. + """ + if not isinstance(other, Rect): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class NormalizedRect: + """A rectangle with rotation in normalized coordinates. The values of box + center location and size are within [0, 1]. + + Attributes: + x_center : The X normalized coordinate of the top-left corner. + y_center : The Y normalized coordinate of the top-left corner. + width: The width of the rectangle. + height: The height of the rectangle. + rotation: Rotation angle is clockwise in radians. + rect_id: Optional unique id to help associate different rectangles to each + other. + """ + + x_center: float + y_center: float + width: float + height: float + rotation: Optional[float] = 0.0 + rect_id: Optional[int] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _NormalizedRectProto: + """Generates a NormalizedRect protobuf object.""" + return _NormalizedRectProto( + x_center=self.x_center, + y_center=self.y_center, + width=self.width, + height=self.height, + rotation=self.rotation, + rect_id=self.rect_id + ) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _NormalizedRectProto) -> 'NormalizedRect': + """Creates a `NormalizedRect` object from the given protobuf object.""" + return NormalizedRect( + x_center=pb2_obj.x_center, + y_center=pb2_obj.y_center, + width=pb2_obj.width, + height=pb2_obj.height, + rotation=pb2_obj.rotation, + rect_id=pb2_obj.rect_id + ) + + def __eq__(self, other: Any) -> bool: + """Checks if this object is equal to the given object. + + Args: + other: The object to be compared with. + + Returns: + True if the objects are equal. + """ + if not isinstance(other, NormalizedRect): + return False + + return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/components/proto/BUILD b/mediapipe/tasks/python/components/proto/BUILD new file mode 100644 index 00000000..973f150c --- /dev/null +++ b/mediapipe/tasks/python/components/proto/BUILD @@ -0,0 +1,28 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Placeholder for internal Python strict library compatibility macro. + +package(default_visibility = ["//mediapipe/tasks:internal"]) + +licenses(["notice"]) + +py_library( + name = "embedder_options", + srcs = ["embedder_options.py"], + deps = [ + "//mediapipe/tasks/cc/components/proto:embedder_options_py_pb2", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) diff --git a/mediapipe/tasks/python/components/proto/__init__.py b/mediapipe/tasks/python/components/proto/__init__.py new file mode 100644 index 00000000..65c1214a --- /dev/null +++ b/mediapipe/tasks/python/components/proto/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/mediapipe/tasks/python/components/proto/embedder_options.py b/mediapipe/tasks/python/components/proto/embedder_options.py new file mode 100644 index 00000000..3c257b97 --- /dev/null +++ b/mediapipe/tasks/python/components/proto/embedder_options.py @@ -0,0 +1,72 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Embedder options data class.""" + +import dataclasses +from typing import Any, Optional + +from mediapipe.tasks.cc.components.proto import embedder_options_pb2 +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + +_EmbedderOptionsProto = embedder_options_pb2.EmbedderOptions + + +@dataclasses.dataclass +class EmbedderOptions: + """Shared options used by all embedding extraction tasks. + + Attributes: + l2_normalize: Whether to normalize the returned feature vector with L2 norm. + Use this option only if the model does not already contain a native + L2_NORMALIZATION TF Lite Op. In most cases, this is already the case and + L2 norm is thus achieved through TF Lite inference. + quantize: Whether the returned embedding should be quantized to bytes via + scalar quantization. Embeddings are implicitly assumed to be unit-norm and + therefore any dimension is guaranteed to have a value in [-1.0, 1.0]. Use + the l2_normalize option if this is not the case. + """ + + l2_normalize: Optional[bool] = None + quantize: Optional[bool] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _EmbedderOptionsProto: + """Generates a EmbedderOptions protobuf object.""" + return _EmbedderOptionsProto( + l2_normalize=self.l2_normalize, + quantize=self.quantize + ) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _EmbedderOptionsProto) -> 'EmbedderOptions': + """Creates a `EmbedderOptions` object from the given protobuf object.""" + return EmbedderOptions( + l2_normalize=pb2_obj.l2_normalize, + quantize=pb2_obj.quantize + ) + + def __eq__(self, other: Any) -> bool: + """Checks if this object is equal to the given object. + + Args: + other: The object to be compared with. + + Returns: + True if the objects are equal. + """ + if not isinstance(other, EmbedderOptions): + return False + + return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/test/vision/BUILD b/mediapipe/tasks/python/test/vision/BUILD index 290b665e..62595d37 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -36,3 +36,22 @@ py_test( "//mediapipe/tasks/python/vision/core:vision_task_running_mode", ], ) + +py_test( + name = "image_embedder_test", + srcs = ["image_embedder_test.py"], + data = [ + "//mediapipe/tasks/testdata/vision:test_images", + "//mediapipe/tasks/testdata/vision:test_models", + ], + deps = [ + "//mediapipe/python:_framework_bindings", + "//mediapipe/tasks/python/components/proto:embedder_options", + "//mediapipe/tasks/python/components/containers:embeddings", + "//mediapipe/tasks/python/components/containers:rect", + "//mediapipe/tasks/python/core:base_options", + "//mediapipe/tasks/python/test:test_utils", + "//mediapipe/tasks/python/vision:image_embedder", + "//mediapipe/tasks/python/vision/core:vision_task_running_mode", + ], +) diff --git a/mediapipe/tasks/python/test/vision/image_embedder_test.py b/mediapipe/tasks/python/test/vision/image_embedder_test.py new file mode 100644 index 00000000..8ddf3c99 --- /dev/null +++ b/mediapipe/tasks/python/test/vision/image_embedder_test.py @@ -0,0 +1,98 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for image embedder.""" + +import enum +from unittest import mock + +import numpy as np +from absl.testing import absltest +from absl.testing import parameterized + +from mediapipe.python._framework_bindings import image as image_module +from mediapipe.tasks.python.components.proto import embedder_options as embedder_options_module +from mediapipe.tasks.python.components.containers import embeddings as embeddings_module +from mediapipe.tasks.python.components.containers import rect as rect_module +from mediapipe.tasks.python.core import base_options as base_options_module +from mediapipe.tasks.python.test import test_utils +from mediapipe.tasks.python.vision import image_embedder +from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module + +_NormalizedRect = rect_module.NormalizedRect +_BaseOptions = base_options_module.BaseOptions +_EmbedderOptions = embedder_options_module.EmbedderOptions +_FloatEmbedding = embeddings_module.FloatEmbedding +_QuantizedEmbedding = embeddings_module.QuantizedEmbedding +_ClassificationEntry = embeddings_module.EmbeddingEntry +_Classifications = embeddings_module.Embeddings +_ClassificationResult = embeddings_module.EmbeddingResult +_Image = image_module.Image +_ImageEmbedder = image_embedder.ImageEmbedder +_ImageEmbedderOptions = image_embedder.ImageEmbedderOptions +_RUNNING_MODE = running_mode_module.VisionTaskRunningMode + +_MODEL_FILE = 'mobilenet_v3_small_100_224_embedder.tflite' +_IMAGE_FILE = 'burger.jpg' +_ALLOW_LIST = ['cheeseburger', 'guacamole'] +_DENY_LIST = ['cheeseburger'] +_SCORE_THRESHOLD = 0.5 +_MAX_RESULTS = 3 + + +class ModelFileType(enum.Enum): + FILE_CONTENT = 1 + FILE_NAME = 2 + + +class ImageClassifierTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self.test_image = _Image.create_from_file( + test_utils.get_test_data_path(_IMAGE_FILE)) + self.model_path = test_utils.get_test_data_path(_MODEL_FILE) + + @parameterized.parameters( + (ModelFileType.FILE_NAME, False, False), + (ModelFileType.FILE_CONTENT, False, False)) + def test_embed(self, model_file_type, l2_normalize, quantize): + # Creates embedder. + if model_file_type is ModelFileType.FILE_NAME: + base_options = _BaseOptions(model_asset_path=self.model_path) + elif model_file_type is ModelFileType.FILE_CONTENT: + with open(self.model_path, 'rb') as f: + model_content = f.read() + base_options = _BaseOptions(model_asset_buffer=model_content) + else: + # Should never happen + raise ValueError('model_file_type is invalid.') + + embedder_options = _EmbedderOptions(l2_normalize=l2_normalize, + quantize=quantize) + options = _ImageEmbedderOptions( + base_options=base_options, embedder_options=embedder_options) + embedder = _ImageEmbedder.create_from_options(options) + + # Performs image embedding extraction on the input. + image_result = embedder.embed(self.test_image) + + # TODO: Verify results. + + # Closes the embedder explicitly when the classifier is not used in + # a context. + embedder.close() + + +if __name__ == '__main__': + absltest.main() diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index 7ff81861..08c2709f 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -36,3 +36,22 @@ py_library( "//mediapipe/tasks/python/vision/core:vision_task_running_mode", ], ) + +py_library( + name = "image_embedder", + srcs = [ + "image_embedder.py", + ], + deps = [ + "//mediapipe/python:_framework_bindings", + "//mediapipe/python:packet_creator", + "//mediapipe/python:packet_getter", + "//mediapipe/tasks/cc/vision/image_embedder/proto:image_embedder_graph_options_py_pb2", + "//mediapipe/tasks/python/components/containers:embeddings", + "//mediapipe/tasks/python/core:base_options", + "//mediapipe/tasks/python/core:optional_dependencies", + "//mediapipe/tasks/python/core:task_info", + "//mediapipe/tasks/python/vision/core:base_vision_task_api", + "//mediapipe/tasks/python/vision/core:vision_task_running_mode", + ], +) diff --git a/mediapipe/tasks/python/vision/image_embedder.py b/mediapipe/tasks/python/vision/image_embedder.py new file mode 100644 index 00000000..23ef492e --- /dev/null +++ b/mediapipe/tasks/python/vision/image_embedder.py @@ -0,0 +1,288 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""MediaPipe image embedder task.""" + +import dataclasses +from typing import Callable, Mapping, Optional + +from mediapipe.python import packet_creator +from mediapipe.python import packet_getter +from mediapipe.python._framework_bindings import image as image_module +from mediapipe.python._framework_bindings import packet as packet_module +from mediapipe.python._framework_bindings import task_runner as task_runner_module +from mediapipe.tasks.cc.vision.image_embedder.proto import image_embedder_graph_options_pb2 +from mediapipe.tasks.python.components.proto import embedder_options +from mediapipe.tasks.python.components.containers import embeddings as embeddings_module +from mediapipe.tasks.python.components.containers import rect as rect_module +from mediapipe.tasks.python.core import base_options as base_options_module +from mediapipe.tasks.python.core import task_info as task_info_module +from mediapipe.tasks.python.core.optional_dependencies import doc_controls +from mediapipe.tasks.python.vision.core import base_vision_task_api +from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module + +_NormalizedRect = rect_module.NormalizedRect +_BaseOptions = base_options_module.BaseOptions +_ImageEmbedderGraphOptionsProto = image_embedder_graph_options_pb2.ImageEmbedderGraphOptions +_EmbedderOptions = embedder_options.EmbedderOptions +_RunningMode = running_mode_module.VisionTaskRunningMode +_TaskInfo = task_info_module.TaskInfo +_TaskRunner = task_runner_module.TaskRunner + +_EMBEDDING_RESULT_OUT_STREAM_NAME = 'embedding_result_out' +_EMBEDDING_RESULT_TAG = 'EMBEDDING_RESULT' +_IMAGE_IN_STREAM_NAME = 'image_in' +_IMAGE_OUT_STREAM_NAME = 'image_out' +_IMAGE_TAG = 'IMAGE' +_NORM_RECT_NAME = 'norm_rect_in' +_NORM_RECT_TAG = 'NORM_RECT' +_TASK_GRAPH_NAME = 'mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph' +_MICRO_SECONDS_PER_MILLISECOND = 1000 + + +def _build_full_image_norm_rect() -> _NormalizedRect: + # Builds a NormalizedRect covering the entire image. + return _NormalizedRect(x_center=0.5, y_center=0.5, width=1, height=1) + + +@dataclasses.dataclass +class ImageEmbedderOptions: + """Options for the image embedder task. + + Attributes: + base_options: Base options for the image embedder task. + running_mode: The running mode of the task. Default to the image mode. + Image embedder task has three running modes: + 1) The image mode for embedding image on single image inputs. + 2) The video mode for embedding image on the decoded frames of a + video. + 3) The live stream mode for embedding image on a live stream of input + data, such as from camera. + embedder_options: Options for the image embedder task. + result_callback: The user-defined result callback for processing live stream + data. The result callback should only be specified when the running mode + is set to the live stream mode. + """ + base_options: _BaseOptions + running_mode: _RunningMode = _RunningMode.IMAGE + embedder_options: _EmbedderOptions = _EmbedderOptions() + result_callback: Optional[ + Callable[[embeddings_module.EmbeddingResult, image_module.Image, + int], None]] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _ImageEmbedderGraphOptionsProto: + """Generates an ImageEmbedderOptions protobuf object.""" + base_options_proto = self.base_options.to_pb2() + base_options_proto.use_stream_mode = False if self.running_mode == _RunningMode.IMAGE else True + embedder_options_proto = self.embedder_options.to_pb2() + + return _ImageEmbedderGraphOptionsProto( + base_options=base_options_proto, + embedder_options=embedder_options_proto + ) + + +class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): + """Class that performs embedding extraction on images.""" + + @classmethod + def create_from_model_path(cls, model_path: str) -> 'ImageEmbedder': + """Creates an `ImageEmbedder` object from a TensorFlow Lite model and the + default `ImageEmbedderOptions`. + + Note that the created `ImageEmbedder` instance is in image mode, for + embedding image on single image inputs. + + Args: + model_path: Path to the model. + + Returns: + `ImageEmbedder` object that's created from the model file and the default + `ImageEmbedderOptions`. + + Raises: + ValueError: If failed to create `ImageClassifier` object from the provided + file such as invalid file path. + RuntimeError: If other types of error occurred. + """ + base_options = _BaseOptions(model_asset_path=model_path) + options = ImageEmbedderOptions( + base_options=base_options, running_mode=_RunningMode.IMAGE) + return cls.create_from_options(options) + + @classmethod + def create_from_options(cls, + options: ImageEmbedderOptions) -> 'ImageEmbedder': + """Creates the `ImageEmbedder` object from image embedder options. + + Args: + options: Options for the image embedder task. + + Returns: + `ImageEmbedder` object that's created from `options`. + + Raises: + ValueError: If failed to create `ImageEmbedder` object from + `ImageEmbedderOptions` such as missing the model. + RuntimeError: If other types of error occurred. + """ + + def packets_callback(output_packets: Mapping[str, packet_module.Packet]): + if output_packets[_IMAGE_OUT_STREAM_NAME].is_empty(): + return + embedding_result_proto = packet_getter.get_proto( + output_packets[_EMBEDDING_RESULT_OUT_STREAM_NAME]) + + embedding_result = embeddings_module.EmbeddingResult([ + embeddings_module.Embeddings.create_from_pb2(embedding) + for embedding in embedding_result_proto.embeddings + ]) + image = packet_getter.get_image(output_packets[_IMAGE_OUT_STREAM_NAME]) + timestamp = output_packets[_IMAGE_OUT_STREAM_NAME].timestamp + options.result_callback(embedding_result, image, + timestamp.value // _MICRO_SECONDS_PER_MILLISECOND) + + task_info = _TaskInfo( + task_graph=_TASK_GRAPH_NAME, + input_streams=[ + ':'.join([_IMAGE_TAG, _IMAGE_IN_STREAM_NAME]), + ':'.join([_NORM_RECT_TAG, _NORM_RECT_NAME]), + ], + output_streams=[ + ':'.join([_EMBEDDING_RESULT_TAG, + _EMBEDDING_RESULT_OUT_STREAM_NAME]), + ':'.join([_IMAGE_TAG, _IMAGE_OUT_STREAM_NAME]) + ], + task_options=options) + return cls( + task_info.generate_graph_config( + enable_flow_limiting=options.running_mode == + _RunningMode.LIVE_STREAM), options.running_mode, + packets_callback if options.result_callback else None) + + def embed( + self, + image: image_module.Image, + roi: Optional[_NormalizedRect] = None + ) -> embeddings_module.EmbeddingResult: + """Performs image embedding extraction on the provided MediaPipe Image. + Extraction is performed on the region of interest specified by the `roi` + argument if provided, or on the entire image otherwise. + + Args: + image: MediaPipe Image. + roi: The region of interest. + + Returns: + A embedding result object that contains a list of embeddings. + + Raises: + ValueError: If any of the input arguments is invalid. + RuntimeError: If image embedder failed to run. + """ + norm_rect = roi if roi is not None else _build_full_image_norm_rect() + output_packets = self._process_image_data({ + _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image), + _NORM_RECT_NAME: packet_creator.create_proto(norm_rect.to_pb2())}) + embedding_result_proto = packet_getter.get_proto( + output_packets[_EMBEDDING_RESULT_OUT_STREAM_NAME]) + + return embeddings_module.EmbeddingResult([ + embeddings_module.Embeddings.create_from_pb2(embedding) + for embedding in embedding_result_proto.embeddings + ]) + + def embed_for_video( + self, image: image_module.Image, + timestamp_ms: int, + roi: Optional[_NormalizedRect] = None + ) -> embeddings_module.EmbeddingResult: + """Performs image embedding extraction on the provided video frames. + Extraction is performed on the region of interested specified by the `roi` + argument if provided, or on the entire image otherwise. + + Only use this method when the ImageEmbedder is created with the video + running mode. It's required to provide the video frame's timestamp (in + milliseconds) along with the video frame. The input timestamps should be + monotonically increasing for adjacent calls of this method. + + Args: + image: MediaPipe Image. + timestamp_ms: The timestamp of the input video frame in milliseconds. + roi: The region of interest. + + Returns: + A embedding result object that contains a list of embeddings. + + Raises: + ValueError: If any of the input arguments is invalid. + RuntimeError: If image embedder failed to run. + """ + norm_rect = roi if roi is not None else _build_full_image_norm_rect() + output_packets = self._process_video_data({ + _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND), + _NORM_RECT_NAME: packet_creator.create_proto(norm_rect.to_pb2()).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) + }) + embedding_result_proto = packet_getter.get_proto( + output_packets[_EMBEDDING_RESULT_OUT_STREAM_NAME]) + + return embeddings_module.EmbeddingResult([ + embeddings_module.Embeddings.create_from_pb2(embedding) + for embedding in embedding_result_proto.embeddings + ]) + + def embed_async( + self, + image: image_module.Image, + timestamp_ms: int, + roi: Optional[_NormalizedRect] = None + ) -> None: + """ Sends live image data to embedder, and the results will be available via + the "result_callback" provided in the ImageEmbedderOptions. Embedding + extraction is performed on the region of interested specified by the `roi` + argument if provided, or on the entire image otherwise. + + Only use this method when the ImageEmbedder is created with the live + stream running mode. The input timestamps should be monotonically increasing + for adjacent calls of this method. This method will return immediately after + the input image is accepted. The results will be available via the + `result_callback` provided in the `ImageEmbedderOptions`. The + `embed_async` method is designed to process live stream data such as + camera input. To lower the overall latency, image embedder may drop the + input images if needed. In other words, it's not guaranteed to have output + per input image. + + The `result_callback` provides: + - A embedding result object that contains a list of embeddings. + - The input image that the image embedder runs on. + - The input timestamp in milliseconds. + + Args: + image: MediaPipe Image. + timestamp_ms: The timestamp of the input image in milliseconds. + roi: The region of interest. + + Raises: + ValueError: If the current input timestamp is smaller than what the image + embedder has already processed. + """ + norm_rect = roi if roi is not None else _build_full_image_norm_rect() + self._send_live_stream_data({ + _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND), + _NORM_RECT_NAME: packet_creator.create_proto(norm_rect.to_pb2()).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) + }) From 492607152afb8ac697e7d84d17db0425e87a9469 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Thu, 3 Nov 2022 10:56:38 -0700 Subject: [PATCH 02/21] Reverted changes to rect --- .../python/components/containers/rect.py | 84 ++++++------------- 1 file changed, 26 insertions(+), 58 deletions(-) diff --git a/mediapipe/tasks/python/components/containers/rect.py b/mediapipe/tasks/python/components/containers/rect.py index aadb404d..4fdccbaf 100644 --- a/mediapipe/tasks/python/components/containers/rect.py +++ b/mediapipe/tasks/python/components/containers/rect.py @@ -19,78 +19,48 @@ from typing import Any, Optional from mediapipe.framework.formats import rect_pb2 from mediapipe.tasks.python.core.optional_dependencies import doc_controls -_RectProto = rect_pb2.Rect _NormalizedRectProto = rect_pb2.NormalizedRect @dataclasses.dataclass class Rect: - """A rectangle with rotation in image coordinates. + """A rectangle, used as part of detection results or as input region-of-interest. + + The coordinates are normalized wrt the image dimensions, i.e. generally in + [0,1] but they may exceed these bounds if describing a region overlapping the + image. The origin is on the top-left corner of the image. Attributes: - x_center : The X coordinate of the top-left corner, in pixels. - y_center : The Y coordinate of the top-left corner, in pixels. - width: The width of the rectangle, in pixels. - height: The height of the rectangle, in pixels. - rotation: Rotation angle is clockwise in radians. - rect_id: Optional unique id to help associate different rectangles to each - other. + left: The X coordinate of the left side of the rectangle. + top: The Y coordinate of the top of the rectangle. + right: The X coordinate of the right side of the rectangle. + bottom: The Y coordinate of the bottom of the rectangle. """ - x_center: int - y_center: int - width: int - height: int - rotation: Optional[float] = 0.0 - rect_id: Optional[int] = None - - @doc_controls.do_not_generate_docs - def to_pb2(self) -> _RectProto: - """Generates a Rect protobuf object.""" - return _RectProto( - x_center=self.x_center, - y_center=self.y_center, - width=self.width, - height=self.height, - ) - - @classmethod - @doc_controls.do_not_generate_docs - def create_from_pb2(cls, pb2_obj: _RectProto) -> 'Rect': - """Creates a `Rect` object from the given protobuf object.""" - return Rect( - x_center=pb2_obj.x_center, - y_center=pb2_obj.y_center, - width=pb2_obj.width, - height=pb2_obj.height) - - def __eq__(self, other: Any) -> bool: - """Checks if this object is equal to the given object. - - Args: - other: The object to be compared with. - - Returns: - True if the objects are equal. - """ - if not isinstance(other, Rect): - return False - - return self.to_pb2().__eq__(other.to_pb2()) + left: float + top: float + right: float + bottom: float @dataclasses.dataclass class NormalizedRect: - """A rectangle with rotation in normalized coordinates. The values of box - center location and size are within [0, 1]. + """A rectangle with rotation in normalized coordinates. + + Location of the center of the rectangle in image coordinates. The (0.0, 0.0) + point is at the (top, left) corner. + + The values of box center location and size are within [0, 1]. Attributes: - x_center : The X normalized coordinate of the top-left corner. - y_center : The Y normalized coordinate of the top-left corner. + x_center: The normalized X coordinate of the rectangle, in image + coordinates. + y_center: The normalized Y coordinate of the rectangle, in image + coordinates. width: The width of the rectangle. height: The height of the rectangle. rotation: Rotation angle is clockwise in radians. - rect_id: Optional unique id to help associate different rectangles to each + rect_id: Optional unique id to help associate different rectangles to each other. """ @@ -110,8 +80,7 @@ class NormalizedRect: width=self.width, height=self.height, rotation=self.rotation, - rect_id=self.rect_id - ) + rect_id=self.rect_id) @classmethod @doc_controls.do_not_generate_docs @@ -123,8 +92,7 @@ class NormalizedRect: width=pb2_obj.width, height=pb2_obj.height, rotation=pb2_obj.rotation, - rect_id=pb2_obj.rect_id - ) + rect_id=pb2_obj.rect_id) def __eq__(self, other: Any) -> bool: """Checks if this object is equal to the given object. From e2d50745ac0c0d84b56f1759c3e26165e5979159 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Thu, 3 Nov 2022 14:30:21 -0700 Subject: [PATCH 03/21] Revised image embedder implementation --- .../components/containers/embeddings.py | 16 +- .../components/proto/embedder_options.py | 6 +- mediapipe/tasks/python/components/utils/BUILD | 28 ++ .../tasks/python/components/utils/__init__.py | 13 + .../components/utils/cosine_similarity.py | 61 ++++ mediapipe/tasks/python/test/vision/BUILD | 2 + .../python/test/vision/image_embedder_test.py | 316 ++++++++++++++++-- mediapipe/tasks/python/vision/BUILD | 1 + .../tasks/python/vision/image_embedder.py | 69 ++-- 9 files changed, 456 insertions(+), 56 deletions(-) create mode 100644 mediapipe/tasks/python/components/utils/BUILD create mode 100644 mediapipe/tasks/python/components/utils/__init__.py create mode 100644 mediapipe/tasks/python/components/utils/cosine_similarity.py diff --git a/mediapipe/tasks/python/components/containers/embeddings.py b/mediapipe/tasks/python/components/containers/embeddings.py index 21f53670..c1185c84 100644 --- a/mediapipe/tasks/python/components/containers/embeddings.py +++ b/mediapipe/tasks/python/components/containers/embeddings.py @@ -131,18 +131,14 @@ class EmbeddingEntry: cls, pb2_obj: _EmbeddingEntryProto) -> 'EmbeddingEntry': """Creates a `EmbeddingEntry` object from the given protobuf object.""" - if pb2_obj.float_embedding: - return EmbeddingEntry( - embedding=np.array(pb2_obj.float_embedding.values, dtype=float)) - - elif pb2_obj.quantized_embedding: - return EmbeddingEntry( - embedding=np.array(bytearray(pb2_obj.quantized_embedding.values), - dtype=np.uint8)) + quantized_embedding = np.array( + bytearray(pb2_obj.quantized_embedding.values)) + float_embedding = np.array(pb2_obj.float_embedding.values, dtype=float) + if len(quantized_embedding) == 0: + return EmbeddingEntry(embedding=float_embedding) else: - raise ValueError("Either float_embedding or quantized_embedding must " - "exist.") + return EmbeddingEntry(embedding=quantized_embedding) def __eq__(self, other: Any) -> bool: """Checks if this object is equal to the given object. diff --git a/mediapipe/tasks/python/components/proto/embedder_options.py b/mediapipe/tasks/python/components/proto/embedder_options.py index 3c257b97..49bcfb98 100644 --- a/mediapipe/tasks/python/components/proto/embedder_options.py +++ b/mediapipe/tasks/python/components/proto/embedder_options.py @@ -45,8 +45,7 @@ class EmbedderOptions: """Generates a EmbedderOptions protobuf object.""" return _EmbedderOptionsProto( l2_normalize=self.l2_normalize, - quantize=self.quantize - ) + quantize=self.quantize) @classmethod @doc_controls.do_not_generate_docs @@ -54,8 +53,7 @@ class EmbedderOptions: """Creates a `EmbedderOptions` object from the given protobuf object.""" return EmbedderOptions( l2_normalize=pb2_obj.l2_normalize, - quantize=pb2_obj.quantize - ) + quantize=pb2_obj.quantize) def __eq__(self, other: Any) -> bool: """Checks if this object is equal to the given object. diff --git a/mediapipe/tasks/python/components/utils/BUILD b/mediapipe/tasks/python/components/utils/BUILD new file mode 100644 index 00000000..7ec01a03 --- /dev/null +++ b/mediapipe/tasks/python/components/utils/BUILD @@ -0,0 +1,28 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Placeholder for internal Python strict library compatibility macro. + +package(default_visibility = ["//mediapipe/tasks:internal"]) + +licenses(["notice"]) + +py_library( + name = "cosine_similarity", + srcs = ["cosine_similarity.py"], + deps = [ + "//mediapipe/tasks/python/components/containers:embeddings", + "//mediapipe/tasks/python/components/proto:embedder_options", + ], +) diff --git a/mediapipe/tasks/python/components/utils/__init__.py b/mediapipe/tasks/python/components/utils/__init__.py new file mode 100644 index 00000000..65c1214a --- /dev/null +++ b/mediapipe/tasks/python/components/utils/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/mediapipe/tasks/python/components/utils/cosine_similarity.py b/mediapipe/tasks/python/components/utils/cosine_similarity.py new file mode 100644 index 00000000..8723a55e --- /dev/null +++ b/mediapipe/tasks/python/components/utils/cosine_similarity.py @@ -0,0 +1,61 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Cosine similarity utilities.""" + +import numpy as np + +from mediapipe.tasks.python.components.containers import embeddings +from mediapipe.tasks.python.components.proto import embedder_options + +_EmbeddingEntry = embeddings.EmbeddingEntry +_EmbedderOptions = embedder_options.EmbedderOptions + + +def _compute_cosine_similarity(u, v): + if len(u.embedding) <= 0: + raise ValueError("Cannot compute cosing similarity on empty embeddings.") + + norm_u = np.linalg.norm(u.embedding) + norm_v = np.linalg.norm(v.embedding) + + if norm_u <= 0 or norm_v <= 0: + raise ValueError( + "Cannot compute cosine similarity on embedding with 0 norm.") + + return np.dot(u.embedding, v.embedding.T) / (norm_u * norm_v) + + +def cosine_similarity(u: _EmbeddingEntry, v: _EmbeddingEntry) -> float: + """Utility function to compute cosine similarity between two embedding + entries. May return an InvalidArgumentError if e.g. the feature vectors are + of different types (quantized vs. float), have different sizes, or have an + L2-norm of 0. + + Args: + u: An embedding entry. + v: An embedding entry. + """ + if len(u.embedding) != len(v.embedding): + raise ValueError(f"Cannot compute cosine similarity between embeddings " + f"of different sizes " + f"({len(u.embedding)} vs. {len(v.embedding)}).") + + if u.embedding.dtype == float and v.embedding.dtype == float: + return _compute_cosine_similarity(u, v) + + if u.embedding.dtype == np.uint8 and v.embedding.dtype == np.uint8: + return _compute_cosine_similarity(u, v) + + raise ValueError("Cannot compute cosine similarity between quantized and " + "float embeddings.") diff --git a/mediapipe/tasks/python/test/vision/BUILD b/mediapipe/tasks/python/test/vision/BUILD index 6adab680..9fee8a02 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -84,11 +84,13 @@ py_test( deps = [ "//mediapipe/python:_framework_bindings", "//mediapipe/tasks/python/components/proto:embedder_options", + "//mediapipe/tasks/python/components/utils:cosine_similarity", "//mediapipe/tasks/python/components/containers:embeddings", "//mediapipe/tasks/python/components/containers:rect", "//mediapipe/tasks/python/core:base_options", "//mediapipe/tasks/python/test:test_utils", "//mediapipe/tasks/python/vision:image_embedder", + "//mediapipe/tasks/python/vision/core:image_processing_options", "//mediapipe/tasks/python/vision/core:vision_task_running_mode", ], ) diff --git a/mediapipe/tasks/python/test/vision/image_embedder_test.py b/mediapipe/tasks/python/test/vision/image_embedder_test.py index 8ddf3c99..4f109ea2 100644 --- a/mediapipe/tasks/python/test/vision/image_embedder_test.py +++ b/mediapipe/tasks/python/test/vision/image_embedder_test.py @@ -14,6 +14,7 @@ """Tests for image embedder.""" import enum +import os from unittest import mock import numpy as np @@ -23,31 +24,32 @@ from absl.testing import parameterized from mediapipe.python._framework_bindings import image as image_module from mediapipe.tasks.python.components.proto import embedder_options as embedder_options_module from mediapipe.tasks.python.components.containers import embeddings as embeddings_module -from mediapipe.tasks.python.components.containers import rect as rect_module +from mediapipe.tasks.python.components.containers import rect from mediapipe.tasks.python.core import base_options as base_options_module from mediapipe.tasks.python.test import test_utils from mediapipe.tasks.python.vision import image_embedder +from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module -_NormalizedRect = rect_module.NormalizedRect +_Rect = rect.Rect _BaseOptions = base_options_module.BaseOptions _EmbedderOptions = embedder_options_module.EmbedderOptions _FloatEmbedding = embeddings_module.FloatEmbedding _QuantizedEmbedding = embeddings_module.QuantizedEmbedding -_ClassificationEntry = embeddings_module.EmbeddingEntry -_Classifications = embeddings_module.Embeddings -_ClassificationResult = embeddings_module.EmbeddingResult +_EmbeddingEntry = embeddings_module.EmbeddingEntry +_Embeddings = embeddings_module.Embeddings +_EmbeddingResult = embeddings_module.EmbeddingResult _Image = image_module.Image _ImageEmbedder = image_embedder.ImageEmbedder _ImageEmbedderOptions = image_embedder.ImageEmbedderOptions _RUNNING_MODE = running_mode_module.VisionTaskRunningMode +_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _MODEL_FILE = 'mobilenet_v3_small_100_224_embedder.tflite' -_IMAGE_FILE = 'burger.jpg' -_ALLOW_LIST = ['cheeseburger', 'guacamole'] -_DENY_LIST = ['cheeseburger'] -_SCORE_THRESHOLD = 0.5 -_MAX_RESULTS = 3 +_BURGER_IMAGE_FILE = 'burger.jpg' +_BURGER_CROPPED_IMAGE_FILE = 'burger_crop.jpg' +_TEST_DATA_DIR = 'mediapipe/tasks/testdata/vision' +_SIMILARITY_TOLERANCE = 1e-6 class ModelFileType(enum.Enum): @@ -55,18 +57,55 @@ class ModelFileType(enum.Enum): FILE_NAME = 2 -class ImageClassifierTest(parameterized.TestCase): +class ImageEmbedderTest(parameterized.TestCase): def setUp(self): super().setUp() self.test_image = _Image.create_from_file( - test_utils.get_test_data_path(_IMAGE_FILE)) - self.model_path = test_utils.get_test_data_path(_MODEL_FILE) + test_utils.get_test_data_path( + os.path.join(_TEST_DATA_DIR, _BURGER_IMAGE_FILE))) + self.test_cropped_image = _Image.create_from_file( + test_utils.get_test_data_path( + os.path.join(_TEST_DATA_DIR, _BURGER_CROPPED_IMAGE_FILE))) + self.model_path = test_utils.get_test_data_path( + os.path.join(_TEST_DATA_DIR, _MODEL_FILE)) + + def _check_cosine_similarity(self, result0, result1, quantize, + expected_similarity): + # Checks head_index and head_name. + self.assertEqual(result0.embeddings[0].head_index, 0) + self.assertEqual(result1.embeddings[0].head_index, 0) + self.assertEqual(result0.embeddings[0].head_name, 'feature') + self.assertEqual(result1.embeddings[0].head_name, 'feature') + + # Check embedding sizes. + def _check_embedding_size(result): + self.assertLen(result.embeddings, 1) + embedding_entry = result.embeddings[0].entries[0] + self.assertLen(embedding_entry.embedding, 1024) + if quantize: + self.assertEqual(embedding_entry.embedding.dtype, np.uint8) + else: + self.assertEqual(embedding_entry.embedding.dtype, float) + + # Checks results sizes. + _check_embedding_size(result0) + _check_embedding_size(result1) + + # Checks cosine similarity. + similarity = _ImageEmbedder.cosine_similarity( + result0.embeddings[0].entries[0], result1.embeddings[0].entries[0]) + self.assertAlmostEqual(similarity, expected_similarity, + delta=_SIMILARITY_TOLERANCE) @parameterized.parameters( - (ModelFileType.FILE_NAME, False, False), - (ModelFileType.FILE_CONTENT, False, False)) - def test_embed(self, model_file_type, l2_normalize, quantize): + (False, False, False, ModelFileType.FILE_NAME, 0.925519, -0.2101883), + (True, False, False, ModelFileType.FILE_NAME, 0.925519, -0.0142344), + # (False, True, False, ModelFileType.FILE_NAME, 0.926791, 229), + (False, False, True, ModelFileType.FILE_CONTENT, 0.999931, -0.195062) + ) + def test_embed(self, l2_normalize, quantize, with_roi, model_file_type, + expected_similarity, expected_first_value): # Creates embedder. if model_file_type is ModelFileType.FILE_NAME: base_options = _BaseOptions(model_asset_path=self.model_path) @@ -84,15 +123,254 @@ class ImageClassifierTest(parameterized.TestCase): base_options=base_options, embedder_options=embedder_options) embedder = _ImageEmbedder.create_from_options(options) - # Performs image embedding extraction on the input. - image_result = embedder.embed(self.test_image) + image_processing_options = None + if with_roi: + # Region-of-interest in "burger.jpg" corresponding to "burger_crop.jpg". + roi = _Rect(left=0, top=0, right=0.833333, bottom=1) + image_processing_options = _ImageProcessingOptions(roi) - # TODO: Verify results. + # Extracts both embeddings. + image_result = embedder.embed(self.test_image, image_processing_options) + crop_result = embedder.embed(self.test_cropped_image) + # Check embedding value. + self.assertAlmostEqual(image_result.embeddings[0].entries[0].embedding[0], + expected_first_value) + + # Checks cosine similarity. + self._check_cosine_similarity(image_result, crop_result, quantize, + expected_similarity) # Closes the embedder explicitly when the classifier is not used in # a context. embedder.close() + @parameterized.parameters( + (False, False, ModelFileType.FILE_NAME, 0.925519), + (False, False, ModelFileType.FILE_CONTENT, 0.925519)) + def test_embed_in_context(self, l2_normalize, quantize, model_file_type, + expected_similarity): + # Creates embedder. + if model_file_type is ModelFileType.FILE_NAME: + base_options = _BaseOptions(model_asset_path=self.model_path) + elif model_file_type is ModelFileType.FILE_CONTENT: + with open(self.model_path, 'rb') as f: + model_content = f.read() + base_options = _BaseOptions(model_asset_buffer=model_content) + else: + # Should never happen + raise ValueError('model_file_type is invalid.') + + embedder_options = _EmbedderOptions(l2_normalize=l2_normalize, + quantize=quantize) + options = _ImageEmbedderOptions( + base_options=base_options, embedder_options=embedder_options) + + with _ImageEmbedder.create_from_options(options) as embedder: + # Extracts both embeddings. + image_result = embedder.embed(self.test_image) + crop_result = embedder.embed(self.test_cropped_image) + + # Checks cosine similarity. + self._check_cosine_similarity(image_result, crop_result, quantize, + expected_similarity) + + def test_missing_result_callback(self): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM) + with self.assertRaisesRegex(ValueError, + r'result callback must be provided'): + with _ImageEmbedder.create_from_options(options) as unused_embedder: + pass + + @parameterized.parameters((_RUNNING_MODE.IMAGE), (_RUNNING_MODE.VIDEO)) + def test_illegal_result_callback(self, running_mode): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=running_mode, + result_callback=mock.MagicMock()) + with self.assertRaisesRegex(ValueError, + r'result callback should not be provided'): + with _ImageEmbedder.create_from_options(options) as unused_embedder: + pass + + def test_calling_embed_for_video_in_image_mode(self): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.IMAGE) + with _ImageEmbedder.create_from_options(options) as embedder: + with self.assertRaisesRegex(ValueError, + r'not initialized with the video mode'): + embedder.embed_for_video(self.test_image, 0) + + def test_calling_embed_async_in_image_mode(self): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.IMAGE) + with _ImageEmbedder.create_from_options(options) as embedder: + with self.assertRaisesRegex(ValueError, + r'not initialized with the live stream mode'): + embedder.embed_async(self.test_image, 0) + + def test_calling_embed_in_video_mode(self): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _ImageEmbedder.create_from_options(options) as embedder: + with self.assertRaisesRegex(ValueError, + r'not initialized with the image mode'): + embedder.embed(self.test_image) + + def test_calling_embed_async_in_video_mode(self): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _ImageEmbedder.create_from_options(options) as embedder: + with self.assertRaisesRegex(ValueError, + r'not initialized with the live stream mode'): + embedder.embed_async(self.test_image, 0) + + def test_embed_for_video_with_out_of_order_timestamp(self): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _ImageEmbedder.create_from_options(options) as embedder: + unused_result = embedder.embed_for_video(self.test_image, 1) + with self.assertRaisesRegex( + ValueError, r'Input timestamp must be monotonically increasing'): + embedder.embed_for_video(self.test_image, 0) + + def test_embed_for_video(self): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _ImageEmbedder.create_from_options(options) as embedder0, \ + _ImageEmbedder.create_from_options(options) as embedder1: + for timestamp in range(0, 300, 30): + # Extracts both embeddings. + image_result = embedder0.embed_for_video(self.test_image, timestamp) + crop_result = embedder1.embed_for_video(self.test_cropped_image, + timestamp) + # Checks cosine similarity. + self._check_cosine_similarity( + image_result, crop_result, quantize=False, + expected_similarity=0.925519) + + def test_embed_for_video_succeeds_with_region_of_interest(self): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _ImageEmbedder.create_from_options(options) as embedder0, \ + _ImageEmbedder.create_from_options(options) as embedder1: + # Region-of-interest in "burger.jpg" corresponding to "burger_crop.jpg". + roi = _Rect(left=0, top=0, right=0.833333, bottom=1) + image_processing_options = _ImageProcessingOptions(roi) + + for timestamp in range(0, 300, 30): + # Extracts both embeddings. + image_result = embedder0.embed_for_video(self.test_image, timestamp, + image_processing_options) + crop_result = embedder1.embed_for_video(self.test_cropped_image, + timestamp) + + # Checks cosine similarity. + self._check_cosine_similarity( + image_result, crop_result, quantize=False, + expected_similarity=0.999931) + + def test_calling_embed_in_live_stream_mode(self): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=mock.MagicMock()) + with _ImageEmbedder.create_from_options(options) as embedder: + with self.assertRaisesRegex(ValueError, + r'not initialized with the image mode'): + embedder.embed(self.test_image) + + def test_calling_classify_for_video_in_live_stream_mode(self): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=mock.MagicMock()) + with _ImageEmbedder.create_from_options(options) as embedder: + with self.assertRaisesRegex(ValueError, + r'not initialized with the video mode'): + embedder.embed_for_video(self.test_image, 0) + + def test_classify_async_calls_with_illegal_timestamp(self): + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=mock.MagicMock()) + with _ImageEmbedder.create_from_options(options) as embedder: + embedder.embed_async(self.test_image, 100) + with self.assertRaisesRegex( + ValueError, r'Input timestamp must be monotonically increasing'): + embedder.embed_async(self.test_image, 0) + + def test_embed_async_calls(self): + # Get the embedding result for the cropped image. + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.IMAGE) + with _ImageEmbedder.create_from_options(options) as embedder: + crop_result = embedder.embed(self.test_cropped_image) + + observed_timestamp_ms = -1 + + def check_result(result: _EmbeddingResult, output_image: _Image, + timestamp_ms: int): + # Checks cosine similarity. + self._check_cosine_similarity(result, crop_result, quantize=False, + expected_similarity=0.925519) + self.assertTrue( + np.array_equal(output_image.numpy_view(), + self.test_image.numpy_view())) + self.assertLess(observed_timestamp_ms, timestamp_ms) + self.observed_timestamp_ms = timestamp_ms + + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=check_result) + with _ImageEmbedder.create_from_options(options) as embedder: + for timestamp in range(0, 300, 30): + embedder.embed_async(self.test_image, timestamp) + + def test_classify_async_succeeds_with_region_of_interest(self): + # Get the embedding result for the cropped image. + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.IMAGE) + with _ImageEmbedder.create_from_options(options) as embedder: + crop_result = embedder.embed(self.test_cropped_image) + + # Region-of-interest in "burger.jpg" corresponding to "burger_crop.jpg". + roi = _Rect(left=0, top=0, right=0.833333, bottom=1) + image_processing_options = _ImageProcessingOptions(roi) + observed_timestamp_ms = -1 + + def check_result(result: _EmbeddingResult, output_image: _Image, + timestamp_ms: int): + # Checks cosine similarity. + self._check_cosine_similarity(result, crop_result, quantize=False, + expected_similarity=0.999931) + self.assertTrue( + np.array_equal(output_image.numpy_view(), + self.test_image.numpy_view())) + self.assertLess(observed_timestamp_ms, timestamp_ms) + self.observed_timestamp_ms = timestamp_ms + + options = _ImageEmbedderOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=check_result) + with _ImageEmbedder.create_from_options(options) as embedder: + for timestamp in range(0, 300, 30): + embedder.embed_async(self.test_image, timestamp, + image_processing_options) + if __name__ == '__main__': absltest.main() diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index 96cf6288..9d406be2 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -118,6 +118,7 @@ py_library( "//mediapipe/tasks/python/core:optional_dependencies", "//mediapipe/tasks/python/core:task_info", "//mediapipe/tasks/python/vision/core:base_vision_task_api", + "//mediapipe/tasks/python/vision/core:image_processing_options", "//mediapipe/tasks/python/vision/core:vision_task_running_mode", ], ) diff --git a/mediapipe/tasks/python/vision/image_embedder.py b/mediapipe/tasks/python/vision/image_embedder.py index 23ef492e..e287593f 100644 --- a/mediapipe/tasks/python/vision/image_embedder.py +++ b/mediapipe/tasks/python/vision/image_embedder.py @@ -23,20 +23,21 @@ from mediapipe.python._framework_bindings import packet as packet_module from mediapipe.python._framework_bindings import task_runner as task_runner_module from mediapipe.tasks.cc.vision.image_embedder.proto import image_embedder_graph_options_pb2 from mediapipe.tasks.python.components.proto import embedder_options +from mediapipe.tasks.python.components.utils import cosine_similarity from mediapipe.tasks.python.components.containers import embeddings as embeddings_module -from mediapipe.tasks.python.components.containers import rect as rect_module from mediapipe.tasks.python.core import base_options as base_options_module from mediapipe.tasks.python.core import task_info as task_info_module from mediapipe.tasks.python.core.optional_dependencies import doc_controls from mediapipe.tasks.python.vision.core import base_vision_task_api +from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module -_NormalizedRect = rect_module.NormalizedRect _BaseOptions = base_options_module.BaseOptions _ImageEmbedderGraphOptionsProto = image_embedder_graph_options_pb2.ImageEmbedderGraphOptions _EmbedderOptions = embedder_options.EmbedderOptions _RunningMode = running_mode_module.VisionTaskRunningMode _TaskInfo = task_info_module.TaskInfo +_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _TaskRunner = task_runner_module.TaskRunner _EMBEDDING_RESULT_OUT_STREAM_NAME = 'embedding_result_out' @@ -44,17 +45,12 @@ _EMBEDDING_RESULT_TAG = 'EMBEDDING_RESULT' _IMAGE_IN_STREAM_NAME = 'image_in' _IMAGE_OUT_STREAM_NAME = 'image_out' _IMAGE_TAG = 'IMAGE' -_NORM_RECT_NAME = 'norm_rect_in' +_NORM_RECT_STREAM_NAME = 'norm_rect_in' _NORM_RECT_TAG = 'NORM_RECT' _TASK_GRAPH_NAME = 'mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph' _MICRO_SECONDS_PER_MILLISECOND = 1000 -def _build_full_image_norm_rect() -> _NormalizedRect: - # Builds a NormalizedRect covering the entire image. - return _NormalizedRect(x_center=0.5, y_center=0.5, width=1, height=1) - - @dataclasses.dataclass class ImageEmbedderOptions: """Options for the image embedder task. @@ -75,6 +71,8 @@ class ImageEmbedderOptions: """ base_options: _BaseOptions running_mode: _RunningMode = _RunningMode.IMAGE + l2_normalize: Optional[bool] = None + quantize: Optional[bool] = None embedder_options: _EmbedderOptions = _EmbedderOptions() result_callback: Optional[ Callable[[embeddings_module.EmbeddingResult, image_module.Image, @@ -157,7 +155,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): task_graph=_TASK_GRAPH_NAME, input_streams=[ ':'.join([_IMAGE_TAG, _IMAGE_IN_STREAM_NAME]), - ':'.join([_NORM_RECT_TAG, _NORM_RECT_NAME]), + ':'.join([_NORM_RECT_TAG, _NORM_RECT_STREAM_NAME]), ], output_streams=[ ':'.join([_EMBEDDING_RESULT_TAG, @@ -174,7 +172,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): def embed( self, image: image_module.Image, - roi: Optional[_NormalizedRect] = None + image_processing_options: Optional[_ImageProcessingOptions] = None ) -> embeddings_module.EmbeddingResult: """Performs image embedding extraction on the provided MediaPipe Image. Extraction is performed on the region of interest specified by the `roi` @@ -182,7 +180,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): Args: image: MediaPipe Image. - roi: The region of interest. + image_processing_options: Options for image processing. Returns: A embedding result object that contains a list of embeddings. @@ -191,10 +189,11 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): ValueError: If any of the input arguments is invalid. RuntimeError: If image embedder failed to run. """ - norm_rect = roi if roi is not None else _build_full_image_norm_rect() + normalized_rect = self.convert_to_normalized_rect(image_processing_options) output_packets = self._process_image_data({ _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image), - _NORM_RECT_NAME: packet_creator.create_proto(norm_rect.to_pb2())}) + _NORM_RECT_STREAM_NAME: packet_creator.create_proto( + normalized_rect.to_pb2())}) embedding_result_proto = packet_getter.get_proto( output_packets[_EMBEDDING_RESULT_OUT_STREAM_NAME]) @@ -206,7 +205,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): def embed_for_video( self, image: image_module.Image, timestamp_ms: int, - roi: Optional[_NormalizedRect] = None + image_processing_options: Optional[_ImageProcessingOptions] = None ) -> embeddings_module.EmbeddingResult: """Performs image embedding extraction on the provided video frames. Extraction is performed on the region of interested specified by the `roi` @@ -220,7 +219,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): Args: image: MediaPipe Image. timestamp_ms: The timestamp of the input video frame in milliseconds. - roi: The region of interest. + image_processing_options: Options for image processing. Returns: A embedding result object that contains a list of embeddings. @@ -229,12 +228,13 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): ValueError: If any of the input arguments is invalid. RuntimeError: If image embedder failed to run. """ - norm_rect = roi if roi is not None else _build_full_image_norm_rect() + normalized_rect = self.convert_to_normalized_rect(image_processing_options) output_packets = self._process_video_data({ _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image).at( timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND), - _NORM_RECT_NAME: packet_creator.create_proto(norm_rect.to_pb2()).at( - timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) + _NORM_RECT_STREAM_NAME: packet_creator.create_proto( + normalized_rect.to_pb2()).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) }) embedding_result_proto = packet_getter.get_proto( output_packets[_EMBEDDING_RESULT_OUT_STREAM_NAME]) @@ -248,7 +248,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): self, image: image_module.Image, timestamp_ms: int, - roi: Optional[_NormalizedRect] = None + image_processing_options: Optional[_ImageProcessingOptions] = None ) -> None: """ Sends live image data to embedder, and the results will be available via the "result_callback" provided in the ImageEmbedderOptions. Embedding @@ -273,16 +273,39 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): Args: image: MediaPipe Image. timestamp_ms: The timestamp of the input image in milliseconds. - roi: The region of interest. + image_processing_options: Options for image processing. Raises: ValueError: If the current input timestamp is smaller than what the image embedder has already processed. """ - norm_rect = roi if roi is not None else _build_full_image_norm_rect() + normalized_rect = self.convert_to_normalized_rect(image_processing_options) self._send_live_stream_data({ _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image).at( timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND), - _NORM_RECT_NAME: packet_creator.create_proto(norm_rect.to_pb2()).at( - timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) + _NORM_RECT_STREAM_NAME: packet_creator.create_proto( + normalized_rect.to_pb2()).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) }) + + @staticmethod + def cosine_similarity(u: embeddings_module.EmbeddingEntry, + v: embeddings_module.EmbeddingEntry) -> float: + """Utility function to compute cosine similarity [1] between two embedding + entries. May return an InvalidArgumentError if e.g. the feature vectors are + of different types (quantized vs. float), have different sizes, or have a + an L2-norm of 0. + + Args: + u: An embedding entry. + v: An embedding entry. + + Returns: + The cosine similarity for the two embeddings. + + Raises: + ValueError: May return an error if e.g. the feature vectors are of + different types (quantized vs. float), have different sizes, or have + an L2-norm of 0 + """ + return cosine_similarity.cosine_similarity(u, v) From 664d9c49e7cf120b753fb572c936be569e93b217 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Mon, 7 Nov 2022 13:59:07 -0800 Subject: [PATCH 04/21] Revised image embedder implementation --- mediapipe/python/BUILD | 1 - .../components/containers/embeddings.py | 99 ++++++------------- .../tasks/python/components/processors/BUILD | 9 ++ .../{proto => processors}/embedder_options.py | 2 +- mediapipe/tasks/python/components/proto/BUILD | 28 ------ .../tasks/python/components/proto/__init__.py | 13 --- mediapipe/tasks/python/components/utils/BUILD | 2 +- .../components/utils/cosine_similarity.py | 16 +-- mediapipe/tasks/python/test/vision/BUILD | 2 +- .../python/test/vision/image_embedder_test.py | 17 ++-- mediapipe/tasks/python/vision/BUILD | 1 + .../tasks/python/vision/image_embedder.py | 39 ++++---- 12 files changed, 79 insertions(+), 150 deletions(-) rename mediapipe/tasks/python/components/{proto => processors}/embedder_options.py (96%) delete mode 100644 mediapipe/tasks/python/components/proto/BUILD delete mode 100644 mediapipe/tasks/python/components/proto/__init__.py diff --git a/mediapipe/python/BUILD b/mediapipe/python/BUILD index 2423370e..0f049f30 100644 --- a/mediapipe/python/BUILD +++ b/mediapipe/python/BUILD @@ -92,7 +92,6 @@ cc_library( "//mediapipe/tasks/cc/vision/image_segmenter:image_segmenter_graph", "//mediapipe/tasks/cc/vision/object_detector:object_detector_graph", "//mediapipe/tasks/cc/vision/image_embedder:image_embedder_graph", - ], ] + select({ # TODO: Build text_classifier_graph on Windows. "//mediapipe:windows": [], diff --git a/mediapipe/tasks/python/components/containers/embeddings.py b/mediapipe/tasks/python/components/containers/embeddings.py index c1185c84..3a024079 100644 --- a/mediapipe/tasks/python/components/containers/embeddings.py +++ b/mediapipe/tasks/python/components/containers/embeddings.py @@ -22,8 +22,7 @@ from mediapipe.tasks.python.core.optional_dependencies import doc_controls _FloatEmbeddingProto = embeddings_pb2.FloatEmbedding _QuantizedEmbeddingProto = embeddings_pb2.QuantizedEmbedding -_EmbeddingEntryProto = embeddings_pb2.EmbeddingEntry -_EmbeddingsProto = embeddings_pb2.Embeddings +_EmbeddingProto = embeddings_pb2.Embedding _EmbeddingResultProto = embeddings_pb2.EmbeddingResult @@ -99,28 +98,34 @@ class QuantizedEmbedding: @dataclasses.dataclass -class EmbeddingEntry: - """Floating-point or scalar-quantized embedding with an optional timestamp. +class Embedding: + """Embedding result for a given embedder head. Attributes: embedding: The actual embedding, either floating-point or scalar-quantized. - timestamp_ms: The optional timestamp (in milliseconds) associated to the - embedding entry. This is useful for time series use cases, e.g. audio - embedding. + head_index: The index of the embedder head that produced this embedding. + This is useful for multi-head models. + head_name: The name of the embedder head, which is the corresponding tensor + metadata name (if any). This is useful for multi-head models. """ embedding: np.ndarray - timestamp_ms: Optional[int] = None + head_index: int + head_name: str @doc_controls.do_not_generate_docs - def to_pb2(self) -> _EmbeddingEntryProto: - """Generates a EmbeddingEntry protobuf object.""" + def to_pb2(self) -> _EmbeddingProto: + """Generates a Embedding protobuf object.""" if self.embedding.dtype == float: - return _EmbeddingEntryProto(float_embedding=self.embedding) + return _EmbeddingProto(float_embedding=self.embedding, + head_index=self.head_index, + head_name=self.head_name) elif self.embedding.dtype == np.uint8: - return _EmbeddingEntryProto(quantized_embedding=bytes(self.embedding)) + return _EmbeddingProto(quantized_embedding=bytes(self.embedding), + head_index=self.head_index, + head_name=self.head_name) else: raise ValueError("Invalid dtype. Only float and np.uint8 are supported.") @@ -128,17 +133,21 @@ class EmbeddingEntry: @classmethod @doc_controls.do_not_generate_docs def create_from_pb2( - cls, pb2_obj: _EmbeddingEntryProto) -> 'EmbeddingEntry': - """Creates a `EmbeddingEntry` object from the given protobuf object.""" + cls, pb2_obj: _EmbeddingProto) -> 'Embedding': + """Creates a `Embedding` object from the given protobuf object.""" quantized_embedding = np.array( bytearray(pb2_obj.quantized_embedding.values)) float_embedding = np.array(pb2_obj.float_embedding.values, dtype=float) if len(quantized_embedding) == 0: - return EmbeddingEntry(embedding=float_embedding) + return Embedding(embedding=float_embedding, + head_index=pb2_obj.head_index, + head_name=pb2_obj.head_name) else: - return EmbeddingEntry(embedding=quantized_embedding) + return Embedding(embedding=quantized_embedding, + head_index=pb2_obj.head_index, + head_name=pb2_obj.head_name) def __eq__(self, other: Any) -> bool: """Checks if this object is equal to the given object. @@ -147,55 +156,7 @@ class EmbeddingEntry: Returns: True if the objects are equal. """ - if not isinstance(other, EmbeddingEntry): - return False - - return self.to_pb2().__eq__(other.to_pb2()) - - -@dataclasses.dataclass -class Embeddings: - """Embeddings for a given embedder head. - Attributes: - entries: A list of `ClassificationEntry` objects. - head_index: The index of the embedder head that produced this embedding. - This is useful for multi-head models. - head_name: The name of the embedder head, which is the corresponding tensor - metadata name (if any). This is useful for multi-head models. - """ - - entries: List[EmbeddingEntry] - head_index: int - head_name: str - - @doc_controls.do_not_generate_docs - def to_pb2(self) -> _EmbeddingsProto: - """Generates a Embeddings protobuf object.""" - return _EmbeddingsProto( - entries=[entry.to_pb2() for entry in self.entries], - head_index=self.head_index, - head_name=self.head_name) - - @classmethod - @doc_controls.do_not_generate_docs - def create_from_pb2(cls, pb2_obj: _EmbeddingsProto) -> 'Embeddings': - """Creates a `Embeddings` object from the given protobuf object.""" - return Embeddings( - entries=[ - EmbeddingEntry.create_from_pb2(entry) - for entry in pb2_obj.entries - ], - head_index=pb2_obj.head_index, - head_name=pb2_obj.head_name) - - def __eq__(self, other: Any) -> bool: - """Checks if this object is equal to the given object. - Args: - other: The object to be compared with. - Returns: - True if the objects are equal. - """ - if not isinstance(other, Embeddings): + if not isinstance(other, Embedding): return False return self.to_pb2().__eq__(other.to_pb2()) @@ -203,12 +164,12 @@ class Embeddings: @dataclasses.dataclass class EmbeddingResult: - """Contains one set of results per embedder head. + """Embedding results for a given embedder model. Attributes: - embeddings: A list of `Embeddings` objects. + embeddings: A list of `Embedding` objects. """ - embeddings: List[Embeddings] + embeddings: List[Embedding] @doc_controls.do_not_generate_docs def to_pb2(self) -> _EmbeddingResultProto: @@ -225,7 +186,7 @@ class EmbeddingResult: """Creates a `EmbeddingResult` object from the given protobuf object.""" return EmbeddingResult( embeddings=[ - Embeddings.create_from_pb2(embedding) + Embedding.create_from_pb2(embedding) for embedding in pb2_obj.embeddings ]) diff --git a/mediapipe/tasks/python/components/processors/BUILD b/mediapipe/tasks/python/components/processors/BUILD index f87a579b..eef368db 100644 --- a/mediapipe/tasks/python/components/processors/BUILD +++ b/mediapipe/tasks/python/components/processors/BUILD @@ -28,3 +28,12 @@ py_library( "//mediapipe/tasks/python/core:optional_dependencies", ], ) + +py_library( + name = "embedder_options", + srcs = ["embedder_options.py"], + deps = [ + "//mediapipe/tasks/cc/components/processors/proto:embedder_options_py_pb2", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) diff --git a/mediapipe/tasks/python/components/proto/embedder_options.py b/mediapipe/tasks/python/components/processors/embedder_options.py similarity index 96% rename from mediapipe/tasks/python/components/proto/embedder_options.py rename to mediapipe/tasks/python/components/processors/embedder_options.py index 49bcfb98..dcd316dc 100644 --- a/mediapipe/tasks/python/components/proto/embedder_options.py +++ b/mediapipe/tasks/python/components/processors/embedder_options.py @@ -16,7 +16,7 @@ import dataclasses from typing import Any, Optional -from mediapipe.tasks.cc.components.proto import embedder_options_pb2 +from mediapipe.tasks.cc.components.processors.proto import embedder_options_pb2 from mediapipe.tasks.python.core.optional_dependencies import doc_controls _EmbedderOptionsProto = embedder_options_pb2.EmbedderOptions diff --git a/mediapipe/tasks/python/components/proto/BUILD b/mediapipe/tasks/python/components/proto/BUILD deleted file mode 100644 index 973f150c..00000000 --- a/mediapipe/tasks/python/components/proto/BUILD +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright 2022 The MediaPipe Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Placeholder for internal Python strict library compatibility macro. - -package(default_visibility = ["//mediapipe/tasks:internal"]) - -licenses(["notice"]) - -py_library( - name = "embedder_options", - srcs = ["embedder_options.py"], - deps = [ - "//mediapipe/tasks/cc/components/proto:embedder_options_py_pb2", - "//mediapipe/tasks/python/core:optional_dependencies", - ], -) diff --git a/mediapipe/tasks/python/components/proto/__init__.py b/mediapipe/tasks/python/components/proto/__init__.py deleted file mode 100644 index 65c1214a..00000000 --- a/mediapipe/tasks/python/components/proto/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright 2022 The MediaPipe Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/mediapipe/tasks/python/components/utils/BUILD b/mediapipe/tasks/python/components/utils/BUILD index 7ec01a03..6d00bb31 100644 --- a/mediapipe/tasks/python/components/utils/BUILD +++ b/mediapipe/tasks/python/components/utils/BUILD @@ -23,6 +23,6 @@ py_library( srcs = ["cosine_similarity.py"], deps = [ "//mediapipe/tasks/python/components/containers:embeddings", - "//mediapipe/tasks/python/components/proto:embedder_options", + "//mediapipe/tasks/python/components/processors:embedder_options", ], ) diff --git a/mediapipe/tasks/python/components/utils/cosine_similarity.py b/mediapipe/tasks/python/components/utils/cosine_similarity.py index 8723a55e..616f2651 100644 --- a/mediapipe/tasks/python/components/utils/cosine_similarity.py +++ b/mediapipe/tasks/python/components/utils/cosine_similarity.py @@ -16,9 +16,9 @@ import numpy as np from mediapipe.tasks.python.components.containers import embeddings -from mediapipe.tasks.python.components.proto import embedder_options +from mediapipe.tasks.python.components.processors import embedder_options -_EmbeddingEntry = embeddings.EmbeddingEntry +_Embedding = embeddings.Embedding _EmbedderOptions = embedder_options.EmbedderOptions @@ -36,15 +36,15 @@ def _compute_cosine_similarity(u, v): return np.dot(u.embedding, v.embedding.T) / (norm_u * norm_v) -def cosine_similarity(u: _EmbeddingEntry, v: _EmbeddingEntry) -> float: - """Utility function to compute cosine similarity between two embedding - entries. May return an InvalidArgumentError if e.g. the feature vectors are - of different types (quantized vs. float), have different sizes, or have an +def cosine_similarity(u: _Embedding, v: _Embedding) -> float: + """Utility function to compute cosine similarity between two embedding. + May return an InvalidArgumentError if e.g. the feature vectors are of + different types (quantized vs. float), have different sizes, or have an L2-norm of 0. Args: - u: An embedding entry. - v: An embedding entry. + u: An embedding. + v: An embedding. """ if len(u.embedding) != len(v.embedding): raise ValueError(f"Cannot compute cosine similarity between embeddings " diff --git a/mediapipe/tasks/python/test/vision/BUILD b/mediapipe/tasks/python/test/vision/BUILD index 9fee8a02..5fd39616 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -83,7 +83,7 @@ py_test( ], deps = [ "//mediapipe/python:_framework_bindings", - "//mediapipe/tasks/python/components/proto:embedder_options", + "//mediapipe/tasks/python/components/processors:embedder_options", "//mediapipe/tasks/python/components/utils:cosine_similarity", "//mediapipe/tasks/python/components/containers:embeddings", "//mediapipe/tasks/python/components/containers:rect", diff --git a/mediapipe/tasks/python/test/vision/image_embedder_test.py b/mediapipe/tasks/python/test/vision/image_embedder_test.py index 4f109ea2..7bcf48d7 100644 --- a/mediapipe/tasks/python/test/vision/image_embedder_test.py +++ b/mediapipe/tasks/python/test/vision/image_embedder_test.py @@ -22,7 +22,7 @@ from absl.testing import absltest from absl.testing import parameterized from mediapipe.python._framework_bindings import image as image_module -from mediapipe.tasks.python.components.proto import embedder_options as embedder_options_module +from mediapipe.tasks.python.components.processors import embedder_options as embedder_options_module from mediapipe.tasks.python.components.containers import embeddings as embeddings_module from mediapipe.tasks.python.components.containers import rect from mediapipe.tasks.python.core import base_options as base_options_module @@ -36,8 +36,7 @@ _BaseOptions = base_options_module.BaseOptions _EmbedderOptions = embedder_options_module.EmbedderOptions _FloatEmbedding = embeddings_module.FloatEmbedding _QuantizedEmbedding = embeddings_module.QuantizedEmbedding -_EmbeddingEntry = embeddings_module.EmbeddingEntry -_Embeddings = embeddings_module.Embeddings +_Embedding = embeddings_module.Embedding _EmbeddingResult = embeddings_module.EmbeddingResult _Image = image_module.Image _ImageEmbedder = image_embedder.ImageEmbedder @@ -81,12 +80,12 @@ class ImageEmbedderTest(parameterized.TestCase): # Check embedding sizes. def _check_embedding_size(result): self.assertLen(result.embeddings, 1) - embedding_entry = result.embeddings[0].entries[0] - self.assertLen(embedding_entry.embedding, 1024) + embedding_result = result.embeddings[0] + self.assertLen(embedding_result.embedding, 1024) if quantize: - self.assertEqual(embedding_entry.embedding.dtype, np.uint8) + self.assertEqual(embedding_result.embedding.dtype, np.uint8) else: - self.assertEqual(embedding_entry.embedding.dtype, float) + self.assertEqual(embedding_result.embedding.dtype, float) # Checks results sizes. _check_embedding_size(result0) @@ -94,7 +93,7 @@ class ImageEmbedderTest(parameterized.TestCase): # Checks cosine similarity. similarity = _ImageEmbedder.cosine_similarity( - result0.embeddings[0].entries[0], result1.embeddings[0].entries[0]) + result0.embeddings[0], result1.embeddings[0]) self.assertAlmostEqual(similarity, expected_similarity, delta=_SIMILARITY_TOLERANCE) @@ -134,7 +133,7 @@ class ImageEmbedderTest(parameterized.TestCase): crop_result = embedder.embed(self.test_cropped_image) # Check embedding value. - self.assertAlmostEqual(image_result.embeddings[0].entries[0].embedding[0], + self.assertAlmostEqual(image_result.embeddings[0].embedding[0], expected_first_value) # Checks cosine similarity. diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index 9d406be2..1d60fa5b 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -114,6 +114,7 @@ py_library( "//mediapipe/python:packet_getter", "//mediapipe/tasks/cc/vision/image_embedder/proto:image_embedder_graph_options_py_pb2", "//mediapipe/tasks/python/components/containers:embeddings", + "//mediapipe/tasks/python/components/processors:classifier_options", "//mediapipe/tasks/python/core:base_options", "//mediapipe/tasks/python/core:optional_dependencies", "//mediapipe/tasks/python/core:task_info", diff --git a/mediapipe/tasks/python/vision/image_embedder.py b/mediapipe/tasks/python/vision/image_embedder.py index e287593f..2851970d 100644 --- a/mediapipe/tasks/python/vision/image_embedder.py +++ b/mediapipe/tasks/python/vision/image_embedder.py @@ -22,7 +22,7 @@ from mediapipe.python._framework_bindings import image as image_module from mediapipe.python._framework_bindings import packet as packet_module from mediapipe.python._framework_bindings import task_runner as task_runner_module from mediapipe.tasks.cc.vision.image_embedder.proto import image_embedder_graph_options_pb2 -from mediapipe.tasks.python.components.proto import embedder_options +from mediapipe.tasks.python.components.processors import embedder_options from mediapipe.tasks.python.components.utils import cosine_similarity from mediapipe.tasks.python.components.containers import embeddings as embeddings_module from mediapipe.tasks.python.core import base_options as base_options_module @@ -32,6 +32,7 @@ from mediapipe.tasks.python.vision.core import base_vision_task_api from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module +_ImageEmbedderResult = embeddings_module.EmbeddingResult _BaseOptions = base_options_module.BaseOptions _ImageEmbedderGraphOptionsProto = image_embedder_graph_options_pb2.ImageEmbedderGraphOptions _EmbedderOptions = embedder_options.EmbedderOptions @@ -40,8 +41,8 @@ _TaskInfo = task_info_module.TaskInfo _ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _TaskRunner = task_runner_module.TaskRunner -_EMBEDDING_RESULT_OUT_STREAM_NAME = 'embedding_result_out' -_EMBEDDING_RESULT_TAG = 'EMBEDDING_RESULT' +_EMBEDDINGS_OUT_STREAM_NAME = 'embeddings_out' +_EMBEDDINGS_TAG = 'EMBEDDINGS' _IMAGE_IN_STREAM_NAME = 'image_in' _IMAGE_OUT_STREAM_NAME = 'image_out' _IMAGE_TAG = 'IMAGE' @@ -140,15 +141,15 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): if output_packets[_IMAGE_OUT_STREAM_NAME].is_empty(): return embedding_result_proto = packet_getter.get_proto( - output_packets[_EMBEDDING_RESULT_OUT_STREAM_NAME]) + output_packets[_EMBEDDINGS_OUT_STREAM_NAME]) - embedding_result = embeddings_module.EmbeddingResult([ - embeddings_module.Embeddings.create_from_pb2(embedding) + embeddings = embeddings_module.EmbeddingResult([ + embeddings_module.Embedding.create_from_pb2(embedding) for embedding in embedding_result_proto.embeddings ]) image = packet_getter.get_image(output_packets[_IMAGE_OUT_STREAM_NAME]) timestamp = output_packets[_IMAGE_OUT_STREAM_NAME].timestamp - options.result_callback(embedding_result, image, + options.result_callback(embeddings, image, timestamp.value // _MICRO_SECONDS_PER_MILLISECOND) task_info = _TaskInfo( @@ -158,8 +159,8 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): ':'.join([_NORM_RECT_TAG, _NORM_RECT_STREAM_NAME]), ], output_streams=[ - ':'.join([_EMBEDDING_RESULT_TAG, - _EMBEDDING_RESULT_OUT_STREAM_NAME]), + ':'.join([_EMBEDDINGS_TAG, + _EMBEDDINGS_OUT_STREAM_NAME]), ':'.join([_IMAGE_TAG, _IMAGE_OUT_STREAM_NAME]) ], task_options=options) @@ -173,7 +174,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): self, image: image_module.Image, image_processing_options: Optional[_ImageProcessingOptions] = None - ) -> embeddings_module.EmbeddingResult: + ) -> _ImageEmbedderResult: """Performs image embedding extraction on the provided MediaPipe Image. Extraction is performed on the region of interest specified by the `roi` argument if provided, or on the entire image otherwise. @@ -195,18 +196,18 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): _NORM_RECT_STREAM_NAME: packet_creator.create_proto( normalized_rect.to_pb2())}) embedding_result_proto = packet_getter.get_proto( - output_packets[_EMBEDDING_RESULT_OUT_STREAM_NAME]) + output_packets[_EMBEDDINGS_OUT_STREAM_NAME]) return embeddings_module.EmbeddingResult([ - embeddings_module.Embeddings.create_from_pb2(embedding) - for embedding in embedding_result_proto.embeddings + embeddings_module.Embedding.create_from_pb2(embedding) + for embedding in embedding_result_proto.embeddings ]) def embed_for_video( self, image: image_module.Image, timestamp_ms: int, image_processing_options: Optional[_ImageProcessingOptions] = None - ) -> embeddings_module.EmbeddingResult: + ) -> _ImageEmbedderResult: """Performs image embedding extraction on the provided video frames. Extraction is performed on the region of interested specified by the `roi` argument if provided, or on the entire image otherwise. @@ -237,11 +238,11 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) }) embedding_result_proto = packet_getter.get_proto( - output_packets[_EMBEDDING_RESULT_OUT_STREAM_NAME]) + output_packets[_EMBEDDINGS_OUT_STREAM_NAME]) return embeddings_module.EmbeddingResult([ - embeddings_module.Embeddings.create_from_pb2(embedding) - for embedding in embedding_result_proto.embeddings + embeddings_module.Embedding.create_from_pb2(embedding) + for embedding in embedding_result_proto.embeddings ]) def embed_async( @@ -289,8 +290,8 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): }) @staticmethod - def cosine_similarity(u: embeddings_module.EmbeddingEntry, - v: embeddings_module.EmbeddingEntry) -> float: + def cosine_similarity(u: embeddings_module.Embedding, + v: embeddings_module.Embedding) -> float: """Utility function to compute cosine similarity [1] between two embedding entries. May return an InvalidArgumentError if e.g. the feature vectors are of different types (quantized vs. float), have different sizes, or have a From dd6fdedd5f4f280a9cd99c43f22e66aaa2869df5 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Tue, 8 Nov 2022 23:15:58 -0800 Subject: [PATCH 05/21] Added some sanity tests --- .../python/test/vision/image_embedder_test.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/mediapipe/tasks/python/test/vision/image_embedder_test.py b/mediapipe/tasks/python/test/vision/image_embedder_test.py index 7bcf48d7..624a9d99 100644 --- a/mediapipe/tasks/python/test/vision/image_embedder_test.py +++ b/mediapipe/tasks/python/test/vision/image_embedder_test.py @@ -69,6 +69,34 @@ class ImageEmbedderTest(parameterized.TestCase): self.model_path = test_utils.get_test_data_path( os.path.join(_TEST_DATA_DIR, _MODEL_FILE)) + def test_create_from_file_succeeds_with_valid_model_path(self): + # Creates with default option and valid model file successfully. + with _ImageEmbedder.create_from_model_path(self.model_path) as embedder: + self.assertIsInstance(embedder, _ImageEmbedder) + + def test_create_from_options_succeeds_with_valid_model_path(self): + # Creates with options containing model file successfully. + base_options = _BaseOptions(model_asset_path=self.model_path) + options = _ImageEmbedderOptions(base_options=base_options) + with _ImageEmbedder.create_from_options(options) as embedder: + self.assertIsInstance(embedder, _ImageEmbedder) + + def test_create_from_options_fails_with_invalid_model_path(self): + with self.assertRaisesRegex( + RuntimeError, 'Unable to open file at /path/to/invalid/model.tflite'): + base_options = _BaseOptions( + model_asset_path='/path/to/invalid/model.tflite') + options = _ImageEmbedderOptions(base_options=base_options) + _ImageEmbedder.create_from_options(options) + + def test_create_from_options_succeeds_with_valid_model_content(self): + # Creates with options containing model content successfully. + with open(self.model_path, 'rb') as f: + base_options = _BaseOptions(model_asset_buffer=f.read()) + options = _ImageEmbedderOptions(base_options=base_options) + embedder = _ImageEmbedder.create_from_options(options) + self.assertIsInstance(embedder, _ImageEmbedder) + def _check_cosine_similarity(self, result0, result1, quantize, expected_similarity): # Checks head_index and head_name. From d327b3649df98a55049bd2d5e216584bf040a392 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Tue, 8 Nov 2022 23:47:58 -0800 Subject: [PATCH 06/21] Fixed some typos in methods and comments --- mediapipe/tasks/python/test/vision/image_embedder_test.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/mediapipe/tasks/python/test/vision/image_embedder_test.py b/mediapipe/tasks/python/test/vision/image_embedder_test.py index 624a9d99..0dfce91c 100644 --- a/mediapipe/tasks/python/test/vision/image_embedder_test.py +++ b/mediapipe/tasks/python/test/vision/image_embedder_test.py @@ -167,7 +167,7 @@ class ImageEmbedderTest(parameterized.TestCase): # Checks cosine similarity. self._check_cosine_similarity(image_result, crop_result, quantize, expected_similarity) - # Closes the embedder explicitly when the classifier is not used in + # Closes the embedder explicitly when the embedder is not used in # a context. embedder.close() @@ -315,7 +315,7 @@ class ImageEmbedderTest(parameterized.TestCase): r'not initialized with the image mode'): embedder.embed(self.test_image) - def test_calling_classify_for_video_in_live_stream_mode(self): + def test_calling_embed_for_video_in_live_stream_mode(self): options = _ImageEmbedderOptions( base_options=_BaseOptions(model_asset_path=self.model_path), running_mode=_RUNNING_MODE.LIVE_STREAM, @@ -325,7 +325,7 @@ class ImageEmbedderTest(parameterized.TestCase): r'not initialized with the video mode'): embedder.embed_for_video(self.test_image, 0) - def test_classify_async_calls_with_illegal_timestamp(self): + def test_embed_async_calls_with_illegal_timestamp(self): options = _ImageEmbedderOptions( base_options=_BaseOptions(model_asset_path=self.model_path), running_mode=_RUNNING_MODE.LIVE_STREAM, @@ -365,7 +365,7 @@ class ImageEmbedderTest(parameterized.TestCase): for timestamp in range(0, 300, 30): embedder.embed_async(self.test_image, timestamp) - def test_classify_async_succeeds_with_region_of_interest(self): + def test_embed_async_succeeds_with_region_of_interest(self): # Get the embedding result for the cropped image. options = _ImageEmbedderOptions( base_options=_BaseOptions(model_asset_path=self.model_path), From dc30cf973273bd8693ce94465839205bf717ec1e Mon Sep 17 00:00:00 2001 From: kinaryml Date: Tue, 8 Nov 2022 23:51:55 -0800 Subject: [PATCH 07/21] Updated embeddings container to use a timestamp and made parameters - head_index,head_name optional --- .../tasks/python/components/containers/embeddings.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/mediapipe/tasks/python/components/containers/embeddings.py b/mediapipe/tasks/python/components/containers/embeddings.py index 3a024079..35882b9f 100644 --- a/mediapipe/tasks/python/components/containers/embeddings.py +++ b/mediapipe/tasks/python/components/containers/embeddings.py @@ -110,8 +110,8 @@ class Embedding: """ embedding: np.ndarray - head_index: int - head_name: str + head_index: Optional[int] = None + head_name: Optional[str] = None @doc_controls.do_not_generate_docs def to_pb2(self) -> _EmbeddingProto: @@ -167,9 +167,16 @@ class EmbeddingResult: """Embedding results for a given embedder model. Attributes: embeddings: A list of `Embedding` objects. + timestamp_ms: The optional timestamp (in milliseconds) of the start of the + chunk of data corresponding to these results. This is only used for + embedding extraction on time series (e.g. audio embedding). In these use + cases, the amount of data to process might exceed the maximum size that + the model can process: to solve this, the input data is split into + multiple chunks starting at different timestamps. """ embeddings: List[Embedding] + timestamp_ms: Optional[int] = None @doc_controls.do_not_generate_docs def to_pb2(self) -> _EmbeddingResultProto: From 17bb174444ed374578aaa38387f59ab8389b8822 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Wed, 9 Nov 2022 11:42:32 -0800 Subject: [PATCH 08/21] Refactored embeddings to embedding_result --- .../tasks/python/components/containers/BUILD | 4 +- .../{embeddings.py => embedding_result.py} | 0 mediapipe/tasks/python/components/utils/BUILD | 2 +- .../components/utils/cosine_similarity.py | 4 +- mediapipe/tasks/python/test/vision/BUILD | 2 +- .../python/test/vision/image_embedder_test.py | 14 ++--- mediapipe/tasks/python/vision/BUILD | 3 +- .../tasks/python/vision/image_embedder.py | 52 +++++++++---------- 8 files changed, 40 insertions(+), 41 deletions(-) rename mediapipe/tasks/python/components/containers/{embeddings.py => embedding_result.py} (100%) diff --git a/mediapipe/tasks/python/components/containers/BUILD b/mediapipe/tasks/python/components/containers/BUILD index 1f01e295..7091c1f4 100644 --- a/mediapipe/tasks/python/components/containers/BUILD +++ b/mediapipe/tasks/python/components/containers/BUILD @@ -106,8 +106,8 @@ py_library( ) py_library( - name = "embeddings", - srcs = ["embeddings.py"], + name = "embedding_result", + srcs = ["embedding_result.py"], deps = [ "//mediapipe/tasks/cc/components/containers/proto:embeddings_py_pb2", "//mediapipe/tasks/python/core:optional_dependencies", diff --git a/mediapipe/tasks/python/components/containers/embeddings.py b/mediapipe/tasks/python/components/containers/embedding_result.py similarity index 100% rename from mediapipe/tasks/python/components/containers/embeddings.py rename to mediapipe/tasks/python/components/containers/embedding_result.py diff --git a/mediapipe/tasks/python/components/utils/BUILD b/mediapipe/tasks/python/components/utils/BUILD index 6d00bb31..50d4094c 100644 --- a/mediapipe/tasks/python/components/utils/BUILD +++ b/mediapipe/tasks/python/components/utils/BUILD @@ -22,7 +22,7 @@ py_library( name = "cosine_similarity", srcs = ["cosine_similarity.py"], deps = [ - "//mediapipe/tasks/python/components/containers:embeddings", + "//mediapipe/tasks/python/components/containers:embedding_result", "//mediapipe/tasks/python/components/processors:embedder_options", ], ) diff --git a/mediapipe/tasks/python/components/utils/cosine_similarity.py b/mediapipe/tasks/python/components/utils/cosine_similarity.py index 616f2651..d6102f0b 100644 --- a/mediapipe/tasks/python/components/utils/cosine_similarity.py +++ b/mediapipe/tasks/python/components/utils/cosine_similarity.py @@ -15,10 +15,10 @@ import numpy as np -from mediapipe.tasks.python.components.containers import embeddings +from mediapipe.tasks.python.components.containers import embedding_result from mediapipe.tasks.python.components.processors import embedder_options -_Embedding = embeddings.Embedding +_Embedding = embedding_result.Embedding _EmbedderOptions = embedder_options.EmbedderOptions diff --git a/mediapipe/tasks/python/test/vision/BUILD b/mediapipe/tasks/python/test/vision/BUILD index 5fd39616..553e1f5a 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -85,7 +85,7 @@ py_test( "//mediapipe/python:_framework_bindings", "//mediapipe/tasks/python/components/processors:embedder_options", "//mediapipe/tasks/python/components/utils:cosine_similarity", - "//mediapipe/tasks/python/components/containers:embeddings", + "//mediapipe/tasks/python/components/containers:embedding_result", "//mediapipe/tasks/python/components/containers:rect", "//mediapipe/tasks/python/core:base_options", "//mediapipe/tasks/python/test:test_utils", diff --git a/mediapipe/tasks/python/test/vision/image_embedder_test.py b/mediapipe/tasks/python/test/vision/image_embedder_test.py index 0dfce91c..e9ff50ed 100644 --- a/mediapipe/tasks/python/test/vision/image_embedder_test.py +++ b/mediapipe/tasks/python/test/vision/image_embedder_test.py @@ -23,7 +23,7 @@ from absl.testing import parameterized from mediapipe.python._framework_bindings import image as image_module from mediapipe.tasks.python.components.processors import embedder_options as embedder_options_module -from mediapipe.tasks.python.components.containers import embeddings as embeddings_module +from mediapipe.tasks.python.components.containers import embedding_result as embedding_result_module from mediapipe.tasks.python.components.containers import rect from mediapipe.tasks.python.core import base_options as base_options_module from mediapipe.tasks.python.test import test_utils @@ -31,13 +31,13 @@ from mediapipe.tasks.python.vision import image_embedder from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module +ImageEmbedderResult = embedding_result_module.EmbeddingResult _Rect = rect.Rect _BaseOptions = base_options_module.BaseOptions _EmbedderOptions = embedder_options_module.EmbedderOptions -_FloatEmbedding = embeddings_module.FloatEmbedding -_QuantizedEmbedding = embeddings_module.QuantizedEmbedding -_Embedding = embeddings_module.Embedding -_EmbeddingResult = embeddings_module.EmbeddingResult +_FloatEmbedding = embedding_result_module.FloatEmbedding +_QuantizedEmbedding = embedding_result_module.QuantizedEmbedding +_Embedding = embedding_result_module.Embedding _Image = image_module.Image _ImageEmbedder = image_embedder.ImageEmbedder _ImageEmbedderOptions = image_embedder.ImageEmbedderOptions @@ -346,7 +346,7 @@ class ImageEmbedderTest(parameterized.TestCase): observed_timestamp_ms = -1 - def check_result(result: _EmbeddingResult, output_image: _Image, + def check_result(result: ImageEmbedderResult, output_image: _Image, timestamp_ms: int): # Checks cosine similarity. self._check_cosine_similarity(result, crop_result, quantize=False, @@ -378,7 +378,7 @@ class ImageEmbedderTest(parameterized.TestCase): image_processing_options = _ImageProcessingOptions(roi) observed_timestamp_ms = -1 - def check_result(result: _EmbeddingResult, output_image: _Image, + def check_result(result: ImageEmbedderResult, output_image: _Image, timestamp_ms: int): # Checks cosine similarity. self._check_cosine_similarity(result, crop_result, quantize=False, diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index 3c040fb4..0af8f07e 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -113,7 +113,8 @@ py_library( "//mediapipe/python:packet_creator", "//mediapipe/python:packet_getter", "//mediapipe/tasks/cc/vision/image_embedder/proto:image_embedder_graph_options_py_pb2", - "//mediapipe/tasks/python/components/containers:embeddings", + "//mediapipe/tasks/cc/components/containers/proto:embeddings_py_pb2", + "//mediapipe/tasks/python/components/containers:embedding_result", "//mediapipe/tasks/python/components/processors:classifier_options", "//mediapipe/tasks/python/core:base_options", "//mediapipe/tasks/python/core:optional_dependencies", diff --git a/mediapipe/tasks/python/vision/image_embedder.py b/mediapipe/tasks/python/vision/image_embedder.py index 2851970d..bec9682d 100644 --- a/mediapipe/tasks/python/vision/image_embedder.py +++ b/mediapipe/tasks/python/vision/image_embedder.py @@ -22,9 +22,10 @@ from mediapipe.python._framework_bindings import image as image_module from mediapipe.python._framework_bindings import packet as packet_module from mediapipe.python._framework_bindings import task_runner as task_runner_module from mediapipe.tasks.cc.vision.image_embedder.proto import image_embedder_graph_options_pb2 +from mediapipe.tasks.cc.components.containers.proto import embeddings_pb2 from mediapipe.tasks.python.components.processors import embedder_options from mediapipe.tasks.python.components.utils import cosine_similarity -from mediapipe.tasks.python.components.containers import embeddings as embeddings_module +from mediapipe.tasks.python.components.containers import embedding_result as embedding_result_module from mediapipe.tasks.python.core import base_options as base_options_module from mediapipe.tasks.python.core import task_info as task_info_module from mediapipe.tasks.python.core.optional_dependencies import doc_controls @@ -32,7 +33,7 @@ from mediapipe.tasks.python.vision.core import base_vision_task_api from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module -_ImageEmbedderResult = embeddings_module.EmbeddingResult +ImageEmbedderResult = embedding_result_module.EmbeddingResult _BaseOptions = base_options_module.BaseOptions _ImageEmbedderGraphOptionsProto = image_embedder_graph_options_pb2.ImageEmbedderGraphOptions _EmbedderOptions = embedder_options.EmbedderOptions @@ -76,7 +77,7 @@ class ImageEmbedderOptions: quantize: Optional[bool] = None embedder_options: _EmbedderOptions = _EmbedderOptions() result_callback: Optional[ - Callable[[embeddings_module.EmbeddingResult, image_module.Image, + Callable[[ImageEmbedderResult, image_module.Image, int], None]] = None @doc_controls.do_not_generate_docs @@ -140,17 +141,17 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): def packets_callback(output_packets: Mapping[str, packet_module.Packet]): if output_packets[_IMAGE_OUT_STREAM_NAME].is_empty(): return - embedding_result_proto = packet_getter.get_proto( - output_packets[_EMBEDDINGS_OUT_STREAM_NAME]) - embeddings = embeddings_module.EmbeddingResult([ - embeddings_module.Embedding.create_from_pb2(embedding) - for embedding in embedding_result_proto.embeddings - ]) + embedding_result_proto = embeddings_pb2.EmbeddingResult() + embedding_result_proto.CopyFrom( + packet_getter.get_proto(output_packets[_EMBEDDINGS_OUT_STREAM_NAME])) + image = packet_getter.get_image(output_packets[_IMAGE_OUT_STREAM_NAME]) timestamp = output_packets[_IMAGE_OUT_STREAM_NAME].timestamp - options.result_callback(embeddings, image, - timestamp.value // _MICRO_SECONDS_PER_MILLISECOND) + options.result_callback( + ImageEmbedderResult.create_from_pb2(embedding_result_proto), + image, + timestamp.value // _MICRO_SECONDS_PER_MILLISECOND) task_info = _TaskInfo( task_graph=_TASK_GRAPH_NAME, @@ -174,7 +175,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): self, image: image_module.Image, image_processing_options: Optional[_ImageProcessingOptions] = None - ) -> _ImageEmbedderResult: + ) -> ImageEmbedderResult: """Performs image embedding extraction on the provided MediaPipe Image. Extraction is performed on the region of interest specified by the `roi` argument if provided, or on the entire image otherwise. @@ -195,19 +196,18 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image), _NORM_RECT_STREAM_NAME: packet_creator.create_proto( normalized_rect.to_pb2())}) - embedding_result_proto = packet_getter.get_proto( - output_packets[_EMBEDDINGS_OUT_STREAM_NAME]) - return embeddings_module.EmbeddingResult([ - embeddings_module.Embedding.create_from_pb2(embedding) - for embedding in embedding_result_proto.embeddings - ]) + embedding_result_proto = embeddings_pb2.EmbeddingResult() + embedding_result_proto.CopyFrom( + packet_getter.get_proto(output_packets[_EMBEDDINGS_OUT_STREAM_NAME])) + + return ImageEmbedderResult.create_from_pb2(embedding_result_proto) def embed_for_video( self, image: image_module.Image, timestamp_ms: int, image_processing_options: Optional[_ImageProcessingOptions] = None - ) -> _ImageEmbedderResult: + ) -> ImageEmbedderResult: """Performs image embedding extraction on the provided video frames. Extraction is performed on the region of interested specified by the `roi` argument if provided, or on the entire image otherwise. @@ -237,13 +237,11 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): normalized_rect.to_pb2()).at( timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) }) - embedding_result_proto = packet_getter.get_proto( - output_packets[_EMBEDDINGS_OUT_STREAM_NAME]) + embedding_result_proto = embeddings_pb2.EmbeddingResult() + embedding_result_proto.CopyFrom( + packet_getter.get_proto(output_packets[_EMBEDDINGS_OUT_STREAM_NAME])) - return embeddings_module.EmbeddingResult([ - embeddings_module.Embedding.create_from_pb2(embedding) - for embedding in embedding_result_proto.embeddings - ]) + return ImageEmbedderResult.create_from_pb2(embedding_result_proto) def embed_async( self, @@ -290,8 +288,8 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): }) @staticmethod - def cosine_similarity(u: embeddings_module.Embedding, - v: embeddings_module.Embedding) -> float: + def cosine_similarity(u: embedding_result_module.Embedding, + v: embedding_result_module.Embedding) -> float: """Utility function to compute cosine similarity [1] between two embedding entries. May return an InvalidArgumentError if e.g. the feature vectors are of different types (quantized vs. float), have different sizes, or have a From 7ec0d8cf3b236c4ee5bccd02197984e3ccaae4de Mon Sep 17 00:00:00 2001 From: kinaryml Date: Wed, 9 Nov 2022 11:53:30 -0800 Subject: [PATCH 09/21] Added tolerance for vector coordinate values in embeddings --- mediapipe/tasks/python/test/vision/image_embedder_test.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/mediapipe/tasks/python/test/vision/image_embedder_test.py b/mediapipe/tasks/python/test/vision/image_embedder_test.py index e9ff50ed..18fd644a 100644 --- a/mediapipe/tasks/python/test/vision/image_embedder_test.py +++ b/mediapipe/tasks/python/test/vision/image_embedder_test.py @@ -48,6 +48,9 @@ _MODEL_FILE = 'mobilenet_v3_small_100_224_embedder.tflite' _BURGER_IMAGE_FILE = 'burger.jpg' _BURGER_CROPPED_IMAGE_FILE = 'burger_crop.jpg' _TEST_DATA_DIR = 'mediapipe/tasks/testdata/vision' +# Tolerance for embedding vector coordinate values. +_EPSILON = 1e-4 +# Tolerance for cosine similarity evaluation. _SIMILARITY_TOLERANCE = 1e-6 @@ -162,7 +165,7 @@ class ImageEmbedderTest(parameterized.TestCase): # Check embedding value. self.assertAlmostEqual(image_result.embeddings[0].embedding[0], - expected_first_value) + expected_first_value, delta=_EPSILON) # Checks cosine similarity. self._check_cosine_similarity(image_result, crop_result, quantize, From 0e9b9257262abc625089664e13571af7168ff576 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Thu, 10 Nov 2022 02:30:17 -0800 Subject: [PATCH 10/21] Fixed some typos and revised image embedder tests --- .../python/test/vision/image_embedder_test.py | 75 +++++++++---------- .../tasks/python/vision/image_embedder.py | 10 +-- 2 files changed, 40 insertions(+), 45 deletions(-) diff --git a/mediapipe/tasks/python/test/vision/image_embedder_test.py b/mediapipe/tasks/python/test/vision/image_embedder_test.py index 18fd644a..3df1ed1c 100644 --- a/mediapipe/tasks/python/test/vision/image_embedder_test.py +++ b/mediapipe/tasks/python/test/vision/image_embedder_test.py @@ -100,28 +100,22 @@ class ImageEmbedderTest(parameterized.TestCase): embedder = _ImageEmbedder.create_from_options(options) self.assertIsInstance(embedder, _ImageEmbedder) - def _check_cosine_similarity(self, result0, result1, quantize, - expected_similarity): - # Checks head_index and head_name. - self.assertEqual(result0.embeddings[0].head_index, 0) - self.assertEqual(result1.embeddings[0].head_index, 0) - self.assertEqual(result0.embeddings[0].head_name, 'feature') - self.assertEqual(result1.embeddings[0].head_name, 'feature') + def _check_embedding_value(self, result, expected_first_value): + # Check embedding first value. + self.assertAlmostEqual(result.embeddings[0].embedding[0], + expected_first_value, delta=_EPSILON) - # Check embedding sizes. - def _check_embedding_size(result): - self.assertLen(result.embeddings, 1) - embedding_result = result.embeddings[0] - self.assertLen(embedding_result.embedding, 1024) - if quantize: - self.assertEqual(embedding_result.embedding.dtype, np.uint8) - else: - self.assertEqual(embedding_result.embedding.dtype, float) - - # Checks results sizes. - _check_embedding_size(result0) - _check_embedding_size(result1) + def _check_embedding_size(self, result, quantize, expected_embedding_size): + # Check embedding size. + self.assertLen(result.embeddings, 1) + embedding_result = result.embeddings[0] + self.assertLen(embedding_result.embedding, expected_embedding_size) + if quantize: + self.assertEqual(embedding_result.embedding.dtype, np.uint8) + else: + self.assertEqual(embedding_result.embedding.dtype, float) + def _check_cosine_similarity(self, result0, result1, expected_similarity): # Checks cosine similarity. similarity = _ImageEmbedder.cosine_similarity( result0.embeddings[0], result1.embeddings[0]) @@ -129,13 +123,17 @@ class ImageEmbedderTest(parameterized.TestCase): delta=_SIMILARITY_TOLERANCE) @parameterized.parameters( - (False, False, False, ModelFileType.FILE_NAME, 0.925519, -0.2101883), - (True, False, False, ModelFileType.FILE_NAME, 0.925519, -0.0142344), - # (False, True, False, ModelFileType.FILE_NAME, 0.926791, 229), - (False, False, True, ModelFileType.FILE_CONTENT, 0.999931, -0.195062) + (False, False, False, ModelFileType.FILE_NAME, + 0.925519, 1024, (-0.2101883, -0.193027)), + (True, False, False, ModelFileType.FILE_NAME, + 0.925519, 1024, (-0.0142344, -0.0131606)), + # (False, True, False, ModelFileType.FILE_NAME, + # 0.926791, 1024, (229, 231)), + (False, False, True, ModelFileType.FILE_CONTENT, + 0.999931, 1024, (-0.195062, -0.193027)) ) def test_embed(self, l2_normalize, quantize, with_roi, model_file_type, - expected_similarity, expected_first_value): + expected_similarity, expected_size, expected_first_values): # Creates embedder. if model_file_type is ModelFileType.FILE_NAME: base_options = _BaseOptions(model_asset_path=self.model_path) @@ -163,12 +161,13 @@ class ImageEmbedderTest(parameterized.TestCase): image_result = embedder.embed(self.test_image, image_processing_options) crop_result = embedder.embed(self.test_cropped_image) - # Check embedding value. - self.assertAlmostEqual(image_result.embeddings[0].embedding[0], - expected_first_value, delta=_EPSILON) - - # Checks cosine similarity. - self._check_cosine_similarity(image_result, crop_result, quantize, + # Checks embeddings and cosine similarity. + expected_result0_value, expected_result1_value = expected_first_values + self._check_embedding_size(image_result, quantize, expected_size) + self._check_embedding_size(crop_result, quantize, expected_size) + self._check_embedding_value(image_result, expected_result0_value) + self._check_embedding_value(crop_result, expected_result1_value) + self._check_cosine_similarity(image_result, crop_result, expected_similarity) # Closes the embedder explicitly when the embedder is not used in # a context. @@ -201,7 +200,7 @@ class ImageEmbedderTest(parameterized.TestCase): crop_result = embedder.embed(self.test_cropped_image) # Checks cosine similarity. - self._check_cosine_similarity(image_result, crop_result, quantize, + self._check_cosine_similarity(image_result, crop_result, expected_similarity) def test_missing_result_callback(self): @@ -283,8 +282,7 @@ class ImageEmbedderTest(parameterized.TestCase): timestamp) # Checks cosine similarity. self._check_cosine_similarity( - image_result, crop_result, quantize=False, - expected_similarity=0.925519) + image_result, crop_result, expected_similarity=0.925519) def test_embed_for_video_succeeds_with_region_of_interest(self): options = _ImageEmbedderOptions( @@ -305,8 +303,7 @@ class ImageEmbedderTest(parameterized.TestCase): # Checks cosine similarity. self._check_cosine_similarity( - image_result, crop_result, quantize=False, - expected_similarity=0.999931) + image_result, crop_result, expected_similarity=0.999931) def test_calling_embed_in_live_stream_mode(self): options = _ImageEmbedderOptions( @@ -352,8 +349,8 @@ class ImageEmbedderTest(parameterized.TestCase): def check_result(result: ImageEmbedderResult, output_image: _Image, timestamp_ms: int): # Checks cosine similarity. - self._check_cosine_similarity(result, crop_result, quantize=False, - expected_similarity=0.925519) + self._check_cosine_similarity(result, crop_result, + expected_similarity=0.925519) self.assertTrue( np.array_equal(output_image.numpy_view(), self.test_image.numpy_view())) @@ -384,7 +381,7 @@ class ImageEmbedderTest(parameterized.TestCase): def check_result(result: ImageEmbedderResult, output_image: _Image, timestamp_ms: int): # Checks cosine similarity. - self._check_cosine_similarity(result, crop_result, quantize=False, + self._check_cosine_similarity(result, crop_result, expected_similarity=0.999931) self.assertTrue( np.array_equal(output_image.numpy_view(), diff --git a/mediapipe/tasks/python/vision/image_embedder.py b/mediapipe/tasks/python/vision/image_embedder.py index bec9682d..e696ebdc 100644 --- a/mediapipe/tasks/python/vision/image_embedder.py +++ b/mediapipe/tasks/python/vision/image_embedder.py @@ -20,7 +20,6 @@ from mediapipe.python import packet_creator from mediapipe.python import packet_getter from mediapipe.python._framework_bindings import image as image_module from mediapipe.python._framework_bindings import packet as packet_module -from mediapipe.python._framework_bindings import task_runner as task_runner_module from mediapipe.tasks.cc.vision.image_embedder.proto import image_embedder_graph_options_pb2 from mediapipe.tasks.cc.components.containers.proto import embeddings_pb2 from mediapipe.tasks.python.components.processors import embedder_options @@ -40,7 +39,6 @@ _EmbedderOptions = embedder_options.EmbedderOptions _RunningMode = running_mode_module.VisionTaskRunningMode _TaskInfo = task_info_module.TaskInfo _ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions -_TaskRunner = task_runner_module.TaskRunner _EMBEDDINGS_OUT_STREAM_NAME = 'embeddings_out' _EMBEDDINGS_TAG = 'EMBEDDINGS' @@ -112,7 +110,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): `ImageEmbedderOptions`. Raises: - ValueError: If failed to create `ImageClassifier` object from the provided + ValueError: If failed to create `ImageEmbedder` object from the provided file such as invalid file path. RuntimeError: If other types of error occurred. """ @@ -185,7 +183,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): image_processing_options: Options for image processing. Returns: - A embedding result object that contains a list of embeddings. + An embedding result object that contains a list of embeddings. Raises: ValueError: If any of the input arguments is invalid. @@ -223,7 +221,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): image_processing_options: Options for image processing. Returns: - A embedding result object that contains a list of embeddings. + An embedding result object that contains a list of embeddings. Raises: ValueError: If any of the input arguments is invalid. @@ -265,7 +263,7 @@ class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): per input image. The `result_callback` provides: - - A embedding result object that contains a list of embeddings. + - An embedding result object that contains a list of embeddings. - The input image that the image embedder runs on. - The input timestamp in milliseconds. From f329e38dc17d751b29eac36cd387ba57e3acdb3f Mon Sep 17 00:00:00 2001 From: Jiuqiang Tang Date: Thu, 10 Nov 2022 22:10:41 -0800 Subject: [PATCH 11/21] Map the "com_github_glog_glog" dependency of "com_google_sentencepiece" to mediapipe's "com_github_glog_glog_no_gflags". PiperOrigin-RevId: 487727239 --- WORKSPACE | 2 +- mediapipe/calculators/tensor/BUILD | 2 ++ mediapipe/tasks/cc/text/text_classifier/BUILD | 1 + mediapipe/tasks/cc/text/text_embedder/BUILD | 1 + mediapipe/tasks/cc/text/tokenizers/BUILD | 2 ++ 5 files changed, 7 insertions(+), 1 deletion(-) diff --git a/WORKSPACE b/WORKSPACE index 046da997..702d1899 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -177,7 +177,7 @@ http_archive( "//third_party:com_google_sentencepiece_no_gflag_no_gtest.diff", ], patch_args = ["-p1"], - repo_mapping = {"@com_google_glog" : "@com_github_glog_glog"}, + repo_mapping = {"@com_google_glog" : "@com_github_glog_glog_no_gflags"}, ) http_archive( diff --git a/mediapipe/calculators/tensor/BUILD b/mediapipe/calculators/tensor/BUILD index 3385bcf4..3f127839 100644 --- a/mediapipe/calculators/tensor/BUILD +++ b/mediapipe/calculators/tensor/BUILD @@ -266,6 +266,7 @@ cc_test( "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings", + "@com_google_sentencepiece//src:sentencepiece_processor", ], ) @@ -321,6 +322,7 @@ cc_test( "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings", + "@com_google_sentencepiece//src:sentencepiece_processor", ], ) diff --git a/mediapipe/tasks/cc/text/text_classifier/BUILD b/mediapipe/tasks/cc/text/text_classifier/BUILD index b2e1bed2..52b0c0e4 100644 --- a/mediapipe/tasks/cc/text/text_classifier/BUILD +++ b/mediapipe/tasks/cc/text/text_classifier/BUILD @@ -85,6 +85,7 @@ cc_test( "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings", "@com_google_absl//absl/strings:cord", + "@com_google_sentencepiece//src:sentencepiece_processor", "@org_tensorflow//tensorflow/lite/core/shims:cc_shims_test_util", ], ) diff --git a/mediapipe/tasks/cc/text/text_embedder/BUILD b/mediapipe/tasks/cc/text/text_embedder/BUILD index 33190236..e2e16c9c 100644 --- a/mediapipe/tasks/cc/text/text_embedder/BUILD +++ b/mediapipe/tasks/cc/text/text_embedder/BUILD @@ -82,6 +82,7 @@ cc_test( "@com_google_absl//absl/flags:flag", "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", + "@com_google_sentencepiece//src:sentencepiece_processor", "@org_tensorflow//tensorflow/lite/core/shims:cc_shims_test_util", ], ) diff --git a/mediapipe/tasks/cc/text/tokenizers/BUILD b/mediapipe/tasks/cc/text/tokenizers/BUILD index 5ce08b2d..7f1ea284 100644 --- a/mediapipe/tasks/cc/text/tokenizers/BUILD +++ b/mediapipe/tasks/cc/text/tokenizers/BUILD @@ -83,6 +83,7 @@ cc_test( ":sentencepiece_tokenizer", "//mediapipe/framework/port:gtest_main", "//mediapipe/tasks/cc/core:utils", + "@com_google_sentencepiece//src:sentencepiece_processor", ], ) @@ -132,6 +133,7 @@ cc_test( "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings", "@com_google_absl//absl/strings:cord", + "@com_google_sentencepiece//src:sentencepiece_processor", ], ) From 185a57cec51886cd18747273f7fcefe59636a44c Mon Sep 17 00:00:00 2001 From: Mark McDonald Date: Thu, 10 Nov 2022 23:11:15 -0800 Subject: [PATCH 12/21] Support nested `mediapipe` dir in Java API doc builder. PiperOrigin-RevId: 487735796 --- docs/build_java_api_docs.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/build_java_api_docs.py b/docs/build_java_api_docs.py index 7b44e79f..e96e1fd8 100644 --- a/docs/build_java_api_docs.py +++ b/docs/build_java_api_docs.py @@ -45,6 +45,12 @@ def main(_) -> None: while (mp_root := mp_root.parent).name != 'mediapipe': # Find the nearest `mediapipe` dir. pass + + # Externally, parts of the repo are nested inside a mediapipe/ directory + # that does not exist internally. Support both. + if (mp_root / 'mediapipe').exists(): + mp_root = mp_root / 'mediapipe' + java_root = mp_root / 'tasks/java' gen_java.gen_java_docs( From b0583a1821e1a101976bfd90cded0e15e474b828 Mon Sep 17 00:00:00 2001 From: MediaPipe Team Date: Fri, 11 Nov 2022 11:04:28 -0800 Subject: [PATCH 13/21] Fixes SetAlphaCalculator silently failing to convert float inputs. PiperOrigin-RevId: 487868409 --- .../calculators/image/set_alpha_calculator.cc | 62 ++++++++++++++----- 1 file changed, 45 insertions(+), 17 deletions(-) diff --git a/mediapipe/calculators/image/set_alpha_calculator.cc b/mediapipe/calculators/image/set_alpha_calculator.cc index 04c3b2cf..f5ed703e 100644 --- a/mediapipe/calculators/image/set_alpha_calculator.cc +++ b/mediapipe/calculators/image/set_alpha_calculator.cc @@ -46,6 +46,40 @@ constexpr char kOutputFrameTagGpu[] = "IMAGE_GPU"; constexpr int kNumChannelsRGBA = 4; enum { ATTRIB_VERTEX, ATTRIB_TEXTURE_POSITION, NUM_ATTRIBUTES }; + +// Combines an RGB cv::Mat and a single-channel alpha cv::Mat of the same +// dimensions into an RGBA cv::Mat. Alpha may be read as uint8 or as another +// numeric type; in the latter case, it is upscaled to values between 0 and 255 +// from an assumed input range of [0, 1). RGB and RGBA Mat's must be uchar. +template +absl::Status MergeRGBA8Image(const cv::Mat input_mat, const cv::Mat& alpha_mat, + cv::Mat& output_mat) { + RET_CHECK_EQ(input_mat.rows, alpha_mat.rows); + RET_CHECK_EQ(input_mat.cols, alpha_mat.cols); + RET_CHECK_EQ(input_mat.rows, output_mat.rows); + RET_CHECK_EQ(input_mat.cols, output_mat.cols); + + for (int i = 0; i < output_mat.rows; ++i) { + const uchar* in_ptr = input_mat.ptr(i); + const AlphaType* alpha_ptr = alpha_mat.ptr(i); + uchar* out_ptr = output_mat.ptr(i); + for (int j = 0; j < output_mat.cols; ++j) { + const int out_idx = j * kNumChannelsRGBA; + const int in_idx = j * input_mat.channels(); + const int alpha_idx = j * alpha_mat.channels(); + out_ptr[out_idx + 0] = in_ptr[in_idx + 0]; + out_ptr[out_idx + 1] = in_ptr[in_idx + 1]; + out_ptr[out_idx + 2] = in_ptr[in_idx + 2]; + if constexpr (std::is_same::value) { + out_ptr[out_idx + 3] = alpha_ptr[alpha_idx + 0]; + } else { + const AlphaType alpha = alpha_ptr[alpha_idx + 0]; + out_ptr[out_idx + 3] = static_cast(round(alpha * 255.0f)); + } + } + } + return absl::OkStatus(); +} } // namespace // A calculator for setting the alpha channel of an RGBA image. @@ -250,28 +284,22 @@ absl::Status SetAlphaCalculator::RenderCpu(CalculatorContext* cc) { const bool has_alpha_mask = cc->Inputs().HasTag(kInputAlphaTag) && !cc->Inputs().Tag(kInputAlphaTag).IsEmpty(); - const bool use_alpa_mask = alpha_value_ < 0 && has_alpha_mask; + const bool use_alpha_mask = alpha_value_ < 0 && has_alpha_mask; // Setup alpha image and Update image in CPU. - if (use_alpa_mask) { + if (use_alpha_mask) { const auto& alpha_mask = cc->Inputs().Tag(kInputAlphaTag).Get(); cv::Mat alpha_mat = mediapipe::formats::MatView(&alpha_mask); - RET_CHECK_EQ(input_mat.rows, alpha_mat.rows); - RET_CHECK_EQ(input_mat.cols, alpha_mat.cols); - for (int i = 0; i < output_mat.rows; ++i) { - const uchar* in_ptr = input_mat.ptr(i); - uchar* alpha_ptr = alpha_mat.ptr(i); - uchar* out_ptr = output_mat.ptr(i); - for (int j = 0; j < output_mat.cols; ++j) { - const int out_idx = j * kNumChannelsRGBA; - const int in_idx = j * input_mat.channels(); - const int alpha_idx = j * alpha_mat.channels(); - out_ptr[out_idx + 0] = in_ptr[in_idx + 0]; - out_ptr[out_idx + 1] = in_ptr[in_idx + 1]; - out_ptr[out_idx + 2] = in_ptr[in_idx + 2]; - out_ptr[out_idx + 3] = alpha_ptr[alpha_idx + 0]; // channel 0 of mask - } + const bool alpha_is_float = alpha_mat.type() == CV_32FC1; + RET_CHECK(alpha_is_float || alpha_mat.type() == CV_8UC1); + + if (alpha_is_float) { + MP_RETURN_IF_ERROR( + MergeRGBA8Image(input_mat, alpha_mat, output_mat)); + } else { + MP_RETURN_IF_ERROR( + MergeRGBA8Image(input_mat, alpha_mat, output_mat)); } } else { const uchar alpha_value = std::min(std::max(0.0f, alpha_value_), 255.0f); From ce292c2a499c0d2492c7b78a8df7b9f7a6176ce6 Mon Sep 17 00:00:00 2001 From: Jiuqiang Tang Date: Fri, 11 Nov 2022 11:18:22 -0800 Subject: [PATCH 14/21] Fix a typo. PiperOrigin-RevId: 487872120 --- mediapipe/tasks/python/test/text/text_classifier_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mediapipe/tasks/python/test/text/text_classifier_test.py b/mediapipe/tasks/python/test/text/text_classifier_test.py index e864cc02..8678d219 100644 --- a/mediapipe/tasks/python/test/text/text_classifier_test.py +++ b/mediapipe/tasks/python/test/text/text_classifier_test.py @@ -125,7 +125,7 @@ class ModelFileType(enum.Enum): FILE_NAME = 2 -class ImageClassifierTest(parameterized.TestCase): +class TextClassifierTest(parameterized.TestCase): def setUp(self): super().setUp() From a83d87e157877b998cdbc3a59123f65559aae9c5 Mon Sep 17 00:00:00 2001 From: Hadon Nash Date: Fri, 11 Nov 2022 11:48:22 -0800 Subject: [PATCH 15/21] Internal change PiperOrigin-RevId: 487880137 --- .../core/flow_limiter_calculator_test.cc | 244 ++++++++++++------ 1 file changed, 165 insertions(+), 79 deletions(-) diff --git a/mediapipe/calculators/core/flow_limiter_calculator_test.cc b/mediapipe/calculators/core/flow_limiter_calculator_test.cc index 8a8cc965..45bace27 100644 --- a/mediapipe/calculators/core/flow_limiter_calculator_test.cc +++ b/mediapipe/calculators/core/flow_limiter_calculator_test.cc @@ -79,21 +79,25 @@ std::vector PacketValues(const std::vector& packets) { return result; } -template -std::vector MakePackets(std::vector> contents) { - std::vector result; - for (auto& entry : contents) { - result.push_back(MakePacket(entry.second).At(entry.first)); - } - return result; -} - std::string SourceString(Timestamp t) { return (t.IsSpecialValue()) ? t.DebugString() : absl::StrCat("Timestamp(", t.DebugString(), ")"); } +template +std::string SourceString(Packet packet) { + std::ostringstream oss; + if (packet.IsEmpty()) { + oss << "Packet()"; + } else { + oss << "MakePacket<" << MediaPipeTypeStringOrDemangled() << ">(" + << packet.Get() << ")"; + } + oss << ".At(" << SourceString(packet.Timestamp()) << ")"; + return oss.str(); +} + template class PacketsEqMatcher : public ::testing::MatcherInterface { @@ -123,8 +127,9 @@ class PacketsEqMatcher } for (auto i1 = c1.begin(), i2 = c2.begin(); i1 != c1.end(); ++i1, ++i2) { Packet p1 = *i1, p2 = *i2; - if (p1.Timestamp() != p2.Timestamp() || - p1.Get() != p2.Get()) { + if (p1.Timestamp() != p2.Timestamp() || p1.IsEmpty() != p2.IsEmpty() || + (!p1.IsEmpty() && + p1.Get() != p2.Get())) { return false; } } @@ -133,10 +138,9 @@ class PacketsEqMatcher void Print(const PacketContainer& packets, ::std::ostream* os) const { for (auto it = packets.begin(); it != packets.end(); ++it) { const Packet& packet = *it; - *os << (it == packets.begin() ? "{" : "") << "{" - << SourceString(packet.Timestamp()) << ", " - << packet.Get() << "}" - << (std::next(it) == packets.end() ? "}" : ", "); + *os << (it == packets.begin() ? "{" : ""); + *os << SourceString(packet); + *os << (std::next(it) == packets.end() ? "}" : ", "); } } @@ -144,7 +148,7 @@ class PacketsEqMatcher }; template -::testing::Matcher PackestEq( +::testing::Matcher PacketsEq( const PacketContainer& packets) { return MakeMatcher( new PacketsEqMatcher(packets)); @@ -739,8 +743,8 @@ TEST_F(FlowLimiterCalculatorTest, TwoInputStreams) { // The processing time "sleep_time" is reduced from 22ms to 12ms to create // the same frame rate as FlowLimiterCalculatorTest::TwoInputStreams. TEST_F(FlowLimiterCalculatorTest, ZeroQueue) { - auto BoolPackestEq = PackestEq, bool>; - auto IntPackestEq = PackestEq, int>; + auto BoolPacketsEq = PacketsEq, bool>; + auto IntPacketsEq = PacketsEq, int>; // Configure the test. SetUpInputData(); @@ -835,52 +839,86 @@ TEST_F(FlowLimiterCalculatorTest, ZeroQueue) { input_packets_[0], input_packets_[2], input_packets_[15], input_packets_[17], input_packets_[19], }; - EXPECT_THAT(out_1_packets_, IntPackestEq(expected_output)); + EXPECT_THAT(out_1_packets_, IntPacketsEq(expected_output)); // Exactly the timestamps released by FlowLimiterCalculator for in_1_sampled. std::vector expected_output_2 = { input_packets_[0], input_packets_[2], input_packets_[4], input_packets_[15], input_packets_[17], input_packets_[19], }; - EXPECT_THAT(out_2_packets, IntPackestEq(expected_output_2)); + EXPECT_THAT(out_2_packets, IntPacketsEq(expected_output_2)); // Validate the ALLOW stream output. - std::vector expected_allow = MakePackets( // - {{Timestamp(0), true}, {Timestamp(10000), false}, - {Timestamp(20000), true}, {Timestamp(30000), false}, - {Timestamp(40000), true}, {Timestamp(50000), false}, - {Timestamp(60000), false}, {Timestamp(70000), false}, - {Timestamp(80000), false}, {Timestamp(90000), false}, - {Timestamp(100000), false}, {Timestamp(110000), false}, - {Timestamp(120000), false}, {Timestamp(130000), false}, - {Timestamp(140000), false}, {Timestamp(150000), true}, - {Timestamp(160000), false}, {Timestamp(170000), true}, - {Timestamp(180000), false}, {Timestamp(190000), true}, - {Timestamp(200000), false}}); - EXPECT_THAT(allow_packets_, BoolPackestEq(expected_allow)); + std::vector expected_allow = { + MakePacket(true).At(Timestamp(0)), + MakePacket(false).At(Timestamp(10000)), + MakePacket(true).At(Timestamp(20000)), + MakePacket(false).At(Timestamp(30000)), + MakePacket(true).At(Timestamp(40000)), + MakePacket(false).At(Timestamp(50000)), + MakePacket(false).At(Timestamp(60000)), + MakePacket(false).At(Timestamp(70000)), + MakePacket(false).At(Timestamp(80000)), + MakePacket(false).At(Timestamp(90000)), + MakePacket(false).At(Timestamp(100000)), + MakePacket(false).At(Timestamp(110000)), + MakePacket(false).At(Timestamp(120000)), + MakePacket(false).At(Timestamp(130000)), + MakePacket(false).At(Timestamp(140000)), + MakePacket(true).At(Timestamp(150000)), + MakePacket(false).At(Timestamp(160000)), + MakePacket(true).At(Timestamp(170000)), + MakePacket(false).At(Timestamp(180000)), + MakePacket(true).At(Timestamp(190000)), + MakePacket(false).At(Timestamp(200000)), + }; + EXPECT_THAT(allow_packets_, BoolPacketsEq(expected_allow)); +} + +std::vector StripBoundsUpdates(const std::vector& packets, + Timestamp begin = Timestamp::Min(), + Timestamp end = Timestamp::Max()) { + std::vector result; + for (const auto& packet : packets) { + Timestamp ts = packet.Timestamp(); + if (packet.IsEmpty() && ts >= begin && ts < end) { + continue; + } + result.push_back(packet); + } + return result; } // Shows how FlowLimiterCalculator releases auxiliary input packets. // In this test, auxiliary input packets arrive at twice the primary rate. TEST_F(FlowLimiterCalculatorTest, AuxiliaryInputs) { - auto BoolPackestEq = PackestEq, bool>; - auto IntPackestEq = PackestEq, int>; + auto BoolPacketsEq = PacketsEq, bool>; + auto IntPacketsEq = PacketsEq, int>; // Configure the test. SetUpInputData(); SetUpSimulationClock(); CalculatorGraphConfig graph_config = ParseTextProtoOrDie(R"pb( - input_stream: 'in_1' - input_stream: 'in_2' + input_stream: 'input_1' + input_stream: 'auxiliary_input_2' + input_stream: 'auxiliary_input_3' node { calculator: 'FlowLimiterCalculator' - input_side_packet: 'OPTIONS:limiter_options' - input_stream: 'in_1' - input_stream: 'in_2' + options { + [mediapipe.FlowLimiterCalculatorOptions.ext] { + max_in_flight: 1 + max_in_queue: 0 + in_flight_timeout: 1000000 # 1s + } + } + input_stream: 'input_1' + input_stream: 'auxiliary_input_2' + input_stream: 'auxiliary_input_3' input_stream: 'FINISHED:out_1' input_stream_info: { tag_index: 'FINISHED' back_edge: true } - output_stream: 'in_1_sampled' - output_stream: 'in_2_sampled' + output_stream: 'input_1_sampled' + output_stream: 'auxiliary_input_2_sampled' + output_stream: 'auxiliary_input_3_sampled' output_stream: 'ALLOW:allow' } node { @@ -888,49 +926,75 @@ TEST_F(FlowLimiterCalculatorTest, AuxiliaryInputs) { input_side_packet: 'WARMUP_TIME:warmup_time' input_side_packet: 'SLEEP_TIME:sleep_time' input_side_packet: 'CLOCK:clock' - input_stream: 'PACKET:in_1_sampled' + input_stream: 'PACKET:input_1_sampled' output_stream: 'PACKET:out_1' } )pb"); - auto limiter_options = ParseTextProtoOrDie( - R"pb( - max_in_flight: 1 max_in_queue: 0 in_flight_timeout: 1000000 # 1s - )pb"); std::map side_packets = { - {"limiter_options", - MakePacket(limiter_options)}, + // Fake processing lazy initialization time in microseconds. {"warmup_time", MakePacket(22000)}, + // Fake processing duration in microseconds. {"sleep_time", MakePacket(22000)}, + // The SimulationClock to count virtual elapsed time. {"clock", MakePacket(clock_)}, }; // Start the graph. MP_ASSERT_OK(graph_.Initialize(graph_config)); - MP_EXPECT_OK(graph_.ObserveOutputStream("out_1", [this](Packet p) { - out_1_packets_.push_back(p); - return absl::OkStatus(); - })); - std::vector out_2_packets; - MP_EXPECT_OK(graph_.ObserveOutputStream("in_2_sampled", [&](Packet p) { - out_2_packets.push_back(p); - return absl::OkStatus(); - })); - MP_EXPECT_OK(graph_.ObserveOutputStream("allow", [this](Packet p) { - allow_packets_.push_back(p); - return absl::OkStatus(); - })); + MP_EXPECT_OK(graph_.ObserveOutputStream( + "out_1", + [this](Packet p) { + out_1_packets_.push_back(p); + return absl::OkStatus(); + }, + true)); + std::vector out_2_packets, out_3_packets; + MP_EXPECT_OK(graph_.ObserveOutputStream( + "auxiliary_input_2_sampled", + [&](Packet p) { + out_2_packets.push_back(p); + return absl::OkStatus(); + }, + true)); + MP_EXPECT_OK(graph_.ObserveOutputStream( + "auxiliary_input_3_sampled", + [&](Packet p) { + out_3_packets.push_back(p); + return absl::OkStatus(); + }, + true)); + MP_EXPECT_OK(graph_.ObserveOutputStream( + "allow", + [this](Packet p) { + allow_packets_.push_back(p); + return absl::OkStatus(); + }, + true)); simulation_clock_->ThreadStart(); MP_ASSERT_OK(graph_.StartRun(side_packets)); - // Add packets 2,4,6,8 to stream in_1 and 1..9 to stream in_2. - clock_->Sleep(absl::Microseconds(10000)); + // Add packets 1..9 to auxiliary_input_3, early. + for (int i = 1; i < 10; ++i) { + MP_EXPECT_OK(graph_.AddPacketToInputStream( + "auxiliary_input_3", MakePacket(i).At(Timestamp(i * 10000)))); + } + + // The total count of out_2_packets after each input packet. + // std::vector sizes_2 = {0, 0, 2, 2, 3, 3, 4, 4, 5, 5}; + std::vector sizes_2 = {0, 1, 3, 4, 6, 7, 9, 10, 12, 13}; + + // Add packets 2,4,6,8 to stream input_1. + // Add packets 1..9 to auxiliary_input_2. for (int i = 1; i < 10; ++i) { if (i % 2 == 0) { - MP_EXPECT_OK(graph_.AddPacketToInputStream("in_1", input_packets_[i])); + MP_EXPECT_OK(graph_.AddPacketToInputStream( + "input_1", MakePacket(i).At(Timestamp(i * 10000)))); } - MP_EXPECT_OK(graph_.AddPacketToInputStream("in_2", input_packets_[i])); + MP_EXPECT_OK(graph_.AddPacketToInputStream( + "auxiliary_input_2", MakePacket(i).At(Timestamp(i * 10000)))); clock_->Sleep(absl::Microseconds(10000)); + EXPECT_EQ(out_2_packets.size(), sizes_2[i]); } // Finish the graph run. @@ -942,24 +1006,46 @@ TEST_F(FlowLimiterCalculatorTest, AuxiliaryInputs) { // Validate the output. // Input packets 4 and 8 are dropped due to max_in_flight. std::vector expected_output = { - input_packets_[2], - input_packets_[6], + MakePacket(2).At(Timestamp(20000)), + Packet().At(Timestamp(40000)), + MakePacket(6).At(Timestamp(60000)), + Packet().At(Timestamp(80000)), }; - EXPECT_THAT(out_1_packets_, IntPackestEq(expected_output)); + EXPECT_THAT(out_1_packets_, IntPacketsEq(expected_output)); + // Packets following input packets 2 and 6, and not input packets 4 and 8. - std::vector expected_output_2 = { - input_packets_[1], input_packets_[2], input_packets_[3], - input_packets_[6], input_packets_[7], + std::vector expected_auxiliary_output = { + Packet().At(Timestamp(9999)), + MakePacket(1).At(Timestamp(10000)), + MakePacket(2).At(Timestamp(20000)), + Packet().At(Timestamp(29999)), + MakePacket(3).At(Timestamp(30000)), + Packet().At(Timestamp(40000)), + Packet().At(Timestamp(49999)), + Packet().At(Timestamp(50000)), + MakePacket(6).At(Timestamp(60000)), + Packet().At(Timestamp(69999)), + MakePacket(7).At(Timestamp(70000)), + Packet().At(Timestamp(80000)), + Packet().At(Timestamp(89999)), }; - EXPECT_THAT(out_2_packets, IntPackestEq(expected_output_2)); + std::vector actual_2 = + StripBoundsUpdates(out_2_packets, Timestamp(90000)); + EXPECT_THAT(actual_2, IntPacketsEq(expected_auxiliary_output)); + std::vector expected_3 = + StripBoundsUpdates(expected_auxiliary_output, Timestamp(39999)); + std::vector actual_3 = + StripBoundsUpdates(out_3_packets, Timestamp(39999)); + EXPECT_THAT(actual_3, IntPacketsEq(expected_3)); // Validate the ALLOW stream output. - std::vector expected_allow = - MakePackets({{Timestamp(20000), 1}, - {Timestamp(40000), 0}, - {Timestamp(60000), 1}, - {Timestamp(80000), 0}}); - EXPECT_THAT(allow_packets_, BoolPackestEq(expected_allow)); + std::vector expected_allow = { + MakePacket(true).At(Timestamp(20000)), + MakePacket(false).At(Timestamp(40000)), + MakePacket(true).At(Timestamp(60000)), + MakePacket(false).At(Timestamp(80000)), + }; + EXPECT_THAT(allow_packets_, BoolPacketsEq(expected_allow)); } } // anonymous namespace From 340d7651af8caca795220b81124b2a3e557f4784 Mon Sep 17 00:00:00 2001 From: MediaPipe Team Date: Fri, 11 Nov 2022 11:52:11 -0800 Subject: [PATCH 16/21] Internal change PiperOrigin-RevId: 487881149 --- mediapipe/calculators/tensorflow/BUILD | 1 + ...flow_session_from_saved_model_generator.cc | 22 +++++++++- ...session_from_saved_model_generator_test.cc | 44 +++++++++++++++++++ 3 files changed, 65 insertions(+), 2 deletions(-) diff --git a/mediapipe/calculators/tensorflow/BUILD b/mediapipe/calculators/tensorflow/BUILD index 4037d89c..d0dfc12a 100644 --- a/mediapipe/calculators/tensorflow/BUILD +++ b/mediapipe/calculators/tensorflow/BUILD @@ -613,6 +613,7 @@ cc_library( deps = [ ":tensorflow_session", ":tensorflow_session_from_saved_model_generator_cc_proto", + "@com_google_absl//absl/status", "//mediapipe/framework:packet_generator", "//mediapipe/framework:packet_type", "//mediapipe/framework/tool:status_util", diff --git a/mediapipe/calculators/tensorflow/tensorflow_session_from_saved_model_generator.cc b/mediapipe/calculators/tensorflow/tensorflow_session_from_saved_model_generator.cc index 97c67592..d5236f1c 100644 --- a/mediapipe/calculators/tensorflow/tensorflow_session_from_saved_model_generator.cc +++ b/mediapipe/calculators/tensorflow/tensorflow_session_from_saved_model_generator.cc @@ -14,6 +14,8 @@ #include +#include "absl/status/status.h" + #if !defined(__ANDROID__) #include "mediapipe/framework/port/file_helpers.h" #endif @@ -38,6 +40,8 @@ constexpr char kSessionTag[] = "SESSION"; static constexpr char kStringSavedModelPath[] = "STRING_SAVED_MODEL_PATH"; +static constexpr char kStringSignatureName[] = "STRING_SIGNATURE_NAME"; + // Given the path to a directory containing multiple tensorflow saved models // in subdirectories, replaces path with the alphabetically last subdirectory. absl::Status GetLatestDirectory(std::string* path) { @@ -104,6 +108,10 @@ class TensorFlowSessionFromSavedModelGenerator : public PacketGenerator { if (input_side_packets->HasTag(kStringSavedModelPath)) { input_side_packets->Tag(kStringSavedModelPath).Set(); } + // Set Signature_def. + if (input_side_packets->HasTag(kStringSignatureName)) { + input_side_packets->Tag(kStringSignatureName).Set(); + } // A TensorFlow model loaded and ready for use along with tensor output_side_packets->Tag(kSessionTag).Set(); return absl::OkStatus(); @@ -146,9 +154,19 @@ class TensorFlowSessionFromSavedModelGenerator : public PacketGenerator { auto session = absl::make_unique(); session->session = std::move(saved_model->session); - RET_CHECK(!options.signature_name().empty()); + // Use input side packet to overwrite signature name in options. + std::string signature_name = + input_side_packets.HasTag(kStringSignatureName) + ? input_side_packets.Tag(kStringSignatureName).Get() + : options.signature_name(); + RET_CHECK(!signature_name.empty()); const auto& signature_def_map = saved_model->meta_graph_def.signature_def(); - const auto& signature_def = signature_def_map.at(options.signature_name()); + if (signature_def_map.find(signature_name) == signature_def_map.end()) { + return absl::NotFoundError(absl::StrFormat( + "Signature name '%s' does not exist in the loaded signature def", + signature_name)); + } + const auto& signature_def = signature_def_map.at(signature_name); for (const auto& input_signature : signature_def.inputs()) { session->tag_to_tensor_map[MaybeConvertSignatureToTag( input_signature.first, options)] = input_signature.second.name(); diff --git a/mediapipe/calculators/tensorflow/tensorflow_session_from_saved_model_generator_test.cc b/mediapipe/calculators/tensorflow/tensorflow_session_from_saved_model_generator_test.cc index 5c6de3e8..c002b1bd 100644 --- a/mediapipe/calculators/tensorflow/tensorflow_session_from_saved_model_generator_test.cc +++ b/mediapipe/calculators/tensorflow/tensorflow_session_from_saved_model_generator_test.cc @@ -30,11 +30,13 @@ namespace mediapipe { +using ::testing::status::StatusIs; namespace { namespace tf = ::tensorflow; constexpr char kStringSavedModelPathTag[] = "STRING_SAVED_MODEL_PATH"; +constexpr char kStringSignatureNameTag[] = "STRING_SIGNATURE_NAME"; constexpr char kSessionTag[] = "SESSION"; std::string GetSavedModelDir() { @@ -124,6 +126,48 @@ TEST_F(TensorFlowSessionFromSavedModelGeneratorTest, ASSERT_NE(session.session, nullptr); } +TEST_F(TensorFlowSessionFromSavedModelGeneratorTest, + CreateSessionFromSidePacketWithCorrectSignatureName) { + generator_options_->clear_saved_model_path(); + PacketSet input_side_packets( + tool::CreateTagMap({"STRING_SAVED_MODEL_PATH:saved_model_dir", + "STRING_SIGNATURE_NAME:signature_name"}) + .value()); + input_side_packets.Tag(kStringSavedModelPathTag) = + Adopt(new std::string(GetSavedModelDir())); + input_side_packets.Tag(kStringSignatureNameTag) = + Adopt(new std::string("serving_default")); + PacketSet output_side_packets( + tool::CreateTagMap({"SESSION:session"}).value()); + absl::Status run_status = tool::RunGenerateAndValidateTypes( + "TensorFlowSessionFromSavedModelGenerator", extendable_options_, + input_side_packets, &output_side_packets); + MP_EXPECT_OK(run_status) << run_status.message(); + const TensorFlowSession& session = + output_side_packets.Tag(kSessionTag).Get(); + // Session must be set. + ASSERT_NE(session.session, nullptr); +} + +TEST_F(TensorFlowSessionFromSavedModelGeneratorTest, + CreateSessionFromSidePacketWithWrongSignatureName) { + generator_options_->clear_saved_model_path(); + PacketSet input_side_packets( + tool::CreateTagMap({"STRING_SAVED_MODEL_PATH:saved_model_dir", + "STRING_SIGNATURE_NAME:signature_name"}) + .value()); + input_side_packets.Tag(kStringSavedModelPathTag) = + Adopt(new std::string(GetSavedModelDir())); + input_side_packets.Tag(kStringSignatureNameTag) = + Adopt(new std::string("wrong_signature_name")); + PacketSet output_side_packets( + tool::CreateTagMap({"SESSION:session"}).value()); + absl::Status run_status = tool::RunGenerateAndValidateTypes( + "TensorFlowSessionFromSavedModelGenerator", extendable_options_, + input_side_packets, &output_side_packets); + EXPECT_THAT(run_status, StatusIs(absl::StatusCode::kNotFound)); +} + // Integration test. Verifies that TensorFlowInferenceCalculator correctly // consumes the Packet emitted by this factory. TEST_F(TensorFlowSessionFromSavedModelGeneratorTest, From 20a6f15f182eec372202812d3a737ba4616d72d1 Mon Sep 17 00:00:00 2001 From: Sebastian Schmidt Date: Fri, 11 Nov 2022 13:20:42 -0800 Subject: [PATCH 17/21] Improvements to NPM package PiperOrigin-RevId: 487901715 --- mediapipe/tasks/web/package.json | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/mediapipe/tasks/web/package.json b/mediapipe/tasks/web/package.json index 7726f1cb..d7d484ca 100644 --- a/mediapipe/tasks/web/package.json +++ b/mediapipe/tasks/web/package.json @@ -2,16 +2,15 @@ "name": "@mediapipe/tasks-__NAME__", "version": "__VERSION__", "description": "__DESCRIPTION__", - "main": "__NAME__bundle.js", - "module": "__NAME__bundle.js", + "main": "__NAME___bundle.js", + "module": "__NAME___bundle.js", "exports": { - ".": "./__NAME__bundle.js", - "./loader": "./wasm/__NAME__wasm_internal.js", - "./wasm": "./wasm/__NAME__wasm_internal.wasm" + ".": "./__NAME___bundle.js", + "./loader": "./wasm/__NAME___wasm_internal.js", + "./wasm": "./wasm/__NAME___wasm_internal.wasm" }, "author": "mediapipe@google.com", "license": "Apache-2.0", - "type": "module", "dependencies": { "google-protobuf": "^3.21.2" }, From c7030ac7fa9352deb59b6cac40708e4abaf427ca Mon Sep 17 00:00:00 2001 From: Sebastian Schmidt Date: Fri, 11 Nov 2022 13:23:12 -0800 Subject: [PATCH 18/21] Use CommonJS for NPM package PiperOrigin-RevId: 487902199 --- mediapipe/tasks/web/BUILD | 3 +++ 1 file changed, 3 insertions(+) diff --git a/mediapipe/tasks/web/BUILD b/mediapipe/tasks/web/BUILD index 8fe5f7fd..2c0ea57e 100644 --- a/mediapipe/tasks/web/BUILD +++ b/mediapipe/tasks/web/BUILD @@ -31,6 +31,7 @@ rollup_bundle( name = "audio_bundle", config_file = "rollup.config.mjs", entry_point = "audio.ts", + format = "cjs", output_dir = False, deps = [ ":audio_lib", @@ -67,6 +68,7 @@ rollup_bundle( name = "text_bundle", config_file = "rollup.config.mjs", entry_point = "text.ts", + format = "cjs", output_dir = False, deps = [ ":text_lib", @@ -103,6 +105,7 @@ rollup_bundle( name = "vision_bundle", config_file = "rollup.config.mjs", entry_point = "vision.ts", + format = "cjs", output_dir = False, deps = [ ":vision_lib", From 8ec83d2aa0f0bfe888b169ddf860291bb7bd6d07 Mon Sep 17 00:00:00 2001 From: MediaPipe Team Date: Fri, 11 Nov 2022 15:48:24 -0800 Subject: [PATCH 19/21] Clarify AssetManager usage PiperOrigin-RevId: 487935478 --- mediapipe/util/android/asset_manager_util.h | 22 ++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/mediapipe/util/android/asset_manager_util.h b/mediapipe/util/android/asset_manager_util.h index 2d2582c2..5c963f92 100644 --- a/mediapipe/util/android/asset_manager_util.h +++ b/mediapipe/util/android/asset_manager_util.h @@ -32,17 +32,23 @@ namespace mediapipe { // Thin wrapper over AAssetManager provided by JNI. This class is meant to be // used as a singleton. -// Usage: Call InitializeFromActivity from a JNI function that has access to the -// Java activity in the Android application. This initializes the asset manager -// and now files bundled in the assets folder can be read using ReadFile(). +// +// Usage: Call one of Initialize* functions from a JNI function that has access +// to a context/activity/etc. This initializes the asset manager and now files +// bundled in the assets folder can be read using ReadFile(). +// +// NOTE: initialization should happen strictly once and guaranteed to complete +// before any possible use, otherwise it cannot be used safely across multiple +// threads. class AssetManager { public: AssetManager(const AssetManager&) = delete; AssetManager& operator=(const AssetManager&) = delete; - // Returns the asset manager if it has been set by a call to - // InitializeFromActivity, otherwise returns nullptr. + // Returns the asset manager if it has been set by one of Initialize* + // functions, otherwise returns nullptr. AAssetManager* GetAssetManager(); + // Returns true if AAssetManager was successfully initialized. bool InitializeFromAssetManager(JNIEnv* env, jobject local_asset_manager, const std::string& cache_dir_path); @@ -55,7 +61,7 @@ class AssetManager { const std::string& cache_dir_path); // Returns true if AAssetManager was successfully initialized. - ABSL_DEPRECATED("Use InitializeFromActivity instead.") + ABSL_DEPRECATED("Use one of alternate Initialize* functions instead.") bool InitializeFromAssetManager(JNIEnv* env, jobject local_asset_manager); // Returns true if AAssetManager was successfully initialized. @@ -79,12 +85,14 @@ class AssetManager { std::string* output); // Returns the path to the Android cache directory. Will be empty if - // InitializeFromActivity has not been called. + // AssetManager hasn't been initialized. const std::string& GetCacheDirPath(); // Caches the contents of the given asset as a file, and returns a path to // that file. This can be used to pass an asset to APIs that require a path // to a filesystem file. + // NOTE: this is _not_ thread-safe, e.g. if two threads are requesting the + // same file absl::StatusOr CachedFileFromAsset( const std::string& asset_path); From c2ac040a6c3cd502ab1a5c65018bb0d029e0470d Mon Sep 17 00:00:00 2001 From: MediaPipe Team Date: Fri, 11 Nov 2022 16:50:38 -0800 Subject: [PATCH 20/21] Adds a public import API for `TextClassifier`. PiperOrigin-RevId: 487949023 --- .../python/text/text_classifier/BUILD | 26 ++++---- .../python/text/text_classifier/__init__.py | 18 ++++++ .../text/text_classifier/model_options.py | 10 ++-- .../python/text/text_classifier/model_spec.py | 4 +- .../text/text_classifier/model_spec_test.py | 8 +-- .../text/text_classifier/text_classifier.py | 10 ++-- .../text_classifier/text_classifier_demo.py | 32 +++++----- .../text_classifier/text_classifier_test.py | 60 ++++++++++--------- 8 files changed, 97 insertions(+), 71 deletions(-) diff --git a/mediapipe/model_maker/python/text/text_classifier/BUILD b/mediapipe/model_maker/python/text/text_classifier/BUILD index 35726367..0c35e796 100644 --- a/mediapipe/model_maker/python/text/text_classifier/BUILD +++ b/mediapipe/model_maker/python/text/text_classifier/BUILD @@ -21,6 +21,19 @@ package( licenses(["notice"]) +py_library( + name = "text_classifier_import", + srcs = ["__init__.py"], + deps = [ + ":dataset", + ":model_options", + ":model_spec", + ":text_classifier", + ":text_classifier_options", + "//mediapipe/model_maker/python/core:hyperparameters", + ], +) + py_library( name = "model_options", srcs = ["model_options.py"], @@ -114,12 +127,7 @@ py_test( ], tags = ["requires-net:external"], deps = [ - ":dataset", - ":model_options", - ":model_spec", - ":text_classifier", - ":text_classifier_options", - "//mediapipe/model_maker/python/core:hyperparameters", + ":text_classifier_import", "//mediapipe/tasks/python/test:test_utils", ], ) @@ -128,11 +136,7 @@ py_library( name = "text_classifier_demo_lib", srcs = ["text_classifier_demo.py"], deps = [ - ":dataset", - ":model_spec", - ":text_classifier", - ":text_classifier_options", - "//mediapipe/model_maker/python/core:hyperparameters", + ":text_classifier_import", "//mediapipe/model_maker/python/core/utils:quantization", ], ) diff --git a/mediapipe/model_maker/python/text/text_classifier/__init__.py b/mediapipe/model_maker/python/text/text_classifier/__init__.py index 7ca2f921..5f34fe86 100644 --- a/mediapipe/model_maker/python/text/text_classifier/__init__.py +++ b/mediapipe/model_maker/python/text/text_classifier/__init__.py @@ -11,3 +11,21 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""MediaPipe Public Python API for Text Classifier.""" + +from mediapipe.model_maker.python.core import hyperparameters +from mediapipe.model_maker.python.text.text_classifier import dataset +from mediapipe.model_maker.python.text.text_classifier import model_options +from mediapipe.model_maker.python.text.text_classifier import model_spec +from mediapipe.model_maker.python.text.text_classifier import text_classifier +from mediapipe.model_maker.python.text.text_classifier import text_classifier_options + +HParams = hyperparameters.BaseHParams +CSVParams = dataset.CSVParameters +Dataset = dataset.Dataset +AverageWordEmbeddingClassifierModelOptions = ( + model_options.AverageWordEmbeddingClassifierModelOptions) +BertClassifierModelOptions = model_options.BertClassifierModelOptions +SupportedModels = model_spec.SupportedModels +TextClassifier = text_classifier.TextClassifier +TextClassifierOptions = text_classifier_options.TextClassifierOptions diff --git a/mediapipe/model_maker/python/text/text_classifier/model_options.py b/mediapipe/model_maker/python/text/text_classifier/model_options.py index b48e38da..3dfce316 100644 --- a/mediapipe/model_maker/python/text/text_classifier/model_options.py +++ b/mediapipe/model_maker/python/text/text_classifier/model_options.py @@ -18,12 +18,12 @@ from typing import Union from mediapipe.model_maker.python.text.core import bert_model_options -# BERT text classifier options inherited from BertModelOptions. -BertClassifierOptions = bert_model_options.BertModelOptions +# BERT text classifier model options inherited from BertModelOptions. +BertClassifierModelOptions = bert_model_options.BertModelOptions @dataclasses.dataclass -class AverageWordEmbeddingClassifierOptions: +class AverageWordEmbeddingClassifierModelOptions: """Configurable model options for an Average Word Embedding classifier. Attributes: @@ -41,5 +41,5 @@ class AverageWordEmbeddingClassifierOptions: dropout_rate: float = 0.2 -TextClassifierModelOptions = Union[AverageWordEmbeddingClassifierOptions, - BertClassifierOptions] +TextClassifierModelOptions = Union[AverageWordEmbeddingClassifierModelOptions, + BertClassifierModelOptions] diff --git a/mediapipe/model_maker/python/text/text_classifier/model_spec.py b/mediapipe/model_maker/python/text/text_classifier/model_spec.py index c2694786..1e215c52 100644 --- a/mediapipe/model_maker/python/text/text_classifier/model_spec.py +++ b/mediapipe/model_maker/python/text/text_classifier/model_spec.py @@ -38,8 +38,8 @@ class AverageWordEmbeddingClassifierSpec: # `learning_rate` is unused for the average word embedding model hparams: hp.BaseHParams = hp.BaseHParams( epochs=10, batch_size=32, learning_rate=0) - model_options: mo.AverageWordEmbeddingClassifierOptions = ( - mo.AverageWordEmbeddingClassifierOptions()) + model_options: mo.AverageWordEmbeddingClassifierModelOptions = ( + mo.AverageWordEmbeddingClassifierModelOptions()) name: str = 'AverageWordEmbedding' diff --git a/mediapipe/model_maker/python/text/text_classifier/model_spec_test.py b/mediapipe/model_maker/python/text/text_classifier/model_spec_test.py index 118b84fd..6cd5408b 100644 --- a/mediapipe/model_maker/python/text/text_classifier/model_spec_test.py +++ b/mediapipe/model_maker/python/text/text_classifier/model_spec_test.py @@ -40,7 +40,7 @@ class ModelSpecTest(tf.test.TestCase): }) self.assertEqual( model_spec_obj.model_options, - classifier_model_options.BertClassifierOptions( + classifier_model_options.BertClassifierModelOptions( seq_len=128, do_fine_tuning=True, dropout_rate=0.1)) self.assertEqual( model_spec_obj.hparams, @@ -57,7 +57,7 @@ class ModelSpecTest(tf.test.TestCase): self.assertEqual(model_spec_obj.name, 'AverageWordEmbedding') self.assertEqual( model_spec_obj.model_options, - classifier_model_options.AverageWordEmbeddingClassifierOptions( + classifier_model_options.AverageWordEmbeddingClassifierModelOptions( seq_len=256, wordvec_dim=16, do_lower_case=True, @@ -77,7 +77,7 @@ class ModelSpecTest(tf.test.TestCase): def test_custom_bert_spec(self): custom_bert_classifier_options = ( - classifier_model_options.BertClassifierOptions( + classifier_model_options.BertClassifierModelOptions( seq_len=512, do_fine_tuning=False, dropout_rate=0.3)) model_spec_obj = ( ms.SupportedModels.MOBILEBERT_CLASSIFIER.value( @@ -97,7 +97,7 @@ class ModelSpecTest(tf.test.TestCase): num_gpus=3, tpu='tpu/address') custom_average_word_embedding_model_options = ( - classifier_model_options.AverageWordEmbeddingClassifierOptions( + classifier_model_options.AverageWordEmbeddingClassifierModelOptions( seq_len=512, wordvec_dim=32, do_lower_case=False, diff --git a/mediapipe/model_maker/python/text/text_classifier/text_classifier.py b/mediapipe/model_maker/python/text/text_classifier/text_classifier.py index 919277b8..a6ad9ab5 100644 --- a/mediapipe/model_maker/python/text/text_classifier/text_classifier.py +++ b/mediapipe/model_maker/python/text/text_classifier/text_classifier.py @@ -51,12 +51,12 @@ def _validate(options: text_classifier_options.TextClassifierOptions): return if (isinstance(options.model_options, - mo.AverageWordEmbeddingClassifierOptions) and + mo.AverageWordEmbeddingClassifierModelOptions) and (options.supported_model != ms.SupportedModels.AVERAGE_WORD_EMBEDDING_CLASSIFIER)): raise ValueError("Expected AVERAGE_WORD_EMBEDDING_CLASSIFIER," f" got {options.supported_model}") - if (isinstance(options.model_options, mo.BertClassifierOptions) and + if (isinstance(options.model_options, mo.BertClassifierModelOptions) and (options.supported_model != ms.SupportedModels.MOBILEBERT_CLASSIFIER)): raise ValueError( f"Expected MOBILEBERT_CLASSIFIER, got {options.supported_model}") @@ -194,7 +194,7 @@ class _AverageWordEmbeddingClassifier(TextClassifier): _DELIM_REGEX_PATTERN = r"[^\w\']+" def __init__(self, model_spec: ms.AverageWordEmbeddingClassifierSpec, - model_options: mo.AverageWordEmbeddingClassifierOptions, + model_options: mo.AverageWordEmbeddingClassifierModelOptions, hparams: hp.BaseHParams, label_names: Sequence[str]): super().__init__(model_spec, hparams, label_names) self._model_options = model_options @@ -304,8 +304,8 @@ class _BertClassifier(TextClassifier): _INITIALIZER_RANGE = 0.02 def __init__(self, model_spec: ms.BertClassifierSpec, - model_options: mo.BertClassifierOptions, hparams: hp.BaseHParams, - label_names: Sequence[str]): + model_options: mo.BertClassifierModelOptions, + hparams: hp.BaseHParams, label_names: Sequence[str]): super().__init__(model_spec, hparams, label_names) self._model_options = model_options self._loss_function = tf.keras.losses.SparseCategoricalCrossentropy() diff --git a/mediapipe/model_maker/python/text/text_classifier/text_classifier_demo.py b/mediapipe/model_maker/python/text/text_classifier/text_classifier_demo.py index de6b8575..08f4c2ad 100644 --- a/mediapipe/model_maker/python/text/text_classifier/text_classifier_demo.py +++ b/mediapipe/model_maker/python/text/text_classifier/text_classifier_demo.py @@ -23,12 +23,8 @@ from absl import flags from absl import logging import tensorflow as tf -from mediapipe.model_maker.python.core import hyperparameters as hp from mediapipe.model_maker.python.core.utils import quantization -from mediapipe.model_maker.python.text.text_classifier import dataset as text_ds -from mediapipe.model_maker.python.text.text_classifier import model_spec as ms -from mediapipe.model_maker.python.text.text_classifier import text_classifier -from mediapipe.model_maker.python.text.text_classifier import text_classifier_options +from mediapipe.model_maker.python.text import text_classifier FLAGS = flags.FLAGS @@ -53,31 +49,34 @@ def download_demo_data(): def run(data_dir, export_dir=tempfile.mkdtemp(), - supported_model=ms.SupportedModels.AVERAGE_WORD_EMBEDDING_CLASSIFIER): + supported_model=( + text_classifier.SupportedModels.AVERAGE_WORD_EMBEDDING_CLASSIFIER)): """Runs demo.""" # Gets training data and validation data. - csv_params = text_ds.CSVParameters( + csv_params = text_classifier.CSVParams( text_column='sentence', label_column='label', delimiter='\t') - train_data = text_ds.Dataset.from_csv( + train_data = text_classifier.Dataset.from_csv( filename=os.path.join(os.path.join(data_dir, 'train.tsv')), csv_params=csv_params) - validation_data = text_ds.Dataset.from_csv( + validation_data = text_classifier.Dataset.from_csv( filename=os.path.join(os.path.join(data_dir, 'dev.tsv')), csv_params=csv_params) quantization_config = None - if supported_model == ms.SupportedModels.AVERAGE_WORD_EMBEDDING_CLASSIFIER: - hparams = hp.BaseHParams( + if (supported_model == + text_classifier.SupportedModels.AVERAGE_WORD_EMBEDDING_CLASSIFIER): + hparams = text_classifier.HParams( epochs=10, batch_size=32, learning_rate=0, export_dir=export_dir) # Warning: This takes extremely long to run on CPU - elif supported_model == ms.SupportedModels.MOBILEBERT_CLASSIFIER: + elif ( + supported_model == text_classifier.SupportedModels.MOBILEBERT_CLASSIFIER): quantization_config = quantization.QuantizationConfig.for_dynamic() - hparams = hp.BaseHParams( + hparams = text_classifier.HParams( epochs=3, batch_size=48, learning_rate=3e-5, export_dir=export_dir) # Fine-tunes the model. - options = text_classifier_options.TextClassifierOptions( + options = text_classifier.TextClassifierOptions( supported_model=supported_model, hparams=hparams) model = text_classifier.TextClassifier.create(train_data, validation_data, options) @@ -96,9 +95,10 @@ def main(_): export_dir = os.path.expanduser(FLAGS.export_dir) if FLAGS.supported_model == 'average_word_embedding': - supported_model = ms.SupportedModels.AVERAGE_WORD_EMBEDDING_CLASSIFIER + supported_model = ( + text_classifier.SupportedModels.AVERAGE_WORD_EMBEDDING_CLASSIFIER) elif FLAGS.supported_model == 'bert': - supported_model = ms.SupportedModels.MOBILEBERT_CLASSIFIER + supported_model = text_classifier.SupportedModels.MOBILEBERT_CLASSIFIER run(data_dir, export_dir, supported_model) diff --git a/mediapipe/model_maker/python/text/text_classifier/text_classifier_test.py b/mediapipe/model_maker/python/text/text_classifier/text_classifier_test.py index 41dbb464..55ffd6a7 100644 --- a/mediapipe/model_maker/python/text/text_classifier/text_classifier_test.py +++ b/mediapipe/model_maker/python/text/text_classifier/text_classifier_test.py @@ -18,12 +18,7 @@ import os import tensorflow as tf -from mediapipe.model_maker.python.core import hyperparameters as hp -from mediapipe.model_maker.python.text.text_classifier import dataset -from mediapipe.model_maker.python.text.text_classifier import model_options as mo -from mediapipe.model_maker.python.text.text_classifier import model_spec as ms -from mediapipe.model_maker.python.text.text_classifier import text_classifier -from mediapipe.model_maker.python.text.text_classifier import text_classifier_options +from mediapipe.model_maker.python.text import text_classifier from mediapipe.tasks.python.test import test_utils @@ -43,18 +38,23 @@ class TextClassifierTest(tf.test.TestCase): writer.writeheader() for label, text in labels_and_text: writer.writerow({'text': text, 'label': label}) - csv_params = dataset.CSVParameters(text_column='text', label_column='label') - all_data = dataset.Dataset.from_csv( + csv_params = text_classifier.CSVParams( + text_column='text', label_column='label') + all_data = text_classifier.Dataset.from_csv( filename=csv_file, csv_params=csv_params) return all_data.split(0.5) def test_create_and_train_average_word_embedding_model(self): train_data, validation_data = self._get_data() - options = text_classifier_options.TextClassifierOptions( - supported_model=ms.SupportedModels.AVERAGE_WORD_EMBEDDING_CLASSIFIER, - hparams=hp.BaseHParams(epochs=1, batch_size=1, learning_rate=0)) - average_word_embedding_classifier = text_classifier.TextClassifier.create( - train_data, validation_data, options) + options = ( + text_classifier.TextClassifierOptions( + supported_model=(text_classifier.SupportedModels + .AVERAGE_WORD_EMBEDDING_CLASSIFIER), + hparams=text_classifier.HParams( + epochs=1, batch_size=1, learning_rate=0))) + average_word_embedding_classifier = ( + text_classifier.TextClassifier.create(train_data, validation_data, + options)) _, accuracy = average_word_embedding_classifier.evaluate(validation_data) self.assertGreaterEqual(accuracy, 0.0) @@ -77,10 +77,11 @@ class TextClassifierTest(tf.test.TestCase): def test_create_and_train_bert(self): train_data, validation_data = self._get_data() - options = text_classifier_options.TextClassifierOptions( - supported_model=ms.SupportedModels.MOBILEBERT_CLASSIFIER, - model_options=mo.BertClassifierOptions(do_fine_tuning=False, seq_len=2), - hparams=hp.BaseHParams( + options = text_classifier.TextClassifierOptions( + supported_model=text_classifier.SupportedModels.MOBILEBERT_CLASSIFIER, + model_options=text_classifier.BertClassifierModelOptions( + do_fine_tuning=False, seq_len=2), + hparams=text_classifier.HParams( epochs=1, batch_size=1, learning_rate=3e-5, @@ -94,12 +95,13 @@ class TextClassifierTest(tf.test.TestCase): def test_label_mismatch(self): options = ( - text_classifier_options.TextClassifierOptions( - supported_model=ms.SupportedModels.MOBILEBERT_CLASSIFIER)) + text_classifier.TextClassifierOptions( + supported_model=( + text_classifier.SupportedModels.MOBILEBERT_CLASSIFIER))) train_tf_dataset = tf.data.Dataset.from_tensor_slices([[0]]) - train_data = dataset.Dataset(train_tf_dataset, 1, ['foo']) + train_data = text_classifier.Dataset(train_tf_dataset, 1, ['foo']) validation_tf_dataset = tf.data.Dataset.from_tensor_slices([[0]]) - validation_data = dataset.Dataset(validation_tf_dataset, 1, ['bar']) + validation_data = text_classifier.Dataset(validation_tf_dataset, 1, ['bar']) with self.assertRaisesRegex( ValueError, 'Training data label names .* not equal to validation data label names' @@ -111,9 +113,11 @@ class TextClassifierTest(tf.test.TestCase): train_data, validation_data = self._get_data() avg_options = ( - text_classifier_options.TextClassifierOptions( - supported_model=ms.SupportedModels.MOBILEBERT_CLASSIFIER, - model_options=mo.AverageWordEmbeddingClassifierOptions())) + text_classifier.TextClassifierOptions( + supported_model=( + text_classifier.SupportedModels.MOBILEBERT_CLASSIFIER), + model_options=( + text_classifier.AverageWordEmbeddingClassifierModelOptions()))) with self.assertRaisesRegex( ValueError, 'Expected AVERAGE_WORD_EMBEDDING_CLASSIFIER, got' ' SupportedModels.MOBILEBERT_CLASSIFIER'): @@ -121,10 +125,10 @@ class TextClassifierTest(tf.test.TestCase): avg_options) bert_options = ( - text_classifier_options.TextClassifierOptions( - supported_model=( - ms.SupportedModels.AVERAGE_WORD_EMBEDDING_CLASSIFIER), - model_options=mo.BertClassifierOptions())) + text_classifier.TextClassifierOptions( + supported_model=(text_classifier.SupportedModels + .AVERAGE_WORD_EMBEDDING_CLASSIFIER), + model_options=text_classifier.BertClassifierModelOptions())) with self.assertRaisesRegex( ValueError, 'Expected MOBILEBERT_CLASSIFIER, got' ' SupportedModels.AVERAGE_WORD_EMBEDDING_CLASSIFIER'): From bf6c8a0b63c747e2b99c0e59774c609b799e2277 Mon Sep 17 00:00:00 2001 From: Jiuqiang Tang Date: Sat, 12 Nov 2022 04:33:33 -0800 Subject: [PATCH 21/21] Expose ImageEmbedder APIs in PyPI packages. PiperOrigin-RevId: 488033833 --- mediapipe/tasks/python/vision/__init__.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mediapipe/tasks/python/vision/__init__.py b/mediapipe/tasks/python/vision/__init__.py index 17593357..cf19813c 100644 --- a/mediapipe/tasks/python/vision/__init__.py +++ b/mediapipe/tasks/python/vision/__init__.py @@ -18,6 +18,7 @@ import mediapipe.tasks.python.vision.core import mediapipe.tasks.python.vision.gesture_recognizer import mediapipe.tasks.python.vision.hand_landmarker import mediapipe.tasks.python.vision.image_classifier +import mediapipe.tasks.python.vision.image_embedder import mediapipe.tasks.python.vision.image_segmenter import mediapipe.tasks.python.vision.object_detector @@ -29,6 +30,10 @@ HandLandmarkerOptions = hand_landmarker.HandLandmarkerOptions HandLandmarkerResult = hand_landmarker.HandLandmarkerResult ImageClassifier = image_classifier.ImageClassifier ImageClassifierOptions = image_classifier.ImageClassifierOptions +ImageClassifierResult = image_classifier.ImageClassifierResult +ImageEmbedder = image_embedder.ImageEmbedder +ImageEmbedderOptions = image_embedder.ImageEmbedderOptions +ImageEmbedderResult = image_embedder.ImageEmbedderResult ImageSegmenter = image_segmenter.ImageSegmenter ImageSegmenterOptions = image_segmenter.ImageSegmenterOptions ObjectDetector = object_detector.ObjectDetector @@ -40,6 +45,7 @@ del core del gesture_recognizer del hand_landmarker del image_classifier +del image_embedder del image_segmenter del object_detector del mediapipe