File size: 11,558 Bytes
80e6947
 
b9548de
 
80e6947
 
d68ff83
80e6947
0bbe141
 
80e6947
 
320d29b
58b9e2b
b9548de
0bbe141
 
 
80e6947
 
58b9e2b
0bbe141
b9548de
 
320d29b
0bbe141
80e6947
320d29b
0bbe141
80e6947
 
d915eee
b9548de
 
 
 
 
 
 
 
 
 
 
 
0bbe141
 
80e6947
320d29b
0bbe141
58b9e2b
 
 
80e6947
0bbe141
b9548de
 
80e6947
b9548de
 
 
58b9e2b
 
b9548de
 
 
 
 
 
 
58b9e2b
b9548de
58b9e2b
80e6947
 
58b9e2b
 
b9548de
 
80e6947
b9548de
 
 
58b9e2b
0bbe141
 
 
 
 
 
 
 
 
 
 
 
 
b9548de
 
 
320d29b
58b9e2b
80e6947
b9548de
 
 
 
320d29b
80e6947
b9548de
 
80e6947
b9548de
 
 
320d29b
80e6947
b9548de
 
80e6947
b9548de
 
 
 
 
58b9e2b
 
320d29b
b9548de
 
 
 
 
320d29b
b9548de
80e6947
320d29b
58b9e2b
0bbe141
b9548de
58b9e2b
b9548de
0bbe141
58b9e2b
b9548de
 
 
58b9e2b
0bbe141
 
 
80e6947
b9548de
0bbe141
 
b9548de
 
 
 
80e6947
b9548de
80e6947
320d29b
5fe15a6
b9548de
 
 
 
0bbe141
 
 
b9548de
 
 
 
 
 
 
 
0bbe141
b9548de
 
0bbe141
b9548de
 
0bbe141
 
 
b9548de
 
 
80e6947
 
b9548de
 
 
 
 
0bbe141
 
b9548de
 
 
 
 
320d29b
b9548de
 
 
 
 
 
 
 
 
0bbe141
b9548de
0bbe141
b9548de
0bbe141
 
b9548de
 
 
58b9e2b
 
b9548de
 
 
80e6947
b9548de
58b9e2b
b9548de
 
58b9e2b
b9548de
 
58b9e2b
b9548de
58b9e2b
b9548de
 
 
 
320d29b
b9548de
 
320d29b
b9548de
0bbe141
b9548de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80e6947
b9548de
 
80e6947
 
 
b9548de
 
 
 
58b9e2b
b9548de
 
 
 
58b9e2b
b9548de
 
 
58b9e2b
320d29b
b9548de
 
 
 
 
 
320d29b
b9548de
 
 
 
 
58b9e2b
b9548de
 
 
58b9e2b
80e6947
 
320d29b
b9548de
 
 
 
80e6947
b9548de
80e6947
b9548de
80e6947
b9548de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bbe141
80e6947
58b9e2b
b9548de
 
 
58b9e2b
b9548de
58b9e2b
b9548de
 
 
 
58b9e2b
80e6947
58b9e2b
 
320d29b
58b9e2b
b9548de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py
"""
Quantum Scrutiny Platform β€” Groq-Powered Resume Analyzer
Fully updated + cleaned single-file Streamlit application
"""

import os
import io
import re
import json
import base64
import traceback
from typing import Optional, List

# Env
from dotenv import load_dotenv
load_dotenv()

import streamlit as st
import pandas as pd

# File parsing
import fitz  # PyMuPDF
from docx import Document

# Groq client
from groq import Groq

# Validation
from pydantic import BaseModel, Field, ValidationError


# ---------------------------------------------------------
# Page config
# ---------------------------------------------------------
st.set_page_config(
    page_title="Quantum Scrutiny Platform",
    layout="wide"
)


# ---------------------------------------------------------
# Secrets
# ---------------------------------------------------------
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin")

groq_client = None
if GROQ_API_KEY:
    try:
        groq_client = Groq(api_key=GROQ_API_KEY)
    except Exception as e:
        st.error(f"Failed to initialize Groq client: {e}")
else:
    st.warning("GROQ_API_KEY not found β€” model calls disabled.")


# ---------------------------------------------------------
# Session State
# ---------------------------------------------------------
if 'is_admin_logged_in' not in st.session_state:
    st.session_state.is_admin_logged_in = False

if 'run_analysis' not in st.session_state:
    st.session_state.run_analysis = False

