


'''simple docstring'''



import os
import pickle
import unittest

from transformers import AutoTokenizer
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.models.bert_japanese.tokenization_bert_japanese import (
    VOCAB_FILES_NAMES,
    BertJapaneseTokenizer,
    CharacterTokenizer,
    JumanppTokenizer,
    MecabTokenizer,
    SudachiTokenizer,
    WordpieceTokenizer,
)
from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi

from ...test_tokenization_common import TokenizerTesterMixin





@custom_tokenizers
class    UpperCAmelCase_  (_UpperCAmelCase					,		unittest.TestCase  ):





    """simple docstring"""






    lowerCamelCase  :					str							     =			BertJapaneseTokenizer
    lowerCamelCase  :					Dict							     =			False
    lowerCamelCase  :					Any							     =			True







    def       lowercase_				(							self	)				->     Tuple:
         super().setUp()

         __lowerCamelCase   :	int								=		[
             '[UNK]',
             '[CLS]',
             '[SEP]',
             'こんにちは',
             'こん',
             'にちは',
             'ばんは',
             '##こん',
             '##にちは',
             '##ばんは',
             '世界',
             '##世界',
             '、',
             '##、',
             '。',
             '##。',
         ]

         __lowerCamelCase   :	Tuple								=		os.path.join(self.tmpdirname			,     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]	)	)







    def       lowercase_				(							self			,     SCREAMING_SNAKE_CASE_	)				->     Tuple:
         __lowerCamelCase   :	List[str]								=		'こんにちは、世界。 \nこんばんは、世界。'
         __lowerCamelCase   :	Any								=		'こんにちは 、 世界 。 こんばんは 、 世界 。'
         return input_text, output_text







    def       lowercase_				(							self			,     SCREAMING_SNAKE_CASE_	)				->     Optional[int]:
         __lowerCamelCase				,       __lowerCamelCase   :	Any								=		self.get_input_output_texts(SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	List[Any]								=		tokenizer.encode(SCREAMING_SNAKE_CASE_			,     add_special_tokens=SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	Dict								=		tokenizer.decode(SCREAMING_SNAKE_CASE_			,     clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_	)
         return text, ids







    def       lowercase_				(							self	)				->     List[str]:
         pass  # TODO add if relevant







    def       lowercase_				(							self	)				->     List[Any]:
         pass  # TODO add if relevant







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







    def       lowercase_				(							self	)				->     Dict:
         __lowerCamelCase   :	int								=		self.tokenizer_class(self.vocab_file	)

         __lowerCamelCase   :	Union[str, Any]								=		tokenizer.tokenize('こんにちは、世界。\nこんばんは、世界。'	)
         self.assertListEqual(SCREAMING_SNAKE_CASE_			,     ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']	)
         self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_	)			,     [3, 12, 10, 14, 4, 9, 12, 10, 14]	)







    def       lowercase_				(							self	)				->     int:
         __lowerCamelCase   :	int								=		self.tokenizer_class(self.vocab_file			,     word_tokenizer_type='mecab'	)
         self.assertIsNotNone(SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	List[str]								=		'こんにちは、世界。\nこんばんは、世界。'
         __lowerCamelCase   :	Tuple								=		tokenizer.tokenize(SCREAMING_SNAKE_CASE_	)
         self.assertListEqual(SCREAMING_SNAKE_CASE_			,     ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']	)
         self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_	)			,     [3, 12, 10, 14, 4, 9, 12, 10, 14]	)

         __lowerCamelCase   :	Tuple								=		os.path.join(self.tmpdirname			,     'tokenizer.bin'	)
         with open(SCREAMING_SNAKE_CASE_			,     'wb'	) as handle:
              pickle.dump(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)

         with open(SCREAMING_SNAKE_CASE_			,     'rb'	) as handle:
              __lowerCamelCase   :	List[Any]								=		pickle.load(SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	List[str]								=		tokenizer_new.tokenize(SCREAMING_SNAKE_CASE_	)

         self.assertListEqual(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)







    def       lowercase_				(							self	)				->     Optional[Any]:
         __lowerCamelCase   :	Union[str, Any]								=		MecabTokenizer(mecab_dic='ipadic'	)

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。']			,     )







    def       lowercase_				(							self	)				->     Optional[int]:
         try:
              __lowerCamelCase   :	Dict								=		MecabTokenizer(mecab_dic='unidic_lite'	)
         except ModuleNotFoundError:
              return

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。']			,     )







    def       lowercase_				(							self	)				->     int:
         try:
              __lowerCamelCase   :	List[Any]								=		MecabTokenizer(mecab_dic='unidic'	)
         except ModuleNotFoundError:
              return

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。']			,     )







    def       lowercase_				(							self	)				->     int:
         __lowerCamelCase   :	str								=		MecabTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_			,     mecab_dic='ipadic'	)

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     ['アップルストア', 'で', 'iphone', '8', 'が', '発売', 'さ', 'れ', 'た', '。']			,     )







    def       lowercase_				(							self	)				->     str:
         try:
              __lowerCamelCase   :	Any								=		MecabTokenizer(
                  do_lower_case=SCREAMING_SNAKE_CASE_			,     normalize_text=SCREAMING_SNAKE_CASE_			,     mecab_option='-d /usr/local/lib/mecab/dic/jumandic'	)
         except RuntimeError:
              # if dict doesn't exist in the system, previous code raises this error.
              return

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     ['ｱｯﾌﾟﾙストア', 'で', 'iPhone', '８', 'が', '発売', 'さ', 'れた', '\u3000', '。']			,     )







    def       lowercase_				(							self	)				->     Optional[int]:
         __lowerCamelCase   :	Optional[Any]								=		MecabTokenizer(normalize_text=SCREAMING_SNAKE_CASE_			,     mecab_dic='ipadic'	)

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     ['ｱｯﾌﾟﾙストア', 'で', 'iPhone', '８', 'が', '発売', 'さ', 'れ', 'た', '　', '。']			,     )







    @require_sudachi
    def       lowercase_				(							self	)				->     Tuple:
         __lowerCamelCase   :	Any								=		self.tokenizer_class(self.vocab_file			,     word_tokenizer_type='sudachi'	)
         self.assertIsNotNone(SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	Optional[int]								=		'こんにちは、世界。\nこんばんは、世界。'
         __lowerCamelCase   :	Optional[Any]								=		tokenizer.tokenize(SCREAMING_SNAKE_CASE_	)
         self.assertListEqual(SCREAMING_SNAKE_CASE_			,     ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']	)
         self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_	)			,     [3, 12, 10, 14, 4, 9, 12, 10, 14]	)

         __lowerCamelCase   :	Optional[int]								=		os.path.join(self.tmpdirname			,     'tokenizer.bin'	)
         with open(SCREAMING_SNAKE_CASE_			,     'wb'	) as handle:
              pickle.dump(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)

         with open(SCREAMING_SNAKE_CASE_			,     'rb'	) as handle:
              __lowerCamelCase   :	Dict								=		pickle.load(SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	Optional[int]								=		tokenizer_new.tokenize(SCREAMING_SNAKE_CASE_	)

         self.assertListEqual(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)







    @require_sudachi
    def       lowercase_				(							self	)				->     List[str]:
         __lowerCamelCase   :	List[Any]								=		SudachiTokenizer(sudachi_dict_type='core'	)

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     [' ', '\t', 'アップル', 'ストア', 'で', 'iPhone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' ']			,     )







    @require_sudachi
    def       lowercase_				(							self	)				->     Union[str, Any]:
         __lowerCamelCase   :	Union[str, Any]								=		SudachiTokenizer(sudachi_dict_type='core'			,     sudachi_split_mode='A'	)

         self.assertListEqual(tokenizer.tokenize('外国人参政権'	)			,     ['外国', '人', '参政', '権']	)







    @require_sudachi
    def       lowercase_				(							self	)				->     List[str]:
         __lowerCamelCase   :	Any								=		SudachiTokenizer(sudachi_dict_type='core'			,     sudachi_split_mode='B'	)

         self.assertListEqual(tokenizer.tokenize('外国人参政権'	)			,     ['外国人', '参政権']	)







    @require_sudachi
    def       lowercase_				(							self	)				->     int:
         __lowerCamelCase   :	List[Any]								=		SudachiTokenizer(sudachi_dict_type='core'			,     sudachi_split_mode='C'	)

         self.assertListEqual(tokenizer.tokenize('外国人参政権'	)			,     ['外国人参政権']	)







    @require_sudachi
    def       lowercase_				(							self	)				->     Optional[Any]:
         __lowerCamelCase   :	Optional[int]								=		SudachiTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_			,     sudachi_dict_type='core'	)

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     [' ', '\t', 'アップル', 'ストア', 'で', 'iphone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' ']			,     )







    @require_sudachi
    def       lowercase_				(							self	)				->     Optional[Any]:
         __lowerCamelCase   :	str								=		SudachiTokenizer(normalize_text=SCREAMING_SNAKE_CASE_			,     sudachi_dict_type='core'	)

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     [' ', '\t', 'ｱｯﾌﾟﾙ', 'ストア', 'で', 'iPhone', '８', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', '\u3000', '。', ' ', ' ']			,     )







    @require_sudachi
    def       lowercase_				(							self	)				->     List[str]:
         __lowerCamelCase   :	Any								=		SudachiTokenizer(trim_whitespace=SCREAMING_SNAKE_CASE_			,     sudachi_dict_type='core'	)

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。']			,     )







    @require_jumanpp
    def       lowercase_				(							self	)				->     Union[str, Any]:
         __lowerCamelCase   :	Optional[int]								=		self.tokenizer_class(self.vocab_file			,     word_tokenizer_type='jumanpp'	)
         self.assertIsNotNone(SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	List[Any]								=		'こんにちは、世界。\nこんばんは、世界。'
         __lowerCamelCase   :	List[Any]								=		tokenizer.tokenize(SCREAMING_SNAKE_CASE_	)
         self.assertListEqual(SCREAMING_SNAKE_CASE_			,     ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。']	)
         self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_	)			,     [3, 12, 10, 14, 4, 9, 12, 10, 14]	)

         __lowerCamelCase   :	str								=		os.path.join(self.tmpdirname			,     'tokenizer.bin'	)
         with open(SCREAMING_SNAKE_CASE_			,     'wb'	) as handle:
              pickle.dump(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)

         with open(SCREAMING_SNAKE_CASE_			,     'rb'	) as handle:
              __lowerCamelCase   :	List[Any]								=		pickle.load(SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	Optional[int]								=		tokenizer_new.tokenize(SCREAMING_SNAKE_CASE_	)

         self.assertListEqual(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)







    @require_jumanpp
    def       lowercase_				(							self	)				->     str:
         __lowerCamelCase   :	Dict								=		JumanppTokenizer()

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     ['アップル', 'ストア', 'で', 'iPhone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。']			,     )







    @require_jumanpp
    def       lowercase_				(							self	)				->     int:
         __lowerCamelCase   :	str								=		JumanppTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_	)

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     ['アップル', 'ストア', 'で', 'iphone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。']			,     )







    @require_jumanpp
    def       lowercase_				(							self	)				->     List[str]:
         __lowerCamelCase   :	List[str]								=		JumanppTokenizer(normalize_text=SCREAMING_SNAKE_CASE_	)

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     ['ｱ', 'ｯ', 'ﾌ', 'ﾟ', 'ﾙ', 'ストア', 'で', 'iPhone', '８', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。']			,     )







    @require_jumanpp
    def       lowercase_				(							self	)				->     List[Any]:
         __lowerCamelCase   :	Dict								=		JumanppTokenizer(trim_whitespace=SCREAMING_SNAKE_CASE_	)

         self.assertListEqual(
             tokenizer.tokenize(' \tｱｯﾌﾟﾙストアでiPhone８ が  \n 発売された　。  '	)			,     ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れた', '。']			,     )







    @require_jumanpp
    def       lowercase_				(							self	)				->     Tuple:
         __lowerCamelCase   :	Optional[Any]								=		JumanppTokenizer()

         self.assertListEqual(
             tokenizer.tokenize('ありがとうございますm(_ _)ｍ見つけるのが大変です。'	)			,     ['ありがとう', 'ございます', 'm(_ _)m', '見つける', 'の', 'が', '大変です', '。']			,     )







    def       lowercase_				(							self	)				->     Any:
         __lowerCamelCase   :	List[Any]								=		['[UNK]', '[CLS]', '[SEP]', 'こんにちは', 'こん', 'にちは', 'ばんは', '##こん', '##にちは', '##ばんは']

         __lowerCamelCase   :	Tuple								=		{}
         for i, token in enumerate(SCREAMING_SNAKE_CASE_	):
              __lowerCamelCase   :	Optional[int]								=		i
         __lowerCamelCase   :	Optional[int]								=		WordpieceTokenizer(vocab=SCREAMING_SNAKE_CASE_			,     unk_token='[UNK]'	)

         self.assertListEqual(tokenizer.tokenize(''	)			,     []	)

         self.assertListEqual(tokenizer.tokenize('こんにちは'	)			,     ['こんにちは']	)

         self.assertListEqual(tokenizer.tokenize('こんばんは'	)			,     ['こん', '##ばんは']	)

         self.assertListEqual(tokenizer.tokenize('こんばんは こんばんにちは こんにちは'	)			,     ['こん', '##ばんは', '[UNK]', 'こんにちは']	)







    def       lowercase_				(							self	)				->     Any:
         __lowerCamelCase   :	str								=		BertJapaneseTokenizer.from_pretrained('nlp-waseda/roberta-base-japanese-with-auto-jumanpp'	)
         __lowerCamelCase   :	Optional[Any]								=		tokenizer.subword_tokenizer

         __lowerCamelCase   :	List[str]								=		subword_tokenizer.tokenize('国境 の 長い トンネル を 抜ける と 雪国 であった 。'	)
         self.assertListEqual(SCREAMING_SNAKE_CASE_			,     ['▁国境', '▁の', '▁長い', '▁トンネル', '▁を', '▁抜ける', '▁と', '▁雪', '国', '▁であった', '▁。']	)

         __lowerCamelCase   :	str								=		subword_tokenizer.tokenize('こんばんは こんばん にち は こんにちは'	)
         self.assertListEqual(SCREAMING_SNAKE_CASE_			,     ['▁こん', 'ばん', 'は', '▁こん', 'ばん', '▁に', 'ち', '▁は', '▁こんにちは']	)







    def       lowercase_				(							self	)				->     str:
         __lowerCamelCase   :	Dict								=		self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese'	)

         __lowerCamelCase   :	Dict								=		tokenizer.encode('ありがとう。'			,     add_special_tokens=SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	List[str]								=		tokenizer.encode('どういたしまして。'			,     add_special_tokens=SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	Union[str, Any]								=		tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	Any								=		tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)

         # 2 is for "[CLS]", 3 is for "[SEP]"
         assert encoded_sentence == [2] + text + [3]
         assert encoded_pair == [2] + text + [3] + text_a + [3]







@custom_tokenizers
class    UpperCAmelCase_  (_UpperCAmelCase					,		unittest.TestCase  ):





    """simple docstring"""






    lowerCamelCase  :					Optional[int]							     =			BertJapaneseTokenizer
    lowerCamelCase  :					List[Any]							     =			False







    def       lowercase_				(							self	)				->     Dict:
         super().setUp()

         __lowerCamelCase   :	List[Any]								=		['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。']

         __lowerCamelCase   :	str								=		os.path.join(self.tmpdirname			,     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]	)	)







    def       lowercase_				(							self			,     **SCREAMING_SNAKE_CASE_	)				->     Optional[Any]:
         return BertJapaneseTokenizer.from_pretrained(self.tmpdirname			,     subword_tokenizer_type='character'			,     **SCREAMING_SNAKE_CASE_	)







    def       lowercase_				(							self			,     SCREAMING_SNAKE_CASE_	)				->     Dict:
         __lowerCamelCase   :	Dict								=		'こんにちは、世界。 \nこんばんは、世界。'
         __lowerCamelCase   :	Tuple								=		'こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。'
         return input_text, output_text







    def       lowercase_				(							self	)				->     Dict:
         pass  # TODO add if relevant







    def       lowercase_				(							self	)				->     Any:
         pass  # TODO add if relevant







    def       lowercase_				(							self	)				->     int:
         pass  # TODO add if relevant







    def       lowercase_				(							self	)				->     Any:
         __lowerCamelCase   :	Any								=		self.tokenizer_class(self.vocab_file			,     subword_tokenizer_type='character'	)

         __lowerCamelCase   :	Tuple								=		tokenizer.tokenize('こんにちは、世界。 \nこんばんは、世界。'	)
         self.assertListEqual(
             SCREAMING_SNAKE_CASE_			,     ['こ', 'ん', 'に', 'ち', 'は', '、', '世', '界', '。', 'こ', 'ん', 'ば', 'ん', 'は', '、', '世', '界', '。']	)
         self.assertListEqual(
             tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_	)			,     [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12]	)







    def       lowercase_				(							self	)				->     Optional[Any]:
         __lowerCamelCase   :	str								=		['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。']

         __lowerCamelCase   :	Any								=		{}
         for i, token in enumerate(SCREAMING_SNAKE_CASE_	):
              __lowerCamelCase   :	Optional[int]								=		i
         __lowerCamelCase   :	Any								=		CharacterTokenizer(vocab=SCREAMING_SNAKE_CASE_			,     unk_token='[UNK]'	)

         self.assertListEqual(tokenizer.tokenize(''	)			,     []	)

         self.assertListEqual(tokenizer.tokenize('こんにちは'	)			,     ['こ', 'ん', 'に', 'ち', 'は']	)

         self.assertListEqual(tokenizer.tokenize('こんにちほ'	)			,     ['こ', 'ん', 'に', 'ち', '[UNK]']	)







    def       lowercase_				(							self	)				->     str:
         __lowerCamelCase   :	int								=		self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese-char'	)

         __lowerCamelCase   :	int								=		tokenizer.encode('ありがとう。'			,     add_special_tokens=SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	str								=		tokenizer.encode('どういたしまして。'			,     add_special_tokens=SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	Optional[Any]								=		tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	Tuple								=		tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)

         # 2 is for "[CLS]", 3 is for "[SEP]"
         assert encoded_sentence == [2] + text + [3]
         assert encoded_pair == [2] + text + [3] + text_a + [3]







@custom_tokenizers
class    UpperCAmelCase_  (unittest.TestCase  ):





    """simple docstring"""






    def       lowercase_				(							self	)				->     str:
         __lowerCamelCase   :	List[str]								=		'cl-tohoku/bert-base-japanese'
         __lowerCamelCase   :	Tuple								=		AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_	)
         self.assertIsInstance(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)







class    UpperCAmelCase_  (unittest.TestCase  ):





    """simple docstring"""






    def       lowercase_				(							self	)				->     Union[str, Any]:
         __lowerCamelCase   :	List[Any]								=		'cl-tohoku/bert-base-japanese'
         with self.assertLogs('transformers'			,     level='WARNING'	) as cm:
              BertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_	)
              self.assertTrue(
                  cm.records[0].message.startswith(
                      'The tokenizer class you load from this checkpoint is not the same type as the class this function'
                      ' is called from.'	)	)
         __lowerCamelCase   :	Tuple								=		'bert-base-cased'
         with self.assertLogs('transformers'			,     level='WARNING'	) as cm:
              BertJapaneseTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_	)
              self.assertTrue(
                  cm.records[0].message.startswith(
                      'The tokenizer class you load from this checkpoint is not the same type as the class this function'
                      ' is called from.'	)	)










