Skip to main content

narrative_graph/
series.rs

1use crate::heuristic::{analyze_document_in, Context};
2use crate::types::{
3    CharacterProfile, DocumentAnalysis, FactOccurrence, FamilyLink, Gender, Options, Polarity,
4};
5use crate::Result;
6use std::collections::{BTreeMap, BTreeSet};
7
8/// The order of a chapter in a series. Keep this key when editing the chapter.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
12pub struct ChapterPosition {
13    pub book: u32,
14    pub chapter: u32,
15}
16
17/// Evidence positions are relative to each chapter's own input text.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
21pub struct ChapterSpan {
22    pub position: ChapterPosition,
23    pub span: [usize; 2],
24}
25
26#[derive(Debug, Clone)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
28#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
29pub struct SeriesAggregate {
30    pub subject: String,
31    pub relation: String,
32    pub object: String,
33    pub polarity: Polarity,
34    pub confidence: f32,
35    pub spans: Vec<ChapterSpan>,
36    pub rules: Vec<String>,
37}
38
39type Fact = (String, String, String, Polarity);
40
41/// An incremental graph over independently extracted chapters. Set stable
42/// canonical IDs in [`Options::aliases`] for characters known by multiple names.
43#[derive(Debug, Default)]
44pub struct Series {
45    options: Options,
46    chapters: BTreeMap<ChapterPosition, (u64, DocumentAnalysis)>,
47    facts: BTreeMap<Fact, BTreeMap<ChapterPosition, usize>>,
48}
49
50impl Series {
51    pub fn new(options: Options) -> Self {
52        Self {
53            options,
54            ..Self::default()
55        }
56    }
57
58    /// Insert or replace a chapter. Pass the same revision for identical
59    /// inputs to reuse the cached analysis. Returns whether extraction ran.
60    pub fn update_chapter(
61        &mut self,
62        position: ChapterPosition,
63        revision: u64,
64        text: &str,
65    ) -> Result<bool> {
66        self.update_chapter_in(position, revision, text, &Context::default())
67    }
68
69    /// The revision identifies the chapter text and its supplied context.
70    pub fn update_chapter_in(
71        &mut self,
72        position: ChapterPosition,
73        revision: u64,
74        text: &str,
75        context: &Context,
76    ) -> Result<bool> {
77        if self.chapter_revision(position) == Some(revision) {
78            return Ok(false);
79        }
80        let next = analyze_document_in(text, &self.options, context)?;
81        self.remove_chapter(position);
82        for (index, fact) in next.analysis.aggregates.iter().enumerate() {
83            let key = (
84                fact.subject.clone(),
85                fact.relation.clone(),
86                fact.object.clone(),
87                fact.polarity,
88            );
89            self.facts.entry(key).or_default().insert(position, index);
90        }
91        self.chapters.insert(position, (revision, next));
92        Ok(true)
93    }
94
95    pub fn remove_chapter(&mut self, position: ChapterPosition) -> bool {
96        let Some((_, chapter)) = self.chapters.remove(&position) else {
97            return false;
98        };
99        for fact in chapter.analysis.aggregates {
100            let key = (fact.subject, fact.relation, fact.object, fact.polarity);
101            let references = self
102                .facts
103                .get_mut(&key)
104                .expect("chapter fact missing from series index");
105            references.remove(&position);
106            if references.is_empty() {
107                self.facts.remove(&key);
108            }
109        }
110        true
111    }
112
113    pub fn chapter(&self, position: ChapterPosition) -> Option<&DocumentAnalysis> {
114        self.chapters.get(&position).map(|(_, analysis)| analysis)
115    }
116
117    pub fn chapter_revision(&self, position: ChapterPosition) -> Option<u64> {
118        self.chapters.get(&position).map(|(revision, _)| *revision)
119    }
120
121    pub fn chapters(&self) -> impl Iterator<Item = (ChapterPosition, &DocumentAnalysis)> {
122        self.chapters
123            .iter()
124            .map(|(&position, (_, analysis))| (position, analysis))
125    }
126
127    pub fn relationship_history<'a>(
128        &'a self,
129        person: &'a str,
130        other: &'a str,
131    ) -> impl Iterator<Item = (ChapterPosition, &'a FactOccurrence)> {
132        self.chapters().flat_map(move |(position, chapter)| {
133            chapter
134                .relationship_history(person, other)
135                .map(move |fact| (position, fact))
136        })
137    }
138
139    /// Facts across all books, ordered by the position of their first evidence.
140    pub fn aggregates(&self) -> Vec<SeriesAggregate> {
141        let mut result = Vec::with_capacity(self.facts.len());
142        for ((subject, relation, object, polarity), chapters) in &self.facts {
143            let mut aggregate = SeriesAggregate {
144                subject: subject.clone(),
145                relation: relation.clone(),
146                object: object.clone(),
147                polarity: *polarity,
148                confidence: 0.0,
149                spans: Vec::new(),
150                rules: Vec::new(),
151            };
152            for (&position, &index) in chapters {
153                let evidence = &self.chapters[&position].1.analysis.aggregates[index];
154                aggregate.confidence = aggregate.confidence.max(evidence.confidence);
155                aggregate.spans.extend(
156                    evidence
157                        .spans
158                        .iter()
159                        .map(|&span| ChapterSpan { position, span }),
160                );
161                for rule in &evidence.rules {
162                    if !aggregate.rules.contains(rule) {
163                        aggregate.rules.push(rule.clone());
164                    }
165                }
166            }
167            result.push(aggregate);
168        }
169        result.sort_by_key(|a| a.spans[0]);
170        result
171    }
172
173    pub fn characters(&self) -> Vec<CharacterProfile> {
174        #[derive(Default)]
175        struct Evidence<'a> {
176            aliases: BTreeSet<&'a str>,
177            genders: BTreeSet<Gender>,
178            family: BTreeSet<(&'a str, &'a str)>,
179        }
180        let mut seen: BTreeMap<&str, Evidence<'_>> = BTreeMap::new();
181        for (_, chapter) in self.chapters() {
182            for character in &chapter.characters {
183                let evidence = seen.entry(&character.id).or_default();
184                evidence
185                    .aliases
186                    .extend(character.aliases.iter().map(String::as_str));
187                evidence.genders.extend(character.gender);
188                evidence.family.extend(
189                    character
190                        .family
191                        .iter()
192                        .map(|link| (link.role.as_str(), link.relative.as_str())),
193                );
194            }
195        }
196        seen.into_iter()
197            .map(|(id, evidence)| CharacterProfile {
198                id: id.to_string(),
199                aliases: evidence.aliases.into_iter().map(str::to_string).collect(),
200                gender: (evidence.genders.len() == 1).then(|| *evidence.genders.first().unwrap()),
201                family: evidence
202                    .family
203                    .into_iter()
204                    .map(|(role, relative)| FamilyLink {
205                        role: role.to_string(),
206                        relative: relative.to_string(),
207                    })
208                    .collect(),
209            })
210            .collect()
211    }
212}