preprocessing.py 23.4 KB
Newer Older
zihanl's avatar
zihanl committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
zihanl's avatar
zihanl committed
15

zihanl's avatar
zihanl committed
16
17
"""Preprocessing for Wizard of Wikipedia and Wizard of Internet datasets"""

root's avatar
root committed
18
import torch
zihanl's avatar
zihanl committed
19
20
21
import argparse
from nltk import word_tokenize
from tqdm import tqdm
zihanl's avatar
zihanl committed
22
23
import numpy as np
import json
zihanl's avatar
zihanl committed
24

root's avatar
root committed
25
def get_args():
zihanl's avatar
zihanl committed
26
27
    parser = argparse.ArgumentParser(description="Preprocessing")

root's avatar
root committed
28
    parser.add_argument("--func", type=str, default=None,
zihanl's avatar
zihanl committed
29
                        help="choose to run which function")
zihanl's avatar
zihanl committed
30
    parser.add_argument("--raw_file", type=str, default=None,
zihanl's avatar
zihanl committed
31
                        help="path of the input file")
zihanl's avatar
zihanl committed
32
33
34
35
36
37
38
39
    parser.add_argument("--processed_file", type=str, default=None,
                        help="path of the output file")
    parser.add_argument("--knwl_ref_file", type=str, default=None,
                        help="path of the knowledge reference file")
    parser.add_argument("--resp_ref_file", type=str, default=None,
                        help="path of the knowledge reference file")
    parser.add_argument("--knwl_gen_file", type=str, default=None,
                        help="path of the generated knowledge file")
root's avatar
root committed
40
    parser.add_argument("--test_file", type=str, default=None,
zihanl's avatar
zihanl committed
41
                        help="path of the test file")
root's avatar
root committed
42
    parser.add_argument("--train_file", type=str, default=None,
zihanl's avatar
zihanl committed
43
                        help="path of the train file")
root's avatar
root committed
44
    parser.add_argument("--model_file", type=str, default=None,
zihanl's avatar
zihanl committed
45
                        help="path of the model file")
root's avatar
root committed
46
    parser.add_argument("--data_type", type=str, default=None,
zihanl's avatar
zihanl committed
47
48
                        help="data types, choose one out of three types: \
                              wow_seen, wow_unseen, and woi")
root's avatar
root committed
49
    parser.add_argument("--seed", type=int, default=1234,
zihanl's avatar
zihanl committed
50
                        help="random seed")
zihanl's avatar
zihanl committed
51

root's avatar
root committed
52
53
    args = parser.parse_args()
    return args
zihanl's avatar
zihanl committed
54
55


zihanl's avatar
zihanl committed
56
def process_wow_dataset(raw_file, processed_file, knwl_ref_file, resp_ref_file):
zihanl's avatar
zihanl committed
57
    """
zihanl's avatar
zihanl committed
58
59
      This is a function used for processing the wizard of wikipedia (wow) dataset
      Expected processed format:
zihanl's avatar
zihanl committed
60
61
      topic \t dialogue context \t golden knowledge \t golden response
    """
zihanl's avatar
zihanl committed
62

zihanl's avatar
zihanl committed
63
    # loading the raw data
zihanl's avatar
zihanl committed
64
65
    print("> Loading data from %s" % raw_file)
    with open(raw_file, "r") as fr:
zihanl's avatar
zihanl committed
66
67
        dialog_data = json.load(fr)
    
root's avatar
root committed
68
    print("> Processing data ...")
zihanl's avatar
zihanl committed
69
70
71
72
73
    fproc = open(processed_file, "w")
    fknwl = open(knwl_ref_file, "w") if knwl_ref_file else None
    fresp = open(resp_ref_file, "w") if resp_ref_file else None
    
    for i, sample in enumerate(tqdm(dialog_data)):
zihanl's avatar
zihanl committed
74
        # get all the dialog data for a single dialog sample
