File size: 16,581 Bytes
71a1272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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