lifekeeper 0.1.0__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.
lifekeeper/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Lifekeeper: one page of your life from the data you already have, and answers from your own records."""
2
+
3
+ __version__ = "0.1.0"
lifekeeper/app.py ADDED
@@ -0,0 +1,342 @@
1
+ #!/usr/bin/env python3
2
+ """Lifekeeper as a window: choose your exports folder, press one button, and your page opens in the browser.
3
+ Then ask questions about your life in the same window. The window is a small web page (pywebview); without
4
+ a web engine it falls back to a plain Tk window.
5
+
6
+ python app.py # the window
7
+ python app.py EXPORTS --out my.html # no window: the same as lifekeeper.py
8
+
9
+ .github/workflows/release.yml builds this into a double-click app for Windows and Mac. Nothing is sent anywhere unless you choose Google Gemini for answers.
10
+ """
11
+ import json
12
+ import sys
13
+ import threading
14
+ import webbrowser
15
+ from pathlib import Path
16
+
17
+ try: # installed with pip: part of the lifekeeper package
18
+ from . import lifekeeper
19
+ except ImportError: # run as a script from this folder
20
+ import lifekeeper
21
+
22
+
23
+ def page_path(folder):
24
+ """The page goes next to the exports folder, never inside it: the originals stay untouched."""
25
+ for place in (Path(folder).parent, Path.home() / "Documents", Path.home()):
26
+ try:
27
+ test = place / ".lifekeeper-write-test"
28
+ test.write_text("", encoding="utf-8")
29
+ test.unlink()
30
+ return place / "my-life.html"
31
+ except OSError:
32
+ continue
33
+ raise OSError("There's nowhere to save the page. Try a folder you can write to.")
34
+
35
+
36
+ def make_page(folder, name):
37
+ life = lifekeeper.build(folder, [name] if name.strip() else [])
38
+ page = lifekeeper.render(life, "My life at a glance")
39
+ if page is None:
40
+ raise ValueError("Nothing with a date was found in that folder. Check that it holds your exports "
41
+ "(the guide is in docs/download-your-data).")
42
+ out = page_path(folder)
43
+ out.write_text(page, encoding="utf-8")
44
+ return out, life
45
+
46
+
47
+ def tk_window(): # the plain window, for computers without a web engine
48
+ import tkinter as tk
49
+ from tkinter import filedialog, messagebox, scrolledtext, ttk
50
+
51
+ try:
52
+ from . import ask
53
+ except ImportError:
54
+ import ask
55
+
56
+ root = tk.Tk()
57
+ root.title("Lifekeeper")
58
+ try: # the tree rings in the title bar and taskbar
59
+ try:
60
+ from . import icon_data
61
+ except ImportError:
62
+ import icon_data
63
+ root.iconphoto(True, tk.PhotoImage(data="".join(icon_data.PNG)))
64
+ except Exception: # an icon is never worth failing over
65
+ pass
66
+ root.geometry("640x760")
67
+ root.minsize(560, 640)
68
+ base = ("Segoe UI", 12) if sys.platform == "win32" else ("Helvetica", 14)
69
+ root.option_add("*Font", base)
70
+ pad = {"padx": 24, "anchor": "w"}
71
+ state = {"folder": None, "records": None}
72
+
73
+ tk.Label(root, text="Your life on one page", font=(base[0], base[1] + 8, "bold")).pack(pady=(18, 2), **pad)
74
+ tk.Label(root, text="Put your exports in one folder (zips can stay zipped). Making the page sends nothing anywhere.",
75
+ wraplength=580, justify="left", fg="#555").pack(**pad)
76
+
77
+ tk.Label(root, text="1. The folder with your exports").pack(pady=(14, 4), **pad)
78
+ row = tk.Frame(root)
79
+ row.pack(fill="x", padx=24)
80
+ chosen = tk.Label(row, text="not chosen yet", fg="#777", anchor="w")
81
+
82
+ def choose():
83
+ folder = filedialog.askdirectory(title="Choose the folder with your exports")
84
+ if folder:
85
+ state["folder"], state["records"] = folder, None
86
+ chosen.config(text=folder, fg="#1d1d1f")
87
+ make.config(state="normal")
88
+ ask_button.config(state="disabled")
89
+
90
+ tk.Button(row, text="Choose…", command=choose, width=10).pack(side="left")
91
+ chosen.pack(side="left", padx=10, fill="x", expand=True)
92
+
93
+ tk.Label(root, text="2. Your name as it appears in your chats (you can leave it empty)").pack(pady=(12, 4), **pad)
94
+ name = tk.Entry(root, width=40)
95
+ name.pack(**pad)
96
+
97
+ status = tk.Label(root, text="", wraplength=580, justify="left", fg="#555")
98
+ progress = ttk.Progressbar(root, mode="indeterminate", length=580)
99
+
100
+ def finished(result):
101
+ progress.stop()
102
+ progress.pack_forget()
103
+ make.config(state="normal")
104
+ if isinstance(result, Exception):
105
+ status.config(text="")
106
+ messagebox.showerror("Lifekeeper", str(result))
107
+ return
108
+ out, life = result
109
+ state["records"] = ask.records(life)
110
+ ask_button.config(state="normal")
111
+ status.config(text=f"Done. Your page is saved as {out}. What was read is listed at the end of the page.")
112
+ webbrowser.open(out.as_uri())
113
+
114
+ def work(folder, who):
115
+ try:
116
+ result = make_page(folder, who)
117
+ except Exception as error: # shown to the person in plain words, not as a crash
118
+ result = error
119
+ root.after(0, finished, result)
120
+
121
+ def start():
122
+ if not state["folder"]:
123
+ return
124
+ make.config(state="disabled")
125
+ status.config(text="Reading your exports… Big exports can take a few minutes.")
126
+ progress.pack(pady=(8, 0), **pad)
127
+ progress.start(12)
128
+ threading.Thread(target=work, args=(state["folder"], name.get()), daemon=True).start()
129
+
130
+ make = tk.Button(root, text="3. Make my page", command=start, state="disabled", width=18)
131
+ make.pack(pady=(14, 0), **pad)
132
+ status.pack(pady=(8, 0), **pad)
133
+
134
+ # ---------- ask ----------
135
+ ttk.Separator(root).pack(fill="x", padx=24, pady=(14, 0))
136
+ tk.Label(root, text="4. Ask a question about your life (after the page is made)").pack(pady=(12, 4), **pad)
137
+ question = tk.Entry(root)
138
+ question.pack(fill="x", padx=24)
139
+
140
+ WAYS = ["Show my records (no AI, nothing leaves this computer)",
141
+ "Answer with a model on this computer (Ollama)",
142
+ "Answer with Google Gemini (sends matching records to Google)"]
143
+ way = ttk.Combobox(root, values=WAYS, state="readonly")
144
+ way.current(0)
145
+ way.pack(fill="x", padx=24, pady=(8, 0))
146
+ extra_label = tk.Label(root, text="", fg="#555")
147
+ extra = tk.Entry(root, width=44)
148
+
149
+ def way_changed(_event=None):
150
+ extra_label.pack_forget()
151
+ extra.pack_forget()
152
+ extra.delete(0, "end")
153
+ if way.current() == 1:
154
+ extra_label.config(text="The model's name in Ollama, for example gemma3")
155
+ extra.config(show="")
156
+ elif way.current() == 2:
157
+ extra_label.config(text="Your Gemini API key (it isn't saved)")
158
+ extra.config(show="•")
159
+ if way.current():
160
+ extra_label.pack(pady=(6, 2), before=ask_button, **pad)
161
+ extra.pack(before=ask_button, **pad)
162
+
163
+ way.bind("<<ComboboxSelected>>", way_changed)
164
+
165
+ def answered(text):
166
+ ask_button.config(state="normal")
167
+ shown.config(state="normal")
168
+ shown.delete("1.0", "end")
169
+ shown.insert("1.0", text)
170
+ shown.config(state="disabled")
171
+
172
+ def think(found, asked, chosen, value):
173
+ write = None
174
+ if chosen == 1:
175
+ write = lambda system, prompt: ask.ollama(system, prompt, value) # noqa: E731
176
+ elif chosen == 2:
177
+ write = lambda system, prompt: ask.gemini(system, prompt, value) # noqa: E731
178
+ try:
179
+ text = ask.answer(found, asked, write)
180
+ except Exception as error: # a wrong key, no connection, Ollama not running: said in plain words
181
+ text = str(error)
182
+ root.after(0, answered, text)
183
+
184
+ def ask_now(_event=None):
185
+ asked, value = question.get().strip(), extra.get().strip()
186
+ if not state["records"] or not asked or str(ask_button["state"]) == "disabled":
187
+ return
188
+ if way.current() and not value:
189
+ answered("Type the model's name first." if way.current() == 1 else "Paste your Gemini API key first. A free key: aistudio.google.com/apikey")
190
+ return
191
+ ask_button.config(state="disabled")
192
+ answered("Looking through your records…")
193
+ ask_button.config(state="disabled")
194
+ threading.Thread(target=think, args=(state["records"], asked, way.current(), value), daemon=True).start()
195
+
196
+ ask_button = tk.Button(root, text="Ask", command=ask_now, state="disabled", width=18)
197
+ ask_button.pack(pady=(10, 0), **pad)
198
+ question.bind("<Return>", ask_now)
199
+ shown = scrolledtext.ScrolledText(root, height=9, wrap="word", state="disabled", font=(base[0], base[1] - 1))
200
+ shown.pack(fill="both", expand=True, padx=24, pady=(10, 18))
201
+ root.mainloop()
202
+
203
+
204
+ class FacesApi:
205
+ """The faces add-on, for the window. Without it, the window says how to add it."""
206
+
207
+ def _faces(self):
208
+ try:
209
+ from . import faces
210
+ except ImportError:
211
+ import faces
212
+ return faces
213
+
214
+ def faces_known(self, folder):
215
+ return lifekeeper.faces_file(folder).is_file()
216
+
217
+ def faces_scan(self, folder, name):
218
+ try:
219
+ faces = self._faces()
220
+ report = lambda text: self.window.evaluate_js(f"facesProgress({json.dumps(text)})") # noqa: E731
221
+ photos, found = faces.scan(folder, [name] if (name or "").strip() else [], progress=report)
222
+ return {"photos": photos, "faces": found}
223
+ except Exception as error:
224
+ return {"error": str(error)}
225
+
226
+ def faces_people(self, folder):
227
+ import base64
228
+ try:
229
+ faces = self._faces()
230
+ groups = faces.people(folder)[:60]
231
+ pictures = faces.crops(folder, [face for group in groups for face in group["faces"][:6]])
232
+ return {"groups": [{"person": group["person"], "name": group["name"], "photos": group["photos"],
233
+ "faces": ["data:image/jpeg;base64," + base64.b64encode(pictures[face]).decode()
234
+ for face in group["faces"][:6] if face in pictures]} for group in groups]}
235
+ except Exception as error:
236
+ return {"error": str(error)}
237
+
238
+ def faces_name(self, folder, person, name):
239
+ return self._faces().name(folder, person, name or "")
240
+
241
+ def faces_hide(self, folder, person):
242
+ return self._faces().hide(folder, person)
243
+
244
+
245
+ class Api(FacesApi):
246
+ """What the window's page can ask Python to do. Each call runs in its own thread, so the window stays responsive."""
247
+
248
+ def __init__(self):
249
+ self.window, self.out, self.records = None, None, None
250
+
251
+ def choose_folder(self):
252
+ import webview
253
+ chosen = self.window.create_file_dialog(webview.FileDialog.FOLDER)
254
+ return chosen[0] if chosen else None
255
+
256
+ def make_page(self, folder, name):
257
+ try:
258
+ out, life = make_page(folder, name or "")
259
+ except Exception as error: # said in plain words in the window, not as a crash
260
+ return {"error": str(error)}
261
+ try:
262
+ from . import ask
263
+ except ImportError:
264
+ import ask
265
+ self.out, self.records = out, ask.records(life)
266
+ webbrowser.open(out.as_uri())
267
+ return {"out": str(out)}
268
+
269
+ def open_page(self):
270
+ if self.out:
271
+ webbrowser.open(self.out.as_uri())
272
+
273
+ def ask(self, question, mode, value):
274
+ try:
275
+ from . import ask
276
+ except ImportError:
277
+ import ask
278
+ write = None
279
+ if mode == "ollama":
280
+ write = lambda system, prompt: ask.ollama(system, prompt, value) # noqa: E731
281
+ elif mode == "gemini":
282
+ write = lambda system, prompt: ask.gemini(system, prompt, value) # noqa: E731
283
+ try:
284
+ return {"text": ask.answer(self.records or [], question, write)}
285
+ except Exception as error: # a wrong key, Ollama not running, no connection
286
+ return {"error": str(error)}
287
+
288
+
289
+ def web_window():
290
+ """The window as a small web page in a native window: the same look as the page it makes."""
291
+ import webview
292
+ try:
293
+ from . import webui
294
+ except ImportError:
295
+ import webui
296
+ api = Api()
297
+ api.window = webview.create_window("Lifekeeper", html=webui.PAGE, js_api=api, width=700, height=880,
298
+ min_size=(560, 640))
299
+ webview.start(windows_icon)
300
+
301
+
302
+ def windows_icon():
303
+ """On Windows the window shows the program's icon, which is Python's when run as a script or installed with pip.
304
+ Put the tree rings there instead. Anywhere else, or if anything goes wrong, nothing happens."""
305
+ if sys.platform != "win32":
306
+ return
307
+ try:
308
+ import ctypes
309
+ import time
310
+ icon = Path(__file__).with_name("icon.ico")
311
+ if not icon.is_file():
312
+ return
313
+ user32 = ctypes.windll.user32
314
+ for _ in range(50): # the window appears a moment after start
315
+ hwnd = user32.FindWindowW(None, "Lifekeeper")
316
+ if hwnd:
317
+ break
318
+ time.sleep(0.1)
319
+ for size, which in ((16, 0), (32, 1)): # small and big icons (WM_SETICON = 0x80)
320
+ handle = user32.LoadImageW(None, str(icon), 1, size, size, 0x10) # IMAGE_ICON, LR_LOADFROMFILE
321
+ if handle:
322
+ user32.SendMessageW(hwnd, 0x80, which, handle)
323
+ except Exception:
324
+ pass
325
+
326
+
327
+ def window():
328
+ try:
329
+ web_window()
330
+ except Exception: # no web engine here (pywebview or WebView2 missing): the plain window still works
331
+ tk_window()
332
+
333
+
334
+ def main():
335
+ if len(sys.argv) > 1: # with arguments it's the command line, exactly like lifekeeper.py
336
+ lifekeeper.main()
337
+ else:
338
+ window()
339
+
340
+
341
+ if __name__ == "__main__":
342
+ main()