Spaces:
Runtime error

File size: 27,844 Bytes
227387f
 
 
 
 
 
8ea8fcc
227387f
8ea8fcc
227387f
 
 
 
 
8ea8fcc
227387f
 
 
8ea8fcc
227387f
 
 
8ea8fcc
227387f
 
 
 
 
 
 
 
 
8ea8fcc
227387f
 
 
 
8ea8fcc
227387f
 
 
 
 
8ea8fcc
227387f
 
 
 
 
 
 
 
 
8ea8fcc
227387f
 
 
 
 
 
 
 
 
 
8ea8fcc
227387f
 
 
 
8ea8fcc
227387f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ea8fcc
227387f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc6857f
227387f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc6857f
227387f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ea8fcc
 
 
227387f
cc6857f
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
import os
import json
import hashlib
import uuid
from datetime import datetime
from pathlib import Path
import gradio as gr
import requests

# Configuration
ACCOUNTS_DIR = Path("accounts")
CHATS_DIR = Path("chats")
ACCOUNTS_DIR.mkdir(exist_ok=True)
CHATS_DIR.mkdir(exist_ok=True)

# NVIDIA API Configuration
NVIDIA_API_KEY = "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"
NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"

# Model configurations
CHAT_MODEL = "qwen/qwen2.5-coder-32b-instruct"
CODING_MODEL = "qwen/qwen3-235b-a22b"

