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


    def   lowerCAmelCase_	(       self						:	Dict ,					__lowerCAmelCase						:	Any=0       ):
      _UpperCAmelCase    			=   floats_tensor((1, 3, 128, 128) ,					rng=random.Random(__lowerCAmelCase       )       )
      _UpperCAmelCase    			=   torch.manual_seed(__lowerCAmelCase       )
      _UpperCAmelCase    			=   {
          """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       ):
      _UpperCAmelCase    			=   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,					provider="""CPUExecutionProvider"""       )
      pipe.set_progress_bar_config(disable=__lowerCAmelCase       )

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

      # started as 128, should now be 512
      assert image.shape == (1, 512, 512, 3)
      _UpperCAmelCase    			=   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   lowerCAmelCase_	(       self						:	Optional[int]       ):
      _UpperCAmelCase    			=   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,					provider="""CPUExecutionProvider"""       )
      _UpperCAmelCase    			=   PNDMScheduler.from_config(pipe.scheduler.config ,					skip_prk_steps=__lowerCAmelCase       )
      pipe.set_progress_bar_config(disable=__lowerCAmelCase       )

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

      assert image.shape == (1, 512, 512, 3)
      _UpperCAmelCase    			=   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   lowerCAmelCase_	(       self						:	str       ):
      _UpperCAmelCase    			=   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,					provider="""CPUExecutionProvider"""       )
      _UpperCAmelCase    			=   DPMSolverMultistepScheduler.from_config(pipe.scheduler.config       )
      pipe.set_progress_bar_config(disable=__lowerCAmelCase       )

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

      assert image.shape == (1, 512, 512, 3)
      _UpperCAmelCase    			=   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   lowerCAmelCase_	(       self						:	Any       ):
      _UpperCAmelCase    			=   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,					provider="""CPUExecutionProvider"""       )
      _UpperCAmelCase    			=   EulerDiscreteScheduler.from_config(pipe.scheduler.config       )
      pipe.set_progress_bar_config(disable=__lowerCAmelCase       )

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

      assert image.shape == (1, 512, 512, 3)
      _UpperCAmelCase    			=   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   lowerCAmelCase_	(       self						:	Dict       ):
      _UpperCAmelCase    			=   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,					provider="""CPUExecutionProvider"""       )
      _UpperCAmelCase    			=   EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config       )
      pipe.set_progress_bar_config(disable=__lowerCAmelCase       )

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

      assert image.shape == (1, 512, 512, 3)
      _UpperCAmelCase    			=   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 							a					(		unittest.TestCase ):


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


    @property
    def   lowerCAmelCase_	(       self						:	Dict       ):
      _UpperCAmelCase    			=   ort.SessionOptions()
      _UpperCAmelCase    			=   False
      return options


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

      _UpperCAmelCase    			=   """A fantasy landscape, trending on artstation"""

      _UpperCAmelCase    			=   torch.manual_seed(0       )
      _UpperCAmelCase    			=   pipe(
          prompt=__lowerCAmelCase ,					image=__lowerCAmelCase ,					guidance_scale=7.5 ,					num_inference_steps=10 ,					generator=__lowerCAmelCase ,					output_type="""np""" ,					)
      _UpperCAmelCase    			=   output.images
      _UpperCAmelCase    			=   images[0, 255:258, 383:386, -1]

      assert images.shape == (1, 512, 512, 3)
      _UpperCAmelCase    			=   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   lowerCAmelCase_	(       self						:	int       ):
      _UpperCAmelCase    			=   load_image(
          """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
          """/img2img/sketch-mountains-input.jpg"""       )
      _UpperCAmelCase    			=   init_image.resize((128, 128)       )
      _UpperCAmelCase    			=   LMSDiscreteScheduler.from_pretrained(
          """ssube/stable-diffusion-x4-upscaler-onnx""" ,					subfolder="""scheduler"""       )
      _UpperCAmelCase    			=   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       )

      _UpperCAmelCase    			=   """A fantasy landscape, trending on artstation"""

      _UpperCAmelCase    			=   torch.manual_seed(0       )
      _UpperCAmelCase    			=   pipe(
          prompt=__lowerCAmelCase ,					image=__lowerCAmelCase ,					guidance_scale=7.5 ,					num_inference_steps=20 ,					generator=__lowerCAmelCase ,					output_type="""np""" ,					)
      _UpperCAmelCase    			=   output.images
      _UpperCAmelCase    			=   images[0, 255:258, 383:386, -1]

      assert images.shape == (1, 512, 512, 3)
      _UpperCAmelCase    			=   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