zihanl's avatar
zihanl committed
75
76
        dialog = sample["dialog"]
        
zihanl's avatar
zihanl committed
77
78
        turn_list = []  # collect the dialog history
        # processing for each single dialog sample
zihanl's avatar
zihanl committed
79
        for j, turn in enumerate(dialog):
zihanl's avatar
zihanl committed
80
            # text of each turn
zihanl's avatar
zihanl committed
81
82
83
            text = turn["text"]
            if not (text.endswith("?") or text.endswith(".") or text.endswith("!")):
                text = text + "."
zihanl's avatar
zihanl committed
84
            
zihanl's avatar
zihanl committed
85
86
            if j == 0:
                # first turn
zihanl's avatar
zihanl committed
87
                turn_list.append(text)
zihanl's avatar
zihanl committed
88
89
90
91
92
93
                continue

            speaker = turn["speaker"].lower()
            if "wizard" in speaker:
                checked_sentence = list(turn["checked_sentence"].values())  # knowledge
                checked_passage = list(turn["checked_passage"].values())    # topic
zihanl's avatar
zihanl committed
94
                
zihanl's avatar
zihanl committed
95
                assert len(checked_sentence) <= 1
zihanl's avatar
zihanl committed
96

zihanl's avatar
zihanl committed
97
98
99
100
101
                # get the ground truth knowledge
                if len(checked_sentence) > 0:
                    checked_sentence = checked_sentence[0]
                else:
                    checked_sentence = "no_passages_used"
zihanl's avatar
zihanl committed
102

zihanl's avatar
zihanl committed
103
104
105
106
                if len(checked_passage) == 1:
                    checked_passage = checked_passage[0]
                else:
                    checked_passage = "no_passages_used"
zihanl's avatar
zihanl committed
107

zihanl's avatar
zihanl committed
108
109
110
111
112
113
                # get the topic
                if checked_passage != "no_passages_used":
                    topic = checked_passage
                else:
                    topic = sample["chosen_topic"]
                
zihanl's avatar
zihanl committed
114
                dialog_context = " [SEP] ".join(turn_list)
zihanl's avatar
zihanl committed
115
116
                knowledge = checked_sentence
                response = text
zihanl's avatar
zihanl committed
117
118
119
                # add the response into the dialog history
                turn_list.append(response)

zihanl's avatar
zihanl committed
120
                # write to the output files
zihanl's avatar
zihanl committed
121
                fproc.write(topic + "\t" + dialog_context + "\t" + \
zihanl's avatar
zihanl committed
122
123
124
125
126
127
128
129
                                knowledge + "\t" + response + "\n")
                
                if fknwl:
                    fknwl.write(knowledge + "\n")
                if fresp:
                    # tokenize for evaluation
                    response = " ".join(word_tokenize(response))
                    fresp.write(response + "\n")
zihanl's avatar
zihanl committed
130

zihanl's avatar
zihanl committed
131
132
            else:
                assert "apprentice" in speaker
zihanl's avatar
zihanl committed
133
                turn_list.append(text)
zihanl's avatar
zihanl committed
134
135
136
137
138
139

    fproc.close()
    if fknwl:
        fknwl.close()
    if fresp:
        fresp.close()
zihanl's avatar
zihanl committed
140
141


zihanl's avatar
zihanl committed
142
def process_woi_dataset(raw_file, processed_file, knwl_ref_file, resp_ref_file):
zihanl's avatar
zihanl committed
143
144
145
146
147
    """
      This is a function used for processing the wizard of internet (woi) dataset
      Expected processed format:
      topic \t dialogue context \t golden knowledge \t golden response
    """
zihanl's avatar
zihanl committed
148
149
150
151
152
153
154
155
    
    print("> Processing %s" % raw_file)
    fproc = open(processed_file, "w")
    fknwl = open(knwl_ref_file, "w") if knwl_ref_file else None
    fresp = open(resp_ref_file, "w") if resp_ref_file else None
    
    with open(raw_file, "r") as fr:
        for i, line in tqdm(enumerate(fr)):
