




"""simple docstring"""


import json
import os
import shutil
import tempfile
from unittest import TestCase

from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow
from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available


if is_torch_available() and is_datasets_available() and is_faiss_available():
     from transformers.models.rag.configuration_rag import RagConfig
     from transformers.models.rag.tokenization_rag import RagTokenizer






@require_faiss
@require_torch
class  lowercase(					lowercase__			):







 '''simple docstring'''





 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   _snake_case							:		Any								=  tempfile.mkdtemp()
   _snake_case							:		Tuple								=  8

   # DPR tok
   _snake_case							:		Optional[int]								=  [
       """[UNK]""",
       """[CLS]""",
       """[SEP]""",
       """[PAD]""",
       """[MASK]""",
       """want""",
       """##want""",
       """##ed""",
       """wa""",
       """un""",
       """runn""",
       """##ing""",
       """,""",
       """low""",
       """lowest""",
   ]
   _snake_case							:		List[str]								=  os.path.join(self.tmpdirname,				"""dpr_tokenizer"""		)
   os.makedirs(_UpperCamelCase,				exist_ok=_UpperCamelCase		)
   _snake_case							:		List[Any]								=  os.path.join(_UpperCamelCase,				DPR_VOCAB_FILES_NAMES["""vocab_file"""]		)
   with open(self.vocab_file,				"""w""",				encoding="""utf-8"""		) as vocab_writer:
     vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]		)		)

   # BART tok
   _snake_case							:		Dict								=  [
       """l""",
       """o""",
       """w""",
       """e""",
       """r""",
       """s""",
       """t""",
       """i""",
       """d""",
       """n""",
       """\u0120""",
       """\u0120l""",
       """\u0120n""",
       """\u0120lo""",
       """\u0120low""",
       """er""",
       """\u0120lowest""",
       """\u0120newer""",
       """\u0120wider""",
       """<unk>""",
   ]
   _snake_case							:		Tuple								=  dict(zip(_UpperCamelCase,				range(len(_UpperCamelCase		)		)		)		)
   _snake_case							:		Optional[Any]								=  ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
   _snake_case							:		Union[str, Any]								=  {"""unk_token""": """<unk>"""}

   _snake_case							:		List[Any]								=  os.path.join(self.tmpdirname,				"""bart_tokenizer"""		)
   os.makedirs(_UpperCamelCase,				exist_ok=_UpperCamelCase		)
   _snake_case							:		List[str]								=  os.path.join(_UpperCamelCase,				BART_VOCAB_FILES_NAMES["""vocab_file"""]		)
   _snake_case							:		Tuple								=  os.path.join(_UpperCamelCase,				BART_VOCAB_FILES_NAMES["""merges_file"""]		)
   with open(self.vocab_file,				"""w""",				encoding="""utf-8"""		) as fp:
     fp.write(json.dumps(_UpperCamelCase		) + """\n"""		)
   with open(self.merges_file,				"""w""",				encoding="""utf-8"""		) as fp:
     fp.write("""\n""".join(_UpperCamelCase		)		)


 def 			UpperCamelCase_       (    self:		Tuple		):




   '''simple docstring'''



   return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname,				"""dpr_tokenizer"""		)		)


 def 			UpperCamelCase_       (    self:		Dict		):




   '''simple docstring'''



   return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname,				"""bart_tokenizer"""		)		)


 def 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



   shutil.rmtree(self.tmpdirname		)


 @require_tokenizers
 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   _snake_case							:		Tuple								=  os.path.join(self.tmpdirname,				"""rag_tokenizer"""		)
   _snake_case							:		Optional[int]								=  RagConfig(question_encoder=DPRConfig().to_dict(),				generator=BartConfig().to_dict()		)
   _snake_case							:		List[Any]								=  RagTokenizer(question_encoder=self.get_dpr_tokenizer(),				generator=self.get_bart_tokenizer()		)
   rag_config.save_pretrained(_UpperCamelCase		)
   rag_tokenizer.save_pretrained(_UpperCamelCase		)
   _snake_case							:		Union[str, Any]								=  RagTokenizer.from_pretrained(_UpperCamelCase,				config=_UpperCamelCase		)
   self.assertIsInstance(new_rag_tokenizer.question_encoder,				_UpperCamelCase		)
   self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab(),				rag_tokenizer.question_encoder.get_vocab()		)
   self.assertIsInstance(new_rag_tokenizer.generator,				_UpperCamelCase		)
   self.assertEqual(new_rag_tokenizer.generator.get_vocab(),				rag_tokenizer.generator.get_vocab()		)


 @slow
 def 			UpperCamelCase_       (    self:		Any		):




   '''simple docstring'''



   _snake_case							:		List[Any]								=  RagTokenizer.from_pretrained("""facebook/rag-token-nq"""		)
   _snake_case							:		Union[str, Any]								=  [
       """who got the first nobel prize in physics""",
       """when is the next deadpool movie being released""",
       """which mode is used for short wave broadcast service""",
       """who is the owner of reading football club""",
       """when is the next scandal episode coming out""",
       """when is the last time the philadelphia won the superbowl""",
       """what is the most current adobe flash player version""",
       """how many episodes are there in dragon ball z""",
       """what is the first step in the evolution of the eye""",
       """where is gall bladder situated in human body""",
       """what is the main mineral in lithium batteries""",
       """who is the president of usa right now""",
       """where do the greasers live in the outsiders""",
       """panda is a national animal of which country""",
       """what is the name of manchester united stadium""",
   ]
   _snake_case							:		Tuple								=  tokenizer(_UpperCamelCase		)
   self.assertIsNotNone(_UpperCamelCase		)


 @slow
 def 			UpperCamelCase_       (    self:		Dict		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  RagTokenizer.from_pretrained("""facebook/rag-sequence-nq"""		)
   _snake_case							:		Optional[Any]								=  [
       """who got the first nobel prize in physics""",
       """when is the next deadpool movie being released""",
       """which mode is used for short wave broadcast service""",
       """who is the owner of reading football club""",
       """when is the next scandal episode coming out""",
       """when is the last time the philadelphia won the superbowl""",
       """what is the most current adobe flash player version""",
       """how many episodes are there in dragon ball z""",
       """what is the first step in the evolution of the eye""",
       """where is gall bladder situated in human body""",
       """what is the main mineral in lithium batteries""",
       """who is the president of usa right now""",
       """where do the greasers live in the outsiders""",
       """panda is a national animal of which country""",
       """what is the name of manchester united stadium""",
   ]
   _snake_case							:		str								=  tokenizer(_UpperCamelCase		)
   self.assertIsNotNone(_UpperCamelCase		)









"""simple docstring"""


import unicodedata
from dataclasses import dataclass
from typing import Optional, Union

import numpy as np

from transformers.data.data_collator import DataCollatorMixin
from transformers.file_utils import PaddingStrategy
from transformers.tokenization_utils_base import PreTrainedTokenizerBase


def  UpperCAmelCase__	(snake_case__							: Optional[int]		,       snake_case__							: Any		,       snake_case__							: List[str]		,       snake_case__							: int   ):
  """simple docstring"""

  if isinstance(snake_case__		,       snake_case__   ):
    _snake_case							:		List[Any]								=  np.full((len(snake_case__   ), sequence_length, 2)		,       snake_case__   )
  else:
    _snake_case							:		Any								=  np.full((len(snake_case__   ), sequence_length)		,       snake_case__   )

  for i, tensor in enumerate(snake_case__   ):
    if padding_side == "right":
      if isinstance(snake_case__		,       snake_case__   ):
        _snake_case							:		Dict								=  tensor[:sequence_length]
      else:
        _snake_case							:		List[Any]								=  tensor[:sequence_length]
    else:
      if isinstance(snake_case__		,       snake_case__   ):
        _snake_case							:		str								=  tensor[:sequence_length]
      else:
        _snake_case							:		Tuple								=  tensor[:sequence_length]

  return out_tensor.tolist()


def  UpperCAmelCase__	(snake_case__							: Optional[int]   ):
  """simple docstring"""

  _snake_case							:		str								=  ord(snake_case__   )
  if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 1_23 and cp <= 1_26):
    return True
  _snake_case							:		Union[str, Any]								=  unicodedata.category(snake_case__   )
  if cat.startswith("""P"""   ):
    return True
  return False






