lab-rs 0.1.1

Toolkit and library for reading, writing, and manipulating HTK .lab label files
Documentation
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! a single label (one line of a `.lab` file)

use std::fmt;
use std::str::FromStr;

use crate::error::{ParseError, ParseErrorKind};

/// number of HTK time units (100ns) in one second
pub const UNITS_PER_SECOND: u64 = 10_000_000;

/// a single labelled segment, times are in 100ns units as stored in the
/// file, use the `*_secs` methods to work in seconds
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Label {
    /// start time in 100ns units
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub start: Option<u64>,
    /// end time in 100ns units
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub end: Option<u64>,
    /// the label text, e.g. a phone or word
    pub text: String,
    /// optional score following the label text
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub score: Option<f64>,
}

impl Label {
    /// creates a label spanning `start..end` in 100ns units
    pub fn new(start: u64, end: u64, text: impl Into<String>) -> Self {
        Label {
            start: Some(start),
            end: Some(end),
            text: text.into(),
            score: None,
        }
    }

    /// creates a label spanning `start..end` given in seconds
    pub fn from_secs(start: f64, end: f64, text: impl Into<String>) -> Self {
        Label::new(secs_to_units(start), secs_to_units(end), text)
    }

    /// start time in seconds
    pub fn start_secs(&self) -> Option<f64> {
        self.start.map(units_to_secs)
    }

    /// end time in seconds
    pub fn end_secs(&self) -> Option<f64> {
        self.end.map(units_to_secs)
    }

    /// duration in 100ns units, if both times are present
    pub fn duration(&self) -> Option<u64> {
        match (self.start, self.end) {
            (Some(s), Some(e)) => Some(e.saturating_sub(s)),
            _ => None,
        }
    }

    /// duration in seconds, if both times are present
    pub fn duration_secs(&self) -> Option<f64> {
        self.duration().map(units_to_secs)
    }

    /// returns `true` if `time` (in 100ns units) falls within `start..end`
    pub fn contains(&self, time: u64) -> bool {
        matches!((self.start, self.end), (Some(s), Some(e)) if s <= time && time < e)
    }

    // parses one line, line_no is 1-indexed for error messages
    pub(crate) fn parse_line(line: &str, line_no: usize) -> Result<Self, ParseError> {
        let tokens = tokenize(line, line_no)?;
        if tokens.is_empty() {
            return Err(invalid_label(line_no, "label line is empty"));
        }

        let mut idx = 0;
        let mut start = None;
        let mut end = None;
        if tokens.len() >= 3 && tokens[0].quoted && tokens[0].value.is_empty() && !tokens[1].quoted
        {
            if let Some(t) = parse_time(&tokens[1].value, line_no)? {
                end = Some(t);
                idx = 2;
            }
        }
        // leading integer tokens are times, but a line must keep at least
        // one token for the label text itself
        while idx < tokens.len() - 1 && idx < 2 && !tokens[idx].quoted {
            match parse_time(&tokens[idx].value, line_no)? {
                Some(t) if idx == 0 => start = Some(t),
                Some(t) => end = Some(t),
                None => break,
            }
            idx += 1;
        }

        if let (Some(s), Some(e)) = (start, end) {
            if s > e {
                return Err(ParseError {
                    line: line_no,
                    kind: ParseErrorKind::StartAfterEnd { start: s, end: e },
                });
            }
        }

        let rest = &tokens[idx..];
        let (text_tokens, score) = match rest.split_last() {
            // a trailing numeric token after the label name is a score
            Some((last, init)) if !init.is_empty() && !last.quoted => {
                match last.value.parse::<f64>() {
                    Ok(score) if score.is_finite() => (init, Some(score)),
                    Err(_) => (rest, None),
                    _ => (rest, None),
                }
            }
            _ => (rest, None),
        };

        Ok(Label {
            start,
            end,
            text: text_tokens
                .iter()
                .map(|token| token.value.as_str())
                .collect::<Vec<_>>()
                .join(" "),
            score,
        })
    }
}

impl fmt::Display for Label {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(s) = self.start {
            write!(f, "{s} ")?;
        } else if let Some(e) = self.end {
            write!(f, "\"\" {e} ")?;
        }
        if self.start.is_some() {
            if let Some(e) = self.end {
                write!(f, "{e} ")?;
            }
        }
        write_text(f, &self.text)?;
        if let Some(score) = self.score {
            write!(f, " {score}")?;
        }
        Ok(())
    }
}

impl FromStr for Label {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let line = s.trim_end_matches(['\r', '\n']);
        if line.contains('\r') || line.contains('\n') {
            return Err(invalid_label(1, "a label must contain exactly one line"));
        }
        Label::parse_line(line, 1)
    }
}

/// converts a time in 100ns units to seconds
pub fn units_to_secs(units: u64) -> f64 {
    units as f64 / UNITS_PER_SECOND as f64
}

/// converts a time in seconds to 100ns units, rounding to nearest
pub fn secs_to_units(secs: f64) -> u64 {
    (secs * UNITS_PER_SECOND as f64).round().max(0.0) as u64
}

// Ok(None) means the token is label text, not a time, digit-only tokens
// that overflow u64 are an error rather than silently becoming text
fn parse_time(token: &str, line_no: usize) -> Result<Option<u64>, ParseError> {
    match token.parse::<u64>() {
        Ok(t) => Ok(Some(t)),
        Err(_) if token.bytes().all(|b| b.is_ascii_digit()) => Err(ParseError {
            line: line_no,
            kind: ParseErrorKind::InvalidTime(token.to_string()),
        }),
        Err(_) => Ok(None),
    }
}

