



'''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							(      __UpperCAmelCase				,      unittest.TestCase			):
	# TODO: is there an appropriate internal test set?
	__SCREAMING_SNAKE_CASE       :		List[Any]		      = 'ssube/stable-diffusion-x4-upscaler-onnx'


	def    _a     (self	,				lowercase=0							):
				A_     :						Dict     =					floats_tensor((1, 3, 128, 128)	,				rng=random.Random(lowercase							)							)
				A_     :						int     =					torch.manual_seed(lowercase							)
				A_     :						Dict     =					{
				    """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    _a     (self							):
				A_     :						Optional[int]     =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint	,				provider="""CPUExecutionProvider"""							)
				pipe.set_progress_bar_config(disable=lowercase							)

				A_     :						Union[str, Any]     =					self.get_dummy_inputs()
				A_     :						str     =					pipe(**lowercase							).images
				A_     :						Union[str, Any]     =					image[0, -3:, -3:, -1].flatten()

				# started as 128, should now be 512
				assert image.shape == (1, 512, 512, 3)
				A_     :						Any     =					np.array(
				    [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]							)
				assert np.abs(image_slice - expected_slice							).max() < 1E-1


	def    _a     (self							):
				A_     :						Tuple     =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint	,				provider="""CPUExecutionProvider"""							)
				A_     :						Dict     =					PNDMScheduler.from_config(pipe.scheduler.config	,				skip_prk_steps=lowercase							)
				pipe.set_progress_bar_config(disable=lowercase							)

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

				assert image.shape == (1, 512, 512, 3)
				A_     :						List[Any]     =					np.array(
				    [0.6_89_88_92, 0.59_24_05_56, 0.52_49_95_27, 0.58_86_62_15, 0.52_25_82_35, 0.52_57_27_15, 0.62_41_44_73, 0.6_17_43_87, 0.6_21_49_64]							)
				assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-1


	def    _a     (self							):
				A_     :						Optional[int]     =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint	,				provider="""CPUExecutionProvider"""							)
				A_     :						int     =					DPMSolverMultistepScheduler.from_config(pipe.scheduler.config							)
				pipe.set_progress_bar_config(disable=lowercase							)

				A_     :						List[Any]     =					self.get_dummy_inputs()
				A_     :						Union[str, Any]     =					pipe(**lowercase							).images
				A_     :						Optional[Any]     =					image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				A_     :						Optional[int]     =					np.array(
				    [0.7_65_92_78, 0.76_43_76_64, 0.75_57_91_07, 0.7_69_11_16, 0.77_66_69_86, 0.7_72_76_72, 0.7_75_86_64, 0.7_81_22_26, 0.76_94_25_15]							)

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


	def    _a     (self							):
				A_     :						List[str]     =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint	,				provider="""CPUExecutionProvider"""							)
				A_     :						int     =					EulerDiscreteScheduler.from_config(pipe.scheduler.config							)
				pipe.set_progress_bar_config(disable=lowercase							)

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

				assert image.shape == (1, 512, 512, 3)
				A_     :						Dict     =					np.array(
				    [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]							)
				assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-1


	def    _a     (self							):
				A_     :						List[Any]     =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint	,				provider="""CPUExecutionProvider"""							)
				A_     :						List[str]     =					EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config							)
				pipe.set_progress_bar_config(disable=lowercase							)

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

				assert image.shape == (1, 512, 512, 3)
				A_     :						Dict     =					np.array(
				    [0.77_42_44_96, 0.77_36_01, 0.7_64_52_88, 0.7_76_95_98, 0.7_77_27_39, 0.7_73_86_88, 0.78_18_72_33, 0.77_87_95_84, 0.76_70_43]							)

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







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


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


	@property
	def    _a     (self							):
				A_     :						int     =					ort.SessionOptions()
				A_     :						Tuple     =					False
				return options


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

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

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

				assert images.shape == (1, 512, 512, 3)
				A_     :						int     =					np.array([0.48_83, 0.49_47, 0.49_80, 0.49_75, 0.49_82, 0.49_80, 0.50_00, 0.50_06, 0.49_72]							)
				# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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


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

				A_     :						Any     =					"""A fantasy landscape, trending on artstation"""

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

				assert images.shape == (1, 512, 512, 3)
				A_     :						int     =					np.array(
				    [0.50_17_37_53, 0.50_22_33_56, 0.50_20_39, 0.50_23_30_36, 0.5_02_37_25, 0.5_02_26_01, 0.5_01_87_58, 0.50_23_40_85, 0.50_24_15_66]							)
				# 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
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import SPIECE_UNDERLINE, logging


lowerCamelCase							:Union[str, Any]       = logging.get_logger(__name__)

lowerCamelCase							:Union[str, Any]       = {'''vocab_file''': '''spiece.model'''}

lowerCamelCase							:Tuple       = {
    '''vocab_file''': {
        '''TsinghuaAI/CPM-Generate''': '''https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model''',
    }
}







class      _lowerCAmelCase							(      __UpperCAmelCase			):


	def __init__(self	,				lowercase	,				lowercase=False	,				lowercase=True	,				lowercase=False	,				lowercase="<s>"	,				lowercase="</s>"	,				lowercase="<unk>"	,				lowercase="<sep>"	,				lowercase="<pad>"	,				lowercase="<cls>"	,				lowercase="<mask>"	,				lowercase=["<eop>", "<eod>"]	,				lowercase = None	,				**lowercase	,				):
				A_     :						Optional[int]     =					AddedToken(lowercase	,				lstrip=lowercase	,				rstrip=lowercase							) if isinstance(lowercase	,				lowercase							) else mask_token

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

				super().__init__(
				    do_lower_case=lowercase	,				remove_space=lowercase	,				keep_accents=lowercase	,				bos_token=lowercase	,				eos_token=lowercase	,				unk_token=lowercase	,				sep_token=lowercase	,				pad_token=lowercase	,				cls_token=lowercase	,				mask_token=lowercase	,				additional_special_tokens=lowercase	,				sp_model_kwargs=self.sp_model_kwargs	,				**lowercase	,				)

				A_     :						List[str]     =					3

				A_     :						List[str]     =					do_lower_case
				A_     :						Tuple     =					remove_space
				A_     :						Tuple     =					keep_accents
				A_     :						Tuple     =					vocab_file

				A_     :						int     =					spm.SentencePieceProcessor(**self.sp_model_kwargs							)
				self.sp_model.Load(lowercase							)

				try:
							import jieba
				except ModuleNotFoundError as error:
							raise error.__class__(
							    """You need to install jieba to use CpmTokenizer or CpmTokenizerFast. """
							    """See https://pypi.org/project/jieba/ for installation."""							)
				A_     :						Tuple     =					jieba
				A_     :						int     =					str.maketrans(""" \n"""	,				"""\u2582\u2583"""							)


	@property
	# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
	def    _a     (self							):
				return len(self.sp_model							)


	def    _a     (self							):
				A_     :						str     =					{self.convert_ids_to_tokens(lowercase							): i for i in range(self.vocab_size							)}
				vocab.update(self.added_tokens_encoder							)
				return vocab


	def __getstate__(self							):
				A_     :						Optional[Any]     =					self.__dict__.copy()
				A_     :						Tuple     =					None
				return state


	def __setstate__(self	,				lowercase							):
				A_     :						Tuple     =					d

				# for backward compatibility
				if not hasattr(self	,				"""sp_model_kwargs"""							):
							A_     :						List[Any]     =					{}

				A_     :						int     =					spm.SentencePieceProcessor(**self.sp_model_kwargs							)
				self.sp_model.Load(self.vocab_file							)


	def    _a     (self	,				lowercase							):
				if self.remove_space:
							A_     :						Union[str, Any]     =					""" """.join(inputs.strip().split()							)
				else:
							A_     :						Optional[int]     =					inputs
				A_     :						List[str]     =					outputs.replace("""``"""	,				"""\""""							).replace("""''"""	,				"""\""""							)

				if not self.keep_accents:
							A_     :						str     =					unicodedata.normalize("""NFKD"""	,				lowercase							)
							A_     :						Union[str, Any]     =					"""""".join([c for c in outputs if not unicodedata.combining(lowercase							)]							)
				if self.do_lower_case:
							A_     :						int     =					outputs.lower()

				return outputs


	def    _a     (self	,				lowercase							):
				A_     :						Optional[int]     =					self.preprocess_text(lowercase							)
				A_     :						Dict     =					self.sp_model.encode(lowercase	,				out_type=lowercase							)
				A_     :						List[Any]     =					[]
				for piece in pieces:
							if len(lowercase							) > 1 and piece[-1] == str(""","""							) and piece[-2].isdigit():
										A_     :						Union[str, Any]     =					self.sp_model.EncodeAsPieces(piece[:-1].replace(lowercase	,				""""""							)							)
										if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
													if len(cur_pieces[0]							) == 1:
																A_     :						Dict     =					cur_pieces[1:]
													else:
																A_     :						str     =					cur_pieces[0][1:]
										cur_pieces.append(piece[-1]							)
										new_pieces.extend(lowercase							)
							else:
										new_pieces.append(lowercase							)

				return new_pieces


	def    _a     (self	,				lowercase							):
				return self.sp_model.PieceToId(lowercase							)


	def    _a     (self	,				lowercase							):
				return self.sp_model.IdToPiece(lowercase							)


	def    _a     (self	,				lowercase							):
				A_     :						int     =					"""""".join(lowercase							).replace(lowercase	,				""" """							).strip()
				return out_string


	def    _a     (self	,				lowercase	,				lowercase = None							):
				A_     :						List[str]     =					[self.sep_token_id]
				A_     :						Any     =					[self.cls_token_id]
				if token_ids_a is None:
							return token_ids_a + sep + cls
				return token_ids_a + sep + token_ids_a + sep + cls


	def    _a     (self	,				lowercase	,				lowercase = None	,				lowercase = False							):

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

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


	def    _a     (self	,				lowercase	,				lowercase = None							):
				A_     :						str     =					[self.sep_token_id]
				A_     :						str     =					[2]

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


	def    _a     (self	,				lowercase	,				lowercase = None							):
				if not os.path.isdir(lowercase							):
							logger.error(F'Vocabulary path ({save_directory}) should be a directory'							)
							return
				A_     :						Tuple     =					os.path.join(
				    lowercase	,				(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]							)

				if os.path.abspath(self.vocab_file							) != os.path.abspath(lowercase							) and os.path.isfile(self.vocab_file							):
							copyfile(self.vocab_file	,				lowercase							)
				elif not os.path.isfile(self.vocab_file							):
							with open(lowercase	,				"""wb"""							) as fi:
										A_     :						Dict     =					self.sp_model.serialized_model_proto()
										fi.write(lowercase							)

				return (out_vocab_file,)


	def    _a     (self	,				*lowercase	,				**lowercase							):
				A_     :						Any     =					super()._decode(*lowercase	,				**lowercase							)
				A_     :						int     =					text.replace(""" """	,				""""""							).replace("""\u2582"""	,				""" """							).replace("""\u2583"""	,				"""\n"""							)
				return text