




'''simple docstring'''





from pickle import UnpicklingError

import jax
import jax.numpy as jnp
import numpy as np
from flax.serialization import from_bytes
from flax.traverse_util import flatten_dict

from ..utils import logging


UpperCAmelCase_						=logging.get_logger(__name__)



def       UpperCAmelCase       (     _snake_case						, _snake_case							):
							try:
														with open(lowerCamelCase_						, '''rb'''							) as flax_state_f:
																					lowerCAmelCase   =		from_bytes(lowerCamelCase_						, flax_state_f.read()							)
							except UnpicklingError as e:
														try:
																					with open(lowerCamelCase_							) as f:
																												if f.read().startswith('''version'''							):
																																			raise OSError(
																																			    '''You seem to have cloned a repository without having git-lfs installed. Please'''
																																			    ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the'''
																																			    ''' folder you cloned.'''							)
																												else:
																																			raise ValueError from e
														except (UnicodeDecodeError, ValueError):
																					raise EnvironmentError(F"""Unable to convert {model_file} to Flax deserializable object. """							)

							return load_flax_weights_in_pytorch_model(lowerCamelCase_						, lowerCamelCase_							)



def       UpperCAmelCase       (     _snake_case						, _snake_case							):

							try:
														import torch  # noqa: F401
							except ImportError:
														logger.error(
														    '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see'''
														    ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation'''
														    ''' instructions.'''							)
														raise

							# check if we have bf16 weights
							lowerCAmelCase   =		flatten_dict(jax.tree_util.tree_map(lambda _snake_case							: x.dtype == jnp.bfloataa						, lowerCamelCase_							)							).values()
							if any(lowerCamelCase_							):
														# convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16

														# and bf16 is not fully supported in PT yet.
														logger.warning(
														    '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` '''
														    '''before loading those in PyTorch model.'''							)
														lowerCAmelCase   =		jax.tree_util.tree_map(
														    lambda _snake_case							: params.astype(np.floataa							) if params.dtype == jnp.bfloataa else params						, lowerCamelCase_							)

							lowerCAmelCase   =		''''''

							lowerCAmelCase   =		flatten_dict(lowerCamelCase_						, sep='''.'''							)
							lowerCAmelCase   =		pt_model.state_dict()

							# keep track of unexpected & missing keys
							lowerCAmelCase   =		[]
							lowerCAmelCase   =		set(pt_model_dict.keys()							)

							for flax_key_tuple, flax_tensor in flax_state_dict.items():
														lowerCAmelCase   =		flax_key_tuple.split('''.'''							)

														if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4:
																					lowerCAmelCase   =		flax_key_tuple_array[:-1] + ['''weight''']
																					lowerCAmelCase   =		jnp.transpose(lowerCamelCase_						, (3, 2, 0, 1)							)
														elif flax_key_tuple_array[-1] == "kernel":
																					lowerCAmelCase   =		flax_key_tuple_array[:-1] + ['''weight''']
																					lowerCAmelCase   =		flax_tensor.T
														elif flax_key_tuple_array[-1] == "scale":
																					lowerCAmelCase   =		flax_key_tuple_array[:-1] + ['''weight''']

														if "time_embedding" not in flax_key_tuple_array:
																					for i, flax_key_tuple_string in enumerate(lowerCamelCase_							):
																												lowerCAmelCase   =		(
																												    flax_key_tuple_string.replace('''_0'''						, '''.0'''							)
																												    .replace('''_1'''						, '''.1'''							)
																												    .replace('''_2'''						, '''.2'''							)
																												    .replace('''_3'''						, '''.3'''							)
																												    .replace('''_4'''						, '''.4'''							)
																												    .replace('''_5'''						, '''.5'''							)
																												    .replace('''_6'''						, '''.6'''							)
																												    .replace('''_7'''						, '''.7'''							)
																												    .replace('''_8'''						, '''.8'''							)
																												    .replace('''_9'''						, '''.9'''							)
																												)

														lowerCAmelCase   =		'''.'''.join(lowerCamelCase_							)

														if flax_key in pt_model_dict:
																					if flax_tensor.shape != pt_model_dict[flax_key].shape:
																												raise ValueError(
																												    F"""Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected """
																												    F"""to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}."""							)
																					else:
																												# add weight to pytorch dict
																												lowerCAmelCase   =		np.asarray(lowerCamelCase_							) if not isinstance(lowerCamelCase_						, np.ndarray							) else flax_tensor
																												lowerCAmelCase   =		torch.from_numpy(lowerCamelCase_							)
																												# remove from missing keys
																												missing_keys.remove(lowerCamelCase_							)
														else:
																					# weight is not expected by PyTorch model
																					unexpected_keys.append(lowerCamelCase_							)

							pt_model.load_state_dict(lowerCamelCase_							)

							# re-transform missing_keys to list
							lowerCAmelCase   =		list(lowerCamelCase_							)

							if len(lowerCamelCase_							) > 0:
														logger.warning(
														    '''Some weights of the Flax model were not used when initializing the PyTorch model'''
														    F""" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing"""
														    F""" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture"""
														    ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This'''
														    F""" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect"""
														    ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a'''
														    ''' FlaxBertForSequenceClassification model).'''							)
							if len(lowerCamelCase_							) > 0:
														logger.warning(
														    F"""Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly"""
														    F""" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to"""
														    ''' use it for predictions and inference.'''							)

							return pt_model









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 							__UpperCamelCase			( 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										=1_0 << 2_0  # 10MB
				__a							: Optional[bool]										=None




class 							__UpperCamelCase			( datasets.ArrowBasedBuilder  ):





				'''simple docstring'''



				__a							: str										=JsonConfig



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



				def       __snake_case		( self       , UpperCAmelCase_						):
											if self.config.features is not None:
																		# adding missing columns
																		for column_name in set(self.config.features						) - set(pa_table.column_names						):
																									lowerCAmelCase   =		self.config.features.arrow_schema.field(UpperCAmelCase_						).type
																									lowerCAmelCase   =		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   =		table_cast(UpperCAmelCase_       , self.config.features.arrow_schema						)
											return pa_table






				def       __snake_case		( self       , UpperCAmelCase_						):
											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   =		json.load(UpperCAmelCase_						)

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

																									# We accept two format: a list of dicts or a dict of lists
																									if isinstance(UpperCAmelCase_       , (list, tuple)						):
																																lowerCAmelCase   =		set().union(*[row.keys() for row in dataset]						)
																																lowerCAmelCase   =		{col: [row.get(UpperCAmelCase_						) for row in dataset] for col in keys}
																									else:
																																lowerCAmelCase   =		dataset
																									lowerCAmelCase   =		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   =		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   =		max(self.config.chunksize // 32       , 16 << 10						)
																																lowerCAmelCase   =		(
																																    self.config.encoding_errors if self.config.encoding_errors is not None else '''strict'''
																																)
																																while True:
																																							lowerCAmelCase   =		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   =		batch.decode(self.config.encoding       , errors=UpperCAmelCase_						).encode('''utf-8'''						)
																																							try:
																																														while True:
																																																					try:
																																																												lowerCAmelCase   =		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   =		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   =		set().union(*[row.keys() for row in dataset]						)
																																																												lowerCAmelCase   =		{col: [row.get(UpperCAmelCase_						) for row in dataset] for col in keys}
																																																												lowerCAmelCase   =		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



