File size: 26,801 Bytes
a928595
db455d9
556ee06
 
8c40ab2
 
 
c1efc08
 
8c40ab2
a928595
8c40ab2
7044586
556ee06
7044586
 
 
 
8c40ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbc936b
8c40ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbc936b
8c40ab2
7044586
 
8c40ab2
c1efc08
8c40ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
556ee06
8c40ab2
 
 
 
 
 
 
 
 
 
 
c1efc08
8c40ab2
 
 
 
 
 
 
 
 
 
 
7044586
8c40ab2
7044586
 
 
 
c1efc08
556ee06
 
 
 
 
 
 
7044586
 
 
 
c1efc08
556ee06
 
 
 
 
 
 
7044586
 
 
 
c1efc08
556ee06
 
 
 
 
 
 
7044586
 
 
8c40ab2
7044586
8c40ab2
7044586
8c40ab2
 
 
 
 
 
7044586
 
8c40ab2
 
7044586
 
 
8c40ab2
7044586
8c40ab2
7044586
 
8c40ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7044586
8c40ab2
 
 
 
 
 
 
 
7044586
8c40ab2
556ee06
 
 
8c40ab2
 
 
 
 
 
 
 
 
 
 
 
556ee06
8c40ab2
 
556ee06
8c40ab2
 
 
 
 
 
556ee06
8c40ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
556ee06
8c40ab2
 
c1efc08
 
556ee06
8c40ab2
 
556ee06
 
 
8c40ab2
556ee06
 
c1efc08
 
8c40ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e84a893
8c40ab2
 
c1efc08
8c40ab2
c1efc08
8c40ab2
c1efc08
8c40ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1efc08
8c40ab2
c1efc08
8c40ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e84a893
8c40ab2
 
 
e84a893
8c40ab2
 
e84a893
8c40ab2
 
7044586
8c40ab2
 
7044586
8c40ab2
7044586
556ee06
 
 
 
 
7044586
 
 
 
 
 
 
5bae67b
7044586
 
 
 
 
 
 
556ee06
7044586
 
 
 
 
556ee06
5bae67b
 
7044586
 
8c40ab2
c1efc08
 
 
8c40ab2
7044586
 
8c40ab2
556ee06
 
 
c1efc08
 
7044586
 
8c40ab2
c1efc08
 
 
556ee06
 
8c40ab2
 
556ee06
8c40ab2
556ee06
 
 
 
8c40ab2
556ee06
 
 
c1efc08
 
556ee06
 
8c40ab2
556ee06
 
 
8c40ab2
556ee06
 
 
 
 
 
 
 
8c40ab2
 
556ee06
 
7044586
 
8c40ab2
556ee06
 
 
8c40ab2
556ee06
 
8c40ab2
556ee06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c40ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
556ee06
 
c1efc08
556ee06
 
 
c1efc08
 
 
 
 
556ee06
c1efc08
556ee06
 
c1efc08
 
 
 
556ee06
 
c1efc08
556ee06
 
8c40ab2
c1efc08
556ee06
 
 
 
c1efc08
556ee06
c1efc08
556ee06
 
 
 
8c40ab2
556ee06
 
 
 
 
 
 
 
8c40ab2
 
 
c1efc08
8c40ab2
c1efc08
556ee06
c1efc08
556ee06
 
8c40ab2
c1efc08
556ee06
7044586
 
8c40ab2
7044586
 
 
8c40ab2
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
import streamlit as st
import pdfplumber
import re
import pandas as pd
import matplotlib.pyplot as plt
import torch
from datetime import datetime
import plotly.express as px
import plotly.graph_objects as go
import numpy as np

# Display startup message
st.set_page_config(
    page_title="Resume Screener & Skill Extractor",
    page_icon="πŸ“„",
    layout="wide"
)

st.title("πŸ“„ Resume Screener & Skill Extractor")
startup_message = st.empty()
startup_message.info("Loading dependencies and models... This may take a minute on first run.")

# Import dependencies with fallbacks
try:
    import spacy
    spacy_available = True
except ImportError:
    spacy_available = False
    st.warning("spaCy is not available. Some features will be limited.")

try:
    from transformers import pipeline
    transformers_available = True
except ImportError:
    transformers_available = False
    st.warning("Transformers is not available. Summary generation will be limited.")

