Skip to content

armgit / Handy

Public Imported from GitHub
0

A free, open source, and extensible speech-to-text application that works completely offline.

feat: transcribe files into history (#2315)

CJ Pais73c095857bc4
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 0fd5691e..bc166d43 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2489,6 +2489,7 @@ dependencies = [
"regex",
"reqwest 0.12.28",
"rodio",
+ "rubato",
"rusqlite",
"rusqlite_migration",
"rustfft",
@@ -2499,6 +2500,7 @@ dependencies = [
"specta",
"specta-typescript",
"strsim",
+ "symphonia",
"sys-locale",
"tauri",
"tauri-build",
@@ -6073,9 +6075,14 @@ dependencies = [
"lazy_static",
"symphonia-bundle-flac",
"symphonia-bundle-mp3",
+ "symphonia-codec-aac",
+ "symphonia-codec-adpcm",
+ "symphonia-codec-alac",
"symphonia-codec-pcm",
"symphonia-codec-vorbis",
"symphonia-core",
+ "symphonia-format-isomp4",
+ "symphonia-format-mkv",
"symphonia-format-ogg",
"symphonia-format-riff",
"symphonia-metadata",
@@ -6105,6 +6112,37 @@ dependencies = [
"symphonia-metadata",
]
+[[package]]
+name = "symphonia-codec-aac"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c263845aa86881416849c1729a54c7f55164f8b96111dba59de46849e73a790"
+dependencies = [
+ "lazy_static",
+ "log",
+ "symphonia-core",
+]
+
+[[package]]
+name = "symphonia-codec-adpcm"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2dddc50e2bbea4cfe027441eece77c46b9f319748605ab8f3443350129ddd07f"
+dependencies = [
+ "log",
+ "symphonia-core",
+]
+
+[[package]]
+name = "symphonia-codec-alac"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8413fa754942ac16a73634c9dfd1500ed5c61430956b33728567f667fdd393ab"
+dependencies = [
+ "log",
+ "symphonia-core",
+]
+
[[package]]
name = "symphonia-codec-pcm"
version = "0.5.5"
@@ -6139,6 +6177,32 @@ dependencies = [
"log",
]
+[[package]]
+name = "symphonia-format-isomp4"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "243739585d11f81daf8dac8d9f3d18cc7898f6c09a259675fc364b382c30e0a5"
+dependencies = [
+ "encoding_rs",
+ "log",
+ "symphonia-core",
+ "symphonia-metadata",
+ "symphonia-utils-xiph",
+]
+
+[[package]]
+name = "symphonia-format-mkv"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "122d786d2c43a49beb6f397551b4a050d8229eaa54c7ddf9ee4b98899b8742d0"
+dependencies = [
+ "lazy_static",
+ "log",
+ "symphonia-core",
+ "symphonia-metadata",
+ "symphonia-utils-xiph",
+]
+
[[package]]
name = "symphonia-format-ogg"
version = "0.5.5"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 94c0c33a..420c5ec5 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -56,6 +56,11 @@ earshot = "1.2.2"
enigo = "0.6.1"
# Feedback sounds. No `recording`: microphone capture is handy-recorder's.
rodio = { version = "0.23.0", default-features = false, features = ["playback", "wav", "flac", "mp3", "vorbis"] }
+# Decodes files for transcription. rodio's version, plus the M4A/MP4 (AAC,
+# ALAC) and AIFF support rodio leaves out.
+symphonia = { version = "0.5.5", features = ["aac", "alac", "isomp4", "mp3", "aiff"] }
+# Resamples a decoded file to 16 kHz; the version handy-recorder already uses.
+rubato = "5"
handy-recorder = "0.1"
reqwest = { version = "0.12", features = ["json", "stream", "gzip", "brotli", "deflate"] }
futures-util = "0.3"
diff --git a/src-tauri/src/audio_toolkit/audio/decode.rs b/src-tauri/src/audio_toolkit/audio/decode.rs
new file mode 100644
index 00000000..b5ed0ed8
--- /dev/null
+++ b/src-tauri/src/audio_toolkit/audio/decode.rs
@@ -0,0 +1,306 @@
+//! Decodes a file's audio (or a video's sound track) to 16 kHz mono, the
+//! format every recording is transcribed and kept in.
+
+use anyhow::{anyhow, Context, Result};
+use log::{debug, warn};
+use rubato::audioadapter_buffers::direct::InterleavedSlice;
+use rubato::{Fft, FixedSync, Indexing, Resampler};
+use std::fs::File;
+use std::path::Path;
+use symphonia::core::audio::SampleBuffer;
+use symphonia::core::codecs::{DecoderOptions, CODEC_TYPE_NULL};
+use symphonia::core::errors::Error as SymphoniaError;
+use symphonia::core::formats::FormatOptions;
+use symphonia::core::io::MediaSourceStream;
+use symphonia::core::meta::MetadataOptions;
+use symphonia::core::probe::Hint;
+
+use crate::audio_toolkit::constants::WHISPER_SAMPLE_RATE;
+
+/// Frames the resampler takes per step.
+const RESAMPLER_CHUNK_FRAMES: usize = 1024;
+
+/// The whole of `path`'s first audio track, downmixed to mono and resampled
+/// to 16 kHz.
+pub fn decode_audio_file(path: &Path) -> Result<Vec<f32>> {
+ let file = File::open(path).with_context(|| format!("Failed to open {}", path.display()))?;
+ let source = MediaSourceStream::new(Box::new(file), Default::default());
+ let mut hint = Hint::new();
+ if let Some(extension) = path.extension().and_then(|e| e.to_str()) {
+ hint.with_extension(extension);
+ }
+ let mut format = symphonia::default::get_probe()
+ .format(
+ &hint,
+ source,
+ &FormatOptions::default(),
+ &MetadataOptions::default(),
+ )
+ .map_err(|e| anyhow!("Not a supported audio or video file: {}", e))?
+ .format;
+ let track = format
+ .tracks()
+ .iter()
+ .find(|t| t.codec_params.codec != CODEC_TYPE_NULL)
+ .ok_or_else(|| anyhow!("The file has no audio track"))?;
+ let track_id = track.id;
+ let mut decoder = symphonia::default::get_codecs()
+ .make(&track.codec_params, &DecoderOptions::default())
+ .map_err(|e| anyhow!("The file's audio format is not supported: {}", e))?;
+
+ // Built on the first packet, which gives the sample rate.
+ let mut resampled: Option<Resampled> = None;
+ let mut buffer: Option<SampleBuffer<f32>> = None;
+
+ loop {
+ let packet = match format.next_packet() {
+ Ok(packet) => packet,
+ // The end of the stream.
+ Err(SymphoniaError::IoError(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
+ break
+ }
+ Err(e) => return Err(anyhow!("Failed to read the file: {}", e)),
+ };
+ if packet.track_id() != track_id {
+ continue;
+ }
+ let decoded = match decoder.decode(&packet) {
+ Ok(decoded) => decoded,
+ // A damaged packet loses only its own audio.
+ Err(SymphoniaError::DecodeError(e)) => {
+ warn!("Skipping an undecodable packet: {}", e);
+ continue;
+ }
+ Err(e) => return Err(anyhow!("Failed to decode the file: {}", e)),
+ };
+ let spec = *decoded.spec();
+ let channels = spec.channels.count().max(1);
+ let resampled = match &mut resampled {
+ None => resampled.insert(Resampled::new(spec.rate)?),
+ Some(r) if r.rate != spec.rate => {
+ return Err(anyhow!("The file's sample rate changes partway through"));
+ }
+ Some(r) => r,
+ };
+ let packet_frames = decoded.capacity() as u64;
+ if buffer
+ .as_ref()
+ .is_none_or(|b| b.capacity() < decoded.capacity() * channels)
+ {
+ buffer = Some(SampleBuffer::new(packet_frames, spec));
+ }
+ let buffer = buffer.as_mut().expect("buffer was just sized");
+ buffer.copy_interleaved_ref(decoded);
+ resampled.push(
+ buffer
+ .samples()
+ .chunks_exact(channels)
+ .map(|frame| frame.iter().sum::<f32>() / channels as f32),
+ )?;
+ }
+
+ let resampled = resampled.ok_or_else(|| anyhow!("The file has no audio"))?;
+ debug!(
+ "Decoded {:.1}s of audio at {} Hz from {}",
+ resampled.input_len as f64 / resampled.rate as f64,
+ resampled.rate,
+ path.display()
+ );
+ resampled.finish()
+}
+
+/// Mono audio at the file's rate in, 16 kHz out, one resampler step at a
+/// time, so the file's audio is never held whole at its own rate.
+struct Resampled {
+ rate: u32,
+ /// Input frames taken in so far.
+ input_len: usize,
+ /// `None` when the file is already at 16 kHz.
+ stage: Option<Stage>,
+ output: Vec<f32>,
+}
+
+struct Stage {
+ resampler: Fft<f32>,
+ /// Input not yet resampled: less than one step, plus the latest packet.
+ pending: Vec<f32>,
+ /// One step's output.
+ scratch: Vec<f32>,
+ /// Output frames of the resampler's delay still to drop.
+ delay_left: usize,
+}
+
+impl Resampled {
+ fn new(rate: u32) -> Result<Self> {
+ let target = WHISPER_SAMPLE_RATE as usize;
+ let stage = if rate as usize == target {
+ None
+ } else {
+ let resampler = Fft::<f32>::new(
+ rate as usize,
+ target,
+ RESAMPLER_CHUNK_FRAMES,
+ 1,
+ FixedSync::Input,
+ )
+ .map_err(|e| anyhow!("Failed to set up resampling from {} Hz: {}", rate, e))?;
+ Some(Stage {
+ pending: Vec::with_capacity(2 * resampler.input_frames_max()),
+ scratch: vec![0.0; resampler.output_frames_max()],
+ delay_left: resampler.output_delay(),
+ resampler,
+ })
+ };
+ Ok(Self {
+ rate,
+ input_len: 0,
+ stage,
+ output: Vec::new(),
+ })
+ }
+
+ /// The 16 kHz length of `input_len` frames at the file's rate.
+ fn expected_len(&self, input_len: usize) -> usize {
+ match &self.stage {
+ Some(stage) => (stage.resampler.resample_ratio() * input_len as f64).ceil() as usize,
+ None => input_len,
+ }
+ }
+
+ fn push(&mut self, samples: impl Iterator<Item = f32>) -> Result<()> {
+ let Some(stage) = self.stage.as_mut() else {
+ let before = self.output.len();
+ self.output.extend(samples);
+ self.input_len += self.output.len() - before;
+ return Ok(());
+ };
+ let before = stage.pending.len();
+ stage.pending.extend(samples);
+ self.input_len += stage.pending.len() - before;
+ let mut taken = 0;
+ while stage.pending.len() - taken >= stage.resampler.input_frames_next() {
+ taken += stage.step(taken, None, &mut self.output)?;
+ }
+ stage.pending.drain(..taken);
+ Ok(())
+ }
+
+ fn finish(mut self) -> Result<Vec<f32>> {
+ let expected = self.expected_len(self.input_len);
+ let Some(mut stage) = self.stage.take() else {
+ return Ok(self.output);
+ };
+ let left = stage.pending.len();
+ if left > 0 {
+ stage.step(0, Some(left), &mut self.output)?;
+ }
+ // The resampler holds back its delay's worth; silence pushes it out.
+ while self.output.len() < expected {
+ stage.step(0, Some(0), &mut self.output)?;
+ }
+ self.output.truncate(expected);
+ Ok(self.output)
+ }
+}
+
+impl Stage {
+ /// Resamples one step of `pending` from `offset` (or only `partial` of
+ /// it, padded with silence) into `output`. Returns the frames it took.
+ fn step(
+ &mut self,
+ offset: usize,
+ partial: Option<usize>,
+ output: &mut Vec<f32>,
+ ) -> Result<usize> {
+ let input = InterleavedSlice::new(&self.pending[..], 1, self.pending.len())
+ .map_err(|e| anyhow!("Failed to resample: {}", e))?;
+ let scratch_len = self.scratch.len();
+ let mut out = InterleavedSlice::new_mut(&mut self.scratch[..], 1, scratch_len)
+ .map_err(|e| anyhow!("Failed to resample: {}", e))?;
+ let mut indexing = Indexing::new().input_offset(offset);
+ indexing.partial_len = partial;
+ let (taken, produced) = self
+ .resampler
+ .process_into_buffer(&input, &mut out, Some(&indexing))
+ .map_err(|e| anyhow!("Failed to resample: {}", e))?;
+ let dropped = self.delay_left.min(produced);
+ self.delay_left -= dropped;
+ output.extend_from_slice(&self.scratch[dropped..produced]);
+ Ok(taken)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use hound::{SampleFormat, WavSpec, WavWriter};
+
+ #[test]
+ fn stereo_44k_file_becomes_16k_mono() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("stereo.wav");
+ let spec = WavSpec {
+ channels: 2,
+ sample_rate: 44_100,
+ bits_per_sample: 16,
+ sample_format: SampleFormat::Int,
+ };
+ let mut writer = WavWriter::create(&path, spec).unwrap();
+ for sample in tone(44_100, 88_200) {
+ let value = (sample * i16::MAX as f32) as i16;
+ writer.write_sample(value).unwrap();
+ writer.write_sample(value).unwrap();
+ }
+ writer.finalize().unwrap();
+
+ let samples = decode_audio_file(&path).unwrap();
+
+ assert_eq!(samples.len(), 32_000);
+ let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs()));
+ assert!((0.4..0.6).contains(&peak), "peak {}", peak);
+ }
+
+ fn resample_in_packets(mono: &[f32], rate: u32, packet: usize) -> Vec<f32> {
+ let mut resampled = Resampled::new(rate).unwrap();
+ for chunk in mono.chunks(packet) {
+ resampled.push(chunk.iter().copied()).unwrap();
+ }
+ resampled.finish().unwrap()
+ }
+
+ fn tone(rate: u32, frames: usize) -> Vec<f32> {
+ (0..frames)
+ .map(|i| (i as f32 / rate as f32 * 440.0 * std::f32::consts::TAU).sin() * 0.5)
+ .collect()
+ }
+
+ #[test]
+ fn resampling_keeps_length_and_timing_whatever_the_packet_size() {
+ for rate in [16_000, 44_100, 48_000] {
+ for frames in [500, rate as usize + 337] {
+ let mono = tone(rate, frames);
+ let whole = resample_in_packets(&mono, rate, frames);
+ let expected_len = (frames as f64 * 16_000.0 / rate as f64).ceil() as usize;
+ assert_eq!(whole.len(), expected_len, "{} Hz, {} frames", rate, frames);
+ for packet in [333, 4096] {
+ assert_eq!(resample_in_packets(&mono, rate, packet), whole);
+ }
+ // Delay trimmed: within half a sample of the 16 kHz tone.
+ let reference = tone(16_000, whole.len());
+ let interior = 100..whole.len().saturating_sub(100);
+ let max_error = interior
+ .map(|i| (whole[i] - reference[i]).abs())
+ .fold(0.0f32, f32::max);
+ assert!(max_error < 0.04, "{} Hz: error {}", rate, max_error);
+ }
+ }
+ }
+
+ #[test]
+ fn a_file_that_is_not_audio_fails_to_decode() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("notes.txt");
+ std::fs::write(&path, "not audio at all").unwrap();
+ assert!(decode_audio_file(&path).is_err());
+ }
+}
diff --git a/src-tauri/src/audio_toolkit/audio/mod.rs b/src-tauri/src/audio_toolkit/audio/mod.rs
index 0a21c9cb..3b3d114a 100644
--- a/src-tauri/src/audio_toolkit/audio/mod.rs
+++ b/src-tauri/src/audio_toolkit/audio/mod.rs
@@ -1,9 +1,11 @@
// Re-export all audio components
+mod decode;
mod device;
mod sink;
mod utils;
mod visualizer;
+pub use decode::decode_audio_file;
pub use device::{list_output_devices, output_device_name, OutputDeviceInfo};
pub use sink::{
AudioFrameCallback, CaptureSink, CaptureVad, CapturedAudio, LevelCallback, VadPolicy,
diff --git a/src-tauri/src/audio_toolkit/mod.rs b/src-tauri/src/audio_toolkit/mod.rs
index 9b75c0fa..8fc1a7c4 100644
--- a/src-tauri/src/audio_toolkit/mod.rs
+++ b/src-tauri/src/audio_toolkit/mod.rs
@@ -7,8 +7,8 @@ pub mod utils;
pub mod vad;
pub use audio::{
- list_output_devices, read_wav_samples, save_wav_file, verify_wav_file, CaptureSink, CaptureVad,
- VadPolicy,
+ decode_audio_file, list_output_devices, read_wav_samples, save_wav_file, verify_wav_file,
+ CaptureSink, CaptureVad, VadPolicy,
};
pub use lang_id::detect_output_language;
pub use text::{
diff --git a/src-tauri/src/commands/history.rs b/src-tauri/src/commands/history.rs
index 3792f6f1..9335b1dd 100644
--- a/src-tauri/src/commands/history.rs
+++ b/src-tauri/src/commands/history.rs
@@ -1,8 +1,8 @@
-use crate::actions::process_transcription_output;
use crate::managers::{
- history::{HistoryManager, PaginatedHistory},
- transcription::TranscriptionManager,
+ history::{HistoryEntry, HistoryManager, PaginatedHistory},
+ transcription_jobs::TranscriptionJobManager,
};
+use std::path::PathBuf;
use std::sync::Arc;
use tauri::{AppHandle, State};
@@ -51,58 +51,45 @@ pub async fn get_audio_file_path(
pub async fn delete_history_entry(
_app: AppHandle,
history_manager: State<'_, Arc<HistoryManager>>,
+ jobs: State<'_, Arc<TranscriptionJobManager>>,
id: i64,
) -> Result<(), String> {
+ jobs.cancel(id);
history_manager
.delete_entry(id)
.await
.map_err(|e| e.to_string())
}
+/// Queues the entry to be transcribed again with the current model. Its
+/// progress and outcome arrive as `TranscriptionJob` events.
#[tauri::command]
#[specta::specta]
-pub async fn retry_history_entry_transcription(
- app: AppHandle,
- history_manager: State<'_, Arc<HistoryManager>>,
- transcription_manager: State<'_, Arc<TranscriptionManager>>,
- id: i64,
-) -> Result<(), String> {
- let entry = history_manager
- .get_entry_by_id(id)
- .await
- .map_err(|e| e.to_string())?
- .ok_or_else(|| format!("History entry {} not found", id))?;
-
- let audio_path = history_manager.get_audio_file_path(&entry.file_name);
- let samples = crate::audio_toolkit::read_wav_samples(&audio_path)
- .map_err(|e| format!("Failed to load audio: {}", e))?;
-
- if samples.is_empty() {
- return Err("Recording has no audio samples".to_string());
- }
+pub fn retry_history_entry_transcription(jobs: State<'_, Arc<TranscriptionJobManager>>, id: i64) {
+ jobs.retry(id);
+}
- transcription_manager.initiate_model_load();
+/// Stops the entry's background transcription: a queued one is dropped, a
+/// running one stops after the chunk it is on. The entry keeps the text it
+/// had before.
+#[tauri::command]
+#[specta::specta]
+pub fn cancel_history_entry_transcription(jobs: State<'_, Arc<TranscriptionJobManager>>, id: i64) {
+ jobs.cancel(id);
+}
- let tm = Arc::clone(&transcription_manager);
- let transcription = tauri::async_runtime::spawn_blocking(move || tm.transcribe(samples))
+/// Adds an audio or video file to History and queues its transcription.
+/// Fails without adding anything if the file has no audio Handy can read.
+#[tauri::command]
+#[specta::specta]
+pub async fn transcribe_file(
+ jobs: State<'_, Arc<TranscriptionJobManager>>,
+ path: String,
+) -> Result<HistoryEntry, String> {
+ let jobs = Arc::clone(&jobs);
+ tauri::async_runtime::spawn_blocking(move || jobs.transcribe_file(PathBuf::from(path)))
.await
- .map_err(|e| format!("Transcription task panicked: {}", e))?
- .map_err(|e| e.to_string())?;
-
- if transcription.is_empty() {
- return Err("Recording contains no speech".to_string());
- }
-
- let processed =
- process_transcription_output(&app, &transcription, entry.post_process_requested).await;
- history_manager
- .update_transcription(
- id,
- transcription,
- processed.post_processed_text,
- processed.post_process_prompt,
- )
- .map(|_| ())
+ .map_err(|e| format!("Failed to read the file: {}", e))?
.map_err(|e| e.to_string())
}
diff --git a/src-tauri/src/commands/models.rs b/src-tauri/src/commands/models.rs
index 17c9a7b0..29dd9214 100644
--- a/src-tauri/src/commands/models.rs
+++ b/src-tauri/src/commands/models.rs
@@ -90,6 +90,7 @@ pub async fn delete_model(
// If deleting the active model, unload it and clear the setting
let settings = get_settings(&app_handle);
if settings.selected_model == model_id {
+ transcription_manager.ensure_model_unlocked()?;
// Waits for the worker to exit (behind any transcription in progress)
// before the file is deleted, so keep it off the async workers.
let tm = Arc::clone(&transcription_manager);
@@ -119,6 +120,7 @@ pub async fn delete_model(
pub fn switch_active_model(app: &AppHandle, model_id: &str) -> Result<(), String> {
let model_manager = app.state::<Arc<ModelManager>>();
let transcription_manager = app.state::<Arc<TranscriptionManager>>();
+ transcription_manager.ensure_model_unlocked()?;
// Atomically claim the loading slot — prevents concurrent model loads
// from tray double-clicks or overlapping commands. The guard resets the
diff --git a/src-tauri/src/commands/transcription.rs b/src-tauri/src/commands/transcription.rs
index d51b1673..64d555cf 100644
--- a/src-tauri/src/commands/transcription.rs
+++ b/src-tauri/src/commands/transcription.rs
@@ -35,6 +35,7 @@ pub fn get_model_load_status(
pub fn unload_model_manually(
transcription_manager: State<Arc<TranscriptionManager>>,
) -> Result<(), String> {
+ transcription_manager.ensure_model_unlocked()?;
transcription_manager.request_unload();
Ok(())
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index fdf0042c..7723ac61 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -39,6 +39,7 @@ use managers::audio::AudioRecordingManager;
use managers::history::HistoryManager;
use managers::model::ModelManager;
use managers::transcription::TranscriptionManager;
+use managers::transcription_jobs::TranscriptionJobManager;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::Arc;
use tauri::image::Image;
@@ -214,6 +215,7 @@ fn initialize_core_logic(app_handle: &AppHandle) {
app_handle.manage(transcription_manager.clone());
app_handle.manage(history_manager.clone());
app_handle.manage(tray::TrayState::new());
+ app_handle.manage(TranscriptionJobManager::new(app_handle));
// Note: Shortcuts are NOT initialized here.
// The frontend is responsible for calling the `initialize_shortcuts` command
@@ -304,6 +306,10 @@ fn initialize_core_logic(app_handle: &AppHandle) {
log::warn!("No model is currently loaded.");
return;
}
+ if let Err(e) = transcription_manager.ensure_model_unlocked() {
+ log::warn!("{}", e);
+ return;
+ }
transcription_manager.request_unload();
log::info!("Model unloaded via tray.");
}
@@ -768,12 +774,15 @@ pub fn run(cli_args: CliArgs) {
commands::history::get_audio_file_path,
commands::history::delete_history_entry,
commands::history::retry_history_entry_transcription,
+ commands::history::cancel_history_entry_transcription,
+ commands::history::transcribe_file,
commands::history::update_history_limit,
commands::history::update_recording_retention_period,
helpers::clamshell::is_laptop,
])
.events(collect_events![
managers::history::HistoryUpdatePayload,
+ managers::transcription_jobs::TranscriptionJob,
managers::transcription::StreamTextEvent,
managers::transcription::StreamPhaseEvent,
transcription_coordinator::RecordingStateEvent,
diff --git a/src-tauri/src/managers/history.rs b/src-tauri/src/managers/history.rs
index c73b46c9..88a0222d 100644
--- a/src-tauri/src/managers/history.rs
+++ b/src-tauri/src/managers/history.rs
@@ -1,8 +1,8 @@
use anyhow::{anyhow, Result};
use chrono::{DateTime, Local, Utc};
-use log::{debug, error, info};
+use log::{debug, error, info, warn};
use rusqlite::{params, Connection, OptionalExtension};
-use rusqlite_migration::{Migrations, M};
+use rusqlite_migration::{MigrationDefinitionError, Migrations, M};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::fs;
@@ -63,6 +63,9 @@ pub struct HistoryEntry {
pub post_processed_text: Option<String>,
pub post_process_prompt: Option<String>,
pub post_process_requested: bool,
+ /// The name of the file this entry was transcribed from; `None` for a
+ /// dictation.
+ pub source_name: Option<String>,
}
pub struct HistoryManager {
@@ -105,20 +108,18 @@ impl HistoryManager {
// tauri-plugin-sql used _sqlx_migrations table, rusqlite_migration uses user_version pragma
self.migrate_from_tauri_plugin_sql(&conn)?;
- // Create migrations object and run to latest version
- let migrations = Migrations::new(MIGRATIONS.to_vec());
-
// Validate migrations in debug builds
#[cfg(debug_assertions)]
- migrations.validate().expect("Invalid migrations");
+ Migrations::new(MIGRATIONS.to_vec())
+ .validate()
+ .expect("Invalid migrations");
// Get current version before migration
let version_before: i32 =
conn.pragma_query_value(None, "user_version", |row| row.get(0))?;
debug!("Database version before migration: {}", version_before);
- // Apply any pending migrations
- migrations.to_latest(&mut conn)?;
+ Self::apply_migrations(&mut conn)?;
// Get version after migration
let version_after: i32 = conn.pragma_query_value(None, "user_version", |row| row.get(0))?;
@@ -135,6 +136,39 @@ impl HistoryManager {
Ok(())
}
+ /// Bring the schema up to date. A newer Handy's database opens as is:
+ /// migrations only add columns, and every query names its columns.
+ fn apply_migrations(conn: &mut Connection) -> Result<()> {
+ match Migrations::new(MIGRATIONS.to_vec()).to_latest(conn) {
+ Err(rusqlite_migration::Error::MigrationDefinition(
+ MigrationDefinitionError::DatabaseTooFarAhead,
+ )) => {
+ warn!("history.db is from a newer version of Handy; opening it without migrating")
+ }
+ other => other?,
+ }
+
+ // Not a migration: a higher user_version makes released builds refuse
+ // the database, while an extra nullable column is invisible to them.
+ if !Self::has_column(conn, "source_name")? {
+ conn.execute(
+ "ALTER TABLE transcription_history ADD COLUMN source_name TEXT",
+ [],
+ )?;
+ info!("Added the source_name column to transcription history");
+ }
+
+ Ok(())
+ }
+
+ fn has_column(conn: &Connection, name: &str) -> Result<bool> {
+ Ok(conn.query_row(
+ "SELECT COUNT(*) > 0 FROM pragma_table_info('transcription_history') WHERE name = ?1",
+ [name],
+ |row| row.get(0),
+ )?)
+ }
+
/// Migrate from tauri-plugin-sql's migration tracking to rusqlite_migration's.
/// tauri-plugin-sql used a _sqlx_migrations table, while rusqlite_migration uses
/// SQLite's user_version pragma. This function checks if the old system was in use
@@ -207,6 +241,7 @@ impl HistoryManager {
post_processed_text: row.get("post_processed_text")?,
post_process_prompt: row.get("post_process_prompt")?,
post_process_requested: row.get("post_process_requested")?,
+ source_name: row.get("source_name")?,
})
}
@@ -224,8 +259,45 @@ impl HistoryManager {
post_processed_text: Option<String>,
post_process_prompt: Option<String>,
) -> Result<HistoryEntry> {
- let timestamp = Utc::now().timestamp();
- let title = self.format_timestamp_title(timestamp);
+ let entry = self.insert_entry(HistoryEntry {
+ id: 0,
+ file_name,
+ timestamp: Utc::now().timestamp(),
+ saved: false,
+ title: String::new(),
+ transcription_text,
+ post_processed_text,
+ post_process_prompt,
+ post_process_requested,
+ source_name: None,
+ })?;
+
+ self.cleanup_old_entries()?;
+
+ Ok(entry)
+ }
+
+ /// Save the entry for a file whose audio is already at `file_name`.
+ /// Retention never removes it (only deleting it does); never
+ /// post-processed.
+ pub fn save_file_entry(&self, file_name: String, source_name: String) -> Result<HistoryEntry> {
+ self.insert_entry(HistoryEntry {
+ id: 0,
+ file_name,
+ timestamp: Utc::now().timestamp(),
+ saved: false,
+ title: String::new(),
+ transcription_text: String::new(),
+ post_processed_text: None,
+ post_process_prompt: None,
+ post_process_requested: false,
+ source_name: Some(source_name),
+ })
+ }
+
+ /// Insert `entry`, filling in its id and title, and announce it.
+ fn insert_entry(&self, mut entry: HistoryEntry) -> Result<HistoryEntry> {
+ entry.title = self.format_timestamp_title(entry.timestamp);
let conn = self.get_connection()?;
conn.execute(
@@ -237,36 +309,25 @@ impl HistoryManager {
transcription_text,
post_processed_text,
post_process_prompt,
- post_process_requested
- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
- params![
- &file_name,
- timestamp,
- false,
- &title,
- &transcription_text,
- &post_processed_text,
- &post_process_prompt,
post_process_requested,
+ source_name
+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
+ params![
+ &entry.file_name,
+ entry.timestamp,
+ entry.saved,
+ &entry.title,
+ &entry.transcription_text,
+ &entry.post_processed_text,
+ &entry.post_process_prompt,
+ entry.post_process_requested,
+ &entry.source_name,
],
)?;
-
- let entry = HistoryEntry {
- id: conn.last_insert_rowid(),
- file_name,
- timestamp,
- saved: false,
- title,
- transcription_text,
- post_processed_text,
- post_process_prompt,
- post_process_requested,
- };
+ entry.id = conn.last_insert_rowid();
debug!("Saved history entry with id {}", entry.id);
- self.cleanup_old_entries()?;
-
// Emit typed event for real-time frontend updates
if let Err(e) = (HistoryUpdatePayload::Added {
entry: entry.clone(),
@@ -308,7 +369,7 @@ impl HistoryManager {
let entry = conn
.query_row(
- "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested
+ "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested, source_name
FROM transcription_history WHERE id = ?1",
params![id],
Self::map_history_entry,
@@ -380,9 +441,10 @@ impl HistoryManager {
fn cleanup_by_count(&self, limit: usize) -> Result<()> {
let conn = self.get_connection()?;
- // Get all entries that are not saved, ordered by timestamp desc
+ // Unsaved dictations, newest first. Transcribed files are only ever
+ // deleted explicitly, and don't count toward the limit.
let mut stmt = conn.prepare(
- "SELECT id, file_name FROM transcription_history WHERE saved = 0 ORDER BY timestamp DESC"
+ "SELECT id, file_name FROM transcription_history WHERE saved = 0 AND source_name IS NULL ORDER BY timestamp DESC"
)?;
let rows = stmt.query_map([], |row| {
@@ -421,9 +483,10 @@ impl HistoryManager {
_ => unreachable!("Should not reach here"),
};
- // Get all unsaved entries older than the cutoff timestamp
+ // Unsaved dictations older than the cutoff; transcribed files are only
+ // ever deleted explicitly.
let mut stmt = conn.prepare(
- "SELECT id, file_name FROM transcription_history WHERE saved = 0 AND timestamp < ?1",
+ "SELECT id, file_name FROM transcription_history WHERE saved = 0 AND source_name IS NULL AND timestamp < ?1",
)?;
let rows = stmt.query_map(params![cutoff_timestamp], |row| {
@@ -459,7 +522,7 @@ impl HistoryManager {
(Some(cursor_id), Some(lim)) => {
let fetch_count = (lim + 1) as i64;
let mut stmt = conn.prepare(
- "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested
+ "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested, source_name
FROM transcription_history
WHERE id < ?1
ORDER BY id DESC
@@ -473,7 +536,7 @@ impl HistoryManager {
(None, Some(lim)) => {
let fetch_count = (lim + 1) as i64;
let mut stmt = conn.prepare(
- "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested
+ "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested, source_name
FROM transcription_history
ORDER BY id DESC
LIMIT ?1",
@@ -485,7 +548,7 @@ impl HistoryManager {
}
(_, None) => {
let mut stmt = conn.prepare(
- "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested
+ "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested, source_name
FROM transcription_history
ORDER BY id DESC",
)?;
@@ -516,7 +579,8 @@ impl HistoryManager {
transcription_text,
post_processed_text,
post_process_prompt,
- post_process_requested
+ post_process_requested,
+ source_name
FROM transcription_history
ORDER BY timestamp DESC
LIMIT 1",
@@ -526,7 +590,8 @@ impl HistoryManager {
Ok(entry)
}
- /// Get the latest entry with non-empty transcription text.
+ /// Get the latest dictation with non-empty transcription text. Files are
+ /// left out: a long file's transcript is never the "last transcript".
pub fn get_latest_completed_entry(&self) -> Result<Option<HistoryEntry>> {
let conn = self.get_connection()?;
Self::get_latest_completed_entry_with_conn(&conn)
@@ -543,9 +608,10 @@ impl HistoryManager {
transcription_text,
post_processed_text,
post_process_prompt,
- post_process_requested
+ post_process_requested,
+ source_name
FROM transcription_history
- WHERE transcription_text != ''
+ WHERE transcription_text != '' AND source_name IS NULL
ORDER BY timestamp DESC
LIMIT 1",
)?;
@@ -597,7 +663,8 @@ impl HistoryManager {
transcription_text,
post_processed_text,
post_process_prompt,
- post_process_requested
+ post_process_requested,
+ source_name
FROM transcription_history
WHERE id = ?1",
)?;
@@ -666,7 +733,8 @@ mod tests {
transcription_text TEXT NOT NULL,
post_processed_text TEXT,
post_process_prompt TEXT,
- post_process_requested BOOLEAN NOT NULL DEFAULT 0
+ post_process_requested BOOLEAN NOT NULL DEFAULT 0,
+ source_name TEXT
);",
)
.expect("create transcription_history table");
@@ -699,6 +767,43 @@ mod tests {
.expect("insert history entry");
}
+ fn user_version(conn: &Connection) -> i32 {
+ conn.pragma_query_value(None, "user_version", |row| row.get(0))
+ .expect("read user_version")
+ }
+
+ #[test]
+ fn migrating_adds_source_name_without_raising_the_version() {
+ let mut conn = Connection::open_in_memory().expect("open in-memory db");
+ HistoryManager::apply_migrations(&mut conn).expect("migrate");
+ assert!(HistoryManager::has_column(&conn, "source_name").expect("read table info"));
+ assert_eq!(user_version(&conn), MIGRATIONS.len() as i32);
+
+ // Opening it again changes nothing.
+ HistoryManager::apply_migrations(&mut conn).expect("migrate again");
+ assert_eq!(user_version(&conn), MIGRATIONS.len() as i32);
+ }
+
+ #[test]
+ fn a_database_from_a_newer_handy_still_opens() {
+ let mut conn = Connection::open_in_memory().expect("open in-memory db");
+ HistoryManager::apply_migrations(&mut conn).expect("migrate");
+ conn.execute(
+ "ALTER TABLE transcription_history ADD COLUMN from_the_future TEXT",
+ [],
+ )
+ .expect("add newer column");
+ conn.pragma_update(None, "user_version", MIGRATIONS.len() as i32 + 3)
+ .expect("set newer version");
+
+ HistoryManager::apply_migrations(&mut conn).expect("open newer database");
+ insert_entry(&conn, 100, "still works", None);
+ let entry = HistoryManager::get_latest_entry_with_conn(&conn)
+ .expect("fetch latest entry")
+ .expect("entry exists");
+ assert_eq!(entry.transcription_text, "still works");
+ }
+
#[test]
fn get_latest_entry_returns_none_when_empty() {
let conn = setup_conn();
@@ -734,4 +839,22 @@ mod tests {
assert_eq!(entry.timestamp, 100);
assert_eq!(entry.transcription_text, "completed");
}
+
+ #[test]
+ fn get_latest_completed_entry_skips_files() {
+ let conn = setup_conn();
+ insert_entry(&conn, 100, "dictated", None);
+ conn.execute(
+ "INSERT INTO transcription_history (file_name, timestamp, saved, title, transcription_text, source_name)
+ VALUES ('handy-file-1.wav', 200, 1, 'file', 'from a file', 'talk.mp3')",
+ [],
+ )
+ .expect("insert file entry");
+
+ let entry = HistoryManager::get_latest_completed_entry_with_conn(&conn)
+ .expect("fetch latest completed entry")
+ .expect("completed entry exists");
+
+ assert_eq!(entry.transcription_text, "dictated");
+ }
}
diff --git a/src-tauri/src/managers/mod.rs b/src-tauri/src/managers/mod.rs
index 83450a0d..d6ffbed8 100644
--- a/src-tauri/src/managers/mod.rs
+++ b/src-tauri/src/managers/mod.rs
@@ -4,3 +4,4 @@ pub mod history;
pub mod model;
pub mod model_capabilities;
pub mod transcription;
+pub mod transcription_jobs;
diff --git a/src-tauri/src/managers/transcription.rs b/src-tauri/src/managers/transcription.rs
index 2cd3784a..4173a6b5 100644
--- a/src-tauri/src/managers/transcription.rs
+++ b/src-tauri/src/managers/transcription.rs
@@ -30,12 +30,15 @@ use tauri_specta::Event;
use transcribe_cpp::{Backend, RunOptions, Task, Transcript};
mod chunked;
+mod job;
mod live;
pub mod policy;
+pub use job::ChunkControl;
+
const STREAM_PERF_LOG_INTERVAL: Duration = Duration::from_secs(5);
-fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> String {
+pub(crate) fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> String {
if let Some(message) = payload.downcast_ref::<&str>() {
(*message).to_string()
} else if let Some(message) = payload.downcast_ref::<String>() {
@@ -263,6 +266,9 @@ pub struct TranscriptionManager {
/// yet. This prevents a second worker from starting after finalize/cancel
/// closes the router but before the first worker has fully exited.
active_stream_worker: Arc<AtomicU64>,
+ /// True while a background job is queued or running. It holds the model,
+ /// so one transcript is never written by two models.
+ job_active: Arc<AtomicBool>,
}
impl TranscriptionManager {
@@ -282,6 +288,7 @@ impl TranscriptionManager {
stream_active: Arc::new(AtomicBool::new(false)),
next_stream_worker_id: Arc::new(AtomicU64::new(1)),
active_stream_worker: Arc::new(AtomicU64::new(0)),
+ job_active: Arc::new(AtomicBool::new(false)),
};
// Start the idle watcher
@@ -309,12 +316,12 @@ impl TranscriptionManager {
continue;
}
- // While recording, keep the idle timer fresh so the
- // model is never unloaded mid-session.
+ // While recording or transcribing a file, keep the idle
+ // timer fresh so the model is never unloaded mid-session.
let is_recording = app_handle_cloned
.try_state::<Arc<AudioRecordingManager>>()
.is_some_and(|a| a.is_recording());
- if is_recording {
+ if is_recording || manager_cloned.job_active() {
manager_cloned.touch_activity();
continue;
}
@@ -484,6 +491,11 @@ impl TranscriptionManager {
/// is loaded. Never waits for the worker to exit, so it is safe on any
/// thread, including the event loop.
pub fn maybe_unload_immediately(&self, context: &str) {
+ // A file job keeps the model for its remaining chunks; it unloads
+ // the model itself when it ends.
+ if self.job_active() {
+ return;
+ }
let settings = get_settings(&self.app_handle);
if settings.model_unload_timeout == ModelUnloadTimeout::Immediately
&& self.is_model_loaded()
@@ -704,6 +716,24 @@ impl TranscriptionManager {
self.engine.loaded().map(|info| info.backend)
}
+ /// Whether a file job is queued or running, which holds the model.
+ pub fn job_active(&self) -> bool {
+ self.job_active.load(Ordering::Acquire)
+ }
+
+ pub fn set_job_active(&self, active: bool) {
+ self.job_active.store(active, Ordering::Release);
+ }
+
+ /// Refuses a model switch, unload or delete while a file job holds the
+ /// model.
+ pub fn ensure_model_unlocked(&self) -> std::result::Result<(), String> {
+ if self.job_active() {
+ return Err("The model can't change while a file is transcribing".to_string());
+ }
+ Ok(())
+ }
+
/// Whether a live streaming run is currently in flight.
pub fn is_streaming(&self) -> bool {
self.stream_active.load(Ordering::Acquire)
@@ -963,28 +993,25 @@ impl TranscriptionManager {
// A cancel from here on (during the model-load wait or chunk planning
// included) stops every run of this transcription.
let mark = self.engine.cancel_mark();
-
- // Update last activity timestamp
self.touch_activity();
+ let batch = self.batch_context()?;
+ self.transcribe_cpp(mark, batch, audio)
+ }
- // Check if model is loaded, if not try to load it
+ /// Waits out any model load, then reads what a batch transcription runs
+ /// with: the loaded model, the settings, and the language resolved for it.
+ fn batch_context(&self) -> Result<BatchContext> {
{
- // If the model is loading, wait for it to complete.
let mut is_loading = self.is_loading.lock().unwrap();
while *is_loading {
is_loading = self.loading_condvar.wait(is_loading).unwrap();
}
-
- if !self.is_model_loaded() {
- return Err(anyhow::anyhow!("Model is not loaded for transcription."));
- }
}
+ let Some(info) = self.engine.loaded() else {
+ return Err(anyhow::anyhow!("Model is not loaded for transcription."));
+ };
- // Get current settings for configuration
let settings = get_settings(&self.app_handle);
-
- // Validate selected language against the model's supported languages.
- // If the language isn't supported, fall back to "auto" to prevent errors.
// Validate against the model that's actually loaded (which can differ
// from settings.selected_model when a caller loaded a specific model —
// e.g. the --transcribe-file path's --model), not the persisted
@@ -1004,37 +1031,29 @@ impl TranscriptionManager {
settings.selected_language, validated_language, active_model
);
}
-
- let Some(info) = self.engine.loaded() else {
- return Err(anyhow::anyhow!(
- "Model failed to load after auto-load attempt. Please check your model settings."
- ));
- };
- self.transcribe_cpp(
- mark,
+ let setup = run_setup(&info, &settings, &validated_language);
+ Ok(BatchContext {
info,
- audio,
- &settings,
- &validated_language,
- &active_model,
- )
+ settings,
+ active_model,
+ setup,
+ })
}
- /// transcribe-cpp: the model runs in the engine's worker process, which
- /// recovers from crashes and hangs itself. Long audio is decoded in
- /// chunks cut at pauses, unless the model handles it in one run.
fn transcribe_cpp(
&self,
mark: CancelMark,
- info: LoadedInfo,
+ batch: BatchContext,
audio: Vec<f32>,
- settings: &AppSettings,
- validated_language: &str,
- active_model: &str,
) -> Result<RunOutcome> {
- let setup = run_setup(&info, settings, validated_language);
+ let BatchContext {
+ info,
+ settings,
+ active_model,
+ setup,
+ } = batch;
let whole = |pcm: Vec<f32>| {
- self.run_batch(mark, pcm, &setup.run_options, active_model)
+ self.run_batch(mark, pcm, &setup.run_options, &active_model)
.map_err(engine_error)
};
// `mark` covers every chunk, so a cancel between two stops the rest.
@@ -1045,7 +1064,7 @@ impl TranscriptionManager {
mark,
setup.run_options.clone(),
audio,
- active_model,
+ &active_model,
settings.vad_backend,
)
.map_err(engine_error)?,
@@ -1080,6 +1099,14 @@ impl TranscriptionManager {
}
}
+/// What a batch transcription runs with, read once before its first run.
+struct BatchContext {
+ info: LoadedInfo,
+ settings: AppSettings,
+ active_model: String,
+ setup: RunSetup,
+}
+
/// What one transcription decoded (live or in batch), with how its runs were
/// set up, which post-processing needs to know.
struct RunOutcome {
diff --git a/src-tauri/src/managers/transcription/job.rs b/src-tauri/src/managers/transcription/job.rs
new file mode 100644
index 00000000..5553c920
--- /dev/null
+++ b/src-tauri/src/managers/transcription/job.rs
@@ -0,0 +1,131 @@
+//! Background transcription, always chunked: chunks are the unit of
+//! progress, of yielding to dictation, and of retry.
+
+use anyhow::Result;
+use log::{debug, info, warn};
+use std::time::Instant;
+use transcribe_cpp::Transcript;
+
+use super::{
+ engine_error, post_process_transcription_text, real_time_factor, BatchContext,
+ TranscriptionManager,
+};
+use crate::audio_toolkit::chunking::Chunker;
+use crate::engine_supervisor::EngineError;
+use crate::managers::audio::create_detector;
+
+/// Tries per chunk when a dictation's cancel interrupts it.
+const MAX_CHUNK_ATTEMPTS: usize = 3;
+
+/// Audio handed to the chunker at a time: the first chunk is transcribed
+/// without scoring the whole file first. Cuts match the whole-file plan (a
+/// rare short blip at a feed boundary can nudge one within its pause).
+const FEED_SAMPLES: usize = 60 * 16_000;
+
+/// What a background transcription asks of whoever runs it.
+pub trait ChunkControl {
+ /// Called before each feed to the chunker and before each chunk is
+ /// decoded. Blocks while dictation is using the engine; `false` stops the
+ /// transcription.
+ fn proceed(&self) -> bool;
+ /// `done` of `total` samples are transcribed.
+ fn progress(&self, done: usize, total: usize);
+}
+
+impl TranscriptionManager {
+ /// Transcribe `audio` chunk by chunk with the selected model, one
+ /// paragraph per chunk. `None` if `control` stopped it.
+ pub fn transcribe_in_chunks(
+ &self,
+ audio: Vec<f32>,
+ control: &dyn ChunkControl,
+ ) -> Result<Option<String>> {
+ let started = Instant::now();
+ let total = audio.len();
+ if total == 0 {
+ return Ok(Some(String::new()));
+ }
+
+ self.touch_activity();
+ self.initiate_model_load();
+ // Read once: the model can't change until the job ends.
+ let BatchContext {
+ settings,
+ active_model,
+ setup,
+ ..
+ } = self.batch_context()?;
+
+ let backend = settings.vad_backend;
+ let app_handle = self.app_handle.clone();
+ let mut chunker = Chunker::new(Box::new(move || create_detector(backend, &app_handle)));
+ let mut pieces = audio.chunks(FEED_SAMPLES);
+
+ let mut transcripts: Vec<Transcript> = Vec::new();
+ let mut done = 0;
+ control.progress(done, total);
+ loop {
+ // Scoring waits out dictation too, and stops on cancel.
+ if !control.proceed() {
+ return Ok(None);
+ }
+ let (chunks, last) = match pieces.next() {
+ Some(piece) => (chunker.push(piece), false),
+ None => (chunker.finish(), true),
+ };
+ for chunk in chunks {
+ let len = chunk.len();
+ let mut attempts = 0;
+ let transcript = loop {
+ if !control.proceed() {
+ return Ok(None);
+ }
+ attempts += 1;
+ // A fresh mark per chunk: a dictation's cancel stops only
+ // the chunk it caught, which is then tried again.
+ let mark = self.engine.cancel_mark();
+ match self.run_batch(mark, chunk.clone(), &setup.run_options, &active_model) {
+ Ok(transcript) => break transcript,
+ Err(EngineError::Cancelled) if attempts < MAX_CHUNK_ATTEMPTS => {
+ warn!("A background chunk was cancelled; trying it again");
+ }
+ Err(e) => return Err(engine_error(e)),
+ }
+ };
+ transcripts.push(transcript);
+ done += len;
+ control.progress(done, total);
+ }
+ if last {
+ break;
+ }
+ }
+
+ debug!("Transcribed {} chunks in the background", transcripts.len());
+ let paragraphs: Vec<String> = transcripts
+ .into_iter()
+ .map(|t| {
+ let output_language = setup.output_language(&settings, t.language);
+ post_process_transcription_text(
+ t.text,
+ &settings,
+ setup.custom_words_prompted(),
+ &output_language,
+ &setup.languages,
+ )
+ })
+ .filter(|p| !p.trim().is_empty())
+ .collect();
+
+ let elapsed_secs = started.elapsed().as_secs_f64();
+ let audio_secs = total as f64 / 16_000.0;
+ info!(
+ "Background transcription of {:.1}s of audio in {} paragraphs took {:.1}s ({:.1}x real time)",
+ audio_secs,
+ paragraphs.len(),
+ elapsed_secs,
+ real_time_factor(audio_secs, elapsed_secs)
+ );
+ Ok(Some(paragraphs.join("\n\n")))
+ }
+}
diff --git a/src-tauri/src/managers/transcription_jobs.rs b/src-tauri/src/managers/transcription_jobs.rs
new file mode 100644
index 00000000..9556fffa
--- /dev/null
+++ b/src-tauri/src/managers/transcription_jobs.rs
@@ -0,0 +1,374 @@
+//! Background transcriptions (a file, or an entry transcribed again), one at
+//! a time in chunks that yield to dictation. Progress is kept in memory.
+
+use anyhow::{anyhow, Result};
+use log::{error, info, warn};
+use serde::{Deserialize, Serialize};
+use specta::Type;
+use std::cell::Cell;
+use std::collections::VecDeque;
+use std::panic::{catch_unwind, AssertUnwindSafe};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Condvar, Mutex, MutexGuard};
+use std::thread;
+use std::time::Duration;
+use tauri::{AppHandle, Manager};
+use tauri_specta::Event;
+
+use crate::actions::process_transcription_output;
+use crate::audio_toolkit::{decode_audio_file, read_wav_samples, save_wav_file};
+use crate::managers::history::{HistoryEntry, HistoryManager};
+use crate::managers::transcription::{panic_payload_message, ChunkControl, TranscriptionManager};
+
+/// How often a waiting chunk checks whether dictation has finished.
+const DICTATION_POLL: Duration = Duration::from_millis(200);
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
+#[serde(tag = "state", rename_all = "snake_case")]
+pub enum TranscriptionJobStatus {
+ /// Waiting behind another job.
+ Queued,
+ /// `percent` of the audio is transcribed.
+ Running {
+ percent: u8,
+ },
+ /// The entry has its new text, or the job was cancelled.
+ Finished,
+ Failed {
+ error: String,
+ },
+}
+
+/// A background transcription of one History entry.
+#[derive(Clone, Debug, Serialize, Deserialize, Type, tauri_specta::Event)]
+pub struct TranscriptionJob {
+ pub entry_id: i64,
+ pub status: TranscriptionJobStatus,
+}
+
+struct Running {
+ entry_id: i64,
+ cancelled: Arc<AtomicBool>,
+}
+
+#[derive(Default)]
+struct Jobs {
+ /// Entry ids waiting to be transcribed again. They go before files:
+ /// someone is waiting on them.
+ retries: VecDeque<i64>,
+ /// Entry ids of files waiting to be transcribed.
+ files: VecDeque<i64>,
+ running: Option<Running>,
+}
+
+impl Jobs {
+ fn has(&self, entry_id: i64) -> bool {
+ self.running
+ .as_ref()
+ .is_some_and(|r| r.entry_id == entry_id)
+ || self.retries.contains(&entry_id)
+ || self.files.contains(&entry_id)
+ }
+
+ fn is_idle(&self) -> bool {
+ self.running.is_none() && self.retries.is_empty() && self.files.is_empty()
+ }
+
+ /// Drops the entry from the queues; whether it was in one.
+ fn unqueue(&mut self, entry_id: i64) -> bool {
+ let before = self.retries.len() + self.files.len();
+ self.retries.retain(|&id| id != entry_id);
+ self.files.retain(|&id| id != entry_id);
+ self.retries.len() + self.files.len() != before
+ }
+}
+
+pub struct TranscriptionJobManager {
+ app: AppHandle,
+ jobs: Mutex<Jobs>,
+ wake: Condvar,
+}
+
+impl TranscriptionJobManager {
+ /// Starts the thread that runs the jobs.
+ pub fn new(app: &AppHandle) -> Arc<Self> {
+ let manager = Arc::new(Self {
+ app: app.clone(),
+ jobs: Mutex::new(Jobs::default()),
+ wake: Condvar::new(),
+ });
+ let runner = Arc::clone(&manager);
+ thread::Builder::new()
+ .name("transcription-jobs".into())
+ .spawn(move || runner.run_jobs())
+ .expect("Failed to start the transcription job thread");
+ manager
+ }
+
+ fn lock(&self) -> MutexGuard<'_, Jobs> {
+ self.jobs
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ }
+
+ /// Decodes `path` into a recording, then adds it to History and queues
+ /// it. The recording exists first, so no entry is ever without audio.
+ pub fn transcribe_file(&self, path: PathBuf) -> Result<HistoryEntry> {
+ // A malformed file may panic the decoder.
+ let samples = catch_unwind(AssertUnwindSafe(|| decode_audio_file(&path))).unwrap_or_else(
+ |payload| {
+ Err(anyhow!(
+ "Failed to read the file: {}",
+ panic_payload_message(payload.as_ref())
+ ))
+ },
+ )?;
+ if samples.is_empty() {
+ return Err(anyhow!("The file has no audio"));
+ }
+
+ let hm = self.app.state::<Arc<HistoryManager>>();
+ let file_name = format!("handy-file-{}.wav", chrono::Utc::now().timestamp_millis());
+ let recording = hm.get_audio_file_path(&file_name);
+ // Written aside and renamed, so a crash never leaves a partial one.
+ let partial = recording.with_extension("wav.partial");
+ if let Err(e) = save_wav_file(&partial, &samples)
+ .and_then(|()| std::fs::rename(&partial, &recording).map_err(Into::into))
+ {
+ remove_recording(&partial);
+ return Err(e);
+ }
+ drop(samples);
+
+ let source_name = path
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_else(|| path.display().to_string());
+ let entry = match hm.save_file_entry(file_name, source_name) {
+ Ok(entry) => entry,
+ Err(e) => {
+ remove_recording(&recording);
+ return Err(e);
+ }
+ };
+ info!("Queued file transcription for history entry {}", entry.id);
+ self.queue(entry.id, false);
+ Ok(entry)
+ }
+
+ /// Queues the entry to be transcribed again from its recording, ahead
+ /// of any file.
+ pub fn retry(&self, entry_id: i64) {
+ self.queue(entry_id, true);
+ }
+
+ /// Queues the entry to be transcribed from its recording, unless it
+ /// already is.
+ fn queue(&self, entry_id: i64, retry: bool) {
+ {
+ let mut jobs = self.lock();
+ if jobs.has(entry_id) {
+ return;
+ }
+ if retry {
+ jobs.retries.push_back(entry_id);
+ } else {
+ jobs.files.push_back(entry_id);
+ }
+ self.sync_job_active(&jobs);
+ }
+ self.emit(entry_id, TranscriptionJobStatus::Queued);
+ crate::tray::update_tray_menu(&self.app);
+ self.wake.notify_one();
+ }
+
+ /// Stops the entry's job: a queued one is dropped, a running one stops
+ /// before its next chunk.
+ pub fn cancel(&self, entry_id: i64) {
+ let (was_queued, idle) = {
+ let mut jobs = self.lock();
+ let was_queued = jobs.unqueue(entry_id);
+ if let Some(running) = jobs.running.as_ref().filter(|r| r.entry_id == entry_id) {
+ running.cancelled.store(true, Ordering::Release);
+ }
+ self.sync_job_active(&jobs);
+ (was_queued, jobs.is_idle())
+ };
+ // A running job reports its own end from the job loop; a queued one
+ // never reaches it, so it is reported here.
+ if was_queued {
+ if idle && !crate::tray::dictation_in_progress(&self.app) {
+ self.app
+ .state::<Arc<TranscriptionManager>>()
+ .maybe_unload_immediately("background transcription");
+ }
+ crate::tray::update_tray_menu(&self.app);
+ self.emit(entry_id, TranscriptionJobStatus::Finished);
+ }
+ }
+
+ /// Keeps the model held for as long as any job is queued or running.
+ fn sync_job_active(&self, jobs: &Jobs) {
+ self.app
+ .state::<Arc<TranscriptionManager>>()
+ .set_job_active(!jobs.is_idle());
+ }
+
+ fn emit(&self, entry_id: i64, status: TranscriptionJobStatus) {
+ if let Err(e) = (TranscriptionJob { entry_id, status }).emit(&self.app) {
+ error!("Failed to emit transcription job event: {}", e);
+ }
+ }
+
+ fn run_jobs(&self) {
+ loop {
+ let (entry_id, cancelled) = {
+ let mut jobs = self.lock();
+ let entry_id = loop {
+ if let Some(entry_id) =
+ jobs.retries.pop_front().or_else(|| jobs.files.pop_front())
+ {
+ break entry_id;
+ }
+ jobs = self
+ .wake
+ .wait(jobs)
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ };
+ let cancelled = Arc::new(AtomicBool::new(false));
+ jobs.running = Some(Running {
+ entry_id,
+ cancelled: Arc::clone(&cancelled),
+ });
+ (entry_id, cancelled)
+ };
+ self.emit(entry_id, TranscriptionJobStatus::Running { percent: 0 });
+
+ // A panic fails only this job; the rest of the loop still has to
+ // run, or the model would stay held and the queue stuck.
+ let result = catch_unwind(AssertUnwindSafe(|| self.run_job(entry_id, &cancelled)))
+ .unwrap_or_else(|payload| Err(crashed(payload.as_ref())));
+
+ let idle = {
+ let mut jobs = self.lock();
+ jobs.running = None;
+ self.sync_job_active(&jobs);
+ jobs.is_idle()
+ };
+ let tm = self.app.state::<Arc<TranscriptionManager>>();
+ if idle {
+ // A dictation under way unloads the model itself when it ends.
+ if !crate::tray::dictation_in_progress(&self.app) {
+ tm.maybe_unload_immediately("background transcription");
+ }
+ crate::tray::update_tray_menu(&self.app);
+ }
+ let status = match result {
+ Err(e) if !cancelled.load(Ordering::Acquire) => {
+ warn!("Transcription of history entry {} failed: {}", entry_id, e);
+ TranscriptionJobStatus::Failed {
+ error: e.to_string(),
+ }
+ }
+ _ => TranscriptionJobStatus::Finished,
+ };
+ self.emit(entry_id, status);
+ }
+ }
+
+ fn run_job(&self, entry_id: i64, cancelled: &AtomicBool) -> Result<()> {
+ let hm = Arc::clone(&self.app.state::<Arc<HistoryManager>>());
+ let tm = Arc::clone(&self.app.state::<Arc<TranscriptionManager>>());
+ let entry = tauri::async_runtime::block_on(hm.get_entry_by_id(entry_id))?
+ .ok_or_else(|| anyhow!("History entry {} not found", entry_id))?;
+ let samples = read_wav_samples(hm.get_audio_file_path(&entry.file_name))
+ .map_err(|e| anyhow!("Failed to load audio: {}", e))?;
+ if samples.is_empty() {
+ return Err(anyhow!("Recording has no audio samples"));
+ }
+
+ let control = Control {
+ manager: self,
+ entry_id: entry.id,
+ cancelled,
+ percent: Cell::new(0),
+ };
+ let Some(text) = tm.transcribe_in_chunks(samples, &control)? else {
+ return Ok(());
+ };
+ if text.is_empty() {
+ return Err(anyhow!("Recording contains no speech"));
+ }
+ if cancelled.load(Ordering::Acquire) {
+ return Ok(());
+ }
+
+ let processed = tauri::async_runtime::block_on(process_transcription_output(
+ &self.app,
+ &text,
+ entry.post_process_requested,
+ ));
+ // Post-processing can take a while; a cancel during it still wins.
+ if cancelled.load(Ordering::Acquire) {
+ return Ok(());
+ }
+ hm.update_transcription(
+ entry.id,
+ text,
+ processed.post_processed_text,
+ processed.post_process_prompt,
+ )?;
+ Ok(())
+ }
+}
+
+/// Best-effort cleanup; the caller is already reporting the failure.
+fn remove_recording(path: &Path) {
+ if let Err(e) = std::fs::remove_file(path) {
+ if e.kind() != std::io::ErrorKind::NotFound {
+ error!("Failed to remove {}: {}", path.display(), e);
+ }
+ }
+}
+
+fn crashed(payload: &(dyn std::any::Any + Send)) -> anyhow::Error {
+ anyhow!("Transcription crashed: {}", panic_payload_message(payload))
+}
+
+struct Control<'a> {
+ manager: &'a TranscriptionJobManager,
+ entry_id: i64,
+ cancelled: &'a AtomicBool,
+ /// The last percent reported; the job starts at 0.
+ percent: Cell<u8>,
+}
+
+impl ChunkControl for Control<'_> {
+ fn proceed(&self) -> bool {
+ // Dictation goes first: wait out a recording and its transcription.
+ // A chunk started while a stream is open would end that stream.
+ loop {
+ if self.cancelled.load(Ordering::Acquire) {
+ return false;
+ }
+ if !crate::tray::dictation_in_progress(&self.manager.app) {
+ return true;
+ }
+ thread::sleep(DICTATION_POLL);
+ }
+ }
+
+ fn progress(&self, done: usize, total: usize) {
+ // The chunk a cancel caught still finishes; don't report it as running.
+ if self.cancelled.load(Ordering::Acquire) {
+ return;
+ }
+ let percent = (done * 100 / total.max(1)).min(100) as u8;
+ if self.percent.replace(percent) == percent {
+ return;
+ }
+ self.manager
+ .emit(self.entry_id, TranscriptionJobStatus::Running { percent });
+ }
+}
diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rs
index 8db5eb71..d3db3576 100644
--- a/src-tauri/src/tray.rs
+++ b/src-tauri/src/tray.rs
@@ -56,6 +56,9 @@ impl TrayIconState {
#[derive(Clone, Debug, PartialEq, Eq)]
struct MenuInputs {
busy: bool,
+ /// A background transcription holds the model, so it can't be switched
+ /// or unloaded.
+ models_locked: bool,
warning: bool,
model_loaded: bool,
selected_model: String,
@@ -219,6 +222,13 @@ pub fn set_tray_state(app: &AppHandle, state: TrayIconState) {
sync_tray_with(app, |inner| inner.icon_state = state);
}
+/// Whether a dictation is recording, transcribing or delivering. Every start,
+/// finish and cancel sets the tray state, so it's the record of that.
+pub fn dictation_in_progress(app: &AppHandle) -> bool {
+ app.try_state::<TrayState>()
+ .is_some_and(|state| state.lock().icon_state.is_busy())
+}
+
/// Re-syncs the tray after something other than the recording state changed
/// (theme, Secure Input warning). The recording state itself is preserved.
pub fn refresh_tray_icon(app: &AppHandle) {
@@ -313,7 +323,9 @@ fn compute_desired(app: &AppHandle, icon_state: TrayIconState) -> TrayDesired {
let settings = settings::get_settings(app);
let theme = get_current_theme(app);
let warning = crate::secure_input::tray_warning_active(app);
- let model_loaded = app.state::<Arc<TranscriptionManager>>().is_model_loaded();
+ let tm = app.state::<Arc<TranscriptionManager>>();
+ let model_loaded = tm.is_model_loaded();
+ let models_locked = tm.job_active();
let mut downloaded_models: Vec<(String, String)> = app
.state::<Arc<ModelManager>>()
@@ -328,6 +340,7 @@ fn compute_desired(app: &AppHandle, icon_state: TrayIconState) -> TrayDesired {
icon_path: get_icon_path(theme, icon_state, warning),
menu: MenuInputs {
busy: icon_state.is_busy(),
+ models_locked,
warning,
model_loaded,
selected_model: settings.selected_model,
@@ -538,7 +551,8 @@ fn build_menu(app: &AppHandle, inputs: &MenuInputs) -> tauri::Result<(Menu<tauri
.map(|(_, name)| name.clone())
.unwrap_or_else(|| strings.model.clone());
- let model_submenu = Submenu::with_id(app, "model_submenu", &submenu_label, true)?;
+ let model_submenu =
+ Submenu::with_id(app, "model_submenu", &submenu_label, !inputs.models_locked)?;
for (id, name) in &inputs.downloaded_models {
let is_active = *id == inputs.selected_model;
let item_id = format!("model_select:{}", id);
@@ -550,7 +564,7 @@ fn build_menu(app: &AppHandle, inputs: &MenuInputs) -> tauri::Result<(Menu<tauri
app,
"unload_model",
&strings.unload_model,
- inputs.model_loaded,
+ inputs.model_loaded && !inputs.models_locked,
None::<&str>,
)?;
@@ -682,12 +696,14 @@ mod tests {
post_processed_text: post_processed.map(|text| text.to_string()),
post_process_prompt: None,
post_process_requested: false,
+ source_name: None,
}
}
fn inputs(busy: bool) -> MenuInputs {
MenuInputs {
busy,
+ models_locked: false,
warning: false,
model_loaded: true,
selected_model: "small".to_string(),
diff --git a/src/App.tsx b/src/App.tsx
index 3c5e1b4a..27f980bd 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,4 +1,5 @@
import {
+ useCallback,
useEffect,
useLayoutEffect,
useState,
@@ -29,6 +30,7 @@ import {
} from "./components/onboarding/onboardingStore";
import { DebugSettings, ModelsSettings } from "./components/settings";
import { ErrorBoundary } from "./components/ErrorBoundary";
+import { FileDropOverlay } from "./components/FileDropOverlay";
import { Sidebar, SidebarSection, SECTIONS_CONFIG } from "./components/Sidebar";
import { WhatsNewGate } from "./components/whats-new";
import { useSettings } from "./hooks/useSettings";
@@ -84,6 +86,7 @@ function App() {
const [migrationModelId, setMigrationModelId] = useState<string | null>(null);
const [currentSection, setCurrentSection] =
useState<SidebarSection>("general");
+ const showHistory = useCallback(() => setCurrentSection("history"), []);
const { settings, updateSetting } = useSettings();
const direction = getLanguageDirection(i18n.language);
const refreshAudioDevices = useSettingsStore(
@@ -447,7 +450,8 @@ function App() {
</div>
</div>
{/* Fixed footer at bottom */}
- <Footer />
+ <Footer onShowHistory={showHistory} />
+ <FileDropOverlay onDropped={showHistory} />
</div>
);
}
diff --git a/src/bindings.ts b/src/bindings.ts
index bbde8805..1f13e3d9 100644
--- a/src/bindings.ts
+++ b/src/bindings.ts
@@ -930,9 +930,28 @@ async deleteHistoryEntry(id: number) : Promise<Result<null, string>> {
else return { status: "error", error: e as any };
}
},
-async retryHistoryEntryTranscription(id: number) : Promise<Result<null, string>> {
+/**
+ * Queues the entry to be transcribed again with the current model. Its
+ * progress and outcome arrive as `TranscriptionJob` events.
+ */
+async retryHistoryEntryTranscription(id: number) : Promise<void> {
+ await TAURI_INVOKE("retry_history_entry_transcription", { id });
+},
+/**
+ * Stops the entry's background transcription: a queued one is dropped, a
+ * running one stops after the chunk it is on. The entry keeps the text it
+ * had before.
+ */
+async cancelHistoryEntryTranscription(id: number) : Promise<void> {
+ await TAURI_INVOKE("cancel_history_entry_transcription", { id });
+},
+/**
+ * Adds an audio or video file to History and queues its transcription.
+ * Fails without adding anything if the file has no audio Handy can read.
+ */
+async transcribeFile(path: string) : Promise<Result<HistoryEntry, string>> {
try {
- return { status: "ok", data: await TAURI_INVOKE("retry_history_entry_transcription", { id }) };
+ return { status: "ok", data: await TAURI_INVOKE("transcribe_file", { path }) };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
@@ -978,13 +997,15 @@ historyUpdatePayload: HistoryUpdatePayload,
recordingStateEvent: RecordingStateEvent,
streamPhaseEvent: StreamPhaseEvent,
streamTextEvent: StreamTextEvent,
-transcriptionCompleteEvent: TranscriptionCompleteEvent
+transcriptionCompleteEvent: TranscriptionCompleteEvent,
+transcriptionJob: TranscriptionJob
}>({
historyUpdatePayload: "history-update-payload",
recordingStateEvent: "recording-state-event",
streamPhaseEvent: "stream-phase-event",
streamTextEvent: "stream-text-event",
-transcriptionCompleteEvent: "transcription-complete-event"
+transcriptionCompleteEvent: "transcription-complete-event",
+transcriptionJob: "transcription-job"
})
/** user-defined constants **/
@@ -1096,7 +1117,12 @@ export type ChineseScript =
export type ClipboardHandling = "dont_modify" | "copy_to_clipboard"
export type CustomSounds = { start: boolean; stop: boolean }
export type GpuDeviceOption = { id: string; name: string; total_vram_mb: number }
-export type HistoryEntry = { id: number; file_name: string; timestamp: number; saved: boolean; title: string; transcription_text: string; post_processed_text: string | null; post_process_prompt: string | null; post_process_requested: boolean }
+export type HistoryEntry = { id: number; file_name: string; timestamp: number; saved: boolean; title: string; transcription_text: string; post_processed_text: string | null; post_process_prompt: string | null; post_process_requested: boolean;
+/**
+ * The name of the file this entry was transcribed from; `None` for a
+ * dictation.
+ */
+source_name: string | null }
export type HistoryUpdatePayload = { action: "added"; entry: HistoryEntry } | { action: "updated"; entry: HistoryEntry } | { action: "deleted"; id: number } | { action: "toggled"; id: number }
/**
* Result of changing keyboard implementation
@@ -1288,6 +1314,23 @@ export type TranscribeAcceleratorSetting = "auto" | "cpu" | "gpu"
* Emitted when a dictation finishes (not on cancel); onboarding uses it to measure speed.
*/
export type TranscriptionCompleteEvent = { outcome: TranscriptionOutcome; audio_seconds: number; wait_seconds: number }
+/**
+ * A background transcription of one History entry.
+ */
+export type TranscriptionJob = { entry_id: number; status: TranscriptionJobStatus }
+export type TranscriptionJobStatus =
+/**
+ * Waiting behind another job.
+ */
+{ state: "queued" } |
+/**
+ * `percent` of the audio is transcribed.
+ */
+{ state: "running"; percent: number } |
+/**
+ * The entry has its new text, or the job was cancelled.
+ */
+{ state: "finished" } | { state: "failed"; error: string }
/**
* How a dictation ended.
*/
diff --git a/src/components/FileDropOverlay.tsx b/src/components/FileDropOverlay.tsx
new file mode 100644
index 00000000..72d09382
--- /dev/null
+++ b/src/components/FileDropOverlay.tsx
@@ -0,0 +1,52 @@
+import React, { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { getCurrentWebview } from "@tauri-apps/api/webview";
+import HandyHand from "./icons/HandyHand";
+import { transcribeFiles } from "./settings/history/transcribeFiles";
+
+interface FileDropOverlayProps {
+ // Called once the dropped files are added, to show them in History.
+ onDropped: () => void;
+}
+
+// Files dropped anywhere on the window are transcribed into History.
+export const FileDropOverlay: React.FC<FileDropOverlayProps> = ({
+ onDropped,
+}) => {
+ const { t } = useTranslation();
+ const [dragging, setDragging] = useState(false);
+
+ useEffect(() => {
+ const unlisten = getCurrentWebview().onDragDropEvent(async (event) => {
+ const { payload } = event;
+ if (payload.type === "enter") {
+ setDragging(payload.paths.length > 0);
+ } else if (payload.type === "leave") {
+ setDragging(false);
+ } else if (payload.type === "drop") {
+ setDragging(false);
+ if (payload.paths.length === 0) return;
+ if ((await transcribeFiles(payload.paths)) > 0) onDropped();
+ }
+ });
+ return () => {
+ unlisten.then((fn) => fn());
+ };
+ }, [onDropped]);
+
+ if (!dragging) return null;
+
+ return (
+ <div className="fixed inset-0 z-50 p-3 bg-background/85 pointer-events-none">
+ <div className="h-full w-full flex flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed border-logo-primary text-center">
+ <HandyHand width={44} height={47} />
+ <p className="text-base font-semibold">
+ {t("settings.history.dropTitle")}
+ </p>
+ <p className="text-sm text-ink-2">
+ {t("settings.history.dropDescription")}
+ </p>
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/footer/Footer.tsx b/src/components/footer/Footer.tsx
index 3c50295d..2c33820f 100644
--- a/src/components/footer/Footer.tsx
+++ b/src/components/footer/Footer.tsx
@@ -3,8 +3,13 @@ import { getVersion } from "@tauri-apps/api/app";
import ModelSelector from "../model-selector";
import UpdateChecker from "../update-checker";
+import TranscriptionStatus from "./TranscriptionStatus";
-const Footer: React.FC = () => {
+interface FooterProps {
+ onShowHistory: () => void;
+}
+
+const Footer: React.FC<FooterProps> = ({ onShowHistory }) => {
const [version, setVersion] = useState("");
useEffect(() => {
@@ -26,6 +31,7 @@ const Footer: React.FC = () => {
<div className="flex justify-between items-center text-xs px-4 pb-3 text-ink-2">
<div className="flex items-center gap-4">
<ModelSelector />
+ <TranscriptionStatus onShowHistory={onShowHistory} />
</div>
{/* Update Status */}
diff --git a/src/components/footer/TranscriptionStatus.tsx b/src/components/footer/TranscriptionStatus.tsx
new file mode 100644
index 00000000..ea123a8e
--- /dev/null
+++ b/src/components/footer/TranscriptionStatus.tsx
@@ -0,0 +1,37 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { useTranscriptionJobsStore } from "@/stores/transcriptionJobsStore";
+
+interface TranscriptionStatusProps {
+ /** Where the jobs and their progress are. */
+ onShowHistory: () => void;
+}
+
+/** Background transcription beside the model doing it; opens History. */
+const TranscriptionStatus: React.FC<TranscriptionStatusProps> = ({
+ onShowHistory,
+}) => {
+ const { t } = useTranslation();
+ const jobs = Object.values(useTranscriptionJobsStore((s) => s.jobs));
+ if (jobs.length === 0) return null;
+
+ // Jobs run one at a time; the rest wait behind it.
+ const running = jobs.find((j) => j.state === "running");
+ const text = !running
+ ? t("settings.history.waiting")
+ : running.percent > 0
+ ? t("settings.history.transcribingPercent", { percent: running.percent })
+ : t("settings.history.transcribing");
+
+ return (
+ <button
+ type="button"
+ onClick={onShowHistory}
+ className="cursor-pointer tabular-nums text-ink-3 transition-colors hover:text-text focus:outline-none focus-visible:ring-1 focus-visible:ring-logo-primary"
+ >
+ {text}
+ </button>
+ );
+};
+
+export default TranscriptionStatus;
diff --git a/src/components/model-selector/ModelDropdown.tsx b/src/components/model-selector/ModelDropdown.tsx
index d359a74c..b7741582 100644
--- a/src/components/model-selector/ModelDropdown.tsx
+++ b/src/components/model-selector/ModelDropdown.tsx
@@ -9,23 +9,32 @@ import {
interface ModelDropdownProps {
models: ModelInfo[];
currentModelId: string;
+ // A file is transcribing: show the models, but don't let them be picked.
+ locked?: boolean;
onModelSelect: (modelId: string) => void;
}
const ModelDropdown: React.FC<ModelDropdownProps> = ({
models,
currentModelId,
+ locked = false,
onModelSelect,
}) => {
const { t } = useTranslation();
const downloadedModels = models.filter((m) => m.is_downloaded);
const handleModelClick = (modelId: string) => {
+ if (locked) return;
onModelSelect(modelId);
};
return (
<div className="absolute bottom-full start-0 mb-2 w-64 max-h-[60vh] overflow-y-auto bg-background border border-line rounded-lg shadow-lg py-2 z-50">
+ {locked && (
+ <div className="px-3 pb-2 mb-1 text-xs text-ink-2 border-b border-line">
+ {t("modelSelector.lockedWhileTranscribing")}
+ </div>
+ )}
{downloadedModels.length > 0 ? (
<div>
{downloadedModels.map((model) => (
@@ -38,9 +47,14 @@ const ModelDropdown: React.FC<ModelDropdownProps> = ({
handleModelClick(model.id);
}
}}
- tabIndex={0}
+ tabIndex={locked ? -1 : 0}
role="button"
- className={`w-full px-3 py-2 text-start hover:bg-wash transition-colors cursor-pointer focus:outline-none ${
+ aria-disabled={locked}
+ className={`w-full px-3 py-2 text-start transition-colors focus:outline-none ${
+ locked
+ ? "opacity-50 cursor-not-allowed"
+ : "hover:bg-wash cursor-pointer"
+ } ${
currentModelId === model.id
? "bg-logo-primary/10 text-logo-primary"
: ""
diff --git a/src/components/model-selector/ModelSelector.tsx b/src/components/model-selector/ModelSelector.tsx
index cd52ab9d..9a4b783d 100644
--- a/src/components/model-selector/ModelSelector.tsx
+++ b/src/components/model-selector/ModelSelector.tsx
@@ -4,6 +4,10 @@ import { listen } from "@tauri-apps/api/event";
import { commands } from "@/bindings";
import { getTranslatedModelName } from "../../lib/utils/modelTranslation";
import { useModelStore } from "../../stores/modelStore";
+import {
+ areModelsLocked,
+ useModelsLocked,
+} from "../../stores/transcriptionJobsStore";
import ModelStatusButton from "./ModelStatusButton";
import ModelDropdown from "./ModelDropdown";
import DownloadProgressDisplay from "./DownloadProgressDisplay";
@@ -32,6 +36,7 @@ const ModelSelector: React.FC<ModelSelectorProps> = ({ onError }) => {
verifyingModels,
selectModel,
} = useModelStore();
+ const modelsLocked = useModelsLocked();
const [modelStatus, setModelStatus] = useState<ModelStatus>("unloaded");
const [modelError, setModelError] = useState<string | null>(null);
@@ -102,7 +107,8 @@ const ModelSelector: React.FC<ModelSelectorProps> = ({ onError }) => {
setTimeout(async () => {
try {
const isRecording = await commands.isRecording();
- if (!isRecording) {
+ // A file job holds the current model until it's done.
+ if (!isRecording && !areModelsLocked()) {
setPendingModelId(modelId);
setModelError(null);
setShowModelDropdown(false);
@@ -224,6 +230,7 @@ const ModelSelector: React.FC<ModelSelectorProps> = ({ onError }) => {
status={getDisplayStatus()}
displayText={getModelDisplayText()}
isDropdownOpen={showModelDropdown}
+ busy={modelsLocked}
onClick={() => setShowModelDropdown(!showModelDropdown)}
/>
@@ -232,6 +239,7 @@ const ModelSelector: React.FC<ModelSelectorProps> = ({ onError }) => {
<ModelDropdown
models={models}
currentModelId={displayModelId}
+ locked={modelsLocked}
onModelSelect={handleModelSelect}
/>
)}
diff --git a/src/components/model-selector/ModelStatusButton.tsx b/src/components/model-selector/ModelStatusButton.tsx
index 172a2fa8..3fe9da47 100644
--- a/src/components/model-selector/ModelStatusButton.tsx
+++ b/src/components/model-selector/ModelStatusButton.tsx
@@ -13,6 +13,8 @@ interface ModelStatusButtonProps {
status: ModelStatus;
displayText: string;
isDropdownOpen: boolean;
+ /** Ready, and transcribing in the background. */
+ busy?: boolean;
onClick: () => void;
className?: string;
}
@@ -21,13 +23,16 @@ const ModelStatusButton: React.FC<ModelStatusButtonProps> = ({
status,
displayText,
isDropdownOpen,
+ busy = false,
onClick,
className = "",
}) => {
const getStatusColor = (status: ModelStatus): string => {
switch (status) {
case "ready":
- return "bg-moss";
+ return busy
+ ? "bg-moss animate-pulse motion-reduce:animate-none"
+ : "bg-moss";
case "loading":
return "bg-warning animate-pulse";
case "downloading":
diff --git a/src/components/settings/history/HistorySettings.tsx b/src/components/settings/history/HistorySettings.tsx
index 55a83b4a..cf3bc7a9 100644
--- a/src/components/settings/history/HistorySettings.tsx
+++ b/src/components/settings/history/HistorySettings.tsx
@@ -1,7 +1,23 @@
-import React, { useCallback, useEffect, useRef, useState } from "react";
+import React, {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
import { convertFileSrc } from "@tauri-apps/api/core";
import { readFile } from "@tauri-apps/plugin-fs";
-import { Check, Copy, FolderOpen, RotateCcw, Star, Trash2 } from "lucide-react";
+import {
+ Check,
+ Copy,
+ FileAudio,
+ FilePlus,
+ FolderOpen,
+ RotateCcw,
+ Star,
+ Trash2,
+ X,
+} from "lucide-react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
@@ -11,10 +27,15 @@ import {
type HistoryUpdatePayload,
} from "@/bindings";
import { useOsType } from "@/hooks/useOsType";
+import {
+ useTranscriptionJobsStore,
+ type ActiveJobStatus,
+} from "@/stores/transcriptionJobsStore";
import { formatDateTime } from "@/utils/dateFormat";
import { AudioPlayer, AudioPlayerGroup } from "../../ui/AudioPlayer";
import { Button } from "../../ui/Button";
import { copyToClipboard } from "./clipboard";
+import { pickAndTranscribeFiles } from "./transcribeFiles";
const IconButton: React.FC<{
onClick: () => void;
@@ -39,14 +60,19 @@ const IconButton: React.FC<{
const PAGE_SIZE = 30;
-interface OpenRecordingsButtonProps {
+// Long text folds to this many lines until "Show more".
+const FOLDED_LINES = 4;
+
+interface HeaderButtonProps {
onClick: () => void;
label: string;
+ icon: React.ComponentType<{ className?: string }>;
}
-const OpenRecordingsButton: React.FC<OpenRecordingsButtonProps> = ({
+const HeaderButton: React.FC<HeaderButtonProps> = ({
onClick,
label,
+ icon: Icon,
}) => (
<Button
onClick={onClick}
@@ -55,7 +81,7 @@ const OpenRecordingsButton: React.FC<OpenRecordingsButtonProps> = ({
className="flex items-center gap-2"
title={label}
>
- <FolderOpen className="w-4 h-4" />
+ <Icon className="w-4 h-4" />
<span>{label}</span>
</Button>
);
@@ -63,6 +89,7 @@ const OpenRecordingsButton: React.FC<OpenRecordingsButtonProps> = ({
export const HistorySettings: React.FC = () => {
const { t } = useTranslation();
const osType = useOsType();
+ const jobs = useTranscriptionJobsStore((state) => state.jobs);
const [entries, setEntries] = useState<HistoryEntry[]>([]);
const [loading, setLoading] = useState(true);
const [hasMore, setHasMore] = useState(true);
@@ -217,10 +244,12 @@ export const HistorySettings: React.FC = () => {
}
};
- const retryHistoryEntry = async (id: number) => {
- const result = await commands.retryHistoryEntryTranscription(id);
- if (result.status !== "ok") {
- throw new Error(String(result.error));
+ const transcribeFile = async () => {
+ try {
+ await pickAndTranscribeFiles();
+ } catch (error) {
+ console.error("Failed to pick a file to transcribe:", error);
+ toast.error(t("settings.history.transcribeFailed"));
}
};
@@ -258,11 +287,13 @@ export const HistorySettings: React.FC = () => {
<HistoryEntryComponent
key={entry.id}
entry={entry}
+ job={jobs[entry.id]}
onToggleSaved={() => toggleSaved(entry.id)}
onCopyText={() => copyToClipboard(entry.transcription_text)}
getAudioUrl={getAudioUrl}
deleteAudio={deleteAudioEntry}
- retryTranscription={retryHistoryEntry}
+ retryTranscription={commands.retryHistoryEntryTranscription}
+ cancelTranscription={commands.cancelHistoryEntryTranscription}
/>
))}
</div>
@@ -282,10 +313,18 @@ export const HistorySettings: React.FC = () => {
{t("settings.history.title")}
</h2>
</div>
- <OpenRecordingsButton
- onClick={openRecordingsFolder}
- label={t("settings.history.openFolder")}
- />
+ <div className="flex items-center gap-2">
+ <HeaderButton
+ onClick={transcribeFile}
+ label={t("settings.history.transcribeFile")}
+ icon={FilePlus}
+ />
+ <HeaderButton
+ onClick={openRecordingsFolder}
+ label={t("settings.history.openFolder")}
+ icon={FolderOpen}
+ />
+ </div>
</div>
<div className="bg-background border border-line rounded-lg overflow-visible">
{content}
@@ -297,26 +336,51 @@ export const HistorySettings: React.FC = () => {
interface HistoryEntryProps {
entry: HistoryEntry;
+ job?: ActiveJobStatus;
onToggleSaved: () => void;
onCopyText: () => Promise<boolean>;
getAudioUrl: (fileName: string) => Promise<string | null>;
deleteAudio: (id: number) => Promise<void>;
retryTranscription: (id: number) => Promise<void>;
+ cancelTranscription: (id: number) => Promise<void>;
}
const HistoryEntryComponent: React.FC<HistoryEntryProps> = ({
entry,
+ job,
onToggleSaved,
onCopyText,
getAudioUrl,
deleteAudio,
retryTranscription,
+ cancelTranscription,
}) => {
const { t, i18n } = useTranslation();
const [showCopied, setShowCopied] = useState(false);
- const [retrying, setRetrying] = useState(false);
-
+ // Pressed cancel: a running job stops after its current chunk.
+ const [cancelling, setCancelling] = useState(false);
+ const [expanded, setExpanded] = useState(false);
+ const [overflows, setOverflows] = useState(false);
+ const textRef = useRef<HTMLParagraphElement>(null);
+
+ // Queued or being transcribed in the background.
+ const retrying = job !== undefined;
+ useEffect(() => {
+ if (!retrying) setCancelling(false);
+ }, [retrying]);
const hasTranscription = entry.transcription_text.trim().length > 0;
+ const folded = hasTranscription && !retrying && !expanded;
+
+ // Offer "Show more" only when the folded text is actually cut off.
+ useLayoutEffect(() => {
+ const el = textRef.current;
+ if (!el || !folded) return;
+ const measure = () => setOverflows(el.scrollHeight > el.clientHeight + 1);
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [folded, entry.transcription_text]);
const handleLoadAudio = useCallback(
() => getAudioUrl(entry.file_name),
@@ -347,25 +411,33 @@ const HistoryEntryComponent: React.FC<HistoryEntryProps> = ({
}
};
- const handleRetranscribe = async () => {
- try {
- setRetrying(true);
- await retryTranscription(entry.id);
- } catch (error) {
- console.error("Failed to re-transcribe:", error);
- toast.error(t("settings.history.retranscribeError"));
- } finally {
- setRetrying(false);
- }
- };
-
const formattedDate = formatDateTime(String(entry.timestamp), i18n.language);
+ let progressText = t("settings.history.transcribing");
+ if (job?.state === "queued") {
+ progressText = t("settings.history.waiting");
+ } else if (job?.state === "running" && job.percent > 0) {
+ progressText = t("settings.history.transcribingPercent", {
+ percent: job.percent,
+ });
+ }
+
return (
<div className="px-4 py-2 pb-5 flex flex-col gap-3">
- <div className="flex justify-between items-center">
- <p className="text-sm font-medium">{formattedDate}</p>
- <div className="flex items-center">
+ <div className="flex justify-between items-center gap-3">
+ <div className="flex items-center gap-2 min-w-0">
+ <p className="text-sm font-medium shrink-0">{formattedDate}</p>
+ {entry.source_name && (
+ <span
+ className="flex items-center gap-1 min-w-0 text-sm text-ink-3"
+ title={entry.source_name}
+ >
+ <FileAudio width={14} height={14} className="shrink-0" />
+ <span className="truncate">{entry.source_name}</span>
+ </span>
+ )}
+ </div>
+ <div className="flex items-center shrink-0">
<IconButton
onClick={handleCopyText}
disabled={!hasTranscription || retrying}
@@ -379,7 +451,6 @@ const HistoryEntryComponent: React.FC<HistoryEntryProps> = ({
</IconButton>
<IconButton
onClick={onToggleSaved}
- disabled={retrying}
active={entry.saved}
title={
entry.saved
@@ -393,24 +464,27 @@ const HistoryEntryComponent: React.FC<HistoryEntryProps> = ({
fill={entry.saved ? "currentColor" : "none"}
/>
</IconButton>
- <IconButton
- onClick={handleRetranscribe}
- disabled={retrying}
- title={t("settings.history.retranscribe")}
- >
- <RotateCcw
- width={16}
- height={16}
- style={
- retrying
- ? { animation: "spin 1s linear infinite reverse" }
- : undefined
- }
- />
- </IconButton>
+ {retrying ? (
+ <IconButton
+ onClick={() => {
+ setCancelling(true);
+ void cancelTranscription(entry.id);
+ }}
+ disabled={cancelling}
+ title={t("settings.history.cancelTranscription")}
+ >
+ <X width={16} height={16} />
+ </IconButton>
+ ) : (
+ <IconButton
+ onClick={() => retryTranscription(entry.id)}
+ title={t("settings.history.retranscribe")}
+ >
+ <RotateCcw width={16} height={16} />
+ </IconButton>
+ )}
<IconButton
onClick={handleDeleteEntry}
- disabled={retrying}
title={t("settings.history.delete")}
>
<Trash2 width={16} height={16} />
@@ -418,34 +492,58 @@ const HistoryEntryComponent: React.FC<HistoryEntryProps> = ({
</div>
</div>
- <p
- className={`italic text-sm pb-2 ${
- retrying
- ? ""
- : hasTranscription
- ? "text-text select-text cursor-text whitespace-pre-wrap break-words"
- : "text-ink-3"
- }`}
- style={
- retrying
- ? { animation: "transcribe-pulse 3s ease-in-out infinite" }
- : undefined
- }
- >
- {retrying && (
- <style>{`
+ <div className="flex flex-col items-start gap-1 pb-2">
+ <p
+ ref={textRef}
+ className={`italic text-sm w-full ${
+ retrying
+ ? ""
+ : hasTranscription
+ ? "text-text select-text cursor-text whitespace-pre-wrap break-words"
+ : "text-ink-3"
+ }`}
+ style={
+ retrying
+ ? { animation: "transcribe-pulse 3s ease-in-out infinite" }
+ : folded
+ ? {
+ display: "-webkit-box",
+ WebkitLineClamp: FOLDED_LINES,
+ WebkitBoxOrient: "vertical",
+ overflow: "hidden",
+ }
+ : undefined
+ }
+ >
+ {retrying && (
+ <style>{`
@keyframes transcribe-pulse {
0%, 100% { color: var(--color-ink-3); }
50% { color: var(--color-text); }
}
`}</style>
+ )}
+ {retrying
+ ? progressText
+ : hasTranscription
+ ? entry.transcription_text
+ : entry.source_name
+ ? // Cancelled, interrupted by a quit, or failed.
+ t("settings.history.notTranscribed")
+ : t("settings.history.transcriptionFailed")}
+ </p>
+ {hasTranscription && !retrying && (expanded || overflows) && (
+ <button
+ type="button"
+ onClick={() => setExpanded(!expanded)}
+ className="text-xs font-medium text-ink-3 hover:text-logo-primary cursor-pointer"
+ >
+ {expanded
+ ? t("settings.history.showLess")
+ : t("settings.history.showMore")}
+ </button>
)}
- {retrying
- ? t("settings.history.transcribing")
- : hasTranscription
- ? entry.transcription_text
- : t("settings.history.transcriptionFailed")}
- </p>
+ </div>
<AudioPlayer onLoadRequest={handleLoadAudio} className="w-full" />
</div>
diff --git a/src/components/settings/history/transcribeFiles.ts b/src/components/settings/history/transcribeFiles.ts
new file mode 100644
index 00000000..759e26db
--- /dev/null
+++ b/src/components/settings/history/transcribeFiles.ts
@@ -0,0 +1,66 @@
+import { open } from "@tauri-apps/plugin-dialog";
+import { toast } from "sonner";
+import i18n from "@/i18n";
+import { commands } from "@/bindings";
+
+// What the file picker offers. Dropped files of any type are still tried.
+// No ogg/oga/opus/webm: they're mostly Opus (voice notes), which can't be
+// decoded yet, though Vorbis .ogg works if dropped.
+const MEDIA_EXTENSIONS = [
+ "mp3",
+ "m4a",
+ "aac",
+ "wav",
+ "flac",
+ "aif",
+ "aiff",
+ "mp4",
+ "m4v",
+ "mov",
+];
+
+const fileName = (path: string) => path.split(/[\\/]/).pop() || path;
+
+// Adds each file to History and queues it to be transcribed. Resolves to
+// how many were added.
+export const transcribeFiles = async (paths: string[]): Promise<number> => {
+ let added = 0;
+ for (const path of paths) {
+ // Its audio is read in full before it appears in History.
+ const reading = toast.loading(
+ i18n.t("settings.history.readingFile", { name: fileName(path) }),
+ );
+ let result;
+ try {
+ result = await commands.transcribeFile(path);
+ } finally {
+ toast.dismiss(reading);
+ }
+ if (result.status === "ok") {
+ added += 1;
+ } else {
+ console.error(`Failed to transcribe ${path}:`, result.error);
+ toast.error(
+ i18n.t("settings.history.fileUnsupported", { name: fileName(path) }),
+ );
+ }
+ }
+ return added;
+};
+
+// Asks for files to transcribe. Resolves to false if nothing was picked.
+export const pickAndTranscribeFiles = async (): Promise<boolean> => {
+ const selected = await open({
+ multiple: true,
+ directory: false,
+ filters: [
+ {
+ name: i18n.t("settings.history.mediaFiles"),
+ extensions: MEDIA_EXTENSIONS,
+ },
+ ],
+ });
+ if (!selected) return false;
+ await transcribeFiles(Array.isArray(selected) ? selected : [selected]);
+ return true;
+};
diff --git a/src/components/settings/models/ModelRow.tsx b/src/components/settings/models/ModelRow.tsx
index 9bde9a52..da64748d 100644
--- a/src/components/settings/models/ModelRow.tsx
+++ b/src/components/settings/models/ModelRow.tsx
@@ -1,11 +1,12 @@
import React, { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import { ArrowDown, Loader2, Trash2, X } from "lucide-react";
+import { ArrowDown, Loader2, Lock, Trash2, X } from "lucide-react";
import { Radio } from "@/components/ui/Radio";
import { Button } from "@/components/ui/Button";
import { ModelTableRow } from "@/components/shared/modelTable/ModelTableRow";
import { formatModelSize } from "@/lib/utils/format";
import { useModelStore } from "@/stores/modelStore";
+import { useModelsLocked } from "@/stores/transcriptionJobsStore";
import {
cancelDownload,
pickModel,
@@ -19,18 +20,28 @@ export const ModelRow: React.FC<{ entry: Entry }> = ({ entry }) => {
const { t } = useTranslation();
const place = usePlace(entry.id);
const target = useIsTarget(entry.id);
+ const locked = useModelsLocked();
const percent = useModelStore(
(s) => s.downloadProgress[entry.id]?.percentage ?? 0,
);
const [asking, setAsking] = useState(false);
+ // Pressed while locked: this row says why nothing happened.
+ const [told, setTold] = useState(false);
const askRef = useRef<HTMLSpanElement>(null);
+ useEffect(() => {
+ if (!locked) setTold(false);
+ }, [locked]);
+
useEffect(() => {
if (asking) askRef.current?.querySelector("button")?.focus();
}, [asking]);
const onDisk = place === "active" || place === "ready" || place === "loading";
const on = place === "active";
+ // While History transcribes, the model in use can't change or go away.
+ const deletable = onDisk && !(locked && on);
+ const inert = locked && place === "ready";
const size = formatModelSize(entry.sizeMb);
const download =
place === "downloading" || place === "checking"
@@ -72,9 +83,11 @@ export const ModelRow: React.FC<{ entry: Entry }> = ({ entry }) => {
size,
})}
</span>
+ ) : (locked && on) || (told && inert) ? (
+ t("modelSelector.lockedWhileTranscribing")
) : place === "loading" ? (
t("settings.models.loading")
- ) : place === "downloading" && target ? (
+ ) : place === "downloading" && target && !locked ? (
<span className="tabular-nums">
{t("settings.models.downloadingThenUse", {
percent: Math.round(percent),
@@ -86,6 +99,10 @@ export const ModelRow: React.FC<{ entry: Entry }> = ({ entry }) => {
// Pressing a download makes it the one to switch to when it's done.
const act = () => {
if (asking || on || place === "loading") return;
+ if (inert) {
+ setTold(true);
+ return;
+ }
pickModel(entry.id);
};
@@ -109,7 +126,7 @@ export const ModelRow: React.FC<{ entry: Entry }> = ({ entry }) => {
</button>
);
}
- if (onDisk) {
+ if (deletable) {
const label = t("settings.models.deleteModel", { name: entry.name });
return (
<button
@@ -126,6 +143,9 @@ export const ModelRow: React.FC<{ entry: Entry }> = ({ entry }) => {
</button>
);
}
+ // Where the trash was: the reason it's gone.
+ if (locked && on)
+ return <Lock className="size-[13px] text-ink-3" aria-hidden="true" />;
return <span />;
})();
@@ -167,6 +187,8 @@ export const ModelRow: React.FC<{ entry: Entry }> = ({ entry }) => {
line={line}
slot={slot}
tail={ask || undefined}
+ inert={inert}
+ onDisk={onDisk}
onActivate={act}
onKeyDown={(e) => {
// Escape closes the delete question from its buttons too.
@@ -178,7 +200,7 @@ export const ModelRow: React.FC<{ entry: Entry }> = ({ entry }) => {
return;
}
if (e.target !== e.currentTarget) return;
- if ((e.key === "Delete" || e.key === "Backspace") && onDisk) {
+ if ((e.key === "Delete" || e.key === "Backspace") && deletable) {
e.preventDefault();
setAsking(true);
}
diff --git a/src/components/settings/models/modelEntries.ts b/src/components/settings/models/modelEntries.ts
index 081675a0..7b072a98 100644
--- a/src/components/settings/models/modelEntries.ts
+++ b/src/components/settings/models/modelEntries.ts
@@ -3,6 +3,7 @@ import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { create } from "zustand";
import { useModelStore } from "@/stores/modelStore";
+import { areModelsLocked } from "@/stores/transcriptionJobsStore";
import { useSettings } from "@/hooks/useSettings";
import { useModelCatalog } from "@/hooks/useModelCatalog";
import { averageError, type Grading } from "@/lib/models/grading";
@@ -140,6 +141,11 @@ export const usePlace = (id: string): Place => {
export const useIsTarget = (id: string) => usePageState((s) => s.target === id);
const select = async (id: string) => {
+ // A file is transcribing, so the model in use can't change.
+ if (areModelsLocked()) {
+ usePageState.setState({ target: null });
+ return;
+ }
usePageState.setState({ switching: id, target: null });
try {
await useModelStore.getState().selectModel(id);
@@ -174,7 +180,8 @@ export const pickModel = (id: string) => {
void select(id);
return;
}
- usePageState.setState({ target: id });
+ // Locked: download it, but don't promise to switch to it.
+ if (!areModelsLocked()) usePageState.setState({ target: id });
const done =
id in store.downloadingModels
? whenDownloadEnds(id)
diff --git a/src/components/shared/modelTable/ModelTableRow.tsx b/src/components/shared/modelTable/ModelTableRow.tsx
index f6bae28d..06caa17d 100644
--- a/src/components/shared/modelTable/ModelTableRow.tsx
+++ b/src/components/shared/modelTable/ModelTableRow.tsx
@@ -40,6 +40,10 @@ interface ModelTableRowProps {
/** Runs first; preventDefault() keeps Enter and Space from activating. */
onKeyDown?: (e: React.KeyboardEvent<HTMLDivElement>) => void;
hint?: string;
+ /** Can't be picked right now: no hover, a faded mark. Still clickable. */
+ inert?: boolean;
+ /** Downloaded: never faded for missing your languages. */
+ onDisk?: boolean;
/** View-transition names for onboarding's animations. */
vt?: VtName;
}
@@ -56,13 +60,15 @@ export const ModelTableRow: React.FC<ModelTableRowProps> = ({
onActivate,
onKeyDown,
hint,
+ inert = false,
+ onDisk = false,
vt,
}) => {
const { t } = useTranslation();
const { grading, actions, highlighted } = useModelTable();
const debug = useSettingsStore((s) => s.settings?.debug_mode ?? false);
const role = grading.roleOf(entry.model);
- const dim = grading.missing(entry.model).length > 0 && !tail;
+ const dim = grading.missing(entry.model).length > 0 && !tail && !onDisk;
const capabilities = CAPABILITY_KEYS.filter(
(c) => entry[CAPABILITIES[c].flag],
);
@@ -124,6 +130,7 @@ export const ModelTableRow: React.FC<ModelTableRowProps> = ({
<div
role="radio"
aria-checked={selected}
+ aria-disabled={inert || undefined}
tabIndex={0}
data-row={entry.id}
{...vt?.()}
@@ -144,10 +151,13 @@ export const ModelTableRow: React.FC<ModelTableRowProps> = ({
: selected
? // A quiet grey fill, a step past hover's wash.
"cursor-default bg-line"
- : `cursor-pointer hover:bg-wash ${highlighted === entry.id ? "bg-wash" : ""}`
+ : `${inert ? "cursor-default" : "cursor-pointer hover:bg-wash"} ${highlighted === entry.id ? "bg-wash" : ""}`
}`}
>
- <span {...vt?.("m")} className="grid place-items-center">
+ <span
+ {...vt?.("m")}
+ className={`grid place-items-center ${inert ? "opacity-40" : ""}`}
+ >
{shownMark}
</span>
<span className="flex min-w-0 flex-col items-start">
diff --git a/src/i18n/locales/ar/translation.json b/src/i18n/locales/ar/translation.json
index 98e53df6..497aaa5e 100644
--- a/src/i18n/locales/ar/translation.json
+++ b/src/i18n/locales/ar/translation.json
@@ -317,7 +317,8 @@
"modelError": "خطأ في النموذج",
"modelUnloaded": "تم إلغاء تحميل النموذج",
"noModelDownloadRequired": "لا يوجد نموذج - التنزيل مطلوب",
- "downloadSpeed": "{{speed}} ميجابايت/ث"
+ "downloadSpeed": "{{speed}} ميجابايت/ث",
+ "lockedWhileTranscribing": "يمكنك تغيير النموذج بعد انتهاء النسخ في السجل."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "تقسيم الصوت الطويل",
- "description": "يقسّم التسجيلات الطويلة عند فترات التوقف قبل نسخها، مما يحسّن أداء النسخ عادةً."
+ "description": "يقسّم التسجيلات الطويلة عند فترات التوقف قبل نسخها، مما يحسّن أداء النسخ عادةً. تُقسَّم الملفات المنسوخة وعمليات إعادة النسخ الطويلة دائمًا."
},
"vadBackend": {
"title": "محرك كشف النشاط الصوتي",
@@ -680,9 +681,21 @@
"delete": "حذف الإدخال",
"deleteError": ".فشل حذف الإدخال. يرجى المحاولة مرة أخرى",
"retranscribe": "إعادة النسخ",
- "retranscribeError": "فشلت إعادة النسخ. يرجى المحاولة مرة أخرى.",
+ "cancelTranscription": "إلغاء النسخ",
"transcribing": "جارٍ النسخ...",
- "transcriptionFailed": "فشل النسخ. يمكنك إعادة النسخ باستخدام أيقونة إعادة المحاولة."
+ "transcriptionFailed": "فشل النسخ. يمكنك إعادة النسخ باستخدام أيقونة إعادة المحاولة.",
+ "notTranscribed": "لم يتم النسخ. يمكنك نسخه باستخدام أيقونة إعادة المحاولة.",
+ "transcribeFile": "نسخ ملف",
+ "mediaFiles": "الصوت والفيديو",
+ "fileUnsupported": "تعذّرت قراءة الصوت من {{name}}.",
+ "readingFile": "جارٍ قراءة {{name}}...",
+ "transcribeFailed": "فشل النسخ. يرجى المحاولة مرة أخرى.",
+ "waiting": "في انتظار النسخ",
+ "transcribingPercent": "جارٍ النسخ، {{percent}}%",
+ "showMore": "عرض المزيد",
+ "showLess": "عرض أقل",
+ "dropTitle": "أفلت الملف لنسخه",
+ "dropDescription": "سيظهر في السجل."
},
"debug": {
"title": "تصحيح الأخطاء",
diff --git a/src/i18n/locales/bg/translation.json b/src/i18n/locales/bg/translation.json
index 8becd7cb..fd821ed3 100644
--- a/src/i18n/locales/bg/translation.json
+++ b/src/i18n/locales/bg/translation.json
@@ -317,7 +317,8 @@
"modelError": "Грешка в модела",
"modelUnloaded": "Моделът е разтоварен",
"noModelDownloadRequired": "Няма модел – необходимо е изтегляне",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Можете да смените модела, след като транскрибирането в История приключи."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Разделяне на дълго аудио",
- "description": "Разделя дългите записи на паузите преди транскрибиране, което обикновено подобрява качеството на транскрипцията."
+ "description": "Разделя дългите записи на паузите преди транскрибиране, което обикновено подобрява качеството на транскрипцията. Транскрибираните файлове и дългите повторни транскрипции винаги се разделят."
},
"vadBackend": {
"title": "Бекенд за откриване на глас",
@@ -680,9 +681,21 @@
"delete": "Изтриване на записа",
"deleteError": "Изтриването на записа не бе успешно. Опитайте отново.",
"retranscribe": "Повторна транскрипция",
- "retranscribeError": "Повторната транскрипция не бе успешна. Опитайте отново.",
+ "cancelTranscription": "Отказ от транскрипцията",
"transcribing": "Транскрибиране...",
- "transcriptionFailed": "Транскрипцията не бе успешна. Можете да опитате отново с иконата за повторен опит."
+ "transcriptionFailed": "Транскрипцията не бе успешна. Можете да опитате отново с иконата за повторен опит.",
+ "notTranscribed": "Не е транскрибирано. Можете да го транскрибирате с иконата за повторен опит.",
+ "transcribeFile": "Транскрибиране на файл",
+ "mediaFiles": "Аудио и видео",
+ "fileUnsupported": "Не може да се прочете аудио от {{name}}.",
+ "readingFile": "Четене на {{name}}...",
+ "transcribeFailed": "Транскрипцията не бе успешна. Моля, опитайте отново.",
+ "waiting": "Изчаква транскрибиране",
+ "transcribingPercent": "Транскрибиране, {{percent}}%",
+ "showMore": "Покажи повече",
+ "showLess": "Покажи по-малко",
+ "dropTitle": "Пуснете за транскрибиране",
+ "dropDescription": "Ще се появи в Историята."
},
"debug": {
"title": "Отстраняване",
diff --git a/src/i18n/locales/ca/translation.json b/src/i18n/locales/ca/translation.json
index ce5e9d76..2e60fd93 100644
--- a/src/i18n/locales/ca/translation.json
+++ b/src/i18n/locales/ca/translation.json
@@ -317,7 +317,8 @@
"modelError": "Error del model",
"modelUnloaded": "Model alliberat de la memòria",
"noModelDownloadRequired": "No hi ha cap model: cal baixar-ne un",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Podràs canviar de model quan acabi la transcripció a l'Historial."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Divisió d'àudio llarg",
- "description": "Divideix els enregistraments llargs a les pauses abans de transcriure'ls, cosa que normalment millora el rendiment de la transcripció."
+ "description": "Divideix els enregistraments llargs a les pauses abans de transcriure'ls, cosa que normalment millora el rendiment de la transcripció. Els fitxers transcrits i les retranscripcions llargues sempre es divideixen."
},
"vadBackend": {
"title": "Motor de detecció d'activitat de veu",
@@ -680,9 +681,21 @@
"delete": "Suprimeix l'entrada",
"deleteError": "No s'ha pogut suprimir l'entrada. Torneu-ho a provar.",
"retranscribe": "Torneu a transcriure",
- "retranscribeError": "No s'ha pogut tornar a transcriure. Torneu-ho a provar.",
+ "cancelTranscription": "Cancel·la la transcripció",
"transcribing": "S'està transcrivint...",
- "transcriptionFailed": "La transcripció ha fallat. Podeu tornar a transcriure amb la icona de reintent."
+ "transcriptionFailed": "La transcripció ha fallat. Podeu tornar a transcriure amb la icona de reintent.",
+ "notTranscribed": "No s'ha transcrit. Podeu transcriure-ho amb la icona de reintent.",
+ "transcribeFile": "Transcriu un fitxer",
+ "mediaFiles": "Àudio i vídeo",
+ "fileUnsupported": "No s'ha pogut llegir l'àudio de {{name}}.",
+ "readingFile": "S'està llegint {{name}}...",
+ "transcribeFailed": "La transcripció ha fallat. Torna-ho a provar.",
+ "waiting": "Esperant per transcriure",
+ "transcribingPercent": "Transcrivint, {{percent}}%",
+ "showMore": "Mostra'n més",
+ "showLess": "Mostra'n menys",
+ "dropTitle": "Deixa anar per transcriure",
+ "dropDescription": "Apareixerà a l'historial."
},
"debug": {
"title": "Depuració",
diff --git a/src/i18n/locales/cs/translation.json b/src/i18n/locales/cs/translation.json
index 11cd5ba0..11df6077 100644
--- a/src/i18n/locales/cs/translation.json
+++ b/src/i18n/locales/cs/translation.json
@@ -317,7 +317,8 @@
"modelError": "Chyba modelu",
"modelUnloaded": "Model uvolněn",
"noModelDownloadRequired": "Žádný model - je nutné stáhnout",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Model můžete změnit, až se dokončí přepis v Historii."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Dělení dlouhého zvuku",
- "description": "Před přepisem rozdělí dlouhé nahrávky v pauzách, což obvykle zlepšuje kvalitu přepisu."
+ "description": "Před přepisem rozdělí dlouhé nahrávky v pauzách, což obvykle zlepšuje kvalitu přepisu. Přepisované soubory a dlouhé opakované přepisy se rozdělují vždy."
},
"vadBackend": {
"title": "Backend detekce hlasu",
@@ -680,9 +681,21 @@
"delete": "Smazat záznam",
"deleteError": "Nepodařilo se smazat záznam. Zkuste to prosím znovu.",
"retranscribe": "Přepsat znovu",
- "retranscribeError": "Opětovný přepis se nezdařil. Zkuste to prosím znovu.",
+ "cancelTranscription": "Zrušit přepis",
"transcribing": "Přepisuji...",
- "transcriptionFailed": "Přepis selhal. Můžete zkusit přepis znovu pomocí ikony opakování."
+ "transcriptionFailed": "Přepis selhal. Můžete zkusit přepis znovu pomocí ikony opakování.",
+ "notTranscribed": "Nepřepsáno. Můžete to přepsat pomocí ikony opakování.",
+ "transcribeFile": "Přepsat soubor",
+ "mediaFiles": "Zvuk a video",
+ "fileUnsupported": "Ze souboru {{name}} se nepodařilo načíst zvuk.",
+ "readingFile": "Načítání {{name}}...",
+ "transcribeFailed": "Přepis se nezdařil. Zkuste to prosím znovu.",
+ "waiting": "Čeká na přepis",
+ "transcribingPercent": "Přepisuji, {{percent}} %",
+ "showMore": "Zobrazit více",
+ "showLess": "Zobrazit méně",
+ "dropTitle": "Pusťte pro přepis",
+ "dropDescription": "Zobrazí se v historii."
},
"debug": {
"title": "Ladění",
diff --git a/src/i18n/locales/da/translation.json b/src/i18n/locales/da/translation.json
index dedc6f9a..3a572c22 100644
--- a/src/i18n/locales/da/translation.json
+++ b/src/i18n/locales/da/translation.json
@@ -317,7 +317,8 @@
"modelError": "Modelfejl",
"modelUnloaded": "Model frigjort",
"noModelDownloadRequired": "Ingen model - download påkrævet",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Du kan skifte model, når transskriberingen i Historik er færdig."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Opdeling af lang lyd",
- "description": "Deler lange optagelser ved pauser før transskribering, hvilket typisk forbedrer transskriptionen."
+ "description": "Deler lange optagelser ved pauser før transskribering, hvilket typisk forbedrer transskriptionen. Transskriberede filer og lange gentransskriberinger deles altid."
},
"vadBackend": {
"title": "Stemmedetektions-backend",
@@ -680,9 +681,21 @@
"delete": "Slet post",
"deleteError": "Kunne ikke slette posten. Prøv igen.",
"retranscribe": "Transskribér igen",
- "retranscribeError": "Kunne ikke transskribere igen. Prøv igen.",
+ "cancelTranscription": "Annuller transskription",
"transcribing": "Transskriberer...",
- "transcriptionFailed": "Transskription mislykkedes. Du kan transskribere igen ved hjælp af genforsøgsikonet."
+ "transcriptionFailed": "Transskription mislykkedes. Du kan transskribere igen ved hjælp af genforsøgsikonet.",
+ "notTranscribed": "Ikke transskriberet. Du kan transskribere den ved hjælp af genforsøgsikonet.",
+ "transcribeFile": "Transskriber fil",
+ "mediaFiles": "Lyd og video",
+ "fileUnsupported": "Kunne ikke læse lyd fra {{name}}.",
+ "readingFile": "Læser {{name}}...",
+ "transcribeFailed": "Transskriptionen mislykkedes. Prøv igen.",
+ "waiting": "Venter på transskription",
+ "transcribingPercent": "Transskriberer, {{percent}} %",
+ "showMore": "Vis mere",
+ "showLess": "Vis mindre",
+ "dropTitle": "Slip for at transskribere",
+ "dropDescription": "Den vises i historikken."
},
"debug": {
"title": "Fejlfinding",
diff --git a/src/i18n/locales/de/translation.json b/src/i18n/locales/de/translation.json
index 5d391579..dccf1c04 100644
--- a/src/i18n/locales/de/translation.json
+++ b/src/i18n/locales/de/translation.json
@@ -317,7 +317,8 @@
"modelError": "Modellfehler",
"modelUnloaded": "Modell entladen",
"noModelDownloadRequired": "Kein Modell - Download erforderlich",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Du kannst das Modell wechseln, sobald die Transkription im Verlauf fertig ist."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Lange Aufnahmen aufteilen",
- "description": "Teilt lange Aufnahmen vor der Transkription an Sprechpausen auf, was die Transkription in der Regel verbessert."
+ "description": "Teilt lange Aufnahmen vor der Transkription an Sprechpausen auf, was die Transkription in der Regel verbessert. Transkribierte Dateien und lange erneute Transkriptionen werden immer aufgeteilt."
},
"vadBackend": {
"title": "VAD-Backend",
@@ -680,9 +681,21 @@
"delete": "Eintrag löschen",
"deleteError": "Eintrag konnte nicht gelöscht werden. Bitte versuche es erneut.",
"retranscribe": "Erneut transkribieren",
- "retranscribeError": "Erneute Transkription fehlgeschlagen. Bitte versuche es erneut.",
+ "cancelTranscription": "Transkription abbrechen",
"transcribing": "Transkribiere...",
- "transcriptionFailed": "Transkription fehlgeschlagen. Du kannst über das Wiederholen-Symbol erneut transkribieren."
+ "transcriptionFailed": "Transkription fehlgeschlagen. Du kannst über das Wiederholen-Symbol erneut transkribieren.",
+ "notTranscribed": "Nicht transkribiert. Du kannst es über das Wiederholen-Symbol transkribieren.",
+ "transcribeFile": "Datei transkribieren",
+ "mediaFiles": "Audio und Video",
+ "fileUnsupported": "Audio aus {{name}} konnte nicht gelesen werden.",
+ "readingFile": "{{name}} wird gelesen...",
+ "transcribeFailed": "Transkription fehlgeschlagen. Bitte versuche es erneut.",
+ "waiting": "Wartet auf Transkription",
+ "transcribingPercent": "Transkribiere, {{percent}} %",
+ "showMore": "Mehr anzeigen",
+ "showLess": "Weniger anzeigen",
+ "dropTitle": "Zum Transkribieren ablegen",
+ "dropDescription": "Es erscheint im Verlauf."
},
"debug": {
"title": "Debug",
diff --git a/src/i18n/locales/en/translation.json b/src/i18n/locales/en/translation.json
index c42c5ddb..199ea2d2 100644
--- a/src/i18n/locales/en/translation.json
+++ b/src/i18n/locales/en/translation.json
@@ -317,7 +317,8 @@
"modelError": "Model Error",
"modelUnloaded": "Model Unloaded",
"noModelDownloadRequired": "No Model - Download Required",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "You can switch models once History finishes transcribing."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Long Audio Chunking",
- "description": "Splits long recordings at pauses before transcribing, which typically improves transcription performance."
+ "description": "Splits long recordings at pauses before transcribing, which typically improves transcription performance. Transcribed files and long re-transcriptions are always split."
},
"vadBackend": {
"title": "Voice Activity Backend",
@@ -680,9 +681,21 @@
"delete": "Delete entry",
"deleteError": "Failed to delete entry. Please try again.",
"retranscribe": "Re-transcribe",
- "retranscribeError": "Failed to re-transcribe. Please try again.",
+ "cancelTranscription": "Cancel transcription",
"transcribing": "Transcribing...",
- "transcriptionFailed": "Transcription failed. You can re-transcribe using the retry icon."
+ "transcriptionFailed": "Transcription failed. You can re-transcribe using the retry icon.",
+ "notTranscribed": "Not transcribed. You can transcribe it using the retry icon.",
+ "transcribeFile": "Transcribe File",
+ "mediaFiles": "Audio and video",
+ "fileUnsupported": "Couldn't read audio from {{name}}.",
+ "readingFile": "Reading {{name}}...",
+ "transcribeFailed": "Transcription failed. Please try again.",
+ "waiting": "Waiting to transcribe",
+ "transcribingPercent": "Transcribing, {{percent}}%",
+ "showMore": "Show more",
+ "showLess": "Show less",
+ "dropTitle": "Drop to transcribe",
+ "dropDescription": "It'll show up in History."
},
"debug": {
"title": "Debug",
diff --git a/src/i18n/locales/es/translation.json b/src/i18n/locales/es/translation.json
index 7d5c7393..7e7720e2 100644
--- a/src/i18n/locales/es/translation.json
+++ b/src/i18n/locales/es/translation.json
@@ -317,7 +317,8 @@
"modelError": "Error del modelo",
"modelUnloaded": "Modelo descargado",
"noModelDownloadRequired": "Sin modelo - descarga requerida",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Podrás cambiar de modelo cuando termine la transcripción en el Historial."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "División de audio largo",
- "description": "Divide las grabaciones largas en las pausas antes de transcribirlas, lo que normalmente mejora el rendimiento de la transcripción."
+ "description": "Divide las grabaciones largas en las pausas antes de transcribirlas, lo que normalmente mejora el rendimiento de la transcripción. Los archivos transcritos y las re-transcripciones largas siempre se dividen."
},
"vadBackend": {
"title": "Backend de detección de voz",
@@ -680,9 +681,21 @@
"delete": "Eliminar entrada",
"deleteError": "Error al eliminar la entrada. Por favor, intenta de nuevo.",
"retranscribe": "Re-transcribir",
- "retranscribeError": "No se pudo re-transcribir. Por favor, inténtalo de nuevo.",
+ "cancelTranscription": "Cancelar transcripción",
"transcribing": "Transcribiendo...",
- "transcriptionFailed": "La transcripción falló. Puedes re-transcribir usando el icono de reintentar."
+ "transcriptionFailed": "La transcripción falló. Puedes re-transcribir usando el icono de reintentar.",
+ "notTranscribed": "Sin transcribir. Puedes transcribirlo usando el icono de reintentar.",
+ "transcribeFile": "Transcribir archivo",
+ "mediaFiles": "Audio y vídeo",
+ "fileUnsupported": "No se pudo leer el audio de {{name}}.",
+ "readingFile": "Leyendo {{name}}...",
+ "transcribeFailed": "La transcripción falló. Inténtalo de nuevo.",
+ "waiting": "Esperando para transcribir",
+ "transcribingPercent": "Transcribiendo, {{percent}} %",
+ "showMore": "Mostrar más",
+ "showLess": "Mostrar menos",
+ "dropTitle": "Suelta para transcribir",
+ "dropDescription": "Aparecerá en el historial."
},
"debug": {
"title": "Depuración",
diff --git a/src/i18n/locales/fr/translation.json b/src/i18n/locales/fr/translation.json
index f4816ebb..3d0e4d0a 100644
--- a/src/i18n/locales/fr/translation.json
+++ b/src/i18n/locales/fr/translation.json
@@ -317,7 +317,8 @@
"modelError": "Erreur du Modèle",
"modelUnloaded": "Modèle Déchargé",
"noModelDownloadRequired": "Aucun Modèle - Téléchargement Requis",
- "downloadSpeed": "{{speed}} Mo/s"
+ "downloadSpeed": "{{speed}} Mo/s",
+ "lockedWhileTranscribing": "Vous pourrez changer de modèle une fois la transcription terminée dans l'Historique."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Découpage des longs enregistrements",
- "description": "Découpe les longs enregistrements aux pauses avant la transcription, ce qui améliore généralement la qualité de la transcription."
+ "description": "Découpe les longs enregistrements aux pauses avant la transcription, ce qui améliore généralement la qualité de la transcription. Les fichiers transcrits et les longues re-transcriptions sont toujours découpés."
},
"vadBackend": {
"title": "Backend de détection vocale",
@@ -680,9 +681,21 @@
"delete": "Supprimer l'entrée",
"deleteError": "Échec de la suppression de l'entrée. Veuillez réessayer.",
"retranscribe": "Re-transcrire",
- "retranscribeError": "Impossible de re-transcrire. Veuillez réessayer.",
+ "cancelTranscription": "Annuler la transcription",
"transcribing": "Transcription en cours...",
- "transcriptionFailed": "La transcription a échoué. Vous pouvez re-transcrire en utilisant l'icône de réessai."
+ "transcriptionFailed": "La transcription a échoué. Vous pouvez re-transcrire en utilisant l'icône de réessai.",
+ "notTranscribed": "Non transcrit. Vous pouvez le transcrire en utilisant l'icône de réessai.",
+ "transcribeFile": "Transcrire un fichier",
+ "mediaFiles": "Audio et vidéo",
+ "fileUnsupported": "Impossible de lire l'audio de {{name}}.",
+ "readingFile": "Lecture de {{name}}...",
+ "transcribeFailed": "La transcription a échoué. Veuillez réessayer.",
+ "waiting": "En attente de transcription",
+ "transcribingPercent": "Transcription, {{percent}} %",
+ "showMore": "Afficher plus",
+ "showLess": "Afficher moins",
+ "dropTitle": "Déposez pour transcrire",
+ "dropDescription": "Il apparaîtra dans l'historique."
},
"debug": {
"title": "Débogage",
diff --git a/src/i18n/locales/he/translation.json b/src/i18n/locales/he/translation.json
index 1c12e76e..c88a1d33 100644
--- a/src/i18n/locales/he/translation.json
+++ b/src/i18n/locales/he/translation.json
@@ -317,7 +317,8 @@
"modelError": "שגיאת מודל",
"modelUnloaded": "המודל נפרק",
"noModelDownloadRequired": "אין מודל, נדרשת הורדה",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "אפשר יהיה להחליף מודל אחרי שהתמלול בהיסטוריה יסתיים."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "פיצול שמע ארוך",
- "description": "מפצל הקלטות ארוכות בהפסקות לפני התמלול, מה שבדרך כלל משפר את איכות התמלול."
+ "description": "מפצל הקלטות ארוכות בהפסקות לפני התמלול, מה שבדרך כלל משפר את איכות התמלול. קבצים מתומללים ותמלולים חוזרים ארוכים מפוצלים תמיד."
},
"vadBackend": {
"title": "מנוע זיהוי פעילות קולית",
@@ -680,9 +681,21 @@
"delete": "מחק רשומה",
"deleteError": "מחיקת הרשומה נכשלה. נסה שוב.",
"retranscribe": "תמלל מחדש",
- "retranscribeError": "תמלול מחדש נכשל. נסה שוב.",
+ "cancelTranscription": "ביטול התמלול",
"transcribing": "מתמלל...",
- "transcriptionFailed": "התמלול נכשל. אפשר לתמלל מחדש באמצעות אייקון הניסיון החוזר."
+ "transcriptionFailed": "התמלול נכשל. אפשר לתמלל מחדש באמצעות אייקון הניסיון החוזר.",
+ "notTranscribed": "לא תומלל. אפשר לתמלל באמצעות אייקון הניסיון החוזר.",
+ "transcribeFile": "תמלול קובץ",
+ "mediaFiles": "שמע ווידאו",
+ "fileUnsupported": "לא ניתן לקרוא שמע מ-{{name}}.",
+ "readingFile": "קורא את {{name}}...",
+ "transcribeFailed": "התמלול נכשל. נסו שוב.",
+ "waiting": "ממתין לתמלול",
+ "transcribingPercent": "מתמלל, {{percent}}%",
+ "showMore": "הצג עוד",
+ "showLess": "הצג פחות",
+ "dropTitle": "שחררו כדי לתמלל",
+ "dropDescription": "הוא יופיע בהיסטוריה."
},
"debug": {
"title": "ניפוי שגיאות",
diff --git a/src/i18n/locales/hi/translation.json b/src/i18n/locales/hi/translation.json
index 26e626be..2108622d 100644
--- a/src/i18n/locales/hi/translation.json
+++ b/src/i18n/locales/hi/translation.json
@@ -317,7 +317,8 @@
"modelError": "मॉडल में गड़बड़ी",
"modelUnloaded": "मॉडल अनलोड किया गया",
"noModelDownloadRequired": "कोई मॉडल नहीं - डाउनलोड करना ज़रूरी है",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "इतिहास में ट्रांसक्रिप्शन पूरा होने के बाद आप मॉडल बदल सकते हैं।"
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "लंबे ऑडियो का विभाजन",
- "description": "ट्रांसक्राइब करने से पहले लंबी रिकॉर्डिंग को विरामों पर विभाजित करता है, जिससे आमतौर पर ट्रांसक्रिप्शन बेहतर होता है।"
+ "description": "ट्रांसक्राइब करने से पहले लंबी रिकॉर्डिंग को विरामों पर विभाजित करता है, जिससे आमतौर पर ट्रांसक्रिप्शन बेहतर होता है। ट्रांसक्राइब की गई फ़ाइलें और लंबे पुनः ट्रांसक्रिप्शन हमेशा विभाजित किए जाते हैं।"
},
"vadBackend": {
"title": "वॉइस एक्टिविटी बैकएंड",
@@ -680,9 +681,21 @@
"delete": "एंट्री हटाएं",
"deleteError": "एंट्री हटाई नहीं जा सकी. कृपया फिर से कोशिश करें.",
"retranscribe": "फिर से ट्रांसक्राइब करें",
- "retranscribeError": "फिर से ट्रांसक्राइब नहीं किया जा सका. कृपया फिर से कोशिश करें.",
+ "cancelTranscription": "ट्रांसक्रिप्शन रद्द करें",
"transcribing": "ट्रांसक्राइब हो रहा है...",
- "transcriptionFailed": "ट्रांसक्रिप्शन नहीं हो सका. आप रीट्राई आइकन से फिर से ट्रांसक्राइब कर सकते हैं."
+ "transcriptionFailed": "ट्रांसक्रिप्शन नहीं हो सका. आप रीट्राई आइकन से फिर से ट्रांसक्राइब कर सकते हैं.",
+ "notTranscribed": "ट्रांसक्राइब नहीं हुआ. आप रीट्राई आइकन से इसे ट्रांसक्राइब कर सकते हैं.",
+ "transcribeFile": "फ़ाइल ट्रांसक्राइब करें",
+ "mediaFiles": "ऑडियो और वीडियो",
+ "fileUnsupported": "{{name}} से ऑडियो नहीं पढ़ा जा सका।",
+ "readingFile": "{{name}} पढ़ा जा रहा है...",
+ "transcribeFailed": "ट्रांसक्रिप्शन विफल रहा। कृपया फिर से प्रयास करें।",
+ "waiting": "ट्रांसक्राइब होने की प्रतीक्षा में",
+ "transcribingPercent": "ट्रांसक्राइब हो रहा है, {{percent}}%",
+ "showMore": "और दिखाएँ",
+ "showLess": "कम दिखाएँ",
+ "dropTitle": "ट्रांसक्राइब करने के लिए छोड़ें",
+ "dropDescription": "यह इतिहास में दिखाई देगा।"
},
"debug": {
"title": "डिबग",
diff --git a/src/i18n/locales/id/translation.json b/src/i18n/locales/id/translation.json
index 9392e4a1..229932ac 100644
--- a/src/i18n/locales/id/translation.json
+++ b/src/i18n/locales/id/translation.json
@@ -317,7 +317,8 @@
"modelError": "Kesalahan Model",
"modelUnloaded": "Model Dikeluarkan dari Memori",
"noModelDownloadRequired": "Model Belum Tersedia — Perlu Diunduh",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Anda bisa mengganti model setelah transkripsi di Riwayat selesai."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Pemisahan Audio Panjang",
- "description": "Memisahkan rekaman panjang pada jeda sebelum ditranskripsi, yang biasanya meningkatkan kinerja transkripsi."
+ "description": "Memisahkan rekaman panjang pada jeda sebelum ditranskripsi, yang biasanya meningkatkan kinerja transkripsi. File yang ditranskripsi dan transkripsi ulang yang panjang selalu dipisahkan."
},
"vadBackend": {
"title": "Backend Deteksi Aktivitas Suara",
@@ -680,9 +681,21 @@
"delete": "Hapus entri",
"deleteError": "Gagal menghapus entri. Silakan coba lagi.",
"retranscribe": "Transkripsikan ulang",
- "retranscribeError": "Gagal mentranskripsikan ulang. Silakan coba lagi.",
+ "cancelTranscription": "Batalkan transkripsi",
"transcribing": "Mentranskripsikan...",
- "transcriptionFailed": "Transkripsi gagal. Anda dapat mentranskripsikan ulang menggunakan ikon coba lagi."
+ "transcriptionFailed": "Transkripsi gagal. Anda dapat mentranskripsikan ulang menggunakan ikon coba lagi.",
+ "notTranscribed": "Belum ditranskripsikan. Anda dapat mentranskripsikannya menggunakan ikon coba lagi.",
+ "transcribeFile": "Transkripsikan File",
+ "mediaFiles": "Audio dan video",
+ "fileUnsupported": "Tidak dapat membaca audio dari {{name}}.",
+ "readingFile": "Membaca {{name}}...",
+ "transcribeFailed": "Transkripsi gagal. Silakan coba lagi.",
+ "waiting": "Menunggu untuk ditranskripsi",
+ "transcribingPercent": "Mentranskripsi, {{percent}}%",
+ "showMore": "Tampilkan lebih banyak",
+ "showLess": "Tampilkan lebih sedikit",
+ "dropTitle": "Lepaskan untuk mentranskripsi",
+ "dropDescription": "Akan muncul di Riwayat."
},
"debug": {
"title": "Debug",
diff --git a/src/i18n/locales/it/translation.json b/src/i18n/locales/it/translation.json
index b0863940..7515cee5 100644
--- a/src/i18n/locales/it/translation.json
+++ b/src/i18n/locales/it/translation.json
@@ -317,7 +317,8 @@
"modelError": "Errore del Modello",
"modelUnloaded": "Modello Disattivato",
"noModelDownloadRequired": "Nessun Modello - Download Richiesto",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Potrai cambiare modello al termine della trascrizione nella Cronologia."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Suddivisione dell'audio lungo",
- "description": "Suddivide le registrazioni lunghe in corrispondenza delle pause prima della trascrizione, il che di solito migliora le prestazioni della trascrizione."
+ "description": "Suddivide le registrazioni lunghe in corrispondenza delle pause prima della trascrizione, il che di solito migliora le prestazioni della trascrizione. I file trascritti e le ri-trascrizioni lunghe vengono sempre suddivisi."
},
"vadBackend": {
"title": "Backend di rilevamento vocale",
@@ -680,9 +681,21 @@
"delete": "Elimina elemento",
"deleteError": "Errore nell'eliminazione dell'elemento. Riprova.",
"retranscribe": "Ri-trascrivere",
- "retranscribeError": "Impossibile ri-trascrivere. Riprova.",
+ "cancelTranscription": "Annulla trascrizione",
"transcribing": "Trascrizione in corso...",
- "transcriptionFailed": "Trascrizione fallita. Puoi ri-trascrivere usando l'icona di ripetizione."
+ "transcriptionFailed": "Trascrizione fallita. Puoi ri-trascrivere usando l'icona di ripetizione.",
+ "notTranscribed": "Non trascritto. Puoi trascriverlo usando l'icona di ripetizione.",
+ "transcribeFile": "Trascrivi file",
+ "mediaFiles": "Audio e video",
+ "fileUnsupported": "Impossibile leggere l'audio da {{name}}.",
+ "readingFile": "Lettura di {{name}}...",
+ "transcribeFailed": "Trascrizione non riuscita. Riprova.",
+ "waiting": "In attesa di trascrizione",
+ "transcribingPercent": "Trascrizione, {{percent}}%",
+ "showMore": "Mostra di più",
+ "showLess": "Mostra di meno",
+ "dropTitle": "Rilascia per trascrivere",
+ "dropDescription": "Comparirà nella cronologia."
},
"debug": {
"title": "Debug",
diff --git a/src/i18n/locales/ja/translation.json b/src/i18n/locales/ja/translation.json
index 5277a3ba..8ec64a3b 100644
--- a/src/i18n/locales/ja/translation.json
+++ b/src/i18n/locales/ja/translation.json
@@ -317,7 +317,8 @@
"modelError": "モデルエラー",
"modelUnloaded": "モデルがアンロードされました",
"noModelDownloadRequired": "モデルなし - ダウンロードが必要",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "履歴の文字起こしが終わるとモデルを変更できます。"
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "長い音声の分割",
- "description": "文字起こしの前に長い録音を無音部分で分割します。通常、文字起こしの精度が向上します。"
+ "description": "文字起こしの前に長い録音を無音部分で分割します。通常、文字起こしの精度が向上します。ファイルの文字起こしと長い再文字起こしは常に分割されます。"
},
"vadBackend": {
"title": "音声区間検出バックエンド",
@@ -680,9 +681,21 @@
"delete": "エントリーを削除",
"deleteError": "エントリーの削除に失敗しました。もう一度お試しください。",
"retranscribe": "再文字起こし",
- "retranscribeError": "再文字起こしに失敗しました。もう一度お試しください。",
+ "cancelTranscription": "文字起こしをキャンセル",
"transcribing": "文字起こし中…",
- "transcriptionFailed": "文字起こしに失敗しました。リトライアイコンを使用して再文字起こしできます。"
+ "transcriptionFailed": "文字起こしに失敗しました。リトライアイコンを使用して再文字起こしできます。",
+ "notTranscribed": "文字起こしされていません。リトライアイコンを使用して文字起こしできます。",
+ "transcribeFile": "ファイルを文字起こし",
+ "mediaFiles": "音声と動画",
+ "fileUnsupported": "{{name}} から音声を読み込めませんでした。",
+ "readingFile": "{{name}} を読み込み中...",
+ "transcribeFailed": "文字起こしに失敗しました。もう一度お試しください。",
+ "waiting": "文字起こし待ち",
+ "transcribingPercent": "文字起こし中… {{percent}}%",
+ "showMore": "もっと見る",
+ "showLess": "閉じる",
+ "dropTitle": "ドロップして文字起こし",
+ "dropDescription": "履歴に表示されます。"
},
"debug": {
"title": "デバッグ",
diff --git a/src/i18n/locales/ko/translation.json b/src/i18n/locales/ko/translation.json
index 5781ec45..54a20196 100644
--- a/src/i18n/locales/ko/translation.json
+++ b/src/i18n/locales/ko/translation.json
@@ -317,7 +317,8 @@
"modelError": "모델 오류",
"modelUnloaded": "모델 언로드됨",
"noModelDownloadRequired": "모델 없음 - 다운로드 필요",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "히스토리의 받아쓰기가 끝나면 모델을 변경할 수 있습니다."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "긴 오디오 분할",
- "description": "전사하기 전에 긴 녹음을 쉬는 구간에서 나눕니다. 일반적으로 전사 성능이 향상됩니다."
+ "description": "전사하기 전에 긴 녹음을 쉬는 구간에서 나눕니다. 일반적으로 전사 성능이 향상됩니다. 파일 전사와 긴 재전사는 항상 나누어 처리됩니다."
},
"vadBackend": {
"title": "음성 활동 감지 백엔드",
@@ -680,9 +681,21 @@
"delete": "항목 삭제",
"deleteError": "항목 삭제에 실패했습니다. 다시 시도해주세요.",
"retranscribe": "다시 전사",
- "retranscribeError": "다시 전사에 실패했습니다. 다시 시도해주세요.",
+ "cancelTranscription": "전사 취소",
"transcribing": "전사 중...",
- "transcriptionFailed": "전사에 실패했습니다. 재시도 아이콘을 사용하여 다시 전사할 수 있습니다."
+ "transcriptionFailed": "전사에 실패했습니다. 재시도 아이콘을 사용하여 다시 전사할 수 있습니다.",
+ "notTranscribed": "전사되지 않았습니다. 재시도 아이콘을 사용하여 전사할 수 있습니다.",
+ "transcribeFile": "파일 받아쓰기",
+ "mediaFiles": "오디오 및 비디오",
+ "fileUnsupported": "{{name}}에서 오디오를 읽을 수 없습니다.",
+ "readingFile": "{{name}} 읽는 중...",
+ "transcribeFailed": "받아쓰기에 실패했습니다. 다시 시도해 주세요.",
+ "waiting": "받아쓰기 대기 중",
+ "transcribingPercent": "받아쓰는 중, {{percent}}%",
+ "showMore": "더 보기",
+ "showLess": "간략히 보기",
+ "dropTitle": "놓아서 받아쓰기",
+ "dropDescription": "기록에 표시됩니다."
},
"debug": {
"title": "디버그",
diff --git a/src/i18n/locales/ne/translation.json b/src/i18n/locales/ne/translation.json
index 388b631b..8263f624 100644
--- a/src/i18n/locales/ne/translation.json
+++ b/src/i18n/locales/ne/translation.json
@@ -317,7 +317,8 @@
"modelError": "मोडेल त्रुटि",
"modelUnloaded": "मोडेल अनलोड गरियो",
"noModelDownloadRequired": "मोडेल छैन - डाउनलोड आवश्यक",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "हिस्ट्रीमा ट्रान्सक्रिप्सन सकिएपछि तपाईं मोडेल परिवर्तन गर्न सक्नुहुन्छ।"
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "लामो अडियो विभाजन",
- "description": "ट्रान्सक्राइब गर्नुअघि लामो रेकर्डिङलाई विरामहरूमा विभाजन गर्छ, जसले सामान्यतया ट्रान्सक्रिप्सन सुधार गर्छ।"
+ "description": "ट्रान्सक्राइब गर्नुअघि लामो रेकर्डिङलाई विरामहरूमा विभाजन गर्छ, जसले सामान्यतया ट्रान्सक्रिप्सन सुधार गर्छ। ट्रान्सक्राइब गरिएका फाइलहरू र लामो पुनः ट्रान्सक्रिप्सनहरू सधैं विभाजन गरिन्छन्।"
},
"vadBackend": {
"title": "भ्वाइस एक्टिभिटी ब्याकएन्ड",
@@ -680,9 +681,21 @@
"delete": "प्रविष्टि मेटाउनुहोस्",
"deleteError": "प्रविष्टि मेटाउन सकिएन। कृपया फेरि प्रयास गर्नुहोस्।",
"retranscribe": "फेरि ट्रान्सक्राइब गर्नुहोस्",
- "retranscribeError": "फेरि ट्रान्सक्राइब गर्न सकिएन। कृपया फेरि प्रयास गर्नुहोस्।",
+ "cancelTranscription": "ट्रान्सक्रिप्सन रद्द गर्नुहोस्",
"transcribing": "ट्रान्सक्राइब गरिँदैछ...",
- "transcriptionFailed": "ट्रान्सक्रिप्सन गर्न सकिएन। रिट्राई आइकन प्रयोग गरेर फेरि ट्रान्सक्राइब गर्न सक्नुहुन्छ।"
+ "transcriptionFailed": "ट्रान्सक्रिप्सन गर्न सकिएन। रिट्राई आइकन प्रयोग गरेर फेरि ट्रान्सक्राइब गर्न सक्नुहुन्छ।",
+ "notTranscribed": "ट्रान्सक्राइब भएको छैन। रिट्राई आइकन प्रयोग गरेर ट्रान्सक्राइब गर्न सक्नुहुन्छ।",
+ "transcribeFile": "फाइल ट्रान्सक्राइब गर्नुहोस्",
+ "mediaFiles": "अडियो र भिडियो",
+ "fileUnsupported": "{{name}} बाट अडियो पढ्न सकिएन।",
+ "readingFile": "{{name}} पढ्दै...",
+ "transcribeFailed": "ट्रान्सक्रिप्सन असफल भयो। कृपया फेरि प्रयास गर्नुहोस्।",
+ "waiting": "ट्रान्सक्राइब हुन पर्खँदै",
+ "transcribingPercent": "ट्रान्सक्राइब हुँदै, {{percent}}%",
+ "showMore": "थप देखाउनुहोस्",
+ "showLess": "कम देखाउनुहोस्",
+ "dropTitle": "ट्रान्सक्राइब गर्न छोड्नुहोस्",
+ "dropDescription": "यो इतिहासमा देखिनेछ।"
},
"debug": {
"title": "डिबग",
diff --git a/src/i18n/locales/nl/translation.json b/src/i18n/locales/nl/translation.json
index e53816c3..5d177a17 100644
--- a/src/i18n/locales/nl/translation.json
+++ b/src/i18n/locales/nl/translation.json
@@ -317,7 +317,8 @@
"modelError": "Modelfout",
"modelUnloaded": "Model ontladen",
"noModelDownloadRequired": "Geen model - Download vereist",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Je kunt van model wisselen zodra het transcriberen in Geschiedenis klaar is."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Lange audio opsplitsen",
- "description": "Splitst lange opnames bij pauzes op voordat ze worden getranscribeerd, wat de transcriptie doorgaans verbetert."
+ "description": "Splitst lange opnames bij pauzes op voordat ze worden getranscribeerd, wat de transcriptie doorgaans verbetert. Getranscribeerde bestanden en lange hertranscripties worden altijd opgesplitst."
},
"vadBackend": {
"title": "VAD-backend",
@@ -680,9 +681,21 @@
"delete": "Item verwijderen",
"deleteError": "Item verwijderen mislukt. Probeer het opnieuw.",
"retranscribe": "Opnieuw transcriberen",
- "retranscribeError": "Opnieuw transcriberen mislukt. Probeer het opnieuw.",
+ "cancelTranscription": "Transcriptie annuleren",
"transcribing": "Transcriberen...",
- "transcriptionFailed": "Transcriptie mislukt. Je kunt het opnieuw proberen via het herlaad-pictogram."
+ "transcriptionFailed": "Transcriptie mislukt. Je kunt het opnieuw proberen via het herlaad-pictogram.",
+ "notTranscribed": "Niet getranscribeerd. Je kunt het transcriberen via het herlaad-pictogram.",
+ "transcribeFile": "Bestand transcriberen",
+ "mediaFiles": "Audio en video",
+ "fileUnsupported": "Kon geen audio lezen uit {{name}}.",
+ "readingFile": "{{name}} wordt gelezen...",
+ "transcribeFailed": "Transcriptie mislukt. Probeer het opnieuw.",
+ "waiting": "Wacht op transcriptie",
+ "transcribingPercent": "Transcriberen, {{percent}}%",
+ "showMore": "Meer tonen",
+ "showLess": "Minder tonen",
+ "dropTitle": "Loslaten om te transcriberen",
+ "dropDescription": "Het verschijnt in de geschiedenis."
},
"debug": {
"title": "Probleemoplossing",
diff --git a/src/i18n/locales/pl/translation.json b/src/i18n/locales/pl/translation.json
index ac9c394b..ab99d234 100644
--- a/src/i18n/locales/pl/translation.json
+++ b/src/i18n/locales/pl/translation.json
@@ -317,7 +317,8 @@
"modelError": "Błąd modelu",
"modelUnloaded": "Model wyładowany",
"noModelDownloadRequired": "Brak modelu – wymagane pobranie",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Model będzie można zmienić po zakończeniu transkrypcji w Historii."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Dzielenie długich nagrań",
- "description": "Dzieli długie nagrania w miejscach pauz przed transkrypcją, co zwykle poprawia jakość transkrypcji."
+ "description": "Dzieli długie nagrania w miejscach pauz przed transkrypcją, co zwykle poprawia jakość transkrypcji. Transkrybowane pliki i długie ponowne transkrypcje są zawsze dzielone."
},
"vadBackend": {
"title": "Backend wykrywania głosu",
@@ -680,9 +681,21 @@
"delete": "Usuń wpis",
"deleteError": "Nie udało się usunąć wpisu. Spróbuj ponownie.",
"retranscribe": "Transkrybuj ponownie",
- "retranscribeError": "Nie udało się ponownie transkrybować. Spróbuj ponownie.",
+ "cancelTranscription": "Anuluj transkrypcję",
"transcribing": "Transkrybuję...",
- "transcriptionFailed": "Transkrypcja nie powiodła się. Możesz transkrybować ponownie za pomocą ikony ponowienia."
+ "transcriptionFailed": "Transkrypcja nie powiodła się. Możesz transkrybować ponownie za pomocą ikony ponowienia.",
+ "notTranscribed": "Nie przetranskrybowano. Możesz to przetranskrybować za pomocą ikony ponowienia.",
+ "transcribeFile": "Transkrybuj plik",
+ "mediaFiles": "Audio i wideo",
+ "fileUnsupported": "Nie udało się odczytać dźwięku z {{name}}.",
+ "readingFile": "Wczytywanie {{name}}...",
+ "transcribeFailed": "Transkrypcja nie powiodła się. Spróbuj ponownie.",
+ "waiting": "Oczekuje na transkrypcję",
+ "transcribingPercent": "Transkrypcja, {{percent}}%",
+ "showMore": "Pokaż więcej",
+ "showLess": "Pokaż mniej",
+ "dropTitle": "Upuść, aby transkrybować",
+ "dropDescription": "Pojawi się w historii."
},
"debug": {
"title": "Debugowanie",
diff --git a/src/i18n/locales/pt/translation.json b/src/i18n/locales/pt/translation.json
index 57ef7b9b..3b131a7b 100644
--- a/src/i18n/locales/pt/translation.json
+++ b/src/i18n/locales/pt/translation.json
@@ -317,7 +317,8 @@
"modelError": "Erro no Modelo",
"modelUnloaded": "Modelo Descarregado",
"noModelDownloadRequired": "Sem Modelo - Download Necessário",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Você poderá trocar de modelo quando a transcrição no Histórico terminar."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Divisão de áudio longo",
- "description": "Divide gravações longas nas pausas antes da transcrição, o que normalmente melhora o desempenho da transcrição."
+ "description": "Divide gravações longas nas pausas antes da transcrição, o que normalmente melhora o desempenho da transcrição. Arquivos transcritos e re-transcrições longas são sempre divididos."
},
"vadBackend": {
"title": "Backend de detecção de voz",
@@ -680,9 +681,21 @@
"delete": "Excluir entrada",
"deleteError": "Falha ao excluir entrada. Por favor, tente novamente.",
"retranscribe": "Re-transcrever",
- "retranscribeError": "Falha ao re-transcrever. Por favor, tente novamente.",
+ "cancelTranscription": "Cancelar transcrição",
"transcribing": "Transcrevendo...",
- "transcriptionFailed": "A transcrição falhou. Você pode re-transcrever usando o ícone de tentar novamente."
+ "transcriptionFailed": "A transcrição falhou. Você pode re-transcrever usando o ícone de tentar novamente.",
+ "notTranscribed": "Não transcrito. Você pode transcrevê-lo usando o ícone de tentar novamente.",
+ "transcribeFile": "Transcrever arquivo",
+ "mediaFiles": "Áudio e vídeo",
+ "fileUnsupported": "Não foi possível ler o áudio de {{name}}.",
+ "readingFile": "Lendo {{name}}...",
+ "transcribeFailed": "A transcrição falhou. Tente novamente.",
+ "waiting": "Aguardando transcrição",
+ "transcribingPercent": "Transcrevendo, {{percent}}%",
+ "showMore": "Mostrar mais",
+ "showLess": "Mostrar menos",
+ "dropTitle": "Solte para transcrever",
+ "dropDescription": "Ele aparecerá no histórico."
},
"debug": {
"title": "Depuração",
diff --git a/src/i18n/locales/ru/translation.json b/src/i18n/locales/ru/translation.json
index 0be258a8..75e1e3fe 100644
--- a/src/i18n/locales/ru/translation.json
+++ b/src/i18n/locales/ru/translation.json
@@ -317,7 +317,8 @@
"modelError": "Ошибка модели",
"modelUnloaded": "Модель выгружена",
"noModelDownloadRequired": "Нет модели – требуется загрузка",
- "downloadSpeed": "{{speed}} МБ/с"
+ "downloadSpeed": "{{speed}} МБ/с",
+ "lockedWhileTranscribing": "Модель можно будет сменить, когда закончится расшифровка в Истории."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Разделение длинного аудио",
- "description": "Разделяет длинные записи по паузам перед распознаванием, что обычно улучшает качество распознавания."
+ "description": "Разделяет длинные записи по паузам перед распознаванием, что обычно улучшает качество распознавания. Расшифровываемые файлы и длинные повторные расшифровки всегда разделяются."
},
"vadBackend": {
"title": "Движок определения голоса",
@@ -680,9 +681,21 @@
"delete": "Удалить запись",
"deleteError": "Не удалось удалить запись. Пожалуйста, попробуйте еще раз.",
"retranscribe": "Перетранскрибировать",
- "retranscribeError": "Не удалось перетранскрибировать. Пожалуйста, попробуйте снова.",
+ "cancelTranscription": "Отменить транскрипцию",
"transcribing": "Транскрибирование...",
- "transcriptionFailed": "Транскрипция не удалась. Вы можете перетранскрибировать, используя значок повтора."
+ "transcriptionFailed": "Транскрипция не удалась. Вы можете перетранскрибировать, используя значок повтора.",
+ "notTranscribed": "Не транскрибировано. Вы можете транскрибировать, используя значок повтора.",
+ "transcribeFile": "Расшифровать файл",
+ "mediaFiles": "Аудио и видео",
+ "fileUnsupported": "Не удалось прочитать аудио из {{name}}.",
+ "readingFile": "Чтение {{name}}...",
+ "transcribeFailed": "Не удалось выполнить расшифровку. Попробуйте ещё раз.",
+ "waiting": "Ожидает расшифровки",
+ "transcribingPercent": "Расшифровка, {{percent}}%",
+ "showMore": "Показать больше",
+ "showLess": "Показать меньше",
+ "dropTitle": "Отпустите, чтобы расшифровать",
+ "dropDescription": "Он появится в истории."
},
"debug": {
"title": "Отлаживать",
diff --git a/src/i18n/locales/sv/translation.json b/src/i18n/locales/sv/translation.json
index 1364cd63..18894620 100644
--- a/src/i18n/locales/sv/translation.json
+++ b/src/i18n/locales/sv/translation.json
@@ -317,7 +317,8 @@
"modelError": "Modellfel",
"modelUnloaded": "Modell avlastad",
"noModelDownloadRequired": "Ingen modell - Nedladdning krävs",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Du kan byta modell när transkriberingen i Historik är klar."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Dela upp långt ljud",
- "description": "Delar upp långa inspelningar vid pauser före transkribering, vilket oftast förbättrar transkriberingen."
+ "description": "Delar upp långa inspelningar vid pauser före transkribering, vilket oftast förbättrar transkriberingen. Transkriberade filer och långa omtranskriberingar delas alltid upp."
},
"vadBackend": {
"title": "Backend för röstdetektering",
@@ -680,9 +681,21 @@
"delete": "Ta bort post",
"deleteError": "Misslyckades med att ta bort post. Försök igen.",
"retranscribe": "Transkribera igen",
- "retranscribeError": "Misslyckades med att transkribera igen. Försök igen.",
+ "cancelTranscription": "Avbryt transkribering",
"transcribing": "Transkriberar...",
- "transcriptionFailed": "Transkribering misslyckades. Du kan transkribera igen med hjälp av ikonen för nytt försök."
+ "transcriptionFailed": "Transkribering misslyckades. Du kan transkribera igen med hjälp av ikonen för nytt försök.",
+ "notTranscribed": "Inte transkriberad. Du kan transkribera den med hjälp av ikonen för nytt försök.",
+ "transcribeFile": "Transkribera fil",
+ "mediaFiles": "Ljud och video",
+ "fileUnsupported": "Kunde inte läsa ljud från {{name}}.",
+ "readingFile": "Läser {{name}}...",
+ "transcribeFailed": "Transkriberingen misslyckades. Försök igen.",
+ "waiting": "Väntar på transkribering",
+ "transcribingPercent": "Transkriberar, {{percent}} %",
+ "showMore": "Visa mer",
+ "showLess": "Visa mindre",
+ "dropTitle": "Släpp för att transkribera",
+ "dropDescription": "Den visas i historiken."
},
"debug": {
"title": "Felsökning",
diff --git a/src/i18n/locales/tr/translation.json b/src/i18n/locales/tr/translation.json
index e379d3ad..88916568 100644
--- a/src/i18n/locales/tr/translation.json
+++ b/src/i18n/locales/tr/translation.json
@@ -317,7 +317,8 @@
"modelError": "Model Hatası",
"modelUnloaded": "Model Boşaltıldı",
"noModelDownloadRequired": "Model Yok – İndirme Gerekli",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Geçmiş'teki yazıya dökme bitince modeli değiştirebilirsiniz."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Uzun Sesi Bölme",
- "description": "Uzun kayıtları yazıya dökmeden önce duraklamalardan böler; bu genellikle yazıya dökme performansını artırır."
+ "description": "Uzun kayıtları yazıya dökmeden önce duraklamalardan böler; bu genellikle yazıya dökme performansını artırır. Yazıya dökülen dosyalar ve uzun yeniden transkripsiyonlar her zaman bölünür."
},
"vadBackend": {
"title": "Ses Etkinliği Arka Ucu",
@@ -680,9 +681,21 @@
"delete": "Kaydı sil",
"deleteError": "Kayıt silinemedi. Lütfen tekrar deneyin.",
"retranscribe": "Yeniden transkribe et",
- "retranscribeError": "Yeniden transkripsiyon başarısız oldu. Lütfen tekrar deneyin.",
+ "cancelTranscription": "Transkripsiyonu iptal et",
"transcribing": "Transkribe ediliyor...",
- "transcriptionFailed": "Transkripsiyon başarısız oldu. Yeniden deneme simgesini kullanarak tekrar transkribe edebilirsiniz."
+ "transcriptionFailed": "Transkripsiyon başarısız oldu. Yeniden deneme simgesini kullanarak tekrar transkribe edebilirsiniz.",
+ "notTranscribed": "Transkribe edilmedi. Yeniden deneme simgesini kullanarak transkribe edebilirsiniz.",
+ "transcribeFile": "Dosyayı Yazıya Dök",
+ "mediaFiles": "Ses ve video",
+ "fileUnsupported": "{{name}} dosyasından ses okunamadı.",
+ "readingFile": "{{name}} okunuyor...",
+ "transcribeFailed": "Yazıya dökme başarısız oldu. Lütfen tekrar deneyin.",
+ "waiting": "Yazıya dökülmeyi bekliyor",
+ "transcribingPercent": "Yazıya dökülüyor, %{{percent}}",
+ "showMore": "Daha fazla göster",
+ "showLess": "Daha az göster",
+ "dropTitle": "Yazıya dökmek için bırakın",
+ "dropDescription": "Geçmiş'te görünecek."
},
"debug": {
"title": "Hata Ayıklama",
diff --git a/src/i18n/locales/uk/translation.json b/src/i18n/locales/uk/translation.json
index 1d017f9d..3b036ebf 100644
--- a/src/i18n/locales/uk/translation.json
+++ b/src/i18n/locales/uk/translation.json
@@ -317,7 +317,8 @@
"modelError": "Помилка моделі",
"modelUnloaded": "Модель вивантажена",
"noModelDownloadRequired": "Немає моделі - потрібно завантажити",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Модель можна буде змінити, коли завершиться розшифрування в Історії."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Поділ довгого аудіо",
- "description": "Розділяє довгі записи за паузами перед розпізнаванням, що зазвичай покращує якість розпізнавання."
+ "description": "Розділяє довгі записи за паузами перед розпізнаванням, що зазвичай покращує якість розпізнавання. Розшифровувані файли та довгі повторні розшифрування завжди розділяються."
},
"vadBackend": {
"title": "Рушій виявлення голосу",
@@ -680,9 +681,21 @@
"delete": "Видалити запис",
"deleteError": "Не вдалося видалити запис. Спробуйте ще раз.",
"retranscribe": "Перетранскрибувати",
- "retranscribeError": "Не вдалося перетранскрибувати. Будь ласка, спробуйте ще раз.",
+ "cancelTranscription": "Скасувати транскрипцію",
"transcribing": "Транскрибування...",
- "transcriptionFailed": "Транскрипція не вдалася. Ви можете перетранскрибувати за допомогою іконки повтору."
+ "transcriptionFailed": "Транскрипція не вдалася. Ви можете перетранскрибувати за допомогою іконки повтору.",
+ "notTranscribed": "Не транскрибовано. Ви можете транскрибувати за допомогою іконки повтору.",
+ "transcribeFile": "Розшифрувати файл",
+ "mediaFiles": "Аудіо та відео",
+ "fileUnsupported": "Не вдалося прочитати аудіо з {{name}}.",
+ "readingFile": "Читання {{name}}...",
+ "transcribeFailed": "Не вдалося розшифрувати. Спробуйте ще раз.",
+ "waiting": "Очікує на розшифрування",
+ "transcribingPercent": "Розшифрування, {{percent}}%",
+ "showMore": "Показати більше",
+ "showLess": "Показати менше",
+ "dropTitle": "Відпустіть, щоб розшифрувати",
+ "dropDescription": "Він з'явиться в історії."
},
"debug": {
"title": "Дебаг",
diff --git a/src/i18n/locales/vi/translation.json b/src/i18n/locales/vi/translation.json
index db06c3e4..1235b039 100644
--- a/src/i18n/locales/vi/translation.json
+++ b/src/i18n/locales/vi/translation.json
@@ -317,7 +317,8 @@
"modelError": "Lỗi Mô Hình",
"modelUnloaded": "Mô Hình Đã Gỡ",
"noModelDownloadRequired": "Chưa Có Mô Hình - Cần Tải Xuống",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "Bạn có thể đổi mô hình sau khi việc chép lời trong Lịch sử hoàn tất."
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "Chia nhỏ âm thanh dài",
- "description": "Chia các bản ghi dài tại các khoảng ngắt trước khi chuyển thành văn bản, điều này thường cải thiện hiệu quả chuyển văn bản."
+ "description": "Chia các bản ghi dài tại các khoảng ngắt trước khi chuyển thành văn bản, điều này thường cải thiện hiệu quả chuyển văn bản. Tệp được chép lời và các lần phiên âm lại dài luôn được chia nhỏ."
},
"vadBackend": {
"title": "Bộ phát hiện giọng nói",
@@ -680,9 +681,21 @@
"delete": "Xóa mục",
"deleteError": "Không thể xóa mục. Vui lòng thử lại.",
"retranscribe": "Phiên âm lại",
- "retranscribeError": "Không thể phiên âm lại. Vui lòng thử lại.",
+ "cancelTranscription": "Hủy phiên âm",
"transcribing": "Đang phiên âm...",
- "transcriptionFailed": "Phiên âm thất bại. Bạn có thể phiên âm lại bằng biểu tượng thử lại."
+ "transcriptionFailed": "Phiên âm thất bại. Bạn có thể phiên âm lại bằng biểu tượng thử lại.",
+ "notTranscribed": "Chưa phiên âm. Bạn có thể phiên âm bằng biểu tượng thử lại.",
+ "transcribeFile": "Chép lời tệp",
+ "mediaFiles": "Âm thanh và video",
+ "fileUnsupported": "Không thể đọc âm thanh từ {{name}}.",
+ "readingFile": "Đang đọc {{name}}...",
+ "transcribeFailed": "Chép lời thất bại. Vui lòng thử lại.",
+ "waiting": "Đang chờ chép lời",
+ "transcribingPercent": "Đang chép lời, {{percent}}%",
+ "showMore": "Xem thêm",
+ "showLess": "Thu gọn",
+ "dropTitle": "Thả để chép lời",
+ "dropDescription": "Nó sẽ xuất hiện trong Lịch sử."
},
"debug": {
"title": "Gỡ lỗi",
diff --git a/src/i18n/locales/zh-TW/translation.json b/src/i18n/locales/zh-TW/translation.json
index adc47cbe..7a537fcb 100644
--- a/src/i18n/locales/zh-TW/translation.json
+++ b/src/i18n/locales/zh-TW/translation.json
@@ -317,7 +317,8 @@
"modelError": "模型錯誤",
"modelUnloaded": "模型已卸載",
"noModelDownloadRequired": "無模型 - 需要下載",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "歷史紀錄中的轉錄完成後才能更換模型。"
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "長音訊分段",
- "description": "在轉錄前依停頓處將長錄音分段,通常可以提升轉錄效果。"
+ "description": "在轉錄前依停頓處將長錄音分段,通常可以提升轉錄效果。轉錄檔案與較長的重新轉錄一律會分段。"
},
"vadBackend": {
"title": "語音活動偵測後端",
@@ -680,9 +681,21 @@
"delete": "刪除條目",
"deleteError": "刪除條目失敗,請重試",
"retranscribe": "重新轉錄",
- "retranscribeError": "重新轉錄失敗,請重試。",
+ "cancelTranscription": "取消轉錄",
"transcribing": "轉錄中...",
- "transcriptionFailed": "轉錄失敗。您可以使用重試圖示重新轉錄。"
+ "transcriptionFailed": "轉錄失敗。您可以使用重試圖示重新轉錄。",
+ "notTranscribed": "尚未轉錄。您可以使用重試圖示進行轉錄。",
+ "transcribeFile": "轉錄檔案",
+ "mediaFiles": "音訊和影片",
+ "fileUnsupported": "無法讀取 {{name}} 中的音訊。",
+ "readingFile": "正在讀取 {{name}}...",
+ "transcribeFailed": "轉錄失敗,請重試。",
+ "waiting": "等待轉錄",
+ "transcribingPercent": "正在轉錄,{{percent}}%",
+ "showMore": "顯示更多",
+ "showLess": "收合",
+ "dropTitle": "拖放到此處進行轉錄",
+ "dropDescription": "它會出現在歷史記錄中。"
},
"debug": {
"title": "偵錯",
diff --git a/src/i18n/locales/zh/translation.json b/src/i18n/locales/zh/translation.json
index 8b036a16..9e685c88 100644
--- a/src/i18n/locales/zh/translation.json
+++ b/src/i18n/locales/zh/translation.json
@@ -317,7 +317,8 @@
"modelError": "模型错误",
"modelUnloaded": "模型已卸载",
"noModelDownloadRequired": "无模型 - 需要下载",
- "downloadSpeed": "{{speed}} MB/s"
+ "downloadSpeed": "{{speed}} MB/s",
+ "lockedWhileTranscribing": "历史记录中的转录完成后才能更换模型。"
},
"settings": {
"modelSettings": {
@@ -580,7 +581,7 @@
},
"longFormChunking": {
"title": "长音频分段",
- "description": "在转录前按停顿处将长录音分段,通常可以提升转录效果。"
+ "description": "在转录前按停顿处将长录音分段,通常可以提升转录效果。转录文件与较长的重新转录始终会分段。"
},
"vadBackend": {
"title": "语音活动检测后端",
@@ -680,9 +681,21 @@
"delete": "删除条目",
"deleteError": "删除条目失败,请重试。",
"retranscribe": "重新转录",
- "retranscribeError": "重新转录失败。请重试。",
+ "cancelTranscription": "取消转录",
"transcribing": "转录中...",
- "transcriptionFailed": "转录失败。您可以使用重试图标重新转录。"
+ "transcriptionFailed": "转录失败。您可以使用重试图标重新转录。",
+ "notTranscribed": "尚未转录。您可以使用重试图标进行转录。",
+ "transcribeFile": "转录文件",
+ "mediaFiles": "音频和视频",
+ "fileUnsupported": "无法读取 {{name}} 中的音频。",
+ "readingFile": "正在读取 {{name}}...",
+ "transcribeFailed": "转录失败,请重试。",
+ "waiting": "等待转录",
+ "transcribingPercent": "正在转录,{{percent}}%",
+ "showMore": "显示更多",
+ "showLess": "收起",
+ "dropTitle": "拖放到此处进行转录",
+ "dropDescription": "它会出现在历史记录中。"
},
"debug": {
"title": "调试",
diff --git a/src/main.tsx b/src/main.tsx
index 55c7d5a9..e0de72b2 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -24,7 +24,9 @@ import "./i18n";
// Initialize model store (loads models and sets up event listeners)
import { useModelStore } from "./stores/modelStore";
+import { useTranscriptionJobsStore } from "./stores/transcriptionJobsStore";
useModelStore.getState().initialize();
+useTranscriptionJobsStore.getState().initialize();
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
diff --git a/src/stores/transcriptionJobsStore.ts b/src/stores/transcriptionJobsStore.ts
new file mode 100644
index 00000000..9d59438b
--- /dev/null
+++ b/src/stores/transcriptionJobsStore.ts
@@ -0,0 +1,57 @@
+import { create } from "zustand";
+import { toast } from "sonner";
+import i18n from "@/i18n";
+import { events, type TranscriptionJobStatus } from "@/bindings";
+
+export type ActiveJobStatus = Extract<
+ TranscriptionJobStatus,
+ { state: "queued" } | { state: "running" }
+>;
+
+// Background transcriptions (files, and History entries transcribed again),
+// keyed by History entry id. Only unfinished jobs are kept.
+interface TranscriptionJobsStore {
+ jobs: Record<number, ActiveJobStatus>;
+ initialized: boolean;
+ initialize: () => Promise<void>;
+}
+
+export const useTranscriptionJobsStore = create<TranscriptionJobsStore>()(
+ (set, get) => ({
+ jobs: {},
+ initialized: false,
+
+ initialize: async () => {
+ if (get().initialized) return;
+ set({ initialized: true });
+
+ await events.transcriptionJob.listen(({ payload }) => {
+ const { entry_id: entryId, status } = payload;
+ set((state) => {
+ const jobs = { ...state.jobs };
+ if (status.state === "queued" || status.state === "running") {
+ jobs[entryId] = status;
+ } else {
+ delete jobs[entryId];
+ }
+ return { jobs };
+ });
+ if (status.state === "failed") {
+ console.error(`Transcription of entry ${entryId} failed:`, status);
+ toast.error(i18n.t("settings.history.transcribeFailed"));
+ }
+ });
+ },
+ }),
+);
+
+const hasJobs = (state: TranscriptionJobsStore) =>
+ Object.keys(state.jobs).length > 0;
+
+// While a background transcription runs, the model can't be switched,
+// unloaded or deleted, so one transcript is never written by two models.
+export const useModelsLocked = () => useTranscriptionJobsStore(hasJobs);
+
+// The same, read once outside React.
+export const areModelsLocked = () =>
+ hasJobs(useTranscriptionJobsStore.getState());