File size: 6,683 Bytes
9a243e1
 
b8fdad3
9a243e1
b8fdad3
9a243e1
b8fdad3
05e9d12
b8fdad3
 
05e9d12
9a243e1
b8fdad3
 
 
 
 
05e9d12
b8fdad3
 
 
 
 
 
9a243e1
b8fdad3
 
 
 
9a243e1
 
 
b8fdad3
 
05e9d12
b8fdad3
 
05e9d12
b8fdad3
 
 
 
05e9d12
b8fdad3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05e9d12
b8fdad3
 
 
05e9d12
b8fdad3
 
 
 
9a243e1
05e9d12
b8fdad3
 
 
 
 
 
 
 
 
 
05e9d12
b8fdad3
 
05e9d12
b8fdad3
 
 
 
 
 
 
 
 
 
 
 
 
9a243e1
b8fdad3
 
 
05e9d12
b8fdad3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a243e1
b8fdad3
05e9d12
 
b8fdad3
 
 
05e9d12
b8fdad3
 
 
 
05e9d12
9a243e1
b8fdad3
 
 
05e9d12
 
9a243e1
05e9d12
 
b8fdad3
 
 
 
05e9d12
9a243e1
05e9d12
9a243e1
05e9d12
b8fdad3
05e9d12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import gradio as gr
from transformers import pipeline
import requests

class AIHealthAssistant:
    def __init__(self):
        # Initialize symptom checker model
        self.symptom_checker = pipeline(
            "text-classification",
            model="microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext"
        )
        
        # Initialize medical QA model
        self.medical_qa = pipeline(
            "question-answering",
            model="deepset/roberta-base-squad2"
        )
        
        # Knowledge base (can be replaced with API calls)
        self.disease_db = {
            "influenza": {
                "symptoms": ["fever", "cough", "sore throat", "runny nose", "body aches"],
                "advice": "Rest, stay hydrated, take fever reducers like acetaminophen",
                "precautions": ["Annual flu vaccine", "Frequent hand washing", "Avoid close contact"]
            },
            "migraine": {
                "symptoms": ["severe headache", "nausea", "sensitivity to light", "aura"],
                "advice": "Rest in dark room, take prescribed medication, apply cold compress",
                "precautions": ["Identify triggers", "Maintain sleep schedule", "Stay hydrated"]
            }
        }
    
    def get_disease_from_symptoms(self, symptoms):
        """Predict disease from symptoms using Hugging Face model"""
        try:
            # For production, replace with a proper medical model
            result = self.symptom_checker(symptoms)
            
            # Map to diseases in our database
            for disease in self.disease_db:
                if disease in symptoms.lower():
                    return disease
            
            # Fallback to first disease (in real app, use proper mapping)
            return list(self.disease_db.keys())[0]
        
        except Exception as e:
            print(f"Model error: {e}")
            return "unknown"
    
    def get_medical_info(self, disease, info_type):
        """Get medical information from database or API"""
        disease = disease.lower()
        
        # Check local database first
        if disease in self.disease_db:
            return self.disease_db[disease].get(info_type, "Information not available")
        
        # Fallback to API (example using hypothetical medical API)
        try:
            if info_type == "symptoms":
                prompt = f"What are the symptoms of {disease}?"
            elif info_type == "advice":
                prompt = f"What is the treatment for {disease}?"
            else:
                prompt = f"What precautions should be taken for {disease}?"
            
            # In a real app, replace with actual API call:
            # response = requests.get(f"https://medical-api.example.com/{disease}")
            # return response.json().get(info_type)
            
            # For demo, using the QA model
            context = f"{disease} is a medical condition. {self.get_medical_advice_from_api(disease)}"
            result = self.medical_qa(question=prompt, context=context)
            return result['answer']
        
        except Exception as e:
            print(f"API error: {e}")
            return "Information not available"
    
    def get_medical_advice_from_api(self, disease):
        """Simulate API response for demo purposes"""
        api_responses = {
            "diabetes": "Diabetes requires blood sugar monitoring, insulin therapy, and dietary changes.",
            "hypertension": "Hypertension management includes medication, low-salt diet, and regular exercise."
        }
        return api_responses.get(disease.lower(), "Consult a healthcare professional for proper diagnosis and treatment.")

def create_demo():
    assistant = AIHealthAssistant()
    
    def process_input(user_input, mode):
        if mode == "Symptoms to Disease":
            disease = assistant.get_disease_from_symptoms(user_input)
            symptoms = assistant.get_medical_info(disease, "symptoms")
            advice = assistant.get_medical_info(disease, "advice")
            precautions = assistant.get_medical_info(disease, "precautions")
            
            output = (
                f"πŸ” Possible Condition: {disease.capitalize()}\n\n"
                f"πŸ“‹ Symptoms:\n- " + "\n- ".join(symptoms) + "\n\n"
                f"πŸ’Š Recommended Actions:\n{advice}\n\n"
                f"πŸ›‘οΈ Precautions:\n- " + "\n- ".join(precautions)
            )
        
        elif mode == "Disease to Symptoms":
            symptoms = assistant.get_medical_info(user_input, "symptoms")
            advice = assistant.get_medical_info(user_input, "advice")
            
            output = (
                f"πŸ“‹ Symptoms of {user_input.capitalize()}:\n- " + "\n- ".join(symptoms) + "\n\n"
                f"πŸ’Š Recommended Actions:\n{advice}"
            )
        
        return output
    
    with gr.Blocks(title="AI Health Assistant") as demo:
        gr.Markdown("# πŸ₯ AI Health Assistant")
        gr.Markdown("Enter symptoms or a disease name to get medical information")
        
        with gr.Row():
            input_mode = gr.Radio(
                choices=["Symptoms to Disease", "Disease to Symptoms"],
                label="Input Mode"
            )
            user_input = gr.Textbox(
                label="Input",
                placeholder="Enter symptoms or disease name..."
            )
        
        submit_btn = gr.Button("Get Medical Information")
        output = gr.Textbox(label="Result", interactive=False, lines=10)
        
        # Example inputs
        gr.Examples(
            examples=[
                ["headache, nausea, sensitivity to light", "Symptoms to Disease"],
                ["influenza", "Disease to Symptoms"],
                ["fever, cough, sore throat", "Symptoms to Disease"]
            ],
            inputs=[user_input, input_mode],
            outputs=output,
            fn=process_input,
            cache_examples=True
        )
        
        submit_btn.click(
            fn=process_input,
            inputs=[user_input, input_mode],
            outputs=output
        )
        
        gr.Markdown("""
        ## ⚠️ Important Disclaimer
        This AI assistant provides general health information only and is not a substitute 
        for professional medical advice, diagnosis, or treatment.
        Always seek the advice of your physician or other qualified health provider 
        with any questions you may have regarding a medical condition.
        """)
    
    return demo

if __name__ == "__main__":
    demo = create_demo()
    demo.launch()