zihanl's avatar
zihanl committed
156
            # read line by line, each line uses json format
zihanl's avatar
zihanl committed
157
158
            line = line.strip()
            item_dict = json.loads(line)
zihanl's avatar
zihanl committed
159
160
161

            # item_dict is a dictionary
            # its key is the data id, and its value contains all the data content
zihanl's avatar
zihanl committed
162
            item_dict = item_dict.values()
zihanl's avatar
zihanl committed
163
            item_dict = list(item_dict)[0]  # len(item_dict) == 1
zihanl's avatar
zihanl committed
164
            
zihanl's avatar
zihanl committed
165
            # get the whole dialog data for a single dialog sample
zihanl's avatar
zihanl committed
166
167
168
            dialog_data = item_dict['dialog_history']
            length = len(dialog_data)
            
zihanl's avatar
zihanl committed
169
            turn_list = []  # collect the dialog history
zihanl's avatar
zihanl committed
170
171
172
173
            search_text = ""
            for i in range(length):
                item = dialog_data[i]
                action = item['action']
zihanl's avatar
zihanl committed
174

zihanl's avatar
zihanl committed
175
176
177
178
179
                if action == "Wizard => SearchAgent":
                    search_text = item['text']

                elif action == "Wizard => Apprentice":
                    if len(turn_list) == 0:
zihanl's avatar
zihanl committed
180
                        # first turn
zihanl's avatar
zihanl committed
181
182
                        turn = item['text']
                        turn_list.append(turn)
zihanl's avatar
zihanl committed
183
184
185
186
187
188
189
190
191
192
193
                        continue

                    # get the relevant content
                    contents = item["context"]["contents"]
                    selects = item["context"]["selected_contents"]
                    flag = selects[0][0]
                    selects = selects[1:]
                    assert len(selects) == len(contents)
                    
                    # get the topic
                    if flag:
zihanl's avatar
zihanl committed
194
                        # no knowledge sentence is used for the response
zihanl's avatar
zihanl committed
195
                        topic = "no_topic"
zihanl's avatar
zihanl committed
196
                        knwl_sent = "no_passages_used"
zihanl's avatar
zihanl committed
197
                    else:
zihanl's avatar
zihanl committed
198
                        # we consider the search text as the topic
zihanl's avatar
zihanl committed
199
                        topic = search_text
zihanl's avatar
zihanl committed
200
201
                        # get the knowledge sentence
                        knwl_sent = ""
zihanl's avatar
zihanl committed
202
203
204
205
206
                        for content, select in zip(contents, selects):
                            content = content['content']
                            assert len(content) == len(select)
                            for c, s in zip(content, select):
                                if s:
zihanl's avatar
zihanl committed
207
208
209
210
211
                                    knwl_sent = c
                                    break

                    if knwl_sent == "":
                        # no knowledge is used for the response
zihanl's avatar
zihanl committed
212
                        topic = "no_topic"
zihanl's avatar
zihanl committed
213
                        knwl_sent = "no_passages_used"
zihanl's avatar
zihanl committed
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

                    # get dialogue context, knowledge, and response 
                    dialog_context = " [SEP] ".join(turn_list)
                    response = item['text']

                    # processing
                    topic = topic.replace("\n", "").replace("\r", \
                                "").replace("\t", "")
                    dialog_context = dialog_context.replace("\n", "").replace("\r", \
                                "").replace("\t", "")
                    knwl_sent = knwl_sent.replace("\n", "").replace("\r", \
                                "").replace("\t", "")
                    response = response.replace("\n", "").replace("\r", \
                                "").replace("\t", "")
                    
                    if topic != "no_topic":
                        # write to the ouput files
                        fproc.write(topic + "\t" + dialog_context + "\t" + \
                                        knwl_sent + "\t" + response + "\n")
                        if fknwl:
                            fknwl.write(knwl_sent + "\n")
                        if fresp:
                            # tokenize for evaluation
                            response = " ".join(word_tokenize(response))
                            fresp.write(response + "\n")

                    turn_list.append(response)

                elif action == "Apprentice => Wizard":
                    turn = item['text']
                    turn_list.append(turn)

                else:
