


import textwrap

import pyarrow as pa
import pytest

from datasets import Features, Image
from datasets.packaged_modules.text.text import Text

from ..utils import require_pil






@pytest.fixture
def 		a__       (							A__							):
			SCREAMING_SNAKE_CASE_						:			List[Any]       						= tmp_path / 'text.txt'
			SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= textwrap.dedent(
			    '\\n        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n\n        Second paragraph:\n        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n        '							)
			with open(A__,	'w',	encoding='utf-8'							) as f:
						f.write(A__							)
			return str(A__							)






@pytest.fixture
def 		a__       (							A__,	A__							):
			SCREAMING_SNAKE_CASE_						:			Dict       						= tmp_path / 'text_with_image.txt'
			with open(A__,	'w',	encoding='utf-8'							) as f:
						f.write(A__							)
			return str(A__							)






@pytest.mark.parametrize('keep_linebreaks',	[True, False]							)
def 		a__       (							A__,	A__							):
			with open(A__,	encoding='utf-8'							) as f:
						SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= f.read().splitlines(keepends=A__							)
			SCREAMING_SNAKE_CASE_						:			Dict       						= Text(keep_linebreaks=A__,	encoding='utf-8'							)
			SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= text._generate_tables([[text_file]]							)
			SCREAMING_SNAKE_CASE_						:			Any       						= pa.concat_tables([table for _, table in generator]							).to_pydict()['text']
			assert generated_content == expected_content






@require_pil
def 		a__       (							A__							):
			with open(A__,	encoding='utf-8'							) as f:
						SCREAMING_SNAKE_CASE_						:			int       						= f.read().splitlines()[0]
			SCREAMING_SNAKE_CASE_						:			Tuple       						= Text(encoding='utf-8',	features=Features({'image': Image()}							)							)
			SCREAMING_SNAKE_CASE_						:			List[Any]       						= text._generate_tables([[text_file_with_image]]							)
			SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= pa.concat_tables([table for _, table in generator]							)
			assert pa_table.schema.field('image'							).type == Image()()
			SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= pa_table.to_pydict()['image']
			assert generated_content == [{"path": image_file, "bytes": None}]






@pytest.mark.parametrize('sample_by',	['line', 'paragraph', 'document']							)
def 		a__       (							A__,	A__							):
			with open(A__,	encoding='utf-8'							) as f:
						SCREAMING_SNAKE_CASE_						:			str       						= f.read()
			if sample_by == "line":
						SCREAMING_SNAKE_CASE_						:			Optional[int]       						= expected_content.splitlines()
			elif sample_by == "paragraph":
						SCREAMING_SNAKE_CASE_						:			List[Any]       						= expected_content.split('\n\n'							)
			elif sample_by == "document":
						SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= [expected_content]
			SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= Text(sample_by=A__,	encoding='utf-8',	chunksize=1_0_0							)
			SCREAMING_SNAKE_CASE_						:			Dict       						= text._generate_tables([[text_file]]							)
			SCREAMING_SNAKE_CASE_						:			str       						= pa.concat_tables([table for _, table in generator]							).to_pydict()['text']
			assert generated_content == expected_content









import inspect
import unittest

from transformers import DataaVecVisionConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import (
				    MODEL_MAPPING,
				    DataaVecVisionForImageClassification,
				    DataaVecVisionForSemanticSegmentation,
				    DataaVecVisionModel,
				)
				from transformers.models.dataavec.modeling_dataavec_vision import DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import BeitImageProcessor







