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/// Configuration for entity and relation extraction.
47#[derive(Debug, Clone, Default)]
48#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
49#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
50pub struct Options {
51 /// Optional mapping from surface forms to canonical entity names.
52 /// Example: { "Marcus": "marcus_hale", "Mr Marcus Hale": "marcus_hale" }
53 /// All mentions matching a key in this map resolve to the value.
54 ///
55 /// IMPORTANT: the key's own shape selects how it matches. A key carrying an
56 /// uppercase character is matched against the mention's surface form
57 /// exactly, which is the capitalized run with `.` dropped as a separator:
58 /// "Mr Marcus Hale", never "Mr. Marcus Hale". A wholly lowercase key is a
59 /// lexicon entry instead: the phrase is searched for in the text as a
60 /// literal, word-bounded, case-insensitive match and becomes a mention of
61 /// the canonical name there, which is how "the detective" reaches a
62 /// referent no capitalized-run detector can see. A lexicon match that
63 /// overlaps a mention already detected is dropped, so a key can add a
64 /// mention but never replace one. A pronoun can take a lexicon mention as
65 /// its referent, and a pronoun the mention covers is replaced by it.
66 #[cfg_attr(feature = "serde", serde(default))]
67 pub aliases: BTreeMap<String, String>,
68
69 /// Minimum confidence threshold for returned candidates.
70 /// Candidates below this score are filtered out.
71 /// Default: 0.0 (all candidates returned).
72 #[cfg_attr(feature = "serde", serde(default))]
73 pub min_confidence: Option<f32>,
74
75 /// Candidates the caller has already judged wrong. A candidate whose
76 /// (subject, relation, object) matches one of these is not emitted.
77 ///
78 /// IMPORTANT: the crate persists nothing. This set is caller-owned state
79 /// handed in per call, so where it is stored between runs, and for how
80 /// long, stays the caller's decision.
81 ///
82 /// A rejection suppresses and does nothing else: it does not lower the
83 /// confidence of a sibling candidate, and it does not weaken the rule that
84 /// produced it. Feeding rejections back into scoring would make the output
85 /// depend on a history the caller cannot see in the result, and the span
86 /// and rule name are on every candidate precisely so a caller can audit
87 /// why it fired.
88 #[cfg_attr(feature = "serde", serde(default))]
89 pub rejections: Vec<Rejection>,
90
91 /// Optional mapping from recognized relation patterns to a caller-supplied controlled vocabulary.
92 /// Example: { "loves": "romantic_interest", "is_married_to": "spouse" }
93 /// If a relation type is not in this map, the heuristic default is used.
94 #[cfg_attr(feature = "serde", serde(default))]
95 pub ontology: BTreeMap<String, String>,
96}
97
98/// Whether a document states a fact or states that it does not hold.
99///
100/// IMPORTANT: a denial is a claim, not a missing assertion. Text that neither
101/// asserts nor denies — a conditional, a modal, a question, a complement held
102/// open by its main verb — produces no aggregate at all and so has no polarity.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
104#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
105#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
106#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
107pub enum Polarity {
108 Asserted,
109 Denied,
110}
111
112/// One fact as a whole document states it, with every piece of evidence for it.
113///
114/// `TripleCandidate` is per-sentence and `extract_candidate_triples` keeps the
115/// highest-confidence one per triple, discarding the spans of the rest. An
116/// aggregate keeps them: a passage stating one fact three ways yields one
117/// aggregate carrying three spans.
118#[derive(Debug, Clone)]
119#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
120#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
121pub struct AggregateTriple {
122 pub subject: String,
123 pub relation: String,
124 pub object: String,
125 /// Whether the document states this fact or denies it. A denial and the
126 /// assertion of the same triple are two aggregates, not one, because they
127 /// are two claims — and a document carrying both is the contradiction
128 /// `find_conflicts` reports.
129 pub polarity: Polarity,
130 /// The highest confidence of any supporting candidate.
131 ///
132 /// IMPORTANT: repetition does not raise it, and `spans.len()` is the only
133 /// thing that reports corroboration. In fiction a restatement is not
134 /// independent evidence — an unreliable narrator restates a falsehood as
135 /// readily as a reliable one states a fact — so summing would let a
136 /// thrice-repeated lie outrank a once-stated fact, and averaging would
137 /// punish a strong statement for being echoed by a weaker phrasing. The
138 /// score answers "how good is the best evidence", not "how much is there".
139 pub confidence: f32,
140 /// Every span the fact was found at, in document order. Never empty.
141 pub spans: Vec<[usize; 2]>,
142 /// The rules that produced those spans, first occurrence first, without
143 /// repeats. Two spans from one rule name it once.
144 pub rules: Vec<String>,
145}
146
147/// Why two aggregates cannot both be true.
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
150#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
151#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
152pub enum ConflictKind {
153 /// The document asserts a fact and denies the same fact.
154 Denial,
155 /// The relation admits one subject per object, and two subjects are
156 /// asserted over the same object.
157 Cardinality,
158}
159
160/// Two claims a single passage cannot both support, with the evidence for each.
161///
162/// IMPORTANT: a conflict is not a ranking. Neither side is the true one, and
163/// the crate has no way to decide which is: both carry their spans so the
164/// decision stays with whoever can read the manuscript.
165#[derive(Debug, Clone)]
166#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
167#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
168pub struct Conflict {
169 pub kind: ConflictKind,
170 /// The claim appearing first in the document.
171 pub left: AggregateTriple,
172 /// The claim appearing second.
173 pub right: AggregateTriple,
174}
175
176/// A reference span into the input text with its corresponding surface text.
177#[derive(Debug, Clone)]
178#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
179#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
180pub struct SpannedTriple {
181 pub candidate: TripleCandidate,
182 /// The actual text from input[span[0]..span[1]].
183 pub text: String,
184}
185
186/// Everything one pass over a passage yields: what `extract_candidate_triples`,
187/// `extract_aggregates` and `find_conflicts` return separately.
188#[derive(Debug, Clone)]
189#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
190#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))]
191pub struct Analysis {
192 pub candidates: Vec<TripleCandidate>,
193 pub aggregates: Vec<AggregateTriple>,
194 pub conflicts: Vec<Conflict>,
195}