macrolog 0.1.0__tar.gz
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.
- macrolog-0.1.0/LICENSE +21 -0
- macrolog-0.1.0/PKG-INFO +132 -0
- macrolog-0.1.0/README.md +109 -0
- macrolog-0.1.0/macrolog/__init__.py +0 -0
- macrolog-0.1.0/macrolog/app.py +25 -0
- macrolog-0.1.0/macrolog/budget.py +95 -0
- macrolog-0.1.0/macrolog/config.py +7 -0
- macrolog-0.1.0/macrolog/dashboard.py +261 -0
- macrolog-0.1.0/macrolog/db.py +195 -0
- macrolog-0.1.0/macrolog/mcp_server.py +520 -0
- macrolog-0.1.0/macrolog/static/app.js +539 -0
- macrolog-0.1.0/macrolog/static/icon.svg +6 -0
- macrolog-0.1.0/macrolog/static/index.html +199 -0
- macrolog-0.1.0/macrolog/static/manifest.webmanifest +9 -0
- macrolog-0.1.0/macrolog/static/style.css +306 -0
- macrolog-0.1.0/macrolog/static/vendor/chart.umd.min.js +20 -0
- macrolog-0.1.0/macrolog/stats.py +165 -0
- macrolog-0.1.0/macrolog/timeutil.py +63 -0
- macrolog-0.1.0/macrolog.egg-info/PKG-INFO +132 -0
- macrolog-0.1.0/macrolog.egg-info/SOURCES.txt +30 -0
- macrolog-0.1.0/macrolog.egg-info/dependency_links.txt +1 -0
- macrolog-0.1.0/macrolog.egg-info/entry_points.txt +4 -0
- macrolog-0.1.0/macrolog.egg-info/requires.txt +9 -0
- macrolog-0.1.0/macrolog.egg-info/top_level.txt +1 -0
- macrolog-0.1.0/pyproject.toml +38 -0
- macrolog-0.1.0/setup.cfg +4 -0
- macrolog-0.1.0/tests/test_budget.py +78 -0
- macrolog-0.1.0/tests/test_dashboard_api.py +97 -0
- macrolog-0.1.0/tests/test_db.py +53 -0
- macrolog-0.1.0/tests/test_mcp_tools.py +192 -0
- macrolog-0.1.0/tests/test_stats.py +117 -0
- macrolog-0.1.0/tests/test_timeutil.py +42 -0
macrolog-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Eric Liswung
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
macrolog-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: macrolog
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Log meals by chatting with Claude; track calories, macros and weight in a local dashboard.
|
|
5
|
+
Author: Eric Liswung
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ericliswan/macrolog
|
|
8
|
+
Keywords: mcp,claude,nutrition,calories,macros,food-log
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Topic :: Utilities
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: mcp<3,>=2
|
|
16
|
+
Requires-Dist: starlette
|
|
17
|
+
Requires-Dist: uvicorn
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest; extra == "dev"
|
|
20
|
+
Provides-Extra: app
|
|
21
|
+
Requires-Dist: pywebview>=6; extra == "app"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# macrolog
|
|
25
|
+
|
|
26
|
+
A food diary that lives in the Claude desktop app. You tell Claude what you ate. Claude estimates the calories and macros, and an MCP server stores them in a local SQLite file and keeps the totals. A dashboard shows today's budget, your meals, trend charts and weight. Everything stays on your computer. The full design is in [SPEC.md](SPEC.md).
|
|
27
|
+
|
|
28
|
+
<picture>
|
|
29
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ericliswan/macrolog/main/docs/screenshots/dashboard-dark.png">
|
|
30
|
+
<img alt="Macrolog dashboard: today's calories left with a progress ring, macro bars, the weekly budget, today's meals and a six-month record" src="https://raw.githubusercontent.com/ericliswan/macrolog/main/docs/screenshots/dashboard-light.png">
|
|
31
|
+
</picture>
|
|
32
|
+
|
|
33
|
+
<details>
|
|
34
|
+
<summary>Trends: averages, calorie and protein charts, macro split, body weight, meal types and top foods</summary>
|
|
35
|
+
|
|
36
|
+
<picture>
|
|
37
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ericliswan/macrolog/main/docs/screenshots/trends-dark.png">
|
|
38
|
+
<img alt="Macrolog trends: stat tiles, calories per day, protein per day, calories from each macro, body weight, calories by meal type and top foods" src="https://raw.githubusercontent.com/ericliswan/macrolog/main/docs/screenshots/trends-light.png">
|
|
39
|
+
</picture>
|
|
40
|
+
</details>
|
|
41
|
+
|
|
42
|
+
Screenshots use the demo data from `scripts/seed_demo.py`. The dashboard follows your system's light or dark mode.
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
### Mac app (no Python needed)
|
|
47
|
+
|
|
48
|
+
1. Download `Macrolog-…-mac-arm64.zip` (Apple Silicon) or `…-mac-x86_64.zip` (Intel) from [Releases](https://github.com/ericliswan/macrolog/releases), unzip it, and drag Macrolog to Applications.
|
|
49
|
+
2. Open it. The app isn't signed by Apple yet, so macOS blocks it the first time: click Done, then open System Settings → Privacy & Security, scroll down to "Macrolog was blocked" and click **Open Anyway**. (Or run `xattr -dr com.apple.quarantine /Applications/Macrolog.app` once.)
|
|
50
|
+
3. In the Claude desktop app, open Settings → Developer → Edit Config and add:
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"mcpServers": {
|
|
55
|
+
"macrolog": {
|
|
56
|
+
"command": "/Applications/Macrolog.app/Contents/MacOS/Macrolog",
|
|
57
|
+
"args": ["mcp"]
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Opening Macrolog shows the dashboard in its own window. Claude runs the same app in the background (`mcp`) to log your meals. Both use the same database, so they stay in sync.
|
|
64
|
+
|
|
65
|
+
### With Python (any OS)
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
pipx install macrolog # or: pipx install "macrolog[app]" to also get the macrolog-app window
|
|
69
|
+
which macrolog-mcp # use this full path as "command" in the config above, without "args"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
On Windows the path looks like `C:\\Users\\you\\.local\\bin\\macrolog-mcp.exe`. Backslashes must be doubled in JSON.
|
|
73
|
+
|
|
74
|
+
### Then
|
|
75
|
+
|
|
76
|
+
1. Fully quit the Claude app and open it again.
|
|
77
|
+
2. Click "+" in the chat box, then Connectors. macrolog and its tools should be listed. The app asks for your approval the first time Claude uses each tool.
|
|
78
|
+
3. Say what you ate. The first time, Claude asks about your goal and targets (defaults: maintain weight, 2000 kcal). You can change them later in the dashboard's Settings.
|
|
79
|
+
|
|
80
|
+
## Configuration
|
|
81
|
+
|
|
82
|
+
Set these environment variables in an `"env": {}` block next to `"command"`:
|
|
83
|
+
|
|
84
|
+
| Variable | Default | Meaning |
|
|
85
|
+
|---|---|---|
|
|
86
|
+
| `MACROLOG_DB` | `~/.macrolog/macrolog.db` | Path to the database file |
|
|
87
|
+
| `MACROLOG_PORT` | `8765` | Dashboard port |
|
|
88
|
+
| `MACROLOG_DASHBOARD` | `1` | Set to `0` to stop the MCP server from also running the dashboard |
|
|
89
|
+
|
|
90
|
+
## Dashboard
|
|
91
|
+
|
|
92
|
+
The Mac app shows the dashboard in a window. The MCP server also serves it at http://127.0.0.1:8765 whenever the Claude app is open, and `macrolog-dash` starts it on its own. It only accepts connections from `127.0.0.1` and `localhost`.
|
|
93
|
+
|
|
94
|
+
## Backups and export
|
|
95
|
+
|
|
96
|
+
- **Backups:** the first time the MCP server connects each day, it writes a copy of the database to `<db folder>/backups/`. The last 14 copies are kept. To restore, quit the Claude app and copy a backup over the database file.
|
|
97
|
+
- **Export:** Settings → Export (CSV) downloads your meals and items, weights, or targets.
|
|
98
|
+
|
|
99
|
+
## Demo data
|
|
100
|
+
|
|
101
|
+
To try the dashboard without touching your real diary:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
python scripts/seed_demo.py # writes ~/.macrolog/demo.db
|
|
105
|
+
MACROLOG_DB=~/.macrolog/demo.db MACROLOG_PORT=8799 macrolog-dash
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Then open http://127.0.0.1:8799. The script won't write to the real database or overwrite an existing file.
|
|
109
|
+
|
|
110
|
+
## Troubleshooting
|
|
111
|
+
|
|
112
|
+
- Check `mcp.log` and `mcp-server-macrolog.log` in the Claude app's logs folder:
|
|
113
|
+
- macOS: `~/Library/Logs/Claude`
|
|
114
|
+
- Windows: `%APPDATA%\Claude\logs`
|
|
115
|
+
- Linux: `~/.config/Claude/logs`
|
|
116
|
+
- Run `macrolog-mcp` (or `/Applications/Macrolog.app/Contents/MacOS/Macrolog mcp`) in a terminal to see startup errors.
|
|
117
|
+
- If the dashboard doesn't load, port 8765 may already be in use. Set `MACROLOG_PORT` to a different port.
|
|
118
|
+
|
|
119
|
+
## Development
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
python -m venv .venv && source .venv/bin/activate
|
|
123
|
+
pip install -e ".[dev,app]"
|
|
124
|
+
pytest
|
|
125
|
+
pip install pyinstaller && pyinstaller packaging/macrolog.spec # builds dist/Macrolog.app
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Releasing
|
|
129
|
+
|
|
130
|
+
Bump `version` in `pyproject.toml`, commit, then push a matching tag: `git tag v0.2.0 && git push origin v0.2.0`. The release workflow publishes to PyPI and attaches Apple Silicon and Intel builds of Macrolog.app to a GitHub release.
|
|
131
|
+
|
|
132
|
+
One-time setup: on PyPI, add a trusted publisher for this repo (workflow `release.yml`, environment `pypi`), and create an environment named `pypi` in the repo's GitHub settings.
|
macrolog-0.1.0/README.md
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# macrolog
|
|
2
|
+
|
|
3
|
+
A food diary that lives in the Claude desktop app. You tell Claude what you ate. Claude estimates the calories and macros, and an MCP server stores them in a local SQLite file and keeps the totals. A dashboard shows today's budget, your meals, trend charts and weight. Everything stays on your computer. The full design is in [SPEC.md](SPEC.md).
|
|
4
|
+
|
|
5
|
+
<picture>
|
|
6
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ericliswan/macrolog/main/docs/screenshots/dashboard-dark.png">
|
|
7
|
+
<img alt="Macrolog dashboard: today's calories left with a progress ring, macro bars, the weekly budget, today's meals and a six-month record" src="https://raw.githubusercontent.com/ericliswan/macrolog/main/docs/screenshots/dashboard-light.png">
|
|
8
|
+
</picture>
|
|
9
|
+
|
|
10
|
+
<details>
|
|
11
|
+
<summary>Trends: averages, calorie and protein charts, macro split, body weight, meal types and top foods</summary>
|
|
12
|
+
|
|
13
|
+
<picture>
|
|
14
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ericliswan/macrolog/main/docs/screenshots/trends-dark.png">
|
|
15
|
+
<img alt="Macrolog trends: stat tiles, calories per day, protein per day, calories from each macro, body weight, calories by meal type and top foods" src="https://raw.githubusercontent.com/ericliswan/macrolog/main/docs/screenshots/trends-light.png">
|
|
16
|
+
</picture>
|
|
17
|
+
</details>
|
|
18
|
+
|
|
19
|
+
Screenshots use the demo data from `scripts/seed_demo.py`. The dashboard follows your system's light or dark mode.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
### Mac app (no Python needed)
|
|
24
|
+
|
|
25
|
+
1. Download `Macrolog-…-mac-arm64.zip` (Apple Silicon) or `…-mac-x86_64.zip` (Intel) from [Releases](https://github.com/ericliswan/macrolog/releases), unzip it, and drag Macrolog to Applications.
|
|
26
|
+
2. Open it. The app isn't signed by Apple yet, so macOS blocks it the first time: click Done, then open System Settings → Privacy & Security, scroll down to "Macrolog was blocked" and click **Open Anyway**. (Or run `xattr -dr com.apple.quarantine /Applications/Macrolog.app` once.)
|
|
27
|
+
3. In the Claude desktop app, open Settings → Developer → Edit Config and add:
|
|
28
|
+
|
|
29
|
+
```json
|
|
30
|
+
{
|
|
31
|
+
"mcpServers": {
|
|
32
|
+
"macrolog": {
|
|
33
|
+
"command": "/Applications/Macrolog.app/Contents/MacOS/Macrolog",
|
|
34
|
+
"args": ["mcp"]
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Opening Macrolog shows the dashboard in its own window. Claude runs the same app in the background (`mcp`) to log your meals. Both use the same database, so they stay in sync.
|
|
41
|
+
|
|
42
|
+
### With Python (any OS)
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pipx install macrolog # or: pipx install "macrolog[app]" to also get the macrolog-app window
|
|
46
|
+
which macrolog-mcp # use this full path as "command" in the config above, without "args"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
On Windows the path looks like `C:\\Users\\you\\.local\\bin\\macrolog-mcp.exe`. Backslashes must be doubled in JSON.
|
|
50
|
+
|
|
51
|
+
### Then
|
|
52
|
+
|
|
53
|
+
1. Fully quit the Claude app and open it again.
|
|
54
|
+
2. Click "+" in the chat box, then Connectors. macrolog and its tools should be listed. The app asks for your approval the first time Claude uses each tool.
|
|
55
|
+
3. Say what you ate. The first time, Claude asks about your goal and targets (defaults: maintain weight, 2000 kcal). You can change them later in the dashboard's Settings.
|
|
56
|
+
|
|
57
|
+
## Configuration
|
|
58
|
+
|
|
59
|
+
Set these environment variables in an `"env": {}` block next to `"command"`:
|
|
60
|
+
|
|
61
|
+
| Variable | Default | Meaning |
|
|
62
|
+
|---|---|---|
|
|
63
|
+
| `MACROLOG_DB` | `~/.macrolog/macrolog.db` | Path to the database file |
|
|
64
|
+
| `MACROLOG_PORT` | `8765` | Dashboard port |
|
|
65
|
+
| `MACROLOG_DASHBOARD` | `1` | Set to `0` to stop the MCP server from also running the dashboard |
|
|
66
|
+
|
|
67
|
+
## Dashboard
|
|
68
|
+
|
|
69
|
+
The Mac app shows the dashboard in a window. The MCP server also serves it at http://127.0.0.1:8765 whenever the Claude app is open, and `macrolog-dash` starts it on its own. It only accepts connections from `127.0.0.1` and `localhost`.
|
|
70
|
+
|
|
71
|
+
## Backups and export
|
|
72
|
+
|
|
73
|
+
- **Backups:** the first time the MCP server connects each day, it writes a copy of the database to `<db folder>/backups/`. The last 14 copies are kept. To restore, quit the Claude app and copy a backup over the database file.
|
|
74
|
+
- **Export:** Settings → Export (CSV) downloads your meals and items, weights, or targets.
|
|
75
|
+
|
|
76
|
+
## Demo data
|
|
77
|
+
|
|
78
|
+
To try the dashboard without touching your real diary:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
python scripts/seed_demo.py # writes ~/.macrolog/demo.db
|
|
82
|
+
MACROLOG_DB=~/.macrolog/demo.db MACROLOG_PORT=8799 macrolog-dash
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Then open http://127.0.0.1:8799. The script won't write to the real database or overwrite an existing file.
|
|
86
|
+
|
|
87
|
+
## Troubleshooting
|
|
88
|
+
|
|
89
|
+
- Check `mcp.log` and `mcp-server-macrolog.log` in the Claude app's logs folder:
|
|
90
|
+
- macOS: `~/Library/Logs/Claude`
|
|
91
|
+
- Windows: `%APPDATA%\Claude\logs`
|
|
92
|
+
- Linux: `~/.config/Claude/logs`
|
|
93
|
+
- Run `macrolog-mcp` (or `/Applications/Macrolog.app/Contents/MacOS/Macrolog mcp`) in a terminal to see startup errors.
|
|
94
|
+
- If the dashboard doesn't load, port 8765 may already be in use. Set `MACROLOG_PORT` to a different port.
|
|
95
|
+
|
|
96
|
+
## Development
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
python -m venv .venv && source .venv/bin/activate
|
|
100
|
+
pip install -e ".[dev,app]"
|
|
101
|
+
pytest
|
|
102
|
+
pip install pyinstaller && pyinstaller packaging/macrolog.spec # builds dist/Macrolog.app
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Releasing
|
|
106
|
+
|
|
107
|
+
Bump `version` in `pyproject.toml`, commit, then push a matching tag: `git tag v0.2.0 && git push origin v0.2.0`. The release workflow publishes to PyPI and attaches Apple Silicon and Intel builds of Macrolog.app to a GitHub release.
|
|
108
|
+
|
|
109
|
+
One-time setup: on PyPI, add a trusted publisher for this repo (workflow `release.yml`, environment `pypi`), and create an environment named `pypi` in the repo's GitHub settings.
|
|
File without changes
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Macrolog as a desktop window: serves the dashboard on a private port and shows it in a native webview.
|
|
2
|
+
|
|
3
|
+
Its own port means it keeps working when the Claude app (and the dashboard it hosts) quits. Both use the same DB.
|
|
4
|
+
"""
|
|
5
|
+
import logging
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
import webview
|
|
9
|
+
|
|
10
|
+
from . import dashboard
|
|
11
|
+
from . import mcp_server as t
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main():
|
|
15
|
+
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
|
|
16
|
+
t.conn() # migrate and back up before the first request
|
|
17
|
+
port = dashboard.start_in_background(0)
|
|
18
|
+
webview.settings["ALLOW_DOWNLOADS"] = True # CSV export links
|
|
19
|
+
webview.create_window("Macrolog", f"http://127.0.0.1:{port}/", width=1200, height=900, min_size=(420, 500),
|
|
20
|
+
background_color="#121211")
|
|
21
|
+
webview.start()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
if __name__ == "__main__":
|
|
25
|
+
main()
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from datetime import date, datetime, time, timedelta
|
|
2
|
+
|
|
3
|
+
from . import db, timeutil
|
|
4
|
+
|
|
5
|
+
MACROS = ["protein_g", "carbs_g", "fat_g", "fibre_g"]
|
|
6
|
+
WEEKDAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
|
|
7
|
+
HITS = {"gain": {"on target", "over"}, "maintain": {"on target"}, "lose": {"on target", "under"}}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def status(eaten: float, target: float, tolerance_pct: float) -> str:
|
|
11
|
+
t = tolerance_pct / 100
|
|
12
|
+
if eaten < target * (1 - t):
|
|
13
|
+
return "under"
|
|
14
|
+
if eaten > target * (1 + t):
|
|
15
|
+
return "over"
|
|
16
|
+
return "on target"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def is_hit(st: str, goal_mode: str) -> bool:
|
|
20
|
+
return st in HITS[goal_mode]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def eaten_by_day(conn, start: str, end: str) -> dict[str, dict]:
|
|
24
|
+
"""{log_date: {calories, protein_g, ...}} for days in [start, end] that have meals."""
|
|
25
|
+
rows = conn.execute(
|
|
26
|
+
"SELECT m.log_date, SUM(i.calories) calories, SUM(i.protein_g) protein_g, "
|
|
27
|
+
"SUM(i.carbs_g) carbs_g, SUM(i.fat_g) fat_g, SUM(i.fibre_g) fibre_g "
|
|
28
|
+
"FROM meals m JOIN items i ON i.meal_id = m.id "
|
|
29
|
+
"WHERE m.log_date BETWEEN ? AND ? GROUP BY m.log_date", (start, end))
|
|
30
|
+
return {r["log_date"]: dict(r) for r in rows}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _pace(target: float, eaten: float, day: str, settings: dict, at: datetime) -> dict:
|
|
34
|
+
midnight = datetime.combine(date.fromisoformat(day), time())
|
|
35
|
+
mins = (at.replace(tzinfo=None) - midnight).total_seconds() / 60 # >24h after midnight past rollover
|
|
36
|
+
start, end = (timeutil.parse_time(settings[k]) for k in ("eating_start", "eating_end"))
|
|
37
|
+
s, e = start.hour * 60 + start.minute, end.hour * 60 + end.minute
|
|
38
|
+
f = min(max((mins - s) / (e - s), 0), 1)
|
|
39
|
+
expected = target * f
|
|
40
|
+
return {"fraction": f, "expected": expected, "delta": eaten - expected}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _weekly(conn, day: str, settings: dict, eaten_today: float) -> dict:
|
|
44
|
+
d = date.fromisoformat(day)
|
|
45
|
+
first = d - timedelta(days=(d.weekday() - WEEKDAYS.index(settings["week_start"])) % 7)
|
|
46
|
+
week = [(first + timedelta(days=i)).isoformat() for i in range(7)]
|
|
47
|
+
excluded = {r[0] for r in conn.execute(
|
|
48
|
+
"SELECT log_date FROM days WHERE excluded = 1 AND log_date BETWEEN ? AND ?", (week[0], week[-1]))}
|
|
49
|
+
W = [x for x in week if x not in excluded]
|
|
50
|
+
eaten = eaten_by_day(conn, week[0], week[-1])
|
|
51
|
+
week_target = sum(db.target_for(conn, x)["calories"] for x in W)
|
|
52
|
+
done = sum(eaten.get(x, {}).get("calories") or 0 for x in W if x < day)
|
|
53
|
+
days_left = sum(1 for x in W if x >= day)
|
|
54
|
+
today_counted = eaten_today if day in W else 0
|
|
55
|
+
out = {"start": week[0], "end": week[-1], "target": week_target, "done": done,
|
|
56
|
+
"eaten": done + today_counted, "remaining": week_target - done - today_counted,
|
|
57
|
+
"days_left": days_left, "closed": days_left == 0}
|
|
58
|
+
if days_left:
|
|
59
|
+
out["per_day_needed"] = (week_target - done) / days_left
|
|
60
|
+
return out
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def get_budget(conn, day: str | None = None, at: datetime | None = None) -> dict:
|
|
64
|
+
settings = db.get_settings(conn)
|
|
65
|
+
at = at or timeutil.now()
|
|
66
|
+
today = timeutil.today(settings["day_rollover_hour"], at)
|
|
67
|
+
day = day or today
|
|
68
|
+
tgt = db.target_for(conn, day)
|
|
69
|
+
totals = eaten_by_day(conn, day, day).get(day, {})
|
|
70
|
+
eaten = totals.get("calories") or 0
|
|
71
|
+
target = tgt["calories"]
|
|
72
|
+
|
|
73
|
+
daily = {"target": target, "eaten": eaten, "remaining": target - eaten,
|
|
74
|
+
"progress": eaten / target if target else None,
|
|
75
|
+
"status": status(eaten, target, settings["tolerance_pct"])}
|
|
76
|
+
daily["hit"] = is_hit(daily["status"], settings["goal_mode"])
|
|
77
|
+
|
|
78
|
+
macros = {}
|
|
79
|
+
for m in MACROS:
|
|
80
|
+
row = {"eaten": totals.get(m) or 0}
|
|
81
|
+
if tgt[m] is not None:
|
|
82
|
+
row |= {"target": tgt[m], "remaining": tgt[m] - row["eaten"],
|
|
83
|
+
"progress": row["eaten"] / tgt[m] if tgt[m] else None}
|
|
84
|
+
macros[m] = row
|
|
85
|
+
|
|
86
|
+
ml = conn.execute("SELECT COALESCE(SUM(ml), 0) FROM water WHERE log_date = ?", (day,)).fetchone()[0]
|
|
87
|
+
water = {"ml": ml}
|
|
88
|
+
if tgt["water_ml"] is not None:
|
|
89
|
+
water |= {"target": tgt["water_ml"], "remaining": tgt["water_ml"] - ml}
|
|
90
|
+
|
|
91
|
+
out = {"date": day, "is_today": day == today, "daily": daily, "macros": macros, "water": water,
|
|
92
|
+
"weekly": _weekly(conn, day, settings, eaten), "energy_unit": settings["energy_unit"]}
|
|
93
|
+
if day == today:
|
|
94
|
+
out["pace"] = _pace(target, eaten, day, settings, at)
|
|
95
|
+
return out
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
DB_PATH = Path(os.environ.get("MACROLOG_DB", "~/.macrolog/macrolog.db")).expanduser()
|
|
5
|
+
BACKUP_DIR = DB_PATH.parent / "backups"
|
|
6
|
+
PORT = int(os.environ.get("MACROLOG_PORT", "8765"))
|
|
7
|
+
DASHBOARD = os.environ.get("MACROLOG_DASHBOARD", "1") != "0"
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""Dashboard: a Starlette app serving static/ and a JSON API on 127.0.0.1.
|
|
2
|
+
|
|
3
|
+
The API calls the MCP tool functions, so validation and numbers match the chat exactly.
|
|
4
|
+
"""
|
|
5
|
+
import csv
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import socket
|
|
10
|
+
import sys
|
|
11
|
+
import threading
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import uvicorn
|
|
15
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
16
|
+
from starlette.applications import Starlette
|
|
17
|
+
from starlette.concurrency import run_in_threadpool
|
|
18
|
+
from starlette.middleware import Middleware
|
|
19
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
20
|
+
from starlette.requests import Request
|
|
21
|
+
from starlette.responses import JSONResponse, Response
|
|
22
|
+
from starlette.routing import Mount, Route
|
|
23
|
+
from starlette.staticfiles import StaticFiles
|
|
24
|
+
|
|
25
|
+
from . import config, db, stats, timeutil
|
|
26
|
+
from . import mcp_server as t
|
|
27
|
+
|
|
28
|
+
log = logging.getLogger(__name__)
|
|
29
|
+
STATIC = Path(__file__).parent / "static"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _hosts(port: int) -> set[str]:
|
|
33
|
+
return {f"127.0.0.1:{port}", f"localhost:{port}"}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
async def guard(request: Request, call_next):
|
|
37
|
+
"""§8: exact Host allowlist (blocks DNS rebinding); writes need JSON + our own Origin (blocks CSRF)."""
|
|
38
|
+
hosts = _hosts(request.app.state.port)
|
|
39
|
+
if request.headers.get("host") not in hosts:
|
|
40
|
+
return Response("bad host", 403)
|
|
41
|
+
if request.method not in ("GET", "HEAD", "OPTIONS"):
|
|
42
|
+
if request.headers.get("content-type", "").split(";")[0].strip() != "application/json":
|
|
43
|
+
return Response("content-type must be application/json", 415)
|
|
44
|
+
if request.headers.get("origin") not in {f"http://{h}" for h in hosts}:
|
|
45
|
+
return Response("bad origin", 403)
|
|
46
|
+
return await call_next(request)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
async def _call(fn, **kw) -> Response:
|
|
50
|
+
try:
|
|
51
|
+
return Response(await run_in_threadpool(fn, **kw), media_type="application/json")
|
|
52
|
+
except ToolError as e:
|
|
53
|
+
return JSONResponse({"error": str(e)}, 400)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def _body(request: Request) -> dict:
|
|
57
|
+
try:
|
|
58
|
+
body = await request.json()
|
|
59
|
+
except ValueError:
|
|
60
|
+
body = None
|
|
61
|
+
if not isinstance(body, dict):
|
|
62
|
+
raise ToolError("body must be a JSON object")
|
|
63
|
+
return body
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _q(request: Request) -> dict:
|
|
67
|
+
return {k: v for k, v in request.query_params.items() if v != ""}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def rev(request):
|
|
71
|
+
def get():
|
|
72
|
+
with t._lock:
|
|
73
|
+
return db.get_rev(t.conn())
|
|
74
|
+
return JSONResponse({"rev": await run_in_threadpool(get)})
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
async def budget(request):
|
|
78
|
+
return await _call(t.get_budget, **_q(request))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def day(request):
|
|
82
|
+
def streak():
|
|
83
|
+
with t._lock:
|
|
84
|
+
return stats.streak(t.conn(), timeutil.today(t._settings()["day_rollover_hour"]))
|
|
85
|
+
resp = await _call(t.get_day, **_q(request))
|
|
86
|
+
if resp.status_code != 200:
|
|
87
|
+
return resp
|
|
88
|
+
return JSONResponse(json.loads(resp.body) | {"streak": await run_in_threadpool(streak)}) # for the header
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
async def range_(request):
|
|
92
|
+
q = _q(request)
|
|
93
|
+
if q.get("days") == "all":
|
|
94
|
+
def first():
|
|
95
|
+
with t._lock:
|
|
96
|
+
return t.conn().execute("SELECT MIN(log_date) FROM meals").fetchone()[0]
|
|
97
|
+
start = await run_in_threadpool(first)
|
|
98
|
+
if start is None:
|
|
99
|
+
q = {"days": 1}
|
|
100
|
+
else:
|
|
101
|
+
q = {"start": start, "end": timeutil.today(t._settings()["day_rollover_hour"])}
|
|
102
|
+
return await _call(t.get_summary, **q)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
async def settings(request):
|
|
106
|
+
if request.method == "PUT":
|
|
107
|
+
return await _call(t.update_settings, **await _body(request))
|
|
108
|
+
return await _call(t.get_settings)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
async def targets(request):
|
|
112
|
+
return await _call(t.set_targets, **await _body(request))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
async def _span(request, fn) -> Response:
|
|
116
|
+
"""Run stats fn(conn, start, end) for ?start=&end= (the dashboard passes the range it got from /api/range)."""
|
|
117
|
+
q = _q(request)
|
|
118
|
+
try:
|
|
119
|
+
start, end = (timeutil.parse_date(q[k]).isoformat() for k in ("start", "end"))
|
|
120
|
+
except (KeyError, ValueError):
|
|
121
|
+
return JSONResponse({"error": "give start and end as YYYY-MM-DD"}, 400)
|
|
122
|
+
|
|
123
|
+
def run():
|
|
124
|
+
with t._lock:
|
|
125
|
+
return fn(t.conn(), start, end)
|
|
126
|
+
return JSONResponse(await run_in_threadpool(run))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async def weights(request):
|
|
130
|
+
if request.method == "GET":
|
|
131
|
+
return await _span(request, stats.weight_chart)
|
|
132
|
+
return await _call(t.log_weight, **await _body(request))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
async def top_foods(request):
|
|
136
|
+
return await _span(request, stats.top_foods)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
async def days(request):
|
|
140
|
+
return await _call(t.mark_day, date=request.path_params["date"], **await _body(request))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
async def delete_meal(request):
|
|
144
|
+
return await _call(t.delete_meal, meal_id=request.path_params["id"])
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
async def item(request):
|
|
148
|
+
if request.method == "PATCH":
|
|
149
|
+
return await _call(t.update_item, item_id=request.path_params["id"], **await _body(request))
|
|
150
|
+
return await _call(t.delete_item, item_id=request.path_params["id"])
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
async def meals(request):
|
|
154
|
+
return await _call(t.log_meal, **await _body(request))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
async def meal_items(request):
|
|
158
|
+
return await _call(t.add_items, meal_id=request.path_params["id"], **await _body(request))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
async def saved_foods(request):
|
|
162
|
+
return await _call(t.list_saved_foods)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
EXPORTS = {
|
|
166
|
+
"items": "SELECT m.log_date, m.eaten_at, m.meal_type, m.description, i.name, i.quantity, i.calories, i.protein_g, "
|
|
167
|
+
"i.carbs_g, i.fat_g, i.fibre_g, i.source, i.confidence FROM items i JOIN meals m ON m.id = i.meal_id "
|
|
168
|
+
"ORDER BY m.eaten_at, i.id",
|
|
169
|
+
"weights": "SELECT measured_on, kg, note FROM weights ORDER BY measured_on",
|
|
170
|
+
"targets": "SELECT effective_from, calories, protein_g, carbs_g, fat_g, fibre_g, water_ml, note "
|
|
171
|
+
"FROM targets ORDER BY effective_from",
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
async def export_csv(request):
|
|
176
|
+
table = request.query_params.get("table")
|
|
177
|
+
if table not in EXPORTS:
|
|
178
|
+
return JSONResponse({"error": f"table must be one of {', '.join(EXPORTS)}"}, 400)
|
|
179
|
+
|
|
180
|
+
def run():
|
|
181
|
+
with t._lock:
|
|
182
|
+
cur = t.conn().execute(EXPORTS[table])
|
|
183
|
+
out = io.StringIO()
|
|
184
|
+
w = csv.writer(out)
|
|
185
|
+
w.writerow(c[0] for c in cur.description)
|
|
186
|
+
w.writerows(cur)
|
|
187
|
+
return out.getvalue()
|
|
188
|
+
name = f"macrolog-{table}-{timeutil.today(t._settings()['day_rollover_hour'])}.csv"
|
|
189
|
+
return Response(await run_in_threadpool(run), media_type="text/csv",
|
|
190
|
+
headers={"content-disposition": f'attachment; filename="{name}"'})
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
async def bad_body(request, exc):
|
|
194
|
+
return JSONResponse({"error": str(exc)}, 400)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def create_app(port: int = config.PORT) -> Starlette:
|
|
198
|
+
app = Starlette(
|
|
199
|
+
routes=[
|
|
200
|
+
Route("/api/rev", rev),
|
|
201
|
+
Route("/api/budget", budget),
|
|
202
|
+
Route("/api/day", day),
|
|
203
|
+
Route("/api/range", range_),
|
|
204
|
+
Route("/api/settings", settings, methods=["GET", "PUT"]),
|
|
205
|
+
Route("/api/targets", targets, methods=["POST"]),
|
|
206
|
+
Route("/api/weights", weights, methods=["GET", "POST"]),
|
|
207
|
+
Route("/api/top-foods", top_foods),
|
|
208
|
+
Route("/api/days/{date}", days, methods=["POST"]),
|
|
209
|
+
Route("/api/meals", meals, methods=["POST"]),
|
|
210
|
+
Route("/api/meals/{id:int}", delete_meal, methods=["DELETE"]),
|
|
211
|
+
Route("/api/meals/{id:int}/items", meal_items, methods=["POST"]),
|
|
212
|
+
Route("/api/items/{id:int}", item, methods=["PATCH", "DELETE"]),
|
|
213
|
+
Route("/api/saved-foods", saved_foods),
|
|
214
|
+
Route("/api/export.csv", export_csv),
|
|
215
|
+
Mount("/", StaticFiles(directory=STATIC, html=True)),
|
|
216
|
+
],
|
|
217
|
+
middleware=[Middleware(BaseHTTPMiddleware, dispatch=guard)],
|
|
218
|
+
exception_handlers={ToolError: bad_body},
|
|
219
|
+
)
|
|
220
|
+
app.state.port = port
|
|
221
|
+
return app
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _config(port: int) -> uvicorn.Config:
|
|
225
|
+
# log_config=None keeps uvicorn on our stderr logging; its default access log goes to stdout, which is MCP's
|
|
226
|
+
return uvicorn.Config(create_app(port), log_config=None, access_log=False)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _bind(port: int) -> socket.socket:
|
|
230
|
+
sock = socket.socket()
|
|
231
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # quick restarts; still fails if a server is listening
|
|
232
|
+
try:
|
|
233
|
+
sock.bind(("127.0.0.1", port))
|
|
234
|
+
except OSError:
|
|
235
|
+
sock.close()
|
|
236
|
+
raise
|
|
237
|
+
return sock
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def start_in_background(port: int = config.PORT) -> int | None:
|
|
241
|
+
"""Serve the dashboard from a daemon thread and return its port (0 = any free one), or None if the port is taken."""
|
|
242
|
+
try:
|
|
243
|
+
sock = _bind(port)
|
|
244
|
+
except OSError:
|
|
245
|
+
log.info("port %s is in use, not starting the dashboard", port)
|
|
246
|
+
return None
|
|
247
|
+
port = sock.getsockname()[1]
|
|
248
|
+
server = uvicorn.Server(_config(port))
|
|
249
|
+
threading.Thread(target=server.run, kwargs={"sockets": [sock]}, daemon=True, name="dashboard").start()
|
|
250
|
+
log.info("dashboard at http://127.0.0.1:%s", port)
|
|
251
|
+
return port
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def main():
|
|
255
|
+
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
|
|
256
|
+
t.conn()
|
|
257
|
+
uvicorn.Server(_config(config.PORT)).run(sockets=[_bind(config.PORT)])
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
if __name__ == "__main__":
|
|
261
|
+
main()
|