asham007/Health_Risk_Analyzer
0
1import streamlit as st2from groq import Groq3import os4import json5import plotly.graph_objects as go6import plotly.express as px7import numpy as np8 9# -----------------------10# PAGE CONFIG11# -----------------------12st.set_page_config(page_title="AI Health Intelligence", layout="wide")13 14# -----------------------15# THEME TOGGLE16# -----------------------17if "theme" not in st.session_state:18 st.session_state.theme = "dark"19 20def toggle_theme():21 st.session_state.theme = (22 "light" if st.session_state.theme == "dark" else "dark"23 )24 25st.sidebar.button("โจ Toggle Theme", on_click=toggle_theme)26dark = st.session_state.theme == "dark"27 28bg = "#0e1117" if dark else "#f4f6f9"29text = "#ffffff" if dark else "#000000"30 31# -----------------------32# GLOBAL CSS33# -----------------------34st.markdown(f"""35<style>36.main {{ background-color:{bg}; color:{text}; transition:0.5s; }}37 38.glass-card {{39 background: rgba(255,255,255,0.08);40 padding: 25px;41 border-radius: 18px;42 backdrop-filter: blur(10px);43 box-shadow: 0 10px 25px rgba(0,0,0,0.3);44 text-align:center;45}}46 47.circular-chart {{48 display:block;49 margin:20px auto;50 max-width:220px;51}}52 53.circle-bg {{ fill:none; stroke:#eee; stroke-width:3.8; }}54.circle {{ fill:none; stroke-width:3.8; stroke-linecap:round; }}55 56.avatar-container {{57 position:fixed;58 bottom:30px;59 right:30px;60 width:240px;61 background:rgba(255,255,255,0.08);62 backdrop-filter:blur(12px);63 border-radius:20px;64 padding:20px;65 box-shadow:0 20px 40px rgba(0,0,0,0.4);66}}67 68.avatar-face {{69 width:100px;70 height:100px;71 margin:auto;72 border-radius:50%;73 position:relative;74}}75 76.eye {{77 width:15px;78 height:15px;79 background:white;80 border-radius:50%;81 position:absolute;82 top:35px;83}}84 85.eye.left {{ left:25px; }}86.eye.right {{ right:25px; }}87 88.mouth {{89 width:40px;90 height:20px;91 border-bottom:4px solid white;92 border-radius:0 0 40px 40px;93 position:absolute;94 bottom:25px;95 left:30px;96}}97 98.avatar-status {{99 text-align:center;100 margin-top:15px;101}}102</style>103""", unsafe_allow_html=True)104 105st.title("๐ฅ AI Health Intelligence Dashboard")106 107# -----------------------108# GROQ CLIENT109# -----------------------110api_key = os.environ.get("GROQ_API_KEY")111 112if not api_key:113 st.error("Missing GROQ_API_KEY (add it in HF Space โ Settings โ Secrets)")114 st.stop()115 116client = Groq(api_key=api_key)117 118# -----------------------119# PROFILE STORAGE (HF SAFE)120# -----------------------121PROFILE_FILE = "/tmp/profiles.json"122 123def load_profiles():124 if os.path.exists(PROFILE_FILE):125 with open(PROFILE_FILE, "r") as f:126 return json.load(f)127 return {}128 129def save_profiles(p):130 with open(PROFILE_FILE, "w") as f:131 json.dump(p, f)132 133profiles = load_profiles()134 135# -----------------------136# LOGIN137# -----------------------138st.sidebar.header("๐ค User")139username = st.sidebar.text_input("Username")140 141if not username:142 st.stop()143 144if username not in profiles:145 profiles[username] = {"chat_history": []}146 save_profiles(profiles)147 148mode = st.sidebar.radio(149 "Mode", ["Health Risk Analyzer", "Health Chatbot"]150)151 152# -----------------------153# RISK ENGINE154# -----------------------155def compute_components(sleep, exercise, water, screen, stress):156 157 sleep_score = max(0, (7 - sleep)) * 3158 exercise_score = (7 - exercise) * 3159 water_score = max(0, (8 - water)) * 2160 screen_score = max(0, (screen - 4)) * 2161 stress_score = {"Low":5,"Medium":15,"High":30}[stress]162 163 components = {164 "Sleep": sleep_score,165 "Exercise": exercise_score,166 "Hydration": water_score,167 "Screen Time": screen_score,168 "Stress": stress_score169 }170 171 return components, sum(components.values())172 173# -----------------------174# GAUGE175# -----------------------176def circular_gauge(score):177 178 color = "#00ff99" if score < 30 else "#ffd700" if score < 60 else "#ff4d4d"179 180 st.markdown(f"""181 <svg viewBox="0 0 36 36" class="circular-chart">182 <path class="circle-bg"183 d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831184 a 15.9155 15.9155 0 0 1 0 -31.831"/>185 <path class="circle"186 stroke="{color}"187 stroke-dasharray="{score}, 100"188 d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831189 a 15.9155 15.9155 0 0 1 0 -31.831"/>190 <text x="18" y="20.35" fill="{text}"191 font-size="0.5em" text-anchor="middle">{score}%</text>192 </svg>193 """, unsafe_allow_html=True)194 195score = 0 # prevent undefined variable196 197# ============================198# HEALTH ANALYZER199# ============================200if mode == "Health Risk Analyzer":201 202 col1, col2 = st.columns(2)203 204 with col1:205 sleep = st.slider("Sleep (hours)",0,12,7)206 exercise = st.slider("Exercise (days/week)",0,7,3)207 water = st.slider("Water (glasses/day)",0,15,6)208 209 with col2:210 screen = st.slider("Screen Time (hours/day)",0,16,6)211 stress = st.selectbox("Stress Level",["Low","Medium","High"])212 213 components, score = compute_components(214 sleep,exercise,water,screen,stress215 )216 217 st.divider()218 219 st.markdown(f"""220 <div class="glass-card">221 <h2>Overall Risk Score</h2>222 <h1>{score}</h1>223 </div>224 """, unsafe_allow_html=True)225 226 circular_gauge(score)227 228 # Radar229 fig = go.Figure()230 fig.add_trace(go.Scatterpolar(231 r=list(components.values())+[list(components.values())[0]],232 theta=list(components.keys())+[list(components.keys())[0]],233 fill='toself'234 ))235 st.plotly_chart(fig, width="stretch")236 237 # Heatmap238 heat = px.imshow(239 np.array([list(components.values())]),240 x=list(components.keys()),241 y=["Risk"],242 color_continuous_scale="RdYlGn_r"243 )244 st.plotly_chart(heat, width="stretch")245 246 # Pie247 pie = px.pie(248 values=list(components.values()),249 names=list(components.keys()),250 hole=0.4251 )252 st.plotly_chart(pie, width="stretch")253 254 # Stacked bar255 stack = go.Figure()256 for k,v in components.items():257 stack.add_trace(go.Bar(name=k,y=["Total"],x=[v],orientation='h'))258 259 stack.update_layout(barmode='stack')260 st.plotly_chart(stack, width="stretch")261 262# ============================263# CHATBOT264# ============================265elif mode == "Health Chatbot":266 267 history = profiles[username]["chat_history"]268 269 for msg in history:270 st.chat_message(msg["role"]).markdown(msg["content"])271 272 user_input = st.chat_input("Ask your AI health assistant...")273 274 if user_input:275 history.append({"role":"user","content":user_input})276 st.chat_message("user").markdown(user_input)277 278 response = client.chat.completions.create(279 model="llama3-8b-8192",280 messages=[{281 "role":"system",282 "content":"Provide safe general wellness advice only."283 }] + history[-10:],284 temperature=0.6285 )286 287 reply = response.choices[0].message.content288 289 history.append({"role":"assistant","content":reply})290 profiles[username]["chat_history"] = history291 save_profiles(profiles)292 293 st.chat_message("assistant").markdown(reply)294 295# -----------------------296# EMOTION AVATAR297# -----------------------298if score < 30:299 color="#00ff99"; emotion="๐ Calm"300 mouth="border-bottom:4px solid white;"301elif score < 60:302 color="#ffd700"; emotion="๐ Alert"303 mouth="border-bottom:4px solid white;border-radius:0;"304else:305 color="#ff4d4d"; emotion="๐จ Concerned"306 mouth="border-bottom:none;border-top:4px solid white;border-radius:40px 40px 0 0;"307 308st.markdown(f"""309<div class="avatar-container">310 <div class="avatar-face" style="background:{color};311 box-shadow:0 0 30px {color};">312 <div class="eye left"></div>313 <div class="eye right"></div>314 <div class="mouth" style="{mouth}"></div>315 </div>316 <div class="avatar-status">{emotion}</div>317</div>318""", unsafe_allow_html=True)