






import argparse

import requests
import torch
from PIL import Image

from transformers import (
    CLIPSegConfig,
    CLIPSegForImageSegmentation,
    CLIPSegProcessor,
    CLIPSegTextConfig,
    CLIPSegVisionConfig,
    CLIPTokenizer,
    ViTImageProcessor,
)






def     A(  snake_case_		):
       """simple docstring"""





       lowercase__:    List[Any]        =      CLIPSegTextConfig()
       lowercase__:    Union[str, Any]        =      CLIPSegVisionConfig(patch_size=16		)

       lowercase__:    Optional[int]        =      True if "refined" in model_name else False
       lowercase__:    Optional[Any]        =      16 if "rd16" in model_name else 64

       lowercase__:    List[Any]        =      CLIPSegConfig.from_text_vision_configs(
           snake_case_						,       snake_case_						,       use_complex_transposed_convolution=snake_case_						,       reduce_dim=snake_case_						,       )
       return config






def     A(  snake_case_		):
       """simple docstring"""





       if "clip_model" in name:
              lowercase__:    str        =      name.replace("clip_model"						,       "clip"		)
       if "transformer" in name:
              if "visual" in name:
                     lowercase__:    Union[str, Any]        =      name.replace("visual.transformer"						,       "vision_model"		)
              else:
                     lowercase__:    Any        =      name.replace("transformer"						,       "text_model"		)
       if "resblocks" in name:
              lowercase__:    Tuple        =      name.replace("resblocks"						,       "encoder.layers"		)
       if "ln_1" in name:
              lowercase__:    Optional[int]        =      name.replace("ln_1"						,       "layer_norm1"		)
       if "ln_2" in name:
              lowercase__:    Optional[Any]        =      name.replace("ln_2"						,       "layer_norm2"		)
       if "c_fc" in name:
              lowercase__:    Optional[Any]        =      name.replace("c_fc"						,       "fc1"		)
       if "c_proj" in name:
              lowercase__:    List[str]        =      name.replace("c_proj"						,       "fc2"		)
       if "attn" in name and "self" not in name:
              lowercase__:    str        =      name.replace("attn"						,       "self_attn"		)
       # text encoder
       if "token_embedding" in name:
              lowercase__:    int        =      name.replace("token_embedding"						,       "text_model.embeddings.token_embedding"		)
       if "positional_embedding" in name and "visual" not in name:
              lowercase__:    Optional[Any]        =      name.replace("positional_embedding"						,       "text_model.embeddings.position_embedding.weight"		)
       if "ln_final" in name:
              lowercase__:    Tuple        =      name.replace("ln_final"						,       "text_model.final_layer_norm"		)
       # vision encoder
       if "visual.class_embedding" in name:
              lowercase__:    Optional[int]        =      name.replace("visual.class_embedding"						,       "vision_model.embeddings.class_embedding"		)
       if "visual.conv1" in name:
              lowercase__:    Dict        =      name.replace("visual.conv1"						,       "vision_model.embeddings.patch_embedding"		)
       if "visual.positional_embedding" in name:
              lowercase__:    int        =      name.replace("visual.positional_embedding"						,       "vision_model.embeddings.position_embedding.weight"		)
       if "visual.ln_pre" in name:
              lowercase__:    str        =      name.replace("visual.ln_pre"						,       "vision_model.pre_layrnorm"		)
       if "visual.ln_post" in name:
              lowercase__:    Any        =      name.replace("visual.ln_post"						,       "vision_model.post_layernorm"		)
       # projection layers
       if "visual.proj" in name:
              lowercase__:    Union[str, Any]        =      name.replace("visual.proj"						,       "visual_projection.weight"		)
       if "text_projection" in name:
              lowercase__:    str        =      name.replace("text_projection"						,       "text_projection.weight"		)
       # decoder
       if "trans_conv" in name:
              lowercase__:    Union[str, Any]        =      name.replace("trans_conv"						,       "transposed_convolution"		)
       if "film_mul" in name or "film_add" in name or "reduce" in name or "transposed_convolution" in name:
              lowercase__:    int        =      "decoder." + name
       if "blocks" in name:
              lowercase__:    Dict        =      name.replace("blocks"						,       "decoder.layers"		)
       if "linear1" in name:
              lowercase__:    Any        =      name.replace("linear1"						,       "mlp.fc1"		)
       if "linear2" in name:
              lowercase__:    List[str]        =      name.replace("linear2"						,       "mlp.fc2"		)
       if "norm1" in name and "layer_" not in name:
              lowercase__:    Optional[int]        =      name.replace("norm1"						,       "layer_norm1"		)
       if "norm2" in name and "layer_" not in name:
              lowercase__:    Tuple        =      name.replace("norm2"						,       "layer_norm2"		)

       return name






