Skip to content

Commit ad07d1e

Browse files
Lee Seongjooclaude
andcommitted
Normalization provider: Google Gemini (API) or Ollama (local/remote)
Don't insist on a local model — let normalization use an API or a local server: - Normalizing protocol; GeminiNormalizer (generativelanguage API, x-goog-api-key) alongside the Ollama TextNormalizer. AppState.makeNormalizer() picks by provider; prepareScript falls back to passthrough if no normalizer/key. - Settings: provider picker (Gemini default) → Gemini model + API key entry (stored in Application Support, gitignored) OR Ollama model + URL. The Ollama URL accepts a remote endpoint (e.g. http://host:11434), not just localhost. - Secrets gains generic key read/write; build.sh installs Sidecar/.gemini_key if present. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent a6dc5f9 commit ad07d1e

6 files changed

Lines changed: 139 additions & 30 deletions

File tree

‎.gitignore‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ __pycache__/
1313
# macOS
1414
.DS_Store
1515

16-
# ElevenLabs API key (never commit)
16+
# API keys (never commit)
1717
.eleven_key
18+
.gemini_key
1819
*.key
1920
*.mp3

‎Sources/App/AppState.swift‎

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,16 @@ 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)
29+
// TTS-friendly text normalization (LLM: Gemini API or local Ollama)
30+
enum NormalizeProvider: String, CaseIterable, Identifiable {
31+
case gemini, ollama
32+
var id: String { rawValue }
33+
var label: String { self == .gemini ? "Gemini (API)" : "Ollama (로컬)" }
34+
}
3035
@Published var normalizeEnabled = false
36+
@Published var normalizeProvider: NormalizeProvider = .gemini
37+
@Published var geminiModel = "gemini-2.0-flash"
38+
@Published var geminiKeyPresent = Secrets.geminiKey != nil
3139
@Published var ollamaModel = "gemma4:31b-cloud" // 3B local models garble Korean numbers; a strong model is needed
3240
@Published var ollamaURL = "http://localhost:11434"
3341
@Published var ollamaModels: [String] = []
@@ -176,6 +184,24 @@ final class AppState: ObservableObject {
176184
}
177185
}
178186

187+
private func makeNormalizer() -> Normalizing? {
188+
switch normalizeProvider {
189+
case .gemini:
190+
guard let key = Secrets.geminiKey else { return nil }
191+
return GeminiNormalizer(apiKey: key, model: geminiModel, instruction: normalizePrompt)
192+
case .ollama:
193+
return TextNormalizer(
194+
baseURL: URL(string: ollamaURL) ?? URL(string: "http://localhost:11434")!,
195+
model: ollamaModel, instruction: normalizePrompt)
196+
}
197+
}
198+
199+
func saveGeminiKey(_ key: String) {
200+
let k = key.trimmingCharacters(in: .whitespacesAndNewlines)
201+
Secrets.writeKey(named: "gemini_key", k)
202+
geminiKeyPresent = !k.isEmpty
203+
}
204+
179205
// MARK: - Script (TTS-friendly text)
180206

