-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatbot_api_proper.py
More file actions
1734 lines (1633 loc) · 80 KB
/
chatbot_api_proper.py
File metadata and controls
1734 lines (1633 loc) · 80 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
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uuid
from chatbot_interface import ChatbotInterface
from data_preprocessing_fixed import DataPreprocessorFixed
# ModelTrainer is defined locally in this file
import time
import difflib
from config import MODELS_DIR, TIME_SLOTS, APPOINTMENT_DAYS_AHEAD, BOOKING_ARRIVAL_MINUTES
app = FastAPI(title="Healthcare Chatbot API")
# Allow CORS for all origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize the SAME chatbot as CLI
data_preprocessor = DataPreprocessorFixed()
data_preprocessor.initialize_all(use_augmented=False, use_ai_augmented=False, use_safe_augmented=True)
# Load the enhanced model from Hugging Face
import joblib
import os
from huggingface_hub import hf_hub_download
print("[DEBUG] Downloading model files from Hugging Face")
# Download model files from Hugging Face
try:
model_path = hf_hub_download(
repo_id="hagersobhy/enhanced-chatbot-model",
filename="enhanced_ai_augmented_model.joblib"
)
encoder_path = hf_hub_download(
repo_id="hagersobhy/enhanced-chatbot-model",
filename="enhanced_ai_augmented_label_encoder.joblib"
)
print(f"[DEBUG] Model downloaded to: {model_path}")
print(f"[DEBUG] Encoder downloaded to: {encoder_path}")
except Exception as e:
print(f"[DEBUG] Error downloading from Hugging Face: {e}")
raise SystemExit("❌ Failed to download model files from Hugging Face. Exiting.")
# Debug: Print model file sizes
try:
print("[DEBUG] Model file size:", os.path.getsize(model_path), "bytes")
print("[DEBUG] Encoder file size:", os.path.getsize(encoder_path), "bytes")
except Exception as e:
print("[DEBUG] Error checking model file sizes:", e)
try:
model = joblib.load(model_path)
label_encoder = joblib.load(encoder_path)
print("[DEBUG] Model and encoder loaded successfully!")
except Exception as e:
print(f"❌ Error loading enhanced model: {e}")
raise SystemExit("❌ Failed to load enhanced model. Exiting.")
# Create model trainer
class ModelTrainer:
def __init__(self, model, label_encoder):
self.clf = model
self.label_encoder = label_encoder
model_trainer = ModelTrainer(model, label_encoder)
# Session storage
sessions = {}
class StartSessionRequest(BaseModel):
pass
class StartSessionResponse(BaseModel):
session_id: str
prompt: str
options: list
state: str
class SendMessageRequest(BaseModel):
session_id: str
user_input: str
class SendMessageResponse(BaseModel):
prompt: str
options: list
state: str
class APIChatbotInterface(ChatbotInterface):
"""Extended ChatbotInterface that supports API mode"""
def __init__(self, data_preprocessor, model_trainer):
super().__init__(data_preprocessor, model_trainer)
self.api_mode = True
self.current_state = "initializing"
self.last_prompt = ""
self.last_options = []
# --- New for follow-up logic ---
self.denied_symptoms = set()
self.previously_asked_symptoms = set()
self.follow_up_questions = []
self.follow_up_round = 0
self.max_follow_up_rounds = 2
self.diagnosis_context = {} # Store context for diagnosis session
def api_get_info(self):
"""API version of getInfo - returns structured response"""
self.current_state = "awaiting_name"
self.last_prompt = "Your Name? ->"
self.last_options = []
return {
'prompt': self.last_prompt,
'options': self.last_options,
'state': self.current_state
}
def api_handle_name(self, name):
"""API version of name handling"""
if name.strip().lower() == "undo":
return {
'prompt': "Undo: Please enter your name again.\nYour Name? ->",
'options': [],
'state': "awaiting_name"
}
name = name.strip()
if not name:
self.name = "User"
prompt = "Hello! 👋\nPlease enter your location (city or country):"
else:
self.name = name
prompt = f"Hello {self.name}! 👋\nPlease enter your location (city or country):"
self.current_state = "awaiting_location"
return {
'prompt': prompt,
'options': [],
'state': self.current_state
}
def api_handle_location(self, location):
"""API version of location handling"""
if location.strip().lower() == "undo":
return {
'prompt': "Let's try entering your location again.\nPlease enter your location (city or country):",
'options': [],
'state': "awaiting_location"
}
location = location.strip()
if not location:
return {
'prompt': "Location cannot be empty. Please try again.\nPlease enter your location (city or country):",
'options': [],
'state': "awaiting_location"
}
self.user_location = location
self.current_state = "main_menu"
return self.api_get_main_menu()
def api_get_main_menu(self):
"""API version of main menu"""
prompt = ("What would you like to do?\n"
"1) Diagnosis (disease prediction)\n"
"2) Find a doctor\n"
"3) Find a hospital\n"
"4) Book hospital appointment\n"
"5) I am done / Exit\n"
"(Type 'undo' to go back and enter your location.)\n"
"Enter 1, 2, 3, 4, or 5:")
options = ["1", "2", "3", "4", "5", "undo"]
return {
'prompt': prompt,
'options': options,
'state': "main_menu"
}
def api_handle_main_menu(self, choice):
"""API version of main menu handling"""
choice = choice.strip().lower()
if choice == "undo":
self.current_state = "awaiting_location"
return {
'prompt': "Please enter your location (city or country):",
'options': [],
'state': "awaiting_location"
}
if choice not in ["1", "2", "3", "4", "5"]:
return {
'prompt': "Invalid choice. Please enter 1, 2, 3, 4, or 5.\n" + self.api_get_main_menu()['prompt'],
'options': ["1", "2", "3", "4", "5", "undo"],
'state': "main_menu"
}
if choice == "1":
self.current_state = "diagnosis_method"
prompt = ("Please choose input method:\n"
"1) Traditional (one symptom at a time)\n"
"2) Free text (write all symptoms in one sentence)\n"
"Enter 1 or 2:")
options = ["1", "2", "undo"]
elif choice == "2":
self.current_state = "doctor_search"
prompt = "Enter the medical specialty you are looking for (e.g., Cardiology, Neurology, Dermatology):"
options = ["undo"]
elif choice == "3":
self.current_state = "hospital_search"
prompt = "Enter the city or country you are looking for hospitals in:"
options = ["undo"]
elif choice == "4":
# If user_location is set, skip location prompt and go directly to booking_location handler
if getattr(self, 'user_location', None):
self.current_state = 'booking_location'
return self.api_handle_booking_location(self.user_location)
else:
self.current_state = "booking_location"
prompt = "Enter the city or country you are looking for hospitals in:"
options = ["undo"]
return {
'prompt': prompt,
'options': options,
'state': self.current_state
}
elif choice == "5":
self.current_state = "exit_confirm"
prompt = "Are you sure you want to exit? (yes/y or no/n):"
options = ["yes", "y", "no", "n", "undo"]
if choice not in ["4"]:
return {
'prompt': prompt,
'options': options,
'state': self.current_state
}
def api_handle_diagnosis_method(self, method):
"""API version of diagnosis method handling"""
method = method.strip().lower()
if method == "undo":
return self.api_get_main_menu()
if method not in ["1", "2"]:
return {
'prompt': ("Invalid choice. Please enter 1 or 2.\n"
"Please choose input method:\n"
"1) Traditional (one symptom at a time)\n"
"2) Free text (write all symptoms in one sentence)\n"
"Enter 1 or 2:"),
'options': ["1", "2", "undo"],
'state': "diagnosis_method"
}
self.diagnosis_method = "traditional" if method == "1" else "free_text"
self.symptoms = []
print(f"DEBUG: Method chosen: {method}")
print(f"DEBUG: Diagnosis method: {self.diagnosis_method}")
if method == "1":
self.current_state = "diagnosis_symptom"
prompt = "Enter the symptom you are experiencing ->"
options = ["undo"]
else:
self.current_state = "diagnosis_free_text"
prompt = ("Please write all the symptoms you are experiencing in one sentence "
"(e.g., I have headache and fever and muscle pain):")
options = ["undo"]
print(f"DEBUG: Current state set to: {self.current_state}")
return {
'prompt': prompt,
'options': options,
'state': self.current_state
}
def api_handle_symptom_input(self, symptom_input):
print("DEBUG: api_handle_symptom_input called")
"""API version of symptom input handling"""
if symptom_input.strip().lower() == "undo":
self.current_state = "diagnosis_method"
return {
'prompt': "Please choose input method:\n1) Traditional (one symptom at a time)\n2) Free text (write all symptoms in one sentence)\nEnter 1 or 2:",
'options': ["1", "2", "undo"],
'state': self.current_state
}
# Use the EXACT same logic as CLI
corrected = self.handle_single_symptom_input(symptom_input)
if len(corrected) == 1:
self.symptoms = corrected
self.current_state = "diagnosis_review"
prompt = f"Here are the symptoms I have: {', '.join(self.symptoms)}\nWould you like to change this symptom? (yes/y or no/n)\n-> "
options = ["yes", "y", "no", "n", "undo"]
elif len(corrected) > 1:
self.current_state = "symptom_clarification"
self.symptom_clarification_options = corrected # Store options for clarification step
prompt = (f"You entered '{symptom_input}'. Please specify the type(s):\n" +
'\n'.join([f" {i+1}) {opt}" for i, opt in enumerate(corrected)]) +
"\n 0) None of these / skip\nSelect all that apply (comma-separated numbers, e.g. 1,3,5): ")
options = [str(i+1) for i in range(len(corrected))] + ["0", "undo"]
else:
self.current_state = "diagnosis_symptom"
prompt = "Symptom not recognized. Please try again.\nEnter the symptom you are experiencing ->"
options = ["undo"]
return {
'prompt': prompt,
'options': options,
'state': self.current_state,
'symptoms': corrected
}
def api_handle_diagnosis_review(self, choice):
"""API version of diagnosis review handling"""
choice = choice.strip().lower()
if choice in ["yes", "y"]:
self.current_state = "diagnosis_symptom_edit"
prompt = "Enter the new symptom (or type 'undo' to cancel):"
options = ["undo"]
elif choice in ["no", "n"]:
self.current_state = "diagnosis_days"
prompt = "Okay. For how many days have you had these symptoms? : "
options = ["undo"]
else:
prompt = f"Please enter yes/y or no/n.\nHere are the symptoms I have: {', '.join(self.symptoms)}\nWould you like to change this symptom? (yes/y or no/n)\n-> "
options = ["yes", "y", "no", "n"]
return {
'prompt': prompt,
'options': options,
'state': self.current_state
}
def api_handle_days_input(self, days_input):
"""API version of days input handling"""
try:
num_days = int(days_input)
self.days = num_days
self.current_state = "diagnosis_related"
# Get related symptoms using EXACT same logic as CLI
relevant_symptoms = self.get_medical_relevant_symptoms(self.symptoms[0])
if relevant_symptoms:
rels = [symptom for symptom in relevant_symptoms if symptom not in self.symptoms]
if rels:
formatted_symptom = self._format_symptom_name(rels[0])
prompt = f"Are you experiencing any of these related symptoms?\n{formatted_symptom}? (yes/y or no/n or back): "
options = ["yes", "y", "no", "n", "back"]
else:
return self.api_make_diagnosis()
else:
return self.api_make_diagnosis()
except ValueError:
prompt = "Please enter a valid number for days:"
options = []
return {
'prompt': prompt,
'options': options,
'state': self.current_state
}
def api_make_diagnosis(self):
"""API version of diagnosis - uses EXACT same logic as CLI, now with follow-up escalation"""
denied_symptoms = getattr(self, 'denied_symptoms', set())
previously_asked_symptoms = getattr(self, 'previously_asked_symptoms', set())
follow_up_round = getattr(self, 'follow_up_round', 0)
max_follow_up_rounds = getattr(self, 'max_follow_up_rounds', 2)
symptoms = self.symptoms
# Run prediction
predicted_disease, confidence, top_3_diseases, top_3_confidences, should_make_prediction, follow_up_questions, safety_warnings, risk_level, denied_symptoms = self.predict_disease_with_medical_validation(
symptoms, denied_symptoms
)
conf_str = f"{confidence * 100:.1f}%" if confidence is not None else "Unknown"
# Store context for follow-up
self.diagnosis_context = {
'predicted_disease': predicted_disease,
'confidence': confidence,
'top_3_diseases': top_3_diseases,
'top_3_confidences': top_3_confidences,
'should_make_prediction': should_make_prediction,
'follow_up_questions': follow_up_questions,
'safety_warnings': safety_warnings,
'risk_level': risk_level,
'denied_symptoms': denied_symptoms,
'previously_asked_symptoms': previously_asked_symptoms,
'follow_up_round': follow_up_round,
'symptoms': symptoms.copy(),
}
# If follow-up questions are needed and we haven't hit the max rounds, ask them
if follow_up_questions and follow_up_round < max_follow_up_rounds:
self.current_state = "diagnosis_follow_up"
self.follow_up_questions = follow_up_questions
self.denied_symptoms = denied_symptoms
self.previously_asked_symptoms = previously_asked_symptoms
self.follow_up_round = follow_up_round
# Ask the first follow-up question
question = follow_up_questions[0]
formatted = question.replace("Critical: ", "").replace("Important: ", "")
prompt = f"I need more information for a reliable diagnosis.\nCurrent symptoms: {', '.join(self.symptoms)}\nPotential concern: {predicted_disease} ({conf_str} confidence)\n\nPlease answer:\n{question}? (yes/y or no/n)"
return {
'prompt': prompt,
'options': ["yes", "y", "no", "n", "undo"],
'state': self.current_state,
'question': question,
'symptoms': self.symptoms
}
# --- EMERGENCY LOGIC ---
specialization = self.disease_to_specialty.get(predicted_disease, None)
if specialization == "Emergency":
user_location = getattr(self, 'user_location', None)
emergency_number = self._get_emergency_numbers_by_location(user_location)
filtered_hospitals, all_hospitals = self.get_hospitals_by_location(user_location) if user_location else ([], [])
description = self.data_preprocessor.description_list.get(predicted_disease, "")
precautions = self.data_preprocessor.precautionDictionary.get(predicted_disease, [])
# --- STRUCTURED DIAGNOSIS OBJECT ---
diagnosis_obj = {
'disease': predicted_disease,
'confidence': confidence,
'description': description,
'precautions': precautions,
'emergency': True,
'emergency_number': emergency_number,
'hospitals': filtered_hospitals,
'top_3': list(zip(top_3_diseases, top_3_confidences)),
'doctors': [], # No doctor recommendations for emergency
'risk_level': risk_level,
'safety_warnings': safety_warnings,
'symptoms': symptoms,
}
output = []
output.append(f"\n🚨 EMERGENCY ALERT: {predicted_disease} detected!")
output.append(f"⚠️ This is a medical emergency requiring immediate hospital care.")
output.append(f"\n🩺 Diagnosis: {predicted_disease}")
output.append(f"Confidence: {conf_str}")
if description:
output.append(f"\n📋 Description: {description}")
if precautions:
output.append("\n💊 Take the following precautions:")
for i, precaution in enumerate(precautions, 1):
if precaution.strip():
output.append(f" {i}) {precaution}")
output.append(f"\n🏥 Recommending nearby hospitals for emergency treatment:")
if filtered_hospitals:
output.append(f"\n🏥 Emergency Hospitals in {user_location}:")
for i, hosp in enumerate(filtered_hospitals[:5], 1):
hosp_lines = [
f"{i}. {hosp.get('name', 'Unknown')}",
f" 📍 Location: {hosp.get('city', 'N/A')}, {hosp.get('country', 'N/A')}",
f" 📞 Emergency Phone: {hosp.get('phone', 'N/A')}",
f" ⭐ Rating: {hosp.get('rate', 'N/A')}/5",
f" 🏗️ Established: {hosp.get('Established', 'N/A')}",
]
if hosp.get('Url'):
hosp_lines.append(f" 🌐 Profile: {hosp.get('Url')}")
hosp_lines.append("---------------------------")
output.extend(hosp_lines)
else:
output.append(f"\n⚠️ No hospitals found in {user_location}")
output.append(f"\n🚨 IMMEDIATE ACTION REQUIRED:")
output.append(f"📞 Call emergency services: {emergency_number}")
output.append("1. Go to the nearest hospital emergency department")
output.append("2. Do not delay seeking medical attention")
output.append("3. Bring someone with you if possible")
output.append("\n⚠️ Disclaimer: This is for informational purposes only. Please consult a healthcare professional for proper diagnosis.")
main_menu_prompt = ("\n\nWhat would you like to do?\n"
"1) Diagnosis (disease prediction)\n"
"2) Find a doctor\n"
"3) Find a hospital\n"
"4) Book hospital appointment\n"
"5) I am done / Exit\n"
"(Type 'undo' to go back and enter your location.)\n"
"Enter 1, 2, 3, 4, or 5:")
full_prompt = '\n'.join(output) + main_menu_prompt
self.current_state = "main_menu"
self.denied_symptoms = set()
self.previously_asked_symptoms = set()
self.follow_up_questions = []
self.follow_up_round = 0
self.diagnosis_context = {}
return {
'prompt': full_prompt,
'options': ["1", "2", "3", "4", "5", "undo"],
'state': self.current_state,
'diagnosis': diagnosis_obj
}
# --- END EMERGENCY LOGIC ---
# Otherwise, return the diagnosis (non-emergency)
description = self.data_preprocessor.description_list.get(predicted_disease, "")
precautions = self.data_preprocessor.precautionDictionary.get(predicted_disease, [])
doctor_recommendations = self._get_doctor_recommendations_data(predicted_disease)
# --- STRUCTURED DIAGNOSIS OBJECT ---
diagnosis_obj = {
'disease': predicted_disease,
'confidence': confidence,
'description': description,
'precautions': precautions,
'emergency': False,
'emergency_number': None,
'hospitals': [],
'top_3': list(zip(top_3_diseases, top_3_confidences)),
'doctors': doctor_recommendations,
'risk_level': risk_level,
'safety_warnings': safety_warnings,
'symptoms': symptoms,
}
output = []
output.append(f"\n🩺 Diagnosis: {predicted_disease}")
output.append(f"Confidence: {conf_str}")
if description:
output.append(f"\n📋 Description: {description}")
if precautions:
output.append("\n💊 Take the following precautions:")
for i, precaution in enumerate(precautions, 1):
if precaution.strip():
output.append(f" {i+1}) {precaution}")
output.append("\n⚠️ Disclaimer: This is for informational purposes only. Please consult a healthcare professional for proper diagnosis.")
doctor_lines = []
if doctor_recommendations:
doctor_lines.append("\n🩺 Recommended Doctors:")
for idx, doc in enumerate(doctor_recommendations, 1):
line = f"{idx}. Name: {doc['name']}\n Specialization: {doc['specialization']}\n Location: {doc['city']}, {doc['country']}\n Phone: {doc['phone']}\n Rating: {doc['rate']}"
if doc.get('gender'):
line += f"\n Gender: {doc['gender']}"
if doc.get('img_url'):
line += f"\n Image: {doc['img_url']}"
if doc.get('profile_url'):
line += f"\n Profile: {doc['profile_url']}"
doctor_lines.append(line)
else:
doctor_lines.append("\n⚠️ No doctor recommendations available for this diagnosis and location.")
main_menu_prompt = ("\n\nWhat would you like to do?\n"
"1) Diagnosis (disease prediction)\n"
"2) Find a doctor\n"
"3) Find a hospital\n"
"4) Book hospital appointment\n"
"5) I am done / Exit\n"
"(Type 'undo' to go back and enter your location.)\n"
"Enter 1, 2, 3, 4, or 5:")
full_prompt = '\n'.join(output + doctor_lines) + main_menu_prompt
self.current_state = "main_menu"
self.denied_symptoms = set()
self.previously_asked_symptoms = set()
self.follow_up_questions = []
self.follow_up_round = 0
self.diagnosis_context = {}
return {
'prompt': full_prompt,
'options': ["1", "2", "3", "4", "5", "undo"],
'state': self.current_state,
'diagnosis': diagnosis_obj
}
def api_handle_symptom_edit(self, symptom_input):
"""API version of symptom editing"""
print(f"DEBUG: api_handle_symptom_edit called with input: '{symptom_input}'")
print(f"DEBUG: Current symptoms: {self.symptoms}")
if symptom_input.strip().lower() == "undo":
self.current_state = "diagnosis_review"
prompt = f"Edit cancelled. Keeping the original symptom.\nHere are the symptoms I have: {', '.join(self.symptoms)}\nWould you like to change this symptom? (yes/y or no/n)\n-> "
return {
'prompt': prompt,
'options': ["yes", "y", "no", "n"],
'state': self.current_state
}
# Use the EXACT same logic as CLI
corrected = self.handle_single_symptom_input(symptom_input)
print(f"DEBUG: handle_single_symptom_input returned: {corrected}")
if len(corrected) == 1:
self.symptoms = corrected
self.current_state = "diagnosis_review"
prompt = f"Here are the symptoms I have: {', '.join(self.symptoms)}\nWould you like to change this symptom? (yes/y or no/n)\n-> "
return {
'prompt': prompt,
'options': ["yes", "y", "no", "n"],
'state': self.current_state
}
elif len(corrected) > 1:
self.current_state = "symptom_clarification"
prompt = (f"You entered '{symptom_input}'. Please specify the type(s):\n" +
'\n'.join([f" {i+1}) {opt}" for i, opt in enumerate(corrected)]) +
"\n 0) None of these / skip\nSelect all that apply (comma-separated numbers, e.g. 1,3,5): ")
options = [str(i+1) for i in range(len(corrected))] + ["0"]
return {
'prompt': prompt,
'options': options,
'state': self.current_state
}
else:
# Keep the same state but provide clear error message
prompt = "Symptom not recognized. Please try again.\nEnter the new symptom (or type 'undo' to cancel):"
return {
'prompt': prompt,
'options': ["undo"],
'state': "diagnosis_symptom_edit" # Explicitly set the state
}
def api_handle_free_text_input(self, user_text):
"""API version of free text symptom input handling"""
# Tokenize and clean input
leading_phrases = [
r'^i have ', r'^i am suffering from ', r'^i am having ', r'^i feel ', r'^i am ', r"^i'm ", r'^i got ', r'^i\s+',
r'^my ', r'^having ', r'^suffering from ', r'^experiencing ', r'^with ', r'^and ', r'^, ', r'^\s+'
]
import re
tokens = re.split(r',| and | و | و|,|\band\b', user_text)
cleaned_tokens = []
for t in tokens:
t = t.strip().lower()
for phrase in leading_phrases:
t = re.sub(phrase, '', t)
t = t.strip()
if t:
t = t.replace(' ', '_')
cleaned_tokens.append(t)
# Now, for each token, check for ambiguity
self.free_text_tokens = cleaned_tokens.copy() # Store for clarification
self.free_text_symptom_results = [] # Will store (token, options) pairs
self.free_text_selected_symptoms = [] # Final selected symptoms
for token in cleaned_tokens:
options = self.handle_single_symptom_input(token)
if len(options) > 1:
# Ambiguous, need clarification
self.current_state = 'free_text_symptom_clarification'
self.free_text_clarify_token = token
self.free_text_clarify_options = options
prompt = (f"You entered '{token}'. Please specify the type(s):\n" +
'\n'.join([f" {i+1}) {opt}" for i, opt in enumerate(options)]) +
"\n 0) None of these / skip\nSelect all that apply (comma-separated numbers, e.g. 1,3,5): ")
options_list = [str(i+1) for i in range(len(options))] + ["0", "undo"]
return {
'prompt': prompt,
'options': options_list,
'state': self.current_state
}
elif len(options) == 1:
self.free_text_selected_symptoms.append(options[0])
# else: skip unrecognized
# If no ambiguities, proceed to review
self.symptoms = self.free_text_selected_symptoms
self.current_state = "free_text_review"
prompt = f"\nHere are the symptoms I have: {', '.join([self._format_symptom_name(s) for s in self.symptoms])}\nWhat would you like to do?\n1) Add a symptom\n2) Remove a symptom\n3) Edit all symptoms (re-enter full list)\n4) Continue with current symptoms"
return {
'prompt': prompt,
'options': ["1", "2", "3", "4", "undo"],
'state': self.current_state
}
def api_handle_free_text_symptom_clarification(self, user_input):
"""Handle clarification for ambiguous symptoms in free text mode"""
user_input = user_input.strip()
if user_input.lower() == "undo":
self.current_state = "free_text_review"
prompt = f"\nHere are the symptoms I have: {', '.join([self._format_symptom_name(s) for s in self.free_text_selected_symptoms])}\nWhat would you like to do?\n1) Add a symptom\n2) Remove a symptom\n3) Edit all symptoms (re-enter full list)\n4) Continue with current symptoms"
return {
'prompt': prompt,
'options': ["1", "2", "3", "4", "undo"],
'state': self.current_state
}
selected = [x.strip() for x in user_input.split(',') if x.strip().isdigit()]
indices = [int(x) for x in selected if x != "0"]
options = getattr(self, 'free_text_clarify_options', [])
if options and indices:
for idx in indices:
if 1 <= idx <= len(options):
self.free_text_selected_symptoms.append(options[idx-1])
# Remove the clarified token from the list and continue with the rest
if hasattr(self, 'free_text_tokens') and self.free_text_clarify_token in self.free_text_tokens:
self.free_text_tokens.remove(self.free_text_clarify_token)
# Now process the next token, if any
while self.free_text_tokens:
token = self.free_text_tokens.pop(0)
opts = self.handle_single_symptom_input(token)
if len(opts) > 1:
# Need clarification for this token
self.current_state = 'free_text_symptom_clarification'
self.free_text_clarify_token = token
self.free_text_clarify_options = opts
prompt = (f"You entered '{token}'. Please specify the type(s):\n" +
'\n'.join([f" {i+1}) {opt}" for i, opt in enumerate(opts)]) +
"\n 0) None of these / skip\nSelect all that apply (comma-separated numbers, e.g. 1,3,5): ")
options_list = [str(i+1) for i in range(len(opts))] + ["0", "undo"]
return {
'prompt': prompt,
'options': options_list,
'state': self.current_state
}
elif len(opts) == 1:
self.free_text_selected_symptoms.append(opts[0])
# else: skip unrecognized
# If no more tokens, proceed to review
self.symptoms = self.free_text_selected_symptoms
self.current_state = "free_text_review"
prompt = f"\nHere are the symptoms I have: {', '.join([self._format_symptom_name(s) for s in self.symptoms])}\nWhat would you like to do?\n1) Add a symptom\n2) Remove a symptom\n3) Edit all symptoms (re-enter full list)\n4) Continue with current symptoms"
return {
'prompt': prompt,
'options': ["1", "2", "3", "4", "undo"],
'state': self.current_state
}
def api_handle_free_text_review(self, choice):
"""API version of free text review menu handling"""
if choice == "1":
self.current_state = "free_text_add_symptom"
return {
'prompt': "Enter the symptom you want to add:",
'options': ["undo"],
'state': self.current_state
}
elif choice == "2":
if len(self.symptoms) == 1:
return {
'prompt': "You only have one symptom. You cannot remove it.\n" + self.api_get_free_text_review_menu()['prompt'],
'options': ["1", "2", "3", "4", "undo"],
'state': self.current_state
}
self.current_state = "free_text_remove_symptom"
formatted_symptoms = [f"{i}) {self._format_symptom_name(s)}" for i, s in enumerate(self.symptoms, 1)]
prompt = "Which symptom would you like to remove?\n" + "\n".join(formatted_symptoms)
return {
'prompt': prompt,
'options': [str(i) for i in range(1, len(self.symptoms) + 1)] + ["undo"],
'state': self.current_state
}
elif choice == "3":
self.current_state = "free_text_edit_all"
return {
'prompt': "Enter the full, final list of symptoms separated by commas (or type 'undo' to go back):",
'options': ["undo"],
'state': self.current_state
}
elif choice == "4":
self.current_state = "diagnosis_days"
return {
'prompt': "Okay. For how many days have you had these symptoms? : ",
'options': ["undo"],
'state': self.current_state
}
else:
return {
'prompt': "Invalid choice. Please enter 1, 2, 3, or 4.\n" + self.api_get_free_text_review_menu()['prompt'],
'options': ["1", "2", "3", "4", "undo"],
'state': self.current_state
}
def api_handle_free_text_add_symptom(self, new_symptom):
"""Handle adding a symptom in free text review mode, with clarification if ambiguous."""
new_symptom = new_symptom.strip()
if new_symptom.lower() == "undo":
self.current_state = "free_text_review"
return self.api_get_free_text_review_menu()
# Tokenize and clean input
import re
leading_phrases = [
r'^i have ', r'^i am suffering from ', r'^i am having ', r'^i feel ', r'^i am ', r"^i'm ", r'^i got ', r'^i\s+',
r'^my ', r'^having ', r'^suffering from ', r'^experiencing ', r'^with ', r'^and ', r'^, ', r'^\s+'
]
tokens = re.split(r',| and | و | و|,|\band\b', new_symptom)
cleaned_tokens = []
for t in tokens:
t = t.strip().lower()
for phrase in leading_phrases:
t = re.sub(phrase, '', t)
t = t.strip()
if t:
t = t.replace(' ', '_')
cleaned_tokens.append(t)
# For each token, check for ambiguity
for token in cleaned_tokens:
options = self.handle_single_symptom_input(token)
if len(options) > 1:
# Ambiguous, need clarification
self.current_state = 'free_text_symptom_clarification'
self.free_text_clarify_token = token
self.free_text_clarify_options = options
prompt = (f"You entered '{token}'. Please specify the type(s):\n" +
'\n'.join([f" {i+1}) {opt}" for i, opt in enumerate(options)]) +
"\n 0) None of these / skip\nSelect all that apply (comma-separated numbers, e.g. 1,3,5): ")
options_list = [str(i+1) for i in range(len(options))] + ["0", "undo"]
return {
'prompt': prompt,
'options': options_list,
'state': self.current_state
}
elif len(options) == 1:
if options[0] not in self.symptoms:
self.symptoms.append(options[0])
added = options[0]
else:
added = None
else:
added = None
# If all tokens processed and no ambiguity, show added message and review
added_names = [self._format_symptom_name(s) for s in self.symptoms]
prompt = f"Added: {', '.join(added_names)}\n\nHere are the symptoms I have: {', '.join(added_names)}\nWhat would you like to do?\n1) Add a symptom\n2) Remove a symptom\n3) Edit all symptoms (re-enter full list)\n4) Continue with current symptoms"
self.current_state = "free_text_review"
return {
'prompt': prompt,
'options': ["1", "2", "3", "4", "undo"],
'state': self.current_state
}
def api_handle_free_text_remove_symptom(self, choice):
"""API version of removing symptom in free text mode"""
try:
remove_choice = int(choice)
if 1 <= remove_choice <= len(self.symptoms):
removed_symptom = self.symptoms.pop(remove_choice - 1)
formatted_removed = self._format_symptom_name(removed_symptom)
prompt = f"Removed: {formatted_removed}\n" + self.api_get_free_text_review_menu()['prompt']
self.current_state = "free_text_review"
return {
'prompt': prompt,
'options': ["1", "2", "3", "4"],
'state': self.current_state,
'symptoms': self.symptoms
}
else:
return {
'prompt': "Invalid choice. Please try again.\n" + self.api_get_free_text_review_menu()['prompt'],
'options': ["1", "2", "3", "4"],
'state': self.current_state
}
except ValueError:
return {
'prompt': "Please enter a valid number.\n" + self.api_get_free_text_review_menu()['prompt'],
'options': ["1", "2", "3", "4"],
'state': self.current_state
}
def api_handle_free_text_edit_all(self, final_symptoms):
"""API version of editing all symptoms in free text mode"""
if final_symptoms.strip().lower() == "undo":
self.current_state = "free_text_review"
return self.api_get_free_text_review_menu()
# Use the EXACT same logic as CLI
import re
leading_phrases = [
r'^i have ', r'^i am suffering from ', r'^i am having ', r'^i feel ', r'^i am ', r'^i\'m ', r'^i got ', r'^i\s+',
r'^my ', r'^having ', r'^suffering from ', r'^experiencing ', r'^with ', r'^and ', r'^, ', r'^\s+'
]
tokens = re.split(r',| and | و | و|,|\band\b', final_symptoms)
cleaned_tokens = []
for t in tokens:
t = t.strip().lower()
for phrase in leading_phrases:
t = re.sub(phrase, '', t)
t = t.strip()
if t:
t = t.replace(' ', '_')
cleaned_tokens.append(t)
validated = []
for token in cleaned_tokens:
corrected_tokens = self.handle_single_symptom_input(token)
validated.extend(corrected_tokens)
if validated:
self.symptoms = validated
prompt = f"Symptoms updated.\n" + self.api_get_free_text_review_menu()['prompt']
else:
prompt = "No valid symptoms entered. Please try again.\n" + self.api_get_free_text_review_menu()['prompt']
self.current_state = "free_text_review"
return {
'prompt': prompt,
'options': ["1", "2", "3", "4", "undo"],
'state': self.current_state,
'symptoms': self.symptoms
}
def api_handle_related_symptoms(self, user_input):
"""API version of related symptoms handling"""
user_input = user_input.strip().lower()
# Initialize tracking if not already
if not hasattr(self, 'related_symptom_idx'):
self.related_symptom_idx = 0
self.denied_symptoms = set()
self.all_symptoms = list(self.symptoms)
self.related_symptoms_list = []
# Build the list of (main_symptom, related_symptom) pairs to ask
for main_symptom in self.symptoms:
related = self.get_medical_relevant_symptoms(main_symptom)
for rel in related:
if rel not in self.symptoms and rel not in self.related_symptoms_list:
self.related_symptoms_list.append((main_symptom, rel))
# If no related symptoms to ask, proceed to diagnosis
if not self.related_symptoms_list or self.related_symptom_idx >= len(self.related_symptoms_list):
# Clean up
delattr(self, 'related_symptom_idx')
delattr(self, 'related_symptoms_list')
delattr(self, 'denied_symptoms')
delattr(self, 'all_symptoms')
return self.api_make_diagnosis()
idx = self.related_symptom_idx
main_symptom, rel_symptom = self.related_symptoms_list[idx]
formatted = rel_symptom.replace('_', ' ')
if user_input == 'back':
if idx > 0:
self.related_symptom_idx -= 1
idx = self.related_symptom_idx
main_symptom, rel_symptom = self.related_symptoms_list[idx]
formatted = rel_symptom.replace('_', ' ')
prompt = f"{formatted}? (yes/y or no/n or back)"
return {
'prompt': prompt,
'options': ["yes", "y", "no", "n", "back"],
'state': self.current_state
}
else:
prompt = 'Already at the first related symptom.'
return {
'prompt': prompt,
'options': ["yes", "y", "no", "n", "back"],
'state': self.current_state
}
if user_input in ['yes', 'y']:
if rel_symptom not in self.all_symptoms:
self.all_symptoms.append(rel_symptom)
self.related_symptom_idx += 1
elif user_input in ['no', 'n']:
self.denied_symptoms.add(rel_symptom)
self.related_symptom_idx += 1
else:
prompt = f"Please enter yes/y, no/n, or back.\n{formatted}? (yes/y or no/n or back)"
return {
'prompt': prompt,
'options': ["yes", "y", "no", "n", "back"],
'state': self.current_state
}
# Move to next related symptom or finish
if self.related_symptom_idx < len(self.related_symptoms_list):
next_main, next_rel = self.related_symptoms_list[self.related_symptom_idx]
formatted = next_rel.replace('_', ' ')
prompt = f"{formatted}? (yes/y or no/n or back)"
return {
'prompt': prompt,
'options': ["yes", "y", "no", "n", "back"],
'state': self.current_state
}
else:
# All related symptoms processed
self.symptoms = self.all_symptoms
# Clean up
delattr(self, 'related_symptom_idx')
delattr(self, 'related_symptoms_list')
delattr(self, 'denied_symptoms')
delattr(self, 'all_symptoms')
return self.api_make_diagnosis()
def api_handle_symptom_clarification(self, user_input):
"""API version of symptom clarification"""
user_input = user_input.strip()
selected = [x.strip() for x in user_input.split(',') if x.strip().isdigit()]
indices = [int(x) for x in selected if x != "0"]
options = getattr(self, 'symptom_clarification_options', [])
chosen = []
if options and indices:
for idx in indices:
if 1 <= idx <= len(options):
chosen.append(options[idx-1])
if chosen:
self.symptoms = chosen
self.current_state = "diagnosis_review"
prompt = f"Here are the symptoms I have: {', '.join(self.symptoms)}\nWould you like to change this symptom? (yes/y or no/n)\n-> "
return {
'prompt': prompt,
'options': ["yes", "y", "no", "n", "undo"],
'state': self.current_state
}
else:
self.current_state = "diagnosis_symptom"
prompt = "Enter the symptom you are experiencing ->"
return {
'prompt': prompt,
'options': [],
'state': self.current_state
}
def api_handle_doctor_search(self, user_input):