





'''simple docstring'''


from typing import Union

import torch
from PIL import Image
from torchvision import transforms as tfms
from tqdm.auto import tqdm
from transformers import CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)


class 		UpperCamelCase__     (       a							):
      '''simple docstring'''






      def __init__(     self     , SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE     , )				->  Dict:
        super().__init__()

        self.register_modules(vae=SCREAMING_SNAKE_CASE     , text_encoder=SCREAMING_SNAKE_CASE     , tokenizer=SCREAMING_SNAKE_CASE     , unet=SCREAMING_SNAKE_CASE     , scheduler=SCREAMING_SNAKE_CASE )




      def 	snake_case  (     self     , SCREAMING_SNAKE_CASE )				->  int:
        with torch.no_grad():
          __lowerCAmelCase		:    Optional[Any]			     =  self.vae.encode(tfms.ToTensor()(SCREAMING_SNAKE_CASE ).unsqueeze(0 ).to(self.device ) * 2 - 1 )
          __lowerCAmelCase		:    List[str]			     =  0.1_8_2_1_5 * latent.latent_dist.sample()
        return latent




      def 	snake_case  (     self     , SCREAMING_SNAKE_CASE )				->  Optional[int]:
        __lowerCAmelCase		:    Union[str, Any]			     =  (1 / 0.1_8_2_1_5) * latent
        with torch.no_grad():
          __lowerCAmelCase		:    Tuple			     =  self.vae.decode(SCREAMING_SNAKE_CASE ).sample
        __lowerCAmelCase		:    Tuple			     =  (img / 2 + 0.5).clamp(0     , 1 )
        __lowerCAmelCase		:    List[str]			     =  img.detach().cpu().permute(0     , 2     , 3     , 1 ).numpy()
        __lowerCAmelCase		:    Dict			     =  (img * 2_55).round().astype('uint8' )
        return Image.fromarray(img[0] )




      def 	snake_case  (     self     , SCREAMING_SNAKE_CASE )				->  str:
        __lowerCAmelCase		:    Union[str, Any]			     =  self.tokenizer(
            SCREAMING_SNAKE_CASE     , padding='max_length'     , max_length=self.tokenizer.model_max_length     , truncation=SCREAMING_SNAKE_CASE     , return_tensors='pt'     , )

        __lowerCAmelCase		:    Dict			     =  self.text_encoder(text_input.input_ids.to(self.device ) )[0]

        __lowerCAmelCase		:    List[str]			     =  self.tokenizer(
            ''     , padding='max_length'     , max_length=self.tokenizer.model_max_length     , truncation=SCREAMING_SNAKE_CASE     , return_tensors='pt'     , )

        __lowerCAmelCase		:    List[str]			     =  self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]

        return torch.cat([uncond_embedding, text_embedding] )







      def __call__(     self     , SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE = 0.3     , SCREAMING_SNAKE_CASE = 0.6     , SCREAMING_SNAKE_CASE = 0.5     , SCREAMING_SNAKE_CASE = 42     , SCREAMING_SNAKE_CASE = 50     , SCREAMING_SNAKE_CASE = 7.5     , )				->  Image.Image:
        __lowerCAmelCase		:    Tuple			     =  steps - int(kmin * steps )
        __lowerCAmelCase		:    Union[str, Any]			     =  steps - int(kmax * steps )

        __lowerCAmelCase		:    Tuple			     =  self.prep_text(SCREAMING_SNAKE_CASE )

        self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE )

        __lowerCAmelCase     ,					__lowerCAmelCase		:    Union[str, Any]			     =  img.size
        __lowerCAmelCase		:    List[Any]			     =  self.encode(SCREAMING_SNAKE_CASE )

        torch.manual_seed(SCREAMING_SNAKE_CASE )
        __lowerCAmelCase		:    List[Any]			     =  torch.randn(
            (1, self.unet.config.in_channels, height // 8, width // 8)     , ).to(self.device )

        __lowerCAmelCase		:    List[Any]			     =  self.scheduler.add_noise(
            SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE     , timesteps=self.scheduler.timesteps[tmax]     , )

        __lowerCAmelCase		:    Optional[Any]			     =  torch.cat([latents] * 2 )

        __lowerCAmelCase		:    List[Any]			     =  self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE     , self.scheduler.timesteps[tmax] )

        with torch.no_grad():
          __lowerCAmelCase		:    int			     =  self.unet(
              SCREAMING_SNAKE_CASE     , self.scheduler.timesteps[tmax]     , encoder_hidden_states=SCREAMING_SNAKE_CASE     , ).sample

        __lowerCAmelCase     ,					__lowerCAmelCase		:    Any			     =  pred.chunk(2 )
        __lowerCAmelCase		:    Any			     =  pred_uncond + guidance_scale * (pred_text - pred_uncond)

        __lowerCAmelCase		:    List[Any]			     =  self.scheduler.step(SCREAMING_SNAKE_CASE     , self.scheduler.timesteps[tmax]     , SCREAMING_SNAKE_CASE ).prev_sample

        for i, t in enumerate(tqdm(self.scheduler.timesteps ) ):
          if i > tmax:
            if i < tmin:  # layout generation phase
              __lowerCAmelCase		:    Optional[int]			     =  self.scheduler.add_noise(
                  SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE     , timesteps=SCREAMING_SNAKE_CASE     , )

              __lowerCAmelCase		:    Any			     =  (mix_factor * latents) + (
                  1 - mix_factor
              ) * orig_latents  # interpolating between layout noise and conditionally generated noise to preserve layout sematics
              __lowerCAmelCase		:    Dict			     =  torch.cat([input] * 2 )

            else:  # content generation phase
              __lowerCAmelCase		:    Optional[int]			     =  torch.cat([latents] * 2 )

            __lowerCAmelCase		:    Any			     =  self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE )

            with torch.no_grad():
              __lowerCAmelCase		:    List[Any]			     =  self.unet(
                  SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE     , encoder_hidden_states=SCREAMING_SNAKE_CASE     , ).sample

            __lowerCAmelCase     ,					__lowerCAmelCase		:    Dict			     =  pred.chunk(2 )
            __lowerCAmelCase		:    Union[str, Any]			     =  pred_uncond + guidance_scale * (pred_text - pred_uncond)

            __lowerCAmelCase		:    int			     =  self.scheduler.step(SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE     , SCREAMING_SNAKE_CASE ).prev_sample

        return self.decode(SCREAMING_SNAKE_CASE )












