





"""simple docstring"""






from pathlib import PurePosixPath
from typing import Optional

import fsspec
from fsspec import AbstractFileSystem
from huggingface_hub.hf_api import DatasetInfo

from ..utils.file_utils import get_authentication_headers_for_url
from ..utils.hub import hf_hub_url



class 					__UpperCAmelCase							(						_UpperCamelCase  ):
				__lowerCamelCase				:	str				     =				""
				__lowerCamelCase				:	Dict				     =				"hf-legacy"  # "hf://"" is reserved for hffs
				def __init__(		self    :			Union[str, Any]	, a_    :			Optional[DatasetInfo] = None	, a_    :			Optional[str] = None	, **a_    :			str	, )	->	Dict:



							'''simple docstring'''



							super().__init__(self	, **a_    )
							a__  :	str		 =			repo_info
							a__  :	Dict		 =			token
							a__  :	List[str]		 =			None
				def       UpperCAmelCase      (		self    :			Any    )	->	Tuple:



							'''simple docstring'''



							if self.dir_cache is None:
										a__  :	Tuple		 =			{}
										for hf_file in self.repo_info.siblings:
													# TODO(QL): add sizes
													a__  :	List[str]		 =			{
													    "name": hf_file.rfilename,
													    "size": None,
													    "type": "file",
													}
													self.dir_cache.update(
													    {
													        str(a_    ): {"name": str(a_    ), "size": None, "type": "directory"}
													        for d in list(PurePosixPath(hf_file.rfilename    ).parents    )[:-1]
													    }    )
				def       UpperCAmelCase      (		self    :			List[Any]	, a_    :			str	, a_    :			str = "rb"	, **a_    :			Optional[int]	, )	->	int:



							'''simple docstring'''



							if not isinstance(self.repo_info	, a_    ):
										raise NotImplementedError(F"Open is only implemented for dataset repositories, but got {self.repo_info}"    )
							a__  :	List[Any]		 =			hf_hub_url(self.repo_info.id	, a_	, revision=self.repo_info.sha    )
							return fsspec.open(
							    a_	, mode=a_	, headers=get_authentication_headers_for_url(a_	, use_auth_token=self.token    )	, client_kwargs={"trust_env": True}	, ).open()
				def       UpperCAmelCase      (		self    :			Optional[Any]	, a_    :			Tuple	, **a_    :			Union[str, Any]    )	->	Any:



							'''simple docstring'''



							self._get_dirs()
							a__  :	Union[str, Any]		 =			self._strip_protocol(a_    )
							if path in self.dir_cache:
										return self.dir_cache[path]
							else:
										raise FileNotFoundError(a_    )






				def       UpperCAmelCase      (		self    :			Optional[Any]	, a_    :			Tuple	, a_    :			int=False	, **a_    :			str    )	->	Union[str, Any]:



							'''simple docstring'''



							self._get_dirs()
							a__  :	str		 =			PurePosixPath(path.strip("/"    )    )
							a__  :	Optional[Any]		 =			{}
							for p, f in self.dir_cache.items():
										a__  :	List[str]		 =			PurePosixPath(p.strip("/"    )    )
										a__  :	Optional[int]		 =			p.parent
										if root == path:
													a__  :	Optional[int]		 =			f
							a__  :	Tuple		 =			list(paths.values()    )
							if detail:
										return out
							else:
										return sorted(f["name"] for f in out    )






"""simple docstring"""






from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__UpperCAmelCase						=			logging.get_logger(__name__)






def      lowercase__ (					lowerCAmelCase__   :			Union[tf.Tensor, np.ndarray]			)    ->			List[int]:



			'''simple docstring'''
			if isinstance(lowerCAmelCase__							,			np.ndarray			):
						return list(tensor.shape			)

			a__  :	Optional[int]		 =			tf.shape(lowerCAmelCase__			)

			if tensor.shape == tf.TensorShape(lowerCAmelCase__			):
						return dynamic

			a__  :	Union[str, Any]		 =			tensor.shape.as_list()

			return [dynamic[i] if s is None else s for i, s in enumerate(lowerCAmelCase__			)]






def      lowercase__ (					lowerCAmelCase__   :			tf.Tensor							,			lowerCAmelCase__   :			Optional[int] = None							,			lowerCAmelCase__   :			Optional[str] = None			)    ->			tf.Tensor:



			'''simple docstring'''
			return tf.nn.softmax(logits=logits + 1E-9							,			axis=lowerCAmelCase__							,			name=lowerCAmelCase__			)






def      lowercase__ (					lowerCAmelCase__   :			List[Any]							,			lowerCAmelCase__   :			List[str]							,			lowerCAmelCase__   :			Any							,			lowerCAmelCase__   :			Union[str, Any]=1E-5							,			lowerCAmelCase__   :			str=-1			)    ->			int:



			'''simple docstring'''
			# This is a very simplified functional layernorm, designed to duplicate
			# the functionality of PyTorch nn.functional.layer_norm when this is needed to port
			# models in Transformers.

			if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(lowerCAmelCase__							,			lowerCAmelCase__			):
						raise NotImplementedError("Only 1D weight and bias tensors are supported for now, with only a single axis."			)

			# Get mean and variance on the axis to be normalized
			a__ ,	a__  :	Dict		 =			tf.nn.moments(lowerCAmelCase__							,			axes=[axis]							,			keepdims=lowerCAmelCase__			)

			if axis != -1:
						# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
						# on every dimension except axis
						a__  :	Dict		 =			[1] * inputs.shape.rank
						a__  :	Dict		 =			shape_list(lowerCAmelCase__			)[axis]
						a__  :	Any		 =			tf.reshape(lowerCAmelCase__							,			lowerCAmelCase__			)
						a__  :	List[Any]		 =			tf.reshape(lowerCAmelCase__							,			lowerCAmelCase__			)

			# Compute layer normalization using the batch_normalization
			# function.
			a__  :	List[str]		 =			tf.nn.batch_normalization(
			    lowerCAmelCase__							,			lowerCAmelCase__							,			lowerCAmelCase__							,			offset=lowerCAmelCase__							,			scale=lowerCAmelCase__							,			variance_epsilon=lowerCAmelCase__							,			)
			return outputs






