|
| 1 | +import Foundation |
| 2 | +import Combine |
| 3 | + |
| 4 | +/// Single source of truth for the UI and the speak path. Holds connection, |
| 5 | +/// settings, history, and runs synthesis (cache-first) + playback. |
| 6 | +@MainActor |
| 7 | +final class AppState: ObservableObject { |
| 8 | + |
| 9 | + enum BackendKind: String, CaseIterable, Identifiable { |
| 10 | + case elevenlabs, local |
| 11 | + var id: String { rawValue } |
| 12 | + var label: String { self == .elevenlabs ? "ElevenLabs (클라우드)" : "로컬 (sidecar)" } |
| 13 | + } |
| 14 | + |
| 15 | + // Connection |
| 16 | + @Published var keyPresent: Bool = Secrets.elevenLabsKey != nil |
| 17 | + @Published var backendKind: BackendKind = .elevenlabs |
| 18 | + @Published var voices: [ElevenVoice] = [] |
| 19 | + @Published var connectionStatus = "" |
| 20 | + |
| 21 | + // Settings |
| 22 | + @Published var voiceId = "Yp1WZJMrN7OSdP8PG9sm" // 성주 (cloned) |
| 23 | + @Published var voiceName = "성주" |
| 24 | + @Published var modelId = "eleven_flash_v2_5" |
| 25 | + @Published var voiceSettings = ElevenVoiceSettings() |
| 26 | + @Published var useCache = true |
| 27 | + @Published var localBaseURL = "http://127.0.0.1:8765" |
| 28 | + |
| 29 | + // Runtime |
| 30 | + @Published var isWorking = false |
| 31 | + @Published var statusText = "" |
| 32 | + @Published private(set) var history: [HistoryEntry] = [] |
| 33 | + |
| 34 | + private let cache = CacheStore() |
| 35 | + private let player = AudioPlayer() |
| 36 | + private var task: Task<Void, Never>? |
| 37 | + |
| 38 | + init() { |
| 39 | + loadSettings() |
| 40 | + history = cache.entries |
| 41 | + player.onFinish = { [weak self] in self?.finish() } |
| 42 | + } |
| 43 | + |
| 44 | + private func finish() { isWorking = false; statusText = "" } |
| 45 | + |
| 46 | + var backendIdentity: String { backendKind == .elevenlabs ? "elevenlabs" : "qwen3-local" } |
| 47 | + var settingsHash: String { backendKind == .elevenlabs ? voiceSettings.hash : "" } |
| 48 | + var audioExt: String { backendKind == .elevenlabs ? "mp3" : "wav" } |
| 49 | + |
| 50 | + private func makeBackend() -> TTSBackend? { |
| 51 | + switch backendKind { |
| 52 | + case .elevenlabs: |
| 53 | + guard let key = Secrets.elevenLabsKey else { return nil } |
| 54 | + return ElevenLabsBackend(apiKey: key, settings: voiceSettings) |
| 55 | + case .local: |
| 56 | + return Qwen3MLXBackend(identity: backendIdentity, |
| 57 | + baseURL: URL(string: localBaseURL) ?? URL(string: "http://127.0.0.1:8765")!) |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + // MARK: - Synthesize (cache-first) |
| 62 | + |
| 63 | + func synthesize(_ text: String) { |
| 64 | + let t = text.trimmingCharacters(in: .whitespacesAndNewlines) |
| 65 | + guard !t.isEmpty else { return } |
| 66 | + task?.cancel(); player.stop() |
| 67 | + |
| 68 | + let key = CacheStore.key(text: t, backend: backendIdentity, |
| 69 | + voiceId: voiceId, modelId: modelId, settingsHash: settingsHash) |
| 70 | + if useCache, let data = cache.data(forKey: key) { |
| 71 | + cache.touch(key); history = cache.entries |
| 72 | + isWorking = true; statusText = "캐시에서 재생" |
| 73 | + try? player.play(data) |
| 74 | + return |
| 75 | + } |
| 76 | + guard let backend = makeBackend() else { statusText = "키/백엔드 미설정"; return } |
| 77 | + isWorking = true; statusText = "합성 중…" |
| 78 | + let voice = VoiceConfig(voiceId: voiceId, modelId: modelId, settingsHash: settingsHash) |
| 79 | + let vName = voiceName, ident = backendIdentity, ext = audioExt |
| 80 | + task = Task { [weak self] in |
| 81 | + guard let self else { return } |
| 82 | + do { |
| 83 | + var data = Data() |
| 84 | + for try await chunk in backend.stream(segment: t, voice: voice) { |
| 85 | + try Task.checkCancellation(); data.append(chunk) |
| 86 | + } |
| 87 | + if self.useCache { |
| 88 | + self.cache.save(key: key, text: t, backend: ident, voiceId: self.voiceId, |
| 89 | + voiceName: vName, modelId: self.modelId, ext: ext, data: data) |
| 90 | + self.history = self.cache.entries |
| 91 | + } |
| 92 | + self.statusText = "재생 중…" |
| 93 | + try self.player.play(data) |
| 94 | + } catch is CancellationError { |
| 95 | + self.finish() |
| 96 | + } catch { |
| 97 | + self.isWorking = false |
| 98 | + self.statusText = "오류: \(error.localizedDescription)" |
| 99 | + } |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + func replay(_ e: HistoryEntry) { |
| 104 | + task?.cancel(); player.stop() |
| 105 | + guard let data = cache.data(forKey: e.id) else { statusText = "오디오 파일 없음"; return } |
| 106 | + cache.touch(e.id); history = cache.entries |
| 107 | + isWorking = true; statusText = "캐시에서 재생" |
| 108 | + try? player.play(data) |
| 109 | + } |
| 110 | + |
| 111 | + func stop() { task?.cancel(); player.stop(); finish() } |
| 112 | + |
| 113 | + func deleteHistory(_ id: String) { cache.delete(id); history = cache.entries } |
| 114 | + func clearHistory() { cache.clear(); history = cache.entries } |
| 115 | + |
| 116 | + // MARK: - Connection |
| 117 | + |
| 118 | + func saveKey(_ key: String) { |
| 119 | + let k = key.trimmingCharacters(in: .whitespacesAndNewlines) |
| 120 | + try? FileManager.default.createDirectory(atPath: Secrets.appSupportDir, |
| 121 | + withIntermediateDirectories: true) |
| 122 | + let path = (Secrets.appSupportDir as NSString).appendingPathComponent("eleven_key") |
| 123 | + try? k.write(toFile: path, atomically: true, encoding: .utf8) |
| 124 | + keyPresent = !k.isEmpty |
| 125 | + connectionStatus = k.isEmpty ? "키 삭제됨" : "키 저장됨" |
| 126 | + if !k.isEmpty { refreshVoices() } |
| 127 | + } |
| 128 | + |
| 129 | + func refreshVoices() { |
| 130 | + guard let key = Secrets.elevenLabsKey else { connectionStatus = "키 없음"; return } |
| 131 | + connectionStatus = "연결 확인 중…" |
| 132 | + Task { [weak self] in |
| 133 | + do { |
| 134 | + let vs = try await ElevenLabs.voices(apiKey: key) |
| 135 | + guard let self else { return } |
| 136 | + self.voices = vs |
| 137 | + self.connectionStatus = "연결됨 · 보이스 \(vs.count)개" |
| 138 | + if let v = vs.first(where: { $0.id == self.voiceId }) { self.voiceName = v.name } |
| 139 | + } catch { |
| 140 | + self?.connectionStatus = "연결 실패: \(error.localizedDescription)" |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + // MARK: - Settings persistence |
| 146 | + |
| 147 | + private var settingsURL: URL { |
| 148 | + URL(fileURLWithPath: (Secrets.appSupportDir as NSString).appendingPathComponent("settings.json")) |
| 149 | + } |
| 150 | + |
| 151 | + func saveSettings() { |
| 152 | + let dict: [String: Any] = [ |
| 153 | + "voiceId": voiceId, "voiceName": voiceName, "modelId": modelId, |
| 154 | + "backend": backendKind.rawValue, "useCache": useCache, "localBaseURL": localBaseURL, |
| 155 | + "stability": voiceSettings.stability, "similarity": voiceSettings.similarityBoost, |
| 156 | + "style": voiceSettings.style, "speakerBoost": voiceSettings.useSpeakerBoost, |
| 157 | + ] |
| 158 | + if let d = try? JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted]) { |
| 159 | + try? d.write(to: settingsURL) |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + private func loadSettings() { |
| 164 | + guard let d = try? Data(contentsOf: settingsURL), |
| 165 | + let o = try? JSONSerialization.jsonObject(with: d) as? [String: Any] else { return } |
| 166 | + voiceId = o["voiceId"] as? String ?? voiceId |
| 167 | + voiceName = o["voiceName"] as? String ?? voiceName |
| 168 | + modelId = o["modelId"] as? String ?? modelId |
| 169 | + backendKind = BackendKind(rawValue: o["backend"] as? String ?? "") ?? backendKind |
| 170 | + useCache = o["useCache"] as? Bool ?? useCache |
| 171 | + localBaseURL = o["localBaseURL"] as? String ?? localBaseURL |
| 172 | + voiceSettings.stability = o["stability"] as? Double ?? voiceSettings.stability |
| 173 | + voiceSettings.similarityBoost = o["similarity"] as? Double ?? voiceSettings.similarityBoost |
| 174 | + voiceSettings.style = o["style"] as? Double ?? voiceSettings.style |
| 175 | + voiceSettings.useSpeakerBoost = o["speakerBoost"] as? Bool ?? voiceSettings.useSpeakerBoost |
| 176 | + } |
| 177 | +} |
0 commit comments