File size: 68,084 Bytes
03582cd
 
 
 
 
 
8c0497d
 
e60de6e
 
 
 
 
9ea8425
8c0497d
e518da9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c0497d
 
 
8d94714
 
 
 
 
8c0497d
92adc42
 
be82510
 
b950432
be82510
b950432
be82510
 
 
 
b950432
be82510
e518da9
be82510
 
 
1735116
16bd478
be82510
e518da9
be82510
 
 
1735116
16bd478
be82510
e518da9
be82510
 
 
 
b950432
be82510
e518da9
be82510
 
 
e5fa566
b950432
be82510
e518da9
be82510
 
 
92adc42
8d94714
8c0497d
 
 
 
 
 
8d94714
 
 
 
 
 
 
 
 
8c0497d
 
8d94714
 
8c0497d
8d94714
8c0497d
 
8d94714
8c0497d
92adc42
 
8d94714
03582cd
 
 
 
 
 
 
 
 
 
 
 
 
 
92adc42
8d94714
8c0497d
8d94714
8c0497d
8d94714
8c0497d
 
8d94714
8c0497d
 
 
 
 
5d87b03
 
8c0497d
 
8d94714
 
 
 
 
 
8c0497d
 
 
8d94714
8c0497d
 
 
 
 
e518da9
8c0497d
 
 
 
 
 
 
 
 
 
 
 
 
 
8d94714
8c0497d
 
 
 
5d87b03
8c0497d
 
8d94714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c0497d
e518da9
8c0497d
 
 
e0dce9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d46fb
e0dce9c
 
 
 
 
 
 
 
 
 
 
e518da9
e0dce9c
 
 
 
 
 
 
 
 
 
 
 
 
8c0497d
5d87b03
8c0497d
 
be82510
8c0497d
 
5d87b03
 
8c0497d
8d94714
 
 
8c0497d
8d94714
8c0497d
 
 
8d94714
8c0497d
8d94714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c0497d
 
 
 
 
 
 
e518da9
 
8c0497d
 
 
 
 
 
 
 
 
 
 
e518da9
8c0497d
7547cff
8c0497d
 
 
8d94714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c0497d
 
 
 
 
 
 
e518da9
 
8c0497d
 
 
 
 
 
 
 
 
 
 
e518da9
8c0497d
7547cff
8c0497d
 
 
8d94714
 
 
 
 
 
 
 
 
 
 
 
8c0497d
 
 
 
 
 
 
e518da9
 
8c0497d
 
 
 
 
 
 
 
 
 
 
 
 
 
e518da9
8c0497d
 
 
 
 
 
 
e518da9
8c0497d
 
8d94714
 
 
8c0497d
 
 
 
8d94714
 
 
 
 
8c0497d
 
 
 
8d94714
 
 
 
 
 
 
8c0497d
 
 
 
 
 
e518da9
8c0497d
 
8d94714
 
 
 
8c0497d
8d94714
8c0497d
e21ebce
 
468f84a
 
e21ebce
 
 
468f84a
 
 
 
 
 
 
 
 
 
 
 
 
 
e21ebce
 
 
468f84a
 
 
 
 
 
 
 
e21ebce
468f84a
e21ebce
468f84a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21ebce
 
 
 
 
 
 
 
 
 
 
 
1b63dea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fde3de2
1b63dea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a04f37
 
 
 
fde3de2
1b63dea
fde3de2
 
 
 
 
 
 
 
 
46c024e
fde3de2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b63dea
fde3de2
 
1b63dea
 
fde3de2
 
 
 
 
 
 
 
 
 
 
2a04f37
 
 
 
fde3de2
 
 
e21ebce
92adc42
970a84f
 
60b7707
 
03582cd
 
60b7707
 
 
 
 
 
 
 
 
 
970a84f
 
60b7707
 
03582cd
 
8d94714
8c0497d
e518da9
60b7707
 
 
 
 
 
 
 
 
 
970a84f
 
60b7707
 
 
 
 
 
 
 
 
32610c7
60b7707
 
 
 
 
 
 
 
32610c7
60b7707
32610c7
 
8d94714
8c0497d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60b7707
32610c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970a84f
 
 
 
 
 
 
 
43d46fb
970a84f
 
43d46fb
32610c7
970a84f
 
60b7707
970a84f
 
 
 
 
43d46fb
970a84f
32610c7
970a84f
 
 
f70cd41
478cab7
19dfc29
60b7707
 
 
 
 
1b63dea
32610c7
5131f14
fde3de2
dbda7c1
19dfc29
970a84f
60b7707
ac17970
03582cd
ac17970
970a84f
 
60b7707
 
 
 
 
 
 
 
 
 
970a84f
 
60b7707
32610c7
 
92adc42
f2ffdef
b950432
 
 
 
 
 
4716007
 
 
 
 
 
 
 
 
 
 
 
 
32610c7
 
 
 
 
 
 
 
 
ec96017
 
32610c7
 
 
 
 
 
 
b950432
 
 
32610c7
 
 
 
 
 
 
 
 
 
b950432
f2ffdef
4716007
b950432
 
ec96017
b950432
 
43d46fb
32610c7
 
 
f70cd41
b950432
f70cd41
b950432
f2ffdef
b950432
 
 
43d46fb
32610c7
 
 
f70cd41
32610c7
4716007
f70cd41
32610c7
b950432
ec96017
b950432
46c024e
 
 
 
 
f2ffdef
b950432
 
 
 
32610c7
b950432
 
 
 
fb098b5
ec96017
fb098b5
32610c7
43d46fb
42ea09e
32610c7
 
fb098b5
43d46fb
 
 
 
 
 
 
 
 
 
 
91721d4
 
 
 
 
 
f70cd41
 
 
43d46fb
f70cd41
43d46fb
 
 
 
 
f70cd41
43d46fb
32610c7
f70cd41
91721d4
43d46fb
f70cd41
 
43d46fb
 
f70cd41
43d46fb
f70cd41
43d46fb
 
 
 
32610c7
f70cd41
91721d4
43d46fb
91721d4
43d46fb
 
 
 
91721d4
32610c7
 
91721d4
f70cd41
 
91721d4
 
 
f70cd41
 
 
43d46fb
f70cd41
43d46fb
 
 
 
 
f70cd41
91721d4
b950432
 
 
 
 
 
 
 
32610c7
b950432
 
43d46fb
729d184
b950432
 
 
729d184
ec96017
b950432
 
 
 
 
 
 
 
 
 
 
 
 
ec96017
b950432
 
 
 
 
 
 
 
f2ffdef
32610c7
92adc42
 
89c7d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35e209c
4c2a32a
 
 
32610c7
4c2a32a
 
 
32610c7
 
 
 
 
4c2a32a
32610c7
4c2a32a
32610c7
 
 
 
 
 
 
 
 
 
 
 
4c2a32a
 
35e209c
49bc97e
35e209c
 
 
 
89c7d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21ebce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c2a32a
 
 
 
 
 
32610c7
 
e21ebce
32610c7
 
 
 
 
 
e21ebce
 
468f84a
e21ebce
 
 
468f84a
e21ebce
468f84a
 
4c2a32a
 
 
e21ebce
 
 
468f84a
 
e21ebce
 
468f84a
e21ebce
fde3de2
e21ebce
468f84a
e21ebce
468f84a
 
 
 
 
 
 
e21ebce
 
 
468f84a
e21ebce
468f84a
 
e21ebce
 
468f84a
 
 
 
e21ebce
468f84a
 
 
 
 
 
 
 
 
 
 
e21ebce
 
468f84a
e21ebce
 
468f84a
 
 
 
 
e21ebce
468f84a
e21ebce
468f84a
 
 
 
 
 
 
e21ebce
 
468f84a
 
 
 
 
 
 
 
e21ebce
 
468f84a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21ebce
 
 
468f84a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21ebce
1b63dea
 
 
 
 
 
 
 
 
 
 
 
 
 
fde3de2
1b63dea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fde3de2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b63dea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21ebce
89c7d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32610c7
 
 
 
 
 
 
 
 
89c7d5b
 
 
 
 
 
 
 
 
468f84a
 
 
4c2a32a
468f84a
 
 
 
 
 
 
 
 
 
 
1b63dea
 
 
 
fde3de2
 
 
 
1b63dea
 
 
 
89c7d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c463ffe
89c7d5b
 
e21ebce
 
 
dd8eda2
e21ebce
 
729d184
e21ebce
 
5131f14
e21ebce
 
5131f14
e21ebce
 
dd8eda2
e21ebce
 
 
89c7d5b
03582cd
 
b950432
970a84f
b950432
89c7d5b
729d184
89c7d5b
 
 
8e5c463
 
9c6f22a
 
ec8a468
89c7d5b
9c6f22a
 
 
 
1b63dea
5131f14
8e5c463
03582cd
5131f14
9c6f22a
fde3de2
 
 
 
