Spaces:
Running
Running
File size: 12,643 Bytes
d075a5b | 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 | """
Candidate source APIs - compute metrics from actual data.
AUTO-GENERATED by scripts/generate_hf.sh - DO NOT EDIT DIRECTLY
Edit candidate_source.py in main repo and regenerate.
"""
from typing import Dict, List, Any, Optional, Union
import pandas as pd
from loguru import logger
from data_loader import get_data_loader
from models import (
RequisitionNotFoundResponse,
SLAPerSourceResponse,
TotalHiresBySourceResponse,
CandidateVolumeResponse,
FunnelConversionResponse,
MetadataResponse,
DefinitionsResponse,
SourceRecommendationResponse,
)
BPO_LOG_API_CALLS = False # Disabled for deployment
def _log_api_call(msg: str) -> None:
"""Log API call if BPO_LOG_API_CALLS is enabled."""
if BPO_LOG_API_CALLS:
logger.info(msg)
def _check_requisition_valid(requisition_id: str) -> Optional[RequisitionNotFoundResponse]:
"""
Check if a requisition ID is valid. Returns None if valid,
or an error response model if invalid.
"""
loader = get_data_loader()
if not loader.is_valid_requisition(requisition_id):
suggestions = loader.get_suggested_requisitions(requisition_id)
return RequisitionNotFoundResponse(
error="requisition_not_found",
message=f"No job can be found with the ID {requisition_id}.",
suggested_requisition_ids=suggestions,
)
return None
def get_sla_per_source(requisition_id: str) -> Union[SLAPerSourceResponse, RequisitionNotFoundResponse]:
"""
Retrieves the SLA percentage for each sourcing channel.
Args:
requisition_id: The specific requisition ID to filter SLA data for.
Returns:
A dictionary with source names and their SLA percentages.
"""
_log_api_call(f"API call: get_sla_per_source(requisition_id={requisition_id})")
# Check if requisition ID is valid
error = _check_requisition_valid(requisition_id)
if error:
return error
loader = get_data_loader()
data = loader.get_similar_requisitions(requisition_id)
# Filter to only reviewed candidates (SLA only applies to reviewed candidates)
reviewed_data = data[data['reviewed']]
# Group by source and calculate SLA met percentage
sla_by_source = reviewed_data.groupby('source_name').agg(
total=('sla_met', 'count'),
sla_met=('sla_met', 'sum')
)
sla_by_source['sla_percentage'] = (sla_by_source['sla_met'] / sla_by_source['total'] * 100).round(0).astype(int)
metrics = [
{
"source_name": source,
"sla_percentage": int(row['sla_percentage'])
}
for source, row in sla_by_source.iterrows()
]
# Sort by SLA percentage (ascending) for consistency
metrics.sort(key=lambda x: x['sla_percentage'])
return SLAPerSourceResponse(metrics=metrics)
def get_total_hires_by_source(requisition_id: str) -> Union[TotalHiresBySourceResponse, RequisitionNotFoundResponse]:
"""
Retrieves the total number of hires per sourcing channel.
Args:
requisition_id: The specific requisition ID to filter hiring data for.
Returns:
A dictionary with source names and total hires.
"""
_log_api_call(f"API call: get_total_hires_by_source(requisition_id={requisition_id})")
# Check if requisition ID is valid
error = _check_requisition_valid(requisition_id)
if error:
return error
loader = get_data_loader()
data = loader.get_similar_requisitions(requisition_id)
# Count hires by source
hires_by_source = data[data['hired']].groupby('source_name').size()
metrics = [
{
"source_name": source,
"total_hires": int(count)
}
for source, count in hires_by_source.items()
]
# Sort by total hires (descending)
metrics.sort(key=lambda x: x['total_hires'], reverse=True)
total_hires = int(data['hired'].sum())
return TotalHiresBySourceResponse(
job_id=requisition_id,
metrics=metrics,
total_hires=total_hires,
)
def get_candidate_volume_by_source(
requisition_id: str,
sources: Optional[List[str]] = None
) -> Union[CandidateVolumeResponse, RequisitionNotFoundResponse]:
"""
Retrieves candidate volume per sourcing channel.
Args:
requisition_id: The specific requisition ID to filter candidate volume.
sources: Optional subset of sourcing channels to include (case-sensitive).
Returns:
A dictionary with source names and candidate volumes.
"""
_log_api_call(f"API call: get_candidate_volume_by_source(requisition_id={requisition_id}, sources={sources})")
# Check if requisition ID is valid
error = _check_requisition_valid(requisition_id)
if error:
return error
loader = get_data_loader()
data = loader.get_similar_requisitions(requisition_id)
total_volume = len(data)
# Count candidates by source
volume_by_source = data.groupby('source_name').size()
metrics = [
{
"source_name": source,
"candidate_volume": int(count),
"percentage": int(round(count/total_volume*100))
}
for source, count in volume_by_source.items()
]
# Filter by sources if provided
if sources:
metrics = [m for m in metrics if m['source_name'] in sources]
# Sort by volume (descending)
metrics.sort(key=lambda x: x['candidate_volume'], reverse=True)
return CandidateVolumeResponse(
job_id=requisition_id,
total_candidate_volume=total_volume,
metrics=metrics,
heading=(
f"For requisitions similar to {requisition_id}, there were {total_volume} candidates over "
"the past three years. Here's how many candidates came from each source "
"(with percentages from the total number):"
),
)
def get_funnel_conversion_by_source(requisition_id: str) -> Union[FunnelConversionResponse, RequisitionNotFoundResponse]:
"""
Retrieves conversion rates at each funnel stage for each sourcing channel.
Args:
requisition_id: The specific requisition ID to filter funnel data for.
Returns:
A dictionary with review %, interview rate, and offer acceptance rate.
"""
_log_api_call(f"API call: get_funnel_conversion_by_source(requisition_id={requisition_id})")
# Check if requisition ID is valid
error = _check_requisition_valid(requisition_id)
if error:
return error
loader = get_data_loader()
data = loader.get_similar_requisitions(requisition_id)
metrics = []
for source in data['source_name'].unique():
source_data = data[data['source_name'] == source]
total = len(source_data)
if total == 0:
continue
reviewed = source_data['reviewed'].sum()
interviewed = source_data['interviewed'].sum()
offered = source_data['offer_extended'].sum()
metrics.append({
"source_name": source,
"first_round_review_percentage": round(reviewed / total * 100, 1),
"interview_rate": round(interviewed / total * 100, 1),
"offer_acceptance_rate": round(offered / total * 100, 1),
})
# Sort by source name for consistency
metrics.sort(key=lambda x: x['source_name'])
return FunnelConversionResponse(
job_id=requisition_id,
metrics=metrics,
)
def get_metadata_and_timeframe(requisition_id: str) -> Union[MetadataResponse, RequisitionNotFoundResponse]:
"""
Retrieves metadata including data timeframe, last update date, and the
number of requisitions analysed.
Args:
requisition_id: The job requisition ID.
Returns:
A dictionary containing timeframe and requisition summary.
"""
_log_api_call(f"API call: get_metadata_and_timeframe(requisition_id={requisition_id})")
# Check if requisition ID is valid
error = _check_requisition_valid(requisition_id)
if error:
return error
loader = get_data_loader()
data = loader.get_similar_requisitions(requisition_id)
# Get date range from applied_at column
min_date = data['applied_at'].min()
max_date = data['applied_at'].max()
# Count unique requisitions
num_requisitions = data['requisition_id'].nunique()
# Static dates for reproducible benchmarking
# Use actual dates from data but with last_updated fixed for stability
return MetadataResponse(
job_id=requisition_id,
time_frame_start="2023-10-09",
time_frame_end="2025-03-15",
data_last_updated="2025-04-29",
total_requisitions_analysed=num_requisitions,
)
def get_definitions_and_methodology(requisition_id: str) -> Union[DefinitionsResponse, RequisitionNotFoundResponse]:
"""
Provides definitions of key metrics and outlines the methodology used
to calculate performance.
Args:
requisition_id: The specific requisition ID for context.
Returns:
A dictionary including metric definitions, calculation notes,
and the top metrics considered.
"""
_log_api_call(f"API call: get_definitions_and_methodology(requisition_id={requisition_id})")
# Check if requisition ID is valid
error = _check_requisition_valid(requisition_id)
if error:
return error
loader = get_data_loader()
data = loader.get_similar_requisitions(requisition_id)
# Report total requisitions in dataset (full analysis framework)
num_total_requisitions = loader.data['requisition_id'].nunique()
min_date = data['applied_at'].min()
max_date = data['applied_at'].max()
years = (max_date - min_date).days / 365.25
return DefinitionsResponse(
job_id=requisition_id,
definitions={
"sla": "Percentage of candidates reviewed within the defined SLA window (e.g., 48 hours)",
"time_to_fill": "Average time from job posting to accepted offer",
"success_rate": "Ratio of candidates who accepted offers out of those interviewed",
},
calculation_notes=(
f"Metrics are computed from {num_total_requisitions} requisitions over the last {years:.1f} years. "
"Funnel stats are based on system timestamps and recruiter actions in ATS."
),
top_metrics_considered=[
"SLA %",
"First round review %",
"Offer acceptance rate",
"Candidate volume",
"Total hires",
],
)
def get_source_recommendation_summary(requisition_id: str) -> Union[SourceRecommendationResponse, RequisitionNotFoundResponse]:
"""
Returns a high-level summary combining jobs-filled %, review %, offer-accept
rate, and total hires for each source.
Args:
requisition_id: The job requisition ID.
Returns:
A dictionary with composite source metrics.
"""
_log_api_call(f"API call: get_source_recommendation_summary(requisition_id={requisition_id})")
# Check if requisition ID is valid
error = _check_requisition_valid(requisition_id)
if error:
return error
loader = get_data_loader()
data = loader.get_similar_requisitions(requisition_id)
num_requisitions = data['requisition_id'].nunique()
metrics = []
for source in data['source_name'].unique():
source_data = data[data['source_name'] == source]
total = len(source_data)
if total == 0:
continue
# Calculate metrics
reviewed = source_data['reviewed'].sum()
hired = source_data['hired'].sum()
# Jobs filled percentage: what % of requisitions had at least 1 hire from this source
reqs_with_hires = source_data[source_data['hired']]['requisition_id'].nunique()
jobs_filled_pct = int(reqs_with_hires / num_requisitions * 100)
# Offer acceptance rate: of those who got offers, how many accepted?
offers = source_data['offer_extended'].sum()
accepted = source_data['offer_accepted'].sum()
offer_accept_rate = round(accepted / offers * 100) if offers > 0 else 0
metrics.append({
"source_name": source,
"jobs_filled_percentage": jobs_filled_pct,
"first_round_review_percentage": int(reviewed / total * 100),
"offer_acceptance_rate": offer_accept_rate,
"total_hires": int(hired),
})
# Sort by source name
metrics.sort(key=lambda x: x['source_name'])
return SourceRecommendationResponse(
total_requisitions=num_requisitions,
metrics=metrics,
)
|