-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbasic.rs
More file actions
163 lines (140 loc) · 5.23 KB
/
Copy pathbasic.rs
File metadata and controls
163 lines (140 loc) · 5.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
use std::path::{Path, PathBuf};
use whisper_cpp_plus::{FullParams, SamplingStrategy, WhisperContext};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Find model using flexible path resolution
let model_path = find_model("ggml-tiny.en.bin").ok_or(
"Model file not found. Please download a model or set WHISPER_MODEL_PATH.\n\
You can download the tiny.en model from:\n\
https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-tiny.en.bin",
)?;
println!("Loading Whisper model from {:?}...", model_path);
let ctx = WhisperContext::new(&model_path)?;
println!("Model loaded successfully!");
println!("Model info:");
println!(" - Vocabulary size: {}", ctx.n_vocab());
println!(" - Audio context: {}", ctx.n_audio_ctx());
println!(" - Text context: {}", ctx.n_text_ctx());
println!(" - Multilingual: {}", ctx.is_multilingual());
// Load real audio for testing
println!("\nLoading test audio...");
let audio = find_and_load_audio()?;
// Transcribe with default parameters
println!("Transcribing with default parameters...");
let text = ctx.transcribe(&audio)?;
println!("Transcription result: '{}'", text);
// Transcribe with custom parameters
println!("\nTranscribing with custom parameters...");
let params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 })
.language("en")
.translate(false)
.no_timestamps(false)
.temperature(0.0)
.n_threads(2);
let result = ctx.transcribe_with_full_params(&audio, params)?;
println!("Full transcription result:");
println!(" Text: '{}'", result.text);
println!(" Segments: {}", result.segments.len());
for (i, segment) in result.segments.iter().enumerate() {
println!(
" Segment {}: [{:.2}s - {:.2}s] '{}'",
i + 1,
segment.start_seconds(),
segment.end_seconds(),
segment.text
);
}
println!("\nSuccess! The whisper.cpp Rust wrapper is working correctly.");
Ok(())
}
/// Find model file in common locations
fn find_model(name: &str) -> Option<PathBuf> {
// Check env vars first (WHISPER_TEST_MODEL_DIR or WHISPER_MODEL_PATH)
for env_var in ["WHISPER_TEST_MODEL_DIR", "WHISPER_MODEL_PATH"] {
if let Ok(dir) = std::env::var(env_var) {
let path = Path::new(&dir).join(name);
if path.exists() {
return Some(path);
}
// Also try if env var points directly to a model file
let path = PathBuf::from(&dir);
if path.exists() && path.is_file() {
return Some(path);
}
}
}
// Common locations to check
let search_paths = [
// Crate-relative (running from whisper-cpp-plus/)
format!("tests/models/{}", name),
// Workspace-relative (running from root)
format!("whisper-cpp-plus/tests/models/{}", name),
// whisper.cpp submodule (crate-relative)
format!("../whisper-cpp-plus-sys/whisper.cpp/models/{}", name),
// whisper.cpp submodule (workspace-relative)
format!("whisper-cpp-plus-sys/whisper.cpp/models/{}", name),
// Current directory
name.to_string(),
];
for path_str in &search_paths {
let path = PathBuf::from(path_str);
if path.exists() {
return Some(path);
}
}
None
}
/// Find and load audio file
fn find_and_load_audio() -> Result<Vec<f32>, Box<dyn std::error::Error>> {
// Check env var first
if let Ok(dir) = std::env::var("WHISPER_TEST_AUDIO_DIR") {
let path = Path::new(&dir).join("jfk.wav");
if path.exists() {
println!("Loading audio from: {}", path.display());
return load_wav_file(path.to_str().unwrap());
}
}
let audio_paths = [
// Crate test audio
"tests/audio/jfk.wav",
"whisper-cpp-plus/tests/audio/jfk.wav",
// whisper.cpp submodule samples (crate-relative)
"../whisper-cpp-plus-sys/whisper.cpp/samples/jfk.wav",
// whisper.cpp submodule samples (workspace-relative)
"whisper-cpp-plus-sys/whisper.cpp/samples/jfk.wav",
// User samples
"samples/test.wav",
];
for path in &audio_paths {
if Path::new(path).exists() {
println!("Loading audio from: {}", path);
return load_wav_file(path);
}
}
Err(
"No audio files found. Set WHISPER_TEST_AUDIO_DIR or provide audio at tests/audio/jfk.wav"
.into(),
)
}
fn load_wav_file(path: &str) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
let mut reader = hound::WavReader::open(path)?;
let spec = reader.spec();
// Check format
if spec.sample_rate != 16000 {
eprintln!(
"Warning: Audio sample rate is {}Hz, expected 16000Hz",
spec.sample_rate
);
}
if spec.channels != 1 {
eprintln!(
"Warning: Audio has {} channels, using first channel only",
spec.channels
);
}
let samples: Vec<f32> = reader
.samples::<i16>()
.step_by(spec.channels as usize)
.map(|s| s.unwrap() as f32 / 32768.0)
.collect();
Ok(samples)
}