AI BOTProject

Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

1.

1 FIGURES &ABBREVATIONS

1.2LIST OF FIGURES

S.NO. TOPIC PAGE NO.

1. ENTITY RELATIONAL DIAGRAM 17


2. DATA FLOW DIAGRAM 18
3. USE CASE DIAGRAM 20

1.3 LIST OF ABBREVATIONS

ABBREVATIONS DESCRIPTION

NLTK Natural Language Tool Kit


GUI Graphical User Interface
AI Artificial Intelligent
NLP Natural Language Processing

1
PROJECT OVERVIEW

2
2.1 PROJECT OVERVIEW

An AI desktop chatbot is a project that involves building an artificial intelligence-powered


computer program that can interact with users through a graphical user interface (GUI) on a
desktop computer. The chatbot uses natural language processing (NLP) and machine learning
algorithms to analyze and understand user input and provide relevant responses.

The project typically involves the following steps:

 Defining the purpose and scope of the chatbot: This involves determining the
chatbot's intended use and identifying the specific tasks it will perform, such as
answering inquiries, providing information and open system apps.

 Collecting and preprocessing data: This involves gathering data, such as chat logs or
knowledge bases, and preprocessing it to make it suitable for use in the chatbot.

 Designing and training the chatbot: This involves selecting an appropriate machine
learning algorithm and training the chatbot to recognize and respond to user input.

 Developing a graphical user interface: This involves using a GUI library, such as
tkinter to design and build the chatbot's interface on a desktop computer.

 Testing and refining the chatbot: This involves testing the chatbot's functionality and
refining its responses to improve its accuracy and effectiveness.

 Deployment and maintenance: This involves deploying the chatbot and ensuring it is
properly maintained and updated over time to ensure it remains effective and relevant.

Overall, building an AI desktop chatbot is a complex and involved project that requires
expertise in natural language processing, machine learning, and graphical user interface
design.

3
2.2 INTRODUCTION

An AI desktop chatbot project involves building a computer program that can interact with
users through a graphical user interface (GUI) on a desktop computer. The chatbot is
powered by artificial intelligence (AI) and uses natural language processing (NLP) and
machine learning algorithms to understand user input and provide relevant responses.

The purpose of an AI desktop chatbot is to improve user engagement and efficiency by


automating tasks and providing quick and accurate responses to user inquiries. The chatbot
can be used for a wide range of applications, such as get result from google/Wikipedia, open
system applications, play music and etc.,

Building an AI desktop chatbot project typically involves gathering and preprocessing data,
selecting an appropriate machine learning algorithm, training the chatbot to recognize and
respond to user input, designing and developing the chatbot's graphical user interface, and
testing and refining the chatbot's functionality.

Overall, an AI desktop chatbot project requires expertise in several areas, including natural
language processing, machine learning, and graphical user interface design. However, with
the right skills and tools, it is possible to create a powerful chatbot that can enhance user
engagement and automate various tasks, making it a valuable tool for businesses and
individuals alike

4
2.3 ABSTRACT
An AI desktop chatbot project is a computer program that uses artificial intelligence
and natural language processing to communicate with users through a graphical user interface
on a desktop computer. The project involves gathering and preprocessing data, selecting an
appropriate machine learning algorithm, training the chatbot to recognize and respond to user
input, designing and developing the chatbot's graphical user interface, and testing and
refining the chatbot's functionality. The chatbot can be used for a wide range of applications,
get answer from google, open system apps and conversation with user.

OBJECTIVES
The main objectives of an AI desktop chatbot project are to:
 Provide quick and accurate responses to user inquiries
 Open system apps.
 Improve user engagement by providing a conversational interface
 Reduce workload by handling routine inquiries
 Get correct answer from google

PURPOSE
The purpose of this AI desktop chatbot is to get result from google/Wikipedia and
open system apps, enhance user engagement, and improve overall user experience. With the
increasing demand for efficient and personalized customer service, this chatbot will help
businesses to provide 24/7 support to their user. It will reduce the workload on human agents
and improve response times, leading to increased customer satisfaction. Additionally, the
chatbot will be able to collect data on user interactions, which can be used to improve the
chatbot's performance over time.

5
SYSTEM STUDY

6
3.1 SYSTEM STUDY

Choose a framework: The first step is to choose a Python framework for building your
chatbot. There are several options available. I used ktinker.

