File size: 46,618 Bytes
6a198b1
0d8f38b
5d237f7
 
 
 
 
cb3e2ab
a7d1464
cb3e2ab
ea34782
 
5d237f7
 
6a198b1
cb3e2ab
 
 
6a198b1
cb3e2ab
fca724e
 
2da6147
cb3e2ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75fc42b
5d237f7
 
ea34782
cb3e2ab
 
5d237f7
 
 
cb3e2ab
ea34782
cb3e2ab
 
5d237f7
75fc42b
5d237f7
 
cb3e2ab
 
 
5d237f7
 
 
 
 
 
 
 
cb3e2ab
75fc42b
 
 
 
 
 
 
 
 
 
cb3e2ab
 
 
75fc42b
 
 
6a198b1
8109e33
cb3e2ab
290d8c1
 
 
 
8109e33
cb3e2ab
 
290d8c1
cb3e2ab
 
 
290d8c1
 
 
 
 
 
ab35ebc
f8d9d44
cb3e2ab
09e99eb
cb3e2ab
75fc42b
5d237f7
 
 
290d8c1
cb3e2ab
 
5d237f7
 
 
cb3e2ab
 
5d237f7
75fc42b
 
 
 
 
 
5d237f7
 
cb3e2ab
 
75fc42b
 
 
 
 
 
 
 
 
cb3e2ab
 
 
 
5d237f7
 
 
 
 
 
cb3e2ab
5d237f7
 
 
 
cb3e2ab
5d237f7
 
cb3e2ab
 
75fc42b
 
cb3e2ab
75fc42b
 
 
 
 
 
cb3e2ab
 
5d237f7
cb3e2ab
5d237f7
cb3e2ab
75fc42b
 
 
 
cb3e2ab
290d8c1
5d237f7
 
 
cb3e2ab
75fc42b
 
 
cb3e2ab
75fc42b
 
 
8109e33
cb3e2ab
75fc42b
 
cb3e2ab
 
290d8c1
 
 
 
75fc42b
 
cb3e2ab
 
 
 
 
290d8c1
cb3e2ab
 
 
 
75fc42b
 
cb3e2ab
290d8c1
cb3e2ab
5d237f7
cb3e2ab
290d8c1
cb3e2ab
 
 
 
 
 
5d237f7
cb3e2ab
 
290d8c1
cb3e2ab
290d8c1
cb3e2ab
 
 
 
 
 
 
290d8c1
cb3e2ab
 
5d237f7
cb3e2ab
 
 
75fc42b
 
 
 
cb3e2ab
 
 
 
75fc42b
cb3e2ab
75fc42b
290d8c1
 
cb3e2ab
 
75fc42b
 
 
cb3e2ab
 
75fc42b
 
 
 
 
12bee5e
75fc42b
 
ea34782
cb3e2ab
75fc42b
 
 
 
 
 
 
 
 
cb3e2ab
 
 
 
 
75fc42b
 
cb3e2ab
75fc42b
 
 
 
 
 
cb3e2ab
75fc42b
 
 
 
cb3e2ab
 
 
290d8c1
75fc42b
 
 
 
cb3e2ab
75fc42b
 
cb3e2ab
290d8c1
 
 
75fc42b
 
cb3e2ab
 
290d8c1
 
75fc42b
 
 
 
 
 
 
 
cb3e2ab
 
75fc42b
cb3e2ab
 
 
290d8c1
75fc42b
 
 
 
 
 
 
 
cb3e2ab
75fc42b
 
cb3e2ab
 
 
75fc42b
 
290d8c1
75fc42b
cb3e2ab
75fc42b
290d8c1
75fc42b
 
 
 
 
 
cb3e2ab
 
75fc42b
cb3e2ab
 
 
09e99eb
cb3e2ab
75fc42b
cb3e2ab
 
09e99eb
cb3e2ab
 
 
09e99eb
cb3e2ab
 
 
75fc42b
 
ea34782
cb3e2ab
75fc42b
 
cb3e2ab
290d8c1
75fc42b
 
 
 
ea34782
75fc42b
 
 
5d237f7
 
 
 
 
75fc42b
 
5d237f7
 
 
75fc42b
 
5d237f7
 
 
cb3e2ab
290d8c1
cb3e2ab
 
75fc42b
 
 
 
 
 
 
 
5d237f7
 
 
 
290d8c1
cb3e2ab
5d237f7
75fc42b
 
 
 
 
 
 
290d8c1
cb3e2ab
75fc42b
5d237f7
cb3e2ab
 
 
 
75fc42b
 
 
 
5d237f7
 
 
 
75fc42b
 
5d237f7
75fc42b
 
 
 
 
 
 
5d237f7
 
cb3e2ab
75fc42b
290d8c1
 
cb3e2ab
290d8c1
75fc42b
 
 
 
 
cb3e2ab
 
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb3e2ab
75fc42b
 
 
 
 
cb3e2ab
 
09e99eb
cb3e2ab
75fc42b
290d8c1
cb3e2ab
 
 
 
 
75fc42b
290d8c1
 
 
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
290d8c1
cb3e2ab
75fc42b
 
 
 
 
290d8c1
 
75fc42b
cb3e2ab
75fc42b
 
 
 
 
 
 
cb3e2ab
75fc42b
cb3e2ab
 
 
75fc42b
 
 
 
 
 
 
 
 
 
 
 
cb3e2ab
 
09e99eb
 
cb3e2ab
75fc42b
 
cb3e2ab
09e99eb
 
 
 
 
75fc42b
 
 
 
 
 
 
 
 
 
 
 
290d8c1
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
290d8c1
75fc42b
 
 
 
cb3e2ab
 
 
 
 
75fc42b
 
 
 
 
cb3e2ab
75fc42b
 
 
 
cb3e2ab
75fc42b
290d8c1
cb3e2ab
 
 
75fc42b
 
 
 
 
 
 
 
 
 
 
 
cb3e2ab
 
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb3e2ab
75fc42b
 
 
 
 
 
 
 
 
 
 
09e99eb
cb3e2ab
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09e99eb
3bc3dc6
cb3e2ab
75fc42b
 
cb3e2ab
75fc42b
 
 
 
cb3e2ab
5d237f7
cb3e2ab
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09e99eb
cb3e2ab
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
290d8c1
75fc42b
 
 
09e99eb
75fc42b
 
09e99eb
 
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09e99eb
75fc42b
 
 
09e99eb
 
75fc42b
 
 
 
 
 
 
 
 
 
