Upload weights and the model architecture and some info files
Browse files- README.md +191 -0
- best_model.pt +3 -0
- config.json +28 -0
- modeling_f1tone.py +304 -0
- models.py +124 -0
- requirements.txt +5 -0
README.md
CHANGED
|
@@ -1,3 +1,194 @@
|
|
| 1 |
---
|
|
|
|
|
|
|
| 2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
license: apache-2.0
|
| 5 |
+
tags:
|
| 6 |
+
- audio
|
| 7 |
+
- audio-classification
|
| 8 |
+
- emotion-recognition
|
| 9 |
+
- speech-emotion-recognition
|
| 10 |
+
- f1
|
| 11 |
+
- formula1
|
| 12 |
+
- wavlm
|
| 13 |
+
base_model: microsoft/wavlm-base-plus
|
| 14 |
+
pipeline_tag: audio-classification
|
| 15 |
+
metrics:
|
| 16 |
+
- accuracy
|
| 17 |
+
- f1
|
| 18 |
---
|
| 19 |
+
|
| 20 |
+
# 🏎️ F1 Driver Tone & Emotion Detector
|
| 21 |
+
|
| 22 |
+
An advanced Speech Emotion Recognition (SER) deep learning model designed to detect the emotional tone of Formula 1 driver team radio communications in real-time.
|
| 23 |
+
|
| 24 |
+
The model processes raw audio input from driver-to-pit-wall communications, extracts context-rich speech representations using a pretrained **WavLM** encoder (`microsoft/wavlm-base-plus`), and passes them through a downstream **BiLSTM with Temporal Attention mechanism** to classify driver emotions.
|
| 25 |
+
|
| 26 |
+
---
|
| 27 |
+
|
| 28 |
+
## Model Overview
|
| 29 |
+
|
| 30 |
+
- **Base Audio Encoder:** [microsoft/wavlm-base-plus](https://huggingface.co/microsoft/wavlm-base-plus) (768-dimensional frozen embeddings)
|
| 31 |
+
- **Downstream Architecture:** Bidirectional LSTM (128 hidden size) + Temporal Attention Module + Linear Classifier
|
| 32 |
+
- **Target Emotions (6 Classes):**
|
| 33 |
+
- `0`: **Anger**
|
| 34 |
+
- `1`: **Disgust**
|
| 35 |
+
- `2`: **Fear**
|
| 36 |
+
- `3`: **Happy**
|
| 37 |
+
- `4`: **Neutral**
|
| 38 |
+
- `5`: **Sad**
|
| 39 |
+
|
| 40 |
+
---
|
| 41 |
+
|
| 42 |
+
## Model Architecture
|
| 43 |
+
|
| 44 |
+
```text
|
| 45 |
+
RAW DRIVER AUDIO (.wav, .mp3, .flac)
|
| 46 |
+
|
|
| 47 |
+
v
|
| 48 |
+
Audio Preprocessing Pipeline
|
| 49 |
+
- Convert Multi-channel to Mono
|
| 50 |
+
- Resample to 16,000 Hz (16 kHz)
|
| 51 |
+
- Peak Amplitude Normalization
|
| 52 |
+
|
|
| 53 |
+
v
|
| 54 |
+
Frozen WavLM Encoder
|
| 55 |
+
(microsoft/wavlm-base-plus)
|
| 56 |
+
|
|
| 57 |
+
v
|
| 58 |
+
Frame Embeddings [B, T, 768]
|
| 59 |
+
|
|
| 60 |
+
v
|
| 61 |
+
Bidirectional LSTM
|
| 62 |
+
(hidden_size = 128 x 2 = 256)
|
| 63 |
+
|
|
| 64 |
+
v
|
| 65 |
+
Temporal Attention
|
| 66 |
+
(Aggregates sequence into fixed context vector [B, 256])
|
| 67 |
+
|
|
| 68 |
+
v
|
| 69 |
+
Linear Classifier
|
| 70 |
+
(256 -> 6 Logits)
|
| 71 |
+
|
|
| 72 |
+
v
|
| 73 |
+
Softmax Probabilities & Emotion Output
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
---
|
| 77 |
+
|
| 78 |
+
## 🎛️ Input & Output Specifications
|
| 79 |
+
|
| 80 |
+
### 1️⃣ Direct PyTorch Model I/O (`models.py` + `best_model.pt`)
|
| 81 |
+
For users directly loading the PyTorch `BiLSTMAttentionClassifier` model and `.pt` weights:
|
| 82 |
+
|
| 83 |
+
- **Model Input:**
|
| 84 |
+
- `x`: PyTorch Tensor of WavLM frame embeddings with shape **`[Batch_Size, Sequence_Length, 768]`**
|
| 85 |
+
- `mask`: Timestep mask tensor with shape **`[Batch_Size, Sequence_Length]`** (Optional: 1 for valid frame, 0 for padding)
|
| 86 |
+
- **Model Output:**
|
| 87 |
+
- `logits`: Tensor of shape **`[Batch_Size, 6]`** (Unnormalized raw class logits)
|
| 88 |
+
- `attn_weights`: Attention weight tensor of shape **`[Batch_Size, Sequence_Length]`** (Frame-level temporal attention scores)
|
| 89 |
+
|
| 90 |
+
---
|
| 91 |
+
|
| 92 |
+
### 2️⃣ Full Pipeline I/O (Using `modeling_f1tone.py`)
|
| 93 |
+
For users using the complete audio-to-prediction helper script:
|
| 94 |
+
|
| 95 |
+
- **Input Requirements:**
|
| 96 |
+
- Raw Audio File (`.wav`, `.mp3`, `.flac`, `.ogg`, `.m4a`)
|
| 97 |
+
- Automatically converted to 16 kHz Mono and peak-normalized.
|
| 98 |
+
- **Output Return Format:**
|
| 99 |
+
Structured Python dictionary:
|
| 100 |
+
```json
|
| 101 |
+
{
|
| 102 |
+
"audio_file": "driver_radio_01.wav",
|
| 103 |
+
"predicted_emotion": "Anger",
|
| 104 |
+
"confidence": 94.25,
|
| 105 |
+
"probabilities": {
|
| 106 |
+
"Anger": 94.25,
|
| 107 |
+
"Neutral": 3.10,
|
| 108 |
+
"Disgust": 1.45,
|
| 109 |
+
"Fear": 0.70,
|
| 110 |
+
"Happy": 0.30,
|
| 111 |
+
"Sad": 0.20
|
| 112 |
+
},
|
| 113 |
+
"attention_weights": [0.012, 0.045, 0.180, ...]
|
| 114 |
+
}
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
---
|
| 118 |
+
|
| 119 |
+
## How to Run Inference using `modeling_f1tone.py`
|
| 120 |
+
|
| 121 |
+
### Directory Setup (`input/` folder)
|
| 122 |
+
To run predictions on audio files:
|
| 123 |
+
1. Create an `input/` folder in the directory where `modeling_f1tone.py` is located.
|
| 124 |
+
2. Place your team radio `.wav` or `.mp3` files inside `input/`.
|
| 125 |
+
|
| 126 |
+
```text
|
| 127 |
+
ToneDetectorF1/
|
| 128 |
+
├── best_model.pt
|
| 129 |
+
├── modeling_f1tone.py
|
| 130 |
+
├── config.json
|
| 131 |
+
└── input/
|
| 132 |
+
├── driver_radio_1.wav
|
| 133 |
+
└── pit_communication_2.mp3
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
### Running via Command Line
|
| 137 |
+
|
| 138 |
+
**Option A: Process all files in `input/` folder**
|
| 139 |
+
```bash
|
| 140 |
+
python modeling_f1tone.py
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
**Option B: Pass an explicit audio file path**
|
| 144 |
+
```bash
|
| 145 |
+
python modeling_f1tone.py --audio_path path/to/my_audio.wav
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
### Python Code Integration Example
|
| 149 |
+
```python
|
| 150 |
+
from modeling_f1tone import FinalPredictor
|
| 151 |
+
|
| 152 |
+
# Initialize predictor with model checkpoint
|
| 153 |
+
predictor = FinalPredictor(checkpoint_path="best_model.pt")
|
| 154 |
+
|
| 155 |
+
# Perform inference on an audio clip
|
| 156 |
+
result = predictor.predict_single("input/driver_radio_1.wav")
|
| 157 |
+
|
| 158 |
+
print(f"Predicted Emotion : {result['predicted_emotion']}")
|
| 159 |
+
print(f"Confidence : {result['confidence']:.2f}%")
|
| 160 |
+
print("Full Probabilities:", result['probabilities'])
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
---
|
| 164 |
+
|
| 165 |
+
## 📊 Verified Model Evaluation Results
|
| 166 |
+
|
| 167 |
+
Evaluation performed on holdout test set (1,117 audio evaluation samples):
|
| 168 |
+
|
| 169 |
+
| Metric | Score |
|
| 170 |
+
| :--- | :--- |
|
| 171 |
+
| **Test Set Accuracy** | **67.86%** |
|
| 172 |
+
| **Test Set Macro F1-Score** | **0.6794** |
|
| 173 |
+
| **Validation Accuracy (Epoch 8)** | **69.89%** |
|
| 174 |
+
| **Validation Macro F1-Score** | **0.7006** |
|
| 175 |
+
| **Feature Encoder** | `microsoft/wavlm-base-plus` (768-dim, Frozen) |
|
| 176 |
+
| **Classifier Head** | BiLSTM (128) + Temporal Attention + Linear (6) |
|
| 177 |
+
|
| 178 |
+
### 📈 Per-Class Performance Breakdown (Test Set)
|
| 179 |
+
|
| 180 |
+
| Emotion Class | Precision | Recall | F1-Score | Evaluation Support |
|
| 181 |
+
| :--- | :--- | :--- | :--- | :--- |
|
| 182 |
+
| **Anger** 😡 | **76.71%** | **87.96%** | **0.8195** | 191 samples |
|
| 183 |
+
| **Neutral** 😐 | **77.85%** | **75.46%** | **0.7664** | 163 samples |
|
| 184 |
+
| **Happy** 😊 | **79.05%** | **61.26%** | **0.6903** | 191 samples |
|
| 185 |
+
| **Disgust** 🤢 | **64.65%** | **67.02%** | **0.6581** | 191 samples |
|
| 186 |
+
| **Fear** 😨 | **52.05%** | **66.84%** | **0.5853** | 190 samples |
|
| 187 |
+
| **Sad** 🥺 | **63.33%** | **49.74%** | **0.5572** | 191 samples |
|
| 188 |
+
|
| 189 |
+
---
|
| 190 |
+
|
| 191 |
+
## Citation & License
|
| 192 |
+
|
| 193 |
+
- **License:** Apache 2.0
|
| 194 |
+
- **Base Encoder Paper:** *WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing* (Chen et al., 2022)
|
best_model.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5e258e689054804b02a2c037d1181d939055eaeb756955508ebd3a996fb65c69
|
| 3 |
+
size 11068789
|
config.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"BiLSTMAttentionClassifier"
|
| 4 |
+
],
|
| 5 |
+
"model_type": "wavlm-bilstm-attention",
|
| 6 |
+
"base_encoder": "microsoft/wavlm-base-plus",
|
| 7 |
+
"target_sample_rate": 16000,
|
| 8 |
+
"input_size": 768,
|
| 9 |
+
"hidden_size": 128,
|
| 10 |
+
"num_classes": 6,
|
| 11 |
+
"dropout": 0.3,
|
| 12 |
+
"id2label": {
|
| 13 |
+
"0": "Anger",
|
| 14 |
+
"1": "Disgust",
|
| 15 |
+
"2": "Fear",
|
| 16 |
+
"3": "Happy",
|
| 17 |
+
"4": "Neutral",
|
| 18 |
+
"5": "Sad"
|
| 19 |
+
},
|
| 20 |
+
"label2id": {
|
| 21 |
+
"Anger": 0,
|
| 22 |
+
"Disgust": 1,
|
| 23 |
+
"Fear": 2,
|
| 24 |
+
"Happy": 3,
|
| 25 |
+
"Neutral": 4,
|
| 26 |
+
"Sad": 5
|
| 27 |
+
}
|
| 28 |
+
}
|
modeling_f1tone.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import sys
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
|
| 8 |
+
import torchaudio
|
| 9 |
+
from transformers import WavLMModel
|
| 10 |
+
|
| 11 |
+
# Ensure UTF-8 output encoding for Windows terminal compatibility
|
| 12 |
+
if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
|
| 13 |
+
try:
|
| 14 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 15 |
+
except Exception:
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
# ============================================================
|
| 19 |
+
# CONFIGURATION & CONSTANTS
|
| 20 |
+
# ============================================================
|
| 21 |
+
|
| 22 |
+
WAVLM_MODEL_NAME = "microsoft/wavlm-base-plus"
|
| 23 |
+
CHECKPOINT_PATH = Path("checkpoints/best_model.pt")
|
| 24 |
+
INPUT_DIR = Path("input")
|
| 25 |
+
TARGET_SR = 16000
|
| 26 |
+
|
| 27 |
+
EMOTION_CLASSES = ["Anger", "Disgust", "Fear", "Happy", "Neutral", "Sad"]
|
| 28 |
+
|
| 29 |
+
# ============================================================
|
| 30 |
+
# MODEL ARCHITECTURE DEFINITION (Self-Contained Single File)
|
| 31 |
+
# ============================================================
|
| 32 |
+
|
| 33 |
+
class BiLSTMFeatureExtractor(nn.Module):
|
| 34 |
+
def __init__(self, input_size=768, hidden_size=128, num_layers=1, dropout=0.0):
|
| 35 |
+
super(BiLSTMFeatureExtractor, self).__init__()
|
| 36 |
+
self.input_size = input_size
|
| 37 |
+
self.hidden_size = hidden_size
|
| 38 |
+
self.num_layers = num_layers
|
| 39 |
+
self.bidirectional = True
|
| 40 |
+
|
| 41 |
+
self.bilstm = nn.LSTM(
|
| 42 |
+
input_size=input_size,
|
| 43 |
+
hidden_size=hidden_size,
|
| 44 |
+
num_layers=num_layers,
|
| 45 |
+
batch_first=True,
|
| 46 |
+
bidirectional=True,
|
| 47 |
+
dropout=dropout if num_layers > 1 else 0.0
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def forward(self, x, mask=None):
|
| 51 |
+
batch_size, seq_len, _ = x.shape
|
| 52 |
+
|
| 53 |
+
if mask is not None:
|
| 54 |
+
lengths = mask.sum(dim=1).cpu()
|
| 55 |
+
packed_x = pack_padded_sequence(
|
| 56 |
+
x,
|
| 57 |
+
lengths,
|
| 58 |
+
batch_first=True,
|
| 59 |
+
enforce_sorted=False
|
| 60 |
+
)
|
| 61 |
+
packed_out, (hn, cn) = self.bilstm(packed_x)
|
| 62 |
+
out, _ = pad_packed_sequence(
|
| 63 |
+
packed_out,
|
| 64 |
+
batch_first=True,
|
| 65 |
+
total_length=seq_len
|
| 66 |
+
)
|
| 67 |
+
else:
|
| 68 |
+
out, (hn, cn) = self.bilstm(x)
|
| 69 |
+
|
| 70 |
+
return out
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class TemporalAttention(nn.Module):
|
| 74 |
+
def __init__(self, input_dim=256):
|
| 75 |
+
super(TemporalAttention, self).__init__()
|
| 76 |
+
self.input_dim = input_dim
|
| 77 |
+
self.w = nn.Linear(input_dim, 1, bias=False)
|
| 78 |
+
|
| 79 |
+
def forward(self, h, mask=None):
|
| 80 |
+
scores = self.w(torch.tanh(h)).squeeze(-1) # [B, T]
|
| 81 |
+
|
| 82 |
+
if mask is not None:
|
| 83 |
+
scores = scores.masked_fill(mask == 0, -1e9)
|
| 84 |
+
|
| 85 |
+
attn_weights = torch.softmax(scores, dim=1) # [B, T]
|
| 86 |
+
context = torch.bmm(attn_weights.unsqueeze(1), h).squeeze(1) # [B, 256]
|
| 87 |
+
|
| 88 |
+
return context, attn_weights
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class BiLSTMAttentionClassifier(nn.Module):
|
| 92 |
+
def __init__(self, input_size=768, hidden_size=128, num_classes=6, dropout=0.3):
|
| 93 |
+
super(BiLSTMAttentionClassifier, self).__init__()
|
| 94 |
+
self.bilstm = BiLSTMFeatureExtractor(
|
| 95 |
+
input_size=input_size,
|
| 96 |
+
hidden_size=hidden_size,
|
| 97 |
+
num_layers=1,
|
| 98 |
+
dropout=dropout
|
| 99 |
+
)
|
| 100 |
+
context_dim = hidden_size * 2 # 256
|
| 101 |
+
self.attention = TemporalAttention(input_dim=context_dim)
|
| 102 |
+
self.dropout = nn.Dropout(dropout)
|
| 103 |
+
self.classifier = nn.Linear(context_dim, num_classes)
|
| 104 |
+
|
| 105 |
+
def forward(self, x, mask=None):
|
| 106 |
+
bilstm_out = self.bilstm(x, mask=mask)
|
| 107 |
+
context, attn_weights = self.attention(bilstm_out, mask=mask)
|
| 108 |
+
dropped_context = self.dropout(context)
|
| 109 |
+
logits = self.classifier(dropped_context)
|
| 110 |
+
return logits, attn_weights
|
| 111 |
+
|
| 112 |
+
# ============================================================
|
| 113 |
+
# EXACT AUDIO PREPROCESSING LOGIC (Used During Training)
|
| 114 |
+
# ============================================================
|
| 115 |
+
|
| 116 |
+
def preprocess_audio(audio_path):
|
| 117 |
+
"""
|
| 118 |
+
Load raw audio file (.wav, .mp3, .flac, .ogg), convert to 16 kHz mono, and peak-normalize amplitude.
|
| 119 |
+
"""
|
| 120 |
+
audio_path = Path(audio_path)
|
| 121 |
+
|
| 122 |
+
# 1. Load audio with torchaudio, fallback to soundfile for mp3/flac if needed
|
| 123 |
+
try:
|
| 124 |
+
waveform, sample_rate = torchaudio.load(str(audio_path))
|
| 125 |
+
except Exception:
|
| 126 |
+
import soundfile as sf
|
| 127 |
+
data, sample_rate = sf.read(str(audio_path))
|
| 128 |
+
waveform = torch.tensor(data, dtype=torch.float32)
|
| 129 |
+
if waveform.ndim == 1:
|
| 130 |
+
waveform = waveform.unsqueeze(0)
|
| 131 |
+
elif waveform.ndim == 2:
|
| 132 |
+
waveform = waveform.T
|
| 133 |
+
|
| 134 |
+
# 2. Convert to mono if multi-channel
|
| 135 |
+
if waveform.shape[0] > 1:
|
| 136 |
+
waveform = waveform.mean(dim=0, keepdim=True)
|
| 137 |
+
|
| 138 |
+
# 3. Resample to 16 kHz if necessary
|
| 139 |
+
if sample_rate != TARGET_SR:
|
| 140 |
+
resampler = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=TARGET_SR)
|
| 141 |
+
waveform = resampler(waveform)
|
| 142 |
+
|
| 143 |
+
# 4. Squeeze channel dimension [1, num_samples] -> [num_samples]
|
| 144 |
+
waveform = waveform.squeeze(0)
|
| 145 |
+
|
| 146 |
+
# 5. Amplitude peak normalization
|
| 147 |
+
max_val = waveform.abs().max()
|
| 148 |
+
if max_val > 0:
|
| 149 |
+
waveform = waveform / max_val
|
| 150 |
+
|
| 151 |
+
return waveform
|
| 152 |
+
|
| 153 |
+
# ============================================================
|
| 154 |
+
# FINAL PREDICTOR PIPELINE CLASS
|
| 155 |
+
# ============================================================
|
| 156 |
+
|
| 157 |
+
class FinalPredictor:
|
| 158 |
+
def __init__(self, checkpoint_path=CHECKPOINT_PATH):
|
| 159 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 160 |
+
print("=" * 60)
|
| 161 |
+
print("INITIALIZING F1 DRIVER TONE DETECTOR PIPELINE")
|
| 162 |
+
print("=" * 60)
|
| 163 |
+
print(f"Compute Device : {self.device}")
|
| 164 |
+
if self.device.type == "cuda":
|
| 165 |
+
print(f"GPU : {torch.cuda.get_device_name(0)}")
|
| 166 |
+
|
| 167 |
+
print(f"\n[1] Loading WavLM Encoder ({WAVLM_MODEL_NAME})...")
|
| 168 |
+
self.wavlm = WavLMModel.from_pretrained(WAVLM_MODEL_NAME).to(self.device)
|
| 169 |
+
self.wavlm.eval()
|
| 170 |
+
|
| 171 |
+
print(f"[2] Loading Trained Downstream Model ({checkpoint_path})...")
|
| 172 |
+
if not checkpoint_path.exists():
|
| 173 |
+
raise FileNotFoundError(f"Checkpoint file not found at {checkpoint_path}. Please run training first!")
|
| 174 |
+
|
| 175 |
+
self.classifier = BiLSTMAttentionClassifier(
|
| 176 |
+
input_size=768,
|
| 177 |
+
hidden_size=128,
|
| 178 |
+
num_classes=6
|
| 179 |
+
).to(self.device)
|
| 180 |
+
|
| 181 |
+
checkpoint = torch.load(checkpoint_path, map_location=self.device, weights_only=False)
|
| 182 |
+
self.classifier.load_state_dict(checkpoint["model_state_dict"])
|
| 183 |
+
self.classifier.eval()
|
| 184 |
+
print("Pipeline initialized and ready for inference!")
|
| 185 |
+
print("=" * 60)
|
| 186 |
+
|
| 187 |
+
def predict_single(self, audio_path, chunk_duration=2.5, hop_duration=1.5):
|
| 188 |
+
audio_path = Path(audio_path)
|
| 189 |
+
if not audio_path.exists():
|
| 190 |
+
raise FileNotFoundError(f"Audio file not found: {audio_path}")
|
| 191 |
+
|
| 192 |
+
# 1. Preprocess raw audio waveform [num_samples]
|
| 193 |
+
waveform = preprocess_audio(audio_path)
|
| 194 |
+
num_samples = waveform.size(0)
|
| 195 |
+
duration_sec = num_samples / float(TARGET_SR)
|
| 196 |
+
|
| 197 |
+
chunk_samples = int(chunk_duration * TARGET_SR)
|
| 198 |
+
hop_samples = int(hop_duration * TARGET_SR)
|
| 199 |
+
|
| 200 |
+
chunk_probs = []
|
| 201 |
+
last_attn_weights = None
|
| 202 |
+
|
| 203 |
+
with torch.no_grad():
|
| 204 |
+
# If audio is long (> 4.0s), use 2.5s sliding window chunking
|
| 205 |
+
if duration_sec > 4.0 and num_samples > chunk_samples:
|
| 206 |
+
starts = list(range(0, num_samples - chunk_samples + 1, hop_samples))
|
| 207 |
+
# Ensure the end of audio is covered
|
| 208 |
+
if starts[-1] + chunk_samples < num_samples:
|
| 209 |
+
starts.append(num_samples - chunk_samples)
|
| 210 |
+
|
| 211 |
+
for start in starts:
|
| 212 |
+
end = start + chunk_samples
|
| 213 |
+
chunk_wave = waveform[start:end].unsqueeze(0).to(self.device)
|
| 214 |
+
|
| 215 |
+
outputs = self.wavlm(input_values=chunk_wave)
|
| 216 |
+
embedding = outputs.last_hidden_state
|
| 217 |
+
mask = torch.ones((1, embedding.size(1)), dtype=torch.int64, device=self.device)
|
| 218 |
+
|
| 219 |
+
logits, attn_weights = self.classifier(embedding, mask=mask)
|
| 220 |
+
probs = F.softmax(logits, dim=-1).squeeze(0)
|
| 221 |
+
chunk_probs.append(probs)
|
| 222 |
+
last_attn_weights = attn_weights.squeeze(0).cpu().numpy()
|
| 223 |
+
|
| 224 |
+
probabilities = torch.stack(chunk_probs).mean(dim=0)
|
| 225 |
+
else:
|
| 226 |
+
input_values = waveform.unsqueeze(0).to(self.device)
|
| 227 |
+
outputs = self.wavlm(input_values=input_values)
|
| 228 |
+
embedding = outputs.last_hidden_state
|
| 229 |
+
mask = torch.ones((1, embedding.size(1)), dtype=torch.int64, device=self.device)
|
| 230 |
+
logits, attn_weights = self.classifier(embedding, mask=mask)
|
| 231 |
+
probabilities = F.softmax(logits, dim=-1).squeeze(0)
|
| 232 |
+
last_attn_weights = attn_weights.squeeze(0).cpu().numpy()
|
| 233 |
+
|
| 234 |
+
pred_id = torch.argmax(probabilities).item()
|
| 235 |
+
pred_emotion = EMOTION_CLASSES[pred_id]
|
| 236 |
+
confidence = probabilities[pred_id].item() * 100.0
|
| 237 |
+
|
| 238 |
+
probs_dict = {
|
| 239 |
+
EMOTION_CLASSES[i]: probabilities[i].item() * 100.0
|
| 240 |
+
for i in range(len(EMOTION_CLASSES))
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
return {
|
| 244 |
+
"audio_file": audio_path.name,
|
| 245 |
+
"duration_sec": round(duration_sec, 2),
|
| 246 |
+
"predicted_emotion": pred_emotion,
|
| 247 |
+
"confidence": confidence,
|
| 248 |
+
"probabilities": probs_dict,
|
| 249 |
+
"attention_weights": last_attn_weights,
|
| 250 |
+
"chunks_processed": len(chunk_probs) if chunk_probs else 1
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
# ============================================================
|
| 254 |
+
# MAIN CLI DRIVER
|
| 255 |
+
# ============================================================
|
| 256 |
+
|
| 257 |
+
def print_report(result):
|
| 258 |
+
print("\n" + "=" * 60)
|
| 259 |
+
print(f"PREDICTION REPORT: {result['audio_file']}")
|
| 260 |
+
print("=" * 60)
|
| 261 |
+
print(f"Predicted Emotion : {result['predicted_emotion']} ({result['confidence']:.2f}% confidence)")
|
| 262 |
+
print("-" * 60)
|
| 263 |
+
print("EMOTION PROBABILITY BREAKDOWN:")
|
| 264 |
+
for emotion, prob in result["probabilities"].items():
|
| 265 |
+
bar = "#" * int(prob / 5)
|
| 266 |
+
print(f" {emotion:10s} : {prob:6.2f}% | {bar}")
|
| 267 |
+
print("=" * 60)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def main():
|
| 271 |
+
parser = argparse.ArgumentParser(description="F1 Driver Tone Predictor (Single File Pipeline)")
|
| 272 |
+
parser.add_argument("--audio_path", type=str, default=None,
|
| 273 |
+
help="Path to specific raw driver audio file (.wav, .mp3, .flac, .ogg)")
|
| 274 |
+
args = parser.parse_args()
|
| 275 |
+
|
| 276 |
+
predictor = FinalPredictor()
|
| 277 |
+
|
| 278 |
+
if args.audio_path:
|
| 279 |
+
target_path = Path(args.audio_path)
|
| 280 |
+
result = predictor.predict_single(target_path)
|
| 281 |
+
print_report(result)
|
| 282 |
+
else:
|
| 283 |
+
# Scan input directory
|
| 284 |
+
INPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 285 |
+
valid_extensions = {".wav", ".mp3", ".flac", ".ogg", ".m4a"}
|
| 286 |
+
audio_files = [
|
| 287 |
+
f for f in INPUT_DIR.iterdir()
|
| 288 |
+
if f.is_file() and f.suffix.lower() in valid_extensions
|
| 289 |
+
]
|
| 290 |
+
|
| 291 |
+
if not audio_files:
|
| 292 |
+
print(f"\n[INFO] No audio files found in input/ directory ({INPUT_DIR.resolve()}).")
|
| 293 |
+
print("Usage Options:")
|
| 294 |
+
print(" 1. Place .wav or .mp3 files into the 'input/' folder and re-run python finalpredictor.py")
|
| 295 |
+
print(" 2. Run with explicit file path: python finalpredictor.py --audio_path <path_to_audio_file>")
|
| 296 |
+
else:
|
| 297 |
+
print(f"\nFound {len(audio_files)} audio file(s) in {INPUT_DIR}/ directory. Processing...")
|
| 298 |
+
for audio_file in audio_files:
|
| 299 |
+
result = predictor.predict_single(audio_file)
|
| 300 |
+
print_report(result)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
if __name__ == "__main__":
|
| 304 |
+
main()
|
models.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class BiLSTMFeatureExtractor(nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
BiLSTM Feature Extractor module.
|
| 9 |
+
|
| 10 |
+
Inputs:
|
| 11 |
+
x : Padded WavLM sequence embeddings [B, T, 768]
|
| 12 |
+
mask : Timestep mask [B, T] (optional, 1 for real timesteps, 0 for padding)
|
| 13 |
+
|
| 14 |
+
Outputs:
|
| 15 |
+
out : BiLSTM contextual representations [B, T, 256]
|
| 16 |
+
"""
|
| 17 |
+
def __init__(self, input_size=768, hidden_size=128, num_layers=1, dropout=0.0):
|
| 18 |
+
super(BiLSTMFeatureExtractor, self).__init__()
|
| 19 |
+
|
| 20 |
+
self.input_size = input_size
|
| 21 |
+
self.hidden_size = hidden_size
|
| 22 |
+
self.num_layers = num_layers
|
| 23 |
+
self.bidirectional = True
|
| 24 |
+
|
| 25 |
+
# BiLSTM Layer: hidden_size=128, bidirectional=True -> Output dim = 128 * 2 = 256
|
| 26 |
+
self.bilstm = nn.LSTM(
|
| 27 |
+
input_size=input_size,
|
| 28 |
+
hidden_size=hidden_size,
|
| 29 |
+
num_layers=num_layers,
|
| 30 |
+
batch_first=True,
|
| 31 |
+
bidirectional=True,
|
| 32 |
+
dropout=dropout if num_layers > 1 else 0.0
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def forward(self, x, mask=None):
|
| 36 |
+
batch_size, seq_len, _ = x.shape
|
| 37 |
+
|
| 38 |
+
if mask is not None:
|
| 39 |
+
lengths = mask.sum(dim=1).cpu()
|
| 40 |
+
|
| 41 |
+
packed_x = pack_padded_sequence(
|
| 42 |
+
x,
|
| 43 |
+
lengths,
|
| 44 |
+
batch_first=True,
|
| 45 |
+
enforce_sorted=False
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
packed_out, (hn, cn) = self.bilstm(packed_x)
|
| 49 |
+
|
| 50 |
+
out, _ = pad_packed_sequence(
|
| 51 |
+
packed_out,
|
| 52 |
+
batch_first=True,
|
| 53 |
+
total_length=seq_len
|
| 54 |
+
)
|
| 55 |
+
else:
|
| 56 |
+
out, (hn, cn) = self.bilstm(x)
|
| 57 |
+
|
| 58 |
+
return out
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class TemporalAttention(nn.Module):
|
| 62 |
+
"""
|
| 63 |
+
Temporal Attention Module.
|
| 64 |
+
Learns frame-wise attention scores over sequence length T to aggregate
|
| 65 |
+
BiLSTM output sequence [B, T, 256] into a fixed 256-dimensional context vector [B, 256].
|
| 66 |
+
|
| 67 |
+
Inputs:
|
| 68 |
+
h : BiLSTM outputs [B, T, input_dim] (input_dim=256)
|
| 69 |
+
mask : Timestep mask [B, T] (1 for real timesteps, 0 for padding)
|
| 70 |
+
|
| 71 |
+
Outputs:
|
| 72 |
+
context : Aggregated context vector [B, 256]
|
| 73 |
+
attn_weights : Normalized attention weights [B, T]
|
| 74 |
+
"""
|
| 75 |
+
def __init__(self, input_dim=256):
|
| 76 |
+
super(TemporalAttention, self).__init__()
|
| 77 |
+
self.input_dim = input_dim
|
| 78 |
+
self.w = nn.Linear(input_dim, 1, bias=False)
|
| 79 |
+
|
| 80 |
+
def forward(self, h, mask=None):
|
| 81 |
+
scores = self.w(torch.tanh(h)).squeeze(-1) # [B, T]
|
| 82 |
+
|
| 83 |
+
if mask is not None:
|
| 84 |
+
scores = scores.masked_fill(mask == 0, -1e9)
|
| 85 |
+
|
| 86 |
+
attn_weights = torch.softmax(scores, dim=1) # [B, T]
|
| 87 |
+
context = torch.bmm(attn_weights.unsqueeze(1), h).squeeze(1) # [B, 256]
|
| 88 |
+
|
| 89 |
+
return context, attn_weights
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class BiLSTMAttentionClassifier(nn.Module):
|
| 93 |
+
"""
|
| 94 |
+
Full Downstream Model Architecture:
|
| 95 |
+
WavLM Embedding [B, T, 768] -> BiLSTM -> [B, T, 256] -> Temporal Attention -> [B, 256] -> Linear Classifier -> [B, 6] Logits
|
| 96 |
+
"""
|
| 97 |
+
def __init__(self, input_size=768, hidden_size=128, num_classes=6, dropout=0.3):
|
| 98 |
+
super(BiLSTMAttentionClassifier, self).__init__()
|
| 99 |
+
|
| 100 |
+
self.bilstm = BiLSTMFeatureExtractor(
|
| 101 |
+
input_size=input_size,
|
| 102 |
+
hidden_size=hidden_size,
|
| 103 |
+
num_layers=1,
|
| 104 |
+
dropout=dropout
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
context_dim = hidden_size * 2 # 256
|
| 108 |
+
self.attention = TemporalAttention(input_dim=context_dim)
|
| 109 |
+
|
| 110 |
+
self.dropout = nn.Dropout(dropout)
|
| 111 |
+
self.classifier = nn.Linear(context_dim, num_classes)
|
| 112 |
+
|
| 113 |
+
def forward(self, x, mask=None):
|
| 114 |
+
# 1. BiLSTM: [B, T, 768] -> [B, T, 256]
|
| 115 |
+
bilstm_out = self.bilstm(x, mask=mask)
|
| 116 |
+
|
| 117 |
+
# 2. Temporal Attention: [B, T, 256] -> [B, 256]
|
| 118 |
+
context, attn_weights = self.attention(bilstm_out, mask=mask)
|
| 119 |
+
|
| 120 |
+
# 3. Dropout + Linear Classifier: [B, 256] -> [B, 6]
|
| 121 |
+
dropped_context = self.dropout(context)
|
| 122 |
+
logits = self.classifier(dropped_context)
|
| 123 |
+
|
| 124 |
+
return logits, attn_weights
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.0.0
|
| 2 |
+
torchaudio>=2.0.0
|
| 3 |
+
transformers>=4.30.0
|
| 4 |
+
soundfile>=0.12.1
|
| 5 |
+
numpy>=1.22.0
|