Skip to content

Commit 94f5df7

Browse files
Lee Seongjooclaude
andcommitted
Single-call image explain when the 해설 model is the vision model
- If a screenshot is attached AND the vision model equals the 해설 model (a multimodal model picked for both), skip the transcribe stage: that model reads the screenshot and explains in ONE streamed call (text code + image + hint all in one request via explainStreamWithImages). Avoids transcription loss — it reads the actual code (e.g. /=) and the annotations directly. Different vision/ text models still use the two-stage (transcribe → explain) path. - Vision model: add a "되돌리기" button (shown when overridden) that clears the override so it follows the 해설 model again; status shows 추종 vs 별도 지정. - Drop the per-picker refresh icon (redundant — 설정 has refresh buttons and the picker auto-refreshes on appear); saving a Gemini key now refreshes its model list so Gemini models appear in the combined picker immediately. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent da4e8b7 commit 94f5df7

3 files changed

Lines changed: 48 additions & 9 deletions

File tree

‎Sources/App/AppState.swift‎

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,7 @@ final class AppState: ObservableObject {
352352
let k = key.trimmingCharacters(in: .whitespacesAndNewlines)
353353
Secrets.writeKey(named: "gemini_key", k)
354354
geminiKeyPresent = !k.isEmpty
355+
if !k.isEmpty { refreshGeminiModels() } // populate the combined model list right away
355356
}
356357

357358
// MARK: - Commentary (코드 → 해설)
@@ -369,6 +370,24 @@ final class AppState: ObservableObject {
369370
}
370371
}
371372

373+
/// Single-stage image explain: the 해설 model (== vision model) reads the
374+
/// screenshot(s) and explains in one streamed call, using the explain prompt.
375+
private func explainStreamWithImages(code: String, images: [Data]) -> AsyncThrowingStream<String, Error> {
376+
let prompt = CodeExplanation.prompt(explainPrompt, code, hint: explainHint)
377+
switch explainProvider {
378+
case .gemini:
379+
guard let key = Secrets.geminiKey else {
380+
return AsyncThrowingStream { $0.finish() }
381+
}
382+
return LLM.geminiStream(baseURL: geminiBaseURL, apiKey: key, model: explainGeminiModel,
383+
prompt: prompt, images: images, temperature: explainTemperature)
384+
case .ollama:
385+
let url = URL(string: ollamaURL) ?? URL(string: "http://localhost:11434")!
386+
return LLM.ollamaChatStream(baseURL: url, model: explainOllamaModel,
387+
prompt: prompt, images: images, temperature: explainTemperature)
388+
}
389+
}
390+
372391
/// Stable digest of the attached screenshots, for caching the transcription.
373392
private func imagesDigest(_ imgs: [Data]) -> String {
374393
var h = SHA256()
@@ -468,21 +487,32 @@ final class AppState: ObservableObject {
468487
explaining = true
469488
defer { explaining = false }
470489

471-
// Stage 1 (if images): vision model transcribes screenshots → text.
490+
// If a screenshot is attached AND the vision model is the same as the 해설
491+
// model, that model can both read the image and explain in ONE call — skip
492+
// the transcribe stage (less loss, faster). Otherwise: vision transcribes,
493+
// then the text model explains.
494+
let singleStage = !imgs.isEmpty
495+
&& visionProviderEff == explainProvider && visionModelEff == explainModel
496+
472497
var code = typed
473-
if !imgs.isEmpty {
498+
if !imgs.isEmpty && !singleStage {
474499
statusText = "이미지에서 코드 추출 중…"
475500
guard let transcribed = await transcribeImages(imgs) else {
476501
if statusText.isEmpty { statusText = "이미지 인식 실패" }
477502
return nil
478503
}
479504
code = typed.isEmpty ? transcribed : typed + "\n\n" + transcribed
505+
} else if singleStage {
506+
code = typed.isEmpty
507+
? "(첨부된 스크린샷의 코드를 정확히 읽고, 손으로 그린 강조 표시가 있으면 그것을 해설의 중심에 두어 해설하세요.)"
508+
: typed
480509
}
481510
guard !code.isEmpty else { statusText = "해설 생성 실패 (빈 입력)"; return nil }
482511

483-
// Stage 2: the text model explains the combined code.
512+
// Cache key: single-stage feeds the raw image, so fold its digest in.
484513
let provider = "explain:" + explainProvider.rawValue
485-
let nk = NormalizationCache.key(text: code, provider: provider, model: explainModel,
514+
let keyText = singleStage ? code + imagesDigest(imgs) : code
515+
let nk = NormalizationCache.key(text: keyText, provider: provider, model: explainModel,
486516
prompt: explainPrompt + "\u{1F}" + explainHint)
487517
if !force, let cached = normCache.script(forKey: nk) {
488518
explanationText = cached; lastExplainedCode = code; lastSegment = cached; return cached
@@ -491,7 +521,10 @@ final class AppState: ObservableObject {
491521
statusText = "해설 생성 중…"
492522
var acc = ""
493523
do {
494-
for try await delta in explainer.stream(code, hint: explainHint) {
524+
let stream = singleStage
525+
? explainStreamWithImages(code: code, images: imgs)
526+
: explainer.stream(code, hint: explainHint)
527+
for try await delta in stream {
495528
try Task.checkCancellation()
496529
acc += delta
497530
explanationText = acc // live (raw markdown shows until finalize)

‎Sources/UI/CommentaryView.swift‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,16 @@ struct CommentaryView: View {
142142
geminiModel: visionGeminiBinding,
143143
ollamaModel: visionOllamaBinding,
144144
onChange: { app.saveSettings() })
145-
Text("이미지→코드 추출용 (기본=해설 모델). gemma4는 비전 미동작 → gemma3 권장.")
145+
if app.visionOverridden {
146+
Button {
147+
app.visionOverridden = false; app.saveSettings()
148+
} label: { Image(systemName: "arrow.uturn.backward") }
149+
.controlSize(.small)
150+
.help("비전 모델을 해설 모델로 되돌리기 (추종)")
151+
}
152+
Text(app.visionOverridden
153+
? "이미지→코드 추출용 (해설 모델과 별도 지정됨)"
154+
: "이미지→코드 추출용 (해설 모델 추종)")
146155
.font(.caption2).foregroundStyle(.secondary)
147156
Spacer()
148157
}

‎Sources/UI/LLMModelPicker.swift‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,6 @@ struct LLMModelPicker: View {
4242
}
4343
.labelsHidden().frame(maxWidth: 260)
4444
}
45-
Button { app.refreshAllModels() } label: { Image(systemName: "arrow.clockwise") }
46-
.controlSize(.small)
47-
.help("연결된 제공자(Ollama·Gemini)에서 모델 목록 새로고침")
4845
}
4946
.onAppear { app.refreshAllModelsIfNeeded() }
5047
}

0 commit comments

Comments
 (0)