





"""simple docstring"""


import gc
import unittest

import numpy as np
import torch
import torch.nn.functional as F
from transformers import (
    ClapTextConfig,
    ClapTextModelWithProjection,
    RobertaTokenizer,
    SpeechTaHifiGan,
    SpeechTaHifiGanConfig,
)

from diffusers import (
    AudioLDMPipeline,
    AutoencoderKL,
    DDIMScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class      __SCREAMING_SNAKE_CASE    (						__lowercase		,  unittest.TestCase   ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:List[str]	     =					AudioLDMPipeline
  SCREAMING_SNAKE_CASE__							:int	     =					TEXT_TO_AUDIO_PARAMS
  SCREAMING_SNAKE_CASE__							:Dict	     =					TEXT_TO_AUDIO_BATCH_PARAMS
  SCREAMING_SNAKE_CASE__							:Optional[Any]	     =					frozenset(
      [
          "num_inference_steps",
          "num_waveforms_per_prompt",
          "generator",
          "latents",
          "output_type",
          "return_dict",
          "callback",
          "callback_steps",
      ]   )

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				Optional[int]:
        torch.manual_seed(0	)
        _UpperCamelCase      :	Dict						=       UNetaDConditionModel(
            block_out_channels=(32, 64)					,   layers_per_block=2					,   sample_size=32					,   in_channels=4					,   out_channels=4					,   down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")					,   up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")					,   cross_attention_dim=(32, 64)					,   class_embed_type="simple_projection"					,   projection_class_embeddings_input_dim=32					,   class_embeddings_concat=__a					,   )
        _UpperCamelCase      :	List[str]						=       DDIMScheduler(
            beta_start=0.0_00_85					,   beta_end=0.0_12					,   beta_schedule="scaled_linear"					,   clip_sample=__a					,   set_alpha_to_one=__a					,   )
        torch.manual_seed(0	)
        _UpperCamelCase      :	Any						=       AutoencoderKL(
            block_out_channels=[32, 64]					,   in_channels=1					,   out_channels=1					,   down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]					,   up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]					,   latent_channels=4					,   )
        torch.manual_seed(0	)
        _UpperCamelCase      :	List[Any]						=       ClapTextConfig(
            bos_token_id=0					,   eos_token_id=2					,   hidden_size=32					,   intermediate_size=37					,   layer_norm_eps=1e-0_5					,   num_attention_heads=4					,   num_hidden_layers=5					,   pad_token_id=1					,   vocab_size=1000					,   projection_dim=32					,   )
        _UpperCamelCase      :	Union[str, Any]						=       ClapTextModelWithProjection(__a	)
        _UpperCamelCase      :	List[Any]						=       RobertaTokenizer.from_pretrained("hf-internal-testing/tiny-random-roberta"					,   model_max_length=77	)

        _UpperCamelCase      :	List[Any]						=       SpeechTaHifiGanConfig(
            model_in_dim=8					,   sampling_rate=1_6000					,   upsample_initial_channel=16					,   upsample_rates=[2, 2]					,   upsample_kernel_sizes=[4, 4]					,   resblock_kernel_sizes=[3, 7]					,   resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]]					,   normalize_before=__a					,   )

        _UpperCamelCase      :	Optional[Any]						=       SpeechTaHifiGan(__a	)

        _UpperCamelCase      :	int						=       {
            """unet""": unet,
            """scheduler""": scheduler,
            """vae""": vae,
            """text_encoder""": text_encoder,
            """tokenizer""": tokenizer,
            """vocoder""": vocoder,
        }
        return components

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any					,   __a   :       Optional[Any]					,   __a   :       List[str]=0	)		->				Union[str, Any]:
        if str(__a	).startswith("mps"	):
              _UpperCamelCase      :	List[str]						=       torch.manual_seed(__a	)
        else:
              _UpperCamelCase      :	Optional[Any]						=       torch.Generator(device=__a	).manual_seed(__a	)
        _UpperCamelCase      :	Dict						=       {
            """prompt""": """A hammer hitting a wooden surface""",
            """generator""": generator,
            """num_inference_steps""": 2,
            """guidance_scale""": 6.0,
        }
        return inputs

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				Optional[Any]:
        _UpperCamelCase      :	List[Any]						=       """cpu"""  # ensure determinism for the device-dependent torch.Generator

        _UpperCamelCase      :	Optional[int]						=       self.get_dummy_components()
        _UpperCamelCase      :	List[str]						=       AudioLDMPipeline(**__a	)
        _UpperCamelCase      :	Tuple						=       audioldm_pipe.to(__a	)
        audioldm_pipe.set_progress_bar_config(disable=__a	)

        _UpperCamelCase      :	Optional[int]						=       self.get_dummy_inputs(__a	)
        _UpperCamelCase      :	List[Any]						=       audioldm_pipe(**__a	)
        _UpperCamelCase      :	Optional[Any]						=       output.audios[0]

        assert audio.ndim == 1
        assert len(__a	) == 256

        _UpperCamelCase      :	str						=       audio[:10]
        _UpperCamelCase      :	Any						=       np.array(
            [-0.00_50, 0.00_50, -0.00_60, 0.00_33, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_33]	)

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

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				Dict:
        _UpperCamelCase      :	str						=       self.get_dummy_components()
        _UpperCamelCase      :	int						=       AudioLDMPipeline(**__a	)
        _UpperCamelCase      :	Tuple						=       audioldm_pipe.to(__a	)
        _UpperCamelCase      :	int						=       audioldm_pipe.to(__a	)
        audioldm_pipe.set_progress_bar_config(disable=__a	)

        _UpperCamelCase      :	int						=       self.get_dummy_inputs(__a	)
        _UpperCamelCase      :	Optional[int]						=       3 * [inputs["""prompt"""]]

        # forward
        _UpperCamelCase      :	Union[str, Any]						=       audioldm_pipe(**__a	)
        _UpperCamelCase      :	List[Any]						=       output.audios[0]

        _UpperCamelCase      :	Optional[int]						=       self.get_dummy_inputs(__a	)
        _UpperCamelCase      :	Tuple						=       3 * [inputs.pop("prompt"	)]

        _UpperCamelCase      :	Dict						=       audioldm_pipe.tokenizer(
            __a					,   padding="max_length"					,   max_length=audioldm_pipe.tokenizer.model_max_length					,   truncation=__a					,   return_tensors="pt"					,   )
        _UpperCamelCase      :	List[Any]						=       text_inputs["""input_ids"""].to(__a	)

        _UpperCamelCase      :	List[str]						=       audioldm_pipe.text_encoder(
            __a					,   )
        _UpperCamelCase      :	Any						=       prompt_embeds.text_embeds
        # additional L_2 normalization over each hidden-state
        _UpperCamelCase      :	List[str]						=       F.normalize(__a					,   dim=-1	)

        _UpperCamelCase      :	str						=       prompt_embeds

        # forward
        _UpperCamelCase      :	Dict						=       audioldm_pipe(**__a	)
        _UpperCamelCase      :	List[Any]						=       output.audios[0]

        assert np.abs(audio_a - audio_a	).max() < 1e-2

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]	)		->				Union[str, Any]:
        _UpperCamelCase      :	str						=       self.get_dummy_components()
        _UpperCamelCase      :	List[Any]						=       AudioLDMPipeline(**__a	)
        _UpperCamelCase      :	List[Any]						=       audioldm_pipe.to(__a	)
        _UpperCamelCase      :	Tuple						=       audioldm_pipe.to(__a	)
        audioldm_pipe.set_progress_bar_config(disable=__a	)

        _UpperCamelCase      :	Optional[int]						=       self.get_dummy_inputs(__a	)
        _UpperCamelCase      :	Optional[Any]						=       3 * ["""this is a negative prompt"""]
        _UpperCamelCase      :	int						=       negative_prompt
        _UpperCamelCase      :	Optional[int]						=       3 * [inputs["""prompt"""]]

        # forward
        _UpperCamelCase      :	Any						=       audioldm_pipe(**__a	)
        _UpperCamelCase      :	Optional[Any]						=       output.audios[0]

        _UpperCamelCase      :	Any						=       self.get_dummy_inputs(__a	)
        _UpperCamelCase      :	List[Any]						=       3 * [inputs.pop("prompt"	)]

        _UpperCamelCase      :	int						=       []
        for p in [prompt, negative_prompt]:
              _UpperCamelCase      :	Any						=       audioldm_pipe.tokenizer(
                  __a					,   padding="max_length"					,   max_length=audioldm_pipe.tokenizer.model_max_length					,   truncation=__a					,   return_tensors="pt"					,   )
              _UpperCamelCase      :	Dict						=       text_inputs["""input_ids"""].to(__a	)

              _UpperCamelCase      :	List[Any]						=       audioldm_pipe.text_encoder(
                  __a					,   )
              _UpperCamelCase      :	Union[str, Any]						=       text_embeds.text_embeds
              # additional L_2 normalization over each hidden-state
              _UpperCamelCase      :	str						=       F.normalize(__a					,   dim=-1	)

              embeds.append(__a	)

        _UpperCamelCase      :	Union[str, Any]						=       embeds

        # forward
        _UpperCamelCase      :	List[str]						=       audioldm_pipe(**__a	)
        _UpperCamelCase      :	List[str]						=       output.audios[0]

        assert np.abs(audio_a - audio_a	).max() < 1e-2

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				List[str]:
        _UpperCamelCase      :	int						=       """cpu"""  # ensure determinism for the device-dependent torch.Generator
        _UpperCamelCase      :	Dict						=       self.get_dummy_components()
        _UpperCamelCase      :	List[Any]						=       PNDMScheduler(skip_prk_steps=__a	)
        _UpperCamelCase      :	Optional[Any]						=       AudioLDMPipeline(**__a	)
        _UpperCamelCase      :	int						=       audioldm_pipe.to(__a	)
        audioldm_pipe.set_progress_bar_config(disable=__a	)

        _UpperCamelCase      :	List[Any]						=       self.get_dummy_inputs(__a	)
        _UpperCamelCase      :	Any						=       """egg cracking"""
        _UpperCamelCase      :	str						=       audioldm_pipe(**__a					,   negative_prompt=__a	)
        _UpperCamelCase      :	Optional[Any]						=       output.audios[0]

        assert audio.ndim == 1
        assert len(__a	) == 256

        _UpperCamelCase      :	int						=       audio[:10]
        _UpperCamelCase      :	List[Any]						=       np.array(
            [-0.00_51, 0.00_50, -0.00_60, 0.00_34, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_32]	)

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

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Union[str, Any]:
        _UpperCamelCase      :	int						=       """cpu"""  # ensure determinism for the device-dependent torch.Generator
        _UpperCamelCase      :	Tuple						=       self.get_dummy_components()
        _UpperCamelCase      :	Dict						=       PNDMScheduler(skip_prk_steps=__a	)
        _UpperCamelCase      :	Any						=       AudioLDMPipeline(**__a	)
        _UpperCamelCase      :	List[Any]						=       audioldm_pipe.to(__a	)
        audioldm_pipe.set_progress_bar_config(disable=__a	)

        _UpperCamelCase      :	Optional[Any]						=       """A hammer hitting a wooden surface"""

        # test num_waveforms_per_prompt=1 (default)
        _UpperCamelCase      :	Dict						=       audioldm_pipe(__a					,   num_inference_steps=2	).audios

        assert audios.shape == (1, 256)

        # test num_waveforms_per_prompt=1 (default) for batch of prompts
        _UpperCamelCase      :	List[Any]						=       2
        _UpperCamelCase      :	Tuple						=       audioldm_pipe([prompt] * batch_size					,   num_inference_steps=2	).audios

        assert audios.shape == (batch_size, 256)

        # test num_waveforms_per_prompt for single prompt
        _UpperCamelCase      :	Optional[int]						=       2
        _UpperCamelCase      :	Dict						=       audioldm_pipe(__a					,   num_inference_steps=2					,   num_waveforms_per_prompt=__a	).audios

        assert audios.shape == (num_waveforms_per_prompt, 256)

        # test num_waveforms_per_prompt for batch of prompts
        _UpperCamelCase      :	str						=       2
        _UpperCamelCase      :	Union[str, Any]						=       audioldm_pipe(
            [prompt] * batch_size					,   num_inference_steps=2					,   num_waveforms_per_prompt=__a	).audios

        assert audios.shape == (batch_size * num_waveforms_per_prompt, 256)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				int:
        _UpperCamelCase      :	Any						=       """cpu"""  # ensure determinism for the device-dependent torch.Generator
        _UpperCamelCase      :	str						=       self.get_dummy_components()
        _UpperCamelCase      :	str						=       AudioLDMPipeline(**__a	)
        _UpperCamelCase      :	Any						=       audioldm_pipe.to(__a	)
        audioldm_pipe.set_progress_bar_config(disable=__a	)
        _UpperCamelCase      :	List[Any]						=       audioldm_pipe.vocoder.config.sampling_rate

        _UpperCamelCase      :	Union[str, Any]						=       self.get_dummy_inputs(__a	)
        _UpperCamelCase      :	str						=       audioldm_pipe(audio_length_in_s=0.0_16					,   **__a	)
        _UpperCamelCase      :	int						=       output.audios[0]

        assert audio.ndim == 1
        assert len(__a	) / vocoder_sampling_rate == 0.0_16

        _UpperCamelCase      :	int						=       audioldm_pipe(audio_length_in_s=0.0_32					,   **__a	)
        _UpperCamelCase      :	Any						=       output.audios[0]

        assert audio.ndim == 1
        assert len(__a	) / vocoder_sampling_rate == 0.0_32

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				int:
        _UpperCamelCase      :	Tuple						=       self.get_dummy_components()
        _UpperCamelCase      :	int						=       AudioLDMPipeline(**__a	)
        _UpperCamelCase      :	List[str]						=       audioldm_pipe.to(__a	)
        audioldm_pipe.set_progress_bar_config(disable=__a	)

        _UpperCamelCase      :	int						=       ["""hey"""]

        _UpperCamelCase      :	str						=       audioldm_pipe(__a					,   num_inference_steps=1	)
        _UpperCamelCase      :	Optional[Any]						=       output.audios.shape
        assert audio_shape == (1, 256)

        _UpperCamelCase      :	Optional[int]						=       audioldm_pipe.vocoder.config
        config.model_in_dim *= 2
        _UpperCamelCase      :	Optional[Any]						=       SpeechTaHifiGan(__a	).to(__a	)
        _UpperCamelCase      :	Dict						=       audioldm_pipe(__a					,   num_inference_steps=1	)
        _UpperCamelCase      :	List[str]						=       output.audios.shape
        # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram
        assert audio_shape == (1, 256)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				int:
        self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				str:
        self._test_inference_batch_single_identical(test_mean_pixel_difference=__a	)


  @unittest.skipIf(
      torch_device != "cuda" or not is_xformers_available()					,   reason="XFormers attention is only available with CUDA and `xformers` installed"					,   )
  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict	)		->				str:
        self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__a	)





