Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import transformers
|
| 2 |
+
from transformers import T5Tokenizer, T5Model, T5ForConditionalGeneration, T5TokenizerFast, TFT5ForConditionalGeneration, FlaxT5ForConditionalGeneration
|
| 3 |
+
import evaluate
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import requests
|
| 9 |
+
|
| 10 |
+
Q_LEN = 256
|
| 11 |
+
|
| 12 |
+
model_name = 'PRAli22/t5-base-question-answering-system'
|
| 13 |
+
tokenizer = T5TokenizerFast.from_pretrained(model_name)
|
| 14 |
+
model = T5ForConditionalGeneration.from_pretrained(model_name)
|
| 15 |
+
|
| 16 |
+
def predict_answer(context, question, ref_answer=None):
|
| 17 |
+
inputs = tokenizer(question, context, max_length=Q_LEN, padding="max_length", truncation=True, add_special_tokens=True)
|
| 18 |
+
|
| 19 |
+
input_ids = torch.tensor(inputs["input_ids"], dtype=torch.long).unsqueeze(0)
|
| 20 |
+
attention_mask = torch.tensor(inputs["attention_mask"], dtype=torch.long).unsqueeze(0)
|
| 21 |
+
|
| 22 |
+
outputs = model.generate(input_ids=input_ids, attention_mask=attention_mask)
|
| 23 |
+
|
| 24 |
+
predicted_answer = tokenizer.decode(outputs.flatten(), skip_special_tokens=True)
|
| 25 |
+
|
| 26 |
+
if ref_answer:
|
| 27 |
+
# Load the Bleu metric
|
| 28 |
+
bleu = evaluate.load("google_bleu")
|
| 29 |
+
score = bleu.compute(predictions=[predicted_answer],
|
| 30 |
+
references=[ref_answer])
|
| 31 |
+
|
| 32 |
+
print("Context: \n", context)
|
| 33 |
+
print("\n")
|
| 34 |
+
print("Question: \n", question)
|
| 35 |
+
return {
|
| 36 |
+
"Reference Answer: ": ref_answer,
|
| 37 |
+
"Predicted Answer: ": predicted_answer,
|
| 38 |
+
"BLEU Score: ": score
|
| 39 |
+
}
|
| 40 |
+
else:
|
| 41 |
+
return predicted_answer
|
| 42 |
+
|
| 43 |
+
css_code='body{background-image:url("https://media.istockphoto.com/id/1256252051/vector/people-using-online-translation-app.jpg?s=612x612&w=0&k=20&c=aa6ykHXnSwqKu31fFR6r6Y1bYMS5FMAU9yHqwwylA94=");}'
|
| 44 |
+
|
| 45 |
+
demo = gr.Interface(
|
| 46 |
+
fn=predict_answer,
|
| 47 |
+
inputs=[
|
| 48 |
+
gr.Textbox(label="text", placeholder="Enter the text "),
|
| 49 |
+
gr.Textbox(label="question", placeholder="Enter the question")
|
| 50 |
+
],
|
| 51 |
+
outputs=gr.Textbox(label="answer"),
|
| 52 |
+
title="Question Answering System",
|
| 53 |
+
description= "This is Question Answering System, it takes a text and question in English as inputs and returns it's answer",
|
| 54 |
+
css = css_code
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
demo.launch(share=True)
|