




'''simple docstring'''




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




def 						snake_case__    ( lowerCamelCase__				:   Union[str, Any]			)   ->   Dict:

					def remove_articles(lowerCamelCase__				:   Any			):
										return re.sub(R'''\b(a|an|the)\b'''			,		''' '''			,		lowerCamelCase__			)

					def white_space_fix(lowerCamelCase__				:   int			):
										return " ".join(text.split()			)

					def remove_punc(lowerCamelCase__				:   Any			):
										A_ :     List[Any] =							set(string.punctuation			)
										return "".join(ch for ch in text if ch not in exclude			)

					def lower(lowerCamelCase__				:   List[str]			):
										return text.lower()

					return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase__			)			)			)			)




def 						snake_case__    ( lowerCamelCase__				:   List[str]			,		lowerCamelCase__				:   Tuple			)   ->   Union[str, Any]:
					A_ :     int =							normalize_answer(lowerCamelCase__			).split()
					A_ :     int =							normalize_answer(lowerCamelCase__			).split()
					A_ :     Optional[Any] =							Counter(lowerCamelCase__			) & Counter(lowerCamelCase__			)
					A_ :     Optional[Any] =							sum(common.values()			)
					if num_same == 0:
										return 0
					A_ :     List[str] =							1.0 * num_same / len(lowerCamelCase__			)
					A_ :     int =							1.0 * num_same / len(lowerCamelCase__			)
					A_ :     str =							(2 * precision * recall) / (precision + recall)
					return fa




def 						snake_case__    ( lowerCamelCase__				:   List[Any]			,		lowerCamelCase__				:   Tuple			)   ->   Optional[int]:
					return normalize_answer(lowerCamelCase__			) == normalize_answer(lowerCamelCase__			)




def 						snake_case__    ( lowerCamelCase__				:   Optional[int]			,		lowerCamelCase__				:   Union[str, Any]			,		lowerCamelCase__				:   str			)   ->   Dict:
					A_ :     str =							[]
					for ground_truth in ground_truths:
										A_ :     Optional[int] =							metric_fn(lowerCamelCase__			,		lowerCamelCase__			)
										scores_for_ground_truths.append(lowerCamelCase__			)
					return max(lowerCamelCase__			)




def 						snake_case__    ( lowerCamelCase__				:   List[Any]			,		lowerCamelCase__				:   Optional[int]			)   ->   List[Any]:
					A_ :     int =							0
					for article in dataset:
										for paragraph in article["paragraphs"]:
															for qa in paragraph["qas"]:
																				total += 1
																				if qa["id"] not in predictions:
																									A_ :     List[Any] =							'''Unanswered question ''' + qa['''id'''] + ''' will receive score 0.'''
																									print(lowerCamelCase__			,		file=sys.stderr			)
																									continue
																				A_ :     Dict =							[x['''text'''] for x in qa['''answers''']]
																				A_ :     str =							predictions[qa['''id''']]
																				exact_match += metric_max_over_ground_truths(lowerCamelCase__			,		lowerCamelCase__			,		lowerCamelCase__			)
																				fa += metric_max_over_ground_truths(lowerCamelCase__			,		lowerCamelCase__			,		lowerCamelCase__			)

					A_ :     int =							100.0 * exact_match / total
					A_ :     Optional[Any] =							100.0 * fa / total

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


if __name__ == "__main__":
							snake_case__          =						"""1.1"""
							snake_case__          =						argparse.ArgumentParser(description="""Evaluation for SQuAD """ + expected_version)
							parser.add_argument("""dataset_file""", help="""Dataset file""")
							parser.add_argument("""prediction_file""", help="""Prediction File""")
							snake_case__          =						parser.parse_args()
							with open(args.dataset_file) as dataset_file:
														snake_case__          =						json.load(dataset_file)
														if dataset_json["version"] != expected_version:
																					print(
																					    """Evaluation expects v-""" + expected_version + """, but got dataset with v-""" + dataset_json["""version"""],
																					    file=sys.stderr,
																					)
														snake_case__          =						dataset_json["""data"""]
							with open(args.prediction_file) as prediction_file:
														snake_case__          =						json.load(prediction_file)
							print(json.dumps(evaluate(dataset, predictions)))









