Repository navigation
Expand file tree
/
Copy pathquery.rs
More file actions
2406 lines (2287 loc) · 80.3 KB
/
Copy pathquery.rs
File metadata and controls
2406 lines (2287 loc) · 80.3 KB
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Read-only queries over recorded meetings, for agents (`hex mcp`).
//!
//! Nothing here writes to the meetings folder. A meeting whose recorder holds
//! `active.lock` is in progress: its rolling transcript is read and
//! labeled. Otherwise only the published `transcript.ndjson` is
//! trusted, and an unfinished draft is shown as interrupted, as the app does.
//! Unreadable folders and lines are skipped and reported, never repaired.
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
use color_eyre::eyre::{Result, eyre};
use serde::de::DeserializeOwned;
use unicode_normalization::UnicodeNormalization;
use unicode_normalization::char::is_combining_mark;
use super::transcript::{RollingLine, RollingView};
use super::{
Chapter, MeetingManifest, MeetingSource, MeetingStatus, TranscriptEntry, chapter_entries,
coalesce_transcript, display_title, format_duration, notes_markdown, recovered_status,
section_markdown, transcript_markdown,
};
use crate::dictation::vocabulary::VocabularyEntry;
const TURN_GAP_MS: u64 = 3_000;
const PASSAGE_WORDS: usize = 60;
const SNIPPET_TOKENS: usize = 36;
const CONTEXT_CHARS: usize = 120;
const BM25_K1: f32 = 1.2;
const BM25_B: f32 = 0.75;
/// Where a meeting's transcript came from.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TranscriptSource {
/// The published final transcript.
Final,
/// The rolling in-call transcript (in progress or interrupted).
Rolling,
Missing,
}
impl TranscriptSource {
pub fn label(self) -> &'static str {
match self {
Self::Final => "final transcript",
Self::Rolling => "rolling transcript",
Self::Missing => "no transcript",
}
}
}
/// One meeting folder as read at the moment of the query.
pub struct Meeting {
pub id: String,
pub manifest: MeetingManifest,
/// The status after applying the app's recovery rules, without writing.
pub status: MeetingStatus,
/// Whether a recorder process holds the meeting's lock right now.
pub in_progress: bool,
pub source: TranscriptSource,
pub entries: Vec<TranscriptEntry>,
pub warnings: Vec<String>,
passages: Vec<Passage>,
}
impl Meeting {
pub fn title(&self) -> String {
display_title(&self.manifest)
}
pub fn start_ms(&self) -> u64 {
self.manifest.created_at_ms
}
pub fn duration_ms(&self, now_ms: u64) -> u64 {
if self.in_progress {
return now_ms.saturating_sub(self.manifest.created_at_ms);
}
self.manifest.duration_ms.unwrap_or_else(|| {
self.entries
.iter()
.map(|entry| entry.end_ms)
.max()
.unwrap_or_default()
})
}
/// Entries overlapping `range`, or an error when it starts after the meeting.
pub fn entries_in(&self, range: OffsetRange, now_ms: u64) -> Result<Vec<&TranscriptEntry>> {
range.check(self, now_ms)?;
Ok(self
.entries
.iter()
.filter(|entry| range.overlaps(entry))
.collect())
}
/// Chapter `number` (counting from 1), where it ends, and its entries.
pub fn chapter(&self, number: usize, now_ms: u64) -> Result<ChapterView<'_>> {
let chapters = &self.manifest.chapters;
if chapters.is_empty() {
return Err(eyre!("Meeting {} has no chapters.", self.id));
}
let index = number
.checked_sub(1)
.filter(|index| *index < chapters.len())
.ok_or_else(|| {
eyre!(
"Meeting {} has chapters 1 to {}; there is no chapter {number}.",
self.id,
chapters.len()
)
})?;
Ok(ChapterView {
number,
chapter: &chapters[index],
end_ms: chapters
.get(index + 1)
.map_or_else(|| self.duration_ms(now_ms), |next| next.start_ms)
.max(chapters[index].start_ms),
entries: chapter_entries(&self.entries, chapters, index),
})
}
/// Every chapter, in order.
pub fn chapter_views(&self, now_ms: u64) -> Vec<ChapterView<'_>> {
(1..=self.manifest.chapters.len())
.filter_map(|number| self.chapter(number, now_ms).ok())
.collect()
}
fn status_label(&self) -> String {
let status = status_name(self.status);
if self.in_progress {
format!("{status} (in progress)")
} else {
status.into()
}
}
fn participants(&self) -> String {
match self.manifest.app.as_deref() {
Some(app) => format!("You, Them ({app})"),
None => "You, Them".into(),
}
}
fn heading(&self) -> String {
format!(
"{} \"{}\" · {}",
self.id,
self.title(),
iso_local(self.start_ms())
)
}
}
/// One chapter of a meeting with the entries that start inside it.
pub struct ChapterView<'a> {
/// Counting from 1.
pub number: usize,
pub chapter: &'a Chapter,
pub end_ms: u64,
pub entries: Vec<TranscriptEntry>,
}
impl ChapterView<'_> {
fn span(&self) -> String {
format!(
"{}–{}",
format_duration(self.chapter.start_ms),
format_duration(self.end_ms)
)
}
/// `## title`, its one line, and its turns, for copying one section.
pub fn markdown(&self) -> String {
section_markdown(self.chapter, &self.entries)
}
}
fn status_name(status: MeetingStatus) -> &'static str {
match status {
MeetingStatus::Starting => "starting",
MeetingStatus::Recording => "recording",
MeetingStatus::Transcribing => "transcribing",
MeetingStatus::Complete => "complete",
MeetingStatus::Interrupted => "interrupted",
MeetingStatus::Failed => "failed",
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PassageKind {
Speech(MeetingSource),
Notes,
}
struct Passage {
kind: PassageKind,
start_ms: u64,
text: String,
tokens: Vec<Token>,
frequencies: HashMap<String, u32>,
}
struct Token {
stem: String,
start: usize,
end: usize,
}
impl Passage {
fn new(kind: PassageKind, start_ms: u64, text: String) -> Self {
let tokens = tokenize(&text);
let mut frequencies = HashMap::new();
for token in &tokens {
*frequencies.entry(token.stem.clone()).or_insert(0) += 1;
}
Self {
kind,
start_ms,
text,
tokens,
frequencies,
}
}
fn speaker(&self) -> &'static str {
match self.kind {
PassageKind::Speech(source) => source.label(),
PassageKind::Notes => "Notes",
}
}
}
#[derive(Clone, PartialEq)]
struct Fingerprint {
files: Vec<Option<(u64, Option<SystemTime>)>>,
in_progress: bool,
}
const FINGERPRINT_FILES: [&str; 5] = [
"manifest.json",
super::transcript::ERROR_FILE,
"transcript.ndjson",
"transcript.md",
super::transcript::ROLLING_FILE,
];
/// The meetings folder plus an in-memory cache keyed by file sizes and times.
pub struct Library {
root: PathBuf,
cache: Mutex<HashMap<String, (Fingerprint, Arc<Meeting>)>>,
}
/// A folder that could not be read as a meeting.
pub struct Skipped {
pub id: String,
pub reason: String,
}
pub struct Scan {
pub meetings: Vec<Arc<Meeting>>,
pub skipped: Vec<Skipped>,
}
impl Library {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self {
root: root.into(),
cache: Mutex::default(),
}
}
pub fn root(&self) -> &Path {
&self.root
}
/// Every readable meeting, newest first.
pub fn scan(&self) -> Result<Scan> {
let mut meetings = Vec::new();
let mut skipped = Vec::new();
let entries = match fs::read_dir(&self.root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(Scan { meetings, skipped });
}
Err(error) => {
return Err(eyre!(
"could not read the meetings folder {}: {error}",
self.root.display()
));
}
};
let mut cache = self.cache.lock().unwrap_or_else(|error| error.into_inner());
let mut seen = HashSet::new();
for entry in entries.flatten() {
let directory = entry.path();
let Some(id) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
if id.starts_with('.') || !directory.is_dir() {
continue;
}
seen.insert(id.clone());
let fingerprint = fingerprint(&directory);
if let Some((cached, meeting)) = cache.get(&id)
&& *cached == fingerprint
{
meetings.push(meeting.clone());
continue;
}
match load(&directory, &id, fingerprint.in_progress) {
Ok(meeting) => {
let meeting = Arc::new(meeting);
cache.insert(id, (fingerprint, meeting.clone()));
meetings.push(meeting);
}
Err(error) => {
cache.remove(&id);
skipped.push(Skipped {
id,
reason: error.to_string(),
});
}
}
}
cache.retain(|id, _| seen.contains(id));
// A meeting past its retention is gone even before expiry moves it.
let retention = crate::app_settings::meeting_retention();
let now_ms = crate::desktop::events::now_ms();
meetings.retain(|meeting| {
!super::expired(&meeting.manifest, meeting.status, retention, now_ms)
});
meetings.sort_by_key(|meeting| std::cmp::Reverse(meeting.start_ms()));
skipped.sort_by(|left, right| left.id.cmp(&right.id));
Ok(Scan { meetings, skipped })
}
/// A meeting by exact id, or by a unique prefix of at least six characters.
pub fn meeting(&self, id: &str) -> Result<Arc<Meeting>> {
let id = id.trim();
let meetings = self.scan()?.meetings;
if let Some(meeting) = meetings.iter().find(|meeting| meeting.id == id) {
return Ok(meeting.clone());
}
let matches = meetings
.iter()
.filter(|meeting| id.len() >= 6 && meeting.id.starts_with(id))
.collect::<Vec<_>>();
match matches.as_slice() {
[meeting] => Ok((*meeting).clone()),
[] => Err(eyre!(
"No meeting with id {id:?}. Use list_meetings to find meeting ids."
)),
_ => Err(eyre!(
"The id prefix {id:?} matches {} meetings; use the full id.",
matches.len()
)),
}
}
pub fn list(&self, query: &ListQuery, now_ms: u64) -> Result<String> {
let scan = self.list_matches(query, now_ms)?;
let matching = &scan.meetings;
let limit = query.limit.clamp(1, 200);
let mut output = String::new();
if matching.is_empty() {
let _ = writeln!(output, "No meetings match.");
} else {
let _ = writeln!(
output,
"{} of {} meetings, newest first:",
matching.len().min(limit),
matching.len()
);
}
for meeting in matching.iter().take(limit) {
let turns = coalesce_transcript(meeting.entries.iter().cloned()).len();
let _ = writeln!(
output,
"- {} · \"{}\" · {} · {} · {} · {} ({turns} turns) · participants: {} · notes: {}",
meeting.id,
meeting.title(),
iso_local(meeting.start_ms()),
format_duration(meeting.duration_ms(now_ms)),
meeting.status_label(),
meeting.source.label(),
meeting.participants(),
if meeting.manifest.notes.is_some() {
"yes"
} else {
"no"
}
);
for warning in &meeting.warnings {
let _ = writeln!(output, " warning: {warning}");
}
}
write_skipped(&mut output, &scan.skipped);
Ok(output)
}
/// Shared selection for CLI JSON and MCP text; limit is applied by the renderer.
pub fn list_matches(&self, query: &ListQuery, now_ms: u64) -> Result<Scan> {
let mut scan = self.scan()?;
let range = TimeRange::parse(query.since.as_deref(), query.until.as_deref(), now_ms)?;
let words = query
.query
.as_deref()
.map(|query| query.split_whitespace().map(fold).collect::<Vec<_>>())
.unwrap_or_default();
scan.meetings = scan
.meetings
.into_iter()
.filter(|meeting| query.include_in_progress || !meeting.in_progress)
.filter(|meeting| range.overlaps(meeting, now_ms))
.filter(|meeting| {
if words.is_empty() {
return true;
}
let haystack = fold(&format!(
"{} {} {} {}",
meeting.title(),
meeting.manifest.title,
meeting.manifest.app.as_deref().unwrap_or_default(),
meeting.id
));
words.iter().all(|word| haystack.contains(word.as_str()))
})
.collect::<Vec<_>>();
Ok(scan)
}
pub fn search(&self, query: &SearchQuery, now_ms: u64) -> Result<String> {
let parsed = ParsedQuery::parse(&query.query);
if parsed.is_empty() {
return Err(eyre!("The search query has no words."));
}
let scan = self.scan()?;
let range = TimeRange::parse(query.since.as_deref(), query.until.as_deref(), now_ms)?;
let scope = match &query.meeting_id {
Some(id) => vec![self.meeting(id)?],
None => scan
.meetings
.iter()
.filter(|meeting| query.include_in_progress || !meeting.in_progress)
.filter(|meeting| range.overlaps(meeting, now_ms))
.cloned()
.collect(),
};
let hits = rank(&scope, &parsed, query.fuzzy, &query.vocabulary);
Ok(render_search(query, &parsed, &scope, &hits, &scan.skipped))
}
pub fn transcript(&self, query: &TranscriptQuery, now_ms: u64) -> Result<String> {
let meeting = self.meeting(&query.meeting_id)?;
let range = OffsetRange::parse(query.start.as_deref(), query.end.as_deref())?;
range.check(&meeting, now_ms)?;
let speaker = query.speaker.as_deref().map(parse_speaker).transpose()?;
let cursor = query.cursor.as_deref().map(Cursor::parse).transpose()?;
Ok(render_transcript(
&meeting,
TranscriptWindow {
range,
speaker: speaker.flatten(),
cursor,
max_chars: query.max_chars.clamp(500, 200_000),
},
now_ms,
))
}
pub fn notes(&self, id: &str) -> Result<String> {
let meeting = self.meeting(id)?;
let mut output = String::new();
let _ = writeln!(output, "{}", meeting.heading());
let Some(notes) = &meeting.manifest.notes else {
if meeting.in_progress {
let _ = writeln!(
output,
"No notes yet: the meeting is still {}. Hex writes a title and summary after it is transcribed.",
status_name(meeting.status)
);
} else {
let _ = writeln!(
output,
"No Apple Intelligence notes are stored for this meeting."
);
if let Some(error) = &meeting.manifest.notes_error {
let _ = writeln!(output, "Last notes attempt failed: {error}");
}
let _ = writeln!(
output,
"This read-only server never generates notes. Use get_transcript to read the meeting."
);
}
return Ok(output);
};
let _ = writeln!(
output,
"Apple Intelligence title and summary, generated {}{}",
iso_local(notes.generated_at_ms),
if notes.excerpted() {
" from an excerpt of the transcript"
} else {
""
}
);
if !notes.title.trim().is_empty() {
let _ = writeln!(output, "Title: {}", notes.title.trim());
}
let summary = notes.summary.trim();
let _ = writeln!(
output,
"Summary: {}",
if summary.is_empty() {
"(none)"
} else {
summary
}
);
let _ = writeln!(
output,
"\nThis is only a short model-written overview and may be wrong. Read the transcript \
with get_transcript or search_transcripts for details, decisions, and action items."
);
Ok(output)
}
/// The meeting as Markdown: metadata, stored notes, and labeled turns,
/// limited to the entries overlapping `range`.
pub fn markdown(&self, id: &str, range: OffsetRange, now_ms: u64) -> Result<String> {
let meeting = self.meeting(id)?;
let entries = meeting
.entries_in(range, now_ms)?
.into_iter()
.cloned()
.collect::<Vec<_>>();
let mut output = markdown_header(&meeting, now_ms);
if range.is_bounded() {
let _ = writeln!(output, "- Range: {}", range.describe());
}
if let Some(notes) = &meeting.manifest.notes {
let _ = write!(output, "\n{}\n", notes_markdown(notes));
}
let chapters = meeting.chapter_views(now_ms);
if !chapters.is_empty() {
output.push_str("\n## Chapters\n\n");
for view in &chapters {
let _ = write!(
output,
"{}. {} · {}",
view.number,
format_duration(view.chapter.start_ms),
view.chapter.title
);
if !view.chapter.summary.is_empty() {
let _ = write!(output, " — {}", view.chapter.summary);
}
output.push('\n');
}
}
let transcript = if entries.is_empty() && range.is_bounded() {
"No transcript entries in this range.".into()
} else {
transcript_markdown(&entries)
};
let _ = write!(output, "\n## Transcript\n\n{transcript}\n");
Ok(output)
}
/// One chapter as Markdown: the meeting's metadata, then the chapter's
/// name, line, and turns.
pub fn chapter_markdown(&self, id: &str, number: usize, now_ms: u64) -> Result<String> {
let meeting = self.meeting(id)?;
let view = meeting.chapter(number, now_ms)?;
let mut output = markdown_header(&meeting, now_ms);
let _ = writeln!(
output,
"- Chapter: {} of {} · {}",
view.number,
meeting.manifest.chapters.len(),
view.span()
);
let _ = write!(output, "\n{}\n", view.markdown());
Ok(output)
}
/// A meeting's chapters with their spans and lines.
pub fn chapters(&self, id: &str, now_ms: u64) -> Result<String> {
let meeting = self.meeting(id)?;
let mut output = String::new();
let _ = writeln!(output, "{}", meeting.heading());
let chapters = meeting.chapter_views(now_ms);
if chapters.is_empty() {
let _ = writeln!(
output,
"{}",
if meeting.in_progress {
"No chapters yet. Chapters appear every few minutes while a meeting records \
with live chapters on."
} else {
"No chapters are stored for this meeting. This read-only reader never \
generates them; read the meeting with get_transcript or `hex meetings show`."
}
);
return Ok(output);
}
let _ = writeln!(
output,
"{} chapters, {}:",
chapters.len(),
if meeting.manifest.chapters_refined {
"boundaries corrected over the whole transcript"
} else if meeting.in_progress {
"named live while recording"
} else {
"named live while recording; boundaries not corrected"
}
);
for view in &chapters {
let _ = writeln!(
output,
"{}. {} · {}",
view.number,
view.span(),
view.chapter.title
);
if !view.chapter.summary.is_empty() {
let _ = writeln!(output, " {}", view.chapter.summary);
}
}
let _ = writeln!(
output,
"\nModel-written names that may be wrong. Read a chapter with get_transcript (start \
and end as shown) or `hex meetings show {} --chapter N`.",
meeting.id
);
Ok(output)
}
}
fn markdown_header(meeting: &Meeting, now_ms: u64) -> String {
let mut output = format!("# {}\n\n", meeting.title());
let _ = writeln!(output, "- Meeting: {}", meeting.id);
let _ = writeln!(output, "- Started: {}", iso_local(meeting.start_ms()));
let _ = writeln!(
output,
"- Duration: {}",
format_duration(meeting.duration_ms(now_ms))
);
if let Some(app) = &meeting.manifest.app {
let _ = writeln!(output, "- App: {app}");
}
let _ = writeln!(
output,
"- Status: {} · {}",
meeting.status_label(),
meeting.source.label()
);
output
}
fn write_skipped(output: &mut String, skipped: &[Skipped]) {
if skipped.is_empty() {
return;
}
let _ = writeln!(output, "Skipped {} unreadable folders:", skipped.len());
for folder in skipped {
let _ = writeln!(output, "- {}: {}", folder.id, folder.reason);
}
}
fn fingerprint(directory: &Path) -> Fingerprint {
Fingerprint {
files: FINGERPRINT_FILES
.iter()
.map(|name| {
fs::metadata(directory.join(name))
.ok()
.map(|metadata| (metadata.len(), metadata.modified().ok()))
})
.collect(),
in_progress: recorder_holds_lock(directory),
}
}
/// Whether a recorder holds `active.lock`. Opens it read-only and tries a
/// shared lock, so a stale lock file left by a finished recording reads as
/// not in progress and nothing is created or written.
fn recorder_holds_lock(directory: &Path) -> bool {
let Ok(file) = File::open(directory.join("active.lock")) else {
return false;
};
match fs2::FileExt::try_lock_shared(&file) {
Ok(()) => {
let _ = fs2::FileExt::unlock(&file);
false
}
Err(error) => super::lock_contended(&error),
}
}
fn load(directory: &Path, id: &str, in_progress: bool) -> Result<Meeting> {
let manifest_path = directory.join("manifest.json");
let data = fs::read(&manifest_path).map_err(|error| match error.kind() {
std::io::ErrorKind::NotFound => eyre!("no manifest.json"),
_ => eyre!("could not read manifest.json: {error}"),
})?;
let mut manifest: MeetingManifest = serde_json::from_slice(&data)
.map_err(|error| eyre!("could not decode manifest.json: {error}"))?;
manifest.live_transcription_error =
fs::read_to_string(directory.join(super::transcript::ERROR_FILE))
.ok()
.map(|error| error.trim().to_string());
let final_path = directory.join("transcript.ndjson");
// A recorder publishes the final NDJSON before the Markdown; without one,
// the NDJSON alone is the finished publication.
let final_ready = if in_progress {
final_path.exists() && directory.join("transcript.md").exists()
} else {
final_path.exists()
};
let status = if in_progress {
manifest.status
} else {
recovered_status(manifest.status, false, final_ready)
};
let mut warnings = Vec::new();
let (source, mut entries) = if final_ready {
(
TranscriptSource::Final,
read_lines::<TranscriptEntry>(&final_path, &mut warnings),
)
} else {
let rolling: RollingView = read_lines::<RollingLine>(
&directory.join(super::transcript::ROLLING_FILE),
&mut warnings,
)
.into_iter()
.collect();
let source = if rolling.entries.is_empty() {
TranscriptSource::Missing
} else {
TranscriptSource::Rolling
};
(source, rolling.entries)
};
entries.retain(|entry| !entry.text.trim().is_empty());
entries.sort_by_key(|entry| entry.start_ms);
let passages = passages(&manifest, &entries);
Ok(Meeting {
id: id.into(),
manifest,
status,
in_progress,
source,
entries,
warnings,
passages,
})
}
/// Complete NDJSON lines; an unterminated last line is a write in progress
/// and is ignored, while other unreadable lines are skipped and counted.
fn read_lines<T: DeserializeOwned>(path: &Path, warnings: &mut Vec<String>) -> Vec<T> {
let contents = match fs::read(path) {
Ok(contents) => contents,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Vec::new(),
Err(error) => {
warnings.push(format!("could not read {}: {error}", file_name(path)));
return Vec::new();
}
};
let complete = contents
.iter()
.rposition(|byte| *byte == b'\n')
.map_or(&[][..], |newline| &contents[..newline]);
let mut skipped = 0;
let values = complete
.split(|byte| *byte == b'\n')
.filter(|line| !line.iter().all(u8::is_ascii_whitespace))
.filter_map(|line| match serde_json::from_slice(line) {
Ok(value) => Some(value),
Err(_) => {
skipped += 1;
None
}
})
.collect();
if skipped > 0 {
warnings.push(format!(
"skipped {skipped} unreadable lines in {}",
file_name(path)
));
}
values
}
fn file_name(path: &Path) -> String {
path.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default()
}
fn passages(manifest: &MeetingManifest, entries: &[TranscriptEntry]) -> Vec<Passage> {
let mut groups: Vec<(MeetingSource, u64, u64, usize, String)> = Vec::new();
for entry in entries {
let text = entry.text.trim();
let words = text.split_whitespace().count();
if let Some((source, _, end, count, joined)) = groups.last_mut()
&& *source == entry.source
&& entry.start_ms.saturating_sub(*end) <= TURN_GAP_MS
&& *count + words <= PASSAGE_WORDS
{
joined.push(' ');
joined.push_str(text);
*end = (*end).max(entry.end_ms);
*count += words;
} else {
groups.push((
entry.source,
entry.start_ms,
entry.end_ms,
words,
text.into(),
));
}
}
let mut passages = groups
.into_iter()
.map(|(source, start, _, _, text)| Passage::new(PassageKind::Speech(source), start, text))
.collect::<Vec<_>>();
if let Some(notes) = &manifest.notes {
let text = format!("{}. {}", notes.title.trim(), notes.summary.trim());
passages.push(Passage::new(PassageKind::Notes, 0, text));
}
passages
}
// MARK: Text
/// Lowercase without diacritics: `Café` -> `cafe`.
pub fn fold(text: &str) -> String {
let mut folded = String::with_capacity(text.len());
for character in text.chars() {
for lower in character.to_lowercase() {
folded.extend(
lower
.nfkd()
.filter(|character| !is_combining_mark(*character)),
);
}
}
folded
}
fn tokenize(text: &str) -> Vec<Token> {
let mut tokens = Vec::new();
let mut start = None;
let mut word = String::new();
let mut finish = |start: &mut Option<usize>, word: &mut String, end: usize| {
if let Some(begin) = start.take() {
let folded = fold(word);
if !folded.is_empty() {
tokens.push(Token {
stem: stem(&folded),
start: begin,
end,
});
}
word.clear();
}
};
let mut last_end = 0;
for (index, character) in text.char_indices() {
if character.is_alphanumeric() {
start.get_or_insert(index);
word.push(character);
last_end = index + character.len_utf8();
} else if matches!(character, '\'' | '’') && start.is_some() {
// `don't` and `Dax's` stay one word.
} else {
finish(&mut start, &mut word, last_end);
}
}
finish(&mut start, &mut word, last_end);
tokens
}
/// A light English stemmer: `scheduled`, `schedules`, and `scheduling` all
/// become `schedul`; `recurring` and `recur` become `recur`.
fn stem(word: &str) -> String {
let mut stem = word.to_string();
if stem.chars().count() <= 3 || stem.bytes().any(|byte| byte.is_ascii_digit()) {
return stem;
}
for (suffix, minimum, replacement) in [
("ingly", 3, ""),
("edly", 3, ""),
("ings", 3, ""),
("ing", 3, ""),
("ied", 2, "y"),
("ies", 2, "y"),
("ed", 3, ""),
("es", 3, ""),
("ly", 3, ""),
("s", 3, ""),
] {
if stem.ends_with(suffix)
&& stem.len() - suffix.len() >= minimum
&& !(suffix == "s" && (stem.ends_with("ss") || stem.ends_with("us")))
{
stem.truncate(stem.len() - suffix.len());
stem.push_str(replacement);
break;
}
}
let bytes = stem.as_bytes();
if bytes.len() >= 4 {
let (last, previous) = (bytes[bytes.len() - 1], bytes[bytes.len() - 2]);
if last == previous && last.is_ascii_lowercase() && !b"aeioulsz".contains(&last) {
stem.pop();
}
}
if stem.len() >= 4 && stem.ends_with('e') {
stem.pop();
}
stem
}
const STOPWORDS: &[&str] = &[
"a", "about", "an", "and", "are", "as", "at", "be", "but", "by", "did", "do", "for", "from",
"had", "has", "have", "he", "i", "in", "is", "it", "its", "of", "on", "or", "our", "she", "so",
"that", "the", "their", "them", "there", "they", "this", "to", "was", "we", "were", "what",
"when", "where", "which", "who", "with", "you",
];
fn soundex(word: &str) -> Option<String> {
let mut key = sound_key(word)?;
key.truncate(4);
while key.len() < 4 {
key.push('0');
}
Some(key)
}
/// Soundex without its four-character cap or padding: the first letter, then
/// every consonant sound (`cappuccino` and `capuchin` are both `c125`).
fn sound_key(word: &str) -> Option<String> {
let mut characters = word.chars().filter(char::is_ascii_alphabetic);
let first = characters.next()?;
let code = |character: char| match character {
'b' | 'f' | 'p' | 'v' => Some('1'),
'c' | 'g' | 'j' | 'k' | 'q' | 's' | 'x' | 'z' => Some('2'),
'd' | 't' => Some('3'),
'l' => Some('4'),
'm' | 'n' => Some('5'),
'r' => Some('6'),
_ => None,
};
let mut key = String::from(first);
let mut previous = code(first);
for character in characters {
let current = code(character);
if let Some(digit) = current
&& current != previous
{
key.push(digit);
}
if !matches!(character, 'h' | 'w') {
previous = current;
}
}
Some(key)
}
/// Optimal string alignment distance, or `None` when above `limit`.
fn edit_distance(left: &str, right: &str, limit: usize) -> Option<usize> {
let left = left.chars().collect::<Vec<_>>();
let right = right.chars().collect::<Vec<_>>();
if left.len().abs_diff(right.len()) > limit {
return None;
}
let width = right.len() + 1;
let mut rows = vec![vec![0; width]; left.len() + 1];
for (index, row) in rows.iter_mut().enumerate() {
row[0] = index;
}
for (index, cell) in rows[0].iter_mut().enumerate() {
*cell = index;
}
for i in 1..=left.len() {
for j in 1..=right.len() {