




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							(   __lowerCAmelCase		):

     def 					a__	(  self				)						->							List[str]:
           _A							:     Tuple			=						tempfile.mkdtemp()
           _A							:     str			=						8

           # DPR tok
           _A							:     List[Any]			=						[
               """[UNK]""",
               """[CLS]""",
               """[SEP]""",
               """[PAD]""",
               """[MASK]""",
               """want""",
               """##want""",
               """##ed""",
               """wa""",
               """un""",
               """runn""",
               """##ing""",
               """,""",
               """low""",
               """lowest""",
           ]
           _A							:     List[str]			=						os.path.join(self.tmpdirname		,     """dpr_tokenizer"""				)
           os.makedirs(lowerCAmelCase_		,     exist_ok=lowerCAmelCase_				)
           _A							:     Union[str, Any]			=						os.path.join(lowerCAmelCase_		,     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
           _A							:     int			=						[
               """l""",
               """o""",
               """w""",
               """e""",
               """r""",
               """s""",
               """t""",
               """i""",
               """d""",
               """n""",
               """\u0120""",
               """\u0120l""",
               """\u0120n""",
               """\u0120lo""",
               """\u0120low""",
               """er""",
               """\u0120lowest""",
               """\u0120newer""",
               """\u0120wider""",
               """<unk>""",
           ]
           _A							:     List[Any]			=						dict(zip(lowerCAmelCase_		,     range(len(lowerCAmelCase_				)				)				)				)
           _A							:     str			=						["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
           _A							:     int			=						{"""unk_token""": """<unk>"""}

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

     def 					a__	(  self				)						->							DPRQuestionEncoderTokenizer:
           return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname		,     """dpr_tokenizer"""				)				)

     def 					a__	(  self				)						->							BartTokenizer:
           return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname		,     """bart_tokenizer"""				)				)

     def 					a__	(  self				)						->							Tuple:
           shutil.rmtree(self.tmpdirname				)

     @require_tokenizers
     def 					a__	(  self				)						->							Any:
           _A							:     Union[str, Any]			=						os.path.join(self.tmpdirname		,     """rag_tokenizer"""				)
           _A							:     Union[str, Any]			=						RagConfig(question_encoder=DPRConfig().to_dict()		,     generator=BartConfig().to_dict()				)
           _A							:     Union[str, Any]			=						RagTokenizer(question_encoder=self.get_dpr_tokenizer()		,     generator=self.get_bart_tokenizer()				)
           rag_config.save_pretrained(lowerCAmelCase_				)
           rag_tokenizer.save_pretrained(lowerCAmelCase_				)
           _A							:     Dict			=						RagTokenizer.from_pretrained(lowerCAmelCase_		,     config=lowerCAmelCase_				)
           self.assertIsInstance(new_rag_tokenizer.question_encoder		,     lowerCAmelCase_				)
           self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab()		,     rag_tokenizer.question_encoder.get_vocab()				)
           self.assertIsInstance(new_rag_tokenizer.generator		,     lowerCAmelCase_				)
           self.assertEqual(new_rag_tokenizer.generator.get_vocab()		,     rag_tokenizer.generator.get_vocab()				)

     @slow
     def 					a__	(  self				)						->							str:
           _A							:     Tuple			=						RagTokenizer.from_pretrained("""facebook/rag-token-nq"""				)
           _A							:     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""",
           ]
           _A							:     int			=						tokenizer(lowerCAmelCase_				)
           self.assertIsNotNone(lowerCAmelCase_				)



     @slow
     def 					a__	(  self				)						->							Optional[int]:
           _A							:     List[Any]			=						RagTokenizer.from_pretrained("""facebook/rag-sequence-nq"""				)
           _A							:     str			=						[
               """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""",
           ]
           _A							:     List[Any]			=						tokenizer(lowerCAmelCase_				)
           self.assertIsNotNone(lowerCAmelCase_				)


from unittest.mock import patch

import pyspark

from datasets.packaged_modules.spark.spark import (
    Spark,
    SparkExamplesIterable,
    _generate_iterable_examples,
)

from ..utils import (
    require_dill_gt_0_3_2,
    require_not_windows,
)






def  snake_case  (       snake_case__			:Union[str, Any]   ,	snake_case__			:Dict)						->   Any:
       _A        =  []
       for part_id in partition_order:
              _A        =  df.where(F'''SPARK_PARTITION_ID() = {part_id}''').collect()
              for row_idx, row in enumerate(snake_case__):
                     expected_row_ids_and_row_dicts.append((F'''{part_id}_{row_idx}''', row.asDict()))
       return expected_row_ids_and_row_dicts






@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   Optional[Any]:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(100).repartition(1)
       _A        =  Spark(snake_case__)
       # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means
       # that each partition can hold 2 rows.
       spark_builder._repartition_df_if_needed(max_shard_size=16)
       # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions.
       assert spark_builder.df.rdd.getNumPartitions() == 50






@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   Union[str, Any]:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(10).repartition(2)
       _A        =  [1, 0]
       _A        =  _generate_iterable_examples(snake_case__   ,	snake_case__)  # Reverse the partitions.
       _A        =  _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__   ,	snake_case__)

       for i, (row_id, row_dict) in enumerate(generate_fn()):
              _A   ,  _A        =  expected_row_ids_and_row_dicts[i]
              assert row_id == expected_row_id
              assert row_dict == expected_row_dict






@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   int:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(10).repartition(1)
       _A        =  SparkExamplesIterable(snake_case__)
       assert it.n_shards == 1
       for i, (row_id, row_dict) in enumerate(snake_case__):
              assert row_id == F'''0_{i}'''
              assert row_dict == {"id": i}






@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   Union[str, Any]:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(30).repartition(3)
       # Mock the generator so that shuffle reverses the partition indices.
       with patch("""numpy.random.Generator""") as generator_mock:
              _A        =  lambda snake_case__: x.reverse()
              _A        =  _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__   ,	[2, 1, 0])

              _A        =  SparkExamplesIterable(snake_case__).shuffle_data_sources(snake_case__)
              assert shuffled_it.n_shards == 3
              for i, (row_id, row_dict) in enumerate(snake_case__):
                     _A   ,  _A        =  expected_row_ids_and_row_dicts[i]
                     assert row_id == expected_row_id
                     assert row_dict == expected_row_dict






@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   List[str]:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(20).repartition(4)

       # Partitions 0 and 2
       _A        =  SparkExamplesIterable(snake_case__).shard_data_sources(worker_id=0   ,	num_workers=2)
       assert shard_it_a.n_shards == 2
       _A        =  _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__   ,	[0, 2])
       for i, (row_id, row_dict) in enumerate(snake_case__):
              _A   ,  _A        =  expected_row_ids_and_row_dicts_a[i]
              assert row_id == expected_row_id
              assert row_dict == expected_row_dict

       # Partitions 1 and 3
       _A        =  SparkExamplesIterable(snake_case__).shard_data_sources(worker_id=1   ,	num_workers=2)
       assert shard_it_a.n_shards == 2
       _A        =  _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__   ,	[1, 3])
       for i, (row_id, row_dict) in enumerate(snake_case__):
              _A   ,  _A        =  expected_row_ids_and_row_dicts_a[i]
              assert row_id == expected_row_id
              assert row_dict == expected_row_dict







@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   Tuple:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(100).repartition(1)
       _A        =  Spark(snake_case__)
       # Choose a small max_shard_size for maximum partitioning.
       spark_builder._repartition_df_if_needed(max_shard_size=1)
       # The new number of partitions should not be greater than the number of rows.
       assert spark_builder.df.rdd.getNumPartitions() == 100




