File size: 63,296 Bytes
a24bc79
978c118
 
 
 
 
59b80ef
 
 
978c118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
036b515
90a8eb6
607dfa6
90a8eb6
036b515
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
978c118
 
 
 
 
036b515
978c118
18a38f3
978c118
 
18a38f3
19f2a2d
 
 
 
 
 
 
3654255
301e290
 
 
8f26897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301e290
59b80ef
19f2a2d
 
 
 
 
 
 
 
 
 
 
 
59b80ef
301e290
 
19f2a2d
 
 
 
 
301e290
 
19f2a2d
301e290
 
 
 
 
 
19f2a2d
4b8ca84
301e290
19f2a2d
301e290
19f2a2d
301e290
 
d577d7f
19f2a2d
 
 
 
 
68963d4
301e290
68963d4
4b8ca84
301e290
 
19f2a2d
301e290
 
 
19f2a2d
 
4b8ca84
301e290
4b8ca84
301e290
19f2a2d
301e290
19f2a2d
4b8ca84
 
 
 
301e290
 
19f2a2d
301e290
4b8ca84
301e290
 
 
 
 
4b8ca84
301e290
19f2a2d
4b8ca84
 
 
68963d4
4b8ca84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68963d4
4b8ca84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19f2a2d
301e290
4b8ca84
301e290
 
4b8ca84
 
 
 
 
 
 
 
 
 
 
 
 
47843ae
4b8ca84
 
 
 
 
 
 
 
 
 
 
6d287aa
4b8ca84
 
6d287aa
4b8ca84
 
 
 
 
 
301e290
4b8ca84
301e290
19f2a2d
4b8ca84
19f2a2d
4b8ca84
68963d4
4b8ca84
301e290
 
 
 
 
4b8ca84
 
 
 
 
47843ae
4b8ca84
 
47843ae
 
4b8ca84
6d287aa
4b8ca84
 
 
 
 
47843ae
4b8ca84
47843ae
4b8ca84
6d287aa
4b8ca84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47843ae
4b8ca84
 
 
 
47843ae
4b8ca84
 
 
301e290
4b8ca84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
978c118
 
 
 
 
 
 
036b515
 
 
 
d1a1c63
978c118
 
 
 
 
036b515
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
978c118
 
 
036b515
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f26897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
978c118
 
 
7574b41
036b515
 
 
 
 
 
978c118
 
d1a1c63
978c118
 
59b80ef
978c118
59b80ef
978c118
59b80ef
978c118
59b80ef
978c118
59b80ef
 
 
 
 
 
 
 
 
 
 
25ae2d0
 
 
 
 
 
 
 
 
 
 
 
978c118
 
 
 
59b80ef
 
978c118
59b80ef
 
 
978c118
 
 
 
036b515
59b80ef
 
978c118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
036b515
 
 
 
 
 
978c118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
036b515
978c118
 
 
036b515
 
978c118
 
 
 
 
 
 
 
 
 
 
 
 
 
036b515
 
 
 
 
 
978c118
 
 
 
 
 
036b515
 
d1a1c63
036b515
 
 
 
 
978c118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18a38f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f26897
978c118
 
8f26897
978c118
8f26897
 
978c118
 
8f26897
 
 
 
 
 
978c118
 
d1a1c63
 
 
 
 
978c118
8f26897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
978c118
8f26897
59b80ef
 
 
 
d577d7f
 
59b80ef
8f26897
 
 
978c118
8f26897
978c118
8f26897
978c118
 
 
8f26897
 
 
 
 
 
 
 
 
 
 
978c118
 
 
8f26897
d1a1c63
 
 
 
 
 
 
 
 
 
 
 
8f26897
978c118
59b80ef
 
 
d1a1c63
 
 
 
 
 
 
8f26897
 
 
 
d1a1c63
 
 
8f26897
 
 
 
 
 
 
978c118
8f26897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1a1c63
 
 
8f26897
 
 
 
 
 
 
 
 
 
 
036b515
8f26897
 
 
 
 
d1a1c63
25ae2d0
8f26897
25ae2d0
8f26897
 
 
 
 
25ae2d0
8f26897
978c118
a950f56
8f26897
a950f56
 
 
 
8f26897
a950f56
8f26897
 
a950f56
8f26897
 
 
 
a950f56
8f26897
a950f56
 
8f26897
a950f56
8f26897
 
a950f56
8f26897
 
 
 
a950f56
8f26897
a950f56
8f26897
a950f56
8f26897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a950f56
d1a1c63
8f26897
 
 
 
d1a1c63
8f26897
d1a1c63
8f26897
 
 
 
 
 
25ae2d0
8f26897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
978c118
d1a1c63
8f26897
d1a1c63
8f26897
 
d1a1c63
 
8f26897
 
59b80ef
8f26897
25ae2d0
8f26897
25ae2d0
8f26897
25ae2d0
8f26897
d1a1c63
 
8f26897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25ae2d0
d1a1c63
25ae2d0
8f26897
59b80ef
8f26897
 
 
 
 
 
 
 
 
 
d1a1c63
8f26897
 
25ae2d0
8f26897
 
 
 
 
 
25ae2d0
d1a1c63
8f26897
 
59b80ef
d1a1c63
8f26897
d1a1c63
8f26897
25ae2d0
 
8f26897
25ae2d0
 
8f26897
 
 
25ae2d0
 
8f26897
25ae2d0
8f26897
25ae2d0
8f26897
25ae2d0
8f26897
 
 
 
 
 
 
 
 
25ae2d0
 
8f26897
 
 
 
 
 
 
 
25ae2d0
8f26897
a950f56
8f26897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1a1c63
8f26897
 
 
efdcce5
a950f56
 
 
 
d1a1c63
8f26897
d1a1c63
25ae2d0
8f26897
 
25ae2d0
8f26897
 
 
 
d1a1c63
8f26897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25ae2d0
8f26897
 
25ae2d0
8f26897
 
d577d7f
8f26897
 
 
 
 
 
 
 
 
 
 
d577d7f
47f0895
 
368c893
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
import streamlit as st
import pandas as pd
import numpy as np
import re
import io
import base64
import os
import requests
import json
from collections import Counter
import matplotlib.pyplot as plt
import seaborn as sns
from wordcloud import WordCloud
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime

# File processing imports
import PyPDF2
import pdfplumber
import docx
from docx import Document

# NLP imports
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.stem import WordNetLemmatizer

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, set_seed

# Optional imports with fallbacks
try:
    import spacy
    SPACY_AVAILABLE = True
except ImportError:
    SPACY_AVAILABLE = False

try:
    from fuzzywuzzy import fuzz, process
    FUZZYWUZZY_AVAILABLE = True
except ImportError:
    FUZZYWUZZY_AVAILABLE = False

try:
    import language_tool_python
    GRAMMAR_TOOL_AVAILABLE = True
except ImportError:
    GRAMMAR_TOOL_AVAILABLE = False

