HOW 2 FIND THE NEAREST HOSPITAL FOR BED AVAILABILITY TO FIGHT CORONA VIRUS | RASA CHATBOT

finf the nearest hospital for bed availability | Innovate Yourself
1
0

OVERVIEW

In this blog, you will learn and understand how you can help other people in this tough time of pandemic to fight and survive the real life problem by building a smart helping hand that can tell you to find the details of the nearest hospital for bed availability or to find the other resources availability like oxygen cylinder, ventilator, plasma, etc. Now in this blog you will build the complete custom UI based chatbot that will completely help you to find the nearest hospital for bed availability and to give you the complete details of the hospital like ICU vacant beds, non ICU vacant beds, contact number, google map location, etc.

Here, is a small demo to show you that what exactly you will be able to achieve with the chatbot that you will start building now.

Now, I think you have generated an image in your mind that what exactly we will achieve after the completion of our project. Now, let’s start building our end to end chatbot to find the nearest hospital for bed availability.

Source of Data

Now let’s first understand and go through the websites that we will use here to fetch and present the real-time data through the rasa chatbot. Here are the links:

https://vasaicoronaresources.net/dashboard/
https://covid.army/
https://www.covidbedmbmc.in/

You can go though the above links and get the real-time details of the nearest hospital for bed availability. In our case we will use this link as a reference to fetch the results through web scraping and to display the results in real time. Now let’s start writing the code for web scraping to extract the data from the above website.

WEB SCRAPING TO EXTRACT REAL-TIME DATA

Now, lets use the above link to extract the useful data to present it further through chatbot. Now, let’s write the code to extract the data from the html page and to further extract the information. For doing this we will have to setup an environment that will include all the dependencies for the rasa chatbot plus the three important packages that we’ll have to install for the data extraction, that is, requests, html2text and textblob.

Now we’ll create a function that will accept the website link as an argument and will return you the list containing all the data available for the nearest hospital for bed availability on the website.

import pprint
import re
import time

import html2text
from textblob import TextBlob
import requests
import os

# data_path="files/"
# files=[i.name for i in os.scandir(data_path)]
beds = "https://www.covidbedmbmc.in/HospitalInfo/show"  # "https://coronabeds.jantasamvad.org/beds.html"
icu_beds = "https://coronabeds.jantasamvad.org/all-covid-icu-beds.html"


def bed_availability(beds):
    data = html2text.html2text(requests.get(beds).text)
    time.sleep(2)
    blob = TextBlob(data)
    # print(blob)
    x = blob.split("####")
    # print(x)
    j = [i for i in x if i.startswith(" **")]
    extract_out = []
    for hospital in j:
        try:
            contact = re.findall("[0-9]{10}", hospital)[0]
        except IndexError:
            contact = None
        hospital_name = hospital.split("\n")[0].replace('*', '')
        vacant_index = hospital.split("\n").index('Vacant')
        icu_vacant_index = hospital.split("\n").index('ICU Vacant')
        non_icu_vacant_index = hospital.split("\n").index('Non ICU Vacant')
        # print(vacant_index,icu_vacant_index,non_icu_vacant_index)

        vacant = hospital.split("\n")[vacant_index - 2].replace('*', '').replace(' ', '').replace('_', '')
        icu_vacant = hospital.split("\n")[icu_vacant_index - 2].replace('*', '').replace(' ', '').replace('_', '')
        non_icu_vacant = hospital.split("\n")[non_icu_vacant_index - 2].replace('*', '').replace(' ', '').replace('_',
                                                                                                                  '')
        # print(vacant,icu_vacant,non_icu_vacant)

        extract_out.append((hospital_name, contact, int(vacant), int(icu_vacant), int(non_icu_vacant)))
    return extract_out

In the above code you can see that we have divided the process of data extraction in few steps, first is to collect the data from the website in as it is format, second is to convert that html code to the text and then the last step is to manipulate the data for data extraction.