Design your chatbot: Decide what your chatbot will do, what questions it will answer,
and what kind of responses it will give.

Collect data: To train your chatbot, you'll need to collect a large amount of data in the
form of text response data.

Build a natural language processing (NLP) model: This is where you use machine
learning algorithms to train your chatbot to understand and respond to natural
language. Python libraries such as NLTK and TensorFlow can be used to build your
NLP model.

3.2 EXISTING WORK

 People search whatever they need in system search themselves.


 If people need some in google/Wikipedia the user goes chrome/edge or
anything and search what they need it take lot of time.
 If they any doubt in particular job every time they ask his senior o r higher
position person.

3.3 PROPOSED WORK

 As part of the proposed system, built an AI Desktop chatbot application.


 User can interact with chatbot through GUI (Graphical User Interface).
 This chatbot communicate with user and solve users questions and get answer
from Google/Wikipedia in fraction of second and it has some function like
open camera, mail and more system apps.

7
SYSTEM
REQUIREMENTS

8
4.1 SYSTEM REQUIREMENTS

4.2 SOFTWARE REQUIREMENT

 Coding: Visual Studio Code

To edit or modify the coding part in the project

User interface : Ktinter (GUI)

Execution of the project through the internet and offline

4.3 HARDWARE REQUIREMENT:

 Operating systems: Windows 11

It manages the computer's memory and processes, as well as all of its software and
hardware.

 Processors: AMD 5000 Series

Provides the instructions and processing power the computer needs to do its work.

 Ram: 4 GB.

It is used as a short-term memory for computers to place its data for easy access.

 Rom: 500 GB.

It is essential for the storage and operation of the BIOS, but it can also be used for
basic data management, to hold software for basic processes of utilities and to read and write
to peripheral devices.

9
TECHNOLOGIES

10
5.2 FRONT-END DEVELOPMENT
Ktinter (GUI) Frame work

Tkinter is a Python library used for creating graphical user interfaces (GUIs). It is based on
the Tk GUI toolkit and provides a set of widgets that can be used to build GUIs, including
buttons, labels, and text boxes. Tkinter is included with Python and works on all major
platforms, making it a popular choice for developers. With Tkinter, you can create custom
graphics and animations, handle events, and create custom widgets and dialog boxes. Overall,
Tkinter is a powerful and versatile library for building GUIs in Python.

5.3 BACK-END DEVELOPMENT

PYTHON
Python is a popular programming language used for a wide range of applications,
including web development, data analysis, machine learning, and scientific computing. It is
an open-source language, which means that its source code is freely available and can be
modified by developers to suit their needs.

Python is known for its simplicity, readability, and ease of use. It has a clean and
straightforward syntax that is easy to learn and understand, making it an ideal language for
beginners. Python also has a large and active developer community, which means that there
are plenty of resources and support available for those who need it.

Python is used in web development to create web applications and server-side


programming. It can be used with popular web frameworks such as Django and Flask, which
provide a powerful and flexible platform for building web applications. Python's versatility
makes it an excellent choice for building a wide range of web applications, from simple
websites to complex enterprise systems.

Python is also widely used in data analysis and machine learning. It provides a wide
range of libraries and tools for working with data, including NumPy, Pandas, and SciPy.
These tools allow developers to perform complex data analysis, build predictive models, and
create visualizations and dashboards.

Another key benefit of Python is its portability. It can be used on a wide range of
platforms and operating systems, including Windows, macOS, and Linux. Python's
portability makes it an ideal language for developing applications that need to run on multiple
platforms or devices.

11
Python is used by many of the world's largest and most popular companies, including
Google, Facebook, and Amazon. It is a powerful and reliable tool for web development, data
analysis, and machine learning, and its popularity shows no signs of slowing down.

Overall, Python is an essential technology for anyone interested in programming and


technology. By learning Python, you can gain the skills and knowledge needed to create
powerful and dynamic applications that provide a seamless user experience.

LIBRARIES
Numpy Library

NumPy is a Python library that provides support for large, multi-dimensional arrays
and matrices, along with a large collection of high-level mathematical functions to operate on
these arrays. It is an essential library for scientific computing and data analysis in Python.

Here are some key features and benefits of NumPy:

Multi-dimensional arrays: NumPy arrays are much more efficient than regular
Python arrays for handling large amounts of data. They can be used to store and manipulate
large multi-dimensional arrays of data, such as images, audio signals, or numerical
simulations.

