loki2910 commited on
Commit
d64f292
·
verified ·
1 Parent(s): c994849

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +267 -0
app.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import re
4
+ import tempfile
5
+ import traceback
6
+ from typing import Tuple, Dict
7
+
8
+ import fitz # PyMuPDF
9
+ import docx # python-docx
10
+
11
+ import numpy as np
12
+ from sklearn.metrics.pairwise import cosine_similarity
13
+ import gradio as gr
14
+
15
+ # --------------------------
16
+ # Pre-load all heavy libraries and models at startup.
17
+ # --------------------------
18
+ print("Starting up: Loading transformer models...")
19
+ from sentence_transformers import SentenceTransformer
20
+ from transformers import BertTokenizer, BertModel
21
+ import torch
22
+
23
+ # Load models into memory once when the application starts
24
+ sentence_transformer = SentenceTransformer("all-MiniLM-L6-v2")
25
+ bert_tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
26
+ bert_model = BertModel.from_pretrained("bert-base-uncased")
27
+ bert_model.eval()
28
+ print("Transformer models loaded successfully.")
29
+
30
+ # --------------------------
31
+ # Built-in stopwords
32
+ # --------------------------
33
+ EN_STOPWORDS = {
34
+ "a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "as",
35
+ "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by",
36
+ "could", "did", "do", "does", "doing", "down", "during", "each", "few", "for", "from", "further",
37
+ "had", "has", "have", "having", "he", "her", "here", "hers", "herself", "him", "himself", "his",
38
+ "how", "i", "if", "in", "into", "is", "it", "its", "itself", "just", "me", "more", "most", "my",
39
+ "myself", "no", "nor", "not", "now", "of", "off", "on", "once", "only", "or", "other", "ought", "our",
40
+ "ours", "ourselves", "out", "over", "own", "same", "she", "should", "so", "some", "such", "than",
41
+ "that", "the", "their", "theirs", "them", "themselves", "then", "there", "these", "they", "this",
42
+ "those", "through", "to", "too", "under", "until", "up", "very", "was", "we", "were", "what", "when",
43
+ "where", "which", "while", "who", "whom", "why", "with", "would", "you", "your", "yours", "yourself",
44
+ "yourselves"
45
+ }
46
+
47
+
48
+ # --------------------------
49
+ # Utilities: text extraction
50
+ # --------------------------
51
+ def extract_text_from_pdf_bytes(pdf_bytes: bytes) -> str:
52
+ try:
53
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
54
+ pages = [p.get_text("text") for p in doc]
55
+ doc.close()
56
+ return "\n".join(p for p in pages if p)
57
+ except Exception as e:
58
+ return f"[Error reading PDF: {e}]"
59
+
60
+
61
+ def extract_text_from_docx_bytes(docx_bytes: bytes) -> str:
62
+ try:
63
+ docx_io = io.BytesIO(docx_bytes)
64
+ doc = docx.Document(docx_io)
65
+ paragraphs = [p.text for p in doc.paragraphs if p.text]
66
+ return "\n".join(paragraphs)
67
+ except Exception as e:
68
+ return f"[Error reading DOCX: {e}]"
69
+
70
+
71
+ def extract_text_from_fileobj(file_obj) -> Tuple[str, str]:
72
+ fname = "uploaded_file"
73
+ try:
74
+ fname = os.path.basename(file_obj.name)
75
+ with open(file_obj.name, "rb") as f:
76
+ raw_bytes = f.read()
77
+
78
+ ext = fname.split('.')[-1].lower()
79
+
80
+ if ext == "pdf":
81
+ return (extract_text_from_pdf_bytes(raw_bytes), fname)
82
+ elif ext == "docx":
83
+ return (extract_text_from_docx_bytes(raw_bytes), fname)
84
+ else: # Fallback for .txt or other text-based files
85
+ return (raw_bytes.decode("utf-8", errors="ignore"), fname)
86
+
87
+ except Exception as exc:
88
+ return (f"[Error reading uploaded file: {exc}\n{traceback.format_exc()}]", fname)
89
+
90
+
91
+ # --------------------------
92
+ # Text preprocessing
93
+ # --------------------------
94
+ def preprocess_text(text: str, remove_stopwords: bool = True) -> str:
95
+ if not text:
96
+ return ""
97
+ t = text.lower()
98
+ t = re.sub(r"\s+", " ", t)
99
+ t = re.sub(r"[^a-z0-9\s]", " ", t)
100
+ words = t.split()
101
+ if remove_stopwords:
102
+ words = [w for w in words if w not in EN_STOPWORDS]
103
+ return " ".join(words)
104
+
105
+
106
+ # --------------------------
107
+ # Embedding helpers
108
+ # --------------------------
109
+ def get_sentence_embedding(text: str, mode: str = "sbert") -> np.ndarray:
110
+ if mode == "sbert":
111
+ return sentence_transformer.encode([text], show_progress_bar=False)
112
+ elif mode == "bert":
113
+ tokens = bert_tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
114
+ with torch.no_grad():
115
+ out = bert_model(**tokens)
116
+ cls = out.last_hidden_state[:, 0, :].numpy()
117
+ return cls
118
+ else:
119
+ raise ValueError("Unsupported mode")
120
+
121
+
122
+ def calculate_similarity(resume_text: str, job_text: str, mode: str = "sbert") -> float:
123
+ r_emb = get_sentence_embedding(resume_text, mode=mode)
124
+ j_emb = get_sentence_embedding(job_text, mode=mode)
125
+ sim = cosine_similarity(r_emb, j_emb)[0][0]
126
+ return float(np.round(sim * 100, 2))
127
+
128
+
129
+ # --------------------------
130
+ # Keyword analysis
131
+ # --------------------------
132
+ DEFAULT_KEYWORDS = {
133
+ "skills": {"python", "nlp", "java", "sql", "tensorflow", "pytorch", "docker", "git", "react", "cloud", "aws",
134
+ "azure"},
135
+ "concepts": {"machine", "learning", "data", "analysis", "nlp", "vision", "agile", "scrum"},
136
+ "roles": {"software", "engineer", "developer", "manager", "scientist", "analyst", "architect"},
137
+ }
138
+
139
+
140
+ def analyze_resume_keywords(resume_text: str, job_description: str, keywords: Dict = None):
141
+ if keywords is None:
142
+ keywords = DEFAULT_KEYWORDS
143
+ clean_resume = preprocess_text(resume_text)
144
+ clean_job = preprocess_text(job_description)
145
+ resume_words = set(clean_resume.split())
146
+ job_words = set(clean_job.split())
147
+
148
+ missing = {}
149
+ for cat, kws in keywords.items():
150
+ missing_from_cat = [kw for kw in kws if kw in job_words and kw not in resume_words]
151
+ if missing_from_cat:
152
+ missing[cat] = sorted(missing_from_cat)
153
+
154
+ low_resume = (resume_text or "").lower()
155
+ sections_present = {
156
+ "skills": "skills" in low_resume,
157
+ "experience": "experience" in low_resume or "employment" in low_resume,
158
+ "summary": "summary" in low_resume or "objective" in low_resume,
159
+ }
160
+
161
+ suggestions = []
162
+ if any(missing.values()):
163
+ for cat, kws in missing.items():
164
+ for kw in kws:
165
+ if cat == "skills":
166
+ suggestions.append(f"Add keyword '{kw}' to your Skills section." if sections_present[
167
+ "skills"] else f"Consider creating a Skills section to include '{kw}'.")
168
+ elif cat == "concepts":
169
+ suggestions.append(
170
+ f"Try to demonstrate your knowledge of '{kw}' in your Experience or Projects section.")
171
+ elif cat == "roles":
172
+ suggestions.append(f"Align your Summary/Objective to mention the title '{kw}'.")
173
+ else:
174
+ suggestions.append("Great job! Your resume contains many of the keywords found in the job description.")
175
+
176
+ return missing, "\n".join(f"- {s}" for s in suggestions)
177
+
178
+
179
+ # --------------------------
180
+ # Gradio app logic
181
+ # --------------------------
182
+ def analyze_resume(file, job_description: str, mode: str, show_cleaned: bool):
183
+ if file is None:
184
+ return 0.0, "No file uploaded.", "", {}, "Please upload a PDF or DOCX resume.", ""
185
+
186
+ try:
187
+ resume_text, fname = extract_text_from_fileobj(file)
188
+ if resume_text.strip().startswith("[Error"):
189
+ raise RuntimeError(resume_text)
190
+
191
+ cleaned_resume = preprocess_text(resume_text)
192
+ cleaned_job = preprocess_text(job_description)
193
+
194
+ sim_pct = calculate_similarity(cleaned_resume, cleaned_job, mode=mode)
195
+
196
+ if sim_pct >= 80:
197
+ verdict = "Excellent match"
198
+ elif sim_pct >= 60:
199
+ verdict = "Good match"
200
+ elif sim_pct >= 40:
201
+ verdict = "Fair match — can be improved"
202
+ else:
203
+ verdict = "Low match — consider major revisions"
204
+
205
+ missing, suggestions_text = analyze_resume_keywords(resume_text, job_description)
206
+
207
+ cleaned_preview = cleaned_resume if show_cleaned else "Preview disabled."
208
+ raw_preview = "\n".join([ln.strip() for ln in resume_text.splitlines() if ln.strip()][:15])
209
+
210
+ return float(sim_pct), f"{sim_pct:.2f}% — {verdict}", cleaned_preview, missing, suggestions_text, raw_preview
211
+
212
+ except Exception as e:
213
+ tb = traceback.format_exc()
214
+ return 0.0, f"Error: {e}", "", {}, "An error occurred. Check server logs for details.", tb
215
+
216
+
217
+ # --------------------------
218
+ # Build Gradio UI
219
+ # --------------------------
220
+ def build_ui():
221
+ # The 'theme' parameter is removed to restore the default Gradio look
222
+ with gr.Blocks(title="Resume ↔ Job Matcher") as demo:
223
+ gr.Markdown("# Resume — Job Description Matcher")
224
+ gr.Markdown(
225
+ "Upload a PDF or DOCX resume, paste a job description, and get an instant analysis of how well they match.")
226
+
227
+ with gr.Row():
228
+ with gr.Column(scale=1):
229
+ # THIS LINE IS CHANGED to be more mobile-friendly
230
+ file_in = gr.File(label="Upload resume (PDF or DOCX)", file_count="single", file_types=[".pdf", ".docx"])
231
+ mode = gr.Radio(choices=["sbert", "bert"], value="sbert", label="Analysis Mode",
232
+ info="SBERT is faster, BERT is more detailed.")
233
+ job_desc = gr.Textbox(lines=8, label="Job Description",
234
+ placeholder="Paste the full job description here...")
235
+ show_cleaned = gr.Checkbox(label="Show cleaned (preprocessed) resume preview", value=False)
236
+ run_btn = gr.Button("Analyze Resume", variant="primary")
237
+
238
+ with gr.Column(scale=1):
239
+ gr.Markdown("### Match Score")
240
+ score_slider = gr.Slider(value=0, minimum=0, maximum=100, step=0.01, interactive=False,
241
+ label="Similarity (%)")
242
+ score_text = gr.Textbox(label="Score & Verdict", interactive=False)
243
+
244
+ gr.Markdown("### Keyword Analysis & Suggestions")
245
+ suggestions_out = gr.Textbox(label="Suggestions for Improvement", interactive=False, lines=5)
246
+ missing_out = gr.JSON(label="Missing Keywords from Job Description")
247
+
248
+ with gr.Accordion("Show Previews...", open=False):
249
+ cleaned_preview = gr.Textbox(label="Cleaned Resume Preview", interactive=False, lines=8)
250
+ raw_preview = gr.Textbox(label="Raw Extracted Resume (First 15 lines)", interactive=False, lines=8)
251
+
252
+ run_btn.click(
253
+ analyze_resume,
254
+ inputs=[file_in, job_desc, mode, show_cleaned],
255
+ outputs=[score_slider, score_text, cleaned_preview, missing_out, suggestions_out, raw_preview],
256
+ )
257
+
258
+ gr.Markdown("---")
259
+ gr.Markdown("Built with Gradio. Transformer models are pre-loaded at startup.")
260
+
261
+ return demo
262
+
263
+
264
+ if __name__ == "__main__":
265
+ demo = build_ui()
266
+ # "0.0.0.0" is required for deployment on platforms like Hugging Face Spaces.
267
+ demo.launch(server_name="0.0.0.0")