Yoga-1M / code /backend /app /services /correction.py
Arko007's picture
real backend code for production-path tests
71a1272 verified
Raw History Blame Contribute Delete
16.6 kB
import os
import logging
import requests
from typing import Dict, Optional
logger = logging.getLogger(__name__)
# Biomechanical knowledge graph templates
BIOMECHANICAL_TEMPLATES = {
"warrior_2": {
"knee_l": {
"issue_low": {
"en": "Bend your left knee more to bring it directly over your ankle.",
"hi": "अपने बाएं घुटने को थोड़ा और मोड़ें ताकि वह टखने के ठीक ऊपर रहे।",
"bn": "আপনার বাম হাঁটু আরও বাঁকুন যাতে এটি গোড়ালির ঠিক উপরে থাকে।"
}
},
"knee_r": {
"issue_low": {
"en": "Bend your right knee more to align it directly over your ankle.",
"hi": "अपने दाएं घुटने को थोड़ा और मोड़ें ताकि वह टखने के ठीक ऊपर रहे।",
"bn": "আপনার ডান হাঁটু আরও বাঁকুন যাতে এটি গোড়ালির ঠিক উপরে থাকে।"
}
}
},
"chair_pose": {
"knee_l": {
"issue_low": {
"en": "Sit deeper to bring your thighs closer to parallel to the floor.",
"hi": "जांघों को फर्श के समानांतर लाने के लिए थोड़ा नीचे बैठें।",
"bn": "উরু মেঝের সমান্তরাল করার জন্য আর একটু নিচে বসুন।"
}
},
"knee_r": {
"issue_low": {
"en": "Sit deeper to align both thighs towards parallel to the floor.",
"hi": "दोनों जांघों को फर्श के समानांतर करने के लिए थोड़ा नीचे बैठें।",
"bn": "দুই উরু মেঝের সমান্তরাল করার জন্য আর একটু নিচে বসুন।"
}
}
},
"cobra_pose": {
"neck": {
"issue_low": {
"en": "Elongate your neck and gaze forward, relaxing your shoulders.",
"hi": "अपनी गर्दन को लंबी करें और सामने की ओर देखें, कंधों को ढीला छोड़ें।",
"bn": "আপনার ঘাড় সোজা করুন এবং সামনের দিকে তাকান, কাঁধ শিথিল রাখুন।"
}
}
},
"plank": {
"elbow_l": {
"issue_low": {
"en": "Extend your left elbow to keep your arm straight.",
"hi": "अपने बाएं हाथ को सीधा रखने के लिए अपनी बाईं कोहनी को फैलाएं।",
"bn": "আপনার বাম হাত সোজা রাখতে বাম কনুই প্রসারিত করুন।"
}
},
"elbow_r": {
"issue_low": {
"en": "Extend your right elbow to keep your arm straight.",
"hi": "अपने दाएं हाथ को सीधा रखने के लिए अपनी दाईं कोहनी को फैलाएं।",
"bn": "আপনার ডান হাত সোজা রাখতে ডান কনুই প্রসারিত করুন।"
}
},
"trunk_l": {
"issue_low": {
"en": "Keep your spine and body in a straight line, do not let your hips sag.",
"hi": "अपनी रीढ़ और शरीर को एक सीधी रेखा में रखें, अपने नितंबों को नीचे न झुकने दें।",
"bn": "আপনার মেরুদণ্ড এবং শরীর সোজা রাখুন, নিতম্ব ঝুলে যেতে দেবেন না।"
}
}
},
"tree_pose": {
"knee_l": {
"issue_low": {
"en": "Bend your left knee more and place your foot on your inner thigh.",
"hi": "अपने बाएं घुटने को अधिक मोड़ें और अपने पैर को अपनी आंतरिक जांघ पर रखें।",
"bn": "আপনার বাম হাঁটু আরও বাঁকুন এবং পায়ের পাতাটি উরুর ভেতরের দিকে রাখুন।"
}
},
"hip_abduct_l": {
"issue_low": {
"en": "Open your left hip outward to bring your knee to the side.",
"hi": "अपने बाएं कूल्हे को बाहर की ओर खोलें ताकि आपका घुटना बगल की ओर हो सके।",
"bn": "আপনার বাম হাঁটু পাশের দিকে আনতে বাম হিপ বাইরের দিকে প্রসারিত করুন।"
}
},
"knee_r": {
"issue_low": {
"en": "Keep your standing right leg fully straight and strong.",
"hi": "अपने खड़े हुए दाएं पैर को पूरी तरह से सीधा और मजबूत रखें।",
"bn": "দাঁড়িয়ে থাকা ডান পা সম্পূর্ণ সোজা এবং শক্ত রাখুন।"
}
}
},
"mountain_pose": {
"knee_l": {
"issue_low": {
"en": "Keep your left leg straight and engage your thigh muscles.",
"hi": "अपने बाएं पैर को सीधा रखें और अपनी जांघ की मांसपेशियों को सक्रिय करें।",
"bn": "আপনার বাম পা সোজা রাখুন এবং উরুর পেশী সক্রিয় করুন।"
}
},
"knee_r": {
"issue_low": {
"en": "Keep your right leg straight and engage your thigh muscles.",
"hi": "अपने दाएं पैर को सीधा रखें और अपनी जांघ की मांसपेशियों को सक्रिय करें।",
"bn": "আপনার ডান পা সোজা রাখুন এবং উরুর পেশী সক্রিয় করুন।"
}
},
"trunk_l": {
"issue_low": {
"en": "Lengthen your spine and stand tall with shoulders relaxed.",
"hi": "अपनी रीढ़ को लंबा करें और कंधों को आराम देते हुए सीधे खड़े हों।",
"bn": "মেরুদণ্ড সোজা করে বুক টানটান করে দাঁড়ান এবং কাঁধ শিথিল রাখুন।"
}
}
},
"downward_dog": {
"hip_l": {
"issue_low": {
"en": "Lift your hips higher to form a taller inverted V shape.",
"hi": "अपने कूल्हों को ऊंचा उठाएं ताकि एक बड़ा उल्टा वी आकार बने।",
"bn": "একটি বড় উল্টানো ভি আকৃতি তৈরি করতে আপনার নিতম্ব আরও উঁচু করুন।"
}
},
"knee_l": {
"issue_low": {
"en": "Straighten your legs as much as comfortable, keeping heels reaching down.",
"hi": "जितना आरामदायक हो अपने पैरों को सीधा करें, एड़ियों को नीचे की ओर ले जाते हुए।",
"bn": "যতটা আরামদায়ক পা সোজা করুন, গোড়ালি নিচের দিকে রাখুন।"
}
},
"shoulder_l": {
"issue_low": {
"en": "Press firmly through your hands and extend your arms fully.",
"hi": "अपने हाथों से मजबूती से दबाएं और अपनी बाहों को पूरी तरह फैलाएं।",
"bn": "হাতের উপর দৃঢ়ভাবে চাপ দিন এবং বাহু সম্পূর্ণ প্রসারিত করুন।"
}
}
}
}
DEFAULT_CORRECTIONS = {
"en": "Maintain your posture, breathing steadily.",
"hi": "अपनी मुद्रा बनाए रखें, लगातार सांस लेते रहें।",
"bn": "আপনার অঙ্গভঙ্গি বজায় রাখুন, নিয়মিত শ্বাস নিন।"
}
# Escalation wrappers for the correction-efficacy loop.
#
# When a cue has been delivered and the targeted joint did NOT measurably
# improve, repeating the identical sentence is the least useful thing the
# system can do -- it is what makes automated coaching feel deaf. These are
# pose-agnostic so they compose with any base cue in any of the three
# languages, instead of needing 3 hand-written variants per pose per joint.
#
# Tier 2 adds the measured magnitude, which turns a vague instruction into a
# quantified one. Tier 3 stops asking for more and backs off, because a cue
# that has failed twice usually means the range of motion is not available
# today -- pushing harder there is exactly the injury risk this system exists
# to avoid.
_ESCALATION = {
1: {
"en": "{base} You're about {deg} degrees off.",
"hi": "{base} आप लगभग {deg} डिग्री दूर हैं।",
"bn": "{base} আপনি প্রায় {deg} ডিগ্রি দূরে আছেন।",
},
2: {
"en": "Ease out of the shape and reset. Come back only as far as feels comfortable today.",
"hi": "मुद्रा से धीरे-धीरे बाहर आएं और फिर से शुरू करें। आज जितना सहज लगे, उतना ही करें।",
"bn": "ভঙ্গি থেকে ধীরে বেরিয়ে আসুন এবং আবার শুরু করুন। আজ যতটা স্বচ্ছন্দ, ততটুকুই করুন।",
},
}
def _escalate(text: str, language: str, attempt: int, deg: float) -> str:
"""attempt counts PRIOR deliveries of this cue that produced no measured
improvement. 0 -> the plain cue."""
tier = min(int(attempt), 2)
if tier <= 0:
return text
tmpl = _ESCALATION[tier].get(language) or _ESCALATION[tier]["en"]
return tmpl.format(base=text, deg=int(round(deg)))
def generate_safe_correction(
pose_id: str,
deviations: Dict[str, float],
language: str = "en",
groq_api_key: Optional[str] = None,
attempt: int = 0,
) -> tuple:
"""
Enforces a 3-stage validation pipeline:
Stage 1: Symbolic Rules Engine + Local template matching.
Stage 2: Optional Groq API translation/paraphrase inside safe boundaries.
Stage 3: Post-generation safety validation screening.
"""
pose_templates = BIOMECHANICAL_TEMPLATES.get(pose_id, {})
# Stage 1: Find highest deviation joint exceeding safe threshold (10 degrees)
target_joint = None
max_dev = 0.0
for joint, dev_val in deviations.items():
if joint in pose_templates and dev_val > max_dev:
if dev_val > 10.0:
max_dev = dev_val
target_joint = joint
# Retrieve pre-approved template
if target_joint:
correction_text = pose_templates[target_joint]["issue_low"].get(language, "Adjust your alignment.")
else:
correction_text = DEFAULT_CORRECTIONS.get(language, "Adjust your alignment.")
is_safe = True
# Tier 2 replaces the cue outright with a back-off instruction, so there is
# nothing left to paraphrase and no reason to spend an LLM call on it.
if target_joint and attempt >= 2:
return _escalate(correction_text, language, attempt, max_dev), True, target_joint
# Stage 2: Paraphrase using LLM if Groq API key is available
api_key = groq_api_key or os.environ.get("GROQ_API_KEY")
if api_key:
try:
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
# Map language code to full language name to instruct the LLM
lang_names = {"en": "English", "hi": "Hindi", "bn": "Bengali"}
target_lang_name = lang_names.get(language, "English")
# qwen/qwen3.6-27b was correct when this was written but has since
# been decommissioned: Groq now answers it with 404 model_not_found.
# Because the non-200 branch below used to be silent, the service
# had been quietly returning the Stage-1 template for every request
# instead of the paraphrase -- verified by the live response being
# byte-identical to the template string.
payload = {
"model": "qwen/qwen3.8-27b",
# A system-only message list is rejected by this model with
# 400 "No user query found in messages", so the instruction to
# rewrite goes in the system role and the text to be rewritten
# goes in the user role -- which is also the correct shape.
"messages": [
{
"role": "system",
"content": f"You are a professional yoga instructor. Translate or paraphrase the user's instruction into {target_lang_name}. Do NOT suggest stretching further or pushing deeper. Keep it safe, concise (under 15 words), and respond ONLY in the {target_lang_name} language, with no preamble."
},
{"role": "user", "content": correction_text},
],
"temperature": 0.2,
"max_tokens": 120,
"reasoning_format": "hidden"
}
response = requests.post("https://api.groq.com/openai/v1/chat/completions", json=payload, headers=headers, timeout=8)
if response.status_code != 200:
# Log it. The template fallback is a correct and safe outcome,
# which is exactly why a silent one is dangerous: it looks
# identical to success from the outside.
logger.warning(
"Groq correction call returned %s, falling back to template: %s",
response.status_code, response.text[:200])
if response.status_code == 200:
candidate_text = response.json()["choices"][0]["message"]["content"].strip()
# Stage 3: Post-Generation Safety Validation
forbidden_words = ["push", "force", "hurt", "pain", "stretch more", "further"]
if not any(word in candidate_text.lower() for word in forbidden_words):
correction_text = candidate_text
else:
is_safe = False # Flag candidate as unsafe; fallback to rule-based template
except Exception as e:
logger.warning(f"Groq correction call failed, falling back to template: {e}")
if target_joint and attempt >= 1:
correction_text = _escalate(correction_text, language, attempt, max_dev)
return correction_text, is_safe, target_joint