
from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers import (
          TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
          TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
          TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
          TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
          TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
          LayoutLMvaConfig,
          TFLayoutLMvaForQuestionAnswering,
          TFLayoutLMvaForSequenceClassification,
          TFLayoutLMvaForTokenClassification,
          TFLayoutLMvaModel,
      )

if is_vision_available():
      from PIL import Image

      from transformers import LayoutLMvaImageProcessor



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

    # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
    __a :  Tuple						=  text_seq_length
    __a :  List[Any]						=  (image_size // patch_size) ** 2 + 1
    __a :  Optional[int]						=  self.text_seq_length + self.image_seq_length
   def       lowerCAmelCase			(self :					Any   ):
    __a :  Tuple						=  ids_tensor([self.batch_size, self.text_seq_length]					,				self.vocab_size   )

    __a :  List[str]						=  ids_tensor([self.batch_size, self.text_seq_length, 4]					,				self.range_bbox   )
    __a :  Optional[int]						=  bbox.numpy()
    # 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 :  Dict						=  bbox[i, j, 3]
       __a :  str						=  bbox[i, j, 1]
       __a :  List[Any]						=  tmp_coordinate
      if bbox[i, j, 2] < bbox[i, j, 0]:
       __a :  Tuple						=  bbox[i, j, 2]
       __a :  Optional[Any]						=  bbox[i, j, 0]
       __a :  Union[str, Any]						=  tmp_coordinate
    __a :  Union[str, Any]						=  tf.constant(snake_case_   )

    __a :  Union[str, Any]						=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

    __a :  Optional[Any]						=  None
    if self.use_input_mask:
     __a :  Optional[int]						=  random_attention_mask([self.batch_size, self.text_seq_length]   )

    __a :  str						=  None
    if self.use_token_type_ids:
     __a :  int						=  ids_tensor([self.batch_size, self.text_seq_length]					,				self.type_vocab_size   )

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

    __a :  List[str]						=  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       lowerCAmelCase			(self :					Dict					,				snake_case_ :					Optional[int]					,				snake_case_ :					Union[str, Any]					,				snake_case_ :					List[str]					,				snake_case_ :					List[str]					,				snake_case_ :					str					,				snake_case_ :					Dict   ):
    __a :  Tuple						=  TFLayoutLMvaModel(config=snake_case_   )

    # text + image
    __a :  List[Any]						=  model(snake_case_					,				pixel_values=snake_case_					,				training=snake_case_   )
    __a :  Tuple						=  model(
        snake_case_					,				bbox=snake_case_					,				pixel_values=snake_case_					,				attention_mask=snake_case_					,				token_type_ids=snake_case_					,				training=snake_case_					,				)
    __a :  Tuple						=  model(snake_case_					,				bbox=snake_case_					,				pixel_values=snake_case_					,				training=snake_case_   )

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

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

    # image only
    __a :  Optional[Any]						=  model({'''pixel_values''': pixel_values}					,				training=snake_case_   )
    self.parent.assertEqual(
        result.last_hidden_state.shape					,				(self.batch_size, self.image_seq_length, self.hidden_size)   )
   def       lowerCAmelCase			(self :					int					,				snake_case_ :					List[Any]					,				snake_case_ :					List[Any]					,				snake_case_ :					Any					,				snake_case_ :					Optional[int]					,				snake_case_ :					Union[str, Any]					,				snake_case_ :					Optional[int]					,				snake_case_ :					Optional[int]   ):
    __a :  List[Any]						=  self.num_labels
    __a :  int						=  TFLayoutLMvaForSequenceClassification(config=snake_case_   )
    __a :  Optional[Any]						=  model(
        snake_case_					,				bbox=snake_case_					,				pixel_values=snake_case_					,				attention_mask=snake_case_					,				token_type_ids=snake_case_					,				labels=snake_case_					,				training=snake_case_					,				)
    self.parent.assertEqual(result.logits.shape					,				(self.batch_size, self.num_labels)   )
   def       lowerCAmelCase			(self :					Optional[Any]					,				snake_case_ :					Union[str, Any]					,				snake_case_ :					Union[str, Any]					,				snake_case_ :					Tuple					,				snake_case_ :					int					,				snake_case_ :					Optional[int]					,				snake_case_ :					Optional[Any]					,				snake_case_ :					Union[str, Any]   ):
    __a :  List[str]						=  self.num_labels
    __a :  int						=  TFLayoutLMvaForTokenClassification(config=snake_case_   )
    __a :  List[Any]						=  model(
        snake_case_					,				bbox=snake_case_					,				pixel_values=snake_case_					,				attention_mask=snake_case_					,				token_type_ids=snake_case_					,				labels=snake_case_					,				training=snake_case_					,				)
    self.parent.assertEqual(result.logits.shape					,				(self.batch_size, self.text_seq_length, self.num_labels)   )
   def       lowerCAmelCase			(self :					str					,				snake_case_ :					Optional[int]					,				snake_case_ :					Dict					,				snake_case_ :					Tuple					,				snake_case_ :					Dict					,				snake_case_ :					Optional[int]					,				snake_case_ :					str					,				snake_case_ :					Union[str, Any]   ):
    __a :  List[Any]						=  2
    __a :  Optional[int]						=  TFLayoutLMvaForQuestionAnswering(config=snake_case_   )
    __a :  int						=  model(
        snake_case_					,				bbox=snake_case_					,				pixel_values=snake_case_					,				attention_mask=snake_case_					,				token_type_ids=snake_case_					,				start_positions=snake_case_					,				end_positions=snake_case_					,				training=snake_case_					,				)
    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       lowerCAmelCase			(self :					List[Any]   ):
    __a :  List[Any]						=  self.prepare_config_and_inputs()
    ((__a)				,       (__a)				,       (__a)				,       (__a)				,       (__a)				,       (__a)				,       (__a)				,       (__a)) :  Optional[int]						=  config_and_inputs
    __a :  int						=  {
        '''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_tf
class 		UpperCamelCase__  (       __lowercase    ,__lowercase    ,unittest.TestCase    ):
   _SCREAMING_SNAKE_CASE      :							Tuple	       =      (
       (
           TFLayoutLMvaModel,
           TFLayoutLMvaForQuestionAnswering,
           TFLayoutLMvaForSequenceClassification,
           TFLayoutLMvaForTokenClassification,
       )
       if is_tf_available()
       else ()
   )
   _SCREAMING_SNAKE_CASE      :							int	       =      (
       {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel}
       if is_tf_available()
       else {}
   )

   _SCREAMING_SNAKE_CASE      :							int	       =      False
   _SCREAMING_SNAKE_CASE      :							Union[str, Any]	       =      False
   _SCREAMING_SNAKE_CASE      :							List[Any]	       =      False
   def       lowerCAmelCase			(self :					str					,				snake_case_ :					List[str]					,				snake_case_ :					Tuple					,				snake_case_ :					Any					,				snake_case_ :					Optional[Any]					,				snake_case_ :					Optional[int]   ):
    return True
   def       lowerCAmelCase			(self :					str					,				snake_case_ :					int					,				snake_case_ :					str					,				snake_case_ :					Tuple=False   ):
    __a :  Dict						=  copy.deepcopy(snake_case_   )

    if model_class in get_values(snake_case_   ):
     __a :  List[Any]						=  {
         k: tf.tile(tf.expand_dims(snake_case_					,				1   )					,				(1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)   )
         if isinstance(snake_case_					,				tf.Tensor   ) and v.ndim > 0
         else v
         for k, v in inputs_dict.items()
     }

    if return_labels:
     if model_class in get_values(snake_case_   ):
      __a :  List[Any]						=  tf.ones(self.model_tester.batch_size					,				dtype=tf.intaa   )
     elif model_class in get_values(snake_case_   ):
      __a :  Optional[int]						=  tf.zeros(self.model_tester.batch_size					,				dtype=tf.intaa   )
      __a :  List[Any]						=  tf.zeros(self.model_tester.batch_size					,				dtype=tf.intaa   )
     elif model_class in get_values(snake_case_   ):
      __a :  Any						=  tf.zeros(self.model_tester.batch_size					,				dtype=tf.intaa   )
     elif model_class in get_values(snake_case_   ):
      __a :  Optional[int]						=  tf.zeros(
          (self.model_tester.batch_size, self.model_tester.text_seq_length)					,				dtype=tf.intaa   )

    return inputs_dict
   def       lowerCAmelCase			(self :					int   ):
    __a :  str						=  TFLayoutLMvaModelTester(self   )
    __a :  Any						=  ConfigTester(self					,				config_class=snake_case_					,				hidden_size=3_7   )
   def       lowerCAmelCase			(self :					Any   ):
    self.config_tester.run_common_tests()
   def       lowerCAmelCase			(self :					str   ):
    __a				,       __a :  Optional[Any]						=  self.model_tester.prepare_config_and_inputs_for_common()
    for model_class in self.all_model_classes:
     __a :  str						=  model_class(snake_case_   )
     if getattr(snake_case_					,				'''hf_compute_loss'''					,				snake_case_   ):
      # The number of elements in the loss should be the same as the number of elements in the label
      __a :  List[Any]						=  self._prepare_for_class(inputs_dict.copy()					,				snake_case_					,				return_labels=snake_case_   )
      __a :  Optional[Any]						=  prepared_for_class[
          sorted(prepared_for_class.keys() - inputs_dict.keys()					,				reverse=snake_case_   )[0]
      ]
      __a :  Optional[Any]						=  added_label.shape.as_list()[:1]

      # Test that model correctly compute the loss with kwargs
      __a :  str						=  self._prepare_for_class(inputs_dict.copy()					,				snake_case_					,				return_labels=snake_case_   )
      __a :  Union[str, Any]						=  prepared_for_class.pop('''input_ids'''   )

      __a :  Any						=  model(snake_case_					,				**snake_case_   )[0]
      self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )

      # Test that model correctly compute the loss when we mask some positions
      __a :  Any						=  self._prepare_for_class(inputs_dict.copy()					,				snake_case_					,				return_labels=snake_case_   )
      __a :  int						=  prepared_for_class.pop('''input_ids'''   )
      if "labels" in prepared_for_class:
       __a :  Any						=  prepared_for_class['''labels'''].numpy()
       if len(labels.shape   ) > 1 and labels.shape[1] != 1:
        __a :  str						=  -1_0_0
        __a :  Union[str, Any]						=  tf.convert_to_tensor(snake_case_   )
        __a :  Tuple						=  model(snake_case_					,				**snake_case_   )[0]
        self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )
        self.assertTrue(not np.any(np.isnan(loss.numpy()   )   )   )

                # Test that model correctly compute the loss with a dict
      __a :  str						=  self._prepare_for_class(inputs_dict.copy()					,				snake_case_					,				return_labels=snake_case_   )
      __a :  List[Any]						=  model(snake_case_   )[0]
      self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )

      # Test that model correctly compute the loss with a tuple
      __a :  Tuple						=  self._prepare_for_class(inputs_dict.copy()					,				snake_case_					,				return_labels=snake_case_   )

      # Get keys that were added with the _prepare_for_class function
      __a :  Tuple						=  prepared_for_class.keys() - inputs_dict.keys()
      __a :  int						=  inspect.signature(model.call   ).parameters
      __a :  Union[str, Any]						=  list(signature.keys()   )

      # Create a dictionary holding the location of the tensors in the tuple
      __a :  Dict						=  {0: '''input_ids'''}
      for label_key in label_keys:
       __a :  str						=  signature_names.index(snake_case_   )
       __a :  Tuple						=  label_key
      __a :  List[str]						=  sorted(tuple_index_mapping.items()   )
      # Initialize a list with their default values, update the values and convert to a tuple
      __a :  Any						=  []

      for name in signature_names:
       if name != "kwargs":
        list_input.append(signature[name].default   )

      for index, value in sorted_tuple_index_mapping:
       __a :  str						=  prepared_for_class[value]

      __a :  Optional[int]						=  tuple(snake_case_   )

      # Send to model
      __a :  int						=  model(tuple_input[:-1]   )[0]

      self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )
   def       lowerCAmelCase			(self :					List[str]   ):
    (
        (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       
    ) :  int						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_   )
   def       lowerCAmelCase			(self :					Optional[int]   ):
    (
        (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       
    ) :  Dict						=  self.model_tester.prepare_config_and_inputs()
    for type in ["absolute", "relative_key", "relative_key_query"]:
     __a :  Dict						=  type
     self.model_tester.create_and_check_model(snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_   )
   def       lowerCAmelCase			(self :					List[str]   ):
    (
        (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       
    ) :  Dict						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_sequence_classification(
        snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_   )
   def       lowerCAmelCase			(self :					List[Any]   ):
    (
        (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       
    ) :  Tuple						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_token_classification(
        snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_   )
   def       lowerCAmelCase			(self :					List[str]   ):
    (
        (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       (
        __a
    )				,       
    ) :  List[str]						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_question_answering(
        snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_					,				snake_case_   )







   @slow
   def       lowerCAmelCase			(self :					List[Any]   ):
    for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __a :  Optional[Any]						=  TFLayoutLMvaModel.from_pretrained(snake_case_   )
     self.assertIsNotNone(snake_case_   )





def    __UpperCamelCase     (				):
 __a :  Any						=  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
 return image



@require_tf
class 		UpperCamelCase__  (       unittest.TestCase    ):
   @cached_property
   def       lowerCAmelCase			(self :					str   ):
    return LayoutLMvaImageProcessor(apply_ocr=snake_case_   ) if is_vision_available() else None







   @slow
   def       lowerCAmelCase			(self :					int   ):
    __a :  Optional[Any]						=  TFLayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base'''   )

    __a :  int						=  self.default_image_processor
    __a :  Optional[int]						=  prepare_img()
    __a :  Dict						=  image_processor(images=snake_case_					,				return_tensors='''tf'''   ).pixel_values

    __a :  int						=  tf.constant([[1, 2]]   )
    __a :  int						=  tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]]   )					,				axis=0   )

    # forward pass
    __a :  Optional[Any]						=  model(input_ids=snake_case_					,				bbox=snake_case_					,				pixel_values=snake_case_					,				training=snake_case_   )

    # verify the logits
    __a :  Dict						=  (1, 1_9_9, 7_6_8)
    self.assertEqual(outputs.last_hidden_state.shape					,				snake_case_   )

    __a :  str						=  tf.constant(
        [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]   )

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