The code is written in such a way that it is a callable function that will accept the link as an input and will extract the needful data, that is, hospital name, contact number, total vacant beds, ICU vacant beds and Non ICU vacant beds. So, it will be easy for us to call this function as and when it is needed.
That is all about the data scraping part. Now, let’s start building our chatbot that will help us to find this information in the backend and to present it with smart conversational way having the hospital for bed availability.

BUILDING AN END TO END CHATBOT

Now as you know that we are making a chatbot cum helping hand that will help you find the nearest hospital for bed availability and other resources. First let’s understand what features you will be adding to your chatbot. So here is a list of features that you will now add to you chatbot to help you and your loved ones at the earliest.

  • Finding the vacant ICU beds
  • Finding the non vacant beds
  • Finding the area wise resources
  • Attaching the google map location of the hospital for bed availability
  • Connecting your chatbot to the website through socket.io

Here is the conversation stories that I’ll create and add now to my chatbot to find the nearest hospital for bed availability and other resources.

Story 1:
user: hello
bot: Are you looking for vacant beds? Yes/NO
user: No
bot: Thanks for the visit.
     Wear mask, wash your hands regularly and keep 3m distance from each other. 
     Stay Home, Stay safe.

Story 2:
user: hello
bot: Are you looking for vacant beds? Yes/NO
user: Yes
bot: What are you looking for? ICU vacant beds/Non ICU vacant beds
user: ICU vacant beds
bot: Sure let me check...
     Also check this link for area wise requirements: [COVID ARMY](https://covid.army/)
     Hospital:  St. Ann Hospital  ,       
                
     Contact: 9769070856 ,       
                
     Total Vacant: 17 ,       
                
     ICU Vacant: 3 ,       
                
     Location: "https://www.google.co.in/maps/search/St.+Ann+Hospital"
     Is there anything else that i can help you with? Yes/No

Story 3:
user: hello
bot: Are you looking for vacant beds? Yes/NO
user: Yes
bot: What are you looking for? ICU vacant beds/Non ICU vacant beds
user: Non ICU vacant beds
bot: Sure let me check...
     Also check this link for area wise requirements: [COVID ARMY](https://covid.army/)
     Hospital:  St. Ann Hospital  ,       
                
     Contact: 9769070856 ,       
                
     Total Vacant: 17 ,       
                
     Non ICU Vacant: 9 ,       
                
     Location: "https://www.google.co.in/maps/search/St.+Ann+Hospital"
     Is there anything else that i can help you with? Yes/No

So, here are the stories which now you will add to your project to make it work the same way that we have worked till now in the previous blogs for rasa chatbot. Now, add the below code to your nlu.yml, stories.yml, rules.yml and domain.yml to find the nearest hospital for bed availability and other resources..

nlu.yml

nlu:
- intent: ICU_Vacant_beds
  examples: |
    - I'm looking for ICU vacant beds.
    - just looking for ICU vacant beds.
    - i want icu vacant beds
- intent: Non_ICU_Vacant_beds
  examples: |
    - I'm looking for Non ICU vacant beds.
    - just looking for Non ICU vacant beds.
    - i need non icu vacant beds
stories.yml

stories:

- story: happy icu vacant beds path
  steps:
  - intent: affirm
  - action: utter_beds_type

- story: happy non icu vacant beds path
  steps:
  - intent: ICU_Vacant_beds
  - action: utter_sure
  - action: action_check_vacant_beds

- story: happy non icu vacant beds path
  steps:
  - intent: Non_ICU_Vacant_beds
  - action: utter_sure
  - action: action_check_non_icu_vacant_beds

- story: deny path
  steps:
  - intent: deny
  - action: utter_goodbye
rules.yml

rules:
- rule: Say `hello` when the user starts a conversation with intent `greet
  conversation_start: false
  steps:
  - intent: greet
  - action: utter_greet
domain.yml

intents:
- greet
  - goodbye
  - affirm
  - deny
  - bot_challenge
  - ICU_Vacant_beds
  - Non_ICU_Vacant_beds

responses:
  utter_greet:
  - text: "Are you looking for vacant beds?"
    buttons:
      - payload: "/affirm"
        title: "YES"
      - payload: "/deny"
        title: "NO"

  utter_beds_type:
  - text: "What are you looking for?"
    buttons:
      - payload: "/ICU_Vacant_beds"
        title: "ICU Vacant Beds"
      - payload: "/Non_ICU_Vacant_beds"
        title: "Non ICU Vacant Beds"

  utter_sure:
  - text: "Sure, let me check..."


  utter_goodbye:
  - text: "Thanks for the visit. \nWear mask, wash your hands regularly and keep 3m distance from each other. \nStay Home, Stay safe.\n"

  utter_iamabot:
  - text: "I am a bot, powered by Rasa."

  utter_also_check:
    - text: "Also check this link for area wise requirements: [COVID ARMY](https://covid.army/)"

actions:
  - action_check_icu_vacant_beds
  - action_check_non_icu_vacant_beds

session_config:
  session_expiration_time: 60
  carry_over_slots_to_new_session: true

With the above changes to the chatbot your story will work fine after training and you will be able to get the expected results as per above conversations that we are expecting. Now only the custom actions will not work as we haven’t set anything for it yet. To set the custom actions, first go to the endpoints.yml and uncomment the action_endpoints so that we can link our action server to the rasa server to get the expected results for finding the nearest hospital for bed availability and other resources..

After this now we will add the customs code in actions file to find the nearest hospital for bed availability (bot for non vacant ICU beds or vacant ICU beds). Here is the code that you have to add to your actions.py script,

import time
from typing import Any, Text, Dict, List

from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher

from main import bed_availability


class ActionCheckVacantBeds(Action):

    def name(self) -> Text:
        return "action_check_non_icu_vacant_beds"

    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        # time.sleep(2)
        beds = "https://www.covidbedmbmc.in/HospitalInfo/show"
        extract_output=bed_availability(beds)
        sorted_result=sorted(extract_output,key=lambda x:x[4],reverse=True)
        dispatcher.utter_message(text="Here are the top 5 hospitals having maximum vacant beds with there contact details,")
        top_five=""
        for (hospital_name, contact, vacant, icu_vacant, non_icu_vacant) in sorted_result[:5]:
            # if contact is not None:
                top_five+='''Hospital: {} ,
Contact: {} ,
Total Vacant: {} ,
Non ICU Vacant: {} ,
Location: "[{}](https://www.google.co.in/maps/search/{})"  ,
{}\n'''.format(hospital_name, contact, vacant, non_icu_vacant, hospital_name, hospital_name.strip().replace(" ", "+"), "*" * 50)

        # print(top_five)
        dispatcher.utter_message(text=top_five)
        dispatcher.utter_message(response="utter_also_check")
        dispatcher.utter_message(text="Is there anything else that i can help you with?",buttons=[
            {"title":"Yes","payload":"/affirm"},
            {"title":"NO","payload":"/deny"},
        ])
        return []


class ActionCheckVacentBeds(Action):

    def name(self) -> Text:
        return "action_check_icu_vacant_beds"

    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        # time.sleep(2)
        beds = "https://www.covidbedmbmc.in/HospitalInfo/show"
        extract_output=bed_availability(beds)
        sorted_result=sorted(extract_output,key=lambda x:x[3],reverse=True)
        dispatcher.utter_message(text="Here are the top 5 hospitals having maximum vacant beds with there contact details,")
        top_five=""
        for (hospital_name, contact, vacant, icu_vacant, non_icu_vacant) in sorted_result[:5]:
            # if contact is not None:
                top_five+='''Hospital: {} ,
Contact: {} ,
Total Vacant: {} ,
ICU Vacant: {} ,
Location: "[{}](https://www.google.co.in/maps/search/{})"  ,
{}\n'''.format(hospital_name, contact, vacant, icu_vacant,hospital_name,hospital_name.strip().replace(" ","+"), "*" * 50)

        # print(top_five)
        dispatcher.utter_message(text=top_five)
        dispatcher.utter_message(response="utter_also_check")
        dispatcher.utter_message(text="Is there anything else that i can help you with?", buttons=[
            {"title": "Yes", "payload": "/affirm"},
            {"title": "NO", "payload": "/deny"},
        ])
        return []

Check this link for more clarification,

HOSPITAL FOR BED AVAILABILITY WITH SOCKET.IO

Now, the complete code is done and you can find the nearest hospital for bed availability with the help of your chatbot. Now your chatbot will give you the replies as you may expect, but currently we can talk to our bot either thourh rasa shell or rasa x. Now, we want to deploy our chatbot on to a website through socket.io, so that anyone else can also talk to our chatbot and could find the nearest hospital for bed availability.

To do that we have to and two things one to the credentials.yml for rasa chatbot and the second one is to inject the script to the website where we are planning to deploy it. Here is the code that needs to be added to the credentials.yml to find the nearest hospital for bed availability and other resources,

credentials.yml:

socketio:
  user_message_evt: user_uttered
  bot_message_evt: bot_uttered
  session_persistence: true

Now, as per the changes in the script for the socket.io, here is the new script that you have to inject to your website for deployment,

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hospital Bed Availability</title>
</head>
<body bgcolor="#ddffff">

<img src="https://innovationyourself.com/wp-content/uploads/2020/07/WhatsApp-Image-2020-07-24-at-12.18.03-AM.jpeg" width="15%" height="15%" align="right" /><u><h1 align="center">Hospital Bed Availability</h1></u><br>
<img src="https://www.pinghd.com/wp-content/uploads/2021/02/Wear-a-mask-covid-19.png" width="75%" height="75%" />
<img src="https://www.pinghd.com/wp-content/uploads/2021/02/wash-hands-digitial-signage-landscape.jpg" width="75%" height="75%" />
<img src="https://www.pinghd.com/wp-content/uploads/2021/02/do-the-five-LS.jpg" width="75%" height="75%" />
<img src="https://www.pinghd.com/wp-content/uploads/2021/02/protect-yourself-covid-19-digital-signage-template.jpg" width="75%" height="75%" />


<script>!(function () {
  let e = document.createElement("script"),
    t = document.head || document.getElementsByTagName("head")[0];
  (e.src =
    "https://cdn.jsdelivr.net/npm/[email protected]/lib/index.js"),
    // Replace 1.x.x with the version that you want
    (e.async = !0),
    (e.onload = () => {
      window.WebChat.default(
        {
          selector: "#webchat",
          initPayload: "/greet",
          customData: {"language": "en"}, // arbitrary custom data. Stay minimal as this will be added to the socket
          socketUrl: "http://localhost:5005",
          socketPath: "/socket.io/",
          title: "Hospital Bed Availability",
          subtitle: "Find one, Save Life...",
          params: {"storage": "session"}
        },
        null
      );
    }),
    t.insertBefore(e, t.firstChild);
})();
</script>
</body>
</html>

Here, socketUrl is specified as per the local host that why we are using it in such a way, but if you have already deployed the chatbot on some VM instance or server then use the static ip address or domain of the server instead. Now, we have the complete code to find the nearest hospital for bed availability. Let’s train the model and try the code by running the rasa server and the action server together and find the nearest hospital for bed availability.

Now run the given commands parallelly on two terminals to start the action server and the rasa server.

rasa run --model models --enable-api --cors "*" --debug

and in second terminal,

rasa run actions

with these commands your rasa chatbot is activated and ready to talk and help you to find the nearest hospital for bed availability. Now open index.html file on the browser and see the chatbot in action.

Download the full code here,

FIND HOSPITAL FOR BED AVAILABILITY

find the nearest hospital for bed availability.

Time to wrap up now. Hope you liked our content on building a chatbot to find the nearest hospital for bed availability. See you in our next blog, thanks for reading our blog and do leave a comment below to help us improve the content to serve you all of our experience with you. Stay tuned with us for more rasa chatbot contents.

Also check out our other playlist Rasa Chatbot, Internet of things, Docker, Python Programming, etc.
Become a member of our social family on youtube here.

One thought on “HOW 2 FIND THE NEAREST HOSPITAL FOR BED AVAILABILITY TO FIGHT CORONA VIRUS | RASA CHATBOT

Leave a Reply