Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import pipeline, PegasusForConditionalGeneration, PegasusTokenizer
|
| 4 |
+
|
| 5 |
+
# Q&A model
|
| 6 |
+
qa_classifier = pipeline(
|
| 7 |
+
"question-answering",
|
| 8 |
+
model="deepset/roberta-base-squad2",
|
| 9 |
+
tokenizer="deepset/roberta-base-squad2"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
# paraphrase model
|
| 13 |
+
paraphrase_model_name = 'tuner007/pegasus_paraphrase'
|
| 14 |
+
paraphrase_tokenizer = PegasusTokenizer.from_pretrained(paraphrase_model_name)
|
| 15 |
+
paraphrase_model = PegasusForConditionalGeneration.from_pretrained(paraphrase_model_name)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def find_answer_and_paraphrase(text_input, question):
|
| 19 |
+
# Find the answer
|
| 20 |
+
answer = qa_classifier(context=text_input, question=question)["answer"]
|
| 21 |
+
|
| 22 |
+
# Find the sentence containing the answer
|
| 23 |
+
sentences = text_input.split(".")
|
| 24 |
+
sentence_with_answer = ""
|
| 25 |
+
for sentence in sentences:
|
| 26 |
+
if answer in sentence:
|
| 27 |
+
sentence_with_answer = sentence.strip() + "."
|
| 28 |
+
break
|
| 29 |
+
|
| 30 |
+
# Paraphrase the sentence containing the answer
|
| 31 |
+
input_text = "paraphrase: " + sentence_with_answer
|
| 32 |
+
num_return_sequences = 1
|
| 33 |
+
num_beams = 5
|
| 34 |
+
batch = paraphrase_tokenizer([input_text], truncation=True, padding='longest', max_length=60, return_tensors="pt").to(torch_device)
|
| 35 |
+
translated = paraphrase_model.generate(**batch, max_length=60, num_beams=num_beams, num_return_sequences=num_return_sequences, temperature=1.5)
|
| 36 |
+
paraphrase_text = paraphrase_tokenizer.batch_decode(translated, skip_special_tokens=True)[0]
|
| 37 |
+
|
| 38 |
+
return {"Answer": answer, "Paraphrase": paraphrase_text}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
inputs = [
|
| 42 |
+
gr.inputs.Textbox(label="Text Input"),
|
| 43 |
+
gr.inputs.Textbox(label="Question")
|
| 44 |
+
]
|
| 45 |
+
outputs = gr.outputs.Dict(label="Answer and Paraphrase")
|
| 46 |
+
|
| 47 |
+
iface = gr.Interface(fn=find_answer_and_paraphrase, inputs=inputs, outputs=outputs, title="Question Answering and Paraphrasing", description="Enter the text and question to find the answer and paraphrase the sentence containing the answer.")
|
| 48 |
+
iface.launch()
|