



"""simple docstring"""




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      UpperCAmelCase_  (    _UpperCamelCase	,      unittest.TestCase						):
						__SCREAMING_SNAKE_CASE						:       Dict								=			GPTSanJapaneseTokenizer
						__SCREAMING_SNAKE_CASE						:       Optional[int]								=			False
						__SCREAMING_SNAKE_CASE						:       List[str]								=			{'do_clean_text': False, 'add_prefix_space': False}



						def 						snake_case_ (					self					:     Any						):
											super().setUp()

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

											_UpperCAmelCase      :     List[Any]        =   os.path.join(self.tmpdirname					,     VOCAB_FILES_NAMES["vocab_file"]						)
											_UpperCAmelCase      :     Any        =   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 						snake_case_ (					self					:     int					,     **A					:     List[str]						):
											kwargs.update(self.special_tokens_map						)
											return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname					,     **A						)



						def 						snake_case_ (					self					:     int					,     A					:     Any						):
											_UpperCAmelCase      :     Optional[Any]        =   "こんにちは、世界。 \nこんばんは、㔺界。😀"
											_UpperCAmelCase      :     List[Any]        =   "こんにちは、世界。 \nこんばんは、世界。😀"
											return input_text, output_text



						def 						snake_case_ (					self					:     Optional[Any]					,     A					:     str						):
											_UpperCAmelCase      :     str        =   self.get_input_output_texts(A						)
											_UpperCAmelCase      :     List[Any]        =   tokenizer.encode(A					,     add_special_tokens=A						)
											_UpperCAmelCase      :     Union[str, Any]        =   tokenizer.decode(A					,     clean_up_tokenization_spaces=A						)
											return text, ids



						def 						snake_case_ (					self					:     Any						):
											pass  # TODO add if relevant



						def 						snake_case_ (					self					:     Union[str, Any]						):
											pass  # TODO add if relevant



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



						def 						snake_case_ (					self					:     List[str]						):
											_UpperCAmelCase      :     List[Any]        =   self.get_tokenizer()

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

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

											# Testing conversion to ids with special tokens
											_UpperCAmelCase      :     str        =   tokens + [tokenizer.unk_token]
											_UpperCAmelCase      :     Any        =   [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9]
											_UpperCAmelCase      :     str        =   tokenizer.convert_tokens_to_ids(A						)
											self.assertListEqual(A					,     A						)



						def 						snake_case_ (					self					:     Any						):
											_UpperCAmelCase      :     Union[str, Any]        =   self.get_tokenizer()

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



						@slow
						def 						snake_case_ (					self					:     Dict						):
											_UpperCAmelCase      :     List[Any]        =   self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese"						)

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



						@slow
						def 						snake_case_ (					self					:     Optional[Any]						):
											_UpperCAmelCase      :     Dict        =   self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese"						)

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

											_UpperCAmelCase      :     Optional[Any]        =   len(tokenizer.encode(A						)						) - 2
											_UpperCAmelCase      :     List[Any]        =   len(tokenizer.encode(A						)						) - 2

											_UpperCAmelCase      :     List[str]        =   [1] + [0] * (len_prefix + len_text + 1)
											_UpperCAmelCase      :     str        =   [1] * (len_prefix + len_text + 1) + [0]
											_UpperCAmelCase      :     int        =   [1] + [1] * (len_prefix) + [0] * (len_text + 1)

											_UpperCAmelCase      :     Union[str, Any]        =   tokenizer(prefix_text + input_text						).token_type_ids
											_UpperCAmelCase      :     Any        =   tokenizer(""					,     prefix_text=prefix_text + input_text						).token_type_ids
											_UpperCAmelCase      :     List[Any]        =   tokenizer(A					,     prefix_text=A						).token_type_ids
											self.assertListEqual(A					,     A						)
											self.assertListEqual(A					,     A						)
											self.assertListEqual(A					,     A						)



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

											_UpperCAmelCase      :     Dict        =   tokenizer.encode("あンいワ"						)
											_UpperCAmelCase      :     str        =   tokenizer.encode(""					,     prefix_text="あンいワ"						)
											_UpperCAmelCase      :     Dict        =   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 						snake_case_ (					self					:     List[str]						):
											_UpperCAmelCase      :     Optional[Any]        =   self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese"						)

											_UpperCAmelCase      :     Tuple        =   [["武田信玄", "は、"], ["織田信長", "の配下の、"]]
											_UpperCAmelCase      :     Tuple        =   tokenizer(A					,     padding=A						)
											_UpperCAmelCase      :     str        =   tokenizer.batch_encode_plus(A					,     padding=A						)

											# fmt: off
											_UpperCAmelCase      :     str        =   [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]]
											_UpperCAmelCase      :     str        =   [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]]
											_UpperCAmelCase      :     int        =   [[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 						snake_case_ (					self					:     List[Any]						):
											# Intentionally convert some words to accommodate character fluctuations unique to Japanese
											pass



						def 						snake_case_ (					self					:     int						):
											# tokenizer has no padding token
											pass





"""simple docstring"""




import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

from filelock import FileLock

from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available


_lowerCAmelCase    : Any							=							logging.getLogger(__name__)






@dataclass
class      UpperCAmelCase_  :
      __SCREAMING_SNAKE_CASE						:       str
      __SCREAMING_SNAKE_CASE						:       List[str]
      __SCREAMING_SNAKE_CASE						:       Optional[List[str]]







@dataclass
class      UpperCAmelCase_  :
      __SCREAMING_SNAKE_CASE						:       List[int]
      __SCREAMING_SNAKE_CASE						:       List[int]
      __SCREAMING_SNAKE_CASE						:       Optional[List[int]]								=			None
      __SCREAMING_SNAKE_CASE						:       Optional[List[int]]								=			None







class      UpperCAmelCase_  (    _UpperCamelCase						):
      __SCREAMING_SNAKE_CASE						:       Union[str, Any]								=			'train'
      __SCREAMING_SNAKE_CASE						:       Tuple								=			'dev'
      __SCREAMING_SNAKE_CASE						:       Optional[int]								=			'test'







class      UpperCAmelCase_  :



      @staticmethod
      def 						snake_case_ (					A					:     Union[str, Any]					,     A					:     Union[Split, str]						):
           raise NotImplementedError



      @staticmethod
      def 						snake_case_ (					A					:     str						):
           raise NotImplementedError



      @staticmethod
      def 						snake_case_ (					A					:     List[InputExample]					,     A					:     List[str]					,     A					:     int					,     A					:     PreTrainedTokenizer					,     A					:     Optional[int]=False					,     A					:     List[str]="[CLS]"					,     A					:     List[Any]=1					,     A					:     str="[SEP]"					,     A					:     int=False					,     A					:     int=False					,     A					:     Any=0					,     A					:     List[str]=0					,     A					:     Dict=-1_0_0					,     A					:     str=0					,     A					:     Optional[Any]=True					,     ):
           _UpperCAmelCase      :     Dict        =   {label: i for i, label in enumerate(A						)}

           _UpperCAmelCase      :     str        =   []
           for ex_index, example in enumerate(A						):
                if ex_index % 1_0_0_0_0 == 0:
                     logger.info("Writing example %d of %d"					,     A					,     len(A						)						)

                _UpperCAmelCase      :     int        =   []
                _UpperCAmelCase      :     List[str]        =   []
                for word, label in zip(example.words					,     example.labels						):
                     _UpperCAmelCase      :     str        =   tokenizer.tokenize(A						)

                     # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
                     if len(A						) > 0:
                          tokens.extend(A						)
                          # Use the real label id for the first token of the word, and padding ids for the remaining tokens
                          label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(A						) - 1)						)

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
                _UpperCAmelCase      :     List[str]        =   tokenizer.num_special_tokens_to_add()
                if len(A						) > max_seq_length - special_tokens_count:
                     _UpperCAmelCase      :     List[Any]        =   tokens[: (max_seq_length - special_tokens_count)]
                     _UpperCAmelCase      :     List[Any]        =   label_ids[: (max_seq_length - special_tokens_count)]

                # The convention in BERT is:
                # (a) For sequence pairs:
                #  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
                #  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
                # (b) For single sequences:
                #  tokens:   [CLS] the dog is hairy . [SEP]
                #  type_ids:   0   0   0   0  0     0   0
                #
                # Where "type_ids" are used to indicate whether this is the first
                # sequence or the second sequence. The embedding vectors for `type=0` and
                # `type=1` were learned during pre-training and are added to the wordpiece
                # embedding vector (and position vector). This is not *strictly* necessary
                # since the [SEP] token unambiguously separates the sequences, but it makes
                # it easier for the model to learn the concept of sequences.
                #
                # For classification tasks, the first vector (corresponding to [CLS]) is
                # used as the "sentence vector". Note that this only makes sense because
                # the entire model is fine-tuned.
                tokens += [sep_token]
                label_ids += [pad_token_label_id]
                if sep_token_extra:
                     # roberta uses an extra separator b/w pairs of sentences
                     tokens += [sep_token]
                     label_ids += [pad_token_label_id]
                _UpperCAmelCase      :     Dict        =   [sequence_a_segment_id] * len(A						)

                if cls_token_at_end:
                     tokens += [cls_token]
                     label_ids += [pad_token_label_id]
                     segment_ids += [cls_token_segment_id]
                else:
                     _UpperCAmelCase      :     str        =   [cls_token] + tokens
                     _UpperCAmelCase      :     Dict        =   [pad_token_label_id] + label_ids
                     _UpperCAmelCase      :     Any        =   [cls_token_segment_id] + segment_ids

                _UpperCAmelCase      :     int        =   tokenizer.convert_tokens_to_ids(A						)

                # The mask has 1 for real tokens and 0 for padding tokens. Only real
                # tokens are attended to.
                _UpperCAmelCase      :     List[Any]        =   [1 if mask_padding_with_zero else 0] * len(A						)

                # Zero-pad up to the sequence length.
                _UpperCAmelCase      :     List[str]        =   max_seq_length - len(A						)
                if pad_on_left:
                     _UpperCAmelCase      :     str        =   ([pad_token] * padding_length) + input_ids
                     _UpperCAmelCase      :     str        =   ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
                     _UpperCAmelCase      :     Any        =   ([pad_token_segment_id] * padding_length) + segment_ids
                     _UpperCAmelCase      :     Dict        =   ([pad_token_label_id] * padding_length) + label_ids
                else:
                     input_ids += [pad_token] * padding_length
                     input_mask += [0 if mask_padding_with_zero else 1] * padding_length
                     segment_ids += [pad_token_segment_id] * padding_length
                     label_ids += [pad_token_label_id] * padding_length

                assert len(A						) == max_seq_length
                assert len(A						) == max_seq_length
                assert len(A						) == max_seq_length
                assert len(A						) == max_seq_length

                if ex_index < 5:
                     logger.info("*** Example ***"						)
                     logger.info("guid: %s"					,     example.guid						)
                     logger.info("tokens: %s"					,     " ".join([str(A						) for x in tokens]						)						)
                     logger.info("input_ids: %s"					,     " ".join([str(A						) for x in input_ids]						)						)
                     logger.info("input_mask: %s"					,     " ".join([str(A						) for x in input_mask]						)						)
                     logger.info("segment_ids: %s"					,     " ".join([str(A						) for x in segment_ids]						)						)
                     logger.info("label_ids: %s"					,     " ".join([str(A						) for x in label_ids]						)						)

                if "token_type_ids" not in tokenizer.model_input_names:
                     _UpperCAmelCase      :     Dict        =   None

                features.append(
                    InputFeatures(
                        input_ids=A					,     attention_mask=A					,     token_type_ids=A					,     label_ids=A						)						)
           return features


