File size: 19,249 Bytes
a6326c7 |
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 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 |
# Refer https://github.com/thu-spmi/damd-multiwoz/blob/master/preprocess.py
from utils import parse, read_json_file, read_line_labels, write_json_file
import os, re, json, spacy
from collections import OrderedDict
from tqdm import tqdm
import shutil
all_domains = [
"restaurant",
"hotel",
"attraction",
"train",
"taxi",
"police",
"hospital",
]
mapping_pairs = {
"it 's": "it is",
"don 't": "do not",
"doesn 't": "does not",
"didn 't": "did not",
"you 'd": "you would",
"you 're": "you are",
"you 'll": "you will",
"i 'm": "i am",
"they 're": "they are",
"that 's": "that is",
"what 's": "what is",
"couldn 't": "could not",
"i 've": "i have",
"we 've": "we have",
"can 't": "cannot",
"i 'd": "i would",
"aren 't": "are not",
"isn 't": "is not",
"wasn 't": "was not",
"weren 't": "were not",
"won 't": "will not",
"there 's": "there is",
"there 're": "there are",
". .": ".",
"restaurants": "restaurant -s",
"hotels": "hotel -s",
"laptops": "laptop -s",
"cheaper": "cheap -er",
"dinners": "dinner -s",
"lunches": "lunch -s",
"breakfasts": "breakfast -s",
"expensively": "expensive -ly",
"moderately": "moderate -ly",
"cheaply": "cheap -ly",
"prices": "price -s",
"places": "place -s",
"venues": "venue -s",
"ranges": "range -s",
"meals": "meal -s",
"locations": "location -s",
"areas": "area -s",
"policies": "policy -s",
"children": "child -s",
"kids": "kid -s",
"kidfriendly": "kid friendly",
"cards": "card -s",
"upmarket": "expensive",
"inpricey": "cheap",
"inches": "inch -s",
"uses": "use -s",
"dimensions": "dimension -s",
"driverange": "drive range",
"includes": "include -s",
"computers": "computer -s",
"machines": "machine -s",
"families": "family -s",
"ratings": "rating -s",
"constraints": "constraint -s",
"pricerange": "price range",
"batteryrating": "battery rating",
"requirements": "requirement -s",
"drives": "drive -s",
"specifications": "specification -s",
"weightrange": "weight range",
"harddrive": "hard drive",
"batterylife": "battery life",
"businesses": "business -s",
"hours": "hour -s",
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
"ten": "10",
"eleven": "11",
"twelve": "12",
"anywhere": "any where",
"good bye": "goodbye",
}
normlize_slot_names = {
"car type": "car",
"entrance fee": "price",
"duration": "time",
"leaveat": "leave",
"arriveby": "arrive",
"trainid": "id",
}
def clean_time(utter):
utter = re.sub(
r"(\d+) ([ap]\.?m)", lambda x: x.group(1) + x.group(2), utter
) # 9 am -> 9am
utter = re.sub(r"((?<!\d)\d:\d+)(am)?", r"0\1", utter)
utter = re.sub(r"((?<!\d)\d)am", r"0\1:00", utter)
utter = re.sub(r"((?<!\d)\d)pm", lambda x: str(int(x.group(1)) + 12) + ":00", utter)
utter = re.sub(
r"(\d+)(:\d+)pm", lambda x: str(int(x.group(1)) + 12) + x.group(2), utter
)
utter = re.sub(r"(\d+)a\.?m", r"\1", utter)
return utter
def clean_text(text):
text = text.strip()
text = text.lower()
text = text.replace("’", "'")
text = text.replace("‘", "'")
text = text.replace(";", ",")
text = text.replace('"', " ")
text = text.replace("/", " and ")
text = text.replace("don't", "do n't")
text = clean_time(text)
baddata = {
r"c\.b (\d), (\d) ([a-z])\.([a-z])": r"cb\1\2\3\4",
"c.b. 1 7 d.y": "cb17dy",
"c.b.1 7 d.y": "cb17dy",
"c.b 25, 9 a.q": "cb259aq",
"isc.b 25, 9 a.q": "is cb259aq",
"c.b2, 1 u.f": "cb21uf",
"c.b 1,2 q.a": "cb12qa",
"0-122-336-5664": "01223365664",
"postcodecb21rs": "postcode cb21rs",
r"i\.d": "id",
" i d ": "id",
"Telephone:01223358966": "Telephone: 01223358966",
"depature": "departure",
"depearting": "departing",
"-type": " type",
r"b[\s]?&[\s]?b": "bed and breakfast",
"b and b": "bed and breakfast",
r"guesthouse[s]?": "guest house",
r"swimmingpool[s]?": "swimming pool",
"wo n't": "will not",
" 'd ": " would ",
" 'm ": " am ",
" 're' ": " are ",
" 'll' ": " will ",
" 've ": " have ",
r"^\'": "",
r"\'$": "",
}
for tmpl, good in baddata.items():
text = re.sub(tmpl, good, text)
text = re.sub(r"([a-zT]+)\.([a-z])", r"\1 . \2", text) # 'abc.xyz' -> 'abc . xyz'
text = re.sub(r"(\w+)\.\.? ", r"\1 . ", text) # if 'abc. ' -> 'abc . '
for fromx in mapping_pairs:
tox = mapping_pairs[fromx]
text = " " + text + " "
text = text.replace(" " + fromx + " ", " " + tox + " ")[1:-1]
return text
def clean_slot_values(domain, slot, value):
value = clean_text(value)
if not value:
value = ""
elif value == "not mentioned":
value = ""
elif domain == "attraction":
if slot == "name":
if value == "t":
value = ""
if value == "trinity":
value = "trinity college"
elif slot == "area":
if value in ["town centre", "cent", "center", "ce"]:
value = "centre"
elif value in ["ely", "in town", "museum", "norwich", "same area as hotel"]:
value = ""
elif value in ["we"]:
value = "west"
elif slot == "type":
if value in ["m", "mus", "musuem"]:
value = "museum"
elif value in ["art", "architectural"]:
value = "architecture"
elif value in ["churches"]:
value = "church"
elif value in ["coll"]:
value = "college"
elif value in ["concert", "concerthall"]:
value = "concert hall"
elif value in ["night club"]:
value = "nightclub"
elif value in ["mutiple sports", "mutliple sports", "sports", "galleria"]:
value = "multiple sports"
elif value in ["ol", "science", "gastropub", "la raza"]:
value = ""
elif value in ["swimmingpool", "pool"]:
value = "swimming pool"
elif value in ["fun"]:
value = "entertainment"
elif domain == "hotel":
if slot == "area":
if value in ["cen", "centre of town", "near city center", "center"]:
value = "centre"
elif value in ["east area", "east side"]:
value = "east"
elif value in ["in the north", "north part of town"]:
value = "north"
elif value in ["we"]:
value = "west"
elif slot == "day":
if value == "monda":
value = "monday"
elif value == "t":
value = "tuesday"
elif slot == "name":
if value == "uni":
value = "university arms hotel"
elif value == "university arms":
value = "university arms hotel"
elif value == "acron":
value = "acorn guest house"
elif value == "ashley":
value = "ashley hotel"
elif value == "arbury lodge guesthouse":
value = "arbury lodge guest house"
elif value == "la":
value = "la margherit"
elif value == "no":
value = ""
elif slot == "internet":
if value == "does not":
value = "no"
elif value in ["y", "free", "free internet"]:
value = "yes"
elif value in ["4"]:
value = ""
elif slot == "parking":
if value == "n":
value = "no"
elif value in ["free parking"]:
value = "yes"
elif value in ["y"]:
value = "yes"
elif slot in ["pricerange", "price range"]:
slot = "pricerange"
if value == "moderately":
value = "moderate"
elif value in ["any"]:
value = "do n't care"
elif value in ["any"]:
value = "do n't care"
elif value in ["inexpensive"]:
value = "cheap"
elif value in ["2", "4"]:
value = ""
elif slot == "stars":
if value == "two":
value = "2"
elif value == "three":
value = "3"
elif value in ["4-star", "4 stars", "4 star", "four star", "four stars"]:
value = "4"
elif slot == "type":
if value == "0 star rarting":
value = ""
elif value == "guesthouse":
value = "guest house"
elif value not in ["hotel", "guest house", "do n't care"]:
value = ""
elif domain == "restaurant":
if slot == "area":
if value in [
"center",
"scentre",
"center of town",
"city center",
"cb30aq",
"town center",
"centre of cambridge",
"city centre",
]:
value = "centre"
elif value == "west part of town":
value = "west"
elif value == "n":
value = "north"
elif value in ["the south"]:
value = "south"
elif value not in [
"centre",
"south",
"do n't care",
"west",
"east",
"north",
]:
value = ""
elif slot == "day":
if value == "monda":
value = "monday"
elif value == "t":
value = "tuesday"
elif slot in ["pricerange", "price range"]:
slot = "pricerange"
if value in ["moderately", "mode", "mo"]:
value = "moderate"
elif value in ["not"]:
value = ""
elif value in ["inexpensive", "ch"]:
value = "cheap"
elif slot == "food":
if value == "barbecue":
value = "barbeque"
elif slot == "pricerange":
if value == "moderately":
value = "moderate"
elif slot == "time":
if value == "9:00":
value = "09:00"
elif value == "9:45":
value = "09:45"
elif value == "1330":
value = "13:30"
elif value == "1430":
value = "14:30"
elif value == "9:15":
value = "09:15"
elif value == "9:30":
value = "09:30"
elif value == "1830":
value = "18:30"
elif value == "9":
value = "09:00"
elif value == "2:00":
value = "14:00"
elif value == "1:00":
value = "13:00"
elif value == "3:00":
value = "15:00"
elif domain == "taxi":
if slot in ["arriveBy", "arrive by"]:
slot = "arriveby"
if value == "1530":
value = "15:30"
elif value == "15 minutes":
value = ""
elif slot in ["leaveAt", "leave at"]:
slot = "leaveat"
if value == "1:00":
value = "01:00"
elif value == "21:4":
value = "21:04"
elif value == "4:15":
value = "04:15"
elif value == "5:45":
value = "05:45"
elif value == "0700":
value = "07:00"
elif value == "4:45":
value = "04:45"
elif value == "8:30":
value = "08:30"
elif value == "9:30":
value = "09:30"
value = value.replace(".", ":")
elif domain == "train":
if slot in ["arriveBy", "arrive by"]:
slot = "arriveby"
if value == "1":
value = "01:00"
elif value in ["does not care", "doesnt care", "doesn't care"]:
value = "do n't care"
elif value == "8:30":
value = "08:30"
elif value == "not 15:45":
value = ""
value = value.replace(".", ":")
elif slot == "day":
if value == "doesnt care" or value == "doesn't care":
value = "do n't care"
elif slot in ["leaveAt", "leave at"]:
slot = "leaveat"
if value == "2:30":
value = "02:30"
elif value == "7:54":
value = "07:54"
elif value == "after 5:45 pm":
value = "17:45"
elif value in ["early evening", "friday", "sunday", "tuesday", "afternoon"]:
value = ""
elif value == "12":
value = "12:00"
elif value == "1030":
value = "10:30"
elif value == "1700":
value = "17:00"
elif value in [
"does not care",
"doesnt care",
"do nt care",
"doesn't care",
]:
value = "do n't care"
value = value.replace(".", ":")
if value in ["dont care", "don't care", "do nt care", "doesn't care"]:
value = "do n't care"
if normlize_slot_names.get(slot):
slot = normlize_slot_names[slot]
return slot, value
def parse_belief_state(raw, dial_domains, constraint_dict, model):
for domain in dial_domains:
if not constraint_dict.get(domain):
constraint_dict[domain] = OrderedDict()
info_sv = raw[domain]["semi"]
for s, v in info_sv.items():
s, v = clean_slot_values(domain, s, v)
if len(v.split()) > 1:
v = " ".join([token.text for token in model(v)]).strip()
if v != "":
constraint_dict[domain][s] = v
book_sv = raw[domain]["book"]
for s, v in book_sv.items():
if s == "booked":
continue
s, v = clean_slot_values(domain, s, v)
if len(v.split()) > 1:
v = " ".join([token.text for token in model(v)]).strip()
if v != "":
constraint_dict[domain][s] = v
belief_state = []
for domain in constraint_dict:
cur_domain_bs = {
"intent": "", # FIXME
"informed_slot_value_table": [],
"requested_slots": [], # FIXME
"domain": domain,
}
for slot in constraint_dict[domain]:
cur_domain_bs["informed_slot_value_table"].append(
{
"slot": slot,
"values": [
{
"value": constraint_dict[domain][slot],
"cononical_value": constraint_dict[domain][slot],
}
],
"relation": "=",
}
)
belief_state.append(cur_domain_bs)
return constraint_dict, belief_state
def preprocess(args):
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
data = read_json_file(os.path.join(args.input_dir, "data.json"))
test_split = read_line_labels(os.path.join(args.input_dir, "testListFile.txt"))
dev_split = read_line_labels(os.path.join(args.input_dir, "valListFile.txt"))
model = spacy.load("en_core_web_sm")
with open(os.path.join(args.output_dir, "train.jsonl"), "w") as train_writer, open(
os.path.join(args.output_dir, "dev.jsonl"), "w"
) as dev_writer, open(
os.path.join(args.output_dir, "test.jsonl"), "w"
) as test_writer:
for dial_id in tqdm(data):
origin_dialog = data[dial_id]
constraint_dict = OrderedDict()
# preprocess current dialogue
dialog = {
"turn": "multi",
"domain": [], # FIXME
"dialog": [],
}
# parse all domains
dial_domains = []
for dom, g in origin_dialog["goal"].items():
if dom != "topic" and dom != "message" and g:
if dom in all_domains:
dial_domains.append(dom)
for _, dial_turn in enumerate(origin_dialog["log"]):
dial_state = dial_turn["metadata"]
utterance = " ".join(clean_text(dial_turn["text"]).split())
if not dial_state: # user
new_turn = {
"roles": ["USER"],
"utterance": utterance,
"dialog_acts": [], # FIXME
}
else: # system
constraint_dict, new_bf_state = parse_belief_state(
dial_state, dial_domains, constraint_dict, model
)
dialog["dialog"][-1]["belief_state"] = new_bf_state
new_turn = {
"roles": ["SYSTEM"],
"utterance": utterance,
"dialog_acts": [], # FIXME
}
dialog["dialog"].append(new_turn)
# write to file
if dial_id in test_split:
test_writer.write(json.dumps(dialog) + "\n")
elif dial_id in dev_split:
dev_writer.write(json.dumps(dialog) + "\n")
else:
train_writer.write(json.dumps(dialog) + "\n")
if __name__ == "__main__":
args = parse()
preprocess(args)
schema = {
"taxi": ["leave", "destination", "departure", "arrive"],
"police": [],
"hospital": ["department"],
"hotel": [
"type",
"parking",
"pricerange",
"internet",
"stay",
"day",
"people",
"area",
"stars",
"name",
],
"attraction": ["area", "type", "name"],
"train": ["destination", "day", "arrive", "departure", "people", "leave"],
"restaurant": ["food", "pricerange", "area", "name", "time", "day", "people"],
}
ontology = {domain: {slot: True for slot in schema[domain]} for domain in schema}
write_json_file(ontology, os.path.join(args.output_dir, "train_ontology.json"))
shutil.copyfile(
os.path.join(args.output_dir, "train_ontology.json"),
os.path.join(args.output_dir, "dev_ontology.json"),
)
shutil.copyfile(
os.path.join(args.output_dir, "train_ontology.json"),
os.path.join(args.output_dir, "test_ontology.json"),
)
|