import json
import os
import shutil
import tempfile
import unittest

from transformers import is_speech_available, is_torch_available
from transformers.models.speechta import SpeechTaTokenizer
from transformers.testing_utils import get_tests_dir, require_torch
from transformers.utils import FEATURE_EXTRACTOR_NAME


if is_speech_available() and is_torch_available():
    from transformers import SpeechTaFeatureExtractor, SpeechTaProcessor

    from .test_feature_extraction_speechta import floats_list


lowerCAmelCase__      		=					get_tests_dir('fixtures/test_sentencepiece_bpe_char.model')
@require_torch
class 							a_					(		unittest.TestCase		):






 '''simple docstring'''






 def 						__snake_case		(     self   :    Optional[Any]):







        '''simple docstring'''



        lowerCAmelCase__	      =   tempfile.mkdtemp()

        lowerCAmelCase__	      =   SpeechTaTokenizer(lowercase__)
        tokenizer.save_pretrained(self.tmpdirname)

        lowerCAmelCase__	      =   {
            'feature_size': 1,
            'padding_value': 0.0,
            'sampling_rate': 16_000,
            'do_normalize': False,
            'num_mel_bins': 80,
            'hop_length': 16,
            'win_length': 64,
            'win_function': 'hann_window',
            'fmin': 80,
            'fmax': 7_600,
            'mel_floor': 1e-10,
            'reduction_factor': 2,
            'return_attention_mask': True,
        }

        lowerCAmelCase__	      =   os.path.join(self.tmpdirname     ,       lowercase__)
        with open(self.feature_extraction_file     ,       'w'     ,       encoding='utf-8') as fp:
               fp.write(json.dumps(lowercase__) + '\n')




 def 						__snake_case		(     self   :    str     ,       **lowercase__   :    Tuple):







        '''simple docstring'''



        return SpeechTaTokenizer.from_pretrained(self.tmpdirname     ,       **lowercase__)




 def 						__snake_case		(     self   :    Tuple     ,       **lowercase__   :    List[str]):







        '''simple docstring'''



        return SpeechTaFeatureExtractor.from_pretrained(self.tmpdirname     ,       **lowercase__)




 def 						__snake_case		(     self   :    Dict):







        '''simple docstring'''



        shutil.rmtree(self.tmpdirname)




 def 						__snake_case		(     self   :    Tuple):







        '''simple docstring'''



        lowerCAmelCase__	      =   self.get_tokenizer()
        lowerCAmelCase__	      =   self.get_feature_extractor()

        lowerCAmelCase__	      =   SpeechTaProcessor(tokenizer=lowercase__     ,       feature_extractor=lowercase__)

        processor.save_pretrained(self.tmpdirname)
        lowerCAmelCase__	      =   SpeechTaProcessor.from_pretrained(self.tmpdirname)

        self.assertEqual(processor.tokenizer.get_vocab()     ,       tokenizer.get_vocab())
        self.assertIsInstance(processor.tokenizer     ,       lowercase__)

        self.assertEqual(processor.feature_extractor.to_json_string()     ,       feature_extractor.to_json_string())
        self.assertIsInstance(processor.feature_extractor     ,       lowercase__)




 def 						__snake_case		(     self   :    Optional[Any]):







        '''simple docstring'''



        lowerCAmelCase__	      =   SpeechTaProcessor(tokenizer=self.get_tokenizer()     ,       feature_extractor=self.get_feature_extractor())
        processor.save_pretrained(self.tmpdirname)

        lowerCAmelCase__	      =   self.get_tokenizer(bos_token='(BOS)'     ,       eos_token='(EOS)')
        lowerCAmelCase__	      =   self.get_feature_extractor(do_normalize=lowercase__     ,       padding_value=1.0)

        lowerCAmelCase__	      =   SpeechTaProcessor.from_pretrained(
            self.tmpdirname     ,       bos_token='(BOS)'     ,       eos_token='(EOS)'     ,       do_normalize=lowercase__     ,       padding_value=1.0)

        self.assertEqual(processor.tokenizer.get_vocab()     ,       tokenizer_add_kwargs.get_vocab())
        self.assertIsInstance(processor.tokenizer     ,       lowercase__)

        self.assertEqual(processor.feature_extractor.to_json_string()     ,       feature_extractor_add_kwargs.to_json_string())
        self.assertIsInstance(processor.feature_extractor     ,       lowercase__)




 def 						__snake_case		(     self   :    Tuple):







        '''simple docstring'''



        lowerCAmelCase__	      =   self.get_feature_extractor()
        lowerCAmelCase__	      =   self.get_tokenizer()

        lowerCAmelCase__	      =   SpeechTaProcessor(tokenizer=lowercase__     ,       feature_extractor=lowercase__)

        lowerCAmelCase__	      =   floats_list((3, 1_000))

        lowerCAmelCase__	      =   feature_extractor(audio=lowercase__     ,       return_tensors='np')
        lowerCAmelCase__	      =   processor(audio=lowercase__     ,       return_tensors='np')

        for key in input_feat_extract.keys():
               self.assertAlmostEqual(input_feat_extract[key].sum()     ,       input_processor[key].sum()     ,       delta=1e-2)




 def 						__snake_case		(     self   :    Optional[Any]):







        '''simple docstring'''



        lowerCAmelCase__	      =   self.get_feature_extractor()
        lowerCAmelCase__	      =   self.get_tokenizer()

        lowerCAmelCase__	      =   SpeechTaProcessor(tokenizer=lowercase__     ,       feature_extractor=lowercase__)

        lowerCAmelCase__	      =   floats_list((3, 1_000))

        lowerCAmelCase__	      =   feature_extractor(audio_target=lowercase__     ,       return_tensors='np')
        lowerCAmelCase__	      =   processor(audio_target=lowercase__     ,       return_tensors='np')

        for key in input_feat_extract.keys():
               self.assertAlmostEqual(input_feat_extract[key].sum()     ,       input_processor[key].sum()     ,       delta=1e-2)




 def 						__snake_case		(     self   :    Optional[int]):







        '''simple docstring'''



        lowerCAmelCase__	      =   self.get_feature_extractor()
        lowerCAmelCase__	      =   self.get_tokenizer()

        lowerCAmelCase__	      =   SpeechTaProcessor(tokenizer=lowercase__     ,       feature_extractor=lowercase__)

        lowerCAmelCase__	      =   'This is a test string'

        lowerCAmelCase__	      =   processor(text=lowercase__)
        lowerCAmelCase__	      =   tokenizer(lowercase__)

        for key in encoded_tok.keys():
               self.assertListEqual(encoded_tok[key]     ,       encoded_processor[key])




 def 						__snake_case		(     self   :    Any):







        '''simple docstring'''



        lowerCAmelCase__	      =   self.get_feature_extractor()
        lowerCAmelCase__	      =   self.get_tokenizer()

        lowerCAmelCase__	      =   SpeechTaProcessor(tokenizer=lowercase__     ,       feature_extractor=lowercase__)

        lowerCAmelCase__	      =   'This is a test string'

        lowerCAmelCase__	      =   processor(text_target=lowercase__)
        lowerCAmelCase__	      =   tokenizer(lowercase__)

        for key in encoded_tok.keys():
               self.assertListEqual(encoded_tok[key]     ,       encoded_processor[key])




 def 						__snake_case		(     self   :    int):







        '''simple docstring'''



        lowerCAmelCase__	      =   self.get_feature_extractor()
        lowerCAmelCase__	      =   self.get_tokenizer()

        lowerCAmelCase__	      =   SpeechTaProcessor(tokenizer=lowercase__     ,       feature_extractor=lowercase__)

        lowerCAmelCase__	      =   [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

        lowerCAmelCase__	      =   processor.batch_decode(lowercase__)
        lowerCAmelCase__	      =   tokenizer.batch_decode(lowercase__)

        self.assertListEqual(lowercase__     ,       lowercase__)




 def 						__snake_case		(     self   :    Dict):







        '''simple docstring'''



        lowerCAmelCase__	      =   self.get_feature_extractor()
        lowerCAmelCase__	      =   self.get_tokenizer()

        lowerCAmelCase__	      =   SpeechTaProcessor(tokenizer=lowercase__     ,       feature_extractor=lowercase__)

        self.assertListEqual(
            processor.model_input_names     ,       feature_extractor.model_input_names     ,       msg='`processor` and `feature_extractor` model input names do not match'     ,       )

from __future__ import annotations

from collections.abc import Iterable
class 							a_					:






 '''simple docstring'''






 def __init__(     self   :    int     ,       lowercase__   :    Optional[int]     ,       lowercase__   :    List[str]):







        '''simple docstring'''



        lowerCAmelCase__      ,   lowerCAmelCase__	      =   float(lowercase__), float(lowercase__)




 def __eq__(     self   :    int     ,       lowercase__   :    int):







        '''simple docstring'''



        return self.x == other.x and self.y == other.y




 def __ne__(     self   :    Tuple     ,       lowercase__   :    List[Any]):







        '''simple docstring'''



        return not self == other




 def __gt__(     self   :    Optional[Any]     ,       lowercase__   :    List[Any]):







        '''simple docstring'''



        if self.x > other.x:
               return True
        elif self.x == other.x:
               return self.y > other.y
        return False




 def __lt__(     self   :    str     ,       lowercase__   :    List[str]):







        '''simple docstring'''



        return not self > other




 def __ge__(     self   :    List[Any]     ,       lowercase__   :    Any):







        '''simple docstring'''



        if self.x > other.x:
               return True
        elif self.x == other.x:
               return self.y >= other.y
        return False




 def __le__(     self   :    Dict     ,       lowercase__   :    str):







        '''simple docstring'''



        if self.x < other.x:
               return True
        elif self.x == other.x:
               return self.y <= other.y
        return False




 def __repr__(     self   :    List[str]):







        '''simple docstring'''



        return F"""({self.x}, {self.y})"""




 def __hash__(     self   :    Dict):







        '''simple docstring'''



        return hash(self.x)






def  __lowerCamelCase						(		lowerCAmelCase__      ,    ):
       lowerCAmelCase__	      =   []
       if list_of_tuples:
              for p in list_of_tuples:
                     if isinstance(lowerCAmelCase__      ,    lowerCAmelCase__      ):
                            points.append(lowerCAmelCase__      )
                     else:
                            try:
                                   points.append(Point(p[0]      ,    p[1]      )      )
                            except (IndexError, TypeError):
                                   print(
                                       F"""Ignoring deformed point {p}. All points"""
                                       ' must have at least 2 coordinates.'      )
       return points






def  __lowerCamelCase						(		lowerCAmelCase__      ):

       if not hasattr(lowerCAmelCase__      ,    '__iter__'      ):
              lowerCAmelCase__	      =   F"""Expecting an iterable object but got an non-iterable type {points}"""
              raise ValueError(lowerCAmelCase__      )

       if not points:
              lowerCAmelCase__	      =   F"""Expecting a list of points but got {points}"""
              raise ValueError(lowerCAmelCase__      )

       return _construct_points(lowerCAmelCase__      )






def  __lowerCamelCase						(		lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ):
       lowerCAmelCase__	      =   (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
       return det






def  __lowerCamelCase						(		lowerCAmelCase__      ):
       lowerCAmelCase__	      =   sorted(_validate_input(lowerCAmelCase__      )      )
       lowerCAmelCase__	      =   len(lowerCAmelCase__      )
       lowerCAmelCase__	      =   set()

       for i in range(n - 1      ):
              for j in range(i + 1      ,    lowerCAmelCase__      ):
                     lowerCAmelCase__	      =   lowerCAmelCase__	      =   False
                     lowerCAmelCase__	      =   True
                     for k in range(lowerCAmelCase__      ):
                            if k != i and k != j:
                                   lowerCAmelCase__	      =   _det(points[i]      ,    points[j]      ,    points[k]      )

                                   if det_k > 0:
                                          lowerCAmelCase__	      =   True
                                   elif det_k < 0:
                                          lowerCAmelCase__	      =   True
                                   else:
                                          # point[i], point[j], point[k] all lie on a straight line
                                          # if point[k] is to the left of point[i] or it's to the
                                          # right of point[j], then point[i], point[j] cannot be
                                          # part of the convex hull of A
                                          if points[k] < points[i] or points[k] > points[j]:
                                                 lowerCAmelCase__	      =   False
                                                 break

                            if points_left_of_ij and points_right_of_ij:
                                   lowerCAmelCase__	      =   False
                                   break

                     if ij_part_of_convex_hull:
                            convex_set.update([points[i], points[j]]      )

       return sorted(lowerCAmelCase__      )






def  __lowerCamelCase						(		lowerCAmelCase__      ):
       lowerCAmelCase__	      =   sorted(_validate_input(lowerCAmelCase__      )      )
       lowerCAmelCase__	      =   len(lowerCAmelCase__      )

       # divide all the points into an upper hull and a lower hull
       # the left most point and the right most point are definitely
       # members of the convex hull by definition.
       # use these two anchors to divide all the points into two hulls,
       # an upper hull and a lower hull.

       # all points to the left (above) the line joining the extreme points belong to the
       # upper hull
       # all points to the right (below) the line joining the extreme points below to the
       # lower hull
       # ignore all points on the line joining the extreme points since they cannot be
       # part of the convex hull

       lowerCAmelCase__	      =   points[0]
       lowerCAmelCase__	      =   points[n - 1]

       lowerCAmelCase__	      =   {left_most_point, right_most_point}
       lowerCAmelCase__	      =   []
       lowerCAmelCase__	      =   []

       for i in range(1      ,    n - 1      ):
              lowerCAmelCase__	      =   _det(lowerCAmelCase__      ,    lowerCAmelCase__      ,    points[i]      )

              if det > 0:
                     upper_hull.append(points[i]      )
              elif det < 0:
                     lower_hull.append(points[i]      )

       _construct_hull(lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      )
       _construct_hull(lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      )

       return sorted(lowerCAmelCase__      )






def  __lowerCamelCase						(		lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ):
       if points:
              lowerCAmelCase__	      =   None
              lowerCAmelCase__	      =   float('-inf'      )
              lowerCAmelCase__	      =   []

              for p in points:
                     lowerCAmelCase__	      =   _det(lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      )

                     if det > 0:
                            candidate_points.append(lowerCAmelCase__      )

                            if det > extreme_point_distance:
                                   lowerCAmelCase__	      =   det
                                   lowerCAmelCase__	      =   p

              if extreme_point:
                     _construct_hull(lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      )
                     convex_set.add(lowerCAmelCase__      )
                     _construct_hull(lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      )






def  __lowerCamelCase						(		lowerCAmelCase__      ):
       lowerCAmelCase__	      =   sorted(_validate_input(lowerCAmelCase__      )      )
       lowerCAmelCase__	      =   len(lowerCAmelCase__      )

       lowerCAmelCase__	      =   points[:2]
       for i in range(2      ,    lowerCAmelCase__      ):
              lowerCAmelCase__	      =   _det(convex_hull[1]      ,    convex_hull[0]      ,    points[i]      )
              if det > 0:
                     convex_hull.insert(0      ,    points[i]      )
                     break
              elif det < 0:
                     convex_hull.append(points[i]      )
                     break
              else:
                     lowerCAmelCase__	      =   points[i]
       i += 1

       for j in range(lowerCAmelCase__      ,    lowerCAmelCase__      ):
              if (
                  _det(convex_hull[0]      ,    convex_hull[-1]      ,    points[j]      ) > 0
                  and _det(convex_hull[-1]      ,    convex_hull[0]      ,    points[1]      ) < 0
              ):
                     # The point lies within the convex hull
                     continue

              convex_hull.insert(0      ,    points[j]      )
              convex_hull.append(points[j]      )
              while _det(convex_hull[0]      ,    convex_hull[1]      ,    convex_hull[2]      ) >= 0:
                     del convex_hull[1]
              while _det(convex_hull[-1]      ,    convex_hull[-2]      ,    convex_hull[-3]      ) <= 0:
                     del convex_hull[-2]

    # `convex_hull` is contains the convex hull in circular order
       return sorted(convex_hull[1:] if len(lowerCAmelCase__      ) > 3 else convex_hull      )






def  __lowerCamelCase						(		):
       lowerCAmelCase__	      =   [
           (0, 3),
           (2, 2),
           (1, 1),
           (2, 1),
           (3, 0),
           (0, 0),
           (3, 3),
           (2, -1),
           (2, -4),
           (1, -3),
       ]
       # the convex set of points is
       # [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
       lowerCAmelCase__	      =   convex_hull_bf(lowerCAmelCase__      )

       lowerCAmelCase__	      =   convex_hull_recursive(lowerCAmelCase__      )
       assert results_bf == results_recursive

       lowerCAmelCase__	      =   convex_hull_melkman(lowerCAmelCase__      )
       assert results_bf == results_melkman

       print(lowerCAmelCase__      )


if __name__ == "__main__":
    main()
