nodronm commited on
Commit
b7f38c7
·
verified ·
1 Parent(s): 94bf798

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -213
app.py CHANGED
@@ -1,221 +1,99 @@
1
- import streamlit as st
2
- import pandas as pd
3
  import numpy as np
 
4
  import joblib
5
- import matplotlib.pyplot as plt
6
  import random
7
-
8
- # Set page config
9
- st.set_page_config(
10
- page_title="Team Productivity Predictor",
11
- page_icon="🏆",
12
- layout="wide"
13
- )
14
 
15
  # Load the model
16
- @st.cache_resource
17
- def load_model():
18
- try:
19
- model_path = "model.joblib"
20
- model = joblib.load(model_path)
21
- return model
22
- except Exception as e:
23
- st.error(f"Error loading model: {str(e)}")
24
- return None
25
 
26
- def generate_sample_task():
27
- """Generate random sample task data"""
28
-
29
- # Sample options for categorical features
30
- product_types = ["Mothball", "Perfume", "Candle", "Soap"]
31
- task_types = ["Packaging", "Molding", "Quality Check", "Boxing", "Shipping"]
32
-
33
- # Generate random task
34
- product_type = random.choice(product_types)
35
- task_type = random.choice(task_types)
36
- order_quantity = random.randint(50, 500)
37
- deadline_days = random.randint(2, 14)
38
- experience_years = round(random.uniform(1.0, 15.0), 1)
39
- avg_task_time = round(random.uniform(15.0, 60.0), 1)
40
- error_rate = round(random.uniform(0.01, 0.15), 3)
41
- training_hours = round(random.uniform(5.0, 50.0), 1)
42
- day_number = random.randint(1, 7)
43
- priority_level = random.randint(1, 5)
44
-
45
- # Calculate derived features
46
- throughput_rate = order_quantity / avg_task_time
47
- time_pressure = order_quantity / (deadline_days * avg_task_time)
48
-
49
- return {
50
- 'ProductType': product_type,
51
- 'TaskType': task_type,
52
- 'OrderQuantity': order_quantity,
53
- 'DeadlineDays': deadline_days,
54
- 'ExperienceYears': experience_years,
55
- 'AvgTaskTime_Minutes': avg_task_time,
56
- 'ErrorRate': error_rate,
57
- 'TrainingHours': training_hours,
58
- 'DayNumber': day_number,
59
- 'ThroughputRate': throughput_rate,
60
- 'TimePressure': time_pressure,
61
- 'PriorityLevel': priority_level
62
- }
63
 
