Considering Fitness Data App
I'm now fully focused on the user's objective: a Python app to track and visualize their fitness. I'm exploring the core functionalities needed. I'm considering initial data sources and visualization options to meet their needs.
Outlining Core Functionality
I've scoped out the core features and am progressing with the architecture of the fitness app. SQLite will handle the data storage, Pandas will handle data manipulation, and Streamlit will handle both the interactive user interface and interactive visualizations. Considering user-friendly data entry forms, and interactive charts that update in real-time. Key metrics like date, exercise type, duration, and intensity are top of mind.
Refining Data Input & Display
I'm now focusing on user-friendliness. The plan is to use a Streamlit form for data input, allowing for easy workout logging. Displaying the raw data in the main area is essential. Interactive charts, like a line chart for progress and a bar chart for distribution by activity, are next. The plan is to use SQLite for data storage. I am now working on the database table structure.
Constructing App Implementation
I'm now fully immersed in the code. I've drafted the essential imports, established the SQLite connection, and have built a basic data input form using Streamlit. I've coded the logic for saving user data into the database and have the foundations of the visualization with the line chart plotting calories over time. Next I'll focus on error handling and improving the app's overall aesthetics by adding a title, displaying key workout metrics, and separating the database logic from the user interface.
Documenting App Development
I'm wrapping up the code, making sure everything aligns with the requirements. I've documented the code clearly and added comments for easy understanding. I've also added instructions on how to run the app. I reviewed the code's readability and functionality, focusing on user-friendliness. While a "delete" feature might be complex for this initial version, I am considering ways to improve usability.
Streamlining App Features
I've decided to keep the app focused on "Add" and "View" functionalities for this iteration. I'm prioritizing a clean and simple interface, so deleting is off the table, at least for now. My main goal is to deliver a functional and user-friendly experience first. This helps with managing the scope, and the user can always delete their entire data from the database.
To build a modern, interactive fitness tracker quickly, the best approach is to use Streamlit. Streamlit acts as both the frontend (UI) and the glue code, while SQLite handles storage and Pandas handles data manipulation.
Here is a complete, single-file Python application.
Prerequisites
You will need to install Streamlit and Pandas. Open your terminal and run:
pip install streamlit pandas matplotlib
The Code (app.py)
Create a file named app.py and paste the following code:
import streamlit as st
import pandas as pd
import sqlite3
from datetime import date
# ==========================
# 1. DATABASE CONFIGURATION
# ==========================
DB_NAME = "fitness_log.db"
def init_db():
"""Initialize the SQLite database and create the table if it doesn't exist."""
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS workouts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT,
workout_type TEXT,
duration_minutes INTEGER,
calories_burned INTEGER,
notes TEXT
)
''')
conn.commit()
conn.close()
def add_workout(date_val, workout_type, duration, calories, notes):
"""Add a new workout entry to the database."""
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute('INSERT INTO workouts (date, workout_type, duration_minutes, calories_burned, notes) VALUES (?,?,?,?,?)',
(date_val, workout_type, duration, calories, notes))
conn.commit()
conn.close()
def load_data():
"""Load data from database into a Pandas DataFrame."""
conn = sqlite3.connect(DB_NAME)
df = pd.read_sql_query("SELECT * FROM workouts", conn)
conn.close()
return df
# Initialize the DB on first run
init_db()
# ==========================
# 2. APP UI LAYOUT
# ==========================
st.set_page_config(page_title="Personal Fitness Tracker", page_icon="💪", layout="wide")
st.title("💪 Personal Fitness Tracker")
st.markdown("Track your workouts and visualize your progress.")
# --- SIDEBAR: INPUT FORM ---
st.sidebar.header("Add New Workout")
with st.sidebar.form(key='workout_form'):
date_input = st.date_input("Date", date.today())
workout_type = st.selectbox(
"Workout Type",
["Running", "Cycling", "Weightlifting", "Swimming", "Yoga", "HIIT", "Walking", "Other"]
)
duration = st.number_input("Duration (Minutes)", min_value=0, max_value=600, value=30, step=5)
calories = st.number_input("Calories Burned", min_value=0, max_value=5000, value=0, step=50)
notes = st.text_area("Notes (optional)")
submit_button = st.form_submit_button(label='Add Workout')
if submit_button:
add_workout(date_input, workout_type, duration, calories, notes)
st.sidebar.success("Workout saved!")
# --- MAIN AREA: DATA OVERVIEW ---
df = load_data()
# Convert 'date' column to datetime objects for better sorting/graphing
if not df.empty:
df['date'] = pd.to_datetime(df['date'])
df = df.sort_values(by='date')
# Display Key Metrics
col1, col2, col3 = st.columns(3)
if not df.empty:
total_cals = df['calories_burned'].sum()
total_time = df['duration_minutes'].sum()
total_workouts = len(df)
col1.metric("Total Workouts", total_workouts)
col2.metric("Total Calories Burned", f"{total_cals:,} kcal")
col3.metric("Total Duration", f"{total_time} mins")
else:
st.info("No data found. Use the sidebar to add your first workout!")
st.divider()
# ==========================
# 3. VISUALIZATION
# ==========================
if not df.empty:
# Create two columns for charts
chart_col1, chart_col2 = st.columns(2)
with chart_col1:
st.subheader("Calories Burned Over Time")
# Resample data to sum calories by day (handles multiple workouts in one day)
daily_data = df.groupby('date')['calories_burned'].sum()
st.line_chart(daily_data)
with chart_col2:
st.subheader("Workout Duration Distribution")
# Bar chart for Duration
st.bar_chart(df.set_index('date')['duration_minutes'])
st.subheader("Workout Type Breakdown")
type_counts = df['workout_type'].value_counts()
st.bar_chart(type_counts)
# ==========================
# 4. RAW DATA VIEW
# ==========================
with st.expander("View Raw Data Log"):
# Display dataframe sorted by newest first
st.dataframe(df.sort_values(by='date', ascending=False), use_container_width=True)
# simple delete functionality (delete last entry)
if st.button("Delete Last Entry"):
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
# Get ID of last row
c.execute("SELECT id FROM workouts ORDER BY id DESC LIMIT 1")
last_id = c.fetchone()
if last_id:
c.execute("DELETE FROM workouts WHERE id=?", (last_id[0],))
conn.commit()
st.rerun() # Refresh app
conn.close()
How to Run Application
- Save the code above into a file named
app.py.
- Open your terminal/command prompt in the folder where you saved the file.
- Run the following command:
streamlit run app.py
- A new tab will open in your web browser with your running application.
Implementation Details
- Database (SQLite): The app automatically creates a lightweight local file
fitness_log.db. You don't need to install any database software; it's built into Python.
- Data Processing (Pandas): We use Pandas to load the SQL data produces a DataFrame. This makes it easy to group dates together (e.g., if you worked out twice in one day) and sort data for charts.
- Data Entry (Sidebar): The
st.sidebar.form creates a neat input area specifically for adding data, keeping the visualizations as the main focus.
- Visualizations:
- Line Chart: Shows your calorie progress over time.
- Bar Chart: Shows which types of exercises you do most frequently.
- Metrics: The top "scorecard" shows your total stats instantly.
How to expand this project
Once you have this running, here are ideas to improve it:
- Goal Setting: Add a line on the chart representing a daily calorie goal.
- CSV Export: Add a button to download your data as a CSV file using
df.to_csv().
- Body Stats: Create a second table to track weight and body fat percentage alongside your workouts.