Spaces:
Running on Zero

File size: 57,114 Bytes
7c21a79
 
7598b9f
7c21a79
7598b9f
7c21a79
0efbac7
7c21a79
074bf36
 
 
aec4fce
074bf36
7598b9f
299b4fb
 
 
 
9483dec
 
7598b9f
299b4fb
074bf36
9483dec
 
 
 
 
 
 
 
 
7598b9f
 
 
39c97f2
 
 
 
9483dec
299b4fb
7598b9f
 
 
41c9330
 
 
 
 
 
 
 
0efbac7
 
299b4fb
 
7598b9f
299b4fb
 
9483dec
 
39c97f2
9483dec
 
39c97f2
074bf36
aec4fce
 
7598b9f
 
39c97f2
 
9483dec
2ea7e08
7598b9f
299b4fb
7598b9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299b4fb
7598b9f
7c7f2e8
7598b9f
7c7f2e8
 
 
7598b9f
9483dec
39c97f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7598b9f
9483dec
 
39c97f2
 
 
 
 
 
 
 
9483dec
 
 
39c97f2
9483dec
 
 
 
7598b9f
9483dec
 
 
 
 
 
 
aec4fce
 
9483dec
 
 
 
 
 
7598b9f
 
 
 
 
 
 
 
931fa5d
 
 
 
 
 
 
 
 
 
7598b9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
931fa5d
 
 
 
7598b9f
 
931fa5d
 
 
 
 
7598b9f
 
 
 
 
 
 
 
 
 
931fa5d
 
 
 
 
7598b9f
 
 
 
 
 
 
 
 
 
0efbac7
 
931fa5d
 
 
 
 
 
 
0efbac7
 
931fa5d
 
 
 
 
 
 
 
 
 
 
 
0efbac7
931fa5d
 
 
 
0efbac7
 
 
931fa5d
 
 
 
 
 
 
39c97f2
9483dec
 
 
 
7598b9f
9483dec
 
 
 
 
 
 
299b4fb
9483dec
39c97f2
299b4fb
 
39c97f2
299b4fb
39c97f2
299b4fb
 
7598b9f
39c97f2
7598b9f
39c97f2
7598b9f
 
 
 
 
 
 
41c9330
39c97f2
 
 
 
 
 
 
 
 
 
 
 
7598b9f
39c97f2
 
 
 
 
 
 
 
 
 
7598b9f
39c97f2
 
 
 
 
299b4fb
 
9483dec
 
 
 
 
 
 
 
 
 
 
 
 
 
41c9330
 
9483dec
 
 
 
 
 
 
 
 
 
41c9330
9483dec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0efbac7
 
 
931fa5d
9483dec
 
 
 
 
39c97f2
9483dec
074bf36
 
7598b9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
931fa5d
7598b9f
 
e9f31c5
7598b9f
 
931fa5d
 
 
7598b9f
 
 
 
931fa5d
 
 
 
 
 
 
 
7598b9f
 
931fa5d
 
 
 
7598b9f
931fa5d
 
 
 
 
 
 
e9f31c5
931fa5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f31c5
7598b9f
e9f31c5
 
39c97f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7598b9f
 
 
 
 
e9f31c5
7598b9f
 
 
 
2610306
7598b9f
 
2610306
7598b9f
 
3c377ed
7598b9f
931fa5d
7598b9f
e40ce7e
7598b9f
 
 
 
 
 
 
 
 
 
 
 
 
931fa5d
7598b9f
 
 
 
 
 
 
e40ce7e
7598b9f
 
 
 
e40ce7e
7598b9f
 
931fa5d
 
 
41c9330
 
 
7598b9f
e40ce7e
7598b9f
 
 
e40ce7e
 
7598b9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e40ce7e
39c97f2
e40ce7e
e9f31c5
41c9330
 
 
 
 
 
 
 
 
 
 
 
 
 
0efbac7
 
41c9330
 
 
7598b9f
 
 
 
 
 
 
 
 
 
 
 
e9f31c5
be357e4
7598b9f
 
 
 
 
 
 
 
be357e4
 
0b6f56b
 
 
 
 
 
 
41c9330
0b6f56b
 
 
 
 
 
 
 
 
 
931fa5d
 
 
0b6f56b
 
 
 
 
931fa5d
 
 
0b6f56b
 
 
 
7c21a79
 
 
 
 
 
 
 
 
 
ca0df08
 
 
7c21a79
 
 
 
 
 
 
 
 
 
 
 
 
3c377ed
 
 
 
 
 
 
 
 
9483dec
0b6f56b
 
41c9330
0b6f56b
 
3c377ed
 
 
9483dec
3c377ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9483dec
 
 
931fa5d
 
 
0b6f56b
 
7c21a79
 
0efbac7
 
7c21a79
 
 
 
 
 
41c9330
 
7c21a79
 
 
 
7598b9f
 
7c21a79
 
 
 
 
 
 
be357e4
 
0efbac7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ea7e08
 
 
 
 
 
 
 
 
 
 
9483dec
7598b9f
9483dec
 
 
41c9330
9483dec
7598b9f
9483dec
7598b9f
0efbac7
074bf36
2ea7e08
7c21a79
7598b9f
 
2ea7e08
 
 
7598b9f
 
 
9483dec
 
41c9330
 
 
9483dec
7598b9f
9483dec
 
2ea7e08
7c7f2e8
 
 
299b4fb
7c7f2e8
 
 
299b4fb
 
 
 
 
7c21a79
39c97f2
931fa5d
ca0df08
7c21a79
 
41c9330
 
 
 
 
 
 
 
 
 
39c97f2
931fa5d
7c21a79
41c9330
 
 
 
 
 
 
 
 
 
 
 
 
570f550
2610306
41b6608
7c7f2e8
 
 
931fa5d
 
 
 
 
 
0b6f56b
7c21a79
39c97f2
 
ca0df08
931fa5d
 
 
 
7c21a79
 
2610306
39c97f2
a15cb8b
39c97f2
931fa5d
 
39c97f2
 
 
41c9330
39c97f2
a15cb8b
9483dec
 
41c9330
9483dec
 
41c9330
9483dec
 
 
 
a15cb8b
931fa5d
 
7598b9f
41c9330
 
 
 
 
 
 
 
a15cb8b
39c97f2
 
 
41c9330
 
 
 
 
 
 
 
 
39c97f2
a15cb8b
39c97f2
 
 
 
a15cb8b
 
931fa5d
 
 
39c97f2
 
 
0efbac7
 
 
41c9330
931fa5d
 
 
9483dec
 
 
 
 
 
 
 
931fa5d
 
 
 
9483dec
 
 
 
 
931fa5d
 
 
 
9483dec
 
41c9330
9483dec
 
931fa5d
 
 
 
9483dec
 
931fa5d
 
 
 
 
 
2ea7e08
7598b9f
7c7f2e8
 
931fa5d
 
 
7598b9f
 
e40ce7e
931fa5d
7598b9f
 
931fa5d
 
 
 
 
 
41b6608
7598b9f
074bf36
7598b9f
931fa5d
 
 
bfb98c8
931fa5d
7598b9f
 
 
 
 
 
 
 
 
 
 
 
 
2610306
931fa5d
 
 
7c21a79
be357e4
 
 
 
 
 
 
2ea7e08
9483dec
2ea7e08
9483dec
 
 
 
 
 
 
 
 
 
 
 
7598b9f
 
 
 
931fa5d
 
 
7598b9f
9483dec
41c9330
 
 
 
 
 
9483dec
 
931fa5d
 
9483dec
 
931fa5d
 
9483dec
 
 
7598b9f
9483dec
 
7598b9f
0b6f56b
 
 
 
41c9330
 
0b6f56b
 
be357e4
7598b9f
41c9330
 
 
 
 
 
 
 
 
 
7c21a79
 
7598b9f
 
 
 
931fa5d
 
 
7598b9f
 
 
41c9330
 
7c21a79
41c9330
 
7c21a79
 
be357e4
9483dec
0efbac7
 
41c9330
9483dec
be357e4
7c21a79
41c9330
 
 
7598b9f
 
 
 
41c9330
 
7598b9f
 
41c9330
7598b9f
 
 
 
 
 
 
 
41c9330
 
7598b9f
 
41c9330
7598b9f
 
 
 
7c21a79
 
41c9330
 
 
7c21a79
931fa5d
 
 
 
 
 
 
 
 
 
 
 
 
 
41c9330
 
 
931fa5d
0efbac7
41c9330
0efbac7
 
 
 
 
41c9330
0efbac7
41c9330
931fa5d
 
be357e4
9483dec
 
 
41c9330
 
 
 
 
 
 
9483dec
 
 
 
 
 
 
 
7598b9f
931fa5d
 
 
 
 
7598b9f
 
41c9330
9483dec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7598b9f
 
9483dec
 
 
7598b9f
9483dec
 
41c9330
931fa5d
 
