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.
Files changed (218) hide show
  1. apps/__init__.py +5 -0
  2. apps/about/__init__.py +257 -0
  3. apps/about/app.json +1 -0
  4. apps/about/credits.py +12 -0
  5. apps/about/facts.py +398 -0
  6. apps/about/fonts/OFL.txt +93 -0
  7. apps/about/fonts/latin1_14.bin +0 -0
  8. apps/about/fonts/latin1_16.bin +0 -0
  9. apps/about/fonts/latin1_24.bin +0 -0
  10. apps/about/fonts/latin1_32.bin +0 -0
  11. apps/about/fonts/latin1_40.bin +0 -0
  12. apps/backline/__init__.py +58 -0
  13. apps/backline/app.json +1 -0
  14. apps/backline/app.py +475 -0
  15. apps/backline/art.py +717 -0
  16. apps/backline/ask.py +781 -0
  17. apps/backline/box.py +502 -0
  18. apps/backline/cast.py +137 -0
  19. apps/backline/desk/__init__.py +329 -0
  20. apps/backline/desk/editor.py +331 -0
  21. apps/backline/desk/grid.py +154 -0
  22. apps/backline/desk/look.py +169 -0
  23. apps/backline/desk/pedals.py +102 -0
  24. apps/backline/desk/perform.py +157 -0
  25. apps/backline/desk/prompt.py +210 -0
  26. apps/backline/desk/strip.py +159 -0
  27. apps/backline/desk_main.py +226 -0
  28. apps/backline/engine.py +622 -0
  29. apps/backline/floor.py +509 -0
  30. apps/backline/footswitch.py +119 -0
  31. apps/backline/glyphs.py +82 -0
  32. apps/backline/kits.py +428 -0
  33. apps/backline/midipedal.py +362 -0
  34. apps/backline/page_data.py +413 -0
  35. apps/backline/parts.py +145 -0
  36. apps/backline/pedal.py +107 -0
  37. apps/backline/remote.py +134 -0
  38. apps/backline/songs/ballad_68.json +1 -0
  39. apps/backline/songs/bossa.json +1 -0
  40. apps/backline/songs/country_train.json +1 -0
  41. apps/backline/songs/funk.json +1 -0
  42. apps/backline/songs/metal.json +1 -0
  43. apps/backline/songs/pop.json +1 -0
  44. apps/backline/songs/rock.json +1 -0
  45. apps/backline/songs/shuffle.json +1 -0
  46. apps/battery/__init__.py +101 -0
  47. apps/battery/app.json +1 -0
  48. apps/bit_world/act_deck.py +683 -0
  49. apps/bit_world/act_game.py +762 -0
  50. apps/bit_world/act_pet.py +1032 -0
  51. apps/bit_world/app.json +1 -0
  52. apps/bit_world/bit_output.py +45 -0
  53. apps/bit_world/bit_palette.py +503 -0
  54. apps/bit_world/bit_sound.py +431 -0
  55. apps/bit_world/bit_sprites.py +632 -0
  56. apps/bit_world/bit_world.py +534 -0
  57. apps/btreceiver/__init__.py +690 -0
  58. apps/btreceiver/app.json +1 -0
  59. apps/btreceiver/chime.py +155 -0
  60. apps/btreceiver/demo.py +529 -0
  61. apps/btreceiver/screen.py +633 -0
  62. apps/camera/__init__.py +316 -0
  63. apps/camera/app.json +1 -0
  64. apps/card/__init__.py +113 -0
  65. apps/card/app.json +1 -0
  66. apps/cast/__init__.py +631 -0
  67. apps/cast/app.json +1 -0
  68. apps/cast/receivers.py +193 -0
  69. apps/chess/__init__.py +18 -0
  70. apps/chess/app.json +1 -0
  71. apps/chess/app.py +922 -0
  72. apps/chess/art.py +323 -0
  73. apps/chess/ble.py +411 -0
  74. apps/chess/engine.py +925 -0
  75. apps/chess/game.py +327 -0
  76. apps/chess/net.py +261 -0
  77. apps/clock/__init__.py +38 -0
  78. apps/clock/app.json +1 -0
  79. apps/detect/__init__.py +214 -0
  80. apps/detect/app.json +1 -0
  81. apps/fmsynth/__init__.py +41 -0
  82. apps/fmsynth/algorithms.py +61 -0
  83. apps/fmsynth/app.json +1 -0
  84. apps/fmsynth/app.py +355 -0
  85. apps/fmsynth/editor.py +206 -0
  86. apps/fmsynth/engine.py +257 -0
  87. apps/fmsynth/meters.py +262 -0
  88. apps/fmsynth/midi.py +375 -0
  89. apps/fmsynth/panel_view.py +1071 -0
  90. apps/fmsynth/patches/fmsynth-01.syx +0 -0
  91. apps/fmsynth/settings.py +138 -0
  92. apps/fmsynth/voice.py +398 -0
  93. apps/gamepad/__init__.py +685 -0
  94. apps/gamepad/app.json +1 -0
  95. apps/gamepad/pad.py +94 -0
  96. apps/gamepad/watch.py +352 -0
  97. apps/hidden/__init__.py +72 -0
  98. apps/hidden/app.json +1 -0
  99. apps/home/__init__.py +483 -0
  100. apps/home/app.json +1 -0
  101. apps/home/main.py +36 -0
  102. apps/homeassistant/__init__.py +213 -0
  103. apps/homeassistant/api.py +104 -0
  104. apps/homeassistant/app.json +1 -0
  105. apps/huey/__init__.py +287 -0
  106. apps/huey/acting.py +184 -0
  107. apps/huey/actor.py +194 -0
  108. apps/huey/app.json +1 -0
  109. apps/huey/client.py +125 -0
  110. apps/huey/servers.py +121 -0
  111. apps/huey/settings.example.json +8 -0
  112. apps/huey/settings.py +97 -0
  113. apps/huey/turn.py +504 -0
  114. apps/huey/voice.py +217 -0
  115. apps/info/__init__.py +810 -0
  116. apps/info/app.json +1 -0
  117. apps/lora/__init__.py +62 -0
  118. apps/lora/app.json +1 -0
  119. apps/manifest.py +71 -0
  120. apps/medialink_baby_monitor/__init__.py +222 -0
  121. apps/medialink_baby_monitor/app.json +1 -0
  122. apps/medialink_doorbell/__init__.py +251 -0
  123. apps/medialink_doorbell/app.json +1 -0
  124. apps/medialink_hands_free/__init__.py +217 -0
  125. apps/medialink_hands_free/app.json +1 -0
  126. apps/medialink_surveillance_camera/__init__.py +258 -0
  127. apps/medialink_surveillance_camera/app.json +1 -0
  128. apps/medialink_video_doorbell/__init__.py +289 -0
  129. apps/medialink_video_doorbell/app.json +1 -0
  130. apps/medialink_videophone/__init__.py +273 -0
  131. apps/medialink_videophone/app.json +1 -0
  132. apps/medialink_walkie_talkie/__init__.py +228 -0
  133. apps/medialink_walkie_talkie/app.json +1 -0
  134. apps/midicontroller/__init__.py +774 -0
  135. apps/midicontroller/app.json +1 -0
  136. apps/midicontroller/links.py +421 -0
  137. apps/midicontroller/surface.py +343 -0
  138. apps/midiengine/__init__.py +977 -0
  139. apps/midiengine/app.json +1 -0
  140. apps/midiengine/banks.py +85 -0
  141. apps/midiengine/midiin.py +165 -0
  142. apps/midiengine/player.py +392 -0
  143. apps/midiengine/umidiparser.py +1413 -0
  144. apps/mp3/__init__.py +240 -0
  145. apps/mp3/app.json +1 -0
  146. apps/perch/__init__.py +119 -0
  147. apps/perch/app.json +1 -0
  148. apps/perch/huey.py +481 -0
  149. apps/perch/huey_props.py +386 -0
  150. apps/perch/huey_shift.py +42 -0
  151. apps/perch/huey_views.py +296 -0
  152. apps/perch/scene_bench.py +680 -0
  153. apps/perch/scene_coast.py +479 -0
  154. apps/perch/scene_desk.py +492 -0
  155. apps/perch/stage.py +1274 -0
  156. apps/perch/vec.py +366 -0
  157. apps/repl/__init__.py +325 -0
  158. apps/repl/app.json +1 -0
  159. apps/roku/__init__.py +156 -0
  160. apps/roku/app.json +1 -0
  161. apps/rokucam/__init__.py +362 -0
  162. apps/rokucam/app.json +1 -0
  163. apps/security/__init__.py +261 -0
  164. apps/security/app.json +1 -0
  165. apps/settings/__init__.py +221 -0
  166. apps/settings/app.json +1 -0
  167. apps/shell/__init__.py +33 -0
  168. apps/shell/app.json +1 -0
  169. apps/spotify/__init__.py +669 -0
  170. apps/spotify/app.json +1 -0
  171. apps/spotify/screen.py +82 -0
  172. apps/steps/__init__.py +58 -0
  173. apps/steps/app.json +1 -0
  174. apps/stompbox/__init__.py +31 -0
  175. apps/stompbox/app.json +1 -0
  176. apps/stompbox/app.py +668 -0
  177. apps/stompbox/boards.json +20 -0
  178. apps/stompbox/effects.py +241 -0
  179. apps/stompbox/engine.py +340 -0
  180. apps/stompbox/footswitch.py +331 -0
  181. apps/stompbox/inputs.py +449 -0
  182. apps/stompbox/meter.py +72 -0
  183. apps/stompbox/outputs.py +135 -0
  184. apps/stompbox/pedals.txt +45 -0
  185. apps/stompbox/presets.py +106 -0
  186. apps/stompbox/styles.py +135 -0
  187. apps/stompbox/ui.py +817 -0
  188. apps/stompbox/wavfile.py +73 -0
  189. apps/synthstation/__init__.py +20 -0
  190. apps/synthstation/app.json +1 -0
  191. apps/synthstation/audio.py +397 -0
  192. apps/synthstation/catalog.py +50 -0
  193. apps/synthstation/meters.py +136 -0
  194. apps/synthstation/midi.py +380 -0
  195. apps/synthstation/pads.py +177 -0
  196. apps/synthstation/parts.py +128 -0
  197. apps/synthstation/station.py +1069 -0
  198. apps/system/__init__.py +11 -0
  199. apps/system/app.json +1 -0
  200. apps/touchcal/__init__.py +324 -0
  201. apps/touchcal/app.json +1 -0
  202. apps/touchcal/fit.py +262 -0
  203. apps/wake/__init__.py +268 -0
  204. apps/wake/app.json +1 -0
  205. apps/wake/feed.py +155 -0
  206. apps/watch/__init__.py +355 -0
  207. apps/watch/app.json +1 -0
  208. apps/watch/faces.py +35 -0
  209. apps/watch/wheel.py +157 -0
  210. apps/weather/__init__.py +278 -0
  211. apps/weather/app.json +1 -0
  212. apps/weather/icons.py +172 -0
  213. apps/weather/sizing.py +71 -0
  214. apps/weather/zippad.py +172 -0
  215. omnipython_apps-0.1.4.dev8.dist-info/METADATA +33 -0
  216. omnipython_apps-0.1.4.dev8.dist-info/RECORD +218 -0
  217. omnipython_apps-0.1.4.dev8.dist-info/WHEEL +5 -0
  218. omnipython_apps-0.1.4.dev8.dist-info/top_level.txt +1 -0
