File size: 9,261 Bytes
687bd84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pandas as pd
from api.inference import OverloadPredictor
from api.schemas import TaskAssignment

predictor = OverloadPredictor()

def predict_single(dev_id, task_count, avg_time, skill_match, story_points_assigned,
                   overtime, task_switches, pr_pending, priority, story_points_new,
                   deadline, skill, has_deps, task_type, team_size, sprint_days, velocity):
    try:
        assignment = TaskAssignment(
            developer_id=dev_id,
            current_task_count=task_count,
            avg_completion_time_days=avg_time,
            skill_match_score=skill_match,
            total_story_points_assigned=story_points_assigned,
            recent_overtime_hours=overtime,
            task_switch_frequency=task_switches,
            pr_review_pending=pr_pending,
            priority=priority,
            estimated_story_points=story_points_new,
            days_until_deadline=deadline,
            required_skill=skill,
            has_dependencies=has_deps,
            task_type=task_type,
            team_size=team_size,
            sprint_days_remaining=sprint_days,
            team_avg_velocity=velocity
        )
        
        result = predictor.predict(assignment)
        
        output = f"""
### Prediction Result

**Developer ID:** {result.developer_id}  
**Overload Risk:** {result.risk_label}  
**Confidence:** {result.confidence:.1%}

**Risk Probabilities:**
- Green: {result.risk_probabilities['green']:.1%}
- Yellow: {result.risk_probabilities['yellow']:.1%}
- Red: {result.risk_probabilities['red']:.1%}

**Contributing Factors:**
{chr(10).join(f"- {factor}" for factor in result.contributing_factors)}

**Recommendation:**  
{result.recommendation}
        """
        return output
    
    except Exception as e:
        return f"Error: {str(e)}"

def predict_batch_csv(file):
    try:
        df = pd.read_csv(file.name)
        results = predictor.predict_batch(df)
        return results
    except Exception as e:
        return f"Error processing CSV: {str(e)}"

def recommend_assignment(priority, story_points, deadline, skill, has_deps, task_type, team_file):
    try:
        task_details = {
            'priority': priority,
            'estimated_story_points': story_points,
            'days_until_deadline': deadline,
            'required_skill': skill,
            'has_dependencies': has_deps,
            'task_type': task_type
        }
        
        team_df = pd.read_csv(team_file.name)
        
        recommendations = predictor.recommend_developer(task_details, team_df)
        
        summary = f"""
### Load Balancing Recommendation

**Task Details:**
- Priority: P{priority}
- Story Points: {story_points}
- Deadline: {deadline} days
- Required Skill: {skill}

**Top 3 Recommendations:**
"""
        for idx, row in recommendations.head(3).iterrows():
            emoji = "🥇" if row['rank'] == 1 else "🥈" if row['rank'] == 2 else "🥉"
            summary += f"\n{emoji} **Developer {row['developer_id']}** - {row['risk_label']}"
            summary += f"\n   - Suitability Score: {row['suitability_score']}/100"
            summary += f"\n   - Skill Match: {row['skill_match']}%"
            summary += f"\n   - Current Load: {row['current_tasks']} tasks, {row['current_story_points']} points"
            summary += f"\n   - {row['recommendation']}\n"
        
        return summary, recommendations
    
    except Exception as e:
        return f"Error: {str(e)}", None

