


'''simple docstring'''



import os
import tempfile
import unittest

from transformers import FlaubertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          FlaubertForMultipleChoice,
          FlaubertForQuestionAnswering,
          FlaubertForQuestionAnsweringSimple,
          FlaubertForSequenceClassification,
          FlaubertForTokenClassification,
          FlaubertModel,
          FlaubertWithLMHeadModel,
      )
      from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST



class      a    (		_a	):


     """simple docstring"""






     def __init__(    self					:		Any							,			snake_case					:		List[str]							,			snake_case					:		List[Any]=13							,			snake_case					:		Optional[Any]=7							,			snake_case					:		Optional[Any]=True							,			snake_case					:		Tuple=True							,			snake_case					:		List[str]=True							,			snake_case					:		Dict=True							,			snake_case					:		List[Any]=True							,			snake_case					:		str=False							,			snake_case					:		Tuple=False							,			snake_case					:		str=False							,			snake_case					:		Any=2							,			snake_case					:		Optional[Any]=99							,			snake_case					:		int=0							,			snake_case					:		str=32							,			snake_case					:		Dict=5							,			snake_case					:		Any=4							,			snake_case					:		List[str]=0.1							,			snake_case					:		List[Any]=0.1							,			snake_case					:		Optional[int]=512							,			snake_case					:		List[str]=12							,			snake_case					:		Dict=2							,			snake_case					:		Union[str, Any]=0.02							,			snake_case					:		List[str]=3							,			snake_case					:		Optional[Any]=4							,			snake_case					:		List[str]="last"							,			snake_case					:		Dict=None							,			snake_case					:		str=None							,			)						->							Tuple:
          __UpperCAmelCase     :			Dict  							=      parent
          __UpperCAmelCase     :			List[str]  							=      batch_size
          __UpperCAmelCase     :			Any  							=      seq_length
          __UpperCAmelCase     :			Optional[int]  							=      is_training
          __UpperCAmelCase     :			int  							=      use_input_lengths
          __UpperCAmelCase     :			Tuple  							=      use_token_type_ids
          __UpperCAmelCase     :			Optional[int]  							=      use_labels
          __UpperCAmelCase     :			int  							=      gelu_activation
          __UpperCAmelCase     :			Any  							=      sinusoidal_embeddings
          __UpperCAmelCase     :			List[str]  							=      causal
          __UpperCAmelCase     :			List[str]  							=      asm
          __UpperCAmelCase     :			Optional[int]  							=      n_langs
          __UpperCAmelCase     :			str  							=      vocab_size
          __UpperCAmelCase     :			Dict  							=      n_special
          __UpperCAmelCase     :			List[str]  							=      hidden_size
          __UpperCAmelCase     :			Union[str, Any]  							=      num_hidden_layers
          __UpperCAmelCase     :			Optional[int]  							=      num_attention_heads
          __UpperCAmelCase     :			Optional[Any]  							=      hidden_dropout_prob
          __UpperCAmelCase     :			Union[str, Any]  							=      attention_probs_dropout_prob
          __UpperCAmelCase     :			List[str]  							=      max_position_embeddings
          __UpperCAmelCase     :			Any  							=      type_vocab_size
          __UpperCAmelCase     :			str  							=      type_sequence_label_size
          __UpperCAmelCase     :			Dict  							=      initializer_range
          __UpperCAmelCase     :			int  							=      num_labels
          __UpperCAmelCase     :			Union[str, Any]  							=      num_choices
          __UpperCAmelCase     :			List[Any]  							=      summary_type
          __UpperCAmelCase     :			Tuple  							=      use_proj
          __UpperCAmelCase     :			Optional[int]  							=      scope

     def 			lowerCamelCase__			(    self					:		int      )						->							Any:
          __UpperCAmelCase     :			Dict  							=      ids_tensor([self.batch_size, self.seq_length]							,			self.vocab_size      )
          __UpperCAmelCase     :			Tuple  							=      random_attention_mask([self.batch_size, self.seq_length]      )

          __UpperCAmelCase     :			Union[str, Any]  							=      None
          if self.use_input_lengths:
               __UpperCAmelCase     :			Any  							=      (
                   ids_tensor([self.batch_size]							,			vocab_size=2      ) + self.seq_length - 2
               )  # small variation of seq_length

          __UpperCAmelCase     :			List[str]  							=      None
          if self.use_token_type_ids:
               __UpperCAmelCase     :			Dict  							=      ids_tensor([self.batch_size, self.seq_length]							,			self.n_langs      )

          __UpperCAmelCase     :			List[str]  							=      None
          __UpperCAmelCase     :			int  							=      None
          __UpperCAmelCase     :			List[Any]  							=      None
          if self.use_labels:
               __UpperCAmelCase     :			Dict  							=      ids_tensor([self.batch_size]							,			self.type_sequence_label_size      )
               __UpperCAmelCase     :			str  							=      ids_tensor([self.batch_size, self.seq_length]							,			self.num_labels      )
               __UpperCAmelCase     :			Optional[int]  							=      ids_tensor([self.batch_size]							,			2      ).float()
               __UpperCAmelCase     :			Optional[int]  							=      ids_tensor([self.batch_size]							,			self.num_choices      )

          __UpperCAmelCase     :			List[Any]  							=      self.get_config()

          return (
              config,
              input_ids,
              token_type_ids,
              input_lengths,
              sequence_labels,
              token_labels,
              is_impossible_labels,
              choice_labels,
              input_mask,
          )

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							str:
          return FlaubertConfig(
              vocab_size=self.vocab_size							,			n_special=self.n_special							,			emb_dim=self.hidden_size							,			n_layers=self.num_hidden_layers							,			n_heads=self.num_attention_heads							,			dropout=self.hidden_dropout_prob							,			attention_dropout=self.attention_probs_dropout_prob							,			gelu_activation=self.gelu_activation							,			sinusoidal_embeddings=self.sinusoidal_embeddings							,			asm=self.asm							,			causal=self.causal							,			n_langs=self.n_langs							,			max_position_embeddings=self.max_position_embeddings							,			initializer_range=self.initializer_range							,			summary_type=self.summary_type							,			use_proj=self.use_proj							,			)

     def 			lowerCamelCase__			(    self					:		List[str]							,			snake_case					:		Tuple							,			snake_case					:		Any							,			snake_case					:		str							,			snake_case					:		Optional[int]							,			snake_case					:		str							,			snake_case					:		Optional[int]							,			snake_case					:		str							,			snake_case					:		Optional[int]							,			snake_case					:		Optional[Any]							,			)						->							List[Any]:
          __UpperCAmelCase     :			str  							=      FlaubertModel(config=snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			Optional[int]  							=      model(snake_case							,			lengths=snake_case							,			langs=snake_case      )
          __UpperCAmelCase     :			Any  							=      model(snake_case							,			langs=snake_case      )
          __UpperCAmelCase     :			Tuple  							=      model(snake_case      )
          self.parent.assertEqual(result.last_hidden_state.shape							,			(self.batch_size, self.seq_length, self.hidden_size)      )

     def 			lowerCamelCase__			(    self					:		Union[str, Any]							,			snake_case					:		int							,			snake_case					:		int							,			snake_case					:		str							,			snake_case					:		Tuple							,			snake_case					:		int							,			snake_case					:		int							,			snake_case					:		List[str]							,			snake_case					:		Union[str, Any]							,			snake_case					:		Optional[Any]							,			)						->							Optional[Any]:
          __UpperCAmelCase     :			str  							=      FlaubertWithLMHeadModel(snake_case      )
          model.to(snake_case      )
          model.eval()

          __UpperCAmelCase     :			Dict  							=      model(snake_case							,			token_type_ids=snake_case							,			labels=snake_case      )
          self.parent.assertEqual(result.loss.shape							,			()      )
          self.parent.assertEqual(result.logits.shape							,			(self.batch_size, self.seq_length, self.vocab_size)      )

     def 			lowerCamelCase__			(    self					:		Dict							,			snake_case					:		List[Any]							,			snake_case					:		List[str]							,			snake_case					:		str							,			snake_case					:		Optional[Any]							,			snake_case					:		Tuple							,			snake_case					:		int							,			snake_case					:		str							,			snake_case					:		str							,			snake_case					:		int							,			)						->							int:
          __UpperCAmelCase     :			Optional[Any]  							=      FlaubertForQuestionAnsweringSimple(snake_case      )
          model.to(snake_case      )
          model.eval()

          __UpperCAmelCase     :			Optional[Any]  							=      model(snake_case      )

          __UpperCAmelCase     :			Any  							=      model(snake_case							,			start_positions=snake_case							,			end_positions=snake_case      )
          self.parent.assertEqual(result.start_logits.shape							,			(self.batch_size, self.seq_length)      )
          self.parent.assertEqual(result.end_logits.shape							,			(self.batch_size, self.seq_length)      )

     def 			lowerCamelCase__			(    self					:		Tuple							,			snake_case					:		List[Any]							,			snake_case					:		str							,			snake_case					:		Tuple							,			snake_case					:		Union[str, Any]							,			snake_case					:		Tuple							,			snake_case					:		List[str]							,			snake_case					:		Dict							,			snake_case					:		Optional[Any]							,			snake_case					:		Optional[Any]							,			)						->							Dict:
          __UpperCAmelCase     :			Any  							=      FlaubertForQuestionAnswering(snake_case      )
          model.to(snake_case      )
          model.eval()

          __UpperCAmelCase     :			Optional[int]  							=      model(snake_case      )

          __UpperCAmelCase     :			List[Any]  							=      model(
              snake_case							,			start_positions=snake_case							,			end_positions=snake_case							,			cls_index=snake_case							,			is_impossible=snake_case							,			p_mask=snake_case							,			)

          __UpperCAmelCase     :			Dict  							=      model(
              snake_case							,			start_positions=snake_case							,			end_positions=snake_case							,			cls_index=snake_case							,			is_impossible=snake_case							,			)

          ((__UpperCAmelCase)							,       )     :			Union[str, Any]  							=      result_with_labels.to_tuple()

          __UpperCAmelCase     :			Any  							=      model(snake_case							,			start_positions=snake_case							,			end_positions=snake_case      )

          ((__UpperCAmelCase)							,       )     :			Dict  							=      result_with_labels.to_tuple()

          self.parent.assertEqual(result_with_labels.loss.shape							,			()      )
          self.parent.assertEqual(result.start_top_log_probs.shape							,			(self.batch_size, model.config.start_n_top)      )
          self.parent.assertEqual(result.start_top_index.shape							,			(self.batch_size, model.config.start_n_top)      )
          self.parent.assertEqual(
              result.end_top_log_probs.shape							,			(self.batch_size, model.config.start_n_top * model.config.end_n_top)      )
          self.parent.assertEqual(
              result.end_top_index.shape							,			(self.batch_size, model.config.start_n_top * model.config.end_n_top)      )
          self.parent.assertEqual(result.cls_logits.shape							,			(self.batch_size,)      )

     def 			lowerCamelCase__			(    self					:		Union[str, Any]							,			snake_case					:		Tuple							,			snake_case					:		List[str]							,			snake_case					:		Tuple							,			snake_case					:		List[Any]							,			snake_case					:		List[Any]							,			snake_case					:		Any							,			snake_case					:		int							,			snake_case					:		Union[str, Any]							,			snake_case					:		Tuple							,			)						->							List[Any]:
          __UpperCAmelCase     :			List[Any]  							=      FlaubertForSequenceClassification(snake_case      )
          model.to(snake_case      )
          model.eval()

          __UpperCAmelCase     :			Optional[Any]  							=      model(snake_case      )
          __UpperCAmelCase     :			int  							=      model(snake_case							,			labels=snake_case      )

          self.parent.assertEqual(result.loss.shape							,			()      )
          self.parent.assertEqual(result.logits.shape							,			(self.batch_size, self.type_sequence_label_size)      )

     def 			lowerCamelCase__			(    self					:		Dict							,			snake_case					:		List[Any]							,			snake_case					:		Union[str, Any]							,			snake_case					:		List[Any]							,			snake_case					:		Optional[int]							,			snake_case					:		Union[str, Any]							,			snake_case					:		Optional[int]							,			snake_case					:		Optional[int]							,			snake_case					:		Any							,			snake_case					:		int							,			)						->							Any:
          __UpperCAmelCase     :			Tuple  							=      self.num_labels
          __UpperCAmelCase     :			Optional[int]  							=      FlaubertForTokenClassification(snake_case      )
          model.to(snake_case      )
          model.eval()

          __UpperCAmelCase     :			Tuple  							=      model(snake_case							,			attention_mask=snake_case							,			labels=snake_case      )
          self.parent.assertEqual(result.logits.shape							,			(self.batch_size, self.seq_length, self.num_labels)      )

     def 			lowerCamelCase__			(    self					:		List[str]							,			snake_case					:		List[Any]							,			snake_case					:		int							,			snake_case					:		Union[str, Any]							,			snake_case					:		Tuple							,			snake_case					:		str							,			snake_case					:		Tuple							,			snake_case					:		int							,			snake_case					:		Union[str, Any]							,			snake_case					:		Optional[Any]							,			)						->							Union[str, Any]:
          __UpperCAmelCase     :			Union[str, Any]  							=      self.num_choices
          __UpperCAmelCase     :			Any  							=      FlaubertForMultipleChoice(config=snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			Dict  							=      input_ids.unsqueeze(1      ).expand(-1							,			self.num_choices							,			-1      ).contiguous()
          __UpperCAmelCase     :			Dict  							=      token_type_ids.unsqueeze(1      ).expand(-1							,			self.num_choices							,			-1      ).contiguous()
          __UpperCAmelCase     :			Optional[Any]  							=      input_mask.unsqueeze(1      ).expand(-1							,			self.num_choices							,			-1      ).contiguous()
          __UpperCAmelCase     :			int  							=      model(
              snake_case							,			attention_mask=snake_case							,			token_type_ids=snake_case							,			labels=snake_case							,			)
          self.parent.assertEqual(result.logits.shape							,			(self.batch_size, self.num_choices)      )






     def 			lowerCamelCase__			(    self					:		Dict      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Dict  							=      self.prepare_config_and_inputs()
          (
              (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       
          )     :			str  							=      config_and_inputs
          __UpperCAmelCase     :			List[Any]  							=      {
              '''input_ids''': input_ids,
              '''token_type_ids''': token_type_ids,
              '''lengths''': input_lengths,
              '''attention_mask''': input_mask,
          }
          return config, inputs_dict



@require_torch
class      a    (		_a     ,  _a     ,  unittest.TestCase	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			Tuple							       =       (
         (
             FlaubertModel,
             FlaubertWithLMHeadModel,
             FlaubertForQuestionAnswering,
             FlaubertForQuestionAnsweringSimple,
             FlaubertForSequenceClassification,
             FlaubertForTokenClassification,
             FlaubertForMultipleChoice,
         )
         if is_torch_available()
         else ()
     )
     SCREAMING_SNAKE_CASE	:			str							       =       (
         {
             "feature-extraction": FlaubertModel,
             "fill-mask": FlaubertWithLMHeadModel,
             "question-answering": FlaubertForQuestionAnsweringSimple,
             "text-classification": FlaubertForSequenceClassification,
             "token-classification": FlaubertForTokenClassification,
             "zero-shot": FlaubertForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )

     def 			lowerCamelCase__			(    self					:		List[str]							,			snake_case					:		Tuple							,			snake_case					:		str							,			snake_case					:		str							,			snake_case					:		Optional[Any]							,			snake_case					:		Dict      )						->							List[Any]:
          if (
              pipeline_test_casse_name == "QAPipelineTests"
              and tokenizer_name is not None
              and not tokenizer_name.endswith('''Fast'''      )
          ):
               # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
               # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
               # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
               return True

          return False

     def 			lowerCamelCase__			(    self					:		List[Any]							,			snake_case					:		Tuple							,			snake_case					:		int							,			snake_case					:		Union[str, Any]=False      )						->							str:
          __UpperCAmelCase     :			Union[str, Any]  							=      super()._prepare_for_class(snake_case							,			snake_case							,			return_labels=snake_case      )

          if return_labels:
               if model_class.__name__ == "FlaubertForQuestionAnswering":
                    __UpperCAmelCase     :			List[Any]  							=      torch.zeros(
                        self.model_tester.batch_size							,			dtype=torch.long							,			device=snake_case      )
                    __UpperCAmelCase     :			List[Any]  							=      torch.zeros(
                        self.model_tester.batch_size							,			dtype=torch.long							,			device=snake_case      )

          return inputs_dict

     def 			lowerCamelCase__			(    self					:		Tuple      )						->							List[str]:
          __UpperCAmelCase     :			Union[str, Any]  							=      FlaubertModelTester(self      )
          __UpperCAmelCase     :			Any  							=      ConfigTester(self							,			config_class=snake_case							,			emb_dim=37      )

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							Tuple:
          self.config_tester.run_common_tests()

     def 			lowerCamelCase__			(    self					:		Any      )						->							Optional[int]:
          __UpperCAmelCase     :			int  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_flaubert_model(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Tuple      )						->							int:
          __UpperCAmelCase     :			List[str]  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_flaubert_lm_head(*snake_case      )

     def 			lowerCamelCase__			(    self					:		int      )						->							List[str]:
          __UpperCAmelCase     :			int  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_flaubert_simple_qa(*snake_case      )

     def 			lowerCamelCase__			(    self					:		str      )						->							List[Any]:
          __UpperCAmelCase     :			str  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_flaubert_qa(*snake_case      )

     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							Optional[Any]:
          __UpperCAmelCase     :			Tuple  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_flaubert_sequence_classif(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Union[str, Any]  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_flaubert_token_classif(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							Dict:
          __UpperCAmelCase     :			Tuple  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_flaubert_multiple_choice(*snake_case      )

     @slow
     def 			lowerCamelCase__			(    self					:		str      )						->							List[str]:
          for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __UpperCAmelCase     :			List[str]  							=      FlaubertModel.from_pretrained(snake_case      )
               self.assertIsNotNone(snake_case      )






     @slow
     @require_torch_gpu
     def 			lowerCamelCase__			(    self					:		int      )						->							Optional[int]:
          __UpperCAmelCase							,       __UpperCAmelCase     :			Any  							=      self.model_tester.prepare_config_and_inputs_for_common()
          for model_class in self.all_model_classes:
               # FlauBertForMultipleChoice behaves incorrectly in JIT environments.
               if model_class == FlaubertForMultipleChoice:
                    return

               __UpperCAmelCase     :			str  							=      True
               __UpperCAmelCase     :			Optional[int]  							=      model_class(config=snake_case      )

               __UpperCAmelCase     :			List[Any]  							=      self._prepare_for_class(snake_case							,			snake_case      )
               __UpperCAmelCase     :			int  							=      torch.jit.trace(
                   snake_case							,			(inputs_dict['''input_ids'''].to('''cpu'''      ), inputs_dict['''attention_mask'''].to('''cpu'''      ))      )

               with tempfile.TemporaryDirectory() as tmp:
                    torch.jit.save(snake_case							,			os.path.join(snake_case							,			'''traced_model.pt'''      )      )
                    __UpperCAmelCase     :			int  							=      torch.jit.load(os.path.join(snake_case							,			'''traced_model.pt'''      )							,			map_location=snake_case      )
                    loaded(inputs_dict['''input_ids'''].to(snake_case      )							,			inputs_dict['''attention_mask'''].to(snake_case      )      )



@require_torch
class      a    (		unittest.TestCase	):


     """simple docstring"""






     @slow
     def 			lowerCamelCase__			(    self					:		Dict      )						->							List[Any]:
          __UpperCAmelCase     :			str  							=      FlaubertModel.from_pretrained('''flaubert/flaubert_base_cased'''      )
          __UpperCAmelCase     :			Union[str, Any]  							=      torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]      )
          with torch.no_grad():
               __UpperCAmelCase     :			Any  							=      model(snake_case      )[0]
          __UpperCAmelCase     :			Optional[Any]  							=      torch.Size((1, 11, 768)      )
          self.assertEqual(output.shape							,			snake_case      )
          __UpperCAmelCase     :			str  							=      torch.tensor(
              [[[-2.6_251, -1.4_298, -0.0_227], [-2.8_510, -1.6_387, 0.2_258], [-2.8_114, -1.1_832, -0.3_066]]]      )

          self.assertTrue(torch.allclose(output[:, :3, :3]							,			snake_case							,			atol=1E-4      )      )



'''simple docstring'''



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



@dataclass
class      a    (		datasets.BuilderConfig	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			Optional[datasets.Features]							       =       None
     SCREAMING_SNAKE_CASE	:			str							       =       "utf-8"
     SCREAMING_SNAKE_CASE	:			Optional[str]							       =       None
     SCREAMING_SNAKE_CASE	:			Optional[str]							       =       None
     SCREAMING_SNAKE_CASE	:			bool							       =       True  # deprecated
     SCREAMING_SNAKE_CASE	:			Optional[int]							       =       None  # deprecated
     SCREAMING_SNAKE_CASE	:			int							       =       1_0 << 2_0  # 10MB
     SCREAMING_SNAKE_CASE	:			Optional[bool]							       =       None



class      a    (		datasets.ArrowBasedBuilder	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			Tuple							       =       JsonConfig

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

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






     def 			lowerCamelCase__			(    self					:		Tuple							,			snake_case					:		Any      )						->							Optional[int]:
          for file_idx, file in enumerate(itertools.chain.from_iterable(snake_case      )      ):
               # 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(snake_case							,			encoding=self.config.encoding							,			errors=self.config.encoding_errors      ) as f:
                         __UpperCAmelCase     :			Optional[int]  							=      json.load(snake_case      )

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

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

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