





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


__lowercase       :str       =  logging.getLogger(__name__)
torch.set_grad_enabled(False)
__lowercase       :Optional[Any]       =  "cuda" if torch.cuda.is_available() else "cpu"







def       UpperCAmelCase							(     _lowerCamelCase      :  str			,   _lowerCamelCase      :  str=100			,   _lowerCamelCase      :  str=" "     ):





							'''simple docstring'''


							SCREAMING_SNAKE_CASE__     :				Tuple   =					text.split(_lowerCamelCase     )
							return [character.join(text[i : i + n]     ).strip() for i in range(0			,   len(_lowerCamelCase     )			,   _lowerCamelCase     )]







def       UpperCAmelCase							(     _lowerCamelCase      :  dict     ):





							'''simple docstring'''


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







def       UpperCAmelCase							(     _lowerCamelCase      :  dict			,   _lowerCamelCase      :  DPRContextEncoder			,   _lowerCamelCase      :  DPRContextEncoderTokenizerFast     ):





							'''simple docstring'''


							SCREAMING_SNAKE_CASE__     :				Tuple   =					ctx_tokenizer(
							    documents["title"]			,   documents["text"]			,   truncation=_lowerCamelCase			,   padding="longest"			,   return_tensors="pt"     )["input_ids"]
							SCREAMING_SNAKE_CASE__     :				Dict   =					ctx_encoder(input_ids.to(device=_lowerCamelCase     )			,   return_dict=_lowerCamelCase     ).pooler_output
							return {"embeddings": embeddings.detach().cpu().numpy()}







def       UpperCAmelCase							(     _lowerCamelCase      :  "RagExampleArguments"			,   _lowerCamelCase      :  "ProcessingArguments"			,   _lowerCamelCase      :  "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
							SCREAMING_SNAKE_CASE__     :				Dict   =					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
							SCREAMING_SNAKE_CASE__     :				Tuple   =					dataset.map(_lowerCamelCase			,   batched=_lowerCamelCase			,   num_proc=processing_args.num_proc     )

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

							# And finally save your dataset
							SCREAMING_SNAKE_CASE__     :				Optional[int]   =					os.path.join(rag_example_args.output_dir			,   "my_knowledge_dataset"     )
							dataset.save_to_disk(_lowerCamelCase     )
							# 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
							SCREAMING_SNAKE_CASE__     :				Tuple   =					faiss.IndexHNSWFlat(index_hnsw_args.d			,   index_hnsw_args.m			,   faiss.METRIC_INNER_PRODUCT     )
							dataset.add_faiss_index("embeddings"			,   custom_index=_lowerCamelCase     )

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



@dataclass
class    _a     :






							"""simple docstring"""

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







@dataclass
class    _a     :






							"""simple docstring"""

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







@dataclass
class    _a     :






							"""simple docstring"""

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

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






# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run

import doctest
import sys
import warnings
from os.path import abspath, dirname, join

import _pytest

from transformers.testing_utils import HfDoctestModule, HfDocTestParser


# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
__lowercase       :List[Any]       =  abspath(join(dirname(__file__), "src"))
sys.path.insert(1, git_repo_path)

# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action="ignore", category=FutureWarning)







def       UpperCAmelCase							(     _lowerCamelCase      :  int     ):





						'''simple docstring'''


						config.addinivalue_line(
						    "markers"			,   "is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested"     )
						config.addinivalue_line(
						    "markers"			,   "is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested"     )
						config.addinivalue_line("markers"			,   "is_pipeline_test: mark test to run only when pipelines are tested"     )
						config.addinivalue_line("markers"			,   "is_staging_test: mark test to run only in the staging environment"     )
						config.addinivalue_line("markers"			,   "accelerate_tests: mark test that require accelerate"     )
						config.addinivalue_line("markers"			,   "tool_tests: mark the tool tests that are run on their specific schedule"     )







def       UpperCAmelCase							(     _lowerCamelCase      :  str     ):





						'''simple docstring'''


						from transformers.testing_utils import pytest_addoption_shared

						pytest_addoption_shared(_lowerCamelCase     )







def       UpperCAmelCase							(     _lowerCamelCase      :  Tuple     ):





						'''simple docstring'''


						from transformers.testing_utils import pytest_terminal_summary_main

						SCREAMING_SNAKE_CASE__     :				List[str]   =					terminalreporter.config.getoption("--make-reports"     )
						if make_reports:
												pytest_terminal_summary_main(_lowerCamelCase			,   id=_lowerCamelCase     )







def       UpperCAmelCase							(     _lowerCamelCase      :  List[Any]			,   _lowerCamelCase      :  Dict     ):





						'''simple docstring'''


						if exitstatus == 5:
												SCREAMING_SNAKE_CASE__     :				List[str]   =					0


# Doctest custom flag to ignore output.
__lowercase       :Optional[Any]       =  doctest.register_optionflag("IGNORE_RESULT")

__lowercase       :Dict       =  doctest.OutputChecker



class    _a     (				lowercase__							):






							"""simple docstring"""

							def      A_  (      self				:     Dict							,	a				:     List[str]							,	a				:     Dict							,	a				:     int    )	->Optional[Any]:
													if IGNORE_RESULT & optionflags:
																			return True
													return OutputChecker.check_output(self							,	a							,	a							,	a    )







__lowercase       :Any       =  CustomOutputChecker
__lowercase       :Any       =  HfDoctestModule



__lowercase       :int       =  HfDocTestParser