sivan26 commited on
Commit
c76eee7
·
verified ·
1 Parent(s): f27aeb5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -136
app.py CHANGED
@@ -1,152 +1,132 @@
1
  import gradio as gr
2
  import pandas as pd
3
- import numpy as np
4
- import re
5
- import warnings
6
  from typing import List, Dict
 
7
 
8
- # Import ML libraries from scikit-learn
9
- from sklearn.feature_extraction.text import TfidfVectorizer
10
- from sklearn.metrics.pairwise import cosine_similarity
 
 
 
 
 
 
 
 
 
 
11
 
12
- # --- MODIFIED: Import the dataset from the separate file ---
13
- from jobs_dataset import JOBS_DATABASE
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- # Suppress warnings for a cleaner output
16
- warnings.filterwarnings('ignore')
 
 
 
 
 
 
 
 
 
17
 
18
- # --- The `generate_job_database` function has been REMOVED from this file ---
 
 
 
 
19
 
 
 
 
20
 
21
- # --- MACHINE LEARNING MODEL CLASS (This code is the same) ---
22
- class MLJobRecommendationSystem:
23
- def __init__(self, jobs_database: List[Dict]):
24
- print("🤖 Initializing ML-powered Job Recommendation System...")
25
- self.df = pd.DataFrame(jobs_database)
26
- self.vectorizer = TfidfVectorizer(max_features=500, stop_words='english', ngram_range=(1, 2))
27
- self._train_model()
28
- print(" ML models trained successfully!")
 
 
 
 
 
 
 
 
 
29
 
30
- def _train_model(self):
31
- """Prepares the data and 'trains' the TF-IDF model."""
32
- self.df['combined_text'] = (
33
- self.df['title'] + ' ' +
34
- self.df['description'] + ' ' +
35
- self.df['requirements'].apply(lambda x: ' '.join(x))
36
- ).str.lower()
37
- self.job_vectors = self.vectorizer.fit_transform(self.df['combined_text'])
 
 
 
 
 
 
 
 
 
38
 
39
- def recommend_jobs(self, user_skills: str, num_recommendations: int = 10,
40
- filter_category: str = "All Categories", filter_experience: str = "All Levels") -> str:
41
- """Uses the trained model to find and recommend jobs."""
42
- if not user_skills.strip():
43
- return "🔍 Please enter your skills to get personalized AI-powered job recommendations!"
44
-
45
- try:
46
- user_text = re.sub(r'[^\w\s,]', '', user_skills.lower())
47
- user_vector = self.vectorizer.transform([user_text])
48
-
49
- filtered_df = self.df.copy()
50
- if filter_category and filter_category != "All Categories":
51
- filtered_df = filtered_df[filtered_df['category'] == filter_category]
52
- if filter_experience and filter_experience != "All Levels":
53
- filtered_df = filtered_df[filtered_df['experience_level'] == filter_experience]
54
-
55
- if filtered_df.empty:
56
- return "❌ No jobs found matching your filter criteria. Please adjust your filters and try again."
57
-
58
- filtered_indices = filtered_df.index
59
- filtered_job_vectors = self.job_vectors[filtered_indices]
60
-
61
- similarity_scores = cosine_similarity(user_vector, filtered_job_vectors)[0]
62
-
63
- filtered_df['similarity_score'] = similarity_scores
64
- sorted_jobs = filtered_df.sort_values(by='similarity_score', ascending=False)
65
-
66
- top_jobs = sorted_jobs.head(int(num_recommendations))
67
-
68
- recommendations = ["# 🎯 AI-Powered Job Recommendations\n*Based on semantic similarity between your skills and job descriptions.*\n---"]
69
- for _, job in top_jobs.iterrows():
70
- score = job['similarity_score']
71
- if score < 0.05: continue
72
-
73
- match_quality = "🟢 Excellent Match" if score >= 0.5 else "🟡 Good Match" if score >= 0.25 else "🟠 Moderate Match"
74
-
75
- recommendation = f"""
76
- ## {job['title']}
77
- **{match_quality}** | **AI Confidence: {score:.1%}**
78
- - **Category:** {job['category']}
79
- - **Experience:** {job['experience_level']}
80
- - **Location:** {job['location']}
81
- - **Salary:** {job['salary_range']}
82
- - **Description:** {job['description']}
83
- - **Core Skills:** {', '.join(job['requirements'])}
84
- ---
85
- """
86
- recommendations.append(recommendation)
87
-
88
- if len(recommendations) == 1:
89
- return "😔 No relevant jobs found with the current skills. Try being more descriptive or adjusting filters."
90
-
91
- return '\n'.join(recommendations)
92
-
93
- except Exception as e:
94
- return f"❌ An unexpected error occurred: {str(e)}. Please try again."
95
 
96
- # --- SETUP AND LAUNCH GRADIO INTERFACE ---
 
 
 
97
 
98
- # --- MODIFIED: Initialize the system using the imported database ---
99
- print("🚀 Starting application...")
100
- # We use the JOBS_DATABASE variable we imported from the other file.
101
- ml_system = MLJobRecommendationSystem(JOBS_DATABASE)
102
 
103
- # Define the user interface using Gradio (This code is the same)
104
- with gr.Blocks(theme=gr.themes.Soft(), title="AI Job Recommender") as app:
105
- gr.HTML("""
106
- <div style="text-align: center; max-width: 800px; margin: auto;">
107
- <h1>🤖 AI-Powered Job Recommendation System</h1>
108
- <p>This app uses a Machine Learning model (TF-IDF and Cosine Similarity) to find jobs that are semantically similar to your skills, going beyond simple keyword matching.</p>
109
- </div>
110
- """)
111
-
112
- with gr.Row():
113
- with gr.Column(scale=2):
114
- skills_input = gr.Textbox(
115
- label="Enter Your Skills and Experience",
116
- placeholder="e.g., Python development with flask, data analysis, machine learning models, and aws...",
117
- lines=4,
118
- )
119
-
120
- num_jobs = gr.Slider(
121
- minimum=5, maximum=20, value=10, step=1, label="Number of Recommendations"
122
- )
123
-
124
- with gr.Row():
125
- category_filter = gr.Dropdown(
126
- choices=["All Categories"] + sorted(list(ml_system.df['category'].unique())),
127
- value="All Categories",
128
- label="Filter by Industry"
129
- )
130
-
131
- experience_filter = gr.Dropdown(
132
- choices=["All Levels"] + sorted(list(ml_system.df['experience_level'].unique())),
133
- value="All Levels",
134
- label="Filter by Experience"
135
- )
136
-
137
- submit_btn = gr.Button("🚀 Get AI-Powered Recommendations", variant="primary")
138
-
139
- with gr.Column(scale=3):
140
- output_markdown = gr.Markdown(
141
- value="### Your personalized job recommendations will appear here.\nEnter your skills and click the button to start! ✨"
142
- )
143
-
144
- submit_btn.click(
145
- fn=ml_system.recommend_jobs,
146
- inputs=[skills_input, num_jobs, category_filter, experience_filter],
147
- outputs=output_markdown
148
- )
149
 
150
- # Launch the Gradio app
151
  if __name__ == "__main__":
152
- app.launch()
 
1
  import gradio as gr
2
  import pandas as pd
3
+ import random
 
 
4
  from typing import List, Dict
5
+ from sentence_transformers import SentenceTransformer, util
6
 
7
+ # -----------------------------
8
+ # Job Database Generation
9
+ # -----------------------------
10
+ class JobDatabase:
11
+ def __init__(self):
12
+ self.jobs = self._generate_job_database()
13
+ self.df_jobs = pd.DataFrame(self.jobs)
14
+ # Prepare a textual representation of skills for embeddings
15
+ self.df_jobs['skills_text'] = self.df_jobs['requirements'].apply(lambda x: ", ".join(x))
16
+ # Load lightweight embedding model
17
+ self.model = SentenceTransformer('all-MiniLM-L6-v2')
18
+ # Encode all job skills in advance
19
+ self.job_embeddings = self.model.encode(self.df_jobs['skills_text'].tolist(), convert_to_tensor=True)
20
 
21
+ def _generate_job_database(self) -> List[Dict]:
22
+ """Generate a minimal example database; replace with your full database"""
23
+ job_templates = {
24
+ "Technology": [
25
+ {"title": "Software Engineer", "desc": "Design and develop software applications",
26
+ "skills": ["Python", "Java", "JavaScript", "Git", "Agile", "Problem Solving"]},
27
+ {"title": "Data Scientist", "desc": "Analyze complex data to extract business insights",
28
+ "skills": ["Python", "R", "Machine Learning", "SQL", "Statistics", "Pandas"]}
29
+ ],
30
+ "Finance": [
31
+ {"title": "Financial Analyst", "desc": "Analyze financial data and market trends",
32
+ "skills": ["Financial Modeling", "Excel", "Data Analysis", "Financial Reporting", "Market Research"]}
33
+ ]
34
+ }
35
 
36
+ experience_levels = ["Entry-level", "Mid-level", "Senior", "Lead/Principal"]
37
+ salary_ranges = {
38
+ "Entry-level": ["$35k-$50k", "$40k-$55k"],
39
+ "Mid-level": ["$55k-$75k", "$60k-$80k"],
40
+ "Senior": ["$80k-$110k", "$90k-$120k"],
41
+ "Lead/Principal": ["$120k-$150k", "$130k-$160k"]
42
+ }
43
+ additional_skills = {
44
+ "Technology": ["Debugging", "Code Review", "System Design"],
45
+ "Finance": ["Financial Regulations", "Risk Management", "Excel Advanced"]
46
+ }
47
 
48
+ jobs = []
49
+ job_id = 1
50
+ categories = list(job_templates.keys())
51
+ jobs_per_category = 1000 // len(categories)
52
+ remaining_jobs = 1000 % len(categories)
53
 
54
+ for i, category in enumerate(categories):
55
+ templates = job_templates[category]
56
+ jobs_for_this_category = jobs_per_category + (1 if i < remaining_jobs else 0)
57
 
58
+ for j in range(jobs_for_this_category):
59
+ template = templates[j % len(templates)]
60
+ title_variations = [
61
+ template["title"],
62
+ f"Senior {template['title']}",
63
+ f"Junior {template['title']}",
64
+ f"Lead {template['title']}",
65
+ f"{template['title']} Specialist"
66
+ ]
67
+ title = title_variations[j % len(title_variations)]
68
+ exp_level = random.choice(experience_levels)
69
+ salary = random.choice(salary_ranges[exp_level])
70
+ base_skills = template["skills"].copy()
71
+ extra_skills = random.sample(additional_skills[category],
72
+ random.randint(1, min(3, len(additional_skills[category]))))
73
+ all_skills = base_skills + extra_skills
74
+ unique_skills = list(dict.fromkeys(all_skills))[:8]
75
 
76
+ job = {
77
+ "id": job_id,
78
+ "title": title,
79
+ "description": template["desc"],
80
+ "requirements": unique_skills,
81
+ "experience_level": exp_level,
82
+ "salary_range": salary,
83
+ "category": category,
84
+ "location": random.choice([
85
+ "Remote", "New York, NY", "San Francisco, CA", "Chicago, IL",
86
+ "Austin, TX", "Seattle, WA", "Boston, MA", "Los Angeles, CA",
87
+ "Denver, CO", "Atlanta, GA", "Miami, FL", "Portland, OR"
88
+ ])
89
+ }
90
+ jobs.append(job)
91
+ job_id += 1
92
+ return jobs
93
 
94
+ # -----------------------------
95
+ # Job Matching Function
96
+ # -----------------------------
97
+ def match_jobs_embeddings(user_skills: List[str], db: JobDatabase, top_n=5):
98
+ # Convert user input into single string
99
+ skills_text = ", ".join([s.strip() for s in user_skills if s.strip()])
100
+ if not skills_text:
101
+ return pd.DataFrame([{"title":"No skills entered","description":"","requirements":"","experience_level":"","salary_range":"","location":""}])
102
+
103
+ # Encode user skills
104
+ user_embedding = db.model.encode(skills_text, convert_to_tensor=True)
105
+ # Compute cosine similarity
106
+ cos_scores = util.cos_sim(user_embedding, db.job_embeddings)[0]
107
+ # Get top N matches
108
+ top_results = cos_scores.topk(top_n)
109
+ indices = top_results.indices.tolist()
110
+
111
+ matched_jobs = db.df_jobs.iloc[indices]
112
+ return matched_jobs[['title', 'description', 'requirements', 'experience_level', 'salary_range', 'location']]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
+ # -----------------------------
115
+ # Gradio Interface
116
+ # -----------------------------
117
+ db = JobDatabase()
118
 
119
+ def find_jobs_ui(user_skills_text):
120
+ user_skills = [skill.strip() for skill in user_skills_text.split(",")]
121
+ return match_jobs_embeddings(user_skills, db)
 
122
 
123
+ iface = gr.Interface(
124
+ fn=find_jobs_ui,
125
+ inputs=gr.Textbox(lines=2, placeholder="Enter skills separated by commas, e.g. Python, SQL, Excel"),
126
+ outputs=gr.Dataframe(headers=["Title","Description","Requirements","Experience Level","Salary","Location"]),
127
+ title="Job Finder with AI Embeddings",
128
+ description="Enter your skills and get top matching jobs using AI embeddings."
129
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
 
131
  if __name__ == "__main__":
132
+ iface.launch()