

"""simple docstring"""






import gc
import unittest

import numpy as np
import torch

from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 	__UpperCamelCase    (    a__							,							unittest.TestCase						):
  _UpperCAmelCase          =		DanceDiffusionPipeline
  _UpperCAmelCase          =		UNCONDITIONAL_AUDIO_GENERATION_PARAMS
  _UpperCAmelCase          =		PipelineTesterMixin.required_optional_params - {
      "callback",
      "latents",
      "callback_steps",
      "output_type",
      "num_images_per_prompt",
  }
  _UpperCAmelCase          =		UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		False

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      torch.manual_seed(0      )
      _lowerCAmelCase       :   List[Any]  =    UNetaDModel(
          block_out_channels=(32, 32, 64)    ,extra_in_channels=16    ,sample_size=512    ,sample_rate=1_6000    ,in_channels=2    ,out_channels=2    ,flip_sin_to_cos=_A    ,use_timestep_embedding=_A    ,time_embedding_type='fourier'    ,mid_block_type='UNetMidBlock1D'    ,down_block_types=('DownBlock1DNoSkip', 'DownBlock1D', 'AttnDownBlock1D')    ,up_block_types=('AttnUpBlock1D', 'UpBlock1D', 'UpBlock1DNoSkip')    ,)
      _lowerCAmelCase       :   int  =    IPNDMScheduler()

      _lowerCAmelCase       :   Union[str, Any]  =    {
          'unet': unet,
          'scheduler': scheduler,
      }
      return components

  def __lowerCamelCase		(		self    ,_A    ,_A=0      ):
      '''simple docstring'''

      if str(_A      ).startswith('mps'      ):
          _lowerCAmelCase       :   str  =    torch.manual_seed(_A      )
      else:
          _lowerCAmelCase       :   Optional[Any]  =    torch.Generator(device=_A      ).manual_seed(_A      )
      _lowerCAmelCase       :   int  =    {
          'batch_size': 1,
          'generator': generator,
          'num_inference_steps': 4,
      }
      return inputs

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    'cpu'  # ensure determinism for the device-dependent torch.Generator
      _lowerCAmelCase       :   int  =    self.get_dummy_components()
      _lowerCAmelCase       :   Optional[Any]  =    DanceDiffusionPipeline(**_A      )
      _lowerCAmelCase       :   int  =    pipe.to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   Union[str, Any]  =    self.get_dummy_inputs(_A      )
      _lowerCAmelCase       :   List[str]  =    pipe(**_A      )
      _lowerCAmelCase       :   List[Any]  =    output.audios

      _lowerCAmelCase       :   List[str]  =    audio[0, -3:, -3:]

      assert audio.shape == (1, 2, components["unet"].sample_size)
      _lowerCAmelCase       :   Optional[Any]  =    np.array([-0.7_2_6_5, 1.0_0_0_0, -0.8_3_8_8, 0.1_1_7_5, 0.9_4_9_8, -1.0_0_0_0]      )
      assert np.abs(audio_slice.flatten() - expected_slice      ).max() < 1E-2

  @skip_mps
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return super().test_save_load_local()

  @skip_mps
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3      )

  @skip_mps
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return super().test_save_load_optional_components()

  @skip_mps
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return super().test_attention_slicing_forward_pass()







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      super().test_inference_batch_single_identical(expected_max_diff=3E-3      )







@slow
@require_torch_gpu
class 	__UpperCamelCase    (    unittest.TestCase						):

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    torch_device

      _lowerCAmelCase       :   int  =    DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'      )
      _lowerCAmelCase       :   int  =    pipe.to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   Optional[int]  =    torch.manual_seed(0      )
      _lowerCAmelCase       :   str  =    pipe(generator=_A    ,num_inference_steps=100    ,audio_length_in_s=4.0_9_6      )
      _lowerCAmelCase       :   str  =    output.audios

      _lowerCAmelCase       :   List[str]  =    audio[0, -3:, -3:]

      assert audio.shape == (1, 2, pipe.unet.sample_size)
      _lowerCAmelCase       :   Union[str, Any]  =    np.array([-0.0_1_9_2, -0.0_2_3_1, -0.0_3_1_8, -0.0_0_5_9, 0.0_0_0_2, -0.0_0_2_0]      )

      assert np.abs(audio_slice.flatten() - expected_slice      ).max() < 1E-2







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    torch_device

      _lowerCAmelCase       :   Tuple  =    DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'    ,torch_dtype=torch.floataa      )
      _lowerCAmelCase       :   Optional[int]  =    pipe.to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   Union[str, Any]  =    torch.manual_seed(0      )
      _lowerCAmelCase       :   Optional[int]  =    pipe(generator=_A    ,num_inference_steps=100    ,audio_length_in_s=4.0_9_6      )
      _lowerCAmelCase       :   Union[str, Any]  =    output.audios

      _lowerCAmelCase       :   int  =    audio[0, -3:, -3:]

      assert audio.shape == (1, 2, pipe.unet.sample_size)
      _lowerCAmelCase       :   List[str]  =    np.array([-0.0_3_6_7, -0.0_4_8_8, -0.0_7_7_1, -0.0_5_2_5, -0.0_4_4_4, -0.0_3_4_1]      )

      assert np.abs(audio_slice.flatten() - expected_slice      ).max() < 1E-2








