-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreprocessing.py
More file actions
executable file
·274 lines (236 loc) · 13.2 KB
/
preprocessing.py
File metadata and controls
executable file
·274 lines (236 loc) · 13.2 KB
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
#!/usr/bin/env python3
"""
intent-preprocessing.py
Preprocesses the data
*full.json => train.tsv
validate_*.json => test.tsv
*.json => dev.tsv
1= BookRestaurant
2 = SearchScreeningEvent
3 = RateBook
4 = PlayMusic
5 = AddToPlaylist
6 = GetWeather
7 = SearchCreativeWork
@Author: Fabian Fey, Gianna Weber
"""
import os
import json
import codecs
path_train=[]
path_dev=[]
path_test=[]
intent_dict = {"BookRestaurant":1,
"SearchScreeningEvent":2,
"RateBook":3,
"PlayMusic":4,
"AddToPlaylist":5,
"GetWeather":6,
"SearchCreativeWork":7
}
# for utterance beginning (intent)
joint_intent_dict = {"BookRestaurant":"BookRestaurant",
"SearchScreeningEvent":"SearchScreeningEvent",
"RateBook":"RateBook",
"PlayMusic":"PlayMusic",
"AddToPlaylist":"AddToPlaylist",
"GetWeather":"GetWeather",
"SearchCreativeWork":"SearchCreativeWork"
}
def removeChar(str, n):
first_part = str[:n]
last_part = str[n+1:]
return first_part + last_part
for subdir, dirs, files in os.walk('Data/'):
for file in files:
if "train" in file and "full" not in file: # dev
path_dev.append(os.path.join(subdir, file))
elif "full" in file: # train
path_train.append(os.path.join(subdir, file))
elif "validate" in file: # test
path_test.append(os.path.join(subdir, file))
def intents(paths, filename):
with open(filename, 'w') as OutputFile:
for path in paths:
with open(path, 'r', encoding='ISO-8859-1') as jsonFile:
print(path)
file = json.load(jsonFile)
for intent in file: # {"AddToPlaylist":[...]}
#print(intent)
for data in file[intent]: # {"AddToPlaylist":[{"data": [...]}, {...}, ...]}
#print(data)
for key in data:
# print(key)
text = []
for entry in data[key]:
#print(entry["text"])
tmpText = entry["text"] # phrases for particular slots
tmpText = tmpText.replace("\n", "")
tmpText = tmpText.replace(" ", " ") # to circumvent newlines withing utterance/phrase, e.g. " \n "
text.append(tmpText) # total utterance
if len("".join(text)) != 0:
print(str(intent_dict[intent])+"\t"+"".join(text)) # mapping from 1-7 to possible intents
OutputFile.write(str(intent_dict[intent])+"\t"+"".join(text)+"\n") # create new data files (dev, test, train) for intents
def slots(paths, slotLabel, slotUtterance):
with open(slotLabel, 'w') as SlotLabelOutputFile:
with open(slotUtterance, 'w') as SlotUtteranceOutputFile:
for path in paths: # iterate over all files
with open(path, 'r', encoding='ISO-8859-1') as jsonFile:
file = json.load(jsonFile)
for intent in file: # {"AddToPlaylist":[...]}
# print(intent)
for data in file[intent]: # {"AddToPlaylist":[{"data": [...]}, {...}, ...]}
# print(data)
for key in data:
# print(key)
text = []
entity = []
for entry in data[key]:
entryText = []
if "entity" in entry: # slot "entity"
utterance = entry["text"] # part of utterances
utterance = utterance.replace("\n", "")
utterance = utterance.replace(" ", " ")
textSplit = utterance.split(" ") # split at whitespace
# "text": "Cita Romántica" has "entity": "playlist" -> text = ["Cita", "Romántica"], entity = ["playlist", "playlist"]
for i in range(0, len(textSplit)):
entity.append(entry["entity"])
text.extend(textSplit)
# print("Text: %s", text)
else:
utterance = entry["text"]
utterance = utterance.replace("\n", "")
utterance = utterance.replace(" ", " ")
# Problem with preceding and following whitespaces: needed to be removed
if utterance == " ":
continue
elif utterance[:1] == " ":
if utterance[-1:] == " ":
tmp = removeChar(utterance, 0)
tmp2 = removeChar(tmp, len(tmp)-1)
entryText.extend(tmp2.split(" "))
else:
tmp = removeChar(utterance, 0)
entryText.extend(tmp.split(" "))
elif utterance[-1:] == " ":
tmp = removeChar(utterance, len(utterance)-1)
entryText.extend(tmp.split(" "))
else:
entryText.extend(utterance.split(" "))
for i in range(0, len(entryText)):
entity.append("NULL")
text.extend(entryText)
#print("".join(text))
utterance = "\t".join(text)
labels = "\t".join(entity)
utterance = utterance.replace("\n", "")
utterance = utterance.replace(" ", " ")
labels = labels.replace("\n", "")
SlotLabelOutputFile.write(labels + "\n")
SlotUtteranceOutputFile.write(utterance + "\n")
def joint_intent_slots(paths, slotLabel, slotUtterance):
with open(slotLabel, 'w') as SlotLabelOutputFile:
with open(slotUtterance, 'w') as SlotUtteranceOutputFile:
for path in paths: # iterate over all files
with open(path, 'r', encoding='ISO-8859-1') as jsonFile:
file = json.load(jsonFile)
for intent in file: # {"AddToPlaylist":[...]}
# print(intent)
for data in file[intent]: # {"AddToPlaylist":[{"data": [...]}, {...}, ...]}
# print(data)
for key in data:
# print(key)
text = []
entity = []
for entry in data[key]:
entryText = []
if "entity" in entry: # slot "entity"
utterance = entry["text"] # part of utterances
utterance = utterance.replace("\n", "")
utterance = utterance.replace(" ", " ")
textSplit = utterance.split(" ") # split at whitespace
# "text": "Cita Romántica" has "entity": "playlist" -> text = ["Cita", "Romántica"], entity = ["playlist", "playlist"]
for i in range(0, len(textSplit)):
entity.append(entry["entity"])
text.extend(textSplit)
# print("Text: %s", text)
else:
utterance = entry["text"]
utterance = utterance.replace("\n", "")
utterance = utterance.replace(" ", " ")
# Problem with preceding and following whitespaces: needed to be removed
if utterance == " ":
continue
elif utterance[:1] == " ":
if utterance[-1:] == " ":
tmp = removeChar(utterance, 0)
tmp2 = removeChar(tmp, len(tmp)-1)
entryText.extend(tmp2.split(" "))
else:
tmp = removeChar(utterance, 0)
entryText.extend(tmp.split(" "))
elif utterance[-1:] == " ":
tmp = removeChar(utterance, len(utterance)-1)
entryText.extend(tmp.split(" "))
else:
entryText.extend(utterance.split(" "))
for i in range(0, len(entryText)):
entity.append("NULL")
text.extend(entryText)
#print("".join(text))
utterance = "\t".join(text)
labels = "\t".join(entity)
utterance = utterance.replace("\n", "")
utterance = utterance.replace(" ", " ")
labels = labels.replace("\n", "")
# SlotLabelOutputFile.write(joint_intent_dict[intent] + "\t" + labels + "\t" + joint_intent_dict[intent] + "\n")
# SlotUtteranceOutputFile.write("BOU\t" + utterance + "\tEUO\n") # BOU beginning of utterance
SlotLabelOutputFile.write(joint_intent_dict[intent] + "\t" + labels + "\n")
SlotUtteranceOutputFile.write("BOU\t" + utterance + "\n") # BOU beginning of utterance
# Will be removed in a future version
def slotCount(path_dev, path_test, path_train):
paths = []
paths.extend(path_dev)
paths.extend(path_test)
paths.extend(path_train)
SlotDict = {}
for path in paths:
with open(path, 'r', encoding='ISO-8859-1') as jsonFile:
file = json.load(jsonFile)
for intent in file: # {"AddToPlaylist":[...]}
# print(intent)
for data in file[intent]: # {"AddToPlaylist":[{"data": [...]}, {...}, ...]}
# print(data)
for key in data:
# print(key)
text = []
entity = []
for entry in data[key]:
entryText = []
if "entity" in entry:
slot = entry["entity"]
slot = slot.replace("_", "")
if slot in SlotDict:
SlotDict[slot] +=1
else:
SlotDict[slot] = 1
else:
if "NULL" in SlotDict:
SlotDict["NULL"] +=1
else:
SlotDict["NULL"] = 1
with open("SlotList.tsv", "w") as slotFile:
for key in SlotDict:
slotFile.write(str(key+"\t"))
print(key, SlotDict[key]) # Slot Verteilung
print(len(SlotDict)) # 39 entity, i.e. slot, types
joint_intent_slots(path_dev, "dev_slot_label.tsv", "dev_slot_Utt.tsv")
joint_intent_slots(path_test, "test_slot_label.tsv", "test_slot_Utt.tsv")
joint_intent_slots(path_train, "train_slot_label.tsv", "train_slot_Utt.tsv")
#slotCount(path_dev, path_test, path_train)
# slots(path_dev, "dev_slot_label.tsv", "dev_slot_Utt.tsv")
# slots(path_test, "test_slot_label.tsv", "test_slot_Utt.tsv")
# slots(path_train, "train_slot_label.tsv", "train_slot_Utt.tsv")
# intents(path_dev, "dev.tsv")
# intents(path_test, "test.tsv")
# intents(path_train, "train.tsv")