Full Stack AI Developer LAB MANUAL
Full Stack AI Developer LAB MANUAL
(AUTONOMOUS)
NEAR PAKALA, CHITTOOR-517112
Lab Manual
Name:________________________________________________________
[Link]:_______________________________________________________
Year/Semester:_________________________________________________
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.
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- 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.
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.
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.
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.
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)
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>
);
}
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.
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.
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
# --- 5. Load the Model Later (Example of how to use the saved file) ---
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)
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.
app = Flask(__name__)
@[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)
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
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):
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>
[Link]('prediction-form').addEventListener('submit', async
function(event) {
[Link](); // Prevent the default form submission
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
} catch (error) {
[Link]('There has been a problem with your fetch operation:', error);
[Link]('result').textContent = 'Error getting 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.
Source Code:
Dynamic Updates: To update a chart dynamically, modify its data array and call
the [Link]() method.
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:
# 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
app = Flask(__name__)
[Link]["SECRET_KEY"] = SECRET_KEY
CORS(app, supports_credentials=True, resources={r"/api/*": {"origins":
"[Link]
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
@[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")
@[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)
// 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
// server/[Link]
const express = require("express");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
function generateAccess(user) {
return [Link]({ sub: [Link] }, SECRET, { expiresIn: `$
{ACCESS_MIN}m` });
}
function generateRefresh(user) {
return [Link]({ sub: [Link] }, SECRET, { expiresIn: `$
{REFRESH_DAYS}d` });
}
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.
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
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).
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
deploy:
runs-on: ubuntu-latest
needs: build
if: success()
steps:
- name: Checkout code
uses: actions/checkout@v2
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.
Prerequisites
You will need Python and several libraries. Install them using pip:
pip install pandas scikit-learn notebook
# 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 )
# 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)
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
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.
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