if is_torch_available():
 import torch
 from torch import nn
 from torch.utils.data import Dataset






 class      UpperCAmelCase_  (    _UpperCamelCase						):
       __SCREAMING_SNAKE_CASE						:       List[InputFeatures]
       __SCREAMING_SNAKE_CASE						:       int								=			nn.CrossEntropyLoss().ignore_index



       def __init__(					self					:     Dict					,     A					:     TokenClassificationTask					,     A					:     str					,     A					:     PreTrainedTokenizer					,     A					:     List[str]					,     A					:     str					,     A					:     Optional[int] = None					,     A					:     List[str]=False					,     A					:     Split = Split.train					,     ):
            # Load data features from cache or dataset file
            _UpperCAmelCase      :     int        =   os.path.join(
                A					,     "cached_{}_{}_{}".format(mode.value					,     tokenizer.__class__.__name__					,     str(A						)						)					,     )

            # Make sure only the first process in distributed training processes the dataset,
            # and the others will use the cache.
            _UpperCAmelCase      :     List[str]        =   cached_features_file + ".lock"
            with FileLock(A						):
                 if os.path.exists(A						) and not overwrite_cache:
                      logger.info(f'Loading features from cached file {cached_features_file}'						)
                      _UpperCAmelCase      :     Tuple        =   torch.load(A						)
                 else:
                      logger.info(f'Creating features from dataset file at {data_dir}'						)
                      _UpperCAmelCase      :     List[str]        =   token_classification_task.read_examples_from_file(A					,     A						)
                      # TODO clean up all this to leverage built-in features of tokenizers
                      _UpperCAmelCase      :     List[Any]        =   token_classification_task.convert_examples_to_features(
                          A					,     A					,     A					,     A					,     cls_token_at_end=bool(model_type in ["xlnet"]						)					,     cls_token=tokenizer.cls_token					,     cls_token_segment_id=2 if model_type in ["xlnet"] else 0					,     sep_token=tokenizer.sep_token					,     sep_token_extra=A					,     pad_on_left=bool(tokenizer.padding_side == "left"						)					,     pad_token=tokenizer.pad_token_id					,     pad_token_segment_id=tokenizer.pad_token_type_id					,     pad_token_label_id=self.pad_token_label_id					,     )
                      logger.info(f'Saving features into cached file {cached_features_file}'						)
                      torch.save(self.features					,     A						)



       def __len__(					self					:     Dict						):
            return len(self.features						)



       def __getitem__(					self					:     List[str]					,     A					:     Optional[Any]						):
            return self.features[i]