"""simple docstring"""






import argparse
import json
from typing import List

from ltp import LTP

from transformers import BertTokenizer

def 		lowerCamelCase__		(					_lowerCamelCase   ):

    '''simple docstring'''



    if (
        (cp >= 0X4E00 and cp <= 0X9FFF)
        or (cp >= 0X3400 and cp <= 0X4DBF)  #
        or (cp >= 0X20000 and cp <= 0X2A6DF)  #
        or (cp >= 0X2A700 and cp <= 0X2B73F)  #
        or (cp >= 0X2B740 and cp <= 0X2B81F)  #
        or (cp >= 0X2B820 and cp <= 0X2CEAF)  #
        or (cp >= 0XF900 and cp <= 0XFAFF)
        or (cp >= 0X2F800 and cp <= 0X2FA1F)  #
    ):  #
        return True

    return False

def 		lowerCamelCase__		(					_lowerCamelCase   ):

    '''simple docstring'''



    for char in word:
        _lowerCAmelCase       :   Dict  =    ord(_lowerCamelCase   )
        if not _is_chinese_char(_lowerCamelCase   ):
            return 0
    return 1

def 		lowerCamelCase__		(					_lowerCamelCase   ):

    '''simple docstring'''



    _lowerCAmelCase       :   Tuple  =    set()

    for token in tokens:
        _lowerCAmelCase       :   Optional[int]  =    len(_lowerCamelCase   ) > 1 and is_chinese(_lowerCamelCase   )
        if chinese_word:
            word_set.add(_lowerCamelCase   )
    _lowerCAmelCase       :   Union[str, Any]  =    list(_lowerCamelCase   )
    return word_list

def 		lowerCamelCase__		(					_lowerCamelCase ,   _lowerCamelCase   ):

    '''simple docstring'''



    if not chinese_word_set:
        return bert_tokens
    _lowerCAmelCase       :   Optional[Any]  =    max([len(_lowerCamelCase   ) for w in chinese_word_set]   )

    _lowerCAmelCase       :   str  =    bert_tokens
    _lowerCAmelCase,					_lowerCAmelCase       :   Optional[Any]  =    0, len(_lowerCamelCase   )
    while start < end:
        _lowerCAmelCase       :   Dict  =    True
        if is_chinese(bert_word[start]   ):
            _lowerCAmelCase       :   str  =    min(end - start ,   _lowerCamelCase   )
            for i in range(_lowerCamelCase ,   1 ,   -1   ):
                _lowerCAmelCase       :   List[Any]  =    ''.join(bert_word[start : start + i]   )
                if whole_word in chinese_word_set:
                    for j in range(start + 1 ,   start + i   ):
                        _lowerCAmelCase       :   Tuple  =    '##' + bert_word[j]
                    _lowerCAmelCase       :   Optional[int]  =    start + i
                    _lowerCAmelCase       :   Any  =    False
                    break
        if single_word:
            start += 1
    return bert_word

def 		lowerCamelCase__		(					_lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase   ):

    '''simple docstring'''



    _lowerCAmelCase       :   Dict  =    []

    for i in range(0 ,   len(_lowerCamelCase   ) ,   100   ):
        _lowerCAmelCase       :   Tuple  =    ltp_tokenizer.seg(lines[i : i + 100]   )[0]
        _lowerCAmelCase       :   List[Any]  =    [get_chinese_word(_lowerCamelCase   ) for r in res]
        ltp_res.extend(_lowerCamelCase   )
    assert len(_lowerCamelCase   ) == len(_lowerCamelCase   )

    _lowerCAmelCase       :   int  =    []
    for i in range(0 ,   len(_lowerCamelCase   ) ,   100   ):
        _lowerCAmelCase       :   Dict  =    bert_tokenizer(lines[i : i + 100] ,   add_special_tokens=_lowerCamelCase ,   truncation=_lowerCamelCase ,   max_length=512   )
        bert_res.extend(res['input_ids']   )
    assert len(_lowerCamelCase   ) == len(_lowerCamelCase   )

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

    assert len(_lowerCamelCase   ) == len(_lowerCamelCase   )

    return ref_ids

def 		lowerCamelCase__		(					_lowerCamelCase   ):

    '''simple docstring'''



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

    _lowerCAmelCase       :   Optional[Any]  =    prepare_ref(_lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase   )

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


if __name__ == "__main__":
 _lowerCAmelCase						=		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""")

 _lowerCAmelCase						=		parser.parse_args()
 main(args)





