

import json
import os
import re
import unicodedata
from json.encoder import INFINITY
from typing import Any, Dict, List, Optional, Tuple, Union

import numpy as np
import regex

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging
from ...utils.generic import _is_jax, _is_numpy


a_     :    List[Any]     		=   logging.get_logger(__name__)

a_     :    Union[str, Any]     		=   {
    "artists_file": "artists.json",
    "lyrics_file": "lyrics.json",
    "genres_file": "genres.json",
}

a_     :    List[str]     		=   {
    "artists_file": {
        "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json",
    },
    "genres_file": {
        "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json",
    },
    "lyrics_file": {
        "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json",
    },
}

a_     :    Tuple     		=   {
    "jukebox": 512,
}




class   UpperCamelCase			(  SCREAMING_SNAKE_CASE ):
    __UpperCamelCase    =VOCAB_FILES_NAMES
    __UpperCamelCase    =PRETRAINED_VOCAB_FILES_MAP
    __UpperCamelCase    =PRETRAINED_LYRIC_TOKENS_SIZES
    __UpperCamelCase    =["input_ids", "attention_mask"]

    def __init__(      self			:   List[str]				,     snake_case__			:   Tuple				,     snake_case__			:   str				,     snake_case__			:   List[Any]				,     snake_case__			:   Tuple=["v3", "v2", "v2"]				,     snake_case__			:   Optional[Any]=5_1_2				,     snake_case__			:   Tuple=5				,     snake_case__			:   Optional[int]="<|endoftext|>"				,     **snake_case__			:   List[str]				,     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      AddedToken(snake_case__				,     lstrip=snake_case__				,     rstrip=snake_case__     ) if isinstance(snake_case__				,     snake_case__     ) else unk_token
     super().__init__(
         unk_token=snake_case__				,     n_genres=snake_case__				,     version=snake_case__				,     max_n_lyric_tokens=snake_case__				,     **snake_case__				,     )
     SCREAMING_SNAKE_CASE		    =      version
     SCREAMING_SNAKE_CASE		    =      max_n_lyric_tokens
     SCREAMING_SNAKE_CASE		    =      n_genres

     with open(snake_case__				,     encoding='utf-8'     ) as vocab_handle:
      SCREAMING_SNAKE_CASE		    =      json.load(snake_case__     )

     with open(snake_case__				,     encoding='utf-8'     ) as vocab_handle:
      SCREAMING_SNAKE_CASE		    =      json.load(snake_case__     )

     with open(snake_case__				,     encoding='utf-8'     ) as vocab_handle:
      SCREAMING_SNAKE_CASE		    =      json.load(snake_case__     )

     SCREAMING_SNAKE_CASE		    =      r'[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+'
     # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters.
     if len(self.lyrics_encoder     ) == 7_9:
      SCREAMING_SNAKE_CASE		    =      oov.replace(r'\-\''				,     r'\-+\''     )

     SCREAMING_SNAKE_CASE		    =      regex.compile(snake_case__     )
     SCREAMING_SNAKE_CASE		    =      {v: k for k, v in self.artists_encoder.items()}
     SCREAMING_SNAKE_CASE		    =      {v: k for k, v in self.genres_encoder.items()}
     SCREAMING_SNAKE_CASE		    =      {v: k for k, v in self.lyrics_encoder.items()}

    @property
    def UpperCamelCase      (      self			:   str     ):

     """simple docstring"""






     return len(self.artists_encoder     ) + len(self.genres_encoder     ) + len(self.lyrics_encoder     )

    def UpperCamelCase      (      self			:   Optional[int]     ):

     """simple docstring"""






     return dict(self.artists_encoder				,     self.genres_encoder				,     self.lyrics_encoder     )

    def UpperCamelCase      (      self			:   Optional[int]				,     snake_case__			:   Union[str, Any]				,     snake_case__			:   Optional[int]				,     snake_case__			:   int     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      [self.artists_encoder.get(snake_case__				,     0     ) for artist in list_artists]
     for genres in range(len(snake_case__     )     ):
      SCREAMING_SNAKE_CASE		    =      [self.genres_encoder.get(snake_case__				,     0     ) for genre in list_genres[genres]]
      SCREAMING_SNAKE_CASE		    =      list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres]     ))

     SCREAMING_SNAKE_CASE		    =      [[self.lyrics_encoder.get(snake_case__				,     0     ) for character in list_lyrics[0]], [], []]
     return artists_id, list_genres, lyric_ids

    def UpperCamelCase      (      self			:   Optional[Any]				,     snake_case__			:   str     ):

     """simple docstring"""






     return list(snake_case__     )

    def UpperCamelCase      (      self			:   int				,     snake_case__			:   Dict				,     snake_case__			:   int				,     snake_case__			:   int				,     **snake_case__			:   str     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      self.prepare_for_tokenization(snake_case__				,     snake_case__				,     snake_case__     )
     SCREAMING_SNAKE_CASE		    =      self._tokenize(snake_case__     )
     return artist, genre, lyrics

    def UpperCamelCase      (      self			:   Optional[int]				,     snake_case__			:   str				,     snake_case__			:   str				,     snake_case__			:   str				,     snake_case__			:   bool = False     ):

     """simple docstring"""






     for idx in range(len(self.version     )     ):
      if self.version[idx] == "v3":
       SCREAMING_SNAKE_CASE		    =      artists[idx].lower()
       SCREAMING_SNAKE_CASE		    =      [genres[idx].lower()]
      else:
       SCREAMING_SNAKE_CASE		    =      self._normalize(artists[idx]     ) + '.v2'
       SCREAMING_SNAKE_CASE		    =      [
           self._normalize(snake_case__     ) + '.v2' for genre in genres[idx].split('_'     )
       ]  # split is for the full dictionary with combined genres

     if self.version[0] == "v2":
      SCREAMING_SNAKE_CASE		    =      regex.compile(r'[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+'     )
      SCREAMING_SNAKE_CASE		    =      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n'
      SCREAMING_SNAKE_CASE		    =      {vocab[index]: index + 1 for index in range(len(snake_case__     )     )}
      SCREAMING_SNAKE_CASE		    =      0
      SCREAMING_SNAKE_CASE		    =      len(snake_case__     ) + 1
      SCREAMING_SNAKE_CASE		    =      self.vocab
      SCREAMING_SNAKE_CASE		    =      {v: k for k, v in self.vocab.items()}
      SCREAMING_SNAKE_CASE		    =      ''
     else:
      SCREAMING_SNAKE_CASE		    =      regex.compile(r'[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+'     )

     SCREAMING_SNAKE_CASE		    =      self._run_strip_accents(snake_case__     )
     SCREAMING_SNAKE_CASE		    =      lyrics.replace('\\'				,     '\n'     )
     SCREAMING_SNAKE_CASE		    =      self.out_of_vocab.sub(''				,     snake_case__     ), [], []
     return artists, genres, lyrics

    def UpperCamelCase      (      self			:   List[str]				,     snake_case__			:   str     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      unicodedata.normalize('NFD'				,     snake_case__     )
     SCREAMING_SNAKE_CASE		    =      []
     for char in text:
      SCREAMING_SNAKE_CASE		    =      unicodedata.category(snake_case__     )
      if cat == "Mn":
       continue
      output.append(snake_case__     )
     return "".join(snake_case__     )

    def UpperCamelCase      (      self			:   int				,     snake_case__			:   str     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      (
         [chr(snake_case__     ) for i in range(ord('a'     )				,     ord('z'     ) + 1     )]
         + [chr(snake_case__     ) for i in range(ord('A'     )				,     ord('Z'     ) + 1     )]
         + [chr(snake_case__     ) for i in range(ord('0'     )				,     ord('9'     ) + 1     )]
         + ['.']
     )
     SCREAMING_SNAKE_CASE		    =      frozenset(snake_case__     )
     SCREAMING_SNAKE_CASE		    =      re.compile(r'_+'     )
     SCREAMING_SNAKE_CASE		    =      ''.join([c if c in accepted else '_' for c in text.lower()]     )
     SCREAMING_SNAKE_CASE		    =      pattern.sub('_'				,     snake_case__     ).strip('_'     )
     return text

    def UpperCamelCase      (      self			:   int				,     snake_case__			:   List[str]     ):

     """simple docstring"""






     return " ".join(snake_case__     )

    def UpperCamelCase      (      self			:   Any				,     snake_case__			:   Dict				,     snake_case__			:   Optional[Union[str, TensorType]] = None				,     snake_case__			:   bool = False     ):

     """simple docstring"""






     if not isinstance(snake_case__				,     snake_case__     ):
      SCREAMING_SNAKE_CASE		    =      TensorType(snake_case__     )

     # Get a function reference for the correct framework
     if tensor_type == TensorType.TENSORFLOW:
      if not is_tf_available():
       raise ImportError(
           'Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.'     )
      import tensorflow as tf

      SCREAMING_SNAKE_CASE		    =      tf.constant
      SCREAMING_SNAKE_CASE		    =      tf.is_tensor
     elif tensor_type == TensorType.PYTORCH:
      if not is_torch_available():
       raise ImportError('Unable to convert output to PyTorch tensors format, PyTorch is not installed.'     )
      import torch

      SCREAMING_SNAKE_CASE		    =      torch.tensor
      SCREAMING_SNAKE_CASE		    =      torch.is_tensor
     elif tensor_type == TensorType.JAX:
      if not is_flax_available():
       raise ImportError('Unable to convert output to JAX tensors format, JAX is not installed.'     )
      import jax.numpy as jnp  # noqa: F811

      SCREAMING_SNAKE_CASE		    =      jnp.array
      SCREAMING_SNAKE_CASE		    =      _is_jax
     else:
      SCREAMING_SNAKE_CASE		    =      np.asarray
      SCREAMING_SNAKE_CASE		    =      _is_numpy

     # Do the tensor conversion in batch

     try:
      if prepend_batch_axis:
       SCREAMING_SNAKE_CASE		    =      [inputs]

      if not is_tensor(snake_case__     ):
       SCREAMING_SNAKE_CASE		    =      as_tensor(snake_case__     )
     except:  # noqa E722
      raise ValueError(
          'Unable to create tensor, you should probably activate truncation and/or padding '
          'with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.'     )

     return inputs

    def __call__(      self			:   Tuple				,     snake_case__			:   Union[str, Any]				,     snake_case__			:   Dict				,     snake_case__			:   Optional[int]=""				,     snake_case__			:   Dict="pt"     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      [0, 0, 0]
     SCREAMING_SNAKE_CASE		    =      [artist] * len(self.version     )
     SCREAMING_SNAKE_CASE		    =      [genres] * len(self.version     )

     SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      self.tokenize(snake_case__				,     snake_case__				,     snake_case__     )
     SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      self._convert_token_to_id(snake_case__				,     snake_case__				,     snake_case__     )

     SCREAMING_SNAKE_CASE		    =      [-INFINITY] * len(full_tokens[-1]     )
     SCREAMING_SNAKE_CASE		    =      [
         self.convert_to_tensors(
             [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]]				,     tensor_type=snake_case__     )
         for i in range(len(self.version     )     )
     ]
     return BatchEncoding({'input_ids': input_ids, 'attention_masks': attention_masks}     )

    def UpperCamelCase      (      self			:   Any				,     snake_case__			:   str				,     snake_case__			:   Optional[str] = None     ):

     """simple docstring"""






     if not os.path.isdir(snake_case__     ):
      logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""     )
      return

     SCREAMING_SNAKE_CASE		    =      os.path.join(
         snake_case__				,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['artists_file']     )
     with open(snake_case__				,     'w'				,     encoding='utf-8'     ) as f:
      f.write(json.dumps(self.artists_encoder				,     ensure_ascii=snake_case__     )     )

     SCREAMING_SNAKE_CASE		    =      os.path.join(
         snake_case__				,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['genres_file']     )
     with open(snake_case__				,     'w'				,     encoding='utf-8'     ) as f:
      f.write(json.dumps(self.genres_encoder				,     ensure_ascii=snake_case__     )     )

     SCREAMING_SNAKE_CASE		    =      os.path.join(
         snake_case__				,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['lyrics_file']     )
     with open(snake_case__				,     'w'				,     encoding='utf-8'     ) as f:
      f.write(json.dumps(self.lyrics_encoder				,     ensure_ascii=snake_case__     )     )

     return (artists_file, genres_file, lyrics_file)




    def UpperCamelCase      (      self			:   Tuple				,     snake_case__			:   Union[str, Any]				,     snake_case__			:   str				,     snake_case__			:   str     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.artists_decoder.get(snake_case__     )
     SCREAMING_SNAKE_CASE		    =      [self.genres_decoder.get(snake_case__     ) for genre in genres_index]
     SCREAMING_SNAKE_CASE		    =      [self.lyrics_decoder.get(snake_case__     ) for character in lyric_index]
     return artist, genres, lyrics




import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()




class   UpperCamelCase			(  unittest.TestCase ):

    def UpperCamelCase      (      self			:   Optional[int]     ):

     """simple docstring"""






     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()

    @property
    def UpperCamelCase      (      self			:   Union[str, Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      1
     SCREAMING_SNAKE_CASE		    =      3
     SCREAMING_SNAKE_CASE		    =      (3_2, 3_2)

     SCREAMING_SNAKE_CASE		    =      floats_tensor((batch_size, num_channels) + sizes				,     rng=random.Random(0     )     ).to(snake_case__     )
     return image

    @property
    def UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      UNetaDConditionModel(
         block_out_channels=(3_2, 6_4)				,     layers_per_block=2				,     sample_size=3_2				,     in_channels=4				,     out_channels=4				,     down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')				,     up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')				,     cross_attention_dim=3_2				,     )
     return model

    @property
    def UpperCamelCase      (      self			:   str     ):

     """simple docstring"""






     torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      AutoencoderKL(
         block_out_channels=[3_2, 6_4]				,     in_channels=3				,     out_channels=3				,     down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']				,     up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']				,     latent_channels=4				,     )
     return model

    @property
    def UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      RobertaSeriesConfig(
         hidden_size=3_2				,     project_dim=3_2				,     intermediate_size=3_7				,     layer_norm_eps=1E-05				,     num_attention_heads=4				,     num_hidden_layers=5				,     pad_token_id=1				,     vocab_size=5_0_0_6				,     )
     return RobertaSeriesModelWithTransformation(snake_case__     )

    @property
    def UpperCamelCase      (      self			:   Dict     ):

     """simple docstring"""






     def extract(*snake_case__			:   List[Any]				,     **snake_case__			:   Union[str, Any]     ):




      class   UpperCamelCase			:

          def __init__(      self			:   str     ):

           """simple docstring"""






           SCREAMING_SNAKE_CASE		    =      torch.ones([0]     )




          def UpperCamelCase      (      self			:   Any				,     snake_case__			:   List[str]     ):

           """simple docstring"""






           self.pixel_values.to(snake_case__     )
           return self


      return Out()

     return extract

    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      'cpu'  # ensure determinism for the device-dependent torch.Generator
     SCREAMING_SNAKE_CASE		    =      self.dummy_cond_unet
     SCREAMING_SNAKE_CASE		    =      PNDMScheduler(skip_prk_steps=snake_case__     )
     SCREAMING_SNAKE_CASE		    =      self.dummy_vae
     SCREAMING_SNAKE_CASE		    =      self.dummy_text_encoder
     SCREAMING_SNAKE_CASE		    =      XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'     )
     SCREAMING_SNAKE_CASE		    =      7_7

     SCREAMING_SNAKE_CASE		    =      self.dummy_image.to(snake_case__     )
     SCREAMING_SNAKE_CASE		    =      init_image / 2 + 0.5

     # make sure here that pndm scheduler skips prk
     SCREAMING_SNAKE_CASE		    =      AltDiffusionImgaImgPipeline(
         unet=snake_case__				,     scheduler=snake_case__				,     vae=snake_case__				,     text_encoder=snake_case__				,     tokenizer=snake_case__				,     safety_checker=snake_case__				,     feature_extractor=self.dummy_extractor				,     )
     SCREAMING_SNAKE_CASE		    =      VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,     do_normalize=snake_case__     )
     SCREAMING_SNAKE_CASE		    =      alt_pipe.to(snake_case__     )
     alt_pipe.set_progress_bar_config(disable=snake_case__     )

     SCREAMING_SNAKE_CASE		    =      'A painting of a squirrel eating a burger'
     SCREAMING_SNAKE_CASE		    =      torch.Generator(device=snake_case__     ).manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      alt_pipe(
         [prompt]				,     generator=snake_case__				,     guidance_scale=6.0				,     num_inference_steps=2				,     output_type='np'				,     image=snake_case__				,     )

     SCREAMING_SNAKE_CASE		    =      output.images

     SCREAMING_SNAKE_CASE		    =      torch.Generator(device=snake_case__     ).manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      alt_pipe(
         [prompt]				,     generator=snake_case__				,     guidance_scale=6.0				,     num_inference_steps=2				,     output_type='np'				,     image=snake_case__				,     return_dict=snake_case__				,     )[0]

     SCREAMING_SNAKE_CASE		    =      image[0, -3:, -3:, -1]
     SCREAMING_SNAKE_CASE		    =      image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 3_2, 3_2, 3)
     SCREAMING_SNAKE_CASE		    =      np.array([0.4_427, 0.3_731, 0.4_249, 0.4_941, 0.4_546, 0.4_148, 0.4_193, 0.4_666, 0.4_499]     )

     assert np.abs(image_slice.flatten() - expected_slice     ).max() < 5E-3
     assert np.abs(image_from_tuple_slice.flatten() - expected_slice     ).max() < 5E-3

    @unittest.skipIf(torch_device != 'cuda'				,     'This test requires a GPU'     )
    def UpperCamelCase      (      self			:   str     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.dummy_cond_unet
     SCREAMING_SNAKE_CASE		    =      PNDMScheduler(skip_prk_steps=snake_case__     )
     SCREAMING_SNAKE_CASE		    =      self.dummy_vae
     SCREAMING_SNAKE_CASE		    =      self.dummy_text_encoder
     SCREAMING_SNAKE_CASE		    =      XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'     )
     SCREAMING_SNAKE_CASE		    =      7_7

     SCREAMING_SNAKE_CASE		    =      self.dummy_image.to(snake_case__     )

     # put models in fp16
     SCREAMING_SNAKE_CASE		    =      unet.half()
     SCREAMING_SNAKE_CASE		    =      vae.half()
     SCREAMING_SNAKE_CASE		    =      bert.half()

     # make sure here that pndm scheduler skips prk
     SCREAMING_SNAKE_CASE		    =      AltDiffusionImgaImgPipeline(
         unet=snake_case__				,     scheduler=snake_case__				,     vae=snake_case__				,     text_encoder=snake_case__				,     tokenizer=snake_case__				,     safety_checker=snake_case__				,     feature_extractor=self.dummy_extractor				,     )
     SCREAMING_SNAKE_CASE		    =      VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,     do_normalize=snake_case__     )
     SCREAMING_SNAKE_CASE		    =      alt_pipe.to(snake_case__     )
     alt_pipe.set_progress_bar_config(disable=snake_case__     )

     SCREAMING_SNAKE_CASE		    =      'A painting of a squirrel eating a burger'
     SCREAMING_SNAKE_CASE		    =      torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      alt_pipe(
         [prompt]				,     generator=snake_case__				,     num_inference_steps=2				,     output_type='np'				,     image=snake_case__				,     ).images

     assert image.shape == (1, 3_2, 3_2, 3)




    @unittest.skipIf(torch_device != 'cuda'				,     'This test requires a GPU'     )
    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
         '/img2img/sketch-mountains-input.jpg'     )
     # resize to resolution that is divisible by 8 but not 16 or 32
     SCREAMING_SNAKE_CASE		    =      init_image.resize((7_6_0, 5_0_4)     )

     SCREAMING_SNAKE_CASE		    =      'BAAI/AltDiffusion'
     SCREAMING_SNAKE_CASE		    =      AltDiffusionImgaImgPipeline.from_pretrained(
         snake_case__				,     safety_checker=snake_case__				,     )
     pipe.to(snake_case__     )
     pipe.set_progress_bar_config(disable=snake_case__     )
     pipe.enable_attention_slicing()

     SCREAMING_SNAKE_CASE		    =      'A fantasy landscape, trending on artstation'

     SCREAMING_SNAKE_CASE		    =      torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      pipe(
         prompt=snake_case__				,     image=snake_case__				,     strength=0.75				,     guidance_scale=7.5				,     generator=snake_case__				,     output_type='np'				,     )
     SCREAMING_SNAKE_CASE		    =      output.images[0]

     SCREAMING_SNAKE_CASE		    =      image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]

     assert image.shape == (5_0_4, 7_6_0, 3)
     SCREAMING_SNAKE_CASE		    =      np.array([0.9_358, 0.9_397, 0.9_599, 0.9_901, 1.0_000, 1.0_000, 0.9_882, 1.0_000, 1.0_000]     )

     assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2




