Project 1:
Code for chatbot
https://youtu.be/YB1pkiqZKSo
<html>
<head>
<style>
body {
font: 15px arial, sans-serif;
background-color: #d9d9d9;
padding-top: 15px;
padding-bottom: 15px;
}
#bodybox {
margin: auto;
max-width: 550px;
font: 15px arial, sans-serif;
background-color: white;
border-style: solid;
border-width: 1px;
padding-top: 20px;
padding-bottom: 25px;
padding-right: 25px;
padding-left: 25px;
box-shadow: 5px 5px 5px grey;
border-radius: 15px;
}
#chatborder {
border-style: solid;
background-color: #f6f9f6;
border-width: 3px;
margin-top: 20px;
margin-bottom: 20px;
margin-left: 20px;
margin-right: 20px;
padding-top: 10px;
padding-bottom: 15px;
padding-right: 20px;
padding-left: 15px;
border-radius: 15px;
}
.chatlog {
font: 15px arial, sans-serif;
}
#chatbox {
font: 17px arial, sans-serif;
height: 22px;
width: 100%;
}
h1 {
margin: auto;
}
pre {
background-color: #f0f0f0;
margin-left: 20px;
}
</style>
</head>
<body>
<script>
//links
//http://eloquentjavascript.net/09_regexp.html
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
var messages = [], //array that hold the record of each string in chat
lastUserMessage = "", //keeps track of the most recent input string from the user
botMessage = "", //var keeps track of what the chatbot is going to say
botName = 'Chatbot', //name of the chatbot
talking = true; //when false the speach function doesn't work
//
//
//****************************************************************
//****************************************************************
//****************************************************************
//****************************************************************
//****************************************************************
//****************************************************************
//****************************************************************
//edit this function to change what the chatbot says
function chatbotResponse() {
talking = true;
botMessage = "I'm confused"; //the default message
if (lastUserMessage === 'hi' || lastUserMessage =='hello') {
const hi = ['hi','howdy','hello']
botMessage = hi[Math.floor(Math.random()*(hi.length))];;
}
if (lastUserMessage === 'what is the first humanoid robot' || lastUserMessage =='hello') {
const hi = ['sophia','sophia','sophia']
botMessage = hi[Math.floor(Math.random()*(hi.length))];;
}
if (lastUserMessage === 'what is a robot' || lastUserMessage =='hello') {
const hi = ['it is a machine']
botMessage = hi[Math.floor(Math.random()*(hi.length))];;
}
if (lastUserMessage === 'name') {
botMessage = 'My name is ' + botName;
}
}
//****************************************************************
//****************************************************************
//****************************************************************
//****************************************************************
//****************************************************************
//****************************************************************
//****************************************************************
//
//
//
//this runs each time enter is pressed.
//It controls the overall input and output
function newEntry() {
//if the message from the user isn't empty then run
if (document.getElementById("chatbox").value != "") {
//pulls the value from the chatbox ands sets it to lastUserMessage
lastUserMessage = document.getElementById("chatbox").value;
//sets the chat box to be clear
document.getElementById("chatbox").value = "";
//adds the value of the chatbox to the array messages
messages.push(lastUserMessage);
//Speech(lastUserMessage); //says what the user typed outloud
//sets the variable botMessage in response to lastUserMessage
chatbotResponse();
//add the chatbot's name and message to the array messages
messages.push("<b>" + botName + ":</b> " + botMessage);
// says the message using the text to speech function written below
Speech(botMessage);
//outputs the last few array elements of messages to html
for (var i = 1; i < 8; i++) {
if (messages[messages.length - i])
document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
}
}
}
//text to Speech
//https://developers.google.com/web/updates/2014/01/Web-apps-that-talk-Introduction-to-the-Speech-Synthesis-API
function Speech(say) {
if ('speechSynthesis' in window && talking) {
var utterance = new SpeechSynthesisUtterance(say);
//msg.voice = voices[10]; // Note: some voices don't support altering params
//msg.voiceURI = 'native';
//utterance.volume = 1; // 0 to 1
//utterance.rate = 0.1; // 0.1 to 10
//utterance.pitch = 1; //0 to 2
//utterance.text = 'Hello World';
//utterance.lang = 'en-US';
speechSynthesis.speak(utterance);
}
}
//runs the keypress() function when a key is pressed
document.onkeypress = keyPress;
//if the key pressed is 'enter' runs the function newEntry()
function keyPress(e) {
var x = e || window.event;
var key = (x.keyCode || x.which);
if (key == 13 || key == 3) {
//runs this function when enter is pressed
newEntry();
}
if (key == 38) {
console.log('hi')
//document.getElementById("chatbox").value = lastUserMessage;
}
}
//clears the placeholder text ion the chatbox
//this function is set to run when the users brings focus to the chatbox, by clicking on it
function placeHolder() {
document.getElementById("chatbox").placeholder = "";
}
</script>
<div id='bodybox'>
<div id='chatborder'>
<p id="chatlog7" class="chatlog"> </p>
<p id="chatlog6" class="chatlog"> </p>
<p id="chatlog5" class="chatlog"> </p>
<p id="chatlog4" class="chatlog"> </p>
<p id="chatlog3" class="chatlog"> </p>
<p id="chatlog2" class="chatlog"> </p>
<p id="chatlog1" class="chatlog"> </p>
<input type="text" name="chat" id="chatbox" placeholder="Hi there! Type here to talk to me." onfocus="placeHolder()">
</div>
<br>
<br>
<h2>Build a Chatbot</h2>
</div>
</body>
</html>
Project 2:
Code for Voice Chatbot
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>AI Bot</title>
<script src="https://code.responsivevoice.org/responsivevoice.js?key=OAfulrWk"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>
<script>
let aiapi = "vGbuVODEnLLz";
window.SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition;
let finalTranscript = '';
let recognition = new window.SpeechRecognition();
recognition.interimResults = true;
recognition.maxAlternatives = 10;
recognition.continuous = true;
recognition.onresult = (event) => {
let interimTranscript = '';
for (let i = event.resultIndex, len = event.results.length; i < len; i++) {
let transcript = event.results[i][0].transcript;
if (event.results[i].isFinal) {
finalTranscript += transcript;
document.getElementById("show").innerHTML = "Me :"+ transcript;
console.log(transcript);
async function fetchText() {
let response = await fetch('https://api.pgamerx.com/v4/ai?message='+transcript, {
method: "GET",
headers: {"x-api-key": aiapi}
});
let data = await response.text();
let voiceout = JSON.parse(data);
console.log(voiceout[0]);
document.getElementById("show").innerHTML = "Robot :"+ voiceout[0].message;
responsiveVoice.speak(voiceout[0].message, "UK English Female");
}
fetchText();
}
}
}
function startButton(event) {
recognition.start();
}
recognition.start();
</script>
<div id="show"></div>
<button id="start_button" onclick="startButton(event)"> Start</button>
</body>
</html>
Project 3:
Code for voice search
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Speech Recognition</title>
<script>
window.onload = () => {
const button = document.getElementById('button');
button.addEventListener('click', () => {
if (button.style['animation-name'] === 'flash') {
recognition.stop();
button.style['animation-name'] = 'none';
button.innerText = 'Press to Start';
content.innerText = '';
} else {
button.style['animation-name'] = 'flash';
button.innerText = 'Press to Stop';
recognition.start();
}
});
const content = document.getElementById('content');
const recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onresult = function (event) {
let result = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
result += event.results[i][0].transcript;
}
content.innerText = result;
};
};
</script>
<style>
button {
background: yellow;
animation-name: none;
animation-duration: 3s;
animation-iteration-count: infinite;
}
@keyframes flash {
0% {
background: red;
}
50% {
background: green;
}
}
</style>
</head>
<body>
<button id="button">Press to Start</button>
<div id="content"></div>
</body>
</html>
Project 4:
Text Spam detection using python
tensorflow
Step 1
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import pickle
import tensorflow as tf
import wordcloud
Step 2
df = pd.read_csv("spam.csv",encoding='latin-1')
df.head()
Step 3
data = df.copy() ## make a copy of the data
data.drop(columns=["Unnamed: 2", "Unnamed: 3", "Unnamed: 4"], inplace=True)
#rename the label and text columns
data = data.rename(columns={"v1":"label", "v2":"text"})
data.head()
Step 4
data.label.value_counts()
Step 5
data['label'] = data['label'].map( {'spam': 1, 'ham': 0} )
Step 6
data_ham = data[data['label'] == 0].copy()
data_spam = data[data['label'] == 1].copy()
Step 7
def show_wordcloud(df, title):
text = ' '.join(df['text'].astype(str).tolist())
stopwords = set(wordcloud.STOPWORDS)
fig_wordcloud = wordcloud.WordCloud(stopwords=stopwords,background_color='lightgrey',
colormap='viridis', width=800, height=600).generate(text)
plt.figure(figsize=(10,7), frameon=True)
plt.imshow(fig_wordcloud)
plt.axis('off')
plt.title(title, fontsize=20 )
plt.show()
Step 8
show_wordcloud(data_spam, "Spam messages")
Step 9
show_wordcloud(data_ham, "Ham messages")
Step 10
# helps in text preprocessing
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.preprocessing.text import Tokenizer
# helps in model building
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Embedding
from tensorflow.keras.callbacks import EarlyStopping
# split data into train and test set
from sklearn.model_selection import train_test_split
Step 11
X = data['text'].values
y = data['label'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)
Step 12
# prepare tokenizer
t = Tokenizer()
t.fit_on_texts(X_train)
Step 13
# integer encode the documents
encoded_train = t.texts_to_sequences(X_train)
encoded_test = t.texts_to_sequences(X_test)
print(encoded_train[0:2])
Step 14
# pad documents to a max length of 8words
max_length = 8
padded_train = pad_sequences(encoded_train, maxlen=max_length, padding='post')
padded_test = pad_sequences(encoded_test, maxlen=max_length, padding='post')
print(padded_train)
Step 15
vocab_size = len(t.word_index) + 1
# define the model
model = Sequential()
model.add(Embedding(vocab_size, 24, input_length=max_length))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dense(200, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(100, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# compile the model
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
# summarize the model
print(model.summary())
Step 16
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
def c_report(y_true, y_pred):
print("Classification Report")
print(classification_report(y_true, y_pred))
acc_sc = accuracy_score(y_true, y_pred)
print("Accuracy : "+ str(acc_sc))
return acc_sc
def plot_confusion_matrix(y_true, y_pred):
mtx = confusion_matrix(y_true, y_pred)
sns.heatmap(mtx, annot=True, fmt='d', linewidths=.5,
cmap="Blues", cbar=False)
plt.ylabel('True label')
plt.xlabel('Predicted label')
Step 17
preds = (model.predict(padded_test) > 0.5).astype("int32")
Step 18
c_report(y_test, preds)
Step 19
plot_confusion_matrix(y_test, preds)
Step 20
model.save("spam_model")
Step 21
with open('spam_model/tokenizer.pkl', 'wb') as output:
pickle.dump(t, output, pickle.HIGHEST_PROTOCOL)
Step 22
s_model = tf.keras.models.load_model("spam_model")
with open('spam_model/tokenizer.pkl', 'rb') as input:
tokenizer = pickle.load(input)
Step 23
app = Flask(__name__)
Step 24
@app.route("/")
def index():
spam_msg, not_spam_msg = get_sms_and_predict(0, 5)
template = render_template('index.html', spam_msg=spam_msg, not_spam_msg=not_spam_msg)
response = make_response(template)
return response
Step 25
if __name__ == "__main__":
app.run(host='0.0.0.0', port=4000, debug=True)
Step 26
Finally this show you the output like
when we click on spam button.
Project 5
Detecting Spam Emails Using Tensorflow in Python
Step 1
Project 6
Student result management system code link
Project 7
E-Commerce Webiste using Html and Php, CSS


I also want to be a writer like you. Your writing is my inspiration.
ReplyDeleteHire Angular Developer from Chennai