Daporte commited on
Commit
73a450d
·
verified ·
1 Parent(s): 799027f

Upload features.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. features.py +316 -0
features.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Turn drawn strokes into the prosody features a speech model expects.
2
+
3
+ The transcription models in `finetune_whisper` were trained on two signals
4
+ extracted from real speech at 200 Hz -- interpolated F0 and intensity -- which
5
+ is exactly what a stylus produces: vertical position is pitch, pressure is
6
+ loudness. This module resamples strokes onto that 200 Hz grid and applies the
7
+ same normalisation the training pipeline used, so a drawing can be fed to the
8
+ model as if it were speech.
9
+
10
+ The constants here are not free choices. They mirror the training pipeline's
11
+ own FEATURE_SCALES and the checkpoint's `model_config.json`; if those change,
12
+ these must change with them. This module is a verbatim port of the reference
13
+ implementation's `features.py`, minus code paths the demo never takes, so a
14
+ drawing is turned into model input exactly as in the paper.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass
20
+
21
+ import numpy as np
22
+
23
+ from .f0_interp import interpolate_f0
24
+
25
+ # Prosody features are extracted at 200 Hz (time_step 0.005 s) and the mel
26
+ # target runs at 100 Hz; the model's length_ratio=0.5 encodes that 2:1.
27
+ FEATURE_RATE_HZ = 200.0
28
+
29
+ # Physical-range normalisation, copied from FeaturesToMelDataset.FEATURE_SCALES.
30
+ F0_SCALE = 500.0 # Hz, human pitch range ~50-500
31
+ INTENSITY_SCALE = 100.0 # dB SPL, typical range 0-100
32
+
33
+ # Pen pressure is a 0..1 ratio; speech intensity is dB SPL. These bounds are
34
+ # measured, not chosen: across the extracted templates (2600 frames of real
35
+ # speech from the training distribution) intensity runs p5=51.8, p50=68.6,
36
+ # p95=81.0 dB. Mapping 0..1 onto 50..85 dB covers that spread and puts the
37
+ # speech median at pressure 0.53, so a natural mid-pressure stroke produces
38
+ # typical speech loudness.
39
+ #
40
+ # The earlier 45-80 dB guess put the median at 0.67 and clipped the top: a
41
+ # comfortable touch read ~6 dB quieter than real speech, and the loudest
42
+ # frames (84.5 dB) could not be reached at all.
43
+ #
44
+ # Re-derive with: uv run python scripts/calibrate_intensity.py
45
+ INTENSITY_FLOOR_DB = 50.0
46
+ INTENSITY_CEIL_DB = 85.0
47
+
48
+ # Where speech actually lives. These are measured from the extracted
49
+ # templates (2600 frames of real speech from the training distribution)
50
+ # rather than taken from textbook adult F0 ranges: p1 is MIDI 38.7 and p99.5
51
+ # is MIDI 64.9, so real contours reach well outside the "average adult"
52
+ # 85-255 Hz band.
53
+ #
54
+ # An earlier F2-C#4 (41-61) surface clipped 4.8% of frames, and the clipped
55
+ # frames are the pitch extremes that carry the most information. B1-G4 clips
56
+ # none of the measured 2600.
57
+ #
58
+ # Re-derive with: uv run python scripts/trace_fidelity.py (which reports
59
+ # clipping) after rebuilding templates.json.
60
+ SPEECH_MIDI_LOW = 35 # B1, 61.7 Hz
61
+ SPEECH_MIDI_HIGH = 67 # G4, 392.0 Hz
62
+
63
+ # The widest surface the model can be drawn on at all, as opposed to the
64
+ # range real speech occupies. F0_SCALE is 500 Hz, which is MIDI 71 -- above
65
+ # it the normalised input exceeds 1.0, a value training never contained.
66
+ # Downward there is no such wall: a low pitch simply normalises small.
67
+ #
68
+ # Drawing out here is out of distribution and will transcribe worse, but it
69
+ # is a usable surface rather than a broken one, and a wide sweep is sometimes
70
+ # what the drawing wants.
71
+ # Extended downward rather than upward. The ceiling is a hard wall -- MIDI 71
72
+ # is 494 Hz and F0_SCALE is 500, so there is almost nothing above it -- while
73
+ # downward a low pitch simply normalises small. Logged drawings sit at a p99
74
+ # of MIDI 58, so headroom above 60 is canvas nobody uses; the room worth
75
+ # having is underneath.
76
+ DRAWABLE_MIDI_LOW = 12 # C0, 16.4 Hz
77
+ DRAWABLE_MIDI_HIGH = 71 # B4, 493.9 Hz
78
+
79
+
80
+ def midi_to_hz(midi: float | np.ndarray) -> np.ndarray:
81
+ return 440.0 * 2.0 ** ((np.asarray(midi, dtype=np.float64) - 69.0) / 12.0)
82
+
83
+
84
+ @dataclass
85
+ class ProsodyFeatures:
86
+ """f0 and intensity on the model's 200 Hz grid.
87
+
88
+ `raw` holds physical units (Hz, dB) for inspection; `normalised` is what
89
+ the model consumes.
90
+ """
91
+
92
+ f0_hz: np.ndarray
93
+ intensity_db: np.ndarray
94
+
95
+ @property
96
+ def duration_s(self) -> float:
97
+ return len(self.f0_hz) / FEATURE_RATE_HZ
98
+
99
+ @property
100
+ def num_frames(self) -> int:
101
+ return len(self.f0_hz)
102
+
103
+ def normalised(self) -> np.ndarray:
104
+ """[T, 2] float32 array scaled exactly as in training."""
105
+ f0 = np.asarray(self.f0_hz, dtype=np.float32) / F0_SCALE
106
+ intensity = np.asarray(self.intensity_db, dtype=np.float32) / INTENSITY_SCALE
107
+ return np.stack([f0, intensity], axis=-1).astype(np.float32)
108
+
109
+ def pressure_to_db(
110
+ pressure: np.ndarray,
111
+ floor_db: float = INTENSITY_FLOOR_DB,
112
+ ceil_db: float = INTENSITY_CEIL_DB,
113
+ ) -> np.ndarray:
114
+ """Map 0..1 stylus pressure onto a speech-like dB SPL range."""
115
+ p = np.clip(np.asarray(pressure, dtype=np.float64), 0.0, 1.0)
116
+ return floor_db + (ceil_db - floor_db) * p
117
+
118
+
119
+ def resample_stroke(
120
+ times_s: np.ndarray,
121
+ values: np.ndarray,
122
+ rate_hz: float = FEATURE_RATE_HZ,
123
+ ) -> tuple[np.ndarray, np.ndarray]:
124
+ """Resample irregular pen samples onto a uniform grid.
125
+
126
+ Tablet events arrive at an irregular rate, so the raw samples cannot be
127
+ used directly: the model assumes a fixed 200 Hz step. Returns the grid
128
+ times and the linearly interpolated values.
129
+ """
130
+ times_s = np.asarray(times_s, dtype=np.float64)
131
+ values = np.asarray(values, dtype=np.float64)
132
+ if times_s.size == 0:
133
+ return np.zeros(0), np.zeros(0)
134
+ if times_s.size == 1:
135
+ return times_s.copy(), values.copy()
136
+
137
+ # Pen events are timestamped by arrival and can repeat or (rarely) go
138
+ # backwards; np.interp needs a strictly increasing x.
139
+ order = np.argsort(times_s, kind="stable")
140
+ times_s, values = times_s[order], values[order]
141
+ keep = np.concatenate(([True], np.diff(times_s) > 0))
142
+ times_s, values = times_s[keep], values[keep]
143
+ if times_s.size == 1:
144
+ return times_s.copy(), values.copy()
145
+
146
+ duration = times_s[-1] - times_s[0]
147
+ n = max(2, int(round(duration * rate_hz)) + 1)
148
+ grid = times_s[0] + np.arange(n) / rate_hz
149
+ # Clamp so the last grid point never extrapolates past the final sample.
150
+ grid = np.minimum(grid, times_s[-1])
151
+ return grid, np.interp(grid, times_s, values)
152
+
153
+
154
+ def smooth(values: np.ndarray, window_frames: int) -> np.ndarray:
155
+ """Moving-average smoothing with edge padding.
156
+
157
+ Drawn lines are geometrically smooth but can still have corners that no
158
+ speech F0 contour would contain. A short smoothing window keeps the
159
+ contour closer to what the model saw in training.
160
+ """
161
+ if window_frames <= 1 or values.size == 0:
162
+ return np.asarray(values, dtype=np.float64)
163
+ window_frames = min(window_frames, values.size)
164
+ kernel = np.ones(window_frames) / window_frames
165
+ pad = window_frames // 2
166
+ padded = np.pad(np.asarray(values, dtype=np.float64), pad, mode="edge")
167
+ out = np.convolve(padded, kernel, mode="same")
168
+ return out[pad : pad + values.size]
169
+
170
+
171
+ def features_from_stroke(
172
+ times_s: np.ndarray,
173
+ midi: np.ndarray,
174
+ pressure: np.ndarray,
175
+ smooth_ms: float = 25.0,
176
+ rate_hz: float = FEATURE_RATE_HZ,
177
+ ) -> ProsodyFeatures:
178
+ """Build 200 Hz prosody features from one pen stroke.
179
+
180
+ `times_s` are event timestamps in seconds, `midi` the pitch under the pen
181
+ (fractional MIDI note), `pressure` the stylus pressure in 0..1.
182
+
183
+ Pitch is read as a literal note and converted to Hz, so the drawing
184
+ surface must already sit in the range speech occupies -- see
185
+ SPEECH_MIDI_LOW/HIGH and the roll bounds the app is built with.
186
+ """
187
+ times_s = np.asarray(times_s, dtype=np.float64)
188
+ midi = np.asarray(midi, dtype=np.float64)
189
+ pressure = np.asarray(pressure, dtype=np.float64)
190
+ if not (times_s.size == midi.size == pressure.size):
191
+ raise ValueError("times, midi and pressure must be the same length")
192
+ if times_s.size == 0:
193
+ return ProsodyFeatures(np.zeros(0, np.float64), np.zeros(0, np.float64))
194
+
195
+ grid, midi_grid = resample_stroke(times_s, midi, rate_hz)
196
+ _, pressure_grid = resample_stroke(times_s, pressure, rate_hz)
197
+ # resample_stroke derives its grid from the data, so both calls agree in
198
+ # length; guard anyway rather than silently mis-aligning the channels.
199
+ n = min(len(midi_grid), len(pressure_grid))
200
+ midi_grid, pressure_grid = midi_grid[:n], pressure_grid[:n]
201
+
202
+ f0_raw = midi_to_hz(midi_grid)
203
+
204
+ window = max(1, int(round(smooth_ms / 1000.0 * rate_hz)))
205
+ f0_hz = smooth(f0_raw, window)
206
+ intensity_db = smooth(pressure_to_db(pressure_grid), window)
207
+
208
+ return ProsodyFeatures(f0_hz=f0_hz, intensity_db=intensity_db)
209
+
210
+
211
+ # Quiet frames around a phrase, so it neither starts nor stops dead.
212
+ #
213
+ # Measured, not guessed: across the templates the quiet before and after the
214
+ # speech has a median of 0 ms and a maximum of 80 ms -- these dataset clips
215
+ # are trimmed tight to the utterance, so training really does start at
216
+ # speech. An earlier 250 ms on each side was 3x the observed maximum and
217
+ # contributed more frames than the drawing itself on a short phrase.
218
+ #
219
+ # 40 ms keeps the onset from being a step discontinuity without displacing
220
+ # content; it sits inside the observed range rather than beyond it.
221
+ LEAD_SILENCE_S = 0.04
222
+ TAIL_SILENCE_S = 0.04
223
+
224
+
225
+ def pad_with_silence(
226
+ features: ProsodyFeatures,
227
+ lead_s: float = LEAD_SILENCE_S,
228
+ tail_s: float = TAIL_SILENCE_S,
229
+ rate_hz: float = FEATURE_RATE_HZ,
230
+ ) -> ProsodyFeatures:
231
+ """Surround a phrase with quiet frames so it neither starts nor stops dead.
232
+
233
+ Pitch is held at the adjacent value rather than zeroed, matching how
234
+ f0_interp behaves through unvoiced regions, and intensity sits at the
235
+ floor.
236
+ """
237
+ if features.num_frames == 0:
238
+ return features
239
+
240
+ lead = max(0, int(round(lead_s * rate_hz)))
241
+ tail = max(0, int(round(tail_s * rate_hz)))
242
+ if not lead and not tail:
243
+ return features
244
+
245
+ f0_parts, db_parts = [], []
246
+ if lead:
247
+ f0_parts.append(np.full(lead, features.f0_hz[0]))
248
+ db_parts.append(np.full(lead, INTENSITY_FLOOR_DB))
249
+ f0_parts.append(features.f0_hz)
250
+ db_parts.append(features.intensity_db)
251
+ if tail:
252
+ f0_parts.append(np.full(tail, features.f0_hz[-1]))
253
+ db_parts.append(np.full(tail, INTENSITY_FLOOR_DB))
254
+
255
+ return ProsodyFeatures(
256
+ f0_hz=np.concatenate(f0_parts),
257
+ intensity_db=np.concatenate(db_parts),
258
+ )
259
+
260
+
261
+ def concatenate(
262
+ features: list[ProsodyFeatures],
263
+ gap_s: float | list[float] = 0.12,
264
+ rate_hz: float = FEATURE_RATE_HZ,
265
+ lead_s: float = LEAD_SILENCE_S,
266
+ tail_s: float = TAIL_SILENCE_S,
267
+ ) -> ProsodyFeatures:
268
+ """Join strokes into one utterance, with a quiet gap between them.
269
+
270
+ Each stroke is a "note"; the gaps are what give the model something it can
271
+ read as separate syllables rather than one continuous tone.
272
+
273
+ `gap_s` may be a single duration or one per gap. Per-gap is what the
274
+ canvas passes: the pen's actual lift time is recorded, so there is no
275
+ reason to substitute a constant for it. A fixed gap also compounds -- at
276
+ 120 ms across the 3-8 strokes a phrase typically has, the inserted silence
277
+ can outweigh the drawing itself.
278
+
279
+ Across a gap the pitch is **interpolated by pYAAPT's own routine**, not
280
+ held and not linearly ramped. The conformer was trained on f0_interp,
281
+ which median filters and fits a shape-preserving PCHIP spline through the
282
+ unvoiced regions; holding the previous value gives a flat shelf then a
283
+ step, and a straight line gives a shape speech never has. Gap frames are
284
+ marked unvoiced (f0 = 0) and handed to interpolate_f0, so they are filled
285
+ the same way training filled them. Intensity drops to the floor, which is
286
+ what makes the gap read as a pause.
287
+ """
288
+ usable = [f for f in features if f.num_frames > 0]
289
+ if not usable:
290
+ return ProsodyFeatures(np.zeros(0, np.float64), np.zeros(0, np.float64))
291
+
292
+ if isinstance(gap_s, (int, float)):
293
+ gaps = [float(gap_s)] * max(0, len(usable) - 1)
294
+ else:
295
+ gaps = [float(g) for g in gap_s]
296
+ if len(gaps) < len(usable) - 1:
297
+ gaps += [0.12] * (len(usable) - 1 - len(gaps))
298
+
299
+ f0_parts: list[np.ndarray] = []
300
+ db_parts: list[np.ndarray] = []
301
+
302
+ for i, feat in enumerate(usable):
303
+ gap_frames = max(0, int(round(gaps[i - 1] * rate_hz))) if i > 0 else 0
304
+ if i > 0 and gap_frames:
305
+ # Zero marks the gap as unvoiced; interpolate_f0 fills it below,
306
+ # exactly as yaapt filled unvoiced regions in training.
307
+ f0_parts.append(np.zeros(gap_frames))
308
+ db_parts.append(np.full(gap_frames, INTENSITY_FLOOR_DB))
309
+ f0_parts.append(np.asarray(feat.f0_hz, dtype=np.float64))
310
+ db_parts.append(np.asarray(feat.intensity_db, dtype=np.float64))
311
+
312
+ joined = ProsodyFeatures(
313
+ f0_hz=interpolate_f0(np.concatenate(f0_parts)),
314
+ intensity_db=np.concatenate(db_parts),
315
+ )
316
+ return pad_with_silence(joined, lead_s, tail_s, rate_hz)