hinase-toki 14.2.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. hinase_toki/__init__.py +89 -0
  2. hinase_toki/_audio.py +159 -0
  3. hinase_toki/_curves.py +313 -0
  4. hinase_toki/_lanes.py +70 -0
  5. hinase_toki/_pitch.py +229 -0
  6. hinase_toki/_project.py +101 -0
  7. hinase_toki/_render.py +135 -0
  8. hinase_toki/_repredict.py +72 -0
  9. hinase_toki/_score.py +189 -0
  10. hinase_toki/_score_io.py +77 -0
  11. hinase_toki/_session.py +90 -0
  12. hinase_toki/_text.py +181 -0
  13. hinase_toki/_types.py +66 -0
  14. hinase_toki/_ustx.py +212 -0
  15. hinase_toki/_version.py +24 -0
  16. hinase_toki/_voice.py +368 -0
  17. hinase_toki/cli.py +220 -0
  18. hinase_toki/data/dictionary-ja.txt +268 -0
  19. hinase_toki/errors.py +45 -0
  20. hinase_toki/export.py +85 -0
  21. hinase_toki/hub.py +78 -0
  22. hinase_toki/options.py +87 -0
  23. hinase_toki/plan.py +268 -0
  24. hinase_toki/py.typed +0 -0
  25. hinase_toki/rules.py +134 -0
  26. hinase_toki/score.py +350 -0
  27. hinase_toki/song/__init__.py +13 -0
  28. hinase_toki/song/_align.py +340 -0
  29. hinase_toki/song/_band_flourish.py +213 -0
  30. hinase_toki/song/_band_layers.py +185 -0
  31. hinase_toki/song/_band_reading.py +163 -0
  32. hinase_toki/song/_en.py +104 -0
  33. hinase_toki/song/_fingerprint.py +14 -0
  34. hinase_toki/song/_ja.py +201 -0
  35. hinase_toki/song/_ko.py +118 -0
  36. hinase_toki/song/_lang.py +161 -0
  37. hinase_toki/song/_midi.py +150 -0
  38. hinase_toki/song/_midi_lines.py +153 -0
  39. hinase_toki/song/_paths.py +50 -0
  40. hinase_toki/song/_run_finish.py +130 -0
  41. hinase_toki/song/_run_prepare.py +69 -0
  42. hinase_toki/song/_run_report.py +177 -0
  43. hinase_toki/song/_run_steps.py +125 -0
  44. hinase_toki/song/_runner_mix.py +153 -0
  45. hinase_toki/song/_runner_prepare.py +181 -0
  46. hinase_toki/song/_vocal_chain.py +134 -0
  47. hinase_toki/song/arrange.py +84 -0
  48. hinase_toki/song/assemble.py +297 -0
  49. hinase_toki/song/auto_melody.py +133 -0
  50. hinase_toki/song/backing_mix.py +380 -0
  51. hinase_toki/song/band.py +269 -0
  52. hinase_toki/song/band_mix.py +290 -0
  53. hinase_toki/song/compare.py +158 -0
  54. hinase_toki/song/corrector.py +400 -0
  55. hinase_toki/song/harmony.py +70 -0
  56. hinase_toki/song/harmony_part.py +71 -0
  57. hinase_toki/song/hooks.py +14 -0
  58. hinase_toki/song/judge.py +337 -0
  59. hinase_toki/song/listen.py +185 -0
  60. hinase_toki/song/master.py +126 -0
  61. hinase_toki/song/measure.py +134 -0
  62. hinase_toki/song/midi_cover.py +267 -0
  63. hinase_toki/song/mix.py +186 -0
  64. hinase_toki/song/natural.py +139 -0
  65. hinase_toki/song/parts.py +215 -0
  66. hinase_toki/song/piano_band.py +357 -0
  67. hinase_toki/song/post.py +248 -0
  68. hinase_toki/song/reference.py +197 -0
  69. hinase_toki/song/run.py +390 -0
  70. hinase_toki/song/runner.py +327 -0
  71. hinase_toki/song/score.py +169 -0
  72. hinase_toki/song/score_check.py +71 -0
  73. hinase_toki/song/score_rules.py +23 -0
  74. hinase_toki/song/search.py +246 -0
  75. hinase_toki/song/sing_exact.py +302 -0
  76. hinase_toki/song/spec.py +331 -0
  77. hinase_toki/song/state.py +33 -0
  78. hinase_toki/song/style.py +210 -0
  79. hinase_toki/song/takes.py +164 -0
  80. hinase_toki/song/tidy.py +122 -0
  81. hinase_toki/song/ust_score.py +365 -0
  82. hinase_toki/voice.py +321 -0
  83. hinase_toki-14.2.2.dist-info/METADATA +132 -0
  84. hinase_toki-14.2.2.dist-info/RECORD +87 -0
  85. hinase_toki-14.2.2.dist-info/WHEEL +4 -0
  86. hinase_toki-14.2.2.dist-info/entry_points.txt +2 -0
  87. hinase_toki-14.2.2.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,89 @@
