You are on page 1of 68

INTRODUCTION TO GENERATIVE AI

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.

Types of Generative Algorithms:


Variational Autoencoders (VAEs): VAEs are a type of generative model that learns
to encode and decode data. They are commonly used for tasks such as image generation and data
compression.
Generative Adversarial Networks (GANs):
GANs consist of two neural networks - a generator and a discriminator - that are trained
together in a competitive setting. The generator creates fake data, while the discriminator tries
to distinguish between real and fake data. This adversarial training process results in the
generator producing increasingly realistic data.
Autoregressive Models:
Autoregressive models generate data one element at a time, with each element conditioned on
the previous elements. Examples of autoregressive models include language models like GPT
(Generative Pre-trained Transformer), which generate text, and PixelRNNs, which generate
images pixel by pixel.

Tools used in Gen AI:


Tools used in Gen AI encompass a wide range of software frameworks, libraries, platforms,
and technologies that facilitate the development, training, deployment, and evaluation of
advanced AI systems. These tools cover various aspects of AI research and application,
including machine learning, deep learning, natural language processing, computer vision,
reinforcement learning, and more. Here are some key tools commonly used in Gen AI:

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.

Hugging Face Transformers:

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.

Applications of Generative AI:


Image Generation:
Generative AI algorithms like DALL-E and StyleGAN are capable of creating high-quality,
realistic images based on textual descriptions or other input data.
Text Generation:
Language models like GPT-3 can generate coherent and contextually relevant text based on
prompts provided by users. These models have applications in content generation, dialogue
systems, and natural language understanding tasks.
Creative Design:
Generative AI is increasingly being used in creative fields such as art, design, and music
composition. Artists and designers can use generative algorithms to explore new ideas,
generate novel designs, and create unique pieces of artwork.
Data Augmentation:
Generative models can be used to augment training data for machine learning models. By
generating synthetic data, these models can help improve the performance and robustness of
machine learning systems.
Generative AI holds immense potential to transform various industries and enable new forms
of creativity and innovation. However, it also raises ethical and societal considerations,
particularly regarding the authenticity and ownership of generated content. As research in this
field continues to advance, it will be important to address these challenges while harnessing the
benefits of generative AI for positive impact.

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.

Explainability and Transparency:


Gen AI systems prioritize transparency and explainability, allowing users to understand how
decisions are made and providing insights into the underlying mechanisms of AI algorithms.
This is crucial for building trust and accountability, especially in high-stakes domains like
healthcare, finance, and autonomous systems.

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).

# Customize your product list if necessary.


product_list = '''
# Fashion Shop Product List

## Women's Clothing:

- T-shirt
- Price: $20
- Available Sizes: Small, Medium, Large, XL
- Available Colors: Red, White, Black, Gray, Navy

- Elegant Evening Gown


- Price: $150
- Available Sizes: Small, Medium, Large, XL
- Available Colors: Black, Navy Blue, Burgundy

- Floral Summer Dress


- Price: $45
- Available Sizes: Small, Medium, Large
- Available Colors: Floral Print, Blue, Pink

- 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

- Casual Denim Jeans


- Price: $35
- Available Sizes: 28, 30, 32, 34
- Available Colors: Blue Denim, Black

- Polo Shirt Collection


- Price: $25 each

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

- Formal Leather Shoes


- Price: $90
- Available Sizes: 7-11
- Available Colors: Brown, Black

## 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

- Trendy Kids' Backpacks


- Price: $30
- Available Colors: Blue, Red, Purple

## 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

- Quick-Dry Sports T-shirt


- Price: $20
- Available Sizes: Small, Medium, Large
- Available Colors: Red, Blue, Gray

'''

