




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:    Any											=   {
    '''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''': [5_1_5]},
}


@pytest.mark.parametrize(
    'task_cls'						,	[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]						,	)
def 				_a       (				lowerCAmelCase   )->  Any:
		SCREAMING_SNAKE_CASE_							=       task_cls()
		SCREAMING_SNAKE_CASE_							=       asdict(lowerCAmelCase   )
		SCREAMING_SNAKE_CASE_							=       task_template_from_dict(lowerCAmelCase   )
		assert task == reloaded



class       lowercase_		:



						def   __a				( self  :      Optional[Any]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       LanguageModeling(text_column='input_text'     )
								assert {"input_text": "text"} == task.column_mapping






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

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       Features({'text': Value('string'     )}     )
								SCREAMING_SNAKE_CASE_							=       {'text_column': 'input_text'}
								SCREAMING_SNAKE_CASE_							=       LanguageModeling.from_dict(snake_case__     )
								assert "language-modeling" == task.task
								assert input_schema == task.input_schema



class       lowercase_		(SCREAMING_SNAKE_CASE__   ):



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

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       sorted(['pos', 'neg']     )



						def   __a				( self  :      List[Any]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       TextClassification(text_column='input_text'				,       label_column='input_label'     )
								self.assertDictEqual({'input_text': 'text', 'input_label': 'labels'}				,       task.column_mapping     )



						def   __a				( self  :      Dict     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       Features({'text': Value('string'     )}     )
								# Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
								SCREAMING_SNAKE_CASE_							=       Features({'labels': ClassLabel}     )
								SCREAMING_SNAKE_CASE_							=       {'text_column': 'input_text', 'label_column': 'input_labels'}
								SCREAMING_SNAKE_CASE_							=       TextClassification.from_dict(snake_case__     )
								self.assertEqual('text-classification'				,       task.task     )
								self.assertEqual(snake_case__				,       task.input_schema     )
								self.assertEqual(snake_case__				,       task.label_schema     )






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

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       TextClassification(text_column='input_text'				,       label_column='input_label'     )
								self.assertEqual(task.label_schema['labels']				,       snake_case__     )
								SCREAMING_SNAKE_CASE_							=       task.align_with_features(Features({'input_label': ClassLabel(names=self.labels     )}     )     )
								self.assertEqual(task.label_schema['labels']				,       ClassLabel(names=self.labels     )     )



class       lowercase_		(SCREAMING_SNAKE_CASE__   ):



						def   __a				( self  :      Tuple     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       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   __a				( self  :      str     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       Features({'question': Value('string'     ), 'context': Value('string'     )}     )
								SCREAMING_SNAKE_CASE_							=       Features(
								    {
								        'answers': Sequence(
								            {
								                'text': Value('string'     ),
								                'answer_start': Value('int32'     ),
								            }     )
								    }     )
								SCREAMING_SNAKE_CASE_							=       {
								    'context_column': 'input_input_context',
								    'question_column': 'input_question',
								    'answers_column': 'input_answers',
								}
								SCREAMING_SNAKE_CASE_							=       QuestionAnsweringExtractive.from_dict(snake_case__     )
								self.assertEqual('question-answering-extractive'				,       task.task     )
								self.assertEqual(snake_case__				,       task.input_schema     )
								self.assertEqual(snake_case__				,       task.label_schema     )



class       lowercase_		(SCREAMING_SNAKE_CASE__   ):



						def   __a				( self  :      Dict     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       Summarization(text_column='input_text'				,       summary_column='input_summary'     )
								self.assertDictEqual({'input_text': 'text', 'input_summary': 'summary'}				,       task.column_mapping     )






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

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       Features({'text': Value('string'     )}     )
								SCREAMING_SNAKE_CASE_							=       Features({'summary': Value('string'     )}     )
								SCREAMING_SNAKE_CASE_							=       {'text_column': 'input_text', 'summary_column': 'input_summary'}
								SCREAMING_SNAKE_CASE_							=       Summarization.from_dict(snake_case__     )
								self.assertEqual('summarization'				,       task.task     )
								self.assertEqual(snake_case__				,       task.input_schema     )
								self.assertEqual(snake_case__				,       task.label_schema     )



class       lowercase_		(SCREAMING_SNAKE_CASE__   ):



						def   __a				( self  :      Optional[Any]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       AutomaticSpeechRecognition(audio_column='input_audio'				,       transcription_column='input_transcription'     )
								self.assertDictEqual({'input_audio': 'audio', 'input_transcription': 'transcription'}				,       task.column_mapping     )






						def   __a				( self  :      List[str]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       Features({'audio': Audio()}     )
								SCREAMING_SNAKE_CASE_							=       Features({'transcription': Value('string'     )}     )
								SCREAMING_SNAKE_CASE_							=       {
								    'audio_column': 'input_audio',
								    'transcription_column': 'input_transcription',
								}
								SCREAMING_SNAKE_CASE_							=       AutomaticSpeechRecognition.from_dict(snake_case__     )
								self.assertEqual('automatic-speech-recognition'				,       task.task     )
								self.assertEqual(snake_case__				,       task.input_schema     )
								self.assertEqual(snake_case__				,       task.label_schema     )



class       lowercase_		(SCREAMING_SNAKE_CASE__   ):



						def   __a				( self  :      Tuple     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       sorted(['pos', 'neg']     )



						def   __a				( self  :      Optional[Any]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       AudioClassification(audio_column='input_audio'				,       label_column='input_label'     )
								self.assertDictEqual({'input_audio': 'audio', 'input_label': 'labels'}				,       task.column_mapping     )



						def   __a				( self  :      List[str]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       Features({'audio': Audio()}     )
								SCREAMING_SNAKE_CASE_							=       Features({'labels': ClassLabel}     )
								SCREAMING_SNAKE_CASE_							=       {
								    'audio_column': 'input_image',
								    'label_column': 'input_label',
								}
								SCREAMING_SNAKE_CASE_							=       AudioClassification.from_dict(snake_case__     )
								self.assertEqual('audio-classification'				,       task.task     )
								self.assertEqual(snake_case__				,       task.input_schema     )
								self.assertEqual(snake_case__				,       task.label_schema     )






						def   __a				( self  :      str     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       AudioClassification(audio_column='input_audio'				,       label_column='input_label'     )
								self.assertEqual(task.label_schema['labels']				,       snake_case__     )
								SCREAMING_SNAKE_CASE_							=       task.align_with_features(Features({'input_label': ClassLabel(names=self.labels     )}     )     )
								self.assertEqual(task.label_schema['labels']				,       ClassLabel(names=self.labels     )     )



class       lowercase_		(SCREAMING_SNAKE_CASE__   ):



						def   __a				( self  :      Dict     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       sorted(['pos', 'neg']     )



						def   __a				( self  :      List[Any]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       ImageClassification(image_column='input_image'				,       label_column='input_label'     )
								self.assertDictEqual({'input_image': 'image', 'input_label': 'labels'}				,       task.column_mapping     )



						def   __a				( self  :      Optional[int]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       Features({'image': Image()}     )
								SCREAMING_SNAKE_CASE_							=       Features({'labels': ClassLabel}     )
								SCREAMING_SNAKE_CASE_							=       {
								    'image_column': 'input_image',
								    'label_column': 'input_label',
								}
								SCREAMING_SNAKE_CASE_							=       ImageClassification.from_dict(snake_case__     )
								self.assertEqual('image-classification'				,       task.task     )
								self.assertEqual(snake_case__				,       task.input_schema     )
								self.assertEqual(snake_case__				,       task.label_schema     )






						def   __a				( self  :      int     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       ImageClassification(image_column='input_image'				,       label_column='input_label'     )
								self.assertEqual(task.label_schema['labels']				,       snake_case__     )
								SCREAMING_SNAKE_CASE_							=       task.align_with_features(Features({'input_label': ClassLabel(names=self.labels     )}     )     )
								self.assertEqual(task.label_schema['labels']				,       ClassLabel(names=self.labels     )     )



class       lowercase_		(SCREAMING_SNAKE_CASE__   ):



						def   __a				( self  :      Optional[Any]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       DatasetInfo(task_templates=QuestionAnsweringExtractive()     )
								SCREAMING_SNAKE_CASE_							=       Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}				,       info=snake_case__     )
								assert isinstance(dataset.info.task_templates				,       snake_case__     )
								assert len(dataset.info.task_templates     ) == 1

								def keep_task(snake_case__  :      Dict     ):
										return x

								def dont_keep_task(snake_case__  :      Union[str, Any]     ):
										SCREAMING_SNAKE_CASE_							=       deepcopy(snake_case__     )
										SCREAMING_SNAKE_CASE_							=       0
										return out

								SCREAMING_SNAKE_CASE_							=       dataset.map(snake_case__     )
								assert mapped_dataset.info.task_templates == dataset.info.task_templates
								# reload from cache
								SCREAMING_SNAKE_CASE_							=       dataset.map(snake_case__     )
								assert mapped_dataset.info.task_templates == dataset.info.task_templates

								SCREAMING_SNAKE_CASE_							=       dataset.map(snake_case__     )
								assert mapped_dataset.info.task_templates == []
								# reload from cache
								SCREAMING_SNAKE_CASE_							=       dataset.map(snake_case__     )
								assert mapped_dataset.info.task_templates == []






						def   __a				( self  :      Optional[Any]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       Features({'text': Value('string'     ), 'label': ClassLabel(names=('pos', 'neg')     )}     )
								SCREAMING_SNAKE_CASE_							=       TextClassification(text_column='text'				,       label_column='label'     )
								SCREAMING_SNAKE_CASE_							=       DatasetInfo(features=snake_case__				,       task_templates=snake_case__     )
								SCREAMING_SNAKE_CASE_							=       Dataset.from_dict({'text': ['A sentence.'], 'label': ['pos']}				,       info=snake_case__     )

								def process(snake_case__  :      List[str]     ):
										return example

								SCREAMING_SNAKE_CASE_							=       dataset.remove_columns('label'     )
								SCREAMING_SNAKE_CASE_							=       modified_dataset.map(snake_case__     )
								assert mapped_dataset.info.task_templates == []





import unittest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    SummarizationPipeline,
    TFPreTrainedModel,
    pipeline,
)
from transformers.testing_utils import get_gpu_count, is_pipeline_test, require_tf, require_torch, slow, torch_device
from transformers.tokenization_utils import TruncationStrategy

from .test_pipelines_common import ANY


SCREAMING_SNAKE_CASE:    Optional[Any]											=   -1 if torch_device == '''cpu''' else 0



@is_pipeline_test
class       lowercase_		(unittest.TestCase   ):
						lowerCAmelCase__ 			=MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
						lowerCAmelCase__ 			=TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING



						def   __a				( self  :      Optional[Any]				,       snake_case__  :      Tuple				,       snake_case__  :      Tuple				,       snake_case__  :      Optional[Any]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       SummarizationPipeline(model=snake_case__				,       tokenizer=snake_case__     )
								return summarizer, ["(CNN)The Palestinian Authority officially became", "Some other text"]



						def   __a				( self  :      Tuple				,       snake_case__  :      str				,       snake_case__  :      Union[str, Any]     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       summarizer.model

								SCREAMING_SNAKE_CASE_							=       summarizer('(CNN)The Palestinian Authority officially became'     )
								self.assertEqual(snake_case__				,       [{'summary_text': ANY(snake_case__     )}]     )

								SCREAMING_SNAKE_CASE_							=       summarizer(
								    '(CNN)The Palestinian Authority officially became '				,       num_beams=2				,       min_length=2				,       max_length=5				,       )
								self.assertEqual(snake_case__				,       [{'summary_text': ANY(snake_case__     )}]     )

								# Some models (Switch Transformers, LED, T5, LongT5, etc) can handle long sequences.
								SCREAMING_SNAKE_CASE_							=       [
								    'SwitchTransformersConfig',
								    'T5Config',
								    'LongT5Config',
								    'LEDConfig',
								    'PegasusXConfig',
								    'FSMTConfig',
								    'M2M100Config',
								    'ProphetNetConfig',  # positional embeddings up to a fixed maximum size (otherwise clamping the values)
								]
								if model.config.__class__.__name__ not in model_can_handle_longer_seq:
										# Too long and exception is expected.
										# For TF models, if the weights are initialized in GPU context, we won't get expected index error from
										# the embedding layer.
										if not (
										    isinstance(snake_case__				,       snake_case__     )
										    and get_gpu_count() > 0
										    and len(summarizer.model.trainable_weights     ) > 0
										):
												with self.assertRaises(snake_case__     ):
														SCREAMING_SNAKE_CASE_							=       summarizer('This ' * 10_00     )
								SCREAMING_SNAKE_CASE_							=       summarizer('This ' * 10_00				,       truncation=TruncationStrategy.ONLY_FIRST     )



						@require_torch
						def   __a				( self  :      Dict     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       pipeline(task='summarization'				,       model='sshleifer/tiny-mbart'				,       framework='pt'     )
								SCREAMING_SNAKE_CASE_							=       summarizer('This is a small test'     )
								self.assertEqual(
								    snake_case__				,       [
								        {
								            'summary_text': 'เข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไป'
								        }
								    ]				,       )



						@require_tf
						def   __a				( self  :      Any     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       pipeline(task='summarization'				,       model='sshleifer/tiny-mbart'				,       framework='tf'     )
								SCREAMING_SNAKE_CASE_							=       summarizer('This is a small test'     )
								self.assertEqual(
								    snake_case__				,       [
								        {
								            'summary_text': 'เข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไป'
								        }
								    ]				,       )






						@require_torch
						@slow
						def   __a				( self  :      Any     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       pipeline(task='summarization'				,       device=snake_case__     )
								SCREAMING_SNAKE_CASE_							=       (
								    ' (CNN)The Palestinian Authority officially became the 123rd member of the International Criminal Court on'
								    ' Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The'
								    ' formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based.'
								    ' The Palestinians signed the ICC\'s founding Rome Statute in January, when they also accepted its'
								    ' jurisdiction over alleged crimes committed "in the occupied Palestinian territory, including East'
								    ' Jerusalem, since June 13, 2014." Later that month, the ICC opened a preliminary examination into the'
								    ' situation in Palestinian territories, paving the way for possible war crimes investigations against'
								    ' Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and'
								    ' the United States, neither of which is an ICC member, opposed the Palestinians\' efforts to join the'
								    ' body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday\'s ceremony, said it was a'
								    ' move toward greater justice. "As Palestine formally becomes a State Party to the Rome Statute today, the'
								    ' world is also a step closer to ending a long era of impunity and injustice," he said, according to an'
								    ' ICC news release. "Indeed, today brings us closer to our shared goals of justice and peace." Judge'
								    ' Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the'
								    ' Palestinians. "As the Rome Statute today enters into force for the State of Palestine, Palestine'
								    ' acquires all the rights as well as responsibilities that come with being a State Party to the Statute.'
								    ' These are substantive commitments, which cannot be taken lightly," she said. Rights group Human Rights'
								    ' Watch welcomed the development. "Governments seeking to penalize Palestine for joining the ICC should'
								    ' immediately end their pressure, and countries that support universal acceptance of the court\'s treaty'
								    ' should speak out to welcome its membership," said Balkees Jarrah, international justice counsel for the'
								    ' group. \"What\'s objectionable is the attempts to undermine international justice, not Palestine\'s'
								    ' decision to join a treaty to which over 100 countries around the world are members." In January, when'
								    ' the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an'
								    ' outrage, saying the court was overstepping its boundaries. The United States also said it "strongly"'
								    ' disagreed with the court\'s decision. \"As we have said repeatedly, we do not believe that Palestine is a'
								    ' state and therefore we do not believe that it is eligible to join the ICC," the State Department said in'
								    ' a statement. It urged the warring sides to resolve their differences through direct negotiations. "We'
								    ' will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,"'
								    ' it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the'
								    ' territories as "Palestine." While a preliminary examination is not a formal investigation, it allows the'
								    ' court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou'
								    ' Bensouda said her office would "conduct its analysis in full independence and impartiality." The war'
								    ' between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry'
								    ' will include alleged war crimes committed since June. The International Criminal Court was set up in'
								    ' 2002 to prosecute genocide, crimes against humanity and war crimes. CNN\'s Vasco Cotovio, Kareem Khadder'
								    ' and Faith Karimi contributed to this report.'
								)
								SCREAMING_SNAKE_CASE_							=       (
								    ' The Palestinian Authority becomes the 123rd member of the International Criminal Court . The move gives'
								    ' the court jurisdiction over alleged crimes in Palestinian territories . Israel and the United States'
								    ' opposed the Palestinians\' efforts to join the court . Rights group Human Rights Watch welcomes the move,'
								    ' says governments seeking to penalize Palestine should end pressure .'
								)
								SCREAMING_SNAKE_CASE_							=       summarizer(snake_case__     )
								self.assertEqual(result[0]['summary_text']				,       snake_case__     )