File size: 50,610 Bytes
ced6a25
 
 
 
 
 
ca97deb
 
 
 
38d4a7e
1935d38
ca97deb
 
1750045
ca97deb
7742f47
9991c95
 
 
 
 
 
 
 
 
 
 
 
7742f47
2f01800
9991c95
eb521b9
ca97deb
 
f02a91d
c3ba67c
 
f02a91d
c3ba67c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47c472c
c3ba67c
ca97deb
32f65a0
582db3a
 
1935d38
 
1a7d9b4
1935d38
582db3a
 
 
1750045
1935d38
 
 
582db3a
1750045
ca97deb
ced6a25
 
 
 
 
6ba6190
f0c29ea
 
582db3a
ced6a25
 
 
9991c95
 
 
 
ced6a25
 
 
 
1750045
fa788e6
 
 
 
 
 
 
 
ced6a25
 
 
 
2210ab4
9991c95
 
 
 
 
 
 
 
2210ab4
9991c95
47c472c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca97deb
32f65a0
47c472c
32f65a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47c472c
582db3a
 
32f65a0
 
 
 
 
582db3a
32f65a0
 
 
 
 
 
 
 
 
582db3a
32f65a0
 
 
47c472c
32f65a0
582db3a
 
 
47c472c
 
 
 
 
 
 
 
582db3a
af6ede9
47c472c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
582db3a
c7971eb
ca97deb
 
47c472c
 
 
 
c7971eb
 
ca97deb
 
47c472c
 
 
 
f02a91d
 
 
 
 
 
 
ca97deb
 
 
0416926
47c472c
c3ba67c
0416926
c3ba67c
0416926
 
 
 
 
 
 
 
 
 
9481e69
0416926
47c472c
0416926
9481e69
c3ba67c
0416926
9481e69
 
 
ca97deb
9481e69
c3ba67c
 
0416926
 
47c472c
0416926
 
47c472c
 
0416926
 
 
 
 
 
 
 
 
 
 
47c472c
0416926
 
 
 
 
ca97deb
1750045
6ba6190
47c472c
 
 
 
 
 
 
 
 
 
 
 
 
6ba6190
47c472c
0416926
 
 
 
 
 
 
32f65a0
 
ca97deb
f02a91d
9991c95
ca97deb
47c472c
9991c95
32f65a0
2210ab4
ca97deb
32f65a0
 
 
 
 
1935d38
1750045
47c472c
 
2210ab4
47c472c
 
 
ced6a25
1935d38
32f65a0
 
ca97deb
47c472c
 
f02a91d
47c472c
1750045
47c472c
 
 
 
 
 
 
 
ced6a25
c7971eb
9991c95
47c472c
 
 
 
 
 
 
 
9991c95
 
32f65a0
ca97deb
47c472c
9991c95
47c472c
0416926
 
 
47c472c
 
 
 
 
0416926
 
47c472c
f02a91d
9991c95
c7971eb
47c472c
8d7ac9a
32f65a0
8d7ac9a
47c472c
 
8d7ac9a
47c472c
f0c29ea
1750045
f0c29ea
47c472c
 
1750045
 
47c472c
5b950ab
 
47c472c
 
 
 
5b950ab
47c472c
 
 
 
 
 
 
 
 
f02a91d
 
 
47c472c
f02a91d
 
 
582db3a
5b950ab
582db3a
32f65a0
7a1f3e6
f91438e
9481e69
47c472c
 
 
9481e69
f02a91d
 
 
 
 
 
9481e69
 
 
c3ba67c
 
f02a91d
9481e69
f02a91d
c3ba67c
f02a91d
9481e69
f02a91d
 
9481e69
 
 
 
 
582db3a
9481e69
 
 
 
c3ba67c
9481e69
 
 
 
 
c3ba67c
9481e69
 
47c472c
0416926
 
 
 
 
 
 
 
c3ba67c
7a1f3e6
c3ba67c
 
9481e69
47c472c
9481e69
 
 
 
 
 
 
 
 
 
 
 
f02a91d
47c472c
9481e69
 
c3ba67c
47c472c
0416926
47c472c
 
 
 
 
 
 
9481e69
582db3a
f91438e
 
ca97deb
47c472c
 
 
 
9481e69
c3ba67c
9481e69
0416926
47c472c
 
 
 
f91438e
7a1f3e6
9481e69
 
 
8d7ac9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1750045
 
47c472c
 
 
 
 
f91438e
1750045
47c472c
 
3c1a2de
5b950ab
 
f91438e
32f65a0
5b950ab
 
 
47c472c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32f65a0
8d7ac9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47c472c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d7ac9a
 
47c472c
 
 
 
 
 
 
 
 
5b950ab
1750045
9991c95
47c472c
 
 
 
ca97deb
47c472c
 
 
 
c3ba67c
 
47c472c
ced6a25
c7971eb
47c472c
 
 
 
 
 
9481e69
c7971eb
1750045
ced6a25
1750045
47c472c
 
 
 
 
 
 
 
 
1750045
582db3a
f02a91d
47c472c
f02a91d
47c472c
 
f02a91d
1750045
ced6a25
1750045
47c472c
ca97deb
47c472c
ca97deb
47c472c
 
 
 
 
 
 
 
 
 
 
 
 
 
1750045
47c472c
 
 
 
 
 
 
 
 
 
 
 
 
8f59b64
47c472c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f02a91d
47c472c
0416926
 
 
 
 
 
47c472c
f02a91d
 
47c472c
 
 
 
 
 
 
 
ca97deb
47c472c
 
 
 
 
 
 
 
 
 
 
 
1750045
7742f47
8f59b64
1750045
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
import os
import gradio as gr
import numpy as np
import spaces
import torch
import random
from PIL import Image, ImageFilter
from typing import Iterable
from gradio.themes import Soft
from gradio.themes.utils import colors, fonts, sizes
from deep_translator import GoogleTranslator
from transformers import pipeline
from datetime import date
import json

# --- تعریف تم ---
colors.steel_blue = colors.Color(
    name="steel_blue",
    c50="#EBF3F8",
    c100="#D3E5F0",
    c200="#A8CCE1",
    c300="#7DB3D2",
    c400="#529AC3",
    c500="#4682B4",
    c600="#3E72A0",
    c700="#36638C",
    c800="#2E5378",
    c900="#264364",
    c950="#1E3450",
)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# --- تنظیمات سیستم اعتبار ---
USAGE_LIMIT = 5
DATA_FILE = "usage_data.json" 
PREMIUM_PAGE_ID = '1149636'

