


"""simple docstring"""







import itertools
import os
import random
import tempfile
import unittest

import numpy as np

from transformers import TvltFeatureExtractor, is_datasets_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
		import torch

if is_datasets_available():
		from datasets import load_dataset

a__    :							Tuple            =					random.Random()




def        UpperCAmelCase__	(lowerCAmelCase_  ,						lowerCAmelCase_=1.0  ,						lowerCAmelCase_=None  ,						lowerCAmelCase_=None       ):




					'''simple docstring'''


					if rng is None:
										__SCREAMING_SNAKE_CASE						       =    global_rng

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

					return values




class 			UpperCamelCase_     (			unittest.TestCase):

	"""simple docstring"""





	def __init__(			self      :    int      ,      UpperCAmelCase__      :    str      ,      UpperCAmelCase__      :    Tuple=7      ,      UpperCAmelCase__      :    Optional[int]=4_0_0      ,      UpperCAmelCase__      :    Dict=2_0_0_0      ,      UpperCAmelCase__      :    Any=2_0_4_8      ,      UpperCAmelCase__      :    Any=1_2_8      ,      UpperCAmelCase__      :    List[Any]=1      ,      UpperCAmelCase__      :    List[Any]=5_1_2      ,      UpperCAmelCase__      :    int=3_0      ,      UpperCAmelCase__      :    Dict=4_4_1_0_0      ,      )	->     Union[str, Any]:
						__SCREAMING_SNAKE_CASE						       =    parent
						__SCREAMING_SNAKE_CASE						       =    batch_size
						__SCREAMING_SNAKE_CASE						       =    min_seq_length
						__SCREAMING_SNAKE_CASE						       =    max_seq_length
						__SCREAMING_SNAKE_CASE						       =    (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
						__SCREAMING_SNAKE_CASE						       =    spectrogram_length
						__SCREAMING_SNAKE_CASE						       =    feature_size
						__SCREAMING_SNAKE_CASE						       =    num_audio_channels
						__SCREAMING_SNAKE_CASE						       =    hop_length
						__SCREAMING_SNAKE_CASE						       =    chunk_length
						__SCREAMING_SNAKE_CASE						       =    sampling_rate




	def   UpperCAmelCase_				(			self      :    Optional[int]       )	->     str:
						return {
						    "spectrogram_length": self.spectrogram_length,
						    "feature_size": self.feature_size,
						    "num_audio_channels": self.num_audio_channels,
						    "hop_length": self.hop_length,
						    "chunk_length": self.chunk_length,
						    "sampling_rate": self.sampling_rate,
						}




	def   UpperCAmelCase_				(			self      :    List[str]      ,      UpperCAmelCase__      :    int=False      ,      UpperCAmelCase__      :    Optional[int]=False       )	->     List[Any]:
						def _flatten(UpperCAmelCase__      :    Dict       ):
											return list(itertools.chain(*UpperCAmelCase__       )       )

						if equal_length:
											__SCREAMING_SNAKE_CASE						       =    [floats_list((self.max_seq_length, self.feature_size)       ) for _ in range(self.batch_size       )]
						else:
											# make sure that inputs increase in size
											__SCREAMING_SNAKE_CASE						       =    [
											    floats_list((x, self.feature_size)       )
											    for x in range(self.min_seq_length      ,      self.max_seq_length      ,      self.seq_length_diff       )
											]
						if numpify:
											__SCREAMING_SNAKE_CASE						       =    [np.asarray(UpperCAmelCase__       ) for x in speech_inputs]
						return speech_inputs




@require_torch
@require_torchaudio
class 			UpperCamelCase_     (			UpperCamelCase      ,  unittest.TestCase):

	"""simple docstring"""





	snake_case__    :  int    =      TvltFeatureExtractor




	def   UpperCAmelCase_				(			self      :    List[str]       )	->     str:
						__SCREAMING_SNAKE_CASE						       =    TvltFeatureExtractionTester(self       )




	def   UpperCAmelCase_				(			self      :    Tuple       )	->     str:
						__SCREAMING_SNAKE_CASE						       =    self.feature_extraction_class(**self.feat_extract_dict       )
						self.assertTrue(hasattr(UpperCAmelCase__      ,      "spectrogram_length"       )       )
						self.assertTrue(hasattr(UpperCAmelCase__      ,      "feature_size"       )       )
						self.assertTrue(hasattr(UpperCAmelCase__      ,      "num_audio_channels"       )       )
						self.assertTrue(hasattr(UpperCAmelCase__      ,      "hop_length"       )       )
						self.assertTrue(hasattr(UpperCAmelCase__      ,      "chunk_length"       )       )
						self.assertTrue(hasattr(UpperCAmelCase__      ,      "sampling_rate"       )       )




	def   UpperCAmelCase_				(			self      :    Dict       )	->     str:
						__SCREAMING_SNAKE_CASE						       =    self.feature_extraction_class(**self.feat_extract_dict       )

						with tempfile.TemporaryDirectory() as tmpdirname:
											__SCREAMING_SNAKE_CASE						       =    feat_extract_first.save_pretrained(UpperCAmelCase__       )[0]
											check_json_file_has_correct_format(UpperCAmelCase__       )
											__SCREAMING_SNAKE_CASE						       =    self.feature_extraction_class.from_pretrained(UpperCAmelCase__       )

						__SCREAMING_SNAKE_CASE						       =    feat_extract_first.to_dict()
						__SCREAMING_SNAKE_CASE						       =    feat_extract_second.to_dict()
						__SCREAMING_SNAKE_CASE						       =    dict_first.pop("mel_filters"       )
						__SCREAMING_SNAKE_CASE						       =    dict_second.pop("mel_filters"       )
						self.assertTrue(np.allclose(UpperCAmelCase__      ,      UpperCAmelCase__       )       )
						self.assertEqual(UpperCAmelCase__      ,      UpperCAmelCase__       )




	def   UpperCAmelCase_				(			self      :    Optional[Any]       )	->     Any:
						__SCREAMING_SNAKE_CASE						       =    self.feature_extraction_class(**self.feat_extract_dict       )

						with tempfile.TemporaryDirectory() as tmpdirname:
											__SCREAMING_SNAKE_CASE						       =    os.path.join(UpperCAmelCase__      ,      "feat_extract.json"       )
											feat_extract_first.to_json_file(UpperCAmelCase__       )
											__SCREAMING_SNAKE_CASE						       =    self.feature_extraction_class.from_json_file(UpperCAmelCase__       )

						__SCREAMING_SNAKE_CASE						       =    feat_extract_first.to_dict()
						__SCREAMING_SNAKE_CASE						       =    feat_extract_second.to_dict()
						__SCREAMING_SNAKE_CASE						       =    dict_first.pop("mel_filters"       )
						__SCREAMING_SNAKE_CASE						       =    dict_second.pop("mel_filters"       )
						self.assertTrue(np.allclose(UpperCAmelCase__      ,      UpperCAmelCase__       )       )
						self.assertEqual(UpperCAmelCase__      ,      UpperCAmelCase__       )




	def   UpperCAmelCase_				(			self      :    Any       )	->     int:
						# Initialize feature_extractor
						__SCREAMING_SNAKE_CASE						       =    self.feature_extraction_class(**self.feat_extract_dict       )

						# create three inputs of length 800, 1000, and 1200
						__SCREAMING_SNAKE_CASE						       =    [floats_list((1, x)       )[0] for x in range(8_0_0      ,      1_4_0_0      ,      2_0_0       )]
						__SCREAMING_SNAKE_CASE						       =    [np.asarray(UpperCAmelCase__       ) for speech_input in speech_inputs]

						# Test not batched input
						__SCREAMING_SNAKE_CASE						       =    feature_extractor(np_speech_inputs[0]      ,      return_tensors="np"      ,      sampling_rate=4_4_1_0_0       ).audio_values

						self.assertTrue(encoded_audios.ndim == 4       )
						self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size       )
						self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length       )
						self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels       )

						# Test batched
						__SCREAMING_SNAKE_CASE						       =    feature_extractor(UpperCAmelCase__      ,      return_tensors="np"      ,      sampling_rate=4_4_1_0_0       ).audio_values

						self.assertTrue(encoded_audios.ndim == 4       )
						self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size       )
						self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length       )
						self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels       )

						# Test audio masking
						__SCREAMING_SNAKE_CASE						       =    feature_extractor(
						    UpperCAmelCase__      ,      return_tensors="np"      ,      sampling_rate=4_4_1_0_0      ,      mask_audio=UpperCAmelCase__       ).audio_values

						self.assertTrue(encoded_audios.ndim == 4       )
						self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size       )
						self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length       )
						self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels       )

						# Test 2-D numpy arrays are batched.
						__SCREAMING_SNAKE_CASE						       =    [floats_list((1, x)       )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
						__SCREAMING_SNAKE_CASE						       =    np.asarray(UpperCAmelCase__       )
						__SCREAMING_SNAKE_CASE						       =    feature_extractor(UpperCAmelCase__      ,      return_tensors="np"      ,      sampling_rate=4_4_1_0_0       ).audio_values
						self.assertTrue(encoded_audios.ndim == 4       )
						self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size       )
						self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length       )
						self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels       )




	def   UpperCAmelCase_				(			self      :    int      ,      UpperCAmelCase__      :    Any       )	->     Tuple:
						__SCREAMING_SNAKE_CASE						       =    load_dataset("hf-internal-testing/librispeech_asr_dummy"      ,      "clean"      ,      split="validation"       )
						# automatic decoding with librispeech
						__SCREAMING_SNAKE_CASE						       =    ds.sort("id"       ).select(range(UpperCAmelCase__       )       )[:num_samples]["audio"]

						return [x["array"] for x in speech_samples]




	def   UpperCAmelCase_				(			self      :    Optional[Any]       )	->     str:
						__SCREAMING_SNAKE_CASE						       =    self._load_datasamples(1       )
						__SCREAMING_SNAKE_CASE						       =    TvltFeatureExtractor()
						__SCREAMING_SNAKE_CASE						       =    feature_extractor(UpperCAmelCase__      ,      return_tensors="pt"       ).audio_values

						self.assertEquals(audio_values.shape      ,      (1, 1, 1_9_2, 1_2_8)       )

						__SCREAMING_SNAKE_CASE						       =    torch.tensor([[-0.3_032, -0.2_708], [-0.4_434, -0.4_007]]       )
						self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]      ,      UpperCAmelCase__      ,      atol=1E-4       )       )




"""simple docstring"""







from datetime import datetime

import requests




def        UpperCAmelCase__	(lowerCAmelCase_       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    "https://downloadgram.net/wp-json/wppress/video-downloader/video?url="
					__SCREAMING_SNAKE_CASE						       =    requests.get(base_url + url       ).json()[0]["urls"][0]["src"]
					return requests.get(lowerCAmelCase_       ).content


if __name__ == "__main__":
		a__    :							str            =					input('''Enter Video/IGTV url: ''').strip()
		a__    :							List[Any]            =					F"{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4"
		with open(file_name, '''wb''') as fp:
				fp.write(download_video(url))
		print(F"Done. Video saved to disk as {file_name}.")
