Skip to content

Commit af25f7d

Browse files
Lee Seongjooclaude
andcommitted
Fix abrupt sentence endings + non-stream CLI + rename to "Codebasic TTS"
Ending fix (the model truncates the final syllable via early EOS — confirmed not a max_tokens cap, 96≪264): synthesize with a short filler word appended so the real ending isn't terminal, then trim at the last silence gap, dropping the filler + its leading pause. User-confirmed: keeps a complete "습니다". Also: - CLI uses non-streaming generation (it buffers before playback anyway, and streaming dropped ~0.3-0.5s of the tail). - Loudness normalize (-20 dBFS) + trailing silence (250ms) + small fade (25ms). - Knobs: --filler/--tail-ms/--fade-ms/--rms-db and REPL :filler/:tail/:fade/:rms. - Apply the same pipeline in the sidecar (server.py). - Rename user-facing service to "Codebasic TTS" (Info.plist menu + display name, menu-bar title). Internal ids (executable, bundle id) unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent c6a0e4a commit af25f7d

4 files changed

Lines changed: 108 additions & 14 deletions

File tree

‎Resources/Info.plist‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
<plist version="1.0">
44
<dict>
55
<key>CFBundleName</key>
6-
<string>SelectedTextTTS</string>
6+
<string>Codebasic TTS</string>
77
<key>CFBundleDisplayName</key>
8-
<string>SelectedTextTTS</string>
8+
<string>Codebasic TTS</string>
99
<key>CFBundleIdentifier</key>
1010
<string>com.seongjoo.SelectedTextTTS</string>
1111
<key>CFBundleExecutable</key>
@@ -31,7 +31,7 @@
3131
<key>NSMenuItem</key>
3232
<dict>
3333
<key>default</key>
34-
<string>Read with SelectedTextTTS</string>
34+
<string>Codebasic TTS</string>
3535
</dict>
3636
<key>NSMessage</key>
3737
<string>readSelectedText</string>

‎Sidecar/clone.py‎