181207
/// Build the TTS script from inputText: normalize per paragraph via the LLM
@@ -185,12 +211,9 @@ final class AppState: ObservableObject {
185211
func prepareScript() async -> String {
186212
let src = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
187213
guard !src.isEmpty else { scriptText = ""; return "" }
188-
guard normalizeEnabled else { scriptText = src; return src }
214+
guard normalizeEnabled, let norm = makeNormalizer() else { scriptText = src; return src }
189215

190216
normalizing = true
191-
let norm = TextNormalizer(
192-
baseURL: URL(string: ollamaURL) ?? URL(string: "http://localhost:11434")!,
193-
model: ollamaModel, instruction: normalizePrompt)
194217
var out: [String] = []
195218
for p in TextSplitter.paragraphs(src, maxChars: maxChunkChars) {
196219
out.append((try? await norm.normalize(p)) ?? p)
@@ -294,6 +317,7 @@ final class AppState: ObservableObject {
294317
"maxChunkChars": maxChunkChars,
295318
"normalize": normalizeEnabled, "ollamaModel": ollamaModel, "ollamaURL": ollamaURL,
296319
"normalizePrompt": normalizePrompt,
320+
"normalizeProvider": normalizeProvider.rawValue, "geminiModel": geminiModel,
297321
"stability": voiceSettings.stability, "similarity": voiceSettings.similarityBoost,
298322
"style": voiceSettings.style, "speakerBoost": voiceSettings.useSpeakerBoost,
299323
]
@@ -316,6 +340,8 @@ final class AppState: ObservableObject {
316340
ollamaModel = o["ollamaModel"] as? String ?? ollamaModel
317341
ollamaURL = o["ollamaURL"] as? String ?? ollamaURL
318342
normalizePrompt = o["normalizePrompt"] as? String ?? normalizePrompt
343+
normalizeProvider = NormalizeProvider(rawValue: o["normalizeProvider"] as? String ?? "") ?? normalizeProvider
344+
geminiModel = o["geminiModel"] as? String ?? geminiModel
319345
voiceSettings.stability = o["stability"] as? Double ?? voiceSettings.stability
320346
voiceSettings.similarityBoost = o["similarity"] as? Double ?? voiceSettings.similarityBoost
321347
voiceSettings.style = o["style"] as? Double ?? voiceSettings.style

‎Sources/App/Secrets.swift‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,19 @@ enum Secrets {
77
static let appSupportDir = ("~/Library/Application Support/Codebasic TTS"
88
as NSString).expandingTildeInPath
99

10-
static var elevenLabsKey: String? {
11-
let path = (appSupportDir as NSString).appendingPathComponent("eleven_key")
10+
static var elevenLabsKey: String? { key(named: "eleven_key") }
11+
static var geminiKey: String? { key(named: "gemini_key") }
12+
13+
static func key(named name: String) -> String? {
14+
let path = (appSupportDir as NSString).appendingPathComponent(name)
1215
guard let raw = try? String(contentsOfFile: path, encoding: .utf8) else { return nil }
1316
let key = raw.trimmingCharacters(in: .whitespacesAndNewlines)
1417
return key.isEmpty ? nil : key
1518
}
19+
20+
static func writeKey(named name: String, _ value: String) {
21+
try? FileManager.default.createDirectory(atPath: appSupportDir, withIntermediateDirectories: true)
22+
let path = (appSupportDir as NSString).appendingPathComponent(name)
23+
try? value.write(toFile: path, atomically: true, encoding: .utf8)
24+
}
1625
}

‎Sources/TTS/TextNormalizer.swift‎

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,19 @@
11
import Foundation
22

33
/// 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 {
4+
/// notation, subscripts, symbols). Implementations call an LLM (local or API);
5+
/// callers fall back to the original text on failure so synthesis never blocks.
6+
protocol Normalizing {
7+
func normalize(_ text: String) async throws -> String
8+
}
9+
10+
func normalizationPrompt(_ instruction: String, _ text: String) -> String {
11+
let instr = instruction.isEmpty ? TextNormalizer.defaultInstruction : instruction
12+
return "\(instr)\n\n원문:\n\(text)\n\n변환:"
13+
}
14+
15+
/// Local LLM via Ollama.
16+
struct TextNormalizer: Normalizing {
817
let baseURL: URL
918
let model: String
1019
let instruction: String
@@ -21,8 +30,7 @@ struct TextNormalizer {
2130
"""
2231

2332
func normalize(_ text: String) async throws -> String {
24-
let instr = instruction.isEmpty ? Self.defaultInstruction : instruction
25-
let prompt = "\(instr)\n\n원문:\n\(text)\n\n변환:"
33+
let prompt = normalizationPrompt(instruction, text)
2634
var req = URLRequest(url: baseURL.appendingPathComponent("api/generate"))
2735
req.httpMethod = "POST"
2836
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
@@ -45,6 +53,42 @@ struct TextNormalizer {
4553
}
4654
}
4755

56+
/// Google Gemini API normalizer.
57+
struct GeminiNormalizer: Normalizing {
58+
let apiKey: String
59+
let model: String // e.g. "gemini-2.0-flash"
60+
let instruction: String
61+
62+
static let models = ["gemini-2.0-flash", "gemini-2.5-flash", "gemini-1.5-flash"]
63+
64+
func normalize(_ text: String) async throws -> String {
65+
let prompt = normalizationPrompt(instruction, text)
66+
let url = URL(string:
67+
"https://generativelanguage.googleapis.com/v1beta/models/\(model):generateContent")!
68+
var req = URLRequest(url: url)
69+
req.httpMethod = "POST"
70+
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
71+
req.setValue(apiKey, forHTTPHeaderField: "x-goog-api-key")
72+
req.timeoutInterval = 60
73+
req.httpBody = try JSONSerialization.data(withJSONObject: [
74+
"contents": [["parts": [["text": prompt]]]],
75+
"generationConfig": ["temperature": 0.2],
76+
])
77+
let (data, response) = try await URLSession.shared.data(for: req)
78+
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
79+
let msg = String(data: data, encoding: .utf8) ?? "request failed"
80+
throw NSError(domain: "Gemini", code: (response as? HTTPURLResponse)?.statusCode ?? -1,
81+
userInfo: [NSLocalizedDescriptionKey: msg])
82+
}
83+
let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
84+
let cands = obj?["candidates"] as? [[String: Any]]
85+
let content = cands?.first?["content"] as? [String: Any]
86+
let parts = content?["parts"] as? [[String: Any]]
87+
let out = (parts?.first?["text"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
88+
return out.isEmpty ? text : out
89+
}
90+
}
91+
4892
/// Ollama helpers for the UI.
4993
enum Ollama {
5094
static func models(baseURL: URL) async throws -> [String] {

‎Sources/UI/SettingsView.swift‎

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import SwiftUI
33
/// Generation settings: backend, voice, model, voice tuning, cache.
44
struct SettingsView: View {
55
@EnvironmentObject var app: AppState
6+
@State private var geminiKeyInput = ""
67

78
var body: some View {
89
Form {
@@ -48,32 +49,54 @@ struct SettingsView: View {
4849
.font(.caption).foregroundStyle(.secondary)
4950
}
5051

51-
Section("TTS 친화 정규화 (Ollama)") {
52+
Section("TTS 친화 정규화") {
5253
Toggle("숫자·수식 표기를 발음대로 정규화", isOn: $app.normalizeEnabled)
53-
if app.ollamaModels.isEmpty {
54-
LabeledContent("모델") {
55-
TextField("qwen2.5:3b", text: $app.ollamaModel).frame(width: 160)
54+
Picker("제공자", selection: $app.normalizeProvider) {
55+
ForEach(AppState.NormalizeProvider.allCases) { Text($0.label).tag($0) }
56+
}
57+
58+
if app.normalizeProvider == .gemini {
59+
Picker("모델", selection: $app.geminiModel) {
60+
ForEach(GeminiNormalizer.models, id: \.self) { Text($0).tag($0) }
61+
}
62+
LabeledContent("API 키", value: app.geminiKeyPresent ? "설정됨" : "없음")
63+
SecureField("Gemini API 키 (AIza…)", text: $geminiKeyInput)
64+
HStack {
65+
Button("키 저장") { app.saveGeminiKey(geminiKeyInput); geminiKeyInput = "" }
66+
.disabled(geminiKeyInput.trimmingCharacters(in: .whitespaces).isEmpty)
67+
Spacer()
68+
Text("App Support에 저장됩니다").font(.caption).foregroundStyle(.secondary)
5669
}
5770
} else {
58-
Picker("모델", selection: $app.ollamaModel) {
59-
ForEach(app.ollamaModels, id: \.self) { Text($0).tag($0) }
71+
if app.ollamaModels.isEmpty {
72+
LabeledContent("모델") {
73+
TextField("qwen2.5:3b", text: $app.ollamaModel).frame(width: 180)
74+
}
75+
} else {
76+
Picker("모델", selection: $app.ollamaModel) {
77+
ForEach(app.ollamaModels, id: \.self) { Text($0).tag($0) }
78+
}
79+
}
80+
LabeledContent("Ollama URL (로컬/원격)") {
81+
TextField("http://localhost:11434", text: $app.ollamaURL).frame(width: 250)
82+
}
83+
Text("원격 Ollama도 가능: 예) http://192.168.0.10:11434")
84+
.font(.caption).foregroundStyle(.secondary)
85+
HStack {
86+
Button("연결 확인 / 모델 목록") { app.refreshOllamaModels() }
87+
Spacer()
88+
Text(app.ollamaStatus).font(.caption).foregroundStyle(.secondary)
6089
}
6190
}
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→더블유 일 처럼 다듬은 뒤 합성합니다. 켜면 캐시도 분리됩니다.")
91+
Text("0.5→영 점 오, w1→더블유 일 처럼 다듬어 합성합니다. 경량 로컬 모델은 숫자 읽기가 부정확할 수 있어 Gemini를 권장합니다.")
7192
.font(.caption).foregroundStyle(.secondary)
7293
}
7394
}
7495
.formStyle(.grouped)
7596
.onAppear { if app.ollamaModels.isEmpty { app.refreshOllamaModels() } }
7697
.onChange(of: app.normalizeEnabled) { _, _ in app.saveSettings() }
98+
.onChange(of: app.normalizeProvider) { _, _ in app.saveSettings() }
99+
.onChange(of: app.geminiModel) { _, _ in app.saveSettings() }
77100
.onChange(of: app.ollamaModel) { _, _ in app.saveSettings() }
78101
.onChange(of: app.ollamaURL) { _, _ in app.saveSettings() }
79102
.onChange(of: app.maxChunkChars) { _, _ in app.saveSettings() }

‎build.sh‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,16 @@ install_and_register() {
6767
mkdir -p "$appsup"
6868
tr -d ' \n\r' < "$HERE/Sidecar/.eleven_key" > "$appsup/eleven_key"
6969
chmod 600 "$appsup/eleven_key"
70-
echo " key -> $appsup/eleven_key"
70+
echo " eleven key -> $appsup/eleven_key"
7171
else
7272
echo " (no Sidecar/.eleven_key — speech will be disabled)"
7373
fi
74+
if [ -f "$HERE/Sidecar/.gemini_key" ]; then
75+
mkdir -p "$appsup"
76+
tr -d ' \n\r' < "$HERE/Sidecar/.gemini_key" > "$appsup/gemini_key"
77+
chmod 600 "$appsup/gemini_key"
78+
echo " gemini key -> $appsup/gemini_key"
79+
fi
7480

7581
echo "==> Registering with Launch Services"
7682
"$LSREGISTER" -f "$INSTALL_DIR/$APP_NAME.app"

0 commit comments

Comments
 (0)