Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / wikidesc / src / abstracts.rs
abstracts.rs215 lines · 8.5 KiBRaw
| 1 | //! Streaming reader for the English Wikipedia abstracts dump. |
| 2 | //! |
| 3 | //! `enwiki-latest-abstract.xml` is the lead of every article, already extracted, in one file. That |
| 4 | //! is exactly what this archive needs, and it is why the generator reads a dump instead of calling |
| 5 | //! the API: the admin-place set is of order 10^5-10^6, and that many HTTP requests would need |
| 6 | //! caching, resumability and rate limiting, and would take hours. The dump is one download and one |
| 7 | //! sequential pass. |
| 8 | //! |
| 9 | //! The shape, repeated for every article: |
| 10 | //! |
| 11 | //! ```xml |
| 12 | //! <doc> |
| 13 | //! <title>Wikipedia: Săcălaz</title> |
| 14 | //! <url>https://en.wikipedia.org/wiki/S%C4%83c%C4%83laz</url> |
| 15 | //! <abstract>Săcălaz (formerly Săcalhaz; German: Sackelhausen) is a commune in Timiș County.</abstract> |
| 16 | //! <links>…</links> |
| 17 | //! </doc> |
| 18 | //! ``` |
| 19 | //! |
| 20 | //! Two things about the title matter. It is prefixed `Wikipedia: `, which is not part of the |
| 21 | //! article name and is stripped here. And it is the *display* title, which is what an OSM |
| 22 | //! `wikipedia=en:Săcălaz` tag holds after its language prefix — so the join is a string match and |
| 23 | //! needs no Wikidata round trip. |
| 24 | //! |
| 25 | //! # Why hand-rolled rather than an XML crate |
| 26 | //! |
| 27 | //! The file is ~6 GB and the structure is four fixed tags in a fixed order. A pull parser would be |
| 28 | //! correct and would also pay to validate a document nobody is going to hand-edit. This reads |
| 29 | //! line-oriented, holds one record at a time, and never allocates for the parts it discards |
| 30 | //! (`<url>`, `<links>`, and the per-link `<sublink>` blocks, which are the bulk of the file). |
| 31 | |
| 32 | use std::io::BufRead; |
| 33 | |
| 34 | /// One article's lead. |
| 35 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 36 | pub struct Abstract { |
| 37 | /// The article title, with the dump's `Wikipedia: ` prefix removed. |
| 38 | pub title: String, |
| 39 | /// The lead text, XML-unescaped. May be empty: many stubs have no abstract. |
| 40 | pub text: String, |
| 41 | } |
| 42 | |
| 43 | /// Yields one [`Abstract`] per `<doc>`, holding a single record in memory at a time. |
| 44 | pub struct Abstracts<R: BufRead> { |
| 45 | lines: std::io::Lines<R>, |
| 46 | } |
| 47 | |
| 48 | impl<R: BufRead> Abstracts<R> { |
| 49 | pub fn new(source: R) -> Self { |
| 50 | Abstracts { lines: source.lines() } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | impl<R: BufRead> Iterator for Abstracts<R> { |
| 55 | type Item = Abstract; |
| 56 | |
| 57 | fn next(&mut self) -> Option<Abstract> { |
| 58 | let mut title: Option<String> = None; |
| 59 | let mut text: Option<String> = None; |
| 60 | for line in self.lines.by_ref() { |
| 61 | // A read error mid-file ends the iteration rather than panicking: a partial archive |
| 62 | // built from a truncated download is recoverable, a crash three hours in is not. |
| 63 | let line = line.ok()?; |
| 64 | let line = line.trim(); |
| 65 | if let Some(raw) = tag_body(line, "title") { |
| 66 | title = Some(unescape(raw.strip_prefix("Wikipedia: ").unwrap_or(raw))); |
| 67 | } else if let Some(raw) = tag_body(line, "abstract") { |
| 68 | text = Some(unescape(raw)); |
| 69 | } else if line.starts_with("</doc>") { |
| 70 | // `<abstract/>` and a missing abstract both arrive as no text at all. |
| 71 | return Some(Abstract { |
| 72 | title: title.take()?, |
| 73 | text: text.take().unwrap_or_default(), |
| 74 | }); |
| 75 | } |
| 76 | } |
| 77 | None |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// The contents of `<tag>…</tag>` when `line` is exactly that, else `None`. |
| 82 | /// |
| 83 | /// Both tags must be on one line, which is how the dump is written. A `<tag/>` empty element is |
| 84 | /// not matched and so reads as absent, which is the right answer for an article with no abstract. |
| 85 | fn tag_body<'a>(line: &'a str, tag: &str) -> Option<&'a str> { |
| 86 | let open = format!("<{tag}>"); |
| 87 | let close = format!("</{tag}>"); |
| 88 | line.strip_prefix(&open)?.strip_suffix(&close) |
| 89 | } |
| 90 | |
| 91 | /// The five predefined XML entities. |
| 92 | /// |
| 93 | /// Numeric character references are left alone deliberately: they are rare in abstracts, and a |
| 94 | /// half-decoded `—` is more obviously wrong than a decoded one is right. |
| 95 | fn unescape(raw: &str) -> String { |
| 96 | if !raw.contains('&') { |
| 97 | return raw.to_string(); |
| 98 | } |
| 99 | raw.replace("<", "<") |
| 100 | .replace(">", ">") |
| 101 | .replace(""", "\"") |
| 102 | .replace("'", "'") |
| 103 | // Last, or an escaped ampersand would be decoded twice: `&lt;` is the text `<`. |
| 104 | .replace("&", "&") |
| 105 | } |
| 106 | |
| 107 | /// The article title an OSM `wikipedia` tag refers to, if it names an English article. |
| 108 | /// |
| 109 | /// The tag is `wikipedia=en:Săcălaz`. A bare value with no language prefix is treated as English, |
| 110 | /// which is what the older tagging convention meant. Any other language is `None`: this archive |
| 111 | /// carries English leads, and a German title would silently never match. |
| 112 | pub fn english_title(tag: &str) -> Option<&str> { |
| 113 | let tag = tag.trim(); |
| 114 | if tag.is_empty() { |
| 115 | return None; |
| 116 | } |
| 117 | match tag.split_once(':') { |
| 118 | Some(("en", title)) => Some(title.trim()), |
| 119 | // A colon inside a title with no language prefix, e.g. "Toronto: A City". |
| 120 | Some((prefix, _)) if prefix.len() == 2 || prefix.len() == 3 => None, |
| 121 | _ => Some(tag), |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | #[cfg(test)] |
| 126 | mod tests { |
| 127 | use super::*; |
| 128 | |
| 129 | fn parse(xml: &str) -> Vec<Abstract> { |
| 130 | Abstracts::new(std::io::BufReader::new(xml.as_bytes())).collect() |
| 131 | } |
| 132 | |
| 133 | #[test] |
| 134 | fn a_doc_yields_its_title_and_lead() { |
| 135 | let got = parse( |
| 136 | "<feed>\n<doc>\n<title>Wikipedia: Săcălaz</title>\n\ |
| 137 | <url>https://en.wikipedia.org/wiki/S%C4%83c%C4%83laz</url>\n\ |
| 138 | <abstract>Săcălaz is a commune in Timiș County, Romania.</abstract>\n\ |
| 139 | <links><sublink><anchor>Geography</anchor></sublink></links>\n</doc>\n</feed>", |
| 140 | ); |
| 141 | assert_eq!(got.len(), 1); |
| 142 | assert_eq!(got[0].title, "Săcălaz", "the `Wikipedia: ` prefix is not part of the title"); |
| 143 | assert_eq!(got[0].text, "Săcălaz is a commune in Timiș County, Romania."); |
| 144 | } |
| 145 | |
| 146 | #[test] |
| 147 | fn documents_are_streamed_one_after_another() { |
| 148 | let got = parse( |
| 149 | "<feed>\n\ |
| 150 | <doc>\n<title>Wikipedia: Paris</title>\n<abstract>Paris is in France.</abstract>\n</doc>\n\ |
| 151 | <doc>\n<title>Wikipedia: Berlin</title>\n<abstract>Berlin is in Germany.</abstract>\n</doc>\n\ |
| 152 | </feed>", |
| 153 | ); |
| 154 | assert_eq!(got.len(), 2); |
| 155 | assert_eq!(got[0].title, "Paris"); |
| 156 | assert_eq!(got[1].title, "Berlin"); |
| 157 | assert_eq!(got[1].text, "Berlin is in Germany."); |
| 158 | } |
| 159 | |
| 160 | /// Stubs are common and must not stop the pass or drop the title. |
| 161 | #[test] |
| 162 | fn an_article_with_no_abstract_yields_empty_text() { |
| 163 | let got = parse( |
| 164 | "<doc>\n<title>Wikipedia: Stub</title>\n<abstract/>\n</doc>\n\ |
| 165 | <doc>\n<title>Wikipedia: Other</title>\n</doc>", |
| 166 | ); |
| 167 | assert_eq!(got.len(), 2); |
| 168 | assert_eq!(got[0].text, ""); |
| 169 | assert_eq!(got[1].text, ""); |
| 170 | assert_eq!(got[1].title, "Other"); |
| 171 | } |
| 172 | |
| 173 | #[test] |
| 174 | fn xml_entities_are_decoded() { |
| 175 | let got = parse( |
| 176 | "<doc>\n<title>Wikipedia: A & B</title>\n\ |
| 177 | <abstract>"Quoted" <tagged> 'and' & more.</abstract>\n</doc>", |
| 178 | ); |
| 179 | assert_eq!(got[0].title, "A & B"); |
| 180 | assert_eq!(got[0].text, "\"Quoted\" <tagged> 'and' & more."); |
| 181 | } |
| 182 | |
| 183 | /// `&lt;` is the literal text `<`, not a nested escape. |
| 184 | #[test] |
| 185 | fn an_escaped_ampersand_is_decoded_once() { |
| 186 | let got = parse("<doc>\n<title>Wikipedia: T</title>\n<abstract>&lt;</abstract>\n</doc>"); |
| 187 | assert_eq!(got[0].text, "<"); |
| 188 | } |
| 189 | |
| 190 | /// A dump cut short leaves a `<doc>` with no `</doc>`, which must end the pass rather than |
| 191 | /// emit a half record. |
| 192 | #[test] |
| 193 | fn a_truncated_final_document_is_dropped() { |
| 194 | let got = parse( |
| 195 | "<doc>\n<title>Wikipedia: Complete</title>\n<abstract>All here.</abstract>\n</doc>\n\ |
| 196 | <doc>\n<title>Wikipedia: Cut</title>\n<abstract>Half a", |
| 197 | ); |
| 198 | assert_eq!(got.len(), 1); |
| 199 | assert_eq!(got[0].title, "Complete"); |
| 200 | } |
| 201 | |
| 202 | #[test] |
| 203 | fn the_join_key_comes_from_the_osm_wikipedia_tag() { |
| 204 | assert_eq!(english_title("en:Săcălaz"), Some("Săcălaz")); |
| 205 | assert_eq!(english_title(" en:Paris "), Some("Paris")); |
| 206 | // The older convention: no prefix meant English. |
| 207 | assert_eq!(english_title("Paris"), Some("Paris")); |
| 208 | // Another language cannot match an English dump, so it must not be guessed at. |
| 209 | assert_eq!(english_title("de:Paris"), None); |
| 210 | assert_eq!(english_title("ro:Săcălaz"), None); |
| 211 | assert_eq!(english_title(""), None); |
| 212 | // A colon that is punctuation rather than a language prefix. |
| 213 | assert_eq!(english_title("Toronto: A City"), Some("Toronto: A City")); |
| 214 | } |
| 215 | } |