{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## About\n\n@umongsain kindly shared [a new pretrained model](https://huggingface.co/Umong/wav2vec2-large-mms-1b-bengali). Please upvote @umongsain 's [topic](https://www.kaggle.com/competitions/bengaliai-speech/discussion/435300).\n\nIn this notebook I used two models from hugging faces:\n* `https://huggingface.co/Umong/wav2vec2-large-mms-1b-bengali` for Wav2vec2CTC Model only\n* `https://huggingface.co/arijitx/wav2vec2-xls-r-300m-bengali` for Language Model\n\nI didn't train these models using the competitaion data at all.\n\nThis notebook got 0.451, higher than [my previous baseline](https://www.kaggle.com/code/ttahara/bengali-sr-public-wav2vec2-0-w-lm-baseline) (0.471).\nSo fine-tuned @umongsain 's model may get higher score than fine-tuned `indicwav2vec_v1_bengali` model such as @nischaydnk 's [baseline](https://www.kaggle.com/code/nischaydnk/bengali-finetuning-baseline-wav2vec2-inference). ","metadata":{}},{"cell_type":"markdown","source":"## Import","metadata":{}},{"cell_type":"code","source":"!cp -r ../input/python-packages2 ./\n\n!tar xvfz ./python-packages2/jiwer.tgz\n!pip install ./jiwer/jiwer-2.3.0-py3-none-any.whl -f ./ --no-index\n!tar xvfz ./python-packages2/normalizer.tgz\n!pip install ./normalizer/bnunicodenormalizer-0.0.24.tar.gz -f ./ --no-index\n!tar xvfz ./python-packages2/pyctcdecode.tgz\n!pip install ./pyctcdecode/attrs-22.1.0-py2.py3-none-any.whl -f ./ --no-index --no-deps\n!pip install ./pyctcdecode/exceptiongroup-1.0.0rc9-py3-none-any.whl -f ./ --no-index --no-deps\n!pip install ./pyctcdecode/hypothesis-6.54.4-py3-none-any.whl -f ./ --no-index --no-deps\n!pip install ./pyctcdecode/numpy-1.21.6-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl -f ./ --no-index --no-deps\n!pip install ./pyctcdecode/pygtrie-2.5.0.tar.gz -f ./ --no-index --no-deps\n!pip install ./pyctcdecode/sortedcontainers-2.4.0-py2.py3-none-any.whl -f ./ --no-index --no-deps\n!pip install ./pyctcdecode/pyctcdecode-0.4.0-py2.py3-none-any.whl -f ./ --no-index --no-deps\n\n!tar xvfz ./python-packages2/pypikenlm.tgz\n!pip install ./pypikenlm/pypi-kenlm-0.1.20220713.tar.gz -f ./ --no-index --no-deps","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2023-09-03T10:26:21.226535Z","iopub.execute_input":"2023-09-03T10:26:21.226844Z","iopub.status.idle":"2023-09-03T10:27:40.312056Z","shell.execute_reply.started":"2023-09-03T10:26:21.226811Z","shell.execute_reply":"2023-09-03T10:27:40.310816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rm -r python-packages2 jiwer normalizer pyctcdecode pypikenlm","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:27:40.314352Z","iopub.execute_input":"2023-09-03T10:27:40.316308Z","iopub.status.idle":"2023-09-03T10:27:41.261568Z","shell.execute_reply.started":"2023-09-03T10:27:40.316275Z","shell.execute_reply":"2023-09-03T10:27:41.260304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import typing as tp\nfrom pathlib import Path\nfrom functools import partial\nfrom dataclasses import dataclass, field\n\nimport pandas as pd\nimport pyctcdecode\nimport numpy as np\nfrom tqdm.notebook import tqdm\n\nimport librosa\n\nimport pyctcdecode\nimport kenlm\nimport torch\nfrom transformers import Wav2Vec2ForCTC, Wav2Vec2Processor # , Wav2Vec2ProcessorWithLM\nfrom bnunicodenormalizer import Normalizer","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-09-03T10:27:41.263361Z","iopub.execute_input":"2023-09-03T10:27:41.263875Z","iopub.status.idle":"2023-09-03T10:27:52.860529Z","shell.execute_reply.started":"2023-09-03T10:27:41.263834Z","shell.execute_reply":"2023-09-03T10:27:52.859594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT = Path.cwd().parent\nINPUT = ROOT / \"input\"\nDATA = INPUT / \"bengaliai-speech\"\nTRAIN = DATA / \"train_mp3s\"\nTEST = DATA / \"test_mp3s\"\n\nSAMPLING_RATE = 16_000\nMODEL_PATH = INPUT / \"bengali-sr-download-public-trained-models-v2/wav2vec2-large-mms-1b-bengali/\"\nLM_PATH = INPUT / \"bengali-sr-download-public-trained-models-v2/wav2vec2-xls-r-300m-bengali/language_model/\"","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:27:52.863146Z","iopub.execute_input":"2023-09-03T10:27:52.863498Z","iopub.status.idle":"2023-09-03T10:27:52.869583Z","shell.execute_reply.started":"2023-09-03T10:27:52.863463Z","shell.execute_reply":"2023-09-03T10:27:52.868350Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### load model, processor, decoder","metadata":{}},{"cell_type":"code","source":"model = Wav2Vec2ForCTC.from_pretrained(MODEL_PATH)\nprocessor = Wav2Vec2Processor.from_pretrained(MODEL_PATH)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:27:52.870918Z","iopub.execute_input":"2023-09-03T10:27:52.871995Z","iopub.status.idle":"2023-09-03T10:28:48.888939Z","shell.execute_reply.started":"2023-09-03T10:27:52.871961Z","shell.execute_reply":"2023-09-03T10:28:48.887575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vocab_dict = processor.tokenizer.get_vocab()\nvocab_dict = vocab_dict[\"ben\"]\nvocab_dict['<s>'] = 64\nvocab_dict['</s>'] =  65\nsorted_vocab_dict = {k: v for k, v in sorted(vocab_dict.items(), key=lambda item: item[1])}\n\ndecoder = pyctcdecode.build_ctcdecoder(\n    list(sorted_vocab_dict.keys()),\n    str(LM_PATH / \"5gram.bin\"),\n)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:28:48.894714Z","iopub.execute_input":"2023-09-03T10:28:48.895613Z","iopub.status.idle":"2023-09-03T10:29:37.909262Z","shell.execute_reply.started":"2023-09-03T10:28:48.895562Z","shell.execute_reply":"2023-09-03T10:29:37.908143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# processor_with_lm = Wav2Vec2ProcessorWithLM(\n#     feature_extractor=processor.feature_extractor,\n#     tokenizer=processor.tokenizer,\n#     decoder=decoder\n# )","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:29:37.911081Z","iopub.execute_input":"2023-09-03T10:29:37.911509Z","iopub.status.idle":"2023-09-03T10:29:37.922922Z","shell.execute_reply.started":"2023-09-03T10:29:37.911474Z","shell.execute_reply":"2023-09-03T10:29:37.921838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## prepare dataloader","metadata":{}},{"cell_type":"code","source":"class BengaliSRTestDataset(torch.utils.data.Dataset):\n    \n    def __init__(\n        self,\n        audio_paths: list[str],\n        sampling_rate: int\n    ):\n        self.audio_paths = audio_paths\n        self.sampling_rate = sampling_rate\n        \n    def __len__(self,):\n        return len(self.audio_paths)\n    \n    def __getitem__(self, index: int):\n        audio_path = self.audio_paths[index]\n        sr = self.sampling_rate\n        w = librosa.load(audio_path, sr=sr, mono=False)[0]\n        \n        return w","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:29:37.924432Z","iopub.execute_input":"2023-09-03T10:29:37.924866Z","iopub.status.idle":"2023-09-03T10:29:37.934144Z","shell.execute_reply.started":"2023-09-03T10:29:37.924834Z","shell.execute_reply":"2023-09-03T10:29:37.933009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.read_csv(DATA / \"sample_submission.csv\", dtype={\"id\": str})\nprint(test.head())","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:29:37.935456Z","iopub.execute_input":"2023-09-03T10:29:37.935909Z","iopub.status.idle":"2023-09-03T10:29:37.971656Z","shell.execute_reply.started":"2023-09-03T10:29:37.935867Z","shell.execute_reply":"2023-09-03T10:29:37.970639Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_audio_paths = [str(TEST / f\"{aid}.mp3\") for aid in test[\"id\"].values]","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:29:37.975646Z","iopub.execute_input":"2023-09-03T10:29:37.975952Z","iopub.status.idle":"2023-09-03T10:29:37.981056Z","shell.execute_reply.started":"2023-09-03T10:29:37.975928Z","shell.execute_reply":"2023-09-03T10:29:37.979871Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_dataset = BengaliSRTestDataset(\n    test_audio_paths, SAMPLING_RATE\n)\n\ncollate_func = partial(\n    processor.feature_extractor,\n    # processor_with_lm.feature_extractor,\n    return_tensors=\"pt\", sampling_rate=SAMPLING_RATE,\n    padding=True,\n)\n\ntest_loader = torch.utils.data.DataLoader(\n    test_dataset, batch_size=8, shuffle=False,\n    num_workers=2, collate_fn=collate_func, drop_last=False,\n    pin_memory=True,\n)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:29:37.982992Z","iopub.execute_input":"2023-09-03T10:29:37.983446Z","iopub.status.idle":"2023-09-03T10:29:37.994510Z","shell.execute_reply.started":"2023-09-03T10:29:37.983369Z","shell.execute_reply":"2023-09-03T10:29:37.993456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Inference","metadata":{}},{"cell_type":"code","source":"if not torch.cuda.is_available():\n    device = torch.device(\"cpu\")\nelse:\n    device = torch.device(\"cuda\")\nprint(device)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:29:37.995890Z","iopub.execute_input":"2023-09-03T10:29:37.997075Z","iopub.status.idle":"2023-09-03T10:29:38.077129Z","shell.execute_reply.started":"2023-09-03T10:29:37.997043Z","shell.execute_reply":"2023-09-03T10:29:38.076144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = model.to(device)\nmodel = model.eval()\nmodel = model.half()","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:29:38.078622Z","iopub.execute_input":"2023-09-03T10:29:38.078968Z","iopub.status.idle":"2023-09-03T10:29:44.596636Z","shell.execute_reply.started":"2023-09-03T10:29:38.078942Z","shell.execute_reply":"2023-09-03T10:29:44.595597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_sentence_list = []\n\nwith torch.no_grad():\n    for batch in tqdm(test_loader):\n        x = batch[\"input_values\"]\n        x = x.to(device, non_blocking=True)\n        with torch.cuda.amp.autocast(True):\n            y = model(x).logits\n        y = y.detach().cpu().numpy()\n        \n        # for l in y:  \n        #     sentence = processor_with_lm.decode(l, beam_width=512).text\n        #     pred_sentence_list.append(sentence)\n        for l in y:\n            beam = decoder.decode_beams(l, beam_width=512)\n            s = beam[0][0]\n            pred_sentence_list.append(s)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:29:44.598278Z","iopub.execute_input":"2023-09-03T10:29:44.598665Z","iopub.status.idle":"2023-09-03T10:30:00.385871Z","shell.execute_reply.started":"2023-09-03T10:29:44.598630Z","shell.execute_reply":"2023-09-03T10:30:00.384787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Make Submission","metadata":{}},{"cell_type":"code","source":"bnorm = Normalizer()\n\ndef postprocess(sentence):\n    period_set = set([\".\", \"?\", \"!\", \"।\"])\n    _words = [bnorm(word)['normalized']  for word in sentence.split()]\n    sentence = \" \".join([word for word in _words if word is not None])\n    try:\n        if sentence[-1] not in period_set:\n            sentence+=\"।\"\n    except:\n        # print(sentence)\n        sentence = \"।\"\n    return sentence","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:30:00.387451Z","iopub.execute_input":"2023-09-03T10:30:00.387872Z","iopub.status.idle":"2023-09-03T10:30:00.395046Z","shell.execute_reply.started":"2023-09-03T10:30:00.387827Z","shell.execute_reply":"2023-09-03T10:30:00.394000Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pp_pred_sentence_list = [\n    postprocess(s) for s in tqdm(pred_sentence_list)]","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:30:00.396719Z","iopub.execute_input":"2023-09-03T10:30:00.397458Z","iopub.status.idle":"2023-09-03T10:30:00.444794Z","shell.execute_reply.started":"2023-09-03T10:30:00.397423Z","shell.execute_reply":"2023-09-03T10:30:00.443746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test[\"sentence\"] = pp_pred_sentence_list\n\ntest.to_csv(\"submission.csv\", index=False)\n\nprint(test.head())","metadata":{"execution":{"iopub.status.busy":"2023-09-03T10:30:00.446205Z","iopub.execute_input":"2023-09-03T10:30:00.446629Z","iopub.status.idle":"2023-09-03T10:30:00.462071Z","shell.execute_reply.started":"2023-09-03T10:30:00.446593Z","shell.execute_reply":"2023-09-03T10:30:00.461079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## EOF","metadata":{}}],"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}}