




'''simple docstring'''


import gc
import unittest

import numpy as np
import torch
from torch.backends.cuda import sdp_kernel

from diffusers import (
    CMStochasticIterativeScheduler,
    ConsistencyModelPipeline,
    UNetaDModel,
)
from diffusers.utils import randn_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class     A					(	_a  ,unittest.TestCase					):
							lowercase_           =       ConsistencyModelPipeline
							lowercase_           =       UNCONDITIONAL_IMAGE_GENERATION_PARAMS
							lowercase_           =       UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

							# Override required_optional_params to remove num_images_per_prompt
							lowercase_           =       frozenset(
							    [
							        'num_inference_steps',
							        'generator',
							        'latents',
							        'output_type',
							        'return_dict',
							        'callback',
							        'callback_steps',
							    ]					)







							@property
							def      __lowerCAmelCase    (						self :						Optional[int]      )    ->							Optional[int]:


														"""simple docstring"""


														_a			  =       UNetaDModel.from_pretrained(
														    '''diffusers/consistency-models-test'''							,    subfolder='''test_unet'''							,    )
														return unet







							@property
							def      __lowerCAmelCase    (						self :						List[str]      )    ->							Tuple:


														"""simple docstring"""


														_a			  =       UNetaDModel.from_pretrained(
														    '''diffusers/consistency-models-test'''							,    subfolder='''test_unet_class_cond'''							,    )
														return unet







							def      __lowerCAmelCase    (						self :						Optional[int]							,    lowerCAmelCase_ :						Dict=False      )    ->							Optional[Any]:


														"""simple docstring"""


														if class_cond:
																					_a			  =       self.dummy_cond_unet
														else:
																					_a			  =       self.dummy_uncond_unet

														# Default to CM multistep sampler
														_a			  =       CMStochasticIterativeScheduler(
														    num_train_timesteps=40							,    sigma_min=0.0_0_2							,    sigma_max=8_0.0							,    )

														_a			  =       {
														    '''unet''': unet,
														    '''scheduler''': scheduler,
														}

														return components







							def      __lowerCAmelCase    (						self :						Optional[int]							,    lowerCAmelCase_ :						List[Any]							,    lowerCAmelCase_ :						List[str]=0      )    ->							Tuple:


														"""simple docstring"""


														if str(lowerCAmelCase_      ).startswith('''mps'''      ):
																					_a			  =       torch.manual_seed(lowerCAmelCase_      )
														else:
																					_a			  =       torch.Generator(device=lowerCAmelCase_      ).manual_seed(lowerCAmelCase_      )

														_a			  =       {
														    '''batch_size''': 1,
														    '''num_inference_steps''': None,
														    '''timesteps''': [22, 0],
														    '''generator''': generator,
														    '''output_type''': '''np''',
														}

														return inputs







							def      __lowerCAmelCase    (						self :						int      )    ->							Optional[Any]:


														"""simple docstring"""


														_a			  =       '''cpu'''  # ensure determinism for the device-dependent torch.Generator
														_a			  =       self.get_dummy_components()
														_a			  =       ConsistencyModelPipeline(**lowerCAmelCase_      )
														_a			  =       pipe.to(lowerCAmelCase_      )
														pipe.set_progress_bar_config(disable=lowerCAmelCase_      )

														_a			  =       self.get_dummy_inputs(lowerCAmelCase_      )
														_a			  =       pipe(**lowerCAmelCase_      ).images
														assert image.shape == (1, 32, 32, 3)

														_a			  =       image[0, -3:, -3:, -1]
														_a			  =       np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4]      )

														assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3







							def      __lowerCAmelCase    (						self :						int      )    ->							Any:


														"""simple docstring"""


														_a			  =       '''cpu'''  # ensure determinism for the device-dependent torch.Generator
														_a			  =       self.get_dummy_components(class_cond=lowerCAmelCase_      )
														_a			  =       ConsistencyModelPipeline(**lowerCAmelCase_      )
														_a			  =       pipe.to(lowerCAmelCase_      )
														pipe.set_progress_bar_config(disable=lowerCAmelCase_      )

														_a			  =       self.get_dummy_inputs(lowerCAmelCase_      )
														_a			  =       0
														_a			  =       pipe(**lowerCAmelCase_      ).images
														assert image.shape == (1, 32, 32, 3)

														_a			  =       image[0, -3:, -3:, -1]
														_a			  =       np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4]      )

														assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3







							def      __lowerCAmelCase    (						self :						Tuple      )    ->							Optional[Any]:


														"""simple docstring"""


														_a			  =       '''cpu'''  # ensure determinism for the device-dependent torch.Generator
														_a			  =       self.get_dummy_components()
														_a			  =       ConsistencyModelPipeline(**lowerCAmelCase_      )
														_a			  =       pipe.to(lowerCAmelCase_      )
														pipe.set_progress_bar_config(disable=lowerCAmelCase_      )

														_a			  =       self.get_dummy_inputs(lowerCAmelCase_      )
														_a			  =       1
														_a			  =       None
														_a			  =       pipe(**lowerCAmelCase_      ).images
														assert image.shape == (1, 32, 32, 3)

														_a			  =       image[0, -3:, -3:, -1]
														_a			  =       np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7]      )

														assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3







							def      __lowerCAmelCase    (						self :						Dict      )    ->							Dict:


														"""simple docstring"""


														_a			  =       '''cpu'''  # ensure determinism for the device-dependent torch.Generator
														_a			  =       self.get_dummy_components(class_cond=lowerCAmelCase_      )
														_a			  =       ConsistencyModelPipeline(**lowerCAmelCase_      )
														_a			  =       pipe.to(lowerCAmelCase_      )
														pipe.set_progress_bar_config(disable=lowerCAmelCase_      )

														_a			  =       self.get_dummy_inputs(lowerCAmelCase_      )
														_a			  =       1
														_a			  =       None
														_a			  =       0
														_a			  =       pipe(**lowerCAmelCase_      ).images
														assert image.shape == (1, 32, 32, 3)

														_a			  =       image[0, -3:, -3:, -1]
														_a			  =       np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7]      )

														assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3



