




import random
import shutil
import tempfile
import unittest

import numpy as np

from transformers import TaTokenizer, TaTokenizerFast
from transformers.testing_utils import require_sentencepiece, require_torch
from transformers.utils.import_utils import is_speech_available, is_torch_available


if is_torch_available():
						pass

if is_speech_available():
						from transformers import EncodecFeatureExtractor, MusicgenProcessor


__a  :		Tuple		     =   random.Random()
def  snake_case_					(		SCREAMING_SNAKE_CASE_    ,SCREAMING_SNAKE_CASE_=1.0    ,SCREAMING_SNAKE_CASE_=None    ,SCREAMING_SNAKE_CASE_=None    )      ->			List[Any]:
							if rng is None:
														lowercase__  :	Union[str, Any]        =							global_rng

							lowercase__  :	str        =							[]
							for batch_idx in range(shape[0]    ):
														values.append([]    )
														for _ in range(shape[1]    ):
																					values[-1].append(rng.random() * scale    )

							return values







@require_torch
@require_sentencepiece
class 				UpperCAmelCase(					unittest.TestCase					):



	"""simple docstring"""






	def    __a     (					self    ) ->      int:





								"""simple docstring"""


								lowercase__  :	str        =							"facebook/musicgen-small"
								lowercase__  :	Optional[Any]        =							tempfile.mkdtemp()

	def    __a     (					self	,				**lowerCamelCase    ) ->      int:





								"""simple docstring"""


								return TaTokenizer.from_pretrained(self.checkpoint	,				**lowerCamelCase    )

	def    __a     (					self	,				**lowerCamelCase    ) ->      Union[str, Any]:





								"""simple docstring"""


								return EncodecFeatureExtractor.from_pretrained(self.checkpoint	,				**lowerCamelCase    )

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





								"""simple docstring"""


								shutil.rmtree(self.tmpdirname    )

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





								"""simple docstring"""


								lowercase__  :	List[str]        =							self.get_tokenizer()
								lowercase__  :	Tuple        =							self.get_feature_extractor()

								lowercase__  :	int        =							MusicgenProcessor(tokenizer=lowerCamelCase	,				feature_extractor=lowerCamelCase    )

								processor.save_pretrained(self.tmpdirname    )
								lowercase__  :	Tuple        =							MusicgenProcessor.from_pretrained(self.tmpdirname    )

								self.assertEqual(processor.tokenizer.get_vocab()	,				tokenizer.get_vocab()    )
								self.assertIsInstance(processor.tokenizer	,				lowerCamelCase    )

								self.assertEqual(processor.feature_extractor.to_json_string()	,				feature_extractor.to_json_string()    )
								self.assertIsInstance(processor.feature_extractor	,				lowerCamelCase    )

	def    __a     (					self    ) ->      Optional[int]:





								"""simple docstring"""


								lowercase__  :	Dict        =							MusicgenProcessor(tokenizer=self.get_tokenizer()	,				feature_extractor=self.get_feature_extractor()    )
								processor.save_pretrained(self.tmpdirname    )

								lowercase__  :	List[str]        =							self.get_tokenizer(bos_token="(BOS)"	,				eos_token="(EOS)"    )
								lowercase__  :	List[Any]        =							self.get_feature_extractor(do_normalize=lowerCamelCase	,				padding_value=1.0    )

								lowercase__  :	str        =							MusicgenProcessor.from_pretrained(
								    self.tmpdirname	,				bos_token="(BOS)"	,				eos_token="(EOS)"	,				do_normalize=lowerCamelCase	,				padding_value=1.0    )

								self.assertEqual(processor.tokenizer.get_vocab()	,				tokenizer_add_kwargs.get_vocab()    )
								self.assertIsInstance(processor.tokenizer	,				lowerCamelCase    )

								self.assertEqual(processor.feature_extractor.to_json_string()	,				feature_extractor_add_kwargs.to_json_string()    )
								self.assertIsInstance(processor.feature_extractor	,				lowerCamelCase    )

	def    __a     (					self    ) ->      Dict:





								"""simple docstring"""


								lowercase__  :	Any        =							self.get_feature_extractor()
								lowercase__  :	str        =							self.get_tokenizer()

								lowercase__  :	Optional[Any]        =							MusicgenProcessor(tokenizer=lowerCamelCase	,				feature_extractor=lowerCamelCase    )

								lowercase__  :	List[str]        =							floats_list((3, 1000)    )

								lowercase__  :	Dict        =							feature_extractor(lowerCamelCase	,				return_tensors="np"    )
								lowercase__  :	str        =							processor(lowerCamelCase	,				return_tensors="np"    )

								for key in input_feat_extract.keys():
															self.assertAlmostEqual(input_feat_extract[key].sum()	,				input_processor[key].sum()	,				delta=1E-2    )

	def    __a     (					self    ) ->      Dict:





								"""simple docstring"""


								lowercase__  :	Optional[int]        =							self.get_feature_extractor()
								lowercase__  :	List[Any]        =							self.get_tokenizer()

								lowercase__  :	List[Any]        =							MusicgenProcessor(tokenizer=lowerCamelCase	,				feature_extractor=lowerCamelCase    )

								lowercase__  :	int        =							"This is a test string"

								lowercase__  :	Tuple        =							processor(text=lowerCamelCase    )

								lowercase__  :	Tuple        =							tokenizer(lowerCamelCase    )

								for key in encoded_tok.keys():
															self.assertListEqual(encoded_tok[key]	,				encoded_processor[key]    )

	def    __a     (					self    ) ->      str:





								"""simple docstring"""


								lowercase__  :	List[str]        =							self.get_feature_extractor()
								lowercase__  :	int        =							self.get_tokenizer()

								lowercase__  :	List[str]        =							MusicgenProcessor(tokenizer=lowerCamelCase	,				feature_extractor=lowerCamelCase    )

								lowercase__  :	Tuple        =							[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

								lowercase__  :	List[str]        =							processor.batch_decode(sequences=lowerCamelCase    )
								lowercase__  :	List[str]        =							tokenizer.batch_decode(lowerCamelCase    )

								self.assertListEqual(lowerCamelCase	,				lowerCamelCase    )

	def    __a     (					self    ) ->      Dict:





								"""simple docstring"""


								lowercase__  :	int        =							self.get_feature_extractor()
								lowercase__  :	Optional[Any]        =							self.get_tokenizer()

								lowercase__  :	List[Any]        =							MusicgenProcessor(tokenizer=lowerCamelCase	,				feature_extractor=lowerCamelCase    )

								self.assertListEqual(
								    processor.model_input_names	,				feature_extractor.model_input_names	,				msg="`processor` and `feature_extractor` model input names do not match"	,				)







	def    __a     (					self    ) ->      int:





								"""simple docstring"""


								lowercase__  :	Optional[Any]        =							self.get_feature_extractor(padding_side="left"    )
								lowercase__  :	Any        =							self.get_tokenizer()

								lowercase__  :	Any        =							MusicgenProcessor(tokenizer=lowerCamelCase	,				feature_extractor=lowerCamelCase    )

								lowercase__  :	Any        =							[floats_list((1, x)    )[0] for x in range(5	,				20	,				5    )]
								lowercase__  :	List[str]        =							processor(lowerCamelCase    ).padding_mask

								lowercase__  :	Optional[int]        =							np.asarray(floats_list((3, 20)    )    )[:, None, :]
								lowercase__  :	List[Any]        =							processor.batch_decode(lowerCamelCase	,				padding_mask=lowerCamelCase    )

								self.assertIsInstance(lowerCamelCase	,				lowerCamelCase    )

								for audio in decoded_audios:
															self.assertIsInstance(lowerCamelCase	,				np.ndarray    )

								self.assertTrue(decoded_audios[0].shape == (1, 10)    )
								self.assertTrue(decoded_audios[1].shape == (1, 15)    )
								self.assertTrue(decoded_audios[2].shape == (1, 20)    )





import hashlib
import importlib.util
import json
import os
import pathlib
from types import ModuleType

import pytest
import requests

__a  :		str		     =   pathlib.Path.cwd().joinpath('''project_euler''')
__a  :		Tuple		     =   pathlib.Path.cwd().joinpath(
    '''scripts''', '''project_euler_answers.json'''
)

with open(PROJECT_EULER_ANSWERS_PATH) as file_handle:
						__a  :		dict[str, str]		     =   json.load(file_handle)
def  snake_case_					(		SCREAMING_SNAKE_CASE_    )      ->			ModuleType:
							lowercase__  :	List[str]        =							importlib.util.spec_from_file_location(file_path.name    ,str(SCREAMING_SNAKE_CASE_    )    )
							lowercase__  :	int        =							importlib.util.module_from_spec(SCREAMING_SNAKE_CASE_    )  # type: ignore
							spec.loader.exec_module(SCREAMING_SNAKE_CASE_    )  # type: ignore
							return module
def  snake_case_					(		)      ->			list[pathlib.Path]:
							lowercase__  :	List[str]        =							[]
							for problem_dir_path in PROJECT_EULER_DIR_PATH.iterdir():
														if problem_dir_path.is_file() or problem_dir_path.name.startswith("_"    ):
																					continue
														for file_path in problem_dir_path.iterdir():
																					if file_path.suffix != ".py" or file_path.name.startswith(("_", "test")    ):
																												continue
																					solution_file_paths.append(SCREAMING_SNAKE_CASE_    )
							return solution_file_paths
def  snake_case_					(		)      ->			str:
							with open(os.environ["GITHUB_EVENT_PATH"]    ) as file:
														lowercase__  :	str        =							json.load(SCREAMING_SNAKE_CASE_    )
							return event["pull_request"]["url"] + "/files"
def  snake_case_					(		)      ->			list[pathlib.Path]:
							lowercase__  :	Optional[Any]        =							[]
							lowercase__  :	Dict        =							{
							    "Accept": "application/vnd.github.v3+json",
							    "Authorization": "token " + os.environ["GITHUB_TOKEN"],
							}
							lowercase__  :	Union[str, Any]        =							requests.get(get_files_url()    ,headers=SCREAMING_SNAKE_CASE_    ).json()
							for file in files:
														lowercase__  :	Optional[Any]        =							pathlib.Path.cwd().joinpath(file["filename"]    )
														if (
														    filepath.suffix != ".py"
														    or filepath.name.startswith(("_", "test")    )
														    or not filepath.name.startswith("sol"    )
														):
																					continue
														solution_file_paths.append(SCREAMING_SNAKE_CASE_    )
							return solution_file_paths
def  snake_case_					(		)      ->			list[pathlib.Path]:
							if os.environ.get("CI"    ) and os.environ.get("GITHUB_EVENT_NAME"    ) == "pull_request":
														# Return only if there are any, otherwise default to all solutions
														if filepaths := added_solution_file_path():
																					return filepaths
							return all_solution_file_paths()




@pytest.mark.parametrize(
    "solution_path"    ,collect_solution_file_paths()    ,ids=lambda SCREAMING_SNAKE_CASE_    : F"""{path.parent.name}/{path.name}"""    ,)
def  snake_case_					(		SCREAMING_SNAKE_CASE_    )      ->			None:
							lowercase__  :	str        =							solution_path.parent.name[8:].zfill(3    )
							lowercase__  :	str        =							PROBLEM_ANSWERS[problem_number]
							lowercase__  :	Optional[Any]        =							convert_path_to_module(SCREAMING_SNAKE_CASE_    )
							lowercase__  :	str        =							str(solution_module.solution()    )  # type: ignore
							lowercase__  :	List[str]        =							hashlib.shaaaa(answer.encode()    ).hexdigest()
							assert (
							    answer == expected
							), F"""Expected solution to {problem_number} to have hash {expected}, got {answer}"""