# Custom CSS for ultra modern dark UI
CUSTOM_CSS = """
/* Global Styles */
.gradio-container {
    max-width: 100% !important;
    padding: 0 !important;
    background: linear-gradient(135deg, #0f0f1a 0%, #1a1a2e 50%, #16213e 100%) !important;
    min-height: 100vh;
}

/* Hide default Gradio elements */
.prose, .gradio-container > .flex > .prose {
    display: none !important;
}

/* Main container */
.contain {
    padding: 0 !important;
    max-width: 100% !important;
}

/* Auth container styling */
.auth-box {
    background: rgba(26, 26, 46, 0.95) !important;
    border: 1px solid rgba(99, 102, 241, 0.3) !important;
    border-radius: 20px !important;
    padding: 30px !important;
    box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5), 0 0 100px rgba(99, 102, 241, 0.1) !important;
    backdrop-filter: blur(20px) !important;
}

/* Input styling */
.input-box input, .input-box textarea {
    background: rgba(15, 15, 26, 0.8) !important;
    border: 1px solid rgba(99, 102, 241, 0.3) !important;
    border-radius: 12px !important;
    color: #f8fafc !important;
    font-size: 15px !important;
    padding: 14px 18px !important;
    transition: all 0.3s ease !important;
}

.input-box input:focus, .input-box textarea:focus {
    border-color: #6366f1 !important;
    box-shadow: 0 0 20px rgba(99, 102, 241, 0.3) !important;
}

.input-box input::placeholder, .input-box textarea::placeholder {
    color: #64748b !important;
}

/* Button styling */
.primary-btn {
    background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #a855f7 100%) !important;
    border: none !important;
    border-radius: 12px !important;
    color: white !important;
    font-weight: 600 !important;
    padding: 14px 28px !important;
    font-size: 15px !important;
    transition: all 0.3s ease !important;
    box-shadow: 0 4px 15px rgba(99, 102, 241, 0.4) !important;
}

.primary-btn:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 8px 25px rgba(99, 102, 241, 0.5) !important;
}

.secondary-btn {
    background: rgba(99, 102, 241, 0.1) !important;
    border: 1px solid rgba(99, 102, 241, 0.3) !important;
    border-radius: 12px !important;
    color: #a5b4fc !important;
    font-weight: 500 !important;
    padding: 12px 24px !important;
    transition: all 0.3s ease !important;
}

.secondary-btn:hover {
    background: rgba(99, 102, 241, 0.2) !important;
    border-color: #6366f1 !important;
}

.danger-btn {
    background: rgba(239, 68, 68, 0.1) !important;
    border: 1px solid rgba(239, 68, 68, 0.3) !important;
    border-radius: 10px !important;
    color: #f87171 !important;
    font-weight: 500 !important;
    padding: 10px 20px !important;
    transition: all 0.3s ease !important;
}

.danger-btn:hover {
    background: rgba(239, 68, 68, 0.2) !important;
    border-color: #ef4444 !important;
}

/* Chat container */
.chat-container {
    background: rgba(15, 15, 26, 0.6) !important;
    border: 1px solid rgba(99, 102, 241, 0.2) !important;
    border-radius: 16px !important;
    overflow: hidden !important;
}

/* Message styling */
.message.user {
    background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%) !important;
    border-radius: 18px 18px 4px 18px !important;
    color: white !important;
    padding: 14px 18px !important;
    margin: 8px 0 !important;
    max-width: 80% !important;
    margin-left: auto !important;
    box-shadow: 0 4px 15px rgba(99, 102, 241, 0.3) !important;
}

.message.bot {
    background: rgba(30, 30, 50, 0.8) !important;
    border: 1px solid rgba(99, 102, 241, 0.2) !important;
    border-radius: 18px 18px 18px 4px !important;
    color: #f8fafc !important;
    padding: 14px 18px !important;
    margin: 8px 0 !important;
    max-width: 80% !important;
}

/* Chat input */
.chat-input textarea {
    background: rgba(15, 15, 26, 0.9) !important;
    border: 1px solid rgba(99, 102, 241, 0.3) !important;
    border-radius: 16px !important;
    color: #f8fafc !important;
    min-height: 120px !important;
    max-height: 200px !important;
    padding: 16px 20px !important;
    font-size: 15px !important;
    line-height: 1.6 !important;
    resize: none !important;
}

.chat-input textarea:focus {
    border-color: #6366f1 !important;
    box-shadow: 0 0 30px rgba(99, 102, 241, 0.2) !important;
}

/* Dropdown styling */
.dropdown select {
    background: rgba(15, 15, 26, 0.9) !important;
    border: 1px solid rgba(99, 102, 241, 0.3) !important;
    border-radius: 10px !important;
    color: #f8fafc !important;
    padding: 10px 16px !important;
    font-size: 14px !important;
}

/* Radio button styling */
.radio-group label {
    background: rgba(15, 15, 26, 0.6) !important;
    border: 1px solid rgba(99, 102, 241, 0.2) !important;
    border-radius: 10px !important;
    color: #94a3b8 !important;
    padding: 10px 16px !important;
    transition: all 0.3s ease !important;
}

.radio-group label.selected {
    background: linear-gradient(135deg, rgba(99, 102, 241, 0.3) 0%, rgba(139, 92, 246, 0.3) 100%) !important;
    border-color: #6366f1 !important;
    color: #f8fafc !important;
}

/* Chat list */
.chat-list-item {
    background: rgba(15, 15, 26, 0.4) !important;
    border: 1px solid rgba(99, 102, 241, 0.1) !important;
    border-radius: 12px !important;
    padding: 12px 16px !important;
    margin: 6px 0 !important;
    cursor: pointer !important;
    transition: all 0.3s ease !important;
}

.chat-list-item:hover {
    background: rgba(99, 102, 241, 0.1) !important;
    border-color: rgba(99, 102, 241, 0.3) !important;
}

.chat-list-item.active {
    background: linear-gradient(135deg, rgba(99, 102, 241, 0.2) 0%, rgba(139, 92, 246, 0.2) 100%) !important;
    border-color: #6366f1 !important;
}

/* Title styling */
.title-text {
    background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #a855f7 100%) !important;
    -webkit-background-clip: text !important;
    -webkit-text-fill-color: transparent !important;
    background-clip: text !important;
    font-size: 28px !important;
    font-weight: 700 !important;
}

/* Status text */
.status-text {
    color: #22c55e !important;
    font-size: 13px !important;
}

.error-text {
    color: #ef4444 !important;
    font-size: 14px !important;
    background: rgba(239, 68, 68, 0.1) !important;
    padding: 10px 16px !important;
    border-radius: 10px !important;
    border: 1px solid rgba(239, 68, 68, 0.2) !important;
}

.success-text {
    color: #22c55e !important;
    font-size: 14px !important;
    background: rgba(34, 197, 94, 0.1) !important;
    padding: 10px 16px !important;
    border-radius: 10px !important;
    border: 1px solid rgba(34, 197, 94, 0.2) !important;
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 6px;
}

::-webkit-scrollbar-track {
    background: transparent;
}

::-webkit-scrollbar-thumb {
    background: rgba(99, 102, 241, 0.3);
    border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
    background: rgba(99, 102, 241, 0.5);
}

/* User info */
.user-badge {
    background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%) !important;
    border-radius: 12px !important;
    padding: 8px 16px !important;
    color: white !important;
    font-weight: 500 !important;
}

/* Mode selector */
.mode-selector {
    background: rgba(15, 15, 26, 0.6) !important;
    border: 1px solid rgba(99, 102, 241, 0.2) !important;
    border-radius: 12px !important;
    padding: 16px !important;
}

/* Animation */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

.fade-in {
    animation: fadeIn 0.3s ease !important;
}

/* Loading dots */
.loading-dots::after {
    content: '...';
    animation: dots 1.5s steps(4, end) infinite;
}

@keyframes dots {
    0%, 20% { content: ''; }
    40% { content: '.'; }
    60% { content: '..'; }
    80%, 100% { content: '...'; }
}
"""