1
+ """Hinase Toki: a Japanese singing voice.
2
+
3
+ >>> import hinase_toki as toki
4
+ >>> voice = toki.load("toki-1.4") # doctest: +SKIP
5
+ >>> voice.sing(toki.Score.load("score.txt")).save("vocal.wav") # doctest: +SKIP
6
+
7
+ Importing the package does not load onnxruntime; the first :func:`load` does.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import importlib
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ __all__ = [
16
+ "OFF",
17
+ "PhrasePlan",
18
+ "Plan",
19
+ "DownloadError",
20
+ "LyricError",
21
+ "MissingExtra",
22
+ "Curve",
23
+ "Note",
24
+ "Score",
25
+ "ScoreError",
26
+ "SingOptions",
27
+ "Song",
28
+ "TokiError",
29
+ "UnsupportedControl",
30
+ "Voice",
31
+ "VoiceInfo",
32
+ "VoiceNotFound",
33
+ "__version__",
34
+ "load",
35
+ ]
36
+
37
+ _WHERE = {
38
+ "OFF": "options",
39
+ "Plan": "plan",
40
+ "PhrasePlan": "plan",
41
+ "SingOptions": "options",
42
+ "Curve": "score",
43
+ "Note": "score",
44
+ "Score": "score",
45
+ "Song": "voice",
46
+ "Voice": "voice",
47
+ "VoiceInfo": "voice",
48
+ "load": "voice",
49
+ "DownloadError": "errors",
50
+ "LyricError": "errors",
51
+ "MissingExtra": "errors",
52
+ "ScoreError": "errors",
53
+ "TokiError": "errors",
54
+ "UnsupportedControl": "errors",
55
+ "VoiceNotFound": "errors",
56
+ }
57
+
58
+ if TYPE_CHECKING:
59
+ from .errors import (
60
+ DownloadError,
61
+ LyricError,
62
+ MissingExtra,
63
+ ScoreError,
64
+ TokiError,
65
+ UnsupportedControl,
66
+ VoiceNotFound,
67
+ )
68
+ from .options import OFF, SingOptions
69
+ from .plan import PhrasePlan, Plan
70
+ from .score import Curve, Note, Score
71
+ from .voice import Song, Voice, VoiceInfo, load
72
+
73
+
74
+ def __getattr__(name: str) -> Any:
75
+ if name == "__version__":
76
+ try:
77
+ from ._version import __version__ as v
78
+ except ImportError: # a source checkout without a build
79
+ v = "0.0.0"
80
+ return v
81
+ if name in _WHERE:
82
+ value = getattr(importlib.import_module(f".{_WHERE[name]}", __name__), name)
83
+ globals()[name] = value
84
+ return value
85
+ raise AttributeError(f"module 'hinase_toki' has no attribute {name!r}")
86
+
87
+
88
+ def __dir__() -> list[str]:
89
+ return sorted(__all__)
hinase_toki/_audio.py ADDED
@@ -0,0 +1,159 @@
1
+ """WAV input/output and note names (standard library + numpy)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+ import warnings
9
+ import wave
10
+ from math import gcd
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import numpy as np
15
+ import numpy.typing as npt
16
+
17
+ SR = 44100
18
+ HOP = 512
19
+ FT = HOP / SR # seconds per frame
20
+
21
+ Array = npt.NDArray[Any]
22
+
23
+ NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
24
+ _NOTE_RE = re.compile(r"^([A-Ga-g])([#b]?)(-?\d+)$")
25
+ _SEMI = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
26
+
27
+
28
+ def note_to_midi(name: str) -> int:
29
+ """`"A4"` -> 69. Raises ValueError for anything else."""
30
+ m = _NOTE_RE.match(name.strip())
31
+ if not m:
32
+ raise ValueError(f"bad note name: {name!r}")
33
+ letter, acc, octave = m.groups()
34
+ semi = _SEMI[letter.upper()] + (1 if acc == "#" else -1 if acc == "b" else 0)
35
+ return (int(octave) + 1) * 12 + semi
36
+
37
+
38
+ def midi_to_note(midi: int) -> str:
39
+ """69 -> `"A4"`."""
40
+ return f"{NOTE_NAMES[midi % 12]}{midi // 12 - 1}"
41
+
42
+
43
+ def read_wav(path: str | Path) -> tuple[Array, int]:
44
+ """Mono float [-1, 1] and sample rate; 16/24/32-bit PCM, any channel count."""
45
+ y, sr = read_wav_channels(path)
46
+ return (y.mean(axis=1) if y.shape[1] > 1 else y[:, 0]), sr
47
+
48
+
49
+ def read_wav_channels(path: str | Path) -> tuple[Array, int]:
50
+ """Float [-1, 1] as (samples, channels) and sample rate; 16/24/32-bit PCM."""
51
+ with wave.open(str(path)) as w:
52
+ ch, sw, sr, n = w.getnchannels(), w.getsampwidth(), w.getframerate(), w.getnframes()
53
+ raw = w.readframes(n)
54
+ if sw == 2:
55
+ y = np.frombuffer(raw, "<i2").astype(np.float64) / 32768
56
+ elif sw == 3:
57
+ b = np.frombuffer(raw, np.uint8).reshape(-1, 3)
58
+ y = (
59
+ (b[:, 0].astype(np.int32) | (b[:, 1].astype(np.int32) << 8) | (b[:, 2].astype(np.int32) << 16)) << 8 >> 8
60
+ ).astype(np.float64) / 8388608
61
+ elif sw == 4:
62
+ y = np.frombuffer(raw, "<i4").astype(np.float64) / 2147483648
63
+ else:
64
+ raise ValueError(f"{path}: unsupported sample width {sw}")
65
+ return y.reshape(-1, ch), sr
66
+
67
+
68
+ def write_wav(path: str | Path, y: Array, sr: int = SR) -> Path:
69
+ """16-bit mono, clipped to [-1, 1]."""
70
+ out = Path(path)
71
+ out.parent.mkdir(parents=True, exist_ok=True)
72
+ with wave.open(str(out), "wb") as w:
73
+ w.setnchannels(1)
74
+ w.setsampwidth(2)
75
+ w.setframerate(sr)
76
+ w.writeframes((np.clip(y, -1, 1) * 32767).astype("<i2").tobytes())
77
+ return out
78
+
79
+
80
+ def midi_to_hz(midi: Any) -> Array:
81
+ """MIDI number(s) -> Hz."""
82
+ return 440.0 * 2.0 ** ((np.asarray(midi, dtype=float) - 69) / 12.0)
83
+
84
+
85
+ def resample(y: Array, sr: int, target: int = SR) -> Array:
86
+ if sr == target:
87
+ return y
88
+ from scipy.signal import resample_poly
89
+
90
+ g = gcd(target, sr)
91
+ out: Array = resample_poly(y, target // g, sr // g)
92
+ return out
93
+
94
+
95
+ def load(path: Path, target: int = SR) -> Array:
96
+ """read_wav + resample to `target`."""
97
+ y, sr = read_wav(path)
98
+ return resample(y, sr, target)
99
+
100
+
101
+ def loud_threshold(levels_db: Any, gap: float = 1.0) -> float | None:
102
+ """The level (dB) above which a part of a song counts as its loud part (the choruses): the levels in three groups
103
+ (quiet, verse, chorus; 1-D k-means from the 10/50/90th percentiles), halfway between the top two; None when there
104
+ are under three levels or the top group is not `gap` dB above the middle one (no louder part to speak of)."""
105
+ lv = np.asarray(levels_db, float)
106
+ if len(lv) < 3:
107
+ return None
108
+ c = np.percentile(lv, [10, 50, 90])
109
+ for _ in range(30):
110
+ lab = np.abs(lv[:, None] - c[None]).argmin(1)
111
+ c = np.array([lv[lab == k].mean() if (lab == k).any() else c[k] for k in range(3)])
112
+ c.sort()
113
+ return float((c[1] + c[2]) / 2) if c[2] - c[1] >= gap else None
114
+
115
+
116
+ def db(x: Any) -> float:
117
+ """The RMS level of x in dB (-inf-safe: an empty or silent x is about -180 dB)."""
118
+ x = np.asarray(x, float)
119
+ return float(20 * np.log10(np.sqrt(np.mean(x**2)) + 1e-9)) if x.size else -180.0
120
+
121
+
122
+ def envelope(x: Any, ms: float = 10.0, sr: int = SR) -> Array:
123
+ """The RMS envelope of x over a moving window of `ms` milliseconds, one value per sample."""
124
+ w = max(1, int(ms / 1000 * sr))
125
+ env: Array = np.sqrt(np.convolve(np.asarray(x, float) ** 2, np.ones(w) / w, "same") + 1e-12)
126
+ return env
127
+
128
+
129
+ def to_mp3(wav: Path, mp3: Path | None = None, quality: int = 2) -> Path:
130
+ """An MP3 (LAME VBR `quality`, 0 best) next to the WAV (or at `mp3`); returns its path.
131
+
132
+ Without ffmpeg on PATH it warns and returns the WAV: the MP3 is a convenience, not a step.
133
+ """
134
+ mp3 = Path(mp3) if mp3 else Path(wav).with_suffix(".mp3")
135
+ if shutil.which("ffmpeg") is None:
136
+ warnings.warn(f"ffmpeg not found: kept {wav} without an MP3 (install ffmpeg for MP3s)", stacklevel=2)
137
+ return Path(wav)
138
+ subprocess.run(
139
+ [
140
+ "ffmpeg",
141
+ "-loglevel",
142
+ "error",
143
+ "-y",
144
+ "-i",
145
+ str(wav),
146
+ "-codec:a",
147
+ "libmp3lame",
148
+ "-q:a",
149
+ str(quality),
150
+ str(mp3),
151
+ ],
152
+ check=True,
153
+ )
154
+ return mp3
155
+
156
+
157
+ def mmss(seconds: float) -> str:
158
+ """m:ss.s, the way reports and pictures name a place in a song."""
159
+ return f"{int(seconds // 60)}:{seconds % 60:04.1f}"
hinase_toki/_curves.py ADDED
@@ -0,0 +1,313 @@
1
+ """Phoneme lengths, the voice curves (breathiness, voicing, dynamics) and the gate (dB per frame)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from ._audio import FT, HOP, SR, Array
8
+ from ._score import Note, phrases
9
+ from ._text import SUNG, VOWELS
10
+
11
+ MIN_DUR = {
12
+ "N": 0.07,
13
+ "cl": 0.05,
14
+ "n": 0.045,
15
+ "m": 0.045,
16
+ "k": 0.035,
17
+ "g": 0.035,
18
+ "t": 0.035,
19
+ "d": 0.035,
20
+ "p": 0.035,
21
+ "b": 0.035,
22
+ "ch": 0.04,
23
+ "ts": 0.04,
24
+ "s": 0.05,
25
+ "sh": 0.05,
26
+ "h": 0.05,
27
+ "f": 0.05,
28
+ "z": 0.05,
29
+ "j": 0.05,
30
+ "r": 0.03,
31
+ }
32
+ MIN_CONS, MAX_CONS, MIN_VOWEL = 0.025, 0.16, 0.04
33
+
34
+
35
+ FAST_NOTE = 0.2
36
+
37
+
38
+ def fast_velocity(nf: list[int], speed: float) -> np.ndarray:
39
+ """The acoustic model's speed input per frame [1, n]: 1 on notes of FAST_NOTE s or more, FAST_NOTE / length on
40
+ shorter ones (at most `speed`) - what time-compressed training phrases were labelled with."""
41
+ return np.concatenate([np.full(f, min(speed, max(1.0, FAST_NOTE / max(f * FT, 1e-3))), np.float32) for f in nf])[
42
+ None
43
+ ]
44
+
45
+
46
+ def scale_durations(pred: Array, frames: int) -> list[int]:
47
+ """Predicted phoneme durations of one word scaled to its frames; every phoneme keeps at least one
48
+ frame while there are enough."""
49
+ p = np.maximum(np.asarray(pred, float), 1e-3)
50
+ c = np.round(np.cumsum(p) / p.sum() * frames).astype(int)
51
+ d = np.diff(np.concatenate([[0], c]))
52
+ while frames >= len(d) and d.min() < 1:
53
+ d[int(np.argmin(d))] += 1
54
+ d[int(np.argmax(d))] -= 1
55
+ return [int(x) for x in d]
56
+
57
+
58
+ def _frames(sec: float) -> int:
59
+ return max(1, round(sec / FT))
60
+
61
+
62
+ def clamp_durations(
63
+ ph: list[str],
64
+ durs: list[int],
65
+ words: list[list[str]],
66
+ vowel_share: float | None = None,
67
+ shares: list[float | None] | None = None,
68
+ ) -> list[int]:
69
+ """Consonants, ん and っ get an audible length; a word keeps its frames (its vowel gives or takes).
70
+ vowel_share: the vowel keeps at least this share of its word, taken back from the longest of the next
71
+ consonants (never below their own minimum): on a 0.18 s note a long next consonant left the vowel
72
+ 20-40 ms and it was heard as a whisper. None: off."""
73
+ durs, i = list(durs), 0
74
+ for wi, w in enumerate(words):
75
+ share = shares[wi] if shares is not None and shares[wi] is not None else vowel_share
76
+ head = i if ph[i] in VOWELS else None
77
+ for j in range(i, i + len(w)):
78
+ if j == head or (ph[j] in VOWELS and ph[j] not in MIN_DUR):
79
+ continue
80
+ lo = _frames(max(MIN_CONS, MIN_DUR.get(ph[j], 0)))
81
+ hi = float("inf") if ph[j] in VOWELS else _frames(MAX_CONS)
82
+ want = int(min(hi, max(lo, durs[j]))) # an int: hi is only infinite for a vowel
83
+ if head is None:
84
+ durs[j] = want
85
+ continue
86
+ delta = min(want - durs[j], max(0, durs[head] - _frames(MIN_VOWEL)))
87
+ durs[j] += delta
88
+ durs[head] -= delta
89
+ if head is not None and ph[head] == "N":
90
+ need, j = _frames(MIN_DUR["N"]) - durs[head], i + len(w) - 1
91
+ while need > 0 and j > head:
92
+ take = min(need, max(0, durs[j] - 1))
93
+ durs[j] -= take
94
+ durs[head] += take
95
+ need -= take
96
+ j -= 1
97
+ if share and head is not None and len(w) > 1:
98
+ floor = {j: _frames(max(MIN_CONS, MIN_DUR.get(ph[j], 0))) for j in range(i, i + len(w)) if j != head}
99
+ while durs[head] < share * sum(durs[i : i + len(w)]):
100
+ give = [j for j in floor if durs[j] > floor[j]]
101
+ if not give:
102
+ break
103
+ j = max(give, key=lambda q: durs[q])
104
+ durs[j] -= 1
105
+ durs[head] += 1
106
+ i += len(w)
107
+ return durs
108
+
109
+
110
+ # ---------------------------------------------------------------- voice curves
111
+ def set_lengths(
112
+ ph: list[str], durs: list[int], words: list[list[str]], ph_note: list[int], notes: list[Note]
113
+ ) -> list[int]:
114
+ """Each note's ph_len (seconds, None: keep) on its phonemes; the word's vowel gives or takes the difference so
115
+ the word keeps its frames (never below one frame)."""
116
+ durs = list(durs)
117
+ word_of: list[int] = []
118
+ for wi, w in enumerate(words):
119
+ word_of += [wi] * len(w)
120
+ starts = np.cumsum([0] + [len(w) for w in words])
121
+ for i, n in enumerate(notes):
122
+ if not n.ph_len:
123
+ continue
124
+ mine = [j for j, x in enumerate(ph_note) if x == i]
125
+ for j, sec in zip(mine, n.ph_len):
126
+ if sec is None:
127
+ continue
128
+ want = max(1, round(sec / FT))
129
+ wi = word_of[j]
130
+ head = next((q for q in range(starts[wi], starts[wi + 1]) if ph[q] in VOWELS and q != j), None)
131
+ delta = want - durs[j]
132
+ if head is not None:
133
+ delta = min(delta, durs[head] - 1)
134
+ durs[head] -= delta
135
+ durs[j] += delta
136
+ return durs
137
+
138
+
139
+ def vowel_breath(ph: list[str], durs: list[int], breath: Array, db: float) -> Array:
140
+ """Breathiness [1, n] (dB) with every sung vowel (and ん) `db` dB changed; consonants keep theirs (a global
141
+ cut weakens s/h/f). The exports sing vowels breathier than the recordings they learned from (H1-H2 on A3
142
+ 14.5 dB against 6.7 dB, measured 2026-11-30): heard as a voice that leaks air."""
143
+ breath, pos = np.array(breath, copy=True), 0
144
+ for p, n in zip(ph, durs):
145
+ if p in SUNG:
146
+ breath[0, pos : pos + n] += db
147
+ pos += n
148
+ return breath
149
+
150
+
151
+ def floor_vowels(
152
+ ph: list[str], durs: list[int], voicing: Array, below: float = 4.0, release: float | None = None
153
+ ) -> Array:
154
+ """Voicing curve [1, n] (dB): frames of sung vowels (and ん) are raised to at least the phrase's
155
+ median vowel level minus `below` dB, so the model cannot whisper or drop a note. (The energy the
156
+ variance model predicts is not an input of the acoustic model: it has nothing to raise.)
157
+ release: the last share of a vowel before a rest (or the phrase's end) goes back to the model's own curve,
158
+ gradually, so the voice can fade there instead of being held up until the gate cuts it."""
159
+ voicing = np.array(voicing, copy=True)
160
+ spans, pos = [], 0
161
+ for k, (p, n) in enumerate(zip(ph, durs)):
162
+ if p in SUNG:
163
+ spans.append((pos, pos + n, k + 1 >= len(ph) or ph[k + 1] == "SP"))
164
+ pos += n
165
+ if not spans:
166
+ return voicing
167
+ low = float(np.median(np.concatenate([voicing[0, a:b] for a, b, _ in spans]))) - below
168
+ for a, b, ends in spans:
169
+ own = voicing[0, a:b].copy()
170
+ voicing[0, a:b] = np.maximum(own, low)
171
+ m = int(round((release or 0) * (b - a))) if ends else 0
172
+ if m > 0:
173
+ w = np.linspace(1, 0, m)
174
+ voicing[0, b - m : b] = own[-m:] + w * (voicing[0, b - m : b] - own[-m:])
175
+ return voicing
176
+
177
+
178
+ def phoneme_curve(
179
+ ph: list[str],
180
+ durs: list[int],
181
+ ph_note: list[int],
182
+ notes: list[Note],
183
+ key: str,
184
+ vowels_only: bool = False,
185
+ ramp: int = 4,
186
+ ) -> np.ndarray:
187
+ """One value per frame of a per-note expression, following the note each phoneme belongs to (a note's
188
+ leading consonants sit in the frames of the note before it, but carry this note's value). vowels_only: only
189
+ sung vowels get it, consonants and breaths stay at 0 (breathiness: a cut must not weaken s/h/f/k). The value
190
+ moves over a few frames between phonemes."""
191
+ v = (
192
+ np.concatenate(
193
+ [
194
+ np.full(d, 0.0 if vowels_only and p not in SUNG else float(notes[k].expr.get(key, 0)), "float32")
195
+ for p, d, k in zip(ph, durs, ph_note)
196
+ ]
197
+ )
198
+ if ph
199
+ else np.zeros(0, "float32")
200
+ )
201
+ if v.any() and ramp:
202
+ v = np.convolve(np.pad(v, ramp, mode="edge"), np.ones(2 * ramp + 1) / (2 * ramp + 1), "valid")
203
+ if vowels_only: # the ramp stays inside the vowels
204
+ v *= np.concatenate([np.full(d, float(p in SUNG)) for p, d in zip(ph, durs)])
205
+ return v.astype("float32")
206
+
207
+
208
+ HIGH_HOLD = 0.3
209
+
210
+
211
+ def high_notes(
212
+ ph: list[str],
213
+ durs: list[int],
214
+ ph_note: list[int],
215
+ notes: list[Note],
216
+ nf: list[int],
217
+ breath: Array,
218
+ voicing: Array,
219
+ high: int | None,
220
+ br: float = -6.0,
221
+ floor: float = 2.0,
222
+ ) -> tuple[Array, Array]:
223
+ """Breathiness and voicing [1, n] (dB) with the vowels of high held notes (MIDI >= high, HIGH_HOLD s or more)
224
+ `br` dB less breathy and voiced at least the phrase's median vowel level minus `floor` dB: on high long notes
225
+ every voice tested turned rough or devoiced (eval_high, 2026-11-30). Consonants keep their breath (a global
226
+ cut weakens s/h/f)."""
227
+ breath, voicing = np.array(breath, copy=True), np.array(voicing, copy=True)
228
+
229
+ def chosen(n: Note, f: int) -> bool: # a note's own high=1 / high=0 decides; else the rule
230
+ if n.midi is None:
231
+ return False
232
+ if "high" in n.expr:
233
+ return bool(n.expr["high"])
234
+ return high is not None and n.midi >= high and f * FT >= HIGH_HOLD
235
+
236
+ hit = [chosen(n, f) for n, f in zip(notes, nf)]
237
+ spans: list[tuple[int, int]] = []
238
+ sung: list[tuple[int, int]] = []
239
+ pos = 0
240
+ for p, d, k in zip(ph, durs, ph_note):
241
+ if p in SUNG:
242
+ sung.append((pos, pos + d))
243
+ if hit[k]:
244
+ spans.append((pos, pos + d))
245
+ pos += d
246
+ if not spans:
247
+ return breath, voicing
248
+ level = float(np.median(np.concatenate([voicing[0, a:b] for a, b in sung]))) - floor
249
+ for a, b in spans:
250
+ breath[0, a:b] += br
251
+ voicing[0, a:b] = np.maximum(voicing[0, a:b], level)
252
+ return breath, voicing
253
+
254
+
255
+ def mark_high(
256
+ notes: list[Note], beat: float, which: set[int], split: float = 1.0, max_seconds: float = 12.0
257
+ ) -> list[Note]:
258
+ """The notes with high=1 on every sung note of these phrases (1, 2, ... as phrases() counts them)."""
259
+ segs, _ = phrases(notes, beat, split, max_seconds)
260
+ spans = [(s, s + sum(x.beats for x in ns)) for s, ns in segs]
261
+ out, t = [], 0.0
262
+ for n in notes:
263
+ k = next((i for i, (a, b) in enumerate(spans, 1) if a - 1e-6 <= t < b - 1e-6), None)
264
+ m = n.copy()
265
+ if k in which and m.midi is not None:
266
+ m.expr["high"] = 1.0
267
+ out.append(m)
268
+ t += n.beats
269
+ return out
270
+
271
+
272
+ def dynamics_gain(db: np.ndarray) -> np.ndarray:
273
+ """Sample-wise gain of a frame curve in dB (the notes' `dyn`, see phoneme_curve)."""
274
+ db = np.asarray(db, "float32")
275
+ x = np.arange(len(db) * HOP) / HOP - 0.5
276
+ gain: Array = (10 ** (np.interp(x, np.arange(len(db)), db) / 20)).astype("float32")
277
+ return gain
278
+
279
+
280
+ def gate(wav: np.ndarray, ph: list[str], durs: list[int], soft: bool = False) -> np.ndarray:
281
+ """Silent margins (the model may hum a stray note there), rests inside a phrase at 8 % keeping the
282
+ vowel's release, breaths about 7 dB down. soft: the inner rests eased down over up to 0.12 s and back up
283
+ (cosine) instead of 40 ms straight lines."""
284
+ wav, pos = wav.copy(), 0
285
+ for k, (p, d) in enumerate(zip(ph, durs)):
286
+ a, b = pos * HOP, min(len(wav), (pos + d) * HOP)
287
+ pos += d
288
+ if p == "SP" and k == 0: # silence, opening 30 ms early
289
+ f = min(int(0.03 * SR), b)
290
+ wav[: b - f] = 0
291
+ wav[b - f : b] *= np.linspace(0, 1, f)
292
+ elif p == "SP" and k == len(ph) - 1: # keep 0.18 s of release, then fade
293
+ s, f = a + int(0.18 * SR), int(0.08 * SR)
294
+ wav[s : s + f] *= np.linspace(1, 0, len(wav[s : s + f]))
295
+ wav[s + f :] = 0
296
+ elif p == "SP":
297
+ s, e, f = a + int(0.15 * SR), b - int(0.06 * SR), int(0.04 * SR)
298
+ if e - s > int(0.1 * SR):
299
+ if soft:
300
+ f = max(f, min(int(0.12 * SR), (e - s) // 2))
301
+ down = 0.08 + 0.92 * 0.5 * (1 + np.cos(np.linspace(0, np.pi, f)))
302
+ else:
303
+ down = np.linspace(1, 0.08, f)
304
+ wav[s : s + f] *= down
305
+ wav[e - f : e] *= down[::-1]
306
+ wav[s + f : e - f] *= 0.08
307
+ elif p == "AP":
308
+ f = min(int(0.03 * SR), (b - a) // 3)
309
+ env = np.full(b - a, 0.45)
310
+ if f > 0:
311
+ env[-f:] = np.linspace(0.45, 1, f)
312
+ wav[a:b] *= env
313
+ return wav
hinase_toki/_lanes.py ADDED
@@ -0,0 +1,70 @@
1
+ """Curves over the whole song (DAW-style automation): one lane per control, applied after the engine shapes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass
7
+
8
+ import numpy as np
9
+
10
+ from ._audio import Array
11
+
12
+ LANES = ("pitch", "dynamics", "breathiness", "voicing", "gender", "velocity", "expr")
13
+ MODES = ("add", "scale", "replace")
14
+ INTERPS = ("linear", "step", "smooth")
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Lane:
19
+ """Points (seconds from the start of the song, value), sorted. Before the first point the lane does nothing;
20
+ after the last it holds the last value."""
21
+
22
+ points: tuple[tuple[float, float], ...]
23
+ mode: str = "add"
24
+ interp: str = "linear"
25
+
26
+ def values(self, times: Array) -> tuple[Array, Array]:
27
+ """The lane's value at each time and where it applies."""
28
+ t = np.array([p[0] for p in self.points], float)
29
+ v = np.array([p[1] for p in self.points], float)
30
+ on = times >= t[0]
31
+ if len(t) == 1:
32
+ return np.full(len(times), v[0]), on
33
+ if self.interp == "step":
34
+ idx = np.clip(np.searchsorted(t, times, side="right") - 1, 0, len(t) - 1)
35
+ return v[idx], on
36
+ out = np.interp(times, t, v)
37
+ if self.interp == "smooth": # cosine between points
38
+ idx = np.clip(np.searchsorted(t, times, side="right") - 1, 0, len(t) - 2)
39
+ span = np.maximum(t[idx + 1] - t[idx], 1e-9)
40
+ x = np.clip((times - t[idx]) / span, 0, 1)
41
+ w = 0.5 - 0.5 * np.cos(np.pi * x)
42
+ out = np.where(times >= t[-1], v[-1], v[idx] + (v[idx + 1] - v[idx]) * w)
43
+ return out, on
44
+
45
+
46
+ def apply(arr: Array, lane: Lane | None, times: Array, unit_scale: float = 1.0, base: Array | None = None) -> Array:
47
+ """arr [1, n] with the lane over it. unit_scale turns the lane's unit into arr's (cents -> semitones: 0.01).
48
+ scale multiplies arr (or, with base, its distance from base: a pitch lane scales the melody's movement)."""
49
+ if lane is None:
50
+ return arr
51
+ vals, on = lane.values(times)
52
+ out = np.array(arr, copy=True)
53
+ row = out[0]
54
+ if lane.mode == "add":
55
+ row[on] += (vals[on] * unit_scale).astype(row.dtype)
56
+ elif lane.mode == "replace":
57
+ row[on] = (vals[on] * unit_scale).astype(row.dtype)
58
+ else:
59
+ ref = base[0] if base is not None else np.zeros_like(row)
60
+ row[on] = (ref[on] + (row[on] - ref[on]) * vals[on]).astype(row.dtype)
61
+ return out
62
+
63
+
64
+ def frame_times(t0: float, n: int, ft: float) -> Array:
65
+ return t0 + np.arange(n) * ft
66
+
67
+
68
+ def per_note(nf: Sequence[int], values: Sequence[float]) -> Array:
69
+ """A per-frame row [1, n] holding each note's value over its frames."""
70
+ return np.concatenate([np.full(f, v, np.float32) for f, v in zip(nf, values)])[None]