Broadcasting: NumPy provides broadcasting, which is a powerful mechanism for


applying operations to arrays of different shapes and sizes. This makes it easy to perform
element-wise operations on arrays with different dimensions and shapes.

Mathematical functions: NumPy provides a large collection of mathematical


functions to operate on arrays, including basic functions such as sine, cosine, and logarithm,
as well as more advanced functions such as Fourier transforms and linear algebra functions.

Integration with other Python libraries: NumPy integrates well with other Python
libraries for scientific computing, such as SciPy, Matplotlib, and Pandas. These libraries build
on top of NumPy to provide additional functionality for data analysis and visualization.

12
Speed: NumPy is implemented in C and optimized for speed, making it much faster
than pure Python code for numerical operations. This makes it ideal for processing large
datasets and running computationally intensive algorithms.

PyTorch Library

PyTorch is a popular open-source machine learning library for the Python


programming language, developed primarily by Facebook's AI research team. It is based on
the Torch library, which is a scientific computing framework for Lua programming language.
PyTorch provides a variety of tools and functionalities for building and training deep neural
networks. It has gained popularity due to its ease of use and flexibility, making it a preferred
choice for many researchers and developers.

PyTorch provides two key features:

Tensor computation: PyTorch provides a powerful N-dimensional array called


torch.Tensor with functionalities to perform operations on them. It provides support for
various data types and devices, such as CPU and GPU.

Deep neural networks: PyTorch provides a comprehensive library of tools to build,


train, and evaluate deep neural networks. It provides a modular approach to building
networks, where users can construct custom networks by combining pre-built layers and
modules. PyTorch supports various activation functions, loss functions, and optimizers,
making it easy to customize network architecture and optimization techniques.

Some key features of PyTorch are:

Dynamic computation graph: Unlike other popular deep learning libraries like
TensorFlow, PyTorch uses a dynamic computation graph approach where the graph is built
during runtime. This makes it easier to debug, modify, and experiment with network
architecture.

Distributed computing: PyTorch provides support for distributed training, making it


easier to train large models on multiple GPUs and multiple machines.

13
Easy debugging: PyTorch provides a rich set of tools for debugging deep neural
networks. For instance, users can easily visualize the gradients of their model, track memory
usage, and monitor training progress in real-time.

Interoperability: PyTorch provides an easy-to-use API to convert models from other


popular deep learning frameworks like TensorFlow and Keras, making it easier to switch
between frameworks

NLKT Library

NLTK (Natural Language Toolkit) is a popular open-source library for natural


language processing (NLP) tasks in Python. It provides a wide range of tools and functions to
analyze and process human language data. NLTK is widely used in various NLP tasks,
including text classification, sentiment analysis, part-of-speech tagging, and machine
translation.

Some key features of NLTK are:

Tokenization: NLTK provides a variety of tokenization functions to split text into


words, sentences, or other linguistic units.

Part-of-speech tagging: NLTK provides tools to automatically tag words with their
corresponding part-of-speech, such as noun, verb, adjective, etc.

Sentiment analysis: NLTK provides tools to analyze the sentiment of a given text,
whether it is positive, negative, or neutral.

Stemming and Lemmatization: NLTK provides tools to reduce words to their base
form, such as stemming and lemmatization, which can help in reducing the vocabulary size
and improving the accuracy of models.

Parsing: NLTK provides tools to parse sentences and analyze their grammatical
structure, such as dependency parsing, constituency parsing, and semantic role labeling.

14
Machine learning: NLTK provides tools to build machine learning models for NLP
tasks, such as Naive Bayes, Maximum Entropy, and Decision Trees.

Corpora and resources: NLTK provides access to various linguistic corpora and
resources, including word lists, stop words, and language models.

Overall, NLTK is a powerful library for NLP tasks in Python, providing a range of
tools and functions to process and analyze human language data. It is easy to use and widely
adopted in academia and industry

WinShell Library

WinShell is a Python library that provides a set of functions for working with
Windows shell objects, such as files, folders, and shortcuts. It allows you to create, modify,
and delete these objects, as well as access their properties and perform other operations.

One of the key features of WinShell is its ability to work with shortcut files (.lnk). It
allows you to create, modify, and delete shortcuts, as well as access their properties, such as
the target file, working directory, and command-line arguments. This can be particularly
useful if you need to create shortcuts to frequently used files or applications, or if you want to
modify existing shortcuts to update their properties.

