File size: 53,431 Bytes
e44dfd9
9d1cfbd
 
 
 
 
 
 
 
 
 
e44dfd9
 
9d1cfbd
 
 
e44dfd9
9d1cfbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e44dfd9
9d1cfbd
 
 
 
 
 
 
 
e44dfd9
 
9d1cfbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e44dfd9
 
9d1cfbd
 
 
e44dfd9
9d1cfbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e44dfd9
 
9d1cfbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e44dfd9
 
9d1cfbd
e44dfd9
9d1cfbd
e44dfd9
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
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


# Configuration
SPACE_NAME = 'AI Assistant'
SPACE_DESCRIPTION = 'A customizable AI assistant'

# Default configuration values
DEFAULT_CONFIG = {
    'name': SPACE_NAME,
    'description': SPACE_DESCRIPTION,
    'system_prompt': "You are a helpful tutor that answers student questions on the materials, quizzes them on their knowledge, and points them to the correct answers when required. You make sure the student understands and can describe what they have learned in their own words before you move on. Using the URLs provided, you will first ask the student if they have any questions about the reading to start. Did anything not make sense to them, or was there a word or concept they'd like explained better? Once this is complete, then ask them if they're ready to be quizzed on the reading. Ask them the following questions one by one, allow the student to respond, and explain the correct answer before moving on to the next question. \n\n1. What was the goal of scientific management?\na. to increase workers’ efficiency\nb. to raise workers’ pay\nc. to make factories safer\nd. to shorten the workday\n\n2. How did assembly lines affect workers?\na. They made workdays shorter.\nb. They provided greater protection from injury.\nc. They made jobs boring and repetitious.\nd. They lowered pay.\n\n3. What was an important result of electrifying the workplace?\na. It made jobs more dangerous by exposing workers to electrical currents.\nb. It enabled factories to stay open later and people to work at night.\nc. It provided better heating in the winter.\nd. It reduced the strength needed to perform certain tasks, creating more jobs for children.\n\n4. How did married working-class women in western Europe commonly supplement the family’s income in the late nineteenth century?\na. They did piecework at home.\nb. They worked in mines.\nc. They taught school.\nd. They gave music lessons.\n\n5. To what nineteenth-century event does the term β€œdemographic transition” refer?\na. the disappearance of skilled crafts\nb. the decrease in the age of first marriage\nc. the decrease in family size\nd. the movement from rural areas to cities\n\n6. What was an important medical innovation of the late nineteenth century?\na. the smallpox vaccine\nb. x-rays\nc. CAT scans\nd. the stethoscope\n\n7. Which artistic style features impersonal depictions of characters compelled to behave in ways over which they have no control?\na. romanticism\nb. realism\nc. impressionism\nd. naturalism\n\n8. What was the Great Stink?\na. a stench coming from the polluted River Thames that nearly disrupted British government\nb. the name given to the poorest neighborhood in Chicago\nc. a nickname that city dwellers gave to peasants recently arrived from the countryside\nd. a nickname for the Paris sewer system\n\n9. What common disease of the period was caused by contaminated water?\na. tuberculosis\nb. asthma\nc. cholera\nd. syphilis\n\n10. What innovation made nineteenth-century cities cleaner?\na. streetlights\nb. electric streetcars\nc. outhouses\nd. public water fountains\n\n11. What were Selfridge’s, Le Bon MarchΓ©, and Matsuzakaya?\na. famous saloons\nb. urban department stores\nc. company towns built for miners\nd. newspapers\n\n12. Which artistic and literary movement glorified nature, common people, exotic places, and the historical past?\na. romanticism\nb. modernism\nc. naturalism\nd. classicism\n\n13. What was a common way in which contract laborers could fall into debt bondage?\na. renting a home in a nearby city\nb. buying goods at a store owned by the employer\nc. borrowing money from a friend\nd. running away\n\n14. What was the katorga system?\na. a form of penal servitude in which criminals were sent to labor camps in Siberia\nb. a form of debt bondage used in Brazil\nc. a British system of contracting for passage to another country in exchange for labor\nd. the practice in French brothels of charging prostitutes for food and clothing so they always remained in debt\n\n15. Which social movement was more successful in Protestant societies than in others?\na. housing reform\nb. anti-prostitution campaigns\nc. temperance and prohibition\nd. health insurance advocacy\n\n16. What was Britain’s Alkali Act intended to do?\na. protect drinking water from contamination\nb. ensure that processed foods were safe to eat\nc. prevent cholera\nd. alleviate air pollution\n\n17. Which country was the first to provide health insurance for workers?\na. the United States\nb. Germany\nc. France\nd. Russia\n\n18. Which of the following was an important difference between socialist parties in Europe?\na. Some parties accepted women and some did not.\nb. Some believed the bourgeoisie should be executed and others did not.\nc. Some advocated revolution and some a more gradual democratic approach.\nd. Some supported workers’ rights and some did not.\n\nOnce the student has shown that they understand all of the correct answers, ask them if they are ready to move on to their discussion board assignment for the week. When they say yes, ask them what kind of story they would like to write, give some examples of genres, including historical fiction, nonfiction, true crime, fantasy, etc. then ask the student to write you a prompt so that you can create a story of no more than 5 pages based on the URLs provided focusing on a topic that they choose for you and based on their specific instructions. prompt them to be as detailed as possible with the prompt so that you can write a story specific to them. If they prompt you to do something that does not make sense according to the materials provided, explain to them why and point them to the place in the URLs provided that explains why. once they provide an appropriate prompt, write the story for them. Then ask them if there is anything that they would like you to edit or change. make changes, and when they are satisfied, instruct them to edit the final story so that it contains a clear historical inaccuracy and post their completed story (with the hidden lie) on the discussion board, and also don't forget to click export conversation below to upload this chat to brightspace.",
    'temperature': 0.7,
    'max_tokens': 1550,
    'model': 'mistralai/mistral-medium-3',
    'api_key_var': 'API_KEY',
    'theme': 'Default',
    'grounding_urls': ["https://www.youtube.com/watch?v=w8ispQxpOXg", "https://louis.pressbooks.pub/westernciv2/part/6-life-and-labor-in-the-industrial-world/", "https://louis.pressbooks.pub/westernciv2/chapter/6-1-inventions-innovations-and-mechanization/", "https://louis.pressbooks.pub/westernciv2/chapter/6-2-life-in-the-industrial-city/", "https://louis.pressbooks.pub/westernciv2/chapter/6-3-coerced-and-semicoerced-labor/", "https://louis.pressbooks.pub/westernciv2/chapter/6-4-communities-in-diaspora/", "https://louis.pressbooks.pub/westernciv2/chapter/chapter-6-5-regulation-reform-and-revolutionary-ideologies/", "https://louis.pressbooks.pub/westernciv2/chapter/6-section-summary/", "https://louis.pressbooks.pub/westernciv2/chapter/key-terms-and-assessments/"],
    'enable_dynamic_urls': True,
    'enable_file_upload': True,
    'examples': ['Write a mystery story about a woman working walking home at night from her job at a factory through the london neighborhoods most frequently victimized by jack the ripper', 'Write a romance story about an opera singer in the brazilian rainforest who falls in love with a farmer', 'Write a day in the life of a prisoner in a siberian katorga interweaving his backstory'],
    'language': 'English',
    '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'))

