





'''simple docstring'''


import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import MarianConfig, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
 import os

 # The slow tests are often failing with OOM error on GPU
 # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
 # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
 lowerCAmelCase      :  int      							='''platform'''

 import jax
 import jax.numpy as jnp

 from transformers import MarianTokenizer
 from transformers.models.marian.modeling_flax_marian import FlaxMarianModel, FlaxMarianMTModel, shift_tokens_right
def 							UpperCAmelCase_						(		__lowerCamelCase      :      str			,__lowerCamelCase      :      Dict			,__lowerCamelCase      :      str=None			,__lowerCamelCase      :      List[str]=None			,__lowerCamelCase      :      int=None			,__lowerCamelCase      :      List[Any]=None			,__lowerCamelCase      :      List[str]=None			,__lowerCamelCase      :      Optional[Any]=None			,):
   if attention_mask is None:
      lowercase_    :Union[str, Any]					    =				np.where(input_ids != config.pad_token_id			,1			,0				)
   if decoder_attention_mask is None:
      lowercase_    :List[str]					    =				np.where(decoder_input_ids != config.pad_token_id			,1			,0				)
   if head_mask is None:
      lowercase_    :List[str]					    =				np.ones((config.encoder_layers, config.encoder_attention_heads)				)
   if decoder_head_mask is None:
      lowercase_    :Any					    =				np.ones((config.decoder_layers, config.decoder_attention_heads)				)
   if cross_attn_head_mask is None:
      lowercase_    :str					    =				np.ones((config.decoder_layers, config.decoder_attention_heads)				)
   return {
       "input_ids": input_ids,
       "decoder_input_ids": decoder_input_ids,
       "attention_mask": attention_mask,
       "decoder_attention_mask": attention_mask,
   }
