File size: 50,277 Bytes
7f6a022
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
import gradio as gr
import requests
import os
from dotenv import load_dotenv
from io import BytesIO
from PIL import Image
import PyPDF2
from pdf2image import convert_from_path
import tempfile
import sqlite3
from datetime import datetime

# Load environment variables from .env file
load_dotenv()

SERPAPI_KEY = os.getenv("SERPAPI_KEY")
HYPERBOLIC_API_KEY = os.getenv("HYPERBOLIC_API_KEY")
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")

# Admin password
ADMIN_PASSWORD = "BT54iv!@"

# Database setup
DB_PATH = "students.db"

def init_database():
    """Initialize the SQLite database and create students table if it doesn't exist."""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS students (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            medical_school TEXT NOT NULL,
            year TEXT NOT NULL,
            registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    """)
    conn.commit()
    conn.close()

def save_student(name, medical_school, year):
    """Save student information to the database."""
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute(
            "INSERT INTO students (name, medical_school, year) VALUES (?, ?, ?)",
            (name, medical_school, year)
        )
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"Error saving student: {e}")
        return False

def get_all_students():
    """Retrieve all students from the database."""
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("SELECT id, name, medical_school, year, registration_date FROM students ORDER BY registration_date DESC")
        students = cursor.fetchall()
        conn.close()
        return students
    except Exception as e:
        print(f"Error retrieving students: {e}")
        return []

# Initialize database on startup
init_database()


# Hyperbolic API configuration
HYPERBOLIC_API_URL = "https://api.hyperbolic.xyz/v1/chat/completions"
HYPERBOLIC_MODEL = "meta-llama/Llama-3.3-70B-Instruct"

# ElevenLabs API configuration
ELEVENLABS_API_URL = "https://api.elevenlabs.io/v1/text-to-speech"
# Using a standard "Professor" like voice (e.g., "Brian" - a deep, authoritative British voice, or similar)
# Voice ID for "Brian": nPczCjzI2devNBz1zQrb
ELEVENLABS_VOICE_ID = "nPczCjzI2devNBz1zQrb" 

def generate_audio(text: str, student_name: str = None) -> str:
    """
    Generate audio from text using ElevenLabs API.
    If student_name is provided, prepends a personalized greeting.
    Returns path to temporary audio file or None if failed.
    """
    if not ELEVENLABS_API_KEY:
        print("⚠️ ELEVENLABS_API_KEY is missing")
        return None
    
    if not text:
        print("⚠️ No text provided for audio generation")
        return None
    
    # Add personalized greeting if student name is provided
    if student_name:
        text = f"Welcome to Viva, Doctor {student_name}, let's start. {text}"
        
    print(f"Generating audio for text: {text[:50]}...")
        
    try:
        url = f"{ELEVENLABS_API_URL}/{ELEVENLABS_VOICE_ID}"
        headers = {
            "Accept": "audio/mpeg",
            "Content-Type": "application/json",
            "xi-api-key": ELEVENLABS_API_KEY
        }
        data = {
            "text": text,
            "model_id": "eleven_turbo_v2",
            "voice_settings": {
                "stability": 0.5,
                "similarity_boost": 0.5
            }
        }
        
        response = requests.post(url, json=data, headers=headers)
        
        if response.status_code == 200:
            # Save to temp file
            with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
                f.write(response.content)
                print(f"βœ… Audio generated successfully: {f.name}")
                return f.name
        else:
            print(f"❌ ElevenLabs API Error ({response.status_code}): {response.text}")
            return None
            
    except Exception as e:
        print(f"Error generating audio: {str(e)}")
        return None

def is_anatomy_related(query: str) -> tuple[bool, str]:
    """
    Validate if the query is anatomy-related using the LLM.
    Returns (is_valid, message)
    """
    validation_prompt = f"""You are an anatomy topic validator for medical students. 
Determine if the following question is related to human anatomy ONLY.

Question: "{query}"

Respond with ONLY "YES" if it's about anatomy (structures, organs, systems, blood vessels, nerves, bones, muscles, etc.)
Respond with ONLY "NO" if it's not about anatomy (physiology, biochemistry, pharmacology, diseases, treatments, etc.)

Response:"""

    try:
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {HYPERBOLIC_API_KEY}"
        }
        
        payload = {
            "model": HYPERBOLIC_MODEL,
            "messages": [{"role": "user", "content": validation_prompt}],
            "max_tokens": 10,
            "temperature": 0.1
        }
        
        response = requests.post(HYPERBOLIC_API_URL, headers=headers, json=payload, timeout=10)
        response.raise_for_status()
        
        result = response.json()
        answer = result["choices"][0]["message"]["content"].strip().upper()
        
        if "YES" in answer:
            return True, ""
        else:
            return False, "⚠️ Please ask questions related to anatomy only. This question appears to be about other medical topics."
    
    except Exception as e:
        # If validation fails, allow the query but log the error
        print(f"Validation error: {e}")
        return True, ""


def search_anatomy_image(query: str) -> tuple[list, str]:
    """
    Search for anatomy images using SERPAPI Google Images.
    Returns (list_of_image_urls, error_message)
    """
    try:
        params = {
            "engine": "google_images",
            "q": f"{query} anatomy diagram",
            "api_key": SERPAPI_KEY,
            "num": 10,  # Get more results for fallback
            "safe": "active"
        }
        
        response = requests.get("https://serpapi.com/search", params=params, timeout=15)
        response.raise_for_status()
        
        data = response.json()
        
        if "images_results" in data and len(data["images_results"]) > 0:
            # Get multiple image URLs, filter out SVG files
            image_urls = []
            for img in data["images_results"]:
                url = img.get("original", "")
                # Skip SVG files and other problematic formats
                if url and not url.lower().endswith('.svg'):
                    image_urls.append(url)
            
            if image_urls:
                return image_urls, ""
            else:
                return [], "No supported image formats found (SVG files excluded)."
        else:
            return [], "No images found for this anatomy topic."
    
    except Exception as e:
        return [], f"Error searching for images: {str(e)}"


def download_image(image_url: str) -> Image.Image:
    """
    Download and return PIL Image from URL.
    """
    try:
        # Add headers to mimic a browser request and avoid 403 errors
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.9',
            'Referer': 'https://www.google.com/'
        }
        response = requests.get(image_url, headers=headers, timeout=10)
        response.raise_for_status()
        img = Image.open(BytesIO(response.content))
        return img
    except Exception as e:
        raise Exception(f"Error downloading image: {str(e)}")


def generate_anatomy_info(query: str) -> str:
    """
    Generate educational information about the anatomy topic using Hyperbolic API.
    """
    try:
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {HYPERBOLIC_API_KEY}"
        }
        
        prompt = f"""You are an expert anatomy professor teaching MBBS students. Provide a detailed, high-level educational summary about: {query}

Format your response with clear sections using these exact emoji icons:

πŸ“ **Location & Definition:**
[Precise anatomical definition, location, and relations using standard medical terminology]

πŸ” **Key Anatomical Features:**
- [Detailed feature 1 (e.g., attachments, blood supply, innervation)]
- [Detailed feature 2]
- [Detailed feature 3]

πŸ₯ **Clinical Significance:**
- [Clinical correlation 1 (e.g., pathologies, surgical relevance)]
- [Clinical correlation 2]

πŸ”— **Related Structures:**
- [Related structure 1]
- [Related structure 2]

πŸ’‘ **Quick Memory Tip:**
[A high-yield mnemonic or tip for exams]

Keep it professional, accurate, and suitable for medical school level study. Use proper anatomical terminology throughout."""

        payload = {
            "model": HYPERBOLIC_MODEL,
            "messages": [{"role": "user", "content": prompt}],
            "max_tokens": 600,
            "temperature": 0.7
        }
        
        response = requests.post(HYPERBOLIC_API_URL, headers=headers, json=payload, timeout=20)
        response.raise_for_status()
        
        result = response.json()
        info = result["choices"][0]["message"]["content"]
        
        # Add prominent header to make it stand out
        formatted_info = f"""## πŸ“š Key Learning Points

{info}

---
πŸ’ͺ **Study Tip:** Read through these points carefully, then test yourself with VIVA mode!"""
        
        return formatted_info
    
    except Exception as e:
        return f"⚠️ Error generating information: {str(e)}"


def generate_viva_questions(topic: str) -> list:
    """
    Generate 5 viva questions for the anatomy topic.
    Returns list of question dictionaries with question, hint, and expected answer.
    """
    try:
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {HYPERBOLIC_API_KEY}"
        }
        
        prompt = f"""You are a strict but fair anatomy professor conducting a VIVA exam for final year MBBS students on: {topic}

Generate exactly 5 viva questions that test deep anatomical understanding, clinical application, and relations. For each question, provide:
1. The question (challenging, requiring synthesis of knowledge)
2. A helpful hint (guides thinking without giving the answer)
3. The expected key points in the answer (using proper terminology)

Format your response EXACTLY as follows:
Q1: [question]
HINT: [hint]
ANSWER: [expected answer key points]

Q2: [question]
HINT: [hint]
ANSWER: [expected answer key points]

... and so on for all 5 questions.

Make questions progressively harder. Start with detailed relations/supply, then move to complex clinical scenarios."""

        payload = {
            "model": HYPERBOLIC_MODEL,
            "messages": [{"role": "user", "content": prompt}],
            "max_tokens": 800,
            "temperature": 0.7
        }
        
        response = requests.post(HYPERBOLIC_API_URL, headers=headers, json=payload, timeout=25)
        response.raise_for_status()
        
        result = response.json()
        content = result["choices"][0]["message"]["content"]
        
        # Parse the questions
        questions = []
        lines = content.split('\n')
        current_q = {}
        
        for line in lines:
            line = line.strip()
            if line.startswith('Q') and ':' in line:
                if current_q:
                    questions.append(current_q)
                current_q = {'question': line.split(':', 1)[1].strip()}
            elif line.startswith('HINT:'):
                current_q['hint'] = line.split(':', 1)[1].strip()
            elif line.startswith('ANSWER:'):
                current_q['answer'] = line.split(':', 1)[1].strip()
        
        if current_q:
            questions.append(current_q)
        
        return questions[:5]  # Ensure exactly 5 questions
    
    except Exception as e:
        print(f"Error generating viva questions: {e}")
        return []


def evaluate_viva_answer(question: str, student_answer: str, expected_answer: str) -> tuple[str, str]:
    """
    Evaluate student's answer and provide feedback.
    Returns (feedback, score_emoji)
    """
    if not student_answer.strip():
        return "⏸️ Please provide an answer to continue.", "⏸️"
    
    try:
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {HYPERBOLIC_API_KEY}"
        }
        
        prompt = f"""You are an anatomy professor evaluating an MBBS student's VIVA answer. Expect high standards and precise terminology.

Question: {question}
Expected key points: {expected_answer}
Student's answer: {student_answer}

Provide feedback in this EXACT format:

[First, write one sentence evaluating the precision and depth of the answer]

βœ… **What was correct:**
[List correct points. Praise use of proper terminology.]

❌ **What was missing:**
[List missing key points, relations, or clinical aspects. Be specific about missing terminology.]

**Score:** [Choose: DISTINCTION, PASS, BORDERLINE, or FAIL]

[End with a constructive comment on how to improve to a professional medical standard]

Be professional and constructive. Demand accuracy."""

        payload = {
            "model": HYPERBOLIC_MODEL,
            "messages": [{"role": "user", "content": prompt}],
            "max_tokens": 400,
            "temperature": 0.6
        }
        
        response = requests.post(HYPERBOLIC_API_URL, headers=headers, json=payload, timeout=15)
        response.raise_for_status()
        
        result = response.json()
        feedback = result["choices"][0]["message"]["content"]
        
        # Determine emoji and encouragement based on feedback content
        feedback_upper = feedback.upper()
        if "DISTINCTION" in feedback_upper:
            emoji = "🌟"
            encouragement = "\n\nπŸŽ‰ **Outstanding!** Distinction level answer! You're mastering this topic!"
        elif "PASS" in feedback_upper:
            emoji = "βœ…"
            encouragement = "\n\nπŸ‘ **Good Pass!** Solid understanding. Review the finer details to reach distinction level."
        elif "BORDERLINE" in feedback_upper:
            emoji = "⚠️"
            encouragement = "\n\nπŸ’ͺ **Borderline.** You have the basics, but need more precision with terminology."
        else:
            emoji = "πŸ“š"
            encouragement = "\n\n🌱 **Keep studying.** Focus on the key anatomical relations and clinical points."
        
        # Format the complete feedback
        formatted_feedback = f"{emoji} **VIVA Feedback:**\n\n{feedback}{encouragement}\n\n---\n\nπŸ“– **Reference Answer:**\n{expected_answer}"
        
        return formatted_feedback, emoji
    
    except Exception as e:
        return f"⚠️ Could not evaluate answer: {str(e)}", "⚠️"


def process_anatomy_query(query: str) -> tuple:
    """
    Main function to process anatomy queries.
    Returns (image, info_text, error_message)
    """
    if not query.strip():
        return None, "", "Please enter a question about anatomy."
    
    # Validate if query is anatomy-related
    is_valid, validation_msg = is_anatomy_related(query)
    if not is_valid:
        return None, "", validation_msg
    
    # Search for images
    image_urls, img_error = search_anatomy_image(query)
    
    # Generate educational information
    info = generate_anatomy_info(query)
    
    # Try to download images from the list until one succeeds
    image = None
    download_error = ""
    
    if image_urls:
        for url in image_urls[:5]:  # Try up to 5 images
            try:
                image = download_image(url)
                download_error = ""  # Success!
                break  # Stop trying once we get a valid image
            except Exception as e:
                download_error = str(e)
                continue  # Try next image
        
        if not image and download_error:
            img_error = f"Could not download images. Last error: {download_error}"
    
    # Prepare result
    error_message = ""
    if img_error:
        error_message = f"⚠️ {img_error}"
    
    return image, info, error_message


# Book Learning Mode Functions
def process_uploaded_book(pdf_file):
    """
    Process uploaded PDF book and extract all pages with images and text.
    Returns (list_of_tuples, status_message) where tuple is (image, caption, text)
    """
    if pdf_file is None:
        return [], "Please upload a PDF file."
    
    try:
        extracted_data = []
        
        # Save uploaded file temporarily
        with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
            tmp_file.write(pdf_file)
            tmp_path = tmp_file.name
        
        try:
            # Convert all pages to images (this might take a while for large books)
            images = convert_from_path(tmp_path, dpi=150)
            
            # Extract text from pages
            reader = PyPDF2.PdfReader(tmp_path)
            
            for i, image in enumerate(images):
                # Get text for this page if available
                text_content = ""
                if i < len(reader.pages):
                    try:
                        text_content = reader.pages[i].extract_text()
                    except:
                        text_content = "Could not extract text from this page."
                
                # Limit text length to avoid token limits
                if len(text_content) > 2000:
                    text_content = text_content[:2000] + "..."
                
                extracted_data.append((image, f"Page {i+1}", text_content))
            
            status = f"βœ… Successfully processed {len(extracted_data)} pages from your anatomy textbook!"
            return extracted_data, status
        
        finally:
            # Clean up temp file
            if os.path.exists(tmp_path):
                os.unlink(tmp_path)
    
    except Exception as e:
        return [], f"⚠️ Error processing PDF: {str(e)}"


def analyze_book_image(image, page_info, page_text=""):
    """
    Analyze selected image from book using AI to extract anatomical information.
    Returns formatted explanation text.
    """
    if image is None:
        return "Please select an image from the book."
    
    try:
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {HYPERBOLIC_API_KEY}"
        }
        
        # Include extracted text in the prompt context
        context_text = f"Page Content:\n{page_text}" if page_text else "No text extracted from this page."
        
        prompt = f"""You are an expert anatomy professor helping MBBS students analyze their textbook content.

A student is looking at {page_info} of their anatomy textbook.
{context_text}

Based on the text content above, provide a high-level medical analysis:

## πŸ“– Page Overview
[Summarize the key anatomical topic using standard medical terminology]

## πŸ” Key Concepts Explained
[Explain the concepts in detail, focusing on relations, blood supply, nerve supply, and lymphatic drainage where applicable]

## πŸ₯ Clinical Relevance
[Detailed clinical correlations, surgical landmarks, or pathological conditions mentioned or relevant]

## πŸ’‘ Study Tips
[High-yield memory aids for medical exams]

## ❓ Self-Test Questions (MBBS Level)
1. [Question based on the page text]
2. [Question based on the page text]
...
15. [Question based on the page text]

(Provide at least 15 distinct, challenging questions covering detailed anatomy, relations, and clinical application)

Be professional, accurate, and suitable for medical school level study."""

        payload = {
            "model": HYPERBOLIC_MODEL,
            "messages": [{"role": "user", "content": prompt}],
            "max_tokens": 1200,
            "temperature": 0.5
        }
        
        response = requests.post(HYPERBOLIC_API_URL, headers=headers, json=payload, timeout=25)
        response.raise_for_status()
        
        result = response.json()
        explanation = result["choices"][0]["message"]["content"]
        
        formatted_output = f"""# πŸ“š Textbook Analysis: {page_info}

{explanation}

---

πŸ’ͺ **Next Steps:** Mastered this page? Try the VIVA mode to test yourself!"""
        
        return formatted_output
    
    except Exception as e:
        return f"⚠️ Error analyzing image: {str(e)}"


# VIVA Mode Handler Functions
def start_viva_mode(topic, image, student_name=""):
    """Initialize VIVA mode with questions."""
    if not topic or not image:
        return (
            gr.update(visible=False),  # viva_container
            "Please learn about a topic first before starting VIVA mode!",  # viva_status
            None, None, None, None, None, None, [], None, student_name  # other outputs
        )
    
    questions = generate_viva_questions(topic)
    
    if not questions or len(questions) == 0:
        return (
            gr.update(visible=False),
            "Error generating VIVA questions. Please try again.",
            None, None, None, None, None, gr.update(interactive=False), [], None, student_name
        )
   
    # Start with question 1
    q1 = questions[0]
    
    # Generate audio for first question with student name
    audio_path = generate_audio(q1['question'], student_name if student_name else None)
    
    return (
        gr.update(visible=True),  # Show VIVA container
        f"**VIVA MODE ACTIVE** πŸ“\nTopic: {topic}",  # viva_status
        image,  # viva_image
        f"### Question 1 of 5\n\n**{q1['question']}**",  # current_question_display
        f"πŸ’‘ **Hint:** {q1.get('hint', 'Think about the key anatomical features.')}",  # hint_display
        "",  # Clear answer input
        "",  # Clear feedback
        gr.update(interactive=True, value="Submit Answer"),  # Enable submit button
        questions,  # Store questions in state
        audio_path,  # Return audio path
        student_name  # Return student name to maintain in state
    )

# Wrapper to start VIVA with personalized greeting
def start_viva_with_name(name, topic, image):
    viva_container_out, viva_status_out, viva_image_out, cur_q_disp, hint_disp, stu_ans, fb_disp, sub_btn, viva_q_state, q_audio, student_name_out = start_viva_mode(topic, image, name)
    greeting = f"Doctor {name}, let's go to VIVA!"
    # Add greeting as separate markdown component above question
    viva_greeting_out = greeting
    return viva_container_out, viva_status_out, viva_image_out, cur_q_disp, hint_disp, stu_ans, fb_disp, sub_btn, viva_q_state, q_audio, viva_greeting_out, student_name_out


def submit_viva_answer(answer, questions, current_q_idx, student_name=""):
    """Process student's answer and move to next question."""
    if not questions or current_q_idx >= len(questions):
        return ("VIVA Complete!", "", "", gr.update(interactive=False), current_q_idx, None)
    
    q = questions[current_q_idx]
    feedback_text, emoji = evaluate_viva_answer(q['question'], answer, q.get('answer', ''))
    
    # Move to next question
    next_idx = current_q_idx + 1
    
    if next_idx < len(questions):
        next_q = questions[next_idx]
        next_question = f"### Question {next_idx + 1} of 5\n\n**{next_q['question']}**"
        next_hint = f"πŸ’‘ **Hint:** {next_q.get('hint', 'Think carefully about the anatomical relationships.')}"
        
        # Generate audio for next question with student name
        audio_path = generate_audio(next_q['question'], student_name if student_name else None)
        
        return (
            next_question,  # Show next question
            next_hint,  # Show next hint
            "",  # Clear answer box
            feedback_text,  # Show feedback for current answer
            gr.update(interactive=True, value="Submit Answer"),  # Keep button enabled
            next_idx,  # Update question index
            audio_path  # Play next question audio
        )
    else:
        # VIVA complete
        completion_msg = f"### πŸŽ‰ VIVA Complete!\n\nYou've answered all 5 questions. Great job on completing your anatomy VIVA training!"
        return (
            completion_msg,
            "",  # Clear hint
            "",  # Clear answer
            feedback_text,  # Final feedback
            gr.update(interactive=False, value="VIVA Complete"),
            next_idx,
            None  # No audio
        )


# Create Gradio interface
with gr.Blocks(title="AnatomyBot - MBBS Anatomy Tutor") as demo:
    # State variables
    student_name_state = gr.State("")
    viva_questions_state = gr.State([])
    current_question_idx = gr.State(0)
    current_topic = gr.State("")
    current_image_state = gr.State(None)
    is_registered = gr.State(False)  # Track if user has registered
    
    # Add custom CSS styling via HTML
    gr.HTML("""
        <style>
            /* Modal backdrop using body::after when modal exists and is visible */
            body:has(#registration_modal:not([style*="display: none"]))::after {
                content: '';
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.6);
                backdrop-filter: blur(8px);
                -webkit-backdrop-filter: blur(8px);
                z-index: 999;
                pointer-events: all;
            }
            
            /* Modal container */
            #registration_modal {
                position: fixed !important;
                top: 50% !important;
                left: 50% !important;
                transform: translate(-50%, -50%) !important;
                z-index: 1000 !important;
                background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%) !important;
                padding: 2.5rem !important;
                border-radius: 20px !important;
                border: 3px solid rgba(255,107,53,0.5) !important;
                box-shadow: 
                    0 10px 40px rgba(0,0,0,0.3),
                    0 0 20px rgba(255,107,53,0.2),
                    inset 0 1px 0 rgba(255,255,255,0.9) !important;
                max-width: 600px !important;
                width: 90% !important;
                animation: modalSlideIn 0.3s ease-out !important;
            }
            
            /* Modal animation */
            @keyframes modalSlideIn {
                from {
                    opacity: 0;
                    transform: translate(-50%, -60%);
                }
                to {
                    opacity: 1;
                    transform: translate(-50%, -50%);
                }
            }
            
            /* Beautify modal content */
            #registration_modal h1 {
                color: #2c3e50 !important;
                margin-bottom: 0.5rem !important;
                font-size: 2rem !important;
            }
            
            #registration_modal h3 {
                color: #7f8c8d !important;
                font-weight: 400 !important;
                font-size: 1.1rem !important;
            }
            
            /* ========================================
               RESPONSIVE NAVIGATION BAR FIX
               Ensures navigation stays horizontal in iframe/HF Spaces
               ======================================== */
            
            /* Force navigation bar to stay horizontal */
            #nav_bar {
                display: flex !important;
                flex-direction: row !important;
                flex-wrap: nowrap !important;
                gap: 0.5rem !important;
                width: 100% !important;
                overflow-x: auto !important;
                overflow-y: hidden !important;
            }
            
            /* Equal-width buttons that shrink gracefully */
            #nav_bar button {
                flex: 1 1 0 !important;
                min-width: 0 !important;
                white-space: nowrap !important;
                overflow: hidden !important;
                text-overflow: ellipsis !important;
                font-size: 0.875rem !important;
                padding: 0.5rem 0.75rem !important;
            }
            
            /* Responsive adjustments for narrower viewports */
            @media (max-width: 900px) {
                #nav_bar button {
                    font-size: 0.75rem !important;
                    padding: 0.4rem 0.5rem !important;
                }
            }
            
            @media (max-width: 600px) {
                #nav_bar button {
                    font-size: 0.7rem !important;
                    padding: 0.3rem 0.4rem !important;
                }
                
                /* Hide emojis on very small screens */
                #nav_bar button::before {
                    content: none !important;
                }
            }
        </style>
    """)
    
    # Main Application (always visible now)
    with gr.Column() as main_app:
        gr.Markdown(
            """
            # 🩺 AnatomyBot - Your MBBS Anatomy Tutor
            
            Master anatomy through AI-powered learning and interactive VIVA practice!
            """
        )
        
        # Display student name
        student_name_display = gr.Markdown("")
        
        # Custom Navigation Bar
        with gr.Row(elem_id="nav_bar"):
            nav_learning_btn = gr.Button("πŸ“š Learning Mode", variant="primary", scale=1)
            nav_viva_btn = gr.Button("🎯 VIVA Training Mode", variant="secondary", scale=1)
            nav_book_btn = gr.Button("πŸ“– Book Learning Mode", variant="secondary", scale=1)
            nav_admin_btn = gr.Button("πŸ” Admin Panel", variant="secondary", scale=1)

        # LEARNING MODE COLUMN
        with gr.Column(visible=True, elem_id="learning_col") as learning_col:
            # Search and examples at the top
            with gr.Row():
                query_input = gr.Textbox(
                    label="Ask an Anatomy Question",
                    placeholder="e.g., Show me the Circle of Willis",
                    lines=2
                )
            
            # Examples
            gr.Examples(
                examples=[
                    ["Show me the Circle of Willis"],
                    ["Brachial plexus anatomy"],
                    ["Carpal bones arrangement"],
                    ["Layers of the scalp"],
                    ["Anatomy of the heart chambers"],
                    ["Cranial nerves and their functions"],
                    ["Structure of the kidney nephron"],
                    ["Branches of the abdominal aorta"],
                    ["Rotator cuff muscles"],
                    ["Spinal cord cross section"],
                    ["Femoral triangle anatomy"],
                    ["Larynx cartilages and membranes"],
                    ["Portal venous system"],
                    ["Anatomy of the eyeball"],
                    ["Bronchopulmonary segments"]
                ],
                inputs=query_input
            )
            
            with gr.Row():
                submit_btn = gr.Button("πŸ” Search & Learn", variant="primary", size="lg")
                start_viva_btn = gr.Button("🎯 Start VIVA Training", variant="secondary", size="lg")
            
            error_output = gr.Markdown(label="Status")
            
            # Main content: Key Learning Points (left) and Anatomy Diagram (right)
            with gr.Row():
                with gr.Column(scale=1):
                    info_output = gr.Markdown(label="πŸ“š Key Learning Points")
                
                with gr.Column(scale=1):
                    image_output = gr.Image(label="πŸ–ΌοΈ Anatomy Diagram", type="pil")
        
        # VIVA MODE COLUMN
        with gr.Column(visible=False, elem_id="viva_col") as viva_col:
            viva_status = gr.Markdown("Click 'Start VIVA Training' from Learning Mode after studying a topic!")
            
            # Additional greeting component (initially hidden)
            viva_greeting = gr.Markdown("", visible=False)
            
            with gr.Column(visible=False) as viva_container:
                with gr.Row():
                    with gr.Column(scale=1):
                        viva_image = gr.Image(label="Reference Image", type="pil", interactive=False)
                    
                        with gr.Column(scale=2):
                            current_question_display = gr.Markdown("### Question will appear here")
                            hint_display = gr.Markdown("πŸ’‘ Hint will appear here")
                        
                            # Audio player for question
                            question_audio = gr.Audio(label="πŸ”Š Listen to Question", autoplay=True, interactive=False)
                        
                            student_answer = gr.Textbox(
                                label="Your Answer",
                                placeholder="Type your answer here...",
                                lines=4
                            )
                        
                            submit_answer_btn = gr.Button("Submit Answer", variant="primary")
                        
                            feedback_display = gr.Markdown("Feedback will appear here after you submit your answer")

        # BOOK LEARNING MODE COLUMN
        with gr.Column(visible=False, elem_id="book_col") as book_col:
            # Upload PDF
            pdf_upload = gr.File(label="Upload Anatomy Textbook (PDF)", file_types=[".pdf"], type="binary")
            upload_status = gr.Markdown()
            
            # State to hold extracted images, captions, and text
            book_images_state = gr.State([])
            page_captions_state = gr.State([])
            page_texts_state = gr.State([])
            
            # Dropdown to select a page after processing
            page_dropdown = gr.Dropdown(label="Select Page", choices=[], interactive=False)
            
            # Display selected page image
            selected_page_image = gr.Image(label="Selected Page", type="pil")
            
            # Analysis output
            analysis_output = gr.Markdown(label="Page Analysis")
            
            # Button to start VIVA from this page
            start_viva_book_btn = gr.Button("🎯 Start VIVA Training from this Page", variant="primary", visible=False)
            
            # Process upload
            def handle_book_upload(pdf_bytes):
                extracted_data, status_msg = process_uploaded_book(pdf_bytes)
                if not extracted_data:
                    # No data extracted
                    return [], status_msg, [], [], gr.update(choices=[], interactive=False), None, ""
                
                # Separate images, captions, and text
                img_list = [item[0] for item in extracted_data]
                caps = [item[1] for item in extracted_data]
                texts = [item[2] for item in extracted_data]
                
                # Update dropdown with captions and enable it
                dropdown_update = gr.update(choices=caps, interactive=True)
                return img_list, status_msg, caps, texts, dropdown_update, None, ""
            
            pdf_upload.upload(
                fn=handle_book_upload,
                inputs=[pdf_upload],
                outputs=[book_images_state, upload_status, page_captions_state, page_texts_state, page_dropdown, selected_page_image, analysis_output]
            )
            
            # When a page is selected, show image and analysis
            def show_page_analysis(selected_caption, images, captions, texts):
                if not selected_caption:
                    return None, ""
                # Find index
                try:
                    idx = captions.index(selected_caption)
                except ValueError:
                    return None, ""
                
                img = images[idx]
                text = texts[idx] if idx < len(texts) else ""
                
                analysis = analyze_book_image(img, selected_caption, text)
                
                # Construct a topic string for VIVA
                viva_topic = f"Anatomy of {selected_caption} (from textbook)"
                
                return img, analysis, viva_topic, gr.update(visible=True)
            
            # Hidden state to store current page topic for VIVA
            current_book_topic = gr.State("")
            
            page_dropdown.change(
                fn=show_page_analysis, 
                inputs=[page_dropdown, book_images_state, page_captions_state, page_texts_state], 
                outputs=[selected_page_image, analysis_output, current_book_topic, start_viva_book_btn]
            )
            
            # Start VIVA from Book Mode handler moved to end of file to resolve NameError
        
        # ADMIN PANEL COLUMN
        with gr.Column(visible=False, elem_id="admin_col") as admin_col:
            gr.Markdown("## Admin Panel - Student Database")
            gr.Markdown("Enter the admin password to view registered students.")
            
            # Password input
            with gr.Row():
                admin_password_input = gr.Textbox(
                    label="Admin Password",
                    placeholder="Enter admin password",
                    type="password",
                    scale=2
                )
                admin_login_btn = gr.Button("πŸ”“ Login", variant="primary", scale=1)
            
            admin_status = gr.Markdown("")
            
            # Admin content (hidden until authenticated)
            with gr.Column(visible=False) as admin_content:
                gr.Markdown("### πŸ“Š Registered Students")
                
                admin_stats = gr.Markdown("")
                
                with gr.Row():
                    refresh_btn = gr.Button("πŸ”„ Refresh Data", variant="secondary")
                    logout_btn = gr.Button("πŸšͺ Logout", variant="secondary")
                
                students_table = gr.Dataframe(
                    headers=["ID", "Name", "Medical School", "Year", "Registration Date"],
                    label="Students Database",
                    interactive=False,
                    wrap=True
                )
    
    # Registration Modal Popup (shown on first load)
    with gr.Column(visible=True, elem_id="registration_modal") as registration_modal:
        with gr.Row():
            with gr.Column(scale=1):
                pass  # Spacer
            with gr.Column(scale=2):
                gr.Markdown(
                    """
                    # πŸ‘¨β€βš•οΈ Welcome to AnatomyBot!
                    ### Please enter your information to get started
                    """
                )
                modal_name_input = gr.Textbox(
                    label="Your Name",
                    placeholder="Enter your name",
                    lines=1
                )
                modal_school_input = gr.Textbox(
                    label="Medical School",
                    placeholder="Enter your medical school",
                    lines=1
                )
                modal_year_input = gr.Dropdown(
                    label="Year/Level",
                    choices=["MBBS 1st Year", "MBBS 2nd Year", "MBBS 3rd Year", "MBBS Final Year", "Intern"],
                    value=None
                )
                modal_submit_btn = gr.Button(
                    "βœ… Start Learning",
                    variant="primary",
                    size="lg"
                )
            with gr.Column(scale=1):
                pass  # Spacer

    
    # Event Handlers
    
    # Navigation Logic - change_view function returns exactly 4 values for 4 columns
    def change_view(target_view):
        """
        Handle navigation between views with mutual exclusivity.
        
        Args:
            target_view: The view to display ("learning", "viva", "book", or "admin")
            
        Returns:
            Tuple of 4 gr.update() objects for [learning_col, viva_col, book_col, admin_col]
            Exactly ONE will have visible=True, the rest will have visible=False
        """
        if target_view == "learning":
            return (
                gr.update(visible=True),   # learning_col
                gr.update(visible=False),  # viva_col
                gr.update(visible=False),  # book_col
                gr.update(visible=False)   # admin_col
            )
        elif target_view == "viva":
            return (
                gr.update(visible=False),  # learning_col
                gr.update(visible=True),   # viva_col
                gr.update(visible=False),  # book_col
                gr.update(visible=False)   # admin_col
            )
        elif target_view == "book":
            return (
                gr.update(visible=False),  # learning_col
                gr.update(visible=False),  # viva_col
                gr.update(visible=True),   # book_col
                gr.update(visible=False)   # admin_col
            )
        elif target_view == "admin":
            return (
                gr.update(visible=False),  # learning_col
                gr.update(visible=False),  # viva_col
                gr.update(visible=False),  # book_col
                gr.update(visible=True)    # admin_col
            )
        # Default to learning mode if invalid target
        return (
            gr.update(visible=True),   # learning_col
            gr.update(visible=False),  # viva_col
            gr.update(visible=False),  # book_col
            gr.update(visible=False)   # admin_col
        )

    # Bind Navigation Buttons - Apply change_view logic to all four top buttons
    nav_learning_btn.click(
        fn=lambda: change_view("learning"),
        outputs=[learning_col, viva_col, book_col, admin_col]
    )
    
    nav_viva_btn.click(
        fn=lambda: change_view("viva"),
        outputs=[learning_col, viva_col, book_col, admin_col]
    )
    
    nav_book_btn.click(
        fn=lambda: change_view("book"),
        outputs=[learning_col, viva_col, book_col, admin_col]
    )
    
    nav_admin_btn.click(
        fn=lambda: change_view("admin"),
        outputs=[learning_col, viva_col, book_col, admin_col]
    )

    # Welcome Screen Handler (now for modal)
    def handle_modal_submit(name, medical_school, year):
        """Handle registration modal submission."""
        if not name or not name.strip():
            return gr.update(), gr.update(), ""  # Don't proceed if name is empty
        
        if not medical_school or not medical_school.strip():
            return gr.update(), gr.update(), ""  # Don't proceed if medical school is empty
        
        if not year:
            return gr.update(), gr.update(), ""  # Don't proceed if year is not selected
        
        # Save to database
        save_student(name.strip(), medical_school.strip(), year)
        
        greeting = f"**Welcome, Doctor {name}!** πŸ‘‹ from {medical_school} ({year})"
        return (
            gr.update(visible=False),  # Hide modal
            greeting,                   # Display greeting
            name                        # Store name in state
        )
    
    modal_submit_btn.click(
        fn=handle_modal_submit,
        inputs=[modal_name_input, modal_school_input, modal_year_input],
        outputs=[registration_modal, student_name_display, student_name_state],
        js="""
        (name, school, year) => {
            if (name && name.trim() !== "" && school && school.trim() !== "" && year) {
                const modal = document.getElementById('registration_modal');
                if (modal) {
                    modal.style.display = 'none';
                }
            }
        }
        """
    )
    
    # Event handlers for Learning Mode
    def handle_query(query):
        """Handle learning mode query and store topic/image."""
        img, info, error = process_anatomy_query(query)
        # Reset Start VIVA button
        viva_btn_update = gr.update(value="🎯 Start VIVA Training", interactive=True)
        return img, info, error, query, img, viva_btn_update  # Return topic, image, and button update
    
    submit_btn.click(
        fn=handle_query,
        inputs=[query_input],
        outputs=[image_output, info_output, error_output, current_topic, current_image_state, start_viva_btn]
    )
    
    query_input.submit(
        fn=handle_query,
        inputs=[query_input],
        outputs=[image_output, info_output, error_output, current_topic, current_image_state, start_viva_btn]
    )
    
    # Start VIVA Mode - Directly start with pre-collected name
    start_viva_btn.click(
        fn=lambda: gr.update(value="⏳ Processing VIVA Question...", interactive=False),
        outputs=[start_viva_btn]
    ).then(
        fn=lambda name, topic, image: start_viva_mode(topic, image, name),
        inputs=[student_name_state, current_topic, current_image_state],
        outputs=[
            viva_container, viva_status, viva_image,
            current_question_display, hint_display,
            student_answer, feedback_display, submit_answer_btn,
            viva_questions_state,
            question_audio,  # Output audio
            student_name_state  # Return student name (unchanged)
        ]
    ).then(
        fn=lambda: change_view("viva"),
        outputs=[learning_col, viva_col, book_col, admin_col]
    ).then(
        fn=lambda: gr.update(value="🎯 Start VIVA Training", interactive=True),  # Reset button
        outputs=[start_viva_btn]
    ).then(
        fn=lambda: 0,  # Reset question index
        outputs=[current_question_idx]
    )
    
    # Submit VIVA Answer
    submit_answer_btn.click(
        fn=submit_viva_answer,
        inputs=[student_answer, viva_questions_state, current_question_idx, student_name_state],
        outputs=[
            current_question_display, hint_display, student_answer,
            feedback_display, submit_answer_btn, current_question_idx,
            question_audio  # Output audio for next question
        ]
    )
    
    # Admin Panel Handlers
    def admin_login(password):
        """Verify admin password and show admin content."""
        if password == ADMIN_PASSWORD:
            students = get_all_students()
            total_students = len(students)
            stats = f"**Total Registered Students:** {total_students}"
            return (
                gr.update(value="βœ… Login successful!", visible=True),
                gr.update(visible=True),  # Show admin content
                stats,
                students
            )
        else:
            return (
                gr.update(value="❌ Invalid password. Access denied.", visible=True),
                gr.update(visible=False),  # Hide admin content
                "",
                []
            )
    
    def admin_logout():
        """Logout from admin panel."""
        return (
            gr.update(value=""),  # Clear password
            gr.update(value=""),  # Clear status
            gr.update(visible=False),  # Hide admin content
            "",  # Clear stats
            []  # Clear table
        )
    
    def refresh_students():
        """Refresh the students table."""
        students = get_all_students()
        total_students = len(students)
        stats = f"**Total Registered Students:** {total_students}"
        return stats, students
    
    admin_login_btn.click(
        fn=admin_login,
        inputs=[admin_password_input],
        outputs=[admin_status, admin_content, admin_stats, students_table]
    )
    
    admin_password_input.submit(
        fn=admin_login,
        inputs=[admin_password_input],
        outputs=[admin_status, admin_content, admin_stats, students_table]
    )
    
    logout_btn.click(
        fn=admin_logout,
        outputs=[admin_password_input, admin_status, admin_content, admin_stats, students_table]
    )
    
    refresh_btn.click(
        fn=refresh_students,
        outputs=[admin_stats, students_table]
    )

    # Start VIVA from Book Mode - Use pre-collected name (Moved here to ensure all columns are defined)
    start_viva_book_btn.click(
        fn=lambda name, topic, image: start_viva_with_name(name, topic, image),
        inputs=[student_name_state, current_book_topic, selected_page_image],
        outputs=[
            viva_container, viva_status, viva_image,
            current_question_display, hint_display,
            student_answer, feedback_display, submit_answer_btn,
            viva_questions_state,
            question_audio, viva_greeting, student_name_state
        ]
    ).then(
        fn=lambda: change_view("viva"),
        outputs=[learning_col, viva_col, book_col, admin_col]
    ).then(
        fn=lambda: 0,
        outputs=[current_question_idx]
    )

if __name__ == "__main__":
    # Check if API keys are configured
    if not SERPAPI_KEY or SERPAPI_KEY == "your_serpapi_key_here":
        print("⚠️  WARNING: SERPAPI_KEY not configured in .env file")
    if not HYPERBOLIC_API_KEY or HYPERBOLIC_API_KEY == "your_hyperbolic_api_key_here":
        print("⚠️  WARNING: HYPERBOLIC_API_KEY not configured in .env file")
    
    # Use environment variable for port, default to 7860 for HF Spaces
    port = int(os.getenv("GRADIO_SERVER_PORT", "7860"))
    demo.launch(server_name="0.0.0.0", server_port=port)

# Rebuild trigger