feat(settings): mother-tongue language routing table
Replace the single reverse-direction pair with a general routing table. The saved target is the mother tongue and the default target for every source; languageRoutes is an empty-by-default, source-unique list of source-to-target rules (for example Chinese -> English, Traditional Chinese -> English, German -> English). Rules apply only when the source is confidently detected; otherwise the mother tongue is used. Same-language rules are dropped.\n\nThe panel shows the effective direction and a banner explaining a rule, with a one-capture override back to the mother tongue; the panel picker is now a session-only override. Persistent rules are edited in Settings. The old autoSwitchTarget/fallbackTargetLanguage keys are ignored, so the default after migration is everything -> mother tongue.\n\nAdd LanguageRoute, generalize the direction policy and tests, add the rules UI, and update ADR-022, architecture, translation output, user guide, README and progress. Verified: make verify green; empty rules translate French -> German, a Chinese -> English rule produces Chinese (Simplified) -> English with the banner, and the rules table renders in Settings.
This commit is contained in:
1 parent
41f1cea769
commit
940abcc996
24 files changed
+454
-336
No files matched your search
@@ -1,13 +1,8 @@
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
|
||||
private struct DecodedDirection {
|
||||
let autoSwitch: Bool
|
||||
let fallback: String
|
||||
}
|
||||
|
||||
extension AppSettings {
|
||||
public init(from decoder: any Decoder) throws {
|
||||
public extension AppSettings {
|
||||
init(from decoder: any Decoder) throws {
|
||||
let defaults = AppSettings()
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
|
||||
@@ -21,9 +16,9 @@ extension AppSettings {
|
||||
let decodedTarget = try container.decodeIfPresent(String.self, forKey: .targetLanguage)
|
||||
?? defaults.targetLanguage
|
||||
targetLanguage = HyMT3Languages.resolve(decodedTarget)?.code ?? defaults.targetLanguage
|
||||
let direction = try Self.decodeDirection(from: container, defaults: defaults, target: targetLanguage)
|
||||
autoSwitchTarget = direction.autoSwitch
|
||||
fallbackTargetLanguage = direction.fallback
|
||||
languageRoutes = try AppSettings.normalizedRoutes(
|
||||
container.decodeIfPresent([LanguageRoute].self, forKey: .languageRoutes) ?? []
|
||||
)
|
||||
recentTargetLanguages = try Self.decodeRecentTargets(from: container)
|
||||
let limits = try Self.decodeLimits(from: container, defaults: defaults)
|
||||
doubleCopyWindowMs = limits.window
|
||||
@@ -60,15 +55,14 @@ extension AppSettings {
|
||||
settingsVersion = Self.currentVersion
|
||||
}
|
||||
|
||||
public func encode(to encoder: any Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(endpoint, forKey: .endpoint)
|
||||
try container.encode(allowRemoteEndpoint, forKey: .allowRemoteEndpoint)
|
||||
try container.encode(model, forKey: .model)
|
||||
try container.encode(fastModel, forKey: .fastModel)
|
||||
try container.encode(targetLanguage, forKey: .targetLanguage)
|
||||
try container.encode(autoSwitchTarget, forKey: .autoSwitchTarget)
|
||||
try container.encode(fallbackTargetLanguage, forKey: .fallbackTargetLanguage)
|
||||
try container.encode(languageRoutes, forKey: .languageRoutes)
|
||||
try container.encode(recentTargetLanguages, forKey: .recentTargetLanguages)
|
||||
try container.encode(doubleCopyWindowMs, forKey: .doubleCopyWindowMs)
|
||||
try container.encode(maxCharactersLatin, forKey: .maxCharactersLatin)
|
||||
@@ -93,21 +87,6 @@ extension AppSettings {
|
||||
try container.encode(settingsVersion, forKey: .settingsVersion)
|
||||
}
|
||||
|
||||
private static func decodeDirection(
|
||||
from container: KeyedDecodingContainer<CodingKeys>,
|
||||
defaults: AppSettings,
|
||||
target: String
|
||||
) throws -> DecodedDirection {
|
||||
let autoSwitch = try container.decodeIfPresent(Bool.self, forKey: .autoSwitchTarget)
|
||||
?? defaults.autoSwitchTarget
|
||||
let code = try container.decodeIfPresent(String.self, forKey: .fallbackTargetLanguage)
|
||||
?? defaults.fallbackTargetLanguage
|
||||
return DecodedDirection(
|
||||
autoSwitch: autoSwitch,
|
||||
fallback: AppSettings.normalizedFallback(code, target: target)
|
||||
)
|
||||
}
|
||||
|
||||
private static func decodeRecentTargets(
|
||||
from container: KeyedDecodingContainer<CodingKeys>
|
||||
) throws -> [String] {
|
||||
|
||||
@@ -27,12 +27,10 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
public var model: String
|
||||
/// The optional Fast model tag.
|
||||
public var fastModel: String?
|
||||
/// The selected target BCP-47 code.
|
||||
/// The mother tongue BCP-47 code; the default target when no rule matches.
|
||||
public var targetLanguage: String
|
||||
/// Translate into the fallback when the source is already the target.
|
||||
public var autoSwitchTarget: Bool
|
||||
/// The fallback target BCP-47 code used by `autoSwitchTarget`.
|
||||
public var fallbackTargetLanguage: String
|
||||
/// Source-language to target-language rules. Empty means everything goes to the mother tongue.
|
||||
public var languageRoutes: [LanguageRoute]
|
||||
/// Up to three recent target codes, most recent first.
|
||||
public var recentTargetLanguages: [String]
|
||||
/// The double-copy window in milliseconds (300–1000).
|
||||
@@ -86,10 +84,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
model = HyMT3ModelPreset.defaultModel
|
||||
fastModel = HyMT3ModelPreset.fastModel
|
||||
targetLanguage = systemCode ?? HyMT3Languages.english.code
|
||||
autoSwitchTarget = true
|
||||
fallbackTargetLanguage = targetLanguage == HyMT3Languages.english.code
|
||||
? HyMT3Languages.german.code
|
||||
: HyMT3Languages.english.code
|
||||
languageRoutes = []
|
||||
recentTargetLanguages = []
|
||||
doubleCopyWindowMs = 500
|
||||
maxCharactersLatin = 4000
|
||||
@@ -119,11 +114,6 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
HyMT3Languages.resolve(targetLanguage) ?? HyMT3Languages.english
|
||||
}
|
||||
|
||||
/// The fallback target, always a catalogue entry.
|
||||
public var fallbackTargetModel: ModelLanguage {
|
||||
HyMT3Languages.resolve(fallbackTargetLanguage) ?? HyMT3Languages.english
|
||||
}
|
||||
|
||||
/// The recent targets that still exist in the catalogue.
|
||||
public var recentTargets: [ModelLanguage] {
|
||||
recentTargetLanguages.compactMap(HyMT3Languages.resolve)
|
||||
@@ -136,9 +126,6 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
|
||||
/// Records a target as recent, keeping at most three unique codes.
|
||||
public mutating func noteTarget(_ language: ModelLanguage) {
|
||||
if language.code != targetLanguage, language.code == fallbackTargetLanguage {
|
||||
fallbackTargetLanguage = targetLanguage
|
||||
}
|
||||
targetLanguage = language.code
|
||||
recentTargetLanguages.removeAll { $0 == language.code }
|
||||
recentTargetLanguages.insert(language.code, at: 0)
|
||||
@@ -148,7 +135,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
/// Clamps values edited outside the decoder (Settings UI) to the safe ranges.
|
||||
public mutating func sanitize() {
|
||||
targetLanguage = HyMT3Languages.resolve(targetLanguage)?.code ?? HyMT3Languages.english.code
|
||||
fallbackTargetLanguage = Self.normalizedFallback(fallbackTargetLanguage, target: targetLanguage)
|
||||
languageRoutes = Self.normalizedRoutes(languageRoutes)
|
||||
doubleCopyWindowMs = Self.clamp(doubleCopyWindowMs, to: 300 ... 1000)
|
||||
maxCharactersLatin = Self.clamp(maxCharactersLatin, to: 500 ... 10000)
|
||||
maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 5000)
|
||||
@@ -255,8 +242,8 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
}
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, autoSwitchTarget
|
||||
case fallbackTargetLanguage, recentTargetLanguages
|
||||
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, languageRoutes
|
||||
case recentTargetLanguages
|
||||
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, numCtx, numPredict
|
||||
case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch
|
||||
case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, renderMarkdown
|
||||
@@ -264,12 +251,18 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
case settingsVersion
|
||||
}
|
||||
|
||||
static func normalizedFallback(_ code: String, target: String) -> String {
|
||||
let resolved = HyMT3Languages.resolve(code)?.code ?? HyMT3Languages.english.code
|
||||
guard resolved == target else { return resolved }
|
||||
return target == HyMT3Languages.english.code
|
||||
? HyMT3Languages.german.code
|
||||
: HyMT3Languages.english.code
|
||||
static func normalizedRoutes(_ routes: [LanguageRoute]) -> [LanguageRoute] {
|
||||
var seen = Set<String>()
|
||||
return routes.compactMap { route in
|
||||
guard let source = HyMT3Languages.resolve(route.source)?.code,
|
||||
let target = HyMT3Languages.resolve(route.target)?.code,
|
||||
source.caseInsensitiveCompare(target) != .orderedSame,
|
||||
seen.insert(source.lowercased()).inserted
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
return LanguageRoute(source: source, target: target)
|
||||
}
|
||||
}
|
||||
|
||||
static func clamp(_ value: Int, to range: ClosedRange<Int>) -> Int {
|
||||
|
||||
@@ -21,10 +21,8 @@ public enum PanelPhase: Sendable, Equatable {
|
||||
public struct PanelConfiguration: Sendable, Equatable {
|
||||
/// The selected target language.
|
||||
public var target: ModelLanguage
|
||||
/// Whether the source-equals-target direction switches to `fallbackTarget`.
|
||||
public var autoSwitchTarget: Bool
|
||||
/// The fallback target used when the source is already the target.
|
||||
public var fallbackTarget: ModelLanguage?
|
||||
/// Source-to-target rules. Empty means everything goes to `target` (the mother tongue).
|
||||
public var languageRoutes: [LanguageRoute]
|
||||
/// The selected model tag.
|
||||
public var model: String
|
||||
/// The Ollama keep-alive value.
|
||||
@@ -52,8 +50,7 @@ public struct PanelConfiguration: Sendable, Equatable {
|
||||
translationFontSize: Int = 17,
|
||||
renderMarkdown: Bool = true,
|
||||
closeWithEscape: Bool = true,
|
||||
autoSwitchTarget: Bool = true,
|
||||
fallbackTarget: ModelLanguage? = HyMT3Languages.english,
|
||||
languageRoutes: [LanguageRoute] = [],
|
||||
recentTargets: [ModelLanguage] = []
|
||||
) {
|
||||
self.target = target
|
||||
@@ -64,8 +61,7 @@ public struct PanelConfiguration: Sendable, Equatable {
|
||||
self.translationFontSize = translationFontSize
|
||||
self.renderMarkdown = renderMarkdown
|
||||
self.closeWithEscape = closeWithEscape
|
||||
self.autoSwitchTarget = autoSwitchTarget
|
||||
self.fallbackTarget = fallbackTarget
|
||||
self.languageRoutes = languageRoutes
|
||||
self.recentTargets = recentTargets
|
||||
}
|
||||
}
|
||||
@@ -96,8 +92,8 @@ public final class PanelViewModel {
|
||||
public private(set) var configuration: PanelConfiguration
|
||||
/// The target used by the current request, after an optional reverse-direction switch.
|
||||
public private(set) var effectiveTarget: ModelLanguage
|
||||
/// The saved target that was replaced by `effectiveTarget`, or nil.
|
||||
public private(set) var autoSwitchedFrom: ModelLanguage?
|
||||
/// The matched rule source when `effectiveTarget` differs from the mother tongue, or nil.
|
||||
public private(set) var routedSource: ModelLanguage?
|
||||
/// True after the user dismisses the same-language advisory.
|
||||
public private(set) var sameLanguageDismissed = false
|
||||
|
||||
@@ -217,13 +213,12 @@ public final class PanelViewModel {
|
||||
sourceLanguage = detection?.code
|
||||
let direction = TranslationDirectionPolicy.resolve(
|
||||
configuredTarget: configuration.target,
|
||||
fallbackTarget: configuration.fallbackTarget,
|
||||
routes: configuration.languageRoutes,
|
||||
detection: detection,
|
||||
autoSwitch: configuration.autoSwitchTarget,
|
||||
override: directionOverride
|
||||
)
|
||||
effectiveTarget = direction.target
|
||||
autoSwitchedFrom = direction.didSwitch ? direction.originalTarget : nil
|
||||
routedSource = direction.didRoute ? direction.source : nil
|
||||
sameLanguageDismissed = directionOverride
|
||||
phase = .translating
|
||||
}
|
||||
@@ -262,7 +257,7 @@ public final class PanelViewModel {
|
||||
timing = nil
|
||||
sourceLanguage = nil
|
||||
effectiveTarget = configuration.target
|
||||
autoSwitchedFrom = nil
|
||||
routedSource = nil
|
||||
directionOverride = false
|
||||
}
|
||||
|
||||
@@ -271,7 +266,7 @@ public final class PanelViewModel {
|
||||
guard language.code != effectiveTarget.code else { return }
|
||||
configuration.target = language
|
||||
effectiveTarget = language
|
||||
autoSwitchedFrom = nil
|
||||
routedSource = nil
|
||||
directionOverride = true
|
||||
onTargetChanged(language)
|
||||
if let lastCaptured {
|
||||
@@ -283,7 +278,7 @@ public final class PanelViewModel {
|
||||
public func overrideTarget(_ language: ModelLanguage) async {
|
||||
guard language.code != effectiveTarget.code else { return }
|
||||
effectiveTarget = language
|
||||
autoSwitchedFrom = nil
|
||||
routedSource = nil
|
||||
directionOverride = true
|
||||
sameLanguageDismissed = true
|
||||
if let lastCaptured {
|
||||
@@ -326,7 +321,7 @@ public final class PanelViewModel {
|
||||
self.configuration = configuration
|
||||
if targetChanged || source == nil {
|
||||
effectiveTarget = configuration.target
|
||||
autoSwitchedFrom = nil
|
||||
routedSource = nil
|
||||
directionOverride = false
|
||||
}
|
||||
}
|
||||
@@ -345,7 +340,7 @@ public final class PanelViewModel {
|
||||
isReplacing = false
|
||||
sameLanguageDismissed = false
|
||||
effectiveTarget = configuration.target
|
||||
autoSwitchedFrom = nil
|
||||
routedSource = nil
|
||||
directionOverride = false
|
||||
lastCaptured = nil
|
||||
}
|
||||
|
||||
@@ -3,14 +3,14 @@ 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 {
|
||||
/// True when detection is confident and every meaningful alternative resolves to `language`.
|
||||
public static func isLanguage(_ detection: LanguageDetection, _ language: ModelLanguage) -> Bool {
|
||||
guard detection.confidence >= 0.5, !detection.alternatives.isEmpty else { return false }
|
||||
let targetCode = HyMT3Languages.resolve(target.code)?.code ?? target.code
|
||||
let targetCode = HyMT3Languages.resolve(language.code)?.code ?? language.code
|
||||
var agreed = false
|
||||
for code in detection.alternatives {
|
||||
guard let language = HyMT3Languages.resolve(code),
|
||||
language.code.caseInsensitiveCompare(targetCode) == .orderedSame
|
||||
guard let resolved = HyMT3Languages.resolve(code),
|
||||
resolved.code.caseInsensitiveCompare(targetCode) == .orderedSame
|
||||
else {
|
||||
return false
|
||||
}
|
||||
@@ -18,4 +18,9 @@ public enum LanguageMatching {
|
||||
}
|
||||
return agreed
|
||||
}
|
||||
|
||||
/// True when detection is confident and every meaningful alternative is the target language.
|
||||
public static func isSameLanguage(_ detection: LanguageDetection, target: ModelLanguage) -> Bool {
|
||||
isLanguage(detection, target)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import Foundation
|
||||
|
||||
/// A source-language to target-language rule. The mother tongue is the default when no rule matches.
|
||||
public struct LanguageRoute: Codable, Sendable, Equatable, Hashable, Identifiable {
|
||||
/// The canonical BCP-47 source code.
|
||||
public var source: String
|
||||
/// The canonical BCP-47 target code.
|
||||
public var target: String
|
||||
|
||||
/// The source code is unique in the rule table.
|
||||
public var id: String {
|
||||
source
|
||||
}
|
||||
|
||||
/// Creates a route from canonical codes.
|
||||
public init(source: String, target: String) {
|
||||
self.source = source
|
||||
self.target = target
|
||||
}
|
||||
|
||||
/// Creates a route from catalogue entries.
|
||||
public init(source: ModelLanguage, target: ModelLanguage) {
|
||||
self.init(source: source.code, target: target.code)
|
||||
}
|
||||
|
||||
/// The catalogue entry for the source, or nil when the code is unknown.
|
||||
public var sourceLanguage: ModelLanguage? {
|
||||
HyMT3Languages.resolve(source)
|
||||
}
|
||||
|
||||
/// The catalogue entry for the target, or nil when the code is unknown.
|
||||
public var targetLanguage: ModelLanguage? {
|
||||
HyMT3Languages.resolve(target)
|
||||
}
|
||||
}
|
||||
@@ -4,16 +4,16 @@ import SprachmittlerText
|
||||
public struct TranslationDirection: Sendable, Equatable {
|
||||
/// The language the request will translate into.
|
||||
public let target: ModelLanguage
|
||||
/// True when the configured target was replaced by the fallback target.
|
||||
public let didSwitch: Bool
|
||||
/// The configured target when `didSwitch` is true.
|
||||
public let originalTarget: ModelLanguage?
|
||||
/// True when a language rule changed the target.
|
||||
public let didRoute: Bool
|
||||
/// The rule source when `didRoute` is true.
|
||||
public let source: ModelLanguage?
|
||||
|
||||
/// Creates a direction.
|
||||
public init(target: ModelLanguage, didSwitch: Bool, originalTarget: ModelLanguage?) {
|
||||
public init(target: ModelLanguage, didRoute: Bool, source: ModelLanguage?) {
|
||||
self.target = target
|
||||
self.didSwitch = didSwitch
|
||||
self.originalTarget = originalTarget
|
||||
self.didRoute = didRoute
|
||||
self.source = source
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,25 +23,30 @@ public enum TranslationDirectionPolicy {
|
||||
/// Resolves the target.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - configuredTarget: The user's saved target language.
|
||||
/// - fallbackTarget: The language to use when the source is already the configured target.
|
||||
/// - configuredTarget: The user's mother tongue, used when no rule matches.
|
||||
/// - routes: The source-to-target rules.
|
||||
/// - detection: The advisory source-language detection.
|
||||
/// - autoSwitch: Whether the fallback is enabled.
|
||||
/// - override: True after an explicit target choice for the current capture.
|
||||
public static func resolve(
|
||||
configuredTarget: ModelLanguage,
|
||||
fallbackTarget: ModelLanguage?,
|
||||
routes: [LanguageRoute],
|
||||
detection: LanguageDetection?,
|
||||
autoSwitch: Bool,
|
||||
override: Bool
|
||||
) -> TranslationDirection {
|
||||
guard autoSwitch, !override, let fallbackTarget,
|
||||
fallbackTarget.code.caseInsensitiveCompare(configuredTarget.code) != .orderedSame,
|
||||
let detection,
|
||||
LanguageMatching.isSameLanguage(detection, target: configuredTarget)
|
||||
else {
|
||||
return TranslationDirection(target: configuredTarget, didSwitch: false, originalTarget: nil)
|
||||
guard !override, let detection else {
|
||||
return TranslationDirection(target: configuredTarget, didRoute: false, source: nil)
|
||||
}
|
||||
return TranslationDirection(target: fallbackTarget, didSwitch: true, originalTarget: configuredTarget)
|
||||
for route in routes {
|
||||
guard let source = route.sourceLanguage,
|
||||
let target = route.targetLanguage,
|
||||
target.code.caseInsensitiveCompare(source.code) != .orderedSame,
|
||||
target.code.caseInsensitiveCompare(configuredTarget.code) != .orderedSame,
|
||||
LanguageMatching.isLanguage(detection, source)
|
||||
else {
|
||||
continue
|
||||
}
|
||||
return TranslationDirection(target: target, didRoute: true, source: source)
|
||||
}
|
||||
return TranslationDirection(target: configuredTarget, didRoute: false, source: nil)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user