@dataclass
class  lowercase(					__a			):







 '''simple docstring'''





 lowercase__			 = 42
 lowercase__			 = True
 lowercase__			 = None
 lowercase__			 = None
 lowercase__			 = -1_00
 lowercase__			 = "pt"


 def 			UpperCamelCase_       (    self:		Any,				a_:		Union[str, Any]		):




   '''simple docstring'''



   import torch

   _snake_case							:		Optional[Any]								=  """label""" if """label""" in features[0].keys() else """labels"""
   _snake_case							:		str								=  [feature[label_name] for feature in features] if label_name in features[0].keys() else None
   _snake_case							:		Any								=  self.tokenizer.pad(
       a_,				padding=self.padding,				max_length=self.max_length,				pad_to_multiple_of=self.pad_to_multiple_of,				return_tensors="""pt""" if labels is None else None,				)

   if labels is None:
     return batch

   _snake_case							:		Optional[int]								=  torch.tensor(batch["""entity_ids"""]		).shape[1]
   _snake_case							:		Any								=  self.tokenizer.padding_side
   if padding_side == "right":
     _snake_case							:		Optional[int]								=  [
         list(a_		) + [self.label_pad_token_id] * (sequence_length - len(a_		)) for label in labels
     ]
   else:
     _snake_case							:		Union[str, Any]								=  [
         [self.label_pad_token_id] * (sequence_length - len(a_		)) + list(a_		) for label in labels
     ]

   _snake_case							:		List[Any]								=  [feature["""ner_tags"""] for feature in features]
   _snake_case							:		str								=  padding_tensor(a_,				-1,				a_,				a_		)
   _snake_case							:		Any								=  [feature["""original_entity_spans"""] for feature in features]
   _snake_case							:		int								=  padding_tensor(a_,				(-1, -1),				a_,				a_		)
   _snake_case							:		str								=  {k: torch.tensor(a_,				dtype=torch.intaa		) for k, v in batch.items()}

   return batch


