



import multiprocessing
import os
from typing import BinaryIO, Optional, Union

import fsspec

from .. import Dataset, Features, NamedSplit, config
from ..formatting import query_table
from ..packaged_modules.json.json import Json
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader




class 							lowerCAmelCase__  (	UpperCamelCase						):







					def __init__(       self      :     Dict			,		_A      :     NestedDataStructureLike[PathLike]			,		_A      :     Optional[NamedSplit] = None			,		_A      :     Optional[Features] = None			,		_A      :     str = None			,		_A      :     bool = False			,		_A      :     bool = False			,		_A      :     Optional[str] = None			,		_A      :     Optional[int] = None			,		**_A      :     Dict			,		):
											super().__init__(
											    _A			,		split=_A			,		features=_A			,		cache_dir=_A			,		keep_in_memory=_A			,		streaming=_A			,		num_proc=_A			,		**_A			,		)
											A__	:							Optional[int]						    = field
											A__	:							Dict						    = path_or_paths if isinstance(_A			,		_A) else {self.split: path_or_paths}
											A__	:							int						    = Json(
											    cache_dir=_A			,		data_files=_A			,		features=_A			,		field=_A			,		**_A			,		)







					def  _lowercase			(       self      :     Dict):
											# Build iterable dataset
											if self.streaming:
																	A__	:							Union[str, Any]						    = self.builder.as_streaming_dataset(split=self.split)
											# Build regular (map-style) dataset
											else:
																	A__	:							Optional[Any]						    = None
																	A__	:							Any						    = None
																	A__	:							Tuple						    = None
																	A__	:							Tuple						    = None

																	self.builder.download_and_prepare(
																	    download_config=_A			,		download_mode=_A			,		verification_mode=_A			,		base_path=_A			,		num_proc=self.num_proc			,		)
																	A__	:							Any						    = self.builder.as_dataset(
																	    split=self.split			,		verification_mode=_A			,		in_memory=self.keep_in_memory)
											return dataset




class 							lowerCAmelCase__  :







					def __init__(       self      :     Union[str, Any]			,		_A      :     Dataset			,		_A      :     Union[PathLike, BinaryIO]			,		_A      :     Optional[int] = None			,		_A      :     Optional[int] = None			,		**_A      :     Any			,		):
											if num_proc is not None and num_proc <= 0:
																	raise ValueError(F'num_proc {num_proc} must be an integer > 0.')

											A__	:							Tuple						    = dataset
											A__	:							Tuple						    = path_or_buf
											A__	:							int						    = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
											A__	:							Tuple						    = num_proc
											A__	:							Any						    = "utf-8"
											A__	:							Optional[int]						    = to_json_kwargs







					def  _lowercase			(       self      :     Union[str, Any]):
											A__	:							Any						    = self.to_json_kwargs.pop("path_or_buf"			,		_A)
											A__	:							Union[str, Any]						    = self.to_json_kwargs.pop("orient"			,		"records")
											A__	:							List[Any]						    = self.to_json_kwargs.pop("lines"			,		True if orient == "records" else False)
											A__	:							List[Any]						    = self.to_json_kwargs.pop("index"			,		False if orient in ["split", "table"] else True)
											A__	:							int						    = self.to_json_kwargs.pop("compression"			,		_A)

											if compression not in [None, "infer", "gzip", "bz2", "xz"]:
																	raise NotImplementedError(F'`datasets` currently does not support {compression} compression')

											if isinstance(self.path_or_buf			,		(str, bytes, os.PathLike)):
																	with fsspec.open(self.path_or_buf			,		"wb"			,		compression=_A) as buffer:
																							A__	:							int						    = self._write(file_obj=_A			,		orient=_A			,		lines=_A			,		index=_A			,		**self.to_json_kwargs)
											else:
																	if compression:
																							raise NotImplementedError(
																							    F'The compression parameter is not supported when writing to a buffer, but compression={compression}'
																							    " was passed. Please provide a local path instead.")
																	A__	:							Optional[Any]						    = self._write(
																	    file_obj=self.path_or_buf			,		orient=_A			,		lines=_A			,		index=_A			,		**self.to_json_kwargs)
											return written







					def  _lowercase			(       self      :     List[Any]			,		_A      :     int):
											A__	:							Union[str, Any]						    = args

											A__	:							Dict						    = query_table(
											    table=self.dataset.data			,		key=slice(_A			,		offset + self.batch_size)			,		indices=self.dataset._indices			,		)
											A__	:							Dict						    = batch.to_pandas().to_json(
											    path_or_buf=_A			,		orient=_A			,		lines=_A			,		index=_A			,		**_A)
											if not json_str.endswith("\n"):
																	json_str += "\n"
											return json_str.encode(self.encoding)







					def  _lowercase			(       self      :     List[str]			,		_A      :     BinaryIO			,		_A      :     str			,		_A      :     List[Any]			,		_A      :     Optional[Any]			,		**_A      :     Optional[Any]			,		):
											A__	:							Any						    = 0

											if self.num_proc is None or self.num_proc == 1:
																	for offset in logging.tqdm(
																	    range(0			,		len(self.dataset)			,		self.batch_size)			,		unit="ba"			,		disable=not logging.is_progress_bar_enabled()			,		desc="Creating json from Arrow format"			,		):
																							A__	:							List[str]						    = self._batch_json((offset, orient, lines, index, to_json_kwargs))
																							written += file_obj.write(_A)
											else:
																	A__	:							Union[str, Any]						    = len(self.dataset), self.batch_size
																	with multiprocessing.Pool(self.num_proc) as pool:
																							for json_str in logging.tqdm(
																							    pool.imap(
																							        self._batch_json			,		[(offset, orient, lines, index, to_json_kwargs) for offset in range(0			,		_A			,		_A)]			,		)			,		total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size			,		unit="ba"			,		disable=not logging.is_progress_bar_enabled()			,		desc="Creating json from Arrow format"			,		):
																													written += file_obj.write(_A)

											return written




