diff --git a/app/src/main/java/space/bloggin/scribe/Speech.kt b/app/src/main/java/space/bloggin/scribe/Speech.kt new file mode 100644 index 0000000..d5317cd --- /dev/null +++ b/app/src/main/java/space/bloggin/scribe/Speech.kt @@ -0,0 +1,47 @@ +package space.bloggin.scribe + +/** Turns raw recognised words into note text, handling spoken punctuation and commands. */ +object Speech { + private val punct = listOf( + "question mark" to "?", "exclamation point" to "!", "exclamation mark" to "!", + "new paragraph" to "\n\n", "new line" to "\n", "open quote" to "\"", "close quote" to "\"", + "period" to ".", "comma" to ",", "colon" to ":", "semicolon" to ";" + ) + private val enders = listOf("end note", "stop note", "save note", "finish note") + private val cancels = listOf("cancel note", "discard note", "delete note") + + class Parsed(val text: String, val end: Boolean, val cancel: Boolean, val scratch: Boolean) + + fun parse(raw: String): Parsed { + var t = raw.trim().lowercase() + var end = false + var cancel = false + var scratch = false + for (c in cancels) if (t.endsWith(c)) { t = t.removeSuffix(c).trim(); cancel = true } + for (e in enders) if (t.endsWith(e)) { t = t.removeSuffix(e).trim(); end = true } + if (t.endsWith("scratch that")) { t = t.removeSuffix("scratch that").trim(); scratch = true } + // Spoken punctuation. Whole-word matches only. + for ((spoken, mark) in punct) { + t = t.replace(Regex("\\b" + Regex.escape(spoken) + "\\b"), " \u0001$mark\u0001 ") + } + t = t.replace(Regex("\\s+"), " ").trim() + t = t.replace(" \u0001", "\u0001").replace("\u0001 ", "\u0001") + t = t.replace("\u0001", "") + t = t.replace(Regex("\\bi\\b"), "I").replace(Regex("\\bi'm\\b"), "I'm").replace(Regex("\\bi'll\\b"), "I'll") + .replace(Regex("\\bi've\\b"), "I've").replace(Regex("\\bi'd\\b"), "I'd") + return Parsed(t, end, cancel, scratch) + } + + /** Join a new segment onto the existing text with sensible spacing and capitalisation. */ + fun join(existing: String, seg: String): String { + if (seg.isEmpty()) return existing + val startsWithMark = seg[0] in ".,?!:;" + val prevEndsBreak = existing.isEmpty() || existing.endsWith("\n") + val sep = if (existing.isEmpty() || startsWithMark || prevEndsBreak || seg.startsWith("\n")) "" else " " + var s = seg + val prevTrim = existing.trimEnd(' ') + val needsCap = prevTrim.isEmpty() || prevTrim.endsWith(".") || prevTrim.endsWith("?") || prevTrim.endsWith("!") || prevTrim.endsWith("\n") + if (needsCap && s.isNotEmpty() && s[0].isLetter()) s = s[0].uppercaseChar() + s.substring(1) + return existing + sep + s + } +}