
import argparse
import hashlib
import os
import urllib
import warnings

import torch
from torch import nn
from tqdm import tqdm

from transformers import WhisperConfig, WhisperForConditionalGeneration


lowerCamelCase_						: Dict         =  {
    'tiny.en': 'https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt',
    'tiny': 'https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt',
    'base.en': 'https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt',
    'base': 'https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt',
    'small.en': 'https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt',
    'small': 'https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt',
    'medium.en': 'https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt',
    'medium': 'https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt',
    'large': 'https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt',
    'large-v2': 'https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt',
}







def        A__					(						lowerCamelCase						)  ->	Optional[int]:
    UpperCamelCase_:							List[Any]	=						["""layers""", """blocks"""]
    for k in ignore_keys:
        state_dict.pop(lowercase_     ,    lowercase_						)


lowerCamelCase_						: Any         =  {
    'blocks': 'layers',
    'mlp.0': 'fc1',
    'mlp.2': 'fc2',
    'mlp_ln': 'final_layer_norm',
    '.attn.query': '.self_attn.q_proj',
    '.attn.key': '.self_attn.k_proj',
    '.attn.value': '.self_attn.v_proj',
    '.attn_ln': '.self_attn_layer_norm',
    '.attn.out': '.self_attn.out_proj',
    '.cross_attn.query': '.encoder_attn.q_proj',
    '.cross_attn.key': '.encoder_attn.k_proj',
    '.cross_attn.value': '.encoder_attn.v_proj',
    '.cross_attn_ln': '.encoder_attn_layer_norm',
    '.cross_attn.out': '.encoder_attn.out_proj',
    'decoder.ln.': 'decoder.layer_norm.',
    'encoder.ln.': 'encoder.layer_norm.',
    'token_embedding': 'embed_tokens',
    'encoder.positional_embedding': 'encoder.embed_positions.weight',
    'decoder.positional_embedding': 'decoder.embed_positions.weight',
    'ln_post': 'layer_norm',
}







def        A__					(						lowerCamelCase						)  ->	Any:
    UpperCamelCase_:							Dict	=						list(s_dict.keys()						)
    for key in keys:
        UpperCamelCase_:							List[str]	=						key
        for k, v in WHISPER_MAPPING.items():
            if k in key:
                UpperCamelCase_:							List[Any]	=						new_key.replace(lowercase_     ,    lowercase_						)

        print(F'''{key} -> {new_key}'''						)

        UpperCamelCase_:							Tuple	=						s_dict.pop(lowercase_						)
    return s_dict







def        A__					(						lowerCamelCase						)  ->	Optional[int]:
    UpperCamelCase_:							Any	=						emb.weight.shape
    UpperCamelCase_:							str	=						nn.Linear(lowercase_     ,    lowercase_     ,    bias=lowercase_						)
    UpperCamelCase_:							Union[str, Any]	=						emb.weight.data
    return lin_layer







def        A__					(						lowerCamelCase     ,    lowerCamelCase						)  ->	bytes:
    os.makedirs(lowercase_     ,    exist_ok=lowercase_						)
    UpperCamelCase_:							Tuple	=						os.path.basename(lowercase_						)

    UpperCamelCase_:							int	=						url.split("""/"""						)[-2]
    UpperCamelCase_:							Dict	=						os.path.join(lowercase_     ,    lowercase_						)

    if os.path.exists(lowercase_						) and not os.path.isfile(lowercase_						):
        raise RuntimeError(F'''{download_target} exists and is not a regular file'''						)

    if os.path.isfile(lowercase_						):
        UpperCamelCase_:							Optional[Any]	=						open(lowercase_     ,    """rb"""						).read()
        if hashlib.shaaaa(lowercase_						).hexdigest() == expected_shaaaa:
            return model_bytes
        else:
            warnings.warn(F'''{download_target} exists, but the SHA256 checksum does not match; re-downloading the file'''						)

    with urllib.request.urlopen(lowercase_						) as source, open(lowercase_     ,    """wb"""						) as output:
        with tqdm(
            total=int(source.info().get("""Content-Length"""						)						)     ,    ncols=80     ,    unit="""iB"""     ,    unit_scale=lowercase_     ,    unit_divisor=10_24						) as loop:
            while True:
                UpperCamelCase_:							Any	=						source.read(81_92						)
                if not buffer:
                    break

                output.write(lowercase_						)
                loop.update(len(lowercase_						)						)

    UpperCamelCase_:							Dict	=						open(lowercase_     ,    """rb"""						).read()
    if hashlib.shaaaa(lowercase_						).hexdigest() != expected_shaaaa:
        raise RuntimeError(
            """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model."""						)

    return model_bytes