# ML imports
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

# Report generation
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch

import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import re
from datetime import datetime
from typing import Dict, List

# Set seed for reproducibility
set_seed(42)

# Custom CSS for better UI
def load_custom_css():
    st.markdown("""
    <style>
    .main {
        padding-top: 2rem;
    }
    
    .metric-card {
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 1rem;
        margin: 0.5rem 0;
        text-align: center;
    }
    
    .metric-value {
        font-size: 2rem;
        font-weight: bold;
        color: #28a745;
    }
    
    .metric-label {
        font-size: 0.9rem;
        color: #6c757d;
        margin-top: 0.5rem;
    }
    
    .warning-box {
        background-color: #fff3cd;
        border-left: 4px solid #ffc107;
        padding: 1rem;
        margin: 1rem 0;
    }
    
    .success-box {
        background-color: #d4edda;
        border-left: 4px solid #28a745;
        padding: 1rem;
        margin: 1rem 0;
    }
    
    .error-box {
        background-color: #f8d7da;
        border-left: 4px solid #dc3545;
        padding: 1rem;
        margin: 1rem 0;
    }
    
    .info-box {
        background-color: #d1ecf1;
        border-left: 4px solid #17a2b8;
        padding: 1rem;
        margin: 1rem 0;
    }
    
    .skill-tag {
        display: inline-block;
        background-color: #e9ecef;
        border-radius: 4px;
        padding: 0.25rem 0.5rem;
        margin: 0.25rem;
        font-size: 0.875rem;
    }
    
    .section-header {
        border-bottom: 2px solid #dee2e6;
        padding-bottom: 0.5rem;
        margin-bottom: 1rem;
    }
    
    .nav-pills {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 0.5rem;
        margin-bottom: 1rem;
    }
    
    .sidebar .sidebar-content {
        background-color: #f8f9fa;
    }
    </style>
    """, unsafe_allow_html=True)

class ImprovedNLPProcessor:
    def __init__(self):
        self.setup_nltk()
        
    def setup_nltk(self):
        try:
            nltk.download('punkt', quiet=True)
            nltk.download('stopwords', quiet=True)
            nltk.download('wordnet', quiet=True)
            self.stop_words = set(stopwords.words('english'))
            self.lemmatizer = WordNetLemmatizer()
        except:
            self.stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'with'}
            self.lemmatizer = None
    
    def extract_key_terms(self, text: str, max_terms: int = 5) -> str:
        """Extract key terms without overwhelming the model"""
        try:
            tokens = word_tokenize(text.lower())
        except:
            tokens = text.lower().split()
        
        # Focus on resume-relevant terms
        resume_keywords = ['resume', 'experience', 'skills', 'education', 'job', 'work', 'ats', 'career']
        
        filtered_tokens = []
        for token in tokens:
            if (len(token) > 2 and 
                token not in self.stop_words and 
                (token.isalpha() or token in resume_keywords)):
                filtered_tokens.append(token)
        
        # Return only the most relevant terms
        return ' '.join(filtered_tokens[:max_terms])

class ImprovedChatMemory:
    def __init__(self):
        if 'improved_chat_history' not in st.session_state:
            st.session_state.improved_chat_history = []
    
    def add_conversation(self, user_msg: str, bot_response: str):
        conversation = {
            'user': user_msg,
            'bot': bot_response,
            'timestamp': datetime.now().strftime("%H:%M:%S")
        }
        st.session_state.improved_chat_history.append(conversation)
        
        # Keep only last 6 conversations
        if len(st.session_state.improved_chat_history) > 6:
            st.session_state.improved_chat_history = st.session_state.improved_chat_history[-6:]
    
    def get_simple_context(self) -> str:
        """Get very simple context to avoid confusing the model"""
        if not st.session_state.improved_chat_history:
            return ""
        
        # Only use the last conversation for context
        last_conv = st.session_state.improved_chat_history[-1]
        last_topic = last_conv['user'][:30]  # First 30 chars only
        return f"Previously discussed: {last_topic}"

