




from __future__ import annotations

import copy
import tempfile
import unittest

from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available
from transformers.testing_utils import (
    DUMMY_UNKNOWN_IDENTIFIER,
    SMALL_MODEL_IDENTIFIER,
    RequestCounter,
    require_tensorflow_probability,
    require_tf,
    slow,
)

from ..bert.test_modeling_bert import BertModelTester


if is_tf_available():
    from transformers import (
        TFAutoModel,
        TFAutoModelForCausalLM,
        TFAutoModelForMaskedLM,
        TFAutoModelForPreTraining,
        TFAutoModelForQuestionAnswering,
        TFAutoModelForSeqaSeqLM,
        TFAutoModelForSequenceClassification,
        TFAutoModelForTableQuestionAnswering,
        TFAutoModelForTokenClassification,
        TFAutoModelWithLMHead,
        TFBertForMaskedLM,
        TFBertForPreTraining,
        TFBertForQuestionAnswering,
        TFBertForSequenceClassification,
        TFBertModel,
        TFFunnelBaseModel,
        TFFunnelModel,
        TFGPTaLMHeadModel,
        TFRobertaForMaskedLM,
        TFTaForConditionalGeneration,
        TFTapasForQuestionAnswering,
    )
    from transformers.models.auto.modeling_tf_auto import (
        TF_MODEL_FOR_CAUSAL_LM_MAPPING,
        TF_MODEL_FOR_MASKED_LM_MAPPING,
        TF_MODEL_FOR_PRETRAINING_MAPPING,
        TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
        TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
        TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
        TF_MODEL_MAPPING,
    )
    from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
    from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
    from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
    from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST


class     lowercase__  (					__SCREAMING_SNAKE_CASE		):
  A__=  'new-model'


if is_tf_available():


    class     lowercase__  (					__SCREAMING_SNAKE_CASE		):
      A__=  NewModelConfig


