





"""simple docstring"""





import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
       from PIL import Image
else:

       class 		lowercase					:





             @staticmethod
             def     _snake_case			(       *lowercase      ,						**lowercase )		->     Any:
                   pass

@is_pipeline_test
@require_vision
class 		lowercase					(					unittest.TestCase					):





      @require_torch
      def     _snake_case			(       self )		->     List[str]:
            lowerCAmelCase  						=       pipeline(
                model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""      ,						)
            lowerCAmelCase  						=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
            lowerCAmelCase  						=       image_classifier(lowercase      ,						candidate_labels=["""a""", """b""", """c"""] )

            # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
            # python and torch versions.
            self.assertIn(
                nested_simplify(lowercase )      ,						[
                    [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}],
                    [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """c"""}, {"""score""": 0.333, """label""": """b"""}],
                ]      ,						)

            lowerCAmelCase  						=       image_classifier([image] * 5      ,						candidate_labels=["""A""", """B""", """C"""]      ,						batch_size=2 )
            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                ]      ,						)





      @require_tf
      def     _snake_case			(       self )		->     List[str]:
            lowerCAmelCase  						=       pipeline(
                model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""      ,						framework="""tf""" )
            lowerCAmelCase  						=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
            lowerCAmelCase  						=       image_classifier(lowercase      ,						candidate_labels=["""a""", """b""", """c"""] )

            self.assertEqual(
                nested_simplify(lowercase )      ,						[{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}]      ,						)

            lowerCAmelCase  						=       image_classifier([image] * 5      ,						candidate_labels=["""A""", """B""", """C"""]      ,						batch_size=2 )
            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                    [
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                        {"""score""": 0.333, """label""": ANY(lowercase )},
                    ],
                ]      ,						)





      @slow
      @require_torch
      def     _snake_case			(       self )		->     Union[str, Any]:
            lowerCAmelCase  						=       pipeline(
                task="""zero-shot-image-classification"""      ,						model="""openai/clip-vit-base-patch32"""      ,						)
            # This is an image of 2 cats with remotes and no planes
            lowerCAmelCase  						=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
            lowerCAmelCase  						=       image_classifier(lowercase      ,						candidate_labels=["""cat""", """plane""", """remote"""] )

            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    {"""score""": 0.511, """label""": """remote"""},
                    {"""score""": 0.485, """label""": """cat"""},
                    {"""score""": 0.004, """label""": """plane"""},
                ]      ,						)

            lowerCAmelCase  						=       image_classifier([image] * 5      ,						candidate_labels=["""cat""", """plane""", """remote"""]      ,						batch_size=2 )
            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    [
                        {"""score""": 0.511, """label""": """remote"""},
                        {"""score""": 0.485, """label""": """cat"""},
                        {"""score""": 0.004, """label""": """plane"""},
                    ],
                ]
                * 5      ,						)





      @slow
      @require_tf
      def     _snake_case			(       self )		->     Optional[Any]:
            lowerCAmelCase  						=       pipeline(
                task="""zero-shot-image-classification"""      ,						model="""openai/clip-vit-base-patch32"""      ,						framework="""tf""" )
            # This is an image of 2 cats with remotes and no planes
            lowerCAmelCase  						=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
            lowerCAmelCase  						=       image_classifier(lowercase      ,						candidate_labels=["""cat""", """plane""", """remote"""] )
            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    {"""score""": 0.511, """label""": """remote"""},
                    {"""score""": 0.485, """label""": """cat"""},
                    {"""score""": 0.004, """label""": """plane"""},
                ]      ,						)

            lowerCAmelCase  						=       image_classifier([image] * 5      ,						candidate_labels=["""cat""", """plane""", """remote"""]      ,						batch_size=2 )
            self.assertEqual(
                nested_simplify(lowercase )      ,						[
                    [
                        {"""score""": 0.511, """label""": """remote"""},
                        {"""score""": 0.485, """label""": """cat"""},
                        {"""score""": 0.004, """label""": """plane"""},
                    ],
                ]
                * 5      ,						)












import datetime
import platform
import subprocess
from typing import Optional, Tuple, Union

import numpy as np

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	bytes			,			__UpperCAmelCase						:	int							)					-> np.array:
      SCREAMING_SNAKE_CASE_							=			f"{sampling_rate}"
      SCREAMING_SNAKE_CASE_							=			'1'
      SCREAMING_SNAKE_CASE_							=			'f32le'
      SCREAMING_SNAKE_CASE_							=			[
          'ffmpeg',
          '-i',
          'pipe:0',
          '-ac',
          ac,
          '-ar',
          ar,
          '-f',
          format_for_conversion,
          '-hide_banner',
          '-loglevel',
          'quiet',
          'pipe:1',
      ]

      try:
            with subprocess.Popen(__UpperCAmelCase			,			stdin=subprocess.PIPE			,			stdout=subprocess.PIPE							) as ffmpeg_process:
                  SCREAMING_SNAKE_CASE_							=			ffmpeg_process.communicate(__UpperCAmelCase							)
      except FileNotFoundError as error:
            raise ValueError('ffmpeg was not found but is required to load audio files from filename'							) from error
      SCREAMING_SNAKE_CASE_							=			output_stream[0]
      SCREAMING_SNAKE_CASE_							=			np.frombuffer(__UpperCAmelCase			,			np.floataa							)
      if audio.shape[0] == 0:
            raise ValueError('Malformed soundfile'							)
      return audio

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	int			,			__UpperCAmelCase						:	float			,			__UpperCAmelCase						:	str = "f32le"			,			)					-> int:
      SCREAMING_SNAKE_CASE_							=			f"{sampling_rate}"
      SCREAMING_SNAKE_CASE_							=			'1'
      if format_for_conversion == "s16le":
            SCREAMING_SNAKE_CASE_							=			2
      elif format_for_conversion == "f32le":
            SCREAMING_SNAKE_CASE_							=			4
      else:
            raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`"							)

      SCREAMING_SNAKE_CASE_							=			platform.system()
      if system == "Linux":
            SCREAMING_SNAKE_CASE_							=			'alsa'
            SCREAMING_SNAKE_CASE_							=			'default'
      elif system == "Darwin":
            SCREAMING_SNAKE_CASE_							=			'avfoundation'
            SCREAMING_SNAKE_CASE_							=			':0'
      elif system == "Windows":
            SCREAMING_SNAKE_CASE_							=			'dshow'
            SCREAMING_SNAKE_CASE_							=			'default'

      SCREAMING_SNAKE_CASE_							=			[
          'ffmpeg',
          '-f',
          format_,
          '-i',
          input_,
          '-ac',
          ac,
          '-ar',
          ar,
          '-f',
          format_for_conversion,
          '-fflags',
          'nobuffer',
          '-hide_banner',
          '-loglevel',
          'quiet',
          'pipe:1',
      ]
      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * chunk_length_s							)							) * size_of_sample
      SCREAMING_SNAKE_CASE_							=			_ffmpeg_stream(__UpperCAmelCase			,			__UpperCAmelCase							)
      for item in iterator:
            yield item

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	int			,			__UpperCAmelCase						:	float			,			__UpperCAmelCase						:	Optional[int] = None			,			__UpperCAmelCase						:	Optional[Union[Tuple[float, float], float]] = None			,			__UpperCAmelCase						:	str = "f32le"			,			)					-> Tuple:
      if stream_chunk_s is not None:
            SCREAMING_SNAKE_CASE_							=			stream_chunk_s
      else:
            SCREAMING_SNAKE_CASE_							=			chunk_length_s

      SCREAMING_SNAKE_CASE_							=			ffmpeg_microphone(__UpperCAmelCase			,			__UpperCAmelCase			,			format_for_conversion=__UpperCAmelCase							)
      if format_for_conversion == "s16le":
            SCREAMING_SNAKE_CASE_							=			np.intaa
            SCREAMING_SNAKE_CASE_							=			2
      elif format_for_conversion == "f32le":
            SCREAMING_SNAKE_CASE_							=			np.floataa
            SCREAMING_SNAKE_CASE_							=			4
      else:
            raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`"							)

      if stride_length_s is None:
            SCREAMING_SNAKE_CASE_							=			chunk_length_s / 6
      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * chunk_length_s							)							) * size_of_sample
      if isinstance(__UpperCAmelCase			,			(int, float)							):
            SCREAMING_SNAKE_CASE_							=			[stride_length_s, stride_length_s]

      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * stride_length_s[0]							)							) * size_of_sample
      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * stride_length_s[1]							)							) * size_of_sample
      SCREAMING_SNAKE_CASE_							=			datetime.datetime.now()
      SCREAMING_SNAKE_CASE_							=			datetime.timedelta(seconds=__UpperCAmelCase							)
      for item in chunk_bytes_iter(__UpperCAmelCase			,			__UpperCAmelCase			,			stride=(stride_left, stride_right)			,			stream=__UpperCAmelCase							):
            # Put everything back in numpy scale
            SCREAMING_SNAKE_CASE_							=			np.frombuffer(item['raw']			,			dtype=__UpperCAmelCase							)
            SCREAMING_SNAKE_CASE_							=			(
                item['stride'][0] // size_of_sample,
                item['stride'][1] // size_of_sample,
            )
            SCREAMING_SNAKE_CASE_							=			sampling_rate
            audio_time += delta
            if datetime.datetime.now() > audio_time + 10 * delta:
                  # We're late !! SKIP
                  continue
            yield item

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Optional[Any]			,			__UpperCAmelCase						:	int			,			__UpperCAmelCase						:	Tuple[int, int]			,			__UpperCAmelCase						:	bool = False							)					-> Union[str, Any]:
      SCREAMING_SNAKE_CASE_							=			b''
      SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			stride
      if stride_left + stride_right >= chunk_len:
            raise ValueError(
                f"Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}"							)
      SCREAMING_SNAKE_CASE_							=			0
      for raw in iterator:
            acc += raw
            if stream and len(__UpperCAmelCase							) < chunk_len:
                  SCREAMING_SNAKE_CASE_							=			(_stride_left, 0)
                  yield {"raw": acc[:chunk_len], "stride": stride, "partial": True}
            else:
                  while len(__UpperCAmelCase							) >= chunk_len:
                        # We are flushing the accumulator
                        SCREAMING_SNAKE_CASE_							=			(_stride_left, stride_right)
                        SCREAMING_SNAKE_CASE_							=			{'raw': acc[:chunk_len], 'stride': stride}
                        if stream:
                              SCREAMING_SNAKE_CASE_							=			False
                        yield item
                        SCREAMING_SNAKE_CASE_							=			stride_left
                        SCREAMING_SNAKE_CASE_							=			acc[chunk_len - stride_left - stride_right :]
    # Last chunk
      if len(__UpperCAmelCase							) > stride_left:
            SCREAMING_SNAKE_CASE_							=			{'raw': acc, 'stride': (_stride_left, 0)}
            if stream:
                  SCREAMING_SNAKE_CASE_							=			False
            yield item





def 					UpperCAmelCase_							(      __UpperCAmelCase						:	List[str]			,			__UpperCAmelCase						:	int							)					-> Optional[Any]:
      SCREAMING_SNAKE_CASE_							=			2**24  # 16Mo
      try:
            with subprocess.Popen(__UpperCAmelCase			,			stdout=subprocess.PIPE			,			bufsize=__UpperCAmelCase							) as ffmpeg_process:
                  while True:
                        SCREAMING_SNAKE_CASE_							=			ffmpeg_process.stdout.read(__UpperCAmelCase							)
                        if raw == b"":
                              break
                        yield raw
      except FileNotFoundError as error:
            raise ValueError('ffmpeg was not found but is required to stream audio files from filename'							) from error