zihanl's avatar
zihanl committed
247
248
                    assert action == "SearchAgent => Wizard", \
                            "Please check whether you have used the correct data!"
zihanl's avatar
zihanl committed
249
250
251
252
253
254

    fproc.close()
    if fknwl:
        fknwl.close()
    if fresp:
        fresp.close()
zihanl's avatar
zihanl committed
255
256


root's avatar
root committed
257
258
def get_database(test_datapath, train_datapath, data_type):
    """Get the database by topics"""
zihanl's avatar
zihanl committed
259

zihanl's avatar
zihanl committed
260
261
    assert data_type in ["wow_seen", "wow_unseen", "woi"], \
                "Please input a correct data type!!"
zihanl's avatar
zihanl committed
262
263

    # get test data topic dictionary
zihanl's avatar
zihanl committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
    print("> reading test data from %s" % test_datapath)
    test_topics = {}
    with open(test_datapath, "r") as f:
        for i, line in enumerate(f):
            line = line.strip()
            splits = line.split("\t")
            topic = splits[0]
            test_topics[topic] = True

    print("> reading data from %s" % train_datapath)
    train_data_by_topic = {}
    dialog_data_by_topic = {}
    dialog_examples = []
    with open(train_datapath, "r") as f:
        for i, line in enumerate(f):
            line = line.strip()
            splits = line.split("\t")
            topic = splits[0]
            turns = splits[1].split(" [SEP] ")[-3:]
            knowledge = splits[2]
            response = splits[3]
root's avatar
root committed
285
            # filtering data samples
zihanl's avatar
zihanl committed
286
            if knowledge == "no_passages_used":
zihanl's avatar
zihanl committed
287
                # when no knowledge is used
zihanl's avatar
zihanl committed
288
                continue
root's avatar
root committed
289
            if data_type != "wow_seen" and ("(" in knowledge or ")" in knowledge):
zihanl's avatar
zihanl committed
290
                # when bracket exists in the knowledge
root's avatar
root committed
291
292
                continue
            if data_type != "wow_seen" and topic not in knowledge:
zihanl's avatar
zihanl committed
293
                # when topic does not exist in the knowledge
root's avatar
root committed
294
295
                continue

zihanl's avatar
zihanl committed
296
297
            # get the instance
            last_turn = turns[-1]
zihanl's avatar
zihanl committed
298
            instance = "( " + last_turn + " ) " + topic + " => " + knowledge
zihanl's avatar
zihanl committed
299
300
301
            
            # construct dialog example
            dialog_example = ""
root's avatar
root committed
302
303
304
305
306
            if data_type != "wow_seen":
                dialog_example += "( " + topic + " ) "
            for i, turn in enumerate(turns):
                if i != 0:
                    dialog_example += " "
zihanl's avatar
zihanl committed
307
                dialog_example += turn
root's avatar
root committed
308
            
zihanl's avatar
zihanl committed
309
310
311
312
313
314
315
316
317
318
319
            # check overlaps
            if topic in test_topics:
                if topic not in train_data_by_topic:
                    train_data_by_topic[topic] = [instance]
                else:
                    train_data_by_topic[topic].append(instance)
                
                if topic not in dialog_data_by_topic:
                    dialog_data_by_topic[topic] = [dialog_example]
                else:
                    dialog_data_by_topic[topic].append(dialog_example)
root's avatar
root committed
320
321
322
323
324
325
326
327
328
329
            
            else:
                # filtering data samples
                if len(knowledge.split()) > 20:
                    # knowledge is too long
                    continue
                if knowledge.startswith("It") or knowledge.startswith("it") or \
                   knowledge.startswith("This") or knowledge.startswith("this"):
                    continue
                
