File size: 55,100 Bytes
a99d271
 
 
 
 
 
 
 
 
 
 
faebaa0
 
a99d271
 
 
 
e1f3bc4
a99d271
 
 
 
 
e1f3bc4
a99d271
 
faebaa0
a99d271
65c037b
faebaa0
a99d271
 
 
a8fcdcf
faebaa0
 
 
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8fcdcf
faebaa0
 
 
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10dec08
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10dec08
 
a99d271
10dec08
a99d271
 
 
10dec08
 
 
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10dec08
a99d271
10dec08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a99d271
10dec08
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8fcdcf
 
 
 
 
 
 
 
2850f05
a8fcdcf
 
 
 
 
a99d271
 
 
 
 
 
 
 
 
a8fcdcf
a99d271
 
a8fcdcf
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faebaa0
 
 
 
 
a99d271
 
 
 
 
 
 
faebaa0
 
 
 
 
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faebaa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faebaa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2850f05
a99d271
2850f05
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
a8fcdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10dec08
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
faebaa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a99d271
 
 
 
 
 
 
faebaa0
a99d271
 
 
 
 
 
 
 
a8fcdcf
a99d271
 
 
 
 
 
faebaa0
 
 
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8fcdcf
a99d271
faebaa0
a99d271
 
 
 
 
 
 
 
 
 
 
 
a8fcdcf
a99d271
 
 
 
 
 
faebaa0
 
 
a99d271
 
 
faebaa0
a99d271
faebaa0
a99d271
 
 
a8fcdcf
a99d271
faebaa0
a99d271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import tempfile
import os
import requests
import json
import re
from bs4 import BeautifulSoup
from datetime import datetime
import urllib.parse
from pathlib import Path
from typing import List, Dict, Optional, Any, Tuple
import numpy as np
import time


# Configuration
SPACE_NAME = 'Language Learning Partner'
SPACE_DESCRIPTION = 'AI Italian conversation partner'

# Default configuration values
DEFAULT_CONFIG = {
    'name': SPACE_NAME,
    'description': SPACE_DESCRIPTION,
    'system_prompt': "You are Domenico from Sicily, a Juventus football fan, native Italian speaker serving as a conversational partner for university students in an Italian 101 class. Students will interact and converse with you in Italian, and you must respond EXCLUSIVELY IN ITALIAN without providing English translations, using vocabulary appropriate for beginner-level Italian 101 students. Focus your responses on topics suitable for beginners such as sports, daily life, routines, food, numbers, and hobbies. When students make errors, model the correct forms naturally in your response without explicitly pointing out mistakes, allowing them to learn through exposure to proper usage. Recognize when students demonstrate more advanced abilities and adjust your language complexity accordingly, while ensuring your Italian remains error-free. Keep all responses between 5-50 words, making sure sentences are grammatically complete. Limit all verb conjugations to the present tense only, avoiding all other verb forms and tenses. Address students using the informal second-person singular 'tu' form.",
    'temperature': 0.5,
    'max_tokens': 250,
    'model': 'google/gemma-3-27b-it',
    'api_key_var': 'API_KEY',
    'theme': 'Default',
    'grounding_urls': [],
    'enable_dynamic_urls': True,
    'enable_file_upload': True,
    'examples': ['Ciao! Come stai oggi?', 'Mi piace giocare a calcio. E tu?', 'Cosa mangi di solito a colazione?', 'A che ora ti svegli la mattina?', 'Qual Γ¨ il tuo sport preferito?'],
    'language': 'Italian',
    'enable_tts': True,
    'tts_model': 'microsoft/speecht5_tts',
    'tts_voice': 'default',
    'locked': False
}

# Available themes with proper instantiation
AVAILABLE_THEMES = {
    "Default": gr.themes.Default(),
    "Soft": gr.themes.Soft(),
    "Glass": gr.themes.Glass(),
    "Monochrome": gr.themes.Monochrome(),
    "Base": gr.themes.Base()
}


class ConfigurationManager:
    """Manage configuration with validation and persistence"""
    
    def __init__(self):
        self.config_path = "config.json"
        self.backup_dir = "config_backups"
        self._config = None
    
    def load(self) -> Dict[str, Any]:
        """Load configuration from file with fallback to defaults"""
        try:
            with open(self.config_path, 'r') as f:
                self._config = json.load(f)
                print("βœ… Loaded configuration from config.json")
                return self._config
        except FileNotFoundError:
            print("ℹ️ No config.json found, using default configuration")
            self._config = DEFAULT_CONFIG.copy()
            self.save(self._config)
            return self._config
        except Exception as e:
            print(f"⚠️ Error loading config.json: {e}, using defaults")
            self._config = DEFAULT_CONFIG.copy()
            return self._config
    
    def save(self, config: Dict[str, Any]) -> bool:
        """Save configuration with automatic backup"""
        try:
            # Create backup if config exists
            if os.path.exists(self.config_path):
                self._create_backup()
            
            # Save new configuration
            with open(self.config_path, 'w') as f:
                json.dump(config, f, indent=2)
            
            self._config = config
            return True
        except Exception as e:
            print(f"❌ Error saving configuration: {e}")
            return False
    
    def _create_backup(self):
        """Create timestamped backup"""
        try:
            os.makedirs(self.backup_dir, exist_ok=True)
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            backup_path = os.path.join(self.backup_dir, f"config_{timestamp}.json")
            
            with open(self.config_path, 'r') as source:
                config_data = json.load(source)
                with open(backup_path, 'w') as backup:
                    json.dump(config_data, backup, indent=2)
            
            self._cleanup_old_backups()
        except Exception as e:
            print(f"⚠️ Error creating backup: {e}")
    
    def _cleanup_old_backups(self, keep=10):
        """Keep only the most recent backups"""
        try:
            backups = sorted([
                f for f in os.listdir(self.backup_dir)
                if f.startswith('config_') and f.endswith('.json')
            ])
            
            if len(backups) > keep:
                for old_backup in backups[:-keep]:
                    os.remove(os.path.join(self.backup_dir, old_backup))
        except Exception as e:
            print(f"⚠️ Error cleaning up backups: {e}")
    
    def get(self, key: str, default: Any = None) -> Any:
        """Get configuration value"""
        if self._config is None:
            self.load()
        return self._config.get(key, default)


