



import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""",
    datefmt="""%m/%d/%Y %H:%M:%S""",
    level=logging.INFO,
)
__SCREAMING_SNAKE_CASE     =	logging.getLogger(__name__)

__SCREAMING_SNAKE_CASE     =	int(10000)  # Hardcoded max length to avoid infinite loop

__SCREAMING_SNAKE_CASE     =	{
    """gpt2""": (GPTaLMHeadModel, GPTaTokenizer),
    """ctrl""": (CTRLLMHeadModel, CTRLTokenizer),
    """openai-gpt""": (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    """xlnet""": (XLNetLMHeadModel, XLNetTokenizer),
    """transfo-xl""": (TransfoXLLMHeadModel, TransfoXLTokenizer),
    """xlm""": (XLMWithLMHeadModel, XLMTokenizer),
    """gptj""": (GPTJForCausalLM, AutoTokenizer),
    """bloom""": (BloomForCausalLM, BloomTokenizerFast),
    """llama""": (LlamaForCausalLM, LlamaTokenizer),
    """opt""": (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
__SCREAMING_SNAKE_CASE     =	"""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 						UpperCAmelCase (    _lowerCamelCase     ):
			np.random.seed(args.seed     )
			torch.manual_seed(args.seed     )
			if args.n_gpu > 0:
						torch.cuda.manual_seed_all(args.seed     )




def 						UpperCAmelCase (    _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase     ):
			if args.temperature > 0.7:
						logger.info("CTRL typically works better with lower temperatures (and lower top_k)."     )

			A				:       Union[str, Any]														=    tokenizer.encode(_lowerCamelCase			,     add_special_tokens=_lowerCamelCase     )
			if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()     ):
						logger.info("WARNING! You are not starting your generation from a control code so you won't get good results"     )
			return prompt_text




def 						UpperCAmelCase (    _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase     ):
			# kwargs = {"language": None, "mask_token_id": None}

			# Set the language
			A				:       Optional[int]														=    hasattr(model.config			,     "use_lang_emb"     ) and model.config.use_lang_emb
			if hasattr(model.config			,     "lang2id"     ) and use_lang_emb:
						A				:       Dict														=    model.config.langaid.keys()
						if args.xlm_language in available_languages:
									A				:       Tuple														=    args.xlm_language
						else:
									A				:       Tuple														=    None
									while language not in available_languages:
												A				:       int														=    input("Using XLM. Select language in " + str(list(_lowerCamelCase     )     ) + " >>> "     )

						A				:       Optional[Any]														=    model.config.langaid[language]
						# kwargs["language"] = tokenizer.lang2id[language]

			# TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
			# XLM masked-language modeling (MLM) models need masked token
			# is_xlm_mlm = "mlm" in args.model_name_or_path
			# if is_xlm_mlm:
			#     kwargs["mask_token_id"] = tokenizer.mask_token_id

			return prompt_text




def 						UpperCAmelCase (    _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase     ):
			A				:       Any														=    args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
			A				:       Optional[int]														=    prefix + prompt_text
			return prompt_text




def 						UpperCAmelCase (    _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase     ):
			A				:       List[Any]														=    args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
			A				:       int														=    prefix + prompt_text
			return prompt_text


__SCREAMING_SNAKE_CASE     =	{
    """ctrl""": prepare_ctrl_input,
    """xlm""": prepare_xlm_input,
    """xlnet""": prepare_xlnet_input,
    """transfo-xl""": prepare_transfoxl_input,
}




def 						UpperCAmelCase (    _lowerCamelCase			,     _lowerCamelCase     ):
			if length < 0 and max_sequence_length > 0:
						A				:       Union[str, Any]														=    max_sequence_length
			elif 0 < max_sequence_length < length:
						A				:       Optional[int]														=    max_sequence_length  # No generation bigger than model size
			elif length < 0:
						A				:       Optional[Any]														=    MAX_LENGTH  # avoid infinite loop
			return length




