


import unittest

from datasets import load_dataset

from transformers.pipelines import pipeline
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow


@is_pipeline_test
@require_torch
class     lowercase__  (					unittest.TestCase		):






  @require_torch
  def 			_UpperCAmelCase  (					self      :					List[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     pipeline(
             task="zero-shot-audio-classification"		,						model="hf-internal-testing/tiny-clap-htsat-unfused" )
         UpperCAmelCase__										=     load_dataset("ashraq/esc50" )
         UpperCAmelCase__										=     dataset["train"]["audio"][-1]["array"]
         UpperCAmelCase__										=     audio_classifier(_lowercase		,						candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] )
         self.assertEqual(
             nested_simplify(_lowercase )		,						[{"score": 0.5_0_1, "label": "Sound of a dog"}, {"score": 0.4_9_9, "label": "Sound of vaccum cleaner"}]		,						)






  @unittest.skip("No models are available in TF" )
  def 			_UpperCAmelCase  (					self      :					List[str] ):




         """simple docstring"""







         pass






  @slow
  @require_torch
  def 			_UpperCAmelCase  (					self      :					Optional[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     pipeline(
             task="zero-shot-audio-classification"		,						model="laion/clap-htsat-unfused"		,						)
         # This is an audio of a dog
         UpperCAmelCase__										=     load_dataset("ashraq/esc50" )
         UpperCAmelCase__										=     dataset["train"]["audio"][-1]["array"]
         UpperCAmelCase__										=     audio_classifier(_lowercase		,						candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] )

         self.assertEqual(
             nested_simplify(_lowercase )		,						[
                 {"score": 0.9_9_9, "label": "Sound of a dog"},
                 {"score": 0.0_0_1, "label": "Sound of vaccum cleaner"},
             ]		,						)

         UpperCAmelCase__										=     audio_classifier([audio] * 5		,						candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] )
         self.assertEqual(
             nested_simplify(_lowercase )		,						[
                 [
                     {"score": 0.9_9_9, "label": "Sound of a dog"},
                     {"score": 0.0_0_1, "label": "Sound of vaccum cleaner"},
                 ],
             ]
             * 5		,						)
         UpperCAmelCase__										=     audio_classifier(
             [audio] * 5		,						candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]		,						batch_size=5 )
         self.assertEqual(
             nested_simplify(_lowercase )		,						[
                 [
                     {"score": 0.9_9_9, "label": "Sound of a dog"},
                     {"score": 0.0_0_1, "label": "Sound of vaccum cleaner"},
                 ],
             ]
             * 5		,						)






  @unittest.skip("No models are available in TF" )
  def 			_UpperCAmelCase  (					self      :					List[Any] ):




         """simple docstring"""







         pass









import argparse
import json
from typing import List

from ltp import LTP

from transformers import BertTokenizer





def __UpperCAmelCase       (		__A			)						->					Union[str, Any]:



       '''simple docstring'''





       if (
           (cp >= 0x4_E_0_0 and cp <= 0x9_F_F_F)
           or (cp >= 0x3_4_0_0 and cp <= 0x4_D_B_F)  #
           or (cp >= 0x2_0_0_0_0 and cp <= 0x2_A_6_D_F)  #
           or (cp >= 0x2_A_7_0_0 and cp <= 0x2_B_7_3_F)  #
           or (cp >= 0x2_B_7_4_0 and cp <= 0x2_B_8_1_F)  #
           or (cp >= 0x2_B_8_2_0 and cp <= 0x2_C_E_A_F)  #
           or (cp >= 0xF_9_0_0 and cp <= 0xF_A_F_F)
           or (cp >= 0x2_F_8_0_0 and cp <= 0x2_F_A_1_F)  #
       ):  #
              return True

       return False





def __UpperCAmelCase       (		__A			)						->					List[str]:



       '''simple docstring'''





       for char in word:
              UpperCAmelCase__										=     ord(__A			)
              if not _is_chinese_char(__A			):
                     return 0
       return 1





def __UpperCAmelCase       (		__A			)						->					str:



       '''simple docstring'''





       UpperCAmelCase__										=     set()

       for token in tokens:
              UpperCAmelCase__										=     len(__A			) > 1 and is_chinese(__A			)
              if chinese_word:
                     word_set.add(__A			)
       UpperCAmelCase__										=     list(__A			)
       return word_list





