


'''simple docstring'''






from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block






@dataclass
class    __magic_name__				(						lowerCAmelCase							):
       UpperCAmelCase		 =42






class    __magic_name__				(						lowerCAmelCase   ,lowerCAmelCase							):






       @register_to_config
       def __init__(     self    ,				snake_case = 6_5_5_3_6    ,				snake_case = None    ,				snake_case = 2    ,				snake_case = 2    ,				snake_case = 0    ,				snake_case = "fourier"    ,				snake_case = True    ,				snake_case = False    ,				snake_case = 0.0    ,				snake_case = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")    ,				snake_case = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")    ,				snake_case = "UNetMidBlock1D"    ,				snake_case = None    ,				snake_case = (3_2, 3_2, 6_4)    ,				snake_case = None    ,				snake_case = 8    ,				snake_case = 1    ,				snake_case = False    ,				)		->    Dict:




          '''simple docstring'''
          super().__init__()
          _UpperCAmelCase  :  Optional[int]				       =sample_size

          # time
          if time_embedding_type == "fourier":
             _UpperCAmelCase  :  str				       =GaussianFourierProjection(
                 embedding_size=8    ,				set_W_to_weight=snake_case    ,				log=snake_case    ,				flip_sin_to_cos=snake_case)
             _UpperCAmelCase  :  Optional[Any]				       =2 * block_out_channels[0]
          elif time_embedding_type == "positional":
             _UpperCAmelCase  :  Dict				       =Timesteps(
                 block_out_channels[0]    ,				flip_sin_to_cos=snake_case    ,				downscale_freq_shift=snake_case)
             _UpperCAmelCase  :  Optional[Any]				       =block_out_channels[0]

          if use_timestep_embedding:
             _UpperCAmelCase  :  Optional[int]				       =block_out_channels[0] * 4
             _UpperCAmelCase  :  Union[str, Any]				       =TimestepEmbedding(
                 in_channels=snake_case    ,				time_embed_dim=snake_case    ,				act_fn=snake_case    ,				out_dim=block_out_channels[0]    ,				)

          _UpperCAmelCase  :  List[Any]				       =nn.ModuleList([])
          _UpperCAmelCase  :  Tuple				       =None
          _UpperCAmelCase  :  Optional[int]				       =nn.ModuleList([])
          _UpperCAmelCase  :  Dict				       =None

          # down
          _UpperCAmelCase  :  Dict				       =in_channels
          for i, down_block_type in enumerate(snake_case):
             _UpperCAmelCase  :  str				       =output_channel
             _UpperCAmelCase  :  Tuple				       =block_out_channels[i]

             if i == 0:
                input_channel += extra_in_channels

             _UpperCAmelCase  :  Tuple				       =i == len(snake_case) - 1

             _UpperCAmelCase  :  Dict				       =get_down_block(
                 snake_case    ,				num_layers=snake_case    ,				in_channels=snake_case    ,				out_channels=snake_case    ,				temb_channels=block_out_channels[0]    ,				add_downsample=not is_final_block or downsample_each_block    ,				)
             self.down_blocks.append(snake_case)

          # mid
          _UpperCAmelCase  :  str				       =get_mid_block(
              snake_case    ,				in_channels=block_out_channels[-1]    ,				mid_channels=block_out_channels[-1]    ,				out_channels=block_out_channels[-1]    ,				embed_dim=block_out_channels[0]    ,				num_layers=snake_case    ,				add_downsample=snake_case    ,				)

          # up
          _UpperCAmelCase  :  List[Any]				       =list(reversed(snake_case))
          _UpperCAmelCase  :  Optional[int]				       =reversed_block_out_channels[0]
          if out_block_type is None:
             _UpperCAmelCase  :  int				       =out_channels
          else:
             _UpperCAmelCase  :  int				       =block_out_channels[0]

          for i, up_block_type in enumerate(snake_case):
             _UpperCAmelCase  :  Dict				       =output_channel
             _UpperCAmelCase  :  Dict				       =(
                 reversed_block_out_channels[i + 1] if i < len(snake_case) - 1 else final_upsample_channels
             )

             _UpperCAmelCase  :  List[Any]				       =i == len(snake_case) - 1

             _UpperCAmelCase  :  Any				       =get_up_block(
                 snake_case    ,				num_layers=snake_case    ,				in_channels=snake_case    ,				out_channels=snake_case    ,				temb_channels=block_out_channels[0]    ,				add_upsample=not is_final_block    ,				)
             self.up_blocks.append(snake_case)
             _UpperCAmelCase  :  Optional[Any]				       =output_channel

          # out
          _UpperCAmelCase  :  int				       =norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4    ,				3_2)
          _UpperCAmelCase  :  Optional[int]				       =get_out_block(
              out_block_type=snake_case    ,				num_groups_out=snake_case    ,				embed_dim=block_out_channels[0]    ,				out_channels=snake_case    ,				act_fn=snake_case    ,				fc_dim=block_out_channels[-1] // 4    ,				)






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case    ,				snake_case = True    ,				)		->    Union[UNetaDOutput, Tuple]:




          '''simple docstring'''
          _UpperCAmelCase  :  List[Any]				       =timestep
          if not torch.is_tensor(snake_case):
             _UpperCAmelCase  :  Optional[int]				       =torch.tensor([timesteps]    ,				dtype=torch.long    ,				device=sample.device)
          elif torch.is_tensor(snake_case) and len(timesteps.shape) == 0:
             _UpperCAmelCase  :  List[str]				       =timesteps[None].to(sample.device)

          _UpperCAmelCase  :  Dict				       =self.time_proj(snake_case)
          if self.config.use_timestep_embedding:
             _UpperCAmelCase  :  List[str]				       =self.time_mlp(snake_case)
          else:
             _UpperCAmelCase  :  Optional[Any]				       =timestep_embed[..., None]
             _UpperCAmelCase  :  Optional[int]				       =timestep_embed.repeat([1, 1, sample.shape[2]]).to(sample.dtype)
             _UpperCAmelCase  :  List[str]				       =timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]))

          # 2. down
          _UpperCAmelCase  :  Union[str, Any]				       =()
          for downsample_block in self.down_blocks:
             _UpperCAmelCase       ,			_UpperCAmelCase  :  Tuple				       =downsample_block(hidden_states=snake_case    ,				temb=snake_case)
             down_block_res_samples += res_samples

          # 3. mid
          if self.mid_block:
             _UpperCAmelCase  :  List[Any]				       =self.mid_block(snake_case    ,				snake_case)

          # 4. up
          for i, upsample_block in enumerate(self.up_blocks):
             _UpperCAmelCase  :  str				       =down_block_res_samples[-1:]
             _UpperCAmelCase  :  List[str]				       =down_block_res_samples[:-1]
             _UpperCAmelCase  :  Any				       =upsample_block(snake_case    ,				res_hidden_states_tuple=snake_case    ,				temb=snake_case)

          # 5. post-process
          if self.out_block:
             _UpperCAmelCase  :  Optional[Any]				       =self.out_block(snake_case    ,				snake_case)

          if not return_dict:
             return (sample,)

          return UNetaDOutput(sample=snake_case)





