import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


UpperCAmelCase							   =      """\
@inproceedings{Rajpurkar2016SQuAD10,
  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},
  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},
  booktitle={EMNLP},
  year={2016}
}
"""

UpperCAmelCase							   =      """
This metric wrap the official scoring script for version 2 of the Stanford Question
Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.

SQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions
written adversarially by crowdworkers to look similar to answerable ones.
To do well on SQuAD2.0, systems must not only answer questions when possible, but also
determine when no answer is supported by the paragraph and abstain from answering.
"""

UpperCAmelCase							   =      """
Computes SQuAD v2 scores (F1 and EM).
Args:
    predictions: List of triple for question-answers to score with the following elements:
        - the question-answer 'id' field as given in the references (see below)
        - the text of the answer
        - the probability that the question has no answer
    references: List of question-answers dictionaries with the following key-values:
            - 'id': id of the question-answer pair (see above),
            - 'answers': a list of Dict {'text': text of the answer as a string}
    no_answer_threshold: float
        Probability threshold to decide that a question has no answer.
Returns:
    'exact': Exact match (the normalized answer exactly match the gold answer)
    'f1': The F-score of predicted tokens versus the gold answer
    'total': Number of score considered
    'HasAns_exact': Exact match (the normalized answer exactly match the gold answer)
    'HasAns_f1': The F-score of predicted tokens versus the gold answer
    'HasAns_total': Number of score considered
    'NoAns_exact': Exact match (the normalized answer exactly match the gold answer)
    'NoAns_f1': The F-score of predicted tokens versus the gold answer
    'NoAns_total': Number of score considered
    'best_exact': Best exact match (with varying threshold)
    'best_exact_thresh': No-answer probability threshold associated to the best exact match
    'best_f1': Best F1 (with varying threshold)
    'best_f1_thresh': No-answer probability threshold associated to the best F1
Examples:

    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22', 'no_answer_probability': 0.}]
    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]
    >>> squad_v2_metric = datasets.load_metric(\"squad_v2\")
    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact': 100.0, 'f1': 100.0, 'total': 1, 'HasAns_exact': 100.0, 'HasAns_f1': 100.0, 'HasAns_total': 1, 'best_exact': 100.0, 'best_exact_thresh': 0.0, 'best_f1': 100.0, 'best_f1_thresh': 0.0}
"""






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION       ,      _KWARGS_DESCRIPTION	)
class 							_SCREAMING_SNAKE_CASE(   datasets.Metric	):
   def _lowercase(    self    )	->Optional[int]:
        return datasets.MetricInfo(
            description=_DESCRIPTION							,     citation=_CITATION							,     inputs_description=_KWARGS_DESCRIPTION							,     features=datasets.Features(
                {
                    '''predictions''': {
                        '''id''': datasets.Value('''string'''    ),
                        '''prediction_text''': datasets.Value('''string'''    ),
                        '''no_answer_probability''': datasets.Value('''float32'''    ),
                    },
                    '''references''': {
                        '''id''': datasets.Value('''string'''    ),
                        '''answers''': datasets.features.Sequence(
                            {'''text''': datasets.Value('''string'''    ), '''answer_start''': datasets.Value('''int32'''    )}    ),
                    },
                }    )							,     codebase_urls=['''https://rajpurkar.github.io/SQuAD-explorer/''']							,     reference_urls=['''https://rajpurkar.github.io/SQuAD-explorer/''']							,     )


   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_=1.0    )	->Optional[Any]:
        a  :    int				=						{p['''id''']: p['''no_answer_probability'''] for p in predictions}
        a  :    int				=						[{'''paragraphs''': [{'''qas''': references}]}]
        a  :    Dict				=						{p['''id''']: p['''prediction_text'''] for p in predictions}

        a  :    str				=						make_qid_to_has_ans(lowerCAmelCase_    )  # maps qid to True/False
        a  :    Dict				=						[k for k, v in qid_to_has_ans.items() if v]
        a  :    Optional[int]				=						[k for k, v in qid_to_has_ans.items() if not v]

        a  :    Optional[int]				=						get_raw_scores(lowerCAmelCase_							,     lowerCAmelCase_    )
        a  :    Optional[int]				=						apply_no_ans_threshold(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )
        a  :    Tuple				=						apply_no_ans_threshold(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )
        a  :    str				=						make_eval_dict(lowerCAmelCase_							,     lowerCAmelCase_    )

        if has_ans_qids:
             a  :    Union[str, Any]				=						make_eval_dict(lowerCAmelCase_							,     lowerCAmelCase_							,     qid_list=lowerCAmelCase_    )
             merge_eval(lowerCAmelCase_							,     lowerCAmelCase_							,     '''HasAns'''    )
        if no_ans_qids:
             a  :    Optional[Any]				=						make_eval_dict(lowerCAmelCase_							,     lowerCAmelCase_							,     qid_list=lowerCAmelCase_    )
             merge_eval(lowerCAmelCase_							,     lowerCAmelCase_							,     '''NoAns'''    )
        find_all_best_thresh(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )
        return dict(lowerCAmelCase_    )
