/
entity.rs
258 lines (220 loc) · 7.22 KB
/
entity.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// Stract is an open source web search engine.
// Copyright (C) 2023 Stract ApS
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use std::collections::BTreeMap;
use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{
entity_index::{entity::Span, EntityMatch},
searcher::LocalSearcher,
};
#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
pub struct DisplayedEntity {
pub title: String,
pub small_abstract: String,
pub image_base64: Option<String>,
pub related_entities: Vec<DisplayedEntity>,
pub info: Vec<(String, String)>,
pub match_score: f32,
}
fn prepare_info(info: BTreeMap<String, Span>, searcher: &LocalSearcher) -> Vec<(String, String)> {
let mut info: Vec<_> = info.into_iter().collect();
info.sort_by(|(a, _), (b, _)| {
searcher
.attribute_occurrence(b)
.unwrap_or(0)
.cmp(&searcher.attribute_occurrence(a).unwrap_or(0))
});
info.into_iter()
.map(|(key, value)| {
let mut value = entity_link_to_html(value, 150).replace('*', "•");
if value.starts_with('•') || value.starts_with("\n•") {
if let Some(first_bullet) = value.find('•') {
value = value.chars().skip(first_bullet + 1).collect();
}
}
let value = maybe_prettify_entity_date(value);
(key.replace('_', " "), value)
})
.filter(|(key, _)| {
!matches!(
key.as_str(),
"caption"
| "image size"
| "label"
| "landscape"
| "signature"
| "name"
| "website"
| "logo"
| "image caption"
| "alt"
)
})
.take(5)
.collect()
}
impl DisplayedEntity {
pub fn from(m: EntityMatch, searcher: &LocalSearcher) -> Self {
let entity_abstract = Span {
text: m.entity.entity_abstract,
links: m.entity.links,
};
let small_abstract = entity_link_to_html(entity_abstract, 300);
let image_base64 = m
.entity
.image
.and_then(|image| searcher.entity_image(image))
.map(|image| base64::encode(image.as_raw_bytes()));
Self {
title: m.entity.title,
small_abstract,
image_base64,
related_entities: m
.entity
.related_entities
.into_iter()
.map(|m| DisplayedEntity::from(m, searcher))
.collect(),
info: prepare_info(m.entity.info, searcher),
match_score: m.score,
}
}
}
fn maybe_prettify_entity_date(value: String) -> String {
if let Ok(date) = NaiveDate::parse_from_str(value.trim(), "%Y %-m %-d") {
return format!("{}", date.format("%d/%m/%Y"));
}
if value.split_whitespace().count() == 6 {
let first_date = NaiveDate::parse_from_str(
itertools::intersperse(value.split_whitespace().take(3), " ")
.collect::<String>()
.as_str(),
"%Y %-m %-d",
);
let second_date = NaiveDate::parse_from_str(
itertools::intersperse(value.split_whitespace().skip(3), " ")
.collect::<String>()
.as_str(),
"%Y %-m %-d",
);
if let (Ok(first_date), Ok(second_date)) = (first_date, second_date) {
// the dates are reversed from the parser, so we need to return second_date before first_date
return format!("{}", second_date.format("%d/%m/%Y"))
+ " - "
+ format!("{}", first_date.format("%d/%m/%Y")).as_str();
}
}
value
}
fn entity_link_to_html(span: Span, trunace_to: usize) -> String {
let mut s = span.text;
let truncated = s.len() > trunace_to;
if truncated {
s = s.chars().take(trunace_to).collect();
}
let chars = s.chars();
let num_chars = chars.clone().count();
let mut res = String::new();
let mut last_link_end = 0;
for link in span.links {
if link.start > num_chars {
break;
}
res += chars
.clone()
.skip(last_link_end)
.take(link.start - last_link_end)
.collect::<String>()
.as_str();
let link_text: String = chars
.clone()
.skip(link.start)
.take(link.end - link.start)
.collect();
res += format!(
"<a class=\"hover:underline\" href=\"https://en.wikipedia.org/wiki/{}\">",
link.target.replace(' ', "_")
)
.as_str();
res += link_text.as_str();
res += "</a>";
last_link_end = link.end;
}
res += chars
.clone()
.skip(last_link_end)
.collect::<String>()
.as_str();
if truncated {
res += "...";
}
res
}
#[cfg(test)]
mod tests {
use crate::entity_index::entity::Link;
use super::*;
#[test]
fn simple_link_to_html() {
assert_eq!(
entity_link_to_html(
Span {
text: "some text with a link".to_string(),
links: vec![Link {
start: 5,
end: 9,
target: "text article".to_string()
}]
},
10000
),
"some <a class=\"hover:underline\" href=\"https://en.wikipedia.org/wiki/text_article\">text</a> with a link"
.to_string()
);
}
#[test]
fn truncated_link_to_html() {
assert_eq!(
entity_link_to_html(
Span {
text: "some text".to_string(),
links: vec![Link {
start: 5,
end: 9,
target: "text article".to_string()
}]
},
7
),
"some <a class=\"hover:underline\" href=\"https://en.wikipedia.org/wiki/text_article\">te</a>...".to_string()
);
}
#[test]
fn einstein_date() {
assert_eq!(
maybe_prettify_entity_date("1879 3 14 ".to_string()),
"14/03/1879".to_string()
);
}
#[test]
fn entity_date_span_prettify() {
assert_eq!(
maybe_prettify_entity_date(" 1999 5 27 1879 3 14 ".to_string()),
"14/03/1879 - 27/05/1999".to_string()
);
}
}