

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


snake_case_			  = datasets.utils.logging.get_logger(__name__)


@dataclass
class       SCREAMING_SNAKE_CASE__					(datasets.BuilderConfig     ):
    __lowerCamelCase						:       Optional[datasets.Features]														=     None
    __lowerCamelCase						:       str														=     "utf-8"
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       bool														=     True  # deprecated
    __lowerCamelCase						:       Optional[int]														=     None  # deprecated
    __lowerCamelCase						:       int														=     10 << 20  # 10MB
    __lowerCamelCase						:       Optional[bool]														=     None



class       SCREAMING_SNAKE_CASE__					(datasets.ArrowBasedBuilder     ):
    __lowerCamelCase						:       int														=     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')
              lowercase__    :   int      =       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						,   a):
         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}""")
         lowercase__    :   int      =       dl_manager.download_and_extract(self.config.data_files)
         if isinstance(a						,   (str, list, tuple)):
              lowercase__    :   Any      =       data_files
              if isinstance(a						,   a):
                   lowercase__    :   Optional[Any]      =       [files]
              lowercase__    :   int      =       [dl_manager.iter_files(a) for file in files]
              return [datasets.SplitGenerator(name=datasets.Split.TRAIN						,   gen_kwargs={'files': files})]
         lowercase__    :   Optional[Any]      =       []
         for split_name, files in data_files.items():
              if isinstance(a						,   a):
                   lowercase__    :   Tuple      =       [files]
              lowercase__    :   str      =       [dl_manager.iter_files(a) for file in files]
              splits.append(datasets.SplitGenerator(name=a						,   gen_kwargs={'files': files}))
         return splits





    def       snake_case_				(      self						,   a):
         if self.config.features is not None:
              # adding missing columns
              for column_name in set(self.config.features) - set(pa_table.column_names):
                   lowercase__    :   List[Any]      =       self.config.features.arrow_schema.field(a).type
                   lowercase__    :   Optional[Any]      =       pa_table.append_column(a						,   pa.array([None] * len(a)						,   type=a))
              # more expensive cast to support nested structures with keys in a different order
              # allows str <-> int/float or str to Audio for example
              lowercase__    :   Tuple      =       table_cast(a						,   self.config.features.arrow_schema)
         return pa_table





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

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

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

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




import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
       from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
       from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Dict			):



     '''simple docstring'''





     return 1.0 / (1.0 + np.exp(-_outputs			))

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    str			):



     '''simple docstring'''





     lowercase__    :   int      =       np.max(_outputs	,     axis=-1	,     keepdims=SCREAMING_SNAKE_CASE_			)
     lowercase__    :   int      =       np.exp(_outputs - maxes			)
     return shifted_exp / shifted_exp.sum(axis=-1	,     keepdims=SCREAMING_SNAKE_CASE_			)


class       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    __lowerCamelCase						:       Optional[int]														=     """sigmoid"""
    __lowerCamelCase						:       List[Any]														=     """softmax"""
    __lowerCamelCase						:       Optional[Any]														=     """none"""



@add_end_docstrings(
    __snake_case		,       r"""
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `\"default\"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `\"sigmoid\"`: Applies the sigmoid function on the output.
            - `\"softmax\"`: Applies the softmax function on the output.
            - `\"none\"`: Does not apply any function on the output.
    """		,       )
class       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    __lowerCamelCase						:       Dict														=     False
    __lowerCamelCase						:       List[str]														=     ClassificationFunction.NONE





    def __init__(      self						,   **a):
         super().__init__(**a)

         self.check_model_type(
             TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
             if self.framework == 'tf'
             else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING)





    def       snake_case_				(      self						,   a=None						,   a=None						,   a=""						,   **a):
         # Using "" as default argument because we're going to use `top_k=None` in user code to declare
         # "No top_k"
         lowercase__    :   List[str]      =       tokenizer_kwargs

         lowercase__    :   Dict      =       {}
         if hasattr(self.model.config						,   'return_all_scores') and return_all_scores is None:
              lowercase__    :   Union[str, Any]      =       self.model.config.return_all_scores

         if isinstance(a						,   a) or top_k is None:
              lowercase__    :   Tuple      =       top_k
              lowercase__    :   Any      =       False
         elif return_all_scores is not None:
              warnings.warn(
                  '`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'
                  ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'						,   a						,   )
              if return_all_scores:
                   lowercase__    :   Union[str, Any]      =       None
              else:
                   lowercase__    :   Union[str, Any]      =       1

         if isinstance(a						,   a):
              lowercase__    :   Tuple      =       ClassificationFunction[function_to_apply.upper()]

         if function_to_apply is not None:
              lowercase__    :   List[str]      =       function_to_apply
         return preprocess_params, {}, postprocess_params





    def __call__(      self						,   *a						,   **a):
         lowercase__    :   int      =       super().__call__(*a						,   **a)
         # TODO try and retrieve it in a nicer way from _sanitize_parameters.
         lowercase__    :   Any      =       'top_k' not in kwargs
         if isinstance(args[0]						,   a) and _legacy:
              # This pipeline is odd, and return a list when single item is run
              return [result]
         else:
              return result





    def       snake_case_				(      self						,   a						,   **a):
         lowercase__    :   List[str]      =       self.framework
         if isinstance(a						,   a):
              return self.tokenizer(**a						,   return_tensors=a						,   **a)
         elif isinstance(a						,   a) and len(a) == 1 and isinstance(inputs[0]						,   a) and len(inputs[0]) == 2:
              # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
              return self.tokenizer(
                  text=inputs[0][0]						,   text_pair=inputs[0][1]						,   return_tensors=a						,   **a)
         elif isinstance(a						,   a):
              # This is likely an invalid usage of the pipeline attempting to pass text pairs.
              raise ValueError(
                  'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'
                  ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.')
         return self.tokenizer(a						,   return_tensors=a						,   **a)





    def       snake_case_				(      self						,   a):
         return self.model(**a)





    def       snake_case_				(      self						,   a						,   a=None						,   a=1						,   a=True):
         # `_legacy` is used to determine if we're running the naked pipeline and in backward
         # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
         # the more natural result containing the list.
         # Default value before `set_parameters`
         if function_to_apply is None:
              if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.SIGMOID
              elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.SOFTMAX
              elif hasattr(self.model.config						,   'function_to_apply') and function_to_apply is None:
                   lowercase__    :   List[str]      =       self.model.config.function_to_apply
              else:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.NONE

         lowercase__    :   str      =       model_outputs['logits'][0]
         lowercase__    :   Dict      =       outputs.numpy()

         if function_to_apply == ClassificationFunction.SIGMOID:
              lowercase__    :   int      =       sigmoid(a)
         elif function_to_apply == ClassificationFunction.SOFTMAX:
              lowercase__    :   List[Any]      =       softmax(a)
         elif function_to_apply == ClassificationFunction.NONE:
              lowercase__    :   Any      =       outputs
         else:
              raise ValueError(f"""Unrecognized `function_to_apply` argument: {function_to_apply}""")

         if top_k == 1 and _legacy:
              return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

         lowercase__    :   Any      =       [
             {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a)
         ]
         if not _legacy:
              dict_scores.sort(key=lambda a: x["score"]						,   reverse=a)
              if top_k is not None:
                   lowercase__    :   Optional[Any]      =       dict_scores[:top_k]
         return dict_scores

