
"""simple docstring"""

import importlib
import os
import platform
from pathlib import Path

from packaging import version

from .utils.logging import get_logger


_A				=					get_logger(__name__)

# Datasets
_A				=					"https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets"
_A				=					"https://cdn-datasets.huggingface.co/datasets/datasets"
_A				=					"https://raw.githubusercontent.com/huggingface/datasets/{revision}/datasets/{path}/{name}"

# Metrics
_A				=					"https://s3.amazonaws.com/datasets.huggingface.co/datasets/metrics"
_A				=					"https://cdn-datasets.huggingface.co/datasets/metric"
_A				=					"https://raw.githubusercontent.com/huggingface/datasets/{revision}/metrics/{path}/{name}"

# Hub
_A				=					os.environ.get('HF_ENDPOINT', 'https://huggingface.co')
_A				=					HF_ENDPOINT + "/datasets/{repo_id}/resolve/{revision}/{path}"
_A				=					"main"

_A				=					version.parse(platform.python_version())

if PY_VERSION < version.parse('3.8'):
					import importlib_metadata
else:
					import importlib.metadata as importlib_metadata

# General environment variables accepted values for booleans
_A				=					{"1", "ON", "YES", "TRUE"}
_A				=					ENV_VARS_TRUE_VALUES.union({'AUTO'})


# Imports
_A				=					version.parse(importlib_metadata.version('dill'))
_A				=					version.parse(importlib_metadata.version('pandas'))
_A				=					version.parse(importlib_metadata.version('pyarrow'))

_A				=					os.environ.get('USE_TF', 'AUTO').upper()
_A				=					os.environ.get('USE_TORCH', 'AUTO').upper()
_A				=					os.environ.get('USE_JAX', 'AUTO').upper()

_A				=					"N/A"
_A				=					False

if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
					_A				=					importlib.util.find_spec('torch') is not None
					if TORCH_AVAILABLE:
										try:
															_A				=					version.parse(importlib_metadata.version('torch'))
															logger.info(F"""PyTorch version {TORCH_VERSION} available.""")
										except importlib_metadata.PackageNotFoundError:
															pass
else:
					logger.info('Disabling PyTorch because USE_TF is set')

_A				=					"N/A"
_A				=					False

if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
					_A				=					importlib.util.find_spec('tensorflow') is not None
					if TF_AVAILABLE:
										# For the metadata, we have to look for both tensorflow and tensorflow-cpu
										for package in [
										    "tensorflow",
										    "tensorflow-cpu",
										    "tensorflow-gpu",
										    "tf-nightly",
										    "tf-nightly-cpu",
										    "tf-nightly-gpu",
										    "intel-tensorflow",
										    "tensorflow-rocm",
										    "tensorflow-macos",
										]:
															try:
																				_A				=					version.parse(importlib_metadata.version(package))
															except importlib_metadata.PackageNotFoundError:
																				continue
															else:
																				break
										else:
															_A				=					False
					if TF_AVAILABLE:
										if TF_VERSION.major < 2:
															logger.info(F"""TensorFlow found but with version {TF_VERSION}. `datasets` requires version 2 minimum.""")
															_A				=					False
										else:
															logger.info(F"""TensorFlow version {TF_VERSION} available.""")
else:
					logger.info('Disabling Tensorflow because USE_TORCH is set')


_A				=					"N/A"
_A				=					False

if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
					_A				=					importlib.util.find_spec('jax') is not None and importlib.util.find_spec('jaxlib') is not None
					if JAX_AVAILABLE:
										try:
															_A				=					version.parse(importlib_metadata.version('jax'))
															logger.info(F"""JAX version {JAX_VERSION} available.""")
										except importlib_metadata.PackageNotFoundError:
															pass
else:
					logger.info('Disabling JAX because USE_JAX is set to False')


_A				=					os.environ.get('USE_BEAM', 'AUTO').upper()
_A				=					"N/A"
_A				=					False
if USE_BEAM in ENV_VARS_TRUE_AND_AUTO_VALUES:
					try:
										_A				=					version.parse(importlib_metadata.version('apache_beam'))
										_A				=					True
										logger.info(F"""Apache Beam version {BEAM_VERSION} available.""")
					except importlib_metadata.PackageNotFoundError:
										pass
else:
					logger.info('Disabling Apache Beam because USE_BEAM is set to False')


# Optional tools for data loading
_A				=					importlib.util.find_spec('sqlalchemy') is not None

# Optional tools for feature decoding
_A				=					importlib.util.find_spec('PIL') is not None
_A				=					importlib.util.find_spec('soundfile') is not None and version.parse(
    importlib.import_module('soundfile').__libsndfile_version__
) >= version.parse('1.0.31')
_A				=					importlib.util.find_spec('soundfile') is not None and version.parse(
    importlib.import_module('soundfile').__libsndfile_version__
) >= version.parse('1.1.0')