@slow
class      __SCREAMING_SNAKE_CASE    (						unittest.TestCase   ):







  '''simple docstring'''


  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				Optional[Any]:
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]					,   __a   :       str					,   __a   :       List[str]="cpu"					,   __a   :       Optional[int]=torch.floataa					,   __a   :       Optional[Any]=0	)		->				List[Any]:
        _UpperCamelCase      :	Tuple						=       torch.Generator(device=__a	).manual_seed(__a	)
        _UpperCamelCase      :	Optional[Any]						=       np.random.RandomState(__a	).standard_normal((1, 8, 128, 16)	)
        _UpperCamelCase      :	str						=       torch.from_numpy(__a	).to(device=__a					,   dtype=__a	)
        _UpperCamelCase      :	Optional[int]						=       {
            """prompt""": """A hammer hitting a wooden surface""",
            """latents""": latents,
            """generator""": generator,
            """num_inference_steps""": 3,
            """guidance_scale""": 2.5,
        }
        return inputs

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				Optional[int]:
        _UpperCamelCase      :	Dict						=       AudioLDMPipeline.from_pretrained("cvssp/audioldm"	)
        _UpperCamelCase      :	Optional[Any]						=       audioldm_pipe.to(__a	)
        audioldm_pipe.set_progress_bar_config(disable=__a	)

        _UpperCamelCase      :	int						=       self.get_inputs(__a	)
        _UpperCamelCase      :	Optional[Any]						=       25
        _UpperCamelCase      :	Tuple						=       audioldm_pipe(**__a	).audios[0]

        assert audio.ndim == 1
        assert len(__a	) == 8_1920

        _UpperCamelCase      :	Any						=       audio[7_7230:7_7240]
        _UpperCamelCase      :	Any						=       np.array(
            [-0.48_84, -0.46_07, 0.00_23, 0.50_07, 0.58_96, 0.51_51, 0.38_13, -0.02_08, -0.36_87, -0.43_15]	)
        _UpperCamelCase      :	int						=       np.abs(expected_slice - audio_slice	).max()
        assert max_diff < 1e-2


  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				List[Any]:
        _UpperCamelCase      :	Dict						=       AudioLDMPipeline.from_pretrained("cvssp/audioldm"	)
        _UpperCamelCase      :	str						=       LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config	)
        _UpperCamelCase      :	Optional[int]						=       audioldm_pipe.to(__a	)
        audioldm_pipe.set_progress_bar_config(disable=__a	)

        _UpperCamelCase      :	Tuple						=       self.get_inputs(__a	)
        _UpperCamelCase      :	int						=       audioldm_pipe(**__a	).audios[0]

        assert audio.ndim == 1
        assert len(__a	) == 8_1920

        _UpperCamelCase      :	List[str]						=       audio[2_7780:2_7790]
        _UpperCamelCase      :	Tuple						=       np.array([-0.21_31, -0.08_73, -0.01_24, -0.01_89, 0.05_69, 0.13_73, 0.18_83, 0.28_86, 0.32_97, 0.22_12]	)
        _UpperCamelCase      :	int						=       np.abs(expected_slice - audio_slice	).max()
        assert max_diff < 3e-2







