






import numpy as np
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


SCREAMING_SNAKE_CASE_				      =							logging.get_logger(__name__)






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		):
 __a    :	Dict									=						nn.functional.normalize(SCREAMING_SNAKE_CASE__		)
 __a    :	Optional[Any]									=						nn.functional.normalize(SCREAMING_SNAKE_CASE__		)
 return torch.mm(SCREAMING_SNAKE_CASE__       ,		normalized_text_embeds.t()		)




class 							lowerCAmelCase					(							lowerCamelCase__   ):







   """simple docstring"""







   _A						=   CLIPConfig

   _A						=   ['CLIPEncoderLayer']



   def __init__( self   ,   _A			)    ->   str:
    super().__init__(_A			)

    __a    :	List[Any]									=						CLIPVisionModel(config.vision_config			)
    __a    :	Dict									=						nn.Linear(config.vision_config.hidden_size   ,   config.projection_dim   ,   bias=_A			)

    __a    :	Optional[int]									=						nn.Parameter(torch.ones(17   ,   config.projection_dim			)   ,   requires_grad=_A			)
    __a    :	Any									=						nn.Parameter(torch.ones(3   ,   config.projection_dim			)   ,   requires_grad=_A			)

    __a    :	Optional[int]									=						nn.Parameter(torch.ones(17			)   ,   requires_grad=_A			)
    __a    :	List[Any]									=						nn.Parameter(torch.ones(3			)   ,   requires_grad=_A			)



   @torch.no_grad()
   def    __magic_name__    ( self   ,   _A   ,   _A			)    ->   Optional[Any]:
    __a    :	Optional[Any]									=						self.vision_model(_A			)[1]  # pooled_output
    __a    :	Any									=						self.visual_projection(_A			)

    # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
    __a    :	Union[str, Any]									=						cosine_distance(_A   ,   self.special_care_embeds			).cpu().float().numpy()
    __a    :	str									=						cosine_distance(_A   ,   self.concept_embeds			).cpu().float().numpy()

    __a    :	Tuple									=						[]
    __a    :	str									=						image_embeds.shape[0]
    for i in range(_A			):
     __a    :	Union[str, Any]									=						{'special_scores': {}, 'special_care': [], 'concept_scores': {}, 'bad_concepts': []}

     # increase this value to create a stronger `nfsw` filter
     # at the cost of increasing the possibility of filtering benign images
     __a    :	Dict									=						0.0

     for concept_idx in range(len(special_cos_dist[0]			)			):
      __a    :	Tuple									=						special_cos_dist[i][concept_idx]
      __a    :	Any									=						self.special_care_embeds_weights[concept_idx].item()
      __a    :	Optional[Any]									=						round(concept_cos - concept_threshold + adjustment   ,   3			)
      if result_img["special_scores"][concept_idx] > 0:
       result_img["special_care"].append({concept_idx, result_img['special_scores'][concept_idx]}			)
       __a    :	Dict									=						0.01

     for concept_idx in range(len(cos_dist[0]			)			):
      __a    :	List[Any]									=						cos_dist[i][concept_idx]
      __a    :	Optional[int]									=						self.concept_embeds_weights[concept_idx].item()
      __a    :	List[str]									=						round(concept_cos - concept_threshold + adjustment   ,   3			)
      if result_img["concept_scores"][concept_idx] > 0:
       result_img["bad_concepts"].append(_A			)

     result.append(_A			)

    __a    :	Optional[int]									=						[len(res['bad_concepts']			) > 0 for res in result]

    for idx, has_nsfw_concept in enumerate(_A			):
     if has_nsfw_concept:
      if torch.is_tensor(_A			) or torch.is_tensor(images[0]			):
       __a    :	Optional[Any]									=						torch.zeros_like(images[idx]			)  # black image
      else:
       __a    :	Any									=						np.zeros(images[idx].shape			)  # black image

    if any(_A			):
     logger.warning(
         'Potential NSFW content was detected in one or more images. A black image will be returned instead.'
         ' Try again with a different prompt and/or seed.'			)

    return images, has_nsfw_concepts



   @torch.no_grad()
   def    __magic_name__    ( self   ,   _A   ,   _A			)    ->   Dict:
    __a    :	Union[str, Any]									=						self.vision_model(_A			)[1]  # pooled_output
    __a    :	Optional[Any]									=						self.visual_projection(_A			)

    __a    :	Dict									=						cosine_distance(_A   ,   self.special_care_embeds			)
    __a    :	str									=						cosine_distance(_A   ,   self.concept_embeds			)

    # increase this value to create a stronger `nsfw` filter
    # at the cost of increasing the possibility of filtering benign images
    __a    :	List[Any]									=						0.0

    __a    :	int									=						special_cos_dist - self.special_care_embeds_weights + adjustment
    # special_scores = special_scores.round(decimals=3)
    __a    :	List[Any]									=						torch.any(special_scores > 0   ,   dim=1			)
    __a    :	str									=						special_care * 0.01
    __a    :	Dict									=						special_adjustment.unsqueeze(1			).expand(-1   ,   cos_dist.shape[1]			)

    __a    :	Any									=						(cos_dist - self.concept_embeds_weights) + special_adjustment
    # concept_scores = concept_scores.round(decimals=3)
    __a    :	str									=						torch.any(concept_scores > 0   ,   dim=1			)

    __a    :	str									=						0.0  # black image

    return images, has_nsfw_concepts