if 'individual_analysis' not in st.session_state:
    st.session_state.individual_analysis = []

if 'analyzed_data' not in st.session_state:
    cols = [
        'Name', 'Job Role', 'Resume Score (100)', 'Email', 'Phone', 'Shortlisted',
        'Experience Summary', 'Education Summary', 'Communication Rating (1-10)',
        'Skills/Technologies', 'Certifications', 'ABA Skills (1-10)',
        'RBT/BCBA Cert', 'Autism-Care Exp (1-10)'
    ]
    st.session_state.analyzed_data = pd.DataFrame(columns=cols)


# ---------------------------------------------------------
# Pydantic Schema
# ---------------------------------------------------------
class ResumeAnalysis(BaseModel):
    name: str = Field(default="Unknown")
    email: str = Field(default="")
    phone: str = Field(default="")
    certifications: List[str] = Field(default_factory=list)
    experience_summary: str = Field(default="")
    education_summary: str = Field(default="")
    communication_skills: str = Field(default="N/A")
    technical_skills: List[str] = Field(default_factory=list)
    aba_therapy_skills: Optional[str] = Field(default="N/A")
    rbt_bcba_certification: Optional[str] = Field(default="N/A")
    autism_care_experience_score: Optional[str] = Field(default="N/A")


# ---------------------------------------------------------
# Text Extraction
# ---------------------------------------------------------
def extract_text_from_file(uploaded_file) -> str:
    try:
        content = uploaded_file.read()
        name = uploaded_file.name.lower()

        # PDF
        if name.endswith(".pdf") or content[:5] == b"%PDF-":
            try:
                with fitz.open(stream=content, filetype="pdf") as doc:
                    return "".join([p.get_text() for p in doc]).strip()
            except:
                return ""

        # DOCX
        elif name.endswith(".docx"):
            try:
                doc = Document(io.BytesIO(content))
                return "\n".join([p.text for p in doc.paragraphs]).strip()
            except:
                return ""

        # Fallback
        return content.decode("utf-8", errors="ignore")

    except:
        return ""


# ---------------------------------------------------------
# Groq Streaming Wrapper
# ---------------------------------------------------------
def call_groq_stream_collect(prompt: str) -> Optional[str]:

    if not groq_client:
        st.error("Groq client not initialized.")
        return None

    try:
        completion = groq_client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "system", "content": "You are an AI resume analyzer."},
                {"role": "user", "content": prompt}
            ],
            stream=True,
            temperature=0.0,
            max_completion_tokens=2048
        )

        collected = ""
        for chunk in completion:
            try:
                delta = getattr(chunk.choices[0].delta, "content", None)
                if delta:
                    collected += delta
            except:
                pass
        return collected

    except Exception as e:
        st.error(f"Groq API error: {e}")
        return None


# ---------------------------------------------------------
# JSON Extraction
# ---------------------------------------------------------
def extract_first_json(text: str):
    if not text:
        return None

    # Try simple balanced regex
    match = re.search(r"\{[\s\S]*\}", text)
    if not match:
        return None

    raw_json = match.group(0)

    # Attempt parse
    try:
        return json.loads(raw_json)
    except:
        try:
            return json.loads(raw_json.replace("'", '"'))
        except:
            return None


# ---------------------------------------------------------
# Cached Analysis
# ---------------------------------------------------------
@st.cache_data(show_spinner=False)
def analyze_resume_with_groq_cached(resume_text: str, job_role: str) -> ResumeAnalysis:

    therapist_instruction = (
        "If role is Therapist, extract ABA skills, BCBA/RBT, and Autism-care scores."
        if job_role.lower() == "therapist" else
        "For non-therapist roles, set therapist fields to 'N/A'."
    )

    prompt = f"""
Return a JSON object with keys:
name, email, phone, certifications, experience_summary,
education_summary, communication_skills, technical_skills,
aba_therapy_skills, rbt_bcba_certification, autism_care_experience_score.

{therapist_instruction}

Resume Text:
{resume_text}

Return only JSON.
"""

    raw = call_groq_stream_collect(prompt)
    parsed = extract_first_json(raw)

    if not parsed:
        return ResumeAnalysis(name="Extraction Failed")

    try:
        return ResumeAnalysis.parse_obj(parsed)
    except:
        return ResumeAnalysis(name="Extraction Failed")


