




import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

				if is_vision_available():
								from transformers import MaskaFormerImageProcessor

if is_vision_available():
				from PIL import Image




class       _A				:






		def __init__(    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE=2						,		_SCREAMING_SNAKE_CASE=True						,		_SCREAMING_SNAKE_CASE=False						,		_SCREAMING_SNAKE_CASE=10						,		_SCREAMING_SNAKE_CASE=3						,		_SCREAMING_SNAKE_CASE=32 * 8						,		_SCREAMING_SNAKE_CASE=32 * 8						,		_SCREAMING_SNAKE_CASE=4						,		_SCREAMING_SNAKE_CASE=64						,		):
								_UpperCAmelCase      =			parent
								_UpperCAmelCase      =			batch_size
								_UpperCAmelCase      =			is_training
								_UpperCAmelCase      =			use_auxiliary_loss
								_UpperCAmelCase      =			num_queries
								_UpperCAmelCase      =			num_channels
								_UpperCAmelCase      =			min_size
								_UpperCAmelCase      =			max_size
								_UpperCAmelCase      =			num_labels
								_UpperCAmelCase      =			hidden_dim
								_UpperCAmelCase      =			hidden_dim






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]			).to(
								    _SCREAMING_SNAKE_CASE			)

								_UpperCAmelCase      =			torch.ones([self.batch_size, self.min_size, self.max_size]						,		device=_SCREAMING_SNAKE_CASE			)

								_UpperCAmelCase      =			(
								    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]						,		device=_SCREAMING_SNAKE_CASE			) > 0.5
								).float()
								_UpperCAmelCase      =			(torch.rand((self.batch_size, self.num_labels)						,		device=_SCREAMING_SNAKE_CASE			) > 0.5).long()

								_UpperCAmelCase      =			self.get_config()
								return config, pixel_values, pixel_mask, mask_labels, class_labels






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			MaskaFormerConfig(
								    hidden_size=self.hidden_dim						,		)
								_UpperCAmelCase      =			self.num_queries
								_UpperCAmelCase      =			self.num_labels

								_UpperCAmelCase      =			[1, 1, 1, 1]
								_UpperCAmelCase      =			self.num_channels

								_UpperCAmelCase      =			64
								_UpperCAmelCase      =			128
								_UpperCAmelCase      =			self.hidden_dim
								_UpperCAmelCase      =			self.hidden_dim
								_UpperCAmelCase      =			self.hidden_dim
								return config






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase    ,					_UpperCAmelCase    ,					_UpperCAmelCase    ,					_UpperCAmelCase    ,					_UpperCAmelCase      =			self.prepare_config_and_inputs()
								_UpperCAmelCase      =			{"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
								return config, inputs_dict






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
								_UpperCAmelCase      =			output.encoder_hidden_states
								_UpperCAmelCase      =			output.pixel_decoder_hidden_states
								_UpperCAmelCase      =			output.transformer_decoder_hidden_states

								self.parent.assertTrue(len(_SCREAMING_SNAKE_CASE			)						,		len(config.backbone_config.depths			)			)
								self.parent.assertTrue(len(_SCREAMING_SNAKE_CASE			)						,		len(config.backbone_config.depths			)			)
								self.parent.assertTrue(len(_SCREAMING_SNAKE_CASE			)						,		config.decoder_layers			)






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE=False			):
								with torch.no_grad():
														_UpperCAmelCase      =			MaskaFormerModel(config=_SCREAMING_SNAKE_CASE			)
														model.to(_SCREAMING_SNAKE_CASE			)
														model.eval()

														_UpperCAmelCase      =			model(pixel_values=_SCREAMING_SNAKE_CASE						,		pixel_mask=_SCREAMING_SNAKE_CASE			)
														_UpperCAmelCase      =			model(_SCREAMING_SNAKE_CASE						,		output_hidden_states=_SCREAMING_SNAKE_CASE			)

								self.parent.assertEqual(
								    output.transformer_decoder_last_hidden_state.shape						,		(self.batch_size, self.num_queries, self.hidden_dim)						,		)
								# let's ensure the other two hidden state exists
								self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None			)
								self.parent.assertTrue(output.encoder_last_hidden_state is not None			)

								if output_hidden_states:
														self.check_output_hidden_state(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
								_UpperCAmelCase      =			MaskaFormerForUniversalSegmentation(config=_SCREAMING_SNAKE_CASE			)
								model.to(_SCREAMING_SNAKE_CASE			)
								model.eval()

								def comm_check_on_output(_SCREAMING_SNAKE_CASE			):
														# let's still check that all the required stuff is there
														self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None			)
														self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None			)
														self.parent.assertTrue(result.encoder_last_hidden_state is not None			)
														# okay, now we need to check the logits shape
														# due to the encoder compression, masks have a //4 spatial size
														self.parent.assertEqual(
														    result.masks_queries_logits.shape						,		(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)						,		)
														# + 1 for null class
														self.parent.assertEqual(
														    result.class_queries_logits.shape						,		(self.batch_size, self.num_queries, self.num_labels + 1)			)

								with torch.no_grad():
														_UpperCAmelCase      =			model(pixel_values=_SCREAMING_SNAKE_CASE						,		pixel_mask=_SCREAMING_SNAKE_CASE			)
														_UpperCAmelCase      =			model(_SCREAMING_SNAKE_CASE			)

														comm_check_on_output(_SCREAMING_SNAKE_CASE			)

														_UpperCAmelCase      =			model(
														    pixel_values=_SCREAMING_SNAKE_CASE						,		pixel_mask=_SCREAMING_SNAKE_CASE						,		mask_labels=_SCREAMING_SNAKE_CASE						,		class_labels=_SCREAMING_SNAKE_CASE			)

								comm_check_on_output(_SCREAMING_SNAKE_CASE			)

								self.parent.assertTrue(result.loss is not None			)
								self.parent.assertEqual(result.loss.shape						,		torch.Size([1]			)			)




