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("