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,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
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user