recallic-engine 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- recallic_engine/__init__.py +10 -0
- recallic_engine/api/__init__.py +0 -0
- recallic_engine/api/deps.py +36 -0
- recallic_engine/brain/__init__.py +0 -0
- recallic_engine/brain/features/__init__.py +1 -0
- recallic_engine/brain/features/aggregation_check.py +796 -0
- recallic_engine/brain/features/answer_check.default.json +23 -0
- recallic_engine/brain/features/answer_check.py +199 -0
- recallic_engine/brain/features/answer_check_learning.py +164 -0
- recallic_engine/brain/features/answer_verify.py +78 -0
- recallic_engine/brain/features/as_of.py +122 -0
- recallic_engine/brain/features/calibration.py +119 -0
- recallic_engine/brain/features/dates.py +124 -0
- recallic_engine/brain/features/facts.py +472 -0
- recallic_engine/brain/features/implicit.py +208 -0
- recallic_engine/brain/features/learned_facts.py +121 -0
- recallic_engine/brain/features/modes.py +70 -0
- recallic_engine/brain/features/query.py +297 -0
- recallic_engine/brain/features/reranker.py +87 -0
- recallic_engine/brain/features/schemas.py +222 -0
- recallic_engine/brain/features/summarize.py +72 -0
- recallic_engine/brain/features/trust.default.json +37 -0
- recallic_engine/brain/features/trust.py +165 -0
- recallic_engine/brain/memory/__init__.py +0 -0
- recallic_engine/brain/memory/archive/__init__.py +0 -0
- recallic_engine/brain/memory/archive/archive_store.py +64 -0
- recallic_engine/brain/memory/audit.py +84 -0
- recallic_engine/brain/memory/episodic/__init__.py +0 -0
- recallic_engine/brain/memory/episodic/episodic_memory.py +500 -0
- recallic_engine/brain/memory/freshness.py +104 -0
- recallic_engine/brain/memory/index_key.py +55 -0
- recallic_engine/brain/memory/index_sync.py +109 -0
- recallic_engine/brain/memory/long_term/__init__.py +0 -0
- recallic_engine/brain/memory/long_term/long_term_memory.py +80 -0
- recallic_engine/brain/memory/manager.py +326 -0
- recallic_engine/brain/memory/proactive.py +81 -0
- recallic_engine/brain/memory/reasoning_engine.py +35 -0
- recallic_engine/brain/memory/recall_engine.py +1211 -0
- recallic_engine/brain/memory/reflective/__init__.py +0 -0
- recallic_engine/brain/memory/reflective/reflective_memory.py +58 -0
- recallic_engine/brain/memory/semantic/__init__.py +0 -0
- recallic_engine/brain/memory/semantic/semantic_memory.py +167 -0
- recallic_engine/brain/memory/short_term/__init__.py +0 -0
- recallic_engine/brain/memory/short_term/sensory.py +33 -0
- recallic_engine/brain/memory/truth_engine.py +110 -0
- recallic_engine/brain/memory/update_classifier.py +76 -0
- recallic_engine/brain/memory/updates.py +572 -0
- recallic_engine/brain/memory/working/__init__.py +0 -0
- recallic_engine/brain/memory/working/working_memory.py +74 -0
- recallic_engine/brain/memory_ranking/__init__.py +0 -0
- recallic_engine/brain/memory_ranking/fit_importance.py +91 -0
- recallic_engine/brain/memory_ranking/fit_ranker.py +188 -0
- recallic_engine/brain/memory_ranking/importance_ranker.py +166 -0
- recallic_engine/brain/memory_ranking/importance_weights.default.json +16 -0
- recallic_engine/brain/memory_ranking/importance_weights.prior.json +14 -0
- recallic_engine/brain/memory_ranking/logistic.py +72 -0
- recallic_engine/brain/memory_ranking/ranker.py +414 -0
- recallic_engine/brain/memory_ranking/ranker_model.default.json +54 -0
- recallic_engine/brain/memory_ranking/ranker_model.hash.json +54 -0
- recallic_engine/brain/memory_ranking/ranker_model.prior.json +22 -0
- recallic_engine/brain/memory_ranking/reinforcement_learning.py +57 -0
- recallic_engine/brain/memory_ranking/self_improve.py +187 -0
- recallic_engine/brain/models/__init__.py +0 -0
- recallic_engine/brain/models/model_router.py +189 -0
- recallic_engine/brain/models/onnx_runtime.py +149 -0
- recallic_engine/brain/prediction/__init__.py +0 -0
- recallic_engine/brain/prediction/predictive_recall.py +14 -0
- recallic_engine/brain/utils/__init__.py +0 -0
- recallic_engine/brain/utils/decay_logic.py +27 -0
- recallic_engine/brain/world_model/__init__.py +0 -0
- recallic_engine/brain/world_model/planning_engine.py +47 -0
- recallic_engine/brain/world_model/prediction_engine.py +87 -0
- recallic_engine/brain/world_model/state_inference.py +100 -0
- recallic_engine/brain/world_model/timeline_engine.py +67 -0
- recallic_engine/config.yaml +518 -0
- recallic_engine/embedded.py +65 -0
- recallic_engine/settings.py +115 -0
- recallic_engine/tools/__init__.py +0 -0
- recallic_engine/tools/portable.py +137 -0
- recallic_engine/utils/__init__.py +0 -0
- recallic_engine/utils/internal_client.py +82 -0
- recallic_engine/utils/local_engine.py +136 -0
- recallic_engine/utils/paths.py +29 -0
- recallic_engine-0.1.0.dist-info/METADATA +48 -0
- recallic_engine-0.1.0.dist-info/RECORD +89 -0
- recallic_engine-0.1.0.dist-info/WHEEL +5 -0
- recallic_engine-0.1.0.dist-info/licenses/LICENSE +105 -0
- recallic_engine-0.1.0.dist-info/licenses/NOTICE +19 -0
- recallic_engine-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,796 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Aggregation check: answer-or-decline for questions whose answer is worked out ACROSS memories.
|
|
3
|
+
|
|
4
|
+
"How many weddings did I attend?", "Which came first, the Tame Impala concert or my Denver hike?",
|
|
5
|
+
"How many days after I booked the flight did I arrive?" have no answer phrase inside any one
|
|
6
|
+
memory, so the extractive answer check (features/answer_check.py) cannot confirm them: on the
|
|
7
|
+
aggregation dev set it declined real questions and answered traps at nearly the same rate.
|
|
8
|
+
|
|
9
|
+
What such a question does have is PRESUPPOSITIONS: the events it takes for granted. "Which came
|
|
10
|
+
first, my knitting class or my yoga session?" presupposes a knitting class and a yoga session.
|
|
11
|
+
If the memories support every presupposed event, the question can be worked out from them; if one
|
|
12
|
+
event is supported by nothing (never mentioned, only planned and cancelled, someone else's), the
|
|
13
|
+
honest result is a decline.
|
|
14
|
+
|
|
15
|
+
1. presuppositions(question): rewrite the question into one statement per presupposed event
|
|
16
|
+
("I did attend weddings." / "My knitting class happened." + "My yoga session happened.").
|
|
17
|
+
Rules only; returns None for any question it does not recognise, which then takes the normal path.
|
|
18
|
+
2. An entailment model (natural-language inference: premise = a memory, hypothesis = the statement;
|
|
19
|
+
cross-encoder/nli-deberta-v3-xsmall, 22M-parameter encoder, Apache 2.0, CPU) scores each
|
|
20
|
+
statement against each ranked memory. No LLM.
|
|
21
|
+
3. Every statement entailed by some memory -> answer (the memories are served and the result says the
|
|
22
|
+
answer still has to be worked out). Otherwise decline.
|
|
23
|
+
|
|
24
|
+
Configuration (config.yaml recall.aggregation_check): enabled, model, threshold, memories (how many
|
|
25
|
+
ranked memories are read), max_length, device. How it is applied: RecallEngine.multi_stage_recall.
|
|
26
|
+
"""
|
|
27
|
+
import re
|
|
28
|
+
import threading
|
|
29
|
+
|
|
30
|
+
from recallic_engine import settings
|
|
31
|
+
|
|
32
|
+
_DEFAULT_MODEL = "cross-encoder/nli-deberta-v3-xsmall"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def config():
|
|
36
|
+
from . import modes
|
|
37
|
+
c = settings.get("recall.aggregation_check", {}) or {}
|
|
38
|
+
mode = str(c.get("mode", "rescue")).lower()
|
|
39
|
+
mode = mode if mode in ("rescue", "decide") else "rescue"
|
|
40
|
+
helpful = modes.current() == "helpful" # recall.mode helpful: the check on, in rescue mode
|
|
41
|
+
return {"enabled": bool(c.get("enabled", False)) or helpful, "mode": "rescue" if helpful else mode,
|
|
42
|
+
"model": c.get("model") or _DEFAULT_MODEL,
|
|
43
|
+
"threshold": float(c.get("threshold", 0.5)), "memories": int(c.get("memories", 10)),
|
|
44
|
+
"compute": bool(c.get("compute", True)), "compute_min_support": float(c.get("compute_min_support", 0.9)),
|
|
45
|
+
"max_length": int(c.get("max_length", 256)), "device": c.get("device")}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# ---------------------------------------------------------------- question -> presupposed statements
|
|
49
|
+
|
|
50
|
+
_UNITS = r"(?:days?|weeks?|months?|years?|hours?|minutes?)"
|
|
51
|
+
# words that add nothing to the event itself
|
|
52
|
+
_FILLER = re.compile(r"\b(?:actually|finally|eventually|ever|really|first of all|in total|altogether|so far|overall|"
|
|
53
|
+
r"exactly|roughly|about how|in the end|personally|myself|successfully|officially)\b\s*", re.I)
|
|
54
|
+
# trailing time qualifiers: a memory's text rarely states them (the date is the message's timestamp)
|
|
55
|
+
_TIME_TAIL = re.compile(
|
|
56
|
+
r"\s+(?:(?:in|during|since|throughout|over) (?:the (?:past|last|whole) )?(?:\d{4}|this year|last year|the year|"
|
|
57
|
+
r"the summer|the winter|the spring|the autumn|the fall|the past \w+ \w+)"
|
|
58
|
+
r"|since we started (?:chatting|talking)|this year|last year|so far(?: this year)?"
|
|
59
|
+
r"|(?:on|by|as of|until|before|up to) (?:the )?(?:\d{1,2}(?:st|nd|rd|th)? )?(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?(?: \d{1,2}(?:st|nd|rd|th)?)?(?:,? \d{4})?"
|
|
60
|
+
r"|on \d{4}-\d{2}-\d{2})\s*$", re.I)
|
|
61
|
+
_PAREN = re.compile(r"\s*\([^)]*\)")
|
|
62
|
+
_LEAD = re.compile(r"^(?:the (?:day|time|moment|date)(?: (?:that|when|on which))?|when|the day of)\s+", re.I)
|
|
63
|
+
_DET = r"(?:the|a|an|my|our|his|her|their|this|that|these|those)"
|
|
64
|
+
_IRREGULAR_PAST = ("got|took|ran|went|met|sent|bought|sold|began|did|had|made|told|saw|flew|drove|left|quit|came|gave|"
|
|
65
|
+
"found|heard|wrote|read|paid|spent|won|lost|broke|built|caught|chose|drew|ate|fell|felt|forgot|grew|"
|
|
66
|
+
"held|kept|knew|led|put|rode|said|sang|sat|slept|spoke|stood|swam|taught|thought|threw|woke|wore|"
|
|
67
|
+
"was|were|became|brought|hit|cut|set|let|hurt|shut|hung|rang|rose|shot|stole|struck|swore|tore")
|
|
68
|
+
_FINITE = re.compile(rf"\b(?:\w{{2,}}ed|{_IRREGULAR_PAST})\b", re.I)
|
|
69
|
+
_ING = re.compile(r"^(\w{2,}ing)\b", re.I)
|
|
70
|
+
_NOT_GERUND = {"morning", "evening", "wedding", "meeting", "building", "painting", "training", "booking", "housewarming",
|
|
71
|
+
"thing", "something", "anything", "nothing", "everything", "king", "ring", "spring", "string", "ceiling",
|
|
72
|
+
"sibling", "darling", "pudding", "clothing", "gathering", "opening", "outing", "screening", "tasting",
|
|
73
|
+
"listing", "hearing", "viewing", "fitting", "reading", "writing", "recording", "briefing", "hiking"}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _clean(text):
|
|
77
|
+
t = _PAREN.sub("", str(text or ""))
|
|
78
|
+
t = _FILLER.sub("", t)
|
|
79
|
+
prev = None
|
|
80
|
+
while prev != t:
|
|
81
|
+
prev, t = t, _TIME_TAIL.sub("", t)
|
|
82
|
+
return re.sub(r"\s+", " ", t).strip(" ,.?;:")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _sentence(text):
|
|
86
|
+
t = re.sub(r"\s+", " ", text).strip(" ,.?;:")
|
|
87
|
+
return (t[0].upper() + t[1:] + ".") if t else None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
_AFTER_VERB = re.compile(rf"^(?:{_DET}|to|at|in|on|for|with|from|into|up|out|off|over|back|down|away|about|through|"
|
|
91
|
+
r"me|him|her|them|us|it|abroad|home|\w+ly|[A-Z][\w'\-]*|['\"‘“].*)$")
|
|
92
|
+
_VERB_PREFIX = {"test", "binge", "bulk", "window", "speed", "house", "job", "road", "scuba", "sky", "ice", "rock", "bird"}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _is_gerund(word, following=None):
|
|
96
|
+
"""
|
|
97
|
+
"moving" in "my sister moving to Davao" is the event's verb; "gardening" in "my first gardening
|
|
98
|
+
session" is part of a name. Without a tagger the next word decides: a verb is followed by its
|
|
99
|
+
object or a preposition. Returns True, False, or None when it cannot tell (the phrase ends there).
|
|
100
|
+
"""
|
|
101
|
+
w = (word or "").lower()
|
|
102
|
+
if not (w.endswith("ing") and len(w) > 4):
|
|
103
|
+
return False
|
|
104
|
+
if following is None:
|
|
105
|
+
return None if w not in _NOT_GERUND else False
|
|
106
|
+
return bool(_AFTER_VERB.match(following))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _event(phrase):
|
|
110
|
+
"""
|
|
111
|
+
One presupposed event, as a statement. The phrase is whatever the question used to name it:
|
|
112
|
+
a clause ("I signed the lease", "my friend Liza got her haircut"), a gerund ("ordering the
|
|
113
|
+
cabinets", "me adopting Milo", "my sister moving to Davao") or a noun phrase ("my Denver hike",
|
|
114
|
+
"the Tame Impala concert", "the workshop I attended").
|
|
115
|
+
"""
|
|
116
|
+
t = _LEAD.sub("", _clean(phrase))
|
|
117
|
+
t = _LEAD.sub("", t)
|
|
118
|
+
if not t:
|
|
119
|
+
return None
|
|
120
|
+
low = t.lower()
|
|
121
|
+
if low.startswith("i "): # "I signed the lease"
|
|
122
|
+
return _sentence("I " + t[2:])
|
|
123
|
+
m = re.match(r"^me (\w+ing)\b(.*)$", t, re.I) # "me adopting Milo"
|
|
124
|
+
if m:
|
|
125
|
+
return _sentence(f"I was {m.group(1)}{m.group(2)}")
|
|
126
|
+
t = re.sub(r" that (were|was|got|did|didn't)\b", r" \1", t) # "flights of mine that were cancelled"
|
|
127
|
+
if re.match(rf"^{_DET} ", t, re.I):
|
|
128
|
+
t = re.sub(r"\s+(?:where|when|in which|at which)\b.*$", "", t) # "the follow-up where my cream got adjusted"
|
|
129
|
+
words = t.split()
|
|
130
|
+
if len(words) > 1 and words[0].lower() in _VERB_PREFIX and words[1].lower().endswith("ing"):
|
|
131
|
+
return _sentence("I was " + t[0].lower() + t[1:]) # "test driving the Kia Soul"
|
|
132
|
+
w0 = words[0].lower()
|
|
133
|
+
if w0.endswith("ing") and len(w0) > 4 and (w0 not in _NOT_GERUND or _is_gerund(words[0], words[1] if len(words) > 1 else None)):
|
|
134
|
+
# "ordering the kitchen cabinets", "starting yoga". The person need not have done it with their own hands
|
|
135
|
+
# ("loading the container": the movers did), so the event is also read without a doer.
|
|
136
|
+
return (_sentence("I was " + t[0].lower() + t[1:]), _sentence(t + " happened"))
|
|
137
|
+
m = re.match(rf"^({_DET} .+?) i (\w+)\b(.*)$", t, re.I) # "the workshop I attended"
|
|
138
|
+
if m and " " not in m.group(2):
|
|
139
|
+
return _sentence(f"I {m.group(2)} {m.group(1)[0].lower() + m.group(1)[1:]}{m.group(3)}")
|
|
140
|
+
m = re.match(rf"^({_DET} .+?) ([A-Z][a-z]+) ((?:{_IRREGULAR_PAST}|\w+ed)(?: (?:to|at|in|on|for|with))?)$", t)
|
|
141
|
+
if m: # "the show Alex went to"
|
|
142
|
+
return _sentence(f"{m.group(2)} {m.group(3)} {m.group(1)[0].lower() + m.group(1)[1:]}")
|
|
143
|
+
if _FINITE.search(" ".join(words[1:])): # "my friend Liza got her haircut"
|
|
144
|
+
return _sentence(t)
|
|
145
|
+
happened = _sentence(t + " happened") # "my Denver hike", "the Tame Impala concert"
|
|
146
|
+
for i, w in enumerate(words[1:], 1): # "my sister moving to Davao", "the new phone arriving"
|
|
147
|
+
if i > 5:
|
|
148
|
+
break
|
|
149
|
+
g = _is_gerund(w, words[i + 1] if i + 1 < len(words) else None)
|
|
150
|
+
if g or g is None:
|
|
151
|
+
was = _sentence(" ".join(words[:i]) + " was " + " ".join(words[i:]))
|
|
152
|
+
return was if g else (happened, was) # "my phone screen cracking" / "my first dentist cleaning"
|
|
153
|
+
return happened
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
_ORDINAL = re.compile(r"\b(?:first|second|third|fourth|fifth|initial|final|last|next|latest|earliest|most recent)\s+", re.I)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _did_form(statement):
|
|
160
|
+
""""I was signing the paperwork." -> ("I did sign the paperwork.", "I did signe the paperwork."): the base verb
|
|
161
|
+
needs no tense table; both spellings are tried because "driving" may come from "drive"."""
|
|
162
|
+
m = re.match(r"^(I|We|[A-Z][a-z]+(?: [a-z]+){0,2}) (?:was|were) (\w+?)ing\b(.*)$", statement or "")
|
|
163
|
+
if not m or len(m.group(2)) < 2:
|
|
164
|
+
return ()
|
|
165
|
+
who, stem, rest = m.group(1), m.group(2), m.group(3).rstrip(".")
|
|
166
|
+
if len(stem) > 2 and stem[-1] == stem[-2] and stem[-1] not in "aeiouls":
|
|
167
|
+
stems = (stem[:-1],) # "shopping" -> "shop"
|
|
168
|
+
else:
|
|
169
|
+
stems = (stem, stem + "e") # "signing" -> "sign"; "driving" -> "drive"
|
|
170
|
+
return tuple(_sentence(f"{who} did {x}{rest}") for x in stems)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _alternatives(claim):
|
|
174
|
+
"""
|
|
175
|
+
A claim plus looser phrasings of it, as a tuple (one statement stays a string). "My second haircut
|
|
176
|
+
happened" is also tried as "My haircut happened": which one was first or second is worked out across
|
|
177
|
+
memories; no single memory says it.
|
|
178
|
+
"""
|
|
179
|
+
variants = list(_both(claim, None) or ()) if isinstance(claim, tuple) else [claim]
|
|
180
|
+
variants = [v for v in variants if isinstance(v, str)]
|
|
181
|
+
for v in list(variants):
|
|
182
|
+
variants.extend(_did_form(v))
|
|
183
|
+
for v in list(variants):
|
|
184
|
+
if v and _ORDINAL.search(v):
|
|
185
|
+
variants.append(_sentence(_ORDINAL.sub("", v)))
|
|
186
|
+
variants = list(dict.fromkeys(v for v in variants if v))
|
|
187
|
+
return variants[0] if len(variants) == 1 else tuple(variants) if variants else None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _split_items(text):
|
|
191
|
+
"""'A, B and C' / 'A or B' -> ['A', 'B', 'C']."""
|
|
192
|
+
parts = re.split(r"\s*,\s*(?:and\s+|or\s+)?|\s+(?:and|or)\s+", text)
|
|
193
|
+
return [p.strip(" ,.?;:") for p in parts if p and p.strip(" ,.?;:")]
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _np_like(item):
|
|
197
|
+
w = item.split()[0] if item.split() else ""
|
|
198
|
+
return bool(re.match(rf"^{_DET}$", w, re.I)) or w[:1].isupper() or w[:1] in "'\"‘“" or w[:1].isdigit() or len(item.split()) == 1
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _did(verb_and_rest):
|
|
202
|
+
"""Do-support keeps the base verb, so no tense table is needed: "I did attend weddings"."""
|
|
203
|
+
return _sentence("I did " + verb_and_rest)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
_PRONOUN = r"\b(?:it|them|that one|(?:the|my|his|her|their) (?:(?:first|second|third|last|next|new|other) )?one)\b"
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _both(a, b):
|
|
210
|
+
"""Two readings of one statement (scored separately, the better counts); one when they are the same."""
|
|
211
|
+
out = []
|
|
212
|
+
for x in (a, b):
|
|
213
|
+
for v in (x if isinstance(x, tuple) else (x,)):
|
|
214
|
+
if v and v not in out:
|
|
215
|
+
out.append(v)
|
|
216
|
+
return None if not out else out[0] if len(out) == 1 else tuple(out)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _resolve_it(second, first):
|
|
220
|
+
""""... did I actually run it" after "I signed up for the Lisbon 10K" -> "the Lisbon 10K"."""
|
|
221
|
+
if not re.search(_PRONOUN, second, re.I):
|
|
222
|
+
return second
|
|
223
|
+
starts = [m.start() for m in re.finditer(rf"\b{_DET}\b", first, re.I)]
|
|
224
|
+
noun = first[starts[-1]:].strip(" .") if starts else ""
|
|
225
|
+
if not noun or len(noun.split()) > 5 or re.search(r"\b(?:would|was|were|is|are|had|did|i)\b", noun, re.I):
|
|
226
|
+
return second
|
|
227
|
+
if re.search(r"\b(?:first|second|third|last|next|new|other) one\b", second, re.I): # keep "second": "my second haircut"
|
|
228
|
+
head = _ORDINAL.sub("", re.sub(rf"^{_DET} ", "", noun, flags=re.I)).strip()
|
|
229
|
+
return re.sub(r"\bone\b", head, second, count=1, flags=re.I) if head else second
|
|
230
|
+
return re.sub(_PRONOUN, noun, second, count=1, flags=re.I)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
# who the question is about: "I", "we", a name ("John", "Mel and Dave"), a possessive ("Joanna's scripts",
|
|
234
|
+
# "my sister")
|
|
235
|
+
_SUBJ = (r"(i|we|(?-i:[A-Z][a-z]+)(?:'s \w+)?(?: and (?-i:[A-Z][a-z]+))?|(?:my|his|her|their|our) \w+(?: (?-i:[A-Z][a-z]+))?)")
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _mid(text):
|
|
239
|
+
"""An item moved from the start of the question into the middle of a statement: "Baby showers" -> "baby showers"."""
|
|
240
|
+
words = text.split()
|
|
241
|
+
if words and words[0][:1].isupper() and words[0][1:].islower() and \
|
|
242
|
+
(re.match(rf"^{_DET}$", words[0], re.I) or (len(words) > 1 and words[1][:1].islower())):
|
|
243
|
+
return words[0].lower() + text[len(words[0]):]
|
|
244
|
+
return text
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _state(subject, aux, rest):
|
|
248
|
+
"""("I", "did", "attend weddings") -> "I did attend weddings."; ("John", "has", "injured his ankle")."""
|
|
249
|
+
me = subject.lower() in ("i", "we")
|
|
250
|
+
aux = aux.lower()
|
|
251
|
+
aux = "did" if aux in ("did", "do", "does") else ("have" if me else "has") if aux in ("have", "has") else aux
|
|
252
|
+
return _sentence(f"{'I' if me else subject} {aux} {rest}")
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _counting(q):
|
|
256
|
+
told = r"(?:tell you|told you|mention(?:ed)?|say|said|talk(?:ed)? to you)"
|
|
257
|
+
m = re.match(rf"^how many times (?:did|have|had) i {told} (about |that |having )?(.+)$", q, re.I)
|
|
258
|
+
if m: # the claim is what was told, not the telling
|
|
259
|
+
return [_sentence("I had " + _clean(m.group(2)))] if (m.group(1) or "").strip() == "having" else [_event(m.group(2))]
|
|
260
|
+
m = re.match(rf"^how many (?:of )?(.+?) (?:did|have|had) i {told}(?: about| of)?$", q, re.I)
|
|
261
|
+
if m:
|
|
262
|
+
return [_event(m.group(1))]
|
|
263
|
+
m = re.match(rf"^how many times (did|have|has|had|do|does) {_SUBJ} (.+)$", q, re.I)
|
|
264
|
+
if m: # "How many times did I go to Italy?"
|
|
265
|
+
return [_state(m.group(2), m.group(1), _clean(m.group(3)))]
|
|
266
|
+
m = re.match(rf"^how many (?:different |separate |distinct |total |other )?(.+?) (did|have|has|had|do|does) {_SUBJ} (\w+)\b(.*)$",
|
|
267
|
+
q, re.I)
|
|
268
|
+
if m and not re.match(rf"^{_UNITS}\b", m.group(1), re.I) and m.group(4).lower() not in ("have", "own", "need", "want"):
|
|
269
|
+
things, aux, subject, verb, rest = re.sub(r"^of ", "", m.group(1), flags=re.I), m.group(2), m.group(3), m.group(4), m.group(5)
|
|
270
|
+
rest = re.sub(r"\s+that (?:were|was|are|is)\b.*$", "", rest, flags=re.I).strip()
|
|
271
|
+
lead = re.match(r"^(\w+ing|on|to|in|at|up|out)\b\s*(.*)$", rest) if rest else None
|
|
272
|
+
if lead and (lead.group(1).endswith("ing") or not lead.group(2)): # "finish reading" + books, "been on" + hikes
|
|
273
|
+
verb, rest = f"{verb} {lead.group(1)}", lead.group(2)
|
|
274
|
+
if len(rest.split()) <= 3 and re.search(r"\b(?:about|of|for|to|with|at|in|on|from)$", _clean(rest)):
|
|
275
|
+
body = _clean(f"{verb} {rest} {things}") # "tell you about" + my brother's museum visits
|
|
276
|
+
else:
|
|
277
|
+
body = _clean(f"{verb} {things} {rest}")
|
|
278
|
+
return [_state(subject, aux, body)]
|
|
279
|
+
m = re.match(r"^how many (?:of )?(.+?) (were|was|got|did(?:n't| not)?|have|has|are|is) (.+)$", q, re.I)
|
|
280
|
+
if m and not re.match(rf"^{_UNITS}\b", m.group(1), re.I) and not re.match(r"^times\b", m.group(1), re.I):
|
|
281
|
+
return [_sentence(_clean(f"Some of {m.group(1)} {m.group(2)} {m.group(3)}"))]
|
|
282
|
+
return None
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _ordering(q):
|
|
286
|
+
m = re.match(rf"^which (?:(?:one|of (?:these|them|the two)) )?(?:(\w+(?: \w+)?) )?did {_SUBJ} (\w+)(?: \w+)? "
|
|
287
|
+
r"(?:first|last|earlier|later|next|second|most recently)(?: (?:in|of|during) [^,:]+)?[,:]?\s+(.+)$", q, re.I)
|
|
288
|
+
if m: # "Which city did I visit first, New York or Boston?"
|
|
289
|
+
noun, who, verb, items = m.group(1), m.group(2), m.group(3), _split_items(m.group(4))
|
|
290
|
+
if noun:
|
|
291
|
+
items = [re.sub(r"^the one\b", "the " + noun, i, flags=re.I) for i in items]
|
|
292
|
+
if len(items) >= 2:
|
|
293
|
+
return [_state(who, "did", _clean(f"{verb} {i}")) for i in items]
|
|
294
|
+
m = re.match(rf"^which (?:\w+(?: \w+)? )?did {_SUBJ} (\w+)\b.*?\b(?:after|before|following|prior to) (.+)$", q, re.I)
|
|
295
|
+
if m: # "Which book did I finish next after 'Educated'?"
|
|
296
|
+
return [_state(m.group(1), "did", _clean(f"{m.group(2)} {m.group(3)}"))]
|
|
297
|
+
m = re.match(r"^(?:which|what) (?:\w+ )?(?:came|happened|was|occurred|took place|did i do) "
|
|
298
|
+
r"(?:first|later|earlier|last|second|most recently|earliest|latest)[,:]?\s+(.+)$", q, re.I)
|
|
299
|
+
if m: # "Which came first, A or B?"
|
|
300
|
+
items = [i for i in re.split(r"\s+or\s+|\s*,\s*(?:or\s+)?", m.group(1)) if i.strip(" ,.?")]
|
|
301
|
+
if len(items) >= 2:
|
|
302
|
+
return [_event(i) for i in items]
|
|
303
|
+
m = re.match(rf"^in what order did {_SUBJ} (?:first |then |originally )?(\w+) (?:the following \w+[:,]?\s*)?(.+)$", q, re.I)
|
|
304
|
+
if m: # "In what order did I install A and tile B?"
|
|
305
|
+
who, verb, items = m.group(1), m.group(2), _split_items(m.group(3))
|
|
306
|
+
_did = lambda body: _state(who, "did", body) # noqa: E731 (the question's own subject)
|
|
307
|
+
if items:
|
|
308
|
+
out = [_did(_clean(f"{verb} {items[0]}"))]
|
|
309
|
+
# "have meals with Maya, Laila and Karim": the later names share "meals with"
|
|
310
|
+
shared = re.match(r"^(.+\b(?:with|on|at|in|for|from|to|of|by)) \S", items[0], re.I)
|
|
311
|
+
for i in items[1:]:
|
|
312
|
+
if shared and not re.search(r"\b(?:with|on|at|in|for|from|to|of|by)\b", i, re.I) and \
|
|
313
|
+
not re.match(rf"^{_DET}\b", i, re.I) and (i[:1].isupper() or len(i.split()) == 1):
|
|
314
|
+
out.append((_did(_clean(f"{verb} {shared.group(1)} {i}")), _did(_clean(f"{verb} {i}"))))
|
|
315
|
+
continue
|
|
316
|
+
# a later item is a noun phrase sharing the verb ("... and the Forum") or its own verb phrase
|
|
317
|
+
# ("... and tile the bathroom floor"); when unclear both readings are scored and the better counts
|
|
318
|
+
out.append(_did(_clean(f"{verb} {i}")) if _np_like(i) else (_did(_clean(i)), _did(_clean(f"{verb} {i}"))))
|
|
319
|
+
return out
|
|
320
|
+
return None
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _pair(body, between=False):
|
|
324
|
+
"""'A and B' (between ...) / 'A to B' / 'A until B' (from ...) -> (A, B), cutting where the second event starts."""
|
|
325
|
+
body = re.sub(r",\s*(?:what|how)\b.*$", "", body, flags=re.I) # "... to B, what was the duration in weeks?"
|
|
326
|
+
link = r"(?:and)" if between else r"(?:to|until|till|and)"
|
|
327
|
+
cut = re.search(rf",?\s+{link}\s+(?=(?:the (?:day|time|moment|arrival)|when|me |my |i |{_DET} |\w+ing\b))", body, re.I) \
|
|
328
|
+
or re.search(rf",?\s+{link}\s+", body, re.I)
|
|
329
|
+
return (body[:cut.start()], body[cut.end():]) if cut else None
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _span(text):
|
|
333
|
+
"""The two events after "between ..." / "from ..." in a question, or None."""
|
|
334
|
+
m = re.search(r"\b(between|from) (.+)$", text, re.I)
|
|
335
|
+
pair = m and _pair(m.group(2), between=m.group(1).lower() == "between")
|
|
336
|
+
return _two_events(*pair) if pair else None
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _two_events(a, b):
|
|
340
|
+
shared = re.match(r"^(.*?\b\w+ing) \S", _clean(a)) # "Maria adopting Coco and Shadow": Shadow too
|
|
341
|
+
if shared and len(b.split()) <= 3 and not _FINITE.search(b) and not re.search(r"\w+ing\b", b):
|
|
342
|
+
return [_event(a), _both(_event(f"{shared.group(1)} {b}"), _event(b))]
|
|
343
|
+
return [_event(a), _both(_event(b), _event(_resolve_it(b, _clean(a))))]
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _then(a, b):
|
|
347
|
+
"""The second event of "... after A did <b>": b is "I actually run it" or "his new tablet arrive"."""
|
|
348
|
+
b = _clean(b)
|
|
349
|
+
s = re.match(r"^(i|we) (.+)$", b, re.I)
|
|
350
|
+
if s:
|
|
351
|
+
return _both(_did(s.group(2)), _did(_resolve_it(s.group(2), _clean(a))))
|
|
352
|
+
# "his new tablet arrive": the subject ends where the base verb starts, which rules cannot
|
|
353
|
+
# tell without a tagger, so each split is scored and the best counts
|
|
354
|
+
words = _resolve_it(b, _clean(a)).split()
|
|
355
|
+
return tuple(_sentence(" ".join(words[:i]) + " did " + " ".join(words[i:])) for i in range(1, min(len(words), 5))) or None
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _time_between(q):
|
|
359
|
+
m = re.match(rf"^how (?:many {_UNITS}(?: and {_UNITS})?|long|much time)\b(.*)$", q, re.I)
|
|
360
|
+
if not m:
|
|
361
|
+
return None
|
|
362
|
+
rest = _PAREN.sub("", m.group(1)).strip()
|
|
363
|
+
rest = re.sub(r"^(?:(?:had |have |has )?(?:passed|elapsed|went by|gone by|were there|was there|was it|are there|is it|"
|
|
364
|
+
r"did it take|did i wait|apart were|separated)\s*)+", "", rest, flags=re.I)
|
|
365
|
+
if re.match(r"^(?:between|from) ", rest, re.I) and _span(rest):
|
|
366
|
+
return _span(rest)
|
|
367
|
+
m = re.match(r"^(?:after|before|since|following) (.+?) (?:did|was|were|had) (.+)$", rest, re.I)
|
|
368
|
+
if m: # "... after I signed up for X did I actually run it?"
|
|
369
|
+
return [_event(m.group(1)), _then(m.group(1), m.group(2))]
|
|
370
|
+
return None
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
# ---------------------------------------------------------------- freer phrasings
|
|
374
|
+
# The rules above read the textbook forms. People also front the topic ("Baby showers - how many have I
|
|
375
|
+
# attended?"), ask for a count without "how many" ("What's the number of ...", "Count the ...", "How often
|
|
376
|
+
# ..."), or put the events first ("I signed the lease - how many days later did I move in?"). These are
|
|
377
|
+
# reduced to: what kind of question, which phrases name the events, and which verb the question applies to them.
|
|
378
|
+
|
|
379
|
+
_BREAK = re.compile(r"\s+[-–—]\s+|:\s+")
|
|
380
|
+
_CUE = re.compile(r"\b(?:how many|how often|how long|how much time|which|what(?:'s| is| was)?|put|order|number of|gap|total)\b", re.I)
|
|
381
|
+
_MONTH = r"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?"
|
|
382
|
+
_PAST = rf"(?:\w{{2,}}ed|{_IRREGULAR_PAST}|been|gone|done|taken|seen|eaten|given|written|flown|driven|bought|run|won)"
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _normalise(q):
|
|
386
|
+
q = re.sub(r",? please$", "", q.rstrip(" .!?"), flags=re.I)
|
|
387
|
+
q = re.sub(r",? (?:with|without) [^,]+? (?:included|excluded|left out)\b", "", q, flags=re.I)
|
|
388
|
+
q = re.sub(r"^(?:can you |could you )?(?:tell me|give me|do you know|remind me)\s+", "", q, flags=re.I)
|
|
389
|
+
q = re.sub(rf"^in (?:{_UNITS})(?: \(?and {_UNITS}\)?)?,\s*", "", q, flags=re.I) # "In weeks and days, how long ..."
|
|
390
|
+
q = re.sub(r"^(?:including|counting|leaving|not counting|excluding|with|without) [^,]+,\s*", "", q, flags=re.I)
|
|
391
|
+
q = re.sub(rf"\b(?:on )?{_MONTH} \d{{1,2}}(?:st|nd|rd|th)?,\s+", "", q, flags=re.I) # "From June 7, my first ..."
|
|
392
|
+
q = re.sub(rf"^on {_MONTH} \d{{1,2}}(?:st|nd|rd|th)?,? ", "", q, flags=re.I)
|
|
393
|
+
# past only: "How often does John take his kids to the park?" asks for a habit, which one memory states
|
|
394
|
+
q = re.sub(r"\bhow often(?= (?:did|have|has|had|was|were)\b)", "how many times", q, flags=re.I)
|
|
395
|
+
q = re.sub(r"\b(?:what's|what is|what was) the (?:total )?number of\b", "how many", q, flags=re.I)
|
|
396
|
+
q = re.sub(r"\b(?:what's|what is|what was) the (?:total )?number\b", "how many", q, flags=re.I)
|
|
397
|
+
q = re.sub(r"^(?:count )?the (?:total )?number of\b", "how many", q, flags=re.I)
|
|
398
|
+
q = re.sub(r"\b(?:separate |different |distinct )?(?:occasions|times|instances) (?:on which|when|that|where) ", "times ", q, flags=re.I)
|
|
399
|
+
q = re.sub(r",\s*whether\b.*$", "", q, flags=re.I) # "..., whether matcha or ramen bowls"
|
|
400
|
+
m = re.match(r"^((?:for|at|in|with|to|on|during) [^,]+),\s*(how many .+)$", q, re.I) # "For my brother, how many ..."
|
|
401
|
+
if m:
|
|
402
|
+
q = f"{m.group(2)} {m.group(1)[0].lower() + m.group(1)[1:]}"
|
|
403
|
+
return q[:1].upper() + q[1:] if q else q
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _relative(text):
|
|
407
|
+
""""weddings I've been to" -> "I have been to weddings."; "gifts I bought for my mom" -> "I bought gifts for my mom."."""
|
|
408
|
+
m = re.match(r"^(?:the |my |all the )?(.+?),? (?:that |which )?\b(i|we)('ve| have| had)? (.+)$", text.strip(), re.I)
|
|
409
|
+
if not m:
|
|
410
|
+
return None
|
|
411
|
+
thing, who, aux, rest = m.group(1), m.group(2), (m.group(3) or "").strip(" '"), _clean(m.group(4))
|
|
412
|
+
if not rest or not re.match(rf"^(?:had |have )?{_PAST}\b", rest, re.I) and not aux:
|
|
413
|
+
return None
|
|
414
|
+
lead = re.match(r"^((?:had|have) )?(\w+)\s*(.*)$", rest)
|
|
415
|
+
aux = "have" if aux == "ve" else aux or (lead.group(1) or "").strip()
|
|
416
|
+
verb, tail = lead.group(2), lead.group(3)
|
|
417
|
+
who = "I" if who.lower() in ("i", "we") else who
|
|
418
|
+
thing = _mid(thing)
|
|
419
|
+
if len(tail.split()) <= 2 and (not tail or re.search(r"\b(?:to|at|in|on|for|with|about|of|from|up|out)$", tail)):
|
|
420
|
+
body = f"{verb} {tail} {thing}" # "been to" + weddings
|
|
421
|
+
else:
|
|
422
|
+
body = f"{verb} {thing} {tail}" # "bought" + gifts + "for my mom"
|
|
423
|
+
return _sentence(" ".join(x for x in (who, aux, _clean(body)) if x))
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _applied(who, verb, item, base=False):
|
|
427
|
+
"""The question's own verb applied to one item: ("I", "finished", "'Deep Work'") -> "I finished 'Deep Work'."."""
|
|
428
|
+
item = _clean(item)
|
|
429
|
+
first = item.split()[0] if item else ""
|
|
430
|
+
following = item.split()[1] if len(item.split()) > 1 else None
|
|
431
|
+
doing = first.lower().endswith("ing") and len(first) > 4 and (first.lower() not in _NOT_GERUND or _is_gerund(first, following))
|
|
432
|
+
if not verb or verb.lower() in ("did", "do", "done") or re.match(r"^(?:i|me) ", item, re.I) or doing:
|
|
433
|
+
if verb and verb.lower() in ("did", "do", "done") and not doing and not re.match(r"^(?:i|me) ", item, re.I) \
|
|
434
|
+
and not _np_like(item):
|
|
435
|
+
return _state(who, "did", item) # "what did I do first: install the skylight or ..."
|
|
436
|
+
return _event(item) # the item is itself an event
|
|
437
|
+
item = _mid(item)
|
|
438
|
+
return _state(who, "did", f"{verb} {item}") if base else _sentence(f"{'I' if who.lower() in ('i', 'we') else who} {verb} {item}")
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def _free_ordering(topic, ask, q):
|
|
442
|
+
m = re.match(rf"^did {_SUBJ} (.+?) (?:before or after|after or before|before|after) (.+?)(?:,.*)?$", q, re.I)
|
|
443
|
+
if m: # "Did I have the scan before or after starting the infusions?"
|
|
444
|
+
return [_state(m.group(1), "did", _clean(m.group(2))), _event(m.group(3))]
|
|
445
|
+
m = re.match(r"^(?:after|following) (.+?), which .*?\b(i|we) (\w+)$", q, re.I) # "After 'Educated', which book was the next one I finished?"
|
|
446
|
+
if m:
|
|
447
|
+
return [_applied(m.group(2), m.group(3), m.group(1))]
|
|
448
|
+
if topic is None:
|
|
449
|
+
m = re.match(rf"^what (?:was|is) the order in which {_SUBJ} (\w+) (.+)$", q, re.I)
|
|
450
|
+
if m: # "What was the order in which I sent A, B and C?"
|
|
451
|
+
return [_applied(m.group(1), m.group(2), i) for i in _split_items(m.group(3))]
|
|
452
|
+
m = re.match(r"^what (?:was|is) the order of (.+)$", q, re.I)
|
|
453
|
+
if m: # "What was the order of me clearing the attic and cleaning the gutters?"
|
|
454
|
+
items = _split_items(re.sub(r"^me ", "", m.group(1), flags=re.I))
|
|
455
|
+
lead = re.match(r"^(\w+ing) ", items[0]) if items else None
|
|
456
|
+
out = [_event(items[0])] if items else []
|
|
457
|
+
for i in items[1:]: # a later item may share the first one's verb
|
|
458
|
+
out.append(_both(_event(i), _event(f"{lead.group(1)} {i}")) if lead and not _is_gerund(i.split()[0], "the") else _event(i))
|
|
459
|
+
return out
|
|
460
|
+
m = re.match(r"^between (.+?), which\b(.*)$", q, re.I) # "Between A and B, which one came first?"
|
|
461
|
+
if m:
|
|
462
|
+
topic, ask = m.group(1), "which" + m.group(2)
|
|
463
|
+
else:
|
|
464
|
+
return None
|
|
465
|
+
if re.match(r"^(?:i|we) ", topic, re.I) and re.search(r"\b(?:next|after that|afterwards)\b", ask, re.I):
|
|
466
|
+
return [_event(topic)] # "I finished 'Educated' - what's the next book I finished after that?"
|
|
467
|
+
items = _split_items(topic)
|
|
468
|
+
if not items:
|
|
469
|
+
return None
|
|
470
|
+
who, verb, base = "I", None, False
|
|
471
|
+
m = re.search(rf"\bin (?:the )?order (?:that |in which )?{_SUBJ} (\w+)", ask, re.I) # "put them in the order I finished them"
|
|
472
|
+
if m:
|
|
473
|
+
who, verb = m.group(1), m.group(2)
|
|
474
|
+
else:
|
|
475
|
+
m = re.search(rf"\bwhich (?:\w+ )?did {_SUBJ} (\w+)", ask, re.I) # "which car did I own earlier"
|
|
476
|
+
if m:
|
|
477
|
+
who, verb, base = m.group(1), m.group(2), True
|
|
478
|
+
else:
|
|
479
|
+
m = re.search(rf"\bwhich (?:was|were|got) ({_PAST}) \w+ by (me|us)\b", ask, re.I) # "which was shipped first by me"
|
|
480
|
+
if m:
|
|
481
|
+
verb = m.group(1)
|
|
482
|
+
elif re.search(r"\bwas mine\b", ask, re.I): # "which of these cars was mine first"
|
|
483
|
+
return [_sentence(f"{_clean(i)} was mine") for i in items]
|
|
484
|
+
return [_applied(who, verb, i, base) for i in items]
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _free_time(topic, ask, q):
|
|
488
|
+
if topic is not None:
|
|
489
|
+
if re.match(r"^(?:from|between) ", topic, re.I) and _span(topic): # "From A to B - how many days was that?"
|
|
490
|
+
return _span(topic)
|
|
491
|
+
m = re.search(r"\blater (?:did|was|were) (.+)$", ask, re.I) # "A - how many days later did I B?"
|
|
492
|
+
if m:
|
|
493
|
+
return [_event(topic), _then(topic, m.group(1))]
|
|
494
|
+
m = re.search(r"\bafter (.+?) (?:was|is|did) (?:that|it|this)(?: happen)?$", ask, re.I) # "B - how many days after A was that?"
|
|
495
|
+
if m:
|
|
496
|
+
return [_event(m.group(1)), _event(topic)]
|
|
497
|
+
both = re.split(r",?\s+and\s+(?:later |then |eventually |finally |afterwards )?", topic, maxsplit=1)
|
|
498
|
+
if len(both) == 2: # "A and later B - how many days apart were those?"
|
|
499
|
+
a, b = both
|
|
500
|
+
if re.match(rf"^(?:{_PAST})\b", _clean(b), re.I) and re.match(r"^(i|we) ", a, re.I):
|
|
501
|
+
b = "I " + _clean(b) # "... and later got back from the meeting"
|
|
502
|
+
return [_event(a), _both(_event(b), _event(_resolve_it(b, _clean(a))))]
|
|
503
|
+
return None
|
|
504
|
+
if _span(q): # "How long was it between A and B?"
|
|
505
|
+
return _span(q)
|
|
506
|
+
m = re.search(r"\bhow long after (.+?) did (.+)$", q, re.I)
|
|
507
|
+
if m:
|
|
508
|
+
return [_event(m.group(1)), _then(m.group(1), m.group(2))]
|
|
509
|
+
return None
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _free_counting(topic, ask, q):
|
|
513
|
+
if topic is None:
|
|
514
|
+
m = re.match(r"^(?:count|how many)(?: up)?(?: the| my)? times (?:that )?(.+)$", q, re.I) # "Count the times I ..."
|
|
515
|
+
if m and re.match(rf"^{_SUBJ} ", m.group(1), re.I):
|
|
516
|
+
return [_event(m.group(1))]
|
|
517
|
+
m = re.match(r"^how many times (was|were) (.+?) (\w+ed)$", q, re.I) # "How often was an appointment of mine cancelled?"
|
|
518
|
+
if m:
|
|
519
|
+
return [_sentence(f"{m.group(2)} {m.group(1)} {m.group(3)}")]
|
|
520
|
+
m = re.match(r"^(?:count(?: up)?|how many)\s+(.+)$", q, re.I) # "Count the workshops I went to", "how many weddings I've been to"
|
|
521
|
+
if m: # a bare "how many X does Y have" is one fact, not a count of events
|
|
522
|
+
counted = q.lower().startswith("count")
|
|
523
|
+
return [_relative(m.group(1)) or (_event(re.sub(r"^the ", "my ", m.group(1), flags=re.I)) if counted else None)]
|
|
524
|
+
return None
|
|
525
|
+
topic = re.sub(r"^count(?: up)?\s+", "", topic, flags=re.I)
|
|
526
|
+
told = re.match(r"^(?:i|we) (?:told you about|mentioned|talked about|brought up) (.+)$", topic, re.I)
|
|
527
|
+
if told: # "I told you about my brother's museum visits - how many of them?"
|
|
528
|
+
return [_event(told.group(1))]
|
|
529
|
+
m = re.match(rf"^how many(?: times)?(?: of them)? (did|have|has|had|do|does) {_SUBJ}\b(.*)$", ask, re.I)
|
|
530
|
+
if m: # "Baby showers - how many have I attended?"
|
|
531
|
+
aux, who, rest = m.group(1), m.group(2), _clean(m.group(3))
|
|
532
|
+
rest = re.sub(r"\s*\b(?:it|that|them|those|this)$", "", rest).strip()
|
|
533
|
+
if rest.lower() in ("do", "done", "did", ""): # "Getting a flu shot - how many times have I done that?"
|
|
534
|
+
return [_sentence("I was " + _mid(_clean(topic))) if topic.split()[0].lower().endswith("ing") else _event(topic)]
|
|
535
|
+
if re.search(r"\bthere$", rest): # "Italy - how many times have I gone there?"
|
|
536
|
+
return [_state(who, aux, re.sub(r"\bthere$", "to " + _mid(_clean(topic)), rest))]
|
|
537
|
+
return [_state(who, aux, f"{rest} {_mid(_clean(topic))}")]
|
|
538
|
+
m = re.match(rf"^how many {_SUBJ} ({_PAST})$", _clean(ask), re.I) # "... - what's the number I actually had?"
|
|
539
|
+
if m:
|
|
540
|
+
return [_applied(m.group(1), m.group(2), topic)]
|
|
541
|
+
return [_relative(topic) or _event(re.sub(r"^the ", "my ", topic, flags=re.I))] # "Trips that I cancelled - how many were there?"
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _free(q):
|
|
545
|
+
low = q.lower()
|
|
546
|
+
if re.search(rf"how (?:long|much time)|how many {_UNITS}\b|\bgap\b", low):
|
|
547
|
+
kind = "time_between"
|
|
548
|
+
elif re.search(r"\border\b|\bbefore or after\b|\bwhich\b.*\b(?:first|earlier|earliest|later|latest|next|before|after)\b|"
|
|
549
|
+
r"\bwhat(?:'s| is| was)? .*\b(?:first|next)\b", low):
|
|
550
|
+
kind = "ordering"
|
|
551
|
+
elif re.search(r"\bhow many\b|\bcount\b|\btotal\b", low):
|
|
552
|
+
kind = "counting"
|
|
553
|
+
else:
|
|
554
|
+
return None
|
|
555
|
+
topic, ask = None, q
|
|
556
|
+
parts = _BREAK.split(q, maxsplit=1)
|
|
557
|
+
if len(parts) == 2:
|
|
558
|
+
first, second = (x.strip(" ,.?") for x in parts)
|
|
559
|
+
if _CUE.search(second) and not re.match(r"^(?:how|which|what|put)\b", first, re.I):
|
|
560
|
+
topic, ask = first, second # "Baby showers - how many have I attended?"
|
|
561
|
+
elif _CUE.search(first):
|
|
562
|
+
topic, ask = second, first # "Which was earlier: A or B?"
|
|
563
|
+
if topic is not None and not re.search(r"\b(?:it|that|them|those|there|these)\b", ask, re.I):
|
|
564
|
+
for kind_, rule_ in (("time_between", _time_between), ("ordering", _ordering), ("counting", _counting)):
|
|
565
|
+
claims = rule_(ask[:1].upper() + ask[1:]) # "home reno check - how many walls did I demolish?"
|
|
566
|
+
if claims and all(claims):
|
|
567
|
+
return kind_, claims
|
|
568
|
+
rule = {"time_between": _free_time, "ordering": _free_ordering, "counting": _free_counting}[kind]
|
|
569
|
+
claims = rule(topic, ask, q)
|
|
570
|
+
return (kind, claims) if claims and all(claims) else None
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def presuppositions(question):
|
|
574
|
+
"""
|
|
575
|
+
{"kind": "counting" | "ordering" | "time_between", "claims": [...]} for a question answered by
|
|
576
|
+
counting, ordering or subtracting across memories, else None. Each claim is a statement (or a tuple
|
|
577
|
+
of alternative phrasings of one statement) that some memory must support.
|
|
578
|
+
"""
|
|
579
|
+
q = re.sub(r"\s+", " ", str(question or "")).strip().rstrip("?.! ").strip()
|
|
580
|
+
q = q.replace("’", "'")
|
|
581
|
+
q = re.sub(r"^(?:apart from|besides|other than|excluding|not counting) [^,]+,\s*", "", q, flags=re.I)
|
|
582
|
+
q = re.sub(r"^(?:hey|hi|ok|okay|so|and|also|by the way|quick question)[,:]?\s+", "", q, flags=re.I)
|
|
583
|
+
found = None
|
|
584
|
+
for text in dict.fromkeys((q, _normalise(q))): # as asked, then with the wording normalised
|
|
585
|
+
for kind, rule in (("time_between", _time_between), ("ordering", _ordering), ("counting", _counting)):
|
|
586
|
+
claims = rule(text)
|
|
587
|
+
if claims and all(claims):
|
|
588
|
+
found = (kind, claims)
|
|
589
|
+
break
|
|
590
|
+
if found:
|
|
591
|
+
break
|
|
592
|
+
found = found or _free(_normalise(q))
|
|
593
|
+
if found:
|
|
594
|
+
claims = [_alternatives(c) for c in found[1]]
|
|
595
|
+
if all(claims):
|
|
596
|
+
return {"kind": found[0], "claims": claims}
|
|
597
|
+
return None
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
# ---------------------------------------------------------------- entailment
|
|
601
|
+
|
|
602
|
+
class EntailmentChecker:
|
|
603
|
+
"""Scores (memory, statement) pairs with an NLI cross-encoder: P(the memory entails the statement)."""
|
|
604
|
+
_instances = {}
|
|
605
|
+
_lock = threading.Lock()
|
|
606
|
+
|
|
607
|
+
def __init__(self, model_name, max_length=256, device=None):
|
|
608
|
+
from sentence_transformers import CrossEncoder
|
|
609
|
+
self.model_name = model_name
|
|
610
|
+
self.model = CrossEncoder(model_name, max_length=max_length, device=device)
|
|
611
|
+
labels = {str(v).lower(): int(k) for k, v in self.model.model.config.id2label.items()}
|
|
612
|
+
if "entailment" not in labels:
|
|
613
|
+
raise ValueError(f"{model_name} is not an NLI model (labels: {sorted(labels)})")
|
|
614
|
+
self._entail = labels["entailment"]
|
|
615
|
+
self._infer_lock = threading.Lock()
|
|
616
|
+
|
|
617
|
+
@classmethod
|
|
618
|
+
def from_config(cls):
|
|
619
|
+
"""The configured checker, or None if disabled or unavailable (logged once)."""
|
|
620
|
+
cfg = config()
|
|
621
|
+
if not cfg["enabled"]:
|
|
622
|
+
return None
|
|
623
|
+
key = (cfg["model"], cfg["max_length"], cfg["device"])
|
|
624
|
+
with cls._lock:
|
|
625
|
+
if key not in cls._instances:
|
|
626
|
+
try:
|
|
627
|
+
cls._instances[key] = cls(*key)
|
|
628
|
+
except Exception as e: # missing sentence-transformers/torch, no network for the first download, ...
|
|
629
|
+
print(f"[AggregationCheck] disabled: cannot load {cfg['model']}: {e}")
|
|
630
|
+
cls._instances[key] = None
|
|
631
|
+
return cls._instances[key]
|
|
632
|
+
|
|
633
|
+
def entailment(self, pairs):
|
|
634
|
+
if not pairs:
|
|
635
|
+
return []
|
|
636
|
+
with self._infer_lock:
|
|
637
|
+
scores = self.model.predict(list(pairs), apply_softmax=True, show_progress_bar=False)
|
|
638
|
+
return [float(row[self._entail]) for row in scores]
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def _as_speaker(statement, speaker):
|
|
642
|
+
""""John has injured his ankle." as John himself would say it: "I have injured my ankle." (or None)."""
|
|
643
|
+
if not speaker or not re.search(rf"\b{re.escape(speaker)}\b", statement):
|
|
644
|
+
return None
|
|
645
|
+
name = re.escape(speaker)
|
|
646
|
+
t = re.sub(rf"\b{name}'s\b", "my", statement)
|
|
647
|
+
t = re.sub(rf"\b{name} has\b", "I have", t)
|
|
648
|
+
t = re.sub(rf"\b{name} is\b", "I am", t)
|
|
649
|
+
t = re.sub(rf"\b{name} was\b", "I was", t)
|
|
650
|
+
t = re.sub(rf"^{name}\b", "I", t)
|
|
651
|
+
t = re.sub(rf"\b{name}\b", "me", t)
|
|
652
|
+
if t.startswith("I ") or t.startswith("My ") or " my " in t:
|
|
653
|
+
t = re.sub(r"\b(?:his|her|their)\b", "my", t)
|
|
654
|
+
return _sentence(t)
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
# A memory that only records a plan ("booked flights to goa for march!!", "signed up for the marathon",
|
|
658
|
+
# "planning to visit Hampi next week") says the event was arranged, not that it happened. The entailment
|
|
659
|
+
# model reads "booked flights to Goa" as "flew to Goa", which answered "How many times did I fly to Goa?"
|
|
660
|
+
# for a trip that was cancelled. So a plan-only memory cannot support a claim that the event happened,
|
|
661
|
+
# unless the claim itself is about the plan ("How many days after booking the flights did I cancel them?").
|
|
662
|
+
_PLAN = re.compile(r"\b(?:book(?:ed|ing)?|reserv(?:ed|ing)|register(?:ed|ing)|sign(?:ed|ing) up|signed-up|schedul(?:ed|ing)|"
|
|
663
|
+
r"plan(?:ned|ning|s)?|intend(?:ed|ing)?|bought tickets|got tickets|tickets for|pre-?ordered)\b", re.I)
|
|
664
|
+
# "will", "going to" and the like only mark a plan when a future time is named ("I will never forget it" is not one)
|
|
665
|
+
_WEAK_PLAN = re.compile(r"\b(?:will|'ll|going to|gonna|hoping to|want to|thinking (?:of|about)|my next)\b", re.I)
|
|
666
|
+
_FUTURE = re.compile(r"\b(?:tomorrow|next (?:week|month|year|weekend|monday|tuesday|wednesday|thursday|friday|saturday|sunday)|"
|
|
667
|
+
r"this (?:weekend|coming)|upcoming|soon|later this|in (?:a|two|three|few) (?:days|weeks|months)|"
|
|
668
|
+
r"(?:for|in|on|by) (?:the )?(?:\d{1,2}(?:st|nd|rd|th)?(?: of)? )?"
|
|
669
|
+
r"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\b)", re.I)
|
|
670
|
+
_DONE = re.compile(r"\b(?:today|tonight|this (?:morning|afternoon|evening)|just|finally|got back|came back|"
|
|
671
|
+
r"returned|yesterday|earlier today)\b", re.I)
|
|
672
|
+
_ABOUT_PLANS = re.compile(r"\b(?:book|reserv|regist|sign(?:ed|ing)? up|schedul|plan|cancel|postpon|resched|"
|
|
673
|
+
r"call(?:ed)? off|said i'?d|told you|intend)", re.I)
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def plan_only(text):
|
|
677
|
+
"""True when a memory only records an arrangement for the future, not the event itself."""
|
|
678
|
+
t = str(text or "")
|
|
679
|
+
future = bool(_FUTURE.search(t))
|
|
680
|
+
return (bool(_PLAN.search(t)) and (future or not _DONE.search(t))) or (bool(_WEAK_PLAN.search(t)) and future)
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def check(checker, question, memories, threshold, read=None, speaker=None):
|
|
684
|
+
"""
|
|
685
|
+
None when the question is not an aggregation question. Otherwise
|
|
686
|
+
{"kind", "supported": bool, "claims": [{"statement", "support", "memory"}]}: for each presupposed
|
|
687
|
+
event, the best entailment probability over the memories and the id of that memory.
|
|
688
|
+
`read(memory) -> text` lets the caller decide how a memory is read (default: its content);
|
|
689
|
+
`speaker(memory) -> name` lets a statement about that person also be read in the first person
|
|
690
|
+
("John has injured his ankle" against John's own "I twisted my ankle again").
|
|
691
|
+
"""
|
|
692
|
+
parsed = presuppositions(question)
|
|
693
|
+
if parsed is None or not memories:
|
|
694
|
+
return None
|
|
695
|
+
texts = [(read(m) if read else m.get("content", "")) or "" for m in memories]
|
|
696
|
+
usable = [(m, t) for m, t in zip(memories, texts) if t.strip()]
|
|
697
|
+
report = []
|
|
698
|
+
for claim in parsed["claims"]:
|
|
699
|
+
variants = claim if isinstance(claim, tuple) else (claim,)
|
|
700
|
+
pairs, owners = [], []
|
|
701
|
+
for statement in variants:
|
|
702
|
+
for m, t in usable:
|
|
703
|
+
for hyp in (statement, _as_speaker(statement, speaker(m)) if speaker else None):
|
|
704
|
+
if hyp:
|
|
705
|
+
pairs.append((t, hyp))
|
|
706
|
+
owners.append((m.get("id"), statement))
|
|
707
|
+
best, best_memory, best_statement, discounted = 0.0, None, variants[0], None
|
|
708
|
+
text_of = {m.get("id"): t for m, t in usable}
|
|
709
|
+
support_by_memory = {}
|
|
710
|
+
for (mid, statement), score in zip(owners, checker.entailment(pairs)):
|
|
711
|
+
plan = not _ABOUT_PLANS.search(statement) and plan_only(text_of.get(mid))
|
|
712
|
+
if not plan:
|
|
713
|
+
support_by_memory[mid] = max(score, support_by_memory.get(mid, 0.0))
|
|
714
|
+
if score > best and plan:
|
|
715
|
+
discounted = discounted if discounted and discounted[1] >= score else (mid, score)
|
|
716
|
+
continue
|
|
717
|
+
if score > best:
|
|
718
|
+
best, best_memory, best_statement = score, mid, statement
|
|
719
|
+
entry = {"statement": best_statement, "support": round(best, 3), "memory": best_memory,
|
|
720
|
+
# every memory that supports the event (not only the best): computed answers need to know
|
|
721
|
+
# whether the event happened on one date or several
|
|
722
|
+
"supporters": {m: round(sc, 3) for m, sc in sorted(support_by_memory.items(), key=lambda x: -x[1])
|
|
723
|
+
if sc >= threshold}}
|
|
724
|
+
ordinal = next((o for v in variants for o in ("first", "last") if re.search(rf"\b{o}\b", v, re.I)), None)
|
|
725
|
+
if ordinal:
|
|
726
|
+
entry["ordinal"] = ordinal
|
|
727
|
+
if discounted and discounted[1] > best:
|
|
728
|
+
entry["plan_only"] = {"memory": discounted[0], "support": round(discounted[1], 3)}
|
|
729
|
+
report.append(entry)
|
|
730
|
+
return {"kind": parsed["kind"], "supported": all(c["support"] >= threshold for c in report), "claims": report}
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
# ---------------------------------------------------------------- computed answers
|
|
734
|
+
|
|
735
|
+
def _day(ts):
|
|
736
|
+
from datetime import datetime, timezone
|
|
737
|
+
return datetime.fromtimestamp(float(ts), tz=timezone.utc).date()
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
def _span_text(days, kind_hint=""):
|
|
741
|
+
"""41 -> "41 days (5 weeks 6 days)"; under a week just days; with whole months when 60 days or more."""
|
|
742
|
+
out = f"{days} day{'s' if days != 1 else ''}"
|
|
743
|
+
extra = []
|
|
744
|
+
if days >= 7:
|
|
745
|
+
w, d = divmod(days, 7)
|
|
746
|
+
extra.append(f"{w} week{'s' if w != 1 else ''}" + (f" {d} day{'s' if d != 1 else ''}" if d else ""))
|
|
747
|
+
if days >= 60:
|
|
748
|
+
extra.append(f"about {days / 30.44:.1f} months")
|
|
749
|
+
return out + (f" ({'; '.join(extra)})" if extra else "")
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def compute(result, memories, min_support=0.9):
|
|
753
|
+
"""
|
|
754
|
+
The answer worked out from the memories the check verified, or None. Only for time-between and ordering
|
|
755
|
+
questions, and only when every presupposed event is supported at `min_support` by a distinct memory with a
|
|
756
|
+
timestamp: the arithmetic is exact, choosing the events is the risk, so anything less is left to the caller.
|
|
757
|
+
Counting is not computed (follow-ups, cancellations and near-misses make the set of occasions uncertain).
|
|
758
|
+
{"kind", "text", "events": [{"statement", "memory", "date"}], "working"}.
|
|
759
|
+
"""
|
|
760
|
+
if not result or not result.get("supported") or result.get("kind") not in ("time_between", "ordering"):
|
|
761
|
+
return None
|
|
762
|
+
claims = result.get("claims") or []
|
|
763
|
+
if len(claims) < 2 or any(c.get("support", 0) < min_support or c.get("memory") is None for c in claims):
|
|
764
|
+
return None
|
|
765
|
+
events = []
|
|
766
|
+
for c in claims:
|
|
767
|
+
# every memory that supports this event strongly; several on different dates make it ambiguous,
|
|
768
|
+
# unless the question says which one ("first", "last")
|
|
769
|
+
cands = [m for m, sc in (c.get("supporters") or {c["memory"]: c["support"]}).items()
|
|
770
|
+
if sc >= min_support and memories.get(m) is not None and memories[m].get("timestamp") is not None]
|
|
771
|
+
if not cands:
|
|
772
|
+
return None
|
|
773
|
+
by_date = sorted(cands, key=lambda m: memories[m]["timestamp"])
|
|
774
|
+
if len({_day(memories[m]["timestamp"]) for m in cands}) > 1 and c.get("ordinal") not in ("first", "last"):
|
|
775
|
+
return None
|
|
776
|
+
pick = by_date[-1] if c.get("ordinal") == "last" else by_date[0]
|
|
777
|
+
events.append({"statement": c["statement"], "memory": pick, "date": _day(memories[pick]["timestamp"])})
|
|
778
|
+
if len({e["memory"] for e in events}) != len(events):
|
|
779
|
+
return None
|
|
780
|
+
if result["kind"] == "time_between":
|
|
781
|
+
if len(events) != 2:
|
|
782
|
+
return None
|
|
783
|
+
a, b = events
|
|
784
|
+
if b["date"] < a["date"]:
|
|
785
|
+
return None # "after A ... B" / "between A and B" with B dated before A: these are not the right events
|
|
786
|
+
days = (b["date"] - a["date"]).days
|
|
787
|
+
return {"kind": "time_between", "text": _span_text(days),
|
|
788
|
+
"events": [{**e, "date": e["date"].isoformat()} for e in events],
|
|
789
|
+
"working": f"{a['date'].isoformat()} (memory {a['memory']}) to {b['date'].isoformat()} (memory {b['memory']})"
|
|
790
|
+
f" = {days} days"}
|
|
791
|
+
ordered = sorted(events, key=lambda e: e["date"])
|
|
792
|
+
if len({e["date"] for e in events}) != len(events):
|
|
793
|
+
return None # two events on one day: the order is not known from dates
|
|
794
|
+
return {"kind": "ordering", "text": " -> ".join(e["statement"].rstrip(".") for e in ordered),
|
|
795
|
+
"events": [{**e, "date": e["date"].isoformat()} for e in ordered],
|
|
796
|
+
"working": "; ".join(f"{e['date'].isoformat()}: {e['statement'].rstrip('.')} (memory {e['memory']})" for e in ordered)}
|