




'''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       A   (		_a   ):
							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        __lowerCAmelCase      (  self	:  Optional[Any] )      ->							Optional[Any]:


														"""simple docstring"""


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







							def        __lowerCAmelCase      (  self	:  Optional[int]							,      lowerCAmelCase_	:  str							,      lowerCAmelCase_	:  List[str] )      ->							Any:


														"""simple docstring"""


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







							def        __lowerCAmelCase      (  self	:  Any							,      lowerCAmelCase_	:  Any )      ->							Dict:


														"""simple docstring"""


														_a     					=    outputs.logits
														_a     					=    torch.argmax(logits[:, 2] ).item()
														return self._labels[label_id]







'''simple docstring'''


import tempfile
import unittest

import numpy as np
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import BertConfig, is_flax_available
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax


if is_flax_available():
				import os

				from flax.core.frozen_dict import unfreeze
				from flax.traverse_util import flatten_dict

				from transformers import FlaxBertModel

				_snake_case				:				Optional[Any]       							=		'0.12'  # assumed parallelism: 8

@require_flax
@is_staging_test
class       A   (		unittest.TestCase   ):







							@classmethod
							def        __lowerCAmelCase      (  cls	:  Tuple )      ->							int:


														"""simple docstring"""


														_a     					=    TOKEN
														HfFolder.save_token(lowerCAmelCase_ )







							@classmethod
							def        __lowerCAmelCase      (  cls	:  Tuple )      ->							Optional[int]:


														"""simple docstring"""


														try:
																					delete_repo(token=cls._token							,      repo_id='''test-model-flax''' )
														except HTTPError:
																					pass

														try:
																					delete_repo(token=cls._token							,      repo_id='''valid_org/test-model-flax-org''' )
														except HTTPError:
																					pass







							def        __lowerCAmelCase      (  self	:  Any )      ->							Optional[Any]:


														"""simple docstring"""


														_a     					=    BertConfig(
														    vocab_size=99							,      hidden_size=32							,      num_hidden_layers=5							,      num_attention_heads=4							,      intermediate_size=37 )
														_a     					=    FlaxBertModel(lowerCAmelCase_ )
														model.push_to_hub('''test-model-flax'''							,      use_auth_token=self._token )

														_a     					=    FlaxBertModel.from_pretrained(F'{USER}/test-model-flax' )

														_a     					=    flatten_dict(unfreeze(model.params ) )
														_a     					=    flatten_dict(unfreeze(new_model.params ) )

														for key in base_params.keys():
																					_a     					=    (base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCAmelCase_							,      1e-3							,      msg=F'{key} not identical' )

														# Reset repo
														delete_repo(token=self._token							,      repo_id='''test-model-flax''' )

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(lowerCAmelCase_							,      repo_id='''test-model-flax'''							,      push_to_hub=lowerCAmelCase_							,      use_auth_token=self._token )

														_a     					=    FlaxBertModel.from_pretrained(F'{USER}/test-model-flax' )

														_a     					=    flatten_dict(unfreeze(model.params ) )
														_a     					=    flatten_dict(unfreeze(new_model.params ) )

														for key in base_params.keys():
																					_a     					=    (base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCAmelCase_							,      1e-3							,      msg=F'{key} not identical' )







							def        __lowerCAmelCase      (  self	:  int )      ->							Tuple:


														"""simple docstring"""


														_a     					=    BertConfig(
														    vocab_size=99							,      hidden_size=32							,      num_hidden_layers=5							,      num_attention_heads=4							,      intermediate_size=37 )
														_a     					=    FlaxBertModel(lowerCAmelCase_ )
														model.push_to_hub('''valid_org/test-model-flax-org'''							,      use_auth_token=self._token )

														_a     					=    FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' )

														_a     					=    flatten_dict(unfreeze(model.params ) )
														_a     					=    flatten_dict(unfreeze(new_model.params ) )

														for key in base_params.keys():
																					_a     					=    (base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCAmelCase_							,      1e-3							,      msg=F'{key} not identical' )

														# Reset repo
														delete_repo(token=self._token							,      repo_id='''valid_org/test-model-flax-org''' )

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(
																					    lowerCAmelCase_							,      repo_id='''valid_org/test-model-flax-org'''							,      push_to_hub=lowerCAmelCase_							,      use_auth_token=self._token )

														_a     					=    FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' )

														_a     					=    flatten_dict(unfreeze(model.params ) )
														_a     					=    flatten_dict(unfreeze(new_model.params ) )

														for key in base_params.keys():
																					_a     					=    (base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCAmelCase_							,      1e-3							,      msg=F'{key} not identical' )



def 		snake_case_   (UpperCamelCase	:  List[str]			,						UpperCamelCase	:  Optional[Any]				):





							'''simple docstring'''


							_a     					=    True
							_a     					=    flatten_dict(modela.params				)
							_a     					=    flatten_dict(modela.params				)
							for key in flat_params_a.keys():
														if np.sum(np.abs(flat_params_a[key] - flat_params_a[key]				)				) > 1e-4:
																					_a     					=    False

							return models_are_equal

@require_flax
class       A   (		unittest.TestCase   ):







							def        __lowerCAmelCase      (  self	:  Dict )      ->							int:


														"""simple docstring"""


														_a     					=    BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' )
														_a     					=    FlaxBertModel(lowerCAmelCase_ )

														_a     					=    '''bert'''
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(os.path.join(lowerCAmelCase_							,      lowerCAmelCase_ ) )

																					with self.assertRaises(lowerCAmelCase_ ):
																												_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_ )

																					_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_							,      subfolder=lowerCAmelCase_ )

														self.assertTrue(check_models_equal(lowerCAmelCase_							,      lowerCAmelCase_ ) )







							def        __lowerCAmelCase      (  self	:  Union[str, Any] )      ->							Optional[int]:


														"""simple docstring"""


														_a     					=    BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' )
														_a     					=    FlaxBertModel(lowerCAmelCase_ )

														_a     					=    '''bert'''
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(os.path.join(lowerCAmelCase_							,      lowerCAmelCase_ )							,      max_shard_size='''10KB''' )

																					with self.assertRaises(lowerCAmelCase_ ):
																												_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_ )

																					_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_							,      subfolder=lowerCAmelCase_ )

														self.assertTrue(check_models_equal(lowerCAmelCase_							,      lowerCAmelCase_ ) )







							def        __lowerCAmelCase      (  self	:  Optional[Any] )      ->							List[str]:


														"""simple docstring"""


														_a     					=    '''bert'''
														_a     					=    '''hf-internal-testing/tiny-random-bert-subfolder'''

														with self.assertRaises(lowerCAmelCase_ ):
																					_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_ )

														_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_							,      subfolder=lowerCAmelCase_ )

														self.assertIsNotNone(lowerCAmelCase_ )







							def        __lowerCAmelCase      (  self	:  Tuple )      ->							Tuple:


														"""simple docstring"""


														_a     					=    '''bert'''
														_a     					=    '''hf-internal-testing/tiny-random-bert-sharded-subfolder'''
														with self.assertRaises(lowerCAmelCase_ ):
																					_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_ )

														_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_							,      subfolder=lowerCAmelCase_ )

														self.assertIsNotNone(lowerCAmelCase_ )

