From 30f978b40a6266b3213bf60bfc398def6c8e791a Mon Sep 17 00:00:00 2001 From: Weishaupt Date: Sat, 14 Nov 2026 02:39:27 +0000 Subject: [PATCH] Merge Hey Claude's actions into Hey Dumby Hey Dumby is now the one app: the wake-word listener (with the pre-roll + double-check trick from Hey Claude, so a stray word doesn't trigger it) branches into three things depending on what it hears. - The full phrase ("hey dummy take a note" by default) drops straight into dictation, unchanged from before. - The bare phrase alone ("hey dummy"/"hey dumby"/"okay dummy") beeps and listens for one command: open an app, call, text, directions, or falls through to the Claude app. This is Hey Claude's CommandRouter/AppMatcher/ContactMatcher/Comms, ported over basically unchanged (package renamed, Hey Claude branding swapped for Hey Dumby). - Driving mode (DrivingMode.kt, new): speaks command results out loud with TextToSpeech instead of only showing them. Can be switched on by voice ("hey dummy, driving mode on") or, if Bluetooth permission is granted, auto-arms when the phone connects to something that reports itself as an audio/video Bluetooth device (the closest thing Android has to "this is a car"), and disarms on disconnect. Kept Hey Dumby's bundled-in-the-apk speech model (ModelFiles) over Hey Claude's download-on-first-run one, so the no-network claim on the landing page stays true and the INTERNET permission goes away. Still TODO, not done in this pass: - Settings screen doesn't expose the new toggles yet (driving mode, auto-arm, call/text direct, aliases, strict wake). They all have working Prefs getters/setters, just no UI. Quick Settings tile and the Claude-app fallback aren't wired into a Settings toggle either, though they work. - Not build-tested. No Android SDK in this workspace to compile against; needs a real build on Elessar before it installs. --- app/build.gradle.kts | 37 +- app/src/main/AndroidManifest.xml | 70 ++++ .../java/space/bloggin/scribe/AppMatcher.kt | 90 +++++ .../space/bloggin/scribe/CommandRouter.kt | 222 +++++++++++ .../main/java/space/bloggin/scribe/Comms.kt | 61 +++ .../space/bloggin/scribe/ContactMatcher.kt | 149 ++++++++ .../java/space/bloggin/scribe/DrivingMode.kt | 104 +++++ .../java/space/bloggin/scribe/EventLog.kt | 18 + .../space/bloggin/scribe/LaunchActivity.kt | 77 ++++ .../space/bloggin/scribe/ListenService.kt | 359 ++++++++++++++---- .../main/java/space/bloggin/scribe/Sounds.kt | 49 +++ .../main/java/space/bloggin/scribe/Store.kt | 48 +++ .../space/bloggin/scribe/ToggleTileService.kt | 47 +++ app/src/main/res/drawable/ic_mic.xml | 10 + app/src/main/res/values/styles.xml | 6 + build.gradle.kts | 4 +- 16 files changed, 1268 insertions(+), 83 deletions(-) create mode 100644 app/src/main/java/space/bloggin/scribe/AppMatcher.kt create mode 100644 app/src/main/java/space/bloggin/scribe/CommandRouter.kt create mode 100644 app/src/main/java/space/bloggin/scribe/Comms.kt create mode 100644 app/src/main/java/space/bloggin/scribe/ContactMatcher.kt create mode 100644 app/src/main/java/space/bloggin/scribe/DrivingMode.kt create mode 100644 app/src/main/java/space/bloggin/scribe/EventLog.kt create mode 100644 app/src/main/java/space/bloggin/scribe/LaunchActivity.kt create mode 100644 app/src/main/java/space/bloggin/scribe/Sounds.kt create mode 100644 app/src/main/java/space/bloggin/scribe/ToggleTileService.kt create mode 100755 app/src/main/res/drawable/ic_mic.xml diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 0b0d6cd..37310c1 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -4,17 +4,36 @@ plugins { } android { namespace = "space.bloggin.scribe" - compileSdk = 34 + compileSdk = 35 defaultConfig { applicationId = "space.bloggin.scribe" - minSdk = 26 - targetSdk = 34 - versionCode = 2 - versionName = "0.2.0" - ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a") } + minSdk = 29 + targetSdk = 35 + versionCode = 3 + versionName = "0.3.0" + // Built for a Galaxy Z Fold8. arm64 only, same as Hey Claude was. + ndk { abiFilters += listOf("arm64-v8a") } } + + // The signing key stays on Elessar and is not in this repo. Without it, release + // builds come out unsigned and need signing before they'll install. + val keyFile = file("dumby.jks") + if (keyFile.exists()) { + signingConfigs { + create("release") { + storeFile = keyFile + storePassword = "dumby" + keyAlias = "dumby" + keyPassword = "dumby" + } + } + } + buildTypes { - release { isMinifyEnabled = false } + release { + isMinifyEnabled = false + if (keyFile.exists()) signingConfig = signingConfigs.getByName("release") + } } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 @@ -25,7 +44,7 @@ android { packaging { jniLibs { useLegacyPackaging = true } } } dependencies { - implementation("net.java.dev.jna:jna:5.13.0@aar") - implementation("com.alphacephei:vosk-android:0.3.47") + implementation("net.java.dev.jna:jna:5.17.0@aar") + implementation("com.alphacephei:vosk-android:0.3.75@aar") implementation("androidx.core:core:1.13.1") } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index e1fb5f0..a9d432b 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -6,25 +6,95 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/space/bloggin/scribe/AppMatcher.kt b/app/src/main/java/space/bloggin/scribe/AppMatcher.kt new file mode 100644 index 0000000..abd289b --- /dev/null +++ b/app/src/main/java/space/bloggin/scribe/AppMatcher.kt @@ -0,0 +1,90 @@ +package space.bloggin.scribe + +import android.content.Context +import android.content.Intent +import kotlin.math.max +import kotlin.math.min + +/** Finds an installed app from loosely spoken words ("company cam" -> CompanyCam). */ +object AppMatcher { + + data class AppEntry(val label: String, val pkg: String, val activity: String) { + val compact = compact(label) + } + + fun compact(s: String) = s.lowercase().replace(Regex("[^a-z0-9]"), "") + + fun installed(ctx: Context): List { + val pm = ctx.packageManager + val main = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER) + return pm.queryIntentActivities(main, 0) + .filter { it.activityInfo.packageName != ctx.packageName } + .map { + AppEntry( + it.loadLabel(pm).toString(), + it.activityInfo.packageName, + it.activityInfo.name + ) + } + } + + fun launchIntent(e: AppEntry): Intent = + Intent(Intent.ACTION_MAIN) + .addCategory(Intent.CATEGORY_LAUNCHER) + .setClassName(e.pkg, e.activity) + + fun find(ctx: Context, spoken: String): AppEntry? { + var target = compact(spoken) + if (target.isEmpty()) return null + + val apps = installed(ctx) + if (apps.isEmpty()) return null + + // An app whose name you said exactly always wins + apps.firstOrNull { it.compact == target }?.let { return it } + + // Then nicknames: "terminal = Termux" + for ((said, app) in Prefs.aliases(ctx)) { + if (compact(said) == target) { + target = compact(app) + break + } + } + apps.firstOrNull { it.compact == target }?.let { return it } + + var best: AppEntry? = null + var bestScore = 0.0 + for (a in apps) { + val s = score(target, a.compact) + if (s > bestScore) { + bestScore = s + best = a + } + } + return if (bestScore >= 0.8) best else null + } + + private fun score(said: String, label: String): Double { + if (label.isEmpty()) return 0.0 + if (label.startsWith(said) && said.length >= 3) return 0.9 - (label.length - said.length) * 0.005 + if (said.startsWith(label) && label.length >= 4) return 0.85 + if (label.contains(said) && said.length >= 4) return 0.8 + if (said.contains(label) && label.length >= 4) return 0.78 + val d = levenshtein(said, label) + return 1.0 - d.toDouble() / max(said.length, label.length) + } + + private fun levenshtein(a: String, b: String): Int { + 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 prev[b.length] + } +} diff --git a/app/src/main/java/space/bloggin/scribe/CommandRouter.kt b/app/src/main/java/space/bloggin/scribe/CommandRouter.kt new file mode 100644 index 0000000..c5adb7d --- /dev/null +++ b/app/src/main/java/space/bloggin/scribe/CommandRouter.kt @@ -0,0 +1,222 @@ +package space.bloggin.scribe + +import android.content.Context +import android.content.Intent +import android.net.Uri + +/** Turns what you said into an action. Everything here is plain pattern matching on the phone. */ +object CommandRouter { + + const val CLAUDE_PKG = "com.anthropic.claude" + private const val MAPS_PKG = "com.google.android.apps.maps" + + /** + * What happened. If [followUp] is set, the listener beeps again and passes the + * next thing you say to it (used for "text greg" -> "what's the message?"). + */ + class Outcome(val description: String, val followUp: ((Context, String) -> String)? = null) + + private val WAKE_PREFIX = Regex("^(?:(?:hey|hay|okay|ok)\\s+(?:claude|cloud|clyde|clod)\\s*)+") + private val POLITE = Regex("^(?:please|can you|could you|would you|will you)\\s+") + + private val DIRECTIONS = Regex( + "^(?:give me |get me |show me |i need |i want )?" + + "(?:directions?|start navigation|navigate|navigation|take me|drive me|drive|route me|route|head)" + + "(?:\\s+(?:to|for|over to|back to))?\\s+(.+)$" + ) + private val HOW_GET = Regex("^how (?:do|can) i get to\\s+(.+)$") + private val MAP_SEARCH = Regex("^(?:find|show me|search for|where is|where's|look up)\\s+(.+?)\\s+(?:near me|nearby|close by|on the map|on maps)$") + private val NEAREST = Regex("^(?:find |show me )?(?:the )?(?:nearest|closest)\\s+(.+)$") + private val OPEN = Regex("^(?:open|open up|launch|start|pull up|bring up)\\s+(?:the\\s+|my\\s+)?(.+?)(?:\\s+app)?$") + private val CALL = Regex("^(?:call|called|calling|cole|coal|kohl|dial|phone|ring|give)\\s+(.+?)(?:(?:'s|s)?\\s+(?:on\\s+|at\\s+)?(?:his|her|their)?\\s*(mobile|cell|work|office|home)(?:\\s+(?:phone|number))?)?(?:\\s+a call)?$") + private val TEXT = Regex("^(?:send a text message to|send a text to|send a message to|send text to|shoot a text to|text message|message|texting|texts|text|tex|techs)\\s+(.+)$") + private val BODY_LEAD = Regex("^(?:saying|that says|that|and say|and tell (?:him|her|them)|to say|say)\\s+") + private val ASK_CLAUDE = Regex("^(?:ask claude|ask cloud|claude|cloud|ask)\\s+(.+)$") + private val COMMAND_START = Regex("^(?:please |can you |could you )?(?:call|called|calling|cole|coal|kohl|dial|phone|ring|give|text|texting|texts|tex|techs|message|send|shoot|open|launch|start|run|pull up|bring up|directions?|navigate|navigation|take me|drive|route|head|how do i get|how can i get|find|show me|search for|where is|where's|look up|nearest|closest)\\b") + private val JUST_CLAUDE = Regex("^(?:open claude|open cloud|claude|cloud|clyde)$") + + // Words that show up as leftovers of "hey claude" when the recognizer catches part of it + private val WAKE_NOISE = setOf( + "hey", "hay", "he", "hi", "a", "uh", "um", "eh", "ah", "okay", "ok", "the", "and", "i", + "claude", "cloud", "clouds", "claude's", "cloud's", "clyde", "clod", "clawed", "claw", "loud", "ude", "lord", "plod" + ) + private val WAKE_WORDS = setOf("claude", "cloud", "clouds", "claude's", "cloud's", "clyde", "clod", "clawed") + + fun clean(raw: String): String { + var t = raw.lowercase().trim() + t = WAKE_PREFIX.replace(t, "").trim() + + // If the wake word shows up mid-text with a command after it ("so anyway hey claude + // open termux"), keep only what comes after the last wake word. + run { + val w = t.split(Regex("\\s+")).filter { it.isNotEmpty() } + val last = w.indexOfLast { it in WAKE_WORDS } + if (last >= 0 && last < w.size - 1) { + val rest = w.drop(last + 1).joinToString(" ") + if (COMMAND_START.containsMatchIn(rest)) t = rest + } + } + + // If a command word appears within the first few words and everything before it is + // wake word noise ("a claude open termux", "he clouds call christina"), drop the noise. + val words = t.split(Regex("\\s+")).filter { it.isNotEmpty() } + for (i in 1..minOf(5, words.size - 1)) { + val before = words.take(i) + val rest = words.drop(i).joinToString(" ") + if (before.all { it in WAKE_NOISE } && COMMAND_START.containsMatchIn(rest)) { + t = rest + break + } + } + + // A bare leftover with nothing after it ("a claude", "hey cloud") means you said nothing. + val left = t.split(Regex("\\s+")).filter { it.isNotEmpty() } + if (left.isNotEmpty() && left.all { it in WAKE_NOISE } && left.any { it in WAKE_WORDS }) t = "" + + t = POLITE.replace(t, "").trim() + return t + } + + /** [voice] is false when typed into the test box, so there's no spoken follow-up. */ + fun handle(ctx: Context, raw: String, voice: Boolean = true): Outcome { + val text = clean(raw) + + if (text.isEmpty() || JUST_CLAUDE.matches(text)) { + return Outcome(openClaude(ctx, null)) + } + + NEAREST.matchEntire(text)?.let { + return Outcome(mapSearch(ctx, "nearest " + it.groupValues[1])) + } + MAP_SEARCH.matchEntire(text)?.let { + return Outcome(mapSearch(ctx, it.groupValues[1] + " near me")) + } + HOW_GET.matchEntire(text)?.let { + return Outcome(navigate(ctx, it.groupValues[1])) + } + DIRECTIONS.matchEntire(text)?.let { + val dest = it.groupValues[1].trim() + if (dest.isNotEmpty()) return Outcome(navigate(ctx, dest)) + } + TEXT.matchEntire(text)?.let { + return text(ctx, it.groupValues[1], voice) + } + CALL.matchEntire(text)?.let { + return Outcome(call(ctx, it.groupValues[1].trim(), it.groupValues[2].ifEmpty { null })) + } + OPEN.matchEntire(text)?.let { + val name = it.groupValues[1].trim() + if (name == "claude" || name == "cloud") return Outcome(openClaude(ctx, null)) + val app = AppMatcher.find(ctx, name) + return if (app != null) { + LaunchActivity.go(ctx, AppMatcher.launchIntent(app)) + Outcome("Opened ${app.label}") + } else { + Sounds.error(ctx) + Outcome("No app matched \"$name\". You can add a nickname for it.") + } + } + ASK_CLAUDE.matchEntire(text)?.let { + return Outcome(openClaude(ctx, it.groupValues[1])) + } + + return Outcome(openClaude(ctx, text)) + } + + // ---------- calls and texts ---------- + + private fun call(ctx: Context, who: String, kind: String?): String { + ContactMatcher.spokenNumber(who)?.let { return Comms.call(ctx, it, it) } + if (!ContactMatcher.hasPermission(ctx)) { + Sounds.error(ctx) + return "Contacts permission is off, turn it on in Setup" + } + val c = ContactMatcher.find(ctx, who) + if (c == null) { + Sounds.error(ctx) + return "No contact matched \"$who\". You can add a nickname for them." + } + val num = ContactMatcher.pickNumber(c, kind, forText = false) + if (num == null) { + Sounds.error(ctx) + return "${c.name} has no phone number" + } + return Comms.call(ctx, num, c.name) + } + + private fun text(ctx: Context, rest: String, voice: Boolean): Outcome { + if (!ContactMatcher.hasPermission(ctx)) { + Sounds.error(ctx) + return Outcome("Contacts permission is off, turn it on in Setup") + } + val words = rest.trim().split(Regex("\\s+")) + val m = ContactMatcher.findPrefix(ctx, words) + if (m == null) { + Sounds.error(ctx) + return Outcome("No contact matched \"$rest\". You can add a nickname for them.") + } + val num = ContactMatcher.pickNumber(m.contact, null, forText = true) + if (num == null) { + Sounds.error(ctx) + return Outcome("${m.contact.name} has no phone number") + } + val body = BODY_LEAD.replace(words.drop(m.wordsUsed).joinToString(" "), "").trim() + if (body.isNotEmpty() || !voice) { + return Outcome(Comms.text(ctx, num, m.contact.name, body)) + } + val who = m.contact.name + return Outcome("Texting $who, say the message") { c, said -> + val msg = BODY_LEAD.replace(said.trim().lowercase(), "").trim() + if (msg.isEmpty() || msg == "cancel" || msg == "never mind" || msg == "nevermind") { + "Text to $who cancelled" + } else { + Comms.text(c, num, who, msg) + } + } + } + + // ---------- maps ---------- + + private fun navigate(ctx: Context, dest: String): String { + val nav = Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + Uri.encode(dest))) + .setPackage(MAPS_PKG) + if (nav.resolveActivity(ctx.packageManager) != null) { + LaunchActivity.go(ctx, nav) + return "Directions to \"$dest\"" + } + return mapSearch(ctx, dest) + } + + private fun mapSearch(ctx: Context, query: String): String { + val geo = Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(query))) + if (geo.resolveActivity(ctx.packageManager) == null) { + Sounds.error(ctx) + return "No maps app found" + } + LaunchActivity.go(ctx, geo) + return "Map search for \"$query\"" + } + + // ---------- Claude ---------- + + fun openClaude(ctx: Context, text: String?): String { + val pm = ctx.packageManager + if (text != null && text.isNotBlank() && Prefs.passText(ctx)) { + val share = Intent(Intent.ACTION_SEND) + .setType("text/plain") + .putExtra(Intent.EXTRA_TEXT, text) + .setPackage(CLAUDE_PKG) + if (share.resolveActivity(pm) != null) { + LaunchActivity.go(ctx, share) + return "Sent to Claude: \"$text\"" + } + } + val launch = pm.getLaunchIntentForPackage(CLAUDE_PKG) + if (launch == null) { + Sounds.error(ctx) + return "The Claude app isn't installed" + } + LaunchActivity.go(ctx, launch) + return if (text.isNullOrBlank()) "Opened Claude" else "Opened Claude (you said \"$text\")" + } +} diff --git a/app/src/main/java/space/bloggin/scribe/Comms.kt b/app/src/main/java/space/bloggin/scribe/Comms.kt new file mode 100644 index 0000000..dd92887 --- /dev/null +++ b/app/src/main/java/space/bloggin/scribe/Comms.kt @@ -0,0 +1,61 @@ +package space.bloggin.scribe + +import android.Manifest +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.telephony.SmsManager + +/** Calling and texting. */ +object Comms { + + fun call(ctx: Context, number: String, who: String): String { + val uri = Uri.fromParts("tel", number, null) + val direct = Prefs.callDirect(ctx) && + ctx.checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED + return if (direct) { + LaunchActivity.go(ctx, Intent(Intent.ACTION_CALL, uri)) + "Calling $who ($number)" + } else { + LaunchActivity.go(ctx, Intent(Intent.ACTION_DIAL, uri)) + "Dialer opened for $who ($number)" + } + } + + fun text(ctx: Context, number: String, who: String, rawBody: String): String { + val body = tidy(rawBody) + val direct = Prefs.textDirect(ctx) && body.isNotEmpty() && + ctx.checkSelfPermission(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED + if (direct) { + return try { + val sms = ctx.getSystemService(SmsManager::class.java) + val parts = sms.divideMessage(body) + if (parts.size > 1) sms.sendMultipartTextMessage(number, null, parts, null, null) + else sms.sendTextMessage(number, null, body, null, null) + "Texted $who: \"$body\"" + } catch (e: Exception) { + Sounds.error(ctx) + compose(ctx, number, body) + "Couldn't send directly (${e.message}), opened it in Messages instead" + } + } + compose(ctx, number, body) + return if (body.isEmpty()) "Opened a text to $who" else "Text to $who ready: \"$body\"" + } + + private fun compose(ctx: Context, number: String, body: String) { + val i = Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + Uri.encode(number))) + if (body.isNotEmpty()) i.putExtra("sms_body", body) + LaunchActivity.go(ctx, i) + } + + /** The recognizer gives plain lowercase words, so add a capital and fix "i". */ + private fun tidy(s: String): String { + var t = s.trim().replace(Regex("\\s+"), " ") + if (t.isEmpty()) return t + t = t.replace(Regex("\\bi\\b"), "I") + .replace(Regex("\\bi'(m|ll|ve|d)\\b")) { "I'" + it.groupValues[1] } + return t.substring(0, 1).uppercase() + t.substring(1) + } +} diff --git a/app/src/main/java/space/bloggin/scribe/ContactMatcher.kt b/app/src/main/java/space/bloggin/scribe/ContactMatcher.kt new file mode 100644 index 0000000..e0adf4e --- /dev/null +++ b/app/src/main/java/space/bloggin/scribe/ContactMatcher.kt @@ -0,0 +1,149 @@ +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 + } +} diff --git a/app/src/main/java/space/bloggin/scribe/DrivingMode.kt b/app/src/main/java/space/bloggin/scribe/DrivingMode.kt new file mode 100644 index 0000000..4fab663 --- /dev/null +++ b/app/src/main/java/space/bloggin/scribe/DrivingMode.kt @@ -0,0 +1,104 @@ +package space.bloggin.scribe + +import android.annotation.SuppressLint +import android.bluetooth.BluetoothClass +import android.bluetooth.BluetoothDevice +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.os.Build +import android.speech.tts.TextToSpeech +import java.util.Locale + +/** + * Speaks results instead of relying on the notification text, for when the phone is + * paired to the car over Bluetooth and nobody can look at the screen. + * + * There's no Android flag that means "this Bluetooth device is a car," so this guesses + * from the device's declared Bluetooth class (AUDIO_VIDEO, the class car head units and + * speakers report) the same way most "connected to car" automation on Android does. It + * is a heuristic: a regular Bluetooth speaker or headset reports the same class and will + * also arm driving mode. If that's wrong for you, turn "Auto driving mode" off in Settings + * and flip driving mode by hand with the "hey dummy driving mode on/off" command instead. + * + * Reading READ_CONTACTS is already requested for calls/texts; this adds no new permission + * beyond RECEIVE audio-connect broadcasts, which need none on API 29 to just receive the + * intent (querying bluetoothClass needs BLUETOOTH_CONNECT only on API 31+, requested in the + * manifest; if it's denied at runtime, driving mode just never auto-arms and has to be + * switched on by hand). + */ +object DrivingMode { + @Volatile + var active: Boolean = false + private set + + private var tts: TextToSpeech? = null + private var ttsReady = false + + fun init(ctx: Context) { + if (tts != null) return + tts = TextToSpeech(ctx.applicationContext) { status -> + ttsReady = status == TextToSpeech.SUCCESS + tts?.language = Locale.US + } + } + + fun shutdown() { + tts?.stop() + tts?.shutdown() + tts = null + ttsReady = false + } + + fun setActive(ctx: Context, v: Boolean, announce: Boolean = true) { + if (active == v) return + active = v + Bus.changed() + if (announce) speak(ctx, if (v) "Driving mode on" else "Driving mode off") + } + + fun speak(ctx: Context, text: String) { + if (text.isBlank()) return + init(ctx) + if (!ttsReady) return + tts?.speak(text, TextToSpeech.QUEUE_FLUSH, null, "dumby") + } + + @SuppressLint("MissingPermission") + private fun looksLikeCar(device: BluetoothDevice?): Boolean { + if (device == null) return false + return try { + device.bluetoothClass?.majorDeviceClass == BluetoothClass.Device.Major.AUDIO_VIDEO + } catch (_: SecurityException) { + // BLUETOOTH_CONNECT not granted; can't tell, so don't guess. + false + } + } + + /** Registered by ListenService while it's running. */ + class BtReceiver : BroadcastReceiver() { + override fun onReceive(ctx: Context, intent: Intent) { + if (!Prefs.autoDrivingMode(ctx)) return + val device: BluetoothDevice? = if (Build.VERSION.SDK_INT >= 33) { + intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) + } + when (intent.action) { + BluetoothDevice.ACTION_ACL_CONNECTED -> + if (looksLikeCar(device)) setActive(ctx, true) + BluetoothDevice.ACTION_ACL_DISCONNECTED -> + if (looksLikeCar(device)) setActive(ctx, false) + } + } + + companion object { + fun filter(): IntentFilter = IntentFilter().apply { + addAction(BluetoothDevice.ACTION_ACL_CONNECTED) + addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED) + } + } + } +} diff --git a/app/src/main/java/space/bloggin/scribe/EventLog.kt b/app/src/main/java/space/bloggin/scribe/EventLog.kt new file mode 100644 index 0000000..ea2100b --- /dev/null +++ b/app/src/main/java/space/bloggin/scribe/EventLog.kt @@ -0,0 +1,18 @@ +package space.bloggin.scribe + +/** + * Thin adapter so the command-handling code ported from Hey Claude (CommandRouter, Comms, + * ContactMatcher, LaunchActivity) can call EventLog.add()/setStatus() as before, while the + * actual UI state lives in Bus (which MainActivity already watches). + */ +object EventLog { + fun add(msg: String) { + Bus.state = msg + Bus.changed() + } + + fun setStatus(s: String) { + Bus.state = s + Bus.changed() + } +} diff --git a/app/src/main/java/space/bloggin/scribe/LaunchActivity.kt b/app/src/main/java/space/bloggin/scribe/LaunchActivity.kt new file mode 100644 index 0000000..bbcdb8b --- /dev/null +++ b/app/src/main/java/space/bloggin/scribe/LaunchActivity.kt @@ -0,0 +1,77 @@ +package space.bloggin.scribe + +import android.app.Activity +import android.app.KeyguardManager +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.Bundle +import android.widget.Toast + +/** + * Invisible go-between. The listening service can't open apps directly from the background, + * so it opens this, which wakes the screen, asks you to unlock if needed, opens the target + * and disappears. Also used by the Quick Settings tile to start listening. + */ +class LaunchActivity : Activity() { + + companion object { + private const val EXTRA_TARGET = "target" + const val ACTION_START_LISTENING = "space.bloggin.scribe.START_LISTENING" + + fun go(ctx: Context, target: Intent) { + val i = Intent(ctx, LaunchActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION) + .putExtra(EXTRA_TARGET, target) + try { + ctx.startActivity(i) + } catch (e: Exception) { + EventLog.add("Couldn't open: ${e.message}") + } + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setShowWhenLocked(true) + setTurnScreenOn(true) + + if (intent?.action == ACTION_START_LISTENING) { + ListenService.start(this) + finish() + return + } + + val target: Intent? = if (Build.VERSION.SDK_INT >= 33) { + intent?.getParcelableExtra(EXTRA_TARGET, Intent::class.java) + } else { + @Suppress("DEPRECATION") + intent?.getParcelableExtra(EXTRA_TARGET) + } + if (target == null) { + finish() + return + } + + val km = getSystemService(KeyguardManager::class.java) + if (km != null && km.isKeyguardLocked) { + km.requestDismissKeyguard(this, object : KeyguardManager.KeyguardDismissCallback() { + override fun onDismissSucceeded() = open(target) + override fun onDismissCancelled() = finish() + override fun onDismissError() = finish() + }) + } else { + open(target) + } + } + + private fun open(target: Intent) { + try { + startActivity(target.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } catch (e: Exception) { + Toast.makeText(this, "Hey Dumby couldn't open that", Toast.LENGTH_SHORT).show() + EventLog.add("Couldn't open: ${e.message}") + } + finish() + } +} diff --git a/app/src/main/java/space/bloggin/scribe/ListenService.kt b/app/src/main/java/space/bloggin/scribe/ListenService.kt index 582af82..6f38401 100644 --- a/app/src/main/java/space/bloggin/scribe/ListenService.kt +++ b/app/src/main/java/space/bloggin/scribe/ListenService.kt @@ -19,17 +19,46 @@ import android.media.ToneGenerator import android.os.Build import android.os.IBinder import android.os.PowerManager +import android.os.SystemClock import android.os.VibrationEffect import android.os.Vibrator import org.json.JSONObject import org.vosk.Model import org.vosk.Recognizer +import kotlin.math.max +/** + * One always-on listener for both of what used to be two apps. + * + * It waits for a wake phrase, same trick as before: a tiny Vosk recognizer limited to a + * short list of phrases, double-checked against a second full-vocabulary pass of the last + * few seconds of audio so the TV, a stray "strudel" or "poodle", doesn't set it off. + * + * What happens next depends on which wake phrase it heard: + * - The full phrase ("hey dummy take a note" by default) drops straight into dictation, + * exactly like the old Hey Dumby: segments collected, spoken punctuation handled by + * Speech.parse, saved live to Store, ended by "end note" or a few seconds of silence. + * - The bare phrase alone ("hey dummy" / "hey dumby" / "okay dummy") beeps and listens for + * one command, exactly like the old Hey Claude: CommandRouter turns it into opening an + * app, a call, a text, directions, or falls through to the Claude app. + * + * While driving mode is on (by hand, or auto-armed when the phone connects to something + * that looks like a car over Bluetooth, see DrivingMode), command results are spoken aloud + * instead of only shown in the notification. + */ class ListenService : Service() { + + enum class Mode { WAKE, NOTE, COMMAND } + companion object { const val ACTION_STOP = "space.bloggin.scribe.STOP" private const val CHANNEL = "listen" private const val NOTE_ID = 7 + private const val RATE = 16000 + + private val COMMAND_WAKE_WORDS = listOf("hey dummy", "hey dumby", "okay dummy") + private val COMMAND_WAKE_HIT = Regex("\\b(?:hey|okay) dumm?y\\b") + private val VERIFY_WORDS = setOf("dummy", "dumby", "dubby", "dummies") fun start(ctx: Context) { val i = Intent(ctx, ListenService::class.java) @@ -44,6 +73,8 @@ class ListenService : Service() { @Volatile private var stopFlag = false private var worker: Thread? = null private var wakeLock: PowerManager.WakeLock? = null + private val btReceiver = DrivingMode.BtReceiver() + private var btReceiverRegistered = false override fun onBind(intent: Intent?): IBinder? = null @@ -64,6 +95,16 @@ class ListenService : Service() { Prefs.setWanted(this, true) Bus.running = true stopFlag = false + DrivingMode.init(this) + if (!btReceiverRegistered) { + try { + registerReceiver(btReceiver, DrivingMode.BtReceiver.filter()) + btReceiverRegistered = true + } catch (_: Exception) { + // No BLUETOOTH_CONNECT at runtime, or no Bluetooth hardware. Driving mode + // just stays off until switched on by hand. + } + } if (Prefs.cpu(this)) { val pm = getSystemService(Context.POWER_SERVICE) as PowerManager wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "scribe:listen").also { it.acquire() } @@ -76,6 +117,11 @@ class ListenService : Service() { stopFlag = true try { worker?.join(1500) } catch (_: Exception) {} try { wakeLock?.let { if (it.isHeld) it.release() } } catch (_: Exception) {} + if (btReceiverRegistered) { + try { unregisterReceiver(btReceiver) } catch (_: Exception) {} + btReceiverRegistered = false + } + DrivingMode.shutdown() Bus.running = false Bus.partial = "" Bus.activeNoteId = null @@ -136,123 +182,292 @@ class ListenService : Service() { } } + private fun say(text: String) { + if (DrivingMode.active) DrivingMode.speak(this, text) + } + @SuppressLint("MissingPermission") private fun runLoop() { var model: Model? = null var wake: Recognizer? = null - var free: Recognizer? = null + var command: Recognizer? = null var rec: AudioRecord? = null try { - val phrase = Prefs.wake(this) + val notePhrase = Prefs.wake(this) val shown = Prefs.wakeShown(this) val silenceMs = Prefs.silence(this) * 1000L setState("Loading speech model (first run takes a few seconds)") model = Model(ModelFiles.ensure(this).absolutePath) - wake = Recognizer(model, 16000f, "[\"" + phrase.replace("\"", "") + "\", \"[unk]\"]") - free = Recognizer(model, 16000f) - val min = AudioRecord.getMinBufferSize(16000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) + val grammar = (listOf(notePhrase) + COMMAND_WAKE_WORDS + listOf("[unk]")) + .distinct() + .joinToString(", ") { "\"" + it.replace("\"", "") + "\"" } + wake = Recognizer(model, RATE.toFloat(), "[$grammar]") + command = Recognizer(model, RATE.toFloat()) + + val min = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) rec = AudioRecord( - MediaRecorder.AudioSource.VOICE_RECOGNITION, 16000, - AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, 32000) + MediaRecorder.AudioSource.VOICE_RECOGNITION, RATE, + AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, max(min * 2, 32000) ) if (rec.state != AudioRecord.STATE_INITIALIZED) { setState("The microphone could not be opened. Another app may be using it.") return } rec.startRecording() - val buf = ShortArray(2000) - var dictating = false + val buf = ShortArray(1600) + + var mode = Mode.WAKE var lastSpeech = 0L + var commandStartAt = 0L var lastPartial = "" var noteId: String? = null val segments = ArrayList() + val said = StringBuilder() + var candidateAt = 0L + var ignoreUntil = 0L + val verifyDelay = 400L + var dictatingMessage = false // true while taking the body of a "text X" follow-up + var pendingFollowUp: ((Context, String) -> String)? = null + + val preRoll = ArrayDeque() + val preRollChunks = 30 + + fun text(json: String, key: String): String = + try { JSONObject(json).optString(key, "").trim() } catch (_: Exception) { "" } + setState("Listening for “$shown”") fun endDictation(cancelled: Boolean) { if (cancelled) noteId?.let { Store.delete(it) } - dictating = false + mode = Mode.WAKE noteId = null segments.clear() lastPartial = "" Bus.activeNoteId = null Bus.partial = "" beep(ToneGenerator.TONE_PROP_BEEP2) - // Drop whatever the beep leaked into the microphone. - rec.read(buf, 0, buf.size) + rec.read(buf, 0, buf.size) // drop whatever the beep leaked into the mic wake.reset() - free.reset() + command.reset() + if (!cancelled) say("Note saved") setState("Listening for “$shown”") } + fun backToListening() { + mode = Mode.WAKE + dictatingMessage = false + said.setLength(0) + wake.reset() + command.reset() + ignoreUntil = SystemClock.elapsedRealtime() + 2500 + setState("Listening for “$shown”") + } + + fun runCommand(words: String) { + val follow = pendingFollowUp + if (follow != null) { + pendingFollowUp = null + val r = try { follow(this, words) } catch (e: Exception) { "Error: ${e.message}" } + setState(r) + say(r) + backToListening() + return + } + + val lower = words.trim().lowercase() + if (lower == "driving mode on" || lower == "turn on driving mode") { + DrivingMode.setActive(this, true) + backToListening() + return + } + if (lower == "driving mode off" || lower == "turn off driving mode") { + DrivingMode.setActive(this, false) + backToListening() + return + } + + val outcome = try { + CommandRouter.handle(this, words) + } catch (e: Exception) { + CommandRouter.Outcome("Error: ${e.message}") + } + setState(outcome.description) + say(outcome.description) + + if (outcome.followUp != null) { + pendingFollowUp = outcome.followUp + mode = Mode.COMMAND + dictatingMessage = true + said.setLength(0) + lastSpeech = SystemClock.elapsedRealtime() + commandStartAt = lastSpeech + beep(ToneGenerator.TONE_PROP_ACK) + setState("Say the message…") + return + } + backToListening() + } + while (!stopFlag) { val n = rec.read(buf, 0, buf.size) if (n <= 0) { Thread.sleep(20); continue } - val now = System.currentTimeMillis() - if (!dictating) { - val text = if (wake.acceptWaveForm(buf, n)) { - JSONObject(wake.result).optString("text") - } else JSONObject(wake.partialResult).optString("partial") - if (text.contains(phrase)) { - wake.reset() - free.reset() - dictating = true - lastSpeech = now - lastPartial = "" - Bus.partial = "" - beep(ToneGenerator.TONE_PROP_ACK) - rec.read(buf, 0, buf.size) - lastSpeech = System.currentTimeMillis() - setState("Taking a note. Say “end note” when done") + val now = SystemClock.elapsedRealtime() + if (now < ignoreUntil) continue + + when (mode) { + Mode.WAKE -> { + preRoll.addLast(buf.copyOf(n)) + while (preRoll.size > preRollChunks) preRoll.removeFirst() + + if (candidateAt > 0) { + if (now - candidateAt >= verifyDelay) { + candidateAt = 0 + command.reset() + said.setLength(0) + for (chunk in preRoll) { + if (command.acceptWaveForm(chunk, chunk.size)) { + val t = text(command.result, "text") + if (t.isNotEmpty()) { if (said.isNotEmpty()) said.append(' '); said.append(t) } + } + } + val check = (said.toString() + " " + text(command.partialResult, "partial")).trim().lowercase() + val ok = check.split(Regex("\\s+")).any { it in VERIFY_WORDS } + command.reset() + said.setLength(0) + wake.reset() + if (ok) { + mode = Mode.COMMAND + dictatingMessage = false + lastSpeech = now + commandStartAt = now + preRoll.clear() + beep(ToneGenerator.TONE_PROP_ACK) + rec.read(buf, 0, buf.size) + setState("Go ahead…") + } + } + continue + } + + val finished = wake.acceptWaveForm(buf, n) + val heardFinal = if (finished) text(wake.result, "text") else "" + val heardPartial = if (!finished) text(wake.partialResult, "partial") else "" + val heard = if (finished) heardFinal else heardPartial + + // Full phrase heard in one shot, old behaviour, no extra listening needed. + if (heard.isNotEmpty() && (heard == notePhrase || heard.contains(notePhrase))) { + wake.reset() + command.reset() + mode = Mode.NOTE + lastSpeech = now + lastPartial = "" + Bus.partial = "" + beep(ToneGenerator.TONE_PROP_ACK) + rec.read(buf, 0, buf.size) + lastSpeech = SystemClock.elapsedRealtime() + setState("Taking a note. Say “end note” when done") + continue + } + // Bare "hey dummy" with no "take a note" after it: candidate for a command, + // double-checked before it actually wakes up. + if (finished && COMMAND_WAKE_HIT.containsMatchIn(heardFinal) && !heardFinal.contains(notePhrase)) { + candidateAt = now + wake.reset() + } else if (!finished && !Prefs.strictWake(this) && COMMAND_WAKE_HIT.containsMatchIn(heardPartial)) { + candidateAt = now + } } - continue - } - var finalText: String? = null - if (free.acceptWaveForm(buf, n)) { - finalText = JSONObject(free.result).optString("text") - } else { - val p = JSONObject(free.partialResult).optString("partial") - if (p != lastPartial) { - lastPartial = p - if (p.isNotEmpty()) lastSpeech = now - Bus.partial = p - Bus.changed() - } - } - if (finalText != null) { - lastPartial = "" - Bus.partial = "" - if (finalText.isNotBlank()) { - lastSpeech = now - val p = Speech.parse(finalText) - if (p.cancel) { endDictation(true); continue } - if (p.scratch) { - val id = noteId - if (id != null && segments.isNotEmpty()) { - val last = segments.removeAt(segments.size - 1) - val cur = Store.get(id)?.text ?: "" - val idx = cur.lastIndexOf(last) - if (idx >= 0) Store.setText(id, cur.substring(0, idx).trimEnd(' ')) + + Mode.NOTE -> { + var finalText: String? = null + if (command.acceptWaveForm(buf, n)) { + finalText = text(command.result, "text") + } else { + val p = text(command.partialResult, "partial") + if (p != lastPartial) { + lastPartial = p + if (p.isNotEmpty()) lastSpeech = now + Bus.partial = p + Bus.changed() } } - if (p.text.isNotEmpty()) { - if (noteId == null) { - val note = Store.create() - noteId = note.id - Bus.activeNoteId = note.id + if (finalText != null) { + lastPartial = "" + Bus.partial = "" + if (finalText.isNotBlank()) { + lastSpeech = now + val p = Speech.parse(finalText) + if (p.cancel) { endDictation(true); continue } + if (p.scratch) { + val id = noteId + if (id != null && segments.isNotEmpty()) { + val last = segments.removeAt(segments.size - 1) + val cur = Store.get(id)?.text ?: "" + val idx = cur.lastIndexOf(last) + if (idx >= 0) Store.setText(id, cur.substring(0, idx).trimEnd(' ')) + } + } + if (p.text.isNotEmpty()) { + if (noteId == null) { + val note = Store.create() + noteId = note.id + Bus.activeNoteId = note.id + } + val id = noteId!! + val cur = Store.get(id)?.text ?: "" + val joined = Speech.join(cur, p.text) + segments.add(joined.substring(cur.length).trimStart(' ')) + Store.setText(id, joined) + } + Bus.changed() + if (p.end) { endDictation(false); continue } } - val id = noteId!! - val cur = Store.get(id)?.text ?: "" - val joined = Speech.join(cur, p.text) - segments.add(joined.substring(cur.length).trimStart(' ')) - Store.setText(id, joined) + if (noteId == null) Bus.changed() + } + if (now - lastSpeech > silenceMs) endDictation(false) + } + + Mode.COMMAND -> { + val gap = if (dictatingMessage) 2000 else 1200 + val silenceLimit = if (dictatingMessage) 6000 else 3500 + val maxTime = if (dictatingMessage) 25000 else 12000 + val elapsed = now - commandStartAt + + if (command.acceptWaveForm(buf, n)) { + val t = text(command.result, "text") + if (t.isNotEmpty()) { + if (said.isNotEmpty()) said.append(' ') + said.append(t) + lastSpeech = now + } + } else if (text(command.partialResult, "partial").isNotEmpty()) { + lastSpeech = now + } + + val saidNow = said.toString().trim() + val partialNow = text(command.partialResult, "partial").trim() + var done = false + if (saidNow.isEmpty() && partialNow.isEmpty() && now - lastSpeech > silenceLimit) { + done = true + } else if ((saidNow.isNotEmpty() || partialNow.isNotEmpty()) && now - lastSpeech > gap) { + done = true + } else if (elapsed > maxTime) { + val t = text(command.finalResult, "text") + if (t.isNotEmpty()) { if (said.isNotEmpty()) said.append(' '); said.append(t) } + done = true + } + + if (done) { + val words = said.toString().trim() + said.setLength(0) + command.reset() + wake.reset() + beep(ToneGenerator.TONE_PROP_PROMPT) + runCommand(words) } - Bus.changed() - if (p.end) { endDictation(false); continue } } - if (noteId == null) Bus.changed() } - if (now - lastSpeech > silenceMs) endDictation(false) } } catch (t: Throwable) { setState("Stopped: " + (t.message ?: t.javaClass.simpleName)) @@ -260,7 +475,7 @@ class ListenService : Service() { try { rec?.stop() } catch (_: Exception) {} try { rec?.release() } catch (_: Exception) {} try { wake?.close() } catch (_: Exception) {} - try { free?.close() } catch (_: Exception) {} + try { command?.close() } catch (_: Exception) {} try { model?.close() } catch (_: Exception) {} } } diff --git a/app/src/main/java/space/bloggin/scribe/Sounds.kt b/app/src/main/java/space/bloggin/scribe/Sounds.kt new file mode 100644 index 0000000..28e4ea1 --- /dev/null +++ b/app/src/main/java/space/bloggin/scribe/Sounds.kt @@ -0,0 +1,49 @@ +package space.bloggin.scribe + +import android.content.Context +import android.media.AudioManager +import android.media.ToneGenerator +import android.os.Handler +import android.os.Looper +import android.os.VibrationEffect +import android.os.Vibrator +import android.os.VibratorManager + +object Sounds { + private val main = Handler(Looper.getMainLooper()) + + private fun tone(type: Int, ms: Int) { + try { + val tg = ToneGenerator(AudioManager.STREAM_NOTIFICATION, 85) + tg.startTone(type, ms) + main.postDelayed({ tg.release() }, ms + 300L) + } catch (_: Exception) { + } + } + + private fun buzz(ctx: Context, ms: Long) { + try { + val v = (ctx.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as? VibratorManager)?.defaultVibrator + ?: @Suppress("DEPRECATION") (ctx.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator) + v.vibrate(VibrationEffect.createOneShot(ms, VibrationEffect.DEFAULT_AMPLITUDE)) + } catch (_: Exception) { + } + } + + /** "I'm listening" */ + fun wake(ctx: Context) { + if (Prefs.beep(ctx)) tone(ToneGenerator.TONE_PROP_BEEP, 140) + buzz(ctx, 40) + } + + /** Got it */ + fun done(ctx: Context) { + if (Prefs.beep(ctx)) tone(ToneGenerator.TONE_PROP_ACK, 120) + } + + /** Didn't work */ + fun error(ctx: Context) { + if (Prefs.beep(ctx)) tone(ToneGenerator.TONE_PROP_NACK, 250) + buzz(ctx, 120) + } +} diff --git a/app/src/main/java/space/bloggin/scribe/Store.kt b/app/src/main/java/space/bloggin/scribe/Store.kt index 74ec973..cf32d6c 100644 --- a/app/src/main/java/space/bloggin/scribe/Store.kt +++ b/app/src/main/java/space/bloggin/scribe/Store.kt @@ -93,6 +93,54 @@ object Prefs { fun setCpu(ctx: Context, v: Boolean) = sp(ctx).edit().putBoolean("cpu", v).apply() fun wanted(ctx: Context) = sp(ctx).getBoolean("wanted", false) fun setWanted(ctx: Context, v: Boolean) = sp(ctx).edit().putBoolean("wanted", v).apply() + + // --- ported from Hey Claude, now covering the "hey dummy" (no "take a note") action path --- + + /** Only trigger on a finished wake phrase, not a partial guess. Fewer false triggers, a bit slower. */ + fun strictWake(ctx: Context) = sp(ctx).getBoolean("strictWake", false) + fun setStrictWake(ctx: Context, v: Boolean) = sp(ctx).edit().putBoolean("strictWake", v).apply() + + /** Hand the spoken words to Claude (as shared text) instead of just opening the app. */ + fun passText(ctx: Context) = sp(ctx).getBoolean("passTextV2", false) + fun setPassText(ctx: Context, v: Boolean) = sp(ctx).edit().putBoolean("passTextV2", v).apply() + + /** Place calls immediately instead of showing the dialer first. */ + fun callDirect(ctx: Context) = sp(ctx).getBoolean("callDirect", false) + fun setCallDirect(ctx: Context, v: Boolean) = sp(ctx).edit().putBoolean("callDirect", v).apply() + + /** Send texts immediately instead of opening them in Messages first. */ + fun textDirect(ctx: Context) = sp(ctx).getBoolean("textDirect", false) + fun setTextDirect(ctx: Context, v: Boolean) = sp(ctx).edit().putBoolean("textDirect", v).apply() + + /** Speak results out loud instead of (or in addition to) showing them. Auto-armed on car Bluetooth. */ + fun drivingMode(ctx: Context) = sp(ctx).getBoolean("drivingMode", false) + fun setDrivingMode(ctx: Context, v: Boolean) = sp(ctx).edit().putBoolean("drivingMode", v).apply() + fun autoDrivingMode(ctx: Context) = sp(ctx).getBoolean("autoDrivingMode", true) + fun setAutoDrivingMode(ctx: Context, v: Boolean) = sp(ctx).edit().putBoolean("autoDrivingMode", v).apply() + + /** Raw alias text, one per line: "what you say = app or contact name". */ + fun aliasText(ctx: Context): String = sp(ctx).getString("aliases", DEFAULT_ALIASES) ?: "" + fun setAliasText(ctx: Context, v: String) = sp(ctx).edit().putString("aliases", v).apply() + + fun aliases(ctx: Context): List> = + aliasText(ctx).lines() + .map { it.trim() } + .filter { it.isNotEmpty() && !it.startsWith("#") && it.contains("=") } + .map { + val i = it.indexOf('=') + it.substring(0, i).trim() to it.substring(i + 1).trim() + } + .filter { it.first.isNotEmpty() && it.second.isNotEmpty() } + + private val DEFAULT_ALIASES = """ + # what you say = app or contact name (one per line) + terminal = Termux + term ux = Termux + company cam = CompanyCam + irc = wIRC + w irc = wIRC + maps = Maps + """.trimIndent() } object Bus { diff --git a/app/src/main/java/space/bloggin/scribe/ToggleTileService.kt b/app/src/main/java/space/bloggin/scribe/ToggleTileService.kt new file mode 100644 index 0000000..bca0357 --- /dev/null +++ b/app/src/main/java/space/bloggin/scribe/ToggleTileService.kt @@ -0,0 +1,47 @@ +package space.bloggin.scribe + +import android.app.PendingIntent +import android.content.Intent +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.service.quicksettings.Tile +import android.service.quicksettings.TileService + +/** Quick Settings tile to turn listening on and off. */ +class ToggleTileService : TileService() { + + override fun onStartListening() { + super.onStartListening() + refresh() + } + + override fun onClick() { + super.onClick() + if (ListenService.running) { + ListenService.stop(this) + Handler(Looper.getMainLooper()).postDelayed({ refresh() }, 600) + } else { + // Starting the microphone has to come from something on screen, + // so this goes through the invisible LaunchActivity. + val i = Intent(this, LaunchActivity::class.java) + .setAction(LaunchActivity.ACTION_START_LISTENING) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + if (Build.VERSION.SDK_INT >= 34) { + val pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_IMMUTABLE) + startActivityAndCollapse(pi) + } else { + @Suppress("DEPRECATION") + startActivityAndCollapse(i) + } + } + } + + private fun refresh() { + val t = qsTile ?: return + t.state = if (ListenService.running) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE + t.label = "Hey Dumby" + if (Build.VERSION.SDK_INT >= 29) t.subtitle = if (ListenService.running) "Listening" else "Off" + t.updateTile() + } +} diff --git a/app/src/main/res/drawable/ic_mic.xml b/app/src/main/res/drawable/ic_mic.xml new file mode 100755 index 0000000..979691a --- /dev/null +++ b/app/src/main/res/drawable/ic_mic.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml index 9b419da..9c5aca4 100644 --- a/app/src/main/res/values/styles.xml +++ b/app/src/main/res/values/styles.xml @@ -6,4 +6,10 @@ @color/paper false + + + diff --git a/build.gradle.kts b/build.gradle.kts index 017d909..7e55139 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,4 +1,4 @@ plugins { - id("com.android.application") version "8.5.2" apply false - id("org.jetbrains.kotlin.android") version "1.9.24" apply false + id("com.android.application") version "8.12.3" apply false + id("org.jetbrains.kotlin.android") version "2.1.21" apply false }