#!/usr/bin/env python3
"""
Personal Fitness Tracker
A comprehensive application to track and visualize your fitness data.
Author: Fitness Tracker Team
"""
import tkinter as tk
from tkinter import ttk, messagebox, filedialog, font
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import sqlite3
import csv
import json
from pathlib import Path
from typing import Dict, List, Tuple, Optional
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.dates as mdates
import numpy as np
# Try to import scipy for trend lines, fallback if not available
try:
from scipy import stats
SCIPY_AVAILABLE = True
except ImportError:
SCIPY_AVAILABLE = False
class FitnessDatabase:
"""Handles all database operations for fitness data."""
def __init__(self, db_path: str = "fitness_data.db"):
self.db_path = db_path
self.init_database()
def get_connection(self) -> sqlite3.Connection:
"""Get a database connection."""
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
return conn
def init_database(self):
"""Initialize the database schema."""
conn = self.get_connection()
cursor = conn.cursor()
# Main fitness entries table
cursor.execute('''
CREATE TABLE IF NOT EXISTS fitness_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT UNIQUE NOT NULL,
weight REAL,
calories_consumed INTEGER,
calories_burned INTEGER,
water_intake REAL,
sleep_hours REAL,
exercise_type TEXT,
exercise_duration INTEGER,
steps INTEGER,
heart_rate_avg INTEGER,
notes TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
)
''')
# Goals table
cursor.execute('''
CREATE TABLE IF NOT EXISTS goals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
metric TEXT NOT NULL,
target_value REAL NOT NULL,
start_date TEXT,
end_date TEXT,
is_active INTEGER DEFAULT 1,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)
''')
# Exercise types reference table
cursor.execute('''
CREATE TABLE IF NOT EXISTS exercise_types (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
calories_per_hour INTEGER,
category TEXT
)
''')
# Insert default exercise types if empty
cursor.execute('SELECT COUNT(*) FROM exercise_types')
if cursor.fetchone()[0] == 0:
default_exercises = [
('Running', 600, 'Cardio'),
('Walking', 250, 'Cardio'),
('Cycling', 500, 'Cardio'),
('Swimming', 550, 'Cardio'),
('Weight Training', 350, 'Strength'),
('Yoga', 180, 'Flexibility'),
('HIIT', 700, 'Cardio'),
('Dancing', 400, 'Cardio'),
('Basketball', 500, 'Sports'),
('Tennis', 450, 'Sports'),
]
cursor.executemany(
'INSERT INTO exercise_types (name, calories_per_hour, category) VALUES (?, ?, ?)',
default_exercises
)
conn.commit()
conn.close()
def add_entry(self, data: Dict) -> bool:
"""Add or update a fitness entry for a specific date."""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute('''
INSERT INTO fitness_entries
(date, weight, calories_consumed, calories_burned, water_intake,
sleep_hours, exercise_type, exercise_duration, steps, heart_rate_avg, notes, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(date) DO UPDATE SET
weight = excluded.weight,
calories_consumed = excluded.calories_consumed,
calories_burned = excluded.calories_burned,
water_intake = excluded.water_intake,
sleep_hours = excluded.sleep_hours,
exercise_type = excluded.exercise_type,
exercise_duration = excluded.exercise_duration,
steps = excluded.steps,
heart_rate_avg = excluded.heart_rate_avg,
notes = excluded.notes,
updated_at = CURRENT_TIMESTAMP
''', (
data['date'], data.get('weight'), data.get('calories_consumed'),
data.get('calories_burned'), data.get('water_intake'), data.get('sleep_hours'),
data.get('exercise_type'), data.get('exercise_duration'), data.get('steps'),
data.get('heart_rate_avg'), data.get('notes')
))
conn.commit()
return True
except sqlite3.Error as e:
print(f"Database error: {e}")
return False
finally:
conn.close()
def get_entry(self, date: str) -> Optional[Dict]:
"""Get a fitness entry for a specific date."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM fitness_entries WHERE date = ?', (date,))
row = cursor.fetchone()
conn.close()
return dict(row) if row else None
def get_entries_range(self, start_date: str, end_date: str) -> List[Dict]:
"""Get fitness entries within a date range."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM fitness_entries
WHERE date BETWEEN ? AND ?
ORDER BY date ASC
''', (start_date, end_date))
entries = [dict(row) for row in cursor.fetchall()]
conn.close()
return entries
def get_all_entries(self) -> List[Dict]:
"""Get all fitness entries."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM fitness_entries ORDER BY date ASC')
entries = [dict(row) for row in cursor.fetchall()]
conn.close()
return entries
def delete_entry(self, date: str) -> bool:
"""Delete a fitness entry."""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute('DELETE FROM fitness_entries WHERE date = ?', (date,))
conn.commit()
return cursor.rowcount > 0
except sqlite3.Error:
return False
finally:
conn.close()
def get_statistics(self, days: int = 30) -> Dict:
"""Calculate statistics for the last N days."""
end_date = datetime.now().strftime('%Y-%m-%d')
start_date = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
entries = self.get_entries_range(start_date, end_date)
if not entries:
return {}
stats = {
'total_entries': len(entries),
'date_range': f"{start_date} to {end_date}"
}
# Weight statistics
weights = [e['weight'] for e in entries if e['weight']]
if weights:
stats['weight'] = {
'current': weights[-1],
'min': min(weights),
'max': max(weights),
'avg': np.mean(weights),
'change': weights[-1] - weights[0] if len(weights) > 1 else 0
}
# Calories statistics
calories_consumed = [e['calories_consumed'] for e in entries if e['calories_consumed']]
calories_burned = [e['calories_burned'] for e in entries if e['calories_burned']]
if calories_consumed:
stats['calories_consumed'] = {
'total': sum(calories_consumed),
'avg': np.mean(calories_consumed),
'max': max(calories_consumed),
'min': min(calories_consumed)
}
if calories_burned:
stats['calories_burned'] = {
'total': sum(calories_burned),
'avg': np.mean(calories_burned),
'max': max(calories_burned),
'min': min(calories_burned)
}
# Water intake statistics
water = [e['water_intake'] for e in entries if e['water_intake']]
if water:
stats['water'] = {
'total': sum(water),
'avg': np.mean(water),
'max': max(water),
'min': min(water)
}
# Sleep statistics
sleep = [e['sleep_hours'] for e in entries if e['sleep_hours']]
if sleep:
stats['sleep'] = {
'total': sum(sleep),
'avg': np.mean(sleep),
'max': max(sleep),
'min': min(sleep)
}
# Exercise statistics
exercise_durations = [e['exercise_duration'] for e in entries if e['exercise_duration']]
if exercise_durations:
stats['exercise'] = {
'total_minutes': sum(exercise_durations),
'total_hours': sum(exercise_durations) / 60,
'avg_per_session': np.mean(exercise_durations),
'sessions': len(exercise_durations)
}
# Steps statistics
steps = [e['steps'] for e in entries if e['steps']]
if steps:
stats['steps'] = {
'total': sum(steps),
'avg': np.mean(steps),
'max': max(steps),
'min': min(steps)
}
return stats
def get_exercise_types(self) -> List[Dict]:
"""Get all exercise types."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM exercise_types ORDER BY name')
exercises = [dict(row) for row in cursor.fetchall()]
conn.close()
return exercises
def add_goal(self, metric: str, target: float, end_date: str = None) -> bool:
"""Add a new fitness goal."""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute('''
INSERT INTO goals (metric, target_value, start_date, end_date)
VALUES (?, ?, ?, ?)
''', (metric, target, datetime.now().strftime('%Y-%m-%d'), end_date))
conn.commit()
return True
except sqlite3.Error:
return False
finally:
conn.close()
def get_active_goals(self) -> List[Dict]:
"""Get all active goals."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM goals WHERE is_active = 1 ORDER BY created_at DESC')
goals = [dict(row) for row in cursor.fetchall()]
conn.close()
return goals
def export_to_csv(self, filepath: str) -> bool:
"""Export all data to CSV."""
entries = self.get_all_entries()
if not entries:
return False
try:
with open(filepath, 'w', newline='', encoding='utf-8') as f:
if entries:
writer = csv.DictWriter(f, fieldnames=entries[0].keys())
writer.writeheader()
writer.writerows(entries)
return True
except (IOError, csv.Error):
return False
def import_from_csv(self, filepath: str) -> Tuple[bool, int]:
"""Import data from CSV."""
try:
with open(filepath, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
count = 0
for row in reader:
# Clean up the data
data = {}
for key, value in row.items():
if value == '' or value is None:
data[key] = None
elif key in ['weight', 'water_intake', 'sleep_hours']:
data[key] = float(value) if value else None
elif key in ['calories_consumed', 'calories_burned', 'exercise_duration', 'steps', 'heart_rate_avg']:
data[key] = int(float(value)) if value else None
else:
data[key] = value
if 'date' in data and data['date']:
self.add_entry(data)
count += 1
return True, count
except (IOError, csv.Error, ValueError) as e:
print(f"Import error: {e}")
return False, 0
class DataEntryDialog(tk.Toplevel):
"""Dialog for entering/editing fitness data."""
def __init__(self, parent, db: FitnessDatabase, date: str = None, edit_data: Dict = None):
super().__init__(parent)
self.db = db
self.date = date or datetime.now().strftime('%Y-%m-%d')
self.edit_data = edit_data
self.result = False
self.title("Fitness Entry")
self.geometry("500x700")
self.resizable(False, False)
self.configure(bg='#f0f0f0')
# Make it modal
self.transient(parent)
self.grab_set()
self.create_widgets()
# Center the dialog
self.update_idletasks()
x = parent.winfo_x() + (parent.winfo_width() - self.winfo_width()) // 2
y = parent.winfo_y() + (parent.winfo_height() - self.winfo_height()) // 2
self.geometry(f"+{x}+{y}")
def create_widgets(self):
"""Create all widgets for the dialog."""
main_frame = ttk.Frame(self, padding="20")
main_frame.pack(fill=tk.BOTH, expand=True)
# Date selection
date_frame = ttk.LabelFrame(main_frame, text="Date", padding="10")
date_frame.pack(fill=tk.X, pady=(0, 15))
self.date_var = tk.StringVar(value=self.date)
date_entry = ttk.Entry(date_frame, textvariable=self.date_var, width=15)
date_entry.pack(side=tk.LEFT, padx=(0, 10))
# Date picker buttons
btn_frame = ttk.Frame(date_frame)
btn_frame.pack(side=tk.LEFT)
ttk.Button(btn_frame, text="◀", width=3,
command=lambda: self.change_date(-1)).pack(side=tk.LEFT, padx=2)
ttk.Button(btn_frame, text="Today", width=6,
command=self.set_today).pack(side=tk.LEFT, padx=2)
ttk.Button(btn_frame, text="▶", width=3,
command=lambda: self.change_date(1)).pack(side=tk.LEFT, padx=2)
# Body metrics
body_frame = ttk.LabelFrame(main_frame, text="Body Metrics", padding="10")
body_frame.pack(fill=tk.X, pady=(0, 15))
ttk.Label(body_frame, text="Weight (kg):").grid(row=0, column=0, sticky=tk.W, pady=5)
self.weight_var = tk.StringVar(value=self.edit_data.get('weight', '') if self.edit_data else '')
ttk.Entry(body_frame, textvariable=self.weight_var, width=15).grid(row=0, column=1, padx=10, pady=5)
ttk.Label(body_frame, text="Avg Heart Rate:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.heart_rate_var = tk.StringVar(value=self.edit_data.get('heart_rate_avg', '') if self.edit_data else '')
ttk.Entry(body_frame, textvariable=self.heart_rate_var, width=15).grid(row=1, column=1, padx=10, pady=5)
ttk.Label(body_frame, text="Steps:").grid(row=2, column=0, sticky=tk.W, pady=5)
self.steps_var = tk.StringVar(value=self.edit_data.get('steps', '') if self.edit_data else '')
ttk.Entry(body_frame, textvariable=self.steps_var, width=15).grid(row=2, column=1, padx=10, pady=5)
# Nutrition
nutrition_frame = ttk.LabelFrame(main_frame, text="Nutrition", padding="10")
nutrition_frame.pack(fill=tk.X, pady=(0, 15))
ttk.Label(nutrition_frame, text="Calories Consumed:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.calories_in_var = tk.StringVar(value=self.edit_data.get('calories_consumed', '') if self.edit_data else '')
ttk.Entry(nutrition_frame, textvariable=self.calories_in_var, width=15).grid(row=0, column=1, padx=10, pady=5)
ttk.Label(nutrition_frame, text="Water Intake (L):").grid(row=1, column=0, sticky=tk.W, pady=5)
self.water_var = tk.StringVar(value=self.edit_data.get('water_intake', '') if self.edit_data else '')
ttk.Entry(nutrition_frame, textvariable=self.water_var, width=15).grid(row=1, column=1, padx=10, pady=5)
# Exercise
exercise_frame = ttk.LabelFrame(main_frame, text="Exercise", padding="10")
exercise_frame.pack(fill=tk.X, pady=(0, 15))
ttk.Label(exercise_frame, text="Exercise Type:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.exercise_type_var = tk.StringVar(value=self.edit_data.get('exercise_type', '') if self.edit_data else '')
exercise_types = [e['name'] for e in self.db.get_exercise_types()]
exercise_combo = ttk.Combobox(exercise_frame, textvariable=self.exercise_type_var,
values=exercise_types, width=20)
exercise_combo.grid(row=0, column=1, padx=10, pady=5)
ttk.Label(exercise_frame, text="Duration (min):").grid(row=1, column=0, sticky=tk.W, pady=5)
self.duration_var = tk.StringVar(value=self.edit_data.get('exercise_duration', '') if self.edit_data else '')
ttk.Entry(exercise_frame, textvariable=self.duration_var, width=15).grid(row=1, column=1, padx=10, pady=5)
ttk.Label(exercise_frame, text="Calories Burned:").grid(row=2, column=0, sticky=tk.W, pady=5)
self.calories_out_var = tk.StringVar(value=self.edit_data.get('calories_burned', '') if self.edit_data else '')
ttk.Entry(exercise_frame, textvariable=self.calories_out_var, width=15).grid(row=2, column=1, padx=10, pady=5)
# Sleep
sleep_frame = ttk.LabelFrame(main_frame, text="Sleep", padding="10")
sleep_frame.pack(fill=tk.X, pady=(0, 15))
ttk.Label(sleep_frame, text="Hours Slept:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.sleep_var = tk.StringVar(value=self.edit_data.get('sleep_hours', '') if self.edit_data else '')
sleep_scale = ttk.Scale(sleep_frame, from_=0, to=12, variable=self.sleep_var,
orient=tk.HORIZONTAL, length=150)
sleep_scale.grid(row=0, column=1, padx=10, pady=5)
self.sleep_label = ttk.Label(sleep_frame, text="0 hrs")
self.sleep_label.grid(row=0, column=2, padx=5)
sleep_scale.configure(command=self.update_sleep_label)
# Notes
notes_frame = ttk.LabelFrame(main_frame, text="Notes", padding="10")
notes_frame.pack(fill=tk.X, pady=(0, 15))
self.notes_var = tk.StringVar(value=self.edit_data.get('notes', '') if self.edit_data else '')
notes_text = tk.Text(notes_frame, height=3, width=40)
notes_text.pack(fill=tk.X)
if self.edit_data and self.edit_data.get('notes'):
notes_text.insert('1.0', self.edit_data['notes'])
self.notes_text = notes_text
# Buttons
btn_frame = ttk.Frame(main_frame)
btn_frame.pack(fill=tk.X, pady=(10, 0))
ttk.Button(btn_frame, text="Save", command=self.save, width=15).pack(side=tk.LEFT, padx=5)
ttk.Button(btn_frame, text="Cancel", command=self.cancel, width=15).pack(side=tk.LEFT, padx=5)
if self.edit_data:
ttk.Button(btn_frame, text="Delete", command=self.delete_entry, width=15).pack(side=tk.RIGHT, padx=5)
def update_sleep_label(self, value):
"""Update sleep label with current value."""
self.sleep_label.configure(text=f"{float(value):.1f} hrs")
def change_date(self, delta: int):
"""Change the date by delta days."""
try:
current = datetime.strptime(self.date_var.get(), '%Y-%m-%d')
new_date = current + timedelta(days=delta)
self.date_var.set(new_date.strftime('%Y-%m-%d'))
except ValueError:
pass
def set_today(self):
"""Set date to today."""
self.date_var.set(datetime.now().strftime('%Y-%m-%d'))
def save(self):
"""Save the entry."""
try:
data = {
'date': self.date_var.get(),
'weight': float(self.weight_var.get()) if self.weight_var.get() else None,
'calories_consumed': int(self.calories_in_var.get()) if self.calories_in_var.get() else None,
'calories_burned': int(self.calories_out_var.get()) if self.calories_out_var.get() else None,
'water_intake': float(self.water_var.get()) if self.water_var.get() else None,
'sleep_hours': float(self.sleep_var.get()) if self.sleep_var.get() else None,
'exercise_type': self.exercise_type_var.get() if self.exercise_type_var.get() else None,
'exercise_duration': int(self.duration_var.get()) if self.duration_var.get() else None,
'steps': int(self.steps_var.get()) if self.steps_var.get() else None,
'heart_rate_avg': int(self.heart_rate_var.get()) if self.heart_rate_var.get() else None,
'notes': self.notes_text.get('1.0', tk.END).strip() if self.notes_text.get('1.0', tk.END).strip() else None
}
# Validate date
datetime.strptime(data['date'], '%Y-%m-%d')
if self.db.add_entry(data):
self.result = True
self.destroy()
else:
messagebox.showerror("Error", "Failed to save entry", parent=self)
except ValueError as e:
messagebox.showerror("Validation Error", f"Please check your inputs: {e}", parent=self)
def delete_entry(self):
"""Delete the current entry."""
if messagebox.askyesno("Confirm Delete", "Are you sure you want to delete this entry?", parent=self):
if self.db.delete_entry(self.date_var.get()):
self.result = True
self.destroy()
else:
messagebox.showerror("Error", "Failed to delete entry", parent=self)
def cancel(self):
"""Cancel and close the dialog."""
self.destroy()
class ChartsFrame(ttk.Frame):
"""Frame for displaying fitness charts."""
def __init__(self, parent, db: FitnessDatabase):
super().__init__(parent)
self.db = db
self.create_widgets()
def create_widgets(self):
"""Create chart widgets."""
# Control frame
control_frame = ttk.Frame(self)
control_frame.pack(fill=tk.X, padx=10, pady=10)
ttk.Label(control_frame, text="Time Range:").pack(side=tk.LEFT, padx=5)
self.time_range_var = tk.StringVar(value="30")
time_combo = ttk.Combobox(control_frame, textvariable=self.time_range_var,
values=["7", "14", "30", "60", "90", "180", "365"],
width=10, state='readonly')
time_combo.pack(side=tk.LEFT, padx=5)
time_combo.bind('<<ComboboxSelected>>', lambda e: self.refresh_charts())
ttk.Button(control_frame, text="Refresh", command=self.refresh_charts).pack(side=tk.LEFT, padx=10)
# Notebook for different chart views
self.notebook = ttk.Notebook(self)
self.notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
# Create chart frames
self.weight_chart_frame = ttk.Frame(self.notebook)
self.calories_chart_frame = ttk.Frame(self.notebook)
self.exercise_chart_frame = ttk.Frame(self.notebook)
self.sleep_chart_frame = ttk.Frame(self.notebook)
self.overview_chart_frame = ttk.Frame(self.notebook)
self.notebook.add(self.overview_chart_frame, text="Overview")
self.notebook.add(self.weight_chart_frame, text="Weight")
self.notebook.add(self.calories_chart_frame, text="Calories")
self.notebook.add(self.exercise_chart_frame, text="Exercise")
self.notebook.add(self.sleep_chart_frame, text="Sleep & Water")
# Store chart canvases
self.charts = {}
# Initial chart drawing
self.refresh_charts()
def refresh_charts(self):
"""Refresh all charts."""
days = int(self.time_range_var.get())
end_date = datetime.now()
start_date = end_date - timedelta(days=days)
entries = self.db.get_entries_range(
start_date.strftime('%Y-%m-%d'),
end_date.strftime('%Y-%m-%d')
)
# Clear existing charts
for frame in self.charts.values():
if frame:
for widget in frame.winfo_children():
widget.destroy()
# Draw new charts
self.draw_overview_chart(entries)
self.draw_weight_chart(entries)
self.draw_calories_chart(entries)
self.draw_exercise_chart(entries)
self.draw_sleep_water_chart(entries)
def draw_overview_chart(self, entries):
"""Draw overview chart with multiple metrics."""
for widget in self.overview_chart_frame.winfo_children():
widget.destroy()
if not entries:
ttk.Label(self.overview_chart_frame, text="No data available",
font=('Helvetica', 14)).pack(expand=True)
return
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
fig.suptitle('Fitness Overview', fontsize=14, fontweight='bold')
dates = [datetime.strptime(e['date'], '%Y-%m-%d') for e in entries]
# Weight subplot
ax1 = axes[0, 0]
weights = [e['weight'] for e in entries if e['weight']]
weight_dates = [dates[i] for i, e in enumerate(entries) if e['weight']]
if weights:
ax1.plot(weight_dates, weights, 'b-o', markersize=4, linewidth=2)
ax1.fill_between(weight_dates, weights, alpha=0.3)
ax1.set_title('Weight Trend')
ax1.set_ylabel('Weight (kg)')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
else:
ax1.text(0.5, 0.5, 'No weight data', ha='center', va='center', transform=ax1.transAxes)
ax1.grid(True, alpha=0.3)
# Calories subplot
ax2 = axes[0, 1]
cal_in = [e['calories_consumed'] for e in entries if e['calories_consumed']]
cal_in_dates = [dates[i] for i, e in enumerate(entries) if e['calories_consumed']]
if cal_in:
ax2.bar(cal_in_dates, cal_in, color='coral', alpha=0.7, label='Consumed')
ax2.set_title('Calories Consumed')
ax2.set_ylabel('Calories')
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
else:
ax2.text(0.5, 0.5, 'No calorie data', ha='center', va='center', transform=ax2.transAxes)
ax2.grid(True, alpha=0.3, axis='y')
# Steps subplot
ax3 = axes[1, 0]
steps = [e['steps'] for e in entries if e['steps']]
steps_dates = [dates[i] for i, e in enumerate(entries) if e['steps']]
if steps:
colors = ['green' if s >= 10000 else 'orange' if s >= 5000 else 'red' for s in steps]
ax3.bar(steps_dates, steps, color=colors, alpha=0.7)
ax3.axhline(y=10000, color='green', linestyle='--', label='Goal: 10,000')
ax3.set_title('Daily Steps')
ax3.set_ylabel('Steps')
ax3.legend()
ax3.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
else:
ax3.text(0.5, 0.5, 'No steps data', ha='center', va='center', transform=ax3.transAxes)
ax3.grid(True, alpha=0.3, axis='y')
# Sleep subplot
ax4 = axes[1, 1]
sleep = [e['sleep_hours'] for e in entries if e['sleep_hours']]
sleep_dates = [dates[i] for i, e in enumerate(entries) if e['sleep_hours']]
if sleep:
ax4.bar(sleep_dates, sleep, color='purple', alpha=0.7)
ax4.axhline(y=8, color='green', linestyle='--', label='Recommended: 8 hrs')
ax4.axhline(y=7, color='orange', linestyle='--', alpha=0.5)
ax4.set_title('Sleep Hours')
ax4.set_ylabel('Hours')
ax4.legend()
ax4.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
else:
ax4.text(0.5, 0.5, 'No sleep data', ha='center', va='center', transform=ax4.transAxes)
ax4.grid(True, alpha=0.3, axis='y')
plt.tight_layout()
canvas = FigureCanvasTkAgg(fig, master=self.overview_chart_frame)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
self.charts['overview'] = fig
def draw_weight_chart(self, entries):
"""Draw detailed weight chart."""
for widget in self.weight_chart_frame.winfo_children():
widget.destroy()
weights = [e['weight'] for e in entries if e['weight']]
dates = [datetime.strptime(e['date'], '%Y-%m-%d') for e in entries if e['weight']]
if not weights:
ttk.Label(self.weight_chart_frame, text="No weight data available",
font=('Helvetica', 14)).pack(expand=True)
return
fig, ax = plt.subplots(figsize=(12, 6))
# Plot weight data
ax.plot(dates, weights, 'b-o', markersize=6, linewidth=2, label='Weight')
# Add trend line if scipy is available
if SCIPY_AVAILABLE and len(weights) > 2:
x_numeric = mdates.date2num(dates)
slope, intercept, r_value, p_value, std_err = stats.linregress(x_numeric, weights)
trend_line = slope * x_numeric + intercept
ax.plot(dates, trend_line, 'r--', linewidth=2,
label=f'Trend (R²={r_value**2:.3f})')
# Add moving average
if len(weights) >= 7:
window = 7
weights_array = np.array(weights)
moving_avg = np.convolve(weights_array, np.ones(window)/window, mode='valid')
ma_dates = dates[window-1:]
ax.plot(ma_dates, moving_avg, 'g-', linewidth=2, alpha=0.7,
label='7-day Moving Avg')
ax.set_xlabel('Date')
ax.set_ylabel('Weight (kg)')
ax.set_title('Weight Progress', fontsize=14, fontweight='bold')
ax.legend()
ax.grid(True, alpha=0.3)
# Format x-axis
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1))
plt.xticks(rotation=45)
# Add statistics text box
stats_text = f"Current: {weights[-1]:.1f} kg\n"
stats_text += f"Min: {min(weights):.1f} kg\n"
stats_text += f"Max: {max(weights):.1f} kg\n"
stats_text += f"Avg: {np.mean(weights):.1f} kg\n"
if len(weights) > 1:
change = weights[-1] - weights[0]
stats_text += f"Change: {change:+.1f} kg"
props = dict(boxstyle='round', facecolor='wheat', alpha=0.8)
ax.text(0.02, 0.98, stats_text, transform=ax.transAxes, fontsize=10,
verticalalignment='top', bbox=props)
plt.tight_layout()
canvas = FigureCanvasTkAgg(fig, master=self.weight_chart_frame)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
self.charts['weight'] = fig
def draw_calories_chart(self, entries):
"""Draw calories chart."""
for widget in self.calories_chart_frame.winfo_children():
widget.destroy()
cal_in = [e['calories_consumed'] or 0 for e in entries]
cal_out = [e['calories_burned'] or 0 for e in entries]
dates = [datetime.strptime(e['date'], '%Y-%m-%d') for e in entries]
if not any(cal_in) and not any(cal_out):
ttk.Label(self.calories_chart_frame, text="No calorie data available",
font=('Helvetica', 14)).pack(expand=True)
return
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
x = np.arange(len(dates))
width = 0.35
# Calories consumed vs burned
if any(cal_in) or any(cal_out):
bars1 = ax1.bar(x - width/2, cal_in, width, label='Consumed', color='coral', alpha=0.8)
bars2 = ax1.bar(x + width/2, cal_out, width, label='Burned', color='green', alpha=0.8)
ax1.set_xlabel('Date')
ax1.set_ylabel('Calories')
ax1.set_title('Calories: Consumed vs Burned', fontweight='bold')
ax1.set_xticks(x[::max(1, len(x)//10)])
ax1.set_xticklabels([d.strftime('%m/%d') for d in dates][::max(1, len(dates)//10)])
ax1.legend()
ax1.grid(True, alpha=0.3, axis='y')
# Net calories
net_calories = [c_in - c_out for c_in, c_out in zip(cal_in, cal_out)]
colors = ['green' if nc <= 0 else 'red' for nc in net_calories]
ax2.bar(x, net_calories, color=colors, alpha=0.7)
ax2.axhline(y=0, color='black', linestyle='-', linewidth=0.5)
ax2.set_xlabel('Date')
ax2.set_ylabel('Net Calories')
ax2.set_title('Net Calories (Consumed - Burned)', fontweight='bold')
ax2.set_xticks(x[::max(1, len(x)//10)])
ax2.set_xticklabels([d.strftime('%m/%d') for d in dates][::max(1, len(dates)//10)])
ax2.grid(True, alpha=0.3, axis='y')
# Add statistics
avg_net = np.mean(net_calories) if net_calories else 0
ax2.text(0.02, 0.98, f'Avg Net: {avg_net:.0f} cal/day',
transform=ax2.transAxes, fontsize=10, verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))
plt.tight_layout()
canvas = FigureCanvasTkAgg(fig, master=self.calories_chart_frame)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
self.charts['calories'] = fig
def draw_exercise_chart(self, entries):
"""Draw exercise statistics chart."""
for widget in self.exercise_chart_frame.winfo_children():
widget.destroy()
exercise_entries = [e for e in entries if e['exercise_type'] or e['exercise_duration']]
if not exercise_entries:
ttk.Label(self.exercise_chart_frame, text="No exercise data available",
font=('Helvetica', 14)).pack(expand=True)
return
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# Exercise duration over time
durations = [e['exercise_duration'] or 0 for e in entries]
dates = [datetime.strptime(e['date'], '%Y-%m-%d') for e in entries]
colors = ['green' if d >= 30 else 'orange' if d > 0 else 'gray' for d in durations]
ax1.bar(dates, durations, color=colors, alpha=0.7)
ax1.axhline(y=30, color='green', linestyle='--', label='30 min goal')
ax1.set_xlabel('Date')
ax1.set_ylabel('Duration (minutes)')
ax1.set_title('Exercise Duration', fontweight='bold')
ax1.legend()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
ax1.grid(True, alpha=0.3, axis='y')
# Exercise type distribution
exercise_types = {}
for e in entries:
if e['exercise_type'] and e['exercise_duration']:
exercise_types[e['exercise_type']] = exercise_types.get(e['exercise_type'], 0) + e['exercise_duration']
if exercise_types:
labels = list(exercise_types.keys())
sizes = list(exercise_types.values())
colors_pie = plt.cm.Set3(np.linspace(0, 1, len(labels)))
wedges, texts, autotexts = ax2.pie(sizes, labels=labels, autopct='%1.1f%%',
colors=colors_pie, startangle=90)
ax2.set_title('Exercise Distribution (by time)', fontweight='bold')
else:
ax2.text(0.5, 0.5, 'No exercise type data', ha='center', va='center', transform=ax2.transAxes)
plt.tight_layout()
canvas = FigureCanvasTkAgg(fig, master=self.exercise_chart_frame)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
self.charts['exercise'] = fig
def draw_sleep_water_chart(self, entries):
"""Draw sleep and water intake charts."""
for widget in self.sleep_chart_frame.winfo_children():
widget.destroy()
sleep_data = [e['sleep_hours'] for e in entries if e['sleep_hours']]
water_data = [e['water_intake'] for e in entries if e['water_intake']]
if not sleep_data and not water_data:
ttk.Label(self.sleep_chart_frame, text="No sleep or water data available",
font=('Helvetica', 14)).pack(expand=True)
return
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
dates = [datetime.strptime(e['date'], '%Y-%m-%d') for e in entries]
# Sleep chart
sleep_values = [e['sleep_hours'] or 0 for e in entries]
colors_sleep = ['purple' if s >= 7 else 'orange' if s >= 6 else 'red' for s in sleep_values]
ax1.bar(dates, sleep_values, color=colors_sleep, alpha=0.7)
ax1.axhline(y=8, color='green', linestyle='--', linewidth=2, label='Recommended (8 hrs)')
ax1.axhline(y=7, color='orange', linestyle='--', linewidth=1, alpha=0.5, label='Minimum (7 hrs)')
ax1.set_xlabel('Date')
ax1.set_ylabel('Hours')
ax1.set_title('Sleep Duration', fontweight='bold')
ax1.legend()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
ax1.grid(True, alpha=0.3, axis='y')
ax1.set_ylim(0, 12)
# Water intake chart
water_values = [e['water_intake'] or 0 for e in entries]
colors_water = ['blue' if w >= 2 else 'lightblue' for w in water_values]
ax2.bar(dates, water_values, color=colors_water, alpha=0.7)
ax2.axhline(y=2, color='blue', linestyle='--', linewidth=2, label='Goal (2L)')
ax2.set_xlabel('Date')
ax2.set_ylabel('Liters')
ax2.set_title('Water Intake', fontweight='bold')
ax2.legend()
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
ax2.grid(True, alpha=0.3, axis='y')
# Add statistics
if sleep_values:
avg_sleep = np.mean([s for s in sleep_values if s > 0])
ax1.text(0.02, 0.98, f'Avg: {avg_sleep:.1f} hrs/night',
transform=ax1.transAxes, fontsize=10, verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))
if water_values:
avg_water = np.mean([w for w in water_values if w > 0])
ax2.text(0.02, 0.98, f'Avg: {avg_water:.1f} L/day',
transform=ax2.transAxes, fontsize=10, verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))
plt.tight_layout()
canvas = FigureCanvasTkAgg(fig, master=self.sleep_chart_frame)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
self.charts['sleep_water'] = fig
class StatisticsFrame(ttk.Frame):
"""Frame for displaying statistics and summary."""
def __init__(self, parent, db: FitnessDatabase):
super().__init__(parent)
self.db = db
self.create_widgets()
def create_widgets(self):
"""Create statistics widgets."""
# Title
title_label = ttk.Label(self, text="📊 Fitness Statistics", font=('Helvetica', 16, 'bold'))
title_label.pack(pady=10)
# Time range selection
control_frame = ttk.Frame(self)
control_frame.pack(fill=tk.X, padx=20, pady=5)
ttk.Label(control_frame, text="Statistics for last:").pack(side=tk.LEFT, padx=5)
self.time_range_var = tk.StringVar(value="30")
time_combo = ttk.Combobox(control_frame, textvariable=self.time_range_var,
values=["7", "14", "30", "60", "90", "180", "365"],
width=10, state='readonly')
time_combo.pack(side=tk.LEFT, padx=5)
time_combo.bind('<<ComboboxSelected>>', lambda e: self.refresh_stats())
ttk.Label(control_frame, text="days").pack(side=tk.LEFT)
# Statistics display frame
self.stats_frame = ttk.Frame(self)
self.stats_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
self.refresh_stats()
def refresh_stats(self):
"""Refresh statistics display."""
# Clear existing widgets
for widget in self.stats_frame.winfo_children():
widget.destroy()
days = int(self.time_range_var.get())
stats = self.db.get_statistics(days)
if not stats or stats.get('total_entries', 0) == 0:
ttk.Label(self.stats_frame, text="No data available for the selected period",
font=('Helvetica', 14)).pack(expand=True)
return
# Summary cards frame
cards_frame = ttk.Frame(self.stats_frame)
cards_frame.pack(fill=tk.X, pady=10)
# Create stat cards
card_data = []
if 'weight' in stats:
w = stats['weight']
card_data.append(("⚖️ Weight", f"Current: {w['current']:.1f} kg",
f"Change: {w['change']:+.1f} kg",
"green" if w['change'] <= 0 else "red"))
if 'calories_consumed' in stats:
c = stats['calories_consumed']
card_data.append(("🍽️ Calories In", f"Avg: {c['avg']:.0f}/day",
f"Total: {c['total']:,}", "coral"))
if 'calories_burned' in stats:
c = stats['calories_burned']
card_data.append(("🔥 Calories Out", f"Avg: {c['avg']:.0f}/day",
f"Total: {c['total']:,}", "green"))
if 'exercise' in stats:
e = stats['exercise']
card_data.append(("🏃 Exercise", f"{e['sessions']} sessions",
f"Total: {e['total_hours']:.1f} hrs", "blue"))
if 'sleep' in stats:
s = stats['sleep']
quality = "Good" if s['avg'] >= 7 else "Needs Improvement"
card_data.append(("😴 Sleep", f"Avg: {s['avg']:.1f} hrs/night",
f"Quality: {quality}", "purple"))
if 'water' in stats:
w = stats['water']
card_data.append(("💧 Water", f"Avg: {w['avg']:.1f} L/day",
f"Total: {w['total']:.1f} L", "lightblue"))
if 'steps' in stats:
s = stats['steps']
card_data.append(("👣 Steps", f"Avg: {s['avg']:,.0f}/day",
f"Total: {s['total']:,}", "orange"))
# Display cards in a grid
for i, (title, line1, line2, color) in enumerate(card_data):
row = i // 3
col = i % 3
card = ttk.LabelFrame(cards_frame, text=title, padding=10)
card.grid(row=row, column=col, padx=10, pady=10, sticky='nsew')
ttk.Label(card, text=line1, font=('Helvetica', 11)).pack(anchor='w')
ttk.Label(card, text=line2, font=('Helvetica', 10)).pack(anchor='w')
# Configure grid weights
for i in range(3):
cards_frame.columnconfigure(i, weight=1)
# Detailed statistics table
table_frame = ttk.LabelFrame(self.stats_frame, text="Detailed Statistics", padding=10)
table_frame.pack(fill=tk.BOTH, expand=True, pady=10)
# Create treeview for detailed stats
columns = ("Metric", "Value", "Average", "Min", "Max")
tree = ttk.Treeview(table_frame, columns=columns, show='headings', height=8)
for col in columns:
tree.heading(col, text=col)
tree.column(col, width=100, anchor='center')
# Add data rows
if 'weight' in stats:
w = stats['weight']
tree.insert('', 'end', values=("Weight (kg)", f"{w['current']:.1f}",
f"{w['avg']:.1f}", f"{w['min']:.1f}", f"{w['max']:.1f}"))
if 'calories_consumed' in stats:
c = stats['calories_consumed']
tree.insert('', 'end', values=("Calories In", f"{c['total']:,}",
f"{c['avg']:.0f}", f"{c['min']:,}", f"{c['max']:,}"))
if 'calories_burned' in stats:
c = stats['calories_burned']
tree.insert('', 'end', values=("Calories Out", f"{c['total']:,}",
f"{c['avg']:.0f}", f"{c['min']:,}", f"{c['max']:,}"))
if 'exercise' in stats:
e = stats['exercise']
tree.insert('', 'end', values=("Exercise (min)", f"{e['total_minutes']}",
f"{e['avg_per_session']:.0f}", "-", "-"))
if 'sleep' in stats:
s = stats['sleep']
tree.insert('', 'end', values=("Sleep (hrs)", f"{s['total']:.1f}",
f"{s['avg']:.1f}", f"{s['min']:.1f}", f"{s['max']:.1f}"))
if 'water' in stats:
w = stats['water']
tree.insert('', 'end', values=("Water (L)", f"{w['total']:.1f}",
f"{w['avg']:.1f}", f"{w['min']:.1f}", f"{w['max']:.1f}"))
if 'steps' in stats:
s = stats['steps']
tree.insert('', 'end', values=("Steps", f"{s['total']:,}",
f"{s['avg']:,.0f}", f"{s['min']:,}", f"{s['max']:,}"))
tree.pack(fill=tk.BOTH, expand=True)
# Entries count
ttk.Label(self.stats_frame,
text=f"📊 Total entries in period: {stats['total_entries']} | Date range: {stats['date_range']}",
font=('Helvetica', 10, 'italic')).pack(pady=5)
class HistoryFrame(ttk.Frame):
"""Frame for viewing and managing fitness history."""
def __init__(self, parent, db: FitnessDatabase, main_app):
super().__init__(parent)
self.db = db
self.main_app = main_app
self.create_widgets()
def create_widgets(self):
"""Create history widgets."""
# Title
title_label = ttk.Label(self, text="📅 Fitness History", font=('Helvetica', 16, 'bold'))
title_label.pack(pady=10)
# Filter frame
filter_frame = ttk.Frame(self)
filter_frame.pack(fill=tk.X, padx=20, pady=5)
ttk.Label(filter_frame, text="Show entries from:").pack(side=tk.LEFT, padx=5)
self.days_var = tk.StringVar(value="30")
days_combo = ttk.Combobox(filter_frame, textvariable=self.days_var,
values=["7", "14", "30", "60", "90", "365", "All"],
width=10, state='readonly')
days_combo.pack(side=tk.LEFT, padx=5)
days_combo.bind('<<ComboboxSelected>>', lambda e: self.refresh_history())
ttk.Label(filter_frame, text="days").pack(side=tk.LEFT)
ttk.Button(filter_frame, text="Export CSV", command=self.export_csv).pack(side=tk.RIGHT, padx=5)
ttk.Button(filter_frame, text="Import CSV", command=self.import_csv).pack(side=tk.RIGHT, padx=5)
# Treeview for history
tree_frame = ttk.Frame(self)
tree_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
columns = ("date", "weight", "cal_in", "cal_out", "water", "sleep", "exercise", "duration", "steps")
self.tree = ttk.Treeview(tree_frame, columns=columns, show='headings', height=20)
# Configure columns
column_config = {
"date": ("Date", 100),
"weight": ("Weight (kg)", 90),
"cal_in": ("Cal In", 70),
"cal_out": ("Cal Out", 70),
"water": ("Water (L)", 70),
"sleep": ("Sleep (h)", 70),
"exercise": ("Exercise", 100),
"duration": ("Duration", 70),
"steps": ("Steps", 80)
}
for col, (heading, width) in column_config.items():
self.tree.heading(col, text=heading)
self.tree.column(col, width=width, anchor='center')
# Scrollbars
vsb = ttk.Scrollbar(tree_frame, orient="vertical", command=self.tree.yview)
hsb = ttk.Scrollbar(tree_frame, orient="horizontal", command=self.tree.xview)
self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
self.tree.grid(row=0, column=0, sticky='nsew')
vsb.grid(row=0, column=1, sticky='ns')
hsb.grid(row=1, column=0, sticky='ew')
tree_frame.grid_rowconfigure(0, weight=1)
tree_frame.grid_columnconfigure(0, weight=1)
# Bind double-click to edit
self.tree.bind('<Double-1>', self.on_double_click)
# Button frame
btn_frame = ttk.Frame(self)
btn_frame.pack(fill=tk.X, padx=20, pady=10)
ttk.Button(btn_frame, text="View/Edit Entry", command=self.edit_selected).pack(side=tk.LEFT, padx=5)
ttk.Button(btn_frame, text="Delete Entry", command=self.delete_selected).pack(side=tk.LEFT, padx=5)
ttk.Button(btn_frame, text="Refresh", command=self.refresh_history).pack(side=tk.LEFT, padx=5)
self.refresh_history()
def refresh_history(self):
"""Refresh the history treeview."""
# Clear existing items
for item in self.tree.get_children():
self.tree.delete(item)
# Get entries
days = self.days_var.get()
if days == "All":
entries = self.db.get_all_entries()
else:
end_date = datetime.now().strftime('%Y-%m-%d')
start_date = (datetime.now() - timedelta(days=int(days))).strftime('%Y-%m-%d')
entries = self.db.get_entries_range(start_date, end_date)
# Add entries to tree
for entry in reversed(entries):
values = (
entry['date'],
f"{entry['weight']:.1f}" if entry['weight'] else "-",
entry['calories_consumed'] or "-",
entry['calories_burned'] or "-",
f"{entry['water_intake']:.1f}" if entry['water_intake'] else "-",
f"{entry['sleep_hours']:.1f}" if entry['sleep_hours'] else "-",
entry['exercise_type'] or "-",
f"{entry['exercise_duration']}m" if entry['exercise_duration'] else "-",
f"{entry['steps']:,}" if entry['steps'] else "-"
)
self.tree.insert('', 'end', values=values)
def on_double_click(self, event):
"""Handle double-click on tree item."""
self.edit_selected()
def edit_selected(self):
"""Edit the selected entry."""
selected = self.tree.selection()
if not selected:
messagebox.showwarning("No Selection", "Please select an entry to edit")
return
item = self.tree.item(selected[0])
date = item['values'][0]
entry_data = self.db.get_entry(date)
if entry_data:
dialog = DataEntryDialog(self.main_app.root, self.db, date, entry_data)
self.wait_window(dialog)
if dialog.result:
self.refresh_history()
def delete_selected(self):
"""Delete the selected entry."""
selected = self.tree.selection()
if not selected:
messagebox.showwarning("No Selection", "Please select an entry to delete")
return
item = self.tree.item(selected[0])
date = item['values'][0]
if messagebox.askyesno("Confirm Delete", f"Delete entry for {date}?"):
if self.db.delete_entry(date):
self.refresh_history()
messagebox.showinfo("Success", "Entry deleted successfully")
else:
messagebox.showerror("Error", "Failed to delete entry")
def export_csv(self):
"""Export data to CSV file."""
filepath = filedialog.asksaveasfilename(
defaultextension=".csv",
filetypes=[("CSV files", "*.csv"), ("All files", "*.*")],
title="Export Fitness Data"
)
if filepath:
if self.db.export_to_csv(filepath):
messagebox.showinfo("Export Successful", f"Data exported to {filepath}")
else:
messagebox.showerror("Export Failed", "Failed to export data")
def import_csv(self):
"""Import data from CSV file."""
filepath = filedialog.askopenfilename(
filetypes=[("CSV files", "*.csv"), ("All files", "*.*")],
title="Import Fitness Data"
)
if filepath:
success, count = self.db.import_from_csv(filepath)
if success:
self.refresh_history()
messagebox.showinfo("Import Successful", f"Imported {count} entries")
else:
messagebox.showerror("Import Failed", "Failed to import data")
class GoalsFrame(ttk.Frame):
"""Frame for managing fitness goals."""
def __init__(self, parent, db: FitnessDatabase):
super().__init__(parent)
self.db = db
self.create_widgets()
def create_widgets(self):
"""Create goals widgets."""
# Title
title_label = ttk.Label(self, text="🎯 Fitness Goals", font=('Helvetica', 16, 'bold'))
title_label.pack(pady=10)
# Add goal frame
add_frame = ttk.LabelFrame(self, text="Add New Goal", padding=10)
add_frame.pack(fill=tk.X, padx=20, pady=10)
# Metric selection
metric_frame = ttk.Frame(add_frame)
metric_frame.pack(fill=tk.X, pady=5)
ttk.Label(metric_frame, text="Goal Type:").pack(side=tk.LEFT, padx=5)
self.metric_var = tk.StringVar(value="Weight")
metrics = ["Weight", "Daily Steps", "Daily Calories", "Weekly Exercise", "Daily Water", "Daily Sleep"]
metric_combo = ttk.Combobox(metric_frame, textvariable=self.metric_var, values=metrics, width=20, state='readonly')
metric_combo.pack(side=tk.LEFT, padx=5)
# Target value
ttk.Label(metric_frame, text="Target:").pack(side=tk.LEFT, padx=(20, 5))
self.target_var = tk.StringVar()
ttk.Entry(metric_frame, textvariable=self.target_var, width=10).pack(side=tk.LEFT, padx=5)
self.target_unit_label = ttk.Label(metric_frame, text="kg")
self.target_unit_label.pack(side=tk.LEFT, padx=5)
# Update unit label when metric changes
metric_combo.bind('<<ComboboxSelected>>', self.update_unit_label)
# Add button
ttk.Button(add_frame, text="Add Goal", command=self.add_goal).pack(pady=10)
# Active goals frame
goals_frame = ttk.LabelFrame(self, text="Active Goals", padding=10)
goals_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
# Goals listbox with scrollbar
list_frame = ttk.Frame(goals_frame)
list_frame.pack(fill=tk.BOTH, expand=True)
self.goals_listbox = tk.Listbox(list_frame, font=('Helvetica', 11), height=10)
scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.goals_listbox.yview)
self.goals_listbox.configure(yscrollcommand=scrollbar.set)
self.goals_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Delete button
ttk.Button(goals_frame, text="Delete Selected Goal", command=self.delete_goal).pack(pady=10)
self.refresh_goals()
def update_unit_label(self, event=None):
"""Update the unit label based on selected metric."""
units = {
"Weight": "kg",
"Daily Steps": "steps",
"Daily Calories": "calories",
"Weekly Exercise": "hours",
"Daily Water": "liters",
"Daily Sleep": "hours"
}
self.target_unit_label.configure(text=units.get(self.metric_var.get(), ""))
def add_goal(self):
"""Add a new goal."""
try:
target = float(self.target_var.get())
metric = self.metric_var.get()
if self.db.add_goal(metric, target):
self.refresh_goals()
self.target_var.set("")
messagebox.showinfo("Success", f"Goal added: {metric} = {target}")
else:
messagebox.showerror("Error", "Failed to add goal")
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid number for target")
def delete_goal(self):
"""Delete the selected goal."""
selection = self.goals_listbox.curselection()
if not selection:
messagebox.showwarning("No Selection", "Please select a goal to delete")
return
if messagebox.askyesno("Confirm Delete", "Delete the selected goal?"):
# Get goal ID from selection
goal_text = self.goals_listbox.get(selection[0])
# This is a simplified version - in production, you'd store goal IDs
messagebox.showinfo("Info", "Goal deletion would be implemented with goal ID tracking")
def refresh_goals(self):
"""Refresh the goals list."""
self.goals_listbox.delete(0, tk.END)
goals = self.db.get_active_goals()
stats = self.db.get_statistics(30)
for goal in goals:
metric = goal['metric']
target = goal['target_value']
# Calculate progress
current = "N/A"
progress = 0
if metric == "Weight" and 'weight' in stats:
current = f"{stats['weight']['current']:.1f}"
progress = (target / stats['weight']['current']) * 100 if stats['weight']['current'] else 0
status = "✅" if progress >= 100 else "🔄"
self.goals_listbox.insert(tk.END, f"{status} {metric}: Target {target} (Current: {current})")
class FitnessTrackerApp:
"""Main application class."""
def __init__(self):
self.root = tk.Tk()
self.root.title("🏃 Personal Fitness Tracker")
self.root.geometry("1200x800")
self.root.minsize(900, 600)
# Set app icon (using emoji as fallback)
try:
self.root.iconbitmap('') # Add icon path if available
except:
pass
# Initialize database
self.db = FitnessDatabase()
# Configure styles
self.configure_styles()
# Create main layout
self.create_layout()
# Handle window close
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
def configure_styles(self):
"""Configure ttk styles."""
style = ttk.Style()
# Try to use a modern theme
available_themes = style.theme_names()
if 'clam' in available_themes:
style.theme_use('clam')
elif 'vista' in available_themes:
style.theme_use('vista')
# Configure colors
style.configure('TFrame', background='#f5f5f5')
style.configure('TLabel', background='#f5f5f5', font=('Helvetica', 10))
style.configure('TLabelframe', background='#f5f5f5')
style.configure('TLabelframe.Label', background='#f5f5f5', font=('Helvetica', 11, 'bold'))
style.configure('TButton', font=('Helvetica', 10), padding=5)
style.configure('Accent.TButton', font=('Helvetica', 11, 'bold'))
style.configure('Header.TLabel', font=('Helvetica', 14, 'bold'))
def create_layout(self):
"""Create the main application layout."""
# Main container
main_container = ttk.Frame(self.root)
main_container.pack(fill=tk.BOTH, expand=True)
# Sidebar
sidebar = ttk.Frame(main_container, width=200)
sidebar.pack(side=tk.LEFT, fill=tk.Y, padx=0, pady=0)
sidebar.pack_propagate(False)
# App title in sidebar
title_frame = ttk.Frame(sidebar)
title_frame.pack(fill=tk.X, padx=10, pady=20)
ttk.Label(title_frame, text="🏃 Fitness", font=('Helvetica', 18, 'bold')).pack()
ttk.Label(title_frame, text="Tracker", font=('Helvetica', 18, 'bold')).pack()
ttk.Separator(sidebar, orient='horizontal').pack(fill=tk.X, padx=10, pady=10)
# Navigation buttons
nav_frame = ttk.Frame(sidebar)
nav_frame.pack(fill=tk.X, padx=5)
self.nav_buttons = {}
nav_items = [
("📊 Dashboard", "dashboard"),
("➕ Add Entry", "add_entry"),
("📈 Charts", "charts"),
("📋 Statistics", "statistics"),
("📅 History", "history"),
("🎯 Goals", "goals")
]
for text, key in nav_items:
btn = ttk.Button(nav_frame, text=text, width=18,
command=lambda k=key: self.show_frame(k))
btn.pack(pady=5, padx=5)
self.nav_buttons[key] = btn
# Quick stats in sidebar
ttk.Separator(sidebar, orient='horizontal').pack(fill=tk.X, padx=10, pady=20)
quick_stats_frame = ttk.LabelFrame(sidebar, text="Quick Stats", padding=5)
quick_stats_frame.pack(fill=tk.X, padx=10, pady=5)
self.quick_stats_label = ttk.Label(quick_stats_frame, text="", wraplength=180)
self.quick_stats_label.pack()
self.update_quick_stats()
# Content area
self.content_frame = ttk.Frame(main_container)
self.content_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=10, pady=10)
# Create all frames
self.frames = {}
# Dashboard frame
self.frames['dashboard'] = self.create_dashboard()
# Charts frame
self.frames['charts'] = ChartsFrame(self.content_frame, self.db)
# Statistics frame
self.frames['statistics'] = StatisticsFrame(self.content_frame, self.db)
# History frame
self.frames['history'] = HistoryFrame(self.content_frame, self.db, self)
# Goals frame
self.frames['goals'] = GoalsFrame(self.content_frame, self.db)
# Show dashboard by default
self.show_frame('dashboard')
def create_dashboard(self):
"""Create the dashboard frame."""
dashboard = ttk.Frame(self.content_frame)
# Welcome section
welcome_frame = ttk.Frame(dashboard)
welcome_frame.pack(fill=tk.X, pady=10)
today = datetime.now().strftime('%A, %B %d, %Y')
ttk.Label(welcome_frame, text=f"Welcome back! 👋",
font=('Helvetica', 18, 'bold')).pack(anchor='w')
ttk.Label(welcome_frame, text=today,
font=('Helvetica', 12)).pack(anchor='w')
# Quick action buttons
action_frame = ttk.Frame(dashboard)
action_frame.pack(fill=tk.X, pady=20)
ttk.Button(action_frame, text="➕ Log Today's Data",
command=self.show_add_entry).pack(side=tk.LEFT, padx=5)
ttk.Button(action_frame, text="📊 View Progress",
command=lambda: self.show_frame('charts')).pack(side=tk.LEFT, padx=5)
# Today's summary
summary_frame = ttk.LabelFrame(dashboard, text="Today's Summary", padding=15)
summary_frame.pack(fill=tk.X, pady=10)
today_date = datetime.now().strftime('%Y-%m-%d')
today_data = self.db.get_entry(today_date)
if today_data:
# Create a grid of metrics
metrics = [
("⚖️ Weight", f"{today_data['weight']:.1f} kg" if today_data['weight'] else "Not logged"),
("🍽️ Calories", f"{today_data['calories_consumed']} in / {today_data['calories_burned']} out"
if today_data['calories_consumed'] or today_data['calories_burned'] else "Not logged"),
("💧 Water", f"{today_data['water_intake']:.1f} L" if today_data['water_intake'] else "Not logged"),
("😴 Sleep", f"{today_data['sleep_hours']:.1f} hrs" if today_data['sleep_hours'] else "Not logged"),
("🏃 Exercise", f"{today_data['exercise_type']} ({today_data['exercise_duration']} min)"
if today_data['exercise_type'] else "Not logged"),
("👣 Steps", f"{today_data['steps']:,}" if today_data['steps'] else "Not logged")
]
for i, (label, value) in enumerate(metrics):
row = i // 3
col = i % 3
metric_frame = ttk.Frame(summary_frame)
metric_frame.grid(row=row, column=col, padx=20, pady=10, sticky='w')
ttk.Label(metric_frame, text=label, font=('Helvetica', 11, 'bold')).pack(anchor='w')
ttk.Label(metric_frame, text=value, font=('Helvetica', 11)).pack(anchor='w')
else:
ttk.Label(summary_frame, text="No data logged for today. Click 'Log Today's Data' to get started!",
font=('Helvetica', 12)).pack(pady=20)
# Weekly summary
weekly_frame = ttk.LabelFrame(dashboard, text="This Week's Progress", padding=15)
weekly_frame.pack(fill=tk.BOTH, expand=True, pady=10)
stats = self.db.get_statistics(7)
if stats and stats.get('total_entries', 0) > 0:
# Create a simple weekly summary
summary_text = f"📊 {stats['total_entries']} entries this week\n\n"
if 'weight' in stats:
summary_text += f"⚖️ Weight: {stats['weight']['current']:.1f} kg "
summary_text += f"({'↓' if stats['weight']['change'] < 0 else '↑'} {abs(stats['weight']['change']):.1f} kg)\n"
if 'exercise' in stats:
summary_text += f"🏃 Exercise: {stats['exercise']['total_hours']:.1f} hours across {stats['exercise']['sessions']} sessions\n"
if 'calories_consumed' in stats:
summary_text += f"🍽️ Avg Calories: {stats['calories_consumed']['avg']:.0f}/day\n"
if 'sleep' in stats:
summary_text += f"😴 Avg Sleep: {stats['sleep']['avg']:.1f} hrs/night\n"
if 'steps' in stats:
summary_text += f"👣 Total Steps: {stats['steps']['total']:,}\n"
ttk.Label(weekly_frame, text=summary_text, font=('Helvetica', 11),
justify='left').pack(anchor='w')
else:
ttk.Label(weekly_frame, text="Start logging your data to see weekly progress!",
font=('Helvetica', 12)).pack(pady=20)
return dashboard
def show_frame(self, frame_name):
"""Show the specified frame."""
# Hide all frames
for frame in self.frames.values():
frame.pack_forget()
# Show the selected frame
self.frames[frame_name].pack(fill=tk.BOTH, expand=True)
# Update button states
for key, btn in self.nav_buttons.items():
if key == frame_name:
btn.state(['pressed'])
else:
btn.state(['!pressed'])
# Refresh dynamic frames
if frame_name == 'dashboard':
self.refresh_dashboard()
elif frame_name == 'charts':
self.frames['charts'].refresh_charts()
elif frame_name == 'statistics':
self.frames['statistics'].refresh_stats()
elif frame_name == 'history':
self.frames['history'].refresh_history()
elif frame_name == 'goals':
self.frames['goals'].refresh_goals()
def refresh_dashboard(self):
"""Refresh the dashboard."""
# Recreate dashboard
self.frames['dashboard'].destroy()
self.frames['dashboard'] = self.create_dashboard()
def show_add_entry(self):
"""Show the add entry dialog."""
dialog = DataEntryDialog(self.root, self.db)
self.root.wait_window(dialog)
if dialog.result:
self.refresh_dashboard()
self.update_quick_stats()
def update_quick_stats(self):
"""Update quick stats in sidebar."""
stats = self.db.get_statistics(7)
if stats and stats.get('total_entries', 0) > 0:
text = f"📝 {stats['total_entries']} entries\n"
if 'weight' in stats:
text += f"⚖️ {stats['weight']['current']:.1f} kg\n"
if 'exercise' in stats:
text += f"🏃 {stats['exercise']['sessions']} workouts\n"
if 'sleep' in stats:
text += f"😴 {stats['sleep']['avg']:.1f}h avg sleep"
else:
text = "Start logging\nyour fitness\ndata!"
self.quick_stats_label.configure(text=text)
def on_closing(self):
"""Handle application closing."""
# Clean up matplotlib figures
plt.close('all')
self.root.destroy()
def run(self):
"""Run the application."""
self.root.mainloop()
def main():
"""Main entry point."""
print("=" * 50)
print("🏃 Personal Fitness Tracker")
print("=" * 50)
print("\nStarting application...")
print("- Track weight, calories, exercise, sleep & more")
print("- Visualize your progress with charts")
print("- Export/import data as CSV")
print("\nClose the window to exit.\n")
app = FitnessTrackerApp()
app.run()
if __name__ == "__main__":
main()