Spaces:
Runtime error

File size: 14,303 Bytes
dcf18e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
app.py β€” Main Streamlit application for FitMatch AI

Run with: streamlit run app.py
"""

import streamlit as st
from dotenv import load_dotenv  # Reads .env file for API keys

from utils.resume_parser import extract_text_from_pdf, clean_text
from utils.analyzer import analyze_resume, rewrite_resume, analyze_ats_keywords
from utils.pdf_generator import generate_pdf

# Load environment variables from .env file (for local development)
load_dotenv()

# ─── Page config (must be the first Streamlit command) ───
st.set_page_config(page_title="FitMatch AI", page_icon="🎯", layout="wide")

# ─── App header ───
st.title("FitMatch AI 🎯")
st.markdown("**Smart Resume Analyzer & Job Fit Scorer** β€” Powered by Llama 3 on Groq")
st.markdown("---")

# ─── Initialize session state ───
# session_state lets us keep data when the user switches tabs
if "resume_text" not in st.session_state:
    st.session_state.resume_text = ""
if "job_description" not in st.session_state:
    st.session_state.job_description = ""
if "job_role" not in st.session_state:
    st.session_state.job_role = ""
if "results" not in st.session_state:
    st.session_state.results = None

# ─── Create the three tabs ───
tab1, tab2, tab3 = st.tabs(["πŸ“„ Resume", "πŸ’Ό Job Target", "πŸ“Š Results"])

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TAB 1 β€” Resume Input
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
with tab1:
    st.header("Upload or Paste Your Resume")

    # Two columns: one for upload, one for paste
    col1, col2 = st.columns(2)

    with col1:
        st.subheader("Option A: Upload PDF")
        uploaded_file = st.file_uploader(
            "Choose a PDF file",
            type=["pdf"],
            help="Upload your resume as a PDF file",
        )
        if uploaded_file is not None:
            # Extract text from the uploaded PDF
            extracted = extract_text_from_pdf(uploaded_file)
            st.session_state.resume_text = clean_text(extracted)
            st.success("PDF uploaded and text extracted!")

    with col2:
        st.subheader("Option B: Paste Text")
        pasted_text = st.text_area(
            "Paste your resume text here",
            height=300,
            placeholder="Copy and paste your resume content here...",
            value=st.session_state.resume_text,
        )
        # Update session state if user types/pastes something
        if pasted_text:
            st.session_state.resume_text = clean_text(pasted_text)

    # Show what we have so far
    if st.session_state.resume_text:
        with st.expander("πŸ‘€ Preview extracted resume text", expanded=False):
            st.text(st.session_state.resume_text[:3000])  # Show first 3000 chars
        st.info(f"βœ… Resume loaded β€” {len(st.session_state.resume_text)} characters")
    else:
        st.warning("No resume loaded yet. Upload a PDF or paste text above.")

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TAB 2 β€” Job Target Input
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
with tab2:
    st.header("What Role Are You Targeting?")

    st.subheader("Option A: Paste a Job Description")
    jd_input = st.text_area(
        "Paste the full job description here",
        height=250,
        placeholder="Paste the job posting text here...",
        value=st.session_state.job_description,
    )
    st.session_state.job_description = jd_input

    st.markdown("**β€” OR β€”**")

    st.subheader("Option B: Just Enter a Job Title")
    role_input = st.text_input(
        "Type a job role (e.g. 'Data Analyst', 'Python Developer')",
        value=st.session_state.job_role,
        placeholder="e.g. Frontend Developer",
    )
    st.session_state.job_role = role_input

    # Quick status check
    if jd_input.strip():
        st.info("βœ… Job description provided β€” this will be used for analysis.")
    elif role_input.strip():
        st.info("βœ… Job role provided β€” the AI will generate a typical JD for this role.")
    else:
        st.warning("Please provide a job description or job role above.")

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TAB 3 β€” Analysis Results
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
with tab3:
    st.header("Your Fit Analysis")

    # Check if we have both inputs
    has_resume = bool(st.session_state.resume_text.strip())
    has_job = bool(st.session_state.job_description.strip() or st.session_state.job_role.strip())

    if not has_resume:
        st.warning("⬅️ Go to the **Resume** tab and upload or paste your resume first.")
    elif not has_job:
        st.warning("⬅️ Go to the **Job Target** tab and enter a job description or role.")
    else:
        # Show the Analyze button only when both inputs are ready
        if st.button("πŸ” Analyze Now", type="primary", use_container_width=True):
            with st.spinner("Analyzing your resume with AI... This takes a few seconds."):
                results = analyze_resume(
                    resume_text=st.session_state.resume_text,
                    job_description=st.session_state.job_description,
                    job_role=st.session_state.job_role,
                )
                st.session_state.results = results

    # ─── Display results if we have them ───
    if st.session_state.results:
        results = st.session_state.results

        # Check for errors
        if "error" in results:
            st.error(f"❌ {results['error']}")
            if "raw_response" in results:
                with st.expander("Show raw AI response (for debugging)"):
                    st.code(results["raw_response"])
        else:
            # ── Show Generated JD (if role-only mode was used) ──
            if "generated_jd" in results:
                with st.expander("πŸ“ Generated Job Description (AI-created for this role)"):
                    st.write(results["generated_jd"])

            # ── Row 1: Fit Score ──
            score = results.get("fit_score", 0)

            # Pick color based on score
            if score >= 70:
                color = "🟒"
                bar_color = "#28a745"  # green
            elif score >= 50:
                color = "🟑"
                bar_color = "#ffc107"  # yellow
            else:
                color = "πŸ”΄"
                bar_color = "#dc3545"  # red

            # Big score display
            st.markdown(
                f"<h1 style='text-align:center;'>{color} Fit Score: {score}/100</h1>",
                unsafe_allow_html=True,
            )
            # Visual progress bar
            st.progress(score / 100)

            st.markdown("---")

            # ── Row 2: Matched vs Missing Skills (side by side) ──
            col_match, col_miss = st.columns(2)

            with col_match:
                st.subheader("βœ… Matched Skills")
                matched = results.get("matched_skills", [])
                if matched:
                    for skill in matched:
                        st.markdown(f"- {skill}")
                else:
                    st.write("No matched skills found.")

            with col_miss:
                st.subheader("❌ Missing Skills")
                missing = results.get("missing_skills", [])
                if missing:
                    for skill in missing:
                        st.markdown(f"- {skill}")
                else:
                    st.write("No missing skills β€” great match!")

            st.markdown("---")

            # ── Row 3: Strengths & Suggestions (side by side) ──
            col_str, col_sug = st.columns(2)

            with col_str:
                st.subheader("πŸ’ͺ Resume Strengths")
                strengths = results.get("strengths", [])
                if strengths:
                    for item in strengths:
                        st.markdown(f"- {item}")
                else:
                    st.write("No strengths identified.")

            with col_sug:
                st.subheader("πŸ’‘ Improvement Suggestions")
                suggestions = results.get("suggestions", [])
                if suggestions:
                    for item in suggestions:
                        st.markdown(f"- {item}")
                else:
                    st.write("No suggestions β€” your resume looks solid!")

            # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            # SECTION: ATS Keyword Optimizer
            # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            st.divider()
            st.subheader("πŸ”‘ ATS Keyword Optimizer")
            st.write("See exactly which keywords from the job description are in your resume.")

            # We need a JD for keyword analysis β€” use provided or generated one
            jd_for_ats = st.session_state.job_description.strip()
            if not jd_for_ats and "generated_jd" in results:
                jd_for_ats = results["generated_jd"]

            if not jd_for_ats:
                st.info("ATS keyword analysis requires a job description. Enter one in the Job Target tab.")
            elif st.button("πŸ” Run ATS Keyword Analysis", key="ats_btn"):
                with st.spinner("Scanning for ATS keywords..."):
                    ats_results = analyze_ats_keywords(
                        st.session_state.resume_text, jd_for_ats
                    )
                    st.session_state["ats_results"] = ats_results

            # Display ATS results if available
            if st.session_state.get("ats_results"):
                ats = st.session_state["ats_results"]

                if "error" in ats:
                    st.error(f"❌ {ats['error']}")
                else:
                    # Keyword score
                    ks = ats.get("keyword_score", 0)
                    st.markdown(f"**ATS Keyword Match: {ks}%**")
                    st.progress(ks / 100)

                    col_found, col_missing = st.columns(2)

                    with col_found:
                        st.markdown("**βœ… Found in Resume:**")
                        for kw in ats.get("found_keywords", []):
                            st.markdown(f"- :green[{kw}]")

                    with col_missing:
                        st.markdown("**❌ Missing from Resume:**")
                        for kw in ats.get("missing_keywords", []):
                            st.markdown(f"- :red[{kw}]")

                    # Show insertion suggestions
                    insert_tips = ats.get("insert_suggestions", [])
                    if insert_tips:
                        with st.expander("πŸ’‘ How to add missing keywords", expanded=True):
                            for tip in insert_tips:
                                if isinstance(tip, dict):
                                    st.markdown(
                                        f"- **{tip.get('keyword', '')}** β†’ {tip.get('suggestion', '')}"
                                    )

            # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            # SECTION: AI Resume Rewriter
            # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            st.divider()
            st.subheader("✨ AI Resume Rewriter")
            st.write("Want AI to update your resume based on the gaps found?")

            if st.button("πŸ“ Rewrite My Resume", key="rewrite_btn"):
                with st.spinner("Rewriting your resume... This takes a few seconds."):
                    rewritten = rewrite_resume(
                        resume_text=st.session_state.resume_text,
                        missing_skills=results.get("missing_skills", []),
                        suggestions=results.get("suggestions", []),
                    )
                    st.session_state["rewritten_resume"] = rewritten

            # Display rewritten resume if available
            if st.session_state.get("rewritten_resume"):
                rewritten_text = st.session_state["rewritten_resume"]

                # Check if the rewriter returned an error
                if rewritten_text.startswith("[Error]"):
                    st.error(rewritten_text)
                else:
                    st.caption("⚠️ Always review the rewritten resume before using it. AI does not fabricate, but double-check!")
                    edited_resume = st.text_area(
                        "Your Updated Resume (editable β€” make final tweaks here)",
                        value=rewritten_text,
                        height=400,
                        key="editable_resume",
                    )

                    # Generate PDF and offer download
                    pdf_bytes = bytes(generate_pdf(edited_resume))
                    st.download_button(
                        label="πŸ“₯ Download Updated Resume as PDF",
                        data=pdf_bytes,
                        file_name="updated_resume_fitmatch.pdf",
                        mime="application/pdf",
                    )

# ─── Footer ───
st.markdown("---")
st.markdown(
    "<p style='text-align:center; color:gray;'>"
    "Built with Streamlit + Groq (Llama 3) | FitMatch AI Workshop Demo"
    "</p>",
    unsafe_allow_html=True,
)