class ImprovedCPUChatbot:
    def __init__(self):
        self.model_name = "distilgpt2"
        self.model = None
        self.tokenizer = None
        self.pipeline = None
        self.nlp_processor = ImprovedNLPProcessor()
        self.memory = ImprovedChatMemory()
        self.is_loaded = False
        
        # Predefined responses for common resume questions
        self.template_responses = {
            'experience': "To improve your experience section: Use bullet points with action verbs, quantify achievements with numbers, focus on results rather than duties, and tailor content to match job requirements.",
            'ats': "Make your resume ATS-friendly by: Using standard section headings, including relevant keywords naturally, avoiding images and complex formatting, using common fonts like Arial, and saving as PDF.",
            'skills': "Enhance your skills section by: Organizing technical and soft skills separately, matching skills to job descriptions, providing proficiency levels, and including both hard and soft skills relevant to your target role.",
            'keywords': "Add relevant keywords by: Studying job descriptions in your field, using industry-specific terms, including both acronyms and full terms, and incorporating them naturally throughout your resume.",
            'format': "Improve resume formatting with: Clear section headings, consistent bullet points, readable fonts, appropriate white space, and a clean, professional layout that's easy to scan."
        }
    
    @st.cache_resource
    def load_model(_self):
        """Load the model with better configuration"""
        try:
            with st.spinner("Loading AI model (first time may take 2-3 minutes)..."):
                tokenizer = AutoTokenizer.from_pretrained(_self.model_name)
                tokenizer.pad_token = tokenizer.eos_token
                
                model = AutoModelForCausalLM.from_pretrained(
                    _self.model_name,
                    torch_dtype=torch.float32,
                    low_cpu_mem_usage=True
                )
                
                # Create pipeline with better parameters
                text_generator = pipeline(
                    "text-generation",
                    model=model,
                    tokenizer=tokenizer,
                    device=-1,  # CPU only
                    max_new_tokens=50,  # Reduced for better quality
                    do_sample=True,
                    temperature=0.8,
                    top_p=0.85,
                    top_k=50,
                    repetition_penalty=1.2,  # Reduce repetition
                    pad_token_id=tokenizer.eos_token_id,
                    no_repeat_ngram_size=3  # Prevent 3-gram repetition
                )
                
                return model, tokenizer, text_generator
        except Exception as e:
            st.error(f"Failed to load model: {str(e)}")
            return None, None, None
    
    def initialize(self):
        """Initialize the chatbot"""
        if not self.is_loaded:
            result = self.load_model()
            if result[0] is not None:
                self.model, self.tokenizer, self.pipeline = result
                self.is_loaded = True
                st.success("AI model loaded successfully!")
                return True
            else:
                return False
        return True
    
    def get_template_response(self, user_input: str) -> str:
        """Check if we can use a template response for common questions"""
        user_lower = user_input.lower()
        
        # Check for common patterns
        if any(word in user_lower for word in ['experience', 'work history', 'job history']):
            return self.template_responses['experience']
        elif any(word in user_lower for word in ['ats', 'applicant tracking', 'ats-friendly']):
            return self.template_responses['ats']
        elif any(word in user_lower for word in ['skills', 'technical skills', 'abilities']):
            return self.template_responses['skills']
        elif any(word in user_lower for word in ['keywords', 'keyword', 'terms']):
            return self.template_responses['keywords']
        elif any(word in user_lower for word in ['format', 'formatting', 'layout', 'design']):
            return self.template_responses['format']
        # Add general improvement patterns
        elif any(phrase in user_lower for phrase in ['improve my resume', 'better resume', 'hire me', 'get hired', 'land job']):
            return "To improve your resume for HR success: Use a clear, professional format with standard headings. Tailor your content to match job descriptions. Quantify achievements with numbers. Include relevant keywords naturally. Keep it to 1-2 pages. Use bullet points with action verbs. Proofread carefully for errors."
        elif any(word in user_lower for word in ['help', 'advice', 'tips', 'suggestions']):
            return "Key resume tips: Match your resume to each job application. Use metrics to show your impact. Include both technical and soft skills. Write a compelling summary. Use reverse chronological order. Keep formatting clean and simple."
        
        return None
    
    def create_simple_prompt(self, user_input: str, resume_context: str = "") -> str:
        """Create a very simple, clear prompt"""
        # Try template response first
        template_response = self.get_template_response(user_input)
        if template_response:
            return template_response
        
        # Extract key terms
        key_terms = self.nlp_processor.extract_key_terms(user_input)
        
        # Create simple prompt
        if resume_context:
            context_snippet = resume_context[:100].replace('\n', ' ')
            prompt = f"Resume help: {context_snippet}\nQuestion: {user_input}\nAdvice:"
        else:
            prompt = f"Resume question: {user_input}\nHelpful advice:"
        
        return prompt
    
    def generate_response(self, user_input: str, resume_context: str = "") -> str:
        """Generate response with better quality control and timeout handling"""
        if not self.is_loaded:
            return "Please initialize the AI model first by clicking 'Initialize AI'."
        
        # Check for template response first (this should catch most questions)
        template_response = self.get_template_response(user_input)
        if template_response:
            self.memory.add_conversation(user_input, template_response)
            return template_response
        
        # For non-template questions, provide a general helpful response instead of using the model
        # This avoids the generation loops and stuck behavior
        general_response = self.get_comprehensive_advice(user_input)
        self.memory.add_conversation(user_input, general_response)
        return general_response
    
    def get_comprehensive_advice(self, user_input: str) -> str:
        """Provide comprehensive advice based on user input patterns"""
        user_lower = user_input.lower()
        
        # Comprehensive resume improvement advice
        if any(phrase in user_lower for phrase in ['improve', 'better', 'enhance', 'optimize']):
            return """To improve your resume effectiveness: 1) Tailor it to each job by matching keywords from the job description. 2) Use quantifiable achievements (increased sales by 25%, managed team of 10). 3) Start bullet points with strong action verbs. 4) Keep it concise - ideally 1-2 pages. 5) Use a clean, professional format with consistent styling. 6) Include relevant technical and soft skills. 7) Proofread carefully for any errors."""
        
        # HR/hiring focused advice  
        elif any(phrase in user_lower for phrase in ['hr', 'hire', 'hiring', 'recruiter', 'employer']):
            return """To make your resume appealing to HR and hiring managers: 1) Use standard section headings they expect (Experience, Education, Skills). 2) Include relevant keywords to pass ATS screening. 3) Show clear career progression and achievements. 4) Make it easy to scan with bullet points and white space. 5) Demonstrate value you can bring to their organization. 6) Include measurable results and impacts."""
        
        # Job search and career advice
        elif any(phrase in user_lower for phrase in ['job', 'career', 'position', 'role', 'work']):
            return """For job search success: 1) Customize your resume for each application. 2) Research the company and role requirements. 3) Highlight relevant experience and skills prominently. 4) Use industry-specific terminology. 5) Show how your background aligns with their needs. 6) Include both technical competencies and soft skills."""
        
        # General help
        else:
            return """Key resume best practices: Use a professional format with clear headings. Lead with your strongest qualifications. Include relevant keywords naturally. Quantify achievements with specific numbers. Keep descriptions concise but impactful. Ensure error-free writing and consistent formatting. Focus on what value you bring to employers."""
    
    def get_general_advice(self, user_input: str) -> str:
        """Fallback advice for when model fails"""
        user_lower = user_input.lower()
        if 'experience' in user_lower:
            return "Focus on achievements with numbers, use action verbs, and show results."
        elif 'skill' in user_lower:
            return "List skills that match the job description and organize them by category."
        elif 'ats' in user_lower:
            return "Use standard headings, include keywords, and avoid complex formatting."
        else:
            return "Make sure your resume is clear, relevant to the job, and easy to read."
    
    def clean_response_thoroughly(self, response: str, user_input: str) -> str:
        """Thoroughly clean the generated response"""
        if not response or len(response.strip()) < 5:
            return self.get_general_advice(user_input)
        
        # Remove common problematic patterns
        response = re.sub(r'\|[^|]*\|', '', response)  # Remove pipe-separated content
        response = re.sub(r'Advice:\s*', '', response)  # Remove "Advice:" repetition
        response = re.sub(r'\s+', ' ', response)  # Replace multiple spaces
        response = re.sub(r'[.]{2,}', '.', response)  # Replace multiple periods
        
        # Split into sentences and filter
        sentences = [s.strip() for s in response.split('.') if s.strip()]
        good_sentences = []
        
        seen_content = set()
        for sentence in sentences[:2]:  # Max 2 sentences
            if (len(sentence) > 15 and 
                sentence.lower() not in seen_content and
                not sentence.lower().startswith(('you are', 'i am', 'as a', 'how do')) and
                'advice' not in sentence.lower()):
                
                good_sentences.append(sentence)
                seen_content.add(sentence.lower())
        
        if good_sentences:
            response = '. '.join(good_sentences)
            if not response.endswith('.'):
                response += '.'
        else:
            response = self.get_general_advice(user_input)
        
        return response.strip()

