

"""simple docstring"""




import inspect
from typing import Optional, Union

import numpy as np
import PIL
import torch
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    DPMSolverMultistepScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.utils import (
    PIL_INTERPOLATION,
    randn_tensor,
)





def       lowercase__						(       snake_case_   :Optional[Any]			,		snake_case_   :int			,		snake_case_   :Union[str, Any]    ):
	if isinstance(snake_case_			,		torch.Tensor    ):
		return image
	elif isinstance(snake_case_			,		PIL.Image.Image    ):
		__UpperCAmelCase      		= [image]

	if isinstance(image[0]			,		PIL.Image.Image    ):
		__UpperCAmelCase      		= [np.array(i.resize((w, h)			,		resample=PIL_INTERPOLATION['''lanczos''']    )    )[None, :] for i in image]
		__UpperCAmelCase      		= np.concatenate(snake_case_			,		axis=0    )
		__UpperCAmelCase      		= np.array(snake_case_    ).astype(np.floataa    ) / 255.0
		__UpperCAmelCase      		= image.transpose(0			,		3			,		1			,		2    )
		__UpperCAmelCase      		= 2.0 * image - 1.0
		__UpperCAmelCase      		= torch.from_numpy(snake_case_    )
	elif isinstance(image[0]			,		torch.Tensor    ):
		__UpperCAmelCase      		= torch.cat(snake_case_			,		dim=0    )
	return image





def       lowercase__						(       snake_case_   :List[str]			,		snake_case_   :Optional[int]			,		snake_case_   :Optional[Any]			,		snake_case_   :Union[str, Any]=0.9995    ):
	if not isinstance(snake_case_			,		np.ndarray    ):
		__UpperCAmelCase      		= True
		__UpperCAmelCase      		= va.device
		__UpperCAmelCase      		= va.cpu().numpy()
		__UpperCAmelCase      		= va.cpu().numpy()

	__UpperCAmelCase      		= np.sum(va * va / (np.linalg.norm(snake_case_    ) * np.linalg.norm(snake_case_    ))    )
	if np.abs(snake_case_    ) > DOT_THRESHOLD:
		__UpperCAmelCase      		= (1 - t) * va + t * va
	else:
		__UpperCAmelCase      		= np.arccos(snake_case_    )
		__UpperCAmelCase      		= np.sin(snake_case_    )
		__UpperCAmelCase      		= theta_a * t
		__UpperCAmelCase      		= np.sin(snake_case_    )
		__UpperCAmelCase      		= np.sin(theta_a - theta_t    ) / sin_theta_a
		__UpperCAmelCase      		= sin_theta_t / sin_theta_a
		__UpperCAmelCase      		= sa * va + sa * va

	if inputs_are_torch:
		__UpperCAmelCase      		= torch.from_numpy(snake_case_    ).to(snake_case_    )

	return va





def       lowercase__						(       snake_case_   :Optional[Any]			,		snake_case_   :List[Any]    ):
	__UpperCAmelCase      		= F.normalize(snake_case_			,		dim=-1    )
	__UpperCAmelCase      		= F.normalize(snake_case_			,		dim=-1    )
	return (x - y).norm(dim=-1    ).div(2    ).arcsin().pow(2    ).mul(2    )





def       lowercase__						(       snake_case_   :Union[str, Any]			,		snake_case_   :Optional[int]    ):
	for param in model.parameters():
		__UpperCAmelCase      		= value