import json
import os
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test


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

from test_module.custom_configuration import CustomConfig  # noqa E402


snake_case    :						List[str]  =						{
    'return_dict': False,
    'output_hidden_states': True,
    'output_attentions': True,
    'torchscript': True,
    'torch_dtype': 'float16',
    'use_bfloat16': True,
    'tf_legacy_loss': True,
    'pruned_heads': {'a': 1},
    'tie_word_embeddings': False,
    'is_decoder': True,
    'cross_attention_hidden_size': 1_2_8,
    'add_cross_attention': True,
    'tie_encoder_decoder': True,
    'max_length': 5_0,
    'min_length': 3,
    'do_sample': True,
    'early_stopping': True,
    'num_beams': 3,
    'num_beam_groups': 3,
    'diversity_penalty': 0.5,
    'temperature': 2.0,
    'top_k': 1_0,
    'top_p': 0.7,
    'typical_p': 0.2,
    'repetition_penalty': 0.8,
    'length_penalty': 0.8,
    'no_repeat_ngram_size': 5,
    'encoder_no_repeat_ngram_size': 5,
    'bad_words_ids': [1, 2, 3],
    'num_return_sequences': 3,
    'chunk_size_feed_forward': 5,
    'output_scores': True,
    'return_dict_in_generate': True,
    'forced_bos_token_id': 2,
    'forced_eos_token_id': 3,
    'remove_invalid_values': True,
    'architectures': ['BertModel'],
    'finetuning_task': 'translation',
    'id2label': {0: 'label'},
    'label2id': {'label': '0'},
    'tokenizer_class': 'BertTokenizerFast',
    'prefix': 'prefix',
    'bos_token_id': 6,
    'pad_token_id': 7,
    'eos_token_id': 8,
    'sep_token_id': 9,
    'decoder_start_token_id': 1_0,
    'exponential_decay_length_penalty': (5, 1.01),
    'suppress_tokens': [0, 1],
    'begin_suppress_tokens': 2,
    'task_specific_params': {'translation': 'some_params'},
    'problem_type': 'regression',
}




