Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
community creator

How to create an Offline Chatbot

Jathin Reddy

Chatbot is a PC program that depends on standards or NLP and Machine Learning to “comprehend” and respond to conversational information.

We are now going to create an offline chatbot that searches on Wikipedia.

The packages that need to be installed to create the chatbot are:

  1. Install the Anaconda navigator Application based on the system requirements.
  2. Import the following commands on Spyder:
  • pip install wolfram alpha
  • pip install wikipedia
  1. Import the data from the text file WolframAlpha.py.tx into the Spyder application.

WolframAlpha.py.tx is a code file developed by WolframAlpha that computes expert level codes and answers using Wolfram’s algorithm and AI technology.

WolframAlpha is a knowledge engine that gives you detailed information on codes.

Step 1

Open the Anaconda navigator and select the Spyder application.

Step 2

Open the Spyder application, import the data from the text file WolframAlpha.py.tx into the Spyder application, and then run the code. Comments have been added in the code for a clear understanding.

# import statements
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)

In the code above, we have imported Wikipedia and WolframAlpha; we have added responses to each and every question asked by the user; and we have defined various functions like search, listening, and strings. If the search result is not found, then it will show, “no result from Wikipedia.” We have added different commands to create the bot’s functions.

Step 3

After successfully running the code, give inputs in the console box on the bottom right of the Spyder window.

We have now successfully created an offline chatbot using the WolframAlpha code!

The code given is self-generated from WolframAlpha.

RELATED TAGS

python
community creator
RELATED COURSES

View all Courses

Keep Exploring