





"""simple docstring"""
import os
import posixpath
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union

import numpy as np
import pyarrow as pa

import datasets
from datasets.arrow_writer import ArrowWriter, ParquetWriter
from datasets.config import MAX_SHARD_SIZE
from datasets.filesystems import (
    is_remote_filesystem,
    rename,
)
from datasets.iterable_dataset import _BaseExamplesIterable
from datasets.utils.py_utils import convert_file_size_to_int


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

if TYPE_CHECKING:
  import pyspark






@dataclass
class 					_SCREAMING_SNAKE_CASE(   datasets.BuilderConfig  ):
       SCREAMING_SNAKE_CASE_   :      Optional[datasets.Features]							=  None




def      __lowerCamelCase   (							a_     :		"pyspark.sql.DataFrame" ,   a_     :		List[int] ,   )			->      List[str]:
      import pyspark

      def generate_fn():
            __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  df.select('''*''' ,   pyspark.sql.functions.spark_partition_id().alias('''part_id'''							)							)
            for partition_id in partition_order:
                  __SCREAMING_SNAKE_CASE   :str						=  df_with_partition_id.select('''*'''							).where(f'''part_id = {partition_id}'''							).drop('''part_id'''							)
                  __SCREAMING_SNAKE_CASE   :Tuple						=  partition_df.collect()
                  __SCREAMING_SNAKE_CASE   :Dict						=  0
                  for row in rows:
                        yield f'''{partition_id}_{row_id}''', row.asDict()
                        row_id += 1

      return generate_fn






