-
Notifications
You must be signed in to change notification settings - Fork 1
/
osc_server.py
365 lines (311 loc) · 10.5 KB
/
osc_server.py
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
"""
Code to run the OSC server that listens for various
inputs.
Usage: python osc_server.py
"""
import json
import pythonosc
import argparse
import math
import datetime
from pythonosc import dispatcher, osc_server, udp_client, osc_message_builder
import requests
from collections import OrderedDict
from statistics import mean
import logging
import numpy as np
logger = logging.getLogger('osc_server')
logger.setLevel(logging.INFO)
# create file handler which logs even debug messages
fh = logging.FileHandler('osc_server.log')
fh.setLevel(logging.INFO)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
from util import ip_osc, ip_osc_server, ip_osc_editor, port_server,port_client, port_client_editor, osc_dispatch, api_url
current_state = OrderedDict()
current_state["/state"] = "calm"
current_state["/action"] = "start"
current_state["/sentiment"] = 0.0
current_state["/energy"] = 0.0
current_state["/focus"] = 0.0
def change_state(current_state):
"""
Change the current state dict to
reflect state param: new_state
return current_state
"""
logger.info("Getting Data from AI")
r = requests.get(api_url + 'interact')
if r.status_code == 200:
data = r.json()
else:
data = pickle.load(open('./default-api-response.p','rb'))
logger.info("Using Default Data: {}".format(data))
logger.info
if data['state'] != current_state['/state']:
current_state['/state'] = data['state']
else:
current_state['/state'] = data['state2']
if current_state['/state'] == "angry":
current_state['/state'] == np.random.choice([data['state'],data['state2'],data['state3']])
current_state['/sentiment'] = data['sentiment']
current_state['/focus'] = data['focus']
current_state['/energy'] = data['energy']
logger.info('state updated from API with {0}'.format(data))
logger.info("New State Set to {0}".format(current_state))
return current_state
def send_surface_state_to_ai(sentiment, energy, focus):
"""
sents the state / new talking as JSON to the AI
focus, energy, and sentiment are floats; unit is a string; words and parts are arrays of strings where the indexes correspond, so words[0] goes with parts[0]
"""
change_state(current_state)
logger.info("AI State is: {0} focus, {1} energy, and {2} sentiment".format(focus, energy, sentiment))
data = {
'focus': focus,
'sentiment': sentiment,
'energy': energy
}
r = requests.post(api_url + 'interact-surface', data = data)
return r
def send_answer_to_ai(answer):
"""
Sents an answer to the AI
"""
logger.info("Answer sending ", answer)
headers = {
"content-type": "application/json"
}
r = requests.post(api_url + 'interact',
json={'string': answer},
headers=headers)
return r
def get_api_interact_data():
"""
Gets state from AI, transforms into sentiment.
Returns a string of JSON
"""
logger.info("Getting Data from AI")
r = requests.get(api_url + 'interact')
if r.status_code == 200:
data = r.json()
else:
data = pickle.load(open('./default-api-response.p','rb'))
logger.info("Using Default Data: {}".format(data))
logger.info
if data['state'] != current_state['/state']:
current_state['/state'] = data['state']
else:
current_state['/state'] = data['state2']
current_state['/sentiment'] = data['sentiment']
current_state['/focus'] = data['focus']
current_state['/energy'] = data['energy']
logger.info('state updated from API with {0}'.format(data))
return data
def setup():
"""
sets AI in waiting state
"""
r = requests.get(api_url + "reset")
logger.info("AI Init State Waiting")
current_state = get_api_interact_data()
##pull text from AI
return None
def broadcast_state(state=current_state, ip=ip_osc, port=port_client, num_tries=3):
"""
Broadcasts state
"""
change_state(current_state=state)
logger.info("Called Broadcast State Function")
client = udp_client.UDPClient(ip, port,1)
builder = osc_message_builder.OscMessageBuilder(address='/status')
for k,v in state.items():
builder.add_arg(v)
for _ in range(num_tries):
client.send(builder.build())
logger.info("sent {0} to {1}:{2}. Attempt {3}".format(builder.args, ip, port, _))
return None
def broadcast_text(AItext):
"""
send a fixed piece of text from the AI
add delay into this OSC as second args
get text somehow
"""
osc_dispatch('/textnoquest', AItext, port=port_client_editor)
logger.info("Updating State")
broadcast_state(num_tries=3)
return None
def send_questions_to_line_editor(num_tries=3):
"""
Sends data for display to Line Editor
"""
data = get_api_interact_data()['questions']
broadcast_state()
logger.info("Called send question to the line editor")
ip=ip_osc
port=port_client_editor
client = udp_client.UDPClient(ip, port,1)
logger.info("Prepping to send Data to Line Editor {}:{}", ip, port)
builder = osc_message_builder.OscMessageBuilder(address='/textques')
for k,v in data.items():
logger.info(k,v)
builder.add_arg(v)
for _ in range(num_tries):
client.send(builder.build())
logger.info("sent {0} to {1}:{2}. Attempt {3}".format(builder.args, ip, port, _))
broadcast_state()
return None
surface_data = []
def surface_handler(unused_addr, args):
"""
Handles the surface messages, alts sentiment
Surface argument to be OSC String Formatted as followed
"sentiment: value; focus: value; energy: value"
"""
logger.info("Got Surface Message")
try:
vals = json.loads(args)
## surfaces need to be directed to pi, look in js/machineConfiguration.json
except ValueError:
logger.info("Unable to decode JSON from Surface")
exit()
current_sentiment = vals['sentiment']
current_focus = vals['focus']
current_energy = vals['energy']
current_unit = vals['unit']
logger.info("From Surface Unit {0}".format(current_unit))
current_words = vals['words']
current_parts = vals['parts']
surface_data.append(vals)
return None
def reset_handler(unused_addr, args):
"""
Handles the reset from Editor
"""
logger.info('reset handler')
current_state.update({'/action': 'start'})
broadcast_state()
return None
def answer_handler(unused_addr, args):
"""
Starts answering
"""
logger.info("answer handler")
send_answer_to_ai(args)
current_state.update({'/action': 'thinking'})
broadcast_state(num_tries=3)
send_questions_to_line_editor()
return None
def refresh_handler(unused_addr, args):
"""
Refresh text
"""
logger.info("Refreshing text")
send_questions_to_line_editor()
return None
def talking_handler(unused_addr, args):
"""
Starts talking
"""
logger.info("talking handler")
current_state.update({'/action': 'talking'})
broadcast_state()
return None
def question_handler(unused_addr, args):
"""
shuts the machine up
"""
logger.info('question handler')
current_state.update({'/action': 'question'})
broadcast_state()
return None
def thinking_handler(unsused_addr, args):
"""
shuts the machine up
"""
logger.info('thinking handler')
current_state.update({'/action': 'thinking'})
broadcast_state()
return None
def silent_handler(unused_addr, args):
"""
silences the system after TTS
"""
logger.info("silence handles")
current_state.update({'/action': 'expectant'})
broadcast_state()
return None
def surfacestart_handler(unused_addr, args):
"""
blasts start to the surfaces
"""
logger.info("Blasting Start to the Surfaces")
osc_dispatch('/start-surface', 1, ip='192.168.1.255', num_tries=3)
def surfacereset_handler(unused_addr, args):
"""
blasts reset to surface
"""
logger.info("Blasting Reset to the Surface")
osc_dispatch('/reset-surface', 1, ip='192.168.1.255', num_tries=3)
def surfacestop_handler(unused_addr, args):
"""
blasts stop to surface
"""
logger.info("Blasting Stop to the Surface")
osc_dispatch('/stop-surface', 1, ip='192.168.1.255', num_tries=3)
if len(surface_data) != 0:
sentiment = mean([d['sentiment'] for d in surface_data])
energy = mean([d['energy'] for d in surface_data])
focus = mean([d['focus'] for d in surface_data])
send_surface_state_to_ai(sentiment, energy, focus)
osc_dispatch('/stop-surface', 1, ip='192.168.1.255', num_tries=3)
def end_handler(unused_addr, args):
"""
ends the show
"""
logger.info("end of show")
current_state.update({'/action': 'end'})
broadcast_state()
return
def new_state_handler(unused_addr, args):
logger.info('New State {} recieved'.format(args))
current_state['/state'] = args
logger.info("Updated current_state to {}".format(current_state))
return
def osc_server(ip=ip_osc_server, port=port_server):
"""
sets up and runs the OSC server.
"""
dispatch = dispatcher.Dispatcher()
"""
dispatch.map("/surface-sentiments", surface_handler)
dispatch.map("/reset", reset_handler)
dispatch.map("/silent", silent_handler)
"""
dispatch.map("/surface-sentiments", surface_handler)
dispatch.map("/reset", reset_handler)
dispatch.map("/silent", silent_handler)
dispatch.map("/answer", answer_handler)
dispatch.map("/refresh", refresh_handler)
dispatch.map("/talking", talking_handler)
dispatch.map("/end", end_handler)
dispatch.map("/question", question_handler)
dispatch.map("/thinking", thinking_handler)
dispatch.map("/startsurface", surfacestart_handler)
dispatch.map("/closesurface", surfacestop_handler)
dispatch.map("/resetsurface", surfacereset_handler)
dispatch.map("/newstate", new_state_handler)
server = pythonosc.osc_server.ThreadingOSCUDPServer(
(ip, port), dispatch)
logger.info("Serving on {}".format(server.server_address))
server.serve_forever()
if __name__ == '__main__':
osc_server()