Skip to main content

narrative_graph/heuristic/
context.rs

1//! What extraction knows beyond the paragraph in front of it.
2//!
3//! A paragraph read alone knows little: a bare given name carries no title, and
4//! the one sentence that says "she" settles nothing about a name that three
5//! hundred other paragraphs settle at once. A [`Context`] carries that
6//! evidence from one call to the next, and names the first person for a
7//! narrator who is never called anything in the text.
8
9use super::pack::LanguagePack;
10use super::quotes::QuoteMap;
11use super::register::Register;
12use super::{entities, segment};
13
14/// Document-wide evidence about names, shared across extraction calls.
15///
16/// ```
17/// use narrative_graph::heuristic::{extract_aggregates_in, Context};
18/// use narrative_graph::Options;
19///
20/// let mut context = Context::default().with_narrator("wren");
21/// context.learn("Mrs. Chen waved. Then she fed the cat.");
22/// let found = extract_aggregates_in("I met my mother, Nora.", &Options::default(), &context)
23///     .unwrap();
24/// assert!(found.iter().any(|a| a.relation == "mother_of"));
25/// ```
26#[derive(Debug, Default, Clone)]
27pub struct Context {
28    register: Register,
29    narrator: Option<String>,
30}
31
32impl Context {
33    /// Resolve "I", "me" and "my" outside quoted speech to `canonical`, the
34    /// normalized name (lowercase, underscores) the narrator should carry in
35    /// the graph. Without one, the first person is never a mention.
36    pub fn with_narrator(mut self, canonical: &str) -> Self {
37        self.narrator = Some(canonical.to_string());
38        self
39    }
40
41    /// Record what `text` says about the names in it. Call it for every
42    /// paragraph before extracting from any of them, so that a name's evidence
43    /// is complete when its first mention is read.
44    pub fn learn(&mut self, text: &str) {
45        observe_text(&mut self.register, text, &super::pack::ENGLISH);
46    }
47
48    pub(super) fn register(&self) -> &Register {
49        &self.register
50    }
51
52    pub(super) fn narrator(&self) -> Option<&str> {
53        self.narrator.as_deref()
54    }
55}
56
57/// Feed one text's mentions and pronouns to a register, outside speech only:
58/// a vocative inside a quotation is not the subject of the pronoun after it.
59pub(super) fn observe_text(register: &mut Register, text: &str, pack: &LanguagePack) {
60    let mut open = false;
61    let mut previous_end = 0usize;
62    // As in the pipeline: hard-wrapped text marks a paragraph with a blank line.
63    let paragraph_break = if text.contains("\n\n") { 2 } else { 1 };
64    for (sent_text, sent_start) in segment::split_sentences(text, pack) {
65        if text[previous_end..sent_start].matches('\n').count() >= paragraph_break {
66            open = false;
67        }
68        previous_end = sent_start + sent_text.len();
69        let quotes = QuoteMap::scan(sent_text, open);
70        open = quotes.open_at_end;
71
72        let named = entities::mentions_for_register(sent_text, pack);
73        let mentions: Vec<_> = named.iter().filter(|m| !quotes.inside(m.start)).collect();
74        let pronouns: Vec<_> = entities::extract_pronouns(sent_text, pack)
75            .into_iter()
76            .filter(|p| !quotes.inside(p.start))
77            .map(|p| (p.text, p.start))
78            .collect();
79        register.observe(sent_text, &mentions, &pronouns, pack);
80    }
81}