

import copy
import os
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union


if TYPE_CHECKING:
			from ...processing_utils import ProcessorMixin
			from ...utils import TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


a__												=						logging.get_logger(__name__)

a__												=						{
    '''google/owlvit-base-patch32''': '''https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json''',
    '''google/owlvit-base-patch16''': '''https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json''',
    '''google/owlvit-large-patch14''': '''https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json''',
}

class 							UpperCAmelCase_						(     __lowercase  ):
							"""simple docstring"""







							UpperCAmelCase__			:		List[str]             =       "owlvit_text_model"


							def __init__(     self			,				_a=4_9_4_0_8			,				_a=5_1_2			,				_a=2_0_4_8			,				_a=1_2			,				_a=8			,				_a=1_6			,				_a="quick_gelu"			,				_a=1e-5			,				_a=0.0			,				_a=0.02			,				_a=1.0			,				_a=0			,				_a=4_9_4_0_6			,				_a=4_9_4_0_7			,				**_a			,				)       ->       int:
												super().__init__(pad_token_id=_a			,				bos_token_id=_a			,				eos_token_id=_a			,				**_a			)

												_a      :       Tuple   =						vocab_size
												_a      :       Tuple   =						hidden_size
												_a      :       Optional[int]   =						intermediate_size
												_a      :       Any   =						num_hidden_layers
												_a      :       int   =						num_attention_heads
												_a      :       Tuple   =						max_position_embeddings
												_a      :       List[Any]   =						hidden_act
												_a      :       str   =						layer_norm_eps
												_a      :       Dict   =						attention_dropout
												_a      :       Any   =						initializer_range
												_a      :       Union[str, Any]   =						initializer_factor




							@classmethod
							def 							__lowercase							(     cls			,				_a			,				**_a			)       ->       "PretrainedConfig":
												cls._set_token_in_kwargs(_a			)

												_a ,   _a      :       Optional[int]   =						cls.get_config_dict(_a			,				**_a			)

												# get the text config dict if we are loading from OwlViTConfig
												if config_dict.get('''model_type'''			) == "owlvit":
																	_a      :       int   =						config_dict['''text_config''']

												if "model_type" in config_dict and hasattr(cls			,				'''model_type'''			) and config_dict["model_type"] != cls.model_type:
																	logger.warning(
																	    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
																	    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""			)

												return cls.from_dict(_a			,				**_a			)



class 							UpperCAmelCase_						(     __lowercase  ):
							"""simple docstring"""







							UpperCAmelCase__			:		int             =       "owlvit_vision_model"


							def __init__(     self			,				_a=7_6_8			,				_a=3_0_7_2			,				_a=1_2			,				_a=1_2			,				_a=3			,				_a=7_6_8			,				_a=3_2			,				_a="quick_gelu"			,				_a=1e-5			,				_a=0.0			,				_a=0.02			,				_a=1.0			,				**_a			,				)       ->       Dict:
												super().__init__(**_a			)

												_a      :       Dict   =						hidden_size
												_a      :       Optional[Any]   =						intermediate_size
												_a      :       Optional[Any]   =						num_hidden_layers
												_a      :       int   =						num_attention_heads
												_a      :       int   =						num_channels
												_a      :       int   =						image_size
												_a      :       Dict   =						patch_size
												_a      :       List[str]   =						hidden_act
												_a      :       Tuple   =						layer_norm_eps
												_a      :       int   =						attention_dropout
												_a      :       Any   =						initializer_range
												_a      :       Dict   =						initializer_factor




							@classmethod
							def 							__lowercase							(     cls			,				_a			,				**_a			)       ->       "PretrainedConfig":
												cls._set_token_in_kwargs(_a			)

												_a ,   _a      :       Tuple   =						cls.get_config_dict(_a			,				**_a			)

												# get the vision config dict if we are loading from OwlViTConfig
												if config_dict.get('''model_type'''			) == "owlvit":
																	_a      :       str   =						config_dict['''vision_config''']

												if "model_type" in config_dict and hasattr(cls			,				'''model_type'''			) and config_dict["model_type"] != cls.model_type:
																	logger.warning(
																	    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
																	    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""			)

												return cls.from_dict(_a			,				**_a			)



class 							UpperCAmelCase_						(     __lowercase  ):
							"""simple docstring"""







							UpperCAmelCase__			:		Optional[int]             =       "owlvit"
							UpperCAmelCase__			:		str             =       True


							def __init__(     self			,				_a=None			,				_a=None			,				_a=5_1_2			,				_a=2.6592			,				_a=True			,				**_a			,				)       ->       Any:
												super().__init__(**_a			)

												if text_config is None:
																	_a      :       Union[str, Any]   =						{}
																	logger.info('''text_config is None. Initializing the OwlViTTextConfig with default values.'''			)

												if vision_config is None:
																	_a      :       List[str]   =						{}
																	logger.info('''vision_config is None. initializing the OwlViTVisionConfig with default values.'''			)

												_a      :       str   =						OwlViTTextConfig(**_a			)
												_a      :       Dict   =						OwlViTVisionConfig(**_a			)

												_a      :       int   =						projection_dim
												_a      :       Optional[int]   =						logit_scale_init_value
												_a      :       List[Any]   =						return_dict
												_a      :       Optional[Any]   =						1.0


							@classmethod
							def 							__lowercase							(     cls			,				_a			,				**_a			)       ->       "PretrainedConfig":
												cls._set_token_in_kwargs(_a			)

												_a ,   _a      :       Dict   =						cls.get_config_dict(_a			,				**_a			)

												if "model_type" in config_dict and hasattr(cls			,				'''model_type'''			) and config_dict["model_type"] != cls.model_type:
																	logger.warning(
																	    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
																	    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""			)

												return cls.from_dict(_a			,				**_a			)


							@classmethod
							def 							__lowercase							(     cls			,				_a			,				_a			,				**_a			)       ->       Dict:
												_a      :       int   =						{}
												_a      :       Optional[int]   =						text_config
												_a      :       Optional[Any]   =						vision_config

												return cls.from_dict(_a			,				**_a			)




							def 							__lowercase							(     self			)       ->       Union[str, Any]:
												_a      :       Any   =						copy.deepcopy(self.__dict__			)
												_a      :       Optional[int]   =						self.text_config.to_dict()
												_a      :       Optional[Any]   =						self.vision_config.to_dict()
												_a      :       Union[str, Any]   =						self.__class__.model_type
												return output