Lines changed: 70 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,41 @@ def normalize(audio: np.ndarray, target_rms_db: float = -20.0,
6767
return audio
6868

6969

70+
def trim_after_filler(audio: np.ndarray, sr: int, min_gap_ms: float = 120.0,
71+
thr_ratio: float = 0.02) -> np.ndarray:
72+
"""The model truncates the final syllable of a sentence (early EOS), so the
73+
real ending ('습니다') sounds cut. We synthesize with a short filler word
74+
appended so the real ending is no longer terminal, then cut at the last
75+
silence gap — dropping the filler and its leading pause and keeping the now-
76+
complete ending. If no clear gap is found, return unchanged."""
77+
a = audio.reshape(-1)
78+
pk = float(np.max(np.abs(a))) or 1e-9
79+
idx = np.where(np.abs(a) > thr_ratio * pk)[0]
80+
if idx.size == 0:
81+
return a
82+
gap = int(min_gap_ms * sr / 1000)
83+
big = np.where(np.diff(idx) > gap)[0]
84+
if big.size == 0:
85+
return a
86+
cut = idx[big[-1]] + 1 # last active sample before the final gap
87+
return a[:cut]
88+
89+
90+
def pad_tail(audio: np.ndarray, sr: int, pad_ms: float = 250.0,
91+
fade_ms: float = 12.0) -> np.ndarray:
92+
"""The model leaves almost no silence after the last phoneme (~10-70ms), so
93+
endings feel abruptly cut. Apply a short fade-out (click safety) then append
94+
breathing-room silence."""
95+
audio = audio.reshape(-1).astype(np.float32).copy()
96+
n_fade = int(sr * fade_ms / 1000)
97+
if 0 < n_fade < audio.size:
98+
audio[-n_fade:] *= np.linspace(1.0, 0.0, n_fade, dtype=np.float32)
99+
n_pad = int(sr * pad_ms / 1000)
100+
if n_pad > 0:
101+
audio = np.concatenate([audio, np.zeros(n_pad, dtype=np.float32)])
102+
return audio
103+
104+
70105
def to_wav(audio: np.ndarray, sr: int, path: str):
71106
audio = np.clip(audio.reshape(-1), -1.0, 1.0)
72107
pcm16 = (audio * 32767.0).astype("<i2")
@@ -79,7 +114,7 @@ def to_wav(audio: np.ndarray, sr: int, path: str):
79114

80115
class Engine:
81116
def __init__(self, quant, ref_audio, ref_text, temperature, speed,
82-
norm=True, rms_db=-20.0):
117+
norm=True, rms_db=-20.0, tail_ms=250.0, fade_ms=25.0, filler=" 네."):
83118
self.quant = quant
84119
self.ref_audio = ref_audio
85120
self.ref_text_path = ref_text
@@ -88,6 +123,9 @@ def __init__(self, quant, ref_audio, ref_text, temperature, speed,
88123
self.speed = speed
89124
self.norm = norm
90125
self.rms_db = rms_db
126+
self.tail_ms = tail_ms
127+
self.fade_ms = fade_ms
128+
self.filler = filler
91129
self.model = None
92130
self.sr = 24000
93131
self.load()
@@ -103,23 +141,26 @@ def load(self):
103141
def warmup(self):
104142
print("[warmup] compiling graph (one-time ~30s on cold MLX) ...", flush=True)
105143
t0 = time.time()
106-
self._gen("워밍업.", stream=True, quiet=True)
144+
self._gen("워밍업.", stream=False, quiet=True)
107145
print(f"[warmup] ready in {time.time()-t0:.1f}s", flush=True)
108146

109-
def _gen(self, text, stream=True, quiet=False):
147+
def _gen(self, text, stream=True, quiet=False, filler=None):
148+
gen_text = (text + filler) if filler else text
110149
t0 = time.time()
111150
t_first = None
112151
chunks = []
113152
kw = dict(stream=True, streaming_interval=0.5) if stream else {}
114153
for r in self.model.generate(
115-
text=text, ref_audio=self.ref_audio, ref_text=self.ref_text,
154+
text=gen_text, ref_audio=self.ref_audio, ref_text=self.ref_text,
116155
temperature=self.temperature, speed=self.speed, verbose=False, **kw
117156
):
118157
if t_first is None:
119158
t_first = time.time() - t0
120159
chunks.append(np.array(r.audio).reshape(-1))
121160
total = time.time() - t0
122161
audio = np.concatenate(chunks).astype(np.float32)
162+
if filler: # drop the filler + its leading pause
163+
audio = trim_after_filler(audio, self.sr)
123164
dur = len(audio) / self.sr
124165
if not quiet:
125166
rtf = total / dur if dur else 0
@@ -129,9 +170,14 @@ def _gen(self, text, stream=True, quiet=False):
129170
return audio
130171

131172
def synth(self, text, out_path=None, play=True):
132-
audio = self._gen(text, stream=True)
173+
# Non-streaming: this CLI buffers the whole clip before playback anyway,
174+
# so streaming gives no latency win and its final-chunk drop (~0.3-0.5s)
175+
# truncated the ending. Non-stream keeps the full tail.
176+
audio = self._gen(text, stream=False, filler=self.filler or None)
133177
if self.norm:
134178
audio = normalize(audio, target_rms_db=self.rms_db)
179+
if self.tail_ms > 0 or self.fade_ms > 0:
180+
audio = pad_tail(audio, self.sr, pad_ms=self.tail_ms, fade_ms=self.fade_ms)
135181
path = out_path or os.path.join(tempfile.gettempdir(), "clone_repl.wav")
136182
to_wav(audio, self.sr, path)
137183
if out_path:
@@ -211,7 +257,8 @@ def repl(eng: Engine, save: bool):
211257
break
212258
elif cmd == ":help":
213259
print(":ref PATH | :model 4bit|5bit|6bit|8bit|bf16 | :temp 0.x | "
214-
":speed 1.0 | :norm on|off | :rms -20 | :save on|off | :q", flush=True)
260+
":speed 1.0 | :norm on|off | :rms -20 | :tail 250 | :fade 25 | "
261+
":filler ' 네.'|off | :save on|off | :q", flush=True)
215262
elif cmd.startswith(":ref "):
216263
p = os.path.expanduser(cmd[5:].strip())
217264
if os.path.exists(p):
@@ -232,6 +279,14 @@ def repl(eng: Engine, save: bool):
232279
eng.norm = cmd[6:].strip() == "on"; print(f"[norm] {eng.norm}", flush=True)
233280
elif cmd.startswith(":rms "):
234281
eng.rms_db = float(cmd[5:]); print(f"[rms] target {eng.rms_db} dBFS", flush=True)
282+
elif cmd.startswith(":tail "):
283+
eng.tail_ms = float(cmd[6:]); print(f"[tail] {eng.tail_ms} ms", flush=True)
284+
elif cmd.startswith(":fade "):
285+
eng.fade_ms = float(cmd[6:]); print(f"[fade] {eng.fade_ms} ms", flush=True)
286+
elif cmd.startswith(":filler"):
287+
v = cmd[len(":filler"):].strip()
288+
eng.filler = "" if v in ("off", "''", '""') else (v or eng.filler)
289+
print(f"[filler] {eng.filler!r}", flush=True)
235290
else:
236291
print(f"[?] unknown command: {cmd} (try :help)", flush=True)
237292
continue
@@ -263,11 +318,19 @@ def main():
263318
help="disable loudness normalization (raw model level)")
264319
ap.add_argument("--rms-db", type=float, default=-20.0,
265320
help="target RMS loudness in dBFS (default -20; higher=louder)")
321+
ap.add_argument("--tail-ms", type=float, default=250.0,
322+
help="trailing silence appended after speech (default 250; 0=off)")
323+
ap.add_argument("--fade-ms", type=float, default=25.0,
324+
help="fade-out over the speech end, click safety (default 25; 0=off)")
325+
ap.add_argument("--filler", default=" 네.",
326+
help="filler appended then trimmed so the real ending isn't truncated "
327+
"(default ' 네.'; empty string disables)")
266328
ap.add_argument("--save", action="store_true", help="REPL: keep each wav in ./out/")
267329
args = ap.parse_args()
268330

