Spaces:
Sleeping
Sleeping
File size: 13,058 Bytes
4a8d980 92605fa 4a8d980 919b5d0 4a8d980 919b5d0 4a8d980 b516e57 4a8d980 b516e57 4a8d980 919b5d0 b516e57 4a8d980 919b5d0 4a8d980 b516e57 4a8d980 919b5d0 4a8d980 919b5d0 e6d9ec1 4a8d980 b516e57 4a8d980 e6d9ec1 4a8d980 e6d9ec1 4a8d980 92605fa e6d9ec1 92605fa d8610aa 92605fa d8610aa 92605fa d8610aa 92605fa d8610aa 92605fa d8610aa 92605fa d8610aa 92605fa d8610aa 92605fa d8610aa | 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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 | """
inference.py β predict, decode, and prompt building utilities
"""
import torch
from typing import Dict, List, Optional
# βββββββββββββββββββββββββββββββββββββββββββββ
# POST-WORKOUT FUNCTIONS
# βββββββββββββββββββββββββββββββββββββββββββββ
def predict_post(
text: str,
model,
tokenizer,
device: torch.device,
max_len: int = 128,
) -> Dict[str, int]:
"""
Run PostWorkoutDistilBERT inference on a single text string.
Returns raw integer predictions for each head.
"""
encoding = tokenizer(
text,
max_length=max_len,
padding="max_length",
truncation=True,
return_tensors="pt",
)
input_ids = encoding["input_ids"].to(device)
attention_mask = encoding["attention_mask"].to(device)
with torch.no_grad():
mood_logits, exertion_logits, soreness_region_logits, soreness_severity_logits, completion_logits = model(
input_ids, attention_mask
)
return {
"mood": mood_logits.argmax(dim=1).item(),
"exertion": exertion_logits.argmax(dim=1).item(),
"soreness_region": soreness_region_logits.argmax(dim=1).item(),
"soreness_severity": soreness_severity_logits.argmax(dim=1).item(),
"completion": completion_logits.argmax(dim=1).item(),
}
def decode_post_predictions(
preds: Dict[str, int],
mood_map: Dict[int, str],
exertion_map: Dict[int, str],
soreness_region_map: Dict[int, str],
soreness_severity_map:Dict[int, str],
completion_map: Dict[int, str],
) -> Dict[str, str]:
"""
Decode post-workout integer predictions back to human-readable label strings.
"""
return {
"mood": mood_map[preds["mood"]],
"exertion": exertion_map[preds["exertion"]],
"soreness_region": soreness_region_map[preds["soreness_region"]],
"soreness_severity": soreness_severity_map[preds["soreness_severity"]],
"completion": completion_map[preds["completion"]],
}
def build_post_prompt(
bert_labels: Dict[str, str],
user_text: str,
duration_minutes: int,
workout_type: str,
user_goal: str,
) -> str:
"""
Build the Claude prompt for post-workout debrief generation.
Plain text output only β no Markdown, no asterisks, no symbols.
Section delimiters are ALL-CAPS labels so parse_debrief() can
split the response into named sections reliably.
"""
region = bert_labels["soreness_region"]
severity = bert_labels["soreness_severity"]
if region == "none" or severity == "none":
soreness_str = "no soreness"
else:
soreness_str = f"{severity} {region} soreness"
completion_str = (
"completed the full session"
if bert_labels["completion"] == "full"
else "partially completed the session"
)
prompt = f"""You are an encouraging personal fitness coach writing a post-workout debrief for a user.
Use plain text only β no Markdown, no asterisks, no bold, no bullet points, no special symbols.
Session summary:
- Workout type: {workout_type}
- Duration: {duration_minutes} minutes
- User goal: {user_goal}
- Completion: {completion_str}
- Exertion level: {bert_labels['exertion']}
- Post-workout mood: {bert_labels['mood']}
- Soreness: {soreness_str}
What the user wrote after their session:
"{user_text}"
Write a personalized debrief using the exact section labels below as delimiters. \
Do not add any text before ACKNOWLEDGEMENT or after NEXT SESSION. \
Write one short paragraph per section β warm, concise, and actionable.
ACKNOWLEDGEMENT
[Acknowledge how they felt and what they did β validate their effort regardless of how the session went]
HIGHLIGHTS
[Highlight what went well and give honest context for any soreness or struggles]
NEXT SESSION
[Set them up positively for their next session with one specific actionable tip]"""
return prompt
# ββ Section keys returned by parse_debrief() βββββββββββββββββ
DEBRIEF_SECTIONS = ["ACKNOWLEDGEMENT", "HIGHLIGHTS", "NEXT SESSION"]
def parse_debrief(raw: str) -> Dict[str, str]:
"""
Split a plain-text post-workout debrief into named sections.
Returns a dict with keys:
"acknowledgement" β how they felt / what they did paragraph
"highlights" β what went well / soreness context paragraph
"next_session" β forward-looking actionable tip paragraph
"raw" β original unmodified response (fallback)
If a section is missing the key maps to "".
"""
result = {
"acknowledgement": "",
"highlights": "",
"next_session": "",
"raw": raw,
}
text = raw.replace("\r\n", "\n").strip()
# Build a map of {section_label: start_index} for every label found
indices: Dict[str, int] = {}
for label in DEBRIEF_SECTIONS:
idx = text.find(label)
if idx != -1:
indices[label] = idx
ordered = sorted(indices.items(), key=lambda x: x[1])
for i, (label, start) in enumerate(ordered):
content_start = start + len(label)
content_end = ordered[i + 1][1] if i + 1 < len(ordered) else len(text)
content = text[content_start:content_end].strip()
key_map = {
"ACKNOWLEDGEMENT": "acknowledgement",
"HIGHLIGHTS": "highlights",
"NEXT SESSION": "next_session",
}
result[key_map[label]] = content
return result
# βββββββββββββββββββββββββββββββββββββββββββββ
# PRE-WORKOUT FUNCTIONS
# βββββββββββββββββββββββββββββββββββββββββββββ
def predict_pre(
text: str,
model,
tokenizer,
device: "torch.device",
max_len: int = 128,
) -> Dict[str, int]:
"""
Run PreWorkoutDistilBERT inference on a single text string.
Returns raw integer predictions for each of the 6 heads.
"""
encoding = tokenizer(
text,
max_length=max_len,
padding="max_length",
truncation=True,
return_tensors="pt",
)
input_ids = encoding["input_ids"].to(device)
attention_mask = encoding["attention_mask"].to(device)
with torch.no_grad():
(
mood_logits,
energy_logits,
motivation_logits,
stress_logits,
soreness_region_logits,
soreness_severity_logits,
) = model(input_ids, attention_mask)
return {
"mood": mood_logits.argmax(dim=1).item(),
"energy": energy_logits.argmax(dim=1).item(),
"motivation": motivation_logits.argmax(dim=1).item(),
"stress": stress_logits.argmax(dim=1).item(),
"soreness_region": soreness_region_logits.argmax(dim=1).item(),
"soreness_severity": soreness_severity_logits.argmax(dim=1).item(),
}
def decode_pre_predictions(
preds: Dict[str, int],
mood_map: Dict[int, str],
energy_map: Dict[int, str],
motivation_map: Dict[int, str],
stress_map: Dict[int, str],
soreness_region_map: Dict[int, str],
soreness_severity_map:Dict[int, str],
) -> Dict[str, str]:
"""
Decode pre-workout integer predictions back to human-readable strings.
"""
return {
"mood": mood_map[preds["mood"]],
"energy": energy_map[preds["energy"]],
"motivation": motivation_map[preds["motivation"]],
"stress": stress_map[preds["stress"]],
"soreness_region": soreness_region_map[preds["soreness_region"]],
"soreness_severity": soreness_severity_map[preds["soreness_severity"]],
}
def build_pre_prompt(
bert_labels: Dict[str, str],
user_text: str,
workout_type: str,
duration_minutes: int,
user_goal: str,
equipment: List[str],
) -> str:
"""
Build the Claude prompt that generates a structured pre-workout plan.
Plain text output only β no Markdown, no asterisks, no symbols.
Section delimiters are ALL-CAPS labels so parse_workout_plan()
can split the response into named sections reliably.
"""
region = bert_labels["soreness_region"]
severity = bert_labels["soreness_severity"]
if region == "none" or severity == "none":
soreness_str = "no existing soreness"
else:
soreness_str = f"{severity} {region} soreness going in"
equipment_str = (
", ".join(equipment)
if equipment
else "bodyweight only"
)
prompt = f"""You are an expert personal trainer generating a structured pre-workout plan.
The user has described how they feel before training. Use their physical and mental state \
to prescribe the most appropriate session for them right now.
User state (classified from what they wrote):
- Mood: {bert_labels['mood']}
- Energy level: {bert_labels['energy']}
- Motivation: {bert_labels['motivation']}
- Stress level: {bert_labels['stress']}
- Existing soreness: {soreness_str}
Session parameters (selected in app):
- Workout type: {workout_type}
- Duration: {duration_minutes} minutes
- Goal: {user_goal}
- Available equipment:{equipment_str}
What the user wrote before their session:
"{user_text}"
Generate a complete structured workout plan. Use plain text only β no Markdown, \
no asterisks, no bold, no hyphens as bullet points, no special symbols of any kind.
Use the exact section labels below as delimiters. Do not add any text before \
WARM UP or after COACHING NOTE.
WARM UP
[list each exercise on its own line as: Exercise Name | sets/reps or duration]
MAIN WORKOUT
[list each exercise on its own line as: Exercise Name | sets x reps | rest period]
COOL DOWN
[list each exercise on its own line as: Exercise Name | duration]
COACHING NOTE
[2-3 sentences acknowledging their current state, explaining why you prescribed \
this session, and one actionable tip for today]
Important guidelines:
- If energy is low, reduce volume and intensity β fewer sets, lighter loads
- If stress is high, favour controlled movements over maximal effort
- If motivation is low, keep the session achievable and end on a win
- If soreness is present, programme around that muscle group entirely
- If motivation is high and energy is high, push appropriate intensity
- Match total volume to the duration specified"""
return prompt
# ββ Section keys returned by parse_workout_plan() ββββββββββββ
PLAN_SECTIONS = ["WARM UP", "MAIN WORKOUT", "COOL DOWN", "COACHING NOTE"]
def parse_workout_plan(raw: str) -> Dict[str, str]:
"""
Split a plain-text workout plan response into named sections.
Returns a dict with keys:
"warm_up" β warm up exercises, one per line
"main_workout" β main workout exercises, one per line
"cool_down" β cool down exercises, one per line
"coaching_note" β the coaching note paragraph
"raw" β original unmodified response (fallback)
Each exercise line uses pipe-separated fields:
"Exercise Name | sets x reps | rest period"
which PreWorkoutView splits on "|" to style each field independently.
If a section is missing from the response the key maps to "".
"""
result = {
"warm_up": "",
"main_workout": "",
"cool_down": "",
"coaching_note": "",
"raw": raw,
}
# Normalise line endings
text = raw.replace("\r\n", "\n").strip()
# Build a map of {section_label: start_index} for every label found
indices: Dict[str, int] = {}
for label in PLAN_SECTIONS:
idx = text.find(label)
if idx != -1:
indices[label] = idx
# Extract the text between each found label and the next
ordered = sorted(indices.items(), key=lambda x: x[1])
for i, (label, start) in enumerate(ordered):
# Content starts after the label and its newline
content_start = start + len(label)
content_end = ordered[i + 1][1] if i + 1 < len(ordered) else len(text)
content = text[content_start:content_end].strip()
key_map = {
"WARM UP": "warm_up",
"MAIN WORKOUT": "main_workout",
"COOL DOWN": "cool_down",
"COACHING NOTE": "coaching_note",
}
result[key_map[label]] = content
return result
|