Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat: implement comprehensive markdown sanitization for TTS engine output
Rishabh Bajpaia45296e5aad5
diff --git a/app/src/main/java/com/gotcha/audio/SpeechTextSanitizer.kt b/app/src/main/java/com/gotcha/audio/SpeechTextSanitizer.ktindex 903efff..0baf016 100644--- a/app/src/main/java/com/gotcha/audio/SpeechTextSanitizer.kt+++ b/app/src/main/java/com/gotcha/audio/SpeechTextSanitizer.kt@@ -1,8 +1,25 @@package com.gotcha.audio-/** Cleans up text before it's handed to a TTS engine. */+/**+ * Cleans up text before it's handed to a TTS engine.+ *+ * The on-screen display path never routes through this object — only the TTS+ * call sites in `TtsEngine.speak()`, the chat auto-read, voice-call narration,+ * and Screen Companion all funnel through here so assistant text is readable+ * aloud regardless of which surface triggered it.+ */object SpeechTextSanitizer {+ private const val MAX_ORDINAL = 12++ private val ORDINALS = arrayOf(+ "First", "Second", "Third", "Fourth", "Fifth", "Sixth",+ "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh", "Twelfth"+ )++ private fun ordinalFor(n: Int): String =+ if (n in 1..MAX_ORDINAL) "${ORDINALS[n - 1]}, " else "Next, "+/*** Strip emoji before speaking — TTS engines vocalize them (e.g. reading out a* skin-tone modifier or Unicode name) rather than skipping them silently.@@ -14,7 +31,103 @@ object SpeechTextSanitizer {fun stripEmoji(text: String): String =text.replace(EMOJI_REGEX, "").replace(Regex("[ \\t]{2,}"), " ").trim()+ /**+ * Prepare [text] for the TTS engine. The on-screen display is unaffected —+ * this only runs on the path to the speaker.+ *+ * Strips fenced code blocks, inline code, markdown inline formatting+ * (bold / italic / strikethrough), heading prefixes, and blockquote markers;+ * rewrites contiguous bullet blocks as ordinal sentences (so the engine+ * reads "first, …", "second, …" instead of "dash, …"); replaces bare URLs+ * with the literal word "link"; collapses runs of exclamation/question+ * marks and whitespace; drops the unicode ellipsis to three ASCII dots;+ * and finally strips emoji.+ *+ * Already-numbered lists (1. foo / 2. bar) are left alone — only bare+ * bullets (`-`, `*`, `+`, `•`) get rewritten.+ */+ fun sanitize(text: String): String {+ var s = text+ s = s.replace(FENCED_CODE, "")+ s = s.replace(INLINE_CODE, "$1")+ s = s.replace(BOLD_ASTERISK, "$1")+ s = s.replace(BOLD_UNDERSCORE, "$1")+ s = s.replace(ITALIC_ASTERISK, "$1")+ s = s.replace(ITALIC_UNDERSCORE, "$1")+ s = s.replace(STRIKE, "$1")+ s = s.replace(HEADING_PREFIX, "")+ s = s.replace(BLOCKQUOTE_PREFIX, "")+ s = convertBulletBlocks(s)+ s = s.replace(MARKDOWN_LINK, "$1")+ s = s.replace(MARKDOWN_IMAGE, "$1")+ s = BARE_URL.replace(s) { match -> replaceBareUrl(match.value) }+ s = s.replace(MULTI_EXCLAIM, "!")+ s = s.replace(MULTI_QUESTION, "?")+ s = s.replace(ELLIPSIS_UNICODE, "...")+ s = s.replace(WHITESPACE_RUN, " ")+ s = s.replace(EMOJI_REGEX, "")+ return s.trim()+ }++ /** Replace each contiguous bullet block with "First, … Second, … Third, …." form. */+ private fun convertBulletBlocks(text: String): String {+ val lines = text.split('\n')+ val out = StringBuilder()+ var block = mutableListOf<String>()++ fun flushBlock() {+ if (block.isEmpty()) return+ val numbered = block.mapIndexed { idx, line ->+ ordinalFor(idx + 1) + BULLET_PREFIX.replace(line, "")+ }+ out.append(numbered.joinToString(". ")).append(".\n")+ block = mutableListOf()+ }++ for (line in lines) {+ if (BULLET_PREFIX.containsMatchIn(line)) {+ block.add(line)+ } else {+ flushBlock()+ out.append(line).append('\n')+ }+ }+ flushBlock()+ return out.toString().trimEnd('\n')+ }++ /**+ * Replace a bare URL match with the literal word "link", but keep any+ * sentence-ending punctuation that immediately follows it (`link.` rather+ * than eating the period). Trailing `[.,;:!?)\]']` chars are treated as+ * outside the URL.+ */+ private fun replaceBareUrl(url: String): String {+ val trailing = url.takeLastWhile { it in TRAILING_PUNCT_CHARS }+ return "link$trailing"+ }++ private const val TRAILING_PUNCT_CHARS = ".,;:!?)]'"+private val EMOJI_REGEX = Regex("[\\x{1F000}-\\x{1FFFF}\\x{2600}-\\x{27BF}\\x{2B00}-\\x{2BFF}\\x{FE0F}\\x{FE0E}\\x{200D}]+")++ private val FENCED_CODE = Regex("```[\\s\\S]*?```")+ private val INLINE_CODE = Regex("`([^`]+)`")+ private val BOLD_ASTERISK = Regex("\\*\\*(.+?)\\*\\*")+ private val BOLD_UNDERSCORE = Regex("__(.+?)__")+ private val ITALIC_ASTERISK = Regex("(?<![\\w*])\\*(.+?)\\*(?![\\w*])")+ private val ITALIC_UNDERSCORE = Regex("(?<![\\w])_(.+?)_(?![\\w])")+ private val STRIKE = Regex("~~(.+?)~~")+ private val HEADING_PREFIX = Regex("^[ \\t]{0,3}#{1,6}[ \\t]+", RegexOption.MULTILINE)+ private val BLOCKQUOTE_PREFIX = Regex("^[ \\t]{0,3}>[ \\t]+", RegexOption.MULTILINE)+ private val BULLET_PREFIX = Regex("^[ \\t]{0,3}[-*+•][ \\t]+")+ private val MARKDOWN_LINK = Regex("\\[([^\\]]+)]\\([^)]+\\)")+ private val MARKDOWN_IMAGE = Regex("!\\[([^\\]]*)]\\([^)]+\\)")+ private val BARE_URL = Regex("\\b(?:https?|ftp)://\\S+|\\bwww\\.\\S+")+ private val MULTI_EXCLAIM = Regex("!{2,}")+ private val MULTI_QUESTION = Regex("\\?{2,}")+ private val ELLIPSIS_UNICODE = Regex("…")+ private val WHITESPACE_RUN = Regex("[ \\t\\n\\r]+")}diff --git a/app/src/main/java/com/gotcha/audio/TtsEngine.kt b/app/src/main/java/com/gotcha/audio/TtsEngine.ktindex 4269b96..d8f2953 100644--- a/app/src/main/java/com/gotcha/audio/TtsEngine.kt+++ b/app/src/main/java/com/gotcha/audio/TtsEngine.kt@@ -86,7 +86,7 @@ class TtsEngine(voice: String = "",language: Language = Language.ENGLISH): Boolean = withContext(Dispatchers.IO) {- val sanitized = SpeechTextSanitizer.stripEmoji(text)+ val sanitized = SpeechTextSanitizer.sanitize(text)if (sanitized.isBlank()) return@withContext truetry {when {diff --git a/app/src/test/java/com/gotcha/audio/SpeechTextSanitizerTest.kt b/app/src/test/java/com/gotcha/audio/SpeechTextSanitizerTest.ktindex cd1f159..ec63f55 100644--- a/app/src/test/java/com/gotcha/audio/SpeechTextSanitizerTest.kt+++ b/app/src/test/java/com/gotcha/audio/SpeechTextSanitizerTest.kt@@ -37,4 +37,193 @@ class SpeechTextSanitizerTest {fun `all-emoji input collapses to blank`() {assertEquals("", SpeechTextSanitizer.stripEmoji("😊🙌✨"))}++ // ---- sanitize() ----++ @Test+ fun `sanitize leaves plain text untouched`() {+ assertEquals("Hello world", SpeechTextSanitizer.sanitize("Hello world"))+ }++ @Test+ fun `sanitize strips bold italic and strikethrough`() {+ assertEquals(+ "bold and italic and struck",+ SpeechTextSanitizer.sanitize("**bold** and *italic* and ~~struck~~")+ )+ }++ @Test+ fun `sanitize strips underscore bold and italic`() {+ assertEquals(+ "bold and italic",+ SpeechTextSanitizer.sanitize("__bold__ and _italic_")+ )+ }++ @Test+ fun `sanitize strips heading prefixes at every depth`() {+ assertEquals("Title", SpeechTextSanitizer.sanitize("# Title"))+ assertEquals("Sub", SpeechTextSanitizer.sanitize("### Sub"))+ assertEquals("Deep", SpeechTextSanitizer.sanitize("###### Deep"))+ }++ @Test+ fun `sanitize strips blockquote markers`() {+ assertEquals("quote", SpeechTextSanitizer.sanitize("> quote"))+ }++ @Test+ fun `sanitize removes fenced code blocks`() {+ // Whitespace-run collapse reduces the gap the removed fence left behind.+ assertEquals(+ "before after",+ SpeechTextSanitizer.sanitize("before ```ls -la\npwd``` after")+ )+ }++ @Test+ fun `sanitize unwraps inline code`() {+ assertEquals("run ls now", SpeechTextSanitizer.sanitize("run `ls` now"))+ }++ @Test+ fun `sanitize replaces bare URLs with link`() {+ assertEquals(+ "see link for info",+ SpeechTextSanitizer.sanitize("see https://x.com/a for info")+ )+ assertEquals("go to link", SpeechTextSanitizer.sanitize("go to www.example.com"))+ }++ @Test+ fun `sanitize strips markdown link syntax keeping label text`() {+ assertEquals(+ "click here for details",+ SpeechTextSanitizer.sanitize("click [here](https://x.com) for details")+ )+ }++ @Test+ fun `sanitize converts a dash bullet block to ordinal sentences`() {+ assertEquals(+ "First, Buy milk. Second, Walk dog. Third, Call mom.",+ SpeechTextSanitizer.sanitize("- Buy milk\n- Walk dog\n- Call mom")+ )+ }++ @Test+ fun `sanitize converts mixed bullet characters in one block`() {+ assertEquals(+ "First, a. Second, b. Third, c.",+ SpeechTextSanitizer.sanitize("* a\n- b\n+ c")+ )+ }++ @Test+ fun `sanitize handles bullet blocks separated by blank lines independently`() {+ val input = "Intro\n- one\n- two\n\nAfter\n- three"+ val expected = "Intro First, one. Second, two. After First, three."+ assertEquals(expected, SpeechTextSanitizer.sanitize(input))+ }++ @Test+ fun `sanitize uses Next for items beyond the twelfth ordinal`() {+ val input = (1..14).joinToString("\n") { "- item $it" }+ val once = SpeechTextSanitizer.sanitize(input)+ // First twelve get ordinal words, the rest fall back to "Next".+ assertEquals(+ "First, item 1. Second, item 2. Third, item 3. Fourth, item 4. Fifth, item 5. " ++ "Sixth, item 6. Seventh, item 7. Eighth, item 8. Ninth, item 9. Tenth, item 10. " ++ "Eleventh, item 11. Twelfth, item 12. Next, item 13. Next, item 14.",+ once+ )+ }++ @Test+ fun `sanitize leaves existing numbered lists untouched`() {+ // Numbered lists already have structure — only bullet chars get rewritten.+ assertEquals(+ "1. foo 2. bar 3. baz",+ SpeechTextSanitizer.sanitize("1. foo\n2. bar\n3. baz")+ )+ }++ @Test+ fun `sanitize does not treat dashes without trailing space as bullets`() {+ // "-item" without a space is not a markdown bullet.+ assertEquals(+ "sum a-b is positive",+ SpeechTextSanitizer.sanitize("sum a-b is positive")+ )+ }++ @Test+ fun `sanitize collapses multi-character punctuation`() {+ assertEquals("Stop!", SpeechTextSanitizer.sanitize("Stop!!!"))+ assertEquals("Really?", SpeechTextSanitizer.sanitize("Really???"))+ // Single ? or ! don't trigger collapse (only runs of two or more).+ assertEquals("Wait?!", SpeechTextSanitizer.sanitize("Wait?!"))+ assertEquals("Wow!", SpeechTextSanitizer.sanitize("Wow!!!!!!"))+ }++ @Test+ fun `sanitize normalizes unicode ellipsis to three dots`() {+ assertEquals("wait...", SpeechTextSanitizer.sanitize("wait…"))+ }++ @Test+ fun `sanitize collapses whitespace runs including newlines`() {+ assertEquals("a b c", SpeechTextSanitizer.sanitize("a b\n\nc"))+ assertEquals("a b", SpeechTextSanitizer.sanitize("a\t\tb"))+ }++ @Test+ fun `sanitize strips emoji like stripEmoji`() {+ assertEquals("Hello", SpeechTextSanitizer.sanitize("Hello 😊"))+ assertEquals("", SpeechTextSanitizer.sanitize("😊🙌✨"))+ }++ @Test+ fun `sanitize handles a combined real-world assistant reply`() {+ val input = "# Steps\n- **First**: `ls -la`\n- See https://x.com\nDone ✅"+ assertEquals(+ "Steps First, First: ls -la. Second, See link. Done",+ SpeechTextSanitizer.sanitize(input)+ )+ }++ @Test+ fun `sanitize is idempotent`() {+ val input = "**bold** with `code` and - bullets\n- more\n\nsee https://x.com today!"+ val once = SpeechTextSanitizer.sanitize(input)+ val twice = SpeechTextSanitizer.sanitize(once)+ assertEquals(once, twice)+ }++ @Test+ fun `sanitize handles empty input`() {+ assertEquals("", SpeechTextSanitizer.sanitize(""))+ }++ @Test+ fun `sanitize leaves non-Latin scripts untouched`() {+ val hindi = "हेलो भाई! मैं ठीक हूँ, आप कैसे हो?"+ assertEquals(hindi, SpeechTextSanitizer.sanitize(hindi))+ }++ @Test+ fun `sanitize does not touch snake_case identifiers with underscores`() {+ // `foo_bar_baz` is not italic — underscores are inside a word.+ assertEquals(+ "see foo_bar_baz here",+ SpeechTextSanitizer.sanitize("see foo_bar_baz here")+ )+ }++ @Test+ fun `sanitize preserves trailing sentence periods from prose`() {+ // Non-bullet text already has its own punctuation — don't add extra.+ assertEquals("Hello there.", SpeechTextSanitizer.sanitize("Hello there."))+ }}