Skip to content

Commit

Permalink
refactor app backend
Browse files Browse the repository at this point in the history
  • Loading branch information
thewh1teagle committed Apr 12, 2024
1 parent ab59b3c commit a2cc5c4
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 138 deletions.
7 changes: 1 addition & 6 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,7 @@ async fn main() -> Result<()> {
let mut downloader = vibe::downloader::Downloader::new();
if !vibe::config::get_model_path()?.exists() {
downloader
.download(
vibe::config::URL,
vibe::config::get_model_path()?,
Some(""),
on_download_progress,
)
.download(vibe::config::URL, vibe::config::get_model_path()?, on_download_progress)
.await?;
pb.finish_with_message("Download complete");
}
Expand Down
15 changes: 2 additions & 13 deletions core/src/downloader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ impl Downloader {
Downloader { client }
}

pub async fn download<F, Fut>(&mut self, url: &str, path: PathBuf, _: Option<&str>, on_progress: F) -> Result<()>
pub async fn download<F, Fut>(&mut self, url: &str, path: PathBuf, on_progress: F) -> Result<()>
where
F: Fn(u64, u64) -> Fut,
Fut: Future<Output = ()>,
Expand All @@ -43,18 +43,7 @@ impl Downloader {
callback_offset = downloaded;
}
downloaded += chunk.len() as u64;

// for testing
// break;
}
// check hash
// if let Some(hash) = hash {
// let new_hash = integrity::fast_hash(path)?;
// // for testing comment out
// if new_hash != hash {
// bail!("Invalid hash!");
// }
// }
Ok(())
}
}
Expand All @@ -75,7 +64,7 @@ mod tests {
init();
let mut d = downloader::Downloader::new();
let filepath = config::get_model_path()?;
d.download(config::URL, filepath, Some(config::HASH), on_download_progress)
d.download(config::URL, filepath, on_download_progress)
.await
.context("Cant download")?;
Ok(())
Expand Down
41 changes: 0 additions & 41 deletions core/src/integrity.rs

This file was deleted.

1 change: 0 additions & 1 deletion core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,3 @@ pub mod downloader;
pub mod language;
pub mod model;
pub mod transcript;
pub mod integrity;
12 changes: 5 additions & 7 deletions core/src/model.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
use std::sync::Mutex;
use std::time::Instant;

use anyhow::{bail, Context, Ok, Result};
use log::debug;
use whisper_rs::{FullParams, SamplingStrategy, WhisperContext, WhisperContextParameters};

use crate::audio;
use crate::config::ModelArgs;
use crate::transcript::{Transcript, Utternace};
use anyhow::{bail, Context, Ok, Result};
use log::debug;
use once_cell;
use std::sync::Mutex;
use std::time::Instant;
use whisper_rs::{FullParams, SamplingStrategy, WhisperContext, WhisperContextParameters};

static ON_PROGRESS_CHANGE: once_cell::sync::Lazy<Mutex<Option<Box<dyn Fn(i32) + Send + Sync>>>> =
once_cell::sync::Lazy::new(|| Mutex::new(None));
Expand Down
22 changes: 10 additions & 12 deletions core/src/transcript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,18 +46,16 @@ impl Transcript {
}

pub fn as_vtt(&self) -> String {
self.utterances
.iter()
.fold(String::new(), |transcript, fragment| {
transcript
+ format!(
"{} --> {}\n{}\n",
format_timestamp(fragment.start, false, "."),
format_timestamp(fragment.stop, false, "."),
fragment.text.trim().replace("-->", "->")
)
.as_str()
})
self.utterances.iter().fold(String::new(), |transcript, fragment| {
transcript
+ format!(
"{} --> {}\n{}\n",
format_timestamp(fragment.start, false, "."),
format_timestamp(fragment.stop, false, "."),
fragment.text.trim().replace("-->", "->")
)
.as_str()
})
}

pub fn as_srt(&self) -> String {
Expand Down
50 changes: 50 additions & 0 deletions desktop/src-tauri/src/cmd.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use crate::{config, pretty_error, APP_ASYNC_STATIC, APP_STATIC};
use log;
use tauri::Manager;
use vibe::transcript::Transcript;

fn on_transcribe_progress(progress: i32) {
if let Some(app) = &*APP_STATIC.lock().unwrap() {
log::debug!("desktop progress is {}", progress);
let window = app.get_webview_window("main").unwrap();
window.emit("transcribe_progress", progress).unwrap();
} else {
log::error!("App instance not available");
}
}

async fn on_download_progress(current: u64, total: u64) {
if let Some(app) = APP_ASYNC_STATIC.lock().await.as_ref() {
let window: tauri::WebviewWindow = app.get_webview_window("main").unwrap();
window.emit("download_progress", (current, total)).unwrap();
} else {
log::error!("App instance not available");
}
}

#[tauri::command]
pub async fn download_model() -> Result<(), String> {
let model_path = vibe::config::get_model_path().map_err(|e| pretty_error!(e))?;
let mut downloader = vibe::downloader::Downloader::new();
log::debug!("Download model invoked! with path {}", model_path.display());
downloader
.download(config::URL, model_path.to_owned(), on_download_progress)
.await
.map_err(|e| pretty_error!(e))?;
Ok(())
}

#[tauri::command]
pub async fn get_default_model_path() -> Result<String, String> {
let model_path = vibe::config::get_model_path().map_err(|e| pretty_error!(e))?;
let model_path = model_path.to_str().ok_or("cant convert model path to string")?;
Ok(model_path.to_string())
}

#[tauri::command]
pub async fn transcribe(options: vibe::config::ModelArgs) -> Result<Transcript, String> {
let transcript = vibe::model::transcribe(&options, Some(on_transcribe_progress))
.map_err(|e| pretty_error!(e))
.map_err(|e| format!("{:?}\noptions: {:?}", e, options))?;
Ok(transcript)
}
1 change: 0 additions & 1 deletion desktop/src-tauri/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use vibe;

pub const URL: &str = vibe::config::URL;
pub const HASH: &str = ""; // TODO
75 changes: 18 additions & 57 deletions desktop/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,66 +1,15 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use tauri::Manager;
mod cmd;
mod config;
mod errors;
use env_logger;
use log;
use std::sync::Mutex;
use tauri::Manager;
use vibe::transcript::Transcript;

static APP_INSTANCE: once_cell::sync::Lazy<Mutex<Option<tauri::AppHandle>>> = once_cell::sync::Lazy::new(|| Mutex::new(None));
static APP_ASYNC_INSTANCE: once_cell::sync::Lazy<tokio::sync::Mutex<Option<tauri::AppHandle>>> =
pub static APP_ASYNC_STATIC: once_cell::sync::Lazy<tokio::sync::Mutex<Option<tauri::AppHandle>>> =
once_cell::sync::Lazy::new(|| tokio::sync::Mutex::new(None));

fn on_transcribe_progress(progress: i32) {
if let Some(app) = APP_INSTANCE.lock().unwrap().as_ref() {
log::debug!("desktop progress is {}", progress);
let window = app.get_webview_window("main").unwrap();
window.emit("transcribe_progress", progress).unwrap();
} else {
log::error!("App instance not available");
}
}

async fn on_download_progress(current: u64, total: u64) {
if let Some(app) = APP_ASYNC_INSTANCE.lock().await.as_ref() {
let window: tauri::WebviewWindow = app.get_webview_window("main").unwrap();
window.emit("download_progress", (current, total)).unwrap();
} else {
log::error!("App instance not available");
}
}

#[tauri::command]
async fn download_model(app: tauri::AppHandle) -> Result<(), String> {
*APP_ASYNC_INSTANCE.lock().await = Some(app.clone());
let model_path = vibe::config::get_model_path().map_err(|e| pretty_error!(e))?;
let mut downloader = vibe::downloader::Downloader::new();
log::debug!("Download model invoked! with path {}", model_path.display());
downloader
.download(config::URL, model_path.to_owned(), Some(config::HASH), on_download_progress)
.await
.map_err(|e| pretty_error!(e))?;
Ok(())
}

#[tauri::command]
async fn get_default_model_path() -> Result<String, String> {
let model_path = vibe::config::get_model_path().map_err(|e| pretty_error!(e))?;
let model_path = model_path.to_str().ok_or("cant convert model path to string")?;
Ok(model_path.to_string())
}

#[tauri::command]
async fn transcribe(app: tauri::AppHandle, options: vibe::config::ModelArgs) -> Result<Transcript, String> {
// Store the app instance in the global static variable
*APP_INSTANCE.lock().unwrap() = Some(app.clone());
let transcript = vibe::model::transcribe(&options, Some(on_transcribe_progress))
.map_err(|e| pretty_error!(e))
.map_err(|e| format!("{:?}\noptions: {:?}", e, options))?;
Ok(transcript)
}
pub static APP_STATIC: once_cell::sync::Lazy<std::sync::Mutex<Option<tauri::AppHandle>>> =
once_cell::sync::Lazy::new(|| std::sync::Mutex::new(None));

fn main() {
env_logger::init();
Expand All @@ -73,7 +22,19 @@ fn main() {
.plugin(tauri_plugin_updater::Builder::default().build())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_shell::init())
.invoke_handler(tauri::generate_handler![transcribe, download_model, get_default_model_path])
.setup(|app| {
let app_handle = app.app_handle();
tauri::async_runtime::block_on(async {
*APP_ASYNC_STATIC.lock().await = Some(app_handle.to_owned());
});
*APP_STATIC.lock().unwrap() = Some(app_handle.to_owned());
Ok(())
})
.invoke_handler(tauri::generate_handler![
cmd::transcribe,
cmd::download_model,
cmd::get_default_model_path
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

0 comments on commit a2cc5c4

Please sign in to comment.