try:
    import nltk
    from nltk.tokenize import word_tokenize
    nltk_available = True
    
    # Download required NLTK resources
    try:
        nltk.data.find('tokenizers/punkt')
    except LookupError:
        nltk.download('punkt')
except ImportError:
    nltk_available = False
    st.warning("NLTK is not available. Some text processing features will be limited.")

# Custom sentence-transformers fallback
try:
    from sentence_transformers import SentenceTransformer
    try:
        from sentence_transformers import util as st_util
        sentence_transformers_available = True
    except ImportError:
        # Define our own utility functions
        class CustomSTUtil:
            @staticmethod
            def pytorch_cos_sim(a, b):
                if not isinstance(a, torch.Tensor):
                    a = torch.tensor(a)
                if not isinstance(b, torch.Tensor):
                    b = torch.tensor(b)
                
                if len(a.shape) == 1:
                    a = a.unsqueeze(0)
                if len(b.shape) == 1:
                    b = b.unsqueeze(0)
                
                a_norm = torch.nn.functional.normalize(a, p=2, dim=1)
                b_norm = torch.nn.functional.normalize(b, p=2, dim=1)
                return torch.mm(a_norm, b_norm.transpose(0, 1))
        
        st_util = CustomSTUtil()
        sentence_transformers_available = True
except ImportError:
    sentence_transformers_available = False
    st.warning("Sentence Transformers is not available. Semantic matching will be disabled.")

# Load models with exception handling
@st.cache_resource
def load_models():
    models = {}
    
    # Load spaCy if available
    if spacy_available:
        try:
            models['nlp'] = spacy.load("en_core_web_sm")
        except OSError:
            try:
                import subprocess
                import sys
                subprocess.check_call([sys.executable, "-m", "spacy", "download", "en_core_web_sm"])
                models['nlp'] = spacy.load("en_core_web_sm")
            except Exception as e:
                st.warning(f"Could not load spaCy model: {e}")
                models['nlp'] = None
    else:
        models['nlp'] = None
    
    # Load summarizer if transformers available
    if transformers_available:
        try:
            models['summarizer'] = pipeline("summarization", model="facebook/bart-large-cnn")
        except Exception as e:
            st.warning(f"Could not load summarizer model: {e}")
            # Simple fallback summarizer
            models['summarizer'] = lambda text, **kwargs: [{"summary_text": ". ".join(text.split(". ")[:5]) + "."}]
    else:
        # Simple fallback summarizer
        models['summarizer'] = lambda text, **kwargs: [{"summary_text": ". ".join(text.split(". ")[:5]) + "."}]
    
    # Load sentence transformer if available
    if sentence_transformers_available:
        try:
            models['sentence_model'] = SentenceTransformer('paraphrase-MiniLM-L6-v2')
        except Exception as e:
            st.warning(f"Could not load sentence transformer model: {e}")
            models['sentence_model'] = None
    else:
        models['sentence_model'] = None
    
    return models

# Job descriptions dictionary
job_descriptions = {
    "Software Engineer": {
        "skills": ["python", "java", "javascript", "sql", "algorithms", "data structures", 
                  "git", "cloud", "web development", "software development", "coding"],
        "description": "Looking for software engineers with strong programming skills and experience in software development.",
        "must_have": ["python", "git", "algorithms"],
        "nice_to_have": ["cloud", "java", "javascript"],
        "seniority_levels": {
            "Junior": "0-2 years of experience, familiar with basic programming concepts",
            "Mid-level": "3-5 years of experience, proficient in multiple languages, experience with system design",
            "Senior": "6+ years of experience, expert in software architecture, mentoring, and leading projects"
        }
    },
    "Interaction Designer": {
        "skills": ["ui", "ux", "user research", "wireframing", "prototyping", "figma", 
                  "sketch", "adobe", "design thinking", "interaction design"],
        "description": "Seeking interaction designers with expertise in user experience and interface design.",
        "must_have": ["ui", "ux", "prototyping"],
        "nice_to_have": ["figma", "sketch", "user research"],
        "seniority_levels": {
            "Junior": "0-2 years of experience, basic design skills, understanding of UX principles",
            "Mid-level": "3-5 years of experience, strong portfolio, experience with user research",
            "Senior": "6+ years of experience, leadership in design systems, driving design strategy"
        }
    },
    "Data Scientist": {
        "skills": ["python", "r", "statistics", "machine learning", "data analysis", 
                  "sql", "tensorflow", "pytorch", "pandas", "numpy"],
        "description": "Looking for data scientists with strong analytical and machine learning skills.",
        "must_have": ["python", "statistics", "machine learning"],
        "nice_to_have": ["tensorflow", "pytorch", "r"],
        "seniority_levels": {
            "Junior": "0-2 years of experience, basic knowledge of statistics and ML algorithms",
            "Mid-level": "3-5 years of experience, model development, feature engineering",
            "Senior": "6+ years of experience, advanced ML techniques, research experience"
        }
    }
}

