Spaces:
Sleeping
Sleeping
Update app.py
Browse files22 unmodified lines232425262728294 unmodified lines3435363738394041422 unmodified lines45464748495051525354555657585960616263646566676869707172737475767778798081828384858687888916 unmodified lines1061071081091101111121131141151161171181191201211221234 unmodified lines1281291301311321331341351361371381391403 unmodified lines1441451461471481491509 unmodified lines1601611621631641651661671681691707 unmodified lines17817918018118218318418518618718818919019119222 unmodified linesdf['clean_salary'] = df['Salary'].apply(clean_salary)# Combine title and description for better clusteringdf['combined_text'] = df['Title'] + ' ' + df['Description']return dfexcept Exception as e:st.error(f"Error loading data: {str(e)}")4 unmodified lines# Create TF-IDF vectors from combined textvectorizer = TfidfVectorizer(stop_words='english',max_features=1000, # Limit features to most common termsngram_range=(1, 2) # Include both unigrams and bigrams)tfidf_matrix = vectorizer.fit_transform(df['combined_text'])# Perform K-means clustering2 unmodified linesrandom_state=42,n_init=10)df['cluster'] = kmeans.fit_predict(tfidf_matrix)# Get the most common terms in each clusterfeature_names = vectorizer.get_feature_names_out()cluster_centers = kmeans.cluster_centers_# Get top terms for each clustercluster_terms = {}for i in range(num_clusters):top_indices = cluster_centers[i].argsort()[-5:][::-1] # Get top 5 termstop_terms = [feature_names[j] for j in top_indices]cluster_terms[i] = top_termsreturn vectorizer, kmeans, cluster_termsdef find_matching_jobs(df, job_title, location, min_salary, keywords, vectorizer, kmeans):"""Find matching jobs using K-means clustering."""# Prepare search querysearch_query = job_title + ' ' + (keywords if keywords else '')# Transform search query using the same vectorizerquery_vector = vectorizer.transform([search_query])# Predict cluster for the search queryquery_cluster = kmeans.predict(query_vector)[0]# Get jobs from the same clustermatches = df[df['cluster'] == query_cluster].copy()# Apply additional filtersif location:matches = matches[matches['Location'].str.contains(location, case=False, na=False)]if min_salary > 0:matches = matches[matches['clean_salary'] >= min_salary]if keywords:for keyword in keywords.split(','):keyword = keyword.strip()if keyword:matches = matches[matches['Description'].str.contains(keyword, case=False, na=False)]return matches16 unmodified linesif 'filtered_jobs' not in st.session_state:st.session_state.filtered_jobs = pd.DataFrame()# Create clusters and store cluster informationnum_clusters = st.sidebar.slider("Number of Clusters (K):", 5, 20, 10)vectorizer, kmeans, cluster_terms = create_job_clusters(jobs_df, num_clusters)# Show cluster informationif st.checkbox("Show Cluster Information"):st.subheader("Cluster Analysis")for cluster_id, terms in cluster_terms.items():st.write(f"Cluster {cluster_id} top terms: {', '.join(terms)}")cluster_size = len(jobs_df[jobs_df['cluster'] == cluster_id])st.write(f"Number of jobs in cluster: {cluster_size}")st.write("---")# Sidebar filterswith st.sidebar:4 unmodified lineslocation = st.text_input("Location:", "")min_salary = st.slider("Minimum Salary:", 0, 300000, 50000, step=5000)st.subheader("Keywords")keywords = st.text_area("Enter keywords (comma-separated):",placeholder="e.g., Python, SQL, machine learning",help="Enter keywords to find in job descriptions")search_button = st.form_submit_button("Search Jobs",use_container_width=True,3 unmodified linesif search_button:st.session_state.filtered_jobs = find_matching_jobs(jobs_df, job_title, location, min_salary, keywords,vectorizer, kmeans)st.session_state.search_performed = True9 unmodified linesif not filtered_jobs.empty:for index, row in filtered_jobs.iterrows():with st.expander(f"{row['Title']} - {row['Location']} (Cluster {row['cluster']})"):st.write(f"**Salary:** {row['Salary']}")st.write(f"**Cluster:** {row['cluster']}")st.write("**Top terms in this cluster:**",', '.join(cluster_terms[row['cluster']]))st.write("**Description:**")description = row['Description']7 unmodified linesst.write(description[:500] + "..." if len(description) > 500 else description)else:st.info("No matching jobs found. Try adjusting your filters.")else:st.info("Use the filters in the sidebar and click 'Search Jobs' to find matching positions.")# Statisticswith st.sidebar:st.header("Statistics")st.write(f"Total jobs in database: {len(jobs_df)}")st.write(f"Average salary: ${int(jobs_df['clean_salary'].mean()):,}")if __name__ == "__main__":main()22 unmodified lines232425262728294 unmodified lines34353637383940414243442 unmodified lines474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911016 unmodified lines1271281291301311321331341351364 unmodified lines1411421431441451461471481491501511521531541553 unmodified lines1591601611621631641659 unmodified lines1751761771781791801811821837 unmodified lines19119219319419519619719819920020120220320420522 unmodified linesdf['clean_salary'] = df['Salary'].apply(clean_salary)# Combine title and description for better clusteringdf['combined_text'] = df['Title'].str.lower() + ' ' + df['Description'].str.lower()return dfexcept Exception as e:st.error(f"Error loading data: {str(e)}")4 unmodified lines# Create TF-IDF vectors from combined textvectorizer = TfidfVectorizer(stop_words='english',max_features=1000,ngram_range=(1, 2))# Fit and transform the text datatfidf_matrix = vectorizer.fit_transform(df['combined_text'])# Perform K-means clustering2 unmodified linesrandom_state=42,n_init=10)clusters = kmeans.fit_predict(tfidf_matrix)return vectorizer, kmeans, clustersdef find_matching_jobs(df, job_title, location, min_salary, keywords, vectorizer, kmeans, debug=True):"""Find matching jobs using K-means clustering."""matches = df.copy()# Debug informationif debug:st.write("### Debug Information")st.write(f"Initial number of jobs: {len(matches)}")# Apply title filter if providedif job_title:matches = matches[matches['Title'].str.contains(job_title, case=False, na=False)]if debug:st.write(f"After title filter: {len(matches)} jobs")# Apply location filter if providedif location:matches = matches[matches['Location'].str.contains(location, case=False, na=False)]if debug:st.write(f"After location filter: {len(matches)} jobs")# Apply salary filterif min_salary > 0:matches = matches[matches['clean_salary'] >= min_salary]if debug:st.write(f"After salary filter: {len(matches)} jobs")# Apply keyword filter if providedif keywords:for keyword in keywords.split(','):keyword = keyword.strip()if keyword:matches = matches[matches['Description'].str.contains(keyword, case=False, na=False) |matches['Title'].str.contains(keyword, case=False, na=False)]if debug:st.write(f"After keyword '{keyword}' filter: {len(matches)} jobs")# Only use K-means if we have search termsif job_title or keywords:search_query = (job_title + ' ' + (keywords if keywords else '')).lower()query_vector = vectorizer.transform([search_query])query_cluster = kmeans.predict(query_vector)[0]# Get cluster assignment for all remaining jobsjob_vectors = vectorizer.transform(matches['combined_text'])matches['cluster'] = kmeans.predict(job_vectors)# Filter by clustermatches = matches[matches['cluster'] == query_cluster]if debug:st.write(f"After cluster filtering: {len(matches)} jobs")st.write(f"Query assigned to cluster: {query_cluster}")return matches16 unmodified linesif 'filtered_jobs' not in st.session_state:st.session_state.filtered_jobs = pd.DataFrame()# Create clustersnum_clusters = st.sidebar.slider("Number of Clusters (K):", 5, 20, 10)vectorizer, kmeans, clusters = create_job_clusters(jobs_df, num_clusters)jobs_df['cluster'] = clusters# Sidebar filterswith st.sidebar:4 unmodified lineslocation = st.text_input("Location:", "")min_salary = st.slider("Minimum Salary:", 0, 300000, 50000, step=5000)keywords = st.text_area("Keywords (comma-separated):",placeholder="e.g., Python, SQL, machine learning",help="Enter keywords to find in job descriptions")# Add debug mode checkboxdebug_mode = st.checkbox("Show debug information", value=True)search_button = st.form_submit_button("Search Jobs",use_container_width=True,3 unmodified linesif search_button:st.session_state.filtered_jobs = find_matching_jobs(jobs_df, job_title, location, min_salary, keywords,vectorizer, kmeans, debug=debug_mode)st.session_state.search_performed = True9 unmodified linesif not filtered_jobs.empty:for index, row in filtered_jobs.iterrows():with st.expander(f"{row['Title']} - {row['Location']}"):st.write(f"**Salary:** {row['Salary']}")st.write(f"**Cluster:** {row['cluster']}")st.write("**Description:**")description = row['Description']7 unmodified linesst.write(description[:500] + "..." if len(description) > 500 else description)else:st.warning("""No matching jobs found. Try:1. Using fewer filters2. Using more general keywords3. Reducing the minimum salary4. Checking different locations""")else:st.info("Use the filters in the sidebar and click 'Search Jobs' to find matching positions.")if __name__ == "__main__":main()
app.py+65-52