


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


__lowercase:		Union[str, 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 							SCREAMING_SNAKE_CASE__(		_UpperCamelCase   :					Optional[int] )		->       List[Any]:





   '''simple docstring'''







   UpperCamelCase__			    =    task_cls()
   UpperCamelCase__			    =    asdict(_UpperCamelCase )
   UpperCamelCase__			    =    task_template_from_dict(_UpperCamelCase )
   assert task == reloaded







class 			UpperCAmelCase			:

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





    """simple docstring"""



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

 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



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







class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__):

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





    """simple docstring"""



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

 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



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

 def 		lowercase_    (			self			:						Tuple       ):





    """simple docstring"""



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

 def 		lowercase_    (			self			:						str       ):





    """simple docstring"""



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







class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__):

 def 		lowercase_    (			self			:						str       ):





    """simple docstring"""



    UpperCamelCase__			    =    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			:						Optional[Any]       ):





    """simple docstring"""



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







class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__):

 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



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

 def 		lowercase_    (			self			:						Tuple       ):





    """simple docstring"""



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







class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__):

 def 		lowercase_    (			self			:						Optional[Any]       ):





    """simple docstring"""



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

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





    """simple docstring"""



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







class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__):

 def 		lowercase_    (			self			:						str       ):





    """simple docstring"""



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

 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



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

 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



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

 def 		lowercase_    (			self			:						Optional[Any]       ):





    """simple docstring"""



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







class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__):

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





    """simple docstring"""



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

 def 		lowercase_    (			self			:						str       ):





    """simple docstring"""



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

 def 		lowercase_    (			self			:						Dict       ):





    """simple docstring"""



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

 def 		lowercase_    (			self			:						Dict       ):





    """simple docstring"""



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







class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__):

 def 		lowercase_    (			self			:						Dict       ):





    """simple docstring"""



    UpperCamelCase__			    =    DatasetInfo(task_templates=QuestionAnsweringExtractive()       )
    UpperCamelCase__			    =    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_			:						Optional[Any]       ):
       return x

    def dont_keep_task(a_			:						Dict       ):
       UpperCamelCase__			    =    deepcopy(a_       )
       UpperCamelCase__			    =    0
       return out

    UpperCamelCase__			    =    dataset.map(a_       )
    assert mapped_dataset.info.task_templates == dataset.info.task_templates
    # reload from cache
    UpperCamelCase__			    =    dataset.map(a_       )
    assert mapped_dataset.info.task_templates == dataset.info.task_templates

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

 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



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

    def process(a_			:						Union[str, Any]       ):
       return example

    UpperCamelCase__			    =    dataset.remove_columns("label"       )
    UpperCamelCase__			    =    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 OwlViTImageProcessor







class 			UpperCAmelCase			(							unittest.TestCase):

 def __init__(			self			:						Optional[Any],       a_			:						Optional[int],       a_			:						Dict=7,       a_			:						List[str]=3,       a_			:						int=18,       a_			:						Tuple=30,       a_			:						Any=400,       a_			:						Optional[int]=True,       a_			:						Optional[int]=None,       a_			:						Any=True,       a_			:						Optional[int]=None,       a_			:						int=True,       a_			:						Optional[int]=[0.48_145_466, 0.4_578_275, 0.40_821_073],       a_			:						Optional[Any]=[0.26_862_954, 0.26_130_258, 0.27_577_711],       a_			:						Optional[int]=True,       ):





    """simple docstring"""



    UpperCamelCase__			    =    parent
    UpperCamelCase__			    =    batch_size
    UpperCamelCase__			    =    num_channels
    UpperCamelCase__			    =    image_size
    UpperCamelCase__			    =    min_resolution
    UpperCamelCase__			    =    max_resolution
    UpperCamelCase__			    =    do_resize
    UpperCamelCase__			    =    size if size is not None else {"height": 18, "width": 18}
    UpperCamelCase__			    =    do_center_crop
    UpperCamelCase__			    =    crop_size if crop_size is not None else {"height": 18, "width": 18}
    UpperCamelCase__			    =    do_normalize
    UpperCamelCase__			    =    image_mean
    UpperCamelCase__			    =    image_std
    UpperCamelCase__			    =    do_convert_rgb

 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



    return {
        "do_resize": self.do_resize,
        "size": self.size,
        "do_center_crop": self.do_center_crop,
        "crop_size": self.crop_size,
        "do_normalize": self.do_normalize,
        "image_mean": self.image_mean,
        "image_std": self.image_std,
        "do_convert_rgb": self.do_convert_rgb,
    }







@require_torch
@require_vision
class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__		,      unittest.TestCase):
 _lowerCamelCase			:       Tuple            =       OwlViTImageProcessor if is_vision_available() else None

 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    UpperCamelCase__			    =    OwlViTImageProcessingTester(self       )

 @property
 def 		lowercase_    (			self			:						str       ):





    """simple docstring"""



    return self.image_processor_tester.prepare_image_processor_dict()

 def 		lowercase_    (			self			:						Tuple       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class(**self.image_processor_dict       )
    self.assertTrue(hasattr(a_,       "do_resize"       )       )
    self.assertTrue(hasattr(a_,       "size"       )       )
    self.assertTrue(hasattr(a_,       "do_center_crop"       )       )
    self.assertTrue(hasattr(a_,       "center_crop"       )       )
    self.assertTrue(hasattr(a_,       "do_normalize"       )       )
    self.assertTrue(hasattr(a_,       "image_mean"       )       )
    self.assertTrue(hasattr(a_,       "image_std"       )       )
    self.assertTrue(hasattr(a_,       "do_convert_rgb"       )       )

 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class.from_dict(self.image_processor_dict       )
    self.assertEqual(image_processor.size,       {"height": 18, "width": 18}       )
    self.assertEqual(image_processor.crop_size,       {"height": 18, "width": 18}       )

    UpperCamelCase__			    =    self.image_processing_class.from_dict(self.image_processor_dict,       size=42,       crop_size=84       )
    self.assertEqual(image_processor.size,       {"height": 42, "width": 42}       )
    self.assertEqual(image_processor.crop_size,       {"height": 84, "width": 84}       )

 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class(**self.image_processor_dict       )
    # create random PIL images
    UpperCamelCase__			    =    prepare_image_inputs(self.image_processor_tester,       equal_resolution=a_       )

    for image in image_inputs:
       self.assertIsInstance(a_,       Image.Image       )

    # Test not batched input
    UpperCamelCase__			    =    image_processing(image_inputs[0],       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )

    # Test batched
    UpperCamelCase__			    =    image_processing(a_,       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )

 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class(**self.image_processor_dict       )
    # create random numpy tensors
    UpperCamelCase__			    =    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
    UpperCamelCase__			    =    image_processing(image_inputs[0],       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )

    # Test batched
    UpperCamelCase__			    =    image_processing(a_,       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )

 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.image_processing_class(**self.image_processor_dict       )
    # create random PyTorch tensors
    UpperCamelCase__			    =    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
    UpperCamelCase__			    =    image_processing(image_inputs[0],       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )

    # Test batched
    UpperCamelCase__			    =    image_processing(a_,       return_tensors="pt"       ).pixel_values
    self.assertEqual(
        encoded_images.shape,       (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),       )