


import json
import os
import tempfile

import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features import ArrayaD
from utils import generate_examples, get_duration


UpperCAmelCase     =       (30, 487)
UpperCAmelCase     =       (36, 1024)
UpperCAmelCase     =       (100, 100)
UpperCAmelCase     =       100

UpperCAmelCase     =       datasets.Features(
    {"""text""": ArrayaD(SHAPE_TEST_1, dtype="""float32"""), """image""": ArrayaD(SHAPE_TEST_2, dtype="""float32""")}
)

UpperCAmelCase,				UpperCAmelCase     =       os.path.split(__file__)
UpperCAmelCase     =       os.path.join(RESULTS_BASEPATH, """results""", RESULTS_FILENAME.replace(""".py""", """.json"""))






@get_duration
def 			__lowerCAmelCase       (SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )->    Tuple:




      """simple docstring"""

      with ArrowWriter(features=SCREAMING_SNAKE_CASE   ,   path=os.path.join(SCREAMING_SNAKE_CASE   ,   '''beta.arrow'''   )   ) as writer:
            for key, record in dummy_data:
                  snake_case_			= my_features.encode_example(SCREAMING_SNAKE_CASE   )
                  writer.write(SCREAMING_SNAKE_CASE   )
            snake_case_			,       snake_case_			= writer.finalize()






@get_duration
def 			__lowerCAmelCase       (SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )->    Any:




      """simple docstring"""

      snake_case_			= datasets.Dataset.from_file(
          filename=os.path.join(SCREAMING_SNAKE_CASE   ,   '''beta.arrow'''   )   ,   info=datasets.DatasetInfo(features=SCREAMING_SNAKE_CASE   )   )
      for _ in dataset:
            pass






@get_duration
def 			__lowerCAmelCase       (SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )->    Union[str, Any]:




      """simple docstring"""

      snake_case_			= datasets.Dataset.from_file(
          filename=os.path.join(SCREAMING_SNAKE_CASE   ,   '''beta.arrow'''   )   ,   info=datasets.DatasetInfo(features=SCREAMING_SNAKE_CASE   )   )
      dataset.set_format('''numpy'''   )
      for _ in dataset:
            pass






@get_duration
def 			__lowerCAmelCase       (SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )->    Dict:




      """simple docstring"""

      snake_case_			= 10
      snake_case_			= datasets.Dataset.from_file(
          filename=os.path.join(SCREAMING_SNAKE_CASE   ,   '''beta.arrow'''   )   ,   info=datasets.DatasetInfo(features=SCREAMING_SNAKE_CASE   )   )
      for i in range(0   ,   len(SCREAMING_SNAKE_CASE   )   ,   SCREAMING_SNAKE_CASE   ):
            snake_case_			= dataset[i : i + batch_size]






@get_duration
def 			__lowerCAmelCase       (SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )->    List[str]:




      """simple docstring"""

      snake_case_			= 10
      snake_case_			= datasets.Dataset.from_file(
          filename=os.path.join(SCREAMING_SNAKE_CASE   ,   '''beta.arrow'''   )   ,   info=datasets.DatasetInfo(features=SCREAMING_SNAKE_CASE   )   )
      dataset.set_format('''numpy'''   )
      for i in range(0   ,   len(SCREAMING_SNAKE_CASE   )   ,   SCREAMING_SNAKE_CASE   ):
            snake_case_			= dataset[i : i + batch_size]






@get_duration
def 			__lowerCAmelCase       (SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )->    int:




      """simple docstring"""

      snake_case_			= datasets.Dataset.from_file(
          filename=os.path.join(SCREAMING_SNAKE_CASE   ,   '''beta.arrow'''   )   ,   info=datasets.DatasetInfo(features=SCREAMING_SNAKE_CASE   )   )
      for col in feats:
            snake_case_			= dataset[col]






@get_duration
def 			__lowerCAmelCase       (SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )->    Optional[int]:




      """simple docstring"""

      snake_case_			= datasets.Dataset.from_file(
          filename=os.path.join(SCREAMING_SNAKE_CASE   ,   '''beta.arrow'''   )   ,   info=datasets.DatasetInfo(features=SCREAMING_SNAKE_CASE   )   )
      dataset.set_format('''numpy'''   )
      for col in feats:
            snake_case_			= dataset[col]






