Views
No views yet
1import torch
2from transformers import T5ForConditionalGeneration, T5Tokenizer
3
4def question_parser(question: str) -> str:
5 return " ".join(question.split(":")[1].split())
6
7def generate_questions_v2(context: str, answer: str, n_questions: int = 1):
8 model = T5ForConditionalGeneration.from_pretrained(
9 "pipesanma/chasquilla-question-generator"
10 )
11 tokenizer = T5Tokenizer.from_pretrained("pipesanma/chasquilla-question-generator")
12
13 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
14 model = model.to(device)
15 text = "context: " + context + " " + "answer: " + answer + " </s>"
16
17 encoding = tokenizer.encode_plus(
18 text, max_length=512, padding=True, return_tensors="pt"
19 )
20 input_ids, attention_mask = encoding["input_ids"].to(device), encoding[
21 "attention_mask"
22 ].to(device)
23
24 model.eval()
25 beam_outputs = model.generate(
26 input_ids=input_ids,
27 attention_mask=attention_mask,
28 max_length=72,
29 early_stopping=True,
30 num_beams=5,
31 num_return_sequences=n_questions,
32 )
33
34 questions = []
35
36 for beam_output in beam_outputs:
37 sent = tokenizer.decode(
38 beam_output, skip_special_tokens=True, clean_up_tokenization_spaces=True
39 )
40 print(sent)
41 questions.append(question_parser(sent))
42
43 return questions
44
45
46context = "President Donald Trump said and predicted that some states would reopen this month."
47answer = "Donald Trump"
48
49questions = generate_questions_v2(context, answer, 1)
50print(questions)