




"""simple docstring"""

import warnings
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from .configuration_utils import ConfigMixin, register_to_config
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate






class     A__      (      SCREAMING_SNAKE_CASE__     ):
	A_							:				Any						     =      CONFIG_NAME




	@register_to_config
	def __init__(   self  :	List[str]      ,    lowercase  :	List[str] = True      ,    lowercase  :	Union[str, Any] = 8      ,    lowercase  :	Union[str, Any] = "lanczos"      ,    lowercase  :	Union[str, Any] = True      ,    lowercase  :	List[Any] = False      ,    )					-> List[str]:
						super().__init__()




	@staticmethod
	def 							a_		(   lowercase  :	int	)					-> PIL.Image.Image:



						if images.ndim == 3:
											__snake_case          =	images[None, ...]
						__snake_case          =	(images * 255).round().astype("""uint8"""	)
						if images.shape[-1] == 1:
											# special case for grayscale (single channel) images
											__snake_case          =	[Image.fromarray(image.squeeze()      ,    mode="""L"""	) for image in images]
						else:
											__snake_case          =	[Image.fromarray(lowercase	) for image in images]

						return pil_images




	@staticmethod
	def 							a_		(   lowercase  :	int	)					-> np.ndarray:



						if not isinstance(lowercase      ,    lowercase	):
											__snake_case          =	[images]
						__snake_case          =	[np.array(lowercase	).astype(np.floataa	) / 255.0 for image in images]
						__snake_case          =	np.stack(lowercase      ,    axis=0	)

						return images




	@staticmethod
	def 							a_		(   lowercase  :	Dict	)					-> torch.FloatTensor:



						if images.ndim == 3:
											__snake_case          =	images[..., None]

						__snake_case          =	torch.from_numpy(images.transpose(0      ,    3      ,    1      ,    2	)	)
						return images




	@staticmethod
	def 							a_		(   lowercase  :	List[Any]	)					-> np.ndarray:
						__snake_case          =	images.cpu().permute(0      ,    2      ,    3      ,    1	).float().numpy()
						return images




	@staticmethod
	def 							a_		(   lowercase  :	Dict	)					-> str:
						return 2.0 * images - 1.0




	@staticmethod
	def 							a_		(   lowercase  :	str	)					-> Tuple:
						return (images / 2 + 0.5).clamp(0      ,    1	)




	@staticmethod
	def 							a_		(   lowercase  :	Tuple	)					-> PIL.Image.Image:
						__snake_case          =	image.convert("""RGB"""	)
						return image




	def 							a_		(   self  :	List[Any]      ,    lowercase  :	str      ,    lowercase  :	Dict = None      ,    lowercase  :	Optional[int] = None      ,    )					-> PIL.Image.Image:



						if height is None:
											__snake_case          =	image.height
						if width is None:
											__snake_case          =	image.width

						__snake_case      ,      __snake_case          =	(
						    x - x % self.config.vae_scale_factor for x in (width, height)
						)  # resize to integer multiple of vae_scale_factor
						__snake_case          =	image.resize((width, height)      ,    resample=PIL_INTERPOLATION[self.config.resample]	)
						return image




	def 							a_		(   self  :	int      ,    lowercase  :	List[Any]      ,    lowercase  :	Union[str, Any] = None      ,    lowercase  :	Dict = None      ,    )					-> torch.Tensor:
						__snake_case          =	(PIL.Image.Image, np.ndarray, torch.Tensor)
						if isinstance(lowercase      ,    lowercase	):
											__snake_case          =	[image]
						elif not (isinstance(lowercase      ,    lowercase	) and all(isinstance(lowercase      ,    lowercase	) for i in image	)):
											raise ValueError(
											    f'''Input is in incorrect format: {[type(lowercase	) for i in image]}. Currently, we only support {", ".join(lowercase	)}'''	)

						if isinstance(image[0]      ,    PIL.Image.Image	):
											if self.config.do_convert_rgb:
																__snake_case          =	[self.convert_to_rgb(lowercase	) for i in image]
											if self.config.do_resize:
																__snake_case          =	[self.resize(lowercase      ,    lowercase      ,    lowercase	) for i in image]
											__snake_case          =	self.pil_to_numpy(lowercase	)  # to np
											__snake_case          =	self.numpy_to_pt(lowercase	)  # to pt

						elif isinstance(image[0]      ,    np.ndarray	):
											__snake_case          =	np.concatenate(lowercase      ,    axis=0	) if image[0].ndim == 4 else np.stack(lowercase      ,    axis=0	)
											__snake_case          =	self.numpy_to_pt(lowercase	)
											__snake_case      ,      __snake_case      ,      __snake_case      ,      __snake_case          =	image.shape
											if self.config.do_resize and (
											    height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
											):
																raise ValueError(
																    f'''Currently we only support resizing for PIL image - please resize your numpy array to be divisible by {self.config.vae_scale_factor}'''
																    f'''currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor'''	)

						elif isinstance(image[0]      ,    torch.Tensor	):
											__snake_case          =	torch.cat(lowercase      ,    axis=0	) if image[0].ndim == 4 else torch.stack(lowercase      ,    axis=0	)
											__snake_case      ,      __snake_case      ,      __snake_case      ,      __snake_case          =	image.shape

											# don't need any preprocess if the image is latents
											if channel == 4:
																return image

											if self.config.do_resize and (
											    height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
											):
																raise ValueError(
																    f'''Currently we only support resizing for PIL image - please resize your pytorch tensor to be divisible by {self.config.vae_scale_factor}'''
																    f'''currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor'''	)

        # expected range [0,1], normalize to [-1,1]
						__snake_case          =	self.config.do_normalize
						if image.min() < 0:
											warnings.warn(
											    """Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] """
											    f'''when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]'''      ,    lowercase      ,    )
											__snake_case          =	False

						if do_normalize:
											__snake_case          =	self.normalize(lowercase	)

						return image




	def 							a_		(   self  :	str      ,    lowercase  :	Any      ,    lowercase  :	Tuple = "pil"      ,    lowercase  :	Union[str, Any] = None      ,    )					-> Any:



						if not isinstance(lowercase      ,    torch.Tensor	):
											raise ValueError(
											    f'''Input for postprocessing is in incorrect format: {type(lowercase	)}. We only support pytorch tensor'''	)
						if output_type not in ["latent", "pt", "np", "pil"]:
											__snake_case          =	(
											    f'''the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: '''
											    """`pil`, `np`, `pt`, `latent`"""
											)
											deprecate("""Unsupported output_type"""      ,    """1.0.0"""      ,    lowercase      ,    standard_warn=lowercase	)
											__snake_case          =	"""np"""

						if output_type == "latent":
											return image

						if do_denormalize is None:
											__snake_case          =	[self.config.do_normalize] * image.shape[0]

						__snake_case          =	torch.stack(
						    [self.denormalize(image[i]	) if do_denormalize[i] else image[i] for i in range(image.shape[0]	)]	)

						if output_type == "pt":
											return image

						__snake_case          =	self.pt_to_numpy(lowercase	)

						if output_type == "np":
											return image

						if output_type == "pil":
											return self.numpy_to_pil(lowercase	)






