






import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer


snake_case__   :						Optional[int]													=   logging.get_logger(__name__)

snake_case__   :						Optional[Any]													=   {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

snake_case__   :						Any													=   {
    """vocab_file""": {
        """bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt""",
        """bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt""",
        """bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/vocab.txt""",
        """bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/vocab.txt""",
        """bert-base-multilingual-uncased""": (
            """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt"""
        ),
        """bert-base-multilingual-cased""": """https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt""",
        """bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt""",
        """bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt""",
        """bert-large-uncased-whole-word-masking""": (
            """https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt"""
        ),
        """bert-large-cased-whole-word-masking""": (
            """https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt"""
        ),
        """bert-large-uncased-whole-word-masking-finetuned-squad""": (
            """https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"""
        ),
        """bert-large-cased-whole-word-masking-finetuned-squad""": (
            """https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"""
        ),
        """bert-base-cased-finetuned-mrpc""": (
            """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt"""
        ),
        """bert-base-german-dbmdz-cased""": """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt""",
        """bert-base-german-dbmdz-uncased""": (
            """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt"""
        ),
        """TurkuNLP/bert-base-finnish-cased-v1""": (
            """https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt"""
        ),
        """TurkuNLP/bert-base-finnish-uncased-v1""": (
            """https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt"""
        ),
        """wietsedv/bert-base-dutch-cased""": (
            """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt"""
        ),
    },
    """tokenizer_file""": {
        """bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json""",
        """bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json""",
        """bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json""",
        """bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json""",
        """bert-base-multilingual-uncased""": (
            """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json"""
        ),
        """bert-base-multilingual-cased""": (
            """https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json"""
        ),
        """bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json""",
        """bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json""",
        """bert-large-uncased-whole-word-masking""": (
            """https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json"""
        ),
        """bert-large-cased-whole-word-masking""": (
            """https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json"""
        ),
        """bert-large-uncased-whole-word-masking-finetuned-squad""": (
            """https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"""
        ),
        """bert-large-cased-whole-word-masking-finetuned-squad""": (
            """https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"""
        ),
        """bert-base-cased-finetuned-mrpc""": (
            """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json"""
        ),
        """bert-base-german-dbmdz-cased""": (
            """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json"""
        ),
        """bert-base-german-dbmdz-uncased""": (
            """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json"""
        ),
        """TurkuNLP/bert-base-finnish-cased-v1""": (
            """https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json"""
        ),
        """TurkuNLP/bert-base-finnish-uncased-v1""": (
            """https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json"""
        ),
        """wietsedv/bert-base-dutch-cased""": (
            """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json"""
        ),
    },
}

snake_case__   :						List[str]													=   {
    """bert-base-uncased""": 5_1_2,
    """bert-large-uncased""": 5_1_2,
    """bert-base-cased""": 5_1_2,
    """bert-large-cased""": 5_1_2,
    """bert-base-multilingual-uncased""": 5_1_2,
    """bert-base-multilingual-cased""": 5_1_2,
    """bert-base-chinese""": 5_1_2,
    """bert-base-german-cased""": 5_1_2,
    """bert-large-uncased-whole-word-masking""": 5_1_2,
    """bert-large-cased-whole-word-masking""": 5_1_2,
    """bert-large-uncased-whole-word-masking-finetuned-squad""": 5_1_2,
    """bert-large-cased-whole-word-masking-finetuned-squad""": 5_1_2,
    """bert-base-cased-finetuned-mrpc""": 5_1_2,
    """bert-base-german-dbmdz-cased""": 5_1_2,
    """bert-base-german-dbmdz-uncased""": 5_1_2,
    """TurkuNLP/bert-base-finnish-cased-v1""": 5_1_2,
    """TurkuNLP/bert-base-finnish-uncased-v1""": 5_1_2,
    """wietsedv/bert-base-dutch-cased""": 5_1_2,
}

snake_case__   :						Tuple													=   {
    """bert-base-uncased""": {"""do_lower_case""": True},
    """bert-large-uncased""": {"""do_lower_case""": True},
    """bert-base-cased""": {"""do_lower_case""": False},
    """bert-large-cased""": {"""do_lower_case""": False},
    """bert-base-multilingual-uncased""": {"""do_lower_case""": True},
    """bert-base-multilingual-cased""": {"""do_lower_case""": False},
    """bert-base-chinese""": {"""do_lower_case""": False},
    """bert-base-german-cased""": {"""do_lower_case""": False},
    """bert-large-uncased-whole-word-masking""": {"""do_lower_case""": True},
    """bert-large-cased-whole-word-masking""": {"""do_lower_case""": False},
    """bert-large-uncased-whole-word-masking-finetuned-squad""": {"""do_lower_case""": True},
    """bert-large-cased-whole-word-masking-finetuned-squad""": {"""do_lower_case""": False},
    """bert-base-cased-finetuned-mrpc""": {"""do_lower_case""": False},
    """bert-base-german-dbmdz-cased""": {"""do_lower_case""": False},
    """bert-base-german-dbmdz-uncased""": {"""do_lower_case""": True},
    """TurkuNLP/bert-base-finnish-cased-v1""": {"""do_lower_case""": False},
    """TurkuNLP/bert-base-finnish-uncased-v1""": {"""do_lower_case""": True},
    """wietsedv/bert-base-dutch-cased""": {"""do_lower_case""": False},
}


class     _a							(	UpperCAmelCase__     ):






  """simple docstring"""





  A_						       = VOCAB_FILES_NAMES
  A_						       = PRETRAINED_VOCAB_FILES_MAP
  A_						       = PRETRAINED_INIT_CONFIGURATION
  A_						       = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  A_						       = BertTokenizer




  def __init__(  self		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=True		,		_UpperCAmelCase="[UNK]"		,		_UpperCAmelCase="[SEP]"		,		_UpperCAmelCase="[PAD]"		,		_UpperCAmelCase="[CLS]"		,		_UpperCAmelCase="[MASK]"		,		_UpperCAmelCase=True		,		_UpperCAmelCase=None		,		**_UpperCAmelCase		,		)      ->			List[Any]:
     super().__init__(
         _UpperCAmelCase		,		tokenizer_file=_UpperCAmelCase		,		do_lower_case=_UpperCAmelCase		,		unk_token=_UpperCAmelCase		,		sep_token=_UpperCAmelCase		,		pad_token=_UpperCAmelCase		,		cls_token=_UpperCAmelCase		,		mask_token=_UpperCAmelCase		,		tokenize_chinese_chars=_UpperCAmelCase		,		strip_accents=_UpperCAmelCase		,		**_UpperCAmelCase		,		)

     UpperCamelCase_						=  json.loads(self.backend_tokenizer.normalizer.__getstate__()			)
     if (
         normalizer_state.get('lowercase'		,		_UpperCAmelCase			) != do_lower_case
         or normalizer_state.get('strip_accents'		,		_UpperCAmelCase			) != strip_accents
         or normalizer_state.get('handle_chinese_chars'		,		_UpperCAmelCase			) != tokenize_chinese_chars
     ):
        UpperCamelCase_						=  getattr(_UpperCAmelCase		,		normalizer_state.pop('type'			)			)
        UpperCamelCase_						=  do_lower_case
        UpperCamelCase_						=  strip_accents
        UpperCamelCase_						=  tokenize_chinese_chars
        UpperCamelCase_						=  normalizer_class(**_UpperCAmelCase			)

     UpperCamelCase_						=  do_lower_case




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase=None			)      ->			Union[str, Any]:
     UpperCamelCase_						=  [self.cls_token_id] + token_ids_a + [self.sep_token_id]

     if token_ids_a:
        output += token_ids_a + [self.sep_token_id]

     return output




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase = None			)      ->			List[int]:
     UpperCamelCase_						=  [self.sep_token_id]
     UpperCamelCase_						=  [self.cls_token_id]
     if token_ids_a is None:
        return len(cls + token_ids_a + sep			) * [0]
     return len(cls + token_ids_a + sep			) * [0] + len(token_ids_a + sep			) * [1]




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase = None			)      ->			Tuple[str]:
     UpperCamelCase_						=  self._tokenizer.model.save(_UpperCAmelCase		,		name=_UpperCAmelCase			)
     return tuple(_UpperCAmelCase			)













