neerajkalyank's picture
Update app.py
625bc0c verified
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]
)