@require_torch
class       _A				(		__lowercase       ,     __lowercase       ,     unittest.TestCase     ):
		__a					    =       (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
		__a					    =       {"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {}

		__a					    =       False
		__a					    =       False
		__a					    =       False
		__a					    =       False






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			MaskaFormerModelTester(self			)
								_UpperCAmelCase      =			ConfigTester(self						,		config_class=_SCREAMING_SNAKE_CASE						,		has_text_modality=_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self			):
								self.config_tester.run_common_tests()






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase    ,					_UpperCAmelCase      =			self.model_tester.prepare_config_and_inputs_for_common()
								self.model_tester.create_and_check_maskaformer_model(_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE						,		output_hidden_states=_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_SCREAMING_SNAKE_CASE			)






		@unittest.skip(reason="""Mask2Former does not use inputs_embeds"""			)
		def 				UpperCAmelCase (    self			):
								pass






		@unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method"""			)
		def 				UpperCAmelCase (    self			):
								pass






		@unittest.skip(reason="""Mask2Former is not a generative model"""			)
		def 				UpperCAmelCase (    self			):
								pass






		@unittest.skip(reason="""Mask2Former does not use token embeddings"""			)
		def 				UpperCAmelCase (    self			):
								pass






		@require_torch_multi_gpu
		@unittest.skip(
		    reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""			)
		def 				UpperCAmelCase (    self			):
								pass






		@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""			)
		def 				UpperCAmelCase (    self			):
								pass






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase    ,					_UpperCAmelCase      =			self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
														_UpperCAmelCase      =			model_class(_SCREAMING_SNAKE_CASE			)
														_UpperCAmelCase      =			inspect.signature(model.forward			)
														# signature.parameters is an OrderedDict => so arg_names order is deterministic
														_UpperCAmelCase      =			[*signature.parameters.keys()]

														_UpperCAmelCase      =			["""pixel_values"""]
														self.assertListEqual(arg_names[:1]						,		_SCREAMING_SNAKE_CASE			)






		@slow
		def 				UpperCAmelCase (    self			):
								for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
														_UpperCAmelCase      =			MaskaFormerModel.from_pretrained(_SCREAMING_SNAKE_CASE			)
														self.assertIsNotNone(_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			(self.model_tester.min_size,) * 2
								_UpperCAmelCase      =			{
								    """pixel_values""": torch.randn((2, 3, *size)						,		device=_SCREAMING_SNAKE_CASE			),
								    """mask_labels""": torch.randn((2, 10, *size)						,		device=_SCREAMING_SNAKE_CASE			),
								    """class_labels""": torch.zeros(2						,		10						,		device=_SCREAMING_SNAKE_CASE			).long(),
								}
								_UpperCAmelCase      =			self.model_tester.get_config()

								_UpperCAmelCase      =			MaskaFormerForUniversalSegmentation(_SCREAMING_SNAKE_CASE			).to(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			model(**_SCREAMING_SNAKE_CASE			)
								self.assertTrue(outputs.loss is not None			)






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase    ,					_UpperCAmelCase      =			self.model_tester.prepare_config_and_inputs_for_common()
								self.model_tester.create_and_check_maskaformer_model(_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE						,		output_hidden_states=_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase    ,					_UpperCAmelCase      =			self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
														_UpperCAmelCase      =			model_class(_SCREAMING_SNAKE_CASE			).to(_SCREAMING_SNAKE_CASE			)
														_UpperCAmelCase      =			model(**_SCREAMING_SNAKE_CASE						,		output_attentions=_SCREAMING_SNAKE_CASE			)
														self.assertTrue(outputs.attentions is not None			)






		def 				UpperCAmelCase (    self			):
								if not self.model_tester.is_training:
														return

								_UpperCAmelCase      =			self.all_model_classes[1]
								_UpperCAmelCase    ,					_UpperCAmelCase    ,					_UpperCAmelCase    ,					_UpperCAmelCase    ,					_UpperCAmelCase      =			self.model_tester.prepare_config_and_inputs()

								_UpperCAmelCase      =			model_class(_SCREAMING_SNAKE_CASE			)
								model.to(_SCREAMING_SNAKE_CASE			)
								model.train()

								_UpperCAmelCase      =			model(_SCREAMING_SNAKE_CASE						,		mask_labels=_SCREAMING_SNAKE_CASE						,		class_labels=_SCREAMING_SNAKE_CASE			).loss
								loss.backward()






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			self.all_model_classes[1]
								_UpperCAmelCase    ,					_UpperCAmelCase    ,					_UpperCAmelCase    ,					_UpperCAmelCase    ,					_UpperCAmelCase      =			self.model_tester.prepare_config_and_inputs()
								_UpperCAmelCase      =			True
								_UpperCAmelCase      =			True

								_UpperCAmelCase      =			model_class(_SCREAMING_SNAKE_CASE			).to(_SCREAMING_SNAKE_CASE			)
								model.train()

								_UpperCAmelCase      =			model(_SCREAMING_SNAKE_CASE						,		mask_labels=_SCREAMING_SNAKE_CASE						,		class_labels=_SCREAMING_SNAKE_CASE			)

								_UpperCAmelCase      =			outputs.encoder_hidden_states[0]
								encoder_hidden_states.retain_grad()

								_UpperCAmelCase      =			outputs.pixel_decoder_hidden_states[0]
								pixel_decoder_hidden_states.retain_grad()

								_UpperCAmelCase      =			outputs.transformer_decoder_hidden_states[0]
								transformer_decoder_hidden_states.retain_grad()

								_UpperCAmelCase      =			outputs.attentions[0]
								attentions.retain_grad()

								outputs.loss.backward(retain_graph=_SCREAMING_SNAKE_CASE			)

								self.assertIsNotNone(encoder_hidden_states.grad			)
								self.assertIsNotNone(pixel_decoder_hidden_states.grad			)
								self.assertIsNotNone(transformer_decoder_hidden_states.grad			)
								self.assertIsNotNone(attentions.grad			)



a													=			1E-4




def        _SCREAMING_SNAKE_CASE      (		)						->				Optional[int]:
						_UpperCAmelCase      =			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""       )
						return image




@require_vision
@slow
class       _A				(		unittest.TestCase     ):






		@cached_property
		def 				UpperCAmelCase (    self			):
								return "facebook/mask2former-swin-small-coco-instance"






		@cached_property
		def 				UpperCAmelCase (    self			):
								return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints			) if is_vision_available() else None






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			MaskaFormerModel.from_pretrained(self.model_checkpoints			).to(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			self.default_image_processor
								_UpperCAmelCase      =			prepare_img()
								_UpperCAmelCase      =			image_processor(_SCREAMING_SNAKE_CASE						,		return_tensors="""pt"""			).to(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			inputs["""pixel_values"""].shape
								# check size is divisible by 32
								self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0			)
								# check size
								self.assertEqual(_SCREAMING_SNAKE_CASE						,		(1, 3, 384, 384)			)

								with torch.no_grad():
														_UpperCAmelCase      =			model(**_SCREAMING_SNAKE_CASE			)

								_UpperCAmelCase      =			torch.tensor(
								    [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]]			).to(_SCREAMING_SNAKE_CASE			)
								self.assertTrue(
								    torch.allclose(
								        outputs.encoder_last_hidden_state[0, 0, :3, :3]						,		_SCREAMING_SNAKE_CASE						,		atol=_SCREAMING_SNAKE_CASE			)			)

								_UpperCAmelCase      =			torch.tensor(
								    [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]]			).to(_SCREAMING_SNAKE_CASE			)
								self.assertTrue(
								    torch.allclose(
								        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]						,		_SCREAMING_SNAKE_CASE						,		atol=_SCREAMING_SNAKE_CASE			)			)

								_UpperCAmelCase      =			torch.tensor(
								    [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]]			).to(_SCREAMING_SNAKE_CASE			)
								self.assertTrue(
								    torch.allclose(
								        outputs.transformer_decoder_last_hidden_state[0, :3, :3]						,		_SCREAMING_SNAKE_CASE						,		atol=_SCREAMING_SNAKE_CASE			)			)






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints			).to(_SCREAMING_SNAKE_CASE			).eval()
								_UpperCAmelCase      =			self.default_image_processor
								_UpperCAmelCase      =			prepare_img()
								_UpperCAmelCase      =			image_processor(_SCREAMING_SNAKE_CASE						,		return_tensors="""pt"""			).to(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			inputs["""pixel_values"""].shape
								# check size is divisible by 32
								self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0			)
								# check size
								self.assertEqual(_SCREAMING_SNAKE_CASE						,		(1, 3, 384, 384)			)

								with torch.no_grad():
														_UpperCAmelCase      =			model(**_SCREAMING_SNAKE_CASE			)
								# masks_queries_logits
								_UpperCAmelCase      =			outputs.masks_queries_logits
								self.assertEqual(
								    masks_queries_logits.shape						,		(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)			)
								_UpperCAmelCase      =			[
								    [-8.7839, -9.0056, -8.8121],
								    [-7.4104, -7.0313, -6.5401],
								    [-6.6105, -6.3427, -6.4675],
								]
								_UpperCAmelCase      =			torch.tensor(_SCREAMING_SNAKE_CASE			).to(_SCREAMING_SNAKE_CASE			)
								self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]						,		_SCREAMING_SNAKE_CASE						,		atol=_SCREAMING_SNAKE_CASE			)			)
								# class_queries_logits
								_UpperCAmelCase      =			outputs.class_queries_logits
								self.assertEqual(class_queries_logits.shape						,		(1, model.config.num_queries, model.config.num_labels + 1)			)
								_UpperCAmelCase      =			torch.tensor(
								    [
								        [1.8324, -8.0835, -4.1922],
								        [0.8450, -9.0050, -3.6053],
								        [0.3045, -7.7293, -3.0275],
								    ]			).to(_SCREAMING_SNAKE_CASE			)
								self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]						,		_SCREAMING_SNAKE_CASE						,		atol=_SCREAMING_SNAKE_CASE			)			)






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints			).to(_SCREAMING_SNAKE_CASE			).eval()
								_UpperCAmelCase      =			self.default_image_processor

								_UpperCAmelCase      =			image_processor(
								    [np.zeros((3, 800, 1333)			), np.zeros((3, 800, 1333)			)]						,		segmentation_maps=[np.zeros((384, 384)			).astype(np.floataa			), np.zeros((384, 384)			).astype(np.floataa			)]						,		return_tensors="""pt"""						,		)

								_UpperCAmelCase      =			inputs["""pixel_values"""].to(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			[el.to(_SCREAMING_SNAKE_CASE			) for el in inputs["""mask_labels"""]]
								_UpperCAmelCase      =			[el.to(_SCREAMING_SNAKE_CASE			) for el in inputs["""class_labels"""]]

								with torch.no_grad():
														_UpperCAmelCase      =			model(**_SCREAMING_SNAKE_CASE			)

								self.assertTrue(outputs.loss is not None			)





import io
import json

import fsspec
import pytest

from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.json import JsonDatasetReader, JsonDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases




def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case       )						->				int:
						assert isinstance(snake_case			,     snake_case       )
						assert dataset.num_rows == 4
						assert dataset.num_columns == 3
						assert dataset.column_names == ["col_1", "col_2", "col_3"]
						for feature, expected_dtype in expected_features.items():
												assert dataset.features[feature].dtype == expected_dtype




@pytest.mark.parametrize("""keep_in_memory"""			,     [False, True]       )
def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case			,     snake_case       )						->				Optional[int]:
						_UpperCAmelCase      =			tmp_path / """cache"""
						_UpperCAmelCase      =			{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
						with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
												_UpperCAmelCase      =			JsonDatasetReader(snake_case			,     cache_dir=snake_case			,     keep_in_memory=snake_case       ).read()
						_check_json_dataset(snake_case			,     snake_case       )




@pytest.mark.parametrize(
    """features"""			,     [
        None,
        {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""},
        {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""},
        {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""},
        {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""},
    ]			,     )
def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case			,     snake_case       )						->				Optional[Any]:
						_UpperCAmelCase      =			tmp_path / """cache"""
						_UpperCAmelCase      =			{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
						_UpperCAmelCase      =			features.copy() if features else default_expected_features
						_UpperCAmelCase      =			(
						    Features({feature: Value(snake_case       ) for feature, dtype in features.items()}       ) if features is not None else None
						)
						_UpperCAmelCase      =			JsonDatasetReader(snake_case			,     features=snake_case			,     cache_dir=snake_case       ).read()
						_check_json_dataset(snake_case			,     snake_case       )




@pytest.mark.parametrize(
    """features"""			,     [
        None,
        {"""col_3""": """float64""", """col_1""": """string""", """col_2""": """int64"""},
    ]			,     )
def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case			,     snake_case       )						->				int:
						_UpperCAmelCase      =			tmp_path / """cache"""
						_UpperCAmelCase      =			{"""col_3""": """float64""", """col_1""": """string""", """col_2""": """int64"""}
						_UpperCAmelCase      =			features.copy() if features else default_expected_features
						_UpperCAmelCase      =			(
						    Features({feature: Value(snake_case       ) for feature, dtype in features.items()}       ) if features is not None else None
						)
						_UpperCAmelCase      =			JsonDatasetReader(snake_case			,     features=snake_case			,     cache_dir=snake_case       ).read()
						assert isinstance(snake_case			,     snake_case       )
						assert dataset.num_rows == 2
						assert dataset.num_columns == 3
						assert dataset.column_names == ["col_3", "col_1", "col_2"]
						for feature, expected_dtype in expected_features.items():
												assert dataset.features[feature].dtype == expected_dtype




def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case       )						->				Optional[int]:
						# jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"}
						_UpperCAmelCase      =			{"""col_2""": """int64""", """col_3""": """float64""", """col_1""": """string"""}
						_UpperCAmelCase      =			features.copy()
						_UpperCAmelCase      =			(
						    Features({feature: Value(snake_case       ) for feature, dtype in features.items()}       ) if features is not None else None
						)
						_UpperCAmelCase      =			tmp_path / """cache"""
						_UpperCAmelCase      =			JsonDatasetReader(snake_case			,     features=snake_case			,     cache_dir=snake_case       ).read()
						assert isinstance(snake_case			,     snake_case       )
						assert dataset.num_rows == 2
						assert dataset.num_columns == 3
						assert dataset.column_names == ["col_2", "col_3", "col_1"]
						for feature, expected_dtype in expected_features.items():
												assert dataset.features[feature].dtype == expected_dtype




@pytest.mark.parametrize("""split"""			,     [None, NamedSplit("""train"""       ), """train""", """test"""]       )
def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case			,     snake_case       )						->				List[Any]:
						_UpperCAmelCase      =			tmp_path / """cache"""
						_UpperCAmelCase      =			{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
						_UpperCAmelCase      =			JsonDatasetReader(snake_case			,     cache_dir=snake_case			,     split=snake_case       ).read()
						_check_json_dataset(snake_case			,     snake_case       )
						assert dataset.split == split if split else "train"




@pytest.mark.parametrize("""path_type"""			,     [str, list]       )
def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case			,     snake_case       )						->				Any:
						if issubclass(snake_case			,     snake_case       ):
												_UpperCAmelCase      =			jsonl_path
						elif issubclass(snake_case			,     snake_case       ):
												_UpperCAmelCase      =			[jsonl_path]
						_UpperCAmelCase      =			tmp_path / """cache"""
						_UpperCAmelCase      =			{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
						_UpperCAmelCase      =			JsonDatasetReader(snake_case			,     cache_dir=snake_case       ).read()
						_check_json_dataset(snake_case			,     snake_case       )




def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case			,     snake_case=("train",)       )						->				str:
						assert isinstance(snake_case			,     snake_case       )
						for split in splits:
												_UpperCAmelCase      =			dataset_dict[split]
												assert dataset.num_rows == 4
												assert dataset.num_columns == 3
												assert dataset.column_names == ["col_1", "col_2", "col_3"]
												for feature, expected_dtype in expected_features.items():
																		assert dataset.features[feature].dtype == expected_dtype




@pytest.mark.parametrize("""keep_in_memory"""			,     [False, True]       )
def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case			,     snake_case       )						->				str:
						_UpperCAmelCase      =			tmp_path / """cache"""
						_UpperCAmelCase      =			{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
						with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
												_UpperCAmelCase      =			JsonDatasetReader({"""train""": jsonl_path}			,     cache_dir=snake_case			,     keep_in_memory=snake_case       ).read()
						_check_json_datasetdict(snake_case			,     snake_case       )




@pytest.mark.parametrize(
    """features"""			,     [
        None,
        {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""},
        {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""},
        {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""},
        {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""},
    ]			,     )
def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case			,     snake_case       )						->				Tuple:
						_UpperCAmelCase      =			tmp_path / """cache"""
						_UpperCAmelCase      =			{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
						_UpperCAmelCase      =			features.copy() if features else default_expected_features
						_UpperCAmelCase      =			(
						    Features({feature: Value(snake_case       ) for feature, dtype in features.items()}       ) if features is not None else None
						)
						_UpperCAmelCase      =			JsonDatasetReader({"""train""": jsonl_path}			,     features=snake_case			,     cache_dir=snake_case       ).read()
						_check_json_datasetdict(snake_case			,     snake_case       )




@pytest.mark.parametrize("""split"""			,     [None, NamedSplit("""train"""       ), """train""", """test"""]       )
def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case			,     snake_case       )						->				Optional[Any]:
						if split:
												_UpperCAmelCase      =			{split: jsonl_path}
						else:
												_UpperCAmelCase      =			"""train"""
												_UpperCAmelCase      =			{"""train""": jsonl_path, """test""": jsonl_path}
						_UpperCAmelCase      =			tmp_path / """cache"""
						_UpperCAmelCase      =			{"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}
						_UpperCAmelCase      =			JsonDatasetReader(snake_case			,     cache_dir=snake_case       ).read()
						_check_json_datasetdict(snake_case			,     snake_case			,     splits=list(path.keys()       )       )
						assert all(dataset[split].split == split for split in path.keys()       )




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				List[Any]:
						return json.load(snake_case       )




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				List[Any]:
						return [json.loads(snake_case       ) for line in buffer]




class       _A				:






		@pytest.mark.parametrize("""lines, load_json_function"""						,		[(True, load_json_lines), (False, load_json)]			)
		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
								with io.BytesIO() as buffer:
														JsonDatasetWriter(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		lines=_SCREAMING_SNAKE_CASE			).write()
														buffer.seek(0			)
														_UpperCAmelCase      =			load_json_function(_SCREAMING_SNAKE_CASE			)
								assert isinstance(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)
								assert isinstance(exported_content[0]						,		_SCREAMING_SNAKE_CASE			)
								assert len(_SCREAMING_SNAKE_CASE			) == 10






		@pytest.mark.parametrize(
		    """orient, container, keys, len_at"""						,		[
		        ("""records""", list, {"""tokens""", """labels""", """answers""", """id"""}, None),
		        ("""split""", dict, {"""columns""", """data"""}, """data"""),
		        ("""index""", dict, set("""0123456789"""			), None),
		        ("""columns""", dict, {"""tokens""", """labels""", """answers""", """id"""}, """tokens"""),
		        ("""values""", list, None, None),
		        ("""table""", dict, {"""schema""", """data"""}, """data"""),
		    ]						,		)
		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
								with io.BytesIO() as buffer:
														JsonDatasetWriter(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		lines=_SCREAMING_SNAKE_CASE						,		orient=_SCREAMING_SNAKE_CASE			).write()
														buffer.seek(0			)
														_UpperCAmelCase      =			load_json(_SCREAMING_SNAKE_CASE			)
								assert isinstance(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)
								if keys:
														if container is dict:
																				assert exported_content.keys() == keys
														else:
																				assert exported_content[0].keys() == keys
								else:
														assert not hasattr(_SCREAMING_SNAKE_CASE						,		"""keys"""			) and not hasattr(exported_content[0]						,		"""keys"""			)
								if len_at:
														assert len(exported_content[len_at]			) == 10
								else:
														assert len(_SCREAMING_SNAKE_CASE			) == 10






		@pytest.mark.parametrize("""lines, load_json_function"""						,		[(True, load_json_lines), (False, load_json)]			)
		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
								with io.BytesIO() as buffer:
														JsonDatasetWriter(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		lines=_SCREAMING_SNAKE_CASE						,		num_proc=2			).write()
														buffer.seek(0			)
														_UpperCAmelCase      =			load_json_function(_SCREAMING_SNAKE_CASE			)
								assert isinstance(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)
								assert isinstance(exported_content[0]						,		_SCREAMING_SNAKE_CASE			)
								assert len(_SCREAMING_SNAKE_CASE			) == 10






		@pytest.mark.parametrize(
		    """orient, container, keys, len_at"""						,		[
		        ("""records""", list, {"""tokens""", """labels""", """answers""", """id"""}, None),
		        ("""split""", dict, {"""columns""", """data"""}, """data"""),
		        ("""index""", dict, set("""0123456789"""			), None),
		        ("""columns""", dict, {"""tokens""", """labels""", """answers""", """id"""}, """tokens"""),
		        ("""values""", list, None, None),
		        ("""table""", dict, {"""schema""", """data"""}, """data"""),
		    ]						,		)
		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
								with io.BytesIO() as buffer:
														JsonDatasetWriter(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		lines=_SCREAMING_SNAKE_CASE						,		orient=_SCREAMING_SNAKE_CASE						,		num_proc=2			).write()
														buffer.seek(0			)
														_UpperCAmelCase      =			load_json(_SCREAMING_SNAKE_CASE			)
								assert isinstance(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)
								if keys:
														if container is dict:
																				assert exported_content.keys() == keys
														else:
																				assert exported_content[0].keys() == keys
								else:
														assert not hasattr(_SCREAMING_SNAKE_CASE						,		"""keys"""			) and not hasattr(exported_content[0]						,		"""keys"""			)
								if len_at:
														assert len(exported_content[len_at]			) == 10
								else:
														assert len(_SCREAMING_SNAKE_CASE			) == 10






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE			):
								with pytest.raises(_SCREAMING_SNAKE_CASE			):
														with io.BytesIO() as buffer:
																				JsonDatasetWriter(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		num_proc=0			)






		@pytest.mark.parametrize("""compression, extension"""						,		[("""gzip""", """gz"""), ("""bz2""", """bz2"""), ("""xz""", """xz""")]			)
		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
								_UpperCAmelCase      =			tmp_path_factory.mktemp("""data"""			) / F"test.json.{extension}"
								_UpperCAmelCase      =			str(shared_datadir / F"test_file.json.{extension}"			)
								JsonDatasetWriter(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		compression=_SCREAMING_SNAKE_CASE			).write()

								with fsspec.open(_SCREAMING_SNAKE_CASE						,		"""rb"""						,		compression="""infer"""			) as f:
														_UpperCAmelCase      =			f.read()
								with fsspec.open(_SCREAMING_SNAKE_CASE						,		"""rb"""						,		compression="""infer"""			) as f:
														_UpperCAmelCase      =			f.read()
								assert exported_content == original_content