scriptx 0.4.7

ScriptX is a command line tool to extract scriptures out of the American Sign Language version of the New World Translation.
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/*!
ffprobe wrapper

This module is a wrapper for the [ffprobe](https://ffmpeg.org/ffprobe.html) tool.
It gathers relevant information needed for ScriptX function, for example, it is charged
with collecting and returning chapter information such as the *start* and *end* time
stamps of each verse that is later used by [ffmpeg](https://ffmpeg.org/) to cut out
specific verses from the video file.
*/

use crate::ffwrappers::errors::Errors;
use core::{f64, str};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::{path::Path, process::Command};

#[derive(PartialEq, Debug)]
enum VerseKind {
    SingleVerse,
    RangeVerse,
}

/**
The top most, or *root*, level of the struct

It contains a single struct of vector type which is a collection of all the chapters contained within the video file.
 */
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Root {
    /// The `chapters` fields contains a vector of the type `Chapter` struct.
    pub chapters: Vec<Chapter>,
}
/**
The struct for the chapter

Contains information for each chapter within a video file. Also contains the `Tags` struct. Specifically the
_start_time_ and _end_time_ are used from this struct.
*/
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Chapter {
    /// The `id` field that uniquely identifies each chapter.
    pub id: i64,
    /// The `time_base` field.
    #[serde(rename = "time_base")]
    pub time_base: String,
    /// The `start` field.
    pub start: i64,
    /**
    The `start_time` field.
    This field contains the start time for the chapter.
    */
    #[serde(rename = "start_time")]
    pub start_time: String,
    /// The `end` field.
    pub end: i64,
    #[serde(rename = "end_time")]
    /**
    The `end_time` field.
    This field contains the end time for the chapter.
    */
    pub end_time: String,
    ///The `Tags` field.
    pub tags: Tags,
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
/**
Contains the title field for each chapter.

The *title* field is used to determine the chapter that contains the verse(s) being searched for.

For example, if the verse *John 3:16* needs to be found, searching the title fields will result in
the correct chapter struct which also contains additional information needed to cut the verse.
*/
pub struct Tags {
    /**
    The title field for each chapter.

    The `verse` function searches this field when looking for
    the verse, for example `Ps. 83:13`, needed.
    */
    pub title: String,
}

impl Root {
    /**
    Returns the Root struct when given a path to a video file.

    The `new` function initializes a new chapter video to be worked with.
    The function parses the meta data of the video with [ffprobe](https://ffmpeg.org/ffprobe.html)
    and returns the `Root` struct which contains all the chapter information needed
    for cutting the scriptures.

    ## Example
    For example, if you want to load chapter 3 of the book of John
    to process it, you would do the following:

    ```rust, ignore
    use ff::probe;
    let chapter:Root = probe::new("nwt_43_Joh_ASL_03_r720P.mp4");
    ```
    */
    pub fn new(path: &Path) -> Result<Root, Errors> {
        let probe = Command::new("ffprobe")
            .arg("-v")
            .arg("quiet")
            .arg("-print_format")
            .arg("json")
            .arg("-show_chapters")
            .arg("-i")
            .arg(path)
            .output()
            .unwrap();

        if !probe.status.success() {
            eprint!(
                "The file, {}, was not found by ffprobe. Check path and try again. ",
                path.to_str().unwrap()
            );
            return Err(Errors::FileError);
        }

        let c: Root =
            serde_json::from_slice(&probe.stdout).expect("Error during JSON parsing of file.");
        Ok(c)
    }

    /**
    Returns the *start* and *end* time for the verse passed in.

    The `verse_times` method takes a verse and returns the *start* and *end* times
    for the verse passed in.

    ## Example

    ```rust,
    use ffwrappers::probe;
    # use ffwrappers::probe::{Root, Chapter, Tags};
    # let chapter: Root = Root {
    #     chapters: {
    #         vec![
    #             Chapter {
    #                id: 16,
    #                 time_base: String::from("1/1000"),
    #                 start: 197597,
    #                 start_time: String::from("197.597000"),
    #                 end: 226259,
    #                 end_time: String::from("226.259000"),
    #                 tags: Tags {
    #                     title: String::from("John 3:16"),
    #                 },
    #             },
    #             Chapter {
    #                 id: 17,
    #                 time_base: String::from("1/1000"),
    #                 start: 197597,
    #                 start_time: String::from("226.259000"),
    #                 end: 241908,
    #                 end_time: String::from("241.908000"),
    #                 tags: Tags {
    #                     title: String::from("John 3:17"),
    #                 },
    #             },
    #         ]
    #     }
    # };

    // let chapter:Root = probe::new("nwt_43_Joh_ASL_03_r720P.mp4");
    assert_eq!(chapter.verse("16"), (197.597, 226.259)); // Returned the `start_time` and `end_time`.
    ```

     */
    pub fn verse(&self, verse: &str) -> (f64, f64) {
        let kind: VerseKind = verse_kind(verse);
        match kind {
            VerseKind::SingleVerse => self.return_single_verse(verse),
            VerseKind::RangeVerse => self.return_range_verse(verse),
        }
    }

    /// Returns a tuple with the _start_ and _end_ time for a singe verse.
    fn return_single_verse(&self, verse: &str) -> (f64, f64) {
        self.get_times(self.find_verse_id(format!("{}{}", self.get_prefix(), verse).as_str()))
    }

    /// Returns a tuple with the _start_ and _end_ time for a range of verses.
    fn return_range_verse(&self, verse: &str) -> (f64, f64) {
        let range: (&str, &str) = range_split(verse);

        let start_time: f64 = self.return_single_verse(range.0).0;

        let end_time: f64 = self.return_single_verse(range.1).1;
        (start_time, end_time)
    }

    /// Searches for the title of the verse and returns the ``id`` of the chapter the title is found.
    fn find_verse_id(&self, verse: &str) -> i64 {
        for i in self.chapters.iter() {
            if i.tags.title == verse {
                return i.id;
            }
        }
        panic!("The verse was not found.");
    }

    /// Returns a tuple of the *start* and *end* time for the chapter in which the *id* has been provided for.
    fn get_times(&self, id: i64) -> (f64, f64) {
        for i in self.chapters.iter() {
            if i.id == id {
                return (i.start_time.parse().unwrap(), i.end_time.parse().unwrap());
            }
        }
        unreachable!()
    }

    /// Returns the last chapter in the file.
    fn get_last_chapter(&self) -> &Chapter {
        return self.chapters.last().unwrap();
    }

    /**
    Returns the prefix needed to complete the title being searched for.

    In order to avoid the user from having to type the complete title of the chapter being
    searched, this method finds the prefix of the chapter so the user doesn't have to add it
    when using the `-v` option.

    The method searches for all text up to and including the ':'. For example, the title
    _Joel 1:2_ would match and return the Joel 1:_ as a &str. The prefix is then combined
    with the verse the user wants.
    */
    fn get_prefix(&self) -> &str {
        // let last_chapter = *&self.chapters.last().unwrap();
        let title = self.get_last_chapter().tags.title.as_str();

        let pattern = Regex::new(r"(^[\s\S]*:)").unwrap(); // Regular expression to find the prefix (ig. 'Joel 1:') of a `title`. See https://regexr.com/5vus6
        let prefix = pattern.captures(title);

        match prefix {
            Some(prefix) => {
                return prefix.get(1).unwrap().as_str();
            }
            None => panic!("The prefix pattern was not found."),
        };
    }

    /// Returns all the verses' start and end times in a vector.
    pub fn get_all_verses(&self) -> Vec<(f64, f64)> {
        // let prefix: &str = self.get_prefix(); // Example of prefix: 'John 3:'.
        let last_verse: i32 = get_verse_from_title(self.get_last_chapter().tags.title.as_str());
        let mut all_verses: Vec<(f64, f64)> = Vec::new(); // tuple of all the start/end times for the entire chapter.

        for i in 1..last_verse {
            all_verses.push(self.verse(&i.to_string()));
        }

        all_verses
    }
}

/**
Returns the verse number from a full title.
## Example
```rust
let verse: i32 = get_verse_from_title("John 3:16")
assert_eq!(verse, 16i32));

```
*/
fn get_verse_from_title(title: &str) -> i32 {
    let v: Vec<&str> = title.split(':').collect();
    v[1].parse()
        .expect("Unable to parse verse number from &str to i32.")
}

/// Determines whether the verse is single or part of a range.
fn verse_kind(verse: &str) -> VerseKind {
    if verse.contains('-') {
        VerseKind::RangeVerse
    } else {
        VerseKind::SingleVerse
    }
}

/**
Splits the verse range into two parts and returns a tuple (starting_verse, ending_verse).

## Example
```rust
assert!(true);
```
*/
fn range_split(verse: &str) -> (&str, &str) {
    let s: Vec<&str> = verse.split('-').collect();
    (s[0], s[1])
}

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

    #[test]
    fn test_get_verse_from_title() {
        let title_0 = "Joel 5:1";
        assert_eq!(get_verse_from_title(title_0), 1);

        let title_0 = "John 3:16";
        assert_eq!(get_verse_from_title(title_0), 16);

        let title_0 = "Ps. 18:32";
        assert_eq!(get_verse_from_title(title_0), 32);
    }

    #[test]
    fn test_verse() {
        let root = init_struct_1();
        assert_eq!(root.verse("16"), (197.597, 226.259));
        assert_eq!(root.verse("17"), (226.259, 241.908));
        assert_eq!(root.verse("25"), (358.658, 374.741));
        assert_eq!(root.verse("26"), (374.741, 394.561));
    }

    #[test]
    #[should_panic]
    fn test_verse_not_found() {
        let root = init_struct_1();
        assert_eq!(root.verse("27"), (197.597, 226.259));
    }

    #[test]
    fn test_range_split_1() {
        assert_eq!(range_split("5-7"), ("5", "7"));
    }
    #[test]
    fn test_range_split_2() {
        assert_eq!(range_split("5-17"), ("5", "17"));
    }
    #[test]
    fn test_range_split_3() {
        assert_eq!(range_split("15-17"), ("15", "17"));
    }

    #[test]
    fn test_get_prefix() {
        let r: Root = init_struct_1();
        assert_eq!(r.get_prefix(), "John 3:");
    }
    #[test]
    fn test_find_verse_id() {
        let r: Root = init_struct_1();
        let id = r.find_verse_id("John 3:16");
        assert_eq!(id, 16);
    }
    #[test]
    fn test_find_times() {
        let r: Root = init_struct_1();
        assert_eq!(r.get_times(16), (197.597, 226.259));
    }
    #[test]
    fn test_return_range_verse() {
        let r: Root = init_struct_1();
        assert_eq!(r.return_range_verse("16-17"), (197.597, 241.908))
    }

    #[test]
    fn test_return_single_verse() {
        let r: Root = init_struct_1();
        assert_eq!(r.return_single_verse("16"), (197.597, 226.259))
    }

    #[test]
    fn test_verse_single() {
        let r: Root = init_struct_1();
        assert_eq!(r.verse("16"), (197.597, 226.259))
    }
    #[test]
    fn test_verse_range() {
        let r: Root = init_struct_1();
        assert_eq!(r.verse("16-17"), (197.597, 241.908))
    }

    #[test]
    fn test_verse_kind() {
        assert_eq!(verse_kind("1"), VerseKind::SingleVerse)
    }

    #[test]
    fn test_last_chapter() {
        let r: Root = init_struct_1();
        let chapter: &Chapter = r.get_last_chapter();
        assert_eq!(chapter.id, 26);
    }

    #[test]
    #[ignore = "Need to finish writing the test."]
    fn test_get_all_verses() {
        let f = init_struct_1();
        assert_eq!(f.get_all_verses(), vec![(197.597000, 4226.259000)]);
    }

    fn init_struct_1() -> Root {
        let root_struct: Root = Root {
            chapters: {
                vec![
                    Chapter {
                        id: 16,
                        time_base: String::from("1/1000"),
                        start: 197597,
                        start_time: String::from("197.597000"),
                        end: 226259,
                        end_time: String::from("226.259000"),
                        tags: Tags {
                            title: String::from("John 3:16"),
                        },
                    },
                    Chapter {
                        id: 17,
                        time_base: String::from("1/1000"),
                        start: 197597,
                        start_time: String::from("226.259000"),
                        end: 241908,
                        end_time: String::from("241.908000"),
                        tags: Tags {
                            title: String::from("John 3:17"),
                        },
                    },
                    Chapter {
                        id: 25,
                        time_base: String::from("1/1000"),
                        start: 358658,
                        start_time: String::from("358.658000"),
                        end: 374741,
                        end_time: String::from("374.741000"),
                        tags: Tags {
                            title: String::from("John 3:25"),
                        },
                    },
                    Chapter {
                        id: 26,
                        time_base: String::from("1/1000"),
                        start: 374741,
                        start_time: String::from("374.741000"),
                        end: 394561,
                        end_time: String::from("394.561000"),
                        tags: Tags {
                            title: String::from("John 3:26"),
                        },
                    },
                ]
            },
        };

        root_struct
    }
}
// #[test]
// fn test_last_id() {
//     let r: Root = init_struct_1();
//     let id: i64 = r.last_id();
//     assert_eq!(id, 26);
// }

// #[test]
// #[ignore = "Not sure how to test this method yet."]
// fn test_last_chapter() {
//     let r: Root = init_struct_1();
//     let last_chapter: &Chapter = r.last_chapter();
// }

/*
Structure of the structs used in ff::probe

struct Root {
chapters: Vec<Chapter>,
}
struct Chapter {
id: i64,
time_base: String,
start: i64,
start_time: String,
end: i64,
end_time: String,
tags: Tags,
}
pub struct Tags {
title: String, // The verse(s) being search for is compared to this field.
}
*/