# Initialize configuration manager
config_manager = ConfigurationManager()
config = config_manager.load()

# Load configuration values
SPACE_NAME = config.get('name', DEFAULT_CONFIG['name'])
SPACE_DESCRIPTION = config.get('description', DEFAULT_CONFIG['description'])
SYSTEM_PROMPT = config.get('system_prompt', DEFAULT_CONFIG['system_prompt'])
temperature = config.get('temperature', DEFAULT_CONFIG['temperature'])
max_tokens = config.get('max_tokens', DEFAULT_CONFIG['max_tokens'])
MODEL = config.get('model', DEFAULT_CONFIG['model'])
THEME = config.get('theme', DEFAULT_CONFIG['theme'])
GROUNDING_URLS = config.get('grounding_urls', DEFAULT_CONFIG['grounding_urls'])
ENABLE_DYNAMIC_URLS = config.get('enable_dynamic_urls', DEFAULT_CONFIG['enable_dynamic_urls'])
ENABLE_FILE_UPLOAD = config.get('enable_file_upload', DEFAULT_CONFIG.get('enable_file_upload', True))
LANGUAGE = config.get('language', DEFAULT_CONFIG.get('language', 'English'))
ENABLE_TTS = config.get('enable_tts', DEFAULT_CONFIG.get('enable_tts', False))
TTS_MODEL = config.get('tts_model', DEFAULT_CONFIG.get('tts_model', 'microsoft/speecht5_tts'))
TTS_VOICE = config.get('tts_voice', DEFAULT_CONFIG.get('tts_voice', 'default'))

# Environment variables
ACCESS_CODE = os.environ.get("ACCESS_CODE")
API_KEY_VAR = config.get('api_key_var', DEFAULT_CONFIG['api_key_var'])
API_KEY = os.environ.get(API_KEY_VAR, "").strip() or None
HF_TOKEN = os.environ.get('HF_TOKEN', '')
SPACE_ID = os.environ.get('SPACE_ID', '')


# Utility functions
def validate_api_key() -> bool:
    """Validate API key configuration"""
    if not API_KEY:
        print(f"⚠️  API KEY CONFIGURATION ERROR:")
        print(f"   Variable name: {API_KEY_VAR}")
        print(f"   Status: Not set or empty")
        print(f"   Action needed: Set '{API_KEY_VAR}' in HuggingFace Space secrets")
        return False
    elif not API_KEY.startswith('sk-or-'):
        print(f"⚠️  API KEY FORMAT WARNING:")
        print(f"   Variable name: {API_KEY_VAR}")
        print(f"   Note: OpenRouter keys should start with 'sk-or-'")
        return True
    else:
        print(f"βœ… API Key configured successfully")
        return True


def validate_url_domain(url: str) -> bool:
    """Validate URL domain"""
    try:
        from urllib.parse import urlparse
        parsed = urlparse(url)
        return bool(parsed.netloc and parsed.scheme in ['http', 'https'])
    except:
        return False


def fetch_url_content(url: str, max_length: int = 3000) -> str:
    """Fetch and convert URL content to text"""
    try:
        if not validate_url_domain(url):
            return f"❌ Invalid URL format: {url}"
        
        headers = {
            'User-Agent': 'Mozilla/5.0 (compatible; HuggingFace-Space/1.0)'
        }
        
        response = requests.get(url, headers=headers, timeout=5)
        response.raise_for_status()
        
        content_type = response.headers.get('content-type', '').lower()
        
        if 'text/html' in content_type:
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # Remove script and style elements
            for script in soup(["script", "style"]):
                script.extract()
            
            # Get text content
            text = soup.get_text(separator=' ', strip=True)
            
            # Clean up whitespace
            text = ' '.join(text.split())
            
            # Limit content length
            if len(text) > max_length:
                text = text[:max_length] + "... [truncated]"
            
            return f"πŸ“„ **Content from:** {url}\n\n{text}\n"
        
        elif any(ct in content_type for ct in ['text/plain', 'application/json']):
            text = response.text
            if len(text) > max_length:
                text = text[:max_length] + "... [truncated]"
            return f"πŸ“„ **Content from:** {url}\n\n{text}\n"
        
        else:
            return f"⚠️ Unsupported content type at {url}: {content_type}"
            
    except requests.exceptions.Timeout:
        return f"⏱️ Timeout accessing {url}"
    except requests.exceptions.RequestException as e:
        return f"❌ Error accessing {url}: {str(e)}"
    except Exception as e:
        return f"❌ Unexpected error with {url}: {str(e)}"