zihanl's avatar
zihanl committed
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
            # append all the data into dialogue examples list
            dialog_examples.append((topic, dialog_example, instance))

    return train_data_by_topic, dialog_data_by_topic, dialog_examples


emb_dict = {}
def select_prompts_based_on_similarity(
        query, dialog_list, prompt_list, topic, tokenizer, encoder, topk):
    """Select samples based on the similarity"""

    with torch.no_grad():
        # get the query embeddings
        query_ids = tokenizer.encode(query)
        query_ids = torch.LongTensor([query_ids]).cuda()
        query_emb = encoder(input_ids=query_ids).pooler_output
        query_emb = query_emb[0]
        
        # calculate embeddings for the samples in the database
        if topic in emb_dict:
            example_embeddings = emb_dict[topic]
            example_embeddings = example_embeddings.cuda()
        else:
            for idx, example in enumerate(dialog_list):
                example_ids = tokenizer.encode(example)
                example_ids = torch.LongTensor([example_ids]).cuda()
                example_emb = encoder(input_ids=example_ids).pooler_output
                if idx == 0:
                    example_embeddings = example_emb
                else:
                    example_embeddings = torch.cat(
                        (example_embeddings, example_emb), dim=0)
            emb_dict[topic] = example_embeddings.cpu()

        # compare the similarity and select the topk samples
        similarity_list = example_embeddings.matmul(query_emb)
        _, indices = torch.topk(similarity_list, k=topk)
    
    indices = indices.tolist()
    indices = indices[::-1] # reverse the order
    selected_prompts = []
    for index in indices:
        # index = index.item()
        selected_prompts.append(prompt_list[index])

    return selected_prompts


def prompt_selection_for_knowledge_generation(
root's avatar
root committed
379
        test_datapath, train_datapath, model_path, output_prompt_path, data_type):
zihanl's avatar
zihanl committed
380
381
382
383
384
    """Selecting prompts for the knowledge generation"""

    print("> Selecting prompts for the knowledge generation")

    train_data_by_topic, dialog_data_by_topic, dialog_examples = \
root's avatar
root committed
385
                            get_database(test_datapath, train_datapath, data_type)
zihanl's avatar
zihanl committed
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
    
    from transformers import DPRQuestionEncoderTokenizer
    print("> loading tokenizer and encoder")
    tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
                    'facebook/dpr-question_encoder-single-nq-base')
    encoder = torch.load(model_path).cuda()

    print("> getting dialog embeddings")
    with torch.no_grad():
        for idx, example in tqdm(enumerate(dialog_examples)):
            dialog = example[1]
            dialog_ids = tokenizer.encode(dialog)
            dialog_ids = torch.LongTensor([dialog_ids]).cuda()
            dialog_emb = encoder(input_ids=dialog_ids).pooler_output

            if idx == 0:
                dialog_embeddings = dialog_emb
            else:
                dialog_embeddings = torch.cat((dialog_embeddings, dialog_emb), dim=0)

    print("> reading test data from %s" % test_datapath)
    prompt_list_for_each_sample = []
    with open(test_datapath, "r") as f:
        for i, line in tqdm(enumerate(f)):
            line = line.strip()

            splits = line.split("\t")
            topic = splits[0]
            turns = splits[1].split(" [SEP] ")[-3:]

root's avatar
root committed
416
417
418
419
420
421
422
423
            # get the query sentence
            query_sent = ""
            if data_type != "seen":
                query_sent += "( " + topic + " ) "
            for i, turn in enumerate(turns):
                if i != 0:
                    query_sent += " "
                query_sent += turn
zihanl's avatar
zihanl committed
424

root's avatar
root committed
425
            if topic not in train_data_by_topic:
