Skip to content

Commit f08e6cc

Browse files
Lee Seongjooclaude
andcommitted
TTS-friendly text normalization via a local LLM (Ollama)
Optional preprocessing step that rewrites mis-read notation (decimals like 0.001, percentages, subscripts/variables like w1, math like x^2, symbols like ±) into spoken Korean before synthesis, using Ollama. - TextNormalizer: POST /api/generate with a normalization prompt (temp 0.2), falls back to the original text on any failure so synthesis is never blocked. - AppState: per-chunk normalization on cache miss; the cache namespace includes the normalization model so normalized/raw audio don't collide. Settings: toggle + Ollama model picker (from /api/tags) + base URL, persisted. - Settings UI section with connection check / model list. Model note: small local models (qwen2.5:3b, exaone3.5:2.4b) garble Korean number-to-hangul (0.001 → "영 점 오 영 일", 98.5% → "퍼센트 구 구 팔"); a strong model is needed. Default to gemma4:31b-cloud, which was accurate in testing. The model is user-configurable. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent df218fb commit f08e6cc

3 files changed

Lines changed: 130 additions & 3 deletions

File tree

‎Sources/App/AppState.swift‎

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@ final class AppState: ObservableObject {
2626
@Published var useCache = true
2727
@Published var localBaseURL = "http://127.0.0.1:8765"
2828

29+
// TTS-friendly text normalization (lightweight LLM via Ollama)
30+
@Published var normalizeEnabled = false
31+
@Published var ollamaModel = "gemma4:31b-cloud" // 3B local models garble Korean numbers; a strong model is needed
32+
@Published var ollamaURL = "http://localhost:11434"
33+
@Published var ollamaModels: [String] = []
34+
@Published var ollamaStatus = ""
35+
2936
// Runtime
3037
enum Phase: Equatable { case idle, synthesizing, playing, paused }
3138
@Published var phase: Phase = .idle
@@ -108,9 +115,15 @@ final class AppState: ObservableObject {
108115
player.start(expected: chunks.count)
109116
chunkCount = chunks.count; chunkIndex = 0
110117

111-
let ident = backendIdentity, vid = voiceId, mid = modelId, sHash = settingsHash
118+
let ident = backendIdentity, vid = voiceId, mid = modelId
119+
// Cache namespace includes normalization so normalized/raw audio don't collide.
120+
let sHash = settingsHash + (normalizeEnabled ? "|norm:\(ollamaModel)" : "")
112121
let vName = voiceName, ext = audioExt
113122
let voice = VoiceConfig(voiceId: vid, modelId: mid, settingsHash: sHash)
123+
let normalizer: TextNormalizer? = normalizeEnabled
124+
? TextNormalizer(baseURL: URL(string: ollamaURL) ?? URL(string: "http://localhost:11434")!,
125+
model: ollamaModel)
126+
: nil
114127

115128
task = Task { [weak self] in
116129
guard let self else { return }
@@ -126,13 +139,22 @@ final class AppState: ObservableObject {
126139
self.cache.touch(key); url = u // cache hit: skip synthesizing state
127140
} else {
128141
// "synthesizing" only while waiting for the FIRST chunk
129-
if !startedPlaying { self.phase = .synthesizing; self.statusText = "합성 중…" }
142+
if !startedPlaying {
143+
self.phase = .synthesizing
144+
self.statusText = normalizer != nil ? "정규화·합성 중…" : "합성 중…"
145+
}
130146
if backend == nil { backend = self.makeBackend() }
131147
guard let b = backend else {
132148
self.phase = .idle; self.statusText = "키/백엔드 미설정"; return
133149
}
150+
// TTS-friendly normalization (falls back to original on failure).
151+
var ttsText = chunk
152+
if let normalizer {
153+
ttsText = (try? await normalizer.normalize(chunk)) ?? chunk
154+
try Task.checkCancellation()
155+
}
134156
var data = Data()
135-
for try await c in b.stream(segment: chunk, voice: voice) {
157+
for try await c in b.stream(segment: ttsText, voice: voice) {
136158
try Task.checkCancellation(); data.append(c)
137159
}
138160
if self.useCache {
@@ -208,6 +230,21 @@ final class AppState: ObservableObject {
208230
}
209231
}
210232

233+
func refreshOllamaModels() {
234+
let url = URL(string: ollamaURL) ?? URL(string: "http://localhost:11434")!
235+
ollamaStatus = "확인 중…"
236+
Task { [weak self] in
237+
do {
238+
let ms = try await Ollama.models(baseURL: url)
239+
guard let self else { return }
240+
self.ollamaModels = ms
241+
self.ollamaStatus = "연결됨 · 모델 \(ms.count)개"
242+
} catch {
243+
self?.ollamaStatus = "연결 실패: \(error.localizedDescription)"
244+
}
245+
}
246+
}
247+
211248
// MARK: - Settings persistence
212249

213250
private var settingsURL: URL {
@@ -219,6 +256,7 @@ final class AppState: ObservableObject {
219256
"voiceId": voiceId, "voiceName": voiceName, "modelId": modelId,
220257
"backend": backendKind.rawValue, "useCache": useCache, "localBaseURL": localBaseURL,
221258
"maxChunkChars": maxChunkChars,
259+
"normalize": normalizeEnabled, "ollamaModel": ollamaModel, "ollamaURL": ollamaURL,
222260
"stability": voiceSettings.stability, "similarity": voiceSettings.similarityBoost,
223261
"style": voiceSettings.style, "speakerBoost": voiceSettings.useSpeakerBoost,
224262
]
@@ -237,6 +275,9 @@ final class AppState: ObservableObject {
237275
useCache = o["useCache"] as? Bool ?? useCache
238276
localBaseURL = o["localBaseURL"] as? String ?? localBaseURL
239277
maxChunkChars = o["maxChunkChars"] as? Int ?? maxChunkChars
278+
normalizeEnabled = o["normalize"] as? Bool ?? normalizeEnabled
279+
ollamaModel = o["ollamaModel"] as? String ?? ollamaModel
280+
ollamaURL = o["ollamaURL"] as? String ?? ollamaURL
240281
voiceSettings.stability = o["stability"] as? Double ?? voiceSettings.stability
241282
voiceSettings.similarityBoost = o["similarity"] as? Double ?? voiceSettings.similarityBoost
242283
voiceSettings.style = o["style"] as? Double ?? voiceSettings.style

‎Sources/TTS/TextNormalizer.swift‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import Foundation
2+
3+
/// Rewrites text so the TTS engine pronounces it correctly (decimals, math
4+
/// notation, subscripts, symbols) using a lightweight local LLM via Ollama.
5+
/// Meaning is preserved; on any failure it returns the original text so
6+
/// synthesis is never blocked.
7+
struct TextNormalizer {
8+
let baseURL: URL
9+
let model: String
10+
11+
private static let instruction = """
12+
당신은 TTS(음성 합성)가 정확히 읽도록 텍스트를 다듬는 전처리기입니다.
13+
의미와 문장 구조는 그대로 두고, 잘못 읽힐 수 있는 표기만 한국어 발음대로 풀어 씁니다.
14+
규칙:
15+
- 소수/숫자: 0.5 → 영 점 오, 3.14 → 삼 점 일사
16+
- 변수/첨자/수식: w1 → 더블유 일, x^2 → 엑스 제곱, a_i → 에이 아이, β → 베타
17+
- 기호/단위: % → 퍼센트, ± → 플러스 마이너스, ℃ → 도, ~ → 물결
18+
- 일반 영어 단어/문장과 한글 문장은 그대로 둡니다.
19+
- 설명·따옴표·머리말 없이, 변환된 텍스트만 출력합니다.
20+
"""
21+
22+
func normalize(_ text: String) async throws -> String {
23+
let prompt = "\(Self.instruction)\n\n원문:\n\(text)\n\n변환:"
24+
var req = URLRequest(url: baseURL.appendingPathComponent("api/generate"))
25+
req.httpMethod = "POST"
26+
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
27+
req.timeoutInterval = 60
28+
req.httpBody = try JSONSerialization.data(withJSONObject: [
29+
"model": model,
30+
"prompt": prompt,
31+
"stream": false,
32+
"options": ["temperature": 0.2],
33+
])
34+
let (data, response) = try await URLSession.shared.data(for: req)
35+
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
36+
let msg = String(data: data, encoding: .utf8) ?? "request failed"
37+
throw NSError(domain: "Ollama", code: (response as? HTTPURLResponse)?.statusCode ?? -1,
38+
userInfo: [NSLocalizedDescriptionKey: msg])
39+
}
40+
let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
41+
let out = (obj?["response"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
42+
return out.isEmpty ? text : out
43+
}
44+
}
45+
46+
/// Ollama helpers for the UI.
47+
enum Ollama {
48+
static func models(baseURL: URL) async throws -> [String] {
49+
let (data, response) = try await URLSession.shared.data(
50+
from: baseURL.appendingPathComponent("api/tags"))
51+
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
52+
throw NSError(domain: "Ollama", code: -1,
53+
userInfo: [NSLocalizedDescriptionKey: "Ollama에 연결할 수 없음"])
54+
}
55+
let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
56+
let arr = (obj?["models"] as? [[String: Any]]) ?? []
57+
return arr.compactMap { $0["name"] as? String }
58+
}
59+
}

‎Sources/UI/SettingsView.swift‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,35 @@ struct SettingsView: View {
4747
Text("긴 문단은 이 글자수 기준으로 나눠 따로 요청한 뒤 이어 재생합니다. 캐시도 이 단위.")
4848
.font(.caption).foregroundStyle(.secondary)
4949
}
50+
51+
Section("TTS 친화 정규화 (Ollama)") {
52+
Toggle("숫자·수식 표기를 발음대로 정규화", isOn: $app.normalizeEnabled)
53+
if app.ollamaModels.isEmpty {
54+
LabeledContent("모델") {
55+
TextField("qwen2.5:3b", text: $app.ollamaModel).frame(width: 160)
56+
}
57+
} else {
58+
Picker("모델", selection: $app.ollamaModel) {
59+
ForEach(app.ollamaModels, id: \.self) { Text($0).tag($0) }
60+
}
61+
}
62+
LabeledContent("Ollama URL") {
63+
TextField("http://localhost:11434", text: $app.ollamaURL).frame(width: 200)
64+
}
65+
HStack {
66+
Button("연결 확인 / 모델 목록") { app.refreshOllamaModels() }
67+
Spacer()
68+
Text(app.ollamaStatus).font(.caption).foregroundStyle(.secondary)
69+
}
70+
Text("로컬 경량 LLM이 0.5→영 점 오, w1→더블유 일 처럼 다듬은 뒤 합성합니다. 켜면 캐시도 분리됩니다.")
71+
.font(.caption).foregroundStyle(.secondary)
72+
}
5073
}
5174
.formStyle(.grouped)
75+
.onAppear { if app.ollamaModels.isEmpty { app.refreshOllamaModels() } }
76+
.onChange(of: app.normalizeEnabled) { _, _ in app.saveSettings() }
77+
.onChange(of: app.ollamaModel) { _, _ in app.saveSettings() }
78+
.onChange(of: app.ollamaURL) { _, _ in app.saveSettings() }
5279
.onChange(of: app.maxChunkChars) { _, _ in app.saveSettings() }
5380
.onChange(of: app.voiceId) { _, newID in
5481
if let v = app.voices.first(where: { $0.id == newID }) { app.voiceName = v.name }

0 commit comments

Comments
 (0)