pankilshah's picture
Update app.py
04f6faa verified
import gradio as gr
import pandas as pd
import numpy as np
import joblib
import logging
from pathlib import Path
import uuid
# Create a logs directory if it doesn't exist
Path("logs").mkdir(exist_ok=True)
log_file_path = "logs/predictions.log"
# Configure logging to write to a log file
logging.basicConfig(
filename=log_file_path,
level=logging.WARNING,
# format="%(asctime)s - ID: %(uuid)s - age: %age()s"
)
# Load your model
model = joblib.load("model.joblib")
# Define the function to process inputs
def predict_charges(i_age, i_sex, i_bmi, i_children, i_smoker, i_region):
# Create a DataFrame with the inputs
input_data = pd.DataFrame({
"age": [i_age],
"sex": [i_sex],
"bmi": [i_bmi],
"children": [i_children],
"smoker": [i_smoker],
"region": [i_region]
})
# Model the data to predict the output. Then 'Return' the output.
prediction = model.predict(input_data)[0]
# Log the inputs and the prediction
logging.warning(
# f"ID: {uuid.uuid4()} | age: {i_age} | sex: {i_sex} | bmi: {i_bmi} | children: {i_children} | smoker: {i_smoker} | region: {i_region} | prediction: {prediction}"
# f"{uuid.uuid4()} | {i_age} | {i_sex} | {i_bmi} | {i_children} | {i_smoker} | {i_region} | {prediction}"
f"{prediction}"
)
return prediction
# Function to download the log file
def download_log_file():
return log_file_path
# def download_log_file():
# log_file_path = Path("logs/predictions.log")
# if log_file_path.exists():
# return log_file_path
# else:
# # If log file doesn't exist, create a placeholder to download
# log_file_path.write_text("No logs available yet.")
# return log_file_path
# Gradio interface setup
ageIn = gr.Number(label="Enter Age")
sexIn = gr.Radio(["female","male"], label="Select Sex")
bmiIn = gr.Number(label="Enter BMI")
childrenIn = gr.Number(label="Enter Children")
smokerIn = gr.Radio(["yes", "no"], label="Is Smoker?")
regionIn = gr.Dropdown(["northeast","northwest","southeast","southwest"], label="Select Region")
chargesOut = gr.Number(label="Predicted Charges")
downloadOut = gr.File(label="Download Prediction Logs")
# Initialize the Gradio interface
iface1 = gr.Interface(
fn=predict_charges,
inputs=[ageIn, sexIn, bmiIn, childrenIn, smokerIn, regionIn],
outputs=chargesOut,
title="HealthyLife Insurance Charge Prediction",
description="Enter the details to estimate health insurance charges based on input parameters."
)
# Add a download button for the log file
iface2 = gr.Interface(
fn=download_log_file,
inputs=None,
outputs=downloadOut,
description="Download the log file of inputs and predictions"
)
# Combine main app and download button in a single interface
iface = gr.TabbedInterface([iface1, iface2], ["Predict Charges", "Download Logs"])
# Launch the app
iface.launch()