WinShell also provides functions for working with files and folders, such as copying,
moving, and deleting them. It supports both absolute and relative file paths, as well as
wildcard patterns for matching multiple files. Additionally, it provides functions for
retrieving information about files and folders, such as their size, creation and modification
dates, and attributes.

Another useful feature of WinShell is its ability to interact with the Windows registry.
It provides functions for creating, modifying, and deleting registry keys and values, as well as
retrieving information about existing keys and values. This can be particularly useful if you
need to modify system settings or access application-specific configuration data.

Overall, WinShell is a powerful library that can be extremely useful for a wide range
of Windows scripting and automation tasks. Whether you need to work with files, folders,
shortcuts, or the registry, WinShell provides a simple and intuitive API that makes it easy to
get the job done

15
OS Library

The "os" library in Python provides a way to interact with the operating system. It allows you
to access system-specific functionality, such as creating and deleting files, navigating the file system,
and executing system commands.

Here are some of the key features of the "os" library:

File and Directory Operations: The "os" library allows you to create, delete, move, and
copy files and directories. You can also get information about files and directories, such as their size,
creation time, and modification time.

Process Management: The "os" library provides functions for creating and managing new
processes. You can start new processes, wait for them to complete, and get information about running
processes.

Environment Variables: The "os" library allows you to access and modify environment variables.
You can get the value of an environment variable, set a new value, or delete an existing variable.

Operating System Information: The "os" library provides functions for getting information
about the operating system. You can get the name of the operating system, the current user name, and
the current working directory.

System Commands: The "os" library allows you to execute system commands. You can run
commands in the system shell, and get the output of the command.

Overall, the "os" library is a powerful tool for working with the operating system in Python. It
provides a way to interact with the file system, manage processes, access environment variables, get
operating system information, and execute system commands. The "os" library is platform-
independent, which means that you can use the same code on different operating systems.

16
Json Library
The "json" library in Python provides a way to work with JSON (JavaScript Object
Notation) data. JSON is a lightweight data interchange format that is easy for humans to read
and write, and easy for machines to parse and generate.

Here are some of the key features of the "json" library:

JSON Parsing and Encoding: The "json" library allows you to parse JSON data into
Python objects, and encode Python objects into JSON data. You can convert Python
dictionaries, lists, and other objects to JSON format, and vice versa.

Customizable Encoding and Decoding: The "json" library provides functions for
customizing the encoding and decoding process. You can define custom serialization and
deserialization functions for specific data types, or modify the default behavior of the
encoding and decoding process.

Error Handling: The "json" library provides functions for handling errors that may
occur during the encoding or decoding process. You can catch and handle errors such as
invalid JSON syntax or unsupported data types.

Streaming Support: The "json" library allows you to stream JSON data, which is
useful for working with large data sets. You can read and write JSON data incrementally,
without loading the entire data set into memory at once.

Overall, the "json" library is a powerful tool for working with JSON data in Python. It
provides a way to parse and generate JSON data, customize the encoding and decoding
process, handle errors, and support streaming. The "json" library is widely used in web
applications and APIs, where JSON is a common data format for exchanging data between
client and server.

17
PYWhatKit Library
PyWhatKit is a Python library that provides a variety of tools and utilities for
developers. It allows developers to perform a wide range of tasks, including sending
WhatsApp messages, generating QR codes, searching for information on Google, and much
more.

Here are some of the main features of PyWhatKit:

Send WhatsApp messages: PyWhatKit makes it easy to send WhatsApp messages


using Python. You can send messages to individuals or groups, and you can even send
images and videos.

Generate QR codes: The library allows developers to generate QR codes using


Python. You can generate QR codes for URLs, text, or even entire files.

Search for information: With PyWhatKit, you can search for information on
Google, Wikipedia, or other online sources. You can retrieve search results, summaries, and
even the full text of articles.

Convert text to handwriting: The library also allows developers to convert text to
handwriting. You can choose from different handwriting styles and even adjust the thickness
of the pen strokes.

Play text-to-speech: PyWhatKit also provides the ability to convert text to speech.
You can choose from different voices and even adjust the speed of the speech.

Overall, PyWhatKit is a versatile and useful library for developers who want to add
additional functionality to their Python projects.

18
SYSTEM DESIGN

19
6.2 MODULES

The system has a different segment to process a specific task which is the modules.
This will help the system to develop easily and makes it more user-friendly.

