task-load-balancer / api /inference.py
Sathvik
Deploy task load balancer
687bd84
Raw History Blame Contribute Delete
9.13 kB
import joblib
import numpy as np
import pandas as pd
from pathlib import Path
from api.schemas import TaskAssignment, PredictionResponse
class OverloadPredictor:
def __init__(self):
self.model = joblib.load('models/xgboost_overload_classifier.pkl')
self.label_encoder = joblib.load('models/label_encoder.pkl')
self.feature_cols = [
'current_task_count',
'avg_completion_time_days',
'skill_match_score',
'total_story_points_assigned',
'recent_overtime_hours',
'task_switch_frequency',
'pr_review_pending',
'priority',
'estimated_story_points',
'days_until_deadline',
'required_skill_encoded',
'has_dependencies',
'task_type',
'team_size',
'sprint_days_remaining',
'team_avg_velocity',
'workload_ratio',
'urgency_score',
'capacity_indicator',
'overtime_risk',
'skill_deficit'
]
self.risk_labels = {
0: 'Green (Healthy)',
1: 'Yellow (Moderate)',
2: 'Red (Overload)'
}
def engineer_features(self, data: dict) -> pd.DataFrame:
df = pd.DataFrame([data])
df['required_skill_encoded'] = self.label_encoder.transform([df['required_skill'][0]])[0]
df['workload_ratio'] = df['total_story_points_assigned'] / 40
df['urgency_score'] = (31 - df['days_until_deadline']) / 30
df['capacity_indicator'] = (
df['current_task_count'] / 8 * 0.4 +
df['task_switch_frequency'] / 10 * 0.3 +
df['workload_ratio'] * 0.3
)
df['overtime_risk'] = (df['recent_overtime_hours'] / 20).clip(0, 1)
df['skill_deficit'] = (100 - df['skill_match_score']) / 100
return df[self.feature_cols]
def predict(self, assignment: TaskAssignment) -> PredictionResponse:
X = self.engineer_features(assignment.dict())
prediction = self.model.predict(X)[0]
probabilities = self.model.predict_proba(X)[0]
feature_values = X.iloc[0].to_dict()
factors = []
if feature_values['current_task_count'] > 6:
factors.append(f"High task count ({int(feature_values['current_task_count'])})")
if feature_values['workload_ratio'] > 0.75:
factors.append(f"High story point load ({feature_values['workload_ratio']*100:.0f}%)")
if assignment.skill_match_score < 60:
factors.append(f"Low skill match ({assignment.skill_match_score}%)")
if assignment.recent_overtime_hours > 10:
factors.append(f"Recent overtime ({assignment.recent_overtime_hours}h)")
if assignment.days_until_deadline < 3 and assignment.priority == 0:
factors.append("Urgent deadline with critical priority")
if feature_values['capacity_indicator'] > 0.7:
factors.append(f"High capacity indicator ({feature_values['capacity_indicator']:.2f})")
if prediction == 0:
recommendation = "Safe to assign. Developer has capacity."
elif prediction == 1:
recommendation = "Proceed with caution. Monitor workload closely."
else:
recommendation = "High overload risk. Consider reassigning or extending deadline."
return PredictionResponse(
developer_id=assignment.developer_id,
overload_risk=int(prediction),
risk_label=self.risk_labels[prediction],
confidence=float(probabilities[prediction]),
risk_probabilities={
'green': float(probabilities[0]),
'yellow': float(probabilities[1]),
'red': float(probabilities[2])
},
contributing_factors=factors if factors else ["No significant risk factors"],
recommendation=recommendation
)
def predict_batch(self, df: pd.DataFrame) -> pd.DataFrame:
df['required_skill_encoded'] = self.label_encoder.transform(df['required_skill'])
df['workload_ratio'] = df['total_story_points_assigned'] / 40
df['urgency_score'] = (31 - df['days_until_deadline']) / 30
df['capacity_indicator'] = (
df['current_task_count'] / 8 * 0.4 +
df['task_switch_frequency'] / 10 * 0.3 +
df['workload_ratio'] * 0.3
)
df['overtime_risk'] = (df['recent_overtime_hours'] / 20).clip(0, 1)
df['skill_deficit'] = (100 - df['skill_match_score']) / 100
X = df[self.feature_cols]
predictions = self.model.predict(X)
probabilities = self.model.predict_proba(X)
result_df = df[['developer_id']].copy()
result_df['predicted_risk'] = predictions
result_df['risk_label'] = result_df['predicted_risk'].map(self.risk_labels)
result_df['confidence'] = probabilities.max(axis=1)
result_df['green_prob'] = probabilities[:, 0]
result_df['yellow_prob'] = probabilities[:, 1]
result_df['red_prob'] = probabilities[:, 2]
return result_df
def recommend_developer(self, task_details: dict, team_workload_df: pd.DataFrame) -> pd.DataFrame:
"""
Given a new task and current team workload, recommend which developer should get it.
Args:
task_details: dict with priority, estimated_story_points, days_until_deadline,
required_skill, has_dependencies, task_type
team_workload_df: DataFrame with current workload for all developers
(developer_id, current_task_count, avg_completion_time_days,
skill_match_score, total_story_points_assigned,
recent_overtime_hours, task_switch_frequency, pr_review_pending,
team_size, sprint_days_remaining, team_avg_velocity)
Returns:
DataFrame with ranked recommendations
"""
recommendations = []
for _, dev_row in team_workload_df.iterrows():
assignment_data = {
'developer_id': int(dev_row['developer_id']),
'current_task_count': int(dev_row['current_task_count']),
'avg_completion_time_days': float(dev_row['avg_completion_time_days']),
'skill_match_score': int(dev_row['skill_match_score']),
'total_story_points_assigned': int(dev_row['total_story_points_assigned']),
'recent_overtime_hours': int(dev_row['recent_overtime_hours']),
'task_switch_frequency': float(dev_row['task_switch_frequency']),
'pr_review_pending': int(dev_row['pr_review_pending']),
'priority': int(task_details['priority']),
'estimated_story_points': int(task_details['estimated_story_points']),
'days_until_deadline': int(task_details['days_until_deadline']),
'required_skill': task_details['required_skill'],
'has_dependencies': int(task_details['has_dependencies']),
'task_type': int(task_details['task_type']),
'team_size': int(dev_row['team_size']),
'sprint_days_remaining': int(dev_row['sprint_days_remaining']),
'team_avg_velocity': int(dev_row['team_avg_velocity'])
}
assignment = TaskAssignment(**assignment_data)
result = self.predict(assignment)
suitability_score = (
result.risk_probabilities['green'] * 100 * 0.5 +
(assignment_data['skill_match_score'] / 100) * 40 +
(1 - assignment_data['current_task_count'] / 12) * 10
)
recommendations.append({
'developer_id': assignment_data['developer_id'],
'overload_risk': result.overload_risk,
'risk_label': result.risk_label,
'green_probability': result.risk_probabilities['green'],
'skill_match': assignment_data['skill_match_score'],
'current_tasks': assignment_data['current_task_count'],
'current_story_points': assignment_data['total_story_points_assigned'],
'suitability_score': round(suitability_score, 2),
'recommendation': result.recommendation
})
recommendations_df = pd.DataFrame(recommendations)
recommendations_df = recommendations_df.sort_values('suitability_score', ascending=False)
recommendations_df['rank'] = range(1, len(recommendations_df) + 1)
return recommendations_df[['rank', 'developer_id', 'risk_label', 'suitability_score',
'skill_match', 'current_tasks', 'current_story_points',
'green_probability', 'recommendation']]