# --- مدیریت ذخیره‌سازی داده‌ها ---
def load_usage_data():
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, 'r') as f:
                return json.load(f)
        except:
            return {}
    return {}

def save_usage_data(data):
    try:
        with open(DATA_FILE, 'w') as f:
            json.dump(data, f)
    except Exception as e:
        print(f"Error saving data: {e}")

# بارگذاری اولیه داده‌ها
usage_data_cache = load_usage_data()

# --- بارگذاری مدل تشخیص محتوای نامناسب (Image Safety) ---
print("Loading Safety Checker...")
safety_classifier = pipeline("image-classification", model="Falconsai/nsfw_image_detection", device=-1)

def is_image_nsfw(image):
    if image is None: return False
    try:
        results = safety_classifier(image)
        for result in results:
            if result['label'] == 'nsfw' and result['score'] > 0.75:
                return True
        return False
    except Exception as e:
        print(f"Safety check error: {e}")
        return False

# --- بارگذاری مدل اصلی ---
from diffusers import FlowMatchEulerDiscreteScheduler
from qwenimage.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline
from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel
from qwenimage.qwen_fa3_processor import QwenDoubleStreamAttnProcessorFA3

dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"

print("Loading pipeline...")
pipe = QwenImageEditPlusPipeline.from_pretrained(
    "Qwen/Qwen-Image-Edit-2509",
    transformer=QwenImageTransformer2DModel.from_pretrained(
        "linoyts/Qwen-Image-Edit-Rapid-AIO",
        subfolder='transformer',
        torch_dtype=dtype,
        device_map='cuda'
    ),
    torch_dtype=dtype
).to(device)

# بارگذاری LoRA ها
pipe.load_lora_weights("autoweeb/Qwen-Image-Edit-2509-Photo-to-Anime", weight_name="Qwen-Image-Edit-2509-Photo-to-Anime_000001000.safetensors", adapter_name="anime")
pipe.load_lora_weights("dx8152/Qwen-Edit-2509-Multiple-angles", weight_name="镜头转换.safetensors", adapter_name="multiple-angles")
pipe.load_lora_weights("dx8152/Qwen-Image-Edit-2509-Light_restoration", weight_name="移除光影.safetensors", adapter_name="light-restoration")
pipe.load_lora_weights("dx8152/Qwen-Image-Edit-2509-Relight", weight_name="Qwen-Edit-Relight.safetensors", adapter_name="relight")
pipe.load_lora_weights("dx8152/Qwen-Edit-2509-Multi-Angle-Lighting", weight_name="多角度灯光-251116.safetensors", adapter_name="multi-angle-lighting")
pipe.load_lora_weights("tlennon-ie/qwen-edit-skin", weight_name="qwen-edit-skin_1.1_000002750.safetensors", adapter_name="edit-skin")
pipe.load_lora_weights("lovis93/next-scene-qwen-image-lora-2509", weight_name="next-scene_lora-v2-3000.safetensors", adapter_name="next-scene")
pipe.load_lora_weights("vafipas663/Qwen-Edit-2509-Upscale-LoRA", weight_name="qwen-edit-enhance_64-v3_000001000.safetensors", adapter_name="upscale-image")

pipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessorFA3())
MAX_SEED = np.iinfo(np.int32).max

LORA_MAPPING = {
    "تبدیل عکس به انیمه": "anime",
    "تغییر زاویه دید": "multiple-angles",
    "اصلاح نور و سایه": "light-restoration",
    "نورپردازی مجدد (Relight)": "relight",
    "نورپردازی چند زاویه‌ای": "multi-angle-lighting",
    "روتوش پوست": "edit-skin",
    "صحنه بعدی (سینمایی)": "next-scene",
    "افزایش کیفیت (Upscale)": "upscale-image"
}

ASPECT_RATIOS_LIST = [
    "خودکار (پیش‌فرض)",
    "۱:۱ (مربع - 1024x1024)",
    "۱۶:۹ (افقی - 1344x768)",
    "۹:۱۶ (عمودی - 768x1344)",
    "شخصی‌سازی (Custom)"
]

ASPECT_RATIOS_MAP = {
    "خودکار (پیش‌فرض)": "Auto",
    "۱:۱ (مربع - 1024x1024)": (1024, 1024),
    "۱۶:۹ (افقی - 1344x768)": (1344, 768),
    "۹:۱۶ (عمودی - 768x1344)": (768, 1344),
    "شخصی‌سازی (Custom)": "Custom"
}

# --- لیست کلمات ممنوعه پیشرفته (Strict Mode) ---
BANNED_WORDS = [
    # General NSFW
    "nsfw", "nude", "naked", "sex", "porn", "erotic", "xxx", "18+", "adult",
    "explicit", "uncensored", "sexual", "lewd", "sensual", "lust", "horny",
    
    # Anatomy (Explicit)
    "breast", "breasts", "nipple", "nipples", "vagina", "pussy", "cunt",
    "penis", "dick", "cock", "genital", "genitals", "groin", "pubic",
    "ass", "butt", "buttocks", "anus", "anal", "rectum",
    
    # Acts / Concepts
    "intercourse", "masturbation", "orgasm", "blowjob", "bj", "cum", "sperm",
    "ejaculation", "penetration", "fucking", "sucking", "licking",
    
    # Clothing / Lingerie
    "lingerie", "bikini", "swimwear", "underwear", "panties", "bra", "thong",
    "topless", "bottomless", "undressed", "unclothed", "skimpy", "transparent",
    "see-through",
    
    # Fetish / Styles
    "fetish", "bdsm", "bondage", "latex", "hentai", "ecchi", "ahegao",
    "exhibitionism", "voyeur", "harem",
    
    # Violence / Gore (Optional but recommended for strict safety)
    "gore", "bloody", "blood", "kill", "murder", "dead", "torture", "abuse"
]

def check_text_safety(text):
    """
    بررسی وجود کلمات ممنوعه در متن انگلیسی.
    از متد whole word matching ساده استفاده می‌کند تا کلماتی مثل 'assassin' اشتباهاً حذف نشوند.
    """
    if not text: return True
    text_lower = text.lower()
    
    # نرمال‌سازی متن برای جستجوی دقیق‌تر
    # اضافه کردن فاصله به اول و آخر متن برای تشخیص کلمات اول و آخر جمله
    padded_text = f" {text_lower} "
    
    # حذف علائم نگارشی برای جلوگیری از دور زدن فیلتر (مثلاً sex.)
    for char in [".", ",", "!", "?", "-", "_", "(", ")", "[", "]", "{", "}"]:
        padded_text = padded_text.replace(char, " ")
    
    for word in BANNED_WORDS:
        # جستجو به صورت کلمه مستقل
        if f" {word} " in padded_text: 
            print(f"Safety Triggered: Found banned word '{word}'")
            return False
            
    return True

