Spaces:
Sleeping
Sleeping
Update app.py
Browse files123457 unmodified lines13141516171819202122232425261 unmodified line282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120# app.py - NeuroSense ANIMATED EMOTION PLOT (FINAL FIXED)# Upload CSV β Load β PLAY β Watch emotions flow like a movieimport gradio as grimport numpy as np7 unmodified lines# Load modelmodel = load_model("cnnGru_fydp.keras", compile=False)print("Model loaded")CLASSES = ["Focused", "Funny", "Meditation", "Normal", "Sad"]CLASS_TO_IDX = {c: i for i, c in enumerate(CLASSES)}def process_csv(csv_file):if not csv_file:return None, "Upload a CSV file", gr.update()try:X, timestamps = preprocess_eeg(csv_file.name)1 unmodified linepred_labels = [CLASSES[np.argmax(p)] for p in preds]y = [CLASS_TO_IDX[l] for l in pred_labels]# Create animated figurefig = go.Figure()# Initial tracefig.add_trace(go.Scatter(x=[], y=[], mode='lines+markers',line=dict(width=6, shape='hv', color='#00ffff'),marker=dict(size=10)))# Framesframes = []for i in range(len(timestamps)):frame = go.Frame(data=[go.Scatter(x=timestamps[:i+1], y=y[:i+1])],name=str(i))frames.append(frame)fig.frames = frames# Layout with Play/Pause + Sliderfig.update_layout(template="plotly_dark",height=550,title="Live Emotion Animation (Click Play)",xaxis_title="Time (ms)",yaxis=dict(tickmode='array',tickvals=list(range(5)),ticktext=CLASSES,range=[-0.5, 4.5]),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"}]),],pad={"r": 10, "t": 10},showactive=True,x=0.02, y=1.15)],sliders=[dict(active=0,currentvalue={"prefix": "Time: "},pad={"t": 50},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))])])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)except Exception as e:return None, f"ERROR: {str(e)}", gr.update()# Gradio UIwith gr.Blocks(title="NeuroSense Animated Plot",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 EEG CSV β Click **LOAD** β Press **Play** β Watch emotions animate!")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 = gr.Plot()status = gr.Textbox(label="Status", value="Ready")slider = gr.Slider(label="Manual Control", minimum=0, maximum=100, step=1)load_btn.click(process_csv,inputs=csv_input,outputs=[plot, status, slider])print("LAUNCHING ANIMATED PLOT APP...")demo.queue()demo.launch()123457 unmodified lines13141516171819202122232425261 unmodified line282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176# app.py - NeuroSense ANIMATED PLOT β 100% WORKING (HUGGING FACE SPACES)# Upload CSV β Load β PLAY β WATCH EMOTIONS FLOW LIKE A MOVIEimport gradio as grimport numpy as np7 unmodified lines# Load modelmodel = load_model("cnnGru_fydp.keras", compile=False)print("Model loaded successfully!")CLASSES = ["Focused", "Funny", "Meditation", "Normal", "Sad"]CLASS_TO_IDX = {c: i for i, c in enumerate(CLASSES)}def create_animated_plot(csv_file):if not csv_file:return None, "Upload a CSV file"try:X, timestamps = preprocess_eeg(csv_file.name)1 unmodified linepred_labels = [CLASSES[np.argmax(p)] for p in preds]y = [CLASS_TO_IDX[l] for l in pred_labels]# Create figurefig = go.Figure()# Initial empty linefig.add_trace(go.Scatter(x=[timestamps[0]], y=[y[0]],mode='lines+markers',line=dict(width=6, color='#00ffff', shape='hv'),marker=dict(size=10, color='#00ffff')))# Create framesframes = []for i in range(1, len(timestamps)):frame = go.Frame(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# Animation settingsfig.update_layout(template="plotly_dark",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=[0,1,2,3,4],ticktext=CLASSES,range=[-0.5, 4.5]),# PLAY / PAUSE BUTTONSupdatemenus=[dict(type="buttons",direction="left",buttons=[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": 87},showactive=True,x=0.01,xanchor="left",y=1.15,yanchor="top")],# SLIDERsliders=[dict(active=0,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=[[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))])])# Force animation to work in Gradiofig = 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, statusexcept Exception as e:return None, f"ERROR: {str(e)}"# Gradio appwith gr.Blocks(theme=gr.themes.Soft(),title="NeuroSense Animated Plot",css="""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 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():plot_output = gr.Plot(label="Animated Emotion Plot")status = gr.Textbox(label="Status", value="Ready to load CSV")load_btn.click(create_animated_plot,inputs=csv_input,outputs=[plot_output, status])print("LAUNCHING 100% WORKING ANIMATED PLOT...")demo.queue(max_size=10)demo.launch()
app.py+99-43