import Foundation import NaturalLanguage /// One language hypothesis from `NLLanguageRecognizer`. public struct LanguageDetection: Sendable, Equatable { /// The dominant BCP-47 language code, e.g. `en` or `de`. public let code: String /// The recogniser confidence in `code`, from 0 to 1. public let confidence: Double /// Candidate codes ordered by confidence, including `code` first. public let alternatives: [String] /// Creates a detection value. public init(code: String, confidence: Double, alternatives: [String]) { self.code = code self.confidence = confidence self.alternatives = alternatives } } /// Source-language detection. Advisory only: it never blocks translation. public protocol LanguageDetecting: Sendable { /// Detects the dominant language of `text`, or returns nil for empty/undecidable text. func detect(_ text: String) -> LanguageDetection? } /// `NLLanguageRecognizer`-backed detection (`docs/TRANSLATION_OUTPUT.md` ยง8). public struct NaturalLanguageDetector: LanguageDetecting { /// Creates a detector. public init() {} /// Detects the dominant language. Short or mixed text usually reports low confidence. public func detect(_ text: String) -> LanguageDetection? { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return nil } let recognizer = NLLanguageRecognizer() recognizer.processString(trimmed) guard let dominant = recognizer.dominantLanguage else { return nil } let hypotheses = recognizer.languageHypotheses(withMaximum: 5) // NLLanguageRecognizer returns many near-zero hypotheses. Keep only candidates that // carry meaningful evidence, so a confident single-language text is not treated as mixed. let minimumAlternativeConfidence = 0.05 let ordered = hypotheses .filter { $0.value >= minimumAlternativeConfidence } .sorted { lhs, rhs in lhs.value == rhs.value ? lhs.key.rawValue < rhs.key.rawValue : lhs.value > rhs.value } .map(\.key.rawValue) let alternatives = ordered.isEmpty ? [dominant.rawValue] : ordered return LanguageDetection( code: dominant.rawValue, confidence: Double(hypotheses[dominant] ?? 0), alternatives: alternatives ) } }