-
Notifications
You must be signed in to change notification settings - Fork 0
/
external_knowledges.py
366 lines (315 loc) · 12.7 KB
/
external_knowledges.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
"""
MTTOD: external_knowledges.py
Implements MultiWoZ JSON Object Handler.
This code is referenced from thu-spmi's damd-multiwoz repository:
(https://github.com/thu-spmi/damd-multiwoz/blob/master/db_ops.py)
Copyright 2021 ETRI LIRS, Yohan Lee
Copyright 2019 Yichi Zhang
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import random
from collections import defaultdict
import sqlite3 as sql
import json
from utils import definitions
from utils.io_utils import load_json, get_or_create_logger
logger = get_or_create_logger(__name__)
class CamRestDB:
def __init__(self, path, dataset):
self.dataset = dataset
self.db_vec_size = 4
self.db = os.path.join(path, 'CamRestDB.db')
db_json_path = self.db.replace('.db', '.json')
self.db_json = json.loads(open(db_json_path).read().lower())
if not os.path.exists(self.db):
self._db_construct(self.db)
self.db = sql.connect(self.db).cursor()
def _db_construct(self, save_dir=None):
all_slots = ['id', 'name', 'food', 'pricerange','area', 'phone', 'postcode', 'address',
'type', 'location']
if save_dir is None:
save_dir = 'data/CamRest676/CamRestDB.db'
conn = sql.connect(save_dir)
cur = conn.cursor()
# create table
exec_create = "CREATE TABLE restaurant("
for slot in all_slots:
exec_create += "%s TEXT ," % slot
exec_create = exec_create[:-1] + ");"
cur.execute(exec_create)
for entry in self.db_json:
slots = ",".join([s for s in all_slots])
exec_insert = "INSERT INTO restaurant(" + slots+")\nVALUES ("
for slot in all_slots:
if entry.get(slot):
exec_insert += '"'+ str(entry[slot])+'",'
else:
exec_insert += 'NULL,'
exec_insert = exec_insert[:-1] + ')'
cur.execute(exec_insert)
conn.commit()
conn.close()
def db_json_search(self, constraints):
match_results = []
for entry in self.db_json:
if 'food' not in entry:
entry_values = entry['area'] + ' ' + entry['pricerange']
else:
entry_values = entry['area'] + ' ' + entry['food'] + ' ' + entry['pricerange']
match = True
for s, v in constraints.items():
if v in ['dontcare', "do n't care", 'any']:
continue
if v not in entry_values: # v is str here
match = False
break
if match:
match_results.append(entry)
# print(len(match_results))
return match_results
def get_match_num(self, constraints, return_entry=False):
match = {'general': ''}
entry = {}
for domain in definitions.ALL_DOMAINS[self.dataset]:
match[domain] = ''
if constraints.get(domain):
matched_ents = self.db_json_search(constraints[domain])
match[domain] = len(matched_ents)
if return_entry:
entry[domain] = matched_ents
if return_entry:
return entry
return match
def addDBIndicator(self, domain, match_num, return_num=False):
db_index = match_num
if db_index >= self.db_vec_size:
db_index = self.db_vec_size - 1
db_indicator = '[db_%s]' % db_index
return db_indicator
def bspan_to_DBpointer(self, constraint_dict, match_num):
# print(constraint_dict)
match_num = len(self.db_json_search(constraint_dict))
db_index = match_num
if db_index >= self.db_vec_size:
db_index = self.db_vec_size - 1
db_indicator = '[db_%s]' % db_index
return db_indicator
class MultiWozDB:
""" MultiWoZ JSON Handler class """
def __init__(self, db_dir, dataset):
self.dbs = {}
self.dataset = dataset
for domain in definitions.ALL_DOMAINS[self.dataset]:
self.dbs[domain] = load_json(os.path.join(db_dir,
"{}_db_processed.json".format(domain)))
self.db_domains = ["attraction", "hotel", "restaurant", "train"]
extractive_ontology = {}
for db_domain in self.db_domains:
extractive_ontology[db_domain] = defaultdict(list)
dbs = self.dbs[db_domain]
for ent in dbs:
for slot in definitions.EXTRACTIVE_SLOT:
if slot in ["leave", "arrive"]:
continue
if slot not in ent or ent[slot] in extractive_ontology[db_domain][slot]:
continue
extractive_ontology[db_domain][slot].append(ent[slot])
self.extractive_ontology = extractive_ontology
def one_hot_vector(self, domain, num):
"""Return number of available entities for particular domain."""
vector = [0, 0, 0, 0]
if num == '':
return vector
if domain != 'train':
if num == 0:
vector = [1, 0, 0, 0]
elif num == 1:
vector = [0, 1, 0, 0]
elif num <= 3:
vector = [0, 0, 1, 0]
else:
vector = [0, 0, 0, 1]
else:
if num == 0:
vector = [1, 0, 0, 0]
elif num <= 5:
vector = [0, 1, 0, 0]
elif num <= 10:
vector = [0, 0, 1, 0]
else:
vector = [0, 0, 0, 1]
return vector
def addBookingPointer(self, turn_da):
"""Add information about availability of the booking option."""
# Booking pointer
# Do not consider booking two things in a single turn.
vector = [0, 0]
if turn_da.get('booking-nobook'):
vector = [1, 0]
if turn_da.get('booking-book') or turn_da.get('train-offerbooked'):
vector = [0, 1]
return vector
def addDBPointer(self, domain, match_num, return_num=False):
"""Create database pointer for all related domains."""
# if turn_domains is None:
# turn_domains = db_domains
if domain in self.db_domains:
vector = self.one_hot_vector(domain, match_num)
else:
vector = [0, 0, 0, 0]
return vector
def addDBIndicator(self, domain, match_num, return_num=False):
"""Create database indicator for all related domains."""
# if turn_domains is None:
# turn_domains = db_domains
if domain in self.db_domains:
vector = self.one_hot_vector(domain, match_num)
else:
vector = [0, 0, 0, 0]
# '[db_nores]', '[db_0]', '[db_1]', '[db_2]', '[db_3]'
if vector == [0, 0, 0, 0]:
indicator = '[db_null]'
else:
indicator = '[db_%s]' % vector.index(1)
return indicator
def get_match_num(self, constraints, return_entry=False):
"""Create database pointer for all related domains."""
match = {'general': ''}
entry = {}
# if turn_domains is None:
# turn_domains = db_domains
for domain in definitions.ALL_DOMAINS[self.dataset]:
match[domain] = ''
if domain in self.db_domains and constraints.get(domain):
matched_ents = self.queryJsons(domain, constraints[domain])
match[domain] = len(matched_ents)
if return_entry:
entry[domain] = matched_ents
if return_entry:
return entry
return match
def pointerBack(self, vector, domain):
# multi domain implementation
# domnum = cfg.domain_num
if domain.endswith(']'):
domain = domain[1:-1]
if domain != 'train':
nummap = {
0: '0',
1: '1',
2: '2-3',
3: '>3'
}
else:
nummap = {
0: '0',
1: '1-5',
2: '6-10',
3: '>10'
}
if vector[:4] == [0, 0, 0, 0]:
report = ''
else:
num = vector.index(1)
report = domain+': '+nummap[num] + '; '
if vector[-2] == 0 and vector[-1] == 1:
report += 'booking: ok'
if vector[-2] == 1 and vector[-1] == 0:
report += 'booking: unable'
return report
def queryJsons(self, domain, constraints, exactly_match=True, return_name=False):
"""Returns the list of entities for a given domain
based on the annotation of the belief state
constraints: dict e.g. {'pricerange': 'cheap', 'area': 'west'}
"""
# query the db
if domain == 'taxi':
return [{'taxi_colors': random.choice(self.dbs[domain]['taxi_colors']),
'taxi_types': random.choice(self.dbs[domain]['taxi_types']),
'taxi_phone': [random.randint(1, 9) for _ in range(10)]}]
if domain == 'police':
return self.dbs['police']
if domain == 'hospital':
if constraints.get('department'):
for entry in self.dbs['hospital']:
if entry.get('department') == constraints.get('department'):
return [entry]
else:
return []
valid_cons = False
for v in constraints.values():
if v not in ["not mentioned", "", "none"]:
valid_cons = True
if not valid_cons:
return []
match_result = []
if 'name' in constraints:
for db_ent in self.dbs[domain]:
if 'name' in db_ent:
cons = constraints['name']
dbn = db_ent['name']
if cons == dbn:
db_ent = db_ent if not return_name else db_ent['name']
match_result.append(db_ent)
return match_result
for db_ent in self.dbs[domain]:
match = True
for s, v in constraints.items():
if v == "none":
continue
if s == 'name':
continue
if s in ['people', 'stay'] or (domain == 'hotel' and s == 'day') or \
(domain == 'restaurant' and s in ['day', 'time']):
continue
skip_case = {"don't care": 1, "do n't care": 1,
"dont care": 1, "not mentioned": 1, "dontcare": 1, "": 1}
if skip_case.get(v):
continue
if s not in db_ent:
# logger.warning('Searching warning: slot %s not in %s db', s, domain)
match = False
break
# v = 'guesthouse' if v == 'guest house' else v
# v = 'swimmingpool' if v == 'swimming pool' else v
v = 'yes' if v == 'free' else v
if s in ['arrive', 'leave']:
try:
# raise error if time value is not xx:xx format
h, m = v.split(':')
v = int(h)*60+int(m)
except ValueError:
match = False
break
time = int(db_ent[s].split(':')[0])*60 + \
int(db_ent[s].split(':')[1])
if s == 'arrive' and v > time:
match = False
if s == 'leave' and v < time:
match = False
else:
if exactly_match and v != db_ent[s]:
match = False
break
elif v not in db_ent[s]:
match = False
break
if match:
match_result.append(db_ent)
if not return_name:
return match_result
else:
if domain == 'train':
match_result = [e['id'] for e in match_result]
else:
match_result = [e['name'] for e in match_result]
return match_result