dippatel1994 commited on
Commit
d6cf304
1 Parent(s): cf42d38

Create app.py

Browse files

Adding a code in app.py to prepare UI and use Google's Bert language model for generating answers of asked questions on research paper content.

Files changed (1) hide show
  1. app.py +54 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ from transformers import AutoTokenizer, TFAutoModelForQuestionAnswering
4
+
5
+
6
+ class ResearchPaperQAModel:
7
+ """Class to load the model and answer questions based on abstract and text of reserach paper.
8
+ """
9
+ def __init__(self, model_name):
10
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
11
+ self.model = TFAutoModelForQuestionAnswering.from_pretrained(model_name)
12
+
13
+ def answer_question(self, question, abstract, paper_text):
14
+ # Tokenize input question and context
15
+ if not paper_text:
16
+ context = abstract
17
+ else:
18
+ context = paper_text
19
+
20
+ inputs = self.tokenizer(question, context, return_tensors="tf")
21
+
22
+ # Get the start and end logits for the answer
23
+ outputs = self.model(**inputs)
24
+ start_logits, end_logits = outputs.start_logits[0].numpy(), outputs.end_logits[0].numpy()
25
+
26
+ # Find the tokens with the highest probability for start and end positions
27
+ start_index = tf.argmax(start_logits, axis=-1).numpy()
28
+ end_index = tf.argmax(end_logits, axis=-1).numpy()
29
+
30
+ # Convert token indices to actual tokens
31
+ tokens = self.tokenizer.convert_ids_to_tokens(inputs["input_ids"].numpy().squeeze())
32
+ answer_tokens = tokens[start_index : end_index + 1]
33
+
34
+ # Convert answer tokens back to a string
35
+ answer = self.tokenizer.convert_tokens_to_string(answer_tokens)
36
+
37
+ return answer
38
+
39
+
40
+ model = "bert-large-uncased-whole-word-masking-finetuned-squad" # Model name
41
+ paper_model = ResearchPaperQAModel(model) #Create an instance of the model
42
+
43
+ # Create a Gradio interface
44
+ iface = gr.Interface(
45
+ fn=paper_model.answer_question,
46
+ inputs=["text", "text", "text"],
47
+ outputs="text",
48
+ live=True,
49
+ title="Ask question to research paper",
50
+ description="Enter title of research paper, abstract, research paper content(optional) and list of questions to get answers."
51
+ )
52
+
53
+ # Launch the Gradio interface
54
+ iface.launch(share=True)