Spaces:
Sleeping

NeuroSense_Demo / app1.py
FYDP-HSZ's picture
Update app1.py
2526894 verified
Raw History Blame Contribute Delete
14.2 kB
# app.py - NeuroSense: The Brain IMDb
# FYDP 2025 - Perfect Deployment for Hugging Face Spaces
# TensorFlow 2.19 | Gradio 4.51+ | CNN-GRU .keras | Real-time Sync
import gradio as gr
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from tensorflow.keras.models import load_model
import os
import json
from preprocess import preprocess_eeg # Your preprocessing script
# ================================
# LOAD MODEL (TF 2.19 COMPATIBLE)
# ================================
print("Loading CNN-GRU model (cnnGru_fydp.keras) with TensorFlow 2.19...")
try:
model = load_model("cnnGru_fydp.keras", compile=False)
print("Model loaded successfully!")
except Exception as e:
print(f"Model load failed: {e}")
raise
# ================================
# CONFIGURATION
# ================================
CLASSES = ["Focused", "Funny", "Meditation", "Normal", "Sad"]
COLORS = ["#00ff88", "#ffaa00", "#aa00ff", "#888888", "#3366ff"]
CLASS_COLOR_MAP = dict(zip(CLASSES, COLORS))
CLASS_IDX_TO_NAME = {i: name for i, name in enumerate(CLASSES)}
# ================================
# CUSTOM CSS + JS
# ================================
custom_css = """
body {background: linear-gradient(135deg, #1a1a2e, #16213e); color: white; font-family: 'Segoe UI', sans-serif; margin: 0;}
.logo {
font-size: 2.8rem; font-weight: bold; cursor: pointer; padding: 1rem 2rem;
background: rgba(255,255,255,0.15); border-radius: 20px; backdrop-filter: blur(12px);
display: inline-block; transition: all 0.3s; box-shadow: 0 8px 32px rgba(0,255,255,0.2);
}
.logo:hover {transform: translateY(-5px); background: rgba(0,255,255,0.3); color: black;}
.sidebar {
position: fixed; left: 30px; top: 50%; transform: translateY(-50%);
background: rgba(255,255,255,0.1); padding: 25px 15px; border-radius: 25px;
backdrop-filter: blur(15px); box-shadow: 0 8px 32px rgba(0,0,0,0.4); z-index: 100;
}
.sidebar button {
display: block; width: 100%; margin: 12px 0; padding: 16px 20px;
background: rgba(255,255,255,0.15); border: none; border-radius: 15px;
color: white; font-size: 1.1rem; font-weight: 600; cursor: pointer;
transition: all 0.3s; text-align: left;
}
.sidebar button:hover {background: #00ffff; color: black; transform: translateX(8px);}
.sidebar .active {background: #00ffff !important; color: black !important; font-weight: bold;}
#main-content {margin-left: 240px; margin-top: 90px; padding: 2rem; min-height: 100vh;}
.card {
background: rgba(255,255,255,0.12); padding: 25px; border-radius: 20px;
backdrop-filter: blur(12px); margin: 20px 0; box-shadow: 0 8px 32px rgba(0,0,0,0.3);
}
.current-emotion {
font-size: 4rem; text-align: center; padding: 30px; border-radius: 25px;
background: rgba(0,0,0,0.6); font-weight: bold; margin: 20px 0;
animation: glow 2s infinite alternate; text-transform: uppercase;
}
@keyframes glow {
from {box-shadow: 0 0 20px rgba(0,255,255,0.5);}
to {box-shadow: 0 0 40px rgba(0,255,255,0.9);}
}
"""
custom_js = """
<script>
let currentPage = "landing";
let predictions = [];
let timestamps = [];
let intervalId = null;
const CLASS_COLOR_MAP = %s;
function updateNav(active) {
currentPage = active;
document.querySelectorAll('.sidebar button').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.sidebar button').forEach(b => {
if (b.innerText.toLowerCase().includes(active)) b.classList.add('active');
});
}
function goTo(page) {
updateNav(page);
document.querySelectorAll('[id^="page-"]').forEach(p => p.style.display = 'none');
document.getElementById('page-' + page).style.display = 'block';
if (page === 'analyze' && predictions.length > 0) {
setTimeout(startSync, 500);
}
}
function startSync() {
const video = document.querySelector('video');
const plot = document.getElementById('live-plot').querySelector('div');
const emotion = document.getElementById('current-emotion-text');
if (!video || !emotion) return;
if (intervalId) clearInterval(intervalId);
intervalId = setInterval(() => {
if (video.paused || video.ended) return;
const t = video.currentTime * 1000;
let idx = 0;
for (let i = 0; i < timestamps.length; i++) {
if (timestamps[i] > t) break;
idx = i;
}
if (idx < predictions.length) {
const cls = predictions[idx];
emotion.innerText = cls;
emotion.style.background = CLASS_COLOR_MAP[cls] || "#888";
emotion.style.color = "white";
}
}, 100);
}
function stopSync() {
if (intervalId) clearInterval(intervalId);
}
function updatePlot() {
if (window.plotlyPlot && predictions.length > 0) {
const x = timestamps.slice(0, predictions.length);
const y = predictions.map(p => CLASSES.indexOf(p));
Plotly.react('live-plot', [{
x: x, y: y, mode: 'lines+markers', name: 'Emotion',
line: {shape: 'hv', width: 6}, marker: {size: 10}
}], {
height: 320, template: "plotly_dark",
xaxis: {title: "Time (ms)"},
yaxis: {tickmode: 'array', tickvals: [0,1,2,3,4], ticktext: %s}
});
}
}
</script>
""" % (json.dumps(CLASS_COLOR_MAP), json.dumps(CLASSES))
# ================================
# GRADIO APP
# ================================
with gr.Blocks(css=custom_css, js=custom_js, theme=gr.themes.Soft(), title="NeuroSense") as demo:
# States
page_state = gr.State("landing")
predictions_state = gr.State([])
timestamps_state = gr.State([])
video_file_state = gr.State(None)
duration_state = gr.State(0)
# Header + Popup + Sidebar
gr.HTML("""
<div class="logo" onclick="document.getElementById('popup').style.display='block'">NeuroSense</div>
<div id="popup" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.9); z-index:999; backdrop-filter:blur(10px);">
<div style="position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); background:rgba(255,255,255,0.2); padding:40px; border-radius:25px; max-width:700px; text-align:center;">
<h1 style="color:#00ffff;">NeuroSense</h1>
<p style="font-size:1.4rem;"><b>The Brain IMDb</b><br>Predicting emotions of kids (4-7) watching cartoons via EEG</p>
<hr style="border:1px solid #00ffff;">
<h3>Team:</h3>
<p style="font-size:1.2rem;">• Member 1<br>• Member 2<br>• Member 3</p>
<h3>Supervisor:</h3>
<p style="font-size:1.2rem;">Dr. XYZ</p>
<button onclick="document.getElementById('popup').style.display='none'" style="margin-top:20px; padding:15px 30px; background:#ff3366; border:none; border-radius:15px; color:white; font-size:1.1rem; cursor:pointer;">Close</button>
</div>
</div>
""")
gr.HTML("""
<div class="sidebar">
<button onclick="goTo('landing')">Home</button>
<button onclick="goTo('about')">About</button>
<button onclick="goTo('upload')">Upload</button>
<button onclick="goTo('analyze')">Analyze</button>
<button onclick="goTo('results')">Results</button>
</div>
""")
with gr.Column(elem_id="main-content"):
# PAGE 0: Landing
with gr.Column(visible=True, elem_id="page-landing"):
gr.HTML("<h1 style='text-align:center; font-size:5rem; margin-top:120px; background:linear-gradient(45deg,#00ffff,#ff00ff); -webkit-background-clip:text; -webkit-text-fill-color:transparent;'>NeuroSense</h1>")
gr.HTML("<p style='text-align:center; font-size:2.5rem; color:#00ffff; margin:20px;'>The Brain IMDb</p>")
gr.HTML("<p style='text-align:center; font-size:1.3rem; margin-top:100px; color:#aaa;'>Team: A, B, C &nbsp;&nbsp;|&nbsp;&nbsp; Supervisor: Dr. XYZ</p>")
# PAGE 1: About
with gr.Column(visible=False, elem_id="page-about"):
gr.HTML("<h1>About NeuroSense</h1>")
with gr.Row():
for member in ["Member 1", "Member 2", "Member 3"]:
with gr.Column(scale=1):
gr.HTML(f"<div class='card'><h3>{member}</h3><p>Role & Contribution...</p></div>")
gr.HTML("<div class='card'><h2>How to Use</h2><ol style='font-size:1.1rem;'><li>Upload EEG .csv file (required)</li><li>Optional: Upload matching video</li><li>Click 'Next' → Watch live emotion sync</li><li>Skip to results for full rating</li></ol></div>")
# PAGE 2: Upload
with gr.Column(visible=False, elem_id="page-upload"):
gr.HTML("<h1>Upload Your Data</h1>")
csv_input = gr.File(label="EEG Data (.csv) - Required", file_types=[".csv"])
video_input = gr.Video(label="Video (Optional - for sync)")
status_box = gr.Textbox(label="Status", value="Upload files and click Next", interactive=False)
next_btn = gr.Button("Next →", variant="primary", size="lg")
# PAGE 3: Analyze (Live Sync)
with gr.Column(visible=False, elem_id="page-analyze"):
gr.HTML("<h1>Live Emotion Analysis</h1>")
video_player = gr.Video(visible=False, width=800, height=450)
live_plot = gr.Plot(label="Live Emotion Timeline", elem_id="live-plot")
emotion_display = gr.HTML("<div class='current-emotion' id='current-emotion-text'>Waiting for data...</div>")
skip_btn = gr.Button("Skip to Results →", variant="secondary", size="lg")
# PAGE 4: Results
with gr.Column(visible=False, elem_id="page-results"):
gr.HTML("<h1>Final Results</h1>")
timeline_plot = gr.Plot()
rating_bars = gr.HTML()
dominant_emotion = gr.HTML()
# ================================
# BACKEND LOGIC
# ================================
def run_full_pipeline(csv_file, video_file):
if not csv_file:
return "Error: Please upload EEG .csv file", None, None, None, None, gr.update(visible=False)
status = "Preprocessing EEG data..."
yield status, None, None, None, None, gr.update(visible=False)
try:
X_windows, window_timestamps = preprocess_eeg(csv_file.name)
status += "\nRunning CNN-GRU model..."
yield status, None, None, None, None, gr.update(visible=False)
preds_proba = model.predict(X_windows, verbose=0)
pred_indices = np.argmax(preds_proba, axis=1)
pred_classes = [CLASS_IDX_TO_NAME[idx] for idx in pred_indices]
duration = (window_timestamps[-1] - window_timestamps[0]) / 1000 if len(window_timestamps) > 1 else 0
video_path = video_file.name if video_file else None
return (
"Analysis Complete! Click 'Analyze' tab →",
pred_classes,
window_timestamps.tolist(),
video_path,
duration,
gr.update(visible=video_path is not None)
)
except Exception as e:
return f"Error: {str(e)}", None, None, None, None, gr.update(visible=False)
next_btn.click(
fn=run_full_pipeline,
inputs=[csv_input, video_input],
outputs=[status_box, predictions_state, timestamps_state, video_file_state, duration_state, video_player]
).then(
fn=lambda: gr.update(value="analyze"),
outputs=page_state
)
def update_analyze_page(preds, ts, video_path):
if not preds:
return gr.update(), gr.update(), gr.update(visible=False)
fig = go.Figure()
fig.add_trace(go.Scatter(
x=ts[:1], y=[CLASSES.indexOf(preds[0]) if preds else 0],
mode='lines+markers', line=dict(width=6, shape='hv'),
marker=dict(size=12)
))
fig.update_layout(
height=340, template="plotly_dark",
xaxis_title="Time (ms)", yaxis=dict(
tickmode='array', tickvals=list(range(5)), ticktext=CLASSES
),
margin=dict(l=40, r=40, t=40, b=40)
)
return fig, "Starting sync...", gr.update(visible=video_path is not None)
predictions_state.change(
fn=update_analyze_page,
inputs=[predictions_state, timestamps_state, video_file_state],
outputs=[live_plot, emotion_display, video_player]
)
def generate_results(preds, ts):
if not preds:
return None, "<h3>No predictions</h3>", "<h3>N/A</h3>"
df = pd.DataFrame({"timestamp": ts, "emotion": preds})
counts = df["emotion"].value_counts(normalize=True) * 100
# Timeline
fig = px.bar(df, x="timestamp", y="emotion", color="emotion",
color_discrete_map=CLASS_COLOR_MAP, height=400)
fig.update_layout(template="plotly_dark", showlegend=False, xaxis_title="Time (ms)")
# Rating bars
bars_html = "<div style='margin:40px 0; font-size:1.3rem;'>"
for cls in CLASSES:
pct = counts.get(cls, 0)
bar_width = int(pct * 8)
bars_html += f"""
<div style='margin:15px 0;'>
<b>{cls}</b>:
<div style='display:inline-block; width:{bar_width}px; height:35px; background:{CLASS_COLOR_MAP[cls]}; border-radius:15px; vertical-align:middle;'></div>
<b> {pct:.1f}%</b>
</div>"""
bars_html += "</div>"
dominant = counts.idxmax()
dominant_html = f"<h1 style='text-align:center; color:{CLASS_COLOR_MAP[dominant]}; text-shadow: 0 0 20px {CLASS_COLOR_MAP[dominant]};'>Dominant Emotion: {dominant}</h1>"
return fig, bars_html, dominant_html
skip_btn.click(
fn=generate_results,
inputs=[predictions_state, timestamps_state],
outputs=[timeline_plot, rating_bars, dominant_emotion]
).then(
fn=lambda: gr.update(value="results"),
outputs=page_state
)
demo.load(lambda: gr.update(value="landing"), outputs=page_state)
demo.queue(max_size=10)
demo.launch()