apps/huey/settings.py ADDED
@@ -0,0 +1,97 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """The app's settings: which server Huey talks to, with which models and key.
5
+
6
+ The defaults ask lite-assistant, a server for a computer on your own
7
+ network, whose address only you know: ``base_url`` has to be set.
8
+
9
+ They are one JSON file, ``settings.json`` in the app's data folder
10
+ (``/data/huey`` on a board). `load` reads it over `DEFAULTS`, so the file
11
+ holds only what differs, and no file at all means the defaults.
12
+ """
13
+
14
+ import json
15
+
16
+ import chatclient
17
+
18
+ #: Every setting and its value when the file doesn't give one.
19
+ DEFAULTS = {
20
+ # an OpenAI-compatible server: the address its /chat/completions is
21
+ # under; "" until it is set, since only you know where your server runs
22
+ "base_url": "",
23
+ # a file holding the API key on one line; "" for a server that asks for none
24
+ "key_file": "/lite-assistant.key",
25
+ # what lite-assistant calls its models
26
+ "stt_model": "moonshine",
27
+ "chat_model": "gemma-4-E2B-it",
28
+ "tts_model": "kokoro",
29
+ # a voice the speech model has, or "" for its own: Huey is a he, so a man's
30
+ "voice": "am_puck",
31
+ # the rate of speech that comes back as bare PCM; WAV carries its own
32
+ "speech_rate": 24000,
33
+ # how loud Huey speaks, 0 to 100
34
+ "volume": 80,
35
+ # the longest question, in seconds
36
+ "listen_seconds": 12,
37
+ # where Huey is when the app opens: coast, bench or desk
38
+ "place": "desk",
39
+ # more servers to choose between in the device's picker, under
40
+ # Assistant: each an object with a "name" and any of SERVER_KEYS
41
+ "servers": [],
42
+ }
43
+
44
+ #: The settings a server in ``servers`` may give, over the ones above.
45
+ SERVER_KEYS = ("base_url", "key_file", "stt_model", "chat_model", "tts_model", "voice", "speech_rate")
46
+
47
+
48
+ def load(path):
49
+ """The settings: `DEFAULTS`, with what the file at *path* gives over them.
50
+
51
+ Raises:
52
+ ValueError: The file isn't a JSON object, or names a setting there
53
+ isn't, or gives one the wrong kind of value.
54
+ """
55
+ settings = dict(DEFAULTS)
56
+ try:
57
+ with open(path) as f:
58
+ text = f.read()
59
+ except OSError:
60
+ return settings
61
+ try:
62
+ given = json.loads(text)
63
+ except ValueError:
64
+ raise ValueError("%s isn't JSON" % path)
65
+ if not isinstance(given, dict):
66
+ raise ValueError("%s isn't a JSON object" % path)
67
+ for name in given:
68
+ if name not in DEFAULTS:
69
+ raise ValueError("%s has no setting %r" % (path, name))
70
+ if type(given[name]) is not type(DEFAULTS[name]):
71
+ raise ValueError("%s: %r should be %s" % (path, name, "a number" if isinstance(DEFAULTS[name], int) else "text"))
72
+ settings[name] = given[name]
73
+ for server in settings["servers"]:
74
+ _check_server(path, server)
75
+ return settings
76
+
77
+
78
+ def _check_server(path, server):
79
+ if not isinstance(server, dict) or not isinstance(server.get("name"), str) or not server["name"]:
80
+ raise ValueError("%s: each of servers should be an object with a name" % path)
81
+ for name in server:
82
+ if name == "name":
83
+ continue
84
+ if name not in SERVER_KEYS:
85
+ raise ValueError("%s: server %r has no setting %r" % (path, server["name"], name))
86
+ if type(server[name]) is not type(DEFAULTS[name]):
87
+ raise ValueError("%s: server %r: %r should be %s" % (
88
+ path, server["name"], name, "a number" if isinstance(DEFAULTS[name], int) else "text"))
89
+
90
+
91
+ def read_key(settings):
92
+ """The API key the settings name, or ``""`` when they name no file.
93
+
94
+ Raises:
95
+ OSError: The key file isn't there, or is empty.
96
+ """
97
+ return chatclient.read_key(settings["key_file"])
apps/huey/turn.py ADDED
@@ -0,0 +1,504 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """One turn of a conversation with Huey, from the question to the last word of the answer.
5
+
6
+ A `Turn` takes a press and a release, records what is said between them and
7
+ sends it through the three legs of an answer: the sound becomes text, the
8
+ text gets a reply, the reply becomes speech. Each leg runs on the app's
9
+ worker, so the picture keeps moving, and each one's time is kept in `last`.
10
+ """
11
+
12
+ import time
13
+ from multimer import ticks_diff, ticks_ms
14
+
15
+ from chatclient import web
16
+
17
+ from . import acting, servers, settings as settingsmod
18
+ from .client import Client
19
+ from .voice import Player, Recorder
20
+
21
+ try:
22
+ import network
23
+ except ImportError: # a computer is on its network already
24
+ network = None
25
+ try:
26
+ from _thread import get_ident
27
+ except ImportError: # no threads: the worker runs its jobs between ticks
28
+ get_ident = None
29
+
30
+ RATE = 16000 # what the question is recorded at
31
+ SHORTEST = 0.4 # seconds: a shorter hold is a tap, not a question
32
+ KEPT = 6 # messages of the conversation the model is shown again
33
+ _OPEN_ABOVE = 0.1 # how loud the speech must be for his mouth to open
34
+
35
+
36
+ class Turn:
37
+ """The conversation: `press` and `release` Huey, and call `tick` on every tick of the app.
38
+
39
+ Args:
40
+ stage: The `actor.Actor` that plays it out.
41
+ show: Where words go: ``note(text)`` for what is happening,
42
+ ``heard(text)`` for the question as it was understood,
43
+ ``say(text, trouble)`` for the answer or what went wrong, and
44
+ ``ring(level)`` for how loud the microphone hears, None when he isn't listening.
45
+ worker: The app's ``scope.worker``.
46
+ path (str): The settings file.
47
+ post: What sends a request; a `web.Session`'s, kept from turn to
48
+ turn, unless a test gives its own.
49
+ microphone: What opens the microphone at a rate, in place of the board's.
50
+ speaker: What opens the speaker at a rate and a count of channels, in place of the board's.
51
+ """
52
+
53
+ def __init__(self, stage, show, worker, path, post=None, microphone=None, speaker=None):
54
+ self.stage = stage
55
+ self.show = show
56
+ self.worker = worker
57
+ self.path = path
58
+ #: The connections to the server, kept open across legs and turns:
59
+ #: one for words, one for speech, which can be asked for while the
60
+ #: reply still arrives. None when a test sends its own way.
61
+ self.session = self.voice_session = None
62
+ speech_post = None
63
+ if post is None:
64
+ self.session = web.Session()
65
+ self.voice_session = web.Session()
66
+ post, speech_post = self.session.post, self.voice_session.post
67
+ self._post = post
68
+ self._speech_post = speech_post
69
+ self._microphone = microphone
70
+ self._speaker = speaker
71
+ #: "idle", "listen", "hear", "think", "voice" (the speech is on its way) or "speak".
72
+ self.state = "idle"
73
+ #: What the last finished turn took: seconds of question in ``asked``;
74
+ #: milliseconds in ``text``, ``reply``, ``voice`` (to the first
75
+ #: sound) and ``spoke``; bytes of speech in ``sound``; the question
76
+ #: and the answer as ``heard`` and ``said``.
77
+ self.last = {}
78
+ #: Why the last turn stopped short, or None.
79
+ self.trouble = None
80
+ #: True once a speaker was asked for and there was none: answers are then only shown.
81
+ self.mute = False
82
+ self.history = []
83
+ self.settings = None
84
+ self._client = None
85
+ self._recorder = None
86
+ for session in (self.session, self.voice_session):
87
+ if session is not None:
88
+ session.close()
89
+ self._player = None
90
+ self._id = 0
91
+ self._began = 0
92
+ self._format = None
93
+ self._act = None
94
+ self._asked = None
95
+ self._rest = None # (turn, text): the whole reply, come after his words
96
+ self._timing = {}
97
+ self._open_for = 0
98
+ self._until = 0
99
+ self._thread = None # the worker's thread, while it is running a job of this turn's
100
+ #: Ticks that arrived on the worker's thread, and were left for the next one.
101
+ self.strays = 0
102
+
103
+ def _job(self, work):
104
+ """*work* as the worker runs it: for as long as it runs, `astray` knows the worker's thread."""
105
+
106
+ def run():
107
+ self._thread = get_ident() if get_ident is not None else None
108
+ try:
109
+ return work()
110
+ finally:
111
+ self._thread = None
112
+
113
+ return run
114
+
115
+ def astray(self):
116
+ """True when this is the worker's thread, in the middle of a job.
117
+
118
+ Where threads share one interpreter lock (an ESP32), a timer's
119
+ callback runs on whichever thread looks for one next, and that can
120
+ be the worker, part way through a network call on its own small
121
+ stack. A place or a pose isn't drawn from there: the app leaves a
122
+ tick that finds itself there to the next one.
123
+ """
124
+ if self._thread is None or get_ident() != self._thread:
125
+ return False
126
+ self.strays += 1
127
+ return True
128
+
129
+ # -- what stands in the way ------------------------------------------
130
+
131
+ def ready(self):
132
+ """Load the settings and the key.
133
+
134
+ Returns:
135
+ None when a turn can begin, or what to tell the person holding Huey.
136
+ """
137
+ try:
138
+ self.settings = settingsmod.load(self.path)
139
+ except ValueError as e:
140
+ return "My settings need a fix: %s." % (e,)
141
+ # The server chosen in the device's picker, when there is one.
142
+ self.settings = servers.use(self.settings)
143
+ if not self.settings["base_url"]:
144
+ return "Tell me where my server is: its address goes in %s as base_url." % self.path
145
+ try:
146
+ key = settingsmod.read_key(self.settings)
147
+ except OSError:
148
+ return "I need a key to think with. Put it in %s, a file the settings name." % self.settings["key_file"]
149
+ if network is not None and not network.WLAN(network.STA_IF).isconnected():
150
+ return "I'm not on Wi-Fi, so I can't think. Join a network and hold me again."
151
+ self._client = Client(self.settings, key, self._post, self._speech_post)
152
+ return None
153
+
154
+ def _stop(self, why):
155
+ """End the turn here, and say *why* on the screen."""
156
+ self._id += 1
157
+ self.state = "idle"
158
+ self.trouble = why
159
+ self._drop_player()
160
+ print("huey:", why)
161
+ self.show.ring(None)
162
+ self.show.note("")
163
+ self.show.say(why, True)
164
+ self.stage.rest()
165
+
166
+ def _drop_player(self):
167
+ if self._player is not None:
168
+ player, self._player = self._player, None
169
+ try:
170
+ player.close()
171
+ except Exception as e:
172
+ print("huey: closing the speaker:", e)
173
+
174
+ # -- the question ------------------------------------------------------
175
+
176
+ def press(self):
177
+ """A finger on Huey: whatever he was doing stops, and he listens."""
178
+ self._id += 1
179
+ self._drop_player()
180
+ self.trouble = None
181
+ why = self.ready()
182
+ if why:
183
+ self._stop(why)
184
+ return
185
+ seconds = self.settings["listen_seconds"]
186
+ if self._recorder is None or self._recorder.most != seconds:
187
+ if self._microphone is None:
188
+ self._recorder = Recorder(RATE, seconds)
189
+ else:
190
+ self._recorder = Recorder(RATE, seconds, self._microphone)
191
+ try:
192
+ self._recorder.start()
193
+ except Exception as e:
194
+ self._stop("I can't hear you: no microphone answers here (%s)." % (e,))
195
+ return
196
+ self.state = "listen"
197
+ self._began = ticks_ms()
198
+ self._warm()
199
+ self.stage.listen()
200
+ self.show.say(None, False)
201
+ self.show.note("Listening")
202
+
203
+ def _warm(self):
204
+ """While the question is asked, open the connections its answer will need."""
205
+ sessions, base = (self.session, self.voice_session), self._client.base
206
+ if sessions[0] is None:
207
+ return
208
+
209
+ def warm():
210
+ for session in sessions:
211
+ try:
212
+ session.warm(base, 30)
213
+ except Exception as e:
214
+ # the leg that needs it opens it again, and says so if it can't
215
+ print("huey: opening a connection early:", e)
216
+
217
+ self.worker.submit(self._job(warm))
218
+
219
+ def release(self):
220
+ """The finger lifts: the question is over, and its answer is on the way."""
221
+ if self.state != "listen":
222
+ return
223
+ try:
224
+ sound = self._recorder.stop()
225
+ except Exception as e:
226
+ self._stop("I lost the microphone (%s)." % (e,))
227
+ return
228
+ self.show.ring(None)
229
+ if self._recorder.seconds() < SHORTEST:
230
+ self.state = "idle"
231
+ self.show.note("Hold me while you talk")
232
+ self.stage.rest()
233
+ return
234
+ self._hear(sound, RATE, self._recorder.seconds())
235
+
236
+ def hear(self, sound, rate):
237
+ """Take a question already recorded, 16-bit mono *sound* at *rate*, as if it had just been asked.
238
+
239
+ Returns:
240
+ None, or what stands in the way of a turn.
241
+ """
242
+ self._id += 1
243
+ self._drop_player()
244
+ self.trouble = None
245
+ why = self.ready()
246
+ if why:
247
+ self._stop(why)
248
+ return why
249
+ self.show.say(None, False)
250
+ self._hear(sound, rate, len(sound) / (rate * 2))
251
+ return None
252
+
253
+ def _hear(self, sound, rate, seconds):
254
+ self.state = "hear"
255
+ self._timing = {"asked": seconds}
256
+ self._began = ticks_ms()
257
+ self.stage.think()
258
+ client, turn = self._client, self._id
259
+ self.worker.submit(self._job(lambda: client.transcribe(sound, rate)), lambda text, error: self._on_text(turn, text, error))
260
+
261
+ def _leg(self, name):
262
+ now = ticks_ms()
263
+ self._timing[name] = ticks_diff(now, self._began)
264
+ self._began = now
265
+
266
+ def _on_text(self, turn, text, error):
267
+ if turn != self._id:
268
+ return
269
+ if error is not None:
270
+ self._stop("I couldn't make out the words: %s." % (error,))
271
+ return
272
+ self._leg("text")
273
+ if not text:
274
+ self._stop("I didn't catch that. Hold me and say it again?")
275
+ return
276
+ self._timing["heard"] = text
277
+ self.show.heard(text)
278
+ self.show.note("Thinking")
279
+ self.state = "think"
280
+ stage = self.stage
281
+ messages = [{"role": "system", "content": acting.prompt(stage.place, stage.variant, stage.scheme)}]
282
+ messages.extend(self.history)
283
+ messages.append({"role": "user", "content": text})
284
+ client = self._client
285
+
286
+ def think():
287
+ # read until the words he says are whole; the rest comes while he says them
288
+ chat = client.chat_stream(messages)
289
+ try:
290
+ while not chat.done and acting.early(chat.text) is None:
291
+ chat.more()
292
+ except Exception:
293
+ chat.close()
294
+ raise
295
+ return chat
296
+
297
+ self.worker.submit(self._job(think), lambda chat, error: self._on_reply(turn, text, chat, error))
298
+
299
+ def _on_reply(self, turn, asked, chat, error):
300
+ if turn != self._id:
301
+ if chat is not None:
302
+ chat.close()
303
+ return
304
+ if error is not None:
305
+ self._stop("I couldn't think of an answer: %s." % (error,))
306
+ return
307
+ self._leg("reply")
308
+ self._asked = asked
309
+ if chat.done:
310
+ try:
311
+ act = acting.read(chat.text, self.stage.place)
312
+ except ValueError:
313
+ self._stop("I lost my words. Hold me and ask again?")
314
+ return
315
+ say, chat = act.say, None
316
+ else:
317
+ # the words are whole and the rest is on its way: he can begin
318
+ act = None
319
+ say = acting.early(chat.text)
320
+ self._act = act
321
+ self._rest = None
322
+ self._timing["said"] = say
323
+ self.show.say(say, False)
324
+ if act is not None:
325
+ self._acted(act)
326
+ if self.mute:
327
+ self._speak_silently(say)
328
+ if chat is not None:
329
+ self.worker.submit(self._job(lambda: self._read_rest(turn, chat)))
330
+ return
331
+ self.state = "voice"
332
+ self._format = None
333
+ if self._speaker is None:
334
+ player = self._player = Player(self.settings["volume"])
335
+ else:
336
+ player = self._player = Player(self.settings["volume"], self._speaker)
337
+ client = self._client
338
+
339
+ def fetch():
340
+ try:
341
+ speech = client.speak(say)
342
+ try:
343
+ player.frame = 2 * speech.channels
344
+ self._format = (turn, speech.rate, speech.channels)
345
+ while turn == self._id and self._player is player:
346
+ if not player.has_room():
347
+ if chat is not None and not chat.done:
348
+ self._read_rest(turn, chat, False)
349
+ else:
350
+ time.sleep(0.02)
351
+ continue
352
+ data = speech.read(4096)
353
+ if not data:
354
+ break
355
+ player.put(data)
356
+ finally:
357
+ speech.close()
358
+ player.end()
359
+ finally:
360
+ if chat is not None:
361
+ self._read_rest(turn, chat)
362
+
363
+ self.worker.submit(self._job(fetch), lambda _, error: self._on_spoken(turn, error))
364
+
365
+ def _read_rest(self, turn, chat, wait=True):
366
+ """On the worker: more of the reply, all of it when *wait*, handed to `tick` once it is all here."""
367
+ if chat.done:
368
+ return # an earlier call read the end and handed it over
369
+ try:
370
+ chat.more()
371
+ while wait and turn == self._id and not chat.done:
372
+ chat.more()
373
+ except Exception as e:
374
+ # he has said his words; what he does with them is lost
375
+ print("huey: the rest of the reply:", e)
376
+ chat.close()
377
+ return
378
+ if not chat.done:
379
+ if wait:
380
+ chat.close() # the turn moved on
381
+ else:
382
+ self._rest = (turn, chat.text)
383
+
384
+ def _acted(self, act):
385
+ """The reply is all here: remember it, and act it out."""
386
+ self.history.append({"role": "user", "content": self._asked})
387
+ self.history.append({"role": "assistant", "content": act.record()})
388
+ self.history = self.history[-KEPT:] if KEPT else []
389
+ self.stage.perform(act.colors, act.place, act.variant)
390
+ if self.state == "speak":
391
+ self.stage.mood = act.mood or "calm"
392
+ self.stage.prop = act.prop
393
+
394
+ def _on_spoken(self, turn, error):
395
+ if turn == self._id and error is not None:
396
+ self._stop("I couldn't find my voice: %s." % (error,))
397
+
398
+ def _speak_silently(self, say):
399
+ self.state = "speak"
400
+ self._leg("voice")
401
+ self._until = 60 * len(say) + 800
402
+ self._pose()
403
+
404
+ def _pose(self):
405
+ act = self._act
406
+ self.stage.speak((act and act.mood) or "calm", act and act.prop)
407
+
408
+ # -- every tick --------------------------------------------------------
409
+
410
+ def tick(self):
411
+ rest = self._rest
412
+ if rest is not None and rest[0] == self._id:
413
+ # the reply is all here, perhaps after his words were said
414
+ self._rest = None
415
+ try:
416
+ self._act = acting.read(rest[1], self.stage.place)
417
+ except ValueError:
418
+ pass # nothing more to act out than the words he said
419
+ else:
420
+ self._acted(self._act)
421
+ state = self.state
422
+ if state == "idle":
423
+ return
424
+ waited = ticks_diff(ticks_ms(), self._began) // 1000
425
+ if state == "listen":
426
+ try:
427
+ self._recorder.poll()
428
+ except Exception as e:
429
+ self._stop("I lost the microphone (%s)." % (e,))
430
+ return
431
+ self.show.ring(self._recorder.level)
432
+ self.show.note("Listening %d s" % waited)
433
+ if self._recorder.full:
434
+ self.release()
435
+ elif state == "hear":
436
+ self.show.note("Making out the words %d s" % waited)
437
+ elif state == "think":
438
+ self.show.note("Thinking %d s" % waited)
439
+ elif state == "voice":
440
+ self.show.note("Finding my voice %d s" % waited)
441
+ found = self._format
442
+ if found is not None and found[0] == self._id:
443
+ self._format = None
444
+ try:
445
+ self._player.open(found[1], found[2])
446
+ except Exception as e:
447
+ # the words are on the screen: the turn goes on without sound
448
+ print("huey: no speaker:", e)
449
+ self.mute = True
450
+ self._drop_player()
451
+ self._speak_silently(self._timing["said"])
452
+ self.show.note("No speaker here: read my words")
453
+ return
454
+ self._leg("voice")
455
+ self.state = "speak"
456
+ self.show.note("")
457
+ self._pose()
458
+ elif state == "speak":
459
+ if self._player is None:
460
+ # no speaker: his mouth keeps time with the length of the words
461
+ self._open_for = (self._open_for + 1) % 8
462
+ self.stage.mouth = self._open_for < 4
463
+ if ticks_diff(ticks_ms(), self._began) >= self._until:
464
+ self._finish(0)
465
+ return
466
+ try:
467
+ done = self._player.play()
468
+ except Exception as e:
469
+ self._stop("My speaker stopped: %s." % (e,))
470
+ return
471
+ # open on a loud moment, and for a few ticks, so it doesn't flutter
472
+ if self._player.level > _OPEN_ABOVE:
473
+ self._open_for = 3
474
+ elif self._open_for:
475
+ self._open_for -= 1
476
+ self.stage.mouth = self._open_for > 0
477
+ if done:
478
+ self._finish(self._player.played)
479
+
480
+ def _finish(self, sound):
481
+ self._leg("spoke")
482
+ self._timing["sound"] = sound
483
+ self.last = self._timing
484
+ self._drop_player()
485
+ self.state = "idle"
486
+ self.show.note("")
487
+ self.stage.settle()
488
+ t = self.last
489
+ print("huey: asked %.1f s, text %d ms, reply %d ms, voice %d ms, spoke %d ms" % (t["asked"], t["text"], t["reply"], t["voice"], t["spoke"]))
490
+
491
+ def close(self):
492
+ """Stop whatever is under way and let the microphone and speaker go."""
493
+ self._id += 1
494
+ self.state = "idle"
495
+ self._drop_player()
496
+ if self._recorder is not None and self._recorder.recording:
497
+ try:
498
+ self._recorder.stop()
499
+ except Exception as e:
500
+ print("huey: closing the microphone:", e)
501
+ self._recorder = None
502
+ for session in (self.session, self.voice_session):
503
+ if session is not None:
504
+ session.close()