@require_tf
class     lowercase__  (					unittest.TestCase		):






  @slow
  def 			_UpperCAmelCase  (					self      :					Optional[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     "bert-base-cased"
         UpperCAmelCase__										=     AutoConfig.from_pretrained(__A )
         self.assertIsNotNone(__A )
         self.assertIsInstance(__A		,						__A )

         UpperCAmelCase__										=     TFAutoModel.from_pretrained(__A )
         self.assertIsNotNone(__A )
         self.assertIsInstance(__A		,						__A )






  @slow
  def 			_UpperCAmelCase  (					self      :					Optional[int] ):




         """simple docstring"""







         UpperCAmelCase__										=     "bert-base-cased"
         UpperCAmelCase__										=     AutoConfig.from_pretrained(__A )
         self.assertIsNotNone(__A )
         self.assertIsInstance(__A		,						__A )

         UpperCAmelCase__										=     TFAutoModelForPreTraining.from_pretrained(__A )
         self.assertIsNotNone(__A )
         self.assertIsInstance(__A		,						__A )






  @slow
  def 			_UpperCAmelCase  (					self      :					Dict ):




         """simple docstring"""







         for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                UpperCAmelCase__										=     AutoConfig.from_pretrained(__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )

                UpperCAmelCase__										=     TFAutoModelForCausalLM.from_pretrained(__A )
                UpperCAmelCase__						,			UpperCAmelCase__										=     TFAutoModelForCausalLM.from_pretrained(__A		,						output_loading_info=__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )






  @slow
  def 			_UpperCAmelCase  (					self      :					Tuple ):




         """simple docstring"""







         for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                UpperCAmelCase__										=     AutoConfig.from_pretrained(__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )

                UpperCAmelCase__										=     TFAutoModelWithLMHead.from_pretrained(__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )






  @slow
  def 			_UpperCAmelCase  (					self      :					int ):




         """simple docstring"""







         for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                UpperCAmelCase__										=     AutoConfig.from_pretrained(__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )

                UpperCAmelCase__										=     TFAutoModelForMaskedLM.from_pretrained(__A )
                UpperCAmelCase__						,			UpperCAmelCase__										=     TFAutoModelForMaskedLM.from_pretrained(__A		,						output_loading_info=__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )






  @slow
  def 			_UpperCAmelCase  (					self      :					str ):




         """simple docstring"""







         for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                UpperCAmelCase__										=     AutoConfig.from_pretrained(__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )

                UpperCAmelCase__										=     TFAutoModelForSeqaSeqLM.from_pretrained(__A )
                UpperCAmelCase__						,			UpperCAmelCase__										=     TFAutoModelForSeqaSeqLM.from_pretrained(__A		,						output_loading_info=__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )






  @slow
  def 			_UpperCAmelCase  (					self      :					Union[str, Any] ):




         """simple docstring"""







         for model_name in ["bert-base-uncased"]:
                UpperCAmelCase__										=     AutoConfig.from_pretrained(__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )

                UpperCAmelCase__										=     TFAutoModelForSequenceClassification.from_pretrained(__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )






  @slow
  def 			_UpperCAmelCase  (					self      :					Optional[int] ):




         """simple docstring"""







         for model_name in ["bert-base-uncased"]:
                UpperCAmelCase__										=     AutoConfig.from_pretrained(__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )

                UpperCAmelCase__										=     TFAutoModelForQuestionAnswering.from_pretrained(__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )






  @slow
  @require_tensorflow_probability
  def 			_UpperCAmelCase  (					self      :					Any ):




         """simple docstring"""







         for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]:
                UpperCAmelCase__										=     AutoConfig.from_pretrained(__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )

                UpperCAmelCase__										=     TFAutoModelForTableQuestionAnswering.from_pretrained(__A )
                UpperCAmelCase__						,			UpperCAmelCase__										=     TFAutoModelForTableQuestionAnswering.from_pretrained(
                    __A		,						output_loading_info=__A )
                self.assertIsNotNone(__A )
                self.assertIsInstance(__A		,						__A )






  def 			_UpperCAmelCase  (					self      :					List[str] ):




         """simple docstring"""







         UpperCAmelCase__										=     TFAutoModelWithLMHead.from_pretrained(__A )
         self.assertIsInstance(__A		,						__A )
         self.assertEqual(model.num_parameters()		,						1_44_10 )
         self.assertEqual(model.num_parameters(only_trainable=__A )		,						1_44_10 )






  def 			_UpperCAmelCase  (					self      :					Union[str, Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     TFAutoModelWithLMHead.from_pretrained(__A )
         self.assertIsInstance(__A		,						__A )
         self.assertEqual(model.num_parameters()		,						1_44_10 )
         self.assertEqual(model.num_parameters(only_trainable=__A )		,						1_44_10 )






  def 			_UpperCAmelCase  (					self      :					Optional[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     TFAutoModel.from_pretrained("sgugger/funnel-random-tiny" )
         self.assertIsInstance(__A		,						__A )

         UpperCAmelCase__										=     copy.deepcopy(model.config )
         UpperCAmelCase__										=     ["FunnelBaseModel"]
         UpperCAmelCase__										=     TFAutoModel.from_config(__A )
         self.assertIsInstance(__A		,						__A )

         with tempfile.TemporaryDirectory() as tmp_dir:
                model.save_pretrained(__A )
                UpperCAmelCase__										=     TFAutoModel.from_pretrained(__A )
                self.assertIsInstance(__A		,						__A )






  def 			_UpperCAmelCase  (					self      :					Optional[Any] ):




         """simple docstring"""







         try:
                AutoConfig.register("new-model"		,						__A )

                UpperCAmelCase__										=     [
                    TFAutoModel,
                    TFAutoModelForCausalLM,
                    TFAutoModelForMaskedLM,
                    TFAutoModelForPreTraining,
                    TFAutoModelForQuestionAnswering,
                    TFAutoModelForSequenceClassification,
                    TFAutoModelForTokenClassification,
                ]

                for auto_class in auto_classes:
                       with self.subTest(auto_class.__name__ ):
                              # Wrong config class will raise an error
                              with self.assertRaises(__A ):
                                     auto_class.register(__A		,						__A )
                              auto_class.register(__A		,						__A )
                              # Trying to register something existing in the Transformers library will raise an error
                              with self.assertRaises(__A ):
                                     auto_class.register(__A		,						__A )

                              # Now that the config is registered, it can be used as any other config with the auto-API
                              UpperCAmelCase__										=     BertModelTester(self ).get_config()
                              UpperCAmelCase__										=     NewModelConfig(**tiny_config.to_dict() )
                              UpperCAmelCase__										=     auto_class.from_config(__A )
                              self.assertIsInstance(__A		,						__A )

                              with tempfile.TemporaryDirectory() as tmp_dir:
                                     model.save_pretrained(__A )
                                     UpperCAmelCase__										=     auto_class.from_pretrained(__A )
                                     self.assertIsInstance(__A		,						__A )

         finally:
                if "new-model" in CONFIG_MAPPING._extra_content:
                       del CONFIG_MAPPING._extra_content["new-model"]
                for mapping in (
                    TF_MODEL_MAPPING,
                    TF_MODEL_FOR_PRETRAINING_MAPPING,
                    TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
                    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
                    TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
                    TF_MODEL_FOR_CAUSAL_LM_MAPPING,
                    TF_MODEL_FOR_MASKED_LM_MAPPING,
                ):
                       if NewModelConfig in mapping._extra_content:
                              del mapping._extra_content[NewModelConfig]






  def 			_UpperCAmelCase  (					self      :					Optional[Any] ):




         """simple docstring"""







         with self.assertRaisesRegex(
             __A		,						"bert-base is not a local folder and is not a valid model identifier" ):
                UpperCAmelCase__										=     TFAutoModel.from_pretrained("bert-base" )






  def 			_UpperCAmelCase  (					self      :					List[str] ):




         """simple docstring"""







         with self.assertRaisesRegex(
             __A		,						r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ):
                UpperCAmelCase__										=     TFAutoModel.from_pretrained(__A		,						revision="aaaaaa" )






  def 			_UpperCAmelCase  (					self      :					Tuple ):




         """simple docstring"""







         with self.assertRaisesRegex(
             __A		,						"hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin"		,						):
                UpperCAmelCase__										=     TFAutoModel.from_pretrained("hf-internal-testing/config-no-model" )






  def 			_UpperCAmelCase  (					self      :					int ):




         """simple docstring"""







         with self.assertRaisesRegex(__A		,						"Use `from_pt=True` to load this model" ):
                UpperCAmelCase__										=     TFAutoModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only" )






  def 			_UpperCAmelCase  (					self      :					List[str] ):




         """simple docstring"""







         UpperCAmelCase__										=     TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" )
         with RequestCounter() as counter:
                UpperCAmelCase__										=     TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" )
                self.assertEqual(counter.get_request_count		,						0 )
                self.assertEqual(counter.head_request_count		,						1 )
                self.assertEqual(counter.other_request_count		,						0 )

         # With a sharded checkpoint
         UpperCAmelCase__										=     TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" )
         with RequestCounter() as counter:
                UpperCAmelCase__										=     TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" )
                self.assertEqual(counter.get_request_count		,						0 )
                self.assertEqual(counter.head_request_count		,						1 )
                self.assertEqual(counter.other_request_count		,						0 )









import uuid
from typing import Any, Dict, List, Optional, Union

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
    import tensorflow as tf

if is_torch_available():
    import torch


A      = logging.get_logger(__name__)


class     lowercase__  :






  def __init__(					self      :					List[str]		,						_lowercase      :					str = None		,						_lowercase      :					uuid.UUID = None		,						_lowercase      :					Dict=None		,						_lowercase      :					Any=None ):




         """simple docstring"""







         if not conversation_id:
                UpperCAmelCase__										=     uuid.uuida()
         if past_user_inputs is None:
                UpperCAmelCase__										=     []
         if generated_responses is None:
                UpperCAmelCase__										=     []

         UpperCAmelCase__										=     conversation_id
         UpperCAmelCase__										=     past_user_inputs
         UpperCAmelCase__										=     generated_responses
         UpperCAmelCase__										=     text






  def __eq__(					self      :					Any		,						_lowercase      :					str ):




         """simple docstring"""







         if not isinstance(_lowercase		,						_lowercase ):
                return False
         if self.uuid == other.uuid:
                return True
         return (
             self.new_user_input == other.new_user_input
             and self.past_user_inputs == other.past_user_inputs
             and self.generated_responses == other.generated_responses
         )






  def 			_UpperCAmelCase  (					self      :					Any		,						_lowercase      :					str		,						_lowercase      :					bool = False ):




         """simple docstring"""







         if self.new_user_input:
                if overwrite:
                       logger.warning(
                           F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" was overwritten """
                           F"""with: \"{text}\".""" )
                       UpperCAmelCase__										=     text
                else:
                       logger.warning(
                           F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" new input """
                           F"""ignored: \"{text}\". Set `overwrite` to True to overwrite unprocessed user input""" )
         else:
                UpperCAmelCase__										=     text






  def 			_UpperCAmelCase  (					self      :					int ):




         """simple docstring"""







         if self.new_user_input:
                self.past_user_inputs.append(self.new_user_input )
         UpperCAmelCase__										=     None






  def 			_UpperCAmelCase  (					self      :					List[str]		,						_lowercase      :					str ):




         """simple docstring"""







         self.generated_responses.append(_lowercase )






  def 			_UpperCAmelCase  (					self      :					List[str] ):




         """simple docstring"""







         for user_input, generated_response in zip(self.past_user_inputs		,						self.generated_responses ):
                yield True, user_input
                yield False, generated_response
         if self.new_user_input:
                yield True, self.new_user_input






  def __repr__(					self      :					List[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     F"""Conversation id: {self.uuid} \n"""
         for is_user, text in self.iter_texts():
                UpperCAmelCase__										=     "user" if is_user else "bot"
                output += F"""{name} >> {text} \n"""
         return output




@add_end_docstrings(
    __SCREAMING_SNAKE_CASE					,							R'\n        min_length_for_response (`int`, *optional*, defaults to 32):\n            The minimum length (in number of tokens) for a response.\n        minimum_tokens (`int`, *optional*, defaults to 10):\n            The minimum length of tokens to leave for a response.\n    '					,							)
class     lowercase__  (					__SCREAMING_SNAKE_CASE		):






  def __init__(					self      :					str		,						*_lowercase      :					Union[str, Any]		,						**_lowercase      :					Any ):




         """simple docstring"""







         super().__init__(*_lowercase		,						**_lowercase )
         if self.tokenizer.pad_token_id is None:
                UpperCAmelCase__										=     self.tokenizer.eos_token






  def 			_UpperCAmelCase  (					self      :					List[str]		,						_lowercase      :					int=None		,						_lowercase      :					Any=None		,						_lowercase      :					List[str]=None		,						**_lowercase      :					Dict ):




         """simple docstring"""







         UpperCAmelCase__										=     {}
         UpperCAmelCase__										=     {}
         UpperCAmelCase__										=     {}

         if min_length_for_response is not None:
                UpperCAmelCase__										=     min_length_for_response
         if minimum_tokens is not None:
                UpperCAmelCase__										=     minimum_tokens

         if "max_length" in generate_kwargs:
                UpperCAmelCase__										=     generate_kwargs["max_length"]
                # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
         if clean_up_tokenization_spaces is not None:
                UpperCAmelCase__										=     clean_up_tokenization_spaces

         if generate_kwargs:
                forward_params.update(_lowercase )
         return preprocess_params, forward_params, postprocess_params






  def __call__(					self      :					Dict		,						_lowercase      :					Union[Conversation, List[Conversation]]		,						_lowercase      :					List[str]=0		,						**_lowercase      :					Optional[int] ):




         """simple docstring"""







         UpperCAmelCase__										=     super().__call__(_lowercase		,						num_workers=_lowercase		,						**_lowercase )
         if isinstance(_lowercase		,						_lowercase ) and len(_lowercase ) == 1:
                return outputs[0]
         return outputs






  def 			_UpperCAmelCase  (					self      :					Optional[Any]		,						_lowercase      :					Conversation		,						_lowercase      :					List[Any]=32 ):




         """simple docstring"""







         if not isinstance(_lowercase		,						_lowercase ):
                raise ValueError("ConversationalPipeline, expects Conversation as inputs" )
         if conversation.new_user_input is None:
                raise ValueError(
                    F"""Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. """
                    "Add user inputs with the conversation's `add_user_input` method" )
         if hasattr(self.tokenizer		,						"_build_conversation_input_ids" ):
                UpperCAmelCase__										=     self.tokenizer._build_conversation_input_ids(_lowercase )
         else:
                # If the tokenizer cannot handle conversations, we default to only the old version
                UpperCAmelCase__										=     self._legacy_parse_and_tokenize(_lowercase )

         if self.framework == "pt":
                UpperCAmelCase__										=     torch.LongTensor([input_ids] )
         elif self.framework == "tf":
                UpperCAmelCase__										=     tf.constant([input_ids] )
         return {"input_ids": input_ids, "conversation": conversation}






  def 			_UpperCAmelCase  (					self      :					Optional[Any]		,						_lowercase      :					List[Any]		,						_lowercase      :					List[Any]=10		,						**_lowercase      :					Optional[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     generate_kwargs.get("max_length"		,						self.model.config.max_length )

         UpperCAmelCase__										=     model_inputs["input_ids"].shape[1]
         if max_length - minimum_tokens < n:
                logger.warning(F"""Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})""" )
                UpperCAmelCase__										=     max_length - minimum_tokens
                UpperCAmelCase__										=     model_inputs["input_ids"][:, -trim:]
                if "attention_mask" in model_inputs:
                       UpperCAmelCase__										=     model_inputs["attention_mask"][:, -trim:]
         UpperCAmelCase__										=     model_inputs.pop("conversation" )
         UpperCAmelCase__										=     max_length
         UpperCAmelCase__										=     self.model.generate(**_lowercase		,						**_lowercase )
         if self.model.config.is_encoder_decoder:
                UpperCAmelCase__										=     1
         else:
                UpperCAmelCase__										=     n
         return {"output_ids": output_ids[:, start_position:], "conversation": conversation}






  def 			_UpperCAmelCase  (					self      :					Tuple		,						_lowercase      :					Union[str, Any]		,						_lowercase      :					Optional[Any]=True ):




         """simple docstring"""







         UpperCAmelCase__										=     model_outputs["output_ids"]
         UpperCAmelCase__										=     self.tokenizer.decode(
             output_ids[0]		,						skip_special_tokens=_lowercase		,						clean_up_tokenization_spaces=_lowercase		,						)
         UpperCAmelCase__										=     model_outputs["conversation"]
         conversation.mark_processed()
         conversation.append_response(_lowercase )
         return conversation






  def 			_UpperCAmelCase  (					self      :					List[str]		,						_lowercase      :					Conversation ):




         """simple docstring"""







         UpperCAmelCase__										=     self.tokenizer.eos_token_id
         UpperCAmelCase__										=     []
         for is_user, text in conversation.iter_texts():
                if eos_token_id is not None:
                       input_ids.extend(self.tokenizer.encode(_lowercase		,						add_special_tokens=_lowercase ) + [eos_token_id] )
                else:
                       input_ids.extend(self.tokenizer.encode(_lowercase		,						add_special_tokens=_lowercase ) )

         if len(_lowercase ) > self.tokenizer.model_max_length:
                UpperCAmelCase__										=     input_ids[-self.tokenizer.model_max_length :]
         return input_ids