"""simple docstring"""


from __future__ import annotations

import random

# Maximum size of the population.  Bigger could be faster but is more memory expensive.
lowerCamelCase__				  =   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.
lowerCamelCase__				  =   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.
lowerCamelCase__				  =   0.4
# Just a seed to improve randomness required by the algorithm.
random.seed(random.randint(0, 1000))




def 					lowercase__    (					lowercase_		,lowercase_			)					->		tuple[str, float]:




      """simple docstring"""

      _UpperCamelCase      :	str						=       len([g for position, g in enumerate(lowercase_			) if g == main_target[position]]			)
      return (item, float(lowercase_			))




def 					lowercase__    (					lowercase_		,lowercase_			)					->		tuple[str, str]:




      """simple docstring"""

      _UpperCamelCase      :	Tuple						=       random.randint(0		,len(lowercase_			) - 1			)
      _UpperCamelCase      :	Dict						=       parent_a[:random_slice] + parent_a[random_slice:]
      _UpperCamelCase      :	Tuple						=       parent_a[:random_slice] + parent_a[random_slice:]
      return (child_a, child_a)




def 					lowercase__    (					lowercase_		,lowercase_			)					->		str:




      """simple docstring"""

      _UpperCamelCase      :	int						=       list(lowercase_			)
      if random.uniform(0		,1			) < MUTATION_PROBABILITY:
            _UpperCamelCase      :	int						=       random.choice(lowercase_			)
      return "".join(lowercase_			)




