





import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


_UpperCAmelCase				:       Tuple	   =				datasets.utils.logging.get_logger(__name__)

@dataclass
class    lowerCAmelCase							(					datasets.BuilderConfig			):
 UpperCAmelCase__													=		None
 UpperCAmelCase__													=		"utf-8"
 UpperCAmelCase__													=		None
 UpperCAmelCase__													=		None
 UpperCAmelCase__													=		True  # deprecated
 UpperCAmelCase__													=		None  # deprecated
 UpperCAmelCase__													=		10 << 20  # 10MB
 UpperCAmelCase__													=		None


class    lowerCAmelCase							(					datasets.ArrowBasedBuilder			):
 UpperCAmelCase__													=		JsonConfig
 def      A_	(      self  :      Tuple	)			->	Optional[int]:
     if self.config.block_size is not None:
         logger.warning('The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'	)
         lowerCamelCase__    :      Optional[Any]					 =		self.config.block_size
     if self.config.use_threads is not True:
         logger.warning(
             'The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.'	)
     if self.config.newlines_in_values is not None:
         raise ValueError('The JSON loader parameter `newlines_in_values` is no longer supported'	)
     return datasets.DatasetInfo(features=self.config.features	)
 def      A_	(      self  :      Any			,     UpperCAmelCase  :      List[str]	)			->	Optional[int]:
     if not self.config.data_files:
         raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}"""	)
     lowerCamelCase__    :      str					 =		dl_manager.download_and_extract(self.config.data_files	)
     if isinstance(UpperCAmelCase			,     (str, list, tuple)	):
         lowerCamelCase__    :      Optional[Any]					 =		data_files
         if isinstance(UpperCAmelCase			,     UpperCAmelCase	):
             lowerCamelCase__    :      List[Any]					 =		[files]
         lowerCamelCase__    :      Optional[Any]					 =		[dl_manager.iter_files(UpperCAmelCase	) for file in files]
         return [datasets.SplitGenerator(name=datasets.Split.TRAIN			,     gen_kwargs={'files': files}	)]
     lowerCamelCase__    :      Any					 =		[]
     for split_name, files in data_files.items():
         if isinstance(UpperCAmelCase			,     UpperCAmelCase	):
             lowerCamelCase__    :      Tuple					 =		[files]
         lowerCamelCase__    :      Any					 =		[dl_manager.iter_files(UpperCAmelCase	) for file in files]
         splits.append(datasets.SplitGenerator(name=UpperCAmelCase			,     gen_kwargs={'files': files}	)	)
     return splits
 def      A_	(      self  :      Any			,     UpperCAmelCase  :      pa.Table	)			->	pa.Table:
     if self.config.features is not None:
         # adding missing columns
         for column_name in set(self.config.features	) - set(pa_table.column_names	):
             lowerCamelCase__    :      str					 =		self.config.features.arrow_schema.field(UpperCAmelCase	).type
             lowerCamelCase__    :      int					 =		pa_table.append_column(UpperCAmelCase			,     pa.array([None] * len(UpperCAmelCase	)			,     type=UpperCAmelCase	)	)
         # more expensive cast to support nested structures with keys in a different order
         # allows str <-> int/float or str to Audio for example
         lowerCamelCase__    :      int					 =		table_cast(UpperCAmelCase			,     self.config.features.arrow_schema	)
     return pa_table







 def      A_	(      self  :      str			,     UpperCAmelCase  :      Tuple	)			->	Dict:
     for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCAmelCase	)	):
         # If the file is one json object and if we need to look at the list of items in one specific field
         if self.config.field is not None:
             with open(UpperCAmelCase			,     encoding=self.config.encoding			,     errors=self.config.encoding_errors	) as f:
                 lowerCamelCase__    :      Optional[Any]					 =		json.load(UpperCAmelCase	)

             # We keep only the field we are interested in
             lowerCamelCase__    :      Optional[int]					 =		dataset[self.config.field]

             # We accept two format: a list of dicts or a dict of lists
             if isinstance(UpperCAmelCase			,     (list, tuple)	):
                 lowerCamelCase__    :      Any					 =		set().union(*[row.keys() for row in dataset]	)
                 lowerCamelCase__    :      List[Any]					 =		{col: [row.get(UpperCAmelCase	) for row in dataset] for col in keys}
             else:
                 lowerCamelCase__    :      int					 =		dataset
             lowerCamelCase__    :      Union[str, Any]					 =		pa.Table.from_pydict(UpperCAmelCase	)
             yield file_idx, self._cast_table(UpperCAmelCase	)

         # If the file has one json object per line
         else:
             with open(UpperCAmelCase			,     'rb'	) as f:
                 lowerCamelCase__    :      Any					 =		0
                 # Use block_size equal to the chunk size divided by 32 to leverage multithreading
                 # Set a default minimum value of 16kB if the chunk size is really small
                 lowerCamelCase__    :      Optional[int]					 =		max(self.config.chunksize // 32			,     16 << 10	)
                 lowerCamelCase__    :      List[str]					 =		(
                     self.config.encoding_errors if self.config.encoding_errors is not None else 'strict'
                 )
                 while True:
                     lowerCamelCase__    :      Optional[int]					 =		f.read(self.config.chunksize	)
                     if not batch:
                         break
                     # Finish current line
                     try:
                         batch += f.readline()
                     except (AttributeError, io.UnsupportedOperation):
                         batch += readline(UpperCAmelCase	)
                     # PyArrow only accepts utf-8 encoded bytes
                     if self.config.encoding != "utf-8":
                         lowerCamelCase__    :      Union[str, Any]					 =		batch.decode(self.config.encoding			,     errors=UpperCAmelCase	).encode('utf-8'	)
                     try:
                         while True:
                             try:
                                 lowerCamelCase__    :      List[str]					 =		paj.read_json(
                                     io.BytesIO(UpperCAmelCase	)			,     read_options=paj.ReadOptions(block_size=UpperCAmelCase	)	)
                                 break
                             except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
                                 if (
                                     isinstance(UpperCAmelCase			,     pa.ArrowInvalid	)
                                     and "straddling" not in str(UpperCAmelCase	)
                                     or block_size > len(UpperCAmelCase	)
                                 ):
                                     raise
                                 else:
                                     # Increase the block size in case it was too small.
                                     # The block size will be reset for the next file.
                                     logger.debug(
                                         F"""Batch of {len(UpperCAmelCase	)} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}."""	)
                                     block_size *= 2
                     except pa.ArrowInvalid as e:
                         try:
                             with open(
                                 UpperCAmelCase			,     encoding=self.config.encoding			,     errors=self.config.encoding_errors	) as f:
                                 lowerCamelCase__    :      str					 =		json.load(UpperCAmelCase	)
                         except json.JSONDecodeError:
                             logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase	)}: {e}"""	)
                             raise e
                         # If possible, parse the file as a list of json objects and exit the loop
                         if isinstance(UpperCAmelCase			,     UpperCAmelCase	):  # list is the only sequence type supported in JSON
                             try:
                                 lowerCamelCase__    :      List[str]					 =		set().union(*[row.keys() for row in dataset]	)
                                 lowerCamelCase__    :      Optional[Any]					 =		{col: [row.get(UpperCAmelCase	) for row in dataset] for col in keys}
                                 lowerCamelCase__    :      int					 =		pa.Table.from_pydict(UpperCAmelCase	)
                             except (pa.ArrowInvalid, AttributeError) as e:
                                 logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase	)}: {e}"""	)
                                 raise ValueError(F"""Not able to read records in the JSON file at {file}."""	) from None
                             yield file_idx, self._cast_table(UpperCAmelCase	)
                             break
                         else:
                             logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase	)}: {e}"""	)
                             raise ValueError(
                                 F"""Not able to read records in the JSON file at {file}. """
                                 F"""You should probably indicate the field of the JSON file containing your records. """
                                 F"""This JSON file contain the following fields: {str(list(dataset.keys()	)	)}. """
                                 F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """	) from None
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                     yield (file_idx, batch_idx), self._cast_table(UpperCAmelCase	)
                     batch_idx += 1






import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402





class 					lowercase__						(   unittest.TestCase):


						def        __A       (       self	:				List[Any]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Dict							=							0


						def        __A       (       self	:				Dict						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    str							=							AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32'''						)
												self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				Dict						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    str							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		SCREAMING_SNAKE_CASE							:    Dict							=							Path(UpperCamelCase__						) / '''config.json'''
																		json.dump(
																		    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																		json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																		SCREAMING_SNAKE_CASE							:    Any							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																		self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				int						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    Tuple							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		SCREAMING_SNAKE_CASE							:    Dict							=							Path(UpperCamelCase__						) / '''config.json'''
																		json.dump(
																		    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																		json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																		SCREAMING_SNAKE_CASE							:    Optional[Any]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																		self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				List[str]						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    Dict							=							CLIPConfig()

																		# Create a dummy config file with image_proceesor_type
																		SCREAMING_SNAKE_CASE							:    Dict							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		SCREAMING_SNAKE_CASE							:    List[str]							=							Path(UpperCamelCase__						) / '''config.json'''
																		json.dump(
																		    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																		json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																		# remove image_processor_type to make sure config.json alone is enough to load image processor locally
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						).to_dict()

																		config_dict.pop('''image_processor_type'''						)
																		SCREAMING_SNAKE_CASE							:    str							=							CLIPImageProcessor(**UpperCamelCase__						)

																		# save in new folder
																		model_config.save_pretrained(UpperCamelCase__						)
																		config.save_pretrained(UpperCamelCase__						)

																		SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)

																		# make sure private variable is not incorrectly saved
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							json.loads(config.to_json_string()						)
																		self.assertTrue('''_processor_class''' not in dict_as_saved						)

												self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				Tuple						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    Optional[int]							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		json.dump(
																		    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)

																		SCREAMING_SNAKE_CASE							:    Dict							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																		self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				int						):





												'''simple docstring'''





												with self.assertRaisesRegex(
												    UpperCamelCase__    ,		'''clip-base is not a local folder and is not a valid model identifier'''						):
																		SCREAMING_SNAKE_CASE							:    List[str]							=							AutoImageProcessor.from_pretrained('''clip-base'''						)


						def        __A       (       self	:				List[str]						):





												'''simple docstring'''





												with self.assertRaisesRegex(
												    UpperCamelCase__    ,		r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''						):
																		SCREAMING_SNAKE_CASE							:    Tuple							=							AutoImageProcessor.from_pretrained(UpperCamelCase__    ,		revision='''aaaaaa'''						)


						def        __A       (       self	:				Dict						):





												'''simple docstring'''





												with self.assertRaisesRegex(
												    UpperCamelCase__    ,		'''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''    ,		):
																		SCREAMING_SNAKE_CASE							:    Dict							=							AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model'''						)


						def        __A       (       self	:				List[Any]						):





												'''simple docstring'''





												with self.assertRaises(UpperCamelCase__						):
																		SCREAMING_SNAKE_CASE							:    str							=							AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''						)
												# If remote code is disabled, we can't load this config.
												with self.assertRaises(UpperCamelCase__						):
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							AutoImageProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)

												SCREAMING_SNAKE_CASE							:    List[Any]							=							AutoImageProcessor.from_pretrained(
												    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)
												self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)

												# Test image processor can be reloaded.
												with tempfile.TemporaryDirectory() as tmp_dir:
																		image_processor.save_pretrained(UpperCamelCase__						)
																		SCREAMING_SNAKE_CASE							:    Optional[int]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__    ,		trust_remote_code=UpperCamelCase__						)
												self.assertEqual(reloaded_image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)


						def        __A       (       self	:				Optional[Any]						):





												'''simple docstring'''





												try:
																		AutoConfig.register('''custom'''    ,		UpperCamelCase__						)
																		AutoImageProcessor.register(UpperCamelCase__    ,		UpperCamelCase__						)
																		# Trying to register something existing in the Transformers library will raise an error
																		with self.assertRaises(UpperCamelCase__						):
																								AutoImageProcessor.register(UpperCamelCase__    ,		UpperCamelCase__						)

																		with tempfile.TemporaryDirectory() as tmpdirname:
																								SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																								SCREAMING_SNAKE_CASE							:    Any							=							Path(UpperCamelCase__						) / '''config.json'''
																								json.dump(
																								    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																								json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																								SCREAMING_SNAKE_CASE							:    Tuple							=							CustomImageProcessor.from_pretrained(UpperCamelCase__						)

																		# Now that the config is registered, it can be used as any other config with the auto-API
																		with tempfile.TemporaryDirectory() as tmp_dir:
																								image_processor.save_pretrained(UpperCamelCase__						)
																								SCREAMING_SNAKE_CASE							:    Any							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																								self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)

												finally:
																		if "custom" in CONFIG_MAPPING._extra_content:
																								del CONFIG_MAPPING._extra_content["custom"]
																		if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																								del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]



						def        __A       (       self	:				Any						):





												'''simple docstring'''





												class 					lowercase__						(   UpperCamelCase_):
																		UpperCamelCase_     =		True

												try:
																		AutoConfig.register('''custom'''    ,		UpperCamelCase__						)
																		AutoImageProcessor.register(UpperCamelCase__    ,		UpperCamelCase__						)
																		# If remote code is not set, the default is to use local
																		SCREAMING_SNAKE_CASE							:    str							=							AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''						)
																		self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)
																		self.assertTrue(image_processor.is_local						)

																		# If remote code is disabled, we load the local one.
																		SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							AutoImageProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)
																		self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)
																		self.assertTrue(image_processor.is_local						)

																		# If remote is enabled, we load from the Hub
																		SCREAMING_SNAKE_CASE							:    Optional[Any]							=							AutoImageProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)
																		self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)
																		self.assertTrue(not hasattr(UpperCamelCase__    ,		'''is_local'''						)						)

												finally:
																		if "custom" in CONFIG_MAPPING._extra_content:
																								del CONFIG_MAPPING._extra_content["custom"]
																		if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																								del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]





