VHA1 / app.py
lukiod's picture
Create app.py
4ef990b verified
raw
history blame
9.82 kB
import gradio as gr
import pandas as pd
from datetime import datetime
from huggingface_hub import InferenceClient
import json
import os
from typing import Optional
# Initialize LLM client
def init_llm():
try:
client = InferenceClient(
model="meta-llama/Llama-2-7b-chat-hf",
token=os.getenv("HF_TOKEN")
)
return client, True
except Exception as e:
print(f"LLM initialization failed: {str(e)}")
return None, False
llm_client, has_llm = init_llm()
# Global storage (in production, use a database)
metrics_data = []
medication_data = []
chat_history = []
def generate_prompt(instruction: str, context: str = "") -> str:
"""Generate prompt for LLaMA format"""
system_prompt = """You are a helpful healthcare assistant. Provide accurate information while noting
you're not a replacement for professional medical advice. Always include relevant medical disclaimers."""
return f"""<s>[INST] <<SYS>>{system_prompt}<</SYS>>
{context}
{instruction} [/INST]"""
def get_llm_response(prompt: str, temperature: float = 0.7) -> str:
"""Get response from LLM"""
if not has_llm:
return "Service is running in fallback mode. Using basic response templates."
try:
formatted_prompt = generate_prompt(prompt)
response = llm_client.text_generation(
formatted_prompt,
max_new_tokens=512,
temperature=temperature,
repetition_penalty=1.1
)
return response
except Exception as e:
return f"Error accessing LLM: {str(e)}"
def analyze_symptoms(symptoms: str) -> str:
"""Analyze symptoms using LLM"""
if not symptoms:
return "Please describe your symptoms."
prompt = f"""Analyze these symptoms and provide a detailed assessment:
Symptoms: {symptoms}
Please provide:
1. Risk Level (Low/Medium/High)
2. Possible causes
3. Recommendations
4. Whether immediate medical attention is needed
Format the response in a clear, structured way."""
response = get_llm_response(prompt, temperature=0.3)
return response if response else "Unable to analyze symptoms. Please try again."
def get_health_advice(topic: str, question: str) -> str:
"""Get health advice using LLM"""
if not question:
return "Please enter a question."
context = f"Topic: {topic}\nContext: {HEALTH_KNOWLEDGE.get(topic, '')}"
prompt = f"""Based on this health topic and context, answer the following question:
Question: {question}
Provide a clear, informative answer with relevant health recommendations."""
response = get_llm_response(prompt)
return response if response else "Unable to provide advice at the moment. Please try again."
def chat_with_assistant(message: str, history: list) -> str:
"""Chat with the health assistant"""
if not message:
return ""
# Format history for context
context = "\n".join([f"User: {h[0]}\nAssistant: {h[1]}" for h in history[-3:]])
prompt = f"""Previous conversation:
{context}
User's new message: {message}
Provide a helpful response about their health question or concern."""
response = get_llm_response(prompt)
return response if response else "I apologize, but I'm unable to process your request at the moment."
# Gradio Interface
with gr.Blocks(title="Virtual Health Assistant", theme=gr.themes.Soft()) as demo:
gr.Markdown(
"""
# πŸ₯ Virtual Health Assistant
Powered by AI to provide health information, track metrics, and manage medications.
βš•οΈ This is an AI assistant and not a replacement for professional medical advice.
"""
)
with gr.Tabs():
# Chat Interface Tab
with gr.Tab("πŸ’¬ Health Chat"):
chatbot = gr.Chatbot(label="Chat History")
msg = gr.Textbox(label="Type your message", placeholder="Ask about health topics...")
clear = gr.Button("Clear Chat")
def respond(message, history):
bot_message = chat_with_assistant(message, history)
history.append((message, bot_message))
return "", history
msg.submit(respond, [msg, chatbot], [msg, chatbot])
clear.click(lambda: None, None, chatbot, queue=False)
# Symptom Checker Tab
with gr.Tab("πŸ” Symptom Checker"):
with gr.Row():
with gr.Column():
symptoms_input = gr.Textbox(
label="Describe your symptoms",
placeholder="Enter your symptoms here...",
lines=3
)
symptoms_button = gr.Button("Analyze Symptoms")
symptoms_output = gr.Markdown(label="Analysis")
with gr.Column():
gr.Markdown("""
### How to use:
1. Describe your symptoms in detail
2. Include duration and severity
3. Mention any relevant medical history
⚠️ For emergencies, call emergency services immediately
""")
symptoms_button.click(
analyze_symptoms,
inputs=[symptoms_input],
outputs=[symptoms_output]
)
# Health Metrics Tab
with gr.Tab("πŸ“Š Health Metrics"):
with gr.Row():
with gr.Column():
weight_input = gr.Number(label="Weight (kg)")
steps_input = gr.Number(label="Steps")
sleep_input = gr.Number(label="Hours Slept")
metrics_button = gr.Button("Save Metrics")
metrics_output = gr.Textbox(
label="Status",
readonly=True
)
with gr.Column():
view_metrics_button = gr.Button("View Metrics")
metrics_plot = gr.Plot(label="Your Health Trends")
def save_metrics(weight, steps, sleep):
metrics_data.append({
'date': datetime.now().strftime('%Y-%m-%d'),
'weight': weight,
'steps': steps,
'sleep': sleep
})
return "βœ… Metrics saved successfully!"
def view_metrics():
if not metrics_data:
return None
df = pd.DataFrame(metrics_data)
fig = df.plot(x='date', figsize=(10, 6), title="Health Metrics Over Time")
return fig
metrics_button.click(
save_metrics,
inputs=[weight_input, steps_input, sleep_input],
outputs=[metrics_output]
)
view_metrics_button.click(
view_metrics,
outputs=[metrics_plot]
)
# Medication Manager Tab
with gr.Tab("πŸ’Š Medication Manager"):
with gr.Row():
with gr.Column():
med_name = gr.Textbox(label="Medication Name")
med_dosage = gr.Textbox(label="Dosage")
med_time = gr.Textbox(label="Time (e.g., 9:00 AM)")
med_notes = gr.Textbox(label="Notes (optional)")
med_button = gr.Button("Add Medication")
med_output = gr.Textbox(
label="Status",
readonly=True
)
with gr.Column():
view_meds_button = gr.Button("View Medications")
meds_table = gr.Dataframe(
headers=["Medication", "Dosage", "Time", "Notes"],
label="Your Medications"
)
def add_med(name, dosage, time, notes):
if not all([name, dosage, time]):
return "❌ Please fill in all required fields."
medication_data.append({
'Medication': name,
'Dosage': dosage,
'Time': time,
'Notes': notes
})
return f"βœ… Added {name} to medications!"
def view_meds():
return pd.DataFrame(medication_data)
med_button.click(
add_med,
inputs=[med_name, med_dosage, med_time, med_notes],
outputs=[med_output]
)
view_meds_button.click(
view_meds,
outputs=[meds_table]
)
gr.Markdown(
"""
### ⚠️ Important Disclaimer
This Virtual Health Assistant uses AI to provide general health information.
It is not a substitute for professional medical advice, diagnosis, or treatment.
Always seek the advice of qualified healthcare providers with questions about medical conditions.
"""
)
# Launch the app
demo.launch()