

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

from ...utils import logging


lowerCAmelCase__		      =       logging.get_logger(__name__)



def     lowerCAmelCase__							(		SCREAMING_SNAKE_CASE_:							Optional[int]		,				SCREAMING_SNAKE_CASE_:							int					)	->					int:




				'''simple docstring'''





				A__						=	nn.functional.normalize(SCREAMING_SNAKE_CASE_					)
				A__						=	nn.functional.normalize(SCREAMING_SNAKE_CASE_					)
				return torch.mm(SCREAMING_SNAKE_CASE_		,				normalized_text_embeds.t()					)





class     a__  (    snake_case	):
			"""simple docstring"""







			__lowerCamelCase       				=				CLIPConfig

			__lowerCamelCase       				=				['CLIPEncoderLayer']


			def __init__(			self					,					lowercase				)     ->  Optional[int]:
							'''simple docstring'''






							super().__init__(lowercase				)

							A__						=	CLIPVisionModel(config.vision_config				)
							A__						=	nn.Linear(config.vision_config.hidden_size					,					config.projection_dim					,					bias=lowercase				)

							A__						=	nn.Parameter(torch.ones(17					,					config.projection_dim				)					,					requires_grad=lowercase				)
							A__						=	nn.Parameter(torch.ones(3					,					config.projection_dim				)					,					requires_grad=lowercase				)

							A__						=	nn.Parameter(torch.ones(17				)					,					requires_grad=lowercase				)
							A__						=	nn.Parameter(torch.ones(3				)					,					requires_grad=lowercase				)


			@torch.no_grad()
			def    UpperCamelCase						(			self					,					lowercase					,					lowercase				)     ->  Any:
							'''simple docstring'''






							A__						=	self.vision_model(lowercase				)[1]  # pooled_output
							A__						=	self.visual_projection(lowercase				)

							# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
							A__						=	cosine_distance(lowercase					,					self.special_care_embeds				).cpu().float().numpy()
							A__						=	cosine_distance(lowercase					,					self.concept_embeds				).cpu().float().numpy()

							A__						=	[]
							A__						=	image_embeds.shape[0]
							for i in range(lowercase				):
											A__						=	{"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__						=	0.0

											for concept_idx in range(len(special_cos_dist[0]				)				):
															A__						=	special_cos_dist[i][concept_idx]
															A__						=	self.special_care_embeds_weights[concept_idx].item()
															A__						=	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__						=	0.01

											for concept_idx in range(len(cos_dist[0]				)				):
															A__						=	cos_dist[i][concept_idx]
															A__						=	self.concept_embeds_weights[concept_idx].item()
															A__						=	round(concept_cos - concept_threshold + adjustment					,					3				)
															if result_img["concept_scores"][concept_idx] > 0:
																			result_img["bad_concepts"].append(lowercase				)

											result.append(lowercase				)

							A__						=	[len(res["bad_concepts"]				) > 0 for res in result]

							return images, has_nsfw_concepts


			@torch.no_grad()
			def    UpperCamelCase						(			self					,					lowercase					,					lowercase				)     ->  Any:
							'''simple docstring'''






							A__						=	self.vision_model(lowercase				)[1]  # pooled_output
							A__						=	self.visual_projection(lowercase				)

							A__						=	cosine_distance(lowercase					,					self.special_care_embeds				)
							A__						=	cosine_distance(lowercase					,					self.concept_embeds				)

							# increase this value to create a stronger `nsfw` filter
							# at the cost of increasing the possibility of filtering benign images
							A__						=	0.0

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

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

							return images, has_nsfw_concepts







import datetime
import platform
import subprocess
from typing import Optional, Tuple, Union

import numpy as np

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	bytes			,			__UpperCAmelCase						:	int							)					-> np.array:
      SCREAMING_SNAKE_CASE_							=			f"{sampling_rate}"
      SCREAMING_SNAKE_CASE_							=			'1'
      SCREAMING_SNAKE_CASE_							=			'f32le'
      SCREAMING_SNAKE_CASE_							=			[
          'ffmpeg',
          '-i',
          'pipe:0',
          '-ac',
          ac,
          '-ar',
          ar,
          '-f',
          format_for_conversion,
          '-hide_banner',
          '-loglevel',
          'quiet',
          'pipe:1',
      ]

      try:
            with subprocess.Popen(__UpperCAmelCase			,			stdin=subprocess.PIPE			,			stdout=subprocess.PIPE							) as ffmpeg_process:
                  SCREAMING_SNAKE_CASE_							=			ffmpeg_process.communicate(__UpperCAmelCase							)
      except FileNotFoundError as error:
            raise ValueError('ffmpeg was not found but is required to load audio files from filename'							) from error
      SCREAMING_SNAKE_CASE_							=			output_stream[0]
      SCREAMING_SNAKE_CASE_							=			np.frombuffer(__UpperCAmelCase			,			np.floataa							)
      if audio.shape[0] == 0:
            raise ValueError('Malformed soundfile'							)
      return audio

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	int			,			__UpperCAmelCase						:	float			,			__UpperCAmelCase						:	str = "f32le"			,			)					-> int:
      SCREAMING_SNAKE_CASE_							=			f"{sampling_rate}"
      SCREAMING_SNAKE_CASE_							=			'1'
      if format_for_conversion == "s16le":
            SCREAMING_SNAKE_CASE_							=			2
      elif format_for_conversion == "f32le":
            SCREAMING_SNAKE_CASE_							=			4
      else:
            raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`"							)

      SCREAMING_SNAKE_CASE_							=			platform.system()
      if system == "Linux":
            SCREAMING_SNAKE_CASE_							=			'alsa'
            SCREAMING_SNAKE_CASE_							=			'default'
      elif system == "Darwin":
            SCREAMING_SNAKE_CASE_							=			'avfoundation'
            SCREAMING_SNAKE_CASE_							=			':0'
      elif system == "Windows":
            SCREAMING_SNAKE_CASE_							=			'dshow'
            SCREAMING_SNAKE_CASE_							=			'default'

      SCREAMING_SNAKE_CASE_							=			[
          'ffmpeg',
          '-f',
          format_,
          '-i',
          input_,
          '-ac',
          ac,
          '-ar',
          ar,
          '-f',
          format_for_conversion,
          '-fflags',
          'nobuffer',
          '-hide_banner',
          '-loglevel',
          'quiet',
          'pipe:1',
      ]
      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * chunk_length_s							)							) * size_of_sample
      SCREAMING_SNAKE_CASE_							=			_ffmpeg_stream(__UpperCAmelCase			,			__UpperCAmelCase							)
      for item in iterator:
            yield item

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	int			,			__UpperCAmelCase						:	float			,			__UpperCAmelCase						:	Optional[int] = None			,			__UpperCAmelCase						:	Optional[Union[Tuple[float, float], float]] = None			,			__UpperCAmelCase						:	str = "f32le"			,			)					-> Tuple:
      if stream_chunk_s is not None:
            SCREAMING_SNAKE_CASE_							=			stream_chunk_s
      else:
            SCREAMING_SNAKE_CASE_							=			chunk_length_s

      SCREAMING_SNAKE_CASE_							=			ffmpeg_microphone(__UpperCAmelCase			,			__UpperCAmelCase			,			format_for_conversion=__UpperCAmelCase							)
      if format_for_conversion == "s16le":
            SCREAMING_SNAKE_CASE_							=			np.intaa
            SCREAMING_SNAKE_CASE_							=			2
      elif format_for_conversion == "f32le":
            SCREAMING_SNAKE_CASE_							=			np.floataa
            SCREAMING_SNAKE_CASE_							=			4
      else:
            raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`"							)

      if stride_length_s is None:
            SCREAMING_SNAKE_CASE_							=			chunk_length_s / 6
      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * chunk_length_s							)							) * size_of_sample
      if isinstance(__UpperCAmelCase			,			(int, float)							):
            SCREAMING_SNAKE_CASE_							=			[stride_length_s, stride_length_s]

      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * stride_length_s[0]							)							) * size_of_sample
      SCREAMING_SNAKE_CASE_							=			int(round(sampling_rate * stride_length_s[1]							)							) * size_of_sample
      SCREAMING_SNAKE_CASE_							=			datetime.datetime.now()
      SCREAMING_SNAKE_CASE_							=			datetime.timedelta(seconds=__UpperCAmelCase							)
      for item in chunk_bytes_iter(__UpperCAmelCase			,			__UpperCAmelCase			,			stride=(stride_left, stride_right)			,			stream=__UpperCAmelCase							):
            # Put everything back in numpy scale
            SCREAMING_SNAKE_CASE_							=			np.frombuffer(item['raw']			,			dtype=__UpperCAmelCase							)
            SCREAMING_SNAKE_CASE_							=			(
                item['stride'][0] // size_of_sample,
                item['stride'][1] // size_of_sample,
            )
            SCREAMING_SNAKE_CASE_							=			sampling_rate
            audio_time += delta
            if datetime.datetime.now() > audio_time + 10 * delta:
                  # We're late !! SKIP
                  continue
            yield item

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Optional[Any]			,			__UpperCAmelCase						:	int			,			__UpperCAmelCase						:	Tuple[int, int]			,			__UpperCAmelCase						:	bool = False							)					-> Union[str, Any]:
      SCREAMING_SNAKE_CASE_							=			b''
      SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			stride
      if stride_left + stride_right >= chunk_len:
            raise ValueError(
                f"Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}"							)
      SCREAMING_SNAKE_CASE_							=			0
      for raw in iterator:
            acc += raw
            if stream and len(__UpperCAmelCase							) < chunk_len:
                  SCREAMING_SNAKE_CASE_							=			(_stride_left, 0)
                  yield {"raw": acc[:chunk_len], "stride": stride, "partial": True}
            else:
                  while len(__UpperCAmelCase							) >= chunk_len:
                        # We are flushing the accumulator
                        SCREAMING_SNAKE_CASE_							=			(_stride_left, stride_right)
                        SCREAMING_SNAKE_CASE_							=			{'raw': acc[:chunk_len], 'stride': stride}
                        if stream:
                              SCREAMING_SNAKE_CASE_							=			False
                        yield item
                        SCREAMING_SNAKE_CASE_							=			stride_left
                        SCREAMING_SNAKE_CASE_							=			acc[chunk_len - stride_left - stride_right :]
    # Last chunk
      if len(__UpperCAmelCase							) > stride_left:
            SCREAMING_SNAKE_CASE_							=			{'raw': acc, 'stride': (_stride_left, 0)}
            if stream:
                  SCREAMING_SNAKE_CASE_							=			False
            yield item





def 					UpperCAmelCase_							(      __UpperCAmelCase						:	List[str]			,			__UpperCAmelCase						:	int							)					-> Optional[Any]:
      SCREAMING_SNAKE_CASE_							=			2**24  # 16Mo
      try:
            with subprocess.Popen(__UpperCAmelCase			,			stdout=subprocess.PIPE			,			bufsize=__UpperCAmelCase							) as ffmpeg_process:
                  while True:
                        SCREAMING_SNAKE_CASE_							=			ffmpeg_process.stdout.read(__UpperCAmelCase							)
                        if raw == b"":
                              break
                        yield raw
      except FileNotFoundError as error:
            raise ValueError('ffmpeg was not found but is required to stream audio files from filename'							) from error