Commit ·
8ea9334
1
Parent(s): a9b4950
PLUS: артикуляция (легато/стакато) и измеренные концы нот
Browse files- plus/articulation.py +171 -0
plus/articulation.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Артикуляция: настоящий конец ноты и легато/стакато вместо условных длительностей.
|
| 2 |
+
|
| 3 |
+
Модель даёт онсет и грубый конец. Для профессионального звучания нужно другое:
|
| 4 |
+
конец берётся из записи (где реально упала энергия), а артикуляция — из
|
| 5 |
+
отношения длительности к паузе до следующей ноты того же голоса.
|
| 6 |
+
|
| 7 |
+
Термины:
|
| 8 |
+
legato — нота дожимается до следующего онсета (пауза ≤ 30 мс);
|
| 9 |
+
portato — пауза 30..150 мс, конец по записи;
|
| 10 |
+
staccato — нота короче половины шага, конец обрезается по записи (не более 60% шага);
|
| 11 |
+
tenuto — пауза больше половины шага, конец по записи.
|
| 12 |
+
|
| 13 |
+
Звук не синтезируется заново: меняются только начала/концы нот, высоты и
|
| 14 |
+
инструменты остаются модельные.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
|
| 20 |
+
import numpy
|
| 21 |
+
|
| 22 |
+
FLOOR_DB = 14.0 # насколько энергия должна упасть от пика, чтобы считать ноту законченной
|
| 23 |
+
FRAME = 0.010 # 10 мс
|
| 24 |
+
LEGATO_GAP = 0.030
|
| 25 |
+
PORTATO_GAP = 0.150
|
| 26 |
+
STACCATO_SHARE = 0.60
|
| 27 |
+
MAX_TAIL = 6.0
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def envelope(audio_path, frame=FRAME):
|
| 31 |
+
"""RMS-огибающая записи по кадрам."""
|
| 32 |
+
import velocity
|
| 33 |
+
samples, rate = velocity.decode_audio(audio_path)
|
| 34 |
+
step = max(16, int(frame * rate))
|
| 35 |
+
count = max(1, len(samples) // step)
|
| 36 |
+
trimmed = samples[:count * step].reshape(count, step).astype("float64")
|
| 37 |
+
rms = numpy.sqrt(numpy.mean(trimmed ** 2, axis=1) + 1e-20)
|
| 38 |
+
return 20.0 * numpy.log10(rms + 1e-12), frame
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def band_end(segment, rate, midi, hop=0.010, win=None, drop_db=18.0):
|
| 42 |
+
"""Конец ноты по спаду энергии в полосе её основного тона."""
|
| 43 |
+
f0 = 440.0 * 2 ** ((midi - 69) / 12.0)
|
| 44 |
+
if win is None:
|
| 45 |
+
win = min(0.25, max(0.040, 6.0 / f0)) # 41 Гц требует ~0.15 с
|
| 46 |
+
low, high = f0 * 0.92, f0 * 1.08
|
| 47 |
+
hop_n, win_n = int(hop * rate), max(256, int(win * rate))
|
| 48 |
+
if len(segment) < win_n:
|
| 49 |
+
return None
|
| 50 |
+
frames = 1 + (len(segment) - win_n) // hop_n
|
| 51 |
+
if frames < 3:
|
| 52 |
+
return None
|
| 53 |
+
window = numpy.hanning(win_n)
|
| 54 |
+
band = numpy.zeros(frames)
|
| 55 |
+
freqs = numpy.fft.rfftfreq(win_n, 1.0 / rate)
|
| 56 |
+
mask = (freqs >= low) & (freqs <= high)
|
| 57 |
+
if not mask.any():
|
| 58 |
+
return None
|
| 59 |
+
for index in range(frames):
|
| 60 |
+
piece = segment[index * hop_n:index * hop_n + win_n] * window
|
| 61 |
+
spectrum = numpy.abs(numpy.fft.rfft(piece))
|
| 62 |
+
band[index] = spectrum[mask].sum()
|
| 63 |
+
if band.max() <= 0:
|
| 64 |
+
return None
|
| 65 |
+
peak = int(numpy.argmax(band))
|
| 66 |
+
threshold = band[peak] * (10 ** (-drop_db / 20.0))
|
| 67 |
+
for index in range(peak + 1, frames):
|
| 68 |
+
if band[index] <= threshold:
|
| 69 |
+
return (index + 1) * hop
|
| 70 |
+
return frames * hop
|
| 71 |
+
|
| 72 |
+
def measure_end(note, env, next_start=None, frame=FRAME):
|
| 73 |
+
"""Конец по падению энергии от пика, но не дальше следующей ноты."""
|
| 74 |
+
levels, _ = env
|
| 75 |
+
start = max(0, int(note["start"] / frame))
|
| 76 |
+
if start >= len(levels):
|
| 77 |
+
return None
|
| 78 |
+
limit = len(levels)
|
| 79 |
+
if next_start is not None:
|
| 80 |
+
limit = min(limit, max(start + 1, int(next_start / frame)))
|
| 81 |
+
else:
|
| 82 |
+
limit = min(limit, start + int(MAX_TAIL / frame))
|
| 83 |
+
window = levels[start:limit]
|
| 84 |
+
if not len(window):
|
| 85 |
+
return None
|
| 86 |
+
peak_index = int(numpy.argmax(window))
|
| 87 |
+
peak = window[peak_index]
|
| 88 |
+
threshold = peak - FLOOR_DB
|
| 89 |
+
end_index = len(window) - 1
|
| 90 |
+
for offset in range(peak_index + 1, len(window)):
|
| 91 |
+
if window[offset] <= threshold:
|
| 92 |
+
end_index = offset
|
| 93 |
+
break
|
| 94 |
+
return (start + end_index + 1) * frame
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def refine(notes, audio_path, min_duration=0.045):
|
| 98 |
+
"""Пересчитать концы и расставить артикуляцию. Возвращает (notes, stats)."""
|
| 99 |
+
env = envelope(audio_path)
|
| 100 |
+
import velocity
|
| 101 |
+
segments, rate = velocity.decode_audio(audio_path)
|
| 102 |
+
by_voice = defaultdict(list)
|
| 103 |
+
for note in notes:
|
| 104 |
+
by_voice[note.get("instrument", "?")].append(note)
|
| 105 |
+
for voice in by_voice.values():
|
| 106 |
+
voice.sort(key=lambda n: n["start"])
|
| 107 |
+
|
| 108 |
+
counts = defaultdict(int)
|
| 109 |
+
for voice in by_voice.values():
|
| 110 |
+
onsets = []
|
| 111 |
+
for note in voice: # аккорд = один онсет, а не очередь нот
|
| 112 |
+
if not onsets or note["start"] - onsets[-1] > 0.030:
|
| 113 |
+
onsets.append(note["start"])
|
| 114 |
+
for index, note in enumerate(voice):
|
| 115 |
+
later = [o for o in onsets if o > note["start"] + 0.030]
|
| 116 |
+
next_start = later[0] if later else None
|
| 117 |
+
nominal = note.get("end", note["start"] + 0.1)
|
| 118 |
+
measured = None
|
| 119 |
+
if segments is not None and len(segments):
|
| 120 |
+
start_n = max(0, int(note["start"] * rate))
|
| 121 |
+
cap = next_start if next_start is not None else note["start"] + MAX_TAIL
|
| 122 |
+
pad = 0.0 if next_start is not None else 0.2
|
| 123 |
+
stop_n = min(len(segments), int(cap * rate) + int(pad * rate))
|
| 124 |
+
piece = segments[start_n:stop_n]
|
| 125 |
+
if len(piece) > 64:
|
| 126 |
+
tail = band_end(piece, rate, note["pitch"])
|
| 127 |
+
if tail:
|
| 128 |
+
measured = note["start"] + tail
|
| 129 |
+
if measured is None:
|
| 130 |
+
measured = measure_end(note, env, next_start)
|
| 131 |
+
nominal_len = nominal - note["start"]
|
| 132 |
+
if measured is not None and nominal_len > 0.02:
|
| 133 |
+
if (measured - note["start"]) < 0.5 * nominal_len:
|
| 134 |
+
measured = None # явно недомер, верим модели
|
| 135 |
+
elif next_start is not None and measured > next_start:
|
| 136 |
+
measured = next_start
|
| 137 |
+
end = measured if measured is not None else nominal
|
| 138 |
+
end = max(end, note["start"] + min_duration)
|
| 139 |
+
note["measured_end"] = round(end, 3)
|
| 140 |
+
|
| 141 |
+
step = (next_start - note["start"]) if next_start else None
|
| 142 |
+
gap = (next_start - end) if next_start else None
|
| 143 |
+
|
| 144 |
+
if step is None:
|
| 145 |
+
note["articulation"] = "natural"
|
| 146 |
+
elif gap is not None and gap <= LEGATO_GAP:
|
| 147 |
+
note["articulation"] = "legato"
|
| 148 |
+
end = next_start - 0.005
|
| 149 |
+
elif step and (end - note["start"]) >= 0.9 * step:
|
| 150 |
+
note["articulation"] = "tenuto"
|
| 151 |
+
elif gap is not None and gap > 0.5 * step:
|
| 152 |
+
note["articulation"] = "staccato"
|
| 153 |
+
end = note["start"] + max(min_duration, min(end - note["start"],
|
| 154 |
+
STACCATO_SHARE * step))
|
| 155 |
+
else:
|
| 156 |
+
note["articulation"] = "portato"
|
| 157 |
+
counts[note["articulation"]] += 1
|
| 158 |
+
note["end"] = round(max(end, note["start"] + min_duration), 3)
|
| 159 |
+
|
| 160 |
+
stats = {
|
| 161 |
+
"notes": len(notes),
|
| 162 |
+
"legato": counts.get("legato", 0),
|
| 163 |
+
"portato": counts.get("portato", 0),
|
| 164 |
+
"staccato": counts.get("staccato", 0),
|
| 165 |
+
"tenuto": counts.get("tenuto", 0),
|
| 166 |
+
}
|
| 167 |
+
if notes:
|
| 168 |
+
lengths = [n["end"] - n["start"] for n in notes]
|
| 169 |
+
stats["median_length"] = round(float(numpy.median(lengths)), 3)
|
| 170 |
+
stats["mean_length"] = round(float(numpy.mean(lengths)), 3)
|
| 171 |
+
return notes, stats
|