




'''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,
    RagRetriever,
    RagSequenceForGeneration,
    RagTokenizer,
)


A							:      int 	=       logging.getLogger(__name__)
torch.set_grad_enabled(False)
A							:      List[Any] 	=       """cuda""" if torch.cuda.is_available() else """cpu"""
def 				snake_case_  (   a__		:	str    ,a__		:	Optional[int]=1_00    ,a__		:	List[Any]=" "			):



    """simple docstring"""




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



    """simple docstring"""




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



    """simple docstring"""




    __lowercase							=						ctx_tokenizer(
        documents["""title"""]    ,documents["""text"""]    ,truncation=a__    ,padding="""longest"""    ,return_tensors="""pt"""			)["""input_ids"""]
    __lowercase							=						ctx_encoder(input_ids.to(device=a__			)    ,return_dict=a__			).pooler_output
    return {"embeddings": embeddings.detach().cpu().numpy()}
def 				snake_case_  (   a__		:	"RagExampleArguments"    ,a__		:	"ProcessingArguments"    ,a__		:	"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
    __lowercase							=						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
    __lowercase							=						dataset.map(a__    ,batched=a__    ,num_proc=processing_args.num_proc			)

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

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

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

    ######################################
    logger.info("""Step 3 - Load RAG"""			)
    ######################################

    # Easy way to load the model
    __lowercase							=						RagRetriever.from_pretrained(
        rag_example_args.rag_model_name    ,index_name="""custom"""    ,indexed_dataset=a__			)
    __lowercase							=						RagSequenceForGeneration.from_pretrained(rag_example_args.rag_model_name    ,retriever=a__			)
    __lowercase							=						RagTokenizer.from_pretrained(rag_example_args.rag_model_name			)

    # For distributed fine-tuning you'll need to provide the paths instead, as the dataset and the index are loaded separately.
    # retriever = RagRetriever.from_pretrained(rag_model_name, index_name="custom", passages_path=passages_path, index_path=index_path)

    ######################################
    logger.info("""Step 4 - Have fun"""			)
    ######################################

    __lowercase							=						rag_example_args.question or """What does Moses' rod turn into ?"""
    __lowercase							=						tokenizer.question_encoder(a__    ,return_tensors="""pt"""			)["""input_ids"""]
    __lowercase							=						model.generate(a__			)
    __lowercase							=						tokenizer.batch_decode(a__    ,skip_special_tokens=a__			)[0]
    logger.info("""Q: """ + question			)
    logger.info("""A: """ + generated_string			)






@dataclass
class        SCREAMING_SNAKE_CASE:
       snake_case_ :     str    =					field(
           default=str(Path(__A     ).parent / """test_data""" / """my_knowledge_dataset.csv"""     )   ,      metadata={"""help""": """Path to a tab-separated csv file with columns 'title' and 'text'"""}   ,      )
       snake_case_ :     Optional[str]    =					field(
           default=__A   ,      metadata={"""help""": """Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."""}   ,      )
       snake_case_ :     str    =					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_ :     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'"""
               )
           }   ,      )
       snake_case_ :     Optional[str]    =					field(
           default=__A   ,      metadata={"""help""": """Path to a directory where the dataset passages and the index will be saved"""}   ,      )






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






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

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










'''simple docstring'''
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import BlipImageProcessor






class        SCREAMING_SNAKE_CASE(				unittest.TestCase     ):

       def __init__(    self					,		lowerCamelCase__					,		lowerCamelCase__=7					,		lowerCamelCase__=3					,		lowerCamelCase__=18					,		lowerCamelCase__=30					,		lowerCamelCase__=400					,		lowerCamelCase__=True					,		lowerCamelCase__=None					,		lowerCamelCase__=True					,		lowerCamelCase__=False					,		lowerCamelCase__=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]					,		lowerCamelCase__=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]					,		lowerCamelCase__=True					,		)    ->					Union[str, Any]:

           """simple docstring"""



           __lowercase							=						size if size is not None else {"""height""": 20, """width""": 20}
           __lowercase							=						parent
           __lowercase							=						batch_size
           __lowercase							=						num_channels
           __lowercase							=						image_size
           __lowercase							=						min_resolution
           __lowercase							=						max_resolution
           __lowercase							=						do_resize
           __lowercase							=						size
           __lowercase							=						do_normalize
           __lowercase							=						image_mean
           __lowercase							=						image_std
           __lowercase							=						do_pad
           __lowercase							=						do_convert_rgb

       def     snake_case__			(    self     )    ->					Optional[int]:

           """simple docstring"""



           return {
               "do_resize": self.do_resize,
               "size": self.size,
               "do_normalize": self.do_normalize,
               "image_mean": self.image_mean,
               "image_std": self.image_std,
               "do_convert_rgb": self.do_convert_rgb,
               "do_pad": self.do_pad,
           }




       def     snake_case__			(    self					,		lowerCamelCase__=False					,		lowerCamelCase__=False					,		lowerCamelCase__=False     )    ->					Tuple:

           """simple docstring"""



           assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

           if equal_resolution:
               __lowercase							=						[]
               for i in range(self.batch_size     ):
                   image_inputs.append(
                       np.random.randint(
                           255					,		size=(self.num_channels, self.max_resolution, self.max_resolution)					,		dtype=np.uinta     )     )
           else:
               __lowercase							=						[]
               for i in range(self.batch_size     ):
                   __lowercase				,__lowercase							=						np.random.choice(np.arange(self.min_resolution					,		self.max_resolution     )					,		2     )
                   image_inputs.append(np.random.randint(255					,		size=(self.num_channels, width, height)					,		dtype=np.uinta     )     )

           if not numpify and not torchify:
               # PIL expects the channel dimension as last dimension
               __lowercase							=						[Image.fromarray(np.moveaxis(lowerCamelCase__					,		0					,		-1     )     ) for x in image_inputs]

           if torchify:
               __lowercase							=						[torch.from_numpy(lowerCamelCase__     ) for x in image_inputs]

           return image_inputs






@require_torch
@require_vision
class        SCREAMING_SNAKE_CASE(				__A   ,      unittest.TestCase     ):
       snake_case_ :     Optional[int]    =					BlipImageProcessor if is_vision_available() else None

       def     snake_case__			(    self     )    ->					List[Any]:

           """simple docstring"""



           __lowercase							=						BlipImageProcessingTester(self     )

       @property
       def     snake_case__			(    self     )    ->					Optional[int]:

           """simple docstring"""



           return self.image_processor_tester.prepare_image_processor_dict()

       def     snake_case__			(    self     )    ->					List[Any]:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_resize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""size"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_normalize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_mean"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_std"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_convert_rgb"""     )     )

       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           pass

       def     snake_case__			(    self     )    ->					List[str]:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random PIL images
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		Image.Image     )

           # Test not batched input
           __lowercase							=						image_processor(image_inputs[0]					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)

           # Test batched
           __lowercase							=						image_processor(lowerCamelCase__					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)

       def     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random numpy tensors
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__					,		numpify=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		np.ndarray     )

           # Test not batched input
           __lowercase							=						image_processor(image_inputs[0]					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)

           # Test batched
           __lowercase							=						image_processor(lowerCamelCase__					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)




       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random PyTorch tensors
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__					,		torchify=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		torch.Tensor     )

           # Test not batched input
           __lowercase							=						image_processor(image_inputs[0]					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)

           # Test batched
           __lowercase							=						image_processor(lowerCamelCase__					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)






@require_torch
@require_vision
class        SCREAMING_SNAKE_CASE(				__A   ,      unittest.TestCase     ):
       snake_case_ :     Union[str, Any]    =					BlipImageProcessor if is_vision_available() else None

       def     snake_case__			(    self     )    ->					List[str]:

           """simple docstring"""



           __lowercase							=						BlipImageProcessingTester(self					,		num_channels=4     )
           __lowercase							=						3

       @property
       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           return self.image_processor_tester.prepare_image_processor_dict()

       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_resize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""size"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_normalize"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_mean"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""image_std"""     )     )
           self.assertTrue(hasattr(lowerCamelCase__					,		"""do_convert_rgb"""     )     )

       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           pass




       def     snake_case__			(    self     )    ->					Union[str, Any]:

           """simple docstring"""



           __lowercase							=						self.image_processing_class(**self.image_processor_dict     )
           # create random PIL images
           __lowercase							=						self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase__     )
           for image in image_inputs:
               self.assertIsInstance(lowerCamelCase__					,		Image.Image     )

           # Test not batched input
           __lowercase							=						image_processor(image_inputs[0]					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   1,
                   self.expected_encoded_image_num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)

           # Test batched
           __lowercase							=						image_processor(lowerCamelCase__					,		return_tensors="""pt"""     ).pixel_values
           self.assertEqual(
               encoded_images.shape					,		(
                   self.image_processor_tester.batch_size,
                   self.expected_encoded_image_num_channels,
                   self.image_processor_tester.size["""height"""],
                   self.image_processor_tester.size["""width"""],
               )					,		)