class     A__      (      SCREAMING_SNAKE_CASE__     ):
	A_							:				int						     =      CONFIG_NAME




	@register_to_config
	def __init__(   self  :	Union[str, Any]      ,    lowercase  :	Union[str, Any] = True      ,    lowercase  :	Tuple = 8      ,    lowercase  :	Optional[int] = "lanczos"      ,    lowercase  :	int = True      ,    )					-> List[str]:
						super().__init__()




	@staticmethod
	def 							a_		(   lowercase  :	Tuple	)					-> Tuple:



						if images.ndim == 3:
											__snake_case          =	images[None, ...]
						__snake_case          =	(images * 255).round().astype("""uint8"""	)
						if images.shape[-1] == 1:
											# special case for grayscale (single channel) images
											__snake_case          =	[Image.fromarray(image.squeeze()      ,    mode="""L"""	) for image in images]
						else:
											__snake_case          =	[Image.fromarray(image[:, :, :3]	) for image in images]

						return pil_images




	@staticmethod
	def 							a_		(   lowercase  :	Dict	)					-> Optional[Any]:
						return image[:, :, 1] * 2**8 + image[:, :, 2]




	def 							a_		(   self  :	Union[str, Any]      ,    lowercase  :	Any	)					-> Optional[int]:



						if images.ndim == 3:
											__snake_case          =	images[None, ...]
						__snake_case          =	images[:, :, :, 3:]
						if images.shape[-1] == 6:
											__snake_case          =	(images_depth * 255).round().astype("""uint8"""	)
											__snake_case          =	[
											    Image.fromarray(self.rgblike_to_depthmap(lowercase	)      ,    mode="""I;16"""	) for image_depth in images_depth
											]
						elif images.shape[-1] == 4:
											__snake_case          =	(images_depth * 65_535.0).astype(np.uintaa	)
											__snake_case          =	[Image.fromarray(lowercase      ,    mode="""I;16"""	) for image_depth in images_depth]
						else:
											raise Exception("""Not supported"""	)

						return pil_images




	def 							a_		(   self  :	Union[str, Any]      ,    lowercase  :	Optional[Any]      ,    lowercase  :	Optional[Any] = "pil"      ,    lowercase  :	Optional[int] = None      ,    )					-> Union[str, Any]:



						if not isinstance(lowercase      ,    torch.Tensor	):
											raise ValueError(
											    f'''Input for postprocessing is in incorrect format: {type(lowercase	)}. We only support pytorch tensor'''	)
						if output_type not in ["latent", "pt", "np", "pil"]:
											__snake_case          =	(
											    f'''the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: '''
											    """`pil`, `np`, `pt`, `latent`"""
											)
											deprecate("""Unsupported output_type"""      ,    """1.0.0"""      ,    lowercase      ,    standard_warn=lowercase	)
											__snake_case          =	"""np"""

						if do_denormalize is None:
											__snake_case          =	[self.config.do_normalize] * image.shape[0]

						__snake_case          =	torch.stack(
						    [self.denormalize(image[i]	) if do_denormalize[i] else image[i] for i in range(image.shape[0]	)]	)

						__snake_case          =	self.pt_to_numpy(lowercase	)

						if output_type == "np":
											if image.shape[-1] == 6:
																__snake_case          =	np.stack([self.rgblike_to_depthmap(im[:, :, 3:]	) for im in image]      ,    axis=0	)
											else:
																__snake_case          =	image[:, :, :, 3:]
											return image[:, :, :, :3], image_depth

						if output_type == "pil":
											return self.numpy_to_pil(lowercase	), self.numpy_to_depth(lowercase	)
						else:
											raise Exception(f'''This type {output_type} is not supported'''	)








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


