Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / poi_reviews.rs
poi_reviews.rs332 lines · 11.9 KiBRaw
| 1 | //! External review data merged into `poi_attrs.bin` at build time. |
| 2 | //! |
| 3 | //! `summarize_reviews.py` writes a UTF-8, tab-separated table, one place per line: |
| 4 | //! |
| 5 | //! ```text |
| 6 | //! element<TAB>id<TAB>rating<TAB>review_count<TAB>summary |
| 7 | //! node 148855851 3.9 3480 Classic diner fare ... |
| 8 | //! ``` |
| 9 | //! |
| 10 | //! `element` is `node`, `way` or `relation` and `id` is the plain OSM id (relations |
| 11 | //! are NOT negated here; the negation in `poi_build` is internal). Empty columns |
| 12 | //! mean "unknown". Blank lines and lines starting with `#` are ignored. |
| 13 | //! |
| 14 | //! The join key has to be the OSM element because `poi_index.bin` and |
| 15 | //! `poi_attrs.bin` carry no OSM id, so this is the last point where one exists. |
| 16 | |
| 17 | use std::path::Path; |
| 18 | |
| 19 | use crate::poi_attrs::{KEY_RATING, KEY_REVIEW_COUNT, KEY_REVIEW_SUMMARY}; |
| 20 | use crate::proto::{Error, Result}; |
| 21 | |
| 22 | pub const ELEMENT_NODE: u8 = 1; |
| 23 | pub const ELEMENT_WAY: u8 = 2; |
| 24 | pub const ELEMENT_RELATION: u8 = 3; |
| 25 | |
| 26 | /// Longest summary kept, in bytes. The writer targets 280 characters; this leaves |
| 27 | /// room for multi-byte scripts while keeping one bad row from bloating the sidecar. |
| 28 | const MAX_SUMMARY_BYTES: usize = 1024; |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub struct Review { |
| 32 | rating: Option<String>, |
| 33 | review_count: Option<String>, |
| 34 | summary: Option<String>, |
| 35 | } |
| 36 | |
| 37 | impl Review { |
| 38 | /// The record fields to append, ascending by key. |
| 39 | pub fn fields(&self) -> Vec<(u8, &[u8])> { |
| 40 | let mut out = Vec::with_capacity(3); |
| 41 | if let Some(r) = &self.rating { |
| 42 | out.push((KEY_RATING, r.as_bytes())); |
| 43 | } |
| 44 | if let Some(c) = &self.review_count { |
| 45 | out.push((KEY_REVIEW_COUNT, c.as_bytes())); |
| 46 | } |
| 47 | if let Some(s) = &self.summary { |
| 48 | out.push((KEY_REVIEW_SUMMARY, s.as_bytes())); |
| 49 | } |
| 50 | out |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | #[derive(Debug, Default)] |
| 55 | pub struct ReviewTable { |
| 56 | /// Sorted by key, one entry per key (the LAST row for that key wins, as the |
| 57 | /// `HashMap::insert` this replaced did). A sorted `Vec` rather than a map so |
| 58 | /// the 2.7M-row planet table can be built and ordered in parallel. |
| 59 | rows: Vec<((u8, i64), Review)>, |
| 60 | } |
| 61 | |
| 62 | /// One parsed row, or `(line index within its chunk, why)` for the first bad one. |
| 63 | type ChunkRows = std::result::Result<Vec<((u8, i64), Review)>, (usize, String)>; |
| 64 | |
| 65 | /// Smallest parse chunk. The table is ~400 MB on a planet build; below a few MiB a |
| 66 | /// chunk is not worth a task. |
| 67 | const MIN_PARSE_CHUNK: usize = 4 << 20; |
| 68 | |
| 69 | impl ReviewTable { |
| 70 | pub fn load(path: &Path) -> Result<Self> { |
| 71 | let text = std::fs::read_to_string(path) |
| 72 | .map_err(|e| Error(format!("cannot read reviews {}: {e}", path.display())))?; |
| 73 | Self::parse(&text).map_err(|e| Error(format!("{}: {}", path.display(), e.0))) |
| 74 | } |
| 75 | |
| 76 | /// Parse the whole table. |
| 77 | /// |
| 78 | /// Parallel, and identical to the serial parse it replaced: the text is cut |
| 79 | /// only immediately after a `\n`, so the chunks' `lines()` concatenate to the |
| 80 | /// whole text's `lines()`; each chunk reports its line count, so an error |
| 81 | /// carries the same global line number; the first failing chunk in text order |
| 82 | /// supplies the error, and within a chunk parsing stops at its first bad line, |
| 83 | /// so the reported error is the first bad line of the file. Rows are then |
| 84 | /// stable-sorted by key and deduplicated keeping the last, which is what |
| 85 | /// repeated `HashMap::insert` in file order did. |
| 86 | pub fn parse(text: &str) -> Result<Self> { |
| 87 | let target = (text.len() / (crate::par::threads() * 4).max(1)).max(MIN_PARSE_CHUNK); |
| 88 | Self::parse_chunked(text, target) |
| 89 | } |
| 90 | |
| 91 | /// [`ReviewTable::parse`] with an explicit chunk size, so tests can force |
| 92 | /// many chunks on a tiny table. |
| 93 | fn parse_chunked(text: &str, target: usize) -> Result<Self> { |
| 94 | use rayon::prelude::*; |
| 95 | let target = target.max(1); |
| 96 | let bytes = text.as_bytes(); |
| 97 | let mut chunks: Vec<&str> = Vec::new(); |
| 98 | let mut pos = 0; |
| 99 | while pos < bytes.len() { |
| 100 | let mut end = (pos + target).min(bytes.len()); |
| 101 | if end < bytes.len() { |
| 102 | end = match bytes[end..].iter().position(|b| *b == b'\n') { |
| 103 | Some(k) => end + k + 1, |
| 104 | None => bytes.len(), |
| 105 | }; |
| 106 | } |
| 107 | // `end` is just past an ASCII `\n` or the end, so a char boundary. |
| 108 | chunks.push(&text[pos..end]); |
| 109 | pos = end; |
| 110 | } |
| 111 | |
| 112 | let parsed: Vec<(usize, ChunkRows)> = |
| 113 | crate::par::install(|| chunks.par_iter().map(|c| parse_chunk(c)).collect()); |
| 114 | |
| 115 | let mut first_line = 0usize; |
| 116 | let mut total = 0usize; |
| 117 | for (lines, rows) in &parsed { |
| 118 | match rows { |
| 119 | Ok(r) => total += r.len(), |
| 120 | Err((n, why)) => { |
| 121 | return Err(Error(format!("line {}: {why}", first_line + n + 1))); |
| 122 | } |
| 123 | } |
| 124 | first_line += lines; |
| 125 | } |
| 126 | let mut rows: Vec<((u8, i64), Review)> = Vec::with_capacity(total); |
| 127 | for (_, r) in parsed { |
| 128 | rows.extend(r.expect("errors returned above")); |
| 129 | } |
| 130 | crate::par::install(|| rows.par_sort_by_key(|r| r.0)); |
| 131 | // `dedup_by` hands (later, kept); swapping first leaves the later row kept. |
| 132 | rows.dedup_by(|later, kept| { |
| 133 | if later.0 == kept.0 { |
| 134 | std::mem::swap(later, kept); |
| 135 | true |
| 136 | } else { |
| 137 | false |
| 138 | } |
| 139 | }); |
| 140 | Ok(Self { rows }) |
| 141 | } |
| 142 | |
| 143 | pub fn get(&self, element: u8, id: i64) -> Option<&Review> { |
| 144 | self.rows.binary_search_by_key(&(element, id), |r| r.0).ok().map(|i| &self.rows[i].1) |
| 145 | } |
| 146 | |
| 147 | pub fn len(&self) -> usize { |
| 148 | self.rows.len() |
| 149 | } |
| 150 | |
| 151 | pub fn is_empty(&self) -> bool { |
| 152 | self.rows.is_empty() |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// Parse one line-aligned chunk: `(lines in the chunk, rows or first error)`. |
| 157 | fn parse_chunk(text: &str) -> (usize, ChunkRows) { |
| 158 | let mut out = Vec::new(); |
| 159 | let mut lines = 0usize; |
| 160 | for (n, line) in text.lines().enumerate() { |
| 161 | lines = n + 1; |
| 162 | match parse_line(line) { |
| 163 | Ok(Some(row)) => out.push(row), |
| 164 | Ok(None) => {} |
| 165 | Err(why) => return (lines, Err((n, why))), |
| 166 | } |
| 167 | } |
| 168 | (lines, Ok(out)) |
| 169 | } |
| 170 | |
| 171 | /// One parsed table line, keyed by `(element kind, OSM id)`. |
| 172 | type ParsedLine = std::result::Result<Option<((u8, i64), Review)>, String>; |
| 173 | |
| 174 | /// One table line: `Ok(None)` for a blank or comment line. |
| 175 | fn parse_line(line: &str) -> ParsedLine { |
| 176 | let line = line.trim_end_matches('\r'); |
| 177 | if line.trim().is_empty() || line.starts_with('#') { |
| 178 | return Ok(None); |
| 179 | } |
| 180 | let cols: Vec<&str> = line.split('\t').collect(); |
| 181 | if cols.len() != 5 { |
| 182 | return Err(format!("expected 5 tab-separated columns, found {}", cols.len())); |
| 183 | } |
| 184 | let element = match cols[0] { |
| 185 | "node" => ELEMENT_NODE, |
| 186 | "way" => ELEMENT_WAY, |
| 187 | "relation" => ELEMENT_RELATION, |
| 188 | other => return Err(format!("unknown element `{other}`")), |
| 189 | }; |
| 190 | let id: i64 = cols[1].parse().map_err(|_| "id is not an integer".to_string())?; |
| 191 | if id <= 0 { |
| 192 | return Err("id must be positive".into()); |
| 193 | } |
| 194 | let rating = match cols[2].trim() { |
| 195 | "" => None, |
| 196 | r => { |
| 197 | let v: f32 = r.parse().map_err(|_| "rating is not a number".to_string())?; |
| 198 | if !(1.0..=5.0).contains(&v) { |
| 199 | return Err("rating must be between 1 and 5".into()); |
| 200 | } |
| 201 | Some(format!("{v:.1}")) |
| 202 | } |
| 203 | }; |
| 204 | let review_count = match cols[3].trim() { |
| 205 | "" => None, |
| 206 | c => { |
| 207 | let v: u32 = |
| 208 | c.parse().map_err(|_| "review_count is not a positive integer".to_string())?; |
| 209 | (v > 0).then(|| v.to_string()) |
| 210 | } |
| 211 | }; |
| 212 | let summary = Some(cols[4].trim()) |
| 213 | .filter(|s| !s.is_empty() && s.len() <= MAX_SUMMARY_BYTES) |
| 214 | .map(str::to_string); |
| 215 | Ok(Some(((element, id), Review { rating, review_count, summary }))) |
| 216 | } |
| 217 | |
| 218 | #[cfg(test)] |
| 219 | mod tests { |
| 220 | use super::*; |
| 221 | |
| 222 | #[test] |
| 223 | fn parses_rows_and_skips_comments_and_blanks() { |
| 224 | let t = ReviewTable::parse( |
| 225 | "# element\tid\trating\treview_count\tsummary\n\ |
| 226 | node\t148855851\t3.9\t3480\tClassic diner fare.\n\ |
| 227 | \n\ |
| 228 | way\t30636913\t4.25\t\t\n\ |
| 229 | relation\t7\t\t12\tBig park.\r\n", |
| 230 | ) |
| 231 | .unwrap(); |
| 232 | assert_eq!(t.len(), 3); |
| 233 | let node = t.get(ELEMENT_NODE, 148855851).unwrap(); |
| 234 | assert_eq!( |
| 235 | node.fields(), |
| 236 | vec![ |
| 237 | (KEY_RATING, &b"3.9"[..]), |
| 238 | (KEY_REVIEW_COUNT, &b"3480"[..]), |
| 239 | (KEY_REVIEW_SUMMARY, &b"Classic diner fare."[..]) |
| 240 | ] |
| 241 | ); |
| 242 | assert_eq!(t.get(ELEMENT_WAY, 30636913).unwrap().fields(), vec![(KEY_RATING, &b"4.2"[..])]); |
| 243 | assert_eq!( |
| 244 | t.get(ELEMENT_RELATION, 7).unwrap().fields(), |
| 245 | vec![(KEY_REVIEW_COUNT, &b"12"[..]), (KEY_REVIEW_SUMMARY, &b"Big park."[..])] |
| 246 | ); |
| 247 | assert!(t.get(ELEMENT_WAY, 148855851).is_none(), "element is part of the key"); |
| 248 | } |
| 249 | |
| 250 | #[test] |
| 251 | fn malformed_rows_name_their_line() { |
| 252 | for (row, why) in [ |
| 253 | ("node\t1\t4.0\t10", "expected 5"), |
| 254 | ("area\t1\t4.0\t10\tx", "unknown element"), |
| 255 | ("node\tabc\t4.0\t10\tx", "id is not"), |
| 256 | ("node\t1\t6.0\t10\tx", "between 1 and 5"), |
| 257 | ("node\t1\t4.0\t-3\tx", "review_count"), |
| 258 | ] { |
| 259 | let err = ReviewTable::parse(&format!("# header\n{row}\n")).unwrap_err().0; |
| 260 | assert!(err.starts_with("line 2:") && err.contains(why), "{row:?} -> {err}"); |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | #[test] |
| 265 | fn an_over_long_summary_is_dropped_not_truncated() { |
| 266 | let t = ReviewTable::parse(&format!( |
| 267 | "node\t1\t4.0\t10\t{}\n", |
| 268 | "x".repeat(MAX_SUMMARY_BYTES + 1) |
| 269 | )) |
| 270 | .unwrap(); |
| 271 | assert_eq!(t.get(ELEMENT_NODE, 1).unwrap().fields().len(), 2); |
| 272 | } |
| 273 | |
| 274 | /// Serial reference: the `HashMap` parse this module used before it went |
| 275 | /// parallel, kept here to pin the parallel one to it. |
| 276 | fn reference( |
| 277 | text: &str, |
| 278 | ) -> std::result::Result<std::collections::HashMap<(u8, i64), Review>, String> { |
| 279 | let mut map = std::collections::HashMap::new(); |
| 280 | for (n, line) in text.lines().enumerate() { |
| 281 | match parse_line(line) { |
| 282 | Ok(Some((k, v))) => { |
| 283 | map.insert(k, v); |
| 284 | } |
| 285 | Ok(None) => {} |
| 286 | Err(why) => return Err(format!("line {}: {why}", n + 1)), |
| 287 | } |
| 288 | } |
| 289 | Ok(map) |
| 290 | } |
| 291 | |
| 292 | fn sample(rows: usize, bad_at: Option<usize>) -> String { |
| 293 | let mut s = String::from("# header\n"); |
| 294 | for i in 0..rows { |
| 295 | if Some(i) == bad_at { |
| 296 | s.push_str("node\tnope\t1\t1\tx\n"); |
| 297 | continue; |
| 298 | } |
| 299 | // Ids repeat, so later rows must overwrite earlier ones. |
| 300 | let el = ["node", "way", "relation"][i % 3]; |
| 301 | s.push_str(&format!("{el}\t{}\t{}.0\t{i}\tsummary {i}\r\n", 1 + i % 37, 1 + i % 5)); |
| 302 | if i % 11 == 0 { |
| 303 | s.push('\n'); |
| 304 | } |
| 305 | } |
| 306 | s |
| 307 | } |
| 308 | |
| 309 | #[test] |
| 310 | fn chunked_parse_matches_the_serial_map_for_every_chunk_size() { |
| 311 | let text = sample(500, None); |
| 312 | let want = reference(&text).unwrap(); |
| 313 | for target in [1usize, 2, 7, 64, 333, 4096, 1 << 20] { |
| 314 | let got = ReviewTable::parse_chunked(&text, target).unwrap(); |
| 315 | assert_eq!(got.len(), want.len(), "target {target}"); |
| 316 | for (k, v) in &want { |
| 317 | assert_eq!(got.get(k.0, k.1), Some(v), "target {target} key {k:?}"); |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | #[test] |
| 323 | fn chunked_parse_reports_the_first_bad_line_globally() { |
| 324 | let mut text = sample(300, Some(123)); |
| 325 | text.push_str("way\tx\t\t\t\n"); |
| 326 | let want = reference(&text).unwrap_err(); |
| 327 | for target in [1usize, 5, 50, 999, 1 << 20] { |
| 328 | let got = ReviewTable::parse_chunked(&text, target).unwrap_err().0; |
| 329 | assert_eq!(got, want, "target {target}"); |
| 330 | } |
| 331 | } |
| 332 | } |