Skip to content

Commit 41f9062

Browse files
Lee Seongjooclaude
andcommitted
해설: generate reading-friendly prose, normalize a TTS 대본 internally
The explainer used to produce TTS-spelled prose ('영 점 오', '웨어 함수'), which reads badly as a subtitle. Now it produces reading-friendly text (0.5, np.where, x @ w) shown in the panel + subtitle, and the 해설 read paths build the spoken 대본 internally via ttsScript(for:) (follows the 대본 정규화 toggle), speaking that while the subtitle shows the 해설 (synthesize(_:displayText:)). - Rewrite CodeExplanation.defaultInstruction: drop the speak-it-out rules, keep digits/code tokens as written; and forbid echoing the input section labels ('[코드]'/'[강조 표시]'/'[참고 자료]') into the prose - explainAndSpeak / speakExplanation / speakContinue normalize then speak - 해설 탭: '전체 재생' is now the primary action; 'TTS로 보내기' demoted to the advanced "inspect/edit the 대본" path; help text corrected Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 6354a66 commit 41f9062

3 files changed

Lines changed: 62 additions & 21 deletions

File tree

‎Sources/App/AppState.swift‎

Lines changed: 48 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -786,8 +786,16 @@ final class AppState: ObservableObject {
786786
func speakContinue() {
787787
let seg = lastSegment.trimmingCharacters(in: .whitespacesAndNewlines)
788788
guard !seg.isEmpty else { return }
789+
cancelActiveWork()
789790
playbackMode = .explain
790-
synthesize(TextSplitter.cleanInput(seg)) // read the latest 해설 segment directly
791+
phase = .synthesizing
792+
let reading = TextSplitter.cleanInput(seg)
793+
scriptTask = Task { [weak self] in
794+
guard let self else { return }
795+
let tts = await self.ttsScript(for: reading) // 음성용 대본은 내부에서만
796+
guard !Task.isCancelled else { return }
797+
self.synthesize(tts, displayText: reading) // 자막은 읽기 좋은 해설
798+
}
791799
}
792800

793801
/// 해설 탭 → 생성 탭: hand the commentary to the script pipeline as its source.
@@ -799,20 +807,51 @@ final class AppState: ObservableObject {
799807
selectedTab = 0 // switch to TTS
800808
}
801809

802-
/// 해설 탭 "전체 재생": read the 해설 directly (no normalize pass). The 음성 대본
803-
/// (정규화된 TTS 대본) lives in the TTS 탭 — send the 해설 there with "TTS로
804-
/// 보내기" when you want that. Does not touch the TTS 탭 panels.
810+
/// 해설 탭 "전체 재생": speak the 해설. The 해설 itself is reading-friendly
811+
/// (shown as the subtitle); the spoken audio uses an internal TTS 대본
812+
/// normalized from it (when 대본 정규화 is on). Does not touch the TTS 탭 panels.
805813
func speakExplanation() {
806814
let text = TextSplitter.cleanInput(explanationText)
807815
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
816+
cancelActiveWork()
808817
playbackMode = .explain
809-
synthesize(text)
818+
phase = .synthesizing
819+
scriptTask = Task { [weak self] in
820+
guard let self else { return }
821+
let tts = await self.ttsScript(for: text) // 음성용 대본은 내부에서만
822+
guard !Task.isCancelled else { return }
823+
self.synthesize(tts, displayText: text) // 자막은 읽기 좋은 해설
824+
}
810825
}
811826

812827
/// Services entry ("코드 해설"): stream the explanation of the selected code,
813828
/// then read the 해설 directly (음성 대본 is an opt-in panel step, not used in
814829
/// the one-shot). Code is fed RAW; a failed/cancelled explanation never falls
815830
/// through to speaking the source. Runs under `explainTask` so 중지 cancels it.
831+
/// Build the speech 대본 for already-readable prose (e.g. a 해설): when 대본
832+
/// 정규화 is enabled, normalize it for TTS (spell numbers/symbols); else read
833+
/// the prose as-is. Cached by content. On cancel/error, falls back to `text`.
834+
private func ttsScript(for text: String) async -> String {
835+
let src = text.trimmingCharacters(in: .whitespacesAndNewlines)
836+
let instruction = scriptInstruction()
837+
guard normalizeEnabled, !src.isEmpty,
838+
let norm = makeNormalizer(instruction: instruction) else { return text }
839+
let nk = NormalizationCache.key(text: src, provider: scriptProvider.rawValue,
840+
model: scriptModel, prompt: instruction)
841+
if let cached = normCache.script(forKey: nk) { return cached }
842+
normalizing = true
843+
defer { normalizing = false }
844+
statusText = "음성 대본 준비 중…"
845+
var acc = ""
846+
do {
847+
for try await delta in norm.normalizeStream(src) { try Task.checkCancellation(); acc += delta }
848+
} catch { return text } // cancel/error → read the prose as-is
849+
let out = acc.trimmingCharacters(in: .whitespacesAndNewlines)
850+
let final = out.isEmpty ? text : out
851+
normCache.put(key: nk, script: final)
852+
return final
853+
}
854+
816855
func explainAndSpeak(_ code: String) {
817856
cancelActiveWork()
818857
playbackMode = .explain
@@ -827,7 +866,10 @@ final class AppState: ObservableObject {
827866
if self.statusText.isEmpty { self.statusText = "해설 생성 실패" }
828867
return // do NOT speak raw code
829868
}
830-
self.synthesize(TextSplitter.cleanInput(explanation))
869+
let reading = TextSplitter.cleanInput(explanation) // 자막: 읽기 좋은 해설
870+
let tts = await self.ttsScript(for: reading) // 음성: 내부 대본(정규화 토글 따름)
871+
guard !Task.isCancelled else { return }
872+
self.synthesize(tts, displayText: reading)
831873
}
832874
}
833875

