memory-cli 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.
- memory_cli/__init__.py +1 -0
- memory_cli/__main__.py +49 -0
- memory_cli/capture/__init__.py +7 -0
- memory_cli/capture/codex_rollout.py +164 -0
- memory_cli/capture/event_lines.py +66 -0
- memory_cli/capture/extract.py +458 -0
- memory_cli/capture/state.py +183 -0
- memory_cli/commands/__init__.py +21 -0
- memory_cli/commands/admin.py +363 -0
- memory_cli/commands/common.py +609 -0
- memory_cli/commands/curate.py +1189 -0
- memory_cli/commands/diagnostics.py +126 -0
- memory_cli/commands/edit.py +1282 -0
- memory_cli/commands/hooks.py +730 -0
- memory_cli/commands/import_recovery.py +45 -0
- memory_cli/commands/install.py +152 -0
- memory_cli/commands/integrate.py +480 -0
- memory_cli/commands/memory.py +2152 -0
- memory_cli/commands/read.py +1290 -0
- memory_cli/commands/sources.py +766 -0
- memory_cli/commands/split.py +97 -0
- memory_cli/commands/split_plan.py +196 -0
- memory_cli/commands/split_transaction.py +230 -0
- memory_cli/commands/synthesis.py +1122 -0
- memory_cli/core/__init__.py +16 -0
- memory_cli/core/auto_state.py +30 -0
- memory_cli/core/codex_pass.py +109 -0
- memory_cli/core/config.py +87 -0
- memory_cli/core/file_journal.py +163 -0
- memory_cli/core/headless.py +130 -0
- memory_cli/core/jobs.py +130 -0
- memory_cli/core/resources.py +57 -0
- memory_cli/core/runner.py +398 -0
- memory_cli/core/safe_io.py +155 -0
- memory_cli/core/store_git.py +407 -0
- memory_cli/core/yaml_load.py +14 -0
- memory_cli/corroborate/__init__.py +11 -0
- memory_cli/corroborate/cli.py +267 -0
- memory_cli/corroborate/decide.py +893 -0
- memory_cli/corroborate/digest.py +425 -0
- memory_cli/corroborate/fill.py +744 -0
- memory_cli/corroborate/job.py +15 -0
- memory_cli/corroborate/reword.py +446 -0
- memory_cli/corroborate/run.py +1142 -0
- memory_cli/corroborate/state.py +300 -0
- memory_cli/digest/__init__.py +4 -0
- memory_cli/digest/lessons.py +483 -0
- memory_cli/entry/__init__.py +12 -0
- memory_cli/entry/auto.py +660 -0
- memory_cli/entry/capture.py +1403 -0
- memory_cli/entry/corroborate.py +214 -0
- memory_cli/entry/integrate.py +684 -0
- memory_cli/entry/integrate_self_check.py +203 -0
- memory_cli/entry/research.py +9 -0
- memory_cli/entry/settle.py +614 -0
- memory_cli/entry/split_auto.py +460 -0
- memory_cli/entry/synthesize.py +22 -0
- memory_cli/integrate/__init__.py +9 -0
- memory_cli/integrate/answers.py +42 -0
- memory_cli/integrate/briefs/check-brief.md +16 -0
- memory_cli/integrate/briefs/place-brief.md +26 -0
- memory_cli/integrate/log.py +43 -0
- memory_cli/integrate/plan.py +125 -0
- memory_cli/integrate/rows.py +99 -0
- memory_cli/integrate/state.py +158 -0
- memory_cli/integrate/undo.py +143 -0
- memory_cli/mem.py +1180 -0
- memory_cli/memories/__init__.py +16 -0
- memory_cli/memories/fingerprints.py +51 -0
- memory_cli/memories/journal.py +93 -0
- memory_cli/memories/locations.py +282 -0
- memory_cli/memories/matching.py +451 -0
- memory_cli/memories/model.py +205 -0
- memory_cli/memories/parse.py +237 -0
- memory_cli/memories/records.py +266 -0
- memory_cli/memories/rules.py +291 -0
- memory_cli/memories/sightings.py +314 -0
- memory_cli/memories/terms.py +148 -0
- memory_cli/memories/write.py +358 -0
- memory_cli/notes/__init__.py +13 -0
- memory_cli/notes/check.py +806 -0
- memory_cli/notes/due.py +260 -0
- memory_cli/notes/fields.py +217 -0
- memory_cli/notes/index.py +230 -0
- memory_cli/notes/links.py +170 -0
- memory_cli/notes/note.py +222 -0
- memory_cli/notes/search.py +391 -0
- memory_cli/notes/split_candidates.py +72 -0
- memory_cli/research/__init__.py +5 -0
- memory_cli/research/checks.py +1065 -0
- memory_cli/research/pipeline.py +952 -0
- memory_cli/session/__init__.py +5 -0
- memory_cli/session/handoff.py +139 -0
- memory_cli/session/notices.py +111 -0
- memory_cli/settle/__init__.py +5 -0
- memory_cli/settle/state.py +111 -0
- memory_cli/settle/verdicts.py +693 -0
- memory_cli/split/briefs/checker-brief.md +5 -0
- memory_cli/split/briefs/editor-brief.md +20 -0
- memory_cli/syntheses/__init__.py +8 -0
- memory_cli/syntheses/document.py +400 -0
- memory_cli/syntheses/edit.py +581 -0
- memory_cli/syntheses/project.py +384 -0
- memory_cli/syntheses/split_conservation.py +50 -0
- memory_cli/syntheses/units.py +427 -0
- memory_cli/synthesize/__init__.py +9 -0
- memory_cli/synthesize/backfill.py +431 -0
- memory_cli/synthesize/briefs/backfill-brief.md +26 -0
- memory_cli/synthesize/briefs/checker-brief.md +13 -0
- memory_cli/synthesize/briefs/fixer-brief.md +19 -0
- memory_cli/synthesize/briefs/memory-brief.md +30 -0
- memory_cli/synthesize/briefs/settle-brief.md +32 -0
- memory_cli/synthesize/briefs/verdict-brief.md +50 -0
- memory_cli/synthesize/briefs/web-brief.md +33 -0
- memory_cli/synthesize/cli.py +311 -0
- memory_cli/synthesize/pipeline.py +764 -0
- memory_cli/synthesize/references.py +164 -0
- memory_cli/synthesize/run.py +150 -0
- memory_cli/synthesize/topics.py +528 -0
- memory_cli/templates/knowledge.md +23 -0
- memory_cli/templates/literature.md +25 -0
- memory_cli/templates/research.md +23 -0
- memory_cli/templates/synthesis.md +6 -0
- memory_cli-0.1.0.dist-info/METADATA +102 -0
- memory_cli-0.1.0.dist-info/RECORD +128 -0
- memory_cli-0.1.0.dist-info/WHEEL +4 -0
- memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
- memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1065 @@
|
|
|
1
|
+
"""Pure parts of the `mem-research` pipeline (stage 1b): the web step's input, the page check (fetch, passages) and
|
|
2
|
+
the application of the verdicts. No model session and no third-party dependency here.
|
|
3
|
+
|
|
4
|
+
Text that comes from the web is data: no quote or claim is ever executed, used as a command name or as an option.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import html.parser
|
|
10
|
+
import http.client
|
|
11
|
+
import ipaddress
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import socket
|
|
17
|
+
import ssl
|
|
18
|
+
import subprocess
|
|
19
|
+
import threading
|
|
20
|
+
import time
|
|
21
|
+
import unicodedata
|
|
22
|
+
import urllib.parse
|
|
23
|
+
from collections.abc import Mapping
|
|
24
|
+
from typing import TYPE_CHECKING, Any, Literal, NamedTuple, TypedDict, TypeGuard, Unpack
|
|
25
|
+
|
|
26
|
+
from memory_cli.core import resources, safe_io
|
|
27
|
+
from memory_cli.memories import records
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from collections.abc import Callable, Iterable, Sequence
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
STANCES = ("supports", "contradicts")
|
|
34
|
+
SOURCE_KINDS = ("official", "paper", "other")
|
|
35
|
+
VERDICTS = ("confirmed", "contradicted", "no source")
|
|
36
|
+
MIN_QUOTE = 20
|
|
37
|
+
MIN_PARAGRAPH = 20 # a shorter paragraph is no passage
|
|
38
|
+
HTTP_OK = 200
|
|
39
|
+
MAX_BYTES = 2 * 1024 * 1024
|
|
40
|
+
MAX_PDF_BYTES = 8 * 1024 * 1024
|
|
41
|
+
PAGE_CHARS = 3000 # passages handed to the verdict step, per page
|
|
42
|
+
ITEM_CHARS = 12000 # and per item, over all its pages
|
|
43
|
+
MIN_FINDING_WORDS = 0.7 # share of a finding's content words that its quote must hold
|
|
44
|
+
QUESTION = "(question)" # the item key of the question; a note's key is its handle
|
|
45
|
+
MAX_REDIRECTS = 3
|
|
46
|
+
TIMEOUT = 10 # per socket operation
|
|
47
|
+
TOTAL_DEADLINE = 20 # per `fetch_text` call, all hops together
|
|
48
|
+
ROWS_PER_URL = 4 # `check_rows` considers at most this many rows per allowed URL
|
|
49
|
+
MEM_ENTRY = resources.mem_command()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# ---- step 2: web input ----
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class WebInput(NamedTuple):
|
|
56
|
+
# {"kind": "question", "text"} then {"kind": "claim", "handle", "text"}
|
|
57
|
+
items: list[dict[str, str]]
|
|
58
|
+
dropped: list[dict[str, str]] # {"handle", "reason"}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _shaped(note: Mapping[str, Any]) -> tuple[str, str] | None:
|
|
62
|
+
"""(handle, claim) of a note that has both as text, else None."""
|
|
63
|
+
handle = note.get("handle") if isinstance(note, Mapping) else None
|
|
64
|
+
claim = note.get("claim") if isinstance(note, Mapping) else None
|
|
65
|
+
if isinstance(handle, str) and handle and isinstance(claim, str) and claim.strip():
|
|
66
|
+
return handle, claim
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _label(note: Mapping[str, Any]) -> str:
|
|
71
|
+
handle = note.get("handle") if isinstance(note, Mapping) else None
|
|
72
|
+
return handle if isinstance(handle, str) else "?"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _web_problem(note: Mapping[str, Any], claim: str, env: Mapping[str, str]) -> str | None:
|
|
76
|
+
"""Why a well-shaped note may not go to the web (`claim` is its normalized claim), else None."""
|
|
77
|
+
if note.get("scope", "global") != "global":
|
|
78
|
+
return "not a global record"
|
|
79
|
+
secret = records.secret_in([claim])
|
|
80
|
+
if secret is not None:
|
|
81
|
+
return f"looks like a secret ({secret})"
|
|
82
|
+
try:
|
|
83
|
+
hits = records.term_hits([claim], env, "note")
|
|
84
|
+
except records.ForbiddenListError as exc:
|
|
85
|
+
return f"forbidden-terms list unreadable ({exc})"
|
|
86
|
+
return "contains a forbidden term" if hits else None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def web_input(
|
|
90
|
+
question: str, notes: Sequence[Mapping[str, Any]], env: Mapping[str, str] | None = None
|
|
91
|
+
) -> WebInput:
|
|
92
|
+
"""What may go to the web: the question as given, and each note claim that passes the secret and the
|
|
93
|
+
forbidden-terms checks of `mem remember`. A note is `{"handle", "claim"}` and, when given, `"scope": "global"`:
|
|
94
|
+
a project-scope record is never accepted. A soft term counts as a hit too, since nobody can approve it here."""
|
|
95
|
+
env = os.environ if env is None else env
|
|
96
|
+
items = [{"kind": "question", "text": question}]
|
|
97
|
+
dropped: list[dict[str, str]] = []
|
|
98
|
+
for note in notes:
|
|
99
|
+
shaped = _shaped(note)
|
|
100
|
+
if shaped is None:
|
|
101
|
+
dropped.append({"handle": _label(note), "reason": "bad shape"})
|
|
102
|
+
continue
|
|
103
|
+
handle, claim = shaped
|
|
104
|
+
claim = " ".join(claim.split())
|
|
105
|
+
reason = _web_problem(note, claim, env)
|
|
106
|
+
if reason is None:
|
|
107
|
+
items.append({"kind": "claim", "handle": handle, "text": claim})
|
|
108
|
+
else:
|
|
109
|
+
dropped.append({"handle": handle, "reason": reason})
|
|
110
|
+
return WebInput(items, dropped)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def question_problem(question: str, env: Mapping[str, str] | None = None) -> str | None:
|
|
114
|
+
"""Why the question may not go to the web (the secret and forbidden-terms checks of `mem remember`), else None."""
|
|
115
|
+
env = os.environ if env is None else env
|
|
116
|
+
text = " ".join(question.split())
|
|
117
|
+
if not text:
|
|
118
|
+
return "the question is empty"
|
|
119
|
+
secret = records.secret_in([text])
|
|
120
|
+
if secret is not None:
|
|
121
|
+
return f"the question looks like a secret ({secret})"
|
|
122
|
+
try:
|
|
123
|
+
hits = records.term_hits([text], env, "note")
|
|
124
|
+
except records.ForbiddenListError as exc:
|
|
125
|
+
return f"forbidden-terms list unreadable ({exc})"
|
|
126
|
+
return "the question contains a forbidden term" if hits else None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def item_ids(items: Sequence[Mapping[str, str]]) -> dict[str, dict[str, str]]:
|
|
130
|
+
"""The id each item has in the web prompt (`q` for the question, `c1`, `c2`... for the claims) -> the item."""
|
|
131
|
+
ids: dict[str, dict[str, str]] = {}
|
|
132
|
+
n = 0
|
|
133
|
+
for item in items:
|
|
134
|
+
if item["kind"] == "question":
|
|
135
|
+
ids["q"] = dict(item)
|
|
136
|
+
else:
|
|
137
|
+
n += 1
|
|
138
|
+
ids[f"c{n}"] = dict(item)
|
|
139
|
+
return ids
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def item_key(item: Mapping[str, str]) -> str:
|
|
143
|
+
return QUESTION if item["kind"] == "question" else item["handle"]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
_FENCE = re.compile(r"```[A-Za-z]*[ \t]*\n(.*?)```", re.DOTALL)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def parse_web_reply(text: str) -> list[Any] | None:
|
|
150
|
+
"""The web session's final reply as a JSON list, a code fence tolerated; anything else is None (no web results)."""
|
|
151
|
+
text = (text or "").strip()
|
|
152
|
+
found = _FENCE.search(text)
|
|
153
|
+
if found:
|
|
154
|
+
text = found.group(1).strip()
|
|
155
|
+
try:
|
|
156
|
+
rows = json.loads(text)
|
|
157
|
+
except ValueError:
|
|
158
|
+
return None
|
|
159
|
+
return rows if isinstance(rows, list) else None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
# ---- step 4: fetch ----
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class FetchError(Exception):
|
|
166
|
+
"""A page that could not be used."""
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
SANDBOX = safe_io.SANDBOX # MEM_SANDBOX=1: a background session; see safe_io.sandbox_refusal
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class FetchRefusedError(FetchError):
|
|
173
|
+
"""The address, scheme or redirect is not allowed."""
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class FetchFailedError(FetchError):
|
|
177
|
+
"""The network or the server failed."""
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class NotCheckedError(FetchError):
|
|
181
|
+
"""The content type is not text: the message reads "not checked: <type>"."""
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
_NAT64 = ipaddress.ip_network("64:ff9b::/96")
|
|
185
|
+
_V4_COMPATIBLE = ipaddress.ip_network("::/96")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _embedded_v4(ip: ipaddress.IPv6Address) -> list[ipaddress.IPv4Address]:
|
|
189
|
+
"""The IPv4 addresses an IPv6 address carries: mapped, compatible, NAT64, 6to4 and Teredo (server and client)."""
|
|
190
|
+
found = []
|
|
191
|
+
if ip.ipv4_mapped is not None:
|
|
192
|
+
found.append(ip.ipv4_mapped)
|
|
193
|
+
if ip in _NAT64 or ip in _V4_COMPATIBLE:
|
|
194
|
+
found.append(ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF))
|
|
195
|
+
if ip.sixtofour is not None:
|
|
196
|
+
found.append(ip.sixtofour)
|
|
197
|
+
if ip.teredo is not None:
|
|
198
|
+
found.extend(ip.teredo)
|
|
199
|
+
return found
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _public(address: str) -> bool:
|
|
203
|
+
ip = ipaddress.ip_address(address.split("%", maxsplit=1)[0])
|
|
204
|
+
if isinstance(ip, ipaddress.IPv6Address):
|
|
205
|
+
if not all(_public(str(v4)) for v4 in _embedded_v4(ip)):
|
|
206
|
+
return False
|
|
207
|
+
if ip in _V4_COMPATIBLE: # deprecated form: when in doubt, refuse
|
|
208
|
+
return False
|
|
209
|
+
return ip.is_global and not ip.is_multicast
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _resolve(host: str, port: int, allow: bool) -> str:
|
|
213
|
+
"""The first address of the host; every address must be public unless the host is allowed."""
|
|
214
|
+
try:
|
|
215
|
+
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
|
216
|
+
except OSError as exc:
|
|
217
|
+
raise FetchFailedError(f"cannot resolve {host}: {exc}") from exc
|
|
218
|
+
addresses = [str(info[4][0]) for info in infos]
|
|
219
|
+
if not addresses:
|
|
220
|
+
raise FetchFailedError(f"no address for {host}")
|
|
221
|
+
if not allow:
|
|
222
|
+
for address in addresses:
|
|
223
|
+
if not _public(address):
|
|
224
|
+
raise FetchRefusedError(f"{host} resolves to a non-public address")
|
|
225
|
+
return addresses[0]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _connection(
|
|
229
|
+
parts: urllib.parse.SplitResult, address: str, port: int, timeout: float = TIMEOUT
|
|
230
|
+
) -> http.client.HTTPConnection:
|
|
231
|
+
"""A connection pinned to the checked address, so a second DNS answer cannot change the target."""
|
|
232
|
+
host = parts.hostname or ""
|
|
233
|
+
https = parts.scheme == "https"
|
|
234
|
+
|
|
235
|
+
def open_socket(timeout: float | None) -> socket.socket:
|
|
236
|
+
sock = socket.create_connection((address, port), timeout)
|
|
237
|
+
if https:
|
|
238
|
+
sock = ssl.create_default_context().wrap_socket(sock, server_hostname=host)
|
|
239
|
+
return sock
|
|
240
|
+
|
|
241
|
+
class PinnedHTTP(http.client.HTTPConnection):
|
|
242
|
+
def connect(self) -> None:
|
|
243
|
+
self.sock = open_socket(self.timeout)
|
|
244
|
+
|
|
245
|
+
class PinnedHTTPS(http.client.HTTPSConnection):
|
|
246
|
+
def connect(self) -> None:
|
|
247
|
+
self.sock = open_socket(self.timeout)
|
|
248
|
+
|
|
249
|
+
return (PinnedHTTPS if https else PinnedHTTP)(host, port, timeout=timeout)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
_BLOCK = {
|
|
253
|
+
"p",
|
|
254
|
+
"div",
|
|
255
|
+
"br",
|
|
256
|
+
"li",
|
|
257
|
+
"ul",
|
|
258
|
+
"ol",
|
|
259
|
+
"tr",
|
|
260
|
+
"td",
|
|
261
|
+
"th",
|
|
262
|
+
"table",
|
|
263
|
+
"h1",
|
|
264
|
+
"h2",
|
|
265
|
+
"h3",
|
|
266
|
+
"h4",
|
|
267
|
+
"h5",
|
|
268
|
+
"h6",
|
|
269
|
+
"section",
|
|
270
|
+
"article",
|
|
271
|
+
"header",
|
|
272
|
+
"footer",
|
|
273
|
+
"pre",
|
|
274
|
+
"blockquote",
|
|
275
|
+
"title",
|
|
276
|
+
"body",
|
|
277
|
+
"head",
|
|
278
|
+
}
|
|
279
|
+
_SKIP = {"script", "style", "template", "noscript"}
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
_VOID = {
|
|
283
|
+
"area",
|
|
284
|
+
"base",
|
|
285
|
+
"br",
|
|
286
|
+
"col",
|
|
287
|
+
"embed",
|
|
288
|
+
"hr",
|
|
289
|
+
"img",
|
|
290
|
+
"input",
|
|
291
|
+
"link",
|
|
292
|
+
"meta",
|
|
293
|
+
"param",
|
|
294
|
+
"source",
|
|
295
|
+
"track",
|
|
296
|
+
"wbr",
|
|
297
|
+
}
|
|
298
|
+
_HIDING_STYLE = re.compile(r"display:none|visibility:hidden")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _hides(attrs: Any) -> bool:
|
|
302
|
+
for name, value in attrs:
|
|
303
|
+
if name == "hidden":
|
|
304
|
+
return True
|
|
305
|
+
if name == "aria-hidden" and (value or "").strip().lower() == "true":
|
|
306
|
+
return True
|
|
307
|
+
if name == "style" and _HIDING_STYLE.search(re.sub(r"\s+", "", (value or "").lower())):
|
|
308
|
+
return True
|
|
309
|
+
return False
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class _Text(html.parser.HTMLParser):
|
|
313
|
+
def __init__(self) -> None:
|
|
314
|
+
super().__init__(convert_charrefs=True)
|
|
315
|
+
self.parts: list[str] = []
|
|
316
|
+
self.skip = 0
|
|
317
|
+
self.open: list[tuple[str, bool]] = [] # open non-void elements: (tag, hides its content)
|
|
318
|
+
self.hidden = 0
|
|
319
|
+
# an open script/style: the parser hands everything up to its end tag as data
|
|
320
|
+
self.raw_tag: str | None = None
|
|
321
|
+
self.raw: list[str] = []
|
|
322
|
+
|
|
323
|
+
def handle_starttag(self, tag: str, attrs: Any) -> None:
|
|
324
|
+
if tag in {"script", "style"}:
|
|
325
|
+
self.raw_tag, self.raw = tag, []
|
|
326
|
+
if tag in _SKIP:
|
|
327
|
+
self.skip += 1
|
|
328
|
+
elif tag in _BLOCK:
|
|
329
|
+
self.parts.append("\n")
|
|
330
|
+
if tag not in _VOID:
|
|
331
|
+
hides = _hides(attrs)
|
|
332
|
+
self.open.append((tag, hides))
|
|
333
|
+
self.hidden += hides
|
|
334
|
+
|
|
335
|
+
def handle_endtag(self, tag: str) -> None:
|
|
336
|
+
if tag == self.raw_tag:
|
|
337
|
+
self.raw_tag = None
|
|
338
|
+
if tag in _SKIP:
|
|
339
|
+
self.skip = max(0, self.skip - 1)
|
|
340
|
+
elif tag in _BLOCK:
|
|
341
|
+
self.parts.append("\n")
|
|
342
|
+
# closes the nearest open element of that name and what it holds
|
|
343
|
+
for index in range(len(self.open) - 1, -1, -1):
|
|
344
|
+
if self.open[index][0] == tag:
|
|
345
|
+
self.hidden -= sum(h for _, h in self.open[index:])
|
|
346
|
+
del self.open[index:]
|
|
347
|
+
break
|
|
348
|
+
|
|
349
|
+
def handle_data(self, data: str) -> None:
|
|
350
|
+
if self.raw_tag:
|
|
351
|
+
self.raw.append(data)
|
|
352
|
+
if not self.skip and not self.hidden:
|
|
353
|
+
self.parts.append(data)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
_PAST_RAW = re.compile(r"<[a-z/]", re.IGNORECASE)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def html_text(markup: str) -> str:
|
|
360
|
+
parser = _Text()
|
|
361
|
+
parser.feed(markup)
|
|
362
|
+
parser.close()
|
|
363
|
+
# CPython 3.12.0 leaves the text after an unclosed script/style in rawdata; later patches hand it over
|
|
364
|
+
if parser.raw_tag and parser.rawdata:
|
|
365
|
+
parser.handle_data(parser.rawdata)
|
|
366
|
+
text = "".join(parser.parts)
|
|
367
|
+
if parser.raw_tag: # a script/style never closed: its "content" runs to the end; resume at the next tag start (known limit: script source before it may leak into the text)
|
|
368
|
+
rest = "".join(parser.raw)
|
|
369
|
+
if (end := _PAST_RAW.search(rest)) is not None:
|
|
370
|
+
return text + html_text(rest[end.start() :])
|
|
371
|
+
return text
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _is_text_type(ctype: str) -> bool:
|
|
375
|
+
return ctype.startswith("text/") or ctype in {
|
|
376
|
+
"application/xhtml+xml",
|
|
377
|
+
"application/xml",
|
|
378
|
+
"application/json",
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _pdf_text(raw: bytes) -> str:
|
|
383
|
+
"""The text of a PDF through `pdftotext` (no shell; the bytes go to its standard input)."""
|
|
384
|
+
try:
|
|
385
|
+
done = subprocess.run(
|
|
386
|
+
["pdftotext", "-q", "-enc", "UTF-8", "-", "-"],
|
|
387
|
+
input=raw,
|
|
388
|
+
capture_output=True,
|
|
389
|
+
timeout=30,
|
|
390
|
+
check=False,
|
|
391
|
+
)
|
|
392
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
393
|
+
raise NotCheckedError(f"not checked: pdf ({type(exc).__name__})") from exc
|
|
394
|
+
if done.returncode != 0 or not done.stdout.strip():
|
|
395
|
+
raise NotCheckedError("not checked: pdf unreadable")
|
|
396
|
+
return done.stdout.decode("utf-8", errors="replace")
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _cut(conn: http.client.HTTPConnection, cut: threading.Event) -> None:
|
|
400
|
+
"""Shut the socket down from another thread, which ends a read blocked on it."""
|
|
401
|
+
cut.set()
|
|
402
|
+
try:
|
|
403
|
+
if conn.sock is not None:
|
|
404
|
+
conn.sock.shutdown(socket.SHUT_RDWR)
|
|
405
|
+
except OSError:
|
|
406
|
+
pass
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _read(resp: http.client.HTTPResponse, limit: int, deadline: float) -> bytes:
|
|
410
|
+
"""At most `limit` bytes, in chunks, so the deadline is checked between reads."""
|
|
411
|
+
chunks: list[bytes] = []
|
|
412
|
+
size = 0
|
|
413
|
+
while size < limit:
|
|
414
|
+
if time.monotonic() >= deadline:
|
|
415
|
+
raise FetchFailedError("total time limit passed")
|
|
416
|
+
chunk = resp.read1(min(65536, limit - size))
|
|
417
|
+
if not chunk:
|
|
418
|
+
break
|
|
419
|
+
chunks.append(chunk)
|
|
420
|
+
size += len(chunk)
|
|
421
|
+
return b"".join(chunks)
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
class FetchOptions(TypedDict, total=False):
|
|
425
|
+
"""The keyword options of `fetch_raw`; an omitted one has the default in the comment after its field."""
|
|
426
|
+
|
|
427
|
+
over: Literal["truncate", "fail"] # "truncate"
|
|
428
|
+
headers: Mapping[str, str] | None # None
|
|
429
|
+
deadline: float | None # None: TOTAL_DEADLINE
|
|
430
|
+
max_redirects: int # MAX_REDIRECTS
|
|
431
|
+
allow_hosts: Iterable[str] # ()
|
|
432
|
+
timeout: float # TIMEOUT
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
class _Call(NamedTuple):
|
|
436
|
+
"""What every hop of one `fetch_raw` call shares."""
|
|
437
|
+
|
|
438
|
+
limit_for: Callable[[str], int]
|
|
439
|
+
over: str
|
|
440
|
+
end: float # the monotonic time the whole call must be over by
|
|
441
|
+
sent: dict[str, str] # request headers
|
|
442
|
+
max_redirects: int
|
|
443
|
+
allowed: set[str] # hosts that skip the address check, on the first hop
|
|
444
|
+
timeout: float
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _call(limit_for: Callable[[str], int], options: FetchOptions) -> _Call:
|
|
448
|
+
if safe_io.sandbox_active():
|
|
449
|
+
raise FetchRefusedError("network access is off in this session")
|
|
450
|
+
deadline = options.get("deadline")
|
|
451
|
+
return _Call(
|
|
452
|
+
limit_for,
|
|
453
|
+
options.get("over", "truncate"),
|
|
454
|
+
time.monotonic() + (TOTAL_DEADLINE if deadline is None else deadline),
|
|
455
|
+
{
|
|
456
|
+
"Accept": "text/html,text/plain,application/pdf",
|
|
457
|
+
"User-Agent": "mem-research",
|
|
458
|
+
**(options.get("headers") or {}),
|
|
459
|
+
},
|
|
460
|
+
options.get("max_redirects", MAX_REDIRECTS),
|
|
461
|
+
{h.lower() for h in options.get("allow_hosts", ())},
|
|
462
|
+
options.get("timeout", TIMEOUT),
|
|
463
|
+
)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _checked_address(
|
|
467
|
+
url: str, hop: int, allowed: set[str]
|
|
468
|
+
) -> tuple[urllib.parse.SplitResult, str, int]:
|
|
469
|
+
"""(parts, address, port) of a URL to connect to: http(s) only, no credentials, and an address that is public
|
|
470
|
+
(or a host of `allowed` on the first hop)."""
|
|
471
|
+
parts = urllib.parse.urlsplit(url)
|
|
472
|
+
if parts.scheme not in {"http", "https"} or not parts.hostname:
|
|
473
|
+
raise FetchRefusedError("only http and https URLs are fetched")
|
|
474
|
+
if parts.username is not None or parts.password is not None:
|
|
475
|
+
raise FetchRefusedError("a URL with credentials is refused")
|
|
476
|
+
try:
|
|
477
|
+
port = parts.port or (443 if parts.scheme == "https" else 80)
|
|
478
|
+
except ValueError as exc:
|
|
479
|
+
raise FetchRefusedError("bad port") from exc
|
|
480
|
+
return (
|
|
481
|
+
parts,
|
|
482
|
+
_resolve(parts.hostname, port, hop == 0 and parts.hostname.lower() in allowed),
|
|
483
|
+
port,
|
|
484
|
+
)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _start_cutter(
|
|
488
|
+
conn: http.client.HTTPConnection, remaining: float
|
|
489
|
+
) -> tuple[threading.Event, threading.Timer]:
|
|
490
|
+
"""A server that drips bytes keeps every single read within its timeout: cut the socket at the deadline."""
|
|
491
|
+
cut = threading.Event()
|
|
492
|
+
cutter = threading.Timer(remaining, _cut, (conn, cut))
|
|
493
|
+
cutter.daemon = True
|
|
494
|
+
cutter.start()
|
|
495
|
+
return cut, cutter
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _location(resp: http.client.HTTPResponse) -> str:
|
|
499
|
+
target = resp.getheader("Location")
|
|
500
|
+
if not target:
|
|
501
|
+
raise FetchFailedError(f"redirect without a location ({resp.status})")
|
|
502
|
+
return target
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _body(resp: http.client.HTTPResponse, call: _Call, cut: threading.Event) -> tuple[bytes, str]:
|
|
506
|
+
header = (resp.getheader("Content-Type") or "").lower()
|
|
507
|
+
limit = call.limit_for(header.split(";")[0].strip())
|
|
508
|
+
raw = _read(resp, limit + (call.over == "fail"), call.end)
|
|
509
|
+
if cut.is_set():
|
|
510
|
+
raise FetchFailedError("total time limit passed")
|
|
511
|
+
if len(raw) > limit:
|
|
512
|
+
raise FetchFailedError(f"response larger than {limit // (1024 * 1024)} MB")
|
|
513
|
+
return raw, header
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _exchange(
|
|
517
|
+
conn: http.client.HTTPConnection,
|
|
518
|
+
parts: urllib.parse.SplitResult,
|
|
519
|
+
call: _Call,
|
|
520
|
+
cut: threading.Event,
|
|
521
|
+
) -> tuple[bytes, str] | str:
|
|
522
|
+
"""One request: (body, Content-Type) of the page, or the Location a redirect points to."""
|
|
523
|
+
path = urllib.parse.urlunsplit(("", "", parts.path or "/", parts.query, ""))
|
|
524
|
+
conn.request(
|
|
525
|
+
"GET",
|
|
526
|
+
path,
|
|
527
|
+
headers={
|
|
528
|
+
**call.sent,
|
|
529
|
+
"Host": parts.netloc.rsplit("@", 1)[-1],
|
|
530
|
+
"Accept-Encoding": "identity",
|
|
531
|
+
},
|
|
532
|
+
)
|
|
533
|
+
resp = conn.getresponse()
|
|
534
|
+
if resp.status in {301, 302, 303, 307, 308}:
|
|
535
|
+
return _location(resp)
|
|
536
|
+
if resp.status != HTTP_OK:
|
|
537
|
+
raise FetchFailedError(f"HTTP {resp.status}")
|
|
538
|
+
return _body(resp, call, cut)
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _failure(exc: Exception, cut: threading.Event) -> FetchFailedError:
|
|
542
|
+
if cut.is_set():
|
|
543
|
+
return FetchFailedError("total time limit passed")
|
|
544
|
+
return FetchFailedError(f"{type(exc).__name__}: {exc}")
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def fetch_raw(
|
|
548
|
+
url: str, limit_for: Callable[[str], int], **options: Unpack[FetchOptions]
|
|
549
|
+
) -> tuple[bytes, str]:
|
|
550
|
+
"""(body, Content-Type lowercased, parameters kept) of a page. Only http(s); a non-public address is refused at
|
|
551
|
+
every hop (`max_redirects` at most); `timeout` seconds per socket operation (TIMEOUT) and `deadline` seconds (TOTAL_DEADLINE) for the whole
|
|
552
|
+
call. `limit_for(content type)` gives the byte limit (it may raise to refuse the type); past it, "truncate" cuts the
|
|
553
|
+
body and "fail" raises FetchFailedError. `allow_hosts` names hosts that skip the address check, for the URL given only
|
|
554
|
+
(a local test page): every redirect target is checked as any other. The pinned connection ignores HTTPS_PROXY."""
|
|
555
|
+
call = _call(limit_for, options)
|
|
556
|
+
for hop in range(call.max_redirects + 1):
|
|
557
|
+
parts, address, port = _checked_address(url, hop, call.allowed)
|
|
558
|
+
remaining = call.end - time.monotonic()
|
|
559
|
+
if remaining <= 0:
|
|
560
|
+
raise FetchFailedError("total time limit passed")
|
|
561
|
+
conn = _connection(parts, address, port, min(call.timeout, remaining))
|
|
562
|
+
cut, cutter = _start_cutter(conn, remaining)
|
|
563
|
+
try:
|
|
564
|
+
got = _exchange(conn, parts, call, cut)
|
|
565
|
+
except (OSError, http.client.HTTPException) as exc:
|
|
566
|
+
raise _failure(exc, cut) from exc
|
|
567
|
+
finally:
|
|
568
|
+
cutter.cancel()
|
|
569
|
+
conn.close()
|
|
570
|
+
if not isinstance(got, str):
|
|
571
|
+
return got
|
|
572
|
+
if hop == call.max_redirects:
|
|
573
|
+
raise FetchRefusedError("too many redirects")
|
|
574
|
+
url = urllib.parse.urljoin(url, got)
|
|
575
|
+
raise FetchRefusedError("too many redirects") # unreachable
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def _charset(header: str) -> str:
|
|
579
|
+
"""The charset parameter of a Content-Type header (utf-8 when absent)."""
|
|
580
|
+
charset = "utf-8"
|
|
581
|
+
for piece in header.split(";")[1:]:
|
|
582
|
+
key, _, value = piece.partition("=")
|
|
583
|
+
if key.strip() == "charset" and value.strip():
|
|
584
|
+
charset = value.strip().strip("\"'")
|
|
585
|
+
return charset
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _decode(raw: bytes, charset: str) -> str:
|
|
589
|
+
try:
|
|
590
|
+
return raw.decode(charset, errors="replace")
|
|
591
|
+
except LookupError:
|
|
592
|
+
return raw.decode("utf-8", errors="replace")
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def fetch_text(url: str, allow_hosts: Iterable[str] = (), deadline: float | None = None) -> str:
|
|
596
|
+
"""The visible text of a page, through `fetch_raw`: 3 redirects at most; 2 MB read at most (8 MB for a PDF, which
|
|
597
|
+
`pdftotext` reads when installed; else it is not checked); any other non-text type is not checked."""
|
|
598
|
+
pdf = False
|
|
599
|
+
|
|
600
|
+
def limit_for(ctype: str) -> int:
|
|
601
|
+
nonlocal pdf
|
|
602
|
+
pdf = ctype == "application/pdf" and shutil.which("pdftotext") is not None
|
|
603
|
+
if not (pdf or _is_text_type(ctype)):
|
|
604
|
+
raise NotCheckedError(f"not checked: {ctype or 'unknown type'}")
|
|
605
|
+
return MAX_PDF_BYTES if pdf else MAX_BYTES
|
|
606
|
+
|
|
607
|
+
raw, header = fetch_raw(url, limit_for, allow_hosts=allow_hosts, deadline=deadline)
|
|
608
|
+
if pdf:
|
|
609
|
+
return _pdf_text(raw)
|
|
610
|
+
text = _decode(raw, _charset(header))
|
|
611
|
+
ctype = header.split(";")[0].strip()
|
|
612
|
+
return html_text(text) if ctype in {"text/html", "application/xhtml+xml"} else text
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
# ---- step 4: quotes ----
|
|
616
|
+
|
|
617
|
+
_PLAIN = str.maketrans({
|
|
618
|
+
"\u2018": "'", # left single quotation mark
|
|
619
|
+
"\u2019": "'", # right single quotation mark
|
|
620
|
+
"\u201a": "'", # single low-9 quotation mark
|
|
621
|
+
"\u201b": "'", # single high-reversed-9 quotation mark
|
|
622
|
+
"\u2032": "'", # prime
|
|
623
|
+
"\u201c": '"', # left double quotation mark
|
|
624
|
+
"\u201d": '"', # right double quotation mark
|
|
625
|
+
"\u201e": '"', # double low-9 quotation mark
|
|
626
|
+
"\u201f": '"', # double high-reversed-9 quotation mark
|
|
627
|
+
"\u2033": '"', # double prime
|
|
628
|
+
"\u2010": "-", # hyphen
|
|
629
|
+
"\u2011": "-", # non-breaking hyphen
|
|
630
|
+
"\u2012": "-", # figure dash
|
|
631
|
+
"\u2013": "-", # en dash
|
|
632
|
+
"\u2014": "-", # em dash
|
|
633
|
+
"\u2015": "-", # horizontal bar
|
|
634
|
+
"\u2212": "-", # minus sign
|
|
635
|
+
})
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def normalize(text: str) -> str:
|
|
639
|
+
return " ".join(unicodedata.normalize("NFKC", text).translate(_PLAIN).split())
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def quote_found(quote: str, text: str) -> bool:
|
|
643
|
+
"""True when the quote, at least 20 characters long once normalized, occurs in the text word for word."""
|
|
644
|
+
wanted = normalize(quote)
|
|
645
|
+
return len(wanted) >= MIN_QUOTE and wanted in normalize(text)
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
class Checked(NamedTuple):
|
|
649
|
+
# {"item": key, "url", "stance", "source_kind", "passages": [str]}
|
|
650
|
+
entries: list[dict[str, Any]]
|
|
651
|
+
pages: dict[str, str] # url -> the text fetched (only URLs that were fetched)
|
|
652
|
+
dropped: list[dict[str, Any]] # {"row", "reason"}
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
_FIELDS = ("item", "url", "stance", "source_kind")
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def _shape_problem(row: Any) -> str | None:
|
|
659
|
+
if not isinstance(row, Mapping):
|
|
660
|
+
return "bad shape: not an object"
|
|
661
|
+
for key in _FIELDS:
|
|
662
|
+
if not isinstance(row.get(key), str) or not row[key].strip():
|
|
663
|
+
return f"bad shape: {key} missing or not text"
|
|
664
|
+
if row["stance"] not in STANCES:
|
|
665
|
+
return f"bad shape: unknown stance {row['stance']!r}"
|
|
666
|
+
if row["source_kind"] not in SOURCE_KINDS:
|
|
667
|
+
return f"bad shape: unknown source_kind {row['source_kind']!r}"
|
|
668
|
+
return None
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def _scored_paragraphs(page: str, terms: set[str]) -> list[tuple[int, int, str]]:
|
|
672
|
+
"""(-score, index, paragraph) of each paragraph of `page` that shares a term and is long enough; the paragraphs
|
|
673
|
+
are blank-line separated, or line separated when the page has no blank line."""
|
|
674
|
+
chunks = re.split(r"\n\s*\n", page)
|
|
675
|
+
if len(chunks) == 1:
|
|
676
|
+
chunks = page.split("\n")
|
|
677
|
+
scored = []
|
|
678
|
+
for index, chunk in enumerate(chunks):
|
|
679
|
+
paragraph = " ".join(chunk.split())
|
|
680
|
+
score = len(terms & set(records.tokenize(paragraph)))
|
|
681
|
+
if score and len(paragraph) >= MIN_PARAGRAPH:
|
|
682
|
+
scored.append((-score, index, paragraph))
|
|
683
|
+
return scored
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def select_passages(page: str, text: str, limit: int = PAGE_CHARS) -> list[str]:
|
|
687
|
+
"""Whole paragraphs of `page` that share content words with `text`, best first, about `limit` characters at most
|
|
688
|
+
(one paragraph longer than that is cut). The engine's tokenizer and stop words."""
|
|
689
|
+
terms = set(records.tokenize(text)) - records.STOPWORDS
|
|
690
|
+
if limit < MIN_QUOTE:
|
|
691
|
+
return []
|
|
692
|
+
chosen: list[str] = []
|
|
693
|
+
used = 0
|
|
694
|
+
for _, _, paragraph in sorted(_scored_paragraphs(page, terms)):
|
|
695
|
+
cut = paragraph[:limit]
|
|
696
|
+
if used + len(cut) > limit:
|
|
697
|
+
continue
|
|
698
|
+
chosen.append(cut)
|
|
699
|
+
used += len(cut)
|
|
700
|
+
return chosen
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def _allowed_urls(
|
|
704
|
+
rows: Sequence[Any], items: Mapping[str, Mapping[str, str]], max_urls: int
|
|
705
|
+
) -> list[str]:
|
|
706
|
+
"""The first `max_urls` distinct URLs of the rows that are well shaped and name a known item."""
|
|
707
|
+
allowed: list[str] = []
|
|
708
|
+
for row in rows:
|
|
709
|
+
if (
|
|
710
|
+
_shape_problem(row) is None
|
|
711
|
+
and row["item"] in items
|
|
712
|
+
and row["url"] not in allowed
|
|
713
|
+
and len(allowed) < max_urls
|
|
714
|
+
):
|
|
715
|
+
allowed.append(row["url"])
|
|
716
|
+
return allowed
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def _fetch_page(fetch: Callable[[str], str], url: str) -> str | FetchError:
|
|
720
|
+
"""The page text, or the error that says why it is not usable."""
|
|
721
|
+
try:
|
|
722
|
+
return fetch(url)
|
|
723
|
+
except FetchRefusedError as exc:
|
|
724
|
+
return FetchRefusedError(f"fetch refused: {exc}")
|
|
725
|
+
except NotCheckedError as exc:
|
|
726
|
+
return exc
|
|
727
|
+
except (FetchError, OSError, ValueError) as exc:
|
|
728
|
+
return FetchFailedError(f"fetch failed: {exc}")
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
class _RowCheck:
|
|
732
|
+
"""The state of one `check_rows` run: what each row adds to the entries or to the dropped rows."""
|
|
733
|
+
|
|
734
|
+
def __init__(
|
|
735
|
+
self,
|
|
736
|
+
items: Mapping[str, Mapping[str, str]],
|
|
737
|
+
fetch: Callable[[str], str],
|
|
738
|
+
allowed: list[str],
|
|
739
|
+
dropped: list[dict[str, Any]],
|
|
740
|
+
) -> None:
|
|
741
|
+
self.items, self.fetch, self.allowed, self.dropped = items, fetch, allowed, dropped
|
|
742
|
+
self.entries: list[dict[str, Any]] = []
|
|
743
|
+
self.pages: dict[str, str | FetchError] = {}
|
|
744
|
+
self.spent: dict[str, int] = {}
|
|
745
|
+
self.seen: set[tuple[str, str, str]] = set()
|
|
746
|
+
|
|
747
|
+
def _rejection(self, row: Any) -> str | None:
|
|
748
|
+
problem = _shape_problem(row)
|
|
749
|
+
if problem:
|
|
750
|
+
return problem
|
|
751
|
+
if row["item"] not in self.items:
|
|
752
|
+
return "unknown item id"
|
|
753
|
+
if row["url"] not in self.allowed:
|
|
754
|
+
return "over the page limit"
|
|
755
|
+
return None
|
|
756
|
+
|
|
757
|
+
def _page(self, url: str) -> str | FetchError:
|
|
758
|
+
if url not in self.pages:
|
|
759
|
+
self.pages[url] = _fetch_page(self.fetch, url)
|
|
760
|
+
return self.pages[url]
|
|
761
|
+
|
|
762
|
+
def _keep(self, row: Any, item: Mapping[str, str], page: str) -> None:
|
|
763
|
+
key = item_key(item)
|
|
764
|
+
passages = select_passages(
|
|
765
|
+
page, item["text"], min(PAGE_CHARS, ITEM_CHARS - self.spent.get(key, 0))
|
|
766
|
+
)
|
|
767
|
+
if not passages:
|
|
768
|
+
self.dropped.append({
|
|
769
|
+
"row": row,
|
|
770
|
+
"reason": "no passage of the page shares terms with the item (or the item's budget is spent)",
|
|
771
|
+
})
|
|
772
|
+
return
|
|
773
|
+
self.spent[key] = self.spent.get(key, 0) + sum(len(p) for p in passages)
|
|
774
|
+
self.entries.append({
|
|
775
|
+
"item": key,
|
|
776
|
+
"url": row["url"],
|
|
777
|
+
"stance": row["stance"],
|
|
778
|
+
"source_kind": row["source_kind"],
|
|
779
|
+
"passages": passages,
|
|
780
|
+
})
|
|
781
|
+
|
|
782
|
+
def add(self, row: Any) -> None:
|
|
783
|
+
reason = self._rejection(row)
|
|
784
|
+
if reason is not None:
|
|
785
|
+
self.dropped.append({"row": row, "reason": reason})
|
|
786
|
+
return
|
|
787
|
+
item = self.items[row["item"]]
|
|
788
|
+
mark = (item_key(item), row["url"], row["stance"])
|
|
789
|
+
if mark in self.seen:
|
|
790
|
+
return
|
|
791
|
+
self.seen.add(mark)
|
|
792
|
+
page = self._page(row["url"])
|
|
793
|
+
if isinstance(page, FetchError):
|
|
794
|
+
self.dropped.append({"row": row, "reason": str(page)})
|
|
795
|
+
return
|
|
796
|
+
self._keep(row, item, page)
|
|
797
|
+
|
|
798
|
+
def result(self) -> Checked:
|
|
799
|
+
return Checked(
|
|
800
|
+
self.entries, {u: p for u, p in self.pages.items() if isinstance(p, str)}, self.dropped
|
|
801
|
+
)
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
def check_rows(
|
|
805
|
+
rows: Iterable[Any],
|
|
806
|
+
items: Mapping[str, Mapping[str, str]],
|
|
807
|
+
fetch: Callable[[str], str] = fetch_text,
|
|
808
|
+
max_urls: int = 5,
|
|
809
|
+
) -> Checked:
|
|
810
|
+
"""The web session's rows (`item` is an id of `items`, see `item_ids`) -> entries with the passages of their page.
|
|
811
|
+
Only the first `4 * max_urls` rows are considered and only the first `max_urls` distinct URLs among them are
|
|
812
|
+
fetched, each once, after all rows are checked for shape: a row of any other URL is dropped before any fetch.
|
|
813
|
+
A row whose page could not be fetched, or whose page shares no term with its item, is dropped with its reason."""
|
|
814
|
+
rows = list(rows)
|
|
815
|
+
dropped: list[dict[str, Any]] = []
|
|
816
|
+
limit = ROWS_PER_URL * max_urls
|
|
817
|
+
if len(rows) > limit:
|
|
818
|
+
dropped.append({"row": f"{len(rows) - limit} more rows", "reason": "over the row limit"})
|
|
819
|
+
rows = rows[:limit]
|
|
820
|
+
check = _RowCheck(items, fetch, _allowed_urls(rows, items, max_urls), dropped)
|
|
821
|
+
for row in rows:
|
|
822
|
+
check.add(row)
|
|
823
|
+
return check.result()
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
# ---- step 6: apply ----
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
class Plan(NamedTuple):
|
|
830
|
+
# arguments after the program: ["note", "confirm", NOTE, "--fact", ...]
|
|
831
|
+
commands: list[list[str]]
|
|
832
|
+
# {"row", "reason"}; reason "downgraded to no source" for a weak contradiction
|
|
833
|
+
refused: list[dict[str, Any]]
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def _dash(values: Iterable[str]) -> str | None:
|
|
837
|
+
return next((v for v in values if v.startswith("-")), None)
|
|
838
|
+
|
|
839
|
+
|
|
840
|
+
_NUMBER = re.compile(r"\d+(?:[.,]\d+)*")
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
_SENTENCE = re.compile(r"(?<=[.!?])\s+")
|
|
844
|
+
|
|
845
|
+
|
|
846
|
+
def finding_problem(claim: str, quote: str) -> str | None:
|
|
847
|
+
"""Why a finding says more than its quote or says the opposite: a number of the claim missing from the quote,
|
|
848
|
+
fewer than 70% of the claim's content words in it, or a negation or opposite present on only one side of the claim
|
|
849
|
+
and the sentence of the quote it rests on. None when it is covered."""
|
|
850
|
+
wanted = set(_NUMBER.findall(normalize(claim)))
|
|
851
|
+
if not wanted <= set(_NUMBER.findall(normalize(quote))):
|
|
852
|
+
return "a number of the claim is not in its quote"
|
|
853
|
+
if records.containment(records.tokenize(claim), records.tokenize(quote)) < MIN_FINDING_WORDS:
|
|
854
|
+
return "the claim says more than its quote (under 70% of its content words are in it)"
|
|
855
|
+
claim_tokens = records.tokenize(claim)
|
|
856
|
+
rests_on = max(
|
|
857
|
+
_SENTENCE.split(quote.strip()),
|
|
858
|
+
key=lambda s: records.containment(claim_tokens, records.tokenize(s)),
|
|
859
|
+
)
|
|
860
|
+
if any(not any(c.isdigit() for c in w) for w in records.flagged_words(claim, rests_on)):
|
|
861
|
+
return "the claim and its quote differ by a negation or an opposite"
|
|
862
|
+
return None
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
_QUOTE_OFF_PAGE = (
|
|
866
|
+
"the quote is not on the fetched page word for word (or is shorter than 20 characters)"
|
|
867
|
+
)
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
class _Planner:
|
|
871
|
+
"""The state of one `plan_commands` run: the commands kept, the rows refused and the quote lookups."""
|
|
872
|
+
|
|
873
|
+
def __init__(
|
|
874
|
+
self, entries: Sequence[Mapping[str, Any]], pages: Mapping[str, str], sent: Iterable[str]
|
|
875
|
+
) -> None:
|
|
876
|
+
self.entries, self.pages, self.sent = entries, pages, set(sent)
|
|
877
|
+
self.commands: list[list[str]] = []
|
|
878
|
+
self.refused: list[dict[str, Any]] = []
|
|
879
|
+
self.found: dict[tuple[str, str], bool] = {}
|
|
880
|
+
self.normalized: dict[str, str] = {} # url -> its page, normalized once
|
|
881
|
+
|
|
882
|
+
def refuse(self, row: Any, reason: str) -> None:
|
|
883
|
+
self.refused.append({"row": row, "reason": reason})
|
|
884
|
+
|
|
885
|
+
def on_page(self, quote: Any, url: str) -> TypeGuard[str]:
|
|
886
|
+
if not isinstance(quote, str): # also unhashable as a lookup key
|
|
887
|
+
return False
|
|
888
|
+
key = (url, quote)
|
|
889
|
+
if key not in self.found:
|
|
890
|
+
if url not in self.normalized:
|
|
891
|
+
self.normalized[url] = normalize(self.pages.get(url, ""))
|
|
892
|
+
wanted = normalize(quote)
|
|
893
|
+
self.found[key] = len(wanted) >= MIN_QUOTE and wanted in self.normalized[url]
|
|
894
|
+
return self.found[key]
|
|
895
|
+
|
|
896
|
+
def _verdict_problem(self, row: Mapping[str, Any]) -> str | None:
|
|
897
|
+
note = row.get("note")
|
|
898
|
+
if not isinstance(note, str) or note not in self.sent:
|
|
899
|
+
return "note was not sent to the web"
|
|
900
|
+
if row.get("verdict") not in VERDICTS:
|
|
901
|
+
return "unknown verdict"
|
|
902
|
+
return None
|
|
903
|
+
|
|
904
|
+
def _source_problem(self, row: Mapping[str, Any]) -> str | None:
|
|
905
|
+
note, verdict, url = row.get("note"), row.get("verdict"), row.get("url")
|
|
906
|
+
stance = "supports" if verdict == "confirmed" else "contradicts"
|
|
907
|
+
match = [
|
|
908
|
+
e
|
|
909
|
+
for e in self.entries
|
|
910
|
+
if e["item"] == note and e["url"] == url and e["stance"] == stance
|
|
911
|
+
]
|
|
912
|
+
if not isinstance(url, str) or not match:
|
|
913
|
+
return f"the web step gave no {stance} URL like this one for the note"
|
|
914
|
+
if verdict == "contradicted" and not any(
|
|
915
|
+
e["source_kind"] in {"official", "paper"} for e in match
|
|
916
|
+
):
|
|
917
|
+
return "downgraded to no source: the source is neither official nor a paper"
|
|
918
|
+
return None
|
|
919
|
+
|
|
920
|
+
def _text_problem(self, row: Mapping[str, Any]) -> str | None:
|
|
921
|
+
note, url, fact, quote = row["note"], row["url"], row.get("fact"), row.get("quote")
|
|
922
|
+
if not self.on_page(quote, url):
|
|
923
|
+
return _QUOTE_OFF_PAGE
|
|
924
|
+
if not isinstance(fact, str) or not fact.strip():
|
|
925
|
+
return "the fact is empty"
|
|
926
|
+
if _dash([note, fact, url, quote]) is not None:
|
|
927
|
+
return "a value starts with '-'"
|
|
928
|
+
return None
|
|
929
|
+
|
|
930
|
+
def _note_problem(self, row: Mapping[str, Any]) -> str | None:
|
|
931
|
+
reason = self._verdict_problem(row)
|
|
932
|
+
if reason is not None or row.get("verdict") == "no source":
|
|
933
|
+
return reason
|
|
934
|
+
return self._source_problem(row) or self._text_problem(row)
|
|
935
|
+
|
|
936
|
+
def note(self, row: Mapping[str, Any]) -> None:
|
|
937
|
+
"""Plan the command of a note row, or refuse it; a `no source` verdict plans nothing."""
|
|
938
|
+
reason = self._note_problem(row)
|
|
939
|
+
if reason is not None:
|
|
940
|
+
self.refuse(row, reason)
|
|
941
|
+
elif row["verdict"] != "no source":
|
|
942
|
+
verb = "confirm" if row["verdict"] == "confirmed" else "dispute"
|
|
943
|
+
self.commands.append([
|
|
944
|
+
"note",
|
|
945
|
+
verb,
|
|
946
|
+
row["note"],
|
|
947
|
+
"--fact",
|
|
948
|
+
row["fact"],
|
|
949
|
+
"--source",
|
|
950
|
+
row["url"],
|
|
951
|
+
"--quote",
|
|
952
|
+
row["quote"],
|
|
953
|
+
])
|
|
954
|
+
|
|
955
|
+
def _quote_problem(self, claim: str, url: str, quote: Any) -> str | None:
|
|
956
|
+
if not self.on_page(quote, url):
|
|
957
|
+
return _QUOTE_OFF_PAGE
|
|
958
|
+
why = finding_problem(claim, quote)
|
|
959
|
+
if why is not None:
|
|
960
|
+
return why
|
|
961
|
+
if _dash([claim, url]) is not None:
|
|
962
|
+
return "a value starts with '-'"
|
|
963
|
+
return None
|
|
964
|
+
|
|
965
|
+
def _finding_problem(self, row: Mapping[str, Any]) -> str | None:
|
|
966
|
+
claim, url = row.get("claim"), row.get("url")
|
|
967
|
+
if not isinstance(claim, str) or not claim.strip():
|
|
968
|
+
return "the claim is empty"
|
|
969
|
+
if not isinstance(url, str) or not any(
|
|
970
|
+
e["url"] == url and e["stance"] == "supports" for e in self.entries
|
|
971
|
+
):
|
|
972
|
+
return "the web step gave no supporting URL like this one"
|
|
973
|
+
return self._quote_problem(claim, url, row.get("quote"))
|
|
974
|
+
|
|
975
|
+
def finding(self, row: Mapping[str, Any]) -> None:
|
|
976
|
+
"""Plan the command of a finding row, or refuse it."""
|
|
977
|
+
reason = self._finding_problem(row)
|
|
978
|
+
if reason is not None:
|
|
979
|
+
self.refuse(row, reason)
|
|
980
|
+
else:
|
|
981
|
+
self.commands.append([
|
|
982
|
+
"remember",
|
|
983
|
+
"--global",
|
|
984
|
+
"--kind",
|
|
985
|
+
"finding",
|
|
986
|
+
"--origin",
|
|
987
|
+
"web",
|
|
988
|
+
"--source",
|
|
989
|
+
row["url"],
|
|
990
|
+
"--claim",
|
|
991
|
+
row["claim"],
|
|
992
|
+
])
|
|
993
|
+
|
|
994
|
+
def rows(self, rows: Any, plan_row: Callable[[Mapping[str, Any]], None]) -> None:
|
|
995
|
+
for row in rows if isinstance(rows, list) else []:
|
|
996
|
+
if isinstance(row, Mapping):
|
|
997
|
+
plan_row(row)
|
|
998
|
+
else:
|
|
999
|
+
self.refuse(row, "bad shape")
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
def plan_commands(
|
|
1003
|
+
verdicts: Mapping[str, Any],
|
|
1004
|
+
entries: Sequence[Mapping[str, Any]],
|
|
1005
|
+
pages: Mapping[str, str],
|
|
1006
|
+
sent: Iterable[str],
|
|
1007
|
+
) -> Plan:
|
|
1008
|
+
"""The commands for a parsed `verdicts.json`. `entries` and `pages` are what `check_rows` kept; `sent` holds the
|
|
1009
|
+
handles that went to the web. A row is kept only when its URL was returned by the web step for that item with the
|
|
1010
|
+
matching stance and its quote is on the text fetched for that URL word for word. Every value is one argument;
|
|
1011
|
+
a value that starts with `-` refuses its row."""
|
|
1012
|
+
planner = _Planner(entries, pages, sent)
|
|
1013
|
+
notes = verdicts.get("notes", []) if isinstance(verdicts, Mapping) else []
|
|
1014
|
+
findings = verdicts.get("findings", []) if isinstance(verdicts, Mapping) else []
|
|
1015
|
+
planner.rows(notes, planner.note)
|
|
1016
|
+
planner.rows(findings, planner.finding)
|
|
1017
|
+
return Plan(planner.commands, planner.refused)
|
|
1018
|
+
|
|
1019
|
+
|
|
1020
|
+
class ApplyOptions(TypedDict, total=False):
|
|
1021
|
+
"""The keyword options of `apply`; an omitted one has the default named beside it."""
|
|
1022
|
+
|
|
1023
|
+
mem_cmd: Sequence[str] # MEM_ENTRY
|
|
1024
|
+
root: str | Path | None # None
|
|
1025
|
+
timeout: int # 120
|
|
1026
|
+
env: Mapping[str, str] | None # None
|
|
1027
|
+
|
|
1028
|
+
|
|
1029
|
+
def apply(
|
|
1030
|
+
verdicts: Mapping[str, Any],
|
|
1031
|
+
entries: Sequence[Mapping[str, Any]],
|
|
1032
|
+
pages: Mapping[str, str],
|
|
1033
|
+
sent: Iterable[str],
|
|
1034
|
+
**options: Unpack[ApplyOptions],
|
|
1035
|
+
) -> dict[str, Any]:
|
|
1036
|
+
"""Run the planned commands, no shell, through `mem_cmd` (this installation's `mem` by default),
|
|
1037
|
+
with `env` as their environment (the inherited one when None).
|
|
1038
|
+
Report: applied (argument lists), refused (rows with reasons), failed (argument list, exit code, stderr)."""
|
|
1039
|
+
plan = plan_commands(verdicts, entries, pages, sent)
|
|
1040
|
+
root, env = options.get("root"), options.get("env")
|
|
1041
|
+
prefix = [
|
|
1042
|
+
*options.get("mem_cmd", MEM_ENTRY),
|
|
1043
|
+
*(["--root", str(root)] if root is not None else []),
|
|
1044
|
+
]
|
|
1045
|
+
applied: list[list[str]] = []
|
|
1046
|
+
failed: list[dict[str, Any]] = []
|
|
1047
|
+
for args in plan.commands:
|
|
1048
|
+
try:
|
|
1049
|
+
done = subprocess.run(
|
|
1050
|
+
[*prefix, *args],
|
|
1051
|
+
shell=False,
|
|
1052
|
+
check=False,
|
|
1053
|
+
capture_output=True,
|
|
1054
|
+
text=True,
|
|
1055
|
+
timeout=options.get("timeout", 120),
|
|
1056
|
+
env=resources.child_env(env),
|
|
1057
|
+
)
|
|
1058
|
+
code, err = done.returncode, done.stderr.strip()
|
|
1059
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
1060
|
+
code, err = -1, f"{type(exc).__name__}: {exc}"
|
|
1061
|
+
if code == 0:
|
|
1062
|
+
applied.append(args)
|
|
1063
|
+
else:
|
|
1064
|
+
failed.append({"args": args, "code": code, "stderr": err})
|
|
1065
|
+
return {"applied": applied, "refused": plan.refused, "failed": failed}
|