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
@@ -1,5 +1,6 @@
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
import SprachmittlerTestSupport
|
||||
@@ -60,18 +61,22 @@ struct CLITests {
|
||||
],
|
||||
onRequest: { box.record($0) }
|
||||
)
|
||||
let factory = HyMT3RequestFactory(model: "test-model", keepAlive: "5m")
|
||||
let outcome = try await TranslateRunner(chat: chat, factory: factory)
|
||||
.run(text: "Hello.", target: HyMT3Languages.german)
|
||||
let model = "test-hy-mt3-model"
|
||||
let pipeline = TranslationPipeline(
|
||||
chat: chat,
|
||||
registry: AdapterRegistry(adapters: [HyMT3Adapter()])
|
||||
)
|
||||
let outcome = try await TranslateRunner(pipeline: pipeline)
|
||||
.run(text: "Hello.", target: HyMT3Languages.german, model: model)
|
||||
|
||||
#expect(outcome.translation == "Hallo")
|
||||
#expect(outcome.model == "test-model")
|
||||
#expect(outcome.model == model)
|
||||
#expect(outcome.target == HyMT3Languages.german)
|
||||
#expect(outcome.sourceCharacters == 6)
|
||||
#expect(outcome.metrics.evalCount == 2)
|
||||
#expect(outcome.timing.outputTokens == 2)
|
||||
|
||||
let request = try #require(box.request)
|
||||
#expect(request.keepAlive == "5m")
|
||||
#expect(request.keepAlive == HyMT3ModelPreset.defaultKeepAlive)
|
||||
#expect(
|
||||
request.messages.first?.content
|
||||
== HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "Hello.")
|
||||
@@ -83,9 +88,9 @@ struct CLITests {
|
||||
translation: "Hallo",
|
||||
model: "test-model",
|
||||
target: HyMT3Languages.german,
|
||||
metrics: ChatMetrics(promptEvalCount: 9, evalCount: 2),
|
||||
firstTokenMs: 4,
|
||||
totalMs: 12,
|
||||
warnings: [.truncated],
|
||||
sourceLanguage: "en",
|
||||
timing: TranslationTiming(firstTokenMs: 4, totalMs: 12, promptTokens: 9, outputTokens: 2),
|
||||
sourceCharacters: 6
|
||||
)
|
||||
|
||||
@@ -95,8 +100,8 @@ struct CLITests {
|
||||
#expect(object["targetLanguage"] as? String == "de")
|
||||
#expect(object["model"] as? String == "test-model")
|
||||
#expect(object["translation"] as? String == "Hallo")
|
||||
#expect(object["sourceLanguage"] is NSNull)
|
||||
#expect((object["warnings"] as? [Any])?.isEmpty == true)
|
||||
#expect(object["sourceLanguage"] as? String == "en")
|
||||
#expect(object["warnings"] as? [String] == ["truncated"])
|
||||
#expect(object["source"] == nil)
|
||||
|
||||
let withSourceData = try outcome.jsonData(includeSource: true, source: "Hello.")
|
||||
@@ -132,10 +137,16 @@ struct CLITests {
|
||||
|
||||
@Test func exitCodesMatchTheContract() throws {
|
||||
let url = try #require(URL(string: "http://127.0.0.1:9"))
|
||||
#expect(CLIError.exitCode(for: .endpointRejected(.remoteNotAllowed)) == 2)
|
||||
#expect(CLIError.exitCode(for: .unreachable(url)) == 3)
|
||||
#expect(CLIError.exitCode(for: .modelNotInstalled("m")) == 4)
|
||||
#expect(CLIError.exitCode(for: .cancelled) == 1)
|
||||
#expect(CLIError.exitCode(for: OllamaError.endpointRejected(.remoteNotAllowed)) == 2)
|
||||
#expect(CLIError.exitCode(for: OllamaError.unreachable(url)) == 3)
|
||||
#expect(CLIError.exitCode(for: OllamaError.modelNotInstalled("m")) == 4)
|
||||
#expect(CLIError.exitCode(for: OllamaError.cancelled) == 1)
|
||||
|
||||
#expect(CLIError.exitCode(for: SprachmittlerError.ollamaUnreachable(url: url)) == 3)
|
||||
#expect(CLIError.exitCode(for: SprachmittlerError.modelNotInstalled(model: "m")) == 4)
|
||||
#expect(CLIError.exitCode(for: SprachmittlerError.noAdapter(model: "m")) == 2)
|
||||
#expect(CLIError.exitCode(for: SprachmittlerError.emptyText) == 2)
|
||||
#expect(CLIError.exitCode(for: SprachmittlerError.textTooLong(characters: 5000, limit: 4000)) == 2)
|
||||
}
|
||||
|
||||
private func assertValidationError(_ arguments: [String], message: String) {
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
import Foundation
|
||||
import SprachmittlerCapture
|
||||
import SprachmittlerTestSupport
|
||||
import Testing
|
||||
|
||||
@Suite("Clipboard snapshot")
|
||||
@MainActor
|
||||
struct ClipboardSnapshotTests {
|
||||
@Test func snapshotCapturesEveryItemAndType() throws {
|
||||
let text = Data("Hello".utf8)
|
||||
let rich = Data("rich".utf8)
|
||||
let image = Data([0x01, 0x02, 0x03])
|
||||
let pasteboard = FakePasteboard(
|
||||
changeCount: 3,
|
||||
text: "Hello",
|
||||
items: [
|
||||
ClipboardItemData(data: ["public.utf8-plain-text": text, "public.rtf": rich]),
|
||||
ClipboardItemData(data: ["public.png": image]),
|
||||
]
|
||||
)
|
||||
|
||||
let snapshot = try #require(pasteboard.snapshot())
|
||||
#expect(snapshot.changeCount == 3)
|
||||
#expect(snapshot.items.count == 2)
|
||||
#expect(snapshot.items[0].data["public.utf8-plain-text"] == text)
|
||||
#expect(snapshot.items[0].data["public.rtf"] == rich)
|
||||
#expect(snapshot.items[1].data["public.png"] == image)
|
||||
}
|
||||
|
||||
@Test func restoreOnlyWhenChangeCountMatches() throws {
|
||||
let text = Data("Hello".utf8)
|
||||
let pasteboard = FakePasteboard(
|
||||
changeCount: 3,
|
||||
text: "Hello",
|
||||
items: [ClipboardItemData(data: ["public.utf8-plain-text": text])]
|
||||
)
|
||||
let snapshot = try #require(pasteboard.snapshot())
|
||||
#expect(pasteboard.restore(snapshot, onlyIfChangeCountMatches: 3))
|
||||
#expect(pasteboard.text == "Hello")
|
||||
#expect(!pasteboard.hasOwnWriteMarkers)
|
||||
}
|
||||
|
||||
@Test func anotherAppChangingTheClipboardPreventsRestore() throws {
|
||||
let text = Data("Hello".utf8)
|
||||
let pasteboard = FakePasteboard(
|
||||
changeCount: 3,
|
||||
text: "Hello",
|
||||
items: [ClipboardItemData(data: ["public.utf8-plain-text": text])]
|
||||
)
|
||||
let snapshot = try #require(pasteboard.snapshot())
|
||||
|
||||
pasteboard.simulateCopy("Other")
|
||||
#expect(!pasteboard.restore(snapshot, onlyIfChangeCountMatches: 3))
|
||||
#expect(pasteboard.text == "Other")
|
||||
}
|
||||
|
||||
@Test func restoreFailureIsReported() throws {
|
||||
let pasteboard = FakePasteboard(changeCount: 1, text: "Hello")
|
||||
let snapshot = try #require(pasteboard.snapshot())
|
||||
pasteboard.restoreSucceeds = false
|
||||
#expect(!pasteboard.restore(snapshot, onlyIfChangeCountMatches: 1))
|
||||
}
|
||||
|
||||
@Test func snapshotFailureReturnsNil() {
|
||||
let pasteboard = FakePasteboard()
|
||||
pasteboard.snapshotSucceeds = false
|
||||
#expect(pasteboard.snapshot() == nil)
|
||||
}
|
||||
|
||||
@Test func writeAddsOwnAndTransientMarkers() {
|
||||
let pasteboard = FakePasteboard()
|
||||
let newCount = pasteboard.write("Hallo")
|
||||
#expect(newCount == 1)
|
||||
#expect(pasteboard.text == "Hallo")
|
||||
#expect(pasteboard.hasOwnWriteMarkers)
|
||||
#expect(pasteboard.writtenTexts == ["Hallo"])
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import SprachmittlerCapture
|
||||
|
||||
@Suite("Double-copy detector")
|
||||
struct DoubleCopyDetectorTests {
|
||||
private let start = Date(timeIntervalSince1970: 1000)
|
||||
|
||||
@Test func twoIdenticalCopiesWithinTheWindowTrigger() {
|
||||
var detector = DoubleCopyDetector()
|
||||
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
|
||||
#expect(detector.record(changeCount: 2, text: "Hello", at: start.addingTimeInterval(0.3))
|
||||
== .captured("Hello"))
|
||||
}
|
||||
|
||||
@Test func slowCopiesDoNotTrigger() {
|
||||
var detector = DoubleCopyDetector()
|
||||
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
|
||||
#expect(detector.record(changeCount: 2, text: "Hello", at: start.addingTimeInterval(0.6)) == .none)
|
||||
#expect(detector.record(changeCount: 3, text: "Hello", at: start.addingTimeInterval(0.7))
|
||||
== .captured("Hello"))
|
||||
}
|
||||
|
||||
@Test func differentTextDoesNotTrigger() {
|
||||
var detector = DoubleCopyDetector()
|
||||
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
|
||||
#expect(detector.record(changeCount: 2, text: "World", at: start.addingTimeInterval(0.1)) == .none)
|
||||
#expect(detector.record(changeCount: 3, text: "World", at: start.addingTimeInterval(0.2))
|
||||
== .captured("World"))
|
||||
}
|
||||
|
||||
@Test func emptyOrWhitespaceTextResets() {
|
||||
var detector = DoubleCopyDetector()
|
||||
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
|
||||
#expect(detector.record(changeCount: 2, text: " ", at: start.addingTimeInterval(0.1)) == .empty)
|
||||
#expect(detector.record(changeCount: 3, text: "Hello", at: start.addingTimeInterval(0.2)) == .none)
|
||||
}
|
||||
|
||||
@Test func duplicateChangeCountIsIgnored() {
|
||||
var detector = DoubleCopyDetector()
|
||||
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
|
||||
#expect(detector.record(changeCount: 1, text: "Hello", at: start.addingTimeInterval(0.1)) == .none)
|
||||
}
|
||||
|
||||
@Test func comparisonTrimsAndNormalisesLineEndingsOnly() {
|
||||
var detector = DoubleCopyDetector()
|
||||
#expect(detector.record(changeCount: 1, text: " Hello\r\nworld ", at: start) == .none)
|
||||
#expect(detector.record(changeCount: 2, text: "Hello\nworld", at: start.addingTimeInterval(0.1))
|
||||
== .captured("Hello\nworld"))
|
||||
}
|
||||
|
||||
@Test func internalWhitespaceIsSignificant() {
|
||||
var detector = DoubleCopyDetector()
|
||||
#expect(detector.record(changeCount: 1, text: "a b", at: start) == .none)
|
||||
#expect(detector.record(changeCount: 2, text: "a b", at: start.addingTimeInterval(0.1)) == .none)
|
||||
}
|
||||
|
||||
@Test func resetForgetsTheRememberedCopy() {
|
||||
var detector = DoubleCopyDetector()
|
||||
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
|
||||
detector.reset()
|
||||
#expect(detector.record(changeCount: 2, text: "Hello", at: start.addingTimeInterval(0.1)) == .none)
|
||||
}
|
||||
|
||||
@Test func expireClearsACandidateAfterTheWindow() {
|
||||
var detector = DoubleCopyDetector()
|
||||
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
|
||||
detector.expire(at: start.addingTimeInterval(0.6))
|
||||
#expect(detector.record(changeCount: 2, text: "Hello", at: start.addingTimeInterval(0.7)) == .none)
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerTestSupport
|
||||
import Testing
|
||||
@testable import SprachmittlerCapture
|
||||
|
||||
@Suite("Pasteboard watcher")
|
||||
@MainActor
|
||||
struct PasteboardWatcherTests {
|
||||
private let start = Date(timeIntervalSince1970: 2000)
|
||||
|
||||
@Test func readsOnlyAfterAChange() {
|
||||
let pasteboard = FakePasteboard(text: "Hello")
|
||||
let watcher = PasteboardWatcher(pasteboard: pasteboard)
|
||||
#expect(watcher.poll(at: start) == nil)
|
||||
#expect(pasteboard.stringReadCount == 0)
|
||||
}
|
||||
|
||||
@Test func twoIdenticalCopiesAreCaptured() {
|
||||
let pasteboard = FakePasteboard()
|
||||
let watcher = PasteboardWatcher(pasteboard: pasteboard)
|
||||
|
||||
pasteboard.simulateCopy("Hello")
|
||||
#expect(watcher.poll(at: start) == nil)
|
||||
pasteboard.simulateCopy("Hello")
|
||||
let event = watcher.poll(at: start.addingTimeInterval(0.1))
|
||||
|
||||
guard case let .captured(captured) = event else {
|
||||
Issue.record("expected a capture")
|
||||
return
|
||||
}
|
||||
#expect(captured.text == "Hello")
|
||||
#expect(captured.source == .doubleCopy)
|
||||
#expect(captured.capturedAt == start.addingTimeInterval(0.1))
|
||||
}
|
||||
|
||||
@Test func slowCopiesDoNotTrigger() {
|
||||
let pasteboard = FakePasteboard()
|
||||
let watcher = PasteboardWatcher(pasteboard: pasteboard)
|
||||
|
||||
pasteboard.simulateCopy("Hello")
|
||||
#expect(watcher.poll(at: start) == nil)
|
||||
pasteboard.simulateCopy("Hello")
|
||||
#expect(watcher.poll(at: start.addingTimeInterval(0.6)) == nil)
|
||||
}
|
||||
|
||||
@Test func tooLongTextUsesTheScriptAwareLimit() {
|
||||
let latin = FakePasteboard()
|
||||
let latinWatcher = PasteboardWatcher(pasteboard: latin)
|
||||
latin.simulateCopy(String(repeating: "a", count: 4001))
|
||||
_ = latinWatcher.poll(at: start)
|
||||
latin.simulateCopy(String(repeating: "a", count: 4001))
|
||||
#expect(
|
||||
latinWatcher.poll(at: start.addingTimeInterval(0.1))
|
||||
== .textTooLong(characters: 4001, limit: 4000)
|
||||
)
|
||||
|
||||
let dense = FakePasteboard()
|
||||
let denseWatcher = PasteboardWatcher(pasteboard: dense)
|
||||
let cjk = String(repeating: "你", count: 2001)
|
||||
dense.simulateCopy(cjk)
|
||||
_ = denseWatcher.poll(at: start)
|
||||
dense.simulateCopy(cjk)
|
||||
#expect(
|
||||
denseWatcher.poll(at: start.addingTimeInterval(0.1))
|
||||
== .textTooLong(characters: 2001, limit: 2000)
|
||||
)
|
||||
}
|
||||
|
||||
@Test func ownWritesAreSuppressedFor750Milliseconds() {
|
||||
let pasteboard = FakePasteboard()
|
||||
let watcher = PasteboardWatcher(pasteboard: pasteboard)
|
||||
|
||||
pasteboard.simulateOwnMarkerCopy("Hallo")
|
||||
#expect(watcher.poll(at: start) == .ignoredOwnWrite)
|
||||
|
||||
pasteboard.simulateCopy("Hello")
|
||||
#expect(watcher.poll(at: start.addingTimeInterval(0.1)) == .ignoredOwnWrite)
|
||||
|
||||
pasteboard.simulateCopy("Hello")
|
||||
#expect(watcher.poll(at: start.addingTimeInterval(0.8)) == nil)
|
||||
pasteboard.simulateCopy("Hello")
|
||||
let event = watcher.poll(at: start.addingTimeInterval(0.9))
|
||||
#expect(event != nil)
|
||||
}
|
||||
|
||||
@Test func noteOwnWriteSuppressesTheNextChange() {
|
||||
let pasteboard = FakePasteboard()
|
||||
let watcher = PasteboardWatcher(pasteboard: pasteboard)
|
||||
watcher.noteOwnWrite(at: start)
|
||||
|
||||
pasteboard.simulateCopy("Hallo")
|
||||
#expect(watcher.poll(at: start.addingTimeInterval(0.1)) == .ignoredOwnWrite)
|
||||
}
|
||||
|
||||
@Test func clearForgetsTheFirstCopy() {
|
||||
let pasteboard = FakePasteboard()
|
||||
let watcher = PasteboardWatcher(pasteboard: pasteboard)
|
||||
|
||||
pasteboard.simulateCopy("Hello")
|
||||
#expect(watcher.poll(at: start) == nil)
|
||||
watcher.clear()
|
||||
pasteboard.simulateCopy("Hello")
|
||||
#expect(watcher.poll(at: start.addingTimeInterval(0.1)) == nil)
|
||||
}
|
||||
|
||||
@Test func startAndStopDoNotLeakThePollTask() async {
|
||||
let pasteboard = FakePasteboard()
|
||||
let ticker = ManualPasteboardTicker()
|
||||
let watcher = PasteboardWatcher(pasteboard: pasteboard, ticker: ticker)
|
||||
|
||||
watcher.start { _ in }
|
||||
#expect(watcher.isRunning)
|
||||
for _ in 0 ..< 1000 where !ticker.isStarted {
|
||||
await Task.yield()
|
||||
}
|
||||
watcher.stop()
|
||||
#expect(!watcher.isRunning)
|
||||
for _ in 0 ..< 1000 where !ticker.isTerminated {
|
||||
await Task.yield()
|
||||
}
|
||||
#expect(ticker.isTerminated)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerTestSupport
|
||||
import Testing
|
||||
@testable import SprachmittlerCapture
|
||||
|
||||
@Suite("Services provider")
|
||||
@MainActor
|
||||
struct ServicesProviderTests {
|
||||
@Test func deliversTheSelectedTextWithoutAccessibility() throws {
|
||||
let pasteboard = NSPasteboard(name: NSPasteboard.Name("SprachmittlerTests-\(UUID().uuidString)"))
|
||||
pasteboard.clearContents()
|
||||
pasteboard.setString("Hello from Services", forType: .string)
|
||||
|
||||
let box = CapturedBox()
|
||||
let provider = ServicesProvider { box.record($0) }
|
||||
var error: NSString = ""
|
||||
provider.translateSelection(pasteboard, userData: "", error: &error)
|
||||
|
||||
let captured = try #require(box.captured)
|
||||
#expect(captured.text == "Hello from Services")
|
||||
#expect(captured.source == .services)
|
||||
}
|
||||
|
||||
@Test func emptySelectionReturnsAnError() {
|
||||
let pasteboard = NSPasteboard(name: NSPasteboard.Name("SprachmittlerTests-\(UUID().uuidString)"))
|
||||
pasteboard.clearContents()
|
||||
|
||||
let box = CapturedBox()
|
||||
let provider = ServicesProvider { box.record($0) }
|
||||
var error: NSString = ""
|
||||
provider.translateSelection(pasteboard, userData: "", error: &error)
|
||||
|
||||
#expect(error.length > 0)
|
||||
#expect(box.captured == nil)
|
||||
}
|
||||
|
||||
@Test func ownWriteMarkersAreIgnored() {
|
||||
let pasteboard = NSPasteboard(name: NSPasteboard.Name("SprachmittlerTests-\(UUID().uuidString)"))
|
||||
pasteboard.clearContents()
|
||||
pasteboard.setString("Hallo", forType: .string)
|
||||
pasteboard.setData(
|
||||
Data(),
|
||||
forType: NSPasteboard.PasteboardType("com.schihei.sprachmittler.own")
|
||||
)
|
||||
|
||||
let box = CapturedBox()
|
||||
let provider = ServicesProvider { box.record($0) }
|
||||
var error: NSString = ""
|
||||
provider.translateSelection(pasteboard, userData: "", error: &error)
|
||||
|
||||
#expect(error.length > 0)
|
||||
#expect(box.captured == nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// @unchecked Sendable is safe because every field is guarded by `lock`.
|
||||
private final class CapturedBox: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var value: CapturedText?
|
||||
|
||||
var captured: CapturedText? {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return value
|
||||
}
|
||||
|
||||
func record(_ captured: CapturedText) {
|
||||
lock.lock()
|
||||
value = captured
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
import SprachmittlerCapture
|
||||
import Testing
|
||||
|
||||
@Suite("System pasteboard adapter")
|
||||
@MainActor
|
||||
struct SystemPasteboardTests {
|
||||
private func makePasteboard() -> (NSPasteboard, SystemPasteboard) {
|
||||
let pasteboard = NSPasteboard(name: NSPasteboard.Name("SprachmittlerTests-\(UUID().uuidString)"))
|
||||
pasteboard.clearContents()
|
||||
return (pasteboard, SystemPasteboard(pasteboard: pasteboard))
|
||||
}
|
||||
|
||||
@Test func writeAddsTextAndMarkers() {
|
||||
let (pasteboard, adapter) = makePasteboard()
|
||||
let before = adapter.changeCount
|
||||
|
||||
let after = adapter.write("Hallo")
|
||||
|
||||
#expect(after > before)
|
||||
#expect(pasteboard.string(forType: .string) == "Hallo")
|
||||
#expect(adapter.containsOwnWriteMarkers())
|
||||
}
|
||||
|
||||
@Test func snapshotAndRestoreRoundTripMultipleTypes() throws {
|
||||
let (pasteboard, adapter) = makePasteboard()
|
||||
let rtf = Data("rich".utf8)
|
||||
pasteboard.setString("Hello", forType: .string)
|
||||
pasteboard.setData(rtf, forType: .rtf)
|
||||
|
||||
let snapshot = try #require(adapter.snapshot())
|
||||
_ = adapter.write("Translation")
|
||||
|
||||
#expect(adapter.restore(snapshot, onlyIfChangeCountMatches: adapter.changeCount))
|
||||
#expect(pasteboard.string(forType: .string) == "Hello")
|
||||
#expect(pasteboard.data(forType: .rtf) == rtf)
|
||||
}
|
||||
|
||||
@Test func restoreIsRefusedAfterAnotherChange() throws {
|
||||
let (pasteboard, adapter) = makePasteboard()
|
||||
pasteboard.setString("Hello", forType: .string)
|
||||
let snapshot = try #require(adapter.snapshot())
|
||||
|
||||
pasteboard.clearContents()
|
||||
pasteboard.setString("Other", forType: .string)
|
||||
|
||||
#expect(!adapter.restore(snapshot, onlyIfChangeCountMatches: snapshot.changeCount))
|
||||
#expect(pasteboard.string(forType: .string) == "Other")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import SprachmittlerCore
|
||||
import Testing
|
||||
|
||||
@Suite("Capture policy")
|
||||
struct CapturePolicyTests {
|
||||
@Test func emptyAndWhitespaceTextAreRejected() {
|
||||
#expect(CapturePolicy.validate("") == .empty)
|
||||
#expect(CapturePolicy.validate(" \n\t") == .empty)
|
||||
}
|
||||
|
||||
@Test func latinLimitIs4000() {
|
||||
#expect(CapturePolicy.validate(String(repeating: "a", count: 4000)) == .valid)
|
||||
#expect(
|
||||
CapturePolicy.validate(String(repeating: "a", count: 4001))
|
||||
== .textTooLong(characters: 4001, limit: 4000)
|
||||
)
|
||||
}
|
||||
|
||||
@Test func denseScriptLimitIs2000() {
|
||||
let valid = String(repeating: "你", count: 2000)
|
||||
let tooLong = String(repeating: "你", count: 2001)
|
||||
#expect(CapturePolicy.validate(valid) == .valid)
|
||||
#expect(
|
||||
CapturePolicy.validate(tooLong)
|
||||
== .textTooLong(characters: 2001, limit: 2000)
|
||||
)
|
||||
}
|
||||
}
|
||||
+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()
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
Please accurately translate the following text into {target_lang}. You must **retain the exact same number of delimiters in the translation. Strictly do not omit, escape, or translate these symbols, and pay close attention to their placement**.
|
||||
|
||||
{source_text}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
### Task
|
||||
Translate the user-facing text within the following {format_type} data into {target_lang}.
|
||||
|
||||
### Strict Rules
|
||||
1. **Structure Preservation:** You MUST preserve the original {format_type} data structure, nesting, hierarchy, and indentation exactly as they are.
|
||||
2. **Selective Translation:** Translate ONLY the visible, user-facing text content/values.
|
||||
3. **Strict Non-Translation:** NEVER translate or alter code tags, keys, properties, object names, or variable placeholders. Leave them exactly in their original English/code form.
|
||||
|
||||
### Source Data
|
||||
{source_text}
|
||||
@@ -0,0 +1,106 @@
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
import SprachmittlerText
|
||||
import Testing
|
||||
@testable import SprachmittlerEngines
|
||||
|
||||
@Suite("Hy-MT3 adapter and registry")
|
||||
struct HyMT3AdapterTests {
|
||||
private let adapter = HyMT3Adapter()
|
||||
|
||||
@Test func matchesEveryHyMT3TagAndRejectsOtherFamilies() {
|
||||
#expect(adapter.supports(model: HyMT3ModelPreset.defaultModel))
|
||||
#expect(adapter.supports(model: HyMT3ModelPreset.fastModel))
|
||||
#expect(adapter.supports(model: "hf.co/tencent/Hy-MT3-30B-A3B-GGUF:Q4_K_M"))
|
||||
#expect(!adapter.supports(model: "llama3.1:8b"))
|
||||
|
||||
let registry = AdapterRegistry(adapters: [adapter])
|
||||
#expect(registry.adapter(for: HyMT3ModelPreset.defaultModel)?.identifier == "hy-mt3")
|
||||
#expect(registry.adapter(for: "llama3.1:8b") == nil)
|
||||
#expect(throws: AdapterError.noAdapter(model: "llama3.1:8b")) {
|
||||
try registry.makeRequest(
|
||||
AdapterRequest(
|
||||
text: "Hello.",
|
||||
target: HyMT3Languages.german,
|
||||
model: "llama3.1:8b",
|
||||
keepAlive: "30m"
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func requestHasOneUserMessageAndPublisherSampling() {
|
||||
let request = adapter.makeRequest(
|
||||
AdapterRequest(
|
||||
text: "Hello.",
|
||||
target: HyMT3Languages.german,
|
||||
model: "test-model",
|
||||
keepAlive: "5m"
|
||||
)
|
||||
)
|
||||
|
||||
#expect(request.model == "test-model")
|
||||
#expect(request.stream)
|
||||
#expect(request.keepAlive == "5m")
|
||||
#expect(request.messages.count == 1)
|
||||
#expect(request.messages.first?.role == "user")
|
||||
#expect(request.messages.first?.content == HyMT3Prompt.defaultTranslation(
|
||||
target: HyMT3Languages.german,
|
||||
source: "Hello."
|
||||
))
|
||||
#expect(request.options.temperature == 0.7)
|
||||
#expect(request.options.topP == 0.6)
|
||||
#expect(request.options.topK == 20)
|
||||
#expect(request.options.repeatPenalty == 1.05)
|
||||
#expect(request.options.numPredict == 4096)
|
||||
#expect(request.options.numCtx == 8192)
|
||||
}
|
||||
|
||||
@Test func encodingUsesOnlyTheDocumentedOptionNames() throws {
|
||||
let request = adapter.makeRequest(
|
||||
AdapterRequest(
|
||||
text: "Hello.",
|
||||
target: HyMT3Languages.german,
|
||||
model: "test-model",
|
||||
keepAlive: "30m"
|
||||
)
|
||||
)
|
||||
let data = try JSONEncoder().encode(request)
|
||||
let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
let options = try #require(object["options"] as? [String: Any])
|
||||
|
||||
#expect(Set(options.keys) == ["temperature", "top_p", "top_k", "repeat_penalty", "num_predict", "num_ctx"])
|
||||
#expect(object["keep_alive"] as? String == "30m")
|
||||
#expect((object["messages"] as? [[String: Any]])?.first?["role"] as? String == "user")
|
||||
#expect(object["think"] == nil)
|
||||
#expect(object["system"] == nil)
|
||||
}
|
||||
|
||||
@Test func warmUpAndUnloadUseFixedText() {
|
||||
let warmUp = adapter.warmUpRequest(model: "test-model", keepAlive: "30m")
|
||||
#expect(warmUp.messages.first?.content == "Hello.")
|
||||
#expect(warmUp.options.numPredict == 8)
|
||||
|
||||
let unload = adapter.unloadRequest(model: "test-model")
|
||||
#expect(unload.messages.first?.content == "Hello.")
|
||||
#expect(unload.keepAlive == "0")
|
||||
}
|
||||
|
||||
@Test func samplingMergeOnlyOverridesKnownKeys() {
|
||||
let merged = SamplingOptions.publisherDefault.merging(
|
||||
SamplingOverrides(temperature: 0.2, numPredict: 2048)
|
||||
)
|
||||
#expect(merged.temperature == 0.2)
|
||||
#expect(merged.numPredict == 2048)
|
||||
#expect(merged.topP == 0.6)
|
||||
#expect(merged.numCtx == 8192)
|
||||
#expect(merged.chatOptions() == ChatOptions(
|
||||
temperature: 0.2,
|
||||
topP: 0.6,
|
||||
topK: 20,
|
||||
repeatPenalty: 1.05,
|
||||
numPredict: 2048,
|
||||
numCtx: 8192
|
||||
))
|
||||
}
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
import Testing
|
||||
@testable import SprachmittlerEngines
|
||||
|
||||
@Suite("Hy-MT3 request factory")
|
||||
struct HyMT3RequestFactoryTests {
|
||||
@Test func warmUpUsesFixedTextAndEightTokens() throws {
|
||||
let request = HyMT3RequestFactory().warmUpRequest()
|
||||
let message = try #require(request.messages.first)
|
||||
#expect(request.messages.count == 1)
|
||||
#expect(message.role == "user")
|
||||
#expect(message.content == "Hello.")
|
||||
#expect(request.options.numPredict == 8)
|
||||
#expect(request.options.numCtx == 8192)
|
||||
#expect(request.keepAlive == "30m")
|
||||
#expect(request.stream)
|
||||
#expect(request.model == HyMT3ModelPreset.defaultModel)
|
||||
}
|
||||
|
||||
@Test func unloadUsesKeepAliveZero() {
|
||||
let request = HyMT3RequestFactory().unloadRequest()
|
||||
#expect(request.keepAlive == "0")
|
||||
#expect(request.messages.map(\.content) == ["Hello."])
|
||||
}
|
||||
|
||||
@Test func translationPromptIsByteExact() throws {
|
||||
let factory = HyMT3RequestFactory(model: "test-model", keepAlive: "5m")
|
||||
let request = factory.translationRequest(text: "Hello.", target: HyMT3Languages.german)
|
||||
let message = try #require(request.messages.first)
|
||||
#expect(request.messages.count == 1)
|
||||
#expect(
|
||||
message.content
|
||||
== "Translate the following text into German. "
|
||||
+ "Note that you should **only output the translated result without any additional explanation**:"
|
||||
+ "\n\nHello."
|
||||
)
|
||||
#expect(request.model == "test-model")
|
||||
#expect(request.keepAlive == "5m")
|
||||
#expect(request.options.numPredict == 4096)
|
||||
#expect(request.options.numCtx == 8192)
|
||||
#expect(request.options.temperature == 0.7)
|
||||
#expect(request.options.topP == 0.6)
|
||||
#expect(request.options.topK == 20)
|
||||
#expect(request.options.repeatPenalty == 1.05)
|
||||
}
|
||||
|
||||
@Test func promptMatchesTheGoldenFixture() throws {
|
||||
let base = try #require(Bundle.module.resourceURL)
|
||||
let url = base.appendingPathComponent("Fixtures/default-prompt.txt")
|
||||
let template = try String(contentsOf: url, encoding: .utf8)
|
||||
.trimmingCharacters(in: .newlines)
|
||||
let expected = template
|
||||
.replacingOccurrences(of: "{target_lang}", with: "German")
|
||||
.replacingOccurrences(of: "{source_text}", with: "Hello.")
|
||||
#expect(
|
||||
HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "Hello.")
|
||||
== expected
|
||||
)
|
||||
}
|
||||
|
||||
@Test func promptPrefixIsStableForTheSameTarget() {
|
||||
let factory = HyMT3RequestFactory()
|
||||
let first = factory.translationRequest(text: "One.", target: HyMT3Languages.german)
|
||||
let second = factory.translationRequest(text: "Two.", target: HyMT3Languages.german)
|
||||
let firstContent = first.messages[0].content
|
||||
let secondContent = second.messages[0].content
|
||||
let suffix = "\n\n"
|
||||
let firstPrefix = firstContent.components(separatedBy: suffix)[0]
|
||||
let secondPrefix = secondContent.components(separatedBy: suffix)[0]
|
||||
#expect(firstPrefix == secondPrefix)
|
||||
#expect(firstContent.hasSuffix("One."))
|
||||
#expect(secondContent.hasSuffix("Two."))
|
||||
}
|
||||
|
||||
@Test func resolvesOnlyTheProvisionalCommonLanguages() {
|
||||
#expect(HyMT3Languages.resolve("de") == HyMT3Languages.german)
|
||||
#expect(HyMT3Languages.resolve("EN") == HyMT3Languages.english)
|
||||
#expect(HyMT3Languages.resolve("zh-Hant")?.modelName == "Traditional Chinese")
|
||||
#expect(HyMT3Languages.resolve("xx") == nil)
|
||||
#expect(HyMT3Languages.all.count == 16)
|
||||
}
|
||||
|
||||
@Test func optionsMatchTheDocumentedPublisherValues() {
|
||||
#expect(HyMT3Options.translation.temperature == 0.7)
|
||||
#expect(HyMT3Options.translation.topP == 0.6)
|
||||
#expect(HyMT3Options.translation.topK == 20)
|
||||
#expect(HyMT3Options.translation.repeatPenalty == 1.05)
|
||||
#expect(HyMT3Options.translation.numPredict == 4096)
|
||||
#expect(HyMT3Options.translation.numCtx == 8192)
|
||||
#expect(HyMT3Options.warmUp.numPredict == 8)
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import Testing
|
||||
@testable import SprachmittlerEngines
|
||||
|
||||
@Suite("Hy-MT3 language catalogue")
|
||||
struct LanguageCatalogueTests {
|
||||
@Test func containsAll102Languages() {
|
||||
#expect(HyMT3Languages.count == 102)
|
||||
#expect(Set(HyMT3Languages.all.map(\.code)).count == 102)
|
||||
}
|
||||
|
||||
@Test func exactModelNamesForVariants() {
|
||||
#expect(HyMT3Languages.resolve("zh")?.modelName == "Chinese")
|
||||
#expect(HyMT3Languages.resolve("zh-Hant")?.modelName == "Traditional Chinese")
|
||||
#expect(HyMT3Languages.resolve("pt")?.modelName == "Portuguese")
|
||||
#expect(HyMT3Languages.resolve("nb")?.modelName == "Norwegian")
|
||||
#expect(HyMT3Languages.resolve("nn")?.modelName == "Norwegian Nynorsk")
|
||||
#expect(HyMT3Languages.resolve("kk")?.modelName == "Arabic Kazakh")
|
||||
#expect(HyMT3Languages.resolve("kk-Cyrl")?.modelName == "Cyrillic Kazakh")
|
||||
#expect(HyMT3Languages.resolve("mn")?.modelName == "Traditional Mongolian")
|
||||
#expect(HyMT3Languages.resolve("mn-Cyrl")?.modelName == "Cyrillic Mongolian")
|
||||
#expect(HyMT3Languages.resolve("ku")?.modelName == "Kurdish")
|
||||
#expect(HyMT3Languages.resolve("ckb")?.modelName == "Central Kurdish")
|
||||
}
|
||||
|
||||
@Test func variantsCollapseToCanonicalCodes() {
|
||||
#expect(HyMT3Languages.resolve("zh-Hans")?.code == "zh")
|
||||
#expect(HyMT3Languages.resolve("zh-CN")?.code == "zh")
|
||||
#expect(HyMT3Languages.resolve("zh-TW")?.code == "zh-Hant")
|
||||
#expect(HyMT3Languages.resolve("pt-BR")?.code == "pt")
|
||||
#expect(HyMT3Languages.resolve("pt-PT")?.code == "pt")
|
||||
#expect(HyMT3Languages.resolve("no")?.code == "nb")
|
||||
#expect(HyMT3Languages.resolve("fil")?.code == "tl")
|
||||
#expect(HyMT3Languages.resolve("iw")?.code == "he")
|
||||
#expect(HyMT3Languages.resolve("in")?.code == "id")
|
||||
#expect(HyMT3Languages.resolve("kk-KZ")?.code == "kk-Cyrl")
|
||||
#expect(HyMT3Languages.resolve("de-AT")?.code == "de")
|
||||
}
|
||||
|
||||
@Test func unknownCodesAreNeverGuessed() {
|
||||
#expect(HyMT3Languages.resolve("xx") == nil)
|
||||
#expect(HyMT3Languages.resolve("xx-YY") == nil)
|
||||
#expect(HyMT3Languages.resolve("") == nil)
|
||||
}
|
||||
|
||||
@Test func rightToLeftLanguagesAreMarked() {
|
||||
let codes = Set(HyMT3Languages.rightToLeft.map(\.code))
|
||||
#expect(codes.isSuperset(of: ["ar", "he", "fa", "ur", "ps", "sd", "ug", "ckb", "yi", "kk"]))
|
||||
#expect(!codes.contains("de"))
|
||||
}
|
||||
|
||||
@Test func displayNamesNeverEnterThePrompt() {
|
||||
let german = HyMT3Languages.german
|
||||
#expect(german.modelName == "German")
|
||||
#expect(!german.displayName.isEmpty)
|
||||
#expect(!german.localizedDisplayName.isEmpty)
|
||||
#expect(
|
||||
HyMT3Prompt.defaultTranslation(target: german, source: "x")
|
||||
.contains("into German.")
|
||||
)
|
||||
}
|
||||
|
||||
@Test func commonTargetsAreTheDocumentedFifteen() {
|
||||
#expect(HyMT3Languages.common.map(\.code) == [
|
||||
"en", "de", "fr", "es", "it", "pt", "nl", "pl", "zh", "ja", "ko", "ar", "tr", "ru", "uk",
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import SprachmittlerText
|
||||
import Testing
|
||||
@testable import SprachmittlerEngines
|
||||
|
||||
@Suite("Output validation")
|
||||
struct OutputValidatorTests {
|
||||
private let validator = OutputValidator()
|
||||
private let scanner = ProtectedTokenScanner()
|
||||
|
||||
@Test func cleanOutputHasNoWarnings() {
|
||||
let source = "Open https://example.com and write to a@example.com."
|
||||
let translation = "Öffne https://example.com und schreibe an a@example.com."
|
||||
let result = validator.validate(
|
||||
source: source,
|
||||
translation: translation,
|
||||
doneReason: "stop",
|
||||
tokens: scanner.scan(source)
|
||||
)
|
||||
#expect(result == .clean)
|
||||
#expect(!result.blocksReplacement)
|
||||
}
|
||||
|
||||
@Test func missingURLIsAWarning() {
|
||||
let source = "Open https://example.com now."
|
||||
let result = validator.validate(
|
||||
source: source,
|
||||
translation: "Öffne jetzt.",
|
||||
doneReason: "stop",
|
||||
tokens: scanner.scan(source)
|
||||
)
|
||||
#expect(result.warnings.contains(.missingProtectedToken("https://example.com")))
|
||||
#expect(result.blocksReplacement)
|
||||
}
|
||||
|
||||
@Test func preambleIsDetectedAndKept() {
|
||||
let translation = "Here is the translation:\n\nThe text."
|
||||
let result = validator.validate(
|
||||
source: "The text.",
|
||||
translation: translation,
|
||||
doneReason: "stop",
|
||||
tokens: []
|
||||
)
|
||||
#expect(result.warnings.contains(.preambleDetected(firstLine: "Here is the translation:")))
|
||||
#expect(result.blocksReplacement)
|
||||
}
|
||||
|
||||
@Test func aColonWithoutABlankLineIsNotAPreamble() {
|
||||
let result = validator.validate(
|
||||
source: "Note:\nThe text.",
|
||||
translation: "Note:\nThe text.",
|
||||
doneReason: "stop",
|
||||
tokens: []
|
||||
)
|
||||
#expect(!result.warnings.contains {
|
||||
if case .preambleDetected = $0 {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@Test func lengthReasonIsTruncated() {
|
||||
let result = validator.validate(
|
||||
source: "x",
|
||||
translation: "x",
|
||||
doneReason: "length",
|
||||
tokens: []
|
||||
)
|
||||
#expect(result.warnings.contains(.truncated))
|
||||
#expect(result.blocksReplacement)
|
||||
}
|
||||
|
||||
@Test func emptyOutputIsBlocking() {
|
||||
let result = validator.validate(
|
||||
source: "x",
|
||||
translation: " ",
|
||||
doneReason: "stop",
|
||||
tokens: []
|
||||
)
|
||||
#expect(result.warnings == [.emptyOutput])
|
||||
#expect(result.blocksReplacement)
|
||||
}
|
||||
|
||||
@Test func repetitionLoopIsDetected() {
|
||||
let line = "This line repeats exactly."
|
||||
let translation = Array(repeating: line, count: 7).joined(separator: "\n")
|
||||
let result = validator.validate(
|
||||
source: "x",
|
||||
translation: translation,
|
||||
doneReason: "stop",
|
||||
tokens: []
|
||||
)
|
||||
#expect(result.warnings.contains(.repetitionLoop))
|
||||
#expect(result.blocksReplacement)
|
||||
}
|
||||
|
||||
@Test func numericMismatchIsNonBlocking() {
|
||||
let result = validator.validate(
|
||||
source: "It costs 1.5 EUR in 2026.",
|
||||
translation: "Es kostet 1,5 EUR.",
|
||||
doneReason: "stop",
|
||||
tokens: []
|
||||
)
|
||||
#expect(result.warnings.contains(.numericMismatch))
|
||||
#expect(!result.blocksReplacement)
|
||||
}
|
||||
|
||||
@Test func localeNumbersMatchSemantically() {
|
||||
let result = validator.validate(
|
||||
source: "It costs 1.5 EUR.",
|
||||
translation: "Es kostet 1,5 EUR.",
|
||||
doneReason: "stop",
|
||||
tokens: []
|
||||
)
|
||||
#expect(!result.warnings.contains(.numericMismatch))
|
||||
}
|
||||
|
||||
@Test func duplicateTokenCountMustMatch() {
|
||||
let source = "https://example.com and https://example.com"
|
||||
let result = validator.validate(
|
||||
source: source,
|
||||
translation: "https://example.com",
|
||||
doneReason: "stop",
|
||||
tokens: scanner.scan(source)
|
||||
)
|
||||
#expect(result.warnings.contains(.missingProtectedToken("https://example.com")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import SprachmittlerEngines
|
||||
|
||||
@Suite("Documented prompts")
|
||||
struct PromptGoldenTests {
|
||||
private func fixture(_ name: String) throws -> String {
|
||||
let base = try #require(Bundle.module.resourceURL)
|
||||
let url = base.appendingPathComponent("Fixtures/\(name)")
|
||||
var text = try String(contentsOf: url, encoding: .utf8)
|
||||
// Fixtures have one final line terminator; the production prompt has none. Remove exactly
|
||||
// that one terminator so an accidental extra newline still fails the comparison.
|
||||
if text.hasSuffix("\n") {
|
||||
text.removeLast()
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
@Test func defaultPromptMatchesTheGoldenFile() throws {
|
||||
let expected = try fixture("default-prompt.txt")
|
||||
.replacingOccurrences(of: "{target_lang}", with: "German")
|
||||
.replacingOccurrences(of: "{source_text}", with: "Hello.")
|
||||
#expect(HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "Hello.") == expected)
|
||||
}
|
||||
|
||||
@Test func delimitersPromptMatchesTheGoldenFile() throws {
|
||||
let expected = try fixture("delimiters-prompt.txt")
|
||||
.replacingOccurrences(of: "{target_lang}", with: "German")
|
||||
.replacingOccurrences(of: "{source_text}", with: "Use {{limit}}.")
|
||||
#expect(
|
||||
HyMT3Prompt.delimiters(target: HyMT3Languages.german, source: "Use {{limit}}.")
|
||||
== expected
|
||||
)
|
||||
}
|
||||
|
||||
@Test func structuredData1MatchesTheGoldenFile() throws {
|
||||
let expected = try fixture("structured-data-1-prompt.txt")
|
||||
.replacingOccurrences(of: "{format_type}", with: "JSON")
|
||||
.replacingOccurrences(of: "{target_lang}", with: "German")
|
||||
.replacingOccurrences(of: "{source_text}", with: #"{"name":"value"}"#)
|
||||
#expect(
|
||||
HyMT3Prompt.structuredData1(
|
||||
format: .json,
|
||||
target: HyMT3Languages.german,
|
||||
source: #"{"name":"value"}"#
|
||||
) == expected
|
||||
)
|
||||
}
|
||||
|
||||
@Test func prefixIsStableForTheSameTarget() {
|
||||
let first = HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "One.")
|
||||
let second = HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "Two.")
|
||||
let prefix = "Translate the following text into German. Note that you should "
|
||||
+ "**only output the translated result without any additional explanation**:\n\n"
|
||||
#expect(first.hasPrefix(prefix))
|
||||
#expect(second.hasPrefix(prefix))
|
||||
#expect(first != second)
|
||||
}
|
||||
|
||||
@Test func variantsResolveToDocumentedTemplates() {
|
||||
#expect(
|
||||
HyMT3Prompt.text(for: .structuredData1(format: .markdown), target: HyMT3Languages.german, source: "x")
|
||||
.contains("### Task")
|
||||
)
|
||||
#expect(
|
||||
HyMT3Prompt.text(for: .delimiters, target: HyMT3Languages.german, source: "x")
|
||||
.contains("retain the exact same number of delimiters")
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import SprachmittlerText
|
||||
import Testing
|
||||
@testable import SprachmittlerEngines
|
||||
|
||||
@Suite("Prompt policy")
|
||||
struct PromptPolicyTests {
|
||||
private let policy = PromptPolicy()
|
||||
private let token = ProtectedToken(kind: .url, value: "https://example.com")
|
||||
|
||||
@Test func v1StartsWithDefaultForEveryContentClass() {
|
||||
for content in ContentClass.allCases {
|
||||
#expect(policy.initialPrompt(for: content) == .defaultTranslation)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func structuredContentUsesStructuredData1AfterALostToken() {
|
||||
#expect(policy.retryPrompt(for: .json, lostToken: token) == .structuredData1(format: .json))
|
||||
#expect(policy.retryPrompt(for: .html, lostToken: token) == .structuredData1(format: .html))
|
||||
#expect(policy.retryPrompt(for: .markdown, lostToken: token) == .structuredData1(format: .markdown))
|
||||
}
|
||||
|
||||
@Test func plainAndDelimitedTextUseDelimitersAfterALostToken() {
|
||||
#expect(policy.retryPrompt(for: .plain, lostToken: token) == .delimiters)
|
||||
#expect(policy.retryPrompt(for: .delimited, lostToken: token) == .delimiters)
|
||||
#expect(policy.retryPrompt(for: .code, lostToken: token) == .delimiters)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("Repetition and numbers")
|
||||
struct RepetitionAndNumberTests {
|
||||
@Test func detectsARepeatedLine() {
|
||||
let text = Array(repeating: "This is a repeated line.", count: 6).joined(separator: "\n")
|
||||
#expect(RepetitionDetector.detectsLoop(in: text))
|
||||
}
|
||||
|
||||
@Test func doesNotFlagOrdinaryText() {
|
||||
#expect(!RepetitionDetector.detectsLoop(in: "This is an ordinary translation with no loop."))
|
||||
}
|
||||
|
||||
@Test func detectsARepeatedWindow() {
|
||||
let window = String(repeating: "a", count: 64)
|
||||
#expect(RepetitionDetector.detectsLoop(in: String(repeating: window, count: 8)))
|
||||
}
|
||||
|
||||
@Test func incrementalDetectorFiresWhileStreaming() {
|
||||
var detector = RepetitionDetector()
|
||||
var fired = false
|
||||
for _ in 0 ..< 6 {
|
||||
fired = detector.append("This is a repeated line.\n")
|
||||
}
|
||||
#expect(fired)
|
||||
}
|
||||
|
||||
@Test func numericNormalisationTreatsLocaleSeparatorsAsEqual() {
|
||||
#expect(NumericTokenNormalizer.normalize("1.5") == "1.5")
|
||||
#expect(NumericTokenNormalizer.normalize("1,5") == "1.5")
|
||||
#expect(NumericTokenNormalizer.normalize("1 000") == "1000")
|
||||
#expect(NumericTokenNormalizer.normalize("1,234.56") == "1234.56")
|
||||
#expect(NumericTokenNormalizer.normalize("1.234,56") == "1234.56")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import Testing
|
||||
@testable import SprachmittlerText
|
||||
|
||||
@Suite("Chunker")
|
||||
struct ChunkerTests {
|
||||
@Test func splitsLongLatinTextAtParagraphsAndRoundTrips() {
|
||||
let paragraph = String(repeating: "The quick brown fox jumps over the lazy dog. ", count: 25)
|
||||
let text = Array(repeating: paragraph, count: 9).joined(separator: "\n\n")
|
||||
let chunker = Chunker()
|
||||
let chunks = chunker.chunks(for: text)
|
||||
|
||||
#expect(chunks.count > 1)
|
||||
#expect(chunks.allSatisfy { $0.text.count <= 4000 })
|
||||
#expect(Chunker.reassemble(chunks) == text)
|
||||
#expect(chunks.dropLast().contains { $0.separatorAfter.contains("\n\n") })
|
||||
}
|
||||
|
||||
@Test func cjkUsesTheSmallerLimit() {
|
||||
let text = String(repeating: "你好世界。", count: 900)
|
||||
let chunks = Chunker().chunks(for: text)
|
||||
|
||||
#expect(TextScript.isDense(text))
|
||||
#expect(chunks.count > 1)
|
||||
#expect(chunks.allSatisfy { $0.text.count <= 2000 })
|
||||
#expect(Chunker.reassemble(chunks) == text)
|
||||
}
|
||||
|
||||
@Test func neverSplitsAGraphemeCluster() {
|
||||
let family = "👨👩👧👦"
|
||||
let text = String(repeating: family, count: 20)
|
||||
let chunks = Chunker(latinLimit: 1, denseLimit: 1).chunks(for: text)
|
||||
|
||||
#expect(chunks.count == 20)
|
||||
#expect(chunks.allSatisfy { $0.text == family })
|
||||
#expect(Chunker.reassemble(chunks) == text)
|
||||
}
|
||||
|
||||
@Test func splitsASingleLongWord() {
|
||||
let text = String(repeating: "a", count: 5000)
|
||||
let chunks = Chunker(latinLimit: 100, denseLimit: 100).chunks(for: text)
|
||||
|
||||
#expect(chunks.count >= 50)
|
||||
#expect(chunks.allSatisfy { $0.text.count <= 100 })
|
||||
#expect(Chunker.reassemble(chunks) == text)
|
||||
}
|
||||
|
||||
@Test func leadingBlankLinesRoundTripExactly() {
|
||||
let text = "\n\nHello world."
|
||||
let chunks = Chunker().chunks(for: text)
|
||||
#expect(Chunker.reassemble(chunks) == text)
|
||||
}
|
||||
|
||||
@Test func leadingWhitespaceInLongTextRoundTripsExactly() {
|
||||
let text = " " + String(repeating: "word ", count: 10)
|
||||
let chunks = Chunker(latinLimit: 10, denseLimit: 10).chunks(for: text)
|
||||
#expect(Chunker.reassemble(chunks) == text)
|
||||
}
|
||||
|
||||
@Test func emptyTextHasNoChunks() {
|
||||
#expect(Chunker().chunks(for: "").isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import Testing
|
||||
@testable import SprachmittlerText
|
||||
|
||||
@Suite("Content classifier")
|
||||
struct ContentClassifierTests {
|
||||
private let classifier = ContentClassifier()
|
||||
|
||||
@Test func classifiesPlainProse() {
|
||||
#expect(classifier.classify("The quick brown fox jumps over the lazy dog.") == .plain)
|
||||
#expect(classifier.classify("If x < y < z then the order is strict.") == .plain)
|
||||
}
|
||||
|
||||
@Test func classifiesJSON() {
|
||||
#expect(classifier.classify(#"{"name":"value","count":2}"#) == .json)
|
||||
}
|
||||
|
||||
@Test func classifiesHTML() {
|
||||
#expect(classifier.classify("<div><p>Hello</p></div>") == .html)
|
||||
}
|
||||
|
||||
@Test func classifiesMarkdown() {
|
||||
#expect(classifier.classify("# Heading\n\n- one\n- two") == .markdown)
|
||||
}
|
||||
|
||||
@Test func classifiesDelimiterHeavyText() {
|
||||
#expect(
|
||||
classifier.classify("Use {{a}}, {{b}}, {{c}} and https://example.com today.")
|
||||
== .delimited
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import Testing
|
||||
@testable import SprachmittlerText
|
||||
|
||||
@Suite("Language detection")
|
||||
struct LanguageDetectorTests {
|
||||
private let detector = NaturalLanguageDetector()
|
||||
|
||||
@Test func detectsGerman() throws {
|
||||
let detection = try #require(
|
||||
detector.detect(
|
||||
"Die schnelle Katze springt über den faulen Hund. Das ist ein deutscher Satz mit genügend Wörtern."
|
||||
)
|
||||
)
|
||||
#expect(detection.code == "de")
|
||||
#expect(detection.confidence > 0.5)
|
||||
}
|
||||
|
||||
@Test func detectsEnglish() throws {
|
||||
let detection = try #require(
|
||||
detector.detect(
|
||||
"The quick brown fox jumps over the lazy dog. This is an English paragraph with enough words."
|
||||
)
|
||||
)
|
||||
#expect(detection.code == "en")
|
||||
#expect(detection.confidence > 0.5)
|
||||
}
|
||||
|
||||
@Test func emptyTextHasNoDetection() {
|
||||
#expect(detector.detect(" ") == nil)
|
||||
#expect(detector.detect("") == nil)
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import Testing
|
||||
@testable import SprachmittlerText
|
||||
|
||||
@Suite("Protected token scanner")
|
||||
struct ProtectedTokenScannerTests {
|
||||
private let scanner = ProtectedTokenScanner()
|
||||
|
||||
@Test func findsEveryTokenKind() {
|
||||
let text = """
|
||||
Visit https://example.com/docs?lang=en#top and mail name@example.com.
|
||||
Use {{ limit }}, ${name}, %s, %1$@ and %02d.
|
||||
Inline `let x = 1` and:
|
||||
```swift
|
||||
let y = 2
|
||||
```
|
||||
<a href="https://example.com">link</a>
|
||||
Path /Users/someone/file.txt and key: {"name":"value"}
|
||||
"""
|
||||
let kinds = Set(scanner.scan(text).map(\.kind))
|
||||
|
||||
#expect(kinds.contains(.url))
|
||||
#expect(kinds.contains(.email))
|
||||
#expect(kinds.contains(.mustache))
|
||||
#expect(kinds.contains(.templateLiteral))
|
||||
#expect(kinds.contains(.printf))
|
||||
#expect(kinds.contains(.codeSpan))
|
||||
#expect(kinds.contains(.fencedCode))
|
||||
#expect(kinds.contains(.htmlTag))
|
||||
#expect(kinds.contains(.jsonKey))
|
||||
#expect(kinds.contains(.filePath))
|
||||
}
|
||||
|
||||
@Test func trimsSentencePunctuationFromURLs() {
|
||||
let tokens = scanner.scan("See https://example.com/a. Then https://example.com/b?x=1)")
|
||||
let urls = tokens.filter { $0.kind == .url }.map(\.value)
|
||||
#expect(urls.contains("https://example.com/a"))
|
||||
#expect(urls.contains("https://example.com/b?x=1"))
|
||||
}
|
||||
|
||||
@Test func ordinaryTextHasNoTokens() {
|
||||
let tokens = scanner.scan("Costs 3.50 (approx.) - see the note; 100% done.")
|
||||
#expect(tokens.isEmpty)
|
||||
}
|
||||
|
||||
@Test func htmlTagKeepsItsURL() {
|
||||
let token = scanner.scan("<a href=\"https://example.com\">x</a>").first { $0.kind == .htmlTag }
|
||||
#expect(token?.value == "<a href=\"https://example.com\">")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import SprachmittlerText
|
||||
|
||||
@Suite("Text normalisation")
|
||||
struct TextNormalizationTests {
|
||||
@Test func inputNormalisationFollowsN1ToN3() {
|
||||
let input = "\u{FEFF} Hello\r\nworld\u{0}\u{200B}\u{1}\u{200D}\u{200C} "
|
||||
#expect(TextNormalization.normalizeInput(input) == "Hello\nworld\u{200D}\u{200C}")
|
||||
}
|
||||
|
||||
@Test func outputOnlyTrimsAndNormalisesLineEndings() {
|
||||
let output = " first line\r\n\tsecond line \n\nthird "
|
||||
#expect(TextNormalization.normalizeOutput(output) == "first line\n\tsecond line \n\nthird")
|
||||
}
|
||||
|
||||
@Test func comparisonNormalisationKeepsInternalWhitespace() {
|
||||
#expect(
|
||||
TextNormalization.normalizeForComparison(" a \t b\r\n") == "a \t b"
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user