class 					_SCREAMING_SNAKE_CASE(   _BaseExamplesIterable  ):




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=None		,)			->      Optional[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :str						=  df
             __SCREAMING_SNAKE_CASE   :List[Any]						=  partition_order or range(self.df.rdd.getNumPartitions()							)
             __SCREAMING_SNAKE_CASE   :str						=  _generate_iterable_examples(self.df		,self.partition_order							)




       def __iter__(						self							)			->      Tuple:





             """simple docstring"""






             yield from self.generate_examples_fn()




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__							)			->      "SparkExamplesIterable":





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Any						=  list(range(self.df.rdd.getNumPartitions()							)							)
             generator.shuffle(SCREAMING_SNAKE_CASE__							)
             return SparkExamplesIterable(self.df		,partition_order=SCREAMING_SNAKE_CASE__							)




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)			->      "SparkExamplesIterable":





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[str]						=  self.split_shard_indices_by_worker(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             return SparkExamplesIterable(self.df		,partition_order=SCREAMING_SNAKE_CASE__							)




       @property
       def     _UpperCamelCase     (						self							)			->      int:





             """simple docstring"""






             return len(self.partition_order							)






class 					_SCREAMING_SNAKE_CASE(   datasets.DatasetBuilder  ):
       SCREAMING_SNAKE_CASE_   :      List[Any]							=  SparkConfig




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = None		,SCREAMING_SNAKE_CASE__ = None		,**SCREAMING_SNAKE_CASE__		,)			->      Tuple:





             """simple docstring"""






             import pyspark

             __SCREAMING_SNAKE_CASE   :Optional[int]						=  pyspark.sql.SparkSession.builder.getOrCreate()
             __SCREAMING_SNAKE_CASE   :str						=  df
             __SCREAMING_SNAKE_CASE   :List[str]						=  working_dir

             super().__init__(
                 cache_dir=SCREAMING_SNAKE_CASE__		,config_name=str(self.df.semanticHash()							)		,**SCREAMING_SNAKE_CASE__		,)




       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             def create_cache_and_write_probe(SCREAMING_SNAKE_CASE__							):
                   # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories
                   # already exist.
                   os.makedirs(self._cache_dir		,exist_ok=SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE   :int						=  os.path.join(self._cache_dir		,'''fs_test''' + uuid.uuida().hex							)
                   # Opening the file in append mode will create a new file unless it already exists, in which case it will not
                   # change the file contents.
                   open(SCREAMING_SNAKE_CASE__		,'''a'''							)
                   return [probe_file]

             if self._spark.conf.get('''spark.master'''		,''''''							).startswith('''local'''							):
                   return

             # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS
             # accessible to the driver.
             # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error.
             if self._cache_dir:
                   __SCREAMING_SNAKE_CASE   :Dict						=  (
                       self._spark.sparkContext.parallelize(range(1							)		,1							).mapPartitions(SCREAMING_SNAKE_CASE__							).collect()
                   )
                   if os.path.isfile(probe[0]							):
                         return

             raise ValueError(
                 '''When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir'''							)




       def     _UpperCamelCase     (						self							)			->      Dict:





             """simple docstring"""






             return datasets.DatasetInfo(features=self.config.features							)




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__							)			->      Tuple:





             """simple docstring"""






             return [datasets.SplitGenerator(name=datasets.Split.TRAIN							)]




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__							)			->      Optional[Any]:





             """simple docstring"""






             import pyspark

             def get_arrow_batch_size(SCREAMING_SNAKE_CASE__							):
                   for batch in it:
                         yield pa.RecordBatch.from_pydict({'''batch_bytes''': [batch.nbytes]}							)

             __SCREAMING_SNAKE_CASE   :Any						=  self.df.count()
             __SCREAMING_SNAKE_CASE   :Any						=  df_num_rows if df_num_rows <= 1_00 else 1_00
             # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample.
             __SCREAMING_SNAKE_CASE   :str						=  (
                 self.df.limit(SCREAMING_SNAKE_CASE__							)
                 .repartition(1							)
                 .mapInArrow(SCREAMING_SNAKE_CASE__		,'''batch_bytes: long'''							)
                 .agg(pyspark.sql.functions.sum('''batch_bytes'''							).alias('''sample_bytes'''							)							)
                 .collect()[0]
                 .sample_bytes
                 / sample_num_rows
             )
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  approx_bytes_per_row * df_num_rows
             if approx_total_size > max_shard_size:
                   # Make sure there is at least one row per partition.
                   __SCREAMING_SNAKE_CASE   :Dict						=  min(SCREAMING_SNAKE_CASE__		,int(approx_total_size / max_shard_size							)							)
                   __SCREAMING_SNAKE_CASE   :List[Any]						=  self.df.repartition(SCREAMING_SNAKE_CASE__							)




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,)			->      Iterable[Tuple[int, bool, Union[int, tuple]]]:





             """simple docstring"""






             import pyspark

             __SCREAMING_SNAKE_CASE   :List[str]						=  ParquetWriter if file_format == '''parquet''' else ArrowWriter
             __SCREAMING_SNAKE_CASE   :List[Any]						=  os.path.join(self._working_dir		,os.path.basename(SCREAMING_SNAKE_CASE__							)							) if self._working_dir else fpath
             __SCREAMING_SNAKE_CASE   :List[Any]						=  file_format == '''parquet'''

             # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to
             # pickling the SparkContext.
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  self.config.features
             __SCREAMING_SNAKE_CASE   :int						=  self._writer_batch_size
             __SCREAMING_SNAKE_CASE   :Any						=  self._fs.storage_options

             def write_arrow(SCREAMING_SNAKE_CASE__							):
                   # Within the same SparkContext, no two task attempts will share the same attempt ID.
                   __SCREAMING_SNAKE_CASE   :str						=  pyspark.TaskContext().taskAttemptId()
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  next(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
                   if first_batch is None:
                         # Some partitions might not receive any data.
                         return pa.RecordBatch.from_arrays(
                             [[task_id], [0], [0]]		,names=['''task_id''', '''num_examples''', '''num_bytes''']		,)
                   __SCREAMING_SNAKE_CASE   :List[str]						=  0
                   __SCREAMING_SNAKE_CASE   :List[Any]						=  writer_class(
                       features=SCREAMING_SNAKE_CASE__		,path=working_fpath.replace('''SSSSS'''		,f'''{shard_id:05d}'''							).replace('''TTTTT'''		,f'''{task_id:05d}'''							)		,writer_batch_size=SCREAMING_SNAKE_CASE__		,storage_options=SCREAMING_SNAKE_CASE__		,embed_local_files=SCREAMING_SNAKE_CASE__		,)
                   __SCREAMING_SNAKE_CASE   :int						=  pa.Table.from_batches([first_batch]							)
                   writer.write_table(SCREAMING_SNAKE_CASE__							)
                   for batch in it:
                         if max_shard_size is not None and writer._num_bytes >= max_shard_size:
                               __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :str						=  writer.finalize()
                               writer.close()
                               yield pa.RecordBatch.from_arrays(
                                   [[task_id], [num_examples], [num_bytes]]		,names=['''task_id''', '''num_examples''', '''num_bytes''']		,)
                               shard_id += 1
                               __SCREAMING_SNAKE_CASE   :int						=  writer_class(
                                   features=writer._features		,path=working_fpath.replace('''SSSSS'''		,f'''{shard_id:05d}'''							).replace('''TTTTT'''		,f'''{task_id:05d}'''							)		,writer_batch_size=SCREAMING_SNAKE_CASE__		,storage_options=SCREAMING_SNAKE_CASE__		,embed_local_files=SCREAMING_SNAKE_CASE__		,)
                         __SCREAMING_SNAKE_CASE   :Any						=  pa.Table.from_batches([batch]							)
                         writer.write_table(SCREAMING_SNAKE_CASE__							)

                   if writer._num_bytes > 0:
                         __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Union[str, Any]						=  writer.finalize()
                         writer.close()
                         yield pa.RecordBatch.from_arrays(
                             [[task_id], [num_examples], [num_bytes]]		,names=['''task_id''', '''num_examples''', '''num_bytes''']		,)

                   if working_fpath != fpath:
                         for file in os.listdir(os.path.dirname(SCREAMING_SNAKE_CASE__							)							):
                               __SCREAMING_SNAKE_CASE   :Any						=  os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE__							)		,os.path.basename(SCREAMING_SNAKE_CASE__							)							)
                               shutil.move(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  (
                 self.df.mapInArrow(SCREAMING_SNAKE_CASE__		,'''task_id: long, num_examples: long, num_bytes: long'''							)
                 .groupBy('''task_id'''							)
                 .agg(
                     pyspark.sql.functions.sum('''num_examples'''							).alias('''total_num_examples'''							)		,pyspark.sql.functions.sum('''num_bytes'''							).alias('''total_num_bytes'''							)		,pyspark.sql.functions.count('''num_bytes'''							).alias('''num_shards'''							)		,pyspark.sql.functions.collect_list('''num_examples'''							).alias('''shard_lengths'''							)		,)
                 .collect()
             )
             for row in stats:
                   yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths)




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = "arrow"		,SCREAMING_SNAKE_CASE__ = None		,SCREAMING_SNAKE_CASE__ = None		,**SCREAMING_SNAKE_CASE__		,)			->      Any:





             """simple docstring"""






             self._validate_cache_dir()

             __SCREAMING_SNAKE_CASE   :Optional[int]						=  convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE							)
             self._repartition_df_if_needed(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  not is_remote_filesystem(self._fs							)
             __SCREAMING_SNAKE_CASE   :Tuple						=  os.path.join if is_local else posixpath.join

             __SCREAMING_SNAKE_CASE   :int						=  '''-TTTTT-SSSSS-of-NNNNN'''
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}'''
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  path_join(self._output_dir		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  0
             __SCREAMING_SNAKE_CASE   :List[str]						=  0
             __SCREAMING_SNAKE_CASE   :List[Any]						=  0
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  []
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  []

             for task_id, content in self._prepare_split_single(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							):
                   (
                       (
                       __SCREAMING_SNAKE_CASE
                   )				,(
                       __SCREAMING_SNAKE_CASE
                   )				,(
                       __SCREAMING_SNAKE_CASE
                   )				,(
                       __SCREAMING_SNAKE_CASE
                   )				,
                   )   :Dict						=  content
                   if num_bytes > 0:
                         total_num_examples += num_examples
                         total_num_bytes += num_bytes
                         total_shards += num_shards
                         task_id_and_num_shards.append((task_id, num_shards)							)
                         all_shard_lengths.extend(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  total_num_examples
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  total_num_bytes

             # should rename everything at the end
             logger.debug(f'''Renaming {total_shards} shards.'''							)
             if total_shards > 1:
                   __SCREAMING_SNAKE_CASE   :Dict						=  all_shard_lengths

                   # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a
                   # pickling error due to pickling the SparkContext.
                   __SCREAMING_SNAKE_CASE   :int						=  self._fs

                   # use the -SSSSS-of-NNNNN pattern
                   def _rename_shard(
                       SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,):
                         rename(
                             SCREAMING_SNAKE_CASE__		,fpath.replace('''SSSSS'''		,f'''{shard_id:05d}'''							).replace('''TTTTT'''		,f'''{task_id:05d}'''							)		,fpath.replace('''TTTTT-SSSSS'''		,f'''{global_shard_id:05d}'''							).replace('''NNNNN'''		,f'''{total_shards:05d}'''							)		,)

                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  []
                   __SCREAMING_SNAKE_CASE   :List[Any]						=  0
                   for i in range(len(SCREAMING_SNAKE_CASE__							)							):
                         __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Optional[Any]						=  task_id_and_num_shards[i]
                         for shard_id in range(SCREAMING_SNAKE_CASE__							):
                               args.append([task_id, shard_id, global_shard_id]							)
                               global_shard_id += 1
                   self._spark.sparkContext.parallelize(SCREAMING_SNAKE_CASE__		,len(SCREAMING_SNAKE_CASE__							)							).map(lambda SCREAMING_SNAKE_CASE__							: _rename_shard(*SCREAMING_SNAKE_CASE__							)							).collect()
             else:
                   # don't use any pattern
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  0
                   __SCREAMING_SNAKE_CASE   :List[Any]						=  task_id_and_num_shards[0][0]
                   self._rename(
                       fpath.replace('''SSSSS'''		,f'''{shard_id:05d}'''							).replace('''TTTTT'''		,f'''{task_id:05d}'''							)		,fpath.replace(SCREAMING_SNAKE_CASE__		,''''''							)		,)




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,)			->      SparkExamplesIterable:





             """simple docstring"""






             return SparkExamplesIterable(self.df							)






"""simple docstring"""
import argparse
import os

import torch

from transformers import FlavaImageCodebook, FlavaImageCodebookConfig



def      __lowerCamelCase   (							a_     :		str ,   a_     :		Dict ,   a_     :		Any ,   a_     :		str							)			->      str:
      __SCREAMING_SNAKE_CASE   :int						=  s.rsplit(a_ ,   a_							)
      return new.join(a_							)



def      __lowerCamelCase   (							a_     :		List[str]							)			->      Dict:
      # encoder.embeddings are double copied in original FLAVA
      return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items()							)



def      __lowerCamelCase   (							a_     :		Optional[int]							)			->      Any:
      __SCREAMING_SNAKE_CASE   :Optional[int]						=  {}

      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  ['''group_1''', '''group_2''', '''group_3''', '''group_4''']
      for key, value in state_dict.items():
            for group_key in group_keys:
                  if group_key in key:
                        __SCREAMING_SNAKE_CASE   :Optional[Any]						=  key.replace(f'''{group_key}.''' ,   f'''{group_key}.group.'''							)

            if "res_path" in key:
                  __SCREAMING_SNAKE_CASE   :str						=  key.replace('''res_path.''' ,   '''res_path.path.'''							)

            if key.endswith('''.w'''							):
                  __SCREAMING_SNAKE_CASE   :List[Any]						=  rreplace(a_ ,   '''.w''' ,   '''.weight''' ,   1							)
            if key.endswith('''.b'''							):
                  __SCREAMING_SNAKE_CASE   :List[Any]						=  rreplace(a_ ,   '''.b''' ,   '''.bias''' ,   1							)

            __SCREAMING_SNAKE_CASE   :Optional[Any]						=  value.float()

      return upgrade



@torch.no_grad()
def      __lowerCamelCase   (							a_     :		List[Any] ,   a_     :		Optional[int] ,   a_     :		Optional[int]=None ,   a_     :		Dict=True							)			->      Union[str, Any]:
      from dall_e import Encoder

      __SCREAMING_SNAKE_CASE   :int						=  Encoder()
      if os.path.exists(a_							):
            __SCREAMING_SNAKE_CASE   :Dict						=  torch.load(a_							)
      else:
            __SCREAMING_SNAKE_CASE   :List[str]						=  torch.hub.load_state_dict_from_url(a_							)

      if isinstance(a_ ,   a_							):
            __SCREAMING_SNAKE_CASE   :List[str]						=  ckpt.state_dict()
      encoder.load_state_dict(a_							)

      if config_path is not None:
            __SCREAMING_SNAKE_CASE   :Any						=  FlavaImageCodebookConfig.from_pretrained(a_							)
      else:
            __SCREAMING_SNAKE_CASE   :Optional[int]						=  FlavaImageCodebookConfig()

      __SCREAMING_SNAKE_CASE   :Tuple						=  FlavaImageCodebook(a_							).eval()
      __SCREAMING_SNAKE_CASE   :List[str]						=  encoder.state_dict()

      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  upgrade_state_dict(a_							)
      hf_model.load_state_dict(a_							)
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  hf_model.state_dict()
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  count_parameters(a_							)
      __SCREAMING_SNAKE_CASE   :Any						=  count_parameters(a_							)

      assert torch.allclose(a_ ,   a_ ,   atol=1e-3							)

      if save_checkpoint:
            hf_model.save_pretrained(a_							)
      else:
            return hf_state_dict


if __name__ == "__main__":
  lowerCamelCase_								=		argparse.ArgumentParser()
  parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
  parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to flava checkpoint")
  parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
  lowerCamelCase_								=		parser.parse_args()

  convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)