Elffuss BraidHub

kikocis/utopia public

da80a58c3af3 · 16.2 KiBRawPermalink
1//! 把模型说出的谓词落到本体里**已经有**的关系上。
2//!
3//! 抽取原本只做精确 key 比对(`rel_ids.get(f.predicate)`),对不上就降级成
4//! `related_to`,原词留在 `fact_evidence.proposed_predicate` 等人来采纳。
5//!
6//! 实测这样漏得很凶。ai-timeline 语料(维基百科的 AI 公司条目)跑到一半时,
7//! 49.8% 的事实是 `related_to`,`ontology_misses` 里 398 个不同的关系名、895 次使用。
8//! 其中一类根本不是缺词汇,是**词汇就在本体里,模型只是说反了或换了时态**:
9//! `produced_by | ChatGPT → OpenAI` 想说的就是已有的 `produces`,主宾对调而已。
10//!
11//! 那个 49.8% 是**测量台把自动扩本体关掉之后**的数字(`run.mjs` 建库即置
12//! `auto_extend_ontology=FALSE`,而列默认值是 true)。产品的实际冷启动路径是
13//! `bootstrap_ontology` 事后补本体,所以别拿这个占比去说产品有多糟——
14//! 它量的是"缺词汇时降级有多频繁",而这正是本模块要减少的那一部分。
15//!
16//! 这里补三段,**顺序即优先级**,宽的永远排在窄的后面:
17//!
18//! 1. 精确 key —— 原有行为,一字不改
19//! 2. 写法对齐 —— `acquiredFrom` / `acquired_from` / `Acquired From` 是同一个
20//! 3. 屈折归一 —— `produced` 与 `produces` 折到同一串(只削时态与单复数,见 `inflect_base`)
21//!
22//! 2、3 各再试一次「去掉结尾的 by」,命中就**把主宾对调**:英语里 `_by` 是被动的
23//! 明确标记,`X produced_by Y` 与 `Y produces X` 是同一条边。
24//!
25//! **撞车就不匹配。** 本体里若同时有 `produces` 和 `produced`,两者折到同一串,
26//! 这时选谁都是猜——宁可降级,让人去采纳。只有精确 key 不受此限,它本来就唯一。
27//!
28//! **量到了什么**(同一份 895 次未匹配,两种词表):种子本体 10 个关系捞回 49 次;
29//! schema.org 629 个关系捞回 59 次。捞回的 9 个说法里 6 个正确、3 个方向可疑
30//!(`addresses→address`、`funds→funding`、`sponsors→sponsor`),各 1 次,
31//! **全部来自光削一个 `s` 那条路**——英语里 `sponsors` 既是动词第三人称也是名词复数,
32//! 靠后缀分不出来。没为这三条再加规则:样本太小,加了就是过拟合。
33//! 它们的反事实也不是「正确」,而是 `related_to`——原词仍在 proposed_predicate 里。
34//!
35//! 不做同义判断(`partners_with` 与 `collaborates_with`):那是检索与模型的活。
36//! 摆在这里会把「写法对齐」悄悄变成「意思大概差不多」,而后者错了没人看得见。
37
38use std::collections::HashMap;
39use utopia_core::models::RelationType;
40use uuid::Uuid;
41
42/// 切词:非字母数字处切,驼峰的大小写交界处也切。
43///
44/// 驼峰那一半不是可选的:OWL 导入的 key 就是 `acquiredFrom`,不切的话它跟手写的
45/// `acquired_from` 折不到一起,而「导入的本体能不能被用上」正是这条路要保的。
46fn words(s: &str) -> Vec<String> {
47 let mut out = Vec::new();
48 let mut cur = String::new();
49 let mut prev_is_lower_or_digit = false;
50 for c in s.chars() {
51 if !c.is_alphanumeric() {
52 if !cur.is_empty() {
53 out.push(std::mem::take(&mut cur));
54 }
55 prev_is_lower_or_digit = false;
56 continue;
57 }
58 if c.is_uppercase() && prev_is_lower_or_digit && !cur.is_empty() {
59 out.push(std::mem::take(&mut cur));
60 }
61 prev_is_lower_or_digit = c.is_lowercase() || c.is_numeric();
62 cur.extend(c.to_lowercase());
63 }
64 if !cur.is_empty() {
65 out.push(cur);
66 }
67 out
68}
69
70/// 写法对齐形:切完的词直接拼起来,分隔符不留。与
71/// `api::ontology_routes::normalize_name` 同规则。
72fn joined(words: &[String]) -> String {
73 words.concat()
74}
75
76/// 屈折归一:削掉时态与单复数,**不碰派生后缀**。
77///
78/// 这里一度用的是 Snowball(`rust-stemmers`),实测反了:词表 10 个词时捞回 49 次,
79/// 换成 schema.org 的 629 个词只剩 18 次。因为 Snowball 连派生后缀一起削,
80/// `producer` 与 `produces` 都成了 `produc`,撞车规则于是拒绝匹配——**词表越大越不敢动**。
81/// 而 `producer`(一个人)和 `produces`(一个动作)本来就该是两个关系,
82/// 折到一起是词干器的错,不是撞车规则的错。
83///
84/// 所以只做屈折:`-ies→y`、`-ing`、`-ed`、`-s`(`-ss` 除外),削完再去掉结尾的 `e`。
85/// 最后那一步是为了让 `-s` 和 `-ed` 两条路汇合——`produces→produce→produc`、
86/// `produced→produc`,否则同一个动词的两种时态永远对不上。
87///
88/// 长度守卫看的是**削完之后**的结果,不是中间结果。按中间结果卡会让两条路
89/// 走岔:`uses` 削 `-s` 剩三个字母过关、再掉个 `e` 变两个,而 `used` 削 `-ed`
90/// 当场就是两个、被拦下——同一个动词的两种时态于是永远对不上。
91/// 剩不到两个字母就整个不削(`is` 不该变成 `i`,`led` 不该变成 `l`)。
92///
93/// 中文没有屈折后缀,走这里是恒等变换,所以不必按 `ontology_lang` 分叉。
94fn inflect_base(w: &str) -> String {
95 let n = w.len();
96 let mut s = if w.ends_with("ies") && n > 3 {
97 format!("{}y", &w[..n - 3])
98 } else if w.ends_with("ing") && n > 3 {
99 w[..n - 3].to_string()
100 } else if w.ends_with("ed") && n > 2 {
101 w[..n - 2].to_string()
102 } else if w.ends_with('s') && !w.ends_with("ss") && n > 1 {
103 w[..n - 1].to_string()
104 } else {
105 w.to_string()
106 };
107 // 结尾的 e 一律去掉:`produces→produce` 与 `produced→produc` 靠这一步汇合,
108 // 顺带让 `note` 与 `notes` 落到一起
109 if s.ends_with('e') {
110 s.pop();
111 }
112 if s.chars().count() < 2 {
113 return w.to_string();
114 }
115 s
116}
117
118fn stems(words: &[String]) -> Vec<String> {
119 words.iter().map(|w| inflect_base(w)).collect()
120}
121
122/// 一个说法的**归并键**:同一个关系的不同时态落到同一个键上。
123///
124/// 给本体采纳那条路用的。抽取时说法要跟**已有**关系比对(上面那套三段匹配),
125/// 采纳时要做的是另一件事——把彼此之间是同一个意思的说法先并起来再算票数。
126///
127/// 不并就要吃亏,而且吃得见:ai-timeline 跑完后还压在兜底谓词上的说法里,
128/// `sued` 与 `sues` 是两条(各 11 和 5)、`integrated_with` 与 `integrates_with`
129/// 是两条(各 5)、`announced`/`announces`、`supported`/`supports`、
130/// `developed`/`develops` 都是。各自算票,各自够不着「出现在 ≥2 篇」的门槛;
131/// 并起来之后够格的候选从 70 组涨到 85 组、281 条涨到 355 条。
132///
133/// **介词不并**:`integrated_with` 与 `integrated_into` 保持两组。`works_at` 与
134/// `works_in` 确实可能是两回事,这里宁可漏。
135///
136/// **`_by` 也不并**(待做):`founded_by` 与 `founded` 是同一条边的两个方向。
137///
138/// 当初不并的理由是「采纳路径从旧行原样复制主语,对调不了」——**那个理由已经
139/// 不成立**(#109 让 `adopt` 显式绑定主语并支持交换)。现在缺口只剩一处:
140/// 两边都还不在本体里时(`founded_by` 42 条、`founded` 4 条,都够票),
141/// 采纳前的 `PredicateIndex` 查询谁也匹配不上,于是各建一个、方向相反。
142/// 补法是把 `_by` 折进同一组并把整组标成需对调,不再有阻碍。
143pub fn merge_key(form: &str) -> Vec<String> {
144 stems(&words(form))
145}
146
147/// 撞车即作废:同一个形式落到两个不同的关系上,选谁都是猜。
148fn insert<K: std::hash::Hash + Eq>(map: &mut HashMap<K, Option<Uuid>>, key: K, id: Uuid) {
149 map.entry(key)
150 .and_modify(|slot| {
151 if *slot != Some(id) {
152 *slot = None;
153 }
154 })
155 .or_insert(Some(id));
156}
157
158pub struct PredicateIndex {
159 exact: HashMap<String, Uuid>,
160 by_joined: HashMap<String, Option<Uuid>>,
161 by_stems: HashMap<Vec<String>, Option<Uuid>>,
162}
163
164impl PredicateIndex {
165 /// **只收 `kind == "relation"`。** 属性走字面值通道,模糊匹配跨过去,
166 /// `founding_date` 就会变成一条指向实体「2015」的边——那正是本体采纳那条路
167 /// 已经专门挡掉的东西,这里不能从后门放回来。
168 pub fn build(rtypes: &[RelationType]) -> Self {
169 let mut exact = HashMap::new();
170 let mut by_joined = HashMap::new();
171 let mut by_stems = HashMap::new();
172 for r in rtypes.iter().filter(|r| r.kind == "relation") {
173 exact.insert(r.key.clone(), r.id);
174 let w = words(&r.key);
175 if w.is_empty() {
176 continue;
177 }
178 insert(&mut by_joined, joined(&w), r.id);
179 insert(&mut by_stems, stems(&w), r.id);
180 }
181 Self {
182 exact,
183 by_joined,
184 by_stems,
185 }
186 }
187
188 fn widened(&self, w: &[String]) -> Option<Uuid> {
189 if w.is_empty() {
190 return None;
191 }
192 if let Some(hit) = self.by_joined.get(&joined(w)) {
193 return *hit;
194 }
195 *self.by_stems.get(&stems(w))?
196 }
197
198 /// 返回 `(关系 id, 主宾是否要对调)`。`None` = 本体里确实没有,该降级。
199 pub fn lookup(&self, proposed: &str) -> Option<(Uuid, bool)> {
200 if let Some(id) = self.exact.get(proposed) {
201 return Some((*id, false));
202 }
203 let w = words(proposed);
204 if let Some(id) = self.widened(&w) {
205 return Some((id, false));
206 }
207 // 被动形:`produced_by` 去掉 by 之后才对得上 `produces`,且主宾要反过来。
208 // 要求至少两个词——光一个 `by` 削完是空的。
209 if w.len() >= 2 && w[w.len() - 1] == "by" {
210 if let Some(id) = self.widened(&w[..w.len() - 1]) {
211 return Some((id, true));
212 }
213 }
214 None
215 }
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 fn rel(key: &str) -> RelationType {
223 RelationType {
224 id: Uuid::new_v4(),
225 kb_id: Uuid::nil(),
226 key: key.to_string(),
227 label: key.to_string(),
228 temporal: "state".into(),
229 functional: false,
230 inverse_functional: false,
231 builtin: false,
232 description: String::new(),
233 iri: None,
234 kind: "relation".into(),
235 domains: Vec::new(),
236 ranges: Vec::new(),
237 datatype: None,
238 unit: None,
239 }
240 }
241
242 fn attr(key: &str) -> RelationType {
243 RelationType {
244 kind: "attribute".into(),
245 ..rel(key)
246 }
247 }
248
249 #[test]
250 fn splits_camel_case_and_separators_the_same_way() {
251 assert_eq!(words("acquiredFrom"), ["acquired", "from"]);
252 assert_eq!(words("acquired_from"), ["acquired", "from"]);
253 assert_eq!(words("Acquired From"), ["acquired", "from"]);
254 // 全大写不是驼峰边界,别把 IRI 切成 i/r/i
255 assert_eq!(words("IRI"), ["iri"]);
256 assert_eq!(words("gpt4Model"), ["gpt4", "model"]);
257 }
258
259 #[test]
260 fn exact_key_still_wins_unchanged() {
261 let types = [rel("produces")];
262 let idx = PredicateIndex::build(&types);
263 assert_eq!(idx.lookup("produces"), Some((types[0].id, false)));
264 }
265
266 #[test]
267 fn separator_and_case_differences_align() {
268 let types = [rel("acquired_from")];
269 let idx = PredicateIndex::build(&types);
270 assert_eq!(idx.lookup("acquiredFrom"), Some((types[0].id, false)));
271 assert_eq!(idx.lookup("Acquired From"), Some((types[0].id, false)));
272 }
273
274 #[test]
275 fn tense_folds_without_swapping() {
276 let types = [rel("produces")];
277 let idx = PredicateIndex::build(&types);
278 // 模型写过去式,说的还是同一条边,方向也没变
279 assert_eq!(idx.lookup("produced"), Some((types[0].id, false)));
280 }
281
282 /// 这条是这个模块存在的理由:`ChatGPT produced_by OpenAI` 与
283 /// `OpenAI produces ChatGPT` 是同一条边,只差主宾方向。
284 #[test]
285 fn passive_form_matches_and_asks_for_a_swap() {
286 let types = [rel("produces")];
287 let idx = PredicateIndex::build(&types);
288 assert_eq!(idx.lookup("produced_by"), Some((types[0].id, true)));
289 assert_eq!(idx.lookup("producedBy"), Some((types[0].id, true)));
290 }
291
292 #[test]
293 fn multi_word_passive_matches() {
294 let types = [rel("invests_in")];
295 let idx = PredicateIndex::build(&types);
296 assert_eq!(idx.lookup("invested_in"), Some((types[0].id, false)));
297 }
298
299 /// **派生不是屈折。** 这条是换掉 Snowball 的理由:schema.org 里 `producer`
300 /// 与 `produces` 并存,词干器把两个都折成 `produc`,于是撞车规则把
301 /// `produced` 也一并拒了——词表越大捞得越少(实测 49 次掉到 18 次)。
302 /// 只削屈折后缀就不会有这个撞车:`producer` 保持原样。
303 #[test]
304 fn derivational_forms_stay_separate_from_inflected_ones() {
305 let types = [rel("produces"), rel("producer"), rel("production_company")];
306 let idx = PredicateIndex::build(&types);
307 assert_eq!(idx.lookup("produced"), Some((types[0].id, false)));
308 assert_eq!(idx.lookup("produced_by"), Some((types[0].id, true)));
309 assert_eq!(idx.lookup("producer"), Some((types[1].id, false)));
310 // 派生词之间也别互相串
311 assert_eq!(idx.lookup("producers"), Some((types[1].id, false)));
312 }
313
314 /// 单复数与时态两条路要汇合到同一串,否则同一个动词的两种写法永远对不上。
315 #[test]
316 fn plural_and_past_forms_meet_at_the_same_base() {
317 assert_eq!(inflect_base("produces"), inflect_base("produced"));
318 assert_eq!(inflect_base("uses"), inflect_base("used"));
319 assert_eq!(inflect_base("notes"), inflect_base("note"));
320 assert_eq!(inflect_base("studies"), inflect_base("study"));
321 // 短词不削:is 不该变成 i
322 assert_eq!(inflect_base("is"), "is");
323 // -ss 不是复数
324 assert_eq!(inflect_base("address"), inflect_base("addresses"));
325 }
326
327 /// 撞车宁可不匹配:本体里同时有 `produces` 和 `produced` 时,
328 /// `producing` 折到两者共同的词干上,选谁都是猜。
329 #[test]
330 fn ambiguous_stem_declines_rather_than_guesses() {
331 let types = [rel("produces"), rel("produced")];
332 let idx = PredicateIndex::build(&types);
333 assert_eq!(idx.lookup("producing"), None);
334 // 但精确 key 不受影响,它本来就唯一
335 assert_eq!(idx.lookup("produces"), Some((types[0].id, false)));
336 assert_eq!(idx.lookup("produced"), Some((types[1].id, false)));
337 }
338
339 /// 属性不能从这条路被匹配上:宾语是字面值,配不出一条边。
340 #[test]
341 fn attributes_are_not_reachable() {
342 let types = [attr("founding_date")];
343 let idx = PredicateIndex::build(&types);
344 assert_eq!(idx.lookup("founding_date"), None);
345 assert_eq!(idx.lookup("foundingDate"), None);
346 }
347
348 /// 本体里真没有的,照旧降级——这里不做同义判断。
349 #[test]
350 fn genuinely_missing_vocabulary_still_declines() {
351 let types = [rel("produces"), rel("works_at")];
352 let idx = PredicateIndex::build(&types);
353 assert_eq!(idx.lookup("partners_with"), None);
354 assert_eq!(idx.lookup("acquired"), None);
355 // 介词不同就是不同的关系,别替模型改口
356 assert_eq!(idx.lookup("works_in"), None);
357 }
358
359 #[test]
360 fn lone_by_does_not_strip_to_nothing() {
361 let types = [rel("produces")];
362 let idx = PredicateIndex::build(&types);
363 assert_eq!(idx.lookup("by"), None);
364 assert_eq!(idx.lookup("_by_"), None);
365 }
366
367 /// 中文 key 走词干器是恒等变换,不该被削也不该错配。
368 #[test]
369 fn chinese_keys_pass_through() {
370 let types = [rel("隶属于"), rel("生产")];
371 let idx = PredicateIndex::build(&types);
372 assert_eq!(idx.lookup("隶属于"), Some((types[0].id, false)));
373 assert_eq!(idx.lookup("生产"), Some((types[1].id, false)));
374 assert_eq!(idx.lookup("收购"), None);
375 }
376}