use anyhow::{anyhow, bail, Context, Result};
use arrow::array::{Array, ArrayRef, BinaryArray, LargeBinaryArray, StringArray};
use arrow::datatypes::DataType;
use clap::Parser;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::arrow::ProjectionMask;
use rayon::prelude::*;
use rusqlite::functions::FunctionFlags;
use rusqlite::{params, Connection};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Instant;
const SUPPORTED_EXT: &[&str] = &[
"parquet", "gpkg", "fgb", "geojson", "json", "shp", "csv", "pbf",
];
const ALIASES: &[(&str, &[&str])] = &[
(
"label",
&[
"label",
"full_address",
"display_name",
"adresse",
"address",
"idu",
"graphie",
"nom_toponyme",
"toponyme",
],
),
(
"housenumber",
&[
"numero",
"housenumber",
"house_number",
"addr:housenumber",
"number",
"num",
],
),
(
"suffix",
&[
"suffixe",
"rep",
"repetition",
"indice_de_repetition",
"suffix",
"unit",
],
),
(
"street",
&[
"nom_voie",
"street",
"addr:street",
"voie",
"nom_afnor",
"road",
"thoroughfare",
"toponyme",
"nom_toponyme",
"graphie_du_toponyme",
"graphie",
"section",
"name",
"nom",
"nature_detaillee",
"nature",
],
),
(
"locality",
&[
"lieu_dit",
"nom_ld",
"addr:place",
"place",
"hamlet",
"feuille",
"nature_detaillee_de_l_objet",
"nature_de_l_objet",
"classe_de_l_objet",
],
),
(
"postcode",
&[
"code_postal",
"postcode",
"postal_code",
"addr:postcode",
"zip",
"zipcode",
"cp",
"code_com",
"insee_com",
],
),
(
"city",
&[
"nom_commune",
"nom_com",
"city",
"addr:city",
"commune",
"municipality",
"town",
"village",
"locality_name",
],
),
("lon", &["lon", "longitude", "lng", "long", "x"]),
("lat", &["lat", "latitude", "y"]),
];
const KEYS: [&str; 7] = [
"label",
"housenumber",
"suffix",
"street",
"locality",
"postcode",
"city",
];
#[derive(Parser)]
#[command(
name = "build-geocoder",
about = "Build an offline FTS5 + R*Tree address database for cesium-viewer --geocoder."
)]
struct Args {
#[arg(short, long, num_args = 1.., required = true)]
input: Vec<PathBuf>,
#[arg(short, long)]
output: PathBuf,
#[arg(long, allow_hyphen_values = true)]
bbox: Option<String>,
#[arg(long = "field", value_name = "KEY=COLUMN")]
field: Vec<String>,
#[arg(long = "ignore-number", value_name = "VALUE")]
ignore_number: Option<Vec<String>>,
#[arg(long, default_value_t = 200_000)]
batch_rows: usize,
#[arg(long)]
no_nice: bool,
#[arg(long = "ban-plus", num_args = 1..)]
ban_plus: Vec<PathBuf>,
}
fn find_col(names: &[String], cands: &[&str]) -> Option<String> {
let lower: HashMap<String, &String> = names.iter().map(|n| (n.to_lowercase(), n)).collect();
cands
.iter()
.find_map(|c| lower.get(*c).map(|s| (*s).clone()))
}
fn log(msg: &str) {
println!("[{}] {msg}", chrono::Local::now().format("%H:%M:%S"));
}
type Fields = HashMap<&'static str, Option<String>>;
fn resolve_fields(names: &[String], overrides: &HashMap<String, String>) -> Result<Fields> {
let lower: HashMap<String, &String> = names.iter().map(|n| (n.to_lowercase(), n)).collect();
let mut out = Fields::new();
for (key, cands) in ALIASES {
if let Some(want) = overrides.get(*key) {
let Some(col) = lower.get(&want.to_lowercase()) else {
bail!(
"--field {key}={want}: column not found (available: {})",
names.join(", ")
);
};
out.insert(key, Some((*col).clone()));
continue;
}
out.insert(
key,
cands
.iter()
.find_map(|c| lower.get(*c).map(|s| (*s).clone())),
);
}
Ok(out)
}
fn mapping_str(f: &Fields) -> String {
ALIASES
.iter()
.filter_map(|(k, _)| f[k].as_ref().map(|v| format!("{k}={v}")))
.collect::<Vec<_>>()
.join(", ")
}
fn clean(v: Option<&str>) -> String {
let s = v.unwrap_or("").trim();
match s.to_lowercase().as_str() {
"none" | "nan" | "null" => String::new(),
_ => s.to_string(),
}
}
type Row = (String, String, String, String, String);
fn make_row(rec: &[Option<&str>; 7], ignore: &HashSet<String>) -> Option<Row> {
let mut num = clean(rec[1]);
if let Some(stem) = num.strip_suffix(".0") {
if !stem.is_empty() && stem.chars().all(|c| c.is_ascii_digit()) {
num = stem.to_string();
}
}
if ignore.contains(&num) {
num.clear();
}
let suffix = clean(rec[2]);
let mut street = clean(rec[3]);
if street.is_empty() {
street = clean(rec[4]);
}
let postcode = clean(rec[5]);
let city = clean(rec[6]);
let full_num = if num.is_empty() {
String::new()
} else {
format!("{num} {suffix}").trim().to_string()
};
let mut label = clean(rec[0]);
if label.is_empty() {
let left = format!("{full_num} {street}").trim().to_string();
let right = format!("{postcode} {city}").trim().to_string();
label = [left, right]
.into_iter()
.filter(|p| !p.is_empty())
.collect::<Vec<_>>()
.join(", ");
}
if label.is_empty() {
return None;
}
Some((label, full_num, street, postcode, city))
}
fn fold_fuzzy(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
let folded = match c {
'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' | 'ă' | 'ą' => 'a',
'ç' | 'ć' | 'č' | 'ĉ' | 'ċ' => 'c',
'ď' | 'đ' => 'd',
'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e',
'ì' | 'í' | 'î' | 'ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' => 'i',
'ñ' | 'ń' | 'ņ' | 'ň' => 'n',
'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' | 'ŏ' | 'ő' => 'o',
'ř' | 'ŕ' => 'r',
'ś' | 'š' | 'ş' | 'ŝ' => 's',
'ť' | 'ţ' => 't',
'ù' | 'ú' | 'û' | 'ü' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' => 'u',
'ý' | 'ÿ' | 'ŷ' => 'y',
'ž' | 'ź' | 'ż' => 'z',
'æ' | 'Æ' => 'a',
'œ' | 'Œ' => 'o',
c if ('\u{0300}'..='\u{036f}').contains(&c) => continue,
c => c,
};
out.push(folded.to_ascii_lowercase());
}
out
}
fn ext_of(p: &Path) -> String {
p.extension()
.map(|e| e.to_string_lossy().to_lowercase())
.unwrap_or_default()
}
fn rglob(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
for e in std::fs::read_dir(dir)? {
let p = e?.path();
if p.is_dir() {
rglob(&p, out)?;
} else {
out.push(p);
}
}
Ok(())
}
fn discover(inputs: &[PathBuf]) -> Result<Vec<PathBuf>> {
let mut files = Vec::new();
for p in inputs {
if !p.exists() {
bail!("Input '{}' does not exist", p.display());
}
if p.is_dir() {
let mut all = Vec::new();
rglob(p, &mut all)?;
let mut sel: Vec<_> = all
.into_iter()
.filter(|f| {
SUPPORTED_EXT.contains(&ext_of(f).as_str())
&& !f
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_lowercase()
.starts_with("lien_")
})
.collect();
sel.sort();
files.extend(sel);
} else {
files.push(p.clone());
}
}
if files.is_empty() {
bail!("No supported address files found");
}
Ok(files)
}
struct Batch {
lon: Vec<f64>,
lat: Vec<f64>,
cols: Vec<Option<Vec<Option<String>>>>,
wkb: Option<Vec<Option<Vec<u8>>>>,
id_adr: Option<Vec<Option<String>>>,
idu: Option<Vec<Option<String>>>,
}
impl Batch {
fn len(&self) -> usize {
self.lon.len()
}
fn get(&self, k: usize, i: usize) -> Option<&str> {
self.cols[k].as_ref().and_then(|c| c[i].as_deref())
}
}
fn geoparquet_geom_column(path: &Path) -> Result<Option<String>> {
if ext_of(path) != "parquet" {
return Ok(None);
}
let b = ParquetRecordBatchReaderBuilder::try_new(File::open(path)?)?;
let Some(geo) = b.schema().metadata().get("geo") else {
return Ok(None);
};
let g: serde_json::Value = serde_json::from_str(geo)?;
let col = g
.get("primary_column")
.and_then(|v| v.as_str())
.unwrap_or("geometry")
.to_string();
let info = g
.get("columns")
.and_then(|c| c.get(&col))
.cloned()
.unwrap_or_default();
let enc = info
.get("encoding")
.and_then(|v| v.as_str())
.unwrap_or("WKB");
if !enc.eq_ignore_ascii_case("WKB") {
return Ok(None);
}
if let Some(crs) = info.get("crs").filter(|c| !c.is_null()) {
let id = crs.get("id").cloned().unwrap_or_default();
let code = match id.get("code") {
Some(serde_json::Value::String(s)) => s.clone(),
Some(v) if !v.is_null() => v.to_string(),
_ => String::new(),
};
let auth = id
.get("authority")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_uppercase();
if !((auth == "EPSG" && code == "4326")
|| (auth == "OGC" && code.eq_ignore_ascii_case("CRS84")))
{
return Ok(None);
}
}
Ok(Some(col))
}
fn wkb_is_polygon(b: &[u8]) -> bool {
if b.len() < 5 {
return false;
}
let le = b[0] == 1;
let raw_type = if le {
u32::from_le_bytes([b[1], b[2], b[3], b[4]])
} else {
u32::from_be_bytes([b[1], b[2], b[3], b[4]])
};
let base = (raw_type & 0xFFFF) % 1000;
base == 3 || base == 6
}
fn wkb_point(b: &[u8]) -> (f64, f64) {
fn parse_geom(b: &[u8], pos: &mut usize, sx: &mut f64, sy: &mut f64, cnt: &mut usize) -> bool {
if *pos + 5 > b.len() {
return false;
}
let le = b[*pos] == 1;
*pos += 1;
let rd32 = |s: &[u8]| {
let a = [s[0], s[1], s[2], s[3]];
if le {
u32::from_le_bytes(a)
} else {
u32::from_be_bytes(a)
}
};
let rd64 = |s: &[u8]| {
let a: [u8; 8] = s[..8].try_into().unwrap();
if le {
f64::from_le_bytes(a)
} else {
f64::from_be_bytes(a)
}
};
let raw_type = rd32(&b[*pos..*pos + 4]);
*pos += 4;
if raw_type & 0x2000_0000 != 0 {
if *pos + 4 > b.len() {
return false;
}
*pos += 4;
}
let has_ewkb_z = (raw_type & 0x8000_0000) != 0;
let has_ewkb_m = (raw_type & 0x4000_0000) != 0;
let iso = raw_type & 0xFFFF;
let base = iso % 1000;
let dims = 2
+ usize::from(has_ewkb_z || matches!(iso / 1000, 1 | 3))
+ usize::from(has_ewkb_m || matches!(iso / 1000, 2 | 3));
let stride = dims * 8;
let read_pts =
|pos: &mut usize, n: usize, sx: &mut f64, sy: &mut f64, cnt: &mut usize| -> bool {
let need = n.saturating_mul(stride);
if *pos + need > b.len() {
return false;
}
for _ in 0..n {
let x = rd64(&b[*pos..*pos + 8]);
let y = rd64(&b[*pos + 8..*pos + 16]);
if x.is_finite() && y.is_finite() {
*sx += x;
*sy += y;
*cnt += 1;
}
*pos += stride;
}
true
};
match base {
1 => read_pts(pos, 1, sx, sy, cnt),
2 => {
if *pos + 4 > b.len() {
return false;
}
let n = rd32(&b[*pos..*pos + 4]) as usize;
*pos += 4;
read_pts(pos, n, sx, sy, cnt)
}
3 => {
if *pos + 4 > b.len() {
return false;
}
let nr = rd32(&b[*pos..*pos + 4]) as usize;
*pos += 4;
for _ in 0..nr {
if *pos + 4 > b.len() {
return false;
}
let n = rd32(&b[*pos..*pos + 4]) as usize;
*pos += 4;
if !read_pts(pos, n, sx, sy, cnt) {
return false;
}
}
true
}
4..=7 => {
if *pos + 4 > b.len() {
return false;
}
let ng = rd32(&b[*pos..*pos + 4]) as usize;
*pos += 4;
for _ in 0..ng {
if !parse_geom(b, pos, sx, sy, cnt) {
return false;
}
}
true
}
_ => false,
}
}
let mut pos = 0;
let (mut sx, mut sy, mut cnt) = (0.0, 0.0, 0usize);
if parse_geom(b, &mut pos, &mut sx, &mut sy, &mut cnt) && cnt > 0 {
(sx / cnt as f64, sy / cnt as f64)
} else {
(f64::NAN, f64::NAN)
}
}
fn to_strings(a: &ArrayRef) -> Result<Vec<Option<String>>> {
let s = arrow::compute::cast(a, &DataType::Utf8)?;
let s = s
.as_any()
.downcast_ref::<StringArray>()
.ok_or_else(|| anyhow!("cast to string failed"))?;
Ok((0..s.len())
.map(|i| {
if s.is_null(i) {
None
} else {
Some(s.value(i).to_string())
}
})
.collect())
}
fn read_geoparquet(
path: &Path,
geom_col: &str,
overrides: &HashMap<String, String>,
batch_rows: usize,
sink: &mut dyn FnMut(Batch) -> Result<()>,
) -> Result<()> {
let b = ParquetRecordBatchReaderBuilder::try_new(File::open(path)?)?;
let names: Vec<String> = b
.schema()
.fields()
.iter()
.map(|f| f.name().clone())
.collect();
let fields = resolve_fields(&names, overrides)?;
let id_adr_col = find_col(
&names,
&[
"id_adr",
"cle_interop",
"cle_d_interoperabilite",
"identifiant_adresse",
"id",
],
);
let idu_col = find_col(&names, &["idu", "id_parc"]);
log(&format!(
" GeoParquet fast path ({} rows) | mapping: {}",
b.metadata().file_metadata().num_rows(),
mapping_str(&fields)
));
let mut wanted: HashSet<&str> = fields.values().flatten().map(|s| s.as_str()).collect();
wanted.insert(geom_col);
if let Some(c) = id_adr_col.as_deref() {
wanted.insert(c);
}
if let Some(c) = idu_col.as_deref() {
wanted.insert(c);
}
let sd = b.parquet_schema();
let roots: Vec<usize> = (0..sd.root_schema().get_fields().len())
.filter(|&i| wanted.contains(sd.root_schema().get_fields()[i].name()))
.collect();
let mask = ProjectionMask::roots(sd, roots);
let reader = b
.with_projection(mask)
.with_batch_size(batch_rows)
.build()?;
for rb in reader {
let rb = rb?;
let n = rb.num_rows();
let g = rb
.column_by_name(geom_col)
.ok_or_else(|| anyhow!("geometry column missing"))?;
type GeomPointPoly = ((f64, f64), Option<Vec<u8>>);
type GeomExtract = ((Vec<f64>, Vec<f64>), Vec<Option<Vec<u8>>>);
let extract_wkb = |v: &[u8]| (wkb_point(v), wkb_is_polygon(v).then(|| v.to_vec()));
let ((lon, lat), wkb): GeomExtract =
if let Some(a) = g.as_any().downcast_ref::<BinaryArray>() {
let pairs: Vec<GeomPointPoly> = (0..a.len())
.into_par_iter()
.map(|i| {
if a.is_null(i) {
((f64::NAN, f64::NAN), None)
} else {
extract_wkb(a.value(i))
}
})
.collect();
pairs.into_iter().unzip()
} else if let Some(a) = g.as_any().downcast_ref::<LargeBinaryArray>() {
let pairs: Vec<GeomPointPoly> = (0..a.len())
.into_par_iter()
.map(|i| {
if a.is_null(i) {
((f64::NAN, f64::NAN), None)
} else {
extract_wkb(a.value(i))
}
})
.collect();
pairs.into_iter().unzip()
} else {
let c = arrow::compute::cast(g, &DataType::Binary)?;
let a = c.as_any().downcast_ref::<BinaryArray>().unwrap();
let pairs: Vec<GeomPointPoly> = (0..a.len())
.into_par_iter()
.map(|i| {
if a.is_null(i) {
((f64::NAN, f64::NAN), None)
} else {
extract_wkb(a.value(i))
}
})
.collect();
pairs.into_iter().unzip()
};
debug_assert_eq!(lon.len(), n);
let mut cols = Vec::with_capacity(KEYS.len());
for k in KEYS {
cols.push(match &fields[k] {
Some(c) => Some(to_strings(rb.column_by_name(c).unwrap())?),
None => None,
});
}
let id_adr = match &id_adr_col {
Some(c) => Some(to_strings(rb.column_by_name(c).unwrap())?),
None => None,
};
let idu = match &idu_col {
Some(c) => Some(to_strings(rb.column_by_name(c).unwrap())?),
None => None,
};
sink(Batch {
lon,
lat,
cols,
wkb: Some(wkb),
id_adr,
idu,
})?;
}
Ok(())
}
fn parse_f(s: Option<&str>) -> f64 {
s.and_then(|v| v.trim().parse::<f64>().ok())
.unwrap_or(f64::NAN)
}
fn read_csv(
path: &Path,
overrides: &HashMap<String, String>,
batch_rows: usize,
sink: &mut dyn FnMut(Batch) -> Result<()>,
) -> Result<()> {
let mut head_str = String::new();
std::io::BufRead::read_line(
&mut std::io::BufReader::new(File::open(path)?),
&mut head_str,
)?;
let head = head_str.as_bytes();
let delim = b",;\t|"
.iter()
.copied()
.max_by_key(|d| head.iter().filter(|c| *c == d).count())
.unwrap();
let mut rdr = csv::ReaderBuilder::new()
.delimiter(delim)
.flexible(true)
.from_path(path)?;
let names: Vec<String> = rdr.headers()?.iter().map(|s| s.to_string()).collect();
let fields = resolve_fields(&names, overrides)?;
log(&format!(
" CSV layer '{}' | mapping: {}",
path.display(),
mapping_str(&fields)
));
let idx = |k: &str| {
fields[k]
.as_ref()
.and_then(|c| names.iter().position(|n| n == c))
};
let (ilon, ilat) = (idx("lon"), idx("lat"));
if ilon.is_none() || ilat.is_none() {
bail!(
"CSV '{}': no lon/lat columns found (use --field lon=... --field lat=...)",
path.display()
);
}
let kidx: Vec<Option<usize>> = KEYS.iter().map(|k| idx(k)).collect();
let i_id_adr = find_col(
&names,
&[
"id_adr",
"cle_interop",
"cle_d_interoperabilite",
"identifiant_adresse",
"id",
],
)
.and_then(|c| names.iter().position(|n| n == &c));
let i_idu =
find_col(&names, &["idu", "id_parc"]).and_then(|c| names.iter().position(|n| n == &c));
let new_batch = || Batch {
lon: Vec::new(),
lat: Vec::new(),
cols: kidx.iter().map(|i| i.map(|_| Vec::new())).collect(),
wkb: None,
id_adr: i_id_adr.map(|_| Vec::new()),
idu: i_idu.map(|_| Vec::new()),
};
let mut b = new_batch();
for rec in rdr.records() {
let rec = rec?;
b.lon.push(parse_f(rec.get(ilon.unwrap())));
b.lat.push(parse_f(rec.get(ilat.unwrap())));
for (c, i) in b.cols.iter_mut().zip(&kidx) {
if let (Some(c), Some(i)) = (c, i) {
c.push(rec.get(*i).filter(|s| !s.is_empty()).map(|s| s.to_string()));
}
}
if let (Some(v), Some(i)) = (&mut b.id_adr, i_id_adr) {
v.push(rec.get(i).filter(|s| !s.is_empty()).map(|s| s.to_string()));
}
if let (Some(v), Some(i)) = (&mut b.idu, i_idu) {
v.push(rec.get(i).filter(|s| !s.is_empty()).map(|s| s.to_string()));
}
if b.len() >= batch_rows {
sink(std::mem::replace(&mut b, new_batch()))?;
}
}
if b.len() > 0 {
sink(b)?;
}
Ok(())
}
fn coords_mean(v: &serde_json::Value, acc: &mut (f64, f64, usize)) {
if let Some(a) = v.as_array() {
if a.len() >= 2 && a[0].is_number() && a[1].is_number() {
acc.0 += a[0].as_f64().unwrap();
acc.1 += a[1].as_f64().unwrap();
acc.2 += 1;
} else {
a.iter().for_each(|c| coords_mean(c, acc));
}
}
}
fn value_str(v: &serde_json::Value) -> Option<String> {
match v {
serde_json::Value::Null => None,
serde_json::Value::String(s) => Some(s.clone()),
o => Some(o.to_string()),
}
}
fn read_geojson(
path: &Path,
overrides: &HashMap<String, String>,
batch_rows: usize,
sink: &mut dyn FnMut(Batch) -> Result<()>,
) -> Result<()> {
let root: serde_json::Value =
serde_json::from_reader(std::io::BufReader::new(File::open(path)?))
.with_context(|| format!("parsing GeoJSON '{}'", path.display()))?;
let feats = root
.get("features")
.and_then(|f| f.as_array())
.ok_or_else(|| anyhow!("not a FeatureCollection"))?;
let mut names: Vec<String> = Vec::new();
let mut seen = HashSet::new();
for f in feats.iter().take(1000) {
if let Some(p) = f.get("properties").and_then(|p| p.as_object()) {
for k in p.keys() {
if seen.insert(k.clone()) {
names.push(k.clone());
}
}
}
}
let fields = resolve_fields(&names, overrides)?;
log(&format!(
" GeoJSON '{}' ({} features) | mapping: {}",
path.display(),
feats.len(),
mapping_str(&fields)
));
for chunk in feats.chunks(batch_rows.max(1)) {
let mut b = Batch {
lon: Vec::new(),
lat: Vec::new(),
wkb: None,
id_adr: None,
idu: None,
cols: KEYS
.iter()
.map(|k| fields[k].as_ref().map(|_| Vec::new()))
.collect(),
};
for f in chunk {
let props = f.get("properties");
let prop = |c: &Option<String>| {
c.as_ref()
.and_then(|c| props.and_then(|p| p.get(c)))
.and_then(value_str)
};
let mut acc = (0.0, 0.0, 0usize);
if let Some(c) = f.get("geometry").and_then(|g| g.get("coordinates")) {
coords_mean(c, &mut acc);
}
let (x, y) = if acc.2 > 0 {
(acc.0 / acc.2 as f64, acc.1 / acc.2 as f64)
} else {
(
parse_f(prop(&fields["lon"]).as_deref()),
parse_f(prop(&fields["lat"]).as_deref()),
)
};
b.lon.push(x);
b.lat.push(y);
for (c, k) in b.cols.iter_mut().zip(KEYS) {
if let Some(c) = c {
c.push(prop(&fields[k]));
}
}
}
sink(b)?;
}
Ok(())
}
fn main() -> Result<()> {
let args = Args::parse();
if !args.no_nice {
#[cfg(unix)]
unsafe {
libc::nice(10);
}
}
let mut overrides = HashMap::new();
for kv in &args.field {
let (k, v) = kv.split_once('=').unwrap_or((kv, ""));
if !ALIASES.iter().any(|(a, _)| *a == k) || v.is_empty() {
bail!("Invalid --field '{kv}'");
}
overrides.insert(k.to_string(), v.to_string());
}
let mut ignore: HashSet<String> = match &args.ignore_number {
Some(v) => v.iter().cloned().collect(),
None => ["99999".to_string()].into(),
};
ignore.remove("");
let bbox = match &args.bbox {
Some(s) => {
let v: Vec<f64> = s
.split(',')
.map(|x| x.trim().parse::<f64>())
.collect::<Result<_, _>>()?;
if v.len() != 4 {
bail!("--bbox expects west,south,east,north");
}
Some(v)
}
None => None,
};
let files = discover(&args.input)?;
let out = &args.output;
if let Some(p) = out.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(p)?;
}
let tmp = PathBuf::from(format!("{}.tmp", out.display()));
if tmp.exists() {
std::fs::remove_file(&tmp)?;
}
let t0 = Instant::now();
let mut con = Connection::open(&tmp)?;
con.execute_batch(
"PRAGMA page_size = 4096;
PRAGMA journal_mode = OFF;
PRAGMA synchronous = OFF;
PRAGMA temp_store = MEMORY;
PRAGMA cache_size = -262144;
CREATE TABLE metadata (name TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE addresses (
id INTEGER PRIMARY KEY,
label TEXT NOT NULL,
housenumber TEXT NOT NULL DEFAULT '',
street TEXT NOT NULL DEFAULT '',
postcode TEXT NOT NULL DEFAULT '',
city TEXT NOT NULL DEFAULT '',
lon REAL NOT NULL,
lat REAL NOT NULL,
wkb BLOB
);",
)?;
let has_ban_plus = !args.ban_plus.is_empty();
let join_tmp = PathBuf::from(format!("{}.join_tmp", out.display()));
if join_tmp.exists() {
let _ = std::fs::remove_file(&join_tmp);
}
if has_ban_plus {
con.execute(
"ATTACH DATABASE ?1 AS join_db",
params![join_tmp.to_string_lossy().as_ref()],
)?;
con.execute_batch(
"PRAGMA join_db.journal_mode = OFF;
PRAGMA join_db.synchronous = OFF;
CREATE TABLE join_db.tmp_adr_key (id INTEGER PRIMARY KEY, id_adr TEXT NOT NULL);
CREATE TABLE join_db.tmp_parcel_wkb (idu TEXT PRIMARY KEY, wkb BLOB NOT NULL);
CREATE TABLE join_db.tmp_adr_parcel (id_adr TEXT NOT NULL, idu TEXT NOT NULL);",
)?;
}
let (mut total, mut scanned) = (0i64, 0usize);
let (mut w, mut s, mut e, mut n) = (
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
);
let ogr_chunk_size = rayon::current_num_threads().clamp(4, 16);
for chunk in files.chunks(ogr_chunk_size) {
let prepared: Vec<Result<(PathBuf, Option<PathBuf>)>> = chunk
.par_iter()
.enumerate()
.map(|(idx, f)| {
if geoparquet_geom_column(f)?.is_some()
|| matches!(ext_of(f).as_str(), "csv" | "geojson" | "json" | "pbf")
{
return Ok((f.clone(), None));
}
match ext_of(f).as_str() {
"fgb" | "shp" | "gpkg" => {
let tmp_pq = std::env::temp_dir().join(format!(
"build_geocoder_in_{}_{idx}.parquet",
std::process::id()
));
let status = std::process::Command::new("ogr2ogr")
.args(["-t_srs", "EPSG:4326", "-f", "Parquet"])
.arg(&tmp_pq)
.arg(f)
.status()
.with_context(|| {
format!(
"Failed to invoke `ogr2ogr` to reproject '{}' to EPSG:4326 GeoParquet",
f.display()
)
})?;
if !status.success() {
let _ = std::fs::remove_file(&tmp_pq);
bail!("ogr2ogr failed on '{}'", f.display());
}
Ok((f.clone(), Some(tmp_pq)))
}
other => bail!(
"'{}': unsupported format '{other}' (only EPSG:4326 GeoParquet, CSV and GeoJSON are read \
natively; convert with e.g. `ogr2ogr -t_srs EPSG:4326 -f Parquet out.parquet {}`)",
f.display(),
f.display()
),
}
})
.collect();
for item in prepared {
let (f, tmp_pq_opt) = item?;
log(&format!("Reading '{}'", f.display()));
let mut sink = |b: Batch| -> Result<()> {
scanned += b.len();
let tx = con.transaction()?;
{
let mut st =
tx.prepare_cached("INSERT INTO addresses VALUES (?,?,?,?,?,?,?,?,?)")?;
let mut st_adr_key = if has_ban_plus {
Some(tx.prepare_cached(
"INSERT OR IGNORE INTO join_db.tmp_adr_key VALUES (?,?)",
)?)
} else {
None
};
let mut st_parcel_wkb = if has_ban_plus {
Some(tx.prepare_cached(
"INSERT OR IGNORE INTO join_db.tmp_parcel_wkb VALUES (?,?)",
)?)
} else {
None
};
for i in 0..b.len() {
let (x, y) = (b.lon[i], b.lat[i]);
let mut ok =
x.is_finite() && y.is_finite() && x.abs() <= 180.0 && y.abs() <= 90.0;
if let Some(bb) = &bbox {
ok &= x >= bb[0] && x <= bb[2] && y >= bb[1] && y <= bb[3];
}
if !ok {
continue;
}
(w, e, s, n) = (w.min(x), e.max(x), s.min(y), n.max(y));
let rec: [Option<&str>; 7] = std::array::from_fn(|k| b.get(k, i));
let Some(r) = make_row(&rec, &ignore) else {
continue;
};
total += 1;
let wkb_blob = b.wkb.as_ref().and_then(|v| v[i].as_deref());
st.execute(params![total, r.0, r.1, r.2, r.3, r.4, x, y, wkb_blob])?;
if has_ban_plus {
if let (Some(blob), Some(idu)) =
(wkb_blob, b.idu.as_ref().and_then(|v| v[i].as_deref()))
{
if let Some(st_p) = &mut st_parcel_wkb {
st_p.execute(params![idu, blob])?;
}
} else if let Some(id_adr) =
b.id_adr.as_ref().and_then(|v| v[i].as_deref())
{
if let Some(st_a) = &mut st_adr_key {
st_a.execute(params![total, id_adr])?;
}
}
}
}
}
tx.commit()?;
let dt = t0.elapsed().as_secs_f64().max(1e-6);
print!(
"\r {scanned} scanned -> {total} addresses ({:.0}/s)",
total as f64 / dt
);
std::io::stdout().flush().ok();
Ok(())
};
if let Some(tmp_pq) = tmp_pq_opt {
let gc = geoparquet_geom_column(&tmp_pq)?.ok_or_else(|| {
anyhow!(
"ogr2ogr output '{}' has no GeoParquet geometry",
tmp_pq.display()
)
})?;
let res = read_geoparquet(&tmp_pq, &gc, &overrides, args.batch_rows, &mut sink);
let _ = std::fs::remove_file(&tmp_pq);
res?;
} else if let Some(gc) = geoparquet_geom_column(&f)? {
read_geoparquet(&f, &gc, &overrides, args.batch_rows, &mut sink)?;
} else {
match ext_of(&f).as_str() {
"csv" => read_csv(&f, &overrides, args.batch_rows, &mut sink)?,
"geojson" | "json" => read_geojson(&f, &overrides, args.batch_rows, &mut sink)?,
"pbf" => {
read_osm_pbf_batches(&f, &bbox, &overrides, args.batch_rows, &mut sink)?
}
_ => unreachable!(),
}
}
println!();
}
}
if total == 0 {
drop(con);
let _ = std::fs::remove_file(&tmp);
let _ = std::fs::remove_file(&join_tmp);
bail!("No valid addresses found (check inputs / --bbox / --field)");
}
if has_ban_plus {
apply_ban_plus(&mut con, &args.ban_plus, &join_tmp, args.batch_rows)?;
}
log("Building FTS5 full-text index (accent-insensitive)…");
con.execute_batch(
"CREATE VIRTUAL TABLE addresses_fts USING fts5(
label, content='addresses', content_rowid='id',
tokenize='unicode61 remove_diacritics 2'
);
INSERT INTO addresses_fts(addresses_fts) VALUES('rebuild');
INSERT INTO addresses_fts(addresses_fts) VALUES('optimize');",
)?;
log("Building FTS5 trigram fuzzy index (accent-folded labels)…");
con.create_scalar_function(
"fold_fuzzy",
1,
FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
|ctx| {
let s = ctx.get::<String>(0)?;
Ok(fold_fuzzy(&s))
},
)?;
con.execute_batch(
"CREATE VIRTUAL TABLE addresses_trgm USING fts5(label, content='', tokenize='trigram');
INSERT INTO addresses_trgm(rowid,label) SELECT id, fold_fuzzy(label) FROM addresses;
INSERT INTO addresses_trgm(addresses_trgm) VALUES('optimize');",
)?;
log("Building R*Tree spatial index…");
con.execute_batch(
"CREATE VIRTUAL TABLE addresses_rtree USING rtree(id, min_lon, max_lon, min_lat, max_lat);
INSERT INTO addresses_rtree SELECT id, lon, lon, lat, lat FROM addresses;",
)?;
let sources = files
.iter()
.map(|f| {
f.file_name()
.unwrap_or_default()
.to_string_lossy()
.into_owned()
})
.collect::<Vec<_>>()
.join(";");
let meta = [
("format", "cesium-geocoder".to_string()),
("version", "1.0".to_string()),
("count", total.to_string()),
("bounds", format!("{w:.7},{s:.7},{e:.7},{n:.7}")),
("sources", sources),
(
"created",
chrono::Local::now().format("%Y-%m-%dT%H:%M:%S").to_string(),
),
];
for (k, v) in &meta {
con.execute("INSERT INTO metadata VALUES (?, ?)", params![k, v])?;
}
con.query_row("PRAGMA journal_mode = DELETE", [], |_| Ok(()))?;
drop(con);
std::fs::rename(&tmp, out)?;
let size = std::fs::metadata(out)?.len() as f64 / 1048576.0;
log(&format!(
"Done: {total} addresses -> '{}' ({size:.1} MiB) in {:.1} s",
out.display(),
t0.elapsed().as_secs_f64()
));
log(&format!(
"Use it with: cesium-viewer <terrain> --geocoder {}",
out.display()
));
Ok(())
}
fn discover_ban_plus_links(inputs: &[PathBuf]) -> Result<Vec<PathBuf>> {
let mut files = Vec::new();
for p in inputs {
if !p.exists() {
bail!("--ban-plus '{}' does not exist", p.display());
}
if p.is_dir() {
let mut all = Vec::new();
rglob(p, &mut all)?;
let mut sel: Vec<_> = all
.into_iter()
.filter(|f| {
let name = f
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_lowercase();
name.starts_with("lien_adresse-parcelle")
&& matches!(
ext_of(f).as_str(),
"shp" | "parquet" | "csv" | "fgb" | "gpkg"
)
})
.collect();
sel.sort();
files.extend(sel);
} else {
files.push(p.clone());
}
}
Ok(files)
}
fn apply_ban_plus(
con: &mut Connection,
inputs: &[PathBuf],
join_tmp: &Path,
batch_rows: usize,
) -> Result<()> {
let link_files = discover_ban_plus_links(inputs)?;
if link_files.is_empty() {
log("Warning: --ban-plus found no Lien_Adresse-Parcelle files; skipping parcel join.");
con.execute_batch("DETACH DATABASE join_db;")?;
let _ = std::fs::remove_file(join_tmp);
return Ok(());
}
log(&format!(
"Joining BAN-PLUS Adresse<->Parcelle links ({} files)…",
link_files.len()
));
let prepared: Vec<Result<(PathBuf, PathBuf, bool)>> = link_files
.par_iter()
.enumerate()
.map(|(idx, f)| {
let ext = ext_of(f);
if ext == "csv" || ext == "parquet" {
Ok((f.clone(), f.clone(), false))
} else {
let tmp_pq = std::env::temp_dir().join(format!(
"ban_plus_link_{}_{idx}.parquet",
std::process::id()
));
let status = std::process::Command::new("ogr2ogr")
.args(["-f", "Parquet", "-select", "ID_ADR,IDU"])
.arg(&tmp_pq)
.arg(f)
.status()
.with_context(|| format!("Failed to invoke ogr2ogr on '{}'", f.display()))?;
if !status.success() {
let _ = std::fs::remove_file(&tmp_pq);
bail!("ogr2ogr failed on '{}'", f.display());
}
Ok((f.clone(), tmp_pq, true))
}
})
.collect();
let mut link_count = 0usize;
for item in prepared {
let (orig, pq_path, cleanup) = item?;
let ext = ext_of(&orig);
let mut insert_pair = |pairs: &[(String, String)]| -> Result<()> {
let tx = con.transaction()?;
{
let mut st =
tx.prepare_cached("INSERT INTO join_db.tmp_adr_parcel VALUES (?,?)")?;
for (id_adr, idu) in pairs {
st.execute(params![id_adr, idu])?;
}
}
tx.commit()?;
link_count += pairs.len();
Ok(())
};
if ext == "csv" {
let mut rdr = csv::ReaderBuilder::new().flexible(true).from_path(&orig)?;
let names: Vec<String> = rdr.headers()?.iter().map(|s| s.to_string()).collect();
let i_adr = find_col(&names, &["id_adr", "cle_interop"])
.and_then(|c| names.iter().position(|n| n == &c))
.ok_or_else(|| anyhow!("Missing ID_ADR column in '{}'", orig.display()))?;
let i_idu = find_col(&names, &["idu", "id_parc"])
.and_then(|c| names.iter().position(|n| n == &c))
.ok_or_else(|| anyhow!("Missing IDU column in '{}'", orig.display()))?;
let mut buf = Vec::with_capacity(batch_rows.min(50_000));
for rec in rdr.records() {
let rec = rec?;
if let (Some(a), Some(u)) = (
rec.get(i_adr).filter(|s| !s.is_empty()),
rec.get(i_idu).filter(|s| !s.is_empty()),
) {
buf.push((a.to_string(), u.to_string()));
if buf.len() >= 50_000 {
insert_pair(&buf)?;
buf.clear();
}
}
}
if !buf.is_empty() {
insert_pair(&buf)?;
}
} else {
let b = ParquetRecordBatchReaderBuilder::try_new(File::open(&pq_path)?)?;
let names: Vec<String> = b
.schema()
.fields()
.iter()
.map(|fld| fld.name().clone())
.collect();
let c_adr = find_col(&names, &["id_adr", "cle_interop"])
.ok_or_else(|| anyhow!("Missing ID_ADR column in '{}'", orig.display()))?;
let c_idu = find_col(&names, &["idu", "id_parc"])
.ok_or_else(|| anyhow!("Missing IDU column in '{}'", orig.display()))?;
let reader = b.with_batch_size(batch_rows).build()?;
for rb in reader {
let rb = rb?;
let adrs = to_strings(rb.column_by_name(&c_adr).unwrap())?;
let idus = to_strings(rb.column_by_name(&c_idu).unwrap())?;
let pairs: Vec<(String, String)> = adrs
.into_iter()
.zip(idus)
.filter_map(|(a, u)| match (a, u) {
(Some(a), Some(u)) if !a.is_empty() && !u.is_empty() => Some((a, u)),
_ => None,
})
.collect();
if !pairs.is_empty() {
insert_pair(&pairs)?;
}
}
if cleanup {
let _ = std::fs::remove_file(&pq_path);
}
}
}
log(&format!(
"Loaded {link_count} Adresse<->Parcelle links; attaching polygons…"
));
con.execute_batch(
"CREATE INDEX join_db.idx_tmp_adr_parcel ON tmp_adr_parcel(id_adr);
UPDATE main.addresses AS a
SET wkb = p.wkb
FROM join_db.tmp_adr_key k
JOIN join_db.tmp_adr_parcel l ON l.id_adr = k.id_adr
JOIN join_db.tmp_parcel_wkb p ON p.idu = l.idu
WHERE a.id = k.id AND a.wkb IS NULL;",
)?;
let updated = con.changes();
con.execute_batch("DETACH DATABASE join_db;")?;
let _ = std::fs::remove_file(join_tmp);
log(&format!("Attached parcel polygons to {updated} addresses."));
Ok(())
}
fn encode_polygon_wkb(pts: &[[f64; 2]]) -> Vec<u8> {
let mut out = Vec::with_capacity(13 + pts.len() * 16);
out.push(1u8); out.extend_from_slice(&3u32.to_le_bytes()); out.extend_from_slice(&1u32.to_le_bytes()); out.extend_from_slice(&(pts.len() as u32).to_le_bytes());
for &[x, y] in pts {
out.extend_from_slice(&x.to_le_bytes());
out.extend_from_slice(&y.to_le_bytes());
}
out
}
fn read_osm_pbf_batches(
path: &Path,
bbox: &Option<Vec<f64>>,
overrides: &HashMap<String, String>,
batch_rows: usize,
sink: &mut dyn FnMut(Batch) -> Result<()>,
) -> Result<()> {
let osm_bb = bbox.as_ref().map(|b| cesium_osm::OsmBbox {
west: b[0],
south: b[1],
east: b[2],
north: b[3],
});
let osm_keys: Vec<String> = [
"name",
"amenity",
"shop",
"tourism",
"leisure",
"railway",
"addr:housenumber",
"addr:street",
"addr:place",
"addr:postcode",
"addr:city",
]
.into_iter()
.map(String::from)
.collect();
let fields = resolve_fields(&osm_keys, overrides)?;
let mut total_feats = 0usize;
log(&format!(
" OSM PBF '{}' | mapping: {}",
path.display(),
mapping_str(&fields)
));
cesium_osm::read_osm_pbf_batched(
path,
&cesium_osm::OsmTagFilter::geocoder_poi(),
osm_bb,
batch_rows.max(1),
|chunk| {
total_feats += chunk.len();
let mut b = Batch {
lon: Vec::with_capacity(chunk.len()),
lat: Vec::with_capacity(chunk.len()),
cols: KEYS
.iter()
.map(|k| fields[k].as_ref().map(|_| Vec::with_capacity(chunk.len())))
.collect(),
wkb: Some(Vec::with_capacity(chunk.len())),
id_adr: None,
idu: None,
};
for f in &chunk {
let (lon, lat, poly_wkb) = match &f.geom {
cesium_osm::OsmGeom::Point([x, y]) => (*x, *y, None),
cesium_osm::OsmGeom::Line(pts) if !pts.is_empty() => {
let (mut sx, mut sy) = (0.0, 0.0);
for [x, y] in pts {
sx += *x;
sy += *y;
}
(sx / pts.len() as f64, sy / pts.len() as f64, None)
}
cesium_osm::OsmGeom::Polygon(pts) if pts.len() >= 4 => {
let n = pts.len() - 1;
let (mut sx, mut sy) = (0.0, 0.0);
for [x, y] in &pts[..n] {
sx += *x;
sy += *y;
}
(sx / n as f64, sy / n as f64, Some(encode_polygon_wkb(pts)))
}
cesium_osm::OsmGeom::MultiPolygon(polys) => {
let Some(outer) = polys
.first()
.and_then(|p| p.first())
.filter(|r| r.len() >= 4)
else {
continue;
};
let n = outer.len() - 1;
let (mut sx, mut sy) = (0.0, 0.0);
for [x, y] in &outer[..n] {
sx += *x;
sy += *y;
}
(
sx / n as f64,
sy / n as f64,
Some(encode_polygon_wkb(outer)),
)
}
_ => continue,
};
b.lon.push(lon);
b.lat.push(lat);
if let Some(ref mut w) = b.wkb {
w.push(poly_wkb);
}
for (c, k) in b.cols.iter_mut().zip(KEYS) {
if let Some(col_vec) = c {
let val = fields[k].as_ref().and_then(|key| {
f.attrs
.iter()
.find(|(ak, _)| ak == key)
.map(|(_, v)| v.clone())
});
col_vec.push(val);
}
}
}
if b.len() > 0 {
sink(b)?;
}
Ok(())
},
)?;
log(&format!(
" OSM PBF '{}' finished ({} features)",
path.display(),
total_feats
));
Ok(())
}