



"""simple docstring"""







import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class 			__A			(      __a	,__a	,unittest.TestCase       ):







		'''simple docstring'''





		lowerCAmelCase     :   List[str]        =							StableDiffusionXLImgaImgPipeline
		lowerCAmelCase     :   Dict        =							TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
		lowerCAmelCase     :   Dict        =							PipelineTesterMixin.required_optional_params - {'''latents'''}
		lowerCAmelCase     :   Optional[Any]        =							TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
		lowerCAmelCase     :   int        =							IMAGE_TO_IMAGE_IMAGE_PARAMS
		lowerCAmelCase     :   List[str]        =							IMAGE_TO_IMAGE_IMAGE_PARAMS







		def    UpperCAmelCase       (      self		:    Optional[Any]		)   ->						Tuple:






				"""simple docstring"""



				torch.manual_seed(0		)
				lowercase__  :       int												=     UNetaDConditionModel(
				    block_out_channels=(32, 64)     ,layers_per_block=2     ,sample_size=32     ,in_channels=4     ,out_channels=4     ,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')     ,up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')     ,attention_head_dim=(2, 4)     ,use_linear_projection=__UpperCamelCase     ,addition_embed_type='''text_time'''     ,addition_time_embed_dim=8     ,transformer_layers_per_block=(1, 2)     ,projection_class_embeddings_input_dim=80     ,cross_attention_dim=64     ,)
				lowercase__  :       Union[str, Any]												=     EulerDiscreteScheduler(
				    beta_start=0.0_0085     ,beta_end=0.012     ,steps_offset=1     ,beta_schedule='''scaled_linear'''     ,timestep_spacing='''leading'''     ,)
				torch.manual_seed(0		)
				lowercase__  :       Tuple												=     AutoencoderKL(
				    block_out_channels=[32, 64]     ,in_channels=3     ,out_channels=3     ,down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']     ,up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']     ,latent_channels=4     ,sample_size=128     ,)
				torch.manual_seed(0		)
				lowercase__  :       Union[str, Any]												=     CLIPTextConfig(
				    bos_token_id=0     ,eos_token_id=2     ,hidden_size=32     ,intermediate_size=37     ,layer_norm_eps=1e-05     ,num_attention_heads=4     ,num_hidden_layers=5     ,pad_token_id=1     ,vocab_size=1_000     ,hidden_act='''gelu'''     ,projection_dim=32     ,)
				lowercase__  :       List[str]												=     CLIPTextModel(__UpperCamelCase		)
				lowercase__  :       Optional[Any]												=     CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''     ,local_files_only=__UpperCamelCase		)

				lowercase__  :       Tuple												=     CLIPTextModelWithProjection(__UpperCamelCase		)
				lowercase__  :       List[Any]												=     CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''     ,local_files_only=__UpperCamelCase		)

				lowercase__  :       List[Any]												=     {
				    """unet""": unet,
				    """scheduler""": scheduler,
				    """vae""": vae,
				    """text_encoder""": text_encoder,
				    """tokenizer""": tokenizer,
				    """text_encoder_2""": text_encoder_a,
				    """tokenizer_2""": tokenizer_a,
				    # "safety_checker": None,
				    # "feature_extractor": None,
				}
				return components







		def    UpperCAmelCase       (      self		:    Optional[Any]     ,_snake_case		:    Tuple     ,_snake_case		:    str=0		)   ->						Dict:






				"""simple docstring"""



				lowercase__  :       Union[str, Any]												=     floats_tensor((1, 3, 32, 32)     ,rng=random.Random(__UpperCamelCase		)		).to(__UpperCamelCase		)
				lowercase__  :       str												=     image / 2 + 0.5
				if str(__UpperCamelCase		).startswith('''mps'''		):
						lowercase__  :       int												=     torch.manual_seed(__UpperCamelCase		)
				else:
						lowercase__  :       List[str]												=     torch.Generator(device=__UpperCamelCase		).manual_seed(__UpperCamelCase		)
				lowercase__  :       List[Any]												=     {
				    """prompt""": """A painting of a squirrel eating a burger""",
				    """image""": image,
				    """generator""": generator,
				    """num_inference_steps""": 2,
				    """guidance_scale""": 5.0,
				    """output_type""": """numpy""",
				    """strength""": 0.75,
				}
				return inputs







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






				"""simple docstring"""



				lowercase__  :       Union[str, Any]												=     """cpu"""  # ensure determinism for the device-dependent torch.Generator
				lowercase__  :       Optional[int]												=     self.get_dummy_components()
				lowercase__  :       Optional[Any]												=     StableDiffusionXLImgaImgPipeline(**__UpperCamelCase		)
				lowercase__  :       List[Any]												=     sd_pipe.to(__UpperCamelCase		)
				sd_pipe.set_progress_bar_config(disable=__UpperCamelCase		)

				lowercase__  :       int												=     self.get_dummy_inputs(__UpperCamelCase		)
				lowercase__  :       Optional[int]												=     sd_pipe(**__UpperCamelCase		).images
				lowercase__  :       Dict												=     image[0, -3:, -3:, -1]

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

				lowercase__  :       Tuple												=     np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165]		)

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







		def    UpperCAmelCase       (      self		:    str		)   ->						Tuple:






				"""simple docstring"""



				super().test_attention_slicing_forward_pass(expected_max_diff=3e-3		)







		def    UpperCAmelCase       (      self		:    Dict		)   ->						Dict:






				"""simple docstring"""



				super().test_inference_batch_single_identical(expected_max_diff=3e-3		)







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






				"""simple docstring"""



				pass







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






				"""simple docstring"""



				lowercase__  :       int												=     self.get_dummy_components()
				lowercase__  :       List[str]												=     StableDiffusionXLImgaImgPipeline(**__UpperCamelCase		)
				lowercase__  :       List[str]												=     sd_pipe.to(__UpperCamelCase		)
				lowercase__  :       Any												=     sd_pipe.to(__UpperCamelCase		)
				sd_pipe.set_progress_bar_config(disable=__UpperCamelCase		)

				# forward without prompt embeds
				lowercase__  :       Any												=     self.get_dummy_inputs(__UpperCamelCase		)
				lowercase__  :       Any												=     3 * ["""this is a negative prompt"""]
				lowercase__  :       int												=     negative_prompt
				lowercase__  :       Tuple												=     3 * [inputs["""prompt"""]]

				lowercase__  :       List[str]												=     sd_pipe(**__UpperCamelCase		)
				lowercase__  :       List[str]												=     output.images[0, -3:, -3:, -1]

				# forward with prompt embeds
				lowercase__  :       List[str]												=     self.get_dummy_inputs(__UpperCamelCase		)
				lowercase__  :       Optional[Any]												=     3 * ["""this is a negative prompt"""]
				lowercase__  :       Union[str, Any]												=     3 * [inputs.pop('''prompt'''		)]

				(
				    lowercase__
				)  :       int												=     sd_pipe.encode_prompt(__UpperCamelCase     ,negative_prompt=__UpperCamelCase		)

				lowercase__  :       str												=     sd_pipe(
				    **__UpperCamelCase     ,prompt_embeds=__UpperCamelCase     ,negative_prompt_embeds=__UpperCamelCase     ,pooled_prompt_embeds=__UpperCamelCase     ,negative_pooled_prompt_embeds=__UpperCamelCase     ,)
				lowercase__  :       Optional[int]												=     output.images[0, -3:, -3:, -1]

				# make sure that it's equal
				assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()		).max() < 1e-4





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







		'''simple docstring'''





		def    UpperCAmelCase       (      self		:    Any		)   ->						Tuple:






				"""simple docstring"""



				super().tearDown()
				gc.collect()
				torch.cuda.empty_cache()







		def    UpperCAmelCase       (      self		:    List[Any]     ,_snake_case		:    Any     ,_snake_case		:    Union[str, Any]="cpu"     ,_snake_case		:    List[Any]=torch.floataa     ,_snake_case		:    Optional[int]=0		)   ->						Optional[int]:






				"""simple docstring"""



				lowercase__  :       Any												=     torch.Generator(device=__UpperCamelCase		).manual_seed(__UpperCamelCase		)
				lowercase__  :       Any												=     np.random.RandomState(__UpperCamelCase		).standard_normal((1, 4, 64, 64)		)
				lowercase__  :       Optional[int]												=     torch.from_numpy(__UpperCamelCase		).to(device=__UpperCamelCase     ,dtype=__UpperCamelCase		)
				lowercase__  :       Tuple												=     {
				    """prompt""": """a photograph of an astronaut riding a horse""",
				    """latents""": latents,
				    """generator""": generator,
				    """num_inference_steps""": 3,
				    """guidance_scale""": 7.5,
				    """output_type""": """numpy""",
				}
				return inputs







		def    UpperCAmelCase       (      self		:    Any		)   ->						Optional[int]:






				"""simple docstring"""



				lowercase__  :       Union[str, Any]												=     DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''		)
				pipe.to(__UpperCamelCase		)
				pipe.set_progress_bar_config(disable=__UpperCamelCase		)

				lowercase__  :       Optional[Any]												=     self.get_inputs(__UpperCamelCase		)
				lowercase__  :       str												=     pipe(**__UpperCamelCase		).images
				lowercase__  :       List[Any]												=     image[0, -3:, -3:, -1].flatten()

				assert image.shape == (1, 512, 512, 3)
				lowercase__  :       List[str]												=     np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506]		)
				assert np.abs(image_slice - expected_slice		).max() < 7e-3

