Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import pandas as pd | |
| from datetime import datetime | |
| import json | |
| from transformers import pipeline | |
| import logging | |
| import os | |
| import plotly.express as px | |
| # Configure logging for debugging | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
| # Load Hugging Face summarization model | |
| try: | |
| logging.info("Attempting to load Hugging Face model...") | |
| summarizer = pipeline("text2text-generation", model="google/flan-t5-base") | |
| logging.info("Hugging Face model loaded successfully") | |
| except Exception as e: | |
| logging.error(f"Failed to load model: {str(e)}") | |
| raise e | |
| # Format summary prompt and generate report | |
| def summarize_logs(df, lab_name, start_date, end_date): | |
| try: | |
| total_devices = df["device_id"].nunique() | |
| avg_uptime = "97%" # Placeholder | |
| most_used = df.groupby("device_id")["usage_hours"].sum().idxmax() if not df.empty else "N/A" | |
| downtime_events = 3 # Placeholder | |
| prompt = ( | |
| f"Summarize maintenance and usage logs for lab {lab_name} " | |
| f"from {start_date} to {end_date}. " | |
| f"There were {total_devices} devices. " | |
| f"The most used device was {most_used}." | |
| ) | |
| summary = summarizer(prompt, max_length=200, do_sample=False)[0]["generated_text"] | |
| logging.info("Summary generated successfully") | |
| return summary | |
| except Exception as e: | |
| logging.error(f"Summary generation failed: {str(e)}") | |
| return "Failed to generate summary." | |
| # Create a bar chart for usage hours per device | |
| def create_usage_chart(df): | |
| try: | |
| usage_data = df.groupby("device_id")["usage_hours"].sum().reset_index() | |
| fig = px.bar( | |
| usage_data, | |
| x="device_id", | |
| y="usage_hours", | |
| title="Usage Hours per Device", | |
| labels={"device_id": "Device ID", "usage_hours": "Usage Hours"}, | |
| color="usage_hours", | |
| color_continuous_scale="Blues" | |
| ) | |
| fig.update_layout( | |
| title_font_size=16, | |
| margin=dict(l=20, r=20, t=40, b=20), | |
| plot_bgcolor="white", | |
| paper_bgcolor="white", | |
| font=dict(size=12) | |
| ) | |
| return fig | |
| except Exception as e: | |
| logging.error(f"Failed to create usage chart: {str(e)}") | |
| return None | |
| # Main Gradio function | |
| def process_logs(file_obj, lab_site, start_date, end_date): | |
| try: | |
| if file_obj is None: | |
| logging.warning("No file uploaded, returning empty results") | |
| return "No file uploaded.", "No data to preview.", None | |
| # Read file based on extension | |
| file_name = file_obj.name if hasattr(file_obj, 'name') else file_obj | |
| logging.info(f"Processing file: {file_name}") | |
| if file_name.endswith(".json"): | |
| df = pd.read_json(file_name) | |
| elif file_name.endswith(".csv"): | |
| df = pd.read_csv(file_name) | |
| else: | |
| logging.error("Unsupported file format") | |
| return "Unsupported file format. Please upload a CSV or JSON file.", None, None | |
| logging.info(f"File loaded successfully with {len(df)} rows") | |
| # Convert timestamp to datetime and filter by date range | |
| try: | |
| df["timestamp"] = pd.to_datetime(df["timestamp"]) | |
| start_date = pd.to_datetime(start_date) | |
| end_date = pd.to_datetime(end_date) | |
| df = df[(df["timestamp"] >= start_date) & (df["timestamp"] <= end_date)] | |
| logging.info(f"Filtered to {len(df)} rows within date range {start_date} to {end_date}") | |
| except Exception as e: | |
| logging.error(f"Date filtering failed: {str(e)}") | |
| return f"Failed to filter data by date: {str(e)}", None, None | |
| if df.empty: | |
| logging.warning("No data within the specified date range") | |
| return "No data available for the specified date range.", "No data to preview.", None | |
| summary = summarize_logs(df, lab_site, start_date, end_date) | |
| preview = df.head().to_markdown() if not df.empty else "No data available." | |
| chart = create_usage_chart(df) | |
| return summary, preview, chart | |
| except Exception as e: | |
| logging.error(f"Failed to process file: {str(e)}") | |
| return f"Failed to process file: {str(e)}", None, None | |
| # Gradio Interface with Dashboard Layout | |
| try: | |
| logging.info("Initializing Gradio Blocks interface...") | |
| with gr.Blocks(css=""" | |
| .dashboard-container {border: 1px solid #e0e0e0; padding: 10px; border-radius: 5px; background-color: #f9f9f9;} | |
| .dashboard-title {font-size: 24px; font-weight: bold; margin-bottom: 10px;} | |
| .dashboard-section {margin-bottom: 15px;} | |
| .dashboard-section h3 {font-size: 18px; margin-bottom: 5px;} | |
| """) as iface: | |
| gr.Markdown("<h1>LabOps Log Analyzer Dashboard (Hugging Face AI)</h1>") | |
| gr.Markdown("Upload a CSV or JSON file containing lab equipment logs to analyze usage.") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| file_input = gr.File(label="Upload Logs (CSV or JSON)", file_types=[".csv", ".json"]) | |
| lab_site_input = gr.Textbox(label="Lab Site", placeholder="e.g., Lab A") | |
| start_date_input = gr.Textbox(label="Start Date (YYYY-MM-DD)", placeholder="e.g., 2025-01-01") | |
| end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", placeholder="e.g., 2025-01-31") | |
| submit_button = gr.Button("Submit", variant="primary") | |
| with gr.Column(scale=2): | |
| with gr.Group(elem_classes="dashboard-container"): | |
| gr.Markdown("<div class='dashboard-title'>Analysis Dashboard</div>") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| with gr.Group(elem_classes="dashboard-section"): | |
| gr.Markdown("### Summary Report") | |
| summary_output = gr.Textbox(lines=5) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| with gr.Group(elem_classes="dashboard-section"): | |
| gr.Markdown("### Usage Chart") | |
| chart_output = gr.Plot() | |
| with gr.Column(scale=1): | |
| with gr.Group(elem_classes="dashboard-section"): | |
| gr.Markdown("### Log Preview") | |
| preview_output = gr.Markdown() | |
| submit_button.click( | |
| fn=process_logs, | |
| inputs=[file_input, lab_site_input, start_date_input, end_date_input], | |
| outputs=[summary_output, preview_output, chart_output] | |
| ) | |
| logging.info("Gradio interface initialized successfully") | |
| except Exception as e: | |
| logging.error(f"Failed to initialize Gradio interface: {str(e)}") | |
| raise e | |
| if __name__ == "__main__": | |
| try: | |
| logging.info("Launching Gradio interface...") | |
| iface.launch(server_name="0.0.0.0", server_port=7860, debug=True, share=False) | |
| logging.info("Gradio interface launched successfully") | |
| except Exception as e: | |
| logging.error(f"Failed to launch Gradio interface: {str(e)}") | |
| print(f"Error launching app: {str(e)}") | |
| raise e |