<commit_before># 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 hand landmarker."""

import enum
from unittest import mock

import numpy as np
from google.protobuf import text_format
from absl.testing import absltest
from absl.testing import parameterized

from mediapipe.python._framework_bindings import image as image_module
from mediapipe.tasks.cc.components.containers.proto import landmarks_detection_result_pb2
from mediapipe.tasks.python.components.containers import rect as rect_module
from mediapipe.tasks.python.components.containers import landmark as landmark_module
from mediapipe.tasks.python.components.containers import landmark_detection_result as landmark_detection_result_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 hand_landmarker
from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module
from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module

_LandmarksDetectionResultProto = landmarks_detection_result_pb2.LandmarksDetectionResult
_BaseOptions = base_options_module.BaseOptions
_Rect = rect_module.Rect
_Landmark = landmark_module.Landmark
_NormalizedLandmark = landmark_module.NormalizedLandmark
_LandmarksDetectionResult = landmark_detection_result_module.LandmarksDetectionResult
_Image = image_module.Image
_HandLandmarker = hand_landmarker.HandLandmarker
_HandLandmarkerOptions = hand_landmarker.HandLandmarkerOptions
_HandLandmarksDetectionResult = hand_landmarker.HandLandmarksDetectionResult
_RUNNING_MODE = running_mode_module.VisionTaskRunningMode
_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions

_HAND_LANDMARKER_BUNDLE_ASSET_FILE = 'hand_landmarker.task'
_NO_HANDS_IMAGE = 'cats_and_dogs.jpg'
_TWO_HANDS_IMAGE = 'right_hands.jpg'
_THUMB_UP_IMAGE = 'thumb_up.jpg'
_THUMB_UP_LANDMARKS = 'thumb_up_landmarks.pbtxt'
_POINTING_UP_IMAGE = 'pointing_up.jpg'
_POINTING_UP_LANDMARKS = 'pointing_up_landmarks.pbtxt'
_POINTING_UP_ROTATED_IMAGE = 'pointing_up_rotated.jpg'
_POINTING_UP_ROTATED_LANDMARKS = 'pointing_up_rotated_landmarks.pbtxt'
_LANDMARKS_ERROR_TOLERANCE = 0.03
_HANDEDNESS_MARGIN = 0.05


def _get_expected_hand_landmarks_detection_result(
    file_path: str) -> _HandLandmarksDetectionResult:
  landmarks_detection_result_file_path = test_utils.get_test_data_path(
    file_path)
  with open(landmarks_detection_result_file_path, "rb") as f:
    landmarks_detection_result_proto = _LandmarksDetectionResultProto()
    # Use this if a .pb file is available.
    # landmarks_detection_result_proto.ParseFromString(f.read())
    text_format.Parse(f.read(), landmarks_detection_result_proto)
    landmarks_detection_result = _LandmarksDetectionResult.create_from_pb2(
        landmarks_detection_result_proto)
  return _HandLandmarksDetectionResult(
      handedness=[landmarks_detection_result.categories],
      hand_landmarks=[landmarks_detection_result.landmarks],
      hand_world_landmarks=[landmarks_detection_result.world_landmarks])


class ModelFileType(enum.Enum):
  FILE_CONTENT = 1
  FILE_NAME = 2


