




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 					snake_case__							(_UpperCamelCase					, unittest.TestCase     ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_ :							List[Any]											=      """ssube/stable-diffusion-x4-upscaler-onnx"""





				def 							__UpperCAmelCase							(   self       :  Tuple      ,   __lowerCamelCase       :  Any=0							)      ->  Tuple:
							a					=    floats_tensor((1, 3, 1_28, 1_28)      ,   rng=random.Random(__lowerCamelCase							)							)
							a					=    torch.manual_seed(__lowerCamelCase							)
							a					=    {
							    "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       :  Dict							)      ->  Optional[Any]:
							a					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint      ,   provider="CPUExecutionProvider"							)
							pipe.set_progress_bar_config(disable=__lowerCamelCase							)

							a					=    self.get_dummy_inputs()
							a					=    pipe(**__lowerCamelCase							).images
							a					=    image[0, -3:, -3:, -1].flatten()

							# started as 128, should now be 512
							assert image.shape == (1, 5_12, 5_12, 3)
							a					=    np.array(
							    [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223]							)
							assert np.abs(image_slice - expected_slice							).max() < 1e-1





				def 							__UpperCAmelCase							(   self       :  Union[str, Any]							)      ->  int:
							a					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint      ,   provider="CPUExecutionProvider"							)
							a					=    PNDMScheduler.from_config(pipe.scheduler.config      ,   skip_prk_steps=__lowerCamelCase							)
							pipe.set_progress_bar_config(disable=__lowerCamelCase							)

							a					=    self.get_dummy_inputs()
							a					=    pipe(**__lowerCamelCase							).images
							a					=    image[0, -3:, -3:, -1]

							assert image.shape == (1, 5_12, 5_12, 3)
							a					=    np.array(
							    [0.6_898_892, 0.59_240_556, 0.52_499_527, 0.58_866_215, 0.52_258_235, 0.52_572_715, 0.62_414_473, 0.6_174_387, 0.6_214_964]							)
							assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-1





				def 							__UpperCAmelCase							(   self       :  Dict							)      ->  List[Any]:
							a					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint      ,   provider="CPUExecutionProvider"							)
							a					=    DPMSolverMultistepScheduler.from_config(pipe.scheduler.config							)
							pipe.set_progress_bar_config(disable=__lowerCamelCase							)

							a					=    self.get_dummy_inputs()
							a					=    pipe(**__lowerCamelCase							).images
							a					=    image[0, -3:, -3:, -1]

							assert image.shape == (1, 5_12, 5_12, 3)
							a					=    np.array(
							    [0.7_659_278, 0.76_437_664, 0.75_579_107, 0.7_691_116, 0.77_666_986, 0.7_727_672, 0.7_758_664, 0.7_812_226, 0.76_942_515]							)

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





				def 							__UpperCAmelCase							(   self       :  Optional[int]							)      ->  str:
							a					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint      ,   provider="CPUExecutionProvider"							)
							a					=    EulerDiscreteScheduler.from_config(pipe.scheduler.config							)
							pipe.set_progress_bar_config(disable=__lowerCamelCase							)

							a					=    self.get_dummy_inputs()
							a					=    pipe(**__lowerCamelCase							).images
							a					=    image[0, -3:, -3:, -1]

							assert image.shape == (1, 5_12, 5_12, 3)
							a					=    np.array(
							    [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223]							)
							assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-1





				def 							__UpperCAmelCase							(   self       :  List[Any]							)      ->  Union[str, Any]:
							a					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint      ,   provider="CPUExecutionProvider"							)
							a					=    EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config							)
							pipe.set_progress_bar_config(disable=__lowerCamelCase							)

							a					=    self.get_dummy_inputs()
							a					=    pipe(**__lowerCamelCase							).images
							a					=    image[0, -3:, -3:, -1]

							assert image.shape == (1, 5_12, 5_12, 3)
							a					=    np.array(
							    [0.77_424_496, 0.773_601, 0.7_645_288, 0.7_769_598, 0.7_772_739, 0.7_738_688, 0.78_187_233, 0.77_879_584, 0.767_043]							)

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




