Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,214 +1,173 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
from datetime import datetime
|
| 4 |
-
import
|
| 5 |
-
import io
|
| 6 |
from transformers import pipeline
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
# Configure logging
|
| 9 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 10 |
|
| 11 |
-
# Load Hugging Face model
|
| 12 |
try:
|
| 13 |
-
logging.info("
|
| 14 |
-
summarizer = pipeline("text2text-generation", model="t5-
|
| 15 |
-
logging.info("
|
| 16 |
except Exception as e:
|
| 17 |
logging.error(f"Failed to load model: {str(e)}")
|
| 18 |
raise e
|
| 19 |
|
| 20 |
-
#
|
| 21 |
def summarize_logs(df, lab_name, start_date, end_date):
|
| 22 |
try:
|
| 23 |
total_devices = df["device_id"].nunique()
|
|
|
|
| 24 |
most_used = df.groupby("device_id")["usage_hours"].sum().idxmax() if not df.empty else "N/A"
|
|
|
|
|
|
|
| 25 |
prompt = (
|
| 26 |
-
f"Summarize maintenance logs for lab {lab_name} "
|
| 27 |
f"from {start_date} to {end_date}. "
|
| 28 |
-
f"
|
|
|
|
| 29 |
)
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
logging.info("Summary generated: %s", summary)
|
| 33 |
return summary
|
| 34 |
except Exception as e:
|
| 35 |
logging.error(f"Summary generation failed: {str(e)}")
|
| 36 |
-
return
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
def
|
| 40 |
try:
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
| 49 |
)
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
except Exception as e:
|
| 53 |
-
logging.error(f"
|
| 54 |
-
return
|
| 55 |
|
| 56 |
-
#
|
| 57 |
-
def
|
| 58 |
try:
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
| 68 |
else:
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
"- Routine Maintenance: No devices exceed usage thresholds.\n"
|
| 72 |
-
"- Monitor Trends: Track usage patterns."
|
| 73 |
-
)
|
| 74 |
-
logging.info("Suggested actions generated: %s", actions)
|
| 75 |
-
return actions
|
| 76 |
-
except Exception as e:
|
| 77 |
-
logging.error(f"Suggested actions generation failed: {str(e)}")
|
| 78 |
-
return f"Error generating suggested actions: {str(e)}"
|
| 79 |
|
| 80 |
-
|
| 81 |
-
def generate_maintenance_report(df, lab_name, start_date, end_date):
|
| 82 |
-
try:
|
| 83 |
-
report_data = {
|
| 84 |
-
"Lab Name": [lab_name] * len(df),
|
| 85 |
-
"Device ID": df["device_id"],
|
| 86 |
-
"Usage Hours": df["usage_hours"],
|
| 87 |
-
"Timestamp": df["timestamp"],
|
| 88 |
-
"Report Period Start": [start_date] * len(df),
|
| 89 |
-
"Report Period End": [end_date] * len(df)
|
| 90 |
-
}
|
| 91 |
-
report_df = pd.DataFrame(report_data)
|
| 92 |
-
output = io.StringIO()
|
| 93 |
-
report_df.to_csv(output, index=False)
|
| 94 |
-
output.seek(0)
|
| 95 |
-
logging.info("Maintenance report generated")
|
| 96 |
-
return output.getvalue(), f"{lab_name}_maintenance_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
|
| 97 |
-
except Exception as e:
|
| 98 |
-
logging.error(f"Report generation failed: {str(e)}")
|
| 99 |
-
return None, None
|
| 100 |
|
| 101 |
-
#
|
| 102 |
-
def process_logs(file_obj, lab_site, start_date, end_date):
|
| 103 |
-
try:
|
| 104 |
-
# Fallback data if no file is uploaded
|
| 105 |
-
if not file_obj:
|
| 106 |
-
logging.warning("No file uploaded, using sample data")
|
| 107 |
-
df = pd.DataFrame({
|
| 108 |
-
"device_id": ["Device1", "Device2", "Device1"],
|
| 109 |
-
"usage_hours": [5.5, 3.2, 4.0],
|
| 110 |
-
"timestamp": ["2025-05-01 10:00:00", "2025-05-02 12:00:00", "2025-05-03 14:00:00"]
|
| 111 |
-
})
|
| 112 |
-
df["timestamp"] = pd.to_datetime(df["timestamp"])
|
| 113 |
-
else:
|
| 114 |
-
logging.info(f"Processing file: {file_obj.name}")
|
| 115 |
-
if file_obj.name.endswith(".json"):
|
| 116 |
-
df = pd.read_json(file_obj)
|
| 117 |
-
elif file_obj.name.endswith(".csv"):
|
| 118 |
-
df = pd.read_csv(file_obj)
|
| 119 |
-
else:
|
| 120 |
-
logging.error("Unsupported file format")
|
| 121 |
-
return "Upload a CSV or JSON file.", None, None, None, None
|
| 122 |
-
|
| 123 |
-
logging.info(f"Loaded data with {len(df)} rows")
|
| 124 |
-
|
| 125 |
-
# Filter by date range
|
| 126 |
try:
|
| 127 |
df["timestamp"] = pd.to_datetime(df["timestamp"])
|
| 128 |
start_date = pd.to_datetime(start_date)
|
| 129 |
end_date = pd.to_datetime(end_date)
|
| 130 |
df = df[(df["timestamp"] >= start_date) & (df["timestamp"] <= end_date)]
|
| 131 |
-
logging.info(f"Filtered to {len(df)} rows")
|
| 132 |
-
if df.empty:
|
| 133 |
-
return "No data in date range.", None, None, None, None
|
| 134 |
except Exception as e:
|
| 135 |
logging.error(f"Date filtering failed: {str(e)}")
|
| 136 |
-
return f"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
-
text_response = generate_text_response(df, lab_site, start_date, end_date)
|
| 139 |
-
maintenance_report, report_filename = generate_maintenance_report(df, lab_site, start_date, end_date)
|
| 140 |
-
suggested_actions = generate_suggested_actions(df)
|
| 141 |
summary = summarize_logs(df, lab_site, start_date, end_date)
|
|
|
|
|
|
|
| 142 |
|
| 143 |
-
return
|
| 144 |
except Exception as e:
|
| 145 |
-
logging.error(f"
|
| 146 |
-
return f"
|
| 147 |
-
|
| 148 |
-
# Gradio Interface
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
.
|
| 153 |
-
.
|
| 154 |
-
.
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
gr.Markdown("
|
| 159 |
-
gr.Markdown("Upload a CSV or JSON file to generate a maintenance report. Use format: device_id, usage_hours, timestamp.")
|
| 160 |
|
| 161 |
with gr.Row():
|
| 162 |
with gr.Column(scale=1):
|
| 163 |
file_input = gr.File(label="Upload Logs (CSV or JSON)", file_types=[".csv", ".json"])
|
| 164 |
lab_site_input = gr.Textbox(label="Lab Site", placeholder="e.g., Lab A")
|
| 165 |
-
start_date_input = gr.Textbox(label="Start Date (YYYY-MM-DD)", placeholder="e.g., 2025-
|
| 166 |
-
end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", placeholder="e.g., 2025-
|
| 167 |
-
submit_button = gr.Button("
|
| 168 |
|
| 169 |
with gr.Column(scale=2):
|
| 170 |
-
with gr.Group(elem_classes="
|
| 171 |
-
gr.Markdown("<div class='
|
| 172 |
-
|
| 173 |
-
with gr.Row():
|
| 174 |
-
with gr.Column():
|
| 175 |
-
with gr.Group(elem_classes="report-section"):
|
| 176 |
-
gr.Markdown("### Report Overview")
|
| 177 |
-
text_response_output = gr.Textbox(lines=6, show_copy_button=True, label="")
|
| 178 |
|
| 179 |
with gr.Row():
|
| 180 |
-
with gr.Column():
|
| 181 |
-
with gr.Group(elem_classes="
|
| 182 |
-
gr.Markdown("###
|
| 183 |
-
|
| 184 |
|
| 185 |
with gr.Row():
|
| 186 |
-
with gr.Column():
|
| 187 |
-
with gr.Group(elem_classes="
|
| 188 |
-
gr.Markdown("###
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
gr.Markdown(
|
| 195 |
-
summary_output = gr.Textbox(lines=6, show_copy_button=True, label="")
|
| 196 |
|
| 197 |
submit_button.click(
|
| 198 |
fn=process_logs,
|
| 199 |
inputs=[file_input, lab_site_input, start_date_input, end_date_input],
|
| 200 |
-
outputs=[
|
| 201 |
)
|
| 202 |
-
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
if __name__ == "__main__":
|
| 206 |
try:
|
| 207 |
-
logging.info("
|
| 208 |
-
iface =
|
| 209 |
-
|
| 210 |
-
logging.info("Interface launched successfully")
|
| 211 |
except Exception as e:
|
| 212 |
-
logging.error(f"Failed to launch interface: {str(e)}")
|
| 213 |
print(f"Error launching app: {str(e)}")
|
| 214 |
raise e
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
from datetime import datetime
|
| 4 |
+
import json
|
|
|
|
| 5 |
from transformers import pipeline
|
| 6 |
+
import logging
|
| 7 |
+
import os
|
| 8 |
+
import plotly.express as px
|
| 9 |
|
| 10 |
+
# Configure logging for debugging
|
| 11 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 12 |
|
| 13 |
+
# Load Hugging Face summarization model
|
| 14 |
try:
|
| 15 |
+
logging.info("Attempting to load Hugging Face model...")
|
| 16 |
+
summarizer = pipeline("text2text-generation", model="google/flan-t5-base")
|
| 17 |
+
logging.info("Hugging Face model loaded successfully")
|
| 18 |
except Exception as e:
|
| 19 |
logging.error(f"Failed to load model: {str(e)}")
|
| 20 |
raise e
|
| 21 |
|
| 22 |
+
# Format summary prompt and generate report
|
| 23 |
def summarize_logs(df, lab_name, start_date, end_date):
|
| 24 |
try:
|
| 25 |
total_devices = df["device_id"].nunique()
|
| 26 |
+
avg_uptime = "97%" # Placeholder
|
| 27 |
most_used = df.groupby("device_id")["usage_hours"].sum().idxmax() if not df.empty else "N/A"
|
| 28 |
+
downtime_events = 3 # Placeholder
|
| 29 |
+
|
| 30 |
prompt = (
|
| 31 |
+
f"Summarize maintenance and usage logs for lab {lab_name} "
|
| 32 |
f"from {start_date} to {end_date}. "
|
| 33 |
+
f"There were {total_devices} devices. "
|
| 34 |
+
f"The most used device was {most_used}."
|
| 35 |
)
|
| 36 |
+
summary = summarizer(prompt, max_length=200, do_sample=False)[0]["generated_text"]
|
| 37 |
+
logging.info("Summary generated successfully")
|
|
|
|
| 38 |
return summary
|
| 39 |
except Exception as e:
|
| 40 |
logging.error(f"Summary generation failed: {str(e)}")
|
| 41 |
+
return "Failed to generate summary."
|
| 42 |
|
| 43 |
+
# Create a bar chart for usage hours per device
|
| 44 |
+
def create_usage_chart(df):
|
| 45 |
try:
|
| 46 |
+
usage_data = df.groupby("device_id")["usage_hours"].sum().reset_index()
|
| 47 |
+
fig = px.bar(
|
| 48 |
+
usage_data,
|
| 49 |
+
x="device_id",
|
| 50 |
+
y="usage_hours",
|
| 51 |
+
title="Usage Hours per Device",
|
| 52 |
+
labels={"device_id": "Device ID", "usage_hours": "Usage Hours"},
|
| 53 |
+
color="usage_hours",
|
| 54 |
+
color_continuous_scale="Blues"
|
| 55 |
)
|
| 56 |
+
fig.update_layout(
|
| 57 |
+
title_font_size=16,
|
| 58 |
+
margin=dict(l=20, r=20, t=40, b=20),
|
| 59 |
+
plot_bgcolor="white",
|
| 60 |
+
paper_bgcolor="white",
|
| 61 |
+
font=dict(size=12)
|
| 62 |
+
)
|
| 63 |
+
return fig
|
| 64 |
except Exception as e:
|
| 65 |
+
logging.error(f"Failed to create usage chart: {str(e)}")
|
| 66 |
+
return None
|
| 67 |
|
| 68 |
+
# Main Gradio function
|
| 69 |
+
def process_logs(file_obj, lab_site, start_date, end_date):
|
| 70 |
try:
|
| 71 |
+
if file_obj is None:
|
| 72 |
+
logging.warning("No file uploaded, returning empty results")
|
| 73 |
+
return "No file uploaded.", "No data to preview.", None
|
| 74 |
+
|
| 75 |
+
# Read file based on extension
|
| 76 |
+
file_name = file_obj.name if hasattr(file_obj, 'name') else file_obj
|
| 77 |
+
logging.info(f"Processing file: {file_name}")
|
| 78 |
+
|
| 79 |
+
if file_name.endswith(".json"):
|
| 80 |
+
df = pd.read_json(file_name)
|
| 81 |
+
elif file_name.endswith(".csv"):
|
| 82 |
+
df = pd.read_csv(file_name)
|
| 83 |
else:
|
| 84 |
+
logging.error("Unsupported file format")
|
| 85 |
+
return "Unsupported file format. Please upload a CSV or JSON file.", None, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
logging.info(f"File loaded successfully with {len(df)} rows")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
# Convert timestamp to datetime and filter by date range
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
try:
|
| 91 |
df["timestamp"] = pd.to_datetime(df["timestamp"])
|
| 92 |
start_date = pd.to_datetime(start_date)
|
| 93 |
end_date = pd.to_datetime(end_date)
|
| 94 |
df = df[(df["timestamp"] >= start_date) & (df["timestamp"] <= end_date)]
|
| 95 |
+
logging.info(f"Filtered to {len(df)} rows within date range {start_date} to {end_date}")
|
|
|
|
|
|
|
| 96 |
except Exception as e:
|
| 97 |
logging.error(f"Date filtering failed: {str(e)}")
|
| 98 |
+
return f"Failed to filter data by date: {str(e)}", None, None
|
| 99 |
+
|
| 100 |
+
if df.empty:
|
| 101 |
+
logging.warning("No data within the specified date range")
|
| 102 |
+
return "No data available for the specified date range.", "No data to preview.", None
|
| 103 |
|
|
|
|
|
|
|
|
|
|
| 104 |
summary = summarize_logs(df, lab_site, start_date, end_date)
|
| 105 |
+
preview = df.head().to_markdown() if not df.empty else "No data available."
|
| 106 |
+
chart = create_usage_chart(df)
|
| 107 |
|
| 108 |
+
return summary, preview, chart
|
| 109 |
except Exception as e:
|
| 110 |
+
logging.error(f"Failed to process file: {str(e)}")
|
| 111 |
+
return f"Failed to process file: {str(e)}", None, None
|
| 112 |
+
|
| 113 |
+
# Gradio Interface with Dashboard Layout
|
| 114 |
+
try:
|
| 115 |
+
logging.info("Initializing Gradio Blocks interface...")
|
| 116 |
+
with gr.Blocks(css="""
|
| 117 |
+
.dashboard-container {border: 1px solid #e0e0e0; padding: 10px; border-radius: 5px; background-color: #f9f9f9;}
|
| 118 |
+
.dashboard-title {font-size: 24px; font-weight: bold; margin-bottom: 10px;}
|
| 119 |
+
.dashboard-section {margin-bottom: 15px;}
|
| 120 |
+
.dashboard-section h3 {font-size: 18px; margin-bottom: 5px;}
|
| 121 |
+
""") as iface:
|
| 122 |
+
gr.Markdown("<h1>LabOps Log Analyzer Dashboard (Hugging Face AI)</h1>")
|
| 123 |
+
gr.Markdown("Upload a CSV or JSON file containing lab equipment logs to analyze usage.")
|
|
|
|
| 124 |
|
| 125 |
with gr.Row():
|
| 126 |
with gr.Column(scale=1):
|
| 127 |
file_input = gr.File(label="Upload Logs (CSV or JSON)", file_types=[".csv", ".json"])
|
| 128 |
lab_site_input = gr.Textbox(label="Lab Site", placeholder="e.g., Lab A")
|
| 129 |
+
start_date_input = gr.Textbox(label="Start Date (YYYY-MM-DD)", placeholder="e.g., 2025-01-01")
|
| 130 |
+
end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", placeholder="e.g., 2025-01-31")
|
| 131 |
+
submit_button = gr.Button("Submit", variant="primary")
|
| 132 |
|
| 133 |
with gr.Column(scale=2):
|
| 134 |
+
with gr.Group(elem_classes="dashboard-container"):
|
| 135 |
+
gr.Markdown("<div class='dashboard-title'>Analysis Dashboard</div>")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
with gr.Row():
|
| 138 |
+
with gr.Column(scale=1):
|
| 139 |
+
with gr.Group(elem_classes="dashboard-section"):
|
| 140 |
+
gr.Markdown("### Summary Report")
|
| 141 |
+
summary_output = gr.Textbox(lines=5)
|
| 142 |
|
| 143 |
with gr.Row():
|
| 144 |
+
with gr.Column(scale=1):
|
| 145 |
+
with gr.Group(elem_classes="dashboard-section"):
|
| 146 |
+
gr.Markdown("### Usage Chart")
|
| 147 |
+
chart_output = gr.Plot()
|
| 148 |
+
|
| 149 |
+
with gr.Column(scale=1):
|
| 150 |
+
with gr.Group(elem_classes="dashboard-section"):
|
| 151 |
+
gr.Markdown("### Log Preview")
|
| 152 |
+
preview_output = gr.Markdown()
|
|
|
|
| 153 |
|
| 154 |
submit_button.click(
|
| 155 |
fn=process_logs,
|
| 156 |
inputs=[file_input, lab_site_input, start_date_input, end_date_input],
|
| 157 |
+
outputs=[summary_output, preview_output, chart_output]
|
| 158 |
)
|
| 159 |
+
|
| 160 |
+
logging.info("Gradio interface initialized successfully")
|
| 161 |
+
except Exception as e:
|
| 162 |
+
logging.error(f"Failed to initialize Gradio interface: {str(e)}")
|
| 163 |
+
raise e
|
| 164 |
|
| 165 |
if __name__ == "__main__":
|
| 166 |
try:
|
| 167 |
+
logging.info("Launching Gradio interface...")
|
| 168 |
+
iface.launch(server_name="0.0.0.0", server_port=7860, debug=True, share=False)
|
| 169 |
+
logging.info("Gradio interface launched successfully")
|
|
|
|
| 170 |
except Exception as e:
|
| 171 |
+
logging.error(f"Failed to launch Gradio interface: {str(e)}")
|
| 172 |
print(f"Error launching app: {str(e)}")
|
| 173 |
raise e
|