





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			 =       0
 A			 =       1
 A			 =       2




@add_end_docstrings(_a		)
class 							UpperCamelCase_							(       _a		):







 """simple docstring"""

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


 def __init__(   self  ,				*UpperCAmelCase  ,				**UpperCAmelCase							):
       super().__init__(*snake_case_  ,				**snake_case_							)
       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				   =       self._sanitize_parameters(prefix=snake_case_  ,				**self._forward_params							)
                   __lowerCamelCase				   =       {**self._preprocess_params, **preprocess_params}
                   __lowerCamelCase				   =       {**self._forward_params, **forward_params}


 def 		lowerCamelCase_ (   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(
                 snake_case_  ,				padding=snake_case_  ,				add_special_tokens=snake_case_  ,				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(snake_case_							)
       __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(snake_case_  ,				add_special_tokens=snake_case_							)
             if len(snake_case_							) > 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 		lowerCamelCase_ (   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(*snake_case_  ,				**snake_case_							)


 def __call__(   self  ,				UpperCAmelCase  ,				**UpperCAmelCase							):
       return super().__call__(snake_case_  ,				**snake_case_							)


 def 		lowerCamelCase_ (   self  ,				UpperCAmelCase  ,				UpperCAmelCase=""  ,				UpperCAmelCase=None  ,				**UpperCAmelCase							):
       __lowerCamelCase				   =       self.tokenizer(
           prefix + prompt_text  ,				padding=snake_case_  ,				add_special_tokens=snake_case_  ,				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 		lowerCamelCase_ (   self  ,				UpperCAmelCase  ,				**UpperCAmelCase							):
       __lowerCamelCase				   =       model_inputs["""input_ids"""]
       __lowerCamelCase				   =       model_inputs.get("""attention_mask"""  ,				snake_case_							)
       # 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=snake_case_  ,				attention_mask=snake_case_  ,				**snake_case_							)
       __lowerCamelCase				   =       generated_sequence.shape[0]
       if self.framework == "pt":
             __lowerCamelCase				   =       generated_sequence.reshape(snake_case_  ,				out_b // in_b  ,				*generated_sequence.shape[1:]							)
       elif self.framework == "tf":
             __lowerCamelCase				   =       tf.reshape(snake_case_  ,				(in_b, out_b // in_b, *generated_sequence.shape[1:])							)
       return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}



 def 		lowerCamelCase_ (   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(
                       snake_case_  ,				skip_special_tokens=snake_case_  ,				clean_up_tokenization_spaces=snake_case_  ,				)

                   # 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=snake_case_  ,				clean_up_tokenization_spaces=snake_case_  ,				)							)

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

                   __lowerCamelCase				   =       {"""generated_text""": all_text}
             records.append(snake_case_							)

       return records











'''simple docstring'''





import os
from tempfile import TemporaryDirectory
from unittest import TestCase

import pytest
from absl.testing import parameterized

from datasets import config
from datasets.arrow_reader import HF_GCP_BASE_URL
from datasets.builder import DatasetBuilder
from datasets.dataset_dict import IterableDatasetDict
from datasets.iterable_dataset import IterableDataset
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.file_utils import cached_path


__a  			=						[
    {"dataset": "wikipedia", "config_name": "20220301.de"},
    {"dataset": "wikipedia", "config_name": "20220301.en"},
    {"dataset": "wikipedia", "config_name": "20220301.fr"},
    {"dataset": "wikipedia", "config_name": "20220301.frr"},
    {"dataset": "wikipedia", "config_name": "20220301.it"},
    {"dataset": "wikipedia", "config_name": "20220301.simple"},
    {"dataset": "snli", "config_name": "plain_text"},
    {"dataset": "eli5", "config_name": "LFQA_reddit"},
    {"dataset": "wiki40b", "config_name": "en"},
    {"dataset": "wiki_dpr", "config_name": "psgs_w100.nq.compressed"},
    {"dataset": "wiki_dpr", "config_name": "psgs_w100.nq.no_index"},
    {"dataset": "wiki_dpr", "config_name": "psgs_w100.multiset.no_index"},
    {"dataset": "natural_questions", "config_name": "default"},
]





def 		__snake_case(							_lowerCAmelCase=True						)						->					Dict:
      if with_config:
            return [
                {
                    "testcase_name": d["dataset"] + "/" + d["config_name"],
                    "dataset": d["dataset"],
                    "config_name": d["config_name"],
                }
                for d in DATASETS_ON_HF_GCP
            ]
      else:
            return [
                {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP}
            ]







@parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=_a      )      )
class        UpperCAmelCase_			(			_a      ):
    """simple docstring"""







    lowercase   =						None
    lowercase   =						None




    def lowerCamelCase			(       self   :	List[Any]					,	snake_case_   :	Union[str, Any]					,	snake_case_   :	Optional[int]		):
          with TemporaryDirectory() as tmp_dir:
                snake_case__    :       Dict       		= dataset_module_factory(snake_case_					,	cache_dir=snake_case_		)

                snake_case__    :       Optional[int]       		= import_main_class(dataset_module.module_path					,	dataset=snake_case_		)

                snake_case__    :       DatasetBuilder       		= builder_cls(
                    cache_dir=snake_case_					,	config_name=snake_case_					,	hash=dataset_module.hash					,	)

                snake_case__    :       Dict       		= """/""".join(
                    [
                        HF_GCP_BASE_URL,
                        builder_instance._relative_data_dir(with_hash=snake_case_		).replace(os.sep					,	"""/"""		),
                        config.DATASET_INFO_FILENAME,
                    ]		)
                snake_case__    :       List[str]       		= cached_path(snake_case_					,	cache_dir=snake_case_		)
                self.assertTrue(os.path.exists(snake_case_		)		)





@pytest.mark.integration
def 		__snake_case(							_lowerCAmelCase						)						->					Tuple:
      snake_case__    :       Optional[int]       		= tmp_path_factory.mktemp("""test_hf_gcp"""						) / """test_wikipedia_simple"""
      snake_case__    :       Dict       		= dataset_module_factory("""wikipedia"""	,  cache_dir=_lowerCAmelCase						)
      snake_case__    :       Dict       		= import_main_class(dataset_module.module_path						)
      snake_case__    :       DatasetBuilder       		= builder_cls(
          cache_dir=_lowerCAmelCase	,  config_name="""20220301.frr"""	,  hash=dataset_module.hash	,  )
      # use the HF cloud storage, not the original download_and_prepare that uses apache-beam
      snake_case__    :       Any       		= None
      builder_instance.download_and_prepare()
      snake_case__    :       Union[str, Any]       		= builder_instance.as_dataset()
      assert ds





@pytest.mark.integration
def 		__snake_case(							_lowerCAmelCase						)						->					List[str]:
      snake_case__    :       Optional[int]       		= dataset_module_factory("""wikipedia"""	,  cache_dir=_lowerCAmelCase						)
      snake_case__    :       List[str]       		= import_main_class(dataset_module.module_path	,  dataset=_lowerCAmelCase						)
      snake_case__    :       DatasetBuilder       		= builder_cls(
          cache_dir=_lowerCAmelCase	,  config_name="""20220301.frr"""	,  hash=dataset_module.hash	,  )
      snake_case__    :       Any       		= builder_instance.as_streaming_dataset()
      assert ds
      assert isinstance(_lowerCAmelCase	,  _lowerCAmelCase						)
      assert "train" in ds
      assert isinstance(ds["""train"""]	,  _lowerCAmelCase						)
      assert next(iter(ds["""train"""]						)						)