context = [{'role': 'system',


'content': f"""
You are ShopBot, an AI assistant for my online fashion shop - Nhi Yen.

Your role is to assist customers in browsing products, providing information, and guiding them
through the checkout process.

Be friendly and helpful in your interactions.

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.

The Current Product List is limited as below:

```{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}"})

# Record the start time


start_time = time.time()

response = get_completion_from_messages(context)

# Record the end time


end_time = time.time()

# Calculate the duration


duration = end_time - start_time

# 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
},
)

context.append({'role': 'assistant', 'content': f"{response}"})

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]))

inp = widgets.Text(value="Hi", placeholder='Enter text here…')


button_conversation = widgets.Button(description="Chat!")
button_conversation.on_click(collect_messages)

dashboard = widgets.VBox([inp, button_conversation])

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)

Certainly! Here's a summary of your order:

| Product | Color | Size | Price |


|---------------------|-------|------|-------|
| Red Women's T-shirt | Red | Small| $20 |
| Black Running Shoes | Black | 10 | $40 |

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

# Importing the dataset


training_dataset = pd.read_csv('Training.csv')
test_dataset = pd.read_csv('Testing.csv')

# Slicing and Dicing the dataset to separate features from predictions


X = training_dataset.iloc[:, 0:132].values
#print(X)
y = training_dataset.iloc[:, -1].values
#print(y)

# Dimensionality Reduction for removing redundancies


dimensionality_reduction = training_dataset.groupby(training_dataset['prognosis']).max()
#print(dimensionality_reduction)

# Encoding String values to integer constants


from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
y = labelencoder.fit_transform(y)

VIGNESH BJ 13 211521205182
#print(y)

# Splitting the dataset into training set and test set


from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)

# Implementing the Decision Tree Classifier


from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier()
classifier.fit(X_train, y_train)

# Saving the information of columns


cols = training_dataset.columns
cols = cols[:-1]

# Checking the Important features


importances = classifier.feature_importances_
indices = np.argsort(importances)[::-1]
features = cols

# Implementing the Visual Tree


from sklearn.tree import _tree

# Method to simulate the working of a Chatbot by extracting and formulating questions


def execute_bot():

print("Please reply with yes/Yes or no/No for the following symptoms")


def print_disease(node):
#print(node)

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

doc_dataset = pd.read_csv('doctors_dataset.csv', names = ['Name', 'Description'])

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']

record = doctors[doctors['disease'] == 'AIDS']


record['name']
record['link']

# Execute the bot and see it in Action


execute_bot()

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

# Load the knowledge base from a JSON file


def load_knowledge_base(file_path: str):
with open(file_path, 'r') as file:
data: dict = json.load(file)
return data

# Save the updated knowledge base to the JSON file


def save_knowledge_base(file_path: str, data: dict):
with open(file_path, 'w') as file:
json.dump(data, file, indent=2)

# Find the closest matching question


def find_best_match(user_question: str, questions: list[str]) -> str | None:
matches: list = get_close_matches(
user_question, questions, n=1, cutoff=0.6)
return matches[0] if matches else None

def get_answer_for_question(question: str, knowledge_base: dict) -> str | None:


for q in knowledge_base["questions"]:
if q["question"] == question:
return q["answer"]
return None

# Main function to handle user input and respond


def chatbot():
knowledge_base: dict = load_knowledge_base('knowledge_base.json')

while True:
user_input: str = input("You: ")

VIGNESH BJ 20 211521205182
if user_input.lower() == 'quit':
break

# Finds the best match, otherwise returns None


best_match: str | None = find_best_match(
user_input, [q["question"] for q in knowledge_base["questions"]])

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 = {}

SELECTREMOVE, ALARM = range(2)

def start(bot, update):


update.message.reply_text('Hi! Use /set <24 hr time><space><reason> to set a
reminder')
return ConversationHandler.END
def alarmgym(bot, job):
bot.send_message(job.context, text = "It's time for your exercise!")
def alarmmedicine(bot, job):
bot.send_message(job.context, text = "It's time to take your medicine")

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] + " "

if int(time.ctime()[11:13]) <= int(two) and int(time.ctime()[11:13]) <= int(two):


total += 3600 * (int(two) - int(time.ctime()[11:13]))
total += 60 * (int(three) - int(time.ctime()[14:16]))
elif int(time.ctime()[11:13]) <= int(two) and int(time.ctime()[11:13]) > int(two):
total += 3600 * (int(two) - int(time.ctime()[11:13]))
total -= 60 * (int(time.ctime()[14:16]) - int(three))
elif int(time.ctime()[11:13]) > int(two) and int(time.ctime()[11:13]) < int(two):
total += 3600 * ((24 - int(time.ctime()[11:13])) + (int(two)))
total += 60 * (int(three) - int(time.ctime()[14:16]))
else:
total += 3600 * ((24 - int(time.ctime()[11:13])) + (int(two)))
total -= 60 * (int(time.ctime()[14:16]) - int(three))
if total < 0:
update.message.reply_text('Sorry we can not go back to future!')
return
if "exercise" in reason:
job = job_queue.run_repeating(alarmgym, context = chat_id, interval =
86400, first = total)

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!')

except (IndexError, ValueError):


update.message.reply_text('Usage: /set <24 hr time><space><reason>')
return ConversationHandler.END

def unset(bot, update, args, chat_data):


tosend = ""
if len(chat_data[update.message.chat.id]) == 0:
update.message.reply_text('You have no remainders set')
return
else:
update.message.reply_text("please enter the time of the reminder you wish to
delete from among the following")
for _ in range(len(chat_data[update.message.chat.id])):
tosend += (str(chat_data[update.message.chat.id][_]['Time']) + " : " +
str(chat_data[update.message.chat.id][_]['Reason'])) + "\n"
update.message.reply_text(tosend)
return SELECTREMOVE

def removeset(bot, update, chat_data):


for _ in range(len(chat_data[update.message.chat.id])):
if chat_data[update.message.chat.id][_]['Time'] == update.message.text:

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 error(bot, update, error):


logger.warning('Update "%s" caused error "%s"', update, error)

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

from telegram import Bot


from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
RegexHandler,
ConversationHandler)
import pickle
import threading
import logging
import re
import nltk
import time
import requests
import json
from random import randint
from nltk.stem.porter import PorterStemmer
ps = PorterStemmer()
from math import radians, cos, sin, asin, sqrt
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)

logger = logging.getLogger(__name__)

LOCATION, WHATUSERWANTS, BMICALCULATORHELPER, SELECTREMOVE =


range(4)

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.']

def find_partner(user_location, user_chat_id, user_activity):


try:
partner_list = []
current_user_dictionary = database
for i in current_user_dictionary:
if i != user_chat_id:
print (i, user_chat_id)
coordinate_dictionary = {}

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)

print ("list is: ", partner_list)


except:
print ("list is empty")
return partner_list

def checkDistance(user_location, other_user_location):


user_lon = user_location["longitude"]
user_lat = user_location["latitude"]
other_lon = other_user_location["longitude"]
other_lat = other_user_location["latitude"]

lon1, lat1, lon2, lat2 = map(radians, [user_lon, user_lat, other_lon, other_lat])

km = 6371*(2*asin(sqrt(sin((lat2 - lat1)/2)**2 + cos(lat1) * cos(lat2) * sin((lon2 -


lon1)/2)**2)))
print ("The distance between the two points is: " + str(km))
return km

def start(bot, update):


print (update.message.chat.id)
print (update.message.chat.first_name)
database[update.message.chat.id] = {}

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

def location(bot, update):


user = update.message.from_user
user_location = update.message.location
logger.info("Location of %s: %f / %f", user.first_name, user_location.latitude,
user_location.longitude)
database[update.message.chat.id]['first_name'] = user.first_name
database[update.message.chat.id]['username'] = user.username
database[update.message.chat.id]['coordinates'] = (user_location.latitude,
user_location.longitude)
#find_partner(user_location, update.message.chat.id)
update.message.reply_text('Maybe I can visit you sometime! '
'At last, What sort of fitness activity
interests you?')

return WHATUSERWANTS

def skip_location(bot, update):


user = update.message.from_user
logger.info("User %s did not send a location.", user.first_name)
update.message.reply_text('You seem a bit paranoid! '
'I really need your location!')
return LOCATION

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

def cancel(bot, update):


user = update.message.from_user
logger.info("User %s canceled the conversation.", user.first_name)
update.message.reply_text('Bye! I hope we can talk again some day.',

VIGNESH BJ 33 211521205182
reply_markup=ReplyKeyboardRemove())

return ConversationHandler.END

def error(bot, update, error):


logger.warning('Update "%s" caused error "%s"', update, error)

def help(bot, update):


update.message.reply_text('''Hey! Welcome to Fitness Partner. I will help you find a
partner for your daily fitness activities to motivate you and keep you going!\n
You can control me by sending these commands:\n
1. /start - find a partner for your activity
2. /setreminder - set a reminder for a particular activity
3. /showreminders - show all existing reminders
4. /removereminders - delete reminders
5. /viewpeople - view what people are upto near you

Miscellaneous Functions:
1. /bmicalculator - to calculate your BMI''',
reply_markup=ReplyKeyboardRemove())

return ConversationHandler.END

def view_people(bot, update):


try:
user_chat_id = update.message.chat.id

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()

def bmi_calculator(bot, update):


update.message.reply_text("Enter your height (in m) and weight (in kg) [height
weight]")

VIGNESH BJ 35 211521205182
return BMICALCULATORHELPER

def bmicalculatorhelper(bot, update):

details = update.message.text

height = float(details.split(" ")[0])


weight = float(details.split(" ")[1])
update.message.reply_text("Your BMI is: " + str(round(weight/(height)**2,3)))

return ConversationHandler.END

def alarmgym(bot, job):


bot.send_message(job.context, text = "It's time for your exercise!")

def alarmmedicine(bot, job):


bot.send_message(job.context, text = "It's time to take your medicine")

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)):

VIGNESH BJ 36 211521205182
reason += args[i] + " "

if int(time.ctime()[11:13]) <= int(two) and int(time.ctime()[11:13]) <= int(two):


total += 3600 * (int(two) - int(time.ctime()[11:13]))
total += 60 * (int(three) - int(time.ctime()[14:16]))
elif int(time.ctime()[11:13]) <= int(two) and int(time.ctime()[11:13]) > int(two):
total += 3600 * (int(two) - int(time.ctime()[11:13]))
total -= 60 * (int(time.ctime()[14:16]) - int(three))
elif int(time.ctime()[11:13]) > int(two) and int(time.ctime()[11:13]) < int(two):
total += 3600 * ((24 - int(time.ctime()[11:13])) + (int(two)))
total += 60 * (int(three) - int(time.ctime()[14:16]))
else:
total += 3600 * ((24 - int(time.ctime()[11:13])) + (int(two)))
total -= 60 * (int(time.ctime()[14:16]) - int(three))
if total < 0:
update.message.reply_text('Sorry we can not go back to future!')
return
if "exercise" in reason:
job = job_queue.run_repeating(alarmgym, context = chat_id, interval =
86400, first = total)
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!')

except (IndexError, ValueError):


update.message.reply_text('Usage: /set <24 hr time><space><reason>')

VIGNESH BJ 37 211521205182
return ConversationHandler.END

def unset(bot, update, args, chat_data):


tosend = ""
if len(chat_data[update.message.chat.id]) == 0:
update.message.reply_text('You have no remainders set')
return
else:
update.message.reply_text("please enter the time of the reminder you wish to
delete from among the following")
for _ in range(len(chat_data[update.message.chat.id])):
tosend += (str(chat_data[update.message.chat.id][_]['Time']) + " : " +
str(chat_data[update.message.chat.id][_]['Reason'])) + "\n"
update.message.reply_text(tosend)
return SELECTREMOVE

def removeset(bot, update, chat_data):


for _ in range(len(chat_data[update.message.chat.id])):
if chat_data[update.message.chat.id][_]['Time'] == update.message.text:
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 error(bot, update, error):


logger.warning('Update "%s" caused error "%s"', update, error)

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.

6. Layout and Design:

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.

10 Promotion and Distribution:


 Promote your tutorial through various channels to reach your intended
audience. Share it on social media, educational forums, or mailing lists, and
encourage others to engage with and share your content.

PROGRAM :
import openai
import matplotlib.pyplot as plt

openai.api_key = 'your_openai_api_key_here'
def generate_images(text_descriptions):

# Call the DALL-E model to generate images based on text descriptions

response = openai.Image.create(
engine="davinci",
prompt=text_descriptions,
max_tokens=50,
temperature=0.7
)

# Extract image URL from the response

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()

# Example text descriptions

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 :

1. Collect property data including images, videos, and floor plans.


2. Generate a script using NLP algorithms highlighting key features and
neighborhood information.
3. Utilize TTS technology for a natural-sounding voiceover.
4. Compile visuals, voiceover, and any animations using video editing software or AI
platforms.
5. Offer customization options like branding and background music.
6. Implement a feedback loop for improvement. Distribute the video across various
platforms.
7. Track analytics for insights on engagement and effectiveness

PROGRAM:

# Import necessary libraries

import os
import random
import textwrap
from gtts import gTTS
from moviepy.editor import VideoClip, concatenate_videoclips
from moviepy.video.io.VideoFileClip import VideoFileClip

# Define functions for generating voiceover and combining videos

def generate_voiceover(script_text, output_path):


tts = gTTS(text=script_text, lang='en')

tts.save(output_path)

# Sample data (replace with actual data)

property_images = ['image1.jpg', 'image2.jpg', 'image3.jpg']


property_videos = ['video1.mp4', 'video2.mp4']
script_text = "Welcome to our property tour. This beautiful home features..."

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)

# Combine images and videos

all_media = property_images + property_videos


random.shuffle(all_media) # Shuffle to create variety in the video
video_paths = [os.path.join('media_folder', media) for media in all_media]
output_video_path = 'property_tour.mp4'
combine_videos(video_paths, output_video_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 :

from flask import Flask, request, jsonify

app = Flask(__name__)

# Dummy event planning resources

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.'
]
}

# Dummy event details

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

#-------------- GETTING USER INPUT --------------


option = 6
user_input_audio =
'D:\\GPT\\GPT\\english_tutoring_chatbot_shared_final\\i_am_good_how_are_you.wav'
# user_input_text = 'nothing much what about you'

client = OpenAI(
# api_key defaults to os.environ.get("OPENAI_API_KEY")
api_key="YOUR_OPENAI_API_KEY",
)

def get_completion_from_messages(messages, model='gpt-3.5-turbo', temperature=0):


response = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature
)
return response.choices[0].message.content

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'

#-------------- VARIABLE TO GET AND SET USERNAME --------------


global user_name

#-------------- CHATBOT CONTEXT --------------


if option == 1:
context = [
{'role': 'system', 'content': 'you are at a professional event engaging with people at a sophisticated
and professional level. keep the conversation brief'}
]
elif option == 2:
context = [
{'role': 'system', 'content': 'you are a medical MD intern at a hospital talking to a patient. continue
the conversation accordingly.'}
]
elif option == 3:
context = [
{'role': 'system', 'content': 'you are inteviewing a potential candidate for a job. keep the conversation
brief'}
]
elif option == 4:
context = [
{'role': 'system', 'content': 'you are meeting a friend at a coffee break. keep the conversation lively'}
]
elif option == 5:
context = [
{'role': 'system', 'content': 'you are an airline assistant talking to a client. keep the conversation
professional and brief'}
]
elif option == 6:
context = [
{'role': 'system', 'content': 'you are an event planner talking to a client regarding an upcomng event.
keep the conversation lively, professional and brief'}
]

#-------------- CHATBOT FUNCTION -------------


prompt = user_input_text
user_input_audio = user_input_audio
option = option

#-------------- EVALUATING USER INPUT --------------


accuracy, completeness, fluency, per_word_pronounciation_evaluation, final_words =
pronounce_assessment_file.pronunciation_assessment_continuous_from_file(user_input_audio, 'en-US',
prompt)
pitch_input_text = prompt.split(' ')

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)

#-------------- GETTING AND RETURNING USERNAME --------------


if 'what is my name' in prompt:
if user_name:
response= 'Your name is ' + user_name
else:
response = 'I don\'t know your name. You can tell me by saying: my name is [Your Name]'
elif 'my name is' in prompt:
user_name = prompt.split("my name is")[1].strip()
response = 'Nice to meet you ' + user_name + '!'

#-------------- GETTING CHATBOT RESPONSE --------------


context.append({'role': 'user', 'content': f"{prompt}"})
# print('User: ', prompt)
response = get_completion_from_messages(context)
context.append({'role': 'assistant', 'content': f"{response}"})
print('Assistant:', response)

#-------------- TEXT TO SPEECH CHATBOT RESPONSE --------------


tts.text_to_speech(voice_name, response)
tts_to_wav.text_to_speech(voice_name, response, output_filename)

#-------------- PRINTING CONTEXT --------------


print('Context: ', context)

return response, user_input_text, int(accuracy), int(completeness), int(fluency),


per_word_pronounciation_evaluation, pitch_per_word, int(overall_pitch), 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 get_completion_from_messages(messages, model='gpt-3.5-turbo', temperature=0):


response = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature
)
return response.choices[0].message.content

def chat():
#-------------- GETTING USER INPUT --------------
prompt = ''

#-------------- VARIABLE TO GET AND SET USERNAME --------------


global user_name

#-------------- CHATBOT CONTEXT --------------


if option == 1:
context = [
{'role': 'system', 'content': 'you are at a professional event engaging with people at a sophisticated
and professional level. keep the conversation brief'}
]
elif option == 2:
context = [
{'role': 'system', 'content': 'you are a medical MD intern at a hospital talking to a patient. continue
the conversation accordingly.'}
]
elif option == 3:
context = [
{'role': 'system', 'content': 'you are inteviewing a potential candidate for a job. keep the conversation
brief'}
]
elif option == 4:
context = [
{'role': 'system', 'content': 'you are meeting a friend at a coffee break. keep the conversation lively'}
]
elif option == 5:
context = [
{'role': 'system', 'content': 'you are an airline assistant talking to a client. keep the conversation
professional and brief'}
]
elif option == 6:
context = [

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'}
]

#-------------- CHATBOT FUNCTION -------------


while prompt != 'exit':
prompt = input('User: ')
prompt = prompt.lower()

#-------------- EVALUATING USER INPUT --------------


tts.text_to_speech(voice_name, prompt)
results = pronounce_assessment_mic.pronunciation_assessment_from_microphone('en-US', prompt)
for word in results.words:
acc = word.accuracy_score
while acc < 50:
print('You mispronounced ', word.word)
# wrong_pronounce.append(word.word)
tts.text_to_speech(voice_name, word.word)
re_pronounce = pronounce_assessment_mic.pronunciation_assessment_from_microphone('en-
US', word.word)
for i in re_pronounce.words:
acc = i.accuracy_score

#-------------- GETTING AND RETURNING USERNAME --------------


if 'what is my name' in prompt:
if user_name:
response= 'Your name is ' + user_name
else:
response = 'I don\'t know your name. You can tell me by saying: my name is [Your Name]'
elif 'my name is' in prompt:
user_name = prompt.split("my name is")[1].strip()
response = 'Nice to meet you ' + user_name + '!'

#-------------- GETTING CHATBOT RESPONSE --------------


context.append({'role': 'user', 'content': f"{prompt}"})
# print('User: ', prompt)
response = get_completion_from_messages(context)
context.append({'role': 'assistant', 'content': f"{response}"})
print('Assistant:', response)

#-------------- TEXT TO SPEECH CHATBOT RESPONSE --------------


tts.text_to_speech(voice_name, response)

#-------------- PRINTING CONTEXT --------------


# print('Context: ', context)

chat()

inotation.py

VIGNESH BJ 55 211521205182
import parselmouth
import numpy as np
import tts

def pitch(input_words, output):


per_word_pitch = []
sound = parselmouth.Sound(output)

# Calculate pitch
pitch = sound.to_pitch()
# print(pitch)

# Print the overall average pitch value


# print(f"Overall Pitch: {overall_average_pitch:.2f} Hz")

return per_word_pitch, overall_average_pitch

# per_word_putch, _ = pitch(input_words, output)


# print(per_word_putch)

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')

[nltk_data] Downloading package punkt to /root/nltk_data...


[nltk_data] Package punkt is already up-to-date!
[nltk_data] Downloading collection 'all'
[nltk_data] |
[nltk_data] | Downloading package abc to /root/nltk_data...
[nltk_data] | Package abc is already up-to-date!
[nltk_data] | Downloading package alpino to /root/nltk_data...
[nltk_data] | Package alpino is already up-to-date!
[nltk_data] | Downloading package biocreative_ppi to
[nltk_data] | /root/nltk_data...
[nltk_data] | Package biocreative_ppi is already up-to-date!
[nltk_data] | Downloading package brown to /root/nltk_data...
[nltk_data] | Package brown is already up-to-date!
[nltk_data] | Downloading package brown_tei to /root/nltk_data...
[nltk_data] | Package brown_tei is already up-to-date!
[nltk_data] | Downloading package cess_cat to /root/nltk_data...
[nltk_data] | Package cess_cat is already up-to-date!
[nltk_data] | Downloading package cess_esp to /root/nltk_data...
[nltk_data] | Package cess_esp is already up-to-date!
[nltk_data] | Downloading package chat80 to /root/nltk_data...
[nltk_data] | Package chat80 is already up-to-date!
[nltk_data] | Downloading package city_database to
[nltk_data] | /root/nltk_data...
[nltk_data] | Package city_database is already up-to-date!
[nltk_data] | Downloading package cmudict to /root/nltk_data...
[nltk_data] | Package cmudict is already up-to-date!
[nltk_data] | Downloading package comparative_sentences to
[nltk_data] | /root/nltk_data...
[nltk_data] | Package comparative_sentences is already up-to-
[nltk_data] | date!

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)

|████████ | 10kB 16.7MB/s eta 0:00:01


|████████████████ | 20kB 22.6MB/s eta 0:00:01
|███████████████████████▉ | 30kB 10.7MB/s eta 0:00:01
|███████████████████████████████▉| 40kB 9.6MB/s eta 0:00:01
|████████████████████████████████| 51kB 3.9MB/s
Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packag
es (from torchviz) (1.7.0+cu101)
Requirement already satisfied: graphviz in /usr/local/lib/python3.6/dist-pac
kages (from torchviz) (0.10.1)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6
/dist-packages (from torch->torchviz) (3.7.4.3)
Requirement already satisfied: dataclasses in /usr/local/lib/python3.6/dist-
packages (from torch->torchviz) (0.8)

# create training data


X_train = []
y_train = []
#using a tuple to run through the pair
for (pattern_sentence, tag) in pair:
# X-->is the bag of words for each pattern_sentence
bag = BagOfWords(pattern_sentence, all_the_words)
X_train.append(bag)
# y: PyTorch CrossEntropyLoss needs only class labels, not one-hot.so
defining label
label = tags.index(tag)
y_train.append(label)
#array
X_train = np.array(X_train)
y_train = np.array(y_train)

# 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()]

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


prob = probs[0][predicted.item()]
if prob.item() > 0.75:
for intent in intents['intents']:
if tag == intent["tag"]:
print(f"{bot_name}:
{random.choice(intent['responses'])}")
else:
print(f"{bot_name}: I do not understand...")

OUTPUT :

Enter Your Name: GopikaSR


FinBot:Hey, Let's chat! (type 'quit' to exit)Also when you start bargaining
give digits
GopikaSR:Hello
FinBot: Hello
GopikaSR:Who are you?
FinBot: It’s FinBot here, a digital+financial assistant to help you out
GopikaSR:Can I buy something?
FinBot: Ofcourse, there are new offers for you, fantastic selections, choose
what interests you!
GopikaSR:Okay, when will the shop be open?
FinBot: Our shop centre will be open from 9 am-9pm in all the days
GopikaSR:What is the price of a saree?
FinBot: We have collections of trending sarees ranging from 500Rs to 10000 R
s
GopikaSR:Where are you located?
FinBot: We are situated at the intersection of state Alley and Techno Avenu
e in Delhi, India
GopikaSR:Can I bargain today?
FinBot: yes, today you can bargaining for a ribbon. its rated price is 30 Rs

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

def initialize_pinecone_client(api_key: str) -> Pinecone:


"""Initializes and returns a Pinecone client."""
return Pinecone(api_key=api_key)

def get_response(user_query: str) -> Dict[str, Optional[str]]:


"""Generates a response for the user's query based on British building regulations.

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)

# Wait for index connection


time.sleep(1)

index.describe_index_stats()

vectorstore = LangChainPinecone(index=index, embedding=embedding_model,


text_key="context")
llm = OpenAI(temperature=TEMPERATURE, openai_api_key=st.secrets["openai_api_key"])
retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k":
NUM_RETRIEVED_DOCS})

qa_chain = RetrievalQAWithSourcesChain.from_chain_type(llm=llm, retriever=retriever)


response = qa_chain(full_query)

return response

st.title("Architect Assistant Chatbot")


st.write(
"""
This chatbot is designed to assist with queries related to British building regulations.
Simply enter your question below and receive concise, regulation-based answers.

**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?_

**Location of the answer in the document**:


Page 739 of the document
"""
)

user_query = st.text_area("Enter your question here:")


if st.button("Get Response"):
if user_query:
response = get_response(user_query)
st.write("Answer:", response.get("answer", "No answer found."))
sources = response.get("sources")
if sources:
st.write("Source:", os.path.basename(sources))
else:
st.write("No specific source cited.")
else:
st.error("Please enter a question.")

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

You might also like