

# Copyright 2021 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 packaging import version

from .. import __version__
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from .doc import (
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    copy_func,
    replace_return_docstrings,
)
from .generic import (
    ContextManagers,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    TensorType,
    add_model_info_to_auto_map,
    cached_property,
    can_return_loss,
    expand_dims,
    find_labels,
    flatten_dict,
    infer_framework,
    is_jax_tensor,
    is_numpy_array,
    is_tensor,
    is_tf_symbolic_tensor,
    is_tf_tensor,
    is_torch_device,
    is_torch_dtype,
    is_torch_tensor,
    reshape,
    squeeze,
    strtobool,
    tensor_size,
    to_numpy,
    to_py_obj,
    transpose,
    working_or_temp_dir,
)
from .hub import (
    CLOUDFRONT_DISTRIB_PREFIX,
    DISABLE_TELEMETRY,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    EntryNotFoundError,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    cached_file,
    default_cache_path,
    define_sagemaker_information,
    download_url,
    extract_commit_hash,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    has_file,
    http_user_agent,
    is_offline_mode,
    is_remote_url,
    move_cache,
    send_example_telemetry,
    try_to_load_from_cache,
)
from .import_utils import (
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    TORCH_FX_REQUIRED_VERSION,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    _LazyModule,
    ccl_version,
    direct_transformers_import,
    get_torch_version,
    is_accelerate_available,
    is_apex_available,
    is_bitsandbytes_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_cython_available,
    is_datasets_available,
    is_decord_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_jieba_available,
    is_jumanpp_available,
    is_kenlm_available,
    is_keras_nlp_available,
    is_librosa_available,
    is_natten_available,
    is_ninja_available,
    is_onnx_available,
    is_openai_available,
    is_optimum_available,
    is_pandas_available,
    is_peft_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytest_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sacremoses_available,
    is_safetensors_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_sudachi_available,
    is_tensorflow_probability_available,
    is_tensorflow_text_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_bfaa_cpu_available,
    is_torch_bfaa_gpu_available,
    is_torch_compile_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_neuroncore_available,
    is_torch_tensorrt_fx_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_torchdistx_available,
    is_torchdynamo_available,
    is_torchvision_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    requires_backends,
    torch_only_method,
)


A_       : Tuple         =			'pytorch_model.bin'
A_       : List[str]         =			'pytorch_model.bin.index.json'
A_       : Any         =			'adapter_config.json'
A_       : Union[str, Any]         =			'adapter_model.bin'
A_       : List[Any]         =			'adapter_model.safetensors'
A_       : int         =			'tf_model.h5'
A_       : Tuple         =			'tf_model.h5.index.json'
A_       : List[str]         =			'model.ckpt'
A_       : Optional[Any]         =			'flax_model.msgpack'
A_       : Any         =			'flax_model.msgpack.index.json'
A_       : Tuple         =			'model.safetensors'
A_       : List[str]         =			'model.safetensors.index.json'
A_       : List[Any]         =			'config.json'
A_       : Any         =			'preprocessor_config.json'
A_       : Any         =			FEATURE_EXTRACTOR_NAME
A_       : Optional[int]         =			'generation_config.json'
A_       : Dict         =			'modelcard.json'

A_       : Tuple         =			'▁'
A_       : List[str]         =			SENTENCEPIECE_UNDERLINE  # Kept for backward compatibility

