-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
235 lines (180 loc) · 7.52 KB
/
app.py
File metadata and controls
235 lines (180 loc) · 7.52 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
"""Manifold Visualizer — Flask backend.
Serves manifold generation, presets, and live performance APIs.
Also serves as a fallback when the GPU server is unreachable — nginx
routes to this if the GPU upstream returns 502/503/504.
"""
import os
import re
import subprocess
import sys
from flask import Flask, jsonify, render_template, request
# Add lambda/ to sys.path so we can import from it (can't use 'from lambda.x'
# because 'lambda' is a Python keyword)
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "lambda"))
app = Flask(__name__)
# ---------------------------------------------------------------------------
# Fallback: serve the full app when GPU server is down
# ---------------------------------------------------------------------------
@app.route("/")
def index():
return render_template("index.html")
# Import manifold generators for fallback API
from manifolds import GENERATORS, MANIFOLD_INFO, MANIFOLD_PARAMS
@app.route("/api/manifold/<manifold_type>")
def manifold(manifold_type):
if manifold_type not in GENERATORS:
return jsonify({"error": f"Unknown manifold type: {manifold_type}",
"available": list(GENERATORS.keys())}), 404
resolution = request.args.get("resolution", 30, type=int)
resolution = max(4, min(resolution, 120))
kwargs = {}
param_defs = MANIFOLD_PARAMS.get(manifold_type, {})
for pname, pdef in param_defs.items():
val = request.args.get(pname, type=float)
if val is not None:
kwargs[pname] = val
result = GENERATORS[manifold_type](resolution, **kwargs)
if isinstance(result, dict) and result.get("gpu_fractal"):
result["params"] = {**result.get("params", {}), **kwargs}
result["info"] = MANIFOLD_INFO.get(manifold_type, {})
resp = jsonify(result)
resp.headers["Access-Control-Allow-Origin"] = "*"
return resp
verts, faces, normals, curvature = result
info = MANIFOLD_INFO.get(manifold_type, {})
resp = jsonify({
"type": manifold_type,
"vertices": verts,
"faces": faces,
"normals": normals,
"curvature": curvature,
"params": {"resolution": resolution, **kwargs},
"info": info,
})
resp.headers["Access-Control-Allow-Origin"] = "*"
return resp
@app.route("/api/manifold/<manifold_type>/params")
def manifold_params(manifold_type):
if manifold_type not in GENERATORS:
return jsonify({"error": f"Unknown manifold type: {manifold_type}"}), 404
params = MANIFOLD_PARAMS.get(manifold_type, {})
info = MANIFOLD_INFO.get(manifold_type, {})
return jsonify({"type": manifold_type, "params": params, "info": info})
@app.route("/api/manifolds")
def list_manifolds():
manifolds = {}
for name in GENERATORS:
info = MANIFOLD_INFO.get(name, {})
manifolds[name] = {
"category": info.get("category", "classic"),
"has_params": bool(MANIFOLD_PARAMS.get(name)),
}
return jsonify({"manifolds": manifolds})
# Fallback presets (import from extracted module)
from presets import PresetStore
_preset_store = PresetStore()
@app.route("/api/presets", methods=["GET"])
def list_presets():
return jsonify(_preset_store.list_all())
@app.route("/api/presets/<name>", methods=["GET"])
def get_preset(name):
preset = _preset_store.get(name)
if preset is None:
return jsonify({"error": f"Preset not found: {name}"}), 404
return jsonify(preset)
@app.route("/api/presets", methods=["POST"])
def save_preset():
body = request.get_json()
if not body or "name" not in body:
return jsonify({"error": "Preset must have a 'name' field"}), 400
result, status = _preset_store.save(body)
return jsonify(result), status
@app.route("/api/presets/<name>", methods=["DELETE"])
def delete_preset(name):
result, status = _preset_store.delete(name)
return jsonify(result), status
# ---------------------------------------------------------------------------
# Live Performance — SuperCollider proxy endpoints
# ---------------------------------------------------------------------------
ALLOWED_SYNTHS = {
'dubKick', 'dubSnare', 'dubHat', 'wobbleClassic', 'wobbleGrowl',
'fmBassClassic', 'neuroReese', 'riddimBass', 'riser', 'impact',
'fxSweep', 'dubstepBass', 'padWarm', 'leadSharp',
}
ALLOWED_PARAM_KEYS = {'amp', 'freq', 'dur', 'pan', 'gate', 'attack', 'release', 'sustain', 'decay'}
@app.route("/api/live/trigger", methods=["POST"])
def live_trigger():
"""Trigger a SuperCollider synth via the audio-processing-suite CLI."""
body = request.get_json() or {}
synth = body.get("synth", "dubKick")
if synth not in ALLOWED_SYNTHS:
return jsonify({"error": f"Unknown synth: {synth}"}), 400
params = body.get("params", {})
cmd = ["audio-suite", "system", "osc-send", "/s_new", synth, "1000", "0", "0"]
for k, v in params.items():
if k not in ALLOWED_PARAM_KEYS:
continue
try:
float(v)
cmd.extend([str(k), str(v)])
except (TypeError, ValueError):
continue
try:
subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except FileNotFoundError:
pass
return jsonify({"status": "triggered", "synth": synth})
@app.route("/api/live/pattern", methods=["POST"])
def live_pattern():
"""Control the pattern sequencer."""
body = request.get_json() or {}
action = body.get("action")
if action == "start":
pattern = body.get("pattern", "dubstep_classic")
if not re.match(r'^[a-zA-Z0-9_]+$', pattern):
return jsonify({"error": "Invalid pattern name"}), 400
try:
subprocess.Popen(["audio-suite", "pattern", "quick", pattern],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except FileNotFoundError:
pass
elif action == "stop":
try:
subprocess.Popen(["audio-suite", "pattern", "stop"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except FileNotFoundError:
pass
elif action == "bpm":
bpm = body.get("value", 140)
try:
bpm = int(float(bpm))
bpm = max(40, min(300, bpm))
subprocess.Popen(["audio-suite", "pattern", "bpm", str(bpm)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except (TypeError, ValueError, FileNotFoundError):
pass
return jsonify({"status": "ok", "action": action})
@app.route("/api/live/status")
def live_status():
"""Check SuperCollider connection status."""
try:
result = subprocess.run(
["audio-suite", "system", "status"],
capture_output=True, text=True, timeout=3
)
connected = result.returncode == 0
except (FileNotFoundError, subprocess.TimeoutExpired):
connected = False
return jsonify({"connected": connected})
# ---------------------------------------------------------------------------
# CORS + Cache headers
# ---------------------------------------------------------------------------
@app.after_request
def add_cors(response):
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Headers"] = "Content-Type"
response.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS"
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
return response
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8123, debug=False)