






'''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 		lowerCamelCase__      (						A	,   unittest.TestCase     ):




					'''simple docstring'''



					A_						    =						DanceDiffusionPipeline
					A_						    =						UNCONDITIONAL_AUDIO_GENERATION_PARAMS
					A_						    =						PipelineTesterMixin.required_optional_params - {
					    """callback""",
					    """latents""",
					    """callback_steps""",
					    """output_type""",
					    """num_images_per_prompt""",
					}
					A_						    =						UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
					A_						    =						False
					A_						    =						False




					def 						__UpperCAmelCase     (  self				:	Dict					)  ->       Tuple:



						'''simple docstring'''





						torch.manual_seed(0					)
						_lowercase					:       List[str]       =		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=UpperCamelCase_     ,  use_timestep_embedding=UpperCamelCase_     ,  time_embedding_type='fourier'     ,  mid_block_type='UNetMidBlock1D'     ,  down_block_types=('DownBlock1DNoSkip', 'DownBlock1D', 'AttnDownBlock1D')     ,  up_block_types=('AttnUpBlock1D', 'UpBlock1D', 'UpBlock1DNoSkip')     ,  )
						_lowercase					:       List[str]       =		IPNDMScheduler()

						_lowercase					:       Tuple       =		{
						    'unet': unet,
						    'scheduler': scheduler,
						}
						return components




					def 						__UpperCAmelCase     (  self				:	Optional[Any]     ,  UpperCamelCase_				:	Any     ,  UpperCamelCase_				:	Any=0					)  ->       List[Any]:



						'''simple docstring'''





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




					def 						__UpperCAmelCase     (  self				:	Any					)  ->       List[Any]:



						'''simple docstring'''





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

						_lowercase					:       str       =		self.get_dummy_inputs(UpperCamelCase_					)
						_lowercase					:       Optional[Any]       =		pipe(**UpperCamelCase_					)
						_lowercase					:       Any       =		output.audios

						_lowercase					:       Dict       =		audio[0, -3:, -3:]

						assert audio.shape == (1, 2, components["unet"].sample_size)
						_lowercase					:       Union[str, Any]       =		np.array([-0.72_65, 1.00_00, -0.83_88, 0.11_75, 0.94_98, -1.00_00]					)
						assert np.abs(audio_slice.flatten() - expected_slice					).max() < 1E-2




					@skip_mps
					def 						__UpperCAmelCase     (  self				:	Dict					)  ->       int:



						'''simple docstring'''





						return super().test_save_load_local()




					@skip_mps
					def 						__UpperCAmelCase     (  self				:	int					)  ->       Any:



						'''simple docstring'''





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




					@skip_mps
					def 						__UpperCAmelCase     (  self				:	str					)  ->       List[str]:



						'''simple docstring'''





						return super().test_save_load_optional_components()




					@skip_mps
					def 						__UpperCAmelCase     (  self				:	int					)  ->       str:



						'''simple docstring'''





						return super().test_attention_slicing_forward_pass()




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



						'''simple docstring'''





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






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




					'''simple docstring'''



					def 						__UpperCAmelCase     (  self				:	int					)  ->       Dict:



						'''simple docstring'''





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




					def 						__UpperCAmelCase     (  self				:	Dict					)  ->       str:



						'''simple docstring'''





						_lowercase					:       int       =		torch_device

						_lowercase					:       Tuple       =		DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'					)
						_lowercase					:       Dict       =		pipe.to(UpperCamelCase_					)
						pipe.set_progress_bar_config(disable=UpperCamelCase_					)

						_lowercase					:       int       =		torch.manual_seed(0					)
						_lowercase					:       Dict       =		pipe(generator=UpperCamelCase_     ,  num_inference_steps=100     ,  audio_length_in_s=4.0_96					)
						_lowercase					:       Union[str, Any]       =		output.audios

						_lowercase					:       Union[str, Any]       =		audio[0, -3:, -3:]

						assert audio.shape == (1, 2, pipe.unet.sample_size)
						_lowercase					:       List[str]       =		np.array([-0.01_92, -0.02_31, -0.03_18, -0.00_59, 0.00_02, -0.00_20]					)

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




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



						'''simple docstring'''





						_lowercase					:       int       =		torch_device

						_lowercase					:       int       =		DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'     ,  torch_dtype=torch.floataa					)
						_lowercase					:       Union[str, Any]       =		pipe.to(UpperCamelCase_					)
						pipe.set_progress_bar_config(disable=UpperCamelCase_					)

						_lowercase					:       Union[str, Any]       =		torch.manual_seed(0					)
						_lowercase					:       List[str]       =		pipe(generator=UpperCamelCase_     ,  num_inference_steps=100     ,  audio_length_in_s=4.0_96					)
						_lowercase					:       Any       =		output.audios

						_lowercase					:       Any       =		audio[0, -3:, -3:]

						assert audio.shape == (1, 2, pipe.unet.sample_size)
						_lowercase					:       Dict       =		np.array([-0.03_67, -0.04_88, -0.07_71, -0.05_25, -0.04_44, -0.03_41]					)

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





'''simple docstring'''

from __future__ import annotations

import math
from collections import Counter
from string import ascii_lowercase







def 						__UpperCamelCase				(							_lowercase					) ->			None:
	_lowercase  ,    _lowercase					:       List[Any]       =		analyze_text(_lowercase					)
	_lowercase					:       Any       =		list(' ' + ascii_lowercase					)
	# what is our total sum of probabilities.
	_lowercase					:       Union[str, Any]       =		sum(single_char_strings.values()					)

	# one length string
	_lowercase					:       Union[str, Any]       =		0
	# for each alpha we go in our dict and if it is in it we calculate entropy
	for ch in my_alphas:
		if ch in single_char_strings:
			_lowercase					:       Any       =		single_char_strings[ch]
			_lowercase					:       int       =		my_str / all_sum
			my_fir_sum += prob * math.loga(_lowercase					)  # entropy formula.

    # print entropy
	print(f'''{round(-1 * my_fir_sum					):.1f}'''					)

	# two len string
	_lowercase					:       str       =		sum(two_char_strings.values()					)
	_lowercase					:       str       =		0
	# for each alpha (two in size) calculate entropy.
	for cha in my_alphas:
		for cha in my_alphas:
			_lowercase					:       Optional[Any]       =		cha + cha
			if sequence in two_char_strings:
				_lowercase					:       int       =		two_char_strings[sequence]
				_lowercase					:       Optional[int]       =		int(_lowercase					) / all_sum
				my_sec_sum += prob * math.loga(_lowercase					)

    # print second entropy
	print(f'''{round(-1 * my_sec_sum					):.1f}'''					)

	# print the difference between them
	print(f'''{round((-1 * my_sec_sum) - (-1 * my_fir_sum)					):.1f}'''					)







def 						__UpperCamelCase				(							_lowercase					) ->			tuple[dict, dict]:
	_lowercase					:       Optional[Any]       =		Counter()  # type: ignore
	_lowercase					:       List[Any]       =		Counter()  # type: ignore
	single_char_strings[text[-1]] += 1

	# first case when we have space at start.
	two_char_strings[" " + text[0]] += 1
	for i in range(0,				len(_lowercase					) - 1					):
		single_char_strings[text[i]] += 1
		two_char_strings[text[i : i + 2]] += 1
	return single_char_strings, two_char_strings







def 						__UpperCamelCase				(							) ->			List[Any]:
	import doctest

	doctest.testmod()
	# text = (
	#     "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark "
	#     "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest "
	#     "jointure saw horrible. He private he on be imagine suppose. Fertile "
	#     "beloved evident through no service elderly is. Blind there if every no so "
	#     "at. Own neglected you preferred way sincerity delivered his attempted. To "
	#     "of message cottage windows do besides against uncivil.  Delightful "
	#     "unreserved impossible few estimating men favourable see entreaties. She "
	#     "propriety immediate was improving. He or entrance humoured likewise "
	#     "moderate. Much nor game son say feel. Fat make met can must form into "
	#     "gate. Me we offending prevailed discovery. "
	# )

	# calculate_prob(text)


if __name__ == "__main__":
		main()