7598b9f
 
 
 
 
 
 
 
 
41c9330
7598b9f
 
 
 
 
2ea7e08
9483dec
 
 
 
41c9330
 
9483dec
 
41c9330
7598b9f
 
 
9483dec
 
 
41c9330
 
931fa5d
 
 
9483dec
7598b9f
 
 
 
9483dec
 
 
41c9330
 
9483dec
 
7598b9f
 
 
 
9483dec
 
 
7c21a79
 
0efbac7
7598b9f
 
39c97f2
 
 
7c21a79
7598b9f
 
7c21a79
41c9330
 
7c21a79
 
 
 
41c9330
 
7c21a79
9483dec
7c21a79
7598b9f
7c21a79
9483dec
7c21a79
 
 
be357e4
0efbac7
7598b9f
41c9330
be357e4
9483dec
 
7598b9f
9483dec
 
 
0efbac7
9483dec
 
41c9330
9483dec
 
7598b9f
 
 
 
41c9330
7598b9f
 
9483dec
7598b9f
9483dec
7598b9f
 
be357e4
9483dec
7598b9f
9483dec
 
be357e4
0efbac7
2ea7e08
 
 
0efbac7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
074bf36
 
cf12bbe
 
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
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
import csv
import json
import math
import os
import re
import tempfile
from datetime import datetime

import cv2
import gradio as gr
import numpy as np
import spaces
import torch
from PIL import ExifTags, Image
from transformers import (
    AutoImageProcessor,
    AutoModelForDepthEstimation,
    AutoModelForSemanticSegmentation,
    AutoModelForZeroShotObjectDetection,
    AutoProcessor,
    Mask2FormerForUniversalSegmentation,
)

try:
    from transformers import Sam2Model, Sam2Processor

    HAS_SAM2 = True
except ImportError:
    from transformers import SamModel, SamProcessor

    HAS_SAM2 = False

MASK2FORMER_ID = "facebook/mask2former-swin-large-ade-semantic"
SEGFORMER_FALLBACK_ID = "nvidia/segformer-b2-finetuned-ade-512-512"
DEPTH_METRIC_ID = "depth-anything/Depth-Anything-V2-Metric-Indoor-Base-hf"
GDINO_PRIMARY_ID = "IDEA-Research/grounding-dino-base"
GDINO_FALLBACK_ID = "IDEA-Research/grounding-dino-tiny"
SAM2_PRIMARY_ID = "facebook/sam2.1-hiera-base-plus"
SAM2_FALLBACK_ID = "facebook/sam2.1-hiera-tiny"
SAM1_MODEL_ID = "facebook/sam-vit-base"

SQM_TO_SQFT = 10.7639104
FT_TO_M = 0.3048

CLADDING_PROMPTS = [
    "wood paneling",
    "fluted panel",
    "marble wall",
    "wall cladding",
]
AUTO_OPENING_PROMPTS = ["doorway", "archway", "mirror"]

CALIBRATION_LOG_PATH = os.path.join(tempfile.gettempdir(), "smart_area_calibration_log.jsonl")

seg_processor = None
seg_model = None
seg_is_mask2former = True
depth_processor = None
depth_model = None
gdino_processor = None
gdino_model = None
gdino_active_id = GDINO_PRIMARY_ID
sam_processor = None
sam_model = None
sam_active_id = SAM2_PRIMARY_ID


def get_models():
    global seg_processor, seg_model, seg_is_mask2former
    global depth_processor, depth_model
    global gdino_processor, gdino_model, gdino_active_id
    global sam_processor, sam_model, sam_active_id

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

    if seg_model is None:
        try:
            seg_processor = AutoImageProcessor.from_pretrained(MASK2FORMER_ID)
            seg_model = (
                Mask2FormerForUniversalSegmentation.from_pretrained(MASK2FORMER_ID)
                .to(device)
                .eval()
            )
            seg_is_mask2former = True
        except Exception:
            seg_processor = AutoImageProcessor.from_pretrained(SEGFORMER_FALLBACK_ID)
            seg_model = (
                AutoModelForSemanticSegmentation.from_pretrained(SEGFORMER_FALLBACK_ID)
                .to(device)
                .eval()
            )
            seg_is_mask2former = False

    if depth_model is None:
        depth_processor = AutoImageProcessor.from_pretrained(DEPTH_METRIC_ID)
        depth_model = (
            AutoModelForDepthEstimation.from_pretrained(DEPTH_METRIC_ID)
            .to(device)
            .eval()
        )

    if gdino_model is None:
        try:
            gdino_processor = AutoProcessor.from_pretrained(GDINO_PRIMARY_ID)
            gdino_model = (
                AutoModelForZeroShotObjectDetection.from_pretrained(GDINO_PRIMARY_ID)
                .to(device)
                .eval()
            )
            gdino_active_id = GDINO_PRIMARY_ID
        except Exception:
            gdino_processor = AutoProcessor.from_pretrained(GDINO_FALLBACK_ID)
            gdino_model = (
                AutoModelForZeroShotObjectDetection.from_pretrained(GDINO_FALLBACK_ID)
                .to(device)
                .eval()
            )
            gdino_active_id = GDINO_FALLBACK_ID

    if sam_model is None:
        if HAS_SAM2:
            try:
                sam_processor = Sam2Processor.from_pretrained(SAM2_PRIMARY_ID)
                sam_model = Sam2Model.from_pretrained(SAM2_PRIMARY_ID).to(device).eval()
                sam_active_id = SAM2_PRIMARY_ID
            except Exception:
                sam_processor = Sam2Processor.from_pretrained(SAM2_FALLBACK_ID)
                sam_model = Sam2Model.from_pretrained(SAM2_FALLBACK_ID).to(device).eval()
                sam_active_id = SAM2_FALLBACK_ID
        else:
            sam_processor = SamProcessor.from_pretrained(SAM1_MODEL_ID)
            sam_model = SamModel.from_pretrained(SAM1_MODEL_ID).to(device).eval()
            sam_active_id = SAM1_MODEL_ID

    return (
        seg_processor,
        seg_model,
        seg_is_mask2former,
        depth_processor,
        depth_model,
        gdino_processor,
        gdino_model,
        sam_processor,
        sam_model,
    )


def _parse_terms(csv_text):
    if not csv_text:
        return []
    return [t.strip().lower() for t in csv_text.split(",") if t.strip()]


def extract_focal_px_from_exif(img_pil, width, height):
    try:
        exif = img_pil.getexif()
        if exif:
            tag_map = {ExifTags.TAGS.get(k, k): v for k, v in exif.items()}
            f35 = tag_map.get("FocalLengthIn35mmFilm")
            if f35 and float(f35) > 5.0:
                focal_px = (float(f35) / 36.0) * float(max(width, height))
                return (
                    float(
                        np.clip(
                            focal_px,
                            0.55 * max(width, height),
                            1.8 * max(width, height),
                        )
                    ),
                    f"EXIF 35mm ({float(f35):.0f}mm)",
                )
    except Exception:
        pass
    return 0.85 * float(max(width, height)), "Default FOV (~60°)"


def parse_boq_scope(scope_text):
    txt = (scope_text or "").lower()

    coats_match = re.search(r"(\d+)\s*coat", txt)
    paint_coats = int(coats_match.group(1)) if coats_match else 2

    wastage_match = re.search(r"(\d+(?:\.\d+)?)\s*%\s*wast", txt)
    wastage_pct = float(wastage_match.group(1)) if wastage_match else 10.0

    gst_match = re.search(r"(\d+(?:\.\d+)?)\s*%\s*gst", txt)
    gst_pct = float(gst_match.group(1)) if gst_match else 18.0

    tile_match = re.search(
        r"(\d+(?:\.\d+)?)\s*[x×]\s*(\d+(?:\.\d+)?)\s*(ft|feet|inch|in|mm)?", txt
    )
    tile_sqft = 8.0
    tile_label = "2x4 ft"
    if tile_match:
        a, b, unit = (
            float(tile_match.group(1)),
            float(tile_match.group(2)),
            tile_match.group(3) or "ft",
        )
        if unit in ("inch", "in"):
            tile_sqft = (a * b) / 144.0
            tile_label = f"{a:g}x{b:g} in"
        elif unit == "mm":
            tile_sqft = (a * b) / 92903.04
            tile_label = f"{a:g}x{b:g} mm"
        else:
            tile_sqft = a * b
            tile_label = f"{a:g}x{b:g} ft"

    include_ceiling_paint = (
        "ceiling" in txt
        and "no ceiling" not in txt
        and "exclude ceiling" not in txt
    )
    return {
        "paint_coats": max(1, min(paint_coats, 4)),
        "wastage_pct": float(np.clip(wastage_pct, 0.0, 35.0)),
        "gst_pct": float(np.clip(gst_pct, 0.0, 28.0)),
        "tile_sqft": max(tile_sqft, 0.25),
        "tile_label": tile_label,
        "include_ceiling_paint": include_ceiling_paint,
    }


