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
+15
-1
@@ -17,7 +17,7 @@ use crate::model::{
|
||||
AddMessageRequest, ChatMessage, ChatRequest, CreateProjectRequest, DeletedMessagesResponse,
|
||||
LoginRequest, LoginResponse, MeResponse, MessagePage, MessageResponse, Project,
|
||||
ProjectChatRequest, ProjectRecallRequest, ProjectResponse, ProjectsResponse, PublicUser,
|
||||
RecallDoneData, StreamData, StoredMessage, UpdateProjectRequest,
|
||||
RecallDoneData, StreamData, StoredMessage, UpdateProjectRequest, WarmModelRequest,
|
||||
};
|
||||
|
||||
/// Errors surfaced to the GUI (which displays them as-is).
|
||||
@@ -328,6 +328,20 @@ impl ApiClient {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Asks the backend to load `model` into memory ahead of the real request.
|
||||
///
|
||||
/// Ollama drops an idle model after a few minutes, and loading it back costs
|
||||
/// seconds, so this is fired as soon as the user starts typing or recording.
|
||||
/// Best effort: the caller ignores the result, since the chat request that
|
||||
/// follows reports any real failure.
|
||||
pub async fn warm_model(&self, model: &str) -> Result<(), ApiError> {
|
||||
let request = self
|
||||
.http
|
||||
.post(self.url("/api/chat/warm"))
|
||||
.json(&WarmModelRequest { model: Some(model) });
|
||||
self.send_empty(request).await
|
||||
}
|
||||
|
||||
/// Streams a chat completion.
|
||||
///
|
||||
/// `on_event` is called for every fragment as it arrives; it runs on the
|
||||
|
||||
+178
-26
@@ -15,10 +15,12 @@ use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::api::{ApiClient, RecallEvent, StreamEvent};
|
||||
use crate::config::AppConfig;
|
||||
use crate::markdown;
|
||||
use crate::model::{ChatMessage, Project, PublicUser, StoredMessage};
|
||||
use crate::tamagotchi::{self, Mood};
|
||||
use crate::voice::audio::Recorder;
|
||||
use crate::voice::engine::{self, VoiceConfig, VoiceEvent, VoiceHandle};
|
||||
use crate::voice::speech::SentenceChunker;
|
||||
|
||||
/// Key under which the state is persisted (token, email, model, backend URL).
|
||||
const STORAGE_KEY: &str = "jarvise-session";
|
||||
@@ -200,6 +202,15 @@ pub struct JarviseApp {
|
||||
recorder: Option<Recorder>,
|
||||
voice_status: Option<String>,
|
||||
pending_transcript: Option<String>,
|
||||
/// Reassembles the streamed answer into sentences to speak as it arrives,
|
||||
/// instead of waiting for the whole message.
|
||||
speech: SentenceChunker,
|
||||
/// Sentences still queued in the voice thread: the companion only stops
|
||||
/// showing « Speaking » once the last one has been read out.
|
||||
speech_pending: usize,
|
||||
/// Whether the draft being typed already asked the backend to warm the
|
||||
/// model. Keeps a single request per draft instead of one per keystroke.
|
||||
draft_warmed: bool,
|
||||
|
||||
// Companion animation.
|
||||
speaking: bool,
|
||||
@@ -297,6 +308,9 @@ impl JarviseApp {
|
||||
recorder: None,
|
||||
voice_status: None,
|
||||
pending_transcript: None,
|
||||
speech: SentenceChunker::new(),
|
||||
speech_pending: 0,
|
||||
draft_warmed: false,
|
||||
speaking: false,
|
||||
happy_timer: 0.0,
|
||||
};
|
||||
@@ -562,11 +576,15 @@ impl JarviseApp {
|
||||
}
|
||||
|
||||
self.error = None;
|
||||
// A new answer starts from a clean slate: nothing left over from the
|
||||
// previous one may be spoken, and the next draft may warm the model.
|
||||
self.speech.clear();
|
||||
self.draft_warmed = false;
|
||||
self.messages.push(ChatMessage::user(text.clone()));
|
||||
self.input.clear();
|
||||
|
||||
// The history sent to the stateless endpoint ends with the user's message.
|
||||
let history = self.messages.clone();
|
||||
let history = stateless_history(&self.messages);
|
||||
|
||||
// A placeholder assistant bubble receives the streamed fragments.
|
||||
self.messages.push(ChatMessage::assistant(String::new()));
|
||||
@@ -609,6 +627,29 @@ impl JarviseApp {
|
||||
cancel.cancel();
|
||||
}
|
||||
self.streaming = false;
|
||||
// The rest of that answer will never arrive: forget it rather than say
|
||||
// a random half-sentence later.
|
||||
self.speech.clear();
|
||||
}
|
||||
|
||||
/// Asks the backend to load the model into memory before the request that
|
||||
/// will need it. Ollama unloads an idle model after a few minutes and a
|
||||
/// cold load costs several seconds; firing this as soon as the user starts
|
||||
/// typing or recording hides that cost behind the sentence being written.
|
||||
///
|
||||
/// Best effort — the result is ignored, and the real chat request reports
|
||||
/// any genuine failure. At most one call per draft.
|
||||
fn warm_model(&mut self) {
|
||||
if self.draft_warmed || self.streaming {
|
||||
return;
|
||||
}
|
||||
self.draft_warmed = true;
|
||||
|
||||
let api = self.api.clone();
|
||||
let model = self.model.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let _ = api.warm_model(&model).await;
|
||||
});
|
||||
}
|
||||
|
||||
fn logout(&mut self) {
|
||||
@@ -630,6 +671,9 @@ impl JarviseApp {
|
||||
return;
|
||||
}
|
||||
self.error = None;
|
||||
// The user is about to speak: start loading the model now, so it is
|
||||
// resident by the time the transcript reaches the backend.
|
||||
self.warm_model();
|
||||
match Recorder::start() {
|
||||
Ok(recorder) => {
|
||||
self.recorder = Some(recorder);
|
||||
@@ -808,25 +852,30 @@ impl JarviseApp {
|
||||
last.content.push_str(&text);
|
||||
}
|
||||
}
|
||||
// Speak each sentence as soon as it is complete: waiting for
|
||||
// `done` would leave the user in silence for the whole
|
||||
// answer.
|
||||
if self.speak_replies {
|
||||
for sentence in self.speech.push(&text) {
|
||||
self.speech_pending += 1;
|
||||
self.voice.speak(sentence);
|
||||
}
|
||||
// The companion only shows « Speaking » once something is
|
||||
// actually queued.
|
||||
self.speaking = self.speech_pending > 0;
|
||||
}
|
||||
}
|
||||
UiEvent::Done => {
|
||||
self.streaming = false;
|
||||
self.cancel = None;
|
||||
|
||||
// Read the answer out loud when voice output is enabled.
|
||||
let speech = if self.speak_replies {
|
||||
self.messages
|
||||
.last()
|
||||
.filter(|message| {
|
||||
message.role == "assistant" && !message.content.trim().is_empty()
|
||||
})
|
||||
.map(|message| message.content.clone())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(text) = speech {
|
||||
self.speaking = true;
|
||||
self.voice.speak(text);
|
||||
// The answer may end mid-sentence: speak what is left over.
|
||||
if self.speak_replies {
|
||||
for sentence in self.speech.flush() {
|
||||
self.speech_pending += 1;
|
||||
self.voice.speak(sentence);
|
||||
}
|
||||
self.speaking = self.speech_pending > 0;
|
||||
}
|
||||
self.happy_timer = 2.5;
|
||||
|
||||
@@ -851,10 +900,15 @@ impl JarviseApp {
|
||||
}
|
||||
UiEvent::VoiceError(message) => {
|
||||
self.voice_status = None;
|
||||
self.speech_pending = 0;
|
||||
self.speaking = false;
|
||||
self.error = Some(message);
|
||||
}
|
||||
UiEvent::Spoken => self.speaking = false,
|
||||
// One sentence finished playing; others may still be queued.
|
||||
UiEvent::Spoken => {
|
||||
self.speech_pending = self.speech_pending.saturating_sub(1);
|
||||
self.speaking = self.speech_pending > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1141,6 +1195,12 @@ impl JarviseApp {
|
||||
let submitted = response.has_focus()
|
||||
&& ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift);
|
||||
|
||||
// First keystroke of a draft: load the model while the
|
||||
// sentence is still being written.
|
||||
if response.changed() && !self.input.trim().is_empty() {
|
||||
self.warm_model();
|
||||
}
|
||||
|
||||
if self.streaming {
|
||||
if ui
|
||||
.add_sized([button_width, 52.0], egui::Button::new("Stopper"))
|
||||
@@ -1184,6 +1244,10 @@ impl JarviseApp {
|
||||
let submitted = response.has_focus()
|
||||
&& ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift);
|
||||
|
||||
if response.changed() && !self.input.trim().is_empty() {
|
||||
self.warm_model();
|
||||
}
|
||||
|
||||
if self.streaming {
|
||||
if ui
|
||||
.add_sized([button_width, 40.0], egui::Button::new("Stopper"))
|
||||
@@ -1567,7 +1631,8 @@ fn subtitle(ui: &mut egui::Ui, who: &str, text: &str, width: f32, from_jarvis: b
|
||||
.corner_radius(egui::CornerRadius::same(12))
|
||||
.inner_margin(egui::Margin::symmetric(14, 10))
|
||||
.show(ui, |ui| {
|
||||
ui.set_max_width((width - 30.0).max(120.0));
|
||||
let inner_width = (width - 30.0).max(120.0);
|
||||
ui.set_max_width(inner_width);
|
||||
ui.vertical(|ui| {
|
||||
ui.label(
|
||||
egui::RichText::new(who)
|
||||
@@ -1575,11 +1640,33 @@ fn subtitle(ui: &mut egui::Ui, who: &str, text: &str, width: f32, from_jarvis: b
|
||||
.strong()
|
||||
.color(ACCENT_SOFT),
|
||||
);
|
||||
ui.label(text);
|
||||
if from_jarvis {
|
||||
ui.label(markdown::layout(
|
||||
text,
|
||||
&assistant_markdown(),
|
||||
inner_width - 28.0,
|
||||
));
|
||||
} else {
|
||||
ui.label(text);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// How Jarvis' Markdown is painted inside a bubble or a subtitle: prose in the
|
||||
/// app's reading colour, headings and bullets on the accent, code on its own
|
||||
/// slab. Emphasis is a brighter colour because the bundled fonts have a single
|
||||
/// weight per family.
|
||||
fn assistant_markdown() -> markdown::MarkdownStyle {
|
||||
markdown::MarkdownStyle {
|
||||
text: egui::Color32::from_gray(238),
|
||||
strong: egui::Color32::WHITE,
|
||||
accent: ACCENT_SOFT,
|
||||
base_size: 15.0,
|
||||
..markdown::MarkdownStyle::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Consumes the microphone shortcut from the current frame's input and reports
|
||||
/// whether it fired. Consuming it keeps the `Ctrl+Espace` press away from the
|
||||
/// compose box, and makes a single press toggle the capture only once.
|
||||
@@ -1706,6 +1793,31 @@ pub fn chat_area(ui: &mut egui::Ui, messages: &[ChatMessage]) {
|
||||
);
|
||||
}
|
||||
|
||||
/// Turns handed back to the model by `POST /api/chat`: everything that carries
|
||||
/// text, capped at the backend's contract and keeping the most recent exchange.
|
||||
///
|
||||
/// Two bubbles have to be left out, or the request is rejected before it ever
|
||||
/// reaches the model: an abandoned answer leaves an **empty** assistant message
|
||||
/// (the schema requires `minLength: 1`), and a long conversation exceeds the
|
||||
/// 50-message cap. The last entry is always the question, so trimming the
|
||||
/// oldest turns keeps the model's context as recent as the window allows.
|
||||
fn stateless_history(messages: &[ChatMessage]) -> Vec<ChatMessage> {
|
||||
let mut history: Vec<ChatMessage> = messages
|
||||
.iter()
|
||||
.filter(|message| !message.content.trim().is_empty())
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
if history.len() > MAX_HISTORY_MESSAGES {
|
||||
history.drain(..history.len() - MAX_HISTORY_MESSAGES);
|
||||
}
|
||||
|
||||
history
|
||||
}
|
||||
|
||||
/// Longest history `POST /api/chat` accepts (see the backend's JSON schema).
|
||||
const MAX_HISTORY_MESSAGES: usize = 50;
|
||||
|
||||
/// Draws a single message as a chat bubble and returns the rectangle it covers.
|
||||
///
|
||||
/// The text is laid out *before* the bubble is allocated: `egui` only wraps a
|
||||
@@ -1735,14 +1847,22 @@ pub fn render_bubble(ui: &mut egui::Ui, message: &ChatMessage) -> egui::Rect {
|
||||
} else {
|
||||
message.content.as_str()
|
||||
};
|
||||
let galley = ui.ctx().fonts_mut(|fonts| {
|
||||
fonts.layout(
|
||||
text.to_string(),
|
||||
egui::FontId::proportional(15.0),
|
||||
text_color,
|
||||
text_width,
|
||||
)
|
||||
});
|
||||
// Jarvis answers in Markdown: render it (headings, lists, code, emphasis)
|
||||
// instead of showing the syntax. What the user typed stays verbatim — they
|
||||
// write plain prose, and asterisks there mean asterisks.
|
||||
let job = if message.is_user() {
|
||||
let mut job = egui::text::LayoutJob::default();
|
||||
job.wrap.max_width = text_width;
|
||||
job.append(
|
||||
text,
|
||||
0.0,
|
||||
egui::TextFormat::simple(egui::FontId::proportional(15.0), text_color),
|
||||
);
|
||||
job
|
||||
} else {
|
||||
markdown::layout(text, &assistant_markdown(), text_width)
|
||||
};
|
||||
let galley = ui.ctx().fonts_mut(|fonts| fonts.layout_job(job));
|
||||
let size = galley.size() + egui::vec2(2.0 * PADDING, 2.0 * PADDING);
|
||||
|
||||
// The user hugs the right edge of the column, Jarvis hugs the left one.
|
||||
@@ -1858,6 +1978,38 @@ mod tests {
|
||||
assert!(!repeated, "un appui ne doit basculer le micro qu'une fois");
|
||||
}
|
||||
|
||||
/// The model only answers well when it gets the whole conversation, but two
|
||||
/// details of the backend contract decide what may be sent.
|
||||
#[test]
|
||||
fn the_history_sent_back_is_usable() {
|
||||
let mut messages = vec![
|
||||
ChatMessage::user("Bonjour"),
|
||||
ChatMessage::assistant("Bonjour, que puis-je faire ?"),
|
||||
// An answer stopped before its first fragment leaves an empty bubble.
|
||||
ChatMessage::assistant(String::new()),
|
||||
ChatMessage::user("Ouvre le fichier"),
|
||||
];
|
||||
|
||||
let history = stateless_history(&messages);
|
||||
assert_eq!(history.len(), 3, "the empty bubble must not be sent");
|
||||
assert!(history.last().expect("a question").is_user());
|
||||
assert!(history.iter().all(|m| !m.content.trim().is_empty()));
|
||||
|
||||
// A long conversation is trimmed from the oldest turn, never from the
|
||||
// question that is being asked right now.
|
||||
messages.clear();
|
||||
for i in 0..80 {
|
||||
messages.push(ChatMessage::user(format!("question {i}")));
|
||||
messages.push(ChatMessage::assistant(format!("réponse {i}")));
|
||||
}
|
||||
messages.push(ChatMessage::user("dernière question"));
|
||||
|
||||
let history = stateless_history(&messages);
|
||||
assert_eq!(history.len(), MAX_HISTORY_MESSAGES);
|
||||
assert_eq!(history.last().expect("the question").content, "dernière question");
|
||||
assert_eq!(history[0].content, "réponse 55");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modes_have_distinct_tabs() {
|
||||
assert_ne!(Mode::Chat.label(), Mode::Companion.label());
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
pub mod api;
|
||||
pub mod app;
|
||||
pub mod config;
|
||||
pub mod markdown;
|
||||
pub mod model;
|
||||
pub mod tamagotchi;
|
||||
pub mod voice;
|
||||
@@ -0,0 +1,564 @@
|
||||
//! A small Markdown renderer for the answers Jarvis streams back.
|
||||
//!
|
||||
//! `egui` has no Markdown widget, and the bundled fonts ship a single weight per
|
||||
//! family — there is no bold face to switch to. So instead of pulling in a full
|
||||
//! parser (which would hit the same font limit), the renderer keeps what the
|
||||
//! app already does well: one [`LayoutJob`] laid out at a known width, painted
|
||||
//! by the caller's bubble. It styles the blocks the answers actually use —
|
||||
//! headings, lists, quotes, rules, tables, fenced code, and inline emphasis,
|
||||
//! code and links — and drops the syntax markers, so `**gras**` shows as
|
||||
//! *gras* and not as asterisks.
|
||||
//!
|
||||
//! Everything tolerates a half-written answer: an unclosed `**` or code fence
|
||||
//! styles the rest of the message instead of printing the markers, because the
|
||||
//! bubble is laid out again on every streamed fragment.
|
||||
|
||||
use eframe::egui;
|
||||
use egui::text::{LayoutJob, TextFormat};
|
||||
use egui::{Color32, FontId, Stroke};
|
||||
|
||||
/// Colours and base size the renderer paints with. Kept explicit rather than
|
||||
/// read from the egui style so a bubble stays readable whatever the theme does.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct MarkdownStyle {
|
||||
/// Ordinary prose.
|
||||
pub text: Color32,
|
||||
/// Emphasis. `egui` has one weight per font family, so bold is carried by a
|
||||
/// brighter colour instead of a heavier face.
|
||||
pub strong: Color32,
|
||||
/// Headings, bullets, table separators and links.
|
||||
pub accent: Color32,
|
||||
/// Inline code and fenced blocks, painted on [`Self::code_background`].
|
||||
pub code: Color32,
|
||||
pub code_background: Color32,
|
||||
/// Size of ordinary prose; every other size is derived from it.
|
||||
pub base_size: f32,
|
||||
}
|
||||
|
||||
impl Default for MarkdownStyle {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
text: Color32::from_gray(238),
|
||||
strong: Color32::WHITE,
|
||||
accent: Color32::from_rgb(0x9d, 0xbc, 0xff),
|
||||
code: Color32::from_rgb(0xd8, 0xe2, 0xf0),
|
||||
code_background: Color32::from_rgb(0x2a, 0x2f, 0x3b),
|
||||
base_size: 15.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lays `markdown` out into a galley job wrapped at `wrap_width`.
|
||||
pub fn layout(markdown: &str, style: &MarkdownStyle, wrap_width: f32) -> LayoutJob {
|
||||
let mut job = LayoutJob::default();
|
||||
job.wrap.max_width = wrap_width.max(1.0);
|
||||
job.break_on_newline = true;
|
||||
|
||||
let size = style.base_size;
|
||||
let mut in_fence = false;
|
||||
|
||||
for raw in markdown.lines() {
|
||||
let line = raw.trim_end();
|
||||
let trimmed = line.trim_start();
|
||||
// Indented items keep a visual step. The answers nest one level deep at
|
||||
// most, so capping the indent is enough.
|
||||
let indent = " ".repeat((line.len() - trimmed.len()).min(6) / 2);
|
||||
|
||||
// A fence toggles with its own marker line, which is never painted.
|
||||
if trimmed.starts_with("```") {
|
||||
in_fence = !in_fence;
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_fence {
|
||||
job.append(line, 0.0, code_format(style, size * 0.92));
|
||||
push_newline(&mut job, size, style.code);
|
||||
continue;
|
||||
}
|
||||
|
||||
if trimmed.is_empty() {
|
||||
push_newline(&mut job, size, style.text);
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(level) = heading_level(trimmed) {
|
||||
let heading_size = size * heading_scale(level);
|
||||
push_inline(&mut job, &trimmed[level..].trim_start(), style, heading_size, style.accent);
|
||||
push_newline(&mut job, heading_size, style.accent);
|
||||
continue;
|
||||
}
|
||||
|
||||
if is_rule(trimmed) {
|
||||
let format = prose_format(size, style.code);
|
||||
job.append(&"─".repeat(28), 0.0, format);
|
||||
push_newline(&mut job, size, style.code);
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(row) = table_row(trimmed) {
|
||||
match row {
|
||||
// `|---|---|` only marks the header; it carries no content.
|
||||
TableRow::Separator => {}
|
||||
TableRow::Cells(cells) => {
|
||||
push_table_row(&mut job, &cells, style, size);
|
||||
push_newline(&mut job, size, style.text);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(rest) = trimmed.strip_prefix('>') {
|
||||
let format = prose_format(size, style.accent);
|
||||
job.append(&format!("{indent}│ "), 0.0, format);
|
||||
push_inline(&mut job, rest.trim_start(), style, size, style.code);
|
||||
push_newline(&mut job, size, style.text);
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(rest) = bullet_rest(trimmed) {
|
||||
let format = prose_format(size, style.accent);
|
||||
job.append(&format!("{indent}• "), 0.0, format);
|
||||
push_inline(&mut job, rest, style, size, style.text);
|
||||
push_newline(&mut job, size, style.text);
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some((marker, rest)) = ordered_parts(trimmed) {
|
||||
let format = prose_format(size, style.accent);
|
||||
job.append(&format!("{indent}{marker} "), 0.0, format);
|
||||
push_inline(&mut job, rest, style, size, style.text);
|
||||
push_newline(&mut job, size, style.text);
|
||||
continue;
|
||||
}
|
||||
|
||||
push_inline(&mut job, trimmed, style, size, style.text);
|
||||
push_newline(&mut job, size, style.text);
|
||||
}
|
||||
|
||||
job
|
||||
}
|
||||
|
||||
/// What to speak out loud: the same Markdown without its syntax.
|
||||
///
|
||||
/// Fenced blocks are left out entirely — reading code, indentation and
|
||||
/// backticks aloud is noise — while everything else keeps its words. Used only
|
||||
/// by the speech path, never for display.
|
||||
pub fn to_plain_text(markdown: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut in_fence = false;
|
||||
|
||||
for raw in markdown.lines() {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.starts_with("```") {
|
||||
in_fence = !in_fence;
|
||||
continue;
|
||||
}
|
||||
if in_fence || is_rule(trimmed) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut line = trimmed;
|
||||
if let Some(level) = heading_level(line) {
|
||||
line = line[level..].trim_start();
|
||||
} else if let Some(rest) = bullet_rest(line) {
|
||||
line = rest;
|
||||
} else if let Some((_, rest)) = ordered_parts(line) {
|
||||
line = rest;
|
||||
} else if let Some(rest) = line.strip_prefix('>') {
|
||||
line = rest.trim_start();
|
||||
}
|
||||
|
||||
if let Some(row) = table_row(line) {
|
||||
if let TableRow::Cells(cells) = row {
|
||||
out.push_str(&cells.join(", "));
|
||||
out.push('\n');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let spoken = strip_inline(line);
|
||||
if !spoken.is_empty() {
|
||||
out.push_str(&spoken);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
|
||||
// Markers leave doubled spaces behind; a synthesiser reads them as pauses.
|
||||
out.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- blocks */
|
||||
|
||||
fn heading_level(line: &str) -> Option<usize> {
|
||||
let hashes = line.chars().take_while(|c| *c == '#').count();
|
||||
if hashes == 0 || hashes > 6 {
|
||||
return None;
|
||||
}
|
||||
// `#hashtag` is not a heading: a heading marker is followed by a space.
|
||||
let rest = &line[hashes..];
|
||||
(rest.is_empty() || rest.starts_with(' ')).then_some(hashes)
|
||||
}
|
||||
|
||||
fn heading_scale(level: usize) -> f32 {
|
||||
match level {
|
||||
1 => 1.55,
|
||||
2 => 1.35,
|
||||
3 => 1.20,
|
||||
4 => 1.12,
|
||||
_ => 1.05,
|
||||
}
|
||||
}
|
||||
|
||||
fn bullet_rest(line: &str) -> Option<&str> {
|
||||
["- ", "* ", "+ "]
|
||||
.into_iter()
|
||||
.find_map(|marker| line.strip_prefix(marker))
|
||||
}
|
||||
|
||||
/// Splits `12. text` into its marker (`12.`) and the text that follows.
|
||||
fn ordered_parts(line: &str) -> Option<(&str, &str)> {
|
||||
let digits = line.chars().take_while(|c| c.is_ascii_digit()).count();
|
||||
if digits == 0 {
|
||||
return None;
|
||||
}
|
||||
let rest = line[digits..].strip_prefix(". ")?;
|
||||
Some((&line[..=digits], rest))
|
||||
}
|
||||
|
||||
/// `---`, `***` or `___` on a line of their own: a horizontal rule.
|
||||
fn is_rule(line: &str) -> bool {
|
||||
let trimmed = line.trim();
|
||||
let mut chars = trimmed.chars();
|
||||
let Some(first) = chars.next() else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(first, '-' | '*' | '_' | '=') {
|
||||
return false;
|
||||
}
|
||||
trimmed.chars().count() >= 3 && trimmed.chars().all(|c| c == first || c == ' ')
|
||||
}
|
||||
|
||||
enum TableRow<'a> {
|
||||
/// `|---|---|`: the line that underlines a header.
|
||||
Separator,
|
||||
Cells(Vec<&'a str>),
|
||||
}
|
||||
|
||||
fn table_row(line: &str) -> Option<TableRow<'_>> {
|
||||
let inner = line.strip_prefix('|')?.strip_suffix('|')?;
|
||||
let cells: Vec<&str> = inner.split('|').map(str::trim).collect();
|
||||
if cells.iter().all(|cell| {
|
||||
!cell.is_empty() && cell.chars().all(|c| c == '-' || c == ':')
|
||||
}) {
|
||||
return Some(TableRow::Separator);
|
||||
}
|
||||
Some(TableRow::Cells(cells))
|
||||
}
|
||||
|
||||
fn push_table_row(job: &mut LayoutJob, cells: &[&str], style: &MarkdownStyle, size: f32) {
|
||||
let separator = prose_format(size, style.accent);
|
||||
for (index, cell) in cells.iter().enumerate() {
|
||||
if index > 0 {
|
||||
job.append(" • ", 0.0, separator.clone());
|
||||
}
|
||||
push_inline(job, cell, style, size, style.text);
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- inline */
|
||||
|
||||
/// Emphasis state while scanning a line.
|
||||
#[derive(Default, Clone, Copy)]
|
||||
struct Emphasis {
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
strike: bool,
|
||||
}
|
||||
|
||||
fn push_inline(job: &mut LayoutJob, text: &str, style: &MarkdownStyle, size: f32, color: Color32) {
|
||||
// Inside a heading the text is already accented, so bold would be invisible:
|
||||
// keep the heading colour rather than switching to [`MarkdownStyle::strong`].
|
||||
let emphasis = if color == style.text {
|
||||
style.strong
|
||||
} else {
|
||||
color
|
||||
};
|
||||
|
||||
let mut state = Emphasis::default();
|
||||
let mut run_start = 0;
|
||||
let mut i = 0;
|
||||
|
||||
while i < text.len() {
|
||||
let rest = &text[i..];
|
||||
let Some(c) = rest.chars().next() else {
|
||||
break;
|
||||
};
|
||||
|
||||
match c {
|
||||
// Inline code, recognised only once its closing backtick has
|
||||
// arrived: a half-streamed answer must not turn the rest of the
|
||||
// line into code.
|
||||
'`' => match rest[1..].find('`') {
|
||||
Some(end) => {
|
||||
push_run(job, &text[run_start..i], size, color, emphasis, state);
|
||||
job.append(&rest[1..1 + end], 0.0, code_format(style, size * 0.94));
|
||||
i += end + 2;
|
||||
run_start = i;
|
||||
}
|
||||
None => i += 1,
|
||||
},
|
||||
'*' | '_' if rest.starts_with("**") || rest.starts_with("__") => {
|
||||
push_run(job, &text[run_start..i], size, color, emphasis, state);
|
||||
state.bold = !state.bold;
|
||||
i += 2;
|
||||
run_start = i;
|
||||
}
|
||||
// A lone `*` opens emphasis only when a word follows it, so `2 * 3`
|
||||
// stays arithmetic instead of italicising the rest of the line.
|
||||
'*' | '_' => {
|
||||
let opens = rest[1..].chars().next().is_some_and(|n| !n.is_whitespace());
|
||||
if opens || state.italic {
|
||||
push_run(job, &text[run_start..i], size, color, emphasis, state);
|
||||
state.italic = !state.italic;
|
||||
i += 1;
|
||||
run_start = i;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'~' if rest.starts_with("~~") => {
|
||||
push_run(job, &text[run_start..i], size, color, emphasis, state);
|
||||
state.strike = !state.strike;
|
||||
i += 2;
|
||||
run_start = i;
|
||||
}
|
||||
'[' => match parse_link(rest) {
|
||||
Some((label, consumed)) => {
|
||||
push_run(job, &text[run_start..i], size, color, emphasis, state);
|
||||
let mut format = prose_format(size, style.accent);
|
||||
format.italics = state.italic;
|
||||
format.underline = Stroke::new(1.0, style.accent);
|
||||
job.append(label, 0.0, format);
|
||||
i += consumed;
|
||||
run_start = i;
|
||||
}
|
||||
None => i += 1,
|
||||
},
|
||||
_ => i += c.len_utf8(),
|
||||
}
|
||||
}
|
||||
|
||||
push_run(job, &text[run_start..], size, color, emphasis, state);
|
||||
}
|
||||
|
||||
/// `[label](target)` → the label and how many bytes it occupies. An image
|
||||
/// falls back to its alt text, which is the only part worth showing.
|
||||
fn parse_link(text: &str) -> Option<(&str, usize)> {
|
||||
let close = text.find("](")?;
|
||||
let end = text[close + 2..].find(')')?;
|
||||
let label = &text[1..close];
|
||||
if label.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((label, close + 2 + end + 1))
|
||||
}
|
||||
|
||||
/// Drops the inline markers of one line, keeping only what is read out.
|
||||
fn strip_inline(text: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut chars = text.chars().peekable();
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
// Markers carry no sound: only the words around them are spoken.
|
||||
'*' | '_' | '`' | '~' => {}
|
||||
'[' => {
|
||||
let mut label = String::new();
|
||||
let mut closed = false;
|
||||
for n in chars.by_ref() {
|
||||
if n == ']' {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
label.push(n);
|
||||
}
|
||||
// Skip the target, keeping the readable label.
|
||||
if closed && chars.peek() == Some(&'(') {
|
||||
chars.next();
|
||||
for n in chars.by_ref() {
|
||||
if n == ')' {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(&label);
|
||||
}
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- formats */
|
||||
|
||||
fn prose_format(size: f32, color: Color32) -> TextFormat {
|
||||
TextFormat::simple(FontId::proportional(size), color)
|
||||
}
|
||||
|
||||
fn code_format(style: &MarkdownStyle, size: f32) -> TextFormat {
|
||||
let mut format = TextFormat::simple(FontId::monospace(size), style.code);
|
||||
format.background = style.code_background;
|
||||
format
|
||||
}
|
||||
|
||||
fn push_newline(job: &mut LayoutJob, size: f32, color: Color32) {
|
||||
job.append("\n", 0.0, prose_format(size, color));
|
||||
}
|
||||
|
||||
fn push_run(
|
||||
job: &mut LayoutJob,
|
||||
slice: &str,
|
||||
size: f32,
|
||||
color: Color32,
|
||||
emphasis: Color32,
|
||||
state: Emphasis,
|
||||
) {
|
||||
if slice.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut format = prose_format(size, if state.bold { emphasis } else { color });
|
||||
format.italics = state.italic;
|
||||
if state.strike {
|
||||
format.strikethrough = Stroke::new(1.0, format.color);
|
||||
}
|
||||
job.append(slice, 0.0, format);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn dark() -> MarkdownStyle {
|
||||
MarkdownStyle {
|
||||
base_size: 15.0,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headings_grow_and_lose_their_hashes() {
|
||||
let job = layout("# Titre\n\n## Sous-titre", &dark(), 600.0);
|
||||
|
||||
assert!(!job.text.contains('#'), "text was: {:?}", job.text);
|
||||
assert!(job.text.contains("Titre"));
|
||||
|
||||
let sizes: Vec<f32> = job.sections.iter().map(|s| s.format.font_id.size).collect();
|
||||
assert!(sizes.iter().cloned().fold(f32::MIN, f32::max) > 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emphasis_is_styled_instead_of_printed() {
|
||||
let job = layout("du **gras**, de l'*italique* et du ~~barré~~", &dark(), 600.0);
|
||||
|
||||
assert_eq!(job.text.trim_end(), "du gras, de l'italique et du barré");
|
||||
|
||||
let style = dark();
|
||||
assert!(
|
||||
job.sections.iter().any(|s| s.format.color == style.strong),
|
||||
"bold should be brighter than the body text"
|
||||
);
|
||||
assert!(job.sections.iter().any(|s| s.format.italics));
|
||||
assert!(job.sections.iter().any(|s| s.format.strikethrough != Stroke::NONE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_star_stays_arithmetic() {
|
||||
let job = layout("2 * 3 = 6", &dark(), 600.0);
|
||||
|
||||
assert_eq!(job.text.trim_end(), "2 * 3 = 6");
|
||||
assert!(job.sections.iter().all(|s| !s.format.italics));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fence_markers_are_dropped_and_code_is_monospace() {
|
||||
let job = layout("avant\n```rust\nlet x = 1;\n```\naprès", &dark(), 600.0);
|
||||
|
||||
assert!(!job.text.contains("```"));
|
||||
assert!(job.text.contains("let x = 1;"));
|
||||
|
||||
let style = dark();
|
||||
let code = job
|
||||
.sections
|
||||
.iter()
|
||||
.find(|s| s.format.font_id.family == FontId::monospace(15.0).family)
|
||||
.expect("the code line should keep a monospace font");
|
||||
assert_eq!(code.format.background, style.code_background);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclosed_fence_styles_what_has_arrived() {
|
||||
// Mid-stream: the closing fence is still missing.
|
||||
let job = layout("voici :\n```\nlet x", &dark(), 600.0);
|
||||
|
||||
assert!(job.text.contains("let x"));
|
||||
assert!(!job.text.contains("```"));
|
||||
assert!(
|
||||
job.sections
|
||||
.iter()
|
||||
.any(|s| s.format.background == dark().code_background),
|
||||
"an unclosed fence must not print its marker"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bullets_and_numbers_keep_their_text() {
|
||||
let job = layout("- un\n- deux\n\n1. premier\n2. second", &dark(), 600.0);
|
||||
|
||||
assert!(job.text.contains("• un"), "text was: {:?}", job.text);
|
||||
assert!(job.text.contains("1. premier"));
|
||||
assert!(!job.text.contains("- un"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_rows_lose_their_pipes() {
|
||||
let job = layout("| Nom | Rôle |\n|---|---|\n| Jarvis | assistant |", &dark(), 600.0);
|
||||
|
||||
assert!(!job.text.contains('|'), "text was: {:?}", job.text);
|
||||
assert!(job.text.contains("Nom"));
|
||||
assert!(job.text.contains("•"));
|
||||
// The `|---|` marker line only underlines the header.
|
||||
assert!(!job.text.contains("---"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_show_their_label() {
|
||||
let job = layout("voir [la doc](https://example.com/x) pour ça", &dark(), 600.0);
|
||||
|
||||
assert_eq!(job.text.trim_end(), "voir la doc pour ça");
|
||||
assert!(job.sections.iter().any(|s| s.format.underline != Stroke::NONE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spoken_text_has_no_markers_and_no_code() {
|
||||
let spoken = to_plain_text(
|
||||
"## Titre\n\n**gras** et `code`\n\n```sh\ncargo run\n```\n\n- un élément\n> cité",
|
||||
);
|
||||
|
||||
assert_eq!(spoken, "Titre gras et code un élément cité");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_written_answer_still_lays_out() {
|
||||
for partial in [
|
||||
"**gras inachevé",
|
||||
"*italique inachevé",
|
||||
"`code inachevé",
|
||||
"~~barré inachevé",
|
||||
"[lien inachevé](",
|
||||
] {
|
||||
let job = layout(partial, &dark(), 400.0);
|
||||
assert!(!job.text.is_empty(), "{partial:?} should not vanish");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -203,6 +203,14 @@ pub(crate) struct ProjectRecallRequest<'a> {
|
||||
pub model: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// Body of `POST /api/chat/warm`: asks the backend to load the model into
|
||||
/// memory before the request that will actually need it.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct WarmModelRequest<'a> {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub model: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// `done` payload of the recall stream: how many stored messages were actually
|
||||
/// replayed to the model (the backend caps the context it sends).
|
||||
#[derive(Deserialize)]
|
||||
|
||||
@@ -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