File size: 85,258 Bytes
aa27275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "T4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU",
    "widgets": {
      "application/vnd.jupyter.widget-state+json": {
        "f288b0483e30432ca828f6a8fa83c170": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HBoxModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HBoxModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HBoxView",
            "box_style": "",
            "children": [
              "IPY_MODEL_24d4f3354a1e4cb595178f6c2a3d9184",
              "IPY_MODEL_12c0bac81f6c433597b9049d65ef3622",
              "IPY_MODEL_dc4e853706a841e4bb9116367a941777"
            ],
            "layout": "IPY_MODEL_3891ce65fe8644ec9613c56d95bace7f"
          }
        },
        "24d4f3354a1e4cb595178f6c2a3d9184": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_b790751bb9284c91920ac87606388ca9",
            "placeholder": "​",
            "style": "IPY_MODEL_484383d87bdc4126bf966a94f68aff93",
            "value": "Map: 100%"
          }
        },
        "12c0bac81f6c433597b9049d65ef3622": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "FloatProgressModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "FloatProgressModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "ProgressView",
            "bar_style": "success",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_99781a5386464804af0c5e1b9d6c57f6",
            "max": 700,
            "min": 0,
            "orientation": "horizontal",
            "style": "IPY_MODEL_f66bac73f7fb487bad105ba35f5d5e2a",
            "value": 700
          }
        },
        "dc4e853706a841e4bb9116367a941777": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "HTMLModel",
          "model_module_version": "1.5.0",
          "state": {
            "_dom_classes": [],
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "HTMLModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/controls",
            "_view_module_version": "1.5.0",
            "_view_name": "HTMLView",
            "description": "",
            "description_tooltip": null,
            "layout": "IPY_MODEL_1346c30a4e334dd9a153ab10b1fff76a",
            "placeholder": "​",
            "style": "IPY_MODEL_8212317092c04d118da6c8f5c623906d",
            "value": " 700/700 [00:03<00:00, 200.98 examples/s]"
          }
        },
        "3891ce65fe8644ec9613c56d95bace7f": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "b790751bb9284c91920ac87606388ca9": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "484383d87bdc4126bf966a94f68aff93": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        },
        "99781a5386464804af0c5e1b9d6c57f6": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "f66bac73f7fb487bad105ba35f5d5e2a": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "ProgressStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "ProgressStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "bar_color": null,
            "description_width": ""
          }
        },
        "1346c30a4e334dd9a153ab10b1fff76a": {
          "model_module": "@jupyter-widgets/base",
          "model_name": "LayoutModel",
          "model_module_version": "1.2.0",
          "state": {
            "_model_module": "@jupyter-widgets/base",
            "_model_module_version": "1.2.0",
            "_model_name": "LayoutModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "LayoutView",
            "align_content": null,
            "align_items": null,
            "align_self": null,
            "border": null,
            "bottom": null,
            "display": null,
            "flex": null,
            "flex_flow": null,
            "grid_area": null,
            "grid_auto_columns": null,
            "grid_auto_flow": null,
            "grid_auto_rows": null,
            "grid_column": null,
            "grid_gap": null,
            "grid_row": null,
            "grid_template_areas": null,
            "grid_template_columns": null,
            "grid_template_rows": null,
            "height": null,
            "justify_content": null,
            "justify_items": null,
            "left": null,
            "margin": null,
            "max_height": null,
            "max_width": null,
            "min_height": null,
            "min_width": null,
            "object_fit": null,
            "object_position": null,
            "order": null,
            "overflow": null,
            "overflow_x": null,
            "overflow_y": null,
            "padding": null,
            "right": null,
            "top": null,
            "visibility": null,
            "width": null
          }
        },
        "8212317092c04d118da6c8f5c623906d": {
          "model_module": "@jupyter-widgets/controls",
          "model_name": "DescriptionStyleModel",
          "model_module_version": "1.5.0",
          "state": {
            "_model_module": "@jupyter-widgets/controls",
            "_model_module_version": "1.5.0",
            "_model_name": "DescriptionStyleModel",
            "_view_count": null,
            "_view_module": "@jupyter-widgets/base",
            "_view_module_version": "1.2.0",
            "_view_name": "StyleView",
            "description_width": ""
          }
        }
      }
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "AVRjhwEW3M7s"
      },
      "outputs": [],
      "source": [
        "import sys\n",
        "PROJECT_PATH = '/content/drive/MyDrive/durable_invoices_dataset_v9_fixed_finalrun'\n",
        "sys.path.append(PROJECT_PATH)"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "os.environ[\"WANDB_DISABLED\"] = \"true\""
      ],
      "metadata": {
        "id": "4KD1SwaF6ur9"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "import json\n",
        "import torch\n",
        "from datasets import load_dataset\n",
        "from transformers import AutoTokenizer, Trainer, TrainingArguments, HfArgumentParser\n",
        "from transformers.data.data_collator import DataCollatorForTokenClassification\n",
        "import numpy as np\n",
        "from seqeval.metrics import classification_report\n",
        "\n",
        "# Import your custom model and its config from the other file\n",
        "from layout_roberta import LayoutRobertaForTokenClassification, RobertaConfig\n",
        "\n",
        "# ===================================================================\n",
        "# 1. CONFIGURATION\n",
        "# ===================================================================\n",
        "class NERConfig:\n",
        "    # --- Paths ---\n",
        "    ANNOTATION_FILE = \"/content/drive/MyDrive/durable_invoices_dataset_v9_fixed_finalrun/layout_ner_annotations.jsonl\"\n",
        "    OUTPUT_DIR = \"/content/drive/MyDrive/durable_invoices_dataset_v9_fixed_finalrun/layout-aware-invoice-ner-model-final\"\n",
        "\n",
        "    # --- Model ---\n",
        "    BASE_MODEL = \"roberta-base\"\n",
        "\n",
        "    # --- Training Hyperparameters ---\n",
        "    LEARNING_RATE = 3e-5\n",
        "    NUM_EPOCHS = 8 # Layout-aware models can learn quickly\n",
        "    BATCH_SIZE = 4 # Adjust based on your memory (4 is a safe start)\n",
        "    WEIGHT_DECAY = 0.01\n",
        "\n",
        "config = NERConfig()\n",
        "\n",
        "# ===================================================================\n",
        "# 2. DATA LOADING AND PREPARATION\n",
        "# ===================================================================\n",
        "print(\"Loading dataset from:\", config.ANNOTATION_FILE)\n",
        "full_dataset = load_dataset(\"json\", data_files=config.ANNOTATION_FILE, split=\"train\")\n",
        "\n",
        "# Create the mapping from tag names to integers\n",
        "tags = sorted(list(set([tag for example in full_dataset for tag in example[\"ner_tags\"]])))\n",
        "tag2id = {tag: i for i, tag in enumerate(tags)}\n",
        "id2tag = {i: tag for tag, i in tag2id.items()}\n",
        "label_names = list(tag2id.keys())\n",
        "\n",
        "print(f\"Found {len(tags)} unique NER tags.\")\n",
        "\n",
        "# Initialize tokenizer. `add_prefix_space` is important for RoBERTa.\n",
        "tokenizer = AutoTokenizer.from_pretrained(config.BASE_MODEL, add_prefix_space=True)\n",
        "\n",
        "def preprocess_data(examples, max_length=512):\n",
        "    \"\"\"\n",
        "    Prepares words, bboxes, and tags for the LayoutRoBERTa model.\n",
        "    \"\"\"\n",
        "    words = examples['words']\n",
        "    boxes = examples['bboxes']\n",
        "    ner_tags = examples['ner_tags']\n",
        "\n",
        "    # Tokenize words, this will handle subword splitting\n",
        "    tokenized_inputs = tokenizer(\n",
        "        words,\n",
        "        truncation=True,\n",
        "        is_split_into_words=True,\n",
        "        padding=\"max_length\",\n",
        "        max_length=max_length\n",
        "    )\n",
        "\n",
        "    labels = []\n",
        "    bboxes_aligned = []\n",
        "    for i, label_sequence in enumerate(ner_tags):\n",
        "        word_ids = tokenized_inputs.word_ids(batch_index=i)\n",
        "        previous_word_idx = None\n",
        "        label_ids = []\n",
        "        bbox_sequence = []\n",
        "\n",
        "        for word_idx in word_ids:\n",
        "            if word_idx is None: # Special token like [CLS], [SEP], [PAD]\n",
        "                label_ids.append(-100)\n",
        "                bbox_sequence.append([0, 0, 0, 0]) # Use a \"null\" bounding box\n",
        "            elif word_idx != previous_word_idx: # First subword of a new word\n",
        "                label_ids.append(tag2id[label_sequence[word_idx]])\n",
        "                bbox_sequence.append(boxes[i][word_idx])\n",
        "            else: # Subsequent subword of the same word\n",
        "                label_ids.append(-100) # Only label the first subword\n",
        "                bbox_sequence.append(boxes[i][word_idx]) # Propagate the bbox\n",
        "            previous_word_idx = word_idx\n",
        "\n",
        "        labels.append(label_ids)\n",
        "        bboxes_aligned.append(bbox_sequence)\n",
        "\n",
        "    tokenized_inputs[\"labels\"] = labels\n",
        "    tokenized_inputs[\"bbox\"] = bboxes_aligned\n",
        "    return tokenized_inputs\n",
        "\n",
        "print(\"Preprocessing dataset...\")\n",
        "processed_dataset = full_dataset.map(preprocess_data, batched=True, remove_columns=full_dataset.column_names)\n",
        "split_dataset = processed_dataset.train_test_split(test_size=0.15, seed=42)\n",
        "train_dataset = split_dataset[\"train\"]\n",
        "eval_dataset = split_dataset[\"test\"]\n",
        "\n",
        "# ===================================================================\n",
        "# 3. METRICS COMPUTATION\n",
        "# ===================================================================\n",
        "def compute_metrics(p):\n",
        "    \"\"\"Computes precision, recall, F1, and accuracy for token classification.\"\"\"\n",
        "    predictions, labels = p\n",
        "    predictions = np.argmax(predictions, axis=2)\n",
        "\n",
        "    # Remove ignored index (-100)\n",
        "    true_predictions = [\n",
        "        [label_names[p] for (p, l) in zip(prediction, label) if l != -100]\n",
        "        for prediction, label in zip(predictions, labels)\n",
        "    ]\n",
        "    true_labels = [\n",
        "        [label_names[l] for (p, l) in zip(prediction, label) if l != -100]\n",
        "        for prediction, label in zip(predictions, labels)\n",
        "    ]\n",
        "\n",
        "    report = classification_report(true_labels, true_predictions, output_dict=True)\n",
        "    return {\n",
        "        \"precision\": report[\"micro avg\"][\"precision\"],\n",
        "        \"recall\": report[\"micro avg\"][\"recall\"],\n",
        "        \"f1\": report[\"micro avg\"][\"f1-score\"],\n",
        "        \"accuracy\": report[\"micro avg\"][\"precision\"], # For seqeval, precision is accuracy\n",
        "    }\n",
        "\n",
        "# ===================================================================\n",
        "# 4. MODEL TRAINING\n",
        "# ===================================================================\n",
        "# Data collator handles dynamic padding for batches\n",
        "data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)\n",
        "\n",
        "# Load the custom config and add our layout-specific parameters\n",
        "model_config = RobertaConfig.from_pretrained(\n",
        "    config.BASE_MODEL,\n",
        "    num_labels=len(tags),\n",
        "    id2label=id2tag,\n",
        "    label2id=tag2id\n",
        ")\n",
        "model_config.max_2d_position_embeddings = 1024 # Assumes coordinates are normalized to [0, 1000]\n",
        "\n",
        "# Instantiate our custom model\n",
        "# `ignore_mismatched_sizes=True` is crucial because we are replacing the embedding layer.\n",
        "model = LayoutRobertaForTokenClassification.from_pretrained(\n",
        "    config.BASE_MODEL,\n",
        "    config=model_config,\n",
        "    ignore_mismatched_sizes=True\n",
        ")\n",
        "\n",
        "training_args = TrainingArguments(\n",
        "    output_dir=config.OUTPUT_DIR,\n",
        "    learning_rate=config.LEARNING_RATE,\n",
        "    per_device_train_batch_size=config.BATCH_SIZE,\n",
        "    per_device_eval_batch_size=config.BATCH_SIZE,\n",
        "    num_train_epochs=config.NUM_EPOCHS,\n",
        "    weight_decay=config.WEIGHT_DECAY,\n",
        "    evaluation_strategy=\"epoch\",\n",
        "    save_strategy=\"epoch\",\n",
        "    load_best_model_at_end=True, # Automatically save the best model\n",
        "    metric_for_best_model=\"f1\",\n",
        "    push_to_hub=False,\n",
        "    logging_steps=20,\n",
        "    save_total_limit=1, # Only keep the best checkpoint\n",
        ")\n",
        "\n",
        "trainer = Trainer(\n",
        "    model=model,\n",
        "    args=training_args,\n",
        "    train_dataset=train_dataset,\n",
        "    eval_dataset=eval_dataset,\n",
        "    tokenizer=tokenizer,\n",
        "    data_collator=data_collator,\n",
        "    compute_metrics=compute_metrics, # Add our metrics function\n",
        ")\n",
        "\n",
        "print(\"Starting Layout-Aware NER model training...\")\n",
        "trainer.train()\n",
        "\n",
        "# Save the final best model to a clean directory\n",
        "final_model_path = os.path.join(config.OUTPUT_DIR, \"best_model\")\n",
        "trainer.save_model(final_model_path)\n",
        "print(f\"βœ“ Training complete! Best model saved to: {final_model_path}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000,
          "referenced_widgets": [
            "f288b0483e30432ca828f6a8fa83c170",
            "24d4f3354a1e4cb595178f6c2a3d9184",
            "12c0bac81f6c433597b9049d65ef3622",
            "dc4e853706a841e4bb9116367a941777",
            "3891ce65fe8644ec9613c56d95bace7f",
            "b790751bb9284c91920ac87606388ca9",
            "484383d87bdc4126bf966a94f68aff93",
            "99781a5386464804af0c5e1b9d6c57f6",
            "f66bac73f7fb487bad105ba35f5d5e2a",
            "1346c30a4e334dd9a153ab10b1fff76a",
            "8212317092c04d118da6c8f5c623906d"
          ]
        },
        "id": "ygc3ibH03xQA",
        "outputId": "34d5400f-fd6a-42d8-d364-8983ed6e0963"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.12/dist-packages/transformers/utils/generic.py:441: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead.\n",
            "  _torch_pytree._register_pytree_node(\n",
            "/usr/local/lib/python3.12/dist-packages/transformers/utils/generic.py:309: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead.\n",
            "  _torch_pytree._register_pytree_node(\n",
            "/usr/local/lib/python3.12/dist-packages/transformers/utils/generic.py:309: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead.\n",
            "  _torch_pytree._register_pytree_node(\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Loading dataset from: /content/drive/MyDrive/durable_invoices_dataset_v9_fixed_finalrun/layout_ner_annotations.jsonl\n",
            "Found 26 unique NER tags.\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.12/dist-packages/huggingface_hub/file_download.py:942: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.\n",
            "  warnings.warn(\n",
            "/usr/local/lib/python3.12/dist-packages/huggingface_hub/utils/_auth.py:94: UserWarning: \n",
            "The secret `HF_TOKEN` does not exist in your Colab secrets.\n",
            "To authenticate with the Hugging Face Hub, create a token in your settings tab (https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session.\n",
            "You will be able to reuse this secret in all of your notebooks.\n",
            "Please note that authentication is recommended but still optional to access public models or datasets.\n",
            "  warnings.warn(\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Preprocessing dataset...\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "Map:   0%|          | 0/700 [00:00<?, ? examples/s]"
            ],
            "application/vnd.jupyter.widget-view+json": {
              "version_major": 2,
              "version_minor": 0,
              "model_id": "f288b0483e30432ca828f6a8fa83c170"
            }
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "Some weights of LayoutRobertaForTokenClassification were not initialized from the model checkpoint at roberta-base and are newly initialized: ['roberta.embeddings.y0_position_embeddings.weight', 'roberta.embeddings.x0_position_embeddings.weight', 'classifier.bias', 'classifier.weight', 'roberta.embeddings.y1_position_embeddings.weight', 'roberta.embeddings.x1_position_embeddings.weight']\n",
            "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n",
            "Using the `WANDB_DISABLED` environment variable is deprecated and will be removed in v5. Use the --report_to flag to control the integrations used for logging result (for instance --report_to none).\n",
            "/usr/local/lib/python3.12/dist-packages/accelerate/accelerator.py:432: FutureWarning: Passing the following arguments to `Accelerator` is deprecated and will be removed in version 1.0 of Accelerate: dict_keys(['dispatch_batches', 'split_batches']). Please pass an `accelerate.DataLoaderConfiguration` instead: \n",
            "dataloader_config = DataLoaderConfiguration(dispatch_batches=None, split_batches=False)\n",
            "  warnings.warn(\n",
            "You're using a RobertaTokenizerFast tokenizer. Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the text followed by a call to the `pad` method to get a padded encoding.\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Starting Layout-Aware NER model training...\n"
          ]
        },
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ],
            "text/html": [
              "\n",
              "    <div>\n",
              "      \n",
              "      <progress value='1192' max='1192' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
              "      [1192/1192 10:53, Epoch 8/8]\n",
              "    </div>\n",
              "    <table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              " <tr style=\"text-align: left;\">\n",
              "      <th>Epoch</th>\n",
              "      <th>Training Loss</th>\n",
              "      <th>Validation Loss</th>\n",
              "      <th>Precision</th>\n",
              "      <th>Recall</th>\n",
              "      <th>F1</th>\n",
              "      <th>Accuracy</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <td>1</td>\n",
              "      <td>0.064600</td>\n",
              "      <td>0.058615</td>\n",
              "      <td>0.956479</td>\n",
              "      <td>0.968291</td>\n",
              "      <td>0.962349</td>\n",
              "      <td>0.956479</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>2</td>\n",
              "      <td>0.029700</td>\n",
              "      <td>0.015070</td>\n",
              "      <td>0.993336</td>\n",
              "      <td>0.994993</td>\n",
              "      <td>0.994164</td>\n",
              "      <td>0.993336</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>3</td>\n",
              "      <td>0.016100</td>\n",
              "      <td>0.010866</td>\n",
              "      <td>0.994337</td>\n",
              "      <td>0.996328</td>\n",
              "      <td>0.995332</td>\n",
              "      <td>0.994337</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>4</td>\n",
              "      <td>0.009300</td>\n",
              "      <td>0.009888</td>\n",
              "      <td>0.995336</td>\n",
              "      <td>0.997330</td>\n",
              "      <td>0.996332</td>\n",
              "      <td>0.995336</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>5</td>\n",
              "      <td>0.005500</td>\n",
              "      <td>0.009936</td>\n",
              "      <td>0.995670</td>\n",
              "      <td>0.997664</td>\n",
              "      <td>0.996666</td>\n",
              "      <td>0.995670</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>6</td>\n",
              "      <td>0.006200</td>\n",
              "      <td>0.008643</td>\n",
              "      <td>0.996335</td>\n",
              "      <td>0.997997</td>\n",
              "      <td>0.997165</td>\n",
              "      <td>0.996335</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>7</td>\n",
              "      <td>0.004200</td>\n",
              "      <td>0.008044</td>\n",
              "      <td>0.996003</td>\n",
              "      <td>0.997997</td>\n",
              "      <td>0.996999</td>\n",
              "      <td>0.996003</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>8</td>\n",
              "      <td>0.001400</td>\n",
              "      <td>0.008021</td>\n",
              "      <td>0.996336</td>\n",
              "      <td>0.998331</td>\n",
              "      <td>0.997332</td>\n",
              "      <td>0.996336</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table><p>"
            ]
          },
          "metadata": {}
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "βœ“ Training complete! Best model saved to: /content/drive/MyDrive/durable_invoices_dataset_v9_fixed_finalrun/layout-aware-invoice-ner-model-final/best_model\n",
            "\n",
            "--- RUNNING A QUICK INFERENCE EXAMPLE ---\n",
            "Running model prediction...\n"
          ]
        },
        {
          "output_type": "error",
          "ename": "RuntimeError",
          "evalue": "Expected all tensors to be on the same device, but got index is on cpu, different from other tensors on cuda:0 (when checking argument in method wrapper_CUDA__index_select)",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mRuntimeError\u001b[0m                              Traceback (most recent call last)",
            "\u001b[0;32m/tmp/ipython-input-4013341825.py\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m    197\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Running model prediction...\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    198\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mno_grad\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 199\u001b[0;31m     \u001b[0moutputs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmodel\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m**\u001b[0m\u001b[0minputs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    200\u001b[0m     \u001b[0mpredictions\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0margmax\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0moutputs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlogits\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdim\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    201\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_wrapped_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m   1771\u001b[0m             \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_compiled_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m  \u001b[0;31m# type: ignore[misc]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1772\u001b[0m         \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1773\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1774\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1775\u001b[0m     \u001b[0;31m# torchrec tests the code consistency with the following code\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m   1782\u001b[0m                 \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_pre_hooks\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_hooks\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1783\u001b[0m                 or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1784\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1785\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1786\u001b[0m         \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/content/drive/MyDrive/durable_invoices_dataset_v9_fixed_finalrun/layout_roberta.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input_ids, bbox, attention_mask, token_type_ids, position_ids, head_mask, inputs_embeds, labels, output_attentions, output_hidden_states, return_dict)\u001b[0m\n\u001b[1;32m    171\u001b[0m     ):\n\u001b[1;32m    172\u001b[0m         \u001b[0;31m# Call the forward pass of our custom LayoutRobertaModel\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 173\u001b[0;31m         outputs = self.roberta(\n\u001b[0m\u001b[1;32m    174\u001b[0m             \u001b[0minput_ids\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    175\u001b[0m             \u001b[0mbbox\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mbbox\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_wrapped_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m   1771\u001b[0m             \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_compiled_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m  \u001b[0;31m# type: ignore[misc]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1772\u001b[0m         \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1773\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1774\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1775\u001b[0m     \u001b[0;31m# torchrec tests the code consistency with the following code\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m   1782\u001b[0m                 \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_pre_hooks\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_hooks\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1783\u001b[0m                 or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1784\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1785\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1786\u001b[0m         \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/content/drive/MyDrive/durable_invoices_dataset_v9_fixed_finalrun/layout_roberta.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input_ids, bbox, attention_mask, token_type_ids, position_ids, head_mask, inputs_embeds, output_attentions, output_hidden_states, return_dict)\u001b[0m\n\u001b[1;32m    101\u001b[0m         \u001b[0;31m# Generate embeddings using our custom embedding layer\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    102\u001b[0m         \u001b[0;32mif\u001b[0m \u001b[0minputs_embeds\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 103\u001b[0;31m             embedding_output = self.embeddings(\n\u001b[0m\u001b[1;32m    104\u001b[0m                 \u001b[0minput_ids\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0minput_ids\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    105\u001b[0m                 \u001b[0mbbox\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mbbox\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_wrapped_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m   1771\u001b[0m             \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_compiled_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m  \u001b[0;31m# type: ignore[misc]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1772\u001b[0m         \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1773\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1774\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1775\u001b[0m     \u001b[0;31m# torchrec tests the code consistency with the following code\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m   1782\u001b[0m                 \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_pre_hooks\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_hooks\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1783\u001b[0m                 or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1784\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1785\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1786\u001b[0m         \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/content/drive/MyDrive/durable_invoices_dataset_v9_fixed_finalrun/layout_roberta.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input_ids, bbox, token_type_ids, position_ids)\u001b[0m\n\u001b[1;32m     53\u001b[0m         \u001b[0;31m# --- Get Embeddings ---\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     54\u001b[0m         \u001b[0;31m# 1. Word embeddings from token IDs\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 55\u001b[0;31m         \u001b[0mword_embeds\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mword_embeddings\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput_ids\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     56\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     57\u001b[0m         \u001b[0;31m# 2. 1D Position embeddings\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_wrapped_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m   1771\u001b[0m             \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_compiled_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m  \u001b[0;31m# type: ignore[misc]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1772\u001b[0m         \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1773\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1774\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1775\u001b[0m     \u001b[0;31m# torchrec tests the code consistency with the following code\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m   1782\u001b[0m                 \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_pre_hooks\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_hooks\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1783\u001b[0m                 or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1784\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1785\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1786\u001b[0m         \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/torch/nn/modules/sparse.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input)\u001b[0m\n\u001b[1;32m    190\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    191\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 192\u001b[0;31m         return F.embedding(\n\u001b[0m\u001b[1;32m    193\u001b[0m             \u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    194\u001b[0m             \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.12/dist-packages/torch/nn/functional.py\u001b[0m in \u001b[0;36membedding\u001b[0;34m(input, weight, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse)\u001b[0m\n\u001b[1;32m   2544\u001b[0m         \u001b[0;31m# remove once script supports set_grad_enabled\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   2545\u001b[0m         \u001b[0m_no_grad_embedding_renorm_\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmax_norm\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnorm_type\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 2546\u001b[0;31m     \u001b[0;32mreturn\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0membedding\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpadding_idx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mscale_grad_by_freq\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0msparse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   2547\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   2548\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;31mRuntimeError\u001b[0m: Expected all tensors to be on the same device, but got index is on cpu, different from other tensors on cuda:0 (when checking argument in method wrapper_CUDA__index_select)"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# ===================================================================\n",
        "# 5. INFERENCE EXAMPLE\n",
        "# ===================================================================\n",
        "print(\"\\n--- RUNNING A QUICK INFERENCE EXAMPLE ---\")\n",
        "\n",
        "# Get the device the model is on\n",
        "device = model.device\n",
        "\n",
        "# Get an example from the evaluation dataset\n",
        "example = eval_dataset[0]\n",
        "words = tokenizer.convert_ids_to_tokens(example['input_ids'])\n",
        "bboxes = example['bbox']\n",
        "\n",
        "# Manually prepare inputs and move them to the same device as the model\n",
        "inputs = {\n",
        "    \"input_ids\": torch.tensor([example['input_ids']]).to(device),\n",
        "    \"attention_mask\": torch.tensor([example['attention_mask']]).to(device),\n",
        "    \"bbox\": torch.tensor([example['bbox']]).to(device),\n",
        "    \"return_dict\": True  # Force return_dict to True\n",
        "}\n",
        "\n",
        "print(\"Running model prediction...\")\n",
        "model.eval()  # Set model to evaluation mode\n",
        "with torch.no_grad():\n",
        "    outputs = model(**inputs)\n",
        "    # Handle both tuple and dict outputs\n",
        "    if isinstance(outputs, tuple):\n",
        "        logits = outputs[0]  # First element is logits\n",
        "    else:\n",
        "        logits = outputs.logits\n",
        "    predictions = torch.argmax(logits, dim=2)\n",
        "\n",
        "print(\"\\n--- PARSED ENTITIES (EXAMPLE) ---\")\n",
        "predicted_labels = predictions[0].cpu().tolist()  # Move predictions back to CPU\n",
        "true_labels = example['labels']\n",
        "\n",
        "for token, pred_id, true_label_id in zip(words, predicted_labels, true_labels):\n",
        "    if token not in [tokenizer.bos_token, tokenizer.eos_token, tokenizer.pad_token]:\n",
        "        if true_label_id != -100:  # Skip padding tokens\n",
        "            predicted_label = id2tag[pred_id]\n",
        "            true_label = id2tag[true_label_id]\n",
        "            match = \"βœ“\" if predicted_label == true_label else \"βœ—\"\n",
        "            if predicted_label != 'O' or true_label != 'O':  # Only show non-O tags\n",
        "                print(f\"{match} Token: {token:15s} | Predicted: {predicted_label:20s} | True: {true_label}\")\n",
        "\n",
        "print(\"\\nβœ“ Inference example complete!\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Vtnhqy0n4ZcJ",
        "outputId": "089d8d3e-f2e1-4881-d668-9672240f2913"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "--- RUNNING A QUICK INFERENCE EXAMPLE ---\n",
            "Running model prediction...\n",
            "\n",
            "--- PARSED ENTITIES (EXAMPLE) ---\n",
            "βœ“ Token: Δ 25             | Predicted: B-INV_NO             | True: B-INV_NO\n",
            "βœ“ Token: Δ S              | Predicted: B-SELLER_NAME        | True: B-SELLER_NAME\n",
            "βœ“ Token: Δ ELECT          | Predicted: I-SELLER_NAME        | True: I-SELLER_NAME\n",
            "βœ“ Token: Δ 16             | Predicted: B-DATE               | True: B-DATE\n",
            "βœ“ Token: Δ 05             | Predicted: B-SELLER_ADDR        | True: B-SELLER_ADDR\n",
            "βœ“ Token: Δ Moh            | Predicted: I-SELLER_ADDR        | True: I-SELLER_ADDR\n",
            "βœ“ Token: Δ Road           | Predicted: I-SELLER_ADDR        | True: I-SELLER_ADDR\n",
            "βœ“ Token: Δ Haj            | Predicted: I-SELLER_ADDR        | True: I-SELLER_ADDR\n",
            "βœ“ Token: Δ 06             | Predicted: B-SELLER_TAX_ID      | True: B-SELLER_TAX_ID\n",
            "βœ“ Token: Δ R              | Predicted: B-CLIENT_NAME        | True: B-CLIENT_NAME\n",
            "βœ“ Token: Δ NAD            | Predicted: I-CLIENT_NAME        | True: I-CLIENT_NAME\n",
            "βœ“ Token: Δ H              | Predicted: B-CLIENT_ADDR        | True: B-CLIENT_ADDR\n",
            "βœ“ Token: Δ 7              | Predicted: I-CLIENT_ADDR        | True: I-CLIENT_ADDR\n",
            "βœ“ Token: Δ Bo             | Predicted: I-CLIENT_ADDR        | True: I-CLIENT_ADDR\n",
            "βœ“ Token: Δ Nag            | Predicted: I-CLIENT_ADDR        | True: I-CLIENT_ADDR\n",
            "βœ“ Token: Δ Bh             | Predicted: I-CLIENT_ADDR        | True: I-CLIENT_ADDR\n",
            "βœ“ Token: Δ 6              | Predicted: B-CLIENT_PHONE       | True: B-CLIENT_PHONE\n",
            "βœ“ Token: Δ 31             | Predicted: B-CLIENT_TAX_ID      | True: B-CLIENT_TAX_ID\n",
            "βœ“ Token: Δ B              | Predicted: B-ITEM_DESC          | True: B-ITEM_DESC\n",
            "βœ“ Token: Δ Speaker        | Predicted: I-ITEM_DESC          | True: I-ITEM_DESC\n",
            "βœ“ Token: Δ Model          | Predicted: I-ITEM_DESC          | True: I-ITEM_DESC\n",
            "βœ“ Token: Δ B              | Predicted: I-ITEM_DESC          | True: I-ITEM_DESC\n",
            "βœ“ Token: Δ 85             | Predicted: B-ITEM_HSN           | True: B-ITEM_HSN\n",
            "βœ“ Token: Δ 2              | Predicted: B-ITEM_QTY           | True: B-ITEM_QTY\n",
            "βœ“ Token: Δ 50             | Predicted: B-ITEM_PRICE         | True: B-ITEM_PRICE\n",
            "βœ“ Token: Δ 100            | Predicted: B-ITEM_AMOUNT        | True: B-ITEM_AMOUNT\n",
            "βœ“ Token: Δ TV             | Predicted: B-ITEM_DESC          | True: B-ITEM_DESC\n",
            "βœ“ Token: Δ Bike           | Predicted: I-ITEM_DESC          | True: I-ITEM_DESC\n",
            "βœ“ Token: Δ 2              | Predicted: B-ITEM_QTY           | True: B-ITEM_QTY\n",
            "βœ“ Token: Δ Model          | Predicted: I-ITEM_DESC          | True: I-ITEM_DESC\n",
            "βœ“ Token: Δ TV             | Predicted: I-ITEM_DESC          | True: I-ITEM_DESC\n",
            "βœ“ Token: Δ 87             | Predicted: B-ITEM_HSN           | True: B-ITEM_HSN\n",
            "βœ“ Token: Δ 1              | Predicted: B-ITEM_QTY           | True: B-ITEM_QTY\n",
            "βœ“ Token: Δ 66             | Predicted: B-ITEM_PRICE         | True: B-ITEM_PRICE\n",
            "βœ“ Token: Δ 66             | Predicted: B-ITEM_PRICE         | True: B-ITEM_PRICE\n",
            "βœ“ Token: Δ Nikon          | Predicted: B-ITEM_DESC          | True: B-ITEM_DESC\n",
            "βœ“ Token: Δ Camera         | Predicted: I-ITEM_DESC          | True: I-ITEM_DESC\n",
            "βœ“ Token: Δ Model          | Predicted: I-ITEM_DESC          | True: I-ITEM_DESC\n",
            "βœ“ Token: Δ N              | Predicted: I-ITEM_DESC          | True: I-ITEM_DESC\n",
            "βœ“ Token: Δ 85             | Predicted: B-ITEM_HSN           | True: B-ITEM_HSN\n",
            "βœ“ Token: Δ 1              | Predicted: B-ITEM_QTY           | True: B-ITEM_QTY\n",
            "βœ“ Token: Δ 60             | Predicted: B-ITEM_PRICE         | True: B-ITEM_PRICE\n",
            "βœ“ Token: Δ 60             | Predicted: B-ITEM_PRICE         | True: B-ITEM_PRICE\n",
            "βœ“ Token: Δ 227            | Predicted: B-SUBTOTAL           | True: B-SUBTOTAL\n",
            "βœ“ Token: Δ 13             | Predicted: B-CGST               | True: B-CGST\n",
            "βœ“ Token: Δ 13             | Predicted: B-CGST               | True: B-CGST\n",
            "βœ“ Token: Δ 255            | Predicted: B-TOTAL              | True: B-TOTAL\n",
            "\n",
            "βœ“ Inference example complete!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install paddlepaddle-gpu==2.6.2 paddleocr==2.10.0"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "8neo7QNT-Su1",
        "outputId": "1c7b0cf5-48fe-4986-b4af-deff9d0b01bf"
      },
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Collecting paddlepaddle-gpu==2.6.2\n",
            "  Downloading paddlepaddle_gpu-2.6.2-cp312-cp312-manylinux1_x86_64.whl.metadata (8.6 kB)\n",
            "Collecting paddleocr==2.10.0\n",
            "  Downloading paddleocr-2.10.0-py3-none-any.whl.metadata (12 kB)\n",
            "Requirement already satisfied: httpx in /usr/local/lib/python3.12/dist-packages (from paddlepaddle-gpu==2.6.2) (0.28.1)\n",
            "Requirement already satisfied: numpy>=1.13 in /usr/local/lib/python3.12/dist-packages (from paddlepaddle-gpu==2.6.2) (2.0.2)\n",
            "Requirement already satisfied: Pillow in /usr/local/lib/python3.12/dist-packages (from paddlepaddle-gpu==2.6.2) (11.3.0)\n",
            "Requirement already satisfied: decorator in /usr/local/lib/python3.12/dist-packages (from paddlepaddle-gpu==2.6.2) (4.4.2)\n",
            "Collecting astor (from paddlepaddle-gpu==2.6.2)\n",
            "  Downloading astor-0.8.1-py2.py3-none-any.whl.metadata (4.2 kB)\n",
            "Collecting opt-einsum==3.3.0 (from paddlepaddle-gpu==2.6.2)\n",
            "  Downloading opt_einsum-3.3.0-py3-none-any.whl.metadata (6.5 kB)\n",
            "Requirement already satisfied: protobuf>=3.20.2 in /usr/local/lib/python3.12/dist-packages (from paddlepaddle-gpu==2.6.2) (5.29.5)\n",
            "Requirement already satisfied: shapely in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (2.1.2)\n",
            "Requirement already satisfied: scikit-image in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (0.25.2)\n",
            "Collecting pyclipper (from paddleocr==2.10.0)\n",
            "  Downloading pyclipper-1.3.0.post6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (9.0 kB)\n",
            "Collecting lmdb (from paddleocr==2.10.0)\n",
            "  Downloading lmdb-1.7.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.metadata (1.4 kB)\n",
            "Requirement already satisfied: tqdm in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (4.67.1)\n",
            "Collecting rapidfuzz (from paddleocr==2.10.0)\n",
            "  Downloading rapidfuzz-3.14.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (12 kB)\n",
            "Requirement already satisfied: opencv-python in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (4.12.0.88)\n",
            "Requirement already satisfied: opencv-contrib-python in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (4.12.0.88)\n",
            "Requirement already satisfied: cython in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (3.0.12)\n",
            "Requirement already satisfied: pyyaml in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (6.0.3)\n",
            "Collecting python-docx (from paddleocr==2.10.0)\n",
            "  Downloading python_docx-1.2.0-py3-none-any.whl.metadata (2.0 kB)\n",
            "Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (4.13.5)\n",
            "Requirement already satisfied: fonttools>=4.24.0 in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (4.60.1)\n",
            "Collecting fire>=0.3.0 (from paddleocr==2.10.0)\n",
            "  Downloading fire-0.7.1-py3-none-any.whl.metadata (5.8 kB)\n",
            "Requirement already satisfied: requests in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (2.32.4)\n",
            "Requirement already satisfied: albumentations in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (2.0.8)\n",
            "Requirement already satisfied: albucore in /usr/local/lib/python3.12/dist-packages (from paddleocr==2.10.0) (0.0.24)\n",
            "Requirement already satisfied: termcolor in /usr/local/lib/python3.12/dist-packages (from fire>=0.3.0->paddleocr==2.10.0) (3.2.0)\n",
            "Requirement already satisfied: stringzilla>=3.10.4 in /usr/local/lib/python3.12/dist-packages (from albucore->paddleocr==2.10.0) (4.2.3)\n",
            "Requirement already satisfied: simsimd>=5.9.2 in /usr/local/lib/python3.12/dist-packages (from albucore->paddleocr==2.10.0) (6.5.3)\n",
            "Requirement already satisfied: opencv-python-headless>=4.9.0.80 in /usr/local/lib/python3.12/dist-packages (from albucore->paddleocr==2.10.0) (4.12.0.88)\n",
            "Requirement already satisfied: scipy>=1.10.0 in /usr/local/lib/python3.12/dist-packages (from albumentations->paddleocr==2.10.0) (1.16.3)\n",
            "Requirement already satisfied: pydantic>=2.9.2 in /usr/local/lib/python3.12/dist-packages (from albumentations->paddleocr==2.10.0) (2.11.10)\n",
            "Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4->paddleocr==2.10.0) (2.8)\n",
            "Requirement already satisfied: typing-extensions>=4.0.0 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4->paddleocr==2.10.0) (4.15.0)\n",
            "Requirement already satisfied: anyio in /usr/local/lib/python3.12/dist-packages (from httpx->paddlepaddle-gpu==2.6.2) (4.11.0)\n",
            "Requirement already satisfied: certifi in /usr/local/lib/python3.12/dist-packages (from httpx->paddlepaddle-gpu==2.6.2) (2025.10.5)\n",
            "Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.12/dist-packages (from httpx->paddlepaddle-gpu==2.6.2) (1.0.9)\n",
            "Requirement already satisfied: idna in /usr/local/lib/python3.12/dist-packages (from httpx->paddlepaddle-gpu==2.6.2) (3.11)\n",
            "Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.12/dist-packages (from httpcore==1.*->httpx->paddlepaddle-gpu==2.6.2) (0.16.0)\n",
            "Requirement already satisfied: lxml>=3.1.0 in /usr/local/lib/python3.12/dist-packages (from python-docx->paddleocr==2.10.0) (5.4.0)\n",
            "Requirement already satisfied: charset_normalizer<4,>=2 in /usr/local/lib/python3.12/dist-packages (from requests->paddleocr==2.10.0) (3.4.4)\n",
            "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.12/dist-packages (from requests->paddleocr==2.10.0) (2.5.0)\n",
            "Requirement already satisfied: networkx>=3.0 in /usr/local/lib/python3.12/dist-packages (from scikit-image->paddleocr==2.10.0) (3.5)\n",
            "Requirement already satisfied: imageio!=2.35.0,>=2.33 in /usr/local/lib/python3.12/dist-packages (from scikit-image->paddleocr==2.10.0) (2.37.0)\n",
            "Requirement already satisfied: tifffile>=2022.8.12 in /usr/local/lib/python3.12/dist-packages (from scikit-image->paddleocr==2.10.0) (2025.10.16)\n",
            "Requirement already satisfied: packaging>=21 in /usr/local/lib/python3.12/dist-packages (from scikit-image->paddleocr==2.10.0) (25.0)\n",
            "Requirement already satisfied: lazy-loader>=0.4 in /usr/local/lib/python3.12/dist-packages (from scikit-image->paddleocr==2.10.0) (0.4)\n",
            "Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.12/dist-packages (from pydantic>=2.9.2->albumentations->paddleocr==2.10.0) (0.7.0)\n",
            "Requirement already satisfied: pydantic-core==2.33.2 in /usr/local/lib/python3.12/dist-packages (from pydantic>=2.9.2->albumentations->paddleocr==2.10.0) (2.33.2)\n",
            "Requirement already satisfied: typing-inspection>=0.4.0 in /usr/local/lib/python3.12/dist-packages (from pydantic>=2.9.2->albumentations->paddleocr==2.10.0) (0.4.2)\n",
            "Requirement already satisfied: sniffio>=1.1 in /usr/local/lib/python3.12/dist-packages (from anyio->httpx->paddlepaddle-gpu==2.6.2) (1.3.1)\n",
            "Downloading paddlepaddle_gpu-2.6.2-cp312-cp312-manylinux1_x86_64.whl (758.9 MB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m758.9/758.9 MB\u001b[0m \u001b[31m603.1 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hDownloading paddleocr-2.10.0-py3-none-any.whl (2.4 MB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.4/2.4 MB\u001b[0m \u001b[31m92.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hDownloading opt_einsum-3.3.0-py3-none-any.whl (65 kB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m65.5/65.5 kB\u001b[0m \u001b[31m8.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hDownloading fire-0.7.1-py3-none-any.whl (115 kB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m115.9/115.9 kB\u001b[0m \u001b[31m14.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hDownloading astor-0.8.1-py2.py3-none-any.whl (27 kB)\n",
            "Downloading lmdb-1.7.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (299 kB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m299.4/299.4 kB\u001b[0m \u001b[31m28.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hDownloading pyclipper-1.3.0.post6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (963 kB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m963.8/963.8 kB\u001b[0m \u001b[31m68.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hDownloading python_docx-1.2.0-py3-none-any.whl (252 kB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m253.0/253.0 kB\u001b[0m \u001b[31m28.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hDownloading rapidfuzz-3.14.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (3.2 MB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.2/3.2 MB\u001b[0m \u001b[31m101.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hInstalling collected packages: pyclipper, lmdb, rapidfuzz, python-docx, opt-einsum, fire, astor, paddlepaddle-gpu, paddleocr\n",
            "  Attempting uninstall: opt-einsum\n",
            "    Found existing installation: opt_einsum 3.4.0\n",
            "    Uninstalling opt_einsum-3.4.0:\n",
            "      Successfully uninstalled opt_einsum-3.4.0\n",
            "Successfully installed astor-0.8.1 fire-0.7.1 lmdb-1.7.5 opt-einsum-3.3.0 paddleocr-2.10.0 paddlepaddle-gpu-2.6.2 pyclipper-1.3.0.post6 python-docx-1.2.0 rapidfuzz-3.14.3\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "import json\n",
        "import re\n",
        "import torch\n",
        "import numpy as np\n",
        "from PIL import Image\n",
        "from transformers import AutoTokenizer\n",
        "from paddleocr import PaddleOCR\n",
        "from collections import defaultdict\n",
        "import cv2\n",
        "\n",
        "from layout_roberta import LayoutRobertaForTokenClassification, RobertaConfig\n",
        "\n",
        "\n",
        "class InferenceConfig:\n",
        "    MODEL_PATH = r\"/content/drive/MyDrive/durable_invoices_dataset_v9_fixed_finalrun/layout-aware-invoice-ner-model-final/best_model\"\n",
        "\n",
        "    # Path to the new invoice image you want to process\n",
        "    IMAGE_PATH = r\"/content/original-scanned.jpg\"    # Confidence threshold for NER predictions\n",
        "    SCORE_THRESHOLD = 0.85\n",
        "\n",
        "# ===================================================================\n",
        "# 2. HELPER FUNCTIONS (OCR & Post-Processing)\n",
        "# ===================================================================\n",
        "\n",
        "def run_ocr_on_image(image_path: str, ocr_engine: PaddleOCR) -> (list, list, tuple):\n",
        "    \"\"\"\n",
        "    Performs OCR on an image and returns words, normalized bboxes, and image dimensions.\n",
        "    \"\"\"\n",
        "    if not os.path.exists(image_path):\n",
        "        raise FileNotFoundError(f\"Image not found at path: {image_path}\")\n",
        "\n",
        "    words = []\n",
        "    bboxes = []\n",
        "    try:\n",
        "        img = cv2.imread(image_path)\n",
        "        if img is None:\n",
        "            raise IOError(\"Could not read image with OpenCV.\")\n",
        "        img_height, img_width = img.shape[:2]\n",
        "\n",
        "        result = ocr_engine.ocr(img, cls=True)\n",
        "        if not result or not result[0]:\n",
        "            print(\"Warning: OCR did not detect any text.\")\n",
        "            return [], [], (img_width, img_height)\n",
        "\n",
        "        for line in result[0]:\n",
        "            bbox_points, (text, confidence) = line\n",
        "            if confidence < 0.5:\n",
        "                continue\n",
        "\n",
        "            text_words = text.split()\n",
        "            if not text_words:\n",
        "                continue\n",
        "\n",
        "            xs = [p[0] for p in bbox_points]\n",
        "            ys = [p[1] for p in bbox_points]\n",
        "            x0, x1 = min(xs), max(xs)\n",
        "            y0, y1 = min(ys), max(ys)\n",
        "\n",
        "            line_width = x1 - x0\n",
        "            if len(text_words) > 1 and line_width > 0:\n",
        "                word_width_avg = line_width / len(text_words)\n",
        "                for idx, word in enumerate(text_words):\n",
        "                    word_x0 = x0 + (idx * word_width_avg)\n",
        "                    word_x1 = word_x0 + word_width_avg\n",
        "                    norm_bbox = [\n",
        "                        int((word_x0 / img_width) * 1000),\n",
        "                        int((y0 / img_height) * 1000),\n",
        "                        int((word_x1 / img_width) * 1000),\n",
        "                        int((y1 / img_height) * 1000)\n",
        "                    ]\n",
        "                    words.append(word)\n",
        "                    bboxes.append(norm_bbox)\n",
        "            else:\n",
        "                norm_bbox = [\n",
        "                    int((x0 / img_width) * 1000),\n",
        "                    int((y0 / img_height) * 1000),\n",
        "                    int((x1 / img_width) * 1000),\n",
        "                    int((y1 / img_height) * 1000)\n",
        "                ]\n",
        "                words.append(text)\n",
        "                bboxes.append(norm_bbox)\n",
        "\n",
        "    except Exception as e:\n",
        "        print(f\"An error occurred during OCR processing: {e}\")\n",
        "        return [], [], (0, 0)\n",
        "\n",
        "    return words, bboxes, (img_width, img_height)\n",
        "\n",
        "\n",
        "def group_and_clean_entities(ner_results: list, score_threshold: float = 0.85) -> dict:\n",
        "    \"\"\"\n",
        "    The definitive post-processing function.\n",
        "    Cleans, groups, and structures raw NER predictions.\n",
        "    \"\"\"\n",
        "    # Step 1: Group B- and I- tags\n",
        "    grouped_by_tag = []\n",
        "    current_entity = None\n",
        "\n",
        "    for res in ner_results:\n",
        "        if res['score'] < score_threshold:\n",
        "            continue\n",
        "\n",
        "        tag = res['entity']\n",
        "        word = res['word'].replace('Δ ', ' ').strip()\n",
        "\n",
        "        if tag.startswith(\"B-\"):\n",
        "            if current_entity:\n",
        "                grouped_by_tag.append(current_entity)\n",
        "            current_entity = {\"entity_group\": tag[2:], \"value\": word}\n",
        "\n",
        "        elif tag.startswith(\"I-\") and current_entity and tag[2:] == current_entity[\"entity_group\"]:\n",
        "            if word.startswith(' ') or res['word'].startswith('Δ '):\n",
        "                current_entity[\"value\"] += \" \" + word\n",
        "            else:\n",
        "                current_entity[\"value\"] += word\n",
        "        else:\n",
        "            if current_entity:\n",
        "                grouped_by_tag.append(current_entity)\n",
        "            current_entity = None\n",
        "\n",
        "    if current_entity:\n",
        "        grouped_by_tag.append(current_entity)\n",
        "\n",
        "    # Step 2: Aggregate fragments and build the final JSON\n",
        "    aggregated_entities = defaultdict(list)\n",
        "\n",
        "    for entity in grouped_by_tag:\n",
        "        key = entity['entity_group'].lower()\n",
        "        value = entity['value'].strip().lstrip(':').strip()\n",
        "\n",
        "        junk_words = [\n",
        "            \"invoice\", \"no\", \"date\", \"bill\", \"to\", \"ship\", \"ph\", \"gstin\",\n",
        "            \"description\", \"hsn\", \"qty\", \"rate\", \"amount\", \"total\",\n",
        "            \"subtotal\", \"#\", \"@\", \"%\", \":\", \"model\"\n",
        "        ]\n",
        "\n",
        "        if value.lower().strip(': ') in junk_words:\n",
        "            continue\n",
        "\n",
        "        aggregated_entities[key].append(value)\n",
        "\n",
        "    final_json = {}\n",
        "    item_lists = {k: v for k, v in aggregated_entities.items() if k.startswith(\"item_\")}\n",
        "\n",
        "    # Add non-item fields\n",
        "    for key, values in aggregated_entities.items():\n",
        "        if not key.startswith(\"item_\"):\n",
        "            final_json[key] = \" \".join(values)\n",
        "\n",
        "    # Reconstruct line items\n",
        "    num_items = 0\n",
        "    if item_lists:\n",
        "        try:\n",
        "            num_items = max(len(v) for v in item_lists.values())\n",
        "        except ValueError:\n",
        "            num_items = 0\n",
        "\n",
        "    items = []\n",
        "    for i in range(num_items):\n",
        "        item = {}\n",
        "        for key, values in item_lists.items():\n",
        "            if i < len(values):\n",
        "                item_key = key.replace(\"item_\", \"\")\n",
        "                item[item_key] = values[i]\n",
        "        if item:\n",
        "            items.append(item)\n",
        "\n",
        "    if items:\n",
        "        final_json['items'] = items\n",
        "\n",
        "    return final_json\n",
        "\n",
        "\n",
        "# ===================================================================\n",
        "# 3. MAIN INFERENCE PIPELINE\n",
        "# ===================================================================\n",
        "def main():\n",
        "    config = InferenceConfig()\n",
        "    device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
        "\n",
        "    # --- Step 1: Initialize OCR and Model ---\n",
        "    print(\"Initializing PaddleOCR engine...\")\n",
        "    ocr_engine = PaddleOCR(use_angle_cls=True, lang='en')\n",
        "\n",
        "    print(\"Loading fine-tuned Layout-Aware NER model...\")\n",
        "    tokenizer = AutoTokenizer.from_pretrained(config.MODEL_PATH)\n",
        "    model = LayoutRobertaForTokenClassification.from_pretrained(config.MODEL_PATH)\n",
        "    model.to(device)\n",
        "    model.eval()\n",
        "\n",
        "    # --- Step 2: Run OCR on the new image ---\n",
        "    print(\"\\n--- RUNNING OCR ---\")\n",
        "    words, bboxes, (img_w, img_h) = run_ocr_on_image(config.IMAGE_PATH, ocr_engine)\n",
        "\n",
        "    if not words:\n",
        "        print(\"Inference aborted as no text was found in the image.\")\n",
        "        return\n",
        "\n",
        "    print(f\"OCR detected {len(words)} words\")\n",
        "\n",
        "    # --- Step 3: Preprocess data for the model ---\n",
        "    tokenized_inputs = tokenizer(\n",
        "        words,\n",
        "        is_split_into_words=True,\n",
        "        return_tensors=\"pt\",\n",
        "        padding=\"max_length\",\n",
        "        truncation=True,\n",
        "        max_length=512\n",
        "    )\n",
        "\n",
        "    aligned_bboxes = []\n",
        "    word_ids = tokenized_inputs.word_ids()\n",
        "    previous_word_idx = None\n",
        "\n",
        "    for word_idx in word_ids:\n",
        "        if word_idx is None:\n",
        "            aligned_bboxes.append([0, 0, 0, 0])\n",
        "        elif word_idx != previous_word_idx:\n",
        "            aligned_bboxes.append(bboxes[word_idx])\n",
        "        else:\n",
        "            aligned_bboxes.append(bboxes[word_idx])\n",
        "        previous_word_idx = word_idx\n",
        "\n",
        "    # --- Step 4: Run model prediction ---\n",
        "    print(\"\\n--- RUNNING MODEL PREDICTION ---\")\n",
        "    inputs = {\n",
        "        \"input_ids\": tokenized_inputs[\"input_ids\"].to(device),\n",
        "        \"attention_mask\": tokenized_inputs[\"attention_mask\"].to(device),\n",
        "        \"bbox\": torch.tensor([aligned_bboxes]).to(device),\n",
        "        \"return_dict\": True  # Force return_dict\n",
        "    }\n",
        "\n",
        "    with torch.no_grad():\n",
        "        outputs = model(**inputs)\n",
        "        # Handle both tuple and dict outputs\n",
        "        if isinstance(outputs, tuple):\n",
        "            logits = outputs[0]\n",
        "        else:\n",
        "            logits = outputs.logits\n",
        "        predictions = torch.argmax(logits, dim=2)\n",
        "\n",
        "    # --- Step 5: Decode and Post-process the results ---\n",
        "    print(\"\\n--- PARSING ENTITIES ---\")\n",
        "    preds = predictions[0].cpu().tolist()\n",
        "    tokens = tokenizer.convert_ids_to_tokens(tokenized_inputs[\"input_ids\"][0])\n",
        "\n",
        "    raw_results = []\n",
        "    for token, pred_id in zip(tokens, preds):\n",
        "        label = model.config.id2label[pred_id]\n",
        "        if label != \"O\":\n",
        "            raw_results.append({\n",
        "                \"entity\": label,\n",
        "                \"word\": token,\n",
        "                \"score\": 1.0  # Confidence score (could extract from logits if needed)\n",
        "            })\n",
        "\n",
        "    print(f\"Found {len(raw_results)} entity predictions\")\n",
        "\n",
        "    # Post-process and structure the results\n",
        "    final_json = group_and_clean_entities(raw_results, score_threshold=config.SCORE_THRESHOLD)\n",
        "\n",
        "    print(\"\\n\" + \"=\"*60)\n",
        "    print(\"--- FINAL EXTRACTED INVOICE DATA ---\")\n",
        "    print(\"=\"*60)\n",
        "    print(json.dumps(final_json, indent=2))\n",
        "    print(\"=\"*60)\n",
        "    print(\"\\nβœ“ Inference complete!\")\n",
        "\n",
        "if __name__ == '__main__':\n",
        "    main()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VuRchHy9DGcS",
        "outputId": "8a250e8f-21be-4724-97d9-8fc299b9147b"
      },
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Initializing PaddleOCR engine...\n",
            "[2025/11/04 07:02:33] ppocr WARNING: The first GPU is used for inference by default, GPU ID: 0\n",
            "[2025/11/04 07:02:37] ppocr WARNING: The first GPU is used for inference by default, GPU ID: 0\n",
            "[2025/11/04 07:02:41] ppocr WARNING: The first GPU is used for inference by default, GPU ID: 0\n",
            "Loading fine-tuned Layout-Aware NER model...\n",
            "\n",
            "--- RUNNING OCR ---\n",
            "OCR detected 69 words\n",
            "\n",
            "--- RUNNING MODEL PREDICTION ---\n",
            "\n",
            "--- PARSING ENTITIES ---\n",
            "Found 108 entity predictions\n",
            "\n",
            "============================================================\n",
            "--- FINAL EXTRACTED INVOICE DATA ---\n",
            "============================================================\n",
            "{\n",
            "  \"seller_name\": \"NEW FREEZE LAND Club AHMED <pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>\",\n",
            "  \"client_name\": \"MANISHIKA\",\n",
            "  \"inv_no\": \"18 / 0000 15 24 / 76\",\n",
            "  \"client_phone\": \" 76\",\n",
            "  \"date\": \"25 / 8 / 17\",\n",
            "  \"subtotal\": \"257\",\n",
            "  \"total\": \"303\",\n",
            "  \"client_tax_id\": \"GST IN - 24 ABC FM 73 13 D 1 Z Q\",\n",
            "  \"items\": [\n",
            "    {\n",
            "      \"hsn\": \"15\",\n",
            "      \"qty\": \"1\",\n",
            "      \"price\": \"151\",\n",
            "      \"desc\": \"Tortas\"\n",
            "    },\n",
            "    {\n",
            "      \"qty\": \"00\",\n",
            "      \"price\": \"151\",\n",
            "      \"desc\": \"Tortas\"\n",
            "    },\n",
            "    {\n",
            "      \"qty\": \"00\",\n",
            "      \"price\": \"53\"\n",
            "    },\n",
            "    {\n",
            "      \"qty\": \"1\",\n",
            "      \"price\": \"53\"\n",
            "    },\n",
            "    {\n",
            "      \"qty\": \"00\",\n",
            "      \"price\": \"53\"\n",
            "    },\n",
            "    {\n",
            "      \"qty\": \"00\",\n",
            "      \"price\": \"53\"\n",
            "    },\n",
            "    {\n",
            "      \"qty\": \"1\"\n",
            "    },\n",
            "    {\n",
            "      \"qty\": \"00\"\n",
            "    },\n",
            "    {\n",
            "      \"qty\": \"00\"\n",
            "    }\n",
            "  ]\n",
            "}\n",
            "============================================================\n",
            "\n",
            "βœ“ Inference complete!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "o3oX3W08D58s"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}