'''simple docstring'''


from __future__ import annotations

from collections.abc import Callable




def       A							(      _UpperCAmelCase   :				Callable[[int | float], int | float]						,_UpperCAmelCase   :				int | float						,_UpperCAmelCase   :				int | float						,_UpperCAmelCase   :				int = 1_0_0						,)  ->				float:


  '''simple docstring'''




  __lowerCAmelCase		:    Dict			     =  x_start
  __lowerCAmelCase		:    Tuple			     =  fnc(_UpperCAmelCase					)
  __lowerCAmelCase		:    Optional[int]			     =  0.0

  for _ in range(_UpperCAmelCase					):
    # Approximates small segments of curve as linear and solve
    # for trapezoidal area
    __lowerCAmelCase		:    Optional[int]			     =  (x_end - x_start) / steps + xa
    __lowerCAmelCase		:    Optional[Any]			     =  fnc(_UpperCAmelCase					)
    area += abs(fxa + fxa					) * (xa - xa) / 2

    # Increment step
    __lowerCAmelCase		:    Optional[Any]			     =  xa
    __lowerCAmelCase		:    List[Any]			     =  fxa
  return area


if __name__ == "__main__":




    def       A							(      _UpperCAmelCase   :				List[Any]					)  ->				List[Any]:


      '''simple docstring'''




      return x**3

    print("f(x) = x^3")
    print("The area between the curve, x = -10, x = 10 and the x axis is:")
    A_				     =							10
    while i <= 10_00_00:
        A_				     =							trapezoidal_area(f, -5, 5, i)
        print(F'''with {i} steps: {area}''')
        i *= 10





