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.
Files changed (148) hide show
  1. keepfold/__init__.py +1 -0
  2. keepfold/_proc.py +102 -0
  3. keepfold/access.py +154 -0
  4. keepfold/agent_eval.py +162 -0
  5. keepfold/agent_text.py +56 -0
  6. keepfold/anki.py +285 -0
  7. keepfold/app/__init__.py +5 -0
  8. keepfold/app/actions.py +690 -0
  9. keepfold/app/desktop.py +677 -0
  10. keepfold/app/exports.py +254 -0
  11. keepfold/app/hello.py +79 -0
  12. keepfold/app/launch.py +114 -0
  13. keepfold/app/news.py +60 -0
  14. keepfold/app/server.py +3142 -0
  15. keepfold/app/status.py +811 -0
  16. keepfold/app/targets.py +1374 -0
  17. keepfold/app/winpath.py +54 -0
  18. keepfold/app/wizard.py +506 -0
  19. keepfold/ask.py +475 -0
  20. keepfold/askfile.py +322 -0
  21. keepfold/assets/LICENSE-d3.txt +13 -0
  22. keepfold/assets/agent_eval.json +235 -0
  23. keepfold/assets/app/app.css +611 -0
  24. keepfold/assets/app/app.js +2712 -0
  25. keepfold/assets/app/capture.html +16 -0
  26. keepfold/assets/app/capture.js +91 -0
  27. keepfold/assets/app/index.html +149 -0
  28. keepfold/assets/brain3d.js +3730 -0
  29. keepfold/assets/chat_eval.json +454 -0
  30. keepfold/assets/d3.v7.min.js +2 -0
  31. keepfold/assets/dashboard.css +774 -0
  32. keepfold/assets/dashboard.html.tmpl +170 -0
  33. keepfold/assets/dashboard.js +4262 -0
  34. keepfold/assets/help/GUIDE.md +544 -0
  35. keepfold/assets/help/help.md +83 -0
  36. keepfold/assets/keepfold.ico +0 -0
  37. keepfold/assets/whats_new.json +162 -0
  38. keepfold/backup.py +100 -0
  39. keepfold/brainmap.py +1382 -0
  40. keepfold/browse/__init__.py +10 -0
  41. keepfold/browse/build.py +1320 -0
  42. keepfold/browse/forget.py +510 -0
  43. keepfold/browse/legacy.py +95 -0
  44. keepfold/browse/lists.py +285 -0
  45. keepfold/browse/privacy.py +391 -0
  46. keepfold/browse/selftest.py +166 -0
  47. keepfold/browse/sites.py +1068 -0
  48. keepfold/browse/sources.py +329 -0
  49. keepfold/browse/store.py +991 -0
  50. keepfold/browse/takeout.py +312 -0
  51. keepfold/browse/titles.py +127 -0
  52. keepfold/browse/vectors.py +326 -0
  53. keepfold/browse_serve.py +332 -0
  54. keepfold/catalog.py +564 -0
  55. keepfold/chat.py +1464 -0
  56. keepfold/chat_archive.py +165 -0
  57. keepfold/chat_eval.py +583 -0
  58. keepfold/chat_facts.py +721 -0
  59. keepfold/chat_import.py +1045 -0
  60. keepfold/chat_pages.py +291 -0
  61. keepfold/chat_study.py +371 -0
  62. keepfold/chats.py +669 -0
  63. keepfold/claims.py +650 -0
  64. keepfold/cli.py +3254 -0
  65. keepfold/clients.py +96 -0
  66. keepfold/cloudllm.py +135 -0
  67. keepfold/contract.py +43 -0
  68. keepfold/corrections.py +134 -0
  69. keepfold/dashboard.py +959 -0
  70. keepfold/dates.py +202 -0
  71. keepfold/delta.py +146 -0
  72. keepfold/digest.py +72 -0
  73. keepfold/doctor.py +565 -0
  74. keepfold/duplicates.py +145 -0
  75. keepfold/egress.py +68 -0
  76. keepfold/eval_history.py +109 -0
  77. keepfold/events.py +554 -0
  78. keepfold/export_context.py +109 -0
  79. keepfold/fact_harvest.py +578 -0
  80. keepfold/forget.py +720 -0
  81. keepfold/harvest.py +334 -0
  82. keepfold/home.py +714 -0
  83. keepfold/importers.py +627 -0
  84. keepfold/index.py +733 -0
  85. keepfold/know.py +40 -0
  86. keepfold/learning_eval.py +261 -0
  87. keepfold/levels.py +595 -0
  88. keepfold/life_sources.py +747 -0
  89. keepfold/lint.py +241 -0
  90. keepfold/localllm.py +699 -0
  91. keepfold/loops.py +316 -0
  92. keepfold/mcp_server.py +4464 -0
  93. keepfold/migrate.py +552 -0
  94. keepfold/more_sources.py +709 -0
  95. keepfold/packs.py +148 -0
  96. keepfold/people.py +99 -0
  97. keepfold/planner.py +819 -0
  98. keepfold/prime.py +630 -0
  99. keepfold/prime_hook.py +265 -0
  100. keepfold/profiles.py +118 -0
  101. keepfold/quarantine.py +123 -0
  102. keepfold/recall_log.py +93 -0
  103. keepfold/redteam.py +393 -0
  104. keepfold/reflect.py +164 -0
  105. keepfold/relink.py +477 -0
  106. keepfold/render.py +406 -0
  107. keepfold/review.py +1181 -0
  108. keepfold/rollups.py +412 -0
  109. keepfold/safety_net.py +571 -0
  110. keepfold/sample.py +103 -0
  111. keepfold/sample_vault/areas/programming.algorithms.md +11 -0
  112. keepfold/sample_vault/areas/programming.basics.md +11 -0
  113. keepfold/sample_vault/concepts/big-o-notation.md +13 -0
  114. keepfold/sample_vault/concepts/functions.md +13 -0
  115. keepfold/sample_vault/concepts/loops.md +14 -0
  116. keepfold/sample_vault/concepts/recursion.md +13 -0
  117. keepfold/sample_vault/domains/programming.md +10 -0
  118. keepfold/sample_vault/journal/2026-01-12.md +9 -0
  119. keepfold/sample_vault/me/goals.md +17 -0
  120. keepfold/sample_vault/me/profile.md +19 -0
  121. keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
  122. keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
  123. keepfold/sample_vault/problems/fizzbuzz.md +12 -0
  124. keepfold/sample_vault/projects/text-adventure.md +15 -0
  125. keepfold/sample_vault/resources/python-tutorial.md +16 -0
  126. keepfold/semantic.py +1254 -0
  127. keepfold/session.py +764 -0
  128. keepfold/share.py +69 -0
  129. keepfold/sources.py +612 -0
  130. keepfold/sync_copies.py +83 -0
  131. keepfold/tags.py +230 -0
  132. keepfold/taint.py +301 -0
  133. keepfold/tonight.py +195 -0
  134. keepfold/topics.py +1072 -0
  135. keepfold/update.py +300 -0
  136. keepfold/vault.py +942 -0
  137. keepfold/vecstore.py +218 -0
  138. keepfold/voice.py +260 -0
  139. keepfold/voice_memos.py +280 -0
  140. keepfold/watch.py +303 -0
  141. keepfold/where.py +119 -0
  142. keepfold/xray.py +516 -0
  143. keepfold/zotero.py +303 -0
  144. keepfold-0.6.4.dist-info/METADATA +644 -0
  145. keepfold-0.6.4.dist-info/RECORD +148 -0
  146. keepfold-0.6.4.dist-info/WHEEL +4 -0
  147. keepfold-0.6.4.dist-info/entry_points.txt +6 -0
  148. keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,709 @@
