


import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import (
           MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
           MODEL_FOR_QUESTION_ANSWERING_MAPPING,
           MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
           MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
           LayoutLMvaConfig,
           LayoutLMvaForQuestionAnswering,
           LayoutLMvaForSequenceClassification,
           LayoutLMvaForTokenClassification,
           LayoutLMvaModel,
       )
       from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
       from PIL import Image

       from transformers import LayoutLMvaImageProcessor


class   a__	:

       def __init__(   self      :     int      ,							lowerCamelCase_      :     Any      ,							lowerCamelCase_      :     Optional[Any]=2      ,							lowerCamelCase_      :     Optional[Any]=3      ,							lowerCamelCase_      :     int=4      ,							lowerCamelCase_      :     Optional[int]=2      ,							lowerCamelCase_      :     List[str]=7      ,							lowerCamelCase_      :     str=True      ,							lowerCamelCase_      :     Optional[Any]=True      ,							lowerCamelCase_      :     Dict=True      ,							lowerCamelCase_      :     str=True      ,							lowerCamelCase_      :     List[Any]=9_9      ,							lowerCamelCase_      :     Tuple=3_6      ,							lowerCamelCase_      :     int=3      ,							lowerCamelCase_      :     int=4      ,							lowerCamelCase_      :     List[str]=3_7      ,							lowerCamelCase_      :     Optional[Any]="gelu"      ,							lowerCamelCase_      :     Union[str, Any]=0.1      ,							lowerCamelCase_      :     Dict=0.1      ,							lowerCamelCase_      :     Dict=5_1_2      ,							lowerCamelCase_      :     List[str]=1_6      ,							lowerCamelCase_      :     str=2      ,							lowerCamelCase_      :     str=0.0_2      ,							lowerCamelCase_      :     Optional[Any]=6      ,							lowerCamelCase_      :     Union[str, Any]=6      ,							lowerCamelCase_      :     Optional[int]=3      ,							lowerCamelCase_      :     Dict=4      ,							lowerCamelCase_      :     Tuple=None      ,							lowerCamelCase_      :     Dict=1_0_0_0      ,							):
            a_    :     str										=    parent
            a_    :     Union[str, Any]										=    batch_size
            a_    :     str										=    num_channels
            a_    :     int										=    image_size
            a_    :     List[Any]										=    patch_size
            a_    :     Union[str, Any]										=    text_seq_length
            a_    :     int										=    is_training
            a_    :     Any										=    use_input_mask
            a_    :     List[str]										=    use_token_type_ids
            a_    :     List[str]										=    use_labels
            a_    :     Optional[Any]										=    vocab_size
            a_    :     Tuple										=    hidden_size
            a_    :     int										=    num_hidden_layers
            a_    :     Optional[int]										=    num_attention_heads
            a_    :     Optional[int]										=    intermediate_size
            a_    :     Union[str, Any]										=    hidden_act
            a_    :     Union[str, Any]										=    hidden_dropout_prob
            a_    :     List[Any]										=    attention_probs_dropout_prob
            a_    :     int										=    max_position_embeddings
            a_    :     Optional[int]										=    type_vocab_size
            a_    :     Dict										=    type_sequence_label_size
            a_    :     Optional[Any]										=    initializer_range
            a_    :     int										=    coordinate_size
            a_    :     Union[str, Any]										=    shape_size
            a_    :     Optional[int]										=    num_labels
            a_    :     str										=    num_choices
            a_    :     Optional[int]										=    scope
            a_    :     Dict										=    range_bbox

            # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
            a_    :     List[str]										=    text_seq_length
            a_    :     Any										=    (image_size // patch_size) ** 2 + 1
            a_    :     Union[str, Any]										=    self.text_seq_length + self.image_seq_length

       def 						UpperCAmelCase(   self      :     int    ):
            a_    :     Union[str, Any]										=    ids_tensor([self.batch_size, self.text_seq_length]      ,							self.vocab_size    )

            a_    :     int										=    ids_tensor([self.batch_size, self.text_seq_length, 4]      ,							self.range_bbox    )
            # Ensure that bbox is legal
            for i in range(bbox.shape[0]    ):
                 for j in range(bbox.shape[1]    ):
                      if bbox[i, j, 3] < bbox[i, j, 1]:
                           a_    :     List[Any]										=    bbox[i, j, 3]
                           a_    :     Tuple										=    bbox[i, j, 1]
                           a_    :     int										=    t
                      if bbox[i, j, 2] < bbox[i, j, 0]:
                           a_    :     List[str]										=    bbox[i, j, 2]
                           a_    :     Union[str, Any]										=    bbox[i, j, 0]
                           a_    :     Any										=    t

            a_    :     str										=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

            a_    :     Optional[int]										=    None
            if self.use_input_mask:
                 a_    :     List[str]										=    random_attention_mask([self.batch_size, self.text_seq_length]    )

            a_    :     List[Any]										=    None
            if self.use_token_type_ids:
                 a_    :     Optional[Any]										=    ids_tensor([self.batch_size, self.text_seq_length]      ,							self.type_vocab_size    )

            a_    :     str										=    None
            a_    :     int										=    None
            if self.use_labels:
                 a_    :     Union[str, Any]										=    ids_tensor([self.batch_size]      ,							self.type_sequence_label_size    )
                 a_    :     str										=    ids_tensor([self.batch_size, self.text_seq_length]      ,							self.num_labels    )

            a_    :     int										=    LayoutLMvaConfig(
                vocab_size=self.vocab_size      ,							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      ,							max_position_embeddings=self.max_position_embeddings      ,							type_vocab_size=self.type_vocab_size      ,							initializer_range=self.initializer_range      ,							coordinate_size=self.coordinate_size      ,							shape_size=self.shape_size      ,							input_size=self.image_size      ,							patch_size=self.patch_size      ,							)

            return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels

       def 						UpperCAmelCase(   self      :     Union[str, Any]      ,							lowerCamelCase_      :     Optional[int]      ,							lowerCamelCase_      :     Union[str, Any]      ,							lowerCamelCase_      :     Dict      ,							lowerCamelCase_      :     Tuple      ,							lowerCamelCase_      :     List[Any]      ,							lowerCamelCase_      :     Tuple      ,							lowerCamelCase_      :     Tuple      ,							lowerCamelCase_      :     Optional[int]    ):
            a_    :     List[str]										=    LayoutLMvaModel(config=lowerCamelCase_    )
            model.to(lowerCamelCase_    )
            model.eval()

            # text + image
            a_    :     str										=    model(lowerCamelCase_      ,							pixel_values=lowerCamelCase_    )
            a_    :     int										=    model(
                lowerCamelCase_      ,							bbox=lowerCamelCase_      ,							pixel_values=lowerCamelCase_      ,							attention_mask=lowerCamelCase_      ,							token_type_ids=lowerCamelCase_    )
            a_    :     List[Any]										=    model(lowerCamelCase_      ,							bbox=lowerCamelCase_      ,							pixel_values=lowerCamelCase_      ,							token_type_ids=lowerCamelCase_    )
            a_    :     List[str]										=    model(lowerCamelCase_      ,							bbox=lowerCamelCase_      ,							pixel_values=lowerCamelCase_    )

            self.parent.assertEqual(result.last_hidden_state.shape      ,							(self.batch_size, self.seq_length, self.hidden_size)    )

            # text only
            a_    :     str										=    model(lowerCamelCase_    )
            self.parent.assertEqual(
                result.last_hidden_state.shape      ,							(self.batch_size, self.text_seq_length, self.hidden_size)    )

            # image only
            a_    :     Any										=    model(pixel_values=lowerCamelCase_    )
            self.parent.assertEqual(
                result.last_hidden_state.shape      ,							(self.batch_size, self.image_seq_length, self.hidden_size)    )

       def 						UpperCAmelCase(   self      :     List[str]      ,							lowerCamelCase_      :     List[str]      ,							lowerCamelCase_      :     List[Any]      ,							lowerCamelCase_      :     Any      ,							lowerCamelCase_      :     int      ,							lowerCamelCase_      :     List[Any]      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     Dict      ,							lowerCamelCase_      :     List[str]    ):
            a_    :     str										=    self.num_labels
            a_    :     Optional[Any]										=    LayoutLMvaForSequenceClassification(lowerCamelCase_    )
            model.to(lowerCamelCase_    )
            model.eval()
            a_    :     str										=    model(
                lowerCamelCase_      ,							bbox=lowerCamelCase_      ,							pixel_values=lowerCamelCase_      ,							attention_mask=lowerCamelCase_      ,							token_type_ids=lowerCamelCase_      ,							labels=lowerCamelCase_      ,							)
            self.parent.assertEqual(result.logits.shape      ,							(self.batch_size, self.num_labels)    )

       def 						UpperCAmelCase(   self      :     Optional[Any]      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     Optional[Any]      ,							lowerCamelCase_      :     Optional[int]      ,							lowerCamelCase_      :     List[Any]      ,							lowerCamelCase_      :     int      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     Optional[int]    ):
            a_    :     int										=    self.num_labels
            a_    :     Optional[int]										=    LayoutLMvaForTokenClassification(config=lowerCamelCase_    )
            model.to(lowerCamelCase_    )
            model.eval()
            a_    :     Optional[int]										=    model(
                lowerCamelCase_      ,							bbox=lowerCamelCase_      ,							pixel_values=lowerCamelCase_      ,							attention_mask=lowerCamelCase_      ,							token_type_ids=lowerCamelCase_      ,							labels=lowerCamelCase_      ,							)
            self.parent.assertEqual(result.logits.shape      ,							(self.batch_size, self.text_seq_length, self.num_labels)    )

       def 						UpperCAmelCase(   self      :     Union[str, Any]      ,							lowerCamelCase_      :     Union[str, Any]      ,							lowerCamelCase_      :     Optional[Any]      ,							lowerCamelCase_      :     Tuple      ,							lowerCamelCase_      :     Union[str, Any]      ,							lowerCamelCase_      :     Union[str, Any]      ,							lowerCamelCase_      :     Any      ,							lowerCamelCase_      :     Dict      ,							lowerCamelCase_      :     Optional[Any]    ):
            a_    :     Optional[Any]										=    LayoutLMvaForQuestionAnswering(config=lowerCamelCase_    )
            model.to(lowerCamelCase_    )
            model.eval()
            a_    :     Union[str, Any]										=    model(
                lowerCamelCase_      ,							bbox=lowerCamelCase_      ,							pixel_values=lowerCamelCase_      ,							attention_mask=lowerCamelCase_      ,							token_type_ids=lowerCamelCase_      ,							start_positions=lowerCamelCase_      ,							end_positions=lowerCamelCase_      ,							)
            self.parent.assertEqual(result.start_logits.shape      ,							(self.batch_size, self.seq_length)    )
            self.parent.assertEqual(result.end_logits.shape      ,							(self.batch_size, self.seq_length)    )

       def 						UpperCAmelCase(   self      :     str    ):
            a_    :     Tuple										=    self.prepare_config_and_inputs()
            (
                (
                a_
            )			,			(
                a_
            )			,			(
                a_
            )			,			(
                a_
            )			,			(
                a_
            )			,			(
                a_
            )			,			(
                a_
            )			,			(
                a_
            )			,			
            )    :     List[str]										=    config_and_inputs
            a_    :     Optional[Any]										=    {
                """input_ids""": input_ids,
                """bbox""": bbox,
                """pixel_values""": pixel_values,
                """token_type_ids""": token_type_ids,
                """attention_mask""": input_mask,
            }
            return config, inputs_dict


@require_torch
class   a__	(						lowerCAmelCase_						,       lowerCAmelCase_						,       unittest.TestCase    ):
       lowerCamelCase__:     Dict							    =     False
       lowerCamelCase__:     Dict							    =     False
       lowerCamelCase__:     str							    =     False

       lowerCamelCase__:     Any							    =     (
           (
               LayoutLMvaModel,
               LayoutLMvaForSequenceClassification,
               LayoutLMvaForTokenClassification,
               LayoutLMvaForQuestionAnswering,
           )
           if is_torch_available()
           else ()
       )
       lowerCamelCase__:     Dict							    =     (
           {"""document-question-answering""": LayoutLMvaForQuestionAnswering, """feature-extraction""": LayoutLMvaModel}
           if is_torch_available()
           else {}
       )

       def 						UpperCAmelCase(   self      :     Union[str, Any]      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     Optional[Any]      ,							lowerCamelCase_      :     Union[str, Any]      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     Optional[Any]    ):
            # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual
            # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has
            # the sequence dimension of the text embedding only.
            # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`)
            return True

       def 						UpperCAmelCase(   self      :     Optional[int]    ):
            a_    :     Optional[Any]										=    LayoutLMvaModelTester(self    )
            a_    :     Union[str, Any]										=    ConfigTester(self      ,							config_class=lowerCamelCase_      ,							hidden_size=3_7    )

       def 						UpperCAmelCase(   self      :     int      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     Any      ,							lowerCamelCase_      :     Union[str, Any]=False    ):
            a_    :     Optional[int]										=    copy.deepcopy(lowerCamelCase_    )
            if model_class in get_values(lowerCamelCase_    ):
                 a_    :     Optional[Any]										=    {
                     k: v.unsqueeze(1    ).expand(-1      ,							self.model_tester.num_choices      ,							-1    ).contiguous()
                     if isinstance(lowerCamelCase_      ,							torch.Tensor    ) and v.ndim > 1
                     else v
                     for k, v in inputs_dict.items()
                 }
            if return_labels:
                 if model_class in get_values(lowerCamelCase_    ):
                      a_    :     Optional[int]										=    torch.ones(self.model_tester.batch_size      ,							dtype=torch.long      ,							device=lowerCamelCase_    )
                 elif model_class in get_values(lowerCamelCase_    ):
                      a_    :     Union[str, Any]										=    torch.zeros(
                          self.model_tester.batch_size      ,							dtype=torch.long      ,							device=lowerCamelCase_    )
                      a_    :     Optional[int]										=    torch.zeros(
                          self.model_tester.batch_size      ,							dtype=torch.long      ,							device=lowerCamelCase_    )
                 elif model_class in [
                     *get_values(lowerCamelCase_    ),
                 ]:
                      a_    :     List[str]										=    torch.zeros(
                          self.model_tester.batch_size      ,							dtype=torch.long      ,							device=lowerCamelCase_    )
                 elif model_class in [
                     *get_values(lowerCamelCase_    ),
                 ]:
                      a_    :     str										=    torch.zeros(
                          (self.model_tester.batch_size, self.model_tester.text_seq_length)      ,							dtype=torch.long      ,							device=lowerCamelCase_      ,							)

            return inputs_dict

       def 						UpperCAmelCase(   self      :     int    ):
            self.config_tester.run_common_tests()

       def 						UpperCAmelCase(   self      :     Dict    ):
            a_    :     Dict										=    self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*lowerCamelCase_    )

       def 						UpperCAmelCase(   self      :     Any    ):
            a_    :     int										=    self.model_tester.prepare_config_and_inputs()
            for type in ["absolute", "relative_key", "relative_key_query"]:
                 a_    :     Any										=    type
                 self.model_tester.create_and_check_model(*lowerCamelCase_    )

       def 						UpperCAmelCase(   self      :     List[str]    ):
            a_    :     Any										=    self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase_    )

       def 						UpperCAmelCase(   self      :     Optional[Any]    ):
            a_    :     Union[str, Any]										=    self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_token_classification(*lowerCamelCase_    )

       def 						UpperCAmelCase(   self      :     Tuple    ):
            a_    :     List[Any]										=    self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_question_answering(*lowerCamelCase_    )

       @slow
       def 						UpperCAmelCase(   self      :     Any    ):
            for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a_    :     Dict										=    LayoutLMvaModel.from_pretrained(lowerCamelCase_    )
                 self.assertIsNotNone(lowerCamelCase_    )



