Spaces:
Sleeping
Sleeping
Update app.py
Browse files12123457 unmodified lines13141516161718192021212223232425261 unmodified line28293031313233343435363637383738394041414243434445454647484950515253545556575852596061555657626364656667686970607172737475767778796869808182838485868788899091929394959697719899731001011021031041051061077778108109110111112113114115116117118119120808112112212312412512612712812913013113213313486871351361371381391401411421431449014514692147148941491501519798152153154155156102157158159160161162163105106164165108109166110167168113169170115171172173118119174175176# app.py - NeuroSense ANIMATED EMOTION PLOT (FINAL FIXED)# Upload CSV β Load β PLAY β Watch emotions flow like a movie# app.py - NeuroSense ANIMATED PLOT β 100% WORKING (HUGGING FACE SPACES)# Upload CSV β Load β PLAY β WATCH EMOTIONS FLOW LIKE A MOVIE
import gradio as grimport numpy as np7 unmodified lines
# Load modelmodel = load_model("cnnGru_fydp.keras", compile=False)print("Model loaded")print("Model loaded successfully!")
CLASSES = ["Focused", "Funny", "Meditation", "Normal", "Sad"]CLASS_TO_IDX = {c: i for i, c in enumerate(CLASSES)}
def process_csv(csv_file):def create_animated_plot(csv_file): if not csv_file: return None, "Upload a CSV file", gr.update() return None, "Upload a CSV file"
try: X, timestamps = preprocess_eeg(csv_file.name)1 unmodified line pred_labels = [CLASSES[np.argmax(p)] for p in preds] y = [CLASS_TO_IDX[l] for l in pred_labels]
# Create animated figure # Create figure fig = go.Figure()
# Initial trace # Initial empty line fig.add_trace(go.Scatter( x=[timestamps[0]], y=[y[0]], x=[], y=[], mode='lines+markers', line=dict(width=6, shape='hv', color='#00ffff'), marker=dict(size=10) mode='lines+markers', line=dict(width=6, color='#00ffff', shape='hv'), marker=dict(size=10, color='#00ffff') ))
# Frames # Create frames frames = [] for i in range(len(timestamps)): for i in range(1, len(timestamps)): frame = go.Frame( data=[go.Scatter(x=timestamps[:i+1], y=y[:i+1])], data=[go.Scatter( x=timestamps[:i+1], y=y[:i+1], mode='lines+markers', line=dict(width=6, color='#00ffff', shape='hv'), marker=dict(size=10) )], name=str(i) ) frames.append(frame)
fig.frames = frames
# Layout with Play/Pause + Slider # Animation settings fig.update_layout( template="plotly_dark", height=550, title="Live Emotion Animation (Click Play)", xaxis_title="Time (ms)", height=600, title="NeuroSense: Live Emotion Animation", xaxis=dict( title="Time (ms)", range=[0, timestamps[-1] * 1.05] ), yaxis=dict( title="Emotion", tickmode='array', tickvals=list(range(5)), tickvals=[0,1,2,3,4], ticktext=CLASSES, range=[-0.5, 4.5] ), # PLAY / PAUSE BUTTONS updatemenus=[dict( type="buttons", direction="left", buttons=[ dict(label="Play", method="animate", args=[None, {"frame": {"duration": 100, "redraw": True}, "fromcurrent": True, "transition": {"duration": 0}}]), dict(label="Pause", method="animate", args=[[None], {"frame": {"duration": 0, "redraw": False}, "mode": "immediate"}]), dict( label="Play", method="animate", args=[None, { "frame": {"duration": 80, "redraw": True}, "fromcurrent": True, "transition": {"duration": 0} }] ), dict( label="Pause", method="animate", args=[[None], { "frame": {"duration": 0, "redraw": False}, "mode": "immediate" }] ), ], pad={"r": 10, "t": 10}, pad={"r": 10, "t": 87}, showactive=True, x=0.02, y=1.15 x=0.01, xanchor="left", y=1.15, yanchor="top" )], # SLIDER sliders=[dict( active=0, currentvalue={"prefix": "Time: "}, pad={"t": 50}, yanchor="top", xanchor="left", currentvalue={ "font": {"size": 16}, "prefix": "Time: ", "visible": True, "xanchor": "right" }, pad={"b": 10, "t": 50}, len=0.9, x=0.1, y=0, steps=[ dict(method="animate", args=[[str(i)], {"frame": {"duration": 0}, "mode": "immediate"}], label=f"{int(timestamps[i])}ms") for i in range(0, len(timestamps), max(1, len(timestamps)//50)) dict( method="animate", args=[[f"{i}"], { "frame": {"duration": 0, "redraw": True}, "mode": "immediate", "transition": {"duration": 0} }], label=f"{int(timestamps[i])}ms" ) for i in range(0, len(timestamps), max(1, len(timestamps)//30)) ] )] )
status = f"Loaded {len(pred_labels)} predictions | Duration: {timestamps[-1]/1000:.1f}s" return fig, status, gr.update(value=0, maximum=len(pred_labels)-1) # Force animation to work in Gradio fig = fig.to_plotly_json() fig["data"][0]["x"] = timestamps[:1] fig["data"][0]["y"] = y[:1]
status = f"LOADED: {len(pred_labels)} predictions | {timestamps[-1]/1000:.1f}s duration | PRESS PLAY"
return fig, status
except Exception as e: return None, f"ERROR: {str(e)}", gr.update() return None, f"ERROR: {str(e)}"
# Gradio UI# Gradio appwith gr.Blocks( title="NeuroSense Animated Plot", theme=gr.themes.Soft(), title="NeuroSense Animated Plot", css=""" body {background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);} .gradio-container {max-width: 1100px !important; margin: auto;} body {background: linear-gradient(135deg, #0f0c29, #302b63, #24243e); color: white;} .gradio-container {max-width: 1200px !important; margin: auto;} """) as demo: gr.Markdown("# NeuroSense β Animated Emotion Timeline") gr.Markdown("### Upload EEG CSV β Click **LOAD** β Press **Play** β Watch emotions animate!") gr.Markdown("### Upload EEG CSV β Click **LOAD** β Press **PLAY** β Watch magic")
with gr.Row(): csv_input = gr.File(label="Upload EEG CSV (.csv)", file_types=[".csv"]) load_btn = gr.Button("LOAD & START ANIMATION", variant="primary", size="lg")
with gr.Row(): csv_input = gr.File(label="Upload EEG CSV", file_types=[".csv"]) load_btn = gr.Button("LOAD & PREPARE ANIMATION", variant="primary", size="lg") plot_output = gr.Plot(label="Animated Emotion Plot")
plot = gr.Plot() status = gr.Textbox(label="Status", value="Ready") status = gr.Textbox(label="Status", value="Ready to load CSV") slider = gr.Slider(label="Manual Control", minimum=0, maximum=100, step=1)
load_btn.click( process_csv, create_animated_plot, inputs=csv_input, outputs=[plot, status, slider] outputs=[plot_output, status] )
print("LAUNCHING ANIMATED PLOT APP...")demo.queue()print("LAUNCHING 100% WORKING ANIMATED PLOT...")demo.queue(max_size=10)demo.launch()app.py+99-43