zihanl's avatar
zihanl committed
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
                # get the query embedding
                query_ids = tokenizer.encode(query_sent)
                query_ids = torch.LongTensor([query_ids]).cuda()
                query_emb = encoder(input_ids=query_ids).pooler_output
                query_emb = query_emb[0]

                # calculate the similarity
                similarity_list = dialog_embeddings.matmul(query_emb)
                _, indices = torch.sort(similarity_list)
                indices = indices.tolist()
                selected_topics = {}
                selected_prompts = []
                num_prompt = 0
                for index in indices:
                    example = dialog_examples[index]
                    topic_temp = example[0]
                    if topic_temp not in selected_topics:
                        selected_topics[topic_temp] = True
                        selected_prompts.append(example[2])
                        num_prompt += 1
                        if num_prompt == 10:
                            break
                
                # get the selected samples
                example_list = selected_prompts[::-1]
                key = topic + " " + turns[-1]
                prompt_list_for_each_sample.append({key: example_list})

            else:
                num_data_sample = min(len(train_data_by_topic[topic]), 10)
                total_example_list = train_data_by_topic[topic]
root's avatar
root committed
457
                
zihanl's avatar
zihanl committed
458
                dialog_list = dialog_data_by_topic[topic]
root's avatar
root committed
459
                assert len(dialog_list) == len(train_data_by_topic[topic])
zihanl's avatar
zihanl committed
460
461

                # calculate the similarity
root's avatar
root committed
462
                example_list = select_prompts_based_on_similarity(
zihanl's avatar
zihanl committed
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
                                query_sent, dialog_list, total_example_list, 
                                topic, tokenizer, encoder, topk=num_data_sample)
                
                key = topic + " " + turns[-1]
                prompt_list_for_each_sample.append({key: example_list})

    print("writing to %s" % output_prompt_path)
    with open(output_prompt_path, "w") as f:
        for instance in tqdm(prompt_list_for_each_sample):
            json.dump(instance, f)
            f.write("\n")


def prompt_selection_for_response_generation(input_path, output_path, seed):
    """Selecting prompts for the response generation"""

    print("> Selecting prompts for the response generation")
    print("> set random seed")
    np.random.seed(seed)

    prompt_example_list = []
    print("> reading data from %s" % input_path)
    with open(input_path, "r") as f:
        for i, line in tqdm(enumerate(f)):
            line = line.strip()
            splits = line.split("\t")

            # get the topic, context, knowledge and response
            topic = splits[0]
            dialog_context = splits[1]
            knowledge = splits[2]
            response = splits[3]
            turns = dialog_context.split(" [SEP] ")[-3:]
            if knowledge == "no_passages_used":
                continue

            # calculate the overlap ratio
            from nltk import word_tokenize
            knowledge_sent_token_list = word_tokenize(knowledge)
            knowledge_sent_token_dict = {token: True for token in knowledge_sent_token_list}
root's avatar
root committed
503
504
            knowledge_len = len(knowledge_sent_token_list)
            response_token_list = word_tokenize(response)
zihanl's avatar
zihanl committed
505
506
            response_len = len(response_token_list)
            num_overlap_token = 0
root's avatar
root committed
507
            accumulator = 0
zihanl's avatar
zihanl committed
508
509
            for token in response_token_list:
                if token in knowledge_sent_token_dict:
root's avatar
root committed
510
511
512
513
514
515
516
                    accumulator += 1
                else:
                    if accumulator >= 10:
                        num_overlap_token += accumulator
                    accumulator = 0
            if accumulator >= 10:
                num_overlap_token += accumulator
zihanl's avatar
zihanl committed
517
518
519
520
            
            # filtering the data based on the ratio
            if num_overlap_token > response_len * 0.9 or num_overlap_token < response_len * 0.6:
                continue
root's avatar
root committed
521
522
523
524
525
526
            if num_overlap_token < knowledge_len * 0.8:
                continue
            
            last_turn = " ".join(word_tokenize(turns[-1]))
            knowledge = " ".join(word_tokenize(knowledge))
            response = " ".join(word_tokenize(response))
