{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceType":"competition","sourceId":129276,"databundleVersionId":15506988}],"dockerImageVersionId":31260,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install faster-whisper","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T14:48:25.36511Z","iopub.execute_input":"2026-02-22T14:48:25.365935Z","iopub.status.idle":"2026-02-22T14:48:28.54094Z","shell.execute_reply.started":"2026-02-22T14:48:25.365892Z","shell.execute_reply":"2026-02-22T14:48:28.540084Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport time\nimport re\nimport csv\nimport queue\nimport threading\nimport torchaudio\nfrom pathlib import Path\nfrom tqdm import tqdm\nfrom concurrent.futures import ThreadPoolExecutor\nfrom faster_whisper import WhisperModel, BatchedInferencePipeline","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T14:49:06.475897Z","iopub.execute_input":"2026-02-22T14:49:06.476207Z","iopub.status.idle":"2026-02-22T14:49:09.141401Z","shell.execute_reply.started":"2026-02-22T14:49:06.476176Z","shell.execute_reply":"2026-02-22T14:49:09.140794Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"AUDIO_DIR = \"/kaggle/input/competitions/dl-sprint-4-0-bengali-long-form-speech-recognition/transcription/transcription/test/audio\"\nOUTPUT_CSV = \"/kaggle/working/submission_faster_whisper.csv\"\nMODEL_NAME = \"Risalat/whisper-bengali-ct2\"\n\nCOMPUTE_TYPE = \"float16\"\nBATCH_SIZE = 32\nCHUNK_LENGTH = 20\nBEAM_SIZE = 5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T14:49:21.748608Z","iopub.execute_input":"2026-02-22T14:49:21.749418Z","iopub.status.idle":"2026-02-22T14:49:21.753118Z","shell.execute_reply.started":"2026-02-22T14:49:21.74939Z","shell.execute_reply":"2026-02-22T14:49:21.752316Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nBN_PUNCT = r\"[।,!?;:“”\\\"'()\\[\\]{}—–…]\"\n\ndef clean_text(text: str) -> str:\n    \n    text = text.replace(\"প্রশংসা\", \"\")\n    \n    \n    text = re.sub(BN_PUNCT, \"\", text)\n    text = text.replace(\"?\", \"\").replace(\"\\n\", \" \")\n    \n    \n    text = re.sub(r\"\\s+\", \" \", text)\n    return text.strip()\n\n# ======================\n# MULTI-GPU SETUP\n# ======================\naudio_files = sorted(Path(AUDIO_DIR).glob(\"*.wav\"))\nprint(f\"Queueing {len(audio_files)} files for 2 GPUs...\")\n\n\nfile_queue = queue.Queue()\nfor f in audio_files:\n    file_queue.put(f)\n\n\npbar = tqdm(total=len(audio_files), desc=\"Transcribing (2x T4)\", unit=\"file\", dynamic_ncols=True)\npbar_lock = threading.Lock()\n\ndef worker(gpu_id):\n    \"\"\"Worker thread that processes files on a specific GPU.\"\"\"\n    # Kaggle T4x2 has 4 vCPUs total. We restrict each model to 2 CPU threads to prevent CPU thrashing.\n    model = WhisperModel(\n        MODEL_NAME,\n        device=\"cuda\",\n        device_index=gpu_id, \n        compute_type=COMPUTE_TYPE,\n        cpu_threads=2\n    )\n    pipeline = BatchedInferencePipeline(model=model)\n    \n    local_results = []\n    local_total_sec = 0.0\n    \n    while True:\n        try:\n            \n            audio_path = file_queue.get_nowait()\n        except queue.Empty:\n            break \n            \n        info = torchaudio.info(str(audio_path))\n        local_total_sec += info.num_frames / info.sample_rate\n\n        segments, _ = pipeline.transcribe(\n            str(audio_path),\n            language=\"bn\",\n            beam_size=BEAM_SIZE,\n            chunk_length=CHUNK_LENGTH,\n            batch_size=BATCH_SIZE,\n            condition_on_previous_text=False,\n            vad_filter=True,\n            vad_parameters=dict(min_silence_duration_ms=1000, speech_pad_ms=2000)\n        )\n\n        \n        raw_text = \" \".join(seg.text for seg in segments)\n        final_text = clean_text(raw_text)\n        \n        local_results.append((audio_path.stem, final_text))\n        \n        \n        with pbar_lock:\n            pbar.update(1)\n            \n    return local_results, local_total_sec\n\ninfer_start = time.time()\n\n# Launch exactly 2 threads, one for cuda:0 and one for cuda:1\nwith ThreadPoolExecutor(max_workers=2) as executor:\n    futures = [executor.submit(worker, i) for i in range(2)]\n\n# Collect results from both GPUs\nfinal_results = []\ntotal_audio_sec = 0.0\n\nfor f in futures:\n    res, sec = f.result()\n    final_results.extend(res)\n    total_audio_sec += sec\n\npbar.close()\ninfer_time = time.time() - infer_start\n\n# ======================\n# WRITE CSV & TIMING\n# ======================\n# Sort results by filename to ensure CSV order is consistent\nfinal_results.sort(key=lambda x: x[0])\n\nwith open(OUTPUT_CSV, \"w\", encoding=\"utf-8\", newline=\"\") as f:\n    writer = csv.writer(f)\n    writer.writerow([\"filename\", \"transcript\"])\n    writer.writerows(final_results)\n\nrtf = infer_time / total_audio_sec\n\nprint(\"\\n================ TIMING =======================\")\nprint(f\"Total audio duration : {total_audio_sec:.2f} sec\")\nprint(f\"Inference time       : {infer_time:.2f} sec\")\nprint(f\"Real-Time Factor     : {rtf:.4f} (lower is better)\")\nprint(f\"✅ CSV saved to: {OUTPUT_CSV}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T14:49:27.180701Z","iopub.execute_input":"2026-02-22T14:49:27.181283Z","iopub.status.idle":"2026-02-22T15:15:53.805282Z","shell.execute_reply.started":"2026-02-22T14:49:27.181252Z","shell.execute_reply":"2026-02-22T15:15:53.80463Z"}},"outputs":[],"execution_count":null}]}