'''simple docstring'''



import argparse

import torch

# Step 1. clone https://github.com/microsoft/unilm
# Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd
# Step 3. cd unilm
# Step 4. ln -s $(realpath wavlm/modules.py) ./  # create simlink
# import classes
from unilm.wavlm.WavLM import WavLM as WavLMOrig
from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig

from transformers import WavLMConfig, WavLMModel, logging


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

A__		:					List[Any]												=  {
    """post_extract_proj""": """feature_projection.projection""",
    """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""",
    """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""",
    """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""",
    """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""",
    """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""",
    """self_attn.grep_linear""": """encoder.layers.*.attention.gru_rel_pos_linear""",
    """self_attn.relative_attention_bias""": """encoder.layers.*.attention.rel_attn_embed""",
    """self_attn.grep_a""": """encoder.layers.*.attention.gru_rel_pos_const""",
    """self_attn_layer_norm""": """encoder.layers.*.layer_norm""",
    """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""",
    """fc2""": """encoder.layers.*.feed_forward.output_dense""",
    """final_layer_norm""": """encoder.layers.*.final_layer_norm""",
    """encoder.layer_norm""": """encoder.layer_norm""",
    """w2v_model.layer_norm""": """feature_projection.layer_norm""",
    """quantizer.weight_proj""": """quantizer.weight_proj""",
    """quantizer.vars""": """quantizer.codevectors""",
    """project_q""": """project_q""",
    """final_proj""": """project_hid""",
    """w2v_encoder.proj""": """ctc_proj""",
    """mask_emb""": """masked_spec_embed""",
}
A__		:					Tuple												=  [
    """ctc_proj""",
    """quantizer.weight_proj""",
    """quantizer.codevectors""",
    """project_q""",
    """project_hid""",
]



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				int      ,    UpperCAmelCase_    :				List[Any]      ,    UpperCAmelCase_    :				List[str]      ,    UpperCAmelCase_    :				List[Any]      ,    UpperCAmelCase_    :				Optional[int]							)     ->		Tuple:
     for attribute in key.split('.'							):
          __lowerCamelCase   :	List[Any]								=		getattr(UpperCAmelCase_      ,    UpperCAmelCase_							)

     if weight_type is not None:
          __lowerCamelCase   :	Any								=		getattr(UpperCAmelCase_      ,    UpperCAmelCase_							).shape
     else:
          __lowerCamelCase   :	Any								=		hf_pointer.shape

     assert hf_shape == value.shape, (
         F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'
         F' {value.shape} for {full_name}'
     )

     if weight_type == "weight":
          __lowerCamelCase   :	Tuple								=		value
     elif weight_type == "weight_g":
          __lowerCamelCase   :	Optional[int]								=		value
     elif weight_type == "weight_v":
          __lowerCamelCase   :	str								=		value
     elif weight_type == "bias":
          __lowerCamelCase   :	List[Any]								=		value
     else:
          __lowerCamelCase   :	List[str]								=		value

     logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.'							)



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				List[Any]      ,    UpperCAmelCase_    :				Union[str, Any]							)     ->		Optional[int]:
     __lowerCamelCase   :	Optional[Any]								=		[]
     __lowerCamelCase   :	Dict								=		fairseq_model.state_dict()

     __lowerCamelCase   :	List[str]								=		hf_model.feature_extractor

     for name, value in fairseq_dict.items():
          __lowerCamelCase   :	Union[str, Any]								=		False
          if "conv_layers" in name:
               load_conv_layer(
                   UpperCAmelCase_      ,    UpperCAmelCase_      ,    UpperCAmelCase_      ,    UpperCAmelCase_      ,    hf_model.config.feat_extract_norm == 'group'      ,    )
               __lowerCamelCase   :	str								=		True
          else:
               for key, mapped_key in MAPPING.items():
                    if key in name or key.split('w2v_model.'							)[-1] == name.split('.'							)[0]:
                         __lowerCamelCase   :	int								=		True
                         if "*" in mapped_key:
                              __lowerCamelCase   :	Optional[int]								=		name.split(UpperCAmelCase_							)[0].split('.'							)[-2]
                              __lowerCamelCase   :	List[str]								=		mapped_key.replace('*'      ,    UpperCAmelCase_							)
                         if "weight_g" in name:
                              __lowerCamelCase   :	Dict								=		'weight_g'
                         elif "weight_v" in name:
                              __lowerCamelCase   :	Any								=		'weight_v'
                         elif "bias" in name and "relative_attention_bias" not in name:
                              __lowerCamelCase   :	Any								=		'bias'
                         elif "weight" in name:
                              # TODO: don't match quantizer.weight_proj
                              __lowerCamelCase   :	List[Any]								=		'weight'
                         else:
                              __lowerCamelCase   :	str								=		None

                         set_recursively(UpperCAmelCase_      ,    UpperCAmelCase_      ,    UpperCAmelCase_      ,    UpperCAmelCase_      ,    UpperCAmelCase_							)
                    continue
          if not is_used:
               unused_weights.append(UpperCAmelCase_							)

     logger.warning(F'Unused weights: {unused_weights}'							)



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				Any      ,    UpperCAmelCase_    :				List[Any]      ,    UpperCAmelCase_    :				Optional[int]      ,    UpperCAmelCase_    :				Optional[int]      ,    UpperCAmelCase_    :				List[Any]							)     ->		Tuple:
     __lowerCamelCase   :	List[str]								=		full_name.split('conv_layers.'							)[-1]
     __lowerCamelCase   :	List[Any]								=		name.split('.'							)
     __lowerCamelCase   :	Any								=		int(items[0]							)
     __lowerCamelCase   :	Optional[Any]								=		int(items[1]							)

     if type_id == 0:
          if "bias" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
                   F'{full_name} has size {value.shape}, but'
                   F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'
               )
               __lowerCamelCase   :	Union[str, Any]								=		value
               logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.'							)
          elif "weight" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
                   F'{full_name} has size {value.shape}, but'
                   F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'
               )
               __lowerCamelCase   :	Tuple								=		value
               logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.'							)
     elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
          if "bias" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
                   F'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'
                   " found."
               )
               __lowerCamelCase   :	str								=		value
               logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'							)
          elif "weight" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
                   F'{full_name} has size {value.shape}, but'
                   F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'
               )
               __lowerCamelCase   :	List[Any]								=		value
               logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'							)
     else:
          unused_weights.append(UpperCAmelCase_							)