def 						UpperCAmelCase (    _lowerCamelCase     ):
			A				:       str														=    None
			if hasattr(_lowerCamelCase			,     "hidden_size"     ):
						A				:       Optional[Any]														=    model_config.hidden_size
			elif hasattr(_lowerCamelCase			,     "n_embed"     ):
						A				:       List[Any]														=    model_config.n_embed
			elif hasattr(_lowerCamelCase			,     "n_embd"     ):
						A				:       List[Any]														=    model_config.n_embd

			A				:       Any														=    None
			if hasattr(_lowerCamelCase			,     "num_attention_heads"     ):
						A				:       Dict														=    model_config.num_attention_heads
			elif hasattr(_lowerCamelCase			,     "n_head"     ):
						A				:       Optional[int]														=    model_config.n_head

			if embedding_size is None or num_head is None or num_head == 0:
						raise ValueError("Check the model config"     )

			A				:       Optional[int]														=    int(embedding_size / num_head     )
			if hasattr(_lowerCamelCase			,     "n_layer"     ):
						A				:       List[Any]														=    model_config.n_layer
			elif hasattr(_lowerCamelCase			,     "num_hidden_layers"     ):
						A				:       Union[str, Any]														=    model_config.num_hidden_layers
			else:
						raise ValueError("Number of hidden layers couldn't be determined from the model config"     )

			return num_layer, num_head, num_embedding_size_per_head




def 						UpperCAmelCase (    _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase     ):
			A							,			A							,			A				:       Any														=    sparse_model_config(model.config     )
			if model.config.model_type == "bloom":
						A				:       Tuple														=    tuple(
						    (
						        torch.empty(int(num_attention_heads * batch_size     )			,     _lowerCamelCase			,     _lowerCamelCase     )
						        .to(model.dtype     )
						        .to(model.device     ),
						        torch.empty(int(num_attention_heads * batch_size     )			,     _lowerCamelCase			,     _lowerCamelCase     )
						        .to(model.dtype     )
						        .to(model.device     ),
						    )
						    for _ in range(_lowerCamelCase     )     )
			else:
						A				:       Optional[int]														=    tuple(
						    (
						        torch.empty(_lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase     )
						        .to(model.dtype     )
						        .to(model.device     ),
						        torch.empty(_lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase     )
						        .to(model.dtype     )
						        .to(model.device     ),
						    )
						    for _ in range(_lowerCamelCase     )     )
			return past_key_values




def 						UpperCAmelCase (    _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase     ):
			A				:       Optional[int]														=    len(_lowerCamelCase     )
			A				:       List[Any]														=    tokenizer.batch_encode_plus(_lowerCamelCase			,     return_tensors="pt"     )
			A				:       Dict														=    dummy_input.to(model.device     )
			if model.config.use_cache:
						A				:       str														=    generate_past_key_values(_lowerCamelCase			,     _lowerCamelCase			,     1     )
			A				:       Optional[Any]														=    torch.cat(
			    [
			        torch.zeros(dummy_input["attention_mask"].shape[0]			,     1     )
			        .to(dummy_input["attention_mask"].dtype     )
			        .to(model.device     ),
			        dummy_input["attention_mask"],
			    ]			,     -1			,     )
			return dummy_input

class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''
						a__ =	("_optimized", "_default")







						def __init__(						self   :      List[Any]						,						__lowerCamelCase   :      Optional[Any]						,						__lowerCamelCase   :      Optional[int]			)   ->					Optional[int]:
									A				:       Dict														=    optimized
									A				:       str														=    default







						def __call__(						self   :      Optional[int]						,						*__lowerCamelCase   :      Optional[int]						,						**__lowerCamelCase   :      str			)   ->					Tuple:
									if kwargs["past_key_values"] is None and self._default.config.use_cache:
												A				:       List[str]														=    generate_past_key_values(self._default						,						kwargs["input_ids"].shape[0]						,						0			)
									kwargs.pop("position_ids"						,						__lowerCamelCase			)
									for k in list(kwargs.keys()			):
												if kwargs[k] is None or isinstance(kwargs[k]						,						__lowerCamelCase			):
															kwargs.pop(__lowerCamelCase			)
									A				:       str														=    self._optimized(**__lowerCamelCase			)
									A				:       int														=    outputs[0]
									A				:       List[Any]														=    outputs[1]
									A				:       Optional[Any]														=    CausalLMOutputWithPast(
									    loss=__lowerCamelCase						,						logits=__lowerCamelCase						,						past_key_values=__lowerCamelCase						,						hidden_states=__lowerCamelCase						,						attentions=__lowerCamelCase						,						)
									return fixed_output







						def __getattr__(						self   :      Optional[int]						,						__lowerCamelCase   :      List[str]			)   ->					Tuple:
									return getattr(self._default						,						__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]						,						__lowerCamelCase   :      Tuple						,						__lowerCamelCase   :      Dict=None						,						__lowerCamelCase   :      List[str]=None						,						__lowerCamelCase   :      Dict=None						,						**__lowerCamelCase   :      str			)   ->					int:
									return self._default.prepare_inputs_for_generation(
									    __lowerCamelCase						,						past_key_values=__lowerCamelCase						,						inputs_embeds=__lowerCamelCase						,						use_cache=__lowerCamelCase						,						**__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[str]						,						__lowerCamelCase   :      Tuple[Tuple[torch.Tensor]]						,						__lowerCamelCase   :      torch.Tensor			)   ->					Tuple[Tuple[torch.Tensor]]:
									return self._default._reorder_cache(__lowerCamelCase						,						__lowerCamelCase			)







