




import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
		import tensorflow as tf


class 							__UpperCamelCase			( enum.Enum  ):





				'''simple docstring'''



				__a							: List[Any]										=0
				__a							: List[str]										=1
				__a							: Any										=2




@add_end_docstrings(__UpperCAmelCase  )
class 							__UpperCamelCase			( __UpperCAmelCase  ):





				'''simple docstring'''



				__a							: List[Any]										="""
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    """



				def __init__( self       , *UpperCAmelCase_       , **UpperCAmelCase_						):
											super().__init__(*UpperCAmelCase_       , **UpperCAmelCase_						)
											self.check_model_type(
											    TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == '''tf''' else MODEL_FOR_CAUSAL_LM_MAPPING						)
											if "prefix" not in self._preprocess_params:
																		# This is very specific. The logic is quite complex and needs to be done
																		# as a "default".
																		# It also defines both some preprocess_kwargs and generate_kwargs
																		# which is why we cannot put them in their respective methods.
																		lowerCAmelCase   =		None
																		if self.model.config.prefix is not None:
																									lowerCAmelCase   =		self.model.config.prefix
																		if prefix is None and self.model.__class__.__name__ in [
																		    "XLNetLMHeadModel",
																		    "TransfoXLLMHeadModel",
																		    "TFXLNetLMHeadModel",
																		    "TFTransfoXLLMHeadModel",
																		]:
																									# For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
																									lowerCAmelCase   =		self.XL_PREFIX
																		if prefix is not None:
																									# Recalculate some generate_kwargs linked to prefix.
																									lowerCAmelCase   ,     lowerCAmelCase   ,     lowerCAmelCase   =		self._sanitize_parameters(prefix=UpperCAmelCase_       , **self._forward_params						)
																									lowerCAmelCase   =		{**self._preprocess_params, **preprocess_params}
																									lowerCAmelCase   =		{**self._forward_params, **forward_params}



				def       __snake_case		( self       , UpperCAmelCase_=None       , UpperCAmelCase_=None       , UpperCAmelCase_=None       , UpperCAmelCase_=None       , UpperCAmelCase_=None       , UpperCAmelCase_=None       , UpperCAmelCase_=None       , UpperCAmelCase_=None       , **UpperCAmelCase_       , ):
											lowerCAmelCase   =		{}
											if prefix is not None:
																		lowerCAmelCase   =		prefix
											if prefix:
																		lowerCAmelCase   =		self.tokenizer(
																		    UpperCAmelCase_       , padding=UpperCAmelCase_       , add_special_tokens=UpperCAmelCase_       , return_tensors=self.framework						)
																		lowerCAmelCase   =		prefix_inputs['''input_ids'''].shape[-1]

											if handle_long_generation is not None:
																		if handle_long_generation not in {"hole"}:
																									raise ValueError(
																									    F"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"""
																									    ''' [None, \'hole\']'''						)
																		lowerCAmelCase   =		handle_long_generation

											preprocess_params.update(UpperCAmelCase_						)
											lowerCAmelCase   =		generate_kwargs

											lowerCAmelCase   =		{}
											if return_full_text is not None and return_type is None:
																		if return_text is not None:
																									raise ValueError('''`return_text` is mutually exclusive with `return_full_text`'''						)
																		if return_tensors is not None:
																									raise ValueError('''`return_full_text` is mutually exclusive with `return_tensors`'''						)
																		lowerCAmelCase   =		ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
											if return_tensors is not None and return_type is None:
																		if return_text is not None:
																									raise ValueError('''`return_text` is mutually exclusive with `return_tensors`'''						)
																		lowerCAmelCase   =		ReturnType.TENSORS
											if return_type is not None:
																		lowerCAmelCase   =		return_type
											if clean_up_tokenization_spaces is not None:
																		lowerCAmelCase   =		clean_up_tokenization_spaces

											if stop_sequence is not None:
																		lowerCAmelCase   =		self.tokenizer.encode(UpperCAmelCase_       , add_special_tokens=UpperCAmelCase_						)
																		if len(UpperCAmelCase_						) > 1:
																									warnings.warn(
																									    '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of'''
																									    ''' the stop sequence will be used as the stop sequence string in the interim.'''						)
																		lowerCAmelCase   =		stop_sequence_ids[0]

											return preprocess_params, forward_params, postprocess_params



				def       __snake_case		( self       , *UpperCAmelCase_       , **UpperCAmelCase_						):
											# Parse arguments
											if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
																		kwargs.update({'''add_space_before_punct_symbol''': True}						)

											return super()._parse_and_tokenize(*UpperCAmelCase_       , **UpperCAmelCase_						)



				def __call__( self       , UpperCAmelCase_       , **UpperCAmelCase_						):
											return super().__call__(UpperCAmelCase_       , **UpperCAmelCase_						)



				def       __snake_case		( self       , UpperCAmelCase_       , UpperCAmelCase_=""       , UpperCAmelCase_=None       , **UpperCAmelCase_						):
											lowerCAmelCase   =		self.tokenizer(
											    prefix + prompt_text       , padding=UpperCAmelCase_       , add_special_tokens=UpperCAmelCase_       , return_tensors=self.framework						)
											lowerCAmelCase   =		prompt_text

											if handle_long_generation == "hole":
																		lowerCAmelCase   =		inputs['''input_ids'''].shape[-1]
																		if "max_new_tokens" in generate_kwargs:
																									lowerCAmelCase   =		generate_kwargs['''max_new_tokens''']
																		else:
																									lowerCAmelCase   =		generate_kwargs.get('''max_length'''       , self.model.config.max_length						) - cur_len
																									if new_tokens < 0:
																																raise ValueError('''We cannot infer how many new tokens are expected'''						)
																		if cur_len + new_tokens > self.tokenizer.model_max_length:
																									lowerCAmelCase   =		self.tokenizer.model_max_length - new_tokens
																									if keep_length <= 0:
																																raise ValueError(
																																    '''We cannot use `hole` to handle this generation the number of desired tokens exceeds the'''
																																    ''' models max length'''						)

																									lowerCAmelCase   =		inputs['''input_ids'''][:, -keep_length:]
																									if "attention_mask" in inputs:
																																lowerCAmelCase   =		inputs['''attention_mask'''][:, -keep_length:]

											return inputs



				def       __snake_case		( self       , UpperCAmelCase_       , **UpperCAmelCase_						):
											lowerCAmelCase   =		model_inputs['''input_ids''']
											lowerCAmelCase   =		model_inputs.get('''attention_mask'''       , UpperCAmelCase_						)
											# Allow empty prompts
											if input_ids.shape[1] == 0:
																		lowerCAmelCase   =		None
																		lowerCAmelCase   =		None
																		lowerCAmelCase   =		1
											else:
																		lowerCAmelCase   =		input_ids.shape[0]
											lowerCAmelCase   =		model_inputs.pop('''prompt_text'''						)

											# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
											# generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
											lowerCAmelCase   =		generate_kwargs.pop('''prefix_length'''       , 0						)
											if prefix_length > 0:
																		lowerCAmelCase   =		'''max_new_tokens''' in generate_kwargs or (
																		    '''generation_config''' in generate_kwargs
																		    and generate_kwargs['''generation_config'''].max_new_tokens is not None
																		)
																		if not has_max_new_tokens:
																									lowerCAmelCase   =		generate_kwargs.get('''max_length'''						) or self.model.config.max_length
																									generate_kwargs["max_length"] += prefix_length
																		lowerCAmelCase   =		'''min_new_tokens''' in generate_kwargs or (
																		    '''generation_config''' in generate_kwargs
																		    and generate_kwargs['''generation_config'''].min_new_tokens is not None
																		)
																		if not has_min_new_tokens and "min_length" in generate_kwargs:
																									generate_kwargs["min_length"] += prefix_length

        # BS x SL
											lowerCAmelCase   =		self.model.generate(input_ids=UpperCAmelCase_       , attention_mask=UpperCAmelCase_       , **UpperCAmelCase_						)
											lowerCAmelCase   =		generated_sequence.shape[0]
											if self.framework == "pt":
																		lowerCAmelCase   =		generated_sequence.reshape(UpperCAmelCase_       , out_b // in_b       , *generated_sequence.shape[1:]						)
											elif self.framework == "tf":
																		lowerCAmelCase   =		tf.reshape(UpperCAmelCase_       , (in_b, out_b // in_b, *generated_sequence.shape[1:])						)
											return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}






				def       __snake_case		( self       , UpperCAmelCase_       , UpperCAmelCase_=ReturnType.FULL_TEXT       , UpperCAmelCase_=True						):
											lowerCAmelCase   =		model_outputs['''generated_sequence'''][0]
											lowerCAmelCase   =		model_outputs['''input_ids''']
											lowerCAmelCase   =		model_outputs['''prompt_text''']
											lowerCAmelCase   =		generated_sequence.numpy().tolist()
											lowerCAmelCase   =		[]
											for sequence in generated_sequence:
																		if return_type == ReturnType.TENSORS:
																									lowerCAmelCase   =		{'''generated_token_ids''': sequence}
																		elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
																									# Decode text
																									lowerCAmelCase   =		self.tokenizer.decode(
																									    UpperCAmelCase_       , skip_special_tokens=UpperCAmelCase_       , clean_up_tokenization_spaces=UpperCAmelCase_       , )

																									# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
																									if input_ids is None:
																																lowerCAmelCase   =		0
																									else:
																																lowerCAmelCase   =		len(
																																    self.tokenizer.decode(
																																        input_ids[0]       , skip_special_tokens=UpperCAmelCase_       , clean_up_tokenization_spaces=UpperCAmelCase_       , )						)

																									if return_type == ReturnType.FULL_TEXT:
																																lowerCAmelCase   =		prompt_text + text[prompt_length:]
																									else:
																																lowerCAmelCase   =		text[prompt_length:]

																									lowerCAmelCase   =		{'''generated_text''': all_text}
																		records.append(UpperCAmelCase_						)

											return records









import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


UpperCAmelCase_						="""hf-internal-testing/tiny-random-bert"""
UpperCAmelCase_						=os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""")
UpperCAmelCase_						="""9b8c223d42b2188cb49d29af482996f9d0f3e5a6"""


class 							__UpperCamelCase			( unittest.TestCase  ):





				'''simple docstring'''



				def       __snake_case		( self						):
											lowerCAmelCase   =		cached_file(UpperCAmelCase_       , UpperCAmelCase_						)
											# Should have downloaded the file in here
											self.assertTrue(os.path.isdir(UpperCAmelCase_						)						)
											# Cache should contain at least those three subfolders:
											for subfolder in ["blobs", "refs", "snapshots"]:
																		self.assertTrue(os.path.isdir(os.path.join(UpperCAmelCase_       , UpperCAmelCase_						)						)						)
											with open(os.path.join(UpperCAmelCase_       , '''refs'''       , '''main'''						)						) as f:
																		lowerCAmelCase   =		f.read()
											self.assertEqual(UpperCAmelCase_       , os.path.join(UpperCAmelCase_       , '''snapshots'''       , UpperCAmelCase_       , UpperCAmelCase_						)						)
											self.assertTrue(os.path.isfile(UpperCAmelCase_						)						)

											# File is cached at the same place the second time.
											lowerCAmelCase   =		cached_file(UpperCAmelCase_       , UpperCAmelCase_						)
											self.assertEqual(UpperCAmelCase_       , UpperCAmelCase_						)

											# Using a specific revision to test the full commit hash.
											lowerCAmelCase   =		cached_file(UpperCAmelCase_       , UpperCAmelCase_       , revision='''9b8c223'''						)
											self.assertEqual(UpperCAmelCase_       , os.path.join(UpperCAmelCase_       , '''snapshots'''       , UpperCAmelCase_       , UpperCAmelCase_						)						)



				def       __snake_case		( self						):
											with self.assertRaisesRegex(UpperCAmelCase_       , '''is not a valid model identifier'''						):
																		lowerCAmelCase   =		cached_file('''tiny-random-bert'''       , UpperCAmelCase_						)

											with self.assertRaisesRegex(UpperCAmelCase_       , '''is not a valid git identifier'''						):
																		lowerCAmelCase   =		cached_file(UpperCAmelCase_       , UpperCAmelCase_       , revision='''aaaa'''						)

											with self.assertRaisesRegex(UpperCAmelCase_       , '''does not appear to have a file named'''						):
																		lowerCAmelCase   =		cached_file(UpperCAmelCase_       , '''conf'''						)



				def       __snake_case		( self						):
											with self.assertRaisesRegex(UpperCAmelCase_       , '''does not appear to have a file named'''						):
																		lowerCAmelCase   =		cached_file(UpperCAmelCase_       , '''conf'''						)

											with open(os.path.join(UpperCAmelCase_       , '''refs'''       , '''main'''						)						) as f:
																		lowerCAmelCase   =		f.read()
											self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase_       , '''.no_exist'''       , UpperCAmelCase_       , '''conf'''						)						)						)

											lowerCAmelCase   =		cached_file(UpperCAmelCase_       , '''conf'''       , _raise_exceptions_for_missing_entries=UpperCAmelCase_						)
											self.assertIsNone(UpperCAmelCase_						)

											lowerCAmelCase   =		cached_file(UpperCAmelCase_       , '''conf'''       , local_files_only=UpperCAmelCase_       , _raise_exceptions_for_missing_entries=UpperCAmelCase_						)
											self.assertIsNone(UpperCAmelCase_						)

											lowerCAmelCase   =		mock.Mock()
											lowerCAmelCase   =		5_00
											lowerCAmelCase   =		{}
											lowerCAmelCase   =		HTTPError
											lowerCAmelCase   =		{}

											# Under the mock environment we get a 500 error when trying to reach the tokenizer.
											with mock.patch('''requests.Session.request'''       , return_value=UpperCAmelCase_						) as mock_head:
																		lowerCAmelCase   =		cached_file(UpperCAmelCase_       , '''conf'''       , _raise_exceptions_for_connection_errors=UpperCAmelCase_						)
																		self.assertIsNone(UpperCAmelCase_						)
																		# This check we did call the fake head request
																		mock_head.assert_called()



				def       __snake_case		( self						):
											self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only'''       , UpperCAmelCase_						)						)
											self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only'''       , UpperCAmelCase_						)						)
											self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only'''       , UpperCAmelCase_						)						)



				def       __snake_case		( self						):
											# `get_file_from_repo` returns None if the file does not exist
											self.assertIsNone(get_file_from_repo('''bert-base-cased'''       , '''ahah.txt'''						)						)

											# The function raises if the repository does not exist.
											with self.assertRaisesRegex(UpperCAmelCase_       , '''is not a valid model identifier'''						):
																		get_file_from_repo('''bert-base-case'''       , UpperCAmelCase_						)

											# The function raises if the revision does not exist.
											with self.assertRaisesRegex(UpperCAmelCase_       , '''is not a valid git identifier'''						):
																		get_file_from_repo('''bert-base-cased'''       , UpperCAmelCase_       , revision='''ahaha'''						)

											lowerCAmelCase   =		get_file_from_repo('''bert-base-cased'''       , UpperCAmelCase_						)
											# The name is the cached name which is not very easy to test, so instead we load the content.
											lowerCAmelCase   =		json.loads(open(UpperCAmelCase_       , '''r'''						).read()						)
											self.assertEqual(config['''hidden_size''']       , 7_68						)






				def       __snake_case		( self						):
											with tempfile.TemporaryDirectory() as tmp_dir:
																		lowerCAmelCase   =		Path(UpperCAmelCase_						) / '''a.txt'''
																		filename.touch()
																		self.assertEqual(get_file_from_repo(UpperCAmelCase_       , '''a.txt'''						)       , str(UpperCAmelCase_						)						)

																		self.assertIsNone(get_file_from_repo(UpperCAmelCase_       , '''b.txt'''						)						)