# Optional compression tools
_A				=					importlib.util.find_spec('rarfile') is not None
_A				=					importlib.util.find_spec('zstandard') is not None
_A				=					importlib.util.find_spec('lz4') is not None
_A				=					importlib.util.find_spec('py7zr') is not None


# Cache location
_A				=					"~/.cache"
_A				=					os.getenv('XDG_CACHE_HOME', DEFAULT_XDG_CACHE_HOME)
_A				=					os.path.join(XDG_CACHE_HOME, 'huggingface')
_A				=					os.path.expanduser(os.getenv('HF_HOME', DEFAULT_HF_CACHE_HOME))

_A				=					os.path.join(HF_CACHE_HOME, 'datasets')
_A				=					Path(os.getenv('HF_DATASETS_CACHE', DEFAULT_HF_DATASETS_CACHE))

_A				=					os.path.join(HF_CACHE_HOME, 'metrics')
_A				=					Path(os.getenv('HF_METRICS_CACHE', DEFAULT_HF_METRICS_CACHE))

_A				=					os.path.join(HF_CACHE_HOME, 'modules')
_A				=					Path(os.getenv('HF_MODULES_CACHE', DEFAULT_HF_MODULES_CACHE))

_A				=					"downloads"
_A				=					os.path.join(HF_DATASETS_CACHE, DOWNLOADED_DATASETS_DIR)
_A				=					Path(os.getenv('HF_DATASETS_DOWNLOADED_DATASETS_PATH', DEFAULT_DOWNLOADED_DATASETS_PATH))

_A				=					"extracted"
_A				=					os.path.join(DEFAULT_DOWNLOADED_DATASETS_PATH, EXTRACTED_DATASETS_DIR)
_A				=					Path(os.getenv('HF_DATASETS_EXTRACTED_DATASETS_PATH', DEFAULT_EXTRACTED_DATASETS_PATH))

# Download count for the website
_A				=					(
    os.environ.get('HF_UPDATE_DOWNLOAD_COUNTS', 'AUTO').upper() in ENV_VARS_TRUE_AND_AUTO_VALUES
)

# Batch size constants. For more info, see:
# https://github.com/apache/arrow/blob/master/docs/source/cpp/arrays.rst#size-limitations-and-recommendations)
_A				=					1_0_0_0

# Size of the preloaded record batch in `Dataset.__iter__`
_A				=					1_0

# Pickling tables works only for small tables (<4GiB)
# For big tables, we write them on disk instead
_A				=					4 << 3_0

# Max shard size in bytes (e.g. to shard parquet datasets in push_to_hub or download_and_prepare)
_A				=					"500MB"

# Parquet configuration
_A				=					1_0_0
_A				=					1_0_0
_A				=					1_0_0

# Offline mode
_A				=					os.environ.get('HF_DATASETS_OFFLINE', 'AUTO').upper() in ENV_VARS_TRUE_VALUES

# In-memory
_A				=					0  # Disabled
_A				=					float(os.environ.get('HF_DATASETS_IN_MEMORY_MAX_SIZE', DEFAULT_IN_MEMORY_MAX_SIZE))

# File names
_A				=					"dataset.arrow"
_A				=					"indices.arrow"
_A				=					"state.json"
_A				=					"dataset_info.json"
_A				=					"dataset_infos.json"
_A				=					"LICENSE"
_A				=					"metric_info.json"
_A				=					"dataset_dict.json"

_A				=					"datasets_modules"

_A				=					2_5_5

# Streaming
_A				=					2_0
_A				=					5

# Datasets without script
_A				=					2_0_0
_A				=					1_0
_A				=					2_0_0

# Progress bars
_A				=					0.05  # 20 progress updates per sec










"""simple docstring"""






import logging
import random

import ray

from transformers import RagConfig, RagRetriever, RagTokenizer
from transformers.models.rag.retrieval_rag import CustomHFIndex


SCREAMING_SNAKE_CASE__				:  Optional[Any]						= logging.getLogger(__name__)


class 	A_       :





  """simple docstring"""

  def __init__(						self						)				->					Dict:
     a   :	List[str]						=    False
  def 							lowercase_     (						self  ,					__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase						)				->					List[str]:
     if not self.initialized:
        a   :	Dict						=    RagRetriever(
            __UpperCAmelCase  ,					question_encoder_tokenizer=__UpperCAmelCase  ,					generator_tokenizer=__UpperCAmelCase  ,					index=__UpperCAmelCase  ,					init_retrieval=__UpperCAmelCase  ,					)
        a   :	Dict						=    True
  def 							lowercase_     (						self						)				->					List[Any]:
     self.retriever.index.init_index()
  def 							lowercase_     (						self						)				->					List[Any]:
     # delete the old self.retriever object before assigning the new index
     del self.retriever
     a   :	Dict						=    False






  def 							lowercase_     (						self  ,					__UpperCAmelCase  ,					__UpperCAmelCase						)				->					Optional[int]:
     a	, a   :	List[str]						=    self.retriever._main_retrieve(__UpperCAmelCase  ,					__UpperCAmelCase						)
     a   :	List[Any]						=    self.retriever.index.get_doc_dicts(__UpperCAmelCase						)
     return doc_ids, retrieved_doc_embeds, doc_dicts



