feat(m2-m3): adapter, text pipeline, double-copy capture and Services (T2.1-T2.7, T3.1-T3.4)
M2: TranslationAdapter/AdapterRegistry with documented Hy-MT3 prompts and publisher sampling; all 102 languages with BCP-47 variants, RTL and dense-script flags; normalisation, NLLanguage detection, content classification and exact-join script-aware chunking; protected-token scanning and output validation; prompt policy with one documented fallback; shared TranslationPipeline with Core error mapping. The CLI now reports sourceLanguage and warning codes. M3: pure DoubleCopyDetector, 120 ms PasteboardWatcher with 750 ms own-write suppression, SystemPasteboard snapshot/restore and markers, CapturePolicy for the 4000/2000 limits, ServicesProvider and the menu-bar action. T3.5 (10-app manual matrix) remains intentionally open. Docs: ARCHITECTURE, TRANSLATION_OUTPUT, HYMT3_MODEL (§7 spike), SELECTION_AND_CLIPBOARD, PROGRESS; ADR-016 superseded by ADR-017/018. Verified: make verify green (format, strict lint, scripts, privacy, Debug+Release signatures, package tests); live 7B CLI en→de/de→en/Markdown/JSON/placeholders; empty input exits 2 and unreachable exits 3.
This commit is contained in:
1 parent
26b493e7e5
commit
64078e2f04
80 files changed
+4090
-325
No files matched your search
@@ -0,0 +1,322 @@
|
||||
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
|
||||
) 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,
|
||||
tokens: tokens
|
||||
)
|
||||
let accumulator = try await translateAll(chunks, context: context)
|
||||
|
||||
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 tokens: [ProtectedToken]
|
||||
}
|
||||
|
||||
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) async throws -> Accumulator {
|
||||
var accumulator = Accumulator()
|
||||
do {
|
||||
for chunk in chunks {
|
||||
try Task.checkCancellation()
|
||||
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
|
||||
}
|
||||
} 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 registry.makeRequest(
|
||||
AdapterRequest(
|
||||
text: chunk.text,
|
||||
target: context.target,
|
||||
model: context.model,
|
||||
keepAlive: context.keepAlive,
|
||||
prompt: prompt
|
||||
)
|
||||
)
|
||||
let attempt = try await stream(request)
|
||||
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 struct StreamResult {
|
||||
let text: String
|
||||
let doneReason: String?
|
||||
let metrics: ChatMetrics
|
||||
let firstTokenAt: Date?
|
||||
let looped: Bool
|
||||
}
|
||||
|
||||
private func stream(_ request: ChatRequest) 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
|
||||
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 }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user