{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport colorama as c\nimport os\n\nclass PathManager:\n\n    def __init__(self, **paths) -> \"PathManager\":\n        self.paths = paths\n        self.path_names = list(self.paths.keys())\n        self.path_values = list(self.paths.values())\n\n        \n        for path_name, path_value in self.paths.items():\n            if not os.path.exists(path_value):\n                print(f\"{c.Fore.RED}[WARNING] The path {path_value} named {path_name} doesn't exist in device.\")\n                print(f\"{c.Fore.RESET}\", end = \"\")\n                \n    def __getitem__(self, path_name_or_index: str | int) -> str:\n        \n        if isinstance(path_name_or_index, str):\n            \n            if path_name_or_index not in self.paths:\n                raise ValueError(f\"The path name: {path_name_or_index} doesn't exist.\")\n                \n            return self.paths[path_name_or_index]\n            \n        elif isinstance(path_name_or_index, int):\n            \n            if path_name_or_index >= len(self.path_values):\n                raise IndexError(f\"Index is out of range\")\n                \n            return self.path_values[path_name_or_index]\n            \n        else:\n            raise ValueError(f\"Unsupported type: {type(path_name_or_index)} for path_name_or_index\")\n            \n    def __getattr__(self, path_name: str) -> str:\n        \n        if path_name not in self.paths:\n            raise ValueError(f\"The path name: {path_name} doesn't exist.\")\n            \n        return self.paths[path_name]\n\n    def view(self, color = c.Fore.CYAN) -> None:\n        for path_name, path_value in self.paths.items():\n            print(f\"{color}>> {path_name}: {path_value}\")\n        print(f\"{c.Fore.RESET}\", end = \"\")\n\n    def __repr__(self) -> str:\n        \n        repr_values = []\n        for path_name, path_value in self.paths.items():\n            repr_values.append( f\"{c.Fore.CYAN}>> {path_name}: {path_value}\" )\n            \n        return \"\\n\".join(repr_values) + f\"{c.Fore.RESET}\"\n        \n    def insert(self, path_name: str, path: str) -> None:\n        if path_name in self.paths:\n            raise ValueError(f\"Path named: {path_name} already exists.\")\n            \n        if not os.path.exists(path = path):\n            print(f\"{c.Fore.RED}[WARNING] The path {path} named {path_name} doesn't exist in device.\")\n            print(f\"{c.Fore.RESET}\", end = \"\")\n            \n        self.paths[path_name] = path\n        \n    def remove(self, path_name: str) -> None:\n        \n        if path_name not in self.paths:\n            raise ValueError(f\"Path name: {path_name} doesn't exist.\")\n            \n        del self.paths[path_name]","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:13.536454Z","iopub.execute_input":"2026-08-18T18:03:13.537281Z","iopub.status.idle":"2026-08-18T18:03:13.811998Z","shell.execute_reply.started":"2026-08-18T18:03:13.537251Z","shell.execute_reply":"2026-08-18T18:03:13.811043Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"path_manager = PathManager(\n    root = \"/kaggle/input/competitions/audio-demixing-aicc-round-2\",\n    train_meta = \"/kaggle/input/competitions/audio-demixing-aicc-round-2/train.csv\",\n    test_meta = \"/kaggle/input/competitions/audio-demixing-aicc-round-2/test.csv\",\n    data = \"/kaggle/input/competitions/audio-demixing-aicc-round-2/data\",\n    sigs = \"/kaggle/input/competitions/audio-demixing-aicc-round-2/data/sigs\"\n)\npath_manager.view()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:13.813245Z","iopub.execute_input":"2026-08-18T18:03:13.813687Z","iopub.status.idle":"2026-08-18T18:03:13.826854Z","shell.execute_reply.started":"2026-08-18T18:03:13.813663Z","shell.execute_reply":"2026-08-18T18:03:13.825959Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torchaudio \nfrom torchaudio.transforms import MelSpectrogram, AmplitudeToDB, Resample\n\n\ndef load_audio(path: str, \n              target_sr: int = 16000, \n              win_length: int = 512, \n              n_fft: int = 512,\n              hop_length: int = 256,\n              n_mels: int = 80) -> torch.Tensor:\n    \n    waveform, init_sr = torchaudio.load(path)\n    \n    if waveform.shape[0] > 1:\n        waveform = torch.mean(waveform, dim = 0, keepdim = True)\n        \n    if init_sr != target_sr:\n        sampler = Resample(orig_freq = init_sr, new_freq = target_sr)\n        waveform = sampler(waveform)\n\n    window = torch.hann_window(win_length)\n    spec = torch.stft(\n        waveform,\n        n_fft = n_fft,\n        hop_length = hop_length,\n        window = window,\n        win_length = win_length,\n        return_complex = True,\n    )\n\n    return spec\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:13.827792Z","iopub.execute_input":"2026-08-18T18:03:13.828116Z","iopub.status.idle":"2026-08-18T18:03:17.884945Z","shell.execute_reply.started":"2026-08-18T18:03:13.828094Z","shell.execute_reply":"2026-08-18T18:03:17.884054Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nsample_audio = load_audio(path = \"/kaggle/input/competitions/audio-demixing-aicc-round-2/data/0.wav\")\nplt.imshow(sample_audio.abs().squeeze(0).numpy(), cmap = \"magma\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:17.886714Z","iopub.execute_input":"2026-08-18T18:03:17.887092Z","iopub.status.idle":"2026-08-18T18:03:21.730263Z","shell.execute_reply.started":"2026-08-18T18:03:17.887069Z","shell.execute_reply":"2026-08-18T18:03:21.729538Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Exploring the pattern relation that merged audios form \n","metadata":{}},{"cell_type":"code","source":"sample_id: str = \"110\"\n\nmerged_audio_path: str = os.path.join(path_manager.data, f\"{sample_id}.wav\")\nfirst_audio_path: str = os.path.join(path_manager.sigs, f\"{sample_id}_1.wav\")\nsecond_audio_path: str = os.path.join(path_manager.sigs, f\"{sample_id}_2.wav\")\n\nmerged_audio = load_audio(merged_audio_path).abs()\nfirst_audio = load_audio(first_audio_path).abs()\nsecond_audio = load_audio(second_audio_path).abs()\n\nfirst_binary_mask = (first_audio >= second_audio).to(torch.long)\nsecond_binary_mask = torch.abs(1 - first_binary_mask)\n\nexpected_first_audio = merged_audio * first_binary_mask\ncosine_similarity_1 = torch.cosine_similarity(x1 = first_audio.flatten(), x2 = expected_first_audio.flatten(), dim = 0)\n\n\nexpected_second_audio = merged_audio * second_binary_mask\ncosine_similarity_2 = torch.cosine_similarity(x1 = second_audio.flatten(), x2 = expected_second_audio.flatten(), dim = 0)\nprint(f\"The similarity of two audio spectrograms (actual first and expected first): {cosine_similarity_1}\")\nprint(f\"The similarity of two audio spectrograms (actual second and expected second): {cosine_similarity_2}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:21.731281Z","iopub.execute_input":"2026-08-18T18:03:21.731743Z","iopub.status.idle":"2026-08-18T18:03:21.847951Z","shell.execute_reply.started":"2026-08-18T18:03:21.731708Z","shell.execute_reply":"2026-08-18T18:03:21.847123Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"C, sr_c = torchaudio.load(merged_audio_path)\nA, sr_a = torchaudio.load(first_audio_path)\nB, sr_b = torchaudio.load(second_audio_path)\n\nprint(sr_c, sr_a, sr_b)\nprint(C.shape, A.shape, B.shape)\n\ndiff = C - A - B\n\nprint(\"MAE:\", diff.abs().mean())\nprint(\"MAX:\", diff.abs().max())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:21.849007Z","iopub.execute_input":"2026-08-18T18:03:21.849366Z","iopub.status.idle":"2026-08-18T18:03:21.899415Z","shell.execute_reply.started":"2026-08-18T18:03:21.849335Z","shell.execute_reply":"2026-08-18T18:03:21.898738Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nfig, ax = plt.subplots(2, 3, figsize = (12, 4))\nax[0, 0].imshow(first_audio.squeeze(0).numpy(), cmap = \"magma\")\nax[0, 1].imshow(second_audio.squeeze(0).numpy(), cmap = \"magma\")\n\nax[1, 0].imshow(first_binary_mask.squeeze(0).numpy(), cmap = \"grey\")\nax[1, 1].imshow(second_binary_mask.squeeze(0).numpy(), cmap = \"grey\")\n\nax[0, 2].imshow(merged_audio.squeeze(0).numpy(), cmap = \"magma\")\nax[1, 2].imshow((first_binary_mask + second_binary_mask).squeeze(0).numpy(), cmap = \"magma\")\n\nax[0, 0].set_title(\"First signal\")\nax[0, 1].set_title(\"Second signal\")\nax[0, 2].set_title(\"Merged signal\")\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:21.900432Z","iopub.execute_input":"2026-08-18T18:03:21.900719Z","iopub.status.idle":"2026-08-18T18:03:22.414496Z","shell.execute_reply.started":"2026-08-18T18:03:21.900698Z","shell.execute_reply":"2026-08-18T18:03:22.413715Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# EDA Conclusion:\n\nMy inital approach was to create a single binary mask using UNet showcasig 1: Belongs to signal A, 0: belongs to B , I derived this approach by assuming Spec_MergedSignals ~= Spec_SigA + Spec_SigB., However, after EDA , I have concluded that this assumption is wrong miserablely . Thus , we should use 2 masks for the same spectrogram of merged signal . Formula:\nSuppose:\nS_mix = Spectrogram of merged signals\nW_A = The floating point mask\nS_A = spectrogram of A\nHere , (*) is the Hadamard product:\nS_mix * W_A = S_A\n=> W_A = S_A / S_mix\n\nformula follows same of B","metadata":{}},{"cell_type":"code","source":"def generate_mask(mixed_spectrogram: torch.Tensor,\n                  first_spectrogram: torch.Tensor,\n                  second_spectrogram: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:\n    denom = mixed_spectrogram + 1e-6\n    first_mask = torch.clamp(first_spectrogram/denom  , 0.0, 1.0)\n    second_mask = torch.clamp(second_spectrogram/denom, 0.0, 1.0)\n    return torch.cat([first_mask, second_mask], dim = 0)\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:22.415525Z","iopub.execute_input":"2026-08-18T18:03:22.415743Z","iopub.status.idle":"2026-08-18T18:03:22.420573Z","shell.execute_reply.started":"2026-08-18T18:03:22.415722Z","shell.execute_reply":"2026-08-18T18:03:22.419917Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class META_DATA:\n    train = pd.read_csv(path_manager.train_meta)\n    test = pd.read_csv(path_manager.test_meta)\n\n\nMETA_DATA.train.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:22.421466Z","iopub.execute_input":"2026-08-18T18:03:22.421978Z","iopub.status.idle":"2026-08-18T18:03:22.470719Z","shell.execute_reply.started":"2026-08-18T18:03:22.421954Z","shell.execute_reply":"2026-08-18T18:03:22.470151Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def solve_path(path: str) -> str:\n    path = path[2:]\n    path = os.path.join(path_manager.root, path)\n    return path\n\n\nclass FILE_PATHS:\n    merged_signals = [solve_path(path) for path in META_DATA.train[\"file\"]]\n    first_signals = [solve_path(path) for path in META_DATA.train[\"sig_1\"]]\n    second_signals = [solve_path(path) for path in META_DATA.train[\"sig_2\"]]\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:22.472980Z","iopub.execute_input":"2026-08-18T18:03:22.473251Z","iopub.status.idle":"2026-08-18T18:03:22.480675Z","shell.execute_reply.started":"2026-08-18T18:03:22.473231Z","shell.execute_reply":"2026-08-18T18:03:22.480118Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"FILE_PATHS.first_signals[:3]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:22.481576Z","iopub.execute_input":"2026-08-18T18:03:22.481846Z","iopub.status.idle":"2026-08-18T18:03:22.492808Z","shell.execute_reply.started":"2026-08-18T18:03:22.481816Z","shell.execute_reply":"2026-08-18T18:03:22.492197Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import Dataset\nimport albumentations as A\n\nclass DataStream(Dataset):\n\n    def __init__(self, \n                 merged_audio_paths: list[str],\n                 first_signal_paths: list[str],\n                 second_signal_paths: list[str],\n                 indices: list[int]) -> \"DataStream\":\n        super().__init__()\n        self.merged_audio_paths = merged_audio_paths\n        self.first_signal_paths = first_signal_paths\n        self.second_signal_paths = second_signal_paths\n        self.indices = indices\n\n        \n    def __len__(self) -> int:\n        return len(self.indices)\n\n        \n    def __getitem__(self, index: int) -> tuple[dict, dict]:\n        index = int(self.indices[index])\n\n        merged_audio_path = self.merged_audio_paths[index]\n        first_audio_path = self.first_signal_paths[index]\n        second_audio_path = self.second_signal_paths[index]\n\n        merged_spectrogram = load_audio(path = merged_audio_path).abs()\n        first_spectrogram = load_audio(path = first_audio_path).abs()\n        second_spectrogram = load_audio(path = second_audio_path).abs()\n\n        mask = generate_mask(merged_spectrogram, first_spectrogram, second_spectrogram)\n        merged_spectrogram = 20 * torch.log10(merged_spectrogram + 1e-8)\n        \n        _, current_h, current_w = merged_spectrogram.shape\n\n        pad_w = 384 - current_w\n        pad_h = 272 - current_h\n\n        pad_tuple = (0, max(0, pad_w), 0, max(0, pad_h))\n\n        padded_spectrogram = torch.nn.functional.pad(merged_spectrogram, pad_tuple, value = 0.0)\n        padded_mask = torch.nn.functional.pad(mask, pad_tuple, value = 0.0)\n\n        return padded_spectrogram, padded_mask","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:22.493605Z","iopub.execute_input":"2026-08-18T18:03:22.493871Z","iopub.status.idle":"2026-08-18T18:03:24.437463Z","shell.execute_reply.started":"2026-08-18T18:03:22.493840Z","shell.execute_reply":"2026-08-18T18:03:24.436651Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\n\nall_indices: list[int] = [idx for idx in range(META_DATA.train.shape[0])]\ntrain_indices, val_indices = train_test_split(\n    all_indices,\n    train_size = 0.8,\n    test_size = 0.2,\n    shuffle = True,\n    random_state = 13\n)\n\nclass DATA_SOURCE:\n    TrainStream = DataStream(\n        merged_audio_paths = FILE_PATHS.merged_signals,\n        first_signal_paths = FILE_PATHS.first_signals,\n        second_signal_paths = FILE_PATHS.second_signals,\n        indices = train_indices\n    )\n    ValStream = DataStream(\n        merged_audio_paths = FILE_PATHS.merged_signals,\n        first_signal_paths = FILE_PATHS.first_signals,\n        second_signal_paths = FILE_PATHS.second_signals,\n        indices = val_indices\n    )\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:24.438576Z","iopub.execute_input":"2026-08-18T18:03:24.439351Z","iopub.status.idle":"2026-08-18T18:03:24.961329Z","shell.execute_reply.started":"2026-08-18T18:03:24.439279Z","shell.execute_reply":"2026-08-18T18:03:24.960431Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fig3, ax3 = plt.subplots(1, 3, figsize = (10, 4))\nspec, mask = DATA_SOURCE.TrainStream[2]\nax3[0].imshow(spec.squeeze(0), cmap = \"magma\")\nax3[1].imshow(mask[0], cmap = \"grey\")\nax3[2].imshow(mask[1], cmap = \"grey\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:24.962226Z","iopub.execute_input":"2026-08-18T18:03:24.962718Z","iopub.status.idle":"2026-08-18T18:03:25.332903Z","shell.execute_reply.started":"2026-08-18T18:03:24.962694Z","shell.execute_reply":"2026-08-18T18:03:25.332228Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"path_manager.insert(\"model_weights\", \"/kaggle/input/models/mdabdulalhasib/checkpoint-for-a-contest/pytorch/default/1/best_model (10).pth\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:25.333790Z","iopub.execute_input":"2026-08-18T18:03:25.334087Z","iopub.status.idle":"2026-08-18T18:03:25.338818Z","shell.execute_reply.started":"2026-08-18T18:03:25.334065Z","shell.execute_reply":"2026-08-18T18:03:25.337923Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"checkpoint = torch.load(path_manager.model_weights)\nmodel_weights = checkpoint[\"model_state_dict\"]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:25.339803Z","iopub.execute_input":"2026-08-18T18:03:25.340401Z","iopub.status.idle":"2026-08-18T18:03:26.774988Z","shell.execute_reply.started":"2026-08-18T18:03:25.340369Z","shell.execute_reply":"2026-08-18T18:03:26.774223Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import imseg\nfrom torch import nn\nimport torch\n\nclass BCELossForSegmentation(nn.Module):\n\n    def __init__(self):\n        super().__init__()\n        self.bce = nn.BCEWithLogitsLoss()\n        self.flatten = nn.Flatten()\n        \n    def forward(self, preds: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:\n        preds = self.flatten(preds)\n        targets = self.flatten(targets)\n        \n        return self.bce(preds, targets)\n\ncriterion = BCELossForSegmentation()\nunet_model = imseg.AttentionUNet(\n    in_channels = 1,\n    out_channels = 2,\n)\nmodel_manager = imseg.ImageSegmentationModelManager(model = unet_model,\n                                                    module_registry = {\n                                                        \"encoder\": unet_model.encoders + [unet_model.bottleneck],\n                                                        \"decoder\": unet_model.decoders ,\n                                                        \"fc\": [unet_model.final_up]\n                                                    })\nmodel_manager.model.load_state_dict(model_weights)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:26.775876Z","iopub.execute_input":"2026-08-18T18:03:26.776202Z","iopub.status.idle":"2026-08-18T18:03:28.331265Z","shell.execute_reply.started":"2026-08-18T18:03:26.776154Z","shell.execute_reply":"2026-08-18T18:03:28.330529Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_manager.total_params()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:28.332454Z","iopub.execute_input":"2026-08-18T18:03:28.332941Z","iopub.status.idle":"2026-08-18T18:03:28.339066Z","shell.execute_reply.started":"2026-08-18T18:03:28.332917Z","shell.execute_reply":"2026-08-18T18:03:28.338362Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def TRAIN():\n\n    \n    train_dl_configs = {\"batch_size\": 4, \"num_workers\": 4, \"pin_memory\": True}\n    model_manager.train(\n        \"train:0\",\n        train_source = DATA_SOURCE.TrainStream,\n        val_source = DATA_SOURCE.ValStream,\n        criterion = criterion,\n        n_epochs = 20,\n        lr = {\n            \"encoder\": 1e-3,\n            \"decoder\": 1e-3,\n            \"fc\": 1e-3\n        },\n        freeze_encoder = False,\n        auto_compile = False,\n        train_dataloader_configs = train_dl_configs\n    )\n\nHAS_TRAINED: bool = True\nif not HAS_TRAINED:\n    TRAIN()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:28.340002Z","iopub.execute_input":"2026-08-18T18:03:28.340195Z","iopub.status.idle":"2026-08-18T18:03:28.352759Z","shell.execute_reply.started":"2026-08-18T18:03:28.340175Z","shell.execute_reply":"2026-08-18T18:03:28.352115Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class DataStreamForTest(Dataset):\n\n    def __init__(self, ids: list[str], paths: list[str]) -> \"DataStreamForTest\":\n        super().__init__()\n        self.paths = paths\n        self.ids = ids\n\n    \n    def __len__(self) -> int:\n        return len(self.paths)\n        \n    def __getitem__(self, index: int) -> torch.Tensor:\n        \n        path = self.paths[index]\n        sample_id = self.ids[index]\n        spec = load_audio(path)\n        spec = 20 * torch.log10(spec + 1e-8)\n        \n        _, current_h, current_w = spec.shape\n\n        pad_w = 384 - current_w\n        pad_h = 272 - current_h\n\n        pad_tuple = (0, max(0, pad_w), 0, max(0, pad_h))\n\n        padded_spectrogram = torch.nn.functional.pad(spec, pad_tuple, value = 0.0)\n        return sample_id, padded_spectrogram.abs()\n\n\nTestStream = DataStreamForTest(ids = META_DATA.test[\"ID\"],\n                               paths = [solve_path(path = path) for path in META_DATA.test[\"file\"]])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:28.353532Z","iopub.execute_input":"2026-08-18T18:03:28.353868Z","iopub.status.idle":"2026-08-18T18:03:28.366056Z","shell.execute_reply.started":"2026-08-18T18:03:28.353831Z","shell.execute_reply":"2026-08-18T18:03:28.365417Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"TestStream[0][1].shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:28.366828Z","iopub.execute_input":"2026-08-18T18:03:28.367173Z","iopub.status.idle":"2026-08-18T18:03:28.414368Z","shell.execute_reply.started":"2026-08-18T18:03:28.367151Z","shell.execute_reply":"2026-08-18T18:03:28.413759Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"segmented_images = model_manager.segment_images(\n    \"test:0\",\n    data_src = TestStream,\n    device = \"cuda\"\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:03:28.415388Z","iopub.execute_input":"2026-08-18T18:03:28.415929Z","iopub.status.idle":"2026-08-18T18:03:30.037010Z","shell.execute_reply.started":"2026-08-18T18:03:28.415892Z","shell.execute_reply":"2026-08-18T18:03:30.036113Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tqdm import tqdm\n\npredicted_signals = []\nfor index, row in tqdm(META_DATA.test.iterrows()):\n    audio_path = solve_path(row[\"file\"])\n\n    spectrogram = load_audio(audio_path)\n\n    masks = segmented_images[row[\"ID\"]].mask_proba().cpu()\n    spectrogram = spectrogram[:, : 257, : 313]\n    masks = masks[:, : 257, : 313]\n    \n    pred_specs = spectrogram * masks\n\n    pred_sigs = torch.istft(\n        pred_specs,\n        n_fft = 512,\n        win_length = 512,\n        hop_length = 256,\n        window = torch.hann_window(window_length = 512)\n    )\n    resampler = Resample(orig_freq = 16000, new_freq = 44100)\n    pred_sigs = resampler(pred_sigs)\n\n    \n    predicted_signals.append({\n        \"ID\": row[\"ID\"],\n        \"sig_1\": pred_sigs[0, : 16000].numpy(),\n        \"sig_2\": pred_sigs[1, : 16000].numpy(),\n    })\n   \n   ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:30:30.789632Z","iopub.execute_input":"2026-08-18T18:30:30.790394Z","iopub.status.idle":"2026-08-18T18:30:31.795403Z","shell.execute_reply.started":"2026-08-18T18:30:30.790350Z","shell.execute_reply":"2026-08-18T18:30:31.794591Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(predicted_signals[0][\"sig_1\"].shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:30:35.285044Z","iopub.execute_input":"2026-08-18T18:30:35.285701Z","iopub.status.idle":"2026-08-18T18:30:35.289695Z","shell.execute_reply.started":"2026-08-18T18:30:35.285669Z","shell.execute_reply":"2026-08-18T18:30:35.288931Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import base64\n\ndef encode_array_base85(arr: np.ndarray) -> str:\n    arr = np.ascontiguousarray(arr.astype(np.float32).ravel())\n    return base64.b85encode(arr.tobytes()).decode(\"ascii\")\n\n\npredictions = {\n    \"ID\": [],\n    \"sig_1\": [],\n    \"sig_2\": []\n}\nfor sample in tqdm(predicted_signals):\n    predictions[\"ID\"].append(sample[\"ID\"])\n    predictions[\"sig_1\"].append(encode_array_base85(sample[\"sig_1\"]))\n    predictions[\"sig_2\"].append(encode_array_base85(sample[\"sig_2\"]))\n\n\npredictions = pd.DataFrame(predictions)\npredictions.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:30:37.110475Z","iopub.execute_input":"2026-08-18T18:30:37.110850Z","iopub.status.idle":"2026-08-18T18:30:37.689713Z","shell.execute_reply.started":"2026-08-18T18:30:37.110819Z","shell.execute_reply":"2026-08-18T18:30:37.689076Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions.to_csv(\"result.csv\", index = False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-18T18:30:40.701656Z","iopub.execute_input":"2026-08-18T18:30:40.701928Z","iopub.status.idle":"2026-08-18T18:30:40.920583Z","shell.execute_reply.started":"2026-08-18T18:30:40.701903Z","shell.execute_reply":"2026-08-18T18:30:40.919638Z"}},"outputs":[],"execution_count":null}]}