# Core functionality
def extract_text_from_pdf(pdf_file):
    """Extract text from PDF file."""
    text = ""
    try:
        with pdfplumber.open(pdf_file) as pdf:
            for page in pdf.pages:
                text += page.extract_text() or ""
    except Exception as e:
        st.error(f"Error extracting text from PDF: {e}")
    return text

def extract_skills(text, job_title, nlp=None):
    """Extract skills from resume text."""
    found_skills = []
    required_skills = job_descriptions[job_title]["skills"]
    
    # Simple keyword matching (no NLP needed)
    for skill in required_skills:
        if skill.lower() in text.lower():
            found_skills.append(skill)
    
    return found_skills

def extract_experience(text):
    """Extract work experience from resume text."""
    experiences = []
    
    # Define regex pattern for experiences
    experience_pattern = r"(?i)(\w+[\w\s&,.']+)\s*(?:[-|β€’]|\bat\b)\s*([A-Za-z][\w\s&,.']+)\s*(?:[-|β€’]|\bfrom\b)\s*(\d{4}(?:\s*[-–]\s*(?:\d{4}|present|current)))"
    
    matches = re.finditer(experience_pattern, text)
    for match in matches:
        company = match.group(1).strip()
        role = match.group(2).strip()
        duration = match.group(3).strip()
        
        # Process dates
        try:
            date_parts = re.split(r'[-–]', duration)
            start_year = int(date_parts[0].strip())
            
            if len(date_parts) > 1 and 'present' not in date_parts[1].lower() and 'current' not in date_parts[1].lower():
                end_year = int(date_parts[1].strip())
                end_date = datetime(end_year, 12, 31)
            else:
                end_year = datetime.now().year
                end_date = datetime.now()
                
            start_date = datetime(start_year, 1, 1)
            duration_months = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)
            
            experiences.append({
                'company': company,
                'role': role,
                'start_date': start_date,
                'end_date': end_date,
                'duration_months': duration_months
            })
        except:
            experiences.append({
                'company': company,
                'role': role,
                'duration': duration
            })
    
    return experiences

def analyze_resume(text, job_title, models):
    """Analyze resume text."""
    # Extract skills
    found_skills = extract_skills(text, job_title, models.get('nlp'))
    
    # Generate summary
    if models.get('summarizer'):
        try:
            summary = models['summarizer'](text[:3000], max_length=150, min_length=50, do_sample=False)[0]["summary_text"]
        except Exception as e:
            st.warning(f"Error generating summary: {e}")
            summary = text[:500] + "..."
    else:
        summary = text[:500] + "..."
    
    # Extract work experience
    experiences = extract_experience(text)
    
    # Calculate semantic match score
    match_score = 0
    if models.get('sentence_model') and sentence_transformers_available:
        try:
            resume_embedding = models['sentence_model'].encode(text[:5000], convert_to_tensor=True)
            job_embedding = models['sentence_model'].encode(job_descriptions[job_title]["description"], convert_to_tensor=True)
            
            match_score = float(st_util.pytorch_cos_sim(resume_embedding, job_embedding)[0][0]) * 100
        except Exception as e:
            st.warning(f"Error calculating semantic match: {e}")
    else:
        # Fallback to keyword-based score
        match_score = (len(found_skills) / len(job_descriptions[job_title]["skills"])) * 100
    
    # Calculate seniority level
    years_exp = sum(exp.get('duration_months', 0) for exp in experiences if 'duration_months' in exp) / 12
    
    if years_exp < 3:
        seniority = "Junior"
    elif years_exp < 6:
        seniority = "Mid-level"
    else:
        seniority = "Senior"
    
    # Detect skill levels
    skill_levels = {}
    for skill in found_skills:
        # Default level
        skill_levels[skill] = "intermediate"
        
        # Look for advanced indicators
        advanced_patterns = [
            f"expert in {skill}", 
            f"advanced {skill}",
            f"extensive experience with {skill}"
        ]
        if any(pattern in text.lower() for pattern in advanced_patterns):
            skill_levels[skill] = "advanced"
            
        # Look for basic indicators
        basic_patterns = [
            f"familiar with {skill}",
            f"basic knowledge of {skill}",
            f"introduced to {skill}"
        ]
        if any(pattern in text.lower() for pattern in basic_patterns):
            skill_levels[skill] = "basic"
    
    # Check for inconsistencies in timeline
    inconsistencies = []
    if len(experiences) >= 2:
        # Sort experiences by start date
        sorted_exps = sorted(
            [exp for exp in experiences if 'start_date' in exp], 
            key=lambda x: x['start_date']
        )
        
        # Check for overlaps
        for i in range(len(sorted_exps) - 1):
            current = sorted_exps[i]
            next_exp = sorted_exps[i+1]
            
            if current['end_date'] > next_exp['start_date']:
                inconsistencies.append({
                    'type': 'overlap',
                    'description': f"Overlapping roles at {current['company']} and {next_exp['company']}"
                })
    
    # Generate a simple career prediction
    career_prediction = predict_career_path(seniority, job_title)
    
    return {
        'found_skills': found_skills,
        'skill_levels': skill_levels,
        'summary': summary,
        'experiences': experiences,
        'match_score': match_score,
        'seniority': seniority,
        'years_experience': years_exp,
        'inconsistencies': inconsistencies,
        'career_prediction': career_prediction
    }

