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,26 @@
|
||||
import Foundation
|
||||
|
||||
/// One pasteboard item's type-to-data map. The key is the raw pasteboard type.
|
||||
public struct ClipboardItemData: Sendable, Equatable {
|
||||
/// The item's data, keyed by pasteboard type.
|
||||
public let data: [String: Data]
|
||||
|
||||
/// Creates an item snapshot.
|
||||
public init(data: [String: Data]) {
|
||||
self.data = data
|
||||
}
|
||||
}
|
||||
|
||||
/// A full pasteboard snapshot used only for the Replace paste fallback.
|
||||
public struct ClipboardSnapshot: Sendable, Equatable {
|
||||
/// Every item, in pasteboard order.
|
||||
public let items: [ClipboardItemData]
|
||||
/// The `changeCount` when the snapshot was taken.
|
||||
public let changeCount: Int
|
||||
|
||||
/// Creates a snapshot.
|
||||
public init(items: [ClipboardItemData], changeCount: Int) {
|
||||
self.items = items
|
||||
self.changeCount = changeCount
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import Foundation
|
||||
|
||||
/// The double-copy state machine result (`docs/SELECTION_AND_CLIPBOARD.md` §2).
|
||||
public enum DoubleCopyOutcome: Sendable, Equatable {
|
||||
/// No trigger.
|
||||
case none
|
||||
/// A valid double copy; the value is normalised line endings and trimmed, internal whitespace kept.
|
||||
case captured(String)
|
||||
/// The change had no usable text; the state was reset.
|
||||
case empty
|
||||
}
|
||||
|
||||
/// The pure double-copy state machine. It has no pasteboard or timer dependency.
|
||||
public struct DoubleCopyDetector: Sendable {
|
||||
/// Detector configuration.
|
||||
public struct Configuration: Sendable, Equatable {
|
||||
/// The two-copy window; 500 ms by default (range 300–1000).
|
||||
public let window: TimeInterval
|
||||
|
||||
/// Creates a configuration.
|
||||
public init(window: TimeInterval = 0.5) {
|
||||
self.window = window
|
||||
}
|
||||
}
|
||||
|
||||
private struct Candidate {
|
||||
let changeCount: Int
|
||||
let text: String
|
||||
let date: Date
|
||||
}
|
||||
|
||||
private let configuration: Configuration
|
||||
private var candidate: Candidate?
|
||||
|
||||
/// Creates a detector.
|
||||
public init(configuration: Configuration = Configuration()) {
|
||||
self.configuration = configuration
|
||||
}
|
||||
|
||||
/// Records one changed pasteboard value and returns the outcome.
|
||||
public mutating func record(changeCount: Int, text: String?, at date: Date) -> DoubleCopyOutcome {
|
||||
guard let text else {
|
||||
candidate = nil
|
||||
return .empty
|
||||
}
|
||||
let normalized = text
|
||||
.replacingOccurrences(of: "\r\n", with: "\n")
|
||||
.replacingOccurrences(of: "\r", with: "\n")
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard normalized.contains(where: { !$0.isWhitespace }) else {
|
||||
candidate = nil
|
||||
return .empty
|
||||
}
|
||||
|
||||
if let candidate {
|
||||
if candidate.changeCount == changeCount {
|
||||
return .none
|
||||
}
|
||||
let elapsed = date.timeIntervalSince(candidate.date)
|
||||
if candidate.text == normalized, elapsed >= 0, elapsed <= configuration.window {
|
||||
self.candidate = nil
|
||||
return .captured(normalized)
|
||||
}
|
||||
}
|
||||
candidate = Candidate(changeCount: changeCount, text: normalized, date: date)
|
||||
return .none
|
||||
}
|
||||
|
||||
/// Forgets the remembered copy. Call when the session starts or the window expires.
|
||||
public mutating func reset() {
|
||||
candidate = nil
|
||||
}
|
||||
|
||||
/// Clears the remembered copy once the two-copy window has passed, so no text is retained
|
||||
/// longer than necessary.
|
||||
public mutating func expire(at date: Date) {
|
||||
guard let candidate, date.timeIntervalSince(candidate.date) > configuration.window else {
|
||||
return
|
||||
}
|
||||
self.candidate = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import Foundation
|
||||
|
||||
/// The pasteboard operations `SprachmittlerCapture` needs. Tests use a fake; the app uses
|
||||
/// `SystemPasteboard`. Every member is main-actor isolated because `NSPasteboard` is.
|
||||
@MainActor
|
||||
public protocol PasteboardAccessing: AnyObject {
|
||||
/// The current pasteboard change count.
|
||||
var changeCount: Int { get }
|
||||
|
||||
/// The plain-text string, read only after `changeCount` changed.
|
||||
func string() -> String?
|
||||
|
||||
/// True when the pasteboard contains our own marker or a transient/concealed marker.
|
||||
func containsOwnWriteMarkers() -> Bool
|
||||
|
||||
/// Snapshots every item and type, forcing lazy data.
|
||||
func snapshot() -> ClipboardSnapshot?
|
||||
|
||||
/// Restores a snapshot only when `changeCount` still matches the recorded value.
|
||||
func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches: Int) -> Bool
|
||||
|
||||
/// Writes `text` with the own/transient/concealed markers and returns the new change count.
|
||||
@discardableResult
|
||||
func write(_ text: String) -> Int
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import Foundation
|
||||
|
||||
/// A source of pasteboard poll ticks. Production uses a 120 ms timer; tests drive it manually.
|
||||
public protocol PasteboardTicking: Sendable {
|
||||
/// A stream of ticks. Cancelling the consuming task must terminate the stream.
|
||||
func ticks() -> AsyncStream<Void>
|
||||
}
|
||||
|
||||
/// The production 120 ms ticker (`docs/SELECTION_AND_CLIPBOARD.md` §2).
|
||||
public struct TimerPasteboardTicker: PasteboardTicking {
|
||||
/// The poll interval.
|
||||
public let interval: Duration
|
||||
|
||||
/// Creates a ticker.
|
||||
public init(interval: Duration = .milliseconds(120)) {
|
||||
self.interval = interval
|
||||
}
|
||||
|
||||
public func ticks() -> AsyncStream<Void> {
|
||||
AsyncStream { continuation in
|
||||
let task = Task {
|
||||
while !Task.isCancelled {
|
||||
do {
|
||||
try await Task.sleep(for: interval)
|
||||
} catch {
|
||||
break
|
||||
}
|
||||
continuation.yield(())
|
||||
}
|
||||
continuation.finish()
|
||||
}
|
||||
continuation.onTermination = { _ in task.cancel() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
|
||||
/// A pasteboard watcher event.
|
||||
public enum PasteboardWatcherEvent: Sendable, Equatable {
|
||||
/// A validated double copy.
|
||||
case captured(CapturedText)
|
||||
/// The copied text is above the script-aware limit.
|
||||
case textTooLong(characters: Int, limit: Int)
|
||||
/// The change had no usable text.
|
||||
case noText
|
||||
/// A change was our own write or the marker/suppression window.
|
||||
case ignoredOwnWrite
|
||||
}
|
||||
|
||||
/// Polls `changeCount`, reads the string only after a change, and emits double copies.
|
||||
///
|
||||
/// This type never reads the pasteboard in the background: `poll` first compares `changeCount`
|
||||
/// and only then reads the string.
|
||||
@MainActor
|
||||
public final class PasteboardWatcher {
|
||||
/// The own-write suppression window.
|
||||
public static let suppressionWindow: TimeInterval = 0.75
|
||||
|
||||
private let pasteboard: any PasteboardAccessing
|
||||
private let ticker: any PasteboardTicking
|
||||
private let now: @MainActor () -> Date
|
||||
private var detector: DoubleCopyDetector
|
||||
private var lastChangeCount: Int
|
||||
private var suppressUntil = Date.distantPast
|
||||
private var task: Task<Void, Never>?
|
||||
|
||||
/// True while the poll task is running.
|
||||
public private(set) var isRunning = false
|
||||
|
||||
/// Creates a watcher. The initial change count is recorded without reading any string.
|
||||
public init(
|
||||
pasteboard: any PasteboardAccessing,
|
||||
configuration: DoubleCopyDetector.Configuration = DoubleCopyDetector.Configuration(),
|
||||
ticker: any PasteboardTicking = TimerPasteboardTicker(),
|
||||
now: @escaping @MainActor () -> Date = { Date() }
|
||||
) {
|
||||
self.pasteboard = pasteboard
|
||||
detector = DoubleCopyDetector(configuration: configuration)
|
||||
self.ticker = ticker
|
||||
self.now = now
|
||||
lastChangeCount = pasteboard.changeCount
|
||||
}
|
||||
|
||||
/// Starts polling. Calling it twice is a no-op.
|
||||
public func start(onEvent: @escaping @MainActor (PasteboardWatcherEvent) -> Void) {
|
||||
guard task == nil else { return }
|
||||
lastChangeCount = pasteboard.changeCount
|
||||
detector.reset()
|
||||
isRunning = true
|
||||
let ticker = ticker
|
||||
task = Task { [weak self] in
|
||||
for await _ in ticker.ticks() {
|
||||
guard let self else { break }
|
||||
if let event = poll(at: now()) {
|
||||
onEvent(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops polling and releases the in-memory copies.
|
||||
public func stop() {
|
||||
task?.cancel()
|
||||
task = nil
|
||||
isRunning = false
|
||||
detector.reset()
|
||||
}
|
||||
|
||||
/// Polls once. Public so component tests can avoid real time.
|
||||
@discardableResult
|
||||
public func poll(at date: Date) -> PasteboardWatcherEvent? {
|
||||
let count = pasteboard.changeCount
|
||||
guard count != lastChangeCount else {
|
||||
detector.expire(at: date)
|
||||
return nil
|
||||
}
|
||||
lastChangeCount = count
|
||||
|
||||
if date < suppressUntil {
|
||||
return .ignoredOwnWrite
|
||||
}
|
||||
if pasteboard.containsOwnWriteMarkers() {
|
||||
suppressUntil = date.addingTimeInterval(Self.suppressionWindow)
|
||||
detector.reset()
|
||||
return .ignoredOwnWrite
|
||||
}
|
||||
|
||||
guard let string = pasteboard.string() else {
|
||||
detector.reset()
|
||||
return .noText
|
||||
}
|
||||
|
||||
switch detector.record(changeCount: count, text: string, at: date) {
|
||||
case .none:
|
||||
return nil
|
||||
case .empty:
|
||||
return .noText
|
||||
case let .captured(text):
|
||||
let limit = CaptureLimits.characters(for: text)
|
||||
guard text.count <= limit else {
|
||||
detector.reset()
|
||||
return .textTooLong(characters: text.count, limit: limit)
|
||||
}
|
||||
detector.reset()
|
||||
return .captured(CapturedText(text: text, capturedAt: date, source: .doubleCopy))
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks a clipboard write by this app so the watcher suppresses it and the next changes.
|
||||
public func noteOwnWrite(at date: Date) {
|
||||
suppressUntil = date.addingTimeInterval(Self.suppressionWindow)
|
||||
detector.reset()
|
||||
}
|
||||
|
||||
/// Clears the remembered copy without stopping the watcher.
|
||||
public func clear() {
|
||||
detector.reset()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
|
||||
/// The Services entry point (`docs/SELECTION_AND_CLIPBOARD.md` §6).
|
||||
///
|
||||
/// The system supplies the pasteboard, so this path needs no Accessibility permission and no
|
||||
/// polling. `AppDelegate` installs this object as `NSApp.servicesProvider`.
|
||||
///
|
||||
/// `@unchecked Sendable` is safe: the only stored value is an immutable `@Sendable` closure, and
|
||||
/// AppKit invokes the selector on the main thread.
|
||||
public final class ServicesProvider: NSObject, @unchecked Sendable {
|
||||
/// The captured-text handler. The app hops to the main actor itself.
|
||||
public typealias Handler = @Sendable (CapturedText) -> Void
|
||||
|
||||
private let handler: Handler
|
||||
|
||||
/// Creates a provider.
|
||||
public init(handler: @escaping Handler) {
|
||||
self.handler = handler
|
||||
super.init()
|
||||
}
|
||||
|
||||
/// The `NSMessage = translateSelection` selector from Info.plist.
|
||||
@objc
|
||||
@MainActor
|
||||
public func translateSelection(
|
||||
_ pasteboard: NSPasteboard,
|
||||
userData: String,
|
||||
error: AutoreleasingUnsafeMutablePointer<NSString>
|
||||
) {
|
||||
guard !SystemPasteboard.containsOwnWriteMarkers(in: pasteboard),
|
||||
let text = pasteboard.string(forType: .string),
|
||||
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
else {
|
||||
error.pointee = "No text was selected." as NSString
|
||||
return
|
||||
}
|
||||
handler(CapturedText(text: text, capturedAt: Date(), source: .services))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
|
||||
/// The production pasteboard adapter. This is the only type that touches `NSPasteboard.general`.
|
||||
@MainActor
|
||||
public final class SystemPasteboard: PasteboardAccessing {
|
||||
private nonisolated static let ownType = NSPasteboard.PasteboardType("com.schihei.sprachmittler.own")
|
||||
private nonisolated static let transientType = NSPasteboard.PasteboardType("org.nspasteboard.TransientType")
|
||||
private nonisolated static let concealedType = NSPasteboard.PasteboardType("org.nspasteboard.ConcealedType")
|
||||
|
||||
private let pasteboard: NSPasteboard
|
||||
|
||||
/// Creates an adapter for the general pasteboard.
|
||||
public init(pasteboard: NSPasteboard = .general) {
|
||||
self.pasteboard = pasteboard
|
||||
}
|
||||
|
||||
public var changeCount: Int {
|
||||
pasteboard.changeCount
|
||||
}
|
||||
|
||||
public func string() -> String? {
|
||||
pasteboard.string(forType: .string)
|
||||
}
|
||||
|
||||
public func containsOwnWriteMarkers() -> Bool {
|
||||
Self.containsOwnWriteMarkers(in: pasteboard)
|
||||
}
|
||||
|
||||
/// True when a pasteboard carries our own or a transient/concealed marker.
|
||||
public nonisolated static func containsOwnWriteMarkers(in pasteboard: NSPasteboard) -> Bool {
|
||||
let types = pasteboard.types ?? []
|
||||
return types.contains(ownType)
|
||||
|| types.contains(transientType)
|
||||
|| types.contains(concealedType)
|
||||
}
|
||||
|
||||
public func snapshot() -> ClipboardSnapshot? {
|
||||
let items = pasteboard.pasteboardItems ?? []
|
||||
let snapshots = items.map { item -> ClipboardItemData in
|
||||
var data: [String: Data] = [:]
|
||||
for type in item.types {
|
||||
// `data(forType:)` forces lazy providers now; an unresolved provider is skipped.
|
||||
if let value = item.data(forType: type) {
|
||||
data[type.rawValue] = value
|
||||
}
|
||||
}
|
||||
return ClipboardItemData(data: data)
|
||||
}
|
||||
return ClipboardSnapshot(items: snapshots, changeCount: pasteboard.changeCount)
|
||||
}
|
||||
|
||||
public func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches expected: Int) -> Bool {
|
||||
guard pasteboard.changeCount == expected else { return false }
|
||||
pasteboard.clearContents()
|
||||
guard !snapshot.items.isEmpty else { return true }
|
||||
|
||||
let items = snapshot.items.map { snapshotItem -> NSPasteboardItem in
|
||||
let item = NSPasteboardItem()
|
||||
for (type, data) in snapshotItem.data {
|
||||
item.setData(data, forType: NSPasteboard.PasteboardType(type))
|
||||
}
|
||||
return item
|
||||
}
|
||||
return pasteboard.writeObjects(items)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
public func write(_ text: String) -> Int {
|
||||
pasteboard.clearContents()
|
||||
pasteboard.setString(text, forType: .string)
|
||||
let marker = Data()
|
||||
pasteboard.setData(marker, forType: Self.ownType)
|
||||
pasteboard.setData(marker, forType: Self.transientType)
|
||||
pasteboard.setData(marker, forType: Self.concealedType)
|
||||
return pasteboard.changeCount
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import SprachmittlerText
|
||||
|
||||
/// The capture character limit for a text, based on its script (`docs/TRANSLATION_OUTPUT.md` §3).
|
||||
public enum CaptureLimits {
|
||||
/// 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts.
|
||||
public static func characters(for text: String) -> Int {
|
||||
Chunker().limit(for: text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import SprachmittlerText
|
||||
|
||||
/// The result of validating a captured text before any translation request.
|
||||
public enum CaptureValidation: Sendable, Equatable {
|
||||
/// The text may be translated.
|
||||
case valid
|
||||
/// The text has no non-whitespace character.
|
||||
case empty
|
||||
/// The text exceeds the script-aware limit.
|
||||
case textTooLong(characters: Int, limit: Int)
|
||||
}
|
||||
|
||||
/// Applies the capture rules shared by double copy, the menu and Services.
|
||||
public enum CapturePolicy {
|
||||
/// Validates non-emptiness and the 4000/2000 script-aware limit.
|
||||
public static func validate(_ text: String) -> CaptureValidation {
|
||||
guard text.contains(where: { !$0.isWhitespace }) else { return .empty }
|
||||
let limit = CaptureLimits.characters(for: text)
|
||||
let characters = text.count
|
||||
guard characters <= limit else {
|
||||
return .textTooLong(characters: characters, limit: limit)
|
||||
}
|
||||
return .valid
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import SprachmittlerText
|
||||
|
||||
/// Capture-side text helpers. Kept in Core so `SprachmittlerCapture` never imports the text
|
||||
/// module directly (ARCHITECTURE §4).
|
||||
public enum CaptureText {
|
||||
/// Double-copy comparison: line endings and outer trimming only.
|
||||
public static func normalizeForComparison(_ text: String) -> String {
|
||||
TextNormalization.normalizeForComparison(text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import Foundation
|
||||
|
||||
/// Where a captured text came from (`docs/ARCHITECTURE.md` §5).
|
||||
public enum CaptureSource: String, Sendable, Codable, Equatable {
|
||||
/// The double-copy gesture.
|
||||
case doubleCopy
|
||||
/// The Services menu.
|
||||
case services
|
||||
/// The menu-bar item.
|
||||
case menu
|
||||
}
|
||||
|
||||
/// A non-empty text captured for translation.
|
||||
public struct CapturedText: Sendable, Equatable {
|
||||
/// The captured text.
|
||||
public let text: String
|
||||
/// When it was captured.
|
||||
public let capturedAt: Date
|
||||
/// Where it came from.
|
||||
public let source: CaptureSource
|
||||
|
||||
/// Creates a captured text.
|
||||
public init(text: String, capturedAt: Date, source: CaptureSource) {
|
||||
self.text = text
|
||||
self.capturedAt = capturedAt
|
||||
self.source = source
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import Foundation
|
||||
import SprachmittlerText
|
||||
|
||||
/// The target of a Replace action (`docs/SELECTION_AND_CLIPBOARD.md` §4).
|
||||
public struct InsertionTarget: Sendable, Equatable {
|
||||
/// The process that owned the selection.
|
||||
public let pid: pid_t
|
||||
/// The bundle identifier, when available.
|
||||
public let bundleID: String?
|
||||
/// The selected text at capture time, when available.
|
||||
public let selectedText: String?
|
||||
/// When the target was captured.
|
||||
public let capturedAt: Date
|
||||
|
||||
/// Creates an insertion target.
|
||||
public init(pid: pid_t, bundleID: String?, selectedText: String?, capturedAt: Date) {
|
||||
self.pid = pid
|
||||
self.bundleID = bundleID
|
||||
self.selectedText = selectedText
|
||||
self.capturedAt = capturedAt
|
||||
}
|
||||
}
|
||||
|
||||
/// How a Replace action succeeded.
|
||||
public enum InsertionMethod: String, Sendable, Equatable {
|
||||
/// Accessibility direct replacement.
|
||||
case accessibility
|
||||
/// Synthetic paste.
|
||||
case paste
|
||||
}
|
||||
|
||||
/// The outcome of a Replace action.
|
||||
public enum InsertionOutcome: Sendable, Equatable {
|
||||
/// The selection was replaced.
|
||||
case replaced(using: InsertionMethod)
|
||||
/// Nothing was inserted; the translation is on the clipboard.
|
||||
case copiedOnly
|
||||
/// The insertion failed.
|
||||
case failed(SprachmittlerError)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import SprachmittlerEngines
|
||||
|
||||
/// A BCP-47 language code. Codes are stored as their canonical string form.
|
||||
public typealias LanguageCode = String
|
||||
|
||||
/// The UI-facing name for a target language. The value type lives in `SprachmittlerEngines` because
|
||||
/// it carries the exact model-card name used by prompts (ADR-014, ADR-017).
|
||||
public typealias TargetLanguage = SprachmittlerEngines.ModelLanguage
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import SprachmittlerEngines
|
||||
|
||||
/// Validation warnings are defined in `SprachmittlerEngines`, where validation lives, and
|
||||
/// re-exported here for the session and UI layers.
|
||||
public typealias TranslationWarning = SprachmittlerEngines.TranslationWarning
|
||||
@@ -0,0 +1,52 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// The Hy-MT3 adapter: exact documented prompt, publisher sampling, no system message, no
|
||||
/// thinking and an explicit 8192-token context (`docs/HYMT3_MODEL.md` §1–§3).
|
||||
public struct HyMT3Adapter: TranslationAdapter {
|
||||
/// The stable adapter identifier.
|
||||
public let identifier = "hy-mt3"
|
||||
/// The adapter version.
|
||||
public let version = 1
|
||||
|
||||
/// Creates the adapter.
|
||||
public init() {}
|
||||
|
||||
/// Matches every Hy-MT3 tag, including 7B, 1.8B and 30B-A3B conversions.
|
||||
public func supports(model: String) -> Bool {
|
||||
HyMT3ModelPreset.isHyMT3(model)
|
||||
}
|
||||
|
||||
/// Builds one documented request. There is exactly one user message and no system message.
|
||||
public func makeRequest(_ request: AdapterRequest) -> ChatRequest {
|
||||
let content = HyMT3Prompt.text(for: request.prompt, target: request.target, source: request.text)
|
||||
return ChatRequest(
|
||||
model: request.model,
|
||||
messages: [ChatMessage(content: content)],
|
||||
stream: true,
|
||||
keepAlive: request.keepAlive,
|
||||
options: request.sampling.chatOptions()
|
||||
)
|
||||
}
|
||||
|
||||
/// A warm-up request with fixed synthetic text and `num_predict: 8` (T1.5).
|
||||
public func warmUpRequest(model: String, keepAlive: String) -> ChatRequest {
|
||||
ChatRequest(
|
||||
model: model,
|
||||
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
|
||||
stream: true,
|
||||
keepAlive: keepAlive,
|
||||
options: HyMT3Options.warmUp
|
||||
)
|
||||
}
|
||||
|
||||
/// A request that unloads the model after it completes.
|
||||
public func unloadRequest(model: String) -> ChatRequest {
|
||||
ChatRequest(
|
||||
model: model,
|
||||
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
|
||||
stream: true,
|
||||
keepAlive: "0",
|
||||
options: HyMT3Options.warmUp
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,202 @@
|
||||
/// The provisional common-language table for the M1 CLI. T2.3 replaces this with the complete
|
||||
/// 102-language catalogue from docs/LANGUAGES.md.
|
||||
import Foundation
|
||||
|
||||
/// The complete Hy-MT3 language catalogue from `docs/LANGUAGES.md`.
|
||||
///
|
||||
/// `modelName` is the exact English name from the model card and is the only value that may enter
|
||||
/// a prompt. BCP-47 variants collapse to the canonical entry; unknown codes return nil.
|
||||
public enum HyMT3Languages {
|
||||
/// English.
|
||||
public static let english = ModelLanguage(code: "en", modelName: "English")
|
||||
public static let english = lang("en", "English")
|
||||
/// German.
|
||||
public static let german = ModelLanguage(code: "de", modelName: "German")
|
||||
public static let german = lang("de", "German")
|
||||
|
||||
/// The common targets exposed by the M1 CLI.
|
||||
/// All 102 supported languages, in the documentation's order.
|
||||
public static let all: [ModelLanguage] = [
|
||||
// Supported since Hy-MT2 (33)
|
||||
lang("zh", "Chinese", display: "Chinese (Simplified)", dense: true),
|
||||
english,
|
||||
lang("fr", "French"),
|
||||
lang("pt", "Portuguese"),
|
||||
lang("es", "Spanish"),
|
||||
lang("ja", "Japanese", dense: true),
|
||||
lang("tr", "Turkish"),
|
||||
lang("ru", "Russian"),
|
||||
lang("ar", "Arabic", rtl: true, dense: true),
|
||||
lang("ko", "Korean", dense: true),
|
||||
lang("th", "Thai", dense: true),
|
||||
lang("it", "Italian"),
|
||||
german,
|
||||
ModelLanguage(code: "fr", modelName: "French"),
|
||||
ModelLanguage(code: "es", modelName: "Spanish"),
|
||||
ModelLanguage(code: "it", modelName: "Italian"),
|
||||
ModelLanguage(code: "pt", modelName: "Portuguese"),
|
||||
ModelLanguage(code: "nl", modelName: "Dutch"),
|
||||
ModelLanguage(code: "pl", modelName: "Polish"),
|
||||
ModelLanguage(code: "zh", modelName: "Chinese"),
|
||||
ModelLanguage(code: "zh-Hant", modelName: "Traditional Chinese"),
|
||||
ModelLanguage(code: "ja", modelName: "Japanese"),
|
||||
ModelLanguage(code: "ko", modelName: "Korean"),
|
||||
ModelLanguage(code: "ar", modelName: "Arabic"),
|
||||
ModelLanguage(code: "tr", modelName: "Turkish"),
|
||||
ModelLanguage(code: "ru", modelName: "Russian"),
|
||||
ModelLanguage(code: "uk", modelName: "Ukrainian"),
|
||||
lang("vi", "Vietnamese"),
|
||||
lang("ms", "Malay"),
|
||||
lang("id", "Indonesian"),
|
||||
lang("tl", "Filipino"),
|
||||
lang("hi", "Hindi", dense: true),
|
||||
lang("zh-Hant", "Traditional Chinese", dense: true),
|
||||
lang("pl", "Polish"),
|
||||
lang("cs", "Czech"),
|
||||
lang("nl", "Dutch"),
|
||||
lang("km", "Khmer", dense: true),
|
||||
lang("my", "Burmese", dense: true),
|
||||
lang("fa", "Persian", rtl: true, dense: true),
|
||||
lang("gu", "Gujarati", dense: true),
|
||||
lang("ur", "Urdu", rtl: true, dense: true),
|
||||
lang("te", "Telugu", dense: true),
|
||||
lang("mr", "Marathi", dense: true),
|
||||
lang("he", "Hebrew", rtl: true, dense: true),
|
||||
lang("bn", "Bengali", dense: true),
|
||||
lang("ta", "Tamil", dense: true),
|
||||
lang("uk", "Ukrainian"),
|
||||
|
||||
// Chinese minority languages and dialects (5)
|
||||
lang("bo", "Tibetan", dense: true),
|
||||
lang("mn", "Traditional Mongolian", dense: true),
|
||||
lang("yue", "Cantonese", dense: true),
|
||||
lang("kk", "Arabic Kazakh", rtl: true, dense: true),
|
||||
lang("ug", "Uyghur", rtl: true, dense: true),
|
||||
|
||||
// Newly supported in Hy-MT3 (64)
|
||||
lang("el", "Greek"),
|
||||
lang("cy", "Welsh"),
|
||||
lang("si", "Sinhala", dense: true),
|
||||
lang("ro", "Romanian"),
|
||||
lang("ca", "Catalan"),
|
||||
lang("pa", "Punjabi", dense: true),
|
||||
lang("hu", "Hungarian"),
|
||||
lang("gl", "Galician"),
|
||||
lang("sd", "Sindhi", rtl: true, dense: true),
|
||||
lang("bg", "Bulgarian"),
|
||||
lang("eu", "Basque"),
|
||||
lang("as", "Assamese", dense: true),
|
||||
lang("sr", "Serbian"),
|
||||
lang("af", "Afrikaans"),
|
||||
lang("or", "Odia", dense: true),
|
||||
lang("hr", "Croatian"),
|
||||
lang("lb", "Luxembourgish"),
|
||||
lang("kn", "Kannada", dense: true),
|
||||
lang("sk", "Slovak"),
|
||||
lang("mt", "Maltese"),
|
||||
lang("ml", "Malayalam", dense: true),
|
||||
lang("sl", "Slovenian"),
|
||||
lang("eo", "Esperanto"),
|
||||
lang("sa", "Sanskrit", dense: true),
|
||||
lang("sq", "Albanian"),
|
||||
lang("yi", "Yiddish", rtl: true, dense: true),
|
||||
lang("lo", "Lao", dense: true),
|
||||
lang("mk", "Macedonian"),
|
||||
lang("hy", "Armenian"),
|
||||
lang("jv", "Javanese"),
|
||||
lang("be", "Belarusian"),
|
||||
lang("ka", "Georgian"),
|
||||
lang("su", "Sundanese"),
|
||||
lang("lt", "Lithuanian"),
|
||||
lang("az", "Azerbaijani"),
|
||||
lang("ceb", "Cebuano"),
|
||||
lang("lv", "Latvian"),
|
||||
lang("uz", "Uzbek"),
|
||||
lang("war", "Waray"),
|
||||
lang("et", "Estonian"),
|
||||
lang("ky", "Kyrgyz"),
|
||||
lang("sw", "Swahili"),
|
||||
lang("fi", "Finnish"),
|
||||
lang("tk", "Turkmen"),
|
||||
lang("am", "Amharic", dense: true),
|
||||
lang("sv", "Swedish"),
|
||||
lang("tg", "Tajik"),
|
||||
lang("so", "Somali"),
|
||||
lang("da", "Danish"),
|
||||
lang("tt", "Tatar"),
|
||||
lang("mg", "Malagasy"),
|
||||
lang("nb", "Norwegian"),
|
||||
lang("ba", "Bashkir"),
|
||||
lang("ht", "Haitian Creole"),
|
||||
lang("nn", "Norwegian Nynorsk"),
|
||||
lang("ku", "Kurdish"),
|
||||
lang("kk-Cyrl", "Cyrillic Kazakh"),
|
||||
lang("is", "Icelandic"),
|
||||
lang("ckb", "Central Kurdish", rtl: true, dense: true),
|
||||
lang("mn-Cyrl", "Cyrillic Mongolian"),
|
||||
lang("ga", "Irish"),
|
||||
lang("ps", "Pashto", rtl: true, dense: true),
|
||||
lang("gd", "Scottish Gaelic"),
|
||||
lang("ne", "Nepali", dense: true),
|
||||
]
|
||||
|
||||
/// Resolves a BCP-47 code case-insensitively; unknown codes return nil (never a guess).
|
||||
/// The 15 common targets from `docs/LANGUAGES.md` §5, in display order.
|
||||
public static let common: [ModelLanguage] = [
|
||||
"en", "de", "fr", "es", "it", "pt", "nl", "pl", "zh", "ja", "ko", "ar", "tr", "ru", "uk",
|
||||
].compactMap { byCode[$0] }
|
||||
|
||||
/// The number of catalogue entries; the model card documents 102.
|
||||
public static var count: Int {
|
||||
all.count
|
||||
}
|
||||
|
||||
private static let byCode: [String: ModelLanguage] = Dictionary(
|
||||
all.map { ($0.code.lowercased(), $0) },
|
||||
uniquingKeysWith: { first, _ in first }
|
||||
)
|
||||
|
||||
private static let aliases: [String: String] = [
|
||||
"zh-hans": "zh", "zh-cn": "zh", "zh-sg": "zh",
|
||||
"zh-tw": "zh-Hant", "zh-hk": "zh-Hant", "zh-tr": "zh-Hant",
|
||||
"pt-br": "pt", "pt-pt": "pt",
|
||||
"no": "nb", "fil": "tl", "iw": "he", "in": "id",
|
||||
"kk-kz": "kk-Cyrl",
|
||||
]
|
||||
|
||||
/// Resolves a BCP-47 code case-insensitively. Variants collapse to the canonical entry;
|
||||
/// unknown codes return nil and are never guessed (`docs/LANGUAGES.md` §4).
|
||||
public static func resolve(_ code: String) -> ModelLanguage? {
|
||||
let normalized = code.lowercased()
|
||||
return all.first { $0.code.lowercased() == normalized }
|
||||
let normalized = code
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
.replacingOccurrences(of: "_", with: "-")
|
||||
.lowercased()
|
||||
guard !normalized.isEmpty else { return nil }
|
||||
|
||||
if let exact = byCode[normalized] {
|
||||
return exact
|
||||
}
|
||||
if let alias = aliases[normalized], let language = byCode[alias.lowercased()] {
|
||||
return language
|
||||
}
|
||||
if normalized.hasPrefix("zh-hant") {
|
||||
return byCode["zh-hant"]
|
||||
}
|
||||
if normalized.hasPrefix("zh") {
|
||||
return byCode["zh"]
|
||||
}
|
||||
if normalized.hasPrefix("kk-cyrl") {
|
||||
return byCode["kk-cyrl"]
|
||||
}
|
||||
if normalized.hasPrefix("mn-cyrl") {
|
||||
return byCode["mn-cyrl"]
|
||||
}
|
||||
|
||||
if let separator = normalized.firstIndex(of: "-") {
|
||||
let base = String(normalized[..<separator])
|
||||
return byCode[base]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// All right-to-left languages.
|
||||
public static var rightToLeft: [ModelLanguage] {
|
||||
all.filter(\.isRTL)
|
||||
}
|
||||
|
||||
private static func lang(
|
||||
_ code: String,
|
||||
_ modelName: String,
|
||||
display: String? = nil,
|
||||
rtl: Bool = false,
|
||||
dense: Bool = false
|
||||
) -> ModelLanguage {
|
||||
ModelLanguage(
|
||||
code: code,
|
||||
modelName: modelName,
|
||||
displayName: display,
|
||||
isRTL: rtl,
|
||||
usesDenseScript: dense
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -9,4 +9,9 @@ public enum HyMT3ModelPreset {
|
||||
public static let defaultKeepAlive = "30m"
|
||||
/// The only text used for warm-up. Never user text.
|
||||
public static let warmUpText = "Hello."
|
||||
|
||||
/// True for any Hy-MT3 conversion tag. The registry uses this through `HyMT3Adapter`.
|
||||
public static func isHyMT3(_ model: String) -> Bool {
|
||||
model.lowercased().contains("hy-mt3")
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,10 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// The documented Hy-MT3 sampling values from docs/HYMT3_MODEL.md §2.
|
||||
/// Documented Hy-MT3 option sets (`docs/HYMT3_MODEL.md` §2).
|
||||
public enum HyMT3Options {
|
||||
/// Translation defaults: temperature 0.7, top_p 0.6, top_k 20, repeat_penalty 1.05,
|
||||
/// num_predict 4096, num_ctx 8192.
|
||||
public static let translation = ChatOptions(
|
||||
temperature: 0.7,
|
||||
topP: 0.6,
|
||||
topK: 20,
|
||||
repeatPenalty: 1.05,
|
||||
numPredict: 4096,
|
||||
numCtx: 8192
|
||||
)
|
||||
|
||||
/// Warm-up uses the same model settings but only 8 output tokens.
|
||||
public static let warmUp = ChatOptions(
|
||||
temperature: 0.7,
|
||||
topP: 0.6,
|
||||
topK: 20,
|
||||
repeatPenalty: 1.05,
|
||||
numPredict: 8,
|
||||
numCtx: 8192
|
||||
)
|
||||
/// Warm-up uses the publisher sampling but only 8 output tokens. The publisher values come
|
||||
/// from `SamplingOptions`, so there is one source of truth.
|
||||
public static let warmUp = SamplingOptions.publisherDefault
|
||||
.merging(SamplingOverrides(numPredict: 8))
|
||||
.chatOptions()
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
/// The documented Hy-MT3 prompt templates. v1 uses the Default Translation template.
|
||||
/// The documented Hy-MT3 prompt templates (`docs/HYMT3_MODEL.md` §3–§4).
|
||||
///
|
||||
/// These are the only prompt strings in the app. The Default template is canonical for v1; the
|
||||
/// Delimiters and Structured Data 1 templates are the only documented fallbacks (ADR-012).
|
||||
public enum HyMT3Prompt {
|
||||
/// The byte-exact Default Translation prompt from docs/HYMT3_MODEL.md §3.
|
||||
/// The byte-exact Default Translation prompt from `docs/HYMT3_MODEL.md` §3.
|
||||
///
|
||||
/// The prefix depends only on the target language; the source text is appended last so the
|
||||
/// Ollama prompt cache stays valid.
|
||||
@@ -9,4 +12,50 @@ public enum HyMT3Prompt {
|
||||
+ "Note that you should **only output the translated result without any additional explanation**:"
|
||||
return prefix + "\n\n" + source
|
||||
}
|
||||
|
||||
/// The byte-exact Delimiters prompt, the single documented fallback for a lost token.
|
||||
public static func delimiters(target: ModelLanguage, source: String) -> String {
|
||||
let instruction = "Please accurately translate the following text into \(target.modelName). "
|
||||
+ "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**."
|
||||
return instruction + "\n\n" + source
|
||||
}
|
||||
|
||||
/// The byte-exact Structured Data 1 prompt for JSON, HTML or Markdown.
|
||||
public static func structuredData1(
|
||||
format: StructuredFormat,
|
||||
target: ModelLanguage,
|
||||
source: String
|
||||
) -> String {
|
||||
let type = format.rawValue
|
||||
let preservation = "1. **Structure Preservation:** You MUST preserve the original \(type) data "
|
||||
+ "structure, nesting, hierarchy, and indentation exactly as they are."
|
||||
let nonTranslation = "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."
|
||||
return [
|
||||
"### Task",
|
||||
"Translate the user-facing text within the following \(type) data into \(target.modelName).",
|
||||
"",
|
||||
"### Strict Rules",
|
||||
preservation,
|
||||
"2. **Selective Translation:** Translate ONLY the visible, user-facing text content/values.",
|
||||
nonTranslation,
|
||||
"",
|
||||
"### Source Data",
|
||||
source,
|
||||
].joined(separator: "\n")
|
||||
}
|
||||
|
||||
/// Builds the prompt for a variant.
|
||||
public static func text(for variant: PromptVariant, target: ModelLanguage, source: String) -> String {
|
||||
switch variant {
|
||||
case .defaultTranslation:
|
||||
defaultTranslation(target: target, source: source)
|
||||
case .delimiters:
|
||||
delimiters(target: target, source: source)
|
||||
case let .structuredData1(format):
|
||||
structuredData1(format: format, target: target, source: source)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// Builds the documented Hy-MT3 requests. T2.1/T2.2 replace this with the adapter protocol;
|
||||
/// until then this is the only place the translation request shape is assembled.
|
||||
public struct HyMT3RequestFactory: Sendable {
|
||||
/// The model tag.
|
||||
public let model: String
|
||||
/// The Ollama `keep_alive` value.
|
||||
public let keepAlive: String
|
||||
|
||||
/// Creates a factory.
|
||||
public init(
|
||||
model: String = HyMT3ModelPreset.defaultModel,
|
||||
keepAlive: String = HyMT3ModelPreset.defaultKeepAlive
|
||||
) {
|
||||
self.model = model
|
||||
self.keepAlive = keepAlive
|
||||
}
|
||||
|
||||
/// A translation request with the documented prompt and sampling.
|
||||
public func translationRequest(text: String, target: ModelLanguage) -> ChatRequest {
|
||||
ChatRequest(
|
||||
model: model,
|
||||
messages: [ChatMessage(content: HyMT3Prompt.defaultTranslation(target: target, source: text))],
|
||||
stream: true,
|
||||
keepAlive: keepAlive,
|
||||
options: HyMT3Options.translation
|
||||
)
|
||||
}
|
||||
|
||||
/// A warm-up request with fixed synthetic text and `num_predict: 8`.
|
||||
public func warmUpRequest() -> ChatRequest {
|
||||
ChatRequest(
|
||||
model: model,
|
||||
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
|
||||
stream: true,
|
||||
keepAlive: keepAlive,
|
||||
options: HyMT3Options.warmUp
|
||||
)
|
||||
}
|
||||
|
||||
/// A request that unloads the model after it completes.
|
||||
public func unloadRequest() -> ChatRequest {
|
||||
ChatRequest(
|
||||
model: model,
|
||||
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
|
||||
stream: true,
|
||||
keepAlive: "0",
|
||||
options: HyMT3Options.warmUp
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import SprachmittlerText
|
||||
|
||||
/// Family-neutral same-language check used by the pipeline. The canonical-code mapping stays in
|
||||
/// Engines, next to the catalogue that defines it.
|
||||
public enum LanguageMatching {
|
||||
/// True when detection is confident and every alternative resolves to the target language.
|
||||
public static func isSameLanguage(_ detection: LanguageDetection, target: ModelLanguage) -> Bool {
|
||||
guard detection.confidence >= 0.5, !detection.alternatives.isEmpty else { return false }
|
||||
let targetCode = HyMT3Languages.resolve(target.code)?.code ?? target.code
|
||||
var agreed = false
|
||||
for code in detection.alternatives {
|
||||
guard let language = HyMT3Languages.resolve(code),
|
||||
language.code.caseInsensitiveCompare(targetCode) == .orderedSame
|
||||
else {
|
||||
return false
|
||||
}
|
||||
agreed = true
|
||||
}
|
||||
return agreed
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,48 @@
|
||||
import Foundation
|
||||
|
||||
/// A BCP-47 code paired with the exact English model-card name used in the prompt.
|
||||
public struct ModelLanguage: Sendable, Hashable, Codable {
|
||||
/// The BCP-47 code, e.g. `de` or `zh-Hant`.
|
||||
///
|
||||
/// `modelName` is never localised: it is inserted into the prompt byte for byte
|
||||
/// (`docs/LANGUAGES.md` §4). Use `localizedDisplayName` for UI labels.
|
||||
public struct ModelLanguage: Sendable, Hashable, Codable, Identifiable {
|
||||
/// The canonical BCP-47 code, e.g. `de`, `zh-Hant` or `kk-Cyrl`.
|
||||
public let code: String
|
||||
/// The exact model-card name, e.g. `German` or `Traditional Chinese`.
|
||||
public let modelName: String
|
||||
/// The English display name, used as a fallback when `Locale` has no localised name.
|
||||
public let displayName: String
|
||||
/// True for right-to-left scripts.
|
||||
public let isRTL: Bool
|
||||
/// True for scripts that use the smaller chunk limit.
|
||||
public let usesDenseScript: Bool
|
||||
|
||||
/// Creates a language pair.
|
||||
public init(code: String, modelName: String) {
|
||||
/// `Identifiable` conformance for UI lists.
|
||||
public var id: String {
|
||||
code
|
||||
}
|
||||
|
||||
/// The display name in the current UI locale, never used in a prompt. When the locale only
|
||||
/// has a generic name (for example “Chinese”), the catalogue's more specific name wins.
|
||||
public var localizedDisplayName: String {
|
||||
let localized = Locale.current.localizedString(forLanguageCode: code)
|
||||
if let localized, localized.caseInsensitiveCompare(modelName) != .orderedSame {
|
||||
return localized
|
||||
}
|
||||
return displayName
|
||||
}
|
||||
|
||||
/// Creates a language entry.
|
||||
public init(
|
||||
code: String,
|
||||
modelName: String,
|
||||
displayName: String? = nil,
|
||||
isRTL: Bool = false,
|
||||
usesDenseScript: Bool = false
|
||||
) {
|
||||
self.code = code
|
||||
self.modelName = modelName
|
||||
self.displayName = displayName ?? modelName
|
||||
self.isRTL = isRTL
|
||||
self.usesDenseScript = usesDenseScript
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import Foundation
|
||||
|
||||
/// Normalises numeric tokens for the semantic check in `docs/TRANSLATION_OUTPUT.md` §9.
|
||||
///
|
||||
/// Locale separators legitimately change during translation, so `1.5`, `1,5` and `1 5` may all
|
||||
/// represent the same value. Thousands separators are removed and the decimal separator becomes
|
||||
/// `.`. This never edits the translation; it only decides whether a warning is shown.
|
||||
public enum NumericTokenNormalizer {
|
||||
private static let regex = try? NSRegularExpression(pattern: "\\d+(?:[.,\\s]\\d+)*")
|
||||
|
||||
/// The normalised numeric values in `text`, in source order.
|
||||
public static func numbers(in text: String) -> [String] {
|
||||
guard let regex else { return [] }
|
||||
let nsText = text as NSString
|
||||
let matches = regex.matches(in: text, range: NSRange(location: 0, length: nsText.length))
|
||||
return matches.map { normalize(nsText.substring(with: $0.range)) }
|
||||
}
|
||||
|
||||
/// Normalises one numeric token.
|
||||
public static func normalize(_ raw: String) -> String {
|
||||
var value = raw.filter { !$0.isWhitespace }
|
||||
guard !value.isEmpty else { return value }
|
||||
|
||||
let hasComma = value.contains(",")
|
||||
let hasDot = value.contains(".")
|
||||
if hasComma, hasDot, let comma = value.lastIndex(of: ","), let dot = value.lastIndex(of: ".") {
|
||||
let decimal = comma > dot ? comma : dot
|
||||
let integer = value[..<decimal].filter { $0 != "," && $0 != "." }
|
||||
let fraction = value[value.index(after: decimal)...].filter { $0 != "," && $0 != "." }
|
||||
value = String(integer) + "." + String(fraction)
|
||||
} else if hasComma || hasDot {
|
||||
let separator: Character = hasComma ? "," : "."
|
||||
let parts = value.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
|
||||
if parts.count == 2, parts[1].count == 3, parts[0] != "0", !parts[0].isEmpty {
|
||||
value = parts[0] + parts[1]
|
||||
} else if separator == "," {
|
||||
value = parts.joined(separator: ".")
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import SprachmittlerText
|
||||
|
||||
/// The completed validation of one translation.
|
||||
public struct OutputValidation: Sendable, Equatable {
|
||||
/// Every warning found, in a stable order.
|
||||
public let warnings: [TranslationWarning]
|
||||
|
||||
/// True when at least one warning should disable Replace by default.
|
||||
public var blocksReplacement: Bool {
|
||||
warnings.contains(where: \.blocksReplacement)
|
||||
}
|
||||
|
||||
/// Creates a validation result.
|
||||
public init(warnings: [TranslationWarning]) {
|
||||
self.warnings = warnings
|
||||
}
|
||||
|
||||
/// A clean result.
|
||||
public static let clean = OutputValidation(warnings: [])
|
||||
}
|
||||
|
||||
/// Validation from `docs/TRANSLATION_OUTPUT.md` §4–§7. It never edits the output.
|
||||
public struct OutputValidator: Sendable {
|
||||
private let preambleDetector: PreambleDetector
|
||||
|
||||
/// Creates a validator.
|
||||
public init(preambleDetector: PreambleDetector = PreambleDetector()) {
|
||||
self.preambleDetector = preambleDetector
|
||||
}
|
||||
|
||||
/// Validates a T1-normalised translation.
|
||||
public func validate(
|
||||
source: String,
|
||||
translation: String,
|
||||
doneReason: String?,
|
||||
tokens: [ProtectedToken],
|
||||
includeRepetition: Bool = true
|
||||
) -> OutputValidation {
|
||||
if translation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
|
||||
return OutputValidation(warnings: [.emptyOutput])
|
||||
}
|
||||
|
||||
var warnings: [TranslationWarning] = []
|
||||
if doneReason == "length" {
|
||||
warnings.append(.truncated)
|
||||
}
|
||||
if includeRepetition, RepetitionDetector.detectsLoop(in: translation) {
|
||||
warnings.append(.repetitionLoop)
|
||||
}
|
||||
if let line = preambleDetector.firstLine(in: translation) {
|
||||
warnings.append(.preambleDetected(firstLine: line))
|
||||
}
|
||||
|
||||
for token in uniqueTokens(tokens) where count(of: token.value, in: source) != count(
|
||||
of: token.value,
|
||||
in: translation
|
||||
) {
|
||||
warnings.append(.missingProtectedToken(token.value))
|
||||
}
|
||||
|
||||
let sourceNumbers = Set(NumericTokenNormalizer.numbers(in: source))
|
||||
let translatedNumbers = Set(NumericTokenNormalizer.numbers(in: translation))
|
||||
if !sourceNumbers.isSubset(of: translatedNumbers) {
|
||||
warnings.append(.numericMismatch)
|
||||
}
|
||||
|
||||
return OutputValidation(warnings: deduplicated(warnings))
|
||||
}
|
||||
|
||||
/// The protected tokens whose occurrence count differs between source and translation.
|
||||
public func missingTokens(
|
||||
source: String,
|
||||
translation: String,
|
||||
tokens: [ProtectedToken]
|
||||
) -> [ProtectedToken] {
|
||||
uniqueTokens(tokens).filter {
|
||||
count(of: $0.value, in: source) != count(of: $0.value, in: translation)
|
||||
}
|
||||
}
|
||||
|
||||
private func uniqueTokens(_ tokens: [ProtectedToken]) -> [ProtectedToken] {
|
||||
var seen = Set<ProtectedToken>()
|
||||
return tokens.filter { seen.insert($0).inserted }
|
||||
}
|
||||
|
||||
private func deduplicated(_ warnings: [TranslationWarning]) -> [TranslationWarning] {
|
||||
var seen = Set<TranslationWarning>()
|
||||
return warnings.filter { seen.insert($0).inserted }
|
||||
}
|
||||
|
||||
private func count(of needle: String, in haystack: String) -> Int {
|
||||
guard !needle.isEmpty else { return 0 }
|
||||
var count = 0
|
||||
var searchRange = haystack.startIndex ..< haystack.endIndex
|
||||
while let range = haystack.range(of: needle, range: searchRange) {
|
||||
count += 1
|
||||
searchRange = range.upperBound ..< haystack.endIndex
|
||||
}
|
||||
return count
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/// Detects a likely model preamble without rewriting it (`docs/TRANSLATION_OUTPUT.md` §6).
|
||||
public struct PreambleDetector: Sendable {
|
||||
/// The maximum first-line length for a preamble.
|
||||
public static let maximumFirstLineLength = 80
|
||||
|
||||
/// Creates a detector.
|
||||
public init() {}
|
||||
|
||||
/// Returns the suspicious first line, or nil.
|
||||
///
|
||||
/// The heuristic is deliberately simple: a first non-empty line of at most 80 characters
|
||||
/// ending in `:` or `:`, followed by a blank line and at least one more non-empty line.
|
||||
public func firstLine(in text: String) -> String? {
|
||||
let lines = text.components(separatedBy: "\n")
|
||||
guard let firstIndex = lines.firstIndex(where: { !$0.trimmingCharacters(in: .whitespaces).isEmpty })
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
let line = lines[firstIndex].trimmingCharacters(in: .whitespaces)
|
||||
guard line.count <= Self.maximumFirstLineLength, line.hasSuffix(":") || line.hasSuffix(":"),
|
||||
firstIndex + 1 < lines.count,
|
||||
lines[firstIndex + 1].trimmingCharacters(in: .whitespaces).isEmpty else { return nil }
|
||||
let hasMoreText = lines[(firstIndex + 2)...].contains {
|
||||
!$0.trimmingCharacters(in: .whitespaces).isEmpty
|
||||
}
|
||||
return hasMoreText ? line : nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import SprachmittlerText
|
||||
|
||||
/// Chooses the documented prompt template (`docs/TRANSLATION_OUTPUT.md` §1, ADR-012).
|
||||
///
|
||||
/// v1 starts with Default Translation for everything. Structured Data 1 and Delimiters are used
|
||||
/// only as the single fallback after a protected token was lost.
|
||||
public struct PromptPolicy: Sendable {
|
||||
/// Creates a policy.
|
||||
public init() {}
|
||||
|
||||
/// The initial prompt for a content class. v1 always returns Default Translation.
|
||||
public func initialPrompt(for content: ContentClass) -> PromptVariant {
|
||||
_ = content
|
||||
return .defaultTranslation
|
||||
}
|
||||
|
||||
/// The one fallback prompt for a lost protected token, or nil when no documented fallback
|
||||
/// applies. The caller enforces the one-retry limit.
|
||||
public func retryPrompt(for content: ContentClass, lostToken: ProtectedToken) -> PromptVariant? {
|
||||
switch content {
|
||||
case .json:
|
||||
return .structuredData1(format: .json)
|
||||
case .html:
|
||||
return .structuredData1(format: .html)
|
||||
case .markdown:
|
||||
return .structuredData1(format: .markdown)
|
||||
case .code, .delimited, .plain:
|
||||
_ = lostToken
|
||||
return .delimiters
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/// The documented formats for Structured Data 1.
|
||||
public enum StructuredFormat: String, Sendable, Equatable, CaseIterable {
|
||||
/// JSON data.
|
||||
case json = "JSON"
|
||||
/// HTML markup.
|
||||
case html = "HTML"
|
||||
/// Markdown text.
|
||||
case markdown = "Markdown"
|
||||
}
|
||||
|
||||
/// One of the documented prompt templates (`docs/HYMT3_MODEL.md` §4).
|
||||
public enum PromptVariant: Sendable, Equatable {
|
||||
/// The canonical Default Translation template.
|
||||
case defaultTranslation
|
||||
/// The Delimiters template; used once when a protected token is lost in plain text.
|
||||
case delimiters
|
||||
/// Structured Data 1 with the matching format; used once for structured text.
|
||||
case structuredData1(format: StructuredFormat)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/// Detects repetition loops in a streaming translation (`docs/TRANSLATION_OUTPUT.md` §7).
|
||||
public struct RepetitionDetector: Sendable {
|
||||
/// The repeated-line threshold.
|
||||
public static let minimumLineLength = 8
|
||||
/// How many identical consecutive lines count as a loop.
|
||||
public static let lineRepeatThreshold = 6
|
||||
/// The repeated-window length.
|
||||
public static let windowLength = 64
|
||||
/// How many identical windows count as a loop.
|
||||
public static let windowRepeatThreshold = 8
|
||||
/// How much trailing text is inspected for window loops.
|
||||
public static let windowSearchLength = 2048
|
||||
|
||||
private var buffer = ""
|
||||
|
||||
/// Creates a detector.
|
||||
public init() {}
|
||||
|
||||
/// Appends a delta and returns true when a loop is detected.
|
||||
public mutating func append(_ delta: String) -> Bool {
|
||||
buffer += delta
|
||||
if buffer.count > Self.windowSearchLength * 2 {
|
||||
buffer = String(buffer.suffix(Self.windowSearchLength))
|
||||
}
|
||||
return Self.detectsLoop(in: buffer)
|
||||
}
|
||||
|
||||
/// Checks a complete or partial output for a loop.
|
||||
public static func detectsLoop(in text: String) -> Bool {
|
||||
hasRepeatedLine(in: text) || hasRepeatedWindow(in: text)
|
||||
}
|
||||
|
||||
private static func hasRepeatedLine(in text: String) -> Bool {
|
||||
let lines = text
|
||||
.components(separatedBy: "\n")
|
||||
.suffix(12)
|
||||
.map { $0.trimmingCharacters(in: .whitespaces) }
|
||||
guard !lines.isEmpty else { return false }
|
||||
|
||||
var run = 1
|
||||
for index in 1 ..< lines.count {
|
||||
if !lines[index].isEmpty, lines[index].count >= minimumLineLength, lines[index] == lines[index - 1] {
|
||||
run += 1
|
||||
if run >= lineRepeatThreshold {
|
||||
return true
|
||||
}
|
||||
} else {
|
||||
run = 1
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private static func hasRepeatedWindow(in text: String) -> Bool {
|
||||
guard text.count >= windowLength else { return false }
|
||||
let search = String(text.suffix(windowSearchLength))
|
||||
let window = String(text.suffix(windowLength))
|
||||
guard search.count >= windowLength * windowRepeatThreshold else { return false }
|
||||
|
||||
var count = 0
|
||||
var range = search.startIndex ..< search.endIndex
|
||||
while let found = search.range(of: window, range: range) {
|
||||
count += 1
|
||||
if count >= windowRepeatThreshold {
|
||||
return true
|
||||
}
|
||||
range = found.upperBound ..< search.endIndex
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// The documented Hy-MT3 sampling values (`docs/HYMT3_MODEL.md` §2).
|
||||
public struct SamplingOptions: Sendable, Equatable {
|
||||
/// `temperature`.
|
||||
public var temperature: Double
|
||||
/// `top_p`.
|
||||
public var topP: Double
|
||||
/// `top_k`.
|
||||
public var topK: Int
|
||||
/// `repeat_penalty`.
|
||||
public var repeatPenalty: Double
|
||||
/// `num_predict`.
|
||||
public var numPredict: Int
|
||||
/// `num_ctx`.
|
||||
public var numCtx: Int
|
||||
|
||||
/// Creates sampling values.
|
||||
public init(
|
||||
temperature: Double = 0.7,
|
||||
topP: Double = 0.6,
|
||||
topK: Int = 20,
|
||||
repeatPenalty: Double = 1.05,
|
||||
numPredict: Int = 4096,
|
||||
numCtx: Int = 8192
|
||||
) {
|
||||
self.temperature = temperature
|
||||
self.topP = topP
|
||||
self.topK = topK
|
||||
self.repeatPenalty = repeatPenalty
|
||||
self.numPredict = numPredict
|
||||
self.numCtx = numCtx
|
||||
}
|
||||
|
||||
/// The publisher's recommendation for 1.8B and 7B.
|
||||
public static let publisherDefault = SamplingOptions()
|
||||
|
||||
/// Applies explicit overrides on top of these values. Publisher values are always sent; a
|
||||
/// model default is never relied on, because `/api/show` exposes no sampling defaults.
|
||||
public func merging(_ overrides: SamplingOverrides) -> SamplingOptions {
|
||||
var merged = self
|
||||
if let value = overrides.temperature {
|
||||
merged.temperature = value
|
||||
}
|
||||
if let value = overrides.topP {
|
||||
merged.topP = value
|
||||
}
|
||||
if let value = overrides.topK {
|
||||
merged.topK = value
|
||||
}
|
||||
if let value = overrides.repeatPenalty {
|
||||
merged.repeatPenalty = value
|
||||
}
|
||||
if let value = overrides.numPredict {
|
||||
merged.numPredict = value
|
||||
}
|
||||
if let value = overrides.numCtx {
|
||||
merged.numCtx = value
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
/// The exact Ollama option names sent on the wire.
|
||||
public func chatOptions() -> ChatOptions {
|
||||
ChatOptions(
|
||||
temperature: temperature,
|
||||
topP: topP,
|
||||
topK: topK,
|
||||
repeatPenalty: repeatPenalty,
|
||||
numPredict: numPredict,
|
||||
numCtx: numCtx
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Optional per-setting overrides. Only the documented six sampling keys exist.
|
||||
public struct SamplingOverrides: Sendable, Equatable {
|
||||
/// `temperature` override.
|
||||
public var temperature: Double?
|
||||
/// `top_p` override.
|
||||
public var topP: Double?
|
||||
/// `top_k` override.
|
||||
public var topK: Int?
|
||||
/// `repeat_penalty` override.
|
||||
public var repeatPenalty: Double?
|
||||
/// `num_predict` override.
|
||||
public var numPredict: Int?
|
||||
/// `num_ctx` override.
|
||||
public var numCtx: Int?
|
||||
|
||||
/// Creates overrides.
|
||||
public init(
|
||||
temperature: Double? = nil,
|
||||
topP: Double? = nil,
|
||||
topK: Int? = nil,
|
||||
repeatPenalty: Double? = nil,
|
||||
numPredict: Int? = nil,
|
||||
numCtx: Int? = nil
|
||||
) {
|
||||
self.temperature = temperature
|
||||
self.topP = topP
|
||||
self.topK = topK
|
||||
self.repeatPenalty = repeatPenalty
|
||||
self.numPredict = numPredict
|
||||
self.numCtx = numCtx
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import SprachmittlerOllama
|
||||
import SprachmittlerText
|
||||
|
||||
/// One translation request before a model family adapter shapes it.
|
||||
public struct AdapterRequest: Sendable, Equatable {
|
||||
/// The chunk text.
|
||||
public let text: String
|
||||
/// The target language.
|
||||
public let target: ModelLanguage
|
||||
/// The installed model tag.
|
||||
public let model: String
|
||||
/// The Ollama `keep_alive` value.
|
||||
public let keepAlive: String
|
||||
/// The documented prompt template.
|
||||
public let prompt: PromptVariant
|
||||
/// The sampling values.
|
||||
public let sampling: SamplingOptions
|
||||
|
||||
/// Creates a request.
|
||||
public init(
|
||||
text: String,
|
||||
target: ModelLanguage,
|
||||
model: String,
|
||||
keepAlive: String,
|
||||
prompt: PromptVariant = .defaultTranslation,
|
||||
sampling: SamplingOptions = .publisherDefault
|
||||
) {
|
||||
self.text = text
|
||||
self.target = target
|
||||
self.model = model
|
||||
self.keepAlive = keepAlive
|
||||
self.prompt = prompt
|
||||
self.sampling = sampling
|
||||
}
|
||||
}
|
||||
|
||||
/// A model family adapter: the only type that knows how to turn a translation into a request.
|
||||
public protocol TranslationAdapter: Sendable {
|
||||
/// A stable identifier, e.g. `hy-mt3`.
|
||||
var identifier: String { get }
|
||||
/// The adapter version; bump when the request shape changes.
|
||||
var version: Int { get }
|
||||
|
||||
/// True when this adapter handles `model`.
|
||||
func supports(model: String) -> Bool
|
||||
|
||||
/// Builds the documented request for one chunk.
|
||||
func makeRequest(_ request: AdapterRequest) -> ChatRequest
|
||||
}
|
||||
|
||||
/// The adapters available in the app, in priority order.
|
||||
public struct AdapterRegistry: Sendable {
|
||||
private let adapters: [any TranslationAdapter]
|
||||
|
||||
/// Creates a registry. The production root passes `[HyMT3Adapter()]`.
|
||||
public init(adapters: [any TranslationAdapter]) {
|
||||
self.adapters = adapters
|
||||
}
|
||||
|
||||
/// The first adapter that supports `model`, or nil.
|
||||
public func adapter(for model: String) -> (any TranslationAdapter)? {
|
||||
adapters.first { $0.supports(model: model) }
|
||||
}
|
||||
|
||||
/// Builds a request or throws `AdapterError.noAdapter` for an unknown family. Never guesses.
|
||||
public func makeRequest(_ request: AdapterRequest) throws -> ChatRequest {
|
||||
guard let adapter = adapter(for: request.model) else {
|
||||
throw AdapterError.noAdapter(model: request.model)
|
||||
}
|
||||
return adapter.makeRequest(request)
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors raised while choosing an adapter.
|
||||
public enum AdapterError: Error, Sendable, Equatable {
|
||||
/// No adapter handles this model family.
|
||||
case noAdapter(model: String)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/// A non-fatal validation finding shown in the panel and the CLI JSON output.
|
||||
public enum TranslationWarning: Sendable, Equatable, Hashable {
|
||||
/// A short first line ending in a colon was followed by a blank line and more text.
|
||||
case preambleDetected(firstLine: String)
|
||||
/// `done_reason` was `length`.
|
||||
case truncated
|
||||
/// The output repeated a line or window too many times.
|
||||
case repetitionLoop
|
||||
/// A protected token from the source is missing or changed in the translation.
|
||||
case missingProtectedToken(String)
|
||||
/// The translation was empty after T1.
|
||||
case emptyOutput
|
||||
/// The detected source language is the target language.
|
||||
case sameLanguage(source: String, target: String)
|
||||
/// A source number is absent from the translation.
|
||||
case numericMismatch
|
||||
/// One chunk failed; the panel keeps the partial translation.
|
||||
case chunkFailed(index: Int)
|
||||
}
|
||||
|
||||
public extension TranslationWarning {
|
||||
/// A stable code for JSON output and diagnostics.
|
||||
var code: String {
|
||||
switch self {
|
||||
case .preambleDetected: "preambleDetected"
|
||||
case .truncated: "truncated"
|
||||
case .repetitionLoop: "repetitionLoop"
|
||||
case .missingProtectedToken: "missingProtectedToken"
|
||||
case .emptyOutput: "emptyOutput"
|
||||
case .sameLanguage: "sameLanguage"
|
||||
case .numericMismatch: "numericMismatch"
|
||||
case .chunkFailed: "chunkFailed"
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocking warnings disable Replace by default (`docs/TRANSLATION_OUTPUT.md` §4–§7).
|
||||
var blocksReplacement: Bool {
|
||||
switch self {
|
||||
case .preambleDetected, .truncated, .repetitionLoop, .missingProtectedToken, .emptyOutput, .chunkFailed:
|
||||
true
|
||||
case .sameLanguage, .numericMismatch:
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import Foundation
|
||||
import SprachmittlerCapture
|
||||
|
||||
/// A main-actor pasteboard fake for watcher and snapshot tests.
|
||||
@MainActor
|
||||
public final class FakePasteboard: PasteboardAccessing {
|
||||
public private(set) var changeCount: Int
|
||||
public private(set) var text: String?
|
||||
public private(set) var items: [ClipboardItemData]
|
||||
public private(set) var hasOwnWriteMarkers: Bool
|
||||
public private(set) var stringReadCount = 0
|
||||
public private(set) var snapshotCount = 0
|
||||
public private(set) var writtenTexts: [String] = []
|
||||
public var restoreSucceeds = true
|
||||
public var snapshotSucceeds = true
|
||||
|
||||
public init(
|
||||
changeCount: Int = 0,
|
||||
text: String? = nil,
|
||||
items: [ClipboardItemData] = [],
|
||||
hasOwnWriteMarkers: Bool = false
|
||||
) {
|
||||
self.changeCount = changeCount
|
||||
self.text = text
|
||||
self.items = items
|
||||
self.hasOwnWriteMarkers = hasOwnWriteMarkers
|
||||
}
|
||||
|
||||
/// Simulates another app copying text.
|
||||
public func simulateCopy(_ text: String?) {
|
||||
self.text = text
|
||||
hasOwnWriteMarkers = false
|
||||
changeCount += 1
|
||||
}
|
||||
|
||||
/// Simulates a copy that carries a transient/own marker.
|
||||
public func simulateOwnMarkerCopy(_ text: String?) {
|
||||
self.text = text
|
||||
hasOwnWriteMarkers = true
|
||||
changeCount += 1
|
||||
}
|
||||
|
||||
public func string() -> String? {
|
||||
stringReadCount += 1
|
||||
return text
|
||||
}
|
||||
|
||||
public func containsOwnWriteMarkers() -> Bool {
|
||||
hasOwnWriteMarkers
|
||||
}
|
||||
|
||||
public func snapshot() -> ClipboardSnapshot? {
|
||||
guard snapshotSucceeds else { return nil }
|
||||
snapshotCount += 1
|
||||
return ClipboardSnapshot(items: items, changeCount: changeCount)
|
||||
}
|
||||
|
||||
public func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches expected: Int) -> Bool {
|
||||
guard restoreSucceeds, changeCount == expected else { return false }
|
||||
items = snapshot.items
|
||||
text = snapshot.items.first?.data["public.utf8-plain-text"]
|
||||
.flatMap { String(data: $0, encoding: .utf8) }
|
||||
hasOwnWriteMarkers = false
|
||||
changeCount += 1
|
||||
return true
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
public func write(_ text: String) -> Int {
|
||||
writtenTexts.append(text)
|
||||
self.text = text
|
||||
hasOwnWriteMarkers = true
|
||||
changeCount += 1
|
||||
return changeCount
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import Foundation
|
||||
import SprachmittlerCapture
|
||||
|
||||
/// A manual ticker for watcher tests. No real time passes.
|
||||
///
|
||||
/// `@unchecked Sendable` is safe: every mutable field is guarded by `lock`.
|
||||
public final class ManualPasteboardTicker: PasteboardTicking, @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var continuation: AsyncStream<Void>.Continuation?
|
||||
private var terminated = false
|
||||
private var started = false
|
||||
|
||||
/// Creates a manual ticker.
|
||||
public init() {}
|
||||
|
||||
public func ticks() -> AsyncStream<Void> {
|
||||
AsyncStream { continuation in
|
||||
lock.lock()
|
||||
self.continuation = continuation
|
||||
started = true
|
||||
lock.unlock()
|
||||
continuation.onTermination = { [weak self] _ in
|
||||
self?.markTerminated()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True once the watcher has subscribed.
|
||||
public var isStarted: Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return started
|
||||
}
|
||||
|
||||
/// Emits one tick.
|
||||
public func tick() {
|
||||
lock.lock()
|
||||
let continuation = continuation
|
||||
lock.unlock()
|
||||
continuation?.yield(())
|
||||
}
|
||||
|
||||
/// True once the stream has terminated.
|
||||
public var isTerminated: Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return terminated
|
||||
}
|
||||
|
||||
private func markTerminated() {
|
||||
lock.lock()
|
||||
terminated = true
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import Foundation
|
||||
|
||||
/// Splits text at paragraph, sentence, word and grapheme boundaries with script-aware limits.
|
||||
///
|
||||
/// Joining `chunks(for:)` with `reassemble(_:)` always returns the input exactly. The chunker does
|
||||
/// not trim, normalise or invent separators; call `TextNormalization.normalizeInput` first.
|
||||
public struct Chunker: Sendable {
|
||||
/// The limit for Latin, Cyrillic and Greek text.
|
||||
public let latinLimit: Int
|
||||
/// The limit for CJK, Arabic, Thai, Indic and other dense scripts.
|
||||
public let denseLimit: Int
|
||||
|
||||
/// Creates a chunker.
|
||||
public init(latinLimit: Int = 4000, denseLimit: Int = 2000) {
|
||||
self.latinLimit = latinLimit
|
||||
self.denseLimit = denseLimit
|
||||
}
|
||||
|
||||
/// The character limit that applies to `text`.
|
||||
public func limit(for text: String) -> Int {
|
||||
TextScript.isDense(text) ? denseLimit : latinLimit
|
||||
}
|
||||
|
||||
/// Splits `text` into chunks of at most the script-aware limit.
|
||||
public func chunks(for text: String) -> [TextChunk] {
|
||||
guard !text.isEmpty else { return [] }
|
||||
let limit = max(1, limit(for: text))
|
||||
var pieces: [(text: String, separator: String)] = []
|
||||
for unit in paragraphUnits(text) {
|
||||
split(unit.text, trailing: unit.separator, limit: limit, into: &pieces)
|
||||
}
|
||||
return pack(mergingLeadingEmpty(pieces), limit: limit)
|
||||
}
|
||||
|
||||
/// Reassembles chunks into the original text.
|
||||
public static func reassemble(_ chunks: [TextChunk]) -> String {
|
||||
chunks.sorted { $0.index < $1.index }.reduce(into: "") { result, chunk in
|
||||
result += chunk.text
|
||||
result += chunk.separatorAfter
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Splitting
|
||||
|
||||
private func split(
|
||||
_ text: String,
|
||||
trailing: String,
|
||||
limit: Int,
|
||||
into pieces: inout [(text: String, separator: String)]
|
||||
) {
|
||||
if text.count <= limit {
|
||||
pieces.append((text, trailing))
|
||||
return
|
||||
}
|
||||
|
||||
let sentences = sentenceUnits(text)
|
||||
if sentences.count > 1 {
|
||||
splitSubunits(sentences, trailing: trailing, limit: limit, into: &pieces)
|
||||
return
|
||||
}
|
||||
|
||||
let words = wordUnits(text)
|
||||
if words.count > 1 {
|
||||
splitSubunits(words, trailing: trailing, limit: limit, into: &pieces)
|
||||
return
|
||||
}
|
||||
|
||||
splitGraphemes(text, trailing: trailing, into: &pieces)
|
||||
}
|
||||
|
||||
private func splitSubunits(
|
||||
_ units: [(text: String, separator: String)],
|
||||
trailing: String,
|
||||
limit: Int,
|
||||
into pieces: inout [(text: String, separator: String)]
|
||||
) {
|
||||
for (offset, unit) in units.enumerated() {
|
||||
let separator = offset == units.count - 1 ? unit.separator + trailing : unit.separator
|
||||
split(unit.text, trailing: separator, limit: limit, into: &pieces)
|
||||
}
|
||||
}
|
||||
|
||||
private func splitGraphemes(
|
||||
_ text: String,
|
||||
trailing: String,
|
||||
into pieces: inout [(text: String, separator: String)]
|
||||
) {
|
||||
let characters = Array(text)
|
||||
for (offset, character) in characters.enumerated() {
|
||||
let separator = offset == characters.count - 1 ? trailing : ""
|
||||
pieces.append((String(character), separator))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Units
|
||||
|
||||
private func paragraphUnits(_ text: String) -> [(text: String, separator: String)] {
|
||||
guard let regex = try? NSRegularExpression(pattern: "\\n[ \\t]*\\n(?:[ \\t]*\\n)*") else {
|
||||
return [(text, "")]
|
||||
}
|
||||
let nsText = text as NSString
|
||||
let matches = regex.matches(in: text, range: NSRange(location: 0, length: nsText.length))
|
||||
guard !matches.isEmpty else { return [(text, "")] }
|
||||
|
||||
var units: [(String, String)] = []
|
||||
var cursor = 0
|
||||
for match in matches {
|
||||
let body = nsText.substring(with: NSRange(location: cursor, length: match.range.location - cursor))
|
||||
let separator = nsText.substring(with: match.range)
|
||||
units.append((body, separator))
|
||||
cursor = match.range.location + match.range.length
|
||||
}
|
||||
let tail = nsText.substring(from: cursor)
|
||||
units.append((tail, ""))
|
||||
return units
|
||||
}
|
||||
|
||||
private func sentenceUnits(_ text: String) -> [(text: String, separator: String)] {
|
||||
let terminators: Set<Character> = [".", "!", "?", "。", "!", "?", "…"]
|
||||
let closers: Set<Character> = ["\"", "'", "”", "’", ")", "]", "}"]
|
||||
let characters = Array(text)
|
||||
var units: [(String, String)] = []
|
||||
var start = 0
|
||||
var index = 0
|
||||
|
||||
while index < characters.count {
|
||||
guard terminators.contains(characters[index]) else {
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
var end = index + 1
|
||||
while end < characters.count, terminators.contains(characters[end]) {
|
||||
end += 1
|
||||
}
|
||||
while end < characters.count, closers.contains(characters[end]) {
|
||||
end += 1
|
||||
}
|
||||
guard end < characters.count, characters[end].isWhitespace else {
|
||||
index = end
|
||||
continue
|
||||
}
|
||||
var separatorEnd = end
|
||||
while separatorEnd < characters.count, characters[separatorEnd].isWhitespace {
|
||||
separatorEnd += 1
|
||||
}
|
||||
let body = String(characters[start ..< end])
|
||||
let separator = String(characters[end ..< separatorEnd])
|
||||
units.append((body, separator))
|
||||
start = separatorEnd
|
||||
index = separatorEnd
|
||||
}
|
||||
|
||||
if start < characters.count {
|
||||
units.append((String(characters[start...]), ""))
|
||||
}
|
||||
return units.isEmpty ? [(text, "")] : units
|
||||
}
|
||||
|
||||
private func wordUnits(_ text: String) -> [(text: String, separator: String)] {
|
||||
let characters = Array(text)
|
||||
var units: [(String, String)] = []
|
||||
var start = 0
|
||||
var index = 0
|
||||
|
||||
while index < characters.count {
|
||||
guard characters[index].isWhitespace else {
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
let body = String(characters[start ..< index])
|
||||
var end = index
|
||||
while end < characters.count, characters[end].isWhitespace {
|
||||
end += 1
|
||||
}
|
||||
let separator = String(characters[index ..< end])
|
||||
units.append((body, separator))
|
||||
start = end
|
||||
index = end
|
||||
}
|
||||
|
||||
if start < characters.count {
|
||||
units.append((String(characters[start...]), ""))
|
||||
}
|
||||
return units.isEmpty ? [(text, "")] : units
|
||||
}
|
||||
|
||||
// MARK: - Packing
|
||||
|
||||
/// Keeps a leading empty body's separator (for example a text starting with `\n\n` or a long
|
||||
/// over-limit text starting with whitespace) by attaching it to the first non-empty piece.
|
||||
private func mergingLeadingEmpty(
|
||||
_ pieces: [(text: String, separator: String)]
|
||||
) -> [(text: String, separator: String)] {
|
||||
var result = pieces
|
||||
var prefix = ""
|
||||
while let first = result.first, first.text.isEmpty {
|
||||
prefix += first.separator
|
||||
result.removeFirst()
|
||||
}
|
||||
guard !result.isEmpty else {
|
||||
return prefix.isEmpty ? [] : [(prefix, "")]
|
||||
}
|
||||
var first = result[0]
|
||||
first.text = prefix + first.text
|
||||
result[0] = first
|
||||
return result
|
||||
}
|
||||
|
||||
private func pack(
|
||||
_ pieces: [(text: String, separator: String)],
|
||||
limit: Int
|
||||
) -> [TextChunk] {
|
||||
var chunks: [TextChunk] = []
|
||||
var current = ""
|
||||
var trailing = ""
|
||||
var lastSeparator = ""
|
||||
var index = 0
|
||||
|
||||
func emit() {
|
||||
guard !current.isEmpty else { return }
|
||||
chunks.append(TextChunk(index: index, text: current, separatorAfter: trailing))
|
||||
index += 1
|
||||
current = ""
|
||||
trailing = ""
|
||||
lastSeparator = ""
|
||||
}
|
||||
|
||||
for piece in pieces {
|
||||
if current.isEmpty {
|
||||
current = piece.text
|
||||
} else if current.count + lastSeparator.count + piece.text.count <= limit {
|
||||
current += lastSeparator + piece.text
|
||||
} else {
|
||||
emit()
|
||||
current = piece.text
|
||||
}
|
||||
trailing = piece.separator
|
||||
lastSeparator = piece.separator
|
||||
}
|
||||
emit()
|
||||
return chunks
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/// The source-content classes from `docs/ARCHITECTURE.md` §9.1.
|
||||
public enum ContentClass: String, Sendable, Equatable, CaseIterable {
|
||||
/// Ordinary prose.
|
||||
case plain
|
||||
/// Markdown, including headings, lists, tables and fenced code.
|
||||
case markdown
|
||||
/// JSON data.
|
||||
case json
|
||||
/// HTML markup.
|
||||
case html
|
||||
/// Code without Markdown prose.
|
||||
case code
|
||||
/// Many placeholders, URLs or delimiters.
|
||||
case delimited
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import Foundation
|
||||
|
||||
/// A simple content classifier used only to choose a documented prompt fallback.
|
||||
public struct ContentClassifier: Sendable {
|
||||
private let scanner: ProtectedTokenScanner
|
||||
private static let tagRegex = try? NSRegularExpression(pattern: "</?[A-Za-z][^>]*>")
|
||||
|
||||
/// Creates a classifier.
|
||||
public init(scanner: ProtectedTokenScanner = ProtectedTokenScanner()) {
|
||||
self.scanner = scanner
|
||||
}
|
||||
|
||||
/// Classifies `text` as plain, Markdown, JSON, HTML, code or delimiter-heavy.
|
||||
public func classify(_ text: String) -> ContentClass {
|
||||
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else { return .plain }
|
||||
|
||||
if isJSON(trimmed) {
|
||||
return .json
|
||||
}
|
||||
if isHTML(trimmed) {
|
||||
return .html
|
||||
}
|
||||
|
||||
let fenced = trimmed.components(separatedBy: "```").count > 1
|
||||
let markdownMarkers = trimmed.components(separatedBy: "\n").filter { line in
|
||||
let trimmedLine = line.trimmingCharacters(in: .whitespaces)
|
||||
return trimmedLine.hasPrefix("#") || trimmedLine.hasPrefix("- ") || trimmedLine.hasPrefix("* ")
|
||||
|| trimmedLine.hasPrefix("> ") || trimmedLine.hasPrefix("|") || trimmedLine.hasPrefix("[")
|
||||
|| trimmedLine.hasPrefix("![")
|
||||
}.count
|
||||
if markdownMarkers >= 1 || fenced {
|
||||
return fenced && markdownMarkers == 0 ? .code : .markdown
|
||||
}
|
||||
|
||||
let tokens = scanner.scan(trimmed)
|
||||
if tokens.count >= 3 {
|
||||
return .delimited
|
||||
}
|
||||
return .plain
|
||||
}
|
||||
|
||||
private func isJSON(_ text: String) -> Bool {
|
||||
guard text.hasPrefix("{") || text.hasPrefix("["), let data = text.data(using: .utf8) else { return false }
|
||||
return (try? JSONSerialization.jsonObject(with: data)) != nil
|
||||
}
|
||||
|
||||
private func isHTML(_ text: String) -> Bool {
|
||||
guard let tagRegex = Self.tagRegex else { return false }
|
||||
let range = NSRange(location: 0, length: (text as NSString).length)
|
||||
return tagRegex.numberOfMatches(in: text, range: range) >= 2
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import Foundation
|
||||
import NaturalLanguage
|
||||
|
||||
/// One language hypothesis from `NLLanguageRecognizer`.
|
||||
public struct LanguageDetection: Sendable, Equatable {
|
||||
/// The dominant BCP-47 language code, e.g. `en` or `de`.
|
||||
public let code: String
|
||||
/// The recogniser confidence in `code`, from 0 to 1.
|
||||
public let confidence: Double
|
||||
/// Candidate codes ordered by confidence, including `code` first.
|
||||
public let alternatives: [String]
|
||||
|
||||
/// Creates a detection value.
|
||||
public init(code: String, confidence: Double, alternatives: [String]) {
|
||||
self.code = code
|
||||
self.confidence = confidence
|
||||
self.alternatives = alternatives
|
||||
}
|
||||
}
|
||||
|
||||
/// Source-language detection. Advisory only: it never blocks translation.
|
||||
public protocol LanguageDetecting: Sendable {
|
||||
/// Detects the dominant language of `text`, or returns nil for empty/undecidable text.
|
||||
func detect(_ text: String) -> LanguageDetection?
|
||||
}
|
||||
|
||||
/// `NLLanguageRecognizer`-backed detection (`docs/TRANSLATION_OUTPUT.md` §8).
|
||||
public struct NaturalLanguageDetector: LanguageDetecting {
|
||||
/// Creates a detector.
|
||||
public init() {}
|
||||
|
||||
/// Detects the dominant language. Short or mixed text usually reports low confidence.
|
||||
public func detect(_ text: String) -> LanguageDetection? {
|
||||
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else { return nil }
|
||||
|
||||
let recognizer = NLLanguageRecognizer()
|
||||
recognizer.processString(trimmed)
|
||||
guard let dominant = recognizer.dominantLanguage else { return nil }
|
||||
let hypotheses = recognizer.languageHypotheses(withMaximum: 3)
|
||||
let ordered = hypotheses.sorted { lhs, rhs in
|
||||
lhs.value == rhs.value ? lhs.key.rawValue < rhs.key.rawValue : lhs.value > rhs.value
|
||||
}.map(\.key.rawValue)
|
||||
let alternatives = ordered.isEmpty ? [dominant.rawValue] : ordered
|
||||
return LanguageDetection(
|
||||
code: dominant.rawValue,
|
||||
confidence: Double(hypotheses[dominant] ?? 0),
|
||||
alternatives: alternatives
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import Foundation
|
||||
|
||||
/// A protected token that must survive translation (`docs/TRANSLATION_OUTPUT.md` §4).
|
||||
public struct ProtectedToken: Sendable, Equatable, Hashable {
|
||||
/// The token kind.
|
||||
public let kind: ProtectedTokenKind
|
||||
/// The exact text that must appear in the translation.
|
||||
public let value: String
|
||||
|
||||
/// Creates a protected token.
|
||||
public init(kind: ProtectedTokenKind, value: String) {
|
||||
self.kind = kind
|
||||
self.value = value
|
||||
}
|
||||
}
|
||||
|
||||
/// The protected-token kinds from `docs/TRANSLATION_OUTPUT.md` §4.
|
||||
public enum ProtectedTokenKind: String, Sendable, Equatable, CaseIterable {
|
||||
/// `https://…`, `http://…`, `www.…`
|
||||
case url
|
||||
/// `name@example.com`
|
||||
case email
|
||||
/// `{{name}}`, `{{ name }}`
|
||||
case mustache
|
||||
/// `${name}`
|
||||
case templateLiteral
|
||||
/// `%s`, `%d`, `%1$@`, `%02d`
|
||||
case printf
|
||||
/// `` `code` ``
|
||||
case codeSpan
|
||||
/// A fenced code block.
|
||||
case fencedCode
|
||||
/// `<a href="…">`, `</div>`
|
||||
case htmlTag
|
||||
/// A quoted JSON key followed by `:`.
|
||||
case jsonKey
|
||||
/// `/Users/…`, `C:\…`
|
||||
case filePath
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import Foundation
|
||||
|
||||
/// Finds URLs, e-mail addresses, placeholders, code spans, HTML tags, JSON keys and paths that
|
||||
/// must survive translation (`docs/TRANSLATION_OUTPUT.md` §4).
|
||||
public struct ProtectedTokenScanner: Sendable {
|
||||
private struct Rule {
|
||||
let kind: ProtectedTokenKind
|
||||
let regex: NSRegularExpression
|
||||
let group: Int
|
||||
}
|
||||
|
||||
private static let rules: [Rule] = {
|
||||
func rule(
|
||||
_ kind: ProtectedTokenKind,
|
||||
_ pattern: String,
|
||||
group: Int = 0,
|
||||
options: NSRegularExpression.Options = []
|
||||
) -> Rule? {
|
||||
guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else {
|
||||
return nil
|
||||
}
|
||||
return Rule(kind: kind, regex: regex, group: group)
|
||||
}
|
||||
let rules: [Rule?] = [
|
||||
rule(.fencedCode, "```[\\s\\S]*?```"),
|
||||
rule(.codeSpan, "`[^`\\n]+`"),
|
||||
rule(.htmlTag, "</?[A-Za-z][^>\\n]*>"),
|
||||
rule(.url, "(?:https?://|www\\.)[^\\s<>\"']+"),
|
||||
rule(.email, "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"),
|
||||
rule(.mustache, "\\{\\{\\s*[^{}\\n]+\\s*\\}\\}"),
|
||||
rule(.templateLiteral, "\\$\\{[^{}\\n]+\\}"),
|
||||
rule(.printf, "%(?:\\d+\\$)?[-+0#]*\\d*(?:\\.\\d+)?[sd@]"),
|
||||
rule(.jsonKey, "(\"(?:[^\"\\\\]|\\\\.)*\")\\s*:", group: 1),
|
||||
rule(.filePath, "(?:/(?:Users|home|var|usr|opt|tmp)/[^\\s,;:\"'<>]+|[A-Za-z]:\\\\[^\\s,;:\"'<>]+)"),
|
||||
]
|
||||
return rules.compactMap(\.self)
|
||||
}()
|
||||
|
||||
/// Creates a scanner.
|
||||
public init() {}
|
||||
|
||||
/// Scans `text` and returns the protected tokens in source order, without duplicates.
|
||||
public func scan(_ text: String) -> [ProtectedToken] {
|
||||
let nsText = text as NSString
|
||||
let fullRange = NSRange(location: 0, length: nsText.length)
|
||||
var occupied: [NSRange] = []
|
||||
var tokens: [(range: NSRange, token: ProtectedToken)] = []
|
||||
|
||||
for rule in Self.rules {
|
||||
for match in rule.regex.matches(in: text, options: [], range: fullRange) {
|
||||
let range = match.range(at: rule.group)
|
||||
guard range.location != NSNotFound else { continue }
|
||||
if occupied.contains(where: { NSIntersectionRange($0, range).length > 0 }) {
|
||||
continue
|
||||
}
|
||||
var value = nsText.substring(with: range)
|
||||
if rule.kind == .url {
|
||||
value = trimURLTail(value)
|
||||
if value.count < 4 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
let token = ProtectedToken(kind: rule.kind, value: value)
|
||||
if tokens.contains(where: { $0.token == token }) {
|
||||
continue
|
||||
}
|
||||
tokens.append((range, token))
|
||||
occupied.append(range)
|
||||
}
|
||||
}
|
||||
|
||||
return tokens.sorted { $0.range.location < $1.range.location }.map(\.token)
|
||||
}
|
||||
|
||||
/// Removes sentence punctuation that a URL pattern may have swallowed. A balanced closing
|
||||
/// parenthesis is kept, so Wikipedia-style URLs remain intact.
|
||||
private func trimURLTail(_ value: String) -> String {
|
||||
var result = value
|
||||
while let last = result.last, ".,;:!?".contains(last) {
|
||||
result.removeLast()
|
||||
}
|
||||
while let last = result.last, ")]}".contains(last) {
|
||||
let open: Character = last == ")" ? "(" : (last == "]" ? "[" : "{")
|
||||
let opens = result.filter { $0 == open }.count
|
||||
let closes = result.filter { $0 == last }.count
|
||||
guard closes > opens else { break }
|
||||
result.removeLast()
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/// One chunk of a translation, with the separator that followed it in the source.
|
||||
public struct TextChunk: Sendable, Equatable {
|
||||
/// The zero-based chunk index.
|
||||
public let index: Int
|
||||
/// The chunk text.
|
||||
public let text: String
|
||||
/// The source separator after this chunk (`"\n\n"`, `" "` or `""`).
|
||||
public let separatorAfter: String
|
||||
|
||||
/// Creates a chunk.
|
||||
public init(index: Int, text: String, separatorAfter: String) {
|
||||
self.index = index
|
||||
self.text = text
|
||||
self.separatorAfter = separatorAfter
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import Foundation
|
||||
|
||||
/// Input and output normalisation from `docs/TRANSLATION_OUTPUT.md` §2 and §5.
|
||||
public enum TextNormalization {
|
||||
/// N1–N3: line endings to `\n`, strip BOM/NUL/C0 controls (except tab and newline),
|
||||
/// strip U+200B, keep ZWJ/ZWNJ, NFC, then trim outer whitespace (N2).
|
||||
public static func normalizeInput(_ text: String) -> String {
|
||||
let unified = unifyLineEndings(text)
|
||||
let filtered = unified.unicodeScalars.filter { scalar in
|
||||
switch scalar.value {
|
||||
case 0, 0xFEFF, 0x200B:
|
||||
return false
|
||||
default:
|
||||
break
|
||||
}
|
||||
if scalar.properties.generalCategory == .control {
|
||||
return scalar.value == 0x09 || scalar.value == 0x0A
|
||||
}
|
||||
return true
|
||||
}
|
||||
let cleaned = String(String.UnicodeScalarView(filtered))
|
||||
return cleaned.precomposedStringWithCanonicalMapping.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
/// T1: strip NUL, normalise line endings, trim outer whitespace. Internal text is untouched.
|
||||
public static func normalizeOutput(_ text: String) -> String {
|
||||
unifyLineEndings(text)
|
||||
.replacingOccurrences(of: "\0", with: "")
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
/// Comparison normalisation for the double-copy rule: line endings and outer trimming only.
|
||||
/// Internal whitespace is deliberately preserved.
|
||||
public static func normalizeForComparison(_ text: String) -> String {
|
||||
unifyLineEndings(text).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
private static func unifyLineEndings(_ text: String) -> String {
|
||||
text
|
||||
.replacingOccurrences(of: "\r\n", with: "\n")
|
||||
.replacingOccurrences(of: "\r", with: "\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/// Dense-script detection for the chunk limit (`docs/TRANSLATION_OUTPUT.md` §3).
|
||||
///
|
||||
/// The limit is script-based, not language-based: one CJK, Arabic, Thai or Indic character is
|
||||
/// enough to select the smaller limit. Latin, Cyrillic and Greek stay on the larger limit.
|
||||
public enum TextScript {
|
||||
private static let denseRanges: [ClosedRange<UInt32>] = [
|
||||
0x0590 ... 0x05FF, // Hebrew
|
||||
0x0600 ... 0x06FF, // Arabic
|
||||
0x0750 ... 0x077F, // Arabic Supplement
|
||||
0x0900 ... 0x097F, // Devanagari
|
||||
0x0980 ... 0x09FF, // Bengali
|
||||
0x0A00 ... 0x0A7F, // Gurmukhi
|
||||
0x0A80 ... 0x0AFF, // Gujarati
|
||||
0x0B00 ... 0x0B7F, // Oriya
|
||||
0x0B80 ... 0x0BFF, // Tamil
|
||||
0x0C00 ... 0x0C7F, // Telugu
|
||||
0x0C80 ... 0x0CFF, // Kannada
|
||||
0x0D00 ... 0x0D7F, // Malayalam
|
||||
0x0D80 ... 0x0DFF, // Sinhala
|
||||
0x0E00 ... 0x0E7F, // Thai
|
||||
0x0E80 ... 0x0EFF, // Lao
|
||||
0x0F00 ... 0x0FFF, // Tibetan
|
||||
0x1000 ... 0x109F, // Myanmar
|
||||
0x1200 ... 0x137F, // Ethiopic
|
||||
0x1780 ... 0x17FF, // Khmer
|
||||
0x1800 ... 0x18AF, // Mongolian
|
||||
0x2E80 ... 0x9FFF, // CJK, Hiragana, Katakana and Hangul compatibility
|
||||
0xA960 ... 0xA97F, // Hangul Jamo Extended-A
|
||||
0xAC00 ... 0xD7AF, // Hangul syllables
|
||||
0xF900 ... 0xFAFF, // CJK compatibility ideographs
|
||||
0xFE30 ... 0xFE4F, // CJK compatibility forms
|
||||
0xFF66 ... 0xFFDC, // Half-width Katakana and Hangul
|
||||
]
|
||||
|
||||
/// True when `text` contains at least one dense-script scalar.
|
||||
public static func isDense(_ text: String) -> Bool {
|
||||
text.unicodeScalars.contains { scalar in
|
||||
denseRanges.contains { $0.contains(scalar.value) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
@@ -19,7 +20,14 @@ struct CLIEnvironment: Sendable {
|
||||
try OllamaChatClient(http: makeHTTPClient())
|
||||
}
|
||||
|
||||
func makeRequestFactory(model: String) -> HyMT3RequestFactory {
|
||||
HyMT3RequestFactory(model: model)
|
||||
func makeRegistry() -> AdapterRegistry {
|
||||
AdapterRegistry(adapters: [HyMT3Adapter()])
|
||||
}
|
||||
|
||||
func makePipeline() throws -> TranslationPipeline {
|
||||
try TranslationPipeline(
|
||||
chat: makeChatClient(),
|
||||
registry: makeRegistry()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerOllama
|
||||
|
||||
enum CLIError {
|
||||
@@ -18,12 +19,63 @@ enum CLIError {
|
||||
} catch let validation as ValidationError {
|
||||
writeError(String(describing: validation))
|
||||
throw ExitCode(2)
|
||||
} catch let domain as SprachmittlerError {
|
||||
writeError(message(for: domain))
|
||||
throw ExitCode(exitCode(for: domain))
|
||||
} catch {
|
||||
writeError("Error: \(error)")
|
||||
throw ExitCode(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// 2 = endpoint/usage, 3 = unreachable, 4 = model missing, 1 = other runtime failure.
|
||||
static func exitCode(for error: SprachmittlerError) -> Int32 {
|
||||
switch error {
|
||||
case .endpointRejected, .noAdapter, .emptyText, .textTooLong, .badRequest:
|
||||
2
|
||||
case .ollamaUnreachable:
|
||||
3
|
||||
case .modelNotInstalled:
|
||||
4
|
||||
default:
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
static func message(for error: SprachmittlerError) -> String {
|
||||
switch error {
|
||||
case let .ollamaUnreachable(url):
|
||||
"Ollama is not reachable at \(url.absoluteString)."
|
||||
case let .modelNotInstalled(model):
|
||||
"Model not installed: \(model)"
|
||||
case let .noAdapter(model):
|
||||
"No translation adapter for \(model)."
|
||||
case let .endpointRejected(reason):
|
||||
"Endpoint rejected: \(message(for: reason))"
|
||||
default:
|
||||
genericMessage(for: error)
|
||||
}
|
||||
}
|
||||
|
||||
private static func genericMessage(for error: SprachmittlerError) -> String {
|
||||
switch error {
|
||||
case .emptyText:
|
||||
"No text to translate."
|
||||
case let .textTooLong(characters, limit):
|
||||
"Text is too long (\(characters) characters; limit \(limit))."
|
||||
case let .timeout(phase):
|
||||
"Timed out while talking to Ollama (\(phase))."
|
||||
case let .server(status, _):
|
||||
"Ollama returned HTTP \(status)."
|
||||
case .badRequest:
|
||||
"Ollama rejected the request."
|
||||
case .cancelled:
|
||||
"Cancelled."
|
||||
default:
|
||||
"Translation failed."
|
||||
}
|
||||
}
|
||||
|
||||
/// 2 = endpoint/usage, 3 = unreachable, 4 = model missing, 1 = other runtime failure.
|
||||
static func exitCode(for error: OllamaError) -> Int32 {
|
||||
switch error {
|
||||
|
||||
@@ -47,12 +47,10 @@ struct TranslateCommand: AsyncParsableCommand {
|
||||
|
||||
try await CLIError.perform {
|
||||
let environment = try endpoint.makeEnvironment()
|
||||
let chat = try environment.makeChatClient()
|
||||
let runner = TranslateRunner(
|
||||
chat: chat,
|
||||
factory: environment.makeRequestFactory(model: model)
|
||||
let runner = try TranslateRunner(
|
||||
pipeline: environment.makePipeline()
|
||||
)
|
||||
let outcome = try await runner.run(text: source, target: language)
|
||||
let outcome = try await runner.run(text: source, target: language, model: model)
|
||||
if json {
|
||||
let data = try outcome.jsonData(includeSource: includeSource, source: source)
|
||||
print(String(data: data, encoding: .utf8) ?? "{}")
|
||||
|
||||
@@ -1,34 +1,33 @@
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
struct TranslateOutcome: Sendable, Equatable {
|
||||
let translation: String
|
||||
let model: String
|
||||
let target: ModelLanguage
|
||||
let metrics: ChatMetrics
|
||||
let firstTokenMs: Int?
|
||||
let totalMs: Int
|
||||
let warnings: [TranslationWarning]
|
||||
let sourceLanguage: String?
|
||||
let timing: TranslationTiming
|
||||
let sourceCharacters: Int
|
||||
|
||||
/// The CLI JSON contract from docs/TRANSLATION_OUTPUT.md §10. `sourceLanguage` stays null
|
||||
/// until T2.4; warnings stay empty until T2.5.
|
||||
/// The CLI JSON contract from docs/TRANSLATION_OUTPUT.md §10.
|
||||
func jsonData(includeSource: Bool, source: String) throws -> Data {
|
||||
let timing: [String: Any] = [
|
||||
"firstTokenMs": firstTokenMs.map { $0 as Any } ?? NSNull(),
|
||||
"totalMs": totalMs,
|
||||
"promptTokens": metrics.promptEvalCount.map { $0 as Any } ?? NSNull(),
|
||||
"outputTokens": metrics.evalCount.map { $0 as Any } ?? NSNull(),
|
||||
let timingObject: [String: Any] = [
|
||||
"firstTokenMs": timing.firstTokenMs.map { $0 as Any } ?? NSNull(),
|
||||
"totalMs": timing.totalMs,
|
||||
"promptTokens": timing.promptTokens.map { $0 as Any } ?? NSNull(),
|
||||
"outputTokens": timing.outputTokens.map { $0 as Any } ?? NSNull(),
|
||||
]
|
||||
var object: [String: Any] = [
|
||||
"schema": "sprachmittler-translation-v1",
|
||||
"sourceLanguage": NSNull(),
|
||||
"sourceLanguage": sourceLanguage ?? NSNull(),
|
||||
"targetLanguage": target.code,
|
||||
"model": model,
|
||||
"sourceCharacters": sourceCharacters,
|
||||
"translation": translation,
|
||||
"warnings": [String](),
|
||||
"timing": timing,
|
||||
"warnings": warnings.map(\.code),
|
||||
"timing": timingObject,
|
||||
]
|
||||
if includeSource {
|
||||
object["source"] = source
|
||||
|
||||
@@ -1,39 +1,24 @@
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
struct TranslateRunner: Sendable {
|
||||
let chat: any OllamaChatting
|
||||
let factory: HyMT3RequestFactory
|
||||
let pipeline: TranslationPipeline
|
||||
|
||||
func run(text: String, target: ModelLanguage) async throws -> TranslateOutcome {
|
||||
let request = factory.translationRequest(text: text, target: target)
|
||||
let started = Date()
|
||||
var firstDelta: Date?
|
||||
var translation = ""
|
||||
var metrics = ChatMetrics.empty
|
||||
|
||||
for try await event in chat.chat(request) {
|
||||
switch event {
|
||||
case let .delta(delta):
|
||||
if firstDelta == nil {
|
||||
firstDelta = Date()
|
||||
}
|
||||
translation += delta
|
||||
case let .done(_, doneMetrics):
|
||||
metrics = doneMetrics
|
||||
}
|
||||
}
|
||||
|
||||
let totalMs = max(0, Int(Date().timeIntervalSince(started) * 1000))
|
||||
let firstTokenMs = firstDelta.map { max(0, Int($0.timeIntervalSince(started) * 1000)) }
|
||||
return TranslateOutcome(
|
||||
translation: translation,
|
||||
model: request.model,
|
||||
func run(text: String, target: ModelLanguage, model: String) async throws -> TranslateOutcome {
|
||||
let result = try await pipeline.translate(
|
||||
text: text,
|
||||
target: target,
|
||||
metrics: metrics,
|
||||
firstTokenMs: firstTokenMs,
|
||||
totalMs: totalMs,
|
||||
model: model,
|
||||
keepAlive: HyMT3ModelPreset.defaultKeepAlive
|
||||
)
|
||||
return TranslateOutcome(
|
||||
translation: result.translation,
|
||||
model: model,
|
||||
target: target,
|
||||
warnings: result.warnings,
|
||||
sourceLanguage: result.sourceLanguage,
|
||||
timing: result.timing,
|
||||
sourceCharacters: text.count
|
||||
)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user