Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines67891011121314151617181 unmodified line20212223242526274 unmodified lines3233343536373839404142434445464748495051525354555 unmodified lines616263646566676869707172732 unmodified lines7677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731 unmodified line1751761771781791801817 unmodified lines1891901911925 unmodified linesimport redef clean_salary(salary_str):"""Extract and clean salary information."""if pd.isna(salary_str):return 0numbers = re.findall(r'\d+', str(salary_str))if not numbers:return 0return int(numbers[0])def load_and_preprocess_data(url):"""Load and preprocess the dataset."""1 unmodified linedf = pd.read_csv(url)df = df[['Title', 'Location', 'Salary', 'Description']]df.dropna(subset=['Title', 'Location', 'Description'], inplace=True)df['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 df4 unmodified linesdef find_matching_jobs(df, job_title, location, min_salary, keywords, debug=True):"""Find matching jobs using simple filtering first."""matches = df.copy()# Debug informationif debug:st.write("### Debug Information")st.write(f"Initial number of jobs: {len(matches)}")# 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(','):5 unmodified lines]if debug:st.write(f"After keyword '{keyword}' filter: {len(matches)} jobs")# Check if we have any matches before applying K-meansif len(matches) == 0:if debug:st.warning("No jobs match the basic filters. Try relaxing your search criteria.")return matches# Only apply title and K-means clustering if we have matchesif job_title:# Create TF-IDF vectors2 unmodified linesmax_features=1000,ngram_range=(1, 2))# Fit vectorizer on the remaining matchestfidf_matrix = vectorizer.fit_transform(matches['combined_text'])# Create clustersnum_clusters = min(5, len(matches)) # Adjust number of clusters based on matcheskmeans = KMeans(n_clusters=num_clusters, random_state=42, n_init=10)clusters = kmeans.fit_predict(tfidf_matrix)# Transform search querysearch_query = job_title.lower()query_vector = vectorizer.transform([search_query])query_cluster = kmeans.predict(query_vector)[0]# Assign clusters and filtermatches['cluster'] = clustersmatches = matches[matches['cluster'] == query_cluster]if debug:st.write(f"After clustering filter: {len(matches)} jobs")st.write(f"Query assigned to cluster: {query_cluster}")return matchesdef main():st.set_page_config(page_title="Job Search Application", layout="wide")st.title("Job Search Application")st.write("Find jobs that match your preferences!")# Load dataurl = "https://huggingface.co/datasets/burcuonel/datajob_indeed_usa/raw/main/datajob_indeed_usa.csv"jobs_df = load_and_preprocess_data(url)if jobs_df is None:return# Initialize session stateif 'search_performed' not in st.session_state:st.session_state.search_performed = Falseif 'filtered_jobs' not in st.session_state:st.session_state.filtered_jobs = pd.DataFrame()# Sidebar filterswith st.sidebar:st.header("Search Filters")with st.form(key='search_form'):job_title = st.text_input("Job Title:", "")location = 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,type="primary")if search_button:st.session_state.filtered_jobs = find_matching_jobs(jobs_df, job_title, location, min_salary, keywords, debug=debug_mode)st.session_state.search_performed = Trueif st.button("Reset Filters", use_container_width=True):st.session_state.search_performed = Falsest.session_state.filtered_jobs = pd.DataFrame()st.rerun()# Display resultsif st.session_state.search_performed:filtered_jobs = st.session_state.filtered_jobsst.subheader(f"Found {len(filtered_jobs)} Matching Jobs")if 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']}")if 'cluster' in row:st.write(f"**Cluster:** {row['cluster']}")st.write("**Description:**")description = row['Description']# Highlight keywordsif keywords:keyword_list = [k.strip() for k in keywords.split(',')]1 unmodified lineif keyword:pattern = re.compile(f'({re.escape(keyword)})', re.IGNORECASE)description = pattern.sub(r'**\1**', description)st.write(description[:500] + "..." if len(description) > 500 else description)else:st.warning("""7 unmodified linesst.info("Use the filters in the sidebar and click 'Search Jobs' to find matching positions.")if __name__ == "__main__":main()5 unmodified lines67891011121314151617181920212223242526271 unmodified line293031323334353637384 unmodified lines4344454647484950515253545556575859606162636465665 unmodified lines727374757677787980818283842 unmodified lines878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851 unmodified line1871881891901911921937 unmodified lines2012022032045 unmodified linesimport redef clean_salary(salary_str):"""Extract and clean salary information, including ranges."""if pd.isna(salary_str):return 0# Handle ranges like "150000-200000"range_match = re.match(r'(\d+)[^\d]+(\d+)', str(salary_str))if range_match:low, high = map(int, range_match.groups())return (low + high) // 2 # Return average of range# Extract single salary valuenumbers = re.findall(r'\d+', str(salary_str))if numbers:return int(numbers[0])return 0def load_and_preprocess_data(url):"""Load and preprocess the dataset."""1 unmodified linedf = pd.read_csv(url)df = df[['Title', 'Location', 'Salary', 'Description']]df.dropna(subset=['Title', 'Location', 'Description'], inplace=True)# Clean salary columndf['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 df4 unmodified linesdef find_matching_jobs(df, job_title, location, min_salary, keywords, debug=True):"""Find matching jobs using simple filtering first."""matches = df.copy()# Debug informationif debug:st.write("### Debug Information")st.write(f"Initial number of jobs: {len(matches)}")# 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(','):5 unmodified lines]if debug:st.write(f"After keyword '{keyword}' filter: {len(matches)} jobs")# Check if we have any matches before applying K-meansif len(matches) == 0:if debug:st.warning("No jobs match the basic filters. Try relaxing your search criteria.")return matches# Only apply title and K-means clustering if we have matchesif job_title:# Create TF-IDF vectors2 unmodified linesmax_features=1000,ngram_range=(1, 2))# Fit vectorizer on the remaining matchestfidf_matrix = vectorizer.fit_transform(matches['combined_text'])# Create clustersnum_clusters = min(5, len(matches)) # Adjust number of clusters based on matcheskmeans = KMeans(n_clusters=num_clusters, random_state=42, n_init=10)clusters = kmeans.fit_predict(tfidf_matrix)# Transform search querysearch_query = job_title.lower()query_vector = vectorizer.transform([search_query])query_cluster = kmeans.predict(query_vector)[0]# Assign clusters and filtermatches['cluster'] = clustersmatches = matches[matches['cluster'] == query_cluster]if debug:st.write(f"After clustering filter: {len(matches)} jobs")st.write(f"Query assigned to cluster: {query_cluster}")return matchesdef main():st.set_page_config(page_title="Job Search Application", layout="wide")st.title("Job Search Application")st.write("Find jobs that match your preferences!")# Load dataurl = "https://huggingface.co/datasets/burcuonel/datajob_indeed_usa/raw/main/datajob_indeed_usa.csv"jobs_df = load_and_preprocess_data(url)if jobs_df is None:return# Initialize session stateif 'search_performed' not in st.session_state:st.session_state.search_performed = Falseif 'filtered_jobs' not in st.session_state:st.session_state.filtered_jobs = pd.DataFrame()# Sidebar filterswith st.sidebar:st.header("Search Filters")with st.form(key='search_form'):job_title = st.text_input("Job Title:", "")location = 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,type="primary")if search_button:st.session_state.filtered_jobs = find_matching_jobs(jobs_df, job_title, location, min_salary, keywords, debug=debug_mode)st.session_state.search_performed = Trueif st.button("Reset Filters", use_container_width=True):st.session_state.search_performed = Falsest.session_state.filtered_jobs = pd.DataFrame()st.rerun()# Display resultsif st.session_state.search_performed:filtered_jobs = st.session_state.filtered_jobsst.subheader(f"Found {len(filtered_jobs)} Matching Jobs")if 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"**Cleaned Salary:** {row['clean_salary']}")if 'cluster' in row:st.write(f"**Cluster:** {row['cluster']}")st.write("**Description:**")description = row['Description']# Highlight keywordsif keywords:keyword_list = [k.strip() for k in keywords.split(',')]1 unmodified lineif keyword:pattern = re.compile(f'({re.escape(keyword)})', re.IGNORECASE)description = pattern.sub(r'**\1**', description)st.write(description[:500] + "..." if len(description) > 500 else description)else:st.warning("""7 unmodified linesst.info("Use the filters in the sidebar and click 'Search Jobs' to find matching positions.")if __name__ == "__main__":main()
app.py+45-33