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,312 @@
1
+ """Google Takeout "My Activity" for Search, YouTube and Chrome as browse visits, the shape
2
+ `sources.read` returns, so the browse privacy filter and build can take them. Takeout writes one
3
+ `My Activity/<product>/MyActivity.json` per product when Activity records are set to JSON; each
4
+ row has header, title, titleUrl, time, products and, for YouTube, subtitles (the channel).
5
+ Rows of other products (Gemini Apps, Maps and the rest) are skipped. Takeout's default format
6
+ is HTML (`MyActivity.html`); `html_rows` reads it into the same rows, here and for Gemini chats.
7
+ A "YouTube and YouTube Music" Takeout holds `history/watch-history.json` and
8
+ `search-history.json` (or .html): the same rows and the same HTML cells (seen in open-source
9
+ Takeout parsers), read the same way. Their file names stay English in every language.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import html
15
+ import re
16
+ import unicodedata
17
+ import zipfile
18
+ from collections.abc import Iterator
19
+ from datetime import UTC, datetime, timedelta, timezone
20
+ from html.parser import HTMLParser
21
+ from pathlib import Path
22
+ from urllib.parse import parse_qs, urlsplit
23
+
24
+ from keepfold.browse.sources import GAP_CAP, Visit
25
+ from keepfold.vault import VaultError
26
+
27
+ # Takeout writes folder and file names, product names, verbs, labels and dates in the account
28
+ # language. Seen in open-source Takeout parsers: de "Meine Aktivitäten"/"Suche" and
29
+ # "Gesucht nach:"; ja "マイアクティビティ", "検索" and the を検索しました-style verbs. The other
30
+ # "My Activity" names are Google's own UI term in that language.
31
+ # shortcut: unconfirmed wording for es, pt, fr, hi, id (verbs, Search's folder and product
32
+ # name, the "Products:" label), de (visit verb, suffix verbs) and ja ("サービス:"), verify with a
33
+ # real export. A miss leaves the verb in a title or, for a date, skips and counts the row.
34
+ PRODUCTS = {"Search": "search", "YouTube": "youtube", "Chrome": "chrome",
35
+ **dict.fromkeys(("Suche", "Búsqueda", "Pesquisa", "Recherche", "खोज", "Penelusuran",
36
+ "検索"), "search")}
37
+ # "My Activity" as the file is named (spaces dropped): en, de, es, pt, fr, hi, id, ja
38
+ _ACTIVITY = {"myactivity", "meineaktivitäten", "miactividad", "minhaatividade", "monactivité",
39
+ "मेरीगतिविधि", "aktivitassaya", "マイアクティビティ"}
40
+ # YouTube's own history ("YouTube and YouTube Music" Takeout): English in every language
41
+ _YOUTUBE = ("watch-history", "search-history")
42
+ _PREFIXES = ("Searched for", "Watched", "Visited", "Viewed",
43
+ "Gesucht nach:", "Gesucht nach", "Aufgerufen:", "Besucht:", "Angesehen:",
44
+ "Has buscado", "Has visto", "Has visitado",
45
+ "Pesquisou", "Pesquisou por", "Assistiu a", "Assistiu", "Visitou",
46
+ "Vous avez recherché", "Vous avez regardé", "Vous avez consulté",
47
+ "खोजा गया:", "देखा गया:", "विज़िट किया गया:",
48
+ "Mencari", "Menelusuri", "Menonton", "Mengunjungi")
49
+ _SUFFIXES = ("を検索しました", "を視聴しました", "にアクセスしました")
50
+ _VERB = re.compile(r"^(?:{})\s+|^「\s*|\s*」?\s*(?:{})$".format(
51
+ "|".join(map(re.escape, sorted(_PREFIXES, key=len, reverse=True))),
52
+ "|".join(map(re.escape, _SUFFIXES))))
53
+ # German suffix verbs: stripped from German rows only, as other titles may end in them
54
+ _DE_VERB = re.compile(r"\s+(?:angesehen|gesucht)$")
55
+ _PRODUCTS_LABEL = {"Products:", "Produkte:", "Productos:", "Produtos:", "Produits:", "उत्पाद:",
56
+ "Produk:", "サービス:"}
57
+ READ_HINT = ("Takeouts in English, Spanish, Portuguese, French, German, Hindi, Indonesian or "
58
+ "Japanese are read (JSON or HTML): other languages' dates and verbs are not "
59
+ "understood.")
60
+ HEAD = 256 * 1024 # an HTML My Activity file opens with ~140 KB of CSS before its first row
61
+
62
+
63
+ def activity_file(name: str) -> str:
64
+ """"json" or "html" for a My Activity file in a supported language (a prefix such as
65
+ "takeout_MyActivity.json" allowed) or YouTube's watch-history or search-history, else ""."""
66
+ base = unicodedata.normalize("NFC", name.replace("\\", "/").rsplit("/", 1)[-1].lower())
67
+ stem, _, ext = base.replace(" ", "").rpartition(".")
68
+ return ext if ext in ("json", "html") and any(
69
+ map(stem.endswith, (*_ACTIVITY, *_YOUTUBE))) else ""
70
+
71
+
72
+ def wanted(name: str) -> bool:
73
+ """A file `records` reads: any JSON one, and an HTML one alone, in a Search, YouTube or
74
+ Chrome folder or YouTube's own history (its folder is named in the account language), so a
75
+ full Takeout's big Ads or Play Store pages are not parsed."""
76
+ kind = activity_file(name)
77
+ parts = unicodedata.normalize("NFC", name.replace("\\", "/").lower()).split("/")
78
+ return kind == "json" or kind == "html" and (
79
+ len(parts) == 1 or parts[-2] in {p.lower() for p in PRODUCTS}
80
+ or parts[-1].rpartition(".")[0].endswith(_YOUTUBE))
81
+
82
+
83
+ class Rows(list):
84
+ """The visits `records` returns; `skipped` counts HTML rows whose time could not be read."""
85
+ skipped = 0
86
+
87
+
88
+ def records(path: Path) -> Rows:
89
+ """Every Search, YouTube and Chrome row with a URL and a readable time in a Takeout export
90
+ (the .zip, its folder or one MyActivity, watch-history or search-history .json or .html),
91
+ oldest first. A visit lasts until the next one, at most GAP_CAP, as in `sources.read`. A
92
+ row read twice (My Activity's YouTube file and watch-history both hold a watch) is kept
93
+ once, by its time to the second and URL: an HTML time has no fraction of a second."""
94
+ path = Path(path)
95
+ from keepfold.importers import _files, json_value # the one size-capped reader
96
+ files = _files(path)
97
+ if path.suffix.lower() == ".zip" or path.is_dir():
98
+ files = [f for f in files if wanted(f[0])]
99
+ if not files:
100
+ raise VaultError("invalid_argument", f"Found no My Activity file in {path.name}; expected "
101
+ "My Activity/<product>/MyActivity.json or .html, or YouTube's "
102
+ "history/watch-history or search-history (.json or .html).")
103
+ out = Rows()
104
+ for name, *_, read in files: # one file's rows at a time
105
+ # German by the file or folder name; an HTML row may also say so by its label
106
+ de = "meineaktivitäten" in unicodedata.normalize("NFC", name.lower().replace(" ", ""))
107
+ try:
108
+ html_file = name.lower().endswith((".html", ".htm"))
109
+ data, skipped = html_rows(read(), name) if html_file else (json_value(read), 0)
110
+ out.skipped += skipped
111
+ if not isinstance(data, list | Iterator):
112
+ raise VaultError("invalid_argument",
113
+ f"{name} should hold a list of activity rows.")
114
+ out += [v for e in data if (v := _visit(e, de))] # C11: a big file streams here
115
+ except (OSError, ValueError, zipfile.BadZipFile) as e:
116
+ raise VaultError("invalid_argument", f"Cannot read {name}: {e}") from None
117
+ out.sort(key=lambda v: v.start)
118
+ seen: set = set()
119
+ out[:] = [v for v in out if (k := (v.start.replace(microsecond=0), v.url)) not in seen
120
+ and not seen.add(k)]
121
+ for v, nxt in zip(out, [*out[1:], None], strict=True):
122
+ v.secs = min(max((nxt.start - v.start).total_seconds(), 0.0), GAP_CAP) if nxt \
123
+ else GAP_CAP
124
+ return out
125
+
126
+
127
+ def _visit(e, de: bool = False) -> Visit | None:
128
+ if not isinstance(e, dict):
129
+ return None
130
+ products = e.get("products") if isinstance(e.get("products"), list) else []
131
+ kind = next((PRODUCTS[p] for p in products if isinstance(p, str) and p in PRODUCTS), None)
132
+ url = e.get("titleUrl")
133
+ if kind is None or not isinstance(url, str) or not url.startswith("http"):
134
+ return None
135
+ try:
136
+ start = datetime.fromisoformat(str(e.get("time")).replace("Z", "+00:00")).astimezone(UTC)
137
+ except ValueError:
138
+ return None
139
+ u = urlsplit(url)
140
+ if u.netloc.endswith("google.com") and u.path == "/url": # Google's redirect to the page
141
+ url = parse_qs(u.query).get("q", [url])[0]
142
+ subs = e.get("subtitles")
143
+ channel = subs[0].get("name") if kind == "youtube" and isinstance(subs, list) and subs \
144
+ and isinstance(subs[0], dict) else ""
145
+ title = _VERB.sub("", str(e.get("title") or "")).strip()
146
+ if de or e.get("de") is True or "Suche" in products:
147
+ title = _DE_VERB.sub("", title)
148
+ return Visit(start, url, title, 0.0,
149
+ source=f"takeout/{kind}", channel=channel if isinstance(channel, str) else "")
150
+
151
+
152
+ # Takeout's HTML: one div.outer-cell per row, holding a header-cell (the product), a
153
+ # content-cell (verb + link text, <br>, the YouTube channel link or the rest of a Gemini prompt,
154
+ # <br>, the local time, then a Gemini answer) and a caption cell ("Products:" then the name).
155
+ _TIME = re.compile(r"\d{4}.{0,12}?\d{1,2}[:.]\d{2}[:.]\d{2}")
156
+ # shortcut: common abbreviations (IST is India's, MEZ/MESZ German, WIB Indonesian). Unknown ones
157
+ # skip the row; add if seen.
158
+ _TZ = {"UTC": 0, "GMT": 0, "IST": 330, "PST": -480, "PDT": -420, "MST": -420, "MDT": -360,
159
+ "CST": -360, "CDT": -300, "EST": -300, "EDT": -240, "AKST": -540, "AKDT": -480,
160
+ "HST": -600, "BST": 60, "CET": 60, "CEST": 120, "EET": 120, "EEST": 180, "MSK": 180,
161
+ "PKT": 300, "NPT": 345, "BDT": 360, "ICT": 420, "WIB": 420, "SGT": 480, "HKT": 480,
162
+ "PHT": 480, "AWST": 480, "JST": 540, "KST": 540, "ACST": 570, "AEST": 600,
163
+ "AEDT": 660, "NZST": 720, "NZDT": 780, "MEZ": 60, "MESZ": 120, "WEZ": 0, "WESZ": 60,
164
+ "BRT": -180, "ART": -180, "WITA": 480, "WIT": 540}
165
+ # abbreviations several zones share: the one equal to this PC's own offset on that date wins,
166
+ # else the _TZ default (India, US Central, British Summer Time)
167
+ _AMBIGUOUS = {"IST": (330, 60, 120), "CST": (-360, 480), "BST": (60, 360)}
168
+
169
+
170
+ def _system_offset(naive: datetime) -> int:
171
+ """This PC's UTC offset in minutes at local time `naive`."""
172
+ return int(naive.astimezone().utcoffset().total_seconds() // 60)
173
+ # month names and abbreviations: en, es, pt, fr, de, id, hi (ja dates are numeric). A word
174
+ # matches whole, else by its first 4 or 3 letters ("noviembre" -> "nov", "juil." -> "juil").
175
+ _MONTHS = {unicodedata.normalize("NFC", k): n for n, ks in enumerate((
176
+ "jan ene janv जन जनवरी", "feb fev fév févr फ़र फ़रवरी", "mar mär mars मार्च",
177
+ "apr abr avr अप्रैल", "may mai mei मई", "jun juin जून", "jul juil जुल जुलाई",
178
+ "aug ago aoû agu agt अग अगस्त", "sep set sept सित सितंबर",
179
+ "oct okt out अक्तू अक्तूबर अक्टू अक्टूबर", "nov नव नवंबर", "dec dic dez déc des दिस दिसंबर"),
180
+ 1) for k in ks.split()}
181
+
182
+
183
+ def _month(word: str) -> int | None:
184
+ w = word.lower()
185
+ return _MONTHS.get(w) or _MONTHS.get(w[:4]) or _MONTHS.get(w[:3])
186
+
187
+
188
+ def when(text: str) -> datetime | None:
189
+ """A Takeout HTML time in a supported language ("Nov 17, 2026, 10:42:03 PM IST",
190
+ "17.11.2026, 22:42:03 MEZ", "17 नव॰ 2026, 10:42:03 pm IST", "2026/11/17 22:42:03 JST")
191
+ in UTC, or None."""
192
+ body, _, tz = unicodedata.normalize("NFC", " ".join(text.split())).rpartition(" ")
193
+ m = re.fullmatch(r"(?:GMT|UTC)([+\-−])(\d{1,2}):?(\d{2})?", tz)
194
+ mins = (-1 if m[1] != "+" else 1) * (int(m[2]) * 60 + int(m[3] or 0)) if m else _TZ.get(tz)
195
+ t = re.search(r"(?<![\d.:])(\d{1,2})[:.](\d{2})[:.](\d{2})(?![\d.:])", body)
196
+ if mins is None or t is None:
197
+ return None
198
+ date, ampm, hour = body[:t.start()], re.sub(r"[\s.]", "", body[t.end():]).lower(), int(t[1])
199
+ if ampm in ("am", "pm") or "午前" in date or "午後" in date:
200
+ hour = hour % 12 + (12 if ampm == "pm" or "午後" in date else 0)
201
+ elif ampm:
202
+ return None
203
+ words = [w.strip("॰") for w in re.split(r"[\s,/.年月日-]+", date) if w.strip("॰")]
204
+ nums = [int(w) for w in words if w.isdigit()]
205
+ months = [k for w in words if not w.isdigit() and (k := _month(w))]
206
+ if months and len(nums) == 2: # "Nov 17, 2026", "17 de nov. de 2026"
207
+ (y, d), mo = (nums if nums[0] > 31 else nums[::-1]), months[0]
208
+ elif not months and len(nums) == 3: # "17.11.2026", "2026/11/17"
209
+ # assumed day-first (no supported locale writes month-first); "11/05/2026" could be
210
+ # either, so a slashed date with both numbers <= 12 is skipped and counted, not guessed
211
+ if "/" in date and nums[0] <= 12 and nums[1] <= 12 and nums[2] > 31:
212
+ return None
213
+ y, mo, d = nums if nums[0] > 31 else nums[::-1]
214
+ else:
215
+ return None
216
+ try:
217
+ local = datetime(y, mo, d, hour, int(t[2]), int(t[3]))
218
+ if not m and tz in _AMBIGUOUS and (sys_mins := _system_offset(local)) in _AMBIGUOUS[tz]:
219
+ mins = sys_mins
220
+ return local.replace(tzinfo=timezone(timedelta(minutes=mins))).astimezone(UTC)
221
+ except (ValueError, OverflowError, OSError): # astimezone can raise these for far years
222
+ return None
223
+
224
+
225
+ class _Cells(HTMLParser):
226
+ """Each outer cell as [header, content lines, product, "Products:" label]; a line is
227
+ [(text, href or None)]."""
228
+
229
+ def __init__(self):
230
+ super().__init__(convert_charrefs=True)
231
+ self.cells, self.divs, self.mode, self.href = [], [], None, None
232
+
233
+ def handle_starttag(self, tag, attrs):
234
+ a = dict(attrs)
235
+ if tag == "div":
236
+ cls = a.get("class") or ""
237
+ self.divs.append(cls)
238
+ if "outer-cell" in cls:
239
+ self.cells.append(["", [[]], "", ""])
240
+ self.mode = None
241
+ elif self.cells and "header-cell" in cls:
242
+ self.mode = "header"
243
+ elif self.cells and "caption" in cls:
244
+ self.mode = "caption"
245
+ elif self.cells and "content-cell" in cls and "text-right" not in cls:
246
+ self.mode = "content"
247
+ elif tag == "br" and self.mode == "content":
248
+ self.cells[-1][1].append([])
249
+ elif tag == "a":
250
+ self.href = a.get("href")
251
+
252
+ def handle_endtag(self, tag):
253
+ if tag == "a":
254
+ self.href = None
255
+ elif tag == "div" and self.divs and "cell" in self.divs.pop():
256
+ self.mode = None
257
+
258
+ def handle_data(self, data):
259
+ if not self.cells or not self.mode:
260
+ return
261
+ cell = self.cells[-1]
262
+ if self.mode == "header" and not cell[0]:
263
+ cell[0] = data.strip()
264
+ elif self.mode == "content":
265
+ cell[1][-1].append((data, self.href))
266
+ elif self.mode == "caption" and data.strip():
267
+ if cell[2] == "?": # the text right after <b>Products:</b>
268
+ cell[2] = data.strip()
269
+ elif data.strip() in _PRODUCTS_LABEL:
270
+ cell[2], cell[3] = "?", data.strip()
271
+
272
+
273
+ def html_rows(data: bytes, name: str = "MyActivity.html") -> tuple[list[dict], int]:
274
+ """An HTML My Activity file as the JSON export's rows (header, title, titleUrl,
275
+ subtitles, time, products, safeHtmlItem for a Gemini answer), and how many rows were
276
+ skipped because their time could not be read."""
277
+ p = _Cells()
278
+ p.feed(data.decode("utf-8", errors="replace"))
279
+ p.close()
280
+ if not p.cells:
281
+ raise VaultError("invalid_argument", f"{name} is HTML that Keepfold cannot read as Takeout "
282
+ f"My Activity. {READ_HINT}")
283
+ rows, skipped = [], 0
284
+ for header, lines, product, label in p.cells:
285
+ text = [" ".join("".join(t for t, _ in line).split()) for line in lines]
286
+ # the first line that reads as a time: a title such as "notes 2024 v1.12.03" may match
287
+ i, t = next(((i, w) for i, s in enumerate(text) if _TIME.search(s) and (w := when(s))),
288
+ (None, None))
289
+ if t is None:
290
+ skipped += 1
291
+ continue
292
+ # after line 0, a line holding a link is a subtitle (YouTube's channel); the rest of the
293
+ # lines before the time continue the title (a multi-line Gemini prompt)
294
+ linked = [k > 0 and any(h for _, h in line) for k, line in enumerate(lines[:i])]
295
+ row = {"header": header,
296
+ "title": "\n".join(s for s, ln in zip(text[:i], linked, strict=True)
297
+ if s and not ln),
298
+ "time": t.isoformat().replace("+00:00", "Z"), "products": [product or header]}
299
+ if label == "Produkte:":
300
+ row["de"] = True
301
+ url = next((h for _, h in lines[0] if h), None)
302
+ if url:
303
+ row["titleUrl"] = url
304
+ subs = [{"name": text[k], "url": next(h for _, h in lines[k] if h)}
305
+ for k, ln in enumerate(linked) if ln]
306
+ if subs:
307
+ row["subtitles"] = subs
308
+ answer = " ".join(" ".join(t for t, _ in line) for line in lines[i + 1:]).strip()
309
+ if answer: # _gemini strips tags and unescapes, as for the JSON's answer html
310
+ row["safeHtmlItem"] = [{"html": html.escape(answer)}]
311
+ rows.append(row)
312
+ return rows, skipped
@@ -0,0 +1,127 @@
1
+ """The local model's checks of titles and search terms (C1), in batches, and when they may run.
2
+
3
+ `check` asks about BATCH texts per call (`localllm.Runner.classify_many`, a numbered JSON
4
+ reply); a reply that leaves lines out is asked again in halves, down to one text per call
5
+ (`classify`), so a bad answer costs a few calls, never the batch. Each batch's labels are saved
6
+ before the next is asked (`save`), so a stop keeps them and no text is asked twice.
7
+
8
+ `may_run` is the gate for work nobody is waiting for (the app's background pass, the import
9
+ job's title checks): the PC idle for IDLE_S (Windows' last input; nothing full screen), and the
10
+ configured local model already loaded (`localllm.find_loaded`: Ollama's /api/ps, LM Studio's
11
+ model list). It never starts a runner or loads a model.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import ctypes
17
+ import sys
18
+ import time
19
+ from collections import Counter, deque
20
+
21
+ BATCH = 25
22
+ CAP = 300 # texts per background pass
23
+ PAUSE_S = 1.0 # between batches in the background, so the GPU is never held flat out
24
+ IDLE_S = 120
25
+
26
+
27
+ def idle_seconds() -> float | None:
28
+ """Seconds since the last keyboard or mouse input (Windows), else None."""
29
+ if sys.platform != "win32":
30
+ return None
31
+
32
+ class LASTINPUTINFO(ctypes.Structure):
33
+ _fields_ = [("cbSize", ctypes.c_uint), ("dwTime", ctypes.c_uint)]
34
+
35
+ info = LASTINPUTINFO(ctypes.sizeof(LASTINPUTINFO), 0)
36
+ try:
37
+ if not ctypes.windll.user32.GetLastInputInfo(ctypes.byref(info)):
38
+ return None
39
+ now = ctypes.windll.kernel32.GetTickCount() & 0xFFFFFFFF
40
+ except (AttributeError, OSError):
41
+ return None
42
+ return ((now - info.dwTime) & 0xFFFFFFFF) / 1000.0
43
+
44
+
45
+ def full_screen() -> bool:
46
+ """True while a full-screen app, game or presentation runs (Windows' notification state
47
+ busy, D3D full screen or presentation mode)."""
48
+ if sys.platform != "win32":
49
+ return False
50
+ state = ctypes.c_int(0)
51
+ try:
52
+ if ctypes.windll.shell32.SHQueryUserNotificationState(ctypes.byref(state)) != 0:
53
+ return False
54
+ except (AttributeError, OSError):
55
+ return False
56
+ return state.value in (2, 3, 4)
57
+
58
+
59
+ def idle(min_s: float = IDLE_S) -> bool:
60
+ """The owner is away: no input for `min_s` and nothing full screen. False where it cannot
61
+ tell (not Windows): background model work then waits for an explicit run."""
62
+ s = idle_seconds()
63
+ return s is not None and s >= min_s and not full_screen()
64
+
65
+
66
+ def may_run(min_idle_s: float = IDLE_S):
67
+ """(runner, why not): the loaded local runner when the PC is idle, else (None, reason)."""
68
+ from keepfold import localllm
69
+
70
+ if not localllm.enabled():
71
+ return None, "no local model is set up"
72
+ if not idle(min_idle_s):
73
+ return None, "waiting until the PC is idle"
74
+ try:
75
+ r = localllm.find_loaded()
76
+ except ValueError:
77
+ r = None
78
+ return (r, None) if r is not None else (None, "the local model is not loaded")
79
+
80
+
81
+ def check(texts: dict[str, str], runner, labels: list[str], budget=None, *, save=None,
82
+ step=None, gate=None, pause: float = 0.0) -> tuple[dict[str, str], Counter]:
83
+ """Label `texts` ({hash: text}, asked in that order) in batches of BATCH: (labels got,
84
+ counts "calls", "asked", "answered"). Stops when the runner does not answer at all, the
85
+ budget is spent, or `gate()` turns False (the owner came back); what was saved stays.
86
+ `save(labels)` after each call that labelled anything; `step(done, total)` per call."""
87
+ c: Counter = Counter()
88
+ got: dict[str, str] = {}
89
+ hs = list(texts)
90
+ queue = deque(hs[i:i + BATCH] for i in range(0, len(hs), BATCH))
91
+ done, sent = 0, set()
92
+ while queue:
93
+ if budget is not None and not budget.ok():
94
+ c["left"] = sum(map(len, queue))
95
+ break
96
+ if gate is not None and not gate():
97
+ c["paused"] = 1
98
+ c["left"] = sum(map(len, queue))
99
+ break
100
+ batch = queue.popleft()
101
+ c["calls"] += 1
102
+ sent.update(batch)
103
+ if len(batch) == 1:
104
+ r = runner.classify(texts[batch[0]], labels, budget=budget)
105
+ lab = {batch[0]: r[0]} if r else {}
106
+ done += 1 # answered or not: asked again on a later pass, never in this one
107
+ else:
108
+ r = runner.classify_many([texts[h] for h in batch], labels, budget=budget)
109
+ if r is None: # no answer: the runner is gone or busy; the rest waits
110
+ c["left"] = sum(map(len, queue)) + len(batch)
111
+ break
112
+ lab = {batch[i]: v for i, v in r.items() if 0 <= i < len(batch)}
113
+ miss = [h for h in batch if h not in lab]
114
+ done += len(batch) - len(miss)
115
+ if miss: # asked again in halves, before anything else
116
+ half = (len(miss) + 1) // 2
117
+ queue.extendleft([x for x in (miss[half:], miss[:half]) if x])
118
+ c["answered"] += len(lab)
119
+ got.update(lab)
120
+ if save and lab:
121
+ save(lab)
122
+ if step:
123
+ step(done, len(hs))
124
+ if pause and queue:
125
+ time.sleep(pause)
126
+ c["asked"] = len(sent)
127
+ return got, c