Build a Python application to track and visualize personal fitness data.
- User
Build a Python application to track and visualize personal fitness data.
- Assistant
Designing a fitness app
The user wants me to build a Python application for tracking and visualizing personal fitness data, but they didn't specify details like length, environment, or skill level. I think I should consider different types of applications—like a command-line interface, simple web app, or Jupyter notebook. I'll explore options like using pandas and plot libraries. I want to clarify if the user prefers a GUI or something more straightforward. I could propose a Jupyter-based tracker or a full Flask/Streamlit solution!Planning the fitness tracker app
I think Streamlit would be the easiest route for this fitness tracking app, considering it can create interactive charts in a single Python file. Since the user wants to "track and visualize," I'm inclined to use SQLite, pandas, and matplotlib while possibly integrating Streamlit for the user interface. They didn’t mention environment restrictions, so I’ll assume installing dependencies is acceptable. I want to outline features like logging workouts, daily summaries, and graphs, along with the project structure and sample database schema.Creating the fitness app code
I need to provide code to set up a database with SQLite using either SQLAlchemy or sqlite3. I want to include CLI functions for data input and viewing summaries, but I’m thinking of suggesting Streamlit for an easier UI since the user is interested in visualization. I’ll use pandas for data handling and plotly.express for interactive charts. My
app.pywill include a function to createfitness.db, with tables for workouts, body metrics, and nutrition, plus forms for data entry and filters for date ranges.Focusing on a clear approachI realize I shouldn’t cut essential context, but since the user asked for a build, I’ll focus on moderate explanations alongside the code. I plan to provide easily copy-pasteable code in manageable sections while ensuring clarity. I think starting with a brief overview followed by detailed requirements would work well—suggesting a Streamlit app as the main solution. I’ll include installation tips and DB logic code, while keeping it concise to avoid overwhelming the user. Streamlit seems like the right choice!Defining the database schema
I’m defining the database with tables for
workoutsandbody_metrics. Each table will have appropriate fields like date, duration, weight, and calories, among others. I might combine daily steps intobody_metricsto keep it streamlined. Theinit_db()function will ensure these tables are created only if they don’t exist. In the Streamlit app, I'll add an interface that allows users to log workouts or body metrics, providing visualizations using pandas and eitherst.line_chartorst.bar_chart.Crafting the app code and instructionsI’ll simplify the date input for the user with
start_dateandend_dateusing Streamlit. I need to ensure I load body metrics and show them using a line chart while converting the date column to datetime. If there are missing values in daily steps or workouts, I’ll handle that asNaN.I'll define functions for adding workouts and body metrics, using optional fields to handle user input without forcing them to record zeros unnecessarily. The focus will be on clarity while producing a single
app.pycode block and arequirements.txt. Finally, I’ll include setup instructions and quick ideas for extensions. Below is a complete, minimal Streamlit app you can run locally to track and visualize personal fitness data (workouts + body metrics) using Python and SQLite.
1. Project structure
Create a folder for your project, e.g.:
fitness_tracker/ ├─ app.py └─ requirements.txtrequirements.txtstreamlit>=1.30 pandas>=1.5Install dependencies:
cd fitness_tracker pip install -r requirements.txt
2. Main application (
app.py)import streamlit as st import sqlite3 from pathlib import Path from datetime import date, timedelta import pandas as pd DB_PATH = Path("fitness.db") # ---------- Database helpers ---------- def init_db(): """Create tables if they don't exist.""" with sqlite3.connect(DB_PATH) as conn: cur = conn.cursor() # Workouts: cardio/strength/etc. cur.execute( """ CREATE TABLE IF NOT EXISTS workouts ( id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT NOT NULL, workout_type TEXT NOT NULL, duration_min REAL, distance_km REAL, calories REAL, notes TEXT ); """ ) # Body metrics: weight, steps, sleep, etc. cur.execute( """ CREATE TABLE IF NOT EXISTS body_metrics ( id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT NOT NULL, weight_kg REAL, body_fat_pct REAL, steps INTEGER, sleep_hours REAL, calories_in INTEGER, resting_hr INTEGER ); """ ) conn.commit() def add_workout(date_, workout_type, duration, distance, calories, notes): with sqlite3.connect(DB_PATH) as conn: cur = conn.cursor() cur.execute( """ INSERT INTO workouts (date, workout_type, duration_min, distance_km, calories, notes) VALUES (?, ?, ?, ?, ?, ?) """, (date_.isoformat(), workout_type, duration, distance, calories, notes or None), ) conn.commit() def add_body_metrics(date_, weight, body_fat, steps, sleep, calories_in, resting_hr): with sqlite3.connect(DB_PATH) as conn: cur = conn.cursor() cur.execute( """ INSERT INTO body_metrics (date, weight_kg, body_fat_pct, steps, sleep_hours, calories_in, resting_hr) VALUES (?, ?, ?, ?, ?, ?, ?) """, (date_.isoformat(), weight, body_fat, steps, sleep, calories_in, resting_hr), ) conn.commit() def load_body_metrics(start_date, end_date): with sqlite3.connect(DB_PATH) as conn: query = """ SELECT date, weight_kg, body_fat_pct, steps, sleep_hours, calories_in, resting_hr FROM body_metrics WHERE date BETWEEN ? AND ? ORDER BY date """ df = pd.read_sql_query( query, conn, params=(start_date.isoformat(), end_date.isoformat()) ) if not df.empty: df["date"] = pd.to_datetime(df["date"]) return df def load_workouts(start_date, end_date): with sqlite3.connect(DB_PATH) as conn: query = """ SELECT date, workout_type, duration_min, distance_km, calories, notes FROM workouts WHERE date BETWEEN ? AND ? ORDER BY date """ df = pd.read_sql_query( query, conn, params=(start_date.isoformat(), end_date.isoformat()) ) if not df.empty: df["date"] = pd.to_datetime(df["date"]) return df # ---------- Streamlit UI ---------- init_db() st.set_page_config(page_title="Personal Fitness Tracker", layout="wide") st.title("🏋️ Personal Fitness Tracker") # Sidebar: data entry st.sidebar.header("Log new data") log_type = st.sidebar.radio("What do you want to log?", ("Workout", "Body metrics")) if log_type == "Workout": with st.sidebar.form("workout_form", clear_on_submit=True): w_date = st.date_input("Date", value=date.today()) w_type = st.selectbox( "Workout type", ["Run", "Walk", "Cycling", "Strength", "Yoga", "Other"], ) duration = st.number_input("Duration (minutes)", min_value=0.0, step=5.0, value=0.0) distance = st.number_input("Distance (km)", min_value=0.0, step=0.5, value=0.0) calories = st.number_input("Calories burned", min_value=0.0, step=10.0, value=0.0) notes = st.text_area("Notes (optional)", height=80) submitted = st.form_submit_button("Save workout") if submitted: add_workout(w_date, w_type, duration, distance, calories, notes) st.success("Workout saved.") else: # Body metrics with st.sidebar.form("metrics_form", clear_on_submit=True): m_date = st.date_input("Date", value=date.today()) weight = st.number_input("Weight (kg)", min_value=0.0, step=0.1, value=0.0) body_fat = st.number_input("Body fat (%)", min_value=0.0, max_value=60.0, step=0.1, value=0.0) steps = st.number_input("Steps", min_value=0, step=500, value=0) sleep = st.number_input("Sleep (hours)", min_value=0.0, step=0.5, value=0.0) calories_in = st.number_input("Calories consumed", min_value=0, step=50, value=0) resting_hr = st.number_input("Resting heart rate (bpm)", min_value=0, step=1, value=0) submitted = st.form_submit_button("Save body metrics") if submitted: add_body_metrics(m_date, weight, body_fat, steps, sleep, calories_in, resting_hr) st.success("Metrics saved.") # Main area: filters + visualizations st.subheader("Dashboard") col1, col2 = st.columns(2) with col1: start_date = st.date_input("Start date", value=date.today() - timedelta(days=30)) with col2: end_date = st.date_input("End date", value=date.today()) if start_date > end_date: st.error("Start date must be before end date.") st.stop() body_df = load_body_metrics(start_date, end_date) workout_df = load_workouts(start_date, end_date) # ----- Body metrics charts ----- st.markdown("### Body metrics") if body_df.empty: st.info("No body metrics in this date range yet.") else: body_df = body_df.set_index("date").sort_index() metrics_cols = st.multiselect( "Select metrics to plot", ["weight_kg", "body_fat_pct", "steps", "sleep_hours", "calories_in", "resting_hr"], default=["weight_kg", "steps"], format_func=lambda x: { "weight_kg": "Weight (kg)", "body_fat_pct": "Body fat (%)", "steps": "Steps", "sleep_hours": "Sleep (hours)", "calories_in": "Calories in", "resting_hr": "Resting HR", }[x], ) if metrics_cols: st.line_chart(body_df[metrics_cols]) st.caption("Raw body metrics data") st.dataframe(body_df.reset_index(), use_container_width=True) # ----- Workout charts ----- st.markdown("### Workouts") if workout_df.empty: st.info("No workouts in this date range yet.") else: workout_df = workout_df.sort_values("date") # Aggregate by date daily = ( workout_df.groupby("date") .agg( total_duration_min=("duration_min", "sum"), total_distance_km=("distance_km", "sum"), total_calories=("calories", "sum"), ) .sort_index() ) st.write("Total duration (min) by day") st.bar_chart(daily["total_duration_min"]) st.write("Total distance (km) by day") st.bar_chart(daily["total_distance_km"]) # Breakdown by workout type (duration) by_type = ( workout_df.groupby(["date", "workout_type"])["duration_min"] .sum() .unstack(fill_value=0) .sort_index() ) st.write("Duration by workout type") st.area_chart(by_type) st.caption("Raw workout data") st.dataframe(workout_df, use_container_width=True)
3. Run the app
From the
fitness_trackerdirectory:streamlit run app.pyThen open the URL Streamlit prints (usually
http://localhost:8501).You can now:
- Use the sidebar to log workouts and body metrics.
- Use the date filters to see charts of:
- Weight, steps, sleep, etc. over time.
- Daily total workout duration and distance.
- Workout duration broken down by type.
If you tell me which extra features you want (goals, PR tracking, export to CSV, integration with wearables, etc.), I can expand this app accordingly.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.