Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348# app.py — NeuroSense: EEG Emotion Classification# Author: Team NeuroSense | FYDP 2025import gradio as grimport numpy as npimport pandas as pd#import tensorflow as tfimport matplotlib.pyplot as pltimport ioimport keras # instead of tensorflow.kerasfrom keras.models import load_modelfrom keras.initializers import Orthogonalfrom preprocess import preprocess_eeg # your provided preprocessing function# ======================# 🔹 Load Model Once# ======================MODEL_PATH = "cnnGru_fydp.keras"CLASS_NAMES = ["Focused", "Funny", "Meditation", "Normal", "Sad"]# --- Register Orthogonal initializer globally ---keras.utils.get_custom_objects().update({"Orthogonal": Orthogonal})# --- Alternative fallback for strict deserialization ---try:model = load_model(MODEL_PATH, custom_objects={"Orthogonal": Orthogonal})except Exception as e:print(f"[WARN] Standard load_model failed: {e}")print("[INFO] Retrying with SafeConfig deserialization...")from keras.saving import load_model as safe_load_modelmodel = safe_load_model(MODEL_PATH, custom_objects={"Orthogonal": Orthogonal})# ======================# 🔹 Core Functions# ======================def predict_emotions_from_csv(csv_file):"""Load EEG CSV, preprocess, and predict emotion class per window."""X_windows, timestamps = preprocess_eeg(csv_file)preds = model.predict(X_windows, verbose=0)pred_labels = np.argmax(preds, axis=1)return pred_labels, timestampsdef summarize_emotions(pred_labels):"""Summarize overall emotion percentages and dominant emotion."""total = len(pred_labels)counts = {CLASS_NAMES[i]: np.sum(pred_labels == i) for i in range(len(CLASS_NAMES))}percentages = {k: round((v / total) * 100, 2) for k, v in counts.items()}dominant = sorted(percentages.items(), key=lambda x: x[1], reverse=True)[:2]return percentages, dominantdef plot_class_over_time(pred_labels, timestamps):"""Bar-like color plot of class over time."""colors = plt.cm.tab10(np.linspace(0, 1, len(CLASS_NAMES)))class_to_color = {CLASS_NAMES[i]: colors[i] for i in range(len(CLASS_NAMES))}plt.figure(figsize=(10, 2))for i, label in enumerate(pred_labels):plt.barh(0, width=1, left=i, color=class_to_color[CLASS_NAMES[label]])plt.yticks([])plt.xlabel("Time (s)")plt.title("Predicted Emotion Over Time")plt.tight_layout()buf = io.BytesIO()plt.savefig(buf, format='png')buf.seek(0)plt.close()return bufdef plot_emotion_percentages(percentages):"""Horizontal bar chart for overall emotion distribution."""fig, ax = plt.subplots(figsize=(6, 3))ax.barh(list(percentages.keys()), list(percentages.values()))ax.set_xlabel("Percentage (%)")ax.set_title("Video Rating Score")plt.tight_layout()buf = io.BytesIO()plt.savefig(buf, format='png')buf.seek(0)plt.close()return buf# ======================# 🔹 Page Functions# ======================# 1️⃣ About Pagedef about_page():with gr.Column():gr.Markdown("## 🧠 NeuroSense")gr.Markdown("""**Emotion Prediction from EEG Data (Ages 4–7)**Predict and visualize emotional responses while watching cartoons.**Team Members:**- Alice — ML Engineer- Bob — UI/UX Developer- Carol — Data Scientist- Dave — Hardware Specialist**Supervisor:**Dr. John Smith""")gr.Markdown("""### How to Use1. Upload EEG `.csv` file (required) and optional video.2. Run prediction.3. Watch synchronized emotion plot with video.4. See full emotional breakdown and rating score.""")# 2️⃣ Upload Pagedef upload_page():with gr.Blocks() as upload_ui:gr.Markdown("### 📂 EEG Data Upload")with gr.Row():eeg_file = gr.File(label="EEG CSV File", file_types=[".csv"])video_file = gr.File(label="(Optional) Reference Video", file_types=[".mp4", ".mov", ".avi"])status = gr.Markdown("") # live status updates herenext_btn = gr.Button("Next ➡️", variant="primary")# Validation before moving forwarddef validate_files(eeg, video):if eeg is None:return "⚠️ Please upload at least an EEG CSV file before continuing."return "✅ Files ready! Proceed to analysis."next_btn.click(fn=validate_files, inputs=[eeg_file, video_file], outputs=status)return upload_ui, eeg_file, video_file, next_btn# 3️⃣ Analysis Pagedef analysis_page():with gr.Column():gr.Markdown("### 🎬 Live Analysis")video_display = gr.Video(label="Video Playback (Optional)")animated_plot = gr.Plot(label="Emotion Prediction (Animated, 1s Sync)")current_class = gr.Textbox(label="Current Emotion", interactive=False)skip_btn = gr.Button("Skip to Results")# Attach click AFTER the Column blockskip_btn.click(lambda: show_page("results"), None,[page_about, page_upload, page_analysis, page_results])return video_display, animated_plot, current_class, skip_btn# 4️⃣ Results Pagedef results_page():with gr.Column():gr.Markdown("### 📊 Results Summary")full_plot = gr.Image(label="Predicted Emotion Over Time")score_plot = gr.Image(label="Emotion Distribution (Video Rating Score)")dominant_box = gr.Textbox(label="Dominant Emotion(s)", interactive=False)return full_plot, score_plot, dominant_box# ======================# 🔹 App Workflow Logic# ======================def run_analysis(eeg_file):pred_labels, timestamps = predict_emotions_from_csv(eeg_file)percentages, dominant = summarize_emotions(pred_labels)class_plot = plot_class_over_time(pred_labels, timestamps)score_plot = plot_emotion_percentages(percentages)dominant_text = ", ".join([f"{d[0]} ({d[1]}%)" for d in dominant])return class_plot, score_plot, dominant_text# validationdef validate_files(eeg, video):if eeg is None:return gr.Warning("⚠️ Please upload an EEG CSV file before proceeding.")return gr.Success("Files uploaded successfully! Click Next to continue.")# ======================# 🔹 Gradio Multi-Page App# ======================with gr.Blocks(theme=gr.themes.Soft(),css="""#navbar { position: fixed; left: 1rem; top: 50%; transform: translateY(-50%); }.navbtn { margin-bottom: 0.75rem; width: 6rem; }#neurosense-btn { position: fixed; top: 1rem; left: 1rem; font-size: 1.2rem; }.page-content { padding-left: 8rem; padding-top: 5rem; } /* Avoid nav/title overlap */""") as app:# Persistent top-left title blockwith gr.Row():neurosense_btn = gr.Button("🧠 NeuroSense", elem_id="neurosense-btn")info_modal = gr.Markdown("Team info and description will appear here.", visible=False)# Persistent left-side navigation barwith gr.Column(elem_id="navbar"):btn_launch = gr.Button("Launch", elem_classes="navbtn")btn_about = gr.Button("About", elem_classes="navbtn")btn_upload = gr.Button("Upload", elem_classes="navbtn")btn_analysis = gr.Button("Analyze", elem_classes="navbtn")btn_results = gr.Button("Results", elem_classes="navbtn")# ======================# 🔹 PAGES# ======================# 0️⃣ Launch Pagewith gr.Group(visible=True) as page_launch:with gr.Column(elem_classes="page-content", elem_id="launch-page"):gr.Markdown("""<div style='text-align:center; margin-top:20vh;'><h1 style='font-size:4rem; font-weight:800;'>🧠 NeuroSense</h1><h3 style='font-size:1.5rem; color:gray;'>The Brain IMDb</h3></div>""", elem_id="launch-text")# 1️⃣ About Pagewith gr.Group(visible=False) as page_about:with gr.Column(elem_classes="page-content"):about_page()# 2️⃣ Upload Pagewith gr.Group(visible=False) as page_upload:with gr.Column(elem_classes="page-content"):upload_ui, eeg_file, video_file, next_btn = upload_page()# 3️⃣ Analysis Pagewith gr.Group(visible=False) as page_analysis:with gr.Column(elem_classes="page-content"):gr.Markdown("### 🎬 Live Analysis")video_display = gr.Video(label="Video Playback (Optional)", visible=False)animated_plot = gr.Plot(label="Emotion Prediction (Animated, 1s Sync)")current_class = gr.Textbox(label="Current Emotion", interactive=False)skip_btn = gr.Button("Skip to Results")# 4️⃣ Results Pagewith gr.Group(visible=False) as page_results:with gr.Column(elem_classes="page-content"):full_plot, score_plot, dominant_box = results_page()# ======================# 🔹 NAVIGATION LOGIC# ======================def show_page(page_name):return [gr.update(visible=page_name == "launch"),gr.update(visible=page_name == "about"),gr.update(visible=page_name == "upload"),gr.update(visible=page_name == "analysis"),gr.update(visible=page_name == "results"),]btn_launch.click(lambda: show_page("launch"), None,[page_launch, page_about, page_upload, page_analysis, page_results])btn_about.click(lambda: show_page("about"), None,[page_launch, page_about, page_upload, page_analysis, page_results])btn_upload.click(lambda: show_page("upload"), None,[page_launch, page_about, page_upload, page_analysis, page_results])btn_analysis.click(lambda: show_page("analysis"), None,[page_launch, page_about, page_upload, page_analysis, page_results])btn_results.click(lambda: show_page("results"), None,[page_launch, page_about, page_upload, page_analysis, page_results])# ======================# 🔹 WORKFLOW LOGIC# ======================def process_and_show_analysis(eeg, video):"""Run model, then display analysis page once ready."""if eeg is None:return gr.update(value="⚠️ Please upload EEG file first."), gr.skip()pred_labels, timestamps = predict_emotions_from_csv(eeg)percentages, dominant = summarize_emotions(pred_labels)class_plot = plot_class_over_time(pred_labels, timestamps)score_plot = plot_emotion_percentages(percentages)dominant_text = ", ".join([f"{d[0]} ({d[1]}%)" for d in dominant])# Decide if video should be visiblereturn (gr.update(value="✅ Processing complete! Opening analysis..."),gr.update(visible=video is not None),class_plot,dominant_text,show_page("analysis"))# Next button → start preprocessing + open analysis page after done# Step 1: Run analysis when Next button is clickeddef run_and_show_analysis(eeg_file):pred_labels, timestamps = predict_emotions_from_csv(eeg_file)percentages, dominant = summarize_emotions(pred_labels)class_plot = plot_class_over_time(pred_labels, timestamps)score_plot = plot_emotion_percentages(percentages)dominant_text = ", ".join([f"{d[0]} ({d[1]}%)" for d in dominant])# Return the analysis page data and visibility updatesreturn class_plot, score_plot, dominant_text, \gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)with gr.Blocks(theme=gr.themes.Soft(), css="...") as app:# --- Navbar ---with gr.Column(elem_id="navbar"):btn_about = gr.Button("About")btn_upload = gr.Button("Upload")btn_analysis = gr.Button("Analyze")btn_results = gr.Button("Results")# --- Pages ---with gr.Group(visible=True) as page_launch:# launch page contentwith gr.Group(visible=False) as page_about:about_page()with gr.Group(visible=False) as page_upload:upload_ui, eeg_file, video_file, next_btn = upload_page()with gr.Group(visible=False) as page_analysis:video_display, animated_plot, current_class, skip_btn = analysis_page()with gr.Group(visible=False) as page_results:full_plot, score_plot, dominant_box = results_page()# --- Button events (must be here, inside Blocks) ---next_btn.click(fn=run_and_show_analysis,inputs=[eeg_file],outputs=[full_plot, score_plot, dominant_box,page_about, page_upload, page_analysis, page_results],show_progress="full")skip_btn.click(lambda: show_page("results"), None,[page_launch, page_about, page_upload, page_analysis, page_results])# --- Launch app ---if __name__ == "__main__":app.launch()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import gradio as grimport tensorflow as tfimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom preprocess import preprocess_eeg# Load the trained modelMODEL_PATH = "cnnGru_fydp.keras"model = tf.keras.models.load_model(MODEL_PATH)# Emotion labels in the same order as model trainingEMOTIONS = ["funny", "focused", "meditation", "normal", "sad"]def predict_eeg(file):"""Run full pipeline: preprocess EEG → predict → visualize."""try:# Run preprocessingX_windows, window_timestamps = preprocess_eeg(file)# Predict emotion probabilitiespreds = model.predict(X_windows)pred_classes = np.argmax(preds, axis=1)# Convert timestamps to secondstimes_sec = np.array(window_timestamps) / 1000.0pred_labels = [EMOTIONS[i] for i in pred_classes]# --- Plot 1: Emotion vs Time ---fig1, ax1 = plt.subplots(figsize=(8, 3))ax1.scatter(times_sec, pred_classes, c=pred_classes, cmap='viridis', s=25)ax1.set_yticks(range(len(EMOTIONS)))ax1.set_yticklabels(EMOTIONS)ax1.set_xlabel("Time (s)")ax1.set_title("Predicted Emotion over Time")fig1.tight_layout()# --- Plot 2: Class distribution ---unique, counts = np.unique(pred_labels, return_counts=True)percentages = (counts / len(pred_labels)) * 100fig2, ax2 = plt.subplots(figsize=(5, 2.5))ax2.barh(unique, percentages, color='teal')ax2.set_xlabel("Percentage (%)")ax2.set_title("Overall Emotion Distribution")fig2.tight_layout()# --- Dominant emotions ---sorted_idx = np.argsort(-percentages)dominant_classes = [(unique[i], round(percentages[i], 1)) for i in sorted_idx[:2]]dominant_text = "\n".join([f"**{c}**: {p}%" for c, p in dominant_classes])return (fig1, fig2, f"### Dominant Emotions\n{dominant_text}")except Exception as e:return None, None, f"⚠️ Error: {str(e)}"# --- Gradio UI ---title = "NeuroSense: The Brain IMDb"description = """Upload a preprocessed EEG `.csv` file corresponding to a video stimulus shown to a child.The model predicts emotion states every second and summarizes dominant emotions."""demo = gr.Interface(fn=predict_eeg,inputs=gr.File(label="Upload EEG CSV File (.csv)"),outputs=[gr.Plot(label="Emotion vs Time"),gr.Plot(label="Emotion Distribution"),gr.Markdown(label="Dominant Emotions")],title=title,description=description,theme=gr.themes.Soft(primary_hue="teal", secondary_hue="gray"))if __name__ == "__main__":demo.launch()
app.py+71-340