@is_staging_test
class 							lowerCAmelCase__  (	unittest.TestCase						):







					@classmethod
					def  _lowercase			(       cls      :     str):
											A__	:							int						    = TOKEN
											HfFolder.save_token(_A)







					@classmethod
					def  _lowercase			(       cls      :     Optional[Any]):
											try:
																	delete_repo(token=cls._token			,		repo_id="test-config")
											except HTTPError:
																	pass

											try:
																	delete_repo(token=cls._token			,		repo_id="valid_org/test-config-org")
											except HTTPError:
																	pass

											try:
																	delete_repo(token=cls._token			,		repo_id="test-dynamic-config")
											except HTTPError:
																	pass







					def  _lowercase			(       self      :     Dict):
											A__	:							List[str]						    = BertConfig(
											    vocab_size=99			,		hidden_size=32			,		num_hidden_layers=5			,		num_attention_heads=4			,		intermediate_size=37)
											config.push_to_hub("test-config"			,		use_auth_token=self._token)

											A__	:							Dict						    = BertConfig.from_pretrained(F'{USER}/test-config')
											for k, v in config.to_dict().items():
																	if k != "transformers_version":
																							self.assertEqual(_A			,		getattr(_A			,		_A))

        # Reset repo
											delete_repo(token=self._token			,		repo_id="test-config")

											# Push to hub via save_pretrained
											with tempfile.TemporaryDirectory() as tmp_dir:
																	config.save_pretrained(_A			,		repo_id="test-config"			,		push_to_hub=_A			,		use_auth_token=self._token)

											A__	:							Tuple						    = BertConfig.from_pretrained(F'{USER}/test-config')
											for k, v in config.to_dict().items():
																	if k != "transformers_version":
																							self.assertEqual(_A			,		getattr(_A			,		_A))







					def  _lowercase			(       self      :     List[Any]):
											A__	:							List[Any]						    = BertConfig(
											    vocab_size=99			,		hidden_size=32			,		num_hidden_layers=5			,		num_attention_heads=4			,		intermediate_size=37)
											config.push_to_hub("valid_org/test-config-org"			,		use_auth_token=self._token)

											A__	:							Union[str, Any]						    = BertConfig.from_pretrained("valid_org/test-config-org")
											for k, v in config.to_dict().items():
																	if k != "transformers_version":
																							self.assertEqual(_A			,		getattr(_A			,		_A))

        # Reset repo
											delete_repo(token=self._token			,		repo_id="valid_org/test-config-org")

											# Push to hub via save_pretrained
											with tempfile.TemporaryDirectory() as tmp_dir:
																	config.save_pretrained(
																	    _A			,		repo_id="valid_org/test-config-org"			,		push_to_hub=_A			,		use_auth_token=self._token)

											A__	:							List[str]						    = BertConfig.from_pretrained("valid_org/test-config-org")
											for k, v in config.to_dict().items():
																	if k != "transformers_version":
																							self.assertEqual(_A			,		getattr(_A			,		_A))







					def  _lowercase			(       self      :     Optional[int]):
											CustomConfig.register_for_auto_class()
											A__	:							Optional[Any]						    = CustomConfig(attribute=42)

											config.push_to_hub("test-dynamic-config"			,		use_auth_token=self._token)

											# This has added the proper auto_map field to the config
											self.assertDictEqual(config.auto_map			,		{"AutoConfig": "custom_configuration.CustomConfig"})

											A__	:							Optional[Any]						    = AutoConfig.from_pretrained(F'{USER}/test-dynamic-config'			,		trust_remote_code=_A)
											# Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
											self.assertEqual(new_config.__class__.__name__			,		"CustomConfig")
											self.assertEqual(new_config.attribute			,		42)