class      __lowercase  :





							"""simple docstring"""







							def __init__(	self       ,		lowerCAmelCase__       ,		lowerCAmelCase__=1_0_0       ,		lowerCAmelCase__=1_3       ,		lowerCAmelCase__=3_0       ,		lowerCAmelCase__=2       ,		lowerCAmelCase__=3       ,		lowerCAmelCase__=True       ,		lowerCAmelCase__=True       ,		lowerCAmelCase__=3_2       ,		lowerCAmelCase__=4       ,		lowerCAmelCase__=4       ,		lowerCAmelCase__=3_7       ,		lowerCAmelCase__="gelu"       ,		lowerCAmelCase__=0.1       ,		lowerCAmelCase__=0.1       ,		lowerCAmelCase__=1_0       ,		lowerCAmelCase__=0.02       ,		lowerCAmelCase__=3       ,		lowerCAmelCase__=None       ,		lowerCAmelCase__=[0, 1, 2, 3]       ,		):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Tuple       						= parent
										SCREAMING_SNAKE_CASE_						:			Tuple       						= 1_0_0
										SCREAMING_SNAKE_CASE_						:			int       						= batch_size
										SCREAMING_SNAKE_CASE_						:			str       						= image_size
										SCREAMING_SNAKE_CASE_						:			str       						= patch_size
										SCREAMING_SNAKE_CASE_						:			str       						= num_channels
										SCREAMING_SNAKE_CASE_						:			List[Any]       						= is_training
										SCREAMING_SNAKE_CASE_						:			Any       						= use_labels
										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= hidden_size
										SCREAMING_SNAKE_CASE_						:			Tuple       						= num_hidden_layers
										SCREAMING_SNAKE_CASE_						:			Dict       						= num_attention_heads
										SCREAMING_SNAKE_CASE_						:			Any       						= intermediate_size
										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= hidden_act
										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= hidden_dropout_prob
										SCREAMING_SNAKE_CASE_						:			List[Any]       						= attention_probs_dropout_prob
										SCREAMING_SNAKE_CASE_						:			Tuple       						= type_sequence_label_size
										SCREAMING_SNAKE_CASE_						:			str       						= initializer_range
										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= scope
										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= out_indices
										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= num_labels

										# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
										SCREAMING_SNAKE_CASE_						:			List[str]       						= (image_size // patch_size) ** 2
										SCREAMING_SNAKE_CASE_						:			Union[str, Any]       						= num_patches + 1






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Dict       						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= None
										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= None
										if self.use_labels:
													SCREAMING_SNAKE_CASE_						:			List[str]       						= ids_tensor([self.batch_size]       ,		self.type_sequence_label_size    )
													SCREAMING_SNAKE_CASE_						:			Tuple       						= ids_tensor([self.batch_size, self.image_size, self.image_size]       ,		self.num_labels    )

										SCREAMING_SNAKE_CASE_						:			str       						= self.get_config()

										return config, pixel_values, labels, pixel_labels






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										return DataaVecVisionConfig(
										    vocab_size=self.vocab_size       ,		image_size=self.image_size       ,		patch_size=self.patch_size       ,		num_channels=self.num_channels       ,		hidden_size=self.hidden_size       ,		num_hidden_layers=self.num_hidden_layers       ,		num_attention_heads=self.num_attention_heads       ,		intermediate_size=self.intermediate_size       ,		hidden_act=self.hidden_act       ,		hidden_dropout_prob=self.hidden_dropout_prob       ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,		is_decoder=lowerCAmelCase__       ,		initializer_range=self.initializer_range       ,		out_indices=self.out_indices       ,		)






							def  UpperCamelCase__			(	self       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= DataaVecVisionModel(config=lowerCAmelCase__    )
										model.to(lowerCAmelCase__    )
										model.eval()
										SCREAMING_SNAKE_CASE_						:			Dict       						= model(lowerCAmelCase__    )
										# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= (self.image_size // self.patch_size) ** 2
										self.parent.assertEqual(result.last_hidden_state.shape       ,		(self.batch_size, num_patches + 1, self.hidden_size)    )






							def  UpperCamelCase__			(	self       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= self.type_sequence_label_size
										SCREAMING_SNAKE_CASE_						:			Tuple       						= DataaVecVisionForImageClassification(lowerCAmelCase__    )
										model.to(lowerCAmelCase__    )
										model.eval()
										SCREAMING_SNAKE_CASE_						:			int       						= model(lowerCAmelCase__       ,		labels=lowerCAmelCase__    )
										self.parent.assertEqual(result.logits.shape       ,		(self.batch_size, self.type_sequence_label_size)    )






							def  UpperCamelCase__			(	self       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= self.num_labels
										SCREAMING_SNAKE_CASE_						:			List[Any]       						= DataaVecVisionForSemanticSegmentation(lowerCAmelCase__    )
										model.to(lowerCAmelCase__    )
										model.eval()
										SCREAMING_SNAKE_CASE_						:			Dict       						= model(lowerCAmelCase__    )
										self.parent.assertEqual(
										    result.logits.shape       ,		(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)    )
										SCREAMING_SNAKE_CASE_						:			List[Any]       						= model(lowerCAmelCase__       ,		labels=lowerCAmelCase__    )
										self.parent.assertEqual(
										    result.logits.shape       ,		(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= self.prepare_config_and_inputs()
										SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			List[Any]       						= config_and_inputs
										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= {'pixel_values': pixel_values}
										return config, inputs_dict







@require_torch
class      __lowercase  (__SCREAMING_SNAKE_CASE     ,    __SCREAMING_SNAKE_CASE     ,    unittest.TestCase   ):





							"""simple docstring"""







							_UpperCAmelCase     =		(
							    (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
							    if is_torch_available()
							    else ()
							)
							_UpperCAmelCase     =		(
							    {
							        """feature-extraction""": DataaVecVisionModel,
							        """image-classification""": DataaVecVisionForImageClassification,
							        """image-segmentation""": DataaVecVisionForSemanticSegmentation,
							    }
							    if is_torch_available()
							    else {}
							)

							_UpperCAmelCase     =		False
							_UpperCAmelCase     =		False
							_UpperCAmelCase     =		False






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Tuple       						= DataaVecVisionModelTester(self    )
										SCREAMING_SNAKE_CASE_						:			int       						= ConfigTester(
										    self       ,		config_class=lowerCAmelCase__       ,		has_text_modality=lowerCAmelCase__       ,		hidden_size=3_7    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										self.config_tester.run_common_tests()






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										pass






							@require_torch_multi_gpu
							@unittest.skip(
							    reason='Data2VecVision has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'    )
							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										pass






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			Dict       						= self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= model_class(lowerCAmelCase__    )
													self.assertIsInstance(model.get_input_embeddings()       ,		(nn.Module)    )
													SCREAMING_SNAKE_CASE_						:			List[str]       						= model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(lowerCAmelCase__       ,		nn.Linear    )    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			str       						= self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= model_class(lowerCAmelCase__    )
													SCREAMING_SNAKE_CASE_						:			Optional[int]       						= inspect.signature(model.forward    )
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													SCREAMING_SNAKE_CASE_						:			str       						= [*signature.parameters.keys()]

													SCREAMING_SNAKE_CASE_						:			Optional[int]       						= ['pixel_values']
													self.assertListEqual(arg_names[:1]       ,		lowerCAmelCase__    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			int       						= self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase__    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			str       						= self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_segmentation(*lowerCAmelCase__    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										if not self.model_tester.is_training:
													return

										SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			Union[str, Any]       						= self.model_tester.prepare_config_and_inputs_for_common()
										SCREAMING_SNAKE_CASE_						:			str       						= True

										for model_class in self.all_model_classes:
													if model_class in [*get_values(lowerCAmelCase__    )]:
																continue

													SCREAMING_SNAKE_CASE_						:			Union[str, Any]       						= model_class(lowerCAmelCase__    )
													model.to(lowerCAmelCase__    )
													model.train()
													SCREAMING_SNAKE_CASE_						:			Union[str, Any]       						= self._prepare_for_class(lowerCAmelCase__       ,		lowerCAmelCase__       ,		return_labels=lowerCAmelCase__    )
													SCREAMING_SNAKE_CASE_						:			Any       						= model(**lowerCAmelCase__    ).loss
													loss.backward()






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			Any       						= self.model_tester.prepare_config_and_inputs_for_common()
										if not self.model_tester.is_training:
													return

										SCREAMING_SNAKE_CASE_						:			Tuple       						= False
										SCREAMING_SNAKE_CASE_						:			Any       						= True

										for model_class in self.all_model_classes:
													if model_class in [*get_values(lowerCAmelCase__    )] or not model_class.supports_gradient_checkpointing:
																continue
													# TODO: remove the following 3 lines once we have a MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
													# this can then be incorporated into _prepare_for_class in test_modeling_common.py
													elif model_class.__name__ == "Data2VecVisionForSemanticSegmentation":
																SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			str       						= inputs_dict['pixel_values'].shape
																SCREAMING_SNAKE_CASE_						:			Optional[int]       						= torch.zeros(
																    [self.model_tester.batch_size, height, width]       ,		device=lowerCAmelCase__    ).long()
													SCREAMING_SNAKE_CASE_						:			Tuple       						= model_class(lowerCAmelCase__    )
													model.gradient_checkpointing_enable()
													model.to(lowerCAmelCase__    )
													model.train()
													SCREAMING_SNAKE_CASE_						:			str       						= self._prepare_for_class(lowerCAmelCase__       ,		lowerCAmelCase__       ,		return_labels=lowerCAmelCase__    )
													SCREAMING_SNAKE_CASE_						:			Dict       						= model(**lowerCAmelCase__    ).loss
													loss.backward()






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			List[Any]       						= self.model_tester.prepare_config_and_inputs_for_common()

										SCREAMING_SNAKE_CASE_						:			str       						= _config_zero_init(lowerCAmelCase__    )
										for model_class in self.all_model_classes:
													SCREAMING_SNAKE_CASE_						:			List[Any]       						= model_class(config=lowerCAmelCase__    )
													for name, param in model.named_parameters():
																# we skip lambda parameters as these require special initial values
																# determined by config.layer_scale_init_value
																if "lambda" in name:
																			continue
																if param.requires_grad:
																			self.assertIn(
																			    ((param.data.mean() * 1E9).round() / 1E9).item()       ,		[0.0, 1.0]       ,		msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''       ,		)






							def  UpperCamelCase__			(	self       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__=2E-4       ,		lowerCAmelCase__="outputs"       ,		lowerCAmelCase__=None    ):





										"""simple docstring"""




										super().check_pt_tf_outputs(lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			List[str]       						= self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__    )






							@slow
							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													SCREAMING_SNAKE_CASE_						:			Any       						= DataaVecVisionModel.from_pretrained(lowerCAmelCase__    )
													self.assertIsNotNone(lowerCAmelCase__    )







def 		a__       (							):
			SCREAMING_SNAKE_CASE_						:			List[Any]       						= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
			return image







@require_torch
@require_vision
class      __lowercase  (unittest.TestCase   ):





							"""simple docstring"""







							@cached_property
							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										return (
										    BeitImageProcessor.from_pretrained('facebook/data2vec-vision-base-ft1k'    ) if is_vision_available() else None
										)






							@slow
							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= DataaVecVisionForImageClassification.from_pretrained('facebook/data2vec-vision-base-ft1k'    ).to(
										    lowerCAmelCase__    )

										SCREAMING_SNAKE_CASE_						:			Dict       						= self.default_image_processor
										SCREAMING_SNAKE_CASE_						:			List[Any]       						= prepare_img()
										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= image_processor(images=lowerCAmelCase__       ,		return_tensors='pt'    ).to(lowerCAmelCase__    )

										# forward pass
										with torch.no_grad():
													SCREAMING_SNAKE_CASE_						:			List[str]       						= model(**lowerCAmelCase__    )
										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= outputs.logits

										# verify the logits
										SCREAMING_SNAKE_CASE_						:			Tuple       						= torch.Size((1, 1_0_0_0)    )
										self.assertEqual(logits.shape       ,		lowerCAmelCase__    )

										SCREAMING_SNAKE_CASE_						:			Any       						= torch.tensor([0.3_277, -0.1_395, 0.0_911]    ).to(lowerCAmelCase__    )

										self.assertTrue(torch.allclose(logits[0, :3]       ,		lowerCAmelCase__       ,		atol=1E-4    )    )

										SCREAMING_SNAKE_CASE_						:			Tuple       						= [model.config.labelaid[i] for i in ['remote control, remote', 'tabby, tabby cat']]
										self.assertEqual(logits[0].topk(2    ).indices.cpu().tolist()       ,		lowerCAmelCase__    )





