


'''simple docstring'''





from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase_						:      Dict       =						logging.get_logger(__name__)

UpperCamelCase_						:      int       =						{
    '''huggingface/informer-tourism-monthly''': (
        '''https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json'''
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}

class        _a    (						__lowerCAmelCase							):
     SCREAMING_SNAKE_CASE_							:   List[Any]       =						"""informer"""
     SCREAMING_SNAKE_CASE_							:   str       =						{
         """hidden_size""": """d_model""",
         """num_attention_heads""": """encoder_attention_heads""",
         """num_hidden_layers""": """encoder_layers""",
     }






     def __init__(			self ,_SCREAMING_SNAKE_CASE = None ,_SCREAMING_SNAKE_CASE = None ,_SCREAMING_SNAKE_CASE = "student_t" ,_SCREAMING_SNAKE_CASE = "nll" ,_SCREAMING_SNAKE_CASE = 1 ,_SCREAMING_SNAKE_CASE = None ,_SCREAMING_SNAKE_CASE = "mean" ,_SCREAMING_SNAKE_CASE = 0 ,_SCREAMING_SNAKE_CASE = 0 ,_SCREAMING_SNAKE_CASE = 0 ,_SCREAMING_SNAKE_CASE = 0 ,_SCREAMING_SNAKE_CASE = None ,_SCREAMING_SNAKE_CASE = None ,_SCREAMING_SNAKE_CASE = 64 ,_SCREAMING_SNAKE_CASE = 32 ,_SCREAMING_SNAKE_CASE = 32 ,_SCREAMING_SNAKE_CASE = 2 ,_SCREAMING_SNAKE_CASE = 2 ,_SCREAMING_SNAKE_CASE = 2 ,_SCREAMING_SNAKE_CASE = 2 ,_SCREAMING_SNAKE_CASE = True ,_SCREAMING_SNAKE_CASE = "gelu" ,_SCREAMING_SNAKE_CASE = 0.0_5 ,_SCREAMING_SNAKE_CASE = 0.1 ,_SCREAMING_SNAKE_CASE = 0.1 ,_SCREAMING_SNAKE_CASE = 0.1 ,_SCREAMING_SNAKE_CASE = 0.1 ,_SCREAMING_SNAKE_CASE = 100 ,_SCREAMING_SNAKE_CASE = 0.0_2 ,_SCREAMING_SNAKE_CASE=True ,_SCREAMING_SNAKE_CASE = "prob" ,_SCREAMING_SNAKE_CASE = 5 ,_SCREAMING_SNAKE_CASE = True ,**_SCREAMING_SNAKE_CASE ,)							->      Dict:
          # time series specific configuration
          _snake_case							=				prediction_length
          _snake_case							=				context_length or prediction_length
          _snake_case							=				distribution_output
          _snake_case							=				loss
          _snake_case							=				input_size
          _snake_case							=				num_time_features
          _snake_case							=				lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
          _snake_case							=				scaling
          _snake_case							=				num_dynamic_real_features
          _snake_case							=				num_static_real_features
          _snake_case							=				num_static_categorical_features

          # set cardinality
          if cardinality and num_static_categorical_features > 0:
               if len(_SCREAMING_SNAKE_CASE   ) != num_static_categorical_features:
                    raise ValueError(
                        "The cardinality should be a list of the same length as `num_static_categorical_features`"   )
               _snake_case							=				cardinality
          else:
               _snake_case							=				[0]

          # set embedding_dimension
          if embedding_dimension and num_static_categorical_features > 0:
               if len(_SCREAMING_SNAKE_CASE   ) != num_static_categorical_features:
                    raise ValueError(
                        "The embedding dimension should be a list of the same length as `num_static_categorical_features`"   )
               _snake_case							=				embedding_dimension
          else:
               _snake_case							=				[min(50 ,(cat + 1) // 2   ) for cat in self.cardinality]

          _snake_case							=				num_parallel_samples

          # Transformer architecture configuration
          _snake_case							=				input_size * len(self.lags_sequence   ) + self._number_of_features
          _snake_case							=				d_model
          _snake_case							=				encoder_attention_heads
          _snake_case							=				decoder_attention_heads
          _snake_case							=				encoder_ffn_dim
          _snake_case							=				decoder_ffn_dim
          _snake_case							=				encoder_layers
          _snake_case							=				decoder_layers

          _snake_case							=				dropout
          _snake_case							=				attention_dropout
          _snake_case							=				activation_dropout
          _snake_case							=				encoder_layerdrop
          _snake_case							=				decoder_layerdrop

          _snake_case							=				activation_function
          _snake_case							=				init_std

          _snake_case							=				use_cache

          # Informer
          _snake_case							=				attention_type
          _snake_case							=				sampling_factor
          _snake_case							=				distil

          super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE   )






     @property
     def     _lowercase     (			self   )							->      int:
          return (
              sum(self.embedding_dimension   )
              + self.num_dynamic_real_features
              + self.num_time_features
              + self.num_static_real_features
              + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
          )








'''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_						:      Any       =						logging.getLogger(__name__)
torch.set_grad_enabled(False)
UpperCamelCase_						:      Optional[Any]       =						'''cuda''' if torch.cuda.is_available() else '''cpu'''





def      __a     (       _UpperCamelCase:   str ,						_UpperCamelCase:   Union[str, Any]=100 ,						_UpperCamelCase:   List[str]=" "   )						->			List[str]:

     """simple docstring"""




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





def      __a     (       _UpperCamelCase:   dict   )						->			dict:

     """simple docstring"""




     _snake_case							, _snake_case							=				[], []
     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      __a     (       _UpperCamelCase:   dict ,						_UpperCamelCase:   DPRContextEncoder ,						_UpperCamelCase:   DPRContextEncoderTokenizerFast   )						->			dict:

     """simple docstring"""




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





def      __a     (       _UpperCamelCase:   "RagExampleArguments" ,						_UpperCamelCase:   "ProcessingArguments" ,						_UpperCamelCase:   "IndexHnswArguments" ,						)						->			Dict:

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

     # And compute the embeddings
     _snake_case							=				DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name   ).to(device=_UpperCamelCase   )
     _snake_case							=				DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name   )
     _snake_case							=				Features(
         {"text": Value("string"   ), "title": Value("string"   ), "embeddings": Sequence(Value("float32"   )   )}   )  # optional, save as float32 instead of float64 to save space
     _snake_case							=				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
     _snake_case							=				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
     _snake_case							=				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
     _snake_case							=				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    :
     SCREAMING_SNAKE_CASE_							:   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'"""} , )
     SCREAMING_SNAKE_CASE_							:   Optional[str]       =						field(
         default=__lowerCAmelCase , metadata={"""help""": """Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."""} , )
     SCREAMING_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'"""} , )
     SCREAMING_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'"""
             )
         } , )
     SCREAMING_SNAKE_CASE_							:   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        _a    :
     SCREAMING_SNAKE_CASE_							:   Optional[int]       =						field(
         default=__lowerCAmelCase , metadata={
             """help""": """The number of processes to use to split the documents into passages. Default is single process."""
         } , )
     SCREAMING_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        _a    :
     SCREAMING_SNAKE_CASE_							:   int       =						field(
         default=7_68 , metadata={"""help""": """The dimension of the embeddings to pass to the HNSW Faiss index."""} , )
     SCREAMING_SNAKE_CASE_							:   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_						:      List[str]       =						HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments))
   UpperCamelCase_     ,     UpperCamelCase_     ,     UpperCamelCase_						:      List[Any]       =						parser.parse_args_into_dataclasses()
   with TemporaryDirectory() as tmp_dir:
      UpperCamelCase_						:      str       =						rag_example_args.output_dir or tmp_dir
      main(rag_example_args, processing_args, index_hnsw_args)