32610c7
5131f14
9c6f22a
 
 
 
 
5131f14
 
1b63dea
49bc97e
8e5c463
 
fde3de2
5131f14
 
ec8a468
fde3de2
89c7d5b
 
 
 
 
42ea09e
89c7d5b
 
8e5c463
 
 
 
e518da9
89c7d5b
e518da9
 
 
32610c7
ac17970
03582cd
 
 
8e5c463
 
 
 
 
 
 
 
 
 
32610c7
7f10cf8
8e5c463
03582cd
 
f2ffdef
 
b950432
7f10cf8
b950432
970a84f
f2ffdef
 
03582cd
49bc97e
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
import gradio as gr
import pdfplumber
import pandas as pd
import re
import warnings
import logging
import os
from dotenv import load_dotenv
import json
from concurrent.futures import ThreadPoolExecutor
from typing import List, Dict, Optional
import traceback
import time
import openai

# Debugging setup
DEBUG = True
debug_messages = []

def log_debug(message):
    """Log debug messages and keep last 20 entries"""
    if DEBUG:
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
        full_message = f"[{timestamp}] {message}"
        debug_messages.append(full_message)
        print(full_message)  # Print to console
        # Keep only the last 20 messages
        if len(debug_messages) > 20:
            debug_messages.pop(0)
        return "\n".join(debug_messages)
    return ""

# Initialize debug logging
log_debug("Application starting...")

# Load environment variables
load_dotenv()

# Configure logging for pdfminer
logging.getLogger('pdfminer').setLevel(logging.ERROR)

# Suppress specific warnings
warnings.filterwarnings("ignore", category=UserWarning, message="CropBox.*")

 
# ================= DataFrame initializations =================
try:
    job_families_df = pd.read_csv("job_families1.csv", on_bad_lines='skip')
    log_debug(f"Reading {len(job_families_df)} job_families")
except Exception as e:
    log_debug(f"Error reading job_families1.csv: {e}")
    job_families_df = pd.DataFrame()  # Fallback to an empty DataFrame or handle the error appropriately

try:
    occupational_groups_df = pd.read_csv("occupational_groups.csv", on_bad_lines='skip')
    log_debug(f"Reading  {len(occupational_groups_df)} occupational_groups")
except Exception as e:
    log_debug(f"Error reading occupational_groups.csv: {e}")
    occupational_groups_df = pd.DataFrame()  # Fallback to an empty DataFrame or handle the error appropriately

try:
    esco_df = pd.read_csv("ISCOGroups_en.csv", on_bad_lines='skip', dtype={'code': str}  ) # Force 'code' to be read as string
    log_debug(f"Reading  {len(esco_df)}  esco groups")
except Exception as e:
    log_debug(f"Error reading ISCOGroups_en.csv: {e}")
    esco_df = pd.DataFrame()  # Fallback to an empty DataFrame or handle the error appropriately

try:
    esco_level5_df = pd.read_csv("occupations_en.csv", on_bad_lines='skip',  dtype={'code': str, 'iscoGroup': str, }  ) # Force 'code' to be read as string
    log_debug(f"Reading  {len(esco_level5_df)} esco_level5")
except Exception as e:
    log_debug(f"Error reading occupations_en.csv: {e}")
    esco_level5_df = pd.DataFrame()  # Fallback to an empty DataFrame or handle the error appropriately    

try:
    esco_skill_df = pd.read_csv("skills_en.csv", on_bad_lines='skip')
    log_debug(f"Reading  {len(esco_skill_df)}  esco_skill")
except Exception as e:
    log_debug(f"Error reading skills_en.csv: {e}")
    esco_skill_df = pd.DataFrame()  # Fallback to an empty DataFrame or handle the error appropriately
        
try:
    esco_skill_map_df = pd.read_csv("occupationSkillRelations_en.csv", on_bad_lines='skip')
    log_debug(f"Reading  {len(esco_skill_map_df)} esco_skill_map")
except Exception as e:
    log_debug(f"Error reading occupationSkillRelations_en.csv: {e}")
    esco_skill_map_df = pd.DataFrame()  # Fallback to an empty DataFrame or handle the error appropriately


# ================= LLM API =================
def initialize_openai_client():
    try:
        client = openai.AzureOpenAI(
            api_key=os.getenv("AZURE_OPENAI_API_KEY"),
            azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
            api_version=os.getenv("OPENAI_API_VERSION"),
        )
        return client
    except Exception as e:
        raise Exception(f"Failed to initialize OpenAI client: {e}")

client = initialize_openai_client()

def gpt_call(system_prompt: str, user_prompt: str) -> str:
    try:
        response = client.chat.completions.create(
            model=os.getenv("AZURE_DEPLOYMENT_NAME"),
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt}
            ],
            temperature=0.3
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        return f"ERROR: {e}"
        
# ================= Extract text =================
def extract_text_from_pdf(pdf_path: str) -> str:
    text = ""
    with pdfplumber.open(pdf_path) as pdf:
        for page in pdf.pages:
            page_text = page.extract_text()
            if page_text:
                text += page_text + "\n"
            for table in page.extract_tables():
                for row in table:
                    for cell in row:
                        if isinstance(cell, str):
                            text += cell + " "
                    text += "\n"
    return text

# ================= AI Functions =================
def extract_section_from_pdf(full_text: str, section_title: str) -> str:
    user_prompt = f"""
    Carefully evaluate the provided position description (PD) document and extract the content of the section titled "{section_title}" from the following text.
    Return only the content of the section, without the title.
    If the section cannot be found or explicitly mentioned in the text, use "N/A" as the default value.
    Do not repeat in the extracted text the name of the section.
    Extract precisely all the related text.
    Text of the position description:
    {full_text}
    Section to identify: "{section_title}":
    """
    return gpt_call("You are an HR expert working for IOM.", user_prompt)

def classify_job_family(responsibilities: List[str]) -> str:    

    job_family_list = "\n".join(f"- {row['Job_family']}: {row['Job_subfamily']}" for _, row in job_families_df.iterrows())
    user_prompt = f"""
    Here is a list of job responsibilities:
    {responsibilities}
    Here is a list of Job families:
    {job_family_list}
    Based on the responsibilities, suggest the most relevant job family and subfamily from the list above.
    **Important:**
    - Return ONLY the job family, nothing else.
    - The job family should be exactly as shown in the list.
    - Do not include any additional text or explanation.
    """
    return gpt_call("Suggest job family and subfamily based on responsibilities.", user_prompt)

def get_level_CCOG_info(df, code, level_name):
    matches = df[df['code'] == code]
    if len(matches) == 0:
        log_debug(f"Warning: No {level_name} found for CCOG code {code}")
        return {
            f'{level_name}_CCOG_code': code,
            f'{level_name}_CCOG_name': 'UNKNOWN',
            f'{level_name}_CCOG_desc': 'No matching occupation found'
        }
    info = matches.iloc[0]
    return {
        f'{level_name}_CCOG_code': code,
        f'{level_name}_CCOG_name': info['occupation'],
        f'{level_name}_CCOG_desc': info.get('occupation_description', '')
    }

def code_sanitize(input_string, valid_codes):
    for code in valid_codes:
        if code in input_string:
            return code
    return None

def classify_occupational_group_by_level(responsibilities: List[str]) -> dict:

    result = {}
    try:
        for level in range(1, 5):
            level_df = occupational_groups_df[occupational_groups_df['level'] == f"Level {level}"]
            if level > 1:
                prev_level_code = result[f'Level_{level-1}_CCOG_code']
                level_df = level_df[level_df['code'].str.startswith(prev_level_code)]
            job_occupation_list = "\n".join(f"- {row['code']}: {row['occupation']} - {row.get('occupation_description', '')}" for _, row in level_df.iterrows())
            list_output = level_df["code"].tolist()
            user_prompt = f"""
            Here is a list of job responsibilities:
            {responsibilities}
            Here is a list of level {level} Occupation classifications:
            {job_occupation_list}
            Based on the responsibilities, suggest the most relevant level {level} Occupation code from within this list: {', '.join(map(str, list_output))}.
            **Important:**
            - Return ONLY the code, nothing else.
            - The code should be exactly as shown in the list.
            - Do not include any additional text or explanation.
            """
            level_code = gpt_call(f"Identify level {level} occupational group", user_prompt).strip()
            level_code = code_sanitize(level_code, list_output)
            result.update(get_level_CCOG_info(level_df, level_code, f'Level_{level}'))
    except Exception as e:
        log_debug(f"Error during classification: {str(e)}")
        result['error'] = str(e)
    return result


 
