keepfold 0.6.4__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.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
keepfold/voice_memos.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""Sources B, voice memos (RR-30, v9 item 14 part B): a folder of audio files (a phone's voice
|
|
2
|
+
recorder, WhatsApp voice notes copied out) into one private page per memo, transcribed on this
|
|
3
|
+
computer by faster-whisper (CPU, int8, model `MODEL`). Never sent anywhere; the audio is never
|
|
4
|
+
copied into the vault.
|
|
5
|
+
|
|
6
|
+
faster-whisper is optional (the `voice` extra): `keepfold model download --voice` installs it
|
|
7
|
+
(pinned, `PIN`) and downloads the model into ~/.keepfold/models, and is the only place either is
|
|
8
|
+
fetched. Without them an import refuses with `NEEDS`. faster-whisper decodes through PyAV, whose
|
|
9
|
+
wheels bundle FFmpeg, so no ffmpeg on PATH is needed.
|
|
10
|
+
|
|
11
|
+
Whisper invents text on silence, so: its VAD filter; segments with no_speech_prob over
|
|
12
|
+
NO_SPEECH or avg_logprob under MIN_LOGPROB dropped; a phrase looping more than LOOP times in a
|
|
13
|
+
row kept once; a memo under MIN_WORDS words skipped. Its prompt (spelling only) is up to
|
|
14
|
+
PROMPT_TERMS concept titles and people names, never note text.
|
|
15
|
+
|
|
16
|
+
A page is `voice-YYYY-MM-DD-<first words>`: the fact header (When: the date in the file name,
|
|
17
|
+
else the file's date; Summary: the first sentence), then a paragraph per ~PARA_SECONDS of
|
|
18
|
+
speech with [mm:ss] at its start. Keyed by the audio's sha, so an unchanged file is not
|
|
19
|
+
transcribed again; a changed file rewrites its page unless the page was edited (RR-18).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import hashlib
|
|
25
|
+
import importlib
|
|
26
|
+
import importlib.util
|
|
27
|
+
import os
|
|
28
|
+
import re
|
|
29
|
+
import shutil
|
|
30
|
+
import subprocess
|
|
31
|
+
import sys
|
|
32
|
+
import threading
|
|
33
|
+
from datetime import date, datetime
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
|
|
36
|
+
from keepfold import importers, sources
|
|
37
|
+
from keepfold._proc import NO_WINDOW
|
|
38
|
+
from keepfold.vault import Vault, VaultError
|
|
39
|
+
|
|
40
|
+
LABEL = "Voice memos" # the pages' header label; sources.edited_pages lists them
|
|
41
|
+
AUDIO = (".m4a", ".mp3", ".wav", ".ogg", ".opus", ".aac")
|
|
42
|
+
MODEL = "base"
|
|
43
|
+
SIZE = "about 150 MB"
|
|
44
|
+
PIN = "faster-whisper==1.2.1" # the `voice` extra in pyproject.toml
|
|
45
|
+
MAX_SECONDS = 2 * 3600
|
|
46
|
+
PARA_SECONDS = 30
|
|
47
|
+
NO_SPEECH, MIN_LOGPROB = 0.6, -1.0
|
|
48
|
+
MIN_WORDS, LOOP = 3, 3
|
|
49
|
+
PROMPT_TERMS = 40
|
|
50
|
+
TITLE_WORDS = 6
|
|
51
|
+
NEEDS = (f"Voice memos need the local speech model ({SIZE}). Install it with the Voice memos "
|
|
52
|
+
"card in the app, or run `keepfold model download --voice`.")
|
|
53
|
+
SKIPS = ("not audio", "no speech", "over 2 hours", "unreadable")
|
|
54
|
+
_DAY = re.compile(r"(?<!\d)(20\d\d)[-_.]?(0[1-9]|1[0-2])[-_.]?(0[1-9]|[12]\d|3[01])(?!\d)")
|
|
55
|
+
_WORD = re.compile(r"[\W_]+")
|
|
56
|
+
|
|
57
|
+
_model = None
|
|
58
|
+
_LOCK = threading.Lock()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def load_transcriber():
|
|
62
|
+
"""`transcribe(path, prompt) -> (seconds, segments)`, or None when faster-whisper or its
|
|
63
|
+
model is not installed. Never downloads. A file over MAX_SECONDS comes back with no
|
|
64
|
+
segments, undecoded."""
|
|
65
|
+
global _model
|
|
66
|
+
with _LOCK:
|
|
67
|
+
if _model is None:
|
|
68
|
+
importlib.invalidate_caches() # `model download --voice` may have run since start
|
|
69
|
+
try:
|
|
70
|
+
from faster_whisper import WhisperModel
|
|
71
|
+
|
|
72
|
+
from keepfold import semantic
|
|
73
|
+
_model = WhisperModel(MODEL, device="cpu", compute_type="int8",
|
|
74
|
+
download_root=str(semantic.models_dir()),
|
|
75
|
+
local_files_only=True)
|
|
76
|
+
except Exception: # noqa: BLE001 - not installed, or the model is not downloaded
|
|
77
|
+
return None
|
|
78
|
+
model = _model
|
|
79
|
+
|
|
80
|
+
def transcribe(path: Path, prompt: str):
|
|
81
|
+
import av
|
|
82
|
+
with av.open(str(path)) as f:
|
|
83
|
+
seconds = (f.duration or 0) / av.time_base
|
|
84
|
+
if seconds > MAX_SECONDS:
|
|
85
|
+
return seconds, []
|
|
86
|
+
segs, info = model.transcribe(str(path), vad_filter=True, initial_prompt=prompt or None)
|
|
87
|
+
return info.duration, segs
|
|
88
|
+
|
|
89
|
+
return transcribe
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def install(say=print) -> None:
|
|
93
|
+
"""`keepfold model download --voice`: faster-whisper into this Python (uv pip, `PIN`, held to
|
|
94
|
+
the installer's constraints when there are some), then the model into ~/.keepfold/models."""
|
|
95
|
+
from keepfold import semantic, update
|
|
96
|
+
importlib.invalidate_caches()
|
|
97
|
+
if importlib.util.find_spec("faster_whisper") is None:
|
|
98
|
+
d = update.install_dir()
|
|
99
|
+
uv = str(d / "uv.exe") if d and (d / "uv.exe").is_file() else shutil.which("uv")
|
|
100
|
+
if not uv:
|
|
101
|
+
raise RuntimeError("uv is not on PATH, so faster-whisper cannot be installed. "
|
|
102
|
+
f"Install uv, or run: uv pip install {PIN}")
|
|
103
|
+
cmd = [uv, "pip", "install", "--python", sys.executable, PIN]
|
|
104
|
+
env = dict(os.environ)
|
|
105
|
+
cwd = None
|
|
106
|
+
if d: # the installer's pins and cache folder (installer/setup_app.py)
|
|
107
|
+
if (d / "constraints.txt").is_file():
|
|
108
|
+
# relative, run in `d`: uv 0.9.15 splits a -c path on spaces (uv#22290)
|
|
109
|
+
cmd += ["-c", "constraints.txt"]
|
|
110
|
+
cwd = str(d)
|
|
111
|
+
env.update(UV_CACHE_DIR=str(d / "cache"), UV_NATIVE_TLS="1")
|
|
112
|
+
say(f"installing {PIN} ...")
|
|
113
|
+
subprocess.run(cmd, check=True, env=env, cwd=cwd, creationflags=NO_WINDOW)
|
|
114
|
+
importlib.invalidate_caches()
|
|
115
|
+
from faster_whisper import download_model
|
|
116
|
+
say(f"speech model {MODEL}: downloading if missing into {semantic.models_dir()} ...")
|
|
117
|
+
download_model(MODEL, cache_dir=str(semantic.models_dir()))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def recorded(p: Path) -> str:
|
|
121
|
+
"""The day a memo was recorded: a date in its file name (20241103, 2024-11-03), else the
|
|
122
|
+
file's modified date."""
|
|
123
|
+
if m := _DAY.search(p.stem):
|
|
124
|
+
try:
|
|
125
|
+
return date(int(m[1]), int(m[2]), int(m[3])).isoformat()
|
|
126
|
+
except ValueError:
|
|
127
|
+
pass
|
|
128
|
+
return datetime.fromtimestamp(p.stat().st_mtime).date().isoformat()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def spelling(v: Vault) -> str:
|
|
132
|
+
"""Whisper's prompt: up to PROMPT_TERMS concept titles and people names, so it spells the
|
|
133
|
+
owner's terms; never a note's text."""
|
|
134
|
+
from keepfold.catalog import Catalog
|
|
135
|
+
try:
|
|
136
|
+
terms = [e.title for e in Catalog.load(v).entries.values() if e.kind == "concept"]
|
|
137
|
+
except VaultError:
|
|
138
|
+
terms = []
|
|
139
|
+
names = []
|
|
140
|
+
for p in v.note_paths("person"):
|
|
141
|
+
try:
|
|
142
|
+
names.append(str(v.read_path(p).fields.get("title") or p.stem))
|
|
143
|
+
except VaultError:
|
|
144
|
+
continue
|
|
145
|
+
got = terms[:PROMPT_TERMS] + names[:PROMPT_TERMS]
|
|
146
|
+
return ", ".join(got) + "." if got else ""
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def unloop(words: list) -> list:
|
|
150
|
+
"""`words` ((word, start) pairs) with any 3+ word phrase repeated more than LOOP times in
|
|
151
|
+
a row kept once (Whisper's hallucination loops)."""
|
|
152
|
+
norm = [_WORD.sub("", w.lower()) for w, _ in words]
|
|
153
|
+
out, i = [], 0
|
|
154
|
+
while i < len(words):
|
|
155
|
+
for n in range(3, 13):
|
|
156
|
+
k = 1
|
|
157
|
+
while norm[i + k * n:i + (k + 1) * n] == norm[i:i + n] and i + (k + 1) * n \
|
|
158
|
+
<= len(words):
|
|
159
|
+
k += 1
|
|
160
|
+
if k > LOOP:
|
|
161
|
+
out += words[i:i + n]
|
|
162
|
+
i += k * n
|
|
163
|
+
break
|
|
164
|
+
else:
|
|
165
|
+
out.append(words[i])
|
|
166
|
+
i += 1
|
|
167
|
+
return out
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _clock(s: float) -> str:
|
|
171
|
+
s = int(s)
|
|
172
|
+
return f"[{s // 60:02d}:{s % 60:02d}]"
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def transcript(segments, stop=lambda: False) -> str | None:
|
|
176
|
+
"""The kept speech as paragraphs of about PARA_SECONDS, `[mm:ss]` first; "" when under
|
|
177
|
+
MIN_WORDS words are left, None when `stop()` said to stop."""
|
|
178
|
+
words = []
|
|
179
|
+
for s in segments:
|
|
180
|
+
if stop():
|
|
181
|
+
return None
|
|
182
|
+
if s.no_speech_prob > NO_SPEECH or s.avg_logprob < MIN_LOGPROB:
|
|
183
|
+
continue
|
|
184
|
+
words += [(w, s.start) for w in s.text.split()]
|
|
185
|
+
words = unloop(words)
|
|
186
|
+
if len(words) < MIN_WORDS:
|
|
187
|
+
return ""
|
|
188
|
+
paras, t0 = [], None
|
|
189
|
+
for w, start in words:
|
|
190
|
+
if t0 is None or start - t0 >= PARA_SECONDS:
|
|
191
|
+
t0 = start
|
|
192
|
+
paras.append([_clock(start)])
|
|
193
|
+
paras[-1].append(w)
|
|
194
|
+
return "\n\n".join(" ".join(p) for p in paras)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _hidden(rel: str) -> bool:
|
|
198
|
+
return any(x.startswith(".") for x in rel.split("/"))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _sha(p: Path) -> str:
|
|
202
|
+
h = hashlib.sha256()
|
|
203
|
+
with p.open("rb") as f:
|
|
204
|
+
while chunk := f.read(1 << 20):
|
|
205
|
+
h.update(chunk)
|
|
206
|
+
return h.hexdigest()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _audio(root: Path, errors: list) -> list[Path]:
|
|
210
|
+
return [p for p in importers._walk(root, _hidden, errors)
|
|
211
|
+
if p.is_file() and not p.name.startswith(".")]
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def count(v: Vault, path: Path) -> tuple[int, int]:
|
|
215
|
+
"""(audio files, how many are new) in `path`, for the app's Check: nothing transcribed."""
|
|
216
|
+
files = [p for p in _audio(Path(path), []) if p.suffix.lower() in AUDIO]
|
|
217
|
+
known = sources._known_hashes(v)
|
|
218
|
+
new = 0
|
|
219
|
+
for p in files:
|
|
220
|
+
try:
|
|
221
|
+
new += sources._sha(f"voice {_sha(p)}") not in known
|
|
222
|
+
except OSError:
|
|
223
|
+
continue
|
|
224
|
+
return len(files), new
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def voice_source(path: Path, job=None) -> sources.Source:
|
|
228
|
+
"""A folder of audio files into one page per memo; see the module docstring. `job` (the
|
|
229
|
+
app's) gets a progress line per file, and its Cancel stops between segments."""
|
|
230
|
+
root = Path(path)
|
|
231
|
+
if not root.is_dir():
|
|
232
|
+
raise VaultError("invalid_argument", f"{root.name} is not a folder of voice memos.")
|
|
233
|
+
transcribe = load_transcriber()
|
|
234
|
+
if transcribe is None:
|
|
235
|
+
raise VaultError("invalid_argument", NEEDS)
|
|
236
|
+
stop = (lambda: job.cancelled.is_set()) if job is not None else (lambda: False)
|
|
237
|
+
|
|
238
|
+
def items():
|
|
239
|
+
v = src.vault
|
|
240
|
+
known = sources._known_hashes(v) if v is not None else {}
|
|
241
|
+
prompt = spelling(v) if v is not None else ""
|
|
242
|
+
files = _audio(root, src.walk_errors)
|
|
243
|
+
for i, p in enumerate(files, 1):
|
|
244
|
+
if stop():
|
|
245
|
+
return
|
|
246
|
+
if p.suffix.lower() not in AUDIO:
|
|
247
|
+
yield "not audio"
|
|
248
|
+
continue
|
|
249
|
+
try:
|
|
250
|
+
key, day = f"voice {_sha(p)}", recorded(p)
|
|
251
|
+
except (OSError, ValueError, OverflowError):
|
|
252
|
+
yield "unreadable"
|
|
253
|
+
continue
|
|
254
|
+
if sources._sha(key) in known: # unchanged since its import: not transcribed again
|
|
255
|
+
yield sources.Item(p.stem, day, "", str(p), key=key)
|
|
256
|
+
continue
|
|
257
|
+
if job is not None:
|
|
258
|
+
job.say(f"transcribing {i:,} of {len(files):,}: {p.name}")
|
|
259
|
+
try:
|
|
260
|
+
seconds, segs = transcribe(p, prompt)
|
|
261
|
+
text = "" if seconds > MAX_SECONDS else transcript(segs, stop)
|
|
262
|
+
except Exception: # noqa: BLE001 - PyAV and CTranslate2 raise many types
|
|
263
|
+
yield "unreadable"
|
|
264
|
+
continue
|
|
265
|
+
if text is None:
|
|
266
|
+
return
|
|
267
|
+
if seconds > MAX_SECONDS:
|
|
268
|
+
yield "over 2 hours"
|
|
269
|
+
elif not text:
|
|
270
|
+
yield "no speech"
|
|
271
|
+
else:
|
|
272
|
+
speech = re.sub(r"\[\d+:\d\d\] ", "", text)
|
|
273
|
+
first = re.split(r"(?<=[.!?])\s", speech, maxsplit=1)[0]
|
|
274
|
+
title = " ".join(speech.split()[:TITLE_WORDS]).rstrip(".,!?;:")
|
|
275
|
+
yield sources.Item(f"{day} {title}", day, text, str(p), key=key, summary=first)
|
|
276
|
+
|
|
277
|
+
src = sources.Source("voice-memos", LABEL, "folder", items,
|
|
278
|
+
default_tier=sources.Audience.LOCAL, prefix="voice", by_origin=True,
|
|
279
|
+
skips=SKIPS)
|
|
280
|
+
return src
|
keepfold/watch.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Watched folders (R18): a folder the owner adds once (`keepfold watch add`, or the app's Import
|
|
2
|
+
step) comes in by itself. The app's periodic pass (server.start's `auto` loop, after the live
|
|
3
|
+
browse import: every browse_serve.AUTO_EVERY_S) calls `run`, which re-imports each watched
|
|
4
|
+
folder through `sources.run` with its remembered source and tier: documents, notes, git
|
|
5
|
+
projects, calendars (a folder of .ics files, or one .ics file's folder: its month pages gain the
|
|
6
|
+
new lines only), or a Zotero library (keepfold.zotero).
|
|
7
|
+
|
|
8
|
+
WATCHED (.keepfold/watched.json) holds [{path, source, tier, last}]; `last` is the line of the last
|
|
9
|
+
pass that read something, failed or found the folder gone, and when. FILES
|
|
10
|
+
(.keepfold/watch-files.json) holds per folder {entry: signature}: a file's [mtime_ns, size], a
|
|
11
|
+
repo's reflog's, a Zotero item's hash (and "" the database's). An unchanged entry costs a stat,
|
|
12
|
+
never a read; at most PER_PASS new or changed ones are read per folder per pass, the rest on the
|
|
13
|
+
next. Removed files leave FILES; their pages stay.
|
|
14
|
+
|
|
15
|
+
The walk never follows a link or junction out of the folder, skips hidden and system files and
|
|
16
|
+
folders (more_sources.skip_folder's names too), files not on this computer (a cloud
|
|
17
|
+
placeholder: reading one downloads it), the vault and anything under it, and lists at most
|
|
18
|
+
MAX_LISTED files. The importers' size limits hold: their readers refuse a file over them. A
|
|
19
|
+
watched folder that is gone is reported (`missing`), kept, and never an error.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
from dataclasses import replace
|
|
27
|
+
from datetime import datetime
|
|
28
|
+
from functools import partial
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from keepfold import importers, more_sources, sources
|
|
32
|
+
from keepfold.vault import Vault, VaultError
|
|
33
|
+
|
|
34
|
+
WATCHED, FILES = ".keepfold/watched.json", ".keepfold/watch-files.json"
|
|
35
|
+
SOURCES = ("docs", "notes", "repos", "calendar", "zotero")
|
|
36
|
+
SUFFIXES = {"docs": more_sources.DOC_SUFFIXES + importers.NOTE_SUFFIXES,
|
|
37
|
+
"notes": importers.NOTE_SUFFIXES, "calendar": (".ics",)}
|
|
38
|
+
PER_PASS = 200 # new or changed files (repos, Zotero items) read per folder per pass
|
|
39
|
+
MAX_LISTED = 100_000 # files of its kinds listed per folder per pass
|
|
40
|
+
# hidden, system, offline, and the cloud placeholders that download when read (recall on open
|
|
41
|
+
# or on data access: OneDrive's Files On-Demand)
|
|
42
|
+
SKIP_ATTRS = 0x2 | 0x4 | 0x1000 | 0x40000 | 0x400000
|
|
43
|
+
GONE = "Not found; kept, and checked again on the next pass."
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _json(vault: Vault, rel: str, empty):
|
|
47
|
+
try:
|
|
48
|
+
d = json.loads((vault.root / rel).read_text("utf-8"))
|
|
49
|
+
except (OSError, ValueError):
|
|
50
|
+
return empty
|
|
51
|
+
return d if isinstance(d, type(empty)) else empty
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def watched(vault: Vault) -> list[dict]:
|
|
55
|
+
return [w for w in _json(vault, WATCHED, []) if isinstance(w, dict)
|
|
56
|
+
and isinstance(w.get("path"), str) and w.get("source") in SOURCES
|
|
57
|
+
and w.get("tier") in {a.value for a in sources.Audience}]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _write(vault: Vault, rel: str, data) -> None:
|
|
61
|
+
vault.write_text(vault.root / rel, json.dumps(data, indent=1) + "\n")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _norm(p) -> str:
|
|
65
|
+
return os.path.normcase(os.path.abspath(p))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _under(p, root: str) -> bool:
|
|
69
|
+
"""Whether `p` is the folder `root` (normcased) or inside it."""
|
|
70
|
+
p = _norm(p)
|
|
71
|
+
return p == root or p.startswith(root.rstrip(os.sep) + os.sep)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _folder(vault: Vault, path, source: str) -> Path:
|
|
75
|
+
"""The folder a watch reads: absolute, resolved, there, and not the vault or inside it."""
|
|
76
|
+
if source == "zotero":
|
|
77
|
+
from keepfold import zotero
|
|
78
|
+
folder = zotero.find(path).resolve()
|
|
79
|
+
else:
|
|
80
|
+
p = Path(str(path or "").strip().strip("\"'")).expanduser()
|
|
81
|
+
if not p.is_absolute():
|
|
82
|
+
raise VaultError("invalid_argument", "Give the folder's full path, such as "
|
|
83
|
+
"C:\\Users\\you\\Documents\\Papers.")
|
|
84
|
+
folder = p.resolve()
|
|
85
|
+
if source == "calendar" and folder.suffix.lower() == ".ics" and folder.is_file():
|
|
86
|
+
folder = folder.parent # one exported calendar: its folder's .ics files are read
|
|
87
|
+
if not folder.is_dir():
|
|
88
|
+
raise VaultError("invalid_argument", f"{folder} is not a folder.")
|
|
89
|
+
if _under(folder, _norm(vault.root.resolve())):
|
|
90
|
+
raise VaultError("invalid_argument", "That is your vault, or a folder inside it: Keepfold "
|
|
91
|
+
"has it already.")
|
|
92
|
+
return folder
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _source(source: str, folder: Path, todo: list) -> sources.Source:
|
|
96
|
+
"""The import of `todo` (walked entries) from `folder`, as `keepfold import` would make it."""
|
|
97
|
+
if source == "zotero":
|
|
98
|
+
from keepfold import zotero
|
|
99
|
+
return zotero.source(folder, todo)
|
|
100
|
+
if source == "docs": # keyed by the watched folder and its path in it (`updates`): a
|
|
101
|
+
src = more_sources.docs_source(folder, files=todo) # changed document rewrites its page
|
|
102
|
+
at = f"docs {_norm(folder)} "
|
|
103
|
+
return replace(src, items=lambda: (
|
|
104
|
+
# a document's origin is its full path, a .md/.txt note's its name in the folder
|
|
105
|
+
replace(it, key=at + Path(folder, it.origin).relative_to(folder).as_posix())
|
|
106
|
+
if isinstance(it, sources.Item) else it for it in src.items()))
|
|
107
|
+
return {"notes": partial(importers.notes_source, files=todo),
|
|
108
|
+
"repos": partial(more_sources.repos_source, repos=todo),
|
|
109
|
+
"calendar": partial(importers.calendar_source, files=todo)}[source](folder)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def add(vault: Vault, path, source: str = "docs", tier: str | None = None,
|
|
113
|
+
said=None) -> dict:
|
|
114
|
+
"""Watch `path` (for Zotero, None finds the library) as `source` at `tier` (a CLI word or
|
|
115
|
+
an Audience value; None: the source's last choice, else its default). A given tier is
|
|
116
|
+
remembered for the source and a stricter one reaches its earlier pages (sources.pick_tier;
|
|
117
|
+
its line goes to `said`). Adding a watched folder again replaces its source and tier."""
|
|
118
|
+
if source not in SOURCES:
|
|
119
|
+
raise VaultError("invalid_argument", f"source must be one of {', '.join(SOURCES)}.")
|
|
120
|
+
if tier is not None:
|
|
121
|
+
try:
|
|
122
|
+
sources.tier(tier)
|
|
123
|
+
except ValueError as e:
|
|
124
|
+
raise VaultError("invalid_argument", str(e)) from None
|
|
125
|
+
folder = _folder(vault, path, source)
|
|
126
|
+
t, _ = sources.pick_tier(vault, _source(source, folder, []), tier, save=tier is not None,
|
|
127
|
+
said=said)
|
|
128
|
+
entry = {"path": str(folder), "source": source, "tier": t.value}
|
|
129
|
+
with vault.lock():
|
|
130
|
+
rows = watched(vault)
|
|
131
|
+
old = next((w for w in rows if _norm(w["path"]) == _norm(folder)), None)
|
|
132
|
+
_write(vault, WATCHED, [w for w in rows if w is not old] + [entry])
|
|
133
|
+
if old and old["source"] != source: # another source reads other files
|
|
134
|
+
_forget(vault, old["path"])
|
|
135
|
+
return entry
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def remove(vault: Vault, path) -> bool:
|
|
139
|
+
"""Stop watching `path`; its pages stay. False when it was not watched."""
|
|
140
|
+
with vault.lock():
|
|
141
|
+
rows = watched(vault)
|
|
142
|
+
gone = _norm(Path(str(path).strip().strip("\"'")).expanduser().resolve())
|
|
143
|
+
keep = [w for w in rows if _norm(w["path"]) != gone]
|
|
144
|
+
if len(keep) == len(rows):
|
|
145
|
+
return False
|
|
146
|
+
_write(vault, WATCHED, keep)
|
|
147
|
+
for w in rows:
|
|
148
|
+
if w not in keep:
|
|
149
|
+
_forget(vault, w["path"])
|
|
150
|
+
return True
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _forget(vault: Vault, folder: str) -> None:
|
|
154
|
+
files = _json(vault, FILES, {})
|
|
155
|
+
if files.pop(folder, None) is not None:
|
|
156
|
+
_write(vault, FILES, files)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _there(w: dict) -> bool:
|
|
160
|
+
p = Path(w["path"])
|
|
161
|
+
if w["source"] == "zotero":
|
|
162
|
+
from keepfold import zotero
|
|
163
|
+
return (p / zotero.DB).is_file()
|
|
164
|
+
return p.is_dir()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def listing(vault: Vault) -> dict:
|
|
168
|
+
"""The app's rows: each watch with `missing`, and `tiers` (source -> its last tier choice,
|
|
169
|
+
else the default) for the add form."""
|
|
170
|
+
last = sources.remembered(vault)
|
|
171
|
+
return {"rows": [{**w, "missing": not _there(w)} for w in watched(vault)],
|
|
172
|
+
"tiers": {s: last.get(s, sources.Audience.CLOUD).value for s in SOURCES}}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _skip(name: str, st) -> bool:
|
|
176
|
+
return name.startswith(".") or bool(getattr(st, "st_file_attributes", 0) & SKIP_ATTRS)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def walk(folder: Path, vault_root: str, suffixes: tuple[str, ...]) -> tuple[dict, bool]:
|
|
180
|
+
"""({relative name: ([mtime_ns, size], an importers._files entry)}, whether the walk saw
|
|
181
|
+
everything): files ending in `suffixes` under `folder`, by the rules in the module
|
|
182
|
+
docstring. One stat per entry, from the folder listing."""
|
|
183
|
+
out, whole, stack = {}, True, [str(folder)]
|
|
184
|
+
cut = len(os.path.join(str(folder), ""))
|
|
185
|
+
while stack:
|
|
186
|
+
d = stack.pop()
|
|
187
|
+
try:
|
|
188
|
+
with os.scandir(d) as it:
|
|
189
|
+
entries = list(it)
|
|
190
|
+
except OSError:
|
|
191
|
+
whole = False # an unreadable folder: its files are not gone
|
|
192
|
+
continue
|
|
193
|
+
for e in entries:
|
|
194
|
+
try:
|
|
195
|
+
st = e.stat(follow_symlinks=False)
|
|
196
|
+
if e.is_symlink() or e.is_junction() or _skip(e.name, st):
|
|
197
|
+
continue
|
|
198
|
+
if e.is_dir(follow_symlinks=False):
|
|
199
|
+
if not more_sources.skip_folder(e.name) and not _under(e.path, vault_root):
|
|
200
|
+
stack.append(e.path)
|
|
201
|
+
elif e.is_file(follow_symlinks=False) and e.name.lower().endswith(suffixes):
|
|
202
|
+
if len(out) >= MAX_LISTED:
|
|
203
|
+
return out, False
|
|
204
|
+
rel = e.path[cut:].replace(os.sep, "/")
|
|
205
|
+
# its own byte budget: a pass reads up to PER_PASS whole files
|
|
206
|
+
read = partial(importers._read, rel, st.st_size, partial(open, e.path, "rb"),
|
|
207
|
+
[importers.MAX_TOTAL])
|
|
208
|
+
out[rel] = ([st.st_mtime_ns, st.st_size], (rel, st.st_size, st.st_mtime, read))
|
|
209
|
+
except OSError:
|
|
210
|
+
whole = False
|
|
211
|
+
return out, whole
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _repos(folder: Path, vault_root: str) -> tuple[dict, bool]:
|
|
215
|
+
"""{relative path: (its reflog's [mtime_ns, size], the repo)} of `more_sources.find_repos`,
|
|
216
|
+
less a repo reached through a link, junction, hidden or system folder, or the vault."""
|
|
217
|
+
out = {}
|
|
218
|
+
for repo in more_sources.find_repos(folder):
|
|
219
|
+
rel = repo.relative_to(folder)
|
|
220
|
+
steps = [folder.joinpath(*rel.parts[:i + 1]) for i in range(len(rel.parts))]
|
|
221
|
+
try:
|
|
222
|
+
if _under(repo, vault_root) or any(
|
|
223
|
+
os.path.islink(p) or os.path.isjunction(p) or _skip(p.name, p.lstat())
|
|
224
|
+
for p in steps):
|
|
225
|
+
continue
|
|
226
|
+
except OSError:
|
|
227
|
+
continue
|
|
228
|
+
git = repo / ".git" # a commit appends to logs/HEAD
|
|
229
|
+
for p in (git / "logs" / "HEAD", git / "HEAD", git):
|
|
230
|
+
try:
|
|
231
|
+
st = p.stat()
|
|
232
|
+
except OSError:
|
|
233
|
+
continue
|
|
234
|
+
out[rel.as_posix()] = ([st.st_mtime_ns, st.st_size], repo)
|
|
235
|
+
break
|
|
236
|
+
return out, True
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _pass(vault: Vault, w: dict, old: dict) -> dict:
|
|
240
|
+
"""One watched folder: its new and changed entries through `sources.run`. {path, read,
|
|
241
|
+
left, line} (`line`: the report, or why nothing was read)."""
|
|
242
|
+
folder, source, out = Path(w["path"]), w["source"], {"path": w["path"], "read": 0, "left": 0}
|
|
243
|
+
if not _there(w):
|
|
244
|
+
return {**out, "missing": True, "line": GONE}
|
|
245
|
+
if w["tier"] == sources.Audience.SKIP.value:
|
|
246
|
+
return out
|
|
247
|
+
quick = None
|
|
248
|
+
vroot = _norm(vault.root.resolve())
|
|
249
|
+
if source == "zotero":
|
|
250
|
+
from keepfold import zotero
|
|
251
|
+
quick = zotero.stat(folder)
|
|
252
|
+
if quick is not None and old.get("") == quick:
|
|
253
|
+
return out # the database is as last time: nothing is copied
|
|
254
|
+
entries, whole = {k: [s, r] for k, (s, r) in zotero.records(folder).items()}, True
|
|
255
|
+
elif source == "repos":
|
|
256
|
+
entries, whole = _repos(folder, vroot)
|
|
257
|
+
else:
|
|
258
|
+
entries, whole = walk(folder, vroot, SUFFIXES[source])
|
|
259
|
+
todo = sorted(k for k, (sig, _) in entries.items() if old.get(k) != sig)
|
|
260
|
+
batch = todo[:PER_PASS]
|
|
261
|
+
files = dict(old) if not whole else {k: old[k] for k in entries if k in old}
|
|
262
|
+
files.pop("", None)
|
|
263
|
+
if batch:
|
|
264
|
+
src = _source(source, folder, [entries[k][1] for k in batch])
|
|
265
|
+
r = sources.run(vault, src, sources.Audience(w["tier"]))
|
|
266
|
+
r.pop("gone", None) # a pass reads the changed files only: the others are not gone
|
|
267
|
+
out.update(read=len(batch), left=len(todo) - len(batch),
|
|
268
|
+
line=importers.report_line(src.label, r)
|
|
269
|
+
+ (f"; {len(todo) - len(batch):,} more on the next pass" if todo[PER_PASS:]
|
|
270
|
+
else ""))
|
|
271
|
+
files.update({k: entries[k][0] for k in batch})
|
|
272
|
+
if quick is not None and not todo[PER_PASS:]: # all read: the next pass checks the stat
|
|
273
|
+
files[""] = quick
|
|
274
|
+
if files != old:
|
|
275
|
+
with vault.lock():
|
|
276
|
+
now = _json(vault, FILES, {})
|
|
277
|
+
if any(_norm(x["path"]) == _norm(w["path"]) for x in watched(vault)): # not removed
|
|
278
|
+
_write(vault, FILES, {**now, w["path"]: files})
|
|
279
|
+
return out
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def run(vault: Vault) -> list[dict]:
|
|
283
|
+
"""One pass over every watched folder (see the module docstring); a folder that fails is
|
|
284
|
+
reported in its result and tried again on the next pass. The results, and each new line
|
|
285
|
+
is kept as the folder's `last`."""
|
|
286
|
+
old, out = _json(vault, FILES, {}), []
|
|
287
|
+
for w in watched(vault):
|
|
288
|
+
try:
|
|
289
|
+
out.append(_pass(vault, w, old.get(w["path"], {})))
|
|
290
|
+
except (VaultError, OSError, ValueError) as e:
|
|
291
|
+
out.append({"path": w["path"], "read": 0, "left": 0, "line": f"Failed: {e}"})
|
|
292
|
+
lines = {r["path"]: r for r in out if r.get("line")}
|
|
293
|
+
if lines:
|
|
294
|
+
at = datetime.now().isoformat(timespec="seconds")
|
|
295
|
+
with vault.lock():
|
|
296
|
+
rows, changed = watched(vault), False
|
|
297
|
+
for x in rows:
|
|
298
|
+
r = lines.get(x["path"])
|
|
299
|
+
if r and (r["read"] or (x.get("last") or {}).get("line") != r["line"]):
|
|
300
|
+
x["last"], changed = {"at": at, "line": r["line"]}, True
|
|
301
|
+
if changed:
|
|
302
|
+
_write(vault, WATCHED, rows)
|
|
303
|
+
return out
|