forked from Divanshu0212/Pr_Project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp4.py
More file actions
1352 lines (1146 loc) · 50.1 KB
/
Copy pathtemp4.py
File metadata and controls
1352 lines (1146 loc) · 50.1 KB
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
from fastapi import FastAPI, HTTPException, Response
from fastapi.responses import HTMLResponse, FileResponse
from pydantic import BaseModel, Field
from typing import List, Optional, Dict, Any
import requests
import json
import re
from datetime import datetime
import uuid
import os
import tempfile
from pathlib import Path
import weasyprint
from jinja2 import Template
# LangChain imports
from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough, RunnableLambda
from fastapi.middleware.cors import CORSMiddleware
os.environ["LANGCHAIN_API_KEY"] = os.getenv("LANGCHAIN_API_KEY","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")
os.environ["LANGCHAIN_TRACING_V2"] = os.getenv("LANGCHAIN_TRACING_V2", "true")
os.environ["LANGCHAIN_PROJECT"] = os.getenv("LANGCHAIN_PROJECT", "Resume")
# Groq API configuration
GROQ_API_KEY = os.getenv("GROQ_API_KEY","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")
if not GROQ_API_KEY:
raise ValueError("GROQ_API_KEY environment variable is required")
app = FastAPI(title="Resume Maker API with Groq Integration", version="2.1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, replace with specific origins like ["http://localhost:3000", "https://yourdomain.com"]
allow_credentials=True,
allow_methods=["*"], # Or specify methods like ["GET", "POST", "PUT", "DELETE"]
allow_headers=["*"], # Or specify headers like ["Content-Type", "Authorization"]
)
# Pydantic models
class WorkExperience(BaseModel):
company: str
position: str
start_date: str
end_date: Optional[str] = None
location: Optional[str] = None
responsibilities: List[str]
achievements: List[str] = []
class Education(BaseModel):
institution: str
degree: str
field_of_study: str
graduation_date: str
gpa: Optional[str] = None
relevant_coursework: List[str] = []
class Project(BaseModel):
name: str
description: str
technologies: List[str]
achievements: List[str] = []
url: Optional[str] = None
class ResumeData(BaseModel):
personal_info: Dict[str, str] = Field(..., description="Name, email, phone, location, etc.")
professional_summary: Optional[str] = None
work_experience: List[WorkExperience]
education: List[Education]
skills: Dict[str, List[str]] = Field(default_factory=dict, description="Categories of skills")
projects: List[Project] = []
certifications: List[str] = []
languages: List[str] = []
target_job_description: Optional[str] = None
class ResumeRequest(BaseModel):
resume_data: ResumeData
job_description: Optional[str] = None
resume_format: str = "professional"
class ResumeResponse(BaseModel):
resume_id: str
optimized_resume: str
score: int
feedback: Dict[str, Any]
suggestions: List[str]
html_content: str
pdf_available: bool = True
class OptimizedResumeParser:
"""Parser to extract structured data from optimized resume text"""
def parse_optimized_resume(self, optimized_text: str, original_data: ResumeData) -> ResumeData:
"""Parse the optimized resume text and create a new ResumeData object"""
try:
# Create a copy of original data to modify
optimized_data = ResumeData(
personal_info=original_data.personal_info.copy(),
work_experience=[],
education=original_data.education.copy(),
skills=original_data.skills.copy(),
projects=[],
certifications=original_data.certifications.copy(),
languages=original_data.languages.copy()
)
# Extract professional summary
summary_match = re.search(r'\*\*Professional Summary:\*\*\s*\n(.+?)(?=\n\*\*|\n$)', optimized_text, re.DOTALL | re.IGNORECASE)
if summary_match:
summary_text = summary_match.group(1).strip()
summary_text = summary_text.strip('"').strip()
optimized_data.professional_summary = summary_text
# Extract work experience
work_section = re.search(r'\*\*Work Experience:\*\*\s*\n(.+?)(?=\n\*\*Education|\n\*\*Technical Skills|\n$)', optimized_text, re.DOTALL | re.IGNORECASE)
if work_section:
optimized_data.work_experience = self._parse_work_experience(work_section.group(1))
# Extract projects
projects_section = re.search(r'\*\*Projects:\*\*\s*\n(.+?)(?=\n\*\*Certifications|\n\*\*Languages|\n$)', optimized_text, re.DOTALL | re.IGNORECASE)
if projects_section:
optimized_data.projects = self._parse_projects(projects_section.group(1))
return optimized_data
except Exception as e:
print(f"Error parsing optimized resume: {e}")
return original_data
def _parse_work_experience(self, work_text: str) -> List[WorkExperience]:
"""Parse work experience from optimized text"""
experiences = []
# Split by job entries
job_entries = re.split(r'\n(?=\*\*[^*]+\s+at\s+[^*]+\s+\([^)]+\)\*\*)', work_text.strip())
for entry in job_entries:
if not entry.strip():
continue
# Extract job header
header_match = re.search(r'\*\*(.+?)\s+at\s+(.+?)\s+\((.+?)\)\*\*', entry)
if not header_match:
continue
position = header_match.group(1).strip()
company = header_match.group(2).strip()
date_range = header_match.group(3).strip()
# Parse date range
if ' - ' in date_range:
start_date, end_date = date_range.split(' - ', 1)
end_date = None if end_date.strip().lower() == 'present' else end_date.strip()
else:
start_date = date_range
end_date = None
# Extract location if present
location_match = re.search(r'Location:\s*([^\n]+)', entry)
location = location_match.group(1).strip() if location_match else None
# Extract responsibilities
responsibilities = []
resp_section = re.search(r'Responsibilities:\s*\n((?:• .+\n?)+)', entry, re.DOTALL)
if resp_section:
resp_lines = resp_section.group(1).split('\n')
for line in resp_lines:
line = line.strip()
if line.startswith('•'):
clean_line = line.strip('• ').strip().strip('"').strip()
if clean_line:
responsibilities.append(clean_line)
# Extract achievements
achievements = []
ach_section = re.search(r'Achievements:\s*\n((?:• .+\n?)+)', entry, re.DOTALL)
if ach_section:
ach_lines = ach_section.group(1).split('\n')
for line in ach_lines:
line = line.strip()
if line.startswith('•'):
clean_line = line.strip('• ').strip().strip('"').strip()
if clean_line:
achievements.append(clean_line)
experiences.append(WorkExperience(
company=company,
position=position,
start_date=start_date.strip(),
end_date=end_date,
location=location,
responsibilities=responsibilities,
achievements=achievements
))
return experiences
def _parse_projects(self, projects_text: str) -> List[Project]:
"""Parse projects from optimized text"""
projects = []
# Split by project entries
project_entries = re.split(r'\n(?=\*\*[^*]+\*\*(?:\n|$))', projects_text.strip())
for entry in project_entries:
if not entry.strip():
continue
# Extract project name
name_match = re.search(r'\*\*([^*]+?)\*\*', entry)
if not name_match:
continue
full_name = name_match.group(1).strip()
# Check if name contains a dash
if ' - ' in full_name:
name, description = full_name.split(' - ', 1)
name = name.strip()
else:
name = full_name
desc_match = re.search(r'\*\*[^*]+\*\*\s*\n([^\n]+)', entry)
description = desc_match.group(1).strip() if desc_match else ""
# Extract technologies
technologies = []
tech_match = re.search(r'Technologies:\s*([^\n]+)', entry)
if tech_match:
tech_text = tech_match.group(1).strip()
technologies = [tech.strip() for tech in tech_text.split(',')]
# Extract achievements
achievements = []
ach_section = re.search(r'Achievements:\s*\n((?:• .+\n?)+)', entry, re.DOTALL)
if ach_section:
ach_lines = ach_section.group(1).split('\n')
for line in ach_lines:
line = line.strip()
if line.startswith('•'):
clean_line = line.strip('• ').strip().strip('"').strip()
if clean_line:
achievements.append(clean_line)
# Extract URL
url_match = re.search(r'URL:\s*([^\n]+)', entry)
url = url_match.group(1).strip() if url_match else None
projects.append(Project(
name=name,
description=description,
technologies=technologies,
achievements=achievements,
url=url
))
return projects
class HTMLResumeGenerator:
"""Generator for HTML and PDF resumes"""
def __init__(self):
self.template_dir = "html_templates"
self.ensure_template_dir()
self.parser = OptimizedResumeParser()
def ensure_template_dir(self):
"""Ensure template directory exists"""
if not os.path.exists(self.template_dir):
os.makedirs(self.template_dir)
def generate_resume_html(self, original_resume_data: ResumeData, optimized_content: str,
analysis: Dict[str, Any], resume_id: str) -> str:
"""Generate HTML resume using optimized content"""
# Parse optimized content into structured data
optimized_resume_data = self.parser.parse_optimized_resume(optimized_content, original_resume_data)
template = self._get_html_template()
# Prepare template variables using optimized data
template_vars = {
'personal_info': optimized_resume_data.personal_info,
'professional_summary': optimized_resume_data.professional_summary,
'work_experience': optimized_resume_data.work_experience,
'education': optimized_resume_data.education,
'skills': optimized_resume_data.skills,
'projects': optimized_resume_data.projects,
'certifications': optimized_resume_data.certifications,
'languages': optimized_resume_data.languages,
'analysis': analysis,
'resume_id': resume_id,
'optimized_content': optimized_content
}
# Render template
jinja_template = Template(template)
html_content = jinja_template.render(**template_vars)
return html_content
def generate_resume_pdf(self, html_content: str, resume_id: str) -> str:
"""Generate PDF from HTML using WeasyPrint"""
try:
# Create temporary file for PDF
temp_dir = tempfile.gettempdir()
pdf_filename = f"resume_{resume_id}.pdf"
pdf_path = os.path.join(temp_dir, pdf_filename)
# Generate PDF
weasyprint.HTML(string=html_content).write_pdf(pdf_path)
return pdf_path
except Exception as e:
print(f"PDF generation failed: {e}")
return None
def _get_html_template(self) -> str:
"""Get professional HTML template with clean, traditional formatting"""
return """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ personal_info.name or personal_info.Name }} - Resume</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Times New Roman', Times, serif;
line-height: 1.5;
color: #000;
max-width: 210mm;
margin: 0 auto;
padding: 2.5mm;
background: #fff;
font-size: 12px;
}
.header {
text-align: center;
padding-bottom: 5px;
border-bottom: 1px solid #000;
margin-bottom: 8px;
}
.name {
font-size: 20px;
font-weight: bold;
color: #000;
margin-bottom: 3px;
letter-spacing: 1px;
}
.contact-info {
font-size: 11px;
color: #000;
line-height: 1.3;
}
.contact-info span {
display: inline-block;
margin: 0 8px;
}
.contact-info span:not(:last-child):after {
content: " |";
margin-left: 8px;
}
.section {
margin-bottom: 8px;
}
.section-title {
font-size: 14px;
font-weight: bold;
color: #000;
text-transform: uppercase;
letter-spacing: 0.5px;
border-bottom: 1px solid #000;
padding-bottom: 1px;
margin-bottom: 5px;
}
.summary {
text-align: justify;
line-height: 1.4;
color: #000;
margin-bottom: 2px;
}
.experience-item, .education-item, .project-item {
margin-bottom: 6px;
}
.item-header {
margin-bottom: 2px;
}
.item-title {
font-weight: bold;
font-size: 13px;
color: #000;
display: inline;
}
.item-subtitle {
color: #000;
font-size: 12px;
font-style: italic;
display: inline;
margin-left: 10px;
}
.item-date {
color: #000;
font-size: 11px;
float: right;
font-weight: normal;
}
.clear {
clear: both;
}
.bullet-points {
margin-top: 2px;
margin-left: 15px;
}
.bullet-point {
margin-bottom: 1px;
text-align: justify;
line-height: 1.4;
list-style-type: disc;
display: list-item;
}
.bullet-points strong {
font-weight: bold;
margin-bottom: 1px;
display: block;
margin-left: -15px;
}
.skills-grid {
line-height: 1.4;
}
.skill-category {
margin-bottom: 3px;
}
.skill-category h4 {
font-weight: bold;
font-size: 12px;
color: #000;
display: inline;
margin-right: 10px;
}
.skill-tags {
display: inline;
}
.skill-tag {
font-size: 12px;
color: #000;
}
.skill-tag:not(:last-child):after {
content: ", ";
}
.project-tech {
font-size: 11px;
color: #000;
margin-top: 3px;
font-style: italic;
}
.tech-tag {
font-size: 11px;
color: #000;
}
.tech-tag:not(:last-child):after {
content: ", ";
}
.certifications {
list-style-type: none;
margin-left: 0;
}
.certification-item {
margin-bottom: 3px;
position: relative;
padding-left: 15px;
}
.certification-item:before {
content: "•";
position: absolute;
left: 0;
}
.languages-list {
line-height: 1.4;
}
@media print {
body {
font-size: 11px;
padding: 2mm;
}
.name {
font-size: 18px;
}
.section-title {
font-size: 13px;
}
.item-title {
font-size: 12px;
}
}
</style>
</head>
<body>
<!-- Header -->
<div class="header">
<div class="name">{{ personal_info.name or personal_info.Name }}</div>
<div class="contact-info">
{% if personal_info.email or personal_info.Email %}<span>{{ personal_info.email or personal_info.Email }}</span>{% endif %}
{% if personal_info.phone or personal_info.Phone %}<span>{{ personal_info.phone or personal_info.Phone }}</span>{% endif %}
{% if personal_info.location or personal_info.Location %}<span>{{ personal_info.location or personal_info.Location }}</span>{% endif %}
{% if personal_info.linkedin or personal_info.Linkedin %}<span>{{ personal_info.linkedin or personal_info.Linkedin }}</span>{% endif %}
{% if personal_info.github or personal_info.Github %}<span>{{ personal_info.github or personal_info.Github }}</span>{% endif %}
</div>
</div>
<!-- Professional Summary -->
{% if professional_summary %}
<div class="section">
<div class="section-title">Professional Summary</div>
<div class="summary">{{ professional_summary }}</div>
</div>
{% endif %}
<!-- Work Experience -->
{% if work_experience %}
<div class="section">
<div class="section-title">Achievements</div>
{% for exp in work_experience %}
<div class="experience-item">
{% if exp.achievements %}
<div class="bullet-points">
{% for ach in exp.achievements %}
<li class="bullet-point">{{ ach }}</li>
{% endfor %}
</div>
{% endif %}
</div>
{% endfor %}
</div>
{% endif %}
<!-- Education -->
{% if education %}
<div class="section">
<div class="section-title">Education</div>
{% for edu in education %}
<div class="education-item">
<div class="item-header">
<span class="item-title">{{ edu.degree }} in {{ edu.field_of_study }}</span>
<span class="item-subtitle">{{ edu.institution }}</span>
<span class="item-date">{{ edu.graduation_date }}</span>
<div class="clear"></div>
{% if edu.gpa %}<div style="margin-top: 2px; font-size: 11px;"><strong>GPA:</strong> {{ edu.gpa }}</div>{% endif %}
</div>
</div>
{% endfor %}
</div>
{% endif %}
<!-- Skills -->
{% if skills %}
<div class="section">
<div class="section-title">Technical Skills</div>
<div class="skills-grid">
{% for category, skill_list in skills.items() %}
<div class="skill-category">
<h4>{{ category }}:</h4>
<span class="skill-tags">
{% for skill in skill_list %}
<span class="skill-tag">{{ skill }}</span>
{% endfor %}
</span>
</div>
{% endfor %}
</div>
</div>
{% endif %}
<!-- Projects -->
{% if projects %}
<div class="section">
<div class="section-title">Projects</div>
{% for project in projects %}
<div class="project-item">
<div class="item-header">
<span class="item-title">{{ project.name }}</span>
<span class="item-subtitle">{{ project.description }}</span>
{% if project.url %}<span class="item-date">{{ project.url }}</span>{% endif %}
<div class="clear"></div>
</div>
{% if project.technologies %}
<div class="project-tech">
<strong>Technologies:</strong>
{% for tech in project.technologies %}
<span class="tech-tag">{{ tech }}</span>
{% endfor %}
</div>
{% endif %}
{% if project.achievements %}
<div class="bullet-points">
<strong>Achievements:</strong>
{% for ach in project.achievements %}
<li class="bullet-point">{{ ach }}</li>
{% endfor %}
</div>
{% endif %}
</div>
{% endfor %}
</div>
{% endif %}
<!-- Certifications -->
{% if certifications %}
<div class="section">
<div class="section-title">Certifications</div>
<ul class="certifications">
{% for cert in certifications %}
<li class="certification-item">{{ cert }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
<!-- Languages -->
{% if languages %}
<div class="section">
<div class="section-title">Languages</div>
<div class="languages-list">{{ languages | join(', ') }}</div>
</div>
{% endif %}
</body>
</html>
"""
class ResumeOptimizer:
"""Enhanced Resume Optimizer with Groq integration"""
def __init__(self):
self.action_verbs = [
"Achieved", "Developed", "Implemented", "Led", "Managed", "Created",
"Designed", "Established", "Improved", "Increased", "Reduced",
"Streamlined", "Optimized", "Delivered", "Executed", "Launched"
]
self.weak_verbs = [
"responsible for", "worked on", "helped with", "assisted",
"participated in", "involved in", "duties included"
]
# Initialize LangChain components
self.llm = ChatGroq(
model="llama-3.3-70b-versatile", # or "mixtral-8x7b-32768", "gemma-7b-it"
temperature=0.3,
groq_api_key=GROQ_API_KEY
)
self.output_parser = StrOutputParser()
def extract_keywords_from_job_description(self, job_description: str) -> List[str]:
"""Extract relevant keywords from job description"""
if not job_description:
return []
# Create a prompt template for keyword extraction
keyword_prompt = ChatPromptTemplate.from_template("""
Extract the most important technical and professional keywords from this job description.
Focus on skills, technologies, methodologies, and qualifications mentioned as requirements.
Return only a comma-separated list of keywords, nothing else.
Job Description:
{job_description}
""")
# Create a chain
keyword_chain = (
{"job_description": RunnablePassthrough()}
| keyword_prompt
| self.llm
| self.output_parser
)
try:
# Invoke the chain
keyword_response = keyword_chain.invoke(job_description)
# Process the response
keywords = [kw.strip() for kw in keyword_response.split(",") if kw.strip()]
return list(set(keywords))[:20] # Limit to top 20 unique keywords
except Exception as e:
print(f"Error extracting keywords with LangChain: {e}")
# Fallback to regex-based extraction
return self._fallback_keyword_extraction(job_description)
def _fallback_keyword_extraction(self, job_description: str) -> List[str]:
"""Fallback keyword extraction using regex"""
keywords = []
text = job_description.lower()
# Technical skills patterns
tech_patterns = r'\b(?:python|java|javascript|react|node\.?js|sql|aws|docker|kubernetes|machine learning|ai|data science|agile|scrum)\b'
keywords.extend(re.findall(tech_patterns, text, re.IGNORECASE))
# Extract words that appear after common requirement indicators
requirement_patterns = r'(?:require[ds]?|must have|should have|experience with|knowledge of|proficient in|familiar with)[\s:]+([^.!?]+)'
matches = re.findall(requirement_patterns, text, re.IGNORECASE)
for match in matches:
words = re.findall(r'\b[a-zA-Z][a-zA-Z0-9+#.]*\b', match)
keywords.extend(words[:5])
return list(set(keywords))
def analyze_resume_content(self, resume_data: ResumeData, job_keywords: List[str]) -> Dict[str, Any]:
"""Analyze resume content and provide scoring"""
analysis = {
"impact_score": 0,
"keyword_score": 0,
"formatting_score": 0,
"brevity_score": 0,
"issues": [],
"suggestions": []
}
analysis["impact_score"] = self._analyze_impact(resume_data)
analysis["keyword_score"] = self._analyze_keywords(resume_data, job_keywords)
analysis["formatting_score"] = self._analyze_formatting(resume_data)
analysis["brevity_score"] = self._analyze_brevity(resume_data)
return analysis
def _analyze_impact(self, resume_data: ResumeData) -> int:
"""Analyze impact and quantification in resume"""
score = 0
total_points = 0
for experience in resume_data.work_experience:
for responsibility in experience.responsibilities + experience.achievements:
total_points += 1
if re.search(r'\d+%|\$\d+|(\d+,)?\d+\s+(users|customers|people|projects|team|members)', responsibility):
score += 1
if any(verb.lower() in responsibility.lower() for verb in self.action_verbs):
score += 1
return min(100, int((score / max(total_points, 1)) * 100))
def _analyze_keywords(self, resume_data: ResumeData, job_keywords: List[str]) -> int:
"""Analyze keyword optimization"""
if not job_keywords:
return 85
resume_text = self._extract_resume_text(resume_data).lower()
matched_keywords = sum(1 for keyword in job_keywords if keyword.lower() in resume_text)
return min(100, int((matched_keywords / len(job_keywords)) * 100))
def _analyze_formatting(self, resume_data: ResumeData) -> int:
"""Analyze formatting and structure"""
score = 100
if not resume_data.professional_summary:
score -= 10
if not resume_data.work_experience:
score -= 20
if not resume_data.education:
score -= 10
if not resume_data.skills:
score -= 15
return max(0, score)
def _analyze_brevity(self, resume_data: ResumeData) -> int:
"""Analyze brevity and conciseness"""
total_text = self._extract_resume_text(resume_data)
word_count = len(total_text.split())
if 400 <= word_count <= 800:
return 100
elif word_count < 400:
return max(60, 100 - (400 - word_count) // 10 * 5)
else:
return max(60, 100 - (word_count - 800) // 50 * 5)
def _extract_resume_text(self, resume_data: ResumeData) -> str:
"""Extract all text from resume data"""
text_parts = []
if resume_data.professional_summary:
text_parts.append(resume_data.professional_summary)
for exp in resume_data.work_experience:
text_parts.extend(exp.responsibilities + exp.achievements)
for skill_list in resume_data.skills.values():
text_parts.extend(skill_list)
for project in resume_data.projects:
text_parts.append(project.description)
text_parts.extend(project.achievements)
return " ".join(text_parts)
def generate_resume(self, resume_data: ResumeData, analysis: Dict[str, Any],
job_keywords: List[str], format_type: str = "professional") -> str:
"""Generate optimized resume using LangChain pipelines"""
try:
# Create chains for each section
summary_chain = self._create_summary_chain()
bullet_chain = self._create_bullet_chain()
project_chain = self._create_project_chain()
# Optimize professional summary
optimized_summary = summary_chain.invoke({
"current_summary": resume_data.professional_summary or "",
"job_keywords": job_keywords
})
# Optimize work experience
optimized_experience = []
for exp in resume_data.work_experience:
# Optimize responsibilities
optimized_responsibilities = []
for resp in exp.responsibilities:
optimized_resp = bullet_chain.invoke({
"bullet_point": resp,
"job_keywords": job_keywords,
"point_type": "responsibility"
})
optimized_responsibilities.append(optimized_resp)
# Optimize achievements
optimized_achievements = []
for ach in exp.achievements:
optimized_ach = bullet_chain.invoke({
"bullet_point": ach,
"job_keywords": job_keywords,
"point_type": "achievement"
})
optimized_achievements.append(optimized_ach)
optimized_experience.append(WorkExperience(
company=exp.company,
position=exp.position,
start_date=exp.start_date,
end_date=exp.end_date,
location=exp.location,
responsibilities=optimized_responsibilities,
achievements=optimized_achievements
))
# Optimize projects
optimized_projects = []
for project in resume_data.projects:
optimized_description = project_chain.invoke({
"name": project.name,
"description": project.description,
"technologies": project.technologies,
"job_keywords": job_keywords
})
optimized_achievements = []
for ach in project.achievements:
optimized_ach = bullet_chain.invoke({
"bullet_point": ach,
"job_keywords": job_keywords,
"point_type": "project achievement"
})
optimized_achievements.append(optimized_ach)
optimized_projects.append(Project(
name=project.name,
description=optimized_description,
technologies=project.technologies,
achievements=optimized_achievements,
url=project.url
))
# Combine all sections into final resume
return self._combine_sections(
resume_data, optimized_summary, optimized_experience, optimized_projects
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error generating resume with LangChain: {str(e)}")
def _create_summary_chain(self):
"""Create LangChain pipeline for summary optimization"""
prompt = ChatPromptTemplate.from_template("""
You are an expert resume writer. Optimize this professional summary to be more impactful and ATS-friendly.
CURRENT SUMMARY:
{current_summary}
TARGET KEYWORDS TO INCLUDE: {job_keywords}
REQUIREMENTS:
- Keep it 3-4 lines maximum
- Include relevant keywords naturally
- Focus on quantifiable achievements and years of experience
- Make it compelling and specific
- Use active voice and strong action words
Write ONLY the optimized professional summary, nothing else:
""")
return (
{
"current_summary": RunnablePassthrough(),
"job_keywords": RunnablePassthrough()
}
| prompt
| self.llm
| self.output_parser
| RunnableLambda(lambda x: x.strip())
)
def _create_bullet_chain(self):
"""Create LangChain pipeline for bullet point optimization"""
prompt = ChatPromptTemplate.from_template("""
You are an expert resume writer. Optimize this single {point_type} bullet point to be more impactful.
CURRENT BULLET POINT:
{bullet_point}
TARGET KEYWORDS: {job_keywords}
REQUIREMENTS:
- Start with a strong action verb
- Add specific metrics/numbers if possible
- Include relevant keywords naturally
- Keep it 1-2 lines maximum
- Make it quantifiable and results-focused
- Use active voice
Write ONLY the optimized bullet point, nothing else:
""")
return (
{
"bullet_point": RunnablePassthrough(),
"job_keywords": RunnablePassthrough(),
"point_type": RunnablePassthrough()
}
| prompt
| self.llm
| self.output_parser
| RunnableLambda(lambda x: x.strip().lstrip('-•*').strip())
)
def _create_project_chain(self):
"""Create LangChain pipeline for project optimization"""
prompt = ChatPromptTemplate.from_template("""
You are an expert resume writer. Optimize this project description to be more impactful and technical.
PROJECT NAME: {name}
CURRENT DESCRIPTION: {description}
TECHNOLOGIES USED: {technologies}
TARGET KEYWORDS: {job_keywords}
REQUIREMENTS:
- Keep it 2-3 lines maximum
- Include relevant technical keywords
- Focus on what the project accomplished
- Make it sound professional and impactful
- Include scale/scope if possible
Write ONLY the optimized project description, nothing else: