Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,8 +3,8 @@ import os
|
|
| 3 |
import requests
|
| 4 |
|
| 5 |
# Mistral API setup
|
| 6 |
-
MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY", "
|
| 7 |
-
MISTRAL_API_URL = "https://api.mistral.ai/v1/chat/completions"
|
| 8 |
|
| 9 |
def query_mistral(prompt, max_tokens=1024, temperature=0.7):
|
| 10 |
"""Query Mistral AI API"""
|
|
@@ -25,24 +25,38 @@ def query_mistral(prompt, max_tokens=1024, temperature=0.7):
|
|
| 25 |
response.raise_for_status()
|
| 26 |
return response.json()['choices'][0]['message']['content']
|
| 27 |
except requests.exceptions.RequestException as e:
|
| 28 |
-
return f"
|
| 29 |
except Exception as e:
|
| 30 |
-
return f"An unexpected error occurred. Please
|
| 31 |
|
| 32 |
-
def
|
| 33 |
-
"""
|
| 34 |
-
prompt = f"""You are
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
3. Follow-up questions if more information is needed
|
| 41 |
-
4. Clear recommendation on when to see a real doctor
|
| 42 |
-
5. A warm closing
|
| 43 |
|
| 44 |
-
Keep the
|
| 45 |
-
"""
|
|
|
|
| 46 |
return query_mistral(prompt)
|
| 47 |
|
| 48 |
def chatbot_response(message, history, name):
|
|
@@ -51,57 +65,74 @@ def chatbot_response(message, history, name):
|
|
| 51 |
|
| 52 |
# Simple greetings
|
| 53 |
if any(word in message_lower for word in ['hello', 'hi', 'hey']):
|
| 54 |
-
return f"Hello {name}! I'm Dr. Alex
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
elif any(word in message_lower for word in ['thank', 'thanks']):
|
| 56 |
-
return f"You're very welcome, {name}!
|
| 57 |
|
| 58 |
-
#
|
| 59 |
-
return
|
| 60 |
|
| 61 |
# Gradio Interface
|
| 62 |
-
with gr.Blocks(title="Personal Medical
|
| 63 |
-
gr.Markdown("# 👨⚕️ Your Personal Medical
|
| 64 |
|
| 65 |
# Get user's name for personalization
|
| 66 |
name = gr.Textbox(label="Your Name", placeholder="Please enter your name for personalized care")
|
| 67 |
|
| 68 |
with gr.Tabs():
|
| 69 |
-
with gr.TabItem("
|
| 70 |
-
gr.Markdown("##
|
| 71 |
chatbot = gr.ChatInterface(
|
| 72 |
fn=lambda msg, hist: chatbot_response(msg, hist, name.value),
|
| 73 |
examples=[
|
| 74 |
-
"I
|
| 75 |
-
"
|
| 76 |
-
"How
|
| 77 |
],
|
| 78 |
-
title="
|
| 79 |
)
|
| 80 |
|
| 81 |
-
with gr.TabItem("Symptom
|
| 82 |
-
gr.Markdown(f"## {name.value}, let's
|
| 83 |
with gr.Row():
|
| 84 |
with gr.Column():
|
| 85 |
age = gr.Number(label="Your Age", minimum=1, maximum=120)
|
| 86 |
gender = gr.Radio(choices=["Male", "Female", "Other"], label="Gender")
|
| 87 |
-
symptoms = gr.Textbox(label="Describe your symptoms", lines=3
|
|
|
|
| 88 |
duration = gr.Dropdown(
|
| 89 |
-
choices=["Less than
|
| 90 |
-
label="
|
| 91 |
)
|
| 92 |
-
severity = gr.Slider(1, 10, step=1, label="Severity (1-10)")
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
| 94 |
with gr.Column():
|
| 95 |
-
analysis_output = gr.Textbox(label="Dr. Alex's
|
| 96 |
|
| 97 |
analyze_btn.click(
|
| 98 |
-
lambda age, gender, symptoms, duration, severity:
|
| 99 |
name.value,
|
| 100 |
-
f"As a {age}-year-old {gender}, I've had
|
| 101 |
),
|
| 102 |
-
inputs=[age, gender, symptoms, duration, severity],
|
| 103 |
outputs=analysis_output
|
| 104 |
)
|
| 105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
# Launch app
|
| 107 |
demo.launch()
|
|
|
|
| 3 |
import requests
|
| 4 |
|
| 5 |
# Mistral API setup
|
| 6 |
+
MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY", "your_api_key_here") # Replace with your actual API key
|
| 7 |
+
MISTRAL_API_URL = "https://api.mistral.ai/v1/chat/completions"
|
| 8 |
|
| 9 |
def query_mistral(prompt, max_tokens=1024, temperature=0.7):
|
| 10 |
"""Query Mistral AI API"""
|
|
|
|
| 25 |
response.raise_for_status()
|
| 26 |
return response.json()['choices'][0]['message']['content']
|
| 27 |
except requests.exceptions.RequestException as e:
|
| 28 |
+
return f"I apologize, I'm currently unable to access my medical knowledge base. Please try again later."
|
| 29 |
except Exception as e:
|
| 30 |
+
return f"An unexpected error occurred. Please try rephrasing your question."
|
| 31 |
|
| 32 |
+
def generate_medical_response(name, message):
|
| 33 |
+
"""Generate structured medical response"""
|
| 34 |
+
prompt = f"""You are Dr. Alex, an experienced physician. {name} asks: "{message}"
|
| 35 |
+
|
| 36 |
+
Provide a detailed response with these sections (use bullet points):
|
| 37 |
+
|
| 38 |
+
[Assessment]
|
| 39 |
+
- Brief professional assessment of the described condition
|
| 40 |
+
|
| 41 |
+
[Recommended Actions] (3-5 points)
|
| 42 |
+
- Specific self-care measures
|
| 43 |
+
- Home remedies
|
| 44 |
+
- Lifestyle adjustments
|
| 45 |
+
|
| 46 |
+
[Medical Treatments] (if applicable)
|
| 47 |
+
- OTC medications (with dosage examples)
|
| 48 |
+
- When to consider prescription treatments
|
| 49 |
+
|
| 50 |
+
[Warning Signs] (Red Flags)
|
| 51 |
+
- Symptoms that require immediate medical attention
|
| 52 |
|
| 53 |
+
[Follow-up Advice]
|
| 54 |
+
- When to revisit the issue
|
| 55 |
+
- Recommended tests or specialist consultation if needed
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
+
Keep the tone professional yet compassionate. Use simple language.
|
| 58 |
+
Provide concrete, actionable advice. Limit to 250 words."""
|
| 59 |
+
|
| 60 |
return query_mistral(prompt)
|
| 61 |
|
| 62 |
def chatbot_response(message, history, name):
|
|
|
|
| 65 |
|
| 66 |
# Simple greetings
|
| 67 |
if any(word in message_lower for word in ['hello', 'hi', 'hey']):
|
| 68 |
+
return f"""Hello {name}! I'm Dr. Alex. How can I assist you today?
|
| 69 |
+
|
| 70 |
+
Please remember:
|
| 71 |
+
- I can provide general health information
|
| 72 |
+
- For emergencies, contact local emergency services
|
| 73 |
+
- Always consult your personal physician for specific medical advice"""
|
| 74 |
+
|
| 75 |
elif any(word in message_lower for word in ['thank', 'thanks']):
|
| 76 |
+
return f"You're very welcome, {name}! Wishing you good health. Is there anything else you'd like to discuss today?"
|
| 77 |
|
| 78 |
+
# Medical responses
|
| 79 |
+
return generate_medical_response(name, message)
|
| 80 |
|
| 81 |
# Gradio Interface
|
| 82 |
+
with gr.Blocks(title="Dr. Alex - Personal Medical Consultant", theme=gr.themes.Soft()) as demo:
|
| 83 |
+
gr.Markdown("# 👨⚕️ Dr. Alex - Your Personal Medical Consultant")
|
| 84 |
|
| 85 |
# Get user's name for personalization
|
| 86 |
name = gr.Textbox(label="Your Name", placeholder="Please enter your name for personalized care")
|
| 87 |
|
| 88 |
with gr.Tabs():
|
| 89 |
+
with gr.TabItem("Consult Dr. Alex"):
|
| 90 |
+
gr.Markdown("## Describe your health concerns")
|
| 91 |
chatbot = gr.ChatInterface(
|
| 92 |
fn=lambda msg, hist: chatbot_response(msg, hist, name.value),
|
| 93 |
examples=[
|
| 94 |
+
"I have fever and body aches since yesterday",
|
| 95 |
+
"Best home remedies for sore throat",
|
| 96 |
+
"How to manage mild back pain?"
|
| 97 |
],
|
| 98 |
+
title="Private Consultation with Dr. Alex"
|
| 99 |
)
|
| 100 |
|
| 101 |
+
with gr.TabItem("Structured Symptom Checker"):
|
| 102 |
+
gr.Markdown(f"## {name.value}, let's thoroughly evaluate your symptoms")
|
| 103 |
with gr.Row():
|
| 104 |
with gr.Column():
|
| 105 |
age = gr.Number(label="Your Age", minimum=1, maximum=120)
|
| 106 |
gender = gr.Radio(choices=["Male", "Female", "Other"], label="Gender")
|
| 107 |
+
symptoms = gr.Textbox(label="Describe your symptoms in detail", lines=3,
|
| 108 |
+
placeholder="Include location, nature of pain, triggers, etc.")
|
| 109 |
duration = gr.Dropdown(
|
| 110 |
+
choices=["Less than 24 hours", "1-3 days", "4-7 days", "1-2 weeks", "2-4 weeks", "More than 1 month"],
|
| 111 |
+
label="Duration of symptoms"
|
| 112 |
)
|
| 113 |
+
severity = gr.Slider(1, 10, step=1, label="Pain/Severity level (1-10)")
|
| 114 |
+
aggravating_factors = gr.Textbox(label="What makes it worse?", lines=2)
|
| 115 |
+
relieving_factors = gr.Textbox(label="What provides relief?", lines=2)
|
| 116 |
+
analyze_btn = gr.Button("Get Detailed Medical Advice", variant="primary")
|
| 117 |
+
|
| 118 |
with gr.Column():
|
| 119 |
+
analysis_output = gr.Textbox(label="Dr. Alex's Professional Evaluation", lines=15, interactive=False)
|
| 120 |
|
| 121 |
analyze_btn.click(
|
| 122 |
+
lambda age, gender, symptoms, duration, severity, aggravating, relieving: generate_medical_response(
|
| 123 |
name.value,
|
| 124 |
+
f"As a {age}-year-old {gender}, I've had: {symptoms} for {duration}. Severity: {severity}/10. Gets worse with {aggravating} and better with {relieving}."
|
| 125 |
),
|
| 126 |
+
inputs=[age, gender, symptoms, duration, severity, aggravating_factors, relieving_factors],
|
| 127 |
outputs=analysis_output
|
| 128 |
)
|
| 129 |
|
| 130 |
+
gr.Markdown("""
|
| 131 |
+
<div style='background:#f8f9fa;padding:20px;border-radius:10px;margin-top:20px;'>
|
| 132 |
+
<h3>Important Disclaimer</h3>
|
| 133 |
+
<p>This AI provides general health information only, not medical advice. Always consult a qualified healthcare provider for personal medical concerns. In emergencies, contact your local emergency services immediately.</p>
|
| 134 |
+
</div>
|
| 135 |
+
""")
|
| 136 |
+
|
| 137 |
# Launch app
|
| 138 |
demo.launch()
|