def translate_prompt(text):
    if not text:
        return ""
    try:
        translated = GoogleTranslator(source='auto', target='en').translate(text)
        return translated
    except Exception as e:
        print(f"Translation Error: {e}")
        return text

def update_dimensions_on_upload(image):
    if image is None:
        return 1024, 1024
    original_width, original_height = image.size
    if original_width > original_height:
        new_width = 1024
        aspect_ratio = original_height / original_width
        new_height = int(new_width * aspect_ratio)
    else:
        new_height = 1024
        aspect_ratio = original_width / original_height
        new_width = int(new_height * aspect_ratio)
    new_width = (new_width // 8) * 8
    new_height = (new_height // 8) * 8
    return new_width, new_height

def update_sliders_visibility(choice):
    if choice == "شخصی‌سازی (Custom)":
        return gr.update(visible=True), gr.update(visible=True)
    else:
        return gr.update(visible=False), gr.update(visible=False)

def get_error_html(message):
    return f"""
    <div style="background-color: #fee2e2; border: 1px solid #ef4444; color: #b91c1c; padding: 12px; border-radius: 8px; text-align: center; margin-bottom: 10px; font-weight: bold; display: flex; align-items: center; justify-content: center; gap: 8px;">
        <span style="font-size: 1.2em;">⛔</span>
        {message}
    </div>
    """

def get_success_html(message):
    return f"""
    <div style="background-color: #dcfce7; border: 1px solid #22c55e; color: #15803d; padding: 12px; border-radius: 8px; text-align: center; margin-bottom: 10px; font-weight: bold; display: flex; align-items: center; justify-content: center; gap: 8px;">
        <span style="font-size: 1.2em;">✅</span>
        {message}
    </div>
    """

def get_quota_exceeded_html():
    return """
    <div style="background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%); border: 2px solid #f59e0b; padding: 20px; border-radius: 16px; text-align: center; box-shadow: 0 4px 15px rgba(245, 158, 11, 0.1);">
        <div style="font-size: 3rem; margin-bottom: 10px;">💎</div>
        <h3 style="color: #92400e; margin: 0 0 10px 0; font-weight: 800;">اعتبار رایگان امروز تمام شد</h3>
        <p style="color: #b45309; margin: 0; font-size: 0.95em;">شما از ۵ تصویر رایگان امروز استفاده کرده‌اید.<br>برای ساخت تصاویر نامحدود و حرفه‌ای، لطفا نسخه خود را ارتقا دهید.</p>
    </div>
    """

def get_user_record(fingerprint):
    """خواندن رکورد کاربر از دیتابیس بدون اعمال تغییرات"""
    global usage_data_cache
    if not fingerprint: return None
    
    # Reload to get fresh data
    usage_data_cache = load_usage_data()
    today_str = date.today().isoformat()
    
    user_record = usage_data_cache.get(fingerprint)
    
    if not user_record or user_record.get("last_reset") != today_str:
        return {"count": 0, "last_reset": today_str}
        
    return user_record

def consume_quota(fingerprint):
    """کسر اعتبار کاربر"""
    global usage_data_cache
    today_str = date.today().isoformat()
    usage_data_cache = load_usage_data()
    
    user_record = usage_data_cache.get(fingerprint)
    if not user_record or user_record.get("last_reset") != today_str:
        user_record = {"count": 0, "last_reset": today_str}
    
    user_record["count"] += 1
    usage_data_cache[fingerprint] = user_record
    save_usage_data(usage_data_cache)
    return user_record["count"]

# --- تابع بررسی اولیه (بدون GPU) برای نمایش/مخفی کردن دکمه‌ها ---
def check_initial_quota(fingerprint, subscription_status):
    """
    این تابع به محض لود شدن صفحه توسط جاوا اسکریپت صدا زده می‌شود.
    اگر اعتبار تمام شده باشد، دکمه ساخت را مخفی و دکمه ارتقا را نشان می‌دهد.
    """
    if not fingerprint:
        return gr.update(visible=True), gr.update(visible=False), None

    if subscription_status == 'paid':
        return gr.update(visible=True), gr.update(visible=False), None
    
    user_record = get_user_record(fingerprint)
    current_usage = user_record["count"] if user_record else 0
    
    if current_usage >= USAGE_LIMIT:
        # اعتبار تمام شده
        return gr.update(visible=False), gr.update(visible=True), get_quota_exceeded_html()
    else:
        # اعتبار دارد
        return gr.update(visible=True), gr.update(visible=False), None


@spaces.GPU(duration=30)
def infer(
    input_image,
    prompt,
    lora_adapter_persian,
    seed,
    randomize_seed,
    guidance_scale,
    steps,
    aspect_ratio_selection,
    custom_width,
    custom_height,
    fingerprint,
    subscription_status,
    progress=gr.Progress(track_tqdm=True)
):
    # بررسی نهایی اعتبار قبل از شروع پردازش سنگین
    if subscription_status != 'paid':
        user_record = get_user_record(fingerprint)
        if user_record and user_record["count"] >= USAGE_LIMIT:
             return (
                None, seed, get_quota_exceeded_html(), 
                gr.update(visible=False), gr.update(visible=True)
            )
    
    # --- بررسی‌های اولیه (تصویر و متن) قبل از کسر اعتبار ---
    if input_image is None:
        return None, seed, get_error_html("لطفاً ابتدا یک تصویر بارگذاری کنید."), gr.update(visible=True), gr.update(visible=False)

    if is_image_nsfw(input_image):
        return None, seed, get_error_html("تصویر ورودی دارای محتوای نامناسب است و پردازش نمی‌شود."), gr.update(visible=True), gr.update(visible=False)

    # ترجمه و بررسی متن (مهم: قبل از کسر اعتبار)
    english_prompt = translate_prompt(prompt)
    if not check_text_safety(english_prompt):
        return None, seed, get_error_html("متن درخواست شامل کلمات غیرمجاز، جنسی یا خشونت‌آمیز است. لطفاً متن را اصلاح کنید."), gr.update(visible=True), gr.update(visible=False)

    # اگر همه چیز امن بود، حالا اعتبار را کسر می‌کنیم
    if subscription_status != 'paid':
        consume_quota(fingerprint)

    adapter_internal_name = LORA_MAPPING.get(lora_adapter_persian)
    if adapter_internal_name:
        pipe.set_adapters([adapter_internal_name], adapter_weights=[1.0])
    
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)

    generator = torch.Generator(device=device).manual_seed(seed)
    
    # اضافه کردن کلمات منفی ایمنی به صورت پیش‌فرض به پرامپت منفی
    safety_negative = "nsfw, nude, naked, porn, sexual, xxx, breast, nipple, genital, vagina, penis, ass, lingerie, bikini, swimwear, underwear, fetish, topless, gore, violence, blood, explicit"
    base_negative = "worst quality, low quality, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, jpeg artifacts, signature, watermark, username, blurry"
    final_negative_prompt = f"{safety_negative}, {base_negative}"

    original_image = input_image.convert("RGB")
    
    selection_value = ASPECT_RATIOS_MAP.get(aspect_ratio_selection)
    
    if selection_value == "Custom":
        width = (int(custom_width) // 8) * 8
        height = (int(custom_height) // 8) * 8
    elif selection_value == "Auto" or selection_value is None:
        width, height = update_dimensions_on_upload(original_image)
    else:
        width, height = selection_value

    try:
        result = pipe(
            image=original_image,
            prompt=english_prompt,
            negative_prompt=final_negative_prompt,
            height=height,
            width=width,
            num_inference_steps=steps,
            generator=generator,
            true_cfg_scale=guidance_scale,
        ).images[0]

        # بررسی نهایی تصویر تولید شده
        if is_image_nsfw(result):
            return None, seed, get_error_html("تصویر تولید شده حاوی محتوای نامناسب بود و حذف شد."), gr.update(visible=True), gr.update(visible=False)
        
        # محاسبه اعتبار باقی‌مانده برای نمایش
        user_record = get_user_record(fingerprint)
        remaining = USAGE_LIMIT - user_record["count"] if user_record else 0
        
        success_msg = f"تصویر با موفقیت ویرایش شد."
        if subscription_status != 'paid':
             success_msg += f" (اعتبار باقی‌مانده امروز: {remaining})"

        # اگر با این درخواست اعتبار تمام شد، دکمه‌ها را آپدیت می‌کنیم
        if subscription_status != 'paid' and remaining <= 0:
             return result, seed, get_success_html(success_msg), gr.update(visible=False), gr.update(visible=True)

        return result, seed, get_success_html(success_msg), gr.update(visible=True), gr.update(visible=False)

    except Exception as e:
        error_str = str(e)
        # -------------------------------------------------------------
        #  مدیریت خطای GPU QUOTA
        # -------------------------------------------------------------
        if "quota" in error_str.lower() or "exceeded" in error_str.lower():
             raise e 
        
        return None, seed, get_error_html(f"خطا در پردازش: {error_str}"), gr.update(visible=True), gr.update(visible=False)

@spaces.GPU(duration=30)
def infer_example(input_image, prompt, lora_adapter):
    # مثال‌ها اعتبار کم نمی‌کنند
    res, s, status, btn1, btn2 = infer(input_image, prompt, lora_adapter, 0, True, 1.0, 4, "خودکار (پیش‌فرض)", 1024, 1024, "example_user", "paid")
    return res, s, status

# --- جاوااسکریپت برای دکمه دانلود ---
js_download_func = """
async (image) => {
    if (!image) {
        alert("لطفاً ابتدا تصویر را تولید کنید.");
        return;
    }
    let fileUrl = image.url;
    if (fileUrl && !fileUrl.startsWith('http')) {
       fileUrl = window.location.origin + fileUrl;
    } else if (!fileUrl && image.path) {
       fileUrl = window.location.origin + "/file=" + image.path;
    }
    window.parent.postMessage({
        type: 'DOWNLOAD_REQUEST',
        url: fileUrl
    }, '*');
}
"""

# --- جاوااسکریپت برای دکمه ارتقا ---
js_upgrade_func = """
() => {
    window.parent.postMessage({ type: 'NAVIGATE_TO_PREMIUM' }, '*');
}
"""

# --- جاوااسکریپت سراسری ---
js_global_content = """
<script>
document.addEventListener('DOMContentLoaded', () => {
    // ---------------------------------------------
    // 1. Fingerprint & Subscription Logic
    // ---------------------------------------------
    async function getBrowserFingerprint() {
        const components = [];
        components.push(navigator.userAgent);
        components.push(navigator.language);
        components.push(screen.colorDepth);
        components.push(screen.width + 'x' + screen.height);
        components.push(new Date().getTimezoneOffset());
        try {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            ctx.textBaseline = "top"; ctx.font = "14px 'Arial'"; ctx.textBaseline = "alphabetic";
            ctx.fillStyle = "#f60"; ctx.fillRect(125, 1, 62, 20);
            ctx.fillStyle = "#069"; ctx.fillText("Alpha_AI_Fingerprint_v1_!@#", 2, 15);
            components.push(canvas.toDataURL());
        } catch (e) { components.push("canvas-err"); }
        
        const str = components.join('~~~');
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash |= 0;
        }
        return 'fp_' + Math.abs(hash).toString(16);
    }

    function isUserPaid(userObject) {
        const PREMIUM_PAGE_ID = '1149636'; 
        if (userObject && userObject.isLogin && userObject.accessible_pages) {
            if (Array.isArray(userObject.accessible_pages)) {
                 return userObject.accessible_pages.some(page => String(page) === String(PREMIUM_PAGE_ID));
            }
        }
        return false;
    }

    function updateHiddenInputs(fingerprint, status) {
        const fpInput = document.querySelector('#fingerprint_storage textarea');
        const stInput = document.querySelector('#status_storage textarea');
        
        if(fpInput && fingerprint && fpInput.value !== fingerprint) { 
            fpInput.value = fingerprint; 
            fpInput.dispatchEvent(new Event('input', { bubbles: true })); 
        }
        if(stInput && status && stInput.value !== status) { 
            stInput.value = status; 
            stInput.dispatchEvent(new Event('input', { bubbles: true })); 
        }
    }

    function updateSubscriptionBadge(status) {
        const badge = document.getElementById('user-sub-badge');
        if (!badge) return;
        
        if (status === 'paid') {
            badge.innerHTML = '✨ اشتراک: <span style="color: #FFD700; font-weight: bold;">نامحدود (PRO)</span>';
            badge.style.background = 'linear-gradient(45deg, #1e3a8a, #3b82f6)';
        } else {
            badge.innerHTML = '👤 اشتراک: <span style="color: #fff; font-weight: bold;">رایگان (۵ اعتبار روزانه)</span>';
            badge.style.background = 'linear-gradient(45deg, #4b5563, #6b7280)';
        }
        badge.style.display = 'inline-block';
    }

    async function initUserIdentity() {
        window.userFingerprint = await getBrowserFingerprint();
        window.userStatus = 'free'; 
        
        window.parent.postMessage({ type: 'REQUEST_USER_STATUS' }, '*');
        updateSubscriptionBadge('free');
        
        // Initial update
        updateHiddenInputs(window.userFingerprint, window.userStatus);
        
        // Polling to ensure inputs stay synced
        setInterval(() => {
            if(window.userFingerprint) {
                updateHiddenInputs(window.userFingerprint, window.userStatus || 'free');
            }
        }, 1500);
    }

    window.addEventListener('message', (event) => {
        if (event.data && event.data.type === 'USER_STATUS_RESPONSE') {
            try {
                const userObject = typeof event.data.payload === 'string' 
                                   ? JSON.parse(event.data.payload) 
                                   : event.data.payload;
                
                const status = isUserPaid(userObject) ? 'paid' : 'free';
                window.userStatus = status;
                updateSubscriptionBadge(status);
                updateHiddenInputs(window.userFingerprint, status);
            } catch (e) {
                console.error("Error parsing user status:", e);
                updateSubscriptionBadge('free');
            }
        }
    });

    initUserIdentity();

    // ---------------------------------------------
    // 2. GPU QUOTA HANDLER (Modal & Scanner)
    // ---------------------------------------------
    
    // RETRY FUNCTION
    window.retryGeneration = function() {
        const modal = document.getElementById('custom-quota-modal');
        if (modal) modal.remove();

        const runBtn = document.getElementById('run-btn');
        if(runBtn) runBtn.click();
    };
    
    // Close function
    window.closeErrorModal = function() {
         const modal = document.getElementById('custom-quota-modal');
         if (modal) modal.remove();
    };

    // SHOW MODAL FUNCTION
    const showQuotaModal = () => {
        if (document.getElementById('custom-quota-modal')) return;

        const modalHtml = `
            <div id="custom-quota-modal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); backdrop-filter: blur(5px); z-index: 99999; display: flex; align-items: center; justify-content: center; font-family: 'Vazirmatn', sans-serif;">
                <div class="ip-reset-guide-container">
                    <div class="guide-header">
                        <svg class="guide-header-icon" viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> 
                            <defs><lineargradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" style="stop-color: #667eea; stop-opacity: 1;"></stop><stop offset="100%" style="stop-color: #764ba2; stop-opacity: 1;"></stop></lineargradient></defs> 
                            <circle cx="50" cy="50" r="45" fill="url(#grad1)" opacity="0.1"></circle>
                            <circle cx="50" cy="50" r="35" fill="none" stroke="url(#grad1)" stroke-width="2" opacity="0.3"></circle>
                            <path d="M35 50 L45 60 L65 40" stroke="url(#grad1)" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round"></path>
                            <circle cx="65" cy="35" r="8" fill="#fee140"></circle>
                            <path d="M62 35 L68 35 M65 32 L65 38" stroke="white" stroke-width="2" stroke-linecap="round"></path> 
                        </svg>
                        <div>
                            <h2>یک قدم تا ساخت تصاویر جدید</h2>
                            <p>نیازمند تغییر نقطه دستیابی</p>
                        </div>
                    </div>
                    
                    <div class="guide-content">
                        <div class="info-card">
                            <div class="info-card-header">
                                <svg class="info-card-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" fill="#667eea" opacity="0.2"></path><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="#667eea" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg> 
                                <span class="info-card-title">راه حل سریع</span>
                            </div>
                            <p>طبق ویدیو آموزشی پایین بین نقطه دستیابی جابجا شوید تلاش مجدد بزنید تا تصاویر مجدداً تولید بشه.</p>
                        </div>
                        
                        <div class="summary-section">
                            <div class="summary-header">
                                <svg class="summary-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="#56ab2f" opacity="0.2"></circle><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" stroke="#56ab2f" stroke-width="2"></path><path d="M9 12l2 2 4-4" stroke="#56ab2f" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg> 
                                <span class="summary-title">خلاصه راهنما</span>
                            </div>
                            <div class="summary-text">هربار که این صفحه را مشاهده کردید: از اینترنت سیم‌کارت استفاده کنید، VPN را خاموش کرده و طبق ویدیو آموزشی پایین نقطه دستیابی رو تغییر دهید. «تلاش مجدد» کلیک کنید. با این روش ساده می‌توانید به صورت نامحدود تصویر بسازید! ☘️</div>
                        </div>
                        
                        <div class="video-button-container">
                            <button onclick="parent.postMessage({ type: 'NAVIGATE_TO_URL', url: '#/nav/online/news/getSingle/1149635/eyJpdiI6IjhHVGhPQWJwb3E0cjRXbnFWTW5BaUE9PSIsInZhbHVlIjoiS1V0dTdvT21wbXAwSXZaK1RCTG1pVXZqdlFJa1hXV1RKa2FLem9zU3pXMjd5MmlVOGc2YWY0NVdNR3h3Smp1aSIsIm1hYyI6IjY1NTA5ZDYzMjAzMTJhMGQyMWQ4NjA4ZDgyNGZjZDVlY2MyNjdiMjA2NWYzOWRjY2M4ZmVjYWRlMWNlMWQ3ODEiLCJ0YWciOiIifQ==/21135210' }, '*')" class="elegant-video-button"> 
                                <svg class="elegant-video-button-icon" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg> 
                                <span>دیدن ویدیو آموزشی استفاده نامحدود</span> 
                            </button>
                        </div>
                    </div>
                    
                    <div class="guide-actions">
                        <button class="action-button back-button" onclick="window.closeErrorModal()"> 
                            <svg class="action-button-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg> 
                            <span>بازگشت</span> 
                        </button>
                        <button class="action-button retry-button" onclick="window.retryGeneration()"> 
                            <svg class="action-button-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M23 4v6h-6M1 20v-6h6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg> 
                            <span>تلاش مجدد</span> 
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', modalHtml);

        // Auto close after 10 seconds
        setTimeout(() => {
            window.closeErrorModal();
        }, 10000);
    };

    // ERROR SCANNER
    setInterval(() => {
        const potentialErrors = document.querySelectorAll('.toast-body, .error, .toast-wrap, .eta-bar, div[class*="error"]');
        
        potentialErrors.forEach(el => {
            const text = el.innerText || "";
            if (text.toLowerCase().includes('quota') || text.toLowerCase().includes('exceeded')) {
                 
                 showQuotaModal();
                 
                 // Immediately hide the Gradio error
                 el.style.display = 'none';
                 el.style.opacity = '0';
                 el.innerText = '';
                 
                 const parentWrap = el.closest('.toast-wrap');
                 if(parentWrap) parentWrap.style.display = 'none';
            }
        });
    }, 100);

    // ---------------------------------------------
    // 3. Force Light Mode
    // ---------------------------------------------
    const forceLight = () => {
        const body = document.querySelector('body');
        if (body) {
            body.classList.remove('dark');
            body.style.backgroundColor = '#f5f7fa';
            body.style.color = '#333333';
        }
        document.querySelectorAll('.dark').forEach(el => el.classList.remove('dark'));
    };
    forceLight();
    setInterval(forceLight, 1000);
});
</script>
"""

# --- CSS Updated ---
css_code = """
<style>
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;700&display=swap');

:root, .dark, body, .gradio-container {
    --body-background-fill: #f5f7fa !important;
    --body-text-color: #1f2937 !important;
    --background-fill-primary: #ffffff !important;
    --background-fill-secondary: #f3f4f6 !important;
    --border-color-primary: #e5e7eb !important;
    --block-background-fill: #ffffff !important;
    --block-label-text-color: #374151 !important;
    --block-title-text-color: #111827 !important;
    --input-background-fill: #ffffff !important;
    color-scheme: light !important;
    font-family: 'Vazirmatn', sans-serif !important;
}

/* --- IP Reset Guide CSS (مودال) --- */
:root {
    --guide-bg: rgba(255, 255, 255, 0.98);
    --guide-border: rgba(102, 126, 234, 0.2);
    --guide-text-title: #2d3748;
    --guide-text-body: #4a5568;
    --guide-accent: #667eea;
    --primary-gradient-guide: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    --success-gradient-guide: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
    --radius-md-guide: 12px;
    --radius-lg-guide: 16px;
    --shadow-sm: 0 1px 2px 0 rgba(26, 32, 44, 0.03);
    --shadow-md: 0 4px 6px -1px rgba(26, 32, 44, 0.05), 0 2px 4px -2px rgba(26, 32, 44, 0.04);
    --shadow-xl: 0 20px 25px -5px rgba(26, 32, 44, 0.07), 0 8px 10px -6px rgba(26, 32, 44, 0.05);
}

@keyframes float {
    0%, 100% { transform: translateY(0px); }
    50% { transform: translateY(-10px); }
}
@keyframes slideInUp {
    from { opacity: 0; transform: translateY(30px); }
    to { opacity: 1; transform: translateY(0); }
}

.ip-reset-guide-container {
    text-align: right; 
    direction: rtl; 
    background: var(--guide-bg); 
    backdrop-filter: blur(10px);
    padding: 20px;
    border-radius: var(--radius-lg-guide);
    box-shadow: var(--shadow-xl); 
    border: 1px solid var(--guide-border); 
    animation: slideInUp 0.6s cubic-bezier(0.4, 0, 0.2, 1) both;
    width: 90%; 
    max-width: 420px;
    max-height: 90vh;
    overflow-y: auto;
    position: relative; 
    box-sizing: border-box;
    font-family: 'Vazirmatn', sans-serif !important;
}
.ip-reset-guide-container::before {
    content: ''; position: absolute; top: 0; left: 0; right: 0; height: 4px; background: var(--primary-gradient-guide);
}
.guide-header { display: flex; align-items: center; margin-bottom: 15px; }
.guide-header-icon { width: 45px; height: 45px; margin-left: 15px; animation: float 3s ease-in-out infinite; flex-shrink: 0; }
.guide-header h2 { font-size: 1.2rem; color: var(--guide-text-title); font-weight: 700; margin: 0; }
.guide-header p { color: var(--guide-text-body); font-size: 0.8rem; margin-top: 3px; margin-bottom: 0; }

.guide-content { font-size: 0.9rem; color: var(--guide-text-body); line-height: 1.6; }

.info-card { background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%); border: 1px solid rgba(102, 126, 234, 0.2); border-radius: var(--radius-md-guide); padding: 12px; margin: 12px 0; position: relative; overflow: hidden; }
.info-card p { font-size: 0.85rem; line-height: 1.6; margin: 0; }
.info-card::before { content: ''; position: absolute; top: 0; right: 0; width: 3px; height: 100%; background: var(--primary-gradient-guide); }
.info-card-header { display: flex; align-items: center; margin-bottom: 8px; }
.info-card-icon { width: 18px; height: 18px; margin-left: 8px; }
.info-card-title { font-weight: 600; color: var(--guide-text-title); font-size: 0.95rem; }

.summary-section { margin-top: 12px; padding: 12px; border-radius: var(--radius-md-guide); background: linear-gradient(135deg, #56ab2f15 0%, #a8e06315 100%); border: 1px solid rgba(86, 171, 47, 0.2); position: relative; overflow: hidden; }
.summary-section::before { content: ''; position: absolute; top: 0; right: 0; width: 3px; height: 100%; background: var(--success-gradient-guide); }
.summary-header { display: flex; align-items: center; margin-bottom: 8px; }
.summary-icon { width: 18px; height: 18px; margin-left: 8px; }
.summary-title { font-weight: 600; color: #2f5a33; font-size: 0.95rem; }
.summary-text { color: #2f5a33; font-size: 0.85rem; line-height: 1.6; }

.video-button-container { text-align: center; margin: 20px 0 15px 0; width: 100%; }
.elegant-video-button { 
    display: inline-flex !important; 
    align-items: center; 
    justify-content: center; 
    padding: 10px 20px !important; 
    background-color: #fff !important; 
    color: var(--guide-accent) !important; 
    border: 1px solid #e2e8f0 !important; 
    text-decoration: none; 
    border-radius: 50px !important; 
    font-weight: 600 !important; 
    font-size: 0.9rem !important; 
    cursor: pointer !important; 
    font-family: inherit; 
    transition: all 0.3s ease !important; 
    box-shadow: 0 2px 10px rgba(0,0,0,0.05) !important; 
    width: auto !important;
}
.elegant-video-button:hover { 
    background: var(--primary-gradient-guide) !important; 
    color: white !important; 
    border-color: transparent !important; 
    transform: translateY(-2px); 
    box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3) !important; 
}
.elegant-video-button-icon { width: 18px; height: 18px; margin-left: 8px; fill: currentColor; }

.guide-actions { 
    display: flex !important; 
    gap: 12px !important; 
    margin-top: 20px; 
    padding-top: 20px; 
    border-top: 1px solid #e2e8f0; 
    width: 100% !important;
}
.action-button { 
    padding: 12px 15px !important; 
    border: none !important; 
    border-radius: 12px !important; 
    font-size: 0.95rem !important; 
    font-weight: 600 !important; 
    cursor: pointer !important; 
    flex: 1 !important; 
    transition: all 0.3s ease !important; 
    display: flex !important; 
    align-items: center; 
    justify-content: center; 
    font-family: inherit; 
    height: 48px !important;
}
.action-button-icon { width: 20px; height: 20px; margin-right: 0; margin-left: 8px; }

.back-button { 
    background: white !important; 
    color: var(--guide-text-body) !important; 
    border: 2px solid #e2e8f0 !important; 
}
.back-button:hover { 
    background: #f7fafc !important; 
    border-color: var(--guide-accent) !important; 
    transform: translateY(-2px); 
    box-shadow: var(--shadow-md) !important; 
}

.retry-button { 
    background: var(--primary-gradient-guide) !important; 
    color: white !important; 
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3) !important; 
}
.retry-button:hover { 
    transform: translateY(-2px); 
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important; 
}

/* --- Main App CSS --- */
/* Hidden inputs logic */
#fingerprint_storage, #status_storage {
    display: none !important; 
}

/* Badge Style */
#badge-container {
    text-align: center;
    margin-bottom: 30px;
    height: 30px;
}
#user-sub-badge {
    padding: 6px 16px;
    border-radius: 20px;
    font-size: 0.9em;
    color: white;
    margin-top: 10px;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    display: none; 
    transition: all 0.3s ease;
}

body { margin: 0; padding: 10px; }

#col-container {
    margin: 0 auto;
    max-width: 980px;
    direction: rtl;
    text-align: right;
    padding: 30px;
    background: #ffffff !important;
    border-radius: 24px;
    box-shadow: 0 10px 40px -10px rgba(0,0,0,0.08); 
    border: 1px solid rgba(255,255,255,0.8);
}

#main-title h1 {
    font-size: 2.4em !important;
    text-align: center;
    color: #1a202c !important;
    margin-bottom: 15px;
    font-weight: 800;
    background: -webkit-linear-gradient(45deg, #2563eb, #1e40af);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

#main-description {
    text-align: center;
    font-size: 1.15em;
    color: #4b5563 !important;
    margin-bottom: 40px;
    line-height: 1.6;
}

.gr-input-label, span.label-wrap, label span {
    font-weight: 700 !important;
    color: #374151 !important;
    font-size: 0.95em !important;
    margin-bottom: 8px !important;
}

textarea, input[type="text"] {
    border: 2px solid #e2e8f0 !important;
    border-radius: 12px !important;
    background-color: #ffffff !important;
    color: #111827 !important;
    padding: 12px !important;
    transition: all 0.3s ease;
    font-family: 'Vazirmatn', sans-serif !important;
}

textarea:focus, input[type="text"]:focus {
    border-color: #3b82f6 !important;
    box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1) !important;
    outline: none;
}

.gr-dropdown {
    background: #ffffff !important;
    border-radius: 12px !important;
}

/* Run Button */
.primary-btn, button.primary {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 700 !important;
    font-size: 1.1em !important;
    padding: 14px 28px !important;
    border-radius: 14px !important;
    box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3) !important;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
    cursor: pointer !important;
    width: 100%;
    margin-top: 15px;
}
.primary-btn:hover, button.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(16, 185, 129, 0.45) !important;
}

/* Upgrade Button */
.upgrade-btn {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 700 !important;
    font-size: 1.1em !important;
    padding: 14px 28px !important;
    border-radius: 14px !important;
    box-shadow: 0 4px 15px rgba(245, 158, 11, 0.4) !important;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
    cursor: pointer !important;
    width: 100%;
    margin-top: 15px;
    animation: pulse 2s infinite;
}
.upgrade-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(245, 158, 11, 0.5) !important;
}
@keyframes pulse {
    0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(245, 158, 11, 0.7); }
    70% { transform: scale(1.02); box-shadow: 0 0 0 10px rgba(245, 158, 11, 0); }
    100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(245, 158, 11, 0); }
}

#download-btn {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important;
    box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3) !important;
}
#download-btn:hover {
    box-shadow: 0 8px 25px rgba(59, 130, 246, 0.45) !important;
}

.gradio-container .prose table, 
.gradio-container table {
    background-color: #ffffff !important;
    color: #111827 !important;
    border: 1px solid #e5e7eb !important;
    border-radius: 12px !important;
    overflow: hidden !important;
    width: 100% !important;
    margin-top: 20px !important;
}

.gradio-container thead th {
    background-color: #f3f4f6 !important;
    color: #374151 !important;
    font-weight: 700 !important;
    border-bottom: 2px solid #e5e7eb !important;
    padding: 12px !important;
    text-align: right !important;
}

.gradio-container tbody tr {
    background-color: #ffffff !important;
    border-bottom: 1px solid #f3f4f6 !important;
}

.gradio-container tbody tr:hover {
    background-color: #f9fafb !important;
}

.gradio-container tbody td {
    background-color: #ffffff !important;
    color: #374151 !important;
    padding: 10px !important;
}

footer { display: none !important; }
.flagging { display: none !important; }

/* Force toast transparency for cleaner Custom Modal */
.toast-body { direction: rtl !important; text-align: right !important; background: transparent !important; box-shadow: none !important; border: none !important; padding: 0 !important; max-width: 100% !important; width: auto !important; }
.toast-wrap { background: transparent !important; border: none !important; box-shadow: none !important; }

@media (prefers-color-scheme: dark) {
    body, .gradio-container, .prose, table, tr, td, th {
        background-color: #ffffff !important;
        color: #333333 !important;
    }
}
</style>
"""

# ادغام CSS و JS
combined_html = css_code + js_global_content

# استفاده از gr.Blocks
with gr.Blocks() as demo:
    # تزریق کدها به عنوان HTML
    gr.HTML(combined_html)
    
    # اینپوت‌های مخفی برای انتقال دیتای کاربر از JS به Python
    fingerprint_box = gr.Textbox(elem_id="fingerprint_storage", visible=True)
    status_box_input = gr.Textbox(elem_id="status_storage", visible=True)
    
    with gr.Column(elem_id="col-container"):
        gr.Markdown("# **ویرایشگر هوشمند آلفا**", elem_id="main-title")
        gr.Markdown(
            "با هوش مصنوعی آلفا تصاویر تونو به مدل های مختلف ویرایش کنید.", 
            elem_id="main-description"
        )
        
        # محل قرارگیری بج (نشانگر) وضعیت اشتراک
        gr.HTML('<div id="badge-container"><span id="user-sub-badge"></span></div>')

        with gr.Row(equal_height=True):
            with gr.Column():
                input_image = gr.Image(label="بارگذاری تصویر", type="pil", height=320)
                
                prompt = gr.Text(
                    label="دستور ویرایش (به فارسی)",
                    show_label=True,
                    placeholder="مثال: تصویر را به سبک انیمه تبدیل کن...",
                    rtl=True,
                    lines=3
                )
                
                status_box = gr.HTML(label="وضعیت")
                
                # --- دکمه‌ها ---
                # دکمه ساخت تصویر (پیش‌فرض نمایش)
                run_button = gr.Button("✨ شروع پردازش و ساخت تصویر", variant="primary", elem_classes="primary-btn", elem_id="run-btn", visible=True)
                
                # دکمه ارتقا (پیش‌فرض مخفی)
                upgrade_button = gr.Button("💎 خرید نسخه نامحدود (کلیک کنید)", variant="primary", elem_classes="upgrade-btn", elem_id="upgrade-btn", visible=False)

            with gr.Column():
                output_image = gr.Image(label="تصویر نهایی", interactive=False, format="png", height=380)
                
                download_button = gr.Button("📥 دانلود و ذخیره تصویر", variant="secondary", elem_id="download-btn", elem_classes="primary-btn")
                
                with gr.Row():
                    lora_adapter = gr.Dropdown(
                        label="انتخاب سبک ویرایش (LoRA)",
                        choices=list(LORA_MAPPING.keys()),
                        value="تبدیل عکس به انیمه"
                    )
                
                with gr.Accordion("تنظیمات پیشرفته", open=False, visible=True):
                    aspect_ratio_selection = gr.Dropdown(
                        label="ابعاد تصویر خروجی",
                        choices=ASPECT_RATIOS_LIST,
                        value="خودکار (پیش‌فرض)",
                        interactive=True
                    )
                    
                    with gr.Row(visible=False) as custom_dims_row:
                        custom_width = gr.Slider(
                            label="عرض دلخواه (Width)",
                            minimum=256, maximum=2048, step=8, value=1024
                        )
                        custom_height = gr.Slider(
                            label="ارتفاع دلخواه (Height)",
                            minimum=256, maximum=2048, step=8, value=1024
                        )
                    
                    seed = gr.Slider(label="دانه تصادفی (Seed)", minimum=0, maximum=MAX_SEED, step=1, value=0)
                    randomize_seed = gr.Checkbox(label="استفاده از Seed تصادفی", value=True)
                    guidance_scale = gr.Slider(label="میزان وفاداری به متن (Guidance Scale)", minimum=1.0, maximum=10.0, step=0.1, value=1.0)
                    steps = gr.Slider(label="تعداد مراحل پردازش (Steps)", minimum=1, maximum=50, step=1, value=4)
        
        # اصلاح تابع نمایش ردیف اسلایدرها
        def toggle_row(choice):
            if choice == "شخصی‌سازی (Custom)":
                return gr.update(visible=True)
            return gr.update(visible=False)

        aspect_ratio_selection.change(
            fn=toggle_row,
            inputs=aspect_ratio_selection,
            outputs=custom_dims_row
        )

        gr.Examples(
            examples=[
                ["examples/1.jpg", "تبدیل به انیمه کن.", "تبدیل عکس به انیمه"],
                ["examples/5.jpg", "سایه‌ها را حذف کن و نورپردازی نرم به تصویر بده.", "اصلاح نور و سایه"],
                ["examples/4.jpg", "از فیلتر ساعت طلایی با پخش نور ملایم استفاده کن.", "نورپردازی مجدد (Relight)"],
                ["examples/2.jpeg", "دوربین را ۴۵ درجه به سمت چپ بچرخان.", "تغییر زاویه دید"],
                ["examples/7.jpg", "منبع نور را از سمت راست عقب قرار بده.", "نورپردازی چند زاویه‌ای"],
                ["examples/10.jpeg", "کیفیت تصویر را افزایش بده (Upscale).", "افزایش کیفیت (Upscale)"],
                ["examples/7.jpg", "منبع نور را از پایین بتابان.", "نورپردازی چند زاویه‌ای"],
                ["examples/2.jpeg", "زاویه دوربین را به نمای بالا گوشه راست تغییر بده.", "تغییر زاویه دید"],
                ["examples/9.jpg", "دوربین کمی به جلو حرکت می‌کند در حالی که نور خورشید از میان ابرها می‌تابد و درخششی نرم اطراف شبح شخصیت در مه ایجاد می‌کند. سبک سینمایی واقعی.", "صحنه بعدی (سینمایی)"],
                ["examples/8.jpg", "جزئیات پوست سوژه را برجسته‌تر و طبیعی‌تر کن.", "روتوش پوست"],
                ["examples/6.jpg", "دوربین را به نمای پایین به بالا تغییر بده.", "تغییر زاویه دید"],
            ],
            inputs=[input_image, prompt, lora_adapter],
            outputs=[output_image, seed, status_box],
            fn=infer_example,
            cache_examples=False,
            label="نمونه‌ها (برای تست کلیک کنید)"
        )
        
        # --- سیستم هوشمند: بررسی اعتبار در لحظه لود شدن ---
        fingerprint_box.change(
            fn=check_initial_quota,
            inputs=[fingerprint_box, status_box_input],
            outputs=[run_button, upgrade_button, status_box]
        )

        # اجرای اصلی
        run_button.click(
            fn=infer,
            inputs=[
                input_image, prompt, lora_adapter, seed, randomize_seed, 
                guidance_scale, steps, aspect_ratio_selection, 
                custom_width, custom_height,
                fingerprint_box, status_box_input
            ],
            outputs=[output_image, seed, status_box, run_button, upgrade_button],
            api_name="predict"
        )

        # عملکرد دکمه ارتقا (فراخوانی JS)
        upgrade_button.click(
            fn=None,
            js=js_upgrade_func
        )

        download_button.click(
            fn=None,
            inputs=[output_image],
            outputs=None,
            js=js_download_func
        )

if __name__ == "__main__":
    demo.queue(max_size=30).launch(show_error=True)