'''simple docstring'''




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     UpperCamelCase_     (unittest.TestCase     ):







						"""simple docstring"""


						@property
						def       _a    (     self      :       int    ):





											"""simple docstring"""







											A_ :     Dict =							1
											A_ :     Any =							3
											A_ :     Any =							(32, 32)

											A_ :     Dict =							floats_tensor((batch_size, num_channels) + sizes							, rng=random.Random(0    )    ).to(_lowerCamelCase    )
											return image







						@property
						def       _a    (     self      :       Dict    ):





											"""simple docstring"""







											torch.manual_seed(0    )
											A_ :     Optional[int] =							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       _a    (     self      :       Any    ):





											"""simple docstring"""







											torch.manual_seed(0    )
											A_ :     Dict =							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       _a    (     self      :       List[Any]    ):





											"""simple docstring"""







											A_ :     Any =							'''cpu'''
											A_ :     Optional[Any] =							self.dummy_uncond_unet
											A_ :     str =							DDIMScheduler()
											A_ :     Optional[int] =							self.dummy_vq_model

											A_ :     Optional[Any] =							LDMSuperResolutionPipeline(unet=_lowerCamelCase							, vqvae=_lowerCamelCase							, scheduler=_lowerCamelCase    )
											ldm.to(_lowerCamelCase    )
											ldm.set_progress_bar_config(disable=_lowerCamelCase    )

											A_ :     Any =							self.dummy_image.to(_lowerCamelCase    )

											A_ :     str =							torch.Generator(device=_lowerCamelCase    ).manual_seed(0    )
											A_ :     List[Any] =							ldm(image=_lowerCamelCase							, generator=_lowerCamelCase							, num_inference_steps=2							, output_type='''numpy'''    ).images

											A_ :     str =							image[0, -3:, -3:, -1]

											assert image.shape == (1, 64, 64, 3)
											A_ :     List[Any] =							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       _a    (     self      :       Optional[int]    ):





											"""simple docstring"""







											A_ :     Tuple =							self.dummy_uncond_unet
											A_ :     List[str] =							DDIMScheduler()
											A_ :     str =							self.dummy_vq_model

											# put models in fp16
											A_ :     List[Any] =							unet.half()
											A_ :     Optional[int] =							vqvae.half()

											A_ :     Optional[Any] =							LDMSuperResolutionPipeline(unet=_lowerCamelCase							, vqvae=_lowerCamelCase							, scheduler=_lowerCamelCase    )
											ldm.to(_lowerCamelCase    )
											ldm.set_progress_bar_config(disable=_lowerCamelCase    )

											A_ :     Optional[Any] =							self.dummy_image.to(_lowerCamelCase    )

											A_ :     Optional[Any] =							ldm(_lowerCamelCase							, num_inference_steps=2							, output_type='''numpy'''    ).images

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






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







						"""simple docstring"""


						def       _a    (     self      :       int    ):





											"""simple docstring"""







											A_ :     Optional[int] =							load_image(
											    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
											    '''/vq_diffusion/teddy_bear_pool.png'''    )
											A_ :     List[str] =							init_image.resize((64, 64)							, resample=PIL_INTERPOLATION['''lanczos''']    )

											A_ :     List[str] =							LDMSuperResolutionPipeline.from_pretrained('''duongna/ldm-super-resolution'''							, device_map='''auto'''    )
											ldm.set_progress_bar_config(disable=_lowerCamelCase    )

											A_ :     List[str] =							torch.manual_seed(0    )
											A_ :     str =							ldm(image=_lowerCamelCase							, generator=_lowerCamelCase							, num_inference_steps=20							, output_type='''numpy'''    ).images

											A_ :     str =							image[0, -3:, -3:, -1]

											assert image.shape == (1, 256, 256, 3)
											A_ :     Optional[Any] =							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



