Spaces:
Sleeping

NeuroSense_Demo / app.py
FYDP-HSZ's picture
Update app.py
e07bc5c verified
Raw History Blame Contribute Delete
25.4 kB
# ========================================
# NeuroSense β€” The Brain IMDb
# AI-Powered EEG Emotion Analyzer
# Hugging Face Spaces + Gradio App
# ========================================
import gradio as gr
import numpy as np
from tensorflow.keras.models import load_model
from preprocess import preprocess_eeg # Your custom EEG preprocessing script
import time
import matplotlib.pyplot as plt
from collections import Counter
# ========================================
# 1. MODEL & CONFIGURATION
# ========================================
# Load the trained CNN-GRU model (no compile needed for inference)
model = load_model("cnnGru_fydp.keras", compile=False)
print("Model loaded successfully!")
# Define emotion classes and their display colors
CLASSES = ["Funny", "Focused", "Meditation", "Normal", "Sad"]
COLOR_MAP = {
"Focused": "#00ff88", # Green
"Funny": "#ffaa00", # Orange
"Meditation": "#aa00ff", # Purple
"Normal": "#888888", # Gray
"Sad": "#3366ff" # Blue
}
# ========================================
# 2. GLOBAL STATE VARIABLES
# ========================================
# These are shared across functions and persist during app runtime
emotions_list = [] # List of predicted emotion for each second
duration = 0 # Total duration of EEG recording in seconds
current_idx = 0 # Current second being displayed
is_playing = False # Playback state (PLAY or PAUSE)
# ========================================
# 3. VISUALIZATION FUNCTIONS (Bottom Section)
# ========================================
def create_emotion_bar_plot(emo_list):
"""
Generate a horizontal bar plot showing % of time spent in each emotion.
"""
if not emo_list:
return None # No data β†’ no plot
# Count occurrences of each emotion
counts = Counter(emo_list)
total = len(emo_list)
labels, values, colors = [], [], []
for cls in CLASSES:
count = counts.get(cls, 0)
pct = count / total * 100
labels.append(cls)
values.append(pct)
colors.append(COLOR_MAP[cls])
# Create horizontal bar chart
fig, ax = plt.subplots(figsize=(8, 4))
y_pos = np.arange(len(labels))
bars = ax.barh(y_pos, values, color=colors, edgecolor='black', height=0.6)
# Styling
ax.set_yticks(y_pos)
ax.set_yticklabels(labels)
ax.set_xlabel("Percentage of Total Duration (%)")
ax.set_title("Emotion Distribution Over Time", fontsize=14, fontweight='bold')
ax.invert_yaxis() # Highest on top
ax.set_xlim(0, 100)
# Add % labels on bars
for bar, val in zip(bars, values):
ax.text(val + 1, bar.get_y() + bar.get_height()/2,
f'{val:.1f}%', va='center', ha='left', fontweight='bold', color='black')
plt.tight_layout()
return fig
# Emotion plots
def create_emotion_timeline_plot(emo_list, duration):
"""
Create a step plot showing emotion changes over time (1 per second).
"""
if not emo_list or duration <= 0:
return None
times = np.arange(duration)
emotions = np.array(emo_list)
fig, ax = plt.subplots(figsize=(10, 3))
y_positions = [CLASSES.index(emo) for emo in emotions]
ax.step(times, y_positions, where='post', linewidth=3, color='black', alpha=0.2)
# Color each segment
for i in range(len(times) - 1):
ax.fill_between(
[times[i], times[i+1]], y_positions[i], y_positions[i+1],
step='post', color=COLOR_MAP[emotions[i]], alpha=0.7
)
# Final segment
ax.fill_between([times[-1], times[-1]+1], y_positions[-1], y_positions[-1],
color=COLOR_MAP[emotions[-1]], alpha=0.7)
ax.set_yticks(range(len(CLASSES)))
ax.set_yticklabels(CLASSES)
ax.set_xlabel("Time (seconds)")
ax.set_title("Emotion Timeline", fontsize=14, fontweight='bold')
ax.set_xlim(0, duration)
ax.grid(True, axis='x', alpha=0.3)
plt.tight_layout()
return fig
def get_top_emotions_text(emo_list):
"""
Return HTML text showing the two most dominant emotions with percentages.
"""
if not emo_list:
return "<div style='text-align:center; color:#999;'>No data loaded.</div>"
counts = Counter(emo_list)
total = len(emo_list)
sorted_emotions = sorted(counts.items(), key=lambda x: x[1], reverse=True)
top1 = sorted_emotions[0]
top2 = sorted_emotions[1] if len(sorted_emotions) > 1 else top1 # fallback
return (
f"<div style='text-align:center; font-size:1.4rem; padding:18px; background:#f8f9fa; "
f"border-radius:15px; border-left:6px solid {COLOR_MAP[top1[0]]};'>"
f"<strong>Top Emotions:</strong><br>"
f"<span style='color:{COLOR_MAP[top1[0]]}; font-size:1.6rem; font-weight:bold;'>"
f"{top1[0]} ({top1[1]/total*100:.1f}%)</span> β€’ "
f"<span style='color:{COLOR_MAP[top2[0]]}; font-size:1.4rem; font-weight:bold;'>"
f"{top2[0]} ({top2[1]/total*100:.1f}%)</span>"
f"</div>"
)
# ========================================
# 4. CORE DISPLAY & INTERACTION LOGIC
# ========================================
def get_emotion_html(idx):
if not emotions_list or idx >= len(emotions_list):
idx = 0
emo = emotions_list[idx]
return f"""
<div style="
text-align:center; padding:60px; font-size:5rem; font-weight:bold;
background: {COLOR_MAP[emo]}; color:white; border-radius:30px;
box-shadow: 0 0 40px {COLOR_MAP[emo]}80, 0 0 80px {COLOR_MAP[emo]}40;
font-family: 'Orbitron', sans-serif; letter-spacing: 2px;
">
{emo}<br><small style='font-size:2rem; opacity:0.9;'>SEC {idx}</small>
</div>
"""
def load_csv(csv_file):
"""
Main function: Load CSV β†’ Preprocess β†’ Predict β†’ Aggregate per second β†’ Update UI
"""
global emotions_list, duration, current_idx, is_playing
# === Input validation ===
if not csv_file:
csv_file = "52_cocom.csv" # Auto-load default from Spaces
print("No file uploaded β€” using default: 52_cocom.csv")
# === Step 1: Preprocess EEG data ===
X, timestamps_ms = preprocess_eeg(csv_file.name) # Your custom function
# === Step 2: Model prediction ===
preds = model.predict(X, verbose=0)
pred_labels = [CLASSES[np.argmax(p)] for p in preds] # Convert probabilities β†’ labels
# === Step 3: Convert timestamps to seconds ===
timestamps_sec = [t / 1000.0 for t in timestamps_ms]
duration = int(timestamps_sec[-1]) + 1 # Total seconds
# === Step 4: Aggregate predictions into 1 emotion per second ===
emotions_list = []
for sec in range(duration):
# Find all samples in [sec, sec+1)
idxs = [i for i, t in enumerate(timestamps_sec) if sec <= t < sec + 1]
# Use last sample in the second (or fallback)
emo = pred_labels[idxs[-1]] if idxs else pred_labels[-1]
emotions_list.append(emo)
# === Reset playback state ===
current_idx = 0
is_playing = False
# === Generate outputs for all UI components ===
plot_fig = create_emotion_bar_plot(emotions_list)
top_text = get_top_emotions_text(emotions_list)
# return (
# get_emotion_html(0), # emotion_box
# f"Loaded: {duration} seconds", # status
# gr.update(minimum=0, maximum=duration-1, value=0, step=1, interactive=True), # slider
# 0, # idx_state
# "PLAY", # play_pause_btn
# plot_fig, # emotion_plot
# top_text, # top_emotions_text
# emotions_list # emo_list_state (for future use)
# )
# Generate timeline plot
timeline_fig = create_emotion_timeline_plot(emotions_list, duration)
return (
get_emotion_html(0),
f"Loaded: {duration} seconds",
gr.update(minimum=0, maximum=duration-1, value=0, step=1, interactive=True),
0,
"PLAY",
timeline_fig, # ← NEW: timeline_plot
plot_fig, # ← OLD: emotion_plot (now 2nd)
top_text,
emotions_list
)
def toggle_play_pause():
"""Toggle between PLAY and PAUSE states."""
global is_playing
is_playing = not is_playing
return is_playing # Not used directly, but triggers chain
def play_loop():
global current_idx, is_playing, duration
if not emotions_list:
return
while is_playing and current_idx < duration - 1:
current_idx += 1
yield (
get_emotion_html(current_idx),
current_idx,
"PAUSE"
)
time.sleep(1)
# FINAL YIELD β€” NEVER LET DISPLAY DISAPPEAR
is_playing = False
yield (
get_emotion_html(current_idx),
current_idx,
"PLAY"
)
def seek_to(sec):
global current_idx, is_playing
sec = int(sec)
if sec >= len(emotions_list):
sec = len(emotions_list) - 1
current_idx = sec
is_playing = False
return (
get_emotion_html(sec),
sec,
"PLAY"
)
# ========================================
# 5. GRADIO UI LAYOUT (Blocks)
# ========================================
with gr.Blocks(theme=gr.themes.Soft(), title="NeuroSense β€” The Brain IMDb") as demo:
gr.HTML("""
<style>
<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@700;900&family=Exo+2:wght@300;600&display=swap" rel="stylesheet">
/* FULL-WIDTH GLASS SECTION (NO ROUNDED CORNERS, NO CARD) */
.glass-fuller {
background: rgba(10, 10, 30, 0.4) !important;
backdrop-filter: blur(20px) !important;
-webkit-backdrop-filter: blur(20px) !important;
border: 1px solid rgba(0, 255, 255, 0.2) !important;
border-radius: 0px !important;
padding: 80px 40px !important;
margin: 0 !important;
width: 100% !important;
max-width: none !important;
box-shadow: 0 0 40px rgba(0, 255, 255, 0.1) !important;
font-family: 'Exo 2', sans-serif !important;
}
.glass-full {
background: linear-gradient(-45deg, #0f0c29, #302b63, #24243e) !important;
background-size: 400% 400% !important;
animation: gradientShift 18s ease infinite !important;
backdrop-filter: blur(16px) !important;
-webkit-backdrop-filter: blur(16px) !important;
border: none !important;
border-radius: 0px !important;
padding: 0 !important; /* ← WAS 80px 40px β†’ NOW 0 */
margin: 0 !important;
width: 100% !important;
max-width: none !important;
box-shadow: none !important;
}
/* Section Title */
.section-ti {
font-size: 3rem !important;
font-weight: 800 !important;
color: #00ff88 !important;
text-align: center !important;
margin-bottom: 40px !important;
text-shadow: 0 0 20px rgba(0,255,136,0.4) !important;
letter-spacing: 2px !important;
}
.section-title {
font-family: 'Orbitron', sans-serif !important;
font-size: 3.5rem !important;
font-weight: 900 !important;
color: #00ffff !important;
text-shadow: 0 0 20px rgba(0, 255, 255, 0.6), 0 0 40px rgba(0, 255, 255, 0.3) !important;
letter-spacing: 4px !important;
text-align: center !important;
margin-bottom: 40px !important;
}
/* Animation */
@keyframes gradientShift {
0%, 100% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
}
/* Scroll Hint */
.scroll-hint {
position: absolute !important;
bottom: 40px !important;
animation: bounce 2s infinite !important;
}
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-12px); }
}
</style>
""")
# === HEADER: Title, Slogan, Team ===
# ────────────────────── TITLE + SLOGAN ──────────────────────
# === FULL-SCREEN HERO TITLE (FUTURISTIC) ===
gr.HTML("""
<div id="hero" style="
height: 100vh;
background: linear-gradient(-45deg, #0f0c29, #302b63, #24243e);
background-size: 400% 400%;
animation: gradientShift 15s ease infinite;
display: flex; flex-direction: column; justify-content: center; align-items: center;
text-align: center; color: white; position: relative; overflow: hidden;
margin: 0; padding: 0;
">
<!-- Floating Particles -->
<div class="particle" style="position: absolute; width: 4px; height: 4px; background: #00ff88; border-radius: 50%;
animation: float 6s infinite; top: 20%; left: 15%;"></div>
<div class="particle" style="width: 6px; height: 6px; background: #ffaa00; animation: float 8s infinite; top: 60%; left: 70%;"></div>
<div class="particle" style="width: 3px; height: 3px; background: #aa00ff; animation: float 10s infinite; top: 40%; left: 50%;"></div>
<!-- Title -->
<h1 style="
font-family: 'Orbitron', sans-serif;
font-size: 6rem; font-weight: 900; margin: 0;
background: linear-gradient(90deg, #00ffff, #ff00ff);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
text-shadow: 0 0 30px rgba(0,255,255,0.6), 0 0 60px rgba(255,0,255,0.4);
letter-spacing: 10px;
">
NEUROSENSE
</h1>
<!-- Slogan -->
<p style="
font-size: 1.8rem; margin: 20px 0; opacity: 0.9; max-width: 800px;
font-weight: 300; letter-spacing: 1.5px;
text-shadow: 0 0 10px rgba(255,255,255,0.3);
">
<em>The Brain IMDb – Unraveling emotions, one second at a time.</em>
</p>
<!-- Scroll Hint -->
<div style="
position: absolute; bottom: 40px; left: 50%; transform: translateX(-50%);
animation: bounce 2s infinite;
">
<svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="#00ff88" stroke-width="2">
<path d="M7 13l5 5 5-5"></path>
</svg>
</div>
</div>
<style>
@keyframes gradientShift {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
@keyframes float {
0%, 100% { transform: translateY(0) rotate(0deg); }
50% { transform: translateY(-20px) rotate(180deg); }
}
@keyframes titleGlow {
from { text-shadow: 0 0 30px rgba(0,255,136,0.5); }
to { text-shadow: 0 0 50px rgba(0,255,136,0.8), 0 0 70px rgba(255,170,0,0.6); }
}
@keyframes bounce {
0%, 100% { transform: translateX(-50%) translateY(0); }
50% { transform: translateX(-50%) translateY(-10px); }
}
</style>
""")
# ------------------ Changes here
with gr.Column(elem_id="main-content", elem_classes="scroll-container"):
# Add padding to avoid overlap
gr.HTML("<div style='height: 80px;'></div>")
# ────────────────────── TEAM CARDS ──────────────────────
gr.HTML("""
<div style="
min-height: 100vh; padding: 100px 20px;
background: linear-gradient(-45deg, #0f0c29, #302b63, #24243e);
background-size: 400% 400%; animation: gradientShift 15s ease infinite;
display: flex; flex-direction: column; justify-content: center; align-items: center;
text-align: center; color: white; position: relative; overflow: hidden;
">
<h2 style="
font-size: 3.5rem; font-weight: 800; margin: 0 0 60px;
background: linear-gradient(90deg, #00ff88, #ffaa00, #aa00ff);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
letter-spacing: 3px;
">
MEET THE TEAM
</h2>
<div style="display: flex; gap: 40px; flex-wrap: wrap; justify-content: center; max-width: 1200px;">
<!-- Muhammad Shafran -->
<div style="
background: rgba(255,255,255,0.15); backdrop-filter: blur(14px);
border: 1px solid rgba(255,255,255,0.25); border-radius: 24px;
padding: 32px; width: 280px; box-shadow: 0 12px 40px rgba(0,0,0,0.2);
border-left: 8px solid #00ff88;
">
<h3 style="margin:0 0 12px; color:#fff; font-size:1.6rem; font-weight:600;">
Muhammad Shafran
</h3>
<p style="margin:0; color:#ddd; font-size:1.1rem;">RP21-EE-416</p>
</div>
<!-- Hadia Shahid -->
<div style="
background: rgba(255,255,255,0.15); backdrop-filter: blur(14px);
border: 1px solid rgba(255,255,255,0.25); border-radius: 24px;
padding: 32px; width: 280px; box-shadow: 0 12px 40px rgba(0,0,0,0.2);
border-left: 8px solid #ffaa00;
">
<h3 style="margin:0 0 12px; color:#fff; font-size:1.6rem; font-weight:600;">
Hadia Shahid
</h3>
<p style="margin:0; color:#ddd; font-size:1.1rem;">RP21-EE-424</p>
</div>
<!-- Zulqarnain Haider -->
<div style="
background: rgba(255,255,255,0.15); backdrop-filter: blur(14px);
border: 1px solid rgba(255,255,255,0.25); border-radius: 24px;
padding: 32px; width: 280px; box-shadow: 0 12px 40px rgba(0,0,0,0.2);
border-left: 8px solid #aa00ff;
">
<h3 style="margin:0 0 12px; color:#fff; font-size:1.6rem; font-weight:600;">
Zulqarnain Haider
</h3>
<p style="margin:0; color:#ddd; font-size:1.1rem;">RP21-EE-433</p>
</div>
</div>
<!-- Supervisor -->
<div style="
margin-top: 80px; padding: 20px 40px;
background: rgba(255,255,255,0.1); backdrop-filter: blur(10px);
border-radius: 16px; border: 1px solid rgba(255,255,255,0.2);
font-size: 1.3rem; font-weight: 600; color: #ccc;
">
<strong>Supervisor:</strong> Dr. Danish
</div>
<!-- Scroll Hint -->
<div style="position: absolute; bottom: 40px; animation: bounce 2s infinite;">
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#00ff88" stroke-width="2">
<path d="M7 13l5 5 5-5"></path>
</svg>
</div>
</div>
""")
# ────────────────────── SECTION 2: PRODUCT DESCRIPTION (FULL-SCREEN) ──────────────────────
gr.HTML("""
<div style="
min-height: 100vh; padding: 120px 20px;
background: linear-gradient(-45deg, #1a1a2e, #16213e, #0f3460);
background-size: 400% 400%; animation: gradientShift 18s ease infinite;
display: flex; flex-direction: column; justify-content: center; align-items: center;
text-align: center; color: white; position: relative;
">
<h2 style="
font-size: 3.8rem; font-weight: 900; margin: 0 0 50px;
background: linear-gradient(90deg, #aa00ff, #00ff88);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
letter-spacing: 2px;
">
NEUROSENSE
</h2>
<h3 style="font-size: 2rem; margin: 0 0 40px; color: #00ff88; font-weight: 600;">
The Brain IMDb
</h3>
<div style="max-width: 900px; line-height: 1.8; font-size: 1.2rem; color: #ddd;">
<p>
NeuroSense is an AI-powered emotion recognition system that decodes human feelings from EEG brainwave data in real-time.
Using advanced deep learning models (CNN-GRU), it classifies emotions such as <strong>Focused</strong>, <strong>Funny</strong>,
<strong>Meditation</strong>, <strong>Normal</strong>, and <strong>Sad</strong> β€” second by second.
</p>
<p style="margin-top: 20px;">
Whether you're analyzing meditation sessions, detecting focus in learning, or exploring emotional responses to humor,
NeuroSense turns raw brain signals into meaningful insights β€” just like IMDb does for movies.
</p>
<p style="margin-top: 20px; font-style: italic; color: #aaa;">
"Your brain doesn't lie. We just help you listen."
</p>
</div>
<!-- Scroll Hint -->
<div style="position: absolute; bottom: 40px; animation: bounce 2s infinite;">
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#00ff88" stroke-width="2">
<path d="M7 13l5 5 5-5"></path>
</svg>
</div>
</div>
""")
# === ANALYZER SECTION ===
with gr.Column(elem_classes="glass-full"):
with gr.Row():
csv_in = gr.File(label="Upload EEG CSV", file_types=[".csv"])
load_btn = gr.Button("LOAD", variant="primary", size="lg")
emotion_box = gr.HTML(
value="<div style='text-align:center; padding:80px; font-size:3rem; background:#333; color:#666; border-radius:30px;'>Upload CSV to begin</div>"
)
status = gr.Textbox(label="Status", value="Ready", interactive=False)
with gr.Row():
play_pause_btn = gr.Button("PLAY", variant="primary", size="lg")
slider = gr.Slider(0, 60, value=0, step=1, label="Timeline (seconds)", interactive=True)
# Scroll Hint
gr.HTML("""
<div class="scroll-hint">
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#00bcd4" stroke-width="2">
<path d="M7 13l5 5 5-5"></path>
</svg>
</div>
""")
# Hidden States
idx_state = gr.State(0)
emo_list_state = gr.State([])
duration_state = gr.State(0) # for export
# -------------------RESULTS SECTION
# === RESULTS SECTION ===
with gr.Column(elem_classes="glass-full"):
# Timeline
gr.Markdown("#### Emotion Timeline (Per Second)", elem_classes="plot-title")
timeline_plot = gr.Plot()
# Bar Chart
gr.Markdown("#### Emotion Distribution", elem_classes="plot-title")
emotion_plot = gr.Plot()
# Top 2
gr.Markdown("#### Top Emotions", elem_classes="plot-title")
top_emotions_text = gr.HTML(value="<div style='text-align:center; color:#ccc; font-size:1.1rem;'>Load a file to see results.</div>")
# Scroll Hint
gr.HTML("""
<div class="scroll-hint">
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#00bcd4" stroke-width="2">
<path d="M7 13l5 5 5-5"></path>
</svg>
</div>
""")
# ========================================
# 6. EVENT BINDINGS (Interactions)
# ========================================
# --- LOAD BUTTON: Process CSV and update everything ---
load_btn.click(
fn=load_csv,
inputs=csv_in,
outputs=[
emotion_box, status, slider, idx_state, play_pause_btn, timeline_plot,
emotion_plot, top_emotions_text, emo_list_state
]
)
# --- PLAY/PAUSE BUTTON: Complex chain to avoid UI blanking ---
play_pause_btn.click(
toggle_play_pause,
outputs=idx_state
).then(
lambda: None,
outputs=None
).then(
lambda: "PAUSE" if is_playing else "PLAY",
outputs=play_pause_btn
).then(
play_loop,
outputs=[emotion_box, idx_state, play_pause_btn]
)
# --- SLIDER: Seek to any second ---
slider.change(
seek_to,
inputs=slider,
outputs=[emotion_box, idx_state, play_pause_btn]
).then(
lambda x: x,
inputs=idx_state,
outputs=slider
)
demo.load(
fn=None,
inputs=None,
outputs=None,
js="""
() => {
document.documentElement.style.scrollBehavior = 'smooth';
const style = document.createElement('style');
style.innerHTML = `
@keyframes gradientShift { 0%,100% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } }
@keyframes bounce { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-12px); } }
`;
document.head.appendChild(style);
}
"""
)
# ========================================
# 7. LAUNCH APP
# ========================================
print("LAUNCHING NeuroSense β€” FULL VERSION WITH TEAM, PLOTS & UNBREAKABLE PLAYBACK")
demo.queue(max_size=20) # Handle up to 20 concurrent users
demo.launch()