{"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":"gpu","dataSources":[{"sourceId":70203,"databundleVersionId":8068726,"sourceType":"competition"},{"sourceId":59584,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":49854}],"dockerImageVersionId":30717,"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"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n\n# Path to the train_audio folder\ntrain_audio_path = '/kaggle/input/birdclef-2024/train_audio'\n\n# List all directories in train_audio_path, each directory is treated as a class name\nclass_names = [name for name in os.listdir(train_audio_path) if os.path.isdir(os.path.join(train_audio_path, name))]\n\n# Print the class names\nprint(\"Class Names:\")\nfor class_name in class_names:\n    print(class_name)\n\n# Optionally, save the class names to a file\nclass_names_file = './class_names.txt'\nwith open(class_names_file, 'w') as file:\n    for class_name in class_names:\n        file.write(class_name + '\\n')\n\nprint(f'Class names have been saved to {class_names_file}')\n","metadata":{"execution":{"iopub.status.busy":"2024-06-01T23:11:08.605649Z","iopub.execute_input":"2024-06-01T23:11:08.606067Z","iopub.status.idle":"2024-06-01T23:11:08.658621Z","shell.execute_reply.started":"2024-06-01T23:11:08.606031Z","shell.execute_reply":"2024-06-01T23:11:08.657619Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"number_of_files=0\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input/birdclef-2024/unlabeled_soundscapes'):\n    for filename in filenames:\n        number_of_files=number_of_files+1\nprint(\"Total testing dataset: \" ,number_of_files,\"ogg files\")","metadata":{"execution":{"iopub.status.busy":"2024-06-01T23:12:27.938520Z","iopub.execute_input":"2024-06-01T23:12:27.938901Z","iopub.status.idle":"2024-06-01T23:12:29.549280Z","shell.execute_reply.started":"2024-06-01T23:12:27.938874Z","shell.execute_reply":"2024-06-01T23:12:29.548235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport glob\nimport librosa\nimport numpy as np\nimport cv2\nimport tensorflow as tf\nimport pandas as pd\nimport pickle\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, GlobalAveragePooling2D, Input\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.models import Model\n\n# Define the model (assumed structure based on typical CNN for spectrograms)\ndef create_model(input_shape, num_classes):\n    inputs = Input(shape=(224, 224, 3))\n    base_model = MobileNetV2(weights='imagenet', include_top=False, input_tensor=inputs)  # Load pre-trained MobileNetV2\n    x = GlobalAveragePooling2D()(base_model.output)\n    x = Dense(256, activation='relu')(x)\n    outputs = Dense(num_classes, activation='softmax')(x)\n    model = Model(inputs=inputs, outputs=outputs)\n    return model\n\n# Load the model weights\ninput_shape = (224, 224, 3)\nnum_classes = 182\nmodel = create_model(input_shape, num_classes)\nmodel.load_weights('/kaggle/input/best_model-3.keras/keras/best_model/1/best_model (3).keras')\n\n# Function to preprocess audio to spectrogram using librosa and cv2\ndef preprocess_audio_to_spectrogram(audio_path, img_size=224):\n    audio, sr = librosa.load(audio_path)\n    audio = audio[:sr*5]  # Take a 5-second chunk of audio\n    n_fft = 2048  # Length of the FFT window\n    hop_length = 512  # Number of samples between successive frames\n    n_mels = 128  # Number of Mel bands\n    fmin = 1000  # Min frequency (Hz)\n    fmax = 9000  # Max frequency (Hz)\n\n    # Convert to Mel Spectrogram\n    ms = librosa.feature.melspectrogram(y=audio, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels, fmin=fmin, fmax=fmax)\n    log_ms = librosa.power_to_db(ms, ref=np.max)\n    \n    # Normalize log_ms to be between 0 and 1\n    log_ms_normalized = (log_ms - log_ms.min()) / (log_ms.max() - log_ms.min())\n    \n    # Convert log_ms_normalized to 8-bit unsigned integer format\n    log_ms_normalized_uint8 = (log_ms_normalized * 255).astype(np.uint8)\n    \n    # Convert single-channel image to three-channel RGB image\n    log_ms_rgb = cv2.cvtColor(log_ms_normalized_uint8, cv2.COLOR_GRAY2RGB)\n    \n    # Resize to the target image size for the model\n    log_ms_rgb_resized = cv2.resize(log_ms_rgb, (img_size, img_size))\n    \n    # Normalize the image array\n    log_ms_rgb_resized = log_ms_rgb_resized / 255.0\n    \n    return log_ms_rgb_resized\n\n# Load class names from the pkl file\n# with open('/kaggle/input/class-names/class_names.pkl', 'rb') as f:\n#     class_names = pickle.load(f)\n\n# Step 1: Read .ogg files from the test folder\ntest_folder = '/kaggle/input/birdclef-2024/unlabeled_soundscapes'\nogg_files = glob.glob(os.path.join(test_folder, '*.ogg'))\n\n# Step 2: Use the trained model to make predictions directly\npredictions = {}\ncount=0\nfor ogg_file in ogg_files[0:100]:\n    spectrogram = preprocess_audio_to_spectrogram(ogg_file)\n    spectrogram = np.expand_dims(spectrogram, axis=0)  # Create batch axis\n    prediction = model.predict(spectrogram)\n    predictions[os.path.basename(ogg_file)] = prediction\n    count=count+1\n    print(count)\n\n# Step 3: Create a CSV file with predictions\noutput_file = '/kaggle/working/submission.csv'\ncolumns = ['row_id'] + class_names\ndata = []\n\nfor filename, prediction in predictions.items():\n    row_id = f\"soundscape_{filename.replace('.ogg', '')}\"\n    row = [row_id] + prediction.tolist()[0]\n    data.append(row)\n\ndf = pd.DataFrame(data, columns=columns)\ndf.to_csv(output_file, index=False)\n\nprint(f'Predictions saved to {output_file}')","metadata":{"execution":{"iopub.status.busy":"2024-06-01T23:13:10.766611Z","iopub.execute_input":"2024-06-01T23:13:10.766993Z","iopub.status.idle":"2024-06-01T23:14:51.657970Z","shell.execute_reply.started":"2024-06-01T23:13:10.766961Z","shell.execute_reply":"2024-06-01T23:14:51.656829Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nfor dirname, _, filenames in os.walk('/kaggle/working'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"execution":{"iopub.status.busy":"2024-06-01T23:19:44.897250Z","iopub.execute_input":"2024-06-01T23:19:44.898282Z","iopub.status.idle":"2024-06-01T23:19:44.904645Z","shell.execute_reply.started":"2024-06-01T23:19:44.898243Z","shell.execute_reply":"2024-06-01T23:19:44.903584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nprint(pd.read_csv(\"/kaggle/working/submission.csv\").head())","metadata":{"execution":{"iopub.status.busy":"2024-06-01T23:56:55.865507Z","iopub.execute_input":"2024-06-01T23:56:55.865957Z","iopub.status.idle":"2024-06-01T23:56:55.895684Z","shell.execute_reply.started":"2024-06-01T23:56:55.865922Z","shell.execute_reply":"2024-06-01T23:56:55.894495Z"},"trusted":true},"execution_count":null,"outputs":[]}]}