DialogZoo / src /preprocess /MultiDoGo.py
AnAutomaticPencil's picture
data preprocessing update
a6326c7
import os
from utils import read_tsv_file, parse, write_jsonl_file
def parse_slot_value_table(utterance, slot_labels):
tokens = utterance.split(" ")
slot_labels = slot_labels.split()
start = -1
record_slot = None
slots = []
for idx, slot in enumerate(slot_labels):
if slot != "O":
# start
if start < 0:
start = idx
record_slot = slot
# end
if idx == (len(slot_labels) - 1) or slot_labels[idx + 1] == "O":
slots.append((record_slot, start, idx + 1))
start = -1
svt = []
prefix_lengths = [0]
for token in tokens:
prefix_lengths.append(prefix_lengths[-1] + len(token) + 1)
for slot in slots:
start = prefix_lengths[slot[1]]
end = prefix_lengths[slot[2]] - 1
assert utterance[start:end] == " ".join(tokens[slot[1] : slot[2]])
svt.append(
{
"slot": slot[0],
"values": [{"value": utterance[start:end], "start": start, "end": end}],
"relation": "=",
}
)
return svt
def preprocess(args, split):
input_dir = args.input_dir
for domain in os.listdir(input_dir):
domain_dir = os.path.join(input_dir, domain)
outdir = os.path.join(args.output_dir, domain)
infile = os.path.join(domain_dir, f"{split}.tsv")
outfile = os.path.join(outdir, f"{split}.jsonl")
data = read_tsv_file(infile)
processed_data = []
for i in range(len(data)):
row = data.iloc[i]
utterance = str(row["utterance"])
intent = str(row["intent"])
slot_labels = str(row["slot-labels"])
assert len(utterance.split(" ")) == len(
slot_labels.split(" ")
), f"{utterance}\t{slot_labels}"
utterance = utterance.replace("\n", "\\n")
processed_data.append(
{
"turn": "single",
"locale": "en",
"dialog": [
{
"roles": ["USER"],
"utterance": utterance,
"active_intents": [intent],
"slots_to_fill": {
"intent": intent,
"slot_value_table": parse_slot_value_table(
utterance, slot_labels
),
},
}
],
}
)
write_jsonl_file(processed_data, outfile)
if __name__ == "__main__":
args = parse()
preprocess(args, "train")
preprocess(args, "dev")
preprocess(args, "test")