mod aggregate;
mod context;
mod cooccurrence;
mod dialogue;
mod entities;
mod kinds;
pub mod pack;
mod quotes;
mod register;
mod relations;
mod segment;
use crate::types::{AggregateTriple, Analysis, Conflict, Options, Polarity, TripleCandidate};
use crate::Result;
use pack::LanguagePack;
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet};
pub use context::Context;
pub use entities::extract_entities;
pub use relations::normalize_relation;
pub fn extract_candidate_triples(text: &str, opts: &Options) -> Result<Vec<TripleCandidate>> {
extract_candidate_triples_in(text, opts, &Context::default())
}
pub fn extract_candidate_triples_in(
text: &str,
opts: &Options,
context: &Context,
) -> Result<Vec<TripleCandidate>> {
let mut candidates: Vec<TripleCandidate> =
collect_candidates(text, opts, &pack::ENGLISH, context)?
.into_iter()
.filter(|e| e.polarity == Polarity::Asserted)
.map(|e| e.candidate)
.collect();
dedup_candidates(&mut candidates);
Ok(candidates)
}
pub fn extract_aggregates(text: &str, opts: &Options) -> Result<Vec<AggregateTriple>> {
extract_aggregates_in(text, opts, &Context::default())
}
pub fn extract_aggregates_in(
text: &str,
opts: &Options,
context: &Context,
) -> Result<Vec<AggregateTriple>> {
let candidates = collect_candidates(text, opts, &pack::ENGLISH, context)?;
Ok(aggregate::aggregate(candidates).0)
}
pub fn find_conflicts(text: &str, opts: &Options) -> Result<Vec<Conflict>> {
find_conflicts_in(text, opts, &Context::default())
}
pub fn find_conflicts_in(text: &str, opts: &Options, context: &Context) -> Result<Vec<Conflict>> {
let candidates = collect_candidates(text, opts, &pack::ENGLISH, context)?;
let (aggregates, single_filler) = aggregate::aggregate(candidates);
Ok(aggregate::find_conflicts(&aggregates, &single_filler))
}
pub fn analyze(text: &str, opts: &Options) -> Result<Analysis> {
analyze_in(text, opts, &Context::default())
}
pub fn analyze_in(text: &str, opts: &Options, context: &Context) -> Result<Analysis> {
let emitted = collect_candidates(text, opts, &pack::ENGLISH, context)?;
let mut candidates: Vec<TripleCandidate> = emitted
.iter()
.filter(|e| e.polarity == Polarity::Asserted)
.map(|e| e.candidate.clone())
.collect();
dedup_candidates(&mut candidates);
let (aggregates, single_filler) = aggregate::aggregate(emitted);
let conflicts = aggregate::find_conflicts(&aggregates, &single_filler);
Ok(Analysis {
candidates,
aggregates,
conflicts,
})
}
pub(crate) struct Emitted {
candidate: TripleCandidate,
polarity: Polarity,
single_filler: bool,
}
fn collect_candidates(
text: &str,
opts: &Options,
pack: &LanguagePack,
context: &Context,
) -> Result<Vec<Emitted>> {
let min_confidence = opts.min_confidence.unwrap_or(0.0);
if !(0.0..=1.0).contains(&min_confidence) {
return Err(crate::NarrativeGraphError::InvalidConfidenceThreshold(
min_confidence,
));
}
if text.is_empty() {
return Ok(vec![]);
}
let rejected: BTreeSet<(&str, &str, &str)> = opts
.rejections
.iter()
.map(|r| (r.subject.as_str(), r.relation.as_str(), r.object.as_str()))
.collect();
let mut candidates = Vec::new();
let mut carried: Vec<String> = Vec::new();
let mut previous_end = 0usize;
let mut register = context.register().clone();
context::observe_text(&mut register, text, pack);
let narrator = context.narrator();
let mut quote_open = false;
let mut turn = dialogue::Turn::default();
let paragraph_break = if text.contains("\n\n") { 2 } else { 1 };
let mut found = Vec::new();
for (sent_text, sent_start) in segment::split_sentences(text, pack) {
let breaks = text[previous_end..sent_start].matches('\n').count();
if breaks >= paragraph_break {
quote_open = false;
}
if breaks >= paragraph_break {
found.extend(
turn.finish(&opts.ontology, ®ister, pack, false)
.into_iter()
.map(|r| (r, 0)),
);
}
if text[previous_end..sent_start]
.matches('\n')
.nth(1)
.is_some()
{
carried.clear();
}
previous_end = sent_start + sent_text.len();
let opened = quote_open;
let quotes = quotes::QuoteMap::scan(sent_text, quote_open);
quote_open = quotes.open_at_end;
let entities = entities::extract_entities_in(
sent_text,
&opts.aliases,
pack,
&carried,
®ister,
"es,
narrator,
);
carried = entities::carried_referents(sent_text, &entities, pack);
turn.observe(sent_text, sent_start, &entities, "es, opened, pack);
if entities.is_empty() {
continue;
}
let scope = relations::Scope {
register: ®ister,
quotes: "es,
mentions: &entities,
};
found.extend(
relations::extract_relations(sent_text, &entities, &opts.ontology, pack, &scope)
.into_iter()
.map(|r| (r, sent_start)),
);
}
found.extend(
turn.finish(&opts.ontology, ®ister, pack, true)
.into_iter()
.map(|r| (r, 0)),
);
if narrator.is_none() {
if let Some(name) = turn.narrator() {
return collect_candidates(text, opts, pack, &context.clone().with_narrator(&name));
}
}
let common = dialogue::common_words(
text,
found
.iter()
.filter(|(r, _)| dialogue::is_rule(&r.rule))
.flat_map(|(r, _)| [r.subject.as_str(), r.object.as_str()]),
);
found.retain(|(r, _)| {
!dialogue::is_rule(&r.rule)
|| (dialogue::is_voice(&r.subject, 2, &turn, ®ister)
&& dialogue::is_voice(&r.object, 1, &turn, ®ister)
&& ![&r.subject, &r.object]
.iter()
.any(|n| common.contains(*n) || pack.sentence_openers.contains(&n.as_str())))
});
for (rel, offset) in found {
let confidence = cooccurrence::score_confidence(rel.base, rel.gap);
let key = (
rel.subject.as_str(),
rel.relation.as_str(),
rel.object.as_str(),
);
if confidence >= min_confidence && !rejected.contains(&key) {
let span = [offset + rel.span[0], offset + rel.span[1]];
let polarity = match rel.stance {
relations::Stance::Asserted => Polarity::Asserted,
relations::Stance::Denied => Polarity::Denied,
relations::Stance::Suspended => continue,
};
candidates.push(Emitted {
candidate: TripleCandidate {
subject: rel.subject,
relation: rel.relation,
object: rel.object,
confidence,
span,
rule: rel.rule,
},
polarity,
single_filler: rel.single_filler,
});
}
}
Ok(candidates)
}
fn dedup_candidates(candidates: &mut Vec<TripleCandidate>) {
struct Best {
confidence: f32,
span: [usize; 2],
rule: String,
}
let mut best: BTreeMap<(String, String, String), Best> = BTreeMap::new();
for candidate in candidates.drain(..) {
let TripleCandidate {
subject,
relation,
object,
confidence,
span,
rule,
} = candidate;
let evidence = Best {
confidence,
span,
rule,
};
match best.entry((subject, relation, object)) {
Entry::Vacant(entry) => {
entry.insert(evidence);
}
Entry::Occupied(mut entry) => {
if evidence.confidence > entry.get().confidence {
entry.insert(evidence);
}
}
}
}
candidates.extend(
best.into_iter()
.map(|((subject, relation, object), b)| TripleCandidate {
subject,
relation,
object,
confidence: b.confidence,
span: b.span,
rule: b.rule,
}),
);
}