class    a_     :





     def __init__(				self	:      Union[str, Any]			,   lowercase	:      int			,   lowercase	:      Union[str, Any]=13			,   lowercase	:      List[str]=7			,   lowercase	:      Dict=True			,   lowercase	:      Tuple=False			,   lowercase	:      Tuple=99			,   lowercase	:      Tuple=16			,   lowercase	:      Optional[Any]=2			,   lowercase	:      Any=4			,   lowercase	:      int=4			,   lowercase	:      List[str]="gelu"			,   lowercase	:      Optional[Any]=0.1			,   lowercase	:      List[Any]=0.1			,   lowercase	:      str=32			,   lowercase	:      List[Any]=2			,   lowercase	:      List[Any]=1			,   lowercase	:      Optional[int]=0			,   lowercase	:      int=0.02			,   ):





        """simple docstring"""




        lowercase_    :str					    =				parent
        lowercase_    :List[Any]					    =				batch_size
        lowercase_    :Any					    =				seq_length
        lowercase_    :Tuple					    =				is_training
        lowercase_    :int					    =				use_labels
        lowercase_    :List[Any]					    =				vocab_size
        lowercase_    :Optional[Any]					    =				hidden_size
        lowercase_    :Tuple					    =				num_hidden_layers
        lowercase_    :List[Any]					    =				num_attention_heads
        lowercase_    :Any					    =				intermediate_size
        lowercase_    :Optional[int]					    =				hidden_act
        lowercase_    :Any					    =				hidden_dropout_prob
        lowercase_    :str					    =				attention_probs_dropout_prob
        lowercase_    :int					    =				max_position_embeddings
        lowercase_    :str					    =				eos_token_id
        lowercase_    :Any					    =				pad_token_id
        lowercase_    :Any					    =				bos_token_id
        lowercase_    :str					    =				initializer_range





     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




        lowercase_    :List[Any]					    =				np.clip(ids_tensor([self.batch_size, self.seq_length - 1]			,   self.vocab_size		)			,   3			,   self.vocab_size		)
        lowercase_    :Tuple					    =				np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)			,   dtype=np.intaa		))			,   -1		)

        lowercase_    :int					    =				shift_tokens_right(lowercase			,   1			,   2		)

        lowercase_    :int					    =				MarianConfig(
            vocab_size=self.vocab_size			,   d_model=self.hidden_size			,   encoder_layers=self.num_hidden_layers			,   decoder_layers=self.num_hidden_layers			,   encoder_attention_heads=self.num_attention_heads			,   decoder_attention_heads=self.num_attention_heads			,   encoder_ffn_dim=self.intermediate_size			,   decoder_ffn_dim=self.intermediate_size			,   dropout=self.hidden_dropout_prob			,   attention_dropout=self.attention_probs_dropout_prob			,   max_position_embeddings=self.max_position_embeddings			,   eos_token_id=self.eos_token_id			,   bos_token_id=self.bos_token_id			,   pad_token_id=self.pad_token_id			,   initializer_range=self.initializer_range			,   use_cache=lowercase			,   )
        lowercase_    :Dict					    =				prepare_marian_inputs_dict(lowercase			,   lowercase			,   lowercase		)
        return config, inputs_dict





     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        lowercase_    ,							lowercase_    :str					    =				self.prepare_config_and_inputs()
        return config, inputs_dict





     def 							lowercase__   (				self	:      Any			,   lowercase	:      Tuple			,   lowercase	:      Tuple			,   lowercase	:      List[Any]		):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				20
        lowercase_    :Optional[int]					    =				model_class_name(lowercase		)

        lowercase_    :Any					    =				model.encode(inputs_dict["input_ids"]		)

        lowercase_    ,							lowercase_    :int					    =				(
            inputs_dict["decoder_input_ids"],
            inputs_dict["decoder_attention_mask"],
        )

        lowercase_    :Tuple					    =				model.init_cache(decoder_input_ids.shape[0]			,   lowercase			,   lowercase		)
        lowercase_    :Any					    =				jnp.ones((decoder_input_ids.shape[0], max_decoder_length)			,   dtype="i4"		)

        lowercase_    :Dict					    =				jnp.broadcast_to(
            jnp.arange(decoder_input_ids.shape[-1] - 1		)[None, :]			,   (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)			,   )
        lowercase_    :Optional[Any]					    =				model.decode(
            decoder_input_ids[:, :-1]			,   lowercase			,   decoder_attention_mask=lowercase			,   past_key_values=lowercase			,   decoder_position_ids=lowercase			,   )

        lowercase_    :int					    =				jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]			,   dtype="i4"		)
        lowercase_    :int					    =				model.decode(
            decoder_input_ids[:, -1:]			,   lowercase			,   decoder_attention_mask=lowercase			,   past_key_values=outputs_cache.past_key_values			,   decoder_position_ids=lowercase			,   )

        lowercase_    :Any					    =				model.decode(lowercase			,   lowercase		)

        lowercase_    :List[Any]					    =				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])		)		)
        self.parent.assertTrue(diff < 1e-3			,   msg=F'Max diff is {diff}'		)







     def 							lowercase__   (				self	:      Any			,   lowercase	:      Optional[int]			,   lowercase	:      List[Any]			,   lowercase	:      Any		):





        """simple docstring"""




        lowercase_    :List[str]					    =				20
        lowercase_    :List[Any]					    =				model_class_name(lowercase		)

        lowercase_    :Optional[int]					    =				model.encode(inputs_dict["input_ids"]		)

        lowercase_    ,							lowercase_    :int					    =				(
            inputs_dict["decoder_input_ids"],
            inputs_dict["decoder_attention_mask"],
        )

        lowercase_    :List[Any]					    =				jnp.concatenate(
            [
                decoder_attention_mask,
                jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])		),
            ]			,   axis=-1			,   )

        lowercase_    :Union[str, Any]					    =				model.init_cache(decoder_input_ids.shape[0]			,   lowercase			,   lowercase		)
        lowercase_    :Optional[int]					    =				jnp.broadcast_to(
            jnp.arange(decoder_input_ids.shape[-1] - 1		)[None, :]			,   (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)			,   )

        lowercase_    :Any					    =				model.decode(
            decoder_input_ids[:, :-1]			,   lowercase			,   decoder_attention_mask=lowercase			,   past_key_values=lowercase			,   decoder_position_ids=lowercase			,   )
        lowercase_    :Union[str, Any]					    =				jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]			,   dtype="i4"		)
        lowercase_    :List[Any]					    =				model.decode(
            decoder_input_ids[:, -1:]			,   lowercase			,   past_key_values=outputs_cache.past_key_values			,   decoder_attention_mask=lowercase			,   decoder_position_ids=lowercase			,   )

        lowercase_    :Optional[Any]					    =				model.decode(lowercase			,   lowercase			,   decoder_attention_mask=lowercase		)

        lowercase_    :int					    =				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])		)		)
        self.parent.assertTrue(diff < 1e-3			,   msg=F'Max diff is {diff}'		)







