0% found this document useful (0 votes)
4 views40 pages

Full Stack AI Developer LAB MANUAL

The document outlines a lab manual for Full Stack AI Development at Vemu Institute of Technology, detailing course objectives, outcomes, and a series of experiments involving modern web technologies and AI integration. It includes guidelines for laboratory conduct, program educational objectives, and specific outcomes for students in Computer Science and Engineering. Additionally, it provides a structured syllabus with practical exercises for building web applications with Flask, Node.js, and machine learning models.

Uploaded by

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

Full Stack AI Developer LAB MANUAL

The document outlines a lab manual for Full Stack AI Development at Vemu Institute of Technology, detailing course objectives, outcomes, and a series of experiments involving modern web technologies and AI integration. It includes guidelines for laboratory conduct, program educational objectives, and specific outcomes for students in Computer Science and Engineering. Additionally, it provides a structured syllabus with practical exercises for building web applications with Flask, Node.js, and machine learning models.

Uploaded by

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

FULL STACK AI DEVELOPMENT

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING (AI)

VEMU INSTITUTE OF TECHNOLOGY::[Link]

(AUTONOMOUS)
NEAR PAKALA, CHITTOOR-517112

(Approved by AICTE, New Delhi & Affiliated to JNTUA, Anantapuramu)


FULL STACK AI DEVELOPMENT

Lab Manual

Name:________________________________________________________

[Link]:_______________________________________________________

Year/Semester:_________________________________________________

Department of Computer Science & Engineering-AI


VEMU INSTITUTE OF TECHNOLOGY::[Link]
NEAR PAKALA, CHITTOOR-517112
(Approved by AICTE, New Delhi & Affiliated to JNTUA, Anantapuramu)
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Vision

 To become a centre of excellence in the field of Computer Science and Engineering by


producing graduates with sound Technical Knowledge, Research & Consultancy skills along
with Lifelong Learning, Leadership qualities and Ethics.
Mission
 To develop learners technically sound with strong theoretical and practical knowledge in
Computer Science and Engineering discipline by state-of-the art laboratories, research
facilities and core instructions through eminent faculty.
 To enhance students in the cutting edge technologies with an emphasis on innovative ideas
and problem solving skills with strong industry-institution interaction.
 To make graduates globally competent with creative skills, leadership qualities, lifelong
learning, social and ethical values by providing value based education.

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO-1: To strengthen the learners with fundamental concepts of mathematics, applied sciences and basic
engineering subjects to analyze and solve problems in Computer Science and Engineering.
PEO-2: To produce academically strong and technically sound graduates with core instruction, innovative
design competence, development and testing skills for offering solutions to real world problems
using modern tools and techniques.
PEO-3: To make the learners competent in advanced computer programming languages to become efficient
professionals to sustain life long career.
PEO-4: To support the learners with Training, Placement, Career Guidance and Research with
multidisciplinary approach, professional ethics, leadership qualities and good communication
skills.

PROGRAM OUTCOMES (POs)

PO-1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

PO-2 Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

PO-3 Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO-4 Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.

PO-5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.

PO-6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.

PO-7 Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.

PO-8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO-9 Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.

PO- Communication: Communicate effectively on complex engineering activities with the


10 engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and
receive clear instructions.

PO- Project management and finance: Demonstrate knowledge and understanding of the
11 engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

PO- Life-long learning: Recognize the need for, and have the preparation and ability to engage in
12 independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO-1 Responsive to Ideas: Get an employment in Computer Science and Engineering field and
related software industries or become an entrepreneur in the domains such as DBMS, Java,
Networking, IOT, Mobile Computing, Artificial Intelligence and Cloud Computing.

PSO-2 Domain Knowledge: Get qualified in competitive exams to Pursue Higher Education
through the knowledge attained in advanced programming languages like Java, Machine
Learning, PHP, Python, Android Studio, Hadoop Framework, AWS, R and Weka etc.

GENERAL INSTRUCTIONS FOR LABORATORY CLASSES


DO‘S
1. Students are advised to come to the LAB at least 5 minutes before to the starting time.
2. While entering into the LAB students should wear their ID card and with proper uniform.
3. Students should sign in the LOGIN REGISTER before entering into the laboratory.
4. Students should come with observation and record note book to the laboratory.
5. Students should maintain silence inside the laboratory.
6. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept properly.
DONT‘S
1. Students bringing the bags inside the laboratory..
2. Students wearing slippers/shoes insides the laboratory.
3. Students using the computers in an improper way.
4. Students scribbling on the desk and mishandling the chairs.
5. Students using mobile phones inside the laboratory.
6. Students making noise inside the laboratory.
Course Objectives:

 Introduce students to full stack web development using modern technologies like React, [Link], and MongoDB
 Develop the ability to design, build, and deploy responsive and data-driven web applications.
 Equip students with knowledge of integrating AI and ML models into full-stack systems for intelligent automation.
 Provide hands-on experience in Python-based data analysis, visualization, and AI integration.
 Enable students to apply algorithmic thinking and AI techniques to solve real-world problems using web platforms.

Course Outcomes:
Upon completion of the course, students will be able to:

 Design and develop responsive web interfaces using HTML5, CSS3, JavaScript, and GitHub.
 Implement server-side logic and RESTful APIs using [Link], [Link], and MongoDB.
 Build and deploy full-stack applications integrating React frontend with backend services.