# ---------------------------------------------------------
# Scoring
# ---------------------------------------------------------
def calculate_resume_score(analysis: ResumeAnalysis, role: str) -> float:
    score = 0

    # Experience length (40)
    score += min(len(analysis.experience_summary) / 100, 1) * 40

    # Skills count (30)
    score += min(len(analysis.technical_skills) / 10, 1) * 30

    # Communication (20)
    try:
        c = float(re.findall(r"\d+", analysis.communication_skills)[0])
    except:
        c = 5
    score += (min(c, 10) / 10) * 20

    # Certifications (10)
    score += min(len(analysis.certifications), 10)

    # Therapist bonus (10)
    if role.lower() == "therapist":
        try:
            aba = float(re.findall(r"\d+", analysis.aba_therapy_skills)[0])
            autism = float(re.findall(r"\d+", analysis.autism_care_experience_score)[0])
            score += ((aba + autism) / 20) * 10
        except:
            pass

    return float(round(min(score, 100)))


# ---------------------------------------------------------
# Add Row
# ---------------------------------------------------------
def append_analysis_to_dataframe(role, analysis: ResumeAnalysis, score: float):

    df = st.session_state.analyzed_data

    df.loc[len(df)] = [
        analysis.name,
        role,
        score,
        analysis.email,
        analysis.phone,
        "No",
        analysis.experience_summary,
        analysis.education_summary,
        analysis.communication_skills,
        ", ".join(analysis.technical_skills),
        ", ".join(analysis.certifications),
        analysis.aba_therapy_skills,
        analysis.rbt_bcba_certification,
        analysis.autism_care_experience_score
    ]

    st.session_state.analyzed_data = df


# ---------------------------------------------------------
# Excel Export
# ---------------------------------------------------------
def df_to_excel_bytes(df):
    output = io.BytesIO()
    with pd.ExcelWriter(output, engine="openpyxl") as w:
        df.to_excel(w, index=False, sheet_name="Resume Analysis")
    return output.getvalue()


# ---------------------------------------------------------
# UI
# ---------------------------------------------------------
st.title("🌌 Quantum Scrutiny Platform β€” AI Resume Analyzer")

tab_user, tab_admin = st.tabs([
    "πŸ‘€ User Resume Panel",
    "πŸ”’ Admin Dashboard"
])

# ---------------------------------------------------------
# USER PANEL
# ---------------------------------------------------------
with tab_user:

    st.header("Upload Resumes")

    job_role = st.selectbox(
        "Select Job Role",
        ["Software Engineer", "ML Engineer", "Therapist", "Data Analyst", "Project Manager"]
    )

    files = st.file_uploader(
        "Upload PDF or DOCX",
        type=["pdf", "docx"],
        accept_multiple_files=True
    )

    if st.button("πŸš€ Analyze All"):
        if not files:
            st.warning("Upload at least one file.")
        else:
            st.session_state.run_analysis = True
            st.rerun()

    if st.session_state.run_analysis:

        if not files:
            st.error("No files found.")
            st.session_state.run_analysis = False

        else:
            total = len(files)
            progress = st.progress(0)

            for i, f in enumerate(files, 1):
                st.write(f"Analyzing **{f.name}**...")
                text = extract_text_from_file(f)

                if not text:
                    st.error(f"Could not extract text from {f.name}. Skipped.")
                    progress.progress(i / total)
                    continue

                analysis = analyze_resume_with_groq_cached(text, job_role)
                score = calculate_resume_score(analysis, job_role)

                append_analysis_to_dataframe(job_role, analysis, score)
                progress.progress(i / total)

            st.success("All files processed!")
            st.session_state.run_analysis = False


# ---------------------------------------------------------
# ADMIN PANEL
# ---------------------------------------------------------
with tab_admin:

    if not st.session_state.is_admin_logged_in:

        pwd = st.text_input("Admin Password", type="password")
        if st.button("Login"):
            if pwd == ADMIN_PASSWORD:
                st.session_state.is_admin_logged_in = True
                st.rerun()
            else:
                st.error("Incorrect password.")

    else:
        st.subheader("Admin Dashboard β€” Analyzed Data")

        df = st.session_state.analyzed_data
        st.dataframe(df, use_container_width=True)

        if st.button("Download Excel"):
            xls = df_to_excel_bytes(df)
            st.download_button(
                label="Download File",
                data=xls,
                file_name="resume_analysis.xlsx",
                mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            )

        if st.button("Clear Database"):
            st.session_state.analyzed_data = st.session_state.analyzed_data.iloc[0:0]
            st.success("Cleared.")