import os
import tempfile
from functools import partial
from unittest import TestCase
from unittest.mock import patch

import datasets
import datasets.config

from .utils import require_beam


class     _a							(	datasets.BeamBasedBuilder     ):






  """simple docstring"""





  def  _UpperCAmelCase  (  self			)      ->			List[str]:
     return datasets.DatasetInfo(
         features=datasets.Features({'content': datasets.Value('string'			)}			)		,		supervised_keys=_UpperCAmelCase		,		)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Optional[Any]:
     return [datasets.SplitGenerator(name=datasets.Split.TRAIN		,		gen_kwargs={'examples': get_test_dummy_examples()}			)]




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Tuple:
     import apache_beam as beam

     return pipeline | "Load Examples" >> beam.Create(_UpperCAmelCase			)




class     _a							(	datasets.BeamBasedBuilder     ):






  """simple docstring"""





  def  _UpperCAmelCase  (  self			)      ->			Any:
     return datasets.DatasetInfo(
         features=datasets.Features({'a': datasets.Sequence({'b': datasets.Value('string'			)}			)}			)		,		supervised_keys=_UpperCAmelCase		,		)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Tuple:
     return [
         datasets.SplitGenerator(name=datasets.Split.TRAIN		,		gen_kwargs={'examples': get_test_nested_examples()}			)
     ]




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Union[str, Any]:
     import apache_beam as beam

     return pipeline | "Load Examples" >> beam.Create(_UpperCAmelCase			)