@require_flax
class    a_     (       _lowerCAmelCase			,		unittest.TestCase			,		_lowerCAmelCase							):
     __A  				=    True
     __A  				=    (FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
     __A  				=    (FlaxMarianMTModel,) if is_flax_available() else ()





     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :Optional[Any]					    =				FlaxMarianModelTester(self		)





     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        lowercase_    ,							lowercase_    :List[Any]					    =				self.model_tester.prepare_config_and_inputs()
        for model_class in self.all_model_classes:
           self.model_tester.check_use_cache_forward(lowercase			,   lowercase			,   lowercase		)





     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




        lowercase_    ,							lowercase_    :Tuple					    =				self.model_tester.prepare_config_and_inputs()
        for model_class in self.all_model_classes:
           self.model_tester.check_use_cache_forward_with_attn_mask(lowercase			,   lowercase			,   lowercase		)





     def 							lowercase__   (				self	:      Optional[int]		):





        """simple docstring"""




        lowercase_    ,							lowercase_    :List[str]					    =				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           with self.subTest(model_class.__name__		):
              lowercase_    :str					    =				self._prepare_for_class(lowercase			,   lowercase		)
              lowercase_    :List[Any]					    =				model_class(lowercase		)

              @jax.jit
              def encode_jitted(lowercase	:      str			,   lowercase	:      Optional[Any]=None			,   **lowercase	:      Optional[int]		):
                 return model.encode(input_ids=lowercase			,   attention_mask=lowercase		)

              with self.subTest("JIT Enabled"		):
                 lowercase_    :Tuple					    =				encode_jitted(**lowercase		).to_tuple()

              with self.subTest("JIT Disabled"		):
                 with jax.disable_jit():
                    lowercase_    :int					    =				encode_jitted(**lowercase		).to_tuple()

              self.assertEqual(len(lowercase		)			,   len(lowercase		)		)
              for jitted_output, output in zip(lowercase			,   lowercase		):
                 self.assertEqual(jitted_output.shape			,   output.shape		)





     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        lowercase_    ,							lowercase_    :List[str]					    =				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           with self.subTest(model_class.__name__		):
              lowercase_    :Optional[Any]					    =				model_class(lowercase		)
              lowercase_    :Optional[Any]					    =				model.encode(inputs_dict["input_ids"]			,   inputs_dict["attention_mask"]		)

              lowercase_    :List[Any]					    =				{
                  "decoder_input_ids": inputs_dict["decoder_input_ids"],
                  "decoder_attention_mask": inputs_dict["decoder_attention_mask"],
                  "encoder_outputs": encoder_outputs,
              }

              @jax.jit
              def decode_jitted(lowercase	:      List[Any]			,   lowercase	:      Tuple			,   lowercase	:      Optional[int]		):
                 return model.decode(
                     decoder_input_ids=lowercase			,   decoder_attention_mask=lowercase			,   encoder_outputs=lowercase			,   )

              with self.subTest("JIT Enabled"		):
                 lowercase_    :str					    =				decode_jitted(**lowercase		).to_tuple()

              with self.subTest("JIT Disabled"		):
                 with jax.disable_jit():
                    lowercase_    :Union[str, Any]					    =				decode_jitted(**lowercase		).to_tuple()

              self.assertEqual(len(lowercase		)			,   len(lowercase		)		)
              for jitted_output, output in zip(lowercase			,   lowercase		):
                 self.assertEqual(jitted_output.shape			,   output.shape		)







     @slow
     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        for model_class_name in self.all_model_classes:
           lowercase_    :Optional[Any]					    =				model_class_name.from_pretrained("Helsinki-NLP/opus-mt-en-de"		)
           # FlaxMarianForSequenceClassification expects eos token in input_ids
           lowercase_    :str					    =				np.ones((1, 1)		) * model.config.eos_token_id
           lowercase_    :Union[str, Any]					    =				model(lowercase		)
           self.assertIsNotNone(lowercase		)







@require_flax
@require_sentencepiece
@require_tokenizers
class    a_     (       unittest.TestCase							):
     __A  				=    None
     __A  				=    None





     @classmethod
     def 							lowercase__   (				cls	:      str		):





        """simple docstring"""




        lowercase_    :List[str]					    =				F'Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}'
        return cls





     @cached_property
     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




        return MarianTokenizer.from_pretrained(self.model_name		)





     @property
     def 							lowercase__   (				self	:      Union[str, Any]		):





        """simple docstring"""




        return self.tokenizer.eos_token_id





     @cached_property
     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




        lowercase_    :FlaxMarianMTModel					    =				FlaxMarianMTModel.from_pretrained(self.model_name		)
        self.assertEqual(model.config.decoder_start_token_id			,   model.config.pad_token_id		)
        return model





     def 							lowercase__   (				self	:      Optional[Any]			,   **lowercase	:      Tuple		):





        """simple docstring"""




        lowercase_    :Dict					    =				self.translate_src_text(**lowercase		)
        self.assertListEqual(self.expected_text			,   lowercase		)







     def 							lowercase__   (				self	:      Any			,   **lowercase	:      str		):





        """simple docstring"""




        lowercase_    :Tuple					    =				self.tokenizer(self.src_text			,   padding=lowercase			,   return_tensors="np"			,   **lowercase		)
        lowercase_    :Optional[Any]					    =				self.model.generate(
            model_inputs.input_ids			,   attention_mask=model_inputs.attention_mask			,   num_beams=2			,   max_length=128			,   ).sequences
        lowercase_    :str					    =				self.tokenizer.batch_decode(lowercase			,   skip_special_tokens=lowercase		)
        return generated_words







@require_flax
@require_sentencepiece
@require_tokenizers
class    a_     (       _lowerCAmelCase							):
     __A  				=    "en"
     __A  				=    "fr"
     __A  				=    [
         "I am a small frog.",
         "Now I can forget the 100 words of german that I know.",
     ]
     __A  				=    [
         "Je suis une petite grenouille.",
         "Maintenant, je peux oublier les 100 mots d'allemand que je connais.",
     ]





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





        """simple docstring"""




        self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class    a_     (       _lowerCAmelCase							):
     __A  				=    "fr"
     __A  				=    "en"
     __A  				=    [
         "Donnez moi le micro.",
         "Tom et Mary étaient assis à une table.",  # Accents
     ]
     __A  				=    [
         "Give me the microphone.",
         "Tom and Mary were sitting at a table.",
     ]





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





        """simple docstring"""




        self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class    a_     (       _lowerCAmelCase							):
     __A  				=    "mt"
     __A  				=    "en"
     __A  				=    ["Billi messu b'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem."]
     __A  				=    ["Touching gently, Jesus healed a man who was affected by the sad disease of leprosy."]





     @slow
     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class    a_     (       _lowerCAmelCase							):
     __A  				=    "en"
     __A  				=    "de"
     __A  				=    [
         "I am a small frog.",
         "Now I can forget the 100 words of german that I know.",
         "Tom asked his teacher for advice.",
         "That's how I would do it.",
         "Tom really admired Mary's courage.",
         "Turn around and close your eyes.",
     ]
     __A  				=    [
         "Ich bin ein kleiner Frosch.",
         "Jetzt kann ich die 100 Wörter des Deutschen vergessen, die ich kenne.",
         "Tom bat seinen Lehrer um Rat.",
         "So würde ich das machen.",
         "Tom bewunderte Marias Mut wirklich.",
         "Drehen Sie sich um und schließen Sie die Augen.",
     ]





     @slow
     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class    a_     (       _lowerCAmelCase							):
     __A  				=    "en"
     __A  				=    "zh"
     __A  				=    ["My name is Wolfgang and I live in Berlin"]
     __A  				=    ["我叫沃尔夫冈 我住在柏林"]





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





        """simple docstring"""




        self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class    a_     (       _lowerCAmelCase							):
     __A  				=    "ru"
     __A  				=    "fr"
     __A  				=    ["Он показал мне рукопись своей новой пьесы."]
     __A  				=    ["Il m'a montré le manuscrit de sa nouvelle pièce."]





     @slow
     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class    a_     (       _lowerCAmelCase							):
     __A  				=    "en"
     __A  				=    "ROMANCE"
     __A  				=    [
         ">>fr<< Don't spend so much time watching TV.",
         ">>pt<< Your message has been sent.",
         ">>es<< He's two years older than me.",
     ]
     __A  				=    [
         "Ne passez pas autant de temps à regarder la télé.",
         "A sua mensagem foi enviada.",
         "Es dos años más viejo que yo.",
     ]





     @slow
     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        self._assert_generated_batch_equal_expected()









'''simple docstring'''


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


lowerCAmelCase      :  Tuple      							={
    '''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      :      str				):
   lowercase_    :str					    =				task_cls()
   lowercase_    :Tuple					    =				asdict(__lowerCamelCase				)
   lowercase_    :Dict					    =				task_template_from_dict(__lowerCamelCase				)
   assert task == reloaded
class    a_     :





     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				LanguageModeling(text_column="input_text"		)
        assert {"input_text": "text"} == task.column_mapping







     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :Tuple					    =				Features({"text": Value("string"		)}		)
        lowercase_    :List[Any]					    =				{"text_column": "input_text"}
        lowercase_    :List[str]					    =				LanguageModeling.from_dict(lowercase		)
        assert "language-modeling" == task.task
        assert input_schema == task.input_schema







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      Tuple		):





        """simple docstring"""




        lowercase_    :List[str]					    =				sorted(["pos", "neg"]		)





     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




        lowercase_    :List[str]					    =				TextClassification(text_column="input_text"			,   label_column="input_label"		)
        self.assertDictEqual({"input_text": "text", "input_label": "labels"}			,   task.column_mapping		)





     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




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







     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        lowercase_    :Union[str, Any]					    =				TextClassification(text_column="input_text"			,   label_column="input_label"		)
        self.assertEqual(task.label_schema["labels"]			,   lowercase		)
        lowercase_    :Tuple					    =				task.align_with_features(Features({"input_label": ClassLabel(names=self.labels		)}		)		)
        self.assertEqual(task.label_schema["labels"]			,   ClassLabel(names=self.labels		)		)







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        lowercase_    :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 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :Dict					    =				Features({"question": Value("string"		), "context": Value("string"		)}		)
        lowercase_    :List[Any]					    =				Features(
            {
                "answers": Sequence(
                    {
                        "text": Value("string"		),
                        "answer_start": Value("int32"		),
                    }		)
            }		)
        lowercase_    :int					    =				{
            "context_column": "input_input_context",
            "question_column": "input_question",
            "answers_column": "input_answers",
        }
        lowercase_    :int					    =				QuestionAnsweringExtractive.from_dict(lowercase		)
        self.assertEqual("question-answering-extractive"			,   task.task		)
        self.assertEqual(lowercase			,   task.input_schema		)
        self.assertEqual(lowercase			,   task.label_schema		)







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :Tuple					    =				Summarization(text_column="input_text"			,   summary_column="input_summary"		)
        self.assertDictEqual({"input_text": "text", "input_summary": "summary"}			,   task.column_mapping		)







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





        """simple docstring"""




        lowercase_    :int					    =				Features({"text": Value("string"		)}		)
        lowercase_    :str					    =				Features({"summary": Value("string"		)}		)
        lowercase_    :Tuple					    =				{"text_column": "input_text", "summary_column": "input_summary"}
        lowercase_    :Optional[int]					    =				Summarization.from_dict(lowercase		)
        self.assertEqual("summarization"			,   task.task		)
        self.assertEqual(lowercase			,   task.input_schema		)
        self.assertEqual(lowercase			,   task.label_schema		)







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :Any					    =				AutomaticSpeechRecognition(audio_column="input_audio"			,   transcription_column="input_transcription"		)
        self.assertDictEqual({"input_audio": "audio", "input_transcription": "transcription"}			,   task.column_mapping		)







     def 							lowercase__   (				self	:      Optional[int]		):





        """simple docstring"""




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







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




        lowercase_    :str					    =				sorted(["pos", "neg"]		)





     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				AudioClassification(audio_column="input_audio"			,   label_column="input_label"		)
        self.assertDictEqual({"input_audio": "audio", "input_label": "labels"}			,   task.column_mapping		)





     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




        lowercase_    :int					    =				Features({"audio": Audio()}		)
        lowercase_    :Tuple					    =				Features({"labels": ClassLabel}		)
        lowercase_    :List[str]					    =				{
            "audio_column": "input_image",
            "label_column": "input_label",
        }
        lowercase_    :List[Any]					    =				AudioClassification.from_dict(lowercase		)
        self.assertEqual("audio-classification"			,   task.task		)
        self.assertEqual(lowercase			,   task.input_schema		)
        self.assertEqual(lowercase			,   task.label_schema		)







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





        """simple docstring"""




        lowercase_    :Dict					    =				AudioClassification(audio_column="input_audio"			,   label_column="input_label"		)
        self.assertEqual(task.label_schema["labels"]			,   lowercase		)
        lowercase_    :List[Any]					    =				task.align_with_features(Features({"input_label": ClassLabel(names=self.labels		)}		)		)
        self.assertEqual(task.label_schema["labels"]			,   ClassLabel(names=self.labels		)		)







class    a_     (       _lowerCAmelCase							):





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





        """simple docstring"""




        lowercase_    :Union[str, Any]					    =				sorted(["pos", "neg"]		)





     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				ImageClassification(image_column="input_image"			,   label_column="input_label"		)
        self.assertDictEqual({"input_image": "image", "input_label": "labels"}			,   task.column_mapping		)





     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




        lowercase_    :Dict					    =				Features({"image": Image()}		)
        lowercase_    :str					    =				Features({"labels": ClassLabel}		)
        lowercase_    :Optional[Any]					    =				{
            "image_column": "input_image",
            "label_column": "input_label",
        }
        lowercase_    :str					    =				ImageClassification.from_dict(lowercase		)
        self.assertEqual("image-classification"			,   task.task		)
        self.assertEqual(lowercase			,   task.input_schema		)
        self.assertEqual(lowercase			,   task.label_schema		)







     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




        lowercase_    :Any					    =				ImageClassification(image_column="input_image"			,   label_column="input_label"		)
        self.assertEqual(task.label_schema["labels"]			,   lowercase		)
        lowercase_    :Dict					    =				task.align_with_features(Features({"input_label": ClassLabel(names=self.labels		)}		)		)
        self.assertEqual(task.label_schema["labels"]			,   ClassLabel(names=self.labels		)		)







class    a_     (       _lowerCAmelCase							):





     def 							lowercase__   (				self	:      Tuple		):





        """simple docstring"""




        lowercase_    :Dict					    =				DatasetInfo(task_templates=QuestionAnsweringExtractive()		)
        lowercase_    :Optional[Any]					    =				Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}			,   info=lowercase		)
        assert isinstance(dataset.info.task_templates			,   lowercase		)
        assert len(dataset.info.task_templates		) == 1

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

        def dont_keep_task(lowercase	:      Any		):
           lowercase_    :Optional[Any]					    =				deepcopy(lowercase		)
           lowercase_    :Dict					    =				0
           return out

        lowercase_    :List[str]					    =				dataset.map(lowercase		)
        assert mapped_dataset.info.task_templates == dataset.info.task_templates
        # reload from cache
        lowercase_    :List[Any]					    =				dataset.map(lowercase		)
        assert mapped_dataset.info.task_templates == dataset.info.task_templates

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







     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




        lowercase_    :Optional[Any]					    =				Features({"text": Value("string"		), "label": ClassLabel(names=("pos", "neg")		)}		)
        lowercase_    :str					    =				TextClassification(text_column="text"			,   label_column="label"		)
        lowercase_    :Optional[int]					    =				DatasetInfo(features=lowercase			,   task_templates=lowercase		)
        lowercase_    :Dict					    =				Dataset.from_dict({"text": ["A sentence."], "label": ["pos"]}			,   info=lowercase		)

        def process(lowercase	:      Dict		):
           return example

        lowercase_    :Tuple					    =				dataset.remove_columns("label"		)
        lowercase_    :Optional[int]					    =				modified_dataset.map(lowercase		)
        assert mapped_dataset.info.task_templates == []