@slow
@require_torch_gpu
class     A					(	unittest.TestCase					):







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


														"""simple docstring"""


														super().tearDown()
														gc.collect()
														torch.cuda.empty_cache()







							def      __lowerCAmelCase    (						self :						Tuple							,    lowerCAmelCase_ :						Optional[Any]=0							,    lowerCAmelCase_ :						str=False							,    lowerCAmelCase_ :						Any="cpu"							,    lowerCAmelCase_ :						Union[str, Any]=torch.floataa							,    lowerCAmelCase_ :						Union[str, Any]=(1, 3, 64, 64)      )    ->							Union[str, Any]:


														"""simple docstring"""


														_a			  =       torch.manual_seed(lowerCAmelCase_      )

														_a			  =       {
														    '''num_inference_steps''': None,
														    '''timesteps''': [22, 0],
														    '''class_labels''': 0,
														    '''generator''': generator,
														    '''output_type''': '''np''',
														}

														if get_fixed_latents:
																					_a			  =       self.get_fixed_latents(seed=lowerCAmelCase_							,    device=lowerCAmelCase_							,    dtype=lowerCAmelCase_							,    shape=lowerCAmelCase_      )
																					_a			  =       latents

														return inputs







							def      __lowerCAmelCase    (						self :						Any							,    lowerCAmelCase_ :						str=0							,    lowerCAmelCase_ :						Dict="cpu"							,    lowerCAmelCase_ :						List[str]=torch.floataa							,    lowerCAmelCase_ :						str=(1, 3, 64, 64)      )    ->							Any:


														"""simple docstring"""


														if type(lowerCAmelCase_      ) == str:
																					_a			  =       torch.device(lowerCAmelCase_      )
														_a			  =       torch.Generator(device=lowerCAmelCase_      ).manual_seed(lowerCAmelCase_      )
														_a			  =       randn_tensor(lowerCAmelCase_							,    generator=lowerCAmelCase_							,    device=lowerCAmelCase_							,    dtype=lowerCAmelCase_      )
														return latents







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


														"""simple docstring"""


														_a			  =       UNetaDModel.from_pretrained('''diffusers/consistency_models'''							,    subfolder='''diffusers_cd_imagenet64_l2'''      )
														_a			  =       CMStochasticIterativeScheduler(
														    num_train_timesteps=40							,    sigma_min=0.0_0_2							,    sigma_max=8_0.0							,    )
														_a			  =       ConsistencyModelPipeline(unet=lowerCAmelCase_							,    scheduler=lowerCAmelCase_      )
														pipe.to(torch_device=lowerCAmelCase_      )
														pipe.set_progress_bar_config(disable=lowerCAmelCase_      )

														_a			  =       self.get_inputs()
														_a			  =       pipe(**lowerCAmelCase_      ).images
														assert image.shape == (1, 64, 64, 3)

														_a			  =       image[0, -3:, -3:, -1]

														_a			  =       np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4]      )

														assert np.abs(image_slice.flatten() - expected_slice      ).max() < 2e-2







							def      __lowerCAmelCase    (						self :						Optional[Any]      )    ->							Optional[int]:


														"""simple docstring"""


														_a			  =       UNetaDModel.from_pretrained('''diffusers/consistency_models'''							,    subfolder='''diffusers_cd_imagenet64_l2'''      )
														_a			  =       CMStochasticIterativeScheduler(
														    num_train_timesteps=40							,    sigma_min=0.0_0_2							,    sigma_max=8_0.0							,    )
														_a			  =       ConsistencyModelPipeline(unet=lowerCAmelCase_							,    scheduler=lowerCAmelCase_      )
														pipe.to(torch_device=lowerCAmelCase_      )
														pipe.set_progress_bar_config(disable=lowerCAmelCase_      )

														_a			  =       self.get_inputs()
														_a			  =       1
														_a			  =       None
														_a			  =       pipe(**lowerCAmelCase_      ).images
														assert image.shape == (1, 64, 64, 3)

														_a			  =       image[0, -3:, -3:, -1]

														_a			  =       np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7]      )

														assert np.abs(image_slice.flatten() - expected_slice      ).max() < 2e-2







							@require_torch_a
							def      __lowerCAmelCase    (						self :						int      )    ->							Any:


														"""simple docstring"""


														_a			  =       UNetaDModel.from_pretrained('''diffusers/consistency_models'''							,    subfolder='''diffusers_cd_imagenet64_l2'''      )
														_a			  =       CMStochasticIterativeScheduler(
														    num_train_timesteps=40							,    sigma_min=0.0_0_2							,    sigma_max=8_0.0							,    )
														_a			  =       ConsistencyModelPipeline(unet=lowerCAmelCase_							,    scheduler=lowerCAmelCase_      )
														pipe.to(torch_device=lowerCAmelCase_							,    torch_dtype=torch.floataa      )
														pipe.set_progress_bar_config(disable=lowerCAmelCase_      )

														_a			  =       self.get_inputs(get_fixed_latents=lowerCAmelCase_							,    device=lowerCAmelCase_      )
														# Ensure usage of flash attention in torch 2.0
														with sdp_kernel(enable_flash=lowerCAmelCase_							,    enable_math=lowerCAmelCase_							,    enable_mem_efficient=lowerCAmelCase_      ):
																					_a			  =       pipe(**lowerCAmelCase_      ).images
														assert image.shape == (1, 64, 64, 3)

														_a			  =       image[0, -3:, -3:, -1]

														_a			  =       np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3]      )

														assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3







							@require_torch_a
							def      __lowerCAmelCase    (						self :						List[str]      )    ->							List[Any]:


														"""simple docstring"""


														_a			  =       UNetaDModel.from_pretrained('''diffusers/consistency_models'''							,    subfolder='''diffusers_cd_imagenet64_l2'''      )
														_a			  =       CMStochasticIterativeScheduler(
														    num_train_timesteps=40							,    sigma_min=0.0_0_2							,    sigma_max=8_0.0							,    )
														_a			  =       ConsistencyModelPipeline(unet=lowerCAmelCase_							,    scheduler=lowerCAmelCase_      )
														pipe.to(torch_device=lowerCAmelCase_							,    torch_dtype=torch.floataa      )
														pipe.set_progress_bar_config(disable=lowerCAmelCase_      )

														_a			  =       self.get_inputs(get_fixed_latents=lowerCAmelCase_							,    device=lowerCAmelCase_      )
														_a			  =       1
														_a			  =       None
														# Ensure usage of flash attention in torch 2.0
														with sdp_kernel(enable_flash=lowerCAmelCase_							,    enable_math=lowerCAmelCase_							,    enable_mem_efficient=lowerCAmelCase_      ):
																					_a			  =       pipe(**lowerCAmelCase_      ).images
														assert image.shape == (1, 64, 64, 3)

														_a			  =       image[0, -3:, -3:, -1]

														_a			  =       np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5]      )

														assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3







