Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626317 unmodified lines8182838485867 unmodified lines9495969798991001011021031041051061071081091101111121131141151161171181191201211221231248 unmodified lines1331341351361371381394 unmodified lines144145146147148149import gradio as grimport numpy as npfrom tensorflow.keras.models import load_modelfrom preprocess import preprocess_eegimport timemodel = load_model("cnnGru_fydp.keras", compile=False)print("Model loaded!")CLASSES = ["Focused", "Funny", "Meditation", "Normal", "Sad"]COLOR_MAP = {"Focused": "#00ff88", "Funny": "#ffaa00", "Meditation": "#aa00ff","Normal": "#888888", "Sad": "#3366ff"}# Global stateemotions_list = []duration = 0current_idx = 0is_playing = Falsedef get_emotion_html(idx):if not emotions_list or idx >= len(emotions_list):idx = 0emo = emotions_list[idx]return f"<div style='text-align:center; padding:50px; font-size:5rem; background:{COLOR_MAP[emo]}; color:white; border-radius:30px; font-weight:bold;'>{emo}<br><small style='font-size:2rem;'>Second {idx}</small></div>"def load_csv(csv_file):global emotions_list, duration, current_idx, is_playingif not csv_file:return "Upload CSV", "Error", gr.update(), 0, "PLAY"X, timestamps_ms = preprocess_eeg(csv_file.name)preds = model.predict(X, verbose=0)pred_labels = [CLASSES[np.argmax(p)] for p in preds]timestamps_sec = [t / 1000.0 for t in timestamps_ms]duration = int(timestamps_sec[-1]) + 1emotions_list = []for sec in range(duration):idxs = [i for i, t in enumerate(timestamps_sec) if sec <= t < sec + 1]emo = pred_labels[idxs[-1]] if idxs else pred_labels[-1]emotions_list.append(emo)current_idx = 0is_playing = Falsereturn (get_emotion_html(0),f"Loaded: {duration} seconds",gr.update(minimum=0, maximum=duration-1, value=0, step=1, interactive=True),0,"PLAY")def toggle_play_pause():global is_playingis_playing = not is_playingreturn is_playingdef play_loop():global current_idx, is_playing, duration17 unmodified lines"PLAY")def seek_to(sec):global current_idx, is_playingsec = int(sec)7 unmodified lines"PLAY")# === GRADIO APP ===with gr.Blocks(theme=gr.themes.Soft(), title="NeuroSense β UNBREAKABLE") as demo:gr.Markdown("# NeuroSense β 1 Emotion Per Second")gr.Markdown("### PLAY Β· PAUSE Β· SCRUB Β· DISPLAY NEVER DISAPPEARS")with gr.Row():csv_in = gr.File(label="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</div>")status = gr.Textbox(label="Status", value="Ready")with gr.Row():play_pause_btn = gr.Button("PLAY", variant="primary", size="lg")slider = gr.Slider(0, 60, value=0, step=1, label="Second", interactive=True)idx_state = gr.State(0)load_btn.click(load_csv,inputs=csv_in,outputs=[emotion_box, status, slider, idx_state, play_pause_btn])# PLAY/PAUSE β FINAL YIELD PREVENTS BLANKplay_pause_btn.click(toggle_play_pause,outputs=idx_state8 unmodified linesoutputs=[emotion_box, idx_state, play_pause_btn])# SCRUBBING β ALWAYS SHOWS EMOTIONslider.change(seek_to,inputs=slider,4 unmodified linesoutputs=slider)print("LAUNCHING UNBREAKABLE FINAL VERSION β DISPLAY NEVER DISAPPEARS")demo.queue(max_size=20)demo.launch()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624717 unmodified lines2652662672682692702717 unmodified lines2792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264278 unmodified lines4364374384394404414424 unmodified lines447448449450451452453454455# ========================================# NeuroSense β The Brain IMDb# AI-Powered EEG Emotion Analyzer# Hugging Face Spaces + Gradio App# ========================================import gradio as grimport numpy as npfrom tensorflow.keras.models import load_modelfrom preprocess import preprocess_eeg # Your custom EEG preprocessing scriptimport timeimport matplotlib.pyplot as pltfrom 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 colorsCLASSES = ["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 runtimeemotions_list = [] # List of predicted emotion for each secondduration = 0 # Total duration of EEG recording in secondscurrent_idx = 0 # Current second being displayedis_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 emotioncounts = Counter(emo_list)total = len(emo_list)labels, values, colors = [], [], []for cls in CLASSES:count = counts.get(cls, 0)pct = count / total * 100labels.append(cls)values.append(pct)colors.append(COLOR_MAP[cls])# Create horizontal bar chartfig, 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)# Stylingax.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 topax.set_xlim(0, 100)# Add % labels on barsfor 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 plotsdef 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 Nonetimes = 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 segmentfor 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 segmentax.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 figdef 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 # fallbackreturn (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):"""Generate colored HTML box showing current emotion and second."""if not emotions_list or idx >= len(emotions_list):idx = 0emo = emotions_list[idx]return (f"<div style='text-align:center; padding:50px; font-size:5rem; background:{COLOR_MAP[emo]}; "f"color:white; border-radius:30px; font-weight:bold; box-shadow: 0 8px 20px rgba(0,0,0,0.2);'>"f"{emo}<br><small style='font-size:2rem; opacity:0.9;'>Second {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:return ("<div style='text-align:center; padding:80px; font-size:3rem; background:#333; color:#666; border-radius:30px;'>""Upload CSV</div>","Error: No file selected",gr.update(), 0, "PLAY", None,"<div style='text-align:center; color:#999;'>No data loaded.</div>",[])# === 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 = 0is_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 plottimeline_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_plotplot_fig, # β OLD: emotion_plot (now 2nd)top_text,emotions_list)def toggle_play_pause():"""Toggle between PLAY and PAUSE states."""global is_playingis_playing = not is_playingreturn is_playing # Not used directly, but triggers chaindef play_loop():global current_idx, is_playing, duration17 unmodified lines"PLAY")def seek_to(sec):global current_idx, is_playingsec = int(sec)7 unmodified lines"PLAY")# ========================================# 5. GRADIO UI LAYOUT (Blocks)# ========================================with gr.Blocks(theme=gr.themes.Soft(), title="NeuroSense β The Brain IMDb") as demo:# === HEADER: Title, Slogan, Team ===# ββββββββββββββββββββββ TITLE + SLOGAN ββββββββββββββββββββββgr.HTML("""<div style="text-align:center;margin:30px 0;padding:25px;background:linear-gradient(135deg, #1e3c72, #2a5298);border-radius:20px;color:white;box-shadow:0 8px 20px rgba(0,0,0,0.25);"><h1 style="margin:0; font-size:3.2rem; font-weight:800;">NeuroSense</h1><p style="margin:8px 0 0; font-size:1.4rem; opacity:0.9;"><em>The Brain IMDb β Unraveling emotions, one second at a time.</em></p></div>""")# ββββββββββββββββββββββ TEAM CARDS ββββββββββββββββββββββwith gr.Row():with gr.Column(scale=1, min_width=200):gr.HTML("""<div style="background:#fff; border-radius:16px; padding:20px;text-align:center; box-shadow:0 4px 12px rgba(0,0,0,0.1);border-left:6px solid #00ff88; height:100%;"><h3 style="margin:0 0 8px; color:#1e3c72;">Alice Johnson</h3><p style="margin:0; color:#555; font-weight:500;">2021-EE-001</p></div>""")with gr.Column(scale=1, min_width=200):gr.HTML("""<div style="background:#fff; border-radius:16px; padding:20px;text-align:center; box-shadow:0 4px 12px rgba(0,0,0,0.1);border-left:6px solid #ffaa00; height:100%;"><h3 style="margin:0 0 8px; color:#1e3c72;">Bob Smith</h3><p style="margin:0; color:#555; font-weight:500;">2021-EE-015</p></div>""")with gr.Column(scale=1, min_width=200):gr.HTML("""<div style="background:#fff; border-radius:16px; padding:20px;text-align:center; box-shadow:0 4px 12px rgba(0,0,0,0.1);border-left:6px solid #aa00ff; height:100%;"><h3 style="margin:0 0 8px; color:#1e3c72;">Charlie Brown</h3><p style="margin:0; color:#555; font-weight:500;">2021-EE-028</p></div>""")# ββββββββββββββββββββββ SUPERVISOR CARD ββββββββββββββββββββββgr.HTML("""<div style="text-align:center; margin:20px 0; padding:12px;background:#f8f9fa; border-radius:12px; font-size:1.1rem;color:#333; font-weight:600;"><strong>Supervisor:</strong> Dr. Danish</div>""")gr.Markdown("---")gr.HTML("<div style='height:30px;'></div>") # Space# === MAIN ANALYZER SECTION ===with gr.Row():csv_in = gr.File(label="Upload EEG CSV", file_types=[".csv"])load_btn = gr.Button("LOAD", variant="primary", size="lg")# Emotion display (big colored box)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")# Playback controlswith 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)# Hidden state to track current index and full emotion listidx_state = gr.State(0)emo_list_state = gr.State([])gr.HTML("<div style='height:50px;'></div>") # Space# ββββββββββββββββββββββ EMOTION TIMELINE PLOT ββββββββββββββββββββββgr.Markdown("---")timeline_plot = gr.Plot(label="Emotion Timeline (Per Second)")gr.HTML("<div style='height:50px;'></div>") # Space# === RESULTS SECTION ===gr.Markdown("---")gr.Markdown("### Emotion Analysis Results")emotion_plot = gr.Plot(label="Emotion Distribution")top_emotions_text = gr.HTML(value="<div style='text-align:center; color:#999;'>Load a file to see results.</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_state8 unmodified linesoutputs=[emotion_box, idx_state, play_pause_btn])# --- SLIDER: Seek to any second ---slider.change(seek_to,inputs=slider,4 unmodified linesoutputs=slider)# ========================================# 7. LAUNCH APP# ========================================print("LAUNCHING NeuroSense β FULL VERSION WITH TEAM, PLOTS & UNBREAKABLE PLAYBACK")demo.queue(max_size=20) # Handle up to 20 concurrent usersdemo.launch()
app.py+336-30