Apply AI and ML algorithms to automate and enhance user interactions within full-stack systems.
 Perform data analysis, visualization, and dashboard creation using Python libraries integrated with web
data. List of Experiments:

Syllabus

List of Experiments:
1. Setup Flask or [Link] server with React/HTML frontend.
2. Create login/signup system with Express/Flask and MongoDB.
3. Train and save ML model (e.g., Naive Bayes, Logistic Regression).
4. Build API to serve ML model predictions via Flask.
5. Integrate ML predictions in frontend using fetch/AJAX.
6. Create dynamic dashboard using [Link]/Plotly.
7. Implement JWT tokens or sessions for authentication.
8. Add file upload functionality (image/text for prediction).
9. Store interactions/predictions in database and visualize history.
10. Create CI/CD pipeline using GitHub Actions/Heroku.
11. Build mini-project: News Classifier / Spam Detector / Fake News Detector.
12. Final Demo & Deployment on Render/Heroku/Vercel/localhost.

Lab Software Requirements:


Lab Software Requirements:
 Languages/Tools: Python, Flask , [Link], [Link], json, HTML 5.0, CSS 3.0, JavaScript, Bootstrap,
[Link], [Link]
 Platforms: Jupyter Notebook / MongoDB/MySQL/ PyCharm / VS Code, npm(Node Package Manager),
INDEX

S. NO EXP NAME PAGE NO

1 Setup Flask or [Link] server with React/HTML frontend.

2 Create login/signup system with Express/Flask and


MongoDB.
3 Train and save ML model (e.g., Naive Bayes, Logistic
Regression).
4 Build API to serve ML model predictions via Flask.

5 Integrate ML predictions in front end using fetch/AJAX.

6 Create dynamic dashboard using [Link]/Plotly.

7 Implement JWT tokens or sessions for authentication.

8 Add file upload functionality (image/text for prediction).

9 Store interactions/predictions in database and visualize


history.
10 Create CI/CD pipeline using GitHub Actions/Heroku.

11 Build mini-project: News Classifier / Spam Detector /


Fake News Detector.
12 Final Demo & Deployment on
Render/Heroku/Vercel/localhost.
SCHEME OF EVALUATION

S. NO EXP NAME OBSERVATION EXECUTION VIVA TOTAL

1 Setup Flask or [Link]


server with React/HTML
frontend.
2 Create login/signup
system with
Express/Flask and
MongoDB.
3 Train and save ML
model (e.g., Naive
Bayes, Logistic
Regression).
4 Build API to serve ML
model predictions via
Flask.
5 Integrate ML predictions
in front end using
fetch/AJAX.
6 Create dynamic
dashboard using
[Link]/Plotly.
7 Implement JWT tokens
or sessions for
authentication.
8 Add file upload
functionality
(image/text for
prediction).
9 Store
interactions/predictions
in database and
visualize history.
10 Create CI/CD pipeline
using GitHub
Actions/Heroku.
11 Build mini-project: News
Classifier / Spam
Detector / Fake News
Detector.
12 Final Demo &
Deployment on
Render/Heroku/Vercel/l
ocalhost.
Signature Of the Lab-Incharge

1. Setup Flask or [Link] server with React/HTML frontend.

Procedure :
Setting up a full-stack application involves creating two separate, communicating
projects: a backend API (Flask or [Link]/Express) and a frontend (React or plain HTML).

Source Code :
Option 1: Flask Backend with React Frontend
This approach uses Python for the backend logic and JavaScript for the frontend UI.

Backend Setup (Flask)


[Link] project directory and virtual environment:
mkdir flask-react-app
cd flask-react-app
python3 -m venv venv
source venv/bin/activate # On Windows, use `.\\venv\\Scripts\\activate`

2. Install Flask and Flask-CORS


pip install flask flask-cors

[Link] a Flask app ([Link]):

from flask import Flask, jsonify


from flask_cors import CORS

app = Flask(__name__)
CORS(app) # Enable CORS for development

@[Link]('/api/data', methods=['GET'])
def get_data():
return jsonify({"message": "Hello from Flask!"})

if __name__ == '__main__':
[Link](debug=True, port=5000)

[Link] the Flask server:


python [Link]
The API will be running at [Link]

Frontend Setup (React)


[Link] a React app in a separate terminal window
npx create-react-app frontend
cd frontend

Alternatively, use Vite for a faster setup: npm create vite@latest frontend -- --template react.

2. Add a proxy to [Link]: This redirects API requests from the React dev server (port 3000) to the
Flask server (port 5000):

"proxy": "[Link]
[Link] src/[Link] to fetch data:
import React, { useState, useEffect } from 'react';

function App() {
const [message, setMessage] = useState('');

useEffect(() => {
fetch('/api/data')
.then(response => [Link]())
.then(data => setMessage([Link]))
.catch(error => [Link]('Error fetching data:', error));
}, []);

return (
<h1>{message}</h1>
);
}

export default App;

[Link] the React development server:


npm start

View the application at [Link] It will display "Hello from Flask!" fetched from the
backend API.

Output:
2. Create login/signup system with Express/Flask and MongoDB.

Building a secure login/signup system involves several key components, including setting up the backend
framework (Express or Flask), connecting to MongoDB, and implementing secure password hashing and
session management.

Common Steps (Express and Flask)


 Set up MongoDB: Create a database and collection for user data using a local instance or a cloud
