molinari135 commited on
Commit
f1e321f
·
verified ·
1 Parent(s): 77e6014

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -24
app.py CHANGED
@@ -4,21 +4,20 @@ import pandas as pd
4
  import os
5
  from datasets import load_dataset
6
 
7
- # FastAPI endpoint URL
8
  API_URL = "https://molinari135-product-return-prediction-api.hf.space/predict/"
9
 
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']).sample(n=15, random_state=42)
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,18 +25,15 @@ def predict_return(selected_products, total_customer_purchases, total_customer_r
26
  total_value = 0
27
 
28
  for selected_product in selected_products:
29
- # Split each selected product into model, fabric, and color
30
  product_info = selected_product.split(" \t\t")
31
- model_fabric_colour = product_info[0] # Questo è del tipo "Model-Fabric-Colour"
32
 
33
- # Dividi il codice prodotto in modello, tessuto e colore
34
  model, fabric, color = model_fabric_colour.split("-")
35
 
36
  models.append(model)
37
  fabrics.append(fabric)
38
  colours.append(color)
39
 
40
- # Get the product details from the inventory
41
  product_details = inventory[(
42
  inventory['Item Brand Model'] == model) &
43
  (inventory['Item Brand Fabric'] == fabric) &
@@ -45,11 +41,9 @@ def predict_return(selected_products, total_customer_purchases, total_customer_r
45
  ]
46
 
47
  if not product_details.empty:
48
- # Calculate the product value and add it to the total
49
  product_value = product_details['Net Sales (FA)'].values[0]
50
  total_value += product_value
51
 
52
- # Add description to the cart
53
  description = (
54
  f"Model: {model}, Fabric: {fabric}, Colour: {color} \tSales Value: {product_value} USD"
55
  )
@@ -57,7 +51,6 @@ def predict_return(selected_products, total_customer_purchases, total_customer_r
57
  else:
58
  descriptions.append(f"{model}-{fabric}-{color}: Not Found")
59
 
60
- # Prepare the data to send to the API
61
  data = {
62
  "models": models,
63
  "fabrics": fabrics,
@@ -67,21 +60,17 @@ def predict_return(selected_products, total_customer_purchases, total_customer_r
67
  }
68
 
69
  try:
70
- # Make the POST request to the FastAPI endpoint
71
  response = requests.post(API_URL, json=data)
72
- response.raise_for_status() # Raise an error for bad responses
73
 
74
- # Get the predictions and return them
75
  result = response.json()
76
  predictions = result.get('predictions', [])
77
 
78
  if not predictions:
79
  return "Error: No predictions found."
80
 
81
- # Format the cart output
82
  cart_output = "\n".join(descriptions) + f"\n\nTotal Cart Value: {round(total_value, 2)} USD"
83
 
84
- # Format the prediction results
85
  formatted_result = "\n".join([f"Product: {pred['product']} \t Prediction: {pred['prediction']} \t Confidence: {pred['confidence']}" for pred in predictions])
86
 
87
  return cart_output, formatted_result
@@ -89,7 +78,6 @@ def predict_return(selected_products, total_customer_purchases, total_customer_r
89
  except requests.exceptions.RequestException as e:
90
  return f"Error: {str(e)}"
91
 
92
- # Crea l'interfaccia Gradio con le checkbox a sinistra
93
  checkbox_choices = [
94
  f"{row['Item Brand Model']}-{row['Item Brand Fabric']}-{row['Item Brand Colour']}"
95
  f" \t\tType: {row['Product Type']} \t\tMaterial: {row['Main Material']} \t\tSales: {round(row['Net Sales (FA)'], 2)} USD"
@@ -97,21 +85,20 @@ checkbox_choices = [
97
  ]
98
 
99
  interface = gr.Interface(
100
- fn=predict_return, # Funzione per la logica di predizione
101
  inputs=[
102
  gr.CheckboxGroup(
103
- choices=checkbox_choices, # Mostra le informazioni dettagliate accanto ai codici
104
  label="Select Products"
105
  ),
106
  gr.Slider(0, 10, step=1, label="Total Customer Purchases", value=0),
107
  gr.Slider(0, 10, step=1, label="Total Customer Returns", value=0)
108
  ],
109
  outputs=[
110
- gr.Textbox(label="Cart Details"), # Dettagli del carrello
111
- gr.Textbox(label="Prediction Results") # Risultati della predizione
112
  ],
113
- live=True # Interattività in tempo reale
114
  )
115
 
116
- # Lancio dell'interfaccia Gradio
117
  interface.launch()
 
4
  import os
5
  from datasets import load_dataset
6
 
7
+
8
  API_URL = "https://molinari135-product-return-prediction-api.hf.space/predict/"
9
 
10
+
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']).sample(n=15, random_state=42)
14
 
15
+
16
  def predict_return(selected_products, total_customer_purchases, total_customer_returns):
17
+
18
  if total_customer_returns > total_customer_purchases:
19
  return "Error: Total returns cannot be greater than total purchases."
20
 
 
21
  models = []
22
  fabrics = []
23
  colours = []
 
25
  total_value = 0
26
 
27
  for selected_product in selected_products:
 
28
  product_info = selected_product.split(" \t\t")
29
+ model_fabric_colour = product_info[0]
30
 
 
31
  model, fabric, color = model_fabric_colour.split("-")
32
 
33
  models.append(model)
34
  fabrics.append(fabric)
35
  colours.append(color)
36
 
 
37
  product_details = inventory[(
38
  inventory['Item Brand Model'] == model) &
39
  (inventory['Item Brand Fabric'] == fabric) &
 
41
  ]
42
 
43
  if not product_details.empty:
 
44
  product_value = product_details['Net Sales (FA)'].values[0]
45
  total_value += product_value
46
 
 
47
  description = (
48
  f"Model: {model}, Fabric: {fabric}, Colour: {color} \tSales Value: {product_value} USD"
49
  )
 
51
  else:
52
  descriptions.append(f"{model}-{fabric}-{color}: Not Found")
53
 
 
54
  data = {
55
  "models": models,
56
  "fabrics": fabrics,
 
60
  }
61
 
62
  try:
 
63
  response = requests.post(API_URL, json=data)
64
+ response.raise_for_status()
65
 
 
66
  result = response.json()
67
  predictions = result.get('predictions', [])
68
 
69
  if not predictions:
70
  return "Error: No predictions found."
71
 
 
72
  cart_output = "\n".join(descriptions) + f"\n\nTotal Cart Value: {round(total_value, 2)} USD"
73
 
 
74
  formatted_result = "\n".join([f"Product: {pred['product']} \t Prediction: {pred['prediction']} \t Confidence: {pred['confidence']}" for pred in predictions])
75
 
76
  return cart_output, formatted_result
 
78
  except requests.exceptions.RequestException as e:
79
  return f"Error: {str(e)}"
80
 
 
81
  checkbox_choices = [
82
  f"{row['Item Brand Model']}-{row['Item Brand Fabric']}-{row['Item Brand Colour']}"
83
  f" \t\tType: {row['Product Type']} \t\tMaterial: {row['Main Material']} \t\tSales: {round(row['Net Sales (FA)'], 2)} USD"
 
85
  ]
86
 
87
  interface = gr.Interface(
88
+ fn=predict_return,
89
  inputs=[
90
  gr.CheckboxGroup(
91
+ choices=checkbox_choices,
92
  label="Select Products"
93
  ),
94
  gr.Slider(0, 10, step=1, label="Total Customer Purchases", value=0),
95
  gr.Slider(0, 10, step=1, label="Total Customer Returns", value=0)
96
  ],
97
  outputs=[
98
+ gr.Textbox(label="Cart Details"),
99
+ gr.Textbox(label="Prediction Results")
100
  ],
101
+ live=False
102
  )
103
 
 
104
  interface.launch()