@torch.no_grad()
def 			UpperCAmelCase__					(	UpperCAmelCase_    :				int      ,    UpperCAmelCase_    :				Tuple      ,    UpperCAmelCase_    :				Optional[Any]=None							)     ->		Optional[int]:
     # load the pre-trained checkpoints
     __lowerCamelCase   :	Optional[Any]								=		torch.load(UpperCAmelCase_							)
     __lowerCamelCase   :	Optional[Any]								=		WavLMConfigOrig(checkpoint['cfg']							)
     __lowerCamelCase   :	Union[str, Any]								=		WavLMOrig(UpperCAmelCase_							)
     model.load_state_dict(checkpoint['model']							)
     model.eval()

     if config_path is not None:
          __lowerCamelCase   :	Optional[int]								=		WavLMConfig.from_pretrained(UpperCAmelCase_							)
     else:
          __lowerCamelCase   :	Any								=		WavLMConfig()

     __lowerCamelCase   :	Optional[int]								=		WavLMModel(UpperCAmelCase_							)

     recursively_load_weights(UpperCAmelCase_      ,    UpperCAmelCase_							)

     hf_wavlm.save_pretrained(UpperCAmelCase_							)


if __name__ == "__main__":
      A__		:					List[Any]												=  argparse.ArgumentParser()
      parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
      parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""")
      parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
      A__		:					List[str]												=  parser.parse_args()
      convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)