09e99eb
 
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2e50a8
09e99eb
75fc42b
 
 
 
 
 
 
ea34782
75fc42b
 
 
3bc3dc6
09e99eb
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09e99eb
75fc42b
 
 
09e99eb
75fc42b
 
 
 
09e99eb
75fc42b
 
 
09e99eb
75fc42b
 
 
 
 
09e99eb
75fc42b
 
09e99eb
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
09e99eb
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09e99eb
 
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09e99eb
 
75fc42b
 
 
 
09e99eb
75fc42b
 
 
 
09e99eb
75fc42b
 
09e99eb
75fc42b
 
 
 
 
 
09e99eb
75fc42b
 
 
 
09e99eb
 
75fc42b
 
 
 
 
 
 
 
 
09e99eb
75fc42b
 
 
09e99eb
 
75fc42b
 
 
 
 
290d8c1
cb3e2ab
 
3bc3dc6
cb3e2ab
75fc42b
b2e50a8
75fc42b
5d237f7
cb3e2ab
 
75fc42b
 
cb3e2ab
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
09e99eb
 
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09e99eb
 
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09e99eb
 
 
75fc42b
 
290d8c1
09e99eb
 
 
75fc42b
 
 
 
09e99eb
75fc42b
 
09e99eb
75fc42b
 
 
09e99eb
75fc42b
09e99eb
75fc42b
 
 
 
09e99eb
75fc42b
 
09e99eb
75fc42b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09e99eb
 
75fc42b
 
 
09e99eb
75fc42b
 
 
09e99eb
 
75fc42b
 
 
09e99eb
75fc42b
 
09e99eb
 
75fc42b
 
 
 
cb3e2ab
 
3bc3dc6
cb3e2ab
75fc42b
a671c88
09e99eb
 
38df419
09e99eb
ab35ebc
ea34782
290d8c1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
import os
import gc
import re
import json
import uuid
import time
import shutil
import random
import sqlite3
import zipfile
import threading
import traceback
from pathlib import Path
from datetime import datetime

os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
os.environ["TOKENIZERS_PARALLELISM"] = "false"

import spaces
import gradio as gr
import torch

from PIL import Image

from diffusers import (
    DiffusionPipeline,
    AutoPipelineForImage2Image,
)

from transformers import (
    AutoTokenizer,
    AutoModelForCausalLM,
    TextIteratorStreamer,
    StoppingCriteria,
    StoppingCriteriaList,
)

from threading import Thread, Event

# =========================================================
# CONFIGURATION
# =========================================================

APP_NAME = "ARISE AI Studio"
DEVELOPER_TELEGRAM = "https://t.me/hardhackar009"

MAX_INPUT_LENGTH = 4096
MAX_HISTORY_MESSAGES = 10
MAX_UPLOAD_FILES = 100
MAX_FILE_SIZE = 10 * 1024 * 1024
MAX_PROJECT_SIZE = 100 * 1024 * 1024
MAX_CONTEXT_SIZE = 80000

IMAGE_DTYPE = torch.float16

DATA_DIR = Path(os.getenv("ARISE_DATA_DIR", "/data/arise_ai_studio"))

try:
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    test_file = DATA_DIR / ".write_test"
    test_file.write_text("ok")
    test_file.unlink()
except Exception:
    DATA_DIR = Path("./arise_ai_studio_data")
    DATA_DIR.mkdir(parents=True, exist_ok=True)

DB_PATH = DATA_DIR / "arise_history.db"
PROJECTS_DIR = DATA_DIR / "projects"
PROJECTS_DIR.mkdir(parents=True, exist_ok=True)

SUPPORTED_TEXT_EXTENSIONS = {
    ".py", ".js", ".jsx", ".ts", ".tsx",
    ".html", ".htm", ".css", ".scss",
    ".json", ".xml", ".yaml", ".yml",
    ".md", ".txt", ".java", ".kt",
    ".gradle", ".properties", ".sh",
    ".bat", ".c", ".cpp", ".h", ".hpp",
    ".php", ".sql", ".go", ".rs",
    ".swift", ".dart", ".vue", ".svelte",
    ".toml", ".ini", ".cfg", ".env.example",
    ".gitignore", ".dockerfile",
}

EXCLUDED_DIRS = {
    ".git", ".gradle", ".idea", ".vscode",
    "__pycache__", "node_modules", "build",
    "dist", ".venv", "venv", ".next",
}

IMAGE_MODELS = {
    "SDXL Turbo": {"id": "stabilityai/sdxl-turbo", "steps": 4, "guidance": 0.0, "max_steps": 4},
    "Stable Diffusion 1.5": {"id": "stable-diffusion-v1-5/stable-diffusion-v1-5", "steps": 25, "guidance": 7.5, "max_steps": 30},
    "SD Turbo": {"id": "stabilityai/sd-turbo", "steps": 4, "guidance": 0.0, "max_steps": 4},
    "Tiny SD": {"id": "segmind/tiny-sd", "steps": 20, "guidance": 7.5, "max_steps": 30},
}

IMAGE_TO_IMAGE_MODELS = {
    "Stable Diffusion 1.5 Img2Img": "stable-diffusion-v1-5/stable-diffusion-v1-5",
}

CODE_MODELS = {
    "Qwen Coder 0.5B": "Qwen/Qwen2.5-Coder-0.5B-Instruct",
    "Qwen Coder 1.5B": "Qwen/Qwen2.5-Coder-1.5B-Instruct",
    "DeepSeek Coder 1.3B": "deepseek-ai/deepseek-coder-1.3b-instruct",
    "Qwen Coder 3B": "Qwen/Qwen2.5-Coder-3B-Instruct",
    "StarCoder2 3B": "bigcode/starcoder2-3b",
    "CodeGen 350M": "Salesforce/codegen-350M-mono",
}

# =========================================================
# DATABASE (Optimized)
# =========================================================

db_lock = threading.RLock()

def db_connect():
    connection = sqlite3.connect(str(DB_PATH), timeout=30, check_same_thread=False)
    connection.row_factory = sqlite3.Row
    return connection

def initialize_database():
    with db_lock:
        connection = db_connect()
        connection.execute("""
            CREATE TABLE IF NOT EXISTS conversations (
                id TEXT PRIMARY KEY,
                session_id TEXT NOT NULL,
                title TEXT NOT NULL,
                history TEXT NOT NULL,
                created TEXT NOT NULL,
                updated TEXT NOT NULL
            )
        """)
        connection.execute("""
            CREATE TABLE IF NOT EXISTS jobs (
                id TEXT PRIMARY KEY,
                session_id TEXT NOT NULL,
                conversation_id TEXT NOT NULL,
                status TEXT NOT NULL,
                prompt TEXT NOT NULL,
                response TEXT NOT NULL,
                error TEXT,
                created TEXT NOT NULL,
                updated TEXT NOT NULL
            )
        """)
        connection.commit()
        connection.close()

