Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Tighten download caching and prune dead transcription code

Manav Rathi264b7bac456f
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index fa848b31da..214253f791 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -6926,7 +6926,6 @@ dependencies = [
"base64 0.22.1",
"bytes",
"encoding_rs",
- "futures-channel",
"futures-core",
"futures-util",
"h2",
diff --git a/rust/bindings/uniffi/ensu/src/transcription.rs b/rust/bindings/uniffi/ensu/src/transcription.rs
index 11e184c418..842e545b46 100644
--- a/rust/bindings/uniffi/ensu/src/transcription.rs
+++ b/rust/bindings/uniffi/ensu/src/transcription.rs
@@ -74,14 +74,6 @@ impl Transcriber {
self.inner.is_model_downloaded()
}
- pub fn model_path(&self) -> String {
- self.inner.model_path().to_string_lossy().into_owned()
- }
-
- pub fn model_size_mb(&self) -> u64 {
- self.inner.model_size_mb()
- }
-
pub fn download_model(
&self,
callback: Box<dyn TranscriptionModelEventCallback>,
diff --git a/rust/crates/ensu/Cargo.toml b/rust/crates/ensu/Cargo.toml
index fd88d3a04a..cbd07ed388 100644
--- a/rust/crates/ensu/Cargo.toml
+++ b/rust/crates/ensu/Cargo.toml
@@ -52,7 +52,6 @@ transcription = [
"dep:flate2",
"dep:ort",
"dep:regex",
- "reqwest/blocking",
"dep:rubato",
"dep:tar",
"dep:transcribe-rs",
diff --git a/rust/crates/ensu/src/download.rs b/rust/crates/ensu/src/download.rs
index 7d47c8a07b..00eaf7ea30 100644
--- a/rust/crates/ensu/src/download.rs
+++ b/rust/crates/ensu/src/download.rs
@@ -166,10 +166,13 @@ async fn fetch_async(
.map_err(|err| err.to_string())?;
let download_started_at = Instant::now();
let mut download_probes = Vec::with_capacity(targets.len());
+ let mut cached = Vec::with_capacity(targets.len());
for target in &targets {
let destination = Path::new(&target.destination_path);
- if prepare_cached_download(target, destination, &validate) {
+ let is_cached = prepare_cached_download(target, destination, &validate);
+ cached.push(is_cached);
+ if is_cached {
download_probes.push(DownloadProbe {
content_length: file_size(destination),
supports_ranges: false,
@@ -201,12 +204,13 @@ async fn fetch_async(
let file_states = targets
.iter()
.zip(&download_probes)
- .map(|(target, probe)| {
+ .zip(&cached)
+ .map(|((target, probe), cached)| {
let existing = existing_download_bytes(
target,
Path::new(&target.destination_path),
probe,
- &validate,
+ *cached,
);
FileDownloadState {
downloaded_bytes: probe
@@ -234,13 +238,10 @@ async fn fetch_async(
let mut downloads = Vec::new();
for (index, target) in targets.iter().enumerate() {
- let destination = PathBuf::from(&target.destination_path);
- if destination.exists()
- && download_metadata_matches(&destination, &target.url)
- && validate(target, &destination).is_ok()
- {
+ if cached[index] {
continue;
}
+ let destination = PathBuf::from(&target.destination_path);
let download_probe = download_probes
.get(index)
@@ -1392,7 +1393,7 @@ fn prepare_cached_download(
if !destination.exists() || validate(target, destination).is_err() {
return false;
}
- if read_download_metadata(destination).is_none() {
+ if !metadata_path_for(destination).exists() {
let size = file_size(destination).unwrap_or(0);
let _ = write_download_metadata(destination, target, size, None);
return true;
@@ -1433,7 +1434,10 @@ fn write_download_metadata(
downloaded_at_ms: now_ms(),
};
let text = serde_json::to_string_pretty(&metadata).map_err(|err| err.to_string())?;
- fs::write(metadata_path_for(path), text).map_err(|err| err.to_string())
+ let metadata_path = metadata_path_for(path);
+ let tmp_path = PathBuf::from(format!("{}.tmp", metadata_path.display()));
+ fs::write(&tmp_path, text).map_err(|err| err.to_string())?;
+ fs::rename(&tmp_path, &metadata_path).map_err(|err| err.to_string())
}
fn response_metadata(response: &Response) -> ResponseMetadata {
@@ -1464,7 +1468,7 @@ fn write_range_download_metadata(
fs::write(path, text).map_err(|err| err.to_string())
}
-fn metadata_path_for(path: &Path) -> PathBuf {
+pub(crate) fn metadata_path_for(path: &Path) -> PathBuf {
PathBuf::from(format!("{}.metadata.json", path.display()))
}
@@ -1488,16 +1492,13 @@ fn existing_download_bytes(
target: &Target,
destination: &Path,
probe: &DownloadProbe,
- validate: &impl Fn(&Target, &Path) -> Result<(), String>,
+ cached: bool,
) -> u64 {
+ if cached {
+ return file_size(destination).unwrap_or(0);
+ }
if destination.exists() {
- return if download_metadata_matches(destination, &target.url)
- && validate(target, destination).is_ok()
- {
- file_size(destination).unwrap_or(0)
- } else {
- 0
- };
+ return 0;
}
if range_metadata_path_for(destination).exists() {
@@ -1976,6 +1977,45 @@ mod tests {
let _ = fs::remove_dir_all(test_dir);
}
+ #[test]
+ fn existing_file_with_corrupt_sidecar_is_redownloaded() {
+ let bytes = Arc::new(sample_bytes(512));
+ let get_count = Arc::new(AtomicUsize::new(0));
+
+ let server = {
+ let bytes = Arc::clone(&bytes);
+ let get_count = Arc::clone(&get_count);
+ TestServer::spawn(move |stream| {
+ handle_no_range_test_request(stream, Arc::clone(&bytes), Arc::clone(&get_count));
+ })
+ };
+
+ let test_dir = scratch_dir("corrupt-sidecar-download");
+ let destination = test_dir.join("model.bin");
+ fs::write(&destination, bytes.as_slice()).expect("place existing file");
+ fs::write(metadata_path_for(&destination), "{ truncated").expect("write corrupt sidecar");
+
+ let target = Target {
+ label: "Model".to_string(),
+ url: server.url("/model.bin"),
+ destination_path: destination.display().to_string(),
+ };
+
+ fetch(vec![target], |_, _| Ok(()), |_| {}, || false).expect("fetch redownloads");
+
+ assert_eq!(
+ get_count.load(Ordering::SeqCst),
+ 1,
+ "a corrupt sidecar must trigger a re-download, not adoption"
+ );
+ assert_eq!(
+ fs::read(&destination).expect("read downloaded file"),
+ *bytes
+ );
+
+ let _ = fs::remove_dir_all(test_dir);
+ }
+
#[test]
fn existing_file_with_stale_sidecar_is_redownloaded() {
let bytes = Arc::new(sample_bytes(512));
diff --git a/rust/crates/ensu/src/transcription/mod.rs b/rust/crates/ensu/src/transcription/mod.rs
index 2942d7689d..b421bea94b 100644
--- a/rust/crates/ensu/src/transcription/mod.rs
+++ b/rust/crates/ensu/src/transcription/mod.rs
@@ -18,12 +18,6 @@ impl From<std::io::Error> for TranscriptionError {
}
}
-impl From<reqwest::Error> for TranscriptionError {
- fn from(value: reqwest::Error) -> Self {
- Self::Message(value.to_string())
- }
-}
-
impl From<transcribe_rs::TranscribeError> for TranscriptionError {
fn from(value: transcribe_rs::TranscribeError) -> Self {
Self::Message(value.to_string())
diff --git a/rust/crates/ensu/src/transcription/model.rs b/rust/crates/ensu/src/transcription/model.rs
index 3e5cd360c0..4ccc2084ad 100644
--- a/rust/crates/ensu/src/transcription/model.rs
+++ b/rust/crates/ensu/src/transcription/model.rs
@@ -12,7 +12,6 @@ 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";
const VAD_LABEL: &str = "Voice activity model";
@@ -45,16 +44,14 @@ pub(crate) fn vad_model_path(models_dir: impl AsRef<Path>) -> PathBuf {
models_dir.as_ref().join(VAD_MODEL_FILE_NAME)
}
-pub(crate) fn model_size_mb() -> u64 {
- MODEL_SIZE_MB
-}
-
pub(crate) fn download_model(
models_dir: impl AsRef<Path>,
mut on_event: impl FnMut(ModelEvent),
) -> Result<PathBuf> {
let models_dir = models_dir.as_ref();
fs::create_dir_all(models_dir)?;
+ let _ = fs::remove_file(models_dir.join(format!("{MODEL_DIR_NAME}.partial")));
+ let _ = fs::remove_file(models_dir.join(format!("{VAD_MODEL_FILE_NAME}.partial")));
let final_model_dir = model_path(models_dir);
let vad_path = vad_model_path(models_dir);
@@ -105,7 +102,7 @@ pub(crate) fn download_model(
let extracting_path = models_dir.join(format!("{MODEL_DIR_NAME}.extracting"));
let extract_result = extract_archive(&archive_path, &extracting_path, &final_model_dir);
let _ = fs::remove_file(&archive_path);
- let _ = fs::remove_file(models_dir.join(format!("{MODEL_DIR_NAME}.tar.gz.metadata.json")));
+ let _ = fs::remove_file(download::metadata_path_for(&archive_path));
if let Err(err) = extract_result {
let _ = fs::remove_dir_all(&extracting_path);
let message = err.to_string();
@@ -125,7 +122,7 @@ fn validate_download(target: &download::Target, path: &Path) -> std::result::Res
if !is_file_present(path) {
return Err(format!("{} is empty", path.display()));
}
- if target.label == MODEL_LABEL && !looks_like_gzip(path) {
+ if target.destination_path.ends_with(".tar.gz") && !looks_like_gzip(path) {
return Err(format!("{} is not a gzip archive", path.display()));
}
Ok(())
diff --git a/rust/crates/ensu/src/transcription/transcriber.rs b/rust/crates/ensu/src/transcription/transcriber.rs
index 29002885ab..4c74a26803 100644
--- a/rust/crates/ensu/src/transcription/transcriber.rs
+++ b/rust/crates/ensu/src/transcription/transcriber.rs
@@ -12,12 +12,7 @@ use crate::transcription::{Result, error};
pub struct Transcriber {
models_dir: PathBuf,
download_lock: Mutex<()>,
- loaded: Mutex<Option<LoadedModel>>,
-}
-
-struct LoadedModel {
- path: PathBuf,
- model: ParakeetModel,
+ loaded: Mutex<Option<ParakeetModel>>,
}
impl Transcriber {
@@ -33,14 +28,6 @@ impl Transcriber {
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> {
let _guard = self
.download_lock
@@ -50,11 +37,9 @@ impl Transcriber {
}
pub fn load_model(&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)
+ let model_dir = self.downloaded_model_dir()?;
+ ensure_loaded(&mut self.lock(), &model_dir)?;
+ Ok(())
}
pub fn unload_model(&self) {
@@ -66,10 +51,7 @@ impl Transcriber {
return Ok(String::new());
}
- let model_dir = model::model_path(&self.models_dir);
- if !model_dir.is_dir() {
- return Err(error("Transcription model is not downloaded"));
- }
+ let model_dir = self.downloaded_model_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"));
@@ -81,11 +63,7 @@ impl Transcriber {
}
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"))?
- .model;
+ let model = ensure_loaded(&mut loaded, &model_dir)?;
let result = model.transcribe_with(
&speech,
&ParakeetParams {
@@ -97,20 +75,25 @@ impl Transcriber {
Ok(filter_transcription_output(&result.text))
}
- fn lock(&self) -> MutexGuard<'_, Option<LoadedModel>> {
+ fn downloaded_model_dir(&self) -> Result<PathBuf> {
+ let model_dir = model::model_path(&self.models_dir);
+ if !model_dir.is_dir() {
+ return Err(error("Transcription model is not downloaded"));
+ }
+ Ok(model_dir)
+ }
+
+ fn lock(&self) -> MutexGuard<'_, Option<ParakeetModel>> {
self.loaded.lock().unwrap_or_else(PoisonError::into_inner)
}
}
-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(());
+fn ensure_loaded<'a>(
+ loaded: &'a mut Option<ParakeetModel>,
+ model_dir: &Path,
+) -> Result<&'a mut ParakeetModel> {
+ match loaded {
+ Some(model) => Ok(model),
+ slot => Ok(slot.insert(ParakeetModel::load(model_dir, &Quantization::Int8)?)),
}
-
- let model = ParakeetModel::load(model_dir, &Quantization::Int8)?;
- *loaded = Some(LoadedModel {
- path: model_dir.to_path_buf(),
- model,
- });
- Ok(())
}