


"""simple docstring"""



import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
  import onnxruntime as ort







class _lowerCAmelCase				(      snake_case_    ,							unittest.TestCase	):
   # TODO: is there an appropriate internal test set?
   __UpperCAmelCase :       Optional[Any]							  =  '''ssube/stable-diffusion-x4-upscaler-onnx'''







   def  lowerCamelCase		(	self						,	UpperCamelCase__=0						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    floats_tensor((1, 3, 128, 128)						,	rng=random.Random(UpperCamelCase__						)						)
       snake_case    :      Any      					=    torch.manual_seed(UpperCamelCase__						)
       snake_case    :      List[str]      					=    {
           "prompt": "A painting of a squirrel eating a burger",
           "image": image,
           "generator": generator,
           "num_inference_steps": 3,
           "guidance_scale": 7.5,
           "output_type": "numpy",
       }
       return inputs







   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Optional[Any]      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"						)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Tuple      					=    self.get_dummy_inputs()
       snake_case    :      int      					=    pipe(**UpperCamelCase__						).images
       snake_case    :      Tuple      					=    image[0, -3:, -3:, -1].flatten()

       # started as 128, should now be 512
       assert image.shape == (1, 512, 512, 3)
       snake_case    :      Optional[int]      					=    np.array(
           [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]						)
       assert np.abs(image_slice - expected_slice						).max() < 1e-1







   def  lowerCamelCase		(	self						)	->		Union[str, Any]:

       '''simple docstring'''




       snake_case    :      Tuple      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"						)
       snake_case    :      Optional[Any]      					=    PNDMScheduler.from_config(pipe.scheduler.config						,	skip_prk_steps=UpperCamelCase__						)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Tuple      					=    self.get_dummy_inputs()
       snake_case    :      Optional[Any]      					=    pipe(**UpperCamelCase__						).images
       snake_case    :      List[str]      					=    image[0, -3:, -3:, -1]

       assert image.shape == (1, 512, 512, 3)
       snake_case    :      Dict      					=    np.array(
           [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964]						)
       assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1







   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       snake_case    :      Optional[int]      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"						)
       snake_case    :      Optional[Any]      					=    DPMSolverMultistepScheduler.from_config(pipe.scheduler.config						)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Any      					=    self.get_dummy_inputs()
       snake_case    :      List[Any]      					=    pipe(**UpperCamelCase__						).images
       snake_case    :      List[str]      					=    image[0, -3:, -3:, -1]

       assert image.shape == (1, 512, 512, 3)
       snake_case    :      Optional[Any]      					=    np.array(
           [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515]						)

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







   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"						)
       snake_case    :      Any      					=    EulerDiscreteScheduler.from_config(pipe.scheduler.config						)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Dict      					=    self.get_dummy_inputs()
       snake_case    :      Union[str, Any]      					=    pipe(**UpperCamelCase__						).images
       snake_case    :      str      					=    image[0, -3:, -3:, -1]

       assert image.shape == (1, 512, 512, 3)
       snake_case    :      Union[str, Any]      					=    np.array(
           [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]						)
       assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      Optional[Any]      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"						)
       snake_case    :      Optional[Any]      					=    EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config						)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Any      					=    self.get_dummy_inputs()
       snake_case    :      int      					=    pipe(**UpperCamelCase__						).images
       snake_case    :      List[Any]      					=    image[0, -3:, -3:, -1]

       assert image.shape == (1, 512, 512, 3)
       snake_case    :      Union[str, Any]      					=    np.array(
           [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043]						)

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







@nightly
@require_onnxruntime
@require_torch_gpu
class _lowerCAmelCase				(      unittest.TestCase	):







   @property
   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       return (
           "CUDAExecutionProvider",
           {
               "gpu_mem_limit": "15000000000",  # 15GB
               "arena_extend_strategy": "kSameAsRequested",
           },
       )







   @property
   def  lowerCamelCase		(	self						)	->		List[Any]:

       '''simple docstring'''




       snake_case    :      List[Any]      					=    ort.SessionOptions()
       snake_case    :      str      					=    False
       return options







   def  lowerCamelCase		(	self						)	->		List[Any]:

       '''simple docstring'''




       snake_case    :      str      					=    load_image(
           "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
           "/img2img/sketch-mountains-input.jpg"						)
       snake_case    :      Tuple      					=    init_image.resize((128, 128)						)
       # using the PNDM scheduler by default
       snake_case    :      Tuple      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(
           "ssube/stable-diffusion-x4-upscaler-onnx"						,	provider=self.gpu_provider						,	sess_options=self.gpu_options						,	)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      List[Any]      					=    "A fantasy landscape, trending on artstation"

       snake_case    :      Union[str, Any]      					=    torch.manual_seed(0						)
       snake_case    :      int      					=    pipe(
           prompt=UpperCamelCase__						,	image=UpperCamelCase__						,	guidance_scale=7.5						,	num_inference_steps=10						,	generator=UpperCamelCase__						,	output_type="np"						,	)
       snake_case    :      str      					=    output.images
       snake_case    :      Tuple      					=    images[0, 255:258, 383:386, -1]

       assert images.shape == (1, 512, 512, 3)
       snake_case    :      int      					=    np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972]						)
       # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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







   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       snake_case    :      Tuple      					=    load_image(
           "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
           "/img2img/sketch-mountains-input.jpg"						)
       snake_case    :      Optional[Any]      					=    init_image.resize((128, 128)						)
       snake_case    :      Union[str, Any]      					=    LMSDiscreteScheduler.from_pretrained(
           "ssube/stable-diffusion-x4-upscaler-onnx"						,	subfolder="scheduler"						)
       snake_case    :      List[Any]      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(
           "ssube/stable-diffusion-x4-upscaler-onnx"						,	scheduler=UpperCamelCase__						,	provider=self.gpu_provider						,	sess_options=self.gpu_options						,	)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Union[str, Any]      					=    "A fantasy landscape, trending on artstation"

       snake_case    :      Tuple      					=    torch.manual_seed(0						)
       snake_case    :      str      					=    pipe(
           prompt=UpperCamelCase__						,	image=UpperCamelCase__						,	guidance_scale=7.5						,	num_inference_steps=20						,	generator=UpperCamelCase__						,	output_type="np"						,	)
       snake_case    :      List[Any]      					=    output.images
       snake_case    :      List[Any]      					=    images[0, 255:258, 383:386, -1]

       assert images.shape == (1, 512, 512, 3)
       snake_case    :      int      					=    np.array(
           [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566]						)
       # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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