64
- def main():
65
- st.title("🏆 Team Productivity Predictor")
66
- st.write("Generate random task data and predict team productivity rankings")
67
-
68
- # Load model
69
- model = load_model()
70
- if model is None:
71
- st.stop()
72
-
73
- # Team and Specialty mapping
74
- teams_specialties = {
75
- 'Team_1': 'Molding',
76
- 'Team_2': 'Packaging',
77
- 'Team_3': 'Quality Check',
78
- 'Team_4': 'Molding',
79
- 'Team_5': 'Boxing',
80
- 'Team_6': 'Shipping',
81
- 'Team_7': 'Boxing',
82
- 'Team_8': 'Packaging'
83
- }
84
-
85
- # Center the button
86
- col1, col2, col3 = st.columns([1, 2, 1])
87
- with col2:
88
- predict_button = st.button("🎲 Generate Sample Task & Predict Rankings",
89
- type="primary",
90
- use_container_width=True)
91
-
92
- if predict_button:
93
- # Generate sample task
94
- sample_task = generate_sample_task()
95
-
96
- # Display task details
97
- st.header("📋 Generated Task Details")
98
-
99
- # Create columns for task details
100
- col1, col2, col3 = st.columns(3)
101
-
102
- with col1:
103
- st.metric("🏷️ Product Type", sample_task['ProductType'])
104
- st.metric("⚙️ Task Type", sample_task['TaskType'])
105
- st.metric("📦 Order Quantity", f"{sample_task['OrderQuantity']:,}")
106
- st.metric("⏰ Deadline Days", sample_task['DeadlineDays'])
107
-
108
- with col2:
109
- st.metric("👨‍💼 Experience Years", f"{sample_task['ExperienceYears']}")
110
- st.metric("⏱️ Avg Task Time (min)", f"{sample_task['AvgTaskTime_Minutes']}")
111
- st.metric("❌ Error Rate", f"{sample_task['ErrorRate']:.3f}")
112
- st.metric("📚 Training Hours", f"{sample_task['TrainingHours']}")
113
-
114
- with col3:
115
- st.metric("📅 Day Number", sample_task['DayNumber'])
116
- st.metric("⭐ Priority Level", sample_task['PriorityLevel'])
117
- st.metric("🚀 Throughput Rate", f"{sample_task['ThroughputRate']:.2f}")
118
- st.metric("⚡ Time Pressure", f"{sample_task['TimePressure']:.3f}")
119
-
120
- try:
121
- # Build DataFrame with one row per team
122
- rows = []
123
- for team, specialty in teams_specialties.items():
124
- r = sample_task.copy()
125
- r['Team'] = team
126
- r['Specialty'] = specialty
127
- rows.append(r)
128
-
129
- test_df = pd.DataFrame(rows)
130
-
131
- # Make predictions
132
- test_df['PredictedProductivity'] = model.predict(test_df)
133
- ranked = test_df.sort_values('PredictedProductivity', ascending=False).reset_index(drop=True)
134
- ranked['Rank'] = range(1, len(ranked) + 1)
135
-
136
- st.header("🏆 Team Productivity Rankings")
137
-
138
- # Display results in two columns
139
- col1, col2 = st.columns([1, 1])
140
-
141
- with col1:
142
- st.subheader("📊 Rankings Table")
143
-
144
- # Style the dataframe
145
- display_df = ranked[['Rank', 'Team', 'Specialty', 'PredictedProductivity']].copy()
146
- display_df['PredictedProductivity'] = display_df['PredictedProductivity'].round(4)
147
-
148
- # Add medal emojis for top 3
149
- medals = {1: "🥇", 2: "🥈", 3: "🥉"}
150
- display_df['Medal'] = display_df['Rank'].map(lambda x: medals.get(x, ""))
151
-
152
- # Reorder columns
153
- display_df = display_df[['Medal', 'Rank', 'Team', 'Specialty', 'PredictedProductivity']]
154
-
155
- st.dataframe(
156
- display_df,
157
- use_container_width=True,
158
- hide_index=True
159
- )
160
-
161
- # Show top 3 teams with special formatting
162
- st.subheader("🎖️ Top 3 Teams")
163
- for i in range(min(3, len(ranked))):
164
- team_data = ranked.iloc[i]
165
- medal = ["🥇", "🥈", "🥉"][i]
166
- st.success(f"{medal} **{team_data['Team']}** ({team_data['Specialty']}) - Score: {team_data['PredictedProductivity']:.4f}")
167
-
168
- with col2:
169
- st.subheader("📈 Productivity Chart")
170
-
171
- # Create horizontal bar chart
172
- fig, ax = plt.subplots(figsize=(8, 6))
173
-
174
- # Color gradient for bars
175
- colors = plt.cm.viridis(np.linspace(0, 1, len(ranked)))
176
-
177
- bars = ax.barh(ranked['Team'], ranked['PredictedProductivity'], color=colors)
178
-
179
- # Customize chart
180
- ax.invert_yaxis()
181
- ax.set_xlabel('Predicted Productivity Score', fontsize=12)
182
- ax.set_title('Team Productivity Rankings', fontsize=14, fontweight='bold')
183
- ax.grid(axis='x', linestyle='--', alpha=0.3)
184
-
185
- # Add value labels on bars
186
- for i, (bar, value) in enumerate(zip(bars, ranked['PredictedProductivity'])):
187
- ax.text(value + 0.001, bar.get_y() + bar.get_height()/2,
188
- f'{value:.3f}', ha='left', va='center', fontsize=9)
189
-
190
- plt.tight_layout()
191
- st.pyplot(fig)
192
- plt.close()
193
-
194
- except Exception as e:
195
- st.error(f"Error making predictions: {str(e)}")
196
- st.write("Please check that your model file is compatible with the expected features.")
197
-
198
- else:
199
- # Show instructions when no button is clicked
200
- st.info("👆 Click the button above to generate a random task and see team productivity rankings!")
201
-
202
- # Show example of what teams are available
203
- st.subheader("👥 Available Teams")
204
- teams_df = pd.DataFrame([
205
- {"Team": team, "Specialty": specialty}
206
- for team, specialty in {
207
- 'Team_1': 'Molding',
208
- 'Team_2': 'Packaging',
209
- 'Team_3': 'Quality Check',
210
- 'Team_4': 'Molding',
211
- 'Team_5': 'Boxing',
212
- 'Team_6': 'Shipping',
213
- 'Team_7': 'Boxing',
214
- 'Team_8': 'Packaging'
215
- }.items()
216
- ])
217
-
218
- st.dataframe(teams_df, use_container_width=True, hide_index=True)
219
 