#[derive(Debug)]
struct Token {
    value: String,
    quoted: bool,
}

fn tokenize(line: &str, line_no: usize) -> Result<Vec<Token>, ParseError> {
    let mut tokens = Vec::new();
    let mut chars = line.chars().peekable();

    while chars.peek().is_some() {
        while chars.peek().is_some_and(|c| c.is_whitespace()) {
            chars.next();
        }
        if chars.peek().is_none() {
            break;
        }

        let mut value = String::new();
        let mut quoted = false;
        while let Some(&c) = chars.peek() {
            if c.is_whitespace() {
                break;
            }
            chars.next();
            if c != '"' {
                value.push(c);
                continue;
            }

            quoted = true;
            let mut closed = false;
            while let Some(c) = chars.next() {
                match c {
                    '"' => {
                        closed = true;
                        break;
                    }
                    '\\' => match chars.next() {
                        Some('n') => value.push('\n'),
                        Some('r') => value.push('\r'),
                        Some('t') => value.push('\t'),
                        Some('\\') => value.push('\\'),
                        Some('"') => value.push('"'),
                        Some(other) => {
                            return Err(invalid_label(
                                line_no,
                                format!("unsupported escape sequence `\\{other}`"),
                            ));
                        }
                        None => return Err(invalid_label(line_no, "unterminated escape sequence")),
                    },
                    other => value.push(other),
                }
            }
            if !closed {
                return Err(invalid_label(line_no, "unterminated quoted label text"));
            }
        }
        tokens.push(Token { value, quoted });
    }

    Ok(tokens)
}

fn invalid_label(line: usize, message: impl Into<String>) -> ParseError {
    ParseError {
        line,
        kind: ParseErrorKind::InvalidLabel(message.into()),
    }
}

fn write_text(f: &mut fmt::Formatter<'_>, text: &str) -> fmt::Result {
    let needs_quotes = text.is_empty()
        || text
            .chars()
            .any(|c| c.is_whitespace() || c == '"' || c == '\\')
        || text.parse::<u64>().is_ok()
        || text.parse::<f64>().is_ok();
    if !needs_quotes {
        return f.write_str(text);
    }

    f.write_str("\"")?;
    for c in text.chars() {
        match c {
            '\n' => f.write_str("\\n")?,
            '\r' => f.write_str("\\r")?,
            '\t' => f.write_str("\\t")?,
            '\\' => f.write_str("\\\\")?,
            '"' => f.write_str("\\\"")?,
            other => write!(f, "{other}")?,
        }
    }
    f.write_str("\"")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_full_line() {
        let l: Label = "0 23823130 pau".parse().unwrap();
        assert_eq!(l, Label::new(0, 23823130, "pau"));
    }

    #[test]
    fn parses_score() {
        let l: Label = "0 100 a -42.5".parse().unwrap();
        assert_eq!(l.score, Some(-42.5));
        assert_eq!(l.text, "a");
    }

    #[test]
    fn parses_label_only() {
        let l: Label = "sil".parse().unwrap();
        assert_eq!((l.start, l.end), (None, None));
        assert_eq!(l.text, "sil");
    }

    #[test]
    fn parses_single_time() {
        let l: Label = "100 sil".parse().unwrap();
        assert_eq!((l.start, l.end), (Some(100), None));
    }

    #[test]
    fn numeric_only_line_is_a_label() {
        // the last token is always the label text, even if numeric
        let l: Label = "100 200".parse().unwrap();
        assert_eq!((l.start, l.end), (Some(100), None));
        assert_eq!(l.text, "200");
    }

    #[test]
    fn rejects_start_after_end() {
        let err = "200 100 a".parse::<Label>().unwrap_err();
        assert_eq!(
            err.kind,
            ParseErrorKind::StartAfterEnd {
                start: 200,
                end: 100
            }
        );
    }

    #[test]
    fn rejects_overflowing_time() {
        let err = "99999999999999999999999 100 a"
            .parse::<Label>()
            .unwrap_err();
        assert!(matches!(err.kind, ParseErrorKind::InvalidTime(_)));
    }

    #[test]
    fn display_round_trips() {
        for line in ["0 23823130 pau", "100 sil", "sil", "0 100 a -42.5"] {
            let l: Label = line.parse().unwrap();
            assert_eq!(l.to_string(), line);
        }
    }

    #[test]
    fn display_round_trips_ambiguous_text_and_end_only_labels() {
        let labels = [
            Label::new(0, 100, "word 123"),
            Label {
                start: None,
                end: Some(100),
                text: "word".into(),
                score: None,
            },
            Label {
                start: None,
                end: None,
                text: "a\nquoted \"label\"".into(),
                score: None,
            },
        ];

        for label in labels {
            assert_eq!(label.to_string().parse::<Label>().unwrap(), label);
        }
    }

    #[test]
    fn rejects_empty_and_multiline_single_labels() {
        let empty = "  ".parse::<Label>().unwrap_err();
        assert!(matches!(empty.kind, ParseErrorKind::InvalidLabel(_)));

        let multiline = "0 10 a\n10 20 b".parse::<Label>().unwrap_err();
        assert!(matches!(multiline.kind, ParseErrorKind::InvalidLabel(_)));
    }

    #[test]
    fn seconds_conversion() {
        let l = Label::from_secs(1.0, 2.5, "a");
        assert_eq!(l.start, Some(10_000_000));
        assert_eq!(l.end, Some(25_000_000));
        assert_eq!(l.duration_secs(), Some(1.5));
        assert!(l.contains(15_000_000));
        assert!(!l.contains(25_000_000));
    }
}