class 	A_       (     _UpperCAmelCase   ):





  """simple docstring"""

  def __init__(						self  ,					__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase=None						)				->					Tuple:
     if index is not None and index.is_initialized() and len(__UpperCAmelCase						) > 0:
        raise ValueError(
            'When using Ray for distributed fine-tuning, '
            'you\'ll need to provide the paths instead, '
            'as the dataset and the index are loaded '
            'separately. More info in examples/rag/use_own_knowledge_dataset.py '						)

     super().__init__(
         __UpperCAmelCase  ,					question_encoder_tokenizer=__UpperCAmelCase  ,					generator_tokenizer=__UpperCAmelCase  ,					index=__UpperCAmelCase  ,					init_retrieval=__UpperCAmelCase  ,					)

     a   :	Tuple						=    retrieval_workers
     a   :	List[str]						=    question_encoder_tokenizer
     a   :	Union[str, Any]						=    generator_tokenizer
     if len(self.retrieval_workers						) > 0:
        ray.get(
            [
                worker.create_rag_retriever.remote(__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase						)
                for worker in self.retrieval_workers
            ]						)
  def 							lowercase_     (						self						)				->					Tuple:
     logger.info('initializing retrieval'						)

     if len(self.retrieval_workers						) > 0:
        ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers]						)
     else:
        # Non-distributed training. Load index into this same process.
        self.index.init_index()
  def 							lowercase_     (						self  ,					__UpperCAmelCase  ,					__UpperCAmelCase						)				->					Tuple:
     if len(self.retrieval_workers						) > 0:
        # Select a random retrieval actor.
        a   :	Dict						=    self.retrieval_workers[random.randint(0  ,					len(self.retrieval_workers						) - 1						)]
        a	, a	, a   :	Any						=    ray.get(
            random_worker.retrieve.remote(__UpperCAmelCase  ,					__UpperCAmelCase						)						)
     else:
        a	, a   :	str						=    self._main_retrieve(__UpperCAmelCase  ,					__UpperCAmelCase						)
        a   :	str						=    self.index.get_doc_dicts(__UpperCAmelCase						)
     return retrieved_doc_embeds, doc_ids, doc_dicts
  @classmethod
  def 							lowercase_     (						cls  ,					__UpperCAmelCase  ,					__UpperCAmelCase=None  ,					**__UpperCAmelCase						)				->					int:
     return super(__UpperCAmelCase  ,					cls						).get_tokenizers(__UpperCAmelCase  ,					__UpperCAmelCase  ,					**__UpperCAmelCase						)
  @classmethod
  def 							lowercase_     (						cls  ,					__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase=None  ,					**__UpperCAmelCase						)				->					str:
     a   :	Union[str, Any]						=    kwargs.pop('config'  ,					__UpperCAmelCase						) or RagConfig.from_pretrained(__UpperCAmelCase  ,					**__UpperCAmelCase						)
     a   :	Optional[Any]						=    RagTokenizer.from_pretrained(__UpperCAmelCase  ,					config=__UpperCAmelCase						)
     a   :	List[str]						=    rag_tokenizer.question_encoder
     a   :	int						=    rag_tokenizer.generator

     if indexed_dataset is not None:
        a   :	Optional[int]						=    'custom'
        a   :	str						=    CustomHFIndex(config.retrieval_vector_size  ,					__UpperCAmelCase						)
     else:
        a   :	Dict						=    cls._build_index(__UpperCAmelCase						)

     return cls(
         __UpperCAmelCase  ,					question_encoder_tokenizer=__UpperCAmelCase  ,					generator_tokenizer=__UpperCAmelCase  ,					retrieval_workers=__UpperCAmelCase  ,					index=__UpperCAmelCase  ,					)






  def 							lowercase_     (						self						)				->					List[Any]:
     logger.info('re-loading the new dataset with embeddings'						)
     # access from the training loop

     ray.get([worker.clear_object.remote() for worker in self.retrieval_workers]						)

     # build the index object again
     a   :	Optional[Any]						=    self._build_index(self.config						)

     ray.get(
         [
             worker.create_rag_retriever.remote(
                 self.config  ,					self.question_encoder_tokenizer  ,					self.generator_tokenizer  ,					__UpperCAmelCase						)
             for worker in self.retrieval_workers
         ]						)





