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

Model   : https://huggingface.co/tarfandoon/paintpath-net-v2 (60.6M, 512x512, 6 Native Stages + Aesthetic Score)
Author  : Ali Jahani
Website : https://jahaniwww.com
Telegram: https://t.me/tarfandoonchannel
"""

import argparse
import base64
import html as html_lib
import io
import os
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Tuple

# On Hugging Face ZeroGPU Spaces, `spaces` MUST be imported before `torch`!
try:
    import spaces
except ImportError:
    spaces = None

import cv2
import gradio as gr
import numpy as np
import timm
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image, ImageDraw
from scipy.optimize import minimize
from sklearn.cluster import KMeans

try:
    from huggingface_hub import PyTorchModelHubMixin
except ImportError:
    class PyTorchModelHubMixin:
        pass


# ============================================================
# 1. PaintPathNetV2 Architecture (tarfandoon/paintpath-net-v2)
# ============================================================
class FiLMResBlock(nn.Module):
    def __init__(self, in_ch: int, out_ch: int, cond_dim: int):
        super().__init__()
        num_groups = next(g for g in (32, 16, 8, 4, 2, 1) if out_ch % g == 0)
        self.conv1 = nn.Conv2d(in_ch, out_ch, kernel_size=3, padding=1, bias=False)
        self.norm1 = nn.GroupNorm(num_groups, out_ch)
        self.conv2 = nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1, bias=False)
        self.norm2 = nn.GroupNorm(num_groups, out_ch)
        self.film = nn.Linear(cond_dim, out_ch * 2)
        nn.init.zeros_(self.film.weight)
        nn.init.zeros_(self.film.bias)
        self.skip = nn.Conv2d(in_ch, out_ch, kernel_size=1) if in_ch != out_ch else nn.Identity()

    def forward(self, x: torch.Tensor, cond: torch.Tensor) -> torch.Tensor:
        h = F.gelu(self.norm1(self.conv1(x)))
        gamma, beta = self.film(cond).chunk(2, dim=-1)
        h = self.norm2(self.conv2(h))
        h = h * (1.0 + gamma[:, :, None, None]) + beta[:, :, None, None]
        return F.gelu(h + self.skip(x))


class PaintPathNetV2(nn.Module, PyTorchModelHubMixin):
    def __init__(
        self,
        backbone: str = "convnext_small.fb_in22k_ft_in1k",
        pretrained: bool = False,
        num_stages: int = 6,
        cond_dim: int = 256,
    ):
        super().__init__()
        self.backbone = backbone
        self.num_stages = num_stages
        self.cond_dim = cond_dim

        self.encoder = timm.create_model(
            backbone,
            pretrained=pretrained,
            features_only=True,
            out_indices=(0, 1, 2, 3),
        )
        chs = self.encoder.feature_info.channels()

        self.stage_emb = nn.Sequential(
            nn.Embedding(num_stages, cond_dim),
            nn.Linear(cond_dim, cond_dim),
            nn.GELU(),
            nn.Linear(cond_dim, cond_dim),
        )

        self.aesthetic_head = nn.Sequential(
            nn.AdaptiveAvgPool2d(1),
            nn.Flatten(),
            nn.LayerNorm(chs[3]),
            nn.Linear(chs[3], 128),
            nn.GELU(),
            nn.Dropout(0.15),
            nn.Linear(128, 1),
            nn.Sigmoid(),
        )

        self.bottleneck = FiLMResBlock(chs[3], 512, cond_dim)
        self.dec3 = FiLMResBlock(512 + chs[2], 256, cond_dim)
        self.dec2 = FiLMResBlock(256 + chs[1], 128, cond_dim)
        self.dec1 = FiLMResBlock(128 + chs[0], 96, cond_dim)

        self.up_half = FiLMResBlock(96, 64, cond_dim)
        self.up_full = FiLMResBlock(64 + 3, 48, cond_dim)
        self.out_head = nn.Sequential(
            nn.Conv2d(48, 32, kernel_size=3, padding=1),
            nn.GELU(),
            nn.Conv2d(32, 3, kernel_size=1),
            nn.Sigmoid(),
        )

        self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
        self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))

    def extract_focal_map(self, img: torch.Tensor) -> torch.Tensor:
        x_norm = (img - self.mean) / self.std
        _, _, f3, f4 = self.encoder(x_norm)
        m4 = torch.norm(f4, dim=1, keepdim=True)
        m3 = torch.norm(f3, dim=1, keepdim=True)
        H, W = img.shape[-2], img.shape[-1]
        m4 = F.interpolate(m4, size=(H, W), mode="bilinear", align_corners=False)
        m3 = F.interpolate(m3, size=(H, W), mode="bilinear", align_corners=False)
        m = 0.65 * (m4 / (m4.amax(dim=(-2, -1), keepdim=True) + 1e-6)) + \
            0.35 * (m3 / (m3.amax(dim=(-2, -1), keepdim=True) + 1e-6))
        m = (m - m.amin(dim=(-2, -1), keepdim=True)) / (m.amax(dim=(-2, -1), keepdim=True) - m.amin(dim=(-2, -1), keepdim=True) + 1e-6)
        return m

    def forward(self, img: torch.Tensor, stage_idx: torch.Tensor):
        x_norm = (img - self.mean) / self.std
        f1, f2, f3, f4 = self.encoder(x_norm)
        cond = self.stage_emb(stage_idx)
        aes_score = self.aesthetic_head(f4).squeeze(-1)

        h = self.bottleneck(f4, cond)
        h = F.interpolate(h, size=f3.shape[-2:], mode="bilinear", align_corners=False)
        h = self.dec3(torch.cat([h, f3], dim=1), cond)

        h = F.interpolate(h, size=f2.shape[-2:], mode="bilinear", align_corners=False)
        h = self.dec2(torch.cat([h, f2], dim=1), cond)

        h = F.interpolate(h, size=f1.shape[-2:], mode="bilinear", align_corners=False)
        h = self.dec1(torch.cat([h, f1], dim=1), cond)

        H, W = img.shape[-2], img.shape[-1]
        h = F.interpolate(h, size=(H // 2, W // 2), mode="bilinear", align_corners=False)
        h = self.up_half(h, cond)

        h = F.interpolate(h, size=(H, W), mode="bilinear", align_corners=False)
        h = self.up_full(torch.cat([h, img], dim=1), cond)
        return self.out_head(h), aes_score


# ============================================================
# 2. Physical Pigment Mixing, Centimeter Rulers & Animations
# ============================================================
ARTIST_TUBES: Dict[str, Tuple[int, int, int]] = {
    "Titanium White": (245, 245, 242),
    "Ivory Black": (28, 28, 30),
    "Ultramarine Blue": (25, 45, 145),
    "Cadmium Red": (208, 38, 32),
    "Cadmium Yellow": (242, 200, 28),
    "Yellow Ochre": (198, 146, 58),
    "Burnt Umber": (84, 52, 34),
    "Viridian Green": (34, 118, 88),
}

TUBE_PERSIAN = {
    "Titanium White": "سفید تیتانیوم",
    "Ivory Black": "مشکی عاجی",
    "Ultramarine Blue": "آبی اولترامارین",
    "Cadmium Red": "قرمز کادمیوم",
    "Cadmium Yellow": "زرد کادمیوم",
    "Yellow Ochre": "زرد اخرایی",
    "Burnt Umber": "قهوه‌ای سوخته (آمبر)",
    "Viridian Green": "سبز ویریدین",
}


def _srgb_to_linear(rgb01: np.ndarray) -> np.ndarray:
    return np.where(rgb01 <= 0.04045, rgb01 / 12.92, ((rgb01 + 0.055) / 1.055) ** 2.4)


def _linear_to_ks(r: np.ndarray) -> np.ndarray:
    r = np.clip(r, 1e-3, 0.999)
    return ((1.0 - r) ** 2) / (2.0 * r)


def solve_tube_recipe(target_rgb: Tuple[int, int, int], max_tubes: int = 3) -> List[Tuple[str, int]]:
    names = list(ARTIST_TUBES.keys())
    tube_lin = _srgb_to_linear(np.array([ARTIST_TUBES[n] for n in names], dtype=np.float64) / 255.0)
    tube_ks = _linear_to_ks(tube_lin)
    tgt_lin = _srgb_to_linear(np.array(target_rgb, dtype=np.float64) / 255.0)

    def _fit(sub_ks: np.ndarray) -> np.ndarray:
        m = len(sub_ks)
        def loss_fn(w):
            ks = np.maximum(w @ sub_ks, 1e-4)
            pred_r = 1.0 + ks - np.sqrt(ks * ks + 2.0 * ks)
            return float(np.sum((pred_r - tgt_lin) ** 2))
        res = minimize(
            loss_fn,
            x0=np.ones(m, dtype=np.float64) / m,
            bounds=[(0.0, 1.0)] * m,
            constraints={"type": "eq", "fun": lambda w: np.sum(w) - 1.0},
            method="SLSQP",
            options={"ftol": 1e-9, "maxiter": 150},
        )
        w = np.maximum(res.x, 0.0)
        return w / (w.sum() + 1e-12)

    w = _fit(tube_ks)
    top_idx = np.argsort(w)[::-1][:max_tubes]
    sw = _fit(tube_ks[top_idx])

    recipe = [(names[idx], int(round(weight * 100))) for idx, weight in zip(top_idx, sw) if int(round(weight * 100)) >= 5]
    if recipe:
        total = sum(p for _, p in recipe)
        if total != 100:
            recipe[0] = (recipe[0][0], recipe[0][1] + (100 - total))
    return recipe


@dataclass
class PaletteColor:
    index: int
    rgb: Tuple[int, int, int]
    hex: str
    proportion: float
    mixing_recipe: List[Tuple[str, int]]


def extract_physical_palette(image_rgb: np.ndarray, k: int = 8, seed: int = 42) -> List[PaletteColor]:
    small = cv2.resize(image_rgb, (128, 128), interpolation=cv2.INTER_AREA)
    lab = cv2.cvtColor(small, cv2.COLOR_RGB2LAB).reshape(-1, 3).astype(np.float32)
    km = KMeans(n_clusters=k, n_init=5, random_state=seed)
    labels = km.fit_predict(lab)
    centers_rgb = cv2.cvtColor(np.clip(km.cluster_centers_, 0, 255).astype(np.uint8).reshape(1, k, 3), cv2.COLOR_LAB2RGB).reshape(k, 3)
    props = np.bincount(labels, minlength=k).astype(np.float64)
    props /= props.sum()

    palette: List[PaletteColor] = []
    for new_i, idx in enumerate(np.argsort(-props)):
        r, g, b = int(centers_rgb[idx, 0]), int(centers_rgb[idx, 1]), int(centers_rgb[idx, 2])
        palette.append(PaletteColor(new_i, (r, g, b), f"#{r:02X}{g:02X}{b:02X}", round(float(props[idx]), 4), solve_tube_recipe((r, g, b))))
    return palette


def auto_crop_borders(img_rgb: np.ndarray, tol: int = 18, max_crop_ratio: float = 0.15) -> np.ndarray:
    h, w = img_rgb.shape[:2]
    gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
    is_br = (gray.std(axis=1) < 8.0) & ((gray.mean(axis=1) > 255 - tol) | (gray.mean(axis=1) < tol))
    is_bc = (gray.std(axis=0) < 8.0) & ((gray.mean(axis=0) > 255 - tol) | (gray.mean(axis=0) < tol))
    top, bottom, left, right = 0, h, 0, w
    while top < int(h * max_crop_ratio) and is_br[top]:
        top += 1
    while bottom > h - int(h * max_crop_ratio) and is_br[bottom - 1]:
        bottom -= 1
    while left < int(w * max_crop_ratio) and is_bc[left]:
        left += 1
    while right > w - int(w * max_crop_ratio) and is_bc[right - 1]:
        right -= 1
    if bottom - top < h * 0.6 or right - left < w * 0.6:
        return img_rgb
    return img_rgb[top:bottom, left:right]


def polish_continuous_sketch(sketch_rgb: np.ndarray) -> np.ndarray:
    """
    Polishes PaintPathNetV2's continuous neural sketch so lines are crisp,
    smooth, unbroken graphite strokes on warm art paper (ZERO dotted noise!).
    """
    gray = cv2.cvtColor(sketch_rgb, cv2.COLOR_RGB2GRAY)
    # Gentle morphological close on inverted lines reconnects any hairline gaps
    inv = 255 - gray
    inv = cv2.morphologyEx(inv, cv2.MORPH_CLOSE, np.ones((2, 2), np.uint8))
    clean_g = 255 - inv
    # Clean contrast stretch so paper is bright & lines are deep graphite
    clean_g = np.clip((clean_g.astype(np.float32) - 25.0) * (255.0 / 215.0), 0, 255).astype(np.uint8)
    # Subtle warm paper tint
    out = np.stack([
        clean_g,
        np.clip(clean_g.astype(np.float32) * 0.99, 0, 255).astype(np.uint8),
        np.clip(clean_g.astype(np.float32) * 0.96, 0, 255).astype(np.uint8),
    ], axis=-1)
    return np.ascontiguousarray(out)


def upscale_hi_res(img_rgb: np.ndarray, target_max: int = 1024, sharpen: bool = True) -> np.ndarray:
    """Crisp Lanczos upscale to ~1024px so Maximize/Fullscreen & Zoom show rich detail."""
    h, w = img_rgb.shape[:2]
    if max(h, w) >= target_max:
        return np.ascontiguousarray(img_rgb)
    scale = target_max / max(h, w)
    nw, nh = int(round(w * scale)), int(round(h * scale))
    up = cv2.resize(img_rgb, (nw, nh), interpolation=cv2.INTER_LANCZOS4)
    if sharpen:
        blur = cv2.GaussianBlur(up, (0, 0), 1.2)
        up = cv2.addWeighted(up, 1.25, blur, -0.25, 0)
    return np.ascontiguousarray(up)


def render_zoom_crop(img_rgb: np.ndarray, zoom_level: float, cx_norm: float = 0.5, cy_norm: float = 0.5) -> np.ndarray:
    """Return a crisp zoomed-in detail view around (cx_norm, cy_norm) at `zoom_level` (1.0 - 4.0x)."""
    if zoom_level <= 1.05:
        return img_rgb
    h, w = img_rgb.shape[:2]
    cw = max(64, int(round(w / zoom_level)))
    ch = max(64, int(round(h / zoom_level)))
    cx = int(round(cx_norm * w))
    cy = int(round(cy_norm * h))
    x0 = max(0, min(w - cw, cx - cw // 2))
    y0 = max(0, min(h - ch, cy - ch // 2))
    crop = img_rgb[y0 : y0 + ch, x0 : x0 + cw]
    return np.ascontiguousarray(cv2.resize(crop, (w, h), interpolation=cv2.INTER_LANCZOS4))


def draw_cm_ruler_grid(img_rgb: np.ndarray, width_cm: float, grid_n: int = 4) -> Tuple[np.ndarray, float, float, float]:
    """
    Draws a clean real-world centimeter ruler border + 4x4 grid on the sketch
    so the painter can measure exact proportions on their physical canvas with a ruler!
    Returns: (annotated_img, height_cm, cell_w_cm, cell_h_cm)
    """
    h, w = img_rgb.shape[:2]
    height_cm = round(width_cm * (h / max(w, 1)), 1)
    cell_w = round(width_cm / grid_n, 1)
    cell_h = round(height_cm / grid_n, 1)

    pad_top, pad_left = 30, 44
    canvas = np.full((h + pad_top + 10, w + pad_left + 10, 3), 248, dtype=np.uint8)
    canvas[pad_top : pad_top + h, pad_left : pad_left + w] = img_rgb

    # Outer canvas border
    cv2.rectangle(canvas, (pad_left, pad_top), (pad_left + w - 1, pad_top + h - 1), (55, 65, 81), 2)

    # Crisp 4x4 proportion grid lines
    for i in range(1, grid_n):
        gx = pad_left + int(round(w * i / grid_n))
        gy = pad_top + int(round(h * i / grid_n))
        cv2.line(canvas, (gx, pad_top), (gx, pad_top + h - 1), (96, 150, 225), 1, cv2.LINE_AA)
        cv2.line(canvas, (pad_left, gy), (pad_left + w - 1, gy), (96, 150, 225), 1, cv2.LINE_AA)

    # Centimeter labels along top & left margins (ASCII-safe PIL bitmap font)
    pil_im = Image.fromarray(canvas)
    draw = ImageDraw.Draw(pil_im)
    for i in range(grid_n + 1):
        gx = pad_left + int(round(w * i / grid_n))
        gy = pad_top + int(round(h * i / grid_n))
        cm_x = round(width_cm * i / grid_n, 1)
        cm_y = round(height_cm * i / grid_n, 1)
        draw.text((max(2, gx - 14), 8), f"{cm_x:g}cm", fill=(30, 41, 59))
        draw.text((4, max(pad_top - 4, gy - 6)), f"{cm_y:g}cm", fill=(30, 41, 59))

    return np.ascontiguousarray(np.array(pil_im)), height_cm, cell_w, cell_h


def make_smooth_sketch_animation(rough_rgb: np.ndarray, full_sketch_rgb: np.ndarray, width_cm: float) -> str:
    """
    Smooth, accurate, non-dotted Pencil Sketching Animation GIF:
      Phase A (0-45%): Draws the centimeter grid & progressively reveals Stage 0 main continuous lines
                       using a diagonal artist-hand sweep mask!
      Phase B (45-100%): Smoothly layers in Stage 1 full continuous details!
    """
    h, w = rough_rgb.shape[:2]
    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
    # Natural top-left to bottom-right diagonal drawing sweep
    sweep = (xx / max(w, 1)) * 0.55 + (yy / max(h, 1)) * 0.45

    paper = np.full((h, w, 3), 250, dtype=np.uint8)
    frames: List[Image.Image] = []
    durations: List[int] = []
    bar_h = 30

    def _pack(arr: np.ndarray, title: str, pct: int) -> Image.Image:
        grid_img, _, _, _ = draw_cm_ruler_grid(arr, width_cm, grid_n=4)
        gh, gw = grid_img.shape[:2]
        out = Image.new("RGB", (gw, gh + bar_h), (245, 240, 232))
        out.paste(Image.fromarray(grid_img), (0, bar_h))
        d = ImageDraw.Draw(out)
        d.text((10, 7), f"{title} ({pct}%)", fill=(30, 35, 48))
        prog = int((gw - 20) * pct / 100)
        d.rectangle([10, bar_h - 5, gw - 10, bar_h - 2], fill=(220, 215, 205))
        d.rectangle([10, bar_h - 5, 10 + prog, bar_h - 2], fill=(217, 119, 6))
        return out

    # Phase A: Continuous reveal of Stage 0 main structural outlines
    for step in range(1, 9):
        t = step / 8.0
        alpha = np.clip((t * 1.15 - sweep) * 5.0, 0.0, 1.0)[..., None]
        cur = np.clip(paper * (1.0 - alpha) + rough_rgb * alpha, 0, 255).astype(np.uint8)
        frames.append(_pack(cur, "1. Main Proportions & Outlines", int(t * 48)))
        durations.append(160)

    # Phase B: Continuous reveal of Stage 1 full details on top of Stage 0
    for step in range(1, 9):
        t = step / 8.0
        alpha = np.clip((t * 1.15 - sweep) * 5.0, 0.0, 1.0)[..., None]
        cur = np.clip(rough_rgb * (1.0 - alpha) + full_sketch_rgb * alpha, 0, 255).astype(np.uint8)
        frames.append(_pack(cur, "2. Refining Full Pencil Details", 48 + int(t * 52)))
        durations.append(170)

    # Hold final crisp sketch
    frames.append(_pack(full_sketch_rgb, "Complete Sketch Ready for Paint", 100))
    durations.append(2200)

    tmp = tempfile.NamedTemporaryFile(suffix=".gif", delete=False)
    tmp.close()
    frames[0].save(tmp.name, save_all=True, append_images=frames[1:], duration=durations, loop=0, optimize=True)
    return tmp.name


def make_timelapse_gif(stages_7: List[np.ndarray]) -> str:
    """Smooth cinematic 7-stage painting timelapse GIF with progress bar."""
    labels = [
        "Step 1/7: Main Outlines & Grid",
        "Step 2/7: Full Pencil Sketch",
        "Step 3/7: Sepia Underpainting",
        "Step 4/7: Broad Color Blocking",
        "Step 5/7: Shadows & 3D Volume",
        "Step 6/7: Mid-Details & Brushwork",
        "Step 7/7: Final Highlights",
    ]
    h, w = stages_7[0].shape[:2]
    bar_h = 32

    def _annotate(arr: np.ndarray, text: str, prog_frac: float) -> Image.Image:
        canvas = Image.new("RGB", (w, h + bar_h), (245, 240, 232))
        canvas.paste(Image.fromarray(arr), (0, bar_h))
        d = ImageDraw.Draw(canvas)
        d.text((10, 7), text, fill=(30, 35, 48))
        prog = int((w - 20) * prog_frac)
        d.rectangle([10, bar_h - 5, w - 10, bar_h - 2], fill=(220, 215, 205))
        d.rectangle([10, bar_h - 5, 10 + prog, bar_h - 2], fill=(79, 70, 229))
        return canvas

    frames: List[Image.Image] = []
    durations: List[int] = []
    n = len(stages_7)
    for i, img in enumerate(stages_7):
        frames.append(_annotate(img, labels[i], (i + 1) / n))
        durations.append(1100 if i < n - 1 else 2400)
        if i < n - 1:
            nxt = stages_7[i + 1]
            for alpha in (0.25, 0.50, 0.75):
                blend = cv2.addWeighted(img, 1.0 - alpha, nxt, alpha, 0)
                frames.append(_annotate(blend, labels[i + 1], (i + 1 + alpha) / n))
                durations.append(85)

    tmp = tempfile.NamedTemporaryFile(suffix=".gif", delete=False)
    tmp.close()
    frames[0].save(tmp.name, save_all=True, append_images=frames[1:], duration=durations, loop=0, optimize=True)
    return tmp.name


def make_clear_paint_zones(prev_img: np.ndarray, curr_img: np.ndarray) -> np.ndarray:
    diff = np.mean(np.abs(curr_img.astype(np.float32) - prev_img.astype(np.float32)), axis=-1)
    diff = cv2.GaussianBlur(diff, (7, 7), 0)
    thr = max(9.0, float(np.percentile(diff, 68)))
    bin_mask = (diff >= thr).astype(np.uint8) * 255
    bin_mask = cv2.morphologyEx(bin_mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))

    soft = cv2.GaussianBlur(bin_mask.astype(np.float32) / 255.0, (9, 9), 0)[..., None]
    gray_bg = cv2.cvtColor(cv2.cvtColor(curr_img, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB).astype(np.float32) * 0.35 + 162.0
    blended = np.ascontiguousarray(np.clip(gray_bg * (1.0 - soft) + curr_img.astype(np.float32) * soft, 0, 255).astype(np.uint8))
    contours, _ = cv2.findContours(bin_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(blended, contours, -1, (234, 88, 12), 2, cv2.LINE_AA)
    return blended


def make_value_study_3tone(img_rgb: np.ndarray) -> np.ndarray:
    gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
    gray = cv2.bilateralFilter(gray, 9, 55, 55)
    t1, t2 = np.percentile(gray, [33, 72])
    out = np.full_like(gray, 138)
    out[gray <= t1] = 28
    out[gray >= t2] = 242
    return cv2.cvtColor(out, cv2.COLOR_GRAY2RGB)


def make_attention_overlay(img_rgb: np.ndarray, focal_01: np.ndarray) -> np.ndarray:
    heat_u8 = np.clip(focal_01 * 255.0, 0, 255).astype(np.uint8)
    heat_u8 = cv2.GaussianBlur(heat_u8, (15, 15), 0)
    heat_bgr = cv2.applyColorMap(heat_u8, cv2.COLORMAP_INFERNO)
    heat_rgb = cv2.cvtColor(heat_bgr, cv2.COLOR_BGR2RGB)
    return cv2.addWeighted(img_rgb, 0.50, heat_rgb, 0.50, 0)


def render_aesthetic_score_html(score_10: float, width_cm: float, height_cm: float, cell_w: float, cell_h: float) -> str:
    pct = int(round(np.clip(score_10 * 10.0, 5, 100)))
    if score_10 >= 8.0:
        tier = "شاهکار و بسیار چشم‌گیر (جزو آثار برتر)"
        bar_col = "#16a34a"
    elif score_10 >= 6.5:
        tier = "جذابیت بصری بالا و ترکیب‌بندی قوی"
        bar_col = "#d97706"
    else:
        tier = "متعادل و آرام (مناسب تمرین آماتور)"
        bar_col = "#4f46e5"

    return f"""
    <div style="background:#fffdf9; border:2px solid #e7d5bc; border-radius:16px; padding:18px 22px; direction:rtl; color:#111827 !important;">
        <div style="display:flex; flex-wrap:wrap; justify-content:space-between; align-items:center; gap:14px;">
            <div>
                <div style="font-size:13px; color:#6b7280 !important; font-weight:700;">امتیاز جذابیت و خیرگی بصری (آموزش‌دیده توسط PaintPathNet v2 روی ۵,۶۰۹ اثر)</div>
                <div style="font-size:28px; font-weight:900; color:#111827 !important; margin-top:2px;">⭐ {score_10:.1f} <span style="font-size:15px; color:#6b7280 !important;">/ 10</span> — <span style="font-size:15px; color:{bar_col} !important;">{tier}</span></div>
            </div>
            <div style="background:#fef3c7; border:1px solid #f59e0b; border-radius:12px; padding:10px 16px; text-align:right;">
                <div style="font-size:12px; color:#92400e !important; font-weight:700;">📐 ابعاد واقعی بوم و شبکه پیشنهادی</div>
                <div style="font-size:15px; font-weight:800; color:#78350f !important;">بوم: {width_cm:g} × {height_cm:g} cm &nbsp;|&nbsp; هر خانه شبکه: {cell_w:g} × {cell_h:g} cm</div>
            </div>
        </div>
        <div style="background:#e5e7eb; border-radius:999px; height:12px; overflow:hidden; margin-top:12px;">
            <div style="width:{pct}%; height:100%; background:{bar_col}; border-radius:999px;"></div>
        </div>
    </div>
    """


def highlight_target_rgb_on_canvas(img_rgb: np.ndarray, target_rgb: Tuple[int, int, int], tolerance: float = 25.0) -> Tuple[np.ndarray, str]:
    img_lab = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2LAB).astype(np.float32)
    t_lab = cv2.cvtColor(np.array([[target_rgb]], dtype=np.uint8), cv2.COLOR_RGB2LAB).astype(np.float32)[0, 0]
    dist = np.linalg.norm(img_lab - t_lab[None, None, :], axis=-1)

    mask = np.clip(1.0 - (dist - tolerance * 0.5) / max(tolerance, 1.0), 0.0, 1.0)
    mask_u8 = (mask > 0.45).astype(np.uint8) * 255
    soft = cv2.GaussianBlur(mask.astype(np.float32), (7, 7), 0)[..., None]

    bg = cv2.cvtColor(cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB).astype(np.float32) * 0.24 + 190.0
    out = np.ascontiguousarray(np.clip(bg * (1.0 - soft) + img_rgb.astype(np.float32) * soft, 0, 255).astype(np.uint8))
    contours, _ = cv2.findContours(mask_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(out, contours, -1, (220, 38, 38), 1, cv2.LINE_AA)

    r, g, b = target_rgb
    hex_code = f"#{r:02X}{g:02X}{b:02X}"
    recipe = solve_tube_recipe(target_rgb)

    bars_html = ""
    for name, pct in recipe:
        tr, tg, tb = ARTIST_TUBES[name]
        fa_name = TUBE_PERSIAN.get(name, name)
        bars_html += f"""
        <div style="margin: 8px 0;">
            <div style="display:flex; justify-content:space-between; font-size:13px; color:#1f2937 !important; font-weight:700;">
                <span>🎨 {fa_name} ({name})</span>
                <span>{pct}%</span>
            </div>
            <div style="background:#e5e7eb; border-radius:8px; height:12px; overflow:hidden; margin-top:3px;">
                <div style="width:{pct}%; height:100%; background:rgb({tr},{tg},{tb}); border:1px solid rgba(0,0,0,0.18);"></div>
            </div>
        </div>
        """

    card_html = f"""
    <div style="background:#fffdf9; border:1px solid #e5dfd5; border-radius:14px; padding:16px; direction:rtl; color:#1f2937 !important;">
        <div style="display:flex; align-items:center; gap:14px; margin-bottom:12px;">
            <div style="width:56px; height:56px; border-radius:12px; background:{hex_code}; border:2px solid #374151; flex-shrink:0;"></div>
            <div>
                <div style="font-size:16px; font-weight:800; color:#111827 !important;">رنگ انتخاب‌شده: <code>{hex_code}</code></div>
                <div style="font-size:13px; color:#4b5563 !important;">RGB({r}, {g}, {b}) — کادرهای قرمز در تصویر دقیقاً تمام نقاطی هستند که باید این رنگ را بزنی!</div>
            </div>
        </div>
        <div style="font-size:14px; font-weight:700; color:#111827 !important; margin-bottom:6px;">🧪 دستور ترکیب واقعی رنگ‌های تیوپی (Kubelka-Munk):</div>
        {bars_html}
    </div>
    """
    return out, card_html


def render_palette_card(palette: List[PaletteColor]) -> np.ndarray:
    card_w, row_h = 720, 50
    im = Image.new("RGB", (card_w, 42 + len(palette) * row_h), (252, 250, 246))
    draw = ImageDraw.Draw(im)
    draw.text((16, 12), "Master Palette - Physical Paint-Tube Mixing Recipes", fill=(30, 30, 35))
    for i, c in enumerate(palette):
        y0 = 38 + i * row_h
        draw.rectangle([16, y0 + 5, 80, y0 + row_h - 5], fill=c.rgb, outline=(60, 60, 60), width=1)
        recipe_str = " + ".join(f"{pct}% {name}" for name, pct in c.mixing_recipe)
        draw.text((94, y0 + 6), f"#{c.index + 1}  {c.hex}  ({c.proportion * 100:.1f}%)", fill=(25, 25, 25))
        draw.text((94, y0 + 25), f"Mix: {recipe_str}", fill=(75, 75, 80))
    return np.array(im)


def evaluate_amateur_painting(ref_img: np.ndarray, user_img: np.ndarray) -> Tuple[Optional[np.ndarray], str]:
    if ref_img is None or user_img is None:
        return None, "لطفاً هم نقاشی اصلی (بالای صفحه) و هم عکس نقاشیِ دستِ خودت را آپلود کن."

    ref = cv2.resize(auto_crop_borders(ref_img), (384, 384), interpolation=cv2.INTER_AREA)
    usr = cv2.resize(auto_crop_borders(user_img), (384, 384), interpolation=cv2.INTER_AREA)

    ref_lab = cv2.cvtColor(ref, cv2.COLOR_RGB2LAB).astype(np.float32)
    usr_lab = cv2.cvtColor(usr, cv2.COLOR_RGB2LAB).astype(np.float32)
    delta_e = np.linalg.norm(ref_lab - usr_lab, axis=-1)
    color_score = float(np.clip(100.0 - delta_e.mean() * 1.4, 0, 100))

    ref_l, usr_l = ref_lab[..., 0], usr_lab[..., 0]
    val_diff = usr_l.mean() - ref_l.mean()
    value_score = float(np.clip(100.0 - np.abs(ref_l - usr_l).mean() * 1.8, 0, 100))

    r_g = cv2.GaussianBlur(cv2.cvtColor(ref, cv2.COLOR_RGB2GRAY).astype(np.float32), (5, 5), 0)
    u_g = cv2.GaussianBlur(cv2.cvtColor(usr, cv2.COLOR_RGB2GRAY).astype(np.float32), (5, 5), 0)
    r_e = np.hypot(cv2.Sobel(r_g, cv2.CV_32F, 1, 0), cv2.Sobel(r_g, cv2.CV_32F, 0, 1))
    u_e = np.hypot(cv2.Sobel(u_g, cv2.CV_32F, 1, 0), cv2.Sobel(u_g, cv2.CV_32F, 0, 1))
    corr = float(np.corrcoef(r_e.flatten(), u_e.flatten())[0, 1]) if r_e.std() > 0 and u_e.std() > 0 else 0.0
    struct_score = float(np.clip((corr + 0.2) * 85.0, 0, 100))

    overall = 0.40 * color_score + 0.35 * value_score + 0.25 * struct_score
    err_blur = cv2.GaussianBlur((np.clip(delta_e / 55.0, 0, 1) * 255).astype(np.uint8), (15, 15), 0)
    heat = cv2.cvtColor(cv2.applyColorMap(err_blur, cv2.COLORMAP_JET), cv2.COLOR_BGR2RGB)
    overlay = cv2.addWeighted(usr, 0.58, heat, 0.42, 0)

    tips = []
    if val_diff > 10:
        tips.append("- **سایه‌ها کمی روشن‌اند:** روی نواحی قرمز، سایه‌ها را با کمی قهوه‌ای سوخته (Burnt Umber) عمیق‌تر کن.")
    elif val_diff < -10:
        tips.append("- **نقاشی کمی تیره شده:** در بخش‌های روشن کمی سفید تیتانیوم اضافه کن.")
    else:
        tips.append("- **تعادل نور و سایه عالی است!**")
    if color_score < 65:
        tips.append("- **دقت رنگ:** در تب «قطره‌چکان ساخت رنگ» روی بخش‌های قرمز کلیک کن تا فرمول ترکیبش را ببینی.")
    if struct_score < 55:
        tips.append("- **تناسبات:** با خط‌کش سانتی‌متری اسلاید ۱ جای اصلی اشیا را چک کن.")

    report = (
        f"### 🏆 امتیاز کلی کار دست تو: **{overall:.1f} / 100**\n"
        f"- دقت رنگ‌ها: `{color_score:.1f}` | تعادل نور و سایه: `{value_score:.1f}` | تناسبات: `{struct_score:.1f}`\n\n"
        f"#### 💡 توصیه‌های مربی (قرمز = نیاز به اصلاح، آبی = عالی):\n" + "\n".join(tips)
    )
    return overlay, report


# ============================================================
# 3. 7-Step Pedagogical Curriculum & Model Loading
# ============================================================
HERE = Path(__file__).resolve().parent
DEFAULT_HF_REPO = "tarfandoon/paintpath-net-v2"
ON_SPACES = bool(os.environ.get("SPACE_ID"))
MODEL = None


def _img_to_b64_jpeg(img_rgb: np.ndarray, max_side: int = 768, quality: int = 85) -> str:
    h, w = img_rgb.shape[:2]
    scale = min(1.0, max_side / max(h, w))
    if scale < 1.0:
        img_rgb = cv2.resize(img_rgb, (int(round(w * scale)), int(round(h * scale))), interpolation=cv2.INTER_AREA)
    buf = io.BytesIO()
    Image.fromarray(img_rgb).save(buf, format="JPEG", quality=quality)
    return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii")


def build_ar_camera_html(rough_rgb: np.ndarray, sketch_rgb: np.ndarray, block_rgb: np.ndarray, final_rgb: np.ndarray) -> str:
    """
    60-FPS Browser-Native AR Canvas Tracing Studio (Phone Back Camera & Laptop Webcam)!
    Uses CSS `mix-blend-mode: multiply` so white paper becomes 100% transparent and
    ONLY the crisp pencil lines float directly over the user's real paper/canvas.
    """
    b64_rough = _img_to_b64_jpeg(rough_rgb)
    b64_sketch = _img_to_b64_jpeg(sketch_rgb)
    b64_block = _img_to_b64_jpeg(block_rgb)
    b64_final = _img_to_b64_jpeg(final_rgb)

    inner_doc = f"""<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
  * {{ box-sizing: border-box; font-family: system-ui, -apple-system, sans-serif; }}
  body {{ margin: 0; padding: 12px; background: #fffdf9; color: #111827; }}
  .controls {{
    display: flex; flex-wrap: wrap; gap: 8px; align-items: center;
    background: #fef6e8; border: 1px solid #e5d1b3; border-radius: 14px;
    padding: 12px; margin-bottom: 12px;
  }}
  button, select {{
    padding: 8px 14px; border-radius: 10px; border: 1px solid #d1d5db;
    background: #1f2937; color: #fff; font-weight: 700; font-size: 13px; cursor: pointer;
  }}
  button.primary {{ background: #d97706; border-color: #b45309; }}
  button.secondary {{ background: #ffffff; color: #1f2937; }}
  select {{ background: #ffffff; color: #111827; }}
  label.rng {{
    display: inline-flex; align-items: center; gap: 6px; font-size: 12px;
    font-weight: 700; color: #374151; background: #fff; padding: 6px 10px;
    border-radius: 10px; border: 1px solid #e5e7eb;
  }}
  .stage-wrap {{
    position: relative; width: 100%; height: 540px; background: #111827;
    border-radius: 16px; overflow: hidden; border: 2px solid #e5d1b3;
    touch-action: none; user-select: none;
  }}
  video#cam {{
    position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;
  }}
  img#overlay {{
    position: absolute; top: 50%; left: 50%;
    max-width: 92%; max-height: 92%;
    transform: translate(-50%, -50%) scale(1);
    opacity: 0.72; pointer-events: none;
    mix-blend-mode: multiply;
    filter: contrast(1.25);
  }}
  .hint {{
    position: absolute; bottom: 10px; right: 12px; left: 12px;
    background: rgba(17, 24, 39, 0.75); color: #fff;
    padding: 8px 12px; border-radius: 10px; font-size: 12px; text-align: center;
  }}
</style>
</head>
<body>
  <div class="controls">
    <button class="primary" onclick="startCam()">📷 روشن کردن دوربین</button>
    <button class="secondary" onclick="flipCam()">🔄 تعویض دوربین (پشت/جلو)</button>
    <select id="layerSel" onchange="changeLayer()">
      <option value="rough">لایه ۱: خطوط اصلی (شفاف روی کاغذ)</option>
      <option value="sketch" selected>لایه ۲: اسکچ کامل مدادی (پیشنهادی)</option>
      <option value="block">لایه ۳: لکه‌های رنگی پایه</option>
      <option value="final">لایه ۴: نقاشی نهایی</option>
    </select>
    <label class="rng">شفافیت <input id="opRng" type="range" min="10" max="100" value="75" oninput="updateTransform()"></label>
    <label class="rng">اندازه <input id="scRng" type="range" min="40" max="180" value="100" oninput="updateTransform()"></label>
    <button class="secondary" onclick="toggleBlend()" id="blendBtn">✨ حذف پس‌زمینه سفید: روشن</button>
    <button class="secondary" onclick="toggleMirror()">🪞 آینه‌ای</button>
    <button class="secondary" onclick="goFullscreen()">⛶ تمام‌صفحه</button>
  </div>

  <div class="stage-wrap" id="arBox">
    <video id="cam" autoplay playsinline muted></video>
    <img id="overlay" src="{b64_sketch}" alt="AR Sketch Overlay" />
    <div class="hint" id="statusMsg">دکمه «📷 روشن کردن دوربین» را بزن، گوشی را روی پایه بگذار و با انگشت یا ماوس طرح را روی کاغذ واقعی تنظیم کن!</div>
  </div>

<script>
  const LAYERS = {{
    rough: "{b64_rough}",
    sketch: "{b64_sketch}",
    block: "{b64_block}",
    final: "{b64_final}"
  }};
  let stream = null;
  let facing = "environment";
  let multiplyOn = true;
  let mirrored = false;
  let dx = 0, dy = 0, dragging = false, sx = 0, sy = 0;

  async function startCam() {{
    const msg = document.getElementById("statusMsg");
    try {{
      if (stream) stream.getTracks().forEach(t => t.stop());
      stream = await navigator.mediaDevices.getUserMedia({{
        video: {{ facingMode: {{ ideal: facing }}, width: {{ ideal: 1280 }}, height: {{ ideal: 720 }} }},
        audio: false
      }});
      document.getElementById("cam").srcObject = stream;
      msg.textContent = "✅ دوربین فعال شد! طرح را با کشیدن (Drag) و اسلایدر اندازه دقیقاً روی کاغذت تنظیم کن و با مداد بکش.";
    }} catch (e) {{
      msg.textContent = "⚠️ دسترسی به دوربین داده نشد یا دوربین پیدا نشد: " + e.message;
    }}
  }}

  function flipCam() {{
    facing = (facing === "environment") ? "user" : "environment";
    startCam();
  }}

  function changeLayer() {{
    const v = document.getElementById("layerSel").value;
    const ov = document.getElementById("overlay");
    ov.src = LAYERS[v];
    // For sketch layers, multiply mode makes white paper 100% invisible!
    multiplyOn = (v === "rough" || v === "sketch");
    ov.style.mixBlendMode = multiplyOn ? "multiply" : "normal";
    document.getElementById("blendBtn").textContent = "✨ حذف پس‌زمینه سفید: " + (multiplyOn ? "روشن" : "خاموش");
  }}

  function toggleBlend() {{
    multiplyOn = !multiplyOn;
    document.getElementById("overlay").style.mixBlendMode = multiplyOn ? "multiply" : "normal";
    document.getElementById("blendBtn").textContent = "✨ حذف پس‌زمینه سفید: " + (multiplyOn ? "روشن" : "خاموش");
  }}

  function toggleMirror() {{
    mirrored = !mirrored;
    updateTransform();
  }}

  function updateTransform() {{
    const ov = document.getElementById("overlay");
    const op = document.getElementById("opRng").value / 100.0;
    const sc = document.getElementById("scRng").value / 100.0;
    const fx = mirrored ? -sc : sc;
    ov.style.opacity = op;
    ov.style.transform = `translate(calc(-50% + ${{dx}}px), calc(-50% + ${{dy}}px)) scale(${{fx}}, ${{sc}})`;
  }}

  function goFullscreen() {{
    const box = document.getElementById("arBox");
    if (box.requestFullscreen) box.requestFullscreen();
  }}

  // Drag overlay smoothly with mouse or touch to align on real paper
  const box = document.getElementById("arBox");
  box.addEventListener("pointerdown", e => {{ dragging = true; sx = e.clientX - dx; sy = e.clientY - dy; }});
  window.addEventListener("pointermove", e => {{
    if (!dragging) return;
    dx = e.clientX - sx; dy = e.clientY - sy;
    updateTransform();
  }});
  window.addEventListener("pointerup", () => {{ dragging = false; }});
</script>
</body>
</html>"""

    escaped = html_lib.escape(inner_doc, quote=True)
    return (
        f'<iframe srcdoc="{escaped}" allow="camera; fullscreen" '
        f'style="width:100%; height:670px; border:none; border-radius:16px; background:#fffdf9;"></iframe>'
    )


def build_step_guides(width_cm: float, height_cm: float, cell_w: float, cell_h: float) -> Dict[int, str]:
    return {
        1: (
            f"### 📐 گام ۱ از ۷ — کادربندی به سانتی‌متر و خطوط اصلی *(مداد HB، خیلی کم‌رنگ)*\n"
            f"- **ابعاد بوم پیشنهادی:** `{width_cm:g} × {height_cm:g} cm` — روی بومت یک شبکه **4×4** با خانه‌های **`{cell_w:g} × {cell_h:g} cm`** بکش.\n"
            f"- فقط خطوط پیوسته و اصلی تصویر را داخل هر خانه منتقل کن تا تناسبات ۱۰۰٪ دقیق شود."
        ),
        2: (
            f"### ✏️ گام ۲ از ۷ — اسکچ کامل مدادی *(مداد 2B)*\n"
            f"- با کمک انیمیشن اسکچ سمت چپ، تمام جزئیات و فرم‌های اصلی را روی طرح گام ۱ کامل کن.\n"
            f"- خطوط اضافه شبکه را بعد از اطمینان از تناسبات با پاک‌کن خمیری کمرنگ کن."
        ),
        3: (
            "### 🤎 گام ۳ از ۷ — زیررنگ‌گذاری تک‌رنگ سپیا *(قلم تخت پهن #14 — حدود ۲.۵ سانتی‌متر)*\n"
            "- یک تکنیک اصیل استادان رنگ‌روغن! فقط با **قهوه‌ای سوخته (Burnt Umber) + کمی سفید**، سایه‌ها و تیرگی‌های اصلی را خیلی رقیق روی بوم بگذار تا حجم کار دربیاید."
        ),
        4: (
            "### 🖌️ گام ۴ از ۷ — رنگ‌گذاری پایه و لکه‌های بزرگ *(قلم تخت #12 — حدود ۲ سانتی‌متر)*\n"
            "- از تب **قطره‌چکان ساخت رنگ**، رنگ هر ناحیه بزرگ را بساز و کل بوم را با لکه‌های ساده و تخت پر کن (فعلاً سراغ جزئیات ریز نرو)."
        ),
        5: (
            "### 🌗 گام ۵ از ۷ — سایه‌ها و حجم سه‌بعدی *(قلم متوسط #8 — حدود ۱ سانتی‌متر)*\n"
            "- تیک **«📍 نشان بده کجا را رنگ کنم»** را بزن! نواحی دارای کادر نارنجی دقیقاً جاهایی هستند که باید سایه‌های عمیق‌تر و حجم اضافه کنی."
        ),
        6: (
            "### ✨ گام ۶ از ۷ — جزئیات میانی و بافت قلم‌مو *(قلم گرد #3 — حدود ۴ میلی‌متر)*\n"
            "- لبه‌های مهم را تمیز کن، بافت اشیا را بکش و انتقال بین رنگ‌های کنار هم را با قلم نرم محو کن."
        ),
        7: (
            "### 🌟 گام ۷ از ۷ — هایلایت‌ها و ضربه‌های نهایی *(قلم ریز #0-#1 — ۱ تا ۲ میلی‌متر)*\n"
            "- با رنگ غلیظ و روشن، آخرین نقطه‌های نور و کنتراست تیز (نواحی کادر نارنجی) را بزن تا نقاشی زنده و تمام شود!"
        ),
    }


def load_paintpath_model(model_dir: str = "", ckpt_path: str = "", hf_repo: str = ""):
    global MODEL
    token = os.environ.get("HF_TOKEN") or None
    init_dev = torch.device("cpu") if ON_SPACES else torch.device("cuda" if torch.cuda.is_available() else "cpu")

    if model_dir and Path(model_dir).exists() and (Path(model_dir) / "config.json").exists():
        MODEL = PaintPathNetV2.from_pretrained(model_dir, pretrained=False).to(init_dev).eval()
        return

    repo = hf_repo or DEFAULT_HF_REPO
    if repo:
        MODEL = PaintPathNetV2.from_pretrained(repo, pretrained=False, token=token).to(init_dev).eval()
        return

    if ckpt_path and Path(ckpt_path).exists():
        m = PaintPathNetV2(pretrained=False).to(init_dev)
        ckpt = torch.load(ckpt_path, map_location=init_dev)
        m.load_state_dict(ckpt["model"] if "model" in ckpt else ckpt)
        MODEL = m.eval()


def _gpu_decorator(fn):
    if spaces is not None and ON_SPACES:
        return spaces.GPU(fn)
    return fn


@_gpu_decorator
@torch.no_grad()
def run_paintpath_studio(input_img: np.ndarray, width_cm: float, num_colors: int):
    if input_img is None or MODEL is None:
        return None, "", None, None, None, "لطفاً ابتدا یک نقاشی آپلود کن.", 1, 1.0, [], None, None, None, "", gr.update(), None, None, ""

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

    clean = auto_crop_borders(input_img)
    h, w = clean.shape[:2]
    # Keep true high-res ~1024px original for crisp fullscreen & zooming
    hi_scale = min(1.0, 1024.0 / max(h, w))
    orig_hi = cv2.resize(clean, (int(round(w * hi_scale)), int(round(h * hi_scale))), interpolation=cv2.INTER_AREA)

    scale = 512.0 / max(h, w)
    nw = max(64, (int(round(w * scale)) // 32) * 32)
    nh = max(64, (int(round(h * scale)) // 32) * 32)
    resized = cv2.resize(clean, (nw, nh), interpolation=cv2.INTER_AREA)

    inp = torch.from_numpy(resized).permute(2, 0, 1).unsqueeze(0).float().to(dev) / 255.0
    gpu_name = torch.cuda.get_device_name(0) if dev.type == "cuda" else ""
    use_amp = (dev.type == "cuda") and ("1650" not in gpu_name and "1660" not in gpu_name)

    # Run all 6 native PaintPathNetV2 stages + Real Aesthetic Score + Deep Focal Map!
    stages_v2 = []
    aes_val = 7.5
    with torch.amp.autocast("cuda", enabled=use_amp, dtype=torch.float16):
        focal_t = MODEL.extract_focal_map(inp)
        for s_idx in range(6):
            st = torch.tensor([s_idx], dtype=torch.long, device=dev)
            pred, aes = MODEL(inp, st)
            if s_idx == 0:
                aes_val = float(aes[0].float().clamp(0, 1).item()) * 10.0
            arr = np.ascontiguousarray((pred[0].float().clamp(0, 1).permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8))
            stages_v2.append(arr)

    focal_01 = focal_t[0, 0].float().cpu().numpy()
    m_rough = polish_continuous_sketch(stages_v2[0])
    m_sketch = polish_continuous_sketch(stages_v2[1])
    m_sepia = stages_v2[2]
    m_block = stages_v2[3]
    m_shadow = stages_v2[4]
    m_detail = stages_v2[5]

    # Smooth animations at fast 512px
    sketch_gif = make_smooth_sketch_animation(m_rough, m_sketch, float(width_cm))
    timelapse_gif = make_timelapse_gif([m_rough, m_sketch, m_sepia, m_block, m_shadow, m_detail, resized])

    # Upscale ALL interactive display stages to crisp 1024px so Maximize & Zoom are razor-sharp!
    hi_rough = upscale_hi_res(m_rough, 1024, sharpen=True)
    hi_sketch = upscale_hi_res(m_sketch, 1024, sharpen=True)
    hi_sepia = upscale_hi_res(m_sepia, 1024, sharpen=False)
    hi_block = upscale_hi_res(m_block, 1024, sharpen=False)
    hi_shadow = upscale_hi_res(m_shadow, 1024, sharpen=True)
    hi_detail = upscale_hi_res(m_detail, 1024, sharpen=True)
    hi_final = cv2.resize(orig_hi, (hi_detail.shape[1], hi_detail.shape[0]), interpolation=cv2.INTER_LANCZOS4)

    # Render centimeter ruler & 4x4 grid AT 1024px for ultra-sharp readable numbers!
    st1_cm, height_cm, cell_w, cell_h = draw_cm_ruler_grid(hi_rough, float(width_cm), grid_n=4)
    st2_cm, _, _, _ = draw_cm_ruler_grid(hi_sketch, float(width_cm), grid_n=4)

    guides = build_step_guides(float(width_cm), height_cm, cell_w, cell_h)
    score_html = render_aesthetic_score_html(aes_val, float(width_cm), height_cm, cell_w, cell_h)

    step_imgs = {1: st1_cm, 2: st2_cm, 3: hi_sepia, 4: hi_block, 5: hi_shadow, 6: hi_detail, 7: hi_final}
    blank_hi = np.full_like(hi_final, 248)
    paint_zones = {
        1: st1_cm,
        2: st2_cm,
        3: make_clear_paint_zones(blank_hi, hi_sepia),
        4: make_clear_paint_zones(hi_sepia, hi_block),
        5: make_clear_paint_zones(hi_block, hi_shadow),
        6: make_clear_paint_zones(hi_shadow, hi_detail),
        7: make_clear_paint_zones(hi_detail, hi_final),
    }

    gallery_items = [
        (st1_cm, "۱. کادر و خطوط اصلی (cm)"),
        (st2_cm, "۲. اسکچ کامل مدادی"),
        (hi_sepia, "۳. زیررنگ سپیا"),
        (hi_block, "۴. رنگ‌گذاری پایه"),
        (hi_shadow, "۵. سایه‌ها و حجم"),
        (hi_detail, "۶. جزئیات میانی"),
        (hi_final, "۷. نقاشی نهایی"),
    ]

    palette = extract_physical_palette(resized, k=int(num_colors))
    pal_card = render_palette_card(palette)
    loc_img, loc_html = highlight_target_rgb_on_canvas(hi_final, palette[0].rgb)
    color_choices = [f"رنگ #{c.index + 1} ({c.hex}) — {c.proportion * 100:.1f}%" for c in palette]

    focal_hi = cv2.resize(focal_01, (hi_final.shape[1], hi_final.shape[0]), interpolation=cv2.INTER_LINEAR)
    attention_img = make_attention_overlay(hi_final, focal_hi)
    value_study = make_value_study_3tone(hi_final)
    ar_html = build_ar_camera_html(m_rough, m_sketch, m_block, resized)

    state = {
        "resized": hi_final,
        "step_imgs": step_imgs,
        "paint_zones": paint_zones,
        "guides": guides,
        "palette": palette,
        "zoom_cx": 0.5,
        "zoom_cy": 0.5,
    }

    return (
        state,
        score_html,
        sketch_gif,
        timelapse_gif,
        step_imgs[1],
        guides[1],
        1,
        1.0,
        gallery_items,
        hi_final,
        pal_card,
        loc_img,
        loc_html,
        gr.update(choices=color_choices, value=color_choices[0]),
        attention_img,
        value_study,
        ar_html,
    )


def render_slide(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict]):
    if not state:
        return None, "ابتدا یک نقاشی آپلود کن.", 1
    s = max(1, min(7, int(step_num)))
    base = state["paint_zones"][s] if show_zones else state["step_imgs"][s]
    zoomed = render_zoom_crop(base, float(zoom_level), state.get("zoom_cx", 0.5), state.get("zoom_cy", 0.5))
    return zoomed, state["guides"][s], s


def prev_slide(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict]):
    return render_slide(max(1, int(step_num) - 1), show_zones, zoom_level, state)


def next_slide(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict]):
    return render_slide(min(7, int(step_num) + 1), show_zones, zoom_level, state)


def on_slide_click_zoom(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict], evt: gr.SelectData):
    """Click anywhere on the slide to center the zoom lens right on that detail!"""
    if not state:
        return None, "ابتدا یک نقاشی آپلود کن.", 1, 1.0
    s = max(1, min(7, int(step_num)))
    base = state["paint_zones"][s] if show_zones else state["step_imgs"][s]
    h, w = base.shape[:2]
    # If currently at 1x, clicking auto-zooms to 2.5x right where clicked; otherwise re-centers zoom
    new_zoom = 2.5 if float(zoom_level) <= 1.05 else float(zoom_level)
    state["zoom_cx"] = float(np.clip(evt.index[0] / max(w, 1), 0.0, 1.0))
    state["zoom_cy"] = float(np.clip(evt.index[1] / max(h, 1), 0.0, 1.0))
    zoomed = render_zoom_crop(base, new_zoom, state["zoom_cx"], state["zoom_cy"])
    return zoomed, state["guides"][s], s, new_zoom


def on_color_dropdown(color_label: str, state: Optional[dict]):
    if not state or not color_label:
        return None, ""
    try:
        idx = int(color_label.split("#")[1].split(" ")[0]) - 1
    except Exception:
        idx = 0
    idx = max(0, min(idx, len(state["palette"]) - 1))
    return highlight_target_rgb_on_canvas(state["resized"], state["palette"][idx].rgb)


def on_canvas_click(state: Optional[dict], evt: gr.SelectData):
    if not state:
        return None, "<p>ابتدا نقاشی را تحلیل کن.</p>"
    img = state["resized"]
    x, y = int(evt.index[0]), int(evt.index[1])
    h, w = img.shape[:2]
    x, y = max(0, min(x, w - 1)), max(0, min(y, h - 1))
    patch = img[max(0, y - 2) : min(h, y + 3), max(0, x - 2) : min(w, x + 3)]
    mean_rgb = tuple(int(round(v)) for v in patch.reshape(-1, 3).mean(axis=0))
    return highlight_target_rgb_on_canvas(img, mean_rgb, tolerance=24.0)


# ============================================================
# 4. Crisp, High-Contrast Flagship UI (Light & Dark Mode Safe)
# ============================================================
CUSTOM_CSS = """
.studio-hero {
    background: linear-gradient(135deg, #fff9ef 0%, #fef2dc 50%, #eef2ff 100%) !important;
    border: 2px solid #e5d1b3 !important;
    border-radius: 22px !important;
    padding: 26px 30px !important;
    margin-bottom: 18px !important;
    text-align: center !important;
    box-shadow: 0 10px 28px rgba(15, 23, 42, 0.06) !important;
}
.studio-hero h1 {
    margin: 0 0 8px 0 !important;
    font-size: 2.1rem !important;
    font-weight: 900 !important;
    color: #111827 !important;
}
.studio-hero p {
    margin: 0 auto 16px auto !important;
    max-width: 780px !important;
    font-size: 1.04rem !important;
    font-weight: 500 !important;
    color: #374151 !important;
}
.brand-links {
    display: flex !important;
    justify-content: center !important;
    flex-wrap: wrap !important;
    gap: 10px !important;
}
.brand-links a {
    display: inline-flex !important;
    align-items: center !important;
    gap: 6px !important;
    padding: 8px 16px !important;
    border-radius: 999px !important;
    background: #1f2937 !important;
    color: #ffffff !important;
    text-decoration: none !important;
    font-size: 0.88rem !important;
    font-weight: 700 !important;
}
.brand-links a:hover {
    background: #d97706 !important;
    color: #ffffff !important;
}
.studio-footer {
    text-align: center !important;
    margin-top: 26px !important;
    padding: 16px !important;
    background: #fff9ef !important;
    border: 1px solid #e5d1b3 !important;
    border-radius: 14px !important;
    color: #1f2937 !important;
    font-size: 0.94rem !important;
    font-weight: 600 !important;
}
.studio-footer a {
    color: #b45309 !important;
    text-decoration: none !important;
    font-weight: 800 !important;
}
"""


def build_ui():
    with gr.Blocks(title="PaintPath Studio v2 — Ali Jahani") as demo:
        studio_state = gr.State(value=None)

        gr.HTML(
            """
            <div class="studio-hero">
                <h1>🎨 PaintPath Studio v2 — هوش مصنوعی مربی نقاشی تو</h1>
                <p>همیشه انسان کار را برای هوش مصنوعی ساده می‌کند؛ این بار هوش مصنوعی نقاشی را با <b>خط‌کش واقعی به سانتی‌متر، انیمیشن اسکچ، ۷ مرحله آموزشی و فرمول ساخت رنگ</b> ساده می‌کند تا تو نقاش بشوی!</p>
                <div class="brand-links">
                    <a href="https://jahaniwww.com" target="_blank">👤 Ali Jahani — jahaniwww.com</a>
                    <a href="https://t.me/tarfandoonchannel" target="_blank">✈️ Telegram: @tarfandoonchannel</a>
                    <a href="https://huggingface.co/tarfandoon/paintpath-net-v2" target="_blank">🤗 Model: PaintPathNet v2 (512px)</a>
                </div>
            </div>
            """
        )

        # Clean Upload + Canvas Size Bar
        with gr.Row(equal_height=True):
            with gr.Column(scale=2):
                in_img = gr.Image(type="numpy", label="۱. نقاشی مورد نظرت را اینجا آپلود کن", height=270)
            with gr.Column(scale=1):
                gr.Markdown("### 📐 تنظیم بوم واقعی و شروع")
                width_cm = gr.Slider(15, 100, value=40, step=5, label="عرض بوم واقعی تو (سانتی‌متر)")
                num_colors = gr.Slider(6, 12, value=8, step=1, label="تعداد رنگ‌های پالت اصلی")
                run_btn = gr.Button("✨ ساخت نقشه ۷ مرحله‌ای + تحلیل کامل", variant="primary", size="lg")

        score_banner = gr.HTML("")

        with gr.Tabs():
            # TAB 1: Interactive 7-Stage Slides + Smooth Animations
            with gr.Tab("🎬 ۱. آموزش ۷ مرحله‌ای + انیمیشن اسکچ و فیلم"):
                with gr.Row():
                    with gr.Column(scale=2):
                        gr.Markdown("### 🖼️ اسلاید تعاملی ۷ مرحله‌ای (کیفیت بالا 1024px — برای زوم روی هر نقطه کلیک کن!)")
                        slide_img = gr.Image(label="بوم هدف (کلیک روی تصویر = زوم روی جزئیات | آیکون فول‌اسکرین = تمام‌صفحه HD)", height=540, interactive=False)
                        with gr.Row():
                            prev_btn = gr.Button("⬅️ مرحله قبل")
                            next_btn = gr.Button("مرحله بعد ➡️", variant="primary")
                            reset_zoom_btn = gr.Button("🔍 ریست زوم (1×)")
                        with gr.Row():
                            step_slider = gr.Slider(1, 7, value=1, step=1, label="شماره مرحله (۱ تا ۷)")
                            zoom_slider = gr.Slider(1.0, 4.0, value=1.0, step=0.25, label="🔍 بزرگ‌نمایی / زوم (1× تا 4×)")
                        zone_chk = gr.Checkbox(value=False, label="📍 نشان بده در این مرحله کجا را رنگ کنم!")
                        slide_guide = gr.Markdown("پس از آپلود نقاشی، اینجا راهنمای دقیق هر مرحله (با سایز قلم‌مو و ابعاد بوم به سانتی‌متر) نمایش داده می‌شود.")

                    with gr.Column(scale=1):
                        gr.Markdown("### ✏️ انیمیشن روان اسکچ کشیدن (خطوط پیوسته)")
                        sketch_gif_out = gr.Image(label="ترسیم مرحله‌به‌مرحله خطوط اصلی و جزئیات", interactive=False)
                        gr.Markdown("### 🎥 فیلم تایم‌لپس کامل ۷ مرحله‌ای")
                        timelapse_out = gr.Image(label="سفر کامل از خطوط اولیه تا نقاشی نهایی", interactive=False)

                gr.Markdown("#### 🗺️ نمای یکپارچه هر ۷ مرحله کنار هم:")
                gallery_out = gr.Gallery(columns=7, height=190, label="مسیر کامل نقاشی")

            # TAB 2: Interactive Click-to-Extract Color Mixer & Canvas Locator
            with gr.Tab("🎨 ۲. قطره‌چکان ساخت رنگ تعاملی (کلیک روی نقاشی!)"):
                gr.Markdown("### 💧 روی هر نقطه‌ای از نقاشی سمت چپ کلیک کن تا **فرمول دقیق ترکیب رنگ تیوپی‌اش** و **تمام جاهایی که آن رنگ روی بوم هست** را ببینی!")
                with gr.Row():
                    clickable_img = gr.Image(label="👆 روی هر نقطه نقاشی کلیک کن", interactive=False)
                    color_loc_img = gr.Image(label="📍 تمام نقاطی که باید این رنگ را بزنی (کادر قرمز)", interactive=False)
                with gr.Row():
                    with gr.Column(scale=1):
                        color_dropdown = gr.Dropdown(choices=[], label="یا از رنگ‌های اصلی پالت انتخاب کن:", interactive=True)
                        color_recipe_html = gr.HTML("<div style='padding:12px; color:#4b5563;'>روی هر نقطه‌ای از نقاشی کلیک کن تا دستور ساخت رنگش را ببینی.</div>")
                    with gr.Column(scale=1):
                        pal_out = gr.Image(label="کارت کامل پالت رنگ فیزیکی")

            # TAB 3: Dedicated Eye Attention, Aesthetic Score & Value Study
            with gr.Tab("👁️ ۳. کانون توجه چشم و نورپردازی"):
                gr.Markdown(
                    "### 🔥 نگاهِ مغز هوش مصنوعی به نقاشی\n"
                    "مدل **`PaintPathNet v2`** نشان می‌دهد **چشم مخاطب اول به کجا خیره می‌شود** (نواحی زرد و قرمز) و در کنارش **مطالعه ۳ سطحی نور و سایه** را می‌دهد."
                )
                with gr.Row():
                    attn_out = gr.Image(label="🔥 نقشه کانون توجه چشم (ConvNeXt Deep Focal Map)")
                    val_out = gr.Image(label="🌗 مطالعه ارزش نوری ۳ سطحی (تیره / میانی / روشن)")

            # TAB 4: AR Live Camera Tracing (Phone Back Camera & Laptop Webcam!)
            with gr.Tab("📱 ۴. دوربین AR (کشیدن مستقیم روی کاغذ واقعی!)"):
                gr.Markdown(
                    "### 📷 حالت واقعیت افزوده (AR Canvas Tracing) — بدون نیاز به اپلیکیشن!\n"
                    "دوربین گوشی (یا وبکم) را روشن کن، پس‌زمینه سفید اسکچ **خودکار حذف می‌شود** و فقط خطوط مدادی روی تصویر زنده کاغذت می‌افتند — گوشی را روی پایه بگذار و مستقیم با مداد روی کاغذ واقعی بکش!"
                )
                ar_camera_out = gr.HTML(
                    "<div style='padding:24px; text-align:center; background:#fff9ef; border:1px solid #e5d1b3; border-radius:14px; color:#374151;'>ابتدا در بالای صفحه یک نقاشی آپلود کن و دکمه «✨ ساخت نقشه ۷ مرحله‌ای» را بزن تا دوربین AR فعال شود!</div>"
                )

            # TAB 5: Check My Hand-Painted Canvas
            with gr.Tab("🏆 ۵. ارزیابی نقاشیِ دستِ تو"):
                gr.Markdown("از نقاشی‌ای که خودت با دست روی بوم یا کاغذ کشیدی عکس بگیر و اینجا آپلود کن تا **امتیاز ۰ تا ۱۰۰ و نقشه اصلاح** بگیری!")
                with gr.Row():
                    user_canvas_in = gr.Image(type="numpy", label="📸 عکس نقاشیِ دستِ خودت")
                    feedback_img_out = gr.Image(label="🔍 نقشه اصلاح (قرمز = نیاز به اصلاح، آبی = عالی)")
                check_btn = gr.Button("✨ ارزیابی نقاشی من", variant="primary")
                feedback_md_out = gr.Markdown("")

        gr.HTML(
            """
            <div class="studio-footer">
                ساخته‌شده با ❤️ توسط <b>Ali Jahani</b> &nbsp;|&nbsp;
                🌐 وبسایت: <a href="https://jahaniwww.com" target="_blank">jahaniwww.com</a> &nbsp;|&nbsp;
                ✈️ کانال تلگرام: <a href="https://t.me/tarfandoonchannel" target="_blank">@tarfandoonchannel</a>
            </div>
            """
        )

        # Events
        run_btn.click(
            fn=run_paintpath_studio,
            inputs=[in_img, width_cm, num_colors],
            outputs=[
                studio_state,
                score_banner,
                sketch_gif_out,
                timelapse_out,
                slide_img,
                slide_guide,
                step_slider,
                zoom_slider,
                gallery_out,
                clickable_img,
                pal_out,
                color_loc_img,
                color_recipe_html,
                color_dropdown,
                attn_out,
                val_out,
                ar_camera_out,
            ],
        )

        step_slider.change(render_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider])
        zone_chk.change(render_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider])
        zoom_slider.change(render_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider])
        prev_btn.click(prev_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider])
        next_btn.click(next_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider])
        slide_img.select(on_slide_click_zoom, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider, zoom_slider])
        reset_zoom_btn.click(lambda s, z, st: (*render_slide(s, z, 1.0, st), 1.0), [step_slider, zone_chk, studio_state], [slide_img, slide_guide, step_slider, zoom_slider])
        color_dropdown.change(on_color_dropdown, [color_dropdown, studio_state], [color_loc_img, color_recipe_html])
        clickable_img.select(on_canvas_click, [studio_state], [color_loc_img, color_recipe_html])
        check_btn.click(evaluate_amateur_painting, [in_img, user_canvas_in], [feedback_img_out, feedback_md_out])

    return demo


if ON_SPACES:
    load_paintpath_model(
        model_dir=str(HERE / "hf_model"),
        hf_repo=os.environ.get("HF_MODEL_REPO", DEFAULT_HF_REPO),
    )
    demo = build_ui()
    demo.launch(theme=gr.themes.Soft(), css=CUSTOM_CSS)
elif __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--model-dir", type=str, default=str(HERE / "hf_model"))
    parser.add_argument("--ckpt", type=str, default="")
    parser.add_argument("--hf-repo", type=str, default=os.environ.get("HF_MODEL_REPO", DEFAULT_HF_REPO))
    parser.add_argument("--port", type=int, default=7861)
    args = parser.parse_args()

    load_paintpath_model(args.model_dir, args.ckpt, args.hf_repo)
    demo = build_ui()
    demo.launch(server_name="127.0.0.1", server_port=args.port, inbrowser=True, theme=gr.themes.Soft(), css=CUSTOM_CSS)