Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# app.py - NeuroSense LIVE SYNC TEST (HUGGING FACE SPACES READY)# Upload CSV + Video β Click β LIVE EMOTION CHANGES β YOU WIN
import gradio as grimport numpy as npimport plotly.graph_objects as gofrom tensorflow.keras.models import load_modelimport jsonimport os
# Suppress warningsos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# Load model & preprocess (already in space)model = load_model("cnnGru_fydp.keras", compile=False)from preprocess import preprocess_eeg
CLASSES = ["Focused", "Funny", "Meditation", "Normal", "Sad"]COLOR_MAP = {"Focused": "#00ff88", "Funny": "#ffaa00", "Meditation": "#aa00ff", "Normal": "#888888", "Sad": "#3366ff"}CLASS_TO_IDX = {c: i for i, c in enumerate(CLASSES)}
def analyze(csv_file, video_file): if not csv_file: return None, gr.HTML("<h2>Upload EEG CSV</h2>"), "Error" X, timestamps = preprocess_eeg(csv_file.name) preds = model.predict(X, verbose=0) pred_labels = [CLASSES[np.argmax(p)] for p in preds]
# Timeline plot y = [CLASS_TO_IDX[l] for l in pred_labels] fig = go.Figure() fig.add_trace(go.Scatter(x=timestamps, y=y, mode='lines+markers', line=dict(width=6, shape='hv', color='#00ffff'))) fig.update_layout(template="plotly_dark", height=400, margin=dict(t=30), xaxis_title="Time (ms)", yaxis=dict(tickmode='array', tickvals=list(range(5)), ticktext=CLASSES))
# JS data + sync script js_data = f""" <script> window.predictions = {json.dumps(pred_labels)}; window.timestamps = {json.dumps(timestamps)}; window.COLOR_MAP = {json.dumps(COLOR_MAP)}; </script> """
video_html = f""" <video width="100%" height="500" controls autoplay ontimeupdate="syncEmotion(this)"> <source src="/file={video_file.name}" type="video/mp4"> Your browser does not support the video tag. </video> """ if video_file else ""
emotion_box = """ <div id="live-emotion" style="font-size:4rem; text-align:center; padding:30px; border-radius:30px; background:#333; color:white; font-weight:bold; margin:20px 0; text-transform:uppercase; letter-spacing:3px;"> Syncing... </div> """
sync_js = """ <script> function syncEmotion(video) { if (!window.predictions) return; const t = video.currentTime * 1000; let idx = 0; for (let i = 0; i < window.timestamps.length; i++) { if (window.timestamps[i] > t) break; idx = i; } if (idx >= window.predictions.length) idx = window.predictions.length - 1; const emo = window.predictions[idx]; const box = document.getElementById('live-emotion'); if (box) { box.innerText = emo; box.style.background = window.COLOR_MAP[emo]; } } </script> """
html_output = js_data + video_html + emotion_box + sync_js status = "SYNC ACTIVE β WATCH EMOTION CHANGE LIVE"
return fig, gr.HTML(html_output), status
# Gradio app β CLEAN & WORKINGwith gr.Blocks( title="NeuroSense β LIVE SYNC TEST", theme=gr.themes.Soft(), css=""" body {background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);} .gradio-container {max-width: 1000px !important; margin: auto !important;} """) as demo: gr.Markdown("# NeuroSense β LIVE EMOTION SYNC TEST") gr.Markdown("### If emotion box changes color + matches video time β **YOU WIN**")
with gr.Row(): csv_in = gr.File(label="EEG CSV (Required)", file_types=[".csv"]) video_in = gr.File(label="Video (mp4)", file_types=[".mp4", ".mov", ".avi"])
btn = gr.Button("START LIVE SYNC", variant="primary", size="lg")
with gr.Row(): plot_out = gr.Plot() video_out = gr.HTML() status = gr.Textbox(label="Status", value="Ready")
btn.click(analyze, [csv_in, video_in], [plot_out, video_out, status])
print("LAUNCHING LIVE SYNC TEST...")demo.queue()demo.launch()app.pyAdded+117