
from __future__ import annotations

import random

# Maximum size of the population.  Bigger could be faster but is more memory expensive.
UpperCAmelCase	      = 200
# Number of elements selected in every generation of evolution. The selection takes
# place from best to worst of that generation and must be smaller than N_POPULATION.
UpperCAmelCase	      = 50
# Probability that an element of a generation can mutate, changing one of its genes.
# This will guarantee that all genes will be used during evolution.
UpperCAmelCase	      = 0.4
# Just a seed to improve randomness required by the algorithm.
random.seed(random.randint(0, 1000))






def 							UpperCAmelCase_		(							__SCREAMING_SNAKE_CASE ,							__SCREAMING_SNAKE_CASE							):
	lowercase       =    len([g for position, g in enumerate(UpperCamelCase__							) if g == main_target[position]]							)
	return (item, float(UpperCamelCase__							))






def 							UpperCAmelCase_		(							__SCREAMING_SNAKE_CASE ,							__SCREAMING_SNAKE_CASE							):
	lowercase       =    random.randint(0 ,							len(UpperCamelCase__							) - 1							)
	lowercase       =    parent_a[:random_slice] + parent_a[random_slice:]
	lowercase       =    parent_a[:random_slice] + parent_a[random_slice:]
	return (child_a, child_a)






def 							UpperCAmelCase_		(							__SCREAMING_SNAKE_CASE ,							__SCREAMING_SNAKE_CASE							):
	lowercase       =    list(UpperCamelCase__							)
	if random.uniform(0 ,							1							) < MUTATION_PROBABILITY:
		lowercase       =    random.choice(UpperCamelCase__							)
	return "".join(UpperCamelCase__							)






def 							UpperCAmelCase_		(							__SCREAMING_SNAKE_CASE ,							__SCREAMING_SNAKE_CASE ,							__SCREAMING_SNAKE_CASE ,							):
	lowercase       =    []
	# Generate more children proportionally to the fitness score.
	lowercase       =    int(parent_a[1] * 100							) + 1
	lowercase       =    10 if child_n >= 10 else child_n
	for _ in range(UpperCamelCase__							):
		lowercase       =    population_score[random.randint(0 ,							UpperCamelCase__							)][0]

		lowercase  ,					lowercase       =    crossover(parent_a[0] ,							UpperCamelCase__							)
		# Append new string to the population list.
		pop.append(mutate(UpperCamelCase__ ,							UpperCamelCase__							)							)
		pop.append(mutate(UpperCamelCase__ ,							UpperCamelCase__							)							)
	return pop






def 							UpperCAmelCase_		(							__SCREAMING_SNAKE_CASE ,							__SCREAMING_SNAKE_CASE ,							__SCREAMING_SNAKE_CASE = True							):


	if N_POPULATION < N_SELECTED:
		lowercase       =    F'''{N_POPULATION} must be bigger than {N_SELECTED}'''
		raise ValueError(UpperCamelCase__							)
	# Verify that the target contains no genes besides the ones inside genes variable.
	lowercase       =    sorted({c for c in target if c not in genes}							)
	if not_in_genes_list:
		lowercase       =    F'''{not_in_genes_list} is not in genes list, evolution cannot converge'''
		raise ValueError(UpperCamelCase__							)

	# Generate random starting population.
	lowercase       =    []
	for _ in range(UpperCamelCase__							):
		population.append(''.join([random.choice(UpperCamelCase__							) for i in range(len(UpperCamelCase__							)							)]							)							)

	# Just some logs to know what the algorithms is doing.
	lowercase  ,					lowercase       =    0, 0

	# This loop will end when we find a perfect match for our target.
	while True:
		generation += 1
		total_population += len(UpperCamelCase__							)

		# Random population created. Now it's time to evaluate.

		# Adding a bit of concurrency can make everything faster,
		#
		# import concurrent.futures
		# population_score: list[tuple[str, float]] = []
		# with concurrent.futures.ThreadPoolExecutor(
		#                                   max_workers=NUM_WORKERS) as executor:
		#     futures = {executor.submit(evaluate, item) for item in population}
		#     concurrent.futures.wait(futures)
		#     population_score = [item.result() for item in futures]
		#
		# but with a simple algorithm like this, it will probably be slower.
		# We just need to call evaluate for every item inside the population.
		lowercase       =    [evaluate(UpperCamelCase__ ,							UpperCamelCase__							) for item in population]

		# Check if there is a matching evolution.
		lowercase       =    sorted(UpperCamelCase__ ,							key=lambda __SCREAMING_SNAKE_CASE							: x[1] ,							reverse=UpperCamelCase__							)
		if population_score[0][0] == target:
			return (generation, total_population, population_score[0][0])

		# Print the best result every 10 generation.
		# Just to know that the algorithm is working.
		if debug and generation % 10 == 0:
			print(
			    F'''\nGeneration: {generation}'''
			    F'''\nTotal Population:{total_population}'''
			    F'''\nBest score: {population_score[0][1]}'''
			    F'''\nBest string: {population_score[0][0]}'''							)

		# Flush the old population, keeping some of the best evolutions.
		# Keeping this avoid regression of evolution.
		lowercase       =    population[: int(N_POPULATION / 3							)]
		population.clear()
		population.extend(UpperCamelCase__							)
		# Normalize population score to be between 0 and 1.
		lowercase       =    [
		    (item, score / len(UpperCamelCase__							)) for item, score in population_score
		]

		# This is selection
		for i in range(UpperCamelCase__							):
			population.extend(select(population_score[int(UpperCamelCase__							)] ,							UpperCamelCase__ ,							UpperCamelCase__							)							)
			# Check if the population has already reached the maximum value and if so,
			# break the cycle.  If this check is disabled, the algorithm will take
			# forever to compute large strings, but will also calculate small strings in
			# a far fewer generations.
			if len(UpperCamelCase__							) > N_POPULATION:
				break


