



'''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


UpperCAmelCase     		=   logging.getLogger(__name__)
torch.set_grad_enabled(False)
UpperCAmelCase     		=   'cuda' if torch.cuda.is_available() else 'cpu'






def 		_snake_case		( _SCREAMING_SNAKE_CASE					:						str							,		_SCREAMING_SNAKE_CASE					:						Any=100							,		_SCREAMING_SNAKE_CASE					:						str=" "							)      ->						List[str]:







	"""simple docstring"""
	lowerCAmelCase   =     text.split(_SCREAMING_SNAKE_CASE							)
	return [character.join(text[i : i + n]							).strip() for i in range(0							,		len(_SCREAMING_SNAKE_CASE							)							,		_SCREAMING_SNAKE_CASE							)]






def 		_snake_case		( _SCREAMING_SNAKE_CASE					:						dict							)      ->						dict:







	"""simple docstring"""
	lowerCAmelCase,       lowerCAmelCase   =     [], []
	for title, text in zip(documents["""title"""]							,		documents["""text"""]							):
		if text is not None:
			for passage in split_text(_SCREAMING_SNAKE_CASE							):
				titles.append(title if title is not None else """"""							)
				texts.append(_SCREAMING_SNAKE_CASE							)
	return {"title": titles, "text": texts}






def 		_snake_case		( _SCREAMING_SNAKE_CASE					:						dict							,		_SCREAMING_SNAKE_CASE					:						DPRContextEncoder							,		_SCREAMING_SNAKE_CASE					:						DPRContextEncoderTokenizerFast							)      ->						dict:







	"""simple docstring"""
	lowerCAmelCase   =     ctx_tokenizer(
	    documents["""title"""]							,		documents["""text"""]							,		truncation=_SCREAMING_SNAKE_CASE							,		padding="""longest"""							,		return_tensors="""pt"""							)["""input_ids"""]
	lowerCAmelCase   =     ctx_encoder(input_ids.to(device=_SCREAMING_SNAKE_CASE							)							,		return_dict=_SCREAMING_SNAKE_CASE							).pooler_output
	return {"embeddings": embeddings.detach().cpu().numpy()}






def 		_snake_case		( _SCREAMING_SNAKE_CASE					:						"RagExampleArguments"							,		_SCREAMING_SNAKE_CASE					:						"ProcessingArguments"							,		_SCREAMING_SNAKE_CASE					:						"IndexHnswArguments"							,		)      ->						Optional[int]:







	"""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
	lowerCAmelCase   =     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   =     dataset.map(_SCREAMING_SNAKE_CASE							,		batched=_SCREAMING_SNAKE_CASE							,		num_proc=processing_args.num_proc							)

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

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

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

@dataclass
class __snake_case:


						'''simple docstring'''



						UpperCAmelCase							:   str									=		field(
						    default=str(Path(_lowerCAmelCase ).parent / "test_run" / "dummy-kb" / "my_knowledge_dataset.csv" )		,							metadata={"help": "Path to a tab-separated csv file with columns 'title' and 'text'"}		,							)
						UpperCAmelCase							:   Optional[str]									=		field(
						    default=_lowerCAmelCase		,							metadata={"help": "Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."}		,							)
						UpperCAmelCase							:   str									=		field(
						    default="facebook/rag-sequence-nq"		,							metadata={"help": "The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"}		,							)
						UpperCAmelCase							:   str									=		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							:   Optional[str]									=		field(
						    default=str(Path(_lowerCAmelCase ).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:


						'''simple docstring'''



						UpperCAmelCase							:   Optional[int]									=		field(
						    default=_lowerCAmelCase		,							metadata={
						        "help": "The number of processes to use to split the documents into passages. Default is single process."
						    }		,							)
						UpperCAmelCase							:   int									=		field(
						    default=16		,							metadata={
						        "help": "The batch size to use when computing the passages embeddings using the DPR context encoder."
						    }		,							)







@dataclass
class __snake_case:


						'''simple docstring'''



						UpperCAmelCase							:   int									=		field(
						    default=7_68		,							metadata={"help": "The dimension of the embeddings to pass to the HNSW Faiss index."}		,							)
						UpperCAmelCase							:   int									=		field(
						    default=1_28		,							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)

				UpperCAmelCase     		=   HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments))
				UpperCAmelCase		,       UpperCAmelCase		,       UpperCAmelCase     		=   parser.parse_args_into_dataclasses()
				with TemporaryDirectory() as tmp_dir:
								UpperCAmelCase     		=   rag_example_args.output_dir or tmp_dir
								main(rag_example_args, processing_args, index_hnsw_args)




'''simple docstring'''

import os
from argparse import ArgumentParser, Namespace

from ..data import SingleSentenceClassificationProcessor as Processor
from ..pipelines import TextClassificationPipeline
from ..utils import is_tf_available, is_torch_available, logging
from . import BaseTransformersCLICommand


if not is_tf_available() and not is_torch_available():
				raise RuntimeError('At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training')

# TF training parameters
UpperCAmelCase     		=   False
UpperCAmelCase     		=   False






def 		_snake_case		( _SCREAMING_SNAKE_CASE					:						Namespace							)      ->						Tuple:







	"""simple docstring"""
	return TrainCommand(_SCREAMING_SNAKE_CASE							)





class __snake_case(				_lowerCAmelCase ):


						'''simple docstring'''



						@staticmethod
						def     __snake_case   ( A_				)     ->     Optional[int]:
							lowerCAmelCase   =     parser.add_parser("""train"""     ,	help="""CLI tool to train a model on a task."""				)

							train_parser.add_argument(
							    """--train_data"""     ,	type=A_     ,	required=A_     ,	help="""path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences."""     ,	)
							train_parser.add_argument(
							    """--column_label"""     ,	type=A_     ,	default=0     ,	help="""Column of the dataset csv file with example labels."""				)
							train_parser.add_argument(
							    """--column_text"""     ,	type=A_     ,	default=1     ,	help="""Column of the dataset csv file with example texts."""				)
							train_parser.add_argument(
							    """--column_id"""     ,	type=A_     ,	default=2     ,	help="""Column of the dataset csv file with example ids."""				)
							train_parser.add_argument(
							    """--skip_first_row"""     ,	action="""store_true"""     ,	help="""Skip the first row of the csv file (headers)."""				)

							train_parser.add_argument("""--validation_data"""     ,	type=A_     ,	default=""""""     ,	help="""path to validation dataset."""				)
							train_parser.add_argument(
							    """--validation_split"""     ,	type=A_     ,	default=0.1     ,	help="""if validation dataset is not provided, fraction of train dataset to use as validation dataset."""     ,	)

							train_parser.add_argument("""--output"""     ,	type=A_     ,	default="""./"""     ,	help="""path to saved the trained model."""				)

							train_parser.add_argument(
							    """--task"""     ,	type=A_     ,	default="""text_classification"""     ,	help="""Task to train the model on."""				)
							train_parser.add_argument(
							    """--model"""     ,	type=A_     ,	default="""bert-base-uncased"""     ,	help="""Model's name or path to stored model."""				)
							train_parser.add_argument("""--train_batch_size"""     ,	type=A_     ,	default=32     ,	help="""Batch size for training."""				)
							train_parser.add_argument("""--valid_batch_size"""     ,	type=A_     ,	default=64     ,	help="""Batch size for validation."""				)
							train_parser.add_argument("""--learning_rate"""     ,	type=A_     ,	default=3e-5     ,	help="""Learning rate."""				)
							train_parser.add_argument("""--adam_epsilon"""     ,	type=A_     ,	default=1e-08     ,	help="""Epsilon for Adam optimizer."""				)
							train_parser.set_defaults(func=A_				)


						def __init__( self     ,	A_				)     ->     Tuple:
							lowerCAmelCase   =     logging.get_logger("""transformers-cli/training"""				)

							lowerCAmelCase   =     """tf""" if is_tf_available() else """torch"""

							os.makedirs(args.output     ,	exist_ok=A_				)
							lowerCAmelCase   =     args.output

							lowerCAmelCase   =     args.column_label
							lowerCAmelCase   =     args.column_text
							lowerCAmelCase   =     args.column_id

							self.logger.info(f'Loading {args.task} pipeline for {args.model}'				)
							if args.task == "text_classification":
								lowerCAmelCase   =     TextClassificationPipeline.from_pretrained(args.model				)
							elif args.task == "token_classification":
								raise NotImplementedError
							elif args.task == "question_answering":
								raise NotImplementedError

							self.logger.info(f'Loading dataset from {args.train_data}'				)
							lowerCAmelCase   =     Processor.create_from_csv(
							    args.train_data     ,	column_label=args.column_label     ,	column_text=args.column_text     ,	column_id=args.column_id     ,	skip_first_row=args.skip_first_row     ,	)
							lowerCAmelCase   =     None
							if args.validation_data:
								self.logger.info(f'Loading validation dataset from {args.validation_data}'				)
								lowerCAmelCase   =     Processor.create_from_csv(
								    args.validation_data     ,	column_label=args.column_label     ,	column_text=args.column_text     ,	column_id=args.column_id     ,	skip_first_row=args.skip_first_row     ,	)

							lowerCAmelCase   =     args.validation_split
							lowerCAmelCase   =     args.train_batch_size
							lowerCAmelCase   =     args.valid_batch_size
							lowerCAmelCase   =     args.learning_rate
							lowerCAmelCase   =     args.adam_epsilon


						def     __snake_case   ( self				)     ->     Optional[int]:
							if self.framework == "tf":
								return self.run_tf()
							return self.run_torch()


						def     __snake_case   ( self				)     ->     Tuple:
							raise NotImplementedError




						def     __snake_case   ( self				)     ->     Tuple:
							self.pipeline.fit(
							    self.train_dataset     ,	validation_data=self.valid_dataset     ,	validation_split=self.validation_split     ,	learning_rate=self.learning_rate     ,	adam_epsilon=self.adam_epsilon     ,	train_batch_size=self.train_batch_size     ,	valid_batch_size=self.valid_batch_size     ,	)

							# Save trained pipeline
							self.pipeline.save_pretrained(self.output				)