



"""simple docstring"""






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

import numpy as np






def 	snake_case_  (				A_ :		bytes,    A_ :		int						):


							'''simple docstring'''





							_lowerCamelCase						:    Any         =			F'''{sampling_rate}'''
							_lowerCamelCase						:    Optional[Any]         =			'''1'''
							_lowerCamelCase						:    str         =			'''f32le'''
							_lowerCamelCase						:    Union[str, Any]         =			[
							    '''ffmpeg''',
							    '''-i''',
							    '''pipe:0''',
							    '''-ac''',
							    ac,
							    '''-ar''',
							    ar,
							    '''-f''',
							    format_for_conversion,
							    '''-hide_banner''',
							    '''-loglevel''',
							    '''quiet''',
							    '''pipe:1''',
							]

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






def 	snake_case_  (				A_ :		int,    A_ :		float,    A_ :		str = "f32le",    ):


							'''simple docstring'''





							_lowerCamelCase						:    Optional[Any]         =			F'''{sampling_rate}'''
							_lowerCamelCase						:    Optional[int]         =			'''1'''
							if format_for_conversion == "s16le":
														_lowerCamelCase						:    List[Any]         =			2
							elif format_for_conversion == "f32le":
														_lowerCamelCase						:    List[str]         =			4
							else:
														raise ValueError(F'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`'''						)

							_lowerCamelCase						:    List[str]         =			platform.system()
							if system == "Linux":
														_lowerCamelCase						:    Tuple         =			'''alsa'''
														_lowerCamelCase						:    Tuple         =			'''default'''
							elif system == "Darwin":
														_lowerCamelCase						:    Any         =			'''avfoundation'''
														_lowerCamelCase						:    List[Any]         =			''':0'''
							elif system == "Windows":
														_lowerCamelCase						:    Union[str, Any]         =			'''dshow'''
														_lowerCamelCase						:    Any         =			'''default'''

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






def 	snake_case_  (				A_ :		int,    A_ :		float,    A_ :		Optional[int] = None,    A_ :		Optional[Union[Tuple[float, float], float]] = None,    A_ :		str = "f32le",    ):


							'''simple docstring'''





							if stream_chunk_s is not None:
														_lowerCamelCase						:    Optional[Any]         =			stream_chunk_s
							else:
														_lowerCamelCase						:    Optional[Any]         =			chunk_length_s

							_lowerCamelCase						:    int         =			ffmpeg_microphone(A_,    A_,    format_for_conversion=A_						)
							if format_for_conversion == "s16le":
														_lowerCamelCase						:    List[str]         =			np.intaa
														_lowerCamelCase						:    List[str]         =			2
							elif format_for_conversion == "f32le":
														_lowerCamelCase						:    str         =			np.floataa
														_lowerCamelCase						:    List[str]         =			4
							else:
														raise ValueError(F'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`'''						)

							if stride_length_s is None:
														_lowerCamelCase						:    List[str]         =			chunk_length_s / 6
							_lowerCamelCase						:    Dict         =			int(round(sampling_rate * chunk_length_s						)						) * size_of_sample
							if isinstance(A_,    (int, float)						):
														_lowerCamelCase						:    int         =			[stride_length_s, stride_length_s]

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






