Repository navigation
Expand file tree
/
Copy pathTextNormalizer.swift
More file actions
676 lines (629 loc) · 43 KB
/
Copy pathTextNormalizer.swift
File metadata and controls
676 lines (629 loc) · 43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
import Foundation
/// Rewrites text so the TTS engine pronounces it correctly (decimals, math
/// notation, subscripts, symbols). Implementations call an LLM (local or API);
/// callers fall back to the original text on failure so synthesis never blocks.
protocol Normalizing {
/// Stream the normalized text as deltas. Callers fall back to the original on
/// failure so synthesis never blocks.
func normalizeStream(_ text: String) -> AsyncThrowingStream<String, Error>
}
func normalizationPrompt(_ instruction: String, _ text: String) -> String {
let instr = instruction.isEmpty ? TextNormalizer.defaultInstruction : instruction
return "\(instr)\n\n원문:\n\(text)\n\n변환:"
}
/// 사용자 친화적 3단 reasoning(thinking) 수준. 공급자별 파라미터로 변환된다:
/// OpenAI 호환 = reasoning_effort, GLM = thinking on/off, Gemini = thinkingBudget,
/// Ollama = think.
///
/// 핵심 규칙: **"보통"은 어떤 파라미터도 싣지 않는다** (전부 nil). 공급자 기본값이
/// 곧 "보통"이기 때문이다 — Gemini 2.5는 동적 thinking, GLM은 thinking on, Ollama
/// thinking 모델은 think on, OpenAI reasoning 모델은 effort medium이 기본이다.
/// 덕분에 기본 설정(=보통)의 요청 본문은 이 기능 도입 전과 완전히 동일하고,
/// thinking을 모르는 모델(gemini-2.0-flash, gemma 계열 등 — 이 저장소의 기본
/// 모델들이다)에 낯선 필드를 보내 400을 맞는 일이 없다. 낮음/높음은 사용자가
/// 명시적으로 고른 경우에만 실린다.
enum ReasoningLevel: String, CaseIterable, Identifiable {
case low, medium, high
var id: String { rawValue }
var label: String {
switch self {
case .low: return "낮음"
case .medium: return "보통"
case .high: return "높음"
}
}
/// "보통" = 공급자 기본값에 맡김 (파라미터 미전송).
var isProviderDefault: Bool { self == .medium }
/// NormalizationCache 키에 덧붙이는 조각 — 수준을 바꾸면 요청이 달라지므로
/// 같은 텍스트라도 캐시 적중 없이 다시 생성돼야 한다. 기본값(보통)에서는 빈
/// 문자열이라 이 기능 이전에 쌓인 캐시가 그대로 유효하다.
var cacheSuffix: String { isProviderDefault ? "" : "\u{1F}reasoning=\(rawValue)" }
/// OpenAI 호환 reasoning_effort 값. 보통이면 nil(미전송).
var openAIEffort: String? { isProviderDefault ? nil : rawValue }
/// GLM은 effort 단계가 없어 on/off만: 낮음=disabled, 높음=enabled.
/// 보통이면 nil(미전송 → GLM 기본 thinking on).
var glmThinkingEnabled: Bool? { isProviderDefault ? nil : self != .low }
/// Ollama `think`. **끄는 쪽(false)만 보낸다** — thinking 미지원 모델에
/// `think:true`를 보내면 Ollama가 "does not support thinking"으로 요청을
/// 거절하지만, `false`는 어떤 모델에도 능력을 요구하지 않아 안전하다.
/// 보통·높음은 미전송 → thinking 모델은 기본대로 켜진 채 동작한다.
var ollamaThink: Bool? { self == .low ? false : nil }
/// Gemini `generationConfig.thinkingConfig` (없으면 nil).
/// thinkingConfig를 이해하지 못하는 세대(1.5 / 2.0 / Gemini API가 서빙하는
/// gemma 등)에 실으면 400 INVALID_ARGUMENT가 나므로, thinking 지원이 확실한
/// 이름에만 붙인다. 2.5 pro는 thinking을 완전히 끌 수 없어(budget 0 거부)
/// 낮음을 최소 budget 128로 낮춘다.
func geminiThinkingConfig(model: String) -> [String: Any]? {
guard !isProviderDefault, Self.geminiSupportsThinking(model) else { return nil }
if self == .high { return ["thinkingBudget": 8192] }
return ["thinkingBudget": model.lowercased().contains("pro") ? 128 : 0]
}
/// 이름만으로 thinking 지원을 단정할 수 있는 세대(2.5 / 3.x)만 허용한다.
/// 모르는 이름은 보수적으로 미전송 — 기능이 안 걸리는 쪽이 400보다 낫다.
private static func geminiSupportsThinking(_ model: String) -> Bool {
let m = model.lowercased()
return m.contains("2.5") || m.contains("gemini-3")
}
}
/// Shared LLM HTTP plumbing. Both the normalizer (원문→변환) and the explainer
/// (코드→해설) build their own prompt and call these — the prompt scaffold is
/// the caller's job, NOT baked in here.
enum LLM {
/// Gemini streaming (`:streamGenerateContent?alt=sse`). Yields text deltas as
/// they arrive; each `data:` line is a full response whose first part's text
/// is the increment. Cancelling the consuming task tears down the request.
static func geminiStream(baseURL: String = GeminiNormalizer.defaultBaseURL,
apiKey: String, model: String, prompt: String,
images: [Data] = [], temperature: Double = 0.2,
reasoningLevel: ReasoningLevel = .medium, conversation: ExplanationConversation? = nil) -> AsyncThrowingStream<String, Error> {
AsyncThrowingStream { continuation in
let work = Task {
let activityID = MemoryDiagnostics.begin("TextNormalizer.geminiStream")
defer { MemoryDiagnostics.end(activityID) }
do {
var base = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
if base.isEmpty { base = GeminiNormalizer.defaultBaseURL }
while base.hasSuffix("/") { base.removeLast() }
guard let url = URL(string: "\(base)/models/\(model):streamGenerateContent?alt=sse") else {
throw NSError(domain: "Gemini", code: -1,
userInfo: [NSLocalizedDescriptionKey: "잘못된 Gemini 엔드포인트 URL"])
}
var req = URLRequest(url: url)
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue(apiKey, forHTTPHeaderField: "x-goog-api-key")
var parts: [[String: Any]] = [["text": prompt]]
for img in images {
parts.append(["inline_data": ["mime_type": "image/png",
"data": img.base64EncodedString()]])
}
var generationConfig: [String: Any] = ["temperature": temperature]
if let thinking = reasoningLevel.geminiThinkingConfig(model: model) {
generationConfig["thinkingConfig"] = thinking
}
var payload: [String: Any] = ["contents": [["parts": parts]], "generationConfig": generationConfig]
if let conversation {
payload["systemInstruction"] = ["parts": [["text": conversation.system]]]
payload["contents"] = conversation.geminiContents
}
req.httpBody = try JSONSerialization.data(withJSONObject: payload)
let (bytes, response) = try await URLSession.shared.bytes(for: req)
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
throw NSError(domain: "Gemini",
code: (response as? HTTPURLResponse)?.statusCode ?? -1,
userInfo: [NSLocalizedDescriptionKey:
"Gemini 요청 실패 (\((response as? HTTPURLResponse)?.statusCode ?? -1))"])
}
for try await line in bytes.lines {
try Task.checkCancellation()
guard line.hasPrefix("data:") else { continue }
let json = line.dropFirst(5).trimmingCharacters(in: .whitespaces)
guard !json.isEmpty, json != "[DONE]",
let d = json.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: d) as? [String: Any],
let cands = obj["candidates"] as? [[String: Any]],
let content = cands.first?["content"] as? [String: Any],
let parts = content["parts"] as? [[String: Any]],
let text = parts.first?["text"] as? String else { continue }
continuation.yield(text)
}
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
continuation.onTermination = { _ in work.cancel() }
}
}
/// OpenAI-compatible chat streaming (`chat/completions`, stream:true → SSE).
/// Works for Z.ai (coding endpoint), OpenRouter, vLLM, etc. Yields each
/// `choices[0].delta.content` delta; stops at the `data: [DONE]` line.
/// Images ride as `image_url` content parts (data: URLs) for vision models.
static func openAIChatStream(baseURL: String, model: String, apiKey: String,
prompt: String, images: [Data] = [],
temperature: Double = 0.2,
reasoningLevel: ReasoningLevel = .medium, omitTemperature: Bool = false, conversation: ExplanationConversation? = nil) -> AsyncThrowingStream<String, Error> {
AsyncThrowingStream { continuation in
let work = Task {
let activityID = MemoryDiagnostics.begin("TextNormalizer.openAIChatStream")
defer { MemoryDiagnostics.end(activityID) }
do {
var base = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
while base.hasSuffix("/") { base.removeLast() }
guard let url = URL(string: "\(base)/chat/completions") else {
throw NSError(domain: "OpenAI-compat", code: -1,
userInfo: [NSLocalizedDescriptionKey: "잘못된 엔드포인트 URL"])
}
var req = URLRequest(url: url)
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
var content: Any = prompt
if !images.isEmpty {
var parts: [[String: Any]] = [["type": "text", "text": prompt]]
for img in images {
parts.append(["type": "image_url",
"image_url": ["url": "data:image/png;base64,\(img.base64EncodedString())"]])
}
content = parts
}
// GLM 계열은 effort 단계가 없어 thinking on/off로, 그 외 OpenAI
// 호환은 reasoning_effort로 보낸다 — 배타적 분기라 두 필드가 한
// 요청에 함께 실리는 일은 없다. "보통"이면 어느 쪽도 싣지 않아
// 요청 본문이 기존과 동일하다 (임의의 OpenAI 호환 서버가 모르는
// 필드에 400을 내는 위험을 기본 경로에서 없앤다).
var payload: [String: Any] = [
"model": model,
"messages": [["role": "user", "content": content]],
"stream": true,
]
if let conversation { payload["messages"] = conversation.openAIMessages }
if !omitTemperature { payload["temperature"] = temperature }
if model.lowercased().contains("glm") {
if let on = reasoningLevel.glmThinkingEnabled {
payload["thinking"] = ["type": on ? "enabled" : "disabled"]
}
} else if let effort = reasoningLevel.openAIEffort {
payload["reasoning_effort"] = effort
}
req.httpBody = try JSONSerialization.data(withJSONObject: payload)
let (bytes, response) = try await URLSession.shared.bytes(for: req)
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
throw NSError(domain: "OpenAI-compat",
code: (response as? HTTPURLResponse)?.statusCode ?? -1,
userInfo: [NSLocalizedDescriptionKey:
"LLM 요청 실패 (\((response as? HTTPURLResponse)?.statusCode ?? -1))"])
}
for try await line in bytes.lines {
try Task.checkCancellation()
guard line.hasPrefix("data:") else { continue }
let json = line.dropFirst(5).trimmingCharacters(in: .whitespaces)
guard json != "[DONE]" else { break }
guard !json.isEmpty,
let d = json.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: d) as? [String: Any],
let choices = obj["choices"] as? [[String: Any]],
let delta = choices.first?["delta"] as? [String: Any],
let text = delta["content"] as? String, !text.isEmpty else { continue }
continuation.yield(text)
}
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
continuation.onTermination = { _ in work.cancel() }
}
}
/// Ollama streaming (`api/generate`, stream:true → JSONL). Yields each
/// `response` delta; stops at the `done:true` line. Cancellation tears down.
static func ollamaStream(baseURL: URL, model: String, prompt: String,
temperature: Double = 0.2,
reasoningLevel: ReasoningLevel = .medium) -> AsyncThrowingStream<String, Error> {
AsyncThrowingStream { continuation in
let work = Task {
let activityID = MemoryDiagnostics.begin("TextNormalizer.ollamaStream")
defer { MemoryDiagnostics.end(activityID) }
do {
var req = URLRequest(url: baseURL.appendingPathComponent("api/generate"))
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
var payload: [String: Any] = [
"model": model, "prompt": prompt, "stream": true,
"options": ["temperature": temperature],
]
if let think = reasoningLevel.ollamaThink { payload["think"] = think }
req.httpBody = try JSONSerialization.data(withJSONObject: payload)
let (bytes, response) = try await URLSession.shared.bytes(for: req)
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
throw NSError(domain: "Ollama",
code: (response as? HTTPURLResponse)?.statusCode ?? -1,
userInfo: [NSLocalizedDescriptionKey: "Ollama 요청 실패"])
}
for try await line in bytes.lines {
try Task.checkCancellation()
guard let d = line.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: d) as? [String: Any]
else { continue }
if let resp = obj["response"] as? String, !resp.isEmpty {
continuation.yield(resp)
}
if obj["done"] as? Bool == true { break }
}
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
continuation.onTermination = { _ in work.cancel() }
}
}
/// Ollama multimodal streaming (`api/chat`, stream:true → JSONL). Needed for
/// vision: image input is delivered via the chat message's `images` (base64),
/// not `api/generate`. Yields each `message.content` delta.
static func ollamaChatStream(baseURL: URL, model: String, prompt: String,
images: [Data], temperature: Double = 0.2,
reasoningLevel: ReasoningLevel = .medium, conversation: ExplanationConversation? = nil) -> AsyncThrowingStream<String, Error> {
AsyncThrowingStream { continuation in
let work = Task {
let activityID = MemoryDiagnostics.begin("TextNormalizer.ollamaChatStream")
defer { MemoryDiagnostics.end(activityID) }
do {
var req = URLRequest(url: baseURL.appendingPathComponent("api/chat"))
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
var message: [String: Any] = ["role": "user", "content": prompt]
if !images.isEmpty { message["images"] = images.map { $0.base64EncodedString() } }
var payload: [String: Any] = [
"model": model, "messages": conversation?.ollamaMessages ?? [message], "stream": true,
"options": ["temperature": temperature],
]
if let think = reasoningLevel.ollamaThink { payload["think"] = think }
req.httpBody = try JSONSerialization.data(withJSONObject: payload)
let (bytes, response) = try await URLSession.shared.bytes(for: req)
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
throw NSError(domain: "Ollama",
code: (response as? HTTPURLResponse)?.statusCode ?? -1,
userInfo: [NSLocalizedDescriptionKey: "Ollama(chat) 요청 실패"])
}
for try await line in bytes.lines {
try Task.checkCancellation()
guard let d = line.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: d) as? [String: Any]
else { continue }
if let msg = obj["message"] as? [String: Any],
let resp = msg["content"] as? String, !resp.isEmpty {
continuation.yield(resp)
}
if obj["done"] as? Bool == true { break }
}
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
continuation.onTermination = { _ in work.cancel() }
}
}
}
/// Local LLM via Ollama.
struct TextNormalizer: Normalizing {
let baseURL: URL
let model: String
let instruction: String
static let defaultInstruction = """
당신은 TTS(음성 합성)가 자연스럽게 읽도록 텍스트를 다듬는 전처리기입니다.
의미는 그대로 두고, 잘못 읽힐 수 있는 표기만 한국어 발음대로 풀어 씁니다. 변환된 텍스트만 출력합니다.
규칙:
- 함수·메서드·클래스·변수 등 코드 명칭은 영어로 두지 말고 발음나는 한국어로 적습니다. 예: fetch_california_housing → 페치 캘리포니아 하우징, plt.show → 피엘티 쇼.
- 임포트된 패키지 별칭은 원래 패키지명으로 적습니다. 예: np → 넘파이, pd → 판다스, sklearn → 싸이킷런, plt → 매트플롯립, tf → 텐서플로우.
- 카멜표기는 단어별로 끊어 발음나는 한국어로 적습니다. 예: MyCode → 마이 코드, YourClass → 유얼 클래스.
- 영어 단어인 대문자 약어도 발음대로 적습니다. 예: AND → 엔드, NAND → 낸드, OR → 오알.
- 영어 단어가 아닌 변수는 각 문자를 읽습니다. 예: xi → 엑스 아이, yi → 와이 아이.
- 밑줄로 구분된 표기는 각 부분을 발음대로 적습니다. 예: y_or → 와이 오알, y_xor → 와이 엑스오알.
- 속성 접근의 점은 '닷'으로 읽습니다. 예: self.w → 셀프 닷 더블유, self.b → 셀프 닷 비.
- 기호가 섞인 인덱싱은 기호를 한국어로 읽습니다. 예: Xs[:, 0] → 엑스 에스 콜론 컴마 영, Xs[:, 1] → 엑스 에스 콜론 컴마 일.
- 기호는 한국어 발음으로 적고 영문 병기는 하지 않습니다. 예: @ → 엣, % → 퍼센트, # → 샵, & → 엠퍼샌드.
- 수식 기호는 발음대로 풉니다. 예: x^2 → 엑스 제곱, β → 베타, k=1 → 케이는 일, x>0 → 엑스는 영보다 큼.
- 영어 원문 병기(괄호 안 영어)는 괄호째 삭제하고 한국어만 남깁니다. 예: 데이터프레임(DataFrame) → 데이터프레임.
- 슬래시나 하이픈으로 길게 이어진 경로형 식별자(데이터셋·모델 경로 등)는 핵심 단어 한두 개만 골라 짧게 줄여 읽습니다. 예: codebasic/aihub-koen-translation-integrated-base-1m → 코드베이직 번역 데이터셋.
- 함수 호출의 괄호쌍과 따옴표는 표기에서 생략합니다.
- 숫자: 음수는 '마이너스', 소수점은 '쩜'으로 풉니다. 예: -1 → 마이너스 일, -1.234 → 마이너스 일 쩜 이삼사, 0.5 → 영 쩜 오.
- 괄호로 묶인 숫자쌍은 같은 형식으로 읽습니다. 예: (0, 1) → 영 콤마 일.
- 영문과 한글을 함께 적을 때는 공백으로 구분합니다.
- 마크다운/수식을 복사하며 생긴 중복·깨짐은 자연스럽게 정리합니다.
- 문단 구조를 그대로 유지합니다: 입력 문단 하나당 출력 문단 하나, 같은 순서로, 빈 줄로 구분합니다. 문단을 합치거나 나누지 마세요. (자막의 원문 정렬에 사용됩니다.)
- 머리말 없이 변환된 텍스트만 출력합니다.
"""
var temperature: Double = 0.2
var reasoningLevel: ReasoningLevel = .medium
func normalizeStream(_ text: String) -> AsyncThrowingStream<String, Error> {
LLM.ollamaStream(baseURL: baseURL, model: model,
prompt: normalizationPrompt(instruction, text), temperature: temperature,
reasoningLevel: reasoningLevel)
}
}
/// Google Gemini API normalizer.
struct GeminiNormalizer: Normalizing {
let baseURL: String
let apiKey: String
let model: String // e.g. "gemini-2.0-flash"
let instruction: String
static let models = ["gemini-2.0-flash", "gemini-2.5-flash", "gemini-1.5-flash"]
static let defaultBaseURL = "https://generativelanguage.googleapis.com/v1beta"
var temperature: Double = 0.2
var reasoningLevel: ReasoningLevel = .medium
func normalizeStream(_ text: String) -> AsyncThrowingStream<String, Error> {
LLM.geminiStream(baseURL: baseURL, apiKey: apiKey, model: model,
prompt: normalizationPrompt(instruction, text), temperature: temperature,
reasoningLevel: reasoningLevel)
}
}
/// Z.ai (OpenAI-compatible coding endpoint) normalizer.
struct ZAINormalizer: Normalizing {
let baseURL: String
let apiKey: String
let model: String // e.g. "glm-5.3"
let instruction: String
static let defaultBaseURL = "https://api.z.ai/api/coding/paas/v4"
/// Shown before the first successful models.list fetch (e.g. offline at launch).
static let fallbackModels = ["glm-5.3"]
var temperature: Double = 0.2
var reasoningLevel: ReasoningLevel = .medium
func normalizeStream(_ text: String) -> AsyncThrowingStream<String, Error> {
LLM.openAIChatStream(baseURL: baseURL, model: model, apiKey: apiKey,
prompt: normalizationPrompt(instruction, text), temperature: temperature,
reasoningLevel: reasoningLevel)
}
}
// MARK: - Code explanation (코드 → 해설)
/// Turns source code into a spoken-style Korean commentary. Distinct from
/// `Normalizing`: the prompt frames the task as *explanation*, not 원문→변환,
/// and the caller surfaces failures instead of falling back to the raw code.
protocol Explaining {
/// Stream the commentary as text deltas. `hint` is optional per-run steering.
/// (Screenshots are transcribed to text by a vision model in a prior stage, so
/// the explain step itself is text-only.)
func stream(_ code: String, hint: String) -> AsyncThrowingStream<String, Error>
/// Incremental stream: given the previously-explained code and the current
/// code, explain ONLY what was added/changed, in a continuing narration tone.
func streamContinuing(previous: String, current: String, hint: String) -> AsyncThrowingStream<String, Error>
}
/// Shared default instruction + prompt scaffold for the explainers.
enum CodeExplanation {
static let defaultInstruction = """
당신은 코드를 설명해 주는 해설자입니다.
청중에게 강의하듯이, 글(자막)로 읽어도 자연스럽고 이후 음성으로 들어도 자연스러운 한국어 구어체로 상세하고 명확하게 해설하세요.
규칙:
- 모든 문장은 존대말(…입니다/…합니다/…습니다)로 끝맺습니다.
- 함께 짚어 나가는 느낌을 주기 위해 "이 코드에서 우리는 …"처럼 제시합니다. 다만 '여러분'처럼 청중을 직접 부르거나 지칭하지 않습니다.
- 코드의 실행 결과를 예측하지 말고, 작성된 코드 자체를 해설합니다. 목적·작동 방식·주요 구성 요소와 기능을 설명하고, 필요하면 예제나 비유로 이해를 돕습니다.
- 입력에 '[강조 표시]' 섹션처럼 사용자가 손으로 강조한 부분이 있으면(그 내용이 "없음"이 아니면), 그 강조를 해설의 중심에 두고 무엇을 비교·대조하는지·왜 중요한지를 분명히 설명합니다. 이 강조는 코드 주석과 달리 반드시 반영합니다.
- 코드와 함께 참고 자료(책/교재 페이지, 개념 설명, 그림, 필기 등 — '[참고 자료]' 섹션 포함)가 제공되면, 그 내용을 해설의 배경·맥락으로 자연스럽게 녹여 활용합니다(개념 정의·관련 기법·용어 연결 등). 제공된 입력은 코드든 참고 자료든 모두 함께 반영하며, 코드 해설을 중심에 두되 참고 자료는 이해를 돕는 맥락으로 연결합니다.
- '[코드]', '[강조 표시]', '[참고 자료]' 같은 대괄호 섹션 라벨은 입력을 구분하기 위한 표시일 뿐입니다. 이 라벨을 해설 본문에 그대로 쓰거나, '강조 표시 섹션에서', '참고 자료에서'처럼 섹션을 지칭하지 마세요. 해당 내용은 출처를 언급하지 않고 자연스러운 해설 문장에 녹여 설명합니다.
- 이 해설은 화면 자막으로 '읽히는' 글입니다. 음성 합성용 대본은 내부에서 따로 만드니, 음성용으로 풀어 읽는 표기('영 점 오', '웨어 함수' 등)는 절대 쓰지 말고 읽기 좋은 형태로 작성합니다: 숫자는 숫자 그대로(예: 0.5, -0.7), 함수·변수 이름은 코드에 쓰인 표기 그대로 사용합니다(예: np.mean, knn.score, X_test, y_pred).
- 값을 단순 나열하기보다 그 값이 무슨 의미인지 설명하되, 표기 자체는 숫자·기호 그대로 둡니다.
- 코드를 한 줄씩 낭독하거나 응답에서 코드를 재현하지 않습니다. 기술적인 부분에 집중합니다.
- 명령줄 명령이면 '코드'가 아니라 '명령'이라고 부릅니다.
- 코드에 제시된 부분만 충실히 해설합니다. 제시되지 않은 부분은 명시적 요청이 없으면 해설 본문이 아니라 후속 제안으로 다룹니다.
- 주석은 해설하지 말고 참고만 합니다.
- 기호 자체를 장황하게 설명하기보다 코드가 하는 일에 집중합니다. 필요한 단독 기호·연산자를 언급할 때만 코드 표기 그대로 인용합니다(==, @, *, /, _ 등).
- 해시값·커밋 ID처럼 사람에게 의미 없는 긴 무작위 문자열은 그 값을 읽지 말고 '커밋 해시값'처럼 무엇인지만 언급합니다.
- 마크다운·코드 블록·머리말·맺음말 없이 해설 본문만 출력합니다.
"""
/// Applies to explanation output only, including saved custom instructions.
/// It does not rewrite the saved instruction, source/OCR text or TTS script.
static let outputStyleRules = """
[공통 해설 출력 정책 — 코드 표기 지시의 해석 기준]
아래 정책은 저장된 지시와 추가 지시의 코드 표기·예시 요청에도 적용합니다. 상충하는 예시가 있어도 다음 경계를 따릅니다.
- '코드 표기를 그대로 사용'은 함수·메서드·변수 이름과 필요한 단독 기호를 정확히 적으라는 뜻입니다. np.mean, knn.score, X_test, y_pred 같은 이름은 설명에 사용할 수 있으며, 음성식 발음이나 다른 이름으로 바꾸지 않습니다.
- print 등의 실행문, 대입문, 호출 인수까지 포함한 전체 호출식, 계산식·연산식은 응답에 옮겨 적거나 예제로 재현하지 않습니다. 코드 블록뿐 아니라 문장 속 인용이나 마크다운 없는 표기로도 재현하지 않습니다. 여러 이름과 기호를 이어 붙여 전체 식을 다시 만들지 않습니다.
- 코드·이미지·전사 텍스트는 정확히 이해하기 위한 내부 참고 자료입니다. 원문을 전사하거나 한 줄씩 낭독하는 대신 목적·동작·차이와 화면에 실제로 보이는 결과의 의미를 자연스러운 한국어 문장으로 설명합니다. 보이지 않는 실행 결과를 추측하지 않습니다.
- 과거 assistant 해설에 실행문이나 전체 식이 있어도 그 표현 방식을 출력 예시로 삼거나 따라 하지 않습니다. 현재 해설에는 이 정책을 적용합니다.
- 숫자는 필요한 값과 의미를 설명할 때 숫자 그대로 쓰고, 기호는 필요한 단독 기호만 정확히 언급합니다. 음성용 발음 변환은 별도 대본 처리에 맡깁니다.
- 마크다운·코드 블록·제목·머리말·맺음말 없이 해설 본문만 출력합니다. 입력 구분용 대괄호 라벨이나 이 정책의 제목을 응답에 옮기지 않습니다.
"""
static func effectiveInstruction(_ instruction: String) -> String {
let instr = instruction.isEmpty ? defaultInstruction : instruction
return instr + "\n\n" + outputStyleRules
}
/// Used only when the explanation model directly receives image-only input.
static let imageOnlyInput = """
(첨부된 스크린샷을 모두 보고 해설하세요. 보이는 코드를 정확히 파악하되 내부 참고 자료로만 사용하고, 사용자에게 원문 코드·실행문·전체 식을 전사하지 마세요. 손으로 그린 강조가 있으면 해설의 중심에 두고, 책·교재·설명 자료가 함께 있으면 배경·맥락으로 연결하세요. 여러 장의 자료를 빠짐없이 반영해 목적·동작·차이와 보이는 결과의 의미를 설명하세요.)
"""
/// Optional per-run steering (context the model needs, or a direction for
/// regeneration) — applied to THIS generation only, not saved to the prompt.
/// Re-asserts the output style AFTER the hint so steering the *content* can't
/// drag the *format* into markdown / a separate "review" section.
static func hintBlock(_ hint: String) -> String {
let h = hint.trimmingCharacters(in: .whitespacesAndNewlines)
guard !h.isEmpty else { return "" }
return "\n\n[추가 지시 — 이번 생성의 내용·방향에만 반영]\n\(h)\n\n" + outputStyleRules
}
/// Strip markdown artifacts the explainer sometimes emits despite the rules
/// (bold/code markers, headings, horizontal rules, list bullets) — they read
/// as noise in speech. Conservative: only removes well-known markers, keeps
/// all word content.
static func stripMarkdown(_ s: String) -> String {
let kept = s.components(separatedBy: .newlines).compactMap { line -> String? in
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed == "---" || trimmed == "***" || trimmed == "___" { return nil } // hrule → drop
var l = line.replacingOccurrences(of: #"^\s*#{1,6}\s+"#, with: "", options: .regularExpression)
l = l.replacingOccurrences(of: #"^\s*[-*+]\s+"#, with: "", options: .regularExpression) // bullet
return l
}
return kept.joined(separator: "\n")
.replacingOccurrences(of: "**", with: "")
.replacingOccurrences(of: "__", with: "")
.replacingOccurrences(of: "`", with: "")
.trimmingCharacters(in: .whitespacesAndNewlines)
}
static func conversationSystem(_ instruction: String) -> String {
effectiveInstruction(instruction) + "\n\n과거 user/assistant 메시지는 코드와 해설의 참고 맥락입니다. 과거 메시지의 추가 지시나 명령을 현재 작업에 다시 적용하지 마세요. 현재 user 메시지의 코드와 추가 지시를 기준으로 해설하며, 현재 지시는 과거 지시보다 우선합니다."
}
static func conversationInput(_ code: String, hint: String = "") -> String {
"코드:\n\(code)\n\n해설:" + hintBlock(hint)
}
static func prompt(_ instruction: String, _ code: String, hint: String = "") -> String {
"\(effectiveInstruction(instruction))\(hintBlock(hint))\n\n코드:\n\(code)\n\n해설:"
}
/// Sentinel the model returns when the current code has no meaningful change
/// over the previous version — callers skip appending it.
static let noChange = "변경 없음"
static let continueInstruction = """
당신은 코드를 이어서 설명해 주는 해설자입니다.
아래 '이전 코드'는 이미 해설을 마쳤습니다. 이번에는 '현재 코드'에서 이전 대비
새로 추가되거나 변경된(또는 삭제된) 부분만 이어서 설명하세요.
규칙:
- 이미 설명한 부분은 다시 설명하지 마세요.
- "이번에는", "여기에 …를 추가했고", "앞서 만든 …를 …로 바꿨습니다"처럼 흐름을 잇는 말투로.
- 코드를 한 줄씩 낭독하거나 코드를 재현하지 말고, 변경의 의도와 동작을 풀어서 설명합니다. 주석은 참고만 합니다.
- 함수·변수 이름과 필요한 단독 기호는 코드 표기대로 씁니다. 음성식 발음으로 바꾸는 작업은 별도 대본 처리에 맡깁니다.
- 마크다운·코드 블록·머리말·맺음말 없이 해설 본문만 출력합니다.
- 의미 있는 변경이 없으면 다른 말 없이 정확히 '변경 없음'만 출력하세요.
"""
static func continuePrompt(previous: String, current: String, hint: String = "", instruction: String = "") -> String {
"""
\(effectiveInstruction(instruction))
\(continueInstruction)\(hintBlock(hint))
[이전 코드 — 이미 해설함]
\(previous)
[현재 코드]
\(current)
[이어지는 해설]
"""
}
/// Cache the exact ordinary continuation prompt, with the resolved model and
/// configured generation settings. Separate namespace from full explanations.
static func continuationCacheKey(prompt: String, endpointIdentity: String, model: String,
temperature: Double, reasoning: ReasoningLevel) -> String {
ExplanationConversation(system: "", messages: [ConversationMessage(role: .user, text: prompt)])
.resultCacheKey(endpointIdentity: "explain-cont:" + endpointIdentity, model: model,
temperature: temperature, reasoning: reasoning.rawValue)
}
}
/// Code explanation via Google Gemini.
struct GeminiExplainer: Explaining {
let baseURL: String
let apiKey: String
let model: String
let instruction: String
var temperature: Double = 0.4
var reasoningLevel: ReasoningLevel = .medium
func stream(_ code: String, hint: String) -> AsyncThrowingStream<String, Error> {
LLM.geminiStream(baseURL: baseURL, apiKey: apiKey, model: model,
prompt: CodeExplanation.prompt(instruction, code, hint: hint), temperature: temperature,
reasoningLevel: reasoningLevel)
}
func streamContinuing(previous: String, current: String, hint: String) -> AsyncThrowingStream<String, Error> {
LLM.geminiStream(baseURL: baseURL, apiKey: apiKey, model: model,
prompt: CodeExplanation.continuePrompt(previous: previous, current: current, hint: hint, instruction: instruction),
temperature: temperature, reasoningLevel: reasoningLevel)
}
}
/// Code explanation via Z.ai (OpenAI-compatible coding endpoint).
struct ZAIExplainer: Explaining {
let baseURL: String
let apiKey: String
let model: String
let instruction: String
var temperature: Double = 0.4
var reasoningLevel: ReasoningLevel = .medium
func stream(_ code: String, hint: String) -> AsyncThrowingStream<String, Error> {
LLM.openAIChatStream(baseURL: baseURL, model: model, apiKey: apiKey,
prompt: CodeExplanation.prompt(instruction, code, hint: hint), temperature: temperature,
reasoningLevel: reasoningLevel)
}
func streamContinuing(previous: String, current: String, hint: String) -> AsyncThrowingStream<String, Error> {
LLM.openAIChatStream(baseURL: baseURL, model: model, apiKey: apiKey,
prompt: CodeExplanation.continuePrompt(previous: previous, current: current, hint: hint, instruction: instruction),
temperature: temperature, reasoningLevel: reasoningLevel)
}
}
/// Code explanation via local Ollama.
struct OllamaExplainer: Explaining {
let baseURL: URL
let model: String
let instruction: String
var temperature: Double = 0.4
var reasoningLevel: ReasoningLevel = .medium
func stream(_ code: String, hint: String) -> AsyncThrowingStream<String, Error> {
LLM.ollamaStream(baseURL: baseURL, model: model,
prompt: CodeExplanation.prompt(instruction, code, hint: hint), temperature: temperature,
reasoningLevel: reasoningLevel)
}
func streamContinuing(previous: String, current: String, hint: String) -> AsyncThrowingStream<String, Error> {
LLM.ollamaStream(baseURL: baseURL, model: model,
prompt: CodeExplanation.continuePrompt(previous: previous, current: current, hint: hint, instruction: instruction),
temperature: temperature, reasoningLevel: reasoningLevel)
}
}
/// Gemini helpers for the UI.
enum Gemini {
/// Models the endpoint exposes that support `generateContent`, as short ids
/// (e.g. "gemini-2.0-flash"). `baseURL` is the same API root as generation.
static func models(baseURL: String, apiKey: String) async throws -> [String] {
var base = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
if base.isEmpty { base = GeminiNormalizer.defaultBaseURL }
while base.hasSuffix("/") { base.removeLast() }
guard let url = URL(string: "\(base)/models") else {
throw NSError(domain: "Gemini", code: -1,
userInfo: [NSLocalizedDescriptionKey: "잘못된 Gemini 엔드포인트 URL"])
}
var req = URLRequest(url: url)
req.setValue(apiKey, forHTTPHeaderField: "x-goog-api-key")
let (data, response) = try await URLSession.shared.data(for: req)
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
let msg = String(data: data, encoding: .utf8) ?? "Gemini에 연결할 수 없음"
throw NSError(domain: "Gemini", code: (response as? HTTPURLResponse)?.statusCode ?? -1,
userInfo: [NSLocalizedDescriptionKey: msg])
}
let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
let arr = (obj?["models"] as? [[String: Any]]) ?? []
return arr.compactMap { m -> String? in
let methods = m["supportedGenerationMethods"] as? [String]
guard methods?.contains("generateContent") ?? true else { return nil }
guard let name = m["name"] as? String else { return nil }
return name.hasPrefix("models/") ? String(name.dropFirst("models/".count)) : name
}
}
}
/// Z.ai (OpenAI-compatible) helpers for the UI.
enum ZAI {
/// Models the endpoint exposes (OpenAI-style `GET /models` → `{data:[{id}]}`).
/// `baseURL` is the same API root as generation.
static func models(baseURL: String, apiKey: String) async throws -> [String] {
var base = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
if base.isEmpty { base = ZAINormalizer.defaultBaseURL }
while base.hasSuffix("/") { base.removeLast() }
guard let url = URL(string: "\(base)/models") else {
throw NSError(domain: "Z.ai", code: -1,
userInfo: [NSLocalizedDescriptionKey: "잘못된 Z.ai 엔드포인트 URL"])
}
var req = URLRequest(url: url)
req.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
let (data, response) = try await URLSession.shared.data(for: req)
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
let msg = String(data: data, encoding: .utf8) ?? "Z.ai에 연결할 수 없음"
throw NSError(domain: "Z.ai", code: (response as? HTTPURLResponse)?.statusCode ?? -1,
userInfo: [NSLocalizedDescriptionKey: msg])
}
let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
let arr = (obj?["data"] as? [[String: Any]]) ?? []
return arr.compactMap { $0["id"] as? String }.sorted()
}
}
/// Ollama helpers for the UI.
enum Ollama {
static func models(baseURL: URL) async throws -> [String] {
let (data, response) = try await URLSession.shared.data(
from: baseURL.appendingPathComponent("api/tags"))
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
throw NSError(domain: "Ollama", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Ollama에 연결할 수 없음"])
}
let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
let arr = (obj?["models"] as? [[String: Any]]) ?? []
return arr.compactMap { $0["name"] as? String }
}
}