service like MongoDB Atlas.
 Connect Application to MongoDB: Use libraries like Mongoose (Express) or PyMongo/Flask-
PyMongo (Flask) to connect your application to the database.
 Define User Schema/Model: Create a structure for user documents, typically including fields for
username/email and a hashed password.
 Implement Signup Route:
 Accept user input (e.g., username, password, email).
 Validate the input.
 Check if the user already exists.
 Hash the password using a strong algorithm like bcrypt before saving to the database.
 Save the new user document to MongoDB.
 Implement Login Route:
 Accept user credentials.
 Find the user in the database by username/email.
 Compare the provided password with the stored hashed password using the same hashing
library's comparison function.

 If valid, create a user session or JSON Web Token (JWT) to manage the user's logged-in status.
 Secure Routes: Use middleware (Express) or decorators (Flask) to protect certain routes, ensuring
only authenticated users can access them.

Source Code :
[Link] Specifics
 Key Libraries: express, mongoose, bcryptjs, jsonwebtoken (for authentication).
 Structure: Typically uses controllers and routes to manage logic and endpoints (e.g.,
[Link], [Link]).
Example Code Snippet (Signup Controller):
javascript
const bcrypt = require("bcrypt");
// ...
[Link] = async (req, res) => {
// ... (validation and user existence check)
const hashedPassword = await [Link](password, 10); // Hash password
const newUser = new User({ username, password: hashedPassword });
await [Link]();
// ...
};

More details and code examples can be found in tutorials for [Link] authentication with Express
and Mongo.

Flask Specifics
 Key Libraries: Flask, Flask-PyMongo or PyMongo, flask-bcrypt or [Link], Flask-
Login (for session management).
 Structure: Logic often resides within [Link] or [Link], utilizing decorators (@[Link]).
 Example Code Snippet (Login Route):
python
from [Link] import check_password_hash, generate_password_hash
# ...
@[Link]('/login', methods=['GET', 'POST'])
def login():
# ... (get form data)
user = [Link].find_one({"username": [Link]})
if user and check_password_hash(user['password'], [Link]):
login_user(User(username=user['username'])) # Log user in with Flask-Login
# ... (redirect)

Output :
3. Train and save ML model (e.g., Naive Bayes, Logistic Regression).

Procedure:
To train and save a machine learning model, such as Naive Bayes or Logistic
Regression, you typically use Python with libraries like scikit-learn for training and
pickle or job lib for saving the model.

Here is a general outline of the steps and a Python code example:


Prerequisites
You will need the necessary libraries installed. You can install them using pip:

pip install scikit-learn pandas joblib

Source Code :

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
import joblib
import pickle

# --- 1. Load and Prepare Data (Example using built-in Iris dataset) ---
from [Link] import load_iris
iris = load_iris()
X = [Link]
y = [Link]
feature_names = iris.feature_names
target_names = iris.target_names

# Split data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

print(f"Training samples: {len(X_train)}, Testing samples: {len(X_test)}")

# --- 2. Initialize and Train the Model ---

# Option A: Naive Bayes Model


model_nb = GaussianNB()
model_nb.fit(X_train, y_train)
print("\nNaive Bayes Model Trained.")

# Option B: Logistic Regression Model


# model_lr = LogisticRegression(solver='liblinear', multi_class='auto')
# model_lr.fit(X_train, y_train)
# print("Logistic Regression Model Trained.")

# For this example, we proceed with the Naive Bayes model


model_to_save = model_nb

# --- 3. Evaluate (Optional but Recommended) ---


predictions = model_to_save.predict(X_test)
accuracy = metrics.accuracy_score(y_test, predictions)
print(f"\nModel Accuracy on test set: {accuracy:.2f}")

# --- 4. Save the Trained Model to a file ---

# Using joblib (Recommended for scikit-learn models)


filename_joblib = 'finalized_model_nb.joblib'
[Link](model_to_save, filename_joblib)
print(f"\nModel successfully saved to '{filename_joblib}' using joblib.")

# Using pickle (General Python object serialization)


filename_pickle = 'finalized_model_nb.pkl'
with open(filename_pickle, 'wb') as file:
[Link](model_to_save, file)
print(f"Model successfully saved to '{filename_pickle}' using pickle.")

# --- 5. Load the Model Later (Example of how to use the saved file) ---

# Load from joblib file


loaded_model_joblib = [Link](filename_joblib)

# Verify the loaded model works


result_prediction = loaded_model_joblib.predict(X_test[0:1])
print(f"\nLoaded model prediction for first test sample: {target_names[result_prediction[0]]}")

Output:
4. Build API to serve ML model predictions via Flask.

Procedure:
Building an API with Flask to serve ML model predictions involves saving your trained
model, creating a Flask application that loads the model into memory, defining an API
endpoint to receive data, and returning predictions as a JSON response.

Prerequisites
Before you start, you should have a trained machine learning model saved to a file,
typically using pickle or joblib

Source Code:
# Example of saving a model (assuming 'model' is your trained model)
import pickle
with open('[Link]', 'wb') as file:
[Link](model, file)

You'll need to install Flask in your Python environment:


pip install Flask

Step-by-Step Implementation
1. Create the Flask App File ([Link])
Create a new Python file named [Link]. This file will contain the logic for your API.
2. Load the Model
In [Link], load your saved model into memory when the application starts. This
ensures the model is loaded only once, not with every request, for efficiency.