def __UpperCAmelCase       (		__A ,						__A			)						->					Optional[Any]:



       '''simple docstring'''





       if not chinese_word_set:
              return bert_tokens
       UpperCAmelCase__										=     max([len(__A			) for w in chinese_word_set]			)

       UpperCAmelCase__										=     bert_tokens
       UpperCAmelCase__						,			UpperCAmelCase__										=     0, len(__A			)
       while start < end:
              UpperCAmelCase__										=     True
              if is_chinese(bert_word[start]			):
                     UpperCAmelCase__										=     min(end - start ,						__A			)
                     for i in range(__A ,						1 ,						-1			):
                            UpperCAmelCase__										=     "".join(bert_word[start : start + i]			)
                            if whole_word in chinese_word_set:
                                   for j in range(start + 1 ,						start + i			):
                                          UpperCAmelCase__										=     "##" + bert_word[j]
                                   UpperCAmelCase__										=     start + i
                                   UpperCAmelCase__										=     False
                                   break
              if single_word:
                     start += 1
       return bert_word





def __UpperCAmelCase       (		__A ,						__A ,						__A			)						->					List[Any]:



       '''simple docstring'''





       UpperCAmelCase__										=     []

       for i in range(0 ,						len(__A			) ,						1_0_0			):
              UpperCAmelCase__										=     ltp_tokenizer.seg(lines[i : i + 1_0_0]			)[0]
              UpperCAmelCase__										=     [get_chinese_word(__A			) for r in res]
              ltp_res.extend(__A			)
       assert len(__A			) == len(__A			)

       UpperCAmelCase__										=     []
       for i in range(0 ,						len(__A			) ,						1_0_0			):
              UpperCAmelCase__										=     bert_tokenizer(lines[i : i + 1_0_0] ,						add_special_tokens=__A ,						truncation=__A ,						max_length=5_1_2			)
              bert_res.extend(res["input_ids"]			)
       assert len(__A			) == len(__A			)

       UpperCAmelCase__										=     []
       for input_ids, chinese_word in zip(__A ,						__A			):
              UpperCAmelCase__										=     []
              for id in input_ids:
                     UpperCAmelCase__										=     bert_tokenizer._convert_id_to_token(__A			)
                     input_tokens.append(__A			)
              UpperCAmelCase__										=     add_sub_symbol(__A ,						__A			)
              UpperCAmelCase__										=     []
              # We only save pos of chinese subwords start with ##, which mean is part of a whole word.
              for i, token in enumerate(__A			):
                     if token[:2] == "##":
                            UpperCAmelCase__										=     token[2:]
                            # save chinese tokens' pos
                            if len(__A			) == 1 and _is_chinese_char(ord(__A			)			):
                                   ref_id.append(__A			)
              ref_ids.append(__A			)

       assert len(__A			) == len(__A			)

       return ref_ids





def __UpperCAmelCase       (		__A			)						->					Optional[int]:



       '''simple docstring'''





       with open(args.file_name ,						"r" ,						encoding="utf-8"			) as f:
              UpperCAmelCase__										=     f.readlines()
       UpperCAmelCase__										=     [line.strip() for line in data if len(__A			) > 0 and not line.isspace()]  # avoid delimiter like '\u2029'
       UpperCAmelCase__										=     LTP(args.ltp			)  # faster in GPU device
       UpperCAmelCase__										=     BertTokenizer.from_pretrained(args.bert			)

       UpperCAmelCase__										=     prepare_ref(__A ,						__A ,						__A			)

       with open(args.save_path ,						"w" ,						encoding="utf-8"			) as f:
              UpperCAmelCase__										=     [json.dumps(__A			) + "\n" for ref in ref_ids]
              f.writelines(__A			)


if __name__ == "__main__":
    A      = argparse.ArgumentParser(description="prepare_chinese_ref")
    parser.add_argument(
        "--file_name",
        type=str,
        default="./resources/chinese-demo.txt",
        help="file need process, same as training data in lm",
    )
    parser.add_argument(
        "--ltp", type=str, default="./resources/ltp", help="resources for LTP tokenizer, usually a path"
    )
    parser.add_argument("--bert", type=str, default="./resources/robert", help="resources for Bert tokenizer")
    parser.add_argument("--save_path", type=str, default="./resources/ref.txt", help="path to save res")

    A      = parser.parse_args()
    main(args)





