student notes / est. for the classroom

HTML, CSS, JavaScript, Python, data science, computer networks — written the way you'd explain it to a classmate, not a compiler.

Top Job & Internship Portals

Handpicked portals for fresher jobs, tech roles, and listings in Hyderabad

GFG

GeeksforGeeks

Tech & Software Roles

Visit →
INT

Internshala

Fresher Jobs & Internships

Visit →
GOOG

Google Careers

Global Google Openings

Visit →
APN

Apna Jobs

Local Jobs in Hyderabad

Visit →
INS

Instahyre

Tech Roles in Hyderabad

Visit →
NAUK

Naukri.com

Fresher Jobs in Hyderabad

Visit →
📢 Updated daily

Internship & Job Alerts

01

Latest notes

February 08, 2023

Project codes

Project 1:

Code for chatbot

Click here for video analysis

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">&nbsp;</p>

    <p id="chatlog6" class="chatlog">&nbsp;</p>

    <p id="chatlog5" class="chatlog">&nbsp;</p>

    <p id="chatlog4" class="chatlog">&nbsp;</p>

    <p id="chatlog3" class="chatlog">&nbsp;</p>

    <p id="chatlog2" class="chatlog">&nbsp;</p>

    <p id="chatlog1" class="chatlog">&nbsp;</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>



 

SCAN this QR code to connect with git hub projects

Project 2:

Code for Voice Chatbot

Click here for video analysis


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


#Importing necessary libraries for EDA
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
 
import string
import nltk
from nltk.corpus import stopwords
from wordcloud import WordCloud
nltk.download('stopwords')
 
#Importing libraries necessary for Model Building and Training
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split
 
 
import warnings
warnings.filterwarnings('ignore')




Step 2


df = pd.read_csv('emails.csv')
df.head()


Download the dataset by the following link




step 3

df.shape



step 4

sns.countplot(data['spam']) plt.show()



step 5

# Downsampling to balance the dataset ham_msg = data[data.spam == 0] spam_msg = data[data.spam == 1] ham_msg = ham_msg.sample(n = len(spam_msg), random_state=42) # Plotting the counts of down sampled dataset balanced_data = ham_msg.append(spam_msg).reset_index(drop = True) plt.figure(figsize = (8, 6)) sns.countplot(balanced_data.spam) plt.title('Distribution of Ham and Spam email messages after downsampling') plt.xlabel('Message types')



step 6

data['text'] = data['text'].str.replace('Subject', '') data.head()




step 7

punctuations_list = string.punctuation def remove_punctuations(text): temp = str.maketrans('', '', punctuations_list) return text.translate(temp) df['text']= df['text'].apply(lambda x: remove_punctuations(x)) df.head()



step 8

def remove_stopwords(text): stop_words = stopwords.words('english') imp_words = [] # Storing the important words for word in str(text).split(): word = word.lower() if word not in stop_words: imp_words.append(word) output = " ".join(imp_words) return output df['text'] = df['text'].apply(lambda text: remove_stopwords(text)) df.head()



step 9

def plot_word_cloud(data, typ): email_corpus = " ".join(data['text']) plt.figure(figsize=(10, 10)) wc = WordCloud(background_color='white', max_words=100, width=200, height=100, collocations=False).generate(email_corpus) plt.title(f'WordCloud for {typ} emails.', fontsize=15) plt.axis('off') plt.imshow(wc) plt.show() print() plot_word_cloud(df[df['spam'] == 0], typ='Non - Spam') plot_word_cloud(df[df['spam'] == 1], typ='Spam')



step 10

#train test split train_X, test_X, train_Y, test_Y = train_test_split(balanced_data['text'], balanced_data['spam'], test_size = 0.2, random_state = 42)
step 11

# training the tokenizer token=Tokenizer() token.fit_on_texts(train_X) #Generating token embeddings Training_seq = token.texts_to_sequences(train_X) Training_pad = pad_sequences(Training_seq, maxlen = 50, padding = 'post', truncating = 'post') Testing_seq = token.texts_to_sequences(test_X) Testing_pad = pad_sequences(Testing_seq, maxlen = 50, padding = 'post', truncating = 'post')





step 12


# Building the Model model = tf.keras.models.Sequential() model.add(tf.keras.layers.Embedding(max_words, 32, input_length=50)) model.add(tf.keras.layers.LSTM(4)) model.add(tf.keras.layers.Dense(32, activation='relu')) model.add(tf.keras.layers.Dense(1, activation='sigmoid'))



step 13

model.compile(loss = tf.keras.losses.BinaryCrossentropy(from_logits = True), metrics = ['accuracy'], optimizer = 'adam')




step 14


from keras.callbacks import EarlyStopping, ReduceLROnPlateau es = EarlyStopping(patience=3, monitor = 'val_accuracy', restore_best_weights = True) lr = ReduceLROnPlateau(patience = 2, monitor = 'val_loss', factor = 0.5, verbose = 0)




step 15

model.evaluate(Testing_pad, test_Y)



step 16

plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch')






 

Project 6

 Student result management system code link

click here


Project 7

E-Commerce Webiste using Html and Php, CSS


Ecommerce

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


1 comment:

02

Capstone resource hub

Codingacharya

Capstone Learning Resources, Notes & Project Hub

TCS NQT Questions
Read Notes
Machine Learning – ACE Theory
Read Notes
Machine Learning PPT
Read Notes
MachienLearning LAB
Read Notes
CSPT LAB programs
Read Notes
Time table and CSPT syllabus
Read Notes
Appreciations
Read Notes
ISTE life memberships
Read Notes
Artificial Intelligence & Analytics
Read Notes
Fullstack Web Dev
Read Notes
MERN Web Dev
Read Notes
Course Structure
Read Notes
Cloud Computing
Read Notes
90 Days ML Challenge
Read Notes
Advanced Analytics & Viz
Read Notes
Advanced Machine Learning
Read Notes
React JS
Read Notes
ML Chaitanya
Read Notes
Important Links
Read Notes
CSS Effects
Read Notes
RESUME
Read Notes
Bootstrap CSS
Read Notes
MongoDB
Read Notes
OWN Python Package
Read Notes
HTML Course
Read Notes
HTML Projects
Read Notes
GitHub Projects
Read Notes
Angular JS
Read Notes
Journals
Read Notes
NLP Notes
Read Notes
Videos
Read Notes
Data Analytics & Viz
Read Notes
Cloud Computing (Archive)
Read Notes
Open CV
Read Notes
jQuery
Read Notes
React JS (Archive)
Read Notes
Node JS
Read Notes
DAV Theory
Read Notes
DAV Lab
Read Notes
Big Data Notes
Read Notes
R-Programming
Read Notes
HADOOP Lab
Read Notes
GATE DA
Read Notes
JAVA Lab
Read Notes
Computer Networks
Read Notes
03

Live projects & profiles