





"""simple docstring"""



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


a_ =			{
    """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 		__lowercase     (   snake_case_  :  List[str]						)   ->Optional[int]:



    '''simple docstring'''







    __A    :						Dict						 =     ['''layers''', '''blocks''']
    for k in ignore_keys:
        state_dict.pop(snake_case_				,snake_case_						)


a_ =			{
    """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 		__lowercase     (   snake_case_  :  List[Any]						)   ->List[Any]:



    '''simple docstring'''







    __A    :						List[str]						 =     list(s_dict.keys()						)
    for key in keys:
        __A    :						Any						 =     key
        for k, v in WHISPER_MAPPING.items():
            if k in key:
                __A    :						Tuple						 =     new_key.replace(snake_case_				,snake_case_						)

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

        __A    :						Any						 =     s_dict.pop(snake_case_						)
    return s_dict







def 		__lowercase     (   snake_case_  :  Optional[Any]						)   ->Tuple:



    '''simple docstring'''







    __A ,       __A    :						Optional[int]						 =     emb.weight.shape
    __A    :						List[str]						 =     nn.Linear(snake_case_				,snake_case_				,bias=snake_case_						)
    __A    :						int						 =     emb.weight.data
    return lin_layer







def 		__lowercase     (   snake_case_  :  str				,snake_case_  :  str						)   ->bytes:



    '''simple docstring'''







    os.makedirs(snake_case_				,exist_ok=snake_case_						)
    __A    :						Any						 =     os.path.basename(snake_case_						)

    __A    :						Any						 =     url.split('''/'''						)[-2]
    __A    :						Union[str, Any]						 =     os.path.join(snake_case_				,snake_case_						)

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

    if os.path.isfile(snake_case_						):
        __A    :						str						 =     open(snake_case_				,'''rb'''						).read()
        if hashlib.shaaaa(snake_case_						).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(snake_case_						) as source, open(snake_case_				,'''wb'''						) as output:
        with tqdm(
            total=int(source.info().get('''Content-Length'''						)						)				,ncols=80				,unit='''iB'''				,unit_scale=snake_case_				,unit_divisor=1024						) as loop:
            while True:
                __A    :						Tuple						 =     source.read(8192						)
                if not buffer:
                    break

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

    __A    :						Tuple						 =     open(snake_case_				,'''rb'''						).read()
    if hashlib.shaaaa(snake_case_						).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 		__lowercase     (   snake_case_  :  Dict				,snake_case_  :  Tuple						)   ->int:



    '''simple docstring'''







    if ".pt" not in checkpoint_path:
        __A    :						str						 =     _download(_MODELS[checkpoint_path]						)
    else:
        __A    :						List[str]						 =     torch.load(snake_case_				,map_location='''cpu'''						)
    __A    :						Tuple						 =     original_checkpoint['''dims''']
    __A    :						str						 =     original_checkpoint['''model_state_dict''']
    __A    :						List[str]						 =     state_dict['''decoder.token_embedding.weight''']
    remove_ignore_keys_(snake_case_						)
    rename_keys(snake_case_						)
    __A    :						Tuple						 =     True
    __A    :						List[str]						 =     state_dict['''decoder.layers.0.fc1.weight'''].shape[0]

    __A    :						Optional[Any]						 =     WhisperConfig(
        vocab_size=dimensions['''n_vocab''']				,encoder_ffn_dim=snake_case_				,decoder_ffn_dim=snake_case_				,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''']				,)

    __A    :						str						 =     WhisperForConditionalGeneration(snake_case_						)
    __A ,       __A    :						Optional[Any]						 =     model.model.load_state_dict(snake_case_				,strict=snake_case_						)
    if len(snake_case_						) > 0 and not set(snake_case_						) <= {
        "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:
        __A    :						Tuple						 =     make_linear_from_emb(model.model.decoder.embed_tokens						)
    else:
        __A    :						Any						 =     proj_out_weights

    model.save_pretrained(snake_case_						)


if __name__ == "__main__":
       a_ =			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.""")
       a_ =			parser.parse_args()

       convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)











"""simple docstring"""



import logging
import os
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import List, Optional

import faiss
import torch
from datasets import Features, Sequence, Value, load_dataset

from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser


a_ =			logging.getLogger(__name__)
torch.set_grad_enabled(False)
a_ =			"""cuda""" if torch.cuda.is_available() else """cpu"""







def 		__lowercase     (   snake_case_  :  str				,snake_case_  :  Tuple=100				,snake_case_  :  int=" "						)   ->List[str]:



    '''simple docstring'''







    __A    :						Dict						 =     text.split(snake_case_						)
    return [character.join(text[i : i + n]						).strip() for i in range(0				,len(snake_case_						)				,snake_case_						)]







def 		__lowercase     (   snake_case_  :  dict						)   ->dict:



    '''simple docstring'''







    __A ,       __A    :						Optional[int]						 =     [], []
    for title, text in zip(documents['''title''']				,documents['''text''']						):
        if text is not None:
            for passage in split_text(snake_case_						):
                titles.append(title if title is not None else ''''''						)
                texts.append(snake_case_						)
    return {"title": titles, "text": texts}







def 		__lowercase     (   snake_case_  :  dict				,snake_case_  :  DPRContextEncoder				,snake_case_  :  DPRContextEncoderTokenizerFast						)   ->dict:



    '''simple docstring'''







    __A    :						Tuple						 =     ctx_tokenizer(
        documents['''title''']				,documents['''text''']				,truncation=snake_case_				,padding='''longest'''				,return_tensors='''pt'''						)['''input_ids''']
    __A    :						int						 =     ctx_encoder(input_ids.to(device=snake_case_						)				,return_dict=snake_case_						).pooler_output
    return {"embeddings": embeddings.detach().cpu().numpy()}







def 		__lowercase     (   snake_case_  :  "RagExampleArguments"				,snake_case_  :  "ProcessingArguments"				,snake_case_  :  "IndexHnswArguments"				,)   ->Tuple:



    '''simple docstring'''







    logger.info('''Step 1 - Create the dataset'''						)
    ######################################

    # The dataset needed for RAG must have three columns:
    # - title (string): title of the document
    # - text (string): text of a passage of the document
    # - embeddings (array of dimension d): DPR representation of the passage
    # Let's say you have documents in tab-separated csv files with columns "title" and "text"
    assert os.path.isfile(rag_example_args.csv_path						), "Please provide a valid path to a csv file"

    # You can load a Dataset object this way
    __A    :						Optional[Any]						 =     load_dataset(
        '''csv'''				,data_files=[rag_example_args.csv_path]				,split='''train'''				,delimiter='''\t'''				,column_names=['''title''', '''text''']						)

    # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files

    # Then split the documents into passages of 100 words
    __A    :						str						 =     dataset.map(snake_case_				,batched=snake_case_				,num_proc=processing_args.num_proc						)

    # And compute the embeddings
    __A    :						Union[str, Any]						 =     DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name						).to(device=snake_case_						)
    __A    :						str						 =     DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name						)
    __A    :						Optional[int]						 =     Features(
        {'''text''': Value('''string'''						), '''title''': Value('''string'''						), '''embeddings''': Sequence(Value('''float32'''						)						)}						)  # optional, save as float32 instead of float64 to save space
    __A    :						List[Any]						 =     dataset.map(
        partial(snake_case_				,ctx_encoder=snake_case_				,ctx_tokenizer=snake_case_						)				,batched=snake_case_				,batch_size=processing_args.batch_size				,features=snake_case_				,)

    # And finally save your dataset
    __A    :						int						 =     os.path.join(rag_example_args.output_dir				,'''my_knowledge_dataset'''						)
    dataset.save_to_disk(snake_case_						)
    # from datasets import load_from_disk
    # dataset = load_from_disk(passages_path)  # to reload the dataset

    ######################################
    logger.info('''Step 2 - Index the dataset'''						)
    ######################################

    # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search
    __A    :						Tuple						 =     faiss.IndexHNSWFlat(index_hnsw_args.d				,index_hnsw_args.m				,faiss.METRIC_INNER_PRODUCT						)
    dataset.add_faiss_index('''embeddings'''				,custom_index=snake_case_						)

    # And save the index
    __A    :						List[str]						 =     os.path.join(rag_example_args.output_dir				,'''my_knowledge_dataset_hnsw_index.faiss'''						)
    dataset.get_index('''embeddings'''						).save(snake_case_						)
    # dataset.load_faiss_index("embeddings", index_path)  # to reload the index






@dataclass
class 		__snake_case					:





 """simple docstring"""


 _lowerCamelCase        =     field(
     default=str(Path(SCREAMING_SNAKE_CASE__     ).parent / """test_run""" / """dummy-kb""" / """my_knowledge_dataset.csv"""     )							,							metadata={"""help""": """Path to a tab-separated csv file with columns 'title' and 'text'"""}							,							)
 _lowerCamelCase        =     field(
     default=SCREAMING_SNAKE_CASE__							,							metadata={"""help""": """Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."""}							,							)
 _lowerCamelCase        =     field(
     default="""facebook/rag-sequence-nq"""							,							metadata={"""help""": """The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"""}							,							)
 _lowerCamelCase        =     field(
     default="""facebook/dpr-ctx_encoder-multiset-base"""							,							metadata={
         """help""": (
             """The DPR context encoder model to use. Either 'facebook/dpr-ctx_encoder-single-nq-base' or"""
             """ 'facebook/dpr-ctx_encoder-multiset-base'"""
         )
     }							,							)
 _lowerCamelCase        =     field(
     default=str(Path(SCREAMING_SNAKE_CASE__     ).parent / """test_run""" / """dummy-kb"""     )							,							metadata={"""help""": """Path to a directory where the dataset passages and the index will be saved"""}							,							)






@dataclass
class 		__snake_case					:





 """simple docstring"""


 _lowerCamelCase        =     field(
     default=SCREAMING_SNAKE_CASE__							,							metadata={
         """help""": """The number of processes to use to split the documents into passages. Default is single process."""
     }							,							)
 _lowerCamelCase        =     field(
     default=16							,							metadata={
         """help""": """The batch size to use when computing the passages embeddings using the DPR context encoder."""
     }							,							)






@dataclass
class 		__snake_case					:





 """simple docstring"""


 _lowerCamelCase        =     field(
     default=7_68							,							metadata={"""help""": """The dimension of the embeddings to pass to the HNSW Faiss index."""}							,							)
 _lowerCamelCase        =     field(
     default=1_28							,							metadata={
         """help""": (
             """The number of bi-directional links created for every new element during the HNSW index construction."""
         )
     }							,							)


if __name__ == "__main__":
       logging.basicConfig(level=logging.WARNING)
       logger.setLevel(logging.INFO)

       a_ =			HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments))
       a_ ,			a_ ,			a_ =			parser.parse_args_into_dataclasses()
       with TemporaryDirectory() as tmp_dir:
              a_ =			rag_example_args.output_dir or tmp_dir
              main(rag_example_args, processing_args, index_hnsw_args)




