




'''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				:				Optional[int]       							=		logging.getLogger(__name__)
torch.set_grad_enabled(False)
_snake_case				:				Union[str, Any]       							=		'cuda' if torch.cuda.is_available() else 'cpu'
def 		snake_case_   (UpperCamelCase	:  str			,						UpperCamelCase	:  Any=100			,						UpperCamelCase	:  Optional[int]=" "				):





							'''simple docstring'''


							_a     					=    text.split(UpperCamelCase				)
							return [character.join(text[i : i + n]				).strip() for i in range(0			,						len(UpperCamelCase				)			,						UpperCamelCase				)]
def 		snake_case_   (UpperCamelCase	:  dict				):





							'''simple docstring'''


							_a					,							_a     					=    [], []
							for title, text in zip(documents['''title''']			,						documents['''text''']				):
														if text is not None:
																					for passage in split_text(UpperCamelCase				):
																												titles.append(title if title is not None else ''''''				)
																												texts.append(UpperCamelCase				)
							return {"title": titles, "text": texts}
def 		snake_case_   (UpperCamelCase	:  dict			,						UpperCamelCase	:  DPRContextEncoder			,						UpperCamelCase	:  DPRContextEncoderTokenizerFast				):





							'''simple docstring'''


							_a     					=    ctx_tokenizer(
							    documents['''title''']			,						documents['''text''']			,						truncation=UpperCamelCase			,						padding='''longest'''			,						return_tensors='''pt'''				)['''input_ids''']
							_a     					=    ctx_encoder(input_ids.to(device=UpperCamelCase				)			,						return_dict=UpperCamelCase				).pooler_output
							return {"embeddings": embeddings.detach().cpu().numpy()}
def 		snake_case_   (UpperCamelCase	:  "RagExampleArguments"			,						UpperCamelCase	:  "ProcessingArguments"			,						UpperCamelCase	:  "IndexHnswArguments"			,						):





							'''simple docstring'''


							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
							_a     					=    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
							_a     					=    dataset.map(UpperCamelCase			,						batched=UpperCamelCase			,						num_proc=processing_args.num_proc				)

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

							# And finally save your dataset
							_a     					=    os.path.join(rag_example_args.output_dir			,						'''my_knowledge_dataset'''				)
							dataset.save_to_disk(UpperCamelCase				)
							# 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
							_a     					=    faiss.IndexHNSWFlat(index_hnsw_args.d			,						index_hnsw_args.m			,						faiss.METRIC_INNER_PRODUCT				)
							dataset.add_faiss_index('''embeddings'''			,						custom_index=UpperCamelCase				)

							# And save the index
							_a     					=    os.path.join(rag_example_args.output_dir			,						'''my_knowledge_dataset_hnsw_index.faiss'''				)
							dataset.get_index('''embeddings'''				).save(UpperCamelCase				)
							# dataset.load_faiss_index("embeddings", index_path)  # to reload the index

@dataclass
class       A   :
							lowercase_          =    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\''}					,)
							lowercase_          =    field(
							    default=_a					,metadata={'help': 'Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'.'}					,)
							lowercase_          =    field(
							    default='facebook/rag-sequence-nq'					,metadata={'help': 'The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\''}					,)
							lowercase_          =    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\''
							        )
							    }					,)
							lowercase_          =    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       A   :
							lowercase_          =    field(
							    default=_a					,metadata={
							        'help': 'The number of processes to use to split the documents into passages. Default is single process.'
							    }					,)
							lowercase_          =    field(
							    default=16					,metadata={
							        'help': 'The batch size to use when computing the passages embeddings using the DPR context encoder.'
							    }					,)



@dataclass
class       A   :
							lowercase_          =    field(
							    default=768					,metadata={'help': 'The dimension of the embeddings to pass to the HNSW Faiss index.'}					,)
							lowercase_          =    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				:				Optional[int]       							=		HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments))
				_snake_case							,    _snake_case							,    _snake_case				:				Optional[int]       							=		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'''


from argparse import ArgumentParser, Namespace

from ..utils import logging
from . import BaseTransformersCLICommand
def 		snake_case_   (UpperCamelCase	:  Namespace				):





							'''simple docstring'''


							return ConvertCommand(
							    args.model_type			,						args.tf_checkpoint			,						args.pytorch_dump_output			,						args.config			,						args.finetuning_task_name				)


_snake_case				:				List[Any]       							=		'\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n'