269331
eng = Engine(args.model, args.ref_audio, args.ref_text, args.temp, args.speed,
270-
norm=not args.no_normalize, rms_db=args.rms_db)
332+
norm=not args.no_normalize, rms_db=args.rms_db,
333+
tail_ms=args.tail_ms, fade_ms=args.fade_ms, filler=args.filler)
271334

272335
if args.text: # one-shot
273336
eng.warmup() # so the single run isn't the 30s cold path

‎Sidecar/server.py‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,39 @@ def _normalize(audio: np.ndarray, target_rms_db: float = -20.0, peak_limit: floa
8282
return audio
8383

8484

85+
FILLER = " 네." # appended then trimmed so the real ending isn't truncated by early EOS
86+
87+
88+
def _trim_after_filler(audio: np.ndarray, sr: int, min_gap_ms: float = 120.0, thr_ratio: float = 0.02) -> np.ndarray:
89+
"""Cut at the last silence gap, dropping the appended filler word + its
90+
leading pause and keeping the now-complete real ending."""
91+
a = audio.reshape(-1)
92+
pk = float(np.max(np.abs(a))) or 1e-9
93+
idx = np.where(np.abs(a) > thr_ratio * pk)[0]
94+
if idx.size == 0:
95+
return a
96+
big = np.where(np.diff(idx) > int(min_gap_ms * sr / 1000))[0]
97+
if big.size == 0:
98+
return a
99+
return a[:idx[big[-1]] + 1]
100+
101+
102+
def _pad_tail(audio: np.ndarray, sr: int, pad_ms: float = 250.0, fade_ms: float = 25.0) -> np.ndarray:
103+
"""Append breathing-room silence (with a short fade-out) so endings don't
104+
sound abruptly cut; the model leaves only ~10-70ms of trailing silence."""
105+
audio = audio.reshape(-1).astype(np.float32).copy()
106+
n_fade = int(sr * fade_ms / 1000)
107+
if 0 < n_fade < audio.size:
108+
audio[-n_fade:] *= np.linspace(1.0, 0.0, n_fade, dtype=np.float32)
109+
n_pad = int(sr * pad_ms / 1000)
110+
if n_pad > 0:
111+
audio = np.concatenate([audio, np.zeros(n_pad, dtype=np.float32)])
112+
return audio
113+
114+
85115
def _pcm_wav_bytes(audio: np.ndarray, sr: int) -> bytes:
86-
"""float32 [-1,1] mono -> 16-bit PCM WAV container (loudness-normalized)."""
87-
audio = np.clip(_normalize(audio).reshape(-1), -1.0, 1.0)
116+
"""float32 [-1,1] mono -> 16-bit PCM WAV container (normalized + tail-padded)."""
117+
audio = np.clip(_pad_tail(_normalize(audio), sr).reshape(-1), -1.0, 1.0)
88118
pcm16 = (audio * 32767.0).astype("<i2")
89119
buf = io.BytesIO()
90120
with wave.open(buf, "wb") as w:
@@ -117,7 +147,7 @@ def tts(req: TTSRequest):
117147

118148
t0 = time.time()
119149
results = list(model.generate(
120-
text=text,
150+
text=text + FILLER,
121151
ref_audio=REF_AUDIO,
122152
ref_text=_state["ref_text"],
123153
temperature=req.temperature,
@@ -126,6 +156,7 @@ def tts(req: TTSRequest):
126156
))
127157
sr = int(getattr(results[0], "sample_rate", 0) or _state["sample_rate"])
128158
audio = np.concatenate([np.array(r.audio).reshape(-1) for r in results]).astype(np.float32)
159+
audio = _trim_after_filler(audio, sr) # drop the filler + its leading pause
129160
wav = _pcm_wav_bytes(audio, sr)
130161
print(f"[sidecar] tts {len(text)} chars -> {len(audio)/sr:.2f}s audio "
131162
f"in {time.time()-t0:.1f}s", flush=True)

‎Sources/App/AppDelegate.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
2929
statusItem.button?.title = "🔊"
3030

3131
let menu = NSMenu()
32-
menu.addItem(withTitle: "SelectedTextTTS", action: nil, keyEquivalent: "")
32+
menu.addItem(withTitle: "Codebasic TTS", action: nil, keyEquivalent: "")
3333
menu.addItem(.separator())
3434

3535
let lastItem = NSMenuItem(title: "Last selection: —", action: nil, keyEquivalent: "")

0 commit comments

Comments
 (0)