'''simple docstring'''


import copy
import os
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence
from datasets.features import ArrayaD, ClassLabel, Features, Image, Value
from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects
from datasets.keyhash import DuplicatedKeysError, InvalidKeyError

from .utils import require_pil

class     A					(	_a					):







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


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







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


														"""simple docstring"""


														with self.assertRaises(lowerCAmelCase_      ):
																					_a			  =       pa.array(TypedSequence([1, 2, 3]      )							,    type=pa.intaa()      )







							def      __lowerCAmelCase    (						self :						Dict      )    ->							Dict:


														"""simple docstring"""


														with self.assertRaises(lowerCAmelCase_      ):
																					_a			  =       pa.array(TypedSequence([1, 2, 3]							,    try_type=Value('''bool'''      )							,    type=Value('''int64'''      )      )      )







							def      __lowerCAmelCase    (						self :						List[str]      )    ->							Optional[Any]:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]							,    type=Value('''int32'''      )      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







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


														"""simple docstring"""


														with self.assertRaises((TypeError, pa.lib.ArrowInvalid)      ):
																					_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    type=Value('''int64'''      )      )      )







							def      __lowerCAmelCase    (						self :						Tuple      )    ->							List[Any]:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]							,    try_type=Value('''int32'''      )      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







							def      __lowerCAmelCase    (						self :						Any      )    ->							Tuple:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    try_type=Value('''int64'''      )      )      )
														self.assertEqual(arr.type							,    pa.string()      )







							def      __lowerCAmelCase    (						self :						List[Any]      )    ->							str:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([[[1, 2, 3]]]							,    type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    ArrayaDExtensionType((1, 3)							,    '''int64'''      )      )







							def      __lowerCAmelCase    (						self :						Optional[Any]      )    ->							Optional[int]:


														"""simple docstring"""


														with self.assertRaises((TypeError, pa.lib.ArrowInvalid)      ):
																					_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    type=ArrayaD((1, 3)							,    '''int64'''      )      )      )







							def      __lowerCAmelCase    (						self :						Tuple      )    ->							Tuple:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([[[1, 2, 3]]]							,    try_type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    ArrayaDExtensionType((1, 3)							,    '''int64'''      )      )







							def      __lowerCAmelCase    (						self :						List[str]      )    ->							Any:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    try_type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    pa.string()      )







							@require_pil
							def      __lowerCAmelCase    (						self :						Tuple      )    ->							List[Any]:


														"""simple docstring"""


														import PIL.Image

														_a			  =       PIL.Image.fromarray(np.arange(10							,    dtype=np.uinta      ).reshape(2							,    5      )      )
														with patch(
														    '''datasets.arrow_writer.cast_to_python_objects'''							,    side_effect=lowerCAmelCase_      ) as mock_cast_to_python_objects:
																					_a			  =       pa.array(TypedSequence([{'''path''': None, '''bytes''': B'''image_bytes'''}, pil_image]							,    type=Image()      )      )
																					_a  ,							_a			  =       mock_cast_to_python_objects.call_args_list[-1]
																					self.assertIn('''optimize_list_casting'''							,    lowerCAmelCase_      )
																					self.assertFalse(kwargs['''optimize_list_casting''']      )



