/
tracker.py
executable file
·414 lines (352 loc) · 16 KB
/
tracker.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
# -*- coding: utf-8 -*-
"""
@author: ryuichi takanobu
@modified: anubhav sachan
"""
import random
import torch
from copy import deepcopy
from dbquery import DBQuery, DSTCDBQuery
from utils import discard, reload
from evaluator import MultiWozEvaluator, DSTCSGDSEvaluator
class StateTracker(object):
def __init__(self, data_dir, config):
self.time_step = 0
self.cfg = config
self.db = DBQuery(data_dir, config)
self.topic = ''
self.evaluator = MultiWozEvaluator(data_dir)
self.lock_evalutor = False
def set_rollout(self, rollout):
if rollout:
self.save_time_step = self.time_step
self.save_topic = self.topic
self.lock_evalutor = True
else:
self.time_step = self.save_time_step
self.save_topic = self.topic
self.lock_evalutor = False
def get_entities(self, s, domain):
origin = s['belief_state'][domain].items()
constraint = []
for k, v in origin:
if v != '?' and k in self.cfg.mapping[domain]:
constraint.append((self.cfg.mapping[domain][k], v))
entities = self.db.query(domain, constraint)
random.shuffle(entities)
return entities
def update_belief_sys(self, old_s, a):
"""
update belief/goal state with sys action
"""
s = deepcopy(old_s)
a_index = torch.nonzero(a) # get multiple da indices
self.time_step += 1
s['others']['turn'] = self.time_step
# update sys/user dialog act
s['sys_action'] = dict()
# update belief part
das = [self.cfg.idx2da[idx.item()] for idx in a_index]
das = [da.split('-') for da in das]
sorted(das, key=lambda x:x[0]) # sort by domain
entities = [] if self.topic == '' else self.get_entities(s, self.topic)
return_flag = False
for domain, intent, slot, p in das:
if domain in self.cfg.belief_domains and domain != self.topic:
self.topic = domain
entities = self.get_entities(s, domain)
da = '-'.join((domain, intent, slot, p))
if intent == 'request':
s['sys_action'][da] = '?'
elif intent in ['nooffer', 'nobook'] and self.topic != '':
return_flag = True
if slot in s['belief_state'][self.topic] and s['belief_state'][self.topic][slot] != '?':
s['sys_action'][da] = s['belief_state'][self.topic][slot]
else:
s['sys_action'][da] = 'none'
elif slot == 'choice':
s['sys_action'][da] = str(len(entities))
elif slot == 'none':
s['sys_action'][da] = 'none'
else:
num = int(p) - 1
if self.topic and len(entities) > num and slot in self.cfg.mapping[self.topic]:
typ = self.cfg.mapping[self.topic][slot]
if typ in entities[num]:
s['sys_action'][da] = entities[num][typ]
else:
s['sys_action'][da] = 'none'
else:
s['sys_action'][da] = 'none'
if not self.topic:
continue
if intent in ['inform', 'recommend', 'offerbook', 'offerbooked', 'book']:
discard(s['belief_state'][self.topic], slot, '?')
if slot in s['user_goal'][self.topic] and s['user_goal'][self.topic][slot] == '?':
s['goal_state'][self.topic][slot] = s['sys_action'][da]
# booked
if intent == 'inform' and slot == 'car': # taxi
if 'booked' not in s['belief_state']['taxi']:
s['belief_state']['taxi']['booked'] = 'taxi-booked'
elif intent in ['offerbooked', 'book'] and slot == 'ref': # train
if self.topic in ['taxi', 'hospital', 'police']:
s['belief_state'][self.topic]['booked'] = f'{self.topic}-booked'
s['sys_action'][da] = f'{self.topic}-booked'
elif entities:
book_domain = entities[0]['ref'].split('-')[0]
if 'booked' not in s['belief_state'][book_domain] and entities:
s['belief_state'][book_domain]['booked'] = entities[0]['ref']
s['sys_action'][da] = entities[0]['ref']
if return_flag:
for da in s['user_action']:
d_usr, i_usr, s_usr = da.split('-')
if i_usr == 'inform' and d_usr == self.topic:
discard(s['belief_state'][d_usr], s_usr)
reload(s['goal_state'], s['user_goal'], self.topic)
if not self.lock_evalutor:
self.evaluator.add_sys_da(s['sys_action'])
return s
def update_belief_usr(self, old_s, a):
"""
update belief/goal state with user action
"""
s = deepcopy(old_s)
a_index = torch.nonzero(a) # get multiple da indices
self.time_step += 1
s['others']['turn'] = self.time_step
s['others']['terminal'] = 1 if (self.cfg.a_dim_usr-1) in a_index else 0
# update sys/user dialog act
s['user_action'] = dict()
# update belief part
das = [self.cfg.idx2da_u[idx.item()] for idx in a_index if idx.item() != self.cfg.a_dim_usr-1]
das = [da.split('-') for da in das]
if s['invisible_domains']:
for da in das:
if da[0] == s['next_available_domain']:
s['next_available_domain'] = s['invisible_domains'][0]
s['invisible_domains'].remove(s['next_available_domain'])
break
sorted(das, key=lambda x:x[0]) # sort by domain
for domain, intent, slot in das:
if domain in self.cfg.belief_domains and domain != self.topic:
self.topic = domain
da = '-'.join((domain, intent, slot))
if intent == 'request':
s['user_action'][da] = '?'
s['belief_state'][self.topic][slot] = '?'
elif slot == 'none':
s['user_action'][da] = 'none'
else:
if self.topic and slot in s['user_goal'][self.topic] and s['user_goal'][domain][slot] != '?':
s['user_action'][da] = s['user_goal'][domain][slot]
else:
s['user_action'][da] = 'dont care'
if not self.topic:
continue
if intent == 'inform':
s['belief_state'][domain][slot] = s['user_action'][da]
if slot in s['user_goal'][self.topic] and s['user_goal'][self.topic][slot] != '?':
discard(s['goal_state'][self.topic], slot)
if not self.lock_evalutor:
self.evaluator.add_usr_da(s['user_action'])
return s
def reset(self, random_seed=None):
"""
Args:
random_seed (int):
Returns:
init_state (dict):
"""
pass
def step(self, s, sys_a):
"""
Args:
s (dict):
sys_a (vector):
Returns:
next_s (dict):
terminal (bool):
"""
pass
class DSTCStateTracker(object):
def __init__(self, data_dir, config):
self.time_step = 0
self.cfg = config
self.topic = ''
self.db = DSTCDBQuery(data_dir, config)
self.evaluator = DSTCSGDSEvaluator(data_dir)
self.lock_evalutor = False
self.services = {} # {'restaurants_1': 'Restaurants_1'}
self.rservices = {} # {'Restaurants_1': 'restaurants_1'}
f = open(data_dir + str('/dstc_services_allcaps.txt'))
content = f.read().split('\n')[:-1]
for serv in content:
self.services[serv.lower()] = serv
self.rservices[serv] = serv.lower()
def set_rollout(self, rollout):
if rollout:
self.save_time_step = self.time_step
self.save_topic = self.topic
self.lock_evalutor = True
else:
self.time_step = self.save_time_step
self.save_topic = self.topic
self.lock_evalutor = False
def get_entities(self, s, domain):
domain = domain.lower()
constraint = []
if domain in s['belief_state'].keys():
origin = s['belief_state'][domain].items()
# else:
# origin = s['belief_state'][self.rservices[domain]].items()
for k, v in origin:
if v != '?':
constraint.append((k, v))
# constraint.append((self.cfg.mapping[domain][k], v))
entities = self.db.query(self.services[domain], constraint)
# random.shuffle(entities)
return entities
def update_belief_sys(self, old_s, a):
"""
update belief/goal state with sys action
"""
s = deepcopy(old_s)
a_index = torch.nonzero(a) # get multiple da indices
self.time_step += 1
s['others']['turn'] = self.time_step
# update sys/user dialog act
s['sys_action'] = dict()
# update belief part
das = [self.cfg.idx2da[idx.item()] for idx in a_index]
das = [da.split('~') for da in das]
sorted(das, key=lambda x:x[0]) # sort by domain #all in small
entities = [] if self.topic == '' else self.get_entities(s, self.topic)
return_flag = False
for domain, intent, slot in das:
# belief_domains_lower = [str(item).lower() for item in self.cfg.belief_domains]
if domain in self.cfg.belief_domains and domain != self.topic:
self.topic = domain
entities = self.get_entities(s, domain)
da = '~'.join((domain, intent, slot))
if da in list(s['sys_action'].keys()):
if s['sys_action'][da] == '_blank':
if slot in s['belief_state'][self.topic] and s['belief_state'][self.topic][slot] != '_blank':
s['sys_action'][da] = s['belief_state'][self.topic][slot]
else:
s['sys_action'][da] = 'none'
# if intent == 'request':
# s['sys_action'][da] = '?'
# elif intent in ['nooffer', 'nobook'] and self.topic != '':
# return_flag = True
# if slot in s['belief_state'][self.topic] and s['belief_state'][self.topic][slot] != '?':
# s['sys_action'][da] = s['belief_state'][self.topic][slot]
# else:
# s['sys_action'][da] = 'none'
# elif slot == 'choice':
# s['sys_action'][da] = str(len(entities))
# elif slot == 'none':
# s['sys_action'][da] = 'none'
else:
# num = int(p) - 1
# if self.topic and len(entities) > num and slot in self.cfg.mapping[self.topic]:
# typ = self.cfg.mapping[self.topic][slot]
# if typ in entities[num]:
# s['sys_action'][da] = entities[num][typ]
# else:
# s['sys_action'][da] = 'none'
# else:
# s['sys_action'][da] = 'none'
if not self.topic:
continue
if intent in ['INFORM', 'OFFER']:
discard(s['belief_state'][self.topic], slot, '?')
if slot in s['user_goal'][self.topic] and s['user_goal'][self.topic][slot] == '?':
s['goal_state'][self.topic][slot] = s['sys_action'][da]
# # booked
# if intent == 'inform' and slot == 'car': # taxi
# if 'booked' not in s['belief_state']['taxi']:
# s['belief_state']['taxi']['booked'] = 'taxi-booked'
# elif intent in ['offerbooked', 'book'] and slot == 'ref': # train
# if self.topic in ['taxi', 'hospital', 'police']:
# s['belief_state'][self.topic]['booked'] = f'{self.topic}-booked'
# s['sys_action'][da] = f'{self.topic}-booked'
# elif entities:
# book_domain = entities[0]['ref'].split('-')[0]
# if 'booked' not in s['belief_state'][book_domain] and entities:
# s['belief_state'][book_domain]['booked'] = entities[0]['ref']
# s['sys_action'][da] = entities[0]['ref']
if return_flag:
for da in s['user_action']:
d_usr, i_usr, s_usr = da.split('~')
if i_usr == 'inform' and d_usr == self.topic:
discard(s['belief_state'][d_usr], s_usr)
reload(s['goal_state'], s['user_goal'], self.topic)
if not self.lock_evalutor:
self.evaluator.add_sys_da(s['sys_action'])
return s
def update_belief_usr(self, old_s, a):
"""
update belief/goal state with user action
"""
s = deepcopy(old_s)
a_index = torch.nonzero(a) # get multiple da indices
self.time_step += 1
s['others']['turn'] = self.time_step
s['others']['terminal'] = 1 if (self.cfg.a_dim_usr-1) in a_index else 0
# update sys/user dialog act
s['user_action'] = dict()
s['belief_state'] = {}
# update belief part
das = [self.cfg.idx2da_u[idx.item()] for idx in a_index if idx.item() != self.cfg.a_dim_usr-1]
das = [da.split('~') for da in das]
for itd in das:
s['belief_state'][itd[0]] = {}
if s['invisible_domains']:
for da in das:
if da[0] == s['next_available_domain']:
s['next_available_domain'] = s['invisible_domains'][0]
s['invisible_domains'].remove(s['next_available_domain'])
break
sorted(das, key=lambda x:x[0]) # sort by domain
for domain, intent, slot in das:
# if domain in self.cfg.belief_domains:
self.topic = self.services[domain]
da = '~'.join((domain, intent, slot))
if intent == 'request':
s['user_action'][da] = '?'
# s['belief_state'][self.topic][slot] = '?'
s['belief_state'][domain][slot] = '?'
elif slot == 'none':
s['user_action'][da] = 'none'
else:
if self.topic and slot in s['user_goal'][self.topic] and s['user_goal'][self.services[domain]][slot] != '?':
s['user_action'][da] = s['user_goal'][self.services[domain]][slot]
else:
s['user_action'][da] = 'dont care'
if not self.topic:
continue
if intent == 'inform':
s['belief_state'][domain][slot] = s['user_action'][da]
if slot in s['user_goal'][self.topic] and s['user_goal'][self.topic][slot] != '?':
discard(s['goal_state'][self.topic], slot)
if not self.lock_evalutor:
self.evaluator.add_usr_da(s['user_action'])
return s
def reset(self, random_seed=None):
"""
Args:
random_seed (int):
Returns:
init_state (dict):
"""
pass
def step(self, s, sys_a):
"""
Args:
s (dict):
sys_a (vector):
Returns:
next_s (dict):
terminal (bool):
"""
pass