# ======================================== # 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 "
No data loaded.
" 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"
" f"Top Emotions:
" f"" f"{top1[0]} ({top1[1]/total*100:.1f}%) • " f"" f"{top2[0]} ({top2[1]/total*100:.1f}%)" f"
" ) # ======================================== # 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"""
{emo}
SEC {idx}
""" 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: return ( "
" "Upload CSV
", "Error: No file selected", gr.update(), 0, "PLAY", None, "
No data loaded.
", [] ) # === 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(""" """) # === HEADER: Title, Slogan, Team === # ────────────────────── TITLE + SLOGAN ────────────────────── # === FULL-SCREEN HERO TITLE (FUTURISTIC) === gr.HTML("""

NEUROSENSE

The Brain IMDb – Unraveling emotions, one second at a time.

""") # ------------------ Changes here with gr.Column(elem_id="main-content", elem_classes="scroll-container"): # Add padding to avoid overlap gr.HTML("
") # ────────────────────── TEAM CARDS ────────────────────── gr.HTML("""

MEET THE TEAM

Muhammad Shafran

RP21-EE-416

Hadia Shahid

RP21-EE-424

Zulqarnain Haider

RP21-EE-433

Supervisor: Dr. Danish
""") # ────────────────────── SECTION 2: PRODUCT DESCRIPTION (FULL-SCREEN) ────────────────────── gr.HTML("""

NEUROSENSE

The Brain IMDb

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 Focused, Funny, Meditation, Normal, and Sad — second by second.

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.

"Your brain doesn't lie. We just help you listen."

""") # === 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="
Upload CSV to begin
" ) 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("""
""") # 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="
Load a file to see results.
") # Scroll Hint gr.HTML("""
""") # ======================================== # 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()