{"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"}},"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":"2023-03-20T11:16:02.506042Z","iopub.execute_input":"2023-03-20T11:16:02.506921Z","iopub.status.idle":"2023-03-20T11:16:03.542242Z","shell.execute_reply.started":"2023-03-20T11:16:02.506879Z","shell.execute_reply":"2023-03-20T11:16:03.540870Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('../input/birdclef-2023/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":"2023-03-20T11:16:03.544681Z","iopub.execute_input":"2023-03-20T11:16:03.545424Z","iopub.status.idle":"2023-03-20T11:16:03.743030Z","shell.execute_reply.started":"2023-03-20T11:16:03.545387Z","shell.execute_reply":"2023-03-20T11:16:03.741890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[df.len_sec_labels>0].sample(3)","metadata":{"execution":{"iopub.status.busy":"2023-03-20T11:16:03.748449Z","iopub.execute_input":"2023-03-20T11:16:03.751099Z","iopub.status.idle":"2023-03-20T11:16:03.791061Z","shell.execute_reply.started":"2023-03-20T11:16:03.751046Z","shell.execute_reply":"2023-03-20T11:16:03.790049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Something has to be done for Birds with <= 1 samples.\n\n## Also the fact that we have to perform inference in 2 hours w/ CPU, I think best solution is just to have single split rather than using multiple folds.","metadata":{}},{"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":"2023-03-20T11:16:03.796693Z","iopub.execute_input":"2023-03-20T11:16:03.799511Z","iopub.status.idle":"2023-03-20T11:16:03.811221Z","shell.execute_reply.started":"2023-03-20T11:16:03.799454Z","shell.execute_reply":"2023-03-20T11:16:03.810120Z"},"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":"2023-03-20T11:16:03.816180Z","iopub.execute_input":"2023-03-20T11:16:03.819046Z","iopub.status.idle":"2023-03-20T11:16:03.888759Z","shell.execute_reply.started":"2023-03-20T11:16:03.818979Z","shell.execute_reply":"2023-03-20T11:16:03.887613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.primary_label.value_counts()","metadata":{"execution":{"iopub.status.busy":"2023-03-20T11:16:03.893757Z","iopub.execute_input":"2023-03-20T11:16:03.896356Z","iopub.status.idle":"2023-03-20T11:16:03.911587Z","shell.execute_reply.started":"2023-03-20T11:16:03.896316Z","shell.execute_reply":"2023-03-20T11:16:03.910469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df.primary_label.value_counts()","metadata":{"execution":{"iopub.status.busy":"2023-03-20T11:16:03.916273Z","iopub.execute_input":"2023-03-20T11:16:03.918705Z","iopub.status.idle":"2023-03-20T11:16:03.932042Z","shell.execute_reply.started":"2023-03-20T11:16:03.918667Z","shell.execute_reply":"2023-03-20T11:16:03.930862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Config:\n    sampling_rate = 32000\n    duration = 15 \n    fmin = 400\n    fmax = None\n    audios_path = Path(\"/kaggle/input/birdclef-2023/train_audio\")\n    out_dir_train = Path(\"specs/train\") \n    \n    out_dir_valid = Path(\"specs/valid\") \n","metadata":{"execution":{"iopub.status.busy":"2023-03-20T11:16:03.936652Z","iopub.execute_input":"2023-03-20T11:16:03.939128Z","iopub.status.idle":"2023-03-20T11:16:03.946571Z","shell.execute_reply.started":"2023-03-20T11:16:03.939090Z","shell.execute_reply":"2023-03-20T11:16:03.945540Z"},"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":"2023-03-20T11:16:03.951374Z","iopub.execute_input":"2023-03-20T11:16:03.953976Z","iopub.status.idle":"2023-03-20T11:16:03.961078Z","shell.execute_reply.started":"2023-03-20T11:16:03.953940Z","shell.execute_reply":"2023-03-20T11:16:03.960056Z"},"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":"2023-03-20T11:16:03.968958Z","iopub.execute_input":"2023-03-20T11:16:03.971862Z","iopub.status.idle":"2023-03-20T11:16:03.980092Z","shell.execute_reply.started":"2023-03-20T11:16:03.971825Z","shell.execute_reply":"2023-03-20T11:16:03.979059Z"},"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":"2023-03-20T11:16:03.984709Z","iopub.execute_input":"2023-03-20T11:16:03.987254Z","iopub.status.idle":"2023-03-20T11:16:03.998284Z","shell.execute_reply.started":"2023-03-20T11:16:03.987216Z","shell.execute_reply":"2023-03-20T11:16:03.997056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tqdm.pandas()\n","metadata":{"execution":{"iopub.status.busy":"2023-03-20T11:16:03.999836Z","iopub.execute_input":"2023-03-20T11:16:04.000253Z","iopub.status.idle":"2023-03-20T11:16:04.008191Z","shell.execute_reply.started":"2023-03-20T11:16:04.000219Z","shell.execute_reply":"2023-03-20T11:16:04.007056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = add_path_df(train_df)","metadata":{"execution":{"iopub.status.busy":"2023-03-20T11:16:04.009985Z","iopub.execute_input":"2023-03-20T11:16:04.010527Z","iopub.status.idle":"2023-03-20T11:17:24.682323Z","shell.execute_reply.started":"2023-03-20T11:16:04.010490Z","shell.execute_reply":"2023-03-20T11:17:24.681078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df = add_path_df(valid_df)","metadata":{"execution":{"iopub.status.busy":"2023-03-20T11:17:24.684428Z","iopub.execute_input":"2023-03-20T11:17:24.684824Z","iopub.status.idle":"2023-03-20T11:17:44.420960Z","shell.execute_reply.started":"2023-03-20T11:17:24.684788Z","shell.execute_reply":"2023-03-20T11:17:44.419920Z"},"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":"2023-03-20T11:17:44.422554Z","iopub.execute_input":"2023-03-20T11:17:44.423197Z","iopub.status.idle":"2023-03-20T11:17:44.429593Z","shell.execute_reply.started":"2023-03-20T11:17:44.423153Z","shell.execute_reply":"2023-03-20T11:17:44.428520Z"},"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":"2023-03-20T11:17:44.431317Z","iopub.execute_input":"2023-03-20T11:17:44.432093Z","iopub.status.idle":"2023-03-20T11:17:44.443369Z","shell.execute_reply.started":"2023-03-20T11:17:44.432046Z","shell.execute_reply":"2023-03-20T11:17:44.442254Z"},"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":"2023-03-20T11:17:44.445217Z","iopub.execute_input":"2023-03-20T11:17:44.445876Z","iopub.status.idle":"2023-03-20T11:17:44.459007Z","shell.execute_reply.started":"2023-03-20T11:17:44.445842Z","shell.execute_reply":"2023-03-20T11:17:44.458072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tqdm.pandas()","metadata":{"execution":{"iopub.status.busy":"2023-03-20T11:17:44.460518Z","iopub.execute_input":"2023-03-20T11:17:44.461195Z","iopub.status.idle":"2023-03-20T11:17:44.474908Z","shell.execute_reply.started":"2023-03-20T11:17:44.461159Z","shell.execute_reply":"2023-03-20T11:17:44.473943Z"},"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":"2023-03-20T11:17:44.476484Z","iopub.execute_input":"2023-03-20T11:17:44.477179Z","iopub.status.idle":"2023-03-20T11:17:44.484776Z","shell.execute_reply.started":"2023-03-20T11:17:44.477144Z","shell.execute_reply":"2023-03-20T11:17:44.483563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_audios_as_images(train_df, train = True)\n","metadata":{"execution":{"iopub.status.busy":"2023-03-20T11:17:44.486379Z","iopub.execute_input":"2023-03-20T11:17:44.487114Z","iopub.status.idle":"2023-03-20T11:47:03.650661Z","shell.execute_reply.started":"2023-03-20T11:17:44.487080Z","shell.execute_reply":"2023-03-20T11:47:03.649610Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_audios_as_images(valid_df, train = False)","metadata":{"execution":{"iopub.status.busy":"2023-03-20T11:47:03.651957Z","iopub.execute_input":"2023-03-20T11:47:03.652362Z","iopub.status.idle":"2023-03-20T11:54:37.863496Z","shell.execute_reply.started":"2023-03-20T11:47:03.652323Z","shell.execute_reply":"2023-03-20T11:54:37.862446Z"},"trusted":true},"execution_count":null,"outputs":[]}]}