Skip to content

Commit a6dc5f9

Browse files
Lee Seongjooclaude
andcommitted
Generate tab: original/script two-panel + editable normalization prompt
Make normalization transparent and controllable: - Two panels: top = original source text, bottom = the TTS-friendly script actually sent to the engine. "TTS 대본 생성" runs the LLM (per paragraph) to fill the script; the script is editable before playback. "재생" speaks the script. - A collapsible "프롬프트 관리" panel edits the normalization instruction (default restorable), persisted. - Synthesis no longer normalizes internally — it speaks the prepared script; Services path builds the script first (speakSelected → prepareScript → synthesize). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent f08e6cc commit a6dc5f9

4 files changed

Lines changed: 115 additions & 40 deletions

File tree

‎Sources/App/AppDelegate.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
9090
func handleSelectedText(_ text: String) {
9191
let preview = text.replacingOccurrences(of: "\n", with: " ").prefix(60)
9292
Log.app.info("handleSelectedText: \(text.count) chars — \"\(preview, privacy: .public)\"")
93-
appState.synthesize(text)
93+
appState.speakSelected(text)
9494
}
9595

9696
// MARK: - Main menu (regular app needs one for ⌘Q and text-editing shortcuts)

‎Sources/App/AppState.swift‎

Lines changed: 54 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,16 @@ final class AppState: ObservableObject {
3232
@Published var ollamaURL = "http://localhost:11434"
3333
@Published var ollamaModels: [String] = []
3434
@Published var ollamaStatus = ""
35+
@Published var normalizePrompt = TextNormalizer.defaultInstruction
36+
@Published var normalizing = false
3537

3638
// Runtime
3739
enum Phase: Equatable { case idle, synthesizing, playing, paused }
3840
@Published var phase: Phase = .idle
3941
@Published var progress: Double = 0 // 0…1 across all chunks
4042
@Published var currentText = "" // text being spoken (overlay label)
41-
@Published var inputText = "" // mirrored into the Generate tab
43+
@Published var inputText = "" // original (top panel / source text)
44+
@Published var scriptText = "" // TTS-friendly script actually sent to the engine (bottom panel)
4245
@Published var chunkIndex = 0 // 1-based chunk being played
4346
@Published var chunkCount = 0
4447
@Published var statusText = ""
@@ -115,15 +118,9 @@ final class AppState: ObservableObject {
115118
player.start(expected: chunks.count)
116119
chunkCount = chunks.count; chunkIndex = 0
117120

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)" : "")
121+
let ident = backendIdentity, vid = voiceId, mid = modelId, sHash = settingsHash
121122
let vName = voiceName, ext = audioExt
122123
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
127124

128125
task = Task { [weak self] in
129126
guard let self else { return }
@@ -141,20 +138,14 @@ final class AppState: ObservableObject {
141138
// "synthesizing" only while waiting for the FIRST chunk
142139
if !startedPlaying {
143140
self.phase = .synthesizing
144-
self.statusText = normalizer != nil ? "정규화·합성 중…" : "합성 중…"
141+
if self.statusText.isEmpty { self.statusText = "합성 중…" }
145142
}
146143
if backend == nil { backend = self.makeBackend() }
147144
guard let b = backend else {
148145
self.phase = .idle; self.statusText = "키/백엔드 미설정"; return
149146
}
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-
}
156147
var data = Data()
157-
for try await c in b.stream(segment: ttsText, voice: voice) {
148+
for try await c in b.stream(segment: chunk, voice: voice) {
158149
try Task.checkCancellation(); data.append(c)
159150
}
160151
if self.useCache {
@@ -185,6 +176,51 @@ final class AppState: ObservableObject {
185176
}
186177
}
187178

179+
// MARK: - Script (TTS-friendly text)
180+
181+
/// Build the TTS script from inputText: normalize per paragraph via the LLM
182+
/// when enabled, otherwise pass the original through. Returns the script and
183+
/// fills `scriptText` (the bottom panel).
184+
@discardableResult
185+
func prepareScript() async -> String {
186+
let src = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
187+
guard !src.isEmpty else { scriptText = ""; return "" }
188+
guard normalizeEnabled else { scriptText = src; return src }
189+
190+
normalizing = true
191+
let norm = TextNormalizer(
192+
baseURL: URL(string: ollamaURL) ?? URL(string: "http://localhost:11434")!,
193+
model: ollamaModel, instruction: normalizePrompt)
194+
var out: [String] = []
195+
for p in TextSplitter.paragraphs(src, maxChars: maxChunkChars) {
196+
out.append((try? await norm.normalize(p)) ?? p)
197+
}
198+
let script = out.joined(separator: "\n")
199+
scriptText = script
200+
normalizing = false
201+
return script
202+
}
203+
204+
/// Generate-tab "재생": speak the script (or the original if it is empty).
205+
func speakScript() {
206+
let s = scriptText.trimmingCharacters(in: .whitespacesAndNewlines)
207+
synthesize(s.isEmpty ? inputText : scriptText)
208+
}
209+
210+
/// Services entry: set the source, build the script, then speak it.
211+
func speakSelected(_ text: String) {
212+
task?.cancel(); player.stop()
213+
inputText = text
214+
scriptText = ""
215+
phase = .synthesizing
216+
statusText = normalizeEnabled ? "대본 생성 중…" : "합성 중…"
217+
Task { [weak self] in
218+
guard let self else { return }
219+
let script = await self.prepareScript()
220+
self.synthesize(script)
221+
}
222+
}
223+
188224
func replay(_ e: HistoryEntry) {
189225
task?.cancel(); player.stop()
190226
guard let url = cache.fileURL(forKey: e.id) else { statusText = "오디오 파일 없음"; return }
@@ -257,6 +293,7 @@ final class AppState: ObservableObject {
257293
"backend": backendKind.rawValue, "useCache": useCache, "localBaseURL": localBaseURL,
258294
"maxChunkChars": maxChunkChars,
259295
"normalize": normalizeEnabled, "ollamaModel": ollamaModel, "ollamaURL": ollamaURL,
296+
"normalizePrompt": normalizePrompt,
260297
"stability": voiceSettings.stability, "similarity": voiceSettings.similarityBoost,
261298
"style": voiceSettings.style, "speakerBoost": voiceSettings.useSpeakerBoost,
262299
]
@@ -278,6 +315,7 @@ final class AppState: ObservableObject {
278315
normalizeEnabled = o["normalize"] as? Bool ?? normalizeEnabled
279316
ollamaModel = o["ollamaModel"] as? String ?? ollamaModel
280317
ollamaURL = o["ollamaURL"] as? String ?? ollamaURL
318+
normalizePrompt = o["normalizePrompt"] as? String ?? normalizePrompt
281319
voiceSettings.stability = o["stability"] as? Double ?? voiceSettings.stability
282320
voiceSettings.similarityBoost = o["similarity"] as? Double ?? voiceSettings.similarityBoost
283321
voiceSettings.style = o["style"] as? Double ?? voiceSettings.style

‎Sources/TTS/TextNormalizer.swift‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@ import Foundation
77
struct TextNormalizer {
88
let baseURL: URL
99
let model: String
10+
let instruction: String
1011

11-
private static let instruction = """
12+
static let defaultInstruction = """
1213
당신은 TTS(음성 합성)가 정확히 읽도록 텍스트를 다듬는 전처리기입니다.
1314
의미와 문장 구조는 그대로 두고, 잘못 읽힐 수 있는 표기만 한국어 발음대로 풀어 씁니다.
1415
규칙:
@@ -20,7 +21,8 @@ struct TextNormalizer {
2021
"""
2122

2223
func normalize(_ text: String) async throws -> String {
23-
let prompt = "\(Self.instruction)\n\n원문:\n\(text)\n\n변환:"
24+
let instr = instruction.isEmpty ? Self.defaultInstruction : instruction
25+
let prompt = "\(instr)\n\n원문:\n\(text)\n\n변환:"
2426
var req = URLRequest(url: baseURL.appendingPathComponent("api/generate"))
2527
req.httpMethod = "POST"
2628
req.setValue("application/json", forHTTPHeaderField: "Content-Type")

‎Sources/UI/GenerateView.swift‎

Lines changed: 56 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,82 @@
11
import SwiftUI
22

3-
/// Direct text input → synthesize + play. The editor is bound to AppState.inputText
4-
/// so text read via the Services menu also appears here.
3+
/// Two-panel generation: top = original (source) text, bottom = the TTS-friendly
4+
/// script actually sent to the engine. A collapsible panel manages the
5+
/// normalization prompt.
56
struct GenerateView: View {
67
@EnvironmentObject var app: AppState
8+
@State private var showPrompt = false
79

10+
private var canPrepare: Bool {
11+
!app.inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !app.normalizing
12+
}
813
private var canPlay: Bool {
9-
!app.inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
14+
let s = app.scriptText.isEmpty ? app.inputText : app.scriptText
15+
return !s.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
1016
}
1117

1218
var body: some View {
13-
VStack(alignment: .leading, spacing: 12) {
14-
Text("텍스트 입력").font(.headline)
15-
19+
VStack(alignment: .leading, spacing: 8) {
20+
Text("원본 텍스트").font(.headline)
1621
TextEditor(text: $app.inputText)
17-
.font(.body)
18-
.frame(minHeight: 200)
22+
.font(.body).frame(minHeight: 110)
1923
.overlay(RoundedRectangle(cornerRadius: 6).stroke(.quaternary))
2024

21-
HStack(spacing: 10) {
25+
HStack(spacing: 8) {
2226
Button {
23-
app.synthesize(app.inputText)
27+
Task { await app.prepareScript() }
2428
} label: {
25-
Label("생성 / 재생", systemImage: "play.fill")
29+
Label(app.normalizeEnabled ? "TTS 대본 생성" : "대본으로 복사",
30+
systemImage: "wand.and.stars")
2631
}
27-
.keyboardShortcut(.return, modifiers: .command)
28-
.disabled(!canPlay)
29-
30-
Button {
31-
app.stop()
32-
} label: {
33-
Label("중지", systemImage: "stop.fill")
32+
.disabled(!canPrepare)
33+
if app.normalizing {
34+
ProgressView().controlSize(.small)
35+
Text("대본 생성 중…").font(.caption).foregroundStyle(.secondary)
36+
}
37+
Spacer()
38+
Image(systemName: "arrow.down").foregroundStyle(.secondary)
39+
if !app.normalizeEnabled {
40+
Text("정규화 꺼짐 (설정)").font(.caption).foregroundStyle(.secondary)
3441
}
35-
.disabled(!app.isBusy)
42+
}
43+
44+
Text("TTS 대본 — 실제 합성에 사용").font(.headline)
45+
TextEditor(text: $app.scriptText)
46+
.font(.body).frame(minHeight: 110)
47+
.overlay(RoundedRectangle(cornerRadius: 6).stroke(.quaternary))
3648

49+
HStack(spacing: 10) {
50+
Button { app.speakScript() } label: { Label("재생", systemImage: "play.fill") }
51+
.keyboardShortcut(.return, modifiers: .command)
52+
.disabled(!canPlay)
53+
Button { app.stop() } label: { Label("중지", systemImage: "stop.fill") }
54+
.disabled(!app.isBusy)
3755
if app.isBusy { ProgressView().controlSize(.small) }
3856
Text(statusLine).font(.callout).foregroundStyle(.secondary)
3957
Spacer()
4058
}
4159

42-
Text("보이스: \(app.voiceName) · 모델: \(app.modelId) · 캐시: \(app.useCache ? "켜짐" : "꺼짐")")
60+
DisclosureGroup("프롬프트 관리", isExpanded: $showPrompt) {
61+
VStack(alignment: .leading, spacing: 6) {
62+
Text("정규화 지시문 — LLM에게 주는 규칙").font(.caption).foregroundStyle(.secondary)
63+
TextEditor(text: $app.normalizePrompt)
64+
.font(.callout.monospaced()).frame(minHeight: 110)
65+
.overlay(RoundedRectangle(cornerRadius: 6).stroke(.quaternary))
66+
HStack {
67+
Button("기본값 복원") {
68+
app.normalizePrompt = TextNormalizer.defaultInstruction
69+
app.saveSettings()
70+
}
71+
Spacer()
72+
}
73+
}
74+
.padding(.top, 4)
75+
.onChange(of: app.normalizePrompt) { _, _ in app.saveSettings() }
76+
}
77+
78+
Text("보이스: \(app.voiceName) · 모델: \(app.modelId)")
4379
.font(.caption).foregroundStyle(.secondary)
44-
Spacer()
4580
}
4681
.padding()
4782
}

0 commit comments

Comments
 (0)