File size: 72,098 Bytes
db79fa6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4323222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db79fa6
 
 
 
 
 
4aff382
db79fa6
458d3f0
4aff382
 
db79fa6
 
 
458d3f0
 
db79fa6
458d3f0
db79fa6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4aff382
 
 
4323222
4aff382
db79fa6
 
 
 
4aff382
 
 
 
 
 
 
 
 
 
 
db79fa6
 
4aff382
 
 
 
 
 
 
 
 
 
db79fa6
4aff382
 
 
 
 
 
 
 
 
 
 
4323222
 
4aff382
 
db79fa6
 
4aff382
 
4323222
4aff382
db79fa6
4aff382
4323222
4aff382
 
 
 
 
 
 
 
 
4323222
4aff382
 
4323222
 
4aff382
4323222
 
4aff382
4323222
 
4aff382
4323222
 
4aff382
4323222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4aff382
4323222
 
4aff382
 
 
 
db79fa6
 
 
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db79fa6
 
 
 
 
 
4323222
 
 
 
 
f334e46
4323222
 
4aff382
 
 
4323222
 
 
 
4aff382
4323222
 
4aff382
4323222
 
 
 
 
 
 
 
4aff382
4323222
 
 
 
 
 
 
4aff382
 
 
4323222
4aff382
 
4323222
4aff382
 
 
 
4323222
4aff382
 
 
4323222
4aff382
 
 
4323222
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4323222
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4323222
4aff382
4323222
4aff382
 
 
 
 
 
4323222
 
 
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4323222
4aff382
 
 
 
 
4323222
 
4aff382
4323222
 
 
4aff382
4323222
 
 
 
 
4aff382
 
4323222
 
 
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4323222
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4323222
4aff382
 
 
4323222
 
 
 
 
 
 
 
4aff382
 
 
 
4323222
 
4aff382
4323222
4aff382
4323222
 
 
 
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db79fa6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4aff382
 
 
 
 
 
 
 
 
4323222
 
 
 
 
 
4aff382
 
 
 
 
 
 
 
 
 
4323222
 
4aff382
 
 
 
4323222
 
4aff382
4323222
4aff382
4323222
 
 
 
4aff382
4323222
4aff382
 
 
 
4323222
4aff382
4323222
 
 
 
4aff382
db79fa6
 
4aff382
 
 
 
 
 
 
 
 
 
 
4323222
4aff382
db79fa6
 
 
 
4aff382
db79fa6
 
 
 
 
 
4aff382
 
 
db79fa6
 
 
4323222
db79fa6
4323222
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
db79fa6
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
db79fa6
4aff382
 
db79fa6
4323222
 
4aff382
 
 
db79fa6
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4323222
4aff382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a24f0e
4323222
 
5a24f0e
db79fa6
 
 
4aff382
 
1e05a70
db79fa6
4aff382
db79fa6
 
4aff382
 
 
 
db79fa6
4aff382
 
 
db79fa6
 
4aff382
 
1e05a70
4aff382
 
db79fa6
4aff382
60b5fc8
 
4aff382
db79fa6
 
 
 
5a24f0e
db79fa6
 
 
 
 
4323222
5a24f0e
 
4aff382
5a24f0e
db79fa6
 
 
5a24f0e
4323222
5a24f0e
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
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
# import os
# from pathlib import Path
# from typing import List, Union
# from PIL import Image
# import ezdxf.units
# import numpy as np
# import torch
# from torchvision import transforms
# from ultralytics import YOLOWorld, YOLO
# from ultralytics.engine.results import Results
# from ultralytics.utils.plotting import save_one_box
# from transformers import AutoModelForImageSegmentation
# import cv2
# import ezdxf
# import gradio as gr
# import gc
# from scalingtestupdated import calculate_scaling_factor
# from scipy.interpolate import splprep, splev
# from scipy.ndimage import gaussian_filter1d
# import json
# import time
# import signal
# from shapely.ops import unary_union
# from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, Point
# from u2netp import U2NETP  # Add U2NETP import
# import logging
# import shutil

# # Initialize logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# # Create cache directory for models
# CACHE_DIR = os.path.join(os.path.dirname(__file__), ".cache")
# os.makedirs(CACHE_DIR, exist_ok=True)

# # Custom Exception Classes
# class TimeoutReachedError(Exception):
#     pass

# class BoundaryOverlapError(Exception):
#     pass

# class TextOverlapError(Exception):
#     pass

# class ReferenceBoxNotDetectedError(Exception):
#     """Raised when the Reference coin cannot be detected in the image"""
#     pass

# class FingerCutOverlapError(Exception):
#     """Raised when finger cuts overlap with existing geometry"""
#     def __init__(self, message="There was an overlap with fingercuts... Please try again to generate dxf."):
#         super().__init__(message)

# # Global model initialization
# print("Loading models...")
# start_time = time.time()

# # Load YOLO reference model
# reference_model_path = os.path.join("", "best1.pt")
# if not os.path.exists(reference_model_path):
#     shutil.copy("best1.pt", reference_model_path)
# reference_detector_global = YOLO(reference_model_path)

# # Load U2NETP model
# u2net_model_path = os.path.join(CACHE_DIR, "u2netp.pth")
# if not os.path.exists(u2net_model_path):
#     shutil.copy("u2netp.pth", u2net_model_path)
# u2net_global = U2NETP(3, 1)
# u2net_global.load_state_dict(torch.load(u2net_model_path, map_location="cpu"))

# # Load BiRefNet model
# birefnet = AutoModelForImageSegmentation.from_pretrained(
#     "zhengpeng7/BiRefNet", trust_remote_code=True, cache_dir=CACHE_DIR
# )

# device = "cpu"
# torch.set_float32_matmul_precision(["high", "highest"][0])

# # Move models to device
# u2net_global.to(device)
# u2net_global.eval()
# birefnet.to(device)
# birefnet.eval()

# # Define transforms
# transform_image = transforms.Compose([
#     transforms.Resize((1024, 1024)),
#     transforms.ToTensor(),
#     transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
# ])

# # Language translations dictionary remains unchanged
# TRANSLATIONS = {
#     "english": {
#         "input_image": "Input Image",
#         "offset_value": "Offset value",  
#         "offset_unit": "Offset unit (mm/in)",
#         "enable_finger": "Enable Finger Clearance",
#         "edge_radius": "Edge rounding radius (mm)",
#         "output_image": "Output Image",
#         "outlines": "Outlines of Objects",
#         "dxf_file": "DXF file",
#         "mask": "Mask",
#         "enable_radius": "Enable Edge Rounding",
#         "radius_disabled": "Rounding Disabled",
#         "scaling_factor": "Scaling Factor(mm)",
#         "scaling_placeholder": "Every pixel is equal to mentioned number in millimeters",
#         "language_selector": "Select Language",
#     },
#     "dutch": {
#         "input_image": "Invoer Afbeelding",
#         "offset_value": "Offset waarde",
#         "offset_unit": "Offset unit (mm/inch)",
#         "enable_finger": "Finger Clearance inschakelen",
#         "edge_radius": "Ronding radius rand (mm)",
#         "output_image": "Uitvoer Afbeelding",
#         "outlines": "Contouren van Objecten",
#         "dxf_file": "DXF bestand",
#         "mask": "Masker",
#         "enable_radius": "Ronding inschakelen",
#         "radius_disabled": "Ronding uitgeschakeld",
#         "scaling_factor": "Schalingsfactor(mm)",
#         "scaling_placeholder": "Elke pixel is gelijk aan genoemd aantal in millimeters",
#         "language_selector": "Selecteer Taal",
#     }
# }

# def remove_bg_u2netp(image: np.ndarray) -> np.ndarray:
#     """Remove background using U2NETP model specifically for reference objects"""
#     try:
#         image_pil = Image.fromarray(image)
#         transform_u2netp = transforms.Compose([
#             transforms.Resize((320, 320)),
#             transforms.ToTensor(),
#             transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
#         ])
        
#         input_tensor = transform_u2netp(image_pil).unsqueeze(0).to(device)
        
#         with torch.no_grad():
#             outputs = u2net_global(input_tensor)
        
#         pred = outputs[0]
#         pred = (pred - pred.min()) / (pred.max() - pred.min() + 1e-8)
#         pred_np = pred.squeeze().cpu().numpy()
#         pred_np = cv2.resize(pred_np, (image_pil.width, image_pil.height))
#         pred_np = (pred_np * 255).astype(np.uint8)
        
#         return pred_np
#     except Exception as e:
#         logger.error(f"Error in U2NETP background removal: {e}")
#         raise

# def remove_bg(image: np.ndarray) -> np.ndarray:
#     """Remove background using BiRefNet model for main objects"""
#     try:
#         image = Image.fromarray(image)
#         input_images = transform_image(image).unsqueeze(0).to(device)

#         with torch.no_grad():
#             preds = birefnet(input_images)[-1].sigmoid().cpu()
#         pred = preds[0].squeeze()

