GMARTINEZMILLA commited on
Commit
04f10a7
1 Parent(s): f0e70c5

feat: generated files

Browse files
Files changed (1) hide show
  1. app.py +27 -60
app.py CHANGED
@@ -26,49 +26,42 @@ def get_supplier_name(code):
26
  name = nombres_proveedores[nombres_proveedores['codigo'] == code]['nombre'].values
27
  return name[0] if len(name) > 0 else code
28
 
29
- # Function to create radar chart
30
  def radar_chart(categories, values, amounts, title):
31
- # Number of variables
32
  N = len(categories)
33
-
34
- # Calculate angles for each point
35
  angles = [n / float(N) * 2 * np.pi for n in range(N)]
36
  angles += angles[:1]
37
 
38
- # Initialize the plot
39
  fig, ax = plt.subplots(figsize=(12, 12), subplot_kw=dict(projection='polar'))
40
 
41
- # Normalize values and amounts
42
- max_value = max(values)
43
- normalized_values = [v / max_value for v in values]
44
- total_amount = sum(amounts)
45
- normalized_amounts = [a / total_amount for a in amounts]
 
 
 
46
 
47
- # Draw polygon for units and fill it
48
  normalized_values += normalized_values[:1]
49
- ax.plot(angles, normalized_values, 'o-', linewidth=2, color='#FF69B4', label='% Units')
50
  ax.fill(angles, normalized_values, alpha=0.25, color='#FF69B4')
51
 
52
- # Draw polygon for amounts and fill it
53
  normalized_amounts += normalized_amounts[:1]
54
- ax.plot(angles, normalized_amounts, 'o-', linewidth=2, color='#4B0082', label='% Spend')
55
  ax.fill(angles, normalized_amounts, alpha=0.25, color='#4B0082')
56
 
57
- # Set axes
58
  ax.set_xticks(angles[:-1])
59
  ax.set_xticklabels(categories, size=8, wrap=True)
60
  ax.set_ylim(0, max(max(normalized_values), max(normalized_amounts)) * 1.1)
61
 
62
- # Draw reference circles
63
  circles = np.linspace(0, 1, 5)
64
  for circle in circles:
65
  ax.plot(angles, [circle]*len(angles), '--', color='gray', alpha=0.3, linewidth=0.5)
66
 
67
- # Remove radial labels and chart borders
68
  ax.set_yticklabels([])
69
  ax.spines['polar'].set_visible(False)
70
 
71
- # Add title and legend
72
  plt.title(title, size=16, y=1.1)
73
  plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))
74
 
@@ -92,60 +85,43 @@ if page == "":
92
  # Customer Analysis Page
93
  elif page == "Customer Analysis":
94
  st.title("Customer Analysis")
95
- st.markdown("""
96
- Use the tools below to explore your customer data.
97
- """)
98
 
99
- # Customer filter field
100
  partial_code = st.text_input("Enter part of Customer Code (or leave empty to see all)")
101
-
102
- # Filter customer options that match the partial code
103
  if partial_code:
104
  filtered_customers = df[df['CLIENTE'].str.contains(partial_code)]
105
  else:
106
  filtered_customers = df
107
-
108
- # Create a list of filtered customers for the selectbox
109
  customer_list = filtered_customers['CLIENTE'].unique()
110
-
111
- # Customer selection with filtered autocomplete
112
  customer_code = st.selectbox("Select Customer Code", customer_list)
113
 
114
  if customer_code:
115
- # Filter data for the selected customer
116
  customer_data = df[df["CLIENTE"] == customer_code]
117
  customer_euros = euros_proveedor[euros_proveedor["CLIENTE"] == customer_code]
118
 
119
  if not customer_data.empty and not customer_euros.empty:
120
  st.write(f"### Analysis for Customer {customer_code}")
121
 
122
- # Define purchase threshold
123
- purchase_threshold = 0
124
-
125
- # Get all manufacturers the customer bought from (ignore the customer column)
126
- all_manufacturers = customer_data.iloc[:, 1:].T[customer_data.iloc[:, 1:].T[customer_data.index[0]] > purchase_threshold]
127
 
