-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
265 lines (224 loc) · 8.56 KB
/
Copy pathserver.py
File metadata and controls
265 lines (224 loc) · 8.56 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import asyncio
import atexit
import json
import logging
import sys
from pathlib import Path
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from ai import AIRequest, handle_ai_request
from sequencer import (
_GM_DRUM_DEFAULTS,
DRUM_MAP,
ChatInterface,
Macro,
Pattern,
_command_registry,
configure_logging,
remap_drum_notes,
)
configure_logging("INFO")
logger = logging.getLogger(__name__)
AUTOSAVE_PATH = Path(__file__).parent / ".autosave.json"
app = FastAPI()
chat = ChatInterface()
# Connected WebSocket clients
clients: set[WebSocket] = set()
def _autosave():
"""Persist current state so it survives reloads."""
try:
project_macros = {n: m.to_dict() for n, m in chat._macros.items() if m.scope == "project"}
data = {
"bpm": chat.seq.bpm,
"steps_per_beat": chat.seq.steps_per_beat,
"patterns": {name: pat.to_dict() for name, pat in chat.seq.patterns.items()},
"drum_map": dict(DRUM_MAP),
"macros": project_macros,
"history": chat._history,
"next_id": chat._next_id,
}
AUTOSAVE_PATH.write_text(json.dumps(data))
logger.debug("Autosaved %d patterns", len(chat.seq.patterns))
except Exception:
logger.error("Autosave failed", exc_info=True)
def _autoload():
"""Restore state from autosave if it exists."""
if not AUTOSAVE_PATH.exists():
return
try:
data = json.loads(AUTOSAVE_PATH.read_text())
chat.seq.bpm = data["bpm"]
chat.seq.steps_per_beat = data.get("steps_per_beat", 4)
chat.seq.patterns.clear()
for name, pat_dict in data["patterns"].items():
chat.seq.patterns[name] = Pattern.from_dict(pat_dict)
DRUM_MAP.clear()
DRUM_MAP.update(data.get("drum_map", _GM_DRUM_DEFAULTS))
remap_drum_notes(chat.seq.patterns)
if "macros" in data:
for name, mdata in data["macros"].items():
macro = Macro.from_dict(mdata)
macro.scope = "project"
chat._macros[name] = macro
if "history" in data:
chat._history = [tuple(h) for h in data["history"]]
chat._next_id = data.get("next_id", 1)
n = len(chat.seq.patterns)
logger.info("Restored %d patterns from autosave (%s BPM)", n, chat.seq.bpm)
except Exception:
logger.error("Autoload failed", exc_info=True)
_autoload()
def _shutdown():
"""Autosave state, close GUIs, stop MIDI, close port."""
logger.info("Shutting down — autosaving and closing MIDI")
_autosave()
chat.seq.close()
atexit.register(_shutdown)
async def broadcast(message: dict):
"""Send a message to all connected WebSocket clients."""
global clients
data = json.dumps(message)
disconnected = set()
for ws in clients:
try:
await ws.send_text(data)
except Exception:
logger.warning("Removing disconnected WebSocket client")
disconnected.add(ws)
clients -= disconnected
_loop = None
@app.on_event("startup")
async def _capture_loop():
global _loop
_loop = asyncio.get_running_loop()
logger.debug("Event loop captured")
def on_sequencer_event(event: dict):
"""Bridge sync sequencer callbacks to async broadcast."""
if _loop is not None:
asyncio.run_coroutine_threadsafe(broadcast(event), _loop)
chat.seq.add_listener(on_sequencer_event)
@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket):
await ws.accept()
clients.add(ws)
logger.info("WebSocket client connected (%d total)", len(clients))
# Send full state on connect
await ws.send_text(json.dumps(chat.seq.get_state()))
try:
while True:
data = await ws.receive_text()
msg = json.loads(data)
if msg.get("type") == "command":
line = msg["line"]
logger.debug("WS command: %s", line)
cmd = line.strip().split()[0].lower() if line.strip() else ""
cont, output = await asyncio.to_thread(chat.handle, line)
if cmd == "load":
await broadcast({"type": "ui", "clear_log": True})
for out_line in output:
await broadcast({"type": "output", "text": out_line})
# Broadcast updated state after command
await broadcast(chat.seq.get_state())
elif msg.get("type") == "macro_save":
name = msg["name"]
commands = [c.strip() for c in msg["commands"] if c.strip()]
params = chat._extract_params(commands)
if name in chat._commands:
await ws.send_text(
json.dumps(
{
"type": "output",
"text": f" '{name}' is a built-in command, choose another name",
}
)
)
elif commands:
existing = chat._macros.get(name)
scope = existing.scope if existing else "project"
chat._macros[name] = Macro(
name=name,
commands=commands,
params=params,
scope=scope,
)
if scope == "global":
chat._save_global_macro(chat._macros[name])
n = len(commands)
await broadcast(
{
"type": "output",
"text": f" ✓ Saved macro '{name}' ({n} commands)",
}
)
await broadcast({"type": "ui", "macro_saved": name})
else:
await broadcast(
{"type": "output", "text": f" Macro '{name}' has no commands, not saved"}
)
except WebSocketDisconnect:
clients.discard(ws)
logger.info("WebSocket client disconnected (%d remaining)", len(clients))
@app.post("/api/ai")
async def ai_translate(req: AIRequest):
logger.info("AI request: %s", req.message[:100])
try:
result = handle_ai_request(chat, req)
except ValueError as e:
logger.error("AI request failed: %s", e)
raise HTTPException(status_code=500, detail=str(e)) from None
await broadcast(chat.seq.get_state())
return result
@app.get("/api/commands")
async def get_commands():
"""Return command registry as JSON for client tab-completion."""
return [
{
"name": c.name,
"category": c.category,
"description": c.description,
"usage": c.usage,
"aliases": c.aliases,
"hint_args": c.hint_args,
"hidden": c.hidden,
}
for c in _command_registry
]
@app.get("/api/session")
async def get_session():
"""Download the current session as JSON."""
project_macros = {n: m.to_dict() for n, m in chat._macros.items() if m.scope == "project"}
return {
"bpm": chat.seq.bpm,
"steps_per_beat": chat.seq.steps_per_beat,
"patterns": {name: pat.to_dict() for name, pat in chat.seq.patterns.items()},
"drum_map": dict(DRUM_MAP),
"macros": project_macros,
}
@app.post("/api/session")
async def load_session(req: dict):
"""Load a session from uploaded JSON."""
chat.seq.bpm = req["bpm"]
chat.seq.steps_per_beat = req.get("steps_per_beat", 4)
chat.seq.patterns.clear()
from sequencer import Pattern
for name, pat_dict in req["patterns"].items():
chat.seq.patterns[name] = Pattern.from_dict(pat_dict)
DRUM_MAP.clear()
DRUM_MAP.update(req.get("drum_map", _GM_DRUM_DEFAULTS))
remap_drum_notes(chat.seq.patterns)
if "macros" in req:
for name, mdata in req["macros"].items():
macro = Macro.from_dict(mdata)
macro.scope = "project"
chat._macros[name] = macro
await broadcast(chat.seq.get_state())
n_pat = len(chat.seq.patterns)
return {"message": f"Loaded {n_pat} patterns, {chat.seq.bpm} BPM"}
# Serve static files — resolve path for both dev and PyInstaller bundle
_base = Path(getattr(sys, "_MEIPASS", Path(__file__).parent))
static_dir = _base / "static"
app.mount("/static", StaticFiles(directory=static_dir), name="static")
@app.get("/")
async def index():
return FileResponse(static_dir / "index.html")