Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -252,9 +252,9 @@ async def process_logs(file_obj, progress=gr.Progress()):
|
|
| 252 |
preview_lines = ["Step 2: Log Preview (First 5 Rows)"]
|
| 253 |
for idx, row in df.head().iterrows():
|
| 254 |
preview_lines.append(f"Row {idx + 1}: Device ID: {row['device_id']}, Log Type: {row['log_type']}, Status: {row['status']}, Timestamp: {row['timestamp']}, Usage Hours: {row['usage_hours']}, Downtime: {row['downtime']}, AMC Date: {row['amc_date']}")
|
| 255 |
-
preview = "\
|
| 256 |
else:
|
| 257 |
-
preview
|
| 258 |
|
| 259 |
# Step 3: Usage Chart
|
| 260 |
chart = create_usage_chart(df, progress)
|
|
@@ -265,7 +265,7 @@ async def process_logs(file_obj, progress=gr.Progress()):
|
|
| 265 |
# Step 5: AMC Reminders
|
| 266 |
amc_reminders = f"Step 4: AMC Reminders\n{check_amc_reminders(df, datetime.now(), progress)}"
|
| 267 |
|
| 268 |
-
# Step 6:
|
| 269 |
insights = f"Step 5: Dashboard Insights (AI)\n{generate_dashboard_insights(df, progress)}"
|
| 270 |
|
| 271 |
# Generate PDF if available
|
|
@@ -274,21 +274,21 @@ async def process_logs(file_obj, progress=gr.Progress()):
|
|
| 274 |
if pdf_file is None and reportlab_available:
|
| 275 |
logging.warning("PDF generation failed, but analysis completed")
|
| 276 |
elif pdf_file is None:
|
| 277 |
-
logging.
|
| 278 |
|
| 279 |
progress(1.0, "Processing complete!")
|
| 280 |
return summary, preview, chart, anomalies, amc_reminders, insights, pdf_file
|
| 281 |
except Exception as e:
|
| 282 |
logging.error(f"Failed to process file: {str(e)}")
|
| 283 |
-
return f"
|
| 284 |
|
| 285 |
# Gradio Interface
|
| 286 |
try:
|
| 287 |
-
logging.info("Initializing Gradio
|
| 288 |
with gr.Blocks(css="""
|
| 289 |
-
.dashboard-container {border: 1px solid #e0e0e0; padding: 10px; border-radius: 5px;
|
| 290 |
.dashboard-title {font-size: 24px; font-weight: bold; margin-bottom: 5px;}
|
| 291 |
-
.dashboard-section {margin-bottom:
|
| 292 |
.dashboard-section h3 {font-size: 18px; margin-bottom: 2px;}
|
| 293 |
.dashboard-section p {margin: 1px 0; line-height: 1.2;}
|
| 294 |
.dashboard-section ul {margin: 2px 0; padding-left: 20px;}
|
|
@@ -300,7 +300,7 @@ try:
|
|
| 300 |
with gr.Column(scale=1):
|
| 301 |
file_input = gr.File(label="Upload Logs (CSV)", file_types=[".csv"])
|
| 302 |
submit_button = gr.Button("Analyze", variant="primary")
|
| 303 |
-
|
| 304 |
with gr.Column(scale=2):
|
| 305 |
with gr.Group(elem_classes="dashboard-container"):
|
| 306 |
gr.Markdown("<div class='dashboard-title'>Analysis Results (Step-by-Step)</div>")
|
|
@@ -314,27 +314,27 @@ try:
|
|
| 314 |
with gr.Group(elem_classes="dashboard-section"):
|
| 315 |
gr.Markdown("### Step 2: Log Preview")
|
| 316 |
preview_output = gr.Markdown()
|
| 317 |
-
|
| 318 |
# Step 3: Usage Chart
|
| 319 |
with gr.Group(elem_classes="dashboard-section"):
|
| 320 |
gr.Markdown("### Step 3: Usage Chart")
|
| 321 |
chart_output = gr.Plot()
|
| 322 |
-
|
| 323 |
# Step 4: Anomaly Detection
|
| 324 |
with gr.Group(elem_classes="dashboard-section"):
|
| 325 |
gr.Markdown("### Step 4: Anomaly Detection")
|
| 326 |
anomaly_output = gr.Markdown()
|
| 327 |
-
|
| 328 |
# Step 5: AMC Reminders
|
| 329 |
with gr.Group(elem_classes="dashboard-section"):
|
| 330 |
gr.Markdown("### Step 5: AMC Reminders")
|
| 331 |
amc_output = gr.Markdown()
|
| 332 |
-
|
| 333 |
# Step 6: Dashboard Insights
|
| 334 |
with gr.Group(elem_classes="dashboard-section"):
|
| 335 |
-
gr.Markdown("### Step 6:
|
| 336 |
insights_output = gr.Markdown()
|
| 337 |
-
|
| 338 |
# PDF Download
|
| 339 |
with gr.Group(elem_classes="dashboard-section"):
|
| 340 |
gr.Markdown("### Download Report")
|
|
@@ -359,96 +359,4 @@ if __name__ == "__main__":
|
|
| 359 |
except Exception as e:
|
| 360 |
logging.error(f"Failed to launch Gradio interface: {str(e)}")
|
| 361 |
print(f"Error launching app: {str(e)}")
|
| 362 |
-
raise e
|
| 363 |
-
</xArtifact>
|
| 364 |
-
|
| 365 |
-
### Key Changes Made
|
| 366 |
-
1. **Fixed Syntax Error**:
|
| 367 |
-
- Removed the invalid leading double quote (`"`) before `except Exception as e:` in the CSV loading section (around line 228).
|
| 368 |
-
- Corrected the syntax to ensure proper error handling:
|
| 369 |
-
```python
|
| 370 |
-
except Exception as e:
|
| 371 |
-
logging.error(f"Failed to load CSV: {str(e)}")
|
| 372 |
-
return f"Failed to load CSV: {str(e)}", None, None, None, None, None, None
|
| 373 |
-
```
|
| 374 |
-
- Fixed another syntax error in the timestamp conversion error message, replacing `error(e)` with `str(e)`.
|
| 375 |
-
|
| 376 |
-
2. **Preserved Functionality**:
|
| 377 |
-
- Retained all analysis functions (`summarize_logs`, `detect_anomalies`, `check_amc_reminders`, `generate_dashboard_insights`, `create_usage_chart`) unchanged.
|
| 378 |
-
- Kept the optional `reportlab` PDF generation with graceful fallback if `reportlab` is not installed.
|
| 379 |
-
- Maintained the Gradio interface layout and CSS styling.
|
| 380 |
-
- Ensured CSV file upload functionality without a row limit.
|
| 381 |
-
|
| 382 |
-
3. **Error Handling**:
|
| 383 |
-
- Fixed syntax errors in error messages (e.g., corrected `error(e)` to `str(e)`).
|
| 384 |
-
- Kept robust logging to diagnose issues, including CSV loading, timestamp conversion, and PDF generation.
|
| 385 |
-
|
| 386 |
-
4. **CSV Validation**:
|
| 387 |
-
- Retained validation for required columns (`device_id`, `log_type`, `status`, `timestamp`, `usage_hours`, `downtime`, `amc_date`).
|
| 388 |
-
- Corrected the log preview loop to use `df.head().iterrows()` consistently.
|
| 389 |
-
|
| 390 |
-
### Prerequisites
|
| 391 |
-
- Install required packages:
|
| 392 |
-
```bash
|
| 393 |
-
pip install gradio pandas plotly scikit-learn transformers torch
|
| 394 |
-
```
|
| 395 |
-
- For PDF generation (optional but recommended):
|
| 396 |
-
```bash
|
| 397 |
-
pip install reportlab
|
| 398 |
-
```
|
| 399 |
-
- No external tools (e.g., `wkhtmltopdf` or LaTeX) are required unless `reportlab` is installed.
|
| 400 |
-
|
| 401 |
-
### CSV File Requirements
|
| 402 |
-
- The CSV file must contain the columns: `device_id`, `log_type`, `status`, `timestamp`, `usage_hours`, `downtime`, and `amc_date`.
|
| 403 |
-
- Example CSV structure:
|
| 404 |
-
```csv
|
| 405 |
-
device_id,log_type,status,timestamp,usage_hours,downtime,amc_date
|
| 406 |
-
DEV001,Maintenance,Active,2025-06-01T10:00:00,5.5,0.2,2025-07-01
|
| 407 |
-
DEV002,Operation,Inactive,2025-06-02T12:00:00,3.0,1.5,2025-06-15
|
| 408 |
-
```
|
| 409 |
-
|
| 410 |
-
### How to Use
|
| 411 |
-
1. Install the required Python packages listed above. Install `reportlab` if you want PDF generation.
|
| 412 |
-
2. Save the code as `app.py` and run it:
|
| 413 |
-
```bash
|
| 414 |
-
python app.py
|
| 415 |
-
```
|
| 416 |
-
3. Open the Gradio interface in your browser (default: `http://0.0.0.0:7860`).
|
| 417 |
-
4. Upload a CSV file with the required columns and click "Analyze".
|
| 418 |
-
5. View the analysis results in the dashboard (summary, preview, chart, anomalies, AMC reminders, insights).
|
| 419 |
-
6. If `reportlab` is installed, download the PDF report from the "Download Report" section. If not, the PDF section will be empty, but other outputs will display.
|
| 420 |
-
|
| 421 |
-
### Troubleshooting
|
| 422 |
-
- **SyntaxError: unterminated string literal**:
|
| 423 |
-
- This error should now be resolved. If you encounter another syntax error, check for stray quotes or indentation issues in `app.py`. Ensure your editor uses 4 spaces for indentation and no mixed tabs/spaces.
|
| 424 |
-
|
| 425 |
-
- **ModuleNotFoundError: No module named 'reportlab'**:
|
| 426 |
-
- If you see a warning like `reportlab module not found. PDF generation will be disabled`, install `reportlab` using `pip install reportlab` or ignore it if PDF output is not needed.
|
| 427 |
-
|
| 428 |
-
- **CSV Parsing Error**:
|
| 429 |
-
- Ensure the CSV file has all required columns and valid data (e.g., `usage_hours` and `downtime` as numbers, `timestamp` and `amc_date` in a recognizable date format like `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM:SS`).
|
| 430 |
-
- Check the terminal for errors like `Missing required columns` or `Failed to load CSV`.
|
| 431 |
-
|
| 432 |
-
- **Gradio Interface Issues**:
|
| 433 |
-
- Ensure port 7860 is available and you’re accessing the correct URL.
|
| 434 |
-
- Check the terminal for errors like `Failed to initialize Gradio interface`.
|
| 435 |
-
|
| 436 |
-
- **Other Errors**:
|
| 437 |
-
- If the interface loads but no output appears, check the terminal for logged errors (e.g., `Failed to process file`).
|
| 438 |
-
- Share the specific error message or terminal output for further assistance.
|
| 439 |
-
|
| 440 |
-
- **Dependency Issues**:
|
| 441 |
-
- Verify all packages are installed using `pip list`. If you encounter version conflicts, use a virtual environment:
|
| 442 |
-
```bash
|
| 443 |
-
python -m venv env
|
| 444 |
-
source env/bin/activate # On Windows: env\Scripts\activate
|
| 445 |
-
pip install gradio pandas plotly scikit-learn transformers torch reportlab
|
| 446 |
-
```
|
| 447 |
-
|
| 448 |
-
### Notes
|
| 449 |
-
- **PDF Generation**: If `reportlab` is not installed, PDF generation is skipped, and a warning is logged. Install `reportlab` for full functionality.
|
| 450 |
-
- **Chart in PDF**: The chart is excluded from the PDF due to complexity in rendering Plotly charts. If needed, I can add code to generate a static image using `plotly.io` and embed it.
|
| 451 |
-
- **Performance**: Large CSV files may slow processing. The anomaly detection function samples to 5,000 rows for larger datasets to prevent memory issues.
|
| 452 |
-
- **Further Issues**: If you encounter other errors, please share the full traceback or terminal output, and I’ll provide a targeted fix.
|
| 453 |
-
|
| 454 |
-
If you need additional features (e.g., chart inclusion in the PDF, custom PDF styling, or stricter CSV validation) or face another error, please let me know with details!
|
|
|
|
| 252 |
preview_lines = ["Step 2: Log Preview (First 5 Rows)"]
|
| 253 |
for idx, row in df.head().iterrows():
|
| 254 |
preview_lines.append(f"Row {idx + 1}: Device ID: {row['device_id']}, Log Type: {row['log_type']}, Status: {row['status']}, Timestamp: {row['timestamp']}, Usage Hours: {row['usage_hours']}, Downtime: {row['downtime']}, AMC Date: {row['amc_date']}")
|
| 255 |
+
preview = "\ scorer_lines)
|
| 256 |
else:
|
| 257 |
+
preview.append("Step 2: Log Preview\nNo data available.")
|
| 258 |
|
| 259 |
# Step 3: Usage Chart
|
| 260 |
chart = create_usage_chart(df, progress)
|
|
|
|
| 265 |
# Step 5: AMC Reminders
|
| 266 |
amc_reminders = f"Step 4: AMC Reminders\n{check_amc_reminders(df, datetime.now(), progress)}"
|
| 267 |
|
| 268 |
+
# Step 6: Insights
|
| 269 |
insights = f"Step 5: Dashboard Insights (AI)\n{generate_dashboard_insights(df, progress)}"
|
| 270 |
|
| 271 |
# Generate PDF if available
|
|
|
|
| 274 |
if pdf_file is None and reportlab_available:
|
| 275 |
logging.warning("PDF generation failed, but analysis completed")
|
| 276 |
elif pdf_file is None:
|
| 277 |
+
logging.info("PDF generation skipped due to missing reportlab")
|
| 278 |
|
| 279 |
progress(1.0, "Processing complete!")
|
| 280 |
return summary, preview, chart, anomalies, amc_reminders, insights, pdf_file
|
| 281 |
except Exception as e:
|
| 282 |
logging.error(f"Failed to process file: {str(e)}")
|
| 283 |
+
return f"Error processing file: {error(e)}", None, None, None, None, None, None
|
| 284 |
|
| 285 |
# Gradio Interface
|
| 286 |
try:
|
| 287 |
+
logging.info("Initializing Gradio interface...")
|
| 288 |
with gr.Blocks(css="""
|
| 289 |
+
.dashboard-container {border: 1px solid #e0e0e0; padding: 10px; border-radius: 5px;}
|
| 290 |
.dashboard-title {font-size: 24px; font-weight: bold; margin-bottom: 5px;}
|
| 291 |
+
.dashboard-section {margin-bottom: 20px;}
|
| 292 |
.dashboard-section h3 {font-size: 18px; margin-bottom: 2px;}
|
| 293 |
.dashboard-section p {margin: 1px 0; line-height: 1.2;}
|
| 294 |
.dashboard-section ul {margin: 2px 0; padding-left: 20px;}
|
|
|
|
| 300 |
with gr.Column(scale=1):
|
| 301 |
file_input = gr.File(label="Upload Logs (CSV)", file_types=[".csv"])
|
| 302 |
submit_button = gr.Button("Analyze", variant="primary")
|
| 303 |
+
|
| 304 |
with gr.Column(scale=2):
|
| 305 |
with gr.Group(elem_classes="dashboard-container"):
|
| 306 |
gr.Markdown("<div class='dashboard-title'>Analysis Results (Step-by-Step)</div>")
|
|
|
|
| 314 |
with gr.Group(elem_classes="dashboard-section"):
|
| 315 |
gr.Markdown("### Step 2: Log Preview")
|
| 316 |
preview_output = gr.Markdown()
|
| 317 |
+
|
| 318 |
# Step 3: Usage Chart
|
| 319 |
with gr.Group(elem_classes="dashboard-section"):
|
| 320 |
gr.Markdown("### Step 3: Usage Chart")
|
| 321 |
chart_output = gr.Plot()
|
| 322 |
+
|
| 323 |
# Step 4: Anomaly Detection
|
| 324 |
with gr.Group(elem_classes="dashboard-section"):
|
| 325 |
gr.Markdown("### Step 4: Anomaly Detection")
|
| 326 |
anomaly_output = gr.Markdown()
|
| 327 |
+
|
| 328 |
# Step 5: AMC Reminders
|
| 329 |
with gr.Group(elem_classes="dashboard-section"):
|
| 330 |
gr.Markdown("### Step 5: AMC Reminders")
|
| 331 |
amc_output = gr.Markdown()
|
| 332 |
+
|
| 333 |
# Step 6: Dashboard Insights
|
| 334 |
with gr.Group(elem_classes="dashboard-section"):
|
| 335 |
+
gr.Markdown("### Step 6: Insights (AI)")
|
| 336 |
insights_output = gr.Markdown()
|
| 337 |
+
|
| 338 |
# PDF Download
|
| 339 |
with gr.Group(elem_classes="dashboard-section"):
|
| 340 |
gr.Markdown("### Download Report")
|
|
|
|
| 359 |
except Exception as e:
|
| 360 |
logging.error(f"Failed to launch Gradio interface: {str(e)}")
|
| 361 |
print(f"Error launching app: {str(e)}")
|
| 362 |
+
raise e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|