zhuqi commited on
Commit
9afcc6e
1 Parent(s): 0cb4b95

Upload database.py

Browse files
Files changed (1) hide show
  1. database.py +67 -0
database.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, download_unified_datasets
9
+
10
+
11
+ class Database(BaseDatabase):
12
+ def __init__(self):
13
+ """extract data.zip and load the database."""
14
+ data_path = download_unified_datasets('camrest', 'data.zip', os.path.dirname(os.path.abspath(__file__)))
15
+ archive = ZipFile(data_path)
16
+ self.dbs = {}
17
+ with archive.open('data/CamRestDB.json') as f:
18
+ self.dbs['restaurant'] = json.loads(f.read())
19
+ self.slot2dbattr = {
20
+ 'price range': 'pricerange',
21
+ }
22
+
23
+ def query(self, domain: str, state: dict, topk: int, ignore_open=False, soft_contraints=(), fuzzy_match_ratio=60) -> list:
24
+ """return a list of topk entities (dict containing slot-value pairs) for a given domain based on the dialogue state."""
25
+ # query the db
26
+ assert domain == 'restaurant'
27
+ 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))
28
+
29
+ found = []
30
+ for i, record in enumerate(self.dbs[domain]):
31
+ constraints_iterator = zip(state, [False] * len(state))
32
+ soft_contraints_iterator = zip(soft_contraints, [True] * len(soft_contraints))
33
+ for (key, val), fuzzy_match in chain(constraints_iterator, soft_contraints_iterator):
34
+ if val in ["", "dont care", 'not mentioned', "don't care", "dontcare", "do n't care"]:
35
+ pass
36
+ else:
37
+ try:
38
+ if key not in record:
39
+ continue
40
+ if record[key].strip() == '?':
41
+ # '?' matches any constraint
42
+ continue
43
+ else:
44
+ if not fuzzy_match:
45
+ if val.strip().lower() != record[key].strip().lower():
46
+ break
47
+ else:
48
+ if fuzz.partial_ratio(val.strip().lower(), record[key].strip().lower()) < fuzzy_match_ratio:
49
+ break
50
+ except:
51
+ continue
52
+ else:
53
+ res = deepcopy(record)
54
+ res['Ref'] = '{0:08d}'.format(i)
55
+ found.append(res)
56
+ if len(found) == topk:
57
+ return found
58
+ return found
59
+
60
+
61
+ if __name__ == '__main__':
62
+ db = Database()
63
+ assert issubclass(Database, BaseDatabase)
64
+ assert isinstance(db, BaseDatabase)
65
+ res = db.query("restaurant", [['price range', 'expensive']], topk=3)
66
+ print(res, len(res))
67
+ # print(db.query("hotel", [['price range', 'moderate'], ['stars','4'], ['type', 'guesthouse'], ['internet', 'yes'], ['parking', 'no'], ['area', 'east']]))