File size: 19,717 Bytes
96a706d |
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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 |
"""
HRHUB V2.1 - Company View
Dynamic company-to-candidate matching interface
"""
import streamlit as st
import sys
from pathlib import Path
import re
# Add parent directory to path for imports
parent_dir = Path(__file__).parent.parent
sys.path.append(str(parent_dir))
from config import *
from data.data_loader import (
load_embeddings,
# find_top_matches_company # Function doesn't exist yet - using embedded version below
)
from utils.display import (
display_company_profile_basic,
display_candidate_card_basic,
display_match_table_candidates,
display_stats_overview_company
)
from utils.visualization import create_network_graph
from utils.viz_heatmap import render_skills_heatmap_section
from utils.viz_bilateral import render_bilateral_fairness_section # NEW IMPORT
import streamlit.components.v1 as components
import numpy as np
def configure_page():
"""Configure Streamlit page settings and custom CSS."""
st.set_page_config(
page_title="HRHUB - Company View",
page_icon="π’",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS
st.markdown("""
<style>
/* Main title styling */
.main-title {
font-size: 2.5rem;
font-weight: bold;
text-align: center;
color: #667eea;
margin-bottom: 0;
}
.sub-title {
font-size: 1rem;
text-align: center;
color: #666;
margin-top: 0;
margin-bottom: 1.5rem;
}
/* Section headers */
.section-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 12px;
border-radius: 8px;
margin: 15px 0;
font-size: 1.3rem;
font-weight: bold;
}
/* Info boxes */
.info-box {
background-color: #FFF4E6;
border-left: 5px solid #FF9800;
padding: 12px;
border-radius: 5px;
margin: 10px 0;
}
/* Success box */
.success-box {
background-color: #D4EDDA;
border-left: 5px solid #28A745;
padding: 12px;
border-radius: 5px;
margin: 10px 0;
color: #155724;
}
/* Warning box */
.warning-box {
background-color: #FFF3CD;
border-left: 5px solid #FFC107;
padding: 12px;
border-radius: 5px;
margin: 10px 0;
color: #856404;
}
/* Metric cards */
div[data-testid="metric-container"] {
background-color: #F8F9FA;
border: 2px solid #E0E0E0;
padding: 12px;
border-radius: 8px;
}
/* Expander styling */
.streamlit-expanderHeader {
background-color: #F0F2F6;
border-radius: 5px;
}
/* Hide Streamlit branding */
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
/* Input field styling */
.stTextInput > div > div > input {
font-size: 1.1rem;
font-weight: 600;
}
</style>
""", unsafe_allow_html=True)
def validate_company_input(input_str):
"""
Validate company input (ID or search term).
Returns: (is_valid, company_id, error_message)
"""
if not input_str:
return False, None, "Please enter a company ID or name"
input_clean = input_str.strip()
# Check if it's a numeric ID
if input_clean.isdigit():
company_id = int(input_clean)
return True, company_id, None
# Otherwise treat as search term (we'll search by name)
return True, input_clean, None
def find_company_by_name(companies_df, search_term):
"""
Find company by name (case-insensitive partial match).
Returns: (found, company_id, company_name)
"""
search_lower = search_term.lower()
# Search in company names
if 'name' in companies_df.columns:
matches = companies_df[companies_df['name'].str.lower().str.contains(search_lower, na=False)]
if len(matches) > 0:
# Return first match
company_id = matches.index[0]
company_name = matches.iloc[0]['name']
return True, company_id, company_name
return False, None, None
def find_top_candidate_matches(company_id, company_embeddings, candidate_embeddings, candidates_df, top_k=10):
"""
Find top candidate matches for a company (reverse of candidate matching).
"""
# Get company embedding
company_emb = company_embeddings[company_id].reshape(1, -1)
# Calculate cosine similarity with all candidates
# Normalize embeddings
company_norm = company_emb / np.linalg.norm(company_emb)
candidate_norms = candidate_embeddings / np.linalg.norm(candidate_embeddings, axis=1, keepdims=True)
# Compute similarities
similarities = np.dot(candidate_norms, company_norm.T).flatten()
# Get top K indices
top_indices = np.argsort(similarities)[::-1][:top_k]
# Format results
matches = []
for idx in top_indices:
matches.append({
'candidate_id': int(idx),
'score': float(similarities[idx])
})
return matches
def render_sidebar():
"""Render sidebar with controls and information."""
with st.sidebar:
# Logo/Title
st.markdown("### π’ Company Matching")
st.markdown("---")
# Settings section
st.markdown("### βοΈ Settings")
# Number of matches
top_k = st.slider(
"Number of Matches",
min_value=5,
max_value=20,
value=DEFAULT_TOP_K,
step=5,
help="Select how many top candidates to display"
)
# Minimum score threshold
min_score = st.slider(
"Minimum Match Score",
min_value=0.0,
max_value=1.0,
value=MIN_SIMILARITY_SCORE,
step=0.05,
help="Filter candidates below this similarity score"
)
st.markdown("---")
# View mode selection
st.markdown("### π View Mode")
view_mode = st.radio(
"Select view:",
["π Overview", "π Detailed Cards", "π Table View"],
help="Choose how to display candidate matches"
)
st.markdown("---")
# Information section
with st.expander("βΉοΈ About", expanded=False):
st.markdown("""
**Company View** helps you discover top talent based on:
- π€ **NLP Embeddings**: 384-dimensional semantic space
- π **Cosine Similarity**: Scale-invariant matching
- π **Job Postings Bridge**: Vocabulary alignment
**How it works:**
1. Enter company ID or search by name
2. System finds top candidate matches
3. Explore candidates with scores and skills
4. Visualize talent network via graph
""")
with st.expander("π Input Format", expanded=False):
st.markdown("""
**Valid formats:**
- `9418` β Company ID 9418
- `30989` β Company ID 30989
- `Anblicks` β Search by name
- `iO Associates` β Partial name search
**Search tips:**
- Case-insensitive
- Partial matches work
- Returns first match found
""")
with st.expander("π Coverage Info", expanded=False):
st.markdown("""
**Company Coverage:**
- π’ **30,000 companies** with job postings
- π‘ **120,000 companies** via collaborative filtering
- π **5x coverage expansion** through skill inference
Companies without job postings inherit skills from similar companies.
""")
st.markdown("---")
# Back to home button
if st.button("π Back to Home", use_container_width=True):
st.switch_page("app.py")
# Version info
st.caption(f"Version: {VERSION}")
st.caption("Β© 2024 HRHUB Team")
return top_k, min_score, view_mode
def get_network_graph_data_company(company_id, matches, companies_df):
"""Generate network graph data from matches (company perspective)."""
nodes = []
edges = []
# Add company node (red/orange)
company_name = companies_df.iloc[company_id].get('name', f'Company {company_id}')
if len(company_name) > 30:
company_name = company_name[:27] + '...'
nodes.append({
'id': f'COMP{company_id}',
'label': company_name,
'color': '#ff6b6b',
'shape': 'box',
'size': 30
})
# Add candidate nodes (green) and edges
for cand_id, score, cand_data in matches:
nodes.append({
'id': f'C{cand_id}',
'label': f'Candidate #{cand_id}',
'color': '#4ade80',
'shape': 'dot',
'size': 20
})
edges.append({
'from': f'COMP{company_id}',
'to': f'C{cand_id}',
'value': float(score) * 10,
'title': f'Match Score: {score:.3f}'
})
return {'nodes': nodes, 'edges': edges}
def render_network_section(company_id: int, matches, companies_df):
"""Render interactive network visualization section."""
st.markdown('<div class="section-header">πΈοΈ Talent Network</div>', unsafe_allow_html=True)
# Explanation box
st.markdown("""
<div class="info-box">
<strong>π‘ What this shows:</strong> Talent network reveals skill alignment and candidate clustering.
Thicker edges indicate stronger semantic match between company requirements and candidate skills.
</div>
""", unsafe_allow_html=True)
with st.spinner("Generating interactive network graph..."):
# Get graph data
graph_data = get_network_graph_data_company(company_id, matches, companies_df)
# Create HTML graph
html_content = create_network_graph(
nodes=graph_data['nodes'],
edges=graph_data['edges'],
height="600px"
)
# Display in Streamlit
components.html(html_content, height=620, scrolling=False)
# Graph instructions
with st.expander("π Graph Controls", expanded=False):
st.markdown("""
**How to interact:**
- π±οΈ **Drag nodes**: Click and drag to reposition
- π **Zoom**: Scroll to zoom in/out
- π **Pan**: Click background and drag to pan
- π― **Hover**: Hover over nodes/edges for details
**Legend:**
- π΄ **Red square**: Your company
- π’ **Green circles**: Matched candidates
- **Line thickness**: Match strength (thicker = better)
""")
def render_matches_section(matches, view_mode: str):
"""Render candidate matches section with different view modes."""
st.markdown('<div class="section-header">π― Candidate Matches</div>', unsafe_allow_html=True)
if view_mode == "π Overview" or view_mode == "π Table View":
# Table view - use display function
display_match_table_candidates(matches)
elif view_mode == "π Detailed Cards":
# Card view - use display function
for rank, (cand_id, score, cand_data) in enumerate(matches, 1):
display_candidate_card_basic(cand_data, cand_id, score, rank)
def main():
"""Main application entry point."""
# Configure page
configure_page()
# Render header
st.markdown('<h1 class="main-title">π’ Company View</h1>', unsafe_allow_html=True)
st.markdown('<p class="sub-title">Discover top talent for your company</p>', unsafe_allow_html=True)
# Render sidebar and get settings
top_k, min_score, view_mode = render_sidebar()
st.markdown("---")
# Load embeddings (cache in session state)
if 'embeddings_loaded' not in st.session_state:
with st.spinner("π Loading embeddings and data..."):
try:
cand_emb, comp_emb, cand_df, comp_df = load_embeddings()
st.session_state.embeddings_loaded = True
st.session_state.candidate_embeddings = cand_emb
st.session_state.company_embeddings = comp_emb
st.session_state.candidates_df = cand_df
st.session_state.companies_df = comp_df
st.markdown("""
<div class="success-box">
β
Data loaded successfully! Ready to find talent.
</div>
""", unsafe_allow_html=True)
except Exception as e:
st.error(f"β Error loading data: {str(e)}")
st.stop()
# Company input section
st.markdown("### π Enter Company ID or Name")
col1, col2 = st.columns([3, 1])
with col1:
company_input = st.text_input(
"Company ID or Name",
value="9418",
max_chars=100,
help="Enter company ID (e.g., 9418) or search by name (e.g., Anblicks)",
label_visibility="collapsed"
)
with col2:
search_button = st.button("π Find Candidates", use_container_width=True, type="primary")
# Validate input
is_valid, company_id_or_search, error_msg = validate_company_input(company_input)
if not is_valid:
st.warning(f"β οΈ {error_msg}")
st.stop()
# Determine if it's ID or search
if isinstance(company_id_or_search, int):
# Direct ID
company_id = company_id_or_search
# Check if company exists
if company_id >= len(st.session_state.companies_df):
st.error(f"β Company ID {company_id} not found. Maximum ID: {len(st.session_state.companies_df) - 1}")
st.stop()
company = st.session_state.companies_df.iloc[company_id]
company_name = company.get('name', f'Company {company_id}')
else:
# Search by name
found, company_id, company_name = find_company_by_name(st.session_state.companies_df, company_id_or_search)
if not found:
st.error(f"β No company found matching: '{company_id_or_search}'")
st.info("π‘ **Tip:** Try searching with partial name or use company ID directly")
st.stop()
company = st.session_state.companies_df.iloc[company_id]
st.success(f"β
Found: **{company_name}** (ID: {company_id})")
# Show company info
st.markdown(f"""
<div class="info-box">
<strong>Selected:</strong> {company_name} (ID: {company_id}) |
<strong>Total companies in system:</strong> {len(st.session_state.companies_df):,}
</div>
""", unsafe_allow_html=True)
# Check if company has job postings
has_postings = company.get('has_job_postings', False) if 'has_job_postings' in company else True
if not has_postings:
st.markdown("""
<div class="warning-box">
βΉοΈ <strong>Note:</strong> This company uses <strong>collaborative filtering</strong>
(skills inherited from similar companies). Matching still works but may be less precise than companies with direct job postings.
</div>
""", unsafe_allow_html=True)
# Find matches
with st.spinner("π Finding top candidate matches..."):
matches_list = find_top_candidate_matches(
company_id,
st.session_state.company_embeddings,
st.session_state.candidate_embeddings,
st.session_state.candidates_df,
top_k
)
# Format matches for display
matches = [
(m['candidate_id'], m['score'], st.session_state.candidates_df.iloc[m['candidate_id']])
for m in matches_list
]
# Filter by minimum score
matches = [(cid, score, cdata) for cid, score, cdata in matches if score >= min_score]
if not matches:
st.warning(f"β οΈ No candidates found above {min_score:.0%} threshold. Try lowering the minimum score in the sidebar.")
st.stop()
st.markdown("---")
# Display statistics using display function
display_stats_overview_company(company, matches)
st.markdown("---")
# Create two columns for layout
col1, col2 = st.columns([1, 2])
with col1:
# Company profile section
st.markdown('<div class="section-header">π’ Company Profile</div>', unsafe_allow_html=True)
# Use basic display function
display_company_profile_basic(company, company_id)
with col2:
# Matches section
render_matches_section(matches, view_mode)
st.markdown("---")
# Skills Heatmap (show for top candidate match)
if len(matches) > 0:
top_cand_id, top_cand_score, top_cand_data = matches[0]
st.markdown("### π₯ Skills Analysis - Top Candidate")
render_skills_heatmap_section(
top_cand_data,
company,
st.session_state.candidate_embeddings[top_cand_id],
st.session_state.company_embeddings[company_id],
top_cand_score
)
st.markdown("---")
# Network visualization (full width)
render_network_section(company_id, matches, st.session_state.companies_df)
st.markdown("---")
# BILATERAL FAIRNESS PROOF SECTION - NEW
render_bilateral_fairness_section(
st.session_state.candidate_embeddings,
st.session_state.company_embeddings
)
st.markdown("---")
# Technical info expander
with st.expander("π§ Technical Details", expanded=False):
st.markdown(f"""
**Current Configuration:**
- Company ID: {company_id}
- Company Name: {company_name}
- Embedding Dimension: {EMBEDDING_DIMENSION}
- Similarity Metric: Cosine Similarity
- Top K Matches: {top_k}
- Minimum Score: {min_score:.0%}
- Candidates Available: {len(st.session_state.candidates_df):,}
- Companies in System: {len(st.session_state.companies_df):,}
**Algorithm:**
1. Load pre-computed company embedding
2. Calculate cosine similarity with all candidate embeddings
3. Rank candidates by similarity score
4. Return top-K matches above threshold
**Coverage Strategy:**
- Companies WITH job postings: Direct semantic matching
- Companies WITHOUT postings: Collaborative filtering (inherit from similar companies)
- Total coverage: 150K companies (5x expansion from 30K base)
""")
if __name__ == "__main__":
main() |