Abaryan commited on
Commit
1f15859
·
verified ·
1 Parent(s): a437b0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +215 -51
app.py CHANGED
@@ -1,64 +1,228 @@
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("rgb2gbr/GRPO_BioMedmcqa_Qwen2.5-0.5B")
8
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
27
 
28
- response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ import torch
5
+ from transformers import AutoModelForMultipleChoice, AutoTokenizer
6
+ import os
7
+ from datasets import load_dataset
8
+ import random
9
+ from typing import Optional, List
10
  import gradio as gr
 
11
 
12
+ app = FastAPI()
 
 
 
13
 
14
+ # Add CORS middleware for Gradio
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"],
18
+ allow_credentials=True,
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
+ )
22
 
23
+ # Define input models
24
+ class QuestionRequest(BaseModel):
25
+ question: str
26
+ options: list[str] # List of 4 options
 
 
 
 
 
27
 
28
+ class DatasetQuestion(BaseModel):
29
+ question: str
30
+ opa: str
31
+ opb: str
32
+ opc: str
33
+ opd: str
34
+ cop: Optional[int] = None # Correct option (0-3)
35
+ exp: Optional[str] = None # Explanation if available
36
 
37
+ # Global variables
38
+ model = None
39
+ tokenizer = None
40
+ dataset = None
41
 
42
+ def load_model():
43
+ global model, tokenizer, dataset
44
+ try:
45
+ # Load your fine-tuned model and tokenizer
46
+ model_name = os.getenv("BioXP-0.5b", "rgb2gbr/GRPO_BioMedmcqa_Qwen2.5-0.5B")
47
+ model = AutoModelForMultipleChoice.from_pretrained(model_name)
48
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
49
+
50
+ # Load MedMCQA dataset
51
+ dataset = load_dataset("openlifescienceai/medmcqa")
52
+
53
+ # Move model to GPU if available
54
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
55
+ model = model.to(device)
56
+ model.eval()
57
+ except Exception as e:
58
+ raise Exception(f"Error loading model: {str(e)}")
59
 
60
+ def predict_gradio(question: str, option_a: str, option_b: str, option_c: str, option_d: str):
61
+ """Gradio interface prediction function"""
62
+ try:
63
+ options = [option_a, option_b, option_c, option_d]
64
+ inputs = []
65
+ for option in options:
66
+ text = f"{question} {option}"
67
+ inputs.append(text)
68
+
69
+ encodings = tokenizer(
70
+ inputs,
71
+ padding=True,
72
+ truncation=True,
73
+ max_length=512,
74
+ return_tensors="pt"
75
+ )
76
+
77
+ device = next(model.parameters()).device
78
+ encodings = {k: v.to(device) for k, v in encodings.items()}
79
+
80
+ with torch.no_grad():
81
+ outputs = model(**encodings)
82
+ logits = outputs.logits
83
+ probabilities = torch.softmax(logits, dim=1)[0].tolist()
84
+ predicted_class = torch.argmax(logits, dim=1).item()
85
+
86
+ # Format the output for Gradio
87
+ result = f"Predicted Answer: {options[predicted_class]}\n\n"
88
+ result += "Confidence Scores:\n"
89
+ for i, (opt, prob) in enumerate(zip(options, probabilities)):
90
+ result += f"{opt}: {prob:.2%}\n"
91
+
92
+ return result
93
+
94
+ except Exception as e:
95
+ return f"Error: {str(e)}"
96
 
97
+ def get_random_question():
98
+ """Get a random question for Gradio interface"""
99
+ if dataset is None:
100
+ return "Error: Dataset not loaded", "", "", "", ""
101
+
102
+ index = random.randint(0, len(dataset['train']) - 1)
103
+ question_data = dataset['train'][index]
104
+
105
+ return (
106
+ question_data['question'],
107
+ question_data['opa'],
108
+ question_data['opb'],
109
+ question_data['opc'],
110
+ question_data['opd']
111
+ )
112
 
