Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a601058f4 | ||
|
|
9f89000b0d | ||
|
|
bd8e3db82d | ||
|
|
940abcc996 | ||
|
|
41f1cea769 | ||
|
|
7c9cece201 | ||
|
|
39ec191348 | ||
|
|
a3e544fbe4 | ||
|
|
d126124f97 | ||
|
|
f8064ac430 | ||
|
|
f466e6dd1c | ||
|
|
40733473c5 | ||
|
|
2cce12ff17 | ||
|
|
0ab5ae78bf | ||
|
|
a78572adc3 | ||
|
|
64078e2f04 | ||
|
|
26b493e7e5 | ||
|
|
7ca5c710ec |
No files matched your search
@@ -2,11 +2,13 @@
|
||||
*.xcodeproj/
|
||||
!*.xcodeproj/project.xcworkspace/xcshareddata/
|
||||
.build/
|
||||
build/
|
||||
DerivedData/
|
||||
xcuserdata/
|
||||
*.xcuserstate
|
||||
.swiftpm/
|
||||
Packages/SprachmittlerKit/.build/
|
||||
build/
|
||||
Packages/SprachmittlerKit/.swiftpm/
|
||||
dist/
|
||||
out/
|
||||
|
||||
@@ -1,19 +1,112 @@
|
||||
import AppKit
|
||||
import Combine
|
||||
import os
|
||||
import SprachmittlerCore
|
||||
|
||||
/// Lifecycle glue: composition root, Services provider, double-copy watcher, termination.
|
||||
/// Lifecycle glue: composition root, Services provider, watcher, panel and windows.
|
||||
@MainActor
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
|
||||
let environment: AppEnvironment
|
||||
private let loggers = Loggers(subsystem: Bundle.main.bundleIdentifier ?? "Sprachmittler")
|
||||
@Published private(set) var menuState = StatusMenuState(
|
||||
targetCode: "",
|
||||
hasTranslation: false,
|
||||
canReplace: false
|
||||
)
|
||||
|
||||
private lazy var onboardingWindow = OnboardingWindowController(
|
||||
model: environment.onboarding,
|
||||
onCopyCommand: { [weak self] text in self?.environment.copyText(text) },
|
||||
onFinished: { [weak self] in
|
||||
self?.environment.settingsDidChange()
|
||||
self?.refreshMenuState()
|
||||
}
|
||||
)
|
||||
|
||||
private lazy var diagnosticsWindow = DiagnosticsWindowController(
|
||||
model: environment.diagnosticsModel,
|
||||
onCopy: { [weak self] text in self?.environment.copyText(text) }
|
||||
)
|
||||
|
||||
override init() {
|
||||
environment = AppEnvironment()
|
||||
super.init()
|
||||
refreshMenuState()
|
||||
}
|
||||
|
||||
func applicationDidFinishLaunching(_ notification: Notification) {
|
||||
// Build AppEnvironment here (composition root): settings, Ollama services, session,
|
||||
// double-copy watcher and panel controller. Start the watcher only after explicit consent.
|
||||
//
|
||||
// The Services provider is wired here once SprachmittlerCapture.ServicesProvider exists:
|
||||
// NSApp.servicesProvider = servicesProvider
|
||||
// NSUpdateDynamicServices()
|
||||
loggers.logger(.session).notice("Sprachmittler launched")
|
||||
environment.onStateChange = { [weak self] in self?.refreshMenuState() }
|
||||
environment.start { [weak self] captured in
|
||||
self?.handle(captured)
|
||||
}
|
||||
NSApp.servicesProvider = environment.servicesProvider
|
||||
NSUpdateDynamicServices()
|
||||
|
||||
if !environment.settingsStore.current().hasCompletedOnboarding {
|
||||
showOnboarding()
|
||||
}
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
// Cancel in-flight translations, stop the pasteboard watcher and close the panel.
|
||||
environment.stop()
|
||||
}
|
||||
|
||||
/// Menu action: translate the current clipboard text.
|
||||
func captureClipboardText() {
|
||||
environment.captureClipboardText()
|
||||
}
|
||||
|
||||
/// Menu action: change the target language.
|
||||
func selectTarget(_ language: TargetLanguage) {
|
||||
environment.selectTarget(language)
|
||||
refreshMenuState()
|
||||
}
|
||||
|
||||
/// Menu action: copy the last translation.
|
||||
func copyLastTranslation() {
|
||||
environment.copyLastTranslation()
|
||||
}
|
||||
|
||||
/// Menu action: replace the last selection with the last translation.
|
||||
func replaceLastTranslation() {
|
||||
environment.replaceLastTranslation()
|
||||
}
|
||||
|
||||
/// Menu action: open setup.
|
||||
func showOnboarding() {
|
||||
onboardingWindow.show()
|
||||
}
|
||||
|
||||
/// Menu action: open diagnostics.
|
||||
func showDiagnostics() {
|
||||
diagnosticsWindow.show()
|
||||
}
|
||||
|
||||
/// Menu action: About and licence notice.
|
||||
func showAbout() {
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
NSApp.orderFrontStandardAboutPanel(options: [
|
||||
.applicationName: "Sprachmittler",
|
||||
.credits: NSAttributedString(
|
||||
string: "Local translation with Hy-MT3. No text leaves this Mac.\n"
|
||||
+ "Hy-MT3 is Apache-2.0 per the model card; Sprachmittler bundles no weights."
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
private func handle(_ captured: CapturedText) {
|
||||
loggers.logger(.capture).notice(
|
||||
"Captured \(captured.text.count) characters from \(captured.source.rawValue, privacy: .public)"
|
||||
)
|
||||
refreshMenuState()
|
||||
}
|
||||
|
||||
private func refreshMenuState() {
|
||||
menuState = StatusMenuState(
|
||||
targetCode: environment.currentTarget.code,
|
||||
hasTranslation: environment.lastTranslation != nil,
|
||||
canReplace: environment.canReplaceLast
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
import SprachmittlerCapture
|
||||
import SprachmittlerCore
|
||||
|
||||
/// The app composition root: settings, Ollama clients, session, panel, capture and diagnostics.
|
||||
@MainActor
|
||||
final class AppEnvironment {
|
||||
let settingsStore: SettingsStore
|
||||
let pasteboard: SystemPasteboard
|
||||
var watcher: PasteboardWatcher
|
||||
let accessibility: AccessibilityPermission
|
||||
let launchAtLogin: LaunchAtLoginController
|
||||
let diagnostics: DiagnosticsStore
|
||||
let targetProvider: FrontmostTargetProvider
|
||||
let session: TranslationSession
|
||||
let settingsModel: SettingsViewModel
|
||||
let onboarding: OnboardingViewModel
|
||||
let diagnosticsModel: DiagnosticsViewModel
|
||||
|
||||
private(set) var lastCaptured: CapturedText?
|
||||
private(set) var lastTranslation: String?
|
||||
private(set) var lastWarnings: [TranslationWarning] = []
|
||||
private(set) var insertionTarget: InsertionTarget?
|
||||
private var insertionTargetGeneration = 0
|
||||
private(set) var lastCaptureFailure: CaptureValidation?
|
||||
var onCapture: ((CapturedText) -> Void)?
|
||||
var onStateChange: (() -> Void)?
|
||||
|
||||
private var watcherEventSink: (@MainActor (PasteboardWatcherEvent) -> Void)?
|
||||
private var watcherWindowMs: Int
|
||||
|
||||
/// The Services provider, created lazily so it can capture `self` weakly.
|
||||
lazy var servicesProvider = ServicesProvider { [weak self] captured in
|
||||
Task { @MainActor in
|
||||
self?.deliver(captured)
|
||||
}
|
||||
}
|
||||
|
||||
/// The insertion coordinator, created on first use.
|
||||
lazy var insertionCoordinator = InsertionCoordinator(
|
||||
pasteboard: pasteboard,
|
||||
accessibility: AXTextEditor(),
|
||||
ownWrite: { [weak self] in self?.watcher.noteOwnWrite(at: Date()) },
|
||||
frontmostPID: { NSWorkspace.shared.frontmostApplication?.processIdentifier ?? 0 }
|
||||
)
|
||||
|
||||
/// The panel model, created on first use.
|
||||
lazy var panelViewModel: PanelViewModel = {
|
||||
let model = PanelViewModel(
|
||||
session: session,
|
||||
configuration: configuration(for: settingsStore.current()),
|
||||
copy: { [weak self] text in
|
||||
self?.copyToPasteboard(text, remember: self?.panelViewModel.translation == text)
|
||||
},
|
||||
replace: { [weak self] in
|
||||
guard let self else { return .failed(.cancelled) }
|
||||
return await performReplace()
|
||||
},
|
||||
onCloseRequest: { [weak self] in self?.panelController.close() },
|
||||
eventObserver: { [weak self] event in self?.observe(event) },
|
||||
onTargetChanged: { [weak self] language in self?.applyTarget(language) }
|
||||
)
|
||||
model.startObserving()
|
||||
return model
|
||||
}()
|
||||
|
||||
/// The panel window controller, created on first use.
|
||||
lazy var panelController = PanelController(viewModel: panelViewModel)
|
||||
|
||||
/// Creates the environment.
|
||||
init() {
|
||||
let store = SettingsStore()
|
||||
let pasteboard = SystemPasteboard()
|
||||
let access = AccessibilityPermission()
|
||||
let launch = LaunchAtLoginController()
|
||||
let diagnostics = DiagnosticsStore()
|
||||
let windowMs = store.current().doubleCopyWindowMs
|
||||
|
||||
settingsStore = store
|
||||
self.pasteboard = pasteboard
|
||||
accessibility = access
|
||||
targetProvider = FrontmostTargetProvider()
|
||||
launchAtLogin = launch
|
||||
self.diagnostics = diagnostics
|
||||
watcherWindowMs = windowMs
|
||||
watcher = PasteboardWatcher(
|
||||
pasteboard: pasteboard,
|
||||
configuration: DoubleCopyDetector.Configuration(
|
||||
window: Double(windowMs) / 1000
|
||||
),
|
||||
limits: store.current().captureLimits
|
||||
)
|
||||
|
||||
let factoryStore = store
|
||||
session = TranslationSession(pipelineFactory: {
|
||||
try AppOllama.makePipeline(settings: factoryStore.current())
|
||||
})
|
||||
|
||||
let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog = { settings in
|
||||
try AppOllama.makeCatalog(settings: settings)
|
||||
}
|
||||
settingsModel = SettingsViewModel(
|
||||
store: store,
|
||||
catalogProvider: catalogProvider,
|
||||
launchAtLogin: launch
|
||||
)
|
||||
onboarding = OnboardingViewModel(
|
||||
settingsStore: store,
|
||||
catalogProvider: catalogProvider,
|
||||
accessibility: access
|
||||
)
|
||||
diagnosticsModel = DiagnosticsViewModel(
|
||||
store: diagnostics,
|
||||
catalogProvider: catalogProvider,
|
||||
settingsProvider: { factoryStore.current() }
|
||||
)
|
||||
}
|
||||
|
||||
/// Starts the watcher and optional warm-up.
|
||||
func start(onCapture: @escaping (CapturedText) -> Void) {
|
||||
self.onCapture = onCapture
|
||||
let sink: @MainActor (PasteboardWatcherEvent) -> Void = { [weak self] event in
|
||||
self?.handle(event)
|
||||
}
|
||||
watcherEventSink = sink
|
||||
watcher.start(onEvent: sink)
|
||||
warmUpIfNeeded()
|
||||
}
|
||||
|
||||
/// Stops the watcher, panel and event stream.
|
||||
func stop() {
|
||||
watcher.stop()
|
||||
panelViewModel.shutdown()
|
||||
Task { await panelViewModel.close() }
|
||||
lastCaptured = nil
|
||||
lastTranslation = nil
|
||||
lastWarnings = []
|
||||
}
|
||||
|
||||
/// Reads the clipboard once for the menu-bar item.
|
||||
func captureClipboardText() {
|
||||
guard !pasteboard.containsOwnWriteMarkers(),
|
||||
let text = pasteboard.string(),
|
||||
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
else {
|
||||
return
|
||||
}
|
||||
deliver(CapturedText(text: text, capturedAt: Date(), source: .menu))
|
||||
}
|
||||
|
||||
/// Copies arbitrary text with the app's own-write markers.
|
||||
func copyText(_ text: String) {
|
||||
copyToPasteboard(text, remember: false)
|
||||
}
|
||||
|
||||
/// Copies the last translation for the status menu.
|
||||
func copyLastTranslation() {
|
||||
guard let lastTranslation else { return }
|
||||
copyToPasteboard(lastTranslation, remember: false)
|
||||
}
|
||||
|
||||
/// True when the last translation can safely be inserted.
|
||||
var canReplaceLast: Bool {
|
||||
lastTranslation != nil
|
||||
&& lastCaptured != nil
|
||||
&& insertionTarget != nil
|
||||
&& !InsertionPolicy.isBlocked(by: lastWarnings)
|
||||
}
|
||||
|
||||
/// Replaces the last selection from the status menu.
|
||||
func replaceLastTranslation() {
|
||||
guard let captured = lastCaptured,
|
||||
let translation = lastTranslation,
|
||||
let target = insertionTarget
|
||||
else {
|
||||
return
|
||||
}
|
||||
Task {
|
||||
do {
|
||||
_ = try await insertionCoordinator.replace(
|
||||
selection: captured,
|
||||
with: translation,
|
||||
target: target
|
||||
)
|
||||
} catch let error as SprachmittlerError {
|
||||
showPanelError(error, source: captured)
|
||||
} catch {
|
||||
showPanelError(.server(status: 0, message: "Insertion failed"), source: captured)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The current target code, for the status menu.
|
||||
var currentTarget: ModelLanguage {
|
||||
settingsStore.current().targetLanguageModel
|
||||
}
|
||||
|
||||
/// Changes the target from the status menu and retranslates the open panel.
|
||||
func selectTarget(_ language: ModelLanguage) {
|
||||
try? settingsStore.update { $0.noteTarget(language) }
|
||||
applySettings()
|
||||
}
|
||||
|
||||
/// Called after Settings or Onboarding saves. Updates the panel and watcher.
|
||||
func settingsDidChange() {
|
||||
applySettings()
|
||||
settingsModel.reload()
|
||||
}
|
||||
|
||||
private func configuration(for settings: AppSettings) -> PanelConfiguration {
|
||||
PanelConfiguration(
|
||||
target: settings.targetLanguageModel,
|
||||
model: settings.model,
|
||||
keepAlive: settings.keepModelLoaded,
|
||||
sampling: settings.samplingOptions,
|
||||
showSourcePreview: settings.showSourcePreview,
|
||||
translationFontSize: settings.translationFontSize,
|
||||
renderMarkdown: settings.renderMarkdown,
|
||||
closeWithEscape: settings.closeWithEscape,
|
||||
languageRoutes: settings.languageRoutes,
|
||||
recentTargets: settings.recentTargets,
|
||||
captureLimits: settings.captureLimits
|
||||
)
|
||||
}
|
||||
|
||||
private func applySettings() {
|
||||
let settings = settingsStore.current()
|
||||
let previousTarget = panelViewModel.configuration.target.code
|
||||
let previousRoutes = panelViewModel.configuration.languageRoutes
|
||||
panelViewModel.updateConfiguration(configuration(for: settings))
|
||||
watcher.limits = settings.captureLimits
|
||||
if settings.doubleCopyWindowMs != watcherWindowMs {
|
||||
watcherWindowMs = settings.doubleCopyWindowMs
|
||||
restartWatcher()
|
||||
}
|
||||
let targetChanged = previousTarget != settings.targetLanguage && panelViewModel.source != nil
|
||||
let routesChanged = previousRoutes != settings.languageRoutes && panelViewModel.source != nil
|
||||
if targetChanged || routesChanged {
|
||||
Task { await panelViewModel.retranslate() }
|
||||
}
|
||||
onStateChange?()
|
||||
}
|
||||
|
||||
private func applyTarget(_ language: ModelLanguage) {
|
||||
try? settingsStore.update { $0.noteTarget(language) }
|
||||
applySettings()
|
||||
}
|
||||
|
||||
private func restartWatcher() {
|
||||
watcher.stop()
|
||||
watcher = PasteboardWatcher(
|
||||
pasteboard: pasteboard,
|
||||
configuration: DoubleCopyDetector.Configuration(
|
||||
window: Double(watcherWindowMs) / 1000
|
||||
),
|
||||
limits: settingsStore.current().captureLimits
|
||||
)
|
||||
if let sink = watcherEventSink {
|
||||
watcher.start(onEvent: sink)
|
||||
}
|
||||
}
|
||||
|
||||
private func handle(_ event: PasteboardWatcherEvent) {
|
||||
switch event {
|
||||
case let .captured(captured):
|
||||
deliver(captured)
|
||||
case let .textTooLong(characters, limit):
|
||||
let error = SprachmittlerError.textTooLong(characters: characters, limit: limit)
|
||||
lastTranslation = nil
|
||||
lastWarnings = []
|
||||
onStateChange?()
|
||||
lastCaptureFailure = .textTooLong(characters: characters, limit: limit)
|
||||
showPanelError(error)
|
||||
case .noText, .ignoredOwnWrite:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func deliver(_ captured: CapturedText) {
|
||||
// A new capture invalidates the previous result for the status-menu actions.
|
||||
lastTranslation = nil
|
||||
lastWarnings = []
|
||||
onStateChange?()
|
||||
|
||||
switch CapturePolicy.validate(captured.text, limits: settingsStore.current().captureLimits) {
|
||||
case .valid:
|
||||
lastCaptureFailure = nil
|
||||
case .empty:
|
||||
lastCaptureFailure = .empty
|
||||
return
|
||||
case let .textTooLong(characters, limit):
|
||||
lastCaptureFailure = .textTooLong(characters: characters, limit: limit)
|
||||
showPanelError(
|
||||
.textTooLong(characters: characters, limit: limit),
|
||||
source: captured
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
lastCaptured = captured
|
||||
captureInsertionTarget()
|
||||
onCapture?(captured)
|
||||
panelViewModel.updateConfiguration(configuration(for: settingsStore.current()))
|
||||
panelViewModel.prepare(captured)
|
||||
panelController.show()
|
||||
Task { await panelViewModel.begin(captured) }
|
||||
}
|
||||
}
|
||||
|
||||
extension AppEnvironment {
|
||||
private func performReplace() async -> InsertionOutcome {
|
||||
guard let captured = lastCaptured,
|
||||
let target = insertionTarget,
|
||||
!panelViewModel.translation.isEmpty
|
||||
else {
|
||||
return .failed(.insertionTargetChanged)
|
||||
}
|
||||
if let warning = panelViewModel.blockingWarnings.first {
|
||||
return .failed(warning.insertionError)
|
||||
}
|
||||
do {
|
||||
if let selected = target.selectedText {
|
||||
let frontmost = NSWorkspace.shared.frontmostApplication?.processIdentifier ?? 0
|
||||
try InsertionPolicy.verify(
|
||||
frontmostPID: frontmost,
|
||||
target: target,
|
||||
selectedText: selected,
|
||||
source: captured.text
|
||||
)
|
||||
}
|
||||
return try await insertionCoordinator.replace(
|
||||
selection: captured,
|
||||
with: panelViewModel.translation,
|
||||
target: target
|
||||
)
|
||||
} catch let error as SprachmittlerError {
|
||||
return .failed(error)
|
||||
} catch is CancellationError {
|
||||
return .failed(.cancelled)
|
||||
} catch {
|
||||
return .failed(.server(status: 0, message: "Insertion failed"))
|
||||
}
|
||||
}
|
||||
|
||||
private func captureInsertionTarget() {
|
||||
guard let base = targetProvider.captureTarget() else {
|
||||
insertionTarget = nil
|
||||
return
|
||||
}
|
||||
insertionTarget = base
|
||||
Task {
|
||||
let editor = AXTextEditor()
|
||||
guard await editor.isTrusted(),
|
||||
let selected = await editor.selectedText(pid: base.pid),
|
||||
insertionTarget?.pid == base.pid
|
||||
else {
|
||||
return
|
||||
}
|
||||
insertionTarget = InsertionTarget(
|
||||
pid: base.pid,
|
||||
bundleID: base.bundleID,
|
||||
selectedText: selected,
|
||||
capturedAt: base.capturedAt
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func showPanelError(_ error: SprachmittlerError, source: CapturedText? = nil) {
|
||||
panelViewModel.updateConfiguration(configuration(for: settingsStore.current()))
|
||||
panelViewModel.showError(error, source: source)
|
||||
panelController.show()
|
||||
}
|
||||
|
||||
private func copyToPasteboard(_ text: String, remember: Bool) {
|
||||
pasteboard.write(text)
|
||||
watcher.noteOwnWrite(at: Date())
|
||||
let shouldRemember = remember
|
||||
&& panelViewModel.phase == .ready
|
||||
&& settingsStore.current().keepRecentTranslationInMemory
|
||||
if shouldRemember {
|
||||
lastTranslation = text
|
||||
}
|
||||
onStateChange?()
|
||||
}
|
||||
|
||||
private func observe(_ event: TranslationSessionEvent) {
|
||||
switch event {
|
||||
case let .finished(_, result):
|
||||
lastWarnings = result.warnings
|
||||
if settingsStore.current().keepRecentTranslationInMemory {
|
||||
lastTranslation = result.translation
|
||||
} else {
|
||||
lastTranslation = nil
|
||||
}
|
||||
let detail = result.warnings.map(\.code).joined(separator: ",")
|
||||
let duration = result.timing.totalMs
|
||||
Task {
|
||||
await diagnostics.record(
|
||||
kind: "translation",
|
||||
durationMs: duration,
|
||||
detail: detail.isEmpty ? nil : detail
|
||||
)
|
||||
}
|
||||
onStateChange?()
|
||||
case let .failed(_, error):
|
||||
Task {
|
||||
await diagnostics.record(kind: "error", detail: error.diagnosticCode)
|
||||
}
|
||||
onStateChange?()
|
||||
case .started, .chunkStarted, .delta, .cancelled:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func warmUpIfNeeded() {
|
||||
let settings = settingsStore.current()
|
||||
guard settings.warmUpOnLaunch else { return }
|
||||
Task {
|
||||
do {
|
||||
try await AppOllama.warmUp(settings: settings)
|
||||
await diagnostics.record(kind: "warmup")
|
||||
} catch {
|
||||
await diagnostics.record(kind: "warmupFailed", detail: "unavailable")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import AppKit
|
||||
import SprachmittlerCore
|
||||
import SwiftUI
|
||||
|
||||
/// The diagnostics window. It shows no text, only versions, digests, timings and error kinds.
|
||||
struct DiagnosticsView: View {
|
||||
@Bindable var model: DiagnosticsViewModel
|
||||
let onCopy: @MainActor (String) -> Void
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Text(String(localized: "Diagnostics"))
|
||||
.font(.title2.bold())
|
||||
Spacer()
|
||||
Button(String(localized: "Refresh")) {
|
||||
Task { await model.refresh() }
|
||||
}
|
||||
.disabled(model.isRefreshing)
|
||||
Button(String(localized: "Copy report")) {
|
||||
onCopy(model.report())
|
||||
}
|
||||
Button(String(localized: "Clear")) {
|
||||
Task { await model.clear() }
|
||||
}
|
||||
}
|
||||
|
||||
GroupBox(String(localized: "Ollama")) {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text("Version: \(model.serverVersion ?? String(localized: "unknown"))")
|
||||
Text(
|
||||
"Models: "
|
||||
+ model.models.map { "\($0.name) [\($0.digest.prefix(12))]" }
|
||||
.joined(separator: ", ")
|
||||
)
|
||||
if let error = model.error {
|
||||
Text(error).foregroundStyle(.red)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
Text(String(localized: "Last 50 events"))
|
||||
.font(.headline)
|
||||
List {
|
||||
ForEach(Array(model.events.enumerated()), id: \.offset) { _, event in
|
||||
HStack {
|
||||
Text(event.kind)
|
||||
Spacer()
|
||||
if let duration = event.durationMs {
|
||||
Text("\(duration) ms").foregroundStyle(.secondary)
|
||||
}
|
||||
if let detail = event.detail {
|
||||
Text(detail).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.font(.callout)
|
||||
}
|
||||
}
|
||||
.frame(minHeight: 220)
|
||||
}
|
||||
.padding(20)
|
||||
.frame(width: 620, height: 520)
|
||||
.task {
|
||||
await model.refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The diagnostics window controller.
|
||||
@MainActor
|
||||
final class DiagnosticsWindowController {
|
||||
private let window: NSWindow
|
||||
|
||||
init(model: DiagnosticsViewModel, onCopy: @escaping @MainActor (String) -> Void) {
|
||||
let window = NSWindow(
|
||||
contentRect: NSRect(x: 0, y: 0, width: 620, height: 520),
|
||||
styleMask: [.titled, .closable, .resizable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
self.window = window
|
||||
window.title = String(localized: "Sprachmittler Diagnostics")
|
||||
window.isReleasedWhenClosed = false
|
||||
window.contentViewController = NSHostingController(
|
||||
rootView: DiagnosticsView(model: model, onCopy: onCopy)
|
||||
)
|
||||
window.center()
|
||||
}
|
||||
|
||||
func show() {
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,15 @@
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleIconName</key>
|
||||
<string>AppIcon</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleLocalizations</key>
|
||||
<array>
|
||||
<string>en</string>
|
||||
<string>de</string>
|
||||
</array>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import Foundation
|
||||
import ServiceManagement
|
||||
import SprachmittlerCore
|
||||
|
||||
/// The production launch-at-login controller backed by `SMAppService.mainApp`.
|
||||
@MainActor
|
||||
final class LaunchAtLoginController: LaunchAtLoginControlling {
|
||||
var isEnabled: Bool {
|
||||
SMAppService.mainApp.status == .enabled
|
||||
}
|
||||
|
||||
func setEnabled(_ enabled: Bool) throws {
|
||||
if enabled {
|
||||
if SMAppService.mainApp.status != .enabled {
|
||||
try SMAppService.mainApp.register()
|
||||
}
|
||||
} else if SMAppService.mainApp.status == .enabled {
|
||||
try SMAppService.mainApp.unregister()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import Foundation
|
||||
|
||||
/// The small observable state the status menu needs.
|
||||
struct StatusMenuState: Equatable {
|
||||
var targetCode: String
|
||||
var hasTranslation: Bool
|
||||
var canReplace: Bool
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import AppKit
|
||||
import SprachmittlerCore
|
||||
import SwiftUI
|
||||
|
||||
/// The menu-bar status menu.
|
||||
struct StatusMenuView: View {
|
||||
@ObservedObject var delegate: AppDelegate
|
||||
|
||||
var body: some View {
|
||||
Button(String(localized: "Translate Clipboard Text")) {
|
||||
delegate.captureClipboardText()
|
||||
}
|
||||
|
||||
Menu(String(localized: "Target Language")) {
|
||||
ForEach(LanguageCatalogue.common) { language in
|
||||
Button {
|
||||
delegate.selectTarget(language)
|
||||
} label: {
|
||||
HStack {
|
||||
Text(language.localizedDisplayName)
|
||||
if language.code == delegate.menuState.targetCode {
|
||||
Image(systemName: "checkmark")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Divider()
|
||||
SettingsLink {
|
||||
Text(String(localized: "More languages…"))
|
||||
}
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
Button(String(localized: "Copy Last Translation")) {
|
||||
delegate.copyLastTranslation()
|
||||
}
|
||||
.disabled(!delegate.menuState.hasTranslation)
|
||||
|
||||
Button(String(localized: "Replace Last Translation")) {
|
||||
delegate.replaceLastTranslation()
|
||||
}
|
||||
.disabled(!delegate.menuState.canReplace)
|
||||
|
||||
Divider()
|
||||
|
||||
Button(String(localized: "Set up Sprachmittler…")) {
|
||||
delegate.showOnboarding()
|
||||
}
|
||||
Button(String(localized: "Diagnostics…")) {
|
||||
delegate.showDiagnostics()
|
||||
}
|
||||
Button(String(localized: "About Sprachmittler")) {
|
||||
delegate.showAbout()
|
||||
}
|
||||
|
||||
SettingsLink {
|
||||
Text(String(localized: "Settings…"))
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
Button(String(localized: "Quit Sprachmittler")) {
|
||||
NSApplication.shared.terminate(nil)
|
||||
}
|
||||
.keyboardShortcut("q")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import AppKit
|
||||
import SprachmittlerCore
|
||||
import SwiftUI
|
||||
|
||||
/// The first-run setup window.
|
||||
struct OnboardingView: View {
|
||||
@Bindable var model: OnboardingViewModel
|
||||
let onCopyCommand: @MainActor (String) -> Void
|
||||
let onFinished: @MainActor () -> Void
|
||||
|
||||
@State private var showLanguagePicker = false
|
||||
@State private var errorMessage: String?
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(String(localized: "Set up Sprachmittler"))
|
||||
.font(.title2.bold())
|
||||
Text(String(localized: "Local translation with Ollama. Nothing leaves this Mac."))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
checkRow(
|
||||
title: String(localized: "Ollama"),
|
||||
state: model.ollama,
|
||||
detail: ollamaDetail
|
||||
) {
|
||||
Button(String(localized: "Check again")) {
|
||||
Task { await model.refresh() }
|
||||
}
|
||||
.controlSize(.small)
|
||||
if case .failed = model.ollama, let url = URL(string: "https://ollama.com/download") {
|
||||
Link(String(localized: "Download Ollama"), destination: url)
|
||||
.controlSize(.small)
|
||||
}
|
||||
}
|
||||
|
||||
checkRow(
|
||||
title: String(localized: "Hy-MT3 model"),
|
||||
state: model.model,
|
||||
detail: modelDetail
|
||||
) {
|
||||
Button(String(localized: "Refresh")) {
|
||||
Task { await model.refresh() }
|
||||
}
|
||||
.controlSize(.small)
|
||||
if case .failed = model.model {
|
||||
Button(String(localized: "Copy pull command")) {
|
||||
onCopyCommand(model.pullCommand)
|
||||
}
|
||||
.controlSize(.small)
|
||||
}
|
||||
}
|
||||
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text(String(localized: "Target language"))
|
||||
.font(.headline)
|
||||
Button {
|
||||
showLanguagePicker.toggle()
|
||||
} label: {
|
||||
HStack {
|
||||
Text(model.target.localizedDisplayName)
|
||||
Image(systemName: "chevron.up.chevron.down")
|
||||
.font(.caption)
|
||||
}
|
||||
}
|
||||
.popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) {
|
||||
LanguagePickerView(
|
||||
selection: Binding(
|
||||
get: { model.target },
|
||||
set: { model.setTarget($0) }
|
||||
)
|
||||
)
|
||||
}
|
||||
.accessibilityLabel(String(localized: "Target language"))
|
||||
}
|
||||
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text(String(localized: "Accessibility (optional)"))
|
||||
.font(.headline)
|
||||
Text(String(localized: "Only Replace needs it. Double copy, translation and Copy work without it."))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
HStack {
|
||||
if model.accessibilityTrusted {
|
||||
Label(String(localized: "Granted"), systemImage: "checkmark.circle.fill")
|
||||
.foregroundStyle(.green)
|
||||
} else {
|
||||
Button(String(localized: "Enable Accessibility")) {
|
||||
model.requestAccessibility()
|
||||
}
|
||||
Button(String(localized: "Open System Settings")) {
|
||||
model.openAccessibilitySettings()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let errorMessage {
|
||||
Text(errorMessage)
|
||||
.font(.callout)
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
HStack {
|
||||
Button(String(localized: "Check again")) {
|
||||
Task { await model.refresh() }
|
||||
}
|
||||
Spacer()
|
||||
Button(String(localized: "Done")) {
|
||||
do {
|
||||
try model.complete()
|
||||
onFinished()
|
||||
} catch {
|
||||
errorMessage = String(localized: "Setup could not be saved.")
|
||||
}
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
.buttonStyle(.borderedProminent)
|
||||
.disabled(!model.canFinish)
|
||||
}
|
||||
}
|
||||
.padding(24)
|
||||
.frame(width: 540, height: 560)
|
||||
.task {
|
||||
await model.refresh()
|
||||
}
|
||||
}
|
||||
|
||||
private var ollamaDetail: String? {
|
||||
switch model.ollama {
|
||||
case let .ok(version): String(localized: "Running, version \(version)")
|
||||
case let .failed(message): message
|
||||
case .checking: String(localized: "Checking…")
|
||||
case .idle: nil
|
||||
}
|
||||
}
|
||||
|
||||
private var modelDetail: String? {
|
||||
switch model.model {
|
||||
case let .ok(tags): tags
|
||||
case let .failed(message): message
|
||||
case .checking: String(localized: "Checking…")
|
||||
case .idle: nil
|
||||
}
|
||||
}
|
||||
|
||||
private func checkRow(
|
||||
title: String,
|
||||
state: OnboardingCheck,
|
||||
detail: String?,
|
||||
@ViewBuilder actions: () -> some View
|
||||
) -> some View {
|
||||
HStack(alignment: .top, spacing: 10) {
|
||||
Image(systemName: icon(for: state))
|
||||
.foregroundStyle(color(for: state))
|
||||
.font(.title3)
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(title).font(.headline)
|
||||
if let detail {
|
||||
Text(detail)
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
HStack(spacing: 8) {
|
||||
actions()
|
||||
}
|
||||
}
|
||||
.padding(10)
|
||||
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 10))
|
||||
}
|
||||
|
||||
private func icon(for state: OnboardingCheck) -> String {
|
||||
switch state {
|
||||
case .ok: "checkmark.circle.fill"
|
||||
case .failed: "xmark.octagon.fill"
|
||||
case .checking: "clock"
|
||||
case .idle: "circle"
|
||||
}
|
||||
}
|
||||
|
||||
private func color(for state: OnboardingCheck) -> Color {
|
||||
switch state {
|
||||
case .ok: .green
|
||||
case .failed: .red
|
||||
case .checking: .secondary
|
||||
case .idle: .secondary
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The onboarding window controller.
|
||||
@MainActor
|
||||
final class OnboardingWindowController {
|
||||
private let window: NSWindow
|
||||
|
||||
init(
|
||||
model: OnboardingViewModel,
|
||||
onCopyCommand: @escaping @MainActor (String) -> Void,
|
||||
onFinished: @escaping @MainActor () -> Void
|
||||
) {
|
||||
let window = NSWindow(
|
||||
contentRect: NSRect(x: 0, y: 0, width: 540, height: 560),
|
||||
styleMask: [.titled, .closable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
self.window = window
|
||||
window.title = String(localized: "Set up Sprachmittler")
|
||||
window.isReleasedWhenClosed = false
|
||||
window.contentViewController = NSHostingController(
|
||||
rootView: OnboardingView(
|
||||
model: model,
|
||||
onCopyCommand: onCopyCommand,
|
||||
onFinished: { [weak window] in
|
||||
window?.close()
|
||||
onFinished()
|
||||
}
|
||||
)
|
||||
)
|
||||
window.center()
|
||||
}
|
||||
|
||||
func show() {
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import SprachmittlerCore
|
||||
import SwiftUI
|
||||
|
||||
/// A searchable language list used by the panel and Settings.
|
||||
struct LanguagePickerView: View {
|
||||
@Binding var selection: ModelLanguage
|
||||
var recent: [ModelLanguage] = []
|
||||
var excluding: String?
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var query = ""
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
TextField(String(localized: "Search languages"), text: $query)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.accessibilityLabel(String(localized: "Search languages"))
|
||||
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 2) {
|
||||
ForEach(filtered) { language in
|
||||
Button {
|
||||
selection = language
|
||||
dismiss()
|
||||
} label: {
|
||||
HStack {
|
||||
Text(language.localizedDisplayName)
|
||||
Spacer()
|
||||
if language.code == selection.code {
|
||||
Image(systemName: "checkmark")
|
||||
}
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.padding(.vertical, 4)
|
||||
.padding(.horizontal, 6)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.frame(width: 320, height: 380)
|
||||
}
|
||||
|
||||
private var filtered: [ModelLanguage] {
|
||||
let all = LanguageCatalogue.all.sorted {
|
||||
$0.localizedDisplayName.localizedCaseInsensitiveCompare($1.localizedDisplayName) == .orderedAscending
|
||||
}
|
||||
let available = all.filter { language in
|
||||
guard let excluding else { return true }
|
||||
return language.code.caseInsensitiveCompare(excluding) != .orderedSame
|
||||
}
|
||||
guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { return available }
|
||||
return available.filter {
|
||||
$0.localizedDisplayName.localizedCaseInsensitiveContains(query)
|
||||
|| $0.modelName.localizedCaseInsensitiveContains(query)
|
||||
|| $0.code.localizedCaseInsensitiveContains(query)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import AppKit
|
||||
import SprachmittlerText
|
||||
import SwiftUI
|
||||
|
||||
/// Renders a translation as formatted Markdown. Copy and Replace still use the raw translation.
|
||||
struct MarkdownTranslationView: View {
|
||||
let markdown: String
|
||||
let fontSize: Int
|
||||
let isRTL: Bool
|
||||
|
||||
private let blocks: [MarkdownBlock]
|
||||
|
||||
init(markdown: String, fontSize: Int, isRTL: Bool) {
|
||||
self.markdown = markdown
|
||||
self.fontSize = fontSize
|
||||
self.isRTL = isRTL
|
||||
blocks = MarkdownPresentation.blocks(in: markdown)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
ForEach(blocks.indices, id: \.self) { index in
|
||||
block(blocks[index])
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.environment(\.layoutDirection, isRTL ? .rightToLeft : .leftToRight)
|
||||
.environment(\.openURL, OpenURLAction { url in
|
||||
guard MarkdownPresentation.isAllowedLink(url) else { return .discarded }
|
||||
NSWorkspace.shared.open(url)
|
||||
return .handled
|
||||
})
|
||||
.accessibilityElement(children: .contain)
|
||||
.accessibilityLabel(String(localized: "Translation"))
|
||||
}
|
||||
|
||||
private var baseSize: CGFloat {
|
||||
CGFloat(fontSize)
|
||||
}
|
||||
|
||||
@ViewBuilder private func block(_ block: MarkdownBlock) -> some View {
|
||||
switch block {
|
||||
case let .paragraph(text):
|
||||
inlineText(text, size: baseSize)
|
||||
case let .heading(level, text):
|
||||
inlineText(text, size: baseSize * headingScale(level), weight: .bold)
|
||||
.accessibilityAddTraits(.isHeader)
|
||||
case let .listItem(ordered, number, indent, text):
|
||||
HStack(alignment: .firstTextBaseline, spacing: 6) {
|
||||
Text(ordered ? "\(number)." : "•")
|
||||
.font(.system(size: baseSize, weight: ordered ? .regular : .bold))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(minWidth: ordered ? 18 : 12, alignment: .trailing)
|
||||
.accessibilityHidden(true)
|
||||
inlineText(text, size: baseSize)
|
||||
}
|
||||
.padding(.leading, CGFloat(indent) * 14)
|
||||
case let .quote(text):
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
Rectangle()
|
||||
.fill(.secondary.opacity(0.35))
|
||||
.frame(width: 3)
|
||||
.accessibilityHidden(true)
|
||||
inlineText(text, size: baseSize)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
case let .codeBlock(_, text):
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
Text(verbatim: text)
|
||||
.font(.system(size: baseSize * 0.95, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
.fixedSize(horizontal: true, vertical: false)
|
||||
.padding(10)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(.primary.opacity(0.06), in: RoundedRectangle(cornerRadius: 8))
|
||||
.environment(\.layoutDirection, .leftToRight)
|
||||
case .rule:
|
||||
Divider()
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
}
|
||||
|
||||
private func inlineText(_ text: String, size: CGFloat, weight: Font.Weight = .regular) -> some View {
|
||||
Text(styled(text, size: size))
|
||||
.font(.system(size: size, weight: weight))
|
||||
.textSelection(.enabled)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
private func styled(_ text: String, size: CGFloat) -> AttributedString {
|
||||
var attributed = MarkdownPresentation.inline(text)
|
||||
let runs = attributed.runs.compactMap { run -> (Range<AttributedString.Index>, InlinePresentationIntent)? in
|
||||
guard let intent = run.inlinePresentationIntent else { return nil }
|
||||
let relevant = intent.contains(.stronglyEmphasized)
|
||||
|| intent.contains(.emphasized)
|
||||
|| intent.contains(.code)
|
||||
return relevant ? (run.range, intent) : nil
|
||||
}
|
||||
|
||||
for (range, intent) in runs {
|
||||
if intent.contains(.code) {
|
||||
var font = Font.system(size: size * 0.95, design: .monospaced)
|
||||
if intent.contains(.stronglyEmphasized) {
|
||||
font = font.bold()
|
||||
}
|
||||
if intent.contains(.emphasized) {
|
||||
font = font.italic()
|
||||
}
|
||||
attributed[range].font = font
|
||||
} else {
|
||||
var font = Font.system(
|
||||
size: size,
|
||||
weight: intent.contains(.stronglyEmphasized) ? .bold : .regular
|
||||
)
|
||||
if intent.contains(.emphasized) {
|
||||
font = font.italic()
|
||||
}
|
||||
attributed[range].font = font
|
||||
}
|
||||
}
|
||||
return attributed
|
||||
}
|
||||
|
||||
private func headingScale(_ level: Int) -> CGFloat {
|
||||
switch level {
|
||||
case 1: 1.6
|
||||
case 2: 1.45
|
||||
case 3: 1.3
|
||||
case 4: 1.2
|
||||
case 5: 1.12
|
||||
default: 1.06
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import AppKit
|
||||
import SprachmittlerCore
|
||||
import SwiftUI
|
||||
|
||||
/// The non-activating floating panel. It never activates the app. While visible it can be the key
|
||||
/// window so Esc and the keyboard shortcuts work without a click.
|
||||
@MainActor
|
||||
final class PanelController: NSObject, NSWindowDelegate {
|
||||
private let panel: TranslationPanel
|
||||
private let viewModel: PanelViewModel
|
||||
private var isClosing = false
|
||||
private var outsideClickMonitor: Any?
|
||||
|
||||
/// Creates the panel and its SwiftUI content.
|
||||
init(viewModel: PanelViewModel) {
|
||||
self.viewModel = viewModel
|
||||
panel = TranslationPanel(
|
||||
contentRect: NSRect(x: 0, y: 0, width: 540, height: 520),
|
||||
styleMask: [.titled, .fullSizeContentView, .nonactivatingPanel],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
super.init()
|
||||
panel.delegate = self
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(panelDidResignKey(_:)),
|
||||
name: NSWindow.didResignKeyNotification,
|
||||
object: panel
|
||||
)
|
||||
panel.isFloatingPanel = true
|
||||
panel.isMovable = true
|
||||
panel.becomesKeyOnlyIfNeeded = false
|
||||
panel.level = .floating
|
||||
panel.hidesOnDeactivate = false
|
||||
panel.isMovableByWindowBackground = true
|
||||
panel.isReleasedWhenClosed = false
|
||||
panel.titleVisibility = .hidden
|
||||
panel.titlebarAppearsTransparent = true
|
||||
panel.backgroundColor = .clear
|
||||
panel.isOpaque = false
|
||||
panel.hasShadow = true
|
||||
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
|
||||
panel.standardWindowButton(.closeButton)?.isHidden = true
|
||||
panel.standardWindowButton(.miniaturizeButton)?.isHidden = true
|
||||
panel.standardWindowButton(.zoomButton)?.isHidden = true
|
||||
panel.contentView = PanelHostingView(
|
||||
rootView: PanelView(
|
||||
model: viewModel,
|
||||
onClose: { [weak self] in self?.close() }
|
||||
)
|
||||
)
|
||||
panel.setContentSize(NSSize(width: 540, height: 520))
|
||||
}
|
||||
|
||||
/// Shows the panel near the mouse without activating the app.
|
||||
func show() {
|
||||
if !panel.isVisible {
|
||||
positionNearMouse()
|
||||
}
|
||||
panel.orderFrontRegardless()
|
||||
if viewModel.configuration.closeWithEscape {
|
||||
panel.makeKey()
|
||||
}
|
||||
installOutsideClickMonitor()
|
||||
}
|
||||
|
||||
/// Hides the panel and cancels/releases its content.
|
||||
func close() {
|
||||
guard !isClosing else { return }
|
||||
isClosing = true
|
||||
defer { isClosing = false }
|
||||
removeOutsideClickMonitor()
|
||||
panel.orderOut(nil)
|
||||
Task { await viewModel.close() }
|
||||
}
|
||||
|
||||
/// A click outside the panel makes another window key. Treat that as a dismissal, but not
|
||||
/// while the language popover (a child window) is open.
|
||||
@objc private func panelDidResignKey(_ notification: Notification) {
|
||||
guard panel.isVisible, !isClosing else { return }
|
||||
if panel.childWindows?.contains(where: \.isVisible) == true {
|
||||
return
|
||||
}
|
||||
close()
|
||||
}
|
||||
|
||||
/// While the panel is visible, a click sent to another app dismisses it. Global monitors do not
|
||||
/// receive events sent to this app, so clicks in the panel and its popover are ignored. The
|
||||
/// event itself is never read.
|
||||
private func installOutsideClickMonitor() {
|
||||
guard outsideClickMonitor == nil else { return }
|
||||
outsideClickMonitor = NSEvent.addGlobalMonitorForEvents(
|
||||
matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]
|
||||
) { [weak self] _ in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, panel.isVisible else { return }
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func removeOutsideClickMonitor() {
|
||||
if let outsideClickMonitor {
|
||||
NSEvent.removeMonitor(outsideClickMonitor)
|
||||
self.outsideClickMonitor = nil
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
func windowWillClose(_ notification: Notification) {
|
||||
removeOutsideClickMonitor()
|
||||
Task { await viewModel.close() }
|
||||
}
|
||||
|
||||
private final class PanelHostingView: NSHostingView<PanelView> {
|
||||
required init(rootView: PanelView) {
|
||||
super.init(rootView: rootView)
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
nil
|
||||
}
|
||||
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
private func positionNearMouse() {
|
||||
let mouse = NSEvent.mouseLocation
|
||||
let screen = NSScreen.screens.first { $0.frame.contains(mouse) } ?? NSScreen.main
|
||||
guard let visible = screen?.visibleFrame else {
|
||||
panel.setFrameOrigin(mouse)
|
||||
return
|
||||
}
|
||||
let size = panel.frame.size
|
||||
var origin = NSPoint(x: mouse.x - size.width / 2, y: mouse.y + 16)
|
||||
origin.x = max(visible.minX + 12, min(origin.x, visible.maxX - size.width - 12))
|
||||
origin.y = max(visible.minY + 12, min(origin.y, visible.maxY - size.height - 12))
|
||||
panel.setFrameOrigin(origin)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import AppKit
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerText
|
||||
import SwiftUI
|
||||
|
||||
extension PanelView {
|
||||
private var rendersMarkdown: Bool {
|
||||
!model.translation.isEmpty
|
||||
&& model.configuration.renderMarkdown
|
||||
&& MarkdownPresentation.shouldRender(
|
||||
source: model.source?.text ?? "",
|
||||
translation: model.translation
|
||||
)
|
||||
}
|
||||
|
||||
var translationArea: some View {
|
||||
ScrollView {
|
||||
translationContent
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.frame(minHeight: 120, maxHeight: 260)
|
||||
.padding(10)
|
||||
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8))
|
||||
.overlay(alignment: .topTrailing) {
|
||||
if model.phase == .translating || model.phase == .streaming {
|
||||
ProgressView()
|
||||
.controlSize(.small)
|
||||
.padding(8)
|
||||
.accessibilityLabel(String(localized: "Translating"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder var translationContent: some View {
|
||||
if rendersMarkdown {
|
||||
MarkdownTranslationView(
|
||||
markdown: model.translation,
|
||||
fontSize: model.configuration.translationFontSize,
|
||||
isRTL: model.effectiveTarget.isRTL
|
||||
)
|
||||
} else {
|
||||
Text(translationText)
|
||||
.font(.system(size: CGFloat(model.configuration.translationFontSize)))
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.foregroundStyle(model.translation.isEmpty ? .secondary : .primary)
|
||||
.environment(
|
||||
\.layoutDirection,
|
||||
model.effectiveTarget.isRTL ? .rightToLeft : .leftToRight
|
||||
)
|
||||
.accessibilityLabel(String(localized: "Translation"))
|
||||
}
|
||||
}
|
||||
|
||||
var translationText: String {
|
||||
if !model.translation.isEmpty {
|
||||
return model.translation
|
||||
}
|
||||
switch model.phase {
|
||||
case .translating, .streaming:
|
||||
return String(localized: "Translating…")
|
||||
case .failed:
|
||||
return String(localized: "No translation.")
|
||||
case .idle, .ready:
|
||||
return String(localized: "No translation yet.")
|
||||
}
|
||||
}
|
||||
|
||||
private func routedMessage(from routedSource: ModelLanguage) -> String {
|
||||
let source = routedSource.localizedDisplayName
|
||||
let target = model.effectiveTarget.localizedDisplayName
|
||||
return String(localized: "Detected \(source). Translating to \(target).")
|
||||
}
|
||||
|
||||
@ViewBuilder var warningArea: some View {
|
||||
if let routedSource = model.routedSource {
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
Image(systemName: "arrow.left.arrow.right.circle.fill")
|
||||
.foregroundStyle(.blue)
|
||||
.accessibilityHidden(true)
|
||||
Text(routedMessage(from: routedSource))
|
||||
.font(.callout)
|
||||
Spacer()
|
||||
Button(String(localized: "Translate to \(model.configuration.target.localizedDisplayName)")) {
|
||||
Task { await model.overrideTarget(model.configuration.target) }
|
||||
}
|
||||
.controlSize(.small)
|
||||
}
|
||||
.padding(8)
|
||||
.background(.blue.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
|
||||
}
|
||||
|
||||
if model.sameLanguageWarning != nil {
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
Image(systemName: "info.circle.fill").foregroundStyle(.blue)
|
||||
Text("This text already appears to be in \(model.effectiveTarget.localizedDisplayName).")
|
||||
.font(.callout)
|
||||
Spacer()
|
||||
Button(String(localized: "Translate anyway")) {
|
||||
model.dismissSameLanguageWarning()
|
||||
}
|
||||
.controlSize(.small)
|
||||
}
|
||||
.padding(8)
|
||||
.background(.blue.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
|
||||
}
|
||||
|
||||
ForEach(Array(visibleWarnings.enumerated()), id: \.offset) { _, warning in
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
Image(systemName: warning.isBlocking ? "exclamationmark.triangle.fill" : "exclamationmark.circle")
|
||||
.foregroundStyle(warning.isBlocking ? .orange : .secondary)
|
||||
Text(warning.panelMessage)
|
||||
.font(.callout)
|
||||
Spacer()
|
||||
}
|
||||
.padding(8)
|
||||
.background(
|
||||
(warning.isBlocking ? Color.orange : Color.secondary)
|
||||
.opacity(0.08),
|
||||
in: RoundedRectangle(cornerRadius: 8)
|
||||
)
|
||||
.accessibilityLabel(warning.panelMessage)
|
||||
}
|
||||
}
|
||||
|
||||
var visibleWarnings: [TranslationWarning] {
|
||||
model.warnings.filter { warning in
|
||||
if case .sameLanguage = warning {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder var errorArea: some View {
|
||||
if let message = model.errorMessage, model.phase == .failed {
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
Image(systemName: "exclamationmark.octagon.fill")
|
||||
.foregroundStyle(.red)
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text(message)
|
||||
.font(.callout)
|
||||
if let action = model.recoveryAction {
|
||||
recoveryButton(action)
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
.padding(8)
|
||||
.background(.red.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
|
||||
.accessibilityLabel(message)
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder func recoveryButton(_ action: RecoveryAction) -> some View {
|
||||
switch action {
|
||||
case .startOllama:
|
||||
if let url = URL(string: "https://ollama.com/download") {
|
||||
Link(String(localized: "Download Ollama"), destination: url)
|
||||
.controlSize(.small)
|
||||
}
|
||||
case let .pullModel(modelName):
|
||||
Button(String(localized: "Copy pull command")) {
|
||||
model.copy("ollama pull \(modelName)")
|
||||
}
|
||||
.controlSize(.small)
|
||||
case .openSettings:
|
||||
if model.error == .accessibilityNotTrusted, let url = accessibilitySettingsURL {
|
||||
Button(String(localized: "Open Accessibility Settings")) {
|
||||
NSWorkspace.shared.open(url)
|
||||
}
|
||||
.controlSize(.small)
|
||||
} else {
|
||||
Button(String(localized: "Open Settings")) {
|
||||
openSettings()
|
||||
}
|
||||
.controlSize(.small)
|
||||
}
|
||||
case .copyInstead:
|
||||
Button(String(localized: "Copy instead")) {
|
||||
model.copyTranslation()
|
||||
}
|
||||
.controlSize(.small)
|
||||
case .shortenText:
|
||||
EmptyView()
|
||||
case .retry:
|
||||
Button(String(localized: "Retry")) {
|
||||
Task { await model.retry() }
|
||||
}
|
||||
.controlSize(.small)
|
||||
case .none:
|
||||
EmptyView()
|
||||
}
|
||||
}
|
||||
|
||||
var accessibilitySettingsURL: URL? {
|
||||
URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
|
||||
}
|
||||
|
||||
var footer: some View {
|
||||
HStack(spacing: 10) {
|
||||
Button {
|
||||
model.copyTranslation()
|
||||
} label: {
|
||||
Label(
|
||||
model.didCopy ? String(localized: "Copied") : String(localized: "Copy"),
|
||||
systemImage: "doc.on.doc"
|
||||
)
|
||||
}
|
||||
.keyboardShortcut("c", modifiers: .command)
|
||||
.disabled(!model.canCopy)
|
||||
.accessibilityLabel(String(localized: "Copy translation"))
|
||||
|
||||
Button {
|
||||
Task { await model.retry() }
|
||||
} label: {
|
||||
Label(String(localized: "Retry"), systemImage: "arrow.clockwise")
|
||||
}
|
||||
.keyboardShortcut("r", modifiers: .command)
|
||||
.disabled(model.source == nil)
|
||||
.accessibilityLabel(String(localized: "Retry translation"))
|
||||
|
||||
if let current = model.currentChunk, let total = model.totalChunks, total > 1 {
|
||||
Text(String(localized: "Part \(current) of \(total)"))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.accessibilityLabel(String(localized: "Part \(current) of \(total)"))
|
||||
} else if model.chunkCount > 1 {
|
||||
Text(String(localized: "\(model.chunkCount) parts"))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.accessibilityLabel(String(localized: "Translated in \(model.chunkCount) parts"))
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
Button {
|
||||
onClose()
|
||||
} label: {
|
||||
Text(String(localized: "Close"))
|
||||
}
|
||||
.keyboardShortcut(.cancelAction)
|
||||
.accessibilityLabel(String(localized: "Close panel"))
|
||||
|
||||
Button {
|
||||
Task { await model.replaceSelection() }
|
||||
} label: {
|
||||
Text(String(localized: "Replace"))
|
||||
}
|
||||
.keyboardShortcut(.return, modifiers: .command)
|
||||
.buttonStyle(.borderedProminent)
|
||||
.disabled(!model.canReplace)
|
||||
.help(model.replaceUnavailableReason ?? String(localized: "Replace the selection"))
|
||||
.accessibilityLabel(String(localized: "Replace selection"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import AppKit
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerText
|
||||
import SwiftUI
|
||||
|
||||
/// The translation panel view. It never activates the app.
|
||||
struct PanelView: View {
|
||||
@Bindable var model: PanelViewModel
|
||||
let onClose: @MainActor () -> Void
|
||||
|
||||
@Environment(\.openSettings) var openSettings
|
||||
@State private var showLanguagePicker = false
|
||||
@State private var showSource = true
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
header
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
if model.configuration.showSourcePreview, let source = model.source {
|
||||
sourcePreview(source)
|
||||
}
|
||||
translationArea
|
||||
warningArea
|
||||
errorArea
|
||||
footer
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.top, 10)
|
||||
.padding(.bottom, 16)
|
||||
}
|
||||
.frame(width: 540)
|
||||
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
|
||||
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: 14, style: .continuous)
|
||||
.strokeBorder(.separator, lineWidth: 1)
|
||||
)
|
||||
.ignoresSafeArea(.container, edges: .top)
|
||||
.onAppear { showSource = model.configuration.showSourcePreview }
|
||||
.onChange(of: model.configuration.showSourcePreview) { _, newValue in
|
||||
showSource = newValue
|
||||
}
|
||||
.onExitCommand(perform: onClose)
|
||||
.accessibilityElement(children: .contain)
|
||||
.accessibilityLabel(String(localized: "Translation panel"))
|
||||
}
|
||||
|
||||
private var header: some View {
|
||||
ZStack {
|
||||
WindowDragArea()
|
||||
Color.primary.opacity(0.04).allowsHitTesting(false)
|
||||
HStack(spacing: 10) {
|
||||
HStack(spacing: 10) {
|
||||
Image(systemName: "line.3.horizontal")
|
||||
.font(.system(size: 12, weight: .semibold))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: 24, height: 32)
|
||||
.background(.quaternary, in: RoundedRectangle(cornerRadius: 7))
|
||||
Image(systemName: "character.bubble")
|
||||
.font(.title2)
|
||||
.foregroundStyle(.tint)
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text(String(localized: "Translate"))
|
||||
.font(.headline)
|
||||
Text("\(sourceLanguageLabel) → \(model.effectiveTarget.localizedDisplayName)")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.allowsHitTesting(false)
|
||||
.accessibilityElement(children: .combine)
|
||||
.accessibilityLabel(String(localized: "Move panel"))
|
||||
|
||||
Spacer().allowsHitTesting(false)
|
||||
Button {
|
||||
showLanguagePicker.toggle()
|
||||
} label: {
|
||||
Label(model.effectiveTarget.localizedDisplayName, systemImage: "globe")
|
||||
.labelStyle(.titleAndIcon)
|
||||
}
|
||||
.accessibilityLabel(String(localized: "Target language"))
|
||||
.popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) {
|
||||
LanguagePickerView(
|
||||
selection: Binding(
|
||||
get: { model.effectiveTarget },
|
||||
set: { language in
|
||||
Task { await model.overrideTarget(language) }
|
||||
}
|
||||
),
|
||||
recent: model.configuration.recentTargets
|
||||
)
|
||||
}
|
||||
Button {
|
||||
openSettings()
|
||||
} label: {
|
||||
Image(systemName: "gearshape")
|
||||
}
|
||||
.accessibilityLabel(String(localized: "Settings"))
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
}
|
||||
.frame(height: 56)
|
||||
.frame(maxWidth: .infinity)
|
||||
.help(String(localized: "Drag to move panel"))
|
||||
}
|
||||
|
||||
private var sourceLanguageLabel: String {
|
||||
guard let code = model.sourceLanguage, let language = LanguageCatalogue.resolve(code) else {
|
||||
return String(localized: "Detected language")
|
||||
}
|
||||
return language.localizedDisplayName
|
||||
}
|
||||
|
||||
private func sourcePreview(_ source: CapturedText) -> some View {
|
||||
DisclosureGroup(isExpanded: $showSource) {
|
||||
ScrollView {
|
||||
Text(source.text)
|
||||
.font(.callout)
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.frame(maxHeight: 100)
|
||||
} label: {
|
||||
Text(showSource ? String(localized: "Source") : String(localized: "Show source"))
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.help(showSource ? String(localized: "Hide source") : String(localized: "Show source"))
|
||||
.accessibilityLabel(String(localized: "Source text"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import AppKit
|
||||
|
||||
/// The translation panel. It can become the key window without activating the app, so Esc and the
|
||||
/// keyboard shortcuts work as soon as it is shown.
|
||||
final class TranslationPanel: NSPanel {
|
||||
override var canBecomeKey: Bool {
|
||||
true
|
||||
}
|
||||
|
||||
override var canBecomeMain: Bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// An AppKit drag surface for the non-activating panel. SwiftUI's hosting view consumes mouse
|
||||
/// events, and `performDrag` is unreliable while the app is inactive, so the view moves the
|
||||
/// window itself from the screen-space mouse delta.
|
||||
struct WindowDragArea: NSViewRepresentable {
|
||||
func makeNSView(context: Context) -> NSView {
|
||||
DragView()
|
||||
}
|
||||
|
||||
func updateNSView(_ nsView: NSView, context: Context) {}
|
||||
}
|
||||
|
||||
private final class DragView: NSView {
|
||||
private var startMouse = NSPoint.zero
|
||||
private var startOrigin = NSPoint.zero
|
||||
|
||||
override var mouseDownCanMoveWindow: Bool {
|
||||
false
|
||||
}
|
||||
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
guard let window else { return }
|
||||
startMouse = NSEvent.mouseLocation
|
||||
startOrigin = window.frame.origin
|
||||
NSCursor.closedHand.push()
|
||||
}
|
||||
|
||||
override func mouseDragged(with event: NSEvent) {
|
||||
guard let window else { return }
|
||||
let mouse = NSEvent.mouseLocation
|
||||
window.setFrameOrigin(
|
||||
NSPoint(
|
||||
x: startOrigin.x + mouse.x - startMouse.x,
|
||||
y: startOrigin.y + mouse.y - startMouse.y
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
override func mouseUp(with event: NSEvent) {
|
||||
NSCursor.pop()
|
||||
}
|
||||
|
||||
override func resetCursorRects() {
|
||||
addCursorRect(bounds, cursor: .openHand)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"images" : [
|
||||
{ "filename" : "icon_16x16.png", "idiom" : "mac", "scale" : "1x", "size" : "16x16" },
|
||||
{ "filename" : "icon_16x16@2x.png", "idiom" : "mac", "scale" : "2x", "size" : "16x16" },
|
||||
{ "filename" : "icon_32x32.png", "idiom" : "mac", "scale" : "1x", "size" : "32x32" },
|
||||
{ "filename" : "icon_32x32@2x.png", "idiom" : "mac", "scale" : "2x", "size" : "32x32" },
|
||||
{ "filename" : "icon_128x128.png", "idiom" : "mac", "scale" : "1x", "size" : "128x128" },
|
||||
{ "filename" : "icon_128x128@2x.png", "idiom" : "mac", "scale" : "2x", "size" : "128x128" },
|
||||
{ "filename" : "icon_256x256.png", "idiom" : "mac", "scale" : "1x", "size" : "256x256" },
|
||||
{ "filename" : "icon_256x256@2x.png", "idiom" : "mac", "scale" : "2x", "size" : "256x256" },
|
||||
{ "filename" : "icon_512x512.png", "idiom" : "mac", "scale" : "1x", "size" : "512x512" },
|
||||
{ "filename" : "icon_512x512@2x.png", "idiom" : "mac", "scale" : "2x", "size" : "512x512" }
|
||||
],
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 641 B |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 170 KiB |
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/* Sprachmittler UI — Deutsch */
|
||||
"Translate Clipboard Text" = "Zwischenablage übersetzen";
|
||||
"Target Language" = "Zielsprache";
|
||||
"More languages…" = "Weitere Sprachen…";
|
||||
"Copy Last Translation" = "Letzte Übersetzung kopieren";
|
||||
"Replace Last Translation" = "Letzte Übersetzung ersetzen";
|
||||
"Set up Sprachmittler…" = "Sprachmittler einrichten…";
|
||||
"Diagnostics…" = "Diagnose…";
|
||||
"About Sprachmittler" = "Über Sprachmittler";
|
||||
"Settings…" = "Einstellungen…";
|
||||
"Quit Sprachmittler" = "Sprachmittler beenden";
|
||||
"Translate" = "Übersetzen";
|
||||
"Move panel" = "Panel verschieben";
|
||||
"Drag to move panel" = "Zum Verschieben ziehen";
|
||||
"Translation text size" = "Schriftgröße der Übersetzung";
|
||||
"Source" = "Quelle";
|
||||
"Show source" = "Quelle anzeigen";
|
||||
"Hide source" = "Quelle ausblenden";
|
||||
"Settings" = "Einstellungen";
|
||||
"Search languages" = "Sprachen suchen";
|
||||
"Copy" = "Kopieren";
|
||||
"Copied" = "Kopiert";
|
||||
"Retry" = "Erneut versuchen";
|
||||
"Close" = "Schließen";
|
||||
"Replace" = "Ersetzen";
|
||||
"Translation" = "Übersetzung";
|
||||
"Translating…" = "Wird übersetzt…";
|
||||
"No translation." = "Keine Übersetzung.";
|
||||
"No translation yet." = "Noch keine Übersetzung.";
|
||||
"Close panel" = "Panel schließen";
|
||||
"Copy translation" = "Übersetzung kopieren";
|
||||
"Retry translation" = "Übersetzung erneut versuchen";
|
||||
"Replace selection" = "Auswahl ersetzen";
|
||||
"Open Accessibility Settings" = "Bedienungshilfen öffnen";
|
||||
"Open Settings" = "Einstellungen öffnen";
|
||||
"Download Ollama" = "Ollama herunterladen";
|
||||
"Copy pull command" = "Pull-Befehl kopieren";
|
||||
"Copy instead" = "Stattdessen kopieren";
|
||||
"Translate anyway" = "Trotzdem übersetzen";
|
||||
"Target language" = "Zielsprache";
|
||||
"Detected language" = "Erkannte Sprache";
|
||||
"Replace the selection" = "Die Auswahl ersetzen";
|
||||
"Replace is not available." = "Ersetzen ist nicht verfügbar.";
|
||||
"General" = "Allgemein";
|
||||
"Model" = "Modell";
|
||||
"Privacy" = "Datenschutz";
|
||||
"Diagnostics" = "Diagnose";
|
||||
"Reset" = "Zurücksetzen";
|
||||
"Save" = "Speichern";
|
||||
"Show source preview" = "Quellenvorschau anzeigen";
|
||||
"Launch at login" = "Bei der Anmeldung starten";
|
||||
"Warm up the model on launch" = "Modell beim Start vorwärmen";
|
||||
"Ollama" = "Ollama";
|
||||
"Endpoint" = "Endpunkt";
|
||||
"Allow a remote HTTPS endpoint" = "Entfernten HTTPS-Endpunkt erlauben";
|
||||
"Refresh installed models" = "Installierte Modelle aktualisieren";
|
||||
"Translation model" = "Übersetzungsmodell";
|
||||
"Fast model tag (optional)" = "Tag des schnellen Modells (optional)";
|
||||
"Keep model loaded" = "Modell geladen halten";
|
||||
"5 minutes" = "5 Minuten";
|
||||
"30 minutes" = "30 Minuten";
|
||||
"1 hour" = "1 Stunde";
|
||||
"Unload after each request" = "Nach jeder Anfrage entladen";
|
||||
"Digest" = "Digest";
|
||||
"Context and output" = "Kontext und Ausgabe";
|
||||
"Sampling" = "Sampling";
|
||||
"Temperature" = "Temperatur";
|
||||
"Top P" = "Top P";
|
||||
"Repetition penalty" = "Wiederholungsstrafe";
|
||||
"Chunking" = "Aufteilung";
|
||||
"Prompt policy" = "Prompt-Richtlinie";
|
||||
"Default translation is fixed for v1." = "Die Standardübersetzung ist für v1 festgelegt.";
|
||||
"Content-aware prompt selection is decided in M7." = "Die inhaltsabhängige Prompt-Auswahl wird in M7 entschieden.";
|
||||
"Local and private" = "Lokal und privat";
|
||||
"Permissions" = "Berechtigungen";
|
||||
"Accessibility is optional and used only for Replace." = "Bedienungshilfen sind optional und werden nur für Ersetzen benötigt.";
|
||||
"Open Diagnostics…" = "Diagnose öffnen…";
|
||||
"Versions, model digests, timings and error kinds only. No text." = "Nur Versionen, Modell-Digests, Zeiten und Fehlerarten. Kein Text.";
|
||||
"Enter a valid endpoint URL." = "Geben Sie eine gültige Endpunkt-URL ein.";
|
||||
"Settings could not be saved." = "Einstellungen konnten nicht gespeichert werden.";
|
||||
"Launch at login could not be changed." = "Der Start bei der Anmeldung konnte nicht geändert werden.";
|
||||
"Set up Sprachmittler" = "Sprachmittler einrichten";
|
||||
"Local translation with Ollama. Nothing leaves this Mac." = "Lokale Übersetzung mit Ollama. Nichts verlässt diesen Mac.";
|
||||
"Check again" = "Erneut prüfen";
|
||||
"Hy-MT3 model" = "Hy-MT3-Modell";
|
||||
"Refresh" = "Aktualisieren";
|
||||
"Accessibility (optional)" = "Bedienungshilfen (optional)";
|
||||
"Only Replace needs it. Double copy, translation and Copy work without it." = "Nur Ersetzen benötigt sie. Doppelkopie, Übersetzung und Kopieren funktionieren ohne.";
|
||||
"Granted" = "Erteilt";
|
||||
"Enable Accessibility" = "Bedienungshilfen aktivieren";
|
||||
"Open System Settings" = "Systemeinstellungen öffnen";
|
||||
"Done" = "Fertig";
|
||||
"Checking…" = "Wird geprüft…";
|
||||
"Setup could not be saved." = "Einrichtung konnte nicht gespeichert werden.";
|
||||
"unknown" = "unbekannt";
|
||||
"Last 50 events" = "Letzte 50 Ereignisse";
|
||||
"Sprachmittler Diagnostics" = "Sprachmittler-Diagnose";
|
||||
"Sprachmittler diagnostics" = "Sprachmittler-Diagnose";
|
||||
"Ollama details are unavailable." = "Ollama-Details sind nicht verfügbar.";
|
||||
"Copy report" = "Bericht kopieren";
|
||||
"Clear" = "Leeren";
|
||||
"Open Diagnostics…" = "Diagnose öffnen…";
|
||||
"Render Markdown formatting" = "Markdown-Formatierung anzeigen";
|
||||
"Render bold, italic, headings, lists, code and links when the source is Markdown." = "Fett, kursiv, Überschriften, Listen, Code und Links anzeigen, wenn die Quelle Markdown ist.";
|
||||
"Close with Esc without clicking" = "Mit Esc schließen, ohne zu klicken";
|
||||
"The panel takes keyboard focus while it is visible. The source app stays frontmost." = "Das Panel übernimmt die Tastatureingabe, solange es sichtbar ist. Die Quell-App bleibt im Vordergrund.";
|
||||
"Detected %@. Translating to %@." = "%@ erkannt. Übersetzung nach %@.";
|
||||
"Translate to %@" = "Nach %@ übersetzen";
|
||||
"This text already appears to be in %@ (detected %@)." = "Dieser Text scheint bereits auf %@ zu sein (erkannt: %@).";
|
||||
"Mother tongue" = "Muttersprache";
|
||||
"The default target for every language unless a rule matches." = "Das Standardziel für jede Sprache, wenn keine Regel passt.";
|
||||
"Language rules" = "Sprachregeln";
|
||||
"Add rule" = "Regel hinzufügen";
|
||||
"No rules. Every language translates to your mother tongue." = "Keine Regeln. Jede Sprache wird in Ihre Muttersprache übersetzt.";
|
||||
"Source language" = "Ausgangssprache";
|
||||
"Remove rule" = "Regel entfernen";
|
||||
"Rules apply only to confidently detected sources; otherwise the mother tongue is used." = "Regeln gelten nur für sicher erkannte Ausgangssprachen; sonst wird die Muttersprache verwendet.";
|
||||
@@ -0,0 +1,117 @@
|
||||
/* Sprachmittler UI — English base */
|
||||
"Translate Clipboard Text" = "Translate Clipboard Text";
|
||||
"Target Language" = "Target Language";
|
||||
"More languages…" = "More languages…";
|
||||
"Copy Last Translation" = "Copy Last Translation";
|
||||
"Replace Last Translation" = "Replace Last Translation";
|
||||
"Set up Sprachmittler…" = "Set up Sprachmittler…";
|
||||
"Diagnostics…" = "Diagnostics…";
|
||||
"About Sprachmittler" = "About Sprachmittler";
|
||||
"Settings…" = "Settings…";
|
||||
"Quit Sprachmittler" = "Quit Sprachmittler";
|
||||
"Translate" = "Translate";
|
||||
"Move panel" = "Move panel";
|
||||
"Drag to move panel" = "Drag to move panel";
|
||||
"Translation text size" = "Translation text size";
|
||||
"Source" = "Source";
|
||||
"Show source" = "Show source";
|
||||
"Hide source" = "Hide source";
|
||||
"Settings" = "Settings";
|
||||
"Search languages" = "Search languages";
|
||||
"Copy" = "Copy";
|
||||
"Copied" = "Copied";
|
||||
"Retry" = "Retry";
|
||||
"Close" = "Close";
|
||||
"Replace" = "Replace";
|
||||
"Translation" = "Translation";
|
||||
"Translating…" = "Translating…";
|
||||
"No translation." = "No translation.";
|
||||
"No translation yet." = "No translation yet.";
|
||||
"Close panel" = "Close panel";
|
||||
"Copy translation" = "Copy translation";
|
||||
"Retry translation" = "Retry translation";
|
||||
"Replace selection" = "Replace selection";
|
||||
"Open Accessibility Settings" = "Open Accessibility Settings";
|
||||
"Open Settings" = "Open Settings";
|
||||
"Download Ollama" = "Download Ollama";
|
||||
"Copy pull command" = "Copy pull command";
|
||||
"Copy instead" = "Copy instead";
|
||||
"Translate anyway" = "Translate anyway";
|
||||
"Target language" = "Target language";
|
||||
"Detected language" = "Detected language";
|
||||
"Replace the selection" = "Replace the selection";
|
||||
"Replace is not available." = "Replace is not available.";
|
||||
"General" = "General";
|
||||
"Model" = "Model";
|
||||
"Privacy" = "Privacy";
|
||||
"Diagnostics" = "Diagnostics";
|
||||
"Reset" = "Reset";
|
||||
"Save" = "Save";
|
||||
"Show source preview" = "Show source preview";
|
||||
"Launch at login" = "Launch at login";
|
||||
"Warm up the model on launch" = "Warm up the model on launch";
|
||||
"Ollama" = "Ollama";
|
||||
"Endpoint" = "Endpoint";
|
||||
"Allow a remote HTTPS endpoint" = "Allow a remote HTTPS endpoint";
|
||||
"Refresh installed models" = "Refresh installed models";
|
||||
"Translation model" = "Translation model";
|
||||
"Fast model tag (optional)" = "Fast model tag (optional)";
|
||||
"Keep model loaded" = "Keep model loaded";
|
||||
"5 minutes" = "5 minutes";
|
||||
"30 minutes" = "30 minutes";
|
||||
"1 hour" = "1 hour";
|
||||
"Unload after each request" = "Unload after each request";
|
||||
"Digest" = "Digest";
|
||||
"Context and output" = "Context and output";
|
||||
"Sampling" = "Sampling";
|
||||
"Temperature" = "Temperature";
|
||||
"Top P" = "Top P";
|
||||
"Repetition penalty" = "Repetition penalty";
|
||||
"Chunking" = "Chunking";
|
||||
"Prompt policy" = "Prompt policy";
|
||||
"Default translation is fixed for v1." = "Default translation is fixed for v1.";
|
||||
"Content-aware prompt selection is decided in M7." = "Content-aware prompt selection is decided in M7.";
|
||||
"Local and private" = "Local and private";
|
||||
"Permissions" = "Permissions";
|
||||
"Accessibility is optional and used only for Replace." = "Accessibility is optional and used only for Replace.";
|
||||
"Open Diagnostics…" = "Open Diagnostics…";
|
||||
"Versions, model digests, timings and error kinds only. No text." = "Versions, model digests, timings and error kinds only. No text.";
|
||||
"Enter a valid endpoint URL." = "Enter a valid endpoint URL.";
|
||||
"Settings could not be saved." = "Settings could not be saved.";
|
||||
"Launch at login could not be changed." = "Launch at login could not be changed.";
|
||||
"Set up Sprachmittler" = "Set up Sprachmittler";
|
||||
"Local translation with Ollama. Nothing leaves this Mac." = "Local translation with Ollama. Nothing leaves this Mac.";
|
||||
"Check again" = "Check again";
|
||||
"Hy-MT3 model" = "Hy-MT3 model";
|
||||
"Refresh" = "Refresh";
|
||||
"Accessibility (optional)" = "Accessibility (optional)";
|
||||
"Only Replace needs it. Double copy, translation and Copy work without it." = "Only Replace needs it. Double copy, translation and Copy work without it.";
|
||||
"Granted" = "Granted";
|
||||
"Enable Accessibility" = "Enable Accessibility";
|
||||
"Open System Settings" = "Open System Settings";
|
||||
"Done" = "Done";
|
||||
"Checking…" = "Checking…";
|
||||
"Setup could not be saved." = "Setup could not be saved.";
|
||||
"unknown" = "unknown";
|
||||
"Last 50 events" = "Last 50 events";
|
||||
"Sprachmittler Diagnostics" = "Sprachmittler Diagnostics";
|
||||
"Sprachmittler diagnostics" = "Sprachmittler diagnostics";
|
||||
"Ollama details are unavailable." = "Ollama details are unavailable.";
|
||||
"Copy report" = "Copy report";
|
||||
"Clear" = "Clear";
|
||||
"Open Diagnostics…" = "Open Diagnostics…";
|
||||
"Render Markdown formatting" = "Render Markdown formatting";
|
||||
"Render bold, italic, headings, lists, code and links when the source is Markdown." = "Render bold, italic, headings, lists, code and links when the source is Markdown.";
|
||||
"Close with Esc without clicking" = "Close with Esc without clicking";
|
||||
"The panel takes keyboard focus while it is visible. The source app stays frontmost." = "The panel takes keyboard focus while it is visible. The source app stays frontmost.";
|
||||
"Detected %@. Translating to %@." = "Detected %@. Translating to %@.";
|
||||
"Translate to %@" = "Translate to %@";
|
||||
"This text already appears to be in %@ (detected %@)." = "This text already appears to be in %@ (detected %@).";
|
||||
"Mother tongue" = "Mother tongue";
|
||||
"The default target for every language unless a rule matches." = "The default target for every language unless a rule matches.";
|
||||
"Language rules" = "Language rules";
|
||||
"Add rule" = "Add rule";
|
||||
"No rules. Every language translates to your mother tongue." = "No rules. Every language translates to your mother tongue.";
|
||||
"Source language" = "Source language";
|
||||
"Remove rule" = "Remove rule";
|
||||
"Rules apply only to confidently detected sources; otherwise the mother tongue is used." = "Rules apply only to confidently detected sources; otherwise the mother tongue is used.";
|
||||
@@ -0,0 +1,93 @@
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerEngines
|
||||
import SwiftUI
|
||||
|
||||
/// The source-to-target rules in Settings ▸ General. An empty table means everything goes to the
|
||||
/// mother tongue.
|
||||
struct LanguageRulesSettings: View {
|
||||
@Binding var routes: [LanguageRoute]
|
||||
let motherTongue: ModelLanguage
|
||||
|
||||
private var languages: [ModelLanguage] {
|
||||
LanguageCatalogue.all.sorted {
|
||||
$0.localizedDisplayName.localizedCaseInsensitiveCompare($1.localizedDisplayName) == .orderedAscending
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
HStack {
|
||||
Text(String(localized: "Language rules"))
|
||||
Spacer()
|
||||
Button(String(localized: "Add rule")) {
|
||||
addRule()
|
||||
}
|
||||
.controlSize(.small)
|
||||
}
|
||||
|
||||
if routes.isEmpty {
|
||||
Text(String(localized: "No rules. Every language translates to your mother tongue."))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
ForEach($routes) { $route in
|
||||
HStack(spacing: 8) {
|
||||
Picker(String(localized: "Source language"), selection: $route.source) {
|
||||
ForEach(sourceOptions(for: route.source)) { language in
|
||||
Text(language.localizedDisplayName).tag(language.code)
|
||||
}
|
||||
}
|
||||
.labelsHidden()
|
||||
.accessibilityLabel(String(localized: "Source language"))
|
||||
|
||||
Image(systemName: "arrow.right")
|
||||
.foregroundStyle(.secondary)
|
||||
.accessibilityHidden(true)
|
||||
|
||||
Picker(String(localized: "Target language"), selection: $route.target) {
|
||||
ForEach(targetOptions(for: route.source)) { language in
|
||||
Text(language.localizedDisplayName).tag(language.code)
|
||||
}
|
||||
}
|
||||
.labelsHidden()
|
||||
.accessibilityLabel(String(localized: "Target language"))
|
||||
|
||||
Button {
|
||||
routes.removeAll { $0.id == route.id }
|
||||
} label: {
|
||||
Image(systemName: "trash")
|
||||
}
|
||||
.buttonStyle(.borderless)
|
||||
.accessibilityLabel(String(localized: "Remove rule"))
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
String(
|
||||
localized: "Rules apply only to confidently detected sources; otherwise the mother tongue is used."
|
||||
)
|
||||
)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
private func sourceOptions(for current: String) -> [ModelLanguage] {
|
||||
let used = Set(routes.map(\.source))
|
||||
return languages.filter { $0.code == current || !used.contains($0.code) }
|
||||
}
|
||||
|
||||
private func targetOptions(for source: String) -> [ModelLanguage] {
|
||||
languages.filter { $0.code.caseInsensitiveCompare(source) != .orderedSame }
|
||||
}
|
||||
|
||||
private func addRule() {
|
||||
let used = Set(routes.map(\.source))
|
||||
let source = languages.first {
|
||||
!used.contains($0.code) && $0.code.caseInsensitiveCompare(motherTongue.code) != .orderedSame
|
||||
} ?? languages.first { !used.contains($0.code) }
|
||||
guard let source else { return }
|
||||
routes.append(LanguageRoute(source: source, target: motherTongue))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import SprachmittlerCore
|
||||
import SwiftUI
|
||||
|
||||
/// The long-selection settings: part size and the number of parts one capture may use.
|
||||
struct LongSelectionsSettings: View {
|
||||
@Binding var draft: AppSettings
|
||||
|
||||
var body: some View {
|
||||
Section(String(localized: "Long selections")) {
|
||||
Stepper(
|
||||
String(localized: "Latin part size: \(draft.maxCharactersLatin)"),
|
||||
value: $draft.maxCharactersLatin,
|
||||
in: 1000 ... 10000,
|
||||
step: 500
|
||||
)
|
||||
Stepper(
|
||||
String(localized: "Dense-script part size: \(draft.maxCharactersCJK)"),
|
||||
value: $draft.maxCharactersCJK,
|
||||
in: 500 ... 4000,
|
||||
step: 250
|
||||
)
|
||||
Stepper(
|
||||
String(localized: "Maximum parts per selection: \(draft.maximumPartsPerSelection)"),
|
||||
value: $draft.maximumPartsPerSelection,
|
||||
in: 1 ... 8
|
||||
)
|
||||
Text(
|
||||
String(
|
||||
localized: """
|
||||
One part rejects text longer than a single part. Higher values translate \
|
||||
long selections one part at a time, which takes longer.
|
||||
"""
|
||||
)
|
||||
)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
import SprachmittlerCore
|
||||
import SwiftUI
|
||||
|
||||
/// The Settings window: General, Model, Translation, Privacy and Diagnostics.
|
||||
@MainActor
|
||||
struct SettingsView: View {
|
||||
@Bindable var model: SettingsViewModel
|
||||
let onOpenDiagnostics: @MainActor () -> Void
|
||||
let onSaved: @MainActor () -> Void
|
||||
|
||||
@State private var draft: AppSettings
|
||||
@State private var endpointText: String
|
||||
@State private var saveMessage: String?
|
||||
@State private var showLanguagePicker = false
|
||||
|
||||
init(
|
||||
model: SettingsViewModel,
|
||||
onOpenDiagnostics: @escaping @MainActor () -> Void,
|
||||
onSaved: @escaping @MainActor () -> Void = {}
|
||||
) {
|
||||
self.model = model
|
||||
self.onOpenDiagnostics = onOpenDiagnostics
|
||||
self.onSaved = onSaved
|
||||
_draft = State(initialValue: model.draft)
|
||||
_endpointText = State(initialValue: model.draft.endpoint.absoluteString)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
TabView {
|
||||
generalTab
|
||||
.tabItem { Label(String(localized: "General"), systemImage: "gearshape") }
|
||||
modelTab
|
||||
.tabItem { Label(String(localized: "Model"), systemImage: "cpu") }
|
||||
translationTab
|
||||
.tabItem { Label(String(localized: "Translation"), systemImage: "text.bubble") }
|
||||
privacyTab
|
||||
.tabItem { Label(String(localized: "Privacy"), systemImage: "lock") }
|
||||
diagnosticsTab
|
||||
.tabItem { Label(String(localized: "Diagnostics"), systemImage: "stethoscope") }
|
||||
}
|
||||
.padding(16)
|
||||
|
||||
Divider()
|
||||
HStack {
|
||||
if let saveMessage {
|
||||
Text(saveMessage)
|
||||
.font(.callout)
|
||||
.foregroundStyle(.red)
|
||||
} else if let launchError = model.launchError {
|
||||
Text(launchError)
|
||||
.font(.callout)
|
||||
.foregroundStyle(.orange)
|
||||
}
|
||||
Spacer()
|
||||
Button(String(localized: "Reset")) {
|
||||
model.reset()
|
||||
draft = model.draft
|
||||
endpointText = model.draft.endpoint.absoluteString
|
||||
saveMessage = nil
|
||||
onSaved()
|
||||
}
|
||||
Button(String(localized: "Save")) {
|
||||
save()
|
||||
}
|
||||
.keyboardShortcut("s", modifiers: .command)
|
||||
.buttonStyle(.borderedProminent)
|
||||
}
|
||||
.padding(12)
|
||||
}
|
||||
.frame(width: 660, height: 520)
|
||||
}
|
||||
|
||||
private var generalTab: some View {
|
||||
Form {
|
||||
Section(String(localized: "Translation")) {
|
||||
LabeledContent(String(localized: "Mother tongue")) {
|
||||
Button {
|
||||
showLanguagePicker.toggle()
|
||||
} label: {
|
||||
HStack {
|
||||
Text(draft.targetLanguageModel.localizedDisplayName)
|
||||
Image(systemName: "chevron.up.chevron.down")
|
||||
.font(.caption)
|
||||
}
|
||||
}
|
||||
.popover(isPresented: $showLanguagePicker, arrowEdge: .bottom) {
|
||||
LanguagePickerView(
|
||||
selection: Binding(
|
||||
get: { draft.targetLanguageModel },
|
||||
set: { draft.targetLanguage = $0.code }
|
||||
),
|
||||
recent: draft.recentTargets
|
||||
)
|
||||
}
|
||||
.accessibilityLabel(String(localized: "Mother tongue"))
|
||||
}
|
||||
Text(String(localized: "The default target for every language unless a rule matches."))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
Toggle(String(localized: "Show source preview"), isOn: $draft.showSourcePreview)
|
||||
Stepper(value: $draft.translationFontSize, in: 12 ... 28) {
|
||||
LabeledContent(
|
||||
String(localized: "Translation text size"),
|
||||
value: "\(draft.translationFontSize) pt"
|
||||
)
|
||||
}
|
||||
.accessibilityLabel(String(localized: "Translation text size"))
|
||||
Toggle(String(localized: "Render Markdown formatting"), isOn: $draft.renderMarkdown)
|
||||
.accessibilityLabel(String(localized: "Render Markdown formatting"))
|
||||
Text(
|
||||
String(
|
||||
localized: """
|
||||
Render bold, italic, headings, lists, code and links when the source is Markdown.
|
||||
"""
|
||||
)
|
||||
)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
Toggle(String(localized: "Close with Esc without clicking"), isOn: $draft.closeWithEscape)
|
||||
.accessibilityLabel(String(localized: "Close with Esc without clicking"))
|
||||
Text(
|
||||
String(
|
||||
localized: "The panel takes keyboard focus while it is visible. The source app stays frontmost."
|
||||
)
|
||||
)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
LanguageRulesSettings(routes: $draft.languageRoutes, motherTongue: draft.targetLanguageModel)
|
||||
}
|
||||
|
||||
Section(String(localized: "Double copy")) {
|
||||
LabeledContent(String(localized: "Window: \(draft.doubleCopyWindowMs) ms")) {
|
||||
Slider(
|
||||
value: Binding(
|
||||
get: { Double(draft.doubleCopyWindowMs) },
|
||||
set: { draft.doubleCopyWindowMs = Int($0) }
|
||||
),
|
||||
in: 300 ... 1000,
|
||||
step: 50
|
||||
)
|
||||
}
|
||||
Text(String(localized: "Two identical copies inside this window trigger a translation."))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
Section(String(localized: "Startup")) {
|
||||
Toggle(String(localized: "Launch at login"), isOn: $draft.launchAtLogin)
|
||||
Toggle(String(localized: "Warm up the model on launch"), isOn: $draft.warmUpOnLaunch)
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
}
|
||||
|
||||
private var modelTab: some View {
|
||||
Form {
|
||||
Section(String(localized: "Ollama")) {
|
||||
TextField(String(localized: "Endpoint"), text: $endpointText)
|
||||
.accessibilityLabel(String(localized: "Ollama endpoint"))
|
||||
Toggle(String(localized: "Allow a remote HTTPS endpoint"), isOn: $draft.allowRemoteEndpoint)
|
||||
Button(String(localized: "Refresh installed models")) {
|
||||
guard let endpoint = URL(string: endpointText) else {
|
||||
saveMessage = String(localized: "Enter a valid endpoint URL.")
|
||||
return
|
||||
}
|
||||
draft.endpoint = endpoint
|
||||
model.draft = draft
|
||||
Task {
|
||||
await model.refreshModels()
|
||||
draft.fastModel = model.detectedFastModel ?? draft.fastModel
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Section(String(localized: "Model")) {
|
||||
Picker(String(localized: "Translation model"), selection: $draft.model) {
|
||||
ForEach(model.modelChoices, id: \.self) { tag in
|
||||
Text(tag).tag(tag)
|
||||
}
|
||||
}
|
||||
TextField(
|
||||
String(localized: "Fast model tag (optional)"),
|
||||
text: Binding(
|
||||
get: { draft.fastModel ?? "" },
|
||||
set: { draft.fastModel = $0.isEmpty ? nil : $0 }
|
||||
)
|
||||
)
|
||||
Picker(String(localized: "Keep model loaded"), selection: $draft.keepModelLoaded) {
|
||||
Text("5 minutes").tag("5m")
|
||||
Text("30 minutes").tag("30m")
|
||||
Text("1 hour").tag("1h")
|
||||
Text("Unload after each request").tag("0")
|
||||
}
|
||||
if let digest = model.selectedDigest {
|
||||
LabeledContent(String(localized: "Digest"), value: String(digest.prefix(12)))
|
||||
}
|
||||
Text(model.licenceNote)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
Section(String(localized: "Context and output")) {
|
||||
Stepper(
|
||||
String(localized: "Context: \(draft.numCtx)"),
|
||||
value: $draft.numCtx,
|
||||
in: 1024 ... 32768,
|
||||
step: 1024
|
||||
)
|
||||
Stepper(
|
||||
String(localized: "Maximum output: \(draft.numPredict)"),
|
||||
value: $draft.numPredict,
|
||||
in: 256 ... 8192,
|
||||
step: 256
|
||||
)
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
}
|
||||
|
||||
private var translationTab: some View {
|
||||
Form {
|
||||
Section(String(localized: "Sampling")) {
|
||||
LabeledContent(String(localized: "Temperature")) {
|
||||
TextField("", value: $draft.temperature, format: .number.precision(.fractionLength(0 ... 2)))
|
||||
.frame(width: 80)
|
||||
.accessibilityLabel(String(localized: "Temperature"))
|
||||
}
|
||||
LabeledContent(String(localized: "Top P")) {
|
||||
TextField("", value: $draft.topP, format: .number.precision(.fractionLength(0 ... 2)))
|
||||
.frame(width: 80)
|
||||
.accessibilityLabel(String(localized: "Top P"))
|
||||
}
|
||||
Stepper(String(localized: "Top K: \(draft.topK)"), value: $draft.topK, in: 1 ... 100)
|
||||
LabeledContent(String(localized: "Repetition penalty")) {
|
||||
TextField("", value: $draft.repeatPenalty, format: .number.precision(.fractionLength(0 ... 2)))
|
||||
.frame(width: 80)
|
||||
.accessibilityLabel(String(localized: "Repetition penalty"))
|
||||
}
|
||||
}
|
||||
|
||||
LongSelectionsSettings(draft: $draft)
|
||||
|
||||
Section(String(localized: "Prompt policy")) {
|
||||
Text(String(localized: "Default translation is fixed for v1."))
|
||||
Text(String(localized: "Content-aware prompt selection is decided in M7."))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
}
|
||||
|
||||
private var privacyTab: some View {
|
||||
Form {
|
||||
Section(String(localized: "Local and private")) {
|
||||
Text(
|
||||
String(
|
||||
localized: "Selected text, translations, the clipboard and app names are never written to disk."
|
||||
)
|
||||
)
|
||||
Text(String(localized: "No telemetry, no analytics and no accounts."))
|
||||
Text(
|
||||
String(
|
||||
localized: "The clipboard is read only after a change; the last translation stays in memory."
|
||||
)
|
||||
)
|
||||
}
|
||||
Section(String(localized: "Permissions")) {
|
||||
Text(String(localized: "Accessibility is optional and used only for Replace."))
|
||||
Text(String(localized: "Input Monitoring, Screen Recording, Camera, Microphone and Apple Events"))
|
||||
Text(String(localized: "are never requested."))
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
}
|
||||
|
||||
private var diagnosticsTab: some View {
|
||||
Form {
|
||||
Section {
|
||||
Button(String(localized: "Open Diagnostics…")) {
|
||||
onOpenDiagnostics()
|
||||
}
|
||||
Text(String(localized: "Versions, model digests, timings and error kinds only. No text."))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
}
|
||||
|
||||
private func save() {
|
||||
guard let endpoint = URL(string: endpointText) else {
|
||||
saveMessage = String(localized: "Enter a valid endpoint URL.")
|
||||
return
|
||||
}
|
||||
draft.endpoint = endpoint
|
||||
model.draft = draft
|
||||
model.save()
|
||||
if let error = model.saveError {
|
||||
saveMessage = error
|
||||
return
|
||||
}
|
||||
draft = model.draft
|
||||
endpointText = draft.endpoint.absoluteString
|
||||
saveMessage = nil
|
||||
onSaved()
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,25 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Entry point. Keep this file thin: scenes only, no business logic (ARCHITECTURE §3).
|
||||
/// Entry point. Scenes and glue only; business logic lives in the package.
|
||||
@main
|
||||
struct SprachmittlerApp: App {
|
||||
@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
|
||||
|
||||
var body: some Scene {
|
||||
MenuBarExtra("Sprachmittler", systemImage: "translate") {
|
||||
// Replaced by MenuBar/StatusMenu.swift.
|
||||
Button("Translate Clipboard Text") {}
|
||||
.disabled(true)
|
||||
Divider()
|
||||
Button("Set up Sprachmittler…") {}
|
||||
.disabled(true)
|
||||
SettingsLink {
|
||||
Text("Settings…")
|
||||
}
|
||||
Divider()
|
||||
Button("Quit Sprachmittler") {
|
||||
NSApplication.shared.terminate(nil)
|
||||
}
|
||||
.keyboardShortcut("q")
|
||||
MenuBarExtra {
|
||||
StatusMenuView(delegate: appDelegate)
|
||||
} label: {
|
||||
Label("Sprachmittler", systemImage: "translate")
|
||||
}
|
||||
.menuBarExtraStyle(.menu)
|
||||
|
||||
Settings {
|
||||
// Replaced by Settings/SettingsView.swift.
|
||||
Text("Settings")
|
||||
.padding()
|
||||
.frame(width: 480, height: 320)
|
||||
SettingsView(
|
||||
model: appDelegate.environment.settingsModel,
|
||||
onOpenDiagnostics: { appDelegate.showDiagnostics() },
|
||||
onSaved: { appDelegate.environment.settingsDidChange() }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
f6951b1dfd3273d8b320f489125b01f6cdbac708f6e6a6a1af1c35fd43f224ce ./.gitignore
|
||||
ac3b5df584dabe8c38d8dde42e1871198e11c0512e1ed57b45b8cbcdfc5e35f6 ./.gitignore
|
||||
b6f32f48809b596fa90c724e986bc78f220cac1928039eb57b8f7c13ea9a3081 ./.opencode/agents/architect.md
|
||||
a58c2194b2a853d0e418ea68b6816e8cde60a007b5fab596819a5cdf77dc4140 ./.opencode/agents/swift-reviewer.md
|
||||
f58fbb98fbe250169d903f3f3233564ebab9ec73db96418adf0a5d9db26ed389 ./.opencode/agents/test-engineer.md
|
||||
@@ -17,76 +17,283 @@ c989a2513d0b926f3a202b0616426c7443594ce72896ee91c29c4e83451d433c ./.opencode/sk
|
||||
57f91677056a59e48748c63557672361cdb24bfa39264560df0209bcff0fd919 ./.swiftformat
|
||||
2c0c375f3f6704a43e1042b250e0b633ba740aa7bc2fbf5518891a7b5464507e ./.swiftlint.yml
|
||||
3222c8553505401c967cc302e2d46a99db95f98d92650f6b245e2a1dc901bea9 ./AGENTS.md
|
||||
52b02a06a5fa40eb610a19c4e83564fb6c5b3592e25a63f271bc42eb75a25924 ./App/AppDelegate.swift
|
||||
c36aade859ae4432a04f5fb050322e1c78a6e535c206a18b61971809c0fef4dd ./App/Info.plist
|
||||
593745fab27436e91148de34b7e0e530cef5137e2c566cb479caed033602b949 ./App/AppDelegate.swift
|
||||
1461fb881c44cee037051e78a4ea1e36ad459abbab1fc7d530ad993687520d11 ./App/AppEnvironment.swift
|
||||
dc41f554a88b5b499840f72ef676b31530e6ebfcc5da636155001c52ca48d8a1 ./App/Diagnostics/DiagnosticsView.swift
|
||||
69f0c24937507ed7a9137abfa95fdcd2798cd909dd74642d4b5e6a859da94253 ./App/Info.plist
|
||||
36aec6e936e6ffff104908b370a7231b9283e178df8d0a453639dca9c573460d ./App/LaunchAtLoginController.swift
|
||||
553ade6c51a4532be13593e95684c0cc3403e7222f1208bb36200f96915d5e83 ./App/MenuBar/README.md
|
||||
3099e4feba33120e9ce41e3b8701d8fb8f305b4fdd965336950c3bb7e0e38c50 ./App/MenuBar/StatusMenuState.swift
|
||||
3b001166f13cac42136917cfde0277c6cd8cfa922280832a4065081b822b3f9d ./App/MenuBar/StatusMenuView.swift
|
||||
c4a25b6c1207197109d12ea740dc15ad8aa75b6304d901110aa3e10570cd65a0 ./App/Onboarding/OnboardingView.swift
|
||||
ba9467153908c81fbb2497d5679642ae15c7b9fa23a10ca9b9ab678042aab222 ./App/Onboarding/README.md
|
||||
382661bb55524acd7a686f215f8dd1cfdd4127dc19629dd637204c5b1e0734e9 ./App/Panel/LanguagePickerView.swift
|
||||
76dcf59e01ae8319d4f0aabc5e600c549adaf56b6db802794804c3215be9377c ./App/Panel/MarkdownTranslationView.swift
|
||||
0d8e9dd5c361987e717e5425cb3a4bef2849a3ba5f40d302a4074f4847abf45b ./App/Panel/PanelController.swift
|
||||
6b84571bda2bd12e4990430d098d081871c6e239782f5c2e07650e3f7cde6dbc ./App/Panel/PanelView+Content.swift
|
||||
5a76a652c8f5b03421f475211a4beff98037092004dfbfb54fcaab18fab67b36 ./App/Panel/PanelView.swift
|
||||
bd37b327672595d55c263f109005b816406cce5928ac58c66286cee0f5d16531 ./App/Panel/README.md
|
||||
9e09591204b9ca4518a031fc856b0cd01245fe8c4e14aa7238e75a83ab05d4c3 ./App/Panel/TranslationPanel.swift
|
||||
9e8223452ecc9eb20a4e0395d225b93871c4fd2cccbdfe58880620c30d3bb047 ./App/Panel/WindowDragArea.swift
|
||||
718f35bba5763975e162109095348661d4edfa1d8f167da04376fbdc71cfc7ad ./App/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json
|
||||
183606ef4431a2099a26983fac8261ab4d8fbf5fb6ff0204367d3a51e11212ce ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_128x128.png
|
||||
5e90d81c2decbf8a5c4fd5624e976cd4591f4f53c4c4a40e146d8bb1872d2353 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_128x128@2x.png
|
||||
968a49a8667ed72ccb608b39fe28afc3f95cd4ee8689d567983ae0dafd6978aa ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_16x16.png
|
||||
f7fb7b04d7936a965befe202545fdaccb69d7c0c95a99449a27c9119d0326991 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_16x16@2x.png
|
||||
5e90d81c2decbf8a5c4fd5624e976cd4591f4f53c4c4a40e146d8bb1872d2353 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_256x256.png
|
||||
182c8e94854779aefc2f19115d04abb2c66493537bd68f7c5448ae9b9161e38f ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_256x256@2x.png
|
||||
f7fb7b04d7936a965befe202545fdaccb69d7c0c95a99449a27c9119d0326991 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_32x32.png
|
||||
77e828091f2a32d6e233182320842921ae6770c33db8b1dd25800c2e88bfb835 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_32x32@2x.png
|
||||
182c8e94854779aefc2f19115d04abb2c66493537bd68f7c5448ae9b9161e38f ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_512x512.png
|
||||
2c8e82d99378ff2fe0ca98754a3ef29861f0130c54008634106532d0754760d6 ./App/Resources/Assets.xcassets/AppIcon.appiconset/icon_512x512@2x.png
|
||||
f23266b9672263c92ced1d26fe4dafa75a14d530eb9bc5fc1f599034d597ab48 ./App/Resources/Assets.xcassets/Contents.json
|
||||
ce0c088300a0a739ecc0a73892aad6b9538397d637760962a810dbf65692f62b ./App/Resources/de.lproj/Localizable.strings
|
||||
ac67edd346d0828cd0e86cae4e3da719a9e574d22217f0f15a6d30558bd76e14 ./App/Resources/en.lproj/Localizable.strings
|
||||
5c2e5222430e1822c3e13cdfed202f54cabc32beefb7651af78475b29494dcf2 ./App/Settings/LanguageRulesSettings.swift
|
||||
0be6586ef0653cd8e5dd12a1b195c236d54fd1aeaf09bbef48da43195e78b6c7 ./App/Settings/LongSelectionsSettings.swift
|
||||
dcdaf8761f3b195e8c8d8889b2b792aa3dabbaa47b0c641fb4db4cdc09436026 ./App/Settings/README.md
|
||||
3066bb45d7b90e3ad07931f56dc234b4b3481c40459842e00430b6a66ef28308 ./App/Settings/SettingsView.swift
|
||||
d3dcb4365c3d9ec39fa379b8e5cc0813745acc68dc851a85b4ab277896a2a5b1 ./App/Sprachmittler.entitlements
|
||||
3a384017b5b54049c946a674f8263be61f445b8f1ff6f48cdefd70a4bfbe2b00 ./App/SprachmittlerApp.swift
|
||||
8bad14fa182903bd8f17cca19edceb0b779246f9ce858ede63cd6b575c2b2265 ./Makefile
|
||||
ddda3377a2e130e25195da349dd0964cfca8a401464b7b0cd8fcec6bfb575fa3 ./App/SprachmittlerApp.swift
|
||||
c3d0de679f6d151f46cfdd11577eba65e1cff1f82be669be32e42a99fba302ba ./Makefile
|
||||
0608007aa6ef1a3533d5e5b4d021e753efe89d24dea881d5ed443429a43a9de2 ./Packages/SprachmittlerKit/Package.resolved
|
||||
8222951112a60723d1d9a65aa00a152f9138d10c4c8b3dc6e7c47bf2b5c46bf5 ./Packages/SprachmittlerKit/Package.swift
|
||||
44627d4034cde7e11afff37e9b7b99b8384b2291db657f9914a5312ff8f5eac8 ./Packages/SprachmittlerKit/Package.swift
|
||||
a6b0221a7c806cfbcb6007c960772ee1c063c0b85727a1d1fc42097baf6dcd70 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AXTextEditor.swift
|
||||
9c7c19d9ea7d8369244447772a3fa0c3fac21cec0ec22b9df700555f4113a22f ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/AccessibilityPermission.swift
|
||||
348b56aa312a253c6a4de1e1af51ca6b9b5c4e49b86aaf7525f43c180ed17937 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/ClipboardSnapshot.swift
|
||||
2386c6d9f5637e4be701eec1296240dad71211509c971bc7dcc334c975f4b9cf ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/DoubleCopyDetector.swift
|
||||
ec2f66d1a2d8ebb308427802f54cc70c6bdead8c31a57ed87648446d6bda9ce1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/FrontmostTargetProvider.swift
|
||||
85abecf8ca1b15fe1a9d5dbaa0caee16a38a4408e932f6115975d9823a2ac47c ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/InsertionCoordinator.swift
|
||||
0b8a8223e67d0c94551c1dd68609858602069d0ecd4eda736f988880d1e04464 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardAccessing.swift
|
||||
4ca88b4f08515057738a45c9ae475260e3a840c1d5bb3d4622a57ce04f5b8cb1 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardTicking.swift
|
||||
dc5f5b08ec537ac917c96b7ba4c1881bfdfb7c21e166a4f9ee1f6d9e1289b351 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/PasteboardWatcher.swift
|
||||
26aeb81883b8216f364215602b804a2d6e6994a221f9c910c0ed52cc70d4c3aa ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/ServicesProvider.swift
|
||||
dada1b00037d12da0df03a24d1140e428beb9488fde7e0a9d99d0cca58d1a4ca ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/SprachmittlerCapture.swift
|
||||
728ab857854f1f2bb46f032a13f6d47edd491ee0d6ca0aa8bf2b98f91ccb3c23 ./Packages/SprachmittlerKit/Sources/SprachmittlerCapture/SystemPasteboard.swift
|
||||
7c580669d76ca3154889a2f3045a1e2689c8984398163496e0ce4cdcad9ae880 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppOllama.swift
|
||||
9030a1f039515cd92b2178f90649cb028d248a941f16e2d1fc9d52663d7239d9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings+Codable.swift
|
||||
e2ced0cedfdbea4621ba9d01907a56e80001770af0e7e41b31712a042d0c451e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/AppSettings.swift
|
||||
a150f68cc08fddc17c09dea5bdb4d85b1b4c3035fa4a9f8a24c48efd1fc0f313 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureLimits.swift
|
||||
d711719fa15d25c28c7e29c1a8773da9da61ff0372917ecf684fe27538e1decf ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturePolicy.swift
|
||||
02421321864ecf0540a96b55a692e91eacb9364d579735d20b9ca94ebcf99a80 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CaptureText.swift
|
||||
3ce80227fe4f6cfb9efc00d83cb4bff28e870fd72aa29d8cc03a723e8694a34e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/CapturedText.swift
|
||||
2a8c7b261b3c955547fd88520a9582c5c31a1e86a4c13d8bebfbe1d4b8f752bc ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsStore.swift
|
||||
3275711919331a617e9db199e89d6ba5a9c28d518eea4a590fd9dac74c7bd876 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/DiagnosticsViewModel.swift
|
||||
d81ffb9aedc1feef70af050f55f3d0bfd85a828bda80d54d32e5a0667e05bef9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/InsertionTarget.swift
|
||||
56037f9dc0096e9e5e0a44365fb29ecd3185e8c39bb7ee156f31ec08e1326ff5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageAliases.swift
|
||||
5d78b5e2aafd267d0e6eba66ae7257dabfc1dfb4b913e78754f7ae128bddfd4d ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LanguageCatalogue.swift
|
||||
c2fcbae9e59d203f90c7f21a92d3c46ffa9c04d916a1565d16b90e4fa1b361fb ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LogCategory.swift
|
||||
cc89553a898735a1288bdd1c67a04fbcd282f99ee812a83c8b18eff9627ab65d ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/LogRedaction.swift
|
||||
39cec81db2748fd5e01c5d6ade00bae5babf4a68d7d472a69e98b20884585c5f ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/Loggers.swift
|
||||
83b6c93fc950df1fa8e4942521187a0ee3ecb319b5ffec6deef6047ef8d2b171 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OllamaErrorMapping.swift
|
||||
b7dfab9b2c613071b97bc329378eae47b97305cae758221fba787c8be4eb52f5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/OnboardingViewModel.swift
|
||||
0e08aac528b2a8da63f2b2cccbc2a4a134c1dbc49927f3d78115b3faaa2944ef ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelViewModel.swift
|
||||
c52e182fdc6806a06f7b516806140ef26aad8c44e72f9e5beb9135acbe28b878 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PanelWarningMessages.swift
|
||||
563d79ceae06a20e8a5b78e155bfe8489bac8f5267a8c3d064fd5c50ecc66cf5 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/PermissionProtocols.swift
|
||||
761c20b4a1c063ac39648c3d24d8864a0329ff348eaf45db4fb27c573f15e44a ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsStore.swift
|
||||
afd0db8a53c0afb37bafc8647e2da0a8f741e0b7396c018f95c63a80484ea80e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SettingsViewModel.swift
|
||||
b126a8164e50da9c4f276efbc2f591fb94a587b9855a5c9379485ab7d334864e ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SignpostInterval.swift
|
||||
e33ebfeeeb27b88029c20f212769852c5c0a697abaeb1bc249d350e7ad649273 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SignpostName.swift
|
||||
20e3977534de6e1c1af8bcc3049318007213a034aa2e8d2d24032b22e1bacba0 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/Signposts.swift
|
||||
b6580ae5a0f5e18b6b527766cb5acd5de4d828df3badac44ae294dd72acfc436 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerCore.swift
|
||||
fa4aeb76903a93335817a71e80829c6a950288c3575deddc0dd3f89d7a59ce79 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/SprachmittlerEngines.swift
|
||||
2864b92feb24a0616fa546ea2683fbdc9f73352ca64ab84da110e19fd7c6a926 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerError.swift
|
||||
359faa0524007bb58a504b073c854c04736482b893e9509e56843a6850d9e7ac ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/SprachmittlerErrorMessages.swift
|
||||
f75ae67b262e18b53721d070acc0e8d7bdfca94698f10c1a5780ef948ef72912 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TextInserting.swift
|
||||
98de162fc7be182a5832e81f12b2bf72c336abf1a65a6a2c94821b4bf51b39d9 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationPipeline.swift
|
||||
d3511504a464cb986ffad56ef31f5723cf6451fdef04b1e2bf6c58d2be21a6be ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationSession.swift
|
||||
480503eea4bc64f3125560c91d47e56cd9905e957af189a54cdf8b816a380ec2 ./Packages/SprachmittlerKit/Sources/SprachmittlerCore/TranslationWarning.swift
|
||||
5a721207611b9aa6228bc288f5f5e0c57dd26c593ab3aec9bd38c91f9a9e0fd2 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Adapter.swift
|
||||
06bf6da9127b3a010cb33b3db091e4301b32aca44f8cc7181ed1c34b00ece7b5 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Languages.swift
|
||||
0b5e6571d378577091f8ce3b86020545b45ca2c3400afe88ebeed7b4aa8b68f8 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3ModelPreset.swift
|
||||
dfbbd5cfa397340a38b844307621c26e28708eb36aa91095739e492838124c9f ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Options.swift
|
||||
021919b8ff8e27bde4f02b4ada08e2b70463225afdc749d4604db6f84efa85cc ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/HyMT3Prompt.swift
|
||||
fd9c98abd3fccbb77154a5ec7822e3eac3624134b377719078f5549f2081eeaa ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/LanguageMatching.swift
|
||||
90c3ab7c90331c97ff18cd8a00fe2fcf5101b1915c45d5217a7edab95e612ac7 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/LanguageRoute.swift
|
||||
1ad2760062b723e41d46c38fe7b1b4cbe959af417f9657aa12c6f3a6c08f406f ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/ModelLanguage.swift
|
||||
ab9d4fcd37731131646decc9bb9a25b1e2338613ee6b093427c89287a2e9b762 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/NumericTokenNormalizer.swift
|
||||
f00f88c07fc06f2abbf5a17554cb3cb7915f4e60fd32cdf98cdeeb810875add6 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/OutputValidator.swift
|
||||
c473fa0f2c89d4a4f75307e81a6a5d28f1f21f3bffcc8911bb30487d27f64486 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/PreambleDetector.swift
|
||||
50394e1fd104b4fd85cd2b206b146addca15fa21d7cadc5e3cef4ea7f88436a9 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/PromptPolicy.swift
|
||||
5c5b1bfa5f10e2be6ce52f13e7c13143cbcbd7ab3e2af53edd3b13badc228f5a ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/PromptVariant.swift
|
||||
dfe9d284e76ae67a42418c69dae4f84810b9ac7e6d3af675ded1625dd083282b ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/RepetitionDetector.swift
|
||||
5ddee40aab9a5e099ffdb3c7844ae9d19ea44c885a89a774335c66b6927de62d ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/SamplingOptions.swift
|
||||
1a0d4d9149432f7771a84060377eda2589d14b9041d9f296b871dc4ae3e92718 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationAdapter.swift
|
||||
edf6c7617410a9ef2f6f0ea4cdf22e12842543d77f88f268075baad0749b74ba ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationDirection.swift
|
||||
8969928cf7b9a71d9aeb2ee36fd6a70cec1c7ba9fdd5f42c23d4bf28e49a43b6 ./Packages/SprachmittlerKit/Sources/SprachmittlerEngines/TranslationWarning.swift
|
||||
418b1f3737fcf926815055c4f4f3409b292e6afcf0d6b81f37d1160b9f65ac35 ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationManifest.swift
|
||||
43d7f19f92767fb2109dadf939ec4e829a58bd738f81c8abe7b8f3c92e58f9bd ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationMetrics.swift
|
||||
dde82951a4e969628d80b224771124fa70caaa2ba0b447366343d5a99dc0361e ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationReportWriter.swift
|
||||
dd445421272beed0c28e0c2f853d267fb6c8832a313cf836f6c2e47cf024b574 ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationRunner.swift
|
||||
83f6c78029abb6c43c78039773f601752411f0f8f23ec3a9891e8008b70387b6 ./Packages/SprachmittlerKit/Sources/SprachmittlerEval/SprachmittlerEval.swift
|
||||
887b767c70d1c765fc73553439980c4216bdc278d4b27f923bde04378cd6d6e9 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/SprachmittlerOllama.swift
|
||||
a517bee61c90ae280f6d8893e998aeff3ea4ccdcfca08a006287e1b4750275fd ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/SprachmittlerTestSupport.swift
|
||||
c5a26fded64056855f876a6a2c0c466afbc3f5fce1de2323eb073da9ec09f256 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/AsyncSleeper.swift
|
||||
58160c8c41ba81d72aa96dee583fa0ffc5fc64654da3a56f608c67c62aa49352 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatEvent.swift
|
||||
0817f2102a866ce7c0bfc06fa8504a73294e75a6fca70ee0578ce78216b42147 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatMessage.swift
|
||||
363bb249519c2b2d67a6a0c516bb5b113298545cad1a575593b5212702418acd ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatMetrics.swift
|
||||
38a5c0272aff387a1ba70a073559a97d2b31b4b9c4550c0540a7ddbcd8a93705 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatOptions.swift
|
||||
7ecf5e465e8cb14182396e850ba8640c74d1a0d1fec3f8c39d288d0ff89cf750 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatRequest.swift
|
||||
f22c1caae9a722373605504cf9a3a268497f3d8683548e0b75b417042d3af9ed ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatStreamContext.swift
|
||||
9944f8e250c2b334a9129a82281fef45663043a5b0a3bf01acdb114b68c565bc ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatTimeoutController.swift
|
||||
4f850d29de8d81ff85e0a3602cc72029f675ea37d56481e75aea7d5b5e0d087d ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ChatTimeouts.swift
|
||||
f158a61553f38138d6e8a08e02c15de949b882898273d9c13b857401a01df7a5 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/EndpointPolicy.swift
|
||||
eb3bdca89e3e15d2c9300e0f92ddd36dfde28d6105e87ee3c4ca29171ca2152d ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/EndpointRejection.swift
|
||||
157abae634245d3646f16e2742ecaeae72adead8c10f6d1ab3dcaa02b5766ff6 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/InstalledModel.swift
|
||||
312b3919d01d0128b57db111a579b0add5b89d7e8010ec270aecdd9a3ef38dac ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/LoadedModel.swift
|
||||
88ea1a3e0617aef24ddcff51073fc30b27974b9bf8454ab8288e9f003240cc11 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/ModelDetails.swift
|
||||
ab586304f68d4e46146577438db1560107eb8f713cd0f4244fb0ae3344496742 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaCatalog.swift
|
||||
68491c3709467eb22a9d9c21ea72d7ef3a37ab04b6acde496a714e772fd3c3f8 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaCatalogClient.swift
|
||||
1ff7419acc3a2401faa719eb0e8955a318ebade41b8718a8bf7c52abc5be2c7b ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaChatClient.swift
|
||||
ba536c52aa94cf7e48dd98b741a41234b3f8709a38503ab264998da281d44dbe ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaChatting.swift
|
||||
5f4ee95364526a59e0776207a1e93ce6cea5eed3473bd5686a8674a425824401 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaError.swift
|
||||
711780019b33a02bf048968196f04b04a4f996ea9d0e1128140b153524a0ddf9 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaErrorBody.swift
|
||||
0020db5fc620a8a188ec0e6feb8d903bd4d849c87808efb8b85449c4056e4bf7 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPClient.swift
|
||||
d76d67d55efc70289aeed9626265c3f6d183b001c4d36047f4e8962180a18ce1 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPRequest.swift
|
||||
c32d05b70ba04d525064a2ed71f5ea67d1655d72c56f9d185aefe4250840321b ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPResponse.swift
|
||||
232e1e3d1eb070a353e72f301c82a4f3ce56c874f8754fddb98bf71a5a816798 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaHTTPTransport.swift
|
||||
92753142b6151ff867de64d1ce93ef1e975c3b0e7cf15f36b23828f3346e0275 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaSessionFactory.swift
|
||||
15038cb5553980b00888fb763a8950da29e9c976fdc5288c0421053e84aefe4d ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaVersion.swift
|
||||
58d527fdb66f62fb6b7009bf454b94ba0f6ebd19c3686d91c5f598154533c830 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaWarmUpPolicy.swift
|
||||
443eefc6de2a8196735ba2deb207bfc36f46b1217e7873db9115c69f6db26921 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaWarmUpRunner.swift
|
||||
314982eecd8a75575e2c25fc776ac785c8d9e99d035a645480e68b946d007a43 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/RedirectRefusingDelegate.swift
|
||||
2c4ec4c3422d65987661842420f313b48c17bb5785b6b8be28ea07cd8f95d02f ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/StreamLineAction.swift
|
||||
54c856650277c61b2e6dde34120eaae59a7b354d0ed621f5ac8634684211b030 ./Packages/SprachmittlerKit/Sources/SprachmittlerOllama/TimeoutPhase.swift
|
||||
9a8d1d437e08462d0f063ac0784812b0f8183dce5b4251b28c5c064e4a47d3fe ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeOllamaCatalog.swift
|
||||
54076808b76b6efd5ecb174403210c331d1b674b15120400323c0623e9e3ac85 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeOllamaChat.swift
|
||||
1cd84966052430f540220cd7bd22203b8a77574540a66700288e588e9b8efb52 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeOllamaHTTPTransport.swift
|
||||
524e816552afe34f8844a1c01bb56b6bc81fc5a83cc96889a25bd044e73dc0c0 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakePasteboard.swift
|
||||
03d570bc4022f205abb52da509bd68444879308b14f46bad497cadf9f80f3845 ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/FakeSettingsAndPermissions.swift
|
||||
16e6ae7d693df1ee6532affec1fa687aeed1e709595b929f2a4e1f00e1b9d88a ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/ManualPasteboardTicker.swift
|
||||
c0f87a5320fe715f5dbc7c9bbc7c0fb19a5b64d1c145c45b26f060c151eccada ./Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/ManualSleeper.swift
|
||||
0ea5a0c60c2185262e52f71c78538f9b1bb308c9835dc2362f70929da9bc42cd ./Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift
|
||||
b639d452d78dcda9e9f3b5ac3298e8499a7837a955839ae5203b508944df2c63 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClass.swift
|
||||
b768d43f50bd4fcede0f3c654787771a605b6ea2648cac722d0e78dd913b4fa5 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ContentClassifier.swift
|
||||
9eebbc1339104d8a0b0f9f579d0c9f0bf69b05b5ad1a4550cf645ca3197686dd ./Packages/SprachmittlerKit/Sources/SprachmittlerText/LanguageDetector.swift
|
||||
41aeff6d807caa027f9496a4bd6048bdde55d6eeb4a11b2acdf445dff39735bc ./Packages/SprachmittlerKit/Sources/SprachmittlerText/MarkdownPresentation.swift
|
||||
c7591458a2fcf4813a166cf4f15aaca69688a85e319cf71ebd5c2dcffba756b8 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ProtectedToken.swift
|
||||
2ec31538fe5a2ed98fcce6b815c1844cfd30a53073f4987eda8043bcd222d58d ./Packages/SprachmittlerKit/Sources/SprachmittlerText/ProtectedTokenScanner.swift
|
||||
6ea915648616c12b9b2ae3bbb97838a512c6c3a91b2bccfc13e144d950d4bb6e ./Packages/SprachmittlerKit/Sources/SprachmittlerText/SprachmittlerText.swift
|
||||
8a349b1fdbd3755bec2f6ef45ebec31af96be8857923e3d0f79696f5c98eeffb ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/SprachmittlerCLI.swift
|
||||
4e05396e9e2f915d450af13f57dde523b961d1ba204bffdb5c94db4ba0d82941 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/TextChunk.swift
|
||||
f528068c473ed46c7daec43a1306b7bd50aec76bf3fc353bfd86fd5e18388854 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/TextNormalization.swift
|
||||
383da4ec8485cf7457d9e336978ec8b4a6d9f49cbfab8db70db45dc833decb56 ./Packages/SprachmittlerKit/Sources/SprachmittlerText/TextScript.swift
|
||||
b2f837437ba28548e74d43a2a88bdc3f2e79d3d1e6ec16b381af04256909174d ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/CLIEnvironment.swift
|
||||
d775cfc21b88687a443118fc0d12f6c4837f712ab674b12286f87470a33bee8f ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/CLIError.swift
|
||||
7475168734bec7883f4f911af91e4a7184da55849b853eaf7429ae20171d3db9 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/CLIOutput.swift
|
||||
9c0e6beeffe1ac02e5f32d24f2fe78159183719414978a5c9bb9752313805777 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/DetectCommand.swift
|
||||
d4ea1f2538934b1c2ffa69fd905c42194760a535a54ac4d241daa616530f976e ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/EndpointOptions.swift
|
||||
57a104206b2e662d3fd8e5040b422242744752a90133f2f902771d1d73e6d62e ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/EvalCommand.swift
|
||||
48a9061c6c40d9bd32a55635873e64f5ed7f97edc97827f78979c7b74eb55a85 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/LanguagesCommand.swift
|
||||
aa686ae5d4b40d290b7963a2ba97dab4e3ae8c2054c0df09e9093448408dbcfc ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ModelSummary.swift
|
||||
97d119e9c05d62a527bb255ac67dff9049d76a7c11ac292b7ed0ce11b63c1cbe ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ModelsCommand.swift
|
||||
b8645b487845964dbc060c2a99081d7f89ca5026fb6ab5be82433bf1aa0c1b18 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ModelsRunner.swift
|
||||
b0125112472bc642661bf0233f0b7cf1bce3ef7f511c333f73364152b0527213 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ShowCommand.swift
|
||||
a2e96139102375e8586a1568f22d44317cb0034e62c977ae45fc691126c4114c ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/ShowRunner.swift
|
||||
1c9b3e180e4ce78c5cf10bba99edd6c36fa9fbac85e4062dce84d396693e1776 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/SprachmittlerCLI.swift
|
||||
78d1933ed58d565c2cc5b5463e8c99b3dbcc379f77ec956c645085912441282c ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/TranslateCommand.swift
|
||||
d0e8bf434a42ce93fba7e611b26797dd5b7d20cd0c9468524fc14ef84b3abcc1 ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/TranslateOutcome.swift
|
||||
e7ec098ecc2e0c3f62ba53cd44afc0659b77b7baf2d5ab307cb4238c1f6efa5c ./Packages/SprachmittlerKit/Sources/sprachmittler-cli/TranslateRunner.swift
|
||||
3466e030b39a884371d10ba4a2b9ea1a05b7b053af1bd0cb88aa046ba1af2067 ./Packages/SprachmittlerKit/Tests/SprachmittlerCLITests/CLITests.swift
|
||||
57fbb191c4bf3a9325d5fdab1cdc950bc6e2579f12ea64442c8b2dbd56b79cf4 ./Packages/SprachmittlerKit/Tests/SprachmittlerCLITests/SmokeTests.swift
|
||||
d4e110c510cac46c1acecc68f28ef8b30daaf1f9b623f0533ad359a6a13680aa ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/ClipboardSnapshotTests.swift
|
||||
23e0c52e3f5f9b5848ff9118bfe3baf474a21c830560be382b978328e794218e ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/DoubleCopyDetectorTests.swift
|
||||
efac77b258ef29cca1cc61311ef8d167e45ad5680a73396a1b4bc6d99d9a3f45 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/InsertionCoordinatorTests.swift
|
||||
c23c58fa553049241f4c40193d41aba4fed8261f1ece4f32bcdf65af25abf099 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PasteboardWatcherTests.swift
|
||||
87e92d608b14675873a6554a3bcce951fb62b45b95ce32972df978cada697a43 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/PlaceholderTests.swift
|
||||
d2d3507f437c7126bf15ebcba7be6d03794a73a637089c511c99096bc564cc5a ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/ServicesProviderTests.swift
|
||||
f7375e2cd08709d7b590ae4f6d70be3edb88f122f9fb3aeaac37c826ff637d12 ./Packages/SprachmittlerKit/Tests/SprachmittlerCaptureTests/SystemPasteboardTests.swift
|
||||
8eb9ab1b8b15568295aff0b90640afad7f1a38ceaf3dfa2145a0a338f7071d57 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/AppSettingsTests.swift
|
||||
2ea18f23e2328110fa6d61e51ecf4607eea7bb82d1c8eeac5dfd844f07c3a6e0 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/CapturePolicyTests.swift
|
||||
2d5742a1fbbb65044455cea92b9f95b9d39f5236e92e4f152b141bcf964c639e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMappingTests.swift
|
||||
c584df764e9fa0a029ed9f17c1a3b27cb4e3b91005f27171d5553aaf51edb48a ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/ErrorMessageTests.swift
|
||||
95ca20f1c4cf0fd68f29a488770a1d6d7911c534913a0f88515ea1fe4f4cdb9e ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/LogRedactionTests.swift
|
||||
6610797e6dd77401d1bce624d65e84db9bdda95820b1f56add1d24cea1f5df91 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/LoggingContractTests.swift
|
||||
8c0462d50ff3796aba6024349083d8b1ede654b495790d7610f95aecc8870001 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/OnboardingAndSettingsTests.swift
|
||||
fa5572b8825c7cff4c21f45e5381cb746606c270a45dee75e304be684b64ce1d ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelChunkingTests.swift
|
||||
f8f1ecfe58f003a0713ee2948c06a7b0ea18272319336025a31f87618bd56f0d ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelRoutingTests.swift
|
||||
f2071269097a49ddd38a23a213920d09a7786201ef7eb68199a8eb90a4bee303 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelTestSupport.swift
|
||||
667624e7bc610bbecf323d4401787082bec3e3a2397bd1de86d1dca897e1082b ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PanelViewModelTests.swift
|
||||
e9fe1b63792e610bac81153c6bc79d4c836c36c4c9538b26887daf62e9684d80 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/PlaceholderTests.swift
|
||||
5671265556115fe93adb7ee3ccd39a9f31786c7da2e022fe9914db06e5555e24 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationPipelineTests.swift
|
||||
641482d5c4e8540861775d67d007d6820e1849f6e7b3d2b0456ef462434ada79 ./Packages/SprachmittlerKit/Tests/SprachmittlerCoreTests/TranslationSessionTests.swift
|
||||
988eb93a5d1483a6db061c1a11d5b06d7632157c076352c435418152f47910a5 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/README.md
|
||||
86bae20b590f03748a5b498a0ae402d7bb10fb0b7ba7bbccc821fcbbcba8ab37 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/default-prompt.txt
|
||||
86fafc88be2c581fb3eeaaace4320c9e6eb8bda2d89b757cfcb3ce1b4540fe74 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PlaceholderTests.swift
|
||||
615de4459d2d77dac87809bb33af42d32ab624cb5367d1b3b9de6841d4935bc3 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/delimiters-prompt.txt
|
||||
4cb7a5de7d493e2b21826322dc38b4d31415352c609f3b68b4786bd12bbdac42 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/structured-data-1-prompt.txt
|
||||
cb657108c3f9b6f1b3a743313d2b6622ecf7b039ce80b8b2a1da3bce78451751 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/HyMT3AdapterTests.swift
|
||||
ada2bbfcf0213001077d55b475c3c2ec764623ddf6bd70e62d73d3dc08c99dad ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/LanguageCatalogueTests.swift
|
||||
e56dc9de2741d731b02ff3bb39ee74532ac4350d232eb66fac86ffb770cb7a86 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/OutputValidatorTests.swift
|
||||
7d1c6fd3193bcd169be2421a56e42fca82e7e44a5a288dd6482957ab6c50af21 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptFixtureTests.swift
|
||||
8bb2e2310a40e5923fa77014ac5209cf09cc8a52056a22cae9544f3468e1d2cc ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptGoldenTests.swift
|
||||
d93aa1ae54f4a6f49aba4f2badb065a86d29c335afb6efd0890684759718a3c3 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/PromptPolicyTests.swift
|
||||
1824f05ed6f704263fbfb70cdbe07fec85812745b1b71133be2781c380963db7 ./Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/TranslationDirectionTests.swift
|
||||
b921811eb2bad2cde5a5c199b9c5e4fac710740193789d324d73580d2b8c7abf ./Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/PlaceholderTests.swift
|
||||
78fd25235b625f82115f3d14c6a9863949055fbead95c9ef83668866bf255d10 ./Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/SprachmittlerEvalTests.swift
|
||||
e9fe1b63792e610bac81153c6bc79d4c836c36c4c9538b26887daf62e9684d80 ./Packages/SprachmittlerKit/Tests/SprachmittlerLiveTests/PlaceholderTests.swift
|
||||
bf9501d4defd98c8249b5524c2113f00e27e05a279548a8cae4fd441b370d256 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/EndpointPolicyTests.swift
|
||||
1581a9133daf1294fb224820af9c8c265a03b73eac959ff921b213107881940b ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/EphemeralSessionTests.swift
|
||||
3552c16d0da451db9b8d9cad3375d9dc4d716003dfb6afb89b6ca92c99d4fa2d ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/FixtureContractTests.swift
|
||||
c48ac2946761e46da0d2eed81204e97a7fd96361b55b44a289ccb56587f6a83b ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/README.md
|
||||
0c2d6cdb4ea5255e9266dee670a8a1d84ad4a27549c6e8a4f8d99eccf6677eab ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/capture-meta.json
|
||||
4157b4206f99f974ce4a6d54f1816f8912f409368f63206d7cc65abf6426d50d ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-de-en.ndjson
|
||||
944d0baa3a932e0bc42ed0eff59a055f2cf01e1a1e2cc66a051ba3a82e8e1f84 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-en-de.ndjson
|
||||
398ae470bf8bc88df8a2d1c1f15289e62cc941f162774d3a5469dd6e3b907378 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-markdown.ndjson
|
||||
e5a38a0283dad14969131052bd8daf60132c783af10945b6d03aff71b89e4b58 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-truncated.ndjson
|
||||
4bafec6db42fb16e1901cb8f4de666c52d9a270c8fadb5e3359b10be7ebec80d ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/capture-meta.json
|
||||
b735e23f9edd09a19969869fe5db53b9924214eabd57932a3a371f8cbafc30de ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-de-en.ndjson
|
||||
7f6f9589c6ce4f4bc542d940f1eb72210acdab4ae39c93e79df40df1b87a2270 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-en-de.ndjson
|
||||
568503e59cf16924996dbfb2ee50a944eed20768fa637d595caa358a91a4ce88 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-markdown.ndjson
|
||||
1a9c3e41b0fc5dbd6d97f1b9bdff0d3db365ccb2621785b8ad34454381cafc99 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-truncated.ndjson
|
||||
2f0cfe6365fe218b3c9ecb2f2a712bb53ebfea811982a5a0d9e4f32076ef3bfe ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/error-missing-model.json
|
||||
a8f7899f295520b026b56e103486fe3ff8e66eb35db9c457f44e36c8a45d8fc2 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/ps.json
|
||||
f1410d0bb4a28d89c049fd9f9cd7df5cef24780f246225de6f1a7c38db5f41d5 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/show-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M.json
|
||||
4e7e6b8cc3ec35a6e3e69d96335ae12fff289374e9cbdedfe0563ec3db8941eb ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/tags.json
|
||||
fbb02594028ba766fe5f93bf8a5b62236841fb9d051277e0dc633f87e2c2d396 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/ps.json
|
||||
e3844615abca9419b448745038c8fe2f9813ea0a56eccb1e34c57be879071a1c ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/show-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M.json
|
||||
dec441bad497eeb245c9b28d2a231a4859762b82b8a4b0b07ab0211f5595ea24 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/tags.json
|
||||
672856105eb7e7811ecbae8fcd189743b8fd44aece7baad3a1a781b5a41c43eb ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/version.json
|
||||
a32b7bdc7476fc1521d3161560ee83a3c7c2ceb83c0ac7c2c0ee22d8c869240e ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/PlaceholderTests.swift
|
||||
a4a387099e42bc0bf9ebc1ffb43e3a0aab843d70ef3d5a09590b72ec9d53fe15 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaCatalogTests.swift
|
||||
da75e1c796f1889f594e9cd8bb4d32b1a11d7d4977647cae7e97d352b1545b55 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaChatClientTests.swift
|
||||
6ed315b6389a479f0bc25865182e76ebe32a6bbca5c3be63c847a0ecac91ca90 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaErrorBodyTests.swift
|
||||
ec4e2973a3933903563b1955da6213f2931b4e961fdc2bd8d40ab1d5577cff48 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaTransportTests.swift
|
||||
4f388b8c70fb6b890d4b2fb86c338b837a7991a3592c3995038946c2df8e2e40 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaWarmUpPolicyTests.swift
|
||||
4442060cc5810f0a0332a0abd05b1b9b54a73bf0045fe0fdc94b543a56238106 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/OllamaWarmUpRunnerTests.swift
|
||||
deb3801d380aaa32228732c60b70ac576ebc2563f1dee8854215f2ee1a1004d7 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Support/ChatStubURLProtocol.swift
|
||||
ecedbb779b022a8d87a385903040d49aa9d1ee144c2ffb58dc50ea58d297f630 ./Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Support/StubURLProtocol.swift
|
||||
766a76be19e12928f2cc39cb1e905de6da07eea86a68f19247464af6a163708c ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ChunkerTests.swift
|
||||
a90dc29af451dac1557a88081a53defcffa8d21fdc0029d7fc19bc3a34d81598 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ContentClassifierTests.swift
|
||||
74e7640a50e5cdc77207700b4a76b608abc88de48464ee76e40c07d9db8c4bf1 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/de-sample.txt
|
||||
f9ede3201de7a3d092b2f114dd7f131dafd3b2d6614c0ba91d6181e326ab005b ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/en-sample.txt
|
||||
b0a7d3451d8830654fe79476b8d32d95709d956817a4436f58c0f73bbd8d3194 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/markdown-sample.md
|
||||
6ceff5d7b34dc4f4099c1ac8415f89b680f64608c3b9e140c4dee1737cf2477b ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/placeholders.txt
|
||||
436ed18c9c1cd8bf15df11e2c2f9ca974f9a6f17ca8b894e5ffef999458653fa ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/LanguageDetectorTests.swift
|
||||
80d28cb607b67a35cda89d86e2819e29e71b38e8234557683cb7c96f611037d1 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/MarkdownPresentationTests.swift
|
||||
8c5c21634d749ad05da8b6a0fc1d8e132a494177a697ba0a1338a7a6b5dba50c ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/PlaceholderTests.swift
|
||||
dc45614d3b3268dd5081f8678f1bd4231dd73b067b49b088271b29362563bb8c ./README.md
|
||||
de21f0e9556ed2d25289c10041a913d1ea55470a4951d05880921cc1e809d964 ./docs/ARCHITECTURE.md
|
||||
67c0f9ba9e818267e99c1756b82643f7e59effa6783325675386aba0a1002cb3 ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/ProtectedTokenScannerTests.swift
|
||||
c3294d486cfe44a6f0a69a1ec05cff33a8eccf090fce04fadffa96b6b2563d6f ./Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/TextNormalizationTests.swift
|
||||
2d902ce53c14b6d64a578bdcc99845b6375a69ced37f503423c9df6cbf3c15f0 ./README.md
|
||||
f1dbc2fb876d909b8486239e9b75b09ed68516c341d586e96d8626715c86a88c ./dist/Sprachmittler-0.1.0-local.dmg
|
||||
b100978fe55c5afbf6b3c987b34e17f3413329d3fd580a2cfcd616f71a564aa9 ./docs/ARCHITECTURE.md
|
||||
018c5faf1a5d2e8d851ab209d45e64993cbd6b7976c4aa90c571359c83e83264 ./docs/CODING_STANDARDS.md
|
||||
c17e0eee0e06c0ee1e3e073545b80eef55142cd1859cfc541e195447b00f68f1 ./docs/DECISIONS.md
|
||||
0186c9d6ccd86c745b0d78068283c7dd786b4329185ef9022f4169e2d4ec1a60 ./docs/HYMT3_MODEL.md
|
||||
7da97c74eb82432130e4cf91b3175504bd2c0fc3b1227be0efb872df922feaa6 ./docs/IMPLEMENTATION_PLAN.md
|
||||
0eddd31ac7f4ad295720b9081896200d622f28ed3a17bdab30f57f557d980bdd ./docs/DECISIONS.md
|
||||
5b80ea8994519f2be34aa10abb345ac3029d3d3a29705dcfa0a1cb344f4b95d2 ./docs/HYMT3_MODEL.md
|
||||
d87fc9df926f6ba77ce67b2731b83f48f2b49848c637f12d0fdfb5f27f3c6775 ./docs/IMPLEMENTATION_PLAN.md
|
||||
c3a1838fb0a06acf6b7826f6ff278e15065af198dab22ffb1435dacdc064ad69 ./docs/KICKOFF.md
|
||||
20a87dc7cf8cb593445c89d334e123f6275232524598ac71a21ca32766cedfb7 ./docs/LANGUAGES.md
|
||||
96c63103091dc9c53c4629e5bc830b2ce92eae04e74096ac1ab15d6c3615528b ./docs/MODEL_EVALUATION.md
|
||||
1abe88261cb0c46df94b195db3307ac2eff8ad0c610c1f3683b306eda67ae243 ./docs/OLLAMA_TRANSLATION_API.md
|
||||
b1d9fcfffd9d0e6b3a9792633ad71acdef29a344eea0dea778e132a7c0330322 ./docs/LANGUAGES.md
|
||||
a28161210fbabe27d1348f3552851fe7b30c9dccc658272f2cc79af5e085ec40 ./docs/MODEL_EVALUATION.md
|
||||
6f94dfe4f2146ce0b9e066198c9e05ce659faf4318513ce586c966989fd3d1c0 ./docs/OLLAMA_TRANSLATION_API.md
|
||||
e6dbccc3cb4c7a169a6daaa563066a6764a76b6b7649738b839dcbd9b2400ee5 ./docs/OPENCODE_V2.md
|
||||
1251f24645cbe526b015c5b683e55073cd61a7ee9a34a1a613167b5d1fdba925 ./docs/PERFORMANCE.md
|
||||
e2b785807ecb56eb1e7c02aaa6a487ce7c1be421865685bed4be2e973269bdce ./docs/PERFORMANCE.md
|
||||
4a37cf1815071b3afdd10443ec9e05a5a78411d615c42f51117c5873922531c4 ./docs/PRD.md
|
||||
8f73b8056f62e3310adaa0252dcab035888772f163e03792f88171e4039da5d4 ./docs/PROGRESS.md
|
||||
d69d08cd64f6ae6c6779692c7e2e04dca6ede7729f53790c0e3e71b6fc8aa367 ./docs/SECURITY_PRIVACY.md
|
||||
8707e5bd7db8f5981c49bdfe739be3ca2da9370efd39e8f3450db29b95ffcbb6 ./docs/SELECTION_AND_CLIPBOARD.md
|
||||
c7609798be659d3d96c0b4e1226bbfd66cc0c0b0d583eaba47df37c3ddb70ddc ./docs/TESTING.md
|
||||
381bf8425054d8b4eb6722ecbff4f6d4a4b0ec868bad8793441ed1246b5153e4 ./docs/TRANSLATION_OUTPUT.md
|
||||
6ea3e3881a9f6a7de968128e660a897c648d8e01af77b3e831228b809d0d94e2 ./docs/PROGRESS.md
|
||||
c72f39e7e5e1fb9c45c32f0741a379564debca4b408e702615d162f360d47ecf ./docs/SECURITY_PRIVACY.md
|
||||
f140344de55d11eb450961639ba85a1ff479cf2e0cfb3c8bd3c4cdb2220a11ea ./docs/SELECTION_AND_CLIPBOARD.md
|
||||
8720e8bf79ba7ab051bb8bd09f55b7766f98941904f354cbe3ab7b88c941e860 ./docs/TESTING.md
|
||||
14677683317de607406997825d4ee239ec042c9872f0b44c29ebdf00f6540aa5 ./docs/TRANSLATION_OUTPUT.md
|
||||
5c4d63f01581cdbc21d7ff9da8604adf8230e280b42512e3375cd0a72a225f5a ./docs/USER_GUIDE.md
|
||||
373b20746a6ed145ee598786458a97cead5cacd97a339db14b3e2341645c6c8d ./evaluation/README.md
|
||||
a60f1917c64ac8c3df0d01dd55818652ae100a6d750c34be24675b33226cad45 ./evaluation/corpus.example.json
|
||||
a5c4b95257aa02eca20ae98acf68dee329acb870f16fb3ac549038627327da71 ./evaluation/corpus.schema.json
|
||||
6a54dadd3426cfc011c8b02b9c9b935f6ba4bbbdc5db38ee59377d71a8919833 ./opencode.json
|
||||
2b065f1791c31305ba1e9c018ffd439a04f82110e96a55f05e67311926cfd6e0 ./project.yml
|
||||
e0628748753d6c8952f05c7da78a632632c2fedd6c9632bc8d9c7bba42127e51 ./project.yml
|
||||
749bfb269c22aed25e67b73abfda7055aee645b68a9907f292ef5c1c38366eae ./scripts/bootstrap.sh
|
||||
443548848c9ce9edb9ce54efac6158e6cc63e69b40259dab4edb6ead89972373 ./scripts/capture-fixtures.sh
|
||||
aa9531690d41071e34dfcb33241bb576f7349092d52c36242cedf55af7ca9c46 ./scripts/capture-fixtures.sh
|
||||
495f78822630ac48a91e21a06c5d96f4ffbb4a38b8b7ee5b591faeaeb1fdbbd0 ./scripts/check-signature.sh
|
||||
fb00d11b43730fd5a22a2b9c9d2bb19dda9933507972071d5cf68fe19f09d60f ./scripts/generate-app-icon.swift
|
||||
ff66487399a93eb08890b8b85027df2db6572c85a183baec823b1f697014a7a7 ./scripts/make-dmg.sh
|
||||
85eef8a97a24d834b7119788f11559c3fc5ab40be87ca2a244abae85801d8cac ./scripts/manifest.sh
|
||||
d8f5a7fd6907772e961e129920af66290257b3299beae867639abcf956d71fb8 ./scripts/opencode-check.sh
|
||||
50d0a6b4f78eca45363a7dded4efd1e6332628127e5f634b0bbba1215a499830 ./scripts/privacy-check.sh
|
||||
480dee8c4969ed231f5d58e8c66999940aae2fa707ac964fd19b4671ce1ad83a ./scripts/privacy-check.sh
|
||||
eba6aa14e31e41da73792503e946251691d635a45124d7150433227a218dc330 ./scripts/privacy-self-test.sh
|
||||
52a752481678227da453b0487043f2d0950862791ef75dab71f695f78950a514 ./scripts/release.sh
|
||||
0cf1aee371a3a98429906be86de2832c5649e8212f2eb35a5433990a0b15ad5d ./scripts/smoke-ollama.sh
|
||||
dca61cd7f7833ecb5c72347c526a69bafab7499fe05c21c67f0b8dee71d50245 ./scripts/verify.sh
|
||||
1a17309daafb04fc4880d74df39ab711c33694b6405cc375681d4fdfd9af9f9c ./scripts/verify.sh
|
||||
@@ -4,9 +4,11 @@ PROJECT := Sprachmittler.xcodeproj
|
||||
SCHEME := Sprachmittler
|
||||
DERIVED := .build/xcode
|
||||
APP_PATH := $(DERIVED)/Build/Products/Debug/Sprachmittler.app
|
||||
RELEASE_APP := .build/xcode-release/Build/Products/Release/Sprachmittler.app
|
||||
INSTALL_DIR ?= /Applications
|
||||
DMG_DIR ?= dist
|
||||
|
||||
.PHONY: bootstrap doctor generate build build-pkg build-app test live-test verify app install fixtures smoke privacy-check format manifest clean
|
||||
.PHONY: bootstrap doctor generate build build-pkg build-app test live-test verify app install release-build dmg release icon fixtures smoke privacy-check format manifest clean
|
||||
|
||||
bootstrap:
|
||||
@scripts/bootstrap.sh
|
||||
@@ -17,6 +19,9 @@ doctor:
|
||||
generate:
|
||||
xcodegen generate --spec project.yml
|
||||
|
||||
icon:
|
||||
swift scripts/generate-app-icon.swift
|
||||
|
||||
build: build-pkg build-app
|
||||
|
||||
build-pkg:
|
||||
@@ -39,12 +44,29 @@ app: build-app
|
||||
@pkill -x Sprachmittler 2>/dev/null || true
|
||||
open "$(APP_PATH)"
|
||||
|
||||
install: build-app
|
||||
release:
|
||||
@scripts/release.sh --dry-run
|
||||
|
||||
release-build: generate
|
||||
xcodebuild -project $(PROJECT) -scheme $(SCHEME) -configuration Release \
|
||||
-derivedDataPath .build/xcode-release -destination 'platform=macOS,arch=arm64' -quiet build
|
||||
|
||||
# Build Release, replace $(INSTALL_DIR)/Sprachmittler.app and start it. Not `cp -r`: ditto keeps
|
||||
# symlinks and attributes. Remove the old copy first, because ditto merges.
|
||||
install: release-build
|
||||
@test -d "$(RELEASE_APP)" || { echo "error: $(RELEASE_APP) not found"; exit 1; }
|
||||
@test -d "$(INSTALL_DIR)" || { echo "error: $(INSTALL_DIR) does not exist"; exit 1; }
|
||||
scripts/check-signature.sh "$(RELEASE_APP)" install
|
||||
@pkill -x Sprachmittler 2>/dev/null || true
|
||||
ditto "$(APP_PATH)" "$(INSTALL_DIR)/Sprachmittler.app"
|
||||
codesign --force --sign - "$(INSTALL_DIR)/Sprachmittler.app"
|
||||
rm -rf "$(INSTALL_DIR)/Sprachmittler.app"
|
||||
ditto "$(RELEASE_APP)" "$(INSTALL_DIR)/Sprachmittler.app"
|
||||
scripts/check-signature.sh "$(INSTALL_DIR)/Sprachmittler.app" install
|
||||
open "$(INSTALL_DIR)/Sprachmittler.app"
|
||||
|
||||
# Local, unnotarised DMG from the same Release build. Use scripts/release.sh for distribution.
|
||||
dmg: release-build
|
||||
@DMG_DIR="$(DMG_DIR)" scripts/make-dmg.sh
|
||||
|
||||
fixtures:
|
||||
@scripts/capture-fixtures.sh
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ let package = Package(
|
||||
products: [
|
||||
.library(name: "SprachmittlerCore", targets: ["SprachmittlerCore"]),
|
||||
.library(name: "SprachmittlerCapture", targets: ["SprachmittlerCapture"]),
|
||||
.library(name: "SprachmittlerText", targets: ["SprachmittlerText"]),
|
||||
.executable(name: "sprachmittler-cli", targets: ["sprachmittler-cli"]),
|
||||
],
|
||||
dependencies: [
|
||||
@@ -45,16 +46,27 @@ let package = Package(
|
||||
.target(name: "SprachmittlerCapture", dependencies: ["SprachmittlerCore"], swiftSettings: strictSettings),
|
||||
|
||||
// Evaluation harness — linked into the CLI only, never into the app.
|
||||
.target(name: "SprachmittlerEval", dependencies: ["SprachmittlerCore"], swiftSettings: strictSettings),
|
||||
.target(
|
||||
name: "SprachmittlerEval",
|
||||
dependencies: ["SprachmittlerCore", "SprachmittlerEngines", "SprachmittlerText", "SprachmittlerOllama"],
|
||||
swiftSettings: strictSettings
|
||||
),
|
||||
|
||||
// Fakes shared by tests (FakePasteboard, FakeClock, FakeOllamaTransport, FakeTextInserter, …).
|
||||
.target(name: "SprachmittlerTestSupport", dependencies: ["SprachmittlerCore"], swiftSettings: strictSettings),
|
||||
.target(
|
||||
name: "SprachmittlerTestSupport",
|
||||
dependencies: ["SprachmittlerCore", "SprachmittlerCapture", "SprachmittlerOllama"],
|
||||
swiftSettings: strictSettings
|
||||
),
|
||||
|
||||
.executableTarget(
|
||||
name: "sprachmittler-cli",
|
||||
dependencies: [
|
||||
"SprachmittlerCore",
|
||||
"SprachmittlerEngines",
|
||||
"SprachmittlerEval",
|
||||
"SprachmittlerOllama",
|
||||
"SprachmittlerText",
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
],
|
||||
swiftSettings: strictSettings
|
||||
@@ -67,17 +79,20 @@ let package = Package(
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerOllamaTests",
|
||||
dependencies: ["SprachmittlerOllama"],
|
||||
dependencies: ["SprachmittlerOllama", "SprachmittlerTestSupport"],
|
||||
resources: [.copy("Fixtures")]
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerEnginesTests",
|
||||
dependencies: ["SprachmittlerEngines"],
|
||||
dependencies: ["SprachmittlerEngines", "SprachmittlerOllama", "SprachmittlerText"],
|
||||
resources: [.copy("Fixtures")]
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerCoreTests",
|
||||
dependencies: ["SprachmittlerCore", "SprachmittlerTestSupport"]
|
||||
dependencies: [
|
||||
"SprachmittlerCore", "SprachmittlerEngines", "SprachmittlerOllama", "SprachmittlerText",
|
||||
"SprachmittlerTestSupport",
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerCaptureTests",
|
||||
@@ -85,7 +100,20 @@ let package = Package(
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerEvalTests",
|
||||
dependencies: ["SprachmittlerEval", "SprachmittlerTestSupport"]
|
||||
dependencies: [
|
||||
"SprachmittlerEval", "SprachmittlerCore", "SprachmittlerEngines", "SprachmittlerText",
|
||||
"SprachmittlerOllama", "SprachmittlerTestSupport",
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerCLITests",
|
||||
dependencies: [
|
||||
"sprachmittler-cli",
|
||||
"SprachmittlerCore",
|
||||
"SprachmittlerEngines",
|
||||
"SprachmittlerOllama",
|
||||
"SprachmittlerTestSupport",
|
||||
]
|
||||
),
|
||||
// Opt-in tests against a real local Ollama: SPRACHMITTLER_LIVE=1 swift test --filter SprachmittlerLiveTests
|
||||
.testTarget(name: "SprachmittlerLiveTests", dependencies: ["SprachmittlerCore"]),
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import ApplicationServices
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
|
||||
/// The Accessibility operations Replace needs, behind a seam for tests.
|
||||
public protocol AccessibilityTextEditing: Sendable {
|
||||
/// Whether the app is trusted for Accessibility.
|
||||
func isTrusted() async -> Bool
|
||||
/// The focused element's selected text, or nil when unsupported.
|
||||
func selectedText(pid: pid_t) async -> String?
|
||||
/// True for a secure/password field.
|
||||
func isSecureField(pid: pid_t) async -> Bool
|
||||
/// Sets the focused selection. Returns false when the app does not accept it.
|
||||
func setSelectedText(pid: pid_t, to text: String) async -> Bool
|
||||
}
|
||||
|
||||
/// Posts the synthetic paste. Tests replace it with a fake.
|
||||
public protocol EventPosting: Sendable {
|
||||
/// Posts ⌘V to a PID. Returns false when events cannot be created.
|
||||
func postPaste(to pid: pid_t) -> Bool
|
||||
}
|
||||
|
||||
/// The production Accessibility editor. AX calls run on this actor, never on the main actor.
|
||||
public actor AXTextEditor: AccessibilityTextEditing {
|
||||
/// Creates the editor.
|
||||
public init() {}
|
||||
|
||||
public func isTrusted() -> Bool {
|
||||
AXIsProcessTrusted()
|
||||
}
|
||||
|
||||
public func selectedText(pid: pid_t) -> String? {
|
||||
guard let focused = focusedElement(pid: pid) else { return nil }
|
||||
var value: CFTypeRef?
|
||||
guard AXUIElementCopyAttributeValue(
|
||||
focused,
|
||||
kAXSelectedTextAttribute as CFString,
|
||||
&value
|
||||
) == .success else {
|
||||
return nil
|
||||
}
|
||||
return value as? String
|
||||
}
|
||||
|
||||
public func isSecureField(pid: pid_t) -> Bool {
|
||||
guard let focused = focusedElement(pid: pid) else { return false }
|
||||
if attribute(focused, kAXSubroleAttribute) == "AXSecureTextField" {
|
||||
return true
|
||||
}
|
||||
return attribute(focused, kAXRoleAttribute) == "AXSecureTextField"
|
||||
}
|
||||
|
||||
private func attribute(_ element: AXUIElement, _ name: String) -> String? {
|
||||
var value: CFTypeRef?
|
||||
guard AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success else {
|
||||
return nil
|
||||
}
|
||||
return value as? String
|
||||
}
|
||||
|
||||
public func setSelectedText(pid: pid_t, to text: String) async -> Bool {
|
||||
guard let focused = focusedElement(pid: pid) else { return false }
|
||||
return AXUIElementSetAttributeValue(
|
||||
focused,
|
||||
kAXSelectedTextAttribute as CFString,
|
||||
text as CFTypeRef
|
||||
) == .success
|
||||
}
|
||||
|
||||
private func focusedElement(pid: pid_t) -> AXUIElement? {
|
||||
let application = AXUIElementCreateApplication(pid)
|
||||
var value: CFTypeRef?
|
||||
guard AXUIElementCopyAttributeValue(
|
||||
application,
|
||||
kAXFocusedUIElementAttribute as CFString,
|
||||
&value
|
||||
) == .success, let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil }
|
||||
return unsafeDowncast(value, to: AXUIElement.self)
|
||||
}
|
||||
}
|
||||
|
||||
/// The production ⌘V poster.
|
||||
public struct CGEventPoster: EventPosting {
|
||||
/// Creates a poster.
|
||||
public init() {}
|
||||
|
||||
public func postPaste(to pid: pid_t) -> Bool {
|
||||
guard let keyDown = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: true),
|
||||
let keyUp = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: false)
|
||||
else {
|
||||
return false
|
||||
}
|
||||
keyDown.flags = .maskCommand
|
||||
keyUp.flags = .maskCommand
|
||||
keyDown.postToPid(pid)
|
||||
keyUp.postToPid(pid)
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import AppKit
|
||||
import ApplicationServices
|
||||
import SprachmittlerCore
|
||||
|
||||
/// The production Accessibility permission gate. It is never called on the capture path.
|
||||
@MainActor
|
||||
public final class AccessibilityPermission: AccessibilityPermissionChecking {
|
||||
/// Creates the gate.
|
||||
public init() {}
|
||||
|
||||
public var isTrusted: Bool {
|
||||
AXIsProcessTrusted()
|
||||
}
|
||||
|
||||
public func requestTrust() {
|
||||
// Use the public option key literal: the ApplicationServices global is not
|
||||
// concurrency-safe under Swift 6, and this is the same documented key.
|
||||
let options = ["AXTrustedCheckOptionPrompt": true] as CFDictionary
|
||||
_ = AXIsProcessTrustedWithOptions(options)
|
||||
}
|
||||
|
||||
public func openSettings() {
|
||||
let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
|
||||
?? URL(fileURLWithPath: "/System/Applications/System Settings.app")
|
||||
NSWorkspace.shared.open(url)
|
||||
}
|
||||
}
|
||||
@@ -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,20 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
|
||||
/// Captures the frontmost app at trigger time. It never reads a full document value.
|
||||
@MainActor
|
||||
public final class FrontmostTargetProvider: InsertionTargetProviding {
|
||||
/// Creates a provider.
|
||||
public init() {}
|
||||
|
||||
public func captureTarget() -> InsertionTarget? {
|
||||
guard let application = NSWorkspace.shared.frontmostApplication else { return nil }
|
||||
return InsertionTarget(
|
||||
pid: application.processIdentifier,
|
||||
bundleID: application.bundleIdentifier,
|
||||
selectedText: nil,
|
||||
capturedAt: Date()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import Darwin
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
|
||||
/// Replaces the selection with Accessibility first and a clipboard paste as fallback.
|
||||
public actor InsertionCoordinator: TextInserting {
|
||||
private let pasteboard: any PasteboardAccessing
|
||||
private let accessibility: any AccessibilityTextEditing
|
||||
private let poster: any EventPosting
|
||||
private let delay: @Sendable (Duration) async throws -> Void
|
||||
private let ownWrite: @MainActor @Sendable () -> Void
|
||||
private let frontmostPID: @MainActor @Sendable () -> pid_t
|
||||
|
||||
/// Creates the coordinator.
|
||||
public init(
|
||||
pasteboard: any PasteboardAccessing,
|
||||
accessibility: any AccessibilityTextEditing,
|
||||
poster: any EventPosting = CGEventPoster(),
|
||||
delay: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) },
|
||||
ownWrite: @escaping @MainActor @Sendable () -> Void,
|
||||
frontmostPID: @escaping @MainActor @Sendable () -> pid_t
|
||||
) {
|
||||
self.pasteboard = pasteboard
|
||||
self.accessibility = accessibility
|
||||
self.poster = poster
|
||||
self.delay = delay
|
||||
self.ownWrite = ownWrite
|
||||
self.frontmostPID = frontmostPID
|
||||
}
|
||||
|
||||
public func replace(
|
||||
selection: CapturedText,
|
||||
with translation: String,
|
||||
target: InsertionTarget
|
||||
) async throws -> InsertionOutcome {
|
||||
guard target.pid != getpid() else {
|
||||
throw SprachmittlerError.insertionTargetChanged
|
||||
}
|
||||
let pid = await frontmostPID()
|
||||
try InsertionPolicy.verify(
|
||||
frontmostPID: pid,
|
||||
target: target,
|
||||
selectedText: nil,
|
||||
source: selection.text
|
||||
)
|
||||
|
||||
guard await accessibility.isTrusted() else {
|
||||
throw SprachmittlerError.accessibilityNotTrusted
|
||||
}
|
||||
if await accessibility.isSecureField(pid: target.pid) {
|
||||
throw SprachmittlerError.accessibilityUnsupported(app: target.bundleID)
|
||||
}
|
||||
|
||||
if let selected = await accessibility.selectedText(pid: target.pid) {
|
||||
try InsertionPolicy.verify(
|
||||
frontmostPID: pid,
|
||||
target: target,
|
||||
selectedText: selected,
|
||||
source: selection.text
|
||||
)
|
||||
if await accessibility.setSelectedText(pid: target.pid, to: translation) {
|
||||
return .replaced(using: .accessibility)
|
||||
}
|
||||
}
|
||||
|
||||
return try await pasteFallback(selection: selection, translation: translation, target: target, pid: pid)
|
||||
}
|
||||
|
||||
private func pasteFallback(
|
||||
selection: CapturedText,
|
||||
translation: String,
|
||||
target: InsertionTarget,
|
||||
pid: pid_t
|
||||
) async throws -> InsertionOutcome {
|
||||
// Re-check the selection after a failed AX set before mutating the clipboard.
|
||||
if let selected = await accessibility.selectedText(pid: target.pid) {
|
||||
try InsertionPolicy.verify(
|
||||
frontmostPID: pid,
|
||||
target: target,
|
||||
selectedText: selected,
|
||||
source: selection.text
|
||||
)
|
||||
}
|
||||
|
||||
guard let snapshot = await pasteboard.snapshot() else {
|
||||
throw SprachmittlerError.pasteboardUnavailable
|
||||
}
|
||||
let written = await pasteboard.write(translation)
|
||||
await ownWrite()
|
||||
do {
|
||||
guard poster.postPaste(to: target.pid) else {
|
||||
throw SprachmittlerError.accessibilityUnsupported(app: target.bundleID)
|
||||
}
|
||||
try await delay(.milliseconds(300))
|
||||
guard await pasteboard.restore(snapshot, onlyIfChangeCountMatches: written) else {
|
||||
throw SprachmittlerError.pasteboardRestoreFailed
|
||||
}
|
||||
} catch {
|
||||
// SP-9: restore even when the paste or the settle delay is cancelled/fails.
|
||||
_ = await pasteboard.restore(snapshot, onlyIfChangeCountMatches: written)
|
||||
throw error
|
||||
}
|
||||
return .replaced(using: .paste)
|
||||
}
|
||||
|
||||
/// Whether Accessibility is currently available; the panel uses this for hints.
|
||||
public func isAccessibilityTrusted() async -> Bool {
|
||||
await accessibility.isTrusted()
|
||||
}
|
||||
}
|
||||
@@ -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, Sendable {
|
||||
/// 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,130 @@
|
||||
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>?
|
||||
|
||||
/// The capture limits used by the next poll.
|
||||
public var limits: CaptureLimits
|
||||
|
||||
/// 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(),
|
||||
limits: CaptureLimits = CaptureLimits(),
|
||||
now: @escaping @MainActor () -> Date = { Date() }
|
||||
) {
|
||||
self.pasteboard = pasteboard
|
||||
detector = DoubleCopyDetector(configuration: configuration)
|
||||
self.ticker = ticker
|
||||
self.limits = limits
|
||||
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 = limits.captureLimit(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,44 @@
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// Builds the Ollama clients and pipeline from a settings snapshot. This keeps every concrete
|
||||
/// client in one composition helper and away from the app target.
|
||||
public typealias OllamaCatalog = SprachmittlerOllama.OllamaCatalog
|
||||
|
||||
public enum AppOllama {
|
||||
/// A catalog for the configured endpoint.
|
||||
public static func makeCatalog(settings: AppSettings) throws -> any OllamaCatalog {
|
||||
let http = try OllamaHTTPClient(
|
||||
baseURL: settings.endpoint,
|
||||
allowRemote: settings.allowRemoteEndpoint
|
||||
)
|
||||
return OllamaCatalogClient(http: http)
|
||||
}
|
||||
|
||||
/// A translation pipeline for the configured endpoint and chunk limits.
|
||||
public static func makePipeline(settings: AppSettings) throws -> TranslationPipeline {
|
||||
let http = try OllamaHTTPClient(
|
||||
baseURL: settings.endpoint,
|
||||
allowRemote: settings.allowRemoteEndpoint
|
||||
)
|
||||
let chat = OllamaChatClient(http: http)
|
||||
let registry = AdapterRegistry(adapters: [HyMT3Adapter()])
|
||||
return TranslationPipeline(chat: chat, registry: registry, chunker: settings.chunker)
|
||||
}
|
||||
|
||||
/// Warms the selected model with fixed synthetic text. Only for a loopback endpoint.
|
||||
public static func warmUp(settings: AppSettings) async throws {
|
||||
guard settings.warmUpOnLaunch, EndpointPolicy.isLoopback(settings.endpoint) else { return }
|
||||
let http = try OllamaHTTPClient(
|
||||
baseURL: settings.endpoint,
|
||||
allowRemote: settings.allowRemoteEndpoint
|
||||
)
|
||||
let chat = OllamaChatClient(http: http)
|
||||
let request = HyMT3Adapter().warmUpRequest(
|
||||
model: settings.model,
|
||||
keepAlive: settings.keepModelLoaded
|
||||
)
|
||||
try await OllamaWarmUpRunner(chat: chat).run(request)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
|
||||
public extension AppSettings {
|
||||
init(from decoder: any Decoder) throws {
|
||||
let defaults = AppSettings()
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
|
||||
endpoint = try container.decodeIfPresent(URL.self, forKey: .endpoint) ?? defaults.endpoint
|
||||
allowRemoteEndpoint = try container.decodeIfPresent(Bool.self, forKey: .allowRemoteEndpoint)
|
||||
?? defaults.allowRemoteEndpoint
|
||||
model = try container.decodeIfPresent(String.self, forKey: .model) ?? defaults.model
|
||||
fastModel = container.contains(.fastModel)
|
||||
? try container.decodeIfPresent(String.self, forKey: .fastModel)
|
||||
: defaults.fastModel
|
||||
let decodedTarget = try container.decodeIfPresent(String.self, forKey: .targetLanguage)
|
||||
?? defaults.targetLanguage
|
||||
targetLanguage = HyMT3Languages.resolve(decodedTarget)?.code ?? defaults.targetLanguage
|
||||
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
|
||||
maxCharactersLatin = limits.latin
|
||||
maxCharactersCJK = limits.cjk
|
||||
maximumPartsPerSelection = limits.parts
|
||||
numCtx = limits.numCtx
|
||||
numPredict = limits.numPredict
|
||||
translationFontSize = limits.fontSize
|
||||
let sampling = try Self.decodeSampling(from: container, defaults: defaults)
|
||||
temperature = sampling.temperature
|
||||
topP = sampling.topP
|
||||
topK = sampling.topK
|
||||
repeatPenalty = sampling.repeatPenalty
|
||||
let keep = try container.decodeIfPresent(String.self, forKey: .keepModelLoaded)
|
||||
?? defaults.keepModelLoaded
|
||||
keepModelLoaded = ["5m", "30m", "1h", "0"].contains(keep) ? keep : defaults.keepModelLoaded
|
||||
warmUpOnLaunch = try container.decodeIfPresent(Bool.self, forKey: .warmUpOnLaunch) ?? defaults.warmUpOnLaunch
|
||||
let policy = try container.decodeIfPresent(PromptVariantPolicy.self, forKey: .promptVariantPolicy)
|
||||
?? defaults.promptVariantPolicy
|
||||
promptVariantPolicy = policy
|
||||
// Auto-copy is a hard invariant: decoding cannot turn it on.
|
||||
autoCopy = false
|
||||
showSourcePreview = try container.decodeIfPresent(Bool.self, forKey: .showSourcePreview)
|
||||
?? defaults.showSourcePreview
|
||||
renderMarkdown = try container.decodeIfPresent(Bool.self, forKey: .renderMarkdown) ?? defaults.renderMarkdown
|
||||
closeWithEscape = try container.decodeIfPresent(Bool.self, forKey: .closeWithEscape) ?? defaults.closeWithEscape
|
||||
launchAtLogin = try container.decodeIfPresent(Bool.self, forKey: .launchAtLogin) ?? defaults.launchAtLogin
|
||||
keepRecentTranslationInMemory = try container.decodeIfPresent(
|
||||
Bool.self,
|
||||
forKey: .keepRecentTranslationInMemory
|
||||
) ?? defaults.keepRecentTranslationInMemory
|
||||
hasCompletedOnboarding = try container.decodeIfPresent(Bool.self, forKey: .hasCompletedOnboarding)
|
||||
?? defaults.hasCompletedOnboarding
|
||||
settingsVersion = Self.currentVersion
|
||||
}
|
||||
|
||||
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(languageRoutes, forKey: .languageRoutes)
|
||||
try container.encode(recentTargetLanguages, forKey: .recentTargetLanguages)
|
||||
try container.encode(doubleCopyWindowMs, forKey: .doubleCopyWindowMs)
|
||||
try container.encode(maxCharactersLatin, forKey: .maxCharactersLatin)
|
||||
try container.encode(maxCharactersCJK, forKey: .maxCharactersCJK)
|
||||
try container.encode(maximumPartsPerSelection, forKey: .maximumPartsPerSelection)
|
||||
try container.encode(numCtx, forKey: .numCtx)
|
||||
try container.encode(numPredict, forKey: .numPredict)
|
||||
try container.encode(temperature, forKey: .temperature)
|
||||
try container.encode(topP, forKey: .topP)
|
||||
try container.encode(topK, forKey: .topK)
|
||||
try container.encode(repeatPenalty, forKey: .repeatPenalty)
|
||||
try container.encode(keepModelLoaded, forKey: .keepModelLoaded)
|
||||
try container.encode(warmUpOnLaunch, forKey: .warmUpOnLaunch)
|
||||
try container.encode(promptVariantPolicy, forKey: .promptVariantPolicy)
|
||||
try container.encode(autoCopy, forKey: .autoCopy)
|
||||
try container.encode(showSourcePreview, forKey: .showSourcePreview)
|
||||
try container.encode(translationFontSize, forKey: .translationFontSize)
|
||||
try container.encode(renderMarkdown, forKey: .renderMarkdown)
|
||||
try container.encode(closeWithEscape, forKey: .closeWithEscape)
|
||||
try container.encode(launchAtLogin, forKey: .launchAtLogin)
|
||||
try container.encode(keepRecentTranslationInMemory, forKey: .keepRecentTranslationInMemory)
|
||||
try container.encode(hasCompletedOnboarding, forKey: .hasCompletedOnboarding)
|
||||
try container.encode(settingsVersion, forKey: .settingsVersion)
|
||||
}
|
||||
|
||||
private static func decodeRecentTargets(
|
||||
from container: KeyedDecodingContainer<CodingKeys>
|
||||
) throws -> [String] {
|
||||
let recents = try container.decodeIfPresent([String].self, forKey: .recentTargetLanguages) ?? []
|
||||
var seen = Set<String>()
|
||||
return recents.compactMap { HyMT3Languages.resolve($0)?.code }
|
||||
.filter { seen.insert($0).inserted }
|
||||
.prefix(3)
|
||||
.map(\.self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
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 mother tongue BCP-47 code; the default target when no rule matches.
|
||||
public var targetLanguage: 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).
|
||||
public var doubleCopyWindowMs: Int
|
||||
/// The Latin/Cyrillic/Greek chunk limit.
|
||||
public var maxCharactersLatin: Int
|
||||
/// The dense-script chunk limit.
|
||||
public var maxCharactersCJK: Int
|
||||
/// How many chunks one capture may contain (1–8). `1` rejects text longer than one chunk.
|
||||
public var maximumPartsPerSelection: 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
|
||||
languageRoutes = []
|
||||
recentTargetLanguages = []
|
||||
doubleCopyWindowMs = 500
|
||||
maxCharactersLatin = 4000
|
||||
maxCharactersCJK = 2000
|
||||
maximumPartsPerSelection = 1
|
||||
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 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) {
|
||||
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
|
||||
languageRoutes = Self.normalizedRoutes(languageRoutes)
|
||||
doubleCopyWindowMs = Self.clamp(doubleCopyWindowMs, to: 300 ... 1000)
|
||||
maxCharactersLatin = Self.clamp(maxCharactersLatin, to: 500 ... 10000)
|
||||
maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 4000)
|
||||
maximumPartsPerSelection = Self.clamp(maximumPartsPerSelection, to: 1 ... 8)
|
||||
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)
|
||||
}
|
||||
|
||||
/// The chunk and capture limits derived from the settings.
|
||||
public var captureLimits: CaptureLimits {
|
||||
CaptureLimits(chunker: chunker, maximumParts: maximumPartsPerSelection)
|
||||
}
|
||||
|
||||
struct DecodedLimits {
|
||||
let window: Int
|
||||
let latin: Int
|
||||
let cjk: Int
|
||||
let parts: 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 ... 4000
|
||||
),
|
||||
parts: clamp(
|
||||
container.decodeIfPresent(Int.self, forKey: .maximumPartsPerSelection)
|
||||
?? defaults.maximumPartsPerSelection,
|
||||
to: 1 ... 8
|
||||
),
|
||||
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, languageRoutes
|
||||
case recentTargetLanguages
|
||||
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, maximumPartsPerSelection
|
||||
case numCtx, numPredict
|
||||
case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch
|
||||
case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, renderMarkdown
|
||||
case closeWithEscape, launchAtLogin, keepRecentTranslationInMemory, hasCompletedOnboarding
|
||||
case settingsVersion
|
||||
}
|
||||
|
||||
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 {
|
||||
min(max(value, range.lowerBound), range.upperBound)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import SprachmittlerText
|
||||
|
||||
/// The per-request chunk size and the total size one capture may have.
|
||||
///
|
||||
/// `maximumParts == 1` rejects anything longer than one chunk. Higher values accept up to
|
||||
/// `maximumParts` chunks and translate them sequentially (`docs/TRANSLATION_OUTPUT.md` §3).
|
||||
public struct CaptureLimits: Sendable, Equatable {
|
||||
/// The per-request chunk size.
|
||||
public let chunker: Chunker
|
||||
/// How many chunks one capture may contain (at least 1).
|
||||
public let maximumParts: Int
|
||||
|
||||
/// Creates limits.
|
||||
public init(chunker: Chunker = Chunker(), maximumParts: Int = 1) {
|
||||
self.chunker = chunker
|
||||
self.maximumParts = max(1, maximumParts)
|
||||
}
|
||||
|
||||
/// The per-chunk character limit for `text`.
|
||||
public func chunkLimit(for text: String) -> Int {
|
||||
chunker.limit(for: text)
|
||||
}
|
||||
|
||||
/// The total character limit for one capture.
|
||||
public func captureLimit(for text: String) -> Int {
|
||||
chunkLimit(for: text) * maximumParts
|
||||
}
|
||||
}
|
||||
@@ -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 capture limit (`chunk size × maximum parts`).
|
||||
public static func validate(_ text: String, limits: CaptureLimits = CaptureLimits()) -> CaptureValidation {
|
||||
guard text.contains(where: { !$0.isWhitespace }) else { return .empty }
|
||||
let limit = limits.captureLimit(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,55 @@
|
||||
import Foundation
|
||||
|
||||
/// One in-memory diagnostic entry. It never contains selected text or a translation.
|
||||
public struct DiagnosticEvent: Sendable, Equatable, Codable {
|
||||
/// When the event happened.
|
||||
public let timestamp: Date
|
||||
/// A short kind such as `translation`, `error` or `capture`.
|
||||
public let kind: String
|
||||
/// A duration in milliseconds, when relevant.
|
||||
public let durationMs: Int?
|
||||
/// A non-text detail such as a warning code or error kind.
|
||||
public let detail: String?
|
||||
|
||||
/// Creates an event.
|
||||
public init(timestamp: Date, kind: String, durationMs: Int? = nil, detail: String? = nil) {
|
||||
self.timestamp = timestamp
|
||||
self.kind = kind
|
||||
self.durationMs = durationMs
|
||||
self.detail = detail
|
||||
}
|
||||
}
|
||||
|
||||
/// A bounded in-memory diagnostics log (`docs/ARCHITECTURE.md` §15).
|
||||
public actor DiagnosticsStore {
|
||||
/// The maximum number of retained events.
|
||||
public static let capacity = 50
|
||||
|
||||
private var events: [DiagnosticEvent] = []
|
||||
private let clock: @Sendable () -> Date
|
||||
|
||||
/// Creates a store.
|
||||
public init(clock: @escaping @Sendable () -> Date = { Date() }) {
|
||||
self.clock = clock
|
||||
}
|
||||
|
||||
/// Records one non-text event, dropping the oldest beyond the capacity.
|
||||
public func record(kind: String, durationMs: Int? = nil, detail: String? = nil) {
|
||||
events.append(
|
||||
DiagnosticEvent(timestamp: clock(), kind: kind, durationMs: durationMs, detail: detail)
|
||||
)
|
||||
if events.count > Self.capacity {
|
||||
events.removeFirst(events.count - Self.capacity)
|
||||
}
|
||||
}
|
||||
|
||||
/// The current events, oldest first.
|
||||
public func snapshot() -> [DiagnosticEvent] {
|
||||
events
|
||||
}
|
||||
|
||||
/// Clears the in-memory list.
|
||||
public func clear() {
|
||||
events.removeAll()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// The diagnostics window model. It formats versions, digests, timings and error kinds only.
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class DiagnosticsViewModel {
|
||||
/// The last events, oldest first.
|
||||
public private(set) var events: [DiagnosticEvent] = []
|
||||
/// The Ollama version.
|
||||
public private(set) var serverVersion: String?
|
||||
/// The installed Hy-MT3 models.
|
||||
public private(set) var models: [InstalledModel] = []
|
||||
/// A short error when the refresh failed.
|
||||
public private(set) var error: String?
|
||||
/// True while refreshing.
|
||||
public private(set) var isRefreshing = false
|
||||
|
||||
private let store: DiagnosticsStore
|
||||
private let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog
|
||||
private let settingsProvider: @Sendable () -> AppSettings
|
||||
|
||||
/// Creates the diagnostics model.
|
||||
public init(
|
||||
store: DiagnosticsStore,
|
||||
catalogProvider: @escaping @Sendable (AppSettings) throws -> any OllamaCatalog,
|
||||
settingsProvider: @escaping @Sendable () -> AppSettings
|
||||
) {
|
||||
self.store = store
|
||||
self.catalogProvider = catalogProvider
|
||||
self.settingsProvider = settingsProvider
|
||||
}
|
||||
|
||||
/// Reloads events and, when possible, server/model details.
|
||||
public func refresh() async {
|
||||
isRefreshing = true
|
||||
defer { isRefreshing = false }
|
||||
events = await store.snapshot()
|
||||
|
||||
do {
|
||||
let catalog = try catalogProvider(settingsProvider())
|
||||
serverVersion = try await catalog.serverVersion()
|
||||
models = try await catalog.installedModels()
|
||||
.filter { HyMT3ModelPreset.isHyMT3($0.name) }
|
||||
error = nil
|
||||
} catch let rejection as EndpointRejection {
|
||||
self.error = SprachmittlerError.endpointRejected(reason: rejection).userMessage
|
||||
} catch {
|
||||
self.error = "Ollama details are unavailable."
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears the in-memory event list.
|
||||
public func clear() async {
|
||||
await store.clear()
|
||||
events = []
|
||||
}
|
||||
|
||||
/// A text-only report for the clipboard; no source text or translation is included.
|
||||
public func report() -> String {
|
||||
var lines = [
|
||||
"Sprachmittler diagnostics",
|
||||
"Ollama: \(serverVersion ?? "unknown")",
|
||||
"Endpoint: \(settingsProvider().endpoint.absoluteString)",
|
||||
"Models: \(models.map { "\($0.name) [\($0.digest.prefix(12))]" }.joined(separator: ", "))",
|
||||
]
|
||||
for event in events {
|
||||
let duration = event.durationMs.map { " \($0) ms" } ?? ""
|
||||
let detail = event.detail.map { " [\($0)]" } ?? ""
|
||||
lines.append("\(event.kind)\(duration)\(detail)")
|
||||
}
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
}
|
||||
@@ -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,11 @@
|
||||
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
|
||||
|
||||
/// The language value type, re-exported for app views.
|
||||
public typealias ModelLanguage = SprachmittlerEngines.ModelLanguage
|
||||
@@ -0,0 +1,19 @@
|
||||
import SprachmittlerEngines
|
||||
|
||||
/// The app-facing language catalogue. It re-exports the model-name data owned by Engines.
|
||||
public enum LanguageCatalogue {
|
||||
/// All 102 supported languages.
|
||||
public static var all: [ModelLanguage] {
|
||||
HyMT3Languages.all
|
||||
}
|
||||
|
||||
/// The common first-run list.
|
||||
public static var common: [ModelLanguage] {
|
||||
HyMT3Languages.common
|
||||
}
|
||||
|
||||
/// Resolves a BCP-47 code.
|
||||
public static func resolve(_ code: String) -> ModelLanguage? {
|
||||
HyMT3Languages.resolve(code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/// Log categories from ARCHITECTURE §15.
|
||||
public enum LogCategory: String, CaseIterable, Sendable {
|
||||
/// Double-copy detection and capture.
|
||||
case capture
|
||||
/// Pasteboard polling and own-write suppression.
|
||||
case pasteboard
|
||||
/// Translation session lifecycle.
|
||||
case session
|
||||
/// Ollama HTTP client.
|
||||
case ollama
|
||||
/// Prompt and adapter construction.
|
||||
case engine
|
||||
/// Output validation.
|
||||
case validate
|
||||
/// Accessibility or paste insertion.
|
||||
case insert
|
||||
/// Panel presentation.
|
||||
case panel
|
||||
/// Settings persistence.
|
||||
case settings
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
|
||||
/// Privacy-safe helpers for log values (SP-2).
|
||||
public enum LogRedaction {
|
||||
/// Returns the first 12 lowercase hex characters of the SHA-256 digest of `value`.
|
||||
///
|
||||
/// Use this for identifiers that must be correlatable across log lines without revealing
|
||||
/// the original text. Always log the result with `privacy: .private`; SECURITY_PRIVACY
|
||||
/// §Logging requires the private qualifier for correlation hashes as well.
|
||||
public static func shortHash(_ value: String) -> String {
|
||||
let digest = SHA256.hash(data: Data(value.utf8))
|
||||
return digest.prefix(6).map { String(format: "%02x", $0) }.joined()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import os
|
||||
|
||||
/// Factory for the app's `os.Logger` and `OSSignposter` instances.
|
||||
///
|
||||
/// The subsystem is supplied by the composition root (the app bundle identifier or the CLI
|
||||
/// subsystem); this module never hard-codes one.
|
||||
///
|
||||
/// ## Leaf modules
|
||||
/// `SprachmittlerOllama` and `SprachmittlerEngines` cannot import Core. When they gain logging,
|
||||
/// the composition root passes `Logger` values created here into their initializers. A leaf that
|
||||
/// needs signposts uses an `OSSignposter` with the literal names from ARCHITECTURE §15. Do not
|
||||
/// add a Core dependency to a leaf module.
|
||||
public struct Loggers: Sendable {
|
||||
/// The `os.Logger` subsystem, normally the app bundle identifier.
|
||||
public let subsystem: String
|
||||
|
||||
/// Creates a factory for the given subsystem.
|
||||
public init(subsystem: String) {
|
||||
self.subsystem = subsystem
|
||||
}
|
||||
|
||||
/// Returns the logger for one ARCHITECTURE §15 category.
|
||||
public func logger(_ category: LogCategory) -> Logger {
|
||||
Logger(subsystem: subsystem, category: category.rawValue)
|
||||
}
|
||||
|
||||
/// Returns the signposter for one ARCHITECTURE §15 category.
|
||||
public func signposts(_ category: LogCategory) -> Signposts {
|
||||
Signposts(subsystem: subsystem, category: category)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// Maps the leaf's transport vocabulary to the domain taxonomy at the Core boundary.
|
||||
public extension SprachmittlerError {
|
||||
/// Creates a domain error from an `OllamaError`.
|
||||
init(ollama error: OllamaError) {
|
||||
switch error {
|
||||
case let .endpointRejected(reason):
|
||||
self = .endpointRejected(reason: reason)
|
||||
case let .unreachable(url):
|
||||
self = .ollamaUnreachable(url: url)
|
||||
case let .modelNotInstalled(model):
|
||||
self = .modelNotInstalled(model: model)
|
||||
case let .badRequest(message):
|
||||
self = .badRequest(message: message)
|
||||
case let .server(status, message):
|
||||
self = .server(status: status, message: message)
|
||||
case let .timeout(phase):
|
||||
self = .timeout(phase: phase)
|
||||
case .cancelled:
|
||||
self = .cancelled
|
||||
case let .decoding(message):
|
||||
self = .server(status: 0, message: message)
|
||||
case let .unsupportedVersion(found, required):
|
||||
self = .ollamaTooOld(found: found, required: required)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// One onboarding check.
|
||||
public enum OnboardingCheck: Sendable, Equatable {
|
||||
/// Not checked yet.
|
||||
case idle
|
||||
/// A check is running.
|
||||
case checking
|
||||
/// The check passed; the value is a short detail.
|
||||
case ok(String)
|
||||
/// The check failed; the value is a user-facing message.
|
||||
case failed(String)
|
||||
}
|
||||
|
||||
/// First-run onboarding state and actions (`docs/IMPLEMENTATION_PLAN.md` T6.2).
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class OnboardingViewModel {
|
||||
/// Ollama reachability and version.
|
||||
public private(set) var ollama: OnboardingCheck = .idle
|
||||
/// Hy-MT3 installation.
|
||||
public private(set) var model: OnboardingCheck = .idle
|
||||
/// Accessibility trust (optional, for Replace).
|
||||
public private(set) var accessibilityTrusted = false
|
||||
/// The selected target.
|
||||
public private(set) var target: ModelLanguage
|
||||
/// The installed Hy-MT3 tags.
|
||||
public private(set) var installedModels: [String] = []
|
||||
/// True while any check is running.
|
||||
public private(set) var isChecking = false
|
||||
|
||||
private let settingsStore: SettingsStore
|
||||
private let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog
|
||||
private let accessibility: any AccessibilityPermissionChecking
|
||||
|
||||
/// Creates the onboarding model.
|
||||
public init(
|
||||
settingsStore: SettingsStore,
|
||||
catalogProvider: @escaping @Sendable (AppSettings) throws -> any OllamaCatalog,
|
||||
accessibility: any AccessibilityPermissionChecking
|
||||
) {
|
||||
self.settingsStore = settingsStore
|
||||
self.catalogProvider = catalogProvider
|
||||
self.accessibility = accessibility
|
||||
let settings = settingsStore.current()
|
||||
target = settings.targetLanguageModel
|
||||
accessibilityTrusted = accessibility.isTrusted
|
||||
}
|
||||
|
||||
/// The command shown when the model is missing.
|
||||
public var pullCommand: String {
|
||||
"ollama pull \(settingsStore.current().model)"
|
||||
}
|
||||
|
||||
/// True when the essential checks passed; the app can be used.
|
||||
public var canFinish: Bool {
|
||||
if case .ok = ollama, case .ok = model {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// Runs all checks.
|
||||
public func refresh() async {
|
||||
isChecking = true
|
||||
ollama = .checking
|
||||
model = .checking
|
||||
accessibilityTrusted = accessibility.isTrusted
|
||||
|
||||
do {
|
||||
let settings = settingsStore.current()
|
||||
let catalog = try catalogProvider(settings)
|
||||
let version = try await catalog.serverVersion()
|
||||
ollama = .ok(version)
|
||||
|
||||
let models = try await catalog.installedModels()
|
||||
let tags = models.map(\.name).filter { HyMT3ModelPreset.isHyMT3($0) }
|
||||
installedModels = tags
|
||||
if tags.isEmpty {
|
||||
model = .failed(SprachmittlerError.modelNotInstalled(model: settings.model).userMessage)
|
||||
} else {
|
||||
if !tags.contains(settings.model), let first = tags.first {
|
||||
try? settingsStore.update { $0.model = first }
|
||||
}
|
||||
model = .ok(tags.joined(separator: ", "))
|
||||
}
|
||||
} catch let error as OllamaError {
|
||||
let domain = SprachmittlerError(ollama: error)
|
||||
ollama = .failed(domain.userMessage)
|
||||
model = .failed(domain.userMessage)
|
||||
} catch let error as SprachmittlerError {
|
||||
ollama = .failed(error.userMessage)
|
||||
model = .failed(error.userMessage)
|
||||
} catch let rejection as EndpointRejection {
|
||||
let message = SprachmittlerError.endpointRejected(reason: rejection).userMessage
|
||||
ollama = .failed(message)
|
||||
model = .failed(message)
|
||||
} catch {
|
||||
let message = "Ollama could not be reached."
|
||||
ollama = .failed(message)
|
||||
model = .failed(message)
|
||||
}
|
||||
isChecking = false
|
||||
}
|
||||
|
||||
/// Saves the chosen target.
|
||||
public func saveTarget() throws {
|
||||
try settingsStore.update { $0.noteTarget(target) }
|
||||
}
|
||||
|
||||
/// Sets the target; the caller saves.
|
||||
public func setTarget(_ language: ModelLanguage) {
|
||||
target = language
|
||||
}
|
||||
|
||||
/// Requests Accessibility trust. Only call from onboarding.
|
||||
public func requestAccessibility() {
|
||||
accessibility.requestTrust()
|
||||
accessibilityTrusted = accessibility.isTrusted
|
||||
}
|
||||
|
||||
/// Opens the Accessibility settings page.
|
||||
public func openAccessibilitySettings() {
|
||||
accessibility.openSettings()
|
||||
}
|
||||
|
||||
/// Marks onboarding complete after a successful setup.
|
||||
public func complete() throws {
|
||||
try saveTarget()
|
||||
try settingsStore.update { $0.hasCompletedOnboarding = true }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerText
|
||||
|
||||
/// The panel phase from `docs/ARCHITECTURE.md` §10.
|
||||
public enum PanelPhase: Sendable, Equatable {
|
||||
/// Nothing captured.
|
||||
case idle
|
||||
/// A request is queued or running.
|
||||
case translating
|
||||
/// Deltas are arriving.
|
||||
case streaming
|
||||
/// A validated translation is ready.
|
||||
case ready
|
||||
/// The request failed.
|
||||
case failed
|
||||
}
|
||||
|
||||
/// The settings snapshot used by the panel for one translation.
|
||||
public struct PanelConfiguration: Sendable, Equatable {
|
||||
/// The selected target language.
|
||||
public var target: 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.
|
||||
public var keepAlive: String
|
||||
/// The sampling values.
|
||||
public var sampling: SamplingOptions
|
||||
/// Whether to show the source preview.
|
||||
public var showSourcePreview: Bool
|
||||
/// Translation text size in points.
|
||||
public var translationFontSize: Int
|
||||
/// Render Markdown formatting for Markdown sources.
|
||||
public var renderMarkdown: Bool
|
||||
/// Make the panel key when shown so Esc works without a click.
|
||||
public var closeWithEscape: Bool
|
||||
/// Recent targets, most recent first.
|
||||
public var recentTargets: [ModelLanguage]
|
||||
/// The chunk and capture limits accepted for this capture.
|
||||
public var captureLimits: CaptureLimits
|
||||
|
||||
/// Creates a configuration.
|
||||
public init(
|
||||
target: ModelLanguage,
|
||||
model: String,
|
||||
keepAlive: String,
|
||||
sampling: SamplingOptions = .publisherDefault,
|
||||
showSourcePreview: Bool = true,
|
||||
translationFontSize: Int = 17,
|
||||
renderMarkdown: Bool = true,
|
||||
closeWithEscape: Bool = true,
|
||||
languageRoutes: [LanguageRoute] = [],
|
||||
recentTargets: [ModelLanguage] = [],
|
||||
captureLimits: CaptureLimits = CaptureLimits()
|
||||
) {
|
||||
self.target = target
|
||||
self.model = model
|
||||
self.keepAlive = keepAlive
|
||||
self.sampling = sampling
|
||||
self.showSourcePreview = showSourcePreview
|
||||
self.translationFontSize = translationFontSize
|
||||
self.renderMarkdown = renderMarkdown
|
||||
self.closeWithEscape = closeWithEscape
|
||||
self.languageRoutes = languageRoutes
|
||||
self.recentTargets = recentTargets
|
||||
self.captureLimits = captureLimits
|
||||
}
|
||||
}
|
||||
|
||||
/// The panel presentation model. It mirrors `TranslationSession` and owns no disk state.
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class PanelViewModel {
|
||||
/// The current phase.
|
||||
public private(set) var phase: PanelPhase = .idle
|
||||
/// The captured source.
|
||||
public private(set) var source: CapturedText?
|
||||
/// The streamed and final translation.
|
||||
public private(set) var translation = ""
|
||||
/// Validation warnings for the current result.
|
||||
public private(set) var warnings: [TranslationWarning] = []
|
||||
/// The current error, if any.
|
||||
public private(set) var error: SprachmittlerError?
|
||||
/// The last timing.
|
||||
public private(set) var timing: TranslationTiming?
|
||||
/// The advisory source language code.
|
||||
public private(set) var sourceLanguage: String?
|
||||
/// True after a successful Copy.
|
||||
public private(set) var didCopy = false
|
||||
/// True while a Replace action is running.
|
||||
public private(set) var isReplacing = false
|
||||
/// The current target, model and prompt settings. `target` is the user's saved preference.
|
||||
public private(set) var configuration: PanelConfiguration
|
||||
/// The target used by the current request, after a language rule or an explicit picker choice.
|
||||
public private(set) var effectiveTarget: 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
|
||||
/// The number of parts in the last finished translation.
|
||||
public private(set) var chunkCount = 1
|
||||
/// The current part while a multi-part request runs.
|
||||
public private(set) var currentChunk: Int?
|
||||
/// The total parts of the current multi-part request.
|
||||
public private(set) var totalChunks: Int?
|
||||
|
||||
/// The copy action. The composition root writes with own-write markers.
|
||||
public let copy: @MainActor (String) -> Void
|
||||
/// The optional Replace action; nil until the insertion module is available.
|
||||
public let replace: (@MainActor () async -> InsertionOutcome)?
|
||||
/// Called when a successful Replace should close the panel.
|
||||
public let onCloseRequest: @MainActor () -> Void
|
||||
/// Called with every session event for diagnostics.
|
||||
public let eventObserver: (@MainActor (TranslationSessionEvent) -> Void)?
|
||||
/// Called when the user changes the target from the panel.
|
||||
public let onTargetChanged: @MainActor (ModelLanguage) -> Void
|
||||
|
||||
private let session: TranslationSession
|
||||
private let detector: any LanguageDetecting
|
||||
private var eventTask: Task<Void, Never>?
|
||||
private var currentEpoch: UInt64 = 0
|
||||
private var lastCaptured: CapturedText?
|
||||
private var targetOverride: ModelLanguage?
|
||||
|
||||
/// Creates a panel model.
|
||||
public init(
|
||||
session: TranslationSession,
|
||||
configuration: PanelConfiguration,
|
||||
copy: @escaping @MainActor (String) -> Void,
|
||||
replace: (@MainActor () async -> InsertionOutcome)? = nil,
|
||||
onCloseRequest: @escaping @MainActor () -> Void = {},
|
||||
eventObserver: (@MainActor (TranslationSessionEvent) -> Void)? = nil,
|
||||
onTargetChanged: @escaping @MainActor (ModelLanguage) -> Void = { _ in },
|
||||
detector: any LanguageDetecting = NaturalLanguageDetector()
|
||||
) {
|
||||
self.session = session
|
||||
self.configuration = configuration
|
||||
effectiveTarget = configuration.target
|
||||
self.detector = detector
|
||||
self.copy = copy
|
||||
self.replace = replace
|
||||
self.onCloseRequest = onCloseRequest
|
||||
self.eventObserver = eventObserver
|
||||
self.onTargetChanged = onTargetChanged
|
||||
}
|
||||
|
||||
/// Starts consuming session events. Call once after init.
|
||||
public func startObserving() {
|
||||
guard eventTask == nil else { return }
|
||||
let session = session
|
||||
eventTask = Task { [weak self] in
|
||||
for await event in await session.events() {
|
||||
guard let self else { return }
|
||||
handle(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True when Copy can write the current translation.
|
||||
public var canCopy: Bool {
|
||||
!translation.isEmpty && (phase == .ready || phase == .failed)
|
||||
}
|
||||
|
||||
/// True when Replace is safe and the insertion module is available.
|
||||
public var canReplace: Bool {
|
||||
phase == .ready
|
||||
&& !isReplacing
|
||||
&& !warnings.contains(where: \.blocksReplacement)
|
||||
&& replace != nil
|
||||
}
|
||||
|
||||
/// The replacement is unavailable until M5 in this build.
|
||||
public var replaceUnavailableReason: String? {
|
||||
replace == nil ? "Replace is not available." : nil
|
||||
}
|
||||
|
||||
/// Warnings that disable Replace.
|
||||
public var blockingWarnings: [TranslationWarning] {
|
||||
warnings.filter(\.blocksReplacement)
|
||||
}
|
||||
|
||||
/// The same-language advisory, if present and not dismissed.
|
||||
public var sameLanguageWarning: TranslationWarning? {
|
||||
guard !sameLanguageDismissed else { return nil }
|
||||
return warnings.first { warning in
|
||||
if case .sameLanguage = warning {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The user-facing error message.
|
||||
public var errorMessage: String? {
|
||||
error?.userMessage
|
||||
}
|
||||
|
||||
/// The error's recovery action.
|
||||
public var recoveryAction: RecoveryAction? {
|
||||
error?.recoveryAction
|
||||
}
|
||||
|
||||
/// Synchronously resets the visible state before the panel is shown and resolves the direction.
|
||||
public func prepare(_ captured: CapturedText, resetDirectionOverride: Bool = true) {
|
||||
currentEpoch = 0
|
||||
lastCaptured = captured
|
||||
source = captured
|
||||
translation = ""
|
||||
warnings = []
|
||||
error = nil
|
||||
timing = nil
|
||||
didCopy = false
|
||||
isReplacing = false
|
||||
chunkCount = 1
|
||||
currentChunk = nil
|
||||
totalChunks = nil
|
||||
if resetDirectionOverride {
|
||||
targetOverride = nil
|
||||
}
|
||||
let normalized = TextNormalization.normalizeInput(captured.text)
|
||||
let detection = detector.detect(normalized)
|
||||
sourceLanguage = detection?.code
|
||||
let direction = TranslationDirectionPolicy.resolve(
|
||||
configuredTarget: configuration.target,
|
||||
routes: configuration.languageRoutes,
|
||||
detection: detection,
|
||||
override: targetOverride
|
||||
)
|
||||
effectiveTarget = direction.target
|
||||
routedSource = direction.didRoute ? direction.source : nil
|
||||
sameLanguageDismissed = targetOverride != nil
|
||||
phase = .translating
|
||||
}
|
||||
|
||||
/// Starts a translation for a captured text.
|
||||
public func begin(_ captured: CapturedText) async {
|
||||
await begin(captured, resetDirectionOverride: true)
|
||||
}
|
||||
|
||||
private func begin(_ captured: CapturedText, resetDirectionOverride: Bool) async {
|
||||
prepare(captured, resetDirectionOverride: resetDirectionOverride)
|
||||
_ = await session.start(request(for: captured))
|
||||
}
|
||||
|
||||
/// Retries the last captured text without discarding a manual direction choice.
|
||||
public func retry() async {
|
||||
guard let lastCaptured else { return }
|
||||
await begin(lastCaptured, resetDirectionOverride: false)
|
||||
}
|
||||
|
||||
/// Retranslates after an external target change and re-evaluates the direction.
|
||||
public func retranslate() async {
|
||||
guard let lastCaptured else { return }
|
||||
await begin(lastCaptured, resetDirectionOverride: true)
|
||||
}
|
||||
|
||||
/// Shows a capture-time error such as a too-long selection.
|
||||
public func showError(_ error: SprachmittlerError, source: CapturedText? = nil) {
|
||||
currentEpoch = 0
|
||||
Task { await session.reset() }
|
||||
phase = .failed
|
||||
self.error = error
|
||||
self.source = source
|
||||
translation = ""
|
||||
warnings = []
|
||||
timing = nil
|
||||
sourceLanguage = nil
|
||||
chunkCount = 1
|
||||
currentChunk = nil
|
||||
totalChunks = nil
|
||||
effectiveTarget = configuration.target
|
||||
routedSource = nil
|
||||
targetOverride = nil
|
||||
}
|
||||
|
||||
/// Changes the saved target from the panel and retranslates the current selection.
|
||||
public func setTarget(_ language: ModelLanguage) async {
|
||||
guard language.code != effectiveTarget.code else { return }
|
||||
configuration.target = language
|
||||
effectiveTarget = language
|
||||
routedSource = nil
|
||||
targetOverride = language
|
||||
onTargetChanged(language)
|
||||
if let lastCaptured {
|
||||
await begin(lastCaptured, resetDirectionOverride: false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses another language for this capture only. It does not change the saved target.
|
||||
public func overrideTarget(_ language: ModelLanguage) async {
|
||||
guard language.code != effectiveTarget.code else { return }
|
||||
effectiveTarget = language
|
||||
routedSource = nil
|
||||
targetOverride = language
|
||||
sameLanguageDismissed = true
|
||||
if let lastCaptured {
|
||||
await begin(lastCaptured, resetDirectionOverride: false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies the translation and keeps the panel open (R023).
|
||||
public func copyTranslation() {
|
||||
guard canCopy else { return }
|
||||
copy(translation)
|
||||
didCopy = true
|
||||
}
|
||||
|
||||
/// Runs the optional Replace action.
|
||||
public func replaceSelection() async {
|
||||
guard canReplace, let replace else { return }
|
||||
isReplacing = true
|
||||
let outcome = await replace()
|
||||
isReplacing = false
|
||||
switch outcome {
|
||||
case .replaced:
|
||||
onCloseRequest()
|
||||
case .copiedOnly:
|
||||
break
|
||||
case let .failed(insertionError):
|
||||
error = insertionError
|
||||
phase = .failed
|
||||
}
|
||||
}
|
||||
|
||||
/// Dismisses the same-language advisory; translation stays available.
|
||||
public func dismissSameLanguageWarning() {
|
||||
sameLanguageDismissed = true
|
||||
}
|
||||
|
||||
/// Updates the settings snapshot without restarting the current request.
|
||||
public func updateConfiguration(_ configuration: PanelConfiguration) {
|
||||
let targetChanged = configuration.target.code != self.configuration.target.code
|
||||
self.configuration = configuration
|
||||
if targetChanged || source == nil {
|
||||
effectiveTarget = configuration.target
|
||||
routedSource = nil
|
||||
targetOverride = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the panel and cancels the active request. The event stream stays open.
|
||||
public func close() async {
|
||||
await session.reset()
|
||||
phase = .idle
|
||||
source = nil
|
||||
translation = ""
|
||||
warnings = []
|
||||
error = nil
|
||||
timing = nil
|
||||
sourceLanguage = nil
|
||||
didCopy = false
|
||||
isReplacing = false
|
||||
sameLanguageDismissed = false
|
||||
chunkCount = 1
|
||||
currentChunk = nil
|
||||
totalChunks = nil
|
||||
effectiveTarget = configuration.target
|
||||
routedSource = nil
|
||||
targetOverride = nil
|
||||
lastCaptured = nil
|
||||
}
|
||||
|
||||
/// Stops the event consumer for app termination.
|
||||
public func shutdown() {
|
||||
eventTask?.cancel()
|
||||
eventTask = nil
|
||||
}
|
||||
|
||||
private func request(for captured: CapturedText) -> TranslationSessionRequest {
|
||||
TranslationSessionRequest(
|
||||
captured: captured,
|
||||
target: effectiveTarget,
|
||||
model: configuration.model,
|
||||
keepAlive: configuration.keepAlive,
|
||||
sampling: configuration.sampling,
|
||||
captureLimits: configuration.captureLimits
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension PanelViewModel {
|
||||
private func handle(_ event: TranslationSessionEvent) {
|
||||
switch event {
|
||||
case let .started(epoch, request):
|
||||
handleStarted(epoch: epoch, request: request)
|
||||
case let .chunkStarted(epoch, index, total):
|
||||
handleChunkStarted(epoch: epoch, index: index, total: total)
|
||||
case let .delta(epoch, text):
|
||||
handleDelta(epoch: epoch, text: text)
|
||||
case let .finished(epoch, result):
|
||||
handleFinished(epoch: epoch, result: result)
|
||||
case let .failed(epoch, error):
|
||||
handleFailed(epoch: epoch, error: error)
|
||||
case let .cancelled(epoch):
|
||||
handleCancelled(epoch: epoch)
|
||||
}
|
||||
eventObserver?(event)
|
||||
}
|
||||
|
||||
private func handleStarted(epoch: UInt64, request: TranslationSessionRequest) {
|
||||
currentEpoch = epoch
|
||||
source = request.captured
|
||||
effectiveTarget = request.target
|
||||
translation = ""
|
||||
warnings = []
|
||||
error = nil
|
||||
chunkCount = 1
|
||||
currentChunk = nil
|
||||
totalChunks = nil
|
||||
phase = .translating
|
||||
}
|
||||
|
||||
private func handleChunkStarted(epoch: UInt64, index: Int, total: Int) {
|
||||
guard epoch == currentEpoch else { return }
|
||||
currentChunk = index
|
||||
totalChunks = total
|
||||
}
|
||||
|
||||
private func handleDelta(epoch: UInt64, text: String) {
|
||||
guard epoch == currentEpoch else { return }
|
||||
translation += text
|
||||
phase = .streaming
|
||||
}
|
||||
|
||||
private func handleFinished(epoch: UInt64, result: PipelineResult) {
|
||||
guard epoch == currentEpoch else { return }
|
||||
translation = result.translation
|
||||
warnings = result.warnings
|
||||
timing = result.timing
|
||||
sourceLanguage = result.sourceLanguage
|
||||
chunkCount = result.chunkCount
|
||||
currentChunk = nil
|
||||
totalChunks = nil
|
||||
if result.warnings.contains(.emptyOutput) {
|
||||
error = .emptyOutput
|
||||
phase = .failed
|
||||
} else {
|
||||
phase = .ready
|
||||
}
|
||||
}
|
||||
|
||||
private func handleFailed(epoch: UInt64, error: SprachmittlerError) {
|
||||
guard epoch == currentEpoch else { return }
|
||||
self.error = error
|
||||
currentChunk = nil
|
||||
phase = .failed
|
||||
}
|
||||
|
||||
private func handleCancelled(epoch: UInt64) {
|
||||
guard epoch == currentEpoch else { return }
|
||||
phase = .idle
|
||||
error = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import Foundation
|
||||
|
||||
/// UI-facing warning helpers re-exported by Core.
|
||||
public extension TranslationWarning {
|
||||
/// A short panel message. It never rewrites the translation.
|
||||
var panelMessage: String {
|
||||
switch self {
|
||||
case let .preambleDetected(line):
|
||||
String(localized: "The model added an explanation: “\(line)”")
|
||||
case .truncated:
|
||||
String(localized: "The translation was cut off.")
|
||||
case .repetitionLoop:
|
||||
String(localized: "The translation started repeating.")
|
||||
case let .missingProtectedToken(token):
|
||||
String(localized: "A protected token was lost: \(token)")
|
||||
case .emptyOutput:
|
||||
String(localized: "The model returned an empty translation.")
|
||||
case let .sameLanguage(source, target):
|
||||
String(localized: "This text already appears to be in \(target) (detected \(source)).")
|
||||
case .numericMismatch:
|
||||
String(localized: "A number may have changed.")
|
||||
case let .chunkFailed(index):
|
||||
String(localized: "Chunk \(index + 1) failed; the translation is incomplete.")
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the warning should disable Replace by default.
|
||||
/// The domain error that blocks Replace for this warning.
|
||||
var insertionError: SprachmittlerError {
|
||||
switch self {
|
||||
case .truncated: .truncated
|
||||
case .repetitionLoop: .repetitionLoop
|
||||
case .preambleDetected: .preambleDetected
|
||||
case let .missingProtectedToken(token): .protectedTokenLost(token: token)
|
||||
case .emptyOutput: .emptyOutput
|
||||
case .chunkFailed: .server(status: 0, message: "Chunk failed")
|
||||
case .sameLanguage, .numericMismatch: .cancelled
|
||||
}
|
||||
}
|
||||
|
||||
var isBlocking: Bool {
|
||||
switch self {
|
||||
case .preambleDetected, .truncated, .repetitionLoop, .missingProtectedToken, .emptyOutput, .chunkFailed:
|
||||
true
|
||||
case .sameLanguage, .numericMismatch:
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/// Accessibility is optional and used only for Replace (SEE: docs/SELECTION_AND_CLIPBOARD.md).
|
||||
@MainActor
|
||||
public protocol AccessibilityPermissionChecking: AnyObject {
|
||||
/// Whether the app is currently trusted for Accessibility.
|
||||
var isTrusted: Bool { get }
|
||||
/// Shows the system prompt. Call only from onboarding or an explicit Replace click.
|
||||
func requestTrust()
|
||||
/// Opens System Settings ▸ Privacy & Security ▸ Accessibility.
|
||||
func openSettings()
|
||||
}
|
||||
|
||||
/// The login-item seam; production uses `SMAppService.mainApp`.
|
||||
@MainActor
|
||||
public protocol LaunchAtLoginControlling: AnyObject {
|
||||
/// The current system state.
|
||||
var isEnabled: Bool { get }
|
||||
/// Registers or unregisters the app.
|
||||
func setEnabled(_ enabled: Bool) throws
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import Foundation
|
||||
|
||||
/// The minimal persistence seam for settings. Production uses `UserDefaults`; tests use memory.
|
||||
public protocol SettingsDataStoring: Sendable {
|
||||
/// Returns the stored data, if any.
|
||||
func data(forKey key: String) -> Data?
|
||||
/// Stores or removes data.
|
||||
func set(_ data: Data?, forKey key: String)
|
||||
}
|
||||
|
||||
/// The production `UserDefaults` adapter. `UserDefaults` is thread-safe; the unchecked
|
||||
/// conformance records that no additional mutable state lives here.
|
||||
public final class UserDefaultsSettingsDataStore: SettingsDataStoring, @unchecked Sendable {
|
||||
private let defaults: UserDefaults
|
||||
|
||||
/// Creates an adapter.
|
||||
public init(defaults: UserDefaults = .standard) {
|
||||
self.defaults = defaults
|
||||
}
|
||||
|
||||
public func data(forKey key: String) -> Data? {
|
||||
defaults.data(forKey: key)
|
||||
}
|
||||
|
||||
public func set(_ data: Data?, forKey key: String) {
|
||||
if let data {
|
||||
defaults.set(data, forKey: key)
|
||||
} else {
|
||||
defaults.removeObject(forKey: key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads, caches, migrates and saves `AppSettings` as one JSON blob.
|
||||
///
|
||||
/// `@unchecked Sendable` is safe: every cached value is guarded by `lock`, and the storage seam is
|
||||
/// itself Sendable.
|
||||
public final class SettingsStore: @unchecked Sendable {
|
||||
/// The single defaults key; only configuration is stored here.
|
||||
public static let storageKey = "com.schihei.sprachmittler.settings"
|
||||
|
||||
private let storage: any SettingsDataStoring
|
||||
private let lock = NSLock()
|
||||
private var cached: AppSettings?
|
||||
|
||||
/// Creates a store.
|
||||
public init(storage: any SettingsDataStoring = UserDefaultsSettingsDataStore()) {
|
||||
self.storage = storage
|
||||
}
|
||||
|
||||
/// The current settings, loading and migrating once.
|
||||
public func current() -> AppSettings {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if let cached {
|
||||
return cached
|
||||
}
|
||||
let settings = loadLocked()
|
||||
cached = settings
|
||||
return settings
|
||||
}
|
||||
|
||||
/// Saves settings and updates the cache.
|
||||
public func save(_ settings: AppSettings) throws {
|
||||
let data = try JSONEncoder().encode(settings)
|
||||
lock.lock()
|
||||
storage.set(data, forKey: Self.storageKey)
|
||||
cached = settings
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
/// Mutates and saves atomically.
|
||||
public func update(_ transform: (inout AppSettings) -> Void) throws {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
var settings = cached ?? loadLocked()
|
||||
transform(&settings)
|
||||
let data = try JSONEncoder().encode(settings)
|
||||
storage.set(data, forKey: Self.storageKey)
|
||||
cached = settings
|
||||
}
|
||||
|
||||
/// Deletes the stored blob and returns defaults.
|
||||
@discardableResult
|
||||
public func reset() -> AppSettings {
|
||||
lock.lock()
|
||||
storage.set(nil, forKey: Self.storageKey)
|
||||
let settings = AppSettings()
|
||||
cached = settings
|
||||
lock.unlock()
|
||||
return settings
|
||||
}
|
||||
|
||||
private func loadLocked() -> AppSettings {
|
||||
guard let data = storage.data(forKey: Self.storageKey) else {
|
||||
return AppSettings()
|
||||
}
|
||||
return (try? JSONDecoder().decode(AppSettings.self, from: data)) ?? AppSettings()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// Settings presentation model. It never stores source text or translations.
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class SettingsViewModel {
|
||||
/// The editable draft.
|
||||
public var draft: AppSettings
|
||||
/// A settings validation or save error.
|
||||
public private(set) var saveError: String?
|
||||
/// A launch-at-login error; the other settings still saved.
|
||||
public private(set) var launchError: String?
|
||||
/// Installed Hy-MT3 tags, loaded on demand.
|
||||
public private(set) var installedModels: [InstalledModel] = []
|
||||
/// True while refreshing the model list.
|
||||
public private(set) var isRefreshingModels = false
|
||||
|
||||
private let store: SettingsStore
|
||||
private let catalogProvider: @Sendable (AppSettings) throws -> any OllamaCatalog
|
||||
private let launchAtLogin: any LaunchAtLoginControlling
|
||||
|
||||
/// Creates the settings model.
|
||||
public init(
|
||||
store: SettingsStore,
|
||||
catalogProvider: @escaping @Sendable (AppSettings) throws -> any OllamaCatalog,
|
||||
launchAtLogin: any LaunchAtLoginControlling
|
||||
) {
|
||||
self.store = store
|
||||
self.catalogProvider = catalogProvider
|
||||
self.launchAtLogin = launchAtLogin
|
||||
draft = store.current()
|
||||
draft.launchAtLogin = launchAtLogin.isEnabled
|
||||
}
|
||||
|
||||
/// Reloads the draft from storage.
|
||||
public func reload() {
|
||||
draft = store.current()
|
||||
draft.launchAtLogin = launchAtLogin.isEnabled
|
||||
saveError = nil
|
||||
}
|
||||
|
||||
/// Validates and saves the draft. The remote endpoint policy is enforced here.
|
||||
public func save() {
|
||||
draft.sanitize()
|
||||
saveError = nil
|
||||
launchError = nil
|
||||
do {
|
||||
_ = try draft.validatedEndpoint()
|
||||
try store.save(draft)
|
||||
} catch let rejection as EndpointRejection {
|
||||
saveError = SprachmittlerError.endpointRejected(reason: rejection).userMessage
|
||||
return
|
||||
} catch {
|
||||
saveError = "Settings could not be saved."
|
||||
return
|
||||
}
|
||||
do {
|
||||
try launchAtLogin.setEnabled(draft.launchAtLogin)
|
||||
} catch {
|
||||
launchError = "Launch at login could not be changed."
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets stored settings and the login item.
|
||||
public func reset() {
|
||||
draft = store.reset()
|
||||
try? launchAtLogin.setEnabled(false)
|
||||
saveError = nil
|
||||
launchError = nil
|
||||
}
|
||||
|
||||
/// Refreshes the installed model list using the draft endpoint.
|
||||
public func refreshModels() async {
|
||||
isRefreshingModels = true
|
||||
defer { isRefreshingModels = false }
|
||||
do {
|
||||
let catalog = try catalogProvider(draft)
|
||||
installedModels = try await catalog.installedModels()
|
||||
.filter { HyMT3ModelPreset.isHyMT3($0.name) }
|
||||
saveError = nil
|
||||
} catch let rejection as EndpointRejection {
|
||||
saveError = SprachmittlerError.endpointRejected(reason: rejection).userMessage
|
||||
} catch let error as OllamaError {
|
||||
saveError = SprachmittlerError(ollama: error).userMessage
|
||||
} catch let error as SprachmittlerError {
|
||||
saveError = error.userMessage
|
||||
} catch {
|
||||
saveError = "Models could not be loaded."
|
||||
}
|
||||
}
|
||||
|
||||
/// The model tags offered to the picker, including the current values.
|
||||
public var modelChoices: [String] {
|
||||
var tags = Set(installedModels.map(\.name))
|
||||
tags.insert(draft.model)
|
||||
if let fast = draft.fastModel {
|
||||
tags.insert(fast)
|
||||
}
|
||||
return tags.sorted()
|
||||
}
|
||||
|
||||
/// The licence text from the model card, not the Ollama field.
|
||||
public var licenceNote: String {
|
||||
"Hy-MT3 is Apache-2.0 per the model card. Sprachmittler bundles no weights."
|
||||
}
|
||||
|
||||
/// The selected model digest, when installed.
|
||||
public var selectedDigest: String? {
|
||||
installedModels.first { $0.name == draft.model }?.digest
|
||||
}
|
||||
|
||||
/// The installed Fast model candidate, if any.
|
||||
public var detectedFastModel: String? {
|
||||
installedModels.first { HyMT3ModelPreset.isFastModel($0.name) }?.name
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import os
|
||||
|
||||
/// A started signpost interval.
|
||||
///
|
||||
/// The value is intentionally not `Sendable`: an interval must begin and end on the same task.
|
||||
/// Obtain one from ``Signposts/begin(_:)`` and pass it to ``Signposts/end(_:)``.
|
||||
public struct SignpostInterval {
|
||||
/// The interval name.
|
||||
public let name: SignpostName
|
||||
|
||||
let state: OSSignpostIntervalState
|
||||
let signposter: OSSignposter
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/// Signpost interval names from ARCHITECTURE §15.
|
||||
public enum SignpostName: String, CaseIterable, Sendable {
|
||||
/// Double-copy detection, from the second copy to a captured text.
|
||||
case capture
|
||||
/// Panel presentation.
|
||||
case panel
|
||||
/// An Ollama request, from send to the final delta.
|
||||
case request
|
||||
/// The first translation token.
|
||||
case firstToken
|
||||
/// The full translation of one chunk.
|
||||
case translate
|
||||
/// Output validation.
|
||||
case validate
|
||||
/// Writing the translation to the clipboard.
|
||||
case copy
|
||||
/// Accessibility or paste insertion.
|
||||
case insert
|
||||
|
||||
/// `OSSignposter.beginInterval` requires a `StaticString`, so each case maps to its own literal.
|
||||
public var literal: StaticString {
|
||||
switch self {
|
||||
case .capture: "capture"
|
||||
case .panel: "panel"
|
||||
case .request: "request"
|
||||
case .firstToken: "firstToken"
|
||||
case .translate: "translate"
|
||||
case .validate: "validate"
|
||||
case .copy: "copy"
|
||||
case .insert: "insert"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import os
|
||||
|
||||
/// Thin wrapper around `OSSignposter` that uses the names from ARCHITECTURE §15.
|
||||
///
|
||||
/// Leaf modules cannot import Core; the composition root can pass an `OSSignposter` directly to
|
||||
/// them, using the literal names in ARCHITECTURE §15.
|
||||
public struct Signposts: Sendable {
|
||||
private let signposter: OSSignposter
|
||||
|
||||
init(subsystem: String, category: LogCategory) {
|
||||
signposter = OSSignposter(subsystem: subsystem, category: category.rawValue)
|
||||
}
|
||||
|
||||
/// Starts an interval; pair it with ``end(_:)`` on the same task.
|
||||
public func begin(_ name: SignpostName) -> SignpostInterval {
|
||||
let state = signposter.beginInterval(name.literal)
|
||||
return SignpostInterval(name: name, state: state, signposter: signposter)
|
||||
}
|
||||
|
||||
/// Ends an interval started by ``begin(_:)``.
|
||||
public func end(_ interval: SignpostInterval) {
|
||||
interval.signposter.endInterval(interval.name.literal, interval.state)
|
||||
}
|
||||
|
||||
/// Emits a single signpost event.
|
||||
public func event(_ name: SignpostName) {
|
||||
signposter.emitEvent(name.literal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// The domain error taxonomy from ARCHITECTURE §5.
|
||||
///
|
||||
/// Leaf modules throw their own errors (e.g. `OllamaError`); this type is produced at the Core
|
||||
/// boundary by `SprachmittlerError(ollama:)`. UI code shows `userMessage`, never a raw body.
|
||||
public enum SprachmittlerError: Error, Sendable, Equatable {
|
||||
// Capture
|
||||
case noSelection
|
||||
case emptyText
|
||||
case textTooLong(characters: Int, limit: Int)
|
||||
case pasteboardUnavailable
|
||||
// Translation
|
||||
case ollamaUnreachable(url: URL)
|
||||
case ollamaTooOld(found: String, required: String)
|
||||
case endpointRejected(reason: EndpointRejection)
|
||||
case modelNotInstalled(model: String)
|
||||
case noAdapter(model: String)
|
||||
case badRequest(message: String)
|
||||
case server(status: Int, message: String)
|
||||
case timeout(phase: TimeoutPhase)
|
||||
case emptyOutput
|
||||
case truncated
|
||||
case repetitionLoop
|
||||
case preambleDetected
|
||||
case protectedTokenLost(token: String)
|
||||
// Insertion
|
||||
case accessibilityNotTrusted
|
||||
case accessibilityUnsupported(app: String?)
|
||||
case insertionTargetChanged
|
||||
case pasteboardRestoreFailed
|
||||
// General
|
||||
case cancelled
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// A user-facing recovery action. The UI never shows a raw `localizedDescription`.
|
||||
public enum RecoveryAction: Sendable, Equatable {
|
||||
/// Start Ollama.
|
||||
case startOllama
|
||||
/// Copy and run `ollama pull <model>`.
|
||||
case pullModel(String)
|
||||
/// Open the relevant System Settings page.
|
||||
case openSettings
|
||||
/// Copy the translation instead.
|
||||
case copyInstead
|
||||
/// Shorten the selection.
|
||||
case shortenText
|
||||
/// Retry the translation.
|
||||
case retry
|
||||
/// Nothing to do.
|
||||
case none
|
||||
}
|
||||
|
||||
public extension SprachmittlerError {
|
||||
/// A short, non-technical message for the panel and onboarding.
|
||||
var userMessage: String {
|
||||
switch self {
|
||||
case .noSelection:
|
||||
"No text was selected."
|
||||
case .emptyText:
|
||||
"No text was copied."
|
||||
case let .textTooLong(_, limit):
|
||||
"This selection is too long (limit \(limit) characters). You can raise the limit in Settings."
|
||||
case .pasteboardUnavailable:
|
||||
"The clipboard is unavailable."
|
||||
case .ollamaUnreachable:
|
||||
"Ollama is not running."
|
||||
case let .ollamaTooOld(_, required):
|
||||
"Ollama is too old. Version \(required) or newer is required."
|
||||
case let .endpointRejected(reason):
|
||||
"The endpoint is not allowed: \(reason.userMessage)"
|
||||
case .modelNotInstalled:
|
||||
"The Hy-MT3 model is not installed."
|
||||
case .noAdapter:
|
||||
"This model is not supported."
|
||||
case .badRequest:
|
||||
"Ollama rejected the request."
|
||||
case .server:
|
||||
"Ollama returned an error."
|
||||
case .timeout:
|
||||
"Ollama took too long to answer."
|
||||
case .emptyOutput:
|
||||
"The model returned an empty translation."
|
||||
case .truncated:
|
||||
"The translation was cut off."
|
||||
case .repetitionLoop:
|
||||
"The translation started repeating."
|
||||
case .preambleDetected:
|
||||
"The model added an explanation."
|
||||
case .protectedTokenLost:
|
||||
"A URL, placeholder or code token was lost."
|
||||
case .accessibilityNotTrusted:
|
||||
"Replace needs the Accessibility permission."
|
||||
case .accessibilityUnsupported:
|
||||
"This app did not accept the replacement."
|
||||
case .insertionTargetChanged:
|
||||
"The selection changed before Replace."
|
||||
case .pasteboardRestoreFailed:
|
||||
"The previous clipboard could not be restored."
|
||||
case .cancelled:
|
||||
"Translation cancelled."
|
||||
}
|
||||
}
|
||||
|
||||
/// A stable non-text code for diagnostics.
|
||||
var diagnosticCode: String {
|
||||
switch self {
|
||||
case .noSelection: "noSelection"
|
||||
case .emptyText: "emptyText"
|
||||
case .textTooLong: "textTooLong"
|
||||
case .pasteboardUnavailable: "pasteboardUnavailable"
|
||||
case .ollamaUnreachable: "ollamaUnreachable"
|
||||
case .ollamaTooOld: "ollamaTooOld"
|
||||
case .endpointRejected: "endpointRejected"
|
||||
case .modelNotInstalled: "modelNotInstalled"
|
||||
case .noAdapter: "noAdapter"
|
||||
case .badRequest: "badRequest"
|
||||
case .server: "server"
|
||||
case .timeout: "timeout"
|
||||
case .emptyOutput: "emptyOutput"
|
||||
case .truncated: "truncated"
|
||||
case .repetitionLoop: "repetitionLoop"
|
||||
case .preambleDetected: "preambleDetected"
|
||||
case .protectedTokenLost: "protectedTokenLost"
|
||||
case .accessibilityNotTrusted: "accessibilityNotTrusted"
|
||||
case .accessibilityUnsupported: "accessibilityUnsupported"
|
||||
case .insertionTargetChanged: "insertionTargetChanged"
|
||||
case .pasteboardRestoreFailed: "pasteboardRestoreFailed"
|
||||
case .cancelled: "cancelled"
|
||||
}
|
||||
}
|
||||
|
||||
/// The primary recovery action, if any.
|
||||
var recoveryAction: RecoveryAction {
|
||||
switch self {
|
||||
case .ollamaUnreachable:
|
||||
.startOllama
|
||||
case let .modelNotInstalled(model):
|
||||
.pullModel(model)
|
||||
case .ollamaTooOld, .endpointRejected:
|
||||
.openSettings
|
||||
case .textTooLong:
|
||||
.openSettings
|
||||
case .accessibilityNotTrusted:
|
||||
.openSettings
|
||||
case .accessibilityUnsupported, .insertionTargetChanged, .pasteboardRestoreFailed:
|
||||
.copyInstead
|
||||
case .timeout, .server, .emptyOutput, .truncated, .repetitionLoop, .preambleDetected:
|
||||
.retry
|
||||
default:
|
||||
.none
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension EndpointRejection {
|
||||
var userMessage: String {
|
||||
switch self {
|
||||
case .scheme:
|
||||
"only http and https are supported"
|
||||
case .form:
|
||||
"it must not contain credentials, a query or a fragment"
|
||||
case .remoteNotAllowed:
|
||||
"remote endpoints are disabled"
|
||||
case .remoteRequiresHTTPS:
|
||||
"remote endpoints require HTTPS"
|
||||
case .redirect:
|
||||
"redirects are refused"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import Foundation
|
||||
|
||||
/// A text replacement implementation. Accessibility direct replacement is preferred; the paste
|
||||
/// fallback is the second strategy (`docs/SELECTION_AND_CLIPBOARD.md` §4).
|
||||
public protocol TextInserting: Sendable {
|
||||
/// Replaces the captured selection with `translation`.
|
||||
func replace(
|
||||
selection: CapturedText,
|
||||
with translation: String,
|
||||
target: InsertionTarget
|
||||
) async throws -> InsertionOutcome
|
||||
}
|
||||
|
||||
/// Captures the source app and, when Accessibility is trusted, the focused selection at trigger
|
||||
/// time. Never reads a full document value.
|
||||
@MainActor
|
||||
public protocol InsertionTargetProviding {
|
||||
/// Returns the target, or nil when no app is frontmost.
|
||||
func captureTarget() -> InsertionTarget?
|
||||
}
|
||||
|
||||
/// The safety checks shared by AX and paste insertion.
|
||||
public enum InsertionPolicy {
|
||||
/// Verifies the frontmost app and, when available, the selected text.
|
||||
public static func verify(
|
||||
frontmostPID: pid_t,
|
||||
target: InsertionTarget,
|
||||
selectedText: String?,
|
||||
source: String
|
||||
) throws {
|
||||
guard frontmostPID == target.pid else {
|
||||
throw SprachmittlerError.insertionTargetChanged
|
||||
}
|
||||
guard let selectedText else { return }
|
||||
let expected = selectedText
|
||||
.replacingOccurrences(of: "\r\n", with: "\n")
|
||||
.replacingOccurrences(of: "\r", with: "\n")
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let actual = source
|
||||
.replacingOccurrences(of: "\r\n", with: "\n")
|
||||
.replacingOccurrences(of: "\r", with: "\n")
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard expected == actual else {
|
||||
throw SprachmittlerError.insertionTargetChanged
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the text should not be replaced because a blocking warning exists.
|
||||
public static func isBlocked(by warnings: [TranslationWarning]) -> Bool {
|
||||
warnings.contains(where: \.blocksReplacement)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
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,
|
||||
sampling: SamplingOptions = .publisherDefault,
|
||||
onDelta: (@Sendable (String) async -> Void)? = nil,
|
||||
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)? = nil
|
||||
) 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,
|
||||
sampling: sampling,
|
||||
tokens: tokens,
|
||||
onDelta: onDelta
|
||||
)
|
||||
let accumulator = try await translateAll(chunks, context: context, onChunk: onChunk)
|
||||
|
||||
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 sampling: SamplingOptions
|
||||
let tokens: [ProtectedToken]
|
||||
let onDelta: (@Sendable (String) async -> Void)?
|
||||
}
|
||||
|
||||
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,
|
||||
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)?
|
||||
) async throws -> Accumulator {
|
||||
var accumulator = Accumulator()
|
||||
do {
|
||||
for (offset, chunk) in chunks.enumerated() {
|
||||
try Task.checkCancellation()
|
||||
await onChunk?(offset + 1, chunks.count)
|
||||
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
|
||||
if !chunk.separatorAfter.isEmpty {
|
||||
await context.onDelta?(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 makeRequest(chunk: chunk, prompt: prompt, context: context)
|
||||
// A retry replaces the first attempt; do not stream both into the panel.
|
||||
let deltaHandler = retried ? nil : context.onDelta
|
||||
let attempt = try await stream(request, onDelta: deltaHandler)
|
||||
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 func makeRequest(
|
||||
chunk: TextChunk,
|
||||
prompt: PromptVariant,
|
||||
context: TranslationContext
|
||||
) throws -> ChatRequest {
|
||||
try registry.makeRequest(
|
||||
AdapterRequest(
|
||||
text: chunk.text,
|
||||
target: context.target,
|
||||
model: context.model,
|
||||
keepAlive: context.keepAlive,
|
||||
prompt: prompt,
|
||||
sampling: context.sampling
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private struct StreamResult {
|
||||
let text: String
|
||||
let doneReason: String?
|
||||
let metrics: ChatMetrics
|
||||
let firstTokenAt: Date?
|
||||
let looped: Bool
|
||||
}
|
||||
|
||||
private func stream(
|
||||
_ request: ChatRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?
|
||||
) 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
|
||||
await onDelta?(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,245 @@
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// The streaming translation seam used by `TranslationSession`. The production implementation is
|
||||
/// `TranslationPipeline`; tests provide a controlled fake.
|
||||
public protocol TranslationStreaming: Sendable {
|
||||
/// Translates one captured selection, optionally forwarding deltas.
|
||||
func translate(
|
||||
_ request: TranslationSessionRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?
|
||||
) async throws -> PipelineResult
|
||||
|
||||
/// Translates one captured selection, forwarding deltas and the start of each chunk.
|
||||
func translate(
|
||||
_ request: TranslationSessionRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?,
|
||||
onChunk: (@Sendable (_ index: Int, _ total: Int) async -> Void)?
|
||||
) async throws -> PipelineResult
|
||||
}
|
||||
|
||||
public extension TranslationStreaming {
|
||||
/// Fakes that do not report chunk progress use this fallback.
|
||||
func translate(
|
||||
_ request: TranslationSessionRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?,
|
||||
onChunk: (@Sendable (Int, Int) async -> Void)?
|
||||
) async throws -> PipelineResult {
|
||||
try await translate(request, onDelta: onDelta)
|
||||
}
|
||||
}
|
||||
|
||||
extension TranslationPipeline: TranslationStreaming {}
|
||||
|
||||
public extension TranslationPipeline {
|
||||
func translate(
|
||||
_ request: TranslationSessionRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?
|
||||
) async throws -> PipelineResult {
|
||||
try await translate(
|
||||
text: request.captured.text,
|
||||
target: request.target,
|
||||
model: request.model,
|
||||
keepAlive: request.keepAlive,
|
||||
sampling: request.sampling,
|
||||
onDelta: onDelta
|
||||
)
|
||||
}
|
||||
|
||||
func translate(
|
||||
_ request: TranslationSessionRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?,
|
||||
onChunk: (@Sendable (Int, Int) async -> Void)?
|
||||
) async throws -> PipelineResult {
|
||||
try await translate(
|
||||
text: request.captured.text,
|
||||
target: request.target,
|
||||
model: request.model,
|
||||
keepAlive: request.keepAlive,
|
||||
sampling: request.sampling,
|
||||
onDelta: onDelta,
|
||||
onChunk: onChunk
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// One translation request, including the settings snapshot it was built from.
|
||||
public struct TranslationSessionRequest: Sendable, Equatable {
|
||||
/// The captured text.
|
||||
public let captured: CapturedText
|
||||
/// 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 sampling values.
|
||||
public let sampling: SamplingOptions
|
||||
/// The chunk and capture limits accepted for this capture.
|
||||
public let captureLimits: CaptureLimits
|
||||
|
||||
/// Creates a request.
|
||||
public init(
|
||||
captured: CapturedText,
|
||||
target: ModelLanguage,
|
||||
model: String,
|
||||
keepAlive: String,
|
||||
sampling: SamplingOptions = .publisherDefault,
|
||||
captureLimits: CaptureLimits = CaptureLimits()
|
||||
) {
|
||||
self.captured = captured
|
||||
self.target = target
|
||||
self.model = model
|
||||
self.keepAlive = keepAlive
|
||||
self.sampling = sampling
|
||||
self.captureLimits = captureLimits
|
||||
}
|
||||
}
|
||||
|
||||
/// An event from the translation session. The epoch lets the panel drop stale events.
|
||||
public enum TranslationSessionEvent: Sendable, Equatable {
|
||||
/// A request started.
|
||||
case started(epoch: UInt64, request: TranslationSessionRequest)
|
||||
/// One chunk of a multi-part request started (`index` is 1-based).
|
||||
case chunkStarted(epoch: UInt64, index: Int, total: Int)
|
||||
/// One streamed delta.
|
||||
case delta(epoch: UInt64, text: String)
|
||||
/// The final validated result.
|
||||
case finished(epoch: UInt64, result: PipelineResult)
|
||||
/// A domain error.
|
||||
case failed(epoch: UInt64, error: SprachmittlerError)
|
||||
/// The request was cancelled or replaced.
|
||||
case cancelled(epoch: UInt64)
|
||||
}
|
||||
|
||||
/// The only translation actor: one request in flight, epochs discard stale events (ADR-015).
|
||||
public actor TranslationSession {
|
||||
private let pipelineFactory: @Sendable () throws -> any TranslationStreaming
|
||||
private let eventsStream: AsyncStream<TranslationSessionEvent>
|
||||
private let continuation: AsyncStream<TranslationSessionEvent>.Continuation
|
||||
private var epoch: UInt64 = 0
|
||||
private var task: Task<Void, Never>?
|
||||
|
||||
/// Creates a session. The factory reads a settings snapshot and builds a pipeline.
|
||||
public init(pipelineFactory: @escaping @Sendable () throws -> any TranslationStreaming) {
|
||||
self.pipelineFactory = pipelineFactory
|
||||
let pair = AsyncStream<TranslationSessionEvent>.makeStream()
|
||||
eventsStream = pair.stream
|
||||
continuation = pair.continuation
|
||||
}
|
||||
|
||||
/// The event stream. It has one consumer, normally `PanelViewModel`.
|
||||
public func events() -> AsyncStream<TranslationSessionEvent> {
|
||||
eventsStream
|
||||
}
|
||||
|
||||
/// Starts a request, cancelling any active one, and returns its epoch.
|
||||
@discardableResult
|
||||
public func start(_ request: TranslationSessionRequest) -> UInt64 {
|
||||
task?.cancel()
|
||||
epoch &+= 1
|
||||
let currentEpoch = epoch
|
||||
continuation.yield(.started(epoch: currentEpoch, request: request))
|
||||
|
||||
guard validate(request, epoch: currentEpoch) else {
|
||||
return currentEpoch
|
||||
}
|
||||
|
||||
task = Task { [pipelineFactory] in
|
||||
do {
|
||||
let pipeline = try pipelineFactory()
|
||||
let result = try await pipeline.translate(
|
||||
request,
|
||||
onDelta: { delta in
|
||||
await self.forwardDelta(epoch: currentEpoch, text: delta)
|
||||
},
|
||||
onChunk: { index, total in
|
||||
await self.forwardChunk(epoch: currentEpoch, index: index, total: total)
|
||||
}
|
||||
)
|
||||
self.finish(epoch: currentEpoch, result: result)
|
||||
} catch let error as SprachmittlerError {
|
||||
if error == .cancelled {
|
||||
self.cancelEvent(epoch: currentEpoch)
|
||||
} else {
|
||||
self.fail(epoch: currentEpoch, error: error)
|
||||
}
|
||||
} catch let error as OllamaError {
|
||||
self.fail(epoch: currentEpoch, error: SprachmittlerError(ollama: error))
|
||||
} catch let rejection as EndpointRejection {
|
||||
self.fail(
|
||||
epoch: currentEpoch,
|
||||
error: .endpointRejected(reason: rejection)
|
||||
)
|
||||
} catch is CancellationError {
|
||||
self.cancelEvent(epoch: currentEpoch)
|
||||
} catch {
|
||||
self.fail(
|
||||
epoch: currentEpoch,
|
||||
error: .server(status: 0, message: "Translation failed")
|
||||
)
|
||||
}
|
||||
}
|
||||
return currentEpoch
|
||||
}
|
||||
|
||||
/// Cancels the active request and emits a cancellation for its epoch.
|
||||
public func cancel() {
|
||||
let previous = epoch
|
||||
epoch &+= 1
|
||||
task?.cancel()
|
||||
task = nil
|
||||
continuation.yield(.cancelled(epoch: previous))
|
||||
}
|
||||
|
||||
/// Cancels without emitting. Use when the panel closes.
|
||||
public func reset() {
|
||||
epoch &+= 1
|
||||
task?.cancel()
|
||||
task = nil
|
||||
}
|
||||
|
||||
private func validate(_ request: TranslationSessionRequest, epoch eventEpoch: UInt64) -> Bool {
|
||||
switch CapturePolicy.validate(request.captured.text, limits: request.captureLimits) {
|
||||
case .valid:
|
||||
return true
|
||||
case .empty:
|
||||
continuation.yield(.failed(epoch: eventEpoch, error: .emptyText))
|
||||
return false
|
||||
case let .textTooLong(characters, limit):
|
||||
continuation.yield(
|
||||
.failed(epoch: eventEpoch, error: .textTooLong(characters: characters, limit: limit))
|
||||
)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private func forwardDelta(epoch eventEpoch: UInt64, text: String) {
|
||||
guard eventEpoch == epoch else { return }
|
||||
continuation.yield(.delta(epoch: eventEpoch, text: text))
|
||||
}
|
||||
|
||||
private func forwardChunk(epoch eventEpoch: UInt64, index: Int, total: Int) {
|
||||
guard eventEpoch == epoch else { return }
|
||||
continuation.yield(.chunkStarted(epoch: eventEpoch, index: index, total: total))
|
||||
}
|
||||
|
||||
private func finish(epoch eventEpoch: UInt64, result: PipelineResult) {
|
||||
guard eventEpoch == epoch else { return }
|
||||
task = nil
|
||||
continuation.yield(.finished(epoch: eventEpoch, result: result))
|
||||
}
|
||||
|
||||
private func fail(epoch eventEpoch: UInt64, error: SprachmittlerError) {
|
||||
guard eventEpoch == epoch else { return }
|
||||
task = nil
|
||||
continuation.yield(.failed(epoch: eventEpoch, error: error))
|
||||
}
|
||||
|
||||
private func cancelEvent(epoch eventEpoch: UInt64) {
|
||||
guard eventEpoch == epoch else { return }
|
||||
task = nil
|
||||
continuation.yield(.cancelled(epoch: eventEpoch))
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
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 = lang("en", "English")
|
||||
/// German.
|
||||
public static let german = lang("de", "German")
|
||||
|
||||
/// 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,
|
||||
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),
|
||||
]
|
||||
|
||||
/// 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
|
||||
.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
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/// The provisional Hy-MT3 model tags. The default is decided by the M7 evaluation; this constant
|
||||
/// is the only place the tag appears outside docs and tests.
|
||||
public enum HyMT3ModelPreset {
|
||||
/// The provisional default: Hy-MT3-7B Q4_K_M.
|
||||
public static let defaultModel = "hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M"
|
||||
/// The Fast preset: Hy-MT3-1.8B Q4_K_M.
|
||||
public static let fastModel = "hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M"
|
||||
/// The settings default for keeping the model warm.
|
||||
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")
|
||||
}
|
||||
|
||||
/// True for the 1.8B Fast tag, without hard-coding the full tag in UI code.
|
||||
public static func isFastModel(_ model: String) -> Bool {
|
||||
model.lowercased().contains("hy-mt3-1.8b")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// Documented Hy-MT3 option sets (`docs/HYMT3_MODEL.md` §2).
|
||||
public enum HyMT3Options {
|
||||
/// 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()
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/// 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 prefix depends only on the target language; the source text is appended last so the
|
||||
/// Ollama prompt cache stays valid.
|
||||
public static func defaultTranslation(target: ModelLanguage, source: String) -> String {
|
||||
let prefix = "Translate the following text into \(target.modelName). "
|
||||
+ "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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
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 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(language.code)?.code ?? language.code
|
||||
var agreed = false
|
||||
for code in detection.alternatives {
|
||||
guard let resolved = HyMT3Languages.resolve(code),
|
||||
resolved.code.caseInsensitiveCompare(targetCode) == .orderedSame
|
||||
else {
|
||||
return false
|
||||
}
|
||||
agreed = true
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import Foundation
|
||||
|
||||
/// A BCP-47 code paired with the exact English model-card name used in the prompt.
|
||||
///
|
||||
/// `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
|
||||
|
||||
/// `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
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
|
||||
|
||||
/// Namespace for the SprachmittlerEngines module.
|
||||
public enum SprachmittlerEnginesModule {
|
||||
public static let moduleName = "SprachmittlerEngines"
|
||||
}
|
||||
@@ -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,55 @@
|
||||
import SprachmittlerText
|
||||
|
||||
/// The effective target for one translation, after a language rule or an explicit override.
|
||||
public struct TranslationDirection: Sendable, Equatable {
|
||||
/// The language the request will translate into.
|
||||
public let target: 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, didRoute: Bool, source: ModelLanguage?) {
|
||||
self.target = target
|
||||
self.didRoute = didRoute
|
||||
self.source = source
|
||||
}
|
||||
}
|
||||
|
||||
/// Chooses the direction for a capture. Detection stays advisory: a switch needs the same
|
||||
/// high-confidence agreement as the same-language advisory.
|
||||
public enum TranslationDirectionPolicy {
|
||||
/// Resolves the target.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - configuredTarget: The user's mother tongue, used when no rule matches.
|
||||
/// - routes: The source-to-target rules.
|
||||
/// - detection: The advisory source-language detection.
|
||||
/// - override: An explicit target choice for the current capture, or nil to use the routes.
|
||||
public static func resolve(
|
||||
configuredTarget: ModelLanguage,
|
||||
routes: [LanguageRoute],
|
||||
detection: LanguageDetection?,
|
||||
override: ModelLanguage?
|
||||
) -> TranslationDirection {
|
||||
if let override {
|
||||
return TranslationDirection(target: override, didRoute: false, source: nil)
|
||||
}
|
||||
guard let detection else {
|
||||
return TranslationDirection(target: configuredTarget, didRoute: false, source: nil)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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,196 @@
|
||||
import Foundation
|
||||
|
||||
/// The corpus categories from `docs/MODEL_EVALUATION.md` §1.
|
||||
public enum EvaluationCategory: String, Codable, CaseIterable, Sendable {
|
||||
/// EN→DE prose.
|
||||
case enDeProse = "en-de-prose"
|
||||
/// DE→EN prose.
|
||||
case deEnProse = "de-en-prose"
|
||||
/// Technical text.
|
||||
case technical
|
||||
/// Legal text.
|
||||
case legal
|
||||
/// Short UI strings.
|
||||
case uiStrings = "ui"
|
||||
/// Markdown structure.
|
||||
case markdown
|
||||
/// JSON keys and values.
|
||||
case json
|
||||
/// URLs, placeholders and e-mail addresses.
|
||||
case placeholders
|
||||
/// Numbers and units.
|
||||
case numbers
|
||||
/// Non-literal meaning.
|
||||
case idioms
|
||||
/// Long, chunked text.
|
||||
case long
|
||||
/// CJK text.
|
||||
case cjk
|
||||
/// Right-to-left text.
|
||||
case rtl
|
||||
}
|
||||
|
||||
/// One manifest segment, before paths are resolved.
|
||||
public struct EvaluationSegment: Codable, Sendable, Equatable {
|
||||
/// Stable identifier matching the schema pattern.
|
||||
public let id: String
|
||||
/// Source path relative to the manifest.
|
||||
public let source: String
|
||||
/// Source BCP-47 code.
|
||||
public let sourceLanguage: String
|
||||
/// Target BCP-47 code.
|
||||
public let targetLanguage: String
|
||||
/// Evaluation category.
|
||||
public let category: EvaluationCategory
|
||||
/// Reference path relative to the manifest.
|
||||
public let reference: String
|
||||
/// `human` or `public`.
|
||||
public let referenceKind: String
|
||||
/// Optional notes.
|
||||
public let notes: String?
|
||||
}
|
||||
|
||||
/// The corpus manifest from `evaluation/corpus.schema.json`.
|
||||
public struct EvaluationManifest: Codable, Sendable, Equatable {
|
||||
/// Schema version; must be 1.
|
||||
public let version: Int
|
||||
/// Optional description.
|
||||
public let description: String?
|
||||
/// The segments.
|
||||
public let segments: [EvaluationSegment]
|
||||
}
|
||||
|
||||
/// A segment with its source and reference text loaded.
|
||||
public struct ResolvedSegment: Sendable, Equatable {
|
||||
/// The manifest segment.
|
||||
public let segment: EvaluationSegment
|
||||
/// Source text.
|
||||
public let sourceText: String
|
||||
/// Human/public reference.
|
||||
public let referenceText: String
|
||||
}
|
||||
|
||||
/// A manifest with all paths resolved and text loaded.
|
||||
public struct ResolvedManifest: Sendable, Equatable {
|
||||
/// The original manifest.
|
||||
public let manifest: EvaluationManifest
|
||||
/// The selected segments.
|
||||
public let segments: [ResolvedSegment]
|
||||
}
|
||||
|
||||
/// Precise manifest failures for the CLI.
|
||||
public enum ManifestError: Error, Equatable, CustomStringConvertible {
|
||||
case unreadable(String)
|
||||
case invalidJSON(String)
|
||||
case unsupportedVersion(Int)
|
||||
case emptySegments
|
||||
case invalidID(String)
|
||||
case duplicateID(String)
|
||||
case invalidLanguage(String)
|
||||
case invalidReferenceKind(String)
|
||||
case missingFile(String)
|
||||
case emptyFile(String)
|
||||
case noMatchingTarget(String)
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case let .unreadable(path): "The manifest could not be read: \(path)"
|
||||
case let .invalidJSON(detail): "The manifest is not valid JSON: \(detail)"
|
||||
case let .unsupportedVersion(version): "Unsupported manifest version \(version); expected 1."
|
||||
case .emptySegments: "The manifest has no segments."
|
||||
case let .invalidID(id): "Invalid segment ID '\(id)'; use lowercase letters, digits and hyphens."
|
||||
case let .duplicateID(id): "Duplicate segment ID '\(id)'."
|
||||
case let .invalidLanguage(code): "Invalid BCP-47 language code '\(code)'."
|
||||
case let .invalidReferenceKind(kind): "Invalid referenceKind '\(kind)'; use human or public."
|
||||
case let .missingFile(path): "Missing corpus file: \(path)"
|
||||
case let .emptyFile(path): "Empty corpus file: \(path)"
|
||||
case let .noMatchingTarget(target): "No segments target '\(target)'."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads and validates a corpus manifest without reading any private path implicitly.
|
||||
public enum EvaluationManifestLoader {
|
||||
private static let idPattern = try? NSRegularExpression(pattern: "^[a-z0-9][a-z0-9-]{1,63}$")
|
||||
private static let languagePattern = try? NSRegularExpression(
|
||||
pattern: "^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$"
|
||||
)
|
||||
|
||||
/// Loads `url`, resolves every source/reference path and filters to `target` when supplied.
|
||||
public static func load(manifestURL url: URL, target: String? = nil) throws -> ResolvedManifest {
|
||||
let data: Data
|
||||
do {
|
||||
data = try Data(contentsOf: url)
|
||||
} catch {
|
||||
throw ManifestError.unreadable(url.path)
|
||||
}
|
||||
let manifest: EvaluationManifest
|
||||
do {
|
||||
manifest = try JSONDecoder().decode(EvaluationManifest.self, from: data)
|
||||
} catch {
|
||||
throw ManifestError.invalidJSON(String(describing: error))
|
||||
}
|
||||
guard manifest.version == 1 else {
|
||||
throw ManifestError.unsupportedVersion(manifest.version)
|
||||
}
|
||||
guard !manifest.segments.isEmpty else {
|
||||
throw ManifestError.emptySegments
|
||||
}
|
||||
|
||||
let base = url.deletingLastPathComponent()
|
||||
var seen = Set<String>()
|
||||
var resolved: [ResolvedSegment] = []
|
||||
for segment in manifest.segments {
|
||||
try validate(segment)
|
||||
guard seen.insert(segment.id).inserted else {
|
||||
throw ManifestError.duplicateID(segment.id)
|
||||
}
|
||||
if let target, segment.targetLanguage != target {
|
||||
continue
|
||||
}
|
||||
let sourceURL = URL(fileURLWithPath: segment.source, relativeTo: base).standardizedFileURL
|
||||
let referenceURL = URL(fileURLWithPath: segment.reference, relativeTo: base).standardizedFileURL
|
||||
let source = try read(sourceURL)
|
||||
let reference = try read(referenceURL)
|
||||
resolved.append(
|
||||
ResolvedSegment(segment: segment, sourceText: source, referenceText: reference)
|
||||
)
|
||||
}
|
||||
if let target, resolved.isEmpty {
|
||||
throw ManifestError.noMatchingTarget(target)
|
||||
}
|
||||
return ResolvedManifest(manifest: manifest, segments: resolved)
|
||||
}
|
||||
|
||||
private static func validate(_ segment: EvaluationSegment) throws {
|
||||
let idRange = NSRange(location: 0, length: (segment.id as NSString).length)
|
||||
guard idPattern?.firstMatch(in: segment.id, range: idRange) != nil else {
|
||||
throw ManifestError.invalidID(segment.id)
|
||||
}
|
||||
for code in [segment.sourceLanguage, segment.targetLanguage] {
|
||||
let range = NSRange(location: 0, length: (code as NSString).length)
|
||||
guard languagePattern?.firstMatch(in: code, range: range) != nil else {
|
||||
throw ManifestError.invalidLanguage(code)
|
||||
}
|
||||
}
|
||||
guard ["human", "public"].contains(segment.referenceKind) else {
|
||||
throw ManifestError.invalidReferenceKind(segment.referenceKind)
|
||||
}
|
||||
}
|
||||
|
||||
private static func read(_ url: URL) throws -> String {
|
||||
guard FileManager.default.fileExists(atPath: url.path) else {
|
||||
throw ManifestError.missingFile(url.path)
|
||||
}
|
||||
let text: String
|
||||
do {
|
||||
text = try String(contentsOf: url, encoding: .utf8)
|
||||
} catch {
|
||||
throw ManifestError.unreadable(url.path)
|
||||
}
|
||||
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
throw ManifestError.emptyFile(url.path)
|
||||
}
|
||||
return text
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerText
|
||||
|
||||
/// chrF and BLEU metrics with no Python dependency (`docs/MODEL_EVALUATION.md` §3).
|
||||
public enum EvaluationMetrics {
|
||||
/// Character n-gram F-score. The beta is 2; spaces and punctuation count as characters.
|
||||
public static func chrF(reference: String, hypothesis: String) -> Double {
|
||||
let ref = Array(reference.lowercased())
|
||||
let hyp = Array(hypothesis.lowercased())
|
||||
guard !ref.isEmpty || !hyp.isEmpty else { return 100 }
|
||||
|
||||
var scores: [Double] = []
|
||||
for size in 1 ... 6 {
|
||||
let refGrams = ngrams(ref, size: size)
|
||||
let hypGrams = ngrams(hyp, size: size)
|
||||
guard !refGrams.isEmpty, !hypGrams.isEmpty else { continue }
|
||||
let matched = min(min(refGrams.count, hypGrams.count), matchingCount(refGrams, hypGrams))
|
||||
let precision = Double(matched) / Double(hypGrams.count)
|
||||
let recall = Double(matched) / Double(refGrams.count)
|
||||
guard precision + recall > 0 else {
|
||||
scores.append(0)
|
||||
continue
|
||||
}
|
||||
let beta = 2.0
|
||||
let betaSquared = beta * beta
|
||||
scores.append((1 + betaSquared) * precision * recall / (betaSquared * precision + recall))
|
||||
}
|
||||
guard !scores.isEmpty else { return 100 }
|
||||
return 100 * scores.reduce(0, +) / Double(scores.count)
|
||||
}
|
||||
|
||||
/// A corpus-style BLEU percentage for one hypothesis/reference pair.
|
||||
public static func bleu(reference: String, hypothesis: String) -> Double {
|
||||
let ref = reference.lowercased().split(whereSeparator: \.isWhitespace).map(String.init)
|
||||
let hyp = hypothesis.lowercased().split(whereSeparator: \.isWhitespace).map(String.init)
|
||||
guard !hyp.isEmpty else { return 0 }
|
||||
|
||||
var logSum = 0.0
|
||||
for size in 1 ... 4 {
|
||||
let hypGrams = wordNgrams(hyp, size: size)
|
||||
let refGrams = wordNgrams(ref, size: size)
|
||||
guard !hypGrams.isEmpty else { return 0 }
|
||||
let matched = min(min(hypGrams.count, refGrams.count), matchingCount(hypGrams, refGrams))
|
||||
guard matched > 0 else { return 0 }
|
||||
logSum += log(Double(matched) / Double(hypGrams.count))
|
||||
}
|
||||
let penalty = hyp.count < ref.count ? exp(1 - Double(ref.count) / Double(hyp.count)) : 1
|
||||
return 100 * penalty * exp(logSum / 4)
|
||||
}
|
||||
|
||||
/// Share of protected-token kinds that survive exactly; 1.0 when the source has none.
|
||||
public static func tokenRetention(source: String, translation: String) -> Double {
|
||||
let tokens = ProtectedTokenScanner().scan(source)
|
||||
guard !tokens.isEmpty else { return 1 }
|
||||
let retained = tokens.filter { token in
|
||||
translation.components(separatedBy: token.value).count - 1
|
||||
>= source.components(separatedBy: token.value).count - 1
|
||||
}
|
||||
return Double(retained.count) / Double(tokens.count)
|
||||
}
|
||||
|
||||
/// Share of source numeric values present after locale normalisation; 1.0 when none.
|
||||
public static func numericConsistency(source: String, translation: String) -> Double {
|
||||
let sourceNumbers = Set(NumericTokenNormalizer.numbers(in: source))
|
||||
guard !sourceNumbers.isEmpty else { return 1 }
|
||||
let translated = Set(NumericTokenNormalizer.numbers(in: translation))
|
||||
return Double(sourceNumbers.intersection(translated).count) / Double(sourceNumbers.count)
|
||||
}
|
||||
|
||||
private static func ngrams(_ characters: [Character], size: Int) -> [String] {
|
||||
guard characters.count >= size else { return [] }
|
||||
return (0 ... characters.count - size).map { index in
|
||||
String(characters[index ..< index + size])
|
||||
}
|
||||
}
|
||||
|
||||
private static func wordNgrams(_ words: [String], size: Int) -> [String] {
|
||||
guard words.count >= size else { return [] }
|
||||
return (0 ... words.count - size).map { index in
|
||||
words[index ..< index + size].joined(separator: " ")
|
||||
}
|
||||
}
|
||||
|
||||
private static func matchingCount(_ lhs: [String], _ rhs: [String]) -> Int {
|
||||
var rhsCounts: [String: Int] = [:]
|
||||
for gram in rhs {
|
||||
rhsCounts[gram, default: 0] += 1
|
||||
}
|
||||
var matched = 0
|
||||
for gram in lhs {
|
||||
guard let count = rhsCounts[gram], count > 0 else { continue }
|
||||
matched += 1
|
||||
rhsCounts[gram] = count - 1
|
||||
}
|
||||
return matched
|
||||
}
|
||||
}
|
||||