Cilia Madani commited on
Commit
6edbbf1
1 Parent(s): c7f37ed
biogpt_qa_pubmedqa_biogpt_large.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """BioGPT-QA-PubMedQA-BioGPT-Large.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1grmKyUETABgEsC3hO7CKgnSG1JGBbmHV
8
+ """
9
+
10
+
11
+ from transformers import AutoTokenizer, AutoModelForCausalLM
12
+ import gradio as gr
13
+ import torch
14
+ import re
15
+
16
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/BioGPT-Large-PubMedQA")
17
+ model = AutoModelForCausalLM.from_pretrained("microsoft/BioGPT-Large-PubMedQA")
18
+
19
+ # Check if GPU is available and move model to GPU
20
+ if torch.cuda.is_available():
21
+ device = torch.device("cuda")
22
+ model.to(device)
23
+ print("Using GPU:", torch.cuda.get_device_name(0))
24
+ else:
25
+ device = torch.device("cpu")
26
+ print("Using CPU")
27
+
28
+ def answer_bio_question(question, context):
29
+ """Answers a biological question using BioGPT-QA-PubMedQA-BioGPT-Large.
30
+
31
+ Args:
32
+ question: The question to be answered.
33
+ context: The context or passage containing the answer (concatenated with the question).
34
+
35
+ Returns:
36
+ The answer extracted from the context based on the question.
37
+ """
38
+ try:
39
+ # Concatenate question and context with a separator
40
+ input_ids = tokenizer(question + " [SEP] " + context, return_tensors="pt").to(device)
41
+
42
+ # Move the input to the chosen device (GPU or CPU)
43
+ input_ids = input_ids.to(device)
44
+
45
+ outputs = model.generate(**input_ids,
46
+ max_new_tokens=1024
47
+ ,
48
+ num_beams=1,
49
+ early_stopping=False,
50
+ do_sample=False,
51
+ )
52
+
53
+
54
+ answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
55
+ print(answer)
56
+ segs = re.search(r"the answer to the question given the context is(.*)", answer)
57
+ ans = "unknown"
58
+ if segs is not None:
59
+ segs = segs.groups()
60
+ ans = segs[0].strip()
61
+
62
+ return "The answer to this question is " + ans
63
+ except Exception as e:
64
+ print(f"Error during question answering: {e}")
65
+ return "An error occurred during question answering. Please try again."
66
+
67
+
68
+
69
+ iface = gr.Interface(
70
+ fn=answer_bio_question,
71
+ inputs=[
72
+ gr.Textbox(label="Question", lines=2),
73
+ gr.Textbox(label="Context (Passage)", lines=5),
74
+ ],
75
+ outputs="textbox",
76
+ title="BioGPT-QA: Answer Biological Questions",
77
+ )
78
+
79
+ # Launch the Gradio interface
80
+ iface.launch( debug=True, share=True)
81
+
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ gradio
4
+ sacremoses