def hash_password(password: str) -> str:
    """Hash password using SHA-256"""
    return hashlib.sha256(password.encode()).hexdigest()


def get_user_file(username: str) -> Path:
    """Get the user's account file path"""
    return ACCOUNTS_DIR / f"{username}.json"


def get_user_chats_dir(username: str) -> Path:
    """Get the user's chats directory"""
    user_dir = CHATS_DIR / username
    user_dir.mkdir(exist_ok=True, parents=True)
    return user_dir


def register_user(username: str, password: str) -> tuple[bool, str]:
    """Register a new user"""
    if not username or not password:
        return False, "Username and password are required"
    
    if len(username) < 3:
        return False, "Username must be at least 3 characters"
    
    if len(password) < 6:
        return False, "Password must be at least 6 characters"
    
    user_file = get_user_file(username)
    if user_file.exists():
        return False, "Username already exists"
    
    user_data = {
        "username": username,
        "password": hash_password(password),
        "created_at": datetime.now().isoformat()
    }
    
    with open(user_file, 'w') as f:
        json.dump(user_data, f, indent=2)
    
    get_user_chats_dir(username)
    return True, "Registration successful! Please login."


def login_user(username: str, password: str) -> tuple[bool, str]:
    """Login a user"""
    if not username or not password:
        return False, "Username and password are required"
    
    user_file = get_user_file(username)
    if not user_file.exists():
        return False, "User not found"
    
    with open(user_file, 'r') as f:
        user_data = json.load(f)
    
    if user_data["password"] != hash_password(password):
        return False, "Invalid password"
    
    return True, f"Welcome back, {username}!"


def create_chat(username: str, title: str = "New Chat") -> dict:
    """Create a new chat for a user"""
    chat_id = str(uuid.uuid4())[:8]
    chat_data = {
        "id": chat_id,
        "title": title,
        "created_at": datetime.now().isoformat(),
        "messages": []
    }
    
    chats_dir = get_user_chats_dir(username)
    chat_file = chats_dir / f"{chat_id}.json"
    
    with open(chat_file, 'w') as f:
        json.dump(chat_data, f, indent=2)
    
    return chat_data


def get_user_chats(username: str) -> list[dict]:
    """Get all chats for a user"""
    chats_dir = get_user_chats_dir(username)
    chats = []
    
    for chat_file in chats_dir.glob("*.json"):
        with open(chat_file, 'r') as f:
            chat_data = json.load(f)
            chats.append(chat_data)
    
    chats.sort(key=lambda x: x["created_at"], reverse=True)
    return chats


def get_chat(username: str, chat_id: str) -> dict | None:
    """Get a specific chat"""
    chats_dir = get_user_chats_dir(username)
    chat_file = chats_dir / f"{chat_id}.json"
    
    if not chat_file.exists():
        return None
    
    with open(chat_file, 'r') as f:
        return json.load(f)