@slow
@require_torch_gpu
class   UpperCamelCase			(  unittest.TestCase ):

    def UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()




    def UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
         '/img2img/sketch-mountains-input.jpg'     )
     SCREAMING_SNAKE_CASE		    =      init_image.resize((7_6_8, 5_1_2)     )
     SCREAMING_SNAKE_CASE		    =      load_numpy(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'     )

     SCREAMING_SNAKE_CASE		    =      'BAAI/AltDiffusion'
     SCREAMING_SNAKE_CASE		    =      AltDiffusionImgaImgPipeline.from_pretrained(
         snake_case__				,     safety_checker=snake_case__				,     )
     pipe.to(snake_case__     )
     pipe.set_progress_bar_config(disable=snake_case__     )
     pipe.enable_attention_slicing()

     SCREAMING_SNAKE_CASE		    =      'A fantasy landscape, trending on artstation'

     SCREAMING_SNAKE_CASE		    =      torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      pipe(
         prompt=snake_case__				,     image=snake_case__				,     strength=0.75				,     guidance_scale=7.5				,     generator=snake_case__				,     output_type='np'				,     )
     SCREAMING_SNAKE_CASE		    =      output.images[0]

     assert image.shape == (5_1_2, 7_6_8, 3)
     # img2img is flaky across GPUs even in fp32, so using MAE here
     assert np.abs(expected_image - image     ).max() < 1E-2