def create_improved_chat_interface(resume_context: str = ""):
    """Create improved chat interface"""
    
    st.header("AI Resume Assistant")
    
    # Initialize chatbot
    if 'improved_chatbot' not in st.session_state:
        st.session_state.improved_chatbot = ImprovedCPUChatbot()
    
    chatbot = st.session_state.improved_chatbot
    
    # Model initialization
    col1, col2 = st.columns([3, 1])
    
    with col1:
        st.info("Using DistilGPT2 with improved response quality")
    
    with col2:
        if st.button("Initialize AI", type="primary"):
            chatbot.initialize()
    
    # Chat interface
    if chatbot.is_loaded:
        st.success("AI Ready")
        
        # Quick questions
        st.subheader("Quick Questions")
        col1, col2 = st.columns(2)
        
        with col1:
            if st.button("How to improve experience section?"):
                st.session_state.quick_question = "What's wrong with my experience section?"
        
        with col2:
            if st.button("Make resume ATS-friendly?"):
                st.session_state.quick_question = "How do I make it more ATS-friendly?"
        
        col3, col4 = st.columns(2)
        with col3:
            if st.button("Add better keywords?"):
                st.session_state.quick_question = "What keywords should I add?"
        
        with col4:
            if st.button("Improve skills section?"):
                st.session_state.quick_question = "How can I improve my skills section?"
        
        # Chat input
        user_question = st.text_input(
            "Ask about your resume:",
            value=st.session_state.get('quick_question', ''),
            placeholder="How can I improve my resume?",
            key="improved_chat_input"
        )
        
        # Send button and clear
        col1, col2 = st.columns([1, 3])
        with col1:
            send_clicked = st.button("Send", type="primary")
        with col2:
            if st.button("Clear Chat"):
                st.session_state.improved_chat_history = []
                if 'quick_question' in st.session_state:
                    del st.session_state.quick_question
                st.experimental_rerun()
        
        # Generate response
        if send_clicked and user_question.strip():
            with st.spinner("Generating advice..."):
                response = chatbot.generate_response(user_question, resume_context)
                if 'quick_question' in st.session_state:
                    del st.session_state.quick_question
                st.experimental_rerun()
        
        # Display chat history
        if st.session_state.improved_chat_history:
            st.subheader("πŸ’¬ Conversation")
            
            for conv in reversed(st.session_state.improved_chat_history[-3:]):  # Show last 3
                st.markdown(f"**You:** {conv['user']}")
                st.markdown(f"**AI:** {conv['bot']}")
                st.caption(f"Time: {conv['timestamp']}")
                st.divider()
    
    else:
        st.warning("Click 'Initialize AI' to start chatting")
        
        with st.expander("Improved Features"):
            st.markdown("""
            **Model**: DistilGPT2 with enhanced parameters
            **Response time**: 1-3 seconds
            **Quality**: Significantly improved over basic version
            """)
@st.cache_resource
def download_nltk_data():
    try:
        nltk.data.find('tokenizers/punkt')
        nltk.data.find('corpora/stopwords')
        nltk.data.find('corpora/wordnet')
    except LookupError:
        with st.spinner("Downloading NLTK data..."):
            nltk.download('punkt', quiet=True)
            nltk.download('stopwords', quiet=True)
            nltk.download('wordnet', quiet=True)
            nltk.download('punkt_tab', quiet=True)

@st.cache_resource
def init_tools():
    download_nltk_data()
    
    nlp = None
    if SPACY_AVAILABLE:
        try:
            nlp = spacy.load("en_core_web_sm")
        except OSError:
            try:
                import subprocess
                import sys
                with st.spinner("Downloading spaCy model..."):
                    subprocess.run([sys.executable, "-m", "spacy", "download", "en_core_web_sm"], 
                                 check=True, capture_output=True)
                nlp = spacy.load("en_core_web_sm")
            except Exception as e:
                nlp = None
    
    grammar_tool = None
    if GRAMMAR_TOOL_AVAILABLE:
        try:
            with st.spinner("Initializing grammar checker..."):
                grammar_tool = language_tool_python.LanguageTool('en-US')
        except Exception as e:
            grammar_tool = None
    
    return nlp, grammar_tool

def simple_fuzzy_match(keyword, text):
    """Simple fuzzy matching fallback when fuzzywuzzy is not available"""
    keyword_lower = keyword.lower()
    text_lower = text.lower()
    
    if keyword_lower in text_lower:
        return 100
    
    keyword_words = keyword_lower.split()
    matches = sum(1 for word in keyword_words if word in text_lower)
    return (matches / len(keyword_words)) * 100 if keyword_words else 0

def basic_grammar_check(text):
    """Basic grammar check when language_tool_python is not available"""
    issues = []
    
    sentences = sent_tokenize(text)
    
    for i, sentence in enumerate(sentences):
        if len(sentence.split()) > 30:
            issues.append(f"Sentence {i+1} might be too long ({len(sentence.split())} words)")
        
        words = sentence.lower().split()
        for j in range(len(words) - 1):
            if words[j] == words[j + 1] and len(words[j]) > 3:
                issues.append(f"Repeated word '{words[j]}' in sentence {i+1}")
    
    return [type('MockError', (), {'message': issue}) for issue in issues]

def display_metric_card(title, value, description=""):
    """Display a metric in a card format"""
    st.markdown(f"""
    <div class="metric-card">
        <div class="metric-value">{value}</div>
        <div class="metric-label">{title}</div>
        {f"<small>{description}</small>" if description else ""}
    </div>
    """, unsafe_allow_html=True)

def display_alert_box(message, alert_type="info"):
    """Display alert box with different types"""
    box_class = f"{alert_type}-box"
    st.markdown(f"""
    <div class="{box_class}">
        {message}
    </div>
    """, unsafe_allow_html=True)

