File size: 45,098 Bytes
f25e634
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": 57,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "JUwKXagI8Vkj",
        "outputId": "c9f6a127-a95e-48d4-d0d8-3725f62cca12"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Predicted Disease: Fungal infection\n"
          ]
        }
      ],
      "source": [
        "import xgboost as xgb\n",
        "import pickle\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "\n",
        "# Load the trained model\n",
        "model = xgb.XGBClassifier()\n",
        "model.load_model(\"symptom_disease_model.json\")\n",
        "\n",
        "# Load the label encoder\n",
        "label_encoder = pickle.load(open(\"label_encoder.pkl\", \"rb\"))\n",
        "\n",
        "# Load symptom names (from preprocessed training data)\n",
        "X_train = pd.read_csv(\"X_train.csv\")  # Get feature names\n",
        "symptom_list = X_train.columns.tolist()\n",
        "\n",
        "# Function to Predict Disease\n",
        "def predict_disease(user_symptoms):\n",
        "    # Convert user symptoms into one-hot encoded format\n",
        "    input_vector = np.zeros(len(symptom_list))\n",
        "\n",
        "    for symptom in user_symptoms:\n",
        "        if symptom in symptom_list:\n",
        "            input_vector[symptom_list.index(symptom)] = 1\n",
        "\n",
        "    input_vector = input_vector.reshape(1, -1)  # Reshape for model\n",
        "\n",
        "    # Predict disease (returns a numerical class)\n",
        "    predicted_class = model.predict(input_vector)[0]\n",
        "\n",
        "    # Convert number to disease name\n",
        "    predicted_disease = label_encoder.inverse_transform([predicted_class])[0]\n",
        "\n",
        "    return predicted_disease\n",
        "\n",
        "# Example Usage\n",
        "user_symptoms = [\"itching\", \"skin_rash\", \"nodal_skin_eruptions\"]\n",
        "predicted_disease = predict_disease(user_symptoms)\n",
        "print(f\"Predicted Disease: {predicted_disease}\")\n"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install zipfile36\n",
        "import sys\n",
        "if sys.version_info >= (3, 6):\n",
        "    import zipfile\n",
        "else:\n",
        "    import zipfile36 as zipfile\n",
        "import os\n",
        "\n",
        "zip_file_path = '/content/disease symptom.zip'  # Update with your path\n",
        "extracted_dir = '/content'  # Where to extract the files\n",
        "\n",
        "with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n",
        "    zip_ref.extractall(extracted_dir)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "_cmO1ieS8rcS",
        "outputId": "51db88e4-f9a6-4404-be06-a161afb80c29"
      },
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Collecting zipfile36\n",
            "  Downloading zipfile36-0.1.3-py3-none-any.whl.metadata (736 bytes)\n",
            "Downloading zipfile36-0.1.3-py3-none-any.whl (20 kB)\n",
            "Installing collected packages: zipfile36\n",
            "Successfully installed zipfile36-0.1.3\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Load the precaution dataset\n",
        "precaution_df = pd.read_csv(\"Disease precaution.csv\")\n",
        "\n",
        "# Convert to dictionary for fast lookup\n",
        "precaution_dict = {}\n",
        "for _, row in precaution_df.iterrows():\n",
        "    disease = row[\"Disease\"].strip().lower()\n",
        "    precautions = [row[f\"Precaution_{i}\"] for i in range(1, 5) if pd.notna(row[f\"Precaution_{i}\"])]\n",
        "    precaution_dict[disease] = precautions\n",
        "\n",
        "# Function to Get Precautions\n",
        "def get_precautions(disease_name):\n",
        "    disease_name = disease_name.strip().lower()\n",
        "    return precaution_dict.get(disease_name, [\"No precautions found\"])\n",
        "\n",
        "# Example Usage\n",
        "precautions = get_precautions(predicted_disease)\n",
        "print(f\"Precautions for {predicted_disease}: {precautions}\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Q-by1c_x8lqq",
        "outputId": "19461912-49d0-48e4-9d9a-2b7e535df0e0"
      },
      "execution_count": 3,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Precautions for Fungal infection: ['bath twice', 'use detol or neem in bathing water', 'keep infected area dry', 'use clean cloths']\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install nltk"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Z9dYwI-Cjzz3",
        "outputId": "1564c447-3876-4979-9c6c-44832e5ab1b7"
      },
      "execution_count": 80,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Requirement already satisfied: nltk in /usr/local/lib/python3.11/dist-packages (3.9.1)\n",
            "Requirement already satisfied: click in /usr/local/lib/python3.11/dist-packages (from nltk) (8.1.8)\n",
            "Requirement already satisfied: joblib in /usr/local/lib/python3.11/dist-packages (from nltk) (1.4.2)\n",
            "Requirement already satisfied: regex>=2021.8.3 in /usr/local/lib/python3.11/dist-packages (from nltk) (2024.11.6)\n",
            "Requirement already satisfied: tqdm in /usr/local/lib/python3.11/dist-packages (from nltk) (4.67.1)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import re\n",
        "import nltk\n",
        "from nltk.corpus import stopwords\n",
        "from nltk.tokenize import word_tokenize\n",
        "\n",
        "# Download stopwords if not already downloaded\n",
        "nltk.download(\"stopwords\")\n",
        "nltk.download(\"punkt\")\n",
        "\n",
        "# Load English stopwords\n",
        "stop_words = set(stopwords.words(\"english\"))\n",
        "nltk.download('punkt_tab')"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "BbkxCwC3j766",
        "outputId": "318849f5-8596-44ac-878e-91e154ef5e2d"
      },
      "execution_count": 83,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "[nltk_data] Downloading package stopwords to /root/nltk_data...\n",
            "[nltk_data]   Package stopwords is already up-to-date!\n",
            "[nltk_data] Downloading package punkt to /root/nltk_data...\n",
            "[nltk_data]   Package punkt is already up-to-date!\n",
            "[nltk_data] Downloading package punkt_tab to /root/nltk_data...\n",
            "[nltk_data]   Unzipping tokenizers/punkt_tab.zip.\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "True"
            ]
          },
          "metadata": {},
          "execution_count": 83
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import xgboost as xgb\n",
        "import pickle\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "import torch\n",
        "from transformers import AutoTokenizer, AutoModelForQuestionAnswering\n",
        "import re  # Import regex module for better input processing\n",
        "\n",
        "# ============================\n",
        "# πŸ”Ή 1. Load Pretrained Medical Q&A Model\n",
        "# ============================\n",
        "qa_model_name = \"deepset/roberta-base-squad2\"  # Better model for medical Q&A\n",
        "tokenizer = AutoTokenizer.from_pretrained(qa_model_name)\n",
        "qa_model = AutoModelForQuestionAnswering.from_pretrained(qa_model_name)\n",
        "\n",
        "# ============================\n",
        "# πŸ”Ή 2. Load Symptom Checker Model & Label Encoder (Fixed)\n",
        "# ============================\n",
        "# Load trained XGBoost model from JSON\n",
        "model = xgb.XGBClassifier()\n",
        "model.load_model(\"symptom_disease_model.json\")\n",
        "common_symptoms = [\"fever\", \"cough\", \"headache\", \"pain\", \"vomiting\", \"fatigue\", \"nausea\", \"rash\", \"chills\", \"dizziness\", \"sore throat\", \"diarrhea\"]\n",
        "\n",
        "# Load Corrected Label Encoder\n",
        "label_encoder = pickle.load(open(\"label_encoder.pkl\", \"rb\"))\n",
        "\n",
        "# Load symptom names from training data\n",
        "X_train = pd.read_csv(\"X_train.csv\")  # Get feature names\n",
        "symptom_list = X_train.columns.tolist()\n",
        "\n",
        "# ============================\n",
        "# πŸ”Ή 3. Load Precaution Data\n",
        "# ============================\n",
        "precaution_df = pd.read_csv(\"Disease precaution.csv\")\n",
        "precaution_dict = {\n",
        "    row[\"Disease\"].strip().lower(): [row[f\"Precaution_{i}\"] for i in range(1, 5) if pd.notna(row[f\"Precaution_{i}\"])]\n",
        "    for _, row in precaution_df.iterrows()\n",
        "}\n",
        "\n",
        "# ============================\n",
        "# πŸ”Ή 4. Load Medical Context\n",
        "# ============================\n",
        "def load_medical_context():\n",
        "    with open(\"medical_context.txt\", \"r\", encoding=\"utf-8\") as file:\n",
        "        return file.read()\n",
        "\n",
        "medical_context = load_medical_context()\n",
        "\n",
        "# ============================\n",
        "# πŸ”Ή 5. Doctor Database (For Appointments)\n",
        "# ============================\n",
        "doctor_database = {\n",
        "    \"malaria\": [{\"name\": \"Dr. Rajesh Kumar\", \"specialty\": \"Infectious Diseases\", \"location\": \"Apollo Hospital\", \"contact\": \"9876543210\"}],\n",
        "    \"diabetes\": [{\"name\": \"Dr. Anil Mehta\", \"specialty\": \"Endocrinologist\", \"location\": \"AIIMS Delhi\", \"contact\": \"9876543233\"}],\n",
        "    \"heart attack\": [{\"name\": \"Dr. Vikram Singh\", \"specialty\": \"Cardiologist\", \"location\": \"Medanta Hospital\", \"contact\": \"9876543255\"}],\n",
        "    \"hepatitis e\": [{\"name\": \"Dr. Sunil Agarwal\", \"specialty\": \"Hepatologist\", \"location\": \"Fortis Hospital\", \"contact\": \"9876543266\"}],\n",
        "    \"pneumonia\": [{\"name\": \"Dr. Priya Sharma\", \"specialty\": \"Pulmonologist\", \"location\": \"Max Healthcare\", \"contact\": \"9876543277\"}],\n",
        "    \"heartattack\": [{\"name\": \"Dr. Vikram Singh\", \"specialty\": \"Cardiologist\", \"location\": \"Medanta Hospital\", \"contact\": \"9876543255\"}],\n",
        "}\n",
        "\n",
        "# ============================\n",
        "# πŸ”Ή 6. Predict Disease from Symptoms (Fully Fixed)\n",
        "# ============================\n",
        "def predict_disease(user_symptoms):\n",
        "    \"\"\"Predicts the disease based on user symptoms using the trained XGBoost model.\"\"\"\n",
        "    input_vector = np.zeros(len(symptom_list))\n",
        "\n",
        "    for symptom in user_symptoms:\n",
        "        if symptom in symptom_list:\n",
        "            input_vector[symptom_list.index(symptom)] = 1  # One-hot encoding\n",
        "\n",
        "    input_vector = input_vector.reshape(1, -1)  # Reshape for model input\n",
        "\n",
        "    # Predict disease (returns a numerical class)\n",
        "    predicted_class = model.predict(input_vector)[0]\n",
        "\n",
        "    # Convert number to disease name\n",
        "    predicted_disease = label_encoder.inverse_transform([predicted_class])[0]\n",
        "\n",
        "    return predicted_disease\n",
        "\n",
        "# ============================\n",
        "# πŸ”Ή 7. Get Precautions for a Disease\n",
        "# ============================\n",
        "def get_precautions(disease):\n",
        "    \"\"\"Returns the precautions for a given disease.\"\"\"\n",
        "    return precaution_dict.get(disease.lower(), [\"No precautions available\"])\n",
        "\n",
        "# ============================\n",
        "# πŸ”Ή 8. Answer Medical Questions (Q&A Model)\n",
        "# ============================\n",
        "def get_medical_answer(question):\n",
        "    \"\"\"Uses the pre-trained Q&A model to answer general medical questions.\"\"\"\n",
        "    inputs = tokenizer(question, medical_context, return_tensors=\"pt\", truncation=True, max_length=512)\n",
        "    with torch.no_grad():\n",
        "        outputs = qa_model(**inputs)\n",
        "\n",
        "    answer_start = torch.argmax(outputs.start_logits)\n",
        "    answer_end = torch.argmax(outputs.end_logits) + 1\n",
        "\n",
        "    answer = tokenizer.convert_tokens_to_string(\n",
        "        tokenizer.convert_ids_to_tokens(inputs[\"input_ids\"][0][answer_start:answer_end])\n",
        "    )\n",
        "\n",
        "    return answer if answer.strip() and answer != \"[CLS]\" else \"No reliable answer found.\"\n",
        "\n",
        "# ============================\n",
        "# πŸ”Ή 9. Book a Doctor's Appointment\n",
        "# ============================\n",
        "def book_appointment(disease):\n",
        "    \"\"\"Finds a doctor for the given disease and returns appointment details.\"\"\"\n",
        "    disease = disease.lower().strip()\n",
        "    doctors = doctor_database.get(disease, [])\n",
        "    if not doctors:\n",
        "        return f\"Sorry, no available doctors found for {disease}.\"\n",
        "\n",
        "    doctor = doctors[0]\n",
        "    return f\"Appointment booked with **{doctor['name']}** ({doctor['specialty']}) at **{doctor['location']}**.\\nContact: {doctor['contact']}\"\n",
        "\n",
        "# ============================\n",
        "# πŸ”Ή 10. Handle User Queries\n",
        "# ============================\n",
        "def extract_treatment_from_context(disease):\n",
        "    \"\"\"Extracts treatment details for a given disease from `medical_context.txt`.\"\"\"\n",
        "    with open(\"medical_context.txt\", \"r\", encoding=\"utf-8\") as file:\n",
        "        lines = file.readlines()\n",
        "\n",
        "    treatment_section = []\n",
        "    found_disease = False\n",
        "    found_treatment = False\n",
        "\n",
        "    for line in lines:\n",
        "        line = line.strip()\n",
        "\n",
        "        #  Check if we found the disease name\n",
        "        if f\"## {disease.lower()}\" in line.lower():\n",
        "            found_disease = True\n",
        "\n",
        "        #  If we found the disease, now look for \"Treatment\"\n",
        "        if found_disease and \"**Treatment**\" in line:\n",
        "            found_treatment = True\n",
        "            continue  # Skip the \"**Treatment**:\" line itself\n",
        "\n",
        "        #  If found, keep extracting treatment details\n",
        "        if found_treatment:\n",
        "            # Stop at blank line or the next section (## New Disease Name)\n",
        "            if line == \"\" or line.startswith(\"## \"):\n",
        "                break\n",
        "            treatment_section.append(line)\n",
        "\n",
        "    return \"\\n\".join(treatment_section) if treatment_section else None\n",
        "\n",
        "\n",
        "def extract_disease_name(user_query):\n",
        "    \"\"\"Extracts the disease name by removing unnecessary words, but keeps medical terms.\"\"\"\n",
        "    user_query_cleaned = re.sub(r\"[^\\w\\s]\", \"\", user_query.lower())  # Remove punctuation\n",
        "    words = word_tokenize(user_query_cleaned)\n",
        "\n",
        "    #  Remove stopwords but keep diseases/symptoms\n",
        "    filtered_words = [word for word in words if word not in stop_words or word in common_symptoms]\n",
        "\n",
        "    return \" \".join(filtered_words).strip()\n",
        "\n",
        "def find_best_match(query, database):\n",
        "    \"\"\"Finds the best matching disease from the database based on query words.\"\"\"\n",
        "    query_words = query.split()  # Split query into words\n",
        "\n",
        "    # Check for exact match first\n",
        "    if query in database:\n",
        "        return query  # Exact match found\n",
        "\n",
        "    # Check if any word in query exists in database keys\n",
        "    for disease in database:\n",
        "        for word in query_words:\n",
        "            if word in disease:  # Partial match found\n",
        "                return disease\n",
        "\n",
        "    return None  # No match found\n",
        "\n",
        "\n",
        "def handle_user_query(user_query):\n",
        "    \"\"\"Handles user queries related to symptoms, diseases, and doctor appointments.\"\"\"\n",
        "\n",
        "    user_query = user_query.lower().strip()\n",
        "\n",
        "    #  Skip Cleaning for \"I have...\" and \"experiencing...\" Cases\n",
        "    if \"i have\" in user_query or \"experiencing\" in user_query:\n",
        "        symptoms = user_query.replace(\"I have\", \"\").replace(\"experiencing\", \"\").strip()\n",
        "        disease = predict_disease(symptoms.split(\", \"))  # Convert to list\n",
        "        precautions = get_precautions(disease)\n",
        "        return f\"**Predicted Disease:** {disease}\\n**Precautions:** {', '.join(precautions)}\\n{book_appointment(disease)}\"\n",
        "\n",
        "    #  Extract Disease Name for Queries\n",
        "    user_query_cleaned = extract_disease_name(user_query)\n",
        "\n",
        "    #  Handle \"Who should I see for...\" Queries (Improved with Partial Matching)\n",
        "    if \"who should i see \" in user_query:\n",
        "        disease_query = user_query.replace(\"who should i see\", \"\").strip()\n",
        "        disease = find_best_match(disease_query, doctor_database)  # Get best match\n",
        "\n",
        "        if disease:\n",
        "            doctor = doctor_database[disease][0]\n",
        "            return f\"You should see a **{doctor['specialty']}** for {disease}.\\nExample: {doctor['name']} at {doctor['location']}.\"\n",
        "        else:\n",
        "            return \"I'm not sure. Please consult a general physician for more guidance.\"\n",
        "\n",
        "    #  Book Appointment (Improved with Partial Matching)\n",
        "    elif \"book appointment\" in user_query_cleaned:\n",
        "        disease_query = user_query_cleaned.replace(\"book appointment\", \"\").strip()\n",
        "        disease = find_best_match(disease_query, doctor_database)\n",
        "        return book_appointment(disease) if disease else \"Sorry, no matching doctor found.\"\n",
        "\n",
        "    #  Symptoms Query\n",
        "    elif \"symptoms\" in user_query_cleaned or \"signs\" in user_query_cleaned:\n",
        "        disease = user_query_cleaned.replace(\"symptoms\", \"\").replace(\"signs\", \"\").strip()\n",
        "        return get_medical_answer(f\"What are the symptoms of {disease}?\")\n",
        "\n",
        "    #  Precautions Query\n",
        "    elif \"precautions\" in user_query_cleaned or \"prevent\" in user_query_cleaned:\n",
        "        disease = user_query_cleaned.replace(\"precautions\", \"\").replace(\"prevent\", \"\").strip()\n",
        "        return \", \".join(get_precautions(disease))\n",
        "\n",
        "    #  Treatment Query\n",
        "    if \"treatment\" in user_query_cleaned or \"treat\" in user_query_cleaned:\n",
        "        disease = user_query_cleaned.replace(\"treatment\", \"\").replace(\"treat\", \"\").strip()\n",
        "\n",
        "        # πŸ”Ή First, try to extract treatment from `medical_context.txt`\n",
        "        treatment_answer = extract_treatment_from_context(disease)\n",
        "        if treatment_answer:\n",
        "            return treatment_answer  #  Use direct extraction first\n",
        "\n",
        "        # πŸ”Ή If no treatment info found, use the Q&A Model\n",
        "        model_answer = get_medical_answer(f\"What is the treatment for {disease}?\")\n",
        "        if model_answer in [\"<s>\", \"\", \"No reliable answer found.\"]:\n",
        "            return f\"I'm not sure, but common treatments for {disease} include medication, therapy, or consulting a specialist.\"\n",
        "        return model_answer\n",
        "\n",
        "    #  General Medical Questions (Fallback)\n",
        "    else:\n",
        "        response = get_medical_answer(user_query)\n",
        "        if response in [\"<s>\", \"\", \"No reliable answer found.\"]:\n",
        "            return \"I'm not sure, but you may consult a specialist for better guidance.\"\n",
        "        return response\n",
        "\n",
        "# ============================\n",
        "# πŸ”Ή 11. Test Cases (Run Examples)\n",
        "# ============================\n",
        "print(handle_user_query(\"I have fever, chills, and muscle aches\"))  # Should predict disease & precautions\n",
        "print(handle_user_query(\"What are the symptoms of pneumonia?\"))  # Should return pneumonia symptoms\n",
        "print(handle_user_query(\"Book an appointment for diabetes\"))  # Should book a diabetes specialist\n",
        "print(handle_user_query(\"Who should I see for  heart attack\"))  # Should return \"Cardiologist\"\n",
        "print(handle_user_query(\"what is the treatment for tuberculosis\"))  # Should return correct treatment\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ccAK0hD9WcZy",
        "outputId": "d36ea7da-1ca1-4de0-e39a-9ad35a0a0b31"
      },
      "execution_count": 110,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "**Predicted Disease:** Hepatitis E\n",
            "**Precautions:** stop alcohol consumption, rest, consult doctor, medication\n",
            "Appointment booked with **Dr. Sunil Agarwal** (Hepatologist) at **Fortis Hospital**.\n",
            "Contact: 9876543266\n",
            " Fever, cough, chest pain, difficulty breathing\n",
            "Appointment booked with **Dr. Anil Mehta** (Endocrinologist) at **AIIMS Delhi**.\n",
            "Contact: 9876543233\n",
            "You should see a **Cardiologist** for heart attack.\n",
            "Example: Dr. Vikram Singh at Medanta Hospital.\n",
            "- **Doctor to consult**: Infectious Disease Specialist\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(handle_user_query(\"What is the treatment for tuberculosis?\"))  # Should return correct treatment\n",
        "print(handle_user_query(\"What is the treatment for malaria?\"))  # Should also work\n",
        "print(handle_user_query(\"What is the treatment for cancer?\"))  # Should return something useful"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ybyh64xuq1ih",
        "outputId": "4bc9e030-8a3a-469d-d5b3-9d0e8aec6367"
      },
      "execution_count": 111,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "- **Doctor to consult**: Infectious Disease Specialist\n",
            "I'm not sure, but common treatments for malaria include medication, therapy, or consulting a specialist.\n",
            "- **Doctor to consult**: Oncologist\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(handle_user_query(\"What is the treatment for tuberculosis?\"))  # Should return correct treatment\n",
        "print(handle_user_query(\"What is the treatment for malaria?\"))  # Should also work\n",
        "print(handle_user_query(\"What is the treatment for cancer?\"))  # Should return something useful\n",
        "print(handle_user_query(\"How to treat diabetes?\"))  # Should return proper treatment\n",
        "print(handle_user_query(\"Tell me the cure for pneumonia?\"))  # Should return treatment\n",
        "print(handle_user_query(\"Treatment for typhoid?\"))  # Should extract treatment\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "6DQ8XH11gwGZ",
        "outputId": "5a8cbacc-05d5-4c9e-cb4c-6b93666971b2"
      },
      "execution_count": 112,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "- **Doctor to consult**: Infectious Disease Specialist\n",
            "I'm not sure, but common treatments for malaria include medication, therapy, or consulting a specialist.\n",
            "- **Doctor to consult**: Oncologist\n",
            "I'm not sure, but common treatments for diabetes include medication, therapy, or consulting a specialist.\n",
            "I'm not sure, but you may consult a specialist for better guidance.\n",
            "I'm not sure, but common treatments for typhoid include medication, therapy, or consulting a specialist.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(handle_user_query(\"What are the symptoms of pneumonia?\"))  # Should return correct symptoms\n",
        "print(handle_user_query(\"Signs of heart attack?\"))  # Should return expected symptoms\n",
        "print(handle_user_query(\"How do I know if I have typhoid?\"))  # Should return typhoid symptoms\n",
        "print(handle_user_query(\"What symptoms should I check for tuberculosis?\"))  # Should work\n",
        "print(handle_user_query(\"Symptoms of dengue?\"))  # Should return symptoms of dengue\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Oq1xVi93u0nN",
        "outputId": "9fd0433b-aad4-4246-bb3d-5cc8c23995e1"
      },
      "execution_count": 113,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            " Fever, cough, chest pain, difficulty breathing\n",
            " Chest pain, shortness of breath, nausea, pain in the left arm\n",
            "**Predicted Disease:** Hepatitis E\n",
            "**Precautions:** stop alcohol consumption, rest, consult doctor, medication\n",
            "Appointment booked with **Dr. Sunil Agarwal** (Hepatologist) at **Fortis Hospital**.\n",
            "Contact: 9876543266\n",
            "<s>\n",
            "<s>\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(handle_user_query(\"Who should I see for a heart attack?\"))  # Should return \"Cardiologist\"\n",
        "print(handle_user_query(\"Which doctor should I visit for diabetes?\"))  # Should return \"Endocrinologist\"\n",
        "print(handle_user_query(\"Who should I consult for a skin rash?\"))  # Should return \"Dermatologist\"\n",
        "print(handle_user_query(\"What kind of doctor treats pneumonia?\"))  # Should return \"Pulmonologist\"\n",
        "print(handle_user_query(\"Who specializes in treating migraines?\"))  # Should return \"Neurologist\"\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "8IyTjf6Ku1r2",
        "outputId": "4776d477-59fc-4d0a-8bd6-c6c97c2fdaf7"
      },
      "execution_count": 114,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "You should see a **Infectious Diseases** for malaria.\n",
            "Example: Dr. Rajesh Kumar at Apollo Hospital.\n",
            "I'm not sure, but you may consult a specialist for better guidance.\n",
            "I'm not sure, but you may consult a specialist for better guidance.\n",
            "I'm not sure, but common treatments for kind doctor s pneumonia include medication, therapy, or consulting a specialist.\n",
            "I'm not sure, but common treatments for specializes ing migraines include medication, therapy, or consulting a specialist.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(handle_user_query(\"Book an appointment for malaria\"))  # Should book doctor for malaria\n",
        "print(handle_user_query(\"I need a doctor for high blood pressure\"))  # Should book doctor for hypertension\n",
        "print(handle_user_query(\"Schedule a consultation for fever\"))  # Should book general physician\n",
        "print(handle_user_query(\"Find a doctor for diabetes treatment\"))  # Should book endocrinologist\n",
        "print(handle_user_query(\"Book an appointment for pneumonia treatment\"))  # Should book pulmonologist\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "RgbA5722u4Bk",
        "outputId": "ea5b0b8d-6194-49c2-8e6b-311c06d0cad2"
      },
      "execution_count": 115,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Appointment booked with **Dr. Rajesh Kumar** (Infectious Diseases) at **Apollo Hospital**.\n",
            "Contact: 9876543210\n",
            "I'm not sure, but you may consult a specialist for better guidance.\n",
            "I'm not sure, but you may consult a specialist for better guidance.\n",
            "I'm not sure, but common treatments for find doctor diabetes include medication, therapy, or consulting a specialist.\n",
            "Appointment booked with **Dr. Priya Sharma** (Pulmonologist) at **Max Healthcare**.\n",
            "Contact: 9876543277\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(handle_user_query(\"I have fever, cough, and chills\"))  # Should predict disease correctly\n",
        "print(handle_user_query(\"Experiencing blurry vision and excessive thirst\"))  # Should return \"Diabetes\"\n",
        "print(handle_user_query(\"I am experiencing severe chest pain and difficulty breathing\"))  # Should return \"Heart Attack\"\n",
        "print(handle_user_query(\"Feeling tired, cold, and gaining weight\"))  # Should return \"Hypothyroidism\"\n",
        "print(handle_user_query(\"I have rash, joint pain, and headache\"))  # Should return \"Dengue\"\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "9zhwGv6gu5yc",
        "outputId": "17cff133-5c44-417a-bc37-4858a72084fd"
      },
      "execution_count": 116,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "**Predicted Disease:** Hepatitis E\n",
            "**Precautions:** stop alcohol consumption, rest, consult doctor, medication\n",
            "Appointment booked with **Dr. Sunil Agarwal** (Hepatologist) at **Fortis Hospital**.\n",
            "Contact: 9876543266\n",
            "**Predicted Disease:** Hepatitis E\n",
            "**Precautions:** stop alcohol consumption, rest, consult doctor, medication\n",
            "Appointment booked with **Dr. Sunil Agarwal** (Hepatologist) at **Fortis Hospital**.\n",
            "Contact: 9876543266\n",
            "**Predicted Disease:** Hepatitis E\n",
            "**Precautions:** stop alcohol consumption, rest, consult doctor, medication\n",
            "Appointment booked with **Dr. Sunil Agarwal** (Hepatologist) at **Fortis Hospital**.\n",
            "Contact: 9876543266\n",
            "I'm not sure, but you may consult a specialist for better guidance.\n",
            "**Predicted Disease:** Hepatitis E\n",
            "**Precautions:** stop alcohol consumption, rest, consult doctor, medication\n",
            "Appointment booked with **Dr. Sunil Agarwal** (Hepatologist) at **Fortis Hospital**.\n",
            "Contact: 9876543266\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(handle_user_query(\"What does a doctor do?\"))  # Should return general doctor description\n",
        "print(handle_user_query(\"What are antibiotics?\"))  # Should explain antibiotics\n",
        "print(handle_user_query(\"How does the immune system work?\"))  # Should explain immunity\n",
        "print(handle_user_query(\"What is the function of the liver?\"))  # Should explain liver function\n",
        "print(handle_user_query(\"Explain how blood pressure works?\"))  # Should provide useful explanation\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "f1_Tt8y3u8wB",
        "outputId": "6b1104ee-32cb-42fd-95ed-894824a49e33"
      },
      "execution_count": 118,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "I'm not sure, but you may consult a specialist for better guidance.\n",
            "bacterial pneumonia\n",
            "I'm not sure, but you may consult a specialist for better guidance.\n",
            "I'm not sure, but you may consult a specialist for better guidance.\n",
            "I'm not sure, but you may consult a specialist for better guidance.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "hh7-xCtRu-NH"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install streamlit\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "lj6ZVPRqwKqG",
        "outputId": "55936a43-a429-4630-bbac-60fa63fa399a"
      },
      "execution_count": 128,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Collecting streamlit\n",
            "  Downloading streamlit-1.43.1-py2.py3-none-any.whl.metadata (8.9 kB)\n",
            "Requirement already satisfied: altair<6,>=4.0 in /usr/local/lib/python3.11/dist-packages (from streamlit) (5.5.0)\n",
            "Requirement already satisfied: blinker<2,>=1.0.0 in /usr/local/lib/python3.11/dist-packages (from streamlit) (1.9.0)\n",
            "Requirement already satisfied: cachetools<6,>=4.0 in /usr/local/lib/python3.11/dist-packages (from streamlit) (5.5.2)\n",
            "Requirement already satisfied: click<9,>=7.0 in /usr/local/lib/python3.11/dist-packages (from streamlit) (8.1.8)\n",
            "Requirement already satisfied: numpy<3,>=1.23 in /usr/local/lib/python3.11/dist-packages (from streamlit) (1.26.4)\n",
            "Requirement already satisfied: packaging<25,>=20 in /usr/local/lib/python3.11/dist-packages (from streamlit) (24.2)\n",
            "Requirement already satisfied: pandas<3,>=1.4.0 in /usr/local/lib/python3.11/dist-packages (from streamlit) (2.2.2)\n",
            "Requirement already satisfied: pillow<12,>=7.1.0 in /usr/local/lib/python3.11/dist-packages (from streamlit) (11.1.0)\n",
            "Requirement already satisfied: protobuf<6,>=3.20 in /usr/local/lib/python3.11/dist-packages (from streamlit) (4.25.6)\n",
            "Requirement already satisfied: pyarrow>=7.0 in /usr/local/lib/python3.11/dist-packages (from streamlit) (18.1.0)\n",
            "Requirement already satisfied: requests<3,>=2.27 in /usr/local/lib/python3.11/dist-packages (from streamlit) (2.32.3)\n",
            "Requirement already satisfied: tenacity<10,>=8.1.0 in /usr/local/lib/python3.11/dist-packages (from streamlit) (9.0.0)\n",
            "Requirement already satisfied: toml<2,>=0.10.1 in /usr/local/lib/python3.11/dist-packages (from streamlit) (0.10.2)\n",
            "Requirement already satisfied: typing-extensions<5,>=4.4.0 in /usr/local/lib/python3.11/dist-packages (from streamlit) (4.12.2)\n",
            "Collecting watchdog<7,>=2.1.5 (from streamlit)\n",
            "  Downloading watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl.metadata (44 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m44.3/44.3 kB\u001b[0m \u001b[31m2.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: gitpython!=3.1.19,<4,>=3.0.7 in /usr/local/lib/python3.11/dist-packages (from streamlit) (3.1.44)\n",
            "Collecting pydeck<1,>=0.8.0b4 (from streamlit)\n",
            "  Downloading pydeck-0.9.1-py2.py3-none-any.whl.metadata (4.1 kB)\n",
            "Requirement already satisfied: tornado<7,>=6.0.3 in /usr/local/lib/python3.11/dist-packages (from streamlit) (6.4.2)\n",
            "Requirement already satisfied: jinja2 in /usr/local/lib/python3.11/dist-packages (from altair<6,>=4.0->streamlit) (3.1.5)\n",
            "Requirement already satisfied: jsonschema>=3.0 in /usr/local/lib/python3.11/dist-packages (from altair<6,>=4.0->streamlit) (4.23.0)\n",
            "Requirement already satisfied: narwhals>=1.14.2 in /usr/local/lib/python3.11/dist-packages (from altair<6,>=4.0->streamlit) (1.29.0)\n",
            "Requirement already satisfied: gitdb<5,>=4.0.1 in /usr/local/lib/python3.11/dist-packages (from gitpython!=3.1.19,<4,>=3.0.7->streamlit) (4.0.12)\n",
            "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.11/dist-packages (from pandas<3,>=1.4.0->streamlit) (2.8.2)\n",
            "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas<3,>=1.4.0->streamlit) (2025.1)\n",
            "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas<3,>=1.4.0->streamlit) (2025.1)\n",
            "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.27->streamlit) (3.4.1)\n",
            "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.27->streamlit) (3.10)\n",
            "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.27->streamlit) (2.3.0)\n",
            "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.27->streamlit) (2025.1.31)\n",
            "Requirement already satisfied: smmap<6,>=3.0.1 in /usr/local/lib/python3.11/dist-packages (from gitdb<5,>=4.0.1->gitpython!=3.1.19,<4,>=3.0.7->streamlit) (5.0.2)\n",
            "Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.11/dist-packages (from jinja2->altair<6,>=4.0->streamlit) (3.0.2)\n",
            "Requirement already satisfied: attrs>=22.2.0 in /usr/local/lib/python3.11/dist-packages (from jsonschema>=3.0->altair<6,>=4.0->streamlit) (25.1.0)\n",
            "Requirement already satisfied: jsonschema-specifications>=2023.03.6 in /usr/local/lib/python3.11/dist-packages (from jsonschema>=3.0->altair<6,>=4.0->streamlit) (2024.10.1)\n",
            "Requirement already satisfied: referencing>=0.28.4 in /usr/local/lib/python3.11/dist-packages (from jsonschema>=3.0->altair<6,>=4.0->streamlit) (0.36.2)\n",
            "Requirement already satisfied: rpds-py>=0.7.1 in /usr/local/lib/python3.11/dist-packages (from jsonschema>=3.0->altair<6,>=4.0->streamlit) (0.23.1)\n",
            "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.11/dist-packages (from python-dateutil>=2.8.2->pandas<3,>=1.4.0->streamlit) (1.17.0)\n",
            "Downloading streamlit-1.43.1-py2.py3-none-any.whl (9.7 MB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m9.7/9.7 MB\u001b[0m \u001b[31m50.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hDownloading pydeck-0.9.1-py2.py3-none-any.whl (6.9 MB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m6.9/6.9 MB\u001b[0m \u001b[31m57.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hDownloading watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl (79 kB)\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m79.1/79.1 kB\u001b[0m \u001b[31m5.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hInstalling collected packages: watchdog, pydeck, streamlit\n",
            "Successfully installed pydeck-0.9.1 streamlit-1.43.1 watchdog-6.0.0\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "%%writefile app.py\n",
        "import streamlit as st\n",
        "import requests\n",
        "\n",
        "st.set_page_config(page_title=\"AI Health Assistant\", page_icon=\"πŸ€–\")\n",
        "\n",
        "st.title(\"🩺 AI Health Assistant\")\n",
        "st.write(\"Ask any medical-related questions:\")\n",
        "\n",
        "# User Input\n",
        "user_input = st.text_input(\"Your Question:\")\n",
        "\n",
        "# Button to Send Query\n",
        "if st.button(\"Ask\"):\n",
        "    response = requests.post(\"https://b7da-35-232-247-117.ngrok-free.app/query/\", json={\"user_input\": user_input})\n",
        "    bot_response = response.json().get(\"response\", \"Error fetching response\")\n",
        "\n",
        "    st.markdown(f\"**πŸ€– Bot:** {bot_response}\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "EDgP-RoV1hxA",
        "outputId": "57a5b4a3-846a-46fc-eb8b-c1c240132284"
      },
      "execution_count": 132,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Writing app.py\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "βœ… Steps to Deploy on Hugging Face Spaces\n",
        "πŸ“Œ Step 1: Create a Hugging Face Space\n",
        "1️⃣ Go to Hugging Face Spaces\n",
        "2️⃣ Click \"New Space\"\n",
        "3️⃣ Name the Space (e.g., AI-Health-Assistant)\n",
        "4️⃣ Select \"Streamlit\" as the SDK\n",
        "5️⃣ Click \"Create Space\" βœ…\n",
        "\n",
        "πŸ“Œ Step 2: Clone the Repository Locally\n",
        "After creating the Space, clone it to your local machine or Google Colab:\n",
        "\n",
        "```bash\n",
        "git clone https://huggingface.co/spaces/YOUR_USERNAME/AI-Health-Assistant\n",
        "cd AI-Health-Assistant\n",
        "```\n",
        "Replace YOUR_USERNAME with your Hugging Face username!\n",
        "\n",
        "πŸ“Œ Step 3: Add app.py (Your Streamlit Chatbot)\n",
        "Inside the cloned folder, create app.py and paste the following:\n",
        "\n",
        "πŸ“Œ Step 4: Create requirements.txt\n",
        "Create a new file requirements.txt inside the same folder and add:\n",
        "```bash\n",
        "streamlit\n",
        "requests\n",
        "```\n",
        "\n",
        "πŸ“Œ Step 5: Push Your Code to Hugging Face\n",
        "Run these commands to push the code:\n",
        "\n",
        "```bash\n",
        "git add .\n",
        "git commit -m \"Initial commit\"\n",
        "git push\n",
        "```\n",
        "πŸš€ Your Space will automatically start building!"
      ],
      "metadata": {
        "id": "4RG98k__4Yg1"
      }
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "Qem1BlA346Ke"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}