Spaces:
Sleeping

File size: 25,651 Bytes
b048301
 
 
 
 
 
4ee990c
 
 
b048301
4ee990c
b048301
 
 
 
 
 
4ee990c
b048301
4ee990c
b048301
4ee990c
b048301
 
4ee990c
b048301
 
 
 
 
4ee990c
 
b048301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ee990c
 
 
 
 
a5fc692
 
 
 
 
 
 
 
 
 
4ee990c
 
b048301
 
 
4ee990c
b048301
 
4ee990c
b048301
 
 
 
 
 
 
 
 
 
 
4ee990c
b048301
4ee990c
b048301
4ee990c
b048301
4ee990c
b048301
4ee990c
b048301
4ee990c
 
b048301
4ee990c
b048301
4ee990c
 
 
b048301
4ee990c
 
 
b048301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ee990c
 
 
 
 
b048301
 
 
 
 
4ee990c
 
 
b048301
4ee990c
 
b048301
 
4ee990c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b048301
4ee990c
 
 
 
 
 
 
 
 
 
 
 
 
 
b048301
 
 
 
 
 
a5fc692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b048301
 
a5fc692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b048301
a5fc692
 
b048301
a5fc692
 
 
b048301
a5fc692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b048301
a5fc692
b048301
a5fc692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b048301
a5fc692
 
 
 
b048301
a5fc692
 
 
 
b048301
a5fc692
 
b048301
a5fc692
 
 
 
b048301
a5fc692
 
 
 
b048301
a5fc692
 
b048301
a5fc692
 
 
 
b048301
a5fc692
 
 
 
b048301
a5fc692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b048301
a5fc692
 
b048301
a5fc692
 
 
 
 
b048301
a5fc692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b048301
a5fc692
b048301
a5fc692
 
b048301
4ee990c
a5fc692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ee990c
a5fc692
4ee990c
b048301
a5fc692
b048301
 
a5fc692
b048301
a5fc692
b048301
 
a5fc692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b048301
 
 
 
4ee990c
b048301
4ee990c
b048301
4ee990c
b048301
 
 
 
4ee990c
 
b048301
4ee990c
 
 
 
 
 
 
 
 
 
 
 
 
 
b048301
4ee990c
 
 
 
 
 
 
 
 
 
a5fc692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b048301
 
 
 
 
4ee990c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# ========================================
# NeuroSense β€” The Brain IMDb
# AI-Powered EEG Emotion Analyzer
# Hugging Face Spaces + Gradio App
# ========================================

import gradio as gr
import numpy as np
from tensorflow.keras.models import load_model
from preprocess import preprocess_eeg  # Your custom EEG preprocessing script
import time
import matplotlib.pyplot as plt
from collections import Counter

# ========================================
# 1. MODEL & CONFIGURATION
# ========================================

# Load the trained CNN-GRU model (no compile needed for inference)
model = load_model("cnnGru_fydp.keras", compile=False)
print("Model loaded successfully!")

# Define emotion classes and their display colors
CLASSES = ["Funny", "Focused", "Meditation", "Normal", "Sad"]
COLOR_MAP = {
    "Focused": "#00ff88",      # Green
    "Funny": "#ffaa00",        # Orange
    "Meditation": "#aa00ff",   # Purple
    "Normal": "#888888",       # Gray
    "Sad": "#3366ff"           # Blue
}

# ========================================
# 2. GLOBAL STATE VARIABLES
# ========================================
# These are shared across functions and persist during app runtime
emotions_list = []      # List of predicted emotion for each second
duration = 0            # Total duration of EEG recording in seconds
current_idx = 0         # Current second being displayed
is_playing = False      # Playback state (PLAY or PAUSE)


# ========================================
# 3. VISUALIZATION FUNCTIONS (Bottom Section)
# ========================================

