





"""simple docstring"""



import itertools
from dataclasses import dataclass
from typing import List, Optional

import pyarrow as pa
import pyarrow.parquet as pq

import datasets
from datasets.table import table_cast


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






@dataclass
class 		__snake_case (		datasets.BuilderConfig					):





 """simple docstring"""


 _lowerCamelCase				=					1_00_00
 _lowerCamelCase				=					None
 _lowerCamelCase				=					None






class 		__snake_case (		datasets.ArrowBasedBuilder					):





 """simple docstring"""


 _lowerCamelCase				=					ParquetConfig

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




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

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     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}"""  )
     __A   :						Any									=					dl_manager.download_and_extract(self.config.data_files  )
     if isinstance(__lowerCamelCase ,						(str, list, tuple)  ):
         __A   :						List[Any]									=					data_files
         if isinstance(__lowerCamelCase ,						__lowerCamelCase  ):
             __A   :						Union[str, Any]									=					[files]
         # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
         __A   :						Dict									=					[dl_manager.iter_files(__lowerCamelCase  ) for file in files]
         return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,						gen_kwargs={'''files''': files}  )]
     __A   :						Optional[Any]									=					[]
     for split_name, files in data_files.items():
         if isinstance(__lowerCamelCase ,						__lowerCamelCase  ):
             __A   :						Union[str, Any]									=					[files]
         # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
         __A   :						Optional[Any]									=					[dl_manager.iter_files(__lowerCamelCase  ) for file in files]
         # Infer features is they are stoed in the arrow schema
         if self.info.features is None:
             for file in itertools.chain.from_iterable(__lowerCamelCase  ):
                 with open(__lowerCamelCase ,						'''rb'''  ) as f:
                     __A   :						str									=					datasets.Features.from_arrow_schema(pq.read_schema(__lowerCamelCase  )  )
                 break
         splits.append(datasets.SplitGenerator(name=__lowerCamelCase ,						gen_kwargs={'''files''': files}  )  )
     return splits

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     if self.info.features is not None:
         # more expensive cast to support nested features with keys in a different order
         # allows str <-> int/float or str to Audio for example
         __A   :						int									=					table_cast(__lowerCamelCase ,						self.info.features.arrow_schema  )
     return pa_table







 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Tuple									=					self.info.features.arrow_schema if self.info.features is not None else None
     if self.info.features is not None and self.config.columns is not None:
         if sorted(field.name for field in schema  ) != sorted(self.config.columns  ):
             raise ValueError(
                 F"""Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'"""  )
     for file_idx, file in enumerate(itertools.chain.from_iterable(__lowerCamelCase  )  ):
         with open(__lowerCamelCase ,						'''rb'''  ) as f:
             __A   :						Union[str, Any]									=					pq.ParquetFile(__lowerCamelCase  )
             try:
                 for batch_idx, record_batch in enumerate(
                     parquet_file.iter_batches(batch_size=self.config.batch_size ,						columns=self.config.columns  )  ):
                     __A   :						Tuple									=					pa.Table.from_batches([record_batch]  )
                     # 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 F"""{file_idx}_{batch_idx}""", self._cast_table(__lowerCamelCase  )
             except ValueError as e:
                 logger.error(F"""Failed to read file '{file}' with error {type(__lowerCamelCase  )}: {e}"""  )
                 raise






"""simple docstring"""



from pathlib import PurePosixPath
from typing import Optional

import fsspec
from fsspec import AbstractFileSystem
from huggingface_hub.hf_api import DatasetInfo

from ..utils.file_utils import get_authentication_headers_for_url
from ..utils.hub import hf_hub_url






class 		__snake_case (		SCREAMING_SNAKE_CASE__					):





 """simple docstring"""


 _lowerCamelCase				=					""""""
 _lowerCamelCase				=					"""hf-legacy"""  # "hf://"" is reserved for hffs

 def __init__(   self ,						__lowerCamelCase = None ,						__lowerCamelCase = None ,						**__lowerCamelCase ,						):



     '''simple docstring'''




     super().__init__(self ,						**__lowerCamelCase  )
     __A   :						int									=					repo_info
     __A   :						Optional[int]									=					token
     __A   :						int									=					None

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     if self.dir_cache is None:
         __A   :						int									=					{}
         for hf_file in self.repo_info.siblings:
             # TODO(QL): add sizes
             __A   :						Tuple									=					{
                 '''name''': hf_file.rfilename,
                 '''size''': None,
                 '''type''': '''file''',
             }
             self.dir_cache.update(
                 {
                     str(__lowerCamelCase  ): {'''name''': str(__lowerCamelCase  ), '''size''': None, '''type''': '''directory'''}
                     for d in list(PurePosixPath(hf_file.rfilename  ).parents  )[:-1]
                 }  )

 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase = "rb" ,						**__lowerCamelCase ,						):



     '''simple docstring'''




     if not isinstance(self.repo_info ,						__lowerCamelCase  ):
         raise NotImplementedError(F"""Open is only implemented for dataset repositories, but got {self.repo_info}"""  )
     __A   :						Union[str, Any]									=					hf_hub_url(self.repo_info.id ,						__lowerCamelCase ,						revision=self.repo_info.sha  )
     return fsspec.open(
         __lowerCamelCase ,						mode=__lowerCamelCase ,						headers=get_authentication_headers_for_url(__lowerCamelCase ,						use_auth_token=self.token  ) ,						client_kwargs={'''trust_env''': True} ,						).open()

 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						**__lowerCamelCase  ):



     '''simple docstring'''




     self._get_dirs()
     __A   :						Optional[Any]									=					self._strip_protocol(__lowerCamelCase  )
     if path in self.dir_cache:
         return self.dir_cache[path]
     else:
         raise FileNotFoundError(__lowerCamelCase  )







 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase=False ,						**__lowerCamelCase  ):



     '''simple docstring'''




     self._get_dirs()
     __A   :						Any									=					PurePosixPath(path.strip('''/'''  )  )
     __A   :						Any									=					{}
     for p, f in self.dir_cache.items():
         __A   :						List[Any]									=					PurePosixPath(p.strip('''/'''  )  )
         __A   :						Dict									=					p.parent
         if root == path:
             __A   :						Union[str, Any]									=					f
     __A   :						List[str]									=					list(paths.values()  )
     if detail:
         return out
     else:
         return sorted(f['''name'''] for f in out  )




