File size: 7,452 Bytes
1056e41
20b0648
1056e41
d2edd75
1056e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28b9a07
1056e41
 
54632a4
1056e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2edd75
4385ddd
1056e41
 
d190ea7
1056e41
 
 
d2edd75
1056e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2edd75
1056e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4385ddd
d2edd75
1056e41
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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