class      _UpperCAmelCase   (							_lowerCAmelCase       ):



	def __init__(  self     :       List[str]			,    _lowercase     :       AutoencoderKL			,    _lowercase     :       CLIPTextModel			,    _lowercase     :       CLIPModel			,    _lowercase     :       CLIPTokenizer			,    _lowercase     :       UNetaDConditionModel			,    _lowercase     :       Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler]			,    _lowercase     :       CLIPFeatureExtractor			,    _lowercase     :       Optional[Any]=None			,    _lowercase     :       Any=None			,    _lowercase     :       Optional[Any]=None			,    ):
		super().__init__()
		self.register_modules(
		    vae=_lowercase			,    text_encoder=_lowercase			,    clip_model=_lowercase			,    tokenizer=_lowercase			,    unet=_lowercase			,    scheduler=_lowercase			,    feature_extractor=_lowercase			,    coca_model=_lowercase			,    coca_tokenizer=_lowercase			,    coca_transform=_lowercase			,    )
		__UpperCAmelCase      		= (
		    feature_extractor.size
		    if isinstance(feature_extractor.size			,    _lowercase						)
		    else feature_extractor.size['''shortest_edge''']
		)
		__UpperCAmelCase      		= transforms.Normalize(mean=feature_extractor.image_mean			,    std=feature_extractor.image_std						)
		set_requires_grad(self.text_encoder			,    _lowercase						)
		set_requires_grad(self.clip_model			,    _lowercase						)



	def        a  (  self     :       Optional[int]			,    _lowercase     :       Optional[Union[str, int]] = "auto"						):
		if slice_size == "auto":
			# half the attention head size is usually a good trade-off between
			# speed and memory
			__UpperCAmelCase      		= self.unet.config.attention_head_dim // 2
		self.unet.set_attention_slice(_lowercase						)



	def        a  (  self     :       List[Any]						):
		self.enable_attention_slicing(_lowercase						)



	def        a  (  self     :       Tuple						):
		set_requires_grad(self.vae			,    _lowercase						)



	def        a  (  self     :       List[str]						):
		set_requires_grad(self.vae			,    _lowercase						)



	def        a  (  self     :       List[Any]						):
		set_requires_grad(self.unet			,    _lowercase						)



	def        a  (  self     :       List[str]						):
		set_requires_grad(self.unet			,    _lowercase						)



	def        a  (  self     :       Tuple			,    _lowercase     :       Optional[int]			,    _lowercase     :       Union[str, Any]			,    _lowercase     :       List[str]						):
		# get the original timestep using init_timestep
		__UpperCAmelCase      		= min(int(num_inference_steps * strength						)			,    _lowercase						)

		__UpperCAmelCase      		= max(num_inference_steps - init_timestep			,    0						)
		__UpperCAmelCase      		= self.scheduler.timesteps[t_start:]

		return timesteps, num_inference_steps - t_start



	def        a  (  self     :       Optional[Any]			,    _lowercase     :       Any			,    _lowercase     :       List[str]			,    _lowercase     :       Any			,    _lowercase     :       Tuple			,    _lowercase     :       List[str]			,    _lowercase     :       Any=None						):
		if not isinstance(_lowercase			,    torch.Tensor						):
			raise ValueError(F'''`image` has to be of type `torch.Tensor` but is {type(_lowercase						)}'''						)

		__UpperCAmelCase      		= image.to(device=_lowercase			,    dtype=_lowercase						)

		if isinstance(_lowercase			,    _lowercase						):
			__UpperCAmelCase      		= [
			    self.vae.encode(image[i : i + 1]						).latent_dist.sample(generator[i]						) for i in range(_lowercase						)
			]
			__UpperCAmelCase      		= torch.cat(_lowercase			,    dim=0						)
		else:
			__UpperCAmelCase      		= self.vae.encode(_lowercase						).latent_dist.sample(_lowercase						)

		# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
		__UpperCAmelCase      		= 0.18_215 * init_latents
		__UpperCAmelCase      		= init_latents.repeat_interleave(_lowercase			,    dim=0						)

		__UpperCAmelCase      		= randn_tensor(init_latents.shape			,    generator=_lowercase			,    device=_lowercase			,    dtype=_lowercase						)

		# get latents
		__UpperCAmelCase      		= self.scheduler.add_noise(_lowercase			,    _lowercase			,    _lowercase						)
		__UpperCAmelCase      		= init_latents

		return latents



	def        a  (  self     :       List[str]			,    _lowercase     :       Any						):
		__UpperCAmelCase      		= self.coca_transform(_lowercase						).unsqueeze(0						)
		with torch.no_grad(), torch.cuda.amp.autocast():
			__UpperCAmelCase      		= self.coca_model.generate(transformed_image.to(device=self.device			,    dtype=self.coca_model.dtype						)						)
		__UpperCAmelCase      		= self.coca_tokenizer.decode(generated[0].cpu().numpy()						)
		return generated.split('''<end_of_text>'''						)[0].replace('''<start_of_text>'''			,    ''''''						).rstrip(''' .,'''						)



	def        a  (  self     :       int			,    _lowercase     :       List[str]			,    _lowercase     :       Optional[int]						):
		__UpperCAmelCase      		= self.feature_extractor.preprocess(_lowercase						)
		__UpperCAmelCase      		= torch.from_numpy(clip_image_input['''pixel_values'''][0]						).unsqueeze(0						).to(self.device						).half()
		__UpperCAmelCase      		= self.clip_model.get_image_features(_lowercase						)
		__UpperCAmelCase      		= image_embeddings_clip / image_embeddings_clip.norm(p=2			,    dim=-1			,    keepdim=_lowercase						)
		__UpperCAmelCase      		= image_embeddings_clip.repeat_interleave(_lowercase			,    dim=0						)
		return image_embeddings_clip



	@torch.enable_grad()
	def        a  (  self     :       Tuple			,    _lowercase     :       Any			,    _lowercase     :       Optional[Any]			,    _lowercase     :       Optional[Any]			,    _lowercase     :       Tuple			,    _lowercase     :       Optional[Any]			,    _lowercase     :       str			,    _lowercase     :       List[str]			,    ):
		__UpperCAmelCase      		= latents.detach().requires_grad_()

		__UpperCAmelCase      		= self.scheduler.scale_model_input(_lowercase			,    _lowercase						)

		# predict the noise residual
		__UpperCAmelCase      		= self.unet(_lowercase			,    _lowercase			,    encoder_hidden_states=_lowercase						).sample

		if isinstance(self.scheduler			,    (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)						):
			__UpperCAmelCase      		= self.scheduler.alphas_cumprod[timestep]
			__UpperCAmelCase      		= 1 - alpha_prod_t
			# compute predicted original sample from predicted noise also called
			# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
			__UpperCAmelCase      		= (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5

			__UpperCAmelCase      		= torch.sqrt(_lowercase						)
			__UpperCAmelCase      		= pred_original_sample * (fac) + latents * (1 - fac)
		elif isinstance(self.scheduler			,    _lowercase						):
			__UpperCAmelCase      		= self.scheduler.sigmas[index]
			__UpperCAmelCase      		= latents - sigma * noise_pred
		else:
			raise ValueError(F'''scheduler type {type(self.scheduler						)} not supported'''						)

		# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
		__UpperCAmelCase      		= 1 / 0.18_215 * sample
		__UpperCAmelCase      		= self.vae.decode(_lowercase						).sample
		__UpperCAmelCase      		= (image / 2 + 0.5).clamp(0			,    1						)

		__UpperCAmelCase      		= transforms.Resize(self.feature_extractor_size						)(_lowercase						)
		__UpperCAmelCase      		= self.normalize(_lowercase						).to(latents.dtype						)

		__UpperCAmelCase      		= self.clip_model.get_image_features(_lowercase						)
		__UpperCAmelCase      		= image_embeddings_clip / image_embeddings_clip.norm(p=2			,    dim=-1			,    keepdim=_lowercase						)

		__UpperCAmelCase      		= spherical_dist_loss(_lowercase			,    _lowercase						).mean() * clip_guidance_scale

		__UpperCAmelCase      		= -torch.autograd.grad(_lowercase			,    _lowercase						)[0]

		if isinstance(self.scheduler			,    _lowercase						):
			__UpperCAmelCase      		= latents.detach() + grads * (sigma**2)
			__UpperCAmelCase      		= noise_pred_original
		else:
			__UpperCAmelCase      		= noise_pred_original - torch.sqrt(_lowercase						) * grads
		return noise_pred, latents



	@torch.no_grad()
	def __call__(  self     :       List[Any]			,    _lowercase     :       Union[torch.FloatTensor, PIL.Image.Image]			,    _lowercase     :       Union[torch.FloatTensor, PIL.Image.Image]			,    _lowercase     :       Optional[str] = None			,    _lowercase     :       Optional[str] = None			,    _lowercase     :       Optional[int] = 5_12			,    _lowercase     :       Optional[int] = 5_12			,    _lowercase     :       float = 0.6			,    _lowercase     :       Optional[int] = 50			,    _lowercase     :       Optional[float] = 7.5			,    _lowercase     :       Optional[int] = 1			,    _lowercase     :       float = 0.0			,    _lowercase     :       Optional[float] = 1_00			,    _lowercase     :       Optional[torch.Generator] = None			,    _lowercase     :       Optional[str] = "pil"			,    _lowercase     :       bool = True			,    _lowercase     :       float = 0.8			,    _lowercase     :       float = 0.1			,    _lowercase     :       float = 0.1			,    ):
		if isinstance(_lowercase			,    _lowercase						) and len(_lowercase						) != batch_size:
			raise ValueError(F'''You have passed {batch_size} batch_size, but only {len(_lowercase						)} generators.'''						)

		if height % 8 != 0 or width % 8 != 0:
			raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.'''						)

		if isinstance(_lowercase			,    torch.Generator						) and batch_size > 1:
			__UpperCAmelCase      		= [generator] + [None] * (batch_size - 1)

		__UpperCAmelCase      		= [
		    ('''model''', self.coca_model is None),
		    ('''tokenizer''', self.coca_tokenizer is None),
		    ('''transform''', self.coca_transform is None),
		]
		__UpperCAmelCase      		= [x[0] for x in coca_is_none if x[1]]
		__UpperCAmelCase      		= ''', '''.join(_lowercase						)
		# generate prompts with coca model if prompt is None
		if content_prompt is None:
			if len(_lowercase						):
				raise ValueError(
				    F'''Content prompt is None and CoCa [{coca_is_none_str}] is None.'''
				    F'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.'''						)
			__UpperCAmelCase      		= self.get_image_description(_lowercase						)
		if style_prompt is None:
			if len(_lowercase						):
				raise ValueError(
				    F'''Style prompt is None and CoCa [{coca_is_none_str}] is None.'''
				    F''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.'''						)
			__UpperCAmelCase      		= self.get_image_description(_lowercase						)

		# get prompt text embeddings for content and style
		__UpperCAmelCase      		= self.tokenizer(
		    _lowercase			,    padding='''max_length'''			,    max_length=self.tokenizer.model_max_length			,    truncation=_lowercase			,    return_tensors='''pt'''			,    )
		__UpperCAmelCase      		= self.text_encoder(content_text_input.input_ids.to(self.device						)						)[0]

		__UpperCAmelCase      		= self.tokenizer(
		    _lowercase			,    padding='''max_length'''			,    max_length=self.tokenizer.model_max_length			,    truncation=_lowercase			,    return_tensors='''pt'''			,    )
		__UpperCAmelCase      		= self.text_encoder(style_text_input.input_ids.to(self.device						)						)[0]

		__UpperCAmelCase      		= slerp(_lowercase			,    _lowercase			,    _lowercase						)

		# duplicate text embeddings for each generation per prompt
		__UpperCAmelCase      		= text_embeddings.repeat_interleave(_lowercase			,    dim=0						)

		# set timesteps
		__UpperCAmelCase      		= '''offset''' in set(inspect.signature(self.scheduler.set_timesteps						).parameters.keys()						)
		__UpperCAmelCase      		= {}
		if accepts_offset:
			__UpperCAmelCase      		= 1

		self.scheduler.set_timesteps(_lowercase			,    **_lowercase						)
		# Some schedulers like PNDM have timesteps as arrays
		# It's more optimized to move all timesteps to correct device beforehand
		self.scheduler.timesteps.to(self.device						)

		__UpperCAmelCase		,							__UpperCAmelCase      		= self.get_timesteps(_lowercase			,    _lowercase			,    self.device						)
		__UpperCAmelCase      		= timesteps[:1].repeat(_lowercase						)

		# Preprocess image
		__UpperCAmelCase      		= preprocess(_lowercase			,    _lowercase			,    _lowercase						)
		__UpperCAmelCase      		= self.prepare_latents(
		    _lowercase			,    _lowercase			,    _lowercase			,    text_embeddings.dtype			,    self.device			,    _lowercase						)

		__UpperCAmelCase      		= preprocess(_lowercase			,    _lowercase			,    _lowercase						)
		__UpperCAmelCase      		= self.prepare_latents(
		    _lowercase			,    _lowercase			,    _lowercase			,    text_embeddings.dtype			,    self.device			,    _lowercase						)

		__UpperCAmelCase      		= slerp(_lowercase			,    _lowercase			,    _lowercase						)

		if clip_guidance_scale > 0:
			__UpperCAmelCase      		= self.get_clip_image_embeddings(_lowercase			,    _lowercase						)
			__UpperCAmelCase      		= self.get_clip_image_embeddings(_lowercase			,    _lowercase						)
			__UpperCAmelCase      		= slerp(
			    _lowercase			,    _lowercase			,    _lowercase						)

		# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
		# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
		# corresponds to doing no classifier free guidance.
		__UpperCAmelCase      		= guidance_scale > 1.0
		# get unconditional embeddings for classifier free guidance
		if do_classifier_free_guidance:
			__UpperCAmelCase      		= content_text_input.input_ids.shape[-1]
			__UpperCAmelCase      		= self.tokenizer(['''''']			,    padding='''max_length'''			,    max_length=_lowercase			,    return_tensors='''pt'''						)
			__UpperCAmelCase      		= self.text_encoder(uncond_input.input_ids.to(self.device						)						)[0]
			# duplicate unconditional embeddings for each generation per prompt
			__UpperCAmelCase      		= uncond_embeddings.repeat_interleave(_lowercase			,    dim=0						)

			# For classifier free guidance, we need to do two forward passes.
			# Here we concatenate the unconditional and text embeddings into a single batch
			# to avoid doing two forward passes
			__UpperCAmelCase      		= torch.cat([uncond_embeddings, text_embeddings]						)

		# get the initial random noise unless the user supplied it

		# Unlike in other pipelines, latents need to be generated in the target device
		# for 1-to-1 results reproducibility with the CompVis implementation.
		# However this currently doesn't work in `mps`.
		__UpperCAmelCase      		= (batch_size, self.unet.config.in_channels, height // 8, width // 8)
		__UpperCAmelCase      		= text_embeddings.dtype
		if latents is None:
			if self.device.type == "mps":
				# randn does not work reproducibly on mps
				__UpperCAmelCase      		= torch.randn(_lowercase			,    generator=_lowercase			,    device='''cpu'''			,    dtype=_lowercase						).to(
				    self.device						)
			else:
				__UpperCAmelCase      		= torch.randn(_lowercase			,    generator=_lowercase			,    device=self.device			,    dtype=_lowercase						)
		else:
			if latents.shape != latents_shape:
				raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}'''						)
			__UpperCAmelCase      		= latents.to(self.device						)

		# scale the initial noise by the standard deviation required by the scheduler
		__UpperCAmelCase      		= latents * self.scheduler.init_noise_sigma

		# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
		# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
		# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
		# and should be between [0, 1]
		__UpperCAmelCase      		= '''eta''' in set(inspect.signature(self.scheduler.step						).parameters.keys()						)
		__UpperCAmelCase      		= {}
		if accepts_eta:
			__UpperCAmelCase      		= eta

		# check if the scheduler accepts generator
		__UpperCAmelCase      		= '''generator''' in set(inspect.signature(self.scheduler.step						).parameters.keys()						)
		if accepts_generator:
			__UpperCAmelCase      		= generator

		with self.progress_bar(total=_lowercase						):
			for i, t in enumerate(_lowercase						):
				# expand the latents if we are doing classifier free guidance
				__UpperCAmelCase      		= torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
				__UpperCAmelCase      		= self.scheduler.scale_model_input(_lowercase			,    _lowercase						)

				# predict the noise residual
				__UpperCAmelCase      		= self.unet(_lowercase			,    _lowercase			,    encoder_hidden_states=_lowercase						).sample

				# perform classifier free guidance
				if do_classifier_free_guidance:
					__UpperCAmelCase		,							__UpperCAmelCase      		= noise_pred.chunk(2						)
					__UpperCAmelCase      		= noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

				# perform clip guidance
				if clip_guidance_scale > 0:
					__UpperCAmelCase      		= (
					    text_embeddings.chunk(2						)[1] if do_classifier_free_guidance else text_embeddings
					)
					__UpperCAmelCase		,							__UpperCAmelCase      		= self.cond_fn(
					    _lowercase			,    _lowercase			,    _lowercase			,    _lowercase			,    _lowercase			,    _lowercase			,    _lowercase			,    )

				# compute the previous noisy sample x_t -> x_t-1
				__UpperCAmelCase      		= self.scheduler.step(_lowercase			,    _lowercase			,    _lowercase			,    **_lowercase						).prev_sample

        # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
		__UpperCAmelCase      		= 1 / 0.18_215 * latents
		__UpperCAmelCase      		= self.vae.decode(_lowercase						).sample

		__UpperCAmelCase      		= (image / 2 + 0.5).clamp(0			,    1						)
		__UpperCAmelCase      		= image.cpu().permute(0			,    2			,    3			,    1						).numpy()

		if output_type == "pil":
			__UpperCAmelCase      		= self.numpy_to_pil(_lowercase						)

		if not return_dict:
			return (image, None)

		return StableDiffusionPipelineOutput(images=_lowercase			,    nsfw_content_detected=_lowercase						)