def 			__lowerCAmelCase       ()->    Any:




      """simple docstring"""

      snake_case_			= {}
      snake_case_			= (
          read_unformated,
          read_formatted_as_numpy,
          read_batch_unformated,
          read_batch_formatted_as_numpy,
          read_col_unformated,
          read_col_formatted_as_numpy,
      )
      with tempfile.TemporaryDirectory() as tmp_dir:
            snake_case_			= datasets.Features({'''image''': ArrayaD(SCREAMING_SNAKE_CASE   ,   dtype='''float32'''   )}   )
            snake_case_			= generate_examples(features=SCREAMING_SNAKE_CASE   ,   num_examples=SCREAMING_SNAKE_CASE   )
            snake_case_			= write(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
            for read_func in read_functions:
                  snake_case_			= read_func(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )

      with tempfile.TemporaryDirectory() as tmp_dir:
            # don't use fixed length for fair comparison
            # feats = datasets.Features(
            #     {"image": datasets.Sequence(datasets.Sequence(datasets.Value("float32"), SPEED_TEST_SHAPE[1]), SPEED_TEST_SHAPE[0])}
            # )
            snake_case_			= datasets.Features({'''image''': datasets.Sequence(datasets.Sequence(datasets.Value('''float32'''   )   )   )}   )
            snake_case_			= generate_examples(
                features=SCREAMING_SNAKE_CASE   ,   num_examples=SCREAMING_SNAKE_CASE   ,   seq_shapes={'''image''': SPEED_TEST_SHAPE}   )
            snake_case_			= write(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
            for read_func in read_functions:
                  snake_case_			= read_func(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )

      with tempfile.TemporaryDirectory() as tmp_dir:
            # don't use fixed length for fair comparison
            # feats = datasets.Features(
            #     {"image": datasets.Sequence(datasets.Value("float32"), SPEED_TEST_SHAPE[0] * SPEED_TEST_SHAPE[1])}
            # )
            snake_case_			= datasets.Features({'''image''': datasets.Sequence(datasets.Value('''float32'''   )   )}   )
            snake_case_			= generate_examples(
                features=SCREAMING_SNAKE_CASE   ,   num_examples=SCREAMING_SNAKE_CASE   ,   seq_shapes={'''image''': [SPEED_TEST_SHAPE[0] * SPEED_TEST_SHAPE[1]]}   ,   )
            snake_case_			= write(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
            for read_func in read_functions:
                  snake_case_			= read_func(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )

      with open(SCREAMING_SNAKE_CASE   ,   '''wb'''   ) as f:
            f.write(json.dumps(SCREAMING_SNAKE_CASE   ).encode('''utf-8'''   )   )


if __name__ == "__main__":  # useful to run the profiler
   benchmark_array_xd()



from collections import OrderedDict
from dataclasses import fields
from typing import Any, Tuple

import numpy as np

from .import_utils import is_torch_available






def 			__lowerCAmelCase       (SCREAMING_SNAKE_CASE   )->    Union[str, Any]:




      """simple docstring"""

      if is_torch_available():
            import torch

            if isinstance(SCREAMING_SNAKE_CASE   ,   torch.Tensor   ):
                  return True

      return isinstance(SCREAMING_SNAKE_CASE   ,   np.ndarray   )







class lowerCAmelCase_		(					lowerCamelCase__			):

 '''simple docstring'''

 def 		UpperCamelCase__	(      self   ):
       snake_case_			= fields(self   )

       # Safety and consistency checks
       if not len(_UpperCAmelCase   ):
             raise ValueError(F'''{self.__class__.__name__} has no fields.'''   )

       snake_case_			= getattr(self						, class_fields[0].name   )
       snake_case_			= all(getattr(self						, field.name   ) is None for field in class_fields[1:]   )

       if other_fields_are_none and isinstance(_UpperCAmelCase						, _UpperCAmelCase   ):
             for key, value in first_field.items():
                   snake_case_			= value
       else:
             for field in class_fields:
                   snake_case_			= getattr(self						, field.name   )
                   if v is not None:
                         snake_case_			= v



 def __delitem__(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''   )



 def 		UpperCamelCase__	(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''   )



 def 		UpperCamelCase__	(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''   )



 def 		UpperCamelCase__	(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''   )



 def __getitem__(      self						, _UpperCAmelCase   ):
       if isinstance(_UpperCAmelCase						, _UpperCAmelCase   ):
             snake_case_			= dict(self.items()   )
             return inner_dict[k]
       else:
             return self.to_tuple()[k]



 def __setattr__(      self						, _UpperCAmelCase						, _UpperCAmelCase   ):
       if name in self.keys() and value is not None:
             # Don't call self.__setitem__ to avoid recursion errors
             super().__setitem__(_UpperCAmelCase						, _UpperCAmelCase   )
       super().__setattr__(_UpperCAmelCase						, _UpperCAmelCase   )



 def __setitem__(      self						, _UpperCAmelCase						, _UpperCAmelCase   ):
       # Will raise a KeyException if needed
       super().__setitem__(_UpperCAmelCase						, _UpperCAmelCase   )
       # Don't call self.__setattr__ to avoid recursion errors
       super().__setattr__(_UpperCAmelCase						, _UpperCAmelCase   )





 def 		UpperCamelCase__	(      self   ):
       return tuple(self[k] for k in self.keys()   )