'''simple docstring'''


from __future__ import annotations

import random

from matplotlib import animation
from matplotlib import pyplot as plt

# Frame rate of the animation
SCREAMING_SNAKE_CASE_				      =							2_0

# Time between time steps in seconds
SCREAMING_SNAKE_CASE_				      =							INTERVAL / 1_0_0_0




class 							lowerCAmelCase					:







   """simple docstring"""







   def __init__( self   ,   _A   ,   _A   ,   _A   ,   _A   ,   _A = 1.0   ,   _A = 1.0   ,   _A = "blue"   ,   )    ->   None:
    __a    :	str									=						position_x
    __a    :	Optional[Any]									=						position_y
    __a    :	List[Any]									=						velocity_x
    __a    :	Tuple									=						velocity_y
    __a    :	Dict									=						mass
    __a    :	int									=						size
    __a    :	Tuple									=						color



   @property
   def    __magic_name__    ( self			)    ->   tuple[float, float]:
    return self.position_x, self.position_y



   @property
   def    __magic_name__    ( self			)    ->   tuple[float, float]:
    return self.velocity_x, self.velocity_y



   def    __magic_name__    ( self   ,   _A   ,   _A   ,   _A			)    ->   None:
    self.velocity_x += force_x * delta_time
    self.velocity_y += force_y * delta_time



   def    __magic_name__    ( self   ,   _A			)    ->   None:
    self.position_x += self.velocity_x * delta_time
    self.position_y += self.velocity_y * delta_time




class 							lowerCAmelCase					:







   """simple docstring"""







   def __init__( self   ,   _A   ,   _A = 1.0   ,   _A = 1.0   ,   _A = 0.0   ,   )    ->   None:
    __a    :	List[str]									=						bodies
    __a    :	List[str]									=						gravitation_constant
    __a    :	int									=						time_factor
    __a    :	List[str]									=						softening_factor



   def __len__( self			)    ->   int:
    return len(self.bodies			)



   def    __magic_name__    ( self   ,   _A			)    ->   None:
    for bodya in self.bodies:
     __a    :	Any									=						0.0
     __a    :	str									=						0.0
     for bodya in self.bodies:
      if bodya != bodya:
       __a    :	Optional[Any]									=						bodya.position_x - bodya.position_x
       __a    :	Dict									=						bodya.position_y - bodya.position_y

       # Calculation of the distance using Pythagoras's theorem
       # Extra factor due to the softening technique
       __a    :	Optional[Any]									=						(dif_x**2 + dif_y**2 + self.softening_factor) ** (
           1 / 2
       )

       # Newton's law of universal gravitation.
       force_x += (
           self.gravitation_constant * bodya.mass * dif_x / distance**3
       )
       force_y += (
           self.gravitation_constant * bodya.mass * dif_y / distance**3
       )

            # Update the body's velocity once all the force components have been added
     bodya.update_velocity(_A   ,   _A   ,   delta_time * self.time_factor			)

    # Update the positions only after all the velocities have been updated
    for body in self.bodies:
     body.update_position(delta_time * self.time_factor			)






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		):
 body_system.update_system(SCREAMING_SNAKE_CASE__		)

 # Update the positions of the patches
 for patch, body in zip(SCREAMING_SNAKE_CASE__       ,		body_system.bodies		):
  __a    :	Dict									=						(body.position_x, body.position_y)






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__ = -1       ,		SCREAMING_SNAKE_CASE__ = 1       ,		SCREAMING_SNAKE_CASE__ = -1       ,		SCREAMING_SNAKE_CASE__ = 1       ,		):
 __a    :	int									=						plt.figure()
 fig.canvas.set_window_title(SCREAMING_SNAKE_CASE__		)
 __a    :	int									=						plt.axes(
     xlim=(x_start, x_end)       ,		ylim=(y_start, y_end)		)  # Set section to be plotted
 plt.gca().set_aspect('equal'		)  # Fix aspect ratio

 # Each body is drawn as a patch by the plt-function
 __a    :	str									=						[
     plt.Circle((body.position_x, body.position_y)       ,		body.size       ,		fc=body.color		)
     for body in body_system.bodies
 ]

 for patch in patches:
  ax.add_patch(SCREAMING_SNAKE_CASE__		)

 # Function called at each step of the animation
 def update(SCREAMING_SNAKE_CASE__		) -> list[plt.Circle]:
  update_step(SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		)
  return patches

 __a    :	Dict									=						animation.FuncAnimation(  # noqa: F841
     SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		interval=SCREAMING_SNAKE_CASE__       ,		blit=SCREAMING_SNAKE_CASE__		)

 plt.show()