A_       : Optional[int]         =			[
    [[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2  # Needs to have 0s and 1s only since XLM uses it for langs too.
A_       : Dict         =			[[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
A_       : int         =			[[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]

def 						UpperCamelCase					(lowercase_: List[str]					)     ->      Optional[Any]:
	if version.parse(lowercase_					) < version.parse(lowercase_					):
		if "dev" in min_version:
			A__							:    List[str]        =		(
			    """This example requires a source install from HuggingFace Transformers (see """
			    """`https://huggingface.co/docs/transformers/installation#install-from-source`),"""
			)
		else:
			A__							:    str        =		f"""This example requires a minimum version of {min_version},"""
		error_message += f""" but the version found is {__version__}.\n"""
		raise ImportError(
		    error_message
		    + """Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other """
		    """versions of HuggingFace Transformers."""					)






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_       : List[Any]         =			logging.get_logger(__name__)



class     _a						:


					'''simple docstring'''






					def __init__( self    ,       A__ = None    ,       A__ = None    ,       A__=None    ,       A__=None			):
						if not conversation_id:
							A__							:    List[Any]        =		uuid.uuida()
						if past_user_inputs is None:
							A__							:    Dict        =		[]
						if generated_responses is None:
							A__							:    int        =		[]

						A__							:    uuid.UUID        =		conversation_id
						A__							:    List[str]        =		past_user_inputs
						A__							:    List[str]        =		generated_responses
						A__							:    Optional[str]        =		text






					def __eq__( self    ,       A__			):
						if not isinstance(A__    ,       A__			):
							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   __A			( self    ,       A__    ,       A__ = False			):
						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}\"."""			)
								A__							:    str        =		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:
							A__							:    Tuple        =		text






					def   __A			( self			):
						if self.new_user_input:
							self.past_user_inputs.append(self.new_user_input			)
						A__							:    Tuple        =		None






					def   __A			( self    ,       A__			):
						self.generated_responses.append(A__			)






					def   __A			( self			):
						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			):
						A__							:    Optional[Any]        =		F"""Conversation id: {self.uuid} \n"""
						for is_user, text in self.iter_texts():
							A__							:    str        =		"""user""" if is_user else """bot"""
							output += F"""{name} >> {text} \n"""
						return output



@add_end_docstrings(
    __magic_name__		,   r'''
        min_length_for_response (`int`, *optional*, defaults to 32):
            The minimum length (in number of tokens) for a response.
        minimum_tokens (`int`, *optional*, defaults to 10):
            The minimum length of tokens to leave for a response.
    '''		,   )
class     _a						(__magic_name__				):


					'''simple docstring'''






					def __init__( self    ,       *A__    ,       **A__			):
						super().__init__(*A__    ,       **A__			)
						if self.tokenizer.pad_token_id is None:
							A__							:    Tuple        =		self.tokenizer.eos_token






					def   __A			( self    ,       A__=None    ,       A__=None    ,       A__=None    ,       **A__			):
						A__							:    Tuple        =		{}
						A__							:    List[str]        =		{}
						A__							:    Union[str, Any]        =		{}

						if min_length_for_response is not None:
							A__							:    str        =		min_length_for_response
						if minimum_tokens is not None:
							A__							:    List[str]        =		minimum_tokens

						if "max_length" in generate_kwargs:
							A__							:    List[Any]        =		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:
							A__							:    Optional[int]        =		clean_up_tokenization_spaces

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






					def __call__( self    ,       A__    ,       A__=0    ,       **A__			):
						A__							:    Optional[Any]        =		super().__call__(A__    ,       num_workers=A__    ,       **A__			)
						if isinstance(A__    ,       A__			) and len(A__			) == 1:
							return outputs[0]
						return outputs






					def   __A			( self    ,       A__    ,       A__=32			):
						if not isinstance(A__    ,       A__			):
							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"""			):
							A__							:    List[str]        =		self.tokenizer._build_conversation_input_ids(A__			)
						else:
							# If the tokenizer cannot handle conversations, we default to only the old version
							A__							:    Tuple        =		self._legacy_parse_and_tokenize(A__			)

						if self.framework == "pt":
							A__							:    List[str]        =		torch.LongTensor([input_ids]			)
						elif self.framework == "tf":
							A__							:    Optional[Any]        =		tf.constant([input_ids]			)
						return {"input_ids": input_ids, "conversation": conversation}






					def   __A			( self    ,       A__    ,       A__=10    ,       **A__			):
						A__							:    List[Any]        =		generate_kwargs.get("""max_length"""    ,       self.model.config.max_length			)

						A__							:    Optional[int]        =		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})"""			)
							A__							:    Dict        =		max_length - minimum_tokens
							A__							:    Optional[int]        =		model_inputs["""input_ids"""][:, -trim:]
							if "attention_mask" in model_inputs:
								A__							:    str        =		model_inputs["""attention_mask"""][:, -trim:]
						A__							:    List[str]        =		model_inputs.pop("""conversation"""			)
						A__							:    Dict        =		max_length
						A__							:    str        =		self.model.generate(**A__    ,       **A__			)
						if self.model.config.is_encoder_decoder:
							A__							:    Union[str, Any]        =		1
						else:
							A__							:    Optional[Any]        =		n
						return {"output_ids": output_ids[:, start_position:], "conversation": conversation}






					def   __A			( self    ,       A__    ,       A__=True			):
						A__							:    Dict        =		model_outputs["""output_ids"""]
						A__							:    str        =		self.tokenizer.decode(
						    output_ids[0]    ,       skip_special_tokens=A__    ,       clean_up_tokenization_spaces=A__    ,       )
						A__							:    Optional[int]        =		model_outputs["""conversation"""]
						conversation.mark_processed()
						conversation.append_response(A__			)
						return conversation






					def   __A			( self    ,       A__			):
						A__							:    str        =		self.tokenizer.eos_token_id
						A__							:    Tuple        =		[]
						for is_user, text in conversation.iter_texts():
							if eos_token_id is not None:
								input_ids.extend(self.tokenizer.encode(A__    ,       add_special_tokens=A__			) + [eos_token_id]			)
							else:
								input_ids.extend(self.tokenizer.encode(A__    ,       add_special_tokens=A__			)			)

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



