Perquisites
- Need machine finding out model(with .h5 extension).By the use of this rationalization I used sing language detection model.
- Set up the labels which are used for teaching the model. For an occasion must you follow model for decide canines and cats then classification labels must be “canine and cat”.
- Arrange python mannequin 3.8.0 must you’re not arrange already and set path precisely.
- Arrange vs code must you’re not arrange already.
- Make itemizing any location irrespective of you want and open it using vs code.
- Open terminal and run beneath directions.
python -m pip arrange --upgrade pip --user
pip arrange flask --user
pip arrange pillow --user
pip arrange tensorflow --user
pip arrange numpy --user
pip arrange keras --user
Step 1: Make folder development
Inside root itemizing make a list known as templates and inside it creates two html data akin to index.html and finish outcome.html
Then navigate as soon as extra into root director and create the rest of the knowledge app.py ,model_name.h5 ,labels.txt and requirments.txt data.
index.html file makes use of for current the home net web page and via net web page shopper able to add images.
finish outcome.html file makes use of for exhibiting finish outcome which is returning by model.
app.py is the middle of the code. all the implementation components are included proper right here.
labele.txt file embrace all the labels which indicate the way in which by which that we categorised the model
requirments.txt makes use of for along with all of the requirements libraries .This file import as quickly as if we arrange this methodology in a single different pc.
Step 2 : Import associated libraries.
Underneath data probably vary and some fashions need further libraries. Usually beneath data are used.
from flask import Flask, render_template, request, jsonify
from keras.fashions import load_model
from PIL import Image, ImageOps
import numpy as np
import os
Step 3 : Initialize loading model.
app = Flask(__name__)model = load_model("keras_model.h5", compile=False)
class_names = open("labels.txt", "r").readlines()
Step 4 : Initialize variable for storing uploaded data.
uploaded_files = []
Step 5 : Initialize preprocessing half.
def preprocess_image(image_path):
image = Image.open(image_path).convert("RGB")
measurement = (224, 224)
image = ImageOps.match(image, measurement, Image.Resampling.LANCZOS)
image_array = np.asarray(image)
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
data = np.ndarray(kind=(1, 224, 224, 3), dtype=np.float32)
data[0] = normalized_image_array
return data
Step 6 : Define path to render the index.html template.
@app.route('/')
def home():
return render_template('index.html')
Step 7 : Define route and relent code for the coping with the prediction course of
@app.route('/predict', methods=['POST'])
def predict():
world uploaded_files
if request.approach == 'POST':
data = request.data.getlist('data[]')
predictions = []
for file in data:
file_path = os.path.be part of("uploads", file.filename)
file.save(file_path)
uploaded_files.append(file_path)
data = preprocess_image(file_path)
prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index][2:].strip()
predictions.append(class_name)
return jsonify({
"standing": "uploaded",
"message": "Photographs uploaded effectively."
})
Step 8 : Define route and relent code for the airing finish outcome.
@app.route('/final_result')
def final_result():
world uploaded_files
predictions = []
for file_path in uploaded_files:
data = preprocess_image(file_path)
prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index][2:].strip()
predictions.append(class_name)
uploaded_files = [] # Clear uploaded data for subsequent submission
return render_template('finish outcome.html', predictions=predictions)
Step 9 : Completed app.py code
from flask import Flask, render_template, request, jsonify
from keras.fashions import load_model
from PIL import Image, ImageOps
import numpy as np
import osapp = Flask(__name__)
model = load_model("keras_model.h5", compile=False)
class_names = open("labels.txt", "r").readlines()
def preprocess_image(image_path):
image = Image.open(image_path).convert("RGB")
measurement = (224, 224)
image = ImageOps.match(image, measurement, Image.Resampling.LANCZOS)
image_array = np.asarray(image)
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
data = np.ndarray(kind=(1, 224, 224, 3), dtype=np.float32)
data[0] = normalized_image_array
return data
uploaded_files = []
@app.route('/predict', methods=['POST'])
def predict():
world uploaded_files
if request.approach == 'POST':
data = request.data.getlist('data[]')
predictions = []
for file in data:
file_path = os.path.be part of("uploads", file.filename)
file.save(file_path)
uploaded_files.append(file_path)
data = preprocess_image(file_path)
prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index][2:].strip()
predictions.append(class_name)
return jsonify({
"standing": "uploaded",
"message": "Photographs uploaded effectively."
})
@app.route('/final_result')
def final_result():
world uploaded_files
predictions = []
for file_path in uploaded_files:
data = preprocess_image(file_path)
prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index][2:].strip()
predictions.append(class_name)
uploaded_files = [] # Clear uploaded data for subsequent submission
return render_template('finish outcome.html', predictions=predictions)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Step 10 : Develop index.html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta establish="viewport" content material materials="width=device-width, initial-scale=1.0" />
<title>Add Photographs</title>
<mannequin>
#imagePreview {
present: flex;
flex-wrap: wrap;
gap: 10px;
}.preview-image {
width: 100px;
peak: 100px;
object-fit: cowl;
}
</mannequin>
<script>
let selectedFiles = [];
carry out handleFileSelect(event) {
const data = Array.from(event.purpose.data);
if (selectedFiles.measurement + data.measurement > 5) {
alert("You can add a most of 5 images");
return;
}
data.forEach((file) => {
selectedFiles.push(file);
});
updateImagePreview();
uploadFiles(data);
}
carry out updateImagePreview() {
const imagePreview = doc.getElementById("imagePreview");
imagePreview.innerHTML = "";
selectedFiles.forEach((file) => {
const reader = new FileReader();
reader.onload = carry out (e) {
const img = doc.createElement("img");
img.src = e.purpose.finish outcome;
img.classList.add("preview-image");
imagePreview.appendChild(img);
};
reader.readAsDataURL(file);
});
}
carry out uploadFiles(data) {
const formData = new FormData();
data.forEach((file) => {
formData.append("data[]", file);
});
fetch("/predict", {
approach: "POST",
physique: formData,
})
.then((response) => response.json())
.then((data) => {
console.log(data);
if (data.standing === "uploaded") {
alert("Photographs uploaded effectively");
}
})
.catch((error) => console.error("Error importing data:", error));
}
</script>
<hyperlink
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="anonymous"
/>
</head>
<physique>
<div class="container-fluid" mannequin="margin-left: 170px">
<br />
<h3>Add Photographs</h3>
<br />
<sort id="uploadForm" enctype="multipart/form-data">
<enter
kind="file"
establish="data[]"
numerous
accept="image/*"
onchange="handleFileSelect(event)"
/>
<div id="imagePreview"></div>
</sort>
<br />
<sort movement="/final_result" approach="get">
<button
kind="submit"
class="btn btn-info"
mannequin="border-radius: 0; width: 300px"
>
Get Consequence
</button>
</sort>
</div>
</physique>
</html>
Step 11 : Develop finish outcome.html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta establish="viewport" content material materials="width=device-width, initial-scale=1.0">
<title>Prediction Outcomes</title>
</script>
<hyperlink href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"></head>
<physique>
<div class="container">
<h3 class="mt-4">Prediction Outcomes</h3><br/>
<div class="form-group">
<textarea id="predictions" class="form-control" readonly mannequin="width: 500px;">{% for prediction in predictions %}{{ prediction }} {% endfor %}</textarea><br/>
</div>
<a href="/" > <button kind="submit" class="btn btn-info" mannequin="border-radius: 0; width: 200px;">Once more</button> </a>
</div>
</physique>
</html>
Step 12 : Create labels.txt file
0 A
1 B
2 C
3 D
4 E
5 F
6 G
7 H
8 I
9 J
10 Okay
11 L
12 M
13 N
14 O
15 P
16 Q
17 R
18 S
19 T
20 U
21 V
22 W
23 X
24 Y
25 Z
26 space
27 nothing
28 del
Step 13 : Create requirment.txt file
flask
tensorflow
keras
pillow
numpy
Step 14 : Run most essential.py
python most essential.py