22 lines
887 B
Swift
22 lines
887 B
Swift
import Foundation
|
|
|
|
/// Whisper sometimes answers a vocabulary prompt with the prompt itself when there is little speech.
|
|
public enum PromptEcho {
|
|
static func normalize(_ text: String) -> String {
|
|
String(text.lowercased().map { $0.isLetter || $0.isNumber ? $0 : " " })
|
|
.split(separator: " ")
|
|
.joined(separator: " ")
|
|
}
|
|
|
|
/// True when `text` is nothing but the first k ≥ 2 terms of the prompt.
|
|
/// A single term on its own is valid speech ("Anthropic").
|
|
public static func isEcho(_ text: String, vocabulary: [String]) -> Bool {
|
|
guard vocabulary.count >= 2 else { return false }
|
|
let normalized = normalize(text)
|
|
guard !normalized.isEmpty else { return false }
|
|
return (2...vocabulary.count).contains { k in
|
|
normalize(vocabulary.prefix(k).joined(separator: " ")) == normalized
|
|
}
|
|
}
|
|
}
|