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