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

Modern-Apps.git / scripts / maps / osm_ingest / src / poi_reviews.rs

poi_reviews.rs174 lines · 6.2 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
17use std::collections::HashMap;
18use std::path::Path;
19
20use crate::poi_attrs::{KEY_RATING, KEY_REVIEW_COUNT, KEY_REVIEW_SUMMARY};
21use crate::proto::{Error, Result};
22
23pub const ELEMENT_NODE: u8 = 1;
24pub const ELEMENT_WAY: u8 = 2;
25pub const ELEMENT_RELATION: u8 = 3;
26
27/// Longest summary kept, in bytes. The writer targets 280 characters; this leaves
28/// room for multi-byte scripts while keeping one bad row from bloating the sidecar.
29const MAX_SUMMARY_BYTES: usize = 1024;
30
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct Review {
33 rating: Option<String>,
34 review_count: Option<String>,
35 summary: Option<String>,
36}
37
38impl Review {
39 /// The record fields to append, ascending by key.
40 pub fn fields(&self) -> Vec<(u8, &[u8])> {
41 let mut out = Vec::with_capacity(3);
42 if let Some(r) = &self.rating {
43 out.push((KEY_RATING, r.as_bytes()));
44 }
45 if let Some(c) = &self.review_count {
46 out.push((KEY_REVIEW_COUNT, c.as_bytes()));
47 }
48 if let Some(s) = &self.summary {
49 out.push((KEY_REVIEW_SUMMARY, s.as_bytes()));
50 }
51 out
52 }
53}
54
55#[derive(Debug, Default)]
56pub struct ReviewTable {
57 map: HashMap<(u8, i64), Review>,
58}
59
60impl ReviewTable {
61 pub fn load(path: &Path) -> Result<Self> {
62 let text = std::fs::read_to_string(path)
63 .map_err(|e| Error(format!("cannot read reviews {}: {e}", path.display())))?;
64 Self::parse(&text).map_err(|e| Error(format!("{}: {}", path.display(), e.0)))
65 }
66
67 pub fn parse(text: &str) -> Result<Self> {
68 let mut map = HashMap::new();
69 for (n, line) in text.lines().enumerate() {
70 let line = line.trim_end_matches('\r');
71 if line.trim().is_empty() || line.starts_with('#') {
72 continue;
73 }
74 let bad = |why: &str| Error(format!("line {}: {why}", n + 1));
75 let cols: Vec<&str> = line.split('\t').collect();
76 if cols.len() != 5 {
77 return Err(bad(&format!("expected 5 tab-separated columns, found {}", cols.len())));
78 }
79 let element = match cols[0] {
80 "node" => ELEMENT_NODE,
81 "way" => ELEMENT_WAY,
82 "relation" => ELEMENT_RELATION,
83 other => return Err(bad(&format!("unknown element `{other}`"))),
84 };
85 let id: i64 = cols[1].parse().map_err(|_| bad("id is not an integer"))?;
86 if id <= 0 {
87 return Err(bad("id must be positive"));
88 }
89 let rating = match cols[2].trim() {
90 "" => None,
91 r => {
92 let v: f32 = r.parse().map_err(|_| bad("rating is not a number"))?;
93 if !(1.0..=5.0).contains(&v) {
94 return Err(bad("rating must be between 1 and 5"));
95 }
96 Some(format!("{v:.1}"))
97 }
98 };
99 let review_count = match cols[3].trim() {
100 "" => None,
101 c => {
102 let v: u32 = c.parse().map_err(|_| bad("review_count is not a positive integer"))?;
103 (v > 0).then(|| v.to_string())
104 }
105 };
106 let summary = Some(cols[4].trim())
107 .filter(|s| !s.is_empty() && s.len() <= MAX_SUMMARY_BYTES)
108 .map(str::to_string);
109 map.insert((element, id), Review { rating, review_count, summary });
110 }
111 Ok(Self { map })
112 }
113
114 pub fn get(&self, element: u8, id: i64) -> Option<&Review> {
115 self.map.get(&(element, id))
116 }
117
118 pub fn len(&self) -> usize {
119 self.map.len()
120 }
121
122 pub fn is_empty(&self) -> bool {
123 self.map.is_empty()
124 }
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130
131 #[test]
132 fn parses_rows_and_skips_comments_and_blanks() {
133 let t = ReviewTable::parse(
134 "# element\tid\trating\treview_count\tsummary\n\
135 node\t148855851\t3.9\t3480\tClassic diner fare.\n\
136 \n\
137 way\t30636913\t4.25\t\t\n\
138 relation\t7\t\t12\tBig park.\r\n",
139 )
140 .unwrap();
141 assert_eq!(t.len(), 3);
142 let node = t.get(ELEMENT_NODE, 148855851).unwrap();
143 assert_eq!(
144 node.fields(),
145 vec![(KEY_RATING, &b"3.9"[..]), (KEY_REVIEW_COUNT, &b"3480"[..]), (KEY_REVIEW_SUMMARY, &b"Classic diner fare."[..])]
146 );
147 assert_eq!(t.get(ELEMENT_WAY, 30636913).unwrap().fields(), vec![(KEY_RATING, &b"4.2"[..])]);
148 assert_eq!(
149 t.get(ELEMENT_RELATION, 7).unwrap().fields(),
150 vec![(KEY_REVIEW_COUNT, &b"12"[..]), (KEY_REVIEW_SUMMARY, &b"Big park."[..])]
151 );
152 assert!(t.get(ELEMENT_WAY, 148855851).is_none(), "element is part of the key");
153 }
154
155 #[test]
156 fn malformed_rows_name_their_line() {
157 for (row, why) in [
158 ("node\t1\t4.0\t10", "expected 5"),
159 ("area\t1\t4.0\t10\tx", "unknown element"),
160 ("node\tabc\t4.0\t10\tx", "id is not"),
161 ("node\t1\t6.0\t10\tx", "between 1 and 5"),
162 ("node\t1\t4.0\t-3\tx", "review_count"),
163 ] {
164 let err = ReviewTable::parse(&format!("# header\n{row}\n")).unwrap_err().0;
165 assert!(err.starts_with("line 2:") && err.contains(why), "{row:?} -> {err}");
166 }
167 }
168
169 #[test]
170 fn an_over_long_summary_is_dropped_not_truncated() {
171 let t = ReviewTable::parse(&format!("node\t1\t4.0\t10\t{}\n", "x".repeat(MAX_SUMMARY_BYTES + 1))).unwrap();
172 assert_eq!(t.get(ELEMENT_NODE, 1).unwrap().fields().len(), 2);
173 }
174}