



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

from ...utils import logging


SCREAMING_SNAKE_CASE_:Union[str, Any] 			=		logging.get_logger(__name__)




def       __UpperCamelCase      (    _lowerCAmelCase ,	_lowerCAmelCase						)			->    str:



    """simple docstring"""






    A					:			str		=  nn.functional.normalize(__UpperCAmelCase						)
    A					:			Optional[Any]		=  nn.functional.normalize(__UpperCAmelCase						)
    return torch.mm(__UpperCAmelCase ,	normalized_text_embeds.t()						)






class SCREAMING_SNAKE_CASE__	(						SCREAMING_SNAKE_CASE_       ):




    '''simple docstring'''






    __lowerCamelCase     :					List[str]   = CLIPConfig

    __lowerCamelCase     :					Any   = ["CLIPEncoderLayer"]






    def __init__(			self,						lowerCamelCase__						):
        super().__init__(__snake_case						)

        A					:			Union[str, Any]		=  CLIPVisionModel(config.vision_config						)
        A					:			Optional[Any]		=  nn.Linear(config.vision_config.hidden_size,						config.projection_dim,						bias=__snake_case						)

        A					:			List[Any]		=  nn.Parameter(torch.ones(17,						config.projection_dim						),						requires_grad=__snake_case						)
        A					:			Any		=  nn.Parameter(torch.ones(3,						config.projection_dim						),						requires_grad=__snake_case						)

        A					:			Any		=  nn.Parameter(torch.ones(17						),						requires_grad=__snake_case						)
        A					:			List[Any]		=  nn.Parameter(torch.ones(3						),						requires_grad=__snake_case						)






    @torch.no_grad()
    def      _lowerCAmelCase   (			self,						lowerCamelCase__,						lowerCamelCase__						):
        A					:			Optional[int]		=  self.vision_model(__snake_case						)[1]  # pooled_output
        A					:			Tuple		=  self.visual_projection(__snake_case						)

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

        A					:			Optional[int]		=  []
        A					:			Tuple		=  image_embeds.shape[0]
        for i in range(__snake_case						):
            A					:			Optional[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					:			List[str]		=  0.0

            for concept_idx in range(len(special_cos_dist[0]						)						):
                A					:			str		=  special_cos_dist[i][concept_idx]
                A					:			List[str]		=  self.special_care_embeds_weights[concept_idx].item()
                A					:			str		=  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					:			Optional[int]		=  0.01

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

            result.append(__snake_case						)

        A					:			int		=  [len(res["""bad_concepts"""]						) > 0 for res in result]

        return images, has_nsfw_concepts






    @torch.no_grad()
    def      _lowerCAmelCase   (			self,						lowerCamelCase__,						lowerCamelCase__						):
        A					:			Tuple		=  self.vision_model(__snake_case						)[1]  # pooled_output
        A					:			List[Any]		=  self.visual_projection(__snake_case						)

        A					:			Dict		=  cosine_distance(__snake_case,						self.special_care_embeds						)
        A					:			Optional[int]		=  cosine_distance(__snake_case,						self.concept_embeds						)

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

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

        A					:			Tuple		=  (cos_dist - self.concept_embeds_weights) + special_adjustment
        # concept_scores = concept_scores.round(decimals=3)
        A					:			List[str]		=  torch.any(concept_scores > 0,						dim=1						)

        return images, has_nsfw_concepts










"""simple docstring"""





# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool



class       __A		(   SCREAMING_SNAKE_CASE_			):
					UpperCAmelCase__								=				"openai/whisper-base"
					UpperCAmelCase__								=				(
					    "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the "
					    "transcribed text."
					)
					UpperCAmelCase__								=				"transcriber"
					UpperCAmelCase__								=				WhisperProcessor
					UpperCAmelCase__								=				WhisperForConditionalGeneration

					UpperCAmelCase__								=				["audio"]
					UpperCAmelCase__								=				["text"]

					def   lowerCamelCase__   (			self  :      Dict     ,		__snake_case  :      List[str]					)			->							Dict:
											return self.pre_processor(__snake_case     ,		return_tensors="""pt"""					).input_features

					def   lowerCamelCase__   (			self  :      int     ,		__snake_case  :      Union[str, Any]					)			->							List[str]:
											return self.model.generate(inputs=__snake_case					)






					def   lowerCamelCase__   (			self  :      Union[str, Any]     ,		__snake_case  :      List[Any]					)			->							Any:
											return self.pre_processor.batch_decode(__snake_case     ,		skip_special_tokens=__snake_case					)[0]