"""simple docstring"""



from manim import *







class _lowerCAmelCase							( snake_case_      ):







   def 					lowerCamelCase						(      self		)      ->						Any:

       '''simple docstring'''




       snake_case       : List[str]    =       Rectangle(height=0.5		,      width=0.5		)
       snake_case       : Dict    =       Rectangle(height=0.46		,      width=0.46		).set_stroke(width=0		)

       snake_case       : Tuple    =       [mem.copy() for i in range(6		)]
       snake_case       : Any    =       [mem.copy() for i in range(6		)]
       snake_case       : Tuple    =       VGroup(*UpperCamelCase__		).arrange(UpperCamelCase__		,      buff=0		)
       snake_case       : Optional[Any]    =       VGroup(*UpperCamelCase__		).arrange(UpperCamelCase__		,      buff=0		)
       snake_case       : Optional[Any]    =       VGroup(UpperCamelCase__		,      UpperCamelCase__		).arrange(UpperCamelCase__		,      buff=0		)
       snake_case       : Optional[Any]    =       Text("CPU"		,      font_size=24		)
       snake_case       : Optional[int]    =       Group(UpperCamelCase__		,      UpperCamelCase__		).arrange(UpperCamelCase__		,      buff=0.5		,      aligned_edge=UpperCamelCase__		)
       cpu.move_to([-2.5, -0.5, 0]		)
       self.add(UpperCamelCase__		)

       snake_case       : Optional[Any]    =       [mem.copy() for i in range(1		)]
       snake_case       : List[str]    =       VGroup(*UpperCamelCase__		).arrange(UpperCamelCase__		,      buff=0		)
       snake_case       : Optional[int]    =       Text("GPU"		,      font_size=24		)
       snake_case       : Tuple    =       Group(UpperCamelCase__		,      UpperCamelCase__		).arrange(UpperCamelCase__		,      buff=0.5		,      aligned_edge=UpperCamelCase__		)
       gpu.align_to(UpperCamelCase__		,      UpperCamelCase__		)
       gpu.set_x(gpu.get_x() - 1		)

       self.add(UpperCamelCase__		)

       snake_case       : Any    =       [mem.copy() for i in range(6		)]
       snake_case       : Any    =       VGroup(*UpperCamelCase__		).arrange(UpperCamelCase__		,      buff=0		)

       snake_case       : Dict    =       Text("Model"		,      font_size=24		)
       snake_case       : Optional[Any]    =       Group(UpperCamelCase__		,      UpperCamelCase__		).arrange(UpperCamelCase__		,      buff=0.5		,      aligned_edge=UpperCamelCase__		)
       model.move_to([3, -1.0, 0]		)

       self.play(
           Create(UpperCamelCase__		,      run_time=1		)		,      Create(UpperCamelCase__		,      run_time=1		)		,      Create(UpperCamelCase__		,      run_time=1		)		,      )

       snake_case       : Optional[Any]    =       MarkupText(
           F'First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.'		,      font_size=24		,      )

       snake_case       : Any    =       Square(side_length=2.2		)
       key.move_to([-5, 2, 0]		)

       snake_case       : Any    =       MarkupText(
           F'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model'		,      font_size=18		,      )

       key_text.move_to([-5, 2.4, 0]		)

       step_a.move_to([2, 2, 0]		)
       self.play(Write(UpperCamelCase__		,      run_time=2.5		)		,      Write(UpperCamelCase__		)		,      Write(UpperCamelCase__		)		)

       self.add(UpperCamelCase__		)

       snake_case       : Optional[Any]    =       []
       snake_case       : Dict    =       []
       snake_case       : Union[str, Any]    =       []
       for i, rect in enumerate(UpperCamelCase__		):
           snake_case       : Any    =       Rectangle(height=0.46		,      width=0.46		).set_stroke(width=0.0		).set_fill(UpperCamelCase__		,      opacity=0.7		)
           cpu_target.move_to(UpperCamelCase__		)
           cpu_target.generate_target()
           snake_case       : Optional[int]    =       0.46 / 4
           snake_case       : Any    =       0.46 / 3

           if i == 0:
               cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT		)		,      buff=0.02		,      direction=UpperCamelCase__		)
               cpu_target.target.set_x(cpu_target.target.get_x() + 0.1		)
           elif i == 3:
               cpu_target.target.next_to(cpu_targs[0].target		,      direction=UpperCamelCase__		,      buff=0.0		)
           else:
               cpu_target.target.next_to(cpu_targs[i - 1].target		,      direction=UpperCamelCase__		,      buff=0.0		)
           cpu_targs.append(UpperCamelCase__		)

           first_animations.append(rect.animate(run_time=0.5		).set_stroke(UpperCamelCase__		)		)
           second_animations.append(MoveToTarget(UpperCamelCase__		,      run_time=1.5		)		)

       self.play(*UpperCamelCase__		)
       self.play(*UpperCamelCase__		)

       self.wait()





