Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,26 +1,25 @@
|
|
1 |
-
import
|
2 |
from transformers import pipeline
|
3 |
from fpdf import FPDF
|
4 |
import os
|
5 |
from groq import Groq
|
6 |
from deep_translator import GoogleTranslator
|
7 |
-
import time
|
8 |
|
9 |
-
# Load API
|
10 |
-
groq_api_key = os.getenv("groq_api_key")
|
11 |
groq_client = Groq(api_key=groq_api_key)
|
12 |
|
13 |
-
#
|
14 |
-
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
|
15 |
-
|
16 |
-
# Translation Function
|
17 |
def translate_text(text, target_lang="en"):
|
18 |
try:
|
19 |
return GoogleTranslator(source="auto", target=target_lang).translate(text)
|
20 |
except Exception as e:
|
21 |
return f"Translation Error: {str(e)}"
|
22 |
|
23 |
-
#
|
|
|
|
|
|
|
24 |
conditions = [
|
25 |
"Asthma", "COPD", "Pneumonia", "Tuberculosis", "COVID-19", "Bronchitis",
|
26 |
"Heart Failure", "Hypertension", "Diabetes Type 1", "Diabetes Type 2",
|
@@ -28,7 +27,7 @@ conditions = [
|
|
28 |
"Chronic Kidney Disease", "UTI", "Osteoporosis", "Psoriasis", "Epilepsy"
|
29 |
]
|
30 |
|
31 |
-
# Specialist Mapping
|
32 |
specialist_mapping = {
|
33 |
"Asthma": ("Pulmonologist", "Respiratory System"),
|
34 |
"COPD": ("Pulmonologist", "Respiratory System"),
|
@@ -51,11 +50,11 @@ specialist_mapping = {
|
|
51 |
"Epilepsy": ("Neurologist", "Nervous System")
|
52 |
}
|
53 |
|
54 |
-
# Function to generate expert analysis
|
55 |
def generate_expert_analysis(condition, symptoms):
|
|
|
56 |
specialist_title = specialist_mapping.get(condition, ("General Physician", "General Medicine"))[0]
|
57 |
|
58 |
-
prompt = f"""As a {specialist_title.lower()}, explain {condition} to a patient experiencing these symptoms: "{symptoms}".
|
59 |
|
60 |
Structure the response into:
|
61 |
1. **Biological Process**
|
@@ -63,7 +62,8 @@ def generate_expert_analysis(condition, symptoms):
|
|
63 |
3. **Long-term Care**
|
64 |
4. **Emergency Signs**
|
65 |
5. **Diet Plan**
|
66 |
-
|
|
|
67 |
"""
|
68 |
|
69 |
response = groq_client.chat.completions.create(
|
@@ -75,10 +75,11 @@ def generate_expert_analysis(condition, symptoms):
|
|
75 |
|
76 |
return response.choices[0].message.content
|
77 |
|
78 |
-
# Function to generate medical report
|
79 |
def create_medical_report(symptoms):
|
|
|
80 |
try:
|
81 |
translated_symptoms = translate_text(symptoms, "en")
|
|
|
82 |
result = classifier(translated_symptoms, conditions, multi_label=False)
|
83 |
diagnosis = result['labels'][0]
|
84 |
specialist, system = specialist_mapping.get(diagnosis, ("General Physician", "General Medicine"))
|
@@ -92,120 +93,53 @@ def create_medical_report(symptoms):
|
|
92 |
f"**Affected System:** {system}\n"
|
93 |
f"**Consult:** {specialist}\n\n"
|
94 |
f"**Expert Analysis:**\n{expert_analysis}\n\n"
|
|
|
|
|
|
|
|
|
|
|
95 |
)
|
96 |
|
97 |
pdf = FPDF()
|
98 |
pdf.add_page()
|
99 |
pdf.set_font("Arial", size=12)
|
100 |
pdf.multi_cell(0, 10, full_report)
|
101 |
-
|
102 |
-
pdf.output(pdf_path)
|
103 |
|
104 |
-
return full_report,
|
105 |
|
106 |
except Exception as e:
|
107 |
return f"Error generating report: {str(e)}", None
|
108 |
|
109 |
-
#
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
[data-testid="stSidebar"] a {
|
128 |
-
color: white !important;
|
129 |
-
font-size: 18px !important;
|
130 |
-
}
|
131 |
-
|
132 |
-
/* Custom Buttons */
|
133 |
-
.stButton>button {
|
134 |
-
background-color: #16A085;
|
135 |
-
color: white;
|
136 |
-
padding: 10px 20px;
|
137 |
-
border-radius: 8px;
|
138 |
-
font-size: 16px;
|
139 |
-
}
|
140 |
-
|
141 |
-
.stButton>button:hover {
|
142 |
-
background-color: #1ABC9C;
|
143 |
-
}
|
144 |
-
|
145 |
-
/* Custom Input Box */
|
146 |
-
.stTextInput>div>div>input {
|
147 |
-
background-color: white !important;
|
148 |
-
border-radius: 10px !important;
|
149 |
-
border: 2px solid #16A085 !important;
|
150 |
-
padding: 8px !important;
|
151 |
-
}
|
152 |
-
|
153 |
-
/* Title Styling */
|
154 |
-
.stApp h1 {
|
155 |
-
text-align: center;
|
156 |
-
font-size: 36px;
|
157 |
-
color: #2C3E50;
|
158 |
-
}
|
159 |
-
|
160 |
-
</style>
|
161 |
-
""", unsafe_allow_html=True)
|
162 |
-
|
163 |
-
|
164 |
-
# Sidebar UI
|
165 |
-
with st.sidebar:
|
166 |
-
st.markdown("## π **Navigation**", unsafe_allow_html=True)
|
167 |
-
page = st.radio("", ["π Home", "π Diagnosis", "π’ About"])
|
168 |
-
st.markdown("---")
|
169 |
-
st.markdown("### π **Built with AI & Healthcare Experts**")
|
170 |
-
|
171 |
-
|
172 |
-
# Main Page
|
173 |
-
st.title("π©Ί MedExpert: AI-Powered Clinical Analysis System")
|
174 |
-
st.markdown("π‘ *Get AI-powered medical analysis & professional reports instantly!*")
|
175 |
-
|
176 |
-
# Home Page
|
177 |
-
if page == "π Home":
|
178 |
-
st.image("https://source.unsplash.com/800x400/?healthcare,hospital", use_container_width=True)
|
179 |
-
st.write("### Welcome to MedExpert!")
|
180 |
-
st.write("πΉ AI-based clinical diagnosis system for analyzing symptoms.")
|
181 |
-
st.write("πΉ Generates professional **medical reports** instantly.")
|
182 |
-
st.write("πΉ Provides **expert doctor recommendations**.")
|
183 |
-
st.write("πΉ Supports **multiple languages** (Urdu, English, Arabic, etc.).")
|
184 |
-
|
185 |
-
# Diagnosis Page
|
186 |
-
elif page == "π Diagnosis":
|
187 |
-
st.subheader("π Describe Your Symptoms")
|
188 |
-
symptoms = st.text_area("Enter symptoms in any language", placeholder="e.g., Mujhay sar main dard hai")
|
189 |
-
|
190 |
-
if st.button("π§ββοΈ Get Diagnosis"):
|
191 |
-
if symptoms.strip():
|
192 |
-
with st.spinner("π **Analyzing Symptoms... Please wait...**"):
|
193 |
-
time.sleep(2) # Simulate processing
|
194 |
-
report_text, pdf_file = create_medical_report(symptoms)
|
195 |
-
|
196 |
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
elif page == "π’ About":
|
209 |
-
st.write("### βΉοΈ About MedExpert")
|
210 |
-
st.write("This AI-powered medical system helps users get professional diagnosis and expert medical recommendations.")
|
211 |
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
from transformers import pipeline
|
3 |
from fpdf import FPDF
|
4 |
import os
|
5 |
from groq import Groq
|
6 |
from deep_translator import GoogleTranslator
|
|
|
7 |
|
8 |
+
# β
Load Groq API key
|
9 |
+
groq_api_key = os.getenv("groq_api_key")
|
10 |
groq_client = Groq(api_key=groq_api_key)
|
11 |
|
12 |
+
# β
Use Google Translate for auto-detection & translation
|
|
|
|
|
|
|
13 |
def translate_text(text, target_lang="en"):
|
14 |
try:
|
15 |
return GoogleTranslator(source="auto", target=target_lang).translate(text)
|
16 |
except Exception as e:
|
17 |
return f"Translation Error: {str(e)}"
|
18 |
|
19 |
+
# β
Load Models
|
20 |
+
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
|
21 |
+
|
22 |
+
# β
Medical Conditions List
|
23 |
conditions = [
|
24 |
"Asthma", "COPD", "Pneumonia", "Tuberculosis", "COVID-19", "Bronchitis",
|
25 |
"Heart Failure", "Hypertension", "Diabetes Type 1", "Diabetes Type 2",
|
|
|
27 |
"Chronic Kidney Disease", "UTI", "Osteoporosis", "Psoriasis", "Epilepsy"
|
28 |
]
|
29 |
|
30 |
+
# β
Specialist Mapping
|
31 |
specialist_mapping = {
|
32 |
"Asthma": ("Pulmonologist", "Respiratory System"),
|
33 |
"COPD": ("Pulmonologist", "Respiratory System"),
|
|
|
50 |
"Epilepsy": ("Neurologist", "Nervous System")
|
51 |
}
|
52 |
|
|
|
53 |
def generate_expert_analysis(condition, symptoms):
|
54 |
+
"""Generates expert medical analysis using Groq API"""
|
55 |
specialist_title = specialist_mapping.get(condition, ("General Physician", "General Medicine"))[0]
|
56 |
|
57 |
+
prompt = f"""As a {specialist_title.lower()}, explain {condition} to a patient experiencing these symptoms: "{symptoms}".
|
58 |
|
59 |
Structure the response into:
|
60 |
1. **Biological Process**
|
|
|
62 |
3. **Long-term Care**
|
63 |
4. **Emergency Signs**
|
64 |
5. **Diet Plan**
|
65 |
+
|
66 |
+
Use professional yet simple language. **No AI disclaimers or generic advice**.
|
67 |
"""
|
68 |
|
69 |
response = groq_client.chat.completions.create(
|
|
|
75 |
|
76 |
return response.choices[0].message.content
|
77 |
|
|
|
78 |
def create_medical_report(symptoms):
|
79 |
+
"""Generates a complete medical report"""
|
80 |
try:
|
81 |
translated_symptoms = translate_text(symptoms, "en")
|
82 |
+
|
83 |
result = classifier(translated_symptoms, conditions, multi_label=False)
|
84 |
diagnosis = result['labels'][0]
|
85 |
specialist, system = specialist_mapping.get(diagnosis, ("General Physician", "General Medicine"))
|
|
|
93 |
f"**Affected System:** {system}\n"
|
94 |
f"**Consult:** {specialist}\n\n"
|
95 |
f"**Expert Analysis:**\n{expert_analysis}\n\n"
|
96 |
+
"**Key Questions for Your Doctor:**\n"
|
97 |
+
"1. Is this condition acute or chronic?\n"
|
98 |
+
"2. What medication options are suitable?\n"
|
99 |
+
"3. What lifestyle changes help manage this condition?\n"
|
100 |
+
"4. What warning signs require immediate attention?\n"
|
101 |
)
|
102 |
|
103 |
pdf = FPDF()
|
104 |
pdf.add_page()
|
105 |
pdf.set_font("Arial", size=12)
|
106 |
pdf.multi_cell(0, 10, full_report)
|
107 |
+
pdf.output("report.pdf")
|
|
|
108 |
|
109 |
+
return full_report, "report.pdf"
|
110 |
|
111 |
except Exception as e:
|
112 |
return f"Error generating report: {str(e)}", None
|
113 |
|
114 |
+
# β
Create Sidebar with Navigation
|
115 |
+
with gr.Blocks(css="body { background-color: #f5f7fa; }") as app:
|
116 |
+
with gr.Row():
|
117 |
+
gr.Markdown("<h1 style='text-align: center; color: #4A90E2;'>MedExpert AI</h1>")
|
118 |
+
|
119 |
+
with gr.Tabs():
|
120 |
+
with gr.TabItem("π Home"):
|
121 |
+
gr.Markdown("""
|
122 |
+
<h2 style="color: #4A90E2;">Welcome to MedExpert</h2>
|
123 |
+
<p style="font-size:18px;">An AI-powered medical assistant that provides expert analysis based on your symptoms.</p>
|
124 |
+
<p style="font-size:18px;">Simply describe your symptoms, and let AI generate a detailed report!</p>
|
125 |
+
""")
|
126 |
+
|
127 |
+
with gr.TabItem("π Medical Diagnosis"):
|
128 |
+
with gr.Row():
|
129 |
+
symptoms_input = gr.Textbox(label="Describe Your Symptoms", placeholder="e.g., Mujhay sar main dard hai", interactive=True)
|
130 |
+
report_btn = gr.Button("π Generate Report", elem_id="generate-btn")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
+
with gr.Row():
|
133 |
+
report_output = gr.Textbox(label="Complete Medical Report", interactive=False)
|
134 |
+
pdf_output = gr.File(label="Download PDF Report")
|
135 |
+
|
136 |
+
report_btn.click(create_medical_report, inputs=[symptoms_input], outputs=[report_output, pdf_output])
|
137 |
+
|
138 |
+
with gr.TabItem("βΉοΈ About"):
|
139 |
+
gr.Markdown("""
|
140 |
+
<h2 style="color: #4A90E2;">About This App</h2>
|
141 |
+
<p style="font-size:18px;">MedExpert AI is an intelligent health assistant designed to provide expert insights into medical conditions.</p>
|
142 |
+
""")
|
|
|
|
|
|
|
143 |
|
144 |
+
# β
Launch App
|
145 |
+
app.launch()
|