AI BOTProject
AI BOTProject
AI BOTProject
1 FIGURES &ABBREVATIONS
1.2LIST OF FIGURES
ABBREVATIONS DESCRIPTION
1
PROJECT OVERVIEW
2
2.1 PROJECT OVERVIEW
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.
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.
7
SYSTEM
REQUIREMENTS
8
4.1 SYSTEM REQUIREMENTS
It manages the computer's memory and processes, as well as all of its software and
hardware.
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.
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.
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 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.
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.
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.
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
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.
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.
NLKT Library
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.
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.
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.
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.
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.
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",
"Hello",
"Good day"
],
"responses": [
"Hey :-)",
},
"tag": "name",
26
"responses": [
},
"tag": "self",
"responses": [
},
"tag": "creator",
"responses": [
},
"tag": "functions",
"responses": [
27
"Open Camera , Open browser , Open mail , Get result
From Google (or) Wikipedia and more..,"
},
"tag": "goodbye",
"responses": [
},
"tag": "thanks",
},
"tag": "open_chrome",
"patterns": [
"chrome"
],
28
"responses": [
"Sure..!"
},
"tag": "open_camera",
"patterns": [
"camera"
],
"responses": [
"Sure..!"
},
"tag": "open_mail",
"patterns": [
"mail"
],
"responses": [
"Sure..!"
29
]
APP.PY
from tkinter import *
BG_GRAY = "#ABB2B9"
BG_COLOR = "#17202A"
TEXT_COLOR = "#EAECEE"
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
text="Welcome", font=FONT_BOLD,
pady=10)
head_label.place(relwidth=1)
# tiny divider
# 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.place(relwidth=1, rely=0.825)
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
command=lambda:
self._on_enter_pressed(None))
msg = self.msg_entry.get()
self._insert_message(msg, "You")
if not msg:
return
32
self.msg_entry.delete(0, END)
self.text_widget.configure(state=NORMAL)
self.text_widget.insert(END, msg1)
self.text_widget.configure(state=DISABLED)
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
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.load_state_dict(model_state)
model.eval()
34
bot_name = "Luna"
def open_camera():{
def open_mail():{
def search_wiki(msg):{
def get_response(msg):
if 'chrome' in msg:
webbrowser.open('www.google.com')
return "Opened"
if 'camera' in msg:
return "opened"
if 'mail' in msg:
return "opened"
35
if 'calender' in msg:
return "opened"
if 'map' in msg:
return "opened"
if 'edge' in msg:
return "opened"
if 'paint' in msg:
return "opened"
if 'photo' in msg:
return "opened"
if 'settings' in msg:
return "opened"
if 'security' in msg:
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"
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=='':
else:
print(f)
os.popen(f)
return 'playing...'
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)
tag = tags[predicted.item()]
prob = probs[0][predicted.item()]
if tag == intent["tag"]:
return random.choice(intent['responses'])
TRAIN.PY
import numpy as np
import random
import json
import torch
import torch.nn as nn
38
from model import NeuralNet
intents = json.load(f)
all_words = []
tags = []
xy = []
tag = intent['tag']
tags.append(tag)
w = tokenize(pattern)
all_words.extend(w)
# add to xy pair
xy.append((w, tag))
39
all_words = sorted(set(all_words))
tags = sorted(set(tags))
print(len(xy), "patterns")
X_train = []
y_train = []
X_train.append(bag)
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
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')
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(),
lr=learning_rate)
words = words.to(device)
labels = labels.to(dtype=torch.long).to(device)
# Forward pass
outputs = model(words)
optimizer.zero_grad()
42
loss.backward()
optimizer.step()
if (epoch+1) % 100 == 0:
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)
43
NLTK_UTILS.PY
import numpy as np
import nltk
nltk.data.path.append('E:\nltk-develop\nltk\tokenize')
stemmer = PorterStemmer()
def tokenize(sentence):
"""
"""
return nltk.word_tokenize(sentence)
def stem(word):
"""
examples:
"""
return stemmer.stem(word.lower())
44
def bag_of_words(tokenized_sentence, words):
"""
example:
bog = [ 0 , 1 , 0 , 1 , 0 , 0 , 0]
"""
if w in sentence_words:
bag[idx] = 1
return bag
MODELS.PY
mport torch
import torch.nn as nn
45
class NeuralNet(nn.Module):
super(NeuralNet, self).__init__()
self.relu = nn.ReLU()
out = self.l1(x)
out = self.relu(out)
out = self.l2(out)
out = self.relu(out)
out = self.l3(out)
return out
46
SCREENSHOTS
47
10. SCREENSHOTS
TRAIN CHATBOT
EXECUTE FUNCTIONS
48
PLAY MUSIC
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.
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