class       A   (		_a   ):







							@staticmethod
							def        __lowerCAmelCase      (  lowerCAmelCase_	:  ArgumentParser )      ->							Any:


														"""simple docstring"""


														_a     					=    parser.add_parser(
														    '''convert'''							,      help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.'''							,      )
														train_parser.add_argument('''--model_type'''							,      type=lowerCAmelCase_							,      required=lowerCAmelCase_							,      help='''Model\'s type.''' )
														train_parser.add_argument(
														    '''--tf_checkpoint'''							,      type=lowerCAmelCase_							,      required=lowerCAmelCase_							,      help='''TensorFlow checkpoint path or folder.''' )
														train_parser.add_argument(
														    '''--pytorch_dump_output'''							,      type=lowerCAmelCase_							,      required=lowerCAmelCase_							,      help='''Path to the PyTorch saved model output.''' )
														train_parser.add_argument('''--config'''							,      type=lowerCAmelCase_							,      default=''''''							,      help='''Configuration file path or folder.''' )
														train_parser.add_argument(
														    '''--finetuning_task_name'''							,      type=lowerCAmelCase_							,      default=lowerCAmelCase_							,      help='''Optional fine-tuning task name if the TF model was a finetuned model.'''							,      )
														train_parser.set_defaults(func=lowerCAmelCase_ )







							def __init__(  self	:  int							,      lowerCAmelCase_	:  str							,      lowerCAmelCase_	:  str							,      lowerCAmelCase_	:  str							,      lowerCAmelCase_	:  str							,      lowerCAmelCase_	:  str							,      *lowerCAmelCase_	:  Optional[Any]							,      )      ->							List[str]:


														"""simple docstring"""


														_a     					=    logging.get_logger('''transformers-cli/converting''' )

														self._logger.info(F'Loading model {model_type}' )
														_a     					=    model_type
														_a     					=    tf_checkpoint
														_a     					=    pytorch_dump_output
														_a     					=    config
														_a     					=    finetuning_task_name







							def        __lowerCAmelCase      (  self	:  Dict )      ->							Dict:


														"""simple docstring"""


														if self._model_type == "albert":
																					try:
																												from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import (
																												    convert_tf_checkpoint_to_pytorch,
																												)
																					except ImportError:
																												raise ImportError(lowerCAmelCase_ )

																					convert_tf_checkpoint_to_pytorch(self._tf_checkpoint							,      self._config							,      self._pytorch_dump_output )
														elif self._model_type == "bert":
																					try:
																												from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import (
																												    convert_tf_checkpoint_to_pytorch,
																												)
																					except ImportError:
																												raise ImportError(lowerCAmelCase_ )

																					convert_tf_checkpoint_to_pytorch(self._tf_checkpoint							,      self._config							,      self._pytorch_dump_output )
														elif self._model_type == "funnel":
																					try:
																												from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import (
																												    convert_tf_checkpoint_to_pytorch,
																												)
																					except ImportError:
																												raise ImportError(lowerCAmelCase_ )

																					convert_tf_checkpoint_to_pytorch(self._tf_checkpoint							,      self._config							,      self._pytorch_dump_output )
														elif self._model_type == "t5":
																					try:
																												from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
																					except ImportError:
																												raise ImportError(lowerCAmelCase_ )

																					convert_tf_checkpoint_to_pytorch(self._tf_checkpoint							,      self._config							,      self._pytorch_dump_output )
														elif self._model_type == "gpt":
																					from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import (
																					    convert_openai_checkpoint_to_pytorch,
																					)

																					convert_openai_checkpoint_to_pytorch(self._tf_checkpoint							,      self._config							,      self._pytorch_dump_output )
														elif self._model_type == "transfo_xl":
																					try:
																												from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import (
																												    convert_transfo_xl_checkpoint_to_pytorch,
																												)
																					except ImportError:
																												raise ImportError(lowerCAmelCase_ )

																					if "ckpt" in self._tf_checkpoint.lower():
																												_a     					=    self._tf_checkpoint
																												_a     					=    ''''''
																					else:
																												_a     					=    self._tf_checkpoint
																												_a     					=    ''''''
																					convert_transfo_xl_checkpoint_to_pytorch(
																					    lowerCAmelCase_							,      self._config							,      self._pytorch_dump_output							,      lowerCAmelCase_ )
														elif self._model_type == "gpt2":
																					try:
																												from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import (
																												    convert_gpta_checkpoint_to_pytorch,
																												)
																					except ImportError:
																												raise ImportError(lowerCAmelCase_ )

																					convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint							,      self._config							,      self._pytorch_dump_output )
														elif self._model_type == "xlnet":
																					try:
																												from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import (
																												    convert_xlnet_checkpoint_to_pytorch,
																												)
																					except ImportError:
																												raise ImportError(lowerCAmelCase_ )

																					convert_xlnet_checkpoint_to_pytorch(
																					    self._tf_checkpoint							,      self._config							,      self._pytorch_dump_output							,      self._finetuning_task_name )
														elif self._model_type == "xlm":
																					from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import (
																					    convert_xlm_checkpoint_to_pytorch,
																					)

																					convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint							,      self._pytorch_dump_output )
														elif self._model_type == "lxmert":
																					from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import (
																					    convert_lxmert_checkpoint_to_pytorch,
																					)

																					convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint							,      self._pytorch_dump_output )
														elif self._model_type == "rembert":
																					from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import (
																					    convert_rembert_tf_checkpoint_to_pytorch,
																					)

																					convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint							,      self._config							,      self._pytorch_dump_output )
														else:
																					raise ValueError(
																					    '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )

