Spaces:
Running
Running
File size: 10,171 Bytes
af91fc8 ba6957d af91fc8 ba6957d af91fc8 ba6957d af91fc8 ba6957d af91fc8 ba6957d af91fc8 ba6957d af91fc8 ba6957d af91fc8 ba6957d af91fc8 f51752f af91fc8 f51752f af91fc8 f51752f af91fc8 f51752f af91fc8 f51752f af91fc8 f51752f 12b8641 f51752f af91fc8 c6d0a9b af91fc8 c6d0a9b af91fc8 12b8641 |
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 |
import gradio as gr
import PyPDF2
import docx2txt
from typing import Optional, List, Dict
import re
from pinecone_handler import PineconeHandler
import hopsworks
import pandas as pd
import os
from dotenv import load_dotenv
load_dotenv()
class Database:
def __init__(self):
# Initialize Hopsworks
project = "orestavf"
api_key = os.getenv("HOPSWORKS_API_KEY")
self.project = hopsworks.login(project=project, api_key_value=api_key)
self.fs = self.project.get_feature_store()
self.feedback_fg = self.fs.get_or_create_feature_group(
name="job_feedback",
version=1,
primary_key=["job_id"],
description="Feature group for storing user feedback on job matches.",
online_enabled=True
)
def save_feedback(self, job_id: str, resume_text: str, headline: str,
occupation: str, description: str, is_relevant: bool):
# Prepare feedback data as a pandas DataFrame
feedback_data = pd.DataFrame([{
"job_id": job_id,
"resume_text": resume_text,
"job_headline": headline,
"job_occupation": occupation,
"job_description": description,
"is_relevant": is_relevant,
#"timestamp": datetime.now()
}])
self.feedback_fg.insert(feedback_data)
print(f"Feedback saved to Hopsworks for job ID: {job_id}")
def extract_text(file) -> Optional[str]:
"""Extract text from uploaded resume file"""
if not file:
return None
try:
file_type = file.name.split('.')[-1].lower()
if file_type == 'pdf':
pdf_reader = PyPDF2.PdfReader(file)
return "\n".join(page.extract_text() for page in pdf_reader.pages)
elif file_type in ['docx', 'doc']:
return docx2txt.process(file)
elif file_type == 'txt':
return str(file.read(), "utf-8")
else:
return f"Unsupported file format: {file_type}"
except Exception as e:
return f"Error processing file: {str(e)}"
class JobMatcher:
def __init__(self):
self.handler = PineconeHandler()
self.db = Database()
self.current_results = []
self.current_resume_text = None
def search_jobs(self, file, num_results: int, city: str = "") -> List[Dict]:
"""Search for matching jobs and return results"""
if not file:
return [{"error": "Please upload a resume file."}]
try:
resume_text = extract_text(file)
if not resume_text:
return [{"error": "Could not extract text from resume."}]
self.current_resume_text = resume_text
resume_text = re.sub(r'\s+', ' ', resume_text).strip()
# Get results from Pinecone
results = self.handler.search_similar_ads(resume_text, top_k=num_results, city=city.strip())
if not results:
return [{"error": "No matching jobs found. Try adjusting your search criteria."}]
# Store results with their Pinecone IDs
self.current_results = [
{
'id': result.id, # Use Pinecone's ID
'score': result.score,
'metadata': result.metadata
}
for result in results
]
return self.current_results
except Exception as e:
return [{"error": f"Error: {str(e)}"}]
def submit_feedback(self, pinecone_id: str, is_relevant: bool) -> str:
"""Submit feedback for a specific job using Pinecone ID"""
try:
# Find the job in current results by Pinecone ID
job = next((job for job in self.current_results if job['id'] == pinecone_id), None)
if not job:
return "Error: Job not found"
metadata = job['metadata']
self.db.save_feedback(
job_id=pinecone_id, # Use Pinecone's ID
resume_text=self.current_resume_text,
headline=metadata['headline'],
occupation=metadata['occupation'],
description=metadata['description'],
is_relevant=is_relevant
)
return f"\u2713 Feedback saved for '{metadata['headline']}'"
except Exception as e:
return f"Error saving feedback: {str(e)}"
def create_interface():
matcher = JobMatcher()
with gr.Blocks() as interface:
gr.Markdown("# AI-Powered Job Search")
with gr.Row():
file_input = gr.File(label="Upload Resume (PDF, DOCX, or TXT)")
num_results = gr.Slider(minimum=1, maximum=20, value=5, step=1, label="Number of Results")
city_input = gr.Textbox(label="Filter by City (Optional)")
search_btn = gr.Button("Search Jobs")
status = gr.Textbox(label="Status", interactive=False)
# Container for job results and feedback buttons
job_containers = []
for i in range(20): # Support up to 20 results
with gr.Column(visible=False) as container:
job_content = gr.Markdown("", elem_id=f"job_content_{i}")
with gr.Row():
relevant_btn = gr.Button("π Relevant", elem_id=f"relevant_{i}")
not_relevant_btn = gr.Button("π Not Relevant", elem_id=f"not_relevant_{i}")
feedback_status = gr.Markdown("")
job_containers.append({
'container': container,
'content': job_content,
'feedback_status': feedback_status,
'pinecone_id': None # Will store Pinecone ID for each job
})
def update_job_displays(file, num_results, city):
results = matcher.search_jobs(file, num_results, city)
# Initialize updates list with default values for all containers
updates = []
if "error" in results[0]:
# If there's an error, hide all containers and show error message
for _ in range(20):
updates.extend([
gr.update(visible=False), # Container visibility
"", # Job content
"" # Feedback status
])
updates.append(results[0]["error"]) # Status message
return updates
# Process results and generate updates
for i in range(20):
if i < len(results):
job = results[i]
metadata = job['metadata']
# Store Pinecone ID for this container
job_containers[i]['pinecone_id'] = job['id']
content = f"""
### {metadata['headline']}
**Match Score:** {job['score']:.2f}
**Location:** {metadata['city']}
**Occupation:** {metadata['occupation']}
**Published:** {metadata['published']}
{metadata['description'][:500]}...
**Contact:** {metadata.get('email', 'Not provided')}
**More Info:** {metadata.get('webpage_url', 'Not available')}
*Job ID: {job['id']}*
"""
updates.extend([
gr.update(visible=True), # Container visibility
content, # Job content
"" # Reset feedback status
])
else:
# For unused containers, hide them and clear content
updates.extend([
gr.update(visible=False), # Container visibility
"", # Job content
"" # Reset feedback status
])
# Add final status message
updates.append("Jobs found! If you decide to help us by rating them as relevant or not relevant, your CV will be uploaded to our servers and used for improving the service. ")
return updates
def handle_feedback(container_index: int, is_relevant: bool):
pinecone_id = job_containers[container_index]['pinecone_id']
if pinecone_id:
response = matcher.submit_feedback(pinecone_id, is_relevant)
return response
return "Error: Job ID not found"
# Connect search button
all_outputs = []
for container in job_containers:
all_outputs.extend([
container['container'],
container['content'],
container['feedback_status']
])
all_outputs.append(status)
search_btn.click(
fn=update_job_displays,
inputs=[file_input, num_results, city_input],
outputs=all_outputs
)
# Connect feedback buttons for each container
for i, container in enumerate(job_containers):
container_obj = container['container']
feedback_status = container['feedback_status']
# Get the buttons from the container
relevant_btn = container_obj.children[1].children[0]
not_relevant_btn = container_obj.children[1].children[1]
relevant_btn.click(
fn=lambda idx=i: handle_feedback(idx, True),
inputs=[],
outputs=[feedback_status]
)
not_relevant_btn.click(
fn=lambda idx=i: handle_feedback(idx, False),
inputs=[],
outputs=[feedback_status]
)
return interface
if __name__ == "__main__":
interface = create_interface()
interface.launch(debug=True)
|