def 					lowercase__    (					lowercase_		,lowercase_		,lowercase_		,)					->		list[str]:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       []
      # Generate more children proportionally to the fitness score.
      _UpperCamelCase      :	List[str]						=       int(parent_a[1] * 100			) + 1
      _UpperCamelCase      :	Union[str, Any]						=       10 if child_n >= 10 else child_n
      for _ in range(lowercase_			):
            _UpperCamelCase      :	Dict						=       population_score[random.randint(0		,lowercase_			)][0]

            _UpperCamelCase,  _UpperCamelCase      :	Dict						=       crossover(parent_a[0]		,lowercase_			)
            # Append new string to the population list.
            pop.append(mutate(lowercase_		,lowercase_			)			)
            pop.append(mutate(lowercase_		,lowercase_			)			)
      return pop




def 					lowercase__    (					lowercase_		,lowercase_		,lowercase_ = True			)					->		tuple[int, int, str]:




      """simple docstring"""

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

      # Generate random starting population.
      _UpperCamelCase      :	Union[str, Any]						=       []
      for _ in range(lowercase_			):
            population.append("".join([random.choice(lowercase_			) for i in range(len(lowercase_			)			)]			)			)

      # Just some logs to know what the algorithms is doing.
      _UpperCamelCase,  _UpperCamelCase      :	str						=       0, 0

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

            # 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.
            _UpperCamelCase      :	int						=       [evaluate(lowercase_		,lowercase_			) for item in population]

            # Check if there is a matching evolution.
            _UpperCamelCase      :	Optional[Any]						=       sorted(lowercase_		,key=lambda lowercase_			: x[1]		,reverse=lowercase_			)
            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.
            _UpperCamelCase      :	str						=       population[: int(N_POPULATION / 3			)]
            population.clear()
            population.extend(lowercase_			)
            # Normalize population score to be between 0 and 1.
            _UpperCamelCase      :	str						=       [
                (item, score / len(lowercase_			)) for item, score in population_score
            ]

            # This is selection
            for i in range(lowercase_			):
                  population.extend(select(population_score[int(lowercase_			)]		,lowercase_		,lowercase_			)			)
                  # 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(lowercase_			) > N_POPULATION:
                        break


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