def predict_career_path(seniority, job_title):
    """Generate a simple career prediction."""
    if seniority == "Junior":
        return f"Next potential role: Senior {job_title}"
    elif seniority == "Mid-level":
        roles = {
            "Software Engineer": "Team Lead, Technical Lead, or Engineering Manager",
            "Data Scientist": "Senior Data Scientist or Data Science Lead",
            "Interaction Designer": "Senior Designer or UX Lead"
        }
        return f"Next potential roles: {roles.get(job_title, f'Senior {job_title}')}"
    else: # Senior
        roles = {
            "Software Engineer": "Engineering Manager, Software Architect, or CTO",
            "Data Scientist": "Head of Data Science, ML Engineering Manager, or Chief Data Officer",
            "Interaction Designer": "Design Director, Head of UX, or VP of Design"
        }
        return f"Next potential roles: {roles.get(job_title, f'Director of {job_title}')}"

def generate_career_advice(resume_text, job_title, found_skills, missing_skills):
    """Generate career advice based on resume analysis."""
    advice = f"""## Career Development Plan for {job_title}

### Skills to Develop

The following skills would strengthen your profile for this position:

"""
    
    for skill in missing_skills:
        advice += f"- **{skill.title()}**: "
        
        if skill == "python":
            advice += "Take online courses like Coursera's Python for Everybody or follow tutorials on Real Python."
        elif skill == "java":
            advice += "Complete the Oracle Java Certification or contribute to open-source Java projects."
        elif skill == "javascript":
            advice += "Build interactive web applications using modern frameworks like React or Vue."
        elif skill == "cloud":
            advice += "Get hands-on experience with AWS, Azure, or GCP through their free tier offerings."
        elif "algorithm" in skill or "data structure" in skill:
            advice += "Practice on platforms like LeetCode or HackerRank and study algorithm design principles."
        elif "ui" in skill or "ux" in skill:
            advice += "Create a portfolio of design work and study interaction design principles."
        elif "machine learning" in skill:
            advice += "Take Andrew Ng's Machine Learning course on Coursera and work on ML projects with real datasets."
        else:
            advice += f"Research and practice this skill through online courses, tutorials, and hands-on projects."
        
        advice += "\n\n"
    
    advice += f"""
### Project Ideas

Consider these projects to showcase your skills for a {job_title} position:

"""
    
    if job_title == "Software Engineer":
        advice += """
1. **Full-Stack Web Application**: Build a complete web app with frontend, backend, and database
2. **API Service**: Create a RESTful or GraphQL API with proper authentication and documentation
3. **Open Source Contribution**: Contribute to relevant open-source projects in your area of interest
"""
    elif job_title == "Data Scientist":
        advice += """
1. **Predictive Model**: Build and deploy a machine learning model that solves a real-world problem
2. **Data Dashboard**: Create an interactive visualization dashboard for complex datasets
3. **Natural Language Processing**: Develop a text classification or sentiment analysis project
"""
    elif job_title == "Interaction Designer":
        advice += """
1. **Design System**: Create a comprehensive design system with components and usage guidelines
2. **UX Case Study**: Document your design process for a real or fictional product improvement
3. **Interactive Prototype**: Design a fully functional prototype that demonstrates your interaction design skills
"""
    
    advice += """
### Learning Resources

- **Online Platforms**: Coursera, Udemy, Pluralsight, LinkedIn Learning
- **Practice Sites**: GitHub, HackerRank, LeetCode, Kaggle
- **Communities**: Stack Overflow, Reddit programming communities, relevant Discord servers
"""
    
    return advice

