Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift
T
schihei 2a601058f4 feat(capture): translate long selections in parts
The capture gate and the chunk size were the same number, so a selection above one chunk was rejected before the pipeline could split it; the Settings sliders moved both thresholds together. Add maximumPartsPerSelection (1-8, default 1, so existing behaviour is unchanged). The capture limit is now part size x parts and travels on TranslationSessionRequest, so the watcher, CapturePolicy and TranslationSession agree for that capture. TranslationStreaming gained an optional per-part callback; the session emits chunkStarted and the panel shows 'Part 2 of 4' while streaming and '2 parts' when finished. textTooLong now points at Settings and offers an Open Settings button. Lower the dense-script part-size maximum to 4000 because 5000 dense characters plus a 4096-token output can overflow the 8192-token context. Tests cover capture limits, watcher limits, pipeline part callbacks, session events and limits, panel progress, settings clamping and migration. Docs updated: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES and README. Verified: make verify green; live 4355-character German text showed Part 1 of 2, Part 2 of 2 and '2 parts'; with one part the panel showed the too-long message and Open Settings.
2026-11-27 20:21:30 +01:00

353 lines
12 KiB
Swift

import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
import SprachmittlerText
/// Timing for one completed translation (`docs/ARCHITECTURE.md` §5).
public struct TranslationTiming: Sendable, Equatable {
/// Time to the first delta, when one arrived.
public let firstTokenMs: Int?
/// Total time.
public let totalMs: Int
/// Prompt tokens reported by Ollama, summed over attempts.
public let promptTokens: Int?
/// Output tokens reported by Ollama, summed over attempts.
public let outputTokens: Int?
/// Creates a timing value.
public init(firstTokenMs: Int?, totalMs: Int, promptTokens: Int?, outputTokens: Int?) {
self.firstTokenMs = firstTokenMs
self.totalMs = totalMs
self.promptTokens = promptTokens
self.outputTokens = outputTokens
}
}
/// The result of the documented translation pipeline.
public struct PipelineResult: Sendable, Equatable {
/// The translation after T1 only.
public let translation: String
/// Validation warnings and guard findings from the output validator.
public let warnings: [TranslationWarning]
/// The advisory source language, when detection succeeded.
public let sourceLanguage: String?
/// Timing counters.
public let timing: TranslationTiming
/// How many chunks were translated.
public let chunkCount: Int
/// Creates a result.
public init(
translation: String,
warnings: [TranslationWarning],
sourceLanguage: String?,
timing: TranslationTiming,
chunkCount: Int
) {
self.translation = translation
self.warnings = warnings
self.sourceLanguage = sourceLanguage
self.timing = timing
self.chunkCount = chunkCount
}
}
/// Translates text with the documented prompt, chunking and validation.
///
/// This type is shared by the CLI and the M4 session. It never edits the model output beyond T1
/// and it retries only once, only when a protected token was lost.
public struct TranslationPipeline: Sendable {
private let chat: any OllamaChatting
private let registry: AdapterRegistry
private let detector: any LanguageDetecting
private let chunker: Chunker
private let scanner: ProtectedTokenScanner
private let validator: OutputValidator
private let policy: PromptPolicy
private let clock: @Sendable () -> Date
/// Creates a pipeline. Concrete clients come from the composition root.
public init(
chat: any OllamaChatting,
registry: AdapterRegistry,
detector: any LanguageDetecting = NaturalLanguageDetector(),
chunker: Chunker = Chunker(),
scanner: ProtectedTokenScanner = ProtectedTokenScanner(),
validator: OutputValidator = OutputValidator(),
policy: PromptPolicy = PromptPolicy(),
clock: @escaping @Sendable () -> Date = { Date() }
) {
self.chat = chat
self.registry = registry
self.detector = detector
self.chunker = chunker
self.scanner = scanner
self.validator = validator
self.policy = policy
self.clock = clock
}
/// Translates `text` into `target` with `model`.
public func translate(
text: String,
target: ModelLanguage,
model: String,
keepAlive: String,
sampling: SamplingOptions = .publisherDefault,
onDelta: (@Sendable (String) async -> Void)? = nil,
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)? = nil
) async throws -> PipelineResult {
let normalized = TextNormalization.normalizeInput(text)
guard !normalized.isEmpty else {
throw SprachmittlerError.emptyText
}
guard registry.adapter(for: model) != nil else {
throw SprachmittlerError.noAdapter(model: model)
}
let started = clock()
let detection = detector.detect(normalized)
let content = ContentClassifier(scanner: scanner).classify(normalized)
let tokens = scanner.scan(normalized)
let chunks = chunker.chunks(for: normalized)
let context = TranslationContext(
content: content,
target: target,
model: model,
keepAlive: keepAlive,
sampling: sampling,
tokens: tokens,
onDelta: onDelta
)
let accumulator = try await translateAll(chunks, context: context, onChunk: onChunk)
let final = TextNormalization.normalizeOutput(accumulator.joined)
let validation = validator.validate(
source: normalized,
translation: final,
doneReason: accumulator.sawLength ? "length" : nil,
tokens: tokens
)
var warnings = accumulator.warnings
warnings.append(contentsOf: validation.warnings)
if let detection, LanguageMatching.isSameLanguage(detection, target: target) {
warnings.append(.sameLanguage(source: detection.code, target: target.code))
}
let elapsed = max(0, Int(clock().timeIntervalSince(started) * 1000))
let firstTokenMs = accumulator.firstTokenAt.map { max(0, Int($0.timeIntervalSince(started) * 1000)) }
return PipelineResult(
translation: final,
warnings: deduplicated(warnings),
sourceLanguage: detection?.code,
timing: TranslationTiming(
firstTokenMs: firstTokenMs,
totalMs: elapsed,
promptTokens: accumulator.promptTokens,
outputTokens: accumulator.outputTokens
),
chunkCount: chunks.count
)
}
private struct TranslationContext {
let content: ContentClass
let target: ModelLanguage
let model: String
let keepAlive: String
let sampling: SamplingOptions
let tokens: [ProtectedToken]
let onDelta: (@Sendable (String) async -> Void)?
}
private struct Accumulator {
var firstTokenAt: Date?
var promptTokens: Int?
var outputTokens: Int?
var joined = ""
var warnings: [TranslationWarning] = []
var sawLength = false
}
private func translateAll(
_ chunks: [TextChunk],
context: TranslationContext,
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)?
) async throws -> Accumulator {
var accumulator = Accumulator()
do {
for (offset, chunk) in chunks.enumerated() {
try Task.checkCancellation()
await onChunk?(offset + 1, chunks.count)
let result = try await translateChunk(chunk, context: context)
if accumulator.firstTokenAt == nil {
accumulator.firstTokenAt = result.firstTokenAt
}
accumulator.promptTokens = sum(accumulator.promptTokens, result.promptTokens)
accumulator.outputTokens = sum(accumulator.outputTokens, result.outputTokens)
if result.looped {
accumulator.warnings.append(.repetitionLoop)
}
if result.doneReason == "length" {
accumulator.sawLength = true
}
accumulator.joined += result.text + chunk.separatorAfter
if !chunk.separatorAfter.isEmpty {
await context.onDelta?(chunk.separatorAfter)
}
}
} catch is CancellationError {
throw SprachmittlerError.cancelled
}
return accumulator
}
private struct ChunkTranslation {
let text: String
let doneReason: String?
let looped: Bool
let firstTokenAt: Date?
let promptTokens: Int?
let outputTokens: Int?
}
private func translateChunk(
_ chunk: TextChunk,
context: TranslationContext
) async throws -> ChunkTranslation {
let chunkTokens = context.tokens.filter { chunk.text.contains($0.value) }
var prompt = policy.initialPrompt(for: context.content)
var retried = false
var response = StreamResult(
text: "",
doneReason: nil,
metrics: .empty,
firstTokenAt: nil,
looped: false
)
var promptTokens: Int?
var outputTokens: Int?
while true {
let request = try makeRequest(chunk: chunk, prompt: prompt, context: context)
// A retry replaces the first attempt; do not stream both into the panel.
let deltaHandler = retried ? nil : context.onDelta
let attempt = try await stream(request, onDelta: deltaHandler)
response = attempt
promptTokens = sum(promptTokens, attempt.metrics.promptEvalCount)
outputTokens = sum(outputTokens, attempt.metrics.evalCount)
let translated = TextNormalization.normalizeOutput(attempt.text)
let missing = validator.missingTokens(
source: chunk.text,
translation: translated,
tokens: chunkTokens
)
let retryPrompt = missing.isEmpty
? nil
: policy.retryPrompt(for: context.content, lostToken: missing[0])
if !retried, let retryPrompt {
retried = true
prompt = retryPrompt
continue
}
break
}
return ChunkTranslation(
text: TextNormalization.normalizeOutput(response.text),
doneReason: response.doneReason,
looped: response.looped,
firstTokenAt: response.firstTokenAt,
promptTokens: promptTokens,
outputTokens: outputTokens
)
}
private func makeRequest(
chunk: TextChunk,
prompt: PromptVariant,
context: TranslationContext
) throws -> ChatRequest {
try registry.makeRequest(
AdapterRequest(
text: chunk.text,
target: context.target,
model: context.model,
keepAlive: context.keepAlive,
prompt: prompt,
sampling: context.sampling
)
)
}
private struct StreamResult {
let text: String
let doneReason: String?
let metrics: ChatMetrics
let firstTokenAt: Date?
let looped: Bool
}
private func stream(
_ request: ChatRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> StreamResult {
var text = ""
var doneReason: String?
var metrics = ChatMetrics.empty
var firstTokenAt: Date?
var repetition = RepetitionDetector()
var looped = false
do {
for try await event in chat.chat(request) {
try Task.checkCancellation()
switch event {
case let .delta(delta):
if firstTokenAt == nil {
firstTokenAt = clock()
}
text += delta
await onDelta?(delta)
if repetition.append(delta) {
looped = true
}
case let .done(reason, doneMetrics):
doneReason = reason
metrics = doneMetrics
}
if looped {
break
}
}
} catch let error as OllamaError {
throw SprachmittlerError(ollama: error)
} catch is CancellationError {
throw SprachmittlerError.cancelled
}
return StreamResult(
text: text,
doneReason: doneReason,
metrics: metrics,
firstTokenAt: firstTokenAt,
looped: looped
)
}
private func sum(_ current: Int?, _ next: Int?) -> Int? {
switch (current, next) {
case let (current?, next?): current + next
case let (current?, nil): current
case let (nil, next?): next
case (nil, nil): nil
}
}
private func deduplicated(_ warnings: [TranslationWarning]) -> [TranslationWarning] {
var seen = Set<TranslationWarning>()
return warnings.filter { seen.insert($0).inserted }
}
}