#         pred_pil: Image = transforms.ToPILImage()(pred)
        
#         scale_ratio = 1024 / max(image.size)
#         scaled_size = (int(image.size[0] * scale_ratio), int(image.size[1] * scale_ratio))
        
#         return np.array(pred_pil.resize(scaled_size))
#     except Exception as e:
#         logger.error(f"Error in BiRefNet background removal: {e}")
#         raise

# def resize_img(img: np.ndarray, resize_dim):
#     return np.array(Image.fromarray(img).resize(resize_dim))

# def make_square(img: np.ndarray):
#     """Make the image square by padding"""
#     height, width = img.shape[:2]
#     max_dim = max(height, width)
    
#     pad_height = (max_dim - height) // 2
#     pad_width = (max_dim - width) // 2
    
#     pad_height_extra = max_dim - height - 2 * pad_height
#     pad_width_extra = max_dim - width - 2 * pad_width
    
#     if len(img.shape) == 3:  # Color image
#         padded = np.pad(
#             img,
#             (
#                 (pad_height, pad_height + pad_height_extra),
#                 (pad_width, pad_width + pad_width_extra),
#                 (0, 0),
#             ),
#             mode="edge",
#         )
#     else:  # Grayscale image
#         padded = np.pad(
#             img,
#             (
#                 (pad_height, pad_height + pad_height_extra),
#                 (pad_width, pad_width + pad_width_extra),
#             ),
#             mode="edge",
#         )
    
#     return padded


# def detect_reference_square(img) -> tuple:
#     """Detect reference square in the image and ignore other coins"""
#     try:
#         res = reference_detector_global.predict(img, conf=0.75)
#         if not res or len(res) == 0 or len(res[0].boxes) == 0:
#             raise ReferenceBoxNotDetectedError("Unable to detect the reference coin in the image.")
        
#         # Get all detected boxes
#         boxes = res[0].cpu().boxes.xyxy
        
#         # Find the largest box (most likely the reference coin)
#         largest_box = None
#         max_area = 0
#         for box in boxes:
#             x_min, y_min, x_max, y_max = box
#             area = (x_max - x_min) * (y_max - y_min)
#             if area > max_area:
#                 max_area = area
#                 largest_box = box
        
#         return (
#             save_one_box(largest_box.unsqueeze(0), img, save=False),
#             largest_box
#         )
#     except Exception as e:
#         if not isinstance(e, ReferenceBoxNotDetectedError):
#             logger.error(f"Error in reference square detection: {e}")
#             raise ReferenceBoxNotDetectedError("Error detecting reference coin. Please try again with a clearer image.")
#         raise


# def exclude_scaling_box(
#     image: np.ndarray,
#     bbox: np.ndarray,
#     orig_size: tuple,
#     processed_size: tuple,
#     expansion_factor: float = 1.2,
# ) -> np.ndarray:
#     x_min, y_min, x_max, y_max = map(int, bbox)
#     scale_x = processed_size[1] / orig_size[1]
#     scale_y = processed_size[0] / orig_size[0]
    
#     x_min = int(x_min * scale_x)
#     x_max = int(x_max * scale_x)
#     y_min = int(y_min * scale_y)
#     y_max = int(y_max * scale_y)
    
#     box_width = x_max - x_min
#     box_height = y_max - y_min
    
#     expanded_x_min = max(0, int(x_min - (expansion_factor - 1) * box_width / 2))
#     expanded_x_max = min(
#         image.shape[1], int(x_max + (expansion_factor - 1) * box_width / 2)
#     )
#     expanded_y_min = max(0, int(y_min - (expansion_factor - 1) * box_height / 2))
#     expanded_y_max = min(
#         image.shape[0], int(y_max + (expansion_factor - 1) * box_height / 2)
#     )
    
#     image[expanded_y_min:expanded_y_max, expanded_x_min:expanded_x_max] = 0
#     return image





# def resample_contour(contour, edge_radius_px: int = 0):
#     """Resample contour with radius-aware smoothing and periodic handling."""
#     logger.info(f"Starting resample_contour with contour of shape {contour.shape}")

#     num_points = 1500
#     sigma = max(2, int(edge_radius_px) // 4)  # Adjust sigma based on radius

#     if len(contour) < 4:  # Need at least 4 points for spline with periodic condition
#         error_msg = f"Contour must have at least 4 points, but has {len(contour)} points."
#         logger.error(error_msg)
#         raise ValueError(error_msg)

#     try:
#         contour = contour[:, 0, :]
#         logger.debug(f"Reshaped contour to shape {contour.shape}")

#         # Ensure contour is closed by making start and end points the same
#         if not np.array_equal(contour[0], contour[-1]):
#             contour = np.vstack([contour, contour[0]])

#         # Create periodic spline representation
#         tck, u = splprep(contour.T, u=None, s=0, per=True)
        
#         # Evaluate spline at evenly spaced points
#         u_new = np.linspace(u.min(), u.max(), num_points)
#         x_new, y_new = splev(u_new, tck, der=0)
        
#         # Apply Gaussian smoothing with wrap-around
#         if sigma > 0:
#             x_new = gaussian_filter1d(x_new, sigma=sigma, mode='wrap')
#             y_new = gaussian_filter1d(y_new, sigma=sigma, mode='wrap')
            
#             # Re-close the contour after smoothing
#             x_new[-1] = x_new[0]
#             y_new[-1] = y_new[0]

#         result = np.array([x_new, y_new]).T
#         logger.info(f"Completed resample_contour with result shape {result.shape}")
#         return result

#     except Exception as e:
#         logger.error(f"Error in resample_contour: {e}")
#         raise






# # def save_dxf_spline(inflated_contours, scaling_factor, height, finger_clearance=False):
# #     doc = ezdxf.new(units=ezdxf.units.MM)
# #     doc.header["$INSUNITS"] = ezdxf.units.MM
# #     msp = doc.modelspace()
# #     final_polygons_inch = []
# #     finger_centers = []
# #     original_polygons = []

# #     for contour in inflated_contours:
# #         try:
# #             # Removed the second parameter since it was causing the error
# #             resampled_contour = resample_contour(contour)  
            
# #             points_inch = [(x * scaling_factor, (height - y) * scaling_factor) 
# #                           for x, y in resampled_contour]
            
# #             if len(points_inch) < 3:
# #                 continue

# #             tool_polygon = build_tool_polygon(points_inch)
# #             original_polygons.append(tool_polygon)
            
# #             if finger_clearance:
# #                 try:
# #                     tool_polygon, center = place_finger_cut_adjusted(
# #                         tool_polygon, points_inch, finger_centers, final_polygons_inch
# #                     )
# #                 except FingerCutOverlapError:
# #                     tool_polygon = original_polygons[-1]
            
# #             exterior_coords = polygon_to_exterior_coords(tool_polygon)
# #             if len(exterior_coords) < 3:
# #                 continue
            
# #             msp.add_spline(exterior_coords, degree=3, dxfattribs={"layer": "TOOLS"})
# #             final_polygons_inch.append(tool_polygon)
            
# #         except ValueError as e:
# #             logger.warning(f"Skipping contour: {e}")

# #     dxf_filepath = os.path.join("./outputs", "out.dxf")
# #     doc.saveas(dxf_filepath)
# #     return dxf_filepath, final_polygons_inch, original_polygons




# def save_dxf_spline(inflated_contours, scaling_factor, height, finger_clearance=False):
#     doc = ezdxf.new(units=ezdxf.units.MM)
#     doc.header["$INSUNITS"] = ezdxf.units.MM
#     msp = doc.modelspace()
#     final_polygons_inch = []
#     finger_centers = []
#     original_polygons = []

#     # Scale correction factor based on your analysis
#     scale_correction = 1.079

#     for contour in inflated_contours:
#         try:
#             resampled_contour = resample_contour(contour)  

#             points_inch = [(x * scaling_factor, (height - y) * scaling_factor) 
#                           for x, y in resampled_contour]

#             if len(points_inch) < 3:
#                 continue

#             tool_polygon = build_tool_polygon(points_inch)
#             original_polygons.append(tool_polygon)

#             if finger_clearance:
#                 try:
#                     tool_polygon, center = place_finger_cut_adjusted(
#                         tool_polygon, points_inch, finger_centers, final_polygons_inch
#                     )
#                 except FingerCutOverlapError:
#                     tool_polygon = original_polygons[-1]

#             exterior_coords = polygon_to_exterior_coords(tool_polygon)
#             if len(exterior_coords) < 3:
#                 continue

#             # Apply scale correction AFTER finger cuts and polygon adjustments
#             corrected_coords = [(x * scale_correction, y * scale_correction) for x, y in exterior_coords]

#             msp.add_spline(corrected_coords, degree=3, dxfattribs={"layer": "TOOLS"})
#             final_polygons_inch.append(tool_polygon)

#         except ValueError as e:
#             logger.warning(f"Skipping contour: {e}")