"""simple docstring"""


from __future__ import annotations

import json

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

UpperCAmelCase__			=    {"""UserAgent""": UserAgent().random}






def      __UpperCAmelCase       (      lowercase		):







  """simple docstring"""
  _UpperCAmelCase    			=   script.contents[0]
  _UpperCAmelCase    			=   json.loads(data[data.find("""{\"config\""""		) : -1]		)
  return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]


class 							a					:


    def __init__(       self						:	Any ,					__lowerCAmelCase						:	Union[str, Any]       ):
      _UpperCAmelCase    			=   f'''https://www.instagram.com/{username}/'''
      _UpperCAmelCase    			=   self.get_json()


    def   lowerCAmelCase_	(       self						:	int       ):
      _UpperCAmelCase    			=   requests.get(self.url ,					headers=__lowerCAmelCase       ).text
      _UpperCAmelCase    			=   BeautifulSoup(__lowerCAmelCase ,					"""html.parser"""       ).find_all("""script"""       )
      try:
        return extract_user_profile(scripts[4]       )
      except (json.decoder.JSONDecodeError, KeyError):
        return extract_user_profile(scripts[3]       )


    def __repr__(       self						:	Dict       ):
      return f'''{self.__class__.__name__}(\'{self.username}\')'''


    def __str__(       self						:	int       ):
      return f'''{self.fullname} ({self.username}) is {self.biography}'''


    @property
    def   lowerCAmelCase_	(       self						:	Union[str, Any]       ):
      return self.user_data["username"]


    @property
    def   lowerCAmelCase_	(       self						:	List[Any]       ):
      return self.user_data["full_name"]


    @property
    def   lowerCAmelCase_	(       self						:	str       ):
      return self.user_data["biography"]


    @property
    def   lowerCAmelCase_	(       self						:	str       ):
      return self.user_data["business_email"]


    @property
    def   lowerCAmelCase_	(       self						:	List[Any]       ):
      return self.user_data["external_url"]


    @property
    def   lowerCAmelCase_	(       self						:	int       ):
      return self.user_data["edge_followed_by"]["count"]


    @property
    def   lowerCAmelCase_	(       self						:	Tuple       ):
      return self.user_data["edge_follow"]["count"]


    @property
    def   lowerCAmelCase_	(       self						:	List[str]       ):
      return self.user_data["edge_owner_to_timeline_media"]["count"]


    @property
    def   lowerCAmelCase_	(       self						:	int       ):
      return self.user_data["profile_pic_url_hd"]


    @property
    def   lowerCAmelCase_	(       self						:	str       ):
      return self.user_data["is_verified"]


    @property
    def   lowerCAmelCase_	(       self						:	int       ):
      return self.user_data["is_private"]






def      __UpperCAmelCase       (      lowercase = "github"		):







  """simple docstring"""
  import os

  if os.environ.get("""CI"""		):
    return  # test failing on GitHub Actions
  _UpperCAmelCase    			=   InstagramUser(lowercase		)
  assert instagram_user.user_data
  assert isinstance(instagram_user.user_data ,lowercase		)
  assert instagram_user.username == username
  if username != "github":
    return
  assert instagram_user.fullname == "GitHub"
  assert instagram_user.biography == "Built for developers."
  assert instagram_user.number_of_posts > 1_50
  assert instagram_user.number_of_followers > 12_00_00
  assert instagram_user.number_of_followings > 15
  assert instagram_user.email == "support@github.com"
  assert instagram_user.website == "https://github.com/readme"
  assert instagram_user.profile_picture_url.startswith("""https://instagram."""		)
  assert instagram_user.is_verified is True
  assert instagram_user.is_private is False


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    UpperCAmelCase__			=    InstagramUser("""github""")
    print(instagram_user)
    print(F'''{instagram_user.number_of_posts = }''')
    print(F'''{instagram_user.number_of_followers = }''')
    print(F'''{instagram_user.number_of_followings = }''')
    print(F'''{instagram_user.email = }''')
    print(F'''{instagram_user.website = }''')
    print(F'''{instagram_user.profile_picture_url = }''')
    print(F'''{instagram_user.is_verified = }''')
    print(F'''{instagram_user.is_private = }''')
