



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


__snake_case		:Optional[Any]   	=  logging.get_logger(__name__)

__snake_case		:Any   	=  {
    '''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 					_A (			__UpperCAmelCase					):
       UpperCamelCase__						:					List[str]		      =		'''owlvit_text_model'''



       def __init__(	self							:  str  ,	__SCREAMING_SNAKE_CASE							:  Dict=49_408  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]=512  ,	__SCREAMING_SNAKE_CASE							:  str=2_048  ,	__SCREAMING_SNAKE_CASE							:  int=12  ,	__SCREAMING_SNAKE_CASE							:  List[str]=8  ,	__SCREAMING_SNAKE_CASE							:  Dict=16  ,	__SCREAMING_SNAKE_CASE							:  Union[str, Any]="quick_gelu"  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]=1E-5  ,	__SCREAMING_SNAKE_CASE							:  List[str]=0.0  ,	__SCREAMING_SNAKE_CASE							:  str=0.02  ,	__SCREAMING_SNAKE_CASE							:  List[Any]=1.0  ,	__SCREAMING_SNAKE_CASE							:  Dict=0  ,	__SCREAMING_SNAKE_CASE							:  Tuple=49_406  ,	__SCREAMING_SNAKE_CASE							:  List[Any]=49_407  ,	**__SCREAMING_SNAKE_CASE							:  Union[str, Any]  ,	):


           '''simple docstring'''

           super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE  ,	bos_token_id=__SCREAMING_SNAKE_CASE  ,	eos_token_id=__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)

           __a		 =       vocab_size
           __a		 =       hidden_size
           __a		 =       intermediate_size
           __a		 =       num_hidden_layers
           __a		 =       num_attention_heads
           __a		 =       max_position_embeddings
           __a		 =       hidden_act
           __a		 =       layer_norm_eps
           __a		 =       attention_dropout
           __a		 =       initializer_range
           __a		 =       initializer_factor





       @classmethod
       def 	_lowerCamelCase    (	cls							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  Union[str, os.PathLike]  ,	**__SCREAMING_SNAKE_CASE							:  List[Any]):


           '''simple docstring'''

           cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE)

           __a ,     __a		 =       cls.get_config_dict(__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)

           # get the text config dict if we are loading from OwlViTConfig
           if config_dict.get('''model_type''') == "owlvit":
               __a		 =       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(__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)


class 					_A (			__UpperCAmelCase					):
       UpperCamelCase__						:					List[Any]		      =		'''owlvit_vision_model'''



       def __init__(	self							:  str  ,	__SCREAMING_SNAKE_CASE							:  Union[str, Any]=768  ,	__SCREAMING_SNAKE_CASE							:  Union[str, Any]=3_072  ,	__SCREAMING_SNAKE_CASE							:  List[Any]=12  ,	__SCREAMING_SNAKE_CASE							:  Any=12  ,	__SCREAMING_SNAKE_CASE							:  Union[str, Any]=3  ,	__SCREAMING_SNAKE_CASE							:  str=768  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]=32  ,	__SCREAMING_SNAKE_CASE							:  Union[str, Any]="quick_gelu"  ,	__SCREAMING_SNAKE_CASE							:  List[str]=1E-5  ,	__SCREAMING_SNAKE_CASE							:  str=0.0  ,	__SCREAMING_SNAKE_CASE							:  List[str]=0.02  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]=1.0  ,	**__SCREAMING_SNAKE_CASE							:  Union[str, Any]  ,	):


           '''simple docstring'''

           super().__init__(**__SCREAMING_SNAKE_CASE)

           __a		 =       hidden_size
           __a		 =       intermediate_size
           __a		 =       num_hidden_layers
           __a		 =       num_attention_heads
           __a		 =       num_channels
           __a		 =       image_size
           __a		 =       patch_size
           __a		 =       hidden_act
           __a		 =       layer_norm_eps
           __a		 =       attention_dropout
           __a		 =       initializer_range
           __a		 =       initializer_factor





       @classmethod
       def 	_lowerCamelCase    (	cls							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  Union[str, os.PathLike]  ,	**__SCREAMING_SNAKE_CASE							:  str):


           '''simple docstring'''

           cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE)

           __a ,     __a		 =       cls.get_config_dict(__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)

           # get the vision config dict if we are loading from OwlViTConfig
           if config_dict.get('''model_type''') == "owlvit":
               __a		 =       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(__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)


class 					_A (			__UpperCAmelCase					):
       UpperCamelCase__						:					List[Any]		      =		'''owlvit'''
       UpperCamelCase__						:					Dict		      =		True



       def __init__(	self							:  Optional[Any]  ,	__SCREAMING_SNAKE_CASE							:  int=None  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]=None  ,	__SCREAMING_SNAKE_CASE							:  Dict=512  ,	__SCREAMING_SNAKE_CASE							:  str=2.65_92  ,	__SCREAMING_SNAKE_CASE							:  Dict=True  ,	**__SCREAMING_SNAKE_CASE							:  Optional[Any]  ,	):


           '''simple docstring'''

           super().__init__(**__SCREAMING_SNAKE_CASE)

           if text_config is None:
               __a		 =       {}
               logger.info('''text_config is None. Initializing the OwlViTTextConfig with default values.''')

           if vision_config is None:
               __a		 =       {}
               logger.info('''vision_config is None. initializing the OwlViTVisionConfig with default values.''')

           __a		 =       OwlViTTextConfig(**__SCREAMING_SNAKE_CASE)
           __a		 =       OwlViTVisionConfig(**__SCREAMING_SNAKE_CASE)

           __a		 =       projection_dim
           __a		 =       logit_scale_init_value
           __a		 =       return_dict
           __a		 =       1.0



       @classmethod
       def 	_lowerCamelCase    (	cls							:  str  ,	__SCREAMING_SNAKE_CASE							:  Union[str, os.PathLike]  ,	**__SCREAMING_SNAKE_CASE							:  Any):


           '''simple docstring'''

           cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE)

           __a ,     __a		 =       cls.get_config_dict(__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)

           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(__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)



       @classmethod
       def 	_lowerCamelCase    (	cls							:  Union[str, Any]  ,	__SCREAMING_SNAKE_CASE							:  Dict  ,	__SCREAMING_SNAKE_CASE							:  Dict  ,	**__SCREAMING_SNAKE_CASE							:  str):


           '''simple docstring'''

           __a		 =       {}
           __a		 =       text_config
           __a		 =       vision_config

           return cls.from_dict(__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)





       def 	_lowerCamelCase    (	self							:  Dict):


           '''simple docstring'''

           __a		 =       copy.deepcopy(self.__dict__)
           __a		 =       self.text_config.to_dict()
           __a		 =       self.vision_config.to_dict()
           __a		 =       self.__class__.model_type
           return output


class 					_A (			__UpperCAmelCase					):



       @property
       def 	_lowerCamelCase    (	self							:  Optional[Any]):


           '''simple docstring'''

           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 	_lowerCamelCase    (	self							:  List[Any]):


           '''simple docstring'''

           return OrderedDict(
               [
                   ('''logits_per_image''', {0: '''batch'''}),
                   ('''logits_per_text''', {0: '''batch'''}),
                   ('''text_embeds''', {0: '''batch'''}),
                   ('''image_embeds''', {0: '''batch'''}),
               ])



       @property
       def 	_lowerCamelCase    (	self							:  List[Any]):


           '''simple docstring'''

           return 1E-4



       def 	_lowerCamelCase    (	self							:  int  ,	__SCREAMING_SNAKE_CASE							:  "ProcessorMixin"  ,	__SCREAMING_SNAKE_CASE							:  int = -1  ,	__SCREAMING_SNAKE_CASE							:  int = -1  ,	__SCREAMING_SNAKE_CASE							:  Optional["TensorType"] = None  ,	):


           '''simple docstring'''

           __a		 =       super().generate_dummy_inputs(
               processor.tokenizer  ,	batch_size=__SCREAMING_SNAKE_CASE  ,	seq_length=__SCREAMING_SNAKE_CASE  ,	framework=__SCREAMING_SNAKE_CASE)
           __a		 =       super().generate_dummy_inputs(
               processor.image_processor  ,	batch_size=__SCREAMING_SNAKE_CASE  ,	framework=__SCREAMING_SNAKE_CASE)
           return {**text_input_dict, **image_input_dict}





       @property
       def 	_lowerCamelCase    (	self							:  List[Any]):


           '''simple docstring'''

           return 14










from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('''3.8'''):
 import importlib_metadata
else:
 import importlib.metadata as importlib_metadata


__snake_case		:int   	=  ''''''


if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''):

 class 					_A (			tr.AbstractTransform					):



        def __init__(	self							:  List[Any]  ,	__SCREAMING_SNAKE_CASE							:  str = " "):


            '''simple docstring'''

            __a		 =       sentence_delimiter



        def 	_lowerCamelCase    (	self							:  Dict  ,	__SCREAMING_SNAKE_CASE							:  str):


            '''simple docstring'''

            return list(__SCREAMING_SNAKE_CASE)





        def 	_lowerCamelCase    (	self							:  int  ,	__SCREAMING_SNAKE_CASE							:  List[str]):


            '''simple docstring'''

            __a		 =       []
            for sent_idx, sentence in enumerate(__SCREAMING_SNAKE_CASE):
                chars.extend(self.process_string(__SCREAMING_SNAKE_CASE))
                if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__SCREAMING_SNAKE_CASE) - 1:
                    chars.append(self.sentence_delimiter)
            return chars


 __snake_case		:Any   	=  tr.Compose(
     [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
 )
else:
 __snake_case		:Optional[int]   	=  tr.Compose(
     [
         tr.RemoveMultipleSpaces(),
         tr.Strip(),
         tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
         tr.ReduceToListOfListOfChars(),
     ]
 )


__snake_case		:Optional[int]   	=  '''\
@inproceedings{inproceedings,
    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
    year = {2004},
    month = {01},
    pages = {},
    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
'''

__snake_case		:Tuple   	=  '''\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).

CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
'''

__snake_case		:Tuple   	=  '''
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = ["this is the prediction", "there is an other sample"]
    >>> references = ["this is the reference", "there is another one"]
    >>> cer = datasets.load_metric("cer")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
'''

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,_KWARGS_DESCRIPTION					)
class 					_A (			datasets.Metric					):



       def 	_lowerCamelCase    (	self							:  Optional[Any]):


           '''simple docstring'''

           return datasets.MetricInfo(
               description=_DESCRIPTION  ,	citation=_CITATION  ,	inputs_description=_KWARGS_DESCRIPTION  ,	features=datasets.Features(
                   {
                       '''predictions''': datasets.Value('''string'''  ,	id='''sequence'''),
                       '''references''': datasets.Value('''string'''  ,	id='''sequence'''),
                   })  ,	codebase_urls=['''https://github.com/jitsi/jiwer/''']  ,	reference_urls=[
                   '''https://en.wikipedia.org/wiki/Word_error_rate''',
                   '''https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates''',
               ]  ,	)





       def 	_lowerCamelCase    (	self							:  Optional[int]  ,	__SCREAMING_SNAKE_CASE							:  str  ,	__SCREAMING_SNAKE_CASE							:  List[Any]  ,	__SCREAMING_SNAKE_CASE							:  Dict=False):


           '''simple docstring'''

           if concatenate_texts:
               return jiwer.compute_measures(
                   __SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE  ,	truth_transform=__SCREAMING_SNAKE_CASE  ,	hypothesis_transform=__SCREAMING_SNAKE_CASE  ,	)["wer"]

           __a		 =       0
           __a		 =       0
           for prediction, reference in zip(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE):
               __a		 =       jiwer.compute_measures(
                   __SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE  ,	truth_transform=__SCREAMING_SNAKE_CASE  ,	hypothesis_transform=__SCREAMING_SNAKE_CASE  ,	)
               incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
               total += measures["substitutions"] + measures["deletions"] + measures["hits"]

           return incorrect / total