class HandLandmarkerTest(parameterized.TestCase):

  def setUp(self):
    super().setUp()
    self.test_image = _Image.create_from_file(
        test_utils.get_test_data_path(_THUMB_UP_IMAGE))
    self.model_path = test_utils.get_test_data_path(
        _HAND_LANDMARKER_BUNDLE_ASSET_FILE)

  def _assert_actual_result_approximately_matches_expected_result(
      self,
      actual_result: _HandLandmarksDetectionResult,
      expected_result: _HandLandmarksDetectionResult
  ):
    # Expects to have the same number of hands detected.
    self.assertLen(actual_result.hand_landmarks,
                   len(expected_result.hand_landmarks))
    self.assertLen(actual_result.hand_world_landmarks,
                   len(expected_result.hand_world_landmarks))
    self.assertLen(actual_result.handedness, len(expected_result.handedness))
    # Actual landmarks match expected landmarks.
    self.assertLen(actual_result.hand_landmarks[0],
                   len(expected_result.hand_landmarks[0]))
    actual_landmarks = actual_result.hand_landmarks[0]
    expected_landmarks = expected_result.hand_landmarks[0]
    for i in range(len(actual_landmarks)):
      self.assertAlmostEqual(actual_landmarks[i].x, expected_landmarks[i].x,
                             delta=_LANDMARKS_ERROR_TOLERANCE)
      self.assertAlmostEqual(actual_landmarks[i].y, expected_landmarks[i].y,
                             delta=_LANDMARKS_ERROR_TOLERANCE)
    # Actual handedness matches expected handedness.
    actual_top_handedness = actual_result.handedness[0][0]
    expected_top_handedness = expected_result.handedness[0][0]
    self.assertEqual(actual_top_handedness.index, expected_top_handedness.index)
    self.assertEqual(actual_top_handedness.category_name,
                     expected_top_handedness.category_name)
    self.assertAlmostEqual(actual_top_handedness.score,
                           expected_top_handedness.score,
                           delta=_HANDEDNESS_MARGIN)

  def test_create_from_file_succeeds_with_valid_model_path(self):
    # Creates with default option and valid model file successfully.
    with _HandLandmarker.create_from_model_path(self.model_path) as landmarker:
      self.assertIsInstance(landmarker, _HandLandmarker)

  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 = _HandLandmarkerOptions(base_options=base_options)
    with _HandLandmarker.create_from_options(options) as landmarker:
      self.assertIsInstance(landmarker, _HandLandmarker)

  def test_create_from_options_fails_with_invalid_model_path(self):
    # Invalid empty model path.
    with self.assertRaisesRegex(
        ValueError,
        r"ExternalFile must specify at least one of 'file_content', "
        r"'file_name', 'file_pointer_meta' or 'file_descriptor_meta'."):
      base_options = _BaseOptions(model_asset_path='')
      options = _HandLandmarkerOptions(base_options=base_options)
      _HandLandmarker.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 = _HandLandmarkerOptions(base_options=base_options)
      landmarker = _HandLandmarker.create_from_options(options)
      self.assertIsInstance(landmarker, _HandLandmarker)

  @parameterized.parameters(
      (ModelFileType.FILE_NAME, _get_expected_hand_landmarks_detection_result(<commit_msg>Updated the 'test_create_from_options_fails_with_invalid_model_path' test case<commit_after># 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 hand landmarker."""

import enum
from unittest import mock

import numpy as np
from google.protobuf import text_format
from absl.testing import absltest
from absl.testing import parameterized

from mediapipe.python._framework_bindings import image as image_module
from mediapipe.tasks.cc.components.containers.proto import landmarks_detection_result_pb2
from mediapipe.tasks.python.components.containers import rect as rect_module
from mediapipe.tasks.python.components.containers import landmark as landmark_module
from mediapipe.tasks.python.components.containers import landmark_detection_result as landmark_detection_result_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 hand_landmarker
from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module
from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module

_LandmarksDetectionResultProto = landmarks_detection_result_pb2.LandmarksDetectionResult
_BaseOptions = base_options_module.BaseOptions
_Rect = rect_module.Rect
_Landmark = landmark_module.Landmark
_NormalizedLandmark = landmark_module.NormalizedLandmark
_LandmarksDetectionResult = landmark_detection_result_module.LandmarksDetectionResult
_Image = image_module.Image
_HandLandmarker = hand_landmarker.HandLandmarker
_HandLandmarkerOptions = hand_landmarker.HandLandmarkerOptions
_HandLandmarksDetectionResult = hand_landmarker.HandLandmarksDetectionResult
_RUNNING_MODE = running_mode_module.VisionTaskRunningMode
_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions

_HAND_LANDMARKER_BUNDLE_ASSET_FILE = 'hand_landmarker.task'
_NO_HANDS_IMAGE = 'cats_and_dogs.jpg'
_TWO_HANDS_IMAGE = 'right_hands.jpg'
_THUMB_UP_IMAGE = 'thumb_up.jpg'
_THUMB_UP_LANDMARKS = 'thumb_up_landmarks.pbtxt'
_POINTING_UP_IMAGE = 'pointing_up.jpg'
_POINTING_UP_LANDMARKS = 'pointing_up_landmarks.pbtxt'
_POINTING_UP_ROTATED_IMAGE = 'pointing_up_rotated.jpg'
_POINTING_UP_ROTATED_LANDMARKS = 'pointing_up_rotated_landmarks.pbtxt'
_LANDMARKS_ERROR_TOLERANCE = 0.03
_HANDEDNESS_MARGIN = 0.05


def _get_expected_hand_landmarks_detection_result(
    file_path: str) -> _HandLandmarksDetectionResult:
  landmarks_detection_result_file_path = test_utils.get_test_data_path(
    file_path)
  with open(landmarks_detection_result_file_path, "rb") as f:
    landmarks_detection_result_proto = _LandmarksDetectionResultProto()
    # Use this if a .pb file is available.
    # landmarks_detection_result_proto.ParseFromString(f.read())
    text_format.Parse(f.read(), landmarks_detection_result_proto)
    landmarks_detection_result = _LandmarksDetectionResult.create_from_pb2(
        landmarks_detection_result_proto)
  return _HandLandmarksDetectionResult(
      handedness=[landmarks_detection_result.categories],
      hand_landmarks=[landmarks_detection_result.landmarks],
      hand_world_landmarks=[landmarks_detection_result.world_landmarks])


class ModelFileType(enum.Enum):
  FILE_CONTENT = 1
  FILE_NAME = 2


class HandLandmarkerTest(parameterized.TestCase):

  def setUp(self):
    super().setUp()
    self.test_image = _Image.create_from_file(
        test_utils.get_test_data_path(_THUMB_UP_IMAGE))
    self.model_path = test_utils.get_test_data_path(
        _HAND_LANDMARKER_BUNDLE_ASSET_FILE)

  def _assert_actual_result_approximately_matches_expected_result(
      self,
      actual_result: _HandLandmarksDetectionResult,
      expected_result: _HandLandmarksDetectionResult
  ):
    # Expects to have the same number of hands detected.
    self.assertLen(actual_result.hand_landmarks,
                   len(expected_result.hand_landmarks))
    self.assertLen(actual_result.hand_world_landmarks,
                   len(expected_result.hand_world_landmarks))
    self.assertLen(actual_result.handedness, len(expected_result.handedness))
    # Actual landmarks match expected landmarks.
    self.assertLen(actual_result.hand_landmarks[0],
                   len(expected_result.hand_landmarks[0]))
    actual_landmarks = actual_result.hand_landmarks[0]
    expected_landmarks = expected_result.hand_landmarks[0]
    for i in range(len(actual_landmarks)):
      self.assertAlmostEqual(actual_landmarks[i].x, expected_landmarks[i].x,
                             delta=_LANDMARKS_ERROR_TOLERANCE)
      self.assertAlmostEqual(actual_landmarks[i].y, expected_landmarks[i].y,
                             delta=_LANDMARKS_ERROR_TOLERANCE)
    # Actual handedness matches expected handedness.
    actual_top_handedness = actual_result.handedness[0][0]
    expected_top_handedness = expected_result.handedness[0][0]
    self.assertEqual(actual_top_handedness.index, expected_top_handedness.index)
    self.assertEqual(actual_top_handedness.category_name,
                     expected_top_handedness.category_name)
    self.assertAlmostEqual(actual_top_handedness.score,
                           expected_top_handedness.score,
                           delta=_HANDEDNESS_MARGIN)

  def test_create_from_file_succeeds_with_valid_model_path(self):
    # Creates with default option and valid model file successfully.
    with _HandLandmarker.create_from_model_path(self.model_path) as landmarker:
      self.assertIsInstance(landmarker, _HandLandmarker)

  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 = _HandLandmarkerOptions(base_options=base_options)
    with _HandLandmarker.create_from_options(options) as landmarker:
      self.assertIsInstance(landmarker, _HandLandmarker)

  def test_create_from_options_fails_with_invalid_model_path(self):
    # Invalid empty model path.
    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 = _HandLandmarkerOptions(base_options=base_options)
      _HandLandmarker.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 = _HandLandmarkerOptions(base_options=base_options)
      landmarker = _HandLandmarker.create_from_options(options)
      self.assertIsInstance(landmarker, _HandLandmarker)

  @parameterized.parameters(
      (ModelFileType.FILE_NAME, _get_expected_hand_landmarks_detection_result(
{'fraction_non_alphanumeric': 0.06294082085040639, 'fraction_numerical': 0.0036273258547726206, 'mean_word_length': 5.42832469775475, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '934390', 'n_tokens_mistral': 4542, 'n_tokens_neox': 4393, 'n_words': 818}