Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -36,7 +36,7 @@ if not app.debug:
|
|
| 36 |
|
| 37 |
|
| 38 |
class DataStore:
|
| 39 |
-
def
|
| 40 |
self.uploaded_data = None
|
| 41 |
self.current_index = 0
|
| 42 |
self.processed_data = []
|
|
@@ -54,7 +54,6 @@ def detect_anomalies(df):
|
|
| 54 |
'filters': 90,
|
| 55 |
'cables': 90
|
| 56 |
}
|
| 57 |
-
|
| 58 |
for idx, row in df.iterrows():
|
| 59 |
row_alerts = []
|
| 60 |
for component, threshold in thresholds.items():
|
|
@@ -76,13 +75,8 @@ def analyze_component_trends(df):
|
|
| 76 |
"""Analyze trends and patterns in component data"""
|
| 77 |
trends = {}
|
| 78 |
for component in ['brakes', 'filters', 'cables']:
|
| 79 |
-
# Calculate rolling average to identify trends
|
| 80 |
rolling_avg = df[component].rolling(window=3).mean()
|
| 81 |
-
|
| 82 |
-
# Calculate rate of change
|
| 83 |
rate_of_change = df[component].diff().mean()
|
| 84 |
-
|
| 85 |
-
# Identify peak usage periods
|
| 86 |
peak_threshold = df[component].quantile(0.75)
|
| 87 |
peak_periods = df[component] > peak_threshold
|
| 88 |
|
|
@@ -103,7 +97,6 @@ def generate_maintenance_insights(df, trends):
|
|
| 103 |
'preventive_measures': [],
|
| 104 |
'optimization_suggestions': []
|
| 105 |
}
|
| 106 |
-
|
| 107 |
for component in ['brakes', 'filters', 'cables']:
|
| 108 |
avg = df[component].mean()
|
| 109 |
max_val = df[component].max()
|
|
@@ -125,7 +118,7 @@ def generate_maintenance_insights(df, trends):
|
|
| 125 |
insights['maintenance_recommendations'].append({
|
| 126 |
'component': component,
|
| 127 |
'urgency': 'High' if avg > 75 else 'Medium',
|
| 128 |
-
'action': f"Schedule maintenance within {'
|
| 129 |
'reason': f"Increasing trend with high average ({round(avg, 1)}%)"
|
| 130 |
})
|
| 131 |
|
|
@@ -146,7 +139,6 @@ def generate_maintenance_insights(df, trends):
|
|
| 146 |
'potential_impact': 'High',
|
| 147 |
'expected_benefit': 'Reduced wear and extended component life'
|
| 148 |
})
|
| 149 |
-
|
| 150 |
return insights
|
| 151 |
|
| 152 |
|
|
@@ -160,22 +152,17 @@ def calculate_statistics(df):
|
|
| 160 |
},
|
| 161 |
'critical_components': [],
|
| 162 |
'maintenance_suggestions': [],
|
| 163 |
-
'component_health': {},
|
| 164 |
-
'maintenance_priority': [],
|
| 165 |
-
'performance_metrics': {},
|
| 166 |
-
'detailed_analysis': {}
|
| 167 |
}
|
| 168 |
-
|
| 169 |
-
# Calculate component health and status
|
| 170 |
for component in ['brakes', 'filters', 'cables']:
|
| 171 |
avg = df[component].mean()
|
| 172 |
max_val = df[component].max()
|
| 173 |
min_val = df[component].min()
|
| 174 |
std_dev = df[component].std()
|
| 175 |
-
|
| 176 |
-
# Calculate health score (0-100)
|
| 177 |
health_score = max(0, min(100, 100 - (avg / 100 * 100)))
|
| 178 |
-
|
| 179 |
stats['component_health'][component] = {
|
| 180 |
'health_score': round(health_score, 1),
|
| 181 |
'average': round(avg, 2),
|
|
@@ -184,8 +171,6 @@ def calculate_statistics(df):
|
|
| 184 |
'variability': round(std_dev, 2),
|
| 185 |
'status': 'Good' if avg < 60 else 'Warning' if avg < 75 else 'Critical'
|
| 186 |
}
|
| 187 |
-
|
| 188 |
-
# Identify critical components
|
| 189 |
if avg > 70:
|
| 190 |
stats['critical_components'].append({
|
| 191 |
'name': component,
|
|
@@ -196,7 +181,6 @@ def calculate_statistics(df):
|
|
| 196 |
'variability': round(std_dev, 2)
|
| 197 |
})
|
| 198 |
|
| 199 |
-
# Generate prioritized maintenance suggestions
|
| 200 |
for component, health in stats['component_health'].items():
|
| 201 |
if health['average'] > 80:
|
| 202 |
stats['maintenance_priority'].append({
|
|
@@ -223,25 +207,19 @@ def calculate_statistics(df):
|
|
| 223 |
'recommendation': f"Monitor {component} performance"
|
| 224 |
})
|
| 225 |
|
| 226 |
-
# Generate detailed maintenance suggestions
|
| 227 |
for component, health in stats['component_health'].items():
|
| 228 |
suggestions = []
|
| 229 |
-
|
| 230 |
if health['average'] > 80:
|
| 231 |
suggestions.append(f"URGENT: Immediate maintenance required - {component} showing critical wear")
|
| 232 |
elif health['average'] > 70:
|
| 233 |
suggestions.append(f"WARNING: Schedule maintenance soon - {component} performance degrading")
|
| 234 |
-
|
| 235 |
if health['variability'] > 10:
|
| 236 |
suggestions.append(f"Monitor {component} - Showing inconsistent readings (±{health['variability']}%)")
|
| 237 |
-
|
| 238 |
if health['max_reading'] > 90:
|
| 239 |
suggestions.append(f"Investigate {component} peak readings of {health['max_reading']}%")
|
| 240 |
-
|
| 241 |
if suggestions:
|
| 242 |
stats['maintenance_suggestions'].extend(suggestions)
|
| 243 |
|
| 244 |
-
# Calculate performance metrics
|
| 245 |
stats['performance_metrics'] = {
|
| 246 |
'overall_health': round(sum(h['health_score'] for h in stats['component_health'].values()) / 3, 1),
|
| 247 |
'critical_count': len([h for h in stats['component_health'].values() if h['status'] == 'Critical']),
|
|
@@ -249,23 +227,18 @@ def calculate_statistics(df):
|
|
| 249 |
'healthy_count': len([h for h in stats['component_health'].values() if h['status'] == 'Good'])
|
| 250 |
}
|
| 251 |
|
| 252 |
-
# Add new detailed analyses
|
| 253 |
trends = analyze_component_trends(df)
|
| 254 |
maintenance_insights = generate_maintenance_insights(df, trends)
|
| 255 |
-
|
| 256 |
stats['detailed_analysis'] = {
|
| 257 |
'trends': trends,
|
| 258 |
'insights': maintenance_insights
|
| 259 |
}
|
| 260 |
-
|
| 261 |
return stats
|
| 262 |
|
| 263 |
|
| 264 |
def create_graphs(df):
|
| 265 |
"""Create all visualization graphs"""
|
| 266 |
graphs = {}
|
| 267 |
-
|
| 268 |
-
# Gauge Charts for all components
|
| 269 |
components = ['brakes', 'filters', 'cables']
|
| 270 |
for component in components:
|
| 271 |
latest_value = df[component].iloc[-1]
|
|
@@ -292,10 +265,8 @@ def create_graphs(df):
|
|
| 292 |
gauge.update_layout(height=300)
|
| 293 |
graphs[f'{component}_gauge'] = gauge.to_html(full_html=False)
|
| 294 |
|
| 295 |
-
# Bar Chart for current readings with historical average
|
| 296 |
current_values = [df[comp].iloc[-1] for comp in components]
|
| 297 |
avg_values = [df[comp].mean() for comp in components]
|
| 298 |
-
|
| 299 |
bar = go.Figure(data=[
|
| 300 |
go.Bar(name='Current Reading', x=components, y=current_values),
|
| 301 |
go.Bar(name='Historical Average', x=components, y=avg_values)
|
|
@@ -307,16 +278,13 @@ def create_graphs(df):
|
|
| 307 |
)
|
| 308 |
graphs['bar'] = bar.to_html(full_html=False)
|
| 309 |
|
| 310 |
-
# Time Series Chart with Moving Average
|
| 311 |
fig_time = go.Figure()
|
| 312 |
for component in components:
|
| 313 |
-
# Add raw data
|
| 314 |
fig_time.add_trace(go.Scatter(
|
| 315 |
y=df[component],
|
| 316 |
name=component.title(),
|
| 317 |
mode='lines'
|
| 318 |
))
|
| 319 |
-
# Add moving average
|
| 320 |
ma = df[component].rolling(window=3).mean()
|
| 321 |
fig_time.add_trace(go.Scatter(
|
| 322 |
y=ma,
|
|
@@ -324,7 +292,6 @@ def create_graphs(df):
|
|
| 324 |
line=dict(dash='dash'),
|
| 325 |
opacity=0.5
|
| 326 |
))
|
| 327 |
-
|
| 328 |
fig_time.update_layout(
|
| 329 |
title='Component Readings Over Time',
|
| 330 |
height=400,
|
|
@@ -339,7 +306,6 @@ def create_graphs(df):
|
|
| 339 |
)
|
| 340 |
graphs['timeseries'] = fig_time.to_html(full_html=False)
|
| 341 |
|
| 342 |
-
# Correlation Matrix Heatmap
|
| 343 |
corr_matrix = df[components].corr()
|
| 344 |
heatmap = go.Figure(data=go.Heatmap(
|
| 345 |
z=corr_matrix,
|
|
@@ -355,7 +321,6 @@ def create_graphs(df):
|
|
| 355 |
)
|
| 356 |
graphs['heatmap'] = heatmap.to_html(full_html=False)
|
| 357 |
|
| 358 |
-
# Box Plot for Distribution Analysis
|
| 359 |
box_data = [go.Box(y=df[component], name=component.title()) for component in components]
|
| 360 |
box_plot = go.Figure(data=box_data)
|
| 361 |
box_plot.update_layout(
|
|
@@ -364,7 +329,6 @@ def create_graphs(df):
|
|
| 364 |
)
|
| 365 |
graphs['box_plot'] = box_plot.to_html(full_html=False)
|
| 366 |
|
| 367 |
-
# Scatter Matrix
|
| 368 |
scatter_matrix = px.scatter_matrix(
|
| 369 |
df[components],
|
| 370 |
dimensions=components,
|
|
@@ -378,6 +342,8 @@ def create_graphs(df):
|
|
| 378 |
|
| 379 |
@app.route('/')
|
| 380 |
def index():
|
|
|
|
|
|
|
| 381 |
return render_template('index.html',
|
| 382 |
data=None,
|
| 383 |
graphs=None,
|
|
@@ -385,57 +351,34 @@ def index():
|
|
| 385 |
anomalies=None)
|
| 386 |
|
| 387 |
|
| 388 |
-
@app.route('/
|
| 389 |
-
def
|
| 390 |
-
if 'file' not in request.files:
|
| 391 |
-
flash('No file uploaded', 'error')
|
| 392 |
-
return redirect(url_for('index'))
|
| 393 |
-
|
| 394 |
-
file = request.files['file']
|
| 395 |
-
if file.filename == '':
|
| 396 |
-
flash('No file selected', 'error')
|
| 397 |
-
return redirect(url_for('index'))
|
| 398 |
-
|
| 399 |
try:
|
| 400 |
-
#
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
df = pd.read_excel(file)
|
| 405 |
-
else:
|
| 406 |
-
flash('Unsupported file format. Please upload CSV or Excel file.', 'error')
|
| 407 |
return redirect(url_for('index'))
|
| 408 |
-
|
| 409 |
-
# Validate required columns
|
| 410 |
required_columns = ['brakes', 'filters', 'cables']
|
| 411 |
missing_columns = [col for col in required_columns if col not in df.columns]
|
| 412 |
-
|
| 413 |
if missing_columns:
|
| 414 |
flash(f"Missing required columns: {', '.join(missing_columns)}", 'error')
|
| 415 |
return redirect(url_for('index'))
|
| 416 |
-
|
| 417 |
-
# Store the data and process it
|
| 418 |
data_store.uploaded_data = df
|
| 419 |
data_store.anomalies = detect_anomalies(df)
|
| 420 |
-
|
| 421 |
-
# Calculate statistics
|
| 422 |
stats = calculate_statistics(df)
|
| 423 |
-
|
| 424 |
-
# Create graphs
|
| 425 |
graphs = create_graphs(df)
|
| 426 |
-
|
| 427 |
-
# Render template with all the data
|
| 428 |
return render_template('index.html',
|
| 429 |
data=df.to_dict('records'),
|
| 430 |
graphs=graphs,
|
| 431 |
stats=stats,
|
| 432 |
anomalies=data_store.anomalies)
|
| 433 |
-
|
| 434 |
except Exception as e:
|
| 435 |
-
flash(f"Error processing
|
| 436 |
return redirect(url_for('index'))
|
| 437 |
|
| 438 |
|
| 439 |
if __name__ == '__main__':
|
| 440 |
port = int(os.environ.get("PORT", 7860))
|
| 441 |
-
app.run(host='0.0.0.0', port=port)
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
class DataStore:
|
| 39 |
+
def __init__(self):
|
| 40 |
self.uploaded_data = None
|
| 41 |
self.current_index = 0
|
| 42 |
self.processed_data = []
|
|
|
|
| 54 |
'filters': 90,
|
| 55 |
'cables': 90
|
| 56 |
}
|
|
|
|
| 57 |
for idx, row in df.iterrows():
|
| 58 |
row_alerts = []
|
| 59 |
for component, threshold in thresholds.items():
|
|
|
|
| 75 |
"""Analyze trends and patterns in component data"""
|
| 76 |
trends = {}
|
| 77 |
for component in ['brakes', 'filters', 'cables']:
|
|
|
|
| 78 |
rolling_avg = df[component].rolling(window=3).mean()
|
|
|
|
|
|
|
| 79 |
rate_of_change = df[component].diff().mean()
|
|
|
|
|
|
|
| 80 |
peak_threshold = df[component].quantile(0.75)
|
| 81 |
peak_periods = df[component] > peak_threshold
|
| 82 |
|
|
|
|
| 97 |
'preventive_measures': [],
|
| 98 |
'optimization_suggestions': []
|
| 99 |
}
|
|
|
|
| 100 |
for component in ['brakes', 'filters', 'cables']:
|
| 101 |
avg = df[component].mean()
|
| 102 |
max_val = df[component].max()
|
|
|
|
| 118 |
insights['maintenance_recommendations'].append({
|
| 119 |
'component': component,
|
| 120 |
'urgency': 'High' if avg > 75 else 'Medium',
|
| 121 |
+
'action': f"Schedule maintenance within {'24 hours' if avg > 75 else 'one week'}",
|
| 122 |
'reason': f"Increasing trend with high average ({round(avg, 1)}%)"
|
| 123 |
})
|
| 124 |
|
|
|
|
| 139 |
'potential_impact': 'High',
|
| 140 |
'expected_benefit': 'Reduced wear and extended component life'
|
| 141 |
})
|
|
|
|
| 142 |
return insights
|
| 143 |
|
| 144 |
|
|
|
|
| 152 |
},
|
| 153 |
'critical_components': [],
|
| 154 |
'maintenance_suggestions': [],
|
| 155 |
+
'component_health': {},
|
| 156 |
+
'maintenance_priority': [],
|
| 157 |
+
'performance_metrics': {},
|
| 158 |
+
'detailed_analysis': {}
|
| 159 |
}
|
|
|
|
|
|
|
| 160 |
for component in ['brakes', 'filters', 'cables']:
|
| 161 |
avg = df[component].mean()
|
| 162 |
max_val = df[component].max()
|
| 163 |
min_val = df[component].min()
|
| 164 |
std_dev = df[component].std()
|
|
|
|
|
|
|
| 165 |
health_score = max(0, min(100, 100 - (avg / 100 * 100)))
|
|
|
|
| 166 |
stats['component_health'][component] = {
|
| 167 |
'health_score': round(health_score, 1),
|
| 168 |
'average': round(avg, 2),
|
|
|
|
| 171 |
'variability': round(std_dev, 2),
|
| 172 |
'status': 'Good' if avg < 60 else 'Warning' if avg < 75 else 'Critical'
|
| 173 |
}
|
|
|
|
|
|
|
| 174 |
if avg > 70:
|
| 175 |
stats['critical_components'].append({
|
| 176 |
'name': component,
|
|
|
|
| 181 |
'variability': round(std_dev, 2)
|
| 182 |
})
|
| 183 |
|
|
|
|
| 184 |
for component, health in stats['component_health'].items():
|
| 185 |
if health['average'] > 80:
|
| 186 |
stats['maintenance_priority'].append({
|
|
|
|
| 207 |
'recommendation': f"Monitor {component} performance"
|
| 208 |
})
|
| 209 |
|
|
|
|
| 210 |
for component, health in stats['component_health'].items():
|
| 211 |
suggestions = []
|
|
|
|
| 212 |
if health['average'] > 80:
|
| 213 |
suggestions.append(f"URGENT: Immediate maintenance required - {component} showing critical wear")
|
| 214 |
elif health['average'] > 70:
|
| 215 |
suggestions.append(f"WARNING: Schedule maintenance soon - {component} performance degrading")
|
|
|
|
| 216 |
if health['variability'] > 10:
|
| 217 |
suggestions.append(f"Monitor {component} - Showing inconsistent readings (±{health['variability']}%)")
|
|
|
|
| 218 |
if health['max_reading'] > 90:
|
| 219 |
suggestions.append(f"Investigate {component} peak readings of {health['max_reading']}%")
|
|
|
|
| 220 |
if suggestions:
|
| 221 |
stats['maintenance_suggestions'].extend(suggestions)
|
| 222 |
|
|
|
|
| 223 |
stats['performance_metrics'] = {
|
| 224 |
'overall_health': round(sum(h['health_score'] for h in stats['component_health'].values()) / 3, 1),
|
| 225 |
'critical_count': len([h for h in stats['component_health'].values() if h['status'] == 'Critical']),
|
|
|
|
| 227 |
'healthy_count': len([h for h in stats['component_health'].values() if h['status'] == 'Good'])
|
| 228 |
}
|
| 229 |
|
|
|
|
| 230 |
trends = analyze_component_trends(df)
|
| 231 |
maintenance_insights = generate_maintenance_insights(df, trends)
|
|
|
|
| 232 |
stats['detailed_analysis'] = {
|
| 233 |
'trends': trends,
|
| 234 |
'insights': maintenance_insights
|
| 235 |
}
|
|
|
|
| 236 |
return stats
|
| 237 |
|
| 238 |
|
| 239 |
def create_graphs(df):
|
| 240 |
"""Create all visualization graphs"""
|
| 241 |
graphs = {}
|
|
|
|
|
|
|
| 242 |
components = ['brakes', 'filters', 'cables']
|
| 243 |
for component in components:
|
| 244 |
latest_value = df[component].iloc[-1]
|
|
|
|
| 265 |
gauge.update_layout(height=300)
|
| 266 |
graphs[f'{component}_gauge'] = gauge.to_html(full_html=False)
|
| 267 |
|
|
|
|
| 268 |
current_values = [df[comp].iloc[-1] for comp in components]
|
| 269 |
avg_values = [df[comp].mean() for comp in components]
|
|
|
|
| 270 |
bar = go.Figure(data=[
|
| 271 |
go.Bar(name='Current Reading', x=components, y=current_values),
|
| 272 |
go.Bar(name='Historical Average', x=components, y=avg_values)
|
|
|
|
| 278 |
)
|
| 279 |
graphs['bar'] = bar.to_html(full_html=False)
|
| 280 |
|
|
|
|
| 281 |
fig_time = go.Figure()
|
| 282 |
for component in components:
|
|
|
|
| 283 |
fig_time.add_trace(go.Scatter(
|
| 284 |
y=df[component],
|
| 285 |
name=component.title(),
|
| 286 |
mode='lines'
|
| 287 |
))
|
|
|
|
| 288 |
ma = df[component].rolling(window=3).mean()
|
| 289 |
fig_time.add_trace(go.Scatter(
|
| 290 |
y=ma,
|
|
|
|
| 292 |
line=dict(dash='dash'),
|
| 293 |
opacity=0.5
|
| 294 |
))
|
|
|
|
| 295 |
fig_time.update_layout(
|
| 296 |
title='Component Readings Over Time',
|
| 297 |
height=400,
|
|
|
|
| 306 |
)
|
| 307 |
graphs['timeseries'] = fig_time.to_html(full_html=False)
|
| 308 |
|
|
|
|
| 309 |
corr_matrix = df[components].corr()
|
| 310 |
heatmap = go.Figure(data=go.Heatmap(
|
| 311 |
z=corr_matrix,
|
|
|
|
| 321 |
)
|
| 322 |
graphs['heatmap'] = heatmap.to_html(full_html=False)
|
| 323 |
|
|
|
|
| 324 |
box_data = [go.Box(y=df[component], name=component.title()) for component in components]
|
| 325 |
box_plot = go.Figure(data=box_data)
|
| 326 |
box_plot.update_layout(
|
|
|
|
| 329 |
)
|
| 330 |
graphs['box_plot'] = box_plot.to_html(full_html=False)
|
| 331 |
|
|
|
|
| 332 |
scatter_matrix = px.scatter_matrix(
|
| 333 |
df[components],
|
| 334 |
dimensions=components,
|
|
|
|
| 342 |
|
| 343 |
@app.route('/')
|
| 344 |
def index():
|
| 345 |
+
# Render the homepage with an "Analyze" button
|
| 346 |
+
# (Assuming your index.html contains the button that directs to the /analyze route)
|
| 347 |
return render_template('index.html',
|
| 348 |
data=None,
|
| 349 |
graphs=None,
|
|
|
|
| 351 |
anomalies=None)
|
| 352 |
|
| 353 |
|
| 354 |
+
@app.route('/analyze', methods=['GET'])
|
| 355 |
+
def analyze():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
try:
|
| 357 |
+
# Hardcoded CSV file path (ensure data.csv is present in the same directory)
|
| 358 |
+
file_path = 'test_data (1).csv'
|
| 359 |
+
if not os.path.exists(file_path):
|
| 360 |
+
flash('Data file not found', 'error')
|
|
|
|
|
|
|
|
|
|
| 361 |
return redirect(url_for('index'))
|
| 362 |
+
df = pd.read_csv(file_path)
|
|
|
|
| 363 |
required_columns = ['brakes', 'filters', 'cables']
|
| 364 |
missing_columns = [col for col in required_columns if col not in df.columns]
|
|
|
|
| 365 |
if missing_columns:
|
| 366 |
flash(f"Missing required columns: {', '.join(missing_columns)}", 'error')
|
| 367 |
return redirect(url_for('index'))
|
|
|
|
|
|
|
| 368 |
data_store.uploaded_data = df
|
| 369 |
data_store.anomalies = detect_anomalies(df)
|
|
|
|
|
|
|
| 370 |
stats = calculate_statistics(df)
|
|
|
|
|
|
|
| 371 |
graphs = create_graphs(df)
|
|
|
|
|
|
|
| 372 |
return render_template('index.html',
|
| 373 |
data=df.to_dict('records'),
|
| 374 |
graphs=graphs,
|
| 375 |
stats=stats,
|
| 376 |
anomalies=data_store.anomalies)
|
|
|
|
| 377 |
except Exception as e:
|
| 378 |
+
flash(f"Error processing data: {str(e)}", 'error')
|
| 379 |
return redirect(url_for('index'))
|
| 380 |
|
| 381 |
|
| 382 |
if __name__ == '__main__':
|
| 383 |
port = int(os.environ.get("PORT", 7860))
|
| 384 |
+
app.run(host='0.0.0.0', port=port)
|