π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Objectify the transcription model and reuse the download engine
Manav Rathiac024f908b0c
diff --git a/rust/bindings/uniffi/ensu/src/llm.rs b/rust/bindings/uniffi/ensu/src/llm.rsindex ee3701c220..48192d7f63 100644--- a/rust/bindings/uniffi/ensu/src/llm.rs+++ b/rust/bindings/uniffi/ensu/src/llm.rs@@ -1,5 +1,5 @@-use ente_ensu::llm as core;use ente_ensu::download;+use ente_ensu::llm as core;use std::sync::Arc;use thiserror::Error;diff --git a/rust/bindings/uniffi/ensu/src/transcription.rs b/rust/bindings/uniffi/ensu/src/transcription.rsindex 09e5ead812..47335b972e 100644--- a/rust/bindings/uniffi/ensu/src/transcription.rs+++ b/rust/bindings/uniffi/ensu/src/transcription.rs@@ -1,3 +1,5 @@+use std::sync::Arc;+use thiserror::Error;use ente_ensu::transcription as core;@@ -54,47 +56,57 @@ pub trait TranscriptionModelEventCallback: Send + Sync {fn on_event(&self, event: TranscriptionModelEvent);}-#[uniffi::export]-pub fn is_transcription_model_downloaded(models_dir: String) -> bool {- core::is_model_downloaded(models_dir)+#[derive(uniffi::Object)]+pub struct TranscriptionModel {+ inner: core::TranscriptionModel,}#[uniffi::export]-pub fn load_transcription_model(models_dir: String) -> Result<(), TranscriptionError> {- core::load_model(models_dir).map_err(Into::into)-}+impl TranscriptionModel {+ #[uniffi::constructor]+ pub fn new(models_dir: String) -> Arc<Self> {+ Arc::new(Self {+ inner: core::TranscriptionModel::new(models_dir),+ })+ }-#[uniffi::export]-pub fn transcription_model_path(models_dir: String) -> String {- core::model_path(models_dir).to_string_lossy().into_owned()-}+ pub fn is_model_downloaded(&self) -> bool {+ self.inner.is_model_downloaded()+ }-#[uniffi::export]-pub fn transcription_model_size_mb() -> u64 {- core::model_size_mb()-}+ pub fn model_path(&self) -> String {+ self.inner.model_path().to_string_lossy().into_owned()+ }-#[uniffi::export]-pub fn download_transcription_model(- models_dir: String,- callback: Box<dyn TranscriptionModelEventCallback>,-) -> Result<String, TranscriptionError> {- core::download_model(models_dir, |event| callback.on_event(event.into()))- .map(|path| path.to_string_lossy().into_owned())- .map_err(Into::into)-}+ pub fn model_size_mb(&self) -> u64 {+ self.inner.model_size_mb()+ }-#[uniffi::export]-pub fn transcribe_pcm16(- models_dir: String,- vad_cache_dir: String,- input_sample_rate: u32,- pcm_le: Vec<u8>,-) -> Result<String, TranscriptionError> {- core::transcribe_pcm16(models_dir, vad_cache_dir, input_sample_rate, pcm_le).map_err(Into::into)-}+ pub fn download_model(+ &self,+ callback: Box<dyn TranscriptionModelEventCallback>,+ ) -> Result<String, TranscriptionError> {+ self.inner+ .download_model(|event| callback.on_event(event.into()))+ .map(|path| path.to_string_lossy().into_owned())+ .map_err(Into::into)+ }-#[uniffi::export]-pub fn unload_transcription_model() -> Result<(), TranscriptionError> {- core::unload_model().map_err(Into::into)+ pub fn load(&self) -> Result<(), TranscriptionError> {+ self.inner.load().map_err(Into::into)+ }++ pub fn unload(&self) {+ self.inner.unload();+ }++ pub fn transcribe(+ &self,+ input_sample_rate: u32,+ pcm_le: Vec<u8>,+ ) -> Result<String, TranscriptionError> {+ self.inner+ .transcribe(input_sample_rate, pcm_le)+ .map_err(Into::into)+ }}diff --git a/rust/crates/ensu/src/transcription/mod.rs b/rust/crates/ensu/src/transcription/mod.rsindex 9f5efff4b6..fbec0107ce 100644--- a/rust/crates/ensu/src/transcription/mod.rs+++ b/rust/crates/ensu/src/transcription/mod.rs@@ -3,8 +3,8 @@ mod model;mod text;mod transcriber;-pub use model::{ModelEvent, download_model, is_model_downloaded, model_path, model_size_mb};-pub use transcriber::{load_model, transcribe_pcm16, unload_model};+pub use model::ModelEvent;+pub use transcriber::TranscriptionModel;#[derive(Debug, thiserror::Error)]pub enum TranscriptionError {diff --git a/rust/crates/ensu/src/transcription/model.rs b/rust/crates/ensu/src/transcription/model.rsindex d3c5d2d9da..9ae50b2a03 100644--- a/rust/crates/ensu/src/transcription/model.rs+++ b/rust/crates/ensu/src/transcription/model.rs@@ -1,23 +1,21 @@use std::fs;use std::fs::File;-use std::io::{Read, Write};+use std::io::Read;use std::path::{Path, PathBuf};-use std::sync::{Mutex, OnceLock};-use std::time::{Duration, Instant};use flate2::read::GzDecoder;-use reqwest::blocking::Client;-use reqwest::header::RANGE;use tar::Archive;+use crate::download;use crate::transcription::{Result, error};const MODEL_URL: &str = "https://models.ente.io/parakeet-v3-int8.tar.gz";const MODEL_DIR_NAME: &str = "parakeet-tdt-0.6b-v3-int8";+const MODEL_LABEL: &str = "Transcription model";const MODEL_SIZE_MB: u64 = 480;const VAD_MODEL_URL: &str = "https://models.ente.io/silero_vad_v4.onnx";const VAD_MODEL_FILE_NAME: &str = "silero_vad_v4.onnx";-static DOWNLOAD_LOCK: OnceLock<Mutex<()>> = OnceLock::new();+const VAD_LABEL: &str = "Voice activity model";#[derive(Debug, Clone)]pub enum ModelEvent {@@ -34,12 +32,12 @@ pub enum ModelEvent {},}-pub fn is_model_downloaded(models_dir: impl AsRef<Path>) -> bool {+pub(crate) fn is_model_downloaded(models_dir: impl AsRef<Path>) -> bool {let models_dir = models_dir.as_ref();model_path(models_dir).is_dir() && is_file_present(vad_model_path(models_dir))}-pub fn model_path(models_dir: impl AsRef<Path>) -> PathBuf {+pub(crate) fn model_path(models_dir: impl AsRef<Path>) -> PathBuf {models_dir.as_ref().join(MODEL_DIR_NAME)}@@ -47,209 +45,98 @@ pub(crate) fn vad_model_path(models_dir: impl AsRef<Path>) -> PathBuf {models_dir.as_ref().join(VAD_MODEL_FILE_NAME)}-pub fn model_size_mb() -> u64 {+pub(crate) fn model_size_mb() -> u64 {MODEL_SIZE_MB}-pub fn download_model(+pub(crate) fn download_model(models_dir: impl AsRef<Path>,mut on_event: impl FnMut(ModelEvent),) -> Result<PathBuf> {- let _download_guard = DOWNLOAD_LOCK- .get_or_init(|| Mutex::new(()))- .lock()- .map_err(|_| error("Transcription model download lock poisoned"))?;-let models_dir = models_dir.as_ref();fs::create_dir_all(models_dir)?;let final_model_dir = model_path(models_dir);let vad_path = vad_model_path(models_dir);- let partial_path = models_dir.join(format!("{MODEL_DIR_NAME}.partial"));- let extracting_path = models_dir.join(format!("{MODEL_DIR_NAME}.extracting"));+ let archive_path = models_dir.join(format!("{MODEL_DIR_NAME}.tar.gz"));if final_model_dir.is_dir() && is_file_present(&vad_path) {- let _ = fs::remove_file(&partial_path);- on_event(ModelEvent::DownloadComplete);- return Ok(final_model_dir);- }-- let client = Client::builder().build()?;-- if final_model_dir.is_dir() {- let _ = fs::remove_file(&partial_path);- ensure_vad_model(&client, models_dir).map_err(|err| {- let message = err.to_string();- on_event(ModelEvent::DownloadError {- message: message.clone(),- });- error(message)- })?;on_event(ModelEvent::DownloadComplete);return Ok(final_model_dir);}- if extracting_path.exists() {- let _ = fs::remove_dir_all(&extracting_path);+ let need_model = !final_model_dir.is_dir();+ let mut targets = Vec::new();+ if need_model {+ targets.push(download::Target {+ label: MODEL_LABEL.to_string(),+ url: MODEL_URL.to_string(),+ destination_path: archive_path.display().to_string(),+ });}-- let mut resume_from = partial_path.metadata().map(|m| m.len()).unwrap_or(0);- let mut response = request_model(&client, resume_from)?;-- if resume_from > 0 && response.status() == reqwest::StatusCode::OK {- let _ = fs::remove_file(&partial_path);- resume_from = 0;- response = request_model(&client, 0)?;+ if !is_file_present(&vad_path) {+ targets.push(download::Target {+ label: VAD_LABEL.to_string(),+ url: VAD_MODEL_URL.to_string(),+ destination_path: vad_path.display().to_string(),+ });}- if !response.status().is_success() && response.status() != reqwest::StatusCode::PARTIAL_CONTENT- {- let message = format!(- "Failed to download transcription model: HTTP {}",- response.status()- );+ if let Err(message) = download::fetch(+ targets,+ validate_download,+ |progress| {+ on_event(ModelEvent::DownloadProgress {+ downloaded: progress.downloaded_bytes,+ total: progress.total_bytes.unwrap_or(0),+ percentage: progress.percentage,+ });+ },+ || false,+ ) {on_event(ModelEvent::DownloadError {message: message.clone(),});return Err(error(message));}- let total = response- .content_length()- .map(|len| len + resume_from)- .unwrap_or(0);- let mut downloaded = resume_from;- let mut file = if resume_from > 0 {- fs::OpenOptions::new()- .create(true)- .append(true)- .open(&partial_path)?- } else {- File::create(&partial_path)?- };-- on_event(ModelEvent::DownloadProgress {- downloaded,- total,- percentage: percentage(downloaded, total),- });-- let mut last_update = Instant::now();- let mut buffer = [0u8; 128 * 1024];- loop {- let read = response.read(&mut buffer)?;- if read == 0 {- break;- }- file.write_all(&buffer[..read])?;- downloaded += read as u64;-- if last_update.elapsed() >= Duration::from_millis(250) {- on_event(ModelEvent::DownloadProgress {- downloaded,- total,- percentage: percentage(downloaded, total),- });- last_update = Instant::now();- }- }- file.flush()?;- drop(file);-- if total > 0 {- let actual = partial_path.metadata()?.len();- if actual != total {- let _ = fs::remove_file(&partial_path);- let message = format!("Download incomplete: expected {total} bytes, got {actual}");+ if need_model {+ on_event(ModelEvent::ExtractionStarted);+ let extracting_path = models_dir.join(format!("{MODEL_DIR_NAME}.extracting"));+ if let Err(err) = extract_archive(&archive_path, &extracting_path, &final_model_dir) {+ let _ = fs::remove_dir_all(&extracting_path);+ let message = err.to_string();on_event(ModelEvent::DownloadError {message: message.clone(),});return Err(error(message));}+ let _ = fs::remove_file(&archive_path);+ let _ = fs::remove_file(models_dir.join(format!("{MODEL_DIR_NAME}.tar.gz.metadata.json")));+ on_event(ModelEvent::ExtractionCompleted);}- on_event(ModelEvent::ExtractionStarted);- extract_archive(&partial_path, &extracting_path, &final_model_dir).map_err(|err| {- let _ = fs::remove_dir_all(&extracting_path);- let message = err.to_string();- on_event(ModelEvent::DownloadError {- message: message.clone(),- });- error(message)- })?;-- let _ = fs::remove_file(&partial_path);- on_event(ModelEvent::ExtractionCompleted);- ensure_vad_model(&client, models_dir).map_err(|err| {- let message = err.to_string();- on_event(ModelEvent::DownloadError {- message: message.clone(),- });- error(message)- })?;on_event(ModelEvent::DownloadComplete);-Ok(final_model_dir)}-fn request_model(- client: &Client,- resume_from: u64,-) -> reqwest::Result<reqwest::blocking::Response> {- let mut request = client.get(MODEL_URL);- if resume_from > 0 {- request = request.header(RANGE, format!("bytes={resume_from}-"));+fn validate_download(target: &download::Target, path: &Path) -> std::result::Result<(), String> {+ if !is_file_present(path) {+ return Err(format!("{} is empty", path.display()));}- request.send()-}--fn ensure_vad_model(client: &Client, models_dir: &Path) -> Result<()> {- let final_path = vad_model_path(models_dir);- if is_file_present(&final_path) {- return Ok(());+ if target.label == MODEL_LABEL && !looks_like_gzip(path) {+ return Err(format!("{} is not a gzip archive", path.display()));}-- let partial_path = models_dir.join(format!("{VAD_MODEL_FILE_NAME}.partial"));- let result = download_vad_model(client, &partial_path, &final_path);- if result.is_err() {- let _ = fs::remove_file(&partial_path);- }- result+ Ok(())}-fn download_vad_model(client: &Client, partial_path: &Path, final_path: &Path) -> Result<()> {- let mut response = client.get(VAD_MODEL_URL).send()?;- if !response.status().is_success() {- return Err(error(format!(- "Failed to download voice activity model: HTTP {}",- response.status()- )));- }-- let mut file = File::create(partial_path)?;- let total = response.content_length().unwrap_or(0);- let mut downloaded = 0;- let mut buffer = [0u8; 128 * 1024];- loop {- let read = response.read(&mut buffer)?;- if read == 0 {- break;- }- file.write_all(&buffer[..read])?;- downloaded += read as u64;- }- file.flush()?;- drop(file);-- if total > 0 && downloaded != total {- let _ = fs::remove_file(partial_path);- return Err(error(format!(- "Voice activity model download incomplete: expected {total} bytes, got {downloaded}"- )));- }-- fs::rename(partial_path, final_path)?;- Ok(())+fn looks_like_gzip(path: &Path) -> bool {+ let mut file = match File::open(path) {+ Ok(file) => file,+ Err(_) => return false,+ };+ let mut header = [0u8; 2];+ file.read_exact(&mut header).is_ok() && header == [0x1f, 0x8b]}fn extract_archive(@@ -297,11 +184,3 @@ fn is_file_present(path: impl AsRef<Path>) -> bool {.map(|metadata| metadata.is_file() && metadata.len() > 0).unwrap_or(false)}--fn percentage(downloaded: u64, total: u64) -> f64 {- if total == 0 {- 0.0- } else {- (downloaded as f64 / total as f64) * 100.0- }-}diff --git a/rust/crates/ensu/src/transcription/transcriber.rs b/rust/crates/ensu/src/transcription/transcriber.rsindex 108b9f8c55..b7991554cb 100644--- a/rust/crates/ensu/src/transcription/transcriber.rs+++ b/rust/crates/ensu/src/transcription/transcriber.rs@@ -1,61 +1,85 @@use std::path::{Path, PathBuf};-use std::sync::{Mutex, OnceLock};+use std::sync::{Mutex, MutexGuard, PoisonError};use transcribe_rs::onnx::Quantization;use transcribe_rs::onnx::parakeet::{ParakeetModel, ParakeetParams, TimestampGranularity};use crate::transcription::audio::extract_speech_from_pcm16;-use crate::transcription::model::{model_path, vad_model_path};+use crate::transcription::model::{self, ModelEvent};use crate::transcription::text::filter_transcription_output;use crate::transcription::{Result, error};-static MANAGER: OnceLock<Mutex<TranscriptionManager>> = OnceLock::new();+pub struct TranscriptionModel {+ models_dir: PathBuf,+ loaded: Mutex<Option<LoadedModel>>,+}-struct TranscriptionManager {- loaded_path: Option<PathBuf>,- model: Option<ParakeetModel>,+struct LoadedModel {+ path: PathBuf,+ model: ParakeetModel,}-impl TranscriptionManager {- fn new() -> Self {+impl TranscriptionModel {+ pub fn new(models_dir: impl Into<PathBuf>) -> Self {Self {- loaded_path: None,- model: None,+ models_dir: models_dir.into(),+ loaded: Mutex::new(None),}}- fn transcribe(- &mut self,- models_dir: impl AsRef<Path>,- _vad_cache_dir: impl AsRef<Path>,- input_sample_rate: u32,- pcm_le: Vec<u8>,- ) -> Result<String> {+ pub fn is_model_downloaded(&self) -> bool {+ model::is_model_downloaded(&self.models_dir)+ }++ pub fn model_path(&self) -> PathBuf {+ model::model_path(&self.models_dir)+ }++ pub fn model_size_mb(&self) -> u64 {+ model::model_size_mb()+ }++ pub fn download_model(&self, on_event: impl FnMut(ModelEvent)) -> Result<PathBuf> {+ model::download_model(&self.models_dir, on_event)+ }++ pub fn load(&self) -> Result<()> {+ let model_dir = model::model_path(&self.models_dir);+ if !model_dir.is_dir() {+ return Err(error("Transcription model is not downloaded"));+ }+ ensure_loaded(&mut self.lock(), &model_dir)+ }++ pub fn unload(&self) {+ *self.lock() = None;+ }++ pub fn transcribe(&self, input_sample_rate: u32, pcm_le: Vec<u8>) -> Result<String> {if pcm_le.is_empty() {return Ok(String::new());}- let models_dir = models_dir.as_ref();- let model_dir = model_path(models_dir);+ let model_dir = model::model_path(&self.models_dir);if !model_dir.is_dir() {return Err(error("Transcription model is not downloaded"));}- let vad_model_path = vad_model_path(models_dir);+ let vad_model_path = model::vad_model_path(&self.models_dir);if !vad_model_path.is_file() {return Err(error("Voice activity model is not downloaded"));}- self.ensure_loaded(&model_dir)?;-let speech = extract_speech_from_pcm16(&vad_model_path, input_sample_rate, &pcm_le)?;if speech.is_empty() {return Ok(String::new());}- let model = self- .model+ let mut loaded = self.lock();+ ensure_loaded(&mut loaded, &model_dir)?;+ let model = &mut loaded.as_mut()- .ok_or_else(|| error("Transcription model is not loaded"))?;+ .ok_or_else(|| error("Transcription model is not loaded"))?+ .model;let result = model.transcribe_with(&speech,&ParakeetParams {@@ -67,60 +91,20 @@ impl TranscriptionManager {Ok(filter_transcription_output(&result.text))}- fn load(&mut self, models_dir: impl AsRef<Path>) -> Result<()> {- let models_dir = models_dir.as_ref();- let model_dir = model_path(models_dir);- if !model_dir.is_dir() {- return Err(error("Transcription model is not downloaded"));- }-- self.ensure_loaded(&model_dir)- }-- fn ensure_loaded(&mut self, model_dir: &Path) -> Result<()> {- if self.loaded_path.as_deref() == Some(model_dir) && self.model.is_some() {- return Ok(());- }-- let model = ParakeetModel::load(model_dir, &Quantization::Int8)?;- self.loaded_path = Some(model_dir.to_path_buf());- self.model = Some(model);- Ok(())+ fn lock(&self) -> MutexGuard<'_, Option<LoadedModel>> {+ self.loaded.lock().unwrap_or_else(PoisonError::into_inner)}-- fn unload(&mut self) {- self.loaded_path = None;- self.model = None;- }-}--fn manager() -> &'static Mutex<TranscriptionManager> {- MANAGER.get_or_init(|| Mutex::new(TranscriptionManager::new()))}-pub fn transcribe_pcm16(- models_dir: impl AsRef<Path>,- vad_cache_dir: impl AsRef<Path>,- input_sample_rate: u32,- pcm_le: Vec<u8>,-) -> Result<String> {- manager()- .lock()- .map_err(|_| error("transcription manager lock poisoned"))?- .transcribe(models_dir, vad_cache_dir, input_sample_rate, pcm_le)-}--pub fn load_model(models_dir: impl AsRef<Path>) -> Result<()> {- manager()- .lock()- .map_err(|_| error("transcription manager lock poisoned"))?- .load(models_dir)-}+fn ensure_loaded(loaded: &mut Option<LoadedModel>, model_dir: &Path) -> Result<()> {+ if loaded.as_ref().map(|entry| entry.path.as_path()) == Some(model_dir) {+ return Ok(());+ }-pub fn unload_model() -> Result<()> {- manager()- .lock()- .map_err(|_| error("transcription manager lock poisoned"))?- .unload();+ let model = ParakeetModel::load(model_dir, &Quantization::Int8)?;+ *loaded = Some(LoadedModel {+ path: model_dir.to_path_buf(),+ model,+ });Ok(())}