




'''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


_SCREAMING_SNAKE_CASE							:     List[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": [515]},
}


@pytest.mark.parametrize(
    "task_cls"							,       [
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]							,       )
def   UpperCamelCase_(			snake_case							: Optional[int]  ):

							'''simple docstring'''






							snake_case_			      =   task_cls()
							snake_case_			      =   asdict(snake_case  )
							snake_case_			      =   task_template_from_dict(snake_case  )
							assert task == reloaded




class 				_snake_case	:




			def      lowerCAmelCase__       (      self							)       ->       Tuple:

										'''simple docstring'''




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




			def      lowerCAmelCase__       (      self							)       ->       str:

										'''simple docstring'''




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




class 				_snake_case	(			lowercase_							):




			def      lowerCAmelCase__       (      self							)       ->       str:

										'''simple docstring'''




										snake_case_			      =   sorted(["pos", "neg"]							)




			def      lowerCAmelCase__       (      self							)       ->       Tuple:

										'''simple docstring'''




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




			def      lowerCAmelCase__       (      self							)       ->       Any:

										'''simple docstring'''




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




			def      lowerCAmelCase__       (      self							)       ->       Optional[int]:

										'''simple docstring'''




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




class 				_snake_case	(			lowercase_							):




			def      lowerCAmelCase__       (      self							)       ->       Any:

										'''simple docstring'''




										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      lowerCAmelCase__       (      self							)       ->       Tuple:

										'''simple docstring'''




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




class 				_snake_case	(			lowercase_							):




			def      lowerCAmelCase__       (      self							)       ->       Optional[Any]:

										'''simple docstring'''




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




			def      lowerCAmelCase__       (      self							)       ->       str:

										'''simple docstring'''




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




class 				_snake_case	(			lowercase_							):




			def      lowerCAmelCase__       (      self							)       ->       Union[str, Any]:

										'''simple docstring'''




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




			def      lowerCAmelCase__       (      self							)       ->       Tuple:

										'''simple docstring'''




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




class 				_snake_case	(			lowercase_							):




			def      lowerCAmelCase__       (      self							)       ->       Optional[Any]:

										'''simple docstring'''




										snake_case_			      =   sorted(["pos", "neg"]							)




			def      lowerCAmelCase__       (      self							)       ->       Any:

										'''simple docstring'''




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




			def      lowerCAmelCase__       (      self							)       ->       str:

										'''simple docstring'''




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




			def      lowerCAmelCase__       (      self							)       ->       Optional[Any]:

										'''simple docstring'''




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




class 				_snake_case	(			lowercase_							):




			def      lowerCAmelCase__       (      self							)       ->       str:

										'''simple docstring'''




										snake_case_			      =   sorted(["pos", "neg"]							)




			def      lowerCAmelCase__       (      self							)       ->       Any:

										'''simple docstring'''




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




			def      lowerCAmelCase__       (      self							)       ->       List[str]:

										'''simple docstring'''




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




			def      lowerCAmelCase__       (      self							)       ->       Dict:

										'''simple docstring'''




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




class 				_snake_case	(			lowercase_							):




			def      lowerCAmelCase__       (      self							)       ->       List[Any]:

										'''simple docstring'''




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

										def keep_task(a__							):
																	return x

										def dont_keep_task(a__							):
																	snake_case_			      =   deepcopy(a__							)
																	snake_case_			      =   0
																	return out

										snake_case_			      =   dataset.map(a__							)
										assert mapped_dataset.info.task_templates == dataset.info.task_templates
										# reload from cache
										snake_case_			      =   dataset.map(a__							)
										assert mapped_dataset.info.task_templates == dataset.info.task_templates

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




			def      lowerCAmelCase__       (      self							)       ->       Union[str, Any]:

										'''simple docstring'''




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

										def process(a__							):
																	return example

										snake_case_			      =   dataset.remove_columns("label"							)
										snake_case_			      =   modified_dataset.map(a__							)
										assert mapped_dataset.info.task_templates == []










'''simple docstring'''





import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image

		from transformers import ViltImageProcessor




class 				_snake_case	(			unittest.TestCase							):




			def __init__(      self       ,							a__       ,							a__=7       ,							a__=3       ,							a__=18       ,							a__=30       ,							a__=400       ,							a__=True       ,							a__=None       ,							a__=2       ,							a__=True       ,							a__=[0.5, 0.5, 0.5]       ,							a__=[0.5, 0.5, 0.5]       ,							)       ->       Any:

										'''simple docstring'''




										snake_case_			      =   size if size is not None else {"shortest_edge": 30}
										snake_case_			      =   parent
										snake_case_			      =   batch_size
										snake_case_			      =   num_channels
										snake_case_			      =   image_size
										snake_case_			      =   min_resolution
										snake_case_			      =   max_resolution
										snake_case_			      =   do_resize
										snake_case_			      =   size
										snake_case_			      =   size_divisor
										snake_case_			      =   do_normalize
										snake_case_			      =   image_mean
										snake_case_			      =   image_std




			def      lowerCAmelCase__       (      self							)       ->       int:

										'''simple docstring'''




										return {
										    "image_mean": self.image_mean,
										    "image_std": self.image_std,
										    "do_normalize": self.do_normalize,
										    "do_resize": self.do_resize,
										    "size": self.size,
										    "size_divisor": self.size_divisor,
										}




			def      lowerCAmelCase__       (      self       ,							a__       ,							a__=False							)       ->       str:

										'''simple docstring'''




										if not batched:
																	snake_case_			      =   self.size["shortest_edge"]
																	snake_case_			      =   image_inputs[0]
																	if isinstance(a__       ,							Image.Image							):
																								snake_case_      ,   snake_case_			      =   image.size
																	else:
																								snake_case_      ,   snake_case_			      =   image.shape[1], image.shape[2]
																	snake_case_			      =   size / min(a__       ,							a__							)
																	if h < w:
																								snake_case_      ,   snake_case_			      =   size, scale * w
																	else:
																								snake_case_      ,   snake_case_			      =   scale * h, size

																	snake_case_			      =   int((1_333 / 800) * size							)
																	if max(a__       ,							a__							) > max_size:
																								snake_case_			      =   max_size / max(a__       ,							a__							)
																								snake_case_			      =   newh * scale
																								snake_case_			      =   neww * scale

																	snake_case_      ,   snake_case_			      =   int(newh + 0.5							), int(neww + 0.5							)
																	snake_case_      ,   snake_case_			      =   (
																	    newh // self.size_divisor * self.size_divisor,
																	    neww // self.size_divisor * self.size_divisor,
																	)

										else:
																	snake_case_			      =   []
																	for image in image_inputs:
																								snake_case_      ,   snake_case_			      =   self.get_expected_values([image]							)
																								expected_values.append((expected_height, expected_width)							)
																	snake_case_			      =   max(a__       ,							key=lambda a__							: item[0]							)[0]
																	snake_case_			      =   max(a__       ,							key=lambda a__							: item[1]							)[1]

										return expected_height, expected_width




@require_torch
@require_vision
class 				_snake_case	(			lowercase_		,		unittest.TestCase							):
			lowerCAmelCase_  :   Union[str, Any]		 =					ViltImageProcessor if is_vision_available() else None




			def      lowerCAmelCase__       (      self							)       ->       Dict:

										'''simple docstring'''




										snake_case_			      =   ViltImageProcessingTester(self							)




			@property
			def      lowerCAmelCase__       (      self							)       ->       Any:

										'''simple docstring'''




										return self.image_processor_tester.prepare_image_processor_dict()




			def      lowerCAmelCase__       (      self							)       ->       List[Any]:

										'''simple docstring'''




										snake_case_			      =   self.image_processing_class(**self.image_processor_dict							)
										self.assertTrue(hasattr(a__       ,							"image_mean"							)							)
										self.assertTrue(hasattr(a__       ,							"image_std"							)							)
										self.assertTrue(hasattr(a__       ,							"do_normalize"							)							)
										self.assertTrue(hasattr(a__       ,							"do_resize"							)							)
										self.assertTrue(hasattr(a__       ,							"size"							)							)
										self.assertTrue(hasattr(a__       ,							"size_divisor"							)							)




			def      lowerCAmelCase__       (      self							)       ->       Dict:

										'''simple docstring'''




										snake_case_			      =   self.image_processing_class.from_dict(self.image_processor_dict							)
										self.assertEqual(image_processor.size       ,							{"shortest_edge": 30}							)

										snake_case_			      =   self.image_processing_class.from_dict(self.image_processor_dict       ,							size=42							)
										self.assertEqual(image_processor.size       ,							{"shortest_edge": 42}							)




			def      lowerCAmelCase__       (      self							)       ->       Optional[int]:

										'''simple docstring'''




										pass




			def      lowerCAmelCase__       (      self							)       ->       Tuple:

										'''simple docstring'''




										snake_case_			      =   self.image_processing_class(**self.image_processor_dict							)
										# create random PIL images
										snake_case_			      =   prepare_image_inputs(self.image_processor_tester       ,							equal_resolution=a__							)
										for image in image_inputs:
																	self.assertIsInstance(a__       ,							Image.Image							)

										# Test not batched input
										snake_case_			      =   image_processing(image_inputs[0]       ,							return_tensors="pt"							).pixel_values

										snake_case_      ,   snake_case_			      =   self.image_processor_tester.get_expected_values(a__							)
										self.assertEqual(
										    encoded_images.shape       ,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,							)

										# Test batched
										snake_case_			      =   image_processing(a__       ,							return_tensors="pt"							).pixel_values

										snake_case_      ,   snake_case_			      =   self.image_processor_tester.get_expected_values(a__       ,							batched=a__							)
										self.assertEqual(
										    encoded_images.shape       ,							(
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )       ,							)




			def      lowerCAmelCase__       (      self							)       ->       Dict:

										'''simple docstring'''




										snake_case_			      =   self.image_processing_class(**self.image_processor_dict							)
										# create random numpy tensors
										snake_case_			      =   prepare_image_inputs(self.image_processor_tester       ,							equal_resolution=a__       ,							numpify=a__							)
										for image in image_inputs:
																	self.assertIsInstance(a__       ,							np.ndarray							)

										# Test not batched input
										snake_case_			      =   image_processing(image_inputs[0]       ,							return_tensors="pt"							).pixel_values

										snake_case_      ,   snake_case_			      =   self.image_processor_tester.get_expected_values(a__							)
										self.assertEqual(
										    encoded_images.shape       ,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,							)

										# Test batched
										snake_case_			      =   image_processing(a__       ,							return_tensors="pt"							).pixel_values

										snake_case_      ,   snake_case_			      =   self.image_processor_tester.get_expected_values(a__       ,							batched=a__							)
										self.assertEqual(
										    encoded_images.shape       ,							(
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )       ,							)




			def      lowerCAmelCase__       (      self							)       ->       Tuple:

										'''simple docstring'''




										snake_case_			      =   self.image_processing_class(**self.image_processor_dict							)
										# create random PyTorch tensors
										snake_case_			      =   prepare_image_inputs(self.image_processor_tester       ,							equal_resolution=a__       ,							torchify=a__							)
										for image in image_inputs:
																	self.assertIsInstance(a__       ,							torch.Tensor							)

										# Test not batched input
										snake_case_			      =   image_processing(image_inputs[0]       ,							return_tensors="pt"							).pixel_values

										snake_case_      ,   snake_case_			      =   self.image_processor_tester.get_expected_values(a__							)
										self.assertEqual(
										    encoded_images.shape       ,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)       ,							)

										# Test batched
										snake_case_			      =   image_processing(a__       ,							return_tensors="pt"							).pixel_values

										snake_case_      ,   snake_case_			      =   self.image_processor_tester.get_expected_values(a__       ,							batched=a__							)
										self.assertEqual(
										    encoded_images.shape       ,							(
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )       ,							)




