Skip to main content

narrative_graph/
types.rs

1use std::collections::BTreeMap;
2
3/// A candidate relational fact extracted from text.
4/// Every candidate carries confidence, provenance span, and the rule that produced it.
5#[derive(Debug, Clone)]
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
8pub struct TripleCandidate {
9    /// The subject entity (normalized to lowercase with underscores for multi-word entities).
10    pub subject: String,
11    /// The relation type (normalized from verb phrases to a controlled vocabulary).
12    pub relation: String,
13    /// The object entity (normalized to lowercase with underscores for multi-word entities).
14    pub object: String,
15    /// Confidence score from 0.0 to 1.0, derived from rule strength and entity proximity.
16    pub confidence: f32,
17    /// Byte range [start, end) in the input text where this candidate was extracted.
18    pub span: [usize; 2],
19    /// The name of the extraction rule that produced this candidate.
20    /// Examples: "possessive-sister-pattern", "verb-mentor-pattern".
21    pub rule: String,
22}
23
24/// A candidate the caller has judged wrong, named by the triple it emitted.
25///
26/// IMPORTANT: the three fields are the *normalized* values as they appeared on
27/// the `TripleCandidate`, which for `relation` means after any `ontology`
28/// mapping. What the caller saw is what the caller rejects; nothing here is
29/// re-derived from the source text.
30///
31/// Keying on the triple rather than the span is deliberate. A span does not
32/// survive an edit to the manuscript, so a span-keyed rejection would come back
33/// on the next save; a triple survives every edit that does not restate the
34/// fact. The cost is that the rejection is document-wide: a caller who meant
35/// "not in this passage" suppresses the claim everywhere, which is the blunter
36/// and more inspectable of the two errors.
37#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
39#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
40pub struct Rejection {
41    pub subject: String,
42    pub relation: String,
43    pub object: String,
44}
45
46/// The language a text is written in, which selects the reader.
47///
48/// English is read by capitalization and word-bounded verb rules. Chinese has
49/// neither capitals nor spaces, so it has a reader of its own, which finds
50/// names from the caller's `aliases` and from a surname followed by a title
51/// (王夫人, 林姑娘). See `heuristic/chinese.rs` for what it reads.
52#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
53#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
54#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
55#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
56#[non_exhaustive]
57pub enum Language {
58    #[default]
59    English,
60    /// Traditional or simplified Chinese.
61    Chinese,
62}
63
64/// Configuration for entity and relation extraction.
65#[derive(Debug, Clone, Default)]
66#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
67#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
68pub struct Options {
69    /// Optional mapping from surface forms to canonical entity names.
70    /// Example: { "Marcus": "marcus_hale", "Mr Marcus Hale": "marcus_hale" }
71    /// All mentions matching a key in this map resolve to the value.
72    ///
73    /// IMPORTANT: the key's own shape selects how it matches. A key carrying an
74    /// uppercase character is matched against the mention's surface form
75    /// exactly, which is the capitalized run with `.` dropped as a separator:
76    /// "Mr Marcus Hale", never "Mr. Marcus Hale". A wholly lowercase key is a
77    /// lexicon entry instead: the phrase is searched for in the text as a
78    /// literal, word-bounded, case-insensitive match and becomes a mention of
79    /// the canonical name there, which is how "the detective" reaches a
80    /// referent no capitalized-run detector can see. A lexicon match that
81    /// overlaps a mention already detected is dropped, so a key can add a
82    /// mention but never replace one. A pronoun can take a lexicon mention as
83    /// its referent, and a pronoun the mention covers is replaced by it.
84    #[cfg_attr(feature = "serde", serde(default))]
85    pub aliases: BTreeMap<String, String>,
86
87    /// Minimum confidence threshold for returned candidates.
88    /// Candidates below this score are filtered out.
89    /// Default: 0.0 (all candidates returned).
90    #[cfg_attr(feature = "serde", serde(default))]
91    pub min_confidence: Option<f32>,
92
93    /// Candidates the caller has already judged wrong. A candidate whose
94    /// (subject, relation, object) matches one of these is not emitted.
95    ///
96    /// IMPORTANT: the crate persists nothing. This set is caller-owned state
97    /// handed in per call, so where it is stored between runs, and for how
98    /// long, stays the caller's decision.
99    ///
100    /// A rejection suppresses and does nothing else: it does not lower the
101    /// confidence of a sibling candidate, and it does not weaken the rule that
102    /// produced it. Feeding rejections back into scoring would make the output
103    /// depend on a history the caller cannot see in the result, and the span
104    /// and rule name are on every candidate precisely so a caller can audit
105    /// why it fired.
106    #[cfg_attr(feature = "serde", serde(default))]
107    pub rejections: Vec<Rejection>,
108
109    /// Optional mapping from recognized relation patterns to a caller-supplied controlled vocabulary.
110    /// Example: { "loves": "romantic_interest", "is_married_to": "spouse" }
111    /// If a relation type is not in this map, the heuristic default is used.
112    #[cfg_attr(feature = "serde", serde(default))]
113    pub ontology: BTreeMap<String, String>,
114
115    /// The language of the text. Default: English.
116    ///
117    /// IMPORTANT: for Chinese, every key of `aliases` is matched as a literal
118    /// run of characters with no word boundary, since the script has none.
119    #[cfg_attr(feature = "serde", serde(default))]
120    pub language: Language,
121}
122
123/// Whether a document states a fact or states that it does not hold.
124///
125/// IMPORTANT: a denial is a claim, not a missing assertion. Text that neither
126/// asserts nor denies — a conditional, a modal, a question, a complement held
127/// open by its main verb — produces no aggregate at all and so has no polarity.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
129#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
130#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
131#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
132pub enum Polarity {
133    Asserted,
134    Denied,
135}
136
137/// One fact as a whole document states it, with every piece of evidence for it.
138///
139/// `TripleCandidate` is per-sentence and `extract_candidate_triples` keeps the
140/// highest-confidence one per triple, discarding the spans of the rest. An
141/// aggregate keeps them: a passage stating one fact three ways yields one
142/// aggregate carrying three spans.
143#[derive(Debug, Clone)]
144#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
145#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
146pub struct AggregateTriple {
147    pub subject: String,
148    pub relation: String,
149    pub object: String,
150    /// Whether the document states this fact or denies it. A denial and the
151    /// assertion of the same triple are two aggregates, not one, because they
152    /// are two claims — and a document carrying both is the contradiction
153    /// `find_conflicts` reports.
154    pub polarity: Polarity,
155    /// The highest confidence of any supporting candidate.
156    ///
157    /// IMPORTANT: repetition does not raise it, and `spans.len()` is the only
158    /// thing that reports corroboration. In fiction a restatement is not
159    /// independent evidence — an unreliable narrator restates a falsehood as
160    /// readily as a reliable one states a fact — so summing would let a
161    /// thrice-repeated lie outrank a once-stated fact, and averaging would
162    /// punish a strong statement for being echoed by a weaker phrasing. The
163    /// score answers "how good is the best evidence", not "how much is there".
164    pub confidence: f32,
165    /// Every span the fact was found at, in document order. Never empty.
166    pub spans: Vec<[usize; 2]>,
167    /// The rules that produced those spans, first occurrence first, without
168    /// repeats. Two spans from one rule name it once.
169    pub rules: Vec<String>,
170}
171
172/// Why two aggregates cannot both be true.
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
175#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
176#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
177pub enum ConflictKind {
178    /// The document asserts a fact and denies the same fact.
179    Denial,
180    /// The relation admits one subject per object, and two subjects are
181    /// asserted over the same object.
182    Cardinality,
183}
184
185/// Two claims a single passage cannot both support, with the evidence for each.
186///
187/// IMPORTANT: a conflict is not a ranking. Neither side is the true one, and
188/// the crate has no way to decide which is: both carry their spans so the
189/// decision stays with whoever can read the manuscript.
190#[derive(Debug, Clone)]
191#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
192#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
193pub struct Conflict {
194    pub kind: ConflictKind,
195    /// The claim appearing first in the document.
196    pub left: AggregateTriple,
197    /// The claim appearing second.
198    pub right: AggregateTriple,
199}
200
201/// A reference span into the input text with its corresponding surface text.
202#[derive(Debug, Clone)]
203#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
204#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
205pub struct SpannedTriple {
206    pub candidate: TripleCandidate,
207    /// The actual text from input[span[0]..span[1]].
208    pub text: String,
209}
210
211/// Everything one pass over a passage yields: what `extract_candidate_triples`,
212/// `extract_aggregates` and `find_conflicts` return separately.
213#[derive(Debug, Clone)]
214#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
215#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
216pub struct Analysis {
217    pub candidates: Vec<TripleCandidate>,
218    pub aggregates: Vec<AggregateTriple>,
219    pub conflicts: Vec<Conflict>,
220}
221
222/// The document's agreeing gender cues for a named character, when available.
223#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
224#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
225#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
226#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
227pub enum Gender {
228    Feminine,
229    Masculine,
230}
231
232/// A family role held by this character with respect to another character.
233#[derive(Debug, Clone, PartialEq, Eq)]
234#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
235#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
236pub struct FamilyLink {
237    pub role: String,
238    pub relative: String,
239}
240
241/// Names, descriptions and family evidence used to resolve a character's mentions.
242#[derive(Debug, Clone, PartialEq, Eq)]
243#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
244#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
245pub struct CharacterProfile {
246    pub id: String,
247    pub aliases: Vec<String>,
248    pub gender: Option<Gender>,
249    pub family: Vec<FamilyLink>,
250}
251
252#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
253#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
254#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
255#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
256pub enum MentionKind {
257    Name,
258    Pronoun,
259    Description,
260}
261
262/// A source span linked to a character ID.
263#[derive(Debug, Clone, PartialEq, Eq)]
264#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
265#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
266pub struct CharacterMention {
267    pub id: String,
268    pub kind: MentionKind,
269    pub span: [usize; 2],
270}
271
272/// Relation analysis and character evidence for one document.
273#[derive(Debug, Clone)]
274#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
275#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
276pub struct DocumentAnalysis {
277    pub analysis: Analysis,
278    pub characters: Vec<CharacterProfile>,
279    pub mentions: Vec<CharacterMention>,
280    /// Individual relation observations, in source order, including restatements.
281    pub timeline: Vec<FactOccurrence>,
282    /// Event occurrences, in source order.
283    pub events: Vec<EventCandidate>,
284    /// Knowledge and communication statements with their source content.
285    pub knowledge: Vec<KnowledgeFact>,
286    pub dialogue: Dialogue,
287}
288
289/// One quoted utterance and any supported attribution.
290#[derive(Debug, Clone, PartialEq, Eq)]
291#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
292#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
293pub struct DialogueLine {
294    pub speaker: Option<String>,
295    pub listener: Option<String>,
296    /// Byte range covering the utterance in the input.
297    pub span: [usize; 2],
298    /// Quoted byte ranges, excluding any interleaved attribution.
299    pub spoken_spans: Vec<[usize; 2]>,
300}
301
302/// Dialogue lines in source order, including lines with incomplete attribution.
303#[derive(Debug, Clone, Default, PartialEq, Eq)]
304#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
305#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
306pub struct Dialogue {
307    pub lines: Vec<DialogueLine>,
308    /// Number of lines with an unknown speaker or listener.
309    pub unattributed: usize,
310}
311
312impl Dialogue {
313    pub(crate) fn from_lines(mut lines: Vec<DialogueLine>) -> Self {
314        lines.sort_by_key(|line| line.span);
315        let unattributed = lines
316            .iter()
317            .filter(|line| line.speaker.is_none() || line.listener.is_none())
318            .count();
319        Self {
320            lines,
321            unattributed,
322        }
323    }
324}
325
326/// A time-varying relationship described by a fact in the timeline.
327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
329#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
330#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
331pub enum RelationshipState {
332    Engaged,
333    Married,
334    Widowed,
335    Divorced,
336    Friends,
337    Enemies,
338    Allies,
339}
340
341impl RelationshipState {
342    pub(crate) fn from_relation(relation: &str) -> Option<Self> {
343        Some(match relation {
344            "engaged_to" | "fiance_of" => Self::Engaged,
345            "spouse_of" | "wife_of" | "husband_of" => Self::Married,
346            "widow_of" => Self::Widowed,
347            "divorced" | "ex_wife_of" | "ex_husband_of" => Self::Divorced,
348            "friend_of" => Self::Friends,
349            "enemy_of" => Self::Enemies,
350            "ally_of" => Self::Allies,
351            _ => return None,
352        })
353    }
354}
355
356/// One statement about a relationship at a particular position in the text.
357#[derive(Debug, Clone)]
358#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
359#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
360pub struct FactOccurrence {
361    pub candidate: TripleCandidate,
362    pub polarity: Polarity,
363    pub state: Option<RelationshipState>,
364    /// An explicit end to a state, such as "no longer friends".
365    pub ends_state: bool,
366    /// Observed correctness of comparable predictions in the public calibration set.
367    pub calibrated_confidence: Option<f32>,
368}
369
370impl DocumentAnalysis {
371    /// All state observations about this pair, in source order.
372    pub fn relationship_history<'a>(
373        &'a self,
374        person: &'a str,
375        other: &'a str,
376    ) -> impl Iterator<Item = &'a FactOccurrence> {
377        self.timeline.iter().filter(move |entry| {
378            let c = &entry.candidate;
379            entry.state.is_some()
380                && ((c.subject == person && c.object == other)
381                    || (c.subject == other && c.object == person))
382        })
383    }
384
385    /// Observations with a supported estimate at or above the requested probability.
386    pub fn facts_at_least(
387        &self,
388        probability: f32,
389    ) -> crate::Result<impl Iterator<Item = &FactOccurrence>> {
390        if !(0.0..=1.0).contains(&probability) {
391            return Err(crate::NarrativeGraphError::InvalidConfidenceThreshold(
392                probability,
393            ));
394        }
395        Ok(self.timeline.iter().filter(move |entry| {
396            entry
397                .calibrated_confidence
398                .is_some_and(|estimate| estimate >= probability)
399        }))
400    }
401}
402
403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
404#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
405#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
406#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
407pub enum EventKind {
408    Duel,
409    Proposal,
410    Journey,
411    Death,
412}
413
414/// One event stated in the text, with canonical participants and a byte span.
415#[derive(Debug, Clone, PartialEq, Eq)]
416#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
417#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
418pub struct EventCandidate {
419    pub kind: EventKind,
420    pub actor: String,
421    pub target: Option<String>,
422    pub location: Option<String>,
423    pub span: [usize; 2],
424    /// The words that name the event in the source text.
425    pub trigger: [usize; 2],
426}
427
428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
429#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
430#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
431#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
432pub enum KnowledgeKind {
433    Learned,
434    Known,
435    Told,
436}
437
438/// A statement made about what a character knows, learns or tells someone.
439#[derive(Debug, Clone, PartialEq, Eq)]
440#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
441#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
442pub struct KnowledgeFact {
443    pub kind: KnowledgeKind,
444    pub actor: String,
445    pub recipient: Option<String>,
446    pub topic: Option<String>,
447    pub span: [usize; 2],
448    /// The proposition or topic phrase in the original text.
449    pub content: [usize; 2],
450}