Compare commits

..

No commits in common. "workoutform" and "main" have entirely different histories.

2 changed files with 72 additions and 86 deletions

View file

@ -1,3 +0,0 @@
{
"github.copilot.nextEditSuggestions.enabled": false
}

View file

@ -13,102 +13,91 @@ host = os.getenv('host')
database = os.getenv('database') database = os.getenv('database')
port = os.getenv('port') port = os.getenv('port')
# --- Database Helper Functions --- workout_table = ['chest','back','legs']
def get_db_connection(): selected_workout = st.selectbox('Select a Workout',options=workout_table)
try: try:
return mysql.connector.connect( conn = mysql.connector.connect(user=user,password=password, host=host,port=port,database=database)
user=user, password=password, host=host, port=port, database=database
)
except mysql.connector.Error as err: except mysql.connector.Error as err:
st.error(f"Database Error: {err}") if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
return None print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
def load_template(workout_type): print("Database does not exist")
conn = get_db_connection() else:
if not conn: return pd.DataFrame() print(err)
else:
cursor = conn.cursor() cursor = conn.cursor()
# Map selection to table name safely if selected_workout == 'chest':
table_map = {'chest': 'chest', 'back': 'back', 'legs': 'legs'} query = ("SELECT * FROM `chest`")
table = table_map.get(workout_type, 'chest') elif selected_workout == 'back':
query = ("SELECT * FROM `back`")
query = f"SELECT * FROM `{table}`" else:
query = ("SELECT * FROM `legs`")
cursor.execute(query) cursor.execute(query)
data = cursor.fetchall() data = cursor.fetchall()
columns = cursor.column_names
cursor.close()
conn.close()
df = pd.DataFrame(data, columns=columns)
df['date'] = date.today()
return df
def save_workout(df):
conn = get_db_connection()
if not conn: return
cursor = conn.cursor()
# Note: Target table uses 'inputdate'
query = ("INSERT INTO `workouts` "
"(`inputdate`, `group`, `exercise`, `set`, `weight`, `reps`, `notes`) "
"VALUES (%s, %s, %s, %s, %s, %s, %s)")
for _, row in df.iterrows():
cursor.execute(query, (
row['date'], row['group'], row['exercise'],
row['set'], row['weight'], row['reps'], row['notes']
))
conn.commit() conn.commit()
cursor.close() cursor.close()
conn.close() conn.close()
st.success("Workout saved successfully!")
# --- Main Application --- today=date.today()
st.title("Workout Logger") df = pd.DataFrame(data,columns=cursor.column_names)
df['date']=today
workout_options = ['chest', 'back', 'legs'] # Initialize session state to keep track of the current row index
selected_workout = st.selectbox('Select a Workout', options=workout_options) if 'current_row' not in st.session_state:
st.session_state.current_row = 0
if 'current_workout' not in st.session_state or st.session_state.current_workout != selected_workout: if 'edited_df' not in st.session_state:
st.session_state.current_workout = selected_workout st.session_state.edited_df = df.copy()
st.session_state.workout_df = load_template(selected_workout)
st.session_state.current_index = 0
df = st.session_state.workout_df def display_row(row):
st.text_input("Date", value=row['date'], key='date')
st.text_input("Group",value=row['group'], key='group')
st.text_input("Exercise",value=row['exercise'], key='exercise')
st.number_input("Set",value=row['set'], key='set',format="%i")
st.number_input("Weight",value=row['weight'], key='weight',format="%0.1f",step=0.5)
st.number_input("Reps",value=row['reps'], key='reps',format="%i")
st.text_input("Notes",value=row['notes'], key='notes')
if not df.empty: def save_edited_row(index):
# Navigation Dropdown st.session_state.edited_df.at[index,'group'] = st.session_state.group
step_labels = [f"{i+1}. {row['exercise']} (Set {row['set']})" for i, row in df.iterrows()] st.session_state.edited_df.at[index,'exercise'] = st.session_state.exercise
selected_step = st.selectbox("Jump to Exercise", options=step_labels, index=st.session_state.current_index) st.session_state.edited_df.at[index,'set'] = st.session_state.set
st.session_state.current_index = step_labels.index(selected_step) st.session_state.edited_df.at[index,'weight'] = st.session_state.weight
st.session_state.edited_df.at[index,'reps'] = st.session_state.reps
st.session_state.edited_df.at[index,'notes'] = st.session_state.notes
# Current Row Data # Display the current row of data
idx = st.session_state.current_index if st.session_state.current_row < len(df):
row = df.iloc[idx] row_data = df.iloc[st.session_state.current_row]
display_row(row_data)
else:
st.write("No more rows to display")
st.divider() # Button to clear form and move to the next row
if st.button('Save and Next'):
if st.session_state.current_row < len(df):
save_edited_row(st.session_state.current_row)
st.session_state.current_row += 1
st.rerun() # Rerun the app to display the next row
# Input Form - Using dynamic key to ensure fresh widgets for each row st.write("")
with st.form(key=f"row_form_{idx}"):
st.subheader(f"{row['exercise']}")
st.caption(f"Set: {row['set']} | Group: {row['group']}")
c1, c2 = st.columns(2) # Button to save all changes back to the dataframe
new_weight = c1.number_input("Weight", value=float(row['weight']), step=2.5) if st.button('Save All Changes'):
new_reps = c2.number_input("Reps", value=int(row['reps']), step=1) df.update(st.session_state.edited_df)
new_notes = st.text_input("Notes", value=str(row['notes']) if row['notes'] else "") st.write("All changes saved!")
st.write(df)
conn = mysql.connector.connect(user=user,password=password, host=host,port=port,database=database)
cursor = conn.cursor()
for index, row in df.iterrows():
query = ("INSERT INTO `workouts`"
"(`inputdate`,`group`,`exercise`,`set`,`weight`,`reps`,`notes`) "
"VALUES (%s,%s,%s,%s,%s,%s,%s)")
cursor.execute(query,(row.iloc[1],row.iloc[2],row.iloc[3],row.iloc[4],row.iloc[5],row.iloc[6],row.iloc[7]))
conn.commit()
cursor.close()
conn.close()
if st.form_submit_button("Save & Next"):
st.session_state.workout_df.at[idx, 'weight'] = new_weight
st.session_state.workout_df.at[idx, 'reps'] = new_reps
st.session_state.workout_df.at[idx, 'notes'] = new_notes
if idx < len(df) - 1:
st.session_state.current_index += 1
st.rerun()
st.divider()
st.dataframe(st.session_state.workout_df)
if st.button("Commit Workout to Database"):
save_workout(st.session_state.workout_df)