with gr.Blocks(title="Task Load Balancer", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # Intelligent Task Load Balancer
    
    **Predict developer overload risk using ML before assigning tasks.**
    
    This system analyzes workload, skills, deadlines, and team context to recommend optimal task assignments.
    
    ### How to Use:
    1. **Single Prediction:** Check risk for specific developer
    2. **Batch Prediction:** Upload CSV with multiple assignments
    3. **Load Balancing:** Get recommendation for which developer should get a new task
    """)
    
    with gr.Tab("Single Prediction"):
        gr.Markdown("### Developer & Task Details")
        
        with gr.Row():
            with gr.Column():
                dev_id = gr.Number(label="Developer ID", value=5)
                task_count = gr.Slider(0, 12, value=4, step=1, label="Current Task Count")
                avg_time = gr.Slider(1, 25, value=6, step=0.5, label="Avg Completion Time (days)")
                skill_match = gr.Slider(0, 100, value=85, step=5, label="Skill Match Score (%)")
                story_assigned = gr.Slider(0, 40, value=15, step=1, label="Current Story Points")
                overtime = gr.Slider(0, 20, value=2, step=1, label="Recent Overtime (hours)")
            
            with gr.Column():
                task_switches = gr.Slider(0, 10, value=3, step=0.5, label="Task Switches/Day")
                pr_pending = gr.Slider(0, 15, value=2, step=1, label="PRs Pending Review")
                priority = gr.Radio([0, 1, 2, 3], value=1, label="Priority (0=P0, 3=P3)")
                story_new = gr.Radio([1, 2, 3, 5, 8, 13], value=5, label="New Task Story Points")
                deadline = gr.Slider(1, 30, value=7, step=1, label="Days Until Deadline")
                skill = gr.Dropdown(["frontend", "backend", "devops", "ml", "testing"], 
                                    value="backend", label="Required Skill")
        
        with gr.Row():
            has_deps = gr.Radio([0, 1], value=0, label="Has Dependencies?")
            task_type = gr.Radio([0, 1, 2], value=0, label="Task Type (0=feature, 1=bug, 2=maint)")
            team_size = gr.Slider(5, 15, value=10, step=1, label="Team Size")
            sprint_days = gr.Slider(1, 14, value=8, step=1, label="Sprint Days Remaining")
            velocity = gr.Slider(20, 80, value=50, step=5, label="Team Avg Velocity")
        
        predict_btn = gr.Button("Predict Overload Risk", variant="primary")
        output_single = gr.Markdown()
        
        predict_btn.click(
            predict_single,
            inputs=[dev_id, task_count, avg_time, skill_match, story_assigned,
                   overtime, task_switches, pr_pending, priority, story_new,
                   deadline, skill, has_deps, task_type, team_size, sprint_days, velocity],
            outputs=output_single
        )
    
    with gr.Tab("Batch Prediction (CSV Upload)"):
        gr.Markdown("""
        ### Upload CSV File
        
        **Required columns:**
        `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`, `priority`, `estimated_story_points`, `days_until_deadline`, 
        `required_skill`, `has_dependencies`, `task_type`, `team_size`, `sprint_days_remaining`, 
        `team_avg_velocity`
        """)
        
        file_input = gr.File(label="Upload CSV", file_types=[".csv"])
        predict_csv_btn = gr.Button("Predict Batch", variant="primary")
        output_batch = gr.Dataframe()
        
        predict_csv_btn.click(predict_batch_csv, inputs=file_input, outputs=output_batch)
    
    with gr.Tab("Load Balancing (Recommend Developer)"):
        gr.Markdown("""
        ### Find Best Developer for New Task
        
        Upload team workload CSV and specify task details to get ranked recommendations.
        """)
        
        with gr.Row():
            with gr.Column():
                gr.Markdown("**Task Details:**")
                task_priority = gr.Radio([0, 1, 2, 3], value=1, label="Priority (0=P0, 3=P3)")
                task_story_points = gr.Radio([1, 2, 3, 5, 8, 13], value=5, label="Story Points")
                task_deadline = gr.Slider(1, 30, value=7, step=1, label="Days Until Deadline")
                task_skill = gr.Dropdown(["frontend", "backend", "devops", "ml", "testing"], 
                                        value="backend", label="Required Skill")
                task_has_deps = gr.Radio([0, 1], value=0, label="Has Dependencies?")
                task_task_type = gr.Radio([0, 1, 2], value=0, label="Task Type")
            
            with gr.Column():
                gr.Markdown("**Team Workload CSV:**")
                gr.Markdown("Upload CSV with columns: `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`")
                team_workload_file = gr.File(label="Upload Team Workload CSV", file_types=[".csv"])
        
        recommend_btn = gr.Button("Get Recommendation", variant="primary")
        recommendation_summary = gr.Markdown()
        recommendation_table = gr.Dataframe()
        
        recommend_btn.click(
            recommend_assignment,
            inputs=[task_priority, task_story_points, task_deadline, task_skill, 
                   task_has_deps, task_task_type, team_workload_file],
            outputs=[recommendation_summary, recommendation_table]
        )

if __name__ == "__main__":
    demo.launch()