How to create offline chatbot using Anaconda Navigator (Spyder)

Preliminaries


A chatbot is an artificially intelligent software that simulates a conversation with a user in natural language through messaging applications, websites, mobile apps, telephone, etc.Users communicate with these tools using a chat interface or by voice, just like they would converse with another person. Chatbots interpret the words given to them by a person and provide a pre-set answer. There are many types of chatbots available, a few of them can be classified as follows:

  1. Text-based chatbot: In a text-based chatbot, a bot answers the user’s questions via text interface.

  2. Voice-based chatbot: In a voice or speech-based chatbot, a bot answers the user’s questions via a human voice interface (e.g., Apple Siri, Amazon Alexa, etc.)

Steps

Step 1: Packages to install in an offline chatbot

  1. We first need to install an apt Anaconda package based on system requirements.
  2. After installing the package, we must run these commands on Anaconda Prompt:
pip install wikipedia

pip install wolframalpha

Step 2: Import the data from the wolframalpha.py.txt text file into the Spyder application in the Anaconda Navigator, else you can use this code:

// # Wiki-Bandara - a virtual assistant using Wolfram Alpha and Wikipedia

## dependencies
## pip install wolframalpha
## pip install wikipedia


import wolframalpha
import wikipedia
import re


## Wikipedia search function
def search_wiki(keyword=''):

  # search in wikipedia
  searchResults = wikipedia.search(keyword)

  if not searchResults:
    message = "Sorry, No result from Wikipedia. Try again."
    response(message)
    return

  try:
    page = wikipedia.page(searchResults[0])

  except err:
    page = wikipedia.page(err.options[0])

  wikiTitle = str(page.title.encode('utf-8'))
  wikiSummary = str(page.summary.encode('utf-8'))

  return str(wikiSummary)[2:]


## Wolframalpha search function
def search(text=''):

  res = client.query(text)

  # check if query is resolved
  if res['@success'] == 'false':
     # search wikipedia if unsuccessful  
     response(search_wiki(text))
  else:
    result = ''
    # pod0 contains query and pod1 contains result
    pod0 = res['pod'][0]
    pod1 = res['pod'][1]
    if (('definition' in pod1['@title'].lower()) or ('result' in  pod1['@title'].lower()) or (pod1.get('@primary','false') == 'true')):
      
      result = resolveListOrDict(pod1['subpod'])
      return result
    else:
      question = resolveListOrDict(pod0['subpod'])
      question = question.split('(')[0]
      search_wiki(question)


def resolveListOrDict(variable):
  if isinstance(variable, list):
    return variable[0]['plaintext']
  else:
    return variable['plaintext']


## Bot activity function
def activity(data):

    # about bot
    if re.search("are you", data) or re.search("your name", data):
        listening = True
        intro = "I'm Wiki-Bandaara. I have access to Wolfram|Alpha and Wikipedia."
        response(intro)

    # bot help
    elif re.search("help", data) or re.search("you do", data):
        listening = True
        message = 'I have access to Wolfram|Alpha and Wikipedia. Ask anything. To get results from wikipedia, say so. To quit say bye or stop'
        response(message)

    # search only in wikipedia
    elif re.search("in wikipedia", data) or re.search("from wikipedia", data):
        listening = True
        result = search_wiki(data)
        if result!=None:
            response(result)

    # stop the bot
    elif re.search("stop", data) or re.search("bye", data) or re.search("quit", data):
        listening = False
        print('Bot: Bye')
        print('Listening stopped')
        return listening

    # search keyword
    else:
        listening = True
        result = search(data)
        if result is not None:
            response(result)
        else:
            message = "Please try again."
            response(message)

    return listening


## Text response function
def response(data):
    print('Bot:', data)
    

### main ###

## Wolframalpha App Id
appId = 'JH9XHR-W9J76L7H5A'
## Wolfram Instance
client = wolframalpha.Client(appId)


greet = "Hi there, what can I do for you?"
response(greet)

## loop till listening is False
listening = True
while listening == True:
    
    data = str(input('User: ')).lower()
    if data != '':
        listening = activity(data)
    else:
        message = "Please try again."
        response(message)

Step 3 : Run the code and give the inputs.

Free Resources