6个版本
0.3.3 | 2024年6月6日 |
---|---|
0.3.2 | 2023年12月1日 |
0.2.0 | 2023年11月23日 |
0.1.0 | 2023年10月11日 |
#41 in WebSocket
每月 25 次下载
1.5MB
2.5K SLoC
Speechmatics Rust SDK
重要:这是一个正在进行中的工作,API可能会发生重大变化,并且许多错误处理目前尚缺。我们希望最终将此代码转换为生产状态,但现阶段它应该可以作为Rust实现的指南。我们欢迎贡献,所以请随时联系我们!
此crate使用tokio-tungstenite进行实时通信和reqwest,并且可以很好地与您的异步Rust堆栈集成,允许您异步运行转录任务以及其他任务。
入门
首先,设置您希望使用的功能标志。这些选项是
- 实时 - 启用实时功能,导致tokio和tokio-tungstenite作为依赖项安装
- 批处理 - 启用批处理功能,导致reqwest和rand作为依赖项安装
为了连接到API,您还需要一个API密钥。您可以从我们的门户获取密钥。您需要创建一个免费账户来访问门户(无需信用卡)。
实时转录
为了实时转录,您需要安装tokio和speechmatics crate。然后您可以在main.rs文件中运行以下代码。不要忘记更新API密钥和文件路径。以下示例创建了一个模拟存储,以展示如何将RealtimeSession的输出传递到某些外部状态,例如数据库或对外部系统的API请求。
use speechmatics::realtime::*;
use std::{path::PathBuf, sync::{Arc, Mutex}};
use tokio::{self, fs::File, try_join};
struct MockStore {
transcript: String
}
impl MockStore {
pub fn new() -> Self {
Self {
transcript: "".to_owned()
}
}
pub fn append(&mut self, transcript: String) {
self.transcript = format!("{} {}", self.transcript, transcript);
}
pub fn print(&self) {
print!("{}", self.transcript)
}
}
#[tokio::main]
async fn main() {
let api_key: String = std::env::var("API_KEY").unwrap();
let (mut rt_session, mut receive_channel) = RealtimeSession::new(api_key, None).unwrap();
let test_file_path = PathBuf::new()
.join(".")
.join("tests")
.join("data")
.join("example.wav");
let file = File::open(test_file_path).await.unwrap();
let mut config: SessionConfig = Default::default();
let audio_config = models::AudioFormat::new(models::audio_format::Type::File);
config.audio_format = Some(audio_config);
let mock_store = Arc::new(Mutex::new(MockStore::new()));
let mock_store_clone = mock_store.clone();
let message_task = tokio::spawn(async move {
while let Some(message) = receive_channel.recv().await {
match message {
ReadMessage::AddTranscript(mess) => {
mock_store_clone.lock().unwrap().append(mess.metadata.transcript);
},
ReadMessage::EndOfTranscript(_) => {
return
},
_ => {}
}
}
});
let run_task = { rt_session.run(config, file) };
try_join!(async move { message_task.await.map_err(anyhow::Error::from) }, run_task).unwrap();
mock_store.lock().unwrap().print(); // this should print the whole transcript, demonstrating it has successfully been stored
}
批量转录
为了批量转录,您需要安装您选择的异步运行时。在这里,我们使用tokio以保持一致性。然后可以将以下代码添加到main.rs文件中并运行。不要忘记更新API密钥和文件路径。
use speechmatics::batch::{
models::{self, JobConfig, TranscriptionConfig},
BatchClient,
};
use std::path::PathBuf;
use tokio;
#[tokio::main]
async fn main() {
// instantiate the client
let api_key: String = std::env::var("API_KEY").unwrap();
let batch_client = BatchClient::new(&api_key, None).unwrap();
// set up the path to the file and load in the config
let test_file_path = PathBuf::new()
.join("..")
.join("tests")
.join("data")
.join("example.wav");
let mut config = JobConfig::default();
let mut transcription_config = TranscriptionConfig::default();
transcription_config.language = "en".to_owned();
config.transcription_config = Some(Box::new(transcription_config));
// submit the job
let job_res = batch_client
.submit_job(config, test_file_path)
.await
.unwrap();
// wait for the job to return a completed status, or to enter an error status in which case panic
let mut success = false;
let mut retries = 0;
while !success {
let get_job_res = batch_client.get_job(&job_res.id).await.unwrap();
if get_job_res.job.status == models::job_details::Status::Done {
success = true
} else if get_job_res.job.status != models::job_details::Status::Running {
panic!("Job failed");
} else {
if retries > 6 {
panic!("Job took too long to complete");
}
retries += 1;
std::thread::sleep(std::time::Duration::from_millis(3000));
}
}
// get the json transcript of the job
let get_result_res = batch_client.get_json_result(&job_res.id).await.unwrap();
println!("{:?}", get_result_res);
}
示例
您可以在示例文件夹中找到更多代码示例。为了运行示例,您需要设置API_KEY环境变量。这应该是您的speechmatics API的API密钥。
获取帮助
如果您需要帮助,可以使用以下几种渠道
- 在我们的问题板上提出问题
- 在我们的讨论论坛上联系我们
- 在 Stack Overflow 上提问
贡献
如果您有兴趣进行贡献,请参阅 CONTRIBUTING
支持的 Rust 版本
该包是用 rust 版本 1.72.0 构建的。尽管它可能在较老的 rust 版本上也能正常工作,但我们不保证。
许可
本项目遵循 MIT 许可协议。
依赖项
~3–17MB
~275K SLoC