GMARTINEZMILLA commited on
Commit
f447385
·
verified ·
1 Parent(s): 42a7b22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -53
app.py CHANGED
@@ -877,6 +877,11 @@ elif page == "💡 Recomendación de Artículos":
877
  # Inicializar session state para la cesta si no existe
878
  if 'new_basket' not in st.session_state:
879
  st.session_state['new_basket'] = [] # Inicializar como una lista vacía
 
 
 
 
 
880
 
881
  def add_to_basket(rec_code):
882
  if rec_code not in st.session_state['new_basket']:
@@ -901,8 +906,9 @@ elif page == "💡 Recomendación de Artículos":
901
  article_dict = dict(zip(available_articles['DESCRIPCION'], available_articles['ARTICULO']))
902
 
903
  # Permitir seleccionar las descripciones, pero trabajar con los códigos
904
- selected_descriptions = st.multiselect("Selecciona los artículos", available_articles['DESCRIPCION'].unique())
905
-
 
906
 
907
  if selected_descriptions:
908
  st.write("### Visualiza la selección de artículos:")
@@ -932,59 +938,60 @@ elif page == "💡 Recomendación de Artículos":
932
  st.write(f"Artículos seleccionados (códigos): {new_basket}")
933
 
934
  if new_basket:
935
- # Procesar la lista para recomendar utilizando tu función 'recomienda_tf'
936
- recommendations_df = recomienda_tf(new_basket, cestas,productos)
937
-
938
- if not recommendations_df.empty:
939
- st.success("### Según tu cesta, te recomendamos que consideres añadir estos artículos:")
940
-
941
- # Mostrar los artículos recomendados con imágenes y relevancia
942
- for idx, row in recommendations_df.iterrows():
943
- rec_code = row['ARTICULO']
944
- rec_desc = row['DESCRIPCION']
945
- rec_relevance = row['RELEVANCIA'] # Usar la relevancia calculada
946
- rec_img_url = f"https://www.saneamiento-martinez.com/imagenes/articulos/{rec_code}_1.JPG"
947
-
948
- # Verificar si la imagen existe antes de mostrar el artículo
949
- if image_exists(rec_img_url):
950
- rec_col1, rec_col2, rec_col3, rec_col4 = st.columns([1, 3, 1, 1]) # Añadir una columna para la relevancia
951
- with rec_col1:
952
- st.image(rec_img_url, width=100)
953
- with rec_col2:
954
- st.write(f"**{rec_desc}** (Código: {rec_code})")
955
- with rec_col3:
956
- st.metric(label="Relevancia",value =f"{rec_relevance * 100:.2f}") # Mostrar la relevancia con 4 decimales
957
- with rec_col4:
958
- # Botón para añadir artículo recomendado a la cesta
959
- if rec_code not in st.session_state['new_basket']:
960
- st.button("➕", key=f"add_{rec_code}", on_click=add_to_basket, args=(rec_code,))
961
- else:
962
- st.write("")
963
-
964
- # Mostrar una sección de previsualización de la nueva cesta antes de agregarla al histórico
965
- st.write("### Previsualiza la cesta completa antes de agregarla:")
966
- for code in st.session_state['new_basket']:
967
- # Mostrar la descripción del artículo en la previsualización
968
- article_desc = productos[productos['ARTICULO'] == code]['DESCRIPCION'].values[0]
969
- st.write(f"- {article_desc} (Código: {code})")
970
-
971
-
972
- # Botón para añadir la cesta nueva al histórico
973
- if st.button("📦 Añadir cesta al histórico"):
974
- if st.session_state['new_basket']:
975
- # Usar la función retroalimentacion para añadir la cesta
976
- retroalimentacion(cestas, st.session_state['new_basket'])
977
- st.success("✓ La cesta ha sido añadida al histórico.")
978
- # Limpiar la cesta después de añadirla al histórico
979
- st.session_state['new_basket'] = []
980
- st.rerun() # Limpiar las recomendaciones también
981
  else:
982
- st.warning("⚠️ No hay artículos en la cesta para añadir.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
983
  else:
984
- st.warning("⚠️ No se encontraron recomendaciones para la cesta proporcionada.")
985
- else:
986
- st.warning("⚠️ Por favor selecciona al menos un artículo y define su cantidad.")
987
-
988
 
989
 
990
  # elif page == "💡 Recomendación de Artículos":
 
877
  # Inicializar session state para la cesta si no existe
878
  if 'new_basket' not in st.session_state:
879
  st.session_state['new_basket'] = [] # Inicializar como una lista vacía
880
+ if 'recommendations_df' not in st.session_state:
881
+ st.session_state['recommendations_df'] = None
882
+
883
+ if 'selected_descriptions' not in st.session_state:
884
+ st.session_state['selected_descriptions'] = []
885
 
886
  def add_to_basket(rec_code):
887
  if rec_code not in st.session_state['new_basket']:
 
906
  article_dict = dict(zip(available_articles['DESCRIPCION'], available_articles['ARTICULO']))
907
 
908
  # Permitir seleccionar las descripciones, pero trabajar con los códigos
909
+ selected_descriptions = st.multiselect("Selecciona los artículos",available_articles['DESCRIPCION'].unique(),default=st.session_state['selected_descriptions'])
910
+
911
+ st.session_state['selected_descriptions'] = selected_descriptions
912
 
913
  if selected_descriptions:
914
  st.write("### Visualiza la selección de artículos:")
 
938
  st.write(f"Artículos seleccionados (códigos): {new_basket}")
939
 
940
  if new_basket:
941
+
942
+ st.session_state['recommendations_df'] = recomienda_tf(new_basket, cestas, productos)
943
+ st.experimental_rerun()
944
+
945
+
946
+ # Display recommendations from session state
947
+ if st.session_state['recommendations_df'] is not None and not st.session_state['recommendations_df'].empty:
948
+ st.success("### Según tu cesta, te recomendamos que consideres añadir estos artículos:")
949
+
950
+ for idx, row in st.session_state['recommendations_df'].iterrows():
951
+ rec_code = row['ARTICULO']
952
+ rec_desc = row['DESCRIPCION']
953
+ rec_relevance = row['RELEVANCIA']
954
+ rec_img_url = f"https://www.saneamiento-martinez.com/imagenes/articulos/{rec_code}_1.JPG"
955
+
956
+ if image_exists(rec_img_url):
957
+ rec_col1, rec_col2, rec_col3, rec_col4 = st.columns([1, 3, 1, 1])
958
+ with rec_col1:
959
+ st.image(rec_img_url, width=100)
960
+ with rec_col2:
961
+ st.write(f"**{rec_desc}** (Código: {rec_code})")
962
+ with rec_col3:
963
+ st.metric(label="Relevancia", value=f"{rec_relevance * 100:.2f}")
964
+ with rec_col4:
965
+ # Disable button if item is already in basket
966
+ button_disabled = rec_code in st.session_state['new_basket']
967
+ if not button_disabled:
968
+ st.button("",
969
+ key=f"add_{rec_code}",
970
+ on_click=add_to_basket,
971
+ args=(rec_code,),
972
+ disabled=button_disabled)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
973
  else:
974
+ st.write("")
975
+
976
+ # Preview section
977
+ st.write("### Previsualiza la cesta completa antes de agregarla:")
978
+ for code in st.session_state['new_basket']:
979
+ article_desc = productos[productos['ARTICULO'] == code]['DESCRIPCION'].values[0]
980
+ st.write(f"- {article_desc} (Código: {code})")
981
+
982
+ if st.button("📦 Añadir cesta al histórico"):
983
+ if st.session_state['new_basket']:
984
+ retroalimentacion(cestas, st.session_state['new_basket'])
985
+ st.success("✓ La cesta ha sido añadida al histórico.")
986
+ # Reset all session states
987
+ st.session_state['new_basket'] = []
988
+ st.session_state['recommendations_df'] = None
989
+ st.session_state['selected_descriptions'] = []
990
+ st.experimental_rerun()
991
  else:
992
+ st.warning("⚠️ No hay artículos en la cesta para añadir.")
993
+ elif st.session_state['recommendations_df'] is not None:
994
+ st.warning("⚠️ No se encontraron recomendaciones para la cesta proporcionada.")
 
995
 
996
 
997
  # elif page == "💡 Recomendación de Artículos":