‎Sources/TTS/TextNormalizer.swift‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -231,24 +231,23 @@ protocol Explaining {
231231
/// Shared default instruction + prompt scaffold for the explainers.
232232
enum CodeExplanation {
233233
static let defaultInstruction = """
234-
당신은 코드를 음성으로 설명해 주는 해설자입니다.
235-
청중에게 강의하듯이, 작성된 해설이 그대로 읽혔을 때 자연스럽게 들리도록 한국어 구어체로 상세하고 명확하게 해설하세요.
234+
당신은 코드를 설명해 주는 해설자입니다.
235+
청중에게 강의하듯이, 글(자막)로 읽어도 자연스럽고 이후 음성으로 들어도 자연스러운 한국어 구어체로 상세하고 명확하게 해설하세요.
236236
규칙:
237237
- 모든 문장은 존대말(…입니다/…합니다/…습니다)로 끝맺습니다.
238238
- 함께 짚어 나가는 느낌을 주기 위해 "이 코드에서 우리는 …"처럼 제시합니다. 다만 '여러분'처럼 청중을 직접 부르거나 지칭하지 않습니다.
239239
- 코드의 실행 결과를 예측하지 말고, 작성된 코드 자체를 해설합니다. 목적·작동 방식·주요 구성 요소와 기능을 설명하고, 필요하면 예제나 비유로 이해를 돕습니다.
240240
- 입력에 '[강조 표시]' 섹션처럼 사용자가 손으로 강조한 부분이 있으면(그 내용이 "없음"이 아니면), 그 강조를 해설의 중심에 두고 무엇을 비교·대조하는지·왜 중요한지를 분명히 설명합니다. 이 강조는 코드 주석과 달리 반드시 반영합니다.
241241
- 코드와 함께 참고 자료(책/교재 페이지, 개념 설명, 그림, 필기 등 — '[참고 자료]' 섹션 포함)가 제공되면, 그 내용을 해설의 배경·맥락으로 자연스럽게 녹여 활용합니다(개념 정의·관련 기법·용어 연결 등). 제공된 입력은 코드든 참고 자료든 모두 함께 반영하며, 코드 해설을 중심에 두되 참고 자료는 이해를 돕는 맥락으로 연결합니다.
242-
- 숫자 값은 그대로 읽기보다 그 값이 무슨 의미인지 해설합니다. 연산자 기호가 섞여 의미가 어려우면 코드 동작을 더 자세히 풀어 설명합니다.
242+
- '[코드]', '[강조 표시]', '[참고 자료]' 같은 대괄호 섹션 라벨은 입력을 구분하기 위한 표시일 뿐입니다. 이 라벨을 해설 본문에 그대로 쓰거나, '강조 표시 섹션에서', '참고 자료에서'처럼 섹션을 지칭하지 마세요. 해당 내용은 출처를 언급하지 않고 자연스러운 해설 문장에 녹여 설명합니다.
243+
- 이 해설은 화면 자막으로 '읽히는' 글입니다. 음성 합성용 대본은 내부에서 따로 만드니, 음성용으로 풀어 읽는 표기('영 점 오', '웨어 함수' 등)는 절대 쓰지 말고 읽기 좋은 형태로 작성합니다: 숫자는 숫자 그대로(예: 0.5, -0.7), 함수·변수·연산자 등 코드 요소는 코드에 쓰인 표기 그대로 사용합니다(예: np.where, Xs, x @ w).
244+
- 값을 단순 나열하기보다 그 값이 무슨 의미인지 설명하되, 표기 자체는 숫자·기호 그대로 둡니다.
243245
- 코드를 한 줄씩 낭독하거나 응답에서 코드를 재현하지 않습니다. 기술적인 부분에 집중합니다.
244246
- 명령줄 명령이면 '코드'가 아니라 '명령'이라고 부릅니다.
245247
- 코드에 제시된 부분만 충실히 해설합니다. 제시되지 않은 부분은 명시적 요청이 없으면 해설 본문이 아니라 후속 제안으로 다룹니다.
246248
- 주석은 해설하지 말고 참고만 합니다.
247-
- 음성으로 들을 것이므로 기호를 나열하지 말고 풀어서 말합니다. 예: i++ → 아이를 하나 증가, == → 같은지 비교.
248-
- 괄호 열고 닫기는 특별한 이유 없이 해설하지 않습니다. 슬래시(/, \\), 언더바(_), 하이픈(-)은 읽지 않습니다.
249+
- 기호 자체를 장황하게 설명하기보다 코드가 하는 일에 집중합니다. 다만 기호·연산자를 언급할 때는 코드 표기 그대로 인용합니다(i++, ==, @, *, /, _ 등).
249250
- 해시값·커밋 ID처럼 사람에게 의미 없는 긴 무작위 문자열은 그 값을 읽지 말고 '커밋 해시값'처럼 무엇인지만 언급합니다.
250-
- 정규식 등의 별표(*) 같은 특수 기호는 발음대로 풀어 말하되 실제 기호는 표기하지 않습니다.
251-
예: **/*.jpg → "별표 두 개는 모든 폴더를, 별표 한 개는 모든 파일을 의미합니다".
252251
- 마크다운·코드 블록·머리말·맺음말 없이 해설 본문만 출력합니다.
253252
"""
254253

‎Sources/UI/CommentaryView.swift‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -173,21 +173,21 @@ struct CommentaryView: View {
173173
.overlay(border)
174174

175175
HStack(spacing: 10) {
176-
Button { app.sendExplanationToGenerate() } label: {
177-
Label("TTS로 보내기", systemImage: "arrow.right.circle.fill")
178-
}
179-
.buttonStyle(.borderedProminent)
180-
.disabled(explanationEmpty)
181-
.help("해설을 TTS 탭으로 보내 음성 대본(정규화)을 만들고 재생합니다")
182-
183176
Button { app.speakExplanation() } label: { Label("전체 재생", systemImage: "play.fill") }
177+
.buttonStyle(.borderedProminent)
184178
.disabled(explanationEmpty || app.isBusy || app.explaining)
185-
.help("해설을 그대로 읽습니다 (음성 대본 정규화는 TTS 탭)")
179+
.help("해설을 재생합니다. 자막은 이 해설 그대로, 음성은 내부 대본(설정 → 음성 대본 정규화가 켜져 있으면 정규화)으로 읽습니다")
186180
Button { app.speakContinue() } label: { Label("이어서 읽기", systemImage: "forward.end.fill") }
187181
.disabled(!app.hasLastSegment || app.explaining)
188182
.help("마지막에 추가된 해설을 이어서 읽습니다 (재생 중이면 멈추고 그 부분을 재생)")
189183
Button { app.stop() } label: { Label("중지", systemImage: "stop.fill") }
190184
.disabled(!app.isBusy && !app.explaining)
185+
186+
Button { app.sendExplanationToGenerate() } label: {
187+
Label("TTS로 보내기", systemImage: "arrow.right.circle")
188+
}
189+
.disabled(explanationEmpty)
190+
.help("해설을 TTS 탭으로 보내 음성 대본을 직접 보고 다듬은 뒤 재생합니다 (고급)")
191191
if app.isBusy { ProgressView().controlSize(.small) }
192192
Text(app.statusText).font(.callout).foregroundStyle(.secondary)
193193
Spacer()

0 commit comments

Comments
 (0)