def create_emotion_bar_plot(emo_list):
    """
    Generate a horizontal bar plot showing % of time spent in each emotion.
    """
    if not emo_list:
        return None  # No data β†’ no plot

    # Count occurrences of each emotion
    counts = Counter(emo_list)
    total = len(emo_list)

    labels, values, colors = [], [], []
    for cls in CLASSES:
        count = counts.get(cls, 0)
        pct = count / total * 100
        labels.append(cls)
        values.append(pct)
        colors.append(COLOR_MAP[cls])

    # Create horizontal bar chart
    fig, ax = plt.subplots(figsize=(8, 4))
    y_pos = np.arange(len(labels))
    bars = ax.barh(y_pos, values, color=colors, edgecolor='black', height=0.6)

    # Styling
    ax.set_yticks(y_pos)
    ax.set_yticklabels(labels)
    ax.set_xlabel("Percentage of Total Duration (%)")
    ax.set_title("Emotion Distribution Over Time", fontsize=14, fontweight='bold')
    ax.invert_yaxis()  # Highest on top
    ax.set_xlim(0, 100)

    # Add % labels on bars
    for bar, val in zip(bars, values):
        ax.text(val + 1, bar.get_y() + bar.get_height()/2,
                f'{val:.1f}%', va='center', ha='left', fontweight='bold', color='black')

    plt.tight_layout()
    return fig


# Emotion plots
def create_emotion_timeline_plot(emo_list, duration):
    """
    Create a step plot showing emotion changes over time (1 per second).
    """
    if not emo_list or duration <= 0:
        return None

    times = np.arange(duration)
    emotions = np.array(emo_list)

    fig, ax = plt.subplots(figsize=(10, 3))
    y_positions = [CLASSES.index(emo) for emo in emotions]
    ax.step(times, y_positions, where='post', linewidth=3, color='black', alpha=0.2)
    
    # Color each segment
    for i in range(len(times) - 1):
        ax.fill_between(
            [times[i], times[i+1]], y_positions[i], y_positions[i+1],
            step='post', color=COLOR_MAP[emotions[i]], alpha=0.7
        )
    # Final segment
    ax.fill_between([times[-1], times[-1]+1], y_positions[-1], y_positions[-1],
                    color=COLOR_MAP[emotions[-1]], alpha=0.7)

    ax.set_yticks(range(len(CLASSES)))
    ax.set_yticklabels(CLASSES)
    ax.set_xlabel("Time (seconds)")
    ax.set_title("Emotion Timeline", fontsize=14, fontweight='bold')
    ax.set_xlim(0, duration)
    ax.grid(True, axis='x', alpha=0.3)
    plt.tight_layout()
    return fig



def get_top_emotions_text(emo_list):
    """
    Return HTML text showing the two most dominant emotions with percentages.
    """
    if not emo_list:
        return "<div style='text-align:center; color:#999;'>No data loaded.</div>"

    counts = Counter(emo_list)
    total = len(emo_list)
    sorted_emotions = sorted(counts.items(), key=lambda x: x[1], reverse=True)

    top1 = sorted_emotions[0]
    top2 = sorted_emotions[1] if len(sorted_emotions) > 1 else top1  # fallback

    return (
        f"<div style='text-align:center; font-size:1.4rem; padding:18px; background:#f8f9fa; "
        f"border-radius:15px; border-left:6px solid {COLOR_MAP[top1[0]]};'>"
        f"<strong>Top Emotions:</strong><br>"
        f"<span style='color:{COLOR_MAP[top1[0]]}; font-size:1.6rem; font-weight:bold;'>"
        f"{top1[0]} ({top1[1]/total*100:.1f}%)</span>  β€’  "
        f"<span style='color:{COLOR_MAP[top2[0]]}; font-size:1.4rem; font-weight:bold;'>"
        f"{top2[0]} ({top2[1]/total*100:.1f}%)</span>"
        f"</div>"
    )


# ========================================
# 4. CORE DISPLAY & INTERACTION LOGIC
# ========================================

