



import gc
import random
import unittest

import numpy as np
import torch

from diffusers import (
    DDIMScheduler,
    KandinskyVaaControlnetPipeline,
    KandinskyVaaPriorPipeline,
    UNetaDConditionModel,
    VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()





class 		UpperCAmelCase						(						__SCREAMING_SNAKE_CASE       ,unittest.TestCase				):
   SCREAMING_SNAKE_CASE__							=     KandinskyVaaControlnetPipeline
   SCREAMING_SNAKE_CASE__							=     ['image_embeds', 'negative_image_embeds', 'hint']
   SCREAMING_SNAKE_CASE__							=     ['image_embeds', 'negative_image_embeds', 'hint']
   SCREAMING_SNAKE_CASE__							=     [
       'generator',
       'height',
       'width',
       'latents',
       'guidance_scale',
       'num_inference_steps',
       'return_dict',
       'guidance_scale',
       'num_images_per_prompt',
       'output_type',
       'return_dict',
   ]
   SCREAMING_SNAKE_CASE__							=     False





   @property
   def 	__lowerCAmelCase							(	self			):
         return 32





   @property
   def 	__lowerCAmelCase							(	self			):
         return 32





   @property
   def 	__lowerCAmelCase							(	self			):
         return self.time_input_dim





   @property
   def 	__lowerCAmelCase							(	self			):
         return self.time_input_dim * 4





   @property
   def 	__lowerCAmelCase							(	self			):
         return 100





   @property
   def 	__lowerCAmelCase							(	self			):
         torch.manual_seed(0			)

         _lowerCAmelCase 			=  {
             '''in_channels''': 8,
             # Out channels is double in channels because predicts mean and variance
             '''out_channels''': 8,
             '''addition_embed_type''': '''image_hint''',
             '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),
             '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),
             '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',
             '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),
             '''layers_per_block''': 1,
             '''encoder_hid_dim''': self.text_embedder_hidden_size,
             '''encoder_hid_dim_type''': '''image_proj''',
             '''cross_attention_dim''': self.cross_attention_dim,
             '''attention_head_dim''': 4,
             '''resnet_time_scale_shift''': '''scale_shift''',
             '''class_embed_type''': None,
         }

         _lowerCAmelCase 			=  UNetaDConditionModel(**_a			)
         return model





   @property
   def 	__lowerCAmelCase							(	self			):
         return {
             "block_out_channels": [32, 32, 64, 64],
             "down_block_types": [
                 "DownEncoderBlock2D",
                 "DownEncoderBlock2D",
                 "DownEncoderBlock2D",
                 "AttnDownEncoderBlock2D",
             ],
             "in_channels": 3,
             "latent_channels": 4,
             "layers_per_block": 1,
             "norm_num_groups": 8,
             "norm_type": "spatial",
             "num_vq_embeddings": 12,
             "out_channels": 3,
             "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
             "vq_embed_dim": 4,
         }





   @property
   def 	__lowerCAmelCase							(	self			):
         torch.manual_seed(0			)
         _lowerCAmelCase 			=  VQModel(**self.dummy_movq_kwargs			)
         return model





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.dummy_unet
         _lowerCAmelCase 			=  self.dummy_movq

         _lowerCAmelCase 			=  DDIMScheduler(
             num_train_timesteps=1_000       ,     beta_schedule='''linear'''       ,     beta_start=0.00_085       ,     beta_end=0.012       ,     clip_sample=_a       ,     set_alpha_to_one=_a       ,     steps_offset=1       ,     prediction_type='''epsilon'''       ,     thresholding=_a       ,     )

         _lowerCAmelCase 			=  {
             '''unet''': unet,
             '''scheduler''': scheduler,
             '''movq''': movq,
         }
         return components





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase=0			):
         _lowerCAmelCase 			=  floats_tensor((1, self.text_embedder_hidden_size)       ,     rng=random.Random(_a			)			).to(_a			)
         _lowerCAmelCase 			=  floats_tensor((1, self.text_embedder_hidden_size)       ,     rng=random.Random(seed + 1			)			).to(
             _a			)

         # create hint
         _lowerCAmelCase 			=  floats_tensor((1, 3, 64, 64)       ,     rng=random.Random(_a			)			).to(_a			)

         if str(_a			).startswith('''mps'''			):
               _lowerCAmelCase 			=  torch.manual_seed(_a			)
         else:
               _lowerCAmelCase 			=  torch.Generator(device=_a			).manual_seed(_a			)
         _lowerCAmelCase 			=  {
             '''image_embeds''': image_embeds,
             '''negative_image_embeds''': negative_image_embeds,
             '''hint''': hint,
             '''generator''': generator,
             '''height''': 64,
             '''width''': 64,
             '''guidance_scale''': 4.0,
             '''num_inference_steps''': 2,
             '''output_type''': '''np''',
         }
         return inputs





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  '''cpu'''

         _lowerCAmelCase 			=  self.get_dummy_components()

         _lowerCAmelCase 			=  self.pipeline_class(**_a			)
         _lowerCAmelCase 			=  pipe.to(_a			)

         pipe.set_progress_bar_config(disable=_a			)

         _lowerCAmelCase 			=  pipe(**self.get_dummy_inputs(_a			)			)
         _lowerCAmelCase 			=  output.images

         _lowerCAmelCase 			=  pipe(
             **self.get_dummy_inputs(_a			)       ,     return_dict=_a       ,     )[0]

         _lowerCAmelCase 			=  image[0, -3:, -3:, -1]
         _lowerCAmelCase 			=  image_from_tuple[0, -3:, -3:, -1]

         assert image.shape == (1, 64, 64, 3)

         _lowerCAmelCase 			=  np.array(
             [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595]			)

         assert (
             np.abs(image_slice.flatten() - expected_slice			).max() < 1E-2
         ), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''

         assert (
             np.abs(image_from_tuple_slice.flatten() - expected_slice			).max() < 1E-2
         ), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''






