arahmanmdmajid commited on
Commit
7ce1cd2
Β·
verified Β·
1 Parent(s): 1b7ec65

Upload QUICK_REFERENCE_FIXED.md

Browse files
Files changed (1) hide show
  1. QUICK_REFERENCE_FIXED.md +378 -0
QUICK_REFERENCE_FIXED.md ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TabeebAI Quick Reference - FIXED for Latest Groq SDK
2
+
3
+ ## πŸ”§ The Issue
4
+ The Groq SDK API changed. Use `client.chat.completions.create()` instead of `client.messages.create()`
5
+
6
+ ---
7
+
8
+ ## βœ… CELL 1: Install + Import (UNCHANGED)
9
+
10
+ ```python
11
+ # Install packages
12
+ import subprocess
13
+ import sys
14
+
15
+ for pkg in ["groq", "python-dotenv"]:
16
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", pkg])
17
+
18
+ print("βœ“ Packages installed!")
19
+
20
+ # Imports
21
+ import os
22
+ import json
23
+ from groq import Groq
24
+ from datetime import datetime
25
+
26
+ # Set API key (from Colab secrets)
27
+ from google.colab import userdata
28
+ GROQ_API_KEY = userdata.get('GROQ_API_KEY')
29
+
30
+ # Initialize client
31
+ client = Groq(api_key=GROQ_API_KEY)
32
+ print("βœ“ Groq client ready!")
33
+ ```
34
+
35
+ ---
36
+
37
+ ## βœ… CELL 2: Symptom Extraction - FIXED ⚑
38
+
39
+ ```python
40
+ def extract_symptoms(text_input, language="auto"):
41
+ """Extract symptoms from patient speech"""
42
+
43
+ prompt = f"""You are a medical assistant. Extract symptoms from this patient statement.
44
+
45
+ Patient: "{text_input}"
46
+
47
+ Respond ONLY with valid JSON (no markdown, no extra text):
48
+ {{
49
+ "chief_complaint": "main problem",
50
+ "symptoms": [
51
+ {{"name": "symptom", "severity": "mild/moderate/severe", "duration": "time"}}
52
+ ],
53
+ "language_detected": "urdu/english",
54
+ "confidence": 0.0,
55
+ "needs_emergency": false
56
+ }}"""
57
+
58
+ try:
59
+ # FIXED: Use chat.completions.create() instead of messages.create()
60
+ msg = client.chat.completions.create(
61
+ model="mixtral-8x7b-32768",
62
+ max_tokens=300,
63
+ messages=[{"role": "user", "content": prompt}]
64
+ )
65
+
66
+ response = msg.choices[0].message.content.strip()
67
+
68
+ # Extract JSON
69
+ start = response.find('{')
70
+ end = response.rfind('}') + 1
71
+ json_str = response[start:end]
72
+ data = json.loads(json_str)
73
+
74
+ return {"success": True, "data": data}
75
+
76
+ except Exception as e:
77
+ return {"success": False, "error": str(e)}
78
+
79
+ # Test it!
80
+ result = extract_symptoms("I have chest pain and I'm sweating")
81
+ print(json.dumps(result, indent=2, ensure_ascii=False))
82
+ ```
83
+
84
+ ---
85
+
86
+ ## βœ… CELL 3: Test with Urdu (UNCHANGED)
87
+
88
+ ```python
89
+ # Test cases - just copy and paste!
90
+
91
+ test_cases = [
92
+ {
93
+ "text": "Ω…Ψ¬ΪΎΫ’ Ψ³ΫŒΩ†Ϋ’ Ω…ΫŒΪΊ بہΨͺ Ψ―Ψ±Ψ― ہے اور Ω…Ψ¬ΪΎΫ’ Ψ³Ψ§Ω†Ψ³ Ω„ΫŒΩ†Ϋ’ Ω…ΫŒΪΊ دشواری ہو رہی ہے",
94
+ "language": "Urdu",
95
+ "expected": "EMERGENCY"
96
+ },
97
+ {
98
+ "text": "Ω…ΫŒΨ±Ψ§ درجہ Ψ­Ψ±Ψ§Ψ±Ψͺ 39 ڈگری ہے اور Ω…ΫŒΨ±Ϋ’ Ψ³Ψ± Ω…ΫŒΪΊ Ψ―Ψ±Ψ― ہے",
99
+ "language": "Urdu",
100
+ "expected": "High"
101
+ },
102
+ {
103
+ "text": "I have chest pain and difficulty breathing",
104
+ "language": "English",
105
+ "expected": "EMERGENCY"
106
+ },
107
+ ]
108
+
109
+ # Run tests
110
+ for i, test in enumerate(test_cases, 1):
111
+ print(f"\n{'='*50}")
112
+ print(f"Test {i}: {test['language']}")
113
+ print(f"Input: {test['text']}")
114
+ print(f"{'='*50}")
115
+
116
+ result = extract_symptoms(test['text'])
117
+ if result['success']:
118
+ print("βœ“ Success!")
119
+ print(json.dumps(result['data'], indent=2, ensure_ascii=False))
120
+ else:
121
+ print(f"βœ— Failed: {result['error']}")
122
+ ```
123
+
124
+ ---
125
+
126
+ ## βœ… CELL 4: Risk Scoring (UNCHANGED)
127
+
128
+ ```python
129
+ def calculate_risk_score(symptoms_data):
130
+ """Convert symptoms to risk score (0-100)"""
131
+
132
+ if not symptoms_data.get('data'):
133
+ return 0
134
+
135
+ data = symptoms_data['data']
136
+ score = 0
137
+
138
+ # Severity scoring
139
+ severity_map = {"mild": 5, "moderate": 25, "severe": 40}
140
+
141
+ for symptom in data.get('symptoms', []):
142
+ sev = symptom.get('severity', 'mild')
143
+ score += severity_map.get(sev, 5)
144
+
145
+ # Emergency bonus
146
+ if data.get('needs_emergency'):
147
+ score += 50
148
+
149
+ # Normalize
150
+ score = min(score, 100)
151
+
152
+ return score
153
+
154
+ def get_risk_level(score):
155
+ """Convert score to severity level"""
156
+ if score >= 71:
157
+ return "πŸ”΄ RED - EMERGENCY"
158
+ elif score >= 31:
159
+ return "🟑 YELLOW - MODERATE"
160
+ else:
161
+ return "🟒 GREEN - LOW RISK"
162
+
163
+ # Test
164
+ result = extract_symptoms("I have chest pain and difficulty breathing")
165
+ score = calculate_risk_score(result)
166
+ level = get_risk_level(score)
167
+
168
+ print(f"Risk Score: {score}/100")
169
+ print(f"Severity: {level}")
170
+ ```
171
+
172
+ ---
173
+
174
+ ## βœ… CELL 5: SOAP Report (UNCHANGED)
175
+
176
+ ```python
177
+ def generate_soap_report(symptoms_data, risk_score):
178
+ """Generate SOAP format medical report"""
179
+
180
+ if not symptoms_data.get('success'):
181
+ return "Unable to generate report"
182
+
183
+ data = symptoms_data['data']
184
+ symptoms_list = data.get('symptoms', [])
185
+ chief_complaint = data.get('chief_complaint', 'Not specified')
186
+
187
+ # Build SOAP
188
+ subjective = f"Patient reports: {chief_complaint}"
189
+ for s in symptoms_list:
190
+ subjective += f"\n β€’ {s.get('name', 'Unknown')}: {s.get('duration', 'Unknown duration')}"
191
+
192
+ objective = "Speech indicates " + ("distress" if risk_score > 50 else "no acute distress")
193
+
194
+ assessment = f"Clinical risk assessment score: {risk_score}/100"
195
+
196
+ plan = get_risk_level(risk_score)
197
+ if risk_score >= 71:
198
+ plan += "\n β€’ Immediate emergency evaluation required\n β€’ Call ambulance\n β€’ Do not delay treatment"
199
+ elif risk_score >= 31:
200
+ plan += "\n β€’ Medical evaluation within 24 hours\n β€’ Schedule urgent appointment"
201
+ else:
202
+ plan += "\n β€’ Home care with monitoring\n β€’ Follow up if symptoms worsen"
203
+
204
+ report = f"""
205
+ ╔═══════════════════════════════════════╗
206
+ β•‘ MEDICAL ASSESSMENT REPORT β•‘
207
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
208
+
209
+ SUBJECTIVE:
210
+ {subjective}
211
+
212
+ OBJECTIVE:
213
+ {objective}
214
+
215
+ ASSESSMENT:
216
+ {assessment}
217
+ {get_risk_level(risk_score)}
218
+
219
+ PLAN:
220
+ {plan}
221
+
222
+ ═══════════════════════════════════════
223
+ Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
224
+ """
225
+
226
+ return report
227
+
228
+ # Test
229
+ result = extract_symptoms("Ω…Ψ¬ΪΎΫ’ Ψ³ΫŒΩ†Ϋ’ Ω…ΫŒΪΊ Ψ―Ψ±Ψ― ہے اور Ω…Ψ¬ΪΎΫ’ ΩΎΨ³ΫŒΩ†Ϋ Ψ’ رہا ہے")
230
+ score = calculate_risk_score(result)
231
+ report = generate_soap_report(result, score)
232
+ print(report)
233
+ ```
234
+
235
+ ---
236
+
237
+ ## βœ… CELL 6: Complete Pipeline (UNCHANGED)
238
+
239
+ ```python
240
+ def complete_pipeline(patient_input):
241
+ """One function to rule them all!"""
242
+
243
+ print(f"\nπŸ”„ Processing: {patient_input[:50]}...")
244
+
245
+ # Step 1: Extract symptoms
246
+ symptoms_result = extract_symptoms(patient_input)
247
+
248
+ if not symptoms_result['success']:
249
+ return f"❌ Error: {symptoms_result['error']}"
250
+
251
+ # Step 2: Calculate risk
252
+ risk_score = calculate_risk_score(symptoms_result)
253
+ risk_level = get_risk_level(risk_score)
254
+
255
+ # Step 3: Generate report
256
+ report = generate_soap_report(symptoms_result, risk_score)
257
+
258
+ # Return formatted output
259
+ output = {
260
+ "status": "βœ“ Complete",
261
+ "risk_score": risk_score,
262
+ "severity": risk_level,
263
+ "symptoms": symptoms_result['data'].get('symptoms', []),
264
+ "report": report
265
+ }
266
+
267
+ return output
268
+
269
+ # Test it!
270
+ test_input = "Ω…Ψ¬ΪΎΫ’ Ψ³Ψ± Ω…ΫŒΪΊ Ψ―Ψ±Ψ― ہے اور Ω…ΫŒΨ±Ψ§ درجہ Ψ­Ψ±Ψ§Ψ±Ψͺ بہΨͺ زیادہ ہے"
271
+ result = complete_pipeline(test_input)
272
+ print(json.dumps(result, indent=2, ensure_ascii=False))
273
+ ```
274
+
275
+ ---
276
+
277
+ ## 🎯 Key Changes Made
278
+
279
+ | Old | New |
280
+ |-----|-----|
281
+ | `client.messages.create()` | `client.chat.completions.create()` |
282
+ | `msg.content[0].text` | `msg.choices[0].message.content` |
283
+
284
+ ---
285
+
286
+ ## πŸ“‹ Copy-Paste All at Once
287
+
288
+ If you want to paste everything in one cell:
289
+
290
+ ```python
291
+ import subprocess, sys
292
+ for pkg in ["groq"]:
293
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", pkg])
294
+
295
+ import os, json
296
+ from groq import Groq
297
+ from datetime import datetime
298
+ from google.colab import userdata
299
+
300
+ GROQ_API_KEY = userdata.get('GROQ_API_KEY')
301
+ client = Groq(api_key=GROQ_API_KEY)
302
+ print("βœ“ Ready!")
303
+
304
+ # ===== SYMPTOM EXTRACTION =====
305
+ def extract_symptoms(text_input, language="auto"):
306
+ prompt = f"""You are a medical assistant. Extract symptoms from: "{text_input}"
307
+
308
+ Respond ONLY with JSON:
309
+ {{"chief_complaint": "problem", "symptoms": [{{"name": "symptom", "severity": "mild/moderate/severe", "duration": "time"}}], "language_detected": "urdu/english", "confidence": 0.0, "needs_emergency": false}}"""
310
+
311
+ try:
312
+ msg = client.chat.completions.create(
313
+ model="mixtral-8x7b-32768",
314
+ max_tokens=300,
315
+ messages=[{"role": "user", "content": prompt}]
316
+ )
317
+ response = msg.choices[0].message.content.strip()
318
+ start = response.find('{')
319
+ end = response.rfind('}') + 1
320
+ data = json.loads(response[start:end])
321
+ return {"success": True, "data": data}
322
+ except Exception as e:
323
+ return {"success": False, "error": str(e)}
324
+
325
+ # ===== RISK SCORING =====
326
+ def calculate_risk_score(symptoms_data):
327
+ if not symptoms_data.get('data'): return 0
328
+ data = symptoms_data['data']
329
+ score = sum({"mild": 5, "moderate": 25, "severe": 40}.get(s.get('severity', 'mild'), 5)
330
+ for s in data.get('symptoms', []))
331
+ if data.get('needs_emergency'): score += 50
332
+ return min(score, 100)
333
+
334
+ def get_risk_level(score):
335
+ if score >= 71: return "πŸ”΄ RED - EMERGENCY"
336
+ elif score >= 31: return "🟑 YELLOW - MODERATE"
337
+ else: return "🟒 GREEN - LOW RISK"
338
+
339
+ # ===== SOAP REPORT =====
340
+ def generate_soap_report(symptoms_data, risk_score):
341
+ if not symptoms_data.get('success'): return "Error"
342
+ data = symptoms_data['data']
343
+ report = f"""
344
+ SUBJECTIVE: {data.get('chief_complaint', 'N/A')}
345
+ """
346
+ for s in data.get('symptoms', []):
347
+ report += f"\n β€’ {s.get('name', 'Unknown')} ({s.get('severity', 'Unknown')})"
348
+ report += f"""
349
+ OBJECTIVE: Speech indicates {'distress' if risk_score > 50 else 'no distress'}
350
+ ASSESSMENT: Risk Score {risk_score}/100
351
+ PLAN: {get_risk_level(risk_score)}
352
+ """
353
+ return report
354
+
355
+ # ===== COMPLETE PIPELINE =====
356
+ def complete_pipeline(text):
357
+ result = extract_symptoms(text)
358
+ if not result['success']: return result
359
+ score = calculate_risk_score(result)
360
+ return {"status": "βœ“", "risk_score": score, "severity": get_risk_level(score), "report": generate_soap_report(result, score)}
361
+
362
+ # TEST
363
+ print(complete_pipeline("I have chest pain and difficulty breathing"))
364
+ print("\n" + "="*50 + "\n")
365
+ print(complete_pipeline("Ω…Ψ¬ΪΎΫ’ Ψ³ΫŒΩ†Ϋ’ Ω…ΫŒΪΊ Ψ―Ψ±Ψ― ہے"))
366
+ ```
367
+
368
+ ---
369
+
370
+ ## βœ… Now Run This
371
+
372
+ 1. **Cell 1**: Install + Init (copy-paste above)
373
+ 2. **Cell 2**: Test with English
374
+ 3. **Cell 3**: Test with Urdu
375
+
376
+ You should see βœ“ Success now!
377
+
378
+ Let me know if you still get errors!