





"""simple docstring"""


def 							a__     (					_UpperCAmelCase = "mytext.txt"		,       _UpperCAmelCase = False		)      ->					None:

 '''simple docstring'''






 import socket

 snake_case__      							=			1_2_3_1_2  # Reserve a port for your service.
 snake_case__      							=			socket.socket()  # Create a socket object
 snake_case__      							=			socket.gethostname()  # Get local machine name
 sock.bind((host, port)		)  # Bind to the port
 sock.listen(5		)  # Now wait for client connection.

 print("Server listening...."		)

 while True:
  snake_case__							,				snake_case__      							=			sock.accept()  # Establish connection with client.
  print(f"Got connection from {addr}"		)
  snake_case__      							=			conn.recv(1_0_2_4		)
  print(f"Server received: {data = }"		)

  with open(_UpperCAmelCase		,       "rb"		) as in_file:
   snake_case__      							=			in_file.read(1_0_2_4		)
   while data:
    conn.send(_UpperCAmelCase		)
    print(f"Sent {data!r}"		)
    snake_case__      							=			in_file.read(1_0_2_4		)

  print("Done sending"		)
  conn.close()
  if testing:  # Allow the test to complete
   break

 sock.shutdown(1		)
 sock.close()


if __name__ == "__main__":
   send_file()








"""simple docstring"""


import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


a__   :       Optional[Any]   						=			logging.get_logger(__name__)  # pylint: disable=invalid-name

a__   :       Tuple   						=			"""
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 15.0
        >>> prompt = \"a shark\"

        >>> images = pipe(
        ...     prompt,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")
        ```
"""



@dataclass
class        lowercase_			(       __lowerCAmelCase							):
       snake_case__			:							Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]