def save_chat(username: str, chat_id: str, chat_data: dict):
    """Save chat data"""
    chats_dir = get_user_chats_dir(username)
    chat_file = chats_dir / f"{chat_id}.json"
    
    with open(chat_file, 'w') as f:
        json.dump(chat_data, f, indent=2)


def delete_chat_file(username: str, chat_id: str):
    """Delete a chat file"""
    chats_dir = get_user_chats_dir(username)
    chat_file = chats_dir / f"{chat_id}.json"
    
    if chat_file.exists():
        chat_file.unlink()


def stream_nvidia_response(messages: list[dict], mode: str = "chat"):
    """Stream response from NVIDIA API"""
    model = CODING_MODEL if mode == "coding" else CHAT_MODEL
    max_tokens = 8192 if mode == "coding" else 4096
    
    headers = {
        "Authorization": f"Bearer {NVIDIA_API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": model,
        "messages": messages,
        "temperature": 0.2,
        "top_p": 0.7,
        "max_tokens": max_tokens,
        "stream": True
    }
    
    if mode == "coding":
        payload["chat_template_kwargs"] = {"thinking": False}
    
    try:
        response = requests.post(
            f"{NVIDIA_BASE_URL}/chat/completions",
            headers=headers,
            json=payload,
            stream=True,
            timeout=120
        )
        
        for line in response.iter_lines():
            if line:
                line = line.decode('utf-8')
                if line.startswith("data: "):
                    data = line[6:]
                    if data == "[DONE]":
                        break
                    try:
                        chunk = json.loads(data)
                        if chunk.get("choices") and chunk["choices"][0].get("delta", {}).get("content"):
                            yield chunk["choices"][0]["delta"]["content"]
                    except json.JSONDecodeError:
                        continue
    except Exception as e:
        yield f"\n[Error: {str(e)}]"


def format_chat_history(messages: list[dict]) -> list:
    """Format messages for display in Gradio Chatbot"""
    formatted = []
    for msg in messages:
        role = "user" if msg["role"] == "user" else "assistant"
        formatted.append([msg["content"] if role == "user" else None, 
                         msg["content"] if role == "assistant" else None])
    return formatted


