


"""simple docstring"""





import logging
import os
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import List, Optional

import faiss
import torch
from datasets import Features, Sequence, Value, load_dataset

from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser


snake_case__						:   List[str]			 = logging.getLogger(__name__)
torch.set_grad_enabled(False)
snake_case__						:   Any			 = '''cuda''' if torch.cuda.is_available() else '''cpu'''


def    _snake_case  (  _snake_case :	str       ,      _snake_case :	Union[str, Any]=100       ,      _snake_case :	List[str]=" "	):
      lowerCAmelCase    :		Union[str, Any]				=      text.split(_snake_case	)
      return [character.join(text[i : i + n]	).strip() for i in range(0       ,      len(_snake_case	)       ,      _snake_case	)]


def    _snake_case  (  _snake_case :	dict	):
      lowerCAmelCase,					lowerCAmelCase    :		List[str]				=      [], []
      for title, text in zip(documents['''title''']       ,      documents['''text''']	):
            if text is not None:
                  for passage in split_text(_snake_case	):
                        titles.append(title if title is not None else ''''''	)
                        texts.append(_snake_case	)
      return {"title": titles, "text": texts}


def    _snake_case  (  _snake_case :	dict       ,      _snake_case :	DPRContextEncoder       ,      _snake_case :	DPRContextEncoderTokenizerFast	):
      lowerCAmelCase    :		Optional[int]				=      ctx_tokenizer(
          documents['''title''']       ,      documents['''text''']       ,      truncation=_snake_case       ,      padding='''longest'''       ,      return_tensors='''pt'''	)['''input_ids''']
      lowerCAmelCase    :		List[str]				=      ctx_encoder(input_ids.to(device=_snake_case	)       ,      return_dict=_snake_case	).pooler_output
      return {"embeddings": embeddings.detach().cpu().numpy()}


def    _snake_case  (  _snake_case :	"RagExampleArguments"       ,      _snake_case :	"ProcessingArguments"       ,      _snake_case :	"IndexHnswArguments"       ,      ):
      ######################################
      logger.info('''Step 1 - Create the dataset'''	)
      ######################################

      # The dataset needed for RAG must have three columns:
      # - title (string): title of the document
      # - text (string): text of a passage of the document
      # - embeddings (array of dimension d): DPR representation of the passage
      # Let's say you have documents in tab-separated csv files with columns "title" and "text"
      assert os.path.isfile(rag_example_args.csv_path	), "Please provide a valid path to a csv file"

      # You can load a Dataset object this way
      lowerCAmelCase    :		Any				=      load_dataset(
          '''csv'''       ,      data_files=[rag_example_args.csv_path]       ,      split='''train'''       ,      delimiter='''\t'''       ,      column_names=['''title''', '''text''']	)

      # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files

      # Then split the documents into passages of 100 words
      lowerCAmelCase    :		Optional[int]				=      dataset.map(_snake_case       ,      batched=_snake_case       ,      num_proc=processing_args.num_proc	)

      # And compute the embeddings
      lowerCAmelCase    :		Optional[Any]				=      DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name	).to(device=_snake_case	)
      lowerCAmelCase    :		Union[str, Any]				=      DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name	)
      lowerCAmelCase    :		Dict				=      Features(
          {'''text''': Value('''string'''	), '''title''': Value('''string'''	), '''embeddings''': Sequence(Value('''float32'''	)	)}	)  # optional, save as float32 instead of float64 to save space
      lowerCAmelCase    :		Optional[Any]				=      dataset.map(
          partial(_snake_case       ,      ctx_encoder=_snake_case       ,      ctx_tokenizer=_snake_case	)       ,      batched=_snake_case       ,      batch_size=processing_args.batch_size       ,      features=_snake_case       ,      )

      # And finally save your dataset
      lowerCAmelCase    :		Any				=      os.path.join(rag_example_args.output_dir       ,      '''my_knowledge_dataset'''	)
      dataset.save_to_disk(_snake_case	)
      # from datasets import load_from_disk
      # dataset = load_from_disk(passages_path)  # to reload the dataset

      ######################################
      logger.info('''Step 2 - Index the dataset'''	)
      ######################################

      # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search
      lowerCAmelCase    :		Any				=      faiss.IndexHNSWFlat(index_hnsw_args.d       ,      index_hnsw_args.m       ,      faiss.METRIC_INNER_PRODUCT	)
      dataset.add_faiss_index('''embeddings'''       ,      custom_index=_snake_case	)

      # And save the index
      lowerCAmelCase    :		List[Any]				=      os.path.join(rag_example_args.output_dir       ,      '''my_knowledge_dataset_hnsw_index.faiss'''	)
      dataset.get_index('''embeddings'''	).save(_snake_case	)
      # dataset.load_faiss_index("embeddings", index_path)  # to reload the index