class        lowercase_			(       __lowerCAmelCase							):

       def __init__(     self				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   ):






        '''simple docstring'''

        super().__init__()

        self.register_modules(
            prior=__SCREAMING_SNAKE_CASE				,   text_encoder=__SCREAMING_SNAKE_CASE				,   tokenizer=__SCREAMING_SNAKE_CASE				,   scheduler=__SCREAMING_SNAKE_CASE				,   renderer=__SCREAMING_SNAKE_CASE				,   )

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):






        '''simple docstring'''

        if latents is None:
         snake_case__      							=			randn_tensor(__SCREAMING_SNAKE_CASE				,   generator=__SCREAMING_SNAKE_CASE				,   device=__SCREAMING_SNAKE_CASE				,   dtype=__SCREAMING_SNAKE_CASE       )
        else:
         if latents.shape != shape:
          raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"       )
         snake_case__      							=			latents.to(__SCREAMING_SNAKE_CASE       )

        snake_case__      							=			latents * scheduler.init_noise_sigma
        return latents

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE=0       ):






        '''simple docstring'''

        if is_accelerate_available():
         from accelerate import cpu_offload
        else:
         raise ImportError("Please install accelerate via `pip install accelerate`"       )

        snake_case__      							=			torch.device(F"cuda:{gpu_id}"       )

        snake_case__      							=			[self.text_encoder, self.prior]
        for cpu_offloaded_model in models:
         if cpu_offloaded_model is not None:
          cpu_offload(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       )

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE=0       ):






        '''simple docstring'''

        if is_accelerate_available() and is_accelerate_version(">="				,   "0.17.0.dev0"       ):
         from accelerate import cpu_offload_with_hook
        else:
         raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."       )

        snake_case__      							=			torch.device(F"cuda:{gpu_id}"       )

        if self.device.type != "cpu":
         self.to("cpu"				,   silence_dtype_warnings=__SCREAMING_SNAKE_CASE       )
         torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

        snake_case__      							=			None
        for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
         snake_case__							,				snake_case__      							=			cpu_offload_with_hook(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   prev_module_hook=__SCREAMING_SNAKE_CASE       )

        if self.safety_checker is not None:
         snake_case__							,				snake_case__      							=			cpu_offload_with_hook(self.safety_checker				,   __SCREAMING_SNAKE_CASE				,   prev_module_hook=__SCREAMING_SNAKE_CASE       )

        # We'll offload the last model manually.
        snake_case__      							=			hook

       @property
       def 						_SCREAMING_SNAKE_CASE(     self       ):






        '''simple docstring'''

        if self.device != torch.device("meta"       ) or not hasattr(self.text_encoder				,   "_hf_hook"       ):
         return self.device
        for module in self.text_encoder.modules():
         if (
             hasattr(__SCREAMING_SNAKE_CASE				,   "_hf_hook"       )
             and hasattr(module._hf_hook				,   "execution_device"       )
             and module._hf_hook.execution_device is not None
         ):
          return torch.device(module._hf_hook.execution_device       )
        return self.device

       def 						_SCREAMING_SNAKE_CASE(     self				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   ):






        '''simple docstring'''

        len(__SCREAMING_SNAKE_CASE       ) if isinstance(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ) else 1

        # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
        snake_case__      							=			0
        # get prompt text embeddings
        snake_case__      							=			self.tokenizer(
            __SCREAMING_SNAKE_CASE				,   padding="max_length"				,   max_length=self.tokenizer.model_max_length				,   truncation=__SCREAMING_SNAKE_CASE				,   return_tensors="pt"				,   )
        snake_case__      							=			text_inputs.input_ids
        snake_case__      							=			self.tokenizer(__SCREAMING_SNAKE_CASE				,   padding="longest"				,   return_tensors="pt"       ).input_ids

        if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):
         snake_case__      							=			self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]       )
         logger.warning(
             "The following part of your input was truncated because CLIP can only handle sequences up to"
             F" {self.tokenizer.model_max_length} tokens: {removed_text}"       )

        snake_case__      							=			self.text_encoder(text_input_ids.to(__SCREAMING_SNAKE_CASE       )       )
        snake_case__      							=			text_encoder_output.text_embeds

        snake_case__      							=			prompt_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE				,   dim=0       )
        # in Shap-E it normalize the prompt_embeds and then later rescale it
        snake_case__      							=			prompt_embeds / torch.linalg.norm(__SCREAMING_SNAKE_CASE				,   dim=-1				,   keepdim=__SCREAMING_SNAKE_CASE       )

        if do_classifier_free_guidance:
         snake_case__      							=			torch.zeros_like(__SCREAMING_SNAKE_CASE       )

         # 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
         snake_case__      							=			torch.cat([negative_prompt_embeds, prompt_embeds]       )

        # Rescale the features to have unit variance
        snake_case__      							=			math.sqrt(prompt_embeds.shape[1]       ) * prompt_embeds

        return prompt_embeds

       @torch.no_grad()
       @replace_example_docstring(__SCREAMING_SNAKE_CASE       )
       def __call__(     self				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE = 1				,   __SCREAMING_SNAKE_CASE = 25				,   __SCREAMING_SNAKE_CASE = None				,   __SCREAMING_SNAKE_CASE = None				,   __SCREAMING_SNAKE_CASE = 4.0				,   __SCREAMING_SNAKE_CASE = 64				,   __SCREAMING_SNAKE_CASE = "pil"				,   __SCREAMING_SNAKE_CASE = True				,   ):






        '''simple docstring'''

        if isinstance(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):
         snake_case__      							=			1
        elif isinstance(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       ):
         snake_case__      							=			len(__SCREAMING_SNAKE_CASE       )
        else:
         raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(__SCREAMING_SNAKE_CASE       )}"       )

        snake_case__      							=			self._execution_device

        snake_case__      							=			batch_size * num_images_per_prompt

        snake_case__      							=			guidance_scale > 1.0
        snake_case__      							=			self._encode_prompt(__SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       )

        # prior

        self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE				,   device=__SCREAMING_SNAKE_CASE       )
        snake_case__      							=			self.scheduler.timesteps

        snake_case__      							=			self.prior.config.num_embeddings
        snake_case__      							=			self.prior.config.embedding_dim

        snake_case__      							=			self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim)				,   prompt_embeds.dtype				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE				,   self.scheduler				,   )

        # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
        snake_case__      							=			latents.reshape(latents.shape[0]				,   __SCREAMING_SNAKE_CASE				,   __SCREAMING_SNAKE_CASE       )

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

         snake_case__      							=			self.prior(
             __SCREAMING_SNAKE_CASE				,   timestep=__SCREAMING_SNAKE_CASE				,   proj_embedding=__SCREAMING_SNAKE_CASE				,   ).predicted_image_embedding

         # remove the variance
         snake_case__							,				snake_case__      							=			noise_pred.split(
             scaled_model_input.shape[2]				,   dim=2       )  # batch_size, num_embeddings, embedding_dim

         if do_classifier_free_guidance is not None:
          snake_case__							,				snake_case__      							=			noise_pred.chunk(2       )
          snake_case__      							=			noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

         snake_case__      							=			self.scheduler.step(
             __SCREAMING_SNAKE_CASE				,   timestep=__SCREAMING_SNAKE_CASE				,   sample=__SCREAMING_SNAKE_CASE				,   ).prev_sample

        if output_type == "latent":
         return ShapEPipelineOutput(images=__SCREAMING_SNAKE_CASE       )

        snake_case__      							=			[]
        for i, latent in enumerate(__SCREAMING_SNAKE_CASE       ):
         snake_case__      							=			self.renderer.decode(
             latent[None, :]				,   __SCREAMING_SNAKE_CASE				,   size=__SCREAMING_SNAKE_CASE				,   ray_batch_size=4096				,   n_coarse_samples=64				,   n_fine_samples=128				,   )
         images.append(__SCREAMING_SNAKE_CASE       )

        snake_case__      							=			torch.stack(__SCREAMING_SNAKE_CASE       )

        if output_type not in ["np", "pil"]:
         raise ValueError(F"Only the output types `pil` and `np` are supported not output_type={output_type}"       )

        snake_case__      							=			images.cpu().numpy()

        if output_type == "pil":
         snake_case__      							=			[self.numpy_to_pil(__SCREAMING_SNAKE_CASE       ) for image in images]

        # Offload last model to CPU
        if hasattr(self				,   "final_offload_hook"       ) and self.final_offload_hook is not None:
         self.final_offload_hook.offload()

        if not return_dict:
         return (images,)

        return ShapEPipelineOutput(images=__SCREAMING_SNAKE_CASE       )