#     dxf_filepath = os.path.join("./outputs", "out.dxf")
#     doc.saveas(dxf_filepath)
#     return dxf_filepath, final_polygons_inch, original_polygons





# def build_tool_polygon(points_inch):
#     return Polygon(points_inch)



# def polygon_to_exterior_coords(poly):
#     logger.info(f"Starting polygon_to_exterior_coords with input geometry type: {poly.geom_type}")

#     try:
#         # 1) If it's a GeometryCollection or MultiPolygon, fuse everything into one shape
#         if poly.geom_type == "GeometryCollection" or poly.geom_type == "MultiPolygon":
#             logger.debug(f"Performing unary_union on {poly.geom_type}")
#             unified = unary_union(poly)
#             if unified.is_empty:
#                 logger.warning("unary_union produced an empty geometry; returning empty list")
#                 return []
#             # If union still yields multiple disjoint pieces, pick the largest Polygon
#             if unified.geom_type == "GeometryCollection" or unified.geom_type == "MultiPolygon":
#                 largest = None
#                 max_area = 0.0
#                 for g in getattr(unified, "geoms", []):
#                     if hasattr(g, "area") and g.area > max_area and hasattr(g, "exterior"):
#                         max_area = g.area
#                         largest = g
#                 if largest is None:
#                     logger.warning("No valid Polygon found in unified geometry; returning empty list")
#                     return []
#                 poly = largest
#             else:
#                 # Now unified should be a single Polygon or LinearRing
#                 poly = unified

#         # 2) At this point, we must have a single Polygon (or something with an exterior)
#         if not hasattr(poly, "exterior") or poly.exterior is None:
#             logger.warning("Input geometry has no exterior ring; returning empty list")
#             return []

#         raw_coords = list(poly.exterior.coords)
#         total = len(raw_coords)
#         logger.info(f"Extracted {total} raw exterior coordinates")

#         if total == 0:
#             return []

#         # 3) Subsample coordinates to at most 100 points (evenly spaced)
#         max_pts = 100
#         if total > max_pts:
#             step = total // max_pts
#             sampled = [raw_coords[i] for i in range(0, total, step)]
#             # Ensure we include the last point to close the loop
#             if sampled[-1] != raw_coords[-1]:
#                 sampled.append(raw_coords[-1])
#             logger.info(f"Downsampled perimeter from {total} to {len(sampled)} points")
#             return sampled
#         else:
#             return raw_coords

#     except Exception as e:
#         logger.error(f"Error in polygon_to_exterior_coords: {e}")
#         return []








# def place_finger_cut_adjusted(
#     tool_polygon: Polygon,
#     points_inch: list,
#     existing_centers: list,
#     all_polygons: list,
#     circle_diameter: float = 25.4,
#     min_gap: float = 0.5,
#     max_attempts: int = 100
# ) -> (Polygon, tuple):
#     logger.info(f"Starting place_finger_cut_adjusted with {len(points_inch)} input points")

#     from shapely.geometry import Point
#     import numpy as np
#     import time
#     import random

#     # Fallback: if we run out of time or attempts, place in the "middle" of the outline
#     def fallback_solution():
#         logger.warning("Using fallback approach for finger cut placement")
#         # Pick the midpoint of the original outline as a last-resort center
#         fallback_center = points_inch[len(points_inch) // 2]
#         r = circle_diameter / 2.0
#         fallback_circle = Point(fallback_center).buffer(r, resolution=32)
#         try:
#             union_poly = tool_polygon.union(fallback_circle)
#         except Exception as e:
#             logger.warning(f"Fallback union failed ({e}); trying buffer-union fallback")
#             union_poly = tool_polygon.buffer(0).union(fallback_circle.buffer(0))

#         existing_centers.append(fallback_center)
#         logger.info(f"Fallback finger cut placed at {fallback_center}")
#         return union_poly, fallback_center

#     # Precompute values
#     r = circle_diameter / 2.0
#     needed_center_dist = circle_diameter + min_gap

#     # 1) Get perimeter coordinates of this polygon
#     raw_perimeter = polygon_to_exterior_coords(tool_polygon)
#     if not raw_perimeter:
#         logger.warning("No valid exterior coords found; using fallback immediately")
#         return fallback_solution()

#     # 2) Possibly subsample to at most 100 perimeter points
#     if len(raw_perimeter) > 100:
#         step = len(raw_perimeter) // 100
#         perimeter_coords = raw_perimeter[::step]
#         logger.info(f"Subsampled perimeter from {len(raw_perimeter)} to {len(perimeter_coords)} points")
#     else:
#         perimeter_coords = raw_perimeter[:]

#     # 3) Randomize the order to avoid bias
#     indices = list(range(len(perimeter_coords)))
#     random.shuffle(indices)
#     logger.debug(f"Shuffled perimeter indices for candidate order")

#     # 4) Non-blocking timeout setup
#     start_time = time.time()
#     timeout_secs = 5.0  # leave ~0.1s margin

#     attempts = 0
#     try:
#         while attempts < max_attempts:
#             # 5) Abort if we're running out of time
#             if time.time() - start_time > timeout_secs - 0.1:
#                 logger.warning(f"Approaching timeout after {attempts} attempts")
#                 return fallback_solution()

#             # 6) For each shuffled perimeter point, try small offsets
#             for idx in indices:
#                 # Check timeout inside the loop as well
#                 if time.time() - start_time > timeout_secs - 0.05:
#                     logger.warning("Timeout during candidate-point loop")
#                     return fallback_solution()

#                 cx, cy = perimeter_coords[idx]
#                 # Try five small offsets: (0,0), (±min_gap/2, 0), (0, ±min_gap/2)
#                 for dx, dy in [(0, 0), (-min_gap/2, 0), (min_gap/2, 0), (0, -min_gap/2), (0, min_gap/2)]:
#                     candidate_center = (cx + dx, cy + dy)

#                     # 6a) Check distance to existing finger centers
#                     too_close_finger = any(
#                         np.hypot(candidate_center[0] - ex, candidate_center[1] - ey) 
#                         < needed_center_dist 
#                         for (ex, ey) in existing_centers
#                     )
#                     if too_close_finger:
#                         continue

#                     # 6b) Build candidate circle with reduced resolution for speed
#                     candidate_circle = Point(candidate_center).buffer(r, resolution=32)

#                     # 6c) Must overlap ≥30% with this polygon
#                     try:
#                         inter_area = tool_polygon.intersection(candidate_circle).area
#                     except Exception:
#                         continue

#                     if inter_area < 0.3 * candidate_circle.area:
#                         continue

#                     # 6d) Must not intersect or even "touch" any other polygon (buffered by min_gap)
#                     invalid = False
#                     for other_poly in all_polygons:
#                         if other_poly.equals(tool_polygon):
#                             # Don't compare against itself
#                             continue
#                         # Buffer the other polygon by min_gap to enforce a strict clearance
#                         if other_poly.buffer(min_gap).intersects(candidate_circle) or \
#                            other_poly.buffer(min_gap).touches(candidate_circle):
#                             invalid = True
#                             break
#                     if invalid:
#                         continue

#                     # 6e) Candidate passes all tests → union and return
#                     try:
#                         union_poly = tool_polygon.union(candidate_circle)
#                         # If union is a MultiPolygon (more than one piece), reject
#                         if union_poly.geom_type == "MultiPolygon" and len(union_poly.geoms) > 1:
#                             continue
#                         # If union didn't change anything (no real cut), reject
#                         if union_poly.equals(tool_polygon):
#                             continue
#                     except Exception:
#                         continue

#                     existing_centers.append(candidate_center)
#                     logger.info(f"Finger cut placed successfully at {candidate_center} after {attempts} attempts")
#                     return union_poly, candidate_center

#             attempts += 1
#             # If we've done half the attempts and we're near timeout, bail out
#             if attempts >= (max_attempts // 2) and (time.time() - start_time) > timeout_secs * 0.8:
#                 logger.warning(f"Approaching timeout (attempt {attempts})")
#                 return fallback_solution()

#             logger.debug(f"Completed iteration {attempts}/{max_attempts}")

#         # If we exit loop without finding a valid spot
#         logger.warning(f"No valid spot after {max_attempts} attempts, using fallback")
#         return fallback_solution()

#     except Exception as e:
#         logger.error(f"Error in place_finger_cut_adjusted: {e}")
#         return fallback_solution()










# def extract_outlines(binary_image: np.ndarray) -> tuple:
#     contours, _ = cv2.findContours(
#         binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE
#     )

#     outline_image = np.full_like(binary_image, 255)  # White background

#     return outline_image, contours




# def round_edges(mask: np.ndarray, radius_mm: float, scaling_factor: float) -> np.ndarray:
#     """Rounds mask edges using contour smoothing."""
#     if radius_mm <= 0 or scaling_factor <= 0:
#         return mask
    
#     radius_px = max(1, int(radius_mm / scaling_factor))  # Ensure min 1px
    