def     A(  snake_case_						,       snake_case_		):
       """simple docstring"""





       for key in orig_state_dict.copy().keys():
              lowercase__:    List[str]        =      orig_state_dict.pop(snake_case_		)

              if key.startswith("clip_model"		) and "attn.in_proj" in key:
                     lowercase__:    str        =      key.split("."		)
                     if "visual" in key:
                            lowercase__:    Optional[Any]        =      int(key_split[4]		)
                            lowercase__:    Optional[Any]        =      config.vision_config.hidden_size
                            lowercase__:    Optional[int]        =      "vision_model"
                     else:
                            lowercase__:    List[Any]        =      int(key_split[3]		)
                            lowercase__:    Union[str, Any]        =      config.text_config.hidden_size
                            lowercase__:    Optional[int]        =      "text_model"

                     if "weight" in key:
                            lowercase__:    str        =      val[:dim, :]
                            lowercase__:    str        =      val[
                                dim : dim * 2, :
                            ]
                            lowercase__:    Dict        =      val[-dim:, :]
                     else:
                            lowercase__:    int        =      val[:dim]
                            lowercase__:    int        =      val[dim : dim * 2]
                            lowercase__:    Tuple        =      val[-dim:]
              elif "self_attn" in key and "out_proj" not in key:
                     lowercase__:    Any        =      key.split("."		)
                     lowercase__:    Union[str, Any]        =      int(key_split[1]		)
                     lowercase__:    Dict        =      config.reduce_dim
                     if "weight" in key:
                            lowercase__:    Any        =      val[:dim, :]
                            lowercase__:    List[Any]        =      val[dim : dim * 2, :]
                            lowercase__:    str        =      val[-dim:, :]
                     else:
                            lowercase__:    List[Any]        =      val[:dim]
                            lowercase__:    Dict        =      val[dim : dim * 2]
                            lowercase__:    Any        =      val[-dim:]
              else:
                     lowercase__:    Dict        =      rename_key(snake_case_		)
                     if "visual_projection" in new_name or "text_projection" in new_name:
                            lowercase__:    Union[str, Any]        =      val.T
                     lowercase__:    Dict        =      val

       return orig_state_dict






def     A(  ):
       """simple docstring"""





       lowercase__:    Optional[int]        =      "http://images.cocodataset.org/val2017/000000039769.jpg"
       lowercase__:    Any        =      Image.open(requests.get(snake_case_						,       stream=snake_case_		).raw		)
       return image






def     A(  snake_case_						,       snake_case_						,       snake_case_						,       snake_case_		):
       """simple docstring"""





       lowercase__:    List[str]        =      get_clipseg_config(snake_case_		)
       lowercase__:    Dict        =      CLIPSegForImageSegmentation(snake_case_		)
       model.eval()

       lowercase__:    str        =      torch.load(snake_case_						,       map_location="cpu"		)

       # remove some keys
       for key in state_dict.copy().keys():
              if key.startswith("model"		):
                     state_dict.pop(snake_case_						,       snake_case_		)

    # rename some keys
       lowercase__:    int        =      convert_state_dict(snake_case_						,       snake_case_		)
       lowercase__  ,     lowercase__:    int        =      model.load_state_dict(snake_case_						,       strict=snake_case_		)

       if missing_keys != ["clip.text_model.embeddings.position_ids", "clip.vision_model.embeddings.position_ids"]:
              raise ValueError("Missing keys that are not expected: {}".format(snake_case_		)		)
       if unexpected_keys != ["decoder.reduce.weight", "decoder.reduce.bias"]:
              raise ValueError(F"""Unexpected keys: {unexpected_keys}"""		)

       lowercase__:    str        =      ViTImageProcessor(size=352		)
       lowercase__:    int        =      CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch32"		)
       lowercase__:    Any        =      CLIPSegProcessor(image_processor=snake_case_						,       tokenizer=snake_case_		)

       lowercase__:    Optional[int]        =      prepare_img()
       lowercase__:    int        =      ["a glass", "something to fill", "wood", "a jar"]

       lowercase__:    Dict        =      processor(text=snake_case_						,       images=[image] * len(snake_case_		)						,       padding="max_length"						,       return_tensors="pt"		)

       with torch.no_grad():
              lowercase__:    Any        =      model(**snake_case_		)

       # verify values
       lowercase__:    Dict        =      torch.tensor([0.11_10, -0.18_82, 0.16_45]		)
       lowercase__:    Dict        =      torch.tensor([0.26_92, -0.71_97, -0.13_28]		)
       if model_name == "clipseg-rd64-refined":
              lowercase__:    int        =      torch.tensor(
                  [[-10.04_07, -9.94_31, -10.26_46], [-9.97_51, -9.70_64, -9.95_86], [-9.68_91, -9.56_45, -9.96_18]]		)
       elif model_name == "clipseg-rd64":
              lowercase__:    List[Any]        =      torch.tensor(
                  [[-7.28_77, -7.27_11, -7.24_63], [-7.26_52, -7.27_80, -7.25_20], [-7.22_39, -7.22_04, -7.20_01]]		)
       elif model_name == "clipseg-rd16":
              lowercase__:    int        =      torch.tensor(
                  [[-6.39_55, -6.40_55, -6.41_51], [-6.39_11, -6.40_33, -6.41_00], [-6.34_74, -6.37_02, -6.37_62]]		)
       else:
              raise ValueError(F"""Model name {model_name} not supported."""		)

       assert torch.allclose(outputs.logits[0, :3, :3]						,       snake_case_						,       atol=1E-3		)
       assert torch.allclose(outputs.conditional_embeddings[0, :3]						,       snake_case_						,       atol=1E-3		)
       assert torch.allclose(outputs.pooled_output[0, :3]						,       snake_case_						,       atol=1E-3		)
       print("Looks ok!"		)

       if pytorch_dump_folder_path is not None:
              print(F"""Saving model and processor to {pytorch_dump_folder_path}"""		)
              model.save_pretrained(snake_case_		)
              processor.save_pretrained(snake_case_		)

       if push_to_hub:
              print(F"""Pushing model and processor for {model_name} to the hub"""		)
              model.push_to_hub(F"""CIDAS/{model_name}"""		)
              processor.push_to_hub(F"""CIDAS/{model_name}"""		)