from flask import Flask, request, jsonify


import pickle
import numpy as np

app = Flask(__name__)

# Load the pre-trained model (update '[Link]' to your filename)


try:
with open('[Link]', 'rb') as file:
model = [Link](file)
except FileNotFoundError:
print("Error: [Link] not found. Please train and save your model first.")
# Exit or handle appropriately

# ... rest of your [Link] code …


3. Define the Prediction Endpoint
Create a route (URL endpoint) that accepts POST requests, processes the incoming
data, makes a prediction using the loaded model, and returns the result as JSON.

# ... (imports and model loading from above) ...

@[Link]('/predict', methods=['POST'])
def predict():
# Get data from Post Request in JSON format
data = request.get_json(force=True)

# Convert the JSON data to a format your model can understand (e.g., numpy array)
# The structure must match the format the model was trained on
try:
# Example: assuming input is a dictionary with keys matching features
features = [Link]([[data['feature1'], data['feature2'], data['feature3']]])

# Make prediction
prediction = [Link](features)

# Convert the prediction (often a numpy type) to a standard Python type


output = int(prediction[0])

# Return the result as a JSON object


return jsonify({'prediction': output})

except KeyError as e:
return jsonify({'error': f'Missing feature in request data: {e}'}), 400
except Exception as e:
return jsonify({'error': f'An error occurred during prediction: {e}'}), 500

# ... rest of your [Link] code …

4. Run the Flask App


Add the code to run the development server when the script is executed directly.
# ... (all code from above) ...

if __name__ == '__main__':
# Run the app in debug mode for development
# Use a production server like Gunicorn for deployment
[Link](debug=True)
5. Test Your API
Run your Flask application from your terminal:
python [Link]

The API will run locally at [Link]. You can test the /predict endpoint by sending a
POST request with a JSON payload using tools like Postman or curl.
Example curl command (adjust feature names/values as needed):

curl -X POST [Link] -H "Content-Type: application/json" -d


'{"feature1": 10, "feature2": 2.5, "feature3": 0.1}'

To help with model development and saving, a code example of training a simple model
with scikit-learn and saving it as a pickle file is available.

Out Put:
5. Integrate ML predictions in frontend using fetch/AJAX.

Procedure:
To integrate ML predictions in a frontend application using fetch/AJAX, the typical
approach is to have the ML model running on a backend server as a REST API. The
frontend then sends user input to this API and receives the prediction asynchronously.

Prerequisites
A trained Machine Learning model deployed as a web service (e.g., using Flask,
FastAPI, or a cloud service like AWS or Azure). This service will have a specific URL
endpoint (e.g., /predict) that accepts data and returns a prediction.
A frontend application (HTML, CSS, JavaScript).

Source Code:
Step-by-Step Integration
1. Capture User Input in the Frontend
Create an HTML form or interface to gather the necessary data from the user.
<form id="prediction-form">
<label for="input-data">Enter input for ML model:</label>
<input type="text" id="input-data" name="input_data">
<button type="submit">Get Prediction</button>
</form>
<p>Prediction Result: <strong id="result"></strong></p>

2. Send Data to the Backend using fetch()


Use the JavaScript fetch() API within an event listener to send the user's data to the
backend API endpoint asynchronously. The data is typically sent in JSON format

[Link]('prediction-form').addEventListener('submit', async
function(event) {
[Link](); // Prevent the default form submission

const inputElement = [Link]('input-data');


const inputData = { data: [Link] }; // Structure your data as expected by
the backend

try {
const response = await fetch('/predict', { // Replace '/predict' with your actual API
endpoint URL
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link](inputData)
});

if (![Link]) {
throw new Error('Network response was not ok');
}

const resultData = await [Link](); // Parse the JSON response from the
backend

// Display the result in the frontend


[Link]('result').textContent = [Link]; // Use the
key your API returns (e.g., 'prediction')

} catch (error) {
[Link]('There has been a problem with your fetch operation:', error);
[Link]('result').textContent = 'Error getting prediction.';
}
});

3. Backend Processing (Conceptual)


On the server side, the backend API receives the POST request, processes the input
data, runs the ML model to get a prediction, and returns the result as a JSON response

# Conceptual Python/Flask backend


@[Link]('/predict', methods=['POST'])
def predict():
data = request.get_json(force=True)
user_input = data['data']
# Process input and run ML model
prediction = my_model.predict(user_input)
return jsonify({'prediction': str(prediction)})

This process allows for a responsive user experience by updating only the necessary
parts of the page without a full reload.

Out Put:
6. Create dynamic dashboard using [Link]/Plotly.

Procedure:
Creating a dynamic dashboard involves using JavaScript with [Link] or [Link] for
front-end rendering and likely a back-end for data processing and interactivity (e.g.,
Python with Plotly Dash). Both libraries are powerful, open-source, and support
dynamic updates.

General Steps for a Dynamic Dashboard


 Set up your development environment: This requires standard web technologies:
HTML, CSS, and JavaScript. You'll need to include the library files in your
HTML using script tags or a package manager like npm.
 Define the layout: Create HTML <div> elements that will serve as containers for
your charts and user interface components (like dropdowns, sliders, or filters).
 Fetch data: Dynamic dashboards require data that can change. This often