# Load models
models = load_models()

# Clear startup message
startup_message.empty()

# App description
st.markdown("""
This app helps recruiters analyze resumes by:
- Extracting relevant skills for specific job positions
- Generating a concise summary of the candidate's background
- Identifying skill gaps for the selected role
- Providing personalized career advice and project recommendations
""")

# Create two columns
col1, col2 = st.columns([2, 1])

with col1:
    # File upload
    uploaded_file = st.file_uploader("Upload Resume (PDF)", type=["pdf"])

with col2:
    # Job selection
    job_title = st.selectbox("Select Job Position", list(job_descriptions.keys()))
    
    # Show job description
    if job_title:
        st.info(f"**Required Skills:**\n" + 
                "\n".join([f"- {skill.title()}" for skill in job_descriptions[job_title]["skills"]]))

if uploaded_file and job_title:
    try:
        # Show spinner while processing
        with st.spinner("Analyzing resume..."):
            # Extract text from PDF
            text = extract_text_from_pdf(uploaded_file)
            
            # Analyze resume
            analysis_results = analyze_resume(text, job_title, models)
            
            # Calculate missing skills
            missing_skills = [skill for skill in job_descriptions[job_title]["skills"] 
                             if skill not in analysis_results['found_skills']]
        
        # Display results in tabs
        tab1, tab2, tab3, tab4 = st.tabs([
            "πŸ“Š Skills Match", 
            "πŸ“ Resume Summary", 
            "🎯 Skills Gap", 
            "πŸš€ Career Advice"
        ])
        
        with tab1:
            # Create two columns
            col1, col2 = st.columns(2)
            
            with col1:
                # Display matched skills
                st.subheader("🎯 Matched Skills")
                if analysis_results['found_skills']:
                    for skill in analysis_results['found_skills']:
                        # Show skill with proficiency level
                        level = analysis_results['skill_levels'].get(skill, 'intermediate')
                        level_emoji = "🟒" if level == 'advanced' else "🟑" if level == 'intermediate' else "🟠"
                        st.success(f"{level_emoji} {skill.title()} ({level.title()})")
                    
                    # Calculate match percentage
                    match_percentage = len(analysis_results['found_skills']) / len(job_descriptions[job_title]["skills"]) * 100
                    st.metric("Skills Match", f"{match_percentage:.1f}%")
                else:
                    st.warning("No direct skill matches found.")
            
            with col2:
                # Display semantic match score
                st.subheader("πŸ’‘ Semantic Match")
                st.metric("Overall Match Score", f"{analysis_results['match_score']:.1f}%")
                
                # Display must-have skills match
                must_have_skills = job_descriptions[job_title]["must_have"]
                must_have_count = sum(1 for skill in must_have_skills if skill in analysis_results['found_skills'])
                must_have_percentage = (must_have_count / len(must_have_skills)) * 100
                
                st.write("Must-have skills:")
                st.progress(must_have_percentage / 100)
                st.write(f"{must_have_count} out of {len(must_have_skills)} ({must_have_percentage:.1f}%)")
                
                # Professional level assessment
                st.subheader("🧠 Seniority Assessment")
                st.info(f"**{analysis_results['seniority']}** ({analysis_results['years_experience']:.1f} years equivalent experience)")
                st.write(job_descriptions[job_title]["seniority_levels"][analysis_results['seniority']])
        
        with tab2:
            # Display resume summary
            st.subheader("πŸ“ Resume Summary")
            st.write(analysis_results['summary'])
            
            # Display experience timeline
            st.subheader("⏳ Experience Timeline")
            if analysis_results['experiences']:
                # Convert experiences to dataframe for display
                exp_data = []
                for exp in analysis_results['experiences']:
                    if 'start_date' in exp and 'end_date' in exp:
                        exp_data.append({
                            'Company': exp['company'],
                            'Role': exp['role'],
                            'Start Date': exp['start_date'].strftime('%b %Y') if exp['start_date'] else 'Unknown',
                            'End Date': exp['end_date'].strftime('%b %Y') if exp['end_date'] != datetime.now() else 'Present',
                            'Duration (months)': exp.get('duration_months', 'Unknown')
                        })
                    else:
                        exp_data.append({
                            'Company': exp['company'],
                            'Role': exp['role'],
                            'Duration': exp.get('duration', 'Unknown')
                        })
                
                if exp_data:
                    exp_df = pd.DataFrame(exp_data)
                    st.dataframe(exp_df)
                    
                    # Create a timeline visualization if dates are available
                    timeline_data = [exp for exp in analysis_results['experiences'] if 'start_date' in exp and 'end_date' in exp]
                    if timeline_data and len(timeline_data) > 0:
                        try:
                            # Sort by start date
                            timeline_data = sorted(timeline_data, key=lambda x: x['start_date'])
                            
                            # Create figure
                            fig = go.Figure()
                            
                            for i, exp in enumerate(timeline_data):
                                fig.add_trace(go.Bar(
                                    x=[(exp['end_date'] - exp['start_date']).days / 30],  # Duration in months
                                    y=[exp['company']],
                                    orientation='h',
                                    name=exp['role'],
                                    hovertext=f"{exp['role']} at {exp['company']}",
                                    marker=dict(color=px.colors.qualitative.Plotly[i % len(px.colors.qualitative.Plotly)])
                                ))
                            
                            fig.update_layout(
                                title="Career Timeline",
                                xaxis_title="Duration (months)",
                                yaxis_title="Company",
                                height=400,
                                margin=dict(l=0, r=0, b=0, t=30)
                            )
                            
                            st.plotly_chart(fig, use_container_width=True)
                        except Exception as e:
                            st.warning(f"Could not create timeline visualization: {e}")
            else:
                st.warning("No work experience data could be extracted.")
        
        with tab3:
            # Display missing skills
            st.subheader("πŸ“Œ Skills to Develop")
            
            # Create two columns
            col1, col2 = st.columns(2)
            
            with col1:
                # Missing skills
                if missing_skills:
                    for skill in missing_skills:
                        st.warning(f"βž– {skill.title()}")
                else:
                    st.success("Great! The candidate has all the required skills!")
            
            with col2:
                # Skills gap analysis
                st.subheader("πŸ” Gap Analysis")
                
                # Show must-have skills that are missing
                missing_must_have = [skill for skill in job_descriptions[job_title]["must_have"] 
                                   if skill not in analysis_results['found_skills']]
                
                if missing_must_have:
                    st.error("**Critical Skills Missing:**")
                    for skill in missing_must_have:
                        st.write(f"- {skill.title()}")
                    
                    st.markdown("These are must-have skills for this position.")
                else:
                    st.success("Candidate has all the must-have skills for this position!")
                
                # Show nice-to-have skills gap
                missing_nice_to_have = [skill for skill in job_descriptions[job_title]["nice_to_have"]
                                      if skill not in analysis_results['found_skills']]
                
                if missing_nice_to_have:
                    st.warning("**Nice-to-Have Skills Missing:**")
                    for skill in missing_nice_to_have:
                        st.write(f"- {skill.title()}")
                else:
                    st.success("Candidate has all the nice-to-have skills!")
                    
            # Display career trajectory
            st.subheader("πŸ‘¨β€πŸ’Ό Career Trajectory")
            st.info(analysis_results['career_prediction'])
        
        with tab4:
            # Display career advice
            st.subheader("πŸš€ Career Advice and Project Recommendations")
            
            if st.button("Generate Career Advice"):
                with st.spinner("Generating personalized career advice..."):
                    advice = generate_career_advice(text, job_title, analysis_results['found_skills'], missing_skills)
                    st.markdown(advice)
    
    except Exception as e:
        st.error(f"An error occurred while processing the resume: {str(e)}")
        st.exception(e)

# Add footer
st.markdown("---")
st.markdown("Made with ❀️ using Streamlit and Hugging Face")