128
- # Sort manufacturers by value in descending order and limit to top 20
129
- all_manufacturers = all_manufacturers.sort_values(by=customer_data.index[0], ascending=False).head(20)
130
-
131
- # Prepare values and manufacturers
132
- values = all_manufacturers[customer_data.index[0]].values.tolist()
133
- manufacturers = [get_supplier_name(m) for m in all_manufacturers.index.tolist()]
134
 
135
- # Get amounts in euros
 
136
  amounts = []
137
- for m in all_manufacturers.index.tolist():
138
- if m in customer_euros.columns:
139
- amounts.append(customer_euros[m].values[0])
140
- else:
141
- amounts.append(0)
142
-
143
- # Display the results for each manufacturer
144
- st.write(f"### Results for top {len(manufacturers)} manufacturers (sorted):")
145
  for manufacturer, value, amount in zip(manufacturers, values, amounts):
146
  st.write(f"{manufacturer} = {value:.4f} units, €{amount:.2f}")
147
 
148
- # Create and display the radar chart
149
  fig = radar_chart(manufacturers, values, amounts, f'Radar Chart for Top {len(manufacturers)} Manufacturers of Customer {customer_code}')
150
  st.pyplot(fig)
151
 
@@ -170,32 +146,23 @@ elif page == "Customer Recommendations":
170
  Get tailored recommendations for your customers based on their purchasing history.
