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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowerCamelCase__          =		logging.get_logger(__name__)

lowerCamelCase__          =		"▁"

lowerCamelCase__          =		{"vocab_file": "sentencepiece.bpe.model"}

lowerCamelCase__          =		{
    "vocab_file": {
        "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model",
    }
}

lowerCamelCase__          =		{
    "facebook/xglm-564M": 2048,
}







class      A__							(     _a	):
				lowercase			    =  VOCAB_FILES_NAMES
				lowercase			    =  PRETRAINED_VOCAB_FILES_MAP
				lowercase			    =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				lowercase			    =  ["""input_ids""", """attention_mask"""]






				def __init__(						self					:      Optional[Any]    ,     a					:      List[Any]    ,     a					:      str="<s>"    ,     a					:      Union[str, Any]="</s>"    ,     a					:      str="</s>"    ,     a					:      Optional[int]="<s>"    ,     a					:      str="<unk>"    ,     a					:      str="<pad>"    ,     a					:      Any = None    ,     **a					:      Any    ,     ):






							'''simple docstring'''







							lowerCAmelCase__      :      str         =		{} if sp_model_kwargs is None else sp_model_kwargs

							# Compatibility with the original tokenizer
							lowerCAmelCase__      :      List[str]         =		7
							lowerCAmelCase__      :      str         =		[f'''<madeupword{i}>''' for i in range(self.num_madeup_words   )]

							lowerCAmelCase__      :      List[str]         =		kwargs.get('additional_special_tokens'    ,     []   )
							kwargs["additional_special_tokens"] += [
							    word for word in madeup_words if word not in kwargs["additional_special_tokens"]
							]

							super().__init__(
							    bos_token=a    ,     eos_token=a    ,     unk_token=a    ,     sep_token=a    ,     cls_token=a    ,     pad_token=a    ,     sp_model_kwargs=self.sp_model_kwargs    ,     **a    ,     )

							lowerCAmelCase__      :      Any         =		spm.SentencePieceProcessor(**self.sp_model_kwargs   )
							self.sp_model.Load(str(a   )   )
							lowerCAmelCase__      :      List[Any]         =		vocab_file

							# Original fairseq vocab and spm vocab must be "aligned":
							# Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
							# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
							# fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
							# spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

							# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
							lowerCAmelCase__      :      int         =		1

							# Mimic fairseq token-to-id alignment for the first 4 token
							lowerCAmelCase__      :      int         =		{'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3}

							lowerCAmelCase__      :      Any         =		len(self.sp_model   )
							lowerCAmelCase__      :      Optional[int]         =		{f'''<madeupword{i}>''': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words   )}
							self.fairseq_tokens_to_ids.update(a   )

							lowerCAmelCase__      :      Tuple         =		{v: k for k, v in self.fairseq_tokens_to_ids.items()}






				def __getstate__(						self					:      Optional[int]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Any         =		self.__dict__.copy()
							lowerCAmelCase__      :      Optional[int]         =		None
							lowerCAmelCase__      :      Optional[Any]         =		self.sp_model.serialized_model_proto()
							return state






				def __setstate__(						self					:      Optional[Any]    ,     a					:      Any   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[Any]         =		d

							# for backward compatibility
							if not hasattr(self    ,     'sp_model_kwargs'   ):
										lowerCAmelCase__      :      str         =		{}

							lowerCAmelCase__      :      List[str]         =		spm.SentencePieceProcessor(**self.sp_model_kwargs   )
							self.sp_model.LoadFromSerializedProto(self.sp_model_proto   )






				def 							_lowerCamelCase		(						self					:      Optional[Any]    ,     a					:      str    ,     a					:      Optional[Any] = None   ):






							'''simple docstring'''







							if token_ids_a is None:
										return [self.sep_token_id] + token_ids_a
							lowerCAmelCase__      :      Union[str, Any]         =		[self.sep_token_id]
							return sep + token_ids_a + sep + sep + token_ids_a






				def 							_lowerCamelCase		(						self					:      Any    ,     a					:      Tuple    ,     a					:      Dict = None    ,     a					:      str = False   ):






							'''simple docstring'''







							if already_has_special_tokens:
										return super().get_special_tokens_mask(
										    token_ids_a=a    ,     token_ids_a=a    ,     already_has_special_tokens=a   )

							if token_ids_a is None:
										return [1] + ([0] * len(a   ))
							return [1] + ([0] * len(a   )) + [1, 1] + ([0] * len(a   ))






				def 							_lowerCamelCase		(						self					:      Optional[int]    ,     a					:      List[Any]    ,     a					:      Optional[Any] = None   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[int]         =		[self.sep_token_id]

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






				@property
				def 							_lowerCamelCase		(						self					:      Union[str, Any]   ):






							'''simple docstring'''







							return len(self.sp_model   ) + self.fairseq_offset + self.num_madeup_words






				def 							_lowerCamelCase		(						self					:      Tuple   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[Any]         =		{self.convert_ids_to_tokens(a   ): i for i in range(self.vocab_size   )}
							vocab.update(self.added_tokens_encoder   )
							return vocab






				def 							_lowerCamelCase		(						self					:      Tuple    ,     a					:      Any   ):






							'''simple docstring'''







							return self.sp_model.encode(a    ,     out_type=a   )






				def 							_lowerCamelCase		(						self					:      Tuple    ,     a					:      Optional[Any]   ):






							'''simple docstring'''







							if token in self.fairseq_tokens_to_ids:
										return self.fairseq_tokens_to_ids[token]
							lowerCAmelCase__      :      Optional[Any]         =		self.sp_model.PieceToId(a   )

							# Need to return unknown token if the SP model returned 0
							return spm_id + self.fairseq_offset if spm_id else self.unk_token_id






				def 							_lowerCamelCase		(						self					:      List[Any]    ,     a					:      Union[str, Any]   ):






							'''simple docstring'''







							if index in self.fairseq_ids_to_tokens:
										return self.fairseq_ids_to_tokens[index]
							return self.sp_model.IdToPiece(index - self.fairseq_offset   )






				def 							_lowerCamelCase		(						self					:      List[Any]    ,     a					:      Optional[int]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Union[str, Any]         =		''.join(a   ).replace(a    ,     ' '   ).strip()
							return out_string






				def 							_lowerCamelCase		(						self					:      Optional[Any]    ,     a					:      Dict    ,     a					:      List[str] = None   ):






							'''simple docstring'''







							if not os.path.isdir(a   ):
										logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''   )
										return
							lowerCAmelCase__      :      Optional[Any]         =		os.path.join(
							    a    ,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']   )

							if os.path.abspath(self.vocab_file   ) != os.path.abspath(a   ) and os.path.isfile(self.vocab_file   ):
										copyfile(self.vocab_file    ,     a   )
							elif not os.path.isfile(self.vocab_file   ):
										with open(a    ,     'wb'   ) as fi:
													lowerCAmelCase__      :      Optional[int]         =		self.sp_model.serialized_model_proto()
													fi.write(a   )

							return (out_vocab_file,)



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(						_a, unittest.TestCase   ):
       # TODO: is there an appropriate internal test set?
       lowercase_ :	int     =			"""ssube/stable-diffusion-x4-upscaler-onnx"""
       def 			UpperCamelCase     (					self,      lowerCamelCase=0)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase       :							Dict      		=		floats_tensor((1, 3, 1_28, 1_28),      rng=random.Random(lowerCamelCase))
           _lowercase       :							Union[str, Any]      		=		torch.manual_seed(lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		{
               '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 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							Tuple      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,      provider='CPUExecutionProvider')
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							Dict      		=		self.get_dummy_inputs()
           _lowercase       :							Optional[int]      		=		pipe(**lowerCamelCase).images
           _lowercase       :							Optional[int]      		=		image[0, -3:, -3:, -1].flatten()

           # started as 128, should now be 512
           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							Union[str, Any]      		=		np.array(
               [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3])
           assert np.abs(image_slice - expected_slice).max() < 1E-1
       def 			UpperCamelCase     (					self)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase       :							int      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,      provider='CPUExecutionProvider')
           _lowercase       :							str      		=		PNDMScheduler.from_config(pipe.scheduler.config,      skip_prk_steps=lowerCamelCase)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

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

           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							int      		=		np.array(
               [0.6_8_9_8_8_9_2, 0.5_9_2_4_0_5_5_6, 0.5_2_4_9_9_5_2_7, 0.5_8_8_6_6_2_1_5, 0.5_2_2_5_8_2_3_5, 0.5_2_5_7_2_7_1_5, 0.6_2_4_1_4_4_7_3, 0.6_1_7_4_3_8_7, 0.6_2_1_4_9_6_4])
           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           _lowercase       :							Dict      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,      provider='CPUExecutionProvider')
           _lowercase       :							Optional[int]      		=		DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							Optional[int]      		=		self.get_dummy_inputs()
           _lowercase       :							Union[str, Any]      		=		pipe(**lowerCamelCase).images
           _lowercase       :							str      		=		image[0, -3:, -3:, -1]

           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							Optional[int]      		=		np.array(
               [0.7_6_5_9_2_7_8, 0.7_6_4_3_7_6_6_4, 0.7_5_5_7_9_1_0_7, 0.7_6_9_1_1_1_6, 0.7_7_6_6_6_9_8_6, 0.7_7_2_7_6_7_2, 0.7_7_5_8_6_6_4, 0.7_8_1_2_2_2_6, 0.7_6_9_4_2_5_1_5])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							List[str]      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,      provider='CPUExecutionProvider')
           _lowercase       :							List[str]      		=		EulerDiscreteScheduler.from_config(pipe.scheduler.config)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							Dict      		=		self.get_dummy_inputs()
           _lowercase       :							Optional[Any]      		=		pipe(**lowerCamelCase).images
           _lowercase       :							Optional[int]      		=		image[0, -3:, -3:, -1]

           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							Union[str, Any]      		=		np.array(
               [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3])
           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1




       def 			UpperCamelCase     (					self)       ->   Dict:




           """simple docstring"""

           _lowercase       :							Tuple      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,      provider='CPUExecutionProvider')
           _lowercase       :							Any      		=		EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

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

           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							Union[str, Any]      		=		np.array(
               [0.7_7_4_2_4_4_9_6, 0.7_7_3_6_0_1, 0.7_6_4_5_2_8_8, 0.7_7_6_9_5_9_8, 0.7_7_7_2_7_3_9, 0.7_7_3_8_6_8_8, 0.7_8_1_8_7_2_3_3, 0.7_7_8_7_9_5_8_4, 0.7_6_7_0_4_3])

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






@nightly
@require_onnxruntime
@require_torch_gpu
class _lowerCamelCase(						unittest.TestCase   ):
       @property
       def 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           return (
               "CUDAExecutionProvider",
               {
                   "gpu_mem_limit": "15000000000",  # 15GB
                   "arena_extend_strategy": "kSameAsRequested",
               },
           )
       @property
       def 			UpperCamelCase     (					self)       ->   Any:




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		ort.SessionOptions()
           _lowercase       :							str      		=		False
           return options
       def 			UpperCamelCase     (					self)       ->   Any:




           """simple docstring"""

           _lowercase       :							Optional[int]      		=		load_image(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
               '/img2img/sketch-mountains-input.jpg')
           _lowercase       :							int      		=		init_image.resize((1_28, 1_28))
           # using the PNDM scheduler by default
           _lowercase       :							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=lowerCamelCase)

           _lowercase       :							Optional[int]      		=		'A fantasy landscape, trending on artstation'

           _lowercase       :							List[Any]      		=		torch.manual_seed(0)
           _lowercase       :							str      		=		pipe(
               prompt=lowerCamelCase,      image=lowerCamelCase,      guidance_scale=7.5,      num_inference_steps=10,      generator=lowerCamelCase,      output_type='np',      )
           _lowercase       :							List[Any]      		=		output.images
           _lowercase       :							List[Any]      		=		images[0, 2_55:2_58, 3_83:3_86, -1]

           assert images.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							List[Any]      		=		np.array([0.4_8_8_3, 0.4_9_4_7, 0.4_9_8_0, 0.4_9_7_5, 0.4_9_8_2, 0.4_9_8_0, 0.5_0_0_0, 0.5_0_0_6, 0.4_9_7_2])
           # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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




       def 			UpperCamelCase     (					self)       ->   Any:




           """simple docstring"""

           _lowercase       :							Optional[int]      		=		load_image(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
               '/img2img/sketch-mountains-input.jpg')
           _lowercase       :							int      		=		init_image.resize((1_28, 1_28))
           _lowercase       :							str      		=		LMSDiscreteScheduler.from_pretrained(
               'ssube/stable-diffusion-x4-upscaler-onnx',      subfolder='scheduler')
           _lowercase       :							Dict      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(
               'ssube/stable-diffusion-x4-upscaler-onnx',      scheduler=lowerCamelCase,      provider=self.gpu_provider,      sess_options=self.gpu_options,      )
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							Optional[int]      		=		'A fantasy landscape, trending on artstation'

           _lowercase       :							List[Any]      		=		torch.manual_seed(0)
           _lowercase       :							str      		=		pipe(
               prompt=lowerCamelCase,      image=lowerCamelCase,      guidance_scale=7.5,      num_inference_steps=20,      generator=lowerCamelCase,      output_type='np',      )
           _lowercase       :							str      		=		output.images
           _lowercase       :							str      		=		images[0, 2_55:2_58, 3_83:3_86, -1]

           assert images.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							Union[str, Any]      		=		np.array(
               [0.5_0_1_7_3_7_5_3, 0.5_0_2_2_3_3_5_6, 0.5_0_2_0_3_9, 0.5_0_2_3_3_0_3_6, 0.5_0_2_3_7_2_5, 0.5_0_2_2_6_0_1, 0.5_0_1_8_7_5_8, 0.5_0_2_3_4_0_8_5, 0.5_0_2_4_1_5_6_6])
           # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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


