Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / wikidesc / src / bin / wikidesc_build.rs

wikidesc_build.rs143 lines · 5.2 KiBRaw
1//! `wikidesc_build` — build the place-description archive.
2//!
3//! ```text
4//! wikidesc_build <out.wikidesc> --pbf <planet.osm.pbf> --abstracts <enwiki-latest-abstract.xml>
5//! ```
6//!
7//! Two sequential passes over two large files, holding neither.
8//!
9//! 1. Scan the `.pbf` for every element carrying an English `wikipedia` tag, recording the article
10//! title it wants against the element's tagged id. Resident set is one string per notable
11//! element, of order 10^6 — not the 80 GB the planet occupies on disk.
12//! 2. Stream the abstracts dump once, and for every article somebody asked for, clean the lead and
13//! record it.
14//!
15//! The dump is not indexed and the places are not re-walked: either would mean holding a whole
16//! input in memory. See `join` for why the pass goes in this direction.
17
18use std::fs::File;
19use std::io::{BufReader, BufWriter};
20use std::path::PathBuf;
21use std::process::ExitCode;
22
23use osm_ingest::osm::{self, Element};
24use osm_ingest::pbf;
25use wikidesc::{ids, Abstracts, Wanted};
26
27fn main() -> ExitCode {
28 match run() {
29 Ok(()) => ExitCode::SUCCESS,
30 Err(e) => {
31 eprintln!("wikidesc_build: {e}");
32 ExitCode::FAILURE
33 }
34 }
35}
36
37struct Args {
38 out: PathBuf,
39 pbf: PathBuf,
40 abstracts: PathBuf,
41}
42
43fn parse_args() -> Result<Args, String> {
44 let (mut out, mut pbf, mut abstracts) = (None, None, None);
45 let mut args = std::env::args().skip(1);
46 while let Some(arg) = args.next() {
47 match arg.as_str() {
48 "--pbf" => pbf = args.next().map(PathBuf::from),
49 "--abstracts" => abstracts = args.next().map(PathBuf::from),
50 other if other.starts_with("--") => return Err(format!("unknown flag {other}")),
51 other if out.is_none() => out = Some(PathBuf::from(other)),
52 other => return Err(format!("unexpected argument {other}")),
53 }
54 }
55 Ok(Args {
56 out: out.ok_or("usage: wikidesc_build <out.wikidesc> --pbf <x.osm.pbf> --abstracts <enwiki-latest-abstract.xml>")?,
57 pbf: pbf.ok_or("missing --pbf")?,
58 abstracts: abstracts.ok_or("missing --abstracts")?,
59 })
60}
61
62fn run() -> Result<(), String> {
63 let args = parse_args()?;
64
65 // Pass 1. Nodes, ways and relations alike: a landmark is a node in one place, a building
66 // outline in another and a multipolygon in a third, and which it is says nothing about
67 // whether it has an article.
68 let blobs = pbf::scan_blobs(&args.pbf).map_err(|e| e.to_string())?;
69 let want = pbf::KIND_NODES | pbf::KIND_WAYS | pbf::KIND_RELATIONS;
70 let (chunks, _kinds) = pbf::run_pass(
71 &args.pbf,
72 &blobs,
73 None,
74 want,
75 "Pass 1: elements with a wikipedia tag",
76 Vec::<(u64, String)>::new,
77 |found, block| {
78 let mut kinds = 0u8;
79 osm::visit_block(block, want, &mut kinds, &mut |element| {
80 // The tag IS the notability filter. Not a list of kinds: a mapper adds
81 // `wikipedia` when an article exists, which is the question being asked, and
82 // the list would never be finished.
83 let (id, tags) = match element {
84 Element::Node(n) => (ids::node(n.id), n.tags),
85 Element::Way(w) => (ids::way(w.id), w.tags),
86 Element::Relation(r) => (ids::relation(r.id), r.tags),
87 };
88 if let Some(tag) = tags.get_str("wikipedia") {
89 if id != ids::ID_NONE {
90 found.push((id, tag.to_string()));
91 }
92 }
93 Ok(())
94 })?;
95 Ok(kinds)
96 },
97 )
98 .map_err(|e| e.to_string())?;
99
100 let mut wanted = Wanted::new();
101 for chunk in chunks {
102 for (id, tag) in chunk {
103 wanted.add(id, &tag);
104 }
105 }
106 println!(
107 "wikidesc_build: {} element(s) want {} distinct English article(s)",
108 wanted.places(),
109 wanted.titles(),
110 );
111 if wanted.is_empty() {
112 return Err("no element carries an English wikipedia tag - wrong extract?".to_string());
113 }
114
115 // Pass 2.
116 let dump = File::open(&args.abstracts)
117 .map_err(|e| format!("{}: {e}", args.abstracts.display()))?;
118 // A big reader because this is one long sequential scan of several gigabytes.
119 let dump = BufReader::with_capacity(1 << 22, dump);
120 let (builder, stats) = wikidesc::join(&wanted, Abstracts::new(dump));
121 println!(
122 "wikidesc_build: matched {} article(s), described {} place(s), {} empty, {} missing",
123 stats.matched, stats.described, stats.empty, stats.missing,
124 );
125 println!(
126 "wikidesc_build: {} entry/entries, {} sharing text, {:.1} MB of text",
127 builder.len(),
128 builder.shared(),
129 builder.blob_len() as f64 / 1_048_576.0,
130 );
131
132 let file = File::create(&args.out).map_err(|e| format!("{}: {e}", args.out.display()))?;
133 let mut out = BufWriter::with_capacity(1 << 20, file);
134 builder.write(&mut out).map_err(|e| e.to_string())?;
135 drop(out);
136 let bytes = std::fs::metadata(&args.out).map(|m| m.len()).unwrap_or(0);
137 println!(
138 "wikidesc_build: wrote {} ({:.1} MB)",
139 args.out.display(),
140 bytes as f64 / 1_048_576.0,
141 );
142 Ok(())
143}