171
  """)
172
 
173
- # Customer filter field
174
  partial_code = st.text_input("Enter part of Customer Code for Recommendations (or leave empty to see all)")
175
-
176
- # Filter customer options that match the partial code
177
  if partial_code:
178
  filtered_customers = df[df['CLIENTE'].str.contains(partial_code)]
179
  else:
180
  filtered_customers = df
181
-
182
- # Create a list of filtered customers for the selectbox
183
  customer_list = filtered_customers['CLIENTE'].unique()
184
-
185
- # Customer selection with filtered autocomplete
186
  customer_code = st.selectbox("Select Customer Code for Recommendations", customer_list)
187
 
188
  if customer_code:
189
  customer_data = df[df["CLIENTE"] == customer_code]
190
 
191
  if not customer_data.empty:
192
- # Show selected customer's purchase history
193
  st.write(f"### Purchase History for Customer {customer_code}")
194
  st.write(customer_data)
195
 
196
- # Generate recommendations (placeholder)
197
  st.write(f"### Recommended Products for Customer {customer_code}")
198
- # You can replace this with the logic of the recommendation model
199
  st.write("Product A, Product B, Product C")
200
  else:
201
  st.warning(f"No data found for customer {customer_code}. Please check the code.")
 
26
  name = nombres_proveedores[nombres_proveedores['codigo'] == code]['nombre'].values
27
  return name[0] if len(name) > 0 else code
28
 
29
+ # Function to create radar chart with square root transformation
30
  def radar_chart(categories, values, amounts, title):
 
31
  N = len(categories)
 
 
32
  angles = [n / float(N) * 2 * np.pi for n in range(N)]
33
  angles += angles[:1]
34
 
 
35
  fig, ax = plt.subplots(figsize=(12, 12), subplot_kw=dict(projection='polar'))
36
 
37
+ # Apply square root transformation
38
+ sqrt_values = np.sqrt(values)
39
+ sqrt_amounts = np.sqrt(amounts)
40
+
41
+ max_sqrt_value = max(sqrt_values)
42
+ normalized_values = [v / max_sqrt_value for v in sqrt_values]
43
+ total_sqrt_amount = sum(sqrt_amounts)
44
+ normalized_amounts = [a / total_sqrt_amount for a in sqrt_amounts]
45
 
 
46
  normalized_values += normalized_values[:1]
47
+ ax.plot(angles, normalized_values, 'o-', linewidth=2, color='#FF69B4', label='% Units (sqrt)')
48
  ax.fill(angles, normalized_values, alpha=0.25, color='#FF69B4')
49
 
 
50
  normalized_amounts += normalized_amounts[:1]
51
+ ax.plot(angles, normalized_amounts, 'o-', linewidth=2, color='#4B0082', label='% Spend (sqrt)')
52
  ax.fill(angles, normalized_amounts, alpha=0.25, color='#4B0082')
53
 
 
54
  ax.set_xticks(angles[:-1])
55
  ax.set_xticklabels(categories, size=8, wrap=True)
56
  ax.set_ylim(0, max(max(normalized_values), max(normalized_amounts)) * 1.1)
57
 
 
58
  circles = np.linspace(0, 1, 5)
59
  for circle in circles:
60
  ax.plot(angles, [circle]*len(angles), '--', color='gray', alpha=0.3, linewidth=0.5)
61
 
 
62
  ax.set_yticklabels([])
63
  ax.spines['polar'].set_visible(False)
64
 
 
65
  plt.title(title, size=16, y=1.1)
66
  plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))
67
 
 
85
  # Customer Analysis Page
86
  elif page == "Customer Analysis":
87
  st.title("Customer Analysis")
88
+ st.markdown("Use the tools below to explore your customer data.")
 
 
89
 
 
90
  partial_code = st.text_input("Enter part of Customer Code (or leave empty to see all)")
 
 
91
  if partial_code:
92
  filtered_customers = df[df['CLIENTE'].str.contains(partial_code)]
93
  else:
94
  filtered_customers = df
 
 
95
  customer_list = filtered_customers['CLIENTE'].unique()
 
 
96
  customer_code = st.selectbox("Select Customer Code", customer_list)
97
 
98
  if customer_code:
 
99
  customer_data = df[df["CLIENTE"] == customer_code]
100
  customer_euros = euros_proveedor[euros_proveedor["CLIENTE"] == customer_code]
101
 
102
  if not customer_data.empty and not customer_euros.empty:
103
  st.write(f"### Analysis for Customer {customer_code}")
104
 
105
+ all_manufacturers = customer_data.iloc[:, 1:].T[customer_data.iloc[:, 1:].T[customer_data.index[0]] > 0]
 
 
 
 
106
 
107
+ top_units = all_manufacturers.sort_values(by=customer_data.index[0], ascending=False).head(10)
108
+ top_sales = customer_euros.iloc[0].sort_values(ascending=False).head(10)
109
+ combined_top = pd.concat([top_units, top_sales]).index.unique()
 
 
 
110
 
111
+ values = []
112
+ manufacturers = []
113
  amounts = []
114
+
115
+ for m in combined_top:
116
+ if m in all_manufacturers.index:
117
+ values.append(all_manufacturers[m])
118
+ manufacturers.append(get_supplier_name(m))
119
+ amounts.append(customer_euros[m].values[0] if m in customer_euros.columns else 0)
120
+
121
+ st.write(f"### Results for top {len(manufacturers)} manufacturers (balanced by units and sales):")
122
  for manufacturer, value, amount in zip(manufacturers, values, amounts):
123
  st.write(f"{manufacturer} = {value:.4f} units, €{amount:.2f}")
124
 
 
125
  fig = radar_chart(manufacturers, values, amounts, f'Radar Chart for Top {len(manufacturers)} Manufacturers of Customer {customer_code}')
126
  st.pyplot(fig)
127
 
 
146
  Get tailored recommendations for your customers based on their purchasing history.
147
  """)
148
 
 
149
  partial_code = st.text_input("Enter part of Customer Code for Recommendations (or leave empty to see all)")
 
 
150
  if partial_code:
151
  filtered_customers = df[df['CLIENTE'].str.contains(partial_code)]
152
  else:
153
  filtered_customers = df
 
 
154
  customer_list = filtered_customers['CLIENTE'].unique()
 
 
155
  customer_code = st.selectbox("Select Customer Code for Recommendations", customer_list)
156
 
157
  if customer_code:
158
  customer_data = df[df["CLIENTE"] == customer_code]
159
 
160
  if not customer_data.empty:
 
161
  st.write(f"### Purchase History for Customer {customer_code}")
162
  st.write(customer_data)
163
 
 
164
  st.write(f"### Recommended Products for Customer {customer_code}")
165
+ # Placeholder for recommendation logic
166
  st.write("Product A, Product B, Product C")
167
  else:
168
  st.warning(f"No data found for customer {customer_code}. Please check the code.")