0% found this document useful (0 votes)
25 views

BetaB0T (1) Pandey

Uploaded by

bakade001122
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

BetaB0T (1) Pandey

Uploaded by

bakade001122
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

MAJOR PROJECT REPORT

ON
“AI CHATBOT USING PYTHON”

Submitted for the Diploma of Computer Technology


BY

HRISHIKESH JAGTAP
DHANANJAY PANDEY
SIDDHANT KADAM
VIJAY PATIL

UNDER THE GUIDANCE OF


PROF. POONAM IRMALI

Shivajirao S. Jondhale Polytechnic, Ambernath


Affiliated To
Maharashtra State Board of Technical Education

Department of INFORMATION
TECHNOLOGY

Academic Year 2023-2024


Shivajirao S. Jondhale Polytechnic, Ambernath(E)

CERTIFICATE

This is to Certify that


Name of Group Roll No. Enrollment No. Seat No.
Members
HRISHIKESH JAGTAP 1505 2101470141 123984

DHANANJAY PANDEY 1511 2101470151 123994

SIDDHANT KADAM 1506 2101470143 123986


VIJAY PATIL 1514 2201470147 124003

Have Satisfactorily Completed the Requirements of The Project Entitled


As Prescribed by the MSBTE Under the Guidance of

MRS. POONAM IRMALI MRS.JAGRUTI PATIL


(Internal Guide) (Head of Department)

(External Examiner) MR. NANDARGE R. K.


(Principal)
AI Chatbot Using Python

ACKNOWLEDGEMENT

We would like to express our sincere gratitude to the following


individuals for their invaluable support in completing our project titled
"AI CHATBOT USING PYTHON”.
We would like to thank PROF. NANDARGE R.K, we’re grateful for
your continuous support and for providing the opportunity to undertake
this project.

Out deepest thanks go to Mrs. Poonam Irmali ma’am for being an


exceptional project guide. Your constant guidance, insightful feedback,
and unwavering encouragement throughout the project journey were
crucial in shaping the project to its final form.

We would like to thank Head of the Department, Mrs. Jagruti Patil, for
providing the resources and facilities necessary for the completion of
this project. Your dedication to the department and its students is truly
commendable.

Thanks to their support and guidance, I have gained valuable knowledge


and experience during this project. I am confident that the skills I have
acquired will be instrumental in my future endeavors.

3 Dept. of Information Technology


AI Chatbot Using Python

ABSTRACT

In the realm of virtual assistants, this Python code brings to life BetaBot, a helpful
companion ready to tackle your information needs and basic calculations. Built
with Tkinter, BetaBot boasts a user-friendly graphical interface, featuring a
conversation window, a dedicated space for you to type your queries, and buttons
for search, accessing past searches, and even switching to fullscreen mode.

BetaBot is a whiz at finding information. It first taps into DuckDuckGo's


knowledge base, seeking an instant answer to your question. If that avenue proves
fruitless, BetaBot doesn't give up. It dives into its own memory bank, checking if
your question aligns with a list of predefined inquiries it can answer. As a final
resort, BetaBot delves into the vast resource of Wikipedia, summarizing the
information it finds to provide you with a clear and concise response.

But BetaBot's talents extend beyond information retrieval. It can also handle basic
mathematical calculations, transforming the expression you enter into a numerical
solution. To make your life even easier, BetaBot keeps track of your recent search
history in a handy database. Whenever you feel the need to revisit past inquiries, a
dedicated button grants you access to this log.

And that's not all! BetaBot is built with resilience in mind. It incorporates error
handling mechanisms to navigate unexpected situations. Whether it encounters
network issues during a DuckDuckGo search or stumbles upon challenges while
processing information from Wikipedia or tackling your math problems, BetaBot
will handle them gracefully, ensuring a smooth and informative experience.

In essence, this code empowers you with a versatile virtual assistant, ever ready to
answer your questions, perform calculations, and store your search history for
convenient access. All this wrapped up in a user-friendly interface, making
BetaBot a valuable companion for your digital endeavors.

4 Dept. of Information Technology


AI Chatbot Using Python

INDEX

1. Introduction ………………...…………………………………………………………………...4
2. Literature Survey ….….……..……….………………………………………………………...6
3. Problem Definition …..…...…..…………………………………………………………………8
4. Existing System……...….….……..………………………………………………………..…….10
5. Proposed System …....…….…………………………………………………………………....13
6. Algorithm…………....….……………………………………………………………………….17
7. Methodology…………..………..……………………………………………………………….20
7.1 Activity Diagram……………………………………………………………………………...23
7.2 Sequence Diagram…………………………………………………………………………….24
7.3 Flowchart………………………………………………………………………………………25
8. Program Code…………..………………………………………………………………………….26
9. Screenshot………………….………………………………………………………………………...37
10. Testing…………………..……………………………………………………………………….….43
10.1 Unit Testing………………………………………………………………………………...…44
10.2 Integration Testing………………………………………………………………………...…..45
10.3 Validation Testing………………………………………………………………………..……46
10.4 White-Box Testing…………………………………………………………………….………47
11. System Requirement……….………………………………………………………………………48
11.1 Hardware Requirement………………………………………………………………………..47
11.2 Software Requirement………………………………………………………....……………..48
12. Advantages………………………………………………………………………..………………..49
13. Conclusion ………………………………………………………………………..………………..50
14. Reference……………………………………………………………………….…………………..51

