{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":70203,"databundleVersionId":8068726,"sourceType":"competition"}],"dockerImageVersionId":30684,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport librosa as lb\nimport librosa.display as lbd\nimport soundfile as sf\nfrom  soundfile import SoundFile\nimport pandas as pd\nfrom  IPython.display import Audio\nfrom pathlib import Path\n\nfrom matplotlib import pyplot as plt\n\nfrom tqdm.notebook import tqdm\nimport joblib, json, re\n\nfrom  sklearn.model_selection  import StratifiedKFold\ntqdm.pandas()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-09T13:32:56.978209Z","iopub.execute_input":"2024-04-09T13:32:56.978789Z","iopub.status.idle":"2024-04-09T13:33:00.060491Z","shell.execute_reply.started":"2024-04-09T13:32:56.978734Z","shell.execute_reply":"2024-04-09T13:33:00.059116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/birdclef-2024/train_metadata.csv')\ndf['secondary_labels'] = df['secondary_labels'].apply(lambda x: re.findall(r\"'(\\w+)'\", x))\ndf['len_sec_labels'] = df['secondary_labels'].map(len)","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:33:00.062559Z","iopub.execute_input":"2024-04-09T13:33:00.063218Z","iopub.status.idle":"2024-04-09T13:33:00.322986Z","shell.execute_reply.started":"2024-04-09T13:33:00.063184Z","shell.execute_reply":"2024-04-09T13:33:00.321698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[df.len_sec_labels>0].sample(3)","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:33:00.324736Z","iopub.execute_input":"2024-04-09T13:33:00.325159Z","iopub.status.idle":"2024-04-09T13:33:00.366871Z","shell.execute_reply.started":"2024-04-09T13:33:00.325118Z","shell.execute_reply":"2024-04-09T13:33:00.365719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.primary_label.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:33:00.369662Z","iopub.execute_input":"2024-04-09T13:33:00.370027Z","iopub.status.idle":"2024-04-09T13:33:00.388695Z","shell.execute_reply.started":"2024-04-09T13:33:00.369995Z","shell.execute_reply":"2024-04-09T13:33:00.387657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nimport pandas as pd\n\ndef birds_stratified_split(df, target_col, test_size=0.2):\n    class_counts = df[target_col].value_counts()\n    low_count_classes = class_counts[class_counts < 2].index.tolist() ### Birds with single counts\n\n    df['train'] = df[target_col].isin(low_count_classes)\n\n    train_df, val_df = train_test_split(df[~df['train']], test_size=test_size, stratify=df[~df['train']][target_col], random_state=42)\n\n    train_df = pd.concat([train_df, df[df['train']]], axis=0).reset_index(drop=True)\n\n    # Remove the 'valid' column\n    train_df.drop('train', axis=1, inplace=True)\n    val_df.drop('train', axis=1, inplace=True)\n\n    return train_df, val_df","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:33:00.389721Z","iopub.execute_input":"2024-04-09T13:33:00.390128Z","iopub.status.idle":"2024-04-09T13:33:00.401186Z","shell.execute_reply.started":"2024-04-09T13:33:00.390097Z","shell.execute_reply":"2024-04-09T13:33:00.399867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df, valid_df = birds_stratified_split(df, 'primary_label', 0.2)","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:33:08.100993Z","iopub.execute_input":"2024-04-09T13:33:08.101474Z","iopub.status.idle":"2024-04-09T13:33:08.210621Z","shell.execute_reply.started":"2024-04-09T13:33:08.101439Z","shell.execute_reply":"2024-04-09T13:33:08.209590Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.primary_label.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:33:14.239594Z","iopub.execute_input":"2024-04-09T13:33:14.240009Z","iopub.status.idle":"2024-04-09T13:33:14.253850Z","shell.execute_reply.started":"2024-04-09T13:33:14.239980Z","shell.execute_reply":"2024-04-09T13:33:14.252487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.primary_label.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:33:20.494485Z","iopub.execute_input":"2024-04-09T13:33:20.494910Z","iopub.status.idle":"2024-04-09T13:33:20.508771Z","shell.execute_reply.started":"2024-04-09T13:33:20.494881Z","shell.execute_reply":"2024-04-09T13:33:20.507629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df.primary_label.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:33:28.964967Z","iopub.execute_input":"2024-04-09T13:33:28.965422Z","iopub.status.idle":"2024-04-09T13:33:28.975893Z","shell.execute_reply.started":"2024-04-09T13:33:28.965387Z","shell.execute_reply":"2024-04-09T13:33:28.974758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Config:\n    sampling_rate = 32000\n    duration = 5 \n    fmin = 0\n    fmax = None\n    audios_path = Path(\"/kaggle/input/birdclef-2024/train_audio\")\n    out_dir_train = Path(\"specs/train\") \n    \n    out_dir_valid = Path(\"specs/valid\") ","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:33:48.820621Z","iopub.execute_input":"2024-04-09T13:33:48.821026Z","iopub.status.idle":"2024-04-09T13:33:48.826871Z","shell.execute_reply.started":"2024-04-09T13:33:48.820998Z","shell.execute_reply":"2024-04-09T13:33:48.825740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Config.out_dir_train.mkdir(exist_ok=True, parents=True)\nConfig.out_dir_valid.mkdir(exist_ok=True, parents=True)","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:33:55.752577Z","iopub.execute_input":"2024-04-09T13:33:55.753020Z","iopub.status.idle":"2024-04-09T13:33:55.758141Z","shell.execute_reply.started":"2024-04-09T13:33:55.752984Z","shell.execute_reply":"2024-04-09T13:33:55.757273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_audio_info(filepath):\n    \"\"\"Get some properties from  an audio file\"\"\"\n    with SoundFile(filepath) as f:\n        sr = f.samplerate\n        frames = f.frames\n        duration = float(frames)/sr\n    return {\"frames\": frames, \"sr\": sr, \"duration\": duration}","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:34:01.884099Z","iopub.execute_input":"2024-04-09T13:34:01.884530Z","iopub.status.idle":"2024-04-09T13:34:01.890858Z","shell.execute_reply.started":"2024-04-09T13:34:01.884501Z","shell.execute_reply":"2024-04-09T13:34:01.889647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def add_path_df(df):\n    \n    df[\"path\"] = [str(Config.audios_path/filename) for filename in df.filename]\n    df = df.reset_index(drop=True)\n    pool = joblib.Parallel(2)\n    mapper = joblib.delayed(get_audio_info)\n    tasks = [mapper(filepath) for filepath in df.path]\n    df2 =  pd.DataFrame(pool(tqdm(tasks))).reset_index(drop=True)\n    df = pd.concat([df,df2], axis=1).reset_index(drop=True)\n\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:34:07.950058Z","iopub.execute_input":"2024-04-09T13:34:07.950478Z","iopub.status.idle":"2024-04-09T13:34:07.958068Z","shell.execute_reply.started":"2024-04-09T13:34:07.950447Z","shell.execute_reply":"2024-04-09T13:34:07.956992Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tqdm.pandas()","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:34:13.249857Z","iopub.execute_input":"2024-04-09T13:34:13.250283Z","iopub.status.idle":"2024-04-09T13:34:13.257931Z","shell.execute_reply.started":"2024-04-09T13:34:13.250253Z","shell.execute_reply":"2024-04-09T13:34:13.256524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = add_path_df(train_df)","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:34:18.184616Z","iopub.execute_input":"2024-04-09T13:34:18.185027Z","iopub.status.idle":"2024-04-09T13:36:00.710164Z","shell.execute_reply.started":"2024-04-09T13:34:18.185000Z","shell.execute_reply":"2024-04-09T13:36:00.708999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df = add_path_df(valid_df)","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:36:00.712762Z","iopub.execute_input":"2024-04-09T13:36:00.713512Z","iopub.status.idle":"2024-04-09T13:36:27.328847Z","shell.execute_reply.started":"2024-04-09T13:36:00.713464Z","shell.execute_reply":"2024-04-09T13:36:27.327738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.to_csv('train.csv', index=False)\nvalid_df.to_csv('valid.csv', index=False)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df[\"duration\"].describe()","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:36:27.330004Z","iopub.execute_input":"2024-04-09T13:36:27.330902Z","iopub.status.idle":"2024-04-09T13:36:27.348029Z","shell.execute_reply.started":"2024-04-09T13:36:27.330869Z","shell.execute_reply":"2024-04-09T13:36:27.346894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def compute_melspec(y, sr, n_mels, fmin, fmax):\n    \"\"\"\n    Computes a mel-spectrogram and puts it at decibel scale\n    Arguments:\n        y {np array} -- signal\n        params {AudioParams} -- Parameters to use for the spectrogram. Expected to have the attributes sr, n_mels, f_min, f_max\n    Returns:\n        np array -- Mel-spectrogram\n    \"\"\"\n    melspec = lb.feature.melspectrogram(\n        y=y, sr=sr, n_mels=n_mels, fmin=fmin, fmax=fmax,\n    )\n\n    melspec = lb.power_to_db(melspec).astype(np.float32)\n    return melspec","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:36:27.351111Z","iopub.execute_input":"2024-04-09T13:36:27.351867Z","iopub.status.idle":"2024-04-09T13:36:27.359058Z","shell.execute_reply.started":"2024-04-09T13:36:27.351825Z","shell.execute_reply":"2024-04-09T13:36:27.357765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def mono_to_color(X, eps=1e-6, mean=None, std=None):\n    mean = mean or X.mean()\n    std = std or X.std()\n    X = (X - mean) / (std + eps)\n    \n    _min, _max = X.min(), X.max()\n\n    if (_max - _min) > eps:\n        V = np.clip(X, _min, _max)\n        V = 255 * (V - _min) / (_max - _min)\n        V = V.astype(np.uint8)\n    else:\n        V = np.zeros_like(X, dtype=np.uint8)\n\n    return V\n\ndef crop_or_pad(y, length, is_train=True, start=None):\n    if len(y) < length:\n        y = np.concatenate([y, np.zeros(length - len(y))])\n        \n        n_repeats = length // len(y)\n        epsilon = length % len(y)\n        \n        y = np.concatenate([y]*n_repeats + [y[:epsilon]])\n        \n    elif len(y) > length:\n        if not is_train:\n            start = start or 0\n        else:\n            start = start or np.random.randint(len(y) - length)\n\n        y = y[start:start + length]\n\n    return y","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:36:27.360855Z","iopub.execute_input":"2024-04-09T13:36:27.361246Z","iopub.status.idle":"2024-04-09T13:36:27.375165Z","shell.execute_reply.started":"2024-04-09T13:36:27.361196Z","shell.execute_reply":"2024-04-09T13:36:27.373944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class AudioToImage:\n    def __init__(self, sr=Config.sampling_rate, n_mels=128, fmin=Config.fmin, fmax=Config.fmax, duration=Config.duration, step=None, res_type=\"kaiser_fast\", resample=True, train = True):\n\n        self.sr = sr\n        self.n_mels = n_mels\n        self.fmin = fmin\n        self.fmax = fmax or self.sr//2\n\n        self.duration = duration\n        self.audio_length = self.duration*self.sr\n        self.step = step or self.audio_length\n        \n        self.res_type = res_type\n        self.resample = resample\n\n        self.train = train\n    def audio_to_image(self, audio):\n        melspec = compute_melspec(audio, self.sr, self.n_mels, self.fmin, self.fmax ) \n        image = mono_to_color(melspec)\n#         compute_melspec(y, sr, n_mels, fmin, fmax)\n        return image\n\n    def __call__(self, row, save=True):\n\n      audio, orig_sr = sf.read(row.path, dtype=\"float32\")\n\n      if self.resample and orig_sr != self.sr:\n        audio = lb.resample(audio, orig_sr, self.sr, res_type=self.res_type)\n        \n      audios = [audio[i:i+self.audio_length] for i in range(0, max(1, len(audio) - self.audio_length + 1), self.step)]\n      audios[-1] = crop_or_pad(audios[-1] , length=self.audio_length)\n      images = [self.audio_to_image(audio) for audio in audios]\n      images = np.stack(images)\n        \n      if save:\n        if self.train:\n            path = Config.out_dir_train/f\"{row.filename}.npy\"\n        else:\n            path = Config.out_dir_valid/f\"{row.filename}.npy\"\n            \n        path.parent.mkdir(exist_ok=True, parents=True)\n        np.save(str(path), images)\n      else:\n        return  row.filename, images","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:36:27.376826Z","iopub.execute_input":"2024-04-09T13:36:27.377326Z","iopub.status.idle":"2024-04-09T13:36:27.398080Z","shell.execute_reply.started":"2024-04-09T13:36:27.377291Z","shell.execute_reply":"2024-04-09T13:36:27.396825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tqdm.pandas()","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:36:27.400409Z","iopub.execute_input":"2024-04-09T13:36:27.401577Z","iopub.status.idle":"2024-04-09T13:36:27.416058Z","shell.execute_reply.started":"2024-04-09T13:36:27.401487Z","shell.execute_reply":"2024-04-09T13:36:27.414757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_audios_as_images(df, train = True):\n    pool = joblib.Parallel(2)\n    \n    converter = AudioToImage(step=int(Config.duration*0.666*Config.sampling_rate),train=train)\n    mapper = joblib.delayed(converter)\n    tasks = [mapper(row) for row in df.itertuples(False)]\n    pool(tqdm(tasks))","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:36:27.420171Z","iopub.execute_input":"2024-04-09T13:36:27.420560Z","iopub.status.idle":"2024-04-09T13:36:27.427602Z","shell.execute_reply.started":"2024-04-09T13:36:27.420530Z","shell.execute_reply":"2024-04-09T13:36:27.426463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_audios_as_images(train_df, train = True)","metadata":{"execution":{"iopub.status.busy":"2024-04-09T13:36:27.429211Z","iopub.execute_input":"2024-04-09T13:36:27.429694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_audios_as_images(valid_df, train = False)","metadata":{},"execution_count":null,"outputs":[]}]}