





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       :   Tuple				       =							logging.getLogger(__name__)
torch.set_grad_enabled(False)
__UpperCAmelCase       :   str				       =							"cuda" if torch.cuda.is_available() else "cpu"







def 			A__							(    SCREAMING_SNAKE_CASE__					,					SCREAMING_SNAKE_CASE__=100					,					SCREAMING_SNAKE_CASE__=" ")   ->    List[str]:
  __snake_case:						Union[str, Any]   =						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 			A__							(    SCREAMING_SNAKE_CASE__)   ->    dict:
  __snake_case  ,   __snake_case:						int   =						[], []
  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 			A__							(    SCREAMING_SNAKE_CASE__					,					SCREAMING_SNAKE_CASE__					,					SCREAMING_SNAKE_CASE__)   ->    dict:
  __snake_case:						List[str]   =						ctx_tokenizer(
      documents["""title"""]					,					documents["""text"""]					,					truncation=SCREAMING_SNAKE_CASE__					,					padding="""longest"""					,					return_tensors="""pt""")["""input_ids"""]
  __snake_case:						List[Any]   =						ctx_encoder(input_ids.to(device=SCREAMING_SNAKE_CASE__)					,					return_dict=SCREAMING_SNAKE_CASE__).pooler_output
  return {"embeddings": embeddings.detach().cpu().numpy()}