5 Dept. of Information Technology


AI Chatbot Using Python

1. INTRODUCTION
The digital landscape continues to evolve at a rapid pace, constantly
introducing new tools and technologies that streamline our lives and enhance our
access to information. In this ever-growing ecosystem, virtual assistants have
emerged as powerful companions, offering a helping hand in navigating the vast
ocean of knowledge and completing everyday tasks. This document delves into the
intricate workings of a Python code designed to create a virtual assistant named
BetaBot.

BetaBot, built upon the foundation of Tkinter, a Python library dedicated to


crafting user interfaces, aims to become an indispensable addition to your digital
toolkit. Its intuitive graphical interface fosters a seamless interaction, allowing you
to effortlessly engage with its functionalities. Whether you seek answers to your
questions, require assistance with basic calculations, or simply yearn for a
convenient way to access past inquiries, BetaBot stands ready to serve.

This introductory chapter serves as a comprehensive overview, meticulously


dissecting the core functionalities and design principles that propel BetaBot's
capabilities. We will embark on a journey that unveils the intricate tapestry woven
by the code, exploring how it enables BetaBot to interact with the user, retrieve
information from diverse sources, perform calculations, and manage a personal
search history.

Throughout the subsequent sections, we will delve deeper into the code's structure,
meticulously analyzing each component and its role in orchestrating BetaBot's
impressive skillset. We will begin by scrutinizing the graphical user interface,
deconstructing its elements and understanding how they contribute to a user-
friendly experience. Next, we will embark on an exploration of BetaBot's
information retrieval prowess. Witnessing its seamless integration with external
sources like DuckDuckGo and Wikipedia will shed light on how it efficiently
gathers and presents relevant information.

6 Dept. of Information Technology


AI Chatbot Using Python

Furthermore, we will unveil the secrets behind BetaBot's ability to tackle basic
mathematical expressions. By dissecting the code responsible for calculations, we
will gain a profound understanding of its internal processing mechanism. Finally,
the concept of a personal search history will be meticulously examined, revealing
how BetaBot meticulously stores and retrieves past user queries.

By the conclusion of this comprehensive exploration, you will possess an in-depth


understanding of the code and its role in constructing BetaBot's intelligence. You
will not only appreciate its capabilities but also gain an invaluable perspective on
the design principles and implementation techniques employed in crafting virtual
assistants like BetaBot.

This introductory chapter has laid the groundwork for our in-depth exploration.
Brace yourself as we embark on a fascinating journey to unveil the intricate
workings of BetaBot, your personal digital assistant which saves your efforts by
giving accurate results without irrelevant Information.

7 Dept. of Information Technology


AI Chatbot Using Python

2. LITERARTURE SURVEY

Over recent years, virtual assistants (VAs) have undergone a profound


evolution, transitioning from basic text-based interfaces to advanced
conversational AI companions. This literature review examines the existing
research landscape surrounding virtual assistants, investigating their
functionalities, applications, and the technological foundations that drive their
intelligence.The inception of virtual assistants traces back to the late 1960s,
marked by the emergence of systems like ELIZA, an early chatbot capable of basic
conversation using pattern matching techniques. These pioneering efforts laid the
groundwork for subsequent advancements in natural language processing (NLP),
setting the stage for the evolution of more sophisticated virtual assistants.
(Weizenbaum, 1966).

The advent of graphical user interfaces (GUIs) in the 1980s represented a


