
"""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.
import torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool






class        _UpperCAmelCase(       lowerCamelCase      ):
		lowercase__         = 'facebook/bart-large-mnli'
		lowercase__         = (
		    'This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which '
		    'should be the text to classify, and `labels`, which should be the list of labels to use for classification. '
		    'It returns the most likely label in the list of provided `labels` for the input text.'
		)
		lowercase__         = 'text_classifier'
		lowercase__         = AutoTokenizer
		lowercase__         = AutoModelForSequenceClassification

		lowercase__         = ['text', ['text']]
		lowercase__         = ['text']



		def 		UpperCAmelCase				(   self)			->			int:






							'''simple docstring'''
							super().setup()
							_UpperCamelCase									=    self.model.config
							_UpperCamelCase									=    -1
							for idx, label in config.idalabel.items():
												if label.lower().startswith('''entail'''):
																	_UpperCamelCase									=    int(__a)
							if self.entailment_id == -1:
												raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.''')



		def 		UpperCAmelCase				(   self							,						__a							,						__a)			->			Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    labels
							return self.pre_processor(
							    [text] * len(__a)							,						[F'''This example is {label}''' for label in labels]							,						return_tensors='''pt'''							,						padding='''max_length'''							,						)




		def 		UpperCAmelCase				(   self							,						__a)			->			List[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    outputs.logits
							_UpperCamelCase									=    torch.argmax(logits[:, 2]).item()
							return self._labels[label_id]












import torch
from torch import nn
from transformers import CLIPPreTrainedModel, CLIPVisionModel

from ...models.attention import BasicTransformerBlock
from ...utils import logging


__magic_name__  :  List[str]					=       logging.get_logger(__name__)  # pylint: disable=invalid-name





class     SCREAMING_SNAKE_CASE__		(_a			):
     def __init__(						self	:		List[Any]       ,						__lowerCamelCase	:		Tuple       ,						__lowerCamelCase	:		List[Any]=7_68						):



       """simple docstring"""
       super().__init__(__lowerCamelCase						)
       lowerCAmelCase__										=      proj_size

       lowerCAmelCase__										=      CLIPVisionModel(__lowerCamelCase						)
       lowerCAmelCase__										=      PaintByExampleMapper(__lowerCamelCase						)
       lowerCAmelCase__										=      nn.LayerNorm(config.hidden_size						)
       lowerCAmelCase__										=      nn.Linear(config.hidden_size       ,						self.proj_size						)

       # uncondition for scaling
       lowerCAmelCase__										=      nn.Parameter(torch.randn((1, 1, self.proj_size)						)						)



     def        A__      (						self	:		Tuple       ,						__lowerCamelCase	:		int       ,						__lowerCamelCase	:		str=False						):



       """simple docstring"""
       lowerCAmelCase__										=      self.model(pixel_values=__lowerCamelCase						)
       lowerCAmelCase__										=      clip_output.pooler_output
       lowerCAmelCase__										=      self.mapper(latent_states[:, None]						)
       lowerCAmelCase__										=      self.final_layer_norm(__lowerCamelCase						)
       lowerCAmelCase__										=      self.proj_out(__lowerCamelCase						)
       if return_uncond_vector:
         return latent_states, self.uncond_vector

       return latent_states





class     SCREAMING_SNAKE_CASE__		(nn.Module			):
     def __init__(						self	:		Optional[Any]       ,						__lowerCamelCase	:		Tuple						):



       """simple docstring"""
       super().__init__()
       lowerCAmelCase__										=      (config.num_hidden_layers + 1) // 5
       lowerCAmelCase__										=      config.hidden_size
       lowerCAmelCase__										=      1
       lowerCAmelCase__										=      nn.ModuleList(
           [
               BasicTransformerBlock(__lowerCamelCase       ,						__lowerCamelCase       ,						__lowerCamelCase       ,						activation_fn='''gelu'''       ,						attention_bias=__lowerCamelCase						)
               for _ in range(__lowerCamelCase						)
           ]						)



     def        A__      (						self	:		str       ,						__lowerCamelCase	:		Optional[Any]						):



       """simple docstring"""
       for block in self.blocks:
         lowerCAmelCase__										=      block(__lowerCamelCase						)

       return hidden_states