#     # Handle small objects
#     if np.count_nonzero(mask) < 500:  # Small object threshold
#         return cv2.dilate(cv2.erode(mask, np.ones((3,3))), np.ones((3,3)))
    
#     # Existing contour processing with improvements:
#     contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    
#     # NEW: Filter small contours
#     contours = [c for c in contours if cv2.contourArea(c) > 100]
#     smoothed_contours = []
    
#     for contour in contours:
#         try:
#             # Resample with radius-based smoothing
#             resampled = resample_contour(contour, radius_px)
#             resampled = resampled.astype(np.int32).reshape((-1, 1, 2))
#             smoothed_contours.append(resampled)
#         except Exception as e:
#             logger.warning(f"Error smoothing contour: {e}")
#             smoothed_contours.append(contour)  # Fallback to original contour
    
#     # Draw smoothed contours
#     rounded = np.zeros_like(mask)
#     cv2.drawContours(rounded, smoothed_contours, -1, 255, thickness=cv2.FILLED)
    
#     return rounded


# def predict_og(image, offset, offset_unit, edge_radius, finger_clearance=False):
#     print(f"DEBUG: Image shape: {image.shape}, dtype: {image.dtype}, range: {image.min()}-{image.max()}")

#     coin_size_mm = 20.0

#     if offset_unit == "inches":
#         offset *= 25.4

#     if edge_radius is None or edge_radius == 0:
#         edge_radius = 0.0001

#     if offset < 0:
#         raise gr.Error("Offset Value Can't be negative")

#     try:
#         reference_obj_img, scaling_box_coords = detect_reference_square(image)
#     except ReferenceBoxNotDetectedError as e:
#         return (
#         None,
#         None,
#         None,
#         None,
#         f"Error: {str(e)}"
#     )
#     except Exception as e:
#         raise gr.Error(f"Error processing image: {str(e)}")

#     reference_obj_img = make_square(reference_obj_img)
    
#     # Use U2NETP for reference object background removal
#     reference_square_mask = remove_bg_u2netp(reference_obj_img)
#     reference_square_mask = resize_img(reference_square_mask, reference_obj_img.shape[:2][::-1])

#     try:
#         scaling_factor = calculate_scaling_factor(
#             target_image=reference_square_mask,
#             reference_obj_size_mm=coin_size_mm,
#             feature_detector="ORB",
#         )
#     except Exception as e:
#         scaling_factor = None
#         logger.warning(f"Error calculating scaling factor: {e}")

#     if not scaling_factor:
#         ref_size_px = (reference_square_mask.shape[0] + reference_square_mask.shape[1]) / 2
#         scaling_factor = 20.0 / ref_size_px
#         logger.info(f"Fallback scaling: {scaling_factor:.4f} mm/px using 20mm reference")

#     # Use BiRefNet for main object background removal
#     orig_size = image.shape[:2]
#     objects_mask = remove_bg(image)
#     processed_size = objects_mask.shape[:2]

#     # REMOVE ALL COINS from mask:
#     res = reference_detector_global.predict(image, conf=0.05)
#     boxes = res[0].cpu().boxes.xyxy if res and len(res) > 0 else []

#     for box in boxes:
#         objects_mask = exclude_scaling_box(
#             objects_mask,
#             box,
#             orig_size,
#             processed_size,
#             expansion_factor=1.2,
#         )

#     objects_mask = resize_img(objects_mask, (image.shape[1], image.shape[0]))

#     # offset_pixels = (float(offset) / scaling_factor) * 2 + 1 if scaling_factor else 1
#     # dilated_mask = cv2.dilate(objects_mask, np.ones((int(offset_pixels), int(offset_pixels)), np.uint8))
#     # Image.fromarray(dilated_mask).save("./outputs/scaled_mask_original.jpg")
#     # dilated_mask_orig = dilated_mask.copy()

#     # #if edge_radius > 0:
#     #     # Use morphological rounding instead of contour-based
#     # rounded_mask = round_edges(objects_mask, edge_radius, scaling_factor)
#     # #else:
#     #     #rounded_mask = objects_mask.copy()
    
#     # # Apply dilation AFTER rounding
#     # offset_pixels = (float(offset) / scaling_factor) * 2 + 1 if scaling_factor else 1
#     # kernel = np.ones((int(offset_pixels), int(offset_pixels)), np.uint8)
#     # dilated_mask = cv2.dilate(rounded_mask, kernel)
#     # Apply edge rounding first
#     rounded_mask = round_edges(objects_mask, edge_radius, scaling_factor)

#     # Apply dilation AFTER rounding
#     offset_pixels = (float(offset) / scaling_factor) * 2 + 1 if scaling_factor else 1
#     kernel = np.ones((int(offset_pixels), int(offset_pixels)), np.uint8)
#     final_dilated_mask = cv2.dilate(rounded_mask, kernel)

#     # Save for debugging
#     Image.fromarray(final_dilated_mask).save("./outputs/scaled_mask_original.jpg")
        

#     outlines, contours = extract_outlines(final_dilated_mask)

#     try:
#         dxf, finger_polygons, original_polygons = save_dxf_spline(
#             contours,
#             scaling_factor,
#             processed_size[0],
#             finger_clearance=(finger_clearance == "On")
#         )
#     except FingerCutOverlapError as e:
#         raise gr.Error(str(e))

#     shrunked_img_contours = image.copy()

#     if finger_clearance == "On":
#         outlines = np.full_like(final_dilated_mask, 255)
#         for poly in finger_polygons:
#             try:
#                 coords = np.array([
#                     (int(x / scaling_factor), int(processed_size[0] - y / scaling_factor))
#                     for x, y in poly.exterior.coords
#                 ], np.int32).reshape((-1, 1, 2))

#                 cv2.drawContours(shrunked_img_contours, [coords], -1, 0, thickness=2)
#                 cv2.drawContours(outlines, [coords], -1, 0, thickness=2)
#             except Exception as e:
#                 logger.warning(f"Failed to draw finger cut: {e}")
#                 continue
#     else:
#         outlines = np.full_like(final_dilated_mask, 255)
#         cv2.drawContours(shrunked_img_contours, contours, -1, 0, thickness=2)
#         cv2.drawContours(outlines, contours, -1, 0, thickness=2)

#     return (
#     shrunked_img_contours,
#     outlines,
#     dxf,
#     final_dilated_mask,
#     f"{scaling_factor:.4f}")


# def predict_simple(image):
#     """
#     Only image in → returns (annotated, outlines, dxf, mask).
#     Uses offset=0 mm, no fillet, no finger-cut.
#     """
#     ann, outlines, dxf_path, mask, _ = predict_og(
#         image,
#         offset=0,
#         offset_unit="mm",
#         edge_radius=0,
#         finger_clearance="Off",
#     )
#     return ann, outlines, dxf_path, mask

# def predict_middle(image, enable_fillet, fillet_value_mm):
#     """
#     image + (On/Off) fillet toggle + fillet radius → returns (annotated, outlines, dxf, mask).
#     Uses offset=0 mm, finger-cut off.
#     """
#     radius = fillet_value_mm if enable_fillet == "On" else 0
#     ann, outlines, dxf_path, mask, _ = predict_og(
#         image,
#         offset=0,
#         offset_unit="mm",
#         edge_radius=radius,
#         finger_clearance="Off",
#     )
#     return ann, outlines, dxf_path, mask

# def predict_full(image, enable_fillet, fillet_value_mm, enable_finger_cut):
#     """
#     image + fillet toggle/value + finger-cut toggle → returns (annotated, outlines, dxf, mask).
#     Uses offset=0 mm.
#     """
#     radius = fillet_value_mm if enable_fillet == "On" else 0
#     finger_flag = "On" if enable_finger_cut == "On" else "Off"
#     ann, outlines, dxf_path, mask, _ = predict_og(
#         image,
#         offset=0,
#         offset_unit="mm",
#         edge_radius=radius,
#         finger_clearance=finger_flag,
#     )
#     return ann, outlines, dxf_path, mask




# def update_interface(language):
#     return [
#         gr.Image(label=TRANSLATIONS[language]["input_image"], type="numpy"),
#         gr.Row([
#             gr.Number(label=TRANSLATIONS[language]["offset_value"], value=0),
#             gr.Dropdown(["mm", "inches"], value="mm", 
#                       label=TRANSLATIONS[language]["offset_unit"])
#         ]),
#         gr.Slider(minimum=0,maximum=20,step=1,value=5,label=TRANSLATIONS[language]["edge_radius"],visible=False,interactive=True),
#         gr.Radio(choices=["On", "Off"],value="Off",label=TRANSLATIONS[language]["enable_radius"],),
#         gr.Image(label=TRANSLATIONS[language]["output_image"]),
#         gr.Image(label=TRANSLATIONS[language]["outlines"]),
#         gr.File(label=TRANSLATIONS[language]["dxf_file"]),
#         gr.Image(label=TRANSLATIONS[language]["mask"]),
#         gr.Textbox(label=TRANSLATIONS[language]["scaling_factor"],placeholder=TRANSLATIONS[language]["scaling_placeholder"],),
#     ]

# if __name__ == "__main__":
#     os.makedirs("./outputs", exist_ok=True)

#     with gr.Blocks() as demo:
#         language = gr.Dropdown(
#             choices=["english", "dutch"],
#             value="english",
#             label="Select Language",
#             interactive=True
#         )
        
#         input_image = gr.Image(label=TRANSLATIONS["english"]["input_image"], type="numpy")
        
#         with gr.Row():
#             offset = gr.Number(label=TRANSLATIONS["english"]["offset_value"], value=0)
#             offset_unit = gr.Dropdown([
#                 "mm", "inches"
#             ], value="mm", label=TRANSLATIONS["english"]["offset_unit"])
            
#         finger_toggle = gr.Radio(
#             choices=["On", "Off"],
#             value="Off",
#             label=TRANSLATIONS["english"]["enable_finger"]
#         )
        
#         edge_radius = gr.Slider(
#             minimum=0,
#             maximum=20,
#             step=1,
#             value=5,
#             label=TRANSLATIONS["english"]["edge_radius"],
#             visible=False,
#             interactive=True
#         )
        
#         radius_toggle = gr.Radio(
#             choices=["On", "Off"],
#             value="Off",
#             label=TRANSLATIONS["english"]["enable_radius"],
#             interactive=True
#         )
        
#         def toggle_radius(choice):
#             if choice == "On":
#                 return gr.Slider(visible=True)
#             return gr.Slider(visible=False, value=0)

#         radius_toggle.change(
#             fn=toggle_radius,
#             inputs=radius_toggle,
#             outputs=edge_radius
#         )
        
#         output_image = gr.Image(label=TRANSLATIONS["english"]["output_image"])
#         outlines = gr.Image(label=TRANSLATIONS["english"]["outlines"])
#         dxf_file = gr.File(label=TRANSLATIONS["english"]["dxf_file"])
#         mask = gr.Image(label=TRANSLATIONS["english"]["mask"])
        
#         scaling = gr.Textbox(
#             label=TRANSLATIONS["english"]["scaling_factor"],
#             placeholder=TRANSLATIONS["english"]["scaling_placeholder"]
#         )

#         submit_btn = gr.Button("Submit")
        
#         language.change(
#             fn=lambda x: [
#                 gr.update(label=TRANSLATIONS[x]["input_image"]),
#                 gr.update(label=TRANSLATIONS[x]["offset_value"]),
#                 gr.update(label=TRANSLATIONS[x]["offset_unit"]),
#                 gr.update(label=TRANSLATIONS[x]["output_image"]),
#                 gr.update(label=TRANSLATIONS[x]["outlines"]),
#                 gr.update(label=TRANSLATIONS[x]["enable_finger"]),
#                 gr.update(label=TRANSLATIONS[x]["dxf_file"]),
#                 gr.update(label=TRANSLATIONS[x]["mask"]),
#                 gr.update(label=TRANSLATIONS[x]["enable_radius"]),
#                 gr.update(label=TRANSLATIONS[x]["edge_radius"]),
#                 gr.update(
#                     label=TRANSLATIONS[x]["scaling_factor"],
#                     placeholder=TRANSLATIONS[x]["scaling_placeholder"]
#                 ),
#             ],
#             inputs=[language],
#             outputs=[
#                 input_image, offset, offset_unit,
#                 output_image, outlines, finger_toggle, dxf_file,
#                 mask, radius_toggle, edge_radius, scaling
#             ]
#         )
        
#         def custom_predict_and_format(*args):
#             output_image, outlines, dxf_path, mask, scaling = predict_og(*args)
#             if output_image is None:
#                 return (
#                     None, None, None, None, "Reference coin not detected!"
#                 )
#             return (
#                 output_image, outlines, dxf_path, mask, scaling
#             )

#         submit_btn.click(
#             fn=custom_predict_and_format,
#             inputs=[input_image, offset, offset_unit, edge_radius, finger_toggle],
#             outputs=[output_image, outlines, dxf_file, mask, scaling]
#         )


#         gr.Examples(
#             examples=[
#                 ["./examples/Test20.jpg", 0, "mm"],
#                 ["./examples/Test21.jpg", 0, "mm"],
#                 ["./examples/Test22.jpg", 0, "mm"],
#                 ["./examples/Test23.jpg", 0, "mm"],
#             ],
#             inputs=[input_image, offset, offset_unit]
#         )

#     demo.launch(share=True)

import os
from pathlib import Path
from typing import List, Union
from PIL import Image
import ezdxf.units
import numpy as np
import torch
from torchvision import transforms
from ultralytics import YOLOWorld, YOLO
from ultralytics.engine.results import Results
from ultralytics.utils.plotting import save_one_box
from transformers import AutoModelForImageSegmentation
import cv2
import ezdxf
import gradio as gr
import gc
from scalingtestupdated import calculate_scaling_factor
from scipy.interpolate import splprep, splev
from scipy.ndimage import gaussian_filter1d
import json
import time
import signal
from shapely.ops import unary_union
from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, Point
from u2netp import U2NETP  # Add U2NETP import
import logging
import shutil

# Initialize logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Create cache directory for models
CACHE_DIR = os.path.join(os.path.dirname(__file__), ".cache")
os.makedirs(CACHE_DIR, exist_ok=True)

# Custom Exception Classes
class TimeoutReachedError(Exception):
    pass

class BoundaryOverlapError(Exception):
    pass

class TextOverlapError(Exception):
    pass

class ReferenceBoxNotDetectedError(Exception):
    """Raised when the Reference coin cannot be detected in the image"""
    pass

class FingerCutOverlapError(Exception):
    """Raised when finger cuts overlap with existing geometry"""
    def __init__(self, message="There was an overlap with fingercuts... Please try again to generate dxf."):
        super().__init__(message)

# ===== LAZY LOADING - REPLACE THE GLOBAL MODEL INITIALIZATION =====
# Instead of loading models at startup, declare them as None
print("Initializing lazy model loading...")
reference_detector_global = None
u2net_global = None
birefnet = None

# Model paths - use absolute paths for Docker
reference_model_path = os.path.join(CACHE_DIR, "best1.pt")
u2net_model_path = os.path.join(CACHE_DIR, "u2netp.pth")

# Copy model files to cache if they don't exist - with error handling
def ensure_model_files():
    if not os.path.exists(reference_model_path):
        if os.path.exists("best1.pt"):
            shutil.copy("best1.pt", reference_model_path)
        else:
            raise FileNotFoundError("best1.pt model file not found")
    if not os.path.exists(u2net_model_path):
        if os.path.exists("u2netp.pth"):
            shutil.copy("u2netp.pth", u2net_model_path)
        else:
            raise FileNotFoundError("u2netp.pth model file not found")

# Call this at startup
ensure_model_files()

# device = "cpu"
# torch.set_float32_matmul_precision(["high", "highest"][0])

# ===== LAZY LOADING FUNCTIONS - ADD THESE =====
def get_reference_detector():
    """Lazy load reference detector model"""
    global reference_detector_global
    if reference_detector_global is None:
        logger.info("Loading reference detector model...")
        reference_detector_global = YOLO(reference_model_path)
        logger.info("Reference detector loaded successfully")
    return reference_detector_global

def get_u2net():
    """Lazy load U2NETP model"""
    global u2net_global
    if u2net_global is None:
        logger.info("Loading U2NETP model...")
        u2net_global = U2NETP(3, 1)
        u2net_global.load_state_dict(torch.load(u2net_model_path, map_location="cpu"))
        u2net_global.to(device)
        u2net_global.eval()
        logger.info("U2NETP model loaded successfully")
    return u2net_global
def load_birefnet_model():
    """Load BiRefNet model from HuggingFace"""
    from transformers import AutoModelForImageSegmentation
    return AutoModelForImageSegmentation.from_pretrained(
        'ZhengPeng7/BiRefNet', 
        trust_remote_code=True
    )
def get_birefnet():
    """Lazy load BiRefNet model"""
    global birefnet
    if birefnet is None:
        logger.info("Loading BiRefNet model...")
        birefnet = load_birefnet_model()
        birefnet.to(device)
        birefnet.eval()
        logger.info("BiRefNet model loaded successfully")
    return birefnet




device = "cpu"
torch.set_float32_matmul_precision(["high", "highest"][0])

# Move models to device
# u2net_global.to(device)
# u2net_global.eval()
# birefnet.to(device)
# birefnet.eval()

# Define transforms
transform_image = transforms.Compose([
    transforms.Resize((1024, 1024)),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])

def remove_bg_u2netp(image: np.ndarray) -> np.ndarray:
    """Remove background using U2NETP model specifically for reference objects"""
    try:
        u2net_model = get_u2net()  # <-- ADD THIS LINE
        
        image_pil = Image.fromarray(image)
        transform_u2netp = transforms.Compose([
            transforms.Resize((320, 320)),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
        ])
        
        input_tensor = transform_u2netp(image_pil).unsqueeze(0).to(device)
        
        with torch.no_grad():
            outputs = u2net_model(input_tensor)  # <-- CHANGE FROM u2net_global
        
        pred = outputs[0]
        pred = (pred - pred.min()) / (pred.max() - pred.min() + 1e-8)
        pred_np = pred.squeeze().cpu().numpy()
        pred_np = cv2.resize(pred_np, (image_pil.width, image_pil.height))
        pred_np = (pred_np * 255).astype(np.uint8)
        
        return pred_np
    except Exception as e:
        logger.error(f"Error in U2NETP background removal: {e}")
        raise

def remove_bg(image: np.ndarray) -> np.ndarray:
    """Remove background using BiRefNet model for main objects"""
    try:
        birefnet_model = get_birefnet()  # <-- ADD THIS LINE
        
        image = Image.fromarray(image)
        input_images = transform_image(image).unsqueeze(0).to(device)

        with torch.no_grad():
            preds = birefnet_model(input_images)[-1].sigmoid().cpu()  # <-- CHANGE FROM birefnet
        pred = preds[0].squeeze()

        pred_pil: Image = transforms.ToPILImage()(pred)
        
        scale_ratio = 1024 / max(image.size)
        scaled_size = (int(image.size[0] * scale_ratio), int(image.size[1] * scale_ratio))
        
        return np.array(pred_pil.resize(scaled_size))
    except Exception as e:
        logger.error(f"Error in BiRefNet background removal: {e}")
        raise

def resize_img(img: np.ndarray, resize_dim):
    return np.array(Image.fromarray(img).resize(resize_dim))

def make_square(img: np.ndarray):
    """Make the image square by padding"""
    height, width = img.shape[:2]
    max_dim = max(height, width)
    
    pad_height = (max_dim - height) // 2
    pad_width = (max_dim - width) // 2
    
    pad_height_extra = max_dim - height - 2 * pad_height
    pad_width_extra = max_dim - width - 2 * pad_width
    
    if len(img.shape) == 3:  # Color image
        padded = np.pad(
            img,
            (
                (pad_height, pad_height + pad_height_extra),
                (pad_width, pad_width + pad_width_extra),
                (0, 0),
            ),
            mode="edge",
        )
    else:  # Grayscale image
        padded = np.pad(
            img,
            (
                (pad_height, pad_height + pad_height_extra),
                (pad_width, pad_width + pad_width_extra),
            ),
            mode="edge",
        )
    
    return padded


def detect_reference_square(img) -> tuple:
    """Detect reference square in the image and ignore other coins"""
    try:
        reference_detector = get_reference_detector()  # <-- ADD THIS LINE
        
        res = reference_detector.predict(img, conf=0.70)  # <-- CHANGE FROM reference_detector_global
        if not res or len(res) == 0 or len(res[0].boxes) == 0:
            raise ReferenceBoxNotDetectedError("Unable to detect the reference coin in the image.")
        
        # Get all detected boxes
        boxes = res[0].cpu().boxes.xyxy
        
        # Find the largest box (most likely the reference coin)
        largest_box = None
        max_area = 0
        for box in boxes:
            x_min, y_min, x_max, y_max = box
            area = (x_max - x_min) * (y_max - y_min)
            if area > max_area:
                max_area = area
                largest_box = box
        
        return (
            save_one_box(largest_box.unsqueeze(0), img, save=False),
            largest_box
        )
    except Exception as e:
        if not isinstance(e, ReferenceBoxNotDetectedError):
            logger.error(f"Error in reference square detection: {e}")
            raise ReferenceBoxNotDetectedError("Error detecting reference coin. Please try again with a clearer image.")
        raise








def exclude_scaling_box(
    image: np.ndarray,
    bbox: np.ndarray,
    orig_size: tuple,
    processed_size: tuple,
    expansion_factor: float = 1.2,
) -> np.ndarray:
    x_min, y_min, x_max, y_max = map(int, bbox)
    scale_x = processed_size[1] / orig_size[1]
    scale_y = processed_size[0] / orig_size[0]
    
    x_min = int(x_min * scale_x)
    x_max = int(x_max * scale_x)
    y_min = int(y_min * scale_y)
    y_max = int(y_max * scale_y)
    
    box_width = x_max - x_min
    box_height = y_max - y_min
    
    expanded_x_min = max(0, int(x_min - (expansion_factor - 1) * box_width / 2))
    expanded_x_max = min(
        image.shape[1], int(x_max + (expansion_factor - 1) * box_width / 2)
    )
    expanded_y_min = max(0, int(y_min - (expansion_factor - 1) * box_height / 2))
    expanded_y_max = min(
        image.shape[0], int(y_max + (expansion_factor - 1) * box_height / 2)
    )
    
    image[expanded_y_min:expanded_y_max, expanded_x_min:expanded_x_max] = 0
    return image