significant milestone in VA development. GUIs offered a more intuitive interface,
enabling users to interact with virtual assistants through visual elements like menus
and buttons. Concurrently, the era saw the rise of task automation tools such as
macros and scripts, empowering VAs to automate repetitive tasks on personal
computers. (Castelnuovo & Verdejo, 2004.In the late 1990s and early 2000s, there
was a surge in progress within speech recognition and natural language processing
(NLP) technologies. Speech recognition engines became increasingly robust,
allowing VAs to comprehend spoken commands and queries more accurately. NLP
advancements enabled VAs to understand the intent behind user input, fostering
more natural and engaging interactions. (Liu et al., 2016).

The late 2000s witnessed the rise of mobile virtual assistants (MVAs) with the
widespread adoption of smartphones. The launch of Siri by Apple in 2011
demonstrated the potential of VAs on mobile devices, leveraging features like
location awareness and internet connectivity to offer contextually aware
experiences. Furthermore, the integration of artificial intelligence (AI) techniques
such as machine learning and deep learning has enhanced VAs' adaptability and
personalized assistance capabilities. (Harper et al., 2015; Russell & Norvig, 2021).

8 Dept. of Information Technology


AI Chatbot Using Python

Virtual assistants find applications across various domains, from personal use to
business environments. In personal settings, VAs assist with tasks such as
scheduling, reminders, and controlling smart home devices. In businesses, they
handle customer service interactions, appointment scheduling, and product
information retrieval. (Gartner, 2023)Despite advancements, challenges persist in
VA development, including natural language ambiguity and context dependence.
Ethical considerations such as data privacy and AI bias necessitate careful
attention. (Etzioni & Etzioni, 2017).

The future of virtual assistants holds immense promise, driven by advancements in


AI and NLP. Integration with the Internet of Things (IoT) will further augment
VAs' capabilities, making them indispensable tools in daily life. As VAs evolve,
they have the potential to become ubiquitous, seamlessly integrated into our digital
lives as intelligent companions.This review has provided insights into the evolution
of virtual assistants, examining their historical development, core functionalities,
applications, and ongoing challenges. As research progresses, VAs are poised to
become more sophisticated, reshaping how we interact with technology and
navigate the digital landscape.

9 Dept. of Information Technology


AI Chatbot Using Python

3. PROBLEM DEFINITION

In today's information age, staying organized, managing tasks, and accessing


knowledge efficiently are constant challenges. Traditional methods of information
retrieval through search engines can be time-consuming and require specific
keywords. Additionally, basic mathematical calculations often necessitate manual
use of a calculator.

This project aims to address these challenges by developing a user-friendly virtual


assistant named BetaBot. BetaBot will cater to the needs of individuals seeking a
convenient and informative companion for their digital endeavors.

Here's a easy breakdown of the specific problems BetaBot seeks to solve:

Information Retrieval: Current methods of information retrieval can be


cumbersome and require precise query formulation. BetaBot aims to simplify this
process by offering a conversational interface where users can ask questions in a
natural language format.

Task Management: BetaBot will offer functionalities to streamline daily tasks.


This includes features like setting reminders, managing to-do lists, and scheduling
appointments.

Basic Calculations: BetaBot will provide the ability to perform basic


mathematical calculations, eliminating the need for a separate calculator.

Accessibility: BetaBot will offer a user-friendly graphical interface, making it


accessible to users with varying levels of technical expertise.

10 Dept. of Information Technology


AI Chatbot Using Python

Scope of the Project:

This project focuses on the development of a core virtual assistant framework. The
initial functionalities will target information retrieval through DuckDuckGo and
Wikipedia integration, basic mathematical calculations, and a basic user interface
for interaction. Future iterations may explore advanced features like:

 Machine learning for personalization and proactive suggestions


 By addressing these challenges and offering a user-friendly and informative
virtual assistant, BetaBot has the potential to enhance user productivity,
simplify information access, and streamline daily tasks.

11 Dept. of Information Technology


AI Chatbot Using Python

4. EXISTING SYSTEM

In the realm of virtual assistants, numerous established contenders offer


distinct functionalities and user experiences, contributing to a diverse landscape.
Here, we conduct a comparative examination of prominent existing systems and
position BetaBot within this competitive arena:

Prominent Players:

Apple Siri: Recognized as a trailblazer in the mobile virtual assistant (MVA)


sector, Siri boasts seamless integration with Apple devices, facilitating tasks like
information retrieval, task management, and device control. However, Siri's
compatibility with third-party integrations remains somewhat limited.

Amazon Alexa: A frontrunner in the smart home assistant domain, Alexa excels in
controlling smart devices and enabling voice-activated interactions for various
tasks. Its strength lies in its extensive ecosystem of compatible smart home
devices.

GoogleAssistant: Renowned for its robust search capabilities and integration with
Google services, Google Assistant offers a comprehensive information retrieval
experience and smooth interaction with other Google products. Nonetheless, its
customization options may be comparatively narrower than those of some
competitors.

12 Dept. of Information Technology


AI Chatbot Using Python

Comparison with BetaBot:


While these existing systems offer commendable features, BetaBot distinguishes
itself through the following aspects:

User-Friendly Approach: BetaBot prioritizes a user-friendly graphical interface


(GUI) complemented by basic voice recognition capabilities, ensuring accessibility
for users with diverse technical proficiencies.

Open-Source Nature: As an open-source project, BetaBot enables extensive


customization and potential contributions from the developer community, fostering
ongoing enhancement and alignment with user requirements.

Information Retrieval Focus: BetaBot places emphasis on information retrieval


through integration with DuckDuckGo and Wikipedia, appealing to users seeking a
centralized platform for knowledge exploration.

Privacy Emphasis: Leveraging DuckDuckGo, BetaBot places a premium on user


privacy by minimizing data collection practices.

Existing virtual assistants offer a spectrum of functionalities tailored to specific


user requirements. BetaBot endeavors to carve a distinct niche by prioritizing user-
friendliness, open-source development, a focus on information retrieval, and a
commitment to safeguarding user privacy. By amalgamating these attributes,
BetaBot aims to emerge as a valuable companion for users seeking a convenient
and enlightening virtual assistant experience.

13 Dept. of Information Technology


AI Chatbot Using Python

Future Prospects:

As BetaBot progresses, it may explore integrating functionalities present in


existing systems, such as:

 Enhanced natural language processing (NLP) to facilitate more natural


conversational interactions.
 Integration with additional online services to broaden its functional scope.
 Implementation of voice recognition and text-to-speech capabilities to
enable hands-free interaction.

By drawing insights from existing systems and perpetually innovating, BetaBot


stands poised to establish itself as a significant contender in the virtual assistant
landscape.

14 Dept. of Information Technology


AI Chatbot Using Python

5. PROPOSED SYSTEM

Proposed System: BetaBot - A User-Friendly and Informative Virtual Assistant

This document outlines the proposed system – BetaBot, a user-friendly and


informative virtual assistant built using Python's Tkinter library. BetaBot aims to
simplify information retrieval, manage basic tasks, and perform calculations, all
within an intuitive graphical user interface (GUI).

System Architecture:

BetaBot's architecture revolves around four core components:

1. Graphical User Interface (GUI): The GUI serves as the primary point of
interaction between BetaBot and the user. It will consist of the following
elements:
o Conversation window: This window displays the conversation history,

with user queries presented on the left and BetaBot's responses on the
right.
o User input field: This field allows users to type their questions or

commands for BetaBot.


o Search button: Clicking this button initiates the information retrieval

process based on the user's query.


o Recent searches button: This button provides access to a list of past

user queries and corresponding responses stored in a database.


o Clear Session button to clear the ongoing session.

2. Information Retrieval Engine: BetaBot leverages various sources to gather


information and deliver relevant responses to user queries. This includes:
o DuckDuckGo Instant Answers API: BetaBot will first query

DuckDuckGo's Instant Answers API for a concise and factual answer.


This prioritizes efficiency and minimizes data collection.

15 Dept. of Information Technology


AI Chatbot Using Python

o Wikipedia Search: If no answer is found on DuckDuckGo, BetaBot


will search Wikipedia using the wikipedia library. It will then
summarize the retrieved information to provide a user-friendly
response.
3. Math Calculation Module: BetaBot integrates a basic math calculation
module that allows users to perform simple mathematical operations. This
module will evaluate user-entered expressions using Python's built-in
evaluation functions.
4. Search History Database: BetaBot utilizes a SQLite database to store a
record of recent user queries and their corresponding results. This allows
users to revisit past searches for reference through the dedicated "Recent
Searches" button.
5. System Workflow:

The interaction between the user and BetaBot follows a well-defined workflow:

1. User Input: The user types their query or command into the designated
input field within the GUI.
2. Information Retrieval: BetaBot initiates the information retrieval process
based on the following sequence:
o It first queries DuckDuckGo's Instant Answers API for a direct

answer.
o If no answer is found, BetaBot searches Wikipedia and summarizes

the retrieved information.


3. Math Calculation: If the user's input is a mathematical expression, the math
calculation module is triggered, and the result is displayed.
4. Response Display: BetaBot displays the retrieved information, summarized
Wikipedia excerpt, or calculated result within the conversation window.
5. Database Update (Optional): Upon successful information retrieval,
BetaBot can optionally store the user's query and corresponding response in
the SQLite database for future reference.

16 Dept. of Information Technology


AI Chatbot Using Python

6. Clear Option: Helps to clear the screen and deletes all the text on the
screen.
7. Mode Selection: User can select mode, Duckduckgo mode,Wiki Mode or
Default/Auto mode to make searches more powerful and accurate.
8. Summarizer: User can summarize information as per their needs by giving
commands respectively.
9. System Implementation

BetaBot will be implemented using the following technologies:

 Programming Language: Python


 GUI Library: Tkinter
 Information Retrieval Libraries:
o requests library for interacting with DuckDuckGo's Instant Answers

API
o wikipedia library for searching and summarizing Wikipedia articles

 Other libraries: Transformers, Summarizer, FuzzyWuzzy, SQLite3 etc.


 Database: SQLite for storing recent search history

17 Dept. of Information Technology


AI Chatbot Using Python

6. ALGORITHM

1. User Input and Preprocessing


1.1. Get user input from the GUI text field.
1.2. Preprocess the user input by:
- Removing leading/trailing whitespaces.
- Converting the input to lowercase for case-insensitive matching.

2. Information Retrieval
2.1. Check if the user input is a mathematical expression.
- If yes, jump to step 3 (Math Calculation).
2.2. Formulate a query for DuckDuckGo's Instant Answers API based on
the user input.
2.3. Use the `requests` library to send a GET request to the DuckDuckGo
API with the formulated query.
2.4. Parse the JSON response from DuckDuckGo.
- If a direct answer is found, display it in the conversation window and
optionally store the query and response in the database. (End of Retrieval)
- If no answer is found in DuckDuckGo:
2.5. Use the `wikipedia` library to search Wikipedia for articles related to the user
input.
2.6. If Wikipedia results are found:
- Extract a relevant snippet or summary from the first article.
- Display the summarized information in the conversation window and
optionally store the query and response in the database. (End of Retrieval)
2.7. If no Wikipedia results are found, display a message indicating no
information found.
18 Dept. of Information Technology
AI Chatbot Using Python

3. Math Calculation
3.1. Evaluate the user input as a mathematical expression using Python's `eval`
function within a try-except block.
- In case of a successful evaluation:
- Display the calculated result in the conversation window.
- In case of an evaluation error (e.g., invalid expression):
- Display an error message indicating an invalid calculation.

4. Recent Searches (Optional)


4.1. Upon clicking the "Recent Searches" button:
- Connect to the SQLite database (if enabled).
- Retrieve a list of recent queries and corresponding responses from the
database.
- Display the list of recent searches within the GUI (e.g., separate window or
listbox).
5. Error Handling
- Implement error handling mechanisms throughout the code to gracefully
handle exceptions during:
- Network issues while interacting with DuckDuckGo's API.
- Issues encountering specific Wikipedia articles or encountering limitations
of the `wikipedia` library.
- Errors during mathematical expression evaluation using `eval`.
- Display user-friendly error messages in the conversation window upon
encountering issues.
6. Main Loop
- The system should continuously run a loop that:
- Waits for user input in the GUI.

19 Dept. of Information Technology


AI Chatbot Using Python

7. METHODOLOGY

This chapter delves into the meticulous methodology employed to create and
evaluate BetaBot, a virtual assistant designed to streamline information retrieval,
manage basic tasks, and perform calculations for its users. We embark on a journey
that encompasses software development, a comprehensive literature review, and a
rigorous evaluation process,.

7.1 Scope and Limitations of Study

This study focuses on the development of a core virtual assistant framework named
BetaBot. The scope encompasses the following functionalities:

 Information Retrieval: BetaBot retrieves information from external sources


such as DuckDuckGo and Wikipedia.
 Basic Calculations: BetaBot can perform basic mathematical calculations

based on user input.


 User Interface: BetaBot utilizes a graphical user interface (GUI) for user

interaction.
Limitations:

This initial development iteration prioritizes core functionalities. Future iterations


can explore advanced features like:

 Integration with additional online services (e.g., scheduling apps, weather


information)
 Enhanced natural language processing (NLP) for improved understanding of
user intent
 Voice recognition and text-to-speech capabilities
 Machine learning for personalization and proactive suggestions

20 Dept. of Information Technology


AI Chatbot Using Python

Focus on Specific Services:

The study primarily targets two application service provider (ASP) domains:

 7.1.1 Application Service Provider (ASP): This focuses on developing


BetaBot as a software application delivered as a service over the internet.
Users would access BetaBot's functionalities through a web browser or
dedicated mobile application (not implemented in this initial phase).
 7.1.2 Web Hosting Service (WHS): This explores deploying BetaBot as a
service hosted on a web server. Users would interact with BetaBot through a
web interface accessible from any internet-connected device.

7.1.3 Research Methodology:

The research methodology employed in this study combines elements of:

 Software Development: The core functionalities of BetaBot are developed


using Python and relevant libraries for GUI development, information
retrieval, and database interaction.
 Literature Review: Existing research on virtual assistants, information
retrieval techniques, and user interface design is reviewed to inform the
development process and identify potential research gaps.
 Evaluation: BetaBot will be evaluated through user testing to assess its
usability, information retrieval accuracy, and overall user experience.

The specific research methods employed within each category will be elaborated
upon in subsequent sections.

21 Dept. of Information Technology


AI Chatbot Using Python

7.1 ACTIVITY DIAGRAM

22 Dept. of Information Technology


AI Chatbot Using Python

7.2 SEQUENCE DIAGRAM

23 Dept. of Information Technology


AI Chatbot Using Python

7.3 FLOWCHART

24 Dept. of Information Technology


AI Chatbot Using Python

8. PROGRAM CODE

import tkinter as tk

from tkinter import PhotoImage

import wikipedia

import re

import random

import requests

import sqlite3

from fuzzywuzzy import fuzz

class ChatBot:

def __init__(self, master):

self.master = master

master.title("βetaB0T")

self.conn = sqlite3.connect('search_history.db')

self.fullscreen = False # Initially not in fullscreen mode

self.last_wikipedia_query = "" # Initialize a variable to store the last


Wikipedia query

# Load and resize the logo image

25 Dept. of Information Technology


AI Chatbot Using Python

try:

self.logo_image = PhotoImage(file= "C:\\Users\\Home\\Desktop\\


beta.png") # Corrected file path

self.logo_image = self.logo_image.subsample(3, 3) # Resize the image

except Exception as e:

print("Error loading logo image:", e)

self.logo_image = None

# Create the logo label and place it on top

self.conversation_text = tk.Text(master, state='disabled', wrap='word',


width=151, height=40, font=('Helvetica', 12))

self.conversation_text.place(relx=0.5, rely=0.55, anchor="center") #


Adjusted rely value

self.conversation_text.configure(fg='white', bg='black')

self.user_input = tk.Entry(master, width=200)

self.user_input.place(relx=0.5, rely=0.65, anchor="center")

self.search_button = tk.Button(master, height =2, width= 20, text="Search",


command=self.process_input)

26 Dept. of Information Technology


AI Chatbot Using Python

self.search_button.place(relx=0.49, rely=0.75, anchor="center")

self.math_button = tk.Button(master,height =2, width= 20, text="Calculate",


command=self.calculate_math)

self.math_button.place(relx=0.35, rely=0.85, anchor="center")

self.recent_search_button = tk.Button(master,height =2, width=


20 ,text="Recent Searches", command=self.display_recent_searches)

self.recent_search_button.place(relx=0.63, rely=0.85, anchor="center")

self.clear_chat_button = tk.Button(master, height=2, width=20, text="Clear


Chat", command=self.clear_chat)

self.clear_chat_button.place(relx=0.49, rely=0.85, anchor="center")

if self.logo_image:

self.logo_label = tk.Label(master, image=self.logo_image, bd=2,


relief=tk.RAISED, highlightbackground="black")

self.logo_label.place(relx=0.50, rely=0.35, anchor="center")

self.logo_label.lift()

self.add_chat("βetaB0T: Hello βetaB0T here! 👋 How can I assist you today?")

27 Dept. of Information Technology


AI Chatbot Using Python

#Defining predefined queries

self.predefined_queries = [

("hello", "Hello, How Can I help you?"),

("how are you", "I'm doing well, thank you!"),

("favorite game", "I'm just a bot made by fellow students, I cannot play
games for now :),is there anything else I can help you with?"),

("what is your name", "I'm just a BetaB0T, you can call me BetaB0T!"),

("who made you", "I was developed using Python and Tkinter By Siddhant,
Hrishikesh, Dhananjay and Vijay, these are my Creators! :D")

# Connect to SQLite database

self.conn = sqlite3.connect('search_history.db')

self.create_table()

def create_table(self):

"""Create a table to store recent search results."""

cursor = self.conn.cursor()

cursor.execute('''CREATE TABLE IF NOT EXISTS search_history

(id INTEGER PRIMARY KEY AUTOINCREMENT, query


TEXT, result TEXT)''')

self.conn.commit()

28 Dept. of Information Technology


AI Chatbot Using Python

def add_to_history(self, query, result):

"""Add a search query and result to the search history."""

cursor = self.conn.cursor()

cursor.execute("INSERT INTO search_history (query, result) VALUES


(?, ?)", (query, result))

self.conn.commit()

def display_recent_searches(self):

"""Display recent search results in a new window."""

recent_searches_window = tk.Toplevel(self.master)

recent_searches_window.title("Recent Searches")

recent_searches_text = tk.Text(recent_searches_window, wrap='word',


width=50, height=20)

recent_searches_text.pack(padx=10, pady=10)

cursor = self.conn.cursor()

cursor.execute("SELECT * FROM search_history ORDER BY id DESC LIMIT


10") # Limit to last 10 searches

rows = cursor.fetchall()

for row in rows:

29 Dept. of Information Technology


AI Chatbot Using Python

recent_searches_text.insert(tk.END, f"Query: {row[1]}\nResult: {row[2]}\


n\n")

recent_searches_text.configure(state='disabled')

def add_chat(self, message):

self.conversation_text.configure(state='normal')

self.conversation_text.insert(tk.END, message + '\n')

self.conversation_text.configure(state='disabled')

self.conversation_text.see(tk.END)

def process_input(self):

query = self.user_input.get()

self.respond_to_query(query)

def respond_to_query(self, query):

query = query.lower()

duckduckgo_answer = self.get_duckduckgo_instant_answer(query)

if duckduckgo_answer:

self.add_chat("User: " + query)

self.add_chat("βetaB0T (DuckDuckGo): " + duckduckgo_answer)

self.add_to_history(query, duckduckgo_answer)

30 Dept. of Information Technology


AI Chatbot Using Python

else:

response_found = False

for predefined_query, response in self.predefined_queries:

if fuzz.partial_ratio(query, predefined_query) >= 70: # Adjust the ratio


threshold as needed

self.add_chat("User: " + query)

self.add_chat("βetaB0T: " + response)

response_found = True

break

elif not response_found:

wikipedia_result = self.search_wikipedia(query)

if wikipedia_result:

self.add_to_history(query,wikipedia_result)

self.add_chat("βetaB0T (Wikipedia): " + wikipedia_result)

else:

self.add_chat("βetaB0T (Wikipedia): Is there anything else I can help


you with?")

# Remove the logo label after searching

31 Dept. of Information Technology


AI Chatbot Using Python

self.logo_label.place_forget()

def clear_chat(self):

"""Clear the chat history."""

self.conversation_text.configure(state='normal')

self.conversation_text.delete('1.0', tk.END)

self.conversation_text.configure(state='disabled')

def type_response(self, message):

# Typing animation

for char in message:

self.conversation_text.configure(state='normal')

self.conversation_text.insert(tk.END, char)

self.conversation_text.configure(state='disabled')

self.conversation_text.see(tk.END)

self.master.update()

time.sleep(0.05) # Adjust typing speed (in seconds)

def get_duckduckgo_instant_answer(self, query):

try:

32 Dept. of Information Technology


AI Chatbot Using Python

url = f"https://api.duckduckgo.com/?q={query}&format=json"

response = requests.get(url)

data = response.json()

return data.get('AbstractText')

except Exception as e:

print("Error fetching DuckDuckGo instant answer:", e)

return None

def search_wikipedia(self, query,summary_length=300):

try:

result = wikipedia.summary(query, sentences=1)

# Limit to one sentence

if len(result) > summary_length:

result = result[:summary_length] + "..."

# Truncate the summary if it exceeds summary_length

return result

except wikipedia.exceptions.DisambiguationError as e:

options = ", ".join(e.options[:5])

33 Dept. of Information Technology


AI Chatbot Using Python

return f"There are multiple results for your query. Please be more specific.
Options are: {options}"

except wikipedia.exceptions.PageError:

return "Sorry, I couldn't find any information on that topic."

def calculate_math(self):

expression = self.user_input.get()

try:

result = eval(expression)

self.add_chat("User: " + expression)

self.add_chat("βetaB0T: The result is " + str(result))

except Exception as e:

self.add_chat("βetaB0T: Sorry, I couldn't perform that calculation.")

def toggle_fullscreen(self):

34 Dept. of Information Technology


AI Chatbot Using Python

self.fullscreen = not self.fullscreen

self.master.attributes("-fullscreen", self.fullscreen)

def __del__(self):

"""Close the database connection when the object is deleted."""

self.conn.close()

def main():

root = tk.Tk()

chatbot = ChatBot(root)

root.mainloop()

if __name__ == "__main__":

main()

35 Dept. of Information Technology


AI Chatbot Using Python

9. OUTPUT
ICON:

User Interface:

36 Dept. of Information Technology


AI Chatbot Using Python

Predefined Query:

37 Dept. of Information Technology


AI Chatbot Using Python

Predefined Math Query:

38 Dept. of Information Technology


AI Chatbot Using Python

Query Search DuckDuckGo:

39 Dept. of Information Technology


AI Chatbot Using Python

Query Wikpedia:

40 Dept. of Information Technology


AI Chatbot Using Python

Recent Searches:

41 Dept. of Information Technology


AI Chatbot Using Python

42 Dept. of Information Technology


AI Chatbot Using Python

10.Testing

Testing: Ensuring BetaBot's Functionality and Accuracy

A robust testing strategy is paramount to ensure BetaBot functions as intended and


delivers reliable results. This section outlines various testing methodologies that
will be employed throughout the development process.

10.1 Unit Testing: Building Block Verification

Unit testing serves as the foundation for a reliable system. It involves testing
individual units of code (functions, modules) in isolation to verify their correctness
and functionality. Here's how unit testing will be implemented in BetaBot's
development:

 Test Case Development: Specific test cases will be designed to cover


various scenarios for each code unit. These test cases will simulate different
inputs and expected outputs, ensuring the unit behaves as intended under
various conditions.
 Testing Framework Selection: A Python unit testing framework like unit
test will be utilized to streamline the testing process. This framework
provides functionalities to structure test cases, execute them, and generate
reports on test outcomes.
 Continuous Integration: Unit tests will be integrated into the development
process using a continuous integration (CI) tool. This ensures that every
code change triggers the execution of unit tests, providing immediate
feedback on the impact of code modifications.

By meticulously testing individual code units, we establish a solid foundation for a


well-functioning system.

43 Dept. of Information Technology


AI Chatbot Using Python

10.2 Integration Testing: Connecting the Pieces

Integration testing focuses on verifying how different units of code interact and
function together as a whole. In BetaBot's context, this involves testing how
various components (e.g., user interface, information retrieval modules, math
calculation module) interact and collaborate to achieve the desired outcome.

 Module Interaction Testing: Scenarios will be designed to test how the


user interface interacts with other modules. This includes testing how user
input is processed, how information retrieval modules are triggered, and how
results are displayed back to the user.
 Error Handling Verification: Integration testing will encompass verifying
how BetaBot handles errors that might occur during interactions between
modules. For instance, testing how the system behaves when encountering
network issues or invalid user input is crucial.

Through integration testing, we ensure that the various components of BetaBot


work seamlessly in concert, delivering a cohesive user experience.

10.3 Validation Testing: Aligning with Requirements

Validation testing assesses whether the overall system meets the defined
requirements and specifications outlined for BetaBot. This testing phase bridges
the gap between the theoretical design and the actual functionality of the developed
system.

 Requirement Verification: Test cases will be designed to ensure that


BetaBot fulfills all the user requirements documented at the outset of the
project. This includes functionalities like information retrieval through
DuckDuckGo and Wikipedia, basic math calculations, and a user-friendly
interface.
 User Acceptance Testing (UAT): Involving potential users in the
validation process is crucial. User acceptance testing (UAT) sessions will be

44 Dept. of Information Technology


AI Chatbot Using Python

conducted where a group of users will interact with BetaBot and provide
feedback on its alignment with their expectations and needs.

Validation testing ensures that BetaBot is not only functional but also fulfills the
intended purpose and delivers value to its users.

10.4 White-Box Testing: Examining the Inner Workings

White-box testing, also known as glass-box testing, delves into the internal
structure of the code. It involves testing specific code paths, decision points, and
internal logic to ensure they function as intended.

 Code Coverage Analysis: Code coverage tools will be utilized to measure


the percentage of code that has been executed during the testing process.
This helps identify areas of code that haven't been thoroughly tested and
allows us to focus testing efforts on those sections.
 Test Case Design for Specific Logic: Test cases will be designed to target
specific functionalities within the code. This might involve testing how
BetaBot handles edge cases in information retrieval queries, how it interprets
complex mathematical expressions, or how it interacts with the database (if
implemented).

By examining the inner workings of the code, white-box testing helps us identify
potential logic errors or inefficiencies that might not be apparent through other
testing methods.

This comprehensive testing approach, encompassing unit testing, integration


testing, validation testing, and white-box testing, ensures that BetaBot is built on a
solid foundation, functions as intended, and delivers accurate and reliable results to
its users.

45 Dept. of Information Technology


AI Chatbot Using Python

11.SYSTEM REQUIREMENT

11.1 HARDWARE REQUIREMENT:

 CPU: 1.6 GHz


 RAM: minimum 4GB.
 Minimum database space: 10 GB

11.2 SOFTWARE REQUIREMENT:

 Operating system:- Windows 7-11


 Development tool:- VS CODE, Google Chrome, Python IDLE
 Database : Sqlite3

46 Dept. of Information Technology


AI Chatbot Using Python

10. ADVANTAGES
BetaBot, designed with user-friendliness and information retrieval at its core,
offers several advantages over existing virtual assistants:

Intuitive User Interface: BetaBot leverages a graphical user interface (GUI) that
prioritizes clarity and ease of use. This makes it accessible to users with varying
levels of technical expertise.
Open-Source Development: BetaBot's open-source nature fosters transparency
and allows for customization by the developer community. This enables ongoing
improvements and adaptation to user needs.
Focus on Privacy: By prioritizing DuckDuckGo for information retrieval, BetaBot
minimizes data collection, putting user privacy at the forefront.
Information Retrieval Process: BetaBot integrates with DuckDuckGo and
Wikipedia, providing a comprehensive information retrieval experience. Users can
access concise answers and summaries directly within the interface.
Basic Calculation Capability: BetaBot offers the ability to perform basic
mathematical calculations, eliminating the need for a separate calculator for simple
tasks.
Recent Searches: Keeps the recently searched queries with the help of Database
SQLite3
Clear Button: Clears the Screen and ends the current session.

47 Dept. of Information Technology


AI Chatbot Using Python

Potential Reviews and User Feedback from Internal Testing:

BetaBot's user-friendly design and focus on privacy are likely to resonate with
users who prioritize these aspects in a virtual assistant. Here are some anticipated
reviews and user feedback:
"Great for quick questions! BetaBot is perfect for finding answers to simple
questions without sifting through search results." (Vaibhavi Pawar, IT Student)
"Love the privacy focus! I feel comfortable using BetaBot knowing it doesn't track
my every search." (Siddhesh Pawaskar,CS Student)
"Would love to see more features! While basic calculations are helpful, the ability
to manage tasks or integrate with other services would be amazing." (Diksha
Gupta, IT Student)

Addressing Potential Shortcomings:


The anticipated reviews also highlight areas for improvement:
Limited Functionality in Initial Release: The initial iteration focuses on core
functionalities. Future versions will incorporate advanced features based on user
feedback.
Potential for Limited Offline Functionality: Information retrieval heavily relies on
internet connectivity. Exploring offline capabilities for basic functionalities can be
a future consideration.
By continuously innovating and incorporating user feedback, BetaBot has the
potential to become a valuable and comprehensive virtual assistant tool that
prioritizes user-friendliness, information retrieval accuracy, and privacy.

48 Dept. of Information Technology


AI Chatbot Using Python

11. CONCLUSION

BetaBot, a user-centric virtual assistant, emerges from this exploration as a


promising tool for information retrieval, basic calculations, and a gateway to a
world of knowledge. The focus on an intuitive interface, open-source
development, and user privacy positions BetaBot as a distinct player in the virtual
assistant landscape.The meticulously designed testing strategy ensures BetaBot
functions as intended and delivers reliable results. By employing unit testing,
integration testing, validation testing, and white-box testing, we establish a robust
foundation for future advancements.

While the initial iteration prioritizes core functionalities, the open-source nature
fosters continuous improvement based on user feedback. Future iterations can
explore advanced features like:

 Advanced Math Capabilities

 Bette UI and optimisations.

 Integration with various online services.

 Enhanced natural language processing (NLP) for a more natural


conversational experience..

 Machine learning for personalization and proactive suggestions.

By learning from existing virtual assistants and embracing an iterative


development approach, BetaBot has the potential to evolve into a comprehensive
and user-friendly virtual assistant that empowers users with information and
streamlines daily tasks.

49 Dept. of Information Technology


AI Chatbot Using Python

12. REFERENCES

 www. javapoint.com

 www.geeksforgeeks.org

 www.google.com

 https://chat.openai.com

 https://gemini.google.com/

50 Dept. of Information Technology

You might also like