File size: 78,211 Bytes
33185cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 🧠 HRHUB v2.1 - Enhanced with LLM (FREE VERSION)\n",
    "\n",
    "## πŸ“˜ Project Overview\n",
    "\n",
    "**Bilateral HR Matching System with LLM-Powered Intelligence**\n",
    "\n",
    "### What's New in v2.1:\n",
    "- βœ… **FREE LLM**: Using Hugging Face Inference API (no cost)\n",
    "- βœ… **Job Level Classification**: Zero-shot & few-shot learning\n",
    "- βœ… **Structured Skills Extraction**: Pydantic schemas\n",
    "- βœ… **Match Explainability**: LLM-generated reasoning\n",
    "- βœ… **Flexible Data Loading**: Upload OR Google Drive\n",
    "\n",
    "### Tech Stack:\n",
    "```\n",
    "Embeddings: sentence-transformers (local, free)\n",
    "LLM: Hugging Face Inference API (free tier)\n",
    "Schemas: Pydantic\n",
    "Platform: Google Colab β†’ VS Code\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "**Master's Thesis - Aalborg University**  \n",
    "*Business Data Science Program*  \n",
    "*December 2025*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 1: Install Dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "βœ… All packages installed!\n"
     ]
    }
   ],
   "source": [
    "# Install required packages\n",
    "#!pip install -q sentence-transformers huggingface-hub pydantic plotly pyvis nbformat scikit-learn pandas numpy\n",
    "\n",
    "print(\"βœ… All packages installed!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 2: Import Libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "βœ… Environment variables loaded from .env\n",
      "βœ… All libraries imported!\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import json\n",
    "import os\n",
    "from typing import List, Dict, Optional, Literal\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "# ML & NLP\n",
    "from sentence_transformers import SentenceTransformer\n",
    "from sklearn.metrics.pairwise import cosine_similarity\n",
    "\n",
    "# LLM Integration (FREE)\n",
    "from huggingface_hub import InferenceClient\n",
    "from pydantic import BaseModel, Field\n",
    "\n",
    "# Visualization\n",
    "import plotly.graph_objects as go\n",
    "from IPython.display import HTML, display\n",
    "\n",
    "# Configuration Settings\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "# Carrega variΓ‘veis do .env\n",
    "load_dotenv()\n",
    "print(\"βœ… Environment variables loaded from .env\")\n",
    "# ============== ATΓ‰ AQUI ⬆️ ==============\n",
    "\n",
    "print(\"βœ… All libraries imported!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 3: Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "βœ… Configuration loaded!\n",
      "🧠 Embedding model: all-MiniLM-L6-v2\n",
      "πŸ€– LLM model: meta-llama/Llama-3.2-3B-Instruct\n",
      "πŸ”‘ HF Token configured: Yes βœ…\n",
      "πŸ“‚ Data path: ../csv_files/\n"
     ]
    }
   ],
   "source": [
    "class Config:\n",
    "    \"\"\"Centralized configuration for VS Code\"\"\"\n",
    "    \n",
    "    # Paths - VS Code structure\n",
    "    CSV_PATH = '../csv_files/'\n",
    "    PROCESSED_PATH = '../processed/'\n",
    "    RESULTS_PATH = '../results/'\n",
    "    \n",
    "    # Embedding Model\n",
    "    EMBEDDING_MODEL = 'all-MiniLM-L6-v2'\n",
    "    \n",
    "    # LLM Settings (FREE - Hugging Face)\n",
    "    HF_TOKEN = os.getenv('HF_TOKEN', '')  # βœ… Pega do .env\n",
    "    LLM_MODEL = 'meta-llama/Llama-3.2-3B-Instruct'\n",
    "    \n",
    "    LLM_MAX_TOKENS = 1000\n",
    "    \n",
    "    # Matching Parameters\n",
    "    TOP_K_MATCHES = 10\n",
    "    SIMILARITY_THRESHOLD = 0.5\n",
    "    RANDOM_SEED = 42\n",
    "\n",
    "np.random.seed(Config.RANDOM_SEED)\n",
    "\n",
    "print(\"βœ… Configuration loaded!\")\n",
    "print(f\"🧠 Embedding model: {Config.EMBEDDING_MODEL}\")\n",
    "print(f\"πŸ€– LLM model: {Config.LLM_MODEL}\")\n",
    "print(f\"πŸ”‘ HF Token configured: {'Yes βœ…' if Config.HF_TOKEN else 'No ⚠️'}\")\n",
    "print(f\"πŸ“‚ Data path: {Config.CSV_PATH}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 4: Load All Datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸ“‚ Loading all datasets...\n",
      "\n",
      "======================================================================\n",
      "βœ… Candidates: 9,544 rows Γ— 35 columns\n",
      "βœ… Companies (base): 24,473 rows\n",
      "βœ… Company industries: 24,375 rows\n",
      "βœ… Company specialties: 169,387 rows\n",
      "βœ… Employee counts: 35,787 rows\n",
      "βœ… Postings: 123,849 rows Γ— 31 columns\n",
      "βœ… Job skills: 213,768 rows\n",
      "βœ… Job industries: 164,808 rows\n",
      "\n",
      "======================================================================\n",
      "βœ… All datasets loaded successfully!\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(\"πŸ“‚ Loading all datasets...\\n\")\n",
    "print(\"=\" * 70)\n",
    "\n",
    "# Load main datasets\n",
    "candidates = pd.read_csv(f'{Config.CSV_PATH}resume_data.csv')\n",
    "print(f\"βœ… Candidates: {len(candidates):,} rows Γ— {len(candidates.columns)} columns\")\n",
    "\n",
    "companies_base = pd.read_csv(f'{Config.CSV_PATH}companies.csv')\n",
    "print(f\"βœ… Companies (base): {len(companies_base):,} rows\")\n",
    "\n",
    "company_industries = pd.read_csv(f'{Config.CSV_PATH}company_industries.csv')\n",
    "print(f\"βœ… Company industries: {len(company_industries):,} rows\")\n",
    "\n",
    "company_specialties = pd.read_csv(f'{Config.CSV_PATH}company_specialities.csv')\n",
    "print(f\"βœ… Company specialties: {len(company_specialties):,} rows\")\n",
    "\n",
    "employee_counts = pd.read_csv(f'{Config.CSV_PATH}employee_counts.csv')\n",
    "print(f\"βœ… Employee counts: {len(employee_counts):,} rows\")\n",
    "\n",
    "postings = pd.read_csv(f'{Config.CSV_PATH}postings.csv', on_bad_lines='skip', engine='python')\n",
    "print(f\"βœ… Postings: {len(postings):,} rows Γ— {len(postings.columns)} columns\")\n",
    "\n",
    "# Optional datasets\n",
    "try:\n",
    "    job_skills = pd.read_csv(f'{Config.CSV_PATH}job_skills.csv')\n",
    "    print(f\"βœ… Job skills: {len(job_skills):,} rows\")\n",
    "except:\n",
    "    job_skills = None\n",
    "    print(\"⚠️  Job skills not found (optional)\")\n",
    "\n",
    "try:\n",
    "    job_industries = pd.read_csv(f'{Config.CSV_PATH}job_industries.csv')\n",
    "    print(f\"βœ… Job industries: {len(job_industries):,} rows\")\n",
    "except:\n",
    "    job_industries = None\n",
    "    print(\"⚠️  Job industries not found (optional)\")\n",
    "\n",
    "print(\"\\n\" + \"=\" * 70)\n",
    "print(\"βœ… All datasets loaded successfully!\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 5: Merge & Enrich Company Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸ”— Merging company data...\n",
      "\n",
      "βœ… Aggregated industries for 24,365 companies\n",
      "βœ… Aggregated specialties for 17,780 companies\n",
      "\n",
      "βœ… Base company merge complete: 35,787 companies\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(\"πŸ”— Merging company data...\\n\")\n",
    "\n",
    "# Aggregate industries\n",
    "company_industries_agg = company_industries.groupby('company_id')['industry'].apply(\n",
    "    lambda x: ', '.join(map(str, x.tolist()))\n",
    ").reset_index()\n",
    "company_industries_agg.columns = ['company_id', 'industries_list']\n",
    "print(f\"βœ… Aggregated industries for {len(company_industries_agg):,} companies\")\n",
    "\n",
    "# Aggregate specialties\n",
    "company_specialties_agg = company_specialties.groupby('company_id')['speciality'].apply(\n",
    "    lambda x: ' | '.join(x.astype(str).tolist())\n",
    ").reset_index()\n",
    "company_specialties_agg.columns = ['company_id', 'specialties_list']\n",
    "print(f\"βœ… Aggregated specialties for {len(company_specialties_agg):,} companies\")\n",
    "\n",
    "# Merge all company data\n",
    "companies_merged = companies_base.copy()\n",
    "companies_merged = companies_merged.merge(company_industries_agg, on='company_id', how='left')\n",
    "companies_merged = companies_merged.merge(company_specialties_agg, on='company_id', how='left')\n",
    "companies_merged = companies_merged.merge(employee_counts, on='company_id', how='left')\n",
    "\n",
    "print(f\"\\nβœ… Base company merge complete: {len(companies_merged):,} companies\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 6: Enrich with Job Postings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸŒ‰ Enriching companies with job posting data...\n",
      "\n",
      "======================================================================\n",
      "KEY INSIGHT: Postings = 'Requirements Language Bridge'\n",
      "======================================================================\n",
      "\n",
      "βœ… Enriched 35,787 companies with posting data\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(\"πŸŒ‰ Enriching companies with job posting data...\\n\")\n",
    "print(\"=\" * 70)\n",
    "print(\"KEY INSIGHT: Postings = 'Requirements Language Bridge'\")\n",
    "print(\"=\" * 70 + \"\\n\")\n",
    "\n",
    "postings = postings.fillna('')\n",
    "postings['company_id'] = postings['company_id'].astype(str)\n",
    "\n",
    "# Aggregate postings per company\n",
    "postings_agg = postings.groupby('company_id').agg({\n",
    "    'title': lambda x: ' | '.join(x.astype(str).tolist()[:10]),\n",
    "    'description': lambda x: ' '.join(x.astype(str).tolist()[:5]),\n",
    "    'skills_desc': lambda x: ' | '.join(x.dropna().astype(str).tolist()),\n",
    "    'formatted_experience_level': lambda x: ' | '.join(x.dropna().unique().astype(str)),\n",
    "}).reset_index()\n",
    "\n",
    "postings_agg.columns = ['company_id', 'posted_job_titles', 'posted_descriptions', 'required_skills', 'experience_levels']\n",
    "\n",
    "companies_merged['company_id'] = companies_merged['company_id'].astype(str)\n",
    "companies_full = companies_merged.merge(postings_agg, on='company_id', how='left').fillna('')\n",
    "\n",
    "print(f\"βœ… Enriched {len(companies_full):,} companies with posting data\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>company_id</th>\n",
       "      <th>name</th>\n",
       "      <th>description</th>\n",
       "      <th>company_size</th>\n",
       "      <th>state</th>\n",
       "      <th>country</th>\n",
       "      <th>city</th>\n",
       "      <th>zip_code</th>\n",
       "      <th>address</th>\n",
       "      <th>url</th>\n",
       "      <th>industries_list</th>\n",
       "      <th>specialties_list</th>\n",
       "      <th>employee_count</th>\n",
       "      <th>follower_count</th>\n",
       "      <th>time_recorded</th>\n",
       "      <th>posted_job_titles</th>\n",
       "      <th>posted_descriptions</th>\n",
       "      <th>required_skills</th>\n",
       "      <th>experience_levels</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1009</td>\n",
       "      <td>IBM</td>\n",
       "      <td>At IBM, we do more than work. We create. We cr...</td>\n",
       "      <td>7.0</td>\n",
       "      <td>NY</td>\n",
       "      <td>US</td>\n",
       "      <td>Armonk, New York</td>\n",
       "      <td>10504</td>\n",
       "      <td>International Business Machines Corp.</td>\n",
       "      <td>https://www.linkedin.com/company/ibm</td>\n",
       "      <td>IT Services and IT Consulting</td>\n",
       "      <td>Cloud | Mobile | Cognitive | Security | Resear...</td>\n",
       "      <td>314102</td>\n",
       "      <td>16253625</td>\n",
       "      <td>1712378162</td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1009</td>\n",
       "      <td>IBM</td>\n",
       "      <td>At IBM, we do more than work. We create. We cr...</td>\n",
       "      <td>7.0</td>\n",
       "      <td>NY</td>\n",
       "      <td>US</td>\n",
       "      <td>Armonk, New York</td>\n",
       "      <td>10504</td>\n",
       "      <td>International Business Machines Corp.</td>\n",
       "      <td>https://www.linkedin.com/company/ibm</td>\n",
       "      <td>IT Services and IT Consulting</td>\n",
       "      <td>Cloud | Mobile | Cognitive | Security | Resear...</td>\n",
       "      <td>313142</td>\n",
       "      <td>16309464</td>\n",
       "      <td>1713392385</td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1009</td>\n",
       "      <td>IBM</td>\n",
       "      <td>At IBM, we do more than work. We create. We cr...</td>\n",
       "      <td>7.0</td>\n",
       "      <td>NY</td>\n",
       "      <td>US</td>\n",
       "      <td>Armonk, New York</td>\n",
       "      <td>10504</td>\n",
       "      <td>International Business Machines Corp.</td>\n",
       "      <td>https://www.linkedin.com/company/ibm</td>\n",
       "      <td>IT Services and IT Consulting</td>\n",
       "      <td>Cloud | Mobile | Cognitive | Security | Resear...</td>\n",
       "      <td>313147</td>\n",
       "      <td>16309985</td>\n",
       "      <td>1713402495</td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1009</td>\n",
       "      <td>IBM</td>\n",
       "      <td>At IBM, we do more than work. We create. We cr...</td>\n",
       "      <td>7.0</td>\n",
       "      <td>NY</td>\n",
       "      <td>US</td>\n",
       "      <td>Armonk, New York</td>\n",
       "      <td>10504</td>\n",
       "      <td>International Business Machines Corp.</td>\n",
       "      <td>https://www.linkedin.com/company/ibm</td>\n",
       "      <td>IT Services and IT Consulting</td>\n",
       "      <td>Cloud | Mobile | Cognitive | Security | Resear...</td>\n",
       "      <td>311223</td>\n",
       "      <td>16314846</td>\n",
       "      <td>1713501255</td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1016</td>\n",
       "      <td>GE HealthCare</td>\n",
       "      <td>Every day millions of people feel the impact o...</td>\n",
       "      <td>7.0</td>\n",
       "      <td>0</td>\n",
       "      <td>US</td>\n",
       "      <td>Chicago</td>\n",
       "      <td>0</td>\n",
       "      <td>-</td>\n",
       "      <td>https://www.linkedin.com/company/gehealthcare</td>\n",
       "      <td>Hospitals and Health Care</td>\n",
       "      <td>Healthcare | Biotechnology</td>\n",
       "      <td>56873</td>\n",
       "      <td>2185368</td>\n",
       "      <td>1712382540</td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  company_id           name  \\\n",
       "0       1009            IBM   \n",
       "1       1009            IBM   \n",
       "2       1009            IBM   \n",
       "3       1009            IBM   \n",
       "4       1016  GE HealthCare   \n",
       "\n",
       "                                         description company_size state  \\\n",
       "0  At IBM, we do more than work. We create. We cr...          7.0    NY   \n",
       "1  At IBM, we do more than work. We create. We cr...          7.0    NY   \n",
       "2  At IBM, we do more than work. We create. We cr...          7.0    NY   \n",
       "3  At IBM, we do more than work. We create. We cr...          7.0    NY   \n",
       "4  Every day millions of people feel the impact o...          7.0     0   \n",
       "\n",
       "  country              city zip_code                                address  \\\n",
       "0      US  Armonk, New York    10504  International Business Machines Corp.   \n",
       "1      US  Armonk, New York    10504  International Business Machines Corp.   \n",
       "2      US  Armonk, New York    10504  International Business Machines Corp.   \n",
       "3      US  Armonk, New York    10504  International Business Machines Corp.   \n",
       "4      US           Chicago        0                                      -   \n",
       "\n",
       "                                             url  \\\n",
       "0           https://www.linkedin.com/company/ibm   \n",
       "1           https://www.linkedin.com/company/ibm   \n",
       "2           https://www.linkedin.com/company/ibm   \n",
       "3           https://www.linkedin.com/company/ibm   \n",
       "4  https://www.linkedin.com/company/gehealthcare   \n",
       "\n",
       "                 industries_list  \\\n",
       "0  IT Services and IT Consulting   \n",
       "1  IT Services and IT Consulting   \n",
       "2  IT Services and IT Consulting   \n",
       "3  IT Services and IT Consulting   \n",
       "4      Hospitals and Health Care   \n",
       "\n",
       "                                    specialties_list  employee_count  \\\n",
       "0  Cloud | Mobile | Cognitive | Security | Resear...          314102   \n",
       "1  Cloud | Mobile | Cognitive | Security | Resear...          313142   \n",
       "2  Cloud | Mobile | Cognitive | Security | Resear...          313147   \n",
       "3  Cloud | Mobile | Cognitive | Security | Resear...          311223   \n",
       "4                         Healthcare | Biotechnology           56873   \n",
       "\n",
       "   follower_count  time_recorded posted_job_titles posted_descriptions  \\\n",
       "0        16253625     1712378162                                         \n",
       "1        16309464     1713392385                                         \n",
       "2        16309985     1713402495                                         \n",
       "3        16314846     1713501255                                         \n",
       "4         2185368     1712382540                                         \n",
       "\n",
       "  required_skills experience_levels  \n",
       "0                                    \n",
       "1                                    \n",
       "2                                    \n",
       "3                                    \n",
       "4                                    "
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "companies_full.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================================================================\n",
      "πŸ” DUPLICATE DETECTION REPORT\n",
      "================================================================================\n",
      "\n",
      "β”Œβ”€ πŸ“Š resume_data.csv (Candidates)\n",
      "β”‚  Primary Key: Resume_ID\n",
      "β”‚  Total rows:     9,544\n",
      "β”‚  Unique rows:    9,544\n",
      "β”‚  Duplicates:     0\n",
      "β”‚  Status:         βœ… CLEAN\n",
      "└─\n",
      "\n",
      "β”Œβ”€ πŸ“Š companies.csv (Companies Base)\n",
      "β”‚  Primary Key: company_id\n",
      "β”‚  Total rows:     24,473\n",
      "β”‚  Unique rows:    24,473\n",
      "β”‚  Duplicates:     0\n",
      "β”‚  Status:         βœ… CLEAN\n",
      "└─\n",
      "\n",
      "β”Œβ”€ πŸ“Š company_industries.csv\n",
      "β”‚  Primary Key: company_id + industry\n",
      "β”‚  Total rows:     24,375\n",
      "β”‚  Unique rows:    24,375\n",
      "β”‚  Duplicates:     0\n",
      "β”‚  Status:         βœ… CLEAN\n",
      "└─\n",
      "\n",
      "β”Œβ”€ πŸ“Š company_specialities.csv\n",
      "β”‚  Primary Key: company_id + speciality\n",
      "β”‚  Total rows:     169,387\n",
      "β”‚  Unique rows:    169,387\n",
      "β”‚  Duplicates:     0\n",
      "β”‚  Status:         βœ… CLEAN\n",
      "└─\n",
      "\n",
      "β”Œβ”€ πŸ“Š employee_counts.csv\n",
      "β”‚  Primary Key: company_id\n",
      "β”‚  Total rows:     35,787\n",
      "β”‚  Unique rows:    24,473\n",
      "β”‚  Duplicates:     11,314\n",
      "β”‚  Status:         πŸ”΄ HAS DUPLICATES\n",
      "└─\n",
      "\n",
      "β”Œβ”€ πŸ“Š postings.csv (Job Postings)\n",
      "β”‚  Primary Key: job_id\n",
      "β”‚  Total rows:     123,849\n",
      "β”‚  Unique rows:    123,849\n",
      "β”‚  Duplicates:     0\n",
      "β”‚  Status:         βœ… CLEAN\n",
      "└─\n",
      "\n",
      "β”Œβ”€ πŸ“Š companies_full (After Enrichment)\n",
      "β”‚  Primary Key: company_id\n",
      "β”‚  Total rows:     35,787\n",
      "β”‚  Unique rows:    24,473\n",
      "β”‚  Duplicates:     11,314\n",
      "β”‚  Status:         πŸ”΄ HAS DUPLICATES\n",
      "β”‚\n",
      "β”‚  Top duplicate company_ids:\n",
      "β”‚    - 33242739 (Confidential): 13 times\n",
      "β”‚    - 5235 (LHH): 13 times\n",
      "β”‚    - 79383535 (Akkodis): 12 times\n",
      "β”‚    - 1681 (Robert Half): 12 times\n",
      "β”‚    - 220336 (Hyatt Hotels Corporation): 11 times\n",
      "└─\n",
      "\n",
      "================================================================================\n",
      "πŸ“Š SUMMARY\n",
      "================================================================================\n",
      "\n",
      "βœ… Clean datasets:          5/7\n",
      "πŸ”΄ Datasets with duplicates: 2/7\n",
      "πŸ—‘οΈ  Total duplicates found:  22,628 rows\n",
      "\n",
      "⚠️  DUPLICATES DETECTED!\n",
      "================================================================================\n"
     ]
    }
   ],
   "source": [
    "## πŸ” Data Quality Check - Duplicate Detection\n",
    "\n",
    "\"\"\"\n",
    "Checking for duplicates in all datasets based on primary keys.\n",
    "This cell only REPORTS duplicates, does not modify data.\n",
    "\"\"\"\n",
    "\n",
    "print(\"=\" * 80)\n",
    "print(\"πŸ” DUPLICATE DETECTION REPORT\")\n",
    "print(\"=\" * 80)\n",
    "print()\n",
    "\n",
    "# Define primary keys for each dataset\n",
    "duplicate_report = []\n",
    "\n",
    "# 1. Candidates\n",
    "print(\"β”Œβ”€ πŸ“Š resume_data.csv (Candidates)\")\n",
    "print(f\"β”‚  Primary Key: Resume_ID\")\n",
    "cand_total = len(candidates)\n",
    "cand_unique = candidates['Resume_ID'].nunique() if 'Resume_ID' in candidates.columns else len(candidates)\n",
    "cand_dups = cand_total - cand_unique\n",
    "print(f\"β”‚  Total rows:     {cand_total:,}\")\n",
    "print(f\"β”‚  Unique rows:    {cand_unique:,}\")\n",
    "print(f\"β”‚  Duplicates:     {cand_dups:,}\")\n",
    "print(f\"β”‚  Status:         {'βœ… CLEAN' if cand_dups == 0 else 'πŸ”΄ HAS DUPLICATES'}\")\n",
    "print(\"└─\\n\")\n",
    "duplicate_report.append(('Candidates', cand_total, cand_unique, cand_dups))\n",
    "\n",
    "# 2. Companies Base\n",
    "print(\"β”Œβ”€ πŸ“Š companies.csv (Companies Base)\")\n",
    "print(f\"β”‚  Primary Key: company_id\")\n",
    "comp_total = len(companies_base)\n",
    "comp_unique = companies_base['company_id'].nunique()\n",
    "comp_dups = comp_total - comp_unique\n",
    "print(f\"β”‚  Total rows:     {comp_total:,}\")\n",
    "print(f\"β”‚  Unique rows:    {comp_unique:,}\")\n",
    "print(f\"β”‚  Duplicates:     {comp_dups:,}\")\n",
    "print(f\"β”‚  Status:         {'βœ… CLEAN' if comp_dups == 0 else 'πŸ”΄ HAS DUPLICATES'}\")\n",
    "if comp_dups > 0:\n",
    "    dup_ids = companies_base[companies_base.duplicated('company_id', keep=False)]['company_id'].value_counts().head(3)\n",
    "    print(f\"β”‚  Top duplicates:\")\n",
    "    for cid, count in dup_ids.items():\n",
    "        print(f\"β”‚    - company_id={cid}: {count} times\")\n",
    "print(\"└─\\n\")\n",
    "duplicate_report.append(('Companies Base', comp_total, comp_unique, comp_dups))\n",
    "\n",
    "# 3. Company Industries\n",
    "print(\"β”Œβ”€ πŸ“Š company_industries.csv\")\n",
    "print(f\"β”‚  Primary Key: company_id + industry\")\n",
    "ci_total = len(company_industries)\n",
    "ci_unique = len(company_industries.drop_duplicates(subset=['company_id', 'industry']))\n",
    "ci_dups = ci_total - ci_unique\n",
    "print(f\"β”‚  Total rows:     {ci_total:,}\")\n",
    "print(f\"β”‚  Unique rows:    {ci_unique:,}\")\n",
    "print(f\"β”‚  Duplicates:     {ci_dups:,}\")\n",
    "print(f\"β”‚  Status:         {'βœ… CLEAN' if ci_dups == 0 else 'πŸ”΄ HAS DUPLICATES'}\")\n",
    "print(\"└─\\n\")\n",
    "duplicate_report.append(('Company Industries', ci_total, ci_unique, ci_dups))\n",
    "\n",
    "# 4. Company Specialties\n",
    "print(\"β”Œβ”€ πŸ“Š company_specialities.csv\")\n",
    "print(f\"β”‚  Primary Key: company_id + speciality\")\n",
    "cs_total = len(company_specialties)\n",
    "cs_unique = len(company_specialties.drop_duplicates(subset=['company_id', 'speciality']))\n",
    "cs_dups = cs_total - cs_unique\n",
    "print(f\"β”‚  Total rows:     {cs_total:,}\")\n",
    "print(f\"β”‚  Unique rows:    {cs_unique:,}\")\n",
    "print(f\"β”‚  Duplicates:     {cs_dups:,}\")\n",
    "print(f\"β”‚  Status:         {'βœ… CLEAN' if cs_dups == 0 else 'πŸ”΄ HAS DUPLICATES'}\")\n",
    "print(\"└─\\n\")\n",
    "duplicate_report.append(('Company Specialties', cs_total, cs_unique, cs_dups))\n",
    "\n",
    "# 5. Employee Counts\n",
    "print(\"β”Œβ”€ πŸ“Š employee_counts.csv\")\n",
    "print(f\"β”‚  Primary Key: company_id\")\n",
    "ec_total = len(employee_counts)\n",
    "ec_unique = employee_counts['company_id'].nunique()\n",
    "ec_dups = ec_total - ec_unique\n",
    "print(f\"β”‚  Total rows:     {ec_total:,}\")\n",
    "print(f\"β”‚  Unique rows:    {ec_unique:,}\")\n",
    "print(f\"β”‚  Duplicates:     {ec_dups:,}\")\n",
    "print(f\"β”‚  Status:         {'βœ… CLEAN' if ec_dups == 0 else 'πŸ”΄ HAS DUPLICATES'}\")\n",
    "print(\"└─\\n\")\n",
    "duplicate_report.append(('Employee Counts', ec_total, ec_unique, ec_dups))\n",
    "\n",
    "# 6. Postings\n",
    "print(\"β”Œβ”€ πŸ“Š postings.csv (Job Postings)\")\n",
    "print(f\"β”‚  Primary Key: job_id\")\n",
    "if 'job_id' in postings.columns:\n",
    "    post_total = len(postings)\n",
    "    post_unique = postings['job_id'].nunique()\n",
    "    post_dups = post_total - post_unique\n",
    "else:\n",
    "    post_total = len(postings)\n",
    "    post_unique = len(postings.drop_duplicates())\n",
    "    post_dups = post_total - post_unique\n",
    "print(f\"β”‚  Total rows:     {post_total:,}\")\n",
    "print(f\"β”‚  Unique rows:    {post_unique:,}\")\n",
    "print(f\"β”‚  Duplicates:     {post_dups:,}\")\n",
    "print(f\"β”‚  Status:         {'βœ… CLEAN' if post_dups == 0 else 'πŸ”΄ HAS DUPLICATES'}\")\n",
    "print(\"└─\\n\")\n",
    "duplicate_report.append(('Postings', post_total, post_unique, post_dups))\n",
    "\n",
    "# 7. Companies Full (After Merge)\n",
    "print(\"β”Œβ”€ πŸ“Š companies_full (After Enrichment)\")\n",
    "print(f\"β”‚  Primary Key: company_id\")\n",
    "cf_total = len(companies_full)\n",
    "cf_unique = companies_full['company_id'].nunique()\n",
    "cf_dups = cf_total - cf_unique\n",
    "print(f\"β”‚  Total rows:     {cf_total:,}\")\n",
    "print(f\"β”‚  Unique rows:    {cf_unique:,}\")\n",
    "print(f\"β”‚  Duplicates:     {cf_dups:,}\")\n",
    "print(f\"β”‚  Status:         {'βœ… CLEAN' if cf_dups == 0 else 'πŸ”΄ HAS DUPLICATES'}\")\n",
    "if cf_dups > 0:\n",
    "    dup_ids = companies_full[companies_full.duplicated('company_id', keep=False)]['company_id'].value_counts().head(5)\n",
    "    print(f\"β”‚\")\n",
    "    print(f\"β”‚  Top duplicate company_ids:\")\n",
    "    for cid, count in dup_ids.items():\n",
    "        comp_name = companies_full[companies_full['company_id'] == cid]['name'].iloc[0]\n",
    "        print(f\"β”‚    - {cid} ({comp_name}): {count} times\")\n",
    "print(\"└─\\n\")\n",
    "duplicate_report.append(('Companies Full', cf_total, cf_unique, cf_dups))\n",
    "\n",
    "# Summary\n",
    "print(\"=\" * 80)\n",
    "print(\"πŸ“Š SUMMARY\")\n",
    "print(\"=\" * 80)\n",
    "print()\n",
    "\n",
    "total_dups = sum(r[3] for r in duplicate_report)\n",
    "clean_datasets = sum(1 for r in duplicate_report if r[3] == 0)\n",
    "dirty_datasets = len(duplicate_report) - clean_datasets\n",
    "\n",
    "print(f\"βœ… Clean datasets:          {clean_datasets}/{len(duplicate_report)}\")\n",
    "print(f\"πŸ”΄ Datasets with duplicates: {dirty_datasets}/{len(duplicate_report)}\")\n",
    "print(f\"πŸ—‘οΈ  Total duplicates found:  {total_dups:,} rows\")\n",
    "print()\n",
    "\n",
    "if dirty_datasets > 0:\n",
    "    print(\"⚠️  DUPLICATES DETECTED!\")\n",
    "else:\n",
    "    print(\"βœ… All datasets are clean! No duplicates found.\")\n",
    "\n",
    "print(\"=\" * 80)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "🧹 CLEANING DUPLICATES...\n",
      "\n",
      "================================================================================\n",
      "βœ… companies_base: Already clean\n",
      "\n",
      "βœ… company_industries: Already clean\n",
      "\n",
      "βœ… company_specialties: Already clean\n",
      "\n",
      "βœ… employee_counts:\n",
      "   Removed 11,314 duplicates\n",
      "   35,787 β†’ 24,473 rows\n",
      "\n",
      "βœ… postings: Already clean\n",
      "\n",
      "βœ… companies_full:\n",
      "   Removed 11,314 duplicates\n",
      "   35,787 β†’ 24,473 rows\n",
      "\n",
      "================================================================================\n",
      "βœ… DATA CLEANING COMPLETE!\n",
      "================================================================================\n",
      "\n",
      "πŸ“Š Total duplicates removed: 22,628 rows\n",
      "\n",
      "Cleaned datasets:\n",
      "  - employee_counts: 35,787 β†’ 24,473\n",
      "  - companies_full: 35,787 β†’ 24,473\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "## 🧹 Data Cleaning - Remove Duplicates\n",
    "\n",
    "Based on the report above, removing duplicates from datasets.\n",
    "\"\"\"\n",
    "\n",
    "print(\"🧹 CLEANING DUPLICATES...\\n\")\n",
    "print(\"=\" * 80)\n",
    "\n",
    "# Store original counts\n",
    "original_counts = {}\n",
    "\n",
    "# 1. Clean Companies Base (if needed)\n",
    "if len(companies_base) != companies_base['company_id'].nunique():\n",
    "    original_counts['companies_base'] = len(companies_base)\n",
    "    companies_base = companies_base.drop_duplicates(subset=['company_id'], keep='first')\n",
    "    removed = original_counts['companies_base'] - len(companies_base)\n",
    "    print(f\"βœ… companies_base:\")\n",
    "    print(f\"   Removed {removed:,} duplicates\")\n",
    "    print(f\"   {original_counts['companies_base']:,} β†’ {len(companies_base):,} rows\\n\")\n",
    "else:\n",
    "    print(f\"βœ… companies_base: Already clean\\n\")\n",
    "\n",
    "# 2. Clean Company Industries (if needed)\n",
    "if len(company_industries) != len(company_industries.drop_duplicates(subset=['company_id', 'industry'])):\n",
    "    original_counts['company_industries'] = len(company_industries)\n",
    "    company_industries = company_industries.drop_duplicates(subset=['company_id', 'industry'], keep='first')\n",
    "    removed = original_counts['company_industries'] - len(company_industries)\n",
    "    print(f\"βœ… company_industries:\")\n",
    "    print(f\"   Removed {removed:,} duplicates\")\n",
    "    print(f\"   {original_counts['company_industries']:,} β†’ {len(company_industries):,} rows\\n\")\n",
    "else:\n",
    "    print(f\"βœ… company_industries: Already clean\\n\")\n",
    "\n",
    "# 3. Clean Company Specialties (if needed)\n",
    "if len(company_specialties) != len(company_specialties.drop_duplicates(subset=['company_id', 'speciality'])):\n",
    "    original_counts['company_specialties'] = len(company_specialties)\n",
    "    company_specialties = company_specialties.drop_duplicates(subset=['company_id', 'speciality'], keep='first')\n",
    "    removed = original_counts['company_specialties'] - len(company_specialties)\n",
    "    print(f\"βœ… company_specialties:\")\n",
    "    print(f\"   Removed {removed:,} duplicates\")\n",
    "    print(f\"   {original_counts['company_specialties']:,} β†’ {len(company_specialties):,} rows\\n\")\n",
    "else:\n",
    "    print(f\"βœ… company_specialties: Already clean\\n\")\n",
    "\n",
    "# 4. Clean Employee Counts (if needed)\n",
    "if len(employee_counts) != employee_counts['company_id'].nunique():\n",
    "    original_counts['employee_counts'] = len(employee_counts)\n",
    "    employee_counts = employee_counts.drop_duplicates(subset=['company_id'], keep='first')\n",
    "    removed = original_counts['employee_counts'] - len(employee_counts)\n",
    "    print(f\"βœ… employee_counts:\")\n",
    "    print(f\"   Removed {removed:,} duplicates\")\n",
    "    print(f\"   {original_counts['employee_counts']:,} β†’ {len(employee_counts):,} rows\\n\")\n",
    "else:\n",
    "    print(f\"βœ… employee_counts: Already clean\\n\")\n",
    "\n",
    "# 5. Clean Postings (if needed)\n",
    "if 'job_id' in postings.columns:\n",
    "    if len(postings) != postings['job_id'].nunique():\n",
    "        original_counts['postings'] = len(postings)\n",
    "        postings = postings.drop_duplicates(subset=['job_id'], keep='first')\n",
    "        removed = original_counts['postings'] - len(postings)\n",
    "        print(f\"βœ… postings:\")\n",
    "        print(f\"   Removed {removed:,} duplicates\")\n",
    "        print(f\"   {original_counts['postings']:,} β†’ {len(postings):,} rows\\n\")\n",
    "    else:\n",
    "        print(f\"βœ… postings: Already clean\\n\")\n",
    "\n",
    "# 6. Clean Companies Full (if needed)\n",
    "if len(companies_full) != companies_full['company_id'].nunique():\n",
    "    original_counts['companies_full'] = len(companies_full)\n",
    "    companies_full = companies_full.drop_duplicates(subset=['company_id'], keep='first')\n",
    "    removed = original_counts['companies_full'] - len(companies_full)\n",
    "    print(f\"βœ… companies_full:\")\n",
    "    print(f\"   Removed {removed:,} duplicates\")\n",
    "    print(f\"   {original_counts['companies_full']:,} β†’ {len(companies_full):,} rows\\n\")\n",
    "else:\n",
    "    print(f\"βœ… companies_full: Already clean\\n\")\n",
    "\n",
    "print(\"=\" * 80)\n",
    "print(\"βœ… DATA CLEANING COMPLETE!\")\n",
    "print(\"=\" * 80)\n",
    "print()\n",
    "\n",
    "# Summary\n",
    "if original_counts:\n",
    "    total_removed = sum(original_counts[k] - globals()[k].shape[0] if k in globals() else 0 \n",
    "                       for k in original_counts.keys())\n",
    "    print(f\"πŸ“Š Total duplicates removed: {total_removed:,} rows\")\n",
    "    print()\n",
    "    print(\"Cleaned datasets:\")\n",
    "    for dataset, original in original_counts.items():\n",
    "        current = len(globals()[dataset]) if dataset in globals() else 0\n",
    "        print(f\"  - {dataset}: {original:,} β†’ {current:,}\")\n",
    "else:\n",
    "    print(\"βœ… No duplicates found - all datasets were already clean!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 7: Load Embedding Model & Pre-computed Vectors"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "🧠 Loading embedding model...\n",
      "\n",
      "βœ… Model loaded: all-MiniLM-L6-v2\n",
      "πŸ“ Embedding dimension: ℝ^384\n",
      "\n",
      "πŸ“‚ Loading pre-computed embeddings...\n",
      "βœ… Loaded from ../processed/\n",
      "πŸ“Š Candidate vectors: (9544, 384)\n",
      "πŸ“Š Company vectors: (35787, 384)\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(\"🧠 Loading embedding model...\\n\")\n",
    "model = SentenceTransformer(Config.EMBEDDING_MODEL)\n",
    "embedding_dim = model.get_sentence_embedding_dimension()\n",
    "print(f\"βœ… Model loaded: {Config.EMBEDDING_MODEL}\")\n",
    "print(f\"πŸ“ Embedding dimension: ℝ^{embedding_dim}\\n\")\n",
    "\n",
    "print(\"πŸ“‚ Loading pre-computed embeddings...\")\n",
    "\n",
    "try:\n",
    "    # Try to load from processed folder\n",
    "    cand_vectors = np.load(f'{Config.PROCESSED_PATH}candidate_embeddings.npy')\n",
    "    comp_vectors = np.load(f'{Config.PROCESSED_PATH}company_embeddings.npy')\n",
    "    \n",
    "    print(f\"βœ… Loaded from {Config.PROCESSED_PATH}\")\n",
    "    print(f\"πŸ“Š Candidate vectors: {cand_vectors.shape}\")\n",
    "    print(f\"πŸ“Š Company vectors: {comp_vectors.shape}\\n\")\n",
    "    \n",
    "except FileNotFoundError:\n",
    "    print(\"⚠️  Pre-computed embeddings not found!\")\n",
    "    print(\"   Embeddings will need to be generated (takes ~5-10 minutes)\")\n",
    "    print(\"   This is normal if running for the first time.\\n\")\n",
    "    \n",
    "    # You can add embedding generation code here if needed\n",
    "    # For now, we'll skip to keep notebook clean\n",
    "    cand_vectors = None\n",
    "    comp_vectors = None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 8: Core Matching Function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "βœ… Matching function ready\n"
     ]
    }
   ],
   "source": [
    "def find_top_matches(candidate_idx: int, top_k: int = 10) -> List[tuple]:\n",
    "    \"\"\"\n",
    "    Find top K company matches for a candidate using cosine similarity.\n",
    "    \n",
    "    Args:\n",
    "        candidate_idx: Index of candidate\n",
    "        top_k: Number of top matches to return\n",
    "    \n",
    "    Returns:\n",
    "        List of (company_index, similarity_score) tuples\n",
    "    \"\"\"\n",
    "    if cand_vectors is None or comp_vectors is None:\n",
    "        raise ValueError(\"Embeddings not loaded! Please run Step 8 first.\")\n",
    "    \n",
    "    cand_vec = cand_vectors[candidate_idx].reshape(1, -1)\n",
    "    similarities = cosine_similarity(cand_vec, comp_vectors)[0]\n",
    "    top_indices = np.argsort(similarities)[::-1][:top_k]\n",
    "    \n",
    "    return [(int(idx), float(similarities[idx])) for idx in top_indices]\n",
    "\n",
    "print(\"βœ… Matching function ready\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 9: Initialize FREE LLM (Hugging Face)\n",
    "\n",
    "### Get your FREE token: https://huggingface.co/settings/tokens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "βœ… Hugging Face client initialized (FREE)\n",
      "πŸ€– Model: meta-llama/Llama-3.2-3B-Instruct\n",
      "πŸ’° Cost: $0.00 (completely free!)\n",
      "\n",
      "βœ… LLM helper functions ready\n"
     ]
    }
   ],
   "source": [
    "# Initialize Hugging Face Inference Client (FREE)\n",
    "if Config.HF_TOKEN:\n",
    "    try:\n",
    "        hf_client = InferenceClient(token=Config.HF_TOKEN)\n",
    "        print(\"βœ… Hugging Face client initialized (FREE)\")\n",
    "        print(f\"πŸ€– Model: {Config.LLM_MODEL}\")\n",
    "        print(\"πŸ’° Cost: $0.00 (completely free!)\\n\")\n",
    "        LLM_AVAILABLE = True\n",
    "    except Exception as e:\n",
    "        print(f\"⚠️  Failed to initialize HF client: {e}\")\n",
    "        LLM_AVAILABLE = False\n",
    "else:\n",
    "    print(\"⚠️  No Hugging Face token configured\")\n",
    "    print(\"   LLM features will be disabled\")\n",
    "    print(\"\\nπŸ“ To enable:\")\n",
    "    print(\"   1. Go to: https://huggingface.co/settings/tokens\")\n",
    "    print(\"   2. Create a token (free)\")\n",
    "    print(\"   3. Set: Config.HF_TOKEN = 'your-token-here'\\n\")\n",
    "    LLM_AVAILABLE = False\n",
    "    hf_client = None\n",
    "\n",
    "def call_llm(prompt: str, max_tokens: int = 1000) -> str:\n",
    "    \"\"\"\n",
    "    Generic LLM call using Hugging Face Inference API (FREE).\n",
    "    \"\"\"\n",
    "    if not LLM_AVAILABLE:\n",
    "        return \"[LLM not available - check .env file for HF_TOKEN]\"\n",
    "    \n",
    "    try:\n",
    "        response = hf_client.chat_completion(  # βœ… chat_completion\n",
    "            messages=[{\"role\": \"user\", \"content\": prompt}],\n",
    "            model=Config.LLM_MODEL,\n",
    "            max_tokens=max_tokens,\n",
    "            temperature=0.7\n",
    "        )\n",
    "        return response.choices[0].message.content  # βœ… Extrai conteΓΊdo\n",
    "    except Exception as e:\n",
    "        return f\"[Error: {str(e)}]\"\n",
    "\n",
    "print(\"βœ… LLM helper functions ready\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 10: Pydantic Schemas for Structured Output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "βœ… Pydantic schemas defined\n"
     ]
    }
   ],
   "source": [
    "class JobLevelClassification(BaseModel):\n",
    "    \"\"\"Job level classification result\"\"\"\n",
    "    level: Literal['Entry', 'Mid', 'Senior', 'Executive']\n",
    "    confidence: float = Field(ge=0.0, le=1.0)\n",
    "    reasoning: str\n",
    "\n",
    "class SkillsTaxonomy(BaseModel):\n",
    "    \"\"\"Structured skills extraction\"\"\"\n",
    "    technical_skills: List[str] = Field(default_factory=list)\n",
    "    soft_skills: List[str] = Field(default_factory=list)\n",
    "    certifications: List[str] = Field(default_factory=list)\n",
    "    languages: List[str] = Field(default_factory=list)\n",
    "\n",
    "class MatchExplanation(BaseModel):\n",
    "    \"\"\"Match reasoning\"\"\"\n",
    "    overall_score: float = Field(ge=0.0, le=1.0)\n",
    "    match_strengths: List[str]\n",
    "    skill_gaps: List[str]\n",
    "    recommendation: str\n",
    "    fit_summary: str = Field(max_length=200)\n",
    "\n",
    "print(\"βœ… Pydantic schemas defined\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 11: Job Level Classification (Zero-Shot)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸ§ͺ Testing zero-shot classification...\n",
      "\n",
      "πŸ“Š Classification Result:\n",
      "{\n",
      "  \"level\": \"Entry\",\n",
      "  \"confidence\": 0.75,\n",
      "  \"reasoning\": \"The job posting mentions 'some experience in graphic design' and 'fun, kind, ambitious members of the sales team' indicating a junior role.\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "def classify_job_level_zero_shot(job_description: str) -> Dict:\n",
    "    \"\"\"\n",
    "    Zero-shot job level classification.\n",
    "    \n",
    "    Returns classification as: Entry, Mid, Senior, or Executive\n",
    "    \"\"\"\n",
    "    \n",
    "    prompt = f\"\"\"Classify this job posting into ONE seniority level.\n",
    "\n",
    "Levels:\n",
    "- Entry: 0-2 years experience, junior roles\n",
    "- Mid: 3-5 years experience, independent work\n",
    "- Senior: 6-10 years experience, technical leadership\n",
    "- Executive: 10+ years, strategic leadership, C-level\n",
    "\n",
    "Job Posting:\n",
    "{job_description[:500]}\n",
    "\n",
    "Return ONLY valid JSON:\n",
    "{{\n",
    "    \"level\": \"Entry|Mid|Senior|Executive\",\n",
    "    \"confidence\": 0.85,\n",
    "    \"reasoning\": \"Brief explanation\"\n",
    "}}\n",
    "\"\"\"\n",
    "    \n",
    "    response = call_llm(prompt)\n",
    "    \n",
    "    try:\n",
    "        # Extract JSON\n",
    "        json_str = response.strip()\n",
    "        if '```json' in json_str:\n",
    "            json_str = json_str.split('```json')[1].split('```')[0].strip()\n",
    "        elif '```' in json_str:\n",
    "            json_str = json_str.split('```')[1].split('```')[0].strip()\n",
    "        \n",
    "        # Find JSON in response\n",
    "        if '{' in json_str and '}' in json_str:\n",
    "            start = json_str.index('{')\n",
    "            end = json_str.rindex('}') + 1\n",
    "            json_str = json_str[start:end]\n",
    "        \n",
    "        result = json.loads(json_str)\n",
    "        return result\n",
    "    except:\n",
    "        return {\n",
    "            \"level\": \"Unknown\",\n",
    "            \"confidence\": 0.0,\n",
    "            \"reasoning\": \"Failed to parse response\"\n",
    "        }\n",
    "\n",
    "# Test if LLM available and data loaded\n",
    "if LLM_AVAILABLE and len(postings) > 0:\n",
    "    print(\"πŸ§ͺ Testing zero-shot classification...\\n\")\n",
    "    sample = postings.iloc[0]['description']\n",
    "    result = classify_job_level_zero_shot(sample)\n",
    "    \n",
    "    print(\"πŸ“Š Classification Result:\")\n",
    "    print(json.dumps(result, indent=2))\n",
    "else:\n",
    "    print(\"⚠️  Skipped - LLM not available or no data\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 12: Few-Shot Learning"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸ§ͺ Comparing Zero-Shot vs Few-Shot...\n",
      "\n",
      "πŸ“Š Comparison:\n",
      "Zero-shot: Unknown (confidence: 0.00)\n",
      "Few-shot:  Entry (confidence: 0.90)\n"
     ]
    }
   ],
   "source": [
    "def classify_job_level_few_shot(job_description: str) -> Dict:\n",
    "    \"\"\"\n",
    "    Few-shot classification with examples.\n",
    "    \"\"\"\n",
    "    \n",
    "    prompt = f\"\"\"Classify this job posting using examples.\n",
    "\n",
    "EXAMPLES:\n",
    "\n",
    "Example 1 (Entry):\n",
    "\"Recent graduate wanted. Python basics. Mentorship provided.\"\n",
    "β†’ Entry level (learning focus, 0-2 years)\n",
    "\n",
    "Example 2 (Senior):\n",
    "\"5+ years backend. Lead team of 3. System architecture.\"\n",
    "β†’ Senior level (technical leadership, 6-10 years)\n",
    "\n",
    "Example 3 (Executive):\n",
    "\"CTO position. 15+ years. Define technical strategy.\"\n",
    "β†’ Executive level (C-level, strategic)\n",
    "\n",
    "NOW CLASSIFY:\n",
    "{job_description[:500]}\n",
    "\n",
    "Return JSON:\n",
    "{{\n",
    "    \"level\": \"Entry|Mid|Senior|Executive\",\n",
    "    \"confidence\": 0.0-1.0,\n",
    "    \"reasoning\": \"Explain\"\n",
    "}}\n",
    "\"\"\"\n",
    "    \n",
    "    response = call_llm(prompt)\n",
    "    \n",
    "    try:\n",
    "        json_str = response.strip()\n",
    "        if '```json' in json_str:\n",
    "            json_str = json_str.split('```json')[1].split('```')[0].strip()\n",
    "        \n",
    "        if '{' in json_str and '}' in json_str:\n",
    "            start = json_str.index('{')\n",
    "            end = json_str.rindex('}') + 1\n",
    "            json_str = json_str[start:end]\n",
    "        \n",
    "        result = json.loads(json_str)\n",
    "        return result\n",
    "    except:\n",
    "        return {\"level\": \"Unknown\", \"confidence\": 0.0, \"reasoning\": \"Parse error\"}\n",
    "\n",
    "# Compare zero-shot vs few-shot\n",
    "if LLM_AVAILABLE and len(postings) > 0:\n",
    "    print(\"πŸ§ͺ Comparing Zero-Shot vs Few-Shot...\\n\")\n",
    "    sample = postings.iloc[0]['description']\n",
    "    \n",
    "    zero = classify_job_level_zero_shot(sample)\n",
    "    few = classify_job_level_few_shot(sample)\n",
    "    \n",
    "    print(\"πŸ“Š Comparison:\")\n",
    "    print(f\"Zero-shot: {zero['level']} (confidence: {zero['confidence']:.2f})\")\n",
    "    print(f\"Few-shot:  {few['level']} (confidence: {few['confidence']:.2f})\")\n",
    "else:\n",
    "    print(\"⚠️  Skipped\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 13: Structured Skills Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸ” Testing skills extraction...\n",
      "\n",
      "πŸ“Š Extracted Skills:\n",
      "{\n",
      "  \"technical_skills\": [\n",
      "    \"Adobe Creative Cloud\",\n",
      "    \"Microsoft Office Suite\"\n",
      "  ],\n",
      "  \"soft_skills\": [\n",
      "    \"Communication\",\n",
      "    \"Leadership\",\n",
      "    \"Organization\",\n",
      "    \"Responsibility\",\n",
      "    \"Respect\",\n",
      "    \"Positive attitude\",\n",
      "    \"Proactivity\",\n",
      "    \"Creativity\",\n",
      "    \"Time management\",\n",
      "    \"Cool-under-pressure\"\n",
      "  ],\n",
      "  \"certifications\": [\n",
      "    \"Adobe Creative Cloud skills\"\n",
      "  ],\n",
      "  \"languages\": [\n",
      "    \"English\"\n",
      "  ]\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "def extract_skills_taxonomy(job_description: str) -> Dict:\n",
    "    \"\"\"\n",
    "    Extract structured skills using LLM + Pydantic validation.\n",
    "    \"\"\"\n",
    "    \n",
    "    prompt = f\"\"\"Extract skills from this job posting.\n",
    "\n",
    "Job Posting:\n",
    "{job_description[:800]}\n",
    "\n",
    "Return ONLY valid JSON:\n",
    "{{\n",
    "    \"technical_skills\": [\"Python\", \"Docker\", \"AWS\"],\n",
    "    \"soft_skills\": [\"Communication\", \"Leadership\"],\n",
    "    \"certifications\": [\"AWS Certified\"],\n",
    "    \"languages\": [\"English\", \"Danish\"]\n",
    "}}\n",
    "\"\"\"\n",
    "    \n",
    "    response = call_llm(prompt, max_tokens=800)\n",
    "    \n",
    "    try:\n",
    "        json_str = response.strip()\n",
    "        if '```json' in json_str:\n",
    "            json_str = json_str.split('```json')[1].split('```')[0].strip()\n",
    "        \n",
    "        if '{' in json_str and '}' in json_str:\n",
    "            start = json_str.index('{')\n",
    "            end = json_str.rindex('}') + 1\n",
    "            json_str = json_str[start:end]\n",
    "        \n",
    "        data = json.loads(json_str)\n",
    "        # Validate with Pydantic\n",
    "        validated = SkillsTaxonomy(**data)\n",
    "        return validated.model_dump()\n",
    "    except:\n",
    "        return {\n",
    "            \"technical_skills\": [],\n",
    "            \"soft_skills\": [],\n",
    "            \"certifications\": [],\n",
    "            \"languages\": []\n",
    "        }\n",
    "\n",
    "# Test extraction\n",
    "if LLM_AVAILABLE and len(postings) > 0:\n",
    "    print(\"πŸ” Testing skills extraction...\\n\")\n",
    "    sample = postings.iloc[0]['description']\n",
    "    skills = extract_skills_taxonomy(sample)\n",
    "    \n",
    "    print(\"πŸ“Š Extracted Skills:\")\n",
    "    print(json.dumps(skills, indent=2))\n",
    "else:\n",
    "    print(\"⚠️  Skipped\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 14: Match Explainability"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸ’‘ Testing match explainability...\n",
      "\n",
      "πŸ“Š Match Explanation:\n",
      "{\n",
      "  \"overall_score\": 0.7028058171272278,\n",
      "  \"match_strengths\": [\n",
      "    \"Unable to generate\"\n",
      "  ],\n",
      "  \"skill_gaps\": [],\n",
      "  \"recommendation\": \"Review manually\",\n",
      "  \"fit_summary\": \"Match score: 0.70\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "def explain_match(candidate_idx: int, company_idx: int, similarity_score: float) -> Dict:\n",
    "    \"\"\"\n",
    "    Generate LLM explanation for why candidate matches company.\n",
    "    \"\"\"\n",
    "    \n",
    "    cand = candidates.iloc[candidate_idx]\n",
    "    comp = companies_full.iloc[company_idx]\n",
    "    \n",
    "    cand_skills = str(cand.get('skills', 'N/A'))[:300]\n",
    "    cand_exp = str(cand.get('positions', 'N/A'))[:300]\n",
    "    comp_req = str(comp.get('required_skills', 'N/A'))[:300]\n",
    "    comp_name = comp.get('name', 'Unknown')\n",
    "    \n",
    "    prompt = f\"\"\"Explain why this candidate matches this company.\n",
    "\n",
    "Candidate:\n",
    "Skills: {cand_skills}\n",
    "Experience: {cand_exp}\n",
    "\n",
    "Company: {comp_name}\n",
    "Requirements: {comp_req}\n",
    "\n",
    "Similarity Score: {similarity_score:.2f}\n",
    "\n",
    "Return JSON:\n",
    "{{\n",
    "    \"overall_score\": {similarity_score},\n",
    "    \"match_strengths\": [\"Top 3-5 matching factors\"],\n",
    "    \"skill_gaps\": [\"Missing skills\"],\n",
    "    \"recommendation\": \"What candidate should do\",\n",
    "    \"fit_summary\": \"One sentence summary\"\n",
    "}}\n",
    "\"\"\"\n",
    "    \n",
    "    response = call_llm(prompt, max_tokens=1000)\n",
    "    \n",
    "    try:\n",
    "        json_str = response.strip()\n",
    "        if '```json' in json_str:\n",
    "            json_str = json_str.split('```json')[1].split('```')[0].strip()\n",
    "        \n",
    "        if '{' in json_str and '}' in json_str:\n",
    "            start = json_str.index('{')\n",
    "            end = json_str.rindex('}') + 1\n",
    "            json_str = json_str[start:end]\n",
    "        \n",
    "        data = json.loads(json_str)\n",
    "        return data\n",
    "    except:\n",
    "        return {\n",
    "            \"overall_score\": similarity_score,\n",
    "            \"match_strengths\": [\"Unable to generate\"],\n",
    "            \"skill_gaps\": [],\n",
    "            \"recommendation\": \"Review manually\",\n",
    "            \"fit_summary\": f\"Match score: {similarity_score:.2f}\"\n",
    "        }\n",
    "\n",
    "# Test explainability\n",
    "if LLM_AVAILABLE and cand_vectors is not None and len(candidates) > 0:\n",
    "    print(\"πŸ’‘ Testing match explainability...\\n\")\n",
    "    matches = find_top_matches(0, top_k=1)\n",
    "    if matches:\n",
    "        comp_idx, score = matches[0]\n",
    "        explanation = explain_match(0, comp_idx, score)\n",
    "        \n",
    "        print(\"πŸ“Š Match Explanation:\")\n",
    "        print(json.dumps(explanation, indent=2))\n",
    "else:\n",
    "    print(\"⚠️  Skipped - requirements not met\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 16: Detailed Match Visualization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸ” DETAILED MATCH ANALYSIS\n",
      "====================================================================================================\n",
      "\n",
      "🎯 CANDIDATE #0\n",
      "Resume ID: N/A\n",
      "Category: N/A\n",
      "Skills: ['Big Data', 'Hadoop', 'Hive', 'Python', 'Mapreduce', 'Spark', 'Java', 'Machine Learning', 'Cloud', 'Hdfs', 'YARN', 'Core Java', 'Data Science', 'C++'...\n",
      "\n",
      "πŸ”— TOP 5 MATCHES:\n",
      "\n",
      "#1. TeachTown (Score: 0.7028)\n",
      "    Industries: E-Learning Providers...\n",
      "#3. Wolverine Power Systems (Score: 0.7026)\n",
      "    Industries: Renewable Energy Semiconductor Manufacturing...\n",
      "#5. Mariner (Score: 0.7010)\n",
      "    Industries: Financial Services...\n",
      "\n",
      "====================================================================================================\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[(9418, 0.7028058171272278),\n",
       " (30989, 0.7026211023330688),\n",
       " (9417, 0.7025721669197083),\n",
       " (30990, 0.7019376754760742),\n",
       " (9416, 0.7010321021080017)]"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# ============================================================================\n",
    "# πŸ” DETAILED MATCH EXAMPLE\n",
    "# ============================================================================\n",
    "\n",
    "def show_detailed_match_example(candidate_idx=0, top_k=5):\n",
    "    print(\"πŸ” DETAILED MATCH ANALYSIS\")\n",
    "    print(\"=\" * 100)\n",
    "    \n",
    "    if candidate_idx >= len(candidates):\n",
    "        print(f\"❌ ERROR: Candidate {candidate_idx} out of range\")\n",
    "        return None\n",
    "    \n",
    "    cand = candidates.iloc[candidate_idx]\n",
    "    \n",
    "    print(f\"\\n🎯 CANDIDATE #{candidate_idx}\")\n",
    "    print(f\"Resume ID: {cand.get('Resume_ID', 'N/A')}\")\n",
    "    print(f\"Category: {cand.get('Category', 'N/A')}\")\n",
    "    print(f\"Skills: {str(cand.get('skills', 'N/A'))[:150]}...\\n\")\n",
    "    \n",
    "    matches = find_top_matches(candidate_idx, top_k=top_k)\n",
    "    \n",
    "    print(f\"πŸ”— TOP {len(matches)} MATCHES:\\n\")\n",
    "    \n",
    "    for rank, (comp_idx, score) in enumerate(matches, 1):\n",
    "        if comp_idx >= len(companies_full):\n",
    "            continue\n",
    "        \n",
    "        company = companies_full.iloc[comp_idx]\n",
    "        print(f\"#{rank}. {company.get('name', 'N/A')} (Score: {score:.4f})\")\n",
    "        print(f\"    Industries: {str(company.get('industries_list', 'N/A'))[:60]}...\")\n",
    "    \n",
    "    print(\"\\n\" + \"=\" * 100)\n",
    "    return matches\n",
    "\n",
    "# Test\n",
    "show_detailed_match_example(candidate_idx=0, top_k=5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 17: Bridging Concept Analysis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸŒ‰ THE BRIDGING CONCEPT\n",
      "==========================================================================================\n",
      "\n",
      "πŸ“Š DATA REALITY:\n",
      "   Total companies: 24,473\n",
      "   WITH postings: 0 (0.0%)\n",
      "   WITHOUT postings: 24,473\n",
      "\n",
      "🎯 THE PROBLEM:\n",
      "   Companies: 'We are in TECH INDUSTRY'\n",
      "   Candidates: 'I know PYTHON, AWS'\n",
      "   β†’ Different languages! 🚫\n",
      "\n",
      "πŸŒ‰ THE SOLUTION (BRIDGING):\n",
      "   1. Extract from postings: 'Need PYTHON developers'\n",
      "   2. Enrich company profile with skills\n",
      "   3. Now both speak SKILLS LANGUAGE! βœ…\n",
      "\n",
      "==========================================================================================\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(Empty DataFrame\n",
       " Columns: [company_id, name, description, company_size, state, country, city, zip_code, address, url, industries_list, specialties_list, employee_count, follower_count, time_recorded, posted_job_titles, posted_descriptions, required_skills, experience_levels]\n",
       " Index: [],\n",
       "       company_id                               name  \\\n",
       " 0           1009                                IBM   \n",
       " 4           1016                      GE HealthCare   \n",
       " 14          1025         Hewlett Packard Enterprise   \n",
       " 18          1028                             Oracle   \n",
       " 23          1033                          Accenture   \n",
       " ...          ...                                ...   \n",
       " 35782  103463217                       JRC Services   \n",
       " 35783  103466352             Centent Consulting LLC   \n",
       " 35784  103467540  Kings and Queens Productions, LLC   \n",
       " 35785  103468936                           WebUnite   \n",
       " 35786  103472979                            BlackVe   \n",
       " \n",
       "                                              description company_size  \\\n",
       " 0      At IBM, we do more than work. We create. We cr...          7.0   \n",
       " 4      Every day millions of people feel the impact o...          7.0   \n",
       " 14     Official LinkedIn of Hewlett Packard Enterpris...          7.0   \n",
       " 18     We’re a cloud technology company that provides...          7.0   \n",
       " 23     Accenture is a leading global professional ser...          7.0   \n",
       " ...                                                  ...          ...   \n",
       " 35782                                                             2.0   \n",
       " 35783  Centent Consulting LLC is a reputable human re...                \n",
       " 35784  We are a small but mighty collection of thinke...                \n",
       " 35785  Our mission at WebUnite is to offer experience...                \n",
       " 35786                                                             1.0   \n",
       " \n",
       "               state country              city zip_code  \\\n",
       " 0                NY      US  Armonk, New York    10504   \n",
       " 4                 0      US           Chicago        0   \n",
       " 14            Texas      US           Houston    77389   \n",
       " 18            Texas      US            Austin    78741   \n",
       " 23                0      IE          Dublin 2        0   \n",
       " ...             ...     ...               ...      ...   \n",
       " 35782             0       0                 0        0   \n",
       " 35783             0       0                 0        0   \n",
       " 35784             0       0                 0        0   \n",
       " 35785  Pennsylvania      US       Southampton    18966   \n",
       " 35786             0       0                 0        0   \n",
       " \n",
       "                                      address  \\\n",
       " 0      International Business Machines Corp.   \n",
       " 4                                          -   \n",
       " 14               1701 E Mossy Oaks Rd Spring   \n",
       " 18                           2300 Oracle Way   \n",
       " 23                       Grand Canal Harbour   \n",
       " ...                                      ...   \n",
       " 35782                                      0   \n",
       " 35783                                      0   \n",
       " 35784                                      0   \n",
       " 35785                    720 2nd Street Pike   \n",
       " 35786                                      0   \n",
       " \n",
       "                                                      url  \\\n",
       " 0                   https://www.linkedin.com/company/ibm   \n",
       " 4          https://www.linkedin.com/company/gehealthcare   \n",
       " 14     https://www.linkedin.com/company/hewlett-packa...   \n",
       " 18               https://www.linkedin.com/company/oracle   \n",
       " 23            https://www.linkedin.com/company/accenture   \n",
       " ...                                                  ...   \n",
       " 35782       https://www.linkedin.com/company/jrcservices   \n",
       " 35783  https://www.linkedin.com/company/centent-consu...   \n",
       " 35784  https://www.linkedin.com/company/kings-and-que...   \n",
       " 35785          https://www.linkedin.com/company/webunite   \n",
       " 35786           https://www.linkedin.com/company/blackve   \n",
       " \n",
       "                                    industries_list  \\\n",
       " 0                    IT Services and IT Consulting   \n",
       " 4                        Hospitals and Health Care   \n",
       " 14                   IT Services and IT Consulting   \n",
       " 18                   IT Services and IT Consulting   \n",
       " 23                Business Consulting and Services   \n",
       " ...                                            ...   \n",
       " 35782                          Facilities Services   \n",
       " 35783             Business Consulting and Services   \n",
       " 35784  Broadcast Media Production and Distribution   \n",
       " 35785             Business Consulting and Services   \n",
       " 35786              Defense and Space Manufacturing   \n",
       " \n",
       "                                         specialties_list  employee_count  \\\n",
       " 0      Cloud | Mobile | Cognitive | Security | Resear...          314102   \n",
       " 4                             Healthcare | Biotechnology           56873   \n",
       " 14                                                                 79528   \n",
       " 18     enterprise | software | applications | databas...          192099   \n",
       " 23     Management Consulting | Systems Integration an...          574664   \n",
       " ...                                                  ...             ...   \n",
       " 35782                                                                  0   \n",
       " 35783                                                                  0   \n",
       " 35784                                                                  0   \n",
       " 35785                                                                  0   \n",
       " 35786                                                                  0   \n",
       " \n",
       "        follower_count  time_recorded posted_job_titles posted_descriptions  \\\n",
       " 0            16253625     1712378162                                         \n",
       " 4             2185368     1712382540                                         \n",
       " 14            3586194     1712870106                                         \n",
       " 18            9465968     1712642952                                         \n",
       " 23           11864908     1712641699                                         \n",
       " ...               ...            ...               ...                 ...   \n",
       " 35782              21     1713552037                                         \n",
       " 35783               0     1713550651                                         \n",
       " 35784              12     1713554225                                         \n",
       " 35785               1     1713535939                                         \n",
       " 35786               0     1713539379                                         \n",
       " \n",
       "       required_skills experience_levels  \n",
       " 0                                        \n",
       " 4                                        \n",
       " 14                                       \n",
       " 18                                       \n",
       " 23                                       \n",
       " ...               ...               ...  \n",
       " 35782                                    \n",
       " 35783                                    \n",
       " 35784                                    \n",
       " 35785                                    \n",
       " 35786                                    \n",
       " \n",
       " [24473 rows x 19 columns])"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# ============================================================================\n",
    "# πŸŒ‰ BRIDGING CONCEPT ANALYSIS\n",
    "# ============================================================================\n",
    "\n",
    "def show_bridging_concept_analysis():\n",
    "    print(\"πŸŒ‰ THE BRIDGING CONCEPT\")\n",
    "    print(\"=\" * 90)\n",
    "    \n",
    "    companies_with = companies_full[companies_full['required_skills'] != '']\n",
    "    companies_without = companies_full[companies_full['required_skills'] == '']\n",
    "    \n",
    "    print(f\"\\nπŸ“Š DATA REALITY:\")\n",
    "    print(f\"   Total companies: {len(companies_full):,}\")\n",
    "    print(f\"   WITH postings: {len(companies_with):,} ({len(companies_with)/len(companies_full)*100:.1f}%)\")\n",
    "    print(f\"   WITHOUT postings: {len(companies_without):,}\\n\")\n",
    "    \n",
    "    print(\"🎯 THE PROBLEM:\")\n",
    "    print(\"   Companies: 'We are in TECH INDUSTRY'\")\n",
    "    print(\"   Candidates: 'I know PYTHON, AWS'\")\n",
    "    print(\"   β†’ Different languages! 🚫\\n\")\n",
    "    \n",
    "    print(\"πŸŒ‰ THE SOLUTION (BRIDGING):\")\n",
    "    print(\"   1. Extract from postings: 'Need PYTHON developers'\")\n",
    "    print(\"   2. Enrich company profile with skills\")\n",
    "    print(\"   3. Now both speak SKILLS LANGUAGE! βœ…\\n\")\n",
    "    \n",
    "    print(\"=\" * 90)\n",
    "    return companies_with, companies_without\n",
    "\n",
    "# Test\n",
    "show_bridging_concept_analysis()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 18: Export Results to CSV"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸ’Ύ Exporting 50 candidates (top 5 each)...\n",
      "\n",
      "   Processing 1/50...\n",
      "\n",
      "βœ… Exported 129 matches\n",
      "πŸ“„ File: ../results/hrhub_matches.csv\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# ============================================================================\n",
    "# πŸ’Ύ EXPORT MATCHES TO CSV\n",
    "# ============================================================================\n",
    "\n",
    "def export_matches_to_csv(num_candidates=100, top_k=10):\n",
    "    print(f\"πŸ’Ύ Exporting {num_candidates} candidates (top {top_k} each)...\\n\")\n",
    "    \n",
    "    results = []\n",
    "    \n",
    "    for i in range(min(num_candidates, len(candidates))):\n",
    "        if i % 50 == 0:\n",
    "            print(f\"   Processing {i+1}/{num_candidates}...\")\n",
    "        \n",
    "        matches = find_top_matches(i, top_k=top_k)\n",
    "        cand = candidates.iloc[i]\n",
    "        \n",
    "        for rank, (comp_idx, score) in enumerate(matches, 1):\n",
    "            if comp_idx >= len(companies_full):\n",
    "                continue\n",
    "            \n",
    "            company = companies_full.iloc[comp_idx]\n",
    "            \n",
    "            results.append({\n",
    "                'candidate_id': i,\n",
    "                'candidate_category': cand.get('Category', 'N/A'),\n",
    "                'company_id': company.get('company_id', 'N/A'),\n",
    "                'company_name': company.get('name', 'N/A'),\n",
    "                'match_rank': rank,\n",
    "                'similarity_score': round(float(score), 4)\n",
    "            })\n",
    "    \n",
    "    results_df = pd.DataFrame(results)\n",
    "    output_file = f'{Config.RESULTS_PATH}hrhub_matches.csv'\n",
    "    results_df.to_csv(output_file, index=False)\n",
    "    \n",
    "    print(f\"\\nβœ… Exported {len(results_df):,} matches\")\n",
    "    print(f\"πŸ“„ File: {output_file}\\n\")\n",
    "    \n",
    "    return results_df\n",
    "\n",
    "# Export sample\n",
    "matches_df = export_matches_to_csv(num_candidates=50, top_k=5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## πŸ“Š Step 19: Summary\n",
    "\n",
    "### What We Built"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "======================================================================\n",
      "🎯 HRHUB v2.1 - SUMMARY\n",
      "======================================================================\n",
      "\n",
      "βœ… IMPLEMENTED:\n",
      "  1. Zero-Shot Job Classification (Entry/Mid/Senior/Executive)\n",
      "  2. Few-Shot Learning with Examples\n",
      "  3. Structured Skills Extraction (Pydantic schemas)\n",
      "  4. Match Explainability (LLM-generated reasoning)\n",
      "  5. FREE LLM Integration (Hugging Face)\n",
      "  6. Flexible Data Loading (Upload OR Google Drive)\n",
      "\n",
      "πŸ’° COST: $0.00 (completely free!)\n",
      "\n",
      "πŸ“ˆ COURSE ALIGNMENT:\n",
      "  βœ… LLMs for structured output\n",
      "  βœ… Pydantic schemas\n",
      "  βœ… Classification pipelines\n",
      "  βœ… Zero-shot & few-shot learning\n",
      "  βœ… JSON extraction\n",
      "  βœ… Transformer architecture (embeddings)\n",
      "  βœ… API deployment strategies\n",
      "\n",
      "======================================================================\n",
      "πŸš€ READY TO MOVE TO VS CODE!\n",
      "======================================================================\n"
     ]
    }
   ],
   "source": [
    "print(\"=\"*70)\n",
    "print(\"🎯 HRHUB v2.1 - SUMMARY\")\n",
    "print(\"=\"*70)\n",
    "print(\"\")\n",
    "print(\"βœ… IMPLEMENTED:\")\n",
    "print(\"  1. Zero-Shot Job Classification (Entry/Mid/Senior/Executive)\")\n",
    "print(\"  2. Few-Shot Learning with Examples\")\n",
    "print(\"  3. Structured Skills Extraction (Pydantic schemas)\")\n",
    "print(\"  4. Match Explainability (LLM-generated reasoning)\")\n",
    "print(\"  5. FREE LLM Integration (Hugging Face)\")\n",
    "print(\"  6. Flexible Data Loading (Upload OR Google Drive)\")\n",
    "print(\"\")\n",
    "print(\"πŸ’° COST: $0.00 (completely free!)\")\n",
    "print(\"\")\n",
    "print(\"πŸ“ˆ COURSE ALIGNMENT:\")\n",
    "print(\"  βœ… LLMs for structured output\")\n",
    "print(\"  βœ… Pydantic schemas\")\n",
    "print(\"  βœ… Classification pipelines\")\n",
    "print(\"  βœ… Zero-shot & few-shot learning\")\n",
    "print(\"  βœ… JSON extraction\")\n",
    "print(\"  βœ… Transformer architecture (embeddings)\")\n",
    "print(\"  βœ… API deployment strategies\")\n",
    "print(\"\")\n",
    "print(\"=\"*70)\n",
    "print(\"πŸš€ READY TO MOVE TO VS CODE!\")\n",
    "print(\"=\"*70)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}