def get_emotion_html(idx):
    if not emotions_list or idx >= len(emotions_list):
        idx = 0
    emo = emotions_list[idx]
    return f"""
    <div style="
        text-align:center; padding:60px; font-size:5rem; font-weight:bold;
        background: {COLOR_MAP[emo]}; color:white; border-radius:30px;
        box-shadow: 0 0 40px {COLOR_MAP[emo]}80, 0 0 80px {COLOR_MAP[emo]}40;
        font-family: 'Orbitron', sans-serif; letter-spacing: 2px;
    ">
        {emo}<br><small style='font-size:2rem; opacity:0.9;'>SEC {idx}</small>
    </div>
    """

def load_csv(csv_file):
    """
    Main function: Load CSV β†’ Preprocess β†’ Predict β†’ Aggregate per second β†’ Update UI
    """
    global emotions_list, duration, current_idx, is_playing

    # === Input validation ===
    if not csv_file:
        return (
            "<div style='text-align:center; padding:80px; font-size:3rem; background:#333; color:#666; border-radius:30px;'>"
            "Upload CSV</div>",
            "Error: No file selected", 
            gr.update(), 0, "PLAY", None, 
            "<div style='text-align:center; color:#999;'>No data loaded.</div>", 
            []
        )

    # === Step 1: Preprocess EEG data ===
    X, timestamps_ms = preprocess_eeg(csv_file.name)  # Your custom function

    # === Step 2: Model prediction ===
    preds = model.predict(X, verbose=0)
    pred_labels = [CLASSES[np.argmax(p)] for p in preds]  # Convert probabilities β†’ labels

    # === Step 3: Convert timestamps to seconds ===
    timestamps_sec = [t / 1000.0 for t in timestamps_ms]
    duration = int(timestamps_sec[-1]) + 1  # Total seconds

    # === Step 4: Aggregate predictions into 1 emotion per second ===
    emotions_list = []
    for sec in range(duration):
        # Find all samples in [sec, sec+1)
        idxs = [i for i, t in enumerate(timestamps_sec) if sec <= t < sec + 1]
        # Use last sample in the second (or fallback)
        emo = pred_labels[idxs[-1]] if idxs else pred_labels[-1]
        emotions_list.append(emo)

    # === Reset playback state ===
    current_idx = 0
    is_playing = False

    # === Generate outputs for all UI components ===
    plot_fig = create_emotion_bar_plot(emotions_list)
    top_text = get_top_emotions_text(emotions_list)

#    return (
#        get_emotion_html(0),                                    # emotion_box
 #       f"Loaded: {duration} seconds",                         # status
 #       gr.update(minimum=0, maximum=duration-1, value=0, step=1, interactive=True),  # slider
 #       0,                                                     # idx_state
 #       "PLAY",                                                # play_pause_btn
 #       plot_fig,                                              # emotion_plot
 #       top_text,                                              # top_emotions_text
 #       emotions_list                                          # emo_list_state (for future use)
 #   )

    # Generate timeline plot
    timeline_fig = create_emotion_timeline_plot(emotions_list, duration)

    return (
        get_emotion_html(0),
        f"Loaded: {duration} seconds",
        gr.update(minimum=0, maximum=duration-1, value=0, step=1, interactive=True),
        0,
        "PLAY",
        timeline_fig,        # ← NEW: timeline_plot
        plot_fig,            # ← OLD: emotion_plot (now 2nd)
        top_text,
        emotions_list
    )

def toggle_play_pause():
    """Toggle between PLAY and PAUSE states."""
    global is_playing
    is_playing = not is_playing
    return is_playing  # Not used directly, but triggers chain


def play_loop():
    global current_idx, is_playing, duration
    if not emotions_list:
        return

    while is_playing and current_idx < duration - 1:
        current_idx += 1
        yield (
            get_emotion_html(current_idx),
            current_idx,
            "PAUSE"
        )
        time.sleep(1)

    # FINAL YIELD β€” NEVER LET DISPLAY DISAPPEAR
    is_playing = False
    yield (
        get_emotion_html(current_idx),
        current_idx,
        "PLAY"
    )


