AnAutomaticPencil's picture
data preprocessing update
a6326c7
from utils import write_jsonl_file, parse, read_line_labels
import os
sent_map = {
"POS": "positive",
"NEU": "neutral",
"NEG": "negative",
}
def get_char_index(lengths, tok_ids):
start = lengths[tok_ids[0]] + tok_ids[0]
end = (
lengths[tok_ids[-1] + 1]
- lengths[tok_ids[0]]
+ start
+ tok_ids[-1]
- tok_ids[0]
)
return start, end
def parse_aspects(utterance, aspects):
toks = utterance.split()
lengths = list(map(lambda x: len(x), toks))
lengths = [0] + lengths
for i in range(1, len(lengths)):
lengths[i] += lengths[i - 1]
parsed_aspects = []
for target, opinion, sentiment in aspects:
target_start, target_end = get_char_index(lengths, target)
opinion_start, opinion_end = get_char_index(lengths, opinion)
target_value = " ".join(toks[target[0] : target[-1] + 1])
opinion_value = " ".join(toks[opinion[0] : opinion[-1] + 1])
assert target_value == utterance[target_start:target_end]
assert opinion_value == utterance[opinion_start:opinion_end]
parsed_aspects.append(
{
"target": {
"value": target_value,
"start": target_start,
"end": target_end,
},
"opinion": {
"value": opinion_value,
"start": opinion_start,
"end": opinion_end,
},
"sentiment": sent_map[sentiment],
}
)
return parsed_aspects
def reformat(args, file):
for domain in os.listdir(args.input_dir):
path = os.path.join(os.path.join(args.input_dir, domain), f"{file}.txt")
data = read_line_labels(path)
dials = []
for line in data:
utterance, aspects = line.strip().split("####")
aspects = eval(aspects)
dial = {
"turn": "single",
"locale": "en",
"dialog": [
{
"roles": ["USER"],
"utterance": utterance,
"aspects": parse_aspects(utterance, aspects),
}
],
}
dials.append(dial)
write_jsonl_file(
dials, os.path.join(os.path.join(args.output_dir, domain), f"{file}.jsonl")
)
def preprocess(args):
reformat(args, "train")
reformat(args, "dev")
reformat(args, "test")
if __name__ == "__main__":
args = parse()
preprocess(args)