class ResumeAnalyzer:
    def __init__(self):
        self.nlp, self.grammar_tool = init_tools()
        self.chatbot = ImprovedCPUChatbot()
        
        try:
            self.stop_words = set(stopwords.words('english'))
        except LookupError:
            self.stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'should', 'could', 'can', 'may', 'might', 'must'}
        
        self.lemmatizer = WordNetLemmatizer()
        
        # Job role keywords dictionary
        self.job_keywords = {
            "Data Scientist": ["python", "machine learning", "statistics", "pandas", "numpy", "scikit-learn", 
                              "tensorflow", "pytorch", "sql", "data analysis", "visualization", "jupyter", "r", "statistics", "deep learning"],
            "Software Engineer": ["programming", "java", "python", "javascript", "react", "node.js", "database",
                                 "git", "agile", "testing", "debugging", "api", "frontend", "backend", "algorithms", "data structures"],
            "Product Manager": ["product", "strategy", "roadmap", "stakeholder", "analytics", "user experience",
                               "market research", "agile", "scrum", "requirements", "metrics", "wireframes", "user stories"],
            "Marketing Manager": ["marketing", "digital marketing", "seo", "social media", "analytics", "campaigns",
                                 "brand", "content", "advertising", "growth", "conversion", "roi", "crm"],
            "Data Analyst": ["sql", "excel", "python", "tableau", "power bi", "statistics", "reporting",
                            "data visualization", "business intelligence", "analytics", "dashboards", "kpi"],
            "DevOps Engineer": ["docker", "kubernetes", "aws", "azure", "gcp", "jenkins", "ci/cd", "terraform",
                               "ansible", "monitoring", "linux", "bash", "infrastructure", "deployment"],
            "UI/UX Designer": ["figma", "sketch", "adobe xd", "prototyping", "wireframes", "user research",
                              "usability testing", "design systems", "responsive design", "accessibility", "typography"],
            "Cybersecurity Analyst": ["security", "penetration testing", "vulnerability assessment", "siem", "firewall",
                                     "incident response", "compliance", "risk assessment", "cryptography", "network security"],
            "Business Analyst": ["requirements gathering", "process improvement", "stakeholder management", "documentation",
                                "business process", "gap analysis", "user stories", "workflow", "project management"],
            "Full Stack Developer": ["html", "css", "javascript", "react", "angular", "vue", "node.js", "express",
                                   "mongodb", "postgresql", "rest api", "graphql", "version control", "responsive design"],
            "Machine Learning Engineer": [
                "python", "tensorflow", "pytorch", "scikit-learn", "pandas", "numpy", "machine learning",
                "deep learning", "neural networks", "computer vision", "nlp", "data science", "algorithms",
                "statistics", "linear algebra", "calculus", "regression", "classification", "clustering",
                "feature engineering", "model deployment", "mlops", "docker", "kubernetes", "aws", "gcp"
            ],
            "AI Engineer": [
                "artificial intelligence", "machine learning", "deep learning", "neural networks", "python",
                "tensorflow", "pytorch", "computer vision", "nlp", "natural language processing", "opencv",
                "transformers", "bert", "gpt", "reinforcement learning", "generative ai", "llm", "chatbot",
                "model optimization", "ai ethics", "edge ai", "quantization", "onnx", "tensorrt"
            ]
        }
        
        # Common skills database
        self.technical_skills = [
            "python", "java", "javascript", "c++", "c#", "php", "ruby", "go", "rust", "swift",
            "sql", "html", "css", "react", "angular", "vue", "node.js", "express", "django", "flask",
            "machine learning", "deep learning", "tensorflow", "pytorch", "pandas", "numpy",
            "docker", "kubernetes", "aws", "azure", "gcp", "git", "jenkins", "ci/cd", "mongodb", "postgresql",
            "redis", "elasticsearch", "spark", "hadoop", "tableau", "power bi", "excel", "figma", "sketch",
            "linux", "bash", "terraform", "ansible", "selenium", "junit", "jira", "confluence"
        ]
        
        self.soft_skills = [
            "leadership", "communication", "teamwork", "problem solving", "critical thinking",
            "project management", "time management", "adaptability", "creativity", "analytical",
            "collaboration", "innovation", "strategic thinking", "customer service", "negotiation",
            "presentation", "mentoring", "conflict resolution", "decision making", "emotional intelligence"
        ]

    def extract_text_from_pdf(self, file):
        """Extract text from PDF file"""
        try:
            with pdfplumber.open(file) as pdf:
                text = ""
                for page in pdf.pages:
                    text += page.extract_text() or ""
            return text
        except:
            try:
                pdf_reader = PyPDF2.PdfReader(file)
                text = ""
                for page in pdf_reader.pages:
                    text += page.extract_text()
                return text
            except:
                return "Error extracting PDF text"

    def extract_text_from_docx(self, file):
        """Extract text from DOCX file"""
        try:
            doc = Document(file)
            text = ""
            for paragraph in doc.paragraphs:
                text += paragraph.text + "\n"
            return text
        except:
            return "Error extracting DOCX text"

    def extract_text_from_txt(self, file):
        """Extract text from TXT file"""
        try:
            return str(file.read(), "utf-8")
        except:
            return "Error extracting TXT text"

    def extract_sections(self, text):
        """Extract different sections from resume"""
        sections = {}
        
        section_patterns = {
            'education': r'(education|academic|qualification|degree|university|college)',
            'experience': r'(experience|employment|work|career|professional|job|position)',
            'skills': r'(skills|technical|competencies|expertise|abilities|technologies)',
            'projects': r'(projects|portfolio|work samples|personal projects)',
            'certifications': r'(certifications?|certificates?|licensed?|credentials)',
            'summary': r'(summary|objective|profile|about|overview)'
        }
        
        text_lower = text.lower()
        lines = text.split('\n')
        
        for section_name, pattern in section_patterns.items():
            section_content = []
            capturing = False
            
            for i, line in enumerate(lines):
                if re.search(pattern, line.lower()):
                    capturing = True
                    continue
                
                if capturing:
                    if any(re.search(p, line.lower()) for p in section_patterns.values() if p != pattern):
                        break
                    if line.strip():
                        section_content.append(line.strip())
            
            sections[section_name] = '\n'.join(section_content)
        
        return sections

    def extract_skills(self, text):
        """Extract technical and soft skills"""
        text_lower = text.lower()
        
        found_technical = []
        found_soft = []
        
        for skill in self.technical_skills:
            if skill.lower() in text_lower:
                found_technical.append(skill)
        
        for skill in self.soft_skills:
            skill_words = skill.lower().split()
            if all(word in text_lower for word in skill_words):
                found_soft.append(skill)
        
        return found_technical, found_soft

    def keyword_matching(self, text, job_role):
        """Match keywords for specific job role"""
        if job_role not in self.job_keywords:
            return [], 0
        
        keywords = self.job_keywords[job_role]
        text_lower = text.lower()
        
        found_keywords = []
        for keyword in keywords:
            if FUZZYWUZZY_AVAILABLE:
                if fuzz.partial_ratio(keyword, text_lower) > 80:
                    found_keywords.append(keyword)
            else:
                if simple_fuzzy_match(keyword, text_lower) > 80:
                    found_keywords.append(keyword)
        
        match_percentage = (len(found_keywords) / len(keywords)) * 100
        return found_keywords, match_percentage

    def grammar_check(self, text):
        """Check grammar and language quality"""
        if self.grammar_tool and GRAMMAR_TOOL_AVAILABLE:
            try:
                matches = self.grammar_tool.check(text[:5000])
                return matches
            except:
                return basic_grammar_check(text)
        else:
            return basic_grammar_check(text)

    def calculate_ats_score(self, text, sections):
        """Calculate ATS friendliness score"""
        score = 0
        
        # Check for key sections (40 points)
        required_sections = ['experience', 'education', 'skills']
        for section in required_sections:
            if sections.get(section) and len(sections[section]) > 50:
                score += 13.33
        
        # Check text length (20 points)
        word_count = len(text.split())
        if 300 <= word_count <= 800:
            score += 20
        elif word_count > 200:
            score += 10
        
        # Check for contact information (20 points)
        email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
        phone_pattern = r'(\+\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}'
        
        if re.search(email_pattern, text):
            score += 10
        if re.search(phone_pattern, text):
            score += 10
        
        # Check for bullet points (20 points)
        bullet_patterns = [r'β€’', r'β—¦', r'\*', r'-\s', r'β†’']
        bullet_count = sum(len(re.findall(pattern, text)) for pattern in bullet_patterns)
        if bullet_count >= 5:
            score += 20
        elif bullet_count >= 2:
            score += 10
        
        return min(score, 100)

    def create_pdf_report(self, text, sections, ats_score, match_percentage, selected_role, tech_skills, soft_skills, found_keywords):
        """Create a PDF report using ReportLab"""
        buffer = io.BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=letter)
        styles = getSampleStyleSheet()
        story = []
        
        # Title
        story.append(Paragraph("Resume Analysis Report", styles['Title']))
        story.append(Spacer(1, 12))
        
        # Date
        story.append(Paragraph(f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", styles['Normal']))
        story.append(Spacer(1, 12))
        
        # Overview section
        story.append(Paragraph("Overview", styles['Heading1']))
        story.append(Paragraph(f"ATS Score: {ats_score}/100", styles['Normal']))
        story.append(Paragraph(f"Role Match for {selected_role}: {match_percentage:.1f}%", styles['Normal']))
        story.append(Paragraph(f"Overall Score: {(ats_score + match_percentage) / 2:.1f}/100", styles['Normal']))
        story.append(Spacer(1, 12))
        
        # Skills section
        story.append(Paragraph("Skills Analysis", styles['Heading1']))
        if tech_skills:
            story.append(Paragraph(f"Technical Skills: {', '.join(tech_skills)}", styles['Normal']))
        if soft_skills:
            story.append(Paragraph(f"Soft Skills: {', '.join(soft_skills)}", styles['Normal']))
        if found_keywords:
            story.append(Paragraph(f"Role-specific Keywords Found: {', '.join(found_keywords)}", styles['Normal']))
        story.append(Spacer(1, 12))
        
        # Recommendations
        story.append(Paragraph("Recommendations", styles['Heading1']))
        recommendations = []
        
        if ats_score < 70:
            recommendations.extend([
                "β€’ Add more bullet points to improve readability",
                "β€’ Include contact information (email, phone)",
                "β€’ Ensure all major sections are present"
            ])
        
        if match_percentage < 60:
            recommendations.append(f"β€’ Include more {selected_role}-specific keywords")
        
        for rec in recommendations:
            story.append(Paragraph(rec, styles['Normal']))
        
        # Build PDF
        doc.build(story)
        buffer.seek(0)
        return buffer

def main():
    st.set_page_config(
        page_title="Professional Resume Analyzer",
        page_icon="πŸ“„",
        layout="wide",
        initial_sidebar_state="expanded"
    )
    
    # Load custom CSS
    load_custom_css()
    
    # Header section
    st.title("Professional Resume Analyzer")
    st.markdown("**Comprehensive resume analysis with AI-powered insights and personalized recommendations**")
    
    # Initialize analyzer
    try:
        analyzer = ResumeAnalyzer()
    except Exception as e:
        st.error(f"Error initializing analyzer: {str(e)}")
        return
    
    # Sidebar configuration
    with st.sidebar:
        st.header("Analysis Configuration")
        
        job_roles = list(analyzer.job_keywords.keys())
        selected_role = st.selectbox(
            "Target Job Role:",
            job_roles,
            help="Select the job role you're targeting to get relevant keyword analysis"
        )
        
        st.divider()
        
        st.header("Analysis Features")
        st.markdown("""
        **Comprehensive Analysis:**
        - ATS Compatibility Score
        - Skills Detection & Matching
        - Section Structure Analysis
        - Grammar & Language Check
        - Keyword Optimization
        - PDF Report Generation
        
        **AI Assistant:**
        - Personalized Resume Advice
        - Quick Expert Recommendations
        - Interactive Q&A
        """)
    
    # Initialize session state
    if "chat_history" not in st.session_state:
        st.session_state.chat_history = []
    if "resume_context" not in st.session_state:
        st.session_state.resume_context = ""
    if "analysis_done" not in st.session_state:
        st.session_state.analysis_done = False
    
    # Main content area
    st.markdown('<h2 class="section-header">Upload Resume</h2>', unsafe_allow_html=True)
    
    uploaded_file = st.file_uploader(
        "Select your resume file",
        type=['pdf', 'docx', 'txt'],
        help="Supported formats: PDF, DOCX, TXT (Maximum size: 200MB)"
    )
    
    if uploaded_file is not None:
        # Show file information
        file_details = {
            "Filename": uploaded_file.name,
            "File size": f"{uploaded_file.size / 1024:.1f} KB",
            "File type": uploaded_file.type
        }
        
        with st.expander("File Information", expanded=False):
            for key, value in file_details.items():
                st.write(f"**{key}:** {value}")
        
        # Extract text based on file type
        file_type = uploaded_file.type
        
        with st.spinner("Processing your resume..."):
            try:
                if file_type == "application/pdf":
                    text = analyzer.extract_text_from_pdf(uploaded_file)
                elif file_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                    text = analyzer.extract_text_from_docx(uploaded_file)
                else:  # txt
                    text = analyzer.extract_text_from_txt(uploaded_file)
            except Exception as e:
                st.error(f"Error extracting text: {str(e)}")
                return
        
        if "Error" not in text and text.strip():
            st.success("Resume processed successfully!")
            
            # Store resume context for chatbot
            st.session_state.resume_context = text
            
            try:
                # Extract data for analysis
                sections = analyzer.extract_sections(text)
                tech_skills, soft_skills = analyzer.extract_skills(text)
                found_keywords, match_percentage = analyzer.keyword_matching(text, selected_role)
                ats_score = analyzer.calculate_ats_score(text, sections)
                
                # Create navigation tabs
                tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs([
                    "Summary", "Skills Analysis", "Section Review", 
                    "ATS Analysis", "Recommendations", "AI Assistant"
                ])
                
                with tab1:
                    st.markdown('<h3 class="section-header">Resume Summary</h3>', unsafe_allow_html=True)
                    
                    # Key metrics row
                    metric_cols = st.columns(4)
                    
                    with metric_cols[0]:
                        display_metric_card("ATS Score", f"{ats_score}/100")
                    
                    with metric_cols[1]:
                        display_metric_card("Role Match", f"{match_percentage:.1f}%")
                    
                    with metric_cols[2]:
                        word_count = len(text.split())
                        display_metric_card("Word Count", f"{word_count}")
                    
                    with metric_cols[3]:
                        sections_found = len([s for s in sections.values() if s])
                        display_metric_card("Sections", f"{sections_found}/6")
                    
                    st.divider()
                    
                    # Overall assessment
                    overall_score = (ats_score + match_percentage) / 2
                    
                    if overall_score >= 80:
                        display_alert_box("Excellent resume! Your resume shows strong alignment with the target role and good ATS compatibility.", "success")
                    elif overall_score >= 60:
                        display_alert_box("Good foundation with room for improvement. Focus on adding more role-specific keywords and optimizing for ATS.", "warning")
                    else:
                        display_alert_box("Significant improvements needed. Consider restructuring sections, adding relevant keywords, and improving ATS compatibility.", "error")
                    
                    # Quick insights
                    col1, col2 = st.columns(2)
                    
                    with col1:
                        st.subheader("Strengths Identified")
                        strengths = []
                        
                        if ats_score >= 70:
                            strengths.append("Good ATS compatibility")
                        if match_percentage >= 60:
                            strengths.append("Strong role alignment")
                        if len(tech_skills) >= 5:
                            strengths.append("Rich technical skills")
                        if len(soft_skills) >= 3:
                            strengths.append("Good soft skills coverage")
                        
                        if strengths:
                            for strength in strengths:
                                st.write(f"βœ“ {strength}")
                        else:
                            st.write("Focus on the recommendations to improve your resume")
                    
                    with col2:
                        st.subheader("Keywords Found")
                        if found_keywords:
                            # Display as tags
                            keyword_html = ""
                            for keyword in found_keywords[:10]:  # Show first 10
                                keyword_html += f'<span class="skill-tag">{keyword}</span>'
                            st.markdown(keyword_html, unsafe_allow_html=True)
                        else:
                            st.write("No role-specific keywords detected")
                
                with tab2:
                    st.markdown('<h3 class="section-header">Skills Analysis</h3>', unsafe_allow_html=True)
                    
                    col1, col2 = st.columns(2)
                    
                    with col1:
                        st.subheader("Technical Skills Detected")
                        if tech_skills:
                            # Create skill tags
                            tech_html = ""
                            for skill in tech_skills:
                                tech_html += f'<span class="skill-tag">{skill}</span>'
                            st.markdown(tech_html, unsafe_allow_html=True)
                            
                            st.metric("Technical Skills Count", len(tech_skills))
                        else:
                            display_alert_box("No technical skills detected. Consider adding a dedicated skills section.", "warning")
                    
                    with col2:
                        st.subheader("Soft Skills Detected")
                        if soft_skills:
                            # Create skill tags
                            soft_html = ""
                            for skill in soft_skills:
                                soft_html += f'<span class="skill-tag">{skill}</span>'
                            st.markdown(soft_html, unsafe_allow_html=True)
                            
                            st.metric("Soft Skills Count", len(soft_skills))
                        else:
                            display_alert_box("Limited soft skills detected. Consider highlighting leadership, communication, and teamwork skills.", "info")
                    
                    st.divider()
                    
                    # Role-specific analysis
                    st.subheader(f"Analysis for {selected_role}")
                    
                    progress_col, details_col = st.columns([1, 2])
                    
                    with progress_col:
                        # Create a progress bar for match percentage
                        st.metric("Match Percentage", f"{match_percentage:.1f}%")
                        st.progress(match_percentage / 100)
                    
                    with details_col:
                        if match_percentage >= 70:
                            display_alert_box("Excellent match for this role! Your skills align well with industry expectations.", "success")
                        elif match_percentage >= 50:
                            display_alert_box("Good match with opportunities for improvement. Consider adding more role-specific skills.", "warning")
                        else:
                            display_alert_box("Limited match detected. Focus on adding more relevant skills and keywords for this role.", "error")
                    
                    # Missing keywords
                    missing_keywords = [kw for kw in analyzer.job_keywords[selected_role] 
                                      if kw not in found_keywords]
                    
                    if missing_keywords:
                        st.subheader("Suggested Keywords to Add")
                        missing_html = ""
                        for keyword in missing_keywords[:15]:  # Show top 15
                            missing_html += f'<span class="skill-tag" style="background-color: #fff3cd;">{keyword}</span>'
                        st.markdown(missing_html, unsafe_allow_html=True)
                
                with tab3:
                    st.markdown('<h3 class="section-header">Section Structure Review</h3>', unsafe_allow_html=True)
                    
                    # Section status overview
                    st.subheader("Section Completeness")
                    
                    section_status = []
                    for section_name, section_content in sections.items():
                        status = "Complete" if section_content and len(section_content) > 50 else "Missing/Incomplete"
                        section_status.append({
                            "Section": section_name.title(),
                            "Status": status,
                            "Length": len(section_content) if section_content else 0
                        })
                    
                    status_df = pd.DataFrame(section_status)
                    st.dataframe(status_df, use_container_width=True, hide_index=True)
                    
                    st.divider()
                    
                    # Detailed section content
                    st.subheader("Section Content")
                    
                    for section_name, section_content in sections.items():
                        with st.expander(f"{section_name.title()} Section", expanded=False):
                            if section_content:
                                st.text_area(
                                    f"{section_name.title()} content:",
                                    section_content,
                                    height=150,
                                    disabled=True,
                                    key=f"section_{section_name}"
                                )
                            else:
                                st.warning(f"No {section_name} section found or content is too brief")
                
                with tab4:
                    st.markdown('<h3 class="section-header">ATS Compatibility Analysis</h3>', unsafe_allow_html=True)
                    
                    # ATS score breakdown
                    col1, col2 = st.columns([1, 2])
                    
                    with col1:
                        st.metric("Overall ATS Score", f"{ats_score}/100")
                        st.progress(ats_score / 100)
                        
                        # Score interpretation
                        if ats_score >= 80:
                            st.success("Excellent ATS compatibility")
                        elif ats_score >= 60:
                            st.warning("Good ATS compatibility")
                        else:
                            st.error("Needs ATS optimization")
                    
                    with col2:
                        st.subheader("ATS Checklist")
                        
                        # Check various ATS factors
                        checklist_items = []
                        
                        # Section check
                        required_sections = ['experience', 'education', 'skills']
                        sections_present = sum(1 for section in required_sections 
                                             if sections.get(section) and len(sections[section]) > 50)
                        checklist_items.append(("Essential sections present", sections_present >= 2))
                        
                        # Content length check
                        word_count = len(text.split())
                        checklist_items.append(("Appropriate length (300-800 words)", 300 <= word_count <= 800))
                        
                        # Contact information
                        email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
                        phone_pattern = r'(\+\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}'
                        has_email = bool(re.search(email_pattern, text))
                        has_phone = bool(re.search(phone_pattern, text))
                        checklist_items.append(("Contact information included", has_email or has_phone))
                        
                        # Bullet points
                        bullet_patterns = [r'β€’', r'β—¦', r'\*', r'-\s', r'β†’']
                        bullet_count = sum(len(re.findall(pattern, text)) for pattern in bullet_patterns)
                        checklist_items.append(("Uses bullet points", bullet_count >= 2))
                        
                        # Keywords
                        checklist_items.append(("Contains relevant keywords", len(found_keywords) >= 3))
                        
                        for item, passed in checklist_items:
                            status = "βœ“" if passed else "βœ—"
                            color = "green" if passed else "red"
                            st.markdown(f"<span style='color:{color}'>{status} {item}</span>", unsafe_allow_html=True)
                    
                    st.divider()
                    
                    # Grammar analysis
                    col1, col2 = st.columns(2)
                    
                    with col1:
                        st.subheader("Language Quality Check")
                        grammar_issues = analyzer.grammar_check(text)
                        
                        if len(grammar_issues) == 0:
                            display_alert_box("No grammar issues detected", "success")
                        else:
                            display_alert_box(f"{len(grammar_issues)} potential issues found", "warning")
                    
                    with col2:
                        if grammar_issues:
                            st.subheader("Issues Detected")
                            for issue in grammar_issues[:5]:  # Show first 5
                                st.write(f"β€’ {issue.message}")
                    
                    # ATS optimization tips
                    st.subheader("ATS Optimization Recommendations")
                    
                    tips = [
                        "Use standard section headings: Experience, Education, Skills, etc.",
                        "Include relevant keywords naturally throughout your resume",
                        "Use bullet points to improve readability and scanning",
                        "Avoid images, graphics, tables, and complex formatting",
                        "Use standard fonts like Arial, Calibri, or Times New Roman",
                        "Save your resume as a PDF to preserve formatting",
                        "Include your contact information prominently at the top",
                        "Use consistent formatting throughout the document"
                    ]
                    
                    for i, tip in enumerate(tips, 1):
                        st.write(f"{i}. {tip}")
                
                with tab5:
                    st.markdown('<h3 class="section-header">Personalized Recommendations</h3>', unsafe_allow_html=True)
                    
                    # Generate specific recommendations
                    recommendations = []
                    
                    # ATS-based recommendations
                    if ats_score < 70:
                        recommendations.extend([
                            "Improve ATS compatibility by adding more bullet points throughout your resume",
                            "Ensure your contact information (email and phone) is clearly visible at the top",
                            "Use standard section headings that ATS systems can easily recognize"
                        ])
                    
                    # Role matching recommendations
                    if match_percentage < 60:
                        recommendations.append(f"Increase your match for {selected_role} by incorporating more industry-specific keywords")
                    
                    # Skills recommendations
                    if not tech_skills:
                        recommendations.append("Add a dedicated Technical Skills section to highlight your capabilities")
                    
                    if not soft_skills:
                        recommendations.append("Incorporate more soft skills like leadership, communication, and teamwork throughout your experience descriptions")
                    
                    # Section recommendations
                    missing_sections = [name for name, content in sections.items() if not content]
                    if missing_sections:
                        recommendations.append(f"Consider adding these missing sections: {', '.join(missing_sections)}")
                    
                    if not sections.get('projects'):
                        recommendations.append("Add a Projects section to showcase hands-on experience and technical skills")
                    
                    # Display recommendations
                    if recommendations:
                        for i, rec in enumerate(recommendations, 1):
                            st.write(f"**{i}.** {rec}")
                    else:
                        display_alert_box("Your resume looks great! Minor tweaks based on specific job applications can further improve your success rate.", "success")
                    
                    st.divider()
                    
                    # Action plan
                    st.subheader("Priority Action Plan")
                    
                    action_items = []
                    
                    if ats_score < 60:
                        action_items.append("**High Priority:** Improve ATS compatibility - focus on formatting and standard sections")
                    
                    if match_percentage < 50:
                        action_items.append("**High Priority:** Add more role-specific keywords and skills")
                    
                    if not tech_skills and selected_role in ["Data Scientist", "Software Engineer", "DevOps Engineer"]:
                        action_items.append("**Medium Priority:** Add comprehensive technical skills section")
                    
                    if len([s for s in sections.values() if s]) < 4:
                        action_items.append("**Medium Priority:** Ensure all essential sections are complete and substantial")
                    
                    action_items.append("**Ongoing:** Customize your resume for each job application by matching keywords")
                    
                    for action in action_items:
                        st.markdown(action)
                    
                    st.divider()
                    
                    # PDF report generation
                    st.subheader("Download Detailed Report")
                    
                    col1, col2 = st.columns([2, 1])
                    
                    with col1:
                        st.write("Generate a comprehensive PDF report with all analysis results, recommendations, and action items.")
                    
                    with col2:
                        if st.button("Generate PDF Report", type="primary", use_container_width=True):
                            try:
                                with st.spinner("Generating report..."):
                                    pdf_buffer = analyzer.create_pdf_report(
                                        text, sections, ats_score, match_percentage, 
                                        selected_role, tech_skills, soft_skills, found_keywords
                                    )
                                
                                st.download_button(
                                    label="Download Report",
                                    data=pdf_buffer.getvalue(),
                                    file_name=f"resume_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf",
                                    mime="application/pdf",
                                    use_container_width=True
                                )
                            except Exception as e:
                                st.error(f"Error generating PDF: {str(e)}")
                
                with tab6:
                    # AI Chat Interface
                    create_improved_chat_interface(st.session_state.get('resume_context', ''))
                
            except Exception as e:
                st.error(f"Error during analysis: {str(e)}")
                st.error("Please check your resume format and try again.")
        
        else:
            st.error("Could not extract text from the uploaded file. Please check the file format and try again.")
    
    else:
        # Instructions and information when no file is uploaded
        st.markdown('<h3 class="section-header">Getting Started</h3>', unsafe_allow_html=True)
        
        col1, col2 = st.columns([2, 1])
        
        with col1:
            st.subheader("How It Works")
            st.markdown("""
            **1. Upload Your Resume**
            Upload your resume in PDF, DOCX, or TXT format using the file uploader above.
            
            **2. Select Target Role**
            Choose your target job role from the sidebar to get relevant keyword analysis.
            
            **3. Get Comprehensive Analysis**
            Review detailed analysis across multiple categories including ATS compatibility, skills matching, and section structure.
            
            **4. Get AI-Powered Recommendations**
            Use the AI assistant for personalized advice and answers to your specific questions.
            
            **5. Download Report**
            Generate and download a comprehensive PDF report with all findings and recommendations.
            """)
        
        with col2:
            st.subheader("Analysis Features")
            
            features = [
                "ATS Compatibility Scoring",
                "Skills Detection & Matching",
                "Keyword Optimization",
                "Section Structure Analysis",
                "Grammar & Language Check",
                "Role-Specific Recommendations",
                "AI-Powered Chat Assistant",
                "Downloadable PDF Reports"
            ]
            
            for feature in features:
                st.write(f"βœ“ {feature}")
        
        # Sample analysis preview
        with st.expander("Preview: What You'll Get", expanded=False):
            st.subheader("Sample Analysis Output")
            
            sample_cols = st.columns(3)
            
            with sample_cols[0]:
                display_metric_card("ATS Score", "85/100")
            
            with sample_cols[1]:
                display_metric_card("Role Match", "72%")
            
            with sample_cols[2]:
                display_metric_card("Overall", "A-")
            
            st.markdown("""
            **You'll receive detailed analysis including:**
            - Comprehensive scoring and metrics
            - Section-by-section breakdown
            - Specific improvement recommendations
            - Missing keywords identification
            - ATS optimization checklist
            - AI-powered personalized advice
            """)

if __name__ == "__main__":
    main()