def apply_mask_nms(detected_objects, iou_thresh=0.45, contain_thresh=0.65):
    """Deduplicate overlapping and nested SAM masks per label using IoU + containment."""
    if not detected_objects:
        return []

    sorted_objs = sorted(detected_objects, key=lambda o: o["score"], reverse=True)
    kept = []
    for cand in sorted_objs:
        cm = cand["mask"] > 0
        c_area = int(np.count_nonzero(cm))
        if c_area == 0:
            continue

        is_dup = False
        for k in kept:
            same_cls = (
                cand["label"] == k["label"]
                or cand["label"] in k["label"]
                or k["label"] in cand["label"]
            )
            if not same_cls:
                continue
            km = k["mask"] > 0
            k_area = int(np.count_nonzero(km))
            inter = int(np.count_nonzero(cm & km))
            if inter == 0:
                continue
            union = int(np.count_nonzero(cm | km))
            iou = inter / float(union) if union > 0 else 0.0
            containment = inter / float(min(c_area, k_area))
            if iou > iou_thresh or containment > contain_thresh:
                is_dup = True
                break
        if not is_dup:
            kept.append(cand)
    return kept


@spaces.GPU(duration=120)
def run_models(img_pil, prompt_terms):
    (
        s_proc,
        s_mod,
        is_m2f,
        d_proc,
        d_mod,
        g_proc,
        g_mod,
        sam_proc,
        sam_mod,
    ) = get_models()
    device = next(s_mod.parameters()).device
    w, h = img_pil.size
    img_flip = img_pil.transpose(Image.FLIP_LEFT_RIGHT)

    s_inputs = s_proc(images=img_pil, return_tensors="pt").to(device)
    s_inputs_flip = s_proc(images=img_flip, return_tensors="pt").to(device)
    d_inputs = d_proc(images=img_pil, return_tensors="pt").to(device)
    d_inputs_flip = d_proc(images=img_flip, return_tensors="pt").to(device)

    with torch.inference_mode():
        s_out = s_mod(**s_inputs)
        s_out_flip = s_mod(**s_inputs_flip)
        if is_m2f:
            pred_orig = (
                s_proc.post_process_semantic_segmentation(
                    s_out, target_sizes=[(h, w)]
                )[0]
                .detach()
                .cpu()
                .numpy()
            )
            pred_flip = np.fliplr(
                s_proc.post_process_semantic_segmentation(
                    s_out_flip, target_sizes=[(h, w)]
                )[0]
                .detach()
                .cpu()
                .numpy()
            )
            pred_map = pred_orig.copy()
            disagree = pred_orig != pred_flip
            if np.any(disagree):
                med = cv2.medianBlur(pred_orig.astype(np.uint8), 5)
                pred_map[disagree] = med[disagree]
        else:
            logits_orig = s_out.logits
            logits_flip = torch.flip(s_out_flip.logits, dims=[-1])
            pred_map = (
                ((logits_orig + logits_flip) * 0.5)
                .argmax(dim=1)
                .squeeze(0)
                .detach()
                .cpu()
                .numpy()
            )

        d_orig = d_mod(**d_inputs).predicted_depth.squeeze(0).detach().cpu().numpy()
        d_flip = np.fliplr(
            d_mod(**d_inputs_flip).predicted_depth.squeeze(0).detach().cpu().numpy()
        )
        d_pred = 0.5 * (d_orig + d_flip)

    id2label = getattr(s_mod.config, "id2label", {}) or {}

    detected_objects = []
    clean_terms = list(dict.fromkeys([t for t in prompt_terms if t]))
    if clean_terms:
        text_prompt = ". ".join(clean_terms) + "."
        g_inputs = g_proc(images=img_pil, text=text_prompt, return_tensors="pt").to(
            device
        )
        with torch.inference_mode():
            g_outputs = g_mod(**g_inputs)

        g_res = g_proc.post_process_grounded_object_detection(
            g_outputs,
            g_inputs.input_ids,
            threshold=0.35,
            text_threshold=0.28,
            target_sizes=[(h, w)],
        )[0]

        boxes = g_res["boxes"].detach().cpu().numpy()
        scores = g_res["scores"].detach().cpu().numpy()
        raw_labels = (
            g_res["text_labels"] if "text_labels" in g_res else g_res["labels"]
        )

        if len(boxes) > 0:
            order = np.argsort(-scores)[:22]
            boxes = boxes[order]
            scores = scores[order]
            raw_labels = [str(raw_labels[i]).strip().lower() for i in order]

            boxes_list = boxes.tolist()
            sam_inputs = sam_proc(
                images=img_pil, input_boxes=[boxes_list], return_tensors="pt"
            ).to(device)
            with torch.inference_mode():
                sam_outputs = sam_mod(**sam_inputs)

            if HAS_SAM2:
                masks_list = sam_proc.post_process_masks(
                    sam_outputs.pred_masks.cpu(),
                    sam_inputs["original_sizes"].cpu(),
                )[0]
            else:
                masks_list = sam_proc.post_process_masks(
                    sam_outputs.pred_masks.cpu(),
                    sam_inputs["original_sizes"].cpu(),
                    sam_inputs["reshaped_input_sizes"].cpu(),
                )[0]

            iou_scores = sam_outputs.iou_scores.detach().cpu()[0]
            for idx in range(len(boxes_list)):
                best_k = int(iou_scores[idx].argmax())
                m_np = (masks_list[idx, best_k].numpy() > 0).astype(np.uint8) * 255
                if m_np.shape != (h, w):
                    m_np = cv2.resize(
                        m_np, (w, h), interpolation=cv2.INTER_NEAREST
                    )
                detected_objects.append(
                    {
                        "label": raw_labels[idx],
                        "score": float(scores[idx]),
                        "box": [int(round(v)) for v in boxes_list[idx]],
                        "mask": m_np,
                    }
                )

    detected_objects = apply_mask_nms(
        detected_objects, iou_thresh=0.45, contain_thresh=0.65
    )

    return (
        np.asarray(pred_map),
        id2label,
        np.asarray(d_pred, dtype=np.float32),
        detected_objects,
        "Mask2Former-Swin-Large (TTA)" if is_m2f else "SegFormer-B2 (TTA)",
    )


def backproject_depth_to_3d(depth_m, focal_px):
    h, w = depth_m.shape
    cx, cy = w * 0.5, h * 0.5
    u = np.arange(w, dtype=np.float32)[None, :]
    v = np.arange(h, dtype=np.float32)[:, None]

    z = np.clip(depth_m.astype(np.float32), 0.35, 25.0)
    x = (u - cx) * z / focal_px
    y = (v - cy) * z / focal_px
    return x, y, z


def compute_surface_normals(x, y, z):
    z_s = cv2.GaussianBlur(z, (9, 9), 0)
    x_s = cv2.GaussianBlur(x, (9, 9), 0)
    y_s = cv2.GaussianBlur(y, (9, 9), 0)

    dz_dx = cv2.Sobel(z_s, cv2.CV_32F, 1, 0, ksize=5)
    dz_dy = cv2.Sobel(z_s, cv2.CV_32F, 0, 1, ksize=5)
    dx_dx = cv2.Sobel(x_s, cv2.CV_32F, 1, 0, ksize=5)
    dx_dy = cv2.Sobel(x_s, cv2.CV_32F, 0, 1, ksize=5)
    dy_dx = cv2.Sobel(y_s, cv2.CV_32F, 1, 0, ksize=5)
    dy_dy = cv2.Sobel(y_s, cv2.CV_32F, 0, 1, ksize=5)

    tx = np.stack([dx_dx, dy_dx, dz_dx], axis=-1)
    ty = np.stack([dx_dy, dy_dy, dz_dy], axis=-1)
    normals = np.cross(tx, ty)
    norm_len = np.linalg.norm(normals, axis=-1, keepdims=True) + 1e-6
    normals = normals / norm_len
    flip = normals[..., 2] > 0
    normals[flip] *= -1.0
    return normals


def calibrate_metric_scale(masks, door_mask, floor_zone_mask, y_3d, cal_mode, ref_dim_ft):
    ref_m = float(ref_dim_ft) * FT_TO_M
    h, w = masks["wall"].shape

    if cal_mode == "Door Height (ft)" and np.count_nonzero(door_mask) > 400:
        num_l, labels, stats, _ = cv2.connectedComponentsWithStats(door_mask)
        best_lbl = max(
            range(1, num_l), key=lambda l: int(stats[l, cv2.CC_STAT_AREA]), default=0
        )
        if best_lbl > 0 and stats[best_lbl, cv2.CC_STAT_HEIGHT] >= h * 0.15:
            ys = y_3d[labels == best_lbl]
            est_h_m = float(np.percentile(ys, 97) - np.percentile(ys, 3))
            if est_h_m > 0.5:
                scale = float(np.clip(ref_m / est_h_m, 0.75, 1.25))
                return (
                    scale,
                    f"Metric Depth + Door Ref ({ref_dim_ft:.1f} ft, scale {scale:.2f}x)",
                )

    ceil_dil = cv2.dilate(masks["ceiling"], np.ones((15, 15), np.uint8))
    floor_dil = cv2.dilate(floor_zone_mask, np.ones((19, 19), np.uint8))

    wall_cols = np.where(np.any(masks["wall"] > 0, axis=0))[0]
    strict_spans_m = []
    fallback_spans_m = []

    for col in wall_cols[::4]:
        ys_idx = np.where(masks["wall"][:, col] > 0)[0]
        if len(ys_idx) < int(h * 0.20):
            continue
        top_y, bot_y = int(ys_idx[0]), int(ys_idx[-1])
        y_vals = y_3d[ys_idx, col]
        span = float(np.percentile(y_vals, 97) - np.percentile(y_vals, 3))
        if span <= 0.8:
            continue

        touches_ceil = bool(ceil_dil[top_y, col] > 0)
        touches_floor = bool(floor_dil[bot_y, col] > 0)
        if touches_ceil and touches_floor:
            strict_spans_m.append(span)
        elif top_y > 8 and bot_y < h - 8:
            fallback_spans_m.append(span)

    chosen_spans = strict_spans_m if len(strict_spans_m) >= 5 else fallback_spans_m
    if chosen_spans:
        est_ceil_m = float(np.percentile(chosen_spans, 70))
        scale = float(np.clip(ref_m / est_ceil_m, 0.75, 1.25))
        tag = "strict" if chosen_spans is strict_spans_m else "fallback"
        return (
            scale,
            f"Metric Depth + Ceiling Ref ({ref_dim_ft:.1f} ft, scale {scale:.2f}x, {tag})",
        )

    return 1.0, "Pure Metric Depth (unscaled)"


def merge_coplanar_planes(planes, z_3d, normal_angle_tol=15.0, depth_tol_m=0.35):
    if len(planes) <= 1:
        return planes

    merged = []
    used = [False] * len(planes)
    for i in range(len(planes)):
        if used[i]:
            continue
        base = planes[i].copy()
        base_mask = base["mask"].copy()
        n_i = np.array(base["normal"], dtype=np.float32)

        for j in range(i + 1, len(planes)):
            if used[j]:
                continue
            n_j = np.array(planes[j]["normal"], dtype=np.float32)
            cos_sim = float(np.clip(np.dot(n_i, n_j), -1.0, 1.0))
            ang_diff = float(np.degrees(np.arccos(abs(cos_sim))))
            depth_diff = abs(base["median_depth_m"] - planes[j]["median_depth_m"])
            if ang_diff <= normal_angle_tol and depth_diff <= depth_tol_m:
                base_mask = cv2.bitwise_or(base_mask, planes[j]["mask"])
                used[j] = True

        py, px = np.where(base_mask > 0)
        base["mask"] = base_mask
        base["area_px"] = int(len(py))
        base["centroid"] = (int(np.mean(px)), int(np.mean(py)))
        base["median_depth_m"] = float(np.median(z_3d[py, px]))
        merged.append(base)

    merged.sort(key=lambda p: p["centroid"][0])
    return merged


def fit_3d_wall_planes_ransac(wall_mask, x_3d, y_3d, z_3d, min_area_ratio=0.03):
    h, w = wall_mask.shape
    min_px = int(h * w * min_area_ratio)
    remaining = (wall_mask > 0).copy()
    planes = []
    rng = np.random.default_rng(42)

    for _ in range(6):
        ys, xs = np.where(remaining)
        if len(ys) < min_px:
            break

        pts = np.stack([x_3d[ys, xs], y_3d[ys, xs], z_3d[ys, xs]], axis=1)
        n_pts = len(pts)

        sub_idx = rng.choice(n_pts, size=min(n_pts, 4000), replace=False)
        sub_pts = pts[sub_idx]

        best_normal = None
        best_d = 0.0
        best_count = 0

        for _it in range(140):
            sample = sub_pts[rng.choice(len(sub_pts), size=3, replace=False)]
            v1 = sample[1] - sample[0]
            v2 = sample[2] - sample[0]
            n = np.cross(v1, v2)
            n_norm = np.linalg.norm(n)
            if n_norm < 1e-5:
                continue
            n = n / n_norm
            if abs(n[1]) > 0.45:
                continue
            d = -np.dot(n, sample[0])
            dist = np.abs(sub_pts @ n + d)
            count = int(np.sum(dist < 0.14))
            if count > best_count:
                best_count = count
                best_normal = n
                best_d = d

        if best_normal is None or best_count < 80:
            break

        full_dist = np.abs(pts @ best_normal + best_d)
        inlier_mask_1d = full_dist < 0.18
        if int(np.sum(inlier_mask_1d)) < min_px:
            break

        plane_mask = np.zeros((h, w), np.uint8)
        plane_mask[ys[inlier_mask_1d], xs[inlier_mask_1d]] = 255
        plane_mask = cv2.morphologyEx(
            plane_mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8)
        )
        plane_mask = cv2.morphologyEx(
            plane_mask, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8)
        )
        plane_mask = cv2.bitwise_and(plane_mask, wall_mask)

        area_px = int(np.count_nonzero(plane_mask))
        if area_px < min_px:
            remaining[plane_mask > 0] = False
            continue

        if best_normal[2] > 0:
            best_normal = -best_normal

        cos_theta = float(np.clip(abs(best_normal[2]), 0.35, 1.0))
        sec_theta = 1.0 / cos_theta
        angle_deg = float(np.degrees(np.arccos(cos_theta)))

        py, px = np.where(plane_mask > 0)
        planes.append(
            {
                "mask": plane_mask,
                "area_px": area_px,
                "centroid": (int(np.mean(px)), int(np.mean(py))),
                "normal": best_normal.tolist(),
                "sec_theta": sec_theta,
                "angle_deg": angle_deg,
                "median_depth_m": float(np.median(z_3d[plane_mask > 0])),
            }
        )
        remaining[plane_mask > 0] = False

    return merge_coplanar_planes(planes, z_3d)


def estimate_3d_room_footprint_sqft(wall_planes, x_3d, z_3d):
    if not wall_planes:
        return 0.0, 0.0, 0.0
    xs_all, zs_all = [], []
    for p in wall_planes:
        ys, xs = np.where(p["mask"] > 0)
        if len(ys) > 50:
            xs_all.append(x_3d[ys, xs])
            zs_all.append(z_3d[ys, xs])
    if not xs_all:
        return 0.0, 0.0, 0.0

    x_cat = np.concatenate(xs_all)
    z_cat = np.concatenate(zs_all)
    span_x_m = float(np.clip(np.percentile(x_cat, 96) - np.percentile(x_cat, 4), 1.8, 10.0))
    span_z_m = float(np.clip(np.percentile(z_cat, 96) - np.percentile(z_cat, 4), 1.8, 10.0))
    return span_x_m * span_z_m * SQM_TO_SQFT, span_x_m / FT_TO_M, span_z_m / FT_TO_M


def compute_3d_surface_area_sqft(mask, z_3d, focal_px, cos_theta=None):
    ys, xs = np.where(mask > 0)
    if len(ys) == 0:
        return 0.0
    z_vals = z_3d[ys, xs]
    px_area_sqm = (z_vals / focal_px) ** 2
    if cos_theta is not None:
        sec_factor = 1.0 / max(float(cos_theta), 0.35)
        total_sqm = float(np.sum(px_area_sqm)) * sec_factor
    else:
        total_sqm = float(np.sum(px_area_sqm))
    return total_sqm * SQM_TO_SQFT


def compute_horizontal_3d_area_sqft(mask, z_3d, normals, focal_px):
    ys, xs = np.where(mask > 0)
    if len(ys) == 0:
        return 0.0
    z_vals = z_3d[ys, xs]
    nz = np.clip(np.abs(normals[ys, xs, 2]), 0.22, 0.95)
    px_area_sqm = ((z_vals / focal_px) ** 2) / nz
    return float(np.sum(px_area_sqm)) * SQM_TO_SQFT


def assign_openings_to_walls(openings_mask, wall_planes):
    h, w = openings_mask.shape
    wall_openings = [np.zeros((h, w), np.uint8) for _ in wall_planes]
    if not wall_planes or np.count_nonzero(openings_mask) == 0:
        return wall_openings

    num_op, op_labels, op_stats, _ = cv2.connectedComponentsWithStats(openings_mask)
    k_border = np.ones((17, 17), np.uint8)

    for op_lbl in range(1, num_op):
        if int(op_stats[op_lbl, cv2.CC_STAT_AREA]) < 150:
            continue
        comp_mask = (op_labels == op_lbl).astype(np.uint8) * 255
        comp_dilated = cv2.dilate(comp_mask, k_border)

        best_idx = -1
        best_overlap = 0
        for idx, plane in enumerate(wall_planes):
            overlap = int(
                np.count_nonzero(cv2.bitwise_and(comp_dilated, plane["mask"]))
            )
            if overlap > best_overlap:
                best_overlap = overlap
                best_idx = idx

        if best_idx >= 0 and best_overlap >= 25:
            wall_openings[best_idx] = cv2.bitwise_or(
                wall_openings[best_idx], comp_mask
            )

    return wall_openings