"""simple docstring"""



import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
  from .tokenization_rembert import RemBertTokenizer
else:
  __snake_case   			=    None

__snake_case   			=    logging.get_logger(__name__)
__snake_case   			=    {"""vocab_file""": """sentencepiece.model""", """tokenizer_file""": """tokenizer.json"""}

__snake_case   			=    {
    """vocab_file""": {
        """google/rembert""": """https://huggingface.co/google/rembert/resolve/main/sentencepiece.model""",
    },
    """tokenizer_file""": {
        """google/rembert""": """https://huggingface.co/google/rembert/resolve/main/tokenizer.json""",
    },
}

__snake_case   			=    {
    """google/rembert""": 256,
}

__snake_case   			=    """▁"""







class _lowerCAmelCase				(      snake_case_	):
   __UpperCAmelCase :       List[str]							  =  VOCAB_FILES_NAMES
   __UpperCAmelCase :       Union[str, Any]							  =  PRETRAINED_VOCAB_FILES_MAP
   __UpperCAmelCase :       str							  =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   __UpperCAmelCase :       str							  =  RemBertTokenizer







   def __init__(	self						,	UpperCamelCase__=None						,	UpperCamelCase__=None						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	UpperCamelCase__=False						,	UpperCamelCase__="[CLS]"						,	UpperCamelCase__="[SEP]"						,	UpperCamelCase__="<unk>"						,	UpperCamelCase__="[SEP]"						,	UpperCamelCase__="<pad>"						,	UpperCamelCase__="[CLS]"						,	UpperCamelCase__="[MASK]"						,	**UpperCamelCase__						,	)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Dict      					=    AddedToken(UpperCamelCase__						,	lstrip=UpperCamelCase__						,	rstrip=UpperCamelCase__						) if isinstance(UpperCamelCase__						,	UpperCamelCase__						) else mask_token

       super().__init__(
           UpperCamelCase__						,	tokenizer_file=UpperCamelCase__						,	do_lower_case=UpperCamelCase__						,	remove_space=UpperCamelCase__						,	keep_accents=UpperCamelCase__						,	bos_token=UpperCamelCase__						,	eos_token=UpperCamelCase__						,	unk_token=UpperCamelCase__						,	sep_token=UpperCamelCase__						,	pad_token=UpperCamelCase__						,	cls_token=UpperCamelCase__						,	mask_token=UpperCamelCase__						,	**UpperCamelCase__						,	)

       snake_case    :      int      					=    do_lower_case
       snake_case    :      Union[str, Any]      					=    remove_space
       snake_case    :      Optional[int]      					=    keep_accents
       snake_case    :      Any      					=    vocab_file
       snake_case    :      Any      					=    False if not self.vocab_file else True







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__ = None						)	->		List[int]:

       '''simple docstring'''




       snake_case    :      Optional[Any]      					=    [self.sep_token_id]
       snake_case    :      Optional[int]      					=    [self.cls_token_id]
       if token_ids_a is None:
           return cls + token_ids_a + sep
       return cls + token_ids_a + sep + token_ids_a + sep







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__ = None						,	UpperCamelCase__ = False						)	->		List[int]:

       '''simple docstring'''




       if already_has_special_tokens:
           if token_ids_a is not None:
               raise ValueError(
                   "You should not supply a second sequence if the provided sequence of "
                   "ids is already formatted with special tokens for the model."						)
           return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

       if token_ids_a is not None:
           return [1] + ([0] * len(UpperCamelCase__						)) + [1] + ([0] * len(UpperCamelCase__						)) + [1]
       return [1] + ([0] * len(UpperCamelCase__						)) + [1]







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__ = None						)	->		List[int]:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    [self.sep_token_id]
       snake_case    :      Optional[int]      					=    [self.cls_token_id]

       if token_ids_a is None:
           return len(cls + token_ids_a + sep						) * [0]
       return len(cls + token_ids_a + sep						) * [0] + len(token_ids_a + sep						) * [1]







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__ = None						)	->		Tuple[str]:

       '''simple docstring'''




       if not os.path.isdir(UpperCamelCase__						):
           logger.error("Vocabulary path ({}) should be a directory".format(UpperCamelCase__						)						)
           return
       snake_case    :      str      					=    os.path.join(
           UpperCamelCase__						,	(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]						)

       if os.path.abspath(self.vocab_file						) != os.path.abspath(UpperCamelCase__						):
           copyfile(self.vocab_file						,	UpperCamelCase__						)

       return (out_vocab_file,)