def seek_to(sec):
    global current_idx, is_playing
    sec = int(sec)
    if sec >= len(emotions_list):
        sec = len(emotions_list) - 1
    current_idx = sec
    is_playing = False
    return (
        get_emotion_html(sec),
        sec,
        "PLAY"
    )


# ========================================
# 5. GRADIO UI LAYOUT (Blocks)
# ========================================

with gr.Blocks(theme=gr.themes.Soft(), title="NeuroSense β€” The Brain IMDb") as demo:

    gr.HTML("""
<style>

<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@700;900&family=Exo+2:wght@300;600&display=swap" rel="stylesheet">



/* FULL-WIDTH GLASS SECTION (NO ROUNDED CORNERS, NO CARD) */
.glass-fuller {
    background: rgba(10, 10, 30, 0.4) !important;
    backdrop-filter: blur(20px) !important;
    -webkit-backdrop-filter: blur(20px) !important;
    border: 1px solid rgba(0, 255, 255, 0.2) !important;
    border-radius: 0px !important;
    padding: 80px 40px !important;
    margin: 0 !important;
    width: 100% !important;
    max-width: none !important;
    box-shadow: 0 0 40px rgba(0, 255, 255, 0.1) !important;
    font-family: 'Exo 2', sans-serif !important;
}
.glass-full {
    background: linear-gradient(-45deg, #0f0c29, #302b63, #24243e) !important;
    background-size: 400% 400% !important;
    animation: gradientShift 18s ease infinite !important;
    backdrop-filter: blur(16px) !important;
    -webkit-backdrop-filter: blur(16px) !important;
    border: none !important;
    border-radius: 0px !important;
    padding: 0 !important;           /* ← WAS 80px 40px β†’ NOW 0 */
    margin: 0 !important;
    width: 100% !important;
    max-width: none !important;
    box-shadow: none !important;
}


/* Section Title */
.section-ti {
    font-size: 3rem !important;
    font-weight: 800 !important;
    color: #00ff88 !important;
    text-align: center !important;
    margin-bottom: 40px !important;
    text-shadow: 0 0 20px rgba(0,255,136,0.4) !important;
    letter-spacing: 2px !important;
}
.section-title {
    font-family: 'Orbitron', sans-serif !important;
    font-size: 3.5rem !important;
    font-weight: 900 !important;
    color: #00ffff !important;
    text-shadow: 0 0 20px rgba(0, 255, 255, 0.6), 0 0 40px rgba(0, 255, 255, 0.3) !important;
    letter-spacing: 4px !important;
    text-align: center !important;
    margin-bottom: 40px !important;
}

/* Animation */
@keyframes gradientShift {
    0%, 100% { background-position: 0% 50%; }
    50% { background-position: 100% 50%; }
}

/* Scroll Hint */
.scroll-hint {
    position: absolute !important;
    bottom: 40px !important;
    animation: bounce 2s infinite !important;
}
@keyframes bounce {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-12px); }
}
</style>
""")

    

    # === HEADER: Title, Slogan, Team ===
        # ──────────────────────  TITLE + SLOGAN  ──────────────────────
        # === FULL-SCREEN HERO TITLE (FUTURISTIC) ===
    gr.HTML("""
    <div id="hero" style="
        height: 100vh; 
        background: linear-gradient(-45deg, #0f0c29, #302b63, #24243e);
        background-size: 400% 400%;
        animation: gradientShift 15s ease infinite;
        display: flex; flex-direction: column; justify-content: center; align-items: center;
        text-align: center; color: white; position: relative; overflow: hidden;
        margin: 0; padding: 0;
    ">
        <!-- Floating Particles -->
        <div class="particle" style="position: absolute; width: 4px; height: 4px; background: #00ff88; border-radius: 50%; 
             animation: float 6s infinite; top: 20%; left: 15%;"></div>
        <div class="particle" style="width: 6px; height: 6px; background: #ffaa00; animation: float 8s infinite; top: 60%; left: 70%;"></div>
        <div class="particle" style="width: 3px; height: 3px; background: #aa00ff; animation: float 10s infinite; top: 40%; left: 50%;"></div>

        <!-- Title -->
       <h1 style="
    font-family: 'Orbitron', sans-serif;
    font-size: 6rem; font-weight: 900; margin: 0;
    background: linear-gradient(90deg, #00ffff, #ff00ff);
    -webkit-background-clip: text; -webkit-text-fill-color: transparent;
    text-shadow: 0 0 30px rgba(0,255,255,0.6), 0 0 60px rgba(255,0,255,0.4);
    letter-spacing: 10px;
">
    NEUROSENSE
</h1>

        <!-- Slogan -->
        <p style="
            font-size: 1.8rem; margin: 20px 0; opacity: 0.9; max-width: 800px;
            font-weight: 300; letter-spacing: 1.5px;
            text-shadow: 0 0 10px rgba(255,255,255,0.3);
        ">
            <em>The Brain IMDb – Unraveling emotions, one second at a time.</em>
        </p>

        <!-- Scroll Hint -->
        <div style="
            position: absolute; bottom: 40px; left: 50%; transform: translateX(-50%);
            animation: bounce 2s infinite;
        ">
            <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="#00ff88" stroke-width="2">
                <path d="M7 13l5 5 5-5"></path>
            </svg>
        </div>
    </div>

    <style>
    @keyframes gradientShift {
        0% { background-position: 0% 50%; }
        50% { background-position: 100% 50%; }
        100% { background-position: 0% 50%; }
    }
    @keyframes float {
        0%, 100% { transform: translateY(0) rotate(0deg); }
        50% { transform: translateY(-20px) rotate(180deg); }
    }
    @keyframes titleGlow {
        from { text-shadow: 0 0 30px rgba(0,255,136,0.5); }
        to { text-shadow: 0 0 50px rgba(0,255,136,0.8), 0 0 70px rgba(255,170,0,0.6); }
    }
    @keyframes bounce {
        0%, 100% { transform: translateX(-50%) translateY(0); }
        50% { transform: translateX(-50%) translateY(-10px); }
    }
    </style>
    """)

    # ------------------ Changes here
    with gr.Column(elem_id="main-content", elem_classes="scroll-container"):
        # Add padding to avoid overlap
        gr.HTML("<div style='height: 80px;'></div>")


    
    # ──────────────────────  TEAM CARDS  ──────────────────────
    gr.HTML("""
        <div style="
            min-height: 100vh; padding: 100px 20px; 
            background: linear-gradient(-45deg, #0f0c29, #302b63, #24243e);
            background-size: 400% 400%; animation: gradientShift 15s ease infinite;
            display: flex; flex-direction: column; justify-content: center; align-items: center;
            text-align: center; color: white; position: relative; overflow: hidden;
        ">
            <h2 style="
                font-size: 3.5rem; font-weight: 800; margin: 0 0 60px;
                background: linear-gradient(90deg, #00ff88, #ffaa00, #aa00ff);
                -webkit-background-clip: text; -webkit-text-fill-color: transparent;
                letter-spacing: 3px;
            ">
                MEET THE TEAM
            </h2>

            <div style="display: flex; gap: 40px; flex-wrap: wrap; justify-content: center; max-width: 1200px;">
                <!-- Muhammad Shafran -->
                <div style="
                    background: rgba(255,255,255,0.15); backdrop-filter: blur(14px);
                    border: 1px solid rgba(255,255,255,0.25); border-radius: 24px;
                    padding: 32px; width: 280px; box-shadow: 0 12px 40px rgba(0,0,0,0.2);
                    border-left: 8px solid #00ff88;
                ">
                    <h3 style="margin:0 0 12px; color:#fff; font-size:1.6rem; font-weight:600;">
                        Muhammad Shafran
                    </h3>
                    <p style="margin:0; color:#ddd; font-size:1.1rem;">RP21-EE-416</p>
                </div>

                <!-- Hadia Shahid -->
                <div style="
                    background: rgba(255,255,255,0.15); backdrop-filter: blur(14px);
                    border: 1px solid rgba(255,255,255,0.25); border-radius: 24px;
                    padding: 32px; width: 280px; box-shadow: 0 12px 40px rgba(0,0,0,0.2);
                    border-left: 8px solid #ffaa00;
                ">
                    <h3 style="margin:0 0 12px; color:#fff; font-size:1.6rem; font-weight:600;">
                        Hadia Shahid
                    </h3>
                    <p style="margin:0; color:#ddd; font-size:1.1rem;">RP21-EE-424</p>
                </div>

                <!-- Zulqarnain Haider -->
                <div style="
                    background: rgba(255,255,255,0.15); backdrop-filter: blur(14px);
                    border: 1px solid rgba(255,255,255,0.25); border-radius: 24px;
                    padding: 32px; width: 280px; box-shadow: 0 12px 40px rgba(0,0,0,0.2);
                    border-left: 8px solid #aa00ff;
                ">
                    <h3 style="margin:0 0 12px; color:#fff; font-size:1.6rem; font-weight:600;">
                        Zulqarnain Haider
                    </h3>
                    <p style="margin:0; color:#ddd; font-size:1.1rem;">RP21-EE-433</p>
                </div>
            </div>

            <!-- Supervisor -->
            <div style="
                margin-top: 80px; padding: 20px 40px;
                background: rgba(255,255,255,0.1); backdrop-filter: blur(10px);
                border-radius: 16px; border: 1px solid rgba(255,255,255,0.2);
                font-size: 1.3rem; font-weight: 600; color: #ccc;
            ">
                <strong>Supervisor:</strong> Dr. Danish
            </div>

            <!-- Scroll Hint -->
            <div style="position: absolute; bottom: 40px; animation: bounce 2s infinite;">
                <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#00ff88" stroke-width="2">
                    <path d="M7 13l5 5 5-5"></path>
                </svg>
            </div>
        </div>
        """)

        # ────────────────────── SECTION 2: PRODUCT DESCRIPTION (FULL-SCREEN) ──────────────────────
    gr.HTML("""
        <div style="
            min-height: 100vh; padding: 120px 20px;
            background: linear-gradient(-45deg, #1a1a2e, #16213e, #0f3460);
            background-size: 400% 400%; animation: gradientShift 18s ease infinite;
            display: flex; flex-direction: column; justify-content: center; align-items: center;
            text-align: center; color: white; position: relative;
        ">
            <h2 style="
                font-size: 3.8rem; font-weight: 900; margin: 0 0 50px;
                background: linear-gradient(90deg, #aa00ff, #00ff88);
                -webkit-background-clip: text; -webkit-text-fill-color: transparent;
                letter-spacing: 2px;
            ">
                NEUROSENSE
            </h2>
            <h3 style="font-size: 2rem; margin: 0 0 40px; color: #00ff88; font-weight: 600;">
                The Brain IMDb
            </h3>
            <div style="max-width: 900px; line-height: 1.8; font-size: 1.2rem; color: #ddd;">
                <p>
                    NeuroSense is an AI-powered emotion recognition system that decodes human feelings from EEG brainwave data in real-time. 
                    Using advanced deep learning models (CNN-GRU), it classifies emotions such as <strong>Focused</strong>, <strong>Funny</strong>, 
                    <strong>Meditation</strong>, <strong>Normal</strong>, and <strong>Sad</strong> β€” second by second.
                </p>
                <p style="margin-top: 20px;">
                    Whether you're analyzing meditation sessions, detecting focus in learning, or exploring emotional responses to humor, 
                    NeuroSense turns raw brain signals into meaningful insights β€” just like IMDb does for movies.
                </p>
                <p style="margin-top: 20px; font-style: italic; color: #aaa;">
                    "Your brain doesn't lie. We just help you listen."
                </p>
            </div>

            <!-- Scroll Hint -->
            <div style="position: absolute; bottom: 40px; animation: bounce 2s infinite;">
                <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#00ff88" stroke-width="2">
                    <path d="M7 13l5 5 5-5"></path>
                </svg>
            </div>
        </div>
        """)
    

    # === ANALYZER SECTION ===
    

    with gr.Column(elem_classes="glass-full"):
        with gr.Row():
            csv_in = gr.File(label="Upload EEG CSV", file_types=[".csv"])
            load_btn = gr.Button("LOAD", variant="primary", size="lg")

        emotion_box = gr.HTML(
            value="<div style='text-align:center; padding:80px; font-size:3rem; background:#333; color:#666; border-radius:30px;'>Upload CSV to begin</div>"
        )

        status = gr.Textbox(label="Status", value="Ready", interactive=False)

        with gr.Row():
            play_pause_btn = gr.Button("PLAY", variant="primary", size="lg")
            slider = gr.Slider(0, 60, value=0, step=1, label="Timeline (seconds)", interactive=True)

        

    # Scroll Hint
    gr.HTML("""
    <div class="scroll-hint">
        <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#00bcd4" stroke-width="2">
            <path d="M7 13l5 5 5-5"></path>
        </svg>
    </div>
    """)