involves fetching data from a database or API using JavaScript's fetch() or a
similar method, potentially in real-time using technologies like WebSockets.
 Initialize charts: Use the chosen library's functions (e.g., [Link]'s new Chart()
or [Link]'s [Link]()) to render initial charts within your HTML
containers.
 Implement interactivity: Use event listeners and callback functions to update the
chart data and visuals when a user interacts with your UI components or when
new data arrives.

Source Code:

[Link] Approach (JavaScript Only)


[Link] is a lightweight, simple-to-use library ideal for modern web projects.
Setup: Load the [Link] library: <script src="[Link]"></script>

Dynamic Updates: To update a chart dynamically, modify its data array and call
the [Link]() method.

// Example of updating data in [Link]


function updateChart(chart, newData) {
[Link][0].data = newData; // Update the data
[Link](); // Tell [Link] to re-render
}
Documentation: Refer to the [Link] documentation for comprehensive guides.
Plotly Approach (JavaScript or Python/Dash)
Plotly is great for complex, interactive, publication-quality graphs and supports
both a standalone JavaScript library ([Link]) and a powerful Python
framework called Dash.

JavaScript Setup: Load the [Link] library: <script src="[Link]"></script>

Dynamic Updates (JS): Use [Link] to update trace properties or


[Link] for layout changes.

// Example of real-time update in [Link]


[Link]('graph-div', { y: [[newValue]] }, [0]);

 Python/Dash Approach: Dash allows you to build entire web dashboards using
only Python, handling interactivity via "callbacks," which makes it excellent if
you prefer not to write JavaScript. The official Dash website offers excellent
documentation and examples.
 Documentation: Refer to the [Link] documentation or the Plotly Dash
documentation.

Out Put:
7. Implement JWT tokens or sessions for authentication.

Procedure:
Implementations for both approaches (JWT and server-side sessions), for Flask and
Node/Express backends, plus minimal React examples showing how the frontend calls
the endpoints. I’ll include security best-practices (HttpOnly cookies, refresh tokens,
password hashing, route protection). Pick the approach you want and copy the files
into your project.

Source Code:

JWT-based auth (stateless, good for APIs, mobile clients)


Flask (PyJWT) — backend/[Link]

# backend/[Link]
from flask import Flask, request, jsonify, make_response
from [Link] import generate_password_hash, check_password_hash
import jwt
import datetime
from functools import wraps
from flask_cors import CORS

SECRET_KEY = "replace_with_a_long_random_secret" # set via env in production


ACCESS_EXPIRES_MIN = 15
REFRESH_EXPIRES_DAYS = 7