def 	snake_case_  (				A_ :		List[Any],    A_ :		int,    A_ :		Tuple[int, int],    A_ :		bool = False						):


							'''simple docstring'''





							_lowerCamelCase						:    Tuple         =			b''''''
							_lowerCamelCase						:    str         =			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}'''						)
							_lowerCamelCase						:    Optional[int]         =			0
							for raw in iterator:
														acc += raw
														if stream and len(A_						) < chunk_len:
																					_lowerCamelCase						:    List[str]         =			(_stride_left, 0)
																					yield {"raw": acc[:chunk_len], "stride": stride, "partial": True}
														else:
																					while len(A_						) >= chunk_len:
																												# We are flushing the accumulator
																												_lowerCamelCase						:    Union[str, Any]         =			(_stride_left, stride_right)
																												_lowerCamelCase						:    Dict         =			{'''raw''': acc[:chunk_len], '''stride''': stride}
																												if stream:
																																			_lowerCamelCase						:    Tuple         =			False
																												yield item
																												_lowerCamelCase						:    Optional[int]         =			stride_left
																												_lowerCamelCase						:    int         =			acc[chunk_len - stride_left - stride_right :]
    # Last chunk
							if len(A_						) > stride_left:
														_lowerCamelCase						:    Dict         =			{'''raw''': acc, '''stride''': (_stride_left, 0)}
														if stream:
																					_lowerCamelCase						:    Dict         =			False
														yield item







def 	snake_case_  (				A_ :		Any,    A_ :		int						):


							'''simple docstring'''





							_lowerCamelCase						:    Union[str, Any]         =			2**24  # 16Mo
							try:
														with subprocess.Popen(A_,    stdout=subprocess.PIPE,    bufsize=A_						) as ffmpeg_process:
																					while True:
																												_lowerCamelCase						:    Union[str, Any]         =			ffmpeg_process.stdout.read(A_						)
																												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







"""simple docstring"""






from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
   from PIL import Image

   from ..image_utils import load_image

if is_torch_available():
   import torch

   from transformers.modeling_outputs import BaseModelOutput

   from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

lowerCAmelCase__      =    logging.get_logger(__name__)






@add_end_docstrings(_lowercase)
class 	__snake_case	(     _lowercase):




  def __init__(			self					:						Any						, **__lowerCAmelCase					:						Union[str, Any]		):






         """simple docstring"""






         super().__init__(**__lowerCAmelCase		)

         if self.framework == "tf":
                raise ValueError(f'''The {self.__class__} is only available in PyTorch.'''		)

         requires_backends(self						, '''vision'''		)
         self.check_model_type(__lowerCAmelCase		)




  def __call__(			self					:						Dict						, __lowerCAmelCase					:						Union[str, "Image.Image", List[Dict[str, Any]]]						, __lowerCAmelCase					:						Union[str, List[str]] = None						, **__lowerCAmelCase					:						int						, ):






         """simple docstring"""






         if "text_queries" in kwargs:
                _lowerCamelCase						:    List[Any]         =			kwargs.pop('''text_queries'''		)

         if isinstance(__lowerCAmelCase						, (str, Image.Image)		):
                _lowerCamelCase						:    Optional[int]         =			{'''image''': image, '''candidate_labels''': candidate_labels}
         else:
                _lowerCamelCase						:    List[Any]         =			image
         _lowerCamelCase						:    List[str]         =			super().__call__(__lowerCAmelCase						, **__lowerCAmelCase		)
         return results




  def 						SCREAMING_SNAKE_CASE    (			self					:						List[Any]						, **__lowerCAmelCase					:						int		):






         """simple docstring"""






         _lowerCamelCase						:    int         =			{}
         if "threshold" in kwargs:
                _lowerCamelCase						:    Optional[Any]         =			kwargs['''threshold''']
         if "top_k" in kwargs:
                _lowerCamelCase						:    int         =			kwargs['''top_k''']
         return {}, {}, postprocess_params




  def 						SCREAMING_SNAKE_CASE    (			self					:						List[Any]						, __lowerCAmelCase					:						Union[str, Any]		):






         """simple docstring"""






         _lowerCamelCase						:    int         =			load_image(inputs['''image''']		)
         _lowerCamelCase						:    Optional[Any]         =			inputs['''candidate_labels''']
         if isinstance(__lowerCAmelCase						, __lowerCAmelCase		):
                _lowerCamelCase						:    int         =			candidate_labels.split(''','''		)

         _lowerCamelCase						:    Tuple         =			torch.tensor([[image.height, image.width]]						, dtype=torch.intaa		)
         for i, candidate_label in enumerate(__lowerCAmelCase		):
                _lowerCamelCase						:    Any         =			self.tokenizer(__lowerCAmelCase						, return_tensors=self.framework		)
                _lowerCamelCase						:    Optional[Any]         =			self.image_processor(__lowerCAmelCase						, return_tensors=self.framework		)
                yield {
                    "is_last": i == len(__lowerCAmelCase		) - 1,
                    "target_size": target_size,
                    "candidate_label": candidate_label,
                    **text_inputs,
                    **image_features,
                }




  def 						SCREAMING_SNAKE_CASE    (			self					:						Any						, __lowerCAmelCase					:						List[Any]		):






         """simple docstring"""






         _lowerCamelCase						:    Optional[Any]         =			model_inputs.pop('''target_size'''		)
         _lowerCamelCase						:    List[Any]         =			model_inputs.pop('''candidate_label'''		)
         _lowerCamelCase						:    Dict         =			model_inputs.pop('''is_last'''		)

         _lowerCamelCase						:    str         =			self.model(**__lowerCAmelCase		)

         _lowerCamelCase						:    Optional[Any]         =			{'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs}
         return model_outputs




  def 						SCREAMING_SNAKE_CASE    (			self					:						Optional[Any]						, __lowerCAmelCase					:						Any						, __lowerCAmelCase					:						Union[str, Any]=0.1						, __lowerCAmelCase					:						Optional[Any]=None		):






         """simple docstring"""






         _lowerCamelCase						:    str         =			[]
         for model_output in model_outputs:
                _lowerCamelCase						:    Any         =			model_output['''candidate_label''']
                _lowerCamelCase						:    Union[str, Any]         =			BaseModelOutput(__lowerCAmelCase		)
                _lowerCamelCase						:    Tuple         =			self.image_processor.post_process_object_detection(
                    outputs=__lowerCAmelCase						, threshold=__lowerCAmelCase						, target_sizes=model_output['''target_size''']		)[0]

                for index in outputs["scores"].nonzero():
                       _lowerCamelCase						:    Tuple         =			outputs['''scores'''][index].item()
                       _lowerCamelCase						:    Optional[Any]         =			self._get_bounding_box(outputs['''boxes'''][index][0]		)

                       _lowerCamelCase						:    Optional[Any]         =			{'''score''': score, '''label''': label, '''box''': box}
                       results.append(__lowerCAmelCase		)

         _lowerCamelCase						:    int         =			sorted(__lowerCAmelCase						, key=lambda __lowerCAmelCase		: x["score"]						, reverse=__lowerCAmelCase		)
         if top_k:
                _lowerCamelCase						:    Dict         =			results[:top_k]

         return results




  def 						SCREAMING_SNAKE_CASE    (			self					:						Any						, __lowerCAmelCase					:						"torch.Tensor"		):






         """simple docstring"""






         if self.framework != "pt":
                raise ValueError('''The ZeroShotObjectDetectionPipeline is only available in PyTorch.'''		)
         _lowerCamelCase      ,   _lowerCamelCase      ,   _lowerCamelCase      ,   _lowerCamelCase						:    Dict         =			box.int().tolist()
         _lowerCamelCase						:    Union[str, Any]         =			{
             '''xmin''': xmin,
             '''ymin''': ymin,
             '''xmax''': xmax,
             '''ymax''': ymax,
         }
         return bbox


