Spaces:
Sleeping
Sleeping
Download app2.py from FYDP-HSZ/NeuroSense_Demo: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/spaces/FYDP-HSZ/NeuroSense_Demo/resolve/main/app2.py
- Command line
-
hf download hf://spaces/FYDP-HSZ/NeuroSense_Demo/app2.py
-
curl -L -o app2.py https://huggingface.co/spaces/FYDP-HSZ/NeuroSense_Demo/resolve/main/app2.py
11 kB
| # app.py - NeuroSense: The Brain IMDb | |
| # FINAL FIXED β NAVIGATION 100% WORKING β UI PERFECT β NO GROWTH β HUGGING FACE READY | |
| import os | |
| os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0' | |
| os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' | |
| 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 json | |
| from preprocess import preprocess_eeg | |
| print("Loading CNN-Gai-GRU model...") | |
| model = load_model("cnnGru_fydp.keras", compile=False) | |
| print("Model loaded successfully!") | |
| CLASSES = ["Focused", "Funny", "Meditation", "Normal", "Sad"] | |
| COLORS = ["#00ff88", "#ffaa00", "#aa00ff", "#888888", "#3366ff"] | |
| COLOR_MAP = dict(zip(CLASSES, COLORS)) | |
| CLASS_TO_IDX = {c: i for i, c in enumerate(CLASSES)} | |
| css = """ | |
| html, body { min-height: 100vh !important; margin: 0; padding: 0; } | |
| .gradio-container { min-height: 100vh !important; margin: 0; padding: 0; overflow: auto; } | |
| body {background: linear-gradient(135deg, #0f0c29, #302b63, #24243e); font-family: 'Segoe UI', sans-serif; color: white;} | |
| .logo {position: fixed; top: 20px; left: 30px; font-size: 3rem; font-weight: bold; cursor: pointer; z-index: 1000; | |
| background: rgba(0,255,255,0.2); padding: 15px 30px; border-radius: 25px; backdrop-filter: blur(15px); | |
| box-shadow: 0 8px 32px rgba(0,255,255,0.3); transition: 0.4s;} | |
| .logo:hover {transform: scale(1.05);} | |
| .sidebar {position: fixed; left: 30px; top: 50%; transform: translateY(-50%); background: rgba(255,255,255,0.08); padding: 22px 14px; border-radius: 22px; backdrop-filter: blur(12px); box-shadow: 0 8px 40px rgba(0,0,0,0.45); z-index: 999;} | |
| .sidebar button {display: block; width: 200px; margin: 12px 0; padding: 14px; background: rgba(255,255,255,0.12); border: none; border-radius: 14px; color: white; font-size: 1.05rem; font-weight: 600; cursor: pointer; transition: 0.25s;} | |
| .sidebar button:hover {background: #00ffff; color: black; transform: translateX(6px);} | |
| .sidebar .active {background: #00ffff !important; color: black !important; font-weight: bold;} | |
| #main-content {margin-left: 270px; margin-top: 90px; padding: 28px; max-height: calc(100vh - 140px); overflow-y: auto; box-sizing: border-box;} | |
| .card {background: rgba(255,255,255,0.06); padding: 22px; border-radius: 18px; backdrop-filter: blur(10px); margin: 18px 0; box-shadow: 0 10px 30px rgba(0,0,0,0.35);} | |
| .current-emotion {font-size: 3.2rem; text-align: center; padding: 28px; border-radius: 20px; background: rgba(0,0,0,0.6); font-weight: bold; text-transform: uppercase; letter-spacing: 2px; animation: pulse 2s infinite;} | |
| @keyframes pulse {0% {box-shadow: 0 0 20px rgba(0,255,255,0.5);} 50% {box-shadow: 0 0 40px rgba(0,255,255,0.9);} 100% {box-shadow: 0 0 20px rgba(0,255,255,0.5);}} | |
| .plot-container {height: 380px !important; margin: 20px 0;} | |
| """ | |
| # FINAL JS β NAVIGATION WORKS 100% β NO BLOCKED onclick | |
| js = """ | |
| <script> | |
| const CLASSES = %s; | |
| const COLOR_MAP = %s; | |
| let predictions = []; | |
| let timestamps = []; | |
| let syncInterval = null; | |
| function goTo(page) { | |
| document.querySelectorAll('[id^="page-"]').forEach(p => p.style.display = 'none'); | |
| const target = document.getElementById('page-' + page); | |
| if (target) target.style.display = 'block'; | |
| document.querySelectorAll('.sidebar button').forEach(b => b.classList.remove('active')); | |
| document.querySelectorAll('.sidebar button').forEach(b => { | |
| if (b.dataset.page === page) b.classList.add('active'); | |
| }); | |
| if (page === 'analyze') setTimeout(startVideoSync, 600); | |
| } | |
| function startVideoSync() { | |
| const video = document.querySelector('video'); | |
| const emotion = document.getElementById('live-emotion'); | |
| if (!video || !emotion || !window.predictions) return; | |
| predictions = window.predictions; | |
| timestamps = window.timestamps; | |
| if (syncInterval) clearInterval(syncInterval); | |
| syncInterval = 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 emo = predictions[idx]; | |
| emotion.innerText = emo; | |
| emotion.style.background = COLOR_MAP[emo] || '#333'; | |
| } | |
| }, 100); | |
| } | |
| // CRITICAL: Attach onclick AFTER DOM is ready | |
| document.addEventListener('DOMContentLoaded', () => { | |
| document.querySelectorAll('.sidebar button').forEach(button => { | |
| button.onclick = () => goTo(button.dataset.page); | |
| }); | |
| goTo('landing'); // Start on landing page | |
| }); | |
| </script> | |
| """ % (json.dumps(CLASSES), json.dumps(COLOR_MAP)) | |
| with gr.Blocks(css=css, js=js, theme=gr.themes.Soft(), title="NeuroSense") as demo: | |
| page = gr.State("landing") | |
| preds_state = gr.State([]) | |
| ts_state = gr.State([]) | |
| video_path = gr.State(None) | |
| js_data = gr.State(None) | |
| 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.95); z-index:9999;"> | |
| <div style="position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); background:rgba(0,255,255,0.15); padding:50px; border-radius:30px; text-align:center; max-width:800px;"> | |
| <h1 style="font-size:4rem; background:linear-gradient(45deg,#00ffff,#ff00ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;">NeuroSense</h1> | |
| <p style="font-size:1.8rem;"><b>The Brain IMDb</b></p> | |
| <p>Predicting emotions of children (4-7) via EEG</p> | |
| <hr style="border:1px solid #00ffff;"> | |
| <h2>Team</h2> | |
| <p>β’ Member 1<br>β’ Member 2<br>β’ Member 3</p> | |
| <h2>Supervisor</h2> | |
| <p>Dr. XYZ</p> | |
| <button onclick="document.getElementById('popup').style.display='none'" style="margin-top:30px; padding:15px 40px; background:#ff3366; border:none; border-radius:20px; color:white; cursor:pointer;">Close</button> | |
| </div> | |
| </div> | |
| <div class="sidebar"> | |
| <button data-page="landing">Home</button> | |
| <button data-page="about">About</button> | |
| <button data-page="upload">Upload</button> | |
| <button data-page="analyze">Analyze</button> | |
| <button data-page="results">Results</button> | |
| </div> | |
| """) | |
| with gr.Column(elem_id="main-content"): | |
| with gr.Column(visible=True, elem_id="page-landing"): | |
| gr.HTML("<h1 style='text-align:center; font-size:6rem; margin-top:150px; 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:3rem; color:#00ffff;'>The Brain IMDb</p>") | |
| with gr.Column(visible=False, elem_id="page-about"): | |
| gr.HTML("<h1>About</h1>") | |
| with gr.Row(): | |
| for name in ["Member 1", "Member 2", "Member 3"]: | |
| with gr.Column(): gr.HTML(f"<div class='card'><h3>{name}</h3><p>FYDP 2025</p></div>") | |
| gr.HTML("<div class='card'><h2>How to Use</h2><ol><li>Upload EEG .csv</li><li>Optional: Video</li><li>Next to Live sync</li><li>Skip to Results</li></ol></div>") | |
| with gr.Column(visible=False, elem_id="page-upload"): | |
| gr.HTML("<h1>Upload Data</h1>") | |
| csv_file = gr.File(label="EEG .csv (Required)", file_types=[".csv"]) | |
| video_file = gr.Video(label="Video (Optional)") | |
| status = gr.Textbox(label="Status", value="Ready") | |
| next_btn = gr.Button("Next to Analyze", variant="primary", size="lg") | |
| with gr.Column(visible=False, elem_id="page-analyze"): | |
| gr.HTML("<h1>Live Emotion Analysis</h1>") | |
| video_player = gr.Video(visible=False, height=500, container=False) | |
| live_plot = gr.Plot(elem_classes="plot-container") | |
| emotion_box = gr.HTML("<div class='current-emotion' id='live-emotion'>Syncing...</div>") | |
| skip_btn = gr.Button("Skip to Results", variant="secondary", size="lg") | |
| with gr.Column(visible=False, elem_id="page-results"): | |
| gr.HTML("<h1>Final Results</h1>") | |
| timeline_plot = gr.Plot() | |
| rating_bars = gr.HTML() | |
| dominant = gr.HTML() | |
| def process(csv, video): | |
| if not csv: | |
| return "Error: Upload CSV", [], [], None, gr.update(visible=False), None | |
| X, ts = preprocess_eeg(csv.name) | |
| preds = model.predict(X, verbose=0) | |
| pred_labels = [CLASSES[np.argmax(p)] for p in preds] | |
| vpath = video.name if video else None | |
| data = json.dumps({"preds": pred_labels, "ts": ts.tolist()}) | |
| return "Done!", pred_labels, ts.tolist(), vpath, gr.update(visible=bool(vpath)), data | |
| next_btn.click( | |
| process, | |
| [csv_file, video_file], | |
| [status, preds_state, ts_state, video_path, video_player, js_data] | |
| ).then(lambda: gr.update(value="analyze"), outputs=page) | |
| def update_plot(preds, ts, vpath): | |
| if not preds: return None | |
| y = [CLASS_TO_IDX[p] for p in preds] | |
| fig = go.Figure() | |
| fig.add_trace(go.Scatter(x=ts, y=y, mode='lines+markers', line=dict(width=7, shape='hv', color='#00ffff'))) | |
| fig.update_layout(template="plotly_dark", height=380, margin=dict(t=20), | |
| xaxis_title="Time (ms)", yaxis=dict(tickmode='array', tickvals=list(range(5)), ticktext=CLASSES)) | |
| return fig | |
| preds_state.change(update_plot, [preds_state, ts_state, video_path], live_plot) | |
| js_data.change( | |
| None, js_data, None, | |
| js="(data) => { if(data) { const d = JSON.parse(data); window.predictions = d.preds; window.timestamps = d.ts; } }" | |
| ) | |
| def results(preds, ts): | |
| if not preds: return None, "<h3>No data</h3>", "<h3>N/A</h3>" | |
| df = pd.DataFrame({"t": ts, "emo": preds}) | |
| counts = df["emo"].value_counts(normalize=True) * 100 | |
| fig = px.bar(df, x="t", y="emo", color="emo", color_discrete_map=COLOR_MAP) | |
| fig.update_layout(template="plotly_dark", height=450, showlegend=False) | |
| bars = "<div style='text-align:center; padding:30px;'>" | |
| for c in CLASSES: | |
| p = counts.get(c, 0) | |
| bars += f"<div style='margin:18px 0;'><b>{c}</b>: <div style='display:inline-block; width:{int(p*8)}px; height:40px; background:{COLOR_MAP[c]}; border-radius:20px;'></div> <b>{p:.1f}%</b></div>" | |
| bars += "</div>" | |
| dom = counts.idxmax() | |
| dom_html = f"<h1 style='text-align:center; color:{COLOR_MAP[dom]}; text-shadow: 0 0 30px {COLOR_MAP[dom]};'>Dominant: {dom}</h1>" | |
| return fig, bars, dom_html | |
| skip_btn.click(results, [preds_state, ts_state], [timeline_plot, rating_bars, dominant])\ | |
| .then(lambda: gr.update(value="results"), outputs=page) | |
| demo.queue(max_size=10) | |
| demo.launch() |