Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8064ac430 | ||
|
|
f466e6dd1c | ||
|
|
40733473c5 | ||
|
|
2cce12ff17 | ||
|
|
0ab5ae78bf |
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/
|
||||
|
||||
@@ -214,6 +214,7 @@ final class AppEnvironment {
|
||||
keepAlive: settings.keepModelLoaded,
|
||||
sampling: settings.samplingOptions,
|
||||
showSourcePreview: settings.showSourcePreview,
|
||||
translationFontSize: settings.translationFontSize,
|
||||
recentTargets: settings.recentTargets
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -20,6 +20,7 @@ final class PanelController: NSObject, NSWindowDelegate {
|
||||
super.init()
|
||||
panel.delegate = self
|
||||
panel.isFloatingPanel = true
|
||||
panel.isMovable = true
|
||||
panel.becomesKeyOnlyIfNeeded = true
|
||||
panel.level = .floating
|
||||
panel.hidesOnDeactivate = false
|
||||
@@ -34,7 +35,7 @@ final class PanelController: NSObject, NSWindowDelegate {
|
||||
panel.standardWindowButton(.closeButton)?.isHidden = true
|
||||
panel.standardWindowButton(.miniaturizeButton)?.isHidden = true
|
||||
panel.standardWindowButton(.zoomButton)?.isHidden = true
|
||||
panel.contentView = NSHostingView(
|
||||
panel.contentView = PanelHostingView(
|
||||
rootView: PanelView(
|
||||
model: viewModel,
|
||||
onClose: { [weak self] in self?.close() }
|
||||
@@ -45,7 +46,9 @@ final class PanelController: NSObject, NSWindowDelegate {
|
||||
|
||||
/// Shows the panel near the mouse without activating the app.
|
||||
func show() {
|
||||
positionNearMouse()
|
||||
if !panel.isVisible {
|
||||
positionNearMouse()
|
||||
}
|
||||
panel.orderFrontRegardless()
|
||||
}
|
||||
|
||||
@@ -59,6 +62,20 @@ final class PanelController: NSObject, NSWindowDelegate {
|
||||
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
|
||||
|
||||
@@ -14,7 +14,7 @@ struct PanelView: View {
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
header
|
||||
if showSource, let source = model.source {
|
||||
if model.configuration.showSourcePreview, let source = model.source {
|
||||
sourcePreview(source)
|
||||
}
|
||||
translationArea
|
||||
@@ -41,17 +41,32 @@ struct PanelView: View {
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 10) {
|
||||
Image(systemName: "character.bubble")
|
||||
.font(.title2)
|
||||
.foregroundStyle(.tint)
|
||||
.accessibilityHidden(true)
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text(String(localized: "Translate"))
|
||||
.font(.headline)
|
||||
Text("\(sourceLanguageLabel) → \(model.configuration.target.localizedDisplayName)")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
ZStack(alignment: .leading) {
|
||||
WindowDragArea()
|
||||
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.configuration.target.localizedDisplayName)")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.allowsHitTesting(false)
|
||||
}
|
||||
.frame(height: 44)
|
||||
.contentShape(Rectangle())
|
||||
.help(String(localized: "Drag to move panel"))
|
||||
.accessibilityLabel(String(localized: "Move panel"))
|
||||
|
||||
Spacer()
|
||||
Button {
|
||||
showLanguagePicker.toggle()
|
||||
@@ -97,17 +112,18 @@ struct PanelView: View {
|
||||
}
|
||||
.frame(maxHeight: 100)
|
||||
} label: {
|
||||
Text(String(localized: "Source"))
|
||||
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"))
|
||||
}
|
||||
|
||||
private var translationArea: some View {
|
||||
ScrollView {
|
||||
Text(translationText)
|
||||
.font(.body)
|
||||
.font(.system(size: CGFloat(model.configuration.translationFontSize)))
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.foregroundStyle(model.translation.isEmpty ? .secondary : .primary)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// An AppKit drag surface for the non-activating panel. SwiftUI's hosting view consumes mouse
|
||||
/// events, so this view starts a native window drag on the first click.
|
||||
struct WindowDragArea: NSViewRepresentable {
|
||||
func makeNSView(context: Context) -> NSView {
|
||||
DragView()
|
||||
}
|
||||
|
||||
func updateNSView(_ nsView: NSView, context: Context) {}
|
||||
}
|
||||
|
||||
private final class DragView: NSView {
|
||||
override var mouseDownCanMoveWindow: Bool {
|
||||
true
|
||||
}
|
||||
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
window?.performDrag(with: event)
|
||||
}
|
||||
|
||||
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,102 @@
|
||||
/* 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…";
|
||||
@@ -0,0 +1,102 @@
|
||||
/* 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…";
|
||||
@@ -96,6 +96,13 @@ struct SettingsView: View {
|
||||
.accessibilityLabel(String(localized: "Target language"))
|
||||
}
|
||||
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"))
|
||||
}
|
||||
|
||||
Section(String(localized: "Double copy")) {
|
||||
|
||||
@@ -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,14 +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 - --options runtime \
|
||||
--entitlements App/Sprachmittler.entitlements "$(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
|
||||
|
||||
|
||||
@@ -45,7 +45,11 @@ 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(
|
||||
@@ -61,6 +65,7 @@ let package = Package(
|
||||
"SprachmittlerEngines",
|
||||
"SprachmittlerEval",
|
||||
"SprachmittlerOllama",
|
||||
"SprachmittlerText",
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
],
|
||||
swiftSettings: strictSettings
|
||||
@@ -94,7 +99,10 @@ let package = Package(
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerEvalTests",
|
||||
dependencies: ["SprachmittlerEval", "SprachmittlerTestSupport"]
|
||||
dependencies: [
|
||||
"SprachmittlerEval", "SprachmittlerCore", "SprachmittlerEngines", "SprachmittlerText",
|
||||
"SprachmittlerOllama", "SprachmittlerTestSupport",
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerCLITests",
|
||||
|
||||
@@ -59,6 +59,8 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
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
|
||||
/// Reflect the login-item setting.
|
||||
public var launchAtLogin: Bool
|
||||
/// Keep the last translation in memory for the panel.
|
||||
@@ -91,6 +93,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
promptVariantPolicy = .defaultOnly
|
||||
autoCopy = false
|
||||
showSourcePreview = true
|
||||
translationFontSize = 17
|
||||
launchAtLogin = false
|
||||
keepRecentTranslationInMemory = true
|
||||
hasCompletedOnboarding = false
|
||||
@@ -132,6 +135,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
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
|
||||
}
|
||||
@@ -161,6 +165,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
let cjk: Int
|
||||
let numCtx: Int
|
||||
let numPredict: Int
|
||||
let fontSize: Int
|
||||
}
|
||||
|
||||
private struct DecodedSampling {
|
||||
@@ -197,6 +202,11 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
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
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -225,7 +235,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, recentTargetLanguages
|
||||
case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, numCtx, numPredict
|
||||
case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch
|
||||
case promptVariantPolicy, autoCopy, showSourcePreview, launchAtLogin
|
||||
case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, launchAtLogin
|
||||
case keepRecentTranslationInMemory, hasCompletedOnboarding, settingsVersion
|
||||
}
|
||||
|
||||
@@ -257,6 +267,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
maxCharactersCJK = limits.cjk
|
||||
numCtx = limits.numCtx
|
||||
numPredict = limits.numPredict
|
||||
translationFontSize = limits.fontSize
|
||||
let sampling = try Self.decodeSampling(from: container, defaults: defaults)
|
||||
temperature = sampling.temperature
|
||||
topP = sampling.topP
|
||||
@@ -307,6 +318,7 @@ public struct AppSettings: Codable, Sendable, Equatable {
|
||||
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(launchAtLogin, forKey: .launchAtLogin)
|
||||
try container.encode(keepRecentTranslationInMemory, forKey: .keepRecentTranslationInMemory)
|
||||
try container.encode(hasCompletedOnboarding, forKey: .hasCompletedOnboarding)
|
||||
|
||||
@@ -28,6 +28,8 @@ public struct PanelConfiguration: Sendable, Equatable {
|
||||
public var sampling: SamplingOptions
|
||||
/// Whether to show the source preview.
|
||||
public var showSourcePreview: Bool
|
||||
/// Translation text size in points.
|
||||
public var translationFontSize: Int
|
||||
/// Recent targets, most recent first.
|
||||
public var recentTargets: [ModelLanguage]
|
||||
|
||||
@@ -38,6 +40,7 @@ public struct PanelConfiguration: Sendable, Equatable {
|
||||
keepAlive: String,
|
||||
sampling: SamplingOptions = .publisherDefault,
|
||||
showSourcePreview: Bool = true,
|
||||
translationFontSize: Int = 17,
|
||||
recentTargets: [ModelLanguage] = []
|
||||
) {
|
||||
self.target = target
|
||||
@@ -45,6 +48,7 @@ public struct PanelConfiguration: Sendable, Equatable {
|
||||
self.keepAlive = keepAlive
|
||||
self.sampling = sampling
|
||||
self.showSourcePreview = showSourcePreview
|
||||
self.translationFontSize = translationFontSize
|
||||
self.recentTargets = recentTargets
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import Foundation
|
||||
|
||||
/// Writes `report.md` and `report.json` (`docs/MODEL_EVALUATION.md` §4).
|
||||
public enum EvaluationReportWriter {
|
||||
/// Writes both report files into `directory`.
|
||||
public static func write(_ report: EvaluationReport, to directory: URL) throws {
|
||||
let fileManager = FileManager.default
|
||||
try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
let json = try JSONEncoder.reportEncoder.encode(report)
|
||||
try json.write(to: directory.appendingPathComponent("report.json"), options: .atomic)
|
||||
try markdown(report).write(
|
||||
to: directory.appendingPathComponent("report.md"),
|
||||
atomically: true,
|
||||
encoding: .utf8
|
||||
)
|
||||
}
|
||||
|
||||
/// The Markdown report.
|
||||
public static func markdown(_ report: EvaluationReport) -> String {
|
||||
var lines = [
|
||||
"# Sprachmittler evaluation",
|
||||
"",
|
||||
"Generated: \(ISO8601DateFormatter().string(from: report.generatedAt))",
|
||||
"",
|
||||
"## Environment",
|
||||
"",
|
||||
]
|
||||
lines.append(contentsOf: environmentLines(report.environment))
|
||||
lines.append("")
|
||||
for model in report.models {
|
||||
lines.append(contentsOf: modelLines(model))
|
||||
lines.append("")
|
||||
}
|
||||
lines.append(contentsOf: observations)
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
|
||||
private static func environmentLines(_ environment: EvaluationEnvironment) -> [String] {
|
||||
var lines = [
|
||||
"| Key | Value |",
|
||||
"|---|---|",
|
||||
"| Ollama | \(environment.ollamaVersion) |",
|
||||
"| Server | \(environment.serverVersion) |",
|
||||
"| Hardware | \(environment.hardware) |",
|
||||
"| macOS | \(environment.macOS) |",
|
||||
]
|
||||
for (model, digest) in environment.models.sorted(by: { $0.key < $1.key }) {
|
||||
lines.append("| \(model) | \(digest) |")
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
private static func modelLines(_ model: ModelRunResult) -> [String] {
|
||||
var lines = [
|
||||
"## \(model.model)",
|
||||
"",
|
||||
"Temperature \(format(model.temperature)), \(model.runs) run(s) per segment.",
|
||||
"",
|
||||
"| Model | Temp | Category | Segments | Fail % | chrF | BLEU | Token retention | "
|
||||
+ "Num. consistency | First token p50/p90 | Warm s/seg p50/p90 |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|",
|
||||
]
|
||||
for category in model.categories {
|
||||
lines.append(
|
||||
"| \(model.model) | \(format(model.temperature)) | \(category.category.rawValue) | "
|
||||
+ "\(category.segments) | \(format(category.failureRate)) | \(format(category.chrF)) | "
|
||||
+ "\(format(category.bleu)) | \(format(category.tokenRetention)) | "
|
||||
+ "\(format(category.numericConsistency)) | "
|
||||
+ "\(latency(category.firstTokenP50, category.firstTokenP90)) | "
|
||||
+ "\(seconds(category.totalP50, category.totalP90)) |"
|
||||
)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
private static var observations: [String] {
|
||||
[
|
||||
"## Observations",
|
||||
"",
|
||||
"- Automated metrics only; review a sample in the panel and record correction minutes.",
|
||||
"- Token retention below 1.0 or a failure rate above 2% disqualifies a default candidate.",
|
||||
"",
|
||||
"## Limitations",
|
||||
"",
|
||||
"- chrF/BLEU are mechanical and do not judge meaning or style.",
|
||||
"- Memory is not included in this report; use `ollama ps` and record it in PERFORMANCE.md.",
|
||||
"- Private corpus text and raw outputs stay under the ignored results directory.",
|
||||
"",
|
||||
]
|
||||
}
|
||||
|
||||
private static func format(_ value: Double) -> String {
|
||||
String(format: "%.2f", value)
|
||||
}
|
||||
|
||||
private static func latency(_ p50: Int?, _ p90: Int?) -> String {
|
||||
let left = p50.map(String.init) ?? "—"
|
||||
let right = p90.map(String.init) ?? "—"
|
||||
return "\(left)/\(right) ms"
|
||||
}
|
||||
|
||||
private static func seconds(_ p50: Int?, _ p90: Int?) -> String {
|
||||
let left = p50.map { String(format: "%.2f", Double($0) / 1000) } ?? "—"
|
||||
let right = p90.map { String(format: "%.2f", Double($0) / 1000) } ?? "—"
|
||||
return "\(left)/\(right) s"
|
||||
}
|
||||
}
|
||||
|
||||
private extension JSONEncoder {
|
||||
static var reportEncoder: JSONEncoder {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
encoder.dateEncodingStrategy = .iso8601
|
||||
return encoder
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerEngines
|
||||
|
||||
/// Fixed environment facts for a report.
|
||||
public struct EvaluationEnvironment: Codable, Sendable, Equatable {
|
||||
/// Ollama server version.
|
||||
public var serverVersion: String
|
||||
/// Ollama executable version, when known.
|
||||
public var ollamaVersion: String
|
||||
/// Hardware description.
|
||||
public var hardware: String
|
||||
/// macOS version.
|
||||
public var macOS: String
|
||||
/// Model tags and digests.
|
||||
public var models: [String: String]
|
||||
|
||||
/// Creates an environment block.
|
||||
public init(
|
||||
serverVersion: String,
|
||||
ollamaVersion: String,
|
||||
hardware: String,
|
||||
macOS: String,
|
||||
models: [String: String]
|
||||
) {
|
||||
self.serverVersion = serverVersion
|
||||
self.ollamaVersion = ollamaVersion
|
||||
self.hardware = hardware
|
||||
self.macOS = macOS
|
||||
self.models = models
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings for one evaluation run.
|
||||
public struct EvaluationConfiguration: Sendable, Equatable {
|
||||
/// Model tags to evaluate.
|
||||
public var models: [String]
|
||||
/// Number of repeated runs per segment.
|
||||
public var runs: Int
|
||||
/// Keep-alive for the evaluation requests.
|
||||
public var keepAlive: String
|
||||
/// Sampling values.
|
||||
public var sampling: SamplingOptions
|
||||
/// Output directory.
|
||||
public var outputDirectory: URL
|
||||
|
||||
/// Creates a configuration.
|
||||
public init(
|
||||
models: [String],
|
||||
runs: Int = 3,
|
||||
keepAlive: String = "30m",
|
||||
sampling: SamplingOptions = .publisherDefault,
|
||||
outputDirectory: URL
|
||||
) {
|
||||
self.models = models
|
||||
self.runs = max(1, runs)
|
||||
self.keepAlive = keepAlive
|
||||
self.sampling = sampling
|
||||
self.outputDirectory = outputDirectory
|
||||
}
|
||||
}
|
||||
|
||||
/// One segment/run measurement. It contains no source or translation text.
|
||||
public struct SegmentResult: Codable, Sendable, Equatable {
|
||||
/// Segment ID.
|
||||
public let id: String
|
||||
/// Category.
|
||||
public let category: EvaluationCategory
|
||||
/// Run index.
|
||||
public let run: Int
|
||||
/// chrF percentage.
|
||||
public let chrF: Double
|
||||
/// BLEU percentage.
|
||||
public let bleu: Double
|
||||
/// Protected-token retention.
|
||||
public let tokenRetention: Double
|
||||
/// Numeric consistency.
|
||||
public let numericConsistency: Double
|
||||
/// True for empty, blocked, or transport failure.
|
||||
public let failed: Bool
|
||||
/// Warning/error codes only.
|
||||
public let warnings: [String]
|
||||
/// First-token latency.
|
||||
public let firstTokenMs: Int?
|
||||
/// Total latency.
|
||||
public let totalMs: Int?
|
||||
/// Output character count.
|
||||
public let outputCharacters: Int
|
||||
}
|
||||
|
||||
/// Aggregate metrics for one model/category.
|
||||
public struct CategorySummary: Codable, Sendable, Equatable {
|
||||
/// Category.
|
||||
public let category: EvaluationCategory
|
||||
/// Number of segment runs.
|
||||
public let segments: Int
|
||||
/// Failure rate percentage.
|
||||
public let failureRate: Double
|
||||
/// Mean chrF.
|
||||
public let chrF: Double
|
||||
/// Mean BLEU.
|
||||
public let bleu: Double
|
||||
/// Mean token retention.
|
||||
public let tokenRetention: Double
|
||||
/// Mean numeric consistency.
|
||||
public let numericConsistency: Double
|
||||
/// First-token p50/p90.
|
||||
public let firstTokenP50: Int?
|
||||
public let firstTokenP90: Int?
|
||||
/// Warm total p50/p90.
|
||||
public let totalP50: Int?
|
||||
public let totalP90: Int?
|
||||
}
|
||||
|
||||
/// All results for one model.
|
||||
public struct ModelRunResult: Codable, Sendable, Equatable {
|
||||
/// Model tag.
|
||||
public let model: String
|
||||
/// Temperature.
|
||||
public let temperature: Double
|
||||
/// Number of repeats.
|
||||
public let runs: Int
|
||||
/// Raw segment results.
|
||||
public let segments: [SegmentResult]
|
||||
/// Category aggregates.
|
||||
public let categories: [CategorySummary]
|
||||
}
|
||||
|
||||
/// The complete evaluation report.
|
||||
public struct EvaluationReport: Codable, Sendable, Equatable {
|
||||
/// Environment facts.
|
||||
public let environment: EvaluationEnvironment
|
||||
/// Creation date.
|
||||
public let generatedAt: Date
|
||||
/// The model results.
|
||||
public let models: [ModelRunResult]
|
||||
}
|
||||
|
||||
/// Runs the corpus through the documented pipeline.
|
||||
public struct EvaluationRunner: Sendable {
|
||||
/// Builds a streaming pipeline for a model tag.
|
||||
public typealias PipelineFactory = @Sendable (String) throws -> any TranslationStreaming
|
||||
/// Warms a model with fixed synthetic text.
|
||||
public typealias WarmUp = @Sendable (String) async throws -> Void
|
||||
/// Unloads a model.
|
||||
public typealias Unload = @Sendable (String) async throws -> Void
|
||||
|
||||
private let manifest: ResolvedManifest
|
||||
private let configuration: EvaluationConfiguration
|
||||
private let environment: EvaluationEnvironment
|
||||
private let pipelineFactory: PipelineFactory
|
||||
private let warmUp: WarmUp
|
||||
private let unload: Unload
|
||||
|
||||
/// Creates a runner.
|
||||
public init(
|
||||
manifest: ResolvedManifest,
|
||||
configuration: EvaluationConfiguration,
|
||||
environment: EvaluationEnvironment,
|
||||
pipelineFactory: @escaping PipelineFactory,
|
||||
warmUp: @escaping WarmUp,
|
||||
unload: @escaping Unload
|
||||
) {
|
||||
self.manifest = manifest
|
||||
self.configuration = configuration
|
||||
self.environment = environment
|
||||
self.pipelineFactory = pipelineFactory
|
||||
self.warmUp = warmUp
|
||||
self.unload = unload
|
||||
}
|
||||
|
||||
/// Runs every configured model and writes raw outputs plus the report.
|
||||
public func run() async throws -> EvaluationReport {
|
||||
try FileManager.default.createDirectory(
|
||||
at: configuration.outputDirectory,
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
var modelResults: [ModelRunResult] = []
|
||||
for model in configuration.models {
|
||||
try await unload(model)
|
||||
try await warmUp(model)
|
||||
var results: [SegmentResult] = []
|
||||
let modelDirectory = configuration.outputDirectory.appendingPathComponent(slug(model))
|
||||
try FileManager.default.createDirectory(at: modelDirectory, withIntermediateDirectories: true)
|
||||
|
||||
for segment in manifest.segments {
|
||||
for run in 0 ..< configuration.runs {
|
||||
let result = await evaluate(segment: segment, run: run, model: model, directory: modelDirectory)
|
||||
results.append(result)
|
||||
}
|
||||
}
|
||||
modelResults.append(
|
||||
ModelRunResult(
|
||||
model: model,
|
||||
temperature: configuration.sampling.temperature,
|
||||
runs: configuration.runs,
|
||||
segments: results,
|
||||
categories: summarize(results)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
let report = EvaluationReport(
|
||||
environment: environment,
|
||||
generatedAt: Date(),
|
||||
models: modelResults
|
||||
)
|
||||
try EvaluationReportWriter.write(report, to: configuration.outputDirectory)
|
||||
return report
|
||||
}
|
||||
|
||||
private func evaluate(
|
||||
segment: ResolvedSegment,
|
||||
run: Int,
|
||||
model: String,
|
||||
directory: URL
|
||||
) async -> SegmentResult {
|
||||
do {
|
||||
let target = HyMT3Languages.resolve(segment.segment.targetLanguage)
|
||||
?? HyMT3Languages.english
|
||||
let pipeline = try pipelineFactory(model)
|
||||
let request = TranslationSessionRequest(
|
||||
captured: CapturedText(
|
||||
text: segment.sourceText,
|
||||
capturedAt: Date(),
|
||||
source: .menu
|
||||
),
|
||||
target: target,
|
||||
model: model,
|
||||
keepAlive: configuration.keepAlive,
|
||||
sampling: configuration.sampling
|
||||
)
|
||||
let result = try await pipeline.translate(request, onDelta: nil)
|
||||
let output = result.translation
|
||||
let failed = output.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
|| result.warnings.contains(where: \.blocksReplacement)
|
||||
let file = directory.appendingPathComponent("\(segment.segment.id)-run\(run).txt")
|
||||
try? Data(output.utf8).write(to: file, options: .atomic)
|
||||
return SegmentResult(
|
||||
id: segment.segment.id,
|
||||
category: segment.segment.category,
|
||||
run: run,
|
||||
chrF: EvaluationMetrics.chrF(reference: segment.referenceText, hypothesis: output),
|
||||
bleu: EvaluationMetrics.bleu(reference: segment.referenceText, hypothesis: output),
|
||||
tokenRetention: EvaluationMetrics.tokenRetention(
|
||||
source: segment.sourceText,
|
||||
translation: output
|
||||
),
|
||||
numericConsistency: EvaluationMetrics.numericConsistency(
|
||||
source: segment.sourceText,
|
||||
translation: output
|
||||
),
|
||||
failed: failed,
|
||||
warnings: result.warnings.map(\.code),
|
||||
firstTokenMs: result.timing.firstTokenMs,
|
||||
totalMs: result.timing.totalMs,
|
||||
outputCharacters: output.count
|
||||
)
|
||||
} catch let error as SprachmittlerError {
|
||||
return failure(segment: segment, run: run, code: error.diagnosticCode)
|
||||
} catch {
|
||||
return failure(segment: segment, run: run, code: "transport")
|
||||
}
|
||||
}
|
||||
|
||||
private func failure(segment: ResolvedSegment, run: Int, code: String) -> SegmentResult {
|
||||
SegmentResult(
|
||||
id: segment.segment.id,
|
||||
category: segment.segment.category,
|
||||
run: run,
|
||||
chrF: 0,
|
||||
bleu: 0,
|
||||
tokenRetention: 0,
|
||||
numericConsistency: 0,
|
||||
failed: true,
|
||||
warnings: [code],
|
||||
firstTokenMs: nil,
|
||||
totalMs: nil,
|
||||
outputCharacters: 0
|
||||
)
|
||||
}
|
||||
|
||||
private func summarize(_ results: [SegmentResult]) -> [CategorySummary] {
|
||||
EvaluationCategory.allCases.compactMap { category in
|
||||
let values = results.filter { $0.category == category }
|
||||
guard !values.isEmpty else { return nil }
|
||||
let first = values.compactMap(\.firstTokenMs)
|
||||
let totals = values.compactMap(\.totalMs)
|
||||
return CategorySummary(
|
||||
category: category,
|
||||
segments: values.count,
|
||||
failureRate: 100 * Double(values.filter(\.failed).count) / Double(values.count),
|
||||
chrF: mean(values.map(\.chrF)),
|
||||
bleu: mean(values.map(\.bleu)),
|
||||
tokenRetention: mean(values.map(\.tokenRetention)),
|
||||
numericConsistency: mean(values.map(\.numericConsistency)),
|
||||
firstTokenP50: percentile(first, 0.5),
|
||||
firstTokenP90: percentile(first, 0.9),
|
||||
totalP50: percentile(totals, 0.5),
|
||||
totalP90: percentile(totals, 0.9)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func mean(_ values: [Double]) -> Double {
|
||||
guard !values.isEmpty else { return 0 }
|
||||
return values.reduce(0, +) / Double(values.count)
|
||||
}
|
||||
|
||||
private func percentile(_ values: [Int], _ fraction: Double) -> Int? {
|
||||
guard !values.isEmpty else { return nil }
|
||||
let sorted = values.sorted()
|
||||
let index = min(sorted.count - 1, Int((Double(sorted.count - 1) * fraction).rounded()))
|
||||
return sorted[index]
|
||||
}
|
||||
|
||||
private func slug(_ model: String) -> String {
|
||||
model.replacingOccurrences(of: "/", with: "_")
|
||||
.replacingOccurrences(of: ":", with: "_")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import SprachmittlerText
|
||||
|
||||
struct DetectCommand: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "detect",
|
||||
abstract: "Detect the source language of text (advisory)."
|
||||
)
|
||||
|
||||
@Option(name: .long, help: "Text to inspect.")
|
||||
var text: String?
|
||||
|
||||
@Option(name: .long, help: "UTF-8 file to inspect.")
|
||||
var file: String?
|
||||
|
||||
@Flag(name: .long, help: "Emit JSON.")
|
||||
var json = false
|
||||
|
||||
func validate() throws {
|
||||
if (text == nil) == (file == nil) {
|
||||
throw ValidationError("Use exactly one of --text or --file.")
|
||||
}
|
||||
}
|
||||
|
||||
func run() throws {
|
||||
let source: String
|
||||
if let text {
|
||||
source = text
|
||||
} else if let file {
|
||||
source = try String(contentsOfFile: file, encoding: .utf8)
|
||||
} else {
|
||||
return
|
||||
}
|
||||
let detection = NaturalLanguageDetector().detect(source)
|
||||
guard let detection else {
|
||||
if json {
|
||||
print(#"{"language":null,"confidence":0,"alternatives":[]}"#)
|
||||
} else {
|
||||
print("unknown")
|
||||
}
|
||||
return
|
||||
}
|
||||
if json {
|
||||
let object: [String: Any] = [
|
||||
"language": detection.code,
|
||||
"confidence": detection.confidence,
|
||||
"alternatives": detection.alternatives,
|
||||
]
|
||||
let data = try JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys])
|
||||
print(String(data: data, encoding: .utf8) ?? "{}")
|
||||
} else {
|
||||
print("\(detection.code)\t\(String(format: "%.2f", detection.confidence))")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerEval
|
||||
import SprachmittlerOllama
|
||||
|
||||
struct EvalCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "eval",
|
||||
abstract: "Run the private-corpus evaluation and write report.md/report.json."
|
||||
)
|
||||
|
||||
@Option(name: .long, help: "Corpus manifest JSON.")
|
||||
var manifest: String
|
||||
|
||||
@Option(name: .long, help: "Comma-separated model tags.")
|
||||
var models = HyMT3ModelPreset.defaultModel
|
||||
|
||||
@Option(name: .long, help: "Target BCP-47 code.")
|
||||
var target = "de"
|
||||
|
||||
@Option(name: .long, help: "Runs per segment (default 3).")
|
||||
var runs = 3
|
||||
|
||||
@Option(name: .long, help: "Sampling temperature override.")
|
||||
var temperature: Double?
|
||||
|
||||
@Option(name: .long, help: "Ollama keep-alive during the run.")
|
||||
var keepAlive = HyMT3ModelPreset.defaultKeepAlive
|
||||
|
||||
@Option(name: .long, help: "Output directory for raw outputs and reports.")
|
||||
var out: String?
|
||||
|
||||
@OptionGroup var endpoint: EndpointOptions
|
||||
|
||||
func validate() throws {
|
||||
guard (1 ... 5).contains(runs) else {
|
||||
throw ValidationError("--runs must be between 1 and 5.")
|
||||
}
|
||||
if let temperature, !(0 ... 2).contains(temperature) {
|
||||
throw ValidationError("--temperature must be between 0 and 2.")
|
||||
}
|
||||
guard HyMT3Languages.resolve(target) != nil else {
|
||||
throw ValidationError("Unknown target language '\(target)'.")
|
||||
}
|
||||
guard !modelTags().isEmpty else {
|
||||
throw ValidationError("Pass at least one model tag.")
|
||||
}
|
||||
}
|
||||
|
||||
func run() async throws {
|
||||
try await CLIError.perform {
|
||||
try await execute()
|
||||
}
|
||||
}
|
||||
|
||||
private func execute() async throws {
|
||||
let manifestURL = URL(fileURLWithPath: manifest)
|
||||
guard let language = HyMT3Languages.resolve(target) else {
|
||||
throw ValidationError("Unknown target language '\(target)'.")
|
||||
}
|
||||
let resolved = try EvaluationManifestLoader.load(manifestURL: manifestURL, target: language.code)
|
||||
let environment = try endpoint.makeEnvironment()
|
||||
let settings = makeSettings(environment: environment, target: language)
|
||||
let configuration = EvaluationConfiguration(
|
||||
models: modelTags(),
|
||||
runs: runs,
|
||||
keepAlive: keepAlive,
|
||||
sampling: settings.samplingOptions,
|
||||
outputDirectory: outputDirectory()
|
||||
)
|
||||
let evaluationEnvironment = try await makeEnvironmentBlock(environment, settings: settings)
|
||||
let evaluation = makeRunner(
|
||||
resolved: resolved,
|
||||
configuration: configuration,
|
||||
environment: evaluationEnvironment,
|
||||
settings: settings,
|
||||
endpointEnvironment: environment
|
||||
)
|
||||
let report = try await evaluation.run()
|
||||
printSummary(report, directory: configuration.outputDirectory)
|
||||
}
|
||||
|
||||
private func makeSettings(environment: CLIEnvironment, target: ModelLanguage) -> AppSettings {
|
||||
var draft = AppSettings()
|
||||
draft.endpoint = environment.baseURL
|
||||
draft.allowRemoteEndpoint = environment.allowRemote
|
||||
draft.targetLanguage = target.code
|
||||
draft.model = modelTags().first ?? HyMT3ModelPreset.defaultModel
|
||||
draft.warmUpOnLaunch = false
|
||||
draft.keepModelLoaded = keepAlive
|
||||
if let temperature {
|
||||
draft.temperature = temperature
|
||||
}
|
||||
return draft
|
||||
}
|
||||
|
||||
private func makeEnvironmentBlock(
|
||||
_ environment: CLIEnvironment,
|
||||
settings: AppSettings
|
||||
) async throws -> EvaluationEnvironment {
|
||||
let catalog = try environment.makeCatalog()
|
||||
let version = try await catalog.serverVersion()
|
||||
let installed = try? await catalog.installedModels()
|
||||
var digests: [String: String] = [:]
|
||||
for model in installed ?? [] {
|
||||
digests[model.name] = String(model.digest.prefix(12))
|
||||
}
|
||||
return EvaluationEnvironment(
|
||||
serverVersion: version,
|
||||
ollamaVersion: version,
|
||||
hardware: hardware(),
|
||||
macOS: ProcessInfo.processInfo.operatingSystemVersionString,
|
||||
models: digests
|
||||
)
|
||||
}
|
||||
|
||||
private func makeRunner(
|
||||
resolved: ResolvedManifest,
|
||||
configuration: EvaluationConfiguration,
|
||||
environment: EvaluationEnvironment,
|
||||
settings: AppSettings,
|
||||
endpointEnvironment: CLIEnvironment
|
||||
) -> EvaluationRunner {
|
||||
let registry = AdapterRegistry(adapters: [HyMT3Adapter()])
|
||||
return EvaluationRunner(
|
||||
manifest: resolved,
|
||||
configuration: configuration,
|
||||
environment: environment,
|
||||
pipelineFactory: { model in
|
||||
var snapshot = settings
|
||||
snapshot.model = model
|
||||
return try TranslationPipeline(
|
||||
chat: endpointEnvironment.makeChatClient(),
|
||||
registry: registry,
|
||||
chunker: snapshot.chunker
|
||||
)
|
||||
},
|
||||
warmUp: { model in
|
||||
let chat = try endpointEnvironment.makeChatClient()
|
||||
try await OllamaWarmUpRunner(chat: chat).run(
|
||||
HyMT3Adapter().warmUpRequest(model: model, keepAlive: keepAlive)
|
||||
)
|
||||
},
|
||||
unload: { model in
|
||||
let chat = try endpointEnvironment.makeChatClient()
|
||||
try await OllamaWarmUpRunner(chat: chat).run(
|
||||
HyMT3Adapter().unloadRequest(model: model)
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private func printSummary(_ report: EvaluationReport, directory: URL) {
|
||||
print("Report: \(directory.path)")
|
||||
for model in report.models {
|
||||
for category in model.categories {
|
||||
print(
|
||||
"\(model.model)\t\(category.category.rawValue)\t"
|
||||
+ String(
|
||||
format: "fail %.1f%%\tchrF %.2f\tBLEU %.2f",
|
||||
category.failureRate,
|
||||
category.chrF,
|
||||
category.bleu
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func modelTags() -> [String] {
|
||||
models.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
|
||||
}
|
||||
|
||||
private func outputDirectory() -> URL {
|
||||
if let out {
|
||||
return URL(fileURLWithPath: out)
|
||||
}
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy-MM-dd"
|
||||
return URL(fileURLWithPath: "evaluation/results/\(formatter.string(from: Date()))")
|
||||
}
|
||||
|
||||
private func hardware() -> String {
|
||||
let memory = ProcessInfo.processInfo.physicalMemory / 1_073_741_824
|
||||
return "Apple Silicon \(memory) GB, \(ProcessInfo.processInfo.processorCount) cores"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
|
||||
struct LanguagesCommand: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "languages",
|
||||
abstract: "List the 102 supported target languages."
|
||||
)
|
||||
|
||||
@Flag(name: .long, help: "Emit JSON.")
|
||||
var json = false
|
||||
|
||||
func run() throws {
|
||||
if json {
|
||||
let data = try JSONEncoder().encode(HyMT3Languages.all)
|
||||
print(String(data: data, encoding: .utf8) ?? "[]")
|
||||
return
|
||||
}
|
||||
for language in HyMT3Languages.all {
|
||||
print("\(language.code)\t\(language.modelName)\t\(language.localizedDisplayName)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,12 @@ struct SprachmittlerCLI: AsyncParsableCommand {
|
||||
commandName: "sprachmittler-cli",
|
||||
abstract: "Headless translator and test harness for Sprachmittler.",
|
||||
subcommands: [
|
||||
LanguagesCommand.self,
|
||||
DetectCommand.self,
|
||||
ModelsCommand.self,
|
||||
ShowCommand.self,
|
||||
TranslateCommand.self,
|
||||
EvalCommand.self,
|
||||
]
|
||||
)
|
||||
}
|
||||
@@ -17,6 +17,7 @@ struct AppSettingsTests {
|
||||
#expect(settings.maxCharactersLatin == 4000)
|
||||
#expect(settings.maxCharactersCJK == 2000)
|
||||
#expect(settings.numCtx == 8192)
|
||||
#expect(settings.translationFontSize == 17)
|
||||
#expect(!settings.autoCopy)
|
||||
#expect(!settings.hasCompletedOnboarding)
|
||||
}
|
||||
@@ -28,6 +29,7 @@ struct AppSettingsTests {
|
||||
settings.targetLanguage = "de"
|
||||
settings.noteTarget(HyMT3Languages.german)
|
||||
settings.temperature = 0.2
|
||||
settings.translationFontSize = 22
|
||||
settings.launchAtLogin = true
|
||||
settings.hasCompletedOnboarding = true
|
||||
|
||||
@@ -82,6 +84,7 @@ struct AppSettingsTests {
|
||||
"topK": 0,
|
||||
"repeatPenalty": 9,
|
||||
"keepModelLoaded": "forever",
|
||||
"translationFontSize": 99,
|
||||
"targetLanguage": "xx"
|
||||
}
|
||||
"""
|
||||
@@ -96,6 +99,7 @@ struct AppSettingsTests {
|
||||
#expect(decoded.topK == 1)
|
||||
#expect(decoded.repeatPenalty == 2)
|
||||
#expect(decoded.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
|
||||
#expect(decoded.translationFontSize == 28)
|
||||
#expect(HyMT3Languages.resolve(decoded.targetLanguage) != nil)
|
||||
}
|
||||
|
||||
@@ -106,6 +110,7 @@ struct AppSettingsTests {
|
||||
settings.topP = -1
|
||||
settings.topK = 0
|
||||
settings.keepModelLoaded = "forever"
|
||||
settings.translationFontSize = 99
|
||||
settings.autoCopy = true
|
||||
settings.targetLanguage = "xx"
|
||||
settings.sanitize()
|
||||
@@ -115,6 +120,7 @@ struct AppSettingsTests {
|
||||
#expect(settings.topP == 0)
|
||||
#expect(settings.topK == 1)
|
||||
#expect(settings.keepModelLoaded == HyMT3ModelPreset.defaultKeepAlive)
|
||||
#expect(settings.translationFontSize == 28)
|
||||
#expect(!settings.autoCopy)
|
||||
#expect(HyMT3Languages.resolve(settings.targetLanguage) != nil)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
import Foundation
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
import Testing
|
||||
@testable import SprachmittlerEval
|
||||
|
||||
@Suite("Evaluation metrics")
|
||||
struct EvaluationMetricsTests {
|
||||
@Test func identicalTextScoresFullMarks() {
|
||||
#expect(EvaluationMetrics.chrF(reference: "Hello world", hypothesis: "Hello world") == 100)
|
||||
#expect(EvaluationMetrics.bleu(reference: "a b c d", hypothesis: "a b c d") == 100)
|
||||
#expect(EvaluationMetrics.tokenRetention(source: "Hello", translation: "Hello") == 1)
|
||||
#expect(EvaluationMetrics.numericConsistency(source: "1.5", translation: "1,5") == 1)
|
||||
}
|
||||
|
||||
@Test func disjointTextScoresZero() {
|
||||
#expect(EvaluationMetrics.chrF(reference: "abc", hypothesis: "xyz") == 0)
|
||||
#expect(EvaluationMetrics.bleu(reference: "a b c d", hypothesis: "w x y z") == 0)
|
||||
}
|
||||
|
||||
@Test func lostProtectedTokenIsCounted() {
|
||||
let source = "Open https://example.com and use {{name}}."
|
||||
#expect(
|
||||
EvaluationMetrics.tokenRetention(
|
||||
source: source,
|
||||
translation: "Öffne https://example.com und nutze {{name}}."
|
||||
) == 1
|
||||
)
|
||||
#expect(
|
||||
EvaluationMetrics.tokenRetention(
|
||||
source: source,
|
||||
translation: "Öffne example.com und nutze name."
|
||||
) == 0
|
||||
)
|
||||
}
|
||||
|
||||
@Test func localeNumbersAreNormalised() {
|
||||
#expect(EvaluationMetrics.numericConsistency(source: "1.5 and 1 000", translation: "1,5 und 1000") == 1)
|
||||
#expect(EvaluationMetrics.numericConsistency(source: "1.5", translation: "2.5") == 0)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("Manifest loading")
|
||||
struct EvaluationManifestTests {
|
||||
@Test func loadsRelativePathsAndFiltersTheTarget() throws {
|
||||
let directory = try makeTemporaryDirectory()
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
try writeText("Hello.", to: directory.appendingPathComponent("source.txt"))
|
||||
try writeText("Hallo.", to: directory.appendingPathComponent("reference.txt"))
|
||||
let manifest = directory.appendingPathComponent("corpus.json")
|
||||
try writeText(
|
||||
#"""
|
||||
{
|
||||
"version": 1,
|
||||
"segments": [
|
||||
{
|
||||
"id": "seg-1",
|
||||
"source": "source.txt",
|
||||
"sourceLanguage": "en",
|
||||
"targetLanguage": "de",
|
||||
"category": "en-de-prose",
|
||||
"reference": "reference.txt",
|
||||
"referenceKind": "human"
|
||||
}
|
||||
]
|
||||
}
|
||||
"""#,
|
||||
to: manifest
|
||||
)
|
||||
|
||||
let resolved = try EvaluationManifestLoader.load(manifestURL: manifest, target: "de")
|
||||
#expect(resolved.segments.count == 1)
|
||||
#expect(resolved.segments[0].sourceText == "Hello.")
|
||||
#expect(resolved.segments[0].referenceText == "Hallo.")
|
||||
#expect(throws: ManifestError.noMatchingTarget("fr")) {
|
||||
try EvaluationManifestLoader.load(manifestURL: manifest, target: "fr")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func rejectsDuplicateIDsAndMissingFiles() throws {
|
||||
let directory = try makeTemporaryDirectory()
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
try writeText("x", to: directory.appendingPathComponent("source.txt"))
|
||||
try writeText("y", to: directory.appendingPathComponent("reference.txt"))
|
||||
let manifest = directory.appendingPathComponent("corpus.json")
|
||||
|
||||
let duplicate = manifestJSON([
|
||||
segmentJSON(id: "seg-1"),
|
||||
segmentJSON(id: "seg-1"),
|
||||
])
|
||||
try writeText(duplicate, to: manifest)
|
||||
#expect(throws: ManifestError.duplicateID("seg-1")) {
|
||||
try EvaluationManifestLoader.load(manifestURL: manifest)
|
||||
}
|
||||
|
||||
let missing = manifestJSON([
|
||||
segmentJSON(id: "seg-1", source: "missing.txt"),
|
||||
])
|
||||
try writeText(missing, to: manifest)
|
||||
#expect(throws: ManifestError.missingFile(directory.appendingPathComponent("missing.txt").path)) {
|
||||
try EvaluationManifestLoader.load(manifestURL: manifest)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func rejectsBadIDsAndReferenceKinds() throws {
|
||||
let directory = try makeTemporaryDirectory()
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
try writeText("x", to: directory.appendingPathComponent("source.txt"))
|
||||
try writeText("y", to: directory.appendingPathComponent("reference.txt"))
|
||||
let manifest = directory.appendingPathComponent("corpus.json")
|
||||
let badID = manifestJSON([
|
||||
segmentJSON(id: "Bad ID"),
|
||||
])
|
||||
try writeText(badID, to: manifest)
|
||||
#expect(throws: ManifestError.invalidID("Bad ID")) {
|
||||
try EvaluationManifestLoader.load(manifestURL: manifest)
|
||||
}
|
||||
|
||||
let badKind = manifestJSON([
|
||||
segmentJSON(id: "seg-1", referenceKind: "machine"),
|
||||
])
|
||||
try writeText(badKind, to: manifest)
|
||||
#expect(throws: ManifestError.invalidReferenceKind("machine")) {
|
||||
try EvaluationManifestLoader.load(manifestURL: manifest)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("Evaluation runner and report")
|
||||
struct EvaluationRunnerTests {
|
||||
@Test func runsSegmentsWritesRawOutputsAndReports() async throws {
|
||||
let directory = try makeTemporaryDirectory()
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
try writeText("Hello.", to: directory.appendingPathComponent("source.txt"))
|
||||
try writeText("Hallo.", to: directory.appendingPathComponent("reference.txt"))
|
||||
let manifestURL = directory.appendingPathComponent("corpus.json")
|
||||
try writeText(manifestJSON([segmentJSON(id: "seg-1")]), to: manifestURL)
|
||||
let manifest = try EvaluationManifestLoader.load(manifestURL: manifestURL)
|
||||
let output = directory.appendingPathComponent("results")
|
||||
let configuration = EvaluationConfiguration(
|
||||
models: ["test-model"],
|
||||
runs: 1,
|
||||
outputDirectory: output
|
||||
)
|
||||
let runner = EvaluationRunner(
|
||||
manifest: manifest,
|
||||
configuration: configuration,
|
||||
environment: EvaluationEnvironment(
|
||||
serverVersion: "0.40.18",
|
||||
ollamaVersion: "0.40.18",
|
||||
hardware: "Test",
|
||||
macOS: "Test",
|
||||
models: ["test-model": "abcdef"]
|
||||
),
|
||||
pipelineFactory: { _ in ImmediateStreaming(translation: "Hallo.") },
|
||||
warmUp: { _ in },
|
||||
unload: { _ in }
|
||||
)
|
||||
|
||||
let report = try await runner.run()
|
||||
#expect(report.models.count == 1)
|
||||
#expect(report.models[0].categories.count == 1)
|
||||
#expect(report.models[0].categories[0].failureRate == 0)
|
||||
#expect(report.models[0].categories[0].chrF == 100)
|
||||
#expect(FileManager.default.fileExists(atPath: output.appendingPathComponent("report.md").path))
|
||||
#expect(FileManager.default.fileExists(atPath: output.appendingPathComponent("report.json").path))
|
||||
#expect(FileManager.default.fileExists(
|
||||
atPath: output.appendingPathComponent("test-model/seg-1-run0.txt").path
|
||||
))
|
||||
|
||||
let markdown = try String(
|
||||
contentsOf: output.appendingPathComponent("report.md"),
|
||||
encoding: .utf8
|
||||
)
|
||||
#expect(markdown.contains("## Environment"))
|
||||
#expect(markdown.contains("| test-model |"))
|
||||
}
|
||||
|
||||
@Test func failureIsReportedAsAFailure() async throws {
|
||||
let directory = try makeTemporaryDirectory()
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
try writeText("Hello.", to: directory.appendingPathComponent("source.txt"))
|
||||
try writeText("Hallo.", to: directory.appendingPathComponent("reference.txt"))
|
||||
let manifestURL = directory.appendingPathComponent("corpus.json")
|
||||
try writeText(manifestJSON([segmentJSON(id: "seg-1")]), to: manifestURL)
|
||||
let manifest = try EvaluationManifestLoader.load(manifestURL: manifestURL)
|
||||
let runner = EvaluationRunner(
|
||||
manifest: manifest,
|
||||
configuration: EvaluationConfiguration(
|
||||
models: ["test-model"],
|
||||
runs: 1,
|
||||
outputDirectory: directory.appendingPathComponent("results")
|
||||
),
|
||||
environment: EvaluationEnvironment(
|
||||
serverVersion: "v",
|
||||
ollamaVersion: "v",
|
||||
hardware: "h",
|
||||
macOS: "m",
|
||||
models: [:]
|
||||
),
|
||||
pipelineFactory: { _ in FailingStreaming() },
|
||||
warmUp: { _ in },
|
||||
unload: { _ in }
|
||||
)
|
||||
|
||||
let report = try await runner.run()
|
||||
#expect(report.models[0].categories[0].failureRate == 100)
|
||||
#expect(report.models[0].segments[0].failed)
|
||||
}
|
||||
}
|
||||
|
||||
private func manifestJSON(_ segments: [[String: String]]) -> String {
|
||||
let object: [String: Any] = ["version": 1, "segments": segments]
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
|
||||
let text = String(data: data, encoding: .utf8)
|
||||
else {
|
||||
return "{}"
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
private func segmentJSON(
|
||||
id: String,
|
||||
source: String = "source.txt",
|
||||
reference: String = "reference.txt",
|
||||
referenceKind: String = "human"
|
||||
) -> [String: String] {
|
||||
[
|
||||
"id": id,
|
||||
"source": source,
|
||||
"sourceLanguage": "en",
|
||||
"targetLanguage": "de",
|
||||
"category": "en-de-prose",
|
||||
"reference": reference,
|
||||
"referenceKind": referenceKind,
|
||||
]
|
||||
}
|
||||
|
||||
private func makeTemporaryDirectory() throws -> URL {
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("sprachmittler-eval-\(UUID().uuidString)")
|
||||
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
|
||||
return url
|
||||
}
|
||||
|
||||
private func writeText(_ text: String, to url: URL) throws {
|
||||
try text.write(to: url, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
private struct ImmediateStreaming: TranslationStreaming {
|
||||
let translation: String
|
||||
|
||||
func translate(
|
||||
_ request: TranslationSessionRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?
|
||||
) async throws -> PipelineResult {
|
||||
PipelineResult(
|
||||
translation: translation,
|
||||
warnings: [],
|
||||
sourceLanguage: request.captured.source.rawValue,
|
||||
timing: TranslationTiming(firstTokenMs: 10, totalMs: 20, promptTokens: 3, outputTokens: 4),
|
||||
chunkCount: 1
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private struct FailingStreaming: TranslationStreaming {
|
||||
func translate(
|
||||
_ request: TranslationSessionRequest,
|
||||
onDelta: (@Sendable (String) async -> Void)?
|
||||
) async throws -> PipelineResult {
|
||||
throw SprachmittlerError.modelNotInstalled(model: request.model)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ This repository is the development kit for building the app with **OpenCode 2.x*
|
||||
|
||||
Sprachmittler is the companion to Schriftleser and Vorleser: Vorleser reads text aloud, Schriftleser reads documents into text, Sprachmittler translates the text you select.
|
||||
|
||||
A user-facing installation, permission and troubleshooting guide is in [docs/USER_GUIDE.md](docs/USER_GUIDE.md).
|
||||
|
||||
## How it works
|
||||
|
||||
1. Select text in Safari, Mail, Word, Notes, an editor or any other app.
|
||||
@@ -36,8 +38,11 @@ make bootstrap # installs xcodegen, swif
|
||||
ollama pull hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M # about 5.15 GB
|
||||
make smoke # translates one fixed synthetic sentence
|
||||
make doctor # checks OpenCode 2.x and the resolved V2 config
|
||||
make verify # the scaffold should already build and test
|
||||
make app # builds and launches Sprachmittler.app
|
||||
make verify # format, lint, privacy, tests, Debug + Release builds
|
||||
make app # builds and launches the Debug app
|
||||
make install # builds Release, installs in /Applications and launches
|
||||
make dmg # local unnotarised DMG from the Release build
|
||||
make icon # regenerate the app icon assets
|
||||
opencode # start OpenCode in the repo root
|
||||
```
|
||||
|
||||
|
||||
@@ -143,7 +143,7 @@ flowchart TD
|
||||
- `SprachmittlerEngines` is the only module that knows model names, tags, prompts, language names and output dialects. It depends on `SprachmittlerOllama` (request types) and `SprachmittlerText` (chunk and token types).
|
||||
- `SprachmittlerCore` composes everything through **protocols** so each part can be faked in tests. It contains no model-specific branches and no AppKit.
|
||||
- `SprachmittlerCapture` is the only module that imports `ApplicationServices`/`Accessibility` and touches `NSPasteboard`. It depends on `SprachmittlerCore` for domain types and protocols.
|
||||
- `SprachmittlerEval` is linked into the CLI only, never into the app.
|
||||
- `SprachmittlerEval` is linked into the CLI only, never into the app. It may use the leaf `SprachmittlerText`, `SprachmittlerEngines` and `SprachmittlerOllama` types for metrics and pipeline construction; it does not add an app dependency.
|
||||
- `sprachmittler-cli` links `SprachmittlerOllama` and `SprachmittlerEngines` directly for the M1 commands; it is never linked into the app.
|
||||
- `SprachmittlerTestSupport` is test-only and depends on `SprachmittlerCore`, `SprachmittlerCapture` and `SprachmittlerOllama`; it is never linked into the app.
|
||||
- The `App` target holds no business logic. Anything with a branch worth testing belongs in a package module.
|
||||
@@ -554,7 +554,7 @@ stateDiagram-v2
|
||||
| Onboarding | `NSWindow` (not a SwiftUI `Window` scene) | Ollama reachable + version, Hy-MT3 installed, target language, optional Accessibility for Replace; each with a fix button |
|
||||
| Diagnostics | Window from the menu | Server version, model digests, last 50 timings and error kinds; copy as text; no text or translations |
|
||||
|
||||
Panel keyboard: **Esc** close, **⌘C** copy translation, **⌘↩** Replace, **⌘R** retry, **⌘,** Settings. The panel becomes key only when clicked; the source app keeps focus until then.
|
||||
Panel keyboard: **Esc** close, **⌘C** copy translation, **⌘↩** Replace, **⌘R** retry, **⌘,** Settings. The panel becomes key only when clicked; the source app keeps focus until then. The left header block and its drag grip move the panel; moving it keeps its position while it stays open, and a newly shown panel is placed near the cursor (DeepL-like transient position). The translation text size is a Settings value.
|
||||
|
||||
Accessibility: every control has an `accessibilityLabel`; the panel exposes source and translation as read-only text elements; full keyboard navigation; respects Reduce Motion and Increase Contrast.
|
||||
|
||||
@@ -586,6 +586,7 @@ Accessibility: every control has an `accessibilityLabel`; the panel exposes sour
|
||||
| `promptVariantPolicy` | `.defaultOnly` / `.contentAware` | `.defaultOnly` until M7 |
|
||||
| `autoCopy` | Bool | **false** (never copy automatically) |
|
||||
| `showSourcePreview` | Bool | true |
|
||||
| `translationFontSize` | Int | 17 pt (12–28) |
|
||||
| `launchAtLogin` | Bool | false |
|
||||
| `keepRecentTranslationInMemory` | Bool | true (cleared on quit; no disk) |
|
||||
| `hasCompletedOnboarding` | Bool | false |
|
||||
@@ -607,7 +608,7 @@ Never store source text, translations, pasteboard contents or app names in setti
|
||||
| Sandbox | **Off** (ADR-003): Accessibility replacement. Hardened Runtime **on**, no exceptions |
|
||||
| Signing | Development: "Sign to Run Locally". Release: Developer ID + notarisation |
|
||||
| ATS | `NSAllowsLocalNetworking = YES`; remote endpoints must be HTTPS |
|
||||
| Distribution | Signed, notarised DMG; Mac App Store not in v1 |
|
||||
| Distribution | Signed, notarised DMG; local `make dmg` for testing; Mac App Store not in v1 |
|
||||
|
||||
`make install` copies the app to `/Applications` and ad-hoc signs it. macOS ties Accessibility permission to the app's signature and location; after a reinstall the user may have to remove and re-add the app in System Settings.
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ Decision: Source text, translations, pasteboard snapshots and app names are neve
|
||||
Consequences: The user cannot look up an old translation after closing the panel; that is the intended trade-off. A future opt-in history needs an ADR, explicit consent and encrypted storage.
|
||||
|
||||
## ADR-008 — Default model chosen by evaluation
|
||||
Status: Proposed (decided in T7.5)
|
||||
Status: Proposed (T7.5 blocked on the private corpus and the 1.8B comparison)
|
||||
|
||||
Context: Publisher benchmarks do not cover the user's texts, and 7B vs 1.8B is a quality/latency trade-off. The 7B is the owner's requested default, but the 1.8B may be better on smaller Macs.
|
||||
Decision: Ship with `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` as the provisional default and the 1.8B Q4_K_M as the Fast preset. Decide the default, the sampling temperature and the prompt policy with `sprachmittler-cli eval` on the user's corpus using the rule in `docs/MODEL_EVALUATION.md` §5. Record the outcome as a new ADR.
|
||||
|
||||
@@ -80,8 +80,11 @@ Write ADR "Default model and sampling" with:
|
||||
|
||||
Until the ADR is accepted, the 7B remains labelled provisional and the app may ask the user to pick a model on first run if both are installed.
|
||||
|
||||
Status 2026-11-26: the manifest, metrics and report harness are complete and validated on a synthetic manifest. T7.4 and T7.5 remain open because the private corpus is not present in this checkout and the 1.8B model is not installed. Do not select a default from the synthetic run.
|
||||
|
||||
## 6. Results log
|
||||
|
||||
| Date | Report | Models | Decision |
|
||||
|---|---|---|---|
|
||||
| 2026-11-26 | kit reference only | 7B Q4_K_M | 246 output tokens, 6.52 s, 44.6 tok/s; no corpus evaluation yet |
|
||||
| 2026-11-26 | synthetic harness validation | 7B Q4_K_M | Harness only (4 synthetic segments, 1 run): fail 0%, chrF 96.34/61.27/94.81/80.84, token retention 1.0, first token 57–102 ms, 0.45–0.91 s/segment. This is not a default-model decision. |
|
||||
@@ -56,3 +56,17 @@ footprint -p $(pgrep -x Sprachmittler) # app memory, excluding Ollama
|
||||
- Do not add a system message, a timestamp or dynamic context to the default prompt.
|
||||
- Changing the target language changes the prefix and the cache; that is expected.
|
||||
- `keep_alive: "30m"` keeps the model loaded between translations. A cold load can add seconds; measure it on the target Mac and record it here.
|
||||
|
||||
## 6. App shell measurements (2026-11-26)
|
||||
|
||||
| Metric | Measurement | Budget | Status |
|
||||
|---|---|---|---|
|
||||
| Idle CPU, app only, panel closed | 0.1% after 6 s | < 0.5% | ✅ |
|
||||
| Idle RSS, app only | 86,960 KB ≈ 84.9 MB | ≤ 90 MB | ✅ |
|
||||
| First translation token, warm 7B (synthetic eval) | 57–102 ms | ≤ 1.5 s | ✅ |
|
||||
| Warm segment, 7B (synthetic eval) | 0.45–0.91 s | 250 tokens ≤ 8 s | ✅ |
|
||||
| Panel visible after a two-copy smoke | panel appeared; latency not instrumented | ≤ 250 ms | not measured |
|
||||
| Copy / Replace / idle hangs | not instrumented | budgets in §2 | not measured |
|
||||
| 1.8B latency and memory | model not installed | budgets in §2 | not measured |
|
||||
|
||||
The synthetic eval used four short segments, one run, 7B Q4_K_M, temperature 0.7, `num_ctx` 8192. It validates the harness and warm 7B behavior, not the private corpus. Measure panel signposts, Copy, Replace, cold load and the 1.8B model on the target Mac before release.
|
||||
@@ -59,19 +59,19 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
|
||||
- [~] T6.5 End-to-end integration checkpoint (gate) — 2026-11-26 · needs the user's manual 10-app pass
|
||||
|
||||
## M7 — Evaluation and the default-model gate
|
||||
- [ ] T7.1 Corpus manifest and eval CLI
|
||||
- [ ] T7.2 Metrics
|
||||
- [ ] T7.3 Reports
|
||||
- [ ] T7.4 Evaluation run
|
||||
- [ ] T7.5 Default-model ADR (gate)
|
||||
- [x] T7.1 Corpus manifest and eval CLI — 2026-11-26
|
||||
- [x] T7.2 Metrics — 2026-11-26
|
||||
- [x] T7.3 Reports — 2026-11-26
|
||||
- [~] T7.4 Evaluation run — 2026-11-26 · synthetic harness validated; private corpus and 1.8B still needed
|
||||
- [~] T7.5 Default-model ADR (gate) — 2026-11-26 · blocked on T7.4 and user decision
|
||||
|
||||
## M8 — Hardening and release
|
||||
- [ ] T8.1 Privacy audit and self-test
|
||||
- [ ] T8.2 Accessibility pass
|
||||
- [ ] T8.3 Performance pass
|
||||
- [ ] T8.4 German localisation and end-user README
|
||||
- [ ] T8.5 Release script
|
||||
- [ ] T8.6 Compatibility matrix completion
|
||||
- [x] T8.1 Privacy audit and self-test — 2026-11-26
|
||||
- [~] T8.2 Accessibility pass — 2026-11-26 · labels/keyboard in code; VoiceOver manual
|
||||
- [~] T8.3 Performance pass — 2026-11-26 · app/7B measured; panel/Copy/Replace/1.8B unmeasured
|
||||
- [x] T8.4 German localisation and end-user README — 2026-11-26 · user review pending
|
||||
- [x] T8.5 Release script — 2026-11-26 · dry-run; credentials/notarisation manual
|
||||
- [~] T8.6 Compatibility matrix completion — 2026-11-26 · 10-app matrix needs a person
|
||||
|
||||
## Environment record
|
||||
|
||||
@@ -138,3 +138,17 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
|
||||
2026-11-26 · T6.5 · The end-to-end gate is ready to run but not marked complete: it needs the user's manual double-copy → panel → Copy/Replace pass.
|
||||
2026-11-26 · M4/M5/M6 smoke · Launched the Debug app and sent two identical clipboard copies; the non-activating panel appeared on screen without a crash. Full focus, Copy/Replace, VoiceOver, onboarding and 10-app matrices remain manual.
|
||||
2026-11-26 · M4/M5/M6 review · Cleared the previous translation when a new capture arrives (menu Replace cannot pair old text with a new selection); restored the clipboard on cancelled/failed paste; reset the panel before showing a new capture; mapped blocked Replace to the real warning; mapped endpoint/transport errors in onboarding and settings; surfaced launch-item errors; moved Fast-model detection to Engines; suppressed retry deltas and streamed chunk separators; made settings updates atomic and fastModel nullable; fixed refresh endpoint validation; localized warning strings; used the captured selection for an early safety check; the event observer now sees only current-epoch events and only a validated `.ready` result can become the status-menu last translation; insertion-target enrichment is generation-guarded. `make verify` green.
|
||||
2026-11-26 · T7.1 · Added `sprachmittler-cli languages`, `detect` and `eval`; manifest decoding/validation, relative path loading, target filtering and precise errors.
|
||||
2026-11-26 · T7.2 · Added chrF, BLEU, protected-token retention, numeric consistency and latency percentiles with hand-computed tests.
|
||||
2026-11-26 · T7.3 · Added `report.md`/`report.json` with environment, per-category tables, observations and limitations; raw outputs stay under the ignored results path.
|
||||
2026-11-26 · T7.4 · Ran the eval harness on a synthetic 4-segment manifest with the 7B: 0% failures, token retention 1.0, chrF 61–96, first token 57–102 ms. The private corpus and 1.8B comparison remain pending; this is not a default decision.
|
||||
2026-11-26 · T7.5 · ADR-008 remains Proposed. The gate needs the private corpus report, 1.8B numbers and the user's decision; docs still label the 7B provisional.
|
||||
2026-11-26 · T8.1 · Extended `privacy-check.sh` for the evaluation harness and added `privacy-self-test.sh`, which seeds and detects every major SP rule; wired into `make verify`.
|
||||
2026-11-26 · T8.2 · Added accessibility labels to panel/settings/onboarding controls and keyboard paths; VoiceOver, Reduce Motion and Increase Contrast remain manual.
|
||||
2026-11-26 · T8.3 · Measured idle CPU 0.1%, app RSS ≈84.9 MB, 7B first token 57–102 ms and 0.45–0.91 s warm on the synthetic eval. Panel/Copy/Replace signposts and 1.8B remain unmeasured.
|
||||
2026-11-26 · T8.4 · Added English/German `Localizable.strings` for the app shell and `docs/USER_GUIDE.md` (install, permissions, privacy, troubleshooting).
|
||||
2026-11-26 · T8.5 · Added `scripts/release.sh` (archive unsigned, Developer ID sign, notarise/staple, DMG, `--dry-run`) and `make release`.
|
||||
2026-11-26 · T8.6 · The compatibility matrix remains a manual 10-app pass; no untested cell is claimed.
|
||||
2026-11-26 · T8.5 · Added a sibling-family app icon (`make icon`), `CFBundleIconName`/asset catalog wiring, `make install` from the Release build, and `make dmg`/`scripts/make-dmg.sh` with a mounted-image signature check. Dry-run release and local DMG/install were verified.
|
||||
2026-11-26 · M4 polish · Enlarged the drag surface to the whole left header block, with a visible grip backed by an AppKit `performDrag` area; the panel keeps a moved position while visible and only recenters near the cursor when shown again. Added a persisted `translationFontSize` setting (default 17 pt, 12–28) with a Settings stepper and applied it to the translation text.
|
||||
2026-11-26 · Panel · The source section now stays available as a collapsed “Show source” disclosure row after the user collapses it, instead of disappearing.
|
||||
@@ -52,6 +52,9 @@ Evaluation:
|
||||
- chrF and BLEU match hand-computed values on a tiny pair.
|
||||
- Protected-token retention is 1.0 for a clean pair and 0.0 for a lost URL.
|
||||
- Numeric normalisation treats `1,5`, `1.5` and `1 5` as the same value only where documented.
|
||||
- Manifest validation rejects duplicate IDs, bad paths, bad languages and unknown reference kinds.
|
||||
- `report.md`/`report.json` contain the environment block and per-category tables.
|
||||
- `scripts/privacy-self-test.sh` seeds and detects one violation for every major SP rule.
|
||||
|
||||
## Manual release checklist
|
||||
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# Sprachmittler — user guide
|
||||
|
||||
Sprachmittler translates the text you select, locally, with Tencent's Hy-MT3 model in Ollama.
|
||||
Nothing is sent to a cloud service and no history is kept.
|
||||
|
||||
## 1. Install Ollama and the model
|
||||
|
||||
1. Install Ollama from <https://ollama.com/download>.
|
||||
2. Open Terminal and run:
|
||||
|
||||
```bash
|
||||
ollama pull hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M
|
||||
```
|
||||
|
||||
This is the 7.5B model (about 5.15 GB download). The smaller Fast model is optional:
|
||||
|
||||
```bash
|
||||
ollama pull hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M
|
||||
```
|
||||
|
||||
3. Leave Ollama running. Sprachmittler uses `http://127.0.0.1:11434` by default.
|
||||
|
||||
## 2. Install Sprachmittler
|
||||
|
||||
Build and install from the repository:
|
||||
|
||||
```bash
|
||||
make install
|
||||
```
|
||||
|
||||
The app appears in the menu bar. There is no Dock icon. On first launch, setup checks Ollama,
|
||||
the Hy-MT3 model and the target language. You can reopen setup from the menu bar at any time.
|
||||
|
||||
## 3. Translate
|
||||
|
||||
1. Select text in any app.
|
||||
2. Press **⌘C** twice quickly (within 500 ms).
|
||||
3. The floating panel appears near the mouse. The source app keeps focus.
|
||||
4. The translation streams in. Use the language picker to change the target.
|
||||
5. Click **Copy** to put the translation on the clipboard, or **Replace** to replace the selection.
|
||||
6. **Esc** closes the panel. **⌘C** copies, **⌘↩** replaces, **⌘R** retries and **⌘,** opens Settings.
|
||||
|
||||
Replace is explicit; nothing is inserted automatically. Replace needs the macOS Accessibility
|
||||
permission. Double copy, translation, Copy and the Services menu work without it.
|
||||
|
||||
## 4. Services and the menu bar
|
||||
|
||||
- **Services ▸ Translate with Sprachmittler** translates the current selection without polling
|
||||
or Accessibility. You can assign a shortcut under System Settings ▸ Keyboard ▸ Keyboard
|
||||
Shortcuts ▸ Services ▸ Text.
|
||||
- The menu bar can translate the current clipboard, change the target, copy or replace the last
|
||||
translation, open setup, open diagnostics or quit.
|
||||
|
||||
## 5. Privacy and permissions
|
||||
|
||||
- Selected text, translations, prompts and clipboard contents are never logged or written to disk.
|
||||
- Settings contain only configuration. There is no translation history.
|
||||
- The default endpoint is loopback. A remote endpoint requires an explicit HTTPS toggle.
|
||||
- Accessibility is optional and requested only for Replace.
|
||||
- Input Monitoring, Screen Recording, Camera, Microphone and Apple Events are never requested.
|
||||
- Diagnostics shows versions, digests, timings and error kinds only — no text.
|
||||
|
||||
## 6. Troubleshooting
|
||||
|
||||
| Symptom | Fix |
|
||||
|---|---|
|
||||
| “Ollama is not running.” | Start Ollama, then retry. |
|
||||
| “The Hy-MT3 model is not installed.” | Run the `ollama pull` command from setup. |
|
||||
| “Replace needs the Accessibility permission.” | Open System Settings ▸ Privacy & Security ▸ Accessibility and enable Sprachmittler, or use Copy. |
|
||||
| Replace fails in an app | Use Copy; some Electron/canvas apps do not expose a settable selection. |
|
||||
| The previous clipboard is not restored | Another app changed the clipboard during the paste; Copy remains available. |
|
||||
| The panel does not appear | Copy the same text twice within 500 ms; check that the text is non-empty. |
|
||||
| Translation is cut off | Shorten the selection or retry; the model's documented translation context is 8192 tokens. |
|
||||
| A number or URL changed | The panel shows a warning; review the text before using it. |
|
||||
| Slow first translation | The model is loading; warm-up and `keep_alive` keep it ready. |
|
||||
|
||||
## 7. Uninstall
|
||||
|
||||
Quit Sprachmittler, remove `Sprachmittler.app` from `/Applications`, and remove its Accessibility
|
||||
entry in System Settings if present. Ollama and the model are separate and can be removed with
|
||||
Ollama's own tools.
|
||||
@@ -53,6 +53,7 @@ targets:
|
||||
CODE_SIGN_IDENTITY: "-" # "Sign to Run Locally" for development
|
||||
ENABLE_APP_SANDBOX: NO # ADR-003: Accessibility insertion needs it off
|
||||
COMBINE_HIDPI_IMAGES: YES
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
|
||||
dependencies:
|
||||
- package: SprachmittlerKit
|
||||
product: SprachmittlerCore
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
#!/usr/bin/env swift
|
||||
// Generates App/Resources/Assets.xcassets/AppIcon.appiconset from vector geometry.
|
||||
//
|
||||
// Run with `make icon` (or `swift scripts/generate-app-icon.swift`). PNGs are committed, so
|
||||
// `make verify` does not depend on this script.
|
||||
//
|
||||
// Family geometry follows Vorleser and Schriftleser: 1024 canvas, 824 opaque indigo tile,
|
||||
// transparent margin, soft shadow. The translation motif is two facing speech bubbles carrying
|
||||
// text bars; small sizes simplify to one bubble for legibility.
|
||||
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import ImageIO
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
private enum Design {
|
||||
static let canvas: CGFloat = 1024
|
||||
static let tileInset: CGFloat = 100
|
||||
static let tileSize = canvas - tileInset * 2
|
||||
static let tileRadius = tileSize * 0.2245
|
||||
|
||||
// Same indigo family tile as Vorleser and Schriftleser.
|
||||
static let gradientTop = srgb(0x5B, 0x7C, 0xFA)
|
||||
static let gradientBottom = srgb(0x2E, 0x3F, 0xC7)
|
||||
static let glyph = srgb(0xFF, 0xFF, 0xFF)
|
||||
static let bar = srgb(0x2F, 0x3E, 0xC4)
|
||||
|
||||
static func srgb(_ r: UInt8, _ g: UInt8, _ b: UInt8) -> CGColor {
|
||||
CGColor(
|
||||
colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!,
|
||||
components: [CGFloat(r) / 255, CGFloat(g) / 255, CGFloat(b) / 255, 1]
|
||||
)!
|
||||
}
|
||||
}
|
||||
|
||||
private struct Bubble {
|
||||
let rect: CGRect
|
||||
let radius: CGFloat
|
||||
let tail: [CGPoint]
|
||||
let bars: [CGFloat]
|
||||
let barHeight: CGFloat
|
||||
let barGap: CGFloat
|
||||
let fill: CGColor
|
||||
let barColor: CGColor
|
||||
}
|
||||
|
||||
private struct Layout {
|
||||
let size: Int
|
||||
let scale: CGFloat
|
||||
let tile: CGRect
|
||||
let tileRadius: CGFloat
|
||||
let bubbles: [Bubble]
|
||||
let shadow: (offset: CGSize, blur: CGFloat, opacity: CGFloat)?
|
||||
|
||||
init(size: Int) {
|
||||
self.size = size
|
||||
scale = CGFloat(size) / Design.canvas
|
||||
tile = CGRect(x: Design.tileInset, y: Design.tileInset, width: Design.tileSize, height: Design.tileSize)
|
||||
tileRadius = Design.tileRadius
|
||||
|
||||
let simplified = size <= 32
|
||||
let barThickness = Design.canvas * (simplified ? 0.075 : 0.045)
|
||||
let barGap = barThickness * (simplified ? 1.15 : 0.85)
|
||||
let tailStroke = Design.canvas * (simplified ? 0.05 : 0.030)
|
||||
|
||||
if simplified {
|
||||
let width = tile.width * 0.76
|
||||
let height = tile.height * 0.56
|
||||
let rect = CGRect(
|
||||
x: tile.midX - width / 2,
|
||||
y: tile.minY + tile.height * 0.52 - height / 2,
|
||||
width: width,
|
||||
height: height
|
||||
)
|
||||
let tail = [
|
||||
CGPoint(x: rect.minX + width * 0.24, y: rect.minY + barThickness * 0.8),
|
||||
CGPoint(x: rect.minX + width * 0.10, y: rect.minY - height * 0.13),
|
||||
CGPoint(x: rect.minX + width * 0.44, y: rect.minY + barThickness * 0.8),
|
||||
]
|
||||
bubbles = [
|
||||
Bubble(
|
||||
rect: rect,
|
||||
radius: height * 0.26,
|
||||
tail: tail,
|
||||
bars: [width * 0.62, width * 0.40],
|
||||
barHeight: barThickness,
|
||||
barGap: barGap,
|
||||
fill: Design.glyph,
|
||||
barColor: Design.bar
|
||||
),
|
||||
]
|
||||
} else {
|
||||
let backWidth = tile.width * 0.56
|
||||
let backHeight = tile.height * 0.33
|
||||
let backRect = CGRect(
|
||||
x: tile.minX + tile.width * 0.06,
|
||||
y: tile.minY + tile.height * 0.34,
|
||||
width: backWidth,
|
||||
height: backHeight
|
||||
)
|
||||
let backTail = [
|
||||
CGPoint(x: backRect.minX + backWidth * 0.18, y: backRect.minY + tailStroke * 0.7),
|
||||
CGPoint(x: backRect.minX + backWidth * 0.02, y: backRect.minY - backHeight * 0.16),
|
||||
CGPoint(x: backRect.minX + backWidth * 0.40, y: backRect.minY + tailStroke * 0.7),
|
||||
]
|
||||
let back = Bubble(
|
||||
rect: backRect,
|
||||
radius: backHeight * 0.26,
|
||||
tail: backTail,
|
||||
bars: [backWidth * 0.62, backWidth * 0.45, backWidth * 0.30],
|
||||
barHeight: barThickness,
|
||||
barGap: barGap,
|
||||
fill: Design.bar,
|
||||
barColor: Design.glyph
|
||||
)
|
||||
|
||||
let frontWidth = tile.width * 0.48
|
||||
let frontHeight = tile.height * 0.30
|
||||
let frontRect = CGRect(
|
||||
x: tile.maxX - tile.width * 0.06 - frontWidth,
|
||||
y: tile.minY + tile.height * 0.18,
|
||||
width: frontWidth,
|
||||
height: frontHeight
|
||||
)
|
||||
let frontTail = [
|
||||
CGPoint(x: frontRect.maxX - frontWidth * 0.18, y: frontRect.minY + tailStroke * 0.7),
|
||||
CGPoint(x: frontRect.maxX - frontWidth * 0.02, y: frontRect.minY - frontHeight * 0.16),
|
||||
CGPoint(x: frontRect.maxX - frontWidth * 0.40, y: frontRect.minY + tailStroke * 0.7),
|
||||
]
|
||||
let front = Bubble(
|
||||
rect: frontRect,
|
||||
radius: frontHeight * 0.26,
|
||||
tail: frontTail,
|
||||
bars: [frontWidth * 0.62, frontWidth * 0.40],
|
||||
barHeight: barThickness,
|
||||
barGap: barGap,
|
||||
fill: Design.glyph,
|
||||
barColor: Design.bar
|
||||
)
|
||||
bubbles = [back, front]
|
||||
}
|
||||
|
||||
shadow = size >= 128 ? (CGSize(width: 0, height: -8), 26, 0.32) : nil
|
||||
}
|
||||
}
|
||||
|
||||
private func roundedRect(_ rect: CGRect, _ radius: CGFloat) -> CGPath {
|
||||
CGPath(roundedRect: rect, cornerWidth: radius, cornerHeight: radius, transform: nil)
|
||||
}
|
||||
|
||||
private func render(size: Int) -> CGImage? {
|
||||
let layout = Layout(size: size)
|
||||
let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
|
||||
guard let context = CGContext(
|
||||
data: nil,
|
||||
width: size,
|
||||
height: size,
|
||||
bitsPerComponent: 8,
|
||||
bytesPerRow: 0,
|
||||
space: colorSpace,
|
||||
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
|
||||
) else { return nil }
|
||||
|
||||
context.setAllowsAntialiasing(true)
|
||||
context.setShouldAntialias(true)
|
||||
context.interpolationQuality = .high
|
||||
context.clear(CGRect(x: 0, y: 0, width: size, height: size))
|
||||
context.scaleBy(x: layout.scale, y: layout.scale)
|
||||
|
||||
let tilePath = roundedRect(layout.tile, layout.tileRadius)
|
||||
context.saveGState()
|
||||
if let shadow = layout.shadow {
|
||||
context.setShadow(
|
||||
offset: shadow.offset,
|
||||
blur: shadow.blur,
|
||||
color: CGColor(colorSpace: colorSpace, components: [0, 0, 0, shadow.opacity])
|
||||
)
|
||||
}
|
||||
context.addPath(tilePath)
|
||||
context.setFillColor(Design.gradientBottom)
|
||||
context.fillPath()
|
||||
context.restoreGState()
|
||||
|
||||
let gradient = CGGradient(
|
||||
colorsSpace: colorSpace,
|
||||
colors: [Design.gradientTop, Design.gradientBottom] as CFArray,
|
||||
locations: [0, 1]
|
||||
)!
|
||||
context.saveGState()
|
||||
context.addPath(tilePath)
|
||||
context.clip()
|
||||
context.drawLinearGradient(
|
||||
gradient,
|
||||
start: CGPoint(x: layout.tile.midX, y: layout.tile.maxY),
|
||||
end: CGPoint(x: layout.tile.midX, y: layout.tile.minY),
|
||||
options: []
|
||||
)
|
||||
context.restoreGState()
|
||||
|
||||
for bubble in layout.bubbles {
|
||||
context.setFillColor(bubble.fill)
|
||||
context.beginPath()
|
||||
context.addLines(between: bubble.tail)
|
||||
context.closePath()
|
||||
context.fillPath()
|
||||
context.addPath(roundedRect(bubble.rect, bubble.radius))
|
||||
context.fillPath()
|
||||
|
||||
let totalHeight = CGFloat(bubble.bars.count) * bubble.barHeight
|
||||
+ CGFloat(bubble.bars.count - 1) * bubble.barGap
|
||||
var y = bubble.rect.midY + totalHeight / 2 - bubble.barHeight
|
||||
let x = bubble.rect.minX + bubble.rect.width * 0.16
|
||||
context.setFillColor(bubble.barColor)
|
||||
for width in bubble.bars {
|
||||
context.addPath(roundedRect(
|
||||
CGRect(x: x, y: y, width: width, height: bubble.barHeight),
|
||||
bubble.barHeight / 2
|
||||
))
|
||||
context.fillPath()
|
||||
y -= bubble.barHeight + bubble.barGap
|
||||
}
|
||||
}
|
||||
|
||||
return context.makeImage()
|
||||
}
|
||||
|
||||
private let slots: [(name: String, pixels: Int)] = [
|
||||
("icon_16x16.png", 16),
|
||||
("icon_16x16@2x.png", 32),
|
||||
("icon_32x32.png", 32),
|
||||
("icon_32x32@2x.png", 64),
|
||||
("icon_128x128.png", 128),
|
||||
("icon_128x128@2x.png", 256),
|
||||
("icon_256x256.png", 256),
|
||||
("icon_256x256@2x.png", 512),
|
||||
("icon_512x512.png", 512),
|
||||
("icon_512x512@2x.png", 1024),
|
||||
]
|
||||
|
||||
private let contents = """
|
||||
{
|
||||
"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 }
|
||||
}
|
||||
|
||||
"""
|
||||
|
||||
private let assetCatalogContents = """
|
||||
{
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
|
||||
"""
|
||||
|
||||
private func writePNG(_ image: CGImage, to url: URL) throws {
|
||||
guard let destination = CGImageDestinationCreateWithURL(
|
||||
url as CFURL,
|
||||
UTType.png.identifier as CFString,
|
||||
1,
|
||||
nil
|
||||
) else {
|
||||
throw NSError(domain: "icon", code: 1, userInfo: [NSLocalizedDescriptionKey: "cannot write \(url.path)"])
|
||||
}
|
||||
CGImageDestinationAddImage(destination, image, nil)
|
||||
guard CGImageDestinationFinalize(destination) else {
|
||||
throw NSError(domain: "icon", code: 2, userInfo: [NSLocalizedDescriptionKey: "cannot finish \(url.path)"])
|
||||
}
|
||||
}
|
||||
|
||||
private func writePreview(to url: URL) throws {
|
||||
let width = 1240
|
||||
let height = 640
|
||||
let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
|
||||
guard let context = CGContext(
|
||||
data: nil,
|
||||
width: width,
|
||||
height: height,
|
||||
bitsPerComponent: 8,
|
||||
bytesPerRow: 0,
|
||||
space: colorSpace,
|
||||
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
|
||||
) else { return }
|
||||
|
||||
context.setFillColor(Design.srgb(0xEC, 0xEC, 0xEE))
|
||||
context.fill(CGRect(x: 0, y: 0, width: width, height: height / 2))
|
||||
context.setFillColor(Design.srgb(0x1C, 0x1C, 0x1E))
|
||||
context.fill(CGRect(x: 0, y: height / 2, width: width, height: height / 2))
|
||||
|
||||
var x = 40
|
||||
for size in [16, 32, 64, 128, 256] {
|
||||
if let image = render(size: size) {
|
||||
context.draw(image, in: CGRect(x: x, y: height / 2 + 40, width: size, height: size))
|
||||
context.draw(image, in: CGRect(x: x, y: 40, width: size, height: size))
|
||||
}
|
||||
x += size + 50
|
||||
}
|
||||
|
||||
x += 20
|
||||
for size in [16, 32] {
|
||||
guard let image = render(size: size) else { continue }
|
||||
let scale = 8
|
||||
let side = size * scale
|
||||
context.saveGState()
|
||||
context.interpolationQuality = .none
|
||||
context.draw(image, in: CGRect(x: x, y: height / 2 - side / 2, width: side, height: side))
|
||||
context.restoreGState()
|
||||
x += side + 40
|
||||
}
|
||||
|
||||
guard let image = context.makeImage() else { return }
|
||||
try writePNG(image, to: url)
|
||||
}
|
||||
|
||||
private let root = URL(fileURLWithPath: #filePath)
|
||||
.deletingLastPathComponent()
|
||||
.deletingLastPathComponent()
|
||||
private let assetCatalog = root
|
||||
.appendingPathComponent("App/Resources/Assets.xcassets", isDirectory: true)
|
||||
private let iconSet = assetCatalog.appendingPathComponent("AppIcon.appiconset", isDirectory: true)
|
||||
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: iconSet, withIntermediateDirectories: true)
|
||||
try assetCatalogContents.write(
|
||||
to: assetCatalog.appendingPathComponent("Contents.json"),
|
||||
atomically: true,
|
||||
encoding: .utf8
|
||||
)
|
||||
try contents.write(to: iconSet.appendingPathComponent("Contents.json"), atomically: true, encoding: .utf8)
|
||||
|
||||
for slot in slots {
|
||||
guard let image = render(size: slot.pixels) else {
|
||||
throw NSError(domain: "icon", code: 3, userInfo: [NSLocalizedDescriptionKey: "render failed at \(slot.pixels)"])
|
||||
}
|
||||
try writePNG(image, to: iconSet.appendingPathComponent(slot.name))
|
||||
}
|
||||
|
||||
let previewDirectory = root.appendingPathComponent(".build", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: previewDirectory, withIntermediateDirectories: true)
|
||||
try writePreview(to: previewDirectory.appendingPathComponent("icon-preview.png"))
|
||||
|
||||
print("wrote \(slots.count) icons to \(iconSet.path)")
|
||||
print("preview: \(previewDirectory.appendingPathComponent("icon-preview.png").path)")
|
||||
} catch {
|
||||
FileHandle.standardError.write(Data("error: \(error.localizedDescription)\n".utf8))
|
||||
exit(1)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build a local, unnotarised DMG from the Release build. For testing/internal sharing only; use
|
||||
# scripts/release.sh for a Developer ID signed and notarised distribution image.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
app="Sprachmittler"
|
||||
release_app=".build/xcode-release/Build/Products/Release/$app.app"
|
||||
dist="${DMG_DIR:-dist}"
|
||||
|
||||
[[ "$(uname -s)" == "Darwin" && "$(uname -m)" == "arm64" ]] \
|
||||
|| { echo "error: Sprachmittler requires an Apple Silicon Mac" >&2; exit 1; }
|
||||
[[ -d "$release_app" ]] || { echo "error: $release_app not found — run 'make release-build'" >&2; exit 1; }
|
||||
|
||||
step() { printf '\n\033[1m▶ %s\033[0m\n' "$*"; }
|
||||
|
||||
check_app() {
|
||||
local candidate="$1"
|
||||
scripts/check-signature.sh "$candidate" install
|
||||
}
|
||||
|
||||
step "Check Release build"
|
||||
check_app "$release_app"
|
||||
version=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "$release_app/Contents/Info.plist")
|
||||
[[ -n "$version" ]] || { echo "error: cannot read CFBundleShortVersionString" >&2; exit 1; }
|
||||
dmg="$dist/$app-$version-local.dmg"
|
||||
|
||||
stage=$(mktemp -d)
|
||||
mountpoint=$(mktemp -d)
|
||||
mounted=0
|
||||
cleanup() {
|
||||
if [[ $mounted -eq 1 ]]; then hdiutil detach "$mountpoint" -quiet || true; fi
|
||||
rm -rf "$stage" "$mountpoint"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
step "Stage $app $version"
|
||||
ditto "$release_app" "$stage/$app.app"
|
||||
ln -s /Applications "$stage/Applications"
|
||||
|
||||
step "Create $dmg"
|
||||
mkdir -p "$dist"
|
||||
rm -f "$dmg"
|
||||
if diskutil image create from --help >/dev/null 2>&1; then
|
||||
if ! output=$(diskutil image create from "$stage" "$dmg" --volumeName "$app" --format UDZO 2>&1); then
|
||||
printf '%s\n' "$output" >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
hdiutil create -volname "$app" -srcfolder "$stage" -ov -format UDZO "$dmg" >/dev/null
|
||||
fi
|
||||
hdiutil verify "$dmg" >/dev/null
|
||||
|
||||
step "Verify mounted image"
|
||||
hdiutil attach "$dmg" -readonly -nobrowse -noautoopen -quiet -mountpoint "$mountpoint"
|
||||
mounted=1
|
||||
check_app "$mountpoint/$app.app"
|
||||
[[ -L "$mountpoint/Applications" ]] \
|
||||
|| { echo "error: Applications link missing from the image" >&2; exit 1; }
|
||||
hdiutil detach "$mountpoint" -quiet
|
||||
mounted=0
|
||||
|
||||
printf '\n\033[32m✔ %s\033[0m\n' "$dmg"
|
||||
printf ' size %s\n' "$(du -h "$dmg" | cut -f1)"
|
||||
printf ' sha256 %s\n' "$(shasum -a 256 "$dmg" | cut -d' ' -f1)"
|
||||
cat <<'TXT'
|
||||
|
||||
Ad-hoc signed and not notarised: this image is for testing and internal sharing only.
|
||||
On another Mac, open it via right-click ▸ Open (or System Settings ▸ Privacy & Security ▸ Open Anyway).
|
||||
For distribution use scripts/release.sh with a Developer ID identity and a notarytool profile.
|
||||
TXT
|
||||
@@ -1,9 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# Static checks for the invariants in docs/SECURITY_PRIVACY.md (SP-1 … SP-15).
|
||||
set -uo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
PKGSRC="Packages/SprachmittlerKit/Sources"
|
||||
SRC="$PKGSRC App"
|
||||
ROOT="${SPRACHMITTLER_PRIVACY_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
|
||||
cd "$ROOT"
|
||||
PKGSRC="$ROOT/Packages/SprachmittlerKit/Sources"
|
||||
SRC="$PKGSRC $ROOT/App"
|
||||
fail=0
|
||||
if ! command -v rg >/dev/null; then echo "warning: ripgrep (rg) not installed, privacy checks skipped (brew install ripgrep)"; exit 0; fi
|
||||
report() { echo "✗ $1"; fail=1; }
|
||||
@@ -23,7 +24,7 @@ h=$(hits 'shortHash' $SRC -g '!**/LogRedaction.swift' | rg -v 'privacy: *\.priva
|
||||
[[ -n "$h" ]] && { report "SP-2: shortHash must be logged with privacy: .private"; echo "$h"; }
|
||||
|
||||
# SP-3: no telemetry or crash-reporting SDKs
|
||||
h=$(hits -i 'firebase|crashlytics|sentry|amplitude|mixpanel|segment\.io|appcenter|bugsnag|datadog' Packages/SprachmittlerKit/Package.swift project.yml $SRC)
|
||||
h=$(hits -i 'firebase|crashlytics|sentry|amplitude|mixpanel|segment\.io|appcenter|bugsnag|datadog' "$ROOT/Packages/SprachmittlerKit/Package.swift" "$ROOT/project.yml" $SRC)
|
||||
[[ -n "$h" ]] && { report "SP-3: telemetry or analytics dependency"; echo "$h"; }
|
||||
|
||||
# SP-4: networking only in SprachmittlerOllama
|
||||
@@ -31,7 +32,7 @@ h=$(hits 'URLSession|URLRequest\(' $SRC -g '!**/SprachmittlerOllama/**' -g '!**/
|
||||
[[ -n "$h" ]] && { report "SP-4: networking outside SprachmittlerOllama"; echo "$h"; }
|
||||
|
||||
# SP-5: no arbitrary loads
|
||||
if rg -n 'NSAllowsArbitraryLoads' App/Info.plist >/dev/null 2>&1; then report "SP-5: NSAllowsArbitraryLoads present"; fi
|
||||
if rg -n 'NSAllowsArbitraryLoads' "$ROOT/App/Info.plist" >/dev/null 2>&1; then report "SP-5: NSAllowsArbitraryLoads present"; fi
|
||||
|
||||
# SP-6: ephemeral session, no shared session
|
||||
h=$(hits 'URLSession\.shared|URLSessionConfiguration\.default' $PKGSRC -g '!**/SprachmittlerTestSupport/**')
|
||||
@@ -42,16 +43,16 @@ h=$(hits -i '(UserDefaults|Keychain|SecItemAdd).*(text|translation|source|pasteb
|
||||
[[ -n "$h" ]] && { report "SP-7: possible text persistence"; echo "$h"; }
|
||||
|
||||
# SP-10: exactly the app-sandbox key, set to false; no unused usage strings
|
||||
ENT=App/Sprachmittler.entitlements
|
||||
ENT="$ROOT/App/Sprachmittler.entitlements"
|
||||
expected=$'com.apple.security.app-sandbox'
|
||||
actual=$(rg -o '<key>[^<]+</key>' "$ENT" 2>/dev/null | sed -E 's#</?key>##g' | sort)
|
||||
[[ "$actual" == "$expected" ]] || { report "SP-10: entitlements differ from the allowed set"; diff <(echo "$expected") <(echo "$actual"); }
|
||||
rg -U -q '<key>com.apple.security.app-sandbox</key>\s*<false/>' "$ENT" || report "SP-10: app-sandbox must be false (ADR-003)"
|
||||
if rg -n 'NS(Microphone|Camera|ScreenCapture|AppleEvents|Accessibility|InputMonitoring)UsageDescription' App/Info.plist >/dev/null 2>&1; then report "SP-10: unexpected usage description in Info.plist"; fi
|
||||
if ! rg -n '<key>LSUIElement</key>' App/Info.plist >/dev/null 2>&1; then report "Shape: LSUIElement missing; Sprachmittler is a menu-bar agent"; fi
|
||||
if rg -n 'NS(Microphone|Camera|ScreenCapture|AppleEvents|Accessibility|InputMonitoring)UsageDescription' "$ROOT/App/Info.plist" >/dev/null 2>&1; then report "SP-10: unexpected usage description in Info.plist"; fi
|
||||
if ! rg -n '<key>LSUIElement</key>' "$ROOT/App/Info.plist" >/dev/null 2>&1; then report "Shape: LSUIElement missing; Sprachmittler is a menu-bar agent"; fi
|
||||
|
||||
# SP-11 / ADR-002: prompt strings only in SprachmittlerEngines
|
||||
h=$(hits '"(Translate the following text into|only output the translated result|Please accurately translate the following|### Task)' $PKGSRC -g '!**/SprachmittlerEngines/**')
|
||||
h=$(hits '"(Translate the following text into|only output the translated result|Please accurately translate the following|### Task)' "$PKGSRC" -g '!**/SprachmittlerEngines/**')
|
||||
[[ -n "$h" ]] && { report "ADR-002: model prompt literal outside SprachmittlerEngines"; echo "$h"; }
|
||||
|
||||
# Permissions: no screen, camera, microphone, Apple Events or global key tap
|
||||
@@ -59,13 +60,13 @@ h=$(hits 'CGWindowListCreateImage|CGDisplayStream|SCStream|AVCaptureDevice|NSApp
|
||||
[[ -n "$h" ]] && { report "Permissions: forbidden capture or key-tap API found"; echo "$h"; }
|
||||
|
||||
# Architectural boundaries (SwiftLint also enforces these)
|
||||
h=$(hits 'NSPasteboard' $PKGSRC -g '!**/SprachmittlerCapture/**' -g '!**/SprachmittlerTestSupport/**')
|
||||
h=$(hits 'NSPasteboard' "$PKGSRC" -g '!**/SprachmittlerCapture/**' -g '!**/SprachmittlerTestSupport/**')
|
||||
[[ -n "$h" ]] && { report "Boundary: NSPasteboard outside SprachmittlerCapture"; echo "$h"; }
|
||||
h=$(hits 'AXUIElement|AXIsProcessTrusted|kAXSelectedText' $PKGSRC -g '!**/SprachmittlerCapture/**' -g '!**/SprachmittlerTestSupport/**')
|
||||
h=$(hits 'AXUIElement|AXIsProcessTrusted|kAXSelectedText' "$PKGSRC" -g '!**/SprachmittlerCapture/**' -g '!**/SprachmittlerTestSupport/**')
|
||||
[[ -n "$h" ]] && { report "Boundary: Accessibility outside SprachmittlerCapture"; echo "$h"; }
|
||||
|
||||
# No write of text to disk (settings only; no file writes yet)
|
||||
h=$(hits '(write\(to:|FileHandle.*write|createFile)' $PKGSRC -g '!**/SprachmittlerTestSupport/**' -g '!**/sprachmittler-cli/**')
|
||||
h=$(hits '(write\(to:|FileHandle.*write|createFile)' $PKGSRC -g '!**/SprachmittlerTestSupport/**' -g '!**/sprachmittler-cli/**' -g '!**/SprachmittlerEval/**')
|
||||
[[ -n "$h" ]] && { report "Persistence: file write found outside the CLI"; echo "$h"; }
|
||||
|
||||
[[ $fail -eq 0 ]] && echo "✓ privacy checks passed"
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env bash
|
||||
# Seeds one representative violation per privacy rule and asserts privacy-check.sh fails.
|
||||
set -euo pipefail
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
CHECK="$HERE/privacy-check.sh"
|
||||
if ! command -v rg >/dev/null; then echo "skip: ripgrep not installed"; exit 0; fi
|
||||
root="$(mktemp -d "${TMPDIR:-/tmp}/sprachmittler-privacy.XXXXXX")"
|
||||
trap 'find "$root" -depth -delete 2>/dev/null || true' EXIT
|
||||
|
||||
mkdir -p "$root/App" "$root/Packages/SprachmittlerKit/Sources/SprachmittlerCore" "$root/Packages/SprachmittlerKit/Sources/SprachmittlerEngines" "$root/Packages/SprachmittlerKit/Sources/SprachmittlerCapture" "$root/Packages/SprachmittlerKit/Sources/SprachmittlerOllama"
|
||||
seed="$root/Packages/SprachmittlerKit/Sources/SprachmittlerCore/Seed.swift"
|
||||
|
||||
write_base() {
|
||||
: > "$seed"
|
||||
cat > "$root/project.yml" <<'EOF'
|
||||
name: PrivacySelfTest
|
||||
EOF
|
||||
cat > "$root/Packages/SprachmittlerKit/Package.swift" <<'EOF'
|
||||
// swift-tools-version:6.0
|
||||
import PackageDescription
|
||||
let package = Package(name: "PrivacySelfTest")
|
||||
EOF
|
||||
cat > "$root/App/Info.plist" <<'EOF'
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict><key>LSUIElement</key><true/></dict></plist>
|
||||
EOF
|
||||
cat > "$root/App/Sprachmittler.entitlements" <<'EOF'
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict><key>com.apple.security.app-sandbox</key><false/></dict></plist>
|
||||
EOF
|
||||
}
|
||||
|
||||
expect_fail() {
|
||||
if SPRACHMITTLER_PRIVACY_ROOT="$root" "$CHECK" >/dev/null 2>&1; then
|
||||
echo "✗ seeded violation was not detected: $1"
|
||||
exit 1
|
||||
fi
|
||||
echo "✓ detected: $1"
|
||||
write_base
|
||||
}
|
||||
|
||||
write_base
|
||||
if ! SPRACHMITTLER_PRIVACY_ROOT="$root" "$CHECK" >/dev/null 2>&1; then
|
||||
echo "✗ clean fixture failed privacy-check"
|
||||
exit 1
|
||||
fi
|
||||
echo "✓ clean fixture passes"
|
||||
|
||||
echo 'let watcher = "FSEventStreamCreate"' > "$seed"
|
||||
expect_fail "SP-1 file watching"
|
||||
|
||||
echo 'Log.error("\(text)")' > "$seed"
|
||||
expect_fail "SP-2 content logging"
|
||||
|
||||
printf '\n// firebase\n' >> "$root/Packages/SprachmittlerKit/Package.swift"
|
||||
expect_fail "SP-3 telemetry dependency"
|
||||
|
||||
echo 'let session = URLSession.shared' > "$seed"
|
||||
expect_fail "SP-4 networking outside Ollama"
|
||||
|
||||
python3 - "$root/App/Info.plist" <<'PY'
|
||||
import sys
|
||||
from pathlib import Path
|
||||
p=Path(sys.argv[1])
|
||||
s=p.read_text().replace('<dict><key>LSUIElement</key><true/></dict>','<dict><key>LSUIElement</key><true/><key>NSAppTransportSecurity</key><dict><key>NSAllowsArbitraryLoads</key><true/></dict></dict>')
|
||||
p.write_text(s)
|
||||
PY
|
||||
expect_fail "SP-5 arbitrary loads"
|
||||
|
||||
echo 'let config = URLSessionConfiguration.default' > "$seed"
|
||||
expect_fail "SP-6 default URL session"
|
||||
|
||||
echo 'UserDefaults.standard.set("text", forKey: "x")' > "$seed"
|
||||
expect_fail "SP-7 text persistence"
|
||||
|
||||
python3 - "$root/App/Sprachmittler.entitlements" <<'PY'
|
||||
import sys
|
||||
from pathlib import Path
|
||||
p=Path(sys.argv[1])
|
||||
s=p.read_text().replace('<key>com.apple.security.app-sandbox</key><false/>','<key>com.apple.security.app-sandbox</key><false/><key>com.apple.security.network.client</key><true/>')
|
||||
p.write_text(s)
|
||||
PY
|
||||
expect_fail "SP-10 extra entitlement"
|
||||
|
||||
echo 'let prompt = "Translate the following text into German."' > "$seed"
|
||||
expect_fail "ADR-002 prompt literal"
|
||||
|
||||
echo 'let pasteboard = NSPasteboard.general' > "$seed"
|
||||
expect_fail "boundary pasteboard"
|
||||
|
||||
echo 'let ax = AXUIElementCreateApplication(1)' > "$seed"
|
||||
expect_fail "boundary Accessibility"
|
||||
|
||||
echo 'try "text".write(to: URL(fileURLWithPath: "/tmp/x"), atomically: true, encoding: .utf8)' > "$seed"
|
||||
expect_fail "persistence write"
|
||||
|
||||
echo 'let image = CGWindowListCreateImage(.zero, .optionOnScreenOnly, kCGNullWindowID, [])' > "$seed"
|
||||
expect_fail "forbidden capture API"
|
||||
|
||||
echo "✓ privacy self-test passed"
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build, sign, notarise, staple and package Sprachmittler. Use --dry-run first.
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
DRY_RUN=0
|
||||
SKIP_NOTARIZE=0
|
||||
VERSION="${MARKETING_VERSION:-0.1.0}"
|
||||
BUILD="$ROOT/build/release"
|
||||
ARCHIVE="$BUILD/Sprachmittler.xcarchive"
|
||||
APP="$ARCHIVE/Products/Applications/Sprachmittler.app"
|
||||
IDENTITY="${DEVELOPER_ID_APPLICATION:-}"
|
||||
PROFILE="${SPRACHMITTLER_NOTARY_PROFILE:-sprachmittler-notary}"
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--dry-run) DRY_RUN=1 ;;
|
||||
--skip-notarize) SKIP_NOTARIZE=1 ;;
|
||||
--version=*) VERSION="${arg#*=}" ;;
|
||||
-h|--help)
|
||||
echo "usage: scripts/release.sh [--dry-run] [--skip-notarize] [--version=X.Y.Z]"
|
||||
echo "env: DEVELOPER_ID_APPLICATION, SPRACHMITTLER_NOTARY_PROFILE"
|
||||
exit 0
|
||||
;;
|
||||
*) echo "unknown argument: $arg" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
run() {
|
||||
if [[ "$DRY_RUN" -eq 1 ]]; then
|
||||
printf '+ %s\n' "$*"
|
||||
else
|
||||
"$@"
|
||||
fi
|
||||
}
|
||||
|
||||
if [[ "$DRY_RUN" -eq 0 && -z "$IDENTITY" ]]; then
|
||||
echo "DEVELOPER_ID_APPLICATION is required for a real release (Developer ID Application identity)." >&2
|
||||
exit 2
|
||||
fi
|
||||
for tool in xcodegen xcodebuild codesign ditto xcrun hdiutil; do
|
||||
command -v "$tool" >/dev/null || { echo "missing tool: $tool" >&2; exit 2; }
|
||||
done
|
||||
|
||||
run mkdir -p "$BUILD"
|
||||
run xcodegen generate --spec project.yml
|
||||
run xcodebuild -project Sprachmittler.xcodeproj -scheme Sprachmittler -configuration Release \
|
||||
-archivePath "$ARCHIVE" -destination 'platform=macOS,arch=arm64' \
|
||||
CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO archive
|
||||
run codesign --force --deep --options runtime \
|
||||
--entitlements App/Sprachmittler.entitlements --sign "$IDENTITY" "$APP"
|
||||
run codesign --verify --deep --strict --verbose=2 "$APP"
|
||||
|
||||
if [[ "$SKIP_NOTARIZE" -eq 0 ]]; then
|
||||
run ditto -c -k --keepParent "$APP" "$BUILD/Sprachmittler.zip"
|
||||
run xcrun notarytool submit "$BUILD/Sprachmittler.zip" --keychain-profile "$PROFILE" --wait
|
||||
run xcrun stapler staple "$APP"
|
||||
run xcrun stapler validate "$APP"
|
||||
run spctl --assess --type execute --verbose=2 "$APP"
|
||||
else
|
||||
echo "warning: notarisation skipped (--skip-notarize)" >&2
|
||||
fi
|
||||
|
||||
run hdiutil create -volname "Sprachmittler $VERSION" -srcfolder "$APP" -ov -format UDZO \
|
||||
"$BUILD/Sprachmittler-$VERSION.dmg"
|
||||
echo "Release artifacts: $BUILD"
|
||||
@@ -21,10 +21,12 @@ for f in opencode.json evaluation/corpus.schema.json evaluation/corpus.example.j
|
||||
jq -e . "$f" >/dev/null
|
||||
done
|
||||
plutil -lint App/Info.plist App/Sprachmittler.entitlements >/dev/null
|
||||
for f in App/Resources/*.lproj/Localizable.strings; do plutil -lint "$f" >/dev/null; done
|
||||
echo "✓ JSON and plists parse"
|
||||
|
||||
step "Privacy checks"
|
||||
scripts/privacy-check.sh
|
||||
scripts/privacy-self-test.sh
|
||||
|
||||
step "Package build"
|
||||
swift build --package-path "$PKG"
|
||||
|
||||