Professional Documents
Culture Documents
Naan Mudalvan
Naan Mudalvan
INTRODUCTION :
Generative AI refers to a subset of artificial intelligence (AI) techniques that
focus on creating new data rather than just analyzing existing data. These algorithms are
designed to generate content that is original and often indistinguishable from human-created
content. Generative AI has gained significant attention in recent years due to its ability to
produce realistic images, text, audio, and even video.
TensorFlow:
TensorFlow is an open-source machine learning framework developed by Google. It provides
comprehensive support for building, training, and deploying deep learning models, including
neural networks for image recognition, natural language processing, and more. TensorFlow's
flexibility and scalability make it a popular choice for Gen AI research and development.
VIGNESH BJ 1 211521205182
PyTorch:
PyTorch is another widely used open-source machine learning framework, developed by
Facebook's AI Research lab (FAIR). It is known for its dynamic computation graph, which
enables more flexible model architectures and easier debugging. PyTorch is favored by many
researchers and practitioners for its simplicity and intuitive API.
Keras:
Keras is a high-level neural networks API written in Python, designed for fast experimentation
and prototyping of deep learning models. It provides a user-friendly interface to TensorFlow,
Theano, and Microsoft Cognitive Toolkit (CNTK), allowing developers to quickly build and
train neural networks with minimal boilerplate code.
Jupyter Notebooks:
Jupyter Notebooks are interactive computing environments that allow users to create and share
documents containing live code, equations, visualizations, and narrative text. They are widely
used by AI researchers and practitioners for exploratory data analysis, prototyping machine
learning models, and documenting research workflows.
OpenAI Gym:
OpenAI Gym is a toolkit for developing and comparing reinforcement learning algorithms. It
provides a diverse collection of environments (simulated tasks) for reinforcement learning
experiments, as well as a simple API for interacting with these environments and evaluating
agent performance.
VIGNESH BJ 2 211521205182
Hugging Face Transformers is a popular library for natural language processing (NLP) tasks,
built on top of PyTorch and TensorFlow. It provides pre-trained models and a unified API for
fine-tuning, inference, and evaluation of state-of-the-art NLP models, including transformer-
based architectures like BERT, GPT, and T5.
FastAI:
FastAI is a deep learning library built on top of PyTorch, designed to make deep learning more
accessible through high-level abstractions and best practices. It provides pre-trained models,
data augmentation techniques, and training utilities that enable rapid experimentation and
development of deep learning applications.
Scikit-learn:
Scikit-learn is a popular machine learning library for classical machine learning algorithms and
data preprocessing techniques. While it's not specifically tailored for deep learning, it offers a
rich set of tools for tasks such as classification, regression, clustering, dimensionality
reduction, and model evaluation.
VIGNESH BJ 3 211521205182
Adaptability and Continual Learning:
Gen AI systems are characterized by their ability to adapt to new tasks, environments, and data
sources. These systems are not static; instead, they continuously learn and improve over time,
leveraging techniques such as reinforcement learning, meta-learning, and lifelong learning.
Contextual Understanding:
Gen AI systems aim to understand and interpret information in context, similar to how humans
understand the world. This includes understanding nuances of language, recognizing subtle
cues in images and videos, and comprehending the broader context in which tasks are
performed.
Multimodal Capabilities:
Gen AI systems can process and generate data across multiple modalities, such as text, images,
audio, and video. This enables richer interactions and more holistic understanding of
information, leading to applications like multimodal translation, content generation, and
assistive technologies.
VIGNESH BJ 4 211521205182
Ethical and Societal Implications:
Gen AI raises important ethical and societal considerations, including issues related to bias
and fairness, privacy and data security, job displacement and workforce automation, and the
broader impact on society and humanity. Addressing these concerns is essential for the
responsible development and deployment of AI technologies.
Human-AI Collaboration:
Gen AI envisions a future where humans and AI systems collaborate closely to solve complex
problems and achieve shared goals. This includes applications like augmented intelligence,
where AI augments human capabilities, and human-in-the-loop systems, where humans
provide feedback and guidance to AI algorithms.
Domain-Specific Expertise:
Gen AI systems can exhibit expertise and proficiency in specific domains, often surpassing
human capabilities in narrow tasks. This expertise is achieved through deep learning, domain-
specific knowledge acquisition, and large-scale data analysis, enabling applications in areas
such as medicine, finance, gaming, and scientific research.
RESULT :
Thus we studied the basics about generative AI and the tools used is successfully studied.
VIGNESH BJ 5 211521205182
EX . NO : 1 CUSTOMER SUPPORT CHATBOT FOR E – COMMERCE
DATE :
AIM :
To create a chatbot for customer support in E- Commerce using Open AI
PROCEDURE :
1. Set Up OpenAI API Access:
Sign up for access to the OpenAI API and obtain your API key.
Install the OpenAI Python client library using pip
pip install openai
2. Create a Flask Application:
Set up a Flask application to handle HTTP requests and responses.
Install Flask if you haven't already
pip install Flask
3. Implement Chatbot Logic:
Write code to send user messages to the OpenAI API and receive responses.
Make sure to handle any errors and process the responses appropriately.
4. Create a Frontend Interface:
Design a user interface (UI) for the chatbot, such as a web page or mobile app.
Use HTML, CSS, and JavaScript to create the UI components for sending
messages and displaying responses.
5. Integrate Backend and Frontend:
Connect the Flask backend to the frontend interface.
Use JavaScript to send user messages to the Flask server and display responses
from the chatbot.
6. Test and Deploy:
Test the chatbot thoroughly to ensure it behaves as expected.
Deploy the chatbot to a web server or platform of your choice, such as Heroku
or AWS.
PROGRAM :
import os
from openai import OpenAI
import comet_llm
from IPython.display import display
import ipywidgets as widgets
import time
import dotenv
VIGNESH BJ 6 211521205182
# Input API keys
MY_OPENAI_KEY = os.getenv('MY_OPENAI_KEY')
MY_COMET_KEY = os.getenv('MY_COMET_KEY')
comet_llm.init(project="ecom_shopbot_openai",
api_key=MY_COMET_KEY)
COMET INFO: Valid Comet API Key saved in /home/codespace/.comet.config (set COMET
_CONFIG to change where it is saved).
## Women's Clothing:
- T-shirt
- Price: $20
- Available Sizes: Small, Medium, Large, XL
- Available Colors: Red, White, Black, Gray, Navy
- Professional Blazer
- Price: $80
- Available Sizes: Small, Medium, Large, XL
- Available Colors: Black, Gray, Navy
## Men's Clothing:
- Classic Suit Set
- Price: $200
- Available Sizes: Small, Medium, Large, XL
- Available Colors: Charcoal Gray, Navy Blue, Black
VIGNESH BJ 7 211521205182
- Available Sizes: Small, Medium, Large, XL
- Available Colors: White, Blue, Red, Green
## Accessories:
- Stylish Sunglasses
- Price: $20
- Available Colors: Black, Brown, Tortoise Shell
- Leather Handbag
- Price: $60
- Available Colors: Brown, Black, Red
- Classic Wristwatch
- Price: $50
- Available Colors: Silver, Gold, Rose Gold
## Footwear:
- High-Heel Ankle Boots
- Price: $70
- Available Sizes: 5-10
- Available Colors: Black, Tan, Burgundy
- Comfortable Sneakers
- Price: $55
- Available Sizes: 6-12
- Available Colors: White, Black, Gray
## Kids' Collection:
- Cute Cartoon T-shirts
- Price: $15 each
- Available Sizes: 2T, 3T, 4T
- Available Colors: Blue, Pink, Yellow
- Adorable Onesies
- Price: $25
- Available Sizes: Newborn, 3M, 6M, 12M
- Available Colors: Pastel Blue, Pink, Mint Green
## Activewear:
- Yoga Leggings
- Price: $30
VIGNESH BJ 8 211521205182
- Available Sizes: Small, Medium, Large
- Available Colors: Black, Gray, Teal
- Running Shoes
- Price: $40
- Available Sizes: 6-12
- Available Colors: White, Black, Neon Green
'''
Your role is to assist customers in browsing products, providing information, and guiding them
through the checkout process.
We offer a variety of products across categories such as Women's Clothing, Men's clothing,
Accessories, Kids' Collection, Footwears and Activewear products.
Feel free to ask customers about their preferences, recommend products, and inform them
about any ongoing promotions.
```{product_list}```
Make the shopping experience enjoyable and encourage customers to reach out if they have
any questions or need assistance.
"""}]
# Create a Chatbot
def get_completion_from_messages(messages, model="gpt-3.5-turbo"):
client = OpenAI(
api_key=MY_OPENAI_KEY,
)
chat_completion = client.chat.completions.create(
messages=messages,
model=model,
)
return chat_completion.choices[0].message.content
VIGNESH BJ 9 211521205182
# Interacting with Customers
def collect_messages(_):
user_input = inp.value
inp.value = ''
context.append({'role':'user', 'content':f"{user_input}"})
response = get_completion_from_messages(context)
# Log to comet_llm
comet_llm.log_prompt(
prompt=user_input,
output=response,
duration=duration,
metadata={
"role": context[-1]['role'],
"content": context[-1]['content'],
"context": context,
"product_list": product_list
},
)
user_pane = widgets.Output()
with user_pane:
display(widgets.HTML(f"<b>User:</b> {user_input}"))
assistant_pane = widgets.Output()
with assistant_pane:
display(widgets.HTML(f"<b>Assistant:</b> {response}"))
display(widgets.VBox([user_pane, assistant_pane]))
VIGNESH BJ 10 211521205182
display(dashboard)
messages = context.copy()
messages.append(
{'role':'system'
, 'content':'create a table summary of the previous order.'}
)
response = get_completion_from_messages(messages)
print(response)
If everything looks good, you can proceed to checkout. Let me know if you need any further as
sistance!
OUTPUT :
RESULT :
Thus the chatbot for customer support for E- commerce has been implemented and the
output verified successfully.
VIGNESH BJ 11 211521205182
EX . NO : 2 CREATE A CHATBOT FOR
HEALTH CARE APPOINTMENT SCHEDULING
DATE :
AIM :
To create a chatbot for health care appointment scheduling.
PROCEDURE :
1. Define Requirements and Use Cases:
Identify the specific requirements for your healthcare appointment scheduling chatbot.
Determine the use cases it should support, such as scheduling appointments, canceling
appointments, checking availability, etc.
2. Design Conversation Flow:
Create a flowchart or diagram outlining the conversation flow between the user and the
chatbot.
Define the prompts the chatbot will use to gather information from the user and provide
responses.
3. Choose a Platform:
Decide where you want to deploy your chatbot. Options include websites, mobile apps,
messaging platforms (e.g., Facebook Messenger, Slack), or standalone chatbot
platforms.
Choose a suitable platform and programming language/framework for development.
4. Implement Backend Logic:
Set up a backend server to handle communication between the chatbot and your
appointment scheduling system.
Implement logic to process user inputs, schedule appointments, check availability, and
handle other relevant tasks.
Integrate with your healthcare appointment scheduling system or database to retrieve
and update appointment information.
5. Natural Language Understanding (NLU):
Implement natural language understanding (NLU) capabilities to interpret user
messages and extract relevant information.
Use NLU tools or libraries to identify entities such as appointment dates, times,
locations, and reasons for appointments.
6. User Authentication and Authorization:
Implement user authentication and authorization mechanisms to ensure that only
authorized users can schedule appointments or access sensitive information.
Securely handle user data and comply with relevant privacy regulations (e.g., HIPAA in
the United States).
7. Testing and Iteration:
Test the chatbot extensively to identify and fix any bugs or issues.
Gather feedback from users and iterate on the design and functionality of the chatbot to
improve user experience.
8. Deployment and Monitoring:
VIGNESH BJ 12 211521205182
Deploy the chatbot to your chosen platform and make it accessible to users.
Monitor the performance of the chatbot, including user interactions, completion rates,
and any errors or exceptions.
Continuously update and maintain the chatbot to ensure it remains functional and up-to-
date with any changes to your appointment scheduling system or requirements.
9. Training and Documentation:
Train your healthcare staff on how to use the chatbot effectively and handle any
situations that may arise.
Provide documentation and support resources for users to help them understand how to
interact with the chatbot and troubleshoot common issues.
PROGRAM :
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
VIGNESH BJ 13 211521205182
#print(y)
VIGNESH BJ 14 211521205182
node = node[0]
#print(len(node))
val = node.nonzero()
#print(val)
disease = labelencoder.inverse_transform(val[0])
return disease
def tree_to_code(tree, feature_names):
tree_ = tree.tree_
#print(tree_)
feature_name = [
feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
for i in tree_.feature
]
#print("def tree({}):".format(", ".join(feature_names)))
symptoms_present = []
def recurse(node, depth):
indent = " " * depth
if tree_.feature[node] != _tree.TREE_UNDEFINED:
name = feature_name[node]
threshold = tree_.threshold[node]
print(name + " ?")
ans = input()
ans = ans.lower()
if ans == 'yes':
val = 1
else:
val = 0
if val <= threshold:
recurse(tree_.children_left[node], depth + 1)
else:
VIGNESH BJ 15 211521205182
symptoms_present.append(name)
recurse(tree_.children_right[node], depth + 1)
else:
present_disease = print_disease(tree_.value[node])
print( "You may have " + present_disease )
print()
red_cols = dimensionality_reduction.columns
symptoms_given =
red_cols[dimensionality_reduction.loc[present_disease].values[0].nonzero()]
print("symptoms present " + str(list(symptoms_present)))
print()
print("symptoms given " + str(list(symptoms_given)) )
print()
confidence_level = (1.0*len(symptoms_present))/len(symptoms_given)
print("confidence level is " + str(confidence_level))
print()
print('The model suggests:')
print()
row = doctors[doctors['disease'] == present_disease[0]]
print('Consult ', str(row['name'].values))
print()
print('Visit ', str(row['link'].values))
#print(present_disease[0])
recurse(0, 1)
tree_to_code(classifier,cols)
VIGNESH BJ 16 211521205182
# This section of code to be run after scraping the data
diseases = dimensionality_reduction.index
diseases = pd.DataFrame(diseases)
doctors = pd.DataFrame()
doctors['name'] = np.nan
doctors['link'] = np.nan
doctors['disease'] = np.nan
doctors['disease'] = diseases['prognosis']
doctors['name'] = doc_dataset['Name']
doctors['link'] = doc_dataset['Description']
VIGNESH BJ 17 211521205182
OUTPUT :
RESULT :
Thus the chatbot for Health care Appointment scheduling has been implemented and
the output verified successfully.
VIGNESH BJ 18 211521205182
EX . NO : 3
CREATE A CHATBOT FOR RESTURENT RESERVATION
DATE :
AIM :
To create the chatbot for Resturent Reservation Using Pycharm
PROCEDURE :
1. Set Up PyCharm:
Install PyCharm if you haven't already. You can download it from the JetBrains website
and follow the installation instructions.
Open PyCharm and create a new Python project for your chatbot.
2. Create Python Virtual Environment:
Inside your PyCharm project, create a Python virtual environment to manage
dependencies. This helps isolate your project's dependencies from other projects.
Open the terminal in PyCharm and run the following command to create a virtual
environment named "venv":
python -m venv venv
Activate the virtual environment by running On Windows:
venv\Scripts\activate
3. Install Required Libraries:
Use pip to install the libraries required for your chatbot project. For example:
pip install flask openai
4. Create Flask Application:
Create a new Python file (e.g., app.py) to define your Flask application.
Write the Flask application code to handle HTTP requests and responses, including
routes for processing user messages and interacting with the OpenAI API.
5. Implement Chatbot Logic:
Write the backend logic for your chatbot, including functions to process user inputs,
make reservations, check availability, etc.
Integrate with the OpenAI API or any other natural language processing libraries for
understanding user messages and generating responses.
6. Design Frontend Interface:
Create HTML, CSS, and JavaScript files for the frontend interface of your chatbot.
Design the UI components for sending messages and displaying responses.
Link the frontend files to your Flask application to enable communication between the
backend and frontend.
7. Test and Debug:
Test your chatbot thoroughly to ensure it behaves as expected.
Debug any issues or errors that arise during testing, using PyCharm's debugging tools
and logging statements.
8. Deploy and Monitor:
Deploy your chatbot to a web server or hosting platform of your choice.
Monitor the performance of your chatbot and gather feedback from users to identify
areas for improvement.
VIGNESH BJ 19 211521205182
9. Document and Maintain:
Document the code and functionality of your chatbot to make it easier for others to
understand and maintain.
Continuously update and improve your chatbot based on user feedback and changes to
your requirements.
PROGRAM :
import json
from difflib import get_close_matches
while True:
user_input: str = input("You: ")
VIGNESH BJ 20 211521205182
if user_input.lower() == 'quit':
break
if best_match:
# If there is a best match, return the answer from the knowledge base
answer: str = get_answer_for_question(best_match, knowledge_base)
print(f"Bot: {answer}")
else:
print("Bot: I don't know the answer. Please ask again?")
new_answer: str = input("Type the answer or type 'skip' to skip: ")
if new_answer.lower() != 'skip':
knowledge_base["questions"].append(
{"question": user_input, "answer": new_answer})
save_knowledge_base('knowledge_base.json', knowledge_base)
print("Bot: Thank you! I've updated the knowledge base.")
if __name__ == "__main__":
chatbot()
OUTPUT :
VIGNESH BJ 21 211521205182
RESULT :
Thus the chatbot for Resturent reservation has been implemented and the output
verified successfully.
VIGNESH BJ 22 211521205182
EX . NO : 4
CREATE A CHATBOT FOR FITNESS AND WORKOUT ASSISTANT
DATE :
AIM :
To create the chatbot for Fitness and Workout Assistant using Pycharm
PROCEDURE :
1. Set Up PyCharm:
Install PyCharm if you haven't already. You can download it from the JetBrains
website and follow the installation instructions.
Open PyCharm and create a new Python project for your chatbot.
2. Create Python Virtual Environment:
Inside your PyCharm project, create a Python virtual environment to manage
dependencies.
Open the terminal in PyCharm and run the following command to create a
virtual environment named "venv":
python -m venv venv
3. Install Required Libraries:
Use pip to install the libraries required for your chatbot project. For example
pip install flask
4. Implement Backend Logic:
Write the backend logic for your chatbot, including functions to provide
workout suggestions, track progress, answer fitness-related questions, etc.
You may need to integrate with fitness tracking APIs or databases to retrieve
user data or provide personalized recommendations.
Consider incorporating natural language processing (NLP) capabilities to
understand user messages and extract relevant information.
5. Create Flask Application:
Create a new Python file (e.g., app.py) to define your Flask application.
Write the Flask application code to handle HTTP requests and responses,
including routes for processing user messages and interacting with the chatbot
logic.
6. Design Frontend Interface :
Optionally, create a frontend interface for your chatbot using HTML, CSS, and
JavaScript.
Design UI components for sending messages, displaying responses, and
visualizing workout plans or progress.
Integrate the frontend interface with your Flask application to enable
communication between the backend and frontend.
7. Testing and Debugging:
Test your chatbot thoroughly to ensure it behaves as expected.
Debug any issues or errors that arise during testing using PyCharm's debugging
tools and logging statements.
VIGNESH BJ 23 211521205182
8. Deployment and Monitoring:
Deploy your chatbot to a web server or hosting platform of your choice.
Monitor the performance of your chatbot and gather feedback from users to
identify areas for improvement.
9. Documentation and Maintenance:
Document the code and functionality of your chatbot to make it easier for others
to understand and maintain.
Continuously update and improve your chatbot based on user feedback and
changes to your requirements.
PROGRAM :
TOKEN = "439442918:AAFtoa3vmZ9uvBc3eNYojEVXXGm2GkTYmAE"
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
RegexHandler, ConversationHandler)
from telegram import Bot
import logging
import time
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s -
%(message)s',level=logging.INFO)
logger = logging.getLogger(__name__)
chat_data = {}
VIGNESH BJ 24 211521205182
def set_timer(bot, update, args, job_queue, chat_data):
print ("entered function")
chat_id = update.message.chat_id
try:
total = 0
reason = ""
one = args[0]
two = one[0:2]
three = one[2:4]
for i in range(1, len(args)):
reason += args[i] + " "
VIGNESH BJ 25 211521205182
else:
job = job_queue.run_repeating(alarmmedicine, context = chat_id,
interval = 86400, first = total)
if chat_id not in chat_data:
chat_data[chat_id] = []
chat_data[chat_id].append({'Job': job, 'Time':args[0], 'Reason':reason})
update.message.reply_text('Reminder successfully set!')
VIGNESH BJ 26 211521205182
job = chat_data[update.message.chat.id][_]['Job']
chat_data[update.message.chat.id].remove(chat_data[update.message.chat.id][_])
job.schedule_removal()
break
update.message.reply_text('Reminder Removed!')
return ConversationHandler.END
def main():
updater = Updater(TOKEN)
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler("start", start), CommandHandler("help", start),
CommandHandler("set", set_timer,pass_args = True, pass_job_queue = True,pass_chat_data =
True),
CommandHandler("unset", unset, pass_chat_data=True, pass_args=True)],
states={SELECTREMOVE: [MessageHandler(Filters.text, removeset,
pass_chat_data = True)],
},
fallbacks=[]
)
dp.add_handler(conv_handler)
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
VIGNESH BJ 27 211521205182
BASE.PY
TOKEN = "454168022:AAENNH29QY7oBnMQAN6Pd1mJjUNeoGKizT8"
URL = "https://api.telegram.org/bot{}/".format(TOKEN)
DISTANCE_THRESHOLD = 5
logger = logging.getLogger(__name__)
database = {}
VIGNESH BJ 28 211521205182
# List of facts about health
factList = ['A lack of exercise is now causing as many deaths as smoking across the world, a
study suggests.',
'People who regularly eat dinner or breakfast in restaurants double their
risk of becoming obese.',
'Laughing 100 times is equivalent to 15 minutes of exercise on a
stationary bicycle.',
'Sitting for more than three hours a day can cut two years off a person\'s
life expectancy.',
'Over 30% of cancer could be prevented by avoiding tobacco and
alcohol, having a healthy diet and physical activity.',
'Sleeping less than 7 hours each night reduces your life expectancy.',
'1 Can of Soda a day increases your chances of getting type 2 diabetes by
22%.',
'There are more skin cancer cases due to indoor tanning than lung cancer
cases due to smoking.',
'Exercise, like walking, can reduce breast cancer risk by 25%.',
'McDonalds\' Caesar salad is more fattening than their hamburger. Not
like the hamburger isn\'t fattening.',
'Severe Depression can cause us to biologically age more by increasing
the aging process in cells.',
'Chicken contains 266% more fat than it did 40 years ago. Someone is
feeding the chicken a little to much I guess.',
'Heavy marijuana smokers are at risk for some of the same health effects
as cigarette smokers, like bronchitis and other respiratory illnesses.',
'On average, people who complain live longer. Releasing the tension
increases immunity and boosts their health.',
'A half hour of physical activity 6 days a week is linked to 40% lower
risk of early death.',
'The U.S. spends more money per person on healthcare than any other
developed country, yet its life expectancy is below average.',
'1 out of every 4 dollars employers pay for healthcare in the U.S. is tied
to unhealthy lifestyle choices or conditions like smoking, stress, or obesity.',
'In terms of your health —not how you look or smell— you only really
have to shower once or twice a week. Well then I have been doing it right from the past 10
years.',
VIGNESH BJ 29 211521205182
'A scientist cracked his knuckles on one hand for over 50 years to prove
it did not cause Arthritis. What can I say he was a scientist after all.',
'Eating too much meat can accelerate your body\'s biological age.',
'Working past age 65 is linked to longer life, a study found.',
'People who read books live an average of almost 2 years longer than
those who do not read at all, a Yale research found.',
'You can burn 20% more fat by exercising in the morning on an empty
stomach. That is if you get up on time.',
'Breathing 100% oxygen, instead of the 21% in our atmosphere, is
generally bad, and sometimes toxic.',
'You can tweak your metabolic health by turning down the bedroom
thermostat a few degrees.',
'Violent dreams may be an early sign of brain disorders down the line,
including Parkinson\'s disease and dementia. Need to cut short on horror movies I guess.',
'More than 13 million working days are lost every year because of stress-
related illnesses. Stay with me won\'t let you take any stress',
'A study found that right-handed individuals have better oral hygiene and
the lower incidence of caries because of their \
better manual dexterity and brush efficiency. I knew I was doing
something better than the others.',
'Drinking very hot beverages increases your risk of developing cancer.
Need to cut down on that coffee man.',
'A study showed that it\'s not necessary to run, swim or work out at the
gym. Household chores such as vacuuming or scrubbing the floor, \
or merely walking to work provide enough exercise to protect the heart
and extend life. And you though household chores were easy.']
VIGNESH BJ 30 211521205182
inner_dictionary = current_user_dictionary[i]
coordinates = inner_dictionary['coordinates']
coordinate_dictionary["longitude"] = coordinates[1]
coordinate_dictionary["latitude"] = coordinates[0]
if checkDistance(user_location, coordinate_dictionary) <
DISTANCE_THRESHOLD and user_activity == inner_dictionary["activity"]:
partner_list.append(inner_dictionary)
VIGNESH BJ 31 211521205182
update.message.reply_text('You can type /help to know more about my Functions. \n
Please send me your location, '
'so I know where you live, or send /skip if
you don\'t want to.',
reply_markup=ReplyKeyboardRemove())
return LOCATION
return WHATUSERWANTS
VIGNESH BJ 32 211521205182
def whatuserwants(bot, update):
message = update.message.text
database[update.message.chat.id]['activity'] = ps.stem(message)
with open('database.pickle', 'wb') as f:
pickle.dump(database, f)
user = update.message.from_user
logger.info("%s wants to: %s", user.first_name, message)
update.message.reply_text('Finding someone nearby...')
print (database)
usernameList =
find_partner({"latitude":database[update.message.chat.id]['coordinates'][0],
"longitude":database[update.message.chat.id]['coordinates'][1]}, update.message.chat.id,
database[update.message.chat.id]['activity'])
if len(usernameList) != 0:
update.message.reply_text('Found the following user(s) near you with similar
interest.\n')
for data in usernameList:
update.message.reply_text('http://t.me/' + data['username'] + '/')
else:
update.message.reply_text("No users found with the same interest :( Please try
again later!")
return ConversationHandler.END
VIGNESH BJ 33 211521205182
reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
Miscellaneous Functions:
1. /bmicalculator - to calculate your BMI''',
reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
VIGNESH BJ 34 211521205182
printable_string = ""
current_user_dictionary = database
for i in current_user_dictionary:
if i!=user_chat_id:
printable_string += "@" +
current_user_dictionary[i]["username"] + " is planning to " +
current_user_dictionary[i]["activity"] + "!\n"
update.message.reply_text(printable_string)
except:
print ("list is empty")
return ConversationHandler.END
def sendToPeople():
global database
bot = Bot(token=TOKEN)
# print ("here", database)
while True:
print ("here")
if (database != {}):
# print ("here")
for j in database.keys():
factNumber = randint(0, len(factList)-1)
print ("Sending fact number", factNumber, "to user",
database[j]["first_name"])
bot.send_message(chat_id=j, text=factList[factNumber])
time.sleep(200)
# threading.Timer(200, sendToPeople).start()
VIGNESH BJ 35 211521205182
return BMICALCULATORHELPER
details = update.message.text
return ConversationHandler.END
VIGNESH BJ 36 211521205182
reason += args[i] + " "
VIGNESH BJ 37 211521205182
return ConversationHandler.END
chat_data[update.message.chat.id].remove(chat_data[update.message.chat.id][_])
job.schedule_removal()
break
update.message.reply_text('Reminder Removed!')
return ConversationHandler.END
VIGNESH BJ 38 211521205182
def main():
updater = Updater(TOKEN)
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start), CommandHandler('help',help),
CommandHandler('viewpeople',view_people),
CommandHandler('bmicalculator',bmi_calculator), CommandHandler('setreminder',
set_timer,pass_args = True,
pass_job_queue = True,
pass_chat_data = True)],
states={
LOCATION: [MessageHandler(Filters.location, location),
CommandHandler('skip', skip_location)],
WHATUSERWANTS: [MessageHandler(Filters.text, whatuserwants)],
BMICALCULATORHELPER: [MessageHandler(Filters.text,
bmicalculatorhelper)],
},
fallbacks=[CommandHandler('cancel', cancel)]
)
dp.add_handler(conv_handler)
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
try:
VIGNESH BJ 39 211521205182
database = pickle.load(open("database.pickle", 'rb'))
print (database)
except:
database = {}
# threading.Thread(target=sendToPeople).start()
main()
OUTPUT :
RESULT :
Thus the chatbot for Fitness and workout Assistant has been implemented and the
output verified successfully.
VIGNESH BJ 40 211521205182
EX . NO : 5
AI GENERATED EDUCATIONAL TUTORIALS USING DALL – E
DATE :
AIM :
The aim of using DALL-E in educational tutorials is to enhance engagement by
providing visually compelling content that captivates learners' attention. By incorporating
generated images, we aim to create an immersive learning experience that fosters active
participation and deeper understanding. .
PROCEDURE :
1. Topic Selection:
Choose a specific topic or concept that you want to cover in your tutorial.
Ensure that it's relevant to your audience and aligns with your educational
objectives.
2. Outline Creation:
Develop an outline for your tutorial, breaking down the topic into key points
or steps that you want to cover. This will serve as a roadmap for the tutorial
creation process.
3. Image Description:
Write detailed descriptions of the images you want to generate for each
point or step in your outline. Clearly communicate the visual elements, such
as objects, scenes, or diagrams, that you envision for each concept.
4. DALL-E Image Generation:
Use DALL-E to generate images based on the descriptions you've provided.
Submit the text descriptions to DALL-E and review the generated images to
ensure they accurately represent the intended concepts.
5. Text Integration:
Write concise and informative text to accompany each image in your
tutorial. This text should provide context, explanations, or instructions that
complement the visual content and help reinforce understanding.
VIGNESH BJ 41 211521205182
Arrange the images and text in a visually appealing layout. Use design
principles such as balance, hierarchy, and consistency to create a cohesive
and easy-to-follow presentation.
7. Review and Revision:
Review the tutorial to check for accuracy, clarity, and coherence. Make any
necessary revisions to the images, text, or layout to improve the overall
quality of the tutorial.
8. Testing and Feedback:
Share the tutorial with a small group of users or peers to gather feedback.
Pay attention to their comments and suggestions, and use them to refine
your tutorial further.
9 .Finalization and Publishing:
Make any final adjustments based on feedback and prepare the tutorial for
publication. Choose a suitable platform or medium to share your tutorial
with your target audience, whether it's a website, blog post, presentation, or
educational platform.
PROGRAM :
import openai
import matplotlib.pyplot as plt
openai.api_key = 'your_openai_api_key_here'
def generate_images(text_descriptions):
response = openai.Image.create(
engine="davinci",
prompt=text_descriptions,
max_tokens=50,
temperature=0.7
)
image_url = response['output']['url']
# Display the generated image
image = plt.imread(image_url)
plt.imshow(image)
plt.axis('off')
VIGNESH BJ 42 211521205182
plt.show()
text_descriptions = """
1. A green apple on a wooden table.
2. A person riding a bicycle in a park.
# Generate images based on the text descriptions
generate_images(text_descriptions)
OUTPUT :
RESULT :
Thus the AI Educational tutorial using DALL – E Algorithm has been implemented
and the output verified successfully.
VIGNESH BJ 43 211521205182
EX . NO : 6
CREATE A AUTOMATED PROPERTY TOUR VIDEOS USING AI
DATE :
FOR REAL ESTATE MARKETING
AIM :
To create a automated property tour videos using Ai for real Estate marketing .
PROCEDURE :
PROGRAM:
import os
import random
import textwrap
from gtts import gTTS
from moviepy.editor import VideoClip, concatenate_videoclips
from moviepy.video.io.VideoFileClip import VideoFileClip
tts.save(output_path)
VIGNESH BJ 44 211521205182
Def combine_videos(video_paths, output_path):
video_clips = [VideoFileClip(path) for path in video_paths]
final_clip = concatenate_videoclips(video_clips)
final_clip.write_videofile(output_path)
# Generate voiceover
voiceover_output_path = 'voiceover.mp3'
generate_voiceover(script_text, voiceover_output_path)
OUTPUT :
RESULT :
Thus the program for automated property tour video for real estate marketing has been
implemented and the output verified successfully.
VIGNESH BJ 45 211521205182
EX . NO : 7
DEVELOP AND ASSIST USERS IN PLANNING AND
DATE :
COORDINATING EVENTS
AIM :
To create and develop and assist users in planning and coordinating events .
PROCEDURE :
1. Define Event Objectives and Requirements:
Work with the event organizer to understand the objectives, goals, and
requirements of the event.
Determine the event type, target audience, budget, timeline, and any special
considerations.
2. Create an Event Plan:
Develop a comprehensive event plan outlining all aspects of the event, including
logistics, marketing, programming, and staffing.
Define roles and responsibilities for team members involved in planning and
executing the event.
3. Set a Date and Venue:
Choose a suitable date and time for the event, taking into account factors such
as availability, seasonality, and competing events.
Select an appropriate venue that can accommodate the expected number of
attendees and meets the requirements of the event.
4. Secure Vendors and Suppliers:
Identify and secure vendors and suppliers for catering, audiovisual equipment,
decorations, and other event essentials.
Negotiate contracts, pricing, and terms with vendors to ensure favorable
arrangements for the event.
5. Develop Marketing and Promotion Strategies:
Create a marketing and promotion plan to generate awareness and interest in the
event.
Utilize various channels such as social media, email marketing, press releases,
and partnerships to reach the target audience.
6. Manage Registrations and Attendees:
Set up an online registration system to collect attendee information and track
RSVPs.
Communicate event details, schedules, and logistics to registered attendees via
email or event management platforms.
7. Coordinate Event Logistics:
Coordinate logistics such as transportation, accommodations, signage,
registration desks, and security.
Develop a detailed timeline and schedule for setup, teardown, and event
activities.
8. Prepare Event Materials and Resources:
VIGNESH BJ 46 211521205182
Create event materials such as programs, agendas, name badges, signage, and
presentation materials.
Ensure that all necessary resources and supplies are available and organized for
the event.
9. Train Staff and Volunteers:
Provide training and guidance to event staff and volunteers on their roles,
responsibilities, and expectations.
Conduct rehearsals or run-throughs to familiarize team members with event
procedures and protocols.
10. Execute and Monitor the Event:
Oversee the execution of the event plan, ensuring that all activities and
operations are carried out according to schedule and requirements.
Monitor event progress, address any issues or challenges that arise, and make
adjustments as needed to keep the event on track.
PROGRAM :
app = Flask(__name__)
event_resources = {
'vendors': {
'catering': ['ABC Catering', 'XYZ Catering'],
'photography': ['John Smith Photography', 'Lisa Photography'],
# Add more vendor categories and listings as needed
},
'budgeting_tips': [
'Create a detailed budget spreadsheet to track expenses.',
'Allocate funds for each aspect of the event: venue, catering, decorations, etc.'
],
'management_guidelines': [
'Develop a timeline with key milestones leading up to the event.',
'Delegate tasks to team members and establish clear communication channels.'
]
}
event_details = {}
@app.route('/chat', methods=['POST'])
def chat():
user_message = request.json['message']
VIGNESH BJ 47 211521205182
bot_response = process_user_message(user_message)
return jsonify({'message': bot_response})
def process_user_message(user_message):
global event_details
if 'start' in user_message.lower():
event_details = {}
return "Let's get started! What is the name of your event?"
elif 'name' in event_details:
event_details['name'] = user_message
return "Great! When is the date of your event?"
elif 'date' in event_details:
event_details['date'] = user_message
return "Where is the venue of your event?"
elif 'venue' in event_details:
event_details['venue'] = user_message
return "What is your estimated budget for the event?"
elif 'budget' in event_details:
event_details['budget'] = user_message
return "Thank you! Your event details have been recorded."
elif 'resources' in user_message.lower():
return "Sure! Here are some event planning resources you can access:\n1. Vendors\n2.
Budgeting Tips\n3. Management Guidelines"
elif 'vendors' in user_message.lower():
return format_resources(event_resources['vendors'])
elif 'budgeting' in user_message.lower():
return format_resources(event_resources['budgeting_tips'])
elif 'management' in user_message.lower():
return format_resources(event_resources['management_guidelines'])
else:
return "Welcome to the Event Planning Assistant! How can I help you with your event?"
def format_resources(resources):
formatted_text = "Here are the available resources:\n"
for category, listings in resources.items():
formatted_text += f"\n{category.capitalize()}:\n"
for item in listings:
formatted_text += f"- {item}\n"
return formatted_text
if __name__ == '__main__':
app.run(debug=True)
VIGNESH BJ 48 211521205182
OUTPUT :
RESULT :
Thus the program for creating a chatbot which assist users to plan and co ordinate event
has been implemented and the output verified successfully.
VIGNESH BJ 49 211521205182
EX . NO : 8
DEVELOP AND ASSIST USERS IN LEARNING A NEW LANGUAGE
DATE :
BY PRACTICING CONVERSATIONS
AIM :
To develop a chatbot which assist the users to learn a new language by practicing
conversations.
PROCEDURE :
1. Define the Scope and Objectives:
Determine the scope of your language learning chatbot, including the target
language, proficiency levels, learning goals, and conversational scenarios you
want to cover.
2. Collect Training Data:
Gather a dataset of conversations and language learning materials in the target
language.
Curate a diverse range of dialogues, language exercises, vocabulary lists,
grammar rules, and cultural references to train the chatbot.
3. Preprocess and Augment Data:
Preprocess the training data to clean and standardize text, remove noise, and
ensure consistency.
Augment the dataset by generating additional training examples using
techniques like paraphrasing, rephrasing, or translating to increase the diversity
of input prompts.
4. Train Generative AI Model:
Choose a Generative AI model like GPT-3 and fine-tune it on your preprocessed
training data.
Train the model to generate coherent and contextually relevant responses to
language learning prompts and inquiries.
5. Design Chatbot Interface:
Develop a user interface for the chatbot, which can be a web-based application,
mobile app, or messaging platform integration.
Design the interface to facilitate user interaction, input of language prompts,
display of chatbot responses, and tracking of user progress.
6. Implement Conversational Logic:
Define the conversational logic and dialogue management system for the
chatbot.
Structure the conversation flow to guide users through language exercises,
provide feedback, and offer assistance based on user input.
7. Integrate Natural Language Processing (NLP):
Incorporate NLP techniques to process user input, extract intent, and identify
language learning objectives.
VIGNESH BJ 50 211521205182
Use NLP libraries and frameworks to tokenize text, perform part-of-speech
tagging, and analyze sentiment to enhance understanding and response
generation.
8. Deploy and Test the Chatbot:
Deploy the language learning chatbot to a hosting platform or cloud service to
make it accessible to users.
Conduct extensive testing to evaluate the chatbot's performance, accuracy, and
usability across different devices and user scenarios.
Gather feedback from users and iterate on the chatbot's design and functionality
to improve user satisfaction and learning outcomes.
9. Monitor and Improve:
Continuously monitor the chatbot's performance and collect user feedback to
identify areas for improvement.
Fine-tune the Generative AI model, update training data, and refine
conversational scripts to enhance the chatbot's effectiveness and adaptability.
PROGRAM :
import pronounce_assessment_file
import intonation
import tts_to_wav
from openai import OpenAI
import stt
import tts
voice_name = 'en-US-JennyMultilingualNeural'
wrong_pronounce = []
user_name = None
client = OpenAI(
# api_key defaults to os.environ.get("OPENAI_API_KEY")
api_key="YOUR_OPENAI_API_KEY",
)
VIGNESH BJ 51 211521205182
def chat(user_input_audio, option):
#-------------- MISPRONOUNCED WORDS --------------
mispronounced_words = []
user_input_text = stt.recognize_from_microphone(user_input_audio)
print(user_input_text)
output_filename = 'output.wav'
VIGNESH BJ 52 211521205182
pitch_per_word, overall_pitch = intonation.pitch(pitch_input_text, user_input_audio)
print(f'Accuracy: {accuracy} \nCompleteness: {completeness} \nFluency: {fluency} \nPer Word
Evaluation: {per_word_pronounciation_evaluation} \nPitch Per Word: {pitch_per_word} \nOverall Pitch:
{overall_pitch}')
for idx, word in enumerate(final_words):
if word.accuracy_score < 50:
mispronounced_words.append(f'{word.word}: {word.accuracy_score}')
print('\nYou mispronounced:',word.word, 'accuracy:', word.accuracy_score)
# print(mispronounced_words)print(mispronounced_words)
chat(user_input_audio, 6)
englishtutor.py
import os
import openai
import pronounce_assessment_mic
import tts
import string
from openai import OpenAI
option = 6
voice_name = 'en-US-JennyMultilingualNeural'
VIGNESH BJ 53 211521205182
wrong_pronounce = []
user_name = None
client = OpenAI(
# api_key defaults to os.environ.get("OPENAI_API_KEY")
api_key="YOUR_OPENAI_API_KEY",
)
def chat():
#-------------- GETTING USER INPUT --------------
prompt = ''
VIGNESH BJ 54 211521205182
{'role': 'system', 'content': 'you are an event planner talking to a client regarding an upcomng event.
keep the conversation lively, professional and brief'}
]
chat()
inotation.py
VIGNESH BJ 55 211521205182
import parselmouth
import numpy as np
import tts
# Calculate pitch
pitch = sound.to_pitch()
# print(pitch)
OUTPUT :
RESULT :
Thus the program for creating a chatbot which help users to learn different languages
has been implemented and the output verified successfully.
VIGNESH BJ 56 211521205182
EX . NO : 9
DEVELOP A CHATBOT TO ASSIST USERS IN MANAGING
DATE :
PERSONAL FINANCES
AIM :
To develop a chatbot to assist users in maching personal finances .
PROCEDURE :
1. Define Objectives and Scope:
Determine the goals and objectives of the chatbot, such as budgeting, expense tracking,
savings planning, investment advice, or debt management.
Identify the target audience and their specific financial needs and preferences.
2. Choose a Platform and Framework:
Select a platform or framework for building the chatbot, such as Facebook Messenger,
Slack, WhatsApp, or a custom web application.
Choose a development framework or toolkit that supports chatbot development, such as
Microsoft Bot Framework, Dialogflow, Rasa, or custom development with Python.
3. Design Conversational Flows:
Define the conversational flows and user journeys for different financial tasks and
scenarios.
Map out the dialogue paths for common user interactions, such as checking account
balances, categorizing expenses, setting budgets, or receiving financial advice.
4. Gather and Preprocess Data:
Collect relevant financial data sources, such as bank account transactions, credit card
statements, income statements, and budget spreadsheets.
Preprocess and clean the data to remove duplicates, standardize formats, and ensure
data privacy and security compliance.
5. Integrate APIs and Services:
Integrate with third-party APIs and financial services to access real-time data and
functionalities, such as account aggregation, transaction categorization, investment
analysis, or credit score monitoring.
Authenticate users securely and obtain consent for accessing their financial
information.
6. Develop Chatbot Logic and Responses:
Implement the chatbot logic and response generation based on user inputs and financial
queries.
Design natural language processing (NLP) algorithms to understand user intent, extract
relevant information, and generate appropriate responses.
Provide personalized recommendations, insights, and actionable advice based on the
user's financial situation and goals.
7. Implement Security and Compliance:
Implement robust security measures to protect users' sensitive financial data, such as
encryption, tokenization, and secure data storage practices.
Ensure compliance with relevant regulations and standards, such as GDPR, CCPA,
PSD2, or financial industry regulations like PCI DSS or FINRA.
8. Test and Iterate:
Conduct extensive testing to validate the chatbot's functionality, accuracy, and usability
across different devices and platforms.
VIGNESH BJ 57 211521205182
Gather user feedback and iterate on the chatbot's design and features to improve user
experience and satisfaction.
9. Deploy and Monitor:
Deploy the chatbot to the chosen platform or channels, and make it available to users.
Monitor the chatbot's performance, usage metrics, and user feedback to identify areas
for optimization and enhancement.
Continuously update and improve the chatbot based on user feedback, evolving
financial needs, and technological advancements.
PROGRAM :
data={"intents":[
{"tag": "welcome",
"patterns":["Hi","Hello","How are you","whats up", "How do you do","How’s
the day?","Hey are you there","How is everything going","glad to meet you"],
"responses":["Hello","Glad to see you again", "Hi there, How can I help
you", "Hello! what you are looking for?", "Hello, how may I help you"],
},
{"tag": "endingnote",
"patterns":["see you. bye","Good Bye","ok then bye","That’ s enough for
me"," Im leaving","See u later! Goodbye","nice to meet you" , "The
bargaining session was fun!I’m happy that I got it at cheap price, see u
again","Enjoyed the experience, good bye"],
"responses":["Hey, Thank you for visiting","Hope to see you again, it was
nice talking with you", " wish you a good day! Hope to have a talk with you
later","Thanks for your time with us.Hope you enjoyed it and satisfied. See
you later", "Sad to see you go. Come whenever you need to bye from us. Stay
intouch."],
},
{"tag": "name",
"patterns":["whats you name?","who are you?","what can I call you","tell me
your name","Are u a robot","Are you a chatbot"],
"responses":["It’s FinBot here, a digital+financial assistant to help you
out","You can call me FinBot.Im a chatRobot/chatbot, tell me what you want",
"I’m FinBot,a digital+financial assistant, I can guide you in our ecommerce
website.", "Its FinBot Here,a digital +financial assistant. How may I help
you?"],
},
{"tag": "shopping",
"patterns":["I would like to buy something here","can I buy something","What
all things are there","can you recommend me something from here","is there
any thing cheaper here","Hey, I want a black shoe"],
"responses":["Yes please, we have a lot of new collections for
you","Ofcourse, there are new offers for you, fantastic selections, choose
what interests you!","Well casual shoes at Rs 220, this offer won’t stay
much","there are good varieties of coloured shoes too also there are black
formal shoes. Take one"],
},
{"tag": "time period",
"patterns":["till what time this be offered?","When will the shop
close?","when will the shop open","How much time it will take for
delivery","When will this site close?","When are you people open","When will
this store be open?", "Is this store will be open at Sunday?"],
"responses":["Our shop centre will be open from 9 am-9pm in all the
days","Yes, we are operating on all the weekdays from 9 am to 9pm", "We are
there to provide services from Monday-sunday from 9 am-9pm","We are
operating from 9 am-9 pm every day"],
VIGNESH BJ 58 211521205182
}}
import json
def writeTOJsonFile(path,data1):
filepathname='./'+path+'/'+'1ECONO_GopikaSR_18412_DATA'+'.json'
with open(filepathname,'w') as fp:
json.dump(data,fp)
writeTOJsonFile('./',data)
with open('/content/1ECONO_GopikaSR_18412_DATA.json', 'r') as f:
intents = json.load(f)
intents
import numpy as np
import random
import json
import torch
import torch.nn as nn
#importing nltk and necessary downloads
import nltk
nltk.download('punkt')
#Im using porter stemmer here
from nltk.stem.porter import PorterStemmer
from torch.utils.data import Dataset, DataLoader
nltk.download('all')
VIGNESH BJ 59 211521205182
!pip install torchviz
Collecting torchviz
Downloading https://files.pythonhosted.org/packages/8f/8e/a9630c7786b846d0
8b47714dd363a051f5e37b4ea0e534460d8cdfc1644b/torchviz-0.0.1.tar.gz (41kB)
# Hyper-parameters are--->
num_epochs = 1000
batch_size = 8
learning_rate = 0.001
#len(X_train[0]) means the length of 1st bag of words because they all have
the same size.
#if we want we can just print and check. But its clear here.
input_size = len(X_train[0])
hidden_size = 8
output_size = len(tags)
#lets print the values
print("inputsize=",input_size)
print("outputsize=",output_size)
inputsize= 209
outputsize= 47
Yes they are working
LETS CHAT
bot_name = "FinBot"
#for taking the input
name=input("Enter Your Name: ")
VIGNESH BJ 60 211521205182
print("FinBot:Hey, Let's chat! (type 'quit' to exit)Also when you start
bargaining give digits")
while True:
#once the person types his name, then from the next chat onwards the name
will be shown
sent=input(name+':')
if sent == "quit":
break
#since im going to offer bargaining offer for only one product and its
rated price is 30 Rs.
#However the person will tell only numbers ranging from 1 to 30
if sent in
["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"
,"18","19","20","21","22","23","24","25","26","27","28","29","30"]:
bargain(sent)
else:
sent = tokenize(sent)
X = BagOfWords(sent, all_the_words)
X = X.reshape(1, X.shape[0])
X = torch.from_numpy(X).to(device)
output = model(X)
_, predicted = torch.max(output, dim=1)
tag = tags[predicted.item()]
OUTPUT :
VIGNESH BJ 61 211521205182
GopikaSR:15
FinBot: Sorry, this is of latest fashion, Can you raise the amount a little
bit
GopikaSR:17
FinBot: Sorry, this is of latest fashion, Can you raise the amount a little
bit
GopikaSR:19
FinBot: Oh no sorry. Please raise a little bit
GopikaSR:20
FinBot: Oh no sorry. Please raise a little bit
GopikaSR:23
FinBot:Yes agreed! Now,you can buy the ribbon at this price
GopikaSR:Nice to meet you
FinBot: wish you a good day! Hope to have a talk with you later
GopikaSR:What is a bitcoin?
FinBot: Bitcoin is a cryptocurrency created in 2009. Marketplaces called “bi
tcoin exchanges” allow people to buy or sell bitcoins using different curren
cies
GopikaSR:What is cryptocurrency?
FinBot: A cryptocurrency is a digital or virtual currency designed to work a
s a medium of exchange
GopikaSR:Do you know crowdfunding?
FinBot: Crowdfunding is the use of small amounts of capital from a large nu
mber of individuals to finance a new business venture.
GopikaSR:leverage?
FinBot: Financial leverage which is also known as leverage or trading on equ
ity, refers to the use of debt to acquire additional assets.
GopikaSR:What is bank run?
FinBot: A situation in which depositors withdraw funds from a commercial ban
k because they fear that it may go bankrupt and not honour its liabilities s
uch as the deposits of the bank's savers.
GopikaSR:Tell me about bank assets.
FinBot: Assets are “owned” by the bank e.g. cash, balances at Bank of Englan
d, loans (Advances), securities (e.g. Bonds) and fixed assets.
GopikaSR:what is mean by term life insurance?
FinBot: If you die within the set term, your beneficiaries receive a payout.
If you don't,the policy expires with no value.
GopikaSR:net worth mean?
FinBot: Your networth is simply the difference between your assets
GopikaSR:I'm leaving
FinBot: I do not understand...
GopikaSR:bye
FinBot: Hey, Thank you for visiting
GopikaSR:quit
RESULT :
Thus the python program for creating a chatbot which can assist the user for there
financial management has been implemented and the output verified successfully.
VIGNESH BJ 62 211521205182
EX . NO : 10
CREATE A CHATBOT TO PROVIDE BASIC LEGAL ADVICES
DATE :
AND GUIDANCE
AIM :
To create a chatbot to provide basic legal advices and guidances using Pycharm.
PROCEDURE :
1. Define the Scope and Objectives:
Determine the scope of legal topics the chatbot will cover, such as contract law,
family law, employment law, or intellectual property.
Identify the target audience and their specific legal needs, such as individuals
seeking general legal information or small businesses requiring basic legal
guidance.
2. Choose a Platform and Framework:
Select a platform or framework for building the chatbot, such as Facebook
Messenger, Slack, WhatsApp, or a custom web application.
Choose a development framework or toolkit that supports chatbot development,
such as Microsoft Bot Framework, Dialogflow, Rasa, or custom development
with Python.
3. Research Legal Content:
Gather legal content and resources relevant to the chosen legal topics, such as
legal statutes, regulations, case law, and legal guides.
Curate a knowledge base of frequently asked legal questions, common legal
issues, and practical legal advice.
4. Design Conversational Flows:
Define the conversational flows and user journeys for different legal scenarios
and inquiries.
Map out the dialogue paths for common legal interactions, such as asking
questions, receiving legal advice, or accessing legal resources.
5. Implement Natural Language Processing (NLP):
Develop natural language processing (NLP) algorithms to understand user
intent, extract relevant information, and generate appropriate responses.
Implement named entity recognition (NER) to identify legal terms, concepts,
and entities mentioned in user queries.
6. Develop Chatbot Logic and Responses:
Implement the chatbot logic and response generation based on user inputs and
legal queries.
Design decision trees or rule-based systems to handle legal inquiries, provide
accurate information, and offer basic legal advice.
Provide disclaimers and caveats regarding the limitations of the chatbot's advice
and the importance of consulting with a qualified attorney for specific legal
matters.
7. Integrate APIs and Services:
Integrate with third-party legal APIs and services to access legal databases,
research tools, or legal document templates.
VIGNESH BJ 63 211521205182
Authenticate users securely and obtain consent for accessing their legal
information and providing personalized advice.
8. Implement Security and Compliance:
Implement robust security measures to protect users' sensitive legal information
and maintain confidentiality.
Ensure compliance with relevant regulations and standards, such as GDPR,
CCPA, or legal industry regulations like attorney-client privilege.
9. Test and Iterate:
Conduct extensive testing to validate the chatbot's functionality, accuracy, and
usability across different devices and platforms.
Gather user feedback and iterate on the chatbot's design and features to improve
user experience and satisfaction.
10. Deploy and Monitor:
Deploy the chatbot to the chosen platform or channels, and make it available to
users.
Monitor the chatbot's performance, usage metrics, and user feedback to identify
areas for optimization and enhancement.
Continuously update and improve the chatbot based on user feedback, evolving
legal needs, and technological advancements.
PROGRAM :
# -*- coding: utf-8 -*-
import os
import time
from typing import Dict, Optional
import streamlit as st
from langchain.chains import RetrievalQAWithSourcesChain
from langchain_community.vectorstores.pinecone import Pinecone as LangChainPinecone
from langchain_openai.embeddings import OpenAIEmbeddings
from langchain_openai.llms import OpenAI
from pinecone import Pinecone
INDEX_NAME = "building-regulations"
PROMPT_TEMPLATE = """You're a specialized chatbot tasked with assisting architects by
providing precise information on
British building regulations, as detailed in the provided document.
VIGNESH BJ 64 211521205182
Ensure your answers are:
- Directly derived from the document's contents.
- Clear and concise, facilitating quick comprehension.
- Free of personal opinions or external advice.
In instances where the document does not contain the necessary information, or if you're
uncertain, clearly state
this to the user, indicating that the response is based on best judgment rather than document
specifics.
Question:"""
NUM_RETRIEVED_DOCS = 5
TEMPERATURE = 0.3
Args:
user_query (str): The user's query.
Returns:
Dict[str, Optional[str]]: A dictionary containing the 'answer' and optionally 'sources'.
"""
full_query = PROMPT_TEMPLATE + user_query
pc_client = initialize_pinecone_client(api_key=st.secrets["pinecone_api_key"])
VIGNESH BJ 65 211521205182
embedding_model = OpenAIEmbeddings(model="text-embedding-ada-002",
openai_api_key=st.secrets["openai_api_key"])
index = pc_client.Index(INDEX_NAME)
index.describe_index_stats()
return response
**Knowledge base**:
[The merged Approved Documents](https://www.gov.uk/guidance/building-regulations-and-
approved-documents-index)
(last updated 8 March 2023)
VIGNESH BJ 66 211521205182
**Sample Question**:
_In the context of food preparation areas, what are the key requirements for sink provision
according to Requirement G6,
and how does it differ in dwellings and buildings other than dwellings?_
VIGNESH BJ 67 211521205182
OUTPUT :
RESULT :
Thus the python program for creating a chatbot which can assist the user to get the legal
advices has been implemented and the output has been executed successfully.
VIGNESH BJ 68 211521205182