Modules of the projects

Chat area module

Chat area module is a main and first module of this project. It is a chat area helps to
chat with chatbot. It is made up of Ktinter framework.

Training Module

Training module is helps to train a cropes data from “intents.json”. This module train
a data with a help of tokenization, stemming and bag of words.

20
SYSTEM ANALYSIS

21
8.1 ER DIAGRAM
 E-R (Entity-Relationship) Diagram is used to represents the relationship between
entities in a table.
 ER diagrams represent the logical structure of databases. ER Diagram represent
relationship between two database tables.
 Helps you to define terms related to entity relationship modeling.
 Provide a preview of how all your tables should connect, what fields are going to be
on each table
 Helps to describe entities, attributes, relationships
 ER diagrams are translatable into relational tables which allows you to build
databases quickly
 ER diagrams can be used by database designers as a blueprint for implementing data
in specific software applications.

ER DIAGRAM

22
8.2 DATA FLOW DIAGRAM
 A Data Flow Diagram (DFD) is a graphical representation of the “flow” of Student
Management System.
 A data flow diagram can also be used for the visualization of Data Processing.
 DFD shows the interaction between the system and outside entities.
 A DFD represents flow of data through a system.
 Data flow diagrams are commonly used during problem analysis.
 It views a system as function that transforms the given input into required output.
 Movement of data through the different transformations or processes in the system is
shown in Data Flow Diagram.

8.2.1 DATA FLOW DIAGRAM

23
8.3 USE CASE DIAGRAM
This part contains the analysis of the functional and non-functional requirements
using use-case diagrams, and use-cases details.

24
CODING

25
9.SAMPLE CODING

