forked from jacnel/LilyInteractive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
525 lines (450 loc) · 18.1 KB
/
main.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
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
from __future__ import print_function
import inspect
import cPickle as pickle
import matplotlib.pyplot as plt
import io
import networkx as nx
from story import Story, StoryError
from functools import partial
from kivy.config import Config
# disable multitouch from mouse
Config.set('input', 'mouse', 'mouse,disable_multitouch')
Config.set('input', 'mouse', 'mouse,disable_on_activity')
from kivy.app import App
from kivy.core.window import Window
from kivy.metrics import dp, Metrics
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen, FallOutTransition
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.filechooser import FileChooser
from kivy.core.image import Image as CoreImage
from kivy.uix.dropdown import DropDown
from kivy.properties import ObjectProperty, StringProperty
Window.size = map(dp, (1280, 720))
# matplotlib parameters
plt.rcParams['figure.dpi'] = 200
plt.rcParams['figure.figsize'] = 16, 12
plt.rcParams['figure.subplot.left'] = 0
plt.rcParams['figure.subplot.right'] = 1
plt.rcParams['figure.subplot.top'] = 1
plt.rcParams['figure.subplot.bottom'] = 0
plt.rcParams['figure.subplot.wspace'] = 0
plt.rcParams['figure.subplot.hspace'] = 0
class AddActionPopup(Popup):
pass
class HomeScreen(Screen):
pass
class FileBrowserPopup(Popup):
action_btn = ObjectProperty()
filename_inp = ObjectProperty()
file_chooser = ObjectProperty()
current_path = StringProperty()
selected_file = StringProperty()
class FileBrowserContent(BoxLayout):
pass
class AddEdgePopup(Popup):
node_list = ObjectProperty()
save_btn = ObjectProperty()
class AddNodePopup(Popup):
submit_btn_wid = ObjectProperty()
node_name = StringProperty()
class AddActionPopup(Popup):
actions_list_wid = ObjectProperty()
add_action_btn_wid = ObjectProperty()
save_btn = ObjectProperty()
cancel_btn = ObjectProperty()
def __init__(self, existing_actions=None, **kwargs):
super(AddActionPopup, self).__init__(**kwargs)
self.actions_list_wid.bind(minimum_height=self.actions_list_wid.setter('height'))
self._actions_temp = None
self.actions_temp = existing_actions
@property
def actions_temp(self):
return self._actions_temp
@actions_temp.setter
def actions_temp(self, actions):
self._actions_temp = []
if actions:
for action in actions:
a = Action()
a.action_type = action['type']
a.type_button_wid.text = action['type']
a.parameters = action['kwargs']
self.add_action(a)
def add_action(self, action):
def move_action_up(button):
for i, a in enumerate(self.actions_temp[:]):
if action is a and i > 0:
self.actions_temp[i-1], self.actions_temp[i] =\
self.actions_temp[i], self.actions_temp[i-1]
self.render_actions()
def move_action_down(button):
for i, a in enumerate(self.actions_temp[:]):
if action is a and i < len(self.actions_temp) - 1:
self.actions_temp[i], self.actions_temp[i+1] =\
self.actions_temp[i+1], self.actions_temp[i]
self.render_actions()
def remove_action(button):
self.actions_list_wid.remove_widget(action)
self.actions_temp.remove(action)
action.move_up_btn.bind(on_release=move_action_up)
action.move_down_btn.bind(on_release=move_action_down)
action.remove_btn.bind(on_release=remove_action)
self.actions_list_wid.add_widget(action)
self.actions_temp.append(action)
def render_actions(self):
self.actions_list_wid.clear_widgets()
for action in self.actions_temp:
self.actions_list_wid.add_widget(action)
class Action(BoxLayout):
action_type = StringProperty()
type_button_wid = ObjectProperty()
set_param_btn_wid = ObjectProperty()
move_up_btn = ObjectProperty()
move_down_btn = ObjectProperty()
remove_btn = ObjectProperty()
def __init__(self, **kwargs):
super(Action, self).__init__(**kwargs)
self.init_type_dropdown()
self.parameters = None # dict of parameters to the corresponding action
def init_type_dropdown(self):
d = DropDown()
action_types = ['say', 'listen', 'play']
for action_type in action_types:
b = Button(text=action_type, size_hint_y=None, height=dp(30))
def action_select_callback(button):
d.select(button.text)
# reset parameters when changing action type
if self.action_type != button.text:
self.parameters = None
self.action_type = button.text
b.bind(on_release=action_select_callback)
d.add_widget(b)
d.bind(on_select=\
lambda instance, text: setattr(self.type_button_wid, 'text', text))
self.type_button_wid.bind(on_release=d.open)
def get_parameters(self):
btn = self.set_param_btn_wid
g = GridLayout(cols=2)
param_temp = {}
def only_if_callback(instance, value):
value = value.strip()
if value:
param_temp['only_if'] = tuple(value.split(','))
if self.action_type == 'say':
g.add_widget(Label(text='message'))
t = TextInput()
if self.parameters:
try:
t.text = self.parameters['message']
except KeyError:
pass
t.bind(text=lambda _, value: param_temp.update({'message': value}))
g.add_widget(t)
g.add_widget(Label(text='only if'))
t = TextInput()
if self.parameters:
try:
t.text = self.parameters['only_if']
except KeyError:
pass
t.bind(text=only_if_callback)
g.add_widget(t)
elif self.action_type == 'listen':
g.add_widget(Label(text='intent'))
t = TextInput(multiline=False)
if self.parameters:
try:
t.text = self.parameters['intent']
except KeyError:
pass
t.bind(text=lambda _, value: param_temp.update({'intent': value}))
g.add_widget(t)
label_dict = {
'entity type': 'entity_type',
'maximum entities': 'n_entities',
'verify with context at': 'verify_with',
'update context at': 'context_key',
'failure message': 'fail_message',
'only if': 'only_if'}
for k, v in label_dict.iteritems():
g.add_widget(Label(text=k))
t = TextInput()
if k == 'failure message':
t.multiline = True
if self.parameters:
try:
t.text = self.parameters[v]
except KeyError:
pass
if k == 'maximum entities':
def int_callback(instance, value):
value = value.strip()
if value:
param_temp['n_entities'] = int(value)
t.bind(text=int_callback)
elif k == 'only if':
t.bind(text=only_if_callback)
else:
t.bind(text=lambda _, value: param_temp.update({v: value}))
g.add_widget(t)
elif self.action_type == 'play':
g.add_widget(Label(text='source'))
t = TextInput(multiline=False)
if self.parameters:
try:
t.text = self.parameters['source']
except KeyError:
pass
t.bind(text=lambda _, value: param_temp.update({'source': value}))
g.add_widget(t)
g.add_widget(Label(text='only if'))
t = TextInput()
if self.parameters:
try:
t.text = self.parameters['only_if']
except KeyError:
pass
t.bind(text=only_if_callback)
g.add_widget(t)
else:
return
p = Popup(title='Set parameters', size_hint=(.5, .8))
# btn.bind(on_release=p.open)
def submit_callback(button):
self.parameters = param_temp
p.dismiss()
submit_btn = Button(text='Submit')
submit_btn.bind(on_release=submit_callback)
cancel_btn = Button(text='Cancel')
cancel_btn.bind(on_release=lambda _: p.dismiss())
g.add_widget(submit_btn)
g.add_widget(cancel_btn)
p.content = g
p.open()
class EditScreen(Screen):
# dropdown_wid = ObjectProperty()
dropdown_btn_wid = ObjectProperty()
node_info_wid = ObjectProperty()
refresh_btn = ObjectProperty()
storyboard_wid = ObjectProperty()
def __init__(self, **kwargs):
super(EditScreen, self).__init__(**kwargs)
self.d = None
self.init_node_select_dropdown()
self.story = Story()
self.current_node = None
self.refresh_btn.bind(on_release=self.refresh_graph)
self.current_file = ''
def init_node_select_dropdown(self):
self.d = d = DropDown()
b = Button(text='Add a node...', size_hint_y=None, height=dp(30))
b.bind(on_release=self.show_add_popup)
d.add_widget(b)
d.bind(on_select=lambda _, text: setattr(self.dropdown_btn_wid, 'text', text))
self.dropdown_btn_wid.bind(on_release=d.open)
def show_file_browser(self, action):
p = FileBrowserPopup()
def update_current_file(instance, text):
self.current_file = p.current_path + '/' + text.strip()
if action == 'save as':
p.filename_inp.bind(text=update_current_file)
p.action_btn.text = 'Save'
def save(button):
self.save_current()
p.dismiss()
p.action_btn.bind(on_release=save)
p.open()
elif action == 'load':
p.action_btn.text = 'Load'
def load(button):
path = p.selected_file
self.load_story(path)
p.dismiss()
p.action_btn.bind(on_release=load)
p.open()
def save_current(self):
if self.current_file:
filename = self.current_file.strip()
# check whether user has appended '.story' filename extension
filename = filename.split('.')
if len(filename) == 1 or filename[-1] != 'story':
filename.append('story')
filename = '.'.join(filename)
print(filename)
with open(filename, 'w') as f:
pickle.dump(self.story, f)
else:
self.show_file_browser('save as')
def load_story(self, path):
# TODO: check whether current file is saved
with open(path, 'r') as f:
try:
obj = pickle.load(f)
except IOError as e:
print(str(e))
return
if isinstance(obj, Story):
self.story = obj
else:
# TODO: display helpful message
return
for node in self.story:
b = Button(text=node, size_hint_y=None, height=dp(30))
b.bind(on_release=self.show_info_callback)
self.d.add_widget(b)
self.refresh_graph()
def check_current_file(self):
board = self.ids['board']
if board.current_file:
board.save_story(board.current_file)
else:
self.show_file_chooser()
def refresh_graph(self, *args):
g = self.story
plt.clf()
nx.draw_networkx(g, node_size=2000, font_size=dp(16), node_shape=',')
curr_axes = plt.gca()
curr_axes.axes.get_xaxis().set_visible(False)
curr_axes.axes.get_yaxis().set_visible(False)
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
image = CoreImage(buf, ext='png')
self.storyboard_wid.texture = image.texture
def show_add_popup(self, button):
# show the add popup
p = AddNodePopup(attach_to=self)
p.open()
def add_callback(button):
"""Add the node to the story and update the dropdown menu
"""
self.d.dismiss()
node_name = p.node_name
self.story.add_node(node_name)
print(self.story.nodes())
p.dismiss()
# update the dropdown menu
b = Button(text=node_name, size_hint_y=None, height=dp(30))
b.bind(on_release=self.show_info_callback)
self.d.add_widget(b)
p.submit_btn_wid.bind(on_release=add_callback)
def show_info_callback(self, button):
"""Shows the node information in the sidebar
"""
self.current_node = button.text
self.d.select(button.text)
# p.dismiss()
node_info = self.node_info_wid
node_info.clear_widgets()
node_info.add_widget(Label(text='name:'))
# TODO: allow node renaming?
node_info.add_widget(TextInput(text=button.text, multiline=False))
node_info.add_widget(Label(text='actions:'))
actions_b = Button(text='edit...')
actions_b.bind(on_release=self.show_add_action_popup)
node_info.add_widget(actions_b)
node_info.add_widget(Label(text='destinations:'))
dest_b = Button(text='edit...')
dest_b.bind(on_release=self.show_add_dest_popup)
node_info.add_widget(dest_b)
node_info.add_widget(Label(text='origins:'))
orig_b = Button(text='edit...')
orig_b.bind(on_release=self.show_add_origin_popup)
node_info.add_widget(orig_b)
def show_add_action_popup(self, button):
p = AddActionPopup(existing_actions=self.story.get_actions(self.current_node),
attach_to=self)
p.open()
def add_action_callback(button):
a = Action()
p.add_action(a)
# p.actions_list_wid.add_widget(a)
# p.actions_temp.append(a)
def update_story(action):
if action.action_type == 'say':
self.story.add_say(self.current_node, **action.parameters)
elif action.action_type == 'listen':
self.story.add_listen(self.current_node, **action.parameters)
elif action.action_type == 'play':
self.story.add_play(self.current_node, **action.parameters)
def save_callback(button):
actions = p.actions_temp
for action in actions:
update_story(action)
p.dismiss()
p.add_action_btn_wid.bind(on_release=add_action_callback)
p.save_btn.bind(on_release=save_callback)
def show_add_dest_popup(self, button):
p = AddEdgePopup(title='Add destinations')
valid_dest = self.story.nodes()
valid_dest.remove(self.current_node)
for dest in valid_dest:
b = ToggleButton(text=dest, size_hint_y=None, height=dp(30))
if dest in self.story.neighbors(self.current_node):
b.state = 'down'
p.node_list.add_widget(b)
p.node_list.add_widget(Widget())
def save_callback(button):
to_add = []
to_remove = []
for child in p.node_list.children:
if isinstance(child, ToggleButton):
node_name = child.text
if child.state == 'down':
to_add.append(node_name)
else:
to_remove.append(node_name)
for node in to_add:
if node not in self.story.neighbors(self.current_node):
self.story.add_edge(self.current_node, node)
for node in to_remove:
if node in self.story.neighbors(self.current_node):
self.story.remove_edge(self.current_node, node)
p.dismiss()
p.save_btn.bind(on_release=save_callback)
p.open()
def show_add_origin_popup(self, button):
p = AddEdgePopup(title='Add origins')
valid_orig = self.story.nodes()
valid_orig.remove(self.current_node)
for orig in valid_orig:
b = ToggleButton(text=orig, size_hint_y=None, height=dp(30))
if orig in self.story.predecessors(self.current_node):
b.state = 'down'
p.node_list.add_widget(b)
p.node_list.add_widget(Widget())
def save_callback(button):
to_add = []
to_remove = []
for child in p.node_list.children:
if isinstance(child, ToggleButton):
node_name = child.text
if child.state == 'down':
to_add.append(node_name)
else:
to_remove.append(node_name)
for node in to_add:
if node not in self.story.predecessors(self.current_node):
self.story.add_edge(node, self.current_node)
for node in to_remove:
if node in self.story.predecessors(self.current_node):
self.story.remove_edge(node, self.current_node)
p.dismiss()
p.save_btn.bind(on_release=save_callback)
p.open()
class StoryboardApp(App):
def build(self):
sm = ScreenManager() # TODO: transitions
# sm.add_widget(HomeScreen(name='home'))
sm.add_widget(EditScreen(name='edit'))
return sm
if __name__ == '__main__':
# print('dpi: %f' % Metrics.dpi)
StoryboardApp().run()