initialize_database()

def now_string():
    return datetime.utcnow().isoformat(timespec="seconds")

def get_project_dir(conversation_id):
    path = PROJECTS_DIR / conversation_id
    path.mkdir(parents=True, exist_ok=True)
    return path

def save_conversation(session_id, conversation_id, title, history):
    timestamp = now_string()
    with db_lock:
        connection = db_connect()
        connection.execute("""
            INSERT INTO conversations
            (id, session_id, title, history, created, updated)
            VALUES (?, ?, ?, ?, ?, ?)
            ON CONFLICT(id) DO UPDATE SET
                title=excluded.title,
                history=excluded.history,
                updated=excluded.updated
        """, (conversation_id, session_id, title,
              json.dumps(history, ensure_ascii=False), timestamp, timestamp))
        connection.commit()
        connection.close()

def get_conversations(session_id):
    with db_lock:
        connection = db_connect()
        rows = connection.execute("""
            SELECT id, title, updated FROM conversations
            WHERE session_id=? ORDER BY updated DESC
        """, (session_id,)).fetchall()
        connection.close()
    return [(f"{row['title']} Β· {row['updated']}", row["id"]) for row in rows]

def get_conversation(session_id, conversation_id):
    with db_lock:
        connection = db_connect()
        row = connection.execute("""
            SELECT * FROM conversations WHERE id=? AND session_id=?
        """, (conversation_id, session_id)).fetchone()
        connection.close()
    if not row:
        return None
    return {"id": row["id"], "title": row["title"], "history": json.loads(row["history"])}

def delete_conversations(session_id, conversation_ids):
    if not conversation_ids:
        return
    with db_lock:
        connection = db_connect()
        for cid in conversation_ids:
            connection.execute("DELETE FROM conversations WHERE id=? AND session_id=?", (cid, session_id))
            connection.execute("DELETE FROM jobs WHERE conversation_id=? AND session_id=?", (cid, session_id))
            project_dir = PROJECTS_DIR / cid
            if project_dir.exists():
                shutil.rmtree(project_dir, ignore_errors=True)
        connection.commit()
        connection.close()

def create_conversation(session_id, title="New Project"):
    conversation_id = uuid.uuid4().hex
    save_conversation(session_id, conversation_id, title, [])
    get_project_dir(conversation_id)
    return conversation_id

def update_job(job_id, **values):
    if not values:
        return
    values["updated"] = now_string()
    assignments = ", ".join(f"{key}=?" for key in values)
    parameters = list(values.values()) + [job_id]
    with db_lock:
        connection = db_connect()
        connection.execute(f"UPDATE jobs SET {assignments} WHERE id=?", parameters)
        connection.commit()
        connection.close()

