import torch
from torch import nn

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin





class      lowerCAmelCase						(					_a			,		_a			):



     @register_to_config
     def __init__(					self				,      *,
         lowerCAmelCase__ = 4				,      lowerCAmelCase__ = 768				,      lowerCAmelCase__				,      lowerCAmelCase__				,      ):
            super().__init__()

            _A=	nn.Parameter(torch.zeros(lowerCAmelCase__       )       )

            # parameters for additional clip time embeddings
            _A=	nn.Linear(lowerCAmelCase__				,      lowerCAmelCase__       )
            _A=	nn.Linear(lowerCAmelCase__				,      lowerCAmelCase__       )

            # parameters for encoder hidden states
            _A=	clip_extra_context_tokens
            _A=	nn.Linear(
                lowerCAmelCase__				,      self.clip_extra_context_tokens * cross_attention_dim       )
            _A=	nn.Linear(lowerCAmelCase__				,      lowerCAmelCase__       )
            _A=	nn.LayerNorm(lowerCAmelCase__       )





     def 			a__  (					self				,      *, lowerCAmelCase__				,      lowerCAmelCase__				,      lowerCAmelCase__				,      lowerCAmelCase__       ):
            if do_classifier_free_guidance:
                   # Add the classifier free guidance embeddings to the image embeddings
                   _A=	image_embeddings.shape[0]
                   _A=	self.learned_classifier_free_guidance_embeddings.unsqueeze(0       )
                   _A=	classifier_free_guidance_embeddings.expand(
                       lowerCAmelCase__				,      -1       )
                   _A=	torch.cat([classifier_free_guidance_embeddings, image_embeddings]				,      dim=0       )

            # The image embeddings batch size and the text embeddings batch size are equal
            assert image_embeddings.shape[0] == prompt_embeds.shape[0]

            _A=	prompt_embeds.shape[0]

            # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and
            # adding CLIP embeddings to the existing timestep embedding, ...
            _A=	self.embedding_proj(lowerCAmelCase__       )
            _A=	self.clip_image_embeddings_project_to_time_embeddings(lowerCAmelCase__       )
            _A=	time_projected_image_embeddings + time_projected_prompt_embeds

            # ... and by projecting CLIP embeddings into four
            # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder"
            _A=	self.clip_extra_context_tokens_proj(lowerCAmelCase__       )
            _A=	clip_extra_context_tokens.reshape(lowerCAmelCase__				,      -1				,      self.clip_extra_context_tokens       )
            _A=	clip_extra_context_tokens.permute(0				,      2				,      1       )

            _A=	self.encoder_hidden_states_proj(lowerCAmelCase__       )
            _A=	self.text_encoder_hidden_states_norm(lowerCAmelCase__       )
            _A=	torch.cat([clip_extra_context_tokens, text_encoder_hidden_states]				,      dim=1       )

            return text_encoder_hidden_states, additive_clip_time_embeddings
from jiwer import compute_measures

import datasets


UpperCAmelCase_								=							'''\
@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.}
}
'''

UpperCAmelCase_								=							'''\
Word error rate (WER) is a common metric of the performance of an automatic speech recognition system.

The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.

This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.

Word error rate can then be computed as:

WER = (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 words,
N is the number of words in the reference (N=S+D+C).

This value indicates the average number of errors per reference word. The lower the value, the better the
performance of the ASR system with a WER of 0 being a perfect score.
'''

UpperCAmelCase_								=							'''
Compute WER score of transcribed segments against references.

Args:
    references: List of references for each speech input.
    predictions: List of transcriptions to score.
    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.

Returns:
    (float): the word error rate

Examples:

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





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



     def 			a__  (					self       ):
            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',
                ]				,      )





     def 			a__  (					self				,      lowerCAmelCase__=None				,      lowerCAmelCase__=None				,      lowerCAmelCase__=False       ):
            if concatenate_texts:
                   return compute_measures(lowerCAmelCase__				,      lowerCAmelCase__       )["wer"]
            else:
                   _A=	0
                   _A=	0
                   for prediction, reference in zip(lowerCAmelCase__				,      lowerCAmelCase__       ):
                          _A=	compute_measures(lowerCAmelCase__				,      lowerCAmelCase__       )
                          incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                          total += measures["substitutions"] + measures["deletions"] + measures["hits"]
                   return incorrect / total