def 						UpperCAmelCase (    ):
			A				:       Union[str, Any]														=    argparse.ArgumentParser()
			parser.add_argument(
			    "--model_type"			,     default=_lowerCamelCase			,     type=_lowerCamelCase			,     required=_lowerCamelCase			,     help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()     )			,     )
			parser.add_argument(
			    "--model_name_or_path"			,     default=_lowerCamelCase			,     type=_lowerCamelCase			,     required=_lowerCamelCase			,     help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(MODEL_CLASSES.keys()     )			,     )

			parser.add_argument("--prompt"			,     type=_lowerCamelCase			,     default=""     )
			parser.add_argument("--length"			,     type=_lowerCamelCase			,     default=20     )
			parser.add_argument("--stop_token"			,     type=_lowerCamelCase			,     default=_lowerCamelCase			,     help="Token at which text generation is stopped"     )

			parser.add_argument(
			    "--temperature"			,     type=_lowerCamelCase			,     default=1.0			,     help="temperature of 1.0 has no effect, lower tend toward greedy sampling"			,     )
			parser.add_argument(
			    "--repetition_penalty"			,     type=_lowerCamelCase			,     default=1.0			,     help="primarily useful for CTRL model; in that case, use 1.2"     )
			parser.add_argument("--k"			,     type=_lowerCamelCase			,     default=0     )
			parser.add_argument("--p"			,     type=_lowerCamelCase			,     default=0.9     )

			parser.add_argument("--prefix"			,     type=_lowerCamelCase			,     default=""			,     help="Text added prior to input."     )
			parser.add_argument("--padding_text"			,     type=_lowerCamelCase			,     default=""			,     help="Deprecated, the use of `--prefix` is preferred."     )
			parser.add_argument("--xlm_language"			,     type=_lowerCamelCase			,     default=""			,     help="Optional language when used with the XLM model."     )

			parser.add_argument("--seed"			,     type=_lowerCamelCase			,     default=42			,     help="random seed for initialization"     )
			parser.add_argument("--no_cuda"			,     action="store_true"			,     help="Avoid using CUDA when available"     )
			parser.add_argument("--num_return_sequences"			,     type=_lowerCamelCase			,     default=1			,     help="The number of samples to generate."     )
			parser.add_argument(
			    "--fp16"			,     action="store_true"			,     help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit"			,     )
			parser.add_argument("--jit"			,     action="store_true"			,     help="Whether or not to use jit trace to accelerate inference"     )
			A				:       Optional[int]														=    parser.parse_args()

			A				:       Union[str, Any]														=    torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu"     )
			A				:       Optional[Any]														=    0 if args.no_cuda else torch.cuda.device_count()

			logger.warning(f"""device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}"""     )

			set_seed(_lowerCamelCase     )

			# Initialize the model and tokenizer
			try:
						A				:       List[Any]														=    args.model_type.lower()
						A							,			A				:       int														=    MODEL_CLASSES[args.model_type]
			except KeyError:
						raise KeyError("the model {} you specified is not supported. You are welcome to add it and open a PR :)"     )

			A				:       Tuple														=    tokenizer_class.from_pretrained(args.model_name_or_path     )
			if tokenizer.pad_token is None:
						A				:       str														=    tokenizer.eos_token
			A				:       Dict														=    model_class.from_pretrained(args.model_name_or_path     )
			model.to(args.device     )

			if args.fpaa:
						model.half()
			A				:       Optional[Any]														=    getattr(model.config			,     "max_position_embeddings"			,     0     )
			A				:       Optional[Any]														=    adjust_length_to_model(args.length			,     max_sequence_length=_lowerCamelCase     )
			logger.info(_lowerCamelCase     )

			A				:       Union[str, Any]														=    args.prompt if args.prompt else input("Model prompt >>> "     )

			# Different models need different input formatting and/or extra arguments
			A				:       List[Any]														=    args.model_type in PREPROCESSING_FUNCTIONS.keys()
			if requires_preprocessing:
						A				:       Optional[int]														=    PREPROCESSING_FUNCTIONS.get(args.model_type     )
						A				:       int														=    prepare_input(_lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase     )

						if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
									A				:       List[str]														=    {"add_space_before_punct_symbol": True}
						else:
									A				:       Tuple														=    {}

						A				:       int														=    tokenizer.encode(
						    _lowerCamelCase			,     add_special_tokens=_lowerCamelCase			,     return_tensors="pt"			,     **_lowerCamelCase     )
			else:
						A				:       Any														=    args.prefix if args.prefix else args.padding_text
						A				:       Optional[int]														=    tokenizer.encode(prefix + prompt_text			,     add_special_tokens=_lowerCamelCase			,     return_tensors="pt"     )
			A				:       Union[str, Any]														=    encoded_prompt.to(args.device     )

			if encoded_prompt.size()[-1] == 0:
						A				:       int														=    None
			else:
						A				:       int														=    encoded_prompt

			if args.jit:
						A				:       Dict														=    ["enable jit"]
						A				:       Any														=    prepare_jit_inputs(_lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase     )
						torch._C._jit_set_texpr_fuser_enabled(_lowerCamelCase     )
						A				:       Tuple														=    False
						if hasattr(_lowerCamelCase			,     "forward"     ):
									A				:       int														=    inspect.signature(model.forward     )
						else:
									A				:       int														=    inspect.signature(model.__call__     )
						A				:       str														=    tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(_lowerCamelCase			,     _lowerCamelCase     ) is not None     )
						A				:       str														=    torch.jit.trace(_lowerCamelCase			,     _lowerCamelCase			,     strict=_lowerCamelCase     )
						A				:       Optional[int]														=    torch.jit.freeze(traced_model.eval()     )
						traced_model(*_lowerCamelCase     )
						traced_model(*_lowerCamelCase     )

						A				:       Tuple														=    _ModelFallbackWrapper(_lowerCamelCase			,     _lowerCamelCase     )

			A				:       Tuple														=    model.generate(
			    input_ids=_lowerCamelCase			,     max_length=args.length + len(encoded_prompt[0]     )			,     temperature=args.temperature			,     top_k=args.k			,     top_p=args.p			,     repetition_penalty=args.repetition_penalty			,     do_sample=_lowerCamelCase			,     num_return_sequences=args.num_return_sequences			,     )

			# Remove the batch dimension when returning multiple sequences
			if len(output_sequences.shape     ) > 2:
						output_sequences.squeeze_()

			A				:       Union[str, Any]														=    []

			for generated_sequence_idx, generated_sequence in enumerate(_lowerCamelCase     ):
						print(f"""=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==="""     )
						A				:       Optional[Any]														=    generated_sequence.tolist()

						# Decode text
						A				:       List[str]														=    tokenizer.decode(_lowerCamelCase			,     clean_up_tokenization_spaces=_lowerCamelCase     )

						# Remove all text after the stop token
						A				:       int														=    text[: text.find(args.stop_token     ) if args.stop_token else None]

						# Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
						A				:       str														=    (
						    prompt_text + text[len(tokenizer.decode(encoded_prompt[0]			,     clean_up_tokenization_spaces=_lowerCamelCase     )     ) :]
						)

						generated_sequences.append(_lowerCamelCase     )
						print(_lowerCamelCase     )

			return generated_sequences