'''simple docstring'''






from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
 from PIL import Image

 from ..image_utils import load_image

if is_tf_available():
 import tensorflow as tf

 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
 from ..tf_utils import stable_softmax

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

lowercase				=logging.get_logger(__name__)






@add_end_docstrings(lowerCAmelCase							)
class    __magic_name__				(						lowerCAmelCase							):






       def __init__(     self    ,				*snake_case    ,				**snake_case)		->    Dict:




          '''simple docstring'''
          super().__init__(*snake_case    ,				**snake_case)
          requires_backends(self    ,				'vision')
          self.check_model_type(
              TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
              if self.framework == 'tf'
              else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING)






       def      lowerCAmelCase						(     self    ,				snake_case=None)		->    str:




          '''simple docstring'''
          _UpperCAmelCase  :  Any				       ={}
          if top_k is not None:
             _UpperCAmelCase  :  Optional[int]				       =top_k
          return {}, {}, postprocess_params






       def __call__(     self    ,				snake_case    ,				**snake_case)		->    List[str]:




          '''simple docstring'''
          return super().__call__(snake_case    ,				**snake_case)






       def      lowerCAmelCase						(     self    ,				snake_case)		->    List[str]:




          '''simple docstring'''
          _UpperCAmelCase  :  int				       =load_image(snake_case)
          _UpperCAmelCase  :  Tuple				       =self.image_processor(images=snake_case    ,				return_tensors=self.framework)
          return model_inputs






       def      lowerCAmelCase						(     self    ,				snake_case)		->    Optional[Any]:




          '''simple docstring'''
          _UpperCAmelCase  :  List[str]				       =self.model(**snake_case)
          return model_outputs






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case=5)		->    Any:




          '''simple docstring'''
          if top_k > self.model.config.num_labels:
             _UpperCAmelCase  :  Optional[Any]				       =self.model.config.num_labels

          if self.framework == "pt":
             _UpperCAmelCase  :  List[Any]				       =model_outputs.logits.softmax(-1)[0]
             _UpperCAmelCase       ,			_UpperCAmelCase  :  Optional[Any]				       =probs.topk(snake_case)
          elif self.framework == "tf":
             _UpperCAmelCase  :  int				       =stable_softmax(model_outputs.logits    ,				axis=-1)[0]
             _UpperCAmelCase  :  List[Any]				       =tf.math.top_k(snake_case    ,				k=snake_case)
             _UpperCAmelCase       ,			_UpperCAmelCase  :  List[str]				       =topk.values.numpy(), topk.indices.numpy()
          else:
             raise ValueError(f"Unsupported framework: {self.framework}")

          _UpperCAmelCase  :  int				       =scores.tolist()
          _UpperCAmelCase  :  Tuple				       =ids.tolist()
          return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(snake_case    ,				snake_case)]