def classify_esco_by_hierarchical_level(responsibilities: List[str]) -> dict:
    """
    Classifies job responsibilities into occupational groups at 4 levels,
    [European Skills, Competences, Qualifications, and Occupations (ESCO)](https://esco.ec.europa.eu/en)
    returning codes, names, and descriptions for each level.
    Args:
        responsibilities: List of job responsibility strings
    Returns:
        Dictionary containing classification information or error message
    """



    result = {}

    ######################## Level 1 ###################
    # Get all top-level codes (single character/digit)
    top_level_codes = sorted({
        code for code in esco_df['code']
        if len(code) == 1 and code.isalnum()
    })

    level1_code = None
    if top_level_codes:
        level1_df = esco_df[esco_df['code'].isin(top_level_codes)]
        job_occupation_list = "\n".join(f"- {row['code']}: {row['preferredLabel']} - {row['description']}"
                                        for _, row in level1_df.iterrows())
        list1_output = level1_df["code"].tolist()  # Convert Series to list
        list1 = ", ".join(map(str, list1_output))  # Join elements with comma

    user_prompt1 = f"""
    Here is a list of job responsibilities:
    {responsibilities}

    Select the most relevant top-level code from these options:
    {job_occupation_list}

    Based on the responsibilities, suggest the most relevant level 1 Occupation code from within this list: {list1}.
        **Important:**
        - Return ONLY the code, nothing else.
        - The code should be exactly as shown in the list.
        - Do not include any additional text or explanation.
    """
    level1_code = gpt_call("Identify top-level occupational group", user_prompt1).strip()
    level1_code = code_sanitize(level1_code, list1_output)
    result.update(get_level_ESCO_info(level1_df, level1_code, 'Level_1'))

    ######################## Level 2 ###################

    level2_code = None
    if level1_code:
        level2_df = esco_df[
            (esco_df['code'].str.startswith(level1_code)) & (esco_df['code'].str.len() == len(level1_code) + 1)
        ]
        if not level2_df.empty:
            level2_options = "\n".join(f"- {row['code']}: {row['preferredLabel']} - {row['description']}"
                                        for _, row in level2_df.iterrows())
        list2_output = level2_df["code"].tolist()  # Convert Series to list
        list2 = ", ".join(map(str, list2_output))  # Join elements with comma

        user_prompt2 = f"""
    Here is a list of job responsibilities:
    {responsibilities}

    Here is a list of level 2 Occupation classifications within {level1_code}:
    {level2_options}

    Based on the responsibilities, suggest the most relevant level 2 Occupation code from within this list: {list2}.
        **Important:**
        - Return ONLY the code, nothing else.
        - The code should be exactly as shown in the list.
        - Do not include any additional text or explanation.
    """
        level2_code = gpt_call("Identify second-level occupational group", user_prompt2).strip()
        level2_code = code_sanitize(level2_code, list2_output)
        result.update(get_level_ESCO_info(level2_df, level2_code, 'Level_2'))

    ######################## Level 3 ###################
    level3_code = None
    if level2_code:
        level3_df = esco_df[
            (esco_df['code'].str.startswith(level2_code)) & (esco_df['code'].str.len() == len(level2_code) + 1)
        ]
        if not level3_df.empty:
            level3_options = "\n".join(f"- {row['code']}: {row['preferredLabel']} - {row['description']}"
                                        for _, row in level3_df.iterrows())
        list3_output = level3_df["code"].tolist()  # Convert Series to list
        list3 = ", ".join(map(str, list3_output))  # Join elements with comma

        user_prompt3 = f"""
    Here is a list of job responsibilities:
    {responsibilities}

    Here is a list of level 3 Occupation classifications within {level2_code}:
    {level3_options}

    Based on the responsibilities, suggest the most relevant level 3 Occupation code from within this list: {list3}.

        **Important:**
        - Return ONLY the code, nothing else.
        - The code should be exactly as shown in the list.
        - Do not include any additional text or explanation.

    """
        level3_code = gpt_call("Identify third-level occupational group", user_prompt3).strip()
        level3_code = code_sanitize(level3_code, list3_output)
        result.update(get_level_ESCO_info(level3_df, level3_code, 'Level_3'))

    ######################## Level 4 ###################
    level4_code = None
    if level3_code:
        level4_df = esco_df[
            (esco_df['code'].str.startswith(level3_code)) & (esco_df['code'].str.len() == len(level3_code) + 1)
        ]
        if not level4_df.empty:
            level4_options = "\n".join(f"- {row['code']}: {row['preferredLabel']} - {row['description']}"
                                        for _, row in level4_df.iterrows())
        list4_output = level4_df["code"].tolist()  # Convert Series to list
        list4 = ", ".join(map(str, list4_output))  # Join elements with comma
        user_prompt4 = f"""
    Here is a list of job responsibilities:
    {responsibilities}

    Here is a list of level 4 Occupation classifications within {level3_code}:
    {level4_options}

    Based on the responsibilities, suggest the most relevant level 4 Occupation code from within this list: {list4}.
        **Important:**
        - Return ONLY the code, nothing else.
        - The code should be exactly as shown in the list.
        - Do not include any additional text or explanation.
    """

        level4_code = gpt_call("Identify fourth-level occupational group", user_prompt4).strip()
        level4_code = code_sanitize(level4_code, list4_output)
        result.update(get_level_ESCO_info(level4_df, level4_code, 'Level_4'))

    ######################## Level 5 ###################
    level5_code = None
    if level4_code:
        level5_df = esco_level5_df[
            (esco_level5_df['iscoGroup'].str.startswith(level4_code))
        ]
        if not level5_df.empty:
            level5_options = "\n".join(f"- {row['code']}: {row['preferredLabel']} - {row['description']}"
                                        for _, row in level5_df.iterrows())

        list5_output = level5_df["code"].tolist()  # Convert Series to list
        list5 = ", ".join(map(str, list5_output))  # Join elements with comma
        user_prompt5 = f"""
    Here is a list of job responsibilities:
    {responsibilities}

    Here is a list of level 4 Occupation classifications within {level4_code}:
    {level5_options}

    Based on the responsibilities, suggest the most relevant level 4 Occupation code from within this list: {list5}.
        **Important:**
        - Return ONLY the code as stated in the provided list, nothing else.
        - The code should be exactly as shown in the list.
        - Do not include any additional text, occupation code or explanation.
    """

        level5_code = gpt_call("Identify fifth-level occupational group", user_prompt5).strip()
        # Handle the case where the LLM might return just the code part
        level5_code = code_sanitize(level5_code, list5_output)
        log_debug(f"Level 5 ESCO code: {level5_code}")
        result.update(get_level_ESCO_info(level5_df, level5_code, 'Level_5'))

    ## Et voila!!
    return result



def get_level_ESCO_info(df, code, level_name):
    """Helper function to get level info with error handling"""
    matches = df[df['code'] == code]
    if len(matches) == 0:
        log_debug(f"Warning: No {level_name} found for ESCO code {code}")
        return {
            f'{level_name}_ESCO_code': code,
            f'{level_name}_ESCO_name': 'UNKNOWN',
            f'{level_name}_ESCO_desc': 'No matching occupation found'
        }
    info = matches.iloc[0]
    return {
        f'{level_name}_ESCO_code': code,
        f'{level_name}_ESCO_name': info['preferredLabel'],
        f'{level_name}_ESCO_desc': info.get('description', '')
    }


def get_skills_info_esco(Level_5_code):
 
    matches = esco_level5_df[esco_level5_df['code'] == Level_5_code]
    conceptUris = matches['conceptUri'].values.tolist()
         
    skills = esco_skill_map_df[esco_skill_map_df['occupationUri'].isin(conceptUris)]
    skillUris = skills['skillUri'].values.tolist()

    
    thisskillslist = esco_skill_df[esco_skill_df['conceptUri'].isin(skillUris)]
    result = thisskillslist[['preferredLabel', 'conceptUri', 'description']].drop_duplicates()
    result = result.rename(columns={'preferredLabel': 'skill_name', 'description': 'skill_description', 'conceptUri': 'skill_code'})
    return result

