





'''simple docstring'''






import argparse

import requests
import torch
from PIL import Image

from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor
def   UpperCamelCase__ (						lowerCAmelCase    ):





      """simple docstring"""


      _lowerCAmelCase					=				SwinConfig(image_size=1_92    )

      if "base" in model_name:
            _lowerCAmelCase					=				6
            _lowerCAmelCase					=				1_28
            _lowerCAmelCase					=				(2, 2, 18, 2)
            _lowerCAmelCase					=				(4, 8, 16, 32)
      elif "large" in model_name:
            _lowerCAmelCase					=				12
            _lowerCAmelCase					=				1_92
            _lowerCAmelCase					=				(2, 2, 18, 2)
            _lowerCAmelCase					=				(6, 12, 24, 48)
      else:
            raise ValueError("""Model not supported, only supports base and large variants"""    )

      _lowerCAmelCase					=				window_size
      _lowerCAmelCase					=				embed_dim
      _lowerCAmelCase					=				depths
      _lowerCAmelCase					=				num_heads

      return config
def   UpperCamelCase__ (						lowerCAmelCase    ):





      """simple docstring"""


      if "encoder.mask_token" in name:
            _lowerCAmelCase					=				name.replace("""encoder.mask_token"""				,      """embeddings.mask_token"""    )
      if "encoder.patch_embed.proj" in name:
            _lowerCAmelCase					=				name.replace("""encoder.patch_embed.proj"""				,      """embeddings.patch_embeddings.projection"""    )
      if "encoder.patch_embed.norm" in name:
            _lowerCAmelCase					=				name.replace("""encoder.patch_embed.norm"""				,      """embeddings.norm"""    )
      if "attn.proj" in name:
            _lowerCAmelCase					=				name.replace("""attn.proj"""				,      """attention.output.dense"""    )
      if "attn" in name:
            _lowerCAmelCase					=				name.replace("""attn"""				,      """attention.self"""    )
      if "norm1" in name:
            _lowerCAmelCase					=				name.replace("""norm1"""				,      """layernorm_before"""    )
      if "norm2" in name:
            _lowerCAmelCase					=				name.replace("""norm2"""				,      """layernorm_after"""    )
      if "mlp.fc1" in name:
            _lowerCAmelCase					=				name.replace("""mlp.fc1"""				,      """intermediate.dense"""    )
      if "mlp.fc2" in name:
            _lowerCAmelCase					=				name.replace("""mlp.fc2"""				,      """output.dense"""    )

      if name == "encoder.norm.weight":
            _lowerCAmelCase					=				"""layernorm.weight"""
      if name == "encoder.norm.bias":
            _lowerCAmelCase					=				"""layernorm.bias"""

      if "decoder" in name:
            pass
      else:
            _lowerCAmelCase					=				"""swin.""" + name

      return name
def   UpperCamelCase__ (						lowerCAmelCase				,      lowerCAmelCase    ):





      """simple docstring"""


      for key in orig_state_dict.copy().keys():
            _lowerCAmelCase					=				orig_state_dict.pop(lowerCAmelCase    )

            if "attn_mask" in key:
                  pass
            elif "qkv" in key:
                  _lowerCAmelCase					=				key.split("""."""    )
                  _lowerCAmelCase					=				int(key_split[2]    )
                  _lowerCAmelCase					=				int(key_split[4]    )
                  _lowerCAmelCase					=				model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size

                  if "weight" in key:
                        _lowerCAmelCase					=				val[:dim, :]
                        _lowerCAmelCase					=				val[
                            dim : dim * 2, :
                        ]
                        _lowerCAmelCase					=				val[-dim:, :]
                  else:
                        _lowerCAmelCase					=				val[
                            :dim
                        ]
                        _lowerCAmelCase					=				val[
                            dim : dim * 2
                        ]
                        _lowerCAmelCase					=				val[
                            -dim:
                        ]
            else:
                  _lowerCAmelCase					=				val

      return orig_state_dict
def   UpperCamelCase__ (						lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase    ):





      """simple docstring"""


      _lowerCAmelCase					=				torch.load(lowerCAmelCase				,      map_location="""cpu"""    )["""model"""]

      _lowerCAmelCase					=				get_swin_config(lowerCAmelCase    )
      _lowerCAmelCase					=				SwinForMaskedImageModeling(lowerCAmelCase    )
      model.eval()

      _lowerCAmelCase					=				convert_state_dict(lowerCAmelCase				,      lowerCAmelCase    )
      model.load_state_dict(lowerCAmelCase    )

      _lowerCAmelCase					=				"""http://images.cocodataset.org/val2017/000000039769.jpg"""

      _lowerCAmelCase					=				ViTImageProcessor(size={"""height""": 1_92, """width""": 1_92}    )
      _lowerCAmelCase					=				Image.open(requests.get(lowerCAmelCase				,      stream=lowerCAmelCase    ).raw    )
      _lowerCAmelCase					=				image_processor(images=lowerCAmelCase				,      return_tensors="""pt"""    )

      with torch.no_grad():
            _lowerCAmelCase					=				model(**lowerCAmelCase    ).logits

      print(outputs.keys()    )
      print("""Looks ok!"""    )

      if pytorch_dump_folder_path is not None:
            print(f"Saving model {model_name} to {pytorch_dump_folder_path}"    )
            model.save_pretrained(lowerCAmelCase    )

            print(f"Saving image processor to {pytorch_dump_folder_path}"    )
            image_processor.save_pretrained(lowerCAmelCase    )

      if push_to_hub:
            print(f"Pushing model and image processor for {model_name} to hub"    )
            model.push_to_hub(f"microsoft/{model_name}"    )
            image_processor.push_to_hub(f"microsoft/{model_name}"    )


