File size: 10,621 Bytes
4aa9c9f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 |
import logging
import math
import time
from pathlib import Path
from typing import Tuple
import cv2
import numpy as np
import pandas as pd
import torch
import torchaudio
import torchaudio.transforms as T
import yaml
from PIL import Image
from tqdm import tqdm
from ultralytics import YOLO
def yaml_read(path: Path) -> dict:
"""Returns yaml content as a python dict."""
with open(path, "r") as f:
return yaml.safe_load(f)
def clip(
waveform: torch.Tensor,
offset: float,
duration: float,
sample_rate: int,
) -> torch.Tensor:
"""
Returns a clipped waveform of `duration` seconds at `offset` in seconds.
"""
offset_frames_start = int(offset * sample_rate)
offset_frames_end = offset_frames_start + int(duration * sample_rate)
return waveform[:, offset_frames_start:offset_frames_end]
def chunk(
waveform: torch.Tensor,
sample_rate: int,
duration: float,
overlap: float,
) -> list[torch.Tensor]:
"""
Returns a list of waveforms as torch.Tensor. Each of these waveforms have the specified
duration and the specified overlap in seconds.
"""
total_seconds = waveform.shape[1] / sample_rate
number_spectrograms = total_seconds / (duration - overlap)
offsets = [
idx * (duration - overlap) for idx in range(0, math.floor(number_spectrograms))
]
return [
clip(
waveform=waveform,
offset=offset,
duration=duration,
sample_rate=sample_rate,
)
for offset in offsets
]
def load_audio(audio_filepath: Path) -> Tuple[torch.Tensor, int]:
"""
Loads an audio_filepath and returns the waveform and sample_rate of the file.
"""
start_time = time.time()
waveform, sample_rate = torchaudio.load(audio_filepath)
end_time = time.time()
elapsed_time = end_time - start_time
logging.info(
f"Elapsed time to load audio file {audio_filepath.name}: {elapsed_time:.2f}s"
)
return waveform, sample_rate
def waveform_to_spectrogram(
waveform: torch.Tensor,
sample_rate: int,
n_fft: int,
hop_length: int,
freq_max: float,
) -> torch.Tensor:
"""
Returns a spectrogram as a torch.Tensor given the provided arguments.
See torchaudio.transforms.Spectrogram for more details about the parameters.
Args:
waveform (torch.Tensor): audio waveform of dimension of `(..., time)`
sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
n_fft (int): Size of FFT
hop_length (int): Length of hop between STFT windows.
freq_max (float): cutoff frequency (Hz)
"""
filtered_waveform = torchaudio.functional.lowpass_biquad(
waveform=waveform, sample_rate=sample_rate, cutoff_freq=freq_max
)
transform = T.Spectrogram(n_fft=n_fft, hop_length=hop_length, power=2)
spectrogram = transform(filtered_waveform)
spectrogram_db = torchaudio.transforms.AmplitudeToDB()(spectrogram)
frequencies = torch.linspace(0, sample_rate // 2, spectrogram_db.size(1))
max_freq_bin = torch.searchsorted(frequencies, freq_max).item()
filtered_spectrogram_db = spectrogram_db[:, :max_freq_bin, :]
return filtered_spectrogram_db
def normalize(x: np.ndarray, max_value: int = 255) -> np.ndarray:
"""
Returns the normalized array, value in [0 - max_value]
Useful for image conversion.
"""
_min, _max = x.min(), x.max()
x_normalized = max_value * (x - _min) / (_max - _min)
return x_normalized.astype(np.uint8)
def spectrogram_tensor_to_np_image(
spectrogram: torch.Tensor, width: int, height: int
) -> np.ndarray:
"""
Returns a numpy array of shape (height, width) that represents the spectrogram tensor as an image.
"""
spectrogram_db_np = spectrogram[0].numpy()
# Normalize to [0, 255] for image conversion
spectrogram_db_normalized = normalize(spectrogram_db_np, max_value=255)
resized_spectrogram_array = cv2.resize(
spectrogram_db_normalized, (width, height), interpolation=cv2.INTER_LINEAR
)
# Horizontal flip to make it show the low frequency range at the bottom left of the image instead of the top left
flipped_resized_spectrogram_array = np.flipud(resized_spectrogram_array)
return flipped_resized_spectrogram_array
def waveform_to_np_image(
waveform: torch.Tensor,
sample_rate: int,
n_fft: int,
hop_length: int,
freq_max: float,
width: int,
height: int,
) -> np.ndarray:
"""
Returns a numpy image of shape (height, width) that represents the waveform tensor as an image of its spectrogram.
Args:
waveform (torch.Tensor): audio waveform of dimension of `(..., time)`
sample_rate (int): sampling rate of the waveform, e.g. 44100 (Hz)
duration (float): time in seconds of the waveform
n_fft (int): Size of FFT
hop_length (int): Length of hop between STFT windows.
freq_max (float): cutoff frequency (Hz)
width (int): width of the generated image
height (int): height of the generated image
"""
spectrogram = waveform_to_spectrogram(
waveform=waveform,
sample_rate=sample_rate,
n_fft=n_fft,
hop_length=hop_length,
freq_max=freq_max,
)
return spectrogram_tensor_to_np_image(
spectrogram=spectrogram,
width=width,
height=height,
)
def batch_sequence(xs: list, batch_size: int):
"""
Yields successive n-sized batches from xs.
"""
for i in range(0, len(xs), batch_size):
yield xs[i : i + batch_size]
def inference(
model: YOLO,
audio_filepath: Path,
duration: float,
overlap: float,
width: int,
height: int,
freq_max: float,
n_fft: int,
hop_length: int,
batch_size: int,
output_dir: Path,
save_spectrograms: bool,
save_predictions: bool,
verbose: bool,
) -> list:
"""
Inference entry point for running on an entire audio_filepath sound file.
"""
logging.info(f"Loading audio filepath {audio_filepath}")
# waveform, sample_rate = torchaudio.load(audio_filepath)
waveform, sample_rate = load_audio(audio_filepath)
waveforms = chunk(
waveform=waveform,
sample_rate=sample_rate,
duration=duration,
overlap=overlap,
)
logging.info(f"Chunking the waveform into {len(waveforms)} overlapping clips")
logging.info(f"Generating {len(waveforms)} spectrograms")
images = [
Image.fromarray(
waveform_to_np_image(
waveform=y,
sample_rate=sample_rate,
n_fft=n_fft,
hop_length=hop_length,
freq_max=freq_max,
width=width,
height=height,
)
)
for y in tqdm(waveforms)
]
if save_spectrograms:
save_dir = output_dir / "spectrograms"
logging.info(f"Saving spectrograms in {save_dir}")
save_dir.mkdir(exist_ok=True, parents=True)
for i, image in tqdm(enumerate(images), total=len(images)):
image.save(save_dir / f"spectrogram_{i}.png")
results = []
batches = list(batch_sequence(images, batch_size=batch_size))
logging.info(f"Running inference on the spectrograms, {len(batches)} batches")
for batch in tqdm(batches):
results.extend(model.predict(batch, verbose=verbose))
if save_predictions:
save_dir = output_dir / "predictions"
save_dir.mkdir(parents=True, exist_ok=True)
logging.info(f"Saving predictions in {save_dir}")
for i, yolov8_prediction in tqdm(enumerate(results), total=len(results)):
yolov8_prediction.save(str(save_dir / f"prediction_{i}.png"))
return results
def index_to_relative_offset(idx: int, duration: float, overlap: float) -> float:
"""
Returns the relative offset in seconds based on the provided spectrogram index, the duration and the overlap.
"""
return idx * (duration - overlap)
def from_yolov8_prediction(
yolov8_prediction,
idx: int,
duration: float,
overlap: float,
freq_min: float,
freq_max: float,
) -> list[dict]:
results = []
for k, box_xyxyn in enumerate(yolov8_prediction.boxes.xyxyn):
conf = yolov8_prediction.boxes.conf[k].item()
x1, y1, x2, y2 = box_xyxyn.numpy()
xmin = min(x1, x2)
xmax = max(x1, x2)
ymin = min(y1, y2)
ymax = max(y1, y2)
freq_start = ymin * (freq_max - freq_min)
freq_end = ymax * (freq_max - freq_min)
t_start = xmin * duration + index_to_relative_offset(
idx=idx, duration=duration, overlap=overlap
)
t_end = xmax * duration + index_to_relative_offset(
idx=idx, duration=duration, overlap=overlap
)
data = {
"probability": conf,
"freq_start": freq_start,
"freq_end": freq_end,
"t_start": t_start,
"t_end": t_end,
}
results.append(data)
return results
def to_dataframe(
yolov8_predictions,
duration: float,
overlap: float,
freq_min: float,
freq_max: float,
) -> pd.DataFrame:
"""
Turns the yolov8 predictions into a pandas dataframe, taking into account the relative offset of each prediction.
The dataframes contains the following columns
probability (float): float in 0-1 that represents the probability that this is an actual rumble
freq_start (float): Hz - where the box starts on the frequency axis
freq_end (float): Hz - where the box ends on the frequency axis
t_start (float): Hz - where the box starts on the time axis
t_end (float): Hz - where the box ends on the time axis
"""
results = []
for idx, yolov8_prediction in enumerate(yolov8_predictions):
results.extend(
from_yolov8_prediction(
yolov8_prediction,
idx=idx,
duration=duration,
overlap=overlap,
freq_min=freq_min,
freq_max=freq_max,
)
)
return pd.DataFrame(results)
def bgr_to_rgb(a: np.ndarray) -> np.ndarray:
"""
Turn a BGR numpy array into a RGB numpy array when the array `a` represents
an image.
"""
return a[:, :, ::-1]
def get_concat_v(im1: Image.Image, im2: Image.Image) -> Image.Image:
"""
Concatenate vertically two PIL images.
"""
dst = Image.new('RGB', (im1.width, im1.height + im2.height))
dst.paste(im1, (0, 0))
dst.paste(im2, (0, im1.height))
return dst
|