def review_skills(Level_5_code: str, top_n: int = 10) -> List[Dict[str, str]]:
    matches = esco_level5_df[esco_level5_df['code'] == Level_5_code]
    esco_occup = matches['preferredLabel'].values.tolist()
    skill_filtered = get_skills_info_esco(Level_5_code)
    skill_filtered_options = "\n".join(f"- {row['skill_code']}: {row['skill_name']} - {row['skill_description']}" for _, row in skill_filtered.iterrows())
    prompt = f"""
    Here is a list of skills:
    {skill_filtered_options}
    Filter the skills that are relevant in the context of the work of the International Organisation for Migration.
    Ensure that skills are relevant in the context of a {esco_occup} working for a non-profit public organization.
    Required JSON structure:
    {{
        "skills": [
            {{
                "skill_name": "string",
                "skill_description": "string",
                "skill_code": "string"
            }}
        ]
    }}
    **Important:**
    - Do not duplicate any records of skills
    - Keep only the 10 most relevant skills
    - Return ONLY the JSON object with no other text
    - Use double quotes for all strings
    - No trailing commas in arrays/objects
    - No markdown formatting (no ```json)
    - No text before or after the JSON
    - Escape all special characters in strings
    - Ensure all brackets are properly closed
    - No trailing commas in arrays/objects, especially before closing brackets
    """
    raw = gpt_call("You are an HR expert working for the International Organisation for Migration and with in-depth knowledge of the European Skills, Competences, Qualifications and Occupations. Extract skills required for this position.", prompt)
    json_text = _extract_json(raw)
    if not json_text:
        return []
    try:
        result = json.loads(json_text)
        skills = result.get("skills", [])
    except json.JSONDecodeError as e:
        log_debug(f"❌ JSON Skills parsing error: {e}")
        log_debug(f"🔍 Problematic JSON Skills: {json_text}")
        return []
    validated_skills = []
    for skill in skills:
        try:
            validated = {
                "skill_name": str(skill["skill_name"]).strip(),
                "skill_description": str(skill["skill_description"]).strip(),
                "skill_code": str(skill["skill_code"]).strip()
            }
            validated_skills.append(validated)
        except (KeyError, TypeError) as e:
            log_debug(f"⚠️ Skipping invalid skill: {skill}. Error: {e}")
            continue
    return validated_skills[:top_n]

def extract_skills(responsibilities: List[str], top_n: int = 10) -> List[Dict[str, str]]:
    prompt = f"""
    Here is a list of job responsibilities:
    {responsibilities}
    List the required skills and knowledge as bullet points (without numbers) using ESCO-style terms.
    For each Skill:
    1. skill_name: precise skills name as used in ESCO framework
    2. skill_description: add the long description as mentioned in ESCO framework
    3. skill_code: include the detailed corresponding ESCO code for that skill.
    Required JSON structure:
    {{
        "skills": [
            {{
                "skill_name": "string",
                "skill_description": "string",
                "skill_code": "string"
            }}
        ]
    }}
    **Important:**
    - Return ONLY the JSON object with no other text
    - Use double quotes for all strings
    - No trailing commas in arrays/objects
    - No markdown formatting (no ```json)
    - No text before or after the JSON
    - Escape all special characters in strings
    - Ensure all brackets are properly closed
    """
    raw = gpt_call("You are an HR expert working for the International Organisation for Migration and with in-depth knowledge of the European Skills, Competences, Qualifications and Occupations. Extract skills required for this position.", prompt)
    json_text = _extract_json(raw)
    if not json_text:
        return []
    try:
        result = json.loads(json_text)
        skills = result.get("skills", [])
    except json.JSONDecodeError as e:
        log_debug(f"❌ JSON Skills extrac parsing error: {e}")
        log_debug(f"🔍 Problematic JSON Skills extract: {json_text}")
        return []
    validated_skills = []
    for skill in skills:
        try:
            validated = {
                "skill_name": str(skill["skill_name"]).strip(),
                "skill_description": str(skill["skill_description"]).strip(),
                "skill_code": str(skill["skill_code"]).strip()
            }
            validated_skills.append(validated)
        except (KeyError, TypeError) as e:
            log_debug(f"⚠️ Skipping invalid skill extract: {skill}. Error: {e}")
            continue
    return validated_skills[:top_n]

def map_proficiency_and_assessment(skills: List[str], responsibilities: List[str]) -> List[Dict]:
    prompt = f"""
    Here is a list of job responsibilities: {responsibilities} that have been associated with the following skills: {skills}
    For each skill, accounting for the context defined within the responsibilities, return a JSON object with:
        - skill_name: the name of the skill
        - importance: essential or optional
        - type: "skill/competence" or "knowledge"
        - proficiency_level: Basic, Intermediate, or Advanced
        - distinctive_elements: what specific and distinctive elements are required at this defined proficiency level?
        - resume_signals: what to look for in a resume to assess this skill?
        - assessment_method: what is the preferred assessment method to accurately assess this skill?
    Respond ONLY with a list of dictionaries in valid JSON.
    Use double quotes for all strings. No markdown, no commentary, no trailing commas.
    """
    raw = gpt_call("Define proficiency level and assessment for each skill.", prompt)
    json_text = _extract_json_array(raw)
    if not json_text:
        return []
    try:
        results = json.loads(json_text)
    except json.JSONDecodeError as e:
        log_debug(f"❌ JSON proficiency parsing error: {e}")
        log_debug(f"🔍 Problematic JSON proficiency: {json_text}")
        return []
    validated = []
    for item in results:
        try:
            validated.append({
                "skill_name": str(item["skill_name"]).strip(),
                "importance": item["importance"].strip().lower(),
                "type": item["type"].strip().lower(),
                "proficiency_level": item["proficiency_level"].strip().capitalize(),
                "distinctive_elements": item["distinctive_elements"].strip(),
                "resume_signals": item["resume_signals"].strip(),
                "assessment_method": item["assessment_method"].strip()
            })
        except (KeyError, TypeError) as e:
            log_debug(f"⚠️ Skipping invalid profiency item: {item}. Error: {e}")
            continue
    return validated

def _extract_json_array(raw: str) -> str:
    json_start = raw.find('[')
    json_end = raw.rfind(']') + 1
    if json_start == -1 or json_end == 0:
        log_debug(f"❌ No JSON array found in response: {raw}")
        return ""
    json_text = raw[json_start:json_end]
    json_text = re.sub(r',\s*([}\]])', r'\1', json_text)
    json_text = re.sub(r'[\n\r\t]', ' ', json_text)
    json_text = re.sub(r'(?<!\\)"', '"', json_text)
    return json_text

def extract_qualification(responsibilities: List[str]) -> List[str]:
    prompt = f"""
    Here is a list of job responsibilities: {responsibilities}
    Infer the required level within the European Qualifications Framework (EQF) to implement them.
    Identify the potential diplomas to testify such qualification
    """
    raw = gpt_call("You are an HR expert that excel in developing competency-based interview questions.", prompt)
    return [line.strip("-• ").strip() for line in raw.splitlines() if line.strip()]

def build_interview(responsibilities: List[str], skill_assess: List[str]) -> List[str]:
    prompt = f"""
    Here is a list of job responsibilities: {responsibilities} and related skills: {skill_assess}
    Output: A structured 40-minute interview with:
        Opening questions (5 min)
        Core competency-based questions (30 min, 5-6 questions)
        Closing & candidate questions (5 min)
    """
    raw = gpt_call("You are an HR expert that excel in developing competency-based interview questions.", prompt)
    return [line.strip("-• ").strip() for line in raw.splitlines() if line.strip()]

def _extract_json(raw: str) -> str:
    json_start = raw.find('{')
    json_end = raw.rfind('}') + 1
    if json_start == -1 or json_end == 0:
        log_debug(f"❌ No JSON found in response: {raw}")
        return ""
    json_text = raw[json_start:json_end]
    json_text = re.sub(r',\s*([}\]])', r'\1', json_text)
    json_text = re.sub(r'[\n\r\t]', ' ', json_text)
    json_text = re.sub(r'\s{2,}', ' ', json_text)
    json_text = re.sub(r'\\(?!["\\/bfnrtu])', r'\\\\', json_text)
    json_text = json_text.strip()
    return json_text

# ================= Format Skills Visualisation =================
def format_skill_cards(skills_data):
    if not skills_data or not isinstance(skills_data, list):
        return "<div class='skills-container'><p>No skills data available</p></div>"
    
    cards = []
    for skill in skills_data:
        if not isinstance(skill, dict):
            continue
            
        # Safely get all fields with fallbacks
        skill_name = skill.get('skill_name', 'Unnamed Skill')
        skill_code = skill.get('skill_code', 'N/A')
        description = skill.get('skill_description', 'No description available')
        skill_type = skill.get('type', '').capitalize()
        importance = skill.get('importance', '').capitalize()
        proficiency = skill.get('proficiency_level', '').capitalize()
        distinctive = skill.get('distinctive_elements', 'Not specified')
        resume_signals = skill.get('resume_signals', 'Not specified')
        assessment = skill.get('assessment_method', 'Not specified')

        card = f"""
        <div class='skill-card'>
            <div class='skill-header'>
                <div class='skill-title'>
                    <h3>{skill_name}</h3>
                    <span class='skill-code'>Code: {skill_code}</span>
                </div>
                <div class='skill-pills'>
                    <span class='skill-pill type-{skill.get("type", "").lower()}'>{skill_type}</span>
                    <span class='skill-pill importance-{skill.get("importance", "").lower()}'>{importance}</span>
                </div>
            </div>
            
            <div class='skill-body'>
                <div class='skill-description'>
                    <p>{description}</p>
                </div>
                
                <div class='skill-details'>
                    <div class='detail-group'>
                        <label>Proficiency Level:</label>
                        <div class='proficiency-bar'>
                            <progress value={get_progress_value(skill.get("proficiency_level"))} max="3"></progress>
                            <span>{proficiency}</span>
                        </div>
                    </div>
                    
                    <div class='detail-group'>
                        <label>Distinctive Elements:</label>
                        <p class='detail-content'>{distinctive}</p>
                    </div>
                    
                    <div class='detail-group'>
                        <label>Resume Signals:</label>
                        <p class='detail-content'>{resume_signals}</p>
                    </div>
                    
                    <div class='detail-group'>
                        <label>Assessment Method:</label>
                        <p class='detail-content'>{assessment}</p>
                    </div>
                </div>
            </div>
        </div>
        """
        cards.append(card)
    
    return f"<div class='skills-container'>{''.join(cards)}</div>"