1
+ """Three `keepfold import` sources on `sources.Source` (v9 item 14): documents, the owner's git
2
+ repos and reading highlights. Each page is short, dated and says what it is in its first line,
3
+ so the local Chat (a small model reading a few ~700-character passages) can answer from it.
4
+
5
+ - docs: one page per .pdf/.docx (pypdf; .docx through zipfile + its word/document.xml): the
6
+ title (PDF metadata, else the file name), the date (PDF creation date, else the file's), the
7
+ full text up to DOC_FULL_CHARS (R17; a PDF's pages under `## Page N` headings, `_paged`).
8
+ Keyed by its first DOC_CHARS characters (all a page held before R17) with `updates`, so a
9
+ re-import refills a page imported clipped, unless the owner edited it (`keeps_edits`).
10
+ .md/.txt go through importers.note_item, keyed as notes are, so a
11
+ note imported before is a duplicate here. Encrypted, scanned (no text) and oversized files are
12
+ skipped with the reason. C2: on Windows a scanned PDF's pages are read with Windows' own
13
+ offline OCR in the parse child (`_pdf_pages`), and the page ends with OCR_LINE.
14
+ - repos: one page per git repo one or two folders down (or the folder itself): the README's
15
+ start, the stack from manifest file names, and from `git log --author=<that repo's
16
+ user.email>` the commit count, first and last dates and the last SUBJECTS subjects. Code,
17
+ diffs and other files' contents are never read; `drops_code` turns a README's code blocks
18
+ into "[code left out]". Keyed by the repo's path with `updates`, so a re-import rewrites it.
19
+ Of the last MINED subjects, the decision-like ones (`decision_word`) are listed on the page;
20
+ the app's Review offers each as an unconfirmed decision (`decision_proposals`).
21
+ - highlights: Kindle `My Clippings.txt` and Readwise CSV make one page per book (one per book
22
+ and month past MANY highlights), keyed by book with `updates`; a Pocket CSV (saved articles,
23
+ no highlights) makes month pages. The format is read from the content, not the file name.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import calendar
29
+ import csv
30
+ import functools
31
+ import io
32
+ import json
33
+ import os
34
+ import queue
35
+ import re
36
+ import subprocess
37
+ import sys
38
+ import threading
39
+ import time
40
+ import zipfile
41
+ from collections import defaultdict
42
+ from datetime import datetime
43
+ from pathlib import Path, PurePosixPath
44
+ from xml.etree import ElementTree
45
+
46
+ from keepfold import importers, life_sources, sources
47
+ from keepfold._proc import NO_WINDOW
48
+ from keepfold.vault import VaultError, is_private
49
+
50
+ DOC_SUFFIXES = (".pdf", ".docx")
51
+ DOC_CHARS, README_CHARS, SUBJECTS, MANY = 1500, 800, 20, 50
52
+ # R17: a document page keeps its full text up to this (about 250 dense pages), so embedding it
53
+ # and opening it in Obsidian stay quick; DOC_CHARS is now only the dedupe key (what the import
54
+ # kept before R17, so a page imported then is found and refilled)
55
+ DOC_FULL_CHARS = 500_000
56
+ KEPT = "Keepfold kept the first {} of {} pages." # a PDF page past DOC_FULL_CHARS or the OCR limits
57
+ # the docs import's lines that are never a page's summary: its page headings and KEPT's line
58
+ NOT_SUMMARY = re.compile(r"## Page \d+|(?:Keepfold|Keepfold) kept the first \d+ of \d+ pages\.")
59
+ MINED, SHOWN_DECISIONS = 200, 5 # subjects mined per repo; decision cards shown at a time
60
+ DECISIONS = "Decisions in my commits" # the repo page's section of decision-like subjects
61
+ # RR-9's narrow set: bare remove, drop and rename are left out (too noisy)
62
+ _DECIDES = re.compile(
63
+ r"\b(decided|decide|decision|chose|choose|switch(?:ed)? to|migrated? to|adopt(?:ed)?|"
64
+ r"deprecated?|replaced? .{1,60}? with|instead of|in favou?r of|default to|moved? to|ADR)\b",
65
+ re.I)
66
+ _NOT_DECISION = re.compile(
67
+ r"^\W*(?:merge|bump|release|wip|fixup|typo|lint|format|revert)(?:s|ed|ing|ting)?\b", re.I)
68
+ _HIT = re.compile(r"^- (\d{4}-\d\d-\d\d) ([0-9a-f]{12}) \(([^)]+)\): (.+)$")
69
+ DOC_SKIPS = ("not a document", "encrypted", "scanned or no text", "over 200 MB", "unreadable",
70
+ "over 5 MB", "not UTF-8 text", "a shortcut, not the file", "parse timed out")
71
+ # RR-37: folders never walked (any hidden folder too), and shortcut files that only point at a
72
+ # document somewhere else (a cloud doc, a link) and hold none of its text
73
+ SKIP_DIRS = frozenset({"node_modules", ".git", ".venv", "__pycache__"})
74
+ POINTERS = (".url", ".lnk", ".gdoc", ".gsheet", ".gslides")
75
+ FOLD_CASE = os.name == "nt" # Windows folder names ignore case (tests patch it)
76
+ PARSE_TIMEOUT = 30.0 # seconds one PDF or .docx may take in the child before it is a skip
77
+ # C2 limits on Windows OCR of scanned pages (`_pdf_pages`): at most OCR_PAGES pages per file, and
78
+ # no page started past OCR_BUDGET seconds into the file, so a long scan returns the pages read
79
+ # so far well inside PARSE_TIMEOUT (unchanged) instead of being killed with nothing
80
+ OCR_PAGES, OCR_BUDGET = 100, 20.0
81
+ OCR_LINE = "Read with Windows OCR: check names and numbers." # an OCR'd document page's mark
82
+ _CHILD = [sys.executable, "-c", "from keepfold.more_sources import _parse_child; _parse_child()"]
83
+ _W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
84
+ _DC = "{http://purl.org/dc/elements/1.1/}"
85
+ _OLE = b"\xd0\xcf\x11\xe0" # a password-protected .docx is an OLE container, not a zip
86
+ # manifest file name -> stack; only names are looked at, never their contents
87
+ STACKS = {"pyproject.toml": "Python", "setup.py": "Python", "requirements.txt": "Python",
88
+ "package.json": "JavaScript", "tsconfig.json": "TypeScript", "deno.json": "Deno",
89
+ "Cargo.toml": "Rust", "go.mod": "Go", "pom.xml": "Java", "build.gradle": "Java",
90
+ "build.gradle.kts": "Kotlin", "Gemfile": "Ruby", "composer.json": "PHP",
91
+ "CMakeLists.txt": "C/C++", "pubspec.yaml": "Dart", "Package.swift": "Swift",
92
+ "mix.exs": "Elixir", "stack.yaml": "Haskell", "build.sbt": "Scala"}
93
+ STACK_SUFFIXES = {".csproj": "C#", ".sln": ".NET", ".fsproj": "F#"}
94
+ _MONTHS = {m.lower(): i for i, m in enumerate(calendar.month_name) if m}
95
+ # Kindle's "Added on Monday, 3 March 2025 10:00:00" or "Added on Monday, March 3, 2025 …"
96
+ _KDATE = re.compile(r"(?:(\d{1,2}) ([A-Za-z]+)|([A-Za-z]+) (\d{1,2}),) (\d{4})")
97
+
98
+
99
+ def _day(ts: float) -> str:
100
+ """A timestamp's Keepfold day (local, 04:00 rollover), as importers.note_item dates notes."""
101
+ return importers._day(ts)
102
+
103
+
104
+ def _clip(text: str, n: int) -> str:
105
+ """The first ~n characters, cut at a space."""
106
+ return text if len(text) <= n else text[:n].rsplit(" ", 1)[0] + " …"
107
+
108
+
109
+ def _origin(path: Path, name: str) -> str:
110
+ return str(path / name) if path.is_dir() else str(path)
111
+
112
+
113
+ # ---- docs ----
114
+
115
+ def _pdf(data: bytes) -> tuple[str, str, list[str], int, int | None] | str:
116
+ """`_pdf_pages` read up to DOC_FULL_CHARS: the documents import's PDF parse."""
117
+ return _pdf_pages(data, DOC_FULL_CHARS)
118
+
119
+
120
+ def _paged(pages: list[str], total: int) -> tuple[str, str]:
121
+ """(a PDF page's text, the text as one line): each page with text on one line under a
122
+ `## Page N` heading (an empty page is skipped, the numbers stay true), whole pages up to
123
+ DOC_FULL_CHARS (a first page longer than that is clipped), and KEPT's line first when pages
124
+ were left out here or by `_pdf_pages` (its char or OCR limits)."""
125
+ flat = [(n, " ".join(p.split())) for n, p in enumerate(pages, 1)]
126
+ flat = [(n, p) for n, p in flat if p]
127
+ parts, size, kept = [], 0, len(pages)
128
+ for n, p in flat:
129
+ part = f"## Page {n}\n{p}"
130
+ if size + len(part) > DOC_FULL_CHARS:
131
+ kept = n - 1 if parts else n
132
+ parts = parts or [_clip(part, DOC_FULL_CHARS)]
133
+ break
134
+ parts.append(part)
135
+ size += len(part) + 2
136
+ head = [KEPT.format(kept, total)] if kept < total else []
137
+ return "\n\n".join(head + parts), " ".join(p for _, p in flat)
138
+
139
+
140
+ @functools.cache
141
+ def _ocr_engine():
142
+ """C2: Windows' offline OCR engine in the person's own languages, or None (not Windows, no
143
+ text-recognition language installed, or the winrt packages missing). Only the parse child
144
+ calls it: nothing is OCR'd in the server, and nothing leaves the computer."""
145
+ if sys.platform != "win32":
146
+ return None
147
+ try:
148
+ from winrt.windows.media.ocr import OcrEngine
149
+ return OcrEngine.try_create_from_user_profile_languages()
150
+ except Exception: # noqa: BLE001 - an import or WinRT failure: no OCR, as before C2
151
+ return None
152
+
153
+
154
+ def _ocr(engine, page) -> str:
155
+ """C2: the text OCR reads in `page`'s images, a line per line read, in reading order; ""
156
+ when the page fails, so that one page is skipped, not the file."""
157
+ import asyncio
158
+ try:
159
+ return asyncio.run(_recognize(engine, [im.image for im in page.images]))
160
+ except Exception: # noqa: BLE001 - an image pypdf or Windows cannot decode, a WinRT error
161
+ return ""
162
+
163
+
164
+ async def _recognize(engine, images) -> str:
165
+ from winrt.windows.graphics.imaging import BitmapDecoder
166
+ from winrt.windows.media.ocr import OcrEngine
167
+ from winrt.windows.storage.streams import Buffer, InMemoryRandomAccessStream
168
+ most, lines = OcrEngine.max_image_dimension, []
169
+ for im in images:
170
+ im = im.convert("RGB") # a fresh copy in a mode BMP holds (CMYK, 1-bit, palette...)
171
+ im.thumbnail((most, most)) # only ever scales down, keeping the aspect
172
+ out = io.BytesIO()
173
+ im.save(out, "BMP") # uncompressed: the quickest for Windows to decode
174
+ data = out.getvalue()
175
+ buf = Buffer(len(data)) # in memory only: nothing is written to disk
176
+ buf.length = len(data)
177
+ memoryview(buf)[:] = data
178
+ stream = InMemoryRandomAccessStream()
179
+ await stream.write_async(buf)
180
+ stream.seek(0)
181
+ bmp = await (await BitmapDecoder.create_async(stream)).get_software_bitmap_async()
182
+ lines += [ln.text for ln in (await engine.recognize_async(bmp)).lines]
183
+ return "\n".join(lines)
184
+
185
+
186
+ def _pdf_pages(data: bytes, limit: int) -> tuple[str, str, list[str], int, int | None] | str:
187
+ """(title, YYYY-MM-DD or "", each page's text up to about `limit` characters in all, the
188
+ page count, ocr) or a skip reason. The app's Chat reads an attached PDF this way (askfile).
189
+
190
+ C2: a page with no text but with images (a scan) is read with Windows OCR (`_ocr`); a page
191
+ with some text is never OCR'd. `ocr` is how many pages OCR read text from, or None when no
192
+ page has text and this computer has no OCR (`_ocr_engine`): then nothing changes from
193
+ before C2. Limits: at most OCR_PAGES pages are OCR'd per file, and none is started past
194
+ OCR_BUDGET seconds; at either the reading stops there, so `pages` is shorter than the page
195
+ count (askfile says where it stopped)."""
196
+ from pypdf import PdfReader
197
+ start = time.monotonic()
198
+ try:
199
+ rd = PdfReader(io.BytesIO(data))
200
+ if rd.is_encrypted:
201
+ try: # many "encrypted" PDFs open with an empty password
202
+ if not rd.decrypt(""):
203
+ return "encrypted"
204
+ except Exception: # noqa: BLE001 - AES needs a crypto library pypdf may lack
205
+ return "encrypted"
206
+ pages, n, tried, read = [], 0, 0, 0
207
+ for page in rd.pages:
208
+ text = page.extract_text() or ""
209
+ if not text.strip() and _has_images(page) and (engine := _ocr_engine()) is not None:
210
+ if tried >= OCR_PAGES or time.monotonic() - start > OCR_BUDGET:
211
+ break
212
+ tried += 1
213
+ text = _ocr(engine, page)
214
+ read += bool(text.strip())
215
+ pages.append(text)
216
+ n += 1 + len(pages[-1])
217
+ if n > limit:
218
+ break
219
+ total = len(rd.pages)
220
+ meta = rd.metadata
221
+ title = str(meta.title or "").strip() if meta else ""
222
+ try:
223
+ made = meta.creation_date.date().isoformat() if meta and meta.creation_date else ""
224
+ except Exception: # noqa: BLE001 - a malformed date string
225
+ made = ""
226
+ except Exception: # noqa: BLE001 - pypdf raises many types on a damaged file
227
+ return "unreadable"
228
+ # the engine is only asked for when no page has text, so a text PDF never loads it
229
+ ocr = read if any(p.strip() for p in pages) or _ocr_engine() is not None else None
230
+ return title, made, pages, total, ocr
231
+
232
+
233
+ def _has_images(page) -> bool:
234
+ try:
235
+ return len(page.images) > 0
236
+ except Exception: # noqa: BLE001 - a damaged resource: no OCR, the page as before C2
237
+ return False
238
+
239
+
240
+ def _docx(data: bytes) -> tuple[str, str, str] | str:
241
+ if data[:4] == _OLE:
242
+ return "encrypted"
243
+ try:
244
+ z = zipfile.ZipFile(io.BytesIO(data))
245
+ info = z.getinfo("word/document.xml")
246
+ if info.file_size > importers.MAX_ENTRY:
247
+ return "over 200 MB"
248
+ doc = ElementTree.fromstring(z.read(info))
249
+ paras = (" ".join("".join(t.text or "" for t in p.iter(_W + "t")).split())
250
+ for p in doc.iter(_W + "p"))
251
+ title = ""
252
+ if "docProps/core.xml" in z.namelist():
253
+ t = ElementTree.fromstring(z.read("docProps/core.xml")).find(_DC + "title")
254
+ title = (t.text or "").strip() if t is not None else ""
255
+ except (zipfile.BadZipFile, KeyError, ElementTree.ParseError, OSError):
256
+ return "unreadable"
257
+ return title, "", "\n".join(p for p in paras if p)
258
+
259
+
260
+ PAGES_CHARS = 2_400_000 # a "pdfpages" parse stops past this many characters (askfile's cap)
261
+
262
+
263
+ def _parse_child() -> None:
264
+ """The parse child's loop: `<kind> <n>\\n` and n bytes in on stdin, one JSON line out (the
265
+ `_pdf` / `_pdf_pages` / `_docx` result for kind pdf / pdfpages / docx) per document, until
266
+ stdin closes."""
267
+ inp, out = sys.stdin.buffer, sys.stdout
268
+ while head := inp.readline():
269
+ kind, n = head.split()
270
+ data = inp.read(int(n))
271
+ out.write(json.dumps(_pdf(data) if kind == b"pdf" else
272
+ _pdf_pages(data, PAGES_CHARS) if kind == b"pdfpages" else
273
+ _docx(data)) + "\n")
274
+ out.flush()
275
+
276
+
277
+ class _Parser:
278
+ """RR-37: PDF and .docx parsing in a child process (`_CHILD`), so a hostile file that
279
+ hangs or crashes pypdf is one "parse timed out" (or "unreadable") skip after
280
+ PARSE_TIMEOUT, not a hung import. One child serves the whole walk; a timeout kills it and
281
+ the next document starts a new one."""
282
+
283
+ def __init__(self):
284
+ self.proc = None
285
+
286
+ def __call__(self, kind: str, data: bytes) -> tuple[str, str, str] | str:
287
+ if self.proc is None:
288
+ self.proc = subprocess.Popen(_CHILD, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
289
+ stderr=subprocess.DEVNULL, creationflags=NO_WINDOW)
290
+ self.lines = queue.Queue()
291
+ threading.Thread(target=self._pump, args=(self.proc.stdout, self.lines),
292
+ daemon=True).start()
293
+ try:
294
+ self.proc.stdin.write(f"{kind} {len(data)}\n".encode() + data)
295
+ self.proc.stdin.flush()
296
+ line = self.lines.get(timeout=PARSE_TIMEOUT)
297
+ except queue.Empty:
298
+ self.close()
299
+ return "parse timed out"
300
+ except OSError: # the child died while reading
301
+ line = None
302
+ if line is None:
303
+ self.close()
304
+ return "unreadable"
305
+ got = json.loads(line)
306
+ return got if isinstance(got, str) else tuple(got)
307
+
308
+ @staticmethod
309
+ def _pump(stream, lines: queue.Queue) -> None:
310
+ try:
311
+ for line in stream:
312
+ lines.put(line)
313
+ except (OSError, ValueError): # closed by `close` after a kill
314
+ pass
315
+ lines.put(None) # end of output: the child exited
316
+
317
+ def close(self) -> None:
318
+ if self.proc is not None:
319
+ self.proc.kill()
320
+ self.proc.wait()
321
+ for f in (self.proc.stdin, self.proc.stdout):
322
+ f.close()
323
+ self.proc = None
324
+
325
+
326
+ def _fold(name: str) -> str:
327
+ return name.casefold() if FOLD_CASE else name
328
+
329
+
330
+ def skip_folder(rel: str, rules: tuple[str, ...] = ()) -> bool:
331
+ """Whether the folder `rel` (relative to the import, "/"-separated) is left out: any hidden
332
+ folder or SKIP_DIRS name in it, or a `rules` entry ("Archive", "School/Old") matching whole
333
+ folder names in a row, so "Archive" never matches "Archived"; case-folded on Windows."""
334
+ parts = [_fold(p) for p in rel.replace("\\", "/").split("/") if p and p != "."]
335
+ if any(p.startswith(".") or p in SKIP_DIRS for p in parts):
336
+ return True
337
+ for rule in rules:
338
+ seg = [_fold(p) for p in rule.replace("\\", "/").split("/") if p]
339
+ if seg and any(parts[i:i + len(seg)] == seg for i in range(len(parts))):
340
+ return True
341
+ return False
342
+
343
+
344
+ def docs_source(path: Path, skip: tuple[str, ...] = (), files: list | None = None
345
+ ) -> sources.Source:
346
+ """One page per document in the folder (or the one file); see the module docstring. The
347
+ walk leaves out `skip_folder`'s folders (`skip`: more folder rules) and shortcut files.
348
+ `files`: `importers._files` entries already walked (a watched folder's changed ones)."""
349
+ path = Path(path)
350
+ if files is None:
351
+ files = importers._files(path, skip_dir=lambda rel: skip_folder(rel, skip))
352
+
353
+ def items():
354
+ parse = _Parser()
355
+ try:
356
+ yield from _doc_items(path, files, skip, parse)
357
+ finally:
358
+ parse.close()
359
+
360
+ return _docs(items)
361
+
362
+
363
+ def _docs(items) -> sources.Source:
364
+ """R17: `updates` (keyed by the text the import kept before), so a page imported clipped
365
+ gets its full text, unless the owner edited it (`keeps_edits`)."""
366
+ return sources.Source("docs", "Documents", "folder", items, skips=DOC_SKIPS, updates=True,
367
+ keeps_edits=True, not_summary=NOT_SUMMARY)
368
+
369
+
370
+ def doc_source(name: str, size: int, mtime: float, read, parse) -> sources.Source:
371
+ """The documents import of one file already read (the app Chat's Save to your brain,
372
+ askfile): `read` gives its bytes, `parse` stands in for the child (`_Parser`'s result)."""
373
+ return _docs(lambda: _doc_items(Path(name), [(name, size, mtime, read)], (), parse))
374
+
375
+
376
+ def _doc_items(path: Path, files: list, skip: tuple[str, ...], parse: _Parser):
377
+ for name, size, mtime, read in files:
378
+ low, folder = name.lower(), PurePosixPath(name).parent.as_posix()
379
+ if PurePosixPath(name).name.startswith(".") or skip_folder(folder, skip):
380
+ yield "not a document" # a hidden file, or a skipped folder inside a .zip
381
+ continue
382
+ if low.endswith(POINTERS):
383
+ yield "a shortcut, not the file"
384
+ continue
385
+ if not low.endswith(DOC_SUFFIXES + importers.NOTE_SUFFIXES):
386
+ yield "not a document"
387
+ continue
388
+ if low.endswith(importers.NOTE_SUFFIXES):
389
+ yield importers.note_item(name, size, mtime, read)
390
+ continue
391
+ try:
392
+ data = read() if size <= importers.MAX_ENTRY else None
393
+ except VaultError: # past the whole import's cap
394
+ data = None
395
+ if data is None:
396
+ yield "over 200 MB"
397
+ continue
398
+ got = parse("pdf" if low.endswith(".pdf") else "docx", data)
399
+ if isinstance(got, str):
400
+ yield got
401
+ continue
402
+ if isinstance(got[2], list): # a PDF: `_pdf_pages`' pages
403
+ title, made, pages, total, ocr = got
404
+ text, flat = _paged(pages, total)
405
+ else:
406
+ (title, made, flat), ocr = got, 0
407
+ text = _clip(flat, DOC_FULL_CHARS)
408
+ if not text.strip():
409
+ yield "scanned or no text"
410
+ continue
411
+ mark = ("\n\n" + OCR_LINE) * bool(ocr) # last: the first body line is the page's summary
412
+ # the key is the text the import kept before R17, so its page is found and refilled
413
+ yield sources.Item(title or PurePosixPath(name).stem, made or _day(mtime), text + mark,
414
+ _origin(path, name), key=_clip(flat, DOC_CHARS) + mark)
415
+
416
+
417
+ # ---- repos ----
418
+
419
+ def _is_repo(d: Path) -> bool:
420
+ return (d / ".git").exists()
421
+
422
+
423
+ def _subdirs(d: Path) -> list[Path]:
424
+ try:
425
+ return sorted(p for p in d.iterdir() if p.is_dir() and not p.name.startswith("."))
426
+ except OSError:
427
+ return []
428
+
429
+
430
+ def find_repos(folder: Path) -> list[Path]:
431
+ """The folder itself when it is a repo, else the repos one or two folders down."""
432
+ folder = Path(folder)
433
+ if _is_repo(folder):
434
+ return [folder]
435
+ out = []
436
+ for d in _subdirs(folder):
437
+ out += [d] if _is_repo(d) else [e for e in _subdirs(d) if _is_repo(e)]
438
+ return out
439
+
440
+
441
+ def holds_repos(path: Path) -> bool:
442
+ """For `importers.detect`: a folder (not an Obsidian vault) with repos one or two down."""
443
+ path = Path(path)
444
+ return path.is_dir() and not (path / ".obsidian").exists() and not _is_repo(path) \
445
+ and bool(find_repos(path))
446
+
447
+
448
+ def _git(repo: Path, *args: str) -> subprocess.CompletedProcess:
449
+ return subprocess.run(["git", "-C", str(repo), "-c", "log.showSignature=false", *args],
450
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
451
+ timeout=60, creationflags=NO_WINDOW)
452
+
453
+
454
+ def _stack(names: list[str]) -> list[str]:
455
+ got = [STACKS[n] for n in names if n in STACKS] + \
456
+ [s for n in names for x, s in STACK_SUFFIXES.items() if n.endswith(x)]
457
+ return list(dict.fromkeys(got))
458
+
459
+
460
+ def _readme(repo: Path, names: list[str]) -> str:
461
+ for n in sorted(names):
462
+ if n.lower().startswith("readme") and (repo / n).is_file():
463
+ with (repo / n).open("rb") as f:
464
+ return _clip(f.read(4 * README_CHARS).decode("utf-8-sig", "replace").strip(),
465
+ README_CHARS)
466
+ return ""
467
+
468
+
469
+ def decision_word(subject: str) -> str | None:
470
+ """The signal word that makes a commit subject look like a decision ("switched to",
471
+ "replace … with"), or None; subjects starting with merge, bump, release, wip, fixup, typo,
472
+ lint, format or revert never are."""
473
+ if _NOT_DECISION.match(subject) or not (m := _DECIDES.search(subject)):
474
+ return None
475
+ w = " ".join(m.group(1).lower().split())
476
+ return re.sub(r"^(replaced?) .* with$", r"\1 … with", w)
477
+
478
+
479
+ def repo_item(repo: Path) -> sources.Item | str:
480
+ """One repo's Item, or why it is skipped. Reads git's log subjects, hashes and dates, the
481
+ root's file names and the README; nothing else. Of the last MINED subjects, those
482
+ `decision_word` picks are listed under `## DECISIONS` (date, hash, word, subject) for the
483
+ Review to offer (`decision_proposals`)."""
484
+ try:
485
+ email = (_git(repo, "config", "user.email").stdout or "").strip()
486
+ if not email:
487
+ return "no git user.email"
488
+ log = _git(repo, "log", "--fixed-strings", f"--author={email}", "--date=short",
489
+ "--format=%ad%x09%H%x09%s")
490
+ except (OSError, subprocess.SubprocessError):
491
+ return "git could not read it"
492
+ if log.stdout is None: # captured output is a str; anything else is a broken git run
493
+ return "git could not read it"
494
+ rows = [r for ln in log.stdout.splitlines() if len(r := ln.split("\t", 2)) == 3] \
495
+ if log.returncode == 0 else []
496
+ if not rows:
497
+ return "no commits by you"
498
+ names = sorted(os.listdir(repo), key=str.upper) # NTFS's order; ext4 lists in hash order
499
+ stack, readme = _stack(names), _readme(repo, names)
500
+ first, last = rows[-1][0], rows[0][0]
501
+ n = len(rows)
502
+ head = (f"Git repository {repo.name}" + (f" ({', '.join(stack)})" if stack else "")
503
+ + f": {n:,} commit{'s' * (n != 1)} by me, from {first} to {last}.")
504
+ hits = [f"- {d} {h[:12]} ({w}): {s}" for d, h, s in rows[:MINED] if (w := decision_word(s))]
505
+ text = head + (f"\n\n## README\n{readme}" if readme else "") + \
506
+ f"\n\n## My last {min(n, SUBJECTS)} commits\n" + \
507
+ "\n".join(f"- {d} {s}" for d, _, s in rows[:SUBJECTS]) + \
508
+ (f"\n\n## {DECISIONS}\n" + "\n".join(hits) if hits else "")
509
+ return sources.Item(repo.name, last, text, str(repo), key=f"repo {repo.resolve()}")
510
+
511
+
512
+ def decision_proposals(vault, events) -> list[dict]:
513
+ """RR-9: up to SHOWN_DECISIONS commit subjects from the repo pages' `## DECISIONS`, newest
514
+ first, as {key, page, project, date, hash, word, subject, private} for the app's Review.
515
+ The key hashes the repo page and the commit, so a re-import never offers one again; left
516
+ out are those the owner approved (a `decide` change) or dismissed (a `dismiss` change), both
517
+ on id `decisions` and holding the key. `private` follows the repo page (an unreadable page
518
+ counts as private), and Approve makes a private page's decision private too."""
519
+ from keepfold import review
520
+ events = list(events)
521
+ voided = review._voided(events)
522
+ done = {c.get("hash") for e in events if e.get("kind") == "change"
523
+ and e.get("id") not in voided and isinstance(c := review._payload(e).get("change"),
524
+ dict)
525
+ and c.get("tool") in ("dismiss", "decide") and c.get("id") == "decisions"}
526
+ out = []
527
+ for p in sorted((vault.root / "resources").glob("repo-*.md")):
528
+ try:
529
+ note = vault.read_path(p)
530
+ except VaultError:
531
+ continue
532
+ if not re.search(r"^Source: Git · ", note.body, re.M):
533
+ continue
534
+ private, project = is_private(note), str(note.fields.get("title") or p.stem)
535
+ section = note.body.partition(f"\n## {DECISIONS}\n")[2].split("\n## ", 1)[0]
536
+ for m in map(_HIT.match, section.splitlines()):
537
+ key = review.text_hash(f"{p.stem} {m.group(2)}") if m else None
538
+ if m and key not in done:
539
+ out.append({"key": key, "page": p.stem, "project": project, "date": m.group(1),
540
+ "hash": m.group(2), "word": m.group(3), "subject": m.group(4),
541
+ "private": private})
542
+ out.sort(key=lambda x: (x["date"], x["project"], x["hash"]), reverse=True)
543
+ return out[:SHOWN_DECISIONS]
544
+
545
+
546
+ def repos_source(path: Path, repos: list[Path] | None = None) -> sources.Source:
547
+ """One page per repo `find_repos` finds (or per one of `repos`, a watched folder's changed
548
+ ones); see the module docstring."""
549
+ path = Path(path)
550
+ if not path.is_dir():
551
+ raise VaultError("invalid_argument", f"{path.name} is not a folder of git projects.")
552
+ if repos is None and not (repos := find_repos(path)):
553
+ raise VaultError("invalid_argument", f"Found no git repository in {path.name} or one "
554
+ "or two folders below it.")
555
+ return sources.Source("repos", "Git", "folder", lambda: map(repo_item, repos),
556
+ prefix="repo", drops_code=True, updates=True,
557
+ skips=("no git user.email", "no commits by you",
558
+ "git could not read it"))
559
+
560
+
561
+ # ---- highlights ----
562
+
563
+ def highlight_format(name: str, read) -> str | None:
564
+ """"kindle", "readwise", "pocket" or None, from a .txt or .csv file's first bytes."""
565
+ low = name.lower()
566
+ if not low.endswith((".txt", ".csv")):
567
+ return None
568
+ head = read(4096).decode("utf-8-sig", "replace")
569
+ if low.endswith(".txt"):
570
+ return "kindle" if "\n==========" in head else None
571
+ cols = {c.strip().lower() for c in next(csv.reader([head.split("\n", 1)[0]]), [])}
572
+ return "readwise" if {"highlight", "book title"} <= cols else \
573
+ "pocket" if {"title", "url", "time_added"} <= cols else None
574
+
575
+
576
+ def _kindle_day(meta: str) -> str:
577
+ m = _KDATE.search(meta.split("|")[-1])
578
+ if not m:
579
+ return ""
580
+ day, month = (m.group(1), m.group(2)) if m.group(1) else (m.group(4), m.group(3))
581
+ try:
582
+ return datetime(int(m.group(5)), _MONTHS[month.lower()], int(day)).date().isoformat()
583
+ except (KeyError, ValueError):
584
+ return ""
585
+
586
+
587
+ def _kindle(text: str):
588
+ """(title, author, day or "", quote, is a note) per clipping, or a skip reason."""
589
+ for entry in text.split("=========="):
590
+ lines = [x.strip().lstrip("") for x in entry.strip().splitlines()]
591
+ if not any(lines):
592
+ continue
593
+ if len(lines) < 3 or not "".join(lines[2:]).strip():
594
+ yield "bookmark or empty"
595
+ continue
596
+ m = re.match(r"(.*?)\s*\(([^()]*)\)$", lines[0])
597
+ title, author = (m.group(1), m.group(2)) if m and m.group(1) else (lines[0], "")
598
+ yield (title, author, _kindle_day(lines[1]), " ".join(" ".join(lines[2:]).split()),
599
+ "note" in lines[1].lower().split("|")[0])
600
+
601
+
602
+ def _readwise(text: str):
603
+ for row in csv.DictReader(io.StringIO(text)):
604
+ quote = " ".join((row.get("Highlight") or "").split())
605
+ if not quote:
606
+ yield "bookmark or empty"
607
+ continue
608
+ day = (row.get("Highlighted at") or "")[:10]
609
+ note = " ".join((row.get("Note") or "").split())
610
+ yield ((row.get("Book Title") or "").strip() or "(untitled)",
611
+ (row.get("Book Author") or "").strip(),
612
+ day if re.fullmatch(r"\d{4}-\d\d-\d\d", day) else "",
613
+ quote + (f" (my note: {note})" if note else ""), False)
614
+
615
+
616
+ def _book_items(app: str, origin: str, mtime: float, rows) -> list:
617
+ """Items per book (per book and month past MANY highlights), and skip reasons."""
618
+ books, out = defaultdict(list), []
619
+ for r in rows:
620
+ if isinstance(r, str):
621
+ out.append(r)
622
+ else:
623
+ books[r[0], r[1]].append(r[2:])
624
+ for (title, author), hs in books.items():
625
+ groups = defaultdict(list)
626
+ for h in hs:
627
+ groups[h[0][:7] if len(hs) > MANY else ""].append(h)
628
+ for i, (month, g) in enumerate(sorted(groups.items())):
629
+ days = sorted(d for d, *_ in g if d)
630
+ span = f", {days[0]} to {days[-1]}" if days else ""
631
+ name = f"{title} ({month or 'undated'})" if len(groups) > 1 else title
632
+ by = f" by {author}" if author else ""
633
+ head = (f"My {app} highlights from \"{title}\"{by}" + (f" in {month}" if month else "")
634
+ + f" ({len(g)} highlight{'s' * (len(g) != 1)}{span}).")
635
+ body = "\n".join(f"- {d + ': ' if d else ''}" + (f"My note: {q}" if note else f'"{q}"')
636
+ for d, q, note in g)
637
+ out.append(sources.Item(name, days[-1] if days else _day(mtime),
638
+ f"{head}\n\n{body}", origin,
639
+ # the first part keeps the whole book's key: a book that
640
+ # grows past MANY rewrites its page, never leaves it stale
641
+ key=f"highlights {app} {title} {author} {month * bool(i)}",
642
+ who=author))
643
+ return out
644
+
645
+
646
+ def _pocket(text: str):
647
+ for row in csv.DictReader(io.StringIO(text)):
648
+ try:
649
+ day = _day(int(row.get("time_added") or ""))
650
+ except (ValueError, OverflowError, OSError):
651
+ yield "no readable date"
652
+ continue
653
+ title = " ".join((row.get("title") or "").split()) or row.get("url") or "(untitled)"
654
+ tags = (row.get("tags") or "").replace("|", ", ")
655
+ yield sources.Item(title, day, f"{day} saved \"{title}\" ({row.get('url', '')})"
656
+ + (f", tagged {tags}" if tags else ""))
657
+
658
+
659
+ def highlights_source(path: Path) -> sources.Source:
660
+ """Kindle and Readwise: item pages per book; Pocket alone: month pages of saved articles.
661
+ A Pocket list beside Kindle or Readwise files is skipped (import it on its own)."""
662
+ path = Path(path)
663
+ found = [(f, k) for f in importers._files(path) if (k := highlight_format(f[0], f[3]))]
664
+ if not found:
665
+ raise VaultError("invalid_argument", f"Found no Kindle clippings, Readwise or Pocket "
666
+ f"export in {path.name}.")
667
+ pocket = all(k == "pocket" for _, k in found)
668
+ skips = ("bookmark or empty", "no readable date", "over 200 MB",
669
+ "a Pocket list (import it on its own)")
670
+
671
+ def items():
672
+ for (name, _size, mtime, read), kind in found:
673
+ if kind == "pocket" and not pocket:
674
+ yield skips[3]
675
+ continue
676
+ try: # My Clippings.txt is a .txt but not a note: an export's cap, not a note's
677
+ text = read(cap=importers.MAX_ENTRY).decode("utf-8-sig", "replace")
678
+ except VaultError:
679
+ yield "over 200 MB"
680
+ continue
681
+ if kind == "pocket":
682
+ yield from _pocket(text)
683
+ continue
684
+ app, rows = ("Kindle", _kindle(text)) if kind == "kindle" else \
685
+ ("Readwise", _readwise(text))
686
+ yield from _book_items(app, _origin(path, name), mtime, rows)
687
+
688
+ if pocket:
689
+ return sources.Source("highlights", "Pocket", "file", items, page="month",
690
+ prefix="pocket", noun="saved articles", skips=skips)
691
+ return sources.Source("highlights", "Highlights", "file", items, updates=True,
692
+ skips=skips)
693
+
694
+
695
+ def zotero_source(path: Path | None) -> sources.Source:
696
+ """R18: a Zotero library (keepfold.zotero); with no path, the one on this computer."""
697
+ from keepfold import zotero # it imports this module
698
+ return zotero.source(path)
699
+
700
+
701
+ def anki_source(path: Path) -> sources.Source:
702
+ """R22: Anki decks (keepfold.anki); the caller runs `anki.link` after the import."""
703
+ from keepfold import anki # loaded only for an Anki import
704
+ return anki.source(path)
705
+
706
+
707
+ SOURCE_OF = {"docs": docs_source, "repos": repos_source, "highlights": highlights_source,
708
+ **life_sources.SOURCE_OF, "zotero": zotero_source, # Sources B, then R18
709
+ "anki": anki_source}