{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"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":[{"sourceId":129271,"databundleVersionId":15506307,"sourceType":"competition"}],"dockerImageVersionId":31260,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport subprocess\nimport sys\n\n# 1. Define the target version\nTARGET_NUMPY = \"1.26.4\"\n\ntry:\n    import numpy as np\n    # Check if we need to downgrade (Kaggle 2024+ defaults to 2.x)\n    if np.__version__.startswith(\"2.\"):\n        print(f\"🔄 Current NumPy {np.__version__} is incompatible. Downgrading to {TARGET_NUMPY}...\")\n        \n        # Install the correct version\n        subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", f\"numpy=={TARGET_NUMPY}\", \"--quiet\"])\n        subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"pyannote.audio\", \"torchaudio\", \"--quiet\"])\n        \n        print(\"🚀 Force-restarting kernel to apply changes...\")\n        # This line kills the current process. Kaggle will automatically start a new one.\n        os._exit(00) \n    else:\n        print(f\"✅ NumPy {np.__version__} is already compatible. Proceeding...\")\n\nexcept ImportError:\n    # If numpy isn't even there (rare in Kaggle), install it\n    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", f\"numpy=={TARGET_NUMPY}\", \"--quiet\"])\n    os._exit(00)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-09T07:11:47.411673Z","iopub.execute_input":"2026-02-09T07:11:47.41228Z","execution_failed":"2026-02-09T07:12:19.067Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import json\nimport torch\nimport torchaudio\nimport pandas as pd\nfrom pathlib import Path\nfrom tqdm.auto import tqdm\nfrom pyannote.audio import Pipeline\n\n# Use your token from Step 2\nHF_TOKEN = \"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\"\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Load Pipeline\npipeline = Pipeline.from_pretrained(\"pyannote/speaker-diarization-3.1\", token=HF_TOKEN)\npipeline.to(DEVICE)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-09T07:58:54.596087Z","iopub.execute_input":"2026-02-09T07:58:54.596377Z","iopub.status.idle":"2026-02-09T07:58:55.262347Z","shell.execute_reply.started":"2026-02-09T07:58:54.59635Z","shell.execute_reply":"2026-02-09T07:58:55.261623Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import json\nimport pandas as pd # Ensure pandas is imported as pd\nimport torchaudio\nimport torch\nfrom pathlib import Path\nfrom tqdm.auto import tqdm\n\n# --- Helper Function for Time Formatting ---\ndef format_time(seconds):\n    \"\"\"Converts seconds into HH:MM:SS format.\"\"\"\n    td = int(round(seconds))\n    hh = td // 3600\n    mm = (td % 3600) // 60\n    ss = td % 60\n    return f\"{hh:02}:{mm:02}:{ss:02}\"\n\n# --- Configuration ---\nAUDIO_DIR = Path(\"/kaggle/input/dl-sprint-4-0-bengali-speaker-diarization-challenge/diarization/diarization/test/audio\")\nOUT_PATH = Path(\"submission.csv\")\nwav_paths = sorted(AUDIO_DIR.glob(\"*.wav\"))\n\npred_rows = []\n\nprint(f\"🚀 Processing {len(wav_paths)} files with live segment tracking...\\n\")\n\nwith torch.no_grad():\n    for wav_path in tqdm(wav_paths, desc=\"Processing Files\"):\n        try:\n            # 1. Load Audio\n            waveform, sample_rate = torchaudio.load(str(wav_path))\n            \n            # 2. Force Mono\n            if waveform.shape[0] > 1:\n                waveform = torch.mean(waveform, dim=0, keepdim=True)\n            \n            # 3. Ensure 16kHz\n            if sample_rate != 16000:\n                resampler = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)\n                waveform = resampler(waveform)\n                sample_rate = 16000\n\n            # 4. Run Diarization\n            result = pipeline({\"waveform\": waveform, \"sample_rate\": sample_rate})\n\n            # Handle the DiarizeOutput wrapper\n            if hasattr(result, \"speaker_diarization\"):\n                diarization = result.speaker_diarization\n            elif hasattr(result, \"annotation\"):\n                diarization = result.annotation\n            else:\n                diarization = result\n            \n            # 5. Extract Segments with Chronological Mapping (1, 2, 3...)\n            turns = []\n            speaker_map = {}  # Tracks {original_label: sequential_id}\n            next_id = 1\n            \n            print(f\"\\n🔍 Analyzing: {wav_path.name}\")\n            \n            for turn, _, speaker in diarization.itertracks(yield_label=True):\n                # Map speaker to a chronological integer ID\n                if speaker not in speaker_map:\n                    speaker_map[speaker] = next_id\n                    next_id += 1\n                \n                # YOUR REQUESTED PRINT STATEMENT\n                print(format_time(turn.start), format_time(turn.end), speaker_map[speaker])\n                \n                turns.append({\n                    \"start_time\": format_time(turn.start),\n                    \"end_time\": format_time(turn.end),\n                    \"speaker_id\": speaker_map[speaker]\n                })\n            \n            # 6. Final JSON formatting for this file\n            json_output = json.dumps(turns, ensure_ascii=False)\n            pred_rows.append({\n                \"filename\": wav_path.stem, \n                \"diarization\": json_output\n            })\n            print(f\"✅ Finished {wav_path.name} - Found {next_id - 1} speakers.\\n\" + \"-\"*30)\n            \n        except Exception as e:\n            print(f\"❌ Error processing {wav_path.name}: {e}\")\n            pred_rows.append({\"filename\": wav_path.stem, \"diarization\": \"[]\"})\n\n# --- Final Save ---\nimport pandas as pd\nsubmission_df = pd.DataFrame(pred_rows)\nsubmission_df.to_csv(OUT_PATH, index=False)\nprint(f\"\\n🏁 Finished! Results saved to {OUT_PATH}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-09T08:47:58.376077Z","iopub.execute_input":"2026-02-09T08:47:58.376553Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}