class 							UpperCAmelCase_						(     __lowercase  ):
							"""simple docstring"""







							@property
							def 							__lowercase							(     self			)       ->       Mapping[str, Mapping[int, str]]:
												return OrderedDict(
												    [
												        ('''input_ids''', {0: '''batch''', 1: '''sequence'''}),
												        ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
												        ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}),
												    ]			)


							@property
							def 							__lowercase							(     self			)       ->       Mapping[str, Mapping[int, str]]:
												return OrderedDict(
												    [
												        ('''logits_per_image''', {0: '''batch'''}),
												        ('''logits_per_text''', {0: '''batch'''}),
												        ('''text_embeds''', {0: '''batch'''}),
												        ('''image_embeds''', {0: '''batch'''}),
												    ]			)


							@property
							def 							__lowercase							(     self			)       ->       float:
												return 1e-4


							def 							__lowercase							(     self			,				_a			,				_a = -1			,				_a = -1			,				_a = None			,				)       ->       Mapping[str, Any]:
												_a      :       Dict   =						super().generate_dummy_inputs(
												    processor.tokenizer			,				batch_size=_a			,				seq_length=_a			,				framework=_a			)
												_a      :       Optional[Any]   =						super().generate_dummy_inputs(
												    processor.image_processor			,				batch_size=_a			,				framework=_a			)
												return {**text_input_dict, **image_input_dict}




							@property
							def 							__lowercase							(     self			)       ->       int:
												return 1_4






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

import numpy as np



def   __UpperCAmelCase					(      __a :     bytes						,__a :     int      )     ->	np.array:

					"""simple docstring"""

					_a      :       int   =						F"""{sampling_rate}"""
					_a      :       str   =						'''1'''
					_a      :       Optional[int]   =						'''f32le'''
					_a      :       Optional[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:
															_a      :       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
					_a      :       Optional[Any]   =						output_stream[0]
					_a      :       Optional[int]   =						np.frombuffer(__a						,np.floataa      )
					if audio.shape[0] == 0:
										raise ValueError('''Malformed soundfile'''      )
					return audio



def   __UpperCAmelCase					(      __a :     int						,__a :     float						,__a :     str = "f32le"						,)     ->	str:

					"""simple docstring"""

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

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

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



def   __UpperCAmelCase					(      __a :     int						,__a :     float						,__a :     Optional[int] = None						,__a :     Optional[Union[Tuple[float, float], float]] = None						,__a :     str = "f32le"						,)     ->	Optional[int]:

					"""simple docstring"""

					if stream_chunk_s is not None:
										_a      :       Tuple   =						stream_chunk_s
					else:
										_a      :       Tuple   =						chunk_length_s

					_a      :       Tuple   =						ffmpeg_microphone(__a						,__a						,format_for_conversion=__a      )
					if format_for_conversion == "s16le":
										_a      :       Any   =						np.intaa
										_a      :       Optional[int]   =						2
					elif format_for_conversion == "f32le":
										_a      :       Dict   =						np.floataa
										_a      :       List[Any]   =						4
					else:
										raise ValueError(F"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`"""      )

					if stride_length_s is None:
										_a      :       List[Any]   =						chunk_length_s / 6
					_a      :       Optional[int]   =						int(round(sampling_rate * chunk_length_s      )      ) * size_of_sample
					if isinstance(__a						,(int, float)      ):
										_a      :       Optional[Any]   =						[stride_length_s, stride_length_s]

					_a      :       Optional[Any]   =						int(round(sampling_rate * stride_length_s[0]      )      ) * size_of_sample
					_a      :       str   =						int(round(sampling_rate * stride_length_s[1]      )      ) * size_of_sample
					_a      :       Optional[Any]   =						datetime.datetime.now()
					_a      :       Tuple   =						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
										_a      :       Dict   =						np.frombuffer(item['''raw''']						,dtype=__a      )
										_a      :       Dict   =						(
										    item['''stride'''][0] // size_of_sample,
										    item['''stride'''][1] // size_of_sample,
										)
										_a      :       str   =						sampling_rate
										audio_time += delta
										if datetime.datetime.now() > audio_time + 10 * delta:
															# We're late !! SKIP
															continue
										yield item



def   __UpperCAmelCase					(      __a :     Optional[int]						,__a :     int						,__a :     Tuple[int, int]						,__a :     bool = False      )     ->	Optional[int]:

					"""simple docstring"""

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







def   __UpperCAmelCase					(      __a :     int						,__a :     int      )     ->	Tuple:

					"""simple docstring"""

					_a      :       Dict   =						2**24  # 16Mo
					try:
										with subprocess.Popen(__a						,stdout=subprocess.PIPE						,bufsize=__a      ) as ffmpeg_process:
															while True:
																				_a      :       int   =						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