def estimate_gross_floor_mask(floor_mask, floor_furniture_mask, wall_mask):
    h, w = floor_mask.shape
    floor_ys = np.where(floor_mask > 0)[0]
    if len(floor_ys) == 0:
        return floor_mask.copy()

    horizon_y = int(np.percentile(floor_ys, 5))
    valid_zone = np.zeros((h, w), np.uint8)
    valid_zone[horizon_y:, :] = 255

    clutter_on_floor = cv2.bitwise_and(floor_furniture_mask, valid_zone)
    clutter_on_floor = cv2.bitwise_and(clutter_on_floor, cv2.bitwise_not(wall_mask))
    combined = cv2.bitwise_or(floor_mask, clutter_on_floor)

    pts = cv2.findNonZero(combined)
    if pts is None or len(pts) < 10:
        return floor_mask.copy()

    hull = cv2.convexHull(pts)
    gross_mask = np.zeros((h, w), np.uint8)
    cv2.fillConvexPoly(gross_mask, hull, 255)
    gross_mask = cv2.bitwise_and(gross_mask, valid_zone)
    gross_mask = cv2.bitwise_and(gross_mask, cv2.bitwise_not(wall_mask))
    return cv2.bitwise_or(gross_mask, floor_mask)


def _boxes_overlap(b1, b2, pad=5):
    return not (
        b1[2] + pad < b2[0]
        or b1[0] - pad > b2[2]
        or b1[3] + pad < b2[1]
        or b1[1] - pad > b2[3]
    )


