molinari135's picture
Update app.py
a380fda verified
raw
history blame
4.38 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']).sample(n=15, random_state=42)
# 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
product_info = selected_product.split(" \t\t")
model_fabric_colour = product_info[0] # Questo è del tipo "Model-Fabric-Colour"
# Dividi il codice prodotto in modello, tessuto e colore
model, fabric, color = model_fabric_colour.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} \tSales 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"\n\nTotal Cart Value: {round(total_value, 2)} 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)}"
# Crea l'interfaccia Gradio con le checkbox a sinistra
checkbox_choices = [
f"{row['Item Brand Model']}-{row['Item Brand Fabric']}-{row['Item Brand Colour']}"
f" \t\tType: {row['Product Type']} \t\tMaterial: {row['Main Material']} \t\tSales: {round(row['Net Sales (FA)'], 2)} USD"
for _, row in inventory.iterrows()
]
interface = gr.Interface(
fn=predict_return, # Funzione per la logica di predizione
inputs=[
gr.CheckboxGroup(
choices=checkbox_choices, # Mostra le informazioni dettagliate accanto ai codici
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()