from __future__ import annotations

import json

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

SCREAMING_SNAKE_CASE		:     Union[str, Any]         =	{"UserAgent": UserAgent().random}






def     lowerCAmelCase_			(   _SCREAMING_SNAKE_CASE     :				Dict			):
						UpperCamelCase_		:							Tuple  =		script.contents[0]
						UpperCamelCase_		:							List[Any]  =		json.loads(data[data.find("""{\"config\""""			) : -1]			)
						return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]

class        UpperCamelCase						:





						def __init__(self			,     __UpperCamelCase						)				->				List[str]:
												UpperCamelCase_		:							Union[str, Any]  =		f'''https://www.instagram.com/{username}/'''
												UpperCamelCase_		:							Optional[int]  =		self.get_json()





						def        A_							(self						)				->				dict:
												UpperCamelCase_		:							Optional[Any]  =		requests.get(self.url			,     headers=__UpperCamelCase						).text
												UpperCamelCase_		:							Any  =		BeautifulSoup(__UpperCamelCase			,     """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						)				->				str:
												return f'''{self.__class__.__name__}(\'{self.username}\')'''





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





						@property
						def        A_							(self						)				->				str:
												return self.user_data["username"]





						@property
						def        A_							(self						)				->				str:
												return self.user_data["full_name"]





						@property
						def        A_							(self						)				->				str:
												return self.user_data["biography"]





						@property
						def        A_							(self						)				->				str:
												return self.user_data["business_email"]





						@property
						def        A_							(self						)				->				str:
												return self.user_data["external_url"]





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





						@property
						def        A_							(self						)				->				int:
												return self.user_data["edge_follow"]["count"]





						@property
						def        A_							(self						)				->				int:
												return self.user_data["edge_owner_to_timeline_media"]["count"]





						@property
						def        A_							(self						)				->				str:
												return self.user_data["profile_pic_url_hd"]





						@property
						def        A_							(self						)				->				bool:
												return self.user_data["is_verified"]





						@property
						def        A_							(self						)				->				bool:
												return self.user_data["is_private"]






def     lowerCAmelCase_			(   _SCREAMING_SNAKE_CASE     :				str = "github"			):
						import os

						if os.environ.get("""CI"""			):
												return  # test failing on GitHub Actions
						UpperCamelCase_		:							Any  =		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 > 150
						assert instagram_user.number_of_followers > 12_0000
						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()
	SCREAMING_SNAKE_CASE		:     Dict         =	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 = }''')