def draw_label_badge(img, text, cx, cy, placed_boxes, accent_bgr=None):
    h, w, _ = img.shape
    font = cv2.FONT_HERSHEY_SIMPLEX
    scale = 0.46
    (tw, th), baseline = cv2.getTextSize(text, font, scale, 1)
    tx = int(np.clip(cx - tw // 2, 8, max(8, w - tw - 12)))

    chosen_box = None
    chosen_ty = int(np.clip(cy, th + 8, h - 8))
    for dy in (0, -32, 32, -64, 64, -96, 96):
        ty = int(np.clip(cy + dy, th + 8, h - 8))
        x0, y0 = max(0, tx - 6), max(0, ty - th - 5)
        x1, y1 = min(w, tx + tw + 6), min(h, ty + baseline + 3)
        cand = (x0, y0, x1, y1)
        if not any(_boxes_overlap(cand, b) for b in placed_boxes):
            chosen_box = cand
            chosen_ty = ty
            break

    if chosen_box is None:
        x0, y0 = max(0, tx - 6), max(0, chosen_ty - th - 5)
        x1, y1 = min(w, tx + tw + 6), min(h, chosen_ty + baseline + 3)
        chosen_box = (x0, y0, x1, y1)

    placed_boxes.append(chosen_box)
    x0, y0, x1, y1 = chosen_box
    img[y0:y1, x0:x1] = (0.35 * img[y0:y1, x0:x1]).astype(np.uint8)
    if accent_bgr is not None:
        cv2.rectangle(img, (x0, y0), (x1, y1), accent_bgr, 1)
    cv2.putText(
        img, text, (tx, chosen_ty), font, scale, (255, 255, 255), 1, cv2.LINE_AA
    )


def export_takeoff_files(payload, rows):
    tmp_dir = tempfile.gettempdir()
    json_path = os.path.join(tmp_dir, "smart_area_v23_report.json")
    csv_path = os.path.join(tmp_dir, "smart_area_v23_takeoff.csv")

    with open(json_path, "w", encoding="utf-8") as jf:
        json.dump(payload, jf, indent=2)

    fieldnames = [
        "Surface",
        "Net_Paintable_SqFt",
        "Cladding_Feature_SqFt",
        "Deducted_Openings_SqFt",
        "Gross_Area_SqFt",
        "Net_Area_SqM",
        "Gross_Area_SqM",
        "Viewing_Angle_Deg",
        "Median_Depth_M",
    ]
    with open(csv_path, "w", newline="", encoding="utf-8") as cf:
        writer = csv.DictWriter(cf, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)

    return json_path, csv_path


def log_ground_truth(last_payload, actual_wall_sqft, actual_floor_sqft, site_notes):
    """Append real laser-tape ground truth alongside v23 features for future regressor training."""
    if not last_payload:
        return "Run an analysis first before logging ground truth.", None

    entry = {
        "timestamp_utc": datetime.utcnow().isoformat() + "Z",
        "site_notes": site_notes or "",
        "actual_laser_sqft": {
            "wall_net_sqft": float(actual_wall_sqft) if actual_wall_sqft else None,
            "floor_gross_sqft": float(actual_floor_sqft) if actual_floor_sqft else None,
        },
        "predicted_summary": last_payload.get("summary", {}),
        "intrinsics": last_payload.get("intrinsics", {}),
        "calibration": last_payload.get("calibration", ""),
    }
    with open(CALIBRATION_LOG_PATH, "a", encoding="utf-8") as f:
        f.write(json.dumps(entry) + "\n")

    with open(CALIBRATION_LOG_PATH, "r", encoding="utf-8") as f:
        total_rows = sum(1 for _ in f)

    return f"Saved ground truth sample #{total_rows} to calibration log.", CALIBRATION_LOG_PATH


def resize_max_side(img_pil, max_side=1024):
    w, h = img_pil.size
    scale = min(max_side / max(w, h), 1.0)
    if scale < 1.0:
        img_pil = img_pil.resize(
            (max(1, int(w * scale)), max(1, int(h * scale))),
            Image.Resampling.LANCZOS,
        )
    return img_pil


def analyze_room(
    input_img_path,
    cal_mode="Ceiling Height (ft)",
    ref_dim_ft=10.0,
    focus_mode="All Room Surfaces (Ignore Clutter)",
    ignore_objects="sofa, couch, bed, table, chair, wardrobe, cabinet, dresser, console, nightstand, shelf, television, curtain, chandelier, fan",
    target_query="door, window",
    boq_scope="2 coats paint, 10% wastage, 2x4 ft tiles, 18% GST",
):
    if input_img_path is None:
        return None, None, "Please upload an interior photo.", None, None, None

    try:
        ref_val = float(ref_dim_ft) if ref_dim_ft and ref_dim_ft > 0 else 10.0
        raw_pil = Image.open(input_img_path)
        img_pil = resize_max_side(raw_pil.convert("RGB"), max_side=1024)
        work_np = np.array(img_pil)
        h, w, _ = work_np.shape

        focal_px, focal_src = extract_focal_px_from_exif(raw_pil, w, h)
        boq_cfg = parse_boq_scope(boq_scope)

        ignore_terms = _parse_terms(ignore_objects)
        target_terms = _parse_terms(target_query)
        combined_prompts = (
            ignore_terms + target_terms + AUTO_OPENING_PROMPTS + CLADDING_PROMPTS
        )

        pred_map, id2label, d_pred_m, detected_objs, seg_name = run_models(
            img_pil, combined_prompts
        )

        pred_2d = np.squeeze(pred_map)
        if pred_2d.ndim == 3:
            pred_2d = pred_2d[0]
        pred_resized = cv2.resize(
            pred_2d.astype(np.float32), (w, h), interpolation=cv2.INTER_NEAREST
        ).astype(np.int32)

        masks = {
            "wall": np.zeros((h, w), np.uint8),
            "ceiling": np.zeros((h, w), np.uint8),
            "floor": np.zeros((h, w), np.uint8),
        }
        door_mask = np.zeros((h, w), np.uint8)
        sem_reflective_mask = np.zeros((h, w), np.uint8)
        sem_opening_mask = np.zeros((h, w), np.uint8)
        wall_openings_source_mask = np.zeros((h, w), np.uint8)
        floor_furniture_mask = np.zeros((h, w), np.uint8)

        structural_opening_keywords = (
            "window",
            "pane",
            "door",
            "doorway",
            "archway",
            "mirror",
            "wardrobe",
            "closet",
        )
        reflective_keywords = ("window", "pane", "mirror", "wardrobe", "closet")
        floor_surface_keywords = ("floor", "rug", "carpet")
        floor_furn_keywords = (
            "sofa",
            "couch",
            "bed",
            "table",
            "chair",
            "ottoman",
            "armchair",
            "desk",
            "bench",
            "dresser",
            "console",
            "nightstand",
            "cabinet",
        )

        for cls_id in np.unique(pred_resized).tolist():
            cid = int(cls_id)
            lbl = str(id2label.get(cid, id2label.get(str(cid), ""))).lower()
            m = (pred_resized == cid).astype(np.uint8) * 255
            if "wall" in lbl:
                masks["wall"] = cv2.bitwise_or(masks["wall"], m)
            if "ceiling" in lbl:
                masks["ceiling"] = cv2.bitwise_or(masks["ceiling"], m)
            if any(fsk in lbl for fsk in floor_surface_keywords):
                masks["floor"] = cv2.bitwise_or(masks["floor"], m)
            if "door" in lbl or "windowpane" in lbl:
                door_mask = cv2.bitwise_or(door_mask, m)
            if any(rk in lbl for rk in reflective_keywords):
                sem_reflective_mask = cv2.bitwise_or(sem_reflective_mask, m)
            if any(sok in lbl for sok in structural_opening_keywords):
                sem_opening_mask = cv2.bitwise_or(sem_opening_mask, m)
                wall_openings_source_mask = cv2.bitwise_or(
                    wall_openings_source_mask, m
                )
            if any(fk in lbl for fk in floor_furn_keywords):
                floor_furniture_mask = cv2.bitwise_or(floor_furniture_mask, m)

        reflective_mask = sem_reflective_mask.copy()
        for obj in detected_objs:
            if any(rk in obj["label"] for rk in reflective_keywords):
                om = obj["mask"]
                om_px = max(1, int(np.count_nonzero(om)))
                sem_overlap = int(
                    np.count_nonzero(cv2.bitwise_and(om, sem_reflective_mask))
                ) / float(om_px)
                if sem_overlap > 0.10 or obj["score"] >= 0.50:
                    reflective_mask = cv2.bitwise_or(reflective_mask, om)

        sam_ignored_mask = np.zeros((h, w), np.uint8)
        sam_target_mask = np.zeros((h, w), np.uint8)
        cladding_mask = np.zeros((h, w), np.uint8)
        ignored_items = []
        focused_items = []
        cladding_items = []

        for obj in detected_objs:
            lbl = obj["label"]
            omask = obj["mask"]
            omask_px = int(np.count_nonzero(omask))
            if omask_px == 0:
                continue

            is_cladding = any(
                ck in lbl for ck in ("panel", "fluted", "marble", "cladding")
            )
            if is_cladding:
                cladding_mask = cv2.bitwise_or(cladding_mask, omask)
                cladding_items.append(obj)
                continue

            if (
                np.count_nonzero(reflective_mask) > 0
                and not any(
                    wk in lbl
                    for wk in (
                        "window",
                        "pane",
                        "curtain",
                        "drape",
                        "mirror",
                        "wardrobe",
                        "closet",
                    )
                )
            ):
                inside_ref = int(
                    np.count_nonzero(cv2.bitwise_and(omask, reflective_mask))
                )
                if inside_ref / float(omask_px) > 0.55:
                    continue

            is_opening_lbl = any(sok in lbl for sok in structural_opening_keywords)
            verified_opening = True
            if is_opening_lbl:
                sem_ov = int(
                    np.count_nonzero(cv2.bitwise_and(omask, sem_opening_mask))
                ) / float(omask_px)
                conf_gate = (
                    0.42 if any(k in lbl for k in ("door", "arch", "mirror")) else 0.55
                )
                verified_opening = (sem_ov > 0.08) or (obj["score"] >= conf_gate)
                if not verified_opening:
                    continue

            is_target = any(t in lbl or lbl in t for t in target_terms)
            is_ignored = any(ig in lbl or lbl in ig for ig in ignore_terms)

            if focus_mode == "Specific Object Only" and is_target:
                sam_target_mask = cv2.bitwise_or(sam_target_mask, omask)
                focused_items.append(obj)
                if "door" in lbl or "window" in lbl:
                    door_mask = cv2.bitwise_or(door_mask, omask)
                if is_opening_lbl and verified_opening:
                    wall_openings_source_mask = cv2.bitwise_or(
                        wall_openings_source_mask, omask
                    )
            elif is_ignored:
                sam_ignored_mask = cv2.bitwise_or(sam_ignored_mask, omask)
                ignored_items.append(obj)
                if any(fk in lbl for fk in floor_furn_keywords):
                    floor_furniture_mask = cv2.bitwise_or(floor_furniture_mask, omask)
                if is_opening_lbl and verified_opening:
                    wall_openings_source_mask = cv2.bitwise_or(
                        wall_openings_source_mask, omask
                    )
                    if "door" in lbl:
                        door_mask = cv2.bitwise_or(door_mask, omask)
            elif is_target or (is_opening_lbl and verified_opening):
                sam_target_mask = cv2.bitwise_or(sam_target_mask, omask)
                focused_items.append(obj)
                if is_opening_lbl and verified_opening:
                    wall_openings_source_mask = cv2.bitwise_or(
                        wall_openings_source_mask, omask
                    )

        if np.count_nonzero(sam_ignored_mask) > 0:
            masks["wall"] = cv2.bitwise_and(
                masks["wall"], cv2.bitwise_not(sam_ignored_mask)
            )
            masks["floor"] = cv2.bitwise_and(
                masks["floor"], cv2.bitwise_not(sam_ignored_mask)
            )

        d_2d = np.squeeze(d_pred_m)
        if d_2d.ndim == 3:
            d_2d = d_2d[0]
        depth_m = cv2.resize(
            d_2d.astype(np.float32), (w, h), interpolation=cv2.INTER_CUBIC
        )
        depth_m = np.nan_to_num(depth_m, nan=2.0, posinf=10.0, neginf=0.5)
        depth_m = np.clip(depth_m, 0.35, 25.0)

        floor_zone_mask = cv2.bitwise_or(masks["floor"], floor_furniture_mask)
        x_raw, y_raw, z_raw = backproject_depth_to_3d(depth_m, focal_px)
        metric_scale, cal_label = calibrate_metric_scale(
            masks, door_mask, floor_zone_mask, y_raw, cal_mode, ref_val
        )
        x_3d, y_3d, z_3d = (
            x_raw * metric_scale,
            y_raw * metric_scale,
            z_raw * metric_scale,
        )
        normals = compute_surface_normals(x_3d, y_3d, z_3d)

        depth_vis = cv2.normalize(z_3d, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
        depth_colored = cv2.cvtColor(
            cv2.applyColorMap(depth_vis, cv2.COLORMAP_INFERNO), cv2.COLOR_BGR2RGB
        )

        wall_planes = fit_3d_wall_planes_ransac(masks["wall"], x_3d, y_3d, z_3d)
        if not wall_planes and np.count_nonzero(masks["wall"]) > 0:
            ys, xs = np.where(masks["wall"] > 0)
            wall_planes = [
                {
                    "mask": masks["wall"],
                    "area_px": int(len(ys)),
                    "centroid": (int(np.mean(xs)), int(np.mean(ys))),
                    "normal": [0.0, 0.0, -1.0],
                    "sec_theta": 1.0,
                    "angle_deg": 0.0,
                    "median_depth_m": float(np.median(z_3d[ys, xs])),
                }
            ]

        wall_openings_masks = assign_openings_to_walls(
            wall_openings_source_mask, wall_planes
        )

        wall_palette = [
            np.array([65, 135, 255]),
            np.array([150, 100, 255]),
            np.array([50, 190, 230]),
            np.array([255, 120, 170]),
            np.array([100, 160, 255]),
        ]
        overlay = work_np.copy()
        placed_boxes = []

        if focus_mode == "Specific Object Only":
            overlay = (0.45 * overlay).astype(np.uint8)
            if np.count_nonzero(sam_target_mask) > 0:
                tm = sam_target_mask > 0
                overlay[tm] = np.clip(
                    0.55 * work_np[tm] + 0.45 * np.array([40, 230, 140]), 0, 255
                ).astype(np.uint8)
                contours, _ = cv2.findContours(
                    sam_target_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
                )
                cv2.drawContours(overlay, contours, -1, (40, 255, 140), 2)
        else:
            for idx, plane in enumerate(wall_planes):
                color = wall_palette[idx % len(wall_palette)]
                pm = plane["mask"] > 0
                overlay[pm] = (0.72 * overlay[pm] + 0.28 * color).astype(np.uint8)
                cnts, _ = cv2.findContours(
                    plane["mask"], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
                )
                cv2.drawContours(overlay, cnts, -1, (0, 255, 255), 1)

            if np.count_nonzero(cladding_mask) > 0:
                cl_cnts, _ = cv2.findContours(
                    cladding_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
                )
                cv2.drawContours(overlay, cl_cnts, -1, (255, 180, 40), 2)

            if focus_mode != "Walls Only (Ignore Floor & Ceiling)":
                overlay[masks["floor"] > 0] = (
                    0.74 * overlay[masks["floor"] > 0]
                    + 0.26 * np.array([75, 210, 130])
                ).astype(np.uint8)
                overlay[masks["ceiling"] > 0] = (
                    0.74 * overlay[masks["ceiling"] > 0]
                    + 0.26 * np.array([255, 195, 70])
                ).astype(np.uint8)

            if np.count_nonzero(sam_ignored_mask) > 0:
                ig_cnts, _ = cv2.findContours(
                    sam_ignored_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
                )
                cv2.drawContours(overlay, ig_cnts, -1, (255, 110, 90), 1)

        plane_lines = []
        wall_records = []
        csv_rows = []
        total_net_paint_sqft = 0.0
        total_cladding_sqft = 0.0
        total_deduct_sqft = 0.0

        for idx, plane in enumerate(wall_planes):
            cos_theta = 1.0 / max(plane["sec_theta"], 1.0)
            plane_clad_mask = cv2.bitwise_and(plane["mask"], cladding_mask)
            plane_paint_mask = cv2.bitwise_and(
                plane["mask"], cv2.bitwise_not(cladding_mask)
            )

            paint_sqft = compute_3d_surface_area_sqft(
                plane_paint_mask, z_3d, focal_px, cos_theta=cos_theta
            )
            clad_sqft = compute_3d_surface_area_sqft(
                plane_clad_mask, z_3d, focal_px, cos_theta=cos_theta
            )

            op_mask = wall_openings_masks[idx]
            op_px = int(np.count_nonzero(op_mask))
            if op_px > 0:
                host_z = plane["median_depth_m"]
                raw_deduct_sqft = (
                    op_px * ((host_z / focal_px) ** 2) / max(cos_theta, 0.35)
                ) * SQM_TO_SQFT
            else:
                raw_deduct_sqft = 0.0

            deduct_sqft = min(raw_deduct_sqft, (paint_sqft + clad_sqft) * 1.85)
            gross_sqft = paint_sqft + clad_sqft + deduct_sqft

            total_net_paint_sqft += paint_sqft
            total_cladding_sqft += clad_sqft
            total_deduct_sqft += deduct_sqft

            cx, cy = plane["centroid"]
            if focus_mode != "Specific Object Only":
                tag = f"W{idx + 1}: {paint_sqft:.0f} sf paint" + (
                    f" + {clad_sqft:.0f} sf clad" if clad_sqft >= 5 else ""
                )
                draw_label_badge(overlay, tag, cx, cy, placed_boxes)

            plane_lines.append(
                f"  - Wall {idx + 1}: Paintable ~{paint_sqft:.1f} sq.ft | Cladding ~{clad_sqft:.1f} sq.ft | "
                f"Openings ~{deduct_sqft:.1f} sq.ft | Gross ~{gross_sqft:.1f} sq.ft "
                f"(3D tilt ~{plane['angle_deg']:.0f}°, depth ~{plane['median_depth_m']:.2f}m)"
            )
            wall_records.append(
                {
                    "wall_id": f"Wall {idx + 1}",
                    "net_paintable_sqft": round(paint_sqft, 2),
                    "cladding_feature_sqft": round(clad_sqft, 2),
                    "deducted_openings_sqft": round(deduct_sqft, 2),
                    "gross_wall_sqft": round(gross_sqft, 2),
                    "net_paintable_sqm": round(paint_sqft / SQM_TO_SQFT, 2),
                    "gross_wall_sqm": round(gross_sqft / SQM_TO_SQFT, 2),
                    "viewing_angle_deg": round(plane["angle_deg"], 1),
                    "median_depth_m": round(plane["median_depth_m"], 2),
                }
            )
            csv_rows.append(
                {
                    "Surface": f"Wall {idx + 1}",
                    "Net_Paintable_SqFt": round(paint_sqft, 2),
                    "Cladding_Feature_SqFt": round(clad_sqft, 2),
                    "Deducted_Openings_SqFt": round(deduct_sqft, 2),
                    "Gross_Area_SqFt": round(gross_sqft, 2),
                    "Net_Area_SqM": round(paint_sqft / SQM_TO_SQFT, 2),
                    "Gross_Area_SqM": round(gross_sqft / SQM_TO_SQFT, 2),
                    "Viewing_Angle_Deg": round(plane["angle_deg"], 1),
                    "Median_Depth_M": round(plane["median_depth_m"], 2),
                }
            )

        total_gross_wall_sqft = (
            total_net_paint_sqft + total_cladding_sqft + total_deduct_sqft
        )

        total_px = h * w
        vis_floor_ratio = np.count_nonzero(masks["floor"]) / float(total_px)
        vis_floor_sqft = compute_horizontal_3d_area_sqft(
            masks["floor"], z_3d, normals, focal_px
        )
        gross_floor_mask = estimate_gross_floor_mask(
            masks["floor"], floor_furniture_mask, masks["wall"]
        )
        hull_floor_sqft = compute_horizontal_3d_area_sqft(
            gross_floor_mask, z_3d, normals, focal_px
        )
        ceil_sqft = compute_horizontal_3d_area_sqft(
            masks["ceiling"], z_3d, normals, focal_px
        )
        inferred_3d_sqft, span_x_ft, span_z_ft = estimate_3d_room_footprint_sqft(
            wall_planes, x_3d, z_3d
        )

        # Cap 3D inferred floor footprint against visible ceiling to prevent bounding-box blowup
        if vis_floor_ratio < 0.15:
            inferred_cap = (
                min(inferred_3d_sqft * 0.85, ceil_sqft * 1.25)
                if ceil_sqft > 40.0
                else inferred_3d_sqft * 0.85
            )
            est_gross_floor_sqft = max(
                vis_floor_sqft, hull_floor_sqft, ceil_sqft * 0.90, inferred_cap
            )
        else:
            est_gross_floor_sqft = max(vis_floor_sqft, hull_floor_sqft)

        sam_obj_records = []
        sam_report_lines = []
        total_focused_sqft = 0.0
        for obj in focused_items + cladding_items + ignored_items:
            if obj in focused_items:
                role = "Focused / Opening"
            elif obj in cladding_items:
                role = "Cladding / Panel"
            else:
                role = "Ignored Clutter"
            omask = obj["mask"]
            ys_o, xs_o = np.where(omask > 0)
            if len(ys_o) == 0:
                continue
            ring = cv2.bitwise_and(
                cv2.dilate(omask, np.ones((25, 25), np.uint8)),
                cv2.bitwise_not(omask),
            )
            ring_z = z_3d[ring > 0]
            obj_z = (
                float(np.median(ring_z))
                if len(ring_z) > 20
                else float(np.median(z_3d[ys_o, xs_o]))
            )
            obj_sqft = (len(ys_o) * ((obj_z / focal_px) ** 2)) * SQM_TO_SQFT

            if role == "Focused / Opening":
                total_focused_sqft += obj_sqft
                ocx, ocy = int(np.mean(xs_o)), int(np.mean(ys_o))
                draw_label_badge(
                    overlay,
                    f"{obj['label']}: ~{obj_sqft:.1f} sf",
                    ocx,
                    ocy,
                    placed_boxes,
                    accent_bgr=(40, 255, 140),
                )
            sam_obj_records.append(
                {
                    "label": obj["label"],
                    "role": role,
                    "confidence": round(obj["score"], 3),
                    "est_area_sqft": round(obj_sqft, 2),
                    "est_area_sqm": round(obj_sqft / SQM_TO_SQFT, 2),
                    "est_depth_m": round(obj_z, 2),
                }
            )
            sam_report_lines.append(
                f"  - [{role}] {obj['label']} ({obj['score']:.0%}): ~{obj_sqft:.1f} sq.ft (~{obj_z:.2f}m)"
            )

        paintable_sqft = total_net_paint_sqft + (
            ceil_sqft if boq_cfg["include_ceiling_paint"] else 0.0
        )
        wastage_mult = 1.0 + boq_cfg["wastage_pct"] / 100.0
        paint_litres = (paintable_sqft * boq_cfg["paint_coats"] * wastage_mult) / 130.0
        primer_litres = (paintable_sqft * wastage_mult) / 150.0
        tile_area_with_wastage = est_gross_floor_sqft * wastage_mult
        tiles_needed = int(math.ceil(tile_area_with_wastage / boq_cfg["tile_sqft"]))

        boq_summary = {
            "scope_parsed": boq_cfg,
            "paintable_area_sqft": round(paintable_sqft, 2),
            "cladding_excluded_sqft": round(total_cladding_sqft, 2),
            "est_primer_litres": round(primer_litres, 1),
            "est_paint_litres": round(paint_litres, 1),
            "floor_tile_area_with_wastage_sqft": round(tile_area_with_wastage, 2),
            "est_tile_count": tiles_needed,
        }

        csv_rows.extend(
            [
                {
                    "Surface": "Total Walls",
                    "Net_Paintable_SqFt": round(total_net_paint_sqft, 2),
                    "Cladding_Feature_SqFt": round(total_cladding_sqft, 2),
                    "Deducted_Openings_SqFt": round(total_deduct_sqft, 2),
                    "Gross_Area_SqFt": round(total_gross_wall_sqft, 2),
                    "Net_Area_SqM": round(total_net_paint_sqft / SQM_TO_SQFT, 2),
                    "Gross_Area_SqM": round(total_gross_wall_sqft / SQM_TO_SQFT, 2),
                    "Viewing_Angle_Deg": "",
                    "Median_Depth_M": "",
                },
                {
                    "Surface": "Floor (Visible / Est. Gross)",
                    "Net_Paintable_SqFt": round(vis_floor_sqft, 2),
                    "Cladding_Feature_SqFt": 0.0,
                    "Deducted_Openings_SqFt": round(
                        max(0.0, est_gross_floor_sqft - vis_floor_sqft), 2
                    ),
                    "Gross_Area_SqFt": round(est_gross_floor_sqft, 2),
                    "Net_Area_SqM": round(vis_floor_sqft / SQM_TO_SQFT, 2),
                    "Gross_Area_SqM": round(est_gross_floor_sqft / SQM_TO_SQFT, 2),
                    "Viewing_Angle_Deg": "",
                    "Median_Depth_M": "",
                },
                {
                    "Surface": "Ceiling",
                    "Net_Paintable_SqFt": round(ceil_sqft, 2),
                    "Cladding_Feature_SqFt": 0.0,
                    "Deducted_Openings_SqFt": 0.0,
                    "Gross_Area_SqFt": round(ceil_sqft, 2),
                    "Net_Area_SqM": round(ceil_sqft / SQM_TO_SQFT, 2),
                    "Gross_Area_SqM": round(ceil_sqft / SQM_TO_SQFT, 2),
                    "Viewing_Angle_Deg": "",
                    "Median_Depth_M": "",
                },
            ]
        )

        payload = {
            "pipeline_version": "v23-containment-nms-capped-footprint",
            "models": {
                "segmentation": seg_name,
                "depth": DEPTH_METRIC_ID + " (Flip-TTA)",
                "detection": gdino_active_id,
                "mask_refinement": sam_active_id,
            },
            "intrinsics": {"focal_px": round(focal_px, 1), "source": focal_src},
            "calibration": cal_label,
            "summary": {
                "net_paintable_wall_sqft": round(total_net_paint_sqft, 2),
                "cladding_feature_wall_sqft": round(total_cladding_sqft, 2),
                "deducted_openings_sqft": round(total_deduct_sqft, 2),
                "gross_wall_sqft": round(total_gross_wall_sqft, 2),
                "visible_floor_sqft": round(vis_floor_sqft, 2),
                "est_gross_floor_sqft": round(est_gross_floor_sqft, 2),
                "inferred_3d_room_footprint_sqft": round(inferred_3d_sqft, 2),
                "inferred_3d_span_ft": [round(span_x_ft, 1), round(span_z_ft, 1)],
                "est_ceiling_sqft": round(ceil_sqft, 2),
                "focused_objects_sqft": round(total_focused_sqft, 2),
            },
            "boq_estimate": boq_summary,
            "walls": wall_records,
            "detected_objects": sam_obj_records,
        }
        json_path, csv_path = export_takeoff_files(payload, csv_rows)

        report_lines = [
            f"Pipeline v23 — {seg_name} + Metric Depth TTA + Containment NMS",
            f"Calibration: {cal_label} | Camera: {focal_src}",
            f"Walls ({np.count_nonzero(masks['wall']) / total_px * 100:.1f}%): Paintable ~{total_net_paint_sqft:.1f} sq.ft | Cladding ~{total_cladding_sqft:.1f} sq.ft | Openings ~{total_deduct_sqft:.1f} sq.ft | Gross ~{total_gross_wall_sqft:.1f} sq.ft",
        ]
        if focus_mode == "Specific Object Only":
            report_lines.append(
                f"Focused Target Objects ({len(focused_items)} found): Total ~{total_focused_sqft:.1f} sq.ft"
            )
        elif focus_mode != "Walls Only (Ignore Floor & Ceiling)":
            report_lines.append(
                f"Floor ({vis_floor_ratio * 100:.1f}%): Visible ~{vis_floor_sqft:.1f} sq.ft | Est. Gross ~{est_gross_floor_sqft:.1f} sq.ft (3D Span ~{span_x_ft:.1f}x{span_z_ft:.1f} ft)"
            )
            report_lines.append(
                f"Ceiling ({np.count_nonzero(masks['ceiling']) / total_px * 100:.1f}%): Visible ~{ceil_sqft:.1f} sq.ft ({ceil_sqft / SQM_TO_SQFT:.1f} sq.m)"
            )

        report_lines.extend(
            [
                "",
                f"BOQ Material Estimate ({boq_cfg['wastage_pct']:.0f}% wastage, {boq_cfg['gst_pct']:.0f}% GST applicable):",
                f"  - Paint ({boq_cfg['paint_coats']} coats @ 130 sq.ft/L, excl. cladding): ~{paint_litres:.1f} L + Primer ~{primer_litres:.1f} L",
                f"  - Flooring Tiles ({boq_cfg['tile_label']}): ~{tiles_needed} tiles (~{tile_area_with_wastage:.1f} sq.ft incl. wastage)",
            ]
        )

        if plane_lines and focus_mode != "Specific Object Only":
            report_lines.append("")
            report_lines.append("3D RANSAC Per-Wall Breakdown:")
            report_lines.extend(plane_lines)
        if sam_report_lines:
            report_lines.append("")
            report_lines.append("Open-Vocabulary Detected Objects (Grounding DINO + SAM 2):")
            report_lines.extend(sam_report_lines)

        return overlay, depth_colored, "\n".join(report_lines), json_path, csv_path, payload

    except Exception as e:
        blank = np.zeros((256, 256, 3), dtype=np.uint8)
        return blank, blank, f"Error: {type(e).__name__}: {e}", None, None, None


with gr.Blocks(title="Smart Area v23 — 3D Metric Depth & BOQ Analyzer") as demo:
    gr.Markdown("## Smart Area v23 — 3D Metric Depth, Containment NMS & BOQ Analyzer")
    last_payload_state = gr.State(None)

    with gr.Row():
        with gr.Column(scale=1):
            img_in = gr.Image(type="filepath", label="Upload Interior Photo (EXIF Preserved)")
            cal_mode_in = gr.Radio(
                choices=["Ceiling Height (ft)", "Door Height (ft)"],
                value="Ceiling Height (ft)",
                label="Calibration Anchor",
            )
            ref_dim_in = gr.Number(value=10.0, label="Reference Dimension (ft)", precision=1)
            focus_mode_in = gr.Radio(
                choices=[
                    "All Room Surfaces (Ignore Clutter)",
                    "Walls Only (Ignore Floor & Ceiling)",
                    "Specific Object Only",
                ],
                value="All Room Surfaces (Ignore Clutter)",
                label="Focus Mode",
            )
            ignore_in = gr.Textbox(
                value="sofa, couch, bed, table, chair, wardrobe, cabinet, dresser, console, nightstand, shelf, television, curtain, chandelier, fan",
                label="Objects to Ignore / Subtract (comma-separated)",
            )
            target_in = gr.Textbox(
                value="door, window",
                label="Target Objects (used in 'Specific Object Only' mode)",
            )
            boq_in = gr.Textbox(
                value="2 coats paint, 10% wastage, 2x4 ft tiles, 18% GST",
                label="BOQ Scope (Natural Language)",
            )
            run_btn = gr.Button("Analyze Room", variant="primary")

        with gr.Column(scale=1):
            overlay_out = gr.Image(label="3D RANSAC Spatial Overlay")
            depth_out = gr.Image(label="Metric Depth Map (Metres)")
            report_out = gr.Textbox(label="3D Geometric & BOQ Breakdown", lines=16)
            with gr.Row():
                json_out = gr.File(label="Download JSON Report")
                csv_out = gr.File(label="Download CSV Takeoff")

    with gr.Accordion("Ground-Truth Calibration Logger (For Training Your Area Regressor)", open=False):
        with gr.Row():
            actual_wall_in = gr.Number(label="Actual Laser Net Wall Area (sq.ft)", value=None)
            actual_floor_in = gr.Number(label="Actual Laser Gross Floor Area (sq.ft)", value=None)
            notes_in = gr.Textbox(label="Site / Room Notes (e.g. 2BHK Pune, bare plaster)")
        log_btn = gr.Button("Log Ground-Truth Sample")
        with gr.Row():
            log_status = gr.Textbox(label="Log Status", interactive=False)
            log_file_out = gr.File(label="Download Calibration Log (.jsonl)")

    run_btn.click(
        fn=analyze_room,
        inputs=[img_in, cal_mode_in, ref_dim_in, focus_mode_in, ignore_in, target_in, boq_in],
        outputs=[overlay_out, depth_out, report_out, json_out, csv_out, last_payload_state],
    )
    log_btn.click(
        fn=log_ground_truth,
        inputs=[last_payload_state, actual_wall_in, actual_floor_in, notes_in],
        outputs=[log_status, log_file_out],
    )

if __name__ == "__main__":
    demo.launch()