Repository navigation
Expand file tree
/
Copy pathpost_care_app.py
More file actions
2040 lines (1739 loc) · 97.6 KB
/
Copy pathpost_care_app.py
File metadata and controls
2040 lines (1739 loc) · 97.6 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
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
# Configure Streamlit page FIRST - must be the very first Streamlit command
st.set_page_config(
page_title="Cardiac Post-Care Assistant",
layout="wide",
page_icon="❤️",
initial_sidebar_state="expanded"
)
import mysql.connector
import datetime
import time
import hashlib
import requests
import json
import html # For HTML escaping
import streamlit.components.v1 as components
import tempfile
import os
import re
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# For text-to-speech and lightweight AI processing
try:
from gtts import gTTS
import tempfile
import os
except ImportError:
st.error("Please install required packages: pip install gtts mysql-connector-python requests python-dotenv")
# Database configuration - loads from .env file if available
DB_CONFIG = {
'host': os.getenv('DB_HOST', 'localhost'),
'user': os.getenv('DB_USER', 'root'), # Update with your MySQL username
'password': os.getenv('DB_PASSWORD', ''), # Update with your MySQL password
'database': os.getenv('DB_NAME', 'post_care_db') # Update with your database name
}
# Initialize database tables
def init_database():
try:
conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor()
# Create users table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
user_type ENUM('patient', 'doctor') NOT NULL,
full_name VARCHAR(100) NOT NULL,
doctor_id INT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (doctor_id) REFERENCES users(id)
)
''')
# Create patient_assessments table
cursor.execute('''
CREATE TABLE IF NOT EXISTS patient_assessments (
id INT AUTO_INCREMENT PRIMARY KEY,
patient_id INT NOT NULL,
doctor_id INT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
cardiac_symptoms TEXT,
breathing_physical TEXT,
medication_response TEXT,
activity_fatigue TEXT,
ai_summary TEXT,
risk_level ENUM('low', 'medium', 'high') DEFAULT 'medium',
FOREIGN KEY (patient_id) REFERENCES users(id),
FOREIGN KEY (doctor_id) REFERENCES users(id)
)
''')
conn.commit()
conn.close()
return True
except Exception as e:
st.error(f"Database initialization error: {e}")
return False
# Password hashing
def hash_password(password):
return hashlib.sha256(str.encode(password)).hexdigest()
# User authentication
def authenticate_user(username, password):
try:
conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor()
cursor.execute("SELECT id, username, user_type, full_name, doctor_id FROM users WHERE username = %s AND password_hash = %s",
(username, hash_password(password)))
user = cursor.fetchone()
conn.close()
return user
except Exception as e:
st.error(f"Authentication error: {e}")
return None
# Create new user
def create_user(username, email, password, user_type, full_name, doctor_id=None):
try:
conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor()
cursor.execute("""
INSERT INTO users (username, email, password_hash, user_type, full_name, doctor_id)
VALUES (%s, %s, %s, %s, %s, %s)
""", (username, email, hash_password(password), user_type, full_name, doctor_id))
conn.commit()
conn.close()
return True
except Exception as e:
st.error(f"User creation error: {e}")
return False
# Get doctors list
def get_doctors():
try:
conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor()
cursor.execute("SELECT id, full_name FROM users WHERE user_type = 'doctor'")
doctors = cursor.fetchall()
conn.close()
return doctors
except Exception as e:
st.error(f"Error fetching doctors: {e}")
return []
# AI Summary using intelligent template analysis (reliable, local processing)
def clean_api_summary(summary):
"""Clean up repetitive or unclear AI-generated summaries."""
if not summary:
return summary
# Remove common repetitive patterns
import re
# Remove excessive repetition of "cardiac" and "patient"
summary = re.sub(r'\b(cardiac|patient)\s+\1\b', r'\1', summary, flags=re.IGNORECASE)
# Remove repetitive phrases like "Patient Patient" or "Cardiac Cardiac"
summary = re.sub(r'\b(\w+)\s+\1\b', r'\1', summary, flags=re.IGNORECASE)
# Clean up excessive colons and formatting artifacts
summary = re.sub(r':\s*:', ':', summary)
summary = re.sub(r'\s+', ' ', summary) # Multiple spaces to single space
# Remove incomplete sentences at the end
sentences = summary.split('.')
if len(sentences) > 1 and len(sentences[-1].strip()) < 10:
summary = '.'.join(sentences[:-1]) + '.'
# Ensure it starts with a capital letter
summary = summary.strip()
if summary and not summary[0].isupper():
summary = summary[0].upper() + summary[1:]
return summary
def generate_ai_summary_api(text):
"""Generate summary using Hugging Face API - optimized for lightweight systems."""
try:
# Use a well-known, reliable summarization model
API_URL = "https://api-inference.huggingface.co/models/microsoft/DialoGPT-medium" # Try this first
BACKUP_API_URL = "https://api-inference.huggingface.co/models/t5-small" # Backup option
BEST_API_URL = "https://api-inference.huggingface.co/models/google/pegasus-xsum" # Best summarization model
# Check for API token in environment variable
api_token = os.getenv('HUGGINGFACE_API_TOKEN', None)
if not api_token:
# For demonstration, try with a demo approach
# In production, users should set their own token
st.info("💡 For enhanced AI summaries, set HUGGINGFACE_API_TOKEN environment variable")
return None
st.info(f"🤖 Using Hugging Face API with token: {api_token[:10]}...")
headers = {"Authorization": f"Bearer {api_token}"}
# Try the best summarization model first (Pegasus)
payload = {
"inputs": text,
"parameters": {
"max_length": 100,
"min_length": 30,
"do_sample": True,
"temperature": 0.7,
"top_p": 0.9,
"repetition_penalty": 1.2
}
}
st.info("🔄 Making API request to Pegasus summarization model...")
response = requests.post(BEST_API_URL, headers=headers, json=payload, timeout=30)
st.info(f"📡 API Response Status: {response.status_code}")
if response.status_code == 200:
result = response.json()
if isinstance(result, list) and len(result) > 0:
api_summary = result[0].get('summary_text', '')
# Clean up the API response
api_summary = clean_api_summary(api_summary)
st.success(f"✅ Pegasus Summary Generated: {api_summary[:100]}...")
return api_summary
elif response.status_code == 503:
# Model is loading - try backup model
st.info("⏳ Pegasus model loading, trying T5-small backup...")
# Try T5-small as backup
payload_backup = {
"inputs": f"summarize: {text}",
"parameters": {
"max_length": 100,
"min_length": 20,
"temperature": 0.7,
"do_sample": True
}
}
response = requests.post(BACKUP_API_URL, headers=headers, json=payload_backup, timeout=30)
if response.status_code == 200:
result = response.json()
if isinstance(result, list) and len(result) > 0:
api_summary = result[0].get('generated_text', '')
# Clean up the API response
api_summary = clean_api_summary(api_summary)
st.success(f"✅ T5 Summary Generated: {api_summary[:100]}...")
return api_summary
else:
st.warning(f"⚠️ API request failed with status {response.status_code}")
except Exception as e:
# Silently fail and use fallback - don't overwhelm user with API errors
st.warning(f"❌ API unavailable: {e}")
st.info("🔄 Falling back to template-based summary")
return None
def generate_ai_summary(cardiac_symptoms, breathing_physical, medication_response, activity_fatigue):
"""Generate AI summary using intelligent template analysis with enhanced medical logic."""
try:
st.info("🎯 Starting intelligent medical summary generation...")
# Always use our enhanced template-based summary for reliability
st.info("📋 Using intelligent template-based summary (most reliable method)")
enhanced_summary = generate_enhanced_template_summary(
cardiac_symptoms, breathing_physical, medication_response, activity_fatigue
)
method = "Intelligent Template Analysis"
# Determine risk level based on content analysis
full_text = f"{cardiac_symptoms} {breathing_physical} {medication_response} {activity_fatigue}"
risk_level = assess_risk_level(full_text)
st.info(f"🏁 Summary generation complete using: {method}")
st.info(f"🎯 Risk level assessed as: {risk_level}")
return enhanced_summary, risk_level
except Exception as e:
st.error(f"❌ Summary generation failed: {str(e)}")
st.warning("🔄 Using basic template fallback")
return generate_fallback_summary(cardiac_symptoms, breathing_physical, medication_response, activity_fatigue)
def generate_enhanced_template_summary(cardiac_symptoms, breathing_physical, medication_response, activity_fatigue):
"""Enhanced template-based summary with intelligent content analysis and medical insights."""
# Analyze content for key medical indicators
cardiac_analysis = analyze_cardiac_content(cardiac_symptoms)
respiratory_analysis = analyze_respiratory_content(breathing_physical)
medication_analysis = analyze_medication_content(medication_response)
activity_analysis = analyze_activity_content(activity_fatigue)
# Generate intelligent medical insights based on combined analysis
overall_status = determine_overall_status(cardiac_analysis, respiratory_analysis, medication_analysis, activity_analysis)
recovery_stage = assess_recovery_stage(cardiac_symptoms, breathing_physical, medication_response, activity_fatigue)
clinical_recommendations = generate_clinical_recommendations(cardiac_analysis, respiratory_analysis, medication_analysis, activity_analysis)
summary = f"""PATIENT ASSESSMENT SUMMARY (Intelligent Medical Analysis):
OVERALL STATUS: {overall_status}
DETAILED ASSESSMENT:
• Cardiac Function: {cardiac_analysis}
• Respiratory Status: {respiratory_analysis}
• Medication Management: {medication_analysis}
• Physical Activity: {activity_analysis}
RECOVERY ASSESSMENT: {recovery_stage}
CLINICAL NOTES:
• Assessment date: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}
• Analysis method: Advanced keyword recognition with medical logic
• Recommendations: {clinical_recommendations}
• Next steps: Continue monitoring per established care plan"""
return summary
def determine_overall_status(cardiac, respiratory, medication, activity):
"""Determine overall patient status based on all assessments."""
positive_count = sum(1 for analysis in [cardiac, respiratory, medication, activity] if "✅" in analysis)
concerning_count = sum(1 for analysis in [cardiac, respiratory, medication, activity] if "⚠️" in analysis)
if concerning_count >= 2:
return "⚠️ Multiple areas of concern requiring immediate medical attention"
elif concerning_count == 1:
return "🔶 One area of concern noted - requires monitoring and possible intervention"
elif positive_count >= 3:
return "✅ Patient showing excellent recovery progress across all major areas"
elif positive_count >= 2:
return "✅ Patient showing good recovery progress with stable condition"
else:
return "🔶 Mixed recovery indicators - requires continued close monitoring"
def assess_recovery_stage(cardiac, respiratory, medication, activity):
"""Assess the current stage of recovery."""
responses = [cardiac.lower(), respiratory.lower(), medication.lower(), activity.lower()]
full_text = " ".join(responses)
# Check for negative statements about symptoms
negative_indicators = ['haven\'t', 'have not', 'no', 'not', 'never', 'none', 'without', 'don\'t']
has_negative_symptoms = any(neg in full_text for neg in negative_indicators)
excellent_indicators = ["excellent", "great", "perfect", "no issues", "normal", "all good"]
good_indicators = ["good", "fine", "better", "improving", "stable", "feel good"]
concerning_indicators = ["severe", "pain", "difficulty", "problems", "worse", "tired", "can't"]
excellent_count = sum(1 for indicator in excellent_indicators if indicator in full_text)
good_count = sum(1 for indicator in good_indicators if indicator in full_text)
concerning_count = sum(1 for indicator in concerning_indicators if indicator in full_text)
# If they mention concerning symptoms in negative context, treat as positive
if concerning_count > 0 and has_negative_symptoms:
excellent_count += 1 # Boost for explicitly denying symptoms
concerning_count = 0 # Reset concerning count
if excellent_count >= 2 or (good_count >= 3 and concerning_count == 0):
return "🟢 Advanced recovery stage - patient demonstrating excellent progress"
elif good_count >= 2 and concerning_count == 0:
return "🟡 Intermediate recovery stage - steady progress with good indicators"
elif concerning_count >= 2:
return "🔴 Early recovery stage - requires intensive monitoring and support"
else:
return "🟡 Progressive recovery stage - showing gradual improvement"
def generate_clinical_recommendations(cardiac, respiratory, medication, activity):
"""Generate specific clinical recommendations based on assessment."""
recommendations = []
if "⚠️" in cardiac:
recommendations.append("Immediate cardiac evaluation")
elif "🔶" in cardiac:
recommendations.append("Enhanced cardiac monitoring")
if "⚠️" in respiratory:
recommendations.append("Respiratory function assessment")
elif "🔶" in respiratory:
recommendations.append("Monitor breathing patterns")
if "⚠️" in medication:
recommendations.append("Medication review and adjustment")
elif "🔶" in medication:
recommendations.append("Medication compliance support")
if "⚠️" in activity:
recommendations.append("Physical therapy evaluation")
elif "🔶" in activity:
recommendations.append("Gradual activity progression")
if not recommendations:
recommendations.append("Continue current treatment plan")
recommendations.append("Regular follow-up monitoring")
return " • ".join(recommendations)
def analyze_cardiac_content(text):
"""Analyze cardiac symptoms for intelligent summary."""
text_lower = text.lower()
if any(word in text_lower for word in ['severe', 'emergency', 'unbearable', 'level 8', 'level 9', 'level 10']):
return "⚠️ CONCERNING SYMPTOMS - Requires immediate medical attention"
elif any(word in text_lower for word in ['moderate', 'level 4', 'level 5', 'level 6', 'occasional']):
return "🔶 Moderate symptoms noted - Continue close monitoring"
elif any(word in text_lower for word in ['mild', 'level 1', 'level 2', 'level 3', 'improving']):
return "✅ Mild symptoms - Positive recovery trajectory"
elif any(word in text_lower for word in ['no pain', 'no symptoms', 'feeling good', 'normal', 'all good', 'good', 'fine', 'great', 'excellent', 'ok', 'okay', 'well', 'better', 'no issues', 'no problems', 'nothing', 'none']):
return "✅ No significant cardiac symptoms reported"
else:
return "🔍 Mixed symptom presentation - Requires clinical evaluation"
def analyze_respiratory_content(text):
"""Analyze respiratory symptoms for intelligent summary."""
text_lower = text.lower()
# Check for negative statements first (haven't, no, not, etc.)
negative_indicators = ['haven\'t', 'have not', 'no', 'not', 'never', 'none', 'without']
has_negative = any(neg in text_lower for neg in negative_indicators)
# Concerning symptoms
concerning_words = ['severe', 'difficulty breathing', 'shortness', 'can\'t breathe']
has_concerning = any(word in text_lower for word in concerning_words)
# If they mention concerning symptoms but in a negative context, treat as positive
if has_concerning and has_negative:
return "✅ No significant respiratory symptoms reported"
elif has_concerning and not has_negative:
return "⚠️ Respiratory concerns noted - Monitor closely"
elif any(word in text_lower for word in ['some', 'mild', 'slight', 'occasional']):
return "🔶 Mild respiratory symptoms - Within expected recovery range"
elif any(word in text_lower for word in ['good', 'normal', 'no problems', 'breathing well', 'all good', 'fine', 'great', 'excellent', 'ok', 'okay', 'well', 'better', 'no issues', 'nothing', 'none']):
return "✅ Normal respiratory function reported"
else:
return "🔍 Respiratory status requires further evaluation"
def analyze_medication_content(text):
"""Analyze medication adherence for intelligent summary."""
text_lower = text.lower()
# Check for negative statements first
negative_indicators = ['haven\'t', 'have not', 'no', 'not', 'never', 'none', 'without']
has_negative = any(neg in text_lower for neg in negative_indicators)
# Concerning medication issues
concerning_words = ['not taking', 'stopped', 'forgot', 'can\'t afford']
side_effect_words = ['side effects', 'problems', 'reaction', 'dizzy', 'nausea']
has_adherence_issues = any(word in text_lower for word in concerning_words)
has_side_effects = any(word in text_lower for word in side_effect_words)
if has_adherence_issues and not has_negative:
return "⚠️ MEDICATION ADHERENCE CONCERN - Requires immediate intervention"
elif has_side_effects and has_negative:
return "✅ Good medication tolerance - No side effects reported"
elif has_side_effects and not has_negative:
return "🔶 Side effects reported - May require medication adjustment"
elif any(word in text_lower for word in ['taking as directed', 'compliant', 'following', 'no problems', 'all good', 'good', 'fine', 'great', 'excellent', 'ok', 'okay', 'well', 'better', 'no issues', 'taking', 'yes', 'everything', 'nothing']):
return "✅ Good medication adherence - Continue current regimen"
else:
return "🔍 Medication compliance status needs clarification"
def analyze_activity_content(text):
"""Analyze activity tolerance for intelligent summary."""
text_lower = text.lower()
if any(word in text_lower for word in ['can\'t', 'unable', 'too tired', 'exhausted', 'bed rest']):
return "⚠️ Significant activity limitations - Consider intervention"
elif any(word in text_lower for word in ['some fatigue', 'getting better', 'slowly improving']):
return "🔶 Gradual improvement in activity tolerance noted"
elif any(word in text_lower for word in ['normal', 'good energy', 'active', 'no problems', 'all good', 'good', 'fine', 'great', 'excellent', 'ok', 'okay', 'well', 'better', 'no issues', 'everything', 'nothing']):
return "✅ Good activity tolerance - Recovery progressing well"
else:
return "🔍 Activity level requires further assessment"
def generate_fallback_summary(cardiac_symptoms, breathing_physical, medication_response, activity_fatigue):
"""Fallback summary generation when AI model is not available."""
summary = f"""PATIENT ASSESSMENT SUMMARY (Template-Based):
Cardiac Status: {cardiac_symptoms[:150]}{'...' if len(cardiac_symptoms) > 150 else ''}
Respiratory Function: {breathing_physical[:150]}{'...' if len(breathing_physical) > 150 else ''}
Medication Management: {medication_response[:150]}{'...' if len(medication_response) > 150 else ''}
Activity and Recovery: {activity_fatigue[:150]}{'...' if len(activity_fatigue) > 150 else ''}
Clinical Note: This summary was generated using template-based analysis.
Assessment completed on {datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}."""
# Determine risk level
full_text = f"{cardiac_symptoms} {breathing_physical} {medication_response} {activity_fatigue}"
risk_level = assess_risk_level(full_text)
return summary, risk_level
def assess_risk_level(text):
"""Assess patient risk level based on response content with negative statement handling."""
text_lower = text.lower()
# Check for negative indicators first
negative_indicators = ['haven\'t', 'have not', 'no', 'not', 'never', 'none', 'without', 'don\'t', 'do not']
has_negative = any(neg in text_lower for neg in negative_indicators)
# High-risk indicators
high_risk_keywords = [
"severe", "chest pain", "difficulty breathing", "emergency", "unbearable",
"pain level 8", "pain level 9", "pain level 10", "worsening", "worse",
"shortness of breath", "dizziness", "fainting", "swelling", "rapid heartbeat",
"irregular heartbeat", "nausea", "vomiting", "sweating", "fatigue severe"
]
# Low-risk indicators
low_risk_keywords = [
"no pain", "feeling better", "improving", "normal", "stable", "good",
"pain level 1", "pain level 2", "pain level 3", "comfortable", "well",
"no issues", "no problems", "managing well", "feeling fine", "recovering",
"all good", "fine", "great", "excellent", "ok", "okay", "everything is fine",
"everything is good", "nothing wrong", "no symptoms", "feeling good",
"better", "no concerns", "everything", "nothing", "none", "alright",
"doing well", "doing good", "all is well", "perfectly fine"
]
# Medium-risk indicators
medium_risk_keywords = [
"moderate", "occasional", "mild", "pain level 4", "pain level 5",
"pain level 6", "some discomfort", "manageable", "tolerable"
]
# Count keywords, but handle negative context
high_risk_count = 0
for keyword in high_risk_keywords:
if keyword in text_lower:
# Check if this symptom is mentioned in a negative context
# Look for negative words within 10 characters before the keyword
keyword_pos = text_lower.find(keyword)
context_before = text_lower[max(0, keyword_pos-20):keyword_pos]
if not any(neg in context_before for neg in negative_indicators):
high_risk_count += 1
low_risk_count = sum(1 for keyword in low_risk_keywords if keyword in text_lower)
medium_risk_count = sum(1 for keyword in medium_risk_keywords if keyword in text_lower)
# If negative statements are used with concerning keywords, treat as positive
if has_negative and any(keyword in text_lower for keyword in high_risk_keywords):
low_risk_count += 2 # Boost low risk for explicitly denying symptoms
if high_risk_count >= 2 or any(keyword in text_lower for keyword in ["severe", "emergency", "pain level 9", "pain level 10"]):
return "high"
elif low_risk_count >= 1 and high_risk_count == 0 and medium_risk_count == 0:
return "low"
elif low_risk_count >= 2 and high_risk_count == 0:
return "low"
elif medium_risk_count >= 1 and high_risk_count == 0 and low_risk_count == 0:
return "medium"
else:
return "medium"
# Text-to-Speech function
def text_to_speech(text):
try:
tts = gTTS(text=text, lang='en')
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
tts.save(tmp_file.name)
return tmp_file.name
except Exception as e:
st.error(f"Text-to-speech error: {e}")
return None
# Web-based speech recognition component
def web_speech_component(step_key):
speech_html = f"""
<div id="speech-container-{step_key}">
<button id="start-speech-{step_key}" onclick="startSpeech_{step_key}()" style="
background: linear-gradient(90deg, #ff6b6b, #ff8e8e);
color: white;
border: none;
padding: 10px 20px;
border-radius: 25px;
font-weight: 600;
cursor: pointer;
margin: 10px;
">🎤 Start Recording</button>
<button id="stop-speech-{step_key}" onclick="stopSpeech_{step_key}()" style="
background: #dc3545;
color: white;
border: none;
padding: 10px 20px;
border-radius: 25px;
font-weight: 600;
cursor: pointer;
margin: 10px;
display: none;
">⏹️ Stop Recording</button>
<div id="speech-status-{step_key}" style="margin: 10px; padding: 10px; background: #f8f9fa; border-radius: 5px; color: #333;">
Click "Start Recording" to begin speech recognition - text will automatically appear in your response
</div>
<button id="manual-paste-{step_key}" onclick="manualPasteToResponse_{step_key}()" style="
background: #28a745;
color: white;
border: none;
padding: 8px 16px;
border-radius: 20px;
font-weight: 600;
cursor: pointer;
margin: 10px;
display: none;
">📝 Paste Speech to Response</button>
<button id="debug-{step_key}" onclick="debugTextareas_{step_key}()" style="
background: #6c757d;
color: white;
border: none;
padding: 6px 12px;
border-radius: 15px;
font-size: 12px;
cursor: pointer;
margin: 10px;
">🔍 Debug</button>
</div>
<script>
let recognition_{step_key} = null;
let isRecording_{step_key} = false;
let fullTranscript_{step_key} = '';
function initSpeechRecognition_{step_key}() {{
if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {{
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
recognition_{step_key} = new SpeechRecognition();
recognition_{step_key}.continuous = true;
recognition_{step_key}.interimResults = true;
recognition_{step_key}.lang = 'en-US';
recognition_{step_key}.onstart = function() {{
document.getElementById('speech-status-{step_key}').innerHTML = '🎤 Listening... Speak now!';
document.getElementById('start-speech-{step_key}').style.display = 'none';
document.getElementById('stop-speech-{step_key}').style.display = 'inline-block';
isRecording_{step_key} = true;
fullTranscript_{step_key} = '';
}};
recognition_{step_key}.onresult = function(event) {{
let interimTranscript = '';
let finalTranscript = '';
for (let i = event.resultIndex; i < event.results.length; i++) {{
const transcript = event.results[i][0].transcript;
if (event.results[i].isFinal) {{
finalTranscript += transcript + ' ';
}} else {{
interimTranscript += transcript;
}}
}}
if (finalTranscript) {{
fullTranscript_{step_key} += finalTranscript;
// Only update main response after a pause to avoid too many updates
clearTimeout(window.updateTimeout_{step_key});
window.updateTimeout_{step_key} = setTimeout(function() {{
pasteToMainResponse_{step_key}();
}}, 2000);
}}
// Speech will be automatically pasted to main response area
}};
recognition_{step_key}.onerror = function(event) {{
document.getElementById('speech-status-{step_key}').innerHTML = '❌ Error: ' + event.error;
resetButtons_{step_key}();
}};
recognition_{step_key}.onend = function() {{
document.getElementById('speech-status-{step_key}').innerHTML = '✅ Recording stopped - Inserting text into response...';
resetButtons_{step_key}();
// Wait a bit longer for Streamlit to render the textarea fully
setTimeout(function() {{
console.log('=== FIRST ATTEMPT (delayed) ===');
pasteToMainResponse_{step_key}(0);
}}, 1500);
setTimeout(function() {{
console.log('=== SECOND ATTEMPT ===');
pasteToMainResponse_{step_key}(1);
}}, 3000);
setTimeout(function() {{
console.log('=== THIRD ATTEMPT ===');
pasteToMainResponse_{step_key}(2);
}}, 5000);
}};
}} else {{
document.getElementById('speech-status-{step_key}').innerHTML = '❌ Speech recognition not supported in this browser';
}}
}}
function startSpeech_{step_key}() {{
if (recognition_{step_key} && !isRecording_{step_key}) {{
recognition_{step_key}.start();
}} else {{
initSpeechRecognition_{step_key}();
if (recognition_{step_key}) {{
recognition_{step_key}.start();
}}
}}
}}
function stopSpeech_{step_key}() {{
if (recognition_{step_key} && isRecording_{step_key}) {{
recognition_{step_key}.stop();
}}
}}
function resetButtons_{step_key}() {{
document.getElementById('start-speech-{step_key}').style.display = 'inline-block';
document.getElementById('stop-speech-{step_key}').style.display = 'none';
isRecording_{step_key} = false;
}}
function pasteToMainResponse_{step_key}(retryCount = 0) {{
const speechText = fullTranscript_{step_key}.trim();
if (speechText) {{
let responseTextarea = null;
console.log('Searching for textarea, attempt:', retryCount + 1);
console.log('Speech text to paste:', speechText);
// Strategy 1: Look for Streamlit textareas specifically first
const streamlitTextareas = document.querySelectorAll('[data-testid="stTextArea"] textarea, [data-baseweb="textarea"] textarea, textarea[data-testid], .stTextArea textarea');
console.log('Streamlit textareas found:', streamlitTextareas.length);
for (let i = 0; i < streamlitTextareas.length; i++) {{
const textarea = streamlitTextareas[i];
const rect = textarea.getBoundingClientRect();
const isVisible = rect.width > 0 && rect.height > 0 &&
window.getComputedStyle(textarea).display !== 'none' &&
window.getComputedStyle(textarea).visibility !== 'hidden';
console.log(`Streamlit Textarea ${{i}}:`, {{
placeholder: textarea.placeholder,
visible: isVisible,
disabled: textarea.disabled,
readOnly: textarea.readOnly,
id: textarea.id,
className: textarea.className,
value: textarea.value.substring(0, 50)
}});
if (isVisible && !textarea.disabled && !textarea.readOnly && !textarea.id.includes('temp-speech-display')) {{
responseTextarea = textarea;
console.log('Found Streamlit textarea:', textarea);
break;
}}
}}
// Strategy 2: Look for textareas by placeholder if Streamlit method failed
if (!responseTextarea) {{
const allTextareas = document.querySelectorAll('textarea');
console.log('All textareas found:', allTextareas.length);
for (let i = 0; i < allTextareas.length; i++) {{
const textarea = allTextareas[i];
const rect = textarea.getBoundingClientRect();
const isVisible = rect.width > 0 && rect.height > 0 &&
window.getComputedStyle(textarea).display !== 'none' &&
window.getComputedStyle(textarea).visibility !== 'hidden';
console.log(`All Textarea ${{i}}:`, {{
placeholder: textarea.placeholder,
visible: isVisible,
disabled: textarea.disabled,
readOnly: textarea.readOnly,
id: textarea.id,
value: textarea.value.substring(0, 50)
}});
// Skip our temporary display and only look for main response textareas
if (isVisible && !textarea.disabled && !textarea.readOnly &&
!textarea.id.includes('temp-speech-display') &&
!textarea.id.includes('speech-container')) {{
const placeholder = textarea.placeholder.toLowerCase();
if (placeholder.includes('describe') ||
placeholder.includes('cardiac') ||
placeholder.includes('breathing') ||
placeholder.includes('medication') ||
placeholder.includes('activity') ||
placeholder.includes('symptoms') ||
placeholder.includes('pain') ||
placeholder.includes('chest')) {{
responseTextarea = textarea;
console.log('Found matching textarea by placeholder:', placeholder);
break;
}}
}}
}}
}}
// Strategy 3: Get the largest visible, writable textarea (excluding temp displays)
if (!responseTextarea) {{
const allTextareas = document.querySelectorAll('textarea');
let largestArea = 0;
for (let textarea of allTextareas) {{
const rect = textarea.getBoundingClientRect();
const area = rect.width * rect.height;
const isVisible = area > 0 &&
window.getComputedStyle(textarea).display !== 'none' &&
window.getComputedStyle(textarea).visibility !== 'hidden';
if (isVisible && !textarea.disabled && !textarea.readOnly &&
!textarea.id.includes('temp-speech-display') &&
area > largestArea) {{
largestArea = area;
responseTextarea = textarea;
console.log('Found largest writable textarea with area:', area);
}}
}}
}}
// Strategy 3: Use MutationObserver to wait for textarea to appear
if (!responseTextarea && retryCount < 2) {{
console.log('Textarea not found, waiting for DOM changes...');
const observer = new MutationObserver(function(mutations) {{
mutations.forEach(function(mutation) {{
if (mutation.type === 'childList') {{
observer.disconnect();
setTimeout(() => {{
pasteToMainResponse_{step_key}(retryCount + 1);
}}, 500);
}}
}});
}});
observer.observe(document.body, {{
childList: true,
subtree: true
}});
// Disconnect observer after 2 seconds
setTimeout(() => {{
observer.disconnect();
if (retryCount < 2) {{
pasteToMainResponse_{step_key}(retryCount + 1);
}}
}}, 2000);
document.getElementById('speech-status-{step_key}').innerHTML = `🔄 Waiting for response area to load... (attempt ${{retryCount + 1}}/3)`;
return;
}}
if (responseTextarea) {{
console.log('Attempting to paste into textarea:', responseTextarea);
// Clear existing value first
responseTextarea.value = '';
responseTextarea.focus();
// Set the value using multiple methods
responseTextarea.value = speechText;
// For Streamlit textareas, we need to trigger React events
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
nativeInputValueSetter.call(responseTextarea, speechText);
// Create and dispatch a proper input event for React
const inputEvent = new Event('input', {{ bubbles: true }});
Object.defineProperty(inputEvent, 'target', {{ writable: false, value: responseTextarea }});
responseTextarea.dispatchEvent(inputEvent);
// Also dispatch change event
const changeEvent = new Event('change', {{ bubbles: true }});
Object.defineProperty(changeEvent, 'target', {{ writable: false, value: responseTextarea }});
responseTextarea.dispatchEvent(changeEvent);
// Try using document.execCommand as additional fallback
responseTextarea.select();
if (document.execCommand) {{
document.execCommand('selectAll', false, null);
document.execCommand('insertText', false, speechText);
}}
// Trigger all possible events that Streamlit might listen to
const eventTypes = ['focus', 'input', 'change', 'keyup', 'keydown', 'blur', 'paste'];
eventTypes.forEach(eventType => {{
const event = new Event(eventType, {{ bubbles: true, cancelable: true }});
responseTextarea.dispatchEvent(event);
}});
// Try InputEvent with more specific properties
try {{
const inputEvent = new InputEvent('input', {{
bubbles: true,
cancelable: true,
data: speechText,
inputType: 'insertText'
}});
responseTextarea.dispatchEvent(inputEvent);
}} catch (e) {{
console.log('InputEvent not supported, using basic Event');
}}
// Force focus and blur cycle multiple times
setTimeout(() => {{
responseTextarea.focus();
responseTextarea.dispatchEvent(new Event('input', {{ bubbles: true }}));
responseTextarea.dispatchEvent(new Event('change', {{ bubbles: true }}));
}}, 100);
setTimeout(() => {{
responseTextarea.blur();
responseTextarea.focus();
responseTextarea.dispatchEvent(new Event('input', {{ bubbles: true }}));
}}, 200);
// Verify the value was set
setTimeout(() => {{
if (responseTextarea.value === speechText) {{
console.log('SUCCESS: Text value confirmed in textarea');
document.getElementById('speech-status-{step_key}').innerHTML = '✅ Text successfully inserted into response area!';
document.getElementById('manual-paste-{step_key}').style.display = 'none';
// Hide temporary display if it exists
const tempDisplay = document.getElementById('temp-speech-display-{step_key}');
if (tempDisplay) {{
tempDisplay.style.display = 'none';
}}
// Scroll to the response area
responseTextarea.scrollIntoView({{ behavior: 'smooth', block: 'center' }});
}} else {{
console.log('WARNING: Text value not confirmed, showing manual options');
document.getElementById('speech-status-{step_key}').innerHTML = '⚠️ Text may not have been inserted. Use manual paste below.';
document.getElementById('manual-paste-{step_key}').style.display = 'inline-block';
}}
}}, 500);
console.log('Speech text insertion completed');
}} else {{
console.log('Failed to find any suitable textarea after all attempts');
console.log('Available textareas:', document.querySelectorAll('textarea'));
// Show manual paste button and copy to clipboard as fallback
document.getElementById('speech-status-{step_key}').innerHTML = '⚠️ <strong>Manual Action Needed:</strong> Click the green "Paste Speech to Response" button below, or copy from the text box.';
document.getElementById('manual-paste-{step_key}').style.display = 'inline-block';
// Create a temporary text display if it doesn't exist
let tempDisplay = document.getElementById('temp-speech-display-{step_key}');
if (!tempDisplay) {{
tempDisplay = document.createElement('textarea');
tempDisplay.id = 'temp-speech-display-{step_key}';
tempDisplay.style.cssText = `
width: 100%;
height: 120px;
margin: 10px 0;
padding: 15px;
border: 2px solid #ff6b6b;
border-radius: 5px;
background: #fff3f3;
font-size: 14px;
color: #333;
font-family: Arial, sans-serif;
resize: vertical;
box-sizing: border-box;
`;
tempDisplay.placeholder = 'Your speech text will appear here - copy and paste it into the response area below';
tempDisplay.readOnly = false; // Make it editable so users can copy
document.getElementById('speech-container-{step_key}').appendChild(tempDisplay);
}}
tempDisplay.value = speechText;
tempDisplay.style.display = 'block';
// Select all text for easy copying
tempDisplay.focus();
tempDisplay.select();
// Copy to clipboard as backup
if (navigator.clipboard) {{
navigator.clipboard.writeText(speechText).then(() => {{
console.log('Text copied to clipboard as fallback');
document.getElementById('speech-status-{step_key}').innerHTML = '⚠️ Text copied to clipboard and shown below. Paste manually into response area.';
}}).catch(e => {{
console.log('Clipboard copy failed:', e);
document.getElementById('speech-status-{step_key}').innerHTML = '⚠️ Copy the text from the box below and paste into response area.';
}});
}} else {{
document.getElementById('speech-status-{step_key}').innerHTML = '⚠️ Copy the text from the box below and paste into response area.';
}}
}}
}} else {{
console.log('No speech text to paste');
}}
}}
function debugTextareas_{step_key}() {{
console.log('=== TEXTAREA DEBUG INFO ===');
// Check for Streamlit-specific textareas first
const streamlitTextareas = document.querySelectorAll('[data-testid="stTextArea"] textarea, [data-baseweb="textarea"] textarea, textarea[data-testid], .stTextArea textarea');
console.log('Streamlit textareas found:', streamlitTextareas.length);
streamlitTextareas.forEach((textarea, index) => {{
const rect = textarea.getBoundingClientRect();
const style = window.getComputedStyle(textarea);
console.log(`Streamlit Textarea ${{index}}:`, {{
placeholder: textarea.placeholder,
value: textarea.value.substring(0, 30) + '...',
visible: rect.width > 0 && rect.height > 0 && style.display !== 'none',
display: style.display,
visibility: style.visibility,
disabled: textarea.disabled,