@nightly
@require_onnxruntime
@require_torch_gpu
class 					snake_case__							(unittest.TestCase     ):
				"""simple docstring"""



				@property
				def 							__UpperCAmelCase							(   self       :  str							)      ->  Optional[Any]:
							return (
							    "CUDAExecutionProvider",
							    {
							        "gpu_mem_limit": "15000000000",  # 15GB
							        "arena_extend_strategy": "kSameAsRequested",
							    },
							)





				@property
				def 							__UpperCAmelCase							(   self       :  Dict							)      ->  List[Any]:
							a					=    ort.SessionOptions()
							a					=    False
							return options





				def 							__UpperCAmelCase							(   self       :  int							)      ->  str:
							a					=    load_image(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
							    "/img2img/sketch-mountains-input.jpg"							)
							a					=    init_image.resize((1_28, 1_28)							)
							# using the PNDM scheduler by default
							a					=    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							)

							a					=    "A fantasy landscape, trending on artstation"

							a					=    torch.manual_seed(0							)
							a					=    pipe(
							    prompt=__lowerCamelCase      ,   image=__lowerCamelCase      ,   guidance_scale=7.5      ,   num_inference_steps=10      ,   generator=__lowerCamelCase      ,   output_type="np"      ,   )
							a					=    output.images
							a					=    images[0, 2_55:2_58, 3_83:3_86, -1]

							assert images.shape == (1, 5_12, 5_12, 3)
							a					=    np.array([0.4_883, 0.4_947, 0.4_980, 0.4_975, 0.4_982, 0.4_980, 0.5_000, 0.5_006, 0.4_972]							)
							# 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       :  List[Any]							)      ->  List[Any]:
							a					=    load_image(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
							    "/img2img/sketch-mountains-input.jpg"							)
							a					=    init_image.resize((1_28, 1_28)							)
							a					=    LMSDiscreteScheduler.from_pretrained(
							    "ssube/stable-diffusion-x4-upscaler-onnx"      ,   subfolder="scheduler"							)
							a					=    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							)

							a					=    "A fantasy landscape, trending on artstation"

							a					=    torch.manual_seed(0							)
							a					=    pipe(
							    prompt=__lowerCamelCase      ,   image=__lowerCamelCase      ,   guidance_scale=7.5      ,   num_inference_steps=20      ,   generator=__lowerCamelCase      ,   output_type="np"      ,   )
							a					=    output.images
							a					=    images[0, 2_55:2_58, 3_83:3_86, -1]

							assert images.shape == (1, 5_12, 5_12, 3)
							a					=    np.array(
							    [0.50_173_753, 0.50_223_356, 0.502_039, 0.50_233_036, 0.5_023_725, 0.5_022_601, 0.5_018_758, 0.50_234_085, 0.50_241_566]							)
							# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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












import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available


if is_vision_available():
		from PIL import Image

		from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor




@require_vision
class 					snake_case__							(unittest.TestCase     ):
				"""simple docstring"""



				def 							__UpperCAmelCase							(   self       :  int							)      ->  Dict:
							a					=    tempfile.mkdtemp()

							a					=    [
							    "[UNK]",
							    "[CLS]",
							    "[SEP]",
							    "[PAD]",
							    "[MASK]",
							    "的",
							    "价",
							    "格",
							    "是",
							    "15",
							    "便",
							    "alex",
							    "##andra",
							    "，",
							    "。",
							    "-",
							    "t",
							    "shirt",
							]
							a					=    os.path.join(self.tmpdirname      ,   VOCAB_FILES_NAMES["vocab_file"]							)
							with open(self.vocab_file      ,   "w"      ,   encoding="utf-8"							) as vocab_writer:
										vocab_writer.write("".join([x + "\n" for x in vocab_tokens]							)							)

							a					=    {
							    "do_resize": True,
							    "size": {"height": 2_24, "width": 2_24},
							    "do_center_crop": True,
							    "crop_size": {"height": 18, "width": 18},
							    "do_normalize": True,
							    "image_mean": [0.48_145_466, 0.4_578_275, 0.40_821_073],
							    "image_std": [0.26_862_954, 0.26_130_258, 0.27_577_711],
							    "do_convert_rgb": True,
							}
							a					=    os.path.join(self.tmpdirname      ,   __lowerCamelCase							)
							with open(self.image_processor_file      ,   "w"      ,   encoding="utf-8"							) as fp:
										json.dump(__lowerCamelCase      ,   __lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  Dict      ,   **__lowerCamelCase       :  Union[str, Any]							)      ->  List[Any]:
							return BertTokenizer.from_pretrained(self.tmpdirname      ,   **__lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  str      ,   **__lowerCamelCase       :  Optional[int]							)      ->  str:
							return BertTokenizerFast.from_pretrained(self.tmpdirname      ,   **__lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  List[str]      ,   **__lowerCamelCase       :  Optional[int]							)      ->  Tuple:
							return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname      ,   **__lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  Optional[int]							)      ->  Optional[Any]:
							shutil.rmtree(self.tmpdirname							)





				def 							__UpperCAmelCase							(   self       :  List[str]							)      ->  Optional[int]:
							a					=    [np.random.randint(2_55      ,   size=(3, 30, 4_00)      ,   dtype=np.uinta							)]

							a					=    [Image.fromarray(np.moveaxis(__lowerCamelCase      ,   0      ,   -1							)							) for x in image_inputs]

							return image_inputs





				def 							__UpperCAmelCase							(   self       :  int							)      ->  List[str]:
							a					=    self.get_tokenizer()
							a					=    self.get_rust_tokenizer()
							a					=    self.get_image_processor()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)
							processor_slow.save_pretrained(self.tmpdirname							)
							a					=    ChineseCLIPProcessor.from_pretrained(self.tmpdirname      ,   use_fast=__lowerCamelCase							)

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)
							processor_fast.save_pretrained(self.tmpdirname							)
							a					=    ChineseCLIPProcessor.from_pretrained(self.tmpdirname							)

							self.assertEqual(processor_slow.tokenizer.get_vocab()      ,   tokenizer_slow.get_vocab()							)
							self.assertEqual(processor_fast.tokenizer.get_vocab()      ,   tokenizer_fast.get_vocab()							)
							self.assertEqual(tokenizer_slow.get_vocab()      ,   tokenizer_fast.get_vocab()							)
							self.assertIsInstance(processor_slow.tokenizer      ,   __lowerCamelCase							)
							self.assertIsInstance(processor_fast.tokenizer      ,   __lowerCamelCase							)

							self.assertEqual(processor_slow.image_processor.to_json_string()      ,   image_processor.to_json_string()							)
							self.assertEqual(processor_fast.image_processor.to_json_string()      ,   image_processor.to_json_string()							)
							self.assertIsInstance(processor_slow.image_processor      ,   __lowerCamelCase							)
							self.assertIsInstance(processor_fast.image_processor      ,   __lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  Optional[int]							)      ->  List[Any]:
							a					=    ChineseCLIPProcessor(tokenizer=self.get_tokenizer()      ,   image_processor=self.get_image_processor()							)
							processor.save_pretrained(self.tmpdirname							)

							a					=    self.get_tokenizer(cls_token="(CLS)"      ,   sep_token="(SEP)"							)
							a					=    self.get_image_processor(do_normalize=__lowerCamelCase							)

							a					=    ChineseCLIPProcessor.from_pretrained(
							    self.tmpdirname      ,   cls_token="(CLS)"      ,   sep_token="(SEP)"      ,   do_normalize=__lowerCamelCase							)

							self.assertEqual(processor.tokenizer.get_vocab()      ,   tokenizer_add_kwargs.get_vocab()							)
							self.assertIsInstance(processor.tokenizer      ,   __lowerCamelCase							)

							self.assertEqual(processor.image_processor.to_json_string()      ,   image_processor_add_kwargs.to_json_string()							)
							self.assertIsInstance(processor.image_processor      ,   __lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  Tuple							)      ->  Dict:
							a					=    self.get_image_processor()
							a					=    self.get_tokenizer()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)

							a					=    self.prepare_image_inputs()

							a					=    image_processor(__lowerCamelCase      ,   return_tensors="np"							)
							a					=    processor(images=__lowerCamelCase      ,   return_tensors="np"							)

							for key in input_feat_extract.keys():
										self.assertAlmostEqual(input_feat_extract[key].sum()      ,   input_processor[key].sum()      ,   delta=1e-2							)





				def 							__UpperCAmelCase							(   self       :  str							)      ->  Optional[int]:
							a					=    self.get_image_processor()
							a					=    self.get_tokenizer()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)

							a					=    "Alexandra，T-shirt的价格是15便士。"

							a					=    processor(text=__lowerCamelCase							)

							a					=    tokenizer(__lowerCamelCase							)

							for key in encoded_tok.keys():
										self.assertListEqual(encoded_tok[key]      ,   encoded_processor[key]							)





				def 							__UpperCAmelCase							(   self       :  List[Any]							)      ->  Any:
							a					=    self.get_image_processor()
							a					=    self.get_tokenizer()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)

							a					=    "Alexandra，T-shirt的价格是15便士。"
							a					=    self.prepare_image_inputs()

							a					=    processor(text=__lowerCamelCase      ,   images=__lowerCamelCase							)

							self.assertListEqual(list(inputs.keys()							)      ,   ["input_ids", "token_type_ids", "attention_mask", "pixel_values"]							)

							# test if it raises when no input is passed
							with pytest.raises(__lowerCamelCase							):
										processor()





				def 							__UpperCAmelCase							(   self       :  List[str]							)      ->  Optional[int]:
							a					=    self.get_image_processor()
							a					=    self.get_tokenizer()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)

							a					=    [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

							a					=    processor.batch_decode(__lowerCamelCase							)
							a					=    tokenizer.batch_decode(__lowerCamelCase							)

							self.assertListEqual(__lowerCamelCase      ,   __lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  Dict							)      ->  List[str]:
							a					=    self.get_image_processor()
							a					=    self.get_tokenizer()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)

							a					=    "Alexandra，T-shirt的价格是15便士。"
							a					=    self.prepare_image_inputs()

							a					=    processor(text=__lowerCamelCase      ,   images=__lowerCamelCase							)

							self.assertListEqual(list(inputs.keys()							)      ,   processor.model_input_names							)






