-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
278 lines (222 loc) · 10.2 KB
/
Copy pathmain.py
File metadata and controls
278 lines (222 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import streamlit as st
import os
import time
import pandas as pd
from dotenv import load_dotenv
load_dotenv()
from services.auth.login_wall import render_login_wall
from services.state.session_defaults import initial_session_defaults
from services.config.workout_config import EXERCISE_OPTIONS
from services.ui.style_loader import load_css, inject_local_font, inject_webrtc_styles
from services.persistence.exercise_repository import init_db
from streamlit_webrtc import webrtc_streamer, WebRtcMode
from services.vision.exercise_video_processor import VideoProcessorClass
from services.tracking.metrics import sync_metrics_update
from services.persistence.exercise_repository import get_users_exercises
from groq import Groq
from services.coaching.llm import LLMCoach
from services.coaching.tts import TextToSpeech
from services.coaching.voice_pipeline import VoicePipeline, autoplay_audio
def main():
st.set_page_config(
page_icon="🏋️",
page_title="FormCheck AI",
initial_sidebar_state="expanded",
layout="centered"
)
load_css(os.path.join(os.getcwd(), "static", "style.css"))
inject_local_font(os.path.join(os.getcwd(), "static", "AdobeClean.otf"), "AdobeClean")
init_db()
if not render_login_wall():
return
initial_session_defaults()
if "voice_pipeline" not in st.session_state:
try:
api_key = os.environ.get("GROQ_API_KEY", "")
if not api_key and hasattr(st, "secrets") and "GROQ_API_KEY" in st.secrets:
api_key = st.secrets["GROQ_API_KEY"]
groq_client = Groq(api_key=api_key)
llm_coach = LLMCoach(groq_client)
tts = TextToSpeech()
st.session_state.voice_pipeline = VoicePipeline(llm_coach, tts)
except Exception as e:
st.session_state.voice_pipeline = None
workout_started = st.session_state.get("workout_started", False)
with st.sidebar:
st.title("🏋️ FormCheck AI")
if st.session_state.username:
st.caption(f"⚡ {st.session_state.username}")
st.divider()
st.subheader("Workout Plan")
if not workout_started:
plan_exercise = st.selectbox("Exercise", options=EXERCISE_OPTIONS, key="plan_exercise")
plan_sets = st.number_input("Sets", min_value=0, max_value=50, key="plan_sets", step=1)
plan_reps = st.number_input("Reps per Set", min_value=0, max_value=50, key="plan_reps", step=1)
st.markdown("")
start_session_button = st.button("Start Workout", use_container_width=True, key="start_session_button")
if start_session_button:
st.session_state.exercise_type = plan_exercise
st.session_state.target_sets = int(plan_sets)
st.session_state.reps_per_set = int(plan_reps)
st.session_state.reps = 0
st.session_state.workout_started = True
st.session_state.set_cycle_started_at = time.time()
st.session_state.last_saved_sets_completed = 0
if st.session_state.voice_pipeline:
result = st.session_state.voice_pipeline.process_event(
event="workout_started",
exercise=plan_exercise,
metrics={}
)
if result:
st.session_state.audio_to_play, st.session_state.coach_feedback = result
st.session_state.last_notified_sets_completed = 0
st.session_state.last_notified_workout_complete = False
st.rerun()
else:
exercise = st.session_state.get("exercise_type")
sets = st.session_state.get("target_sets")
reps = st.session_state.get("reps_per_set")
st.info(f"**{exercise}** — {sets} Sets / {reps} Reps")
end_session_button = st.button("End Workout", key="end_session_button", use_container_width=True)
if end_session_button:
st.session_state.workout_started = False
if st.session_state.voice_pipeline:
result = st.session_state.voice_pipeline.process_event(
event="workout_completed",
exercise=exercise,
metrics={}
)
if result:
st.session_state.audio_to_play, st.session_state.coach_feedback = result
st.rerun()
if workout_started:
st.divider()
exercise = st.session_state.get("exercise_type")
total_reps = st.session_state.get("reps")
current_set_reps = st.session_state.get("current_set_reps")
reps_per_set = st.session_state.get("reps_per_set")
sets_completed = st.session_state.get("sets_completed")
target_sets = st.session_state.get("target_sets")
st.subheader("Progress")
st.metric("Total Reps", f"{total_reps}")
st.metric("Current Set Reps", f"{current_set_reps} / {reps_per_set}")
st.metric("Sets Completed", f"{sets_completed} / {target_sets}")
st.divider()
if exercise == "Squats":
st.subheader("Squat Metrics")
st.metric("Knee Angle", f"{st.session_state.knee_angle}°")
st.metric("Back Angle", f"{st.session_state.back_angle}°")
st.metric("Depth Status", st.session_state.depth_status)
elif exercise == "Push-ups":
st.subheader("Push-up Metrics")
st.metric("Elbow Angle", f"{st.session_state.elbow_angle}°")
st.metric("Body Alignment", st.session_state.body_alignment)
st.metric("Hip Position", st.session_state.hip_status)
elif exercise == "Biceps Curls (Dumbbell)":
st.subheader("Curl Metrics")
st.metric("Elbow Angle", f"{st.session_state.elbow_angle}°")
st.metric("Shoulder Stability", st.session_state.shoulder_status)
st.metric("Swing Detection", st.session_state.swing_status)
elif exercise == "Shoulder Press":
st.subheader("Shoulder Press Metrics")
st.metric("Elbow Angle", f"{st.session_state.elbow_angle}°")
st.metric("Arm Extension", st.session_state.extension_status)
st.metric("Back Arch", st.session_state.back_arch_status)
elif exercise == "Lunges":
st.subheader("Lunge Metrics")
st.metric("Front Knee Angle", f"{st.session_state.front_knee_angle}°")
st.metric("Torso Angle", f"{st.session_state.torso_angle}°")
st.metric("Balance Status", st.session_state.balance_status)
st.divider()
if st.button("Logout", use_container_width=True, key="logout_button"):
for key in list(st.session_state.keys()):
del st.session_state[key]
st.rerun()
st.title("FormCheck AI")
st.markdown("#### Real-time pose detection with AI voice coaching")
if st.session_state.get("audio_to_play"):
autoplay_audio(st.session_state.audio_to_play)
if st.session_state.get("coach_feedback"):
st.markdown("")
st.success(f"🤖 **Coach:** {st.session_state.coach_feedback}")
if not workout_started:
st.markdown(
"""
<div style="
border: 1px solid rgba(255, 184, 0, 0.2);
border-top: 3px solid #FFB800;
background: rgba(255, 184, 0, 0.03);
padding: 52px 32px;
text-align: center;
margin-top: 32px;
margin-bottom: 32px;
">
<h2 style="
color: #FFB800;
margin-bottom: 12px;
font-family: 'AdobeClean', 'Outfit', sans-serif;
font-weight: 700;
font-size: 1.4rem;
letter-spacing: -0.01em;
">Set your workout plan</h2>
<p style="
font-size: 0.95rem;
font-family: 'AdobeClean', 'Outfit', sans-serif;
color: #6B7A94;
line-height: 1.6;
margin: 0;
">
Choose your exercise, sets and reps in the sidebar,<br>
then click <strong style="color:#fff; font-weight:600;">Start Workout</strong> to activate the camera and AI coach.
</p>
</div>
""",
unsafe_allow_html=True,
)
else:
context = webrtc_streamer(
key="exercise-analysis",
mode=WebRtcMode.SENDRECV,
video_processor_factory=VideoProcessorClass,
rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]},
media_stream_constraints={
"video": True,
"audio": False
},
async_processing=True
)
sync_metrics_update(context)
if context.state.playing:
time.sleep(0.25)
st.rerun()
inject_webrtc_styles()
st.divider()
st.markdown("#### Workout History")
user_id = st.session_state.get("user_id", 0)
if isinstance(user_id, int):
history_rows = get_users_exercises(user_id)
arr = [
{
"Exercise": row['exercise_name'],
"Reps": row['reps'],
"Sets": row['sets'],
"Time (sec)": row['time'],
"Date": row['created_at']
}
for row in history_rows
]
df = pd.DataFrame(arr)
if not df.empty:
df["Date"] = pd.to_datetime(df["Date"]).dt.date
agg_df = df.groupby(["Exercise", "Date"]).agg({
"Reps": 'sum',
"Sets": "sum",
"Time (sec)": "sum"
}).reset_index()
agg_df.index += 1
st.table(agg_df)
else:
st.info("No workout history yet. Complete a set to see it here.")
if __name__ == "__main__":
main()