feat(frontend): render Markdown answers and speak them while they stream
Two things made Jarvis feel worse than it was. Its Markdown arrived as raw syntax, because egui has no Markdown widget and the bundled fonts have a single weight per family; the renderer therefore builds its own styled LayoutJob, which keeps the bubble sizing already in place and tolerates a half-streamed answer instead of printing markers. And the voice only started once the whole answer was generated, so a long reply was read out after a silence as long as the reply itself; the stream is now cut into sentences as soon as their punctuation arrives, and the spoken text drops the Markdown and the code blocks, since nobody wants asterisks and backticks read aloud. The client also wakes the model on the first keystroke of a draft or when recording starts, so the load happens while the sentence is still being written, and it now sends a history the backend accepts: empty assistant bubbles left by an abandoned answer are dropped, and only the last fifty messages travel, which a long conversation used to overflow.
This commit is contained in:
13 files changed
+1182
-37
No files matched your search
@@ -8,5 +8,6 @@
|
||||
|
||||
pub mod audio;
|
||||
pub mod engine;
|
||||
pub mod speech;
|
||||
pub mod stt;
|
||||
pub mod tts;
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Splits a streamed answer into sentences the voice can start on immediately.
|
||||
//!
|
||||
//! Waiting for `done` before the first word is spoken means waiting for the
|
||||
//! whole answer: a long reply is read out only once it is complete, and the
|
||||
//! user sits in silence the entire time. Instead, [`SentenceChunker`] is fed
|
||||
//! the same fragments that fill the bubble, and hands back every sentence as
|
||||
//! soon as its final punctuation arrives. The sentences come out in order, and
|
||||
//! the voice thread is a queue, so they are spoken back to back.
|
||||
//!
|
||||
//! The text handed back is already readable aloud: Markdown markers are gone
|
||||
//! and fenced code is skipped ([`crate::markdown::to_plain_text`]).
|
||||
|
||||
use crate::markdown;
|
||||
|
||||
/// A unit longer than this is cut at the next space: a wall of text with no
|
||||
/// punctuation at all (a code-free list, a long URL) must not keep the voice
|
||||
/// silent until the very end.
|
||||
const MAX_UNIT_BYTES: usize = 240;
|
||||
|
||||
/// Shortest unit worth speaking on its own. List numbers, `--` and stray
|
||||
/// punctuation land here and are dropped instead of being read as grunts.
|
||||
const MIN_LETTERS: usize = 2;
|
||||
|
||||
/// Reassembles streamed Markdown fragments into speakable sentences.
|
||||
#[derive(Default)]
|
||||
pub struct SentenceChunker {
|
||||
/// Fragments seen so far minus the sentences already handed out.
|
||||
buffer: String,
|
||||
/// Whether the scan so far has left a fenced code block open.
|
||||
in_fence: bool,
|
||||
/// Fence state at the very start of [`Self::buffer`], restored before each
|
||||
/// scan because everything before it has already been consumed.
|
||||
tail_in_fence: bool,
|
||||
}
|
||||
|
||||
impl SentenceChunker {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Adds a fragment and returns the sentences that are now complete.
|
||||
pub fn push(&mut self, fragment: &str) -> Vec<String> {
|
||||
self.buffer.push_str(fragment);
|
||||
// The buffer is rescanned from its start, so start from the state that
|
||||
// belonged to that position.
|
||||
self.in_fence = self.tail_in_fence;
|
||||
|
||||
let mut sentences = Vec::new();
|
||||
let mut unit_start = 0;
|
||||
let mut fence_at_start = self.in_fence;
|
||||
let mut i = 0;
|
||||
|
||||
while i < self.buffer.len() {
|
||||
if self.buffer[i..].starts_with("```") {
|
||||
self.in_fence = !self.in_fence;
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(c) = self.buffer[i..].chars().next() else {
|
||||
break;
|
||||
};
|
||||
let end = match c {
|
||||
'\n' => Some(i + 1),
|
||||
'.' | '!' | '?' | '…' => {
|
||||
let next = self.buffer[i + c.len_utf8()..].chars().next();
|
||||
// `3.14` and `...` are not the end of a sentence: the
|
||||
// punctuation has to be followed by a space or nothing.
|
||||
match next {
|
||||
None | Some(' ') | Some('\n') | Some('\t') => Some(i + c.len_utf8()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
' ' if i - unit_start >= MAX_UNIT_BYTES => Some(i),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(end) = end {
|
||||
self.emit(unit_start, end, fence_at_start, &mut sentences);
|
||||
unit_start = end;
|
||||
fence_at_start = self.in_fence;
|
||||
}
|
||||
|
||||
i += c.len_utf8();
|
||||
}
|
||||
|
||||
self.buffer.drain(..unit_start);
|
||||
self.tail_in_fence = fence_at_start;
|
||||
sentences
|
||||
}
|
||||
|
||||
/// Sentences still buffered when the answer ends mid-sentence.
|
||||
pub fn flush(&mut self) -> Vec<String> {
|
||||
let mut sentences = Vec::new();
|
||||
let end = self.buffer.len();
|
||||
self.emit(0, end, self.tail_in_fence, &mut sentences);
|
||||
self.clear();
|
||||
sentences
|
||||
}
|
||||
|
||||
/// Forgets everything: the next answer starts from a clean slate.
|
||||
pub fn clear(&mut self) {
|
||||
self.buffer.clear();
|
||||
self.in_fence = false;
|
||||
self.tail_in_fence = false;
|
||||
}
|
||||
|
||||
/// Turns one completed unit into a sentence, unless it is code or noise.
|
||||
fn emit(&self, start: usize, end: usize, in_code: bool, out: &mut Vec<String>) {
|
||||
if in_code {
|
||||
return;
|
||||
}
|
||||
let spoken = markdown::to_plain_text(&self.buffer[start..end]);
|
||||
// `to_plain_text` collapses whitespace, so a fence marker or a lone
|
||||
// "-" comes back empty.
|
||||
if spoken.chars().filter(|c| c.is_alphabetic()).count() < MIN_LETTERS {
|
||||
return;
|
||||
}
|
||||
out.push(spoken);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_sentence_is_ready_as_soon_as_it_ends() {
|
||||
let mut chunker = SentenceChunker::new();
|
||||
|
||||
assert_eq!(chunker.push("Bonjour Jarvis."), vec!["Bonjour Jarvis.".to_string()]);
|
||||
// Only the finished sentence is handed out, not the fragment after it.
|
||||
assert!(chunker.push(" Peux-tu").is_empty());
|
||||
|
||||
let rest = chunker.push(" ouvrir le fichier ?");
|
||||
assert_eq!(rest, vec!["Peux-tu ouvrir le fichier ?".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragments_are_reassembled_across_pushes() {
|
||||
let mut chunker = SentenceChunker::new();
|
||||
|
||||
assert!(chunker.push("Le pro").is_empty());
|
||||
assert!(chunker.push("jet est").is_empty());
|
||||
assert_eq!(
|
||||
chunker.push(" prêt. Ensuite."),
|
||||
vec!["Le projet est prêt.".to_string(), "Ensuite.".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_decimal_point_does_not_cut_a_sentence() {
|
||||
let mut chunker = SentenceChunker::new();
|
||||
|
||||
assert!(chunker.push("Pi vaut 3.14 environ").is_empty());
|
||||
assert_eq!(
|
||||
chunker.flush(),
|
||||
vec!["Pi vaut 3.14 environ".to_string()],
|
||||
"the version number must stay in one piece"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fenced_code_is_never_read_aloud() {
|
||||
let mut chunker = SentenceChunker::new();
|
||||
|
||||
let spoken = chunker.push("Voici :\n```sh\ncargo run --release\n```\nEt voilà.");
|
||||
let spoken = spoken.join(" | ");
|
||||
|
||||
assert!(spoken.contains("Voici"), "spoken was: {spoken}");
|
||||
assert!(spoken.contains("Et voilà"), "spoken was: {spoken}");
|
||||
assert!(!spoken.contains("cargo"), "gone to the voice: {spoken}");
|
||||
assert!(!spoken.contains("```"), "gone to the voice: {spoken}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_markers_are_not_spoken() {
|
||||
let mut chunker = SentenceChunker::new();
|
||||
|
||||
let spoken = chunker.push("## Bilan\n\n**Bravo**, c'est `prêt` !\n").join(" | ");
|
||||
|
||||
assert!(spoken.contains("Bilan"), "spoken was: {spoken}");
|
||||
assert!(spoken.contains("Bravo"), "spoken was: {spoken}");
|
||||
assert!(spoken.contains("prêt"), "spoken was: {spoken}");
|
||||
for marker in ["#", "*", "`"] {
|
||||
assert!(!spoken.contains(marker), "{marker} reached the voice: {spoken}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tail_is_spoken_when_the_answer_stops() {
|
||||
let mut chunker = SentenceChunker::new();
|
||||
|
||||
assert!(chunker.push("Une phrase sans ponctuation").is_empty());
|
||||
assert_eq!(
|
||||
chunker.flush(),
|
||||
vec!["Une phrase sans ponctuation".to_string()]
|
||||
);
|
||||
// The buffer is empty again, so nothing is repeated on the next answer.
|
||||
assert!(chunker.flush().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wall_of_text_is_cut_before_the_end() {
|
||||
let mut chunker = SentenceChunker::new();
|
||||
let wall = "mot ".repeat(200); // 800 bytes, no punctuation at all
|
||||
|
||||
let pieces = chunker.push(&wall);
|
||||
assert!(
|
||||
!pieces.is_empty(),
|
||||
"a long answer must start speaking before the end"
|
||||
);
|
||||
for piece in &pieces {
|
||||
assert!(
|
||||
piece.len() <= MAX_UNIT_BYTES + "mot ".len(),
|
||||
"each piece stays around the cap, got {} bytes",
|
||||
piece.len()
|
||||
);
|
||||
}
|
||||
// Nothing is lost: the tail is still buffered for the next flush.
|
||||
let spoken: usize = pieces.iter().map(|p| p.split_whitespace().count()).sum();
|
||||
let rest = chunker.flush().join(" ");
|
||||
assert_eq!(spoken + rest.split_whitespace().count(), 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_drops_an_abandoned_answer() {
|
||||
let mut chunker = SentenceChunker::new();
|
||||
chunker.push("Une réponse interrompue");
|
||||
|
||||
chunker.clear();
|
||||
assert!(chunker.flush().is_empty());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user