Upload database.py
Browse files- database.py +110 -0
database.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
from fuzzywuzzy import fuzz
|
5 |
+
from itertools import chain
|
6 |
+
from zipfile import ZipFile
|
7 |
+
from copy import deepcopy
|
8 |
+
from convlab.util.unified_datasets_util import BaseDatabase
|
9 |
+
|
10 |
+
|
11 |
+
class Database(BaseDatabase):
|
12 |
+
def __init__(self):
|
13 |
+
"""extract data.zip and load the database."""
|
14 |
+
archive = ZipFile(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data.zip'))
|
15 |
+
self.domains = ['restaurant', 'hotel', 'attraction', 'train', 'hospital', 'police']
|
16 |
+
self.dbs = {}
|
17 |
+
for domain in self.domains:
|
18 |
+
with archive.open('data/{}_db.json'.format(domain)) as f:
|
19 |
+
self.dbs[domain] = json.loads(f.read())
|
20 |
+
# add some missing information
|
21 |
+
self.dbs['taxi'] = {
|
22 |
+
"taxi_colors": ["black","white","red","yellow","blue","grey"],
|
23 |
+
"taxi_types": ["toyota","skoda","bmw","honda","ford","audi","lexus","volvo","volkswagen","tesla"],
|
24 |
+
"taxi_phone": ["^[0-9]{10}$"]
|
25 |
+
}
|
26 |
+
self.dbs['police'][0]['postcode'] = "cb11jg"
|
27 |
+
for entity in self.dbs['hospital']:
|
28 |
+
entity['postcode'] = "cb20qq"
|
29 |
+
entity['address'] = "Hills Rd, Cambridge"
|
30 |
+
|
31 |
+
self.slot2dbattr = {
|
32 |
+
'open hours': 'openhours',
|
33 |
+
'price range': 'pricerange',
|
34 |
+
'arrive by': 'arriveBy',
|
35 |
+
'leave at': 'leaveAt',
|
36 |
+
'train id': 'trainID'
|
37 |
+
}
|
38 |
+
|
39 |
+
def query(self, domain: str, state: dict, topk: int, ignore_open=False, soft_contraints=(), fuzzy_match_ratio=60) -> list:
|
40 |
+
"""return a list of topk entities (dict containing slot-value pairs) for a given domain based on the dialogue state."""
|
41 |
+
# query the db
|
42 |
+
if domain == 'taxi':
|
43 |
+
return [{'taxi_colors': random.choice(self.dbs[domain]['taxi_colors']),
|
44 |
+
'taxi_types': random.choice(self.dbs[domain]['taxi_types']),
|
45 |
+
'taxi_phone': ''.join([str(random.randint(1, 9)) for _ in range(11)])}]
|
46 |
+
if domain == 'police':
|
47 |
+
return deepcopy(self.dbs['police'])
|
48 |
+
if domain == 'hospital':
|
49 |
+
department = None
|
50 |
+
for key, val in state:
|
51 |
+
if key == 'department':
|
52 |
+
department = val
|
53 |
+
if not department:
|
54 |
+
return deepcopy(self.dbs['hospital'])
|
55 |
+
else:
|
56 |
+
return [deepcopy(x) for x in self.dbs['hospital'] if x['department'].lower() == department.strip().lower()]
|
57 |
+
state = list(map(lambda ele: (self.slot2dbattr.get(ele[0], ele[0]), ele[1]) if not(ele[0] == 'area' and ele[1] == 'center') else ('area', 'centre'), state))
|
58 |
+
|
59 |
+
found = []
|
60 |
+
for i, record in enumerate(self.dbs[domain]):
|
61 |
+
constraints_iterator = zip(state, [False] * len(state))
|
62 |
+
soft_contraints_iterator = zip(soft_contraints, [True] * len(soft_contraints))
|
63 |
+
for (key, val), fuzzy_match in chain(constraints_iterator, soft_contraints_iterator):
|
64 |
+
if val in ["", "dont care", 'not mentioned', "don't care", "dontcare", "do n't care"]:
|
65 |
+
pass
|
66 |
+
else:
|
67 |
+
try:
|
68 |
+
if key not in record:
|
69 |
+
continue
|
70 |
+
if key == 'leaveAt':
|
71 |
+
val1 = int(val.split(':')[0]) * 100 + int(val.split(':')[1])
|
72 |
+
val2 = int(record['leaveAt'].split(':')[0]) * 100 + int(record['leaveAt'].split(':')[1])
|
73 |
+
if val1 > val2:
|
74 |
+
break
|
75 |
+
elif key == 'arriveBy':
|
76 |
+
val1 = int(val.split(':')[0]) * 100 + int(val.split(':')[1])
|
77 |
+
val2 = int(record['arriveBy'].split(':')[0]) * 100 + int(record['arriveBy'].split(':')[1])
|
78 |
+
if val1 < val2:
|
79 |
+
break
|
80 |
+
# elif ignore_open and key in ['destination', 'departure', 'name']:
|
81 |
+
elif ignore_open and key in ['destination', 'departure']:
|
82 |
+
continue
|
83 |
+
elif record[key].strip() == '?':
|
84 |
+
# '?' matches any constraint
|
85 |
+
continue
|
86 |
+
else:
|
87 |
+
if not fuzzy_match:
|
88 |
+
if val.strip().lower() != record[key].strip().lower():
|
89 |
+
break
|
90 |
+
else:
|
91 |
+
if fuzz.partial_ratio(val.strip().lower(), record[key].strip().lower()) < fuzzy_match_ratio:
|
92 |
+
break
|
93 |
+
except:
|
94 |
+
continue
|
95 |
+
else:
|
96 |
+
res = deepcopy(record)
|
97 |
+
res['Ref'] = '{0:08d}'.format(i)
|
98 |
+
found.append(res)
|
99 |
+
if len(found) == topk:
|
100 |
+
return found
|
101 |
+
return found
|
102 |
+
|
103 |
+
|
104 |
+
if __name__ == '__main__':
|
105 |
+
db = Database()
|
106 |
+
assert issubclass(Database, BaseDatabase)
|
107 |
+
assert isinstance(db, BaseDatabase)
|
108 |
+
res = db.query("restaurant", [['price range', 'expensive']], topk=3)
|
109 |
+
print(res, len(res))
|
110 |
+
# print(db.query("hotel", [['price range', 'moderate'], ['stars','4'], ['type', 'guesthouse'], ['internet', 'yes'], ['parking', 'no'], ['area', 'east']]))
|