from __future__ import annotations

from fractions import Fraction
from math import gcd, sqrt




def    __UpperCamelCase     (				lowerCAmelCase__							:				int  ):
 __a :  int						=  int(number**0.5  )
 return number == sq * sq




def    __UpperCamelCase     (				lowerCAmelCase__							:				int  ,   lowerCAmelCase__							:				int  ,   lowerCAmelCase__							:				int  ,   lowerCAmelCase__							:				int  ,   lowerCAmelCase__							:				int  ,   lowerCAmelCase__							:				int  ):
 __a :  int						=  x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den
 __a :  int						=  x_den * y_den * z_den
 __a :  int						=  gcd(lowerCAmelCase__  ,   lowerCAmelCase__  )
 top //= hcf
 bottom //= hcf
 return top, bottom




def    __UpperCamelCase     (				lowerCAmelCase__							:				int = 3_5  ):
 __a :  set						=  set()
 __a :  int
 __a :  Fraction						=  Fraction(0  )
 __a :  tuple[int, int]

 for x_num in range(1  ,   order + 1  ):
  for x_den in range(x_num + 1  ,   order + 1  ):
   for y_num in range(1  ,   order + 1  ):
    for y_den in range(y_num + 1  ,   order + 1  ):
     # n=1
     __a :  Any						=  x_num * y_den + x_den * y_num
     __a :  Dict						=  x_den * y_den
     __a :  int						=  gcd(lowerCAmelCase__  ,   lowerCAmelCase__  )
     z_num //= hcf
     z_den //= hcf
     if 0 < z_num < z_den <= order:
      __a :  str						=  add_three(
          lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  )
      unique_s.add(lowerCAmelCase__  )

     # n=2
     __a :  Union[str, Any]						=  (
         x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num
     )
     __a :  Optional[Any]						=  x_den * x_den * y_den * y_den
     if is_sq(lowerCAmelCase__  ) and is_sq(lowerCAmelCase__  ):
      __a :  Any						=  int(sqrt(lowerCAmelCase__  )  )
      __a :  Optional[Any]						=  int(sqrt(lowerCAmelCase__  )  )
      __a :  int						=  gcd(lowerCAmelCase__  ,   lowerCAmelCase__  )
      z_num //= hcf
      z_den //= hcf
      if 0 < z_num < z_den <= order:
       __a :  str						=  add_three(
           lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  )
       unique_s.add(lowerCAmelCase__  )

                    # n=-1
     __a :  List[str]						=  x_num * y_num
     __a :  List[str]						=  x_den * y_num + x_num * y_den
     __a :  str						=  gcd(lowerCAmelCase__  ,   lowerCAmelCase__  )
     z_num //= hcf
     z_den //= hcf
     if 0 < z_num < z_den <= order:
      __a :  Optional[int]						=  add_three(
          lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  )
      unique_s.add(lowerCAmelCase__  )

     # n=2
     __a :  List[str]						=  x_num * x_num * y_num * y_num
     __a :  Optional[int]						=  (
         x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den
     )
     if is_sq(lowerCAmelCase__  ) and is_sq(lowerCAmelCase__  ):
      __a :  Union[str, Any]						=  int(sqrt(lowerCAmelCase__  )  )
      __a :  List[str]						=  int(sqrt(lowerCAmelCase__  )  )
      __a :  Optional[int]						=  gcd(lowerCAmelCase__  ,   lowerCAmelCase__  )
      z_num //= hcf
      z_den //= hcf
      if 0 < z_num < z_den <= order:
       __a :  int						=  add_three(
           lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  )
       unique_s.add(lowerCAmelCase__  )

 for num, den in unique_s:
  total += Fraction(lowerCAmelCase__  ,   lowerCAmelCase__  )

 return total.denominator + total.numerator


if __name__ == "__main__":
      print(F"""{solution() = }""")
