



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_		 =					datasets.utils.logging.get_logger(__name__)


@dataclass
class 	lowerCamelCase__	(       datasets.BuilderConfig):



 """simple docstring"""

 a__					: Optional[datasets.Features] =  None
 a__					: str =  "utf-8"
 a__					: Optional[str] =  None
 a__					: Optional[str] =  None
 a__					: bool =  True  # deprecated
 a__					: Optional[int] =  None  # deprecated
 a__					: int =  10 << 20  # 10MB
 a__					: Optional[bool] =  None


class 	lowerCamelCase__	(       datasets.ArrowBasedBuilder):



 """simple docstring"""

 a__					: List[Any] =  JsonConfig

 def     snake_case_      (    self					:					Any      )   ->	List[str]:
    if self.config.block_size is not None:
       logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'''      )
       _A      =       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     snake_case_      (    self					:					int			,						__lowerCAmelCase					:					Dict      )   ->	Any:
    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}'''      )
    _A      =       dl_manager.download_and_extract(self.config.data_files      )
    if isinstance(__lowerCAmelCase			,						(str, list, tuple)      ):
       _A      =       data_files
       if isinstance(__lowerCAmelCase			,						__lowerCAmelCase      ):
          _A      =       [files]
       _A      =       [dl_manager.iter_files(__lowerCAmelCase      ) for file in files]
       return [datasets.SplitGenerator(name=datasets.Split.TRAIN			,						gen_kwargs={'''files''': files}      )]
    _A      =       []
    for split_name, files in data_files.items():
       if isinstance(__lowerCAmelCase			,						__lowerCAmelCase      ):
          _A      =       [files]
       _A      =       [dl_manager.iter_files(__lowerCAmelCase      ) for file in files]
       splits.append(datasets.SplitGenerator(name=__lowerCAmelCase			,						gen_kwargs={'''files''': files}      )      )
    return splits

 def     snake_case_      (    self					:					Dict			,						__lowerCAmelCase					:					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      ):
          _A      =       self.config.features.arrow_schema.field(__lowerCAmelCase      ).type
          _A      =       pa_table.append_column(__lowerCAmelCase			,						pa.array([None] * len(__lowerCAmelCase      )			,						type=__lowerCAmelCase      )      )
       # more expensive cast to support nested structures with keys in a different order
       # allows str <-> int/float or str to Audio for example
       _A      =       table_cast(__lowerCAmelCase			,						self.config.features.arrow_schema      )
    return pa_table

 def     snake_case_      (    self					:					Any			,						__lowerCAmelCase					:					str      )   ->	int:
    for file_idx, file in enumerate(itertools.chain.from_iterable(__lowerCAmelCase      )      ):
       # 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(__lowerCAmelCase			,						encoding=self.config.encoding			,						errors=self.config.encoding_errors      ) as f:
             _A      =       json.load(__lowerCAmelCase      )

          # We keep only the field we are interested in
          _A      =       dataset[self.config.field]

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

       # If the file has one json object per line
       else:
          with open(__lowerCAmelCase			,						'''rb'''      ) as f:
             _A      =       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
             _A      =       max(self.config.chunksize // 32			,						16 << 10      )
             _A      =       (
                 self.config.encoding_errors if self.config.encoding_errors is not None else '''strict'''
             )
             while True:
                _A      =       f.read(self.config.chunksize      )
                if not batch:
                   break
                # Finish current line
                try:
                   batch += f.readline()
                except (AttributeError, io.UnsupportedOperation):
                   batch += readline(__lowerCAmelCase      )
                # PyArrow only accepts utf-8 encoded bytes
                if self.config.encoding != "utf-8":
                   _A      =       batch.decode(self.config.encoding			,						errors=__lowerCAmelCase      ).encode('''utf-8'''      )
                try:
                   while True:
                      try:
                         _A      =       paj.read_json(
                             io.BytesIO(__lowerCAmelCase      )			,						read_options=paj.ReadOptions(block_size=__lowerCAmelCase      )      )
                         break
                      except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
                         if (
                             isinstance(__lowerCAmelCase			,						pa.ArrowInvalid      )
                             and "straddling" not in str(__lowerCAmelCase      )
                             or block_size > len(__lowerCAmelCase      )
                         ):
                            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(__lowerCAmelCase      )} 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(
                          __lowerCAmelCase			,						encoding=self.config.encoding			,						errors=self.config.encoding_errors      ) as f:
                         _A      =       json.load(__lowerCAmelCase      )
                   except json.JSONDecodeError:
                      logger.error(f'''Failed to read file \'{file}\' with error {type(__lowerCAmelCase      )}: {e}'''      )
                      raise e
                   # If possible, parse the file as a list of json objects and exit the loop
                   if isinstance(__lowerCAmelCase			,						__lowerCAmelCase      ):  # list is the only sequence type supported in JSON
                      try:
                         _A      =       set().union(*[row.keys() for row in dataset]      )
                         _A      =       {col: [row.get(__lowerCAmelCase      ) for row in dataset] for col in keys}
                         _A      =       pa.Table.from_pydict(__lowerCAmelCase      )
                      except (pa.ArrowInvalid, AttributeError) as e:
                         logger.error(f'''Failed to read file \'{file}\' with error {type(__lowerCAmelCase      )}: {e}'''      )
                         raise ValueError(f'''Not able to read records in the JSON file at {file}.'''      ) from None
                      yield file_idx, self._cast_table(__lowerCAmelCase      )
                      break
                   else:
                      logger.error(f'''Failed to read file \'{file}\' with error {type(__lowerCAmelCase      )}: {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(__lowerCAmelCase      )
                batch_idx += 1







import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


a			:			Optional[int]												=					logging.get_logger(__name__)

a			:			Dict												=					{
    '''google/pix2struct-textcaps-base''': (
        '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json'''
    ),
}
class 						lowerCamelCase_							(					lowerCAmelCase__					):



					'''simple docstring'''







					__UpperCAmelCase							  =					"pix2struct_text_model"
					__UpperCAmelCase							  =					["past_key_values"]
					__UpperCAmelCase							  =					{
					    "hidden_size": "hidden_size",
					    "num_attention_heads": "num_heads",
					    "num_hidden_layers": "num_layers",
					}






					def __init__(					self			,							snake_case_=5_0_2_4_4			,							snake_case_=7_6_8			,							snake_case_=6_4			,							snake_case_=2_0_4_8			,							snake_case_=1_2			,							snake_case_=1_2			,							snake_case_=3_2			,							snake_case_=1_2_8			,							snake_case_=0.1			,							snake_case_=1e-6			,							snake_case_=1.0			,							snake_case_="gelu_new"			,							snake_case_=0			,							snake_case_=False			,							snake_case_=0			,							snake_case_=1			,							snake_case_=False			,							snake_case_=True			,							**snake_case_			,							) ->      Optional[int]:







								'''simple docstring'''

								__lowercase			       = vocab_size
								__lowercase			       = hidden_size
								__lowercase			       = d_kv
								__lowercase			       = d_ff
								__lowercase			       = num_layers
								__lowercase			       = num_heads
								__lowercase			       = relative_attention_num_buckets
								__lowercase			       = relative_attention_max_distance
								__lowercase			       = dropout_rate
								__lowercase			       = layer_norm_epsilon
								__lowercase			       = initializer_factor
								__lowercase			       = use_cache

								__lowercase			       = eos_token_id
								__lowercase			       = decoder_start_token_id

								# for backwards compatibility
								__lowercase			       = dense_act_fn

								super().__init__(
								    pad_token_id=snake_case_			,							eos_token_id=snake_case_			,							decoder_start_token_id=snake_case_			,							tie_word_embeddings=snake_case_			,							is_decoder=snake_case_			,							**snake_case_			,							)






					@classmethod
					def A   (					cls			,							snake_case_			,							**snake_case_    ) ->      "PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(snake_case_    )

								__lowercase       ,			__lowercase			       = cls.get_config_dict(snake_case_			,							**snake_case_    )

								# get the text config dict if we are loading from Pix2StructConfig
								if config_dict.get('''model_type'''    ) == "pix2struct":
											__lowercase			       = config_dict['''text_config''']

								if "model_type" in config_dict and hasattr(cls			,							'''model_type'''    ) and config_dict["model_type"] != cls.model_type:
											logger.warning(
											    F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
											    F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'    )

								return cls.from_dict(snake_case_			,							**snake_case_    )




class 						lowerCamelCase_							(					lowerCAmelCase__					):



					'''simple docstring'''







					__UpperCAmelCase							  =					"pix2struct_vision_model"






					def __init__(					self			,							snake_case_=7_6_8			,							snake_case_=7_6_8			,							snake_case_=2_0_4_8			,							snake_case_=6_4			,							snake_case_=1_2			,							snake_case_=1_2			,							snake_case_="gelu_new"			,							snake_case_=1e-6			,							snake_case_=0.0			,							snake_case_=0.0			,							snake_case_=1e-1_0			,							snake_case_=1.0			,							snake_case_=4_0_9_6			,							snake_case_=3_2			,							snake_case_=1_2_8			,							**snake_case_			,							) ->      Union[str, Any]:







								'''simple docstring'''

								super().__init__(**snake_case_    )

								__lowercase			       = hidden_size
								__lowercase			       = patch_embed_hidden_size
								__lowercase			       = d_ff
								__lowercase			       = dropout_rate
								__lowercase			       = num_hidden_layers
								__lowercase			       = num_attention_heads
								__lowercase			       = initializer_range
								__lowercase			       = initializer_factor
								__lowercase			       = attention_dropout
								__lowercase			       = layer_norm_eps
								__lowercase			       = dense_act_fn
								__lowercase			       = seq_len
								__lowercase			       = relative_attention_num_buckets
								__lowercase			       = relative_attention_max_distance
								__lowercase			       = d_kv






					@classmethod
					def A   (					cls			,							snake_case_			,							**snake_case_    ) ->      "PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(snake_case_    )

								__lowercase       ,			__lowercase			       = cls.get_config_dict(snake_case_			,							**snake_case_    )

								# get the vision config dict if we are loading from Pix2StructConfig
								if config_dict.get('''model_type'''    ) == "pix2struct":
											__lowercase			       = config_dict['''vision_config''']

								if "model_type" in config_dict and hasattr(cls			,							'''model_type'''    ) and config_dict["model_type"] != cls.model_type:
											logger.warning(
											    F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
											    F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'    )

								return cls.from_dict(snake_case_			,							**snake_case_    )




class 						lowerCamelCase_							(					lowerCAmelCase__					):



					'''simple docstring'''







					__UpperCAmelCase							  =					"pix2struct"
					__UpperCAmelCase							  =					True






					def __init__(					self			,							snake_case_=None			,							snake_case_=None			,							snake_case_=1.0			,							snake_case_=0.0_2			,							snake_case_=False			,							snake_case_=False			,							snake_case_=True			,							**snake_case_			,							) ->      Optional[int]:







								'''simple docstring'''

								super().__init__(tie_word_embeddings=snake_case_			,							is_encoder_decoder=snake_case_			,							**snake_case_    )

								if text_config is None:
											__lowercase			       = {}
											logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.'''    )

								if vision_config is None:
											__lowercase			       = {}
											logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.'''    )

								__lowercase			       = PixaStructTextConfig(**snake_case_    )
								__lowercase			       = PixaStructVisionConfig(**snake_case_    )

								__lowercase			       = self.text_config.decoder_start_token_id
								__lowercase			       = self.text_config.pad_token_id
								__lowercase			       = self.text_config.eos_token_id

								__lowercase			       = initializer_factor
								__lowercase			       = initializer_range

								__lowercase			       = self.initializer_range
								__lowercase			       = self.initializer_range

								__lowercase			       = is_vqa






					@classmethod
					def A   (					cls			,							snake_case_			,							snake_case_			,							**snake_case_    ) ->      List[str]:







								'''simple docstring'''

								return cls(text_config=text_config.to_dict()			,							vision_config=vision_config.to_dict()			,							**snake_case_    )






					def A   (					self    ) ->      Tuple:







								'''simple docstring'''

								__lowercase			       = copy.deepcopy(self.__dict__    )
								__lowercase			       = self.text_config.to_dict()
								__lowercase			       = self.vision_config.to_dict()
								__lowercase			       = self.__class__.model_type
								return output