zihanl's avatar
zihanl committed
527
528
529
            prompt_example = ""
            # add dialog context
            prompt_example += "Topic: " + topic + ". "
root's avatar
root committed
530
            prompt_example += "User says: " + last_turn + " "
zihanl's avatar
zihanl committed
531
532
533
534
535
            prompt_example += "We know that: " + knowledge + " "
            prompt_example += "System replies: " + response
            
            prompt_example_list.append(prompt_example)
        
root's avatar
root committed
536
    # shuffle the prompt examples
zihanl's avatar
zihanl committed
537
538
539
540
541
542
543
544
545
546
    np.random.shuffle(prompt_example_list)
    
    print("> writing to %s" % output_path)
    with open(output_path, "w") as f:
        # f.write("Generate the System's response based on the knowledge sentence:\n")
        for i in tqdm(range(20)):
            example = prompt_example_list[i]
            f.write(example + "\n")


zihanl's avatar
zihanl committed
547
def prepare_input_for_response_generation(test_file, knwl_gen_file, processed_file):
zihanl's avatar
zihanl committed
548
549
    """Preparing inputs for the response generation"""

zihanl's avatar
zihanl committed
550
    print("> Reading knowledge file from %s" % knwl_gen_file)
zihanl's avatar
zihanl committed
551
    # get the knowledge list
zihanl's avatar
zihanl committed
552
    with open(knwl_gen_file, "r") as f:
zihanl's avatar
zihanl committed
553
554
        knowledge_list = f.readlines()
    
root's avatar
root committed
555
    print("> Processing ...")
zihanl's avatar
zihanl committed
556
    with open(test_file, "r") as fr:
zihanl's avatar
zihanl committed
557
        with open(processed_file, "w") as fw:
zihanl's avatar
zihanl committed
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
            for line_num, line in enumerate(tqdm(fr)):
                line = line.strip()
                splits = line.split("\t")
                # prepare topic, context, knowledge and response
                topic = splits[0]
                dialog_context = splits[1]
                response = splits[3]
                knowledge = knowledge_list[line_num]
                knowledge = knowledge.strip()
                if "<|endoftext|>" in knowledge:
                    knowledge = knowledge.replace("<|endoftext|>", "")

                # write to the output file
                fw.write(topic + "\t" + dialog_context + "\t" \
                                     + knowledge + "\t" + response + "\n")

zihanl's avatar
zihanl committed
574
575
576

if __name__ == "__main__":

root's avatar
root committed
577
578
    args = get_args()
    if args.func == "process_wow_dataset":
zihanl's avatar
zihanl committed
579
        process_wow_dataset(args.raw_file, args.processed_file, args.knwl_ref_file, args.resp_ref_file)
zihanl's avatar
zihanl committed
580

root's avatar
root committed
581
    elif args.func == "process_woi_dataset":
zihanl's avatar
zihanl committed
582
        process_woi_dataset(args.raw_file, args.processed_file, args.knwl_ref_file, args.resp_ref_file)
zihanl's avatar
zihanl committed
583

root's avatar
root committed
584
    elif args.func == "get_knwl_gen_prompts":
zihanl's avatar
zihanl committed
585
        prompt_selection_for_knowledge_generation(
root's avatar
root committed
586
            args.test_file, args.train_file, args.model_file, 
zihanl's avatar
zihanl committed
587
            args.processed_file, args.data_type)
root's avatar
root committed
588
589
    
    elif args.func == "get_resp_gen_prompts":
zihanl's avatar
zihanl committed
590
        prompt_selection_for_response_generation(
zihanl's avatar
zihanl committed
591
            args.train_file, args.processed_file, args.seed)
zihanl's avatar
zihanl committed
592

root's avatar
root committed
593
    elif args.func == "prepare_input":
zihanl's avatar
zihanl committed
594
        prepare_input_for_response_generation(
zihanl's avatar
zihanl committed
595
            args.test_file, args.knwl_gen_file, args.processed_file)