





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     UpperCamelCase__					(     lowerCamelCase__				, unittest.TestCase				):






		'''simple docstring'''






		__a       :       Any       =	"""ssube/stable-diffusion-x4-upscaler-onnx"""






		def 						snake_case__				(							self,   snake_case__=0  )       -> List[Any]:






									"""simple docstring"""
									lowercase_	:   Any  				=     floats_tensor((1, 3, 1_28, 1_28),   rng=random.Random(snake_case__  )  )
									lowercase_	:   int  				=     torch.manual_seed(snake_case__  )
									lowercase_	:   int  				=     {
									    """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 						snake_case__				(							self  )       -> Any:






									"""simple docstring"""
									lowercase_	:   Optional[int]  				=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,   provider="""CPUExecutionProvider"""  )
									pipe.set_progress_bar_config(disable=snake_case__  )

									lowercase_	:   Optional[Any]  				=     self.get_dummy_inputs()
									lowercase_	:   List[str]  				=     pipe(**snake_case__  ).images
									lowercase_	:   Optional[Any]  				=     image[0, -3:, -3:, -1].flatten()

									# started as 128, should now be 512
									assert image.shape == (1, 5_12, 5_12, 3)
									lowercase_	:   Optional[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 - expected_slice  ).max() < 1E-1






		def 						snake_case__				(							self  )       -> Dict:






									"""simple docstring"""
									lowercase_	:   Optional[int]  				=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,   provider="""CPUExecutionProvider"""  )
									lowercase_	:   Union[str, Any]  				=     PNDMScheduler.from_config(pipe.scheduler.config,   skip_prk_steps=snake_case__  )
									pipe.set_progress_bar_config(disable=snake_case__  )

									lowercase_	:   Dict  				=     self.get_dummy_inputs()
									lowercase_	:   Dict  				=     pipe(**snake_case__  ).images
									lowercase_	:   Any  				=     image[0, -3:, -3:, -1]

									assert image.shape == (1, 5_12, 5_12, 3)
									lowercase_	:   str  				=     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 						snake_case__				(							self  )       -> Optional[int]:






									"""simple docstring"""
									lowercase_	:   Any  				=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,   provider="""CPUExecutionProvider"""  )
									lowercase_	:   Union[str, Any]  				=     DPMSolverMultistepScheduler.from_config(pipe.scheduler.config  )
									pipe.set_progress_bar_config(disable=snake_case__  )

									lowercase_	:   List[str]  				=     self.get_dummy_inputs()
									lowercase_	:   Dict  				=     pipe(**snake_case__  ).images
									lowercase_	:   Tuple  				=     image[0, -3:, -3:, -1]

									assert image.shape == (1, 5_12, 5_12, 3)
									lowercase_	:   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 						snake_case__				(							self  )       -> Optional[int]:






									"""simple docstring"""
									lowercase_	:   str  				=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,   provider="""CPUExecutionProvider"""  )
									lowercase_	:   List[str]  				=     EulerDiscreteScheduler.from_config(pipe.scheduler.config  )
									pipe.set_progress_bar_config(disable=snake_case__  )

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

									assert image.shape == (1, 5_12, 5_12, 3)
									lowercase_	:   Optional[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 						snake_case__				(							self  )       -> Optional[Any]:






									"""simple docstring"""
									lowercase_	:   Tuple  				=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,   provider="""CPUExecutionProvider"""  )
									lowercase_	:   str  				=     EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config  )
									pipe.set_progress_bar_config(disable=snake_case__  )

									lowercase_	:   Dict  				=     self.get_dummy_inputs()
									lowercase_	:   Any  				=     pipe(**snake_case__  ).images
									lowercase_	:   List[Any]  				=     image[0, -3:, -3:, -1]

									assert image.shape == (1, 5_12, 5_12, 3)
									lowercase_	:   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     UpperCamelCase__					(     unittest.TestCase				):






		'''simple docstring'''






		@property
		def 						snake_case__				(							self  )       -> Tuple:






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






		@property
		def 						snake_case__				(							self  )       -> Dict:






									"""simple docstring"""
									lowercase_	:   Union[str, Any]  				=     ort.SessionOptions()
									lowercase_	:   Optional[Any]  				=     False
									return options






		def 						snake_case__				(							self  )       -> Tuple:






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

									lowercase_	:   int  				=     """A fantasy landscape, trending on artstation"""

									lowercase_	:   str  				=     torch.manual_seed(0  )
									lowercase_	:   str  				=     pipe(
									    prompt=snake_case__,   image=snake_case__,   guidance_scale=7.5,   num_inference_steps=10,   generator=snake_case__,   output_type="""np""",   )
									lowercase_	:   List[Any]  				=     output.images
									lowercase_	:   Dict  				=     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.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 						snake_case__				(							self  )       -> str:






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

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

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

									assert images.shape == (1, 5_12, 5_12, 3)
									lowercase_	:   Optional[Any]  				=     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






from argparse import ArgumentParser, Namespace
from typing import Any, List, Optional

from ..pipelines import Pipeline, get_supported_tasks, pipeline
from ..utils import logging
from . import BaseTransformersCLICommand


try:
							from fastapi import Body, FastAPI, HTTPException
							from fastapi.routing import APIRoute
							from pydantic import BaseModel
							from starlette.responses import JSONResponse
							from uvicorn import run

							UpperCAmelCase_							=				True
except (ImportError, AttributeError):
							UpperCAmelCase_							=				object





							def  __magic_name__  (				*lowercase				,       **lowercase				)				-> Optional[Any]:

														"""simple docstring"""



														pass




							UpperCAmelCase_							=				False


UpperCAmelCase_							=				logging.get_logger("""transformers-cli/serving""")





def  __magic_name__  (				lowercase				)				-> int:

							"""simple docstring"""



							lowercase_	:   Any  				=     pipeline(
							    task=args.task				,       model=args.model if args.model else None				,       config=args.config				,       tokenizer=args.tokenizer				,       device=args.device				,       )
							return ServeCommand(lowercase				,       args.host				,       args.port				,       args.workers				)
class     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		__a       :       dict




class     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		__a       :       List[str]
		__a       :       Optional[List[int]]




class     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		__a       :       str




class     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		__a       :       Any




class     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		@staticmethod
		def 						snake_case__				(							snake_case__  )       -> Optional[int]:






									"""simple docstring"""
									lowercase_	:   List[str]  				=     parser.add_parser(
									    """serve""",   help="""CLI tool to run inference requests through REST and GraphQL endpoints."""  )
									serve_parser.add_argument(
									    """--task""",   type=snake_case__,   choices=get_supported_tasks(),   help="""The task to run the pipeline on""",   )
									serve_parser.add_argument("""--host""",   type=snake_case__,   default="""localhost""",   help="""Interface the server will listen on."""  )
									serve_parser.add_argument("""--port""",   type=snake_case__,   default=88_88,   help="""Port the serving will listen to."""  )
									serve_parser.add_argument("""--workers""",   type=snake_case__,   default=1,   help="""Number of http workers"""  )
									serve_parser.add_argument("""--model""",   type=snake_case__,   help="""Model's name or path to stored model."""  )
									serve_parser.add_argument("""--config""",   type=snake_case__,   help="""Model's config name or path to stored model."""  )
									serve_parser.add_argument("""--tokenizer""",   type=snake_case__,   help="""Tokenizer name to use."""  )
									serve_parser.add_argument(
									    """--device""",   type=snake_case__,   default=-1,   help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""",   )
									serve_parser.set_defaults(func=snake_case__  )






		def __init__(							self,   snake_case__,   snake_case__,   snake_case__,   snake_case__  )       -> Optional[Any]:






									"""simple docstring"""
									lowercase_	:   str  				=     pipeline

									lowercase_	:   List[str]  				=     host
									lowercase_	:   int  				=     port
									lowercase_	:   Optional[Any]  				=     workers

									if not _serve_dependencies_installed:
																raise RuntimeError(
																    """Using serve command requires FastAPI and uvicorn. """
																    """Please install transformers with [serving]: pip install \"transformers[serving]\"."""
																    """Or install FastAPI and uvicorn separately."""  )
									else:
																logger.info(f"""Serving model over {host}:{port}"""  )
																lowercase_	:   Union[str, Any]  				=     FastAPI(
																    routes=[
																        APIRoute(
																            """/""",   self.model_info,   response_model=snake_case__,   response_class=snake_case__,   methods=["""GET"""],   ),
																        APIRoute(
																            """/tokenize""",   self.tokenize,   response_model=snake_case__,   response_class=snake_case__,   methods=["""POST"""],   ),
																        APIRoute(
																            """/detokenize""",   self.detokenize,   response_model=snake_case__,   response_class=snake_case__,   methods=["""POST"""],   ),
																        APIRoute(
																            """/forward""",   self.forward,   response_model=snake_case__,   response_class=snake_case__,   methods=["""POST"""],   ),
																    ],   timeout=6_00,   )






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






									"""simple docstring"""
									run(self._app,   host=self.host,   port=self.port,   workers=self.workers  )






		def 						snake_case__				(							self  )       -> Dict:






									"""simple docstring"""
									return ServeModelInfoResult(infos=vars(self._pipeline.model.config  )  )






		def 						snake_case__				(							self,   snake_case__ = Body(snake_case__,   embed=snake_case__  ),   snake_case__ = Body(snake_case__,   embed=snake_case__  )  )       -> Optional[int]:






									"""simple docstring"""
									try:
																lowercase_	:   Tuple  				=     self._pipeline.tokenizer.tokenize(snake_case__  )

																if return_ids:
																							lowercase_	:   Union[str, Any]  				=     self._pipeline.tokenizer.convert_tokens_to_ids(snake_case__  )
																							return ServeTokenizeResult(tokens=snake_case__,   tokens_ids=snake_case__  )
																else:
																							return ServeTokenizeResult(tokens=snake_case__  )

									except Exception as e:
																raise HTTPException(status_code=5_00,   detail={"""model""": """""", """error""": str(snake_case__  )}  )






		def 						snake_case__				(							self,   snake_case__ = Body(snake_case__,   embed=snake_case__  ),   snake_case__ = Body(snake_case__,   embed=snake_case__  ),   snake_case__ = Body(snake_case__,   embed=snake_case__  ),   )       -> Dict:






									"""simple docstring"""
									try:
																lowercase_	:   List[Any]  				=     self._pipeline.tokenizer.decode(snake_case__,   snake_case__,   snake_case__  )
																return ServeDeTokenizeResult(model="""""",   text=snake_case__  )
									except Exception as e:
																raise HTTPException(status_code=5_00,   detail={"""model""": """""", """error""": str(snake_case__  )}  )






		async def 						snake_case__				(							self,   snake_case__=Body(snake_case__,   embed=snake_case__  )  )       -> Tuple:






									"""simple docstring"""

									# Check we don't have empty string
									if len(snake_case__  ) == 0:
																return ServeForwardResult(output=[],   attention=[]  )

									try:
																# Forward through the model
																lowercase_	:   Optional[int]  				=     self._pipeline(snake_case__  )
																return ServeForwardResult(output=snake_case__  )
									except Exception as e:
																raise HTTPException(5_00,   {"""error""": str(snake_case__  )}  )