Skip to content
This repository has been archived by the owner on Sep 6, 2024. It is now read-only.

Commit

Permalink
[*] import ui
Browse files Browse the repository at this point in the history
  • Loading branch information
heng30 committed Jan 20, 2024
1 parent 11f41ef commit b4e0d20
Show file tree
Hide file tree
Showing 15 changed files with 96 additions and 49 deletions.
12 changes: 3 additions & 9 deletions transcribe/src/model_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl ModelHandler {
pub fn setup_directory(&self) -> Result<()> {
let path = std::path::Path::new(&self.models_dir);
if !path.exists() {
let _ = std::fs::create_dir_all(path)?;
std::fs::create_dir_all(path)?;
}
Ok(())
}
Expand All @@ -36,10 +36,7 @@ impl ModelHandler {
}

pub fn is_model_existing(&self) -> bool {
match std::fs::metadata(format!("{}/{}", self.models_dir, self.model_name)) {
Ok(_) => true,
Err(_) => false,
}
std::fs::metadata(format!("{}/{}", self.models_dir, self.model_name)).is_ok()
}

pub fn get_model_dir(&self) -> String {
Expand All @@ -62,10 +59,7 @@ pub async fn download_model(
Client::new()
};

let response = client
.get(&url)
.send()
.await?;
let response = client.get(&url).send().await?;

let mut file = std::fs::File::create(format!("{}/{}", models_dir, model_name))?;
let mut content = std::io::Cursor::new(response.bytes().await?);
Expand Down
2 changes: 2 additions & 0 deletions vtbox/src/logic/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ macro_rules! message_info {
};
}

#[allow(dead_code)]
pub fn async_message_warn(ui: Weak<AppWindow>, msg: String) {
let _ = slint::invoke_from_event_loop(move || {
ui.unwrap()
Expand All @@ -34,6 +35,7 @@ pub fn async_message_warn(ui: Weak<AppWindow>, msg: String) {
});
}

#[allow(dead_code)]
pub fn async_message_success(ui: Weak<AppWindow>, msg: String) {
let _ = slint::invoke_from_event_loop(move || {
ui.unwrap()
Expand Down
48 changes: 22 additions & 26 deletions vtbox/src/logic/model.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
use crate::slint_generatedAppWindow::{AppWindow, Logic, ModelItem, Store};
use crate::util::translator::tr;
use crate::{
config,
message::{async_message_success, async_message_warn},
transcribe::model_handler,
util,
};
use crate::{config, message::async_message_warn, util};
use crate::{message_info, message_success, message_warn};
use anyhow::Result;
use native_dialog::FileDialog;
use slint::{ComponentHandle, Model, SharedString, VecModel};
use std::fs;
use tokio::task::spawn;
use transcribe::model_handler;
use uuid::Uuid;

const PREDEFINED_MODELS_V2T: [&str; 5] = [
Expand Down Expand Up @@ -104,7 +100,16 @@ pub fn init(ui: &AppWindow) {
ui.clone(),
format!("{}. {}: {e:?}", tr("下载失败"), tr("原因")),
),
_ => async_message_success(ui.clone(), tr("下载成功")),
_ => {
let _ = slint::invoke_from_event_loop(move || {
let ui = ui.clone().unwrap();
if type_index == ui.get_model_type_index() {
init_model(&ui, type_index);
}

message_success!(ui, tr("下载成功"));
});
}
}
});
});
Expand All @@ -122,7 +127,7 @@ pub fn init(ui: &AppWindow) {
file.file_name().unwrap().to_str().unwrap(),
);

match fs::copy(file, &path) {
match fs::copy(file, path) {
Err(e) => {
message_warn!(&ui, format!("{}. {}: {e:?}", tr("导入失败"), tr("原因")));
}
Expand Down Expand Up @@ -193,7 +198,7 @@ fn model_items(ui: &AppWindow, type_index: i32) -> Result<Vec<ModelItem>> {
model_relative_path(type_index)
);

let mut models = fs::read_dir(path)?
let mut models: Vec<_> = fs::read_dir(path)?
.filter_map(|entry| {
let entry = entry.ok()?;
let path = entry.path();
Expand Down Expand Up @@ -235,31 +240,22 @@ fn is_in_predefined_models(type_index: i32, name: &str) -> bool {
false
}

fn is_in_models(items: &Vec<ModelItem>, name: &str) -> bool {
for item in items.iter() {
if item.name == name {
return true;
}
}

return false;
fn is_in_models(items: &[ModelItem], name: &str) -> bool {
items.iter().any(|item| item.name == name)
}

fn get_model_data(ui: &AppWindow, uuid: &str) -> Option<ModelItem> {
for item in ui.global::<Store>().get_model_datas().iter() {
if item.uuid == uuid {
return Some(item);
}
}

None
ui.global::<Store>()
.get_model_datas()
.iter()
.find(|item| item.uuid == uuid)
}

fn append_undownload_model(type_index: i32, models: &mut Vec<ModelItem>) {
let mut tmp_items = vec![];
if type_index == 0 {
for name in PREDEFINED_MODELS_V2T {
if !is_in_models(&models, name) {
if !is_in_models(models, name) {
tmp_items.push(ModelItem {
uuid: Uuid::new_v4().to_string().into(),
name: name.into(),
Expand All @@ -272,7 +268,7 @@ fn append_undownload_model(type_index: i32, models: &mut Vec<ModelItem>) {
models.append(&mut tmp_items);
}

fn set_combobox_models(ui: &AppWindow, type_index: i32, models: &Vec<ModelItem>) {
fn set_combobox_models(ui: &AppWindow, type_index: i32, models: &[ModelItem]) {
let items = models
.iter()
.map(|item| item.name.clone())
Expand Down
1 change: 1 addition & 0 deletions vtbox/src/logic/ok_cancel_dialog.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::slint_generatedAppWindow::{AppWindow, Logic};
use slint::ComponentHandle;

#[allow(clippy::single_match)]
pub fn init(ui: &AppWindow) {
let ui_handle = ui.as_weak();
ui.global::<Logic>()
Expand Down
40 changes: 36 additions & 4 deletions vtbox/src/logic/v2t.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ use crate::{
message::async_message_warn,
model::model_relative_path,
transcribe::{model_handler, transcriber},
util,
};
use crate::{message_info, message_success, message_warn};
use anyhow::Result;
use chrono::Local;
use native_dialog::FileDialog;
use slint::{ComponentHandle, Model, SharedString};
use tokio::task::spawn;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::task::spawn;

static IS_CONVERTING: AtomicBool = AtomicBool::new(false);

Expand Down Expand Up @@ -59,12 +61,42 @@ pub fn init(ui: &AppWindow) {

message_info!(ui, tr("正在转换..."));

let (ui, model_name, audio_path) =
(ui.as_weak(), model_name.to_string(), audio_path.to_string());
let (ui, ui_timer, model_name, audio_path) = (
ui.as_weak(),
ui.as_weak(),
model_name.to_string(),
audio_path.to_string(),
);

IS_CONVERTING.store(true, Ordering::SeqCst);

spawn(async move {
IS_CONVERTING.store(true, Ordering::SeqCst);
let start_timestamp = Local::now().timestamp();
loop {
if !IS_CONVERTING.load(Ordering::SeqCst) {
return;
}

let diff_timestamp = Local::now().timestamp() - start_timestamp;
let time = match util::time::from_timestamp(diff_timestamp, "%M:%S") {
Ok(v) => v,
Err(e) => {
log::warn!("{e:?}");
return;
}
};

let ui = ui_timer.clone();
let _ = slint::invoke_from_event_loop(move || {
let ui = ui.unwrap();
ui.global::<Store>().set_v2t_convert_time(time.into());
});

tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}
});

spawn(async move {
match inner_start_v2t(&model_name, &audio_path) {
Err(e) => async_message_warn(
ui.clone(),
Expand Down
3 changes: 2 additions & 1 deletion vtbox/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ extern crate serde_derive;
#[macro_use]
extern crate lazy_static;

extern crate transcribe;

mod config;
mod logic;
mod util;
Expand All @@ -20,7 +22,6 @@ use chrono::Local;
use env_logger::fmt::Color as LColor;
use log::debug;
use std::io::Write;
use transcribe;

#[tokio::main]
async fn main() -> Result<()> {
Expand Down
9 changes: 5 additions & 4 deletions vtbox/src/util/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,11 @@ pub fn remove_dir_files(path: &str) -> io::Result<()> {
pub fn filename(path: &str) -> Option<String> {
match Path::new(path).file_name() {
None => None,
Some(v) => match v.to_str() {
None => None,
Some(v) => Some(v.to_string()),
},
Some(v) => v.to_str().map(|v| v.to_string()),
// Some(v) => match v.to_str() {
// None => None,
// Some(v) => Some(v.to_string()),
// },
}
}

Expand Down
9 changes: 8 additions & 1 deletion vtbox/src/util/time.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
use chrono::Local;
use anyhow::{Context, Result};
use chrono::{DateTime, Local, Utc};

pub fn local_now(format: &str) -> String {
return Local::now().format(format).to_string();
}

pub fn from_timestamp(timestamp: i64, format: &str) -> Result<String> {
let dt: DateTime<Utc> = DateTime::<Utc>::from_timestamp(timestamp, 0)
.with_context(|| format!("invalid timestamp: {timestamp}"))?;
Ok(dt.format(format).to_string())
}
2 changes: 1 addition & 1 deletion vtbox/src/version.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
pub static VERSION: &str = "v0.0.4";
pub static VERSION: &str = "v0.0.1";
1 change: 1 addition & 0 deletions vtbox/ui/appwindow.slint
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export component AppWindow inherits Window {
forward-focus: fscope;
title: "vtbox";

in-out property model-type-index <=> panel.model-type-index;
property<length> dialog-max-width: Math.min(root.width * 0.95, Theme.dialog-max-width);

init => { }
Expand Down
2 changes: 2 additions & 0 deletions vtbox/ui/panel/bodyer/model.slint
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { IconBtn } from "../../base/icon-btn.slint";
import { Label } from "../../base/label.slint";

export component Model inherits Rectangle {
in-out property model-type-index <=> type-combox.current-index;

VerticalLayout {
spacing: Theme.spacing * 2;

Expand Down
4 changes: 3 additions & 1 deletion vtbox/ui/panel/bodyer/panel.slint
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import { V2T } from "./v2t.slint";
import { T2V } from "./t2v.slint";

export component Bodyer inherits Rectangle {
Model {
in-out property model-type-index <=> model.model-type-index;

model := Model {
visible: Store.current-panel == "model";
}

Expand Down
5 changes: 5 additions & 0 deletions vtbox/ui/panel/bodyer/v2t.slint
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export component V2T inherits Rectangle {
clicked => {
audio-name-lineedit.text = "";
Store.v2t-text = "";
Store.v2t-convert-time = "00:00";
}
}

Expand All @@ -77,6 +78,10 @@ export component V2T inherits Rectangle {
Logic.start-v2t(model-name-combox.current-value, root.audio-filepath);
}
}

if Store.v2t-convert-time != "" : Label {
text: Store.v2t-convert-time;
}
}
}

Expand Down
2 changes: 2 additions & 0 deletions vtbox/ui/panel/panel.slint
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { Bodyer } from "./bodyer/panel.slint";
import { Divider } from "../base/divider.slint";

export component Panel inherits Rectangle {
in-out property model-type-index <=> bodyer.model-type-index;

header := Header {
x: 0; y: 0; z: 1;
}
Expand Down
5 changes: 3 additions & 2 deletions vtbox/ui/store.slint
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,10 @@ export struct AboutDialog {
}

export global Store {
in-out property<string> current-panel: "v2t";
in-out property <string> current-panel: "v2t";

in-out property <string> v2t-text;
in-out property <string> v2t-convert-time: "00:00";
in-out property <[string]> v2t-models: [
"ggml-tiny.bin",
"ggml-base.bin",
Expand Down Expand Up @@ -82,7 +83,7 @@ export global Store {
ui: {
font-size: "18",
font-family: "SourceHanSerifCN",
win-width: "600",
win-width: "800",
win-height: "500",
language: "cn",
},
Expand Down

0 comments on commit b4e0d20

Please sign in to comment.