220
- if __name__ == "__main__":
221
- main()
 
1
+ import gradio as gr
2
+ import matplotlib.pyplot as plt
3
  import numpy as np
4
+ import pandas as pd
5
  import joblib
 
6
  import random
7
+ import json
 
 
 
 
 
 
8
 
9
  # Load the model
10
+ model = joblib.load("model.joblib")
11
+
12
+ # Load the original dataset to extract real specialty mappings
13
+ df = pd.read_csv("dataset.csv") # <-- Make sure this file is uploaded to Hugging Face
14
+
15
+ # Get actual teams and specialties
16
+ teams = sorted(df['Team'].unique())
17
+ specialty_map = dict(zip(df['Team'], df['Specialty']))
 
18
 
19
+ # Sample task examples (all feature-engineered already)
20
+ sample_tasks = [
21
+ {
22
+ 'ProductType': 'Mothball',
23
+ 'TaskType': 'Packaging',
24
+ 'OrderQuantity': 120,
25
+ 'DeadlineDays': 4,
26
+ 'ExperienceYears': 6,
27
+ 'AvgTaskTime_Minutes': 28.0,
28
+ 'ErrorRate': 0.05,
29
+ 'TrainingHours': 20.0,
30
+ 'DayNumber': 2
31
+ },
32
+ {
33
+ 'ProductType': 'Perfume',
34
+ 'TaskType': 'Boxing',
35
+ 'OrderQuantity': 80,
36
+ 'DeadlineDays': 2,
37
+ 'ExperienceYears': 2,
38
+ 'AvgTaskTime_Minutes': 45.0,
39
+ 'ErrorRate': 0.12,
40
+ 'TrainingHours': 10.0,
41
+ 'DayNumber': 3
42
+ },
43
+ {
44
+ 'ProductType': 'Soap',
45
+ 'TaskType': 'Molding',
46
+ 'OrderQuantity': 200,
47
+ 'DeadlineDays': 6,
48
+ 'ExperienceYears': 4,
49
+ 'AvgTaskTime_Minutes': 32.0,
50
+ 'ErrorRate': 0.07,
51
+ 'TrainingHours': 15.0,
52
+ 'DayNumber': 4
53
+ },
54
+ ]
 
55
 
56
+ # Prediction function
57
+ def predict():
58
+ task = random.choice(sample_tasks)
59
+
60
+ # Feature engineering
61
+ task['ThroughputRate'] = task['OrderQuantity'] / task['AvgTaskTime_Minutes']
62
+ task['TimePressure'] = task['OrderQuantity'] / ((task['DeadlineDays'] or 1) * task['AvgTaskTime_Minutes'])
63
+ task['PriorityLevel'] = 3 # high priority
64
+
65
+ # Predict for each team
66
+ results = []
67
+ for team in teams:
68
+ row = task.copy()
69
+ row['Team'] = team
70
+ row['Specialty'] = specialty_map.get(team, "Unknown")
71
+ input_df = pd.DataFrame([row])
72
+ pred = model.predict(input_df)[0]
73
+ results.append((team, round(pred, 4)))
74
+
75
+ # Sort results
76
+ results.sort(key=lambda x: x[1], reverse=True)
77
+
78
+ # Plot
79
+ teams_sorted, scores_sorted = zip(*results)
80
+ fig, ax = plt.subplots(figsize=(10, 6))
81
+ ax.barh(teams_sorted, scores_sorted, color="skyblue")
82
+ ax.set_xlabel("Predicted Productivity")
83
+ ax.set_title("Team Ranking for Random Task")
84
+ ax.invert_yaxis()
85
+ plt.tight_layout()
86
+
87
+ return fig, json.dumps(task, indent=2)
88
+
89
+ # Gradio UI
90
+ demo = gr.Interface(
91
+ fn=predict,
92
+ inputs=[],
93
+ outputs=[gr.Plot(label="Team Productivity Rankings"), gr.Textbox(label="Task Details")],
94
+ live=False,
95
+ title="Team Productivity Predictor",
96
+ description="Click Generate to predict the best team for a randomly selected task."
97
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
+ demo.launch()