Pranith06 commited on
Commit
98e6dc9
·
verified ·
1 Parent(s): 44f7291

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -155
app.py CHANGED
@@ -1,165 +1,50 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
- import requests
4
 
5
- class AIHealthAssistant:
6
- def __init__(self):
7
- # Initialize symptom checker model
8
- self.symptom_checker = pipeline(
9
- "text-classification",
10
- model="microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext"
11
- )
12
-
13
- # Initialize medical QA model
14
- self.medical_qa = pipeline(
15
- "question-answering",
16
- model="deepset/roberta-base-squad2"
17
- )
18
-
19
- # Knowledge base (can be replaced with API calls)
20
- self.disease_db = {
21
- "influenza": {
22
- "symptoms": ["fever", "cough", "sore throat", "runny nose", "body aches"],
23
- "advice": "Rest, stay hydrated, take fever reducers like acetaminophen",
24
- "precautions": ["Annual flu vaccine", "Frequent hand washing", "Avoid close contact"]
25
- },
26
- "migraine": {
27
- "symptoms": ["severe headache", "nausea", "sensitivity to light", "aura"],
28
- "advice": "Rest in dark room, take prescribed medication, apply cold compress",
29
- "precautions": ["Identify triggers", "Maintain sleep schedule", "Stay hydrated"]
30
- }
31
- }
32
-
33
- def get_disease_from_symptoms(self, symptoms):
34
- """Predict disease from symptoms using Hugging Face model"""
35
- try:
36
- # For production, replace with a proper medical model
37
- result = self.symptom_checker(symptoms)
38
-
39
- # Map to diseases in our database
40
- for disease in self.disease_db:
41
- if disease in symptoms.lower():
42
- return disease
43
-
44
- # Fallback to first disease (in real app, use proper mapping)
45
- return list(self.disease_db.keys())[0]
46
-
47
- except Exception as e:
48
- print(f"Model error: {e}")
49
- return "unknown"
50
 
51
- def get_medical_info(self, disease, info_type):
52
- """Get medical information from database or API"""
53
- disease = disease.lower()
54
-
55
- # Check local database first
56
- if disease in self.disease_db:
57
- return self.disease_db[disease].get(info_type, "Information not available")
58
-
59
- # Fallback to API (example using hypothetical medical API)
60
- try:
61
- if info_type == "symptoms":
62
- prompt = f"What are the symptoms of {disease}?"
63
- elif info_type == "advice":
64
- prompt = f"What is the treatment for {disease}?"
65
- else:
66
- prompt = f"What precautions should be taken for {disease}?"
67
-
68
- # In a real app, replace with actual API call:
69
- # response = requests.get(f"https://medical-api.example.com/{disease}")
70
- # return response.json().get(info_type)
71
-
72
- # For demo, using the QA model
73
- context = f"{disease} is a medical condition. {self.get_medical_advice_from_api(disease)}"
74
- result = self.medical_qa(question=prompt, context=context)
75
- return result['answer']
76
-
77
- except Exception as e:
78
- print(f"API error: {e}")
79
- return "Information not available"
80
 
81
- def get_medical_advice_from_api(self, disease):
82
- """Simulate API response for demo purposes"""
83
- api_responses = {
84
- "diabetes": "Diabetes requires blood sugar monitoring, insulin therapy, and dietary changes.",
85
- "hypertension": "Hypertension management includes medication, low-salt diet, and regular exercise."
86
- }
87
- return api_responses.get(disease.lower(), "Consult a healthcare professional for proper diagnosis and treatment.")
88
 
89
- def create_demo():
90
- assistant = AIHealthAssistant()
 
 
 
 
 
 
 
91
 