@dataclass
class 						snake_case_:
     __UpperCamelCase     =    field(
         default=str(Path(a__	).parent / '''test_run''' / '''dummy-kb''' / '''my_knowledge_dataset.csv'''	)							,    metadata={'''help''': '''Path to a tab-separated csv file with columns \'title\' and \'text\''''}							,    )
     __UpperCamelCase     =    field(
         default=a__							,    metadata={'''help''': '''Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'.'''}							,    )
     __UpperCamelCase     =    field(
         default='''facebook/rag-sequence-nq'''							,    metadata={'''help''': '''The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\''''}							,    )
     __UpperCamelCase     =    field(
         default='''facebook/dpr-ctx_encoder-multiset-base'''							,    metadata={
             '''help''': (
                 '''The DPR context encoder model to use. Either \'facebook/dpr-ctx_encoder-single-nq-base\' or'''
                 ''' \'facebook/dpr-ctx_encoder-multiset-base\''''
             )
         }							,    )
     __UpperCamelCase     =    field(
         default=str(Path(a__	).parent / '''test_run''' / '''dummy-kb'''	)							,    metadata={'''help''': '''Path to a directory where the dataset passages and the index will be saved'''}							,    )



@dataclass
class 						snake_case_:
     __UpperCamelCase     =    field(
         default=a__							,    metadata={
             '''help''': '''The number of processes to use to split the documents into passages. Default is single process.'''
         }							,    )
     __UpperCamelCase     =    field(
         default=16							,    metadata={
             '''help''': '''The batch size to use when computing the passages embeddings using the DPR context encoder.'''
         }							,    )



@dataclass
class 						snake_case_:
     __UpperCamelCase     =    field(
         default=768							,    metadata={'''help''': '''The dimension of the embeddings to pass to the HNSW Faiss index.'''}							,    )
     __UpperCamelCase     =    field(
         default=128							,    metadata={
             '''help''': (
                 '''The number of bi-directional links created for every new element during the HNSW index construction.'''
             )
         }							,    )


if __name__ == "__main__":
 logging.basicConfig(level=logging.WARNING)
 logger.setLevel(logging.INFO)

 snake_case__						:   Any			 = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments))
 snake_case__ ,   snake_case__ ,   snake_case__						:   Dict			 = parser.parse_args_into_dataclasses()
 with TemporaryDirectory() as tmp_dir:
  snake_case__						:   List[Any]			 = rag_example_args.output_dir or tmp_dir
  main(rag_example_args, processing_args, index_hnsw_args)






"""simple docstring"""





import inspect
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
snake_case__						:   Optional[Any]			 = '''src/transformers'''


# This is to make sure the transformers module imported is the one in the repo.
snake_case__						:   Dict			 = direct_transformers_import(PATH_TO_TRANSFORMERS)

snake_case__						:   Optional[int]			 = transformers.models.auto.configuration_auto.CONFIG_MAPPING

# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
snake_case__						:   Optional[int]			 = re.compile(R'''\[(.+?)\]\((https://huggingface\.co/.+?)\)''')


snake_case__						:   int			 = {
    '''DecisionTransformerConfig''',
    '''EncoderDecoderConfig''',
    '''MusicgenConfig''',
    '''RagConfig''',
    '''SpeechEncoderDecoderConfig''',
    '''TimmBackboneConfig''',
    '''VisionEncoderDecoderConfig''',
    '''VisionTextDualEncoderConfig''',
    '''LlamaConfig''',
}


def    _snake_case  (  _snake_case :	List[str]	):
      lowerCAmelCase    :		Dict				=      None

      # source code of `config_class`
      lowerCAmelCase    :		Union[str, Any]				=      inspect.getsource(_snake_case	)
      lowerCAmelCase    :		List[Any]				=      _re_checkpoint.findall(_snake_case	)

      # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
      # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
      for ckpt_name, ckpt_link in checkpoints:
            # allow the link to end with `/`
            if ckpt_link.endswith('''/'''	):
                  lowerCAmelCase    :		List[str]				=      ckpt_link[:-1]

            # verify the checkpoint name corresponds to the checkpoint link
            lowerCAmelCase    :		Optional[int]				=      f'''https://huggingface.co/{ckpt_name}'''
            if ckpt_link == ckpt_link_from_name:
                  lowerCAmelCase    :		List[str]				=      ckpt_name
                  break

      return checkpoint


def    _snake_case  (  ):
      lowerCAmelCase    :		List[Any]				=      []

      for config_class in list(CONFIG_MAPPING.values()	):
            # Skip deprecated models
            if "models.deprecated" in config_class.__module__:
                  continue
            lowerCAmelCase    :		int				=      get_checkpoint_from_config_class(_snake_case	)

            lowerCAmelCase    :		int				=      config_class.__name__
            if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
                  configs_without_checkpoint.append(_snake_case	)

      if len(_snake_case	) > 0:
            lowerCAmelCase    :		Dict				=      '''\n'''.join(sorted(_snake_case	)	)
            raise ValueError(f'''The following configurations don\'t contain any valid checkpoint:\n{message}'''	)


if __name__ == "__main__":
 check_config_docstrings_have_checkpoints()