if __name__ == "__main__":
      A__							:  str    =argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          '''--model_name''',
          default='''swin-base-simmim-window6-192''',
          type=str,
          choices=['''swin-base-simmim-window6-192''', '''swin-large-simmim-window12-192'''],
          help='''Name of the Swin SimMIM model you\'d like to convert.''',
      )
      parser.add_argument(
          '''--checkpoint_path''',
          default='''/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth''',
          type=str,
          help='''Path to the original PyTorch checkpoint (.pth file).''',
      )
      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.'''
      )

      A__							:  List[Any]    =parser.parse_args()
      convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)













'''simple docstring'''






from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('''3.8'''):
      import importlib_metadata
else:
      import importlib.metadata as importlib_metadata


A__							:  Dict    =''''''


if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''):




      class 					UpperCAmelCase	(     tr.AbstractTransform  ):




            def __init__(     self     :					Any     ,     __snake_case     :					str = " "    )							-> Any:
                  _lowerCAmelCase					=				sentence_delimiter




            def 							lowercase__       (     self     :					str     ,     __snake_case     :					str    )							-> Optional[int]:
                  return list(__snake_case    )




            def 							lowercase__       (     self     :					Tuple     ,     __snake_case     :					List[str]    )							-> Union[str, Any]:
                  _lowerCAmelCase					=				[]
                  for sent_idx, sentence in enumerate(__snake_case    ):
                        chars.extend(self.process_string(__snake_case    )    )
                        if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__snake_case    ) - 1:
                              chars.append(self.sentence_delimiter    )
                  return chars




      A__							:  Optional[Any]    =tr.Compose(
          [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
      )
else:
      A__							:  Tuple    =tr.Compose(
          [
              tr.RemoveMultipleSpaces(),
              tr.Strip(),
              tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
              tr.ReduceToListOfListOfChars(),
          ]
      )


A__							:  List[str]    ='''\
@inproceedings{inproceedings,
    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
    year = {2004},
    month = {01},
    pages = {},
    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
'''

A__							:  Optional[int]    ='''\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).

CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
'''

A__							:  List[str]    ='''
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = ["this is the prediction", "there is an other sample"]
    >>> references = ["this is the reference", "there is another one"]
    >>> cer = datasets.load_metric("cer")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
'''




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION				,						_KWARGS_DESCRIPTION  )
class 					UpperCAmelCase	(     datasets.Metric  ):




      def 							lowercase__       (     self     :					Any    )							-> Dict:
            return datasets.MetricInfo(
                description=_DESCRIPTION     ,     citation=_CITATION     ,     inputs_description=_KWARGS_DESCRIPTION     ,     features=datasets.Features(
                    {
                        """predictions""": datasets.Value("""string"""     ,     id="""sequence"""    ),
                        """references""": datasets.Value("""string"""     ,     id="""sequence"""    ),
                    }    )     ,     codebase_urls=["""https://github.com/jitsi/jiwer/"""]     ,     reference_urls=[
                    """https://en.wikipedia.org/wiki/Word_error_rate""",
                    """https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates""",
                ]     ,     )




      def 							lowercase__       (     self     :					Optional[Any]     ,     __snake_case     :					Optional[Any]     ,     __snake_case     :					List[str]     ,     __snake_case     :					Tuple=False    )							-> List[Any]:
            if concatenate_texts:
                  return jiwer.compute_measures(
                      __snake_case     ,     __snake_case     ,     truth_transform=__snake_case     ,     hypothesis_transform=__snake_case     ,     )["wer"]

            _lowerCAmelCase					=				0
            _lowerCAmelCase					=				0
            for prediction, reference in zip(__snake_case     ,     __snake_case    ):
                  _lowerCAmelCase					=				jiwer.compute_measures(
                      __snake_case     ,     __snake_case     ,     truth_transform=__snake_case     ,     hypothesis_transform=__snake_case     ,     )
                  incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                  total += measures["substitutions"] + measures["deletions"] + measures["hits"]

            return incorrect / total