UpperCamelCase__ :    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": [5_15]},
}




@pytest.mark.parametrize(
    """task_cls"""				,					[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]				,					)
def       snake_case__	(       lowerCAmelCase   :		Optional[int]		):
					__snake_case          =	task_cls()
					__snake_case          =	asdict(lowerCAmelCase		)
					__snake_case          =	task_template_from_dict(lowerCAmelCase		)
					assert task == reloaded
class     A__      :




	def 							a_		(   self  :	Tuple	)					-> int:
						__snake_case          =	LanguageModeling(text_column="""input_text"""	)
						assert {"input_text": "text"} == task.column_mapping




	def 							a_		(   self  :	Union[str, Any]	)					-> List[Any]:
						__snake_case          =	Features({"""text""": Value("""string"""	)}	)
						__snake_case          =	{"""text_column""": """input_text"""}
						__snake_case          =	LanguageModeling.from_dict(lowercase	)
						assert "language-modeling" == task.task
						assert input_schema == task.input_schema

class     A__      (      lowercase_     ):




	def 							a_		(   self  :	str	)					-> Any:
						__snake_case          =	sorted(["""pos""", """neg"""]	)




	def 							a_		(   self  :	str	)					-> Union[str, Any]:
						__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  :	int	)					-> List[Any]:
						__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(lowercase	)
						self.assertEqual("""text-classification"""      ,    task.task	)
						self.assertEqual(lowercase      ,    task.input_schema	)
						self.assertEqual(lowercase      ,    task.label_schema	)




	def 							a_		(   self  :	Union[str, Any]	)					-> List[Any]:
						__snake_case          =	TextClassification(text_column="""input_text"""      ,    label_column="""input_label"""	)
						self.assertEqual(task.label_schema["""labels"""]      ,    lowercase	)
						__snake_case          =	task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels	)}	)	)
						self.assertEqual(task.label_schema["""labels"""]      ,    ClassLabel(names=self.labels	)	)