# Create the Gradio app
def create_app():
    with gr.Blocks(title="AI Assistant") as app:
        # State variables
        current_user = gr.State(None)
        current_chat_id = gr.State(None)
        chat_history = gr.State([])
        
        # ==================== AUTH SECTION ====================
        with gr.Group(visible=True, elem_classes=["auth-box"]) as auth_section:
            gr.Markdown("# ✨ AI Assistant", elem_classes=["title-text"])
            gr.Markdown("Your intelligent conversation partner")
            
            with gr.Tabs() as auth_tabs:
                with gr.Tab("Login", id="login_tab"):
                    login_username = gr.Textbox(
                        label="Username",
                        placeholder="Enter your username",
                        elem_classes=["input-box"]
                    )
                    login_password = gr.Textbox(
                        label="Password",
                        placeholder="Enter your password",
                        type="password",
                        elem_classes=["input-box"]
                    )
                    login_btn = gr.Button("Login", variant="primary", elem_classes=["primary-btn"])
                    login_status = gr.Markdown("", elem_classes=["error-text"])
                
                with gr.Tab("Register", id="register_tab"):
                    reg_username = gr.Textbox(
                        label="Username",
                        placeholder="Choose a username (min 3 characters)",
                        elem_classes=["input-box"]
                    )
                    reg_password = gr.Textbox(
                        label="Password",
                        placeholder="Choose a password (min 6 characters)",
                        type="password",
                        elem_classes=["input-box"]
                    )
                    reg_btn = gr.Button("Register", variant="primary", elem_classes=["primary-btn"])
                    reg_status = gr.Markdown("", elem_classes=["error-text"])
        
        # ==================== MAIN APP SECTION ====================
        with gr.Group(visible=False) as main_section:
            with gr.Row():
                # Sidebar
                with gr.Column(scale=1, min_width=280):
                    with gr.Group(elem_classes=["mode-selector"]):
                        gr.Markdown("### πŸ’¬ AI Assistant")
                        user_display = gr.Markdown("", elem_classes=["user-badge"])
                        
                        gr.Markdown("### πŸ“ Your Chats")
                        chat_list = gr.Dataset(
                            label="Select a chat",
                            components=["text"],
                            samples=[["No chats yet"]],
                            elem_classes=["chat-list"]
                        )
                        
                        with gr.Row():
                            new_chat_btn = gr.Button("βž• New Chat", elem_classes=["secondary-btn"])
                            delete_chat_btn = gr.Button("πŸ—‘οΈ Delete", elem_classes=["danger-btn"])
                        
                        logout_btn = gr.Button("Logout", elem_classes=["danger-btn"])
                
                # Main chat area
                with gr.Column(scale=3):
                    with gr.Group(elem_classes=["chat-container"]):
                        chat_title = gr.Markdown("### Select or create a chat")
                        
                        with gr.Row():
                            mode_dropdown = gr.Dropdown(
                                choices=[("πŸ’¬ Chat", "chat"), ("πŸ’» Coding", "coding")],
                                value="chat",
                                label="Mode",
                                interactive=True,
                                elem_classes=["dropdown"]
                            )
                            current_chat_display = gr.Textbox(
                                value="No chat selected",
                                label="Current Chat",
                                interactive=False
                            )
                        
                        chatbot = gr.Chatbot(
                            label="Conversation",
                            height=500,
                            show_label=False,
                            elem_classes=["chat-container"]
                        )
                        
                        with gr.Row():
                            msg_input = gr.Textbox(
                                placeholder="Type your message here... (Press Enter to send, Shift+Enter for new line)",
                                lines=4,
                                max_lines=7,
                                show_label=False,
                                elem_classes=["chat-input"]
                            )
                        
                        with gr.Row():
                            send_btn = gr.Button("Send", variant="primary", elem_classes=["primary-btn"])
                            clear_btn = gr.Button("Clear Display", elem_classes=["secondary-btn"])
        
        # ==================== EVENT HANDLERS ====================
        
        def handle_login(username, password):
            if not username or not password:
                return None, None, [], "Please enter username and password", gr.update()
            
            success, message = login_user(username, password)
            if success:
                chats = get_user_chats(username)
                chat_samples = [[c["title"]] for c in chats] if chats else [["No chats yet"]]
                return (
                    username,
                    None,
                    [],
                    gr.update(visible=False),
                    gr.update(visible=True),
                    gr.update(value=f"**{username}**"),
                    gr.update(samples=chat_samples),
                    "No chat selected",
                    []
                )
            return None, None, [], message, gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
        
        def handle_register(username, password):
            if not username or not password:
                return "Please enter username and password"
            
            success, message = register_user(username, password)
            return message
        
        def handle_new_chat(username):
            if not username:
                return None, "Please login first", gr.update(), []
            
            chat = create_chat(username)
            chats = get_user_chats(username)
            chat_samples = [[c["title"]] for c in chats]
            
            return (
                chat["id"],
                chat["title"],
                gr.update(samples=chat_samples),
                []
            )
        
        def handle_select_chat(evt: gr.SelectData, username):
            if not username:
                return None, "No chat selected", [], gr.update()
            
            chats = get_user_chats(username)
            if evt.index < len(chats):
                selected_chat = chats[evt.index]
                chat_data = get_chat(username, selected_chat["id"])
                
                if chat_data:
                    history = [[m["content"], None] if m["role"] == "user" else [None, m["content"]] 
                              for m in chat_data["messages"]]
                    # Convert to messages format
                    msg_history = []
                    for m in chat_data["messages"]:
                        msg_history.append({"role": m["role"], "content": m["content"]})
                    
                    return (
                        selected_chat["id"],
                        selected_chat["title"],
                        msg_history,
                        gr.update(value=msg_history)
                    )
            return None, "No chat selected", [], gr.update()
        
        def handle_delete_chat(username, chat_id):
            if username and chat_id:
                delete_chat_file(username, chat_id)
                chats = get_user_chats(username)
                chat_samples = [[c["title"]] for c in chats] if chats else [["No chats yet"]]
                return None, "No chat selected", [], gr.update(samples=chat_samples), gr.update(value=[])
            return chat_id, gr.update(), gr.update(), gr.update(), gr.update()
        
        def handle_logout():
            return (
                None,  # current_user
                None,  # current_chat_id
                [],    # chat_history
                gr.update(visible=True),   # auth_section
                gr.update(visible=False),  # main_section
                gr.update(value=""),       # user_display
                gr.update(samples=[["No chats yet"]]),  # chat_list
                "No chat selected",        # current_chat_display
                gr.update(value=[]),       # chatbot
                "",                        # login_username
                "",                        # login_password
                ""                         # login_status
            )
        
        def handle_message(username, chat_id, history, message, mode):
            if not username:
                yield history, "Please login first"
                return
            
            if not chat_id:
                # Create new chat if none selected
                chat = create_chat(username)
                chat_id = chat["id"]
            
            if not message or not message.strip():
                yield history, chat_id
                return
            
            # Add user message to history
            user_msg = {"role": "user", "content": message}
            history = history or []
            history.append(user_msg)
            
            # Update chatbot display
            yield history, chat_id
            
            # Get chat data and add user message
            chat_data = get_chat(username, chat_id)
            if not chat_data:
                chat_data = {"id": chat_id, "title": "New Chat", "messages": []}
            
            chat_data["messages"].append(user_msg)
            
            # Update title if first message
            if len(chat_data["messages"]) == 1:
                chat_data["title"] = message[:40] + ("..." if len(message) > 40 else "")
            
            # Prepare messages for API
            api_messages = [{"role": m["role"], "content": m["content"]} for m in chat_data["messages"]]
            
            # Stream response
            full_response = ""
            assistant_msg = {"role": "assistant", "content": ""}
            
            for chunk in stream_nvidia_response(api_messages, mode):
                full_response += chunk
                assistant_msg["content"] = full_response
                
                # Update history with streaming response
                temp_history = history.copy()
                temp_history.append(assistant_msg.copy())
                yield temp_history, chat_id
            
            # Save the complete response
            chat_data["messages"].append({"role": "assistant", "content": full_response})
            save_chat(username, chat_id, chat_data)
            
            # Update final history
            history.append({"role": "assistant", "content": full_response})
            yield history, chat_id
        
        def clear_chat_display():
            return []
        
        # Connect event handlers
        login_btn.click(
            handle_login,
            inputs=[login_username, login_password],
            outputs=[current_user, current_chat_id, chat_history, login_status, 
                    auth_section, main_section, user_display, chat_list, 
                    current_chat_display, chatbot]
        )
        
        reg_btn.click(
            handle_register,
            inputs=[reg_username, reg_password],
            outputs=[reg_status]
        )
        
        new_chat_btn.click(
            handle_new_chat,
            inputs=[current_user],
            outputs=[current_chat_id, current_chat_display, chat_list, chatbot]
        )
        
        chat_list.select(
            handle_select_chat,
            inputs=[current_user],
            outputs=[current_chat_id, current_chat_display, chat_history, chatbot]
        )
        
        delete_chat_btn.click(
            handle_delete_chat,
            inputs=[current_user, current_chat_id],
            outputs=[current_chat_id, current_chat_display, chat_history, chat_list, chatbot]
        )
        
        logout_btn.click(
            handle_logout,
            outputs=[current_user, current_chat_id, chat_history, auth_section, 
                    main_section, user_display, chat_list, current_chat_display, 
                    chatbot, login_username, login_password, login_status]
        )
        
        send_btn.click(
            handle_message,
            inputs=[current_user, current_chat_id, chat_history, msg_input, mode_dropdown],
            outputs=[chatbot, current_chat_id]
        ).then(
            lambda: "",
            outputs=[msg_input]
        )
        
        # Also allow Enter to send
        msg_input.submit(
            handle_message,
            inputs=[current_user, current_chat_id, chat_history, msg_input, mode_dropdown],
            outputs=[chatbot, current_chat_id]
        ).then(
            lambda: "",
            outputs=[msg_input]
        )
        
        clear_btn.click(
            clear_chat_display,
            outputs=[chatbot]
        )
    
    return app


if __name__ == "__main__":
    app = create_app()
    app.launch(server_name="0.0.0.0", server_port=7860, css=CUSTOM_CSS, theme=gr.themes.Soft())