molinari135's picture
Update app.py
8a98a0c verified
raw
history blame
4.06 kB
import gradio as gr
import requests
import pandas as pd
import os
from datasets import load_dataset
# FastAPI endpoint URL
API_URL = "https://molinari135-product-return-prediction-api.hf.space/predict/"
# Load the inventory dataset from Hugging Face
hf_token = os.getenv("inventory_data")
dataset = load_dataset("molinari135/armani-inventory", token=hf_token, data_files="inventory.tsv")
inventory = pd.DataFrame(dataset['train']).head(50)
# Gradio Interface function
def predict_return(selected_products, total_customer_purchases, total_customer_returns):
# Input validation for returns (must be <= purchases)
if total_customer_returns > total_customer_purchases:
return "Error: Total returns cannot be greater than total purchases."
# Prepare the request data
models = []
fabrics = []
colours = []
descriptions = []
total_value = 0
for selected_product in selected_products:
# Split each selected product into model, fabric, and color
model, fabric, color = selected_product.split("-")
models.append(model)
fabrics.append(fabric)
colours.append(color)
# Get the product details from the inventory
product_details = inventory[(
inventory['Item Brand Model'] == model) &
(inventory['Item Brand Fabric'] == fabric) &
(inventory['Item Brand Colour'] == color)
]
if not product_details.empty:
# Calculate the product value and add it to the total
product_value = product_details['Net Sales (FA)'].values[0]
total_value += product_value
# Add description to the cart
description = (
f"Model: {model}, Fabric: {fabric}, Colour: {color}, "
f"Product Type: {product_details['Product Type'].values[0]}, "
f"Material: {product_details['Main Material'].values[0]}, "
f"Sales Value: {product_value} USD"
)
descriptions.append(description)
else:
descriptions.append(f"{model}-{fabric}-{color}: Not Found")
# Prepare the data to send to the API
data = {
"models": models,
"fabrics": fabrics,
"colours": colours,
"total_customer_purchases": total_customer_purchases,
"total_customer_returns": total_customer_returns
}
try:
# Make the POST request to the FastAPI endpoint
response = requests.post(API_URL, json=data)
response.raise_for_status() # Raise an error for bad responses
# Get the predictions and return them
result = response.json()
predictions = result.get('predictions', [])
if not predictions:
return "Error: No predictions found."
# Format the cart output
cart_output = "\n".join(descriptions) + f"\nTotal Cart Value: {total_value} USD"
# Format the prediction results
formatted_result = "\n".join([f"Product: {pred['product']} \t Prediction: {pred['prediction']} \t Confidence: {pred['confidence']}%" for pred in predictions])
return cart_output, formatted_result
except requests.exceptions.RequestException as e:
return f"Error: {str(e)}"
# Gradio interface elements
interface = gr.Interface(
fn=predict_return, # Funzione per la logica di predizione
inputs=[
gr.CheckboxGroup(
choices=[f"{row['Item Brand Model']}-{row['Item Brand Fabric']}-{row['Item Brand Colour']}"
for _, row in inventory.iterrows()],
label="Select Products"
),
gr.Slider(0, 10, step=1, label="Total Customer Purchases", value=0),
gr.Slider(0, 10, step=1, label="Total Customer Returns", value=0)
],
outputs=[
gr.Textbox(label="Cart Details"), # Dettagli del carrello
gr.Textbox(label="Prediction Results") # Risultati della predizione
],
live=True # Interattività in tempo reale
)
# Lancio dell'interfaccia Gradio
interface.launch()