class     A__      (      lowercase_     ):




	def 							a_		(   self  :	Any	)					-> Tuple:
						__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  :	int	)					-> Tuple:
						__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(lowercase	)
						self.assertEqual("""question-answering-extractive"""      ,    task.task	)
						self.assertEqual(lowercase      ,    task.input_schema	)
						self.assertEqual(lowercase      ,    task.label_schema	)

class     A__      (      lowercase_     ):




	def 							a_		(   self  :	Any	)					-> Union[str, Any]:
						__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  :	List[Any]	)					-> Dict:
						__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(lowercase	)
						self.assertEqual("""summarization"""      ,    task.task	)
						self.assertEqual(lowercase      ,    task.input_schema	)
						self.assertEqual(lowercase      ,    task.label_schema	)

class     A__      (      lowercase_     ):




	def 							a_		(   self  :	Any	)					-> int:
						__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  :	Dict	)					-> List[str]:
						__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(lowercase	)
						self.assertEqual("""automatic-speech-recognition"""      ,    task.task	)
						self.assertEqual(lowercase      ,    task.input_schema	)
						self.assertEqual(lowercase      ,    task.label_schema	)

class     A__      (      lowercase_     ):




	def 							a_		(   self  :	int	)					-> Union[str, Any]:
						__snake_case          =	sorted(["""pos""", """neg"""]	)




	def 							a_		(   self  :	Optional[int]	)					-> str:
						__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  :	Union[str, Any]	)					-> Any:
						__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(lowercase	)
						self.assertEqual("""audio-classification"""      ,    task.task	)
						self.assertEqual(lowercase      ,    task.input_schema	)
						self.assertEqual(lowercase      ,    task.label_schema	)




	def 							a_		(   self  :	Optional[Any]	)					-> Optional[int]:
						__snake_case          =	AudioClassification(audio_column="""input_audio"""      ,    label_column="""input_label"""	)
						self.assertEqual(task.label_schema["""labels"""]      ,    lowercase	)
						__snake_case          =	task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels	)}	)	)
						self.assertEqual(task.label_schema["""labels"""]      ,    ClassLabel(names=self.labels	)	)

class     A__      (      lowercase_     ):




	def 							a_		(   self  :	Optional[int]	)					-> str:
						__snake_case          =	sorted(["""pos""", """neg"""]	)




	def 							a_		(   self  :	Optional[int]	)					-> List[str]:
						__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[Any]	)					-> int:
						__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(lowercase	)
						self.assertEqual("""image-classification"""      ,    task.task	)
						self.assertEqual(lowercase      ,    task.input_schema	)
						self.assertEqual(lowercase      ,    task.label_schema	)




	def 							a_		(   self  :	Optional[int]	)					-> Any:
						__snake_case          =	ImageClassification(image_column="""input_image"""      ,    label_column="""input_label"""	)
						self.assertEqual(task.label_schema["""labels"""]      ,    lowercase	)
						__snake_case          =	task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels	)}	)	)
						self.assertEqual(task.label_schema["""labels"""]      ,    ClassLabel(names=self.labels	)	)

class     A__      (      lowercase_     ):




	def 							a_		(   self  :	str	)					-> str:
						__snake_case          =	DatasetInfo(task_templates=QuestionAnsweringExtractive()	)
						__snake_case          =	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  :	Tuple	):
											return x

						def dont_keep_task(lowercase  :	List[str]	):
											__snake_case          =	deepcopy(lowercase	)
											__snake_case          =	0
											return out

						__snake_case          =	dataset.map(lowercase	)
						assert mapped_dataset.info.task_templates == dataset.info.task_templates
						# reload from cache
						__snake_case          =	dataset.map(lowercase	)
						assert mapped_dataset.info.task_templates == dataset.info.task_templates

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




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

						def process(lowercase  :	List[Any]	):
											return example

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