# 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:
            result = response.json()
            ai_response = result['choices'][0]['message']['content']
            
            # Add file notification if files were uploaded
            if file_notification:
                ai_response += file_notification
            
            return ai_response
        else:
            error_data = response.json()
            error_message = error_data.get('error', {}).get('message', '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)}"


# 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():
                        # Use a regular Button for triggering export
                        export_trigger_btn = gr.Button(
                            "πŸ“₯ Export Conversation",
                            variant="secondary",
                            size="sm"
                        )
                        # Hidden file component for actual download
                        export_file = gr.File(
                            visible=False,
                            label="Download Export"
                        )
                    
                    # Export handler
                    def prepare_export(chat_history):
                        if not chat_history:
                            gr.Warning("No conversation history to export.")
                            return None
                        
                        try:
                            content = export_conversation_to_markdown(chat_history)
                            
                            # 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 the file component with visibility and value
                            return gr.File(visible=True, value=str(temp_path))
                        except Exception as e:
                            gr.Error(f"Failed to export conversation: {str(e)}")
                            return None
                    
                    export_trigger_btn.click(
                        prepare_export,
                        inputs=[chatbot],
                        outputs=[export_file]
                    )
                    
                    # 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])
                    
                    def clear_chat():
                        global chat_history_store
                        chat_history_store = []
                        return [], ""
                    
                    clear_btn.click(clear_chat, 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"
                            )
                        
                        # 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):
                            """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,
                                    '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],
                            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'],
                                        "βœ… Reset to default configuration"
                                    )
                                else:
                                    return (*[gr.update() for _ in range(11)], "❌ Failed to reset")
                            except Exception as e:
                                return (*[gr.update() for _ in range(11)], 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, 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()