from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block






@dataclass
class 							_SCREAMING_SNAKE_CASE(   snake_case__	):
   UpperCamelCase_				:						torch.FloatTensor






class 							_SCREAMING_SNAKE_CASE(   snake_case__       ,      snake_case__	):
   @register_to_config
   def __init__(    self							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = 3							,     lowerCAmelCase_ = 3							,     lowerCAmelCase_ = False							,     lowerCAmelCase_ = "positional"							,     lowerCAmelCase_ = 0							,     lowerCAmelCase_ = True							,     lowerCAmelCase_ = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")							,     lowerCAmelCase_ = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")							,     lowerCAmelCase_ = (2_24, 4_48, 6_72, 8_96)							,     lowerCAmelCase_ = 2							,     lowerCAmelCase_ = 1							,     lowerCAmelCase_ = 1							,     lowerCAmelCase_ = "conv"							,     lowerCAmelCase_ = "conv"							,     lowerCAmelCase_ = "silu"							,     lowerCAmelCase_ = 8							,     lowerCAmelCase_ = 32							,     lowerCAmelCase_ = 1e-5							,     lowerCAmelCase_ = "default"							,     lowerCAmelCase_ = True							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = None							,     )	->Tuple:
        super().__init__()

        a  :    List[Any]				=						sample_size
        a  :    List[Any]				=						block_out_channels[0] * 4

        # Check inputs
        if len(lowerCAmelCase_    ) != len(lowerCAmelCase_    ):
             raise ValueError(
                 F"""Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."""    )

        if len(lowerCAmelCase_    ) != len(lowerCAmelCase_    ):
             raise ValueError(
                 F"""Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."""    )

        # input
        a  :    List[Any]				=						nn.Convad(lowerCAmelCase_							,     block_out_channels[0]							,     kernel_size=3							,     padding=(1, 1)    )

        # time
        if time_embedding_type == "fourier":
             a  :    List[Any]				=						GaussianFourierProjection(embedding_size=block_out_channels[0]							,     scale=16    )
             a  :    List[Any]				=						2 * block_out_channels[0]
        elif time_embedding_type == "positional":
             a  :    Dict				=						Timesteps(block_out_channels[0]							,     lowerCAmelCase_							,     lowerCAmelCase_    )
             a  :    List[str]				=						block_out_channels[0]

        a  :    List[str]				=						TimestepEmbedding(lowerCAmelCase_							,     lowerCAmelCase_    )

        # class embedding
        if class_embed_type is None and num_class_embeds is not None:
             a  :    Dict				=						nn.Embedding(lowerCAmelCase_							,     lowerCAmelCase_    )
        elif class_embed_type == "timestep":
             a  :    str				=						TimestepEmbedding(lowerCAmelCase_							,     lowerCAmelCase_    )
        elif class_embed_type == "identity":
             a  :    List[str]				=						nn.Identity(lowerCAmelCase_							,     lowerCAmelCase_    )
        else:
             a  :    Optional[Any]				=						None

        a  :    str				=						nn.ModuleList([]    )
        a  :    Any				=						None
        a  :    List[Any]				=						nn.ModuleList([]    )

        # down
        a  :    List[Any]				=						block_out_channels[0]
        for i, down_block_type in enumerate(lowerCAmelCase_    ):
             a  :    Dict				=						output_channel
             a  :    Union[str, Any]				=						block_out_channels[i]
             a  :    int				=						i == len(lowerCAmelCase_    ) - 1

             a  :    Tuple				=						get_down_block(
                 lowerCAmelCase_							,     num_layers=lowerCAmelCase_							,     in_channels=lowerCAmelCase_							,     out_channels=lowerCAmelCase_							,     temb_channels=lowerCAmelCase_							,     add_downsample=not is_final_block							,     resnet_eps=lowerCAmelCase_							,     resnet_act_fn=lowerCAmelCase_							,     resnet_groups=lowerCAmelCase_							,     attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel							,     downsample_padding=lowerCAmelCase_							,     resnet_time_scale_shift=lowerCAmelCase_							,     downsample_type=lowerCAmelCase_							,     )
             self.down_blocks.append(lowerCAmelCase_    )

        # mid
        a  :    int				=						UNetMidBlockaD(
            in_channels=block_out_channels[-1]							,     temb_channels=lowerCAmelCase_							,     resnet_eps=lowerCAmelCase_							,     resnet_act_fn=lowerCAmelCase_							,     output_scale_factor=lowerCAmelCase_							,     resnet_time_scale_shift=lowerCAmelCase_							,     attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]							,     resnet_groups=lowerCAmelCase_							,     add_attention=lowerCAmelCase_							,     )

        # up
        a  :    Optional[int]				=						list(reversed(lowerCAmelCase_    )    )
        a  :    Tuple				=						reversed_block_out_channels[0]
        for i, up_block_type in enumerate(lowerCAmelCase_    ):
             a  :    List[Any]				=						output_channel
             a  :    Optional[Any]				=						reversed_block_out_channels[i]
             a  :    Dict				=						reversed_block_out_channels[min(i + 1							,     len(lowerCAmelCase_    ) - 1    )]

             a  :    Any				=						i == len(lowerCAmelCase_    ) - 1

             a  :    List[Any]				=						get_up_block(
                 lowerCAmelCase_							,     num_layers=layers_per_block + 1							,     in_channels=lowerCAmelCase_							,     out_channels=lowerCAmelCase_							,     prev_output_channel=lowerCAmelCase_							,     temb_channels=lowerCAmelCase_							,     add_upsample=not is_final_block							,     resnet_eps=lowerCAmelCase_							,     resnet_act_fn=lowerCAmelCase_							,     resnet_groups=lowerCAmelCase_							,     attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel							,     resnet_time_scale_shift=lowerCAmelCase_							,     upsample_type=lowerCAmelCase_							,     )
             self.up_blocks.append(lowerCAmelCase_    )
             a  :    Any				=						output_channel

        # out
        a  :    str				=						norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4							,     32    )
        a  :    Tuple				=						nn.GroupNorm(num_channels=block_out_channels[0]							,     num_groups=lowerCAmelCase_							,     eps=lowerCAmelCase_    )
        a  :    Any				=						nn.SiLU()
        a  :    List[Any]				=						nn.Convad(block_out_channels[0]							,     lowerCAmelCase_							,     kernel_size=3							,     padding=1    )


   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = True							,     )	->Union[UNetaDOutput, Tuple]:
        # 0. center input if necessary
        if self.config.center_input_sample:
             a  :    Any				=						2 * sample - 1.0

        # 1. time
        a  :    Optional[Any]				=						timestep
        if not torch.is_tensor(lowerCAmelCase_    ):
             a  :    Dict				=						torch.tensor([timesteps]							,     dtype=torch.long							,     device=sample.device    )
        elif torch.is_tensor(lowerCAmelCase_    ) and len(timesteps.shape    ) == 0:
             a  :    Any				=						timesteps[None].to(sample.device    )

        # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
        a  :    Optional[Any]				=						timesteps * torch.ones(sample.shape[0]							,     dtype=timesteps.dtype							,     device=timesteps.device    )

        a  :    Dict				=						self.time_proj(lowerCAmelCase_    )

        # timesteps does not contain any weights and will always return f32 tensors
        # but time_embedding might actually be running in fp16. so we need to cast here.
        # there might be better ways to encapsulate this.
        a  :    Optional[Any]				=						t_emb.to(dtype=self.dtype    )
        a  :    Dict				=						self.time_embedding(lowerCAmelCase_    )

        if self.class_embedding is not None:
             if class_labels is None:
                  raise ValueError('''class_labels should be provided when doing class conditioning'''    )

             if self.config.class_embed_type == "timestep":
                  a  :    List[str]				=						self.time_proj(lowerCAmelCase_    )

             a  :    Any				=						self.class_embedding(lowerCAmelCase_    ).to(dtype=self.dtype    )
             a  :    Optional[int]				=						emb + class_emb

        # 2. pre-process
        a  :    int				=						sample
        a  :    Dict				=						self.conv_in(lowerCAmelCase_    )

        # 3. down
        a  :    Union[str, Any]				=						(sample,)
        for downsample_block in self.down_blocks:
             if hasattr(lowerCAmelCase_							,     '''skip_conv'''    ):
                  a			,							a			,							a  :    str				=						downsample_block(
                      hidden_states=lowerCAmelCase_							,     temb=lowerCAmelCase_							,     skip_sample=lowerCAmelCase_    )
             else:
                  a			,							a  :    List[str]				=						downsample_block(hidden_states=lowerCAmelCase_							,     temb=lowerCAmelCase_    )

             down_block_res_samples += res_samples

        # 4. mid
        a  :    str				=						self.mid_block(lowerCAmelCase_							,     lowerCAmelCase_    )

        # 5. up
        a  :    int				=						None
        for upsample_block in self.up_blocks:
             a  :    List[str]				=						down_block_res_samples[-len(upsample_block.resnets    ) :]
             a  :    Any				=						down_block_res_samples[: -len(upsample_block.resnets    )]

             if hasattr(lowerCAmelCase_							,     '''skip_conv'''    ):
                  a			,							a  :    Any				=						upsample_block(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )
             else:
                  a  :    Union[str, Any]				=						upsample_block(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )

        # 6. post-process
        a  :    Tuple				=						self.conv_norm_out(lowerCAmelCase_    )
        a  :    Optional[Any]				=						self.conv_act(lowerCAmelCase_    )
        a  :    Tuple				=						self.conv_out(lowerCAmelCase_    )

        if skip_sample is not None:
             sample += skip_sample

        if self.config.time_embedding_type == "fourier":
             a  :    Optional[Any]				=						timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]    )))    )
             a  :    int				=						sample / timesteps

        if not return_dict:
             return (sample,)

        return UNetaDOutput(sample=lowerCAmelCase_    )