




import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, LDMSuperResolutionPipeline, UNetaDModel, VQModel
from diffusers.utils import PIL_INTERPOLATION, floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch


enable_full_determinism()

class 	_lowerCamelCase  (     unittest.TestCase				):

      """simple docstring"""

      @property
      def  snake_case		(       self   :	Tuple			):
          __UpperCamelCase											=  1
          __UpperCamelCase											=  3
          __UpperCamelCase											=  (32, 32)

          __UpperCamelCase											=  floats_tensor((batch_size, num_channels) + sizes	,    rng=random.Random(0			)			).to(snake_case			)
          return image







      @property
      def  snake_case		(       self   :	List[str]			):
          torch.manual_seed(0			)
          __UpperCamelCase											=  UNetaDModel(
              block_out_channels=(32, 64)	,    layers_per_block=2	,    sample_size=32	,    in_channels=6	,    out_channels=3	,    down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')	,    up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')	,    )
          return model







      @property
      def  snake_case		(       self   :	int			):
          torch.manual_seed(0			)
          __UpperCamelCase											=  VQModel(
              block_out_channels=[32, 64]	,    in_channels=3	,    out_channels=3	,    down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']	,    up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']	,    latent_channels=3	,    )
          return model







      def  snake_case		(       self   :	List[Any]			):
          __UpperCamelCase											=  '''cpu'''
          __UpperCamelCase											=  self.dummy_uncond_unet
          __UpperCamelCase											=  DDIMScheduler()
          __UpperCamelCase											=  self.dummy_vq_model

          __UpperCamelCase											=  LDMSuperResolutionPipeline(unet=snake_case	,    vqvae=snake_case	,    scheduler=snake_case			)
          ldm.to(snake_case			)
          ldm.set_progress_bar_config(disable=snake_case			)

          __UpperCamelCase											=  self.dummy_image.to(snake_case			)

          __UpperCamelCase											=  torch.Generator(device=snake_case			).manual_seed(0			)
          __UpperCamelCase											=  ldm(image=snake_case	,    generator=snake_case	,    num_inference_steps=2	,    output_type='''numpy'''			).images

          __UpperCamelCase											=  image[0, -3:, -3:, -1]

          assert image.shape == (1, 64, 64, 3)
          __UpperCamelCase											=  np.array([0.86_78, 0.82_45, 0.63_81, 0.68_30, 0.43_85, 0.55_99, 0.46_41, 0.62_01, 0.51_50]			)

          assert np.abs(image_slice.flatten() - expected_slice			).max() < 1E-2







      @unittest.skipIf(torch_device != '''cuda'''	,    '''This test requires a GPU'''			)
      def  snake_case		(       self   :	Optional[Any]			):
          __UpperCamelCase											=  self.dummy_uncond_unet
          __UpperCamelCase											=  DDIMScheduler()
          __UpperCamelCase											=  self.dummy_vq_model

          # put models in fp16
          __UpperCamelCase											=  unet.half()
          __UpperCamelCase											=  vqvae.half()

          __UpperCamelCase											=  LDMSuperResolutionPipeline(unet=snake_case	,    vqvae=snake_case	,    scheduler=snake_case			)
          ldm.to(snake_case			)
          ldm.set_progress_bar_config(disable=snake_case			)

          __UpperCamelCase											=  self.dummy_image.to(snake_case			)

          __UpperCamelCase											=  ldm(snake_case	,    num_inference_steps=2	,    output_type='''numpy'''			).images

          assert image.shape == (1, 64, 64, 3)







