Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerEval/EvaluationManifest.swift
T
schihei 0ab5ae78bf 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.
2026-11-26 14:16:21 +01:00

197 lines
7.2 KiB
Swift

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
}
}