diff --git a/node/InputNode/spectrogram_utils.py b/node/InputNode/spectrogram_utils.py index 836ba391..61365d37 100644 --- a/node/InputNode/spectrogram_utils.py +++ b/node/InputNode/spectrogram_utils.py @@ -7,8 +7,11 @@ converting them to colored RGB images for better visualization and event detection. """ +import tempfile import cv2 import numpy as np +import matplotlib +matplotlib.use('Agg') # Use non-GUI backend to prevent display import matplotlib.cm as cm from matplotlib import pyplot as plt from numpy.lib import stride_tricks @@ -237,12 +240,20 @@ def plot_spectrogram(location, plotpath=None, binsize=2**10, colormap="jet"): Args: location: Chemin du fichier audio (.wav) - plotpath: Chemin de sauvegarde de l'image (si None, affiche à l'écran) + plotpath: Chemin de sauvegarde de l'image (si None, utilise un fichier temporaire) binsize: Taille de la fenêtre FFT (par défaut 1024) colormap: Colormap matplotlib à utiliser Returns: - ims: Matrice du spectrogramme en décibels + tuple: (ims, plotpath) where: + - ims: Matrice du spectrogramme en décibels + - plotpath: Chemin vers l'image du spectrogramme sauvegardée + + Note: + Quand plotpath est None, un fichier temporaire est créé avec delete=False. + Dans ce cas, l'appelant reçoit le chemin du fichier temporaire dans le tuple + de retour et est responsable de son nettoyage. Si plotpath est fourni par + l'appelant, aucun nettoyage n'est nécessaire de la part de cette fonction. """ if wav is None: raise ImportError("scipy is required for plot_spectrogram. Install with: pip install scipy") @@ -282,14 +293,17 @@ def plot_spectrogram(location, plotpath=None, binsize=2**10, colormap="jet"): ylocs = np.int16(np.round(np.linspace(0, freqbins-1, 10))) plt.yticks(ylocs, ["%.02f" % freq[i] for i in ylocs]) - if plotpath: - plt.savefig(plotpath, bbox_inches="tight") - else: - plt.show() - + # Always save to a file instead of displaying + if plotpath is None: + # Use a temporary file if no path is provided + temp_file = tempfile.NamedTemporaryFile(suffix='.png', prefix='spectrogram_', delete=False) + plotpath = temp_file.name + temp_file.close() + + plt.savefig(plotpath, bbox_inches="tight") plt.clf() - return ims + return ims, plotpath def create_spectrogram_from_audio(audio_data, sample_rate=44100, binsize=2**10, colormap="jet"):