def resample_contour(contour, edge_radius_px: int = 0):
    """Resample contour with radius-aware smoothing and periodic handling."""
    logger.info(f"Starting resample_contour with contour of shape {contour.shape}")

    num_points = 1500
    sigma = max(2, int(edge_radius_px) // 4)  # Adjust sigma based on radius

    if len(contour) < 4:  # Need at least 4 points for spline with periodic condition
        error_msg = f"Contour must have at least 4 points, but has {len(contour)} points."
        logger.error(error_msg)
        raise ValueError(error_msg)

    try:
        contour = contour[:, 0, :]
        logger.debug(f"Reshaped contour to shape {contour.shape}")

        # Ensure contour is closed by making start and end points the same
        if not np.array_equal(contour[0], contour[-1]):
            contour = np.vstack([contour, contour[0]])

        # Create periodic spline representation
        tck, u = splprep(contour.T, u=None, s=0, per=True)
        
        # Evaluate spline at evenly spaced points
        u_new = np.linspace(u.min(), u.max(), num_points)
        x_new, y_new = splev(u_new, tck, der=0)
        
        # Apply Gaussian smoothing with wrap-around
        if sigma > 0:
            x_new = gaussian_filter1d(x_new, sigma=sigma, mode='wrap')
            y_new = gaussian_filter1d(y_new, sigma=sigma, mode='wrap')
            
            # Re-close the contour after smoothing
            x_new[-1] = x_new[0]
            y_new[-1] = y_new[0]

        result = np.array([x_new, y_new]).T
        logger.info(f"Completed resample_contour with result shape {result.shape}")
        return result

    except Exception as e:
        logger.error(f"Error in resample_contour: {e}")
        raise






# def save_dxf_spline(inflated_contours, scaling_factor, height, finger_clearance=False):
#     doc = ezdxf.new(units=ezdxf.units.MM)
#     doc.header["$INSUNITS"] = ezdxf.units.MM
#     msp = doc.modelspace()
#     final_polygons_inch = []
#     finger_centers = []
#     original_polygons = []

#     for contour in inflated_contours:
#         try:
#             # Removed the second parameter since it was causing the error
#             resampled_contour = resample_contour(contour)  
            
#             points_inch = [(x * scaling_factor, (height - y) * scaling_factor) 
#                           for x, y in resampled_contour]
            
#             if len(points_inch) < 3:
#                 continue

#             tool_polygon = build_tool_polygon(points_inch)
#             original_polygons.append(tool_polygon)
            
#             if finger_clearance:
#                 try:
#                     tool_polygon, center = place_finger_cut_adjusted(
#                         tool_polygon, points_inch, finger_centers, final_polygons_inch
#                     )
#                 except FingerCutOverlapError:
#                     tool_polygon = original_polygons[-1]
            
#             exterior_coords = polygon_to_exterior_coords(tool_polygon)
#             if len(exterior_coords) < 3:
#                 continue
            
#             msp.add_spline(exterior_coords, degree=3, dxfattribs={"layer": "TOOLS"})
#             final_polygons_inch.append(tool_polygon)
            
#         except ValueError as e:
#             logger.warning(f"Skipping contour: {e}")

#     dxf_filepath = os.path.join("./outputs", "out.dxf")
#     doc.saveas(dxf_filepath)
#     return dxf_filepath, final_polygons_inch, original_polygons




def save_dxf_spline(inflated_contours, scaling_factor, height, finger_clearance=False):
    doc = ezdxf.new(units=ezdxf.units.MM)
    doc.header["$INSUNITS"] = ezdxf.units.MM
    msp = doc.modelspace()
    final_polygons_inch = []
    finger_centers = []
    original_polygons = []

    # Scale correction factor based on your analysis
    scale_correction = 1.079

    for contour in inflated_contours:
        try:
            resampled_contour = resample_contour(contour)  

            points_inch = [(x * scaling_factor, (height - y) * scaling_factor) 
                          for x, y in resampled_contour]

            if len(points_inch) < 3:
                continue

            tool_polygon = build_tool_polygon(points_inch)
            original_polygons.append(tool_polygon)

            if finger_clearance:
                try:
                    tool_polygon, center = place_finger_cut_adjusted(
                        tool_polygon, points_inch, finger_centers, final_polygons_inch
                    )
                except FingerCutOverlapError:
                    tool_polygon = original_polygons[-1]

            exterior_coords = polygon_to_exterior_coords(tool_polygon)
            if len(exterior_coords) < 3:
                continue

            # Apply scale correction AFTER finger cuts and polygon adjustments
            corrected_coords = [(x * scale_correction, y * scale_correction) for x, y in exterior_coords]

            msp.add_spline(corrected_coords, degree=3, dxfattribs={"layer": "TOOLS"})
            final_polygons_inch.append(tool_polygon)

        except ValueError as e:
            logger.warning(f"Skipping contour: {e}")

    dxf_filepath = os.path.join("./outputs", "out.dxf")
    doc.saveas(dxf_filepath)
    return dxf_filepath, final_polygons_inch, original_polygons





def build_tool_polygon(points_inch):
    return Polygon(points_inch)



def polygon_to_exterior_coords(poly):
    logger.info(f"Starting polygon_to_exterior_coords with input geometry type: {poly.geom_type}")

    try:
        # 1) If it's a GeometryCollection or MultiPolygon, fuse everything into one shape
        if poly.geom_type == "GeometryCollection" or poly.geom_type == "MultiPolygon":
            logger.debug(f"Performing unary_union on {poly.geom_type}")
            unified = unary_union(poly)
            if unified.is_empty:
                logger.warning("unary_union produced an empty geometry; returning empty list")
                return []
            # If union still yields multiple disjoint pieces, pick the largest Polygon
            if unified.geom_type == "GeometryCollection" or unified.geom_type == "MultiPolygon":
                largest = None
                max_area = 0.0
                for g in getattr(unified, "geoms", []):
                    if hasattr(g, "area") and g.area > max_area and hasattr(g, "exterior"):
                        max_area = g.area
                        largest = g
                if largest is None:
                    logger.warning("No valid Polygon found in unified geometry; returning empty list")
                    return []
                poly = largest
            else:
                # Now unified should be a single Polygon or LinearRing
                poly = unified

        # 2) At this point, we must have a single Polygon (or something with an exterior)
        if not hasattr(poly, "exterior") or poly.exterior is None:
            logger.warning("Input geometry has no exterior ring; returning empty list")
            return []

        raw_coords = list(poly.exterior.coords)
        total = len(raw_coords)
        logger.info(f"Extracted {total} raw exterior coordinates")

        if total == 0:
            return []

        # 3) Subsample coordinates to at most 100 points (evenly spaced)
        max_pts = 100
        if total > max_pts:
            step = total // max_pts
            sampled = [raw_coords[i] for i in range(0, total, step)]
            # Ensure we include the last point to close the loop
            if sampled[-1] != raw_coords[-1]:
                sampled.append(raw_coords[-1])
            logger.info(f"Downsampled perimeter from {total} to {len(sampled)} points")
            return sampled
        else:
            return raw_coords

    except Exception as e:
        logger.error(f"Error in polygon_to_exterior_coords: {e}")
        return []








def place_finger_cut_adjusted(
    tool_polygon: Polygon,
    points_inch: list,
    existing_centers: list,
    all_polygons: list,
    circle_diameter: float = 25.4,
    min_gap: float = 0.5,
    max_attempts: int = 100
) -> (Polygon, tuple):
    logger.info(f"Starting place_finger_cut_adjusted with {len(points_inch)} input points")

    from shapely.geometry import Point
    import numpy as np
    import time
    import random

    # Fallback: if we run out of time or attempts, place in the "middle" of the outline
    def fallback_solution():
        logger.warning("Using fallback approach for finger cut placement")
        # Pick the midpoint of the original outline as a last-resort center
        fallback_center = points_inch[len(points_inch) // 2]
        r = circle_diameter / 2.0
        fallback_circle = Point(fallback_center).buffer(r, resolution=32)
        try:
            union_poly = tool_polygon.union(fallback_circle)
        except Exception as e:
            logger.warning(f"Fallback union failed ({e}); trying buffer-union fallback")
            union_poly = tool_polygon.buffer(0).union(fallback_circle.buffer(0))

        existing_centers.append(fallback_center)
        logger.info(f"Fallback finger cut placed at {fallback_center}")
        return union_poly, fallback_center

    # Precompute values
    r = circle_diameter / 2.0
    needed_center_dist = circle_diameter + min_gap

    # 1) Get perimeter coordinates of this polygon
    raw_perimeter = polygon_to_exterior_coords(tool_polygon)
    if not raw_perimeter:
        logger.warning("No valid exterior coords found; using fallback immediately")
        return fallback_solution()

    # 2) Possibly subsample to at most 100 perimeter points
    if len(raw_perimeter) > 100:
        step = len(raw_perimeter) // 100
        perimeter_coords = raw_perimeter[::step]
        logger.info(f"Subsampled perimeter from {len(raw_perimeter)} to {len(perimeter_coords)} points")
    else:
        perimeter_coords = raw_perimeter[:]

    # 3) Randomize the order to avoid bias
    indices = list(range(len(perimeter_coords)))
    random.shuffle(indices)
    logger.debug(f"Shuffled perimeter indices for candidate order")

    # 4) Non-blocking timeout setup
    start_time = time.time()
    timeout_secs = 5.0  # leave ~0.1s margin

    attempts = 0
    try:
        while attempts < max_attempts:
            # 5) Abort if we're running out of time
            if time.time() - start_time > timeout_secs - 0.1:
                logger.warning(f"Approaching timeout after {attempts} attempts")
                return fallback_solution()

            # 6) For each shuffled perimeter point, try small offsets
            for idx in indices:
                # Check timeout inside the loop as well
                if time.time() - start_time > timeout_secs - 0.05:
                    logger.warning("Timeout during candidate-point loop")
                    return fallback_solution()

                cx, cy = perimeter_coords[idx]
                # Try five small offsets: (0,0), (±min_gap/2, 0), (0, ±min_gap/2)
                for dx, dy in [(0, 0), (-min_gap/2, 0), (min_gap/2, 0), (0, -min_gap/2), (0, min_gap/2)]:
                    candidate_center = (cx + dx, cy + dy)

                    # 6a) Check distance to existing finger centers
                    too_close_finger = any(
                        np.hypot(candidate_center[0] - ex, candidate_center[1] - ey) 
                        < needed_center_dist 
                        for (ex, ey) in existing_centers
                    )
                    if too_close_finger:
                        continue

                    # 6b) Build candidate circle with reduced resolution for speed
                    candidate_circle = Point(candidate_center).buffer(r, resolution=32)

                    # 6c) Must overlap ≥30% with this polygon
                    try:
                        inter_area = tool_polygon.intersection(candidate_circle).area
                    except Exception:
                        continue

                    if inter_area < 0.3 * candidate_circle.area:
                        continue

                    # 6d) Must not intersect or even "touch" any other polygon (buffered by min_gap)
                    invalid = False
                    for other_poly in all_polygons:
                        if other_poly.equals(tool_polygon):
                            # Don't compare against itself
                            continue
                        # Buffer the other polygon by min_gap to enforce a strict clearance
                        if other_poly.buffer(min_gap).intersects(candidate_circle) or \
                           other_poly.buffer(min_gap).touches(candidate_circle):
                            invalid = True
                            break
                    if invalid:
                        continue

                    # 6e) Candidate passes all tests → union and return
                    try:
                        union_poly = tool_polygon.union(candidate_circle)
                        # If union is a MultiPolygon (more than one piece), reject
                        if union_poly.geom_type == "MultiPolygon" and len(union_poly.geoms) > 1:
                            continue
                        # If union didn't change anything (no real cut), reject
                        if union_poly.equals(tool_polygon):
                            continue
                    except Exception:
                        continue

                    existing_centers.append(candidate_center)
                    logger.info(f"Finger cut placed successfully at {candidate_center} after {attempts} attempts")
                    return union_poly, candidate_center

            attempts += 1
            # If we've done half the attempts and we're near timeout, bail out
            if attempts >= (max_attempts // 2) and (time.time() - start_time) > timeout_secs * 0.8:
                logger.warning(f"Approaching timeout (attempt {attempts})")
                return fallback_solution()

            logger.debug(f"Completed iteration {attempts}/{max_attempts}")

        # If we exit loop without finding a valid spot
        logger.warning(f"No valid spot after {max_attempts} attempts, using fallback")
        return fallback_solution()

    except Exception as e:
        logger.error(f"Error in place_finger_cut_adjusted: {e}")
        return fallback_solution()










def extract_outlines(binary_image: np.ndarray) -> tuple:
    contours, _ = cv2.findContours(
        binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE
    )

    outline_image = np.full_like(binary_image, 255)  # White background

    return outline_image, contours




def round_edges(mask: np.ndarray, radius_mm: float, scaling_factor: float) -> np.ndarray:
    """Rounds mask edges using contour smoothing."""
    if radius_mm <= 0 or scaling_factor <= 0:
        return mask
    
    radius_px = max(1, int(radius_mm / scaling_factor))  # Ensure min 1px
    
    # Handle small objects
    if np.count_nonzero(mask) < 500:  # Small object threshold
        return cv2.dilate(cv2.erode(mask, np.ones((3,3))), np.ones((3,3)))
    
    # Existing contour processing with improvements:
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    
    # NEW: Filter small contours
    contours = [c for c in contours if cv2.contourArea(c) > 100]
    smoothed_contours = []
    
    for contour in contours:
        try:
            # Resample with radius-based smoothing
            resampled = resample_contour(contour, radius_px)
            resampled = resampled.astype(np.int32).reshape((-1, 1, 2))
            smoothed_contours.append(resampled)
        except Exception as e:
            logger.warning(f"Error smoothing contour: {e}")
            smoothed_contours.append(contour)  # Fallback to original contour
    
    # Draw smoothed contours
    rounded = np.zeros_like(mask)
    cv2.drawContours(rounded, smoothed_contours, -1, 255, thickness=cv2.FILLED)
    
    return rounded

def cleanup_memory():
    """Clean up memory after processing"""
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
    gc.collect()
    logger.info("Memory cleanup completed")

def cleanup_models():
    """Unload models to free memory"""
    global reference_detector_global, u2net_global, birefnet
    if reference_detector_global is not None:
        del reference_detector_global
        reference_detector_global = None
    if u2net_global is not None:
        del u2net_global
        u2net_global = None
    if birefnet is not None:
        del birefnet
        birefnet = None
    cleanup_memory()

def predict_og(image, offset, offset_unit, edge_radius, finger_clearance=False):
    coin_size_mm = 20.0

    if offset_unit == "inches":
        offset *= 25.4

    if edge_radius is None or edge_radius == 0:
        edge_radius = 0.0001

    if offset < 0:
        raise gr.Error("Offset Value Can't be negative")

    try:
        reference_obj_img, scaling_box_coords = detect_reference_square(image)
    except ReferenceBoxNotDetectedError as e:
        return (
        None,
        None,
        None,
        None,
        f"Error: {str(e)}"
    )
    except Exception as e:
        raise gr.Error(f"Error processing image: {str(e)}")

    reference_obj_img = make_square(reference_obj_img)
    
    # Use U2NETP for reference object background removal
    reference_square_mask = remove_bg_u2netp(reference_obj_img)
    reference_square_mask = resize_img(reference_square_mask, reference_obj_img.shape[:2][::-1])

    try:
        scaling_factor = calculate_scaling_factor(
            target_image=reference_square_mask,
            reference_obj_size_mm=coin_size_mm,
            feature_detector="ORB",
        )
    except Exception as e:
        scaling_factor = None
        logger.warning(f"Error calculating scaling factor: {e}")

    if not scaling_factor:
        ref_size_px = (reference_square_mask.shape[0] + reference_square_mask.shape[1]) / 2
        scaling_factor = 20.0 / ref_size_px
        logger.info(f"Fallback scaling: {scaling_factor:.4f} mm/px using 20mm reference")

    # Use BiRefNet for main object background removal
    orig_size = image.shape[:2]
    objects_mask = remove_bg(image)
    processed_size = objects_mask.shape[:2]

    # REMOVE ALL COINS from mask:
    # res = reference_detector_global.predict(image, conf=0.05)
    res = get_reference_detector().predict(image, conf=0.05)
    boxes = res[0].cpu().boxes.xyxy if res and len(res) > 0 else []

    for box in boxes:
        objects_mask = exclude_scaling_box(
            objects_mask,
            box,
            orig_size,
            processed_size,
            expansion_factor=1.2,
        )

    objects_mask = resize_img(objects_mask, (image.shape[1], image.shape[0]))

    offset_pixels = (float(offset) / scaling_factor) * 2 + 1 if scaling_factor else 1
    dilated_mask = cv2.dilate(objects_mask, np.ones((int(offset_pixels), int(offset_pixels)), np.uint8))
    Image.fromarray(dilated_mask).save("./outputs/scaled_mask_original.jpg")
    dilated_mask_orig = dilated_mask.copy()

    #if edge_radius > 0:
        # Use morphological rounding instead of contour-based
    rounded_mask = round_edges(objects_mask, edge_radius, scaling_factor)
    #else:
        #rounded_mask = objects_mask.copy()
    
    # Apply dilation AFTER rounding
    offset_pixels = (float(offset) / scaling_factor) * 2 + 1 if scaling_factor else 1
    kernel = np.ones((int(offset_pixels), int(offset_pixels)), np.uint8)
    dilated_mask = cv2.dilate(rounded_mask, kernel)
    
    

    outlines, contours = extract_outlines(dilated_mask)

    try:
        dxf, finger_polygons, original_polygons = save_dxf_spline(
            contours,
            scaling_factor,
            processed_size[0],
            finger_clearance=(finger_clearance == "On")
        )
    except FingerCutOverlapError as e:
        raise gr.Error(str(e))

    shrunked_img_contours = image.copy()

    if finger_clearance == "On":
        outlines = np.full_like(dilated_mask, 255)
        for poly in finger_polygons:
            try:
                coords = np.array([
                    (int(x / scaling_factor), int(processed_size[0] - y / scaling_factor))
                    for x, y in poly.exterior.coords
                ], np.int32).reshape((-1, 1, 2))

                cv2.drawContours(shrunked_img_contours, [coords], -1, 0, thickness=2)
                cv2.drawContours(outlines, [coords], -1, 0, thickness=2)
            except Exception as e:
                logger.warning(f"Failed to draw finger cut: {e}")
                continue
    else:
        outlines = np.full_like(dilated_mask, 255)
        cv2.drawContours(shrunked_img_contours, contours, -1, 0, thickness=2)
        cv2.drawContours(outlines, contours, -1, 0, thickness=2)
    cleanup_models()

    return (
    shrunked_img_contours,
    outlines,
    dxf,
    dilated_mask_orig,
    f"{scaling_factor:.4f}")


def predict_simple(image):
    """
    Only image in → returns (annotated, outlines, dxf, mask).
    Uses offset=0 mm, no fillet, no finger-cut.
    """
    ann, outlines, dxf_path, mask, _ = predict_og(
        image,
        offset=0,
        offset_unit="mm",
        edge_radius=0,
        finger_clearance="Off",
    )
    return ann, outlines, dxf_path, mask

def predict_middle(image, enable_fillet, fillet_value_mm):
    """
    image + (On/Off) fillet toggle + fillet radius → returns (annotated, outlines, dxf, mask).
    Uses offset=0 mm, finger-cut off.
    """
    radius = fillet_value_mm if enable_fillet == "On" else 0
    ann, outlines, dxf_path, mask, _ = predict_og(
        image,
        offset=0,
        offset_unit="mm",
        edge_radius=radius,
        finger_clearance="Off",
    )
    return ann, outlines, dxf_path, mask

def predict_full(image, enable_fillet, fillet_value_mm, enable_finger_cut):
    """
    image + fillet toggle/value + finger-cut toggle → returns (annotated, outlines, dxf, mask).
    Uses offset=0 mm.
    """
    radius = fillet_value_mm if enable_fillet == "On" else 0
    finger_flag = "On" if enable_finger_cut == "On" else "Off"
    ann, outlines, dxf_path, mask, _ = predict_og(
        image,
        offset=0,
        offset_unit="mm",
        edge_radius=radius,
        finger_clearance=finger_flag,
    )
    return ann, outlines, dxf_path, mask



if __name__ == "__main__":
    os.makedirs("./outputs", exist_ok=True)

    with gr.Blocks() as demo:
        input_image = gr.Image(label="Input Image", type="numpy")

        enable_fillet = gr.Radio(
            choices=["On", "Off"],
            value="Off",
            label="Enable Fillet",
            interactive=True
        )

        fillet_value_mm = gr.Slider(
            minimum=0,
            maximum=20,
            step=1,
            value=5,
            label="Edge Radius (mm)",
            visible=False,
            interactive=True
        )

        enable_finger_cut = gr.Radio(
            choices=["On", "Off"],
            value="Off",
            label="Enable Finger Cut"
        )
        
        def toggle_fillet(choice):
            if choice == "On":
                return gr.update(visible=True)
            return gr.update(visible=False, value=0)

        enable_fillet.change(
            fn=toggle_fillet,
            inputs=enable_fillet,
            outputs=fillet_value_mm
        )
                
        output_image = gr.Image(label="Output Image")
        outlines = gr.Image(label="Outlines of Objects")
        dxf_file = gr.File(label="DXF file")
        mask = gr.Image(label="Mask")

        submit_btn = gr.Button("Submit")
        
        
        submit_btn.click(
            fn=predict_full,
            inputs=[input_image, enable_fillet, fillet_value_mm, enable_finger_cut],
            outputs=[output_image, outlines, dxf_file, mask]
        )

    demo.launch(share=True)