Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / wikidesc / src / clean.rs
clean.rs231 lines · 9.1 KiBRaw
| 1 | //! Turning a Wikipedia lead paragraph into one line of plain text. |
| 2 | //! |
| 3 | //! The lead of a geography article is written for a page with hyperlinks and footnotes, and most |
| 4 | //! of what makes it long is not information — it is the same place name repeated in other |
| 5 | //! languages, link markup around words that are already there, and reference markers. On a phone |
| 6 | //! sheet none of that survives contact with a reader, and in an archive shipped to every device it |
| 7 | //! is the difference between a download people accept and one they do not. |
| 8 | //! |
| 9 | //! The worked example this module is specified by: |
| 10 | //! |
| 11 | //! ```text |
| 12 | //! Săcălaz (formerly Săcalhaz; [German](…): Sackelhausen; [Banat Swabian](…): Sacklass;[\[3\]](…) |
| 13 | //! [Hungarian](…): Szakálháza) is a [commune](…) in [Timiș County](…), [Romania](…). It is |
| 14 | //! composed of three villages: Beregsău Mare, Beregsău Mic and Săcălaz (commune seat). |
| 15 | //! ``` |
| 16 | //! |
| 17 | //! becomes |
| 18 | //! |
| 19 | //! ```text |
| 20 | //! Săcălaz is a commune in Timiș County, Romania. It is composed of three villages: Beregsău Mare, |
| 21 | //! Beregsău Mic and Săcălaz. |
| 22 | //! ``` |
| 23 | //! |
| 24 | //! Note what happens to each construct: a link keeps its *text* and loses its target, because the |
| 25 | //! text is the sentence; a reference marker goes entirely; and a parenthesis goes entirely, |
| 26 | //! brackets and all. That last rule is the aggressive one and it is deliberate — see |
| 27 | //! [`strip_parentheticals`]. |
| 28 | |
| 29 | /// Reduce a lead paragraph to one line of plain prose. |
| 30 | pub fn clean(raw: &str) -> String { |
| 31 | let text = unwrap_links(raw); |
| 32 | let text = strip_parentheticals(&text); |
| 33 | tidy(&text) |
| 34 | } |
| 35 | |
| 36 | /// `[text](url)` becomes `text`; a reference marker becomes nothing. |
| 37 | /// |
| 38 | /// A reference is a link whose text is itself bracketed — `[\[3\]](…)` — which is what a footnote |
| 39 | /// looks like once the page is rendered to markdown. Recognising it by shape rather than by |
| 40 | /// number also catches `[\[note 1\]]` and `[\[a\]]`. |
| 41 | fn unwrap_links(raw: &str) -> String { |
| 42 | let mut out = String::with_capacity(raw.len()); |
| 43 | let bytes: Vec<char> = raw.chars().collect(); |
| 44 | let mut i = 0; |
| 45 | while i < bytes.len() { |
| 46 | if bytes[i] == '[' { |
| 47 | if let Some((text, next)) = read_link(&bytes, i) { |
| 48 | if !is_reference(&text) { |
| 49 | out.push_str(&text); |
| 50 | } |
| 51 | i = next; |
| 52 | continue; |
| 53 | } |
| 54 | } |
| 55 | out.push(bytes[i]); |
| 56 | i += 1; |
| 57 | } |
| 58 | out |
| 59 | } |
| 60 | |
| 61 | /// Read `[text](url)` starting at `open`, returning the text and the index just past the link. |
| 62 | /// |
| 63 | /// The label may contain balanced brackets — a reference marker is exactly that — so the scan |
| 64 | /// counts depth rather than stopping at the first `]`. |
| 65 | fn read_link(chars: &[char], open: usize) -> Option<(String, usize)> { |
| 66 | let mut depth = 0usize; |
| 67 | let mut close = None; |
| 68 | for (offset, &c) in chars.iter().enumerate().skip(open) { |
| 69 | match c { |
| 70 | '[' => depth += 1, |
| 71 | ']' => { |
| 72 | depth -= 1; |
| 73 | if depth == 0 { |
| 74 | close = Some(offset); |
| 75 | break; |
| 76 | } |
| 77 | } |
| 78 | _ => {} |
| 79 | } |
| 80 | } |
| 81 | let close = close?; |
| 82 | // A bracketed span is only a link if a parenthesised target follows immediately. |
| 83 | if chars.get(close + 1) != Some(&'(') { |
| 84 | return None; |
| 85 | } |
| 86 | let mut depth = 0usize; |
| 87 | for (offset, &c) in chars.iter().enumerate().skip(close + 1) { |
| 88 | match c { |
| 89 | '(' => depth += 1, |
| 90 | ')' => { |
| 91 | depth -= 1; |
| 92 | if depth == 0 { |
| 93 | let text: String = chars[open + 1..close].iter().collect(); |
| 94 | return Some((text, offset + 1)); |
| 95 | } |
| 96 | } |
| 97 | _ => {} |
| 98 | } |
| 99 | } |
| 100 | None |
| 101 | } |
| 102 | |
| 103 | /// A link label that is itself bracketed, i.e. a footnote marker rather than prose. |
| 104 | /// |
| 105 | /// The backslashes survive the markdown conversion, so `\[3\]` is what actually arrives. |
| 106 | fn is_reference(text: &str) -> bool { |
| 107 | let t = text.trim(); |
| 108 | let t = t.strip_prefix('\\').unwrap_or(t); |
| 109 | t.starts_with('[') |
| 110 | } |
| 111 | |
| 112 | /// Remove every parenthesised span, brackets and contents. |
| 113 | /// |
| 114 | /// **Aggressive on purpose.** In the lead of a settlement article a parenthesis is almost always |
| 115 | /// the name again — `(formerly …; German: …; Hungarian: …)` — and a reader on a phone who already |
| 116 | /// has the name in front of them gains nothing from four more spellings of it. Keeping only the |
| 117 | /// ones that *look* like name lists was the alternative and it is not worth it: the test would be |
| 118 | /// a list of language names, which is unbounded, and the failure mode is silently keeping a |
| 119 | /// paragraph of Cyrillic in a sheet three lines tall. |
| 120 | /// |
| 121 | /// The cost is real and accepted: `(commune seat)` and `(pop. 12,000)` go too. |
| 122 | /// |
| 123 | /// Nesting is counted, so `(a (b) c)` disappears as a unit rather than leaving `c)` behind. |
| 124 | fn strip_parentheticals(text: &str) -> String { |
| 125 | let mut out = String::with_capacity(text.len()); |
| 126 | let mut depth = 0usize; |
| 127 | for c in text.chars() { |
| 128 | match c { |
| 129 | '(' => depth += 1, |
| 130 | ')' => depth = depth.saturating_sub(1), |
| 131 | _ if depth == 0 => out.push(c), |
| 132 | _ => {} |
| 133 | } |
| 134 | } |
| 135 | out |
| 136 | } |
| 137 | |
| 138 | /// Collapse the whitespace the removals leave behind, and close the gaps before punctuation. |
| 139 | /// |
| 140 | /// Cutting ` (commune seat)` out of `… Săcălaz (commune seat).` leaves `… Săcălaz .`, which is the |
| 141 | /// giveaway that a sheet was assembled by a script. Runs of spaces collapse, a space before `.` |
| 142 | /// `,` `;` `:` closes up, and the line is trimmed. |
| 143 | fn tidy(text: &str) -> String { |
| 144 | let mut out = String::with_capacity(text.len()); |
| 145 | let mut pending_space = false; |
| 146 | for c in text.chars() { |
| 147 | if c.is_whitespace() { |
| 148 | pending_space = !out.is_empty(); |
| 149 | continue; |
| 150 | } |
| 151 | if pending_space && !matches!(c, '.' | ',' | ';' | ':' | '!' | '?') { |
| 152 | out.push(' '); |
| 153 | } |
| 154 | pending_space = false; |
| 155 | out.push(c); |
| 156 | } |
| 157 | out.trim().to_string() |
| 158 | } |
| 159 | |
| 160 | #[cfg(test)] |
| 161 | mod tests { |
| 162 | use super::*; |
| 163 | |
| 164 | /// The worked example from the spec, end to end. |
| 165 | #[test] |
| 166 | fn a_settlement_lead_loses_its_names_links_and_footnotes() { |
| 167 | let raw = "Săcălaz (formerly Săcalhaz; [German](https://en.wikipedia.org/wiki/German_language): \ |
| 168 | Sackelhausen; [Banat Swabian](https://en.wikipedia.org/wiki/Banat_Swabians): \ |
| 169 | Sacklass;[\\[3\\]](https://en.wikipedia.org/wiki/S%C4%83c%C4%83laz#cite_note-3) \ |
| 170 | [Hungarian](https://en.wikipedia.org/wiki/Hungarian_language): Szakálháza) is a \ |
| 171 | [commune](https://en.wikipedia.org/wiki/Communes_of_Romania) in \ |
| 172 | [Timiș County](https://en.wikipedia.org/wiki/Timi%C8%99_County), \ |
| 173 | [Romania](https://en.wikipedia.org/wiki/Romania). It is composed of three \ |
| 174 | villages: Beregsău Mare, Beregsău Mic and Săcălaz (commune seat)."; |
| 175 | assert_eq!( |
| 176 | clean(raw), |
| 177 | "Săcălaz is a commune in Timiș County, Romania. It is composed of three villages: \ |
| 178 | Beregsău Mare, Beregsău Mic and Săcălaz.", |
| 179 | ); |
| 180 | } |
| 181 | |
| 182 | #[test] |
| 183 | fn a_link_keeps_its_text_and_loses_its_target() { |
| 184 | assert_eq!(clean("a [commune](https://x/y) in [Timiș](https://x/z)"), "a commune in Timiș"); |
| 185 | } |
| 186 | |
| 187 | /// A footnote is a link whose label is itself bracketed. Recognised by shape, so `[\[note 1\]]` |
| 188 | /// and `[\[a\]]` go the same way as `[\[3\]]`. |
| 189 | #[test] |
| 190 | fn a_reference_marker_leaves_nothing_behind() { |
| 191 | assert_eq!(clean("Sacklass;[\\[3\\]](https://x/#cite_note-3) and more"), "Sacklass; and more"); |
| 192 | assert_eq!(clean("text[\\[note 1\\]](https://x/#n) end"), "text end"); |
| 193 | assert_eq!(clean("text[\\[a\\]](https://x/#a)"), "text"); |
| 194 | } |
| 195 | |
| 196 | /// The aggressive rule, stated as a test so it is a decision rather than an accident. |
| 197 | #[test] |
| 198 | fn every_parenthesis_goes_including_the_useful_ones() { |
| 199 | assert_eq!(clean("Săcălaz (commune seat)."), "Săcălaz."); |
| 200 | assert_eq!(clean("Springfield (pop. 12,000) is a city."), "Springfield is a city."); |
| 201 | // Nested, so the inner close must not end the outer span. |
| 202 | assert_eq!(clean("A (b (c) d) e"), "A e"); |
| 203 | } |
| 204 | |
| 205 | #[test] |
| 206 | fn the_space_left_by_a_removal_is_closed_up() { |
| 207 | assert_eq!(clean("Săcălaz (x) , Romania ."), "Săcălaz, Romania."); |
| 208 | assert_eq!(clean(" leading and trailing "), "leading and trailing"); |
| 209 | assert_eq!(clean("line\nbreaks\tcollapse"), "line breaks collapse"); |
| 210 | } |
| 211 | |
| 212 | /// Bracketed text with no `(target)` after it is prose, not a link. |
| 213 | #[test] |
| 214 | fn a_bracket_that_is_not_a_link_survives() { |
| 215 | assert_eq!(clean("the [sic] spelling"), "the [sic] spelling"); |
| 216 | } |
| 217 | |
| 218 | #[test] |
| 219 | fn plain_prose_is_returned_unchanged() { |
| 220 | let plain = "Paris is the capital and most populous city of France."; |
| 221 | assert_eq!(clean(plain), plain); |
| 222 | } |
| 223 | |
| 224 | /// Malformed input is common in a dump of five million articles and must not panic or hang. |
| 225 | #[test] |
| 226 | fn unbalanced_markup_does_not_panic() { |
| 227 | for raw in ["unclosed [link](http://x", "stray ) paren", "open ( paren", "[", "]", "()", ""] { |
| 228 | let _ = clean(raw); |
| 229 | } |
| 230 | } |
| 231 | } |