diff --git a/.gitignore b/.gitignore index ad35c9d..d6a1190 100644 --- a/.gitignore +++ b/.gitignore @@ -2,11 +2,13 @@ *.xcodeproj/ !*.xcodeproj/project.xcworkspace/xcshareddata/ .build/ +build/ DerivedData/ xcuserdata/ *.xcuserstate .swiftpm/ Packages/SprachmittlerKit/.build/ +build/ Packages/SprachmittlerKit/.swiftpm/ dist/ out/ diff --git a/App/Resources/de.lproj/Localizable.strings b/App/Resources/de.lproj/Localizable.strings new file mode 100644 index 0000000..9495f9c --- /dev/null +++ b/App/Resources/de.lproj/Localizable.strings @@ -0,0 +1,97 @@ +/* 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"; +"Source" = "Quelle"; +"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…"; diff --git a/App/Resources/en.lproj/Localizable.strings b/App/Resources/en.lproj/Localizable.strings new file mode 100644 index 0000000..1b71512 --- /dev/null +++ b/App/Resources/en.lproj/Localizable.strings @@ -0,0 +1,97 @@ +/* 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"; +"Source" = "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…"; diff --git a/Makefile b/Makefile index 491bf4d..69b43b5 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ DERIVED := .build/xcode APP_PATH := $(DERIVED)/Build/Products/Debug/Sprachmittler.app INSTALL_DIR ?= /Applications -.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 fixtures smoke privacy-check format manifest clean bootstrap: @scripts/bootstrap.sh @@ -39,6 +39,9 @@ app: build-app @pkill -x Sprachmittler 2>/dev/null || true open "$(APP_PATH)" +release: + @scripts/release.sh --dry-run + install: build-app @pkill -x Sprachmittler 2>/dev/null || true ditto "$(APP_PATH)" "$(INSTALL_DIR)/Sprachmittler.app" diff --git a/Packages/SprachmittlerKit/Package.swift b/Packages/SprachmittlerKit/Package.swift index 095c0c7..c5d8849 100644 --- a/Packages/SprachmittlerKit/Package.swift +++ b/Packages/SprachmittlerKit/Package.swift @@ -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", diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationManifest.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationManifest.swift new file mode 100644 index 0000000..70334cf --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationManifest.swift @@ -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() + 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 + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationMetrics.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationMetrics.swift new file mode 100644 index 0000000..a14db86 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationMetrics.swift @@ -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 + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationReportWriter.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationReportWriter.swift new file mode 100644 index 0000000..c0beb36 --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationReportWriter.swift @@ -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 + } +} diff --git a/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationRunner.swift b/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationRunner.swift new file mode 100644 index 0000000..4f9372a --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationRunner.swift @@ -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: "_") + } +} diff --git a/Packages/SprachmittlerKit/Sources/sprachmittler-cli/DetectCommand.swift b/Packages/SprachmittlerKit/Sources/sprachmittler-cli/DetectCommand.swift new file mode 100644 index 0000000..1688e3e --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/sprachmittler-cli/DetectCommand.swift @@ -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))") + } + } +} diff --git a/Packages/SprachmittlerKit/Sources/sprachmittler-cli/EvalCommand.swift b/Packages/SprachmittlerKit/Sources/sprachmittler-cli/EvalCommand.swift new file mode 100644 index 0000000..c106cec --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/sprachmittler-cli/EvalCommand.swift @@ -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" + } +} diff --git a/Packages/SprachmittlerKit/Sources/sprachmittler-cli/LanguagesCommand.swift b/Packages/SprachmittlerKit/Sources/sprachmittler-cli/LanguagesCommand.swift new file mode 100644 index 0000000..b799c0a --- /dev/null +++ b/Packages/SprachmittlerKit/Sources/sprachmittler-cli/LanguagesCommand.swift @@ -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)") + } + } +} diff --git a/Packages/SprachmittlerKit/Sources/sprachmittler-cli/SprachmittlerCLI.swift b/Packages/SprachmittlerKit/Sources/sprachmittler-cli/SprachmittlerCLI.swift index 5f6218c..cbf9100 100644 --- a/Packages/SprachmittlerKit/Sources/sprachmittler-cli/SprachmittlerCLI.swift +++ b/Packages/SprachmittlerKit/Sources/sprachmittler-cli/SprachmittlerCLI.swift @@ -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, ] ) } diff --git a/Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/SprachmittlerEvalTests.swift b/Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/SprachmittlerEvalTests.swift new file mode 100644 index 0000000..56133e0 --- /dev/null +++ b/Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/SprachmittlerEvalTests.swift @@ -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) + } +} diff --git a/README.md b/README.md index 39c08bb..c6dc8ae 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5c1176e..69aa9d8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index c38ed66..495f0f4 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -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. diff --git a/docs/MODEL_EVALUATION.md b/docs/MODEL_EVALUATION.md index 3bee550..c66edf3 100644 --- a/docs/MODEL_EVALUATION.md +++ b/docs/MODEL_EVALUATION.md @@ -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. | diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index 099890b..2a61c4d 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -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. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 4677115..3337f7a 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -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,14 @@ 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. diff --git a/docs/TESTING.md b/docs/TESTING.md index 724df19..6d03c03 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -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 diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md new file mode 100644 index 0000000..8712eec --- /dev/null +++ b/docs/USER_GUIDE.md @@ -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 . +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. diff --git a/scripts/privacy-check.sh b/scripts/privacy-check.sh index 15f3922..bbe1c0d 100755 --- a/scripts/privacy-check.sh +++ b/scripts/privacy-check.sh @@ -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 '[^<]+' "$ENT" 2>/dev/null | sed -E 's###g' | sort) [[ "$actual" == "$expected" ]] || { report "SP-10: entitlements differ from the allowed set"; diff <(echo "$expected") <(echo "$actual"); } rg -U -q 'com.apple.security.app-sandbox\s*' "$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 'LSUIElement' 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 'LSUIElement' "$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" diff --git a/scripts/privacy-self-test.sh b/scripts/privacy-self-test.sh new file mode 100755 index 0000000..6a8e08f --- /dev/null +++ b/scripts/privacy-self-test.sh @@ -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' + + +LSUIElement +EOF + cat > "$root/App/Sprachmittler.entitlements" <<'EOF' + + +com.apple.security.app-sandbox +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('LSUIElement','LSUIElementNSAppTransportSecurityNSAllowsArbitraryLoads') +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('com.apple.security.app-sandbox','com.apple.security.app-sandboxcom.apple.security.network.client') +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" diff --git a/scripts/release.sh b/scripts/release.sh new file mode 100755 index 0000000..3e1a2ef --- /dev/null +++ b/scripts/release.sh @@ -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" diff --git a/scripts/verify.sh b/scripts/verify.sh index bc90f6f..841758c 100755 --- a/scripts/verify.sh +++ b/scripts/verify.sh @@ -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"