def create_job(session_id, conversation_id, prompt):
    job_id = uuid.uuid4().hex
    timestamp = now_string()
    with db_lock:
        connection = db_connect()
        connection.execute("""
            INSERT INTO jobs (id, session_id, conversation_id, status, prompt, response, error, created, updated)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (job_id, session_id, conversation_id, "queued", prompt, "", None, timestamp, timestamp))
        connection.commit()
        connection.close()
    return job_id

def get_job(job_id, session_id):
    with db_lock:
        connection = db_connect()
        row = connection.execute("SELECT * FROM jobs WHERE id=? AND session_id=?", (job_id, session_id)).fetchone()
        connection.close()
    return dict(row) if row else None

def get_active_job(session_id, conversation_id):
    with db_lock:
        connection = db_connect()
        row = connection.execute("""
            SELECT * FROM jobs WHERE session_id=? AND conversation_id=?
            AND status IN ('queued', 'running') ORDER BY created DESC LIMIT 1
        """, (session_id, conversation_id)).fetchone()
        connection.close()
    return dict(row) if row else None

# =========================================================
# MODEL CACHE
# =========================================================

image_cache = {"name": None, "pipe": None}
code_cache = {"name": None, "tokenizer": None, "model": None}
image_lock = threading.RLock()
code_lock = threading.RLock()
job_threads = {}
job_threads_lock = threading.RLock()
job_stop_events = {}

def clear_image_cache():
    old_pipe = image_cache["pipe"]
    image_cache["pipe"] = None
    image_cache["name"] = None
    if old_pipe is not None:
        del old_pipe
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()

def clear_code_cache():
    old_model = code_cache["model"]
    old_tokenizer = code_cache["tokenizer"]
    code_cache["model"] = None
    code_cache["tokenizer"] = None
    code_cache["name"] = None
    if old_model is not None:
        del old_model
    if old_tokenizer is not None:
        del old_tokenizer
    gc.collect()

def load_image_pipeline(model_id, mode):
    cache_key = f"{mode}:{model_id}"
    with image_lock:
        if image_cache["name"] == cache_key and image_cache["pipe"] is not None:
            return image_cache["pipe"]
        clear_image_cache()
        if mode == "text":
            pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=IMAGE_DTYPE, token=False)
        elif mode == "image":
            pipe = AutoPipelineForImage2Image.from_pretrained(model_id, torch_dtype=IMAGE_DTYPE, token=False)
        else:
            raise ValueError("Invalid image mode.")
        pipe = pipe.to("cuda")
        if hasattr(pipe, "enable_attention_slicing"):
            pipe.enable_attention_slicing()
        image_cache["pipe"] = pipe
        image_cache["name"] = cache_key
        return pipe

@spaces.GPU(duration=120)
def generate_image(prompt, negative_prompt, model_name, width, height, steps, seed, random_seed):
    if not prompt or not prompt.strip():
        raise gr.Error("Enter an image prompt.")
    if model_name not in IMAGE_MODELS:
        raise gr.Error("Invalid image model.")
    config = IMAGE_MODELS[model_name]
    if random_seed:
        seed = random.randint(0, 2147483647)
    seed = int(seed or 0)
    width = (max(256, min(int(width), 768)) // 8) * 8
    height = (max(256, min(int(height), 768)) // 8) * 8
    actual_steps = min(max(int(steps), 1), config["max_steps"])
    if model_name in ["SDXL Turbo", "SD Turbo"]:
        actual_steps = min(actual_steps, 4)
    try:
        with image_lock:
            pipe = load_image_pipeline(config["id"], "text")
            generator = torch.Generator(device="cuda").manual_seed(seed)
            result = pipe(
                prompt=prompt.strip(),
                negative_prompt=negative_prompt or None,
                width=width, height=height,
                num_inference_steps=actual_steps,
                guidance_scale=config["guidance"],
                generator=generator,
            )
            return result.images[0], seed
    except Exception as error:
        traceback.print_exc()
        raise gr.Error(f"Image generation failed: {error}")

@spaces.GPU(duration=120)
def generate_image_to_image(input_image, prompt, negative_prompt, model_name, strength, steps, guidance, seed, random_seed):
    if input_image is None:
        raise gr.Error("Upload an image.")
    if not prompt or not prompt.strip():
        raise gr.Error("Enter transformation prompt.")
    if model_name not in IMAGE_TO_IMAGE_MODELS:
        raise gr.Error("Invalid image model.")
    if random_seed:
        seed = random.randint(0, 2147483647)
    seed = int(seed or 0)
    strength = max(0.05, min(float(strength), 0.95))
    steps = max(1, min(int(steps), 30))
    try:
        image = input_image.convert("RGB")
        image.thumbnail((768, 768), Image.Resampling.LANCZOS)
        width = max(256, (image.width // 8) * 8)
        height = max(256, (image.height // 8) * 8)
        image = image.resize((width, height), Image.Resampling.LANCZOS)
        model_id = IMAGE_TO_IMAGE_MODELS[model_name]
        with image_lock:
            pipe = load_image_pipeline(model_id, "image")
            generator = torch.Generator(device="cuda").manual_seed(seed)
            result = pipe(
                prompt=prompt.strip(), image=image,
                negative_prompt=negative_prompt or None,
                strength=strength, num_inference_steps=steps,
                guidance_scale=float(guidance), generator=generator,
            )
            return result.images[0], seed
    except Exception as error:
        traceback.print_exc()
        raise gr.Error(f"Image-to-image failed: {error}")

# =========================================================
# SYSTEM PROMPT & FILE HELPERS
# =========================================================

SYSTEM_PROMPT = """
You are ARISE AI, a professional software engineering assistant.
When modifying project files, return every complete modified or new file using exactly this format:
<<<FILE: relative/path/to/file.ext>>>
complete file content here
<<<END FILE>>>
Do not use absolute paths. Do not omit required imports or code.
"""

def load_code_model(model_name):
    if model_name not in CODE_MODELS:
        raise ValueError("Invalid coding model.")
    model_id = CODE_MODELS[model_name]
    with code_lock:
        if code_cache["name"] == model_id and code_cache["model"] is not None:
            return code_cache["tokenizer"], code_cache["model"]
        clear_code_cache()
        tokenizer = AutoTokenizer.from_pretrained(model_id, token=False)
        model = AutoModelForCausalLM.from_pretrained(
            model_id, token=False, torch_dtype=torch.float32, low_cpu_mem_usage=True,
        )
        model.to("cpu")
        model.eval()
        code_cache["name"] = model_id
        code_cache["tokenizer"] = tokenizer
        code_cache["model"] = model
        return tokenizer, model

def safe_relative_path(value):
    value = str(value).replace("\\", "/").strip()
    path = Path(value)
    if not value or path.is_absolute() or ".." in path.parts or "\x00" in value:
        raise ValueError("Unsafe project file path.")
    return path

def is_text_file(path):
    return (path.suffix.lower() in SUPPORTED_TEXT_EXTENSIONS
            or path.name.lower() in {"dockerfile", "makefile", ".gitignore"})

def project_files(project_dir):
    result = []
    for root, dirs, files in os.walk(project_dir):
        dirs[:] = [name for name in dirs if name not in EXCLUDED_DIRS]
        for filename in files:
            full_path = Path(root) / filename
            if full_path.name == "project_index.json":
                continue
            try:
                relative = full_path.relative_to(project_dir)
                size = full_path.stat().st_size
            except Exception:
                continue
            result.append({"path": relative.as_posix(), "size": size, "text": is_text_file(full_path)})
    return result

def build_project_context(project_dir):
    files = project_files(project_dir)
    output = ["PROJECT STRUCTURE:", json.dumps(files, ensure_ascii=False, indent=2), "", "PROJECT FILE CONTENTS:"]
    total = 0
    for item in files:
        if not item["text"]:
            continue
        path = project_dir / item["path"]
        try:
            content = path.read_text(encoding="utf-8", errors="replace")
        except Exception:
            continue
        section = f"\n\n===== FILE: {item['path']} =====\n{content}\n===== END FILE =====\n"
        if total + len(section) > MAX_CONTEXT_SIZE:
            output.append("\n[Project context truncated due to configured context limit.]")
            break
        output.append(section)
        total += len(section)
    return "\n".join(output), files

FILE_BLOCK_PATTERN = re.compile(
    r"<<<FILE:\s*(.*?)>>>\s*(.*?)\s*<<<END FILE>>>",
    re.DOTALL | re.IGNORECASE,
)

def apply_file_changes(response, project_dir):
    changed = []
    for match in FILE_BLOCK_PATTERN.finditer(response):
        relative_name = match.group(1).strip()
        content = match.group(2)
        try:
            relative = safe_relative_path(relative_name)
        except Exception:
            continue
        target = Path(project_dir) / relative
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(content.rstrip() + "\n", encoding="utf-8")
        changed.append(relative.as_posix())
    return changed

def create_project_zip(project_dir):
    project_dir = Path(project_dir)
    zip_path = DATA_DIR / ("ARISE_Project_" + uuid.uuid4().hex[:10] + ".zip")
    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as archive:
        for root, dirs, files in os.walk(project_dir):
            dirs[:] = [name for name in dirs if name not in EXCLUDED_DIRS]
            for filename in files:
                full_path = Path(root) / filename
                if full_path == zip_path:
                    continue
                archive.write(full_path, full_path.relative_to(project_dir))
    return str(zip_path)

def create_single_file_download(project_dir, relative_name):
    relative = safe_relative_path(relative_name)
    source = Path(project_dir) / relative
    if not source.exists() or not source.is_file():
        return None
    download_dir = DATA_DIR / "downloads"
    download_dir.mkdir(exist_ok=True)
    destination = download_dir / (uuid.uuid4().hex[:8] + "_" + source.name)
    shutil.copy2(source, destination)
    return str(destination)

def make_html_preview(project_dir):
    project_dir = Path(project_dir)
    html_files = list(project_dir.rglob("index.html")) or list(project_dir.rglob("*.html"))
    if not html_files:
        return "<div style='padding:25px;color:#ddd'>No HTML file found in this project.</div>"
    html_file = html_files[0]
    try:
        html = html_file.read_text(encoding="utf-8", errors="replace")

        def replace_asset(match):
            asset_name = match.group(1).split("?")[0].split("#")[0]
            asset_path = (html_file.parent / asset_name).resolve()
            try:
                asset_path.relative_to(project_dir.resolve())
            except ValueError:
                return match.group(0)
            if not asset_path.exists():
                return match.group(0)
            content = asset_path.read_text(encoding="utf-8", errors="replace")
            if match.group(0).lower().startswith("<link"):
                return "<style>\n" + content + "\n</style>"
            return "<script>\n" + content + "\n</script>"

        html = re.sub(r'<link[^>]+href=["\']([^"\']+\.css)["\'][^>]*>', replace_asset, html, flags=re.IGNORECASE)
        html = re.sub(r'<script[^>]+src=["\']([^"\']+\.js)["\'][^>]*>\s*</script>', replace_asset, html, flags=re.IGNORECASE)

        return f"""
        <iframe sandbox="allow-scripts allow-forms"
            style="width:100%;height:650px;border:1px solid #34415e;border-radius:14px;background:white;"
            srcdoc="{html.replace('&', '&amp;').replace('"', '&quot;').replace('<', '&lt;').replace('>', '&gt;')}"
        ></iframe>
        """
    except Exception as error:
        return f"<div style='padding:20px;color:#ff9999'>Preview error: {error}</div>"

class StopCriteria(StoppingCriteria):
    def __init__(self, event):
        self.event = event

    def __call__(self, input_ids, scores, **kwargs):
        return self.event.is_set()

# =========================================================
# CODING WORKER (Throttled for smooth streaming)
# =========================================================

def run_coding_worker(job_id, session_id, conversation_id, prompt, model_name, max_tokens, temperature, stop_event):
    try:
        update_job(job_id, status="running", response="")
        project_dir = get_project_dir(conversation_id)
        project_context, files = build_project_context(project_dir)
        tokenizer, model = load_code_model(model_name)

        messages = [{"role": "system", "content": SYSTEM_PROMPT}]
        conversation = get_conversation(session_id, conversation_id)
        history = conversation["history"] if conversation else []

        for item in history[-MAX_HISTORY_MESSAGES:]:
            if (isinstance(item, dict) and item.get("role") in ["user", "assistant"]
                    and isinstance(item.get("content"), str)):
                messages.append({"role": item["role"], "content": item["content"]})

        project_prompt = prompt
        if files:
            project_prompt = (
                "PROJECT CONTEXT:\n" + project_context + "\n\nUSER REQUEST:\n" + prompt + "\n\n"
                + "Analyze the supplied project before editing. Make only the requested changes. "
                + "Return every changed/new file using the required <<<FILE: path>>> format."
            )
        messages.append({"role": "user", "content": project_prompt})

        if getattr(tokenizer, "chat_template", None):
            formatted_prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
        else:
            formatted_prompt = "\n\n".join(f"{i['role'].upper()}:\n{i['content']}" for i in messages) + "\n\nASSISTANT:\n"

        inputs = tokenizer(formatted_prompt, return_tensors="pt", truncation=True, max_length=MAX_INPUT_LENGTH)
        streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=120)

        generation_kwargs = {
            **inputs,
            "streamer": streamer,
            "max_new_tokens": max(128, min(int(max_tokens), 2048)),
            "do_sample": float(temperature) > 0.05,
            "temperature": max(float(temperature), 0.05),
            "pad_token_id": tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id,
            "stopping_criteria": StoppingCriteriaList([StopCriteria(stop_event)]),
        }

        errors = []
        def generate():
            try:
                with torch.inference_mode():
                    model.generate(**generation_kwargs)
            except Exception as error:
                errors.append(str(error))
                traceback.print_exc()
                try:
                    streamer.end()
                except Exception:
                    pass

        generation_thread = Thread(target=generate, daemon=True)
        generation_thread.start()

        response = ""
        last_db_update = time.time()
        
        for token in streamer:
            if stop_event.is_set():
                break
            response += token
            
            # πŸ”₯ LAG FIX: Update database only every 0.2 seconds instead of every token
            if time.time() - last_db_update > 0.2:
                update_job(job_id, response=response, status="running")
                last_db_update = time.time()

        generation_thread.join(timeout=15)
        if generation_thread.is_alive():
            stop_event.set()
        if errors:
            raise RuntimeError(errors[0])
        if stop_event.is_set():
            update_job(job_id, status="stopped", response=response + "\n\nGeneration stopped.")
            return
        if not response.strip():
            response = "No response generated."

        changed_files = apply_file_changes(response, project_dir)
        history = history + [
            {"role": "user", "content": prompt},
            {"role": "assistant", "content": response},
        ]
        title = prompt.strip().replace("\n", " ")[:55] or "ARISE Project"
        save_conversation(session_id, conversation_id, title, history)

        final_response = response
        if changed_files:
            file_status = "\n".join(
                f"- <span style='color:#35d58a'>βœ“</span> `{name}` β€” Edited" for name in changed_files
            )
            final_response += "\n\n---\n### Project File Updates\n" + file_status

        update_job(job_id, status="completed", response=final_response)

    except Exception as error:
        traceback.print_exc()
        update_job(job_id, status="error", error=str(error), response=f"**Coding error:** {error}")
    finally:
        with job_threads_lock:
            job_threads.pop(job_id, None)
            job_stop_events.pop(job_id, None)

def coding_assistant(prompt, model_name, max_tokens, temperature, conversation_id, request: gr.Request):
    if not prompt or not prompt.strip():
        yield ("Please enter your coding request.", conversation_id, "Waiting for prompt.", None, None, None)
        return

    session_id = request.session_hash if request else "default"

    if not conversation_id:
        conversation_id = create_conversation(session_id, prompt.strip().replace("\n", " ")[:55])

    project_dir = get_project_dir(conversation_id)

    job_id = create_job(session_id, conversation_id, prompt.strip())
    stop_event = Event()
    with job_threads_lock:
        job_stop_events[job_id] = stop_event
        worker = Thread(
            target=run_coding_worker,
            args=(job_id, session_id, conversation_id, prompt.strip(),
                  model_name, max_tokens, temperature, stop_event),
            daemon=True,
        )
        job_threads[job_id] = worker
        worker.start()

    yield ("⏳ ARISE AI is analyzing your request...", conversation_id, "Job started.", None, None, job_id)

    previous_response = ""
    while True:
        job = get_job(job_id, session_id)
        if not job:
            yield ("Job not found.", conversation_id, "Job unavailable.", None, None, job_id)
            return

        response = job["response"] or ""
        status = job["status"]
        status_text = {
            "queued": "⏳ Waiting in queue",
            "running": "βš™οΈ ARISE AI is working",
            "completed": "βœ… Coding completed",
            "stopped": "⏹ Generation stopped",
            "error": "❌ Job failed",
        }.get(status, status)

        if response != previous_response or status not in ["queued", "running"]:
            previous_response = response
            zip_file = None
            single_file = None
            if status == "completed":
                zip_file = create_project_zip(project_dir)
                changed = apply_file_changes(response, project_dir)
                if changed:
                    single_file = create_single_file_download(project_dir, changed[-1])
            yield (response or "No response yet.", conversation_id, status_text,
                   zip_file, single_file, job_id)

        if status not in ["queued", "running"]:
            return
        time.sleep(0.5) # πŸ”₯ Faster UI polling

def resume_job(job_id, request: gr.Request):
    session_id = request.session_hash if request else "default"
    if not job_id:
        yield ("No active job selected.", "Nothing to resume.", None, None)
        return
    while True:
        job = get_job(job_id, session_id)
        if not job:
            yield ("Job not found for this session.", "Job unavailable.", None, None)
            return
        status = job["status"]
        response = job["response"] or ""
        yield (response, f"Job status: {status}", None, None)
        if status not in ["queued", "running"]:
            return
        time.sleep(1.5)

def stop_job(job_id):
    if not job_id:
        return "No active job."
    with job_threads_lock:
        event = job_stop_events.get(job_id)
        if event:
            event.set()
            return "⏹ Stop requested."
    return "No running job found."

# =========================================================
# HISTORY
# =========================================================

def refresh_history(request: gr.Request):
    session_id = request.session_hash if request else "default"
    return gr.Dropdown(choices=get_conversations(session_id), value=None)

def load_selected_history(conversation_id, request: gr.Request):
    session_id = request.session_hash if request else "default"
    if not conversation_id:
        return ("", None, "Select a history item.", None)
    conversation = get_conversation(session_id, conversation_id)
    if not conversation:
        return ("", None, "History not found.", None)
    display = ""
    for item in conversation["history"]:
        role = item.get("role", "assistant").title()
        content = item.get("content", "")
        display += f"\n\n### {role}\n{content}\n"
    active_job = get_active_job(session_id, conversation_id)
    job_id = active_job["id"] if active_job else None
    return (display or "This conversation is empty.", conversation_id,
            f"Loaded: {conversation['title']}", job_id)

def delete_selected_history(conversation_ids, request: gr.Request):
    session_id = request.session_hash if request else "default"
    delete_conversations(session_id, conversation_ids or [])
    return (gr.Dropdown(choices=get_conversations(session_id), value=None), "Selected history deleted.")

def clear_current_conversation():
    return ("", None, "Ready for a new conversation.", None)

def preview_project(conversation_id):
    if not conversation_id:
        return "<p>No project selected.</p>"
    return make_html_preview(get_project_dir(conversation_id))

# =========================================================
# PREMIUM CSS β€” Optimized for Smooth Performance
# =========================================================

CSS = r"""
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;600&display=swap');

:root {
    color-scheme: dark;
    --arise-violet: #8b5cf6;
    --arise-cyan: #22d3ee;
    --arise-pink: #f472b6;
    --arise-deep: #06080f;
}

* { box-sizing: border-box; }

body, .gradio-container {
    font-family: 'Space Grotesk', -apple-system, sans-serif !important;
}

/* πŸ”₯ LAG FIX: Lighter background gradient */
body {
    background:
        radial-gradient(circle at 10% 10%, rgba(139,92,246,0.12), transparent 40%),
        radial-gradient(circle at 90% 20%, rgba(34,211,238,0.08), transparent 40%),
        #06080f !important;
    min-height: 100vh;
    overflow-x: hidden;
    position: relative;
}

/* === CONTAINER === */
.gradio-container {
    width: 100% !important;
    max-width: 1300px !important;
    margin: auto !important;
    background: transparent !important;
    padding: 14px !important;
    position: relative;
    z-index: 1;
    animation: fadeBoot 0.5s ease-out;
}

@keyframes fadeBoot {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* === HEADER BANNER === */
#main-header {
    position: relative;
    overflow: hidden;
    text-align: center;
    padding: 46px 20px;
    border: 1px solid rgba(139,92,246,0.4);
    border-radius: 26px;
    background: linear-gradient(135deg, rgba(45,26,90,0.95) 0%, rgba(9,35,57,0.95) 50%, rgba(30,17,70,0.95) 100%);
    box-shadow: 0 0 40px rgba(139,92,246,0.25);
}

.hero-title {
    font-family: 'Space Grotesk', sans-serif;
    font-size: clamp(32px, 6vw, 62px);
    font-weight: 800;
    letter-spacing: -2px;
    background: linear-gradient(90deg, #fff 0%, #b8a5ff 25%, #56e8ff 50%, #f472b6 75%, #fff 100%);
    background-size: 300% auto;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    animation: heroShine 5s linear infinite;
}

@keyframes heroShine {
    0%   { background-position: 0% center; }
    100% { background-position: 300% center; }
}

.hero-subtitle {
    color: #bdc7df;
    font-size: 13px;
    letter-spacing: 4px;
    margin-top: 14px;
    font-weight: 600;
    text-transform: uppercase;
}

.hero-badges span {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: rgba(255,255,255,0.06);
    padding: 8px 16px;
    border-radius: 30px;
    color: #d8d5ff;
    font-size: 12px;
    font-weight: 500;
    margin: 4px;
    border: 1px solid rgba(255,255,255,0.1);
    transition: all 0.3s ease;
}

.hero-badges span:hover {
    background: rgba(139,92,246,0.25);
    border-color: rgba(139,92,246,0.6);
    box-shadow: 0 0 20px rgba(139,92,246,0.5);
    transform: translateY(-3px);
}

/* === TABS === */
.gradio-container .tab-nav {
    border: 1px solid rgba(139,92,246,0.3) !important;
    border-radius: 18px !important;
    background: rgba(18,24,40,0.85) !important;
    padding: 8px !important;
}

.gradio-container .tab-nav button {
    border-radius: 12px !important;
    transition: all 0.3s ease !important;
    font-weight: 600 !important;
}

.gradio-container .tab-nav button.selected {
    background: linear-gradient(135deg, #7045ed, #168edb) !important;
    color: #fff !important;
    box-shadow: 0 0 25px rgba(139,92,246,0.6) !important;
}

/* === BUTTONS === */
.gradio-container button {
    border-radius: 12px !important;
    transition: all 0.3s ease !important;
    font-weight: 600 !important;
}

.primary {
    background: linear-gradient(135deg, #7045ed 0%, #a855f7 50%, #168edb 100%) !important;
    background-size: 200% 200% !important;
    color: white !important;
    font-weight: 700 !important;
    animation: gradientShift 3s ease infinite;
    box-shadow: 0 4px 20px rgba(139,92,246,0.4) !important;
}

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

/* === INPUTS === */
textarea, input[type="text"], input[type="number"] {
    border-radius: 14px !important;
    background: rgba(15,20,35,0.7) !important;
    border: 1px solid rgba(139,92,246,0.2) !important;
    transition: border-color 0.3s ease !important;
}

textarea:focus, input:focus {
    border-color: rgba(139,92,246,0.7) !important;
    box-shadow: 0 0 0 3px rgba(139,92,246,0.2) !important;
    outline: none !important;
}

/* === CODING OUTPUT === */
#coding-output {
    min-height: 320px;
    padding: 22px;
    border: 1px solid rgba(34,211,238,0.3);
    border-radius: 18px;
    background: linear-gradient(135deg, rgba(9,15,28,0.92), rgba(18,15,40,0.92));
    overflow-wrap: anywhere;
    position: relative;
    box-shadow: 0 0 30px rgba(34,211,238,0.15);
    font-family: 'JetBrains Mono', 'Space Grotesk', monospace;
    font-size: 14px;
    line-height: 1.7;
}

#coding-output pre {
    max-width: 100%;
    overflow-x: auto;
    background: rgba(0,0,0,0.5) !important;
    padding: 14px !important;
    border-radius: 10px !important;
    border: 1px solid rgba(139,92,246,0.15);
}

/* Blinking cursor */
#coding-output.streaming::after {
    content: 'β–‹';
    color: #22d3ee;
    animation: cursorBlink 0.8s step-end infinite;
    margin-left: 2px;
}

@keyframes cursorBlink {
    0%, 50% { opacity: 1; }
    51%, 100% { opacity: 0; }
}

/* === STATUS BADGE === */
#coding-status {
    display: inline-block;
    padding: 8px 16px;
    border-radius: 20px;
    background: rgba(34,211,238,0.1);
    border: 1px solid rgba(34,211,238,0.3);
    color: #a5f3fc;
    font-size: 12px;
    font-weight: 600;
}