def get_progress_value(level):
    level_map = {"basic": 1, "intermediate": 2, "advanced": 3}
    return str(level_map.get(level.lower(), 1))

# ================= Format CCOG =================
def format_ccog_card(ccog_data):
    if not ccog_data or not isinstance(ccog_data, dict):
        return "<div class='ccog-container'><p>No CCOG classification data available</p></div>"
    
    # Extract level data
    levels = []
    for i in range(1, 5):
        level_data = {
            'code': ccog_data.get(f'Level_{i}_CCOG_code'),
            'name': ccog_data.get(f'Level_{i}_CCOG_name'),
            'desc': ccog_data.get(f'Level_{i}_CCOG_desc')
        }
        if level_data['code'] or level_data['name']:
            levels.append(level_data)
    
    if not levels:
        return "<div class='ccog-container'><p>No valid CCOG classification found</p></div>"
    
    # Build the card
    card = f"""
    <div class='ccog-card'>
        <div class='ccog-header'>
            <h3>UN Common Classification of Occupational Groups</h3>
        </div>
        
        <div class='ccog-levels'>
    """
    
    for i, level in enumerate(levels, 1):
        card += f"""
            <div class='ccog-level {'active' if level['desc'] else 'inactive'}'>
                <div class='level-header'>
                    <span class='level-number'>Level {i}</span>
                    <span class='level-code'>{level['code'] or 'N/A'}</span>
                </div>
                <div class='level-name'>{level['name'] or 'Not classified'}</div>
                {f"<div class='level-desc'>{level['desc']}</div>" if level['desc'] else ""}
            </div>
        """
    
    card += """
        </div>
    </div>
    """
    
    return f"<div class='ccog-container'>{card}</div>"

# ================= Format CCOG =================
def format_esco_card(esco_data):
    if not esco_data or not isinstance(esco_data, dict):
        return "<div class='ccog-container'><p>No ESCO classification data available</p></div>"
    
    # Extract level data
    levels = []
    for i in range(1, 6):
        level_data = {
            'code': esco_data.get(f'Level_{i}_ESCO_code'),
            'name': esco_data.get(f'Level_{i}_ESCO_name'),
            'desc': esco_data.get(f'Level_{i}_ESCO_desc')
        }
        if level_data['code'] or level_data['name']:
            levels.append(level_data)
    
    if not levels:
        return "<div class='esco-container'><p>No valid ESCO classification found</p></div>"
    
    # Build the card
    card = f"""
    <div class='esco-card'>
        <div class='esco-header'>
            <h3>ESCO Occupation Classification</h3>
        </div>
        
        <div class='esco-levels'>
    """
    
    for i, level in enumerate(levels, 1):
        card += f"""
            <div class='esco-level {'active' if level['desc'] else 'inactive'}'>
                <div class='level-header'>
                    <span class='level-number'>Level {i}</span>
                    <span class='level-code'>{level['code'] or 'N/A'}</span>
                </div>
                <div class='level-name'>{level['name'] or 'Not classified'}</div>
                {f"<div class='level-desc'>{level['desc']}</div>" if level['desc'] else ""}
            </div>
        """
    
    card += """
        </div>
    </div>
    """
    
    return f"<div class='esco-container'>{card}</div>"    

# ================= Process Analysis =================
import tempfile
import json
from concurrent.futures import ThreadPoolExecutor

def process_pdf(file):
    if file is None:
        return (
            "Please upload a PDF file.",
            "",
            "",
            "",
            {},
            "",
            [],
            {},
            {},
            "No file uploaded.",
            None  # JSON path
        )

    try:
        extracted_text = extract_text_from_pdf(file.name)
        responsibilities = extract_section_from_pdf(extracted_text, section_title="Responsibilities and Accountabilities")
        if not responsibilities:
            log_debug(f"Skipping {os.path.basename(file.name)} - no responsibilities section found")
            return (
                os.path.basename(file.name),
                "",
                "",
                "",
                {},
                "",
                [],
                {},
                {},
                "No responsibilities section found.",
                None  # JSON path
            )

        # Use ThreadPoolExecutor to parallelize independent tasks
        with ThreadPoolExecutor() as executor:
            job_family_future = executor.submit(classify_job_family, responsibilities)
            occ_group_future = executor.submit(classify_occupational_group_by_level, responsibilities)
            esco_occ_future = executor.submit(classify_esco_by_hierarchical_level, responsibilities)
            qualification_future = executor.submit(extract_qualification, responsibilities)
            skills_future = executor.submit(extract_skills, responsibilities)
            
            job_family = job_family_future.result()
            occ_group = occ_group_future.result()
            esco_occ = esco_occ_future.result()
            qualification = qualification_future.result()
            skills = skills_future.result()

        log_debug(f"Identified {job_family}")

        interview = build_interview(responsibilities, skills)

        ## Map skills from responsibilities
        skill_map = map_proficiency_and_assessment(skills, responsibilities)
        time.sleep(6)
        assessment_lookup = {item['skill_name']: item for item in skill_map}
        joined_skills = [
            {
                "skill_name": skill["skill_name"],
                "skill_description": skill["skill_description"],
                "skill_code": skill["skill_code"],
                "importance": assessment_lookup.get(skill["skill_name"], {}).get("importance"),
                "type": assessment_lookup.get(skill["skill_name"], {}).get("type"),
                "proficiency_level": assessment_lookup.get(skill["skill_name"], {}).get("proficiency_level"),
                "distinctive_elements": assessment_lookup.get(skill["skill_name"], {}).get("distinctive_elements"),
                "resume_signals": assessment_lookup.get(skill["skill_name"], {}).get("resume_signals"),
                "assessment_method": assessment_lookup.get(skill["skill_name"], {}).get("assessment_method")
            }
            for skill in skills
        ]

        
        ## Generate ESCO skills if we have level 5 mapping.... 
        has_esco = esco_occ.get("Level_5_ESCO_code") is not None
        skill_esco_extract = []
        skill_esco_map = []
        if has_esco:
            Level_5_code = esco_occ["Level_5_ESCO_code"]
            skill_esco_extract = review_skills(Level_5_code)
            skill_esco_map = map_proficiency_and_assessment(skill_esco_extract, responsibilities)
        else:
            log_debug(f"No Level 5 ESCO code found for {os.path.basename(file.name)}, skipping ESCO skills mapping")

        joined_skills_esco = []
        if has_esco and skill_esco_extract:
            assessment_esco_lookup = {item['skill_name']: item for item in skill_esco_map}
            joined_skills_esco = [
                {
                    "skill_name": skill["skill_name"],
                    "skill_description": skill["skill_description"],
                    "skill_code": skill["skill_code"],
                    **assessment_esco_lookup.get(skill["skill_name"], {})
                }
                for skill in skill_esco_extract
            ]
            
        if has_esco:
            esco_levels = {f"Level_{i}_ESCO_{field}": esco_occ.get(f"Level_{i}_ESCO_{field}")
                           for i in range(1, 6) for field in ["code", "name", "desc"]}
            esco_skills = {
                "skills": joined_skills_esco
            }
        else:
            esco_levels = {f"Level_{i}_ESCO_{field}": None
                           for i in range(1, 6) for field in ["code", "name", "desc"]}
            esco_skills = None

        
        # Prepare all data for JSON output
        result_data = {
            "file_name": os.path.basename(file.name),
            "responsibilities": responsibilities,
            "job_family": job_family,
            "qualification": qualification,
            "ccoq_levels": {f"Level_{i}_CCOG_{field}": occ_group.get(f"Level_{i}_CCOG_{field}")
                          for i in range(1, 5) for field in ["code", "name", "desc"]},
            "interview_questions": interview,
            "skills": joined_skills,
            "esco_levels": {f"Level_{i}_ESCO_{field}": esco_occ.get(f"Level_{i}_ESCO_{field}")
                          for i in range(1, 6) for field in ["code", "name", "desc"]},
            "esco_skills": esco_skills,
            "processing_time": time.strftime("%Y-%m-%d %H:%M:%S")
        }

        # Save to temporary JSON file
        with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode='w') as f:
            json.dump(result_data, f, indent=2)
            json_path = f.name
            log_debug(f"Results saved to temporary JSON file: {json_path}")
            log_debug(f"Results data: {result_data}")

        # Format outputs for display through html cards
        formatted_skills = format_skill_cards(joined_skills)
        formatted_ccog = format_ccog_card(result_data['ccoq_levels'])
        formatted_esco_levels = format_esco_card(result_data['esco_levels'])
        formatted_esco_skills = format_skill_cards(joined_skills_esco)
        
        
        return (
            os.path.basename(file.name),
            responsibilities,
            job_family,
            "\n".join(qualification),
            formatted_ccog,
            "\n".join(interview),
            formatted_skills,
            formatted_esco_levels,
            formatted_esco_skills,
            "Processed...",
            json_path  # Return path to JSON file
        )

    except Exception as e:
        error_message = f"Error processing PDF: {str(e)}"
        log_debug(error_message)
        traceback.print_exc()
        return (
            error_message,
            "",
            "",
            "",
            {},
            "",
            [],
            {},
            {},
            error_message,
            None  # No JSON path on error
        )

        
