Repository navigation
Expand file tree
/
Copy pathbird.py
More file actions
125 lines (109 loc) · 3.44 KB
/
Copy pathbird.py
File metadata and controls
125 lines (109 loc) · 3.44 KB
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
!pip install plotly scipy
import numpy as np, base64, io, os, plotly.graph_objects as go
from scipy.io import wavfile
from scipy.signal import stft, get_window
from google.colab import files
print("bird.wav)")
uploaded = files.upload()
assert len(uploaded) == 1, "bird.wav"
AUDIO = list(uploaded.keys())[0]
# --- Carrega WAV (mono float normalizado) ---
sr, y = wavfile.read(AUDIO)
y = y.astype(np.float32)
if y.ndim == 2: # estéreo -> mono
y = y.mean(axis=1)
y /= (np.max(np.abs(y)) or 1.0)
# --- Parâmetros da análise ---
n_fft, hop = 2048, 256
win = get_window("hann", n_fft, fftbins=True)
# --- STFT e potência ---
f, t, Z = stft(y, fs=sr, window=win, nperseg=n_fft, noverlap=n_fft-hop,
boundary=None, padded=False)
P = (np.abs(Z)**2) + 1e-12
# --- Features por frame ---
centroid = (f[:, None] * P).sum(axis=0) / P.sum(axis=0)
spread = np.sqrt(((f[:, None] - centroid[None, :])**2 * P).sum(axis=0) / P.sum(axis=0))
flatness = np.exp(np.log(P).mean(axis=0)) / P.mean(axis=0)
times = t.tolist()
centroid = centroid.tolist()
spread = spread.tolist()
flatness = flatness.tolist()
# (Opcional) reduzir nº de frames
max_frames = 1500
if len(times) > max_frames:
idx = np.linspace(0, len(times)-1, max_frames).astype(int)
times = [times[i] for i in idx]
centroid = [centroid[i] for i in idx]
spread = [spread[i] for i in idx]
flatness = [flatness[i] for i in idx]
# --- Empacota áudio em base64 ---
with open(AUDIO, "rb") as f:
b64audio = base64.b64encode(f.read()).decode("ascii")
# --- HTML com Plotly + <audio> sincronizado ---
html = f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<style>body{{margin:0; font-family:sans-serif}}</style>
</head>
<body>
<div style="position:fixed; top:8px; left:8px; right:8px; height:48px; z-index:10; background:#fff">
<audio id="aud" controls src="data:audio/wav;base64,{b64audio}" style="width:100%"></audio>
</div>
<div id="plot" style="position:fixed; top:64px; left:0; right:0; bottom:0;"></div>
<script>
const times = {times};
const Y = {centroid};
const Z = {spread};
const C = {flatness};
const trace = {{
x: [times[0]], y: [Y[0]], z: [Z[0]],
mode: "lines+markers",
type: "scatter3d",
marker: {{
size: 3,
color: [C[0]],
colorscale: "Viridis", // espectro de calor
opacity: 0.9,
colorbar: {{title: "Spectral Flatness"}}
}},
line: {{width: 3}}
}};
const layout = {{
scene: {{
xaxis: {{title: "Tempo (s)"}},
yaxis: {{title: "Spectral Centroid (Hz)"}},
zaxis: {{title: "Spectral Spread (Hz)"}}
}},
margin: {{l:0, r:0, b:0, t:0}}
}};
Plotly.newPlot('plot', [trace], layout);
const aud = document.getElementById('aud');
let drawn = 1;
function step() {{
if (!aud.paused) {{
const t = aud.currentTime;
while (drawn < times.length && times[drawn] <= t) {{
drawn++;
}}
Plotly.update('plot', {{
x: [times.slice(0, drawn)],
y: [Y.slice(0, drawn)],
z: [Z.slice(0, drawn)],
'marker.color': [C.slice(0, drawn)]
}}, {{}});
}}
requestAnimationFrame(step);
}}
requestAnimationFrame(step);
</script>
</body>
</html>
"""
out = "bird_sync.html"
with open(out, "w", encoding="utf-8") as f:
f.write(html)
print("Generated:", out)
files.download(out)