92
- def process_input(user_input, mode):
93
- if mode == "Symptoms to Disease":
94
- disease = assistant.get_disease_from_symptoms(user_input)
95
- symptoms = assistant.get_medical_info(disease, "symptoms")
96
- advice = assistant.get_medical_info(disease, "advice")
97
- precautions = assistant.get_medical_info(disease, "precautions")
98
-
99
- output = (
100
- f"🔍 Possible Condition: {disease.capitalize()}\n\n"
101
- f"📋 Symptoms:\n- " + "\n- ".join(symptoms) + "\n\n"
102
- f"💊 Recommended Actions:\n{advice}\n\n"
103
- f"🛡️ Precautions:\n- " + "\n- ".join(precautions)
104
- )
105
-
106
- elif mode == "Disease to Symptoms":
107
- symptoms = assistant.get_medical_info(user_input, "symptoms")
108
- advice = assistant.get_medical_info(user_input, "advice")
109
-
110
- output = (
111
- f"📋 Symptoms of {user_input.capitalize()}:\n- " + "\n- ".join(symptoms) + "\n\n"
112
- f"💊 Recommended Actions:\n{advice}"
113
- )
114
-
115
- return output
116
 
117
- with gr.Blocks(title="AI Health Assistant") as demo:
118
- gr.Markdown("# 🏥 AI Health Assistant")
119
- gr.Markdown("Enter symptoms or a disease name to get medical information")
120
-
121
- with gr.Row():
122
- input_mode = gr.Radio(
123
- choices=["Symptoms to Disease", "Disease to Symptoms"],
124
- label="Input Mode"
125
- )
126
- user_input = gr.Textbox(
127
- label="Input",
128
- placeholder="Enter symptoms or disease name..."
129
- )
130
-
131
- submit_btn = gr.Button("Get Medical Information")
132
- output = gr.Textbox(label="Result", interactive=False, lines=10)
133
-
134
- # Example inputs
135
- gr.Examples(
136
- examples=[
137
- ["headache, nausea, sensitivity to light", "Symptoms to Disease"],
138
- ["influenza", "Disease to Symptoms"],
139
- ["fever, cough, sore throat", "Symptoms to Disease"]
140
- ],
141
- inputs=[user_input, input_mode],
142
- outputs=output,
143
- fn=process_input,
144
- cache_examples=True
145
- )
146
-
147
- submit_btn.click(
148
- fn=process_input,
149
- inputs=[user_input, input_mode],
150
- outputs=output
151
- )
152
-
153
- gr.Markdown("""
154
- ## ⚠️ Important Disclaimer
155
- This AI assistant provides general health information only and is not a substitute
156
- for professional medical advice, diagnosis, or treatment.
157
- Always seek the advice of your physician or other qualified health provider
158
- with any questions you may have regarding a medical condition.
159
- """)
160
 
161
- return demo
 
 
 
162
 
163
- if __name__ == "__main__":
164
- demo = create_demo()
165
- demo.launch()
 
1
  import gradio as gr
2
  from transformers import pipeline
 
3
 
4
+ # Initialize medical LLM (using smaller model for Spaces compatibility)
5
+ med_llm = pipeline("text-generation", model="distilgpt2")
6
+
7
+ def diagnose(symptoms):
8
+ prompt = f"""Act as an AI doctor. Analyze these symptoms:
9
+ {symptoms}
10
+
11
+ Possible diagnoses from most to least likely:
12
+ 1."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ diagnosis = med_llm(
15
+ prompt,
16
+ max_length=400,
17
+ num_return_sequences=1,
18
+ temperature=0.7
19
+ )[0]['generated_text']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ # Extract just the diagnosis part
22
+ return diagnosis.split("1.", 1)[-1].strip()
 
 
 
 
 
23
 
24
+ with gr.Blocks() as demo:
25
+ gr.Markdown("# 🌍 Global Symptom Checker")
26
+ gr.Markdown("Enter symptoms to get possible diagnoses")
27
+
28
+ with gr.Row():
29
+ symptoms = gr.Textbox(label="Describe your symptoms", lines=3)
30
+ submit = gr.Button("Diagnose")
31
+
32
+ output = gr.Textbox(label="Possible Conditions", interactive=False)
33
 
34
+ gr.Examples(
35
+ examples=[
36
+ ["fever, headache, muscle pain"],
37
+ ["cough, shortness of breath, fatigue"],
38
+ ["rash, joint pain, red eyes"]
39
+ ],
40
+ inputs=symptoms
41
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ submit.click(diagnose, inputs=symptoms, outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ gr.Markdown("""
46
+ ⚠️ **Disclaimer**: This AI provides general information only.
47
+ Always consult a real doctor for medical advice.
48
+ """)
49
 
50
+ demo.launch()