def 	snake_case_					(UpperCamelCase :						Union[str, Any]				,		UpperCamelCase :						int   ):





							'''simple docstring'''


							_a			  =       pa.BufferReader(UpperCamelCase   ) if isinstance(UpperCamelCase				,		pa.Buffer   ) else pa.memory_map(UpperCamelCase   )
							_a			  =       pa.ipc.open_stream(UpperCamelCase   )
							_a			  =       f.read_all()
							assert len(pa_table.to_batches()   ) == expected_num_chunks
							assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
							del pa_table
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Dict				,		UpperCamelCase :						str   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
def 	snake_case_					():





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       Features({'''labels''': ClassLabel(names=['''neg''', '''pos''']   )}   )
							with ArrowWriter(stream=UpperCamelCase				,		features=UpperCamelCase   ) as writer:
														writer.write({'''labels''': 0}   )
														writer.write({'''labels''': 1}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							assert writer._schema == features.arrow_schema
							assert writer._schema.metadata == features.arrow_schema.metadata
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pa.ipc.open_stream(UpperCamelCase   )
							_a			  =       f.read_all()
							_a			  =       pa_table.schema
							assert pa_table.num_rows == 2
							assert schema == features.arrow_schema
							assert schema.metadata == features.arrow_schema.metadata
							assert features == Features.from_arrow_schema(UpperCamelCase   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
def 	snake_case_					(UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														with pytest.raises(UpperCamelCase   ):
																					writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=[1, 2]   )
																					_a  ,							_a			  =       writer.finalize()
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 2, 10]   )
def 	snake_case_					(UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														with pytest.raises(UpperCamelCase   ):
																					writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=10   )
																					writer.write({'''col_1''': '''bar''', '''col_2''': 2}				,		key=10   )
																					_a  ,							_a			  =       writer.finalize()
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 2, 10]   )
def 	snake_case_					(UpperCamelCase :						int   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=1   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}				,		key=2   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Dict				,		UpperCamelCase :						List[str]   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )
														writer.write_batch({'''col_1''': [], '''col_2''': []}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Any				,		UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						int				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]}   )   )
														writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]}   )   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