@slow
@require_torch_gpu
class 		UpperCAmelCase						(						unittest.TestCase				):





   def 	__lowerCAmelCase							(	self			):
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  load_numpy(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy'''			)

         _lowerCAmelCase 			=  load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/kandinskyv22/hint_image_cat.png'''			)
         _lowerCAmelCase 			=  torch.from_numpy(np.array(_a			)			).float() / 255.0
         _lowerCAmelCase 			=  hint.permute(2       ,     0       ,     1			).unsqueeze(0			)

         _lowerCAmelCase 			=  KandinskyVaaPriorPipeline.from_pretrained(
             '''kandinsky-community/kandinsky-2-2-prior'''       ,     torch_dtype=torch.floataa			)
         pipe_prior.to(_a			)

         _lowerCAmelCase 			=  KandinskyVaaControlnetPipeline.from_pretrained(
             '''kandinsky-community/kandinsky-2-2-controlnet-depth'''       ,     torch_dtype=torch.floataa			)
         _lowerCAmelCase 			=  pipeline.to(_a			)
         pipeline.set_progress_bar_config(disable=_a			)

         _lowerCAmelCase 			=  '''A robot, 4k photo'''

         _lowerCAmelCase 			=  torch.Generator(device='''cuda'''			).manual_seed(0			)
         _lowerCAmelCase			,   _lowerCAmelCase 			=  pipe_prior(
             _a       ,     generator=_a       ,     num_inference_steps=5       ,     negative_prompt=''''''       ,     ).to_tuple()

         _lowerCAmelCase 			=  torch.Generator(device='''cuda'''			).manual_seed(0			)
         _lowerCAmelCase 			=  pipeline(
             image_embeds=_a       ,     negative_image_embeds=_a       ,     hint=_a       ,     generator=_a       ,     num_inference_steps=100       ,     output_type='''np'''       ,     )

         _lowerCAmelCase 			=  output.images[0]

         assert image.shape == (512, 512, 3)

         assert_mean_pixel_difference(_a       ,     _a			)




from __future__ import annotations

import json

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

UpperCAmelCase_									=							{"UserAgent": UserAgent().random}
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Dict				)->dict:
      _lowerCAmelCase 			=  script.contents[0]
      _lowerCAmelCase 			=  json.loads(data[data.find('''{"config"'''				) : -1]				)
      return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]





class 		UpperCAmelCase						:





   def __init__(	self       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  F'''https://www.instagram.com/{username}/'''
         _lowerCAmelCase 			=  self.get_json()





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  requests.get(self.url       ,     headers=_lowerCAmelCase			).text
         _lowerCAmelCase 			=  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			):
         return F'''{self.__class__.__name__}(\'{self.username}\')'''





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





   @property
   def 	__lowerCAmelCase							(	self			):
         return self.user_data["username"]





   @property
   def 	__lowerCAmelCase							(	self			):
         return self.user_data["full_name"]





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





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





   @property
   def 	__lowerCAmelCase							(	self			):
         return self.user_data["external_url"]





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





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





   @property
   def 	__lowerCAmelCase							(	self			):
         return self.user_data["edge_owner_to_timeline_media"]["count"]





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





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





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






def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	str = "github"				)->None:
      import os

      if os.environ.get('''CI'''				):
            return  # test failing on GitHub Actions
      _lowerCAmelCase 			=  InstagramUser(_SCREAMING_SNAKE_CASE				)
      assert instagram_user.user_data
      assert isinstance(instagram_user.user_data     ,				_SCREAMING_SNAKE_CASE				)
      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_5_0
      assert instagram_user.number_of_followers > 1_2_0_0_0_0
      assert instagram_user.number_of_followings > 1_5
      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 = }""")