def   lowerCAmelCase__			(					):
 __a    :	Dict									=						0.970_0436
 __a    :	List[Any]									=						-0.2430_8753
 __a    :	Union[str, Any]									=						0.4_6620_3685
 __a    :	Any									=						0.4323_6573

 __a    :	Optional[int]									=						[
     Body(SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		size=0.2       ,		color='red'		),
     Body(-position_x       ,		-position_y       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		size=0.2       ,		color='green'		),
     Body(0       ,		0       ,		-2 * velocity_x       ,		-2 * velocity_y       ,		size=0.2       ,		color='blue'		),
 ]
 return BodySystem(SCREAMING_SNAKE_CASE__       ,		time_factor=3		)






def   lowerCAmelCase__			(					):
 __a    :	Optional[int]									=						7.34_76E22
 __a    :	List[Any]									=						5.9_72E24
 __a    :	List[Any]									=						1022
 __a    :	str									=						384399000
 __a    :	Optional[int]									=						6.6_74E-11

 # Calculation of the respective velocities so that total impulse is zero,
 # i.e. the two bodies together don't move
 __a    :	str									=						earth_mass * velocity_dif / (earth_mass + moon_mass)
 __a    :	Optional[int]									=						moon_velocity - velocity_dif

 __a    :	Union[str, Any]									=						Body(-earth_moon_distance       ,		0       ,		0       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		10000000       ,		'grey'		)
 __a    :	Union[str, Any]									=						Body(0       ,		0       ,		0       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		50000000       ,		'blue'		)
 return BodySystem([earth, moon]       ,		SCREAMING_SNAKE_CASE__       ,		time_factor=1000000		)






def   lowerCAmelCase__			(					):
 __a    :	Tuple									=						[]
 for _ in range(10		):
  __a    :	Dict									=						random.uniform(-0.5       ,		0.5		)
  __a    :	Optional[int]									=						random.uniform(-0.5       ,		0.5		)

  # Bodies are created pairwise with opposite velocities so that the
  # total impulse remains zero
  bodies.append(
      Body(
          random.uniform(-0.5       ,		0.5		)       ,		random.uniform(-0.5       ,		0.5		)       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		size=0.05       ,		)		)
  bodies.append(
      Body(
          random.uniform(-0.5       ,		0.5		)       ,		random.uniform(-0.5       ,		0.5		)       ,		-velocity_x       ,		-velocity_y       ,		size=0.05       ,		)		)
 return BodySystem(SCREAMING_SNAKE_CASE__       ,		0.01       ,		10       ,		0.1		)


if __name__ == "__main__":
  plot("Figure-8 solution to the 3-body-problem", example_a(), -2, 2, -2, 2)
  plot(
      "Moon's orbit around the earth",
      example_a(),
      -4_3_0_0_0_0_0_0_0,
      4_3_0_0_0_0_0_0_0,
      -4_3_0_0_0_0_0_0_0,
      4_3_0_0_0_0_0_0_0,
  )
  plot("Random system with many bodies", example_a(), -1.5, 1.5, -1.5, 1.5)