# Hidden States
    idx_state = gr.State(0)
    emo_list_state = gr.State([])
    duration_state = gr.State(0)  # for export


        
    
    # -------------------RESULTS SECTION

    # === RESULTS SECTION ===
    

    with gr.Column(elem_classes="glass-full"):
        # Timeline
        gr.Markdown("#### Emotion Timeline (Per Second)", elem_classes="plot-title")
        timeline_plot = gr.Plot()

        # Bar Chart
        gr.Markdown("#### Emotion Distribution", elem_classes="plot-title")
        emotion_plot = gr.Plot()

        # Top 2
        gr.Markdown("#### Top Emotions", elem_classes="plot-title")
        top_emotions_text = gr.HTML(value="<div style='text-align:center; color:#ccc; font-size:1.1rem;'>Load a file to see results.</div>")

    # Scroll Hint
    gr.HTML("""
    <div class="scroll-hint">
        <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#00bcd4" stroke-width="2">
            <path d="M7 13l5 5 5-5"></path>
        </svg>
    </div>
    """)

    # ========================================
    # 6. EVENT BINDINGS (Interactions)
    # ========================================

    # --- LOAD BUTTON: Process CSV and update everything ---
    load_btn.click(
        fn=load_csv,
        inputs=csv_in,
        outputs=[
            emotion_box, status, slider, idx_state, play_pause_btn, timeline_plot,
            emotion_plot, top_emotions_text, emo_list_state
        ]
    )

    # --- PLAY/PAUSE BUTTON: Complex chain to avoid UI blanking ---
    play_pause_btn.click(
        toggle_play_pause,
        outputs=idx_state
    ).then(
        lambda: None,
        outputs=None
    ).then(
        lambda: "PAUSE" if is_playing else "PLAY",
        outputs=play_pause_btn
    ).then(
        play_loop,
        outputs=[emotion_box, idx_state, play_pause_btn]
    )

    # --- SLIDER: Seek to any second ---
    slider.change(
        seek_to,
        inputs=slider,
        outputs=[emotion_box, idx_state, play_pause_btn]
    ).then(
        lambda x: x,
        inputs=idx_state,
        outputs=slider
    )


    demo.load(
        fn=None,
        inputs=None,
        outputs=None,
        js="""
        () => {
            document.documentElement.style.scrollBehavior = 'smooth';
            const style = document.createElement('style');
            style.innerHTML = `
                @keyframes gradientShift { 0%,100% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } }
                @keyframes bounce { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-12px); } }
            `;
            document.head.appendChild(style);
        }
        """
    )

# ========================================
# 7. LAUNCH APP
# ========================================
print("LAUNCHING NeuroSense β€” FULL VERSION WITH TEAM, PLOTS & UNBREAKABLE PLAYBACK")
demo.queue(max_size=20)  # Handle up to 20 concurrent users
demo.launch()