





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


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






def       _A  (      lowerCamelCase							, lowerCamelCase=100							, lowerCamelCase=" "   ):
   a__	:						Union[str, Any]      		=  text.split(lowerCamelCase   )
   return [character.join(text[i : i + n]   ).strip() for i in range(0							, len(lowerCamelCase   )							, lowerCamelCase   )]






def       _A  (      lowerCamelCase   ):
   a__		,     a__	:						Dict      		=  [], []
   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       _A  (      lowerCamelCase							, lowerCamelCase							, lowerCamelCase   ):
   a__	:						Dict      		=  ctx_tokenizer(
       documents["title"]							, documents["text"]							, truncation=lowerCamelCase							, padding="longest"							, return_tensors="pt"   )["input_ids"]
   a__	:						Optional[Any]      		=  ctx_encoder(input_ids.to(device=lowerCamelCase   )							, return_dict=lowerCamelCase   ).pooler_output
   return {"embeddings": embeddings.detach().cpu().numpy()}






def       _A  (      lowerCamelCase							, lowerCamelCase							, lowerCamelCase							, ):
   ######################################
   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
   a__	:						List[Any]      		=  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
   a__	:						Tuple      		=  dataset.map(lowerCamelCase							, batched=lowerCamelCase							, num_proc=processing_args.num_proc   )

   # And compute the embeddings
   a__	:						List[Any]      		=  DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name   ).to(device=lowerCamelCase   )
   a__	:						List[Any]      		=  DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name   )
   a__	:						Dict      		=  Features(
       {"text": Value("string"   ), "title": Value("string"   ), "embeddings": Sequence(Value("float32"   )   )}   )  # optional, save as float32 instead of float64 to save space
   a__	:						Optional[Any]      		=  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
   a__	:						Dict      		=  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
   a__	:						Optional[int]      		=  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
   a__	:						Union[str, Any]      		=  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   __lowerCAmelCase			:
   _UpperCamelCase :						str     		=				field(
       default=str(Path(_UpperCamelCase  ).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=_UpperCamelCase		,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(_UpperCamelCase  ).parent / """test_run""" / """dummy-kb"""  )		,metadata={"""help""": """Path to a directory where the dataset passages and the index will be saved"""}		,)







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

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








import subprocess
import sys

from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch







class   __lowerCAmelCase			(					_UpperCamelCase  ):





   @require_torch
   def 	_snake_case ( self      )				->  str:
      """simple docstring"""





      a__	:						Tuple      		=  "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        "

      a__	:						str      		=  "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n        "

      a__	:						Optional[Any]      		=  "\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\")\nsocket.socket = offline_socket\n        "

      # Force fetching the files so that we can use the cache
      a__	:						Tuple      		=  "hf-internal-testing/tiny-random-bert"
      BertConfig.from_pretrained(snake_case      )
      BertModel.from_pretrained(snake_case      )
      BertTokenizer.from_pretrained(snake_case      )
      pipeline(task="fill-mask"					,			model=snake_case      )

      # baseline - just load from_pretrained with normal network
      a__	:						Optional[int]      		=  [sys.executable, "-c", "\n".join([load, run, mock]      )]

      # should succeed
      a__	:						Dict      		=  self.get_env()
      # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
      a__	:						Tuple      		=  "1"
      a__	:						List[Any]      		=  subprocess.run(snake_case					,			env=snake_case					,			check=snake_case					,			capture_output=snake_case      )
      self.assertEqual(result.returncode					,			0					,			result.stderr      )
      self.assertIn("success"					,			result.stdout.decode()      )





   @require_torch
   def 	_snake_case ( self      )				->  List[Any]:
      """simple docstring"""





      a__	:						Tuple      		=  "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        "

      a__	:						Optional[Any]      		=  "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n        "

      a__	:						Tuple      		=  "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\")\nsocket.socket = offline_socket\n        "

      # Force fetching the files so that we can use the cache
      a__	:						List[Any]      		=  "hf-internal-testing/tiny-random-bert"
      BertConfig.from_pretrained(snake_case      )
      BertModel.from_pretrained(snake_case      )
      BertTokenizer.from_pretrained(snake_case      )
      pipeline(task="fill-mask"					,			model=snake_case      )

      # baseline - just load from_pretrained with normal network
      a__	:						Tuple      		=  [sys.executable, "-c", "\n".join([load, run, mock]      )]

      # should succeed
      a__	:						Any      		=  self.get_env()
      a__	:						int      		=  subprocess.run(snake_case					,			env=snake_case					,			check=snake_case					,			capture_output=snake_case      )
      self.assertEqual(result.returncode					,			0					,			result.stderr      )
      self.assertIn("success"					,			result.stdout.decode()      )





   @require_torch
   def 	_snake_case ( self      )				->  Tuple:
      """simple docstring"""





      a__	:						List[Any]      		=  "\nfrom transformers import BertConfig, BertModel, BertTokenizer\n        "

      a__	:						Dict      		=  "\nmname = \"hf-internal-testing/tiny-random-bert-sharded\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint(\"success\")\n        "

      a__	:						int      		=  "\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n        "

      # baseline - just load from_pretrained with normal network
      a__	:						List[Any]      		=  [sys.executable, "-c", "\n".join([load, run]      )]

      # should succeed
      a__	:						str      		=  self.get_env()
      a__	:						List[str]      		=  subprocess.run(snake_case					,			env=snake_case					,			check=snake_case					,			capture_output=snake_case      )
      self.assertEqual(result.returncode					,			0					,			result.stderr      )
      self.assertIn("success"					,			result.stdout.decode()      )

      # next emulate no network
      a__	:						List[Any]      		=  [sys.executable, "-c", "\n".join([load, mock, run]      )]

      # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
      # env["TRANSFORMERS_OFFLINE"] = "0"
      # result = subprocess.run(cmd, env=env, check=False, capture_output=True)
      # self.assertEqual(result.returncode, 1, result.stderr)

      # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
      a__	:						Union[str, Any]      		=  "1"
      a__	:						Tuple      		=  subprocess.run(snake_case					,			env=snake_case					,			check=snake_case					,			capture_output=snake_case      )
      self.assertEqual(result.returncode					,			0					,			result.stderr      )
      self.assertIn("success"					,			result.stdout.decode()      )





   @require_torch
   def 	_snake_case ( self      )				->  Tuple:
      """simple docstring"""





      a__	:						Optional[Any]      		=  "\nfrom transformers import pipeline\n        "
      a__	:						int      		=  "\nmname = \"hf-internal-testing/tiny-random-bert\"\npipe = pipeline(model=mname)\n        "

      a__	:						Dict      		=  "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n        "
      a__	:						List[str]      		=  self.get_env()
      a__	:						Union[str, Any]      		=  "1"
      a__	:						List[str]      		=  [sys.executable, "-c", "\n".join([load, mock, run]      )]
      a__	:						Any      		=  subprocess.run(snake_case					,			env=snake_case					,			check=snake_case					,			capture_output=snake_case      )
      self.assertEqual(result.returncode					,			1					,			result.stderr      )
      self.assertIn(
          "You cannot infer task automatically within `pipeline` when using offline mode"					,			result.stderr.decode().replace("\n"					,			""      )					,			)





   @require_torch
   def 	_snake_case ( self      )				->  Union[str, Any]:
      """simple docstring"""





      a__	:						Any      		=  "\nfrom transformers import AutoModel\n        "
      a__	:						Any      		=  "\nmname = \"hf-internal-testing/test_dynamic_model\"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint(\"success\")\n        "

      # baseline - just load from_pretrained with normal network
      a__	:						List[str]      		=  [sys.executable, "-c", "\n".join([load, run]      )]

      # should succeed
      a__	:						Optional[Any]      		=  self.get_env()
      a__	:						Union[str, Any]      		=  subprocess.run(snake_case					,			env=snake_case					,			check=snake_case					,			capture_output=snake_case      )
      self.assertEqual(result.returncode					,			0					,			result.stderr      )
      self.assertIn("success"					,			result.stdout.decode()      )

      # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
      a__	:						Dict      		=  "1"
      a__	:						Union[str, Any]      		=  subprocess.run(snake_case					,			env=snake_case					,			check=snake_case					,			capture_output=snake_case      )
      self.assertEqual(result.returncode					,			0					,			result.stderr      )
      self.assertIn("success"					,			result.stdout.decode()      )