INTENTS.JASON
{

"intents": [

"tag": "greeting",

"patterns": [

"Hi",

"Hey",

"How are you",

"Is anyone there?",

"Hello",

"Good day"

],

"responses": [

"Hey :-)",

"Hello, thanks for visiting",

"Hi there, what can I do for you?",

"Hi there, how can I help?"

},

"tag": "name",

"patterns": [ "What is your name ?"],

26
"responses": [

"My name is 'Luna'"

},

"tag": "self",

"patterns": [ "Tell about your self", "See you later",


"Goodbye"],

"responses": [

"My self Luna. I'm your personal assistant."

},

"tag": "creator",

"patterns": [ "Who is created you ?", "your creator name


?"],

"responses": [

"Hemanth Prasath is my creator."

},

"tag": "functions",

"patterns": ["what function can you do ?", "what can you


do ?", "your able functions"],

"responses": [

27
"Open Camera , Open browser , Open mail , Get result
From Google (or) Wikipedia and more..,"

},

"tag": "goodbye",

"patterns": ["Bye", "See you later", "Goodbye"],

"responses": [

"See you later, thanks for visiting",

"Have a nice day",

"Bye! Come back again soon."

},

"tag": "thanks",

"patterns": ["Thanks", "Thank you", "That's helpful",


"Thank's a lot!"],

"responses": ["Happy to help!", "Any time!", "My


pleasure"]

},

"tag": "open_chrome",

"patterns": [

"hey open chrome", "open chrome",

"chrome"

],

28
"responses": [

"Sure..!"

},

"tag": "open_camera",

"patterns": [

"hey open camera", "open camera",

"camera"

],

"responses": [

"Sure..!"

},

"tag": "open_mail",

"patterns": [

"hey open mail", "open mail",

"mail"

],

"responses": [

"Sure..!"

29
]

APP.PY
from tkinter import *

from chat import get_response, bot_name

from tkinter import scrolledtext

BG_GRAY = "#ABB2B9"

BG_COLOR = "#17202A"

TEXT_COLOR = "#EAECEE"

FONT = "Helvetica 14"

FONT_BOLD = "Helvetica 13 bold"

class ChatApplication:

def __init__(self):

self.window = Tk()

self._setup_main_window()

def run(self):

self.window.mainloop()

def _setup_main_window(self):

self.window.title("Luna")

30
self.window.resizable(width=False, height=False)

self.window.configure(width=470, height=550,
bg=BG_COLOR)

# head label

head_label = Label(self.window, bg=BG_COLOR,


fg=TEXT_COLOR,

text="Welcome", font=FONT_BOLD,
pady=10)

head_label.place(relwidth=1)

# tiny divider

line = Label(self.window, width=450, bg=BG_GRAY)

line.place(relwidth=1, rely=0.07, relheight=0.012)

# text widget

self.text_widget =
scrolledtext.ScrolledText(self.window, width=20, height=2,
bg=BG_COLOR, fg=TEXT_COLOR,

font=FONT, padx=5,
pady=5,wrap=WORD)

self.text_widget.place(relheight=0.745, relwidth=1,
rely=0.08)

self.text_widget.configure(cursor="arrow",
state=DISABLED)

31
# bottom label

bottom_label = Label(self.window, bg=BG_GRAY, height=80)

bottom_label.place(relwidth=1, rely=0.825)

# message entry box

self.msg_entry = Entry(bottom_label, bg="#2C3E50",


fg=TEXT_COLOR, font=FONT)

self.msg_entry.place(relwidth=0.74, relheight=0.06,
rely=0.008, relx=0.011)

self.msg_entry.focus()

self.msg_entry.bind("<Return>", self._on_enter_pressed)

# send button

send_button = Button(bottom_label, text="Send",


font=FONT_BOLD, width=20, bg=BG_GRAY,

command=lambda:
self._on_enter_pressed(None))

send_button.place(relx=0.77, rely=0.008, relheight=0.06,


relwidth=0.22)

def _on_enter_pressed(self, event):

msg = self.msg_entry.get()

self._insert_message(msg, "You")

def _insert_message(self, msg, sender):

if not msg:

return

32
self.msg_entry.delete(0, END)

msg1 = f"{sender}: {msg}\n\n"

self.text_widget.configure(state=NORMAL)

self.text_widget.insert(END, msg1)

self.text_widget.configure(state=DISABLED)

msg2 = f"{bot_name}: {get_response(msg)}\n\n"

self.text_widget.configure(state=NORMAL)

self.text_widget.insert(END, msg2)

self.text_widget.configure(state=DISABLED)

self.text_widget.see(END)

if __name__ == "__main__":

app = ChatApplication()

app.run()

CHAT.PY
import random

import json

import os

import wikipedia as wp

import webbrowser

import torch

33
from datetime import *

import winshell

from model import NeuralNet

from nltk_utils import bag_of_words, tokenize

device = torch.device('cuda' if torch.cuda.is_available() else


'cpu')

with open('intents.json', 'r') as json_data:

intents = json.load(json_data)

FILE = "data.pth"

data = torch.load(FILE)

input_size = data["input_size"]

hidden_size = data["hidden_size"]

output_size = data["output_size"]

all_words = data['all_words']

tags = data['tags']

model_state = data["model_state"]

model = NeuralNet(input_size, hidden_size,


output_size).to(device)

model.load_state_dict(model_state)

model.eval()

34
bot_name = "Luna"

def open_camera():{

os.system('cmd /c "start microsoft.windows.camera:"')

def open_mail():{

os.system('cmd /c "start outlookmail:"')

def search_wiki(msg):{

def get_response(msg):

if 'chrome' in msg:

webbrowser.open('www.google.com')

return "Opened"

if 'camera' in msg:

os.system('cmd /c "start microsoft.windows.camera:"')

return "opened"

if 'mail' in msg:

os.system('cmd /c "start outlookmail:"')

return "opened"

35
if 'calender' in msg:

os.system('cmd /c "start outlookcal:"')

return "opened"

if 'map' in msg:

os.system('cmd /c "start ms-drive-to:"')

return "opened"

if 'edge' in msg:

os.system('cmd /c "start microsoft-edge:"')

return "opened"

if 'paint' in msg:

os.system('cmd /c "start ms-paint:"')

return "opened"

if 'photo' in msg:

os.system('cmd /c "start ms-photos:"')

return "opened"

if 'settings' in msg:

os.system('cmd /c "start ms-settings:"')

return "opened"

if 'security' in msg:

os.system('cmd /c "start windowsdefender:"')

return "opened"

if 'time' in msg:

now = datetime.now()

current_time = now.strftime("%H:%M:%S")

return "opened"

36
if 'empty recycle bin' in msg:

winshell.recycle_bin().empty(confirm=False,
show_progress=False, sound=False)

return "Cleared"

elif "music" in msg:

l = os.listdir('./music')

f = ''

lt = ['mp3','wav','avi']

for i in l:

if i.split('.')[-1].lower() in lt:

f = os.getcwd()+'/music/'+i

break

if f=='':

return 'No audio file found'

else:

print(f)

os.popen(f)

return 'playing...'

elif "search" in msg or 'wiki' in msg:

return wp.summary(msg.split('search')[-1], sentences =


2)

sentence = tokenize(msg)

X = bag_of_words(sentence, all_words)

X = X.reshape(1, X.shape[0])

37
X = torch.from_numpy(X).to(device)

output = model(X)

_, predicted = torch.max(output, dim=1)

tag = tags[predicted.item()]

probs = torch.softmax(output, dim=1)

prob = probs[0][predicted.item()]

if prob.item() > 0.75:

for intent in intents['intents']:

if tag == intent["tag"]:

return random.choice(intent['responses'])

return "I do not understand..."

TRAIN.PY
import numpy as np

import random

import json

import torch

import torch.nn as nn

from torch.utils.data import Dataset, DataLoader

from nltk_utils import bag_of_words, tokenize, stem

38
from model import NeuralNet

with open('intents.json', 'r') as f:

intents = json.load(f)

all_words = []

tags = []

xy = []

# loop through each sentence in our intents patterns

for intent in intents['intents']:

tag = intent['tag']

# add to tag list

tags.append(tag)

for pattern in intent['patterns']:

# tokenize each word in the sentence

w = tokenize(pattern)

# add to our words list

all_words.extend(w)

# add to xy pair

xy.append((w, tag))

# stem and lower each word

ignore_words = ['?', '.', '!']

all_words = [stem(w) for w in all_words if w not in


ignore_words]

# remove duplicates and sort

39
all_words = sorted(set(all_words))

tags = sorted(set(tags))

print(len(xy), "patterns")

print(len(tags), "tags:", tags)

print(len(all_words), "unique stemmed words:", all_words)

# create training data

X_train = []

y_train = []

for (pattern_sentence, tag) in xy:

# X: bag of words for each pattern_sentence

bag = bag_of_words(pattern_sentence, all_words)

X_train.append(bag)

# y: PyTorch CrossEntropyLoss needs only class labels, not


one-hot

label = tags.index(tag)

y_train.append(label)

X_train = np.array(X_train)

y_train = np.array(y_train)

# Hyper-parameters

num_epochs = 1000

batch_size = 8

learning_rate = 0.001

40
input_size = len(X_train[0])

hidden_size = 8

output_size = len(tags)

print(input_size, output_size)

class ChatDataset(Dataset):

def __init__(self):

self.n_samples = len(X_train)

self.x_data = X_train

self.y_data = y_train

# support indexing such that dataset[i] can be used to get


i-th sample

def __getitem__(self, index):

return self.x_data[index], self.y_data[index]

# we can call len(dataset) to return the size

def __len__(self):

return self.n_samples

dataset = ChatDataset()

train_loader = DataLoader(dataset=dataset,

batch_size=batch_size,

shuffle=True,

num_workers=0)

41
device = torch.device('cuda' if torch.cuda.is_available() else
'cpu')

model = NeuralNet(input_size, hidden_size,


output_size).to(device)

# Loss and optimizer

criterion = nn.CrossEntropyLoss()

optimizer = torch.optim.Adam(model.parameters(),
lr=learning_rate)

# Train the model

for epoch in range(num_epochs):

for (words, labels) in train_loader:

words = words.to(device)

labels = labels.to(dtype=torch.long).to(device)

# Forward pass

outputs = model(words)

# if y would be one-hot, we must apply

# labels = torch.max(labels, 1)[1]

loss = criterion(outputs, labels)

# Backward and optimize

optimizer.zero_grad()

42
loss.backward()

optimizer.step()

if (epoch+1) % 100 == 0:

print (f'Epoch [{epoch+1}/{num_epochs}], Loss:


{loss.item():.4f}')

print(f'final loss: {loss.item():.4f}')

data = {

"model_state": model.state_dict(),

"input_size": input_size,

"hidden_size": hidden_size,

"output_size": output_size,

"all_words": all_words,

"tags": tags

FILE = "data.pth"

torch.save(data, FILE)

print(f'training complete. file saved to {FILE}')

43
NLTK_UTILS.PY
import numpy as np

import nltk

nltk.data.path.append('E:\nltk-develop\nltk\tokenize')

from nltk.tokenize import sent_tokenize

from nltk.stem.porter import PorterStemmer

stemmer = PorterStemmer()

def tokenize(sentence):

"""

split sentence into array of words/tokens

a token can be a word or punctuation character, or number

"""

return nltk.word_tokenize(sentence)

def stem(word):

"""

stemming = find the root form of the word

examples:

words = ["organize", "organizes", "organizing"]

words = [stem(w) for w in words]

-> ["organ", "organ", "organ"]

"""

return stemmer.stem(word.lower())

44
def bag_of_words(tokenized_sentence, words):

"""

return bag of words array:

1 for each known word that exists in the sentence, 0


otherwise

example:

sentence = ["hello", "how", "are", "you"]

words = ["hi", "hello", "I", "you", "bye", "thank", "cool"]

bog = [ 0 , 1 , 0 , 1 , 0 , 0 , 0]

"""

# stem each word

sentence_words = [stem(word) for word in tokenized_sentence]

# initialize bag with 0 for each word

bag = np.zeros(len(words), dtype=np.float32)

for idx, w in enumerate(words):

if w in sentence_words:

bag[idx] = 1

return bag

MODELS.PY
mport torch

import torch.nn as nn

45
class NeuralNet(nn.Module):

def __init__(self, input_size, hidden_size, num_classes):

super(NeuralNet, self).__init__()

self.l1 = nn.Linear(input_size, hidden_size)

self.l2 = nn.Linear(hidden_size, hidden_size)

self.l3 = nn.Linear(hidden_size, num_classes)

self.relu = nn.ReLU()

def forward(self, x):

out = self.l1(x)

out = self.relu(out)

out = self.l2(out)

out = self.relu(out)

out = self.l3(out)

# no activation and no softmax at the end

return out

46
SCREENSHOTS

47
10. SCREENSHOTS

TRAIN CHATBOT

EXECUTE FUNCTIONS

48
PLAY MUSIC

INTERACTION WITH USER

49
GOOGLE SEARCH

WIKIPEDIA SEARCH

50
YOU TUBE SEARCH

51
CONCLUSION

52
11.1 CONCLUSION
In conclusion, building an AI desktop chatbot using Python can be a challenging but
rewarding project. With the right tools and resources, you can create a chatbot that can
understand and respond to user inputs, automate tasks, and provide useful information.

Some of the key considerations when building a chatbot include choosing a suitable
platform or framework, selecting appropriate natural language processing (NLP) and machine
learning algorithms, and designing a user-friendly interface.

Python offers a wide range of libraries and tools for building chatbots, including Natural
Language Toolkit (NLTK). This tool can be used to build powerful chatbots that can understand
and respond to complex user queries.

Overall, building an AI desktop chatbot using Python can be a valuable learning experience and
can provide a useful tool for automating tasks and providing support to users.

53
11.2 FUTURE ENHANCEMENT
There are several future enhancements that can be made to an AI desktop chatbot built
using Python to improve its performance and functionality. Some of these enhancements include:

Adding more functionality: The chatbot can be expanded to perform additional tasks
such as making reservations, ordering food, or booking appointments. This can be achieved by
integrating the chatbot with relevant APIs or developing custom modules.

Personalization: The chatbot can be customized to provide a personalized experience to


users based on their preferences and previous interactions. This can be achieved by incorporating
user profiling and machine learning algorithms to understand user behavior and preferences.

Multilingual support: The chatbot can be enhanced to support multiple languages,


allowing users from different regions to interact with the chatbot in their native language.

Voice-based interactions: The chatbot can be upgraded to support voice-based


interactions, enabling users to interact with the chatbot through speech rather than text.

Integration with other platforms: The chatbot can be integrated with other platforms
such as social media, email, or messaging applications to provide a seamless experience across
multiple channels.

Continuous learning: The chatbot can be enhanced to continuously learn from user
interactions and improve its performance over time. This can be achieved by incorporating
reinforcement learning algorithms and feedback mechanisms.

Overall, there are many ways to enhance an AI desktop chatbot built using Python, and
these enhancements can provide a better user experience and improve the chatbot's performance
and functionality.

54
BIBLIOGRAPHY

55
12.1REFRENCES
1) Python Programming a Modular Approach Sheetal Tanja & Naveen Kumar
2) Learn AI with Python BPB PUBLICATIONS
3) Machine Learning with PyTorch and Scikit-Learn Sebastian Raschka
4) Building ChatBots With Python Sumit Raj
5) Artificial Intelligence: The ChatBot In Python Yeeshtdevisingh Hosanee

56

You might also like