Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
438 lines (371 loc) · 17.6 KB
/
Copy pathapp.py
File metadata and controls
438 lines (371 loc) · 17.6 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
"""Interactive TUI: what is playing, a live spectrum, play/pause/next, and a mood prompt.
The player is usually the background player (`client.PlayerClient`), so `b` leaves with the music still playing and
`q` stops it; an in-process `Player` works the same way, except that it always stops with the app.
The mood is interpreted by Gentle Shell in a thread worker while the music keeps playing; the new style starts at
the next bar. Everything shown comes from `player.now`, i.e. the bar that is audible right now. What is audible can
be saved under a name and applied later, instantly, without asking Gentle Shell again.
"""
from __future__ import annotations
from rich.text import Text
from textual import work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.markup import escape
from textual.containers import Vertical
from textual.screen import ModalScreen
from textual.theme import Theme
from textual.widgets import Footer, Header, Input, OptionList, Static
from textual.widgets.option_list import Option
from textual.worker import get_current_worker
from .bridge import GentleShell, InterpretError, Usage
from .player import Player
from .presets import NAME_MAX, Preset, PresetError, PresetStore, normalize_name
from .style import Style
DEFAULT_MODEL_LABEL = "Gentle Shell default"
BLOCKS = " ▁▂▃▄▅▆▇█"
# gentlemanprogramming.com palette
GENTLEMAN_THEME = Theme(
name="gentleman",
primary="#ff76c3", # rose
secondary="#f095c8",
accent="#ffb1dd", # pink
foreground="#f6eff3",
background="#140a12",
surface="#241822",
panel="#342230",
success="#b4e7c7",
warning="#f2b86d", # peach
error="#ff718f",
dark=True,
variables={
"text-muted": "#a78e9b",
"border": "#ff76c3",
"border-blurred": "#342230",
"block-cursor-foreground": "#140a12",
"block-cursor-background": "#ff76c3",
"block-cursor-blurred-background": "#342230",
"block-hover-background": "#342230",
"input-cursor-background": "#ff76c3",
"input-cursor-foreground": "#140a12",
"input-selection-background": "#ff76c3 30%",
"footer-background": "#1a1218",
"footer-key-foreground": "#ff76c3",
"footer-description-foreground": "#a78e9b",
"scrollbar": "#342230",
"scrollbar-hover": "#76616b",
"scrollbar-active": "#ff76c3",
"scrollbar-background": "#1a1218",
},
)
# spectrum rows, top to bottom: rose peaks over a muted base
SPECTRUM_COLORS = ("#ff76c3", "#f095c8", "#ffb1dd", "#a78e9b", "#76616b")
def model_label(model: str | None) -> str:
return model or DEFAULT_MODEL_LABEL
class Spectrum(Static):
"""Block-character bars filling the widget, one column per log-spaced band, shaded from rose (top) to muted."""
MIN_ROWS = 5
def __init__(self, player: Player, **kw):
super().__init__(**kw)
self.player = player
def tick(self) -> None:
width = max(8, self.size.width or 48)
rows_n = max(self.MIN_ROWS, self.size.height or self.MIN_ROWS)
levels = self.player.spectrum(width) * rows_n * 8
rows = []
for i, r in enumerate(range(rows_n - 1, -1, -1)): # i = 0 is the top row
color = SPECTRUM_COLORS[min(len(SPECTRUM_COLORS) - 1, i * len(SPECTRUM_COLORS) // rows_n)]
cell = (levels - r * 8).clip(0, 8).astype(int)
rows.append(Text("".join(BLOCKS[c] for c in cell), style=color))
self.update(Text("\n").join(rows))
class ModelPicker(ModalScreen[str | None]):
"""Choose the model Gentle Shell uses to interpret moods."""
BINDINGS = [Binding("escape", "dismiss_picker", "Cancel")]
DEFAULT_CSS = """
ModelPicker { align: center middle; }
ModelPicker > Vertical { width: 60; height: auto; max-height: 80%; border: round $primary; padding: 0 1;
background: $surface; }
ModelPicker .heading { color: $primary; text-style: bold; }
ModelPicker #picker-status { color: $text-muted; }
ModelPicker OptionList, ModelPicker OptionList:focus { height: auto; max-height: 20; border: none;
background: $surface; }
"""
def __init__(self, shell: GentleShell):
super().__init__()
self.shell = shell
def compose(self) -> ComposeResult:
with Vertical():
yield Static("Model for mood interpretation", classes="heading")
yield Static("Loading models…", id="picker-status")
yield OptionList(Option(DEFAULT_MODEL_LABEL, id=""), id="models")
def on_mount(self) -> None:
self.query_one(OptionList).focus()
self._load()
@work(thread=True, exclusive=True)
def _load(self) -> None:
try:
models = self.shell.list_models()
except InterpretError as e:
self.app.call_from_thread(self.query_one("#picker-status", Static).update, f"Could not list models: {escape(str(e))}")
return
self.app.call_from_thread(self._show, models)
def _show(self, models: list[str]) -> None:
options = self.query_one(OptionList)
options.add_options([Option(m, id=m) for m in models])
options.highlighted = 0
self.query_one("#picker-status", Static).update(f"{len(models)} models · current: {model_label(self.shell.model)}")
def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
self.dismiss(event.option.id or None)
def action_dismiss_picker(self) -> None:
self.dismiss(self.shell.model)
class SaveDialog(ModalScreen[str | None]):
"""Name the style that is audible now; Enter saves, Esc cancels."""
BINDINGS = [Binding("escape", "cancel", "Cancel")]
DEFAULT_CSS = """
SaveDialog { align: center middle; }
SaveDialog > Vertical { width: 60; height: auto; border: round $primary; padding: 0 1; background: $surface; }
SaveDialog .heading { color: $primary; text-style: bold; }
SaveDialog #save-status { color: $text-muted; }
SaveDialog Input { border: round $panel; background: $surface; }
SaveDialog Input:focus { border: round $primary; }
"""
def __init__(self, name: str):
super().__init__()
self.initial = name
def compose(self) -> ComposeResult:
with Vertical():
yield Static("Save what is playing", classes="heading")
yield Input(self.initial, placeholder="Name", max_length=NAME_MAX, id="save-name")
yield Static("Enter to save · Esc to cancel", id="save-status")
def on_mount(self) -> None:
self.query_one(Input).focus()
def on_input_submitted(self, event: Input.Submitted) -> None:
event.stop() # otherwise it bubbles to the app and is taken as a mood
try:
self.dismiss(normalize_name(event.value))
except PresetError as e:
self.query_one("#save-status", Static).update(f"[$error]{escape(str(e))}[/]")
def action_cancel(self) -> None:
self.dismiss(None)
class PresetPicker(ModalScreen[Preset | None]):
"""Saved prompts: Enter applies the highlighted one, d deletes it, Esc closes."""
BINDINGS = [
Binding("escape", "cancel", "Close"),
Binding("d,delete", "delete", "Delete"),
]
DEFAULT_CSS = """
PresetPicker { align: center middle; }
PresetPicker > Vertical { width: 72; height: auto; max-height: 80%; border: round $primary; padding: 0 1;
background: $surface; }
PresetPicker .heading { color: $primary; text-style: bold; }
PresetPicker #presets-status { color: $text-muted; }
PresetPicker OptionList, PresetPicker OptionList:focus { height: auto; max-height: 20; border: none;
background: $surface; }
"""
EMPTY = "No saved prompts yet — press s to save what is playing"
def __init__(self, store: PresetStore):
super().__init__()
self.store = store
def compose(self) -> ComposeResult:
with Vertical():
yield Static("Saved prompts", classes="heading")
yield Static(id="presets-status")
yield OptionList(id="presets")
def on_mount(self) -> None:
options = self.query_one(OptionList)
options.add_options([Option(Text(f"{p.name} — {p.mood or p.style.summary()}"), id=p.name)
for p in self.store.list()])
if options.option_count:
options.highlighted = 0
self._show_status(self.store.error)
options.focus()
def _show_status(self, error: str | None = None) -> None:
if error:
text = f"[$error]{escape(error)}[/]"
elif self.query_one(OptionList).option_count:
text = "Enter to apply · d to delete · Esc to close"
else:
text = self.EMPTY
self.query_one("#presets-status", Static).update(text)
def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
event.stop()
preset = self.store.get(event.option.id)
if preset is None:
self._show_status(self.store.error or f"“{event.option.id}” is no longer saved.")
return
self.dismiss(preset)
def action_delete(self) -> None:
options = self.query_one(OptionList)
if options.highlighted is None:
return
option = options.get_option_at_index(options.highlighted)
try:
self.store.delete(option.id)
except PresetError as e:
self._show_status(str(e))
return
options.remove_option(option.id)
self._show_status()
def action_cancel(self) -> None:
self.dismiss(None)
class StreamApp(App):
TITLE = "gentle-stream"
SUB_TITLE = "real-time generative music"
AUTO_FOCUS = None
CSS = """
Screen { background: $background; }
Header { background: #1a1218; color: $primary; }
#panel { padding: 1 2; margin: 1 1 0 1; height: 1fr; border: round $panel; background: $surface; }
#title { text-style: bold; color: $primary; }
#details, #model { color: $text-muted; }
#mood-line { color: $accent; text-style: italic; }
#spectrum { height: 1fr; min-height: 5; margin: 1 0; }
#state { color: $text-muted; }
#status { margin-top: 1; }
#mood { dock: bottom; margin: 0 1 1 1; border: round $panel; background: $surface; }
#mood:focus { border: round $primary; }
"""
BINDINGS = [
Binding("space", "toggle", "Play/Pause"),
Binding("n", "next", "Next"),
Binding("slash", "focus_mood", "Mood"),
Binding("m", "pick_model", "Model"),
Binding("s", "save_preset", "Save"),
Binding("p", "pick_preset", "Saved"),
Binding("plus,equals_sign", "volume(5)", "Vol +5"),
Binding("minus", "volume(-5)", "Vol -5"),
Binding("up", "volume(1)", "Vol +1"),
Binding("down", "volume(-1)", "Vol -1"),
Binding("escape", "leave_mood", show=False),
Binding("b", "back", "Back (keeps playing)"),
Binding("q", "quit", "Quit (stops music)"),
]
def __init__(self, player: Player, shell: GentleShell, initial_mood: str | None = None,
presets: PresetStore | None = None):
super().__init__()
self.player, self.shell, self.initial_mood = player, shell, initial_mood
self.presets = presets if presets is not None else PresetStore()
self.session_usage: Usage | None = None # tokens and cost of every successful interpretation so far
self._keep_playing = False # `b` leaves the music playing, `q` stops it
self.register_theme(GENTLEMAN_THEME)
self.theme = GENTLEMAN_THEME.name
def compose(self) -> ComposeResult:
yield Header()
with Vertical(id="panel"):
yield Static(id="title")
yield Static(id="details")
yield Static(id="mood-line")
yield Spectrum(self.player, id="spectrum")
yield Static(id="state")
yield Static(id="model")
yield Static("Press / to describe a mood.", id="status")
yield Input(placeholder="Describe a feeling, a concept, a place… then Enter (Esc to leave)", id="mood")
yield Footer()
def on_mount(self) -> None:
# keep references: the timer also fires while a modal is on top or the app is shutting down,
# when queries would search another screen
self._w = {name: self.query_one(f"#{name}") for name in ("title", "details", "mood-line", "spectrum",
"state", "model", "status")}
self.player.start()
self._show_model()
self._tick()
self.set_interval(1 / 15, self._tick)
if self.initial_mood:
self._request(self.initial_mood)
def on_unmount(self) -> None:
self.shell.cancel() # a running gentle-shell would otherwise keep the process alive after quit
if self._keep_playing:
self.player.detach()
else:
self.player.close()
# ------------------------------------------------------------ display
def _tick(self) -> None:
w = self._w
try:
w["spectrum"].tick() # first: polling a background player also refreshes what is shown below
except ConnectionError: # the background player was stopped elsewhere (`gentle-stream ctl stop`)
self.exit(message="gentle-stream: the music was stopped")
return
now, p = self.player.now, self.player
w["title"].update(f"♪ {now.style.name}")
w["details"].update(now.style.summary())
w["mood-line"].update(f"“{now.style.mood}”" if now.style.mood else "")
state = "[b $success]▶ Playing[/]" if p.playing else "[b $warning]⏸ Paused[/]"
w["state"].update(f"{state} · piece {now.piece} · bar {now.bar + 1} · vol {round(p.volume * 100)}%")
def _show_model(self) -> None:
session = f" · session: {self.session_usage.format()}" if self.session_usage else ""
self._w["model"].update(f"model: {escape(model_label(self.shell.model))}{session}")
def _status(self, text: str) -> None:
self._w["status"].update(text)
# ------------------------------------------------------------ actions
def action_back(self) -> None:
self._keep_playing = True
self.exit()
def action_toggle(self) -> None:
self.player.toggle()
self._tick()
def action_next(self) -> None:
self.player.next()
self._status("Next piece, same mood.")
def action_volume(self, percent: int) -> None:
"""Change the volume by whole percentage points, so repeated steps never drift."""
self.player.set_volume((round(self.player.volume * 100) + percent) / 100)
self._tick()
def action_focus_mood(self) -> None:
self.query_one("#mood", Input).focus()
def action_leave_mood(self) -> None:
self.set_focus(None)
def action_pick_model(self) -> None:
def chosen(model: str | None) -> None:
self.shell.model = model
self._show_model()
self.push_screen(ModelPicker(self.shell), chosen)
# ------------------------------------------------------------ saved prompts
def action_save_preset(self) -> None:
style = self.player.now.style # what is audible, captured before the dialog opens
def named(name: str | None) -> None:
if name is None:
return
try:
preset, replaced = self.presets.save(name, style)
except PresetError as e:
self._status(f"[$error]Could not save:[/] {escape(str(e))}")
return
self._status(f"{'Replaced' if replaced else 'Saved'} “{escape(preset.name)}”")
self.push_screen(SaveDialog(style.name), named)
def action_pick_preset(self) -> None:
def chosen(preset: Preset | None) -> None:
if preset is None:
return
self.workers.cancel_group(self, "interpret") # a late interpretation must not override the choice
self.player.set_style(preset.style)
self._status(f"Up next: [b]{escape(preset.name)}[/b] (saved)")
self.push_screen(PresetPicker(self.presets), chosen)
# ------------------------------------------------------------ mood interpretation
def on_input_submitted(self, event: Input.Submitted) -> None:
mood = event.value.strip()
event.input.value = ""
self.set_focus(None)
if mood:
self._request(mood)
def _request(self, mood: str) -> None:
self._status(f"Interpreting “{mood}” with {model_label(self.shell.model)}…")
self._interpret(mood)
@work(thread=True, exclusive=True, group="interpret")
def _interpret(self, mood: str) -> None:
worker = get_current_worker()
try:
style, usage = self.shell.interpret_with_usage(mood, self.player.style)
except InterpretError as e:
if not worker.is_cancelled:
self.call_from_thread(self._status, f"[$error]Could not interpret the mood:[/] {escape(str(e))}")
return
if worker.is_cancelled:
return
self.player.set_style(style)
self.call_from_thread(self._interpreted, style, usage)
def _interpreted(self, style: Style, usage: Usage | None) -> None:
cost = f" · {usage.format()}" if usage else ""
self._status(f"Up next: [b]{escape(style.name)}[/b] · {escape(style.summary())}{cost}")
if usage:
self.session_usage = usage if self.session_usage is None else self.session_usage + usage
self._show_model()