

import hashlib
import unittest
from typing import Dict

import numpy as np

from transformers import (
    MODEL_FOR_MASK_GENERATION_MAPPING,
    TF_MODEL_FOR_MASK_GENERATION_MAPPING,
    is_vision_available,
    pipeline,
)
from transformers.pipelines import MaskGenerationPipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)


if is_vision_available():
  from PIL import Image
else:







  class        a__       :







    """simple docstring"""




    @staticmethod
    def  _lowercase      (			*UpperCAmelCase__    : Optional[int]				,				**UpperCAmelCase__    : Optional[int]		)					->Optional[int]:
          """simple docstring"""







          pass






def 					__lowercase      (     _A			)     ->						str:
      SCREAMING_SNAKE_CASE :      int       =   hashlib.mda(image.tobytes()			)
      return m.hexdigest()[:10]






def 					__lowercase      (     _A			)     ->						Dict:
      SCREAMING_SNAKE_CASE :      Any       =   np.array(_A			)
      SCREAMING_SNAKE_CASE :      List[Any]       =   npimg.shape
      return {"hash": hashimage(_A			), "shape": shape}







@is_pipeline_test
@require_vision
@require_torch
class        a__       (   unittest.TestCase       ):







  """simple docstring"""




  UpperCAmelCase__      : List[str]			       =dict(
      (list(MODEL_FOR_MASK_GENERATION_MAPPING.items()       ) if MODEL_FOR_MASK_GENERATION_MAPPING else [])       )
  UpperCAmelCase__      : str			       =dict(
      (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items()       ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else [])       )


  def  _lowercase      (			self    : Optional[Any]				,				UpperCAmelCase__    : List[Any]				,				UpperCAmelCase__    : Tuple				,				UpperCAmelCase__    : Optional[Any]		)					->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Tuple       =   MaskGenerationPipeline(model=UpperCAmelCase__				,				image_processor=UpperCAmelCase__		)
        return image_segmenter, [
            "./tests/fixtures/tests_samples/COCO/000000039769.png",
            "./tests/fixtures/tests_samples/COCO/000000039769.png",
        ]


  def  _lowercase      (			self    : Any				,				UpperCAmelCase__    : Dict				,				UpperCAmelCase__    : Tuple		)					->List[str]:
        """simple docstring"""







        pass


  @require_tf
  @unittest.skip("""Image segmentation not implemented in TF"""		)
  def  _lowercase      (			self    : List[Any]		)					->List[Any]:
        """simple docstring"""







        pass


  @slow
  @require_torch
  def  _lowercase      (			self    : Optional[int]		)					->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      str       =   pipeline("""mask-generation"""				,				model="""facebook/sam-vit-huge"""		)

        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   image_segmenter("""http://images.cocodataset.org/val2017/000000039769.jpg"""				,				points_per_batch=2_5_6		)

        # Shortening by hashing
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   []
        for i, o in enumerate(outputs["""masks"""]		):
              new_outupt += [{"mask": mask_to_test_readable(UpperCAmelCase__		), "scores": outputs["scores"][i]}]

        # fmt: off
        self.assertEqual(
            nested_simplify(UpperCAmelCase__				,				decimals=4		)				,				[
                {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.04_44},
                {"""mask""": {"""hash""": """6affa964c6""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.0_21},
                {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.01_67},
                {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.01_32},
                {"""mask""": {"""hash""": """fe8065c197""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.00_53},
                {"""mask""": {"""hash""": """e2d0b7a0b7""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.99_67},
                {"""mask""": {"""hash""": """453c7844bd""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_93},
                {"""mask""": {"""hash""": """3d44f2926d""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.99_09},
                {"""mask""": {"""hash""": """64033ddc3f""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.98_79},
                {"""mask""": {"""hash""": """801064ff79""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.98_34},
                {"""mask""": {"""hash""": """6172f276ef""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.97_16},
                {"""mask""": {"""hash""": """b49e60e084""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.96_12},
                {"""mask""": {"""hash""": """a811e775fd""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.95_99},
                {"""mask""": {"""hash""": """a6a8ebcf4b""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.95_52},
                {"""mask""": {"""hash""": """9d8257e080""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.95_32},
                {"""mask""": {"""hash""": """32de6454a8""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.95_16},
                {"""mask""": {"""hash""": """af3d4af2c8""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.94_99},
                {"""mask""": {"""hash""": """3c6db475fb""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.94_83},
                {"""mask""": {"""hash""": """c290813fb9""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.94_64},
                {"""mask""": {"""hash""": """b6f0b8f606""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_43},
                {"""mask""": {"""hash""": """92ce16bfdf""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.9_43},
                {"""mask""": {"""hash""": """c749b25868""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.94_08},
                {"""mask""": {"""hash""": """efb6cab859""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.93_35},
                {"""mask""": {"""hash""": """1ff2eafb30""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.93_26},
                {"""mask""": {"""hash""": """788b798e24""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.92_62},
                {"""mask""": {"""hash""": """abea804f0e""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.89_99},
                {"""mask""": {"""hash""": """7b9e8ddb73""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.89_86},
                {"""mask""": {"""hash""": """cd24047c8a""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.89_84},
                {"""mask""": {"""hash""": """6943e6bcbd""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.88_73},
                {"""mask""": {"""hash""": """b5f47c9191""", """shape""": (4_8_0, 6_4_0)}, """scores""": 0.88_71}
            ]				,				)
        # fmt: on




  @require_torch
  @slow
  def  _lowercase      (			self    : Tuple		)					->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Tuple       =   """facebook/sam-vit-huge"""
        SCREAMING_SNAKE_CASE :      Any       =   pipeline("""mask-generation"""				,				model=UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      List[Any]       =   image_segmenter(
            """http://images.cocodataset.org/val2017/000000039769.jpg"""				,				pred_iou_thresh=1				,				points_per_batch=2_5_6		)

        # Shortening by hashing
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   []
        for i, o in enumerate(outputs["""masks"""]		):
              new_outupt += [{"mask": mask_to_test_readable(UpperCAmelCase__		), "scores": outputs["scores"][i]}]

        self.assertEqual(
            nested_simplify(UpperCAmelCase__				,				decimals=4		)				,				[
                {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.04_44},
                {"""mask""": {"""hash""": """6affa964c6""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.02_10},
                {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.01_67},
                {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.01_32},
                {"""mask""": {"""hash""": """fe8065c197""", """shape""": (4_8_0, 6_4_0)}, """scores""": 1.00_53},
            ]				,				)







import flax.linen as nn
import jax.numpy as jnp

from .attention_flax import FlaxTransformeraDModel
from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD







class        a__       (   nn.Module       ):







  """simple docstring"""




  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : float			       =0.0
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : jnp.dtype			       =jnp.floataa


  def  _lowercase      (			self    : Tuple		)					->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      List[str]       =   []
        SCREAMING_SNAKE_CASE :      Any       =   []

        for i in range(self.num_layers		):
              SCREAMING_SNAKE_CASE :      List[Any]       =   self.in_channels if i == 0 else self.out_channels

              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   FlaxResnetBlockaD(
                  in_channels=UpperCAmelCase__				,				out_channels=self.out_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
              resnets.append(UpperCAmelCase__		)

              SCREAMING_SNAKE_CASE :      List[Any]       =   FlaxTransformeraDModel(
                  in_channels=self.out_channels				,				n_heads=self.num_attention_heads				,				d_head=self.out_channels // self.num_attention_heads				,				depth=1				,				use_linear_projection=self.use_linear_projection				,				only_cross_attention=self.only_cross_attention				,				use_memory_efficient_attention=self.use_memory_efficient_attention				,				dtype=self.dtype				,				)
              attentions.append(UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   resnets
        SCREAMING_SNAKE_CASE :      Optional[int]       =   attentions

        if self.add_downsample:
              SCREAMING_SNAKE_CASE :      Tuple       =   FlaxDownsampleaD(self.out_channels				,				dtype=self.dtype		)




  def __call__(			self    : int				,				UpperCAmelCase__    : List[str]				,				UpperCAmelCase__    : Union[str, Any]				,				UpperCAmelCase__    : Optional[Any]				,				UpperCAmelCase__    : List[str]=True		)					->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[int]       =   ()

        for resnet, attn in zip(self.resnets				,				self.attentions		):
              SCREAMING_SNAKE_CASE :      List[str]       =   resnet(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      List[str]       =   attn(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)
              output_states += (hidden_states,)

        if self.add_downsample:
              SCREAMING_SNAKE_CASE :      int       =   self.downsamplers_a(UpperCAmelCase__		)
              output_states += (hidden_states,)

        return hidden_states, output_states







class        a__       (   nn.Module       ):







  """simple docstring"""




  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : float			       =0.0
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : jnp.dtype			       =jnp.floataa


  def  _lowercase      (			self    : Dict		)					->Union[str, Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   []

        for i in range(self.num_layers		):
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   self.in_channels if i == 0 else self.out_channels

              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   FlaxResnetBlockaD(
                  in_channels=UpperCAmelCase__				,				out_channels=self.out_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
              resnets.append(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   resnets

        if self.add_downsample:
              SCREAMING_SNAKE_CASE :      List[str]       =   FlaxDownsampleaD(self.out_channels				,				dtype=self.dtype		)




  def __call__(			self    : Tuple				,				UpperCAmelCase__    : int				,				UpperCAmelCase__    : Optional[Any]				,				UpperCAmelCase__    : Any=True		)					->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[int]       =   ()

        for resnet in self.resnets:
              SCREAMING_SNAKE_CASE :      List[str]       =   resnet(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)
              output_states += (hidden_states,)

        if self.add_downsample:
              SCREAMING_SNAKE_CASE :      Dict       =   self.downsamplers_a(UpperCAmelCase__		)
              output_states += (hidden_states,)

        return hidden_states, output_states







class        a__       (   nn.Module       ):







  """simple docstring"""




  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : float			       =0.0
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : jnp.dtype			       =jnp.floataa


  def  _lowercase      (			self    : int		)					->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   []
        SCREAMING_SNAKE_CASE :      List[Any]       =   []

        for i in range(self.num_layers		):
              SCREAMING_SNAKE_CASE :      Any       =   self.in_channels if (i == self.num_layers - 1) else self.out_channels
              SCREAMING_SNAKE_CASE :      Any       =   self.prev_output_channel if i == 0 else self.out_channels

              SCREAMING_SNAKE_CASE :      Tuple       =   FlaxResnetBlockaD(
                  in_channels=resnet_in_channels + res_skip_channels				,				out_channels=self.out_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
              resnets.append(UpperCAmelCase__		)

              SCREAMING_SNAKE_CASE :      Tuple       =   FlaxTransformeraDModel(
                  in_channels=self.out_channels				,				n_heads=self.num_attention_heads				,				d_head=self.out_channels // self.num_attention_heads				,				depth=1				,				use_linear_projection=self.use_linear_projection				,				only_cross_attention=self.only_cross_attention				,				use_memory_efficient_attention=self.use_memory_efficient_attention				,				dtype=self.dtype				,				)
              attentions.append(UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   resnets
        SCREAMING_SNAKE_CASE :      List[Any]       =   attentions

        if self.add_upsample:
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   FlaxUpsampleaD(self.out_channels				,				dtype=self.dtype		)




  def __call__(			self    : Union[str, Any]				,				UpperCAmelCase__    : str				,				UpperCAmelCase__    : List[Any]				,				UpperCAmelCase__    : Any				,				UpperCAmelCase__    : Union[str, Any]				,				UpperCAmelCase__    : Dict=True		)					->Tuple:
        """simple docstring"""







        for resnet, attn in zip(self.resnets				,				self.attentions		):
              # pop res hidden states
              SCREAMING_SNAKE_CASE :      str       =   res_hidden_states_tuple[-1]
              SCREAMING_SNAKE_CASE :      Dict       =   res_hidden_states_tuple[:-1]
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   jnp.concatenate((hidden_states, res_hidden_states)				,				axis=-1		)

              SCREAMING_SNAKE_CASE :      Tuple       =   resnet(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      Tuple       =   attn(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)

        if self.add_upsample:
              SCREAMING_SNAKE_CASE :      Tuple       =   self.upsamplers_a(UpperCAmelCase__		)

        return hidden_states







class        a__       (   nn.Module       ):







  """simple docstring"""




  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : int
  UpperCAmelCase__      : float			       =0.0
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : jnp.dtype			       =jnp.floataa


  def  _lowercase      (			self    : Union[str, Any]		)					->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[Any]       =   []

        for i in range(self.num_layers		):
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   self.in_channels if (i == self.num_layers - 1) else self.out_channels
              SCREAMING_SNAKE_CASE :      str       =   self.prev_output_channel if i == 0 else self.out_channels

              SCREAMING_SNAKE_CASE :      Optional[int]       =   FlaxResnetBlockaD(
                  in_channels=resnet_in_channels + res_skip_channels				,				out_channels=self.out_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
              resnets.append(UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      Dict       =   resnets

        if self.add_upsample:
              SCREAMING_SNAKE_CASE :      int       =   FlaxUpsampleaD(self.out_channels				,				dtype=self.dtype		)




  def __call__(			self    : Optional[Any]				,				UpperCAmelCase__    : List[str]				,				UpperCAmelCase__    : Dict				,				UpperCAmelCase__    : Tuple				,				UpperCAmelCase__    : Optional[int]=True		)					->Union[str, Any]:
        """simple docstring"""







        for resnet in self.resnets:
              # pop res hidden states
              SCREAMING_SNAKE_CASE :      Dict       =   res_hidden_states_tuple[-1]
              SCREAMING_SNAKE_CASE :      Any       =   res_hidden_states_tuple[:-1]
              SCREAMING_SNAKE_CASE :      Tuple       =   jnp.concatenate((hidden_states, res_hidden_states)				,				axis=-1		)

              SCREAMING_SNAKE_CASE :      Optional[int]       =   resnet(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)

        if self.add_upsample:
              SCREAMING_SNAKE_CASE :      Optional[int]       =   self.upsamplers_a(UpperCAmelCase__		)

        return hidden_states







class        a__       (   nn.Module       ):







  """simple docstring"""




  UpperCAmelCase__      : int
  UpperCAmelCase__      : float			       =0.0
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : int			       =1
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : jnp.dtype			       =jnp.floataa


  def  _lowercase      (			self    : Optional[Any]		)					->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      str       =   [
            FlaxResnetBlockaD(
                in_channels=self.in_channels				,				out_channels=self.in_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
        ]

        SCREAMING_SNAKE_CASE :      List[str]       =   []

        for _ in range(self.num_layers		):
              SCREAMING_SNAKE_CASE :      Tuple       =   FlaxTransformeraDModel(
                  in_channels=self.in_channels				,				n_heads=self.num_attention_heads				,				d_head=self.in_channels // self.num_attention_heads				,				depth=1				,				use_linear_projection=self.use_linear_projection				,				use_memory_efficient_attention=self.use_memory_efficient_attention				,				dtype=self.dtype				,				)
              attentions.append(UpperCAmelCase__		)

              SCREAMING_SNAKE_CASE :      List[str]       =   FlaxResnetBlockaD(
                  in_channels=self.in_channels				,				out_channels=self.in_channels				,				dropout_prob=self.dropout				,				dtype=self.dtype				,				)
              resnets.append(UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      int       =   resnets
        SCREAMING_SNAKE_CASE :      Tuple       =   attentions




  def __call__(			self    : Union[str, Any]				,				UpperCAmelCase__    : List[str]				,				UpperCAmelCase__    : Union[str, Any]				,				UpperCAmelCase__    : Any				,				UpperCAmelCase__    : str=True		)					->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Tuple       =   self.resnets[0](UpperCAmelCase__				,				UpperCAmelCase__		)
        for attn, resnet in zip(self.attentions				,				self.resnets[1:]		):
              SCREAMING_SNAKE_CASE :      Optional[int]       =   attn(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      List[str]       =   resnet(UpperCAmelCase__				,				UpperCAmelCase__				,				deterministic=UpperCAmelCase__		)

        return hidden_states