def        A__					(						lowerCamelCase     ,    lowerCamelCase						)  ->	Optional[Any]:
    if ".pt" not in checkpoint_path:
        UpperCamelCase_:							Tuple	=						_download(_MODELS[checkpoint_path]						)
    else:
        UpperCamelCase_:							Optional[int]	=						torch.load(lowercase_     ,    map_location="""cpu"""						)
    UpperCamelCase_:							str	=						original_checkpoint["""dims"""]
    UpperCamelCase_:							List[Any]	=						original_checkpoint["""model_state_dict"""]
    UpperCamelCase_:							Optional[Any]	=						state_dict["""decoder.token_embedding.weight"""]
    remove_ignore_keys_(lowercase_						)
    rename_keys(lowercase_						)
    UpperCamelCase_:							List[str]	=						True
    UpperCamelCase_:							Optional[Any]	=						state_dict["""decoder.layers.0.fc1.weight"""].shape[0]

    UpperCamelCase_:							List[Any]	=						WhisperConfig(
        vocab_size=dimensions["""n_vocab"""]     ,    encoder_ffn_dim=lowercase_     ,    decoder_ffn_dim=lowercase_     ,    num_mel_bins=dimensions["""n_mels"""]     ,    d_model=dimensions["""n_audio_state"""]     ,    max_target_positions=dimensions["""n_text_ctx"""]     ,    encoder_layers=dimensions["""n_audio_layer"""]     ,    encoder_attention_heads=dimensions["""n_audio_head"""]     ,    decoder_layers=dimensions["""n_text_layer"""]     ,    decoder_attention_heads=dimensions["""n_text_state"""]     ,    max_source_positions=dimensions["""n_audio_ctx"""]     ,    )

    UpperCamelCase_:							Optional[Any]	=						WhisperForConditionalGeneration(lowercase_						)
    UpperCamelCase_:							List[Any]	=						model.model.load_state_dict(lowercase_     ,    strict=lowercase_						)
    if len(lowercase_						) > 0 and not set(lowercase_						) <= {
        "encoder.embed_positions.weights",
        "decoder.embed_positions.weights",
    }:
        raise ValueError(
            """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights`  are allowed to be missing,"""
            F''' but all the following weights are missing {missing}'''						)

    if tie_embeds:
        UpperCamelCase_:							Any	=						make_linear_from_emb(model.model.decoder.embed_tokens						)
    else:
        UpperCamelCase_:							str	=						proj_out_weights

    model.save_pretrained(lowercase_						)


if __name__ == "__main__":
       lowerCamelCase_						: Any         =  argparse.ArgumentParser()
       # # Required parameters
       parser.add_argument("""--checkpoint_path""", type=str, help="""Patht to the downloaded checkpoints""")
       parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
       lowerCamelCase_						: Tuple         =  parser.parse_args()

       convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)








from manim import *

