feat(m7-m8): evaluation harness, privacy self-test, localisation and release

M7: corpus manifest loader/validation, chrF/BLEU/token/numeric metrics, raw-output and report.md/report.json writer, and sprachmittler-cli languages/detect/eval. A synthetic 4-segment run with the 7B validated the harness; the private-corpus and 1.8B evaluation and the default-model ADR remain open.

M8: privacy-check root fixture + seeded self-test wired into make verify; English/German localisation for the app shell; end-user USER_GUIDE; release.sh (unsigned archive, Developer ID sign, notarise/staple, DMG, --dry-run); idle CPU/memory and warm 7B measurements in PERFORMANCE.

Docs: PROGRESS M7–M8, MODEL_EVALUATION results log/gate status, PERFORMANCE measurements, TESTING evaluation cases, ADR-008 status. Compatibility/VoiceOver/notarisation gates remain manual.

Verified: make verify green (format, strict lint, privacy self-test, Debug+Release signatures, 227 package tests); CLI languages/detect/eval run; release dry-run.
This commit is contained in:
schihei committed 2026-11-26 14:16:21 +01:00
1 parent a78572adc3
commit 0ab5ae78bf
26 files changed
+1799 -28

No files matched your search

@@ -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,
]
)
}