def      _snake_case     ():
   return [(i, {"content": content}) for i, content in enumerate(['foo', 'bar', 'foobar'])]






def      _snake_case     ():
   return [(i, {"a": {"b": [content]}}) for i, content in enumerate(['foo', 'bar', 'foobar'])]


class     _a							(	UpperCAmelCase__     ):






  """simple docstring"""





  @require_beam
  def  _UpperCAmelCase  (  self			)      ->			Dict:
     UpperCamelCase_						=  len(get_test_dummy_examples()			)
     with tempfile.TemporaryDirectory() as tmp_cache_dir:
        UpperCamelCase_						=  DummyBeamDataset(cache_dir=_UpperCAmelCase		,		beam_runner='DirectRunner'			)
        builder.download_and_prepare()
        self.assertTrue(
            os.path.exists(
                os.path.join(_UpperCAmelCase		,		builder.name		,		'default'		,		'0.0.0'		,		f"""{builder.name}-train.arrow"""			)			)			)
        self.assertDictEqual(builder.info.features		,		datasets.Features({'content': datasets.Value('string'			)}			)			)
        UpperCamelCase_						=  builder.as_dataset()
        self.assertEqual(dset['train'].num_rows		,		_UpperCAmelCase			)
        self.assertEqual(dset['train'].info.splits['train'].num_examples		,		_UpperCAmelCase			)
        self.assertDictEqual(dset['train'][0]		,		get_test_dummy_examples()[0][1]			)
        self.assertDictEqual(
            dset['train'][expected_num_examples - 1]		,		get_test_dummy_examples()[expected_num_examples - 1][1]			)
        self.assertTrue(
            os.path.exists(os.path.join(_UpperCAmelCase		,		builder.name		,		'default'		,		'0.0.0'		,		'dataset_info.json'			)			)			)
        del dset




  @require_beam
  def  _UpperCAmelCase  (  self			)      ->			List[str]:
     import apache_beam as beam

     UpperCamelCase_						=  beam.io.parquetio.WriteToParquet

     UpperCamelCase_						=  len(get_test_dummy_examples()			)
     with tempfile.TemporaryDirectory() as tmp_cache_dir:
        UpperCamelCase_						=  DummyBeamDataset(cache_dir=_UpperCAmelCase		,		beam_runner='DirectRunner'			)
        with patch('apache_beam.io.parquetio.WriteToParquet'			) as write_parquet_mock:
           UpperCamelCase_						=  partial(_UpperCAmelCase		,		num_shards=2			)
           builder.download_and_prepare()
        self.assertTrue(
            os.path.exists(
                os.path.join(
                    _UpperCAmelCase		,		builder.name		,		'default'		,		'0.0.0'		,		f"""{builder.name}-train-00000-of-00002.arrow"""			)			)			)
        self.assertTrue(
            os.path.exists(
                os.path.join(
                    _UpperCAmelCase		,		builder.name		,		'default'		,		'0.0.0'		,		f"""{builder.name}-train-00000-of-00002.arrow"""			)			)			)
        self.assertDictEqual(builder.info.features		,		datasets.Features({'content': datasets.Value('string'			)}			)			)
        UpperCamelCase_						=  builder.as_dataset()
        self.assertEqual(dset['train'].num_rows		,		_UpperCAmelCase			)
        self.assertEqual(dset['train'].info.splits['train'].num_examples		,		_UpperCAmelCase			)
        # Order is not preserved when sharding, so we just check that all the elements are there
        self.assertListEqual(sorted(dset['train']['content']			)		,		sorted(['foo', 'bar', 'foobar']			)			)
        self.assertTrue(
            os.path.exists(os.path.join(_UpperCAmelCase		,		builder.name		,		'default'		,		'0.0.0'		,		'dataset_info.json'			)			)			)
        del dset




  @require_beam
  def  _UpperCAmelCase  (  self			)      ->			Any:
     with tempfile.TemporaryDirectory() as tmp_cache_dir:
        UpperCamelCase_						=  DummyBeamDataset(cache_dir=_UpperCAmelCase			)
        self.assertRaises(datasets.builder.MissingBeamOptions		,		builder.download_and_prepare			)




  @require_beam
  def  _UpperCAmelCase  (  self			)      ->			Union[str, Any]:
     UpperCamelCase_						=  len(get_test_nested_examples()			)
     with tempfile.TemporaryDirectory() as tmp_cache_dir:
        UpperCamelCase_						=  NestedBeamDataset(cache_dir=_UpperCAmelCase		,		beam_runner='DirectRunner'			)
        builder.download_and_prepare()
        self.assertTrue(
            os.path.exists(
                os.path.join(_UpperCAmelCase		,		builder.name		,		'default'		,		'0.0.0'		,		f"""{builder.name}-train.arrow"""			)			)			)
        self.assertDictEqual(
            builder.info.features		,		datasets.Features({'a': datasets.Sequence({'b': datasets.Value('string'			)}			)}			)			)
        UpperCamelCase_						=  builder.as_dataset()
        self.assertEqual(dset['train'].num_rows		,		_UpperCAmelCase			)
        self.assertEqual(dset['train'].info.splits['train'].num_examples		,		_UpperCAmelCase			)
        self.assertDictEqual(dset['train'][0]		,		get_test_nested_examples()[0][1]			)
        self.assertDictEqual(
            dset['train'][expected_num_examples - 1]		,		get_test_nested_examples()[expected_num_examples - 1][1]			)
        self.assertTrue(
            os.path.exists(os.path.join(_UpperCAmelCase		,		builder.name		,		'default'		,		'0.0.0'		,		'dataset_info.json'			)			)			)
        del dset