if is_tf_available():
 import tensorflow as tf






 class      UpperCAmelCase_  :
       __SCREAMING_SNAKE_CASE						:       List[InputFeatures]
       __SCREAMING_SNAKE_CASE						:       int								=			-1_0_0



       def __init__(					self					:     Tuple					,     A					:     TokenClassificationTask					,     A					:     str					,     A					:     PreTrainedTokenizer					,     A					:     List[str]					,     A					:     str					,     A					:     Optional[int] = None					,     A					:     Optional[Any]=False					,     A					:     Split = Split.train					,     ):
            _UpperCAmelCase      :     Union[str, Any]        =   token_classification_task.read_examples_from_file(A					,     A						)
            # TODO clean up all this to leverage built-in features of tokenizers
            _UpperCAmelCase      :     List[str]        =   token_classification_task.convert_examples_to_features(
                A					,     A					,     A					,     A					,     cls_token_at_end=bool(model_type in ["xlnet"]						)					,     cls_token=tokenizer.cls_token					,     cls_token_segment_id=2 if model_type in ["xlnet"] else 0					,     sep_token=tokenizer.sep_token					,     sep_token_extra=A					,     pad_on_left=bool(tokenizer.padding_side == "left"						)					,     pad_token=tokenizer.pad_token_id					,     pad_token_segment_id=tokenizer.pad_token_type_id					,     pad_token_label_id=self.pad_token_label_id					,     )

            def gen():
                 for ex in self.features:
                      if ex.token_type_ids is None:
                           yield (
                               {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
                               ex.label_ids,
                           )
                      else:
                           yield (
                               {
                                   "input_ids": ex.input_ids,
                                   "attention_mask": ex.attention_mask,
                                   "token_type_ids": ex.token_type_ids,
                               },
                               ex.label_ids,
                           )

            if "token_type_ids" not in tokenizer.model_input_names:
                 _UpperCAmelCase      :     List[str]        =   tf.data.Dataset.from_generator(
                     A					,     ({"input_ids": tf.intaa, "attention_mask": tf.intaa}, tf.intaa)					,     (
                         {"input_ids": tf.TensorShape([None]						), "attention_mask": tf.TensorShape([None]						)},
                         tf.TensorShape([None]						),
                     )					,     )
            else:
                 _UpperCAmelCase      :     List[Any]        =   tf.data.Dataset.from_generator(
                     A					,     ({"input_ids": tf.intaa, "attention_mask": tf.intaa, "token_type_ids": tf.intaa}, tf.intaa)					,     (
                         {
                             "input_ids": tf.TensorShape([None]						),
                             "attention_mask": tf.TensorShape([None]						),
                             "token_type_ids": tf.TensorShape([None]						),
                         },
                         tf.TensorShape([None]						),
                     )					,     )



       def 						snake_case_ (					self					:     str						):
            _UpperCAmelCase      :     Dict        =   self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features						)						)						)

            return self.dataset



       def __len__(					self					:     List[Any]						):
            return len(self.features						)



       def __getitem__(					self					:     int					,     A					:     int						):
            return self.features[i]