if __name__ == "__main__":
  UpperCamelCase			=      argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      """--model_name""",
      default="""clipseg-rd64""",
      type=str,
      choices=["""clipseg-rd16""", """clipseg-rd64""", """clipseg-rd64-refined"""],
      help=(
          """Name of the model. Supported models are: clipseg-rd64, clipseg-rd16 and clipseg-rd64-refined (rd meaning"""
          """ reduce dimension)"""
      ),
  )
  parser.add_argument(
      """--checkpoint_path""",
      default="""/Users/nielsrogge/Documents/CLIPSeg/clip_plus_rd64-uni.pth""",
      type=str,
      help=(
          """Path to the original checkpoint. Note that the script assumes that the checkpoint includes both CLIP and"""
          """ the decoder weights."""
      ),
  )
  parser.add_argument(
      """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
  )
  parser.add_argument(
      """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
  )

  UpperCamelCase			=      parser.parse_args()
  convert_clipseg_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)














"""simple docstring"""





# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ..utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


UpperCamelCase			=      {
    """agents""": ["""Agent""", """AzureOpenAiAgent""", """HfAgent""", """LocalAgent""", """OpenAiAgent"""],
    """base""": ["""PipelineTool""", """RemoteTool""", """Tool""", """launch_gradio_demo""", """load_tool"""],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCamelCase			=      ["""DocumentQuestionAnsweringTool"""]
  UpperCamelCase			=      ["""ImageCaptioningTool"""]
  UpperCamelCase			=      ["""ImageQuestionAnsweringTool"""]
  UpperCamelCase			=      ["""ImageSegmentationTool"""]
  UpperCamelCase			=      ["""SpeechToTextTool"""]
  UpperCamelCase			=      ["""TextClassificationTool"""]
  UpperCamelCase			=      ["""TextQuestionAnsweringTool"""]
  UpperCamelCase			=      ["""TextSummarizationTool"""]
  UpperCamelCase			=      ["""TextToSpeechTool"""]
  UpperCamelCase			=      ["""TranslationTool"""]

if TYPE_CHECKING:
  from .agents import Agent, AzureOpenAiAgent, HfAgent, LocalAgent, OpenAiAgent
  from .base import PipelineTool, RemoteTool, Tool, launch_gradio_demo, load_tool

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .document_question_answering import DocumentQuestionAnsweringTool
    from .image_captioning import ImageCaptioningTool
    from .image_question_answering import ImageQuestionAnsweringTool
    from .image_segmentation import ImageSegmentationTool
    from .speech_to_text import SpeechToTextTool
    from .text_classification import TextClassificationTool
    from .text_question_answering import TextQuestionAnsweringTool
    from .text_summarization import TextSummarizationTool
    from .text_to_speech import TextToSpeechTool
    from .translation import TranslationTool
else:
  import sys

  UpperCamelCase			=      _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)






