Spaces:
Runtime error
Runtime error
File size: 4,547 Bytes
72acb0f f8f4bab 625bc0c ca56d72 f8f4bab 72acb0f f8f4bab 72acb0f f8f4bab ca56d72 f8f4bab ca56d72 f8f4bab ca56d72 72acb0f ca56d72 625bc0c f8f4bab ca56d72 f8f4bab ca56d72 625bc0c ca56d72 f8f4bab 625bc0c ca56d72 f8f4bab 625bc0c |
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 |
import gradio as gr
from datetime import datetime
from risk_model import predict_risk
import pandas as pd
import plotly.express as px
import logging
import os
# Setup logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
# Store prediction history
history = []
def gradio_predict_risk(temperature, duration):
"""
Makes predictions and updates the history of predictions.
Args:
temperature (float): Temperature in °C
duration (float): Duration in minutes
Returns:
tuple: (prediction output, history table, history plot)
"""
try:
# Validate inputs
temperature = float(temperature)
duration = float(duration)
# Make prediction
risk_level, risk_score, alert = predict_risk(temperature, duration)
# Generate timestamp
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Update history
history.append({
"timestamp": timestamp,
"temperature": temperature,
"duration": duration,
"risk_level": risk_level,
"risk_score": risk_score,
"alert": alert
})
# Keep only the last 10 predictions
if len(history) > 10:
history.pop(0)
# Format prediction output
prediction_output = (
f"**Risk Level**: {risk_level}\n"
f"**Risk Score**: {risk_score}% (Model Confidence)\n"
f"**Alert**: {alert}\n"
f"**Timestamp**: {timestamp}"
)
# Format history output
history_df = pd.DataFrame(history)
history_output = history_df.to_markdown(index=False) if not history_df.empty else "No predictions yet."
# Generate history plot
history_plot = create_history_plot(history_df)
logger.info(f"Prediction made: Temperature={temperature}°C, Duration={duration} min, Result={prediction_output}")
return prediction_output, history_output, history_plot
except ValueError as e:
logger.error(f"Input error: {e}")
return f"Error: {e}", "No predictions yet.", None
except Exception as e:
logger.error(f"Unexpected error: {e}")
return f"Error: An unexpected error occurred: {e}", "No predictions yet.", None
def create_history_plot(history_df):
"""
Creates a scatter plot of prediction history using Plotly.
Args:
history_df (pd.DataFrame): DataFrame containing prediction history
Returns:
plotly.graph_objects.Figure: Plotly figure for scatter plot
"""
if history_df.empty:
return None
# Define colors for risk levels
colors = {
"Low": "#4CAF50", # Green
"Moderate": "#FFC107", # Amber
"High": "#F44336" # Red
}
# Create scatter plot
fig = px.scatter(
history_df,
x="temperature",
y="duration",
color="risk_level",
color_discrete_map=colors,
title="Prediction History",
labels={"temperature": "Temperature (°C)", "duration": "Duration (min)"},
hover_data=["timestamp", "risk_score", "alert"]
)
# Update layout
fig.update_layout(
xaxis_range=[50, 200],
yaxis_range=[5, 120],
showlegend=True,
template="plotly_dark" # Use dark theme for compatibility
)
return fig
# Create Gradio interface
with gr.Blocks(theme=gr.themes.Soft()) as iface:
gr.Markdown("# Heating Mantle Risk Prediction")
gr.Markdown("Enter temperature and duration to predict the risk level of the heating mantle operation.")
with gr.Row():
temp_input = gr.Slider(minimum=50, maximum=200, value=100, label="Temperature (°C)", step=1)
duration_input = gr.Slider(minimum=5, maximum=120, value=30, label="Duration (min)", step=1)
predict_button = gr.Button("Predict Risk")
with gr.Row():
with gr.Column():
prediction_output = gr.Textbox(label="Prediction Result", lines=5)
history_output = gr.Textbox(label="Prediction History (Last 10)", lines=10)
with gr.Column():
history_plot = gr.Plot(label="Prediction History Plot")
predict_button.click(
fn=gradio_predict_risk,
inputs=[temp_input, duration_input],
outputs=[prediction_output, history_output, history_plot]
) |