def  _a			(						):
     a_    :     List[str]										=    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
     return image


@require_torch
class   a__	(						unittest.TestCase    ):

       @cached_property
       def 						UpperCAmelCase(   self      :     Dict    ):
            return LayoutLMvaImageProcessor(apply_ocr=lowerCamelCase_    ) if is_vision_available() else None

       @slow
       def 						UpperCAmelCase(   self      :     List[Any]    ):
            a_    :     Any										=    LayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base"""    ).to(lowerCamelCase_    )

            a_    :     List[str]										=    self.default_image_processor
            a_    :     Union[str, Any]										=    prepare_img()
            a_    :     Optional[Any]										=    image_processor(images=lowerCamelCase_      ,							return_tensors="""pt"""    ).pixel_values.to(lowerCamelCase_    )

            a_    :     Dict										=    torch.tensor([[1, 2]]    )
            a_    :     Union[str, Any]										=    torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]    ).unsqueeze(0    )

            # forward pass
            a_    :     Any										=    model(
                input_ids=input_ids.to(lowerCamelCase_    )      ,							bbox=bbox.to(lowerCamelCase_    )      ,							pixel_values=pixel_values.to(lowerCamelCase_    )      ,							)

            # verify the logits
            a_    :     Union[str, Any]										=    torch.Size((1, 1_9_9, 7_6_8)    )
            self.assertEqual(outputs.last_hidden_state.shape      ,							lowerCamelCase_    )

            a_    :     int										=    torch.tensor(
                [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]]    ).to(lowerCamelCase_    )

            self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]      ,							lowerCamelCase_      ,							atol=1E-4    )    )







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  _a			(						__UpperCamelCase  ,  __UpperCamelCase ):
     a_    :     List[Any]										=    len([g for position, g in enumerate(__UpperCamelCase ) if g == main_target[position]] )
     return (item, float(__UpperCamelCase ))



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase ):
     a_    :     List[Any]										=    random.randint(0  ,  len(__UpperCamelCase ) - 1 )
     a_    :     Tuple										=    parent_a[:random_slice] + parent_a[random_slice:]
     a_    :     Optional[Any]										=    parent_a[:random_slice] + parent_a[random_slice:]
     return (child_a, child_a)



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase ):
     a_    :     Optional[int]										=    list(__UpperCamelCase )
     if random.uniform(0  ,  1 ) < MUTATION_PROBABILITY:
          a_    :     int										=    random.choice(__UpperCamelCase )
     return "".join(__UpperCamelCase )



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  ):
     a_    :     Tuple										=    []
     # Generate more children proportionally to the fitness score.
     a_    :     Any										=    int(parent_a[1] * 1_0_0 ) + 1
     a_    :     int										=    1_0 if child_n >= 1_0 else child_n
     for _ in range(__UpperCamelCase ):
          a_    :     Tuple										=    population_score[random.randint(0  ,  __UpperCamelCase )][0]

          a_			,			a_    :     List[str]										=    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  _a			(						__UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase = True ):

     # Verify if N_POPULATION is bigger than N_SELECTED
     if N_POPULATION < N_SELECTED:
          a_    :     Union[str, Any]										=    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.
     a_    :     List[str]										=    sorted({c for c in target if c not in genes} )
     if not_in_genes_list:
          a_    :     Optional[Any]										=    F'''{not_in_genes_list} is not in genes list, evolution cannot converge'''
          raise ValueError(__UpperCamelCase )

     # Generate random starting population.
     a_    :     str										=    []
     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.
     a_			,			a_    :     List[str]										=    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.
          a_    :     Tuple										=    [evaluate(__UpperCamelCase  ,  __UpperCamelCase ) for item in population]

          # Check if there is a matching evolution.
          a_    :     Optional[Any]										=    sorted(__UpperCamelCase  ,  key=lambda __UpperCamelCase : 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 % 1_0 == 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.
          a_    :     List[str]										=    population[: int(N_POPULATION / 3 )]
          population.clear()
          population.extend(__UpperCamelCase )
          # Normalize population score to be between 0 and 1.
          a_    :     Optional[Any]										=    [
              (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__":
       __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}'''
       )