# ================= Build Word Report =================
from docx import Document
import os
import re
import time
import tempfile
from typing import Dict, List, Union

from docx.shared import Pt
from docx.oxml.ns import qn

def set_default_font(doc, font_name="Verdana", font_size=11):
    """Set the default font for the entire Word document."""
    style = doc.styles['Normal']
    font = style.font
    font.name = font_name
    font.size = Pt(font_size)
    style.element.rPr.rFonts.set(qn('w:eastAsia'), font_name)

    

def create_error_doc(message: str) -> str:
    """Create a simple Word document with an error message."""
    doc = Document()
    doc.add_heading('Error Generating Report', level=1)
    doc.add_paragraph(message)
    temp_file = tempfile.NamedTemporaryFile(suffix=".docx", delete=False)
    doc.save(temp_file.name)
    return temp_file.name
    


def generate_word_document(json_path: Optional[str]) -> str:
    """
    Generate a Word document from the analysis results JSON file.
    
    Args:
        json_path: Path to the JSON file containing analysis results
        
    Returns:
        Path to the generated Word document
    """
    if not json_path or not os.path.exists(json_path):
        return create_error_doc("No valid analysis data was provided.")

    try:
        with open(json_path, 'r') as f:
            data = json.load(f)
    except Exception as e:
        return create_error_doc(f"Failed to load JSON file: {str(e)}")

            
    # Initialize document with metadata
    doc = Document()
    set_default_font(doc, font_name="Verdana", font_size=11)
    doc.core_properties.author = "IOM Talent Management System"
    doc.core_properties.title = "Position Description Analysis Report"

    # Default values for all fields
    default_values = {
        "file_name": "Unknown file",
        "responsibilities": "No responsibilities extracted.",
        "classified_job_family": "No job family identified.",
        "qualification": ["No qualification information available."],
        "interview_questions": ["No interview questions generated."],
        "skills": {"skills": [{"skill_name": "No skills identified", "description": "", "code": ""}]},
        "esco_skills": {"skills": [{"skill_name": "No ESCO skills identified", "description": "", "code": ""}]}
    }

    # Safely build the result dictionary with fallbacks
    try:
        result = {
            "file_name": data.get("file_name", default_values["file_name"]),
            "responsibilities": data.get("responsibilities", default_values["responsibilities"]),
            "classified_job_family": data.get("job_family", default_values["classified_job_family"]),
            "qualification": data.get("qualification", default_values["qualification"]),
            "interview_questions": data.get("interview_questions", default_values["interview_questions"]),
            "skills": data.get("skills", default_values["skills"]),
            "esco_skills": data.get("esco_skills", default_values["esco_skills"]),
            "ccoq_levels": data.get("ccoq_levels", {}),
            "esco_levels": data.get("esco_levels", {})
        }

        # Add level information with validation
        if result.get("ccog_levels") and isinstance(result["ccog_levels"], dict):
            result["ccog_levels"] = {k: v for k, v in result["ccog_levels"].items() if v is not None}
        
        if result.get("esco_levels") and isinstance(result["esco_levels"], dict):
            result["esco_levels"] = {k: v for k, v in result["esco_levels"].items() if v is not None}    

    except Exception as e:
        log_debug(f"Error building result dictionary: {str(e)}")
        result = default_values

    #  DOCUMENT CONTENT GENERATION  
    try:
        # Document header
        doc.add_heading('Job Description Analysis Report', level=0)
        doc.add_paragraph(f"Generated on {time.strftime('%Y-%m-%d %H:%M:%S')}")
        doc.add_paragraph("This document contains material generated by artificial intelligence technology. While efforts have been made to ensure accuracy, please be aware that AI-generated content may not always fully represent the intent or expertise of human-authored material and may contain errors or inaccuracies. An AI model might generate content that sounds plausible but that is either factually incorrect or unrelated to the given context. These unexpected outcomes, also called AI hallucinations, can stem from biases, under-performing information retrieval, lack of real-world understanding, or limitations in training data.", style="Intense Quote")

 

        doc.add_heading('Input Information', level=2)
        doc.add_paragraph(f"File: {result['file_name']}")
    
        doc.add_paragraph(result['responsibilities'])
        doc.add_page_break()
        
        doc.add_heading('Job Family Classification', level=2)
        doc.add_paragraph(f" {result['classified_job_family']}")             
       
        # Helper function to add a bold label with regular value
        def add_skill_detail(paragraph_text, value):
            para = doc.add_paragraph()
            para.add_run(paragraph_text).bold = True
            para.add_run(f" {value}")

                         
        # Skills (Extracted)
        doc.add_heading('Skills (Extracted)', level=2)
        skills_list = result['skills']
        if isinstance(skills_list, dict):
            skills_list = skills_list.get("skills", [])
        for skill in skills_list:
            doc.add_heading(f"• {skill.get('skill_name', 'Unnamed Skill')}", level=3)
            add_skill_detail("Description:", skill.get('skill_description', 'N/A'))
            add_skill_detail("Code:", skill.get('skill_code', 'N/A'))
            add_skill_detail("Type:", skill.get('type', 'N/A'))
            add_skill_detail("Importance:", skill.get('importance', 'N/A'))
            add_skill_detail("Proficiency Level:", skill.get('proficiency_level', 'N/A'))
            add_skill_detail("Distinctive Elements:", skill.get('distinctive_elements', 'N/A'))
            add_skill_detail("Resume Signals:", skill.get('resume_signals', 'N/A'))
            add_skill_detail("Assessment Method:", skill.get('assessment_method', 'N/A'))

        doc.add_page_break()
        doc.add_heading('Suggested Qualifications', level=2)
        for item in result['qualification']:
            doc.add_paragraph(item, style='Body Text')

        doc.add_heading('Suggested Interview Questions', level=2)
        for item in result['interview_questions']:
            doc.add_paragraph(item, style='Body Text')


        if result["ccoq_levels"]:
            doc.add_heading('UN Common Classification of Occupational Groups', level=2)
            for key, value in result["ccoq_levels"].items():
                    paragraph = doc.add_paragraph()
                    run = paragraph.add_run(f"{key}: ")
                    run.bold = True
                    paragraph.add_run(str(value))            
    
        doc.add_page_break()
        if result["esco_levels"]:
            doc.add_heading('ESCO Framework Occupational Groups', level=2)
            for key, value in result["esco_levels"].items():
                    paragraph = doc.add_paragraph()
                    run = paragraph.add_run(f"{key}: ")
                    run.bold = True
                    paragraph.add_run(str(value))
        
    
        
        # Skills (ESCO)
        doc.add_heading('Skills (Mapped from ESCO)', level=2)
        esco_skills_list = result['esco_skills']
        if isinstance(esco_skills_list, dict):
            esco_skills_list = esco_skills_list.get("skills", [])
        for skill in esco_skills_list:
            doc.add_heading(f"• {skill.get('skill_name', 'Unnamed Skill')}", level=3)
            add_skill_detail("Description:", skill.get('skill_description', 'N/A'))
            add_skill_detail("Code:", skill.get('skill_code', 'N/A'))
            add_skill_detail("Type:", skill.get('type', 'N/A'))
            add_skill_detail("Importance:", skill.get('importance', 'N/A'))
            add_skill_detail("Proficiency Level:", skill.get('proficiency_level', 'N/A'))
            add_skill_detail("Distinctive Elements:", skill.get('distinctive_elements', 'N/A'))
            add_skill_detail("Resume Signals:", skill.get('resume_signals', 'N/A'))
            add_skill_detail("Assessment Method:", skill.get('assessment_method', 'N/A'))
 
        doc.add_page_break()
    

    except Exception as e:
        log_debug(f"Error generating document content: {str(e)}")
        # Fallback to simple error document
        doc = Document()
        doc.add_heading("Partial Report Generated", level=1)
        doc.add_paragraph(f"Some sections could not be generated due to: {str(e)}")

    #   FILE SAVING WITH MULTIPLE FALLBACKS  
    try:
        # Generate appropriate filename
        base_name = os.path.splitext(os.path.basename(result['file_name']))[0]
        if base_name:
            clean_name = re.sub(r'[^\w\-]', '_', base_name)[:50]  # Sanitize and truncate
            output_filename = f"{clean_name}_analysis_{time.strftime('%Y%m%d')}.docx"
        else:
            output_filename = f"job_analysis_{time.strftime('%Y%m%d_%H%M%S')}.docx"    

        # Try saving to reports directory first
        output_dir = "generated_reports"
        try:
            os.makedirs(output_dir, exist_ok=True)
            output_path = os.path.join(output_dir, output_filename)
            doc.save(output_path)
            return output_path
        except PermissionError:
            # Fallback to system temp directory
            temp_dir = tempfile.gettempdir()
            temp_path = os.path.join(temp_dir, output_filename)
            doc.save(temp_path)
            return temp_path

    except Exception as e:
        # Ultimate fallback with error document
        error_doc = Document()
        error_doc.add_heading("Error Generating Report", level=1)
        error_doc.add_paragraph(f"Could not save report due to: {str(e)}")
        fallback_path = os.path.join(tempfile.gettempdir(), f"error_report_{time.strftime('%Y%m%d_%H%M%S')}.docx")
        error_doc.save(fallback_path)
        return fallback_path

        