@slow
@require_torch
class 	_lowerCamelCase  (     unittest.TestCase				):

      """simple docstring"""

      def  snake_case		(       self   :	Dict			):
          __UpperCamelCase											=  load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/vq_diffusion/teddy_bear_pool.png'''			)
          __UpperCamelCase											=  init_image.resize((64, 64)	,    resample=PIL_INTERPOLATION['''lanczos''']			)

          __UpperCamelCase											=  LDMSuperResolutionPipeline.from_pretrained('''duongna/ldm-super-resolution'''	,    device_map='''auto'''			)
          ldm.set_progress_bar_config(disable=snake_case			)

          __UpperCamelCase											=  torch.manual_seed(0			)
          __UpperCamelCase											=  ldm(image=snake_case	,    generator=snake_case	,    num_inference_steps=20	,    output_type='''numpy'''			).images

          __UpperCamelCase											=  image[0, -3:, -3:, -1]

          assert image.shape == (1, 256, 256, 3)
          __UpperCamelCase											=  np.array([0.76_44, 0.76_79, 0.76_42, 0.76_33, 0.76_66, 0.75_60, 0.74_25, 0.72_57, 0.69_07]			)

          assert np.abs(image_slice.flatten() - expected_slice			).max() < 1E-2












import argparse
import json
import re
import string
import sys
from collections import Counter




def    __SCREAMING_SNAKE_CASE				(					lowercase_ )    ->		Dict:

    """simple docstring"""


    def remove_articles(lowercase_ ):
        return re.sub(r'''\b(a|an|the)\b'''   ,       ''' '''   ,       lowercase_ )

    def white_space_fix(lowercase_ ):
        return " ".join(text.split() )

    def remove_punc(lowercase_ ):
        __UpperCamelCase											=  set(string.punctuation )
        return "".join(ch for ch in text if ch not in exclude )

    def lower(lowercase_ ):
        return text.lower()

    return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) )




def    __SCREAMING_SNAKE_CASE				(					lowercase_   ,       lowercase_ )    ->		List[str]:

    """simple docstring"""


    __UpperCamelCase											=  normalize_answer(lowercase_ ).split()
    __UpperCamelCase											=  normalize_answer(lowercase_ ).split()
    __UpperCamelCase											=  Counter(lowercase_ ) & Counter(lowercase_ )
    __UpperCamelCase											=  sum(common.values() )
    if num_same == 0:
        return 0
    __UpperCamelCase											=  1.0 * num_same / len(lowercase_ )
    __UpperCamelCase											=  1.0 * num_same / len(lowercase_ )
    __UpperCamelCase											=  (2 * precision * recall) / (precision + recall)
    return fa




def    __SCREAMING_SNAKE_CASE				(					lowercase_   ,       lowercase_ )    ->		Any:

    """simple docstring"""


    return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ )




def    __SCREAMING_SNAKE_CASE				(					lowercase_   ,       lowercase_   ,       lowercase_ )    ->		int:

    """simple docstring"""


    __UpperCamelCase											=  []
    for ground_truth in ground_truths:
        __UpperCamelCase											=  metric_fn(lowercase_   ,       lowercase_ )
        scores_for_ground_truths.append(lowercase_ )
    return max(lowercase_ )




def    __SCREAMING_SNAKE_CASE				(					lowercase_   ,       lowercase_ )    ->		Optional[int]:

    """simple docstring"""


    __UpperCamelCase											=  __UpperCamelCase											=  __UpperCamelCase											=  0
    __UpperCamelCase											=  []
    for passage in dataset:
        for qa in passage["qas"]:
            total += 1
            if qa["id"] not in predictions:
                __UpperCamelCase											=  F"Unanswered question {qa['id']} will receive score 0."
                print(lowercase_   ,       file=sys.stderr )
                continue

            __UpperCamelCase											=  [x['''text'''] for x in qa['''answers''']]
            __UpperCamelCase											=  predictions[qa['''id''']]

            __UpperCamelCase											=  metric_max_over_ground_truths(lowercase_   ,       lowercase_   ,       lowercase_ )
            if int(_exact_match ) == 1:
                correct_ids.append(qa['''id'''] )
            exact_match += _exact_match

            fa += metric_max_over_ground_truths(lowercase_   ,       lowercase_   ,       lowercase_ )

    __UpperCamelCase											=  exact_match / total
    __UpperCamelCase											=  fa / total

    return {"exact_match": exact_match, "f1": fa}, correct_ids


if __name__ == "__main__":
 a_										=       "1.0"
 a_										=       argparse.ArgumentParser("Official evaluation script for ReCoRD v1.0.")
 parser.add_argument("data_file", help="The dataset file in JSON format.")
 parser.add_argument("pred_file", help="The model prediction file in JSON format.")
 parser.add_argument("--output_correct_ids", action="store_true", help="Output the correctly answered query IDs.")
 a_										=       parser.parse_args()

 with open(args.data_file) as data_file:
  a_										=       json.load(data_file)
  if dataset_json["version"] != expected_version:
   print(
       f"""Evaluation expects v-{expected_version}, but got dataset with v-{dataset_json['version']}""",
       file=sys.stderr,
   )
  a_										=       dataset_json["data"]

 with open(args.pred_file) as pred_file:
  a_										=       json.load(pred_file)

 a_						,      a_										=       evaluate(dataset, predictions)

 if args.output_correct_ids:
  print(f"""Output {len(correct_ids)} correctly answered question IDs.""")
  with open("correct_ids.json", "w") as f:
   json.dump(correct_ids, f)