def 	snake_case_					():





							'''simple docstring'''


							with tempfile.TemporaryDirectory() as tmp_dir:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
														_a			  =       os.path.join(UpperCamelCase				,		'''test.arrow'''   )
														with ArrowWriter(path=UpperCamelCase				,		schema=pa.schema(UpperCamelCase   )   ) as writer:
																					writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )
																					_a  ,							_a			  =       writer.finalize()
														assert num_examples == 2
														assert num_bytes > 0
														assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
														_check_output(UpperCamelCase				,		1   )
def 	snake_case_					(UpperCamelCase :						List[str]   ):





							'''simple docstring'''


							if pa.types.is_list(UpperCamelCase   ):
														return get_base_dtype(arr_type.value_type   )
							else:
														return arr_type
def 	snake_case_					(UpperCamelCase :						Optional[int]				,		UpperCamelCase :						Any   ):





							'''simple docstring'''


							if isinstance(lst[0]				,		UpperCamelCase   ):
														change_first_primitive_element_in_list(lst[0]				,		UpperCamelCase   )
							else:
														_a			  =       value
@pytest.mark.parametrize('''optimized_int_type, expected_dtype'''				,		[(None, pa.intaa()), (Value('''int32'''   ), pa.intaa())]   )
@pytest.mark.parametrize('''sequence'''				,		[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]   )
def 	snake_case_					(UpperCamelCase :						int				,		UpperCamelCase :						Tuple				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							_a			  =       pa.array(TypedSequence(UpperCamelCase				,		optimized_int_type=UpperCamelCase   )   )
							assert get_base_dtype(arr.type   ) == expected_dtype
@pytest.mark.parametrize(
    '''col, expected_dtype'''				,		[
        ('''attention_mask''', pa.inta()),
        ('''special_tokens_mask''', pa.inta()),
        ('''token_type_ids''', pa.inta()),
        ('''input_ids''', pa.intaa()),
        ('''other''', pa.intaa()),
    ]				,		)
@pytest.mark.parametrize('''sequence'''				,		[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]   )
def 	snake_case_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						str				,		UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							_a			  =       pa.array(OptimizedTypedSequence(UpperCamelCase				,		col=UpperCamelCase   )   )
							assert get_base_dtype(arr.type   ) == expected_dtype

							# not in range
							if col != "other":
														# avoids errors due to in-place modifications
														_a			  =       copy.deepcopy(UpperCamelCase   )
														_a			  =       np.iinfo(expected_dtype.to_pandas_dtype()   ).max + 1
														change_first_primitive_element_in_list(UpperCamelCase				,		UpperCamelCase   )
														_a			  =       pa.array(OptimizedTypedSequence(UpperCamelCase				,		col=UpperCamelCase   )   )
														assert get_base_dtype(arr.type   ) == pa.intaa()
@pytest.mark.parametrize('''raise_exception'''				,		[False, True]   )
def 	snake_case_					(UpperCamelCase :						Optional[Any]				,		UpperCamelCase :						Optional[Any]   ):





							'''simple docstring'''


							_a			  =       str(tmp_path / '''dataset-train.arrow'''   )
							try:
														with ArrowWriter(path=UpperCamelCase   ) as writer:
																					if raise_exception:
																												raise pa.lib.ArrowInvalid()
																					else:
																												writer.stream.close()
							except pa.lib.ArrowInvalid:
														pass
							finally:
														assert writer.stream.closed
def 	snake_case_					(UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							_a			  =       '''mock://dataset-train.arrow'''
							with ArrowWriter(path=UpperCamelCase				,		storage_options=mockfs.storage_options   ) as writer:
														assert isinstance(writer._fs				,		type(UpperCamelCase   )   )
														assert writer._fs.storage_options == mockfs.storage_options
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							assert mockfs.exists(UpperCamelCase   )
def 	snake_case_					():





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ParquetWriter(stream=UpperCamelCase   ) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pq.read_table(UpperCamelCase   )
							assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
@require_pil
@pytest.mark.parametrize('''embed_local_files'''				,		[False, True]   )
def 	snake_case_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							import PIL.Image

							_a			  =       str(tmp_path / '''test_image_rgb.jpg'''   )
							PIL.Image.fromarray(np.zeros((5, 5)				,		dtype=np.uinta   )   ).save(UpperCamelCase				,		format='''png'''   )
							_a			  =       pa.BufferOutputStream()
							with ParquetWriter(
							    stream=UpperCamelCase				,		features=Features({'''image''': Image()}   )				,		embed_local_files=UpperCamelCase   ) as writer:
														writer.write({'''image''': image_path}   )
														writer.finalize()
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pq.read_table(UpperCamelCase   )
							_a			  =       pa_table.to_pydict()
							if embed_local_files:
														assert isinstance(out['''image'''][0]['''path''']				,		UpperCamelCase   )
														with open(UpperCamelCase				,		'''rb'''   ) as f:
																					assert out["image"][0]["bytes"] == f.read()
							else:
														assert out["image"][0]["path"] == image_path
														assert out["image"][0]["bytes"] is None

def 	snake_case_					():





							'''simple docstring'''


							_a			  =       pa.schema([pa.field('''col_1'''				,		pa.string()				,		nullable=UpperCamelCase   )]   )
							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(stream=UpperCamelCase   ) as writer:
														writer._build_writer(inferred_schema=UpperCamelCase   )
														assert writer._schema == pa.schema([pa.field('''col_1'''				,		pa.string()   )]   )