/* === SCROLLBAR === */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: rgba(255,255,255,0.03); border-radius: 10px; }
::-webkit-scrollbar-thumb {
    background: linear-gradient(180deg, #8b5cf6, #22d3ee);
    border-radius: 10px;
}

/* === FOOTER === */
#footer {
    text-align: center;
    color: #8390ad;
    padding: 30px 20px;
    border-top: 1px solid rgba(139,92,246,0.15);
    margin-top: 30px;
}

/* === MOBILE === */
@media(max-width: 650px) {
    .gradio-container { padding: 6px !important; }
    #main-header { padding: 28px 12px; border-radius: 18px; }
    .hero-title { font-size: 30px; letter-spacing: -1px; }
    .hero-subtitle { font-size: 10px; letter-spacing: 2px; }
    .gradio-container .tab-nav button { font-size: 11px !important; padding: 8px 5px !important; }
    #coding-output { min-height: 240px; padding: 12px; font-size: 12px; }
}
"""

# =========================================================
# PREMIUM JS (Lightweight & Smooth)
# =========================================================

PREMIUM_JS = """
() => {
    // Cursor effect on streaming output only
    const attachCursor = () => {
        const output = document.querySelector('#coding-output');
        if (!output || output.dataset.cursorAttached) return;
        output.dataset.cursorAttached = '1';

        let streamTimer = null;
        const observer = new MutationObserver(() => {
            output.classList.add('streaming');
            clearTimeout(streamTimer);
            streamTimer = setTimeout(() => output.classList.remove('streaming'), 1200);
        });
        observer.observe(output, { childList: true, subtree: true, characterData: true });
    };

    // Run once on load
    setTimeout(attachCursor, 1000);
}
"""

# =========================================================
# HEADER
# =========================================================

HEADER = """
<div id="main-header">
    <div style="font-size: 12px; color: #83eaff; letter-spacing: 4px; font-weight: 800; margin-bottom: 14px;">
        ✦ NEXT GENERATION ARTIFICIAL INTELLIGENCE ✦
    </div>
    <div class="hero-title">⚑ ARISE AI STUDIO</div>
    <div class="hero-subtitle">CREATE Β· TRANSFORM Β· CODE Β· INNOVATE</div>
    <div class="hero-badges" style="display: flex; justify-content: center; flex-wrap: wrap; gap: 10px; margin-top: 24px;">
        <span>🎨 AI Art</span>
        <span>πŸ–Ό Image Transform</span>
        <span>πŸ’» AI Coding</span>
    </div>
