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
+225
@@ -0,0 +1,225 @@
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
import SprachmittlerText
|
||||
import Testing
|
||||
|
||||
@Suite("Translation pipeline")
|
||||
struct TranslationPipelineTests {
|
||||
private let german = HyMT3Languages.german
|
||||
private let model = "test-hy-mt3"
|
||||
|
||||
@Test func usesTheDocumentedPromptAndReportsTheSourceLanguage() async throws {
|
||||
let chat = SequencedChat(responses: [[
|
||||
.delta("Hallo"), .done(reason: "stop", metrics: ChatMetrics(promptEvalCount: 9, evalCount: 2)),
|
||||
]])
|
||||
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
|
||||
let result = try await pipeline.translate(text: "Hello.", target: german, model: model, keepAlive: "30m")
|
||||
|
||||
#expect(result.translation == "Hallo")
|
||||
#expect(result.sourceLanguage == "en")
|
||||
#expect(result.chunkCount == 1)
|
||||
#expect(result.warnings.isEmpty)
|
||||
|
||||
let request = try #require(chat.recorded.first)
|
||||
#expect(request.messages.first?.content == HyMT3Prompt.defaultTranslation(target: german, source: "Hello."))
|
||||
#expect(request.options.numCtx == 8192)
|
||||
}
|
||||
|
||||
@Test func chunksAreJoinedWithTheOriginalSeparators() async throws {
|
||||
let chat = SequencedChat(responses: [
|
||||
[.delta("Erster Absatz."), .done(reason: "stop", metrics: .empty)],
|
||||
[.delta("Zweiter Absatz."), .done(reason: "stop", metrics: .empty)],
|
||||
])
|
||||
let pipeline = makePipeline(
|
||||
chat: chat,
|
||||
chunker: Chunker(latinLimit: 20, denseLimit: 20),
|
||||
detector: FixedDetector(code: "en", confidence: 0.9)
|
||||
)
|
||||
let result = try await pipeline.translate(
|
||||
text: "First paragraph.\n\nSecond paragraph.",
|
||||
target: german,
|
||||
model: model,
|
||||
keepAlive: "30m"
|
||||
)
|
||||
|
||||
#expect(result.chunkCount == 2)
|
||||
#expect(result.translation == "Erster Absatz.\n\nZweiter Absatz.")
|
||||
#expect(chat.recorded.count == 2)
|
||||
#expect(chat.recorded[1].messages.first?.content.contains("Second paragraph.") == true)
|
||||
}
|
||||
|
||||
@Test func retriesOnceWithTheDocumentedDelimitersPrompt() async throws {
|
||||
let chat = SequencedChat(responses: [
|
||||
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
|
||||
[.delta("Öffne https://example.com jetzt."), .done(reason: "stop", metrics: .empty)],
|
||||
])
|
||||
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
|
||||
let result = try await pipeline.translate(
|
||||
text: "Open https://example.com now.",
|
||||
target: german,
|
||||
model: model,
|
||||
keepAlive: "30m"
|
||||
)
|
||||
|
||||
#expect(chat.recorded.count == 2)
|
||||
#expect(chat.recorded[1].messages.first?.content.contains("retain the exact same number of delimiters") == true)
|
||||
#expect(result.translation == "Öffne https://example.com jetzt.")
|
||||
#expect(!result.warnings.contains {
|
||||
if case .missingProtectedToken = $0 {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@Test func reportsASecondLostTokenWithoutASecondRetry() async throws {
|
||||
let chat = SequencedChat(responses: [
|
||||
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
|
||||
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
|
||||
])
|
||||
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
|
||||
let result = try await pipeline.translate(
|
||||
text: "Open https://example.com now.",
|
||||
target: german,
|
||||
model: model,
|
||||
keepAlive: "30m"
|
||||
)
|
||||
|
||||
#expect(chat.recorded.count == 2)
|
||||
#expect(result.warnings.contains(.missingProtectedToken("https://example.com")))
|
||||
}
|
||||
|
||||
@Test func emptyTextAndUnknownModelsFailBeforeTheNetwork() async {
|
||||
let chat = SequencedChat(responses: [])
|
||||
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
|
||||
|
||||
await #expect(throws: SprachmittlerError.emptyText) {
|
||||
_ = try await pipeline.translate(text: " ", target: german, model: model, keepAlive: "30m")
|
||||
}
|
||||
|
||||
let emptyRegistry = TranslationPipeline(
|
||||
chat: chat,
|
||||
registry: AdapterRegistry(adapters: []),
|
||||
detector: FixedDetector(code: "en", confidence: 0.9)
|
||||
)
|
||||
await #expect(throws: SprachmittlerError.noAdapter(model: "llama3")) {
|
||||
_ = try await emptyRegistry.translate(text: "Hello.", target: german, model: "llama3", keepAlive: "30m")
|
||||
}
|
||||
#expect(chat.recorded.isEmpty)
|
||||
}
|
||||
|
||||
@Test func sameLanguageIsAnAdvisoryWarning() async throws {
|
||||
let chat = SequencedChat(responses: [
|
||||
[.delta("Hallo."), .done(reason: "stop", metrics: .empty)],
|
||||
])
|
||||
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "de", confidence: 0.9))
|
||||
let result = try await pipeline.translate(text: "Hallo.", target: german, model: model, keepAlive: "30m")
|
||||
|
||||
#expect(result.warnings.contains(.sameLanguage(source: "de", target: "de")))
|
||||
}
|
||||
|
||||
@Test func truncationAndLoopsAreWarnings() async throws {
|
||||
let truncated = SequencedChat(responses: [
|
||||
[.delta("Hallo"), .done(reason: "length", metrics: .empty)],
|
||||
])
|
||||
let truncatedResult = try await makePipeline(
|
||||
chat: truncated,
|
||||
detector: FixedDetector(code: "en", confidence: 0.9)
|
||||
)
|
||||
.translate(text: "Hello.", target: german, model: model, keepAlive: "30m")
|
||||
#expect(truncatedResult.warnings.contains(.truncated))
|
||||
|
||||
let repeated = "This line repeats exactly."
|
||||
let looping = SequencedChat(responses: [[
|
||||
.delta(Array(repeating: repeated, count: 6).joined(separator: "\n")),
|
||||
.done(reason: "stop", metrics: .empty),
|
||||
]])
|
||||
let loopResult = try await makePipeline(chat: looping, detector: FixedDetector(code: "en", confidence: 0.9))
|
||||
.translate(text: "Hello.", target: german, model: model, keepAlive: "30m")
|
||||
#expect(loopResult.warnings.contains(.repetitionLoop))
|
||||
}
|
||||
|
||||
@Test func transportErrorsAreMappedAtTheCoreBoundary() async throws {
|
||||
let url = try #require(URL(string: "http://127.0.0.1:9"))
|
||||
let pipeline = TranslationPipeline(
|
||||
chat: FailingChat(error: .unreachable(url)),
|
||||
registry: AdapterRegistry(adapters: [HyMT3Adapter()]),
|
||||
detector: FixedDetector(code: "en", confidence: 0.9)
|
||||
)
|
||||
await #expect(throws: SprachmittlerError.ollamaUnreachable(url: url)) {
|
||||
_ = try await pipeline.translate(
|
||||
text: "Hello.",
|
||||
target: german,
|
||||
model: model,
|
||||
keepAlive: "30m"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func makePipeline(
|
||||
chat: any OllamaChatting,
|
||||
chunker: Chunker = Chunker(),
|
||||
detector: any LanguageDetecting
|
||||
) -> TranslationPipeline {
|
||||
TranslationPipeline(
|
||||
chat: chat,
|
||||
registry: AdapterRegistry(adapters: [HyMT3Adapter()]),
|
||||
detector: detector,
|
||||
chunker: chunker
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private struct FixedDetector: LanguageDetecting {
|
||||
let code: String
|
||||
let confidence: Double
|
||||
|
||||
func detect(_ text: String) -> LanguageDetection? {
|
||||
LanguageDetection(code: code, confidence: confidence, alternatives: [code])
|
||||
}
|
||||
}
|
||||
|
||||
private struct FailingChat: OllamaChatting {
|
||||
let error: OllamaError
|
||||
|
||||
func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error> {
|
||||
AsyncThrowingStream { continuation in
|
||||
continuation.finish(throwing: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A chat fake that returns one response per call. `@unchecked Sendable` is safe because every
|
||||
/// mutable field is guarded by `lock`.
|
||||
private final class SequencedChat: OllamaChatting, @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var responses: [[ChatEvent]]
|
||||
private var requests: [ChatRequest] = []
|
||||
|
||||
init(responses: [[ChatEvent]]) {
|
||||
self.responses = responses
|
||||
}
|
||||
|
||||
var recorded: [ChatRequest] {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return requests
|
||||
}
|
||||
|
||||
func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error> {
|
||||
lock.lock()
|
||||
requests.append(request)
|
||||
let events = responses.isEmpty ? [] : responses.removeFirst()
|
||||
lock.unlock()
|
||||
|
||||
return AsyncThrowingStream { continuation in
|
||||
for event in events {
|
||||
continuation.yield(event)
|
||||
}
|
||||
continuation.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user