molinari135 commited on
Commit
a97c2f2
·
verified ·
1 Parent(s): 6d19f01

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -27
app.py CHANGED
@@ -10,15 +10,15 @@ API_URL = "https://molinari135-product-return-prediction-api.hf.space/predict/"
10
  # Load the inventory dataset from Hugging Face
11
  hf_token = os.getenv("inventory_data")
12
  dataset = load_dataset("molinari135/armani-inventory", token=hf_token, data_files="inventory.tsv")
13
- inventory = pd.DataFrame(dataset['train']).head(50)
14
 
15
- # Funzione Gradio per la predizione
16
  def predict_return(selected_products, total_customer_purchases, total_customer_returns):
17
- # Verifica che i ritorni non siano maggiori degli acquisti
18
  if total_customer_returns > total_customer_purchases:
19
- return "Errore: il numero dei ritorni non può essere maggiore degli acquisti."
20
 
21
- # Dati per la richiesta
22
  models = []
23
  fabrics = []
24
  colours = []
@@ -26,13 +26,13 @@ def predict_return(selected_products, total_customer_purchases, total_customer_r
26
  total_value = 0
27
 
28
  for selected_product in selected_products:
29
- # Dividi ciascun prodotto selezionato in modello, tessuto e colore
30
  model, fabric, color = selected_product.split("-")
31
  models.append(model)
32
  fabrics.append(fabric)
33
  colours.append(color)
34
 
35
- # Ottieni i dettagli del prodotto dall'inventario
36
  product_details = inventory[(
37
  inventory['Item Brand Model'] == model) &
38
  (inventory['Item Brand Fabric'] == fabric) &
@@ -40,22 +40,20 @@ def predict_return(selected_products, total_customer_purchases, total_customer_r
40
  ]
41
 
42
  if not product_details.empty:
43
- # Calcola il valore del prodotto e somma al totale
44
  product_value = product_details['Net Sales (FA)'].values[0]
45
  total_value += product_value
46
 
47
- # Aggiungi descrizione al carrello
48
  description = (
49
  f"Model: {model}, Fabric: {fabric}, Colour: {color}, "
50
- f"Product Type: {product_details['Product Type'].values[0]}, "
51
- f"Material: {product_details['Main Material'].values[0]}, "
52
  f"Sales Value: {product_value} USD"
53
  )
54
  descriptions.append(description)
55
  else:
56
  descriptions.append(f"{model}-{fabric}-{color}: Not Found")
57
 
58
- # Dati da inviare all'API
59
  data = {
60
  "models": models,
61
  "fabrics": fabrics,
@@ -65,40 +63,36 @@ def predict_return(selected_products, total_customer_purchases, total_customer_r
65
  }
66
 
67
  try:
68
- # Richiesta POST all'endpoint FastAPI
69
  response = requests.post(API_URL, json=data)
70
- response.raise_for_status() # Solleva un'eccezione per risposte errate
71
 
72
- # Ottieni le predizioni e restituiscile
73
  result = response.json()
74
  predictions = result.get('predictions', [])
75
 
76
  if not predictions:
77
- return "Errore: nessuna predizione trovata."
78
 
79
- # Formatta l'output del carrello
80
  cart_output = "\n".join(descriptions) + f"\nTotal Cart Value: {total_value} USD"
81
 
82
- # Formatta i risultati delle predizioni
83
  formatted_result = "\n".join([f"Product: {pred['product']} \t Prediction: {pred['prediction']} \t Confidence: {pred['confidence']}%" for pred in predictions])
84
 
85
  return cart_output, formatted_result
86
 
87
  except requests.exceptions.RequestException as e:
88
- return f"Errore: {str(e)}"
89
-
90
- # Crea l'interfaccia Gradio con le checkbox a sinistra
91
- checkbox_choices = [
92
- f"{row['Item Brand Model']}-{row['Item Brand Fabric']}-{row['Item Brand Colour']} - "
93
- f"Type: {row['Product Type']} - Material: {row['Main Material']} - Sales: {row['Net Sales (FA)']} USD"
94
- for _, row in inventory.iterrows()
95
- ]
96
 
 
97
  interface = gr.Interface(
98
  fn=predict_return, # Funzione per la logica di predizione
99
  inputs=[
100
  gr.CheckboxGroup(
101
- choices=checkbox_choices, # Mostra le informazioni dettagliate accanto ai codici
 
 
102
  label="Select Products"
103
  ),
104
  gr.Slider(0, 10, step=1, label="Total Customer Purchases", value=0),
 
10
  # Load the inventory dataset from Hugging Face
11
  hf_token = os.getenv("inventory_data")
12
  dataset = load_dataset("molinari135/armani-inventory", token=hf_token, data_files="inventory.tsv")
13
+ inventory = pd.DataFrame(dataset['train']).head(20)
14
 
15
+ # Gradio Interface function
16
  def predict_return(selected_products, total_customer_purchases, total_customer_returns):
17
+ # Input validation for returns (must be <= purchases)
18
  if total_customer_returns > total_customer_purchases:
19
+ return "Error: Total returns cannot be greater than total purchases."
20
 
21
+ # Prepare the request data
22
  models = []
23
  fabrics = []
24
  colours = []
 
26
  total_value = 0
27
 
28
  for selected_product in selected_products:
29
+ # Split each selected product into model, fabric, and color
30
  model, fabric, color = selected_product.split("-")
31
  models.append(model)
32
  fabrics.append(fabric)
33
  colours.append(color)
34
 
35
+ # Get the product details from the inventory
36
  product_details = inventory[(
37
  inventory['Item Brand Model'] == model) &
38
  (inventory['Item Brand Fabric'] == fabric) &
 
40
  ]
41
 
42
  if not product_details.empty:
43
+ # Calculate the product value and add it to the total
44
  product_value = product_details['Net Sales (FA)'].values[0]
45
  total_value += product_value
46
 
47
+ # Add description to the cart
48
  description = (
49
  f"Model: {model}, Fabric: {fabric}, Colour: {color}, "
 
 
50
  f"Sales Value: {product_value} USD"
51
  )
52
  descriptions.append(description)
53
  else:
54
  descriptions.append(f"{model}-{fabric}-{color}: Not Found")
55
 
56
+ # Prepare the data to send to the API
57
  data = {
58
  "models": models,
59
  "fabrics": fabrics,
 
63
  }
64
 
65
  try:
66
+ # Make the POST request to the FastAPI endpoint
67
  response = requests.post(API_URL, json=data)
68
+ response.raise_for_status() # Raise an error for bad responses
69
 
70
+ # Get the predictions and return them
71
  result = response.json()
72
  predictions = result.get('predictions', [])
73
 
74
  if not predictions:
75
+ return "Error: No predictions found."
76
 
77
+ # Format the cart output
78
  cart_output = "\n".join(descriptions) + f"\nTotal Cart Value: {total_value} USD"
79
 
80
+ # Format the prediction results
81
  formatted_result = "\n".join([f"Product: {pred['product']} \t Prediction: {pred['prediction']} \t Confidence: {pred['confidence']}%" for pred in predictions])
82
 
83
  return cart_output, formatted_result
84
 
85
  except requests.exceptions.RequestException as e:
86
+ return f"Error: {str(e)}"
 
 
 
 
 
 
 
87
 
88
+ # Gradio interface elements
89
  interface = gr.Interface(
90
  fn=predict_return, # Funzione per la logica di predizione
91
  inputs=[
92
  gr.CheckboxGroup(
93
+ choices=[
94
+ f"{row['Item Brand Model']}-{row['Item Brand Fabric']}-{row['Item Brand Colour']} \nProduct type: {row['Product Type']} Product subtype: {row['Product Subtype']} Price: {row['Net Sales (FA)']}"
95
+ for _, row in inventory.iterrows()],
96
  label="Select Products"
97
  ),
98
  gr.Slider(0, 10, step=1, label="Total Customer Purchases", value=0),