if __name__ == "__main__":
							main()




from copy import deepcopy
from unittest.case import TestCase

import pytest

from datasets.arrow_dataset import Dataset
from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value
from datasets.info import DatasetInfo
from datasets.tasks import (
    AudioClassification,
    AutomaticSpeechRecognition,
    ImageClassification,
    LanguageModeling,
    QuestionAnsweringExtractive,
    Summarization,
    TextClassification,
    task_template_from_dict,
)
from datasets.utils.py_utils import asdict


__SCREAMING_SNAKE_CASE     =	{
    """id""": """5733be284776f41900661182""",
    """title""": """University_of_Notre_Dame""",
    """context""": """Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend \"Venite Ad Me Omnes\". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.""",
    """question""": """To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?""",
    """answers""": {"""text""": ["""Saint Bernadette Soubirous"""], """answer_start""": [515]},
}




@pytest.mark.parametrize(
    "task_cls"			,     [
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]			,     )
def 						UpperCAmelCase (    _lowerCamelCase     ):
			A				:       Optional[int]														=    task_cls()
			A				:       int														=    asdict(_lowerCamelCase     )
			A				:       int														=    task_template_from_dict(_lowerCamelCase     )
			assert task == reloaded

class 						lowerCamelCase_     :






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      Union[str, Any]			)   ->					Any:
									A				:       str														=    LanguageModeling(text_column="input_text"			)
									assert {"input_text": "text"} == task.column_mapping







						def       SCREAMING_SNAKE_CASE__		(						self   :      Any			)   ->					str:
									A				:       Tuple														=    Features({"text": Value("string"			)}			)
									A				:       Dict														=    {"text_column": "input_text"}
									A				:       Optional[int]														=    LanguageModeling.from_dict(__lowerCamelCase			)
									assert "language-modeling" == task.task
									assert input_schema == task.input_schema







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]			)   ->					str:
									A				:       List[Any]														=    sorted(["pos", "neg"]			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      str			)   ->					Optional[int]:
									A				:       List[Any]														=    TextClassification(text_column="input_text"						,						label_column="input_label"			)
									self.assertDictEqual({"input_text": "text", "input_label": "labels"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Dict			)   ->					Optional[int]:
									A				:       Tuple														=    Features({"text": Value("string"			)}			)
									# Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
									A				:       str														=    Features({"labels": ClassLabel}			)
									A				:       List[Any]														=    {"text_column": "input_text", "label_column": "input_labels"}
									A				:       Any														=    TextClassification.from_dict(__lowerCamelCase			)
									self.assertEqual("text-classification"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple			)   ->					int:
									A				:       Dict														=    TextClassification(text_column="input_text"						,						label_column="input_label"			)
									self.assertEqual(task.label_schema["labels"]						,						__lowerCamelCase			)
									A				:       Any														=    task.align_with_features(Features({"input_label": ClassLabel(names=self.labels			)}			)			)
									self.assertEqual(task.label_schema["labels"]						,						ClassLabel(names=self.labels			)			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      str			)   ->					Dict:
									A				:       Optional[int]														=    QuestionAnsweringExtractive(
									    context_column="input_context"						,						question_column="input_question"						,						answers_column="input_answers"			)
									self.assertDictEqual(
									    {"input_context": "context", "input_question": "question", "input_answers": "answers"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[int]			)   ->					Tuple:
									A				:       Dict														=    Features({"question": Value("string"			), "context": Value("string"			)}			)
									A				:       int														=    Features(
									    {
									        "answers": Sequence(
									            {
									                "text": Value("string"			),
									                "answer_start": Value("int32"			),
									            }			)
									    }			)
									A				:       Optional[int]														=    {
									    "context_column": "input_input_context",
									    "question_column": "input_question",
									    "answers_column": "input_answers",
									}
									A				:       Tuple														=    QuestionAnsweringExtractive.from_dict(__lowerCamelCase			)
									self.assertEqual("question-answering-extractive"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[Any]			)   ->					Tuple:
									A				:       Optional[Any]														=    Summarization(text_column="input_text"						,						summary_column="input_summary"			)
									self.assertDictEqual({"input_text": "text", "input_summary": "summary"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]			)   ->					Any:
									A				:       Union[str, Any]														=    Features({"text": Value("string"			)}			)
									A				:       Tuple														=    Features({"summary": Value("string"			)}			)
									A				:       Optional[Any]														=    {"text_column": "input_text", "summary_column": "input_summary"}
									A				:       str														=    Summarization.from_dict(__lowerCamelCase			)
									self.assertEqual("summarization"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      Union[str, Any]			)   ->					Any:
									A				:       Union[str, Any]														=    AutomaticSpeechRecognition(audio_column="input_audio"						,						transcription_column="input_transcription"			)
									self.assertDictEqual({"input_audio": "audio", "input_transcription": "transcription"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]			)   ->					str:
									A				:       Tuple														=    Features({"audio": Audio()}			)
									A				:       Any														=    Features({"transcription": Value("string"			)}			)
									A				:       List[str]														=    {
									    "audio_column": "input_audio",
									    "transcription_column": "input_transcription",
									}
									A				:       Dict														=    AutomaticSpeechRecognition.from_dict(__lowerCamelCase			)
									self.assertEqual("automatic-speech-recognition"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]			)   ->					Tuple:
									A				:       Optional[Any]														=    sorted(["pos", "neg"]			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[Any]			)   ->					Union[str, Any]:
									A				:       Optional[int]														=    AudioClassification(audio_column="input_audio"						,						label_column="input_label"			)
									self.assertDictEqual({"input_audio": "audio", "input_label": "labels"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple			)   ->					Tuple:
									A				:       Union[str, Any]														=    Features({"audio": Audio()}			)
									A				:       Dict														=    Features({"labels": ClassLabel}			)
									A				:       Tuple														=    {
									    "audio_column": "input_image",
									    "label_column": "input_label",
									}
									A				:       Any														=    AudioClassification.from_dict(__lowerCamelCase			)
									self.assertEqual("audio-classification"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple			)   ->					Any:
									A				:       str														=    AudioClassification(audio_column="input_audio"						,						label_column="input_label"			)
									self.assertEqual(task.label_schema["labels"]						,						__lowerCamelCase			)
									A				:       List[str]														=    task.align_with_features(Features({"input_label": ClassLabel(names=self.labels			)}			)			)
									self.assertEqual(task.label_schema["labels"]						,						ClassLabel(names=self.labels			)			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[str]			)   ->					Optional[int]:
									A				:       int														=    sorted(["pos", "neg"]			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple			)   ->					int:
									A				:       List[Any]														=    ImageClassification(image_column="input_image"						,						label_column="input_label"			)
									self.assertDictEqual({"input_image": "image", "input_label": "labels"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Any			)   ->					int:
									A				:       Optional[int]														=    Features({"image": Image()}			)
									A				:       str														=    Features({"labels": ClassLabel}			)
									A				:       List[str]														=    {
									    "image_column": "input_image",
									    "label_column": "input_label",
									}
									A				:       Tuple														=    ImageClassification.from_dict(__lowerCamelCase			)
									self.assertEqual("image-classification"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Union[str, Any]			)   ->					Tuple:
									A				:       str														=    ImageClassification(image_column="input_image"						,						label_column="input_label"			)
									self.assertEqual(task.label_schema["labels"]						,						__lowerCamelCase			)
									A				:       Optional[Any]														=    task.align_with_features(Features({"input_label": ClassLabel(names=self.labels			)}			)			)
									self.assertEqual(task.label_schema["labels"]						,						ClassLabel(names=self.labels			)			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[Any]			)   ->					Optional[int]:
									A				:       Dict														=    DatasetInfo(task_templates=QuestionAnsweringExtractive()			)
									A				:       List[Any]														=    Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}						,						info=__lowerCamelCase			)
									assert isinstance(dataset.info.task_templates						,						__lowerCamelCase			)
									assert len(dataset.info.task_templates			) == 1

									def keep_task(__lowerCamelCase   :      List[str]			):
												return x

									def dont_keep_task(__lowerCamelCase   :      Any			):
												A				:       Optional[Any]														=    deepcopy(__lowerCamelCase			)
												A				:       List[Any]														=    0
												return out

									A				:       Optional[int]														=    dataset.map(__lowerCamelCase			)
									assert mapped_dataset.info.task_templates == dataset.info.task_templates
									# reload from cache
									A				:       List[Any]														=    dataset.map(__lowerCamelCase			)
									assert mapped_dataset.info.task_templates == dataset.info.task_templates

									A				:       Union[str, Any]														=    dataset.map(__lowerCamelCase			)
									assert mapped_dataset.info.task_templates == []
									# reload from cache
									A				:       Optional[Any]														=    dataset.map(__lowerCamelCase			)
									assert mapped_dataset.info.task_templates == []







						def       SCREAMING_SNAKE_CASE__		(						self   :      str			)   ->					Tuple:
									A				:       Optional[Any]														=    Features({"text": Value("string"			), "label": ClassLabel(names=("pos", "neg")			)}			)
									A				:       Optional[Any]														=    TextClassification(text_column="text"						,						label_column="label"			)
									A				:       Optional[Any]														=    DatasetInfo(features=__lowerCamelCase						,						task_templates=__lowerCamelCase			)
									A				:       Optional[int]														=    Dataset.from_dict({"text": ["A sentence."], "label": ["pos"]}						,						info=__lowerCamelCase			)

									def process(__lowerCamelCase   :      Dict			):
												return example

									A				:       List[Any]														=    dataset.remove_columns("label"			)
									A				:       Dict														=    modified_dataset.map(__lowerCamelCase			)
									assert mapped_dataset.info.task_templates == []