Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657582 unmodified linesfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.cluster import KMeansimport streamlit as st# Veri setini yükleme# Hugging Face URL'sini buraya yapıştırınurl = "https://huggingface.co/datasets/burcuonel/datajob_indeed_usa/raw/main/datajob_indeed_usa.csv"# Veri setini yüklejobs = pd.read_csv("https://huggingface.co/datasets/burcuonel/datajob_indeed_usa/raw/main/datajob_indeed_usa.csv")# İlgili sütunları seçmejobs = jobs[['Title', 'Location', 'Salary', 'Description']]jobs.dropna(subset=['Title', 'Location', 'Description'], inplace=True) # Boş değerleri çıkar# Streamlit uygulamasıst.title("Job Search Application")st.write("Filter and find jobs that match your preferences!")# Kullanıcıdan filtre kriterlerini almajob_title = st.text_input("Enter job title (e.g., Data Scientist):", "")location = st.text_input("Enter location (e.g., Remote, CA):", "")salary = st.slider("Minimum Salary (if available):", 0, 300000, 50000)# Text verilerini sayısallaştırmavectorizer = TfidfVectorizer(stop_words='english')tfidf_matrix = vectorizer.fit_transform(jobs['Description'])# K-Means ile kümelemenum_clusters = 5kmeans = KMeans(n_clusters=num_clusters, random_state=42)jobs['Cluster'] = kmeans.fit_predict(tfidf_matrix)# Kullanıcı girdilerine en yakın kümenin belirlenmesiuser_input = f"{job_title} {location}"user_vector = vectorizer.transform([user_input])user_cluster = kmeans.predict(user_vector)[0]# Sonuçları filtrelemefiltered_jobs = jobs[jobs['Cluster'] == user_cluster]filtered_jobs = filtered_jobs[filtered_jobs['Salary'].str.contains("\d", na=False)] # Maaş bilgisi olanları seçfiltered_jobs = filtered_jobs[filtered_jobs['Salary'].apply(lambda x: int(''.join(filter(str.isdigit, x.split('-')[0]))) >= salary if '-' in x else False)]# Sonuçları göstermest.subheader("Top Matching Jobs")if not filtered_jobs.empty:for index, row in filtered_jobs.iterrows():st.write(f"### {row['Title']}")st.write(f"**Location:** {row['Location']}")st.write(f"**Salary:** {row['Salary']}")st.write(f"**Description:** {row['Description'][:200]}...") # İlk 200 karakterst.write("---")else:st.write("No matching jobs found. Try adjusting your filters.")2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911922 unmodified linesfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.cluster import KMeansimport streamlit as stimport 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."""try:df = 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'] + ' ' + df['Description']return dfexcept Exception as e:st.error(f"Error loading data: {str(e)}")return Nonedef create_job_clusters(df, num_clusters=10):"""Create job clusters using TF-IDF and K-means."""# 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 clusteringkmeans = KMeans(n_clusters=num_clusters,random_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 matchesdef main():st.set_page_config(page_title="K-means Job Clustering Search", layout="wide")st.title("Job Search with K-means Clustering")st.write("Find jobs using K-means clustering algorithm!")# 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()# 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: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)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,type="primary")if 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 = 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']} (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']# Highlight keywordsif keywords:keyword_list = [k.strip() for k in keywords.split(',')]for keyword in keyword_list:if 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.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()
app.py+181-47