# ================= GRADIO INTERFACE =================
with gr.Blocks(
    title="AI-powered tool to review Job Position Description",
css="""
    @import url('https://fonts.googleapis.com/css2?family=Lato:wght@400;700&display=swap');
    @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');
/* Completely disable Gradio's dark theme */
.gradio-container.dark {
    --body-background-fill: white !important;
    --background-fill-primary: white !important;
    --background-fill-secondary: #f8f9fa !important;
    --block-background-fill: white !important;
    --input-background-fill: white !important;
    --block-label-text-color: #212529 !important;
    --body-text-color: #212529 !important;
    --block-title-text-color: var(--primary-color) !important;
    --border-color-primary: #dee2e6 !important;
}
.gradio-container.dark .gr-markdown,
.gradio-container.dark .gr-textbox,
.gradio-container.dark .gr-dropdown,
.gradio-container.dark .output-section {
    background: white !important;
    color: #212529 !important;
    border-color: #dee2e6 !important;
}

/* Gradio layout fixes */
.gradio-container {
    max-width: none !important;
    padding: 0 20px !important;
}

.gradio-container .gradio-row {
  max-width: 100% !important;
  margin: 0 auto !important;
  flex: 1 !important;
  display: grid !important;
  grid-template-columns: 1fr !important;
}

.gradio-container .gradio-column {
  min-width: 0 !important;
  padding: 0 !important;
  flex: 1 !important;
  max-width: none !important;
}

/* Ensure the parent container doesn't constrain the grid */
.container-wrap {
    width: 100%;
    max-width: none !important;
    padding: 0 !important;
    margin: 0 !important;
}

/* Set the size of the SVG icon for file download */
.feather-file {
    width: 20px !important; /* Adjust the size as needed */
    height: 20px !important; /* Adjust the size as needed */
}

/* Base Styles */
:root {
    --primary-color: #0033A0;
    --secondary-color: #e67e22;
    --accent-color: #f59e0b;
    --dark-color: #34495e;
    --light-color: #ecf0f1;
    --success-color: #27ae60;
    --warning-color: #f39c12;
    --danger-color: #e74c3c;
    --text-color: #333;
    --text-light: #7f8c8d;
    --border-radius: 8px;
    --box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    --transition: all 0.3s ease;
}
/* Header Styles */
.header {
    text-align: center;
    margin-bottom: 2rem;
    padding: 1rem;
}
.header h1 {
    margin: 0;
    font-family: 'Lato', sans-serif;
    font-size: 2.5rem;
    font-weight: 600;
    color: var(--primary-color);
}
.header p {
    margin: 0.5rem 0 0;
    font-family: 'Lato', sans-serif;
    opacity: 0.9;
    font-size: 1.5rem;
    color: #4b5563;
}
/* Section Titles */
.section-title {
    display: flex;
    align-items: left;
    font-family: 'Lato', sans-serif;
    gap: 0.5rem;
    color: var(--primary-color);
    margin: 1rem 0;
    font-size: 1.25rem;
    font-weight: 600;
}
.section-title i {
    font-size: 1.1em;
    color: var(--accent-color);
}
/* Input Section */
.input-section {
    background: white;
    padding: 0.75rem 0.5rem;
    border: 1px solid #d1d5db;
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
    margin-right: 1rem;
}
/* Output Section */
.output-section {
    background: white;
    padding: 1.5rem;
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
}
/* Form Elements */
.gr-textbox, .gr-dropdown {
    border: 1px solid #ddd;
    border-radius: var(--border-radius) !important;
    padding: 0.75rem 1rem !important;
    transition: var(--transition);
}
.gr-textbox:focus, .gr-dropdown:focus {
    border-color: var(--primary-color) !important;
    box-shadow: 0 0 0 2px rgba(44, 110, 203, 0.2) !important;
    outline: none !important;
}
.gr-textbox::placeholder {
    color: var(--text-light) !important;
    opacity: 0.7 !important;
}
label {
    font-weight: 500 !important;
    color: var(--dark-color) !important;
    margin-bottom: 0.5rem !important;
    display: block !important;
}
/* Buttons */
.btn-primary {
    background: var(--primary-color) !important;
    color: white !important;
    border: none !important;
    border-radius: var(--border-radius) !important;
    padding: 0.75rem 1.5rem !important;
    font-weight: 500 !important;
    transition: var(--transition) !important;
    text-transform: uppercase !important;
    letter-spacing: 0.5px !important;
}
.btn-primary:hover {
    background: #002080 !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15) !important;
}
.btn-primary:active {
    transform: translateY(0) !important;
}

/* Intro */
.intro-box {
        background: #f0f7ff;
        border-left: 4px solid #0033A0;
        border-radius: 4px;
        padding: 16px;
        margin-bottom: 20px;
}
.intro-title {
        color: #0033A0;
        font-weight: 600;
        margin-top: 0 !important;
}
.intro-icon {
        color: #0033A0;
        margin-right: 8px;
}
.benefits-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 12px;
        margin: 16px 0;
}
.benefit-card {
        background: white;
        padding: 12px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

/* Skills Card */
.skills-outer-container {
        width: 100%;
        padding: 0 1rem;
        box-sizing: border-box;
}
    
 

.skills-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 1.5rem;
  padding: 1rem;
  width: 100%;
  margin: 0 auto;
}

/* Card styling */
.skill-card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.08);
    overflow: hidden;
    transition: all 0.3s ease;
    border: 1px solid #e0e0e0;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.skill-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 16px rgba(0,0,0,0.12);
}

/* Header section */
.skill-header {
    background: #ecf0f1;
    color: white;
    padding: 1.2rem;
    display: flex;
    flex-direction: column;
    gap: 0.8rem;
}

.skill-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.skill-title h3 {
    margin: 0;
    font-size: 1.2rem;
    font-weight: 600;
}

.skill-code {
    font-size: 0.85rem;
    opacity: 0.8;
    background: rgba(255,255,255,0.15);
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
}

.skill-pills {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.skill-pill {
    padding: 0.35rem 0.7rem;
    border-radius: 999px;
    font-size: 0.8rem;
    font-weight: 500;
}

/* Type and Importance pills */
.skill-pill.type-skill { background: #4CAF50; color: white; }
.skill-pill.type-knowledge { background: #2196F3; color: white; }
.skill-pill.importance-essential { background: #F44336; color: white; }
.skill-pill.importance-optional { background: #FF9800; color: white; }

/* Body section */
.skill-body {
    padding: 1.2rem;
}

.skill-description {
    margin-bottom: 1.2rem;
    padding-bottom: 1rem;
    border-bottom: 1px dashed #eee;
}

.skill-description p {
    margin: 0;
    color: #555;
    line-height: 1.5;
}

/* Details sections */
.skill-details {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.detail-group {
    display: flex;
    flex-direction: column;
    gap: 0.3rem;
}

.detail-group label {
    font-weight: 600;
    font-size: 0.9rem;
    color: #0033A0;
}

.detail-content {
    margin: 0;
    font-size: 0.95rem;
    color: #444;
    line-height: 1.5;
}

/* Proficiency bar */
.proficiency-bar {
    display: flex;
    align-items: center;
    gap: 0.8rem;
    margin-top: 0.3rem;
}

progress {
    flex-grow: 1;
    height: 8px;
    border-radius: 4px;
}

progress::-webkit-progress-bar {
    background-color: #f0f0f0;
    border-radius: 4px;
}

progress::-webkit-progress-value {
    background-color: #0033A0;
    border-radius: 4px;
}

.proficiency-bar span {
    font-size: 0.9rem;
    font-weight: 500;
    min-width: 80px;
    text-align: right;
}
/* CCOG card */
.ccog-container {
    margin: 1.5rem 0;
}

.ccog-card {
    background: white;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    overflow: hidden;
    border: 1px solid #e0e0e0;
}

.ccog-header {
    background: #ecf0f1;
    color: white;
    padding: 1.2rem;
    border-bottom: 2px solid rgba(255,255,255,0.1);
}

.ccog-header h3 {
    margin: 0;
    font-size: 1.3rem;
    font-weight: 600;
}

.ccog-system {
    opacity: 0.9;
    font-size: 0.85rem;
    margin-top: 0.3rem;
}

.ccog-levels {
    padding: 1rem;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.ccog-level {
    padding: 1rem;
    border-radius: 6px;
    position: relative;
}

.ccog-level.active {
    background: #f8fafc;
    border-left: 4px solid #0033A0;
}

.ccog-level.inactive {
    background: #f5f5f5;
    opacity: 0.7;
}

/* ESCO card */
.esco-container {
    margin: 1.5rem 0;
}

.esco-card {
    background: white;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    overflow: hidden;
    border: 1px solid #e0e0e0;
}

.esco-header {
    background: #ecf0f1;
    color: white;
    padding: 1.2rem;
    border-bottom: 2px solid rgba(255,255,255,0.1);
}

.esco-header h3 {
    margin: 0;
    font-size: 1.3rem;
    font-weight: 600;
}

.esco-system {
    opacity: 0.9;
    font-size: 0.85rem;
    margin-top: 0.3rem;
}

.esco-levels {
    padding: 1rem;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.esco-level {
    padding: 1rem;
    border-radius: 6px;
    position: relative;
}

.esco-level.active {
    background: #f8fafc;
    border-left: 4px solid #0033A0;
}

.esco-level.inactive {
    background: #f5f5f5;
    opacity: 0.7;
}

.level-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
    align-items: center;
}

.level-number {
    font-weight: 600;
    color: #0033A0;
    font-size: 0.9rem;
}

.level-code {
    background: rgba(0,51,160,0.1);
    color: #0033A0;
    padding: 0.2rem 0.5rem;
    border-radius: 4px;
    font-size: 0.8rem;
    font-family: monospace;
}

.level-name {
    font-weight: 500;
    font-size: 1.05rem;
    margin-bottom: 0.5rem;
    color: #333;
}

.level-desc {
    font-size: 0.9rem;
    color: #555;
    line-height: 1.5;
    padding-top: 0.5rem;
    border-top: 1px dashed #e0e0e0;
    margin-top: 0.5rem;
}


/* Output Markdown */
.gr-markdown {
    background: #f9f9f9;
    padding: 1.5rem;
    border-radius: var(--border-radius);
    border-left: 4px solid var(--primary-color);
}
/* Debug Console */
.gr-textbox[label="⚠️ Console Log"] {
    font-family: monospace !important;
    background: #2c3e50 !important;
    color: #ecf0f1 !important;
    border-radius: var(--border-radius) !important;
    padding: 1rem !important;
}
/* Responsive Layout */

/* For larger screens */
@media (min-width: 1200px) {
  .skills-container {
      grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
      max-width: 1400px;
  }
}

@media (max-width: 768px) {
    .gr-row {
        flex-direction: column !important;
    }
    
    .input-section {
        margin-right: 0 !important;
        margin-bottom: 1rem !important;
    }
    
    .skills-container {
        grid-template-columns: 1fr;
        grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
    }
    
    .skill-header {
        flex-direction: column;
    }
    
    .skill-title {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.5rem;
    }

    .ccog-level {
        padding: 0.8rem;
    }

    .esco-level {
        padding: 0.8rem;
    }
    
    .level-name {
        font-size: 1rem;
    }
}
    """,
    head='''
    <meta name="description" content="AI-powered tool to review Job Position Description.">
    <meta name="keywords" content="HR, Position, Job, Skills, Qualification, Interview">
    <meta name="author" content="Edouard Legoupil | IOM Chief Data Officer">
    <link rel="author" href="https://edouard-legoupil.github.io/">
    <meta property="og:title" content="AI-powered tool to review Job Position Description">
    <meta property="og:description" content="AI-powered tool to review Job Position Description">
    <meta property="og:type" content="website">
    <link rel="icon" href="https://www.iom.int/themes/custom/phoenix/favicon.ico" type="image/vnd.microsoft.icon">
    <link rel="apple-touch-icon" href="https://www.iom.int/sites/g/files/tmzbdl486/files/favicon.ico">
    '''
) as demo:

    # Header section
    with gr.Column():
        with gr.Row():
            with gr.Column():
                gr.HTML("""
                <div class="header">
                    <h1>Position Description Review (Demo)</h1>
                    <p>Use AI to standardise an initial position description.</p>
                </div>
                """)
    # Introduction Section
    with gr.Column(elem_classes="intro-box"):
        gr.Markdown("""

        <div class='benefits-grid'>
            <div class='benefit-card'>
                <p><strong>🔍 Strategic Workforce Management</strong>: Aligns existing positions with one among 28 distinct Job Families to enhance Career Development, as well as one among 225 <a href="https://icsc.un.org/Home/JobClassification">UN Common Classification of Occupational Groups</a> and 3007 <a href="https://esco.ec.europa.eu/en/classification">ESCO Framework Occupational Groups</a> to ease external sourcing </p>
            </div>
            <div class='benefit-card'>
                <p><strong>⏱️ Time Saver</strong>: Reduces hours of manual research and mapping to minutes and minimise risk of errors</p>
            </div>
            <div class='benefit-card'>
                <p><strong>⚖️ Reduced Recruitment Bias</strong>: Get Skills Requirements Recommendations using both the description of responsibilities and the standard ESCO skills linked the previously mapped ESCO occupation</p>
            </div>
            <div class='benefit-card'>
                <p><strong>🎯 Better Hiring</strong>: Generates expected qualification description, skills assessment method and tailored interview questions</p>
            </div>
        </div>
        """)
                
    with gr.Row():
        with gr.Column():
            file_input = gr.File(
                        label="Upload a Post Description PDF file - not a scanned file!!!", 
                        file_types=[".pdf"])
            submit_btn = gr.Button(
                        value="✨ Analyse this Post Description! It should take about 2 minutes...",
                        variant="primary",
                        elem_classes="btn-primary"
            )

    with gr.Row():
        with gr.Column():            
            gr.Markdown("### Input for Analysis") 
            file_name_output = gr.Textbox(label="File Name", interactive=False)
            responsibilities_output = gr.Textbox(label="List of Responsibilities used for the review", lines=5, interactive=False)

    with gr.Row():
        with gr.Column():
            gr.Markdown("### Mapped Skills")            
            skills_output = gr.HTML(label="", elem_classes="skills-container")

    with gr.Row():
        with gr.Column():
            gr.Markdown("### Expected Qualifications")
            qualification_output = gr.Textbox(label="", lines=5, interactive=False)
            
    with gr.Row():
        with gr.Column():
            gr.Markdown("## Interview Questions")
            interview_output = gr.Textbox(label="", lines=10, interactive=False)

    with gr.Row():
        with gr.Column():
            gr.Markdown("### Mapped Job Family")
            job_family_output = gr.Textbox(label="", interactive=False)
            
    with gr.Row():
        with gr.Column():
            ccoq_levels_output = gr.HTML(label="", elem_classes="ccog-container")
 
    with gr.Row():
        with gr.Column():
            esco_levels_output = gr.HTML(label="", elem_classes="esco-container")
    
    with gr.Row():        
        with gr.Column():
            esco_skills_output = gr.HTML(label="Linked ESCO Skills", elem_classes="skills-container")


    with gr.Row():
        with gr.Column():
            download_btn = gr.Button(
                        value="📄 Download the corresponding Word report",
                        variant="primary",
                        elem_classes="btn-primary")

    if DEBUG:
        with gr.Row():
            with gr.Column():
                debug_console = gr.Textbox(
                    label="⚠️ Execution Log",
                    interactive=False,
                    elem_classes=["debug-console"]
                )
                temp_json_path = gr.Textbox(label="", interactive=False)

    submit_btn.click(
        fn=process_pdf,
        inputs=file_input,
        outputs=[
            file_name_output,
            responsibilities_output,
            job_family_output,
            qualification_output,
            ccoq_levels_output,
            interview_output,
            skills_output,
            esco_levels_output,
            esco_skills_output,
            debug_console if DEBUG else None,
            temp_json_path
        ]
    )

    download_btn.click(
        fn=generate_word_document,
        inputs=[
            temp_json_path
        ],
        outputs=gr.File(label="Download the corresponding Word report")
    )

if __name__ == "__main__":
    demo.launch(show_error=True, debug=DEBUG)