Bman21 commited on
Commit
8b9374c
Β·
verified Β·
1 Parent(s): 22de66a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -0
app.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
+ import torch
4
+
5
+ # -------------------
6
+ # CONFIG
7
+ # -------------------
8
+ # Using a good medical model - MedAlpaca is excellent for medical Q&A
9
+ DEFAULT_MODEL = "medalpaca/medalpaca-7b" # Medical-specific model
10
+
11
+ # Alternative medical models you can try:
12
+ # "stanford-aimi/stanford-medalpaca-7b"
13
+ # "medicalai/ClinicalBERT"
14
+ # "microsoft/BioGPT-Large"
15
+
16
+ SYSTEM_MESSAGE = """You are a helpful medical tutor AI. Your role is to provide educational information about medical topics.
17
+
18
+ IMPORTANT SAFETY RULES:
19
+ 1. You are for EDUCATIONAL purposes only
20
+ 2. NEVER provide medical advice, diagnoses, or treatment recommendations
21
+ 3. Always clarify that you are an AI tutor, not a doctor
22
+ 4. If asked about personal symptoms, direct users to consult healthcare professionals
23
+ 5. Base your answers on established medical knowledge
24
+
25
+ Please provide clear, accurate explanations suitable for medical students and learners."""
26
+
27
+ MAX_TOKENS = 512
28
+ TEMPERATURE = 0.7
29
+
30
+ # -------------------
31
+ # MODEL LOADER
32
+ # -------------------
33
+ def load_model(model_name):
34
+ print(f"Loading model: {model_name}")
35
+
36
+ try:
37
+ # Load tokenizer and model
38
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
39
+
40
+ # For smaller models, you can load directly. For larger models, you might need 8-bit or quantization
41
+ model = AutoModelForCausalLM.from_pretrained(
42
+ model_name,
43
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
44
+ device_map="auto" if torch.cuda.is_available() else None,
45
+ low_cpu_mem_usage=True
46
+ )
47
+
48
+ # Create text generation pipeline
49
+ generator = pipeline(
50
+ "text-generation",
51
+ model=model,
52
+ tokenizer=tokenizer,
53
+ max_new_tokens=MAX_TOKENS,
54
+ temperature=TEMPERATURE,
55
+ do_sample=True,
56
+ pad_token_id=tokenizer.eos_token_id
57
+ )
58
+
59
+ print(f"βœ… Model {model_name} loaded successfully!")
60
+ return generator, tokenizer, model_name
61
+
62
+ except Exception as e:
63
+ print(f"❌ Error loading {model_name}: {e}")
64
+ # Fallback to a smaller model if the primary one fails
65
+ fallback_model = "microsoft/DialoGPT-medium"
66
+ print(f"πŸ”„ Trying fallback model: {fallback_model}")
67
+ return load_model(fallback_model)
68
+
69
+ # Initialize the model
70
+ generator, tokenizer, current_model_name = load_model(DEFAULT_MODEL)
71
+
72
+ # -------------------
73
+ # CHAT FUNCTION
74
+ # -------------------
75
+ def respond(message, history):
76
+ if not message.strip():
77
+ return "Please enter a medical question."
78
+
79
+ # Prepare the conversation prompt
80
+ conversation_history = ""
81
+ if history:
82
+ for user_msg, bot_msg in history:
83
+ conversation_history += f"User: {user_msg}\nAssistant: {bot_msg}\n"
84
+
85
+ full_prompt = f"{SYSTEM_MESSAGE}\n\n{conversation_history}User: {message}\nAssistant:"
86
+
87
+ try:
88
+ # Generate response
89
+ response = generator(
90
+ full_prompt,
91
+ max_new_tokens=MAX_TOKENS,
92
+ temperature=TEMPERATURE,
93
+ do_sample=True,
94
+ pad_token_id=tokenizer.eos_token_id
95
+ )[0]['generated_text']
96
+
97
+ # Extract only the new assistant response
98
+ assistant_response = response.split("Assistant:")[-1].strip()
99
+
100
+ # Clean up the response
101
+ if "User:" in assistant_response:
102
+ assistant_response = assistant_response.split("User:")[0].strip()
103
+
104
+ # Add safety disclaimer for symptom-related queries
105
+ symptom_keywords = ['symptom', 'pain', 'hurt', 'feel', 'headache', 'fever', 'cough', 'diagnose', 'treatment']
106
+ if any(keyword in message.lower() for keyword in symptom_keywords):
107
+ assistant_response += "\n\n⚠️ **Important**: I am an AI tutor for educational purposes only. Please consult a healthcare professional for personal medical concerns."
108
+
109
+ return assistant_response
110
+
111
+ except Exception as e:
112
+ return f"❌ Error generating response: {str(e)}"
113
+
114
+ def change_model(selected_model):
115
+ global generator, tokenizer, current_model_name
116
+ try:
117
+ generator, tokenizer, current_model_name = load_model(selected_model)
118
+ return f"βœ… Model switched to {selected_model}"
119
+ except Exception as e:
120
+ return f"❌ Failed to switch model: {str(e)}"
121
+
122
+ # -------------------
123
+ # GRADIO UI
124
+ # -------------------
125
+ with gr.Blocks(title="Medical AI Tutor", theme=gr.themes.Soft()) as demo:
126
+ gr.Markdown("""
127
+ # 🩺 Medical AI Tutor
128
+ **Educational medical Q&A powered by specialized AI models**
129
+
130
+ ⚠️ **Disclaimer**: This AI provides educational information only. It is NOT a substitute for professional medical advice.
131
+ """)
132
+
133
+ with gr.Row():
134
+ model_select = gr.Dropdown(
135
+ choices=[
136
+ "medalpaca/medalpaca-7b",
137
+ "stanford-aimi/stanford-medalpaca-7b",
138
+ "microsoft/BioGPT-Large",
139
+ "google/flan-t5-base" # Fallback option
140
+ ],
141
+ value=DEFAULT_MODEL,
142
+ label="🎯 Select Medical Model",
143
+ info="Choose which medical AI model to use"
144
+ )
145
+
146
+ status_text = gr.Textbox(
147
+ value=f"Current model: {current_model_name}",
148
+ label="Status",
149
+ interactive=False
150
+ )
151
+
152
+ # Enhanced chat interface
153
+ chatbot = gr.ChatInterface(
154
+ respond,
155
+ title="Medical Q&A",
156
+ description="Ask any medical education question below:",
157
+ examples=[
158
+ "Explain how antibiotics work",
159
+ "What is the pathophysiology of diabetes?",
160
+ "Describe the structure and function of the heart",
161
+ "What are the different types of neurotransmitters?",
162
+ "Explain the process of protein synthesis"
163
+ ]
164
+ )
165
+
166
+ # Safety disclaimer
167
+ gr.Markdown("""
168
+ ---
169
+ **πŸ”’ Safety Notice**:
170
+ - This AI is for **educational purposes only**
171
+ - It does **not** provide medical advice, diagnosis, or treatment
172
+ - Always consult healthcare professionals for personal health concerns
173
+ - Do not make healthcare decisions based on AI responses
174
+ """)
175
+
176
+ # Model change handler
177
+ model_select.change(
178
+ fn=change_model,
179
+ inputs=model_select,
180
+ outputs=status_text
181
+ )
182
+
183
+ # -------------------
184
+ # OPTIMIZATION FOR DIFFERENT HARDWARE
185
+ # -------------------
186
+ def optimize_for_hardware():
187
+ """Optimize settings based on available hardware"""
188
+ if torch.cuda.is_available():
189
+ print(f"🎯 Using GPU: {torch.cuda.get_device_name()}")
190
+ return "cuda"
191
+ else:
192
+ print("πŸ–₯️ Using CPU - consider using smaller models for better performance")
193
+ return "cpu"
194
+
195
+ if __name__ == "__main__":
196
+ device = optimize_for_hardware()
197
+ print("πŸš€ Starting Medical AI Tutor...")
198
+ demo.launch(
199
+ server_name="0.0.0.0",
200
+ server_port=7860,
201
+ share=False # Set to True if you want a public link
202
+ )