





'''simple docstring'''

import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    UNetaDConditionModel,
    VideoToVideoSDPipeline,
)
from diffusers.utils import floats_tensor, is_xformers_available, skip_mps
from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






@skip_mps
class        UpperCAmelCase     (	UpperCamelCase__      ,	unittest.TestCase    ):
 __lowercase       		=    VideoToVideoSDPipeline
 __lowercase       		=    TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"""video"""}    ) - {"""image""", """width""", """height"""}
 __lowercase       		=    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""video"""}    ) - {"""image"""}
 __lowercase       		=    PipelineTesterMixin.required_optional_params - {"""latents"""}
 __lowercase       		=    False

 # No `output_type`.
 __lowercase       		=    frozenset(
     [
         """num_inference_steps""",
         """generator""",
         """latents""",
         """return_dict""",
         """callback""",
         """callback_steps""",
     ]    )
 def 					UpperCAmelCase_							(    self				:List[Any]							)->							Optional[Any]:
     torch.manual_seed(0							)
     A__    =      UNetaDConditionModel(
         block_out_channels=(32, 64, 64, 64)						,	layers_per_block=2						,	sample_size=32						,	in_channels=4						,	out_channels=4						,	down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D")						,	up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D")						,	cross_attention_dim=32						,	attention_head_dim=4						,	)
     A__    =      DDIMScheduler(
         beta_start=0.0_0_0_8_5						,	beta_end=0.0_1_2						,	beta_schedule="scaled_linear"						,	clip_sample=lowercase_						,	set_alpha_to_one=lowercase_						,	)
     torch.manual_seed(0							)
     A__    =      AutoencoderKL(
         block_out_channels=[32, 64]						,	in_channels=3						,	out_channels=3						,	down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]						,	up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]						,	latent_channels=4						,	sample_size=1_28						,	)
     torch.manual_seed(0							)
     A__    =      CLIPTextConfig(
         bos_token_id=0						,	eos_token_id=2						,	hidden_size=32						,	intermediate_size=37						,	layer_norm_eps=1E-05						,	num_attention_heads=4						,	num_hidden_layers=5						,	pad_token_id=1						,	vocab_size=10_00						,	hidden_act="gelu"						,	projection_dim=5_12						,	)
     A__    =      CLIPTextModel(lowercase_							)
     A__    =      CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"							)

     A__    =      {
         "unet": unet,
         "scheduler": scheduler,
         "vae": vae,
         "text_encoder": text_encoder,
         "tokenizer": tokenizer,
     }
     return components
 def 					UpperCAmelCase_							(    self				:str						,	lowercase_				:int						,	lowercase_				:Any=0							)->							List[str]:
     # 3 frames
     A__    =      floats_tensor((1, 3, 3, 32, 32)						,	rng=random.Random(lowercase_							)							).to(lowercase_							)

     if str(lowercase_							).startswith("mps"							):
         A__    =      torch.manual_seed(lowercase_							)
     else:
         A__    =      torch.Generator(device=lowercase_							).manual_seed(lowercase_							)
     A__    =      {
         "prompt": "A painting of a squirrel eating a burger",
         "video": video,
         "generator": generator,
         "num_inference_steps": 2,
         "guidance_scale": 6.0,
         "output_type": "pt",
     }
     return inputs
 def 					UpperCAmelCase_							(    self				:Tuple							)->							int:
     A__    =      "cpu"  # ensure determinism for the device-dependent torch.Generator
     A__    =      self.get_dummy_components()
     A__    =      VideoToVideoSDPipeline(**lowercase_							)
     A__    =      sd_pipe.to(lowercase_							)
     sd_pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      self.get_dummy_inputs(lowercase_							)
     A__    =      "np"
     A__    =      sd_pipe(**lowercase_							).frames
     A__    =      frames[0][-3:, -3:, -1]

     assert frames[0].shape == (32, 32, 3)
     A__    =      np.array([1_06, 1_17, 1_13, 1_74, 1_37, 1_12, 1_48, 1_51, 1_31]							)

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2
 @unittest.skipIf(
     torch_device != "cuda" or not is_xformers_available()						,	reason="XFormers attention is only available with CUDA and `xformers` installed"						,	)
 def 					UpperCAmelCase_							(    self				:List[Any]							)->							Tuple:
     self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowercase_						,	expected_max_diff=5E-3							)
 @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline."							)
 def 					UpperCAmelCase_							(    self				:Union[str, Any]							)->							List[str]:
     pass
 @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline."							)
 def 					UpperCAmelCase_							(    self				:Tuple							)->							List[Any]:
     pass
 @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline."							)
 def 					UpperCAmelCase_							(    self				:str							)->							List[str]:
     pass



 def 					UpperCAmelCase_							(    self				:Union[str, Any]							)->							int:
     return super().test_progress_bar()






@slow
@skip_mps
class        UpperCAmelCase     (	unittest.TestCase    ):
 def 					UpperCAmelCase_							(    self				:int							)->							List[Any]:
     A__    =      VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL"						,	torch_dtype=torch.floataa							)
     pipe.enable_model_cpu_offload()

     # 10 frames
     A__    =      torch.Generator(device="cpu"							).manual_seed(0							)
     A__    =      torch.randn((1, 10, 3, 10_24, 5_76)						,	generator=lowercase_							)
     A__    =      video.to("cuda"							)

     A__    =      "Spiderman is surfing"

     A__    =      pipe(lowercase_						,	video=lowercase_						,	generator=lowercase_						,	num_inference_steps=3						,	output_type="pt"							).frames

     A__    =      np.array([-1.0_4_5_8_9_8_4, -1.1_2_7_9_2_9_7, -0.9_6_6_3_0_8_6, -0.9_1_5_0_3_9_0_6, -0.7_5_0_9_7_6_5_6]							)
     assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array							).sum() < 1E-2










'''simple docstring'''

from __future__ import annotations

from math import gcd





def 						UpperCamelCase    (							_lowerCamelCase : int						,	_lowerCamelCase : int = 2						,	_lowerCamelCase : int = 1						,	_lowerCamelCase : int = 3						,	):
    # A value less than 2 can cause an infinite loop in the algorithm.
    if num < 2:
        raise ValueError("The input value cannot be less than 2"	)

    # Because of the relationship between ``f(f(x))`` and ``f(x)``, this
    # algorithm struggles to find factors that are divisible by two.
    # As a workaround, we specifically check for two and even inputs.
    #   See: https://math.stackexchange.com/a/2856214/165820
    if num > 2 and num % 2 == 0:
        return 2

    # Pollard's Rho algorithm requires a function that returns pseudorandom
    # values between 0 <= X < ``num``.  It doesn't need to be random in the
    # sense that the output value is cryptographically secure or difficult
    # to calculate, it only needs to be random in the sense that all output
    # values should be equally likely to appear.
    # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num``
    # However, the success of Pollard's algorithm isn't guaranteed and is
    # determined in part by the initial seed and the chosen random function.
    # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num``
    # where ``C`` is a value that we can modify between each attempt.
    def rand_fn(_lowerCamelCase : int						,	_lowerCamelCase : int						,	_lowerCamelCase : int	) -> int:
        return (pow(_lowerCamelCase						,	2	) + step) % modulus

    for _ in range(_lowerCamelCase	):
        # These track the position within the cycle detection logic.
        A__    =      seed
        A__    =      seed

        while True:
            # At each iteration, the tortoise moves one step and the hare moves two.
            A__    =      rand_fn(_lowerCamelCase						,	_lowerCamelCase						,	_lowerCamelCase	)
            A__    =      rand_fn(_lowerCamelCase						,	_lowerCamelCase						,	_lowerCamelCase	)
            A__    =      rand_fn(_lowerCamelCase						,	_lowerCamelCase						,	_lowerCamelCase	)

            # At some point both the tortoise and the hare will enter a cycle whose
            # length ``p`` is a divisor of ``num``.  Once in that cycle, at some point
            # the tortoise and hare will end up on the same value modulo ``p``.
            # We can detect when this happens because the position difference between
            # the tortoise and the hare will share a common divisor with ``num``.
            A__    =      gcd(hare - tortoise						,	_lowerCamelCase	)

            if divisor == 1:
                # No common divisor yet, just keep searching.
                continue
            else:
                # We found a common divisor!
                if divisor == num:
                    # Unfortunately, the divisor is ``num`` itself and is useless.
                    break
                else:
                    # The divisor is a nontrivial factor of ``num``!
                    return divisor

        # If we made it here, then this attempt failed.
        # We need to pick a new starting seed for the tortoise and hare
        # in addition to a new step value for the random function.
        # To keep this example implementation deterministic, the
        # new values will be generated based on currently available
        # values instead of using something like ``random.randint``.

        # We can use the hare's position as the new seed.
        # This is actually what Richard Brent's the "optimized" variant does.
        A__    =      hare

        # The new step value for the random function can just be incremented.
        # At first the results will be similar to what the old function would
        # have produced, but the value will quickly diverge after a bit.
        step += 1

    # We haven't found a divisor within the requested number of attempts.
    # We were unlucky or ``num`` itself is actually prime.
    return None


if __name__ == "__main__":
  import argparse

  __lowerCAmelCase							:     Optional[int]		     =argparse.ArgumentParser()
  parser.add_argument(
      "num",
      type=int,
      help="The value to find a divisor of",
  )
  parser.add_argument(
      "--attempts",
      type=int,
      default=3,
      help="The number of attempts before giving up",
  )
  __lowerCAmelCase							:     Optional[int]		     =parser.parse_args()

  __lowerCAmelCase							:     Dict		     =pollard_rho(args.num, attempts=args.attempts)
  if divisor is None:
    print(f"""{args.num} is probably prime""")
  else:
    __lowerCAmelCase							:     Optional[Any]		     =args.num // divisor
    print(f"""{args.num} = {divisor} * {quotient}""")



