




'''simple docstring'''




from math import acos, sin
from typing import List, Tuple, Union

import numpy as np
import torch
from PIL import Image

from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel

class     lowerCAmelCase_ (			lowercase_ ):







  '''simple docstring'''







  lowerCAmelCase_					:       List[Any]					  =    ["""vqvae"""]


  def __init__(    self     :						Optional[Any]    ,		_UpperCAmelCase     :						AutoencoderKL    ,		_UpperCAmelCase     :						UNetaDConditionModel    ,		_UpperCAmelCase     :						Mel    ,		_UpperCAmelCase     :						Union[DDIMScheduler, DDPMScheduler]    ,		):






   """simple docstring"""






   super().__init__()
   self.register_modules(unet=UpperCamelCase_    ,		scheduler=UpperCamelCase_    ,		mel=UpperCamelCase_    ,		vqvae=UpperCamelCase_			)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						Optional[Any]			):






   """simple docstring"""






   return 50 if isinstance(self.scheduler    ,		UpperCamelCase_			) else 10_00


  @torch.no_grad()
  def __call__(    self     :						int    ,		_UpperCAmelCase     :						int = 1    ,		_UpperCAmelCase     :						str = None    ,		_UpperCAmelCase     :						np.ndarray = None    ,		_UpperCAmelCase     :						int = 0    ,		_UpperCAmelCase     :						int = 0    ,		_UpperCAmelCase     :						int = None    ,		_UpperCAmelCase     :						torch.Generator = None    ,		_UpperCAmelCase     :						float = 0    ,		_UpperCAmelCase     :						float = 0    ,		_UpperCAmelCase     :						torch.Generator = None    ,		_UpperCAmelCase     :						float = 0    ,		_UpperCAmelCase     :						torch.Tensor = None    ,		_UpperCAmelCase     :						torch.Tensor = None    ,		_UpperCAmelCase     :						Dict=True    ,		):






   """simple docstring"""






   UpperCAmelCase__      				=     steps or self.get_default_steps()
   self.scheduler.set_timesteps(UpperCamelCase_			)
   UpperCAmelCase__      				=     step_generator or generator
   # For backwards compatibility
   if type(self.unet.config.sample_size			) == int:
    UpperCAmelCase__      				=     (self.unet.config.sample_size, self.unet.config.sample_size)
   if noise is None:
    UpperCAmelCase__      				=     randn_tensor(
        (
            batch_size,
            self.unet.config.in_channels,
            self.unet.config.sample_size[0],
            self.unet.config.sample_size[1],
        )    ,		generator=UpperCamelCase_    ,		device=self.device    ,		)
   UpperCAmelCase__      				=     noise
   UpperCAmelCase__      				=     None

   if audio_file is not None or raw_audio is not None:
    self.mel.load_audio(UpperCamelCase_    ,		UpperCamelCase_			)
    UpperCAmelCase__      				=     self.mel.audio_slice_to_image(UpperCamelCase_			)
    UpperCAmelCase__      				=     np.frombuffer(input_image.tobytes()    ,		dtype="""uint8"""			).reshape(
        (input_image.height, input_image.width)			)
    UpperCAmelCase__      				=     (input_image / 2_55) * 2 - 1
    UpperCAmelCase__      				=     torch.tensor(input_image[np.newaxis, :, :]    ,		dtype=torch.float			).to(self.device			)

    if self.vqvae is not None:
     UpperCAmelCase__      				=     self.vqvae.encode(torch.unsqueeze(UpperCamelCase_    ,		0			)			).latent_dist.sample(
         generator=UpperCamelCase_			)[0]
     UpperCAmelCase__      				=     self.vqvae.config.scaling_factor * input_images

    if start_step > 0:
     UpperCAmelCase__      				=     self.scheduler.add_noise(UpperCamelCase_    ,		UpperCamelCase_    ,		self.scheduler.timesteps[start_step - 1]			)

    UpperCAmelCase__      				=     (
        self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
    )
    UpperCAmelCase__      				=     int(mask_start_secs * pixels_per_second			)
    UpperCAmelCase__      				=     int(mask_end_secs * pixels_per_second			)
    UpperCAmelCase__      				=     self.scheduler.add_noise(UpperCamelCase_    ,		UpperCamelCase_    ,		torch.tensor(self.scheduler.timesteps[start_step:]			)			)

   for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]			)			):
    if isinstance(self.unet    ,		UpperCamelCase_			):
     UpperCAmelCase__      				=     self.unet(UpperCamelCase_    ,		UpperCamelCase_    ,		UpperCamelCase_			)["""sample"""]
    else:
     UpperCAmelCase__      				=     self.unet(UpperCamelCase_    ,		UpperCamelCase_			)["""sample"""]

    if isinstance(self.scheduler    ,		UpperCamelCase_			):
     UpperCAmelCase__      				=     self.scheduler.step(
         model_output=UpperCamelCase_    ,		timestep=UpperCamelCase_    ,		sample=UpperCamelCase_    ,		eta=UpperCamelCase_    ,		generator=UpperCamelCase_    ,		)["""prev_sample"""]
    else:
     UpperCAmelCase__      				=     self.scheduler.step(
         model_output=UpperCamelCase_    ,		timestep=UpperCamelCase_    ,		sample=UpperCamelCase_    ,		generator=UpperCamelCase_    ,		)["""prev_sample"""]

    if mask is not None:
     if mask_start > 0:
      UpperCAmelCase__      				=     mask[:, step, :, :mask_start]
     if mask_end > 0:
      UpperCAmelCase__      				=     mask[:, step, :, -mask_end:]

   if self.vqvae is not None:
    # 0.18215 was scaling factor used in training to ensure unit variance
    UpperCAmelCase__      				=     1 / self.vqvae.config.scaling_factor * images
    UpperCAmelCase__      				=     self.vqvae.decode(UpperCamelCase_			)["""sample"""]

   UpperCAmelCase__      				=     (images / 2 + 0.5).clamp(0    ,		1			)
   UpperCAmelCase__      				=     images.cpu().permute(0    ,		2    ,		3    ,		1			).numpy()
   UpperCAmelCase__      				=     (images * 2_55).round().astype("""uint8"""			)
   UpperCAmelCase__      				=     list(
       (Image.fromarray(_[:, :, 0]			) for _ in images)
       if images.shape[3] == 1
       else (Image.fromarray(UpperCamelCase_    ,		mode="""RGB"""			).convert("""L"""			) for _ in images)			)

   UpperCAmelCase__      				=     [self.mel.image_to_audio(UpperCamelCase_			) for _ in images]
   if not return_dict:
    return images, (self.mel.get_sample_rate(), audios)

   return BaseOutput(**AudioPipelineOutput(np.array(UpperCamelCase_			)[:, np.newaxis, :]			)    ,		**ImagePipelineOutput(UpperCamelCase_			)			)


  @torch.no_grad()
  def 				SCREAMING_SNAKE_CASE__      (    self     :						List[str]    ,		_UpperCAmelCase     :						List[Image.Image]    ,		_UpperCAmelCase     :						int = 50			):






   """simple docstring"""






   assert isinstance(self.scheduler    ,		UpperCamelCase_			)
   self.scheduler.set_timesteps(UpperCamelCase_			)
   UpperCAmelCase__      				=     np.array(
       [np.frombuffer(image.tobytes()    ,		dtype="""uint8"""			).reshape((1, image.height, image.width)			) for image in images]			)
   UpperCAmelCase__      				=     (sample / 2_55) * 2 - 1
   UpperCAmelCase__      				=     torch.Tensor(UpperCamelCase_			).to(self.device			)

   for t in self.progress_bar(torch.flip(self.scheduler.timesteps    ,		(0,)			)			):
    UpperCAmelCase__      				=     t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
    UpperCAmelCase__      				=     self.scheduler.alphas_cumprod[t]
    UpperCAmelCase__      				=     (
        self.scheduler.alphas_cumprod[prev_timestep]
        if prev_timestep >= 0
        else self.scheduler.final_alpha_cumprod
    )
    UpperCAmelCase__      				=     1 - alpha_prod_t
    UpperCAmelCase__      				=     self.unet(UpperCamelCase_    ,		UpperCamelCase_			)["""sample"""]
    UpperCAmelCase__      				=     (1 - alpha_prod_t_prev) ** 0.5 * model_output
    UpperCAmelCase__      				=     (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
    UpperCAmelCase__      				=     sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output

   return sample



  @staticmethod
  def 				SCREAMING_SNAKE_CASE__      (    _UpperCAmelCase     :						torch.Tensor    ,		_UpperCAmelCase     :						torch.Tensor    ,		_UpperCAmelCase     :						float			):






   """simple docstring"""






   UpperCAmelCase__      				=     acos(torch.dot(torch.flatten(UpperCamelCase_			)    ,		torch.flatten(UpperCamelCase_			)			) / torch.norm(UpperCamelCase_			) / torch.norm(UpperCamelCase_			)			)
   return sin((1 - alpha) * theta			) * xa / sin(UpperCamelCase_			) + sin(alpha * theta			) * xa / sin(UpperCamelCase_			)








import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer


class    __lowercase   (						lowercase_	):







     '''simple docstring'''




     def 		lowerCAmelCase_  (					self							:      int					):


         """simple docstring"""



         __A       =						tempfile.mkdtemp()
         __A       =						5

         # Realm tok
         __A       =						[
             """[UNK]""",
             """[CLS]""",
             """[SEP]""",
             """[PAD]""",
             """[MASK]""",
             """test""",
             """question""",
             """this""",
             """is""",
             """the""",
             """first""",
             """second""",
             """third""",
             """fourth""",
             """fifth""",
             """record""",
             """want""",
             """##want""",
             """##ed""",
             """wa""",
             """un""",
             """runn""",
             """##ing""",
             """,""",
             """low""",
             """lowest""",
         ]
         __A       =						os.path.join(self.tmpdirname			,						"""realm_tokenizer"""					)
         os.makedirs(UpperCamelCase_			,						exist_ok=UpperCamelCase_					)
         __A       =						os.path.join(UpperCamelCase_			,						VOCAB_FILES_NAMES["""vocab_file"""]					)
         with open(self.vocab_file			,						"""w"""			,						encoding="""utf-8"""					) as vocab_writer:
             vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]					)					)

         __A       =						os.path.join(self.tmpdirname			,						"""realm_block_records"""					)
         os.makedirs(UpperCamelCase_			,						exist_ok=UpperCamelCase_					)




     def 		lowerCAmelCase_  (					self							:      List[Any]					):


         """simple docstring"""



         return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname			,						"""realm_tokenizer"""					)					)




     def 		lowerCAmelCase_  (					self							:      Union[str, Any]					):


         """simple docstring"""



         shutil.rmtree(self.tmpdirname					)




     def 		lowerCAmelCase_  (					self							:      str					):


         """simple docstring"""



         __A       =						RealmConfig(num_block_records=self.num_block_records					)
         return config




     def 		lowerCAmelCase_  (					self							:      Dict					):


         """simple docstring"""



         __A       =						Dataset.from_dict(
             {
                 """id""": ["""0""", """1"""],
                 """question""": ["""foo""", """bar"""],
                 """answers""": [["""Foo""", """Bar"""], ["""Bar"""]],
             }					)
         return dataset




     def 		lowerCAmelCase_  (					self							:      str					):


         """simple docstring"""



         __A       =						np.array(
             [
                 B"""This is the first record""",
                 B"""This is the second record""",
                 B"""This is the third record""",
                 B"""This is the fourth record""",
                 B"""This is the fifth record""",
                 B"""This is a longer longer longer record""",
             ]			,						dtype=UpperCamelCase_			,						)
         return block_records




     def 		lowerCAmelCase_  (					self							:      List[Any]					):


         """simple docstring"""



         __A       =						RealmRetriever(
             block_records=self.get_dummy_block_records()			,						tokenizer=self.get_tokenizer()			,						)
         return retriever




     def 		lowerCAmelCase_  (					self							:      Dict					):


         """simple docstring"""



         __A       =						self.get_config()
         __A       =						self.get_dummy_retriever()
         __A       =						retriever.tokenizer

         __A       =						np.array([0, 3]			,						dtype="""long"""					)
         __A       =						tokenizer(["""Test question"""]					).input_ids
         __A       =						tokenizer(
             ["""the fourth"""]			,						add_special_tokens=UpperCamelCase_			,						return_token_type_ids=UpperCamelCase_			,						return_attention_mask=UpperCamelCase_			,						).input_ids
         __A       =						config.reader_seq_len

         __A     ,						__A     ,						__A     ,						__A       =						retriever(
             UpperCamelCase_			,						UpperCamelCase_			,						answer_ids=UpperCamelCase_			,						max_length=UpperCamelCase_			,						return_tensors="""np"""					)

         self.assertEqual(len(UpperCamelCase_					)			,						2					)
         self.assertEqual(len(UpperCamelCase_					)			,						2					)
         self.assertEqual(len(UpperCamelCase_					)			,						2					)
         self.assertEqual(concat_inputs.input_ids.shape			,						(2, 10)					)
         self.assertEqual(concat_inputs.attention_mask.shape			,						(2, 10)					)
         self.assertEqual(concat_inputs.token_type_ids.shape			,						(2, 10)					)
         self.assertEqual(concat_inputs.special_tokens_mask.shape			,						(2, 10)					)
         self.assertEqual(
             tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0]					)			,						["""[CLS]""", """test""", """question""", """[SEP]""", """this""", """is""", """the""", """first""", """record""", """[SEP]"""]			,						)
         self.assertEqual(
             tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1]					)			,						["""[CLS]""", """test""", """question""", """[SEP]""", """this""", """is""", """the""", """fourth""", """record""", """[SEP]"""]			,						)




     def 		lowerCAmelCase_  (					self							:      str					):


         """simple docstring"""



         __A       =						self.get_config()
         __A       =						self.get_dummy_retriever()
         __A       =						retriever.tokenizer

         __A       =						np.array([0, 3, 5]			,						dtype="""long"""					)
         __A       =						tokenizer(["""Test question"""]					).input_ids
         __A       =						tokenizer(
             ["""the fourth""", """longer longer"""]			,						add_special_tokens=UpperCamelCase_			,						return_token_type_ids=UpperCamelCase_			,						return_attention_mask=UpperCamelCase_			,						).input_ids
         __A       =						config.reader_seq_len

         __A     ,						__A     ,						__A     ,						__A       =						retriever(
             UpperCamelCase_			,						UpperCamelCase_			,						answer_ids=UpperCamelCase_			,						max_length=UpperCamelCase_			,						return_tensors="""np"""					)

         self.assertEqual([False, True, True]			,						UpperCamelCase_					)
         self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]]			,						UpperCamelCase_					)
         self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]]			,						UpperCamelCase_					)





     def 		lowerCAmelCase_  (					self							:      str					):


         """simple docstring"""



         __A       =						self.get_dummy_retriever()
         retriever.save_pretrained(os.path.join(self.tmpdirname			,						"""realm_block_records"""					)					)

         # Test local path
         __A       =						retriever.from_pretrained(os.path.join(self.tmpdirname			,						"""realm_block_records"""					)					)
         self.assertEqual(retriever.block_records[0]			,						B"""This is the first record"""					)

         # Test mocked remote path
         with patch("""transformers.models.realm.retrieval_realm.hf_hub_download"""					) as mock_hf_hub_download:
             __A       =						os.path.join(
                 os.path.join(self.tmpdirname			,						"""realm_block_records"""					)			,						_REALM_BLOCK_RECORDS_FILENAME					)
             __A       =						RealmRetriever.from_pretrained("""google/realm-cc-news-pretrained-openqa"""					)

         self.assertEqual(retriever.block_records[0]			,						B"""This is the first record"""					)




