@hyperspell/openclaw-hyperspell 0.4.2 → 0.7.1
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.
- package/README.md +127 -3
- package/client.ts +311 -202
- package/commands/setup.ts +190 -55
- package/commands/wine.ts +164 -0
- package/config.ts +244 -162
- package/graph/cron.ts +364 -0
- package/graph/index.ts +5 -0
- package/graph/ops.ts +253 -0
- package/graph/state.ts +79 -0
- package/graph/tools.ts +117 -0
- package/hooks/auto-context.ts +17 -11
- package/hooks/auto-trace.ts +127 -0
- package/index.ts +123 -95
- package/lib/browser.ts +10 -6
- package/lib/run-script.ts +32 -0
- package/openclaw.plugin.json +110 -74
- package/package.json +6 -2
- package/sommeliagent/references/cross-domain-mappings.md +63 -0
- package/sommeliagent/scripts/auth.py +222 -0
- package/sommeliagent/scripts/history.py +72 -0
- package/sommeliagent/scripts/rate.py +76 -0
- package/sommeliagent/scripts/recommend.py +777 -0
- package/sommeliagent/scripts/test_recommend.py +459 -0
- package/sommeliagent/scripts/wine_db.py +3224 -0
- package/tools/remember.ts +6 -2
- package/tools/search.ts +9 -3
- package/tools/sommelier.ts +254 -0
package/openclaw.plugin.json
CHANGED
|
@@ -1,75 +1,111 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
2
|
+
"id": "openclaw-hyperspell",
|
|
3
|
+
"kind": "memory",
|
|
4
|
+
"uiHints": {
|
|
5
|
+
"apiKey": {
|
|
6
|
+
"label": "Hyperspell API Key",
|
|
7
|
+
"sensitive": true,
|
|
8
|
+
"placeholder": "hs_...",
|
|
9
|
+
"help": "Your API key from app.hyperspell.com (or use ${HYPERSPELL_API_KEY})"
|
|
10
|
+
},
|
|
11
|
+
"userId": {
|
|
12
|
+
"label": "User ID",
|
|
13
|
+
"placeholder": "user_123",
|
|
14
|
+
"help": "User ID (can be your email)",
|
|
15
|
+
"advanced": false
|
|
16
|
+
},
|
|
17
|
+
"autoContext": {
|
|
18
|
+
"label": "Auto-Context",
|
|
19
|
+
"help": "Inject relevant memories before every AI turn",
|
|
20
|
+
"advanced": true
|
|
21
|
+
},
|
|
22
|
+
"autoTrace": {
|
|
23
|
+
"label": "Auto-Trace",
|
|
24
|
+
"help": "Automatically send conversation traces to Hyperspell for memory extraction (procedural, mood) at the end of each session",
|
|
25
|
+
"advanced": true
|
|
26
|
+
},
|
|
27
|
+
"sources": {
|
|
28
|
+
"label": "Sources",
|
|
29
|
+
"placeholder": "notion,slack,google_drive",
|
|
30
|
+
"help": "Comma-separated list of sources to search. Leave empty for all sources.",
|
|
31
|
+
"advanced": true
|
|
32
|
+
},
|
|
33
|
+
"maxResults": {
|
|
34
|
+
"label": "Max Results",
|
|
35
|
+
"placeholder": "10",
|
|
36
|
+
"help": "Maximum memories injected into context per turn",
|
|
37
|
+
"advanced": true
|
|
38
|
+
},
|
|
39
|
+
"debug": {
|
|
40
|
+
"label": "Debug Logging",
|
|
41
|
+
"help": "Enable verbose debug logs for API calls and responses",
|
|
42
|
+
"advanced": true
|
|
43
|
+
},
|
|
44
|
+
"syncMemories": {
|
|
45
|
+
"label": "Sync Memory Files",
|
|
46
|
+
"help": "Automatically sync markdown files in workspace/memory/ to Hyperspell",
|
|
47
|
+
"advanced": true
|
|
48
|
+
},
|
|
49
|
+
"knowledgeGraph": {
|
|
50
|
+
"label": "Memory Network",
|
|
51
|
+
"help": "Extract entities (people, projects, orgs, topics) from memories into structured markdown files. Requires a cron job for periodic scanning.",
|
|
52
|
+
"advanced": true
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
"configSchema": {
|
|
56
|
+
"type": "object",
|
|
57
|
+
"additionalProperties": false,
|
|
58
|
+
"properties": {
|
|
59
|
+
"apiKey": {
|
|
60
|
+
"type": "string"
|
|
61
|
+
},
|
|
62
|
+
"userId": {
|
|
63
|
+
"type": "string"
|
|
64
|
+
},
|
|
65
|
+
"autoContext": {
|
|
66
|
+
"type": "boolean"
|
|
67
|
+
},
|
|
68
|
+
"autoTrace": {
|
|
69
|
+
"type": "object",
|
|
70
|
+
"properties": {
|
|
71
|
+
"enabled": { "type": "boolean" },
|
|
72
|
+
"extract": {
|
|
73
|
+
"type": "array",
|
|
74
|
+
"items": {
|
|
75
|
+
"type": "string",
|
|
76
|
+
"enum": ["procedure", "memory", "mood"]
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
"metadata": { "type": "object" }
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
"sources": {
|
|
83
|
+
"type": "string"
|
|
84
|
+
},
|
|
85
|
+
"maxResults": {
|
|
86
|
+
"type": "number",
|
|
87
|
+
"minimum": 1,
|
|
88
|
+
"maximum": 20
|
|
89
|
+
},
|
|
90
|
+
"debug": {
|
|
91
|
+
"type": "boolean"
|
|
92
|
+
},
|
|
93
|
+
"syncMemories": {
|
|
94
|
+
"type": "boolean"
|
|
95
|
+
},
|
|
96
|
+
"knowledgeGraph": {
|
|
97
|
+
"type": "object",
|
|
98
|
+
"properties": {
|
|
99
|
+
"enabled": { "type": "boolean" },
|
|
100
|
+
"scanIntervalMinutes": {
|
|
101
|
+
"type": "number",
|
|
102
|
+
"minimum": 5,
|
|
103
|
+
"maximum": 1440
|
|
104
|
+
},
|
|
105
|
+
"batchSize": { "type": "number", "minimum": 5, "maximum": 100 }
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
"required": []
|
|
110
|
+
}
|
|
111
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyperspell/openclaw-hyperspell",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "OpenClaw Hyperspell memory plugin",
|
|
6
6
|
"license": "MIT",
|
|
@@ -11,8 +11,10 @@
|
|
|
11
11
|
"hooks/",
|
|
12
12
|
"tools/",
|
|
13
13
|
"sync/",
|
|
14
|
+
"graph/",
|
|
14
15
|
"lib/",
|
|
15
16
|
"types/",
|
|
17
|
+
"sommeliagent/",
|
|
16
18
|
"openclaw.plugin.json",
|
|
17
19
|
"README.md"
|
|
18
20
|
],
|
|
@@ -26,7 +28,9 @@
|
|
|
26
28
|
"memory",
|
|
27
29
|
"rag",
|
|
28
30
|
"ai",
|
|
29
|
-
"plugin"
|
|
31
|
+
"plugin",
|
|
32
|
+
"sommelier",
|
|
33
|
+
"wine"
|
|
30
34
|
],
|
|
31
35
|
"dependencies": {
|
|
32
36
|
"@clack/prompts": "^1.0.0",
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# Cross-Domain Mapping: Music → Wine
|
|
2
|
+
|
|
3
|
+
The core thesis: sensory and aesthetic preferences transfer across domains. Someone who seeks complexity in music seeks complexity in wine. Someone drawn to dark, brooding sounds wants wines with tension and structure, not crowd-pleasers.
|
|
4
|
+
|
|
5
|
+
## Music → Wine Dimension Map
|
|
6
|
+
|
|
7
|
+
| Music Signal | Wine Dimension | Logic |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| Tempo / energy | Body / weight | High energy → bold, full-bodied; ambient → light, delicate |
|
|
10
|
+
| Complexity (jazz, prog, classical) | Complexity (terroir-driven, natural wines) | Listeners who tolerate/seek complexity want wines that challenge |
|
|
11
|
+
| Valence (happy vs dark) | Sweetness / dryness spectrum | Bright pop → approachable, off-dry; minor key → dry, tannic, austere |
|
|
12
|
+
| Acoustic vs electronic | Old World vs New World | Organic, analog sound → traditional winemaking; synthetic → modern, tech-forward wines |
|
|
13
|
+
| Obscurity / niche taste | Obscurity of region/varietal | Niche listeners don't want grocery store Cab Sav |
|
|
14
|
+
| Repetition tolerance | Familiarity preference | Loop-heavy listeners → reliable house pours; variety seekers → discovery |
|
|
15
|
+
| Lyrical depth | Label story / terroir narrative | People who care about lyrics care about provenance |
|
|
16
|
+
|
|
17
|
+
## Mapping Algorithm
|
|
18
|
+
|
|
19
|
+
### Step 1: Music Profile Aggregation
|
|
20
|
+
|
|
21
|
+
From Spotify's audio features API, we aggregate across a user's top 50 tracks:
|
|
22
|
+
- **avgValence** (0-1): musical positiveness
|
|
23
|
+
- **avgEnergy** (0-1): intensity and activity
|
|
24
|
+
- **avgDanceability** (0-1): dance suitability
|
|
25
|
+
- **avgAcousticness** (0-1): acoustic vs electronic
|
|
26
|
+
- **avgTempo** (BPM): normalized to 0-1 range (/200)
|
|
27
|
+
- **avgComplexity** (derived): instrumentalness × 0.3 + time signature variety × 0.3 + (1 - danceability) × 0.4
|
|
28
|
+
- **obscurityScore** (derived): 1 - (average track popularity / 100)
|
|
29
|
+
|
|
30
|
+
### Step 2: Wine Dimension Translation
|
|
31
|
+
|
|
32
|
+
Each wine dimension is a weighted average of music features:
|
|
33
|
+
|
|
34
|
+
**Body** = energy × 0.5 + tempo × 0.3 + (1 - acousticness) × 0.2
|
|
35
|
+
**Sweetness** = valence × 0.6 + danceability × 0.3 + (1 - complexity) × 0.1
|
|
36
|
+
**Tannin** = (1 - valence) × 0.4 + complexity × 0.3 + energy × 0.3
|
|
37
|
+
**Acidity** = complexity × 0.4 + (1 - valence) × 0.3 + obscurity × 0.3
|
|
38
|
+
**Complexity** = complexity × 0.5 + obscurity × 0.3 + (1 - danceability) × 0.2
|
|
39
|
+
**Fruitiness** = valence × 0.5 + energy × 0.3 + (1 - complexity) × 0.2
|
|
40
|
+
**Earthiness** = acousticness × 0.4 + complexity × 0.3 + obscurity × 0.3
|
|
41
|
+
**Spiciness** = energy × 0.4 + (1 - valence) × 0.3 + complexity × 0.3
|
|
42
|
+
|
|
43
|
+
### Step 3: Wine Scoring
|
|
44
|
+
|
|
45
|
+
Each wine in the database has a profile with the same 8 dimensions. Match score = weighted cosine similarity between target profile and wine profile.
|
|
46
|
+
|
|
47
|
+
Weights: body (1.5), sweetness (1.2), complexity (1.5), tannin (1.0), acidity (1.0), fruitiness (0.8), earthiness (0.8), spiciness (0.7).
|
|
48
|
+
|
|
49
|
+
### Step 4: Connection Generation
|
|
50
|
+
|
|
51
|
+
For each recommended wine, the system identifies which specific music-wine connections are strongest and generates explanations.
|
|
52
|
+
|
|
53
|
+
## Expansion Signals (Future)
|
|
54
|
+
|
|
55
|
+
- **Reading history** → intellectual complexity tolerance
|
|
56
|
+
- **Food delivery** → direct cuisine/region pairing data
|
|
57
|
+
- **Time of day / mood** → contextual recommendations
|
|
58
|
+
- **Weather + location** → seasonal suggestions
|
|
59
|
+
- **Instagram aesthetic** → visual preference → label/winemaking philosophy
|
|
60
|
+
|
|
61
|
+
## Philosophy
|
|
62
|
+
|
|
63
|
+
The signal doesn't need to be scientifically rigorous. This is entertainment that gets smarter. The delight is in the explanation, not the accuracy. The feedback loop (ratings) quietly builds a genuine cross-domain taste database over time.
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# /// script
|
|
2
|
+
# requires-python = ">=3.11"
|
|
3
|
+
# dependencies = ["httpx"]
|
|
4
|
+
# ///
|
|
5
|
+
"""
|
|
6
|
+
Spotify OAuth flow for SommeliAgent.
|
|
7
|
+
Opens browser, runs local callback server, saves token.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import html
|
|
11
|
+
import http.server
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import secrets
|
|
15
|
+
import stat
|
|
16
|
+
import sys
|
|
17
|
+
import threading
|
|
18
|
+
import urllib.parse
|
|
19
|
+
import webbrowser
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
import httpx
|
|
23
|
+
|
|
24
|
+
CONFIG_DIR = Path.home() / ".sommeliagent"
|
|
25
|
+
TOKEN_FILE = CONFIG_DIR / "token.json"
|
|
26
|
+
REDIRECT_URI = "http://localhost:8888/callback"
|
|
27
|
+
SCOPES = "user-top-read user-read-recently-played"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def get_credentials() -> tuple[str, str]:
|
|
31
|
+
client_id = os.environ.get("SPOTIFY_CLIENT_ID", "")
|
|
32
|
+
client_secret = os.environ.get("SPOTIFY_CLIENT_SECRET", "")
|
|
33
|
+
if not client_id or not client_secret:
|
|
34
|
+
print("Error: SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET must be set.", file=sys.stderr)
|
|
35
|
+
print("Get them from https://developer.spotify.com/dashboard", file=sys.stderr)
|
|
36
|
+
sys.exit(1)
|
|
37
|
+
return client_id, client_secret
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def save_token(token_data: dict) -> None:
|
|
41
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
tmp = TOKEN_FILE.with_suffix(".tmp")
|
|
43
|
+
tmp.write_text(json.dumps(token_data, indent=2))
|
|
44
|
+
tmp.chmod(stat.S_IRUSR | stat.S_IWUSR) # 600 — owner only
|
|
45
|
+
tmp.replace(TOKEN_FILE)
|
|
46
|
+
print(f"Token saved to {TOKEN_FILE}")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def load_token() -> dict | None:
|
|
50
|
+
if TOKEN_FILE.exists():
|
|
51
|
+
return json.loads(TOKEN_FILE.read_text())
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def refresh_access_token(refresh_token: str, client_id: str, client_secret: str) -> dict:
|
|
56
|
+
resp = httpx.post(
|
|
57
|
+
"https://accounts.spotify.com/api/token",
|
|
58
|
+
data={
|
|
59
|
+
"grant_type": "refresh_token",
|
|
60
|
+
"refresh_token": refresh_token,
|
|
61
|
+
"client_id": client_id,
|
|
62
|
+
"client_secret": client_secret,
|
|
63
|
+
},
|
|
64
|
+
)
|
|
65
|
+
resp.raise_for_status()
|
|
66
|
+
data = resp.json()
|
|
67
|
+
if "refresh_token" not in data:
|
|
68
|
+
data["refresh_token"] = refresh_token
|
|
69
|
+
return data
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def get_access_token() -> str | None:
|
|
73
|
+
"""Get a valid access token, refreshing if needed. Returns None if unavailable."""
|
|
74
|
+
import time as _time
|
|
75
|
+
|
|
76
|
+
token_data = load_token()
|
|
77
|
+
|
|
78
|
+
if token_data and "refresh_token" in token_data:
|
|
79
|
+
# Return existing token if it hasn't expired yet
|
|
80
|
+
expires_at = token_data.get("expires_at", 0)
|
|
81
|
+
if expires_at and _time.time() < expires_at and token_data.get("access_token"):
|
|
82
|
+
return token_data["access_token"]
|
|
83
|
+
|
|
84
|
+
# Need to refresh — now we need credentials
|
|
85
|
+
client_id, client_secret = get_credentials()
|
|
86
|
+
try:
|
|
87
|
+
refreshed = refresh_access_token(
|
|
88
|
+
token_data["refresh_token"], client_id, client_secret
|
|
89
|
+
)
|
|
90
|
+
expires_in = refreshed.get("expires_in", 3600)
|
|
91
|
+
refreshed["expires_at"] = _time.time() + expires_in
|
|
92
|
+
save_token(refreshed)
|
|
93
|
+
return refreshed["access_token"]
|
|
94
|
+
except Exception as e:
|
|
95
|
+
print(f"Token refresh failed: {e}", file=sys.stderr)
|
|
96
|
+
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _make_callback_handler(expected_state: str):
|
|
101
|
+
"""Create a callback handler that validates the OAuth state parameter."""
|
|
102
|
+
|
|
103
|
+
class CallbackHandler(http.server.BaseHTTPRequestHandler):
|
|
104
|
+
auth_code: str | None = None
|
|
105
|
+
error: str | None = None
|
|
106
|
+
|
|
107
|
+
def do_GET(self):
|
|
108
|
+
query = urllib.parse.urlparse(self.path).query
|
|
109
|
+
params = urllib.parse.parse_qs(query)
|
|
110
|
+
|
|
111
|
+
# Validate state to prevent CSRF
|
|
112
|
+
received_state = params.get("state", [None])[0]
|
|
113
|
+
if received_state != expected_state:
|
|
114
|
+
self.send_response(400)
|
|
115
|
+
self.send_header("Content-Type", "text/html")
|
|
116
|
+
self.end_headers()
|
|
117
|
+
self.wfile.write(b"<html><body><h1>Invalid state parameter</h1></body></html>")
|
|
118
|
+
return
|
|
119
|
+
|
|
120
|
+
if "code" in params:
|
|
121
|
+
CallbackHandler.auth_code = params["code"][0]
|
|
122
|
+
self.send_response(200)
|
|
123
|
+
self.send_header("Content-Type", "text/html")
|
|
124
|
+
self.end_headers()
|
|
125
|
+
self.wfile.write(
|
|
126
|
+
b"<html><body><h1>SommeliAgent connected!</h1>"
|
|
127
|
+
b"<p>You can close this tab and return to your terminal.</p></body></html>"
|
|
128
|
+
)
|
|
129
|
+
elif "error" in params:
|
|
130
|
+
CallbackHandler.error = params["error"][0]
|
|
131
|
+
self.send_response(400)
|
|
132
|
+
self.send_header("Content-Type", "text/html")
|
|
133
|
+
self.end_headers()
|
|
134
|
+
safe_error = html.escape(params["error"][0])
|
|
135
|
+
self.wfile.write(f"<html><body><h1>Error: {safe_error}</h1></body></html>".encode())
|
|
136
|
+
else:
|
|
137
|
+
self.send_response(400)
|
|
138
|
+
self.end_headers()
|
|
139
|
+
|
|
140
|
+
def log_message(self, format, *args):
|
|
141
|
+
pass
|
|
142
|
+
|
|
143
|
+
return CallbackHandler
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def run_oauth_flow() -> None:
|
|
147
|
+
client_id, client_secret = get_credentials()
|
|
148
|
+
state = secrets.token_urlsafe(16)
|
|
149
|
+
|
|
150
|
+
auth_url = (
|
|
151
|
+
"https://accounts.spotify.com/authorize?"
|
|
152
|
+
+ urllib.parse.urlencode(
|
|
153
|
+
{
|
|
154
|
+
"response_type": "code",
|
|
155
|
+
"client_id": client_id,
|
|
156
|
+
"scope": SCOPES,
|
|
157
|
+
"redirect_uri": REDIRECT_URI,
|
|
158
|
+
"state": state,
|
|
159
|
+
}
|
|
160
|
+
)
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
handler_class = _make_callback_handler(state)
|
|
164
|
+
|
|
165
|
+
try:
|
|
166
|
+
server = http.server.HTTPServer(("localhost", 8888), handler_class)
|
|
167
|
+
except OSError as e:
|
|
168
|
+
print(f"Error: Could not start callback server on port 8888: {e}", file=sys.stderr)
|
|
169
|
+
print("Make sure nothing else is using that port.", file=sys.stderr)
|
|
170
|
+
sys.exit(1)
|
|
171
|
+
|
|
172
|
+
# Handle up to 3 requests (in case of preflight/favicon/etc hitting first)
|
|
173
|
+
def serve():
|
|
174
|
+
for _ in range(3):
|
|
175
|
+
server.handle_request()
|
|
176
|
+
if handler_class.auth_code or handler_class.error:
|
|
177
|
+
break
|
|
178
|
+
|
|
179
|
+
server_thread = threading.Thread(target=serve, daemon=True)
|
|
180
|
+
server_thread.start()
|
|
181
|
+
|
|
182
|
+
print("Opening Spotify authorization in your browser...")
|
|
183
|
+
print(f"If it doesn't open, visit: {auth_url}")
|
|
184
|
+
webbrowser.open(auth_url)
|
|
185
|
+
|
|
186
|
+
server_thread.join(timeout=120)
|
|
187
|
+
server.server_close()
|
|
188
|
+
|
|
189
|
+
if handler_class.error:
|
|
190
|
+
print(f"Error: Spotify returned: {handler_class.error}", file=sys.stderr)
|
|
191
|
+
sys.exit(1)
|
|
192
|
+
|
|
193
|
+
if not handler_class.auth_code:
|
|
194
|
+
print("Error: No authorization code received (timed out after 120s).", file=sys.stderr)
|
|
195
|
+
sys.exit(1)
|
|
196
|
+
|
|
197
|
+
# Exchange code for token
|
|
198
|
+
resp = httpx.post(
|
|
199
|
+
"https://accounts.spotify.com/api/token",
|
|
200
|
+
data={
|
|
201
|
+
"grant_type": "authorization_code",
|
|
202
|
+
"code": handler_class.auth_code,
|
|
203
|
+
"redirect_uri": REDIRECT_URI,
|
|
204
|
+
"client_id": client_id,
|
|
205
|
+
"client_secret": client_secret,
|
|
206
|
+
},
|
|
207
|
+
)
|
|
208
|
+
resp.raise_for_status()
|
|
209
|
+
token_data = resp.json()
|
|
210
|
+
import time as _time
|
|
211
|
+
token_data["expires_at"] = _time.time() + token_data.get("expires_in", 3600)
|
|
212
|
+
save_token(token_data)
|
|
213
|
+
print("Spotify connected successfully!")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
if __name__ == "__main__":
|
|
217
|
+
token = get_access_token()
|
|
218
|
+
if token:
|
|
219
|
+
print("Already authenticated. Token refreshed successfully.")
|
|
220
|
+
print(f"Token file: {TOKEN_FILE}")
|
|
221
|
+
else:
|
|
222
|
+
run_oauth_flow()
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# /// script
|
|
2
|
+
# requires-python = ">=3.11"
|
|
3
|
+
# dependencies = []
|
|
4
|
+
# ///
|
|
5
|
+
"""
|
|
6
|
+
View SommeliAgent recommendation history and ratings.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
CONFIG_DIR = Path.home() / ".sommeliagent"
|
|
14
|
+
RATINGS_FILE = CONFIG_DIR / "ratings.json"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main():
|
|
18
|
+
if not RATINGS_FILE.exists():
|
|
19
|
+
print("No ratings yet. Try some wines and rate them!")
|
|
20
|
+
sys.exit(0)
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
ratings = json.loads(RATINGS_FILE.read_text())
|
|
24
|
+
except (json.JSONDecodeError, OSError) as e:
|
|
25
|
+
print(f"Error reading ratings file: {e}", file=sys.stderr)
|
|
26
|
+
print(f"You can delete {RATINGS_FILE} to reset.", file=sys.stderr)
|
|
27
|
+
sys.exit(1)
|
|
28
|
+
if not ratings:
|
|
29
|
+
print("No ratings yet. Try some wines and rate them!")
|
|
30
|
+
sys.exit(0)
|
|
31
|
+
|
|
32
|
+
print(f"SommeliAgent — Rating History ({len(ratings)} wines rated)")
|
|
33
|
+
print("=" * 50)
|
|
34
|
+
print()
|
|
35
|
+
|
|
36
|
+
label = {1: "hated it", 2: "not great", 3: "okay", 4: "liked it", 5: "loved it"}
|
|
37
|
+
|
|
38
|
+
for i, entry in enumerate(ratings, 1):
|
|
39
|
+
wine_id = entry.get("wine_id", "unknown")
|
|
40
|
+
rating = max(1, min(5, entry.get("rating", 3)))
|
|
41
|
+
stars = "★" * rating + "☆" * (5 - rating)
|
|
42
|
+
print(f"{i}. {wine_id}")
|
|
43
|
+
print(f" {stars} ({label.get(rating, 'unknown')})")
|
|
44
|
+
if entry.get("notes"):
|
|
45
|
+
print(f" \"{entry['notes']}\"")
|
|
46
|
+
if entry.get("timestamp"):
|
|
47
|
+
print(f" Rated: {entry['timestamp'][:10]}")
|
|
48
|
+
print()
|
|
49
|
+
|
|
50
|
+
# Summary stats
|
|
51
|
+
avg = sum(r.get("rating", 3) for r in ratings) / len(ratings)
|
|
52
|
+
loved = sum(1 for r in ratings if r.get("rating", 3) >= 4)
|
|
53
|
+
print(f"Average rating: {avg:.1f}/5")
|
|
54
|
+
print(f"Wines you loved: {loved}/{len(ratings)}")
|
|
55
|
+
|
|
56
|
+
# Tag preferences
|
|
57
|
+
tag_scores: dict[str, list[int]] = {}
|
|
58
|
+
for r in ratings:
|
|
59
|
+
for tag in r.get("tags", []):
|
|
60
|
+
tag_scores.setdefault(tag, []).append(r.get("rating", 3))
|
|
61
|
+
|
|
62
|
+
if tag_scores:
|
|
63
|
+
print("\nYour taste profile (from ratings):")
|
|
64
|
+
sorted_tags = sorted(tag_scores.items(), key=lambda x: -sum(x[1]) / len(x[1]))
|
|
65
|
+
for tag, scores in sorted_tags[:8]:
|
|
66
|
+
avg_tag = sum(scores) / len(scores)
|
|
67
|
+
bar = "★" * round(avg_tag) + "☆" * (5 - round(avg_tag))
|
|
68
|
+
print(f" {tag:<20} {bar} ({avg_tag:.1f} avg, {len(scores)} wines)")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
if __name__ == "__main__":
|
|
72
|
+
main()
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# /// script
|
|
2
|
+
# requires-python = ">=3.11"
|
|
3
|
+
# dependencies = []
|
|
4
|
+
# ///
|
|
5
|
+
"""
|
|
6
|
+
Rate a wine recommendation to improve future suggestions.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import sys
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from wine_db import WINE_DB
|
|
16
|
+
|
|
17
|
+
CONFIG_DIR = Path.home() / ".sommeliagent"
|
|
18
|
+
RATINGS_FILE = CONFIG_DIR / "ratings.json"
|
|
19
|
+
|
|
20
|
+
# Wine ID → tags mapping (derived from wine_db)
|
|
21
|
+
WINE_TAGS = {w.id: w.tags for w in WINE_DB}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def load_ratings() -> list[dict]:
|
|
25
|
+
if RATINGS_FILE.exists():
|
|
26
|
+
try:
|
|
27
|
+
return json.loads(RATINGS_FILE.read_text())
|
|
28
|
+
except (OSError, json.JSONDecodeError) as e:
|
|
29
|
+
print(f"Warning: could not read {RATINGS_FILE}: {e}", file=sys.stderr)
|
|
30
|
+
return []
|
|
31
|
+
return []
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def save_ratings(ratings: list[dict]) -> None:
|
|
35
|
+
import stat
|
|
36
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
tmp = RATINGS_FILE.with_suffix(".tmp")
|
|
38
|
+
tmp.write_text(json.dumps(ratings, indent=2))
|
|
39
|
+
tmp.chmod(stat.S_IRUSR | stat.S_IWUSR)
|
|
40
|
+
tmp.replace(RATINGS_FILE)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def main():
|
|
44
|
+
parser = argparse.ArgumentParser(description="Rate a wine recommendation")
|
|
45
|
+
parser.add_argument("--wine-id", required=True, help="Wine ID from recommendation")
|
|
46
|
+
parser.add_argument("--rating", type=int, required=True, choices=[1, 2, 3, 4, 5], help="Rating 1-5")
|
|
47
|
+
parser.add_argument("--notes", default="", help="Optional tasting notes")
|
|
48
|
+
args = parser.parse_args()
|
|
49
|
+
|
|
50
|
+
tags = WINE_TAGS.get(args.wine_id)
|
|
51
|
+
if tags is None:
|
|
52
|
+
valid_ids = ", ".join(sorted(WINE_TAGS.keys()))
|
|
53
|
+
print(f"Error: Unknown wine ID '{args.wine_id}'.", file=sys.stderr)
|
|
54
|
+
print(f"Valid IDs: {valid_ids}", file=sys.stderr)
|
|
55
|
+
sys.exit(1)
|
|
56
|
+
|
|
57
|
+
ratings = load_ratings()
|
|
58
|
+
ratings.append({
|
|
59
|
+
"wine_id": args.wine_id,
|
|
60
|
+
"rating": args.rating,
|
|
61
|
+
"notes": args.notes,
|
|
62
|
+
"tags": tags,
|
|
63
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
64
|
+
})
|
|
65
|
+
save_ratings(ratings)
|
|
66
|
+
|
|
67
|
+
label = {1: "hated it", 2: "not great", 3: "okay", 4: "liked it", 5: "loved it"}
|
|
68
|
+
print(f"Rated {args.wine_id}: {args.rating}/5 ({label[args.rating]})")
|
|
69
|
+
if args.notes:
|
|
70
|
+
print(f"Notes: \"{args.notes}\"")
|
|
71
|
+
print(f"Total ratings: {len(ratings)}")
|
|
72
|
+
print("Future recommendations will factor this in.")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
if __name__ == "__main__":
|
|
76
|
+
main()
|