Pranith06 commited on
Commit
fb2385e
Β·
verified Β·
1 Parent(s): bd0ad7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -52
app.py CHANGED
@@ -1,54 +1,106 @@
1
- import gradio as gr
2
- from transformers import pipeline
3
-
4
- # Load the model with accelerate support
5
- generator = pipeline(
6
- "text-generation",
7
- model="ibm-granite/granite-3.3-2b-instruct",
8
- device_map="auto"
9
- )
10
-
11
- # Predict disease from symptoms
12
- def predict_disease(symptoms):
13
- prompt = f"User has the following symptoms: {symptoms}. What is the most probable disease?"
14
- try:
15
- output = generator(prompt, max_new_tokens=150, do_sample=True, temperature=0.7)[0]["generated_text"]
16
- if prompt in output:
17
- response = output.split(prompt)[-1].strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  else:
19
- response = output.strip()
20
- return response
21
- except Exception as e:
22
- return f"Error: {str(e)}"
23
-
24
- # Suggest home remedy from disease
25
- def home_remedy(disease):
26
- prompt = f"Suggest a natural home remedy for the disease: {disease}."
27
- try:
28
- output = generator(prompt, max_new_tokens=150, do_sample=True, temperature=0.7)[0]["generated_text"]
29
- if prompt in output:
30
- response = output.split(prompt)[-1].strip()
 
 
 
31
  else:
32
- response = output.strip()
33
- return response
34
- except Exception as e:
35
- return f"Error: {str(e)}"
36
-
37
- # UI with Gradio
38
- with gr.Blocks() as demo:
39
- gr.Markdown("# 🧠 HealthAI")
40
- gr.Markdown("Identify diseases from symptoms and get natural home remedies.")
41
-
42
- with gr.Tab("πŸ” Symptoms Identifier"):
43
- symptoms_input = gr.Textbox(label="Enter your symptoms", placeholder="e.g. fever, cough, sore throat")
44
- symptoms_output = gr.Textbox(label="Predicted Disease")
45
- symptoms_btn = gr.Button("Predict Disease")
46
- symptoms_btn.click(fn=predict_disease, inputs=symptoms_input, outputs=symptoms_output)
47
-
48
- with gr.Tab("🌿 Home Remedies"):
49
- disease_input = gr.Textbox(label="Enter your disease", placeholder="e.g. Cold, Headache")
50
- remedy_output = gr.Textbox(label="Suggested Remedy")
51
- remedy_btn = gr.Button("Get Remedy")
52
- remedy_btn.click(fn=home_remedy, inputs=disease_input, outputs=remedy_output)
53
-
54
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
+ import pandas as pd
4
+
5
+ # βœ… Load IBM Granite model with cache to speed up
6
+ @st.cache_resource
7
+ def load_model():
8
+ model_id = "ibm-granite/granite-3.3-2b-instruct"
9
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
10
+ model = AutoModelForCausalLM.from_pretrained(model_id)
11
+ return pipeline("text-generation", model=model, tokenizer=tokenizer)
12
+
13
+ generator = load_model()
14
+
15
+ # βœ… Set Streamlit page configuration
16
+ st.title("🩺 HealthAI – Intelligent Healthcare Assistant")
17
+
18
+ # βœ… Define tabs
19
+ tab1, tab2, tab3, tab4 = st.tabs([
20
+ "🧠 Patient Chat", "🧾 Disease Prediction",
21
+ "πŸ’Š Treatment Plans", "πŸ“Š Health Analytics"
22
+ ])
23
+
24
+ # ------------------------------
25
+ # 🧠 TAB 1: Patient Chat
26
+ # ------------------------------
27
+ with tab1:
28
+ st.subheader("Ask any health-related question")
29
+ query = st.text_area("Enter your question here")
30
+
31
+ if st.button("Get Advice", key="chat"):
32
+ if query.strip() == "":
33
+ st.warning("Please enter a question.")
34
  else:
35
+ with st.spinner("Thinking..."):
36
+ response = generator(query, max_new_tokens=200)[0]["generated_text"]
37
+ st.success("AI Response:")
38
+ st.markdown(f"markdown\n{response}\n")
39
+
40
+ # ------------------------------
41
+ # 🧾 TAB 2: Disease Prediction
42
+ # ------------------------------
43
+ with tab2:
44
+ st.subheader("Enter your symptoms (comma-separated)")
45
+ symptoms = st.text_input("E.g. persistent fever, fatigue, dry cough")
46
+
47
+ if st.button("AI Diagnose", key="predict"):
48
+ if symptoms.strip() == "":
49
+ st.warning("Please enter your symptoms.")
50
  else:
51
+ prompt = (
52
+ f"I am feeling unwell. My symptoms are: {symptoms}.\n"
53
+ "Can you please suggest what possible conditions I might have based on this?\n"
54
+ "List top 3 possible diseases with a short reason for each, and give a seriousness score out of 10."
55
+ )
56
+ with st.spinner("Analyzing symptoms..."):
57
+ result = generator(prompt, max_new_tokens=300, do_sample=True)[0]['generated_text']
58
+ st.success("AI Prediction:")
59
+ st.markdown(f"markdown\n{result}\n")
60
+
61
+ # ------------------------------
62
+ # πŸ’Š TAB 3: Treatment Plans
63
+ # ------------------------------
64
+ with tab3:
65
+ st.header("πŸ’Š Treatment Plan Generator")
66
+ condition = st.text_input("Enter the known condition (e.g., Asthma, Diabetes)")
67
+
68
+ if st.button("Get Full Treatment Plan"):
69
+ if not condition.strip():
70
+ st.warning("Please enter a condition.")
71
+ else:
72
+ with st.spinner("Generating treatment plan..."):
73
+
74
+ def get_response(prompt):
75
+ return generator(prompt, max_new_tokens=1000, temperature=0.7, do_sample=True)[0]['generated_text'].strip()
76
+
77
+ prompts = {
78
+ "1️⃣ Medications": f"What medications are usually prescribed for {condition}?",
79
+ "2️⃣ Diet": f"What diet is recommended for someone with {condition}?",
80
+ "3️⃣ Exercise": f"What type of physical activities should a person with {condition} follow?",
81
+ "4️⃣ Follow-Up & Monitoring": f"What follow-up steps and monitoring should be done for {condition}?",
82
+ "5️⃣ Precautions": f"What precautions should be taken by someone with {condition}?",
83
+ "6️⃣ Mental Health & Stress": f"How can someone with {condition} manage stress and mental health?"
84
+ }
85
+
86
+ for section, prompt in prompts.items():
87
+ st.subheader(section)
88
+ st.markdown(f"markdown\n{get_response(prompt)}\n")
89
+
90
+ # ------------------------------
91
+ # πŸ“Š TAB 4: Health Analytics
92
+ # ------------------------------
93
+ with tab4:
94
+ st.subheader("Track your health data over time")
95
+ uploaded = st.file_uploader("Upload your CSV file (with columns like 'blood_pressure', 'heart_rate')", type=["csv"])
96
+
97
+ if uploaded:
98
+ df = pd.read_csv(uploaded)
99
+ st.dataframe(df)
100
+
101
+ for col in df.select_dtypes(include=['float', 'int']).columns:
102
+ st.line_chart(df[col])
103
+ if df[col].mean() > df[col].iloc[-1]:
104
+ st.info(f"πŸ“‰ {col} is improving.")
105
+ else:
106
+ st.warning(f"πŸ“ˆ {col} is rising β€” consider medical advice.")