if __name__ == "__main__":
	UpperCAmelCase	      = (
	    '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!'''
	)
	UpperCAmelCase	      = list(
	    ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm'''
	    '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\'''
	)
	UpperCAmelCase      , UpperCAmelCase      , UpperCAmelCase	      = basic(target_str, genes_list)
	print(
	    F"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}"""
	)







import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import TimesformerConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch
					from torch import nn

					from transformers import (
					    MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
					    TimesformerForVideoClassification,
					    TimesformerModel,
					)
					from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from transformers import VideoMAEImageProcessor







class     __lowerCAmelCase :

			"""simple docstring"""







			def __init__(      self			,						lowerCamelCase__			,						lowerCamelCase__=13			,						lowerCamelCase__=10			,						lowerCamelCase__=3			,						lowerCamelCase__=2			,						lowerCamelCase__=2			,						lowerCamelCase__=True			,						lowerCamelCase__=True			,						lowerCamelCase__=32			,						lowerCamelCase__=5			,						lowerCamelCase__=4			,						lowerCamelCase__=37			,						lowerCamelCase__="gelu"			,						lowerCamelCase__=0.1			,						lowerCamelCase__=0.1			,						lowerCamelCase__=10			,						lowerCamelCase__=0.02			,						lowerCamelCase__="divided_space_time"			,						lowerCamelCase__=None			,						)    ->      Any:



							'''simple docstring'''
							__lowerCamelCase		       =    parent
							__lowerCamelCase		       =    batch_size
							__lowerCamelCase		       =    image_size
							__lowerCamelCase		       =    num_channels
							__lowerCamelCase		       =    patch_size
							__lowerCamelCase		       =    num_frames
							__lowerCamelCase		       =    is_training
							__lowerCamelCase		       =    use_labels
							__lowerCamelCase		       =    hidden_size
							__lowerCamelCase		       =    num_hidden_layers
							__lowerCamelCase		       =    num_attention_heads
							__lowerCamelCase		       =    intermediate_size
							__lowerCamelCase		       =    hidden_act
							__lowerCamelCase		       =    hidden_dropout_prob
							__lowerCamelCase		       =    attention_probs_dropout_prob
							__lowerCamelCase		       =    attention_type
							__lowerCamelCase		       =    initializer_range
							__lowerCamelCase		       =    scope
							__lowerCamelCase		       =    num_labels

							# in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
							__lowerCamelCase		       =    (image_size // patch_size) ** 2
							__lowerCamelCase		       =    (num_frames) * self.num_patches_per_frame + 1


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



							'''simple docstring'''
							__lowerCamelCase		       =    floats_tensor(
							    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]							)

							__lowerCamelCase		       =    None
							if self.use_labels:
											__lowerCamelCase		       =    ids_tensor([self.batch_size]			,						self.num_labels							)

							__lowerCamelCase		       =    self.get_config()

							return config, pixel_values, labels


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



							'''simple docstring'''
							__lowerCamelCase		       =    TimesformerConfig(
							    image_size=self.image_size			,						patch_size=self.patch_size			,						num_channels=self.num_channels			,						num_frames=self.num_frames			,						hidden_size=self.hidden_size			,						num_hidden_layers=self.num_hidden_layers			,						num_attention_heads=self.num_attention_heads			,						intermediate_size=self.intermediate_size			,						hidden_act=self.hidden_act			,						hidden_dropout_prob=self.hidden_dropout_prob			,						attention_probs_dropout_prob=self.attention_probs_dropout_prob			,						initializer_range=self.initializer_range			,						attention_type=self.attention_type			,						)
							__lowerCamelCase		       =    self.num_labels
							return config


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Tuple:



							'''simple docstring'''
							__lowerCamelCase		       =    TimesformerModel(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    model(lowerCamelCase__							)
							self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)							)


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



							'''simple docstring'''
							__lowerCamelCase		       =    TimesformerForVideoClassification(lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()

							__lowerCamelCase		       =    model(lowerCamelCase__							)

							# verify the logits shape
							__lowerCamelCase		       =    torch.Size((self.batch_size, self.num_labels)							)
							self.parent.assertEqual(result.logits.shape			,						lowerCamelCase__							)






			def       lowercase_    (      self							)    ->      Tuple:



							'''simple docstring'''
							__lowerCamelCase		       =    self.prepare_config_and_inputs()
							__lowerCamelCase       ,						__lowerCamelCase       ,						__lowerCamelCase		       =    config_and_inputs
							__lowerCamelCase		       =    {'pixel_values': pixel_values}
							return config, inputs_dict







@require_torch
class     __lowerCAmelCase (       __magic_name__			,				__magic_name__			,				unittest.TestCase ):

			"""simple docstring"""







			snake_case_   		=       (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
			snake_case_   		=       (
			    {'''feature-extraction''': TimesformerModel, '''video-classification''': TimesformerForVideoClassification}
			    if is_torch_available()
			    else {}
			)

			snake_case_   		=       False
			snake_case_   		=       False
			snake_case_   		=       False
			snake_case_   		=       False


			def       lowercase_    (      self							)    ->      List[str]:



							'''simple docstring'''
							__lowerCamelCase		       =    TimesformerModelTester(self							)
							__lowerCamelCase		       =    ConfigTester(
							    self			,						config_class=lowerCamelCase__			,						has_text_modality=lowerCamelCase__			,						hidden_size=37							)


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__=False							)    ->      int:



							'''simple docstring'''
							__lowerCamelCase		       =    copy.deepcopy(lowerCamelCase__							)

							if return_labels:
											if model_class in get_values(lowerCamelCase__							):
															__lowerCamelCase		       =    torch.zeros(
															    self.model_tester.batch_size			,						dtype=torch.long			,						device=lowerCamelCase__							)

							return inputs_dict


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



							'''simple docstring'''
							self.config_tester.run_common_tests()


			@unittest.skip(reason='TimeSformer does not use inputs_embeds'							)
			def       lowercase_    (      self							)    ->      List[str]:



							'''simple docstring'''
							pass


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



							'''simple docstring'''
							__lowerCamelCase       ,						__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											__lowerCamelCase		       =    model_class(lowerCamelCase__							)
											self.assertIsInstance(model.get_input_embeddings()			,						(nn.Module)							)
											__lowerCamelCase		       =    model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(lowerCamelCase__			,						nn.Linear							)							)


			def       lowercase_    (      self							)    ->      List[str]:



							'''simple docstring'''
							__lowerCamelCase       ,						__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											__lowerCamelCase		       =    model_class(lowerCamelCase__							)
											__lowerCamelCase		       =    inspect.signature(model.forward							)
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											__lowerCamelCase		       =    [*signature.parameters.keys()]

											__lowerCamelCase		       =    ['pixel_values']
											self.assertListEqual(arg_names[:1]			,						lowerCamelCase__							)


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



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase__							)


			def       lowercase_    (      self							)    ->      str:



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_video_classification(*lowerCamelCase__							)


			@slow
			def       lowercase_    (      self							)    ->      Dict:



							'''simple docstring'''
							for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCamelCase		       =    TimesformerModel.from_pretrained(lowerCamelCase__							)
											self.assertIsNotNone(lowerCamelCase__							)


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



							'''simple docstring'''
							if not self.has_attentions:
											pass

							else:
											__lowerCamelCase       ,						__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs_for_common()
											__lowerCamelCase		       =    True

											for model_class in self.all_model_classes:
															__lowerCamelCase		       =    self.model_tester.seq_length
															__lowerCamelCase		       =    self.model_tester.num_frames

															__lowerCamelCase		       =    True
															__lowerCamelCase		       =    False
															__lowerCamelCase		       =    True
															__lowerCamelCase		       =    model_class(lowerCamelCase__							)
															model.to(lowerCamelCase__							)
															model.eval()
															with torch.no_grad():
																			__lowerCamelCase		       =    model(**self._prepare_for_class(lowerCamelCase__			,						lowerCamelCase__							)							)
															__lowerCamelCase		       =    outputs.attentions
															self.assertEqual(len(lowerCamelCase__							)			,						self.model_tester.num_hidden_layers							)

															# check that output_attentions also work using config
															del inputs_dict["output_attentions"]
															__lowerCamelCase		       =    True
															__lowerCamelCase		       =    model_class(lowerCamelCase__							)
															model.to(lowerCamelCase__							)
															model.eval()
															with torch.no_grad():
																			__lowerCamelCase		       =    model(**self._prepare_for_class(lowerCamelCase__			,						lowerCamelCase__							)							)
															__lowerCamelCase		       =    outputs.attentions
															self.assertEqual(len(lowerCamelCase__							)			,						self.model_tester.num_hidden_layers							)

															# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
															self.assertListEqual(
															    list(attentions[0].shape[-3:]							)			,						[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]			,						)
															__lowerCamelCase		       =    len(lowerCamelCase__							)

															# Check attention is always last and order is fine
															__lowerCamelCase		       =    True
															__lowerCamelCase		       =    True
															__lowerCamelCase		       =    model_class(lowerCamelCase__							)
															model.to(lowerCamelCase__							)
															model.eval()
															with torch.no_grad():
																			__lowerCamelCase		       =    model(**self._prepare_for_class(lowerCamelCase__			,						lowerCamelCase__							)							)

															self.assertEqual(out_len + 1			,						len(lowerCamelCase__							)							)

															__lowerCamelCase		       =    outputs.attentions

															self.assertEqual(len(lowerCamelCase__							)			,						self.model_tester.num_hidden_layers							)

															# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
															self.assertListEqual(
															    list(self_attentions[0].shape[-3:]							)			,						[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]			,						)






			def       lowercase_    (      self							)    ->      Tuple:



							'''simple docstring'''
							def check_hidden_states_output(lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							):
											__lowerCamelCase		       =    model_class(lowerCamelCase__							)
											model.to(lowerCamelCase__							)
											model.eval()

											with torch.no_grad():
															__lowerCamelCase		       =    model(**self._prepare_for_class(lowerCamelCase__			,						lowerCamelCase__							)							)

											__lowerCamelCase		       =    outputs.hidden_states
											__lowerCamelCase		       =    self.model_tester.num_hidden_layers + 1
											self.assertEqual(len(lowerCamelCase__							)			,						lowerCamelCase__							)

											__lowerCamelCase		       =    self.model_tester.seq_length

											self.assertListEqual(
											    list(hidden_states[0].shape[-2:]							)			,						[seq_length, self.model_tester.hidden_size]			,						)

							__lowerCamelCase       ,						__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											__lowerCamelCase		       =    True
											check_hidden_states_output(lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											__lowerCamelCase		       =    True

											check_hidden_states_output(lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)







def 			lowerCamelCase_		(       )     ->       Any:





				"""simple docstring"""


				__lowerCamelCase		       =    hf_hub_download(
				    repo_id='hf-internal-testing/spaghetti-video' ,     filename='eating_spaghetti.npy' ,     repo_type='dataset'      )
				__lowerCamelCase		       =    np.load(UpperCamelCase__      )
				return list(UpperCamelCase__      )







@require_torch
@require_vision
class     __lowerCAmelCase (       unittest.TestCase ):

			"""simple docstring"""







			@cached_property
			def       lowercase_    (      self							)    ->      List[Any]:



							'''simple docstring'''
							# logits were tested with a different mean and std, so we use the same here
							return (
							    VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]			,						image_std=[0.5, 0.5, 0.5]							)
							    if is_vision_available()
							    else None
							)






			@slow
			def       lowercase_    (      self							)    ->      List[str]:



							'''simple docstring'''
							__lowerCamelCase		       =    TimesformerForVideoClassification.from_pretrained('facebook/timesformer-base-finetuned-k400'							).to(
							    lowerCamelCase__							)

							__lowerCamelCase		       =    self.default_image_processor
							__lowerCamelCase		       =    prepare_video()
							__lowerCamelCase		       =    image_processor(video[:8]			,						return_tensors='pt'							).to(lowerCamelCase__							)

							# forward pass
							with torch.no_grad():
											__lowerCamelCase		       =    model(**lowerCamelCase__							)

							# verify the logits
							__lowerCamelCase		       =    torch.Size((1, 400)							)
							self.assertEqual(outputs.logits.shape			,						lowerCamelCase__							)

							__lowerCamelCase		       =    torch.tensor([-0.30_16, -0.77_13, -0.42_05]							).to(lowerCamelCase__							)

							self.assertTrue(torch.allclose(outputs.logits[0, :3]			,						lowerCamelCase__			,						atol=1e-4							)							)


