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

Modern-Apps.git / scripts / maps / wikidesc / src / join.rs

join.rs219 lines · 8.1 KiBRaw
1//! Joining OSM places to Wikipedia leads.
2//!
3//! Two inputs, each far too large to hold twice: the admin places from a `.pbf`, and the abstracts
4//! dump. The join is by article title, because an OSM place carries `wikipedia=en:Săcălaz` and the
5//! dump's `<title>` is that same string. No Wikidata round trip is involved.
6//!
7//! # Which way round the pass goes
8//!
9//! Titles wanted are collected first, then the dump is streamed once and matched against them.
10//! The other order — index the dump, then walk the places — would hold every English lead in
11//! memory, which is the whole 6 GB file. This way the resident set is one string per admin place
12//! with a `wikipedia` tag, of order 10^5-10^6, and the dump is never held at all.
13//!
14//! One title can be wanted by several ids: a city mapped as both a node and a relation is two OSM
15//! elements and one article. [`Wanted`] therefore maps a title to *all* the ids that asked for it,
16//! and [`Archive`](crate::Archive) stores the text once regardless, because its index is
17//! id-to-offset.
18
19use std::collections::HashMap;
20
21use crate::abstracts::{english_title, Abstract};
22use crate::{clean, Builder};
23
24/// The titles the places want, and which OSM ids each belongs to.
25#[derive(Default)]
26pub struct Wanted {
27 by_title: HashMap<String, Vec<u64>>,
28}
29
30impl Wanted {
31 pub fn new() -> Self {
32 Self::default()
33 }
34
35 /// Record that `osm_id` wants the article its `wikipedia` tag names.
36 ///
37 /// A tag naming a non-English article, or no article, is ignored: this archive carries English
38 /// leads and a German title would never match anything in the dump.
39 pub fn add(&mut self, osm_id: u64, wikipedia_tag: &str) {
40 let Some(title) = english_title(wikipedia_tag) else { return };
41 if title.is_empty() {
42 return;
43 }
44 self.by_title.entry(title.to_string()).or_default().push(osm_id);
45 }
46
47 /// Distinct titles wanted.
48 pub fn titles(&self) -> usize {
49 self.by_title.len()
50 }
51
52 /// Places wanting an article, counting an article wanted twice twice.
53 pub fn places(&self) -> usize {
54 self.by_title.values().map(Vec::len).sum()
55 }
56
57 pub fn is_empty(&self) -> bool {
58 self.by_title.is_empty()
59 }
60}
61
62/// What a join pass did, for the build log.
63#[derive(Debug, Default, PartialEq, Eq)]
64pub struct Stats {
65 /// Articles in the dump that some place wanted.
66 pub matched: usize,
67 /// Places given a description.
68 pub described: usize,
69 /// Matched articles whose lead was empty, or became empty once cleaned.
70 pub empty: usize,
71 /// Titles nobody in the dump had. Usually a redirect, or a place tagged with an article that
72 /// has since been renamed.
73 pub missing: usize,
74}
75
76/// Stream `dump`, filling a [`Builder`] with the leads the places asked for.
77///
78/// Every id wanting a matched title gets the text; the archive stores one copy.
79pub fn join(wanted: &Wanted, dump: impl Iterator<Item = Abstract>) -> (Builder, Stats) {
80 let mut builder = Builder::new();
81 let mut stats = Stats::default();
82 let mut seen: HashMap<&str, ()> = HashMap::new();
83 for article in dump {
84 let Some(ids) = wanted.by_title.get(article.title.as_str()) else { continue };
85 // A dump can repeat a title; the first wins, as it does in the archive itself.
86 let key = wanted.by_title.get_key_value(article.title.as_str()).unwrap().0.as_str();
87 if seen.insert(key, ()).is_some() {
88 continue;
89 }
90 stats.matched += 1;
91 let text = clean(&article.text);
92 if text.is_empty() {
93 stats.empty += 1;
94 continue;
95 }
96 for &id in ids {
97 builder.add(id, &text);
98 stats.described += 1;
99 }
100 }
101 stats.missing = wanted.titles() - stats.matched;
102 (builder, stats)
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108 use crate::Archive;
109
110 fn article(title: &str, text: &str) -> Abstract {
111 Abstract { title: title.to_string(), text: text.to_string() }
112 }
113
114 fn built(wanted: &Wanted, dump: Vec<Abstract>) -> (Archive, Stats) {
115 let (builder, stats) = join(wanted, dump.into_iter());
116 let mut bytes = Vec::new();
117 builder.write(&mut bytes).expect("write");
118 (Archive::parse(&bytes).expect("parse"), stats)
119 }
120
121 #[test]
122 fn a_place_gets_the_lead_of_the_article_it_names() {
123 let mut wanted = Wanted::new();
124 wanted.add(42, "en:Săcălaz");
125 let (archive, stats) = built(
126 &wanted,
127 vec![
128 article("Paris", "Paris is in France."),
129 article("Săcălaz", "Săcălaz is a [commune](https://x) in Timiș County."),
130 ],
131 );
132 assert_eq!(archive.get(42), Some("Săcălaz is a commune in Timiș County."));
133 assert_eq!(stats.matched, 1);
134 assert_eq!(stats.described, 1);
135 assert_eq!(stats.missing, 0, "the one title wanted was found");
136 }
137
138 /// A city mapped as both a node and a relation is two ids and one article.
139 #[test]
140 fn several_places_can_share_one_article() {
141 let mut wanted = Wanted::new();
142 wanted.add(1, "en:Paris");
143 wanted.add(2, "en:Paris");
144 let (archive, stats) = built(&wanted, vec![article("Paris", "Paris is in France.")]);
145 assert_eq!(archive.get(1), Some("Paris is in France."));
146 assert_eq!(archive.get(2), Some("Paris is in France."));
147 assert_eq!(stats.matched, 1, "one article");
148 assert_eq!(stats.described, 2, "two places");
149 assert_eq!(archive.len(), 2);
150 }
151
152 #[test]
153 fn a_title_nobody_has_is_counted_as_missing() {
154 let mut wanted = Wanted::new();
155 wanted.add(1, "en:Renamed Place");
156 let (archive, stats) = built(&wanted, vec![article("Paris", "Paris is in France.")]);
157 assert!(archive.is_empty());
158 assert_eq!(stats.matched, 0);
159 assert_eq!(stats.missing, 1);
160 }
161
162 /// A stub matches but has nothing to say. Better no entry than an empty one - the app cannot
163 /// tell an empty description from a missing one.
164 #[test]
165 fn a_matched_article_with_an_empty_lead_is_not_stored() {
166 let mut wanted = Wanted::new();
167 wanted.add(1, "en:Stub");
168 wanted.add(2, "en:Real");
169 let (archive, stats) =
170 built(&wanted, vec![article("Stub", ""), article("Real", "Something to say.")]);
171 assert_eq!(archive.get(1), None);
172 assert_eq!(archive.get(2), Some("Something to say."));
173 assert_eq!(stats.matched, 2);
174 assert_eq!(stats.empty, 1);
175 assert_eq!(stats.described, 1);
176 }
177
178 /// A lead that is nothing but a parenthesised name list cleans away to nothing, and must be
179 /// treated the same as a stub rather than stored as an empty string.
180 #[test]
181 fn a_lead_that_cleans_away_to_nothing_counts_as_empty() {
182 let mut wanted = Wanted::new();
183 wanted.add(1, "en:Names");
184 let (archive, stats) = built(&wanted, vec![article("Names", "(German: X; Hungarian: Y)")]);
185 assert_eq!(archive.get(1), None);
186 assert_eq!(stats.empty, 1);
187 }
188
189 #[test]
190 fn a_non_english_tag_is_ignored() {
191 let mut wanted = Wanted::new();
192 wanted.add(1, "de:Paris");
193 wanted.add(2, "");
194 assert!(wanted.is_empty(), "neither names an English article");
195 assert_eq!(wanted.titles(), 0);
196 }
197
198 /// Dumps do contain repeated titles. The first wins, matching the archive's own rule, so a
199 /// build does not depend on where in a 6 GB file a duplicate sits.
200 #[test]
201 fn a_repeated_title_in_the_dump_takes_the_first() {
202 let mut wanted = Wanted::new();
203 wanted.add(1, "en:Paris");
204 let (archive, stats) =
205 built(&wanted, vec![article("Paris", "First lead."), article("Paris", "Second lead.")]);
206 assert_eq!(archive.get(1), Some("First lead."));
207 assert_eq!(stats.matched, 1);
208 }
209
210 #[test]
211 fn counts_distinguish_titles_from_places() {
212 let mut wanted = Wanted::new();
213 wanted.add(1, "en:Paris");
214 wanted.add(2, "en:Paris");
215 wanted.add(3, "en:Berlin");
216 assert_eq!(wanted.titles(), 2);
217 assert_eq!(wanted.places(), 3);
218 }
219}