class        _UpperCamelCase				(					_A  ):






			'''simple docstring'''

			def       lowerCAmelCase__	(       self :       int      ):
							UpperCamelCase_:							Dict	=						Rectangle(height=0.5						,	width=0.5      )
							UpperCamelCase_:							Dict	=						Rectangle(height=0.46						,	width=0.46      ).set_stroke(width=0      )

							UpperCamelCase_:							Tuple	=						[mem.copy() for i in range(6      )]
							UpperCamelCase_:							List[str]	=						[mem.copy() for i in range(6      )]
							UpperCamelCase_:							List[str]	=						VGroup(*snake_case_      ).arrange(snake_case_						,	buff=0      )
							UpperCamelCase_:							Tuple	=						VGroup(*snake_case_      ).arrange(snake_case_						,	buff=0      )
							UpperCamelCase_:							Union[str, Any]	=						VGroup(snake_case_						,	snake_case_      ).arrange(snake_case_						,	buff=0      )
							UpperCamelCase_:							Optional[Any]	=						Text("""CPU"""						,	font_size=24      )
							UpperCamelCase_:							int	=						Group(snake_case_						,	snake_case_      ).arrange(snake_case_						,	buff=0.5						,	aligned_edge=snake_case_      )
							cpu.move_to([-2.5, -0.5, 0]      )
							self.add(snake_case_      )

							UpperCamelCase_:							Optional[int]	=						[mem.copy() for i in range(1      )]
							UpperCamelCase_:							Dict	=						VGroup(*snake_case_      ).arrange(snake_case_						,	buff=0      )
							UpperCamelCase_:							Optional[int]	=						Text("""GPU"""						,	font_size=24      )
							UpperCamelCase_:							Optional[int]	=						Group(snake_case_						,	snake_case_      ).arrange(snake_case_						,	buff=0.5						,	aligned_edge=snake_case_      )
							gpu.align_to(snake_case_						,	snake_case_      )
							gpu.set_x(gpu.get_x() - 1      )

							self.add(snake_case_      )

							UpperCamelCase_:							Dict	=						[mem.copy() for i in range(6      )]
							UpperCamelCase_:							List[str]	=						VGroup(*snake_case_      ).arrange(snake_case_						,	buff=0      )

							UpperCamelCase_:							Any	=						Text("""Model"""						,	font_size=24      )
							UpperCamelCase_:							Optional[Any]	=						Group(snake_case_						,	snake_case_      ).arrange(snake_case_						,	buff=0.5						,	aligned_edge=snake_case_      )
							model.move_to([3, -1.0, 0]      )

							self.play(
							    Create(snake_case_						,	run_time=1      )						,	Create(snake_case_						,	run_time=1      )						,	Create(snake_case_						,	run_time=1      )						,	)

							UpperCamelCase_:							List[Any]	=						MarkupText(
							    f'''First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.'''						,	font_size=24						,	)

							UpperCamelCase_:							Optional[Any]	=						Square(side_length=2.2      )
							key.move_to([-5, 2, 0]      )

							UpperCamelCase_:							Union[str, Any]	=						MarkupText(
							    f'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model'''						,	font_size=18						,	)

							key_text.move_to([-5, 2.4, 0]      )

							step_a.move_to([2, 2, 0]      )
							self.play(Write(snake_case_						,	run_time=2.5      )						,	Write(snake_case_      )						,	Write(snake_case_      )      )

							self.add(snake_case_      )

							UpperCamelCase_:							Union[str, Any]	=						[]
							UpperCamelCase_:							Union[str, Any]	=						[]
							UpperCamelCase_:							Tuple	=						[]
							for i, rect in enumerate(snake_case_      ):
											UpperCamelCase_:							Tuple	=						Rectangle(height=0.46						,	width=0.46      ).set_stroke(width=0.0      ).set_fill(snake_case_						,	opacity=0.7      )
											cpu_target.move_to(snake_case_      )
											cpu_target.generate_target()
											UpperCamelCase_:							int	=						0.46 / 4
											UpperCamelCase_:							Optional[int]	=						0.46 / 3

											if i == 0:
															cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT      )						,	buff=0.02						,	direction=snake_case_      )
															cpu_target.target.set_x(cpu_target.target.get_x() + 0.1      )
											elif i == 3:
															cpu_target.target.next_to(cpu_targs[0].target						,	direction=snake_case_						,	buff=0.0      )
											else:
															cpu_target.target.next_to(cpu_targs[i - 1].target						,	direction=snake_case_						,	buff=0.0      )
											cpu_targs.append(snake_case_      )

											first_animations.append(rect.animate(run_time=0.5      ).set_stroke(snake_case_      )      )
											second_animations.append(MoveToTarget(snake_case_						,	run_time=1.5      )      )

							self.play(*snake_case_      )
							self.play(*snake_case_      )

							self.wait()