113
+ # Create Gradio interface
114
+ with gr.Blocks(title="Medical MCQ Predictor") as demo:
115
+ gr.Markdown("# Medical MCQ Predictor")
116
+ gr.Markdown("Enter a medical question and its options, or get a random question from MedMCQA dataset.")
117
+
118
+ with gr.Row():
119
+ with gr.Column():
120
+ question = gr.Textbox(label="Question", lines=3)
121
+ option_a = gr.Textbox(label="Option A")
122
+ option_b = gr.Textbox(label="Option B")
123
+ option_c = gr.Textbox(label="Option C")
124
+ option_d = gr.Textbox(label="Option D")
125
+
126
+ with gr.Row():
127
+ predict_btn = gr.Button("Predict")
128
+ random_btn = gr.Button("Get Random Question")
129
+
130
+ output = gr.Textbox(label="Prediction", lines=5)
131
+
132
+ predict_btn.click(
133
+ fn=predict_gradio,
134
+ inputs=[question, option_a, option_b, option_c, option_d],
135
+ outputs=output
136
+ )
137
+
138
+ random_btn.click(
139
+ fn=get_random_question,
140
+ inputs=[],
141
+ outputs=[question, option_a, option_b, option_c, option_d]
142
+ )
143
 
144
+ # Mount Gradio app to FastAPI
145
+ app = gr.mount_gradio_app(app, demo, path="/")
146
+
147
+ @app.on_event("startup")
148
+ async def startup_event():
149
+ load_model()
150
+
151
+ @app.get("/dataset/question")
152
+ async def get_dataset_question(index: Optional[int] = None, random_question: bool = False):
153
+ """Get a question from the MedMCQA dataset"""
154
+ try:
155
+ if dataset is None:
156
+ raise HTTPException(status_code=500, detail="Dataset not loaded")
157
+
158
+ if random_question:
159
+ index = random.randint(0, len(dataset['train']) - 1)
160
+ elif index is None:
161
+ raise HTTPException(status_code=400, detail="Either index or random_question must be provided")
162
+
163
+ question_data = dataset['train'][index]
164
+
165
+ question = DatasetQuestion(
166
+ question=question_data['question'],
167
+ opa=question_data['opa'],
168
+ opb=question_data['opb'],
169
+ opc=question_data['opc'],
170
+ opd=question_data['opd'],
171
+ cop=question_data['cop'] if 'cop' in question_data else None,
172
+ exp=question_data['exp'] if 'exp' in question_data else None
173
+ )
174
+
175
+ return question
176
+
177
+ except Exception as e:
178
+ raise HTTPException(status_code=500, detail=str(e))
179
 
180
+ @app.post("/predict")
181
+ async def predict(request: QuestionRequest):
182
+ if len(request.options) != 4:
183
+ raise HTTPException(status_code=400, detail="Exactly 4 options are required")
184
+
185
+ try:
186
+ inputs = []
187
+ for option in request.options:
188
+ text = f"{request.question} {option}"
189
+ inputs.append(text)
190
+
191
+ encodings = tokenizer(
192
+ inputs,
193
+ padding=True,
194
+ truncation=True,
195
+ max_length=512,
196
+ return_tensors="pt"
197
+ )
198
+
199
+ device = next(model.parameters()).device
200
+ encodings = {k: v.to(device) for k, v in encodings.items()}
201
+
202
+ with torch.no_grad():
203
+ outputs = model(**encodings)
204
+ logits = outputs.logits
205
+ probabilities = torch.softmax(logits, dim=1)[0].tolist()
206
+ predicted_class = torch.argmax(logits, dim=1).item()
207
+
208
+ response = {
209
+ "predicted_option": request.options[predicted_class],
210
+ "option_index": predicted_class,
211
+ "confidence": probabilities[predicted_class],
212
+ "probabilities": {
213
+ f"option_{i}": prob for i, prob in enumerate(probabilities)
214
+ }
215
+ }
216
+
217
+ return response
218
+
219
+ except Exception as e:
220
+ raise HTTPException(status_code=500, detail=str(e))
221
 
222
+ @app.get("/health")
223
+ async def health_check():
224
+ return {
225
+ "status": "healthy",
226
+ "model_loaded": model is not None,
227
+ "dataset_loaded": dataset is not None
228
+ }