use super::pack::LanguagePack;
use super::quotes::QuoteMap;
use std::collections::BTreeMap;
#[derive(Debug, Clone)]
pub struct EntityCandidate {
pub text: String,
pub normalized: String,
pub start: usize,
pub end: usize,
pub pronoun: bool,
pub quoted: bool,
}
pub fn extract_entities(text: &str, aliases: &BTreeMap<String, String>) -> Vec<EntityCandidate> {
let pack = &super::pack::ENGLISH;
let quotes = QuoteMap::default();
let mut entities = named_mentions(text, aliases, pack, "es);
entities.extend(resolve_pronouns(text, pack, &entities));
entities.sort_by_key(|m| m.start);
entities
}
pub fn mentions_for_register(text: &str, pack: &LanguagePack) -> Vec<EntityCandidate> {
extract_capitalized_entities(text, pack)
}
pub(super) fn named_mentions(
text: &str,
aliases: &BTreeMap<String, String>,
pack: &LanguagePack,
quotes: &QuoteMap,
) -> Vec<EntityCandidate> {
let mut entities = extract_capitalized_entities(text, pack);
for entity in &mut entities {
if let Some(canonical) = aliases.get(&entity.text) {
entity.normalized = canonical.clone();
}
}
entities.extend(lexicon_mentions(text, aliases, &entities));
entities.sort_by_key(|e| e.start);
for entity in &mut entities {
entity.quoted = quotes.inside(entity.start);
}
entities
}
fn is_title_word(word: &str, next: Option<&str>, pack: &LanguagePack) -> bool {
let word = word.to_lowercase();
if pack.honorific_qualifiers.contains(&word.as_str()) {
return next.is_some_and(|n| pack.honorifics.contains(&n.to_lowercase().as_str()));
}
pack.honorifics.contains(&word.as_str())
}
fn strip_honorifics<'a>(entity: &'a str, pack: &LanguagePack) -> &'a str {
let mut rest = entity;
while let Some((head, tail)) = rest.split_once(' ') {
if name_word_count(tail, pack) < 2 || !is_title_word(head, tail.split(' ').next(), pack) {
break;
}
rest = tail;
}
rest
}
fn name_word_count(run: &str, pack: &LanguagePack) -> usize {
run.split(' ')
.filter(|w| !pack.name_particles.contains(&w.to_lowercase().as_str()))
.count()
}
fn is_sentence_start(text: &str, word_start: usize) -> bool {
let mut quoted = false;
for c in text[..word_start].chars().rev() {
if c.is_whitespace() {
continue;
}
if "\"'\u{201C}\u{2018}([".contains(c) {
quoted = true;
continue;
}
return ".!?\u{2026}".contains(c) || (quoted && c == ',');
}
true
}
fn opens_sentence_by_position(
text: &str,
word: &str,
word_start: usize,
pack: &LanguagePack,
) -> bool {
pack.sentence_openers
.iter()
.any(|opener| word.eq_ignore_ascii_case(opener))
&& is_sentence_start(text, word_start)
}
fn push_entity(
entities: &mut Vec<EntityCandidate>,
run: &str,
start: usize,
end: usize,
pack: &LanguagePack,
) {
let is_pronoun = |list: &[&str]| list.iter().any(|p| run.eq_ignore_ascii_case(p));
if is_pronoun(pack.pronouns) || is_pronoun(pack.deictic_pronouns) {
return;
}
entities.push(EntityCandidate {
text: run.to_string(),
normalized: normalize_entity(strip_honorifics(run, pack)),
start,
end,
pronoun: false,
quoted: false,
});
}
fn is_separator(c: char) -> bool {
c == '.' || is_hard_break(c)
}
fn joins_name(text: &str, at: usize, c: char) -> bool {
matches!(c, '\'' | '\u{2019}')
&& text[..at]
.chars()
.next_back()
.is_some_and(char::is_alphabetic)
&& text[at + c.len_utf8()..]
.chars()
.next()
.is_some_and(char::is_uppercase)
}
fn is_hard_break(c: char) -> bool {
matches!(
c,
',' | '!'
| '?'
| ';'
| ':'
| '\u{2014}'
| '\''
| '\u{2019}'
| '\u{2018}'
| '"'
| '\u{201C}'
| '\u{201D}'
| '('
| ')'
| '['
| ']'
)
}
fn extract_capitalized_entities(text: &str, pack: &LanguagePack) -> Vec<EntityCandidate> {
let mut entities = Vec::new();
let mut current_entity = String::new();
let mut start_idx = 0;
let mut current_word = String::new();
let mut word_start = 0;
let mut entity_end = 0;
let mut pending_particles = String::new();
for (byte_pos, c) in text.char_indices() {
let is_sep = c.is_whitespace() || (is_separator(c) && !joins_name(text, byte_pos, c));
if is_sep {
if !current_word.is_empty() {
let is_capitalized = current_word
.chars()
.next()
.is_some_and(|c| c.is_uppercase())
&& !(current_entity.is_empty()
&& opens_sentence_by_position(text, ¤t_word, word_start, pack));
if is_capitalized {
if !current_entity.is_empty() {
current_entity.push(' ');
current_entity.push_str(&pending_particles);
} else {
start_idx = word_start;
}
pending_particles.clear();
current_entity.push_str(¤t_word);
entity_end = byte_pos;
} else if !current_entity.is_empty()
&& c.is_whitespace()
&& pack
.name_particles
.contains(¤t_word.to_lowercase().as_str())
{
pending_particles.push_str(¤t_word);
pending_particles.push(' ');
} else {
if !current_entity.is_empty() {
push_entity(&mut entities, ¤t_entity, start_idx, entity_end, pack);
current_entity.clear();
}
pending_particles.clear();
}
current_word.clear();
}
if is_hard_break(c) && !current_entity.is_empty() {
push_entity(&mut entities, ¤t_entity, start_idx, entity_end, pack);
current_entity.clear();
pending_particles.clear();
}
} else {
if current_word.is_empty() {
word_start = byte_pos;
}
current_word.push(c);
}
}
if !current_word.is_empty() {
let is_capitalized = current_word
.chars()
.next()
.is_some_and(|c| c.is_uppercase())
&& !(current_entity.is_empty()
&& opens_sentence_by_position(text, ¤t_word, word_start, pack));
if is_capitalized {
if !current_entity.is_empty() {
current_entity.push(' ');
current_entity.push_str(&pending_particles);
} else {
start_idx = word_start;
}
current_entity.push_str(¤t_word);
entity_end = text.len();
} else if !current_entity.is_empty() {
push_entity(&mut entities, ¤t_entity, start_idx, entity_end, pack);
current_entity.clear();
}
}
if !current_entity.is_empty() {
push_entity(&mut entities, ¤t_entity, start_idx, entity_end, pack);
}
entities
}
fn lexicon_mentions(
text: &str,
aliases: &BTreeMap<String, String>,
existing: &[EntityCandidate],
) -> Vec<EntityCandidate> {
let mut keys: Vec<(&String, &String)> = aliases
.iter()
.filter(|(key, _)| !key.is_empty() && !key.chars().any(char::is_uppercase))
.collect();
if keys.is_empty() {
return Vec::new();
}
keys.sort_by(|a, b| {
b.0.chars()
.count()
.cmp(&a.0.chars().count())
.then_with(|| a.0.cmp(b.0))
});
let mut found: Vec<EntityCandidate> = Vec::new();
for (key, canonical) in keys {
for (start, _) in text.char_indices() {
if !is_word_boundary(text[..start].chars().next_back()) {
continue;
}
let Some(end) = match_phrase(text, start, key) else {
continue;
};
if !is_word_boundary(text[end..].chars().next()) {
continue;
}
let overlaps = |m: &EntityCandidate| start < m.end && m.start < end;
if existing.iter().any(overlaps) || found.iter().any(overlaps) {
continue;
}
found.push(EntityCandidate {
text: text[start..end].to_string(),
normalized: canonical.clone(),
start,
end,
pronoun: false,
quoted: false,
});
}
}
found
}
fn is_word_boundary(c: Option<char>) -> bool {
!c.is_some_and(char::is_alphanumeric)
}
fn match_phrase(text: &str, start: usize, key: &str) -> Option<usize> {
let mut end = start;
let mut want = key.chars();
for got in text[start..].chars() {
for lowered in got.to_lowercase() {
if want.next()? != lowered {
return None;
}
}
end += got.len_utf8();
if want.as_str().is_empty() {
return Some(end);
}
}
None
}
#[derive(Debug)]
pub(super) struct Pronoun {
pub text: &'static str,
pub start: usize,
pub end: usize,
}
impl Pronoun {
pub fn mention(&self, name: &str) -> EntityCandidate {
EntityCandidate {
text: self.text.to_string(),
normalized: name.to_string(),
start: self.start,
end: self.end,
pronoun: true,
quoted: false,
}
}
}
pub(super) fn extract_pronouns(text: &str, pack: &LanguagePack) -> Vec<Pronoun> {
let mut found = Vec::new();
let mut word_start: Option<usize> = None;
let sentinel = std::iter::once((text.len(), ' '));
for (byte_pos, c) in text.char_indices().chain(sentinel) {
if c.is_alphabetic() {
word_start.get_or_insert(byte_pos);
continue;
}
if let Some(start) = word_start.take() {
let word = &text[start..byte_pos];
if let Some(pronoun) = pack.pronouns.iter().find(|p| word.eq_ignore_ascii_case(p)) {
found.push(Pronoun {
text: pronoun,
start,
end: byte_pos,
});
}
}
}
found
}
fn resolve_pronouns(
text: &str,
pack: &LanguagePack,
mentions: &[EntityCandidate],
) -> Vec<EntityCandidate> {
extract_pronouns(text, pack)
.into_iter()
.filter_map(|pronoun| {
if mentions
.iter()
.any(|m| pronoun.start < m.end && m.start < pronoun.end)
{
return None;
}
let name = mentions.iter().rev().find(|m| m.end <= pronoun.start)?;
Some(pronoun.mention(&name.normalized))
})
.collect()
}
pub(super) fn first_person_mentions(
text: &str,
pack: &LanguagePack,
narrator: &str,
quotes: &QuoteMap,
) -> Vec<EntityCandidate> {
let mut found = Vec::new();
let mut word_start: Option<usize> = None;
let sentinel = std::iter::once((text.len(), ' '));
for (byte_pos, c) in text.char_indices().chain(sentinel) {
if c.is_alphabetic() {
word_start.get_or_insert(byte_pos);
continue;
}
let Some(start) = word_start.take() else {
continue;
};
let word = &text[start..byte_pos];
if pack
.first_person_pronouns
.iter()
.any(|p| word.eq_ignore_ascii_case(p))
&& !quotes.inside(start)
{
found.push(EntityCandidate {
text: word.to_string(),
normalized: narrator.to_string(),
start,
end: byte_pos,
pronoun: true,
quoted: false,
});
}
}
found
}
pub(super) fn carried_referents(
sentence: &str,
entities: &[EntityCandidate],
pack: &LanguagePack,
) -> Vec<String> {
let mut carried: Vec<String> = Vec::new();
for entity in entities {
let is_pronoun = pack
.pronouns
.iter()
.any(|p| entity.text.eq_ignore_ascii_case(p));
let is_possessor = super::relations::opens_possessive(sentence, entity.end, pack);
if is_pronoun
|| entity.pronoun
|| entity.quoted
|| is_possessor
|| carried.contains(&entity.normalized)
{
continue;
}
carried.push(entity.normalized.clone());
}
carried
}
fn normalize_entity(text: &str) -> String {
text.to_lowercase()
.split_whitespace()
.collect::<Vec<_>>()
.join("_")
}