class 							lowerCAmelCase__  (	unittest.TestCase						):







					def  _lowercase			(       self      :     Optional[int]):
											A__	:							List[str]						    = GPTaConfig()

											# attempt to modify each of int/float/bool/str config records and verify they were updated
											A__	:							Optional[int]						    = c.n_embd + 1  # int
											A__	:							Tuple						    = c.resid_pdrop + 1.0  # float
											A__	:							Any						    = not c.scale_attn_weights  # bool
											A__	:							List[Any]						    = c.summary_type + "foo"  # str
											c.update_from_string(
											    F'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}')
											self.assertEqual(_A			,		c.n_embd			,		"mismatch for key: n_embd")
											self.assertEqual(_A			,		c.resid_pdrop			,		"mismatch for key: resid_pdrop")
											self.assertEqual(_A			,		c.scale_attn_weights			,		"mismatch for key: scale_attn_weights")
											self.assertEqual(_A			,		c.summary_type			,		"mismatch for key: summary_type")







					def  _lowercase			(       self      :     Optional[int]):
											A__	:							Any						    = PretrainedConfig()
											A__	:							Optional[Any]						    = [key for key in base_config.__dict__ if key not in config_common_kwargs]
											# If this part of the test fails, you have arguments to addin config_common_kwargs above.
											self.assertListEqual(
											    _A			,		["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"])
											A__	:							Optional[Any]						    = [key for key, value in config_common_kwargs.items() if value == getattr(_A			,		_A)]
											if len(_A) > 0:
																	raise ValueError(
																	    "The following keys are set with the default values in"
																	    " `test_configuration_common.config_common_kwargs` pick another value for them:"
																	    F' {", ".join(_A)}.')







					def  _lowercase			(       self      :     List[str]):
											with self.assertRaises(_A):
																	# config is in subfolder, the following should not work without specifying the subfolder
																	A__	:							Any						    = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder")

											A__	:							str						    = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder"			,		subfolder="bert")

											self.assertIsNotNone(_A)







					def  _lowercase			(       self      :     List[str]):
											# A mock response for an HTTP head request to emulate server down
											A__	:							Tuple						    = mock.Mock()
											A__	:							Dict						    = 500
											A__	:							Union[str, Any]						    = {}
											A__	:							List[Any]						    = HTTPError
											A__	:							Optional[int]						    = {}

											# Download this model to make sure it's in the cache.
											A__	:							Any						    = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert")

											# Under the mock environment we get a 500 error when trying to reach the model.
											with mock.patch("requests.Session.request"			,		return_value=_A) as mock_head:
																	A__	:							List[str]						    = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert")
																	# This check we did call the fake head request
																	mock_head.assert_called()







					def  _lowercase			(       self      :     Optional[int]):
											# This test is for deprecated behavior and can be removed in v5
											A__	:							List[str]						    = BertConfig.from_pretrained(
											    "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json")







					def  _lowercase			(       self      :     Union[str, Any]):
											A__	:							Union[str, Any]						    = AutoConfig.from_pretrained("bert-base-cased")
											A__	:							str						    = ["config.4.0.0.json"]

											with tempfile.TemporaryDirectory() as tmp_dir:
																	configuration.save_pretrained(_A)
																	A__	:							Dict						    = 2
																	json.dump(configuration.to_dict()			,		open(os.path.join(_A			,		"config.4.0.0.json")			,		"w"))

																	# This should pick the new configuration file as the version of Transformers is > 4.0.0
																	A__	:							Any						    = AutoConfig.from_pretrained(_A)
																	self.assertEqual(new_configuration.hidden_size			,		2)

																	# Will need to be adjusted if we reach v42 and this test is still here.
																	# Should pick the old configuration file as the version of Transformers is < 4.42.0
																	A__	:							str						    = ["config.42.0.0.json"]
																	A__	:							Optional[int]						    = 768
																	configuration.save_pretrained(_A)
																	shutil.move(os.path.join(_A			,		"config.4.0.0.json")			,		os.path.join(_A			,		"config.42.0.0.json"))
																	A__	:							Optional[int]						    = AutoConfig.from_pretrained(_A)
																	self.assertEqual(new_configuration.hidden_size			,		768)







					def  _lowercase			(       self      :     Optional[int]):
											# This repo has two configuration files, one for v4.0.0 and above with a different hidden size.
											A__	:							List[str]						    = "hf-internal-testing/test-two-configs"

											import transformers as new_transformers

											A__	:							int						    = "v4.0.0"
											A__    ,       A__	:							str						    = new_transformers.models.auto.AutoConfig.from_pretrained(
											    _A			,		return_unused_kwargs=_A)
											self.assertEqual(new_configuration.hidden_size			,		2)
											# This checks `_configuration_file` ia not kept in the kwargs by mistake.
											self.assertDictEqual(_A			,		{})

											# Testing an older version by monkey-patching the version in the module it's used.
											import transformers as old_transformers

											A__	:							List[Any]						    = "v3.0.0"
											A__	:							Optional[Any]						    = old_transformers.models.auto.AutoConfig.from_pretrained(_A)
											self.assertEqual(old_configuration.hidden_size			,		768)