def extract_urls_from_text(text: str) -> List[str]:
    """Extract URLs from message text"""
    url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+(?:\.[^\s<>"{}|\\^`\[\]])*'
    urls = re.findall(url_pattern, text)
    return [url.rstrip('.,;:)?!') for url in urls]


def process_file_upload(file_path: str) -> str:
    """Process uploaded file with Gradio best practices"""
    if not file_path or not os.path.exists(file_path):
        return "❌ File not found"
    
    try:
        file_size = os.path.getsize(file_path)
        file_name = os.path.basename(file_path)
        _, ext = os.path.splitext(file_path.lower())
        
        # Text file extensions
        text_extensions = {
            '.txt', '.md', '.markdown', '.rst',
            '.py', '.js', '.jsx', '.ts', '.tsx', '.json', '.yaml', '.yml',
            '.html', '.htm', '.xml', '.css', '.scss',
            '.java', '.c', '.cpp', '.h', '.cs', '.go', '.rs',
            '.sh', '.bash', '.log', '.csv', '.sql'
        }
        
        max_chars = 5000  # Define max_chars limit for file reading
        
        if ext in text_extensions:
            with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                content = f.read(max_chars)
                if len(content) == max_chars:
                    content += "\n... [truncated]"
                return f"πŸ“„ **{file_name}** ({file_size:,} bytes)\n```{ext[1:]}\n{content}\n```"
        
        # Special file types
        elif ext == '.pdf':
            return f"πŸ“‘ **{file_name}** (PDF, {file_size:,} bytes)\n⚠️ PDF support requires PyPDF2"
        elif ext in {'.jpg', '.jpeg', '.png', '.gif', '.webp'}:
            return f"πŸ–ΌοΈ **{file_name}** (Image, {file_size:,} bytes)"
        elif ext in {'.xlsx', '.xls'}:
            return f"πŸ“Š **{file_name}** (Spreadsheet, {file_size:,} bytes)"
        elif ext in {'.zip', '.tar', '.gz', '.rar'}:
            return f"πŸ—œοΈ **{file_name}** (Archive, {file_size:,} bytes)"
        else:
            return f"πŸ“Ž **{file_name}** ({ext or 'no extension'}, {file_size:,} bytes)"
            
    except Exception as e:
        return f"❌ Error processing file: {str(e)}"


# URL content cache
_url_content_cache = {}


def get_grounding_context() -> str:
    """Get grounding context from configured URLs with caching"""
    urls = GROUNDING_URLS
    if isinstance(urls, str):
        try:
            urls = json.loads(urls)
        except:
            return ""
    
    if not urls:
        return ""
    
    context_parts = []
    
    # Process primary sources (first 2 URLs with 8000 char limit)
    primary_urls = urls[:2]
    if primary_urls:
        context_parts.append("πŸ“š **PRIMARY SOURCES:**\n")
        for i, url in enumerate(primary_urls, 1):
            if url in _url_content_cache:
                content = _url_content_cache[url]
            else:
                content = fetch_url_content(url, max_length=8000)
                _url_content_cache[url] = content
            
            if not content.startswith("❌") and not content.startswith("⏱️"):
                context_parts.append(f"\n**Primary Source {i} - {url}:**\n{content}")
    
    # Process secondary sources (URLs 3+ with 2500 char limit)
    secondary_urls = urls[2:]
    if secondary_urls:
        context_parts.append("\n\nπŸ“Ž **SECONDARY SOURCES:**\n")
        for i, url in enumerate(secondary_urls, 1):
            if url in _url_content_cache:
                content = _url_content_cache[url]
            else:
                content = fetch_url_content(url, max_length=2500)
                _url_content_cache[url] = content
            
            if not content.startswith("❌") and not content.startswith("⏱️"):
                context_parts.append(f"\n**Secondary Source {i} - {url}:**\n{content}")
    
    if len(context_parts) > 0:
        return "\n".join(context_parts)
    return ""


def export_conversation_to_markdown(history: List[Dict[str, str]]) -> str:
    """Export conversation history to markdown"""
    if not history:
        return "No conversation to export."
    
    markdown_content = f"""# Conversation Export
Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
Space: {SPACE_NAME}
Model: {MODEL}

---

"""
    
    message_count = 0
    for message in history:
        if isinstance(message, dict):
            role = message.get('role', 'unknown')
            content = message.get('content', '')
            
            if role == 'user':
                message_count += 1
                markdown_content += f"## User Message {message_count}\n\n{content}\n\n"
            elif role == 'assistant':
                markdown_content += f"## Assistant Response {message_count}\n\n{content}\n\n---\n\n"
    
    return markdown_content


def generate_response(message: str, history: List[Dict[str, str]], files: Optional[List] = None) -> str:
    """Generate response using OpenRouter API with file support"""
    
    # API key validation
    if not API_KEY:
        return f"""πŸ”‘ **API Key Required**

Please configure your OpenRouter API key:
1. Go to Settings (βš™οΈ) in your HuggingFace Space
2. Click 'Variables and secrets'
3. Add secret: **{API_KEY_VAR}**
4. Value: Your OpenRouter API key (starts with `sk-or-`)

Get your API key at: https://openrouter.ai/keys"""
    
    # Process files if provided
    file_context = ""
    file_notification = ""
    
    if files:
        file_contents = []
        file_names = []
        
        for file_info in files:
            if isinstance(file_info, dict):
                file_path = file_info.get('path', file_info.get('name', ''))
            else:
                file_path = str(file_info)
            
            if file_path and os.path.exists(file_path):
                try:
                    content = process_file_upload(file_path)
                    file_contents.append(content)
                    file_names.append(os.path.basename(file_path))
                    print(f"πŸ“„ Processed file: {os.path.basename(file_path)}")
                except Exception as e:
                    print(f"❌ Error processing file: {e}")
        
        if file_contents:
            file_context = "\n\n[UPLOADED FILES]\n" + "\n\n".join(file_contents) + "\n"
            file_notification = f"\n\n[Note: Uploaded files: {', '.join(file_names)}]"
    
    # Get grounding context
    grounding_context = get_grounding_context()
    
    # Check for dynamic URLs in message
    if ENABLE_DYNAMIC_URLS:
        urls_in_message = extract_urls_from_text(message)
        if urls_in_message:
            print(f"πŸ”— Found {len(urls_in_message)} URLs in message")
            dynamic_context = "\nπŸ“Ž **Dynamic Context:**\n"
            for url in urls_in_message[:3]:  # Limit to 3 URLs
                content = fetch_url_content(url)
                if not content.startswith("❌"):
                    dynamic_context += f"\n{content}"
            grounding_context += dynamic_context
    
    # Build messages with grounding context and file context in system prompt
    system_content = SYSTEM_PROMPT
    
    # Add language instruction if not English
    if LANGUAGE != 'English':
        system_content += f"\n\nIMPORTANT: You must respond EXCLUSIVELY in {LANGUAGE}. All your responses should be written entirely in {LANGUAGE}, even when user input is in a different language, particularly English."
    
    if grounding_context:
        system_content += "\n\nIMPORTANT: When providing information from the reference sources below, please cite the specific URL(s) where the information can be found. Format citations as plain URLs without brackets, or use markdown link format like [text](url). Never use hard brackets like 【url】 as they break the links."
        system_content = f"{system_content}\n\n{grounding_context}"
    if file_context:
        system_content = f"{system_content}\n\n{file_context}"
    
    messages = [{"role": "system", "content": system_content}]
    
    # Add conversation history
    for msg in history:
        if isinstance(msg, dict) and 'role' in msg and 'content' in msg:
            messages.append({
                "role": msg['role'],
                "content": msg['content']
            })
    
    # Add current message
    messages.append({
        "role": "user",
        "content": message
    })
    
    # Make API request
    try:
        # Make API request
        headers = {
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
            "HTTP-Referer": f"https://huggingface.co/spaces/{SPACE_ID}" if SPACE_ID else "https://huggingface.co",
            "X-Title": SPACE_NAME
        }
        
        data = {
            "model": MODEL,
            "messages": messages,
            "temperature": temperature,
            "max_tokens": max_tokens,
            "stream": False
        }
        
        response = requests.post(
            "https://openrouter.ai/api/v1/chat/completions",
            headers=headers,
            json=data,
            timeout=30
        )
        
        if response.status_code == 200:
            try:
                result = response.json()
                ai_response = result['choices'][0]['message']['content']
            except (json.JSONDecodeError, KeyError) as e:
                return f"❌ Error parsing API response: {str(e)}"
            
            # Add file notification if files were uploaded
            if file_notification:
                ai_response += file_notification
            
            return ai_response
        else:
            try:
                error_data = response.json()
                error_message = error_data.get('error', {}).get('message', 'Unknown error')
            except:
                error_message = response.text if response.text else 'Unknown error'
            return f"❌ API Error ({response.status_code}): {error_message}"
            
    except requests.exceptions.Timeout:
        return "⏰ Request timeout (30s limit). Try a shorter message or different model."
    except requests.exceptions.ConnectionError:
        return "🌐 Connection error. Check your internet connection and try again."
    except Exception as e:
        return f"❌ Error: {str(e)}"


# Chat history for export
chat_history_store = []


def verify_hf_token_access() -> Tuple[bool, str]:
    """Verify HuggingFace token and access"""
    if not HF_TOKEN:
        return False, "No HF_TOKEN found"
    
    if not SPACE_ID:
        return False, "No SPACE_ID found - running locally?"
    
    try:
        headers = {"Authorization": f"Bearer {HF_TOKEN}"}
        response = requests.get(
            f"https://huggingface.co/api/spaces/{SPACE_ID}",
            headers=headers,
            timeout=5
        )
        if response.status_code == 200:
            return True, f"HF Token valid for {SPACE_ID}"
        else:
            return False, f"HF Token invalid or no access to {SPACE_ID}"
    except Exception as e:
        return False, f"Error verifying HF token: {str(e)}"


def generate_tts(text: str, max_retries: int = 2) -> Tuple[Optional[Tuple[int, np.ndarray]], str]:
    """Generate TTS audio using HuggingFace Inference API"""
    if not ENABLE_TTS or not text:
        return None, "TTS disabled or no text provided"
    
    hf_token = os.getenv("HF_TOKEN")
    if not hf_token:
        return None, "⚠️ HF_TOKEN not configured for TTS"
    
    # Limit text length for TTS
    text = text[:500]
    
    # Select speaker embedding based on voice preference
    speaker_embeddings = None
    if TTS_MODEL == "microsoft/speecht5_tts":
        # For SpeechT5, we need speaker embeddings
        # Using a predefined speaker ID (7306 is a clear female voice)
        speaker_id = {
            "default": 7306,
            "female": 7306,
            "male": 5105,
            "neutral": 6678
        }.get(TTS_VOICE, 7306)
        
        # Note: In production, you'd load actual embeddings from the dataset
        # For now, we'll let the API handle default voice
        speaker_embeddings = {"speaker_id": speaker_id}
    
    for attempt in range(max_retries):
        try:
            headers = {"Authorization": f"Bearer {hf_token}"}
            api_url = f"https://api-inference.huggingface.co/models/{TTS_MODEL}"
            
            # Prepare payload
            payload = {"inputs": text}
            if speaker_embeddings and TTS_MODEL == "microsoft/speecht5_tts":
                # For models that support speaker embeddings
                payload["parameters"] = speaker_embeddings
            
            response = requests.post(
                api_url,
                headers=headers,
                json=payload,
                timeout=20
            )
            
            if response.status_code == 200:
                # Convert audio bytes to numpy array
                audio_array = np.frombuffer(response.content, dtype=np.int16)
                # Most TTS models output at 16kHz
                sample_rate = 16000
                return (sample_rate, audio_array), "βœ… Audio generated successfully"
            
            elif response.status_code == 503:
                # Model is loading
                if attempt < max_retries - 1:
                    time.sleep(20)  # Wait for model to load
                    continue
                else:
                    return None, "⏳ Model is loading, please try again in a moment"
            
            else:
                try:
                    error_msg = response.json().get('error', 'Unknown error')
                except:
                    error_msg = response.text if response.text else 'Unknown error'
                return None, f"❌ API Error ({response.status_code}): {error_msg}"
                
        except requests.exceptions.Timeout:
            return None, "⏰ TTS request timeout"
        except Exception as e:
            if attempt == max_retries - 1:
                return None, f"❌ TTS Error: {str(e)}"
            time.sleep(2)
    
    return None, "❌ Max retries exceeded"


# Create main interface with clean tab structure
def create_interface():
    """Create the Gradio interface with clean tab structure"""
    
    # Get theme
    theme = AVAILABLE_THEMES.get(THEME, gr.themes.Default())
    
    # Validate API key on startup
    API_KEY_VALID = validate_api_key()
    
    # Check HuggingFace access
    HF_ACCESS_VALID, HF_ACCESS_MESSAGE = verify_hf_token_access()
    
    # Access control check
    has_access = ACCESS_CODE is None  # No access code required
    
    with gr.Blocks(title=SPACE_NAME, theme=theme) as demo:
        # State for access control
        access_granted = gr.State(has_access)
        
        # Header - always visible
        gr.Markdown(f"# {SPACE_NAME}")
        gr.Markdown(SPACE_DESCRIPTION)
        
        # Access control panel (visible when access not granted)
        with gr.Column(visible=(not has_access)) as access_panel:
            gr.Markdown("### πŸ” Access Required")
            gr.Markdown("Please enter the access code:")
            
            with gr.Row():
                access_input = gr.Textbox(
                    label="Access Code",
                    placeholder="Enter access code...",
                    type="password",
                    scale=3
                )
                access_btn = gr.Button("Submit", variant="primary", scale=1)
            
            access_status = gr.Markdown()
        
        # Main interface (visible when access granted)
        with gr.Column(visible=has_access) as main_panel:
            with gr.Tabs() as tabs:
                # Chat Tab
                with gr.Tab("πŸ’¬ Chat"):
                    # Get examples
                    examples = config.get('examples', [])
                    if isinstance(examples, str):
                        try:
                            examples = json.loads(examples)
                        except:
                            examples = []
                    
                    # State to hold uploaded files
                    uploaded_files = gr.State([])
                    
                    # Create chat interface
                    chatbot = gr.Chatbot(type="messages", height=400)
                    msg = gr.Textbox(label="Message", placeholder="Type your message here...", lines=2)
                    
                    with gr.Row():
                        submit_btn = gr.Button("Send", variant="primary")
                        clear_btn = gr.Button("Clear")
                    
                    # Export functionality
                    with gr.Row():
                        export_btn = gr.DownloadButton(
                            "πŸ“₯ Export Conversation",
                            variant="secondary",
                            size="sm"
                        )
                    
                    # Export handler
                    def prepare_export():
                        if not chat_history_store:
                            return None
                        
                        content = export_conversation_to_markdown(chat_history_store)
                        
                        # Create filename
                        space_name_safe = re.sub(r'[^a-zA-Z0-9]+', '_', SPACE_NAME).lower()
                        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                        filename = f"{space_name_safe}_conversation_{timestamp}.md"
                        
                        # Save to temp file
                        temp_path = Path(tempfile.gettempdir()) / filename
                        temp_path.write_text(content, encoding='utf-8')
                        
                        return str(temp_path)
                    
                    export_btn.click(
                        prepare_export,
                        outputs=[export_btn]
                    )
                    
                    # TTS functionality
                    if ENABLE_TTS:
                        with gr.Row():
                            tts_btn = gr.Button("πŸ”Š Read Last Response", variant="secondary", size="sm")
                            audio_output = gr.Audio(label="TTS Output", visible=False, autoplay=True)
                        
                        tts_status = gr.Markdown("", visible=False)
                        last_assistant_message = gr.State("")
                        
                        def update_last_message(chat_history):
                            """Extract the last assistant message from chat history"""
                            if not chat_history:
                                return ""
                            
                            # Find the last assistant message
                            for message in reversed(chat_history):
                                if isinstance(message, dict) and message.get('role') == 'assistant':
                                    return message.get('content', '')
                            return ""
                        
                        def handle_tts_click(last_message):
                            """Handle TTS button click"""
                            if not last_message:
                                return None, gr.update(visible=False), gr.update(value="⚠️ No message to read", visible=True)
                            
                            audio_data, status_msg = generate_tts(last_message)
                            
                            if audio_data:
                                return (
                                    audio_data,
                                    gr.update(visible=True),
                                    gr.update(value=status_msg, visible=True)
                                )
                            else:
                                return (
                                    None,
                                    gr.update(visible=False),
                                    gr.update(value=status_msg, visible=True)
                                )
                        
                        # Update last message whenever chat updates
                        chatbot.change(
                            update_last_message,
                            inputs=[chatbot],
                            outputs=[last_assistant_message]
                        )
                        
                        # Handle TTS button click
                        tts_btn.click(
                            handle_tts_click,
                            inputs=[last_assistant_message],
                            outputs=[audio_output, audio_output, tts_status]
                        )
                    
                    # Examples section
                    if examples:
                        gr.Examples(examples=examples, inputs=msg)
                    
                    # Chat functionality
                    def respond(message, chat_history, files_state, is_granted):
                        if not is_granted:
                            return chat_history, "", is_granted
                        
                        if not message:
                            return chat_history, "", is_granted
                        
                        # Format history for the generate_response function
                        formatted_history = []
                        for h in chat_history:
                            if isinstance(h, dict):
                                formatted_history.append(h)
                        
                        # Get response
                        response = generate_response(message, formatted_history, files_state)
                        
                        # Update chat history
                        chat_history = chat_history + [
                            {"role": "user", "content": message},
                            {"role": "assistant", "content": response}
                        ]
                        
                        # Update stored history for export
                        global chat_history_store
                        chat_history_store = chat_history
                        
                        return chat_history, "", is_granted
                    
                    # Wire up the interface
                    msg.submit(respond, [msg, chatbot, uploaded_files, access_granted], [chatbot, msg, access_granted])
                    submit_btn.click(respond, [msg, chatbot, uploaded_files, access_granted], [chatbot, msg, access_granted])
                    clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg])
                    
                    # File upload accordion
                    if ENABLE_FILE_UPLOAD:
                        with gr.Accordion("πŸ“Ž Upload Files", open=False):
                            file_upload = gr.File(
                                label="Upload Files",
                                file_types=None,
                                file_count="multiple",
                                visible=True,
                                interactive=True
                            )
                            clear_files_btn = gr.Button("Clear Files", size="sm", variant="secondary")
                            uploaded_files_display = gr.Markdown("", visible=False)
                            
                            def handle_file_upload(files):
                                if not files:
                                    return [], "", gr.update(visible=False)
                                
                                file_names = []
                                for file_info in files:
                                    if isinstance(file_info, dict):
                                        file_path = file_info.get('path', file_info.get('name', ''))
                                    else:
                                        file_path = str(file_info)
                                    
                                    if file_path and os.path.exists(file_path):
                                        file_names.append(os.path.basename(file_path))
                                
                                if file_names:
                                    display_text = f"πŸ“Ž **Uploaded files:** {', '.join(file_names)}"
                                    return files, display_text, gr.update(visible=True)
                                return [], "", gr.update(visible=False)
                            
                            def clear_files():
                                return None, [], "", gr.update(visible=False)
                            
                            file_upload.change(
                                handle_file_upload,
                                inputs=[file_upload],
                                outputs=[uploaded_files, uploaded_files_display, uploaded_files_display]
                            )
                            
                            clear_files_btn.click(
                                clear_files,
                                outputs=[file_upload, uploaded_files, uploaded_files_display, uploaded_files_display]
                            )
                    
                    # Configuration accordion
                    with gr.Accordion("ℹ️ Configuration", open=False):
                        gr.JSON(
                            value=config,
                            label="config.json",
                            show_label=True
                        )
                
                # Configuration Tab
                with gr.Tab("βš™οΈ Configuration"):
                    gr.Markdown("## Configuration Management")
                    
                    # State for config tab authentication
                    config_authenticated = gr.State(False)
                    
                    # Authentication panel
                    with gr.Column(visible=True) as config_auth_panel:
                        gr.Markdown("### πŸ” Authentication Required")
                        gr.Markdown("Enter your HF_TOKEN to access configuration settings:")
                        
                        with gr.Row():
                            config_password = gr.Textbox(
                                label="HF Token",
                                placeholder="Enter your HF_TOKEN...",
                                type="password",
                                scale=3
                            )
                            config_auth_btn = gr.Button("Authenticate", variant="primary", scale=1)
                        
                        config_auth_status = gr.Markdown()
                    
                    # Configuration panel (hidden until authenticated)
                    with gr.Column(visible=False) as config_panel:
                        # Show authentication status
                        if HF_ACCESS_VALID:
                            gr.Markdown(f"βœ… {HF_ACCESS_MESSAGE}")
                            gr.Markdown("Configuration changes will be saved to the HuggingFace repository.")
                        else:
                            gr.Markdown(f"ℹ️ {HF_ACCESS_MESSAGE}")
                            gr.Markdown("Set HF_TOKEN in Space secrets to enable auto-save.")
                        
                        # Configuration editor
                        gr.Markdown("### βš™οΈ Configuration Editor")
                        
                        # Show lock status if locked
                        if config.get('locked', False):
                            gr.Markdown("⚠️ **Note:** Configuration is locked.")
                        
                        # Basic settings
                        with gr.Column():
                            edit_name = gr.Textbox(
                            label="Space Name",
                            value=config.get('name', ''),
                            max_lines=1
                        )
                        edit_model = gr.Dropdown(
                            label="Model",
                            choices=[
                                # Google models
                                "google/gemini-2.0-flash-001",
                                "google/gemma-3-27b-it",
                                # Anthropic models
                                "anthropic/claude-3.5-sonnet",
                                "anthropic/claude-3.5-haiku",
                                # OpenAI models
                                "openai/gpt-4o-mini",
                                "openai/gpt-4o-mini-search-preview",
                                "openai/gpt-oss-120b",
                                # MistralAI models
                                "mistralai/mistral-medium-3",
                                # DeepSeek models
                                "deepseek/deepseek-r1-distill-qwen-32b",
                                # NVIDIA models
                                "nvidia/llama-3.1-nemotron-70b-instruct",
                                # Qwen models
                                "qwen/qwen3-30b-a3b-instruct-2507"
                            ],
                            value=config.get('model', ''),
                            allow_custom_value=True
                        )
                        
                        edit_language = gr.Dropdown(
                            label="Language",
                            choices=[
                                "Arabic",
                                "Bengali",
                                "English",
                                "French",
                                "German",
                                "Hindi",
                                "Italian",
                                "Japanese",
                                "Korean",
                                "Mandarin",
                                "Portuguese",
                                "Russian",
                                "Spanish",
                                "Turkish"
                            ],
                            value=config.get('language', 'English')
                        )
                        
                        edit_description = gr.Textbox(
                            label="Description",
                            value=config.get('description', ''),
                            max_lines=2
                        )
                        
                        edit_system_prompt = gr.Textbox(
                            label="System Prompt",
                            value=config.get('system_prompt', ''),
                            lines=5
                        )
                        
                        with gr.Row():
                            edit_temperature = gr.Slider(
                                label="Temperature",
                                minimum=0,
                                maximum=2,
                                value=config.get('temperature', 0.7),
                                step=0.1
                            )
                            edit_max_tokens = gr.Slider(
                                label="Max Tokens",
                                minimum=50,
                                maximum=4096,
                                value=config.get('max_tokens', 750),
                                step=50
                            )
                        
                        edit_examples = gr.Textbox(
                            label="Example Prompts (one per line)",
                            value='\n'.join(config.get('examples', [])),
                            lines=3
                        )
                        
                        # URL Grounding
                        gr.Markdown("### URL Grounding")
                        edit_grounding_urls = gr.Textbox(
                            label="Grounding URLs (one per line)",
                            placeholder="https://example.com/docs\nhttps://example.com/api",
                            value='\n'.join(config.get('grounding_urls', [])),
                            lines=5,
                            info="First 2 URLs: Primary sources (8000 chars). URLs 3+: Secondary sources (2500 chars)."
                        )
                        
                        with gr.Row():
                            edit_enable_dynamic_urls = gr.Checkbox(
                                label="Enable Dynamic URL Extraction",
                                value=config.get('enable_dynamic_urls', True),
                                info="Extract and fetch URLs from user messages"
                            )
                            edit_enable_file_upload = gr.Checkbox(
                                label="Enable File Upload",
                                value=config.get('enable_file_upload', True),
                                info="Allow users to upload files for context"
                            )
                        
                        # TTS Configuration
                        gr.Markdown("### πŸ”Š Text-to-Speech")
                        with gr.Row():
                            edit_enable_tts = gr.Checkbox(
                                label="Enable TTS",
                                value=config.get('enable_tts', False),
                                info="Enable text-to-speech for assistant responses"
                            )
                            edit_tts_model = gr.Dropdown(
                                label="TTS Model",
                                choices=[
                                    "microsoft/speecht5_tts",
                                    "facebook/mms-tts-eng",
                                    "suno/bark",
                                    "parler-tts/parler-tts-mini-v1"
                                ],
                                value=config.get('tts_model', 'microsoft/speecht5_tts'),
                                allow_custom_value=True
                            )
                            edit_tts_voice = gr.Dropdown(
                                label="Voice",
                                choices=["default", "female", "male", "neutral"],
                                value=config.get('tts_voice', 'default')
                            )
                        
                        # Configuration actions
                        with gr.Row():
                            save_btn = gr.Button("πŸ’Ύ Save Configuration", variant="primary")
                            reset_btn = gr.Button("↩️ Reset to Defaults", variant="secondary")
                        
                        config_status = gr.Markdown()
                        
                        def save_configuration(name, description, system_prompt, model, language, temp, tokens, examples, grounding_urls, enable_dynamic_urls, enable_file_upload, enable_tts, tts_model, tts_voice):
                            """Save updated configuration"""
                            try:
                                updated_config = config.copy()
                                updated_config.update({
                                    'name': name,
                                    'description': description,
                                    'system_prompt': system_prompt,
                                    'model': model,
                                    'language': language,
                                    'temperature': temp,
                                    'max_tokens': int(tokens),
                                    'examples': [ex.strip() for ex in examples.split('\n') if ex.strip()],
                                    'grounding_urls': [url.strip() for url in grounding_urls.split('\n') if url.strip()],
                                    'enable_dynamic_urls': enable_dynamic_urls,
                                    'enable_file_upload': enable_file_upload,
                                    'enable_tts': enable_tts,
                                    'tts_model': tts_model,
                                    'tts_voice': tts_voice,
                                    'locked': config.get('locked', False)
                                })
                                
                                if config_manager.save(updated_config):
                                    # Auto-commit if HF token is available
                                    if HF_TOKEN and SPACE_ID:
                                        try:
                                            from huggingface_hub import HfApi, CommitOperationAdd
                                            api = HfApi(token=HF_TOKEN)
                                            
                                            operations = [
                                                CommitOperationAdd(
                                                    path_or_fileobj=config_manager.config_path,
                                                    path_in_repo="config.json"
                                                )
                                            ]
                                            
                                            api.create_commit(
                                                repo_id=SPACE_ID,
                                                operations=operations,
                                                commit_message="Update configuration via web UI",
                                                commit_description=f"Configuration update at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
                                                repo_type="space",
                                                token=HF_TOKEN
                                            )
                                            return "βœ… Configuration saved and committed to repository!"
                                        except Exception as e:
                                            return f"βœ… Configuration saved locally. ⚠️ Auto-commit failed: {str(e)}"
                                    else:
                                        return "βœ… Configuration saved locally (no HF token for auto-commit)"
                                else:
                                    return "❌ Failed to save configuration"
                                    
                            except Exception as e:
                                return f"❌ Error: {str(e)}"
                        
                        save_btn.click(
                            save_configuration,
                            inputs=[edit_name, edit_description, edit_system_prompt, edit_model, edit_language,
                                   edit_temperature, edit_max_tokens, edit_examples, edit_grounding_urls,
                                   edit_enable_dynamic_urls, edit_enable_file_upload, edit_enable_tts, edit_tts_model, edit_tts_voice],
                            outputs=[config_status]
                        )
                        
                        def reset_configuration():
                            """Reset to default configuration"""
                            try:
                                if config_manager.save(DEFAULT_CONFIG):
                                    return (
                                        DEFAULT_CONFIG['name'],
                                        DEFAULT_CONFIG['description'],
                                        DEFAULT_CONFIG['system_prompt'],
                                        DEFAULT_CONFIG['model'],
                                        DEFAULT_CONFIG.get('language', 'English'),
                                        DEFAULT_CONFIG['temperature'],
                                        DEFAULT_CONFIG['max_tokens'],
                                        '\n'.join(DEFAULT_CONFIG['examples']),
                                        '\n'.join(DEFAULT_CONFIG['grounding_urls']),
                                        DEFAULT_CONFIG['enable_dynamic_urls'],
                                        DEFAULT_CONFIG['enable_file_upload'],
                                        DEFAULT_CONFIG.get('enable_tts', False),
                                        DEFAULT_CONFIG.get('tts_model', 'microsoft/speecht5_tts'),
                                        DEFAULT_CONFIG.get('tts_voice', 'default'),
                                        "βœ… Reset to default configuration"
                                    )
                                else:
                                    return (*[gr.update() for _ in range(14)], "❌ Failed to reset")
                            except Exception as e:
                                return (*[gr.update() for _ in range(14)], f"❌ Error: {str(e)}")
                        
                        reset_btn.click(
                            reset_configuration,
                            outputs=[edit_name, edit_description, edit_system_prompt, edit_model, edit_language,
                                    edit_temperature, edit_max_tokens, edit_examples, edit_grounding_urls,
                                    edit_enable_dynamic_urls, edit_enable_file_upload, edit_enable_tts, edit_tts_model, edit_tts_voice, config_status]
                        )
                        
                        # Configuration tab authentication handler
                        def handle_config_auth(password):
                            """Handle configuration tab authentication"""
                            if not HF_TOKEN:
                                return (
                                    gr.update(visible=True),   # Keep auth panel visible
                                    gr.update(visible=False),  # Keep config panel hidden
                                    gr.update(value="❌ No HF_TOKEN is set in Space secrets. Configuration cannot be enabled."),
                                    False
                                )
                            
                            if password == HF_TOKEN:
                                return (
                                    gr.update(visible=False),  # Hide auth panel
                                    gr.update(visible=True),   # Show config panel
                                    gr.update(value="βœ… Authentication successful!"),
                                    True
                                )
                            else:
                                return (
                                    gr.update(visible=True),   # Keep auth panel visible
                                    gr.update(visible=False),  # Keep config panel hidden
                                    gr.update(value="❌ Invalid HF_TOKEN. Please try again."),
                                    False
                                )
                        
                        config_auth_btn.click(
                            handle_config_auth,
                            inputs=[config_password],
                            outputs=[config_auth_panel, config_panel, config_auth_status, config_authenticated]
                        )
                        
                        config_password.submit(
                            handle_config_auth,
                            inputs=[config_password],
                            outputs=[config_auth_panel, config_panel, config_auth_status, config_authenticated]
                        )
        
        # Access control handler
        if ACCESS_CODE:
            def handle_access(code, current_state):
                if code == ACCESS_CODE:
                    return (
                        gr.update(visible=False),  # Hide access panel
                        gr.update(visible=True),   # Show main panel
                        gr.update(value="βœ… Access granted!"),  # Status message
                        True  # Update state
                    )
                else:
                    return (
                        gr.update(visible=True),   # Keep access panel visible
                        gr.update(visible=False),  # Keep main panel hidden
                        gr.update(value="❌ Invalid access code. Please try again."),  # Status message
                        False  # State remains false
                    )
            
            access_btn.click(
                handle_access,
                inputs=[access_input, access_granted],
                outputs=[access_panel, main_panel, access_status, access_granted]
            )
            
            access_input.submit(
                handle_access,
                inputs=[access_input, access_granted],
                outputs=[access_panel, main_panel, access_status, access_granted]
            )
    
    return demo


# Create and launch the interface
if __name__ == "__main__":
    demo = create_interface()
    demo.launch()