-
Notifications
You must be signed in to change notification settings - Fork 1
/
story_converter.py
342 lines (260 loc) · 9.71 KB
/
story_converter.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
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
import argparse
import csv
import sys
import re
def main() -> None:
'''
Parses through the command-line arguments, reading in the path to the
stories & generic utterances/intents CSV.
'''
parser = argparse.ArgumentParser(
description='Converts the stories and generic CSVs to a file\
format required for Rasa training')
parser.add_argument(
'--stories',
dest="stories",
help='Chatbot story CSV',
required=True)
parser.add_argument(
'--utter',
dest="utter",
help='Utterances CSV',
required=True)
parser.add_argument(
'--intent',
dest="intent",
help='Intents CSV',
required=True)
args = parser.parse_args()
story_dat, _ = read_csv(args.stories)
intent_dat, fields = read_csv(args.intent)
utter_dat, _ = read_csv(args.utter)
gen_dict = create_generic(fields, intent_dat, utter_dat)
story_str, intents, utterances, buttons = generate_stories(story_dat, gen_dict)
nlu_str = generate_nlu(intents, gen_dict)
domain_str = generate_domain(intents, utterances, buttons)
store_file(story_str, "stories.md")
store_file(nlu_str, "nlu.md")
store_file(domain_str, "domain.yml")
def store_file(
file_str:str,
file_path:str) -> None:
'''
Take the string and store it in the file path.
:param file_str: The data to be stored in the file path.
:param file_path: The file path that stores file_str.
'''
with open(file_path, "w", encoding='utf-8') as open_file:
open_file.write(file_str)
print("Data has been stored in %s" % file_path)
def generate_domain(
intents:dict,
utterances:dict,
buttons:dict) -> str:
'''
Iterate through the intents & utter dicts and produce the domain.md string
:param intents: dictionary of the intents.
:param utterances: dictionary of the utterances.
:param buttons: dictionary of the buttons.
:returns domain_str: string of domain.yaml
'''
domain_str = "intents:\n"
template_str = "\nresponses:\n"
for intent in intents.keys():
domain_str += (" - %s\n" % intent)
domain_str += "\nactions:\n"
for utter in utterances.keys():
domain_str += (" - %s\n" % utter)
template_str += (" %s:\n" % utter)
for utter_sample in utterances[utter]:
utter_norm = utter_sample.replace("\"", "\'")
template_str += (" - text: \"%s\"\n" % utter_sample)
if utter in buttons:
template_str += (" buttons:\n")
for title in buttons[utter]:
title_norm = title.replace("\"", "\'")
payload_norm = re.sub(r'[^\w\s]','',title_norm).replace(" ", "_")
template_str += (" - title: \"%s\"\n" % title_norm)
template_str += (" payload: /%s\n" % payload_norm)
template_str += "\n"
domain_str += template_str
domain_str += "session_config:\n"
domain_str += " session_expiration_time: 60\n"
domain_str += " carry_over_slots_to_new_session: true\n"
return domain_str
def generate_nlu(
intents:dict,
gen_dict: dict) -> str:
'''
Iterate through the intents dict and produce the nlu.md string
:param intents: dictionary of the intents.
:param gen_dict: dictionary of the generic data.
:returns nlu_str: string of the nlu.md
'''
nlu_str = ""
for intent in intents.keys():
if(intents[intent] != set()):
nlu_str += ("## intent:%s\n" % intent)
for example in intents[intent]:
nlu_str += ("- %s\n" % example)
nlu_str += "\n"
for gen in gen_dict.keys():
if gen in intents:
nlu_str += ("## intent:%s\n" % gen)
for gen_dat in gen_dict[gen]:
nlu_str += ("- %s\n" % gen_dat)
nlu_str += "\n"
return nlu_str
def parse_utter(utter_dat:list) -> dict:
'''
Parses through the utterance data and stores them into a dict.
:param utter_dat: list of the rows from the generic utterance CSV
:return gen_dat: dict of utterances
'''
generic_name = ""
gen_dat = {}
for row in utter_dat:
if (row[0] == "GENNAME"):
generic_name = row[1]
gen_dat[generic_name] = []
elif (row[0] == "GENERIC"):
if (generic_name not in gen_dat):
print("Error: %s has not been defined." % generic_name)
else:
gen_dat[generic_name].append(row[1])
elif (row[0] == ""):
pass
else:
print("Error: Invalid format of %s in utterance dataset." % row[0])
exit()
return gen_dat
def create_generic(
fields:list,
intent_dat:list,
utter_dat:list) -> dict:
'''
Parses through the generic data rows and creates the list of generic
responses.
Example:
gen_dict = {
"REJECT" : [
"No thank you.",
"Nope.",
"I am not interested.",
"No thanks.",
"No.",
"Nah."
]
}
:param fields: list of strs that are the fields of the CSV data
:param intent_dat: list of str lists that represent each row of the intent
data CSV
:param utter_dat: list of str lists that represent each row of the utter
data CSV
:returns gen_dict: dictionary of the generic data
'''
gen_dict = parse_utter(utter_dat)
dict_index = {}
# Add fields with empty lists to the dict
for i, field in enumerate(fields):
gen_dict[field] = []
dict_index[str(i)] = field
# Add each generic sample to the dictionary
for row in intent_dat:
for i, col in enumerate(row):
if (col != ''):
gen_dict[dict_index[str(i)]].append(col)
print(gen_dict)
return gen_dict
def generate_stories(
stories:list,
gen_dict:dict) -> tuple:
'''
Parses the list of stories and creates the markdown files.
:param stories: list of string lists which is each row of the stories CSV.
:param gen_dict: dictionary of the generic label and its data as a list of
strings.
:returns story_str: string of the story.md
:returns intents: dict of the intent and its examples
:returns utterances: dict of the utterance and its raw string
:returns buttons: dict of utterance and its button
'''
intents = {}
utterances = {}
buttons = {}
story_str = ""
path_name = ""
print("gen dict", gen_dict)
for story_row in stories:
story_type = story_row[0]
story_dets = story_row[1:]
if (story_type == "PATH"):
path_name = story_dets[0]
story_str += "## %s\n" % story_dets[0]
elif (story_type == "INTENT"):
if (story_dets[0] in gen_dict):
story_str += ("* %s\n" % story_dets[0])
intents[story_dets[0]] = set()
else:
curr_intent = re.sub(r'[^\w\s]','',story_dets[0])
curr_intent = curr_intent.replace(" ", "_")
story_str += ("* %s\n" % curr_intent)
if (curr_intent not in intents):
intents[curr_intent] = set()
for story_det in story_dets:
if (story_det != ''):
intents[curr_intent].add(story_det)
elif (story_type == "UTTER"):
curr_utter = re.sub(r'[^\w\s]','',story_dets[0])
curr_utter = "utter_%s" % curr_utter.replace(" ", "_")
story_str += (" - %s\n" % curr_utter)
if story_dets[0] in gen_dict:
utterances[curr_utter] = gen_dict[story_dets[0]]
else:
utterances[curr_utter] = [story_dets[0]]
elif (story_type == "BUTTON"):
curr_utter += "_button"
story_str += (" - %s\n" % curr_utter)
buttons[curr_utter] = [story_det for story_det in story_dets[1:] if story_det != '']
utterances[curr_utter] = [story_dets[0]]
elif ((story_type == "GENERIC") or (story_type == "GENNAME")):
print("Generic utterance... skipping...")
elif (story_type == ''):
story_str += "\n"
print("Empty row... Skipping...")
else:
print("Error: Invalid story type of %s" % story_type)
exit()
# print(utterances)
return story_str, intents, utterances, buttons
def read_csv(csv_path: str) -> list:
'''
Reads the CSV row-by-row and each column in a list.
An example is as follows:
csv_contents = [
[
"Yes",
"No thank you",
"Have a great day"
],
[
"I would like to know.",
"Nope.",
"Good bye!"
]
]
:param csv_path: Path to the QA pairs CSV
:returns csv_contents: A list of string lists which are each row of the CSV.
'''
csv_contents = []
with open(csv_path, 'r', encoding='utf-8') as csv_file:
csvreader = csv.reader(csv_file)
fields = next(csvreader)
for row in csvreader:
row_dat = []
for col in row:
row_dat.append(col)
csv_contents.append(row_dat)
return csv_contents, fields
if __name__ == "__main__":
main()