Skip to content

Commit 37c9f50

Browse files
committed
Persist weights table edits in session state
Weights table edits are now stored in Streamlit session state to persist changes across reruns. The reset button updates session state and triggers a rerun. Melody MIDI filenames now include a random string for uniqueness.
1 parent 26eeebd commit 37c9f50

1 file changed

Lines changed: 39 additions & 8 deletions

File tree

playgrounds/app.py

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import sys
3+
import random
34
import streamlit as st
45
import pandas as pd
56
from PIL import Image, ImageOps
@@ -74,22 +75,51 @@
7475

7576
df_defaults = pd.DataFrame(default_weights, columns=["Metric", "Weight"])
7677

78+
# Initialize session state before creating the editor widget.
79+
# Use a different key for storage to avoid modifying the widget key after instantiation.
80+
if "weights_table_data" not in st.session_state:
81+
st.session_state["weights_table_data"] = df_defaults.copy()
82+
7783
with st.expander("Configuración de pesos de fitness", expanded=False):
7884
# editable table
7985
try:
80-
weights_df = st.data_editor(df_defaults, num_rows="fixed", use_container_width=True, key="weights_table")
86+
weights_df = st.data_editor(
87+
st.session_state["weights_table_data"],
88+
num_rows="fixed",
89+
use_container_width=True,
90+
key="weights_table",
91+
)
8192
except Exception:
8293
# fallback if old streamlit version
83-
weights_df = st.experimental_data_editor(df_defaults, num_rows="fixed", use_container_width=True, key="weights_table")
94+
weights_df = st.experimental_data_editor(
95+
st.session_state["weights_table_data"],
96+
num_rows="fixed",
97+
use_container_width=True,
98+
key="weights_table",
99+
)
100+
101+
# Persist the edited table back to session state for the next run
102+
try:
103+
st.session_state["weights_table_data"] = weights_df.copy()
104+
except Exception:
105+
# If weights_df isn't defined for some reason, keep existing session state value
106+
pass
107+
84108
if st.button("Resetear valores por defecto"):
85-
# Reset the table by writing the defaults back via session state key
86-
st.session_state["weights_table"] = df_defaults.copy()
87-
weights_df = df_defaults.copy()
109+
# Reset the stored table values and force a re-run so the widget is re-instantiated
110+
st.session_state["weights_table_data"] = df_defaults.copy()
111+
st.experimental_rerun()
88112

89113
# Validate and extract weights in order
90114
weights = []
115+
# Prefer the editor result, but fall back to the session state stored copy if the widget didn't produce a value
116+
effective_weights_df = None
117+
if 'weights_df' in locals() and isinstance(weights_df, pd.DataFrame):
118+
effective_weights_df = weights_df
119+
else:
120+
effective_weights_df = st.session_state.get("weights_table_data", df_defaults)
91121
try:
92-
weights = [float(w) for w in list(weights_df["Weight"])[:len(df_defaults)]]
122+
weights = [float(w) for w in list(effective_weights_df["Weight"])[:len(df_defaults)]]
93123
except Exception:
94124
st.error("Los pesos deben ser valores numéricos. Corrige la tabla antes de generar la melodía.")
95125

@@ -145,8 +175,9 @@ def streamlit_runner(self, generations: int, history: bool = False):
145175
with st.spinner("Post-processing..."):
146176

147177
melody = ga.best_individual
148-
date = datetime.now().strftime("%d-%m-%y, %H.%M")
149-
midi_path = os.path.join(SAVE_PATH, f"melody_{date}.mid")
178+
date = datetime.now().strftime("%d-%m-%y")
179+
randomstring = ''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=5))
180+
midi_path = os.path.join(SAVE_PATH, f"melody_{date}_{randomstring}.mid")
150181
midi_file = melody_to_midi(melody, filename=midi_path)
151182

152183
# Convertir MIDI a WAV

0 commit comments

Comments
 (0)