use serde::Serialize;
use crate::norm::normalize;
use crate::query::{query_cascade, Hit, Index};
use crate::verdict;
pub const MAX_WINDOWS: usize = 2000;
const MIN_WORDS: usize = 2;
const MAX_WORDS: usize = 10;
#[derive(Clone, Serialize)]
pub struct Found {
pub start: usize,
pub end: usize,
pub text: String,
pub level: &'static str,
pub verdict: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<&'static str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hit: Option<Hit>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Stats {
pub windows: usize,
pub capped: bool,
}
#[derive(Clone, Copy, PartialEq)]
enum Kind {
Word,
Number,
Phone,
}
struct Token {
start: usize,
end: usize,
kind: Kind,
line: usize,
}
fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || matches!(c, '\'' | '’' | '-' | '/' | '.')
}
fn is_house_number(s: &str) -> bool {
let digits = s.chars().take_while(char::is_ascii_digit).count();
if !(1..=5).contains(&digits) {
return false;
}
let rest = &s[digits..];
rest.is_empty()
|| (rest.chars().count() == 1 && rest.chars().all(char::is_alphabetic))
|| (rest.starts_with('/')
&& rest[1..].chars().all(|c| c.is_ascii_digit())
&& rest.len() <= 4)
}
fn tokens(text: &str) -> Vec<Token> {
let mut out: Vec<Token> = Vec::new();
let mut line = 0;
let mut cur: Option<usize> = None;
let push = |out: &mut Vec<Token>, start: usize, end: usize, line: usize| {
let raw = text[start..end].trim_end_matches(['.', '-', '/', '\'']);
let end = start + raw.len();
if raw.is_empty() {
return;
}
let digit_count = raw.chars().filter(char::is_ascii_digit).count();
let dialled = raw.chars().all(|c| c.is_ascii_digit() || c == '-') && digit_count >= 6;
let kind = if dialled || (raw.chars().all(|c| c.is_ascii_digit()) && raw.len() > 5) {
Kind::Phone
} else if is_house_number(raw) {
Kind::Number
} else {
Kind::Word
};
out.push(Token {
start,
end,
kind,
line,
});
};
for (i, c) in text.char_indices() {
if is_word_char(c) {
cur.get_or_insert(i);
} else {
if let Some(s) = cur.take() {
push(&mut out, s, i, line);
}
if c == '\n' || c == ';' {
line += 1;
}
}
}
if let Some(s) = cur {
push(&mut out, s, text.len(), line);
}
mark_phones(text, &mut out);
out
}
fn mark_phones(text: &str, toks: &mut [Token]) {
let numeric = |t: &Token| {
t.kind != Kind::Word
&& text[t.start..t.end]
.chars()
.all(|c| c.is_ascii_digit() || c == '-')
};
let mut i = 0;
while i < toks.len() {
if !numeric(&toks[i]) {
i += 1;
continue;
}
let mut j = i;
while j + 1 < toks.len()
&& numeric(&toks[j + 1])
&& toks[j + 1].line == toks[i].line
&& text[toks[j].end..toks[j + 1].start]
.chars()
.all(|c| matches!(c, ' ' | '-' | '(' | ')'))
{
j += 1;
}
let digits: usize = toks[i..=j]
.iter()
.map(|t| {
text[t.start..t.end]
.chars()
.filter(char::is_ascii_digit)
.count()
})
.sum();
let plus = text[..toks[i].start]
.trim_end_matches([' ', '('])
.ends_with('+');
if plus || digits >= 7 || toks[i..=j].iter().any(|t| t.kind == Kind::Phone) {
for t in &mut toks[i..=j] {
t.kind = Kind::Phone;
}
}
i = j + 1;
}
}
struct Candidate {
start: usize,
end: usize,
words: usize,
house: bool,
exact: bool,
clean: bool,
lead: bool,
number: bool,
found: Found,
}
fn windows(idx: &Index, text: &str, toks: &[Token]) -> Vec<(usize, usize, bool)> {
let anchor = |t: &Token| is_anchor(idx, text, t);
let mut out = Vec::new();
for i in 0..toks.len() {
for n in MIN_WORDS..=MAX_WORDS {
let j = i + n - 1;
if j >= toks.len() || toks[j].line != toks[i].line {
break;
}
let span = &toks[i..=j];
if span.iter().any(|t| t.kind == Kind::Phone) {
break;
}
if span.iter().any(anchor) {
out.push((i, j, span.iter().any(|t| t.kind == Kind::Number)));
}
}
}
out
}
fn is_anchor(idx: &Index, text: &str, t: &Token) -> bool {
t.kind == Kind::Number || idx.is_street_type(&normalize(&text[t.start..t.end]))
}
fn reason(hits: &[Hit]) -> &'static str {
let Some(h) = hits.first() else {
return "street_unknown";
};
if hits.len() > 1 && hits[1].commune != h.commune && hits[1].street == h.street {
return "ambiguous";
}
if h.flags.contains(&"ambiguous_far") {
return "ambiguous";
}
if !h.street.is_empty() && matches!(h.precision, "street" | "interp" | "near" | "house") {
"number_not_on_street"
} else {
"street_unknown"
}
}
pub fn extract(idx: &Index, text: &str, verify: bool) -> (Vec<Found>, Stats) {
let toks = tokens(text);
let mut all = windows(idx, text, &toks);
let stats = Stats {
windows: all.len().min(MAX_WINDOWS),
capped: all.len() > MAX_WINDOWS,
};
all.truncate(MAX_WINDOWS);
use rayon::prelude::*;
let judged: Vec<(Candidate, bool)> = all
.into_par_iter()
.filter_map(|(i, j, has_number)| {
let (start, end) = (toks[i].start, toks[j].end);
let window = &text[start..end];
let hits = query_cascade(idx, None, window, if verify { 2 } else { 1 });
let level = match hits.first().map(|h| judge(idx, text, &toks, (i, j), h)) {
Some(Judged::Found(level)) => Some(level),
Some(Judged::Elsewhere) => return None,
Some(Judged::Missing) | None => None,
};
if level.is_none() && !(verify && has_number) {
return None;
}
let exact = hits
.first()
.is_some_and(|h| h.flags.contains(&"street_exact"));
let clean = hits.first().is_some_and(|h| {
h.precision != "city" && !h.flags.iter().any(|f| f.starts_with("dropped_"))
});
let found = Found {
start,
end,
text: window.to_string(),
level: level.unwrap_or("none"),
verdict: if level.is_some() {
"found"
} else {
"not_found"
},
reason: level.is_none().then(|| reason(&hits)),
hit: hits.first().cloned(),
};
let c = Candidate {
start,
end,
words: j - i + 1,
house: level == Some("house"),
exact,
clean,
lead: is_anchor(idx, text, &toks[i]),
number: has_number,
found,
};
Some((c, level.is_some()))
})
.collect();
let (found, missing): (Vec<_>, Vec<_>) = judged.into_iter().partition(|(_, ok)| *ok);
let found: Vec<Candidate> = found.into_iter().map(|(c, _)| c).collect();
let missing: Vec<Candidate> = missing.into_iter().map(|(c, _)| c).collect();
let mut out = pick(found, false);
if verify {
let overlaps = |a: &Candidate, b: &Candidate| a.start < b.end && b.start < a.end;
let mut missing: Vec<Candidate> = missing
.into_iter()
.filter(|m| !out.iter().any(|f| f.house && overlaps(f, m)))
.collect();
let (replaced, kept): (Vec<Candidate>, Vec<Candidate>) = out
.into_iter()
.partition(|f| !f.house && f.number && missing.iter().any(|m| overlaps(f, m)));
out = kept;
missing.extend(replaced.into_iter().map(|mut f| {
f.found.level = "none";
f.found.verdict = "not_found";
f.found.reason = Some("number_not_on_street");
f
}));
let missing = pick(missing, true);
out.retain(|f| f.house || !missing.iter().any(|m| overlaps(f, m)));
out.extend(missing);
}
out.sort_by_key(|c| c.start);
(out.into_iter().map(|c| c.found).collect(), stats)
}
enum Judged {
Found(&'static str),
Missing,
Elsewhere,
}
#[derive(Debug, Default, PartialEq)]
struct Place {
postcode: Option<u32>,
city: Option<String>,
formal: bool,
}
const PLACE_STOP: [&str; 6] = ["le", "la", "les", "de", "du", "des"];
fn place_after(idx: &Index, text: &str, toks: &[Token], (i, j): (usize, usize)) -> Place {
let on_line =
|p: usize| p < toks.len() && toks[p].line == toks[i].line && toks[p].kind != Kind::Phone;
let mut last = j;
while last + 1 < j + MAX_WORDS && on_line(last + 1) {
last += 1;
}
let mut place = Place::default();
let comma_before =
|p: usize| p > 0 && p < toks.len() && text[toks[p - 1].end..toks[p].start].contains(',');
let mut city_at = vec![(j + 1, comma_before(j + 1))];
let value = |p: usize| text[toks[p].start..toks[p].end].parse::<u32>().ok();
let code =
|p: usize| toks[p].kind == Kind::Number && text[toks[p].start..toks[p].end].len() >= 4;
let inside = (i + 1..=j).any(code).then(|| {
let read = verdict::asked(idx, &text[toks[i].start..toks[j].end]).postcode;
(i + 1..=j)
.find(|&p| code(p) && read.is_some() && value(p) == read)
.zip(read)
});
if let Some(Some((p, pc))) = inside {
place.postcode = Some(pc);
city_at.push((p + 1, true));
} else if (j + 1..=last).any(code) {
let read = verdict::asked(idx, &text[toks[i].start..toks[last].end]).postcode;
let at = (j + 1..=last)
.find(|&p| toks[p].kind == Kind::Number)
.filter(|&p| read.is_some() && value(p) == read);
if let (Some(pc), Some(p)) = (read, at) {
place.postcode = Some(pc);
city_at.push((p + 1, true));
}
}
let next_address = |p: usize| {
on_line(p)
&& on_line(p + 1)
&& toks[p].kind == Kind::Number
&& idx.is_street_type(&normalize(&text[toks[p + 1].start..toks[p + 1].end]))
};
let after = (j + 1..=last)
.find(|&p| next_address(p))
.unwrap_or(last + 1);
city_at.extend(
(j + 2..after)
.filter(|&p| comma_before(p))
.map(|p| (p, true)),
);
city_at.extend((i + 1..=j).filter(|&p| comma_before(p)).map(|p| (p, true)));
city_at.retain(|&(p, _)| p < after);
city_at.sort_by_key(|&(p, _)| (p > j, p));
city_at.dedup_by_key(|c| c.0);
let town = |(p, formal): (usize, bool)| {
(1..=3).rev().find_map(|w| {
let q = p + w - 1;
if !(p..=q).all(|r| r <= last && on_line(r) && toks[r].kind == Kind::Word) {
return None;
}
if next_address(q + 1) {
return None;
}
let name = normalize(&text[toks[p].start..toks[q].end]);
let words: Vec<&str> = name.split_whitespace().collect();
(1..=words.len()).rev().find_map(|k| {
let name = words[..k].join(" ");
let letters = name.chars().filter(|c| c.is_alphabetic()).count();
(letters >= 3
&& !PLACE_STOP.contains(&name.as_str())
&& !country_word(idx, &name)
&& idx.names_commune(&name))
.then_some((name, formal))
})
})
};
if let Some((city, formal)) = city_at.into_iter().rev().find_map(town) {
place.city = Some(city);
place.formal = formal;
}
place
}
fn postcode_agrees(place: &Place, h: &Hit) -> Option<bool> {
let code: String = h.postcode.chars().filter(char::is_ascii_digit).collect();
match (place.postcode, code.parse::<u32>().ok()) {
(Some(a), Some(b)) => {
let (a, b) = (a.to_string(), b.to_string());
Some(a.starts_with(&b) || b.starts_with(&a))
}
_ => None,
}
}
fn same_area(place: &Place, h: &Hit) -> bool {
let code: String = h.postcode.chars().filter(char::is_ascii_digit).collect();
place.postcode.is_some_and(|pc| {
let line = format!("{pc:0w$}", w = code.len());
code.len() >= 2 && line.len() >= 2 && line[..2] == code[..2]
})
}
const COUNTRY_NAMES: [&str; 20] = [
"australia",
"brasil",
"brazil",
"canada",
"deutschland",
"espana",
"france",
"germany",
"italia",
"italy",
"mexico",
"monaco",
"nederland",
"netherlands",
"serbia",
"spain",
"srbija",
"united states",
"usa",
"uzbekistan",
];
fn country_word(idx: &Index, name: &str) -> bool {
let rules = idx.rule_set();
COUNTRY_NAMES.contains(&name)
|| rules.countries_tail.contains(name)
|| rules
.city_tail
.get("junk_tail")
.is_some_and(|junk| junk.split_whitespace().any(|w| w == name))
}
fn city_contradicts(idx: &Index, place: &Place, h: &Hit) -> bool {
place.city.as_deref().is_some_and(|name| {
let own = normalize(&h.commune);
let own_town = own == name || own.starts_with(&format!("{name} "));
!(own_town || idx.near_commune_named(name, h.lat, h.lon))
})
}
fn type_word_street(idx: &Index, h: &Hit) -> bool {
let name = normalize(&h.street);
let mut words = name.split_whitespace();
matches!((words.next(), words.next()), (Some(w), None) if idx.is_street_type(w))
}
fn street_from_another_part(
idx: &Index,
text: &str,
toks: &[Token],
(i, j): (usize, usize),
h: &Hit,
) -> bool {
let Some(n) = (i..=j).find(|&p| toks[p].kind == Kind::Number) else {
return false;
};
let after = n + 1;
if after >= toks.len() || toks[after].line != toks[n].line {
return false;
}
let gap = &text[toks[n].end..toks[after].start];
if !(gap.contains(',') || gap.contains('-')) {
return false;
}
let word = |p: usize| normalize(&text[toks[p].start..toks[p].end]);
if toks[after].kind == Kind::Word && idx.is_street_type(&word(after)) {
return false;
}
let stem = |w: &str| w.chars().take(3).collect::<String>();
let name = normalize(&h.street);
let street: Vec<String> = name.split_whitespace().map(stem).collect();
let compact: String = name.chars().filter(|c| !c.is_whitespace()).collect();
let before: Vec<String> = (i..n)
.flat_map(|p| {
word(p)
.split_whitespace()
.map(str::to_string)
.collect::<Vec<_>>()
})
.filter(|w| !PLACE_STOP.contains(&w.as_str()))
.collect();
let named: Vec<&String> = before.iter().filter(|w| !idx.is_street_type(w)).collect();
let named = if named.is_empty() {
before.iter().collect()
} else {
named
};
!named.iter().any(|w| {
let letters = w.chars().filter(|c| c.is_alphabetic()).count();
(w.chars().any(|c| c.is_ascii_digit()) && w.len() >= 2 && compact.contains(w.as_str()))
|| (letters >= 3 && street.contains(&stem(w)))
})
}
fn judge(idx: &Index, text: &str, toks: &[Token], (i, j): (usize, usize), h: &Hit) -> Judged {
let window = &text[toks[i].start..toks[j].end];
let level = accept(idx, window, h);
let placed = h
.flags
.iter()
.any(|f| f.starts_with("commune_") || *f == "pc_exact" || *f == "place_exact");
if !placed && type_word_street(idx, h) {
return Judged::Elsewhere;
}
if street_from_another_part(idx, text, toks, (i, j), h) {
return Judged::Elsewhere;
}
let place = place_after(idx, text, toks, (i, j));
let postcode = postcode_agrees(&place, h);
let city_off =
postcode != Some(true) && (!placed || place.formal) && city_contradicts(idx, &place, h);
let town_agrees = place.city.is_some() && !city_contradicts(idx, &place, h);
let named =
placed && h.flags.contains(&"street_exact") && (same_area(&place, h) || town_agrees);
if postcode == Some(false) && !named && !h.flags.contains(&"pc_exact") {
return Judged::Elsewhere;
}
if city_off {
return Judged::Elsewhere;
}
level.map_or(Judged::Missing, Judged::Found)
}
fn accept(idx: &Index, window: &str, h: &Hit) -> Option<&'static str> {
if h.flags.contains(&"poi_layer") || crate::query::hit_is_weak(h) {
return None;
}
let v = verdict::field_verdicts(verdict::reading(idx, window), h);
if h.precision == "house" && v.number == "confirmed" && v.street != "unresolved" {
Some("house")
} else if matches!(v.street, "confirmed" | "corrected")
&& matches!(h.precision, "street" | "interp" | "near" | "house")
{
Some("street")
} else {
None
}
}
fn pick(mut cands: Vec<Candidate>, by_lead: bool) -> Vec<Candidate> {
cands.sort_by(|a, b| {
b.house
.cmp(&a.house)
.then(b.exact.cmp(&a.exact))
.then(if by_lead {
b.lead.cmp(&a.lead)
} else {
std::cmp::Ordering::Equal
})
.then(b.clean.cmp(&a.clean))
.then(b.words.cmp(&a.words))
.then(a.start.cmp(&b.start))
});
let mut kept: Vec<Candidate> = Vec::new();
for c in cands {
if kept.iter().all(|k| c.end <= k.start || k.end <= c.start) {
kept.push(c);
}
}
kept
}
#[cfg(test)]
mod tests {
use super::*;
fn kinds(text: &str) -> Vec<(String, bool)> {
tokens(text)
.iter()
.map(|t| (text[t.start..t.end].to_string(), t.kind == Kind::Phone))
.collect()
}
#[test]
fn a_phone_is_never_a_number_anchor() {
let k = kinds("Call +381 11 1234567 or 011 222-33-44, Rue A 3");
assert!(k
.iter()
.filter(|(w, _)| ["381", "11", "1234567", "011", "222-33-44"].contains(&w.as_str()))
.all(|(_, p)| *p));
assert!(
k.iter().any(|(w, p)| w == "3" && !p),
"a lone house number stays an anchor: {k:?}"
);
}
#[test]
fn house_numbers_take_a_letter_or_a_slash_tail() {
assert!(is_house_number("12"));
assert!(is_house_number("12a"));
assert!(is_house_number("12/3"));
assert!(!is_house_number("123456"));
assert!(!is_house_number("12abc"));
}
#[test]
fn offsets_are_bytes_of_the_text_as_given() {
let text = "Ulica Đure 5";
let t = tokens(text);
assert_eq!(&text[t[1].start..t[1].end], "Đure");
assert_eq!(&text[t[2].start..t[2].end], "5");
}
}