This repository has been archived by the owner on Mar 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
worker.rs
81 lines (74 loc) · 2.27 KB
/
worker.rs
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
use async_channel::{Receiver, Sender};
use speech_center_client::{RecognitionClient, Result, SpeechCenterError, Topic};
pub enum Payload {
File {
source: String,
dest: String,
topic: Topic,
language: String,
},
Close(Sender<()>),
}
pub struct Worker {
client: RecognitionClient,
rx: Receiver<Payload>,
}
impl Worker {
pub async fn new(url: &str, token: &str, rx: Receiver<Payload>) -> Result<Self> {
let client = RecognitionClient::new(url, token).await?;
Ok(Self { client, rx })
}
pub async fn start(mut self) {
while let Ok(p) = self.rx.recv().await {
match p {
Payload::File {
source,
dest,
topic,
language,
} => {
debug!("Processing file {}", source);
if let Err(e) = self.process(&source, &dest, topic, language).await {
eprintln!(
"Error processing file [source={}] [dest={}]: {:?}",
source, dest, e
);
}
}
Payload::Close(s) => {
info!("Shutting worker down");
let _ = s.send(()).await;
break;
}
}
}
}
async fn process(
&mut self,
source: &str,
dest: &str,
topic: Topic,
language: String,
) -> Result<()> {
debug!("Reading file contents: {}", source);
let audio = tokio::fs::read(source).await.map_err(|e| {
SpeechCenterError::Unknown(format!(
"Error reading source file [source={}]: {}",
source, e
))
})?;
debug!("Performing recognision");
let res = self
.client
.recognise_with_topic(&language, topic, audio)
.await?;
debug!("Writing transcription: {}", dest);
tokio::fs::write(dest, res.as_bytes()).await.map_err(|e| {
SpeechCenterError::Unknown(format!(
"Error writing transcription [dest={}]: {}",
dest, e
))
})?;
Ok(())
}
}