File size: 6,012 Bytes
7ce4606
402ced8
9b5b810
 
 
 
 
7ce4606
f0a4b33
7ce4606
8f5b13b
9b5b810
 
76eeb8c
9b5b810
b800e1d
76eeb8c
 
 
9b5b810
76eeb8c
 
9b5b810
76eeb8c
 
 
 
9b5b810
76eeb8c
 
 
 
 
 
 
9b5b810
76eeb8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b810
76eeb8c
 
 
 
 
 
 
 
9b5b810
76eeb8c
 
 
9b5b810
402ced8
76eeb8c
9b5b810
76eeb8c
9b5b810
 
402ced8
9b5b810
 
76eeb8c
 
9b5b810
76eeb8c
 
 
 
 
 
9b5b810
76eeb8c
 
9b5b810
76eeb8c
 
9b5b810
76eeb8c
 
9b5b810
76eeb8c
 
 
402ced8
76eeb8c
9b5b810
 
 
 
 
b800e1d
9b5b810
76eeb8c
 
9b5b810
b800e1d
76eeb8c
 
 
 
 
 
 
 
 
9b5b810
 
76eeb8c
 
 
402ced8
76eeb8c
 
9b5b810
76eeb8c
 
9b5b810
 
 
 
 
 
76eeb8c
 
 
 
9b5b810
76eeb8c
 
 
 
 
 
 
 
 
 
9b5b810
76eeb8c
 
9b5b810
76eeb8c
 
 
 
 
9b5b810
76eeb8c
9b5b810
76eeb8c
 
 
 
 
 
b800e1d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import os

# βœ… Fix: Redirect .streamlit and matplotlib configs to writable /tmp
safe_dir = "/tmp/.streamlit"
os.makedirs(safe_dir, exist_ok=True)
os.environ["STREAMLIT_HOME"] = safe_dir
os.environ["STREAMLIT_CONFIG_FILE"] = os.path.join(safe_dir, "config.toml")
os.environ["STREAMLIT_DISABLE_USAGE_STATS"] = "1"
os.environ["MPLCONFIGDIR"] = "/tmp"

import streamlit as st
import pandas as pd
import numpy as np
import librosa
import matplotlib.pyplot as plt
import librosa.display
import tensorflow as tf
from datetime import datetime

# βœ… Load your trained model
@st.cache_resource
def load_model():
    model = tf.keras.models.load_model('src/Heart_ResNet.h5')
    return model

model = load_model()

# βœ… Initialize session state
if 'page' not in st.session_state:
    st.session_state.page = '🏠 Home'
if 'theme' not in st.session_state:
    st.session_state.theme = 'Light Green'
if 'history' not in st.session_state:
    st.session_state.history = []

# βœ… Custom theme styling
def apply_theme():
    if st.session_state.theme == "Light Green":
        st.markdown("""
        <style>
        body, .stApp { background-color: #e8f5e9; }
        .stApp { color: #004d40; }
        .stButton > button, .stFileUpload > div { 
            background-color: #004d40; 
            color: white; 
        }
        .stButton > button:hover, .stFileUpload > div:hover {
            background-color: #00332c;
        }
        </style>
        """, unsafe_allow_html=True)
    else:
        st.markdown("""
        <style>
        body, .stApp { background-color: #e0f7fa; }
        .stApp { color: #006064; }
        .stButton > button, .stFileUpload > div { 
            background-color: #006064; 
            color: white; 
        }
        .stButton > button:hover, .stFileUpload > div:hover {
            background-color: #004d40;
        }
        </style>
        """, unsafe_allow_html=True)

# βœ… Sidebar navigation
with st.sidebar:
    st.title("Heartbeat Analysis 🩺")
    st.session_state.page = st.radio(
        "Navigation",
        ["🏠 Home", "βš™οΈ Settings", "πŸ‘€ Profile"],
        index=["🏠 Home", "βš™οΈ Settings", "πŸ‘€ Profile"].index(st.session_state.page)
    )

# βœ… Process uploaded audio file
def process_audio(file_path):
    SAMPLE_RATE = 22050
    DURATION = 10
    input_length = int(SAMPLE_RATE * DURATION)
    
    X, sr = librosa.load(file_path, sr=SAMPLE_RATE, duration=DURATION)
    
    if len(X) < input_length:
        pad_width = input_length - len(X)
        X = np.pad(X, (0, pad_width), mode='constant')
    
    mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sr, n_mfcc=52,
                                        n_fft=512, hop_length=256).T, axis=0)
    return mfccs, X, sr

# βœ… Classify audio and store in history
def classify_audio(filepath):
    mfccs, waveform, sr = process_audio(filepath)
    features = mfccs.reshape(1, 52, 1)
    preds = model.predict(features)
    class_names = ["artifact", "murmur", "normal"]
    result = {name: float(preds[0][i]) for i, name in enumerate(class_names)}
    
    st.session_state.history.append({
        'date': datetime.now().strftime("%Y-%m-%d %H:%M"),
        'file': filepath,
        'result': result
    })
    
    return result, waveform, sr

# βœ… Home page
def home_page():
    st.title("Heartbeat Analysis")
    uploaded_file = st.file_uploader("Upload your heartbeat audio", type=["wav", "mp3"])
    
    if uploaded_file is not None:
        # Save uploaded file temporarily
        temp_path = os.path.join("/tmp", uploaded_file.name)
        with open(temp_path, "wb") as f:
            f.write(uploaded_file.getbuffer())
        
        st.audio(uploaded_file, format='audio/wav')
        
        if st.button("Analyze Now"):
            with st.spinner('Analyzing...'):
                results, waveform, sr = classify_audio(temp_path)

                st.subheader("Analysis Results")
                cols = st.columns(3)
                labels = {
                    'artifact': "🚨 Artifact",
                    'murmur': "πŸ’” Murmur",
                    'normal': "❀️ Normal"
                }
                for (label, value), col in zip(results.items(), cols):
                    with col:
                        st.metric(labels[label], f"{value*100:.2f}%")
                
                st.subheader("Heartbeat Waveform")
                fig, ax = plt.subplots(figsize=(10, 3))
                librosa.display.waveshow(waveform, sr=sr, ax=ax)
                ax.set_title("Audio Waveform")
                st.pyplot(fig)

# βœ… Settings page
def settings_page():
    st.title("Settings")
    new_theme = st.selectbox(
        "Select Theme",
        ["Light Green", "Light Blue"],
        index=0 if st.session_state.theme == "Light Green" else 1
    )
    
    if new_theme != st.session_state.theme:
        st.session_state.theme = new_theme
        st.experimental_rerun()

# βœ… Profile page
def profile_page():
    st.title("Medical Profile")
    with st.expander("Personal Information", expanded=True):
        col1, col2 = st.columns(2)
        with col1:
            st.write("**Name:** Kpetaa Patrick")
            st.write("**Age:** 35")
        with col2:
            st.write("**Blood Type:** O+")
            st.write("**Last Checkup:** 2025-06-17")
    
    st.subheader("Analysis History")
    if not st.session_state.history:
        st.write("No previous analyses found.")
    else:
        for analysis in reversed(st.session_state.history):
            with st.expander(f"Analysis from {analysis['date']}"):
                st.write(f"File: {analysis['file']}")
                for label, value in analysis['result'].items():
                    st.progress(value, text=f"{label.capitalize()}: {value*100:.2f}%")

# βœ… Run app
apply_theme()
if st.session_state.page == "🏠 Home":
    home_page()
elif st.session_state.page == "βš™οΈ Settings":
    settings_page()
elif st.session_state.page == "πŸ‘€ Profile":
    profile_page()