Add opt-in automatic reverse translation for a two-language pair. autoSwitchTarget defaults on with fallbackTargetLanguage English (or German when the target is English); the saved target and the effective request target are separate. Confident source-equals-target text uses the fallback, the header and a panel banner show the effective direction, and the banner can override the direction for one capture without changing the saved target. The language picker still changes the saved target, and changing the target to the fallback swaps the pair. JSON/HTML/code handling is unchanged.\n\nFilter near-zero NLLanguageRecognizer hypotheses so the existing high-confidence same-language rule works for real text. Add resolver, settings, view-model, detector and persistence tests; document ADR-022, the panel, settings and user guide. Verified: make verify green; German text with target German/fallback English renders German → English with the banner, English text stays English → German, a real click on the override shows German → German, and a new German capture switches back to English.
279 lines
11 KiB
Swift
279 lines
11 KiB
Swift
import Foundation
|
||
import SprachmittlerEngines
|
||
import SprachmittlerOllama
|
||
import SprachmittlerText
|
||
|
||
/// The documented prompt policy. `contentAware` is reserved for M7.
|
||
public enum PromptVariantPolicy: String, Codable, Sendable, Equatable {
|
||
/// Default Translation only (v1).
|
||
case defaultOnly
|
||
/// Content-aware prompt selection (reserved for M7).
|
||
case contentAware
|
||
}
|
||
|
||
/// The versioned, text-free application settings from `docs/ARCHITECTURE.md` §12.
|
||
public struct AppSettings: Codable, Sendable, Equatable {
|
||
/// The loopback default endpoint; a compile-time constant.
|
||
public static let defaultEndpoint = URL(string: "http://127.0.0.1:11434")!
|
||
|
||
/// The current settings schema version.
|
||
public static let currentVersion = 1
|
||
|
||
/// Ollama base URL.
|
||
public var endpoint: URL
|
||
/// Whether a non-loopback endpoint is allowed (HTTPS only).
|
||
public var allowRemoteEndpoint: Bool
|
||
/// The selected Hy-MT3 model tag.
|
||
public var model: String
|
||
/// The optional Fast model tag.
|
||
public var fastModel: String?
|
||
/// The selected target BCP-47 code.
|
||
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
|
||
/// Up to three recent target codes, most recent first.
|
||
public var recentTargetLanguages: [String]
|
||
/// The double-copy window in milliseconds (300–1000).
|
||
public var doubleCopyWindowMs: Int
|
||
/// The Latin/Cyrillic/Greek chunk limit.
|
||
public var maxCharactersLatin: Int
|
||
/// The dense-script chunk limit.
|
||
public var maxCharactersCJK: Int
|
||
/// `num_ctx`.
|
||
public var numCtx: Int
|
||
/// `num_predict`.
|
||
public var numPredict: Int
|
||
/// `temperature`.
|
||
public var temperature: Double
|
||
/// `top_p`.
|
||
public var topP: Double
|
||
/// `top_k`.
|
||
public var topK: Int
|
||
/// `repeat_penalty`.
|
||
public var repeatPenalty: Double
|
||
/// `keep_alive` value: `5m`, `30m`, `1h` or `0`.
|
||
public var keepModelLoaded: String
|
||
/// Warm the model after launch (loopback only).
|
||
public var warmUpOnLaunch: Bool
|
||
/// Prompt policy; `defaultOnly` in v1.
|
||
public var promptVariantPolicy: PromptVariantPolicy
|
||
/// Always false; never copy automatically.
|
||
public var autoCopy: Bool
|
||
/// Show the source preview in the panel.
|
||
public var showSourcePreview: Bool
|
||
/// Translation text size in points (12–28).
|
||
public var translationFontSize: Int
|
||
/// Render Markdown formatting in the translation panel.
|
||
public var renderMarkdown: Bool
|
||
/// Make the panel key when shown so Esc and the shortcuts work without a click.
|
||
public var closeWithEscape: Bool
|
||
/// Reflect the login-item setting.
|
||
public var launchAtLogin: Bool
|
||
/// Keep the last translation in memory for the panel.
|
||
public var keepRecentTranslationInMemory: Bool
|
||
/// Whether first-run onboarding has been completed.
|
||
public var hasCompletedOnboarding: Bool
|
||
/// The settings schema version.
|
||
public var settingsVersion: Int
|
||
|
||
/// Creates the defaults. The system language becomes the target when supported.
|
||
public init() {
|
||
let systemCode = Locale.preferredLanguages.first.flatMap { HyMT3Languages.resolve($0)?.code }
|
||
endpoint = Self.defaultEndpoint
|
||
allowRemoteEndpoint = false
|
||
model = HyMT3ModelPreset.defaultModel
|
||
fastModel = HyMT3ModelPreset.fastModel
|
||
targetLanguage = systemCode ?? HyMT3Languages.english.code
|
||
autoSwitchTarget = true
|
||
fallbackTargetLanguage = targetLanguage == HyMT3Languages.english.code
|
||
? HyMT3Languages.german.code
|
||
: HyMT3Languages.english.code
|
||
recentTargetLanguages = []
|
||
doubleCopyWindowMs = 500
|
||
maxCharactersLatin = 4000
|
||
maxCharactersCJK = 2000
|
||
numCtx = 8192
|
||
numPredict = 4096
|
||
temperature = 0.7
|
||
topP = 0.6
|
||
topK = 20
|
||
repeatPenalty = 1.05
|
||
keepModelLoaded = HyMT3ModelPreset.defaultKeepAlive
|
||
warmUpOnLaunch = true
|
||
promptVariantPolicy = .defaultOnly
|
||
autoCopy = false
|
||
showSourcePreview = true
|
||
translationFontSize = 17
|
||
renderMarkdown = true
|
||
closeWithEscape = true
|
||
launchAtLogin = false
|
||
keepRecentTranslationInMemory = true
|
||
hasCompletedOnboarding = false
|
||
settingsVersion = Self.currentVersion
|
||
}
|
||
|
||
/// The target language value, always a catalogue entry.
|
||
public var targetLanguageModel: ModelLanguage {
|
||
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)
|
||
}
|
||
|
||
/// Validates the configured endpoint against the remote policy.
|
||
public func validatedEndpoint() throws -> URL {
|
||
try EndpointPolicy.validate(endpoint, allowRemote: allowRemoteEndpoint)
|
||
}
|
||
|
||
/// 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)
|
||
recentTargetLanguages = Array(recentTargetLanguages.prefix(3))
|
||
}
|
||
|
||
/// 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)
|
||
doubleCopyWindowMs = Self.clamp(doubleCopyWindowMs, to: 300 ... 1000)
|
||
maxCharactersLatin = Self.clamp(maxCharactersLatin, to: 500 ... 10000)
|
||
maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 5000)
|
||
numCtx = Self.clamp(numCtx, to: 1024 ... 32768)
|
||
numPredict = Self.clamp(numPredict, to: 1 ... 8192)
|
||
temperature = min(max(temperature, 0), 2)
|
||
topP = min(max(topP, 0), 1)
|
||
topK = Self.clamp(topK, to: 1 ... 100)
|
||
repeatPenalty = min(max(repeatPenalty, 0.5), 2)
|
||
translationFontSize = Self.clamp(translationFontSize, to: 12 ... 28)
|
||
if !["5m", "30m", "1h", "0"].contains(keepModelLoaded) {
|
||
keepModelLoaded = HyMT3ModelPreset.defaultKeepAlive
|
||
}
|
||
autoCopy = false
|
||
}
|
||
|
||
/// The documented sampling values as an options value.
|
||
public var samplingOptions: SamplingOptions {
|
||
SamplingOptions(
|
||
temperature: temperature,
|
||
topP: topP,
|
||
topK: topK,
|
||
repeatPenalty: repeatPenalty,
|
||
numPredict: numPredict,
|
||
numCtx: numCtx
|
||
)
|
||
}
|
||
|
||
/// The chunker limits.
|
||
public var chunker: Chunker {
|
||
Chunker(latinLimit: maxCharactersLatin, denseLimit: maxCharactersCJK)
|
||
}
|
||
|
||
struct DecodedLimits {
|
||
let window: Int
|
||
let latin: Int
|
||
let cjk: Int
|
||
let numCtx: Int
|
||
let numPredict: Int
|
||
let fontSize: Int
|
||
}
|
||
|
||
struct DecodedSampling {
|
||
let temperature: Double
|
||
let topP: Double
|
||
let topK: Int
|
||
let repeatPenalty: Double
|
||
}
|
||
|
||
static func decodeLimits(
|
||
from container: KeyedDecodingContainer<CodingKeys>,
|
||
defaults: AppSettings
|
||
) throws -> DecodedLimits {
|
||
try DecodedLimits(
|
||
window: clamp(
|
||
container.decodeIfPresent(Int.self, forKey: .doubleCopyWindowMs)
|
||
?? defaults.doubleCopyWindowMs,
|
||
to: 300 ... 1000
|
||
),
|
||
latin: clamp(
|
||
container.decodeIfPresent(Int.self, forKey: .maxCharactersLatin)
|
||
?? defaults.maxCharactersLatin,
|
||
to: 500 ... 10000
|
||
),
|
||
cjk: clamp(
|
||
container.decodeIfPresent(Int.self, forKey: .maxCharactersCJK)
|
||
?? defaults.maxCharactersCJK,
|
||
to: 500 ... 5000
|
||
),
|
||
numCtx: clamp(
|
||
container.decodeIfPresent(Int.self, forKey: .numCtx) ?? defaults.numCtx,
|
||
to: 1024 ... 32768
|
||
),
|
||
numPredict: clamp(
|
||
container.decodeIfPresent(Int.self, forKey: .numPredict) ?? defaults.numPredict,
|
||
to: 1 ... 8192
|
||
),
|
||
fontSize: clamp(
|
||
container.decodeIfPresent(Int.self, forKey: .translationFontSize)
|
||
?? defaults.translationFontSize,
|
||
to: 12 ... 28
|
||
)
|
||
)
|
||
}
|
||
|
||
static func decodeSampling(
|
||
from container: KeyedDecodingContainer<CodingKeys>,
|
||
defaults: AppSettings
|
||
) throws -> DecodedSampling {
|
||
let temperature = try container.decodeIfPresent(Double.self, forKey: .temperature)
|
||
?? defaults.temperature
|
||
let topP = try container.decodeIfPresent(Double.self, forKey: .topP) ?? defaults.topP
|
||
let repeatPenalty = try container.decodeIfPresent(Double.self, forKey: .repeatPenalty)
|
||
?? defaults.repeatPenalty
|
||
return try DecodedSampling(
|
||
temperature: min(max(temperature, 0), 2),
|
||
topP: min(max(topP, 0), 1),
|
||
topK: clamp(
|
||
container.decodeIfPresent(Int.self, forKey: .topK) ?? defaults.topK,
|
||
to: 1 ... 100
|
||
),
|
||
repeatPenalty: min(max(repeatPenalty, 0.5), 2)
|
||
)
|
||
}
|
||
|
||
enum CodingKeys: String, CodingKey {
|
||
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, autoSwitchTarget
|
||
case fallbackTargetLanguage, recentTargetLanguages
|
||
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, numCtx, numPredict
|
||
case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch
|
||
case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, renderMarkdown
|
||
case closeWithEscape, launchAtLogin, keepRecentTranslationInMemory, hasCompletedOnboarding
|
||
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 clamp(_ value: Int, to range: ClosedRange<Int>) -> Int {
|
||
min(max(value, range.lowerBound), range.upperBound)
|
||
}
|
||
}
|