package space.bloggin.scribe import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.provider.ContactsContract.CommonDataKinds.Phone import kotlin.math.max import kotlin.math.min /** Finds a contact and phone number from spoken words ("greg", "greg's cell"). */ object ContactMatcher { data class Number(val number: String, val type: Int, val primary: Boolean) data class Contact(val name: String, val numbers: List) { val compact = compact(name) val first = compact(name.trim().split(Regex("\\s+")).firstOrNull() ?: "") val last = compact(name.trim().split(Regex("\\s+")).let { if (it.size > 1) it.last() else "" }) } data class Match(val contact: Contact, val score: Double, val wordsUsed: Int) private const val THRESHOLD = 0.75 fun compact(s: String) = s.lowercase().replace(Regex("[^a-z0-9]"), "") fun hasPermission(ctx: Context) = ctx.checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED fun all(ctx: Context): List { if (!hasPermission(ctx)) return emptyList() val byName = LinkedHashMap>() ctx.contentResolver.query( Phone.CONTENT_URI, arrayOf(Phone.DISPLAY_NAME, Phone.NUMBER, Phone.TYPE, Phone.IS_SUPER_PRIMARY), null, null, null )?.use { c -> while (c.moveToNext()) { val name = c.getString(0) ?: continue val num = c.getString(1) ?: continue val list = byName.getOrPut(name) { mutableListOf() } val digits = num.filter { it.isDigit() }.takeLast(10) if (list.none { it.number.filter { ch -> ch.isDigit() }.takeLast(10) == digits }) { list.add(Number(num, c.getInt(2), c.getInt(3) != 0)) } } } return byName.map { Contact(it.key, it.value) } } private fun resolveAlias(ctx: Context, spoken: String): String { val s = compact(spoken) for ((said, target) in Prefs.aliases(ctx)) { if (compact(said) == s) return target } return spoken } private fun score(said: String, c: Contact): Double { if (said.isEmpty()) return 0.0 if (c.compact == said) return 1.0 if (c.first == said) return 0.95 if (c.last.isNotEmpty() && c.last == said) return 0.85 if (said.length >= 4 && c.compact.startsWith(said)) return 0.85 val full = ratio(said, c.compact) val first = if (c.first.isNotEmpty()) ratio(said, c.first) * 0.97 else 0.0 return max(full, first) } /** Best contact for the whole phrase. */ fun find(ctx: Context, spoken: String): Contact? { val said = compact(resolveAlias(ctx, spoken)) val list = all(ctx) val best = list.maxByOrNull { score(said, it) } ?: return null return if (score(said, best) >= THRESHOLD) best else null } /** * For "text greg smith i'm running late": tries the first 1 to 4 words as the name * and returns the best match plus how many words were the name. */ fun findPrefix(ctx: Context, words: List): Match? { val list = all(ctx) if (list.isEmpty()) return null var best: Match? = null for (k in min(4, words.size) downTo 1) { val phrase = words.take(k).joinToString(" ") val said = compact(resolveAlias(ctx, phrase)) for (c in list) { val s = score(said, c) if (s >= THRESHOLD && (best == null || s > best.score + 0.01)) { best = Match(c, s, k) } } } return best } /** Pick a number. kind = "mobile", "work", "home" or null for best guess. */ fun pickNumber(c: Contact, kind: String?, forText: Boolean): String? { if (c.numbers.isEmpty()) return null val wanted = when (kind) { "mobile", "cell" -> Phone.TYPE_MOBILE "work", "office" -> Phone.TYPE_WORK "home" -> Phone.TYPE_HOME else -> null } if (wanted != null) c.numbers.firstOrNull { it.type == wanted }?.let { return it.number } if (forText) c.numbers.firstOrNull { it.type == Phone.TYPE_MOBILE }?.let { return it.number } c.numbers.firstOrNull { it.primary }?.let { return it.number } c.numbers.firstOrNull { it.type == Phone.TYPE_MOBILE }?.let { return it.number } return c.numbers.first().number } private fun ratio(a: String, b: String): Double { if (a.isEmpty() || b.isEmpty()) return 0.0 val prev = IntArray(b.length + 1) { it } val cur = IntArray(b.length + 1) for (i in 1..a.length) { cur[0] = i for (j in 1..b.length) { val cost = if (a[i - 1] == b[j - 1]) 0 else 1 cur[j] = min(min(cur[j - 1] + 1, prev[j] + 1), prev[j - 1] + cost) } System.arraycopy(cur, 0, prev, 0, cur.size) } return 1.0 - prev[b.length].toDouble() / max(a.length, b.length) } private val DIGIT_WORDS = mapOf( "zero" to '0', "oh" to '0', "o" to '0', "one" to '1', "two" to '2', "to" to '2', "too" to '2', "three" to '3', "four" to '4', "for" to '4', "five" to '5', "six" to '6', "seven" to '7', "eight" to '8', "nine" to '9' ) /** "two six zero five five five one two one two" -> "2605551212". Null if it isn't a number. */ fun spokenNumber(text: String): String? { val tokens = text.lowercase().split(Regex("[\\s-]+")).filter { it.isNotEmpty() } if (tokens.size < 3) return null val sb = StringBuilder() for (t in tokens) { when { t.all { it.isDigit() } -> sb.append(t) DIGIT_WORDS.containsKey(t) -> sb.append(DIGIT_WORDS[t]) else -> return null } } return if (sb.length >= 3) sb.toString() else null } }