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,747 @@
1
+ """Sources B, part 1: `keepfold import` sources for the owner's own life exports, on
2
+ `sources.Source` like more_sources (Sources A). Each keeps only the owner's own words or a
3
+ coarse daily summary, never other people's text, addresses, coordinates or files.
4
+
5
+ - mail: an .mbox (Google Takeout's "Sent", or All mail) into one page per month of the owner's
6
+ sent messages: date, subject, recipients' names (never addresses) and the owner's own text,
7
+ with quoted replies, forwarded parts, signatures and HTML stripped. Keyed by month with
8
+ `updates`, so a re-import of a newer (cumulative) export rewrites a month page in place.
9
+ - selfchat: a WhatsApp chat-with-yourself .txt and Telegram Saved Messages (result.json) into
10
+ month pages, a line per own message; media named, never copied. Private by default.
11
+ - location: Google Timeline JSON (both shapes) into month pages of one city per day, from the
12
+ visits' postal addresses; no coordinates, streets or network. Private by default.
13
+ - photos: a photo folder into month pages of photos per day and album (folder) names; EXIF
14
+ capture date only, never images or GPS.
15
+ - spotify: streaming history into a page per year of hours and top artists, tracks and
16
+ podcasts; nothing per play.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ from collections import Counter, defaultdict
23
+ from datetime import date
24
+ from html.parser import HTMLParser
25
+ from pathlib import Path
26
+
27
+ from keepfold import importers, sources, voice_memos
28
+ from keepfold.vault import VaultError
29
+
30
+ LOCAL = sources.Audience.LOCAL
31
+ MAIL_CHARS = 1500 # one message's own text on a month page
32
+ MAIL_NAMES = 5 # recipients named per message, then "and N more"
33
+
34
+
35
+ def _s(n: int) -> str:
36
+ return "s" * (n != 1)
37
+
38
+
39
+ # ---- mail ----
40
+
41
+ MAIL_SKIPS = ("not sent by you", "a draft", "no readable date", "no text of yours",
42
+ "malformed message", "the same message twice", "not an mbox file")
43
+ _SIG = re.compile(r"^-- ?$", re.M) # the "-- " signature line (some clients drop the space)
44
+ _OUTLOOK = re.compile(r"^[ \t]*From: [^\n]*\n[ \t]*(?:Sent|Date): ", re.M) # Outlook's quote
45
+ _VOID = {"br", "img", "hr", "meta", "input", "wbr", "link", "area", "col", "source"}
46
+ _BLOCK = {"p", "div", "li", "tr", "h1", "h2", "h3", "h4", "table", "ul", "ol"}
47
+ _HIDE = ("gmail_quote", "gmail_signature", "moz-cite-prefix", "moz-signature")
48
+
49
+
50
+ class _Text(HTMLParser):
51
+ """An HTML mail body as text: no script, style, quoted (blockquote, gmail_quote) or
52
+ signature blocks."""
53
+
54
+ def __init__(self):
55
+ super().__init__(convert_charrefs=True)
56
+ self.out, self.skip = [], 0
57
+
58
+ def handle_starttag(self, tag, attrs):
59
+ if tag in _VOID:
60
+ if tag == "br" and not self.skip:
61
+ self.out.append("\n")
62
+ return
63
+ cls = dict(attrs).get("class") or ""
64
+ if self.skip or tag in ("script", "style", "head", "blockquote", "title") \
65
+ or any(c in cls for c in _HIDE):
66
+ self.skip += 1
67
+ elif tag in _BLOCK:
68
+ self.out.append("\n")
69
+
70
+ def handle_endtag(self, tag):
71
+ if tag in _VOID:
72
+ return
73
+ if self.skip:
74
+ self.skip -= 1
75
+ elif tag in _BLOCK:
76
+ self.out.append("\n")
77
+
78
+ def handle_data(self, data):
79
+ if not self.skip:
80
+ self.out.append(data)
81
+
82
+
83
+ def html_text(html: str) -> str:
84
+ p = _Text()
85
+ p.feed(html)
86
+ p.close()
87
+ return "\n".join(" ".join(ln.split()) for ln in "".join(p.out).splitlines())
88
+
89
+
90
+ def own_text(body: str) -> str:
91
+ """The owner's own words in a mail body: everything from the first "On … wrote:",
92
+ forwarded or original-message line, Outlook "From:/Sent:" block or "-- " signature line
93
+ on is cut, `>` lines are dropped and any e-mail address left becomes [address]."""
94
+ body = body.replace("\r\n", "\n")
95
+ cuts = [m.start() for rx in (sources._ATTRIBUTION, sources._FORWARDED, _OUTLOOK, _SIG)
96
+ if (m := rx.search(body))]
97
+ body = body[:min(cuts)] if cuts else body
98
+ body = "\n".join(ln for ln in body.split("\n") if not ln.lstrip().startswith(">"))
99
+ body = importers._EMAIL.sub("[address]", body)
100
+ return re.sub(r"\n{3,}", "\n\n", body).strip()
101
+
102
+
103
+ def _addr(value) -> str:
104
+ from email.utils import parseaddr
105
+ return parseaddr(str(value or ""))[1].lower()
106
+
107
+
108
+ def _labels(head) -> set[str]:
109
+ return {x.strip().lower() for x in str(head.get("X-Gmail-Labels") or "").split(",")}
110
+
111
+
112
+ def _head(box, key):
113
+ """A message's headers only, read up to the blank line (the first pass)."""
114
+ from email import policy
115
+ from email.parser import BytesHeaderParser
116
+ lines = []
117
+ with box.get_file(key) as f:
118
+ for line in iter(f.readline, b""):
119
+ if line in (b"\n", b"\r\n"):
120
+ break
121
+ lines.append(line)
122
+ return BytesHeaderParser(policy=policy.default).parsebytes(b"".join(lines))
123
+
124
+
125
+ def _names(msg) -> str:
126
+ """Recipients' display names (To, Cc), never their addresses."""
127
+ from email.utils import getaddresses
128
+ got = getaddresses([str(v) for k in ("to", "cc") for v in msg.get_all(k, [])])
129
+ names = list(dict.fromkeys(n for name, _ in got
130
+ if (n := " ".join(importers._EMAIL.sub("", name).split())
131
+ .strip("\"' "))))
132
+ more = len(names) - MAIL_NAMES
133
+ return ", ".join(names[:MAIL_NAMES]) + (f" and {more} more" if more > 0 else "")
134
+
135
+
136
+ def _message(raw: bytes) -> tuple[str, str] | str:
137
+ """(day, section) of one sent message, or a skip reason."""
138
+ from email import policy
139
+ from email.parser import BytesParser
140
+ from email.utils import parsedate_to_datetime
141
+ msg = BytesParser(policy=policy.default).parsebytes(raw)
142
+ try:
143
+ day = parsedate_to_datetime(str(msg["Date"] or "")).date().isoformat()
144
+ except (TypeError, ValueError, IndexError):
145
+ return "no readable date"
146
+ # the body only: never an attachment or a forwarded message/rfc822 part
147
+ part = msg.get_body(preferencelist=("plain", "html"))
148
+ body = "" if part is None else part.get_content()
149
+ if part is not None and part.get_content_type() == "text/html":
150
+ body = html_text(body)
151
+ text = own_text(body)
152
+ if not text:
153
+ return "no text of yours"
154
+ subject = " ".join(importers._EMAIL.sub("[address]", str(msg["Subject"] or "")).split())
155
+ to = _names(msg)
156
+ return day, (f"## {day}: {subject or '(no subject)'}\n" + (f"To {to}.\n" if to else "")
157
+ + f"\n{_clip(text, MAIL_CHARS)}")
158
+
159
+
160
+ def _clip(text: str, n: int) -> str:
161
+ return text if len(text) <= n else text[:n].rsplit(" ", 1)[0] + " …"
162
+
163
+
164
+ def _open_box(path: Path):
165
+ """(the open mbox, {key: its headers or None when malformed}); None when not an mbox."""
166
+ import mailbox
167
+ try:
168
+ box = mailbox.mbox(path, create=False)
169
+ keys = list(box.iterkeys())
170
+ except (OSError, mailbox.Error, ValueError):
171
+ return None
172
+ heads = {}
173
+ for k in keys:
174
+ try:
175
+ heads[k] = _head(box, k)
176
+ except Exception: # noqa: BLE001 - email raises many types on a malformed message
177
+ heads[k] = None
178
+ return box, heads
179
+
180
+
181
+ def _sent_from(path: Path, heads: dict) -> set[str]:
182
+ """The owner's addresses in one box: the senders of its messages labelled Sent; in a box
183
+ with no Gmail labels (a mail app's export), every sender when the box is a Sent folder."""
184
+ heads = [h for h in heads.values() if h]
185
+ if any(h.get("X-Gmail-Labels") for h in heads):
186
+ return {_addr(h["From"]) for h in heads if "sent" in _labels(h)}
187
+ return {_addr(h["From"]) for h in heads} if re.search(r"\bsent\b", path.stem, re.I) \
188
+ else set()
189
+
190
+
191
+ def _mail_box(box, heads: dict, owners: set[str], months: dict, seen: set):
192
+ """Skip reasons for one open .mbox, filling `months` (month -> [(day, section)]). Only
193
+ mail from `owners` (`_sent_from` across all the boxes) is the owner's."""
194
+ if not heads:
195
+ yield "not an mbox file"
196
+ for k, h in heads.items():
197
+ if h is None:
198
+ yield "malformed message"
199
+ continue
200
+ labels = _labels(h)
201
+ if "draft" in labels or "drafts" in labels:
202
+ yield "a draft"
203
+ continue
204
+ if _addr(h["From"]) not in owners:
205
+ yield "not sent by you"
206
+ continue
207
+ mid = str(h["Message-ID"] or "").strip()
208
+ if mid and mid in seen:
209
+ yield "the same message twice"
210
+ continue
211
+ seen.add(mid)
212
+ try:
213
+ got = _message(box.get_bytes(k))
214
+ except Exception: # noqa: BLE001 - a broken charset, header or MIME part
215
+ got = "malformed message"
216
+ if isinstance(got, str):
217
+ yield got
218
+ else:
219
+ months[got[0][:7]].append(got)
220
+
221
+
222
+ def mail_source(path: Path) -> sources.Source:
223
+ """An .mbox file, or a folder of them, into one page per month of sent mail; see the
224
+ module docstring. Mailbox needs the file itself, so a .zip is refused (unzip it first)."""
225
+ path = Path(path)
226
+ if path.suffix.lower() == ".zip":
227
+ raise VaultError("invalid_argument", f"Unzip {path.name} first and give the .mbox "
228
+ "file in it (Takeout: Mail/Sent.mbox or All mail).")
229
+ boxes = [path] if path.is_file() else \
230
+ sorted(p for p in path.rglob("*.mbox") if p.is_file()) if path.is_dir() else []
231
+ if not boxes:
232
+ raise VaultError("invalid_argument", f"Found no .mbox file in {path.name}.")
233
+
234
+ def items():
235
+ months, seen = defaultdict(list), set()
236
+ opened = []
237
+ try:
238
+ for p in boxes:
239
+ opened.append(_open_box(p))
240
+ if not opened[-1]:
241
+ yield "not an mbox file"
242
+ owners = set().union(*(_sent_from(p, o[1]) for p, o in zip(boxes, opened, strict=True)
243
+ if o))
244
+ for o in opened:
245
+ if o:
246
+ yield from _mail_box(*o, owners, months, seen)
247
+ finally:
248
+ for o in opened:
249
+ if o:
250
+ o[0].close()
251
+ for month, msgs in sorted(months.items()):
252
+ msgs.sort(key=lambda m: m[0])
253
+ n = len(msgs)
254
+ yield sources.Item(f"Sent mail {month}", msgs[-1][0],
255
+ f"My sent mail in {month}: {n} message{_s(n)}.\n\n"
256
+ + "\n\n".join(s for _, s in msgs),
257
+ str(boxes[0] if len(boxes) == 1 else path), key=f"mail {month}")
258
+
259
+ return sources.Source("mail", "Sent mail", "file", items, default_tier=LOCAL,
260
+ prefix="mail", strips_quotes=True, updates=True, skips=MAIL_SKIPS,
261
+ size=_figure(r"My sent mail in [\d-]+: (\d+) message"))
262
+
263
+
264
+ def _figure(pattern: str):
265
+ """A page's figure for `Source.size`: the first group of `pattern`, else 0."""
266
+ def size(text: str) -> float:
267
+ m = re.search(pattern, text)
268
+ return float(m.group(1).replace(",", "")) if m else 0.0
269
+ return size
270
+
271
+
272
+ # ---- notes to self (WhatsApp, Telegram) ----
273
+
274
+ CHAT_CHARS = 2000 # one message on a month line
275
+ SELF_SKIPS = ("not a chat with yourself", "a system line", "deleted", "forwarded",
276
+ "not yours", "empty", "malformed file", "over 200 MB")
277
+ # Android "12/03/2024, 09:15 - Name: text"; iOS "[12/03/24, 9:15:23 AM] Name: text"
278
+ _WA = re.compile(r"^[\u200e\u200f]?\[?(\d{1,2})[./-](\d{1,2})[./-](\d{2,4}),?\s+"
279
+ r"(\d{1,2})[:.](\d{2})(?:[:.]\d{2})?\s?([AaPp]\.?\s?[Mm]\.?)?\]?\s(?:-\s)?(.*)$")
280
+ _WA_OMITTED = {"image": "[photo]", "video": "[video]", "audio": "[audio]",
281
+ "sticker": "[sticker]", "gif": "[GIF]", "document": "[file]",
282
+ "contact card": "[contact]"}
283
+ _EXT = {"[photo]": ("jpg", "jpeg", "png", "webp", "heic", "gif"),
284
+ "[video]": ("mp4", "mov", "3gp", "mkv"), "[audio]": ("opus", "ogg", "m4a", "mp3",
285
+ "aac", "wav")}
286
+ _TG_MEDIA = {"voice_message": "[voice note]", "video_message": "[video]",
287
+ "video_file": "[video]", "audio_file": "[audio]", "sticker": "[sticker]",
288
+ "animation": "[GIF]"}
289
+
290
+
291
+ def _by_ext(name: str) -> str:
292
+ ext = name.rsplit(".", 1)[-1].lower().strip("> ")
293
+ return next((tag for tag, exts in _EXT.items() if ext in exts), "[file]")
294
+
295
+
296
+ def wa_media(text: str) -> str:
297
+ """A WhatsApp media line as "[photo]", "[video]"…; any other text as it is. The file
298
+ itself is never read or copied."""
299
+ low = text.strip().strip("\u200e").lower()
300
+ if low == "<media omitted>":
301
+ return "[media]"
302
+ if m := re.fullmatch(r"(image|video|audio|sticker|gif|document|contact card) omitted",
303
+ low):
304
+ return _WA_OMITTED[m.group(1)]
305
+ if low.startswith("<attached:"):
306
+ return _by_ext(low.removesuffix(">"))
307
+ if low.endswith("(file attached)"):
308
+ return _by_ext(low.removesuffix("(file attached)").strip())
309
+ return text
310
+
311
+
312
+ def _one_line(text: str) -> str:
313
+ return _clip(" / ".join(x.strip() for x in text.splitlines() if x.strip()), CHAT_CHARS)
314
+
315
+
316
+ def _hm(h: str, m: str, ampm: str | None) -> str:
317
+ hour, ap = int(h), (ampm or "").lower()
318
+ if ap.startswith("p") and hour < 12:
319
+ hour += 12
320
+ elif ap.startswith("a") and hour == 12:
321
+ hour = 0
322
+ return f"{hour:02d}:{m}"
323
+
324
+
325
+ def _whatsapp(text: str):
326
+ """Items of a WhatsApp chat export with only one person writing in it, or skip reasons."""
327
+ rows, last = [], None
328
+ for line in text.splitlines():
329
+ if m := _WA.match(line):
330
+ last = [m.groups(), m.group(7)]
331
+ rows.append(last)
332
+ elif last is not None: # a message's next line
333
+ last[1] += "\n" + line
334
+ if not rows:
335
+ yield "malformed file"
336
+ return
337
+ pairs = [(int(g[0]), int(g[1])) for g, _ in rows]
338
+ month_first = not any(a > 12 for a, _ in pairs) and any(b > 12 for _, b in pairs)
339
+ msgs, senders = [], Counter()
340
+ for g, rest in rows:
341
+ who, sep, said = rest.partition(": ")
342
+ # iOS puts the encryption notice under the chat's name, not the owner's: not a sender
343
+ if not sep or said.lstrip("‎ ").startswith(
344
+ "Messages and calls are end-to-end encrypted"):
345
+ msgs.append("a system line")
346
+ continue
347
+ senders[who.strip("\u200e ")] += 1
348
+ a, b, y = int(g[0]), int(g[1]), int(g[2])
349
+ d, mo = (b, a) if month_first else (a, b)
350
+ try:
351
+ day = date(y + 2000 if y < 100 else y, mo, d).isoformat()
352
+ except ValueError:
353
+ msgs.append("malformed file")
354
+ continue
355
+ msgs.append((day, _hm(g[3], g[4], g[5]), said))
356
+ if len(senders) > 1: # a chat with others: whose is whose is not known, so none is kept
357
+ yield "not a chat with yourself"
358
+ return
359
+ for x in msgs:
360
+ if isinstance(x, str):
361
+ yield x
362
+ continue
363
+ day, hm, said = x
364
+ said = wa_media(said.strip())
365
+ if said.lower().strip("\u200e ") in ("this message was deleted",
366
+ "you deleted this message"):
367
+ yield "deleted"
368
+ elif not said.strip():
369
+ yield "empty"
370
+ else:
371
+ yield sources.Item(day, day, f"{day} {hm} WhatsApp: {_one_line(said)}")
372
+
373
+
374
+ def _tg_text(t) -> str:
375
+ if isinstance(t, list):
376
+ return "".join(x if isinstance(x, str) else str(x.get("text", "")) for x in t
377
+ if isinstance(x, str | dict))
378
+ return t if isinstance(t, str) else ""
379
+
380
+
381
+ def _telegram(data):
382
+ """Items of Telegram's Saved Messages (a single-chat result.json, or the full export's
383
+ chat of type saved_messages): the owner's own messages; forwarded ones are skipped."""
384
+ chats = [data] if isinstance(data, dict) and "messages" in data else \
385
+ ((data.get("chats") or {}).get("list") or []) if isinstance(data, dict) else []
386
+ saved = [c for c in chats if isinstance(c, dict) and c.get("type") == "saved_messages"]
387
+ if not saved:
388
+ yield "not a chat with yourself"
389
+ return
390
+ for chat in saved:
391
+ msgs = [m for m in chat.get("messages") or [] if isinstance(m, dict)]
392
+ owner = Counter(m.get("from_id") for m in msgs if m.get("type") == "message"
393
+ and not m.get("forwarded_from")).most_common(1)
394
+ for m in msgs:
395
+ if m.get("type") != "message":
396
+ yield "a system line"
397
+ continue
398
+ if m.get("forwarded_from") or m.get("saved_from"):
399
+ yield "forwarded"
400
+ continue
401
+ if owner and m.get("from_id") != owner[0][0]:
402
+ yield "not yours"
403
+ continue
404
+ when = str(m.get("date") or "")
405
+ if not re.match(r"\d{4}-\d\d-\d\dT\d\d:\d\d", when):
406
+ yield "malformed file"
407
+ continue
408
+ tag = "[photo]" if m.get("photo") else _TG_MEDIA.get(m.get("media_type"), "") \
409
+ or ("[file]" if m.get("file") else "")
410
+ said = " ".join(x for x in (tag, _tg_text(m.get("text")).strip()) if x)
411
+ if not said:
412
+ yield "empty"
413
+ continue
414
+ yield sources.Item(when[:10], when[:10],
415
+ f"{when[:10]} {when[11:16]} Telegram: {_one_line(said)}")
416
+
417
+
418
+ def selfchat_source(path: Path) -> sources.Source:
419
+ """A WhatsApp chat-with-yourself .txt export and Telegram Saved Messages result.json (a
420
+ file, folder or .zip) into one private page per month: the owner's own messages, a line
421
+ each, media as "[photo]" and the like."""
422
+ import json
423
+ path = Path(path)
424
+ found = [f for f in importers._files(path)
425
+ if f[0].lower().endswith(".txt") and _WA.match(
426
+ f[3](512).decode("utf-8-sig", "replace").lstrip("\ufeff").split("\n", 1)[0])
427
+ or f[0].lower().endswith(".json")]
428
+ if not found:
429
+ raise VaultError("invalid_argument", f"Found no WhatsApp chat (.txt) or Telegram "
430
+ f"result.json in {path.name}.")
431
+
432
+ def items():
433
+ for name, _size, _mtime, read in found:
434
+ try: # a WhatsApp .txt is not a note: an export's cap, not a note's
435
+ raw = read(cap=importers.MAX_ENTRY)
436
+ except VaultError:
437
+ yield "over 200 MB"
438
+ continue
439
+ if name.lower().endswith(".txt"):
440
+ yield from _whatsapp(raw.decode("utf-8-sig", "replace"))
441
+ continue
442
+ try:
443
+ data = json.loads(raw.decode("utf-8-sig"))
444
+ except (ValueError, UnicodeDecodeError):
445
+ yield "malformed file"
446
+ continue
447
+ yield from _telegram(data)
448
+
449
+ return sources.Source("selfchat", "Notes to self", "file", items, default_tier=LOCAL,
450
+ page="month", noun="messages", skips=SELF_SKIPS)
451
+
452
+
453
+ # ---- location: a city per day ----
454
+
455
+ LOC_SKIPS = ("no place name", "not a location file", "raw points (not read)",
456
+ "malformed file", "over 200 MB")
457
+ _STREET = re.compile(r"\b(?:road|rd|street|st|avenue|ave|lane|ln|marg|drive|dr|blvd|boulevard|"
458
+ r"way|highway|hwy|cross|floor|block|sector|plot|house|flat|apt|suite|"
459
+ r"building|tower|nagar|layout|colony)\b", re.I)
460
+
461
+
462
+ def city(address: str) -> str | None:
463
+ """The city in a one-line postal address ("MG Road, Bengaluru, Karnataka 560001, India"
464
+ -> "Bengaluru"; "Street 1, 10117 Berlin, Germany" -> "Berlin"), or None when the part it
465
+ lands on could be finer than a city (digits or a street word in it)."""
466
+ parts = [p.strip() for p in str(address).replace("\n", ",").split(",") if p.strip()]
467
+ if len(parts) < 2:
468
+ return None
469
+ cand = parts[-2]
470
+ if re.match(r"\d", cand): # "10117 Berlin": the postcode first
471
+ cand = re.sub(r"^[\d\s-]+", "", cand)
472
+ elif re.search(r"\d", cand) and len(parts) >= 3: # "Karnataka 560001": the region
473
+ cand = parts[-3]
474
+ elif len(parts) >= 4: # "street, city, region, country"
475
+ cand = parts[-3]
476
+ cand = re.sub(r"\s+\d[\d\s-]*$", "", cand).strip() # a postcode after the city
477
+ if not cand or re.search(r"\d", cand) or _STREET.search(cand) or len(cand) > 40:
478
+ return None
479
+ return cand
480
+
481
+
482
+ def _when_day(value) -> str:
483
+ """YYYY-MM-DD from an ISO time (its own local date) or epoch milliseconds (UTC)."""
484
+ s = str(value or "")
485
+ if re.match(r"\d{4}-\d\d-\d\d", s):
486
+ return s[:10]
487
+ if s.isdigit():
488
+ from datetime import UTC, datetime
489
+ try:
490
+ return datetime.fromtimestamp(int(s) / 1000, UTC).date().isoformat()
491
+ except (ValueError, OverflowError, OSError):
492
+ return ""
493
+ return ""
494
+
495
+
496
+ def _visits(data):
497
+ """(day, address or None) per place visit, from either Takeout shape: the monthly
498
+ Semantic Location History (`timelineObjects` placeVisit) or the on-device Timeline
499
+ (`semanticSegments`, or a bare list of segments). Movements are not places: skipped.
500
+ Raises ValueError on any other shape."""
501
+ if isinstance(data, dict) and isinstance(data.get("timelineObjects"), list):
502
+ for o in data["timelineObjects"]:
503
+ v = o.get("placeVisit") if isinstance(o, dict) else None
504
+ if isinstance(v, dict):
505
+ dur, loc = v.get("duration") or {}, v.get("location") or {}
506
+ yield (_when_day(dur.get("startTimestamp") or dur.get("startTimestampMs")),
507
+ loc.get("address"))
508
+ return
509
+ segs = data.get("semanticSegments") if isinstance(data, dict) else data
510
+ if not isinstance(segs, list):
511
+ raise ValueError("not a location file")
512
+ for s in segs:
513
+ visit = s.get("visit") if isinstance(s, dict) else None
514
+ if isinstance(visit, dict):
515
+ top = visit.get("topCandidate") or {}
516
+ place = top.get("placeLocation")
517
+ yield (_when_day(s.get("startTime")),
518
+ top.get("address") or (place.get("address") if isinstance(place, dict)
519
+ else None))
520
+
521
+
522
+ def location_file(name: str) -> bool:
523
+ """A Takeout location history JSON, by its path (for `importers.detect`)."""
524
+ low = name.lower().replace("\\", "/")
525
+ base = low.rsplit("/", 1)[-1]
526
+ return low.endswith(".json") and (
527
+ "semantic location history/" in low
528
+ or base in ("timeline.json", "location-history.json", "records.json")
529
+ or re.fullmatch(r"\d{4}_(?:january|february|march|april|may|june|july|august|"
530
+ r"september|october|november|december)\.json", base) is not None)
531
+
532
+
533
+ def location_source(path: Path) -> sources.Source:
534
+ """Google Timeline exports into month pages of `- YYYY-MM-DD: City`, one city per day
535
+ (the most visited that day). Coordinates, street addresses, raw points (Records.json) and
536
+ movements are never read into a page; a day with no address is skipped (no network, no
537
+ reverse geocoding)."""
538
+ import json
539
+ path = Path(path)
540
+ found = [f for f in importers._files(path) if f[0].lower().endswith(".json")]
541
+ if not found:
542
+ raise VaultError("invalid_argument", f"Found no location history .json in "
543
+ f"{path.name}.")
544
+
545
+ def items():
546
+ days = defaultdict(Counter)
547
+ for name, _size, _mtime, read in found:
548
+ if name.lower().rsplit("/", 1)[-1] == "records.json":
549
+ yield "raw points (not read)"
550
+ continue
551
+ try:
552
+ data = json.loads(read().decode("utf-8-sig"))
553
+ visits = list(_visits(data))
554
+ except VaultError:
555
+ yield "over 200 MB"
556
+ continue
557
+ except ValueError as e:
558
+ yield "not a location file" if str(e) == "not a location file" \
559
+ else "malformed file"
560
+ continue
561
+ except (AttributeError, TypeError): # a list of something else
562
+ yield "not a location file"
563
+ continue
564
+ for day, address in visits:
565
+ if day:
566
+ days[day][city(address) if address else None] += 1
567
+ for day, cities in sorted(days.items()):
568
+ cities.pop(None, None)
569
+ if not cities:
570
+ yield "no place name"
571
+ continue
572
+ yield sources.Item(day, day, f"{day}: {cities.most_common(1)[0][0]}")
573
+
574
+ return sources.Source("location", "Location", "file", items, default_tier=LOCAL,
575
+ page="month", noun="places", coarse_place=True, skips=LOC_SKIPS)
576
+
577
+
578
+ # ---- photo dates and albums ----
579
+
580
+ PHOTO_SUFFIXES = (".jpg", ".jpeg", ".png", ".heic", ".heif", ".webp", ".tif", ".tiff", ".dng",
581
+ ".gif")
582
+ ALBUMS = 5 # album names per day, then "and N more"
583
+
584
+
585
+ def photo_day(p: Path) -> str:
586
+ """The day a photo was taken: EXIF DateTimeOriginal (else DateTime) when Pillow can read
587
+ it, else the file's modified date. Only those two tags are read: never GPS or any other."""
588
+ try:
589
+ from PIL import Image
590
+ except ImportError: # Pillow is optional (it comes with pystray on Windows)
591
+ Image = None
592
+ if Image is not None:
593
+ try:
594
+ with Image.open(p) as im:
595
+ exif = im.getexif()
596
+ raw = exif.get_ifd(0x8769).get(36867) or exif.get(306)
597
+ if m := re.match(r"(\d{4}):(\d\d):(\d\d)", str(raw or "")):
598
+ return date(int(m[1]), int(m[2]), int(m[3])).isoformat()
599
+ except Exception: # noqa: BLE001 - Pillow raises many types on a damaged image
600
+ pass
601
+ from datetime import datetime
602
+ return datetime.fromtimestamp(p.stat().st_mtime).date().isoformat()
603
+
604
+
605
+ def photos_source(path: Path) -> sources.Source:
606
+ """A photo folder into month pages of `- YYYY-MM-DD: N photos (albums)`, the album being
607
+ each photo's folder name. Images are never stored or copied; no thumbnails, no GPS."""
608
+ root = Path(path)
609
+ if not root.is_dir():
610
+ raise VaultError("invalid_argument", f"{root.name} is not a folder of photos.")
611
+
612
+ def items():
613
+ days = defaultdict(Counter)
614
+ for p in importers._walk(root, lambda rel: any(
615
+ x.startswith(".") for x in rel.split("/")), []):
616
+ if not p.is_file() or p.name.startswith("."):
617
+ continue
618
+ if p.suffix.lower() not in PHOTO_SUFFIXES:
619
+ yield "not a photo"
620
+ continue
621
+ try:
622
+ day = photo_day(p)
623
+ except (OSError, ValueError, OverflowError):
624
+ yield "unreadable"
625
+ continue
626
+ days[day][p.parent.name if p.parent != root else root.name] += 1
627
+ for day, albums in sorted(days.items()):
628
+ n, names = sum(albums.values()), sorted(albums)
629
+ more = len(names) - ALBUMS
630
+ yield sources.Item(day, day, f"{day}: {n} photo{_s(n)} ("
631
+ + ", ".join(names[:ALBUMS])
632
+ + (f" and {more} more" if more > 0 else "") + ")")
633
+
634
+ return sources.Source("photos", "Photos", "folder", items, page="month", noun="days",
635
+ coarse_place=True, skips=("not a photo", "unreadable"))
636
+
637
+
638
+ # ---- Spotify, a page per year ----
639
+
640
+ TOP, TOP_PODCASTS = 20, 10
641
+ SPOTIFY_SKIPS = ("not a listening history file", "covered by the extended history",
642
+ "malformed file", "over 200 MB")
643
+
644
+
645
+ def spotify_file(name: str) -> str | None:
646
+ """"extended" (Streaming_History_Audio_*.json, endsong_*.json), "account"
647
+ (StreamingHistory*.json, music and podcasts) or None."""
648
+ base = name.lower().replace("\\", "/").rsplit("/", 1)[-1]
649
+ if not base.endswith(".json"):
650
+ return None
651
+ if base.startswith(("streaming_history_audio_", "endsong_")):
652
+ return "extended"
653
+ return "account" if base.startswith("streaminghistory") else None
654
+
655
+
656
+ def _hours(ms: float) -> str:
657
+ return f"{ms / 3.6e6:,.1f}"
658
+
659
+
660
+ def _plays(rows: list, kind: str, years: dict) -> None:
661
+ """Add one file's rows to `years` (year -> {total, music, podcasts, artists, tracks,
662
+ shows, last}); nothing per play is kept."""
663
+ for r in rows:
664
+ if not isinstance(r, dict):
665
+ continue
666
+ extended = kind == "extended"
667
+ when = str(r.get("ts" if extended else "endTime") or "")
668
+ ms = r.get("ms_played" if extended else "msPlayed")
669
+ if not re.match(r"\d{4}-\d\d-\d\d", when) or not isinstance(ms, int | float) or ms <= 0:
670
+ continue
671
+ y = years.setdefault(when[:4], {"total": 0, "music": 0, "podcasts": 0,
672
+ "artists": Counter(), "tracks": Counter(),
673
+ "shows": Counter(), "last": ""})
674
+ y["total"] += ms
675
+ y["last"] = max(y["last"], when[:10])
676
+ track = r.get("master_metadata_track_name" if extended else "trackName")
677
+ artist = r.get("master_metadata_album_artist_name" if extended else "artistName")
678
+ show = r.get("episode_show_name" if extended else "podcastName")
679
+ if track and artist:
680
+ y["music"] += ms
681
+ y["artists"][artist] += ms
682
+ y["tracks"][track, artist] += ms
683
+ elif show:
684
+ y["podcasts"] += ms
685
+ y["shows"][show] += ms
686
+
687
+
688
+ def _year_text(year: str, y: dict) -> str:
689
+ head = (f"My Spotify listening in {year}: {_hours(y['total'])} hours (music "
690
+ f"{_hours(y['music'])}, podcasts {_hours(y['podcasts'])}).")
691
+ out = [head]
692
+ for title, rows in (
693
+ (f"Top {TOP} artists", [f"{a}: {_hours(ms)} hours"
694
+ for a, ms in y["artists"].most_common(TOP)]),
695
+ (f"Top {TOP} tracks", [f"\"{t}\" by {a}: {_hours(ms)} hours"
696
+ for (t, a), ms in y["tracks"].most_common(TOP)]),
697
+ ("Top podcasts", [f"{s}: {_hours(ms)} hours"
698
+ for s, ms in y["shows"].most_common(TOP_PODCASTS)])):
699
+ if rows:
700
+ out.append(f"## {title}\n" + "\n".join(f"{i}. {x}" for i, x in enumerate(rows, 1)))
701
+ return "\n\n".join(out)
702
+
703
+
704
+ def spotify_source(path: Path) -> sources.Source:
705
+ """A Spotify data export (the account data's StreamingHistory*.json or the extended
706
+ Streaming_History_Audio_*.json; the extended one wins when both are there) into one page
707
+ per year: total hours, the top artists and tracks by time, the top podcasts. Keyed by
708
+ year with `updates`, so a newer export rewrites the year in place."""
709
+ import json
710
+ path = Path(path)
711
+ found = [(f, k) for f in importers._files(path) if (k := spotify_file(f[0]))]
712
+ if not found:
713
+ raise VaultError("invalid_argument", f"Found no Spotify streaming history "
714
+ f"(StreamingHistory*.json or Streaming_History_Audio_*.json) in "
715
+ f"{path.name}.")
716
+ extended = any(k == "extended" for _, k in found)
717
+
718
+ def items():
719
+ years = {}
720
+ for (_name, _size, _mtime, read), kind in found:
721
+ if extended and kind == "account":
722
+ yield "covered by the extended history"
723
+ continue
724
+ try:
725
+ rows = json.loads(read().decode("utf-8-sig"))
726
+ except VaultError:
727
+ yield "over 200 MB"
728
+ continue
729
+ except ValueError:
730
+ yield "malformed file"
731
+ continue
732
+ if not isinstance(rows, list):
733
+ yield "not a listening history file"
734
+ continue
735
+ _plays(rows, kind, years)
736
+ for year, y in sorted(years.items()):
737
+ yield sources.Item(f"Spotify {year}", y["last"], _year_text(year, y),
738
+ key=f"spotify {year}")
739
+
740
+ return sources.Source("spotify", "Spotify", "file", items, prefix="listening",
741
+ updates=True, skips=SPOTIFY_SKIPS,
742
+ size=_figure(r"My Spotify listening in \d{4}: ([\d,.]+) hours"))
743
+
744
+
745
+ SOURCE_OF = {"mail": mail_source, "selfchat": selfchat_source, "location": location_source,
746
+ "photos": photos_source, "spotify": spotify_source,
747
+ "voice-memos": voice_memos.voice_source}