omnipython-apps 0.1.4.dev8__py3-none-any.whl
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.
- apps/__init__.py +5 -0
- apps/about/__init__.py +257 -0
- apps/about/app.json +1 -0
- apps/about/credits.py +12 -0
- apps/about/facts.py +398 -0
- apps/about/fonts/OFL.txt +93 -0
- apps/about/fonts/latin1_14.bin +0 -0
- apps/about/fonts/latin1_16.bin +0 -0
- apps/about/fonts/latin1_24.bin +0 -0
- apps/about/fonts/latin1_32.bin +0 -0
- apps/about/fonts/latin1_40.bin +0 -0
- apps/backline/__init__.py +58 -0
- apps/backline/app.json +1 -0
- apps/backline/app.py +475 -0
- apps/backline/art.py +717 -0
- apps/backline/ask.py +781 -0
- apps/backline/box.py +502 -0
- apps/backline/cast.py +137 -0
- apps/backline/desk/__init__.py +329 -0
- apps/backline/desk/editor.py +331 -0
- apps/backline/desk/grid.py +154 -0
- apps/backline/desk/look.py +169 -0
- apps/backline/desk/pedals.py +102 -0
- apps/backline/desk/perform.py +157 -0
- apps/backline/desk/prompt.py +210 -0
- apps/backline/desk/strip.py +159 -0
- apps/backline/desk_main.py +226 -0
- apps/backline/engine.py +622 -0
- apps/backline/floor.py +509 -0
- apps/backline/footswitch.py +119 -0
- apps/backline/glyphs.py +82 -0
- apps/backline/kits.py +428 -0
- apps/backline/midipedal.py +362 -0
- apps/backline/page_data.py +413 -0
- apps/backline/parts.py +145 -0
- apps/backline/pedal.py +107 -0
- apps/backline/remote.py +134 -0
- apps/backline/songs/ballad_68.json +1 -0
- apps/backline/songs/bossa.json +1 -0
- apps/backline/songs/country_train.json +1 -0
- apps/backline/songs/funk.json +1 -0
- apps/backline/songs/metal.json +1 -0
- apps/backline/songs/pop.json +1 -0
- apps/backline/songs/rock.json +1 -0
- apps/backline/songs/shuffle.json +1 -0
- apps/battery/__init__.py +101 -0
- apps/battery/app.json +1 -0
- apps/bit_world/act_deck.py +683 -0
- apps/bit_world/act_game.py +762 -0
- apps/bit_world/act_pet.py +1032 -0
- apps/bit_world/app.json +1 -0
- apps/bit_world/bit_output.py +45 -0
- apps/bit_world/bit_palette.py +503 -0
- apps/bit_world/bit_sound.py +431 -0
- apps/bit_world/bit_sprites.py +632 -0
- apps/bit_world/bit_world.py +534 -0
- apps/btreceiver/__init__.py +690 -0
- apps/btreceiver/app.json +1 -0
- apps/btreceiver/chime.py +155 -0
- apps/btreceiver/demo.py +529 -0
- apps/btreceiver/screen.py +633 -0
- apps/camera/__init__.py +316 -0
- apps/camera/app.json +1 -0
- apps/card/__init__.py +113 -0
- apps/card/app.json +1 -0
- apps/cast/__init__.py +631 -0
- apps/cast/app.json +1 -0
- apps/cast/receivers.py +193 -0
- apps/chess/__init__.py +18 -0
- apps/chess/app.json +1 -0
- apps/chess/app.py +922 -0
- apps/chess/art.py +323 -0
- apps/chess/ble.py +411 -0
- apps/chess/engine.py +925 -0
- apps/chess/game.py +327 -0
- apps/chess/net.py +261 -0
- apps/clock/__init__.py +38 -0
- apps/clock/app.json +1 -0
- apps/detect/__init__.py +214 -0
- apps/detect/app.json +1 -0
- apps/fmsynth/__init__.py +41 -0
- apps/fmsynth/algorithms.py +61 -0
- apps/fmsynth/app.json +1 -0
- apps/fmsynth/app.py +355 -0
- apps/fmsynth/editor.py +206 -0
- apps/fmsynth/engine.py +257 -0
- apps/fmsynth/meters.py +262 -0
- apps/fmsynth/midi.py +375 -0
- apps/fmsynth/panel_view.py +1071 -0
- apps/fmsynth/patches/fmsynth-01.syx +0 -0
- apps/fmsynth/settings.py +138 -0
- apps/fmsynth/voice.py +398 -0
- apps/gamepad/__init__.py +685 -0
- apps/gamepad/app.json +1 -0
- apps/gamepad/pad.py +94 -0
- apps/gamepad/watch.py +352 -0
- apps/hidden/__init__.py +72 -0
- apps/hidden/app.json +1 -0
- apps/home/__init__.py +483 -0
- apps/home/app.json +1 -0
- apps/home/main.py +36 -0
- apps/homeassistant/__init__.py +213 -0
- apps/homeassistant/api.py +104 -0
- apps/homeassistant/app.json +1 -0
- apps/huey/__init__.py +287 -0
- apps/huey/acting.py +184 -0
- apps/huey/actor.py +194 -0
- apps/huey/app.json +1 -0
- apps/huey/client.py +125 -0
- apps/huey/servers.py +121 -0
- apps/huey/settings.example.json +8 -0
- apps/huey/settings.py +97 -0
- apps/huey/turn.py +504 -0
- apps/huey/voice.py +217 -0
- apps/info/__init__.py +810 -0
- apps/info/app.json +1 -0
- apps/lora/__init__.py +62 -0
- apps/lora/app.json +1 -0
- apps/manifest.py +71 -0
- apps/medialink_baby_monitor/__init__.py +222 -0
- apps/medialink_baby_monitor/app.json +1 -0
- apps/medialink_doorbell/__init__.py +251 -0
- apps/medialink_doorbell/app.json +1 -0
- apps/medialink_hands_free/__init__.py +217 -0
- apps/medialink_hands_free/app.json +1 -0
- apps/medialink_surveillance_camera/__init__.py +258 -0
- apps/medialink_surveillance_camera/app.json +1 -0
- apps/medialink_video_doorbell/__init__.py +289 -0
- apps/medialink_video_doorbell/app.json +1 -0
- apps/medialink_videophone/__init__.py +273 -0
- apps/medialink_videophone/app.json +1 -0
- apps/medialink_walkie_talkie/__init__.py +228 -0
- apps/medialink_walkie_talkie/app.json +1 -0
- apps/midicontroller/__init__.py +774 -0
- apps/midicontroller/app.json +1 -0
- apps/midicontroller/links.py +421 -0
- apps/midicontroller/surface.py +343 -0
- apps/midiengine/__init__.py +977 -0
- apps/midiengine/app.json +1 -0
- apps/midiengine/banks.py +85 -0
- apps/midiengine/midiin.py +165 -0
- apps/midiengine/player.py +392 -0
- apps/midiengine/umidiparser.py +1413 -0
- apps/mp3/__init__.py +240 -0
- apps/mp3/app.json +1 -0
- apps/perch/__init__.py +119 -0
- apps/perch/app.json +1 -0
- apps/perch/huey.py +481 -0
- apps/perch/huey_props.py +386 -0
- apps/perch/huey_shift.py +42 -0
- apps/perch/huey_views.py +296 -0
- apps/perch/scene_bench.py +680 -0
- apps/perch/scene_coast.py +479 -0
- apps/perch/scene_desk.py +492 -0
- apps/perch/stage.py +1274 -0
- apps/perch/vec.py +366 -0
- apps/repl/__init__.py +325 -0
- apps/repl/app.json +1 -0
- apps/roku/__init__.py +156 -0
- apps/roku/app.json +1 -0
- apps/rokucam/__init__.py +362 -0
- apps/rokucam/app.json +1 -0
- apps/security/__init__.py +261 -0
- apps/security/app.json +1 -0
- apps/settings/__init__.py +221 -0
- apps/settings/app.json +1 -0
- apps/shell/__init__.py +33 -0
- apps/shell/app.json +1 -0
- apps/spotify/__init__.py +669 -0
- apps/spotify/app.json +1 -0
- apps/spotify/screen.py +82 -0
- apps/steps/__init__.py +58 -0
- apps/steps/app.json +1 -0
- apps/stompbox/__init__.py +31 -0
- apps/stompbox/app.json +1 -0
- apps/stompbox/app.py +668 -0
- apps/stompbox/boards.json +20 -0
- apps/stompbox/effects.py +241 -0
- apps/stompbox/engine.py +340 -0
- apps/stompbox/footswitch.py +331 -0
- apps/stompbox/inputs.py +449 -0
- apps/stompbox/meter.py +72 -0
- apps/stompbox/outputs.py +135 -0
- apps/stompbox/pedals.txt +45 -0
- apps/stompbox/presets.py +106 -0
- apps/stompbox/styles.py +135 -0
- apps/stompbox/ui.py +817 -0
- apps/stompbox/wavfile.py +73 -0
- apps/synthstation/__init__.py +20 -0
- apps/synthstation/app.json +1 -0
- apps/synthstation/audio.py +397 -0
- apps/synthstation/catalog.py +50 -0
- apps/synthstation/meters.py +136 -0
- apps/synthstation/midi.py +380 -0
- apps/synthstation/pads.py +177 -0
- apps/synthstation/parts.py +128 -0
- apps/synthstation/station.py +1069 -0
- apps/system/__init__.py +11 -0
- apps/system/app.json +1 -0
- apps/touchcal/__init__.py +324 -0
- apps/touchcal/app.json +1 -0
- apps/touchcal/fit.py +262 -0
- apps/wake/__init__.py +268 -0
- apps/wake/app.json +1 -0
- apps/wake/feed.py +155 -0
- apps/watch/__init__.py +355 -0
- apps/watch/app.json +1 -0
- apps/watch/faces.py +35 -0
- apps/watch/wheel.py +157 -0
- apps/weather/__init__.py +278 -0
- apps/weather/app.json +1 -0
- apps/weather/icons.py +172 -0
- apps/weather/sizing.py +71 -0
- apps/weather/zippad.py +172 -0
- omnipython_apps-0.1.4.dev8.dist-info/METADATA +33 -0
- omnipython_apps-0.1.4.dev8.dist-info/RECORD +218 -0
- omnipython_apps-0.1.4.dev8.dist-info/WHEEL +5 -0
- omnipython_apps-0.1.4.dev8.dist-info/top_level.txt +1 -0
apps/backline/ask.py
ADDED
|
@@ -0,0 +1,781 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""Ask for a groove in words: a chat model writes a song spec, and Backline turns it into a song.
|
|
5
|
+
|
|
6
|
+
"A slow 12-bar blues groove at 72, 4 times through, slowing in the outro"
|
|
7
|
+
goes to any OpenAI-compatible ``chat/completions`` server (`chatclient`),
|
|
8
|
+
which must answer with a song spec: one JSON object, never code. `SCHEMA`
|
|
9
|
+
says what it holds, and `check` holds the answer to it strictly, once
|
|
10
|
+
`fold` has written a form listed over again as ``play.repeat``. An answer
|
|
11
|
+
that doesn't fit is sent back once with what was wrong; a second one that
|
|
12
|
+
doesn't fit fails with what was wrong, and so does a server that is off or
|
|
13
|
+
refuses. A song named in the prompt is a style, a tempo and a feel to
|
|
14
|
+
borrow, never a drum part to copy, and the model is told so.
|
|
15
|
+
|
|
16
|
+
`build` makes the songmodel project from a spec: the parts the spec writes
|
|
17
|
+
as step grids, the parts it leaves out (fills, the outro, an accent) taken
|
|
18
|
+
from the starter song closest in style, and the play plan as the song's
|
|
19
|
+
``repeat`` and ``tempo_map``. `preview` is what a screen shows before
|
|
20
|
+
anyone hears it.
|
|
21
|
+
|
|
22
|
+
The settings are the server's address, a key file and the model, in
|
|
23
|
+
``settings.json`` in the app's data folder (`load_settings`): the same
|
|
24
|
+
three Huey takes, so one lite-assistant or DeepInfra account serves both.
|
|
25
|
+
|
|
26
|
+
Imports on CPython and MicroPython with songmodel; asking imports chatclient. The
|
|
27
|
+
calls block, so the box makes them from a worker.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
import json
|
|
31
|
+
|
|
32
|
+
from songmodel import model
|
|
33
|
+
|
|
34
|
+
#: Every setting and its value when ``settings.json`` doesn't give one.
|
|
35
|
+
DEFAULTS = {
|
|
36
|
+
# an OpenAI-compatible server: the address its /chat/completions is
|
|
37
|
+
# under; "" until it is set, since only you know where your server runs
|
|
38
|
+
"base_url": "",
|
|
39
|
+
# a file holding the API key on one line; "" for a server that asks for none
|
|
40
|
+
"key_file": "/lite-assistant.key",
|
|
41
|
+
# the model that writes the song
|
|
42
|
+
"chat_model": "gemma-4-E2B-it",
|
|
43
|
+
}
|
|
44
|
+
#: Settings the same file holds for the rest of Backline, passed over here:
|
|
45
|
+
#: ``ble``, the name desks find the box by over Bluetooth (`remote.ble_name`).
|
|
46
|
+
OTHERS = ("ble",)
|
|
47
|
+
|
|
48
|
+
#: The parts a spec can write, in the order a song's patterns hold them.
|
|
49
|
+
PARTS = ("intro", "main1", "main2", "fill1", "fill2", "transition", "outro")
|
|
50
|
+
#: A spec's drum names and their General MIDI notes.
|
|
51
|
+
VOICES = (
|
|
52
|
+
("kick", 36), ("snare", 38), ("rim", 37), ("clap", 39), ("closed_hat", 42), ("pedal_hat", 44),
|
|
53
|
+
("open_hat", 46), ("crash", 49), ("ride", 51), ("ride_bell", 53), ("low_tom", 45), ("mid_tom", 47),
|
|
54
|
+
("high_tom", 48), ("floor_tom", 41), ("cowbell", 56), ("tambourine", 54),
|
|
55
|
+
)
|
|
56
|
+
NOTE = dict(VOICES)
|
|
57
|
+
#: What each step character plays at; "." is a rest, and "|" and spaces are only for reading.
|
|
58
|
+
VELOCITY = {"X": 118, "x": 96, "o": 70, "g": 42}
|
|
59
|
+
METERS = ("4/4", "12/8")
|
|
60
|
+
FEELS = ("straight", "swing", "shuffle")
|
|
61
|
+
#: What a kit sounds like, for the model choosing one.
|
|
62
|
+
KIT_NOTES = {
|
|
63
|
+
"rhythm808": "deep electronic kit: hip hop, soul, slow jams",
|
|
64
|
+
"rhythm909": "punchy electronic kit: rock, house, dance",
|
|
65
|
+
"rhythm606": "light, bright electronic kit: country, latin, synth pop",
|
|
66
|
+
"rhythm78": "vintage preset rhythm box: bossa, lounge, ballads",
|
|
67
|
+
"electronic_drums5": "80s electronic kit with big toms: pop, new wave",
|
|
68
|
+
"soundfont": "the default kit, analog-synth drums: rock, pop, funk, anything that suits it",
|
|
69
|
+
}
|
|
70
|
+
TRIES = 2 # the first answer, and one more with what was wrong with it
|
|
71
|
+
#: How much of a bad answer goes back with what was wrong with it.
|
|
72
|
+
ECHO_MOST = 1500
|
|
73
|
+
MAX_TOKENS = 3000
|
|
74
|
+
#: Seconds the server may take to answer: a small model on a computer with no GPU writes a song in minutes.
|
|
75
|
+
TIMEOUT = 600
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class AskError(Exception):
|
|
79
|
+
"""Asking for a song failed: the server, the key or the answer, and why."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def load_settings(path):
|
|
83
|
+
"""The settings: `DEFAULTS`, with what the JSON file at *path* gives over them.
|
|
84
|
+
|
|
85
|
+
Raises:
|
|
86
|
+
ValueError: The file isn't a JSON object, or names a setting there
|
|
87
|
+
isn't, or gives one that isn't text.
|
|
88
|
+
"""
|
|
89
|
+
settings = dict(DEFAULTS)
|
|
90
|
+
try:
|
|
91
|
+
with open(path) as f:
|
|
92
|
+
text = f.read()
|
|
93
|
+
except OSError:
|
|
94
|
+
return settings
|
|
95
|
+
try:
|
|
96
|
+
given = json.loads(text)
|
|
97
|
+
except ValueError:
|
|
98
|
+
raise ValueError("%s isn't JSON" % path)
|
|
99
|
+
if not isinstance(given, dict):
|
|
100
|
+
raise ValueError("%s isn't a JSON object" % path)
|
|
101
|
+
for name in given:
|
|
102
|
+
if name in OTHERS:
|
|
103
|
+
continue
|
|
104
|
+
if name not in DEFAULTS:
|
|
105
|
+
raise ValueError("%s has no setting %r" % (path, name))
|
|
106
|
+
if not isinstance(given[name], str):
|
|
107
|
+
raise ValueError("%s: %r should be text" % (path, name))
|
|
108
|
+
settings[name] = given[name]
|
|
109
|
+
return settings
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# -- the spec ----------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _bars(steps):
|
|
116
|
+
"""A regular expression for one to four bars of *steps* steps, with "|" between them."""
|
|
117
|
+
bar = "[Xxog.]{%d}" % steps
|
|
118
|
+
return "%s(\\|%s){0,3}" % (bar, bar)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def schema(kits):
|
|
122
|
+
"""The JSON Schema a song spec follows, with *kits* the kit names to choose from.
|
|
123
|
+
|
|
124
|
+
It is one of two shapes, a song of 12 steps a bar and a song of 16, so
|
|
125
|
+
a server that holds the model to it holds every grid to the song's
|
|
126
|
+
bar: one to four whole bars, which a small model can then neither
|
|
127
|
+
miscount nor write forever.
|
|
128
|
+
"""
|
|
129
|
+
return {"anyOf": [_song_schema(kits, 16), _song_schema(kits, 12)]}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _song_schema(kits, steps):
|
|
133
|
+
grid = {"type": "string", "pattern": "^%s$" % _bars(steps)}
|
|
134
|
+
voices = {"type": "object", "properties": dict((name, grid) for name, _n in VOICES), "additionalProperties": False}
|
|
135
|
+
return {
|
|
136
|
+
"type": "object",
|
|
137
|
+
"properties": {
|
|
138
|
+
"name": {"type": "string"},
|
|
139
|
+
"style": {"type": "string"},
|
|
140
|
+
"tempo": {"type": "number", "minimum": 40, "maximum": 240},
|
|
141
|
+
"meter": {"type": "string", "enum": list(METERS)},
|
|
142
|
+
"feel": {"type": "string", "enum": list(FEELS)},
|
|
143
|
+
"swing": {"type": "integer", "minimum": 0, "maximum": 60},
|
|
144
|
+
"kit": {"type": "string", "enum": list(kits)},
|
|
145
|
+
"steps": {"type": "integer", "enum": [steps]},
|
|
146
|
+
"form": {"type": "array", "items": {
|
|
147
|
+
"type": "object",
|
|
148
|
+
"properties": {"part": {"type": "string", "enum": list(PARTS)},
|
|
149
|
+
"bars": {"type": "integer", "minimum": 1, "maximum": 16}},
|
|
150
|
+
"required": ["part", "bars"], "additionalProperties": False}},
|
|
151
|
+
"patterns": {"type": "object", "properties": dict((p, voices) for p in PARTS), "additionalProperties": False},
|
|
152
|
+
"play": {"type": "object",
|
|
153
|
+
"properties": {"repeat": {"type": "integer", "minimum": 0, "maximum": 16},
|
|
154
|
+
"outro_tempo": {"type": "number", "minimum": 0, "maximum": 240}},
|
|
155
|
+
"required": ["repeat", "outro_tempo"], "additionalProperties": False},
|
|
156
|
+
},
|
|
157
|
+
"required": ["name", "style", "tempo", "meter", "feel", "swing", "kit", "steps", "form", "patterns", "play"],
|
|
158
|
+
"additionalProperties": False,
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
EXAMPLE = {
|
|
163
|
+
"name": "Straight Rock", "style": "rock", "tempo": 118, "meter": "4/4", "feel": "straight", "swing": 0,
|
|
164
|
+
"kit": "rhythm909", "steps": 16,
|
|
165
|
+
"form": [{"part": "intro", "bars": 1}, {"part": "main1", "bars": 8}, {"part": "fill1", "bars": 1},
|
|
166
|
+
{"part": "outro", "bars": 2}],
|
|
167
|
+
"patterns": {
|
|
168
|
+
"intro": {"closed_hat": "x...x...x...x...", "snare": "........xxXXxxXX", "kick": "X..............."},
|
|
169
|
+
"main1": {"closed_hat": "x.x.x.x.x.x.x.x.", "snare": "....X.......X...",
|
|
170
|
+
"kick": "X.......X.X.....|X.......X.X...x."},
|
|
171
|
+
"fill1": {"snare": "x.x.x.x.XxXxXXXX", "kick": "X.......X......."},
|
|
172
|
+
"outro": {"closed_hat": "x.x.x.x.x.x.x.x.|................", "snare": "....X.......XxXX|................",
|
|
173
|
+
"kick": "X.......X.X.....|X...............", "crash": "................|X..............."},
|
|
174
|
+
},
|
|
175
|
+
"play": {"repeat": 0, "outro_tempo": 0},
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def system_prompt(kits):
|
|
180
|
+
"""What the model is told before the request: the spec, the rules and an example."""
|
|
181
|
+
kit_lines = "\n".join("- %s: %s" % (k, KIT_NOTES.get(k, "a drum kit")) for k in kits)
|
|
182
|
+
return (
|
|
183
|
+
"You write drum grooves for Backline, a drum machine played with a footswitch. "
|
|
184
|
+
"Answer with one JSON object and nothing else: no prose, no code fences, never code.\n\n"
|
|
185
|
+
"The object has these keys, all required:\n"
|
|
186
|
+
"- name: a short title of your own for the groove.\n"
|
|
187
|
+
"- style: the style in a word or two (blues, rock, funk, bossa...).\n"
|
|
188
|
+
"- tempo: beats per minute, 40 to 240. Use the tempo the person asks for exactly.\n"
|
|
189
|
+
"- meter: \"4/4\", or \"12/8\" for a slow triplet ballad.\n"
|
|
190
|
+
"- feel: \"straight\", \"swing\" (swung sixteenths) or \"shuffle\" (triplet feel).\n"
|
|
191
|
+
"- swing: 0 to 60, how late the swung sixteenths are; 0 unless feel is swing.\n"
|
|
192
|
+
"- kit: one of the kits below.\n"
|
|
193
|
+
"- steps: steps in a bar: 12 for a shuffle or 12/8, else 16.\n"
|
|
194
|
+
"- form: the parts in the order they play, each {\"part\": name, \"bars\": n}. Parts: intro, main1, "
|
|
195
|
+
"main2, fill1, fill2, transition, outro. main1 is required. A 12-bar blues has main1 of 12 bars. "
|
|
196
|
+
"fill1 is the fill played in main1, fill2 in main2, transition goes into main2. Each part is in form "
|
|
197
|
+
"once: the song going round more than once is play.repeat, never a part listed again.\n"
|
|
198
|
+
"- patterns: for each part in form, its drums, each a step grid string: one character a step, "
|
|
199
|
+
"X accent, x hit, o soft, g ghost note, . rest. A grid is one bar of exactly steps characters, or two "
|
|
200
|
+
"to four such bars with \"|\" between them, and repeats to fill the part. Drums: %s.\n"
|
|
201
|
+
"- play: {\"repeat\": n, \"outro_tempo\": bpm}. repeat is how many times the song goes through its "
|
|
202
|
+
"main parts before the outro, and 0 loops until the player stops it: \"loop continuously\" is 0, "
|
|
203
|
+
"\"4 times through\" is 4, and when the person doesn't say how many times, 0. outro_tempo is the "
|
|
204
|
+
"tempo the outro slows to by its end: about two thirds of the tempo when the person asks for the end "
|
|
205
|
+
"to slow, and 0, keeping the tempo, when they don't.\n\n"
|
|
206
|
+
"Kits:\n%s\n\n"
|
|
207
|
+
"When the person names a song or an artist, take only its style, tempo and feel, and write an original "
|
|
208
|
+
"groove in that style. Never transcribe or reproduce the drum part of a real recording.\n\n"
|
|
209
|
+
"An example answer:\n%s"
|
|
210
|
+
) % (", ".join(n for n, _p in VOICES), kit_lines, json.dumps(EXAMPLE, separators=(",", ":")))
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
TWICE = ("each part goes in form once, and the song going round again is play.repeat "
|
|
214
|
+
"(\"4 times through\" is play.repeat 4)")
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _grid(text):
|
|
218
|
+
return text.replace("|", "").replace(" ", "")
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def check(spec, kits):
|
|
222
|
+
"""What is wrong with *spec* as a song spec, as a list of sentences; empty when it fits.
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
spec: The parsed answer.
|
|
226
|
+
kits (list): The kit names it may choose from.
|
|
227
|
+
"""
|
|
228
|
+
errors = []
|
|
229
|
+
if not isinstance(spec, dict):
|
|
230
|
+
return ["the answer isn't a JSON object"]
|
|
231
|
+
need = _song_schema(kits, 16)["required"]
|
|
232
|
+
for key in need:
|
|
233
|
+
if key not in spec:
|
|
234
|
+
errors.append("%s is missing" % key)
|
|
235
|
+
for key in spec:
|
|
236
|
+
if key not in need:
|
|
237
|
+
errors.append("%s isn't a key a song has" % key)
|
|
238
|
+
if errors:
|
|
239
|
+
return errors
|
|
240
|
+
|
|
241
|
+
def text(key):
|
|
242
|
+
v = spec[key]
|
|
243
|
+
if not isinstance(v, str) or not v.strip() or len(v) > 60:
|
|
244
|
+
errors.append("%s should be text of 1 to 60 characters" % key)
|
|
245
|
+
|
|
246
|
+
def number(where, v, lo, hi, whole=False):
|
|
247
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)) or (whole and v != int(v)) or not lo <= v <= hi:
|
|
248
|
+
errors.append("%s should be %s from %d to %d, not %r" % (where, "a whole number" if whole else "a number",
|
|
249
|
+
lo, hi, v))
|
|
250
|
+
return False
|
|
251
|
+
return True
|
|
252
|
+
|
|
253
|
+
def one_of(key, choices):
|
|
254
|
+
if spec[key] not in choices:
|
|
255
|
+
errors.append("%s should be one of %s, not %r" % (key, ", ".join(str(c) for c in choices), spec[key]))
|
|
256
|
+
return False
|
|
257
|
+
return True
|
|
258
|
+
|
|
259
|
+
text("name")
|
|
260
|
+
text("style")
|
|
261
|
+
number("tempo", spec["tempo"], 40, 240)
|
|
262
|
+
meter_ok = one_of("meter", METERS)
|
|
263
|
+
feel_ok = one_of("feel", FEELS)
|
|
264
|
+
number("swing", spec["swing"], 0, 60, True)
|
|
265
|
+
one_of("kit", kits)
|
|
266
|
+
steps_ok = one_of("steps", (12, 16))
|
|
267
|
+
if meter_ok and feel_ok and steps_ok:
|
|
268
|
+
want = 12 if spec["meter"] == "12/8" or spec["feel"] == "shuffle" else 16
|
|
269
|
+
if spec["steps"] != want:
|
|
270
|
+
errors.append("steps should be %d for %s %s" % (want, spec["meter"], spec["feel"]))
|
|
271
|
+
steps = spec["steps"] if steps_ok else 16
|
|
272
|
+
|
|
273
|
+
bars = {}
|
|
274
|
+
form = spec["form"]
|
|
275
|
+
if not isinstance(form, list) or not form:
|
|
276
|
+
errors.append("form should be a list of parts")
|
|
277
|
+
form = []
|
|
278
|
+
for i, entry in enumerate(form):
|
|
279
|
+
where = "form[%d]" % i
|
|
280
|
+
if not isinstance(entry, dict) or sorted(entry) != ["bars", "part"]:
|
|
281
|
+
errors.append("%s should be {\"part\": name, \"bars\": n}" % where)
|
|
282
|
+
continue
|
|
283
|
+
if entry["part"] not in PARTS:
|
|
284
|
+
errors.append("%s: part should be one of %s, not %r" % (where, ", ".join(PARTS), entry["part"]))
|
|
285
|
+
continue
|
|
286
|
+
if entry["part"] in bars:
|
|
287
|
+
errors.append("%s: %s is in form twice" % (where, entry["part"]))
|
|
288
|
+
if TWICE not in errors:
|
|
289
|
+
errors.append(TWICE)
|
|
290
|
+
continue
|
|
291
|
+
if number(where + ".bars", entry["bars"], 1, 16, True):
|
|
292
|
+
bars[entry["part"]] = int(entry["bars"])
|
|
293
|
+
if form and "main1" not in bars:
|
|
294
|
+
errors.append("form needs main1")
|
|
295
|
+
if "fill2" in bars and "main2" not in bars:
|
|
296
|
+
errors.append("form has fill2 but no main2")
|
|
297
|
+
|
|
298
|
+
pats = spec["patterns"]
|
|
299
|
+
if not isinstance(pats, dict):
|
|
300
|
+
errors.append("patterns should be an object of parts")
|
|
301
|
+
pats = {}
|
|
302
|
+
for part in pats:
|
|
303
|
+
if part not in PARTS:
|
|
304
|
+
errors.append("patterns.%s isn't a part" % part)
|
|
305
|
+
continue
|
|
306
|
+
if part not in bars:
|
|
307
|
+
errors.append("patterns.%s: %s isn't in form" % (part, part))
|
|
308
|
+
continue
|
|
309
|
+
drums = pats[part]
|
|
310
|
+
if not isinstance(drums, dict) or not drums:
|
|
311
|
+
errors.append("patterns.%s should be an object of drums" % part)
|
|
312
|
+
continue
|
|
313
|
+
hits = bad = 0
|
|
314
|
+
for voice in drums:
|
|
315
|
+
where = "patterns.%s.%s" % (part, voice)
|
|
316
|
+
if voice not in NOTE:
|
|
317
|
+
errors.append("%s: %s isn't a drum (drums: %s)" % (where, voice, ", ".join(n for n, _p in VOICES)))
|
|
318
|
+
bad += 1
|
|
319
|
+
continue
|
|
320
|
+
g = drums[voice]
|
|
321
|
+
if not isinstance(g, str):
|
|
322
|
+
errors.append("%s should be a step grid string" % where)
|
|
323
|
+
bad += 1
|
|
324
|
+
continue
|
|
325
|
+
g = _grid(g)
|
|
326
|
+
wrong = [c for c in g if c not in VELOCITY and c != "."]
|
|
327
|
+
if wrong:
|
|
328
|
+
errors.append("%s has %r, which isn't a step (X x o g .)" % (where, wrong[0]))
|
|
329
|
+
bad += 1
|
|
330
|
+
continue
|
|
331
|
+
n = len(g) // steps if g and len(g) % steps == 0 else 0
|
|
332
|
+
if not n or n > bars[part] or bars[part] % n:
|
|
333
|
+
fits = [str(k * steps) for k in range(1, bars[part] + 1) if bars[part] % k == 0]
|
|
334
|
+
errors.append("%s has %d steps; for %d bar%s of %d steps it should have %s" % (
|
|
335
|
+
where, len(g), bars[part], "" if bars[part] == 1 else "s", steps, " or ".join(fits)))
|
|
336
|
+
bad += 1
|
|
337
|
+
continue
|
|
338
|
+
hits += len(g) - g.count(".")
|
|
339
|
+
if not hits and not bad and part == "main1":
|
|
340
|
+
errors.append("patterns.main1 plays nothing")
|
|
341
|
+
if "main1" in bars and "main1" not in pats:
|
|
342
|
+
errors.append("patterns needs main1, which form lists")
|
|
343
|
+
|
|
344
|
+
play = spec["play"]
|
|
345
|
+
if not isinstance(play, dict) or sorted(play) != ["outro_tempo", "repeat"]:
|
|
346
|
+
errors.append("play should be {\"repeat\": n, \"outro_tempo\": bpm}")
|
|
347
|
+
else:
|
|
348
|
+
number("play.repeat", play["repeat"], 0, 16, True)
|
|
349
|
+
if number("play.outro_tempo", play["outro_tempo"], 0, 240) and 0 < play["outro_tempo"] < 30:
|
|
350
|
+
errors.append("play.outro_tempo should be 0 or 30 to 240, not %r" % play["outro_tempo"])
|
|
351
|
+
return errors
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def fold(spec):
|
|
355
|
+
"""*spec* with the parts its form lists over again folded into ``play.repeat``.
|
|
356
|
+
|
|
357
|
+
A model asked for "four times through" sometimes writes the song's parts
|
|
358
|
+
out again in ``form``. The player only takes each part's length from the
|
|
359
|
+
form: it plays the intro, the mains in order ``play.repeat`` times, then
|
|
360
|
+
the outro, and a fill where the player taps it. So a part listed again
|
|
361
|
+
at the same length can go, and what's left is how many times through:
|
|
362
|
+
|
|
363
|
+
- a ``play.repeat`` of 2 or more already says it, and stays;
|
|
364
|
+
- otherwise, a form that is an intro, the same run of parts some number
|
|
365
|
+
of times and an outro (fills aside) goes through that number of times.
|
|
366
|
+
|
|
367
|
+
A part listed at two lengths, or a form listed over again with nothing
|
|
368
|
+
to say how many times, is left as it is for `check` to say what's wrong.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
spec: The parsed answer.
|
|
372
|
+
|
|
373
|
+
Returns:
|
|
374
|
+
A new spec when there was a form to fold, else *spec* itself.
|
|
375
|
+
"""
|
|
376
|
+
if not isinstance(spec, dict):
|
|
377
|
+
return spec
|
|
378
|
+
form, play = spec.get("form"), spec.get("play")
|
|
379
|
+
if not isinstance(form, list) or not isinstance(play, dict):
|
|
380
|
+
return spec
|
|
381
|
+
if not all(isinstance(e, dict) and sorted(e) == ["bars", "part"] and isinstance(e["part"], str) for e in form):
|
|
382
|
+
return spec
|
|
383
|
+
names = [e["part"] for e in form]
|
|
384
|
+
if len(set(names)) == len(names):
|
|
385
|
+
return spec
|
|
386
|
+
first = {}
|
|
387
|
+
for e in form:
|
|
388
|
+
if first.setdefault(e["part"], e["bars"]) != e["bars"]:
|
|
389
|
+
return spec
|
|
390
|
+
repeat = play.get("repeat")
|
|
391
|
+
if isinstance(repeat, bool) or not isinstance(repeat, int):
|
|
392
|
+
return spec
|
|
393
|
+
if repeat < 2:
|
|
394
|
+
lo, hi = 0, len(names)
|
|
395
|
+
if names[0] == "intro":
|
|
396
|
+
lo = 1
|
|
397
|
+
if hi > lo and names[-1] == "outro":
|
|
398
|
+
hi -= 1
|
|
399
|
+
run = [n for n in names[lo:hi] if n not in ("fill1", "fill2")]
|
|
400
|
+
repeat = 0
|
|
401
|
+
for size in range(1, len(run) // 2 + 1):
|
|
402
|
+
if (len(run) % size == 0 and run[:size] * (len(run) // size) == run and len(set(run[:size])) == size
|
|
403
|
+
and "intro" not in run and "outro" not in run):
|
|
404
|
+
repeat = len(run) // size
|
|
405
|
+
break
|
|
406
|
+
if repeat < 2:
|
|
407
|
+
return spec
|
|
408
|
+
seen = set()
|
|
409
|
+
folded = []
|
|
410
|
+
for e in form:
|
|
411
|
+
if e["part"] not in seen:
|
|
412
|
+
seen.add(e["part"])
|
|
413
|
+
folded.append(e)
|
|
414
|
+
out = dict(spec)
|
|
415
|
+
out["form"] = folded
|
|
416
|
+
out["play"] = dict(play)
|
|
417
|
+
out["play"]["repeat"] = repeat
|
|
418
|
+
return out
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
COUNTS = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9,
|
|
422
|
+
"ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16}
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def times_asked(prompt):
|
|
426
|
+
"""How many times through *prompt* asks for: "four times", "4 times", "twice"; None when it doesn't say.
|
|
427
|
+
|
|
428
|
+
Args:
|
|
429
|
+
prompt (str): The request, in words.
|
|
430
|
+
"""
|
|
431
|
+
words = "".join(c if c.isalpha() or c.isdigit() else " " for c in prompt.lower()).split()
|
|
432
|
+
for i, w in enumerate(words):
|
|
433
|
+
if w == "twice" and words[i + 1:i + 2] != ["as"]:
|
|
434
|
+
return 2
|
|
435
|
+
if w == "once" and words[i + 1:i + 2] == ["through"]:
|
|
436
|
+
return 1
|
|
437
|
+
if w in ("times", "time") and i:
|
|
438
|
+
n = words[i - 1]
|
|
439
|
+
n = int(n) if n.isdigit() else COUNTS.get(n)
|
|
440
|
+
if n and 1 <= n <= 16:
|
|
441
|
+
return n
|
|
442
|
+
return None
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def told(spec, prompt):
|
|
446
|
+
"""*spec* going through as many times as *prompt* asks, when it names a count.
|
|
447
|
+
|
|
448
|
+
Models write "four times through" as a ``play.repeat`` of 3 often enough
|
|
449
|
+
(three more after the first) that the count in the request wins.
|
|
450
|
+
"""
|
|
451
|
+
n = times_asked(prompt)
|
|
452
|
+
if n is None or not isinstance(spec, dict) or not isinstance(spec.get("play"), dict):
|
|
453
|
+
return spec
|
|
454
|
+
if spec["play"].get("repeat") == n:
|
|
455
|
+
return spec
|
|
456
|
+
out = dict(spec)
|
|
457
|
+
out["play"] = dict(spec["play"])
|
|
458
|
+
out["play"]["repeat"] = n
|
|
459
|
+
return out
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def parse(text):
|
|
463
|
+
"""The answer's JSON object: code fences around it are let go, nothing else.
|
|
464
|
+
|
|
465
|
+
Raises:
|
|
466
|
+
ValueError: It isn't JSON.
|
|
467
|
+
"""
|
|
468
|
+
text = text.strip()
|
|
469
|
+
if text.startswith("```"):
|
|
470
|
+
text = text.split("\n", 1)[1] if "\n" in text else ""
|
|
471
|
+
if text.rstrip().endswith("```"):
|
|
472
|
+
text = text.rstrip()[:-3]
|
|
473
|
+
return json.loads(text)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
# -- the song ----------------------------------------------------------------------
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _pattern(bars, steps, drums):
|
|
480
|
+
step = model.BAR // steps
|
|
481
|
+
notes = []
|
|
482
|
+
for voice in drums:
|
|
483
|
+
g = _grid(drums[voice])
|
|
484
|
+
for k in range(bars * steps // len(g)):
|
|
485
|
+
base = k * len(g)
|
|
486
|
+
for i in range(len(g)):
|
|
487
|
+
c = g[i]
|
|
488
|
+
if c in VELOCITY:
|
|
489
|
+
notes.append([(base + i) * step, step, NOTE[voice], VELOCITY[c]])
|
|
490
|
+
notes.sort()
|
|
491
|
+
return {"bars": bars, "notes": notes}
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _grid_of(project):
|
|
495
|
+
"""12 for a starter whose notes fall on triplet steps, else 16."""
|
|
496
|
+
for p in project["tracks"][0]["patterns"]:
|
|
497
|
+
for n in p["notes"]:
|
|
498
|
+
if n[0] % (model.BAR // 16):
|
|
499
|
+
return 12
|
|
500
|
+
return 16
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def closest(spec, starters):
|
|
504
|
+
"""The starter song most like *spec*: its meter, then its grid, then its style, then its tempo.
|
|
505
|
+
|
|
506
|
+
Args:
|
|
507
|
+
starters (list): ``[(name, project)]``.
|
|
508
|
+
"""
|
|
509
|
+
steps = spec["steps"]
|
|
510
|
+
style = spec["style"].lower()
|
|
511
|
+
best = None
|
|
512
|
+
for name, p in starters:
|
|
513
|
+
theirs = (p.get("style") or "").lower()
|
|
514
|
+
score = (
|
|
515
|
+
p.get("meter", "4/4") == spec["meter"],
|
|
516
|
+
_grid_of(p) == steps,
|
|
517
|
+
bool(theirs) and (theirs in style or style in theirs),
|
|
518
|
+
-abs(p.get("tempo", 120) - spec["tempo"]),
|
|
519
|
+
)
|
|
520
|
+
if best is None or score > best[0]:
|
|
521
|
+
best = (score, name, p)
|
|
522
|
+
return (best[1], best[2]) if best else (None, None)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def build(spec, starters, prompt=""):
|
|
526
|
+
"""The songmodel project for a checked *spec*, and what came from a starter song.
|
|
527
|
+
|
|
528
|
+
The parts the spec writes become patterns. A main 2 the form names but
|
|
529
|
+
the spec doesn't write plays main 1's groove. Fills, a transition into
|
|
530
|
+
main 2, the outro and the accent hit, where the spec leaves them out,
|
|
531
|
+
are the closest starter's (`closest`), so every pedal gesture has a
|
|
532
|
+
part to play.
|
|
533
|
+
|
|
534
|
+
Args:
|
|
535
|
+
spec (dict): A spec `check` found nothing wrong with.
|
|
536
|
+
starters (list): ``[(name, project)]``, the starter songs.
|
|
537
|
+
prompt (str): What was asked, kept in the song.
|
|
538
|
+
|
|
539
|
+
Returns:
|
|
540
|
+
``(project, filled)``: *filled* names each part taken from a starter.
|
|
541
|
+
"""
|
|
542
|
+
steps = spec["steps"]
|
|
543
|
+
bars = dict((e["part"], int(e["bars"])) for e in spec["form"])
|
|
544
|
+
_name, donor = closest(spec, starters)
|
|
545
|
+
donor_parts = (donor or {}).get("parts") or {}
|
|
546
|
+
donor_pats = donor["tracks"][0]["patterns"] if donor else []
|
|
547
|
+
title = (donor or {}).get("name", "")
|
|
548
|
+
patterns = []
|
|
549
|
+
where = {}
|
|
550
|
+
filled = []
|
|
551
|
+
|
|
552
|
+
def take(part, pattern):
|
|
553
|
+
where[part] = len(patterns)
|
|
554
|
+
patterns.append(pattern)
|
|
555
|
+
|
|
556
|
+
def borrow(part, index):
|
|
557
|
+
if index is None or not 0 <= index < len(donor_pats):
|
|
558
|
+
return
|
|
559
|
+
take(part, json.loads(json.dumps(donor_pats[index])))
|
|
560
|
+
filled.append("%s from %s" % (part, title))
|
|
561
|
+
|
|
562
|
+
def donor_index(part):
|
|
563
|
+
if part == "outro":
|
|
564
|
+
return donor_parts.get("outro")
|
|
565
|
+
if part in ("fill1", "fill2"):
|
|
566
|
+
fills = donor_parts.get("fills") or []
|
|
567
|
+
i = 0 if part == "fill1" else 1
|
|
568
|
+
return fills[i] if i < len(fills) else (fills[0] if fills else None)
|
|
569
|
+
if part == "transition":
|
|
570
|
+
t = donor_parts.get("transitions", donor_parts.get("transition"))
|
|
571
|
+
return (t[0] if t else None) if isinstance(t, list) else t
|
|
572
|
+
return None
|
|
573
|
+
|
|
574
|
+
for part in PARTS:
|
|
575
|
+
drums = spec["patterns"].get(part)
|
|
576
|
+
if drums:
|
|
577
|
+
take(part, _pattern(bars[part], steps, drums))
|
|
578
|
+
elif part == "main2" and part in bars:
|
|
579
|
+
# a second main the spec names but doesn't write plays the first's groove
|
|
580
|
+
mine = spec["patterns"]["main1"]
|
|
581
|
+
if all(bars[part] % max(1, len(g.replace("|", "").replace(" ", "")) // steps) == 0 for g in mine.values()):
|
|
582
|
+
take(part, _pattern(bars[part], steps, mine))
|
|
583
|
+
else:
|
|
584
|
+
take(part, json.loads(json.dumps(patterns[where["main1"]])))
|
|
585
|
+
filled.append("main2 from main1")
|
|
586
|
+
elif part in ("fill1", "outro") or (part in ("fill2", "transition") and "main2" in bars):
|
|
587
|
+
borrow(part, donor_index(part))
|
|
588
|
+
elif part in bars and part == "intro":
|
|
589
|
+
borrow(part, donor_parts.get("intro"))
|
|
590
|
+
accent = donor_parts.get("accent")
|
|
591
|
+
if accent is not None and 0 <= accent < len(donor_pats):
|
|
592
|
+
where["accent"] = len(patterns)
|
|
593
|
+
patterns.append(json.loads(json.dumps(donor_pats[accent])))
|
|
594
|
+
|
|
595
|
+
p = model.new_project()
|
|
596
|
+
p["name"] = spec["name"].strip()[:40]
|
|
597
|
+
p["style"] = spec["style"].strip()[:40]
|
|
598
|
+
p["tempo"] = float(spec["tempo"])
|
|
599
|
+
p["meter"] = spec["meter"]
|
|
600
|
+
p["swing"] = int(spec["swing"]) if spec["feel"] == "swing" else 0
|
|
601
|
+
p["feel"] = spec["feel"]
|
|
602
|
+
t = model.track("drums", spec["kit"], "Drums")
|
|
603
|
+
t["id"] = 1
|
|
604
|
+
t["patterns"] = patterns
|
|
605
|
+
p["tracks"] = [t]
|
|
606
|
+
parts = {"mains": [where[m] for m in ("main1", "main2") if m in where]}
|
|
607
|
+
parts["fills"] = [where[f] for f in ("fill1", "fill2") if f in where][:len(parts["mains"])]
|
|
608
|
+
if "transition" in where and len(parts["mains"]) > 1:
|
|
609
|
+
parts["transitions"] = [where["transition"]]
|
|
610
|
+
for role in ("intro", "outro", "accent"):
|
|
611
|
+
if role in where:
|
|
612
|
+
parts[role] = where[role]
|
|
613
|
+
p["parts"] = parts
|
|
614
|
+
p["repeat"] = int(spec["play"]["repeat"])
|
|
615
|
+
end = spec["play"]["outro_tempo"]
|
|
616
|
+
p["tempo_map"] = [{"part": "outro", "tempo": float(end)}] if end and "outro" in where else []
|
|
617
|
+
p["prompt"] = prompt
|
|
618
|
+
# a part taken from a starter, or main 2 copied from main 1, plays as long as
|
|
619
|
+
# the pattern it got, whatever the spec's form asked for
|
|
620
|
+
p["form"] = [[e["part"], patterns[where[e["part"]]]["bars"] if e["part"] in where else int(e["bars"])]
|
|
621
|
+
for e in spec["form"]]
|
|
622
|
+
return p, filled
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
LABELS = {"intro": "Intro", "main1": "Main 1", "main2": "Main 2", "fill1": "Fill 1", "fill2": "Fill 2",
|
|
626
|
+
"transition": "Transition", "outro": "Outro"}
|
|
627
|
+
SHORT = {"intro": "INTRO", "main1": "MAIN 1", "main2": "MAIN 2", "fill1": "FILL 1", "fill2": "FILL 2",
|
|
628
|
+
"transition": "TRANS", "outro": "OUTRO"}
|
|
629
|
+
ROLE = {"intro": ("intro", None), "main1": ("main", 0), "main2": ("main", 1), "fill1": ("fill", 0),
|
|
630
|
+
"fill2": ("fill", 1), "transition": ("transition", 1), "outro": ("outro", None)}
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def preview(project, filled=(), tries=1, kit_name=None):
|
|
634
|
+
"""What a screen shows of a made song before it plays: small, plain data.
|
|
635
|
+
|
|
636
|
+
``blocks`` is the song's form as the desk's strip draws it, the parts in
|
|
637
|
+
the order the spec gave, with the outro on the end where a starter gave it.
|
|
638
|
+
"""
|
|
639
|
+
patterns = project["tracks"][0]["patterns"]
|
|
640
|
+
parts = project["parts"]
|
|
641
|
+
form = [list(e) for e in project.get("form") or []]
|
|
642
|
+
if "outro" in parts and not any(e[0] == "outro" for e in form):
|
|
643
|
+
form.append(["outro", patterns[parts["outro"]]["bars"]])
|
|
644
|
+
index = {"intro": parts.get("intro"), "outro": parts.get("outro")}
|
|
645
|
+
for i, m in enumerate(parts.get("mains") or []):
|
|
646
|
+
index["main%d" % (i + 1)] = m
|
|
647
|
+
for i, f in enumerate(parts.get("fills") or []):
|
|
648
|
+
index["fill%d" % (i + 1)] = f
|
|
649
|
+
if parts.get("transitions"):
|
|
650
|
+
index["transition"] = parts["transitions"][0]
|
|
651
|
+
blocks = []
|
|
652
|
+
for part, bars in form:
|
|
653
|
+
if index.get(part) is None:
|
|
654
|
+
continue
|
|
655
|
+
role, number = ROLE[part]
|
|
656
|
+
blocks.append({"role": role, "number": number, "pattern": index[part], "bars": bars,
|
|
657
|
+
"label": LABELS[part], "short": SHORT[part]})
|
|
658
|
+
end = model.ramp_to(project, "outro")
|
|
659
|
+
return {
|
|
660
|
+
"name": project.get("name", ""),
|
|
661
|
+
"style": project.get("style", ""),
|
|
662
|
+
"tempo": project["tempo"],
|
|
663
|
+
"meter": project.get("meter", "4/4"),
|
|
664
|
+
"swing": project.get("swing", 0),
|
|
665
|
+
"feel": project.get("feel", "straight"),
|
|
666
|
+
"kit": project["tracks"][0]["instrument"],
|
|
667
|
+
"kit_name": kit_name or project["tracks"][0]["instrument"],
|
|
668
|
+
"repeat": project.get("repeat", 0),
|
|
669
|
+
"outro_tempo": end or 0,
|
|
670
|
+
"blocks": blocks,
|
|
671
|
+
"filled": list(filled),
|
|
672
|
+
"tries": tries,
|
|
673
|
+
"prompt": project.get("prompt", ""),
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def facts_text(p, dot="-"):
|
|
678
|
+
"""The song in a line, from a `preview`: "Blues - 72 BPM - 4/4 - shuffle - Rhythm 808", *dot* between."""
|
|
679
|
+
style = p.get("style", "")
|
|
680
|
+
# str has no capitalize() on MicroPython
|
|
681
|
+
bits = [style[:1].upper() + style[1:], "%d BPM" % int(p.get("tempo", 0) + 0.5), p.get("meter", "4/4")]
|
|
682
|
+
if p.get("swing"):
|
|
683
|
+
bits.append("swing %d%%" % p["swing"])
|
|
684
|
+
elif p.get("feel") not in (None, "straight"):
|
|
685
|
+
bits.append(p["feel"])
|
|
686
|
+
bits.append(p.get("kit_name") or p.get("kit", ""))
|
|
687
|
+
return " ".join([bits[0]] + ["%s %s" % (dot, b) for b in bits[1:] if b])
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def plan_text(p):
|
|
691
|
+
"""The play plan in words, from a `preview`: "4 times through, the outro slowing to 48"."""
|
|
692
|
+
if p.get("repeat"):
|
|
693
|
+
text = "once through" if p["repeat"] == 1 else "%d times through" % p["repeat"]
|
|
694
|
+
else:
|
|
695
|
+
text = "loops until you stop it"
|
|
696
|
+
if p.get("outro_tempo"):
|
|
697
|
+
text += ", the outro slowing to %d" % int(p["outro_tempo"] + 0.5)
|
|
698
|
+
return text
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
# -- asking ------------------------------------------------------------------------
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def _chatclient():
|
|
705
|
+
# imported when a song is asked for, not before: a desk shows songs and
|
|
706
|
+
# never asks, and a browser's Python has no sockets for chatclient.web
|
|
707
|
+
import chatclient
|
|
708
|
+
|
|
709
|
+
return chatclient
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
class Asker:
|
|
713
|
+
"""Asks the server in the settings for songs.
|
|
714
|
+
|
|
715
|
+
Args:
|
|
716
|
+
settings (dict): ``base_url``, ``key_file`` and ``chat_model``.
|
|
717
|
+
kits (list): The kit names a song may choose.
|
|
718
|
+
starters (list): ``[(name, project)]``, for the parts a spec leaves out.
|
|
719
|
+
post: What sends a request; `chatclient.web.post` unless a test gives its own.
|
|
720
|
+
"""
|
|
721
|
+
|
|
722
|
+
def __init__(self, settings, kits, starters, post=None):
|
|
723
|
+
self.settings = settings
|
|
724
|
+
self.kits = list(kits)
|
|
725
|
+
self.starters = starters
|
|
726
|
+
self.post = post
|
|
727
|
+
self.client = None
|
|
728
|
+
#: Every try of the last `ask`: ``{"text", "errors"}``, the answer and what was wrong with it.
|
|
729
|
+
self.log = []
|
|
730
|
+
|
|
731
|
+
def _client(self):
|
|
732
|
+
base = self.settings["base_url"]
|
|
733
|
+
if not base:
|
|
734
|
+
raise AskError("no server to ask: set base_url in Backline's settings.json")
|
|
735
|
+
try:
|
|
736
|
+
key = _chatclient().read_key(self.settings["key_file"])
|
|
737
|
+
except OSError as e:
|
|
738
|
+
raise AskError("no API key: %s (key_file in settings.json, or \"\" for a server that needs none)" % (e,))
|
|
739
|
+
if self.client is None or self.client.base != base.rstrip("/"):
|
|
740
|
+
self.client = _chatclient().Client(base, key, self.post, timeout=TIMEOUT)
|
|
741
|
+
else:
|
|
742
|
+
self.client._key = key
|
|
743
|
+
return self.client
|
|
744
|
+
|
|
745
|
+
def ask(self, prompt):
|
|
746
|
+
"""A song for *prompt*: ``(project, preview)``. Blocks; call it from a worker.
|
|
747
|
+
|
|
748
|
+
Raises:
|
|
749
|
+
AskError: No server or key, the server is off or refused, or the
|
|
750
|
+
answer didn't fit the spec twice, with what was wrong.
|
|
751
|
+
"""
|
|
752
|
+
client = self._client()
|
|
753
|
+
messages = [{"role": "system", "content": system_prompt(self.kits)}, {"role": "user", "content": prompt}]
|
|
754
|
+
self.log = []
|
|
755
|
+
errors = []
|
|
756
|
+
for attempt in range(TRIES):
|
|
757
|
+
try:
|
|
758
|
+
text = client.chat_json(messages, self.settings["chat_model"], schema(self.kits), "song", stream=True,
|
|
759
|
+
max_tokens=MAX_TOKENS, temperature=0.6)
|
|
760
|
+
except _chatclient().ServerError as e:
|
|
761
|
+
raise AskError("the server refused: %s" % (e,))
|
|
762
|
+
except OSError as e:
|
|
763
|
+
raise AskError("can't reach %s: %s" % (self.settings["base_url"], e))
|
|
764
|
+
try:
|
|
765
|
+
spec = parse(text)
|
|
766
|
+
except ValueError as e:
|
|
767
|
+
spec = None
|
|
768
|
+
errors = ["the answer isn't JSON (%s)" % (e,)]
|
|
769
|
+
else:
|
|
770
|
+
spec = told(fold(spec), prompt)
|
|
771
|
+
errors = check(spec, self.kits)
|
|
772
|
+
self.log.append({"text": text, "errors": errors})
|
|
773
|
+
if not errors:
|
|
774
|
+
project, filled = build(spec, self.starters, prompt)
|
|
775
|
+
return project, preview(project, filled, attempt + 1)
|
|
776
|
+
messages = messages + [
|
|
777
|
+
{"role": "assistant", "content": text[:ECHO_MOST]},
|
|
778
|
+
{"role": "user", "content": "That answer can't be used: %s. Send the whole song again as one JSON "
|
|
779
|
+
"object, with those fixed." % "; ".join(errors[:12])},
|
|
780
|
+
]
|
|
781
|
+
raise AskError("the model's song didn't fit, twice: %s" % "; ".join(errors[:6]))
|