ak0601 commited on
Commit
59a0fd9
Β·
verified Β·
1 Parent(s): a72bcde

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +685 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,687 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import json
3
+ from langchain_core.prompts import ChatPromptTemplate
4
+ from pydantic import BaseModel, Field
5
+ from langchain_openai import ChatOpenAI
6
+ from langchain_community.document_loaders import WebBaseLoader
7
+ import pdfplumber
8
+ import PyPDF2
9
+ import fitz # PyMuPDF
10
+ from PIL import Image
11
+ import easyocr
12
+ import os
13
+ import tempfile
14
+ import re
15
+ import io
16
 
17
+ # Fix for Windows OpenMP conflict
18
+ os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
19
+
20
+ # Set USER_AGENT to avoid warnings
21
+ os.environ["USER_AGENT"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
22
+
23
+ # Set page configuration
24
+ st.set_page_config(
25
+ page_title="ATS_Assassin",
26
+ page_icon="πŸ“„",
27
+ layout="wide",
28
+ initial_sidebar_state="expanded"
29
+ )
30
+
31
+ # Custom CSS for better styling
32
+ st.markdown("""
33
+ <style>
34
+ .main {
35
+ padding: 0rem 1rem;
36
+ }
37
+ .stAlert {
38
+ margin-top: 1rem;
39
+ }
40
+
41
+ /* Enhanced score card styling */
42
+ .score-card {
43
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
44
+ padding: 2rem;
45
+ border-radius: 20px;
46
+ text-align: center;
47
+ margin: 0.5rem;
48
+ box-shadow: 0 10px 20px rgba(0,0,0,0.1);
49
+ transition: transform 0.3s ease, box-shadow 0.3s ease;
50
+ position: relative;
51
+ overflow: hidden;
52
+ }
53
+
54
+ .score-card:hover {
55
+ transform: translateY(-5px);
56
+ box-shadow: 0 15px 30px rgba(0,0,0,0.2);
57
+ }
58
+
59
+ .score-card::before {
60
+ content: "";
61
+ position: absolute;
62
+ top: -50%;
63
+ left: -50%;
64
+ width: 200%;
65
+ height: 200%;
66
+ background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
67
+ animation: shimmer 3s infinite;
68
+ }
69
+
70
+ @keyframes shimmer {
71
+ 0% { transform: rotate(0deg); }
72
+ 100% { transform: rotate(360deg); }
73
+ }
74
+
75
+ .score-card-initial {
76
+ background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
77
+ }
78
+
79
+ .score-card-improved {
80
+ background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
81
+ }
82
+
83
+ .score-card-improvement {
84
+ background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
85
+ }
86
+
87
+ .score-label {
88
+ color: white;
89
+ font-size: 0.9rem;
90
+ font-weight: 500;
91
+ margin-bottom: 0.5rem;
92
+ opacity: 0.9;
93
+ }
94
+
95
+ .score-value {
96
+ color: white;
97
+ font-size: 2.5rem;
98
+ font-weight: bold;
99
+ margin-bottom: 0.5rem;
100
+ text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
101
+ }
102
+
103
+ .score-delta {
104
+ color: white;
105
+ font-size: 1.2rem;
106
+ font-weight: 600;
107
+ display: flex;
108
+ align-items: center;
109
+ justify-content: center;
110
+ gap: 0.3rem;
111
+ }
112
+
113
+ .arrow-up {
114
+ width: 0;
115
+ height: 0;
116
+ border-left: 8px solid transparent;
117
+ border-right: 8px solid transparent;
118
+ border-bottom: 12px solid #4ade80;
119
+ display: inline-block;
120
+ animation: bounce 2s infinite;
121
+ }
122
+
123
+ @keyframes bounce {
124
+ 0%, 100% { transform: translateY(0); }
125
+ 50% { transform: translateY(-5px); }
126
+ }
127
+
128
+ /* Progress ring for scores */
129
+ .progress-ring {
130
+ position: relative;
131
+ width: 120px;
132
+ height: 120px;
133
+ margin: 0 auto 1rem auto;
134
+ }
135
+
136
+ .progress-ring-circle {
137
+ stroke: rgba(255,255,255,0.3);
138
+ fill: transparent;
139
+ stroke-width: 8;
140
+ }
141
+
142
+ .progress-ring-circle-progress {
143
+ stroke: white;
144
+ fill: transparent;
145
+ stroke-width: 8;
146
+ stroke-linecap: round;
147
+ transform: rotate(-90deg);
148
+ transform-origin: 50% 50%;
149
+ transition: stroke-dashoffset 1s ease-in-out;
150
+ }
151
+
152
+ .section-header {
153
+ background-color: #e9ecef;
154
+ padding: 0.5rem 1rem;
155
+ border-radius: 5px;
156
+ margin: 0.5rem 0;
157
+ cursor: pointer;
158
+ }
159
+
160
+ .section-content {
161
+ padding: 1rem;
162
+ background-color: #ffffff;
163
+ border: 1px solid #dee2e6;
164
+ border-radius: 5px;
165
+ margin-bottom: 1rem;
166
+ }
167
+
168
+ /* Animated gradient background for results header */
169
+ .results-header {
170
+ background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
171
+ background-size: 400% 400%;
172
+ animation: gradient 15s ease infinite;
173
+ color: white;
174
+ padding: 2rem;
175
+ border-radius: 15px;
176
+ text-align: center;
177
+ margin-bottom: 2rem;
178
+ box-shadow: 0 5px 15px rgba(0,0,0,0.2);
179
+ }
180
+
181
+ @keyframes gradient {
182
+ 0% { background-position: 0% 50%; }
183
+ 50% { background-position: 100% 50%; }
184
+ 100% { background-position: 0% 50%; }
185
+ }
186
+
187
+ .results-header h1 {
188
+ margin: 0;
189
+ font-size: 2.5rem;
190
+ text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
191
+ }
192
+
193
+ /* Metric styles for native Streamlit metrics */
194
+ [data-testid="metric-container"] {
195
+ background: transparent;
196
+ padding: 0;
197
+ }
198
+
199
+ [data-testid="metric-container"] > div {
200
+ background: transparent;
201
+ }
202
+
203
+ [data-testid="metric-container"] label {
204
+ color: white !important;
205
+ font-weight: 500;
206
+ opacity: 0.9;
207
+ }
208
+
209
+ [data-testid="metric-container"] [data-testid="metric-value"] {
210
+ color: white !important;
211
+ font-size: 2.2rem;
212
+ font-weight: bold;
213
+ }
214
+
215
+ [data-testid="metric-container"] [data-testid="metric-delta"] {
216
+ color: white !important;
217
+ font-size: 1.1rem;
218
+ }
219
+ </style>
220
+ """, unsafe_allow_html=True)
221
+
222
+ # Define Pydantic models
223
+ class ResumeSection(BaseModel):
224
+ """Information about a section in a resume."""
225
+ section_name: str = Field(description="The name of the resume section (e.g., 'Experience', 'Education', 'Skills').")
226
+ content: str = Field(description="The full text content of this section.")
227
+
228
+ class ResumeAnalysis(BaseModel):
229
+ """Analysis of a resume based on a job description."""
230
+ resume_sections: list[ResumeSection] = Field(description="A list of identified sections and their content from the resume.")
231
+ initial_match_score: int = Field(description="An initial match score out of 100, indicating how well the resume matches the job description.")
232
+ score_issues: str = Field(description="A detailed summary of the main reasons why the initial score is not 100, specifically identifying key requirements from the job description that are missing or not clearly highlighted in the resume.")
233
+ suggested_resume_updates: str = Field(description="Specific, actionable suggestions for how to modify the resume content to better match the job description. Focus on adding relevant keywords and rephrasing existing content to align with job requirements.")
234
+ updated_resume_content_suggestion: list[ResumeSection] = Field(description="A suggested revised version of the resume content, presented as a list of sections with potentially modified content based on the job description. These modifications should be realistic and significantly improve the match score.")
235
+
236
+ # Initialize session state
237
+ if 'analysis_complete' not in st.session_state:
238
+ st.session_state.analysis_complete = False
239
+ if 'analysis_result' not in st.session_state:
240
+ st.session_state.analysis_result = None
241
+ if 'ocr_reader' not in st.session_state:
242
+ st.session_state.ocr_reader = None
243
+
244
+ # Helper functions
245
+ @st.cache_resource
246
+ def get_ocr_reader():
247
+ """Initialize OCR reader once and cache it"""
248
+ try:
249
+ return easyocr.Reader(['en'], gpu=False) # Disable GPU for Windows compatibility
250
+ except Exception as e:
251
+ st.warning(f"OCR initialization warning: {e}")
252
+ return None
253
+
254
+ def extract_text_from_pdf(pdf_path):
255
+ """Extracts text from a PDF using multiple methods without requiring poppler."""
256
+
257
+ # Method 1: Try pdfplumber first
258
+ try:
259
+ with pdfplumber.open(pdf_path) as pdf:
260
+ if pdf.pages:
261
+ all_text = ""
262
+ for page in pdf.pages:
263
+ page_text = page.extract_text()
264
+ if page_text:
265
+ all_text += page_text + "\n"
266
+
267
+ if all_text.strip():
268
+ return all_text.strip()
269
+ else:
270
+ st.info("pdfplumber did not extract text. Trying PyPDF2...")
271
+ except Exception as e:
272
+ st.warning(f"pdfplumber failed: {e}. Trying PyPDF2...")
273
+
274
+ # Method 2: Try PyPDF2
275
+ try:
276
+ with open(pdf_path, 'rb') as file:
277
+ pdf_reader = PyPDF2.PdfReader(file)
278
+ all_text = ""
279
+
280
+ for page_num in range(len(pdf_reader.pages)):
281
+ page = pdf_reader.pages[page_num]
282
+ text = page.extract_text()
283
+ if text:
284
+ all_text += text + "\n"
285
+
286
+ if all_text.strip():
287
+ return all_text.strip()
288
+ else:
289
+ st.info("PyPDF2 did not extract text. Trying PyMuPDF with OCR...")
290
+ except Exception as e:
291
+ st.warning(f"PyPDF2 failed: {e}. Trying PyMuPDF with OCR...")
292
+
293
+ # Method 3: Use PyMuPDF (fitz) to convert PDF to images for OCR
294
+ try:
295
+ # Open the PDF with PyMuPDF
296
+ pdf_document = fitz.open(pdf_path)
297
+
298
+ if len(pdf_document) == 0:
299
+ return "The PDF file is empty or has no pages."
300
+
301
+ # Get the first page
302
+ page = pdf_document[0]
303
+
304
+ # Convert page to image
305
+ mat = fitz.Matrix(2, 2) # Increase resolution
306
+ pix = page.get_pixmap(matrix=mat)
307
+ img_data = pix.tobytes("png")
308
+
309
+ # Convert to PIL Image
310
+ image = Image.open(io.BytesIO(img_data))
311
+
312
+ # Save the image temporarily for OCR
313
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as tmp_img:
314
+ image_path = tmp_img.name
315
+ image.save(image_path, 'PNG')
316
+
317
+ # Get or initialize OCR reader
318
+ reader = get_ocr_reader()
319
+ if reader is None:
320
+ return "OCR reader could not be initialized."
321
+
322
+ # Read text from the image
323
+ result = reader.readtext(image_path)
324
+
325
+ # Extract text
326
+ extracted_text = ""
327
+ for (bbox, text, prob) in result:
328
+ extracted_text += text + " "
329
+
330
+ # Clean up
331
+ pdf_document.close()
332
+ try:
333
+ os.unlink(image_path)
334
+ except:
335
+ pass
336
+
337
+ if extracted_text.strip():
338
+ return extracted_text.strip()
339
+ else:
340
+ return "Could not extract text from the PDF using any method."
341
+
342
+ except Exception as e:
343
+ return f"All text extraction methods failed: {e}"
344
+
345
+ def analyze_and_update_resume(resume_text: str, job_description_text: str):
346
+ """Analyze resume against job description and provide suggestions."""
347
+ try:
348
+ # Initialize LLM
349
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
350
+
351
+ # Create prompt template
352
+ prompt = ChatPromptTemplate.from_messages([
353
+ ("system", """You are an expert ATS scorer and resume optimization assistant.
354
+ Your primary goal is to provide actionable and realistic suggestions to *significantly improve* a resume's match score against a given job description.
355
+ Your task is to analyze a resume against a job description with high accuracy, simulating an advanced ATS system.
356
+ First, meticulously identify ALL key sections and their content from the provided resume text.
357
+ Then, perform a detailed assessment of how well the resume's content, skills, and experience align with the requirements and preferences outlined in the job description. Provide an initial match score out of 100, explaining your reasoning based on specific keywords, skills, and experiences mentioned in both the resume and job description.
358
+ Clearly articulate the specific gaps or areas where the resume significantly deviates from or fails to address key aspects of the job description. These should be concrete points directly tied to the job requirements.
359
+ Based on this analysis, provide specific and impactful suggestions for modifying the resume content. **These suggestions must be designed to strategically increase the resume's ATS score against the job description by directly addressing the identified gaps and highlighting relevant experience.** Focus on:
360
+ 1. Incorporating relevant keywords and phrases from the job description where applicable and where supported by the candidate's experience.
361
+ 2. Rephrasing existing bullet points or descriptions to *strongly* highlight experiences that are directly relevant to the job requirements and use action verbs that match the job description's tone.
362
+ 3. Adding missing information if it's implied by the existing content but not explicitly stated (e.g., mentioning specific tools, methodologies, or quantifiable results used) that are mentioned in the job description.
363
+ 4. **Ensure the suggested modifications realistically improve the alignment and are not fabricated.**
364
+ Finally, present the suggested revised version of the resume content. This should be a realistic and optimized version of the original resume, incorporating the suggested changes within the original section structure. Do NOT invent experience or skills that are not at least partially supported by the original resume content; focus on strategically highlighting and re-framing existing information to better match the job description and improve the score.
365
+ Ensure the output is strictly in the specified JSON format. The 'updated_resume_content_suggestion' field should contain the full text of the suggested updated resume sections."""),
366
+ ("human", """Resume Text:
367
+ {resume_text}
368
+
369
+ Job Description Text:
370
+ {job_description_text}"""),
371
+ ])
372
+
373
+ structured_llm = llm.with_structured_output(ResumeAnalysis)
374
+ analysis_chain = prompt | structured_llm
375
+
376
+ # Perform initial analysis
377
+ with st.spinner("Analyzing resume..."):
378
+ initial_analysis = analysis_chain.invoke({
379
+ "resume_text": resume_text,
380
+ "job_description_text": job_description_text
381
+ })
382
+
383
+ # Prepare updated resume text
384
+ suggested_updated_resume_text_sections = ""
385
+ for section in initial_analysis.updated_resume_content_suggestion:
386
+ suggested_updated_resume_text_sections += f"{section.section_name}:\n{section.content}\n\n"
387
+
388
+ # Score the updated resume
389
+ with st.spinner("Calculating improved score..."):
390
+ scoring_prompt = ChatPromptTemplate.from_messages([
391
+ ("system", """You are an expert resume and job description matcher.
392
+ Your task is to assess how well the provided resume text matches the job description and provide a single integer score out of 100 based on ATS scoring principles. Focus on the alignment of skills, experience, and keywords. Provide only the integer score."""),
393
+ ("human", """Assess the match score between the following resume text and job description.
394
+ Provide only a single integer score out of 100.
395
+
396
+ Resume Text:
397
+ {resume_text}
398
+
399
+ Job Description Text:
400
+ {job_description_text}"""),
401
+ ])
402
+
403
+ scoring_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
404
+ scoring_chain = scoring_prompt | scoring_llm
405
+
406
+ updated_score_response = scoring_chain.invoke({
407
+ "resume_text": suggested_updated_resume_text_sections.strip(),
408
+ "job_description_text": job_description_text
409
+ })
410
+
411
+ # Parse score
412
+ try:
413
+ updated_score_text = updated_score_response.content.strip()
414
+ match = re.search(r'\d+', updated_score_text)
415
+ if match:
416
+ updated_score = int(match.group(0))
417
+ updated_score = max(0, min(100, updated_score))
418
+ else:
419
+ updated_score = -1
420
+ except:
421
+ updated_score = -1
422
+
423
+ # Prepare result - using model_dump() instead of dict() for Pydantic v2
424
+ result = {
425
+ "initial_analysis": initial_analysis.model_dump(),
426
+ "initial_score": initial_analysis.initial_match_score,
427
+ "suggested_resume_updates_description": initial_analysis.suggested_resume_updates,
428
+ "suggested_updated_resume_content_json": [sec.model_dump() for sec in initial_analysis.updated_resume_content_suggestion],
429
+ "updated_score": updated_score,
430
+ "score_comparison": f"Initial score: {initial_analysis.initial_match_score}, Updated score: {updated_score}"
431
+ }
432
+
433
+ return result
434
+
435
+ except Exception as e:
436
+ st.error(f"An error occurred during analysis: {e}")
437
+ return {"error": str(e)}
438
+
439
+ # Main app
440
+ st.title("🎯 ATS Assassin - Stealth Mode")
441
+ st.markdown("Upload your resume and job description to get AI-powered suggestions for improvement to enhance the ATS score.")
442
+
443
+ # Installation instructions
444
+ with st.expander("πŸ“¦ Required Dependencies", expanded=False):
445
+ st.markdown("""
446
+ **Install the following packages:**
447
+ ```bash
448
+ pip install streamlit langchain-core langchain-openai langchain-community
449
+ pip install pydantic pdfplumber PyPDF2 pymupdf pillow easyocr
450
+ ```
451
+
452
+ **Note:** This version doesn't require poppler! We use PyMuPDF (fitz) instead of pdf2image.
453
+ """)
454
+
455
+ # Sidebar for configuration
456
+ with st.sidebar:
457
+ st.header("βš™οΈ Configuration")
458
+
459
+ # OpenAI API Key
460
+ api_key = st.text_input("OpenAI API Key", type="password", help="Enter your OpenAI API key")
461
+ if api_key:
462
+ os.environ["OPENAI_API_KEY"] = api_key
463
+
464
+ st.divider()
465
+
466
+ # Job Description Input Method
467
+ st.subheader("πŸ“‹ Job Description Input")
468
+ input_method = st.radio(
469
+ "Choose input method:",
470
+ ["Upload PDF", "Enter URL"],
471
+ help="Select how you want to provide the job description"
472
+ )
473
+
474
+ # Main content area
475
+ col1, col2 = st.columns([1, 1])
476
+
477
+ with col1:
478
+ st.subheader("πŸ“„ Upload Resume")
479
+ resume_file = st.file_uploader("Choose your resume PDF", type=['pdf'])
480
+
481
+ if resume_file:
482
+ st.success(f"βœ… Resume uploaded: {resume_file.name}")
483
+
484
+ with col2:
485
+ st.subheader("πŸ’Ό Job Description")
486
+
487
+ job_description_text = None
488
+
489
+ if input_method == "Upload PDF":
490
+ job_file = st.file_uploader("Choose job description PDF", type=['pdf'])
491
+ if job_file:
492
+ st.success(f"βœ… Job description uploaded: {job_file.name}")
493
+ else:
494
+ job_url = st.text_input("Enter job description URL", placeholder="https://example.com/job-posting")
495
+ if job_url:
496
+ st.success(f"βœ… URL provided")
497
+
498
+ # Analyze button
499
+ if st.button("πŸš€ Analyze Resume", type="primary", use_container_width=True):
500
+ # Validation
501
+ if not api_key:
502
+ st.error("Please enter your OpenAI API key in the sidebar.")
503
+ elif not resume_file:
504
+ st.error("Please upload your resume.")
505
+ elif input_method == "Upload PDF" and not job_file:
506
+ st.error("Please upload the job description PDF.")
507
+ elif input_method == "Enter URL" and not job_url:
508
+ st.error("Please enter the job description URL.")
509
+ else:
510
+ try:
511
+ # Extract resume text
512
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_resume:
513
+ tmp_resume.write(resume_file.read())
514
+ tmp_resume.flush()
515
+ resume_text = extract_text_from_pdf(tmp_resume.name)
516
+ try:
517
+ os.unlink(tmp_resume.name)
518
+ except:
519
+ pass
520
+
521
+ # Extract job description
522
+ if input_method == "Upload PDF":
523
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_job:
524
+ tmp_job.write(job_file.read())
525
+ tmp_job.flush()
526
+ job_description_text = extract_text_from_pdf(tmp_job.name)
527
+ try:
528
+ os.unlink(tmp_job.name)
529
+ except:
530
+ pass
531
+ else:
532
+ with st.spinner("Fetching job description from URL..."):
533
+ loader = WebBaseLoader(job_url)
534
+ docs = loader.load()
535
+ # Try to get description from metadata, fallback to page content
536
+ if docs and len(docs) > 0:
537
+ job_description_text = docs[0].metadata.get("description", docs[0].page_content)
538
+ else:
539
+ st.error("Could not fetch content from the URL")
540
+ job_description_text = None
541
+
542
+ if job_description_text:
543
+ # Perform analysis
544
+ result = analyze_and_update_resume(resume_text, job_description_text)
545
+
546
+ if "error" not in result:
547
+ st.session_state.analysis_complete = True
548
+ st.session_state.analysis_result = result
549
+ else:
550
+ st.error(f"Analysis failed: {result['error']}")
551
+ else:
552
+ st.error("Could not extract job description text")
553
+
554
+ except Exception as e:
555
+ st.error(f"An error occurred: {str(e)}")
556
+ st.exception(e)
557
+
558
+ # Display results
559
+ if st.session_state.analysis_complete and st.session_state.analysis_result:
560
+ result = st.session_state.analysis_result
561
+
562
+ # Animated header
563
+ st.markdown('<div class="results-header"><h1>πŸ“Š Analysis Results</h1></div>', unsafe_allow_html=True)
564
+
565
+ # Score comparison with enhanced styling
566
+ col1, col2, col3 = st.columns([1, 1, 1])
567
+
568
+ initial_score = result['initial_score']
569
+ updated_score = result['updated_score']
570
+ score_diff = updated_score - initial_score if updated_score != -1 else 0
571
+
572
+ with col1:
573
+ st.markdown('<div class="score-card score-card-initial">', unsafe_allow_html=True)
574
+ # Progress ring SVG
575
+ progress_initial = initial_score / 100 * 377 # 377 is the circumference of the circle
576
+ st.markdown(f'''
577
+ <div class="progress-ring">
578
+ <svg width="120" height="120">
579
+ <circle class="progress-ring-circle" cx="60" cy="60" r="50"></circle>
580
+ <circle class="progress-ring-circle-progress" cx="60" cy="60" r="50"
581
+ style="stroke-dasharray: 377; stroke-dashoffset: {377 - progress_initial};">
582
+ </circle>
583
+ <text x="60" y="70" text-anchor="middle" fill="white" style="font-size: 28px; font-weight: bold;">
584
+ {initial_score}
585
+ </text>
586
+ </svg>
587
+ </div>
588
+ <div class="score-label">Initial Score</div>
589
+ ''', unsafe_allow_html=True)
590
+ st.markdown('</div>', unsafe_allow_html=True)
591
+
592
+ with col2:
593
+ st.markdown('<div class="score-card score-card-improved">', unsafe_allow_html=True)
594
+ if updated_score != -1:
595
+ progress_updated = updated_score / 100 * 377
596
+ st.markdown(f'''
597
+ <div class="progress-ring">
598
+ <svg width="120" height="120">
599
+ <circle class="progress-ring-circle" cx="60" cy="60" r="50"></circle>
600
+ <circle class="progress-ring-circle-progress" cx="60" cy="60" r="50"
601
+ style="stroke-dasharray: 377; stroke-dashoffset: {377 - progress_updated};">
602
+ </circle>
603
+ <text x="60" y="70" text-anchor="middle" fill="white" style="font-size: 28px; font-weight: bold;">
604
+ {updated_score}
605
+ </text>
606
+ </svg>
607
+ </div>
608
+ <div class="score-label">Improved Score</div>
609
+ <div class="score-delta">
610
+ <span class="arrow-up"></span>
611
+ <span>+{score_diff} points</span>
612
+ </div>
613
+ ''', unsafe_allow_html=True)
614
+ else:
615
+ st.markdown('<div class="score-value">N/A</div><div class="score-label">Improved Score</div>', unsafe_allow_html=True)
616
+ st.markdown('</div>', unsafe_allow_html=True)
617
+
618
+ with col3:
619
+ st.markdown('<div class="score-card score-card-improvement">', unsafe_allow_html=True)
620
+ if updated_score != -1 and initial_score > 0:
621
+ improvement_percentage = (score_diff / initial_score * 100)
622
+ st.markdown(f'''
623
+ <div style="margin-top: 20px;">
624
+ <div class="score-value">{improvement_percentage:.1f}%</div>
625
+ <div class="score-label">Total Improvement</div>
626
+ <div class="score-delta">
627
+ <span class="arrow-up"></span>
628
+ <span>{score_diff} points gained</span>
629
+ </div>
630
+ </div>
631
+ ''', unsafe_allow_html=True)
632
+ else:
633
+ st.markdown('<div class="score-value">N/A</div><div class="score-label">Improvement</div>', unsafe_allow_html=True)
634
+ st.markdown('</div>', unsafe_allow_html=True)
635
+
636
+ # Add some spacing
637
+ st.markdown("<br>", unsafe_allow_html=True)
638
+
639
+ # Issues identified with better styling
640
+ with st.expander("πŸ” **Issues Identified**", expanded=True):
641
+ st.markdown(f"""
642
+ <div style="background-color: #fff3cd; padding: 1.5rem; border-radius: 10px; border-left: 4px solid #ffc107; color: #856404;">
643
+ <p style="margin: 0; line-height: 1.6; font-size: 1rem;">
644
+ {result['initial_analysis']['score_issues']}
645
+ </p>
646
+ </div>
647
+ """, unsafe_allow_html=True)
648
+
649
+ # Suggestions with better styling
650
+ with st.expander("πŸ’‘ **Improvement Suggestions**", expanded=True):
651
+ st.markdown(f"""
652
+ <div style="background-color: #d4edda; padding: 1.5rem; border-radius: 10px; border-left: 4px solid #28a745; color: #155724;">
653
+ <p style="margin: 0; line-height: 1.6; font-size: 1rem;">
654
+ {result['suggested_resume_updates_description']}
655
+ </p>
656
+ </div>
657
+ """, unsafe_allow_html=True)
658
+
659
+ # Original sections
660
+ st.divider()
661
+ st.subheader("πŸ“‘ Original Resume Sections")
662
+
663
+ for section in result['initial_analysis']['resume_sections']:
664
+ with st.expander(f"**{section['section_name']}**"):
665
+ st.text(section['content'])
666
+
667
+ # Suggested updated sections
668
+ st.divider()
669
+ st.subheader("✨ Suggested Updated Resume Sections")
670
+
671
+ for section in result['suggested_updated_resume_content_json']:
672
+ with st.expander(f"**{section['section_name']}** (Optimized)"):
673
+ st.text(section['content'])
674
+
675
+ # Download button for updated resume
676
+ st.divider()
677
+ updated_resume_text = ""
678
+ for section in result['suggested_updated_resume_content_json']:
679
+ updated_resume_text += f"{section['section_name']}:\n{section['content']}\n\n"
680
+
681
+ st.download_button(
682
+ label="πŸ“₯ Download Optimized Resume (Text)",
683
+ data=updated_resume_text,
684
+ file_name="optimized_resume.txt",
685
+ mime="text/plain",
686
+ use_container_width=True
687
+ )