Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# app.py - NeuroSense LIVE SYNC TEST (HUGGING FACE SPACES READY)# Upload CSV + Video β Click β LIVE EMOTION CHANGES β YOU WINimport 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_eegCLASSES = ["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 ploty = [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 scriptjs_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_jsstatus = "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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132# app.py - NeuroSense ANIMATED PLOT TEST# Upload CSV β Click Start β Watch emotions animate over time# Play / Pause / Stop / Slider β FULL CONTROLimport gradio as grimport numpy as npimport plotly.graph_objects as gofrom tensorflow.keras.models import load_modelimport osfrom preprocess import preprocess_eegos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'# Load modelmodel = 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"}CLASS_TO_IDX = {c: i for i, c in enumerate(CLASSES)}# Global variables for animationcurrent_frame = 0timestamps = []pred_labels = []is_playing = Falsefig = Nonedef process_csv(csv_file):global timestamps, pred_labels, current_frame, figif not csv_file:return gr.update(), "Upload CSV", gr.update(value=0)X, timestamps = preprocess_eeg(csv_file.name)preds = model.predict(X, verbose=0)pred_labels = [CLASSES[np.argmax(p)] for p in preds]current_frame = 0# Create base figurey = [CLASS_TO_IDX[l] for l in pred_labels]fig = go.Figure()# Initial empty tracefig.add_trace(go.Scatter(x=[], y=[], mode='lines+markers',line=dict(width=6, shape='hv', color='#00ffff'),marker=dict(size=10)))fig.update_layout(template="plotly_dark",height=500,title="Live Emotion Timeline (Animated)",xaxis_title="Time (ms)",yaxis=dict(tickmode='array',tickvals=list(range(5)),ticktext=CLASSES,range=[-0.5, 4.5]),xaxis=dict(range=[0, max(timestamps)] if timestamps else [0, 10000]),updatemenus=[dict(type="buttons",direction="left",buttons=[dict(label="Play", method="animate", args=[None, {"frame": {"duration": 100, "redraw": True}, "fromcurrent": True}]),dict(label="Pause", method="animate", args=[[None], {"frame": {"duration": 0, "redraw": False}, "mode": "immediate"}]),dict(label="Stop", method="relayout", args=[{"xaxis.range": [0, max(timestamps)] if timestamps else [0, 10000]}])],pad={"r": 10, "t": 10},showactive=True,x=0.1, y=1.15)])# Create frames for animationframes = []for i in range(len(timestamps)):frame_data = [go.Scatter(x=timestamps[:i+1], y=y[:i+1])]frame = go.Frame(data=frame_data, name=str(i))frames.append(frame)fig.frames = frames# Add slidersliders = [dict(active=0,currentvalue={"prefix": "Time: "},pad={"t": 50},steps=[dict(method="animate", args=[[str(i)], {"frame": {"duration": 0}, "mode": "immediate"}], label=f"{timestamps[i]:.0f}ms")for i in range(0, len(timestamps), max(1, len(timestamps)//50))])]fig.update_layout(sliders=sliders)return fig, f"Loaded {len(pred_labels)} predictions", gr.update(value=0, maximum=len(pred_labels)-1)# Gradio app β CLEAN & ANIMATEDwith gr.Blocks(title="NeuroSense β Animated Plot Test",theme=gr.themes.Soft(),css="""body {background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);}.gradio-container {max-width: 1100px !important; margin: auto;}""") as demo:gr.Markdown("# NeuroSense β Animated Emotion Timeline")gr.Markdown("### Upload CSV β Click Load β Press **Play** β Watch emotions animate!")with gr.Row():csv_in = gr.File(label="EEG CSV", file_types=[".csv"])load_btn = gr.Button("LOAD & PREPARE ANIMATION", variant="primary")plot_out = gr.Plot()status = gr.Textbox(label="Status", value="Ready")slider = gr.Slider(label="Frame", minimum=0, maximum=100, step=1, value=0)load_btn.click(process_csv,inputs=csv_in,outputs=[plot_out, status, slider])print("LAUNCHING ANIMATED PLOT TEST...")demo.queue()demo.launch()
app.py+97-82