app = Flask(__name__)
[Link]["SECRET_KEY"] = SECRET_KEY
CORS(app, supports_credentials=True, resources={r"/api/*": {"origins":
"[Link]

# Simple in-memory user store for demo — replace with DB


USERS = {}

def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = None
# JWT sent in Authorization header as "Bearer <token>"
auth = [Link]("Authorization", None)
if auth and [Link]("Bearer "):
token = [Link](" ", 1)[1]

if not token:
return jsonify({"message": "Token is missing"}), 401

try:
data = [Link](token, [Link]["SECRET_KEY"], algorithms=["HS256"])
current_user = [Link](data["sub"])
if not current_user:
raise Exception("User not found")
except Exception as e:
return jsonify({"message": "Token is invalid", "error": str(e)}), 401

return f(current_user, *args, **kwargs)


return decorated

@[Link]("/api/register", methods=["POST"])
def register():
data = [Link]
username = [Link]("username")
password = [Link]("password")
if not username or not password:
return jsonify({"message":"username and password required"}), 400
if username in USERS:
return jsonify({"message":"user exists"}), 400
USERS[username] = {
"username": username,
"password_hash": generate_password_hash(password)
}
return jsonify({"message":"registered"}), 201

@[Link]("/api/login", methods=["POST"])
def login():
data = [Link]
username = [Link]("username")
password = [Link]("password")
user = [Link](username)
if not user or not check_password_hash(user["password_hash"], password):
return jsonify({"message":"Invalid credentials"}), 401

now = [Link]()
access_token = [Link]({
"sub": username,
"iat": now,
"exp": now + [Link](minutes=ACCESS_EXPIRES_MIN)
}, [Link]["SECRET_KEY"], algorithm="HS256")

refresh_token = [Link]({
"sub": username,
"iat": now,
"exp": now + [Link](days=REFRESH_EXPIRES_DAYS)
}, [Link]["SECRET_KEY"], algorithm="HS256")

# For web apps prefer storing refresh token in HttpOnly cookie.


resp = jsonify({"access_token": access_token})
resp.set_cookie("refresh_token", refresh_token, httponly=True, samesite="Lax") #
secure=True in prod
return resp

@[Link]("/api/refresh", methods=["POST"])
def refresh():
# Refresh token from cookie
refresh_token = [Link]("refresh_token")
if not refresh_token:
return jsonify({"message":"refresh token missing"}), 401
try:
data = [Link](refresh_token, [Link]["SECRET_KEY"],
algorithms=["HS256"])
username = data["sub"]
if username not in USERS:
raise Exception("no user")
now = [Link]()
new_access = [Link]({
"sub": username,
"iat": now,
"exp": now + [Link](minutes=ACCESS_EXPIRES_MIN)
}, [Link]["SECRET_KEY"], algorithm="HS256")
return jsonify({"access_token": new_access})
except Exception as e:
return jsonify({"message":"refresh invalid", "error": str(e)}), 401

@[Link]("/api/protected", methods=["GET"])
@token_required
def protected(current_user):
return jsonify({"message": f"Hello {current_user['username']} — this is protected
data."})

@[Link]("/api/logout", methods=["POST"])
def logout():
resp = make_response({"message":"logged out"})
resp.delete_cookie("refresh_token")
return resp

if __name__ == "__main__":
[Link](debug=True, port=5000)

Notes (Flask JWT):

 access_token is returned in response body and should be sent in Authorization:


Bearer <token>.
 refresh_token is stored in an HttpOnly cookie (so JS can't read it). Frontend calls
/api/refresh to get a new access token.
 In production: use strong random SECRET_KEY from env, secure=True on
cookies, HTTPS, rotate/blacklist refresh tokens if logout should be immediate

React (how to call)

// call login
await fetch("[Link] {
method: "POST",
credentials: "include", // important so cookie is set
headers: { "Content-Type": "application/json" },
body: [Link]({ username, password })
})
// response contains access_token

// call protected route


await fetch("[Link] {
headers: { Authorization: "Bearer " + accessToken }
})

// refresh access token (cookie sent automatically with credentials: 'include')


await fetch("[Link] {
method: "POST",
credentials: "include"
})

[Link] / Express (JWT) — server/[Link]

// server/[Link]
const express = require("express");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");

const SECRET = [Link] || "replace_with_long_secret";


const ACCESS_MIN = 15;
const REFRESH_DAYS = 7;

const app = express();


[Link]([Link]());
[Link](cors({
origin: "[Link]
credentials: true
}));

const USERS = {}; // demo store

function generateAccess(user) {
return [Link]({ sub: [Link] }, SECRET, { expiresIn: `$
{ACCESS_MIN}m` });
}
function generateRefresh(user) {
return [Link]({ sub: [Link] }, SECRET, { expiresIn: `$
{REFRESH_DAYS}d` });
}

[Link]("/api/register", async (req, res) => {


const { username, password } = [Link];
if(!username||!password) return [Link](400).json({message:"required"});
if(USERS[username]) return [Link](400).json({message:"exists"});
const hash = await [Link](password, 10);
USERS[username] = { username, passwordHash: hash };
[Link](201).json({message:"ok"});
});

[Link]("/api/login", async (req, res) => {


const { username, password } = [Link];
const user = USERS[username];
if(!user || !(await [Link](password, [Link]))) {
return [Link](401).json({message:"invalid"});
}
const access = generateAccess(user);
const refresh = generateRefresh(user);
[Link]("refresh_token", refresh, { httpOnly: true, sameSite: "lax" }); // secure:
true in prod
[Link]({ access_token: access });
});

[Link]("/api/refresh", (req, res) => {


const token = [Link] && [Link].refresh_token;
if(!token) return [Link](401).json({message:"no token"});
try {
const payload = [Link](token, SECRET);
if(!USERS[[Link]]) throw new Error("no user");
const newAccess = [Link]({ sub: [Link] }, SECRET, { expiresIn: `$
{ACCESS_MIN}m` });
return [Link]({ access_token: newAccess });
} catch(e) {
return [Link](401).json({message:"invalid refresh", error: [Link]});
}
});

function authMiddleware(req, res, next) {


const auth = [Link];
if(!auth || ![Link]("Bearer ")) return [Link](401).json({message:"no
token"});
const token = [Link](" ",1)[1];
try {
const payload = [Link](token, SECRET);
[Link] = USERS[[Link]];
next();
} catch(e) {
[Link](401).json({message:"invalid token"});
}
}

[Link]("/api/protected", authMiddleware, (req, res) => {


[Link]({message:`hello ${[Link]}`});
});

[Link]("/api/logout", (req, res) => {


[Link]("refresh_token");
[Link]({message:"logged out"});
});

[Link](5000, () => [Link]("Listening on 5000"));

Frontend usage is identical to the Flask example above (credentials: "include" to


include cookie).

Out Put:
8. Add file upload functionality (image/text for prediction).

Procedure:
Adding file upload functionality for image/text prediction involves both client-side
implementation (HTML/JavaScript) and server-side processing with a machine
learning model.

SourceCode:
Here is a general outline of the steps required:
1. Front-End (HTML, CSS, JavaScript)
The front-end handles user interaction and file selection.
HTML Structure: Use an <input type="file"> element within a form.

<form id="uploadForm" enctype="multipart/form-data">


<input type="file" id="fileInput" name="filename" accept="image/*, .txt, .pdf"
onchange="previewFile()" />
<button type="submit">Upload and Predict</button>
</form>
<img src="" id="imagePreview" height="200" alt="Image preview area">
<div id="predictionResult"></div>

The enctype="multipart/form-data" is crucial for sending both the file and other form
data to the server. The accept attribute limits selectable files.

JavaScript (File Handling & Preview): Use the FileReader API to read the file data
locally and, if an image, display a preview.

function previewFile() {
const preview = [Link]('imagePreview');
const file = [Link]('fileInput').files[0];
const reader = new FileReader();

[Link] = () => {
[Link] = [Link];
};

if (file) {
[Link](file); // reads file as a data URL
} else {
[Link] = "";
}
}

JavaScript (Form Submission): Intercept the form submission and use the Fetch API
or XMLHttpRequest with a FormData object to send the file and any other text data to
your back-end server

2. Back-End (Server-Side Logic)


The back-end receives the file, processes it with your model, and returns the
prediction. Common back-end choices include Python with Flask/Django,
[Link], etc.
 Receive the File: Your server-side script will receive the file in the request
body (e.g., using [Link]['image'] in Django or handling the POST
request in Flask).
 Process for Prediction:
 Text: Read the text content of the file.
 Image: Process the image (e.g., resize, convert to an array/tensor) to match
your machine learning model's input requirements.
 Run Inference: Pass the pre-processed data to your loaded machine learning
model to generate a prediction.
 Return Result: Send the prediction result back to the client-side JavaScript,
which will then update the predictionResult div in your HTML.
This flow separates the user interface from the heavy lifting of machine learning
inference.

Out Put:
10. Create CI/CD pipeline using GitHub Actions/Heroku.

Procedure:
Creating a CI/CD pipeline using GitHub Actions and Heroku involves setting up a
workflow that automatically builds, tests, and deploys your application whenever you
push code to GitHub.

Source Code:
Prerequisites
A GitHub account and a repository for your application.
A Heroku account and a new application created within Heroku.
The Heroku CLI installed locally (optional, but useful).

Step 1: Configure Heroku API Key as a GitHub Secret


For security, you should use GitHub secrets to store sensitive information like your
Heroku API key.
 Log in to your Heroku Dashboard and navigate to your Account Settings.
 Scroll down to the API Key section and click Reveal to copy your key.
 In your GitHub repository, go to Settings > Secrets and variables > Actions.
 Click New repository secret.
 Set the Name to HEROKU_API_KEY and paste the copied API Key into the
Value field.

Step 2: Define the GitHub Actions Workflow


GitHub Actions workflows are defined in a YAML file within the .github/workflows
directory of your repository.
 In your GitHub repository, navigate to the Actions tab.
 Select "set up a workflow yourself" or click on New workflow.
 GitHub will create a new file named [Link] in the .github/workflows/
directory.
 Replace the default content with a workflow that includes build, test (CI), and
deploy (CD) jobs.
Example [Link] (for a [Link] app)
This example workflow runs tests and then deploys to Heroku if the tests pass:

name: CI/CD to Heroku

on:
push:
branches:
- main
# You can add other branches like 'develop' for staging environments

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v2

- name: Set up [Link]


uses: actions/setup-node@v2
with:
node-version: '18' # Use your app's required Node version

- name: Install dependencies


run: npm install

- name: Run tests


run: npm test

deploy:
runs-on: ubuntu-latest
needs: build
if: success()

steps:
- name: Checkout code
uses: actions/checkout@v2

- name: Deploy to Heroku


# This uses a pre-built action from the Marketplace for simple deployments
uses: akhileshns/heroku-deploy@v3.12.12
with:
heroku_api_key: ${{ secrets.HEROKU_API_KEY }}
heroku_app_name: "YOUR_APP_NAME" # Replace with your actual Heroku
app name
heroku_email: "your-heroku-email@[Link]" # Replace with your Heroku
account email
# Alternative deployment method using git push (as seen in search snippets):
# run: |
# git remote add heroku [Link]
# git push heroku main

Step 3: Commit and Push


Commit the new [Link] file to your repository directly in the GitHub UI or via the
command line.
Push your changes to the main branch: git push origin main.

Step 4: Monitor the Pipeline


Navigate back to the Actions tab of your GitHub repository. You will see your CI/CD
workflow running. You can click on the run to see the status of each job (build, test,
deploy) and view the build output. If all steps are successful, your application will be
deployed and available at your Heroku app's URL.

The Heroku dashboard's Activity tab will also show the progress and results of the
deployment.
You can also set up automatic deployment directly from the Heroku dashboard's
Deploy tab by connecting your GitHub repository and enabling automatic deploys for a
specific branch.

Now that you have a basic CI/CD pipeline running, we could look into adding different
deployment environments (like staging and production) or incorporating Heroku
Review Apps for pull requests.

Out Put:
11. Build mini-project: News Classifier / Spam Detector / Fake News Detector.

Procedure:
Building a reliable news classifier, spam detector, or fake news detector from scratch
involves data collection, preprocessing, feature engineering, and model training. A
typical mini-project uses supervised machine learning techniques with Python libraries
like scikit-learn and pandas [2, 3].

Source Code:
Here is a step-by-step guide and typical code snippets for a Spam Detector using a
common machine learning approach.

Mini-Project: SMS Spam Detector


This project classifies text messages as "spam" or "ham" (not spam).

Prerequisites
You will need Python and several libraries. Install them using pip:
pip install pandas scikit-learn notebook

Step 1: Get the Dataset


You need a labeled dataset. A common one is the UCI SMS Spam Collection. You can
download [Link], extract SMSSpamCollection, and place it in your
project folder.

Step 2: Load and Prepare the Data


We use pandas to read the data.
import pandas as pd
from sklearn.model_selection import train_test_split

# Load the dataset (assuming the file is in the same directory)


# The file is tab-separated and has no header row
df = pd.read_csv('SMSSpamCollection', sep='\t', names=['label', 'message'])

# Convert 'spam'/'ham' labels to 1/0 numerical values for the model


df['label'] = df['label'].map({'ham': 0, 'spam': 1})

# Split data into training and testing sets (80% train, 20% test)
X_train, X_test, y_train, y_test = train_test_split(
df['message'],
df['label'],
test_size=0.2,
random_state=42 )

Step 3: Vectorize the Text Data


Machine learning models require numerical input. We use the TF-IDF Vectorizer to
convert text messages into a matrix of token counts and frequencies [3].

from sklearn.feature_extraction.text import TfidfVectorizer

# Initialize the vectorizer


tfidf_vectorizer = TfidfVectorizer(stop_words='english', lowercase=True)

# Fit and transform the training data; transform the test data
X_train_tfidf = tfidf_vectorizer.fit_transform(X_train)
X_test_tfidf = tfidf_vectorizer.transform(X_test)

Step 4: Train the Machine Learning Model


A Multinomial Naive Bayes classifier often works well for text classification tasks [3].

from sklearn.naive_bayes import MultinomialNB


from [Link] import accuracy_score, classification_report

# Initialize and train the model


nb_classifier = MultinomialNB()
nb_classifier.fit(X_train_tfidf, y_train)

# Make predictions on the test set


y_pred = nb_classifier.predict(X_test_tfidf)

Step 5: Evaluate the Model


Check how well your model performed.

# Evaluate the accuracy


accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy*100:.2f}%")

# View detailed classification metrics


print("\nClassification Report:")
print(classification_report(y_test, y_pred))
Step 6: Test with New Data
Write a simple function to test custom messages.

def classify_message(message):
# Vectorize the input message using the *same* vectorizer
message_tfidf = tfidf_vectorizer.transform([message])
# Predict the label
prediction = nb_classifier.predict(message_tfidf)[0]

if prediction == 1:
return "SPAM"
else:
return "HAM (Not Spam)"

# Example tests
print(f"\n'Free money now!!!': {classify_message('Free money now!!!')}")
print(f"'Hey, want to grab lunch?': {classify_message('Hey, want to grab lunch?')}")

Out Put:
12. Final Demo & Deployment on Render/Heroku/Vercel/localhost.

Procedure:
Here is step-by-step guides on how to deploy an application using popular platforms
like Render, Heroku, or Vercel, or how to run a demo locally.
Please choose your preferred platform below for detailed instructions:

Deployment Guides
Platform Best For

Full-stack apps, background workers,


Render
databases; generous free tier.

Traditional web apps; simple, mature


Heroku
platform.

Front-end frameworks ([Link], React),


Vercel
serverless functions; excellent for static sites.

Local testing, development, and private


localhost
demonstrations.

Source Code:
Step-by-Step Instructions
1. Deployment to Render
 Render is a modern cloud platform that simplifies deployment for most
application types ([Link], Python, Docker, etc.).
 Prepare your code: Ensure your project is committed and pushed to a GitHub
repository.
 Sign up: Create an account on Render.
 Connect Repo: From the dashboard, click "New" and select your service type
(e.g., "Web Service"). Link your GitHub account and select your repository.
 Configure settings: Render automatically detects common languages. Confirm
the Branch, Root Directory, Runtime, Build Command, and Start Command.
 Deploy: Click "Create Web Service." Render will build and deploy your
application. The deployment log will show progress, and a URL will be provided
when it's live.

2. Deployment to Heroku
 Heroku uses "dynos" and is a widely used, robust platform.
 Prepare your code: Your project must be a Git repository.
 Install Heroku CLI: Download and install the Heroku Command Line Interface
(CLI).
 Log in: Open your terminal/command prompt and run heroku login. Follow the
prompts to log in via your browser.
 Create an app: Run heroku create <app-name> (choose a unique name) in your
project root directory. This creates a remote Heroku repository.
 Deploy: Push your code to the Heroku remote using Git: git push heroku main.
Heroku detects your language (e.g., looks for [Link] or [Link]),
builds the app, and provides a live URL.

3. Deployment to Vercel
 Vercel is optimized for frontend frameworks and fast, global deployments.
 Prepare your code: Your project needs to be on GitHub, GitLab, or Bitbucket.
 Sign up: Create an account on Vercel, signing in directly with your Git provider
is easiest.
 Import Project: From the Vercel dashboard, click "New Project" and import
your repository.
 Configure: Vercel automatically detects most frontend frameworks ([Link],
React, Vue, etc.) and pre-fills the configuration.
 Deploy: Click "Deploy." Your app will be live within seconds and automatically
assigned a *.[Link] URL.

4. Running a Demo on localhost


 Running locally is the simplest way to test and demo your application privately.
 Ensure prerequisites: Make sure you have the necessary runtime installed (e.g.,
[Link], Python, Docker).
 Navigate to project directory: Open your terminal and use cd
path/to/your/project.
 Install dependencies: Run the appropriate command (e.g., npm install, pip install
-r [Link]).
 Start the server: Run the command specified by your project (common examples:
npm start, npm run dev, python [Link], flask run).
 View: Open your web browser and navigate to the address specified in the
terminal output, usually [Link] or [Link]

Out Put:
Department of Computer Science & Engineering-
IT
VEMU INSTITUTE OF TECHNOLOGY:: [Link]
(AUTONOMOUS)
NEAR PAKALA, CHITTOOR-517112(Approved by AICTE, New Delhi & Affiliated to JNTUA,
Anantapuramu

You might also like