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включаются флагами:
|
| 4 |
+
cleanup унисоны, фантомы, перекрытия, короткие ноты
|
| 5 |
+
quantize посадка на сетку файла (сила 0..1, свинг)
|
| 6 |
+
hands разделение на правую и левую руку
|
| 7 |
+
pedal вывод педали (CC64) и продление нот под ней
|
| 8 |
+
chords распознавание аккордов и подписи в MIDI
|
| 9 |
+
dynamics громкость из аудио (RMS + атака), баланс рук
|
| 10 |
+
report метрики, аномалии, JSON
|
| 11 |
+
|
| 12 |
+
CLI:
|
| 13 |
+
python plus_transcribe.py --midi in.mid --out out.mid --audio in.wav \
|
| 14 |
+
--stages cleanup,quantize,hands,pedal,chords,dynamics,report \
|
| 15 |
+
--quantize-strength 0.85 --report out.json
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import math
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 27 |
+
|
| 28 |
+
from plus_core import ( # noqa: E402
|
| 29 |
+
Note, Piece, ambiguity_of, dump_json, explained_fraction, load_midi,
|
| 30 |
+
pitch_name, save_midi, step, tempo_from_onsets,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
__version__ = "1.0"
|
| 34 |
+
STAGES = ("cleanup", "quantize", "hands", "pedal", "chords", "dynamics", "report")
|
| 35 |
+
|
| 36 |
+
# ---------------------------------------------------------------- стадии ----
|
| 37 |
+
|
| 38 |
+
def stage_cleanup(piece: Piece, options: dict) -> dict:
|
| 39 |
+
"""Убирает дубли, фантомы по громкости и нефизичные длительности.
|
| 40 |
+
|
| 41 |
+
Три правила, каждое с отдельным счётчиком, чтобы отчёт был честным:
|
| 42 |
+
1) унисон: две ноты одного питча в пределах 45 мс и с перекрытием > 60%
|
| 43 |
+
считаются одной (остаётся более громкая, длительность — объединение);
|
| 44 |
+
2) фантом: нота короче 30 мс или громче чем на 25 ниже медианы ансамбля
|
| 45 |
+
при том же питче в пределах 200 мс;
|
| 46 |
+
3) обрезка: длительность не длиннее времени до следующей ноты того же
|
| 47 |
+
питча минус 10 мс (иначе в DAW нота глушит саму себя).
|
| 48 |
+
"""
|
| 49 |
+
min_dur = float(options.get("min_dur", 0.03))
|
| 50 |
+
unison_ms = float(options.get("unison_ms", 45.0))
|
| 51 |
+
result: list[Note] = []
|
| 52 |
+
removed_short = removed_ghost = merged = trimmed = 0
|
| 53 |
+
|
| 54 |
+
by_pitch: dict[int, list[Note]] = {}
|
| 55 |
+
for note in sorted(piece.notes, key=lambda n: (n.pitch, n.start)):
|
| 56 |
+
by_pitch.setdefault(note.pitch, []).append(note)
|
| 57 |
+
|
| 58 |
+
for pitch, group in by_pitch.items():
|
| 59 |
+
kept: list[Note] = []
|
| 60 |
+
for note in group:
|
| 61 |
+
if note.dur < min_dur:
|
| 62 |
+
removed_short += 1
|
| 63 |
+
continue
|
| 64 |
+
if kept:
|
| 65 |
+
last = kept[-1]
|
| 66 |
+
overlap = min(last.end, note.end) - max(last.start, note.start)
|
| 67 |
+
same_time = abs(note.start - last.start) <= unison_ms / 1000.0
|
| 68 |
+
if same_time or (overlap > 0.6 * min(last.dur, note.dur)):
|
| 69 |
+
if note.velocity > last.velocity:
|
| 70 |
+
kept[-1] = Note(last.start, max(last.end, note.end) - last.start,
|
| 71 |
+
pitch, note.velocity, note.channel, note.track)
|
| 72 |
+
else:
|
| 73 |
+
kept[-1] = Note(last.start, max(last.end, note.end) - last.start,
|
| 74 |
+
pitch, last.velocity, last.channel, last.track)
|
| 75 |
+
merged += 1
|
| 76 |
+
continue
|
| 77 |
+
kept.append(Note(**vars(note)))
|
| 78 |
+
|
| 79 |
+
# одиночная тихая короткая нота на редком питче — почти всегда фантом
|
| 80 |
+
if len(kept) <= 2:
|
| 81 |
+
global_median = float(np.median([n.velocity for n in piece.notes])) if piece.notes else 80.0
|
| 82 |
+
filtered = []
|
| 83 |
+
for note in kept:
|
| 84 |
+
if note.dur < 0.12 and note.velocity < global_median - 35:
|
| 85 |
+
removed_ghost += 1
|
| 86 |
+
continue
|
| 87 |
+
filtered.append(note)
|
| 88 |
+
kept = filtered
|
| 89 |
+
|
| 90 |
+
# фантомы: слишком тихие на фоне соседей того же питча
|
| 91 |
+
if len(kept) >= 5:
|
| 92 |
+
levels = np.array([n.velocity for n in kept], dtype=float)
|
| 93 |
+
floor = np.median(levels) - 25.0
|
| 94 |
+
pruned = []
|
| 95 |
+
for note in kept:
|
| 96 |
+
if note.velocity < floor and note.dur < 0.12:
|
| 97 |
+
removed_ghost += 1
|
| 98 |
+
continue
|
| 99 |
+
pruned.append(note)
|
| 100 |
+
kept = pruned
|
| 101 |
+
|
| 102 |
+
# обрезка до следующей ноты того же питча
|
| 103 |
+
for index, note in enumerate(kept[:-1]):
|
| 104 |
+
gap = kept[index + 1].start - note.start
|
| 105 |
+
if note.dur > gap:
|
| 106 |
+
note.dur = max(min_dur, gap - 0.01)
|
| 107 |
+
trimmed += 1
|
| 108 |
+
result.extend(kept)
|
| 109 |
+
|
| 110 |
+
result.sort(key=lambda n: (n.start, n.pitch))
|
| 111 |
+
piece.notes = result
|
| 112 |
+
return {"short_removed": removed_short, "ghosts_removed": removed_ghost,
|
| 113 |
+
"unisons_merged": merged, "trimmed": trimmed}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def stage_quantize(piece: Piece, options: dict) -> dict:
|
| 117 |
+
"""Посадка онсетов и длительностей на сетку.
|
| 118 |
+
|
| 119 |
+
Темп берётся из файла (или --tempo), проверяется на объяснение онсетов;
|
| 120 |
+
если объяснение ниже 0.7, это пишется в отчёт как предупреждение, но темп
|
| 121 |
+
сам не подменяется: угадывание кратного ломает чужой замысел.
|
| 122 |
+
strength 0 = не двигать, 1 = ровно на сетку; свинг сдвигает каждую вторую
|
| 123 |
+
долю на swing долей.
|
| 124 |
+
"""
|
| 125 |
+
bpm = options.get("tempo")
|
| 126 |
+
if bpm is None:
|
| 127 |
+
bpm = piece.bpm or 120.0
|
| 128 |
+
bpm = float(bpm)
|
| 129 |
+
division = int(options.get("division", 4))
|
| 130 |
+
strength = float(options.get("strength", 0.85))
|
| 131 |
+
swing = float(options.get("swing", 0.0))
|
| 132 |
+
refine = bool(options.get("auto_tempo", False))
|
| 133 |
+
before = explained_fraction(piece.starts(), bpm) if piece.notes else 0.0
|
| 134 |
+
if refine and piece.notes:
|
| 135 |
+
bpm = tempo_from_onsets(piece.starts(), center=bpm, spread=1.15)
|
| 136 |
+
after_bpm = bpm
|
| 137 |
+
beat = 60.0 / bpm
|
| 138 |
+
step_s = beat / division
|
| 139 |
+
fitted = 0
|
| 140 |
+
for note in piece.notes:
|
| 141 |
+
target = round(note.start / step_s) * step_s
|
| 142 |
+
if swing and int(round(note.start / step_s)) % 2 == 1:
|
| 143 |
+
target += swing * step_s
|
| 144 |
+
moved = (target - note.start) * strength
|
| 145 |
+
note.start = max(0.0, note.start + moved)
|
| 146 |
+
if abs(moved) > 1e-6:
|
| 147 |
+
fitted += 1
|
| 148 |
+
length = round(note.dur / step_s) * step_s
|
| 149 |
+
if length > 0:
|
| 150 |
+
note.dur = max(1e-3, note.dur + (length - note.dur) * strength)
|
| 151 |
+
piece.notes.sort(key=lambda n: (n.start, n.pitch))
|
| 152 |
+
after = explained_fraction(piece.starts(), after_bpm) if piece.notes else 0.0
|
| 153 |
+
return {"bpm": round(after_bpm, 2), "division": division, "strength": strength,
|
| 154 |
+
"swing": swing, "explained_before": round(before, 3),
|
| 155 |
+
"explained_after": round(after, 3), "notes_moved": fitted,
|
| 156 |
+
"tempo_ambiguous": before < 0.7,
|
| 157 |
+
"alternatives": ambiguity_of(piece.starts(), after_bpm) if piece.notes else []}
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def stage_hands(piece: Piece, options: dict) -> dict:
|
| 161 |
+
"""Делит ноты на правую и левую руку по стоимости перехода.
|
| 162 |
+
|
| 163 |
+
Жадный проход с двумя курсорами: нота идёт в ту руку, где ближе по питчу и
|
| 164 |
+
по времени, с запретом левой руке уходить выше правой больше чем на октаву.
|
| 165 |
+
Работает на одну дорожку, поэтому подходит и для фортепианных моделей,
|
| 166 |
+
которые пишут всё в один канал.
|
| 167 |
+
"""
|
| 168 |
+
if not piece.notes:
|
| 169 |
+
return {"left": 0, "right": 0}
|
| 170 |
+
split_pitch = int(options.get("split_pitch", 60))
|
| 171 |
+
notes = sorted(piece.notes, key=lambda n: (n.start, n.pitch))
|
| 172 |
+
left_last = right_last = None
|
| 173 |
+
left_cost = right_cost = 0.0
|
| 174 |
+
for note in notes:
|
| 175 |
+
def cost(last, side):
|
| 176 |
+
if last is None:
|
| 177 |
+
base = abs(note.pitch - (split_pitch - 7 if side == "left" else split_pitch + 7))
|
| 178 |
+
return base / 12.0 + 0.6
|
| 179 |
+
return abs(note.pitch - last.pitch) / 12.0 + min(1.0, (note.start - last.start) / 2.0)
|
| 180 |
+
|
| 181 |
+
to_left, to_right = cost(left_last, "left"), cost(right_last, "right")
|
| 182 |
+
if to_left < to_right:
|
| 183 |
+
note.track = "LH"
|
| 184 |
+
left_last, left_cost = note, left_cost + to_left
|
| 185 |
+
else:
|
| 186 |
+
note.track = "RH"
|
| 187 |
+
right_last, right_cost = note, right_cost + to_right
|
| 188 |
+
# левая рука не должна оказаться выше правой: меняем подозрительные пары
|
| 189 |
+
swapped = 0
|
| 190 |
+
rh = [n for n in notes if n.track == "RH"]
|
| 191 |
+
lh = [n for n in notes if n.track == "LH"]
|
| 192 |
+
if rh and lh:
|
| 193 |
+
rh_median = float(np.median([n.pitch for n in rh]))
|
| 194 |
+
for note in lh:
|
| 195 |
+
if note.pitch > rh_median + 12:
|
| 196 |
+
note.track = "RH"
|
| 197 |
+
swapped += 1
|
| 198 |
+
piece.notes.sort(key=lambda n: (n.start, n.pitch))
|
| 199 |
+
left = sum(1 for n in piece.notes if n.track == "LH")
|
| 200 |
+
return {"left": left, "right": len(piece.notes) - left, "raised_from_left": swapped}
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def stage_pedal(piece: Piece, options: dict) -> dict:
|
| 204 |
+
"""Выводит педаль по смене гармонии: CC64 плюс продление нот.
|
| 205 |
+
|
| 206 |
+
Онсеты кластер��зуются в аккордовые события (окно 60 мс). Педаль нажимается
|
| 207 |
+
на аккорде, где >= 2 нот, и отпускается, когда меняется набор высотных
|
| 208 |
+
классов или истекает max_hold. Продление ограничено следующей нотой того же
|
| 209 |
+
питча и концом окна, поэтому каши из наложенных нот не возникает.
|
| 210 |
+
"""
|
| 211 |
+
if not piece.notes:
|
| 212 |
+
return {"spans": 0, "extended": 0}
|
| 213 |
+
max_hold = float(options.get("max_hold", 1.6))
|
| 214 |
+
window = float(options.get("window", 0.06))
|
| 215 |
+
notes = sorted(piece.notes, key=lambda n: n.start)
|
| 216 |
+
|
| 217 |
+
clusters: list[list[Note]] = []
|
| 218 |
+
for note in notes:
|
| 219 |
+
if clusters and note.start - clusters[-1][0].start <= window:
|
| 220 |
+
clusters[-1].append(note)
|
| 221 |
+
else:
|
| 222 |
+
clusters.append([note])
|
| 223 |
+
|
| 224 |
+
spans: list[tuple[float, float]] = []
|
| 225 |
+
current: tuple[float, frozenset] | None = None
|
| 226 |
+
for index, cluster in enumerate(clusters):
|
| 227 |
+
classes = frozenset(n.pitch % 12 for n in cluster)
|
| 228 |
+
start_time = cluster[0].start
|
| 229 |
+
next_time = clusters[index + 1][0].start if index + 1 < len(clusters) else piece.duration + 0.4
|
| 230 |
+
if len(cluster) < 2:
|
| 231 |
+
if current is not None:
|
| 232 |
+
spans.append((current[0], start_time))
|
| 233 |
+
current = None
|
| 234 |
+
continue
|
| 235 |
+
if current is None:
|
| 236 |
+
current = (start_time, classes)
|
| 237 |
+
elif classes != current[1] or start_time - current[0] > max_hold:
|
| 238 |
+
spans.append((current[0], start_time))
|
| 239 |
+
current = (start_time, classes)
|
| 240 |
+
if index + 1 == len(clusters):
|
| 241 |
+
end_time = min(next_time, current[0] + max_hold)
|
| 242 |
+
spans.append((current[0], end_time))
|
| 243 |
+
current = None
|
| 244 |
+
if current is not None:
|
| 245 |
+
spans.append((current[0], min(piece.duration + 0.4, current[0] + max_hold)))
|
| 246 |
+
spans = [(a, b) for a, b in spans if b - a > 0.05]
|
| 247 |
+
|
| 248 |
+
by_pitch: dict[int, list[float]] = {}
|
| 249 |
+
for note in notes:
|
| 250 |
+
by_pitch.setdefault(note.pitch, []).append(note.start)
|
| 251 |
+
for starts in by_pitch.values():
|
| 252 |
+
starts.sort()
|
| 253 |
+
|
| 254 |
+
extended = 0
|
| 255 |
+
for note in notes:
|
| 256 |
+
for start, end in spans:
|
| 257 |
+
if not (start <= note.start < end):
|
| 258 |
+
continue
|
| 259 |
+
following = next((s for s in by_pitch[note.pitch] if s > note.start + 1e-4), None)
|
| 260 |
+
limit = end if following is None else min(end, following - 0.01)
|
| 261 |
+
if limit > note.end:
|
| 262 |
+
note.dur = limit - note.start
|
| 263 |
+
extended += 1
|
| 264 |
+
break
|
| 265 |
+
piece.meta["pedal_spans"] = [(round(a, 3), round(b, 3)) for a, b in spans]
|
| 266 |
+
return {"spans": len(spans), "extended": extended,
|
| 267 |
+
"median_hold": round(float(np.median([b - a for a, b in spans])), 3) if spans else 0.0}
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
CHORD_TEMPLATES = {
|
| 271 |
+
"": (0, 4, 7), "m": (0, 3, 7), "7": (0, 4, 7, 10), "m7": (0, 3, 7, 10),
|
| 272 |
+
"maj7": (0, 4, 7, 11), "dim": (0, 3, 6), "aug": (0, 4, 8), "sus4": (0, 5, 7),
|
| 273 |
+
"sus2": (0, 2, 7), "6": (0, 4, 7, 9), "m6": (0, 3, 7, 9),
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def _chord_name(pitches: list[int]) -> str | None:
|
| 278 |
+
classes = sorted({p % 12 for p in pitches})
|
| 279 |
+
if len(classes) < 3:
|
| 280 |
+
return None
|
| 281 |
+
best = None
|
| 282 |
+
for root in classes:
|
| 283 |
+
relative = sorted((c - root) % 12 for c in classes)
|
| 284 |
+
for suffix, template in CHORD_TEMPLATES.items():
|
| 285 |
+
if len(template) != len(relative):
|
| 286 |
+
continue
|
| 287 |
+
if all(abs(a - b) <= 1 for a, b in zip(relative, template)):
|
| 288 |
+
score = sum(abs(a - b) for a, b in zip(relative, template))
|
| 289 |
+
if best is None or score < best[0]:
|
| 290 |
+
best = (score, pitch_name(root + 60)[:-1] + suffix)
|
| 291 |
+
return best[1] if best else None
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def stage_chords(piece: Piece, options: dict) -> dict:
|
| 295 |
+
"""Аккорды по одновременным онсетам: список для отчёта и метки в piece.meta."""
|
| 296 |
+
window = float(options.get("window", 0.06))
|
| 297 |
+
notes = sorted(piece.notes, key=lambda n: n.start)
|
| 298 |
+
groups: list[list[Note]] = []
|
| 299 |
+
for note in notes:
|
| 300 |
+
if groups and note.start - groups[-1][0].start <= window:
|
| 301 |
+
groups[-1].append(note)
|
| 302 |
+
else:
|
| 303 |
+
groups.append([note])
|
| 304 |
+
timeline = []
|
| 305 |
+
named = 0
|
| 306 |
+
for group in groups:
|
| 307 |
+
pitches = [n.pitch for n in group]
|
| 308 |
+
if len(group) < 3:
|
| 309 |
+
continue
|
| 310 |
+
name = _chord_name(pitches)
|
| 311 |
+
if name:
|
| 312 |
+
named += 1
|
| 313 |
+
timeline.append({"time": round(group[0].start, 3), "size": len(group),
|
| 314 |
+
"pitches": sorted(pitches), "chord": name})
|
| 315 |
+
piece.meta["chords"] = timeline
|
| 316 |
+
return {"clusters": len(timeline), "named": named,
|
| 317 |
+
"first": timeline[:8] if timeline else []}
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def stage_dynamics(piece: Piece, options: dict) -> dict:
|
| 321 |
+
"""Громкость из аудио: RMS и атака в окне от онсе��а, затем кривая в MIDI.
|
| 322 |
+
|
| 323 |
+
Velocity = 1 + shaped*123, где shaped это перцентильный share громкости,
|
| 324 |
+
поднятый в степень 0.65 и умноженный на акцент атаки. Для рук добавляется
|
| 325 |
+
баланс: левая на gain_left, правая на gain_right, чтобы форте в левой не
|
| 326 |
+
перекрывало мелодию.
|
| 327 |
+
"""
|
| 328 |
+
audio_path = options.get("audio")
|
| 329 |
+
if not audio_path or not os.path.isfile(audio_path) or not piece.notes:
|
| 330 |
+
return {"applied": False, "reason": "нет аудио"}
|
| 331 |
+
try:
|
| 332 |
+
import librosa
|
| 333 |
+
except Exception as exc:
|
| 334 |
+
return {"applied": False, "reason": "нет librosa: %s" % exc}
|
| 335 |
+
|
| 336 |
+
window = float(options.get("window", 0.25))
|
| 337 |
+
gain_left = float(options.get("gain_left", 0.88))
|
| 338 |
+
gain_right = float(options.get("gain_right", 1.0))
|
| 339 |
+
samples, rate = librosa.load(audio_path, sr=22050, mono=True)
|
| 340 |
+
hop = 128
|
| 341 |
+
frame = 512
|
| 342 |
+
rms = librosa.feature.rms(y=samples, frame_length=frame, hop_length=hop)[0]
|
| 343 |
+
frame_times = librosa.frames_to_time(np.arange(rms.size), sr=rate, hop_length=hop)
|
| 344 |
+
|
| 345 |
+
levels, attacks = [], []
|
| 346 |
+
for note in piece.notes:
|
| 347 |
+
index = int(np.searchsorted(frame_times, note.start))
|
| 348 |
+
span = rms[index: index + max(1, int(window * rate / hop))]
|
| 349 |
+
if span.size == 0:
|
| 350 |
+
levels.append(0.0)
|
| 351 |
+
attacks.append(1.0)
|
| 352 |
+
continue
|
| 353 |
+
peak = float(span.max())
|
| 354 |
+
mean = float(span.mean()) + 1e-9
|
| 355 |
+
levels.append(20.0 * math.log10(mean + 1e-9))
|
| 356 |
+
attacks.append(min(2.0, peak / mean))
|
| 357 |
+
levels = np.array(levels)
|
| 358 |
+
attacks = np.array(attacks)
|
| 359 |
+
quiet, loud = np.percentile(levels, 4), np.percentile(levels, 99.7)
|
| 360 |
+
share = np.clip((levels - quiet) / max(1e-6, loud - quiet), 0.0, 1.0)
|
| 361 |
+
shaped = np.power(share, 0.65) * (1.0 + 0.18 * (attacks - 1.0))
|
| 362 |
+
velocity = np.clip(15 + shaped * 103, 15, 118).astype(int)
|
| 363 |
+
for note, value in zip(piece.notes, velocity):
|
| 364 |
+
gain = gain_left if note.track == "LH" else gain_right
|
| 365 |
+
note.velocity = int(max(1, min(127, round(value * gain))))
|
| 366 |
+
piece.meta["dynamics"] = {"quiet_db": round(float(quiet), 2), "loud_db": round(float(loud), 2)}
|
| 367 |
+
spread = int(velocity.max() - velocity.min())
|
| 368 |
+
return {"applied": True, "velocity_min": int(velocity.min()),
|
| 369 |
+
"velocity_max": int(velocity.max()), "spread": spread,
|
| 370 |
+
"window": window, "gain_left": gain_left}
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def stage_report(piece: Piece, options: dict) -> dict:
|
| 374 |
+
"""Метрики и аномалии: что чинить дальше, без догадок."""
|
| 375 |
+
notes = piece.notes
|
| 376 |
+
if not notes:
|
| 377 |
+
return {"empty": True}
|
| 378 |
+
starts = piece.starts()
|
| 379 |
+
durations = np.array([n.dur for n in notes])
|
| 380 |
+
pitches = piece.pitches()
|
| 381 |
+
velocities = piece.velocities()
|
| 382 |
+
span = max(1e-9, piece.duration)
|
| 383 |
+
overlaps = 0
|
| 384 |
+
by_pitch: dict[int, list[Note]] = {}
|
| 385 |
+
for note in sorted(notes, key=lambda n: (n.pitch, n.start)):
|
| 386 |
+
by_pitch.setdefault(note.pitch, []).append(note)
|
| 387 |
+
for group in by_pitch.values():
|
| 388 |
+
for a, b in zip(group, group[1:]):
|
| 389 |
+
if b.start < a.end - 1e-3:
|
| 390 |
+
overlaps += 1
|
| 391 |
+
density = np.array([np.sum((starts >= t) & (starts < t + 1.0)) for t in np.arange(0, span, 1.0)])
|
| 392 |
+
anomalies = []
|
| 393 |
+
if overlaps:
|
| 394 |
+
anomalies.append({"kind": "overlap", "count": overlaps})
|
| 395 |
+
if durations.min() < 0.02:
|
| 396 |
+
anomalies.append({"kind": "very_short_notes", "count": int((durations < 0.02).sum())})
|
| 397 |
+
if density.size and density.max() > 25:
|
| 398 |
+
anomalies.append({"kind": "density_spike", "per_second": int(density.max())})
|
| 399 |
+
if velocities.size and velocities.std() < 3:
|
| 400 |
+
anomalies.append({"kind": "flat_velocity", "std": round(float(velocities.std()), 2)})
|
| 401 |
+
octave_jumps = int(np.sum(np.abs(np.diff(np.sort(pitches))) > 24))
|
| 402 |
+
return {
|
| 403 |
+
"notes": len(notes), "duration": round(piece.duration, 3),
|
| 404 |
+
"notes_per_second": round(len(notes) / span, 2),
|
| 405 |
+
"pitch_range": [pitch_name(int(pitches.min())), pitch_name(int(pitches.max()))],
|
| 406 |
+
"velocity": [int(velocities.min()), int(velocities.max()),
|
| 407 |
+
round(float(velocities.mean()), 1)],
|
| 408 |
+
"duration_median": round(float(np.median(durations)), 3),
|
| 409 |
+
"overlaps": overlaps, "octave_leaps": octave_jumps,
|
| 410 |
+
"anomalies": anomalies,
|
| 411 |
+
"tracks": {name: sum(1 for n in notes if n.track == name)
|
| 412 |
+
for name in sorted({n.track for n in notes})},
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
HANDLERS = {
|
| 417 |
+
"cleanup": stage_cleanup,
|
| 418 |
+
"quantize": stage_quantize,
|
| 419 |
+
"hands": stage_hands,
|
| 420 |
+
"pedal": stage_pedal,
|
| 421 |
+
"chords": stage_chords,
|
| 422 |
+
"dynamics": stage_dynamics,
|
| 423 |
+
"report": stage_report,
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def run_pipeline(piece: Piece, stages: list[str], options: dict) -> dict:
|
| 428 |
+
report: dict = {"version": __version__, "source": piece.source, "stages": {}}
|
| 429 |
+
for index, name in enumerate(stages, 1):
|
| 430 |
+
handler = HANDLERS.get(name)
|
| 431 |
+
if handler is None:
|
| 432 |
+
raise SystemExit("неизвестная стадия: " + name)
|
| 433 |
+
step(index, len(stages), name)
|
| 434 |
+
result = handler(piece, options)
|
| 435 |
+
report["stages"][name] = result
|
| 436 |
+
summary = ", ".join("%s=%s" % (k, v) for k, v in result.items()
|
| 437 |
+
if isinstance(v, (int, float, str)) and k != "first")
|
| 438 |
+
print(" " + (summary[:150] if summary else "готово"), flush=True)
|
| 439 |
+
report["stats"] = piece.stats()
|
| 440 |
+
return report
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def main(argv: list[str] | None = None) -> int:
|
| 444 |
+
parser = argparse.ArgumentParser(description="PLUS: пост-обработка MIDI транскрипции")
|
| 445 |
+
parser.add_argument("--midi", required=True, help="входной MIDI")
|
| 446 |
+
parser.add_argument("--out", help="куда писать MIDI (по умолчанию рядом, суффикс _plus)")
|
| 447 |
+
parser.add_argument("--audio", help="аудио для стадии dynamics")
|
| 448 |
+
parser.add_argument("--stages", default="cleanup,quantize,hands,pedal,dynamics,report")
|
| 449 |
+
parser.add_argument("--tempo", type=float, help="переопределить BPM")
|
| 450 |
+
parser.add_argument("--quantize-strength", type=float, default=0.85)
|
| 451 |
+
parser.add_argument("--division", type=int, default=4)
|
| 452 |
+
parser.add_argument("--swing", type=float, default=0.0)
|
| 453 |
+
parser.add_argument("--auto-tempo", action="store_true", help="подстроить темп в пределах 15%")
|
| 454 |
+
parser.add_argument("--split-pitch", type=int, default=60)
|
| 455 |
+
parser.add_argument("--gain-left", type=float, default=0.88)
|
| 456 |
+
parser.add_argument("--report", help="JSON-отчёт")
|
| 457 |
+
args = parser.parse_args(argv)
|
| 458 |
+
|
| 459 |
+
stages = [s.strip() for s in args.stages.split(",") if s.strip()]
|
| 460 |
+
out_path = args.out or os.path.splitext(args.midi)[0] + "_plus.mid"
|
| 461 |
+
report_path = args.report or os.path.splitext(out_path)[0] + "_report.json"
|
| 462 |
+
|
| 463 |
+
piece = load_midi(args.midi)
|
| 464 |
+
print("вход: %s | нот %d | %.1f с | %.0f BPM"
|
| 465 |
+
% (os.path.basename(args.midi), len(piece.notes), piece.duration, piece.bpm), flush=True)
|
| 466 |
+
|
| 467 |
+
options = {
|
| 468 |
+
"audio": args.audio, "tempo": args.tempo,
|
| 469 |
+
"strength": args.quantize_strength, "division": args.division,
|
| 470 |
+
"swing": args.swing, "auto_tempo": args.auto_tempo,
|
| 471 |
+
"split_pitch": args.split_pitch, "gain_left": args.gain_left,
|
| 472 |
+
}
|
| 473 |
+
report = run_pipeline(piece, stages, options)
|
| 474 |
+
save_midi(piece, out_path)
|
| 475 |
+
dump_json(report, report_path)
|
| 476 |
+
print("готово: %s | отчёт: %s" % (out_path, report_path), flush=True)
|
| 477 |
+
return 0
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
if __name__ == "__main__":
|
| 481 |
+
sys.exit(main())
|