dsh-feiyu-memgate 0.3.2 → 0.4.0
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.
- package/CHANGELOG.md +73 -12
- package/README.md +68 -11
- package/README.zh.md +93 -36
- package/client/README.md +267 -0
- package/client/art/mascot-asleep.webp +0 -0
- package/client/art/mascot-busy.webp +0 -0
- package/client/art/mascot-nag.webp +0 -0
- package/client/art/mascot-ready.webp +0 -0
- package/client/art/mascot-trouble.webp +0 -0
- package/client/client.js +4226 -1269
- package/client/src/clipboard.cjs +52 -0
- package/client/src/constants.cjs +43 -0
- package/client/src/fields.cjs +960 -0
- package/client/src/hooks.cjs +220 -0
- package/client/src/i18n.cjs +444 -0
- package/client/src/index.cjs +69 -0
- package/client/src/kit/controls.cjs +189 -0
- package/client/src/kit/icons.cjs +40 -0
- package/client/src/kit/layout.cjs +124 -0
- package/client/src/layout.cjs +143 -0
- package/client/src/model/changelog.cjs +29 -0
- package/client/src/model/feedback.cjs +168 -0
- package/client/src/model/form.cjs +83 -0
- package/client/src/model/models.cjs +87 -0
- package/client/src/model/overview.cjs +111 -0
- package/client/src/model/page.cjs +104 -0
- package/client/src/model/status.cjs +57 -0
- package/client/src/model/trial.cjs +111 -0
- package/client/src/net.cjs +101 -0
- package/client/src/react.cjs +11 -0
- package/client/src/theme/page.css +1284 -0
- package/client/src/theme/styles.cjs +43 -0
- package/client/src/view/feedback.cjs +180 -0
- package/client/src/view/field-row.cjs +98 -0
- package/client/src/view/hero.cjs +54 -0
- package/client/src/view/markdown.cjs +96 -0
- package/client/src/view/models.cjs +154 -0
- package/client/src/view/page.cjs +199 -0
- package/client/src/view/settings-tab.cjs +78 -0
- package/client/src/view/tabs.cjs +71 -0
- package/client/src/view/trial.cjs +84 -0
- package/docs/DETAIL.en.md +55 -6
- package/docs/DETAIL.md +63 -14
- package/locale/zh.json +1 -1
- package/package.json +2 -1
- package/python/GATEWAY_VERSION.json +37 -31
- package/python/feiyu_memgate/backends/_sqlfile.py +293 -0
- package/python/feiyu_memgate/backends/base.py +121 -6
- package/python/feiyu_memgate/backends/embedding.py +265 -178
- package/python/feiyu_memgate/backends/hybrid.py +330 -83
- package/python/feiyu_memgate/backends/inmemory.py +115 -24
- package/python/feiyu_memgate/backends/openviking.py +7 -10
- package/python/feiyu_memgate/backends/sqlite.py +129 -145
- package/python/feiyu_memgate/builtins.py +1 -0
- package/python/feiyu_memgate/cli.py +124 -20
- package/python/feiyu_memgate/client/block.py +4 -2
- package/python/feiyu_memgate/client/http.py +106 -19
- package/python/feiyu_memgate/client/local.py +4 -3
- package/python/feiyu_memgate/config.py +118 -24
- package/python/feiyu_memgate/core/limits.py +2 -1
- package/python/feiyu_memgate/core/pool.py +29 -2
- package/python/feiyu_memgate/core/recall.py +179 -10
- package/python/feiyu_memgate/core/redact.py +4 -2
- package/python/feiyu_memgate/core/stages.py +52 -9
- package/python/feiyu_memgate/core/tidy.py +2 -1
- package/python/feiyu_memgate/core/watch.py +3 -2
- package/python/feiyu_memgate/core/write.py +9 -3
- package/python/feiyu_memgate/forgetting/archive.py +38 -10
- package/python/feiyu_memgate/forgetting/engine.py +46 -10
- package/python/feiyu_memgate/forgetting/stage.py +4 -2
- package/python/feiyu_memgate/gateway/app.py +168 -272
- package/python/feiyu_memgate/gateway/fields.py +121 -0
- package/python/feiyu_memgate/gateway/policies.py +162 -0
- package/python/feiyu_memgate/gateway/server.py +12 -4
- package/python/feiyu_memgate/gateway/tokens.py +137 -0
- package/python/feiyu_memgate/gateway/validate.py +120 -0
- package/python/feiyu_memgate/identity.py +152 -0
- package/python/feiyu_memgate/model.py +170 -2
- package/python/feiyu_memgate/registry.py +6 -3
- package/python/feiyu_memgate/tools/crypto.py +5 -4
- package/python/feiyu_memgate/tools/evaluate.py +2 -1
- package/python/feiyu_memgate/tools/tenants.py +2 -0
- package/src/block.js +9 -3
- package/src/capture.js +98 -0
- package/src/catalogue.js +4 -4
- package/src/changelog.js +72 -0
- package/src/client.js +145 -10
- package/src/commands.js +112 -62
- package/src/config.js +139 -62
- package/src/followup.js +139 -0
- package/src/gateway.js +79 -4
- package/src/migrate.py +54 -9
- package/src/mirror.py +44 -7
- package/src/plugin.js +416 -412
- package/src/pool.js +298 -0
- package/src/recent.js +68 -0
- package/src/relevance.js +80 -0
- package/src/routes.js +320 -0
- package/src/setup.js +36 -36
- package/src/shared.js +77 -0
- package/src/tiers.js +4 -4
- package/src/time.js +27 -0
- package/src/tools.js +164 -0
package/src/gateway.js
CHANGED
|
@@ -23,12 +23,17 @@ import net from 'node:net'
|
|
|
23
23
|
import os from 'node:os'
|
|
24
24
|
import path from 'node:path'
|
|
25
25
|
import { fileURLToPath } from 'node:url'
|
|
26
|
+
import { speakerAccount } from './shared.js'
|
|
26
27
|
import { effectiveTier, resolveStore, TIERS } from './tiers.js'
|
|
27
28
|
|
|
28
29
|
/** The folder that holds the bundled feiyu_memgate package (python/ in this repository). */
|
|
29
30
|
export const PACKAGE_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'python')
|
|
30
31
|
|
|
31
32
|
export const TOKEN_ENV = 'FEIYU_MEMGATE_TOKEN'
|
|
33
|
+
// The key the gateway turns the accounts of unknown speakers into stand-in codes with (see loadIdentityKey).
|
|
34
|
+
export const IDENTITY_KEY_ENV = 'FEIYU_MEMGATE_IDENTITY_KEY'
|
|
35
|
+
export const IDENTITY_KEY_FILE = 'identity.key'
|
|
36
|
+
const OWNER = 'owner' // the one person of the generated identity table
|
|
32
37
|
const PACKAGE_DIR_ENV = 'FEIYU_MEMGATE_PACKAGE_DIR'
|
|
33
38
|
export const MIN_PYTHON = Object.freeze([3, 11])
|
|
34
39
|
const STORE_NAME = 'memories'
|
|
@@ -199,8 +204,8 @@ export function missingSettings(settings, facts) {
|
|
|
199
204
|
* The gateway configuration for one start.
|
|
200
205
|
* settings readConfig() output (retrieval and advanced are used)
|
|
201
206
|
* facts { embed }: the embedding add-on's snapshot, for the local tier (src/tiers.js)
|
|
202
|
-
* Returns { text, env, store }: env holds the secrets the store reads (never the client token
|
|
203
|
-
* the manager adds itself); store is resolveStore()'s answer.
|
|
207
|
+
* Returns { text, env, store }: env holds the secrets the store reads (never the client token or the
|
|
208
|
+
* identity key, which the manager adds itself); store is resolveStore()'s answer.
|
|
204
209
|
*/
|
|
205
210
|
export function gatewayConfig({ port, dataDir, settings, facts = {}, utcOffsetHours = -new Date().getTimezoneOffset() / 60 }) {
|
|
206
211
|
const resolved = resolveStore(settings.retrieval, dataDir, facts)
|
|
@@ -216,6 +221,8 @@ export function gatewayConfig({ port, dataDir, settings, facts = {}, utcOffsetHo
|
|
|
216
221
|
if (policy.newerFirst) stages.push('newer_first')
|
|
217
222
|
// linked comes after the score lines and newer_first, before fill_text (DEFAULT_STAGES in core/stages.py).
|
|
218
223
|
if (policy.linkedRecall) stages.push('linked')
|
|
224
|
+
// record_audience right after linked (after newer_first or relative_score when those are off), before fill_text.
|
|
225
|
+
stages.push('record_audience')
|
|
219
226
|
stages.push('fill_text', 'drop_oversize')
|
|
220
227
|
if (policy.redaction) stages.push('redact')
|
|
221
228
|
stages.push('dedupe', 'budget')
|
|
@@ -224,7 +231,9 @@ export function gatewayConfig({ port, dataDir, settings, facts = {}, utcOffsetHo
|
|
|
224
231
|
const guards = []
|
|
225
232
|
if (policy.redaction) guards.push('redact')
|
|
226
233
|
if (policy.dailyWrites > 0) guards.push({ type: 'daily_cap', utc_offset_hours: utcOffsetHours })
|
|
227
|
-
|
|
234
|
+
// explain: the settings page's trial bench (POST /v1/explain). The managed client is the owner's.
|
|
235
|
+
// platforms and only_for: the client reports accounts of the platform dsh only, and speaks for the owner only.
|
|
236
|
+
const client = { token_env: TOKEN_ENV, recall: [STORE_NAME], write: STORE_NAME, explain: true, platforms: ['dsh'], only_for: [OWNER] }
|
|
228
237
|
if (policy.dailyWrites > 0) client.daily_writes = policy.dailyWrites
|
|
229
238
|
|
|
230
239
|
const lines = [
|
|
@@ -232,6 +241,10 @@ export function gatewayConfig({ port, dataDir, settings, facts = {}, utcOffsetHo
|
|
|
232
241
|
'# The client token is not in this file: the gateway reads it from the environment.',
|
|
233
242
|
'',
|
|
234
243
|
...table('server', { host: '127.0.0.1', port }),
|
|
244
|
+
// One person, the owner, with the one account this DSH reports (advanced.speakerAccount). The key for
|
|
245
|
+
// stand-in codes is read from the environment, never written here.
|
|
246
|
+
...table('identity', { type: 'table', hash_key_env: IDENTITY_KEY_ENV }),
|
|
247
|
+
...table(`identity.people.${OWNER}`, { owner: true, accounts: [speakerAccount(policy)] }),
|
|
235
248
|
...table(`stores.${STORE_NAME}`, store),
|
|
236
249
|
...table(`clients.${CLIENT_NAME}`, client),
|
|
237
250
|
...table('recall', { profile: policy.profile, stages }),
|
|
@@ -255,6 +268,62 @@ export function gatewayConfig({ port, dataDir, settings, facts = {}, utcOffsetHo
|
|
|
255
268
|
return { text: lines.join('\n'), env: resolved.env, store: resolved }
|
|
256
269
|
}
|
|
257
270
|
|
|
271
|
+
const IDENTITY_KEY_RE = /^[0-9a-fA-F]{64}$/
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* The identity key of the managed gateway: 64 hexadecimal characters (32 random bytes) in identity.key in
|
|
275
|
+
* the data folder. Created when missing (mode 0o600 where the system has modes), read at every gateway
|
|
276
|
+
* start. A file that cannot be read or does not hold 64 hexadecimal characters is replaced by a new one,
|
|
277
|
+
* with one warning that names the kind of problem only ('unreadable', 'malformed', 'unwritable'); when the
|
|
278
|
+
* new file cannot be written either, the key lives in memory for this start. The key is never logged.
|
|
279
|
+
* `warn(kind)` is called with that kind.
|
|
280
|
+
*/
|
|
281
|
+
export function loadIdentityKey(dataDir, warn = () => {}) {
|
|
282
|
+
const file = path.join(dataDir, IDENTITY_KEY_FILE)
|
|
283
|
+
const read = () => fs.readFileSync(file, 'utf8').trim()
|
|
284
|
+
let problem = null // set when a file is there but cannot be used
|
|
285
|
+
try {
|
|
286
|
+
const text = read()
|
|
287
|
+
if (IDENTITY_KEY_RE.test(text)) return text
|
|
288
|
+
problem = 'malformed'
|
|
289
|
+
} catch (error) {
|
|
290
|
+
if (error?.code !== 'ENOENT') problem = 'unreadable'
|
|
291
|
+
}
|
|
292
|
+
const key = randomBytes(32).toString('hex')
|
|
293
|
+
if (problem === null) {
|
|
294
|
+
// Missing: create it without replacing a file another process made in the meantime.
|
|
295
|
+
try {
|
|
296
|
+
fs.writeFileSync(file, key, { encoding: 'utf8', mode: 0o600, flag: 'wx' })
|
|
297
|
+
return key
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (error?.code !== 'EEXIST') {
|
|
300
|
+
warn('unwritable')
|
|
301
|
+
return key
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
const text = read()
|
|
305
|
+
if (IDENTITY_KEY_RE.test(text)) return text
|
|
306
|
+
problem = 'malformed'
|
|
307
|
+
} catch {
|
|
308
|
+
problem = 'unreadable'
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
warn(problem)
|
|
313
|
+
const temp = `${file}.${process.pid}.tmp`
|
|
314
|
+
try {
|
|
315
|
+
fs.writeFileSync(temp, key, { encoding: 'utf8', mode: 0o600 })
|
|
316
|
+
fs.renameSync(temp, file)
|
|
317
|
+
} catch {
|
|
318
|
+
try {
|
|
319
|
+
fs.rmSync(temp, { force: true })
|
|
320
|
+
} catch {
|
|
321
|
+
// nothing to do
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
return key
|
|
325
|
+
}
|
|
326
|
+
|
|
258
327
|
// Counts the memories of one store file without opening it for writing. The path arrives as an
|
|
259
328
|
// argument, never inside the code, and a missing table counts as empty.
|
|
260
329
|
const COUNT = [
|
|
@@ -534,6 +603,7 @@ export function createGatewayManager({
|
|
|
534
603
|
let waiters = []
|
|
535
604
|
let mirroring = null // the running keyword index update, see src/mirror.py
|
|
536
605
|
let mirrorWarned = false
|
|
606
|
+
let keyWarned = false
|
|
537
607
|
|
|
538
608
|
const warn = (message) => {
|
|
539
609
|
try {
|
|
@@ -641,6 +711,11 @@ export function createGatewayManager({
|
|
|
641
711
|
}
|
|
642
712
|
}
|
|
643
713
|
const token = randomBytes(32).toString('base64url')
|
|
714
|
+
const identityKey = loadIdentityKey(dataDir, (kind) => {
|
|
715
|
+
if (keyWarned) return
|
|
716
|
+
keyWarned = true
|
|
717
|
+
warn(`feiyu-memgate: the identity key file could not be used (${kind}); a new key is in use`)
|
|
718
|
+
})
|
|
644
719
|
const proc = spawnImpl(python.argv[0], [
|
|
645
720
|
...python.argv.slice(1),
|
|
646
721
|
'-I',
|
|
@@ -649,7 +724,7 @@ export function createGatewayManager({
|
|
|
649
724
|
'-c', BOOTSTRAP, 'serve', '--config', configFile,
|
|
650
725
|
], {
|
|
651
726
|
cwd: dataDir,
|
|
652
|
-
env: { ...scrubbedEnv(env), ...config.env, [TOKEN_ENV]: token, [PACKAGE_DIR_ENV]: packageDir, PYTHONIOENCODING: 'utf-8' },
|
|
727
|
+
env: { ...scrubbedEnv(env), ...config.env, [TOKEN_ENV]: token, [IDENTITY_KEY_ENV]: identityKey, [PACKAGE_DIR_ENV]: packageDir, PYTHONIOENCODING: 'utf-8' },
|
|
653
728
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
654
729
|
windowsHide: true,
|
|
655
730
|
})
|
package/src/migrate.py
CHANGED
|
@@ -10,6 +10,11 @@ closes: the plugin stopped the copy, or the host process went away however it we
|
|
|
10
10
|
to stdout as JSON lines. Nothing printed names a memory text, a key or a token: failures are reported
|
|
11
11
|
by the kind of error only.
|
|
12
12
|
|
|
13
|
+
The seven record fields (speaker, about, channel, audience, origin, event_date, kind) are copied with
|
|
14
|
+
the text when the keyword store file has them as columns and the target keeps fields; a copied memory
|
|
15
|
+
without an audience gets "owner": these stores are the owner's. Only values the gateway would take are
|
|
16
|
+
copied (a short non-empty string; an audience of the three known ones).
|
|
17
|
+
|
|
13
18
|
A state file next to the stores lists every ref already copied. A memory copied once and later removed
|
|
14
19
|
from the vector store (forgotten, deleted) is therefore not copied again, and a run that stopped half
|
|
15
20
|
way, at its item limit, its time limit or a failure of the embeddings endpoint, resumes where it
|
|
@@ -32,6 +37,9 @@ import time
|
|
|
32
37
|
from pathlib import Path
|
|
33
38
|
|
|
34
39
|
STATE_VERSION = 1
|
|
40
|
+
FIELD_NAMES = ("speaker", "about", "channel", "audience", "origin", "event_date", "kind") # model.FIELDS
|
|
41
|
+
AUDIENCES = ("owner", "group", "public")
|
|
42
|
+
MAX_FIELD = 128
|
|
35
43
|
|
|
36
44
|
|
|
37
45
|
def _watch_stdin():
|
|
@@ -78,11 +86,12 @@ def store_each(target, items, timeout, deadline):
|
|
|
78
86
|
for item in items:
|
|
79
87
|
if time.monotonic() >= deadline:
|
|
80
88
|
break
|
|
89
|
+
ref = item["ref"] if isinstance(item, dict) else item[1]
|
|
81
90
|
try:
|
|
82
91
|
target.put_many([item], timeout=timeout)
|
|
83
|
-
stored.append(
|
|
92
|
+
stored.append(ref)
|
|
84
93
|
except Exception: # noqa: BLE001 - only whether it was accepted matters here
|
|
85
|
-
refused.append(
|
|
94
|
+
refused.append(ref)
|
|
86
95
|
return stored, refused
|
|
87
96
|
|
|
88
97
|
|
|
@@ -102,12 +111,46 @@ def source_refs(db):
|
|
|
102
111
|
return []
|
|
103
112
|
|
|
104
113
|
|
|
105
|
-
def
|
|
114
|
+
def source_columns(db):
|
|
115
|
+
"""The record field columns the keyword store file has (a subset of FIELD_NAMES, in that order)."""
|
|
116
|
+
if db is None:
|
|
117
|
+
return ()
|
|
118
|
+
try:
|
|
119
|
+
names = {row[1] for row in db.execute("PRAGMA table_info(memories)")}
|
|
120
|
+
except sqlite3.OperationalError:
|
|
121
|
+
return ()
|
|
122
|
+
return tuple(name for name in FIELD_NAMES if name in names)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def clean_record_fields(values):
|
|
126
|
+
"""The fields of one copied memory: only usable values, and an audience ("owner" when there is none)."""
|
|
127
|
+
fields = {}
|
|
128
|
+
for name, value in values.items():
|
|
129
|
+
if isinstance(value, str) and value and len(value) <= MAX_FIELD:
|
|
130
|
+
fields[name] = value
|
|
131
|
+
if fields.get("audience") not in AUDIENCES:
|
|
132
|
+
fields["audience"] = "owner"
|
|
133
|
+
return fields
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def source_items(db, refs, columns=(), keeps_fields=False):
|
|
137
|
+
"""The memories of `refs`, in that order: (text, ref, date) tuples, or, when the target keeps fields,
|
|
138
|
+
dicts with "fields" (the columns the file has, an audience of "owner" when it has none)."""
|
|
106
139
|
marks = ",".join("?" * len(refs))
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
140
|
+
names = ("ref", "text", "date") + tuple(columns) if keeps_fields else ("ref", "text", "date")
|
|
141
|
+
rows = db.execute("SELECT %s FROM memories WHERE ref IN (%s)" % (", ".join(names), marks), refs).fetchall()
|
|
142
|
+
found = {row[0]: row[1:] for row in rows}
|
|
143
|
+
items = []
|
|
144
|
+
for ref in refs:
|
|
145
|
+
if ref not in found or not isinstance(found[ref][0], str) or not found[ref][0].strip():
|
|
146
|
+
continue
|
|
147
|
+
text, date = found[ref][0], found[ref][1]
|
|
148
|
+
if keeps_fields:
|
|
149
|
+
fields = clean_record_fields(dict(zip(columns, found[ref][2:])))
|
|
150
|
+
items.append({"text": text, "ref": ref, "date": date, "fields": fields})
|
|
151
|
+
else:
|
|
152
|
+
items.append((text, ref, date))
|
|
153
|
+
return items
|
|
111
154
|
|
|
112
155
|
|
|
113
156
|
def main():
|
|
@@ -128,6 +171,8 @@ def main():
|
|
|
128
171
|
target = registry.create("backend", resolve_env(job["target"], os.environ, "migration"))
|
|
129
172
|
source = open_source(job["source"])
|
|
130
173
|
refs = source_refs(source)
|
|
174
|
+
columns = source_columns(source)
|
|
175
|
+
keeps_fields = getattr(target, "stores_fields", False) is True
|
|
131
176
|
present = {ref for ref, _ in target.refs()}
|
|
132
177
|
except Exception as error: # noqa: BLE001 - reported by kind only
|
|
133
178
|
emit("failed", kind=type(error).__name__)
|
|
@@ -152,8 +197,8 @@ def main():
|
|
|
152
197
|
if moved >= max_items or time.monotonic() >= deadline:
|
|
153
198
|
break
|
|
154
199
|
chunk = todo[position:position + min(batch, max_items - moved)]
|
|
155
|
-
items = source_items(source, chunk)
|
|
156
|
-
offered = {item[1] for item in items}
|
|
200
|
+
items = source_items(source, chunk, columns, keeps_fields)
|
|
201
|
+
offered = {item["ref"] if isinstance(item, dict) else item[1] for item in items}
|
|
157
202
|
# Refs that vanished from the keyword store meanwhile count as handled: there is nothing left to copy.
|
|
158
203
|
copied.update(ref for ref in chunk if ref not in offered)
|
|
159
204
|
try:
|
package/src/mirror.py
CHANGED
|
@@ -20,6 +20,10 @@ closes: the plugin stopped the run, or the host process went away however it wen
|
|
|
20
20
|
to stdout as JSON lines. Nothing printed names a memory text, a ref, a key or a path: counts, and the
|
|
21
21
|
kind of error when a run fails. Exit code 0 for done and partial, 2 for failed.
|
|
22
22
|
|
|
23
|
+
The seven record fields (speaker, about, channel, audience, origin, event_date, kind) go along when the
|
|
24
|
+
vector file has them as columns and the keyword index keeps fields; a memory without an audience gets
|
|
25
|
+
"owner": these stores are the owner's.
|
|
26
|
+
|
|
23
27
|
The vector file is only read, through SQLite directly and read-only (it needs no embeddings endpoint).
|
|
24
28
|
The keyword index is written through the gateway's own backend, so its layout is always the one the
|
|
25
29
|
gateway expects. A run that reaches its time limit reports `partial` and the next start continues.
|
|
@@ -33,6 +37,9 @@ import time
|
|
|
33
37
|
from pathlib import Path
|
|
34
38
|
|
|
35
39
|
BATCH = 200
|
|
40
|
+
FIELD_NAMES = ("speaker", "about", "channel", "audience", "origin", "event_date", "kind") # model.FIELDS
|
|
41
|
+
AUDIENCES = ("owner", "group", "public")
|
|
42
|
+
MAX_FIELD = 128
|
|
36
43
|
DEFAULT_DEADLINE = 60.0
|
|
37
44
|
|
|
38
45
|
|
|
@@ -67,12 +74,37 @@ def vector_refs(db):
|
|
|
67
74
|
return []
|
|
68
75
|
|
|
69
76
|
|
|
70
|
-
def
|
|
71
|
-
"""
|
|
77
|
+
def vector_columns(db):
|
|
78
|
+
"""The record field columns the vector file has (a subset of FIELD_NAMES, in that order)."""
|
|
79
|
+
if db is None:
|
|
80
|
+
return ()
|
|
81
|
+
try:
|
|
82
|
+
names = {row[1] for row in db.execute("PRAGMA table_info(memories)")}
|
|
83
|
+
except sqlite3.OperationalError:
|
|
84
|
+
return ()
|
|
85
|
+
return tuple(name for name in FIELD_NAMES if name in names)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def clean_record_fields(values):
|
|
89
|
+
"""The fields of one memory: only usable values, and an audience ("owner" when there is none)."""
|
|
90
|
+
fields = {}
|
|
91
|
+
for name, value in values.items():
|
|
92
|
+
if isinstance(value, str) and value and len(value) <= MAX_FIELD:
|
|
93
|
+
fields[name] = value
|
|
94
|
+
if fields.get("audience") not in AUDIENCES:
|
|
95
|
+
fields["audience"] = "owner"
|
|
96
|
+
return fields
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def vector_items(db, refs, columns=()):
|
|
100
|
+
"""(text, ref, date, fields) of the given refs, in that order. Empty texts are left out. `fields`
|
|
101
|
+
is the memory's record fields (an audience of "owner" when the file has none)."""
|
|
72
102
|
marks = ",".join("?" * len(refs))
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
103
|
+
names = ("ref", "text", "date") + tuple(columns)
|
|
104
|
+
rows = db.execute("SELECT %s FROM memories WHERE ref IN (%s)" % (", ".join(names), marks), refs).fetchall()
|
|
105
|
+
found = {row[0]: row[1:] for row in rows}
|
|
106
|
+
return [(found[ref][0], ref, found[ref][1], clean_record_fields(dict(zip(columns, found[ref][2:]))))
|
|
107
|
+
for ref in refs
|
|
76
108
|
if ref in found and isinstance(found[ref][0], str) and found[ref][0].strip()]
|
|
77
109
|
|
|
78
110
|
|
|
@@ -89,6 +121,8 @@ def main():
|
|
|
89
121
|
vector = open_vector(job["vector"])
|
|
90
122
|
wanted = vector_refs(vector)
|
|
91
123
|
keyword = registry.create("backend", job["keyword"])
|
|
124
|
+
columns = vector_columns(vector)
|
|
125
|
+
keeps_fields = getattr(keyword, "stores_fields", False) is True
|
|
92
126
|
have = [ref for ref, _ in keyword.refs()]
|
|
93
127
|
wanted_set = set(wanted)
|
|
94
128
|
stale = [ref for ref in have if ref not in wanted_set]
|
|
@@ -107,8 +141,11 @@ def main():
|
|
|
107
141
|
handled = 0 # refs looked at, whether added or skipped as empty
|
|
108
142
|
while handled < len(missing) and time.monotonic() < deadline and removed == len(stale):
|
|
109
143
|
chunk = missing[handled:handled + BATCH]
|
|
110
|
-
for text, ref, date in vector_items(vector, chunk):
|
|
111
|
-
|
|
144
|
+
for text, ref, date, fields in vector_items(vector, chunk, columns):
|
|
145
|
+
if keeps_fields:
|
|
146
|
+
keyword.put(text, ref=ref, date=date, fields=fields)
|
|
147
|
+
else:
|
|
148
|
+
keyword.put(text, ref=ref, date=date)
|
|
112
149
|
added += 1
|
|
113
150
|
handled += len(chunk)
|
|
114
151
|
emit("progress", added=added, removed=removed, remaining=len(missing) - handled + len(stale) - removed)
|