def 			A__							(    SCREAMING_SNAKE_CASE__					,					SCREAMING_SNAKE_CASE__					,					SCREAMING_SNAKE_CASE__					,					)   ->    Optional[int]:
  ######################################
  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:						List[str]   =						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:						Dict   =						dataset.map(SCREAMING_SNAKE_CASE__					,					batched=SCREAMING_SNAKE_CASE__					,					num_proc=processing_args.num_proc)

  # And compute the embeddings
  __snake_case:						Dict   =						DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name).to(device=SCREAMING_SNAKE_CASE__)
  __snake_case:						Any   =						DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name)
  __snake_case:						Any   =						Features(
      {"""text""": Value("""string"""), """title""": Value("""string"""), """embeddings""": Sequence(Value("""float32"""))})  # optional, save as float32 instead of float64 to save space
  __snake_case:						Any   =						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
  __snake_case:						Union[str, Any]   =						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
  __snake_case:						Any   =						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
  __snake_case:						Union[str, Any]   =						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'''







       lowerCAmelCase__      		=     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'"""}   ,			)
       lowerCAmelCase__      		=     field(
           default=__lowerCamelCase   ,			metadata={"""help""": """Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."""}   ,			)
       lowerCAmelCase__      		=     field(
           default="""facebook/rag-sequence-nq"""   ,			metadata={"""help""": """The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"""}   ,			)
       lowerCAmelCase__      		=     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'"""
               )
           }   ,			)
       lowerCAmelCase__      		=     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'''







       lowerCAmelCase__      		=     field(
           default=__lowerCamelCase   ,			metadata={
               """help""": """The number of processes to use to split the documents into passages. Default is single process."""
           }   ,			)
       lowerCAmelCase__      		=     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'''







       lowerCAmelCase__      		=     field(
           default=7_68   ,			metadata={"""help""": """The dimension of the embeddings to pass to the HNSW Faiss index."""}   ,			)
       lowerCAmelCase__      		=     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       :   str				       =							HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments))
      __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       :   Union[str, Any]				       =							parser.parse_args_into_dataclasses()
      with TemporaryDirectory() as tmp_dir:
            __UpperCAmelCase       :   List[str]				       =							rag_example_args.output_dir or tmp_dir
            main(rag_example_args, processing_args, index_hnsw_args)













import json
import os
import unittest

from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import (
    VOCAB_FILES_NAMES,
    GPTSanJapaneseTokenizer,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin







@require_tokenizers
class     __snake_case       (							__lowerCamelCase   ,			unittest.TestCase			):





       '''simple docstring'''







       lowerCAmelCase__      		=     GPTSanJapaneseTokenizer
       lowerCAmelCase__      		=     False
       lowerCAmelCase__      		=     {"""do_clean_text""": False, """add_prefix_space""": False}




       def 							UpperCAmelCase__ (  self :    Union[str, Any]		):
         super().setUp()

         # fmt: off
         __snake_case:						str   =						["""こん""", """こんに""", """にちは""", """ばんは""", """世界,㔺界""", """、""", """。""", """<BR>""", """<SP>""", """<TAB>""", """<URL>""", """<EMAIL>""", """<TEL>""", """<DATE>""", """<PRICE>""", """<BLOCK>""", """<KIGOU>""", """<U2000U2BFF>""", """<|emoji1|>""", """<unk>""", """<|bagoftoken|>""", """<|endoftext|>"""]
         # fmt: on
         __snake_case:						List[Any]   =						{"""emoji""": {"""\ud83d\ude00""": """<|emoji1|>"""}, """emoji_inv""": {"""<|emoji1|>""": """\ud83d\ude00"""}}  # 😀
         __snake_case:						Optional[int]   =						{"""unk_token""": """<unk>"""}

         __snake_case:						Any   =						os.path.join(self.tmpdirname							,				VOCAB_FILES_NAMES["""vocab_file"""]		)
         __snake_case:						int   =						os.path.join(self.tmpdirname							,				VOCAB_FILES_NAMES["""emoji_file"""]		)
         with open(self.vocab_file							,				"""w"""							,				encoding="""utf-8"""		) as vocab_writer:
           vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]		)		)
         with open(self.emoji_file							,				"""w"""		) as emoji_writer:
           emoji_writer.write(json.dumps(A		)		)




       def 							UpperCAmelCase__ (  self :    Optional[int]							,				**A :    int		):
         kwargs.update(self.special_tokens_map		)
         return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname							,				**A		)




       def 							UpperCAmelCase__ (  self :    Optional[Any]							,				A :    Dict		):
         __snake_case:						Tuple   =						"""こんにちは、世界。 \nこんばんは、㔺界。😀"""
         __snake_case:						str   =						"""こんにちは、世界。 \nこんばんは、世界。😀"""
         return input_text, output_text




       def 							UpperCAmelCase__ (  self :    Optional[int]							,				A :    Optional[int]		):
         __snake_case  ,   __snake_case:						Optional[int]   =						self.get_input_output_texts(A		)
         __snake_case:						Optional[Any]   =						tokenizer.encode(A							,				add_special_tokens=A		)
         __snake_case:						int   =						tokenizer.decode(A							,				clean_up_tokenization_spaces=A		)
         return text, ids




       def 							UpperCAmelCase__ (  self :    int		):
         pass  # TODO add if relevant




       def 							UpperCAmelCase__ (  self :    Dict		):
         pass  # TODO add if relevant




       def 							UpperCAmelCase__ (  self :    Optional[int]		):
         pass  # TODO add if relevant




       def 							UpperCAmelCase__ (  self :    Union[str, Any]		):
         __snake_case:						Dict   =						self.get_tokenizer()

         # Testing tokenization
         __snake_case:						List[str]   =						"""こんにちは、世界。　こんばんは、㔺界。"""
         __snake_case:						Optional[int]   =						["""こん""", """にちは""", """、""", """世界""", """。""", """<SP>""", """こん""", """ばんは""", """、""", """㔺界""", """。"""]
         __snake_case:						Any   =						tokenizer.tokenize(A		)
         self.assertListEqual(A							,				A		)

         # Testing conversion to ids without special tokens
         __snake_case:						str   =						[0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
         __snake_case:						str   =						tokenizer.convert_tokens_to_ids(A		)
         self.assertListEqual(A							,				A		)

         # Testing conversion to ids with special tokens
         __snake_case:						Optional[int]   =						tokens + [tokenizer.unk_token]
         __snake_case:						List[str]   =						[0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19]
         __snake_case:						str   =						tokenizer.convert_tokens_to_ids(A		)
         self.assertListEqual(A							,				A		)




       def 							UpperCAmelCase__ (  self :    str		):
         __snake_case:						Union[str, Any]   =						self.get_tokenizer()

         # Testing tokenization
         __snake_case:						Optional[Any]   =						"""こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。"""
         __snake_case:						Optional[Any]   =						"""こんにちは、、、、世界。こんばんは、、、、世界。"""
         __snake_case:						Union[str, Any]   =						tokenizer.encode(A		)
         __snake_case:						List[Any]   =						tokenizer.decode(A		)
         self.assertEqual(A							,				A		)




       @slow
       def 							UpperCAmelCase__ (  self :    Any		):
         __snake_case:						Dict   =						self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""		)

         # Testing tokenization
         __snake_case:						Any   =						"""こんにちは、世界。"""
         __snake_case:						Tuple   =						"""こんばんは、㔺界。😀"""
         __snake_case:						Optional[Any]   =						"""こんにちは、世界。こんばんは、世界。😀"""
         __snake_case:						int   =						tokenizer.encode(prefix_text + input_text		)
         __snake_case:						Union[str, Any]   =						tokenizer.encode(""""""							,				prefix_text=prefix_text + input_text		)
         __snake_case:						Tuple   =						tokenizer.encode(A							,				prefix_text=A		)
         __snake_case:						Union[str, Any]   =						tokenizer.decode(A		)
         __snake_case:						Dict   =						tokenizer.decode(A		)
         __snake_case:						Optional[Any]   =						tokenizer.decode(A		)
         self.assertEqual(A							,				A		)
         self.assertEqual(A							,				A		)
         self.assertEqual(A							,				A		)




       @slow
       def 							UpperCAmelCase__ (  self :    List[str]		):
         __snake_case:						int   =						self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""		)

         # Testing tokenization
         __snake_case:						Optional[int]   =						"""こんにちは、世界。"""
         __snake_case:						Any   =						"""こんばんは、㔺界。😀"""

         __snake_case:						Optional[int]   =						len(tokenizer.encode(A		)		) - 2
         __snake_case:						str   =						len(tokenizer.encode(A		)		) - 2

         __snake_case:						Dict   =						[1] + [0] * (len_prefix + len_text + 1)
         __snake_case:						str   =						[1] * (len_prefix + len_text + 1) + [0]
         __snake_case:						List[Any]   =						[1] + [1] * (len_prefix) + [0] * (len_text + 1)

         __snake_case:						int   =						tokenizer(prefix_text + input_text		).token_type_ids
         __snake_case:						Optional[int]   =						tokenizer(""""""							,				prefix_text=prefix_text + input_text		).token_type_ids
         __snake_case:						Tuple   =						tokenizer(A							,				prefix_text=A		).token_type_ids
         self.assertListEqual(A							,				A		)
         self.assertListEqual(A							,				A		)
         self.assertListEqual(A							,				A		)




       @slow
       def 							UpperCAmelCase__ (  self :    Dict		):
         __snake_case:						Dict   =						self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""		)

         __snake_case:						int   =						tokenizer.encode("""あンいワ"""		)
         __snake_case:						Optional[int]   =						tokenizer.encode(""""""							,				prefix_text="""あンいワ"""		)
         __snake_case:						List[Any]   =						tokenizer.encode("""いワ"""							,				prefix_text="""あン"""		)

         self.assertEqual(tokenizer.decode(A		)							,				tokenizer.decode(A		)		)
         self.assertEqual(tokenizer.decode(A		)							,				tokenizer.decode(A		)		)
         self.assertNotEqual(A							,				A		)
         self.assertNotEqual(A							,				A		)
         self.assertEqual(x_token_a[1]							,				x_token_a[-1]		)  # SEG token
         self.assertEqual(x_token_a[1]							,				x_token_a[3]		)  # SEG token




       @slow
       def 							UpperCAmelCase__ (  self :    int		):
         __snake_case:						List[str]   =						self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""		)

         __snake_case:						Union[str, Any]   =						[["""武田信玄""", """は、"""], ["""織田信長""", """の配下の、"""]]
         __snake_case:						Optional[int]   =						tokenizer(A							,				padding=A		)
         __snake_case:						int   =						tokenizer.batch_encode_plus(A							,				padding=A		)

         # fmt: off
         __snake_case:						List[str]   =						[[35_993, 8_640, 25_948, 35_998, 30_647, 35_675, 35_999, 35_999], [35_993, 10_382, 9_868, 35_998, 30_646, 9_459, 30_646, 35_675]]
         __snake_case:						int   =						[[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]]
         __snake_case:						Dict   =						[[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
         # fmt: on
         self.assertListEqual(x_token.input_ids							,				A		)
         self.assertListEqual(x_token.token_type_ids							,				A		)
         self.assertListEqual(x_token.attention_mask							,				A		)
         self.assertListEqual(x_token_a.input_ids							,				A		)
         self.assertListEqual(x_token_a.token_type_ids							,				A		)
         self.assertListEqual(x_token_a.attention_mask							,				A		)




       def 							UpperCAmelCase__ (  self :    Union[str, Any]		):
         # Intentionally convert some words to accommodate character fluctuations unique to Japanese
         pass






       def 							UpperCAmelCase__ (  self :    List[str]		):
         # tokenizer has no padding token
         pass