def      lowercase__ (					lowerCAmelCase__   :			Optional[int]							,			lowerCAmelCase__   :			Any=0							,			lowerCAmelCase__   :			List[str]=-1			)    ->			List[str]:



			'''simple docstring'''
			# Replicates the behavior of torch.flatten in TF

			# If end_dim or start_dim is negative, count them from the end
			if end_dim < 0:
						end_dim += input.shape.rank
			if start_dim < 0:
						start_dim += input.shape.rank

			if start_dim == end_dim:
						return input

			a__  :	Optional[int]		 =			tf.shape(lowerCAmelCase__			)
			a__  :	str		 =			tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]			)
			a__  :	Union[str, Any]		 =			tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]							,			axis=0			)
			return tf.reshape(lowerCAmelCase__							,			lowerCAmelCase__			)






def      lowercase__ (					lowerCAmelCase__   :			tf.Tensor			)    ->			tf.Tensor:



			'''simple docstring'''
			if not isinstance(lowerCAmelCase__							,			tf.Tensor			):
						a__  :	Optional[Any]		 =			tf.convert_to_tensor(lowerCAmelCase__			)  # Catches stray NumPy inputs
			if encoder_attention_mask.shape.rank == 3:
						a__  :	Tuple		 =			encoder_attention_mask[:, None, :, :]
			if encoder_attention_mask.shape.rank == 2:
						a__  :	int		 =			encoder_attention_mask[:, None, None, :]
			# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
			# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
			# /transformer/transformer_layers.py#L270
			# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
			# encoder_extended_attention_mask.transpose(-1, -2))
			a__  :	int		 =			(
			    tf.cast(1							,			encoder_attention_mask.dtype			) - encoder_extended_attention_mask
			) * encoder_extended_attention_mask.dtype.min

			return encoder_extended_attention_mask






def      lowercase__ (					lowerCAmelCase__   :			tf.Tensor							,			lowerCAmelCase__   :			int							,			lowerCAmelCase__   :			str = "input_ids"			)    ->			None:



			'''simple docstring'''
			tf.debugging.assert_less(
			    lowerCAmelCase__							,			tf.cast(lowerCAmelCase__							,			dtype=tensor.dtype			)							,			message=(
			        F"The maximum value of {tensor_name} ({tf.math.reduce_max(lowerCAmelCase__			)}) must be smaller than the embedding "
			        F"layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."
			    )							,			)






def      lowercase__ (					lowerCAmelCase__   :			Dict							,			lowerCAmelCase__   :			str							,			lowerCAmelCase__   :			Dict			)    ->			Tuple:



			'''simple docstring'''
			a__  :	Optional[Any]		 =			6_4_5_1_2
			# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
			# because in that case even chunking the array would not make the saving
			# possible.
			a__  :	Optional[Any]		 =			[x for x in data if len(lowerCAmelCase__			) > HDF5_OBJECT_HEADER_LIMIT]

			# Expecting this to never be true.
			if bad_attributes:
						raise RuntimeError(
						    "The following attributes cannot be saved to HDF5 file because "
						    F"they are larger than {HDF5_OBJECT_HEADER_LIMIT} "
						    F"bytes: {bad_attributes}"			)

			a__  :	List[str]		 =			np.asarray(lowerCAmelCase__			)

			a__  :	List[str]		 =			1
			a__  :	str		 =			np.array_split(lowerCAmelCase__							,			lowerCAmelCase__			)

			# This will never loop forever thanks to the test above.
			while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data			):
						num_chunks += 1
						a__  :	str		 =			np.array_split(lowerCAmelCase__							,			lowerCAmelCase__			)

			if num_chunks > 1:
						for chunk_id, chunk_data in enumerate(lowerCAmelCase__			):
									a__  :	List[Any]		 =			chunk_data
			else:
						a__  :	List[str]		 =			data






def      lowercase__ (					lowerCAmelCase__   :			List[Any]							,			lowerCAmelCase__   :			Tuple			)    ->			Tuple:



			'''simple docstring'''
			if name in group.attrs:
						a__  :	str		 =			[n.decode("utf8"			) if hasattr(lowerCAmelCase__							,			"decode"			) else n for n in group.attrs[name]]
			else:
						a__  :	str		 =			[]
						a__  :	Any		 =			0
						while "%s%d" % (name, chunk_id) in group.attrs:
									data.extend(
									    [n.decode("utf8"			) if hasattr(lowerCAmelCase__							,			"decode"			) else n for n in group.attrs["%s%d" % (name, chunk_id)]]			)
									chunk_id += 1
			return data






def      lowercase__ (					lowerCAmelCase__   :			Tuple			)    ->			List[Any]:



			'''simple docstring'''

			def _expand_single_ad_tensor(lowerCAmelCase__   :			List[str]			):
						if isinstance(lowerCAmelCase__							,			tf.Tensor			) and t.shape.rank == 1:
									return tf.expand_dims(lowerCAmelCase__							,			axis=-1			)
						return t

			return tf.nest.map_structure(_expand_single_ad_tensor							,			lowerCAmelCase__			)