-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataLoaderResp.py
145 lines (134 loc) · 6.61 KB
/
DataLoaderResp.py
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
import json
import csv
from tqdm import tqdm
from enum import Enum
from DataProcessor import clip_pad_sentence,clip_pad_context
from Vocab import Vocab
import torch
import pickle
import json as js
import numpy as np
class DataLoaderResp():
def __init__(self, args, dataset, vocab):
self.args = args
self.dataset = dataset
self.vocab = vocab
self.final_topic = json.load(open('./dataset/{}/final_topic.json'.format(self.args.dataset), 'r'))
self.processed_data = []
self.processed_session()
self.user2character_metric = self.get_user2character_metric()
def __iter__(self):
return self
def __len__(self):
return len(self.processed_data)
def __getitem__(self, idx):
return self.processed_data[idx]
def processed_session(self):
for conv in tqdm(self.dataset):
if len(conv) > 5:
processed_session = self.process(conv)
self.processed_data.extend(processed_session)
def process(self, conversation):
session_segs = []
id = int(conversation[0])
contexts = conversation[-3]
conv_id = conversation[-1]
utterances = conversation[1:-3]
uttr_len = len(utterances)
pv_action = []
if self.args.dataset == 'TG-ReDial':
skip_len = 2
elif self.args.dataset == 'PersonaChat':
skip_len = 1
if self.args.gpt2:
for i in range(len(contexts)):
contexts[i] = [i for i in ''.join(contexts[i])]
for i in range(2, uttr_len, skip_len):
if self.args.dataset == 'PersonaChat' and (utterances[i - 1][2][-1] == '[UNK]' or utterances[i][2][-1] == '[UNK]'):
continue
response = utterances[i]
action_R = response[2]
if action_R == []:
continue
resp = response[0]
if self.args.gpt2:
resp = [i for i in ''.join(resp)]
resp, resp_len = clip_pad_sentence(resp, self.args.r_max_len, self.args.PAD_WORD, sos='[CLS]', eos='[SEP]')
resp = self.vocab.tokenizer.convert_tokens_to_ids(resp)
context = contexts[:i]
context_all, context_all_len = clip_pad_context(context, self.args.context_all_max_len, self.args.PAD_WORD, '[SEP]')
context, context_len = clip_pad_context(context, self.args.context_max_len, self.args.PAD_WORD, '[SEP]', pad_suffix=False)
else:
resp, resp_len = clip_pad_sentence(resp, self.args.r_max_len, self.args.PAD_WORD, sos=self.args.BOS_RESPONSE, eos=self.args.EOS_RESPONSE)
resp = self.vocab.word2index(resp)
context = contexts[:i]
context_all, context_all_len = clip_pad_context(context, self.args.context_all_max_len, self.args.PAD_WORD, self.args.SENTENCE_SPLITER)
context, context_len = clip_pad_context(context, self.args.context_max_len, self.args.PAD_WORD, self.args.SENTENCE_SPLITER)
final_topic_len = len(self.final_topic[str(conv_id) + '/' + str(i+1)])
if self.args.not_topic_guide:
state_U = response[1][:-final_topic_len]
else:
state_U = response[1]
topic2context = []
k = 0
for topic in state_U[:-final_topic_len]:
if topic in conversation[k+1][-2]:
topic2context.append(k)
else:
while k <= len(conversation) - 1:
if topic in conversation[k + 1][-2]:
topic2context.append(k)
break
k += 1
for _ in range(final_topic_len):
topic2context.append(i - 1)
if max(topic2context) >= i:
state_U = response[1]
topic2context = []
k = 0
for topic in state_U[:-1]:
if topic in conversation[k + 1][-2]:
topic2context.append(k)
else:
while k <= len(conversation) - 1:
if topic in conversation[k + 1][-2]:
topic2context.append(k)
break
k += 1
topic2context.append(i - 1)
assert len(state_U) == len(topic2context)
if len(topic2context) >= self.args.state_num:
topic2context = topic2context[-self.args.state_num:]
else:
topic2context = topic2context + [0] * (self.args.state_num - len(topic2context))
state_U, state_U_len = clip_pad_sentence(state_U, self.args.state_num, self.args.PAD_WORD)
Seeker = utterances[i - 1]
action_U = Seeker[2]
if self.args.gpt2:
context_all_idx = self.vocab.tokenizer.convert_tokens_to_ids(context_all)
context_idx = self.vocab.tokenizer.convert_tokens_to_ids(context)
else:
context_all_idx = self.vocab.word2index(context_all)
context_idx = self.vocab.word2index(context)
state_U = self.vocab.topic2index(state_U)
a_R, a_R_len = clip_pad_sentence(action_R, self.args.action_num, self.args.PAD_WORD)
a_R = self.vocab.topic2index(a_R)
session_segs.append([id, context_all_idx, context_all_len, context_idx, context_len, state_U, state_U_len, a_R, a_R_len, resp, resp_len, topic2context, 0])
if len(session_segs) != 0:
session_segs[0][-1] = 0
return session_segs
def get_user2character_metric(self):
print('create user2character metric')
max_character_num = max([len(i) for i in self.vocab.user_to_Sentidx.values()])
user2character_metric = np.zeros((self.vocab.n_user + 1, max_character_num), dtype=int)
for user, sent_list in tqdm(self.vocab.user_to_Sentidx.items()):
user_idx = int(user)
for idx, sent_idx in enumerate(sent_list):
user2character_metric[user_idx, idx] = sent_idx
return user2character_metric
def one_hot_scatter(indice, num_classes, dtype=torch.float):
indice_shape = list(indice.shape)
placeholder = torch.zeros(*(indice_shape + [num_classes]), device=indice.device, dtype=dtype)
v = 1 if dtype == torch.long else 1.0
placeholder.scatter_(-1, indice.unsqueeze(-1), v)
return placeholder