</div>
"""

# =========================================================
# GRADIO APP
# =========================================================

with gr.Blocks(title=APP_NAME) as demo:

    conversation_state = gr.State(None)
    job_state = gr.State(None)

    gr.HTML(HEADER)

    with gr.Row():
        menu_button = gr.Button("☰ Menu", size="sm")
        gr.Markdown(f"[Developer Contact β†—]({DEVELOPER_TELEGRAM})")

    with gr.Column(visible=False, elem_id="menu-panel") as menu_panel:
        gr.Markdown("### ⚑ ARISE AI Studio Menu")
        gr.Markdown(f"**Developer Contact:** [Telegram @hardhackar009]({DEVELOPER_TELEGRAM})")
        gr.Markdown("Open the **History** tab to load, select or delete saved conversations.")

    menu_button.click(lambda: gr.update(visible=True), outputs=menu_panel)

    with gr.Tabs():

        # --- TEXT TO IMAGE ---
        with gr.Tab("🎨 Text to Image"):
            image_model = gr.Dropdown(choices=list(IMAGE_MODELS.keys()), value="SDXL Turbo", label="Select Image Model")
            image_prompt = gr.Textbox(label="Image Prompt", placeholder="Describe your image in detail...", lines=4)
            negative_prompt = gr.Textbox(label="Negative Prompt", lines=2)
            with gr.Row():
                width = gr.Slider(256, 768, value=512, step=64, label="Image Width")
                height = gr.Slider(256, 768, value=512, step=64, label="Image Height")
            steps = gr.Slider(1, 30, value=4, step=1, label="Inference Steps")
            with gr.Row():
                seed = gr.Number(value=0, precision=0, label="Seed")
                random_seed = gr.Checkbox(value=True, label="Random Seed")
            generate_button = gr.Button("✨ Generate Image", variant="primary")
            image_output = gr.Image(label="Generated Artwork", type="pil", height=400)
            seed_output = gr.Number(label="Used Seed", precision=0)

            generate_button.click(
                fn=generate_image,
                inputs=[image_prompt, negative_prompt, image_model, width, height, steps, seed, random_seed],
                outputs=[image_output, seed_output],
            )

        # --- IMAGE TO IMAGE ---
        with gr.Tab("πŸ–Ό Image to Image"):
            input_image = gr.Image(label="Upload Original Image", type="pil", height=300)
            img2img_model = gr.Dropdown(choices=list(IMAGE_TO_IMAGE_MODELS.keys()), value="Stable Diffusion 1.5 Img2Img", label="Image-to-Image Model")
            img2img_prompt = gr.Textbox(label="Transformation Prompt", placeholder="Describe the new image style...", lines=4)
            img2img_negative = gr.Textbox(label="Negative Prompt", lines=2)
            strength = gr.Slider(0.05, 0.95, value=0.70, step=0.05, label="Transformation Strength")
            with gr.Row():
                img2img_steps = gr.Slider(1, 30, value=25, step=1, label="Inference Steps")
                img2img_guidance = gr.Slider(1, 15, value=7.5, step=0.5, label="Guidance Scale")
            with gr.Row():
                img2img_seed = gr.Number(value=0, precision=0, label="Seed")
                img2img_random = gr.Checkbox(value=True, label="Random Seed")
            img2img_button = gr.Button("πŸͺ„ Transform Image", variant="primary")
            img2img_output = gr.Image(label="Transformed Image", type="pil", height=400)
            img2img_seed_output = gr.Number(label="Used Seed", precision=0)

            img2img_button.click(
                fn=generate_image_to_image,
                inputs=[input_image, img2img_prompt, img2img_negative, img2img_model,
                        strength, img2img_steps, img2img_guidance, img2img_seed, img2img_random],
                outputs=[img2img_output, img2img_seed_output],
            )

        # --- AI CODING ---
        with gr.Tab("πŸ’» AI Coding"):
            gr.Markdown("## πŸ’» ARISE AI Coding Workspace")
            code_model = gr.Dropdown(choices=list(CODE_MODELS.keys()), value="Qwen Coder 0.5B", label="Select Coding Model")
            code_prompt = gr.Textbox(label="Your Coding Request", placeholder="Describe your changes...", lines=5)
            with gr.Row():
                max_tokens = gr.Slider(128, 2048, value=768, step=128, label="Maximum Output Tokens")
                temperature = gr.Slider(0.1, 1.0, value=0.3, step=0.1, label="Temperature")
            
            coding_output = gr.Markdown(value="Ready to work on your project.", elem_id="coding-output")
            
            with gr.Row():
                generate_code = gr.Button("⚑ Start Coding", variant="primary")
                stop_button = gr.Button("⏹ Stop", variant="stop")
                new_project_button = gr.Button("οΌ‹ New Project", variant="secondary")
            
            coding_status = gr.Markdown("Ready.", elem_id="coding-status")
            gr.Markdown("### πŸ“¦ Project Downloads")
            
            with gr.Row():
                project_zip_download = gr.File(label="Download Full Project ZIP", interactive=False)
                single_file_download = gr.File(label="Download Last Edited File", interactive=False)
            
            preview_button = gr.Button("🌐 Preview HTML Project")
            html_preview = gr.HTML(value="<div style='padding:15px;color:#aaa'>HTML preview will appear here.</div>")

            generate_code.click(
                fn=coding_assistant,
                inputs=[code_prompt, code_model, max_tokens, temperature, conversation_state],
                outputs=[coding_output, conversation_state, coding_status, project_zip_download, single_file_download, job_state],
            )
            stop_button.click(fn=stop_job, inputs=job_state, outputs=coding_status)
            new_project_button.click(fn=clear_current_conversation, outputs=[coding_output, conversation_state, coding_status, job_state])
            preview_button.click(fn=preview_project, inputs=conversation_state, outputs=html_preview)

        # --- HISTORY ---
        with gr.Tab("πŸ“š History"):
            history_dropdown = gr.Dropdown(choices=[], label="Saved History", interactive=True)
            with gr.Row():
                refresh_history_button = gr.Button("πŸ”„ Refresh History")
                load_history_button = gr.Button("πŸ“‚ Open Selected", variant="primary")
            history_output = gr.Markdown("Select a saved conversation.")
            history_status = gr.Markdown("")
            resume_button = gr.Button("β–Ά Resume Selected Job")
            with gr.Row():
                delete_history_button = gr.Button("πŸ—‘ Delete Selected", variant="stop")
                delete_all_history_button = gr.Button("πŸ—‘ Delete All", variant="stop")

            refresh_history_button.click(fn=refresh_history, outputs=history_dropdown)
            load_history_button.click(fn=load_selected_history, inputs=history_dropdown, outputs=[history_output, conversation_state, history_status, job_state])
            delete_history_button.click(fn=delete_selected_history, inputs=history_dropdown, outputs=[history_dropdown, history_status])

            def delete_all(request: gr.Request):
                session_id = request.session_hash if request else "default"
                ids = [value for _, value in get_conversations(session_id)]
                delete_conversations(session_id, ids)
                return (gr.Dropdown(choices=[], value=None), "All history deleted.")

            delete_all_history_button.click(fn=delete_all, outputs=[history_dropdown, history_status])
            resume_button.click(fn=resume_job, inputs=job_state, outputs=[history_output, history_status, project_zip_download, single_file_download])

    gr.HTML(f"""
    <div id="footer">
        <div style="font-size:22px;font-weight:800;background:linear-gradient(90deg,#c7b7ff,#67e8f9);-webkit-background-clip:text;-webkit-text-fill-color:transparent;margin-bottom:8px;">
            ⚑ ARISE AI STUDIO
        </div>
        <div style="color:#a5b4fc;font-size:13px;">Premium AI Workspace</div>
        <div style="margin-top:10px;font-size:12px;">Developer: <a href="{DEVELOPER_TELEGRAM}" target="_blank" style="color:#67e8f9;">@hardhackar009</a></div>
    </div>
    """)

    demo.load(fn=None, js=PREMIUM_JS)

# =========================================================
# LAUNCH
# =========================================================

if __name__ == "__main__":
    demo.queue(default_concurrency_limit=1, max_size=20).launch(
        theme=gr.themes.Soft(primary_hue="violet", secondary_hue="cyan", neutral_hue="slate"),
        css=CSS,
        allowed_paths=[str(DATA_DIR.resolve())],
        show_error=True,
        share=False,
    )