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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#![allow(clippy::field_reassign_with_default)]
use std::env;
use std::error;
use std::fmt;
use std::sync::Arc;
use bytes::Bytes;
use chrono::offset::Utc;
use chrono::DateTime;
use reqwest::multipart::Form;
use reqwest::{header, Client, Method, Request, StatusCode, Url};
use serde::{Deserialize, Serialize};
const ENDPOINT: &str = "https://api.rev.ai/speechtotext/v1/";
pub struct RevAI {
key: String,
client: Arc<Client>,
}
impl RevAI {
pub fn new<K>(key: K) -> Self
where
K: ToString,
{
let client = Client::builder().build();
match client {
Ok(c) => Self {
key: key.to_string(),
client: Arc::new(c),
},
Err(e) => panic!("creating client failed: {:?}", e),
}
}
pub fn new_from_env() -> Self {
let key = env::var("REVAI_API_KEY").unwrap();
RevAI::new(key)
}
fn request(&self, method: Method, path: &str, form: Option<Form>, query: Option<Vec<(&str, String)>>) -> Request {
let base = Url::parse(ENDPOINT).unwrap();
let url = base.join(path).unwrap();
let mut headers = header::HeaderMap::new();
if method != Method::POST {
headers.append(header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"));
}
if path.ends_with("/transcript") {
headers.append(header::ACCEPT, header::HeaderValue::from_static("text/plain"));
} else {
headers.append(header::ACCEPT, header::HeaderValue::from_static("application/json"));
}
let mut rb = self.client.request(method, url).headers(headers).bearer_auth(&self.key);
match query {
None => (),
Some(val) => {
rb = rb.query(&val);
}
}
if let Some(f) = form {
rb = rb.multipart(f);
}
rb.build().unwrap()
}
pub async fn create_job(&self, bytes: Bytes) -> Result<Job, APIError> {
let form = Form::new()
.part("media", reqwest::multipart::Part::bytes(bytes.to_vec()).mime_str("video/mp4").unwrap().file_name("testing.mp4"))
.text("options", "{}");
let request = self.request(Method::POST, "jobs", Some(form), None);
let resp = self.client.execute(request).await.unwrap();
match resp.status() {
StatusCode::OK => (),
s => {
return Err(APIError {
status_code: s,
body: resp.text().await.unwrap(),
})
}
};
Ok(resp.json().await.unwrap())
}
pub async fn get_transcript(&self, id: &str) -> Result<String, APIError> {
let request = self.request(Method::GET, &format!("jobs/{}/transcript", id), None, None);
let resp = self.client.execute(request).await.unwrap();
match resp.status() {
StatusCode::OK => (),
s => {
return Err(APIError {
status_code: s,
body: resp.text().await.unwrap(),
})
}
};
Ok(resp.text().await.unwrap())
}
}
pub struct APIError {
pub status_code: StatusCode,
pub body: String,
}
impl fmt::Display for APIError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "APIError: status code -> {}, body -> {}", self.status_code.to_string(), self.body)
}
}
impl fmt::Debug for APIError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "APIError: status code -> {}, body -> {}", self.status_code.to_string(), self.body)
}
}
impl error::Error for APIError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
None
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Job {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub id: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub status: String,
pub created_on: DateTime<Utc>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub type_: String,
#[serde(default)]
pub delete_after_seconds: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobOptions {
pub skip_diarization: bool,
pub skip_punctuation: bool,
pub remove_disfluencies: bool,
pub filter_profanity: bool,
pub speaker_channels_count: i64,
pub metadata: String,
pub callback_url: String,
pub custom_vocabulary_id: String,
pub language: String,
pub delete_after_seconds: i64,
}