# 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 = """
""" % (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("""
NeuroSense
""")
gr.HTML("""
""")
with gr.Column(elem_id="main-content"):
# PAGE 0: Landing
with gr.Column(visible=True, elem_id="page-landing"):
gr.HTML("NeuroSense
")
gr.HTML("The Brain IMDb
")
gr.HTML("Team: A, B, C | Supervisor: Dr. XYZ
")
# PAGE 1: About
with gr.Column(visible=False, elem_id="page-about"):
gr.HTML("About NeuroSense
")
with gr.Row():
for member in ["Member 1", "Member 2", "Member 3"]:
with gr.Column(scale=1):
gr.HTML(f"{member}
Role & Contribution...
")
gr.HTML("How to Use
- Upload EEG .csv file (required)
- Optional: Upload matching video
- Click 'Next' → Watch live emotion sync
- Skip to results for full rating
")
# PAGE 2: Upload
with gr.Column(visible=False, elem_id="page-upload"):
gr.HTML("Upload Your Data
")
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("Live Emotion Analysis
")
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("Waiting for data...
")
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("Final Results
")
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, "No predictions
", "N/A
"
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 = ""
for cls in CLASSES:
pct = counts.get(cls, 0)
bar_width = int(pct * 8)
bars_html += f"""
"""
bars_html += "
"
dominant = counts.idxmax()
dominant_html = f"Dominant Emotion: {dominant}
"
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()