Spaces:
Sleeping
Sleeping
import streamlit as st | |
import pandas as pd | |
import plotly.express as px | |
import matplotlib.pyplot as plt | |
import numpy as np | |
# Configuración de la página principal | |
st.set_page_config(page_title="Customer Insights App", page_icon=":bar_chart:") | |
# Cargar los archivos CSV | |
df = pd.read_csv("df_clean.csv") | |
nombres_proveedores = pd.read_csv("nombres_proveedores.csv", sep=';') | |
# Ignorar las dos últimas columnas | |
df = df.iloc[:, :-2] | |
# Asegurarse de que el código del cliente sea una cadena (string) | |
df['CLIENTE'] = df['CLIENTE'].astype(str) | |
# Función para obtener el nombre del proveedor | |
def get_supplier_name(code): | |
name = nombres_proveedores[nombres_proveedores['codigo'] == code]['nombre'].values | |
return name[0] if len(name) > 0 else code | |
# Función para crear el gráfico de radar | |
def radar_chart(categories, values, title): | |
# Número de variables | |
N = len(categories) | |
# Calcular los ángulos para cada punto | |
angles = [n / float(N) * 2 * np.pi for n in range(N)] | |
angles += angles[:1] | |
# Inicializar el gráfico | |
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(projection='polar')) | |
# Dibujar el polígono y rellenarlo | |
values += values[:1] | |
ax.plot(angles, values, 'o-', linewidth=2, color='#FF69B4') | |
ax.fill(angles, values, alpha=0.25, color='#FF69B4') | |
# Configurar los ejes | |
ax.set_xticks(angles[:-1]) | |
ax.set_xticklabels(categories, size=8, wrap=True) | |
ax.set_ylim(0, max(values) * 1.1) | |
# Dibujar círculos de referencia | |
circles = np.linspace(0, max(values), 5) | |
for circle in circles: | |
ax.plot(angles, [circle]*len(angles), '--', color='gray', alpha=0.3, linewidth=0.5) | |
# Eliminar las etiquetas radiales y los bordes del gráfico | |
ax.set_yticklabels([]) | |
ax.spines['polar'].set_visible(False) | |
# Dibujar el borde exterior en azul | |
max_value = max(values) | |
ax.plot(angles, [max_value]*len(angles), '-', linewidth=2, color='#4169E1') | |
# Añadir el título | |
plt.title(title, size=16, y=1.1) | |
return fig | |
# Diseño de la página principal | |
st.title("Welcome to Customer Insights App") | |
st.markdown(""" | |
This app helps businesses analyze customer behaviors and provide personalized recommendations based on purchase history. | |
Use the tools below to dive deeper into your customer data. | |
""") | |
# Menú de navegación | |
page = st.selectbox("Selecciona la herramienta que quieres utilizar", ["", "Customer Analysis", "Customer Recommendations"]) | |
# Página Home | |
if page == "": | |
st.markdown("## Welcome to the Customer Insights App") | |
st.write("Use the dropdown menu to navigate between the different sections.") | |
# Página Customer Analysis | |
elif page == "Customer Analysis": | |
st.title("Customer Analysis") | |
st.markdown(""" | |
Use the tools below to explore your customer data. | |
""") | |
# Campo para filtrar clientes | |
partial_code = st.text_input("Enter part of Customer Code (or leave empty to see all)") | |
# Filtrar las opciones de clientes que coincidan con el código parcial | |
if partial_code: | |
filtered_customers = df[df['CLIENTE'].str.contains(partial_code)] | |
else: | |
filtered_customers = df | |
# Crear una lista de clientes filtrados para el selectbox | |
customer_list = filtered_customers['CLIENTE'].unique() | |
# Selección de cliente con autocompletar filtrado | |
customer_code = st.selectbox("Select Customer Code", customer_list) | |
if customer_code: | |
# Filtrar datos para el cliente seleccionado | |
customer_data = df[df["CLIENTE"] == customer_code] | |
if not customer_data.empty: | |
st.write(f"### Analysis for Customer {customer_code}") | |
# Obtener las 6 columnas con los valores más altos (ignorar la columna de cliente) | |
top_6_manufacturers = customer_data.iloc[:, 1:].T.nlargest(6, customer_data.index[0]) | |
# Ordenar los fabricantes por valor descendente para mejor visualización | |
top_6_manufacturers = top_6_manufacturers.sort_values(by=customer_data.index[0], ascending=False) | |
# Preparar los valores y fabricantes | |
values = top_6_manufacturers[customer_data.index[0]].values.tolist() | |
manufacturers = [get_supplier_name(m) for m in top_6_manufacturers.index.tolist()] | |
# Mostrar los resultados de cada fabricante | |
st.write("### Resultados porcentaje fabricante (ordenados):") | |
for manufacturer, value in zip(manufacturers, values): | |
st.write(f"{manufacturer} = {value:.4f}") | |
# Crear y mostrar el gráfico de radar | |
fig = radar_chart(manufacturers, values, f'Radar Chart for Top 6 Manufacturers of Customer {customer_code}') | |
st.pyplot(fig) | |
# Ventas del cliente 2021-2024 (si los datos existen) | |
if 'VENTA_2021' in df.columns and 'VENTA_2022' in df.columns and 'VENTA_2023' in df.columns and 'VENTA_2024' in df.columns: | |
years = ['2021', '2022', '2023', '2024'] | |
sales_columns = ['VENTA_2021', 'VENTA_2022', 'VENTA_2023', 'VENTA_2024'] | |
customer_sales = customer_data[sales_columns].values[0] | |
fig_sales = px.line(x=years, y=customer_sales, markers=True, title=f'Sales Over the Years for Customer {customer_code}') | |
fig_sales.update_layout(xaxis_title="Year", yaxis_title="Sales") | |
st.plotly_chart(fig_sales) | |
else: | |
st.warning("Sales data for 2021-2024 not available.") | |
else: | |
st.warning(f"No data found for customer {customer_code}. Please check the code.") | |
# Página Customer Recommendations | |
elif page == "Customer Recommendations": | |
st.title("Customer Recommendations") | |
st.markdown(""" | |
Get tailored recommendations for your customers based on their purchasing history. | |
""") | |
# Campo para filtrar clientes | |
partial_code = st.text_input("Enter part of Customer Code for Recommendations (or leave empty to see all)") | |
# Filtrar las opciones de clientes que coincidan con el código parcial | |
if partial_code: | |
filtered_customers = df[df['CLIENTE'].str.contains(partial_code)] | |
else: | |
filtered_customers = df | |
# Crear una lista de clientes filtrados para el selectbox | |
customer_list = filtered_customers['CLIENTE'].unique() | |
# Selección de cliente con autocompletar filtrado | |
customer_code = st.selectbox("Select Customer Code for Recommendations", customer_list) | |
if customer_code: | |
customer_data = df[df["CLIENTE"] == customer_code] | |
if not customer_data.empty: | |
# Mostrar historial de compras del cliente seleccionado | |
st.write(f"### Purchase History for Customer {customer_code}") | |
st.write(customer_data) | |
# Generar recomendaciones (placeholder) | |
st.write(f"### Recommended Products for Customer {customer_code}") | |
# Aquí puedes reemplazar con la lógica del modelo de recomendación | |
st.write("Product A, Product B, Product C") | |
else: | |
st.warning(f"No data found for customer {customer_code}. Please check the code.") |