Commit db222f0e authored by Maneka Wijesundara's avatar Maneka Wijesundara

python code to link front end and backend

parent d02db5fc
from flask import Flask, render_template, request
import tensorflow as tf
from tensorflow.keras.preprocessing import image
import numpy as np
from PIL import Image
import io
from tensorflow.keras.preprocessing.image import ImageDataGenerator
app = Flask(__name__)
# Define a global variable to hold the loaded model
model = None
# Define a global session to ensure it's reused
session = None
# Define data directories
data_dir = r'C:\Users\Maneka Wijesundara\Desktop\catResearch\cat_v1'
# Define image size and batch size
img_size = (150, 150)
batch_size = 32
# Define the allowed breeds
allowed_breeds = ["siamese", "bengal", "main_coon", "ragdoll", "domestic_shorthair"]
# Data augmentation and preprocessing
datagen = ImageDataGenerator(
rescale=1.0/255.0,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True,
validation_split=0.2
)
# Load and split the data
train_generator = datagen.flow_from_directory(
data_dir,
target_size=img_size,
batch_size=batch_size,
class_mode='categorical',
subset='training'
)
def load_model():
global model, session
if model is None:
model = tf.keras.models.load_model('cat_breed_classifier.h5') # Replace 'my_model.h5' with the actual model path
session = tf.keras.backend.get_session()
def preprocess_image(file):
img = Image.open(io.BytesIO(file.read()))
img = img.resize((150, 150)) # Resize to 150x150 pixels
img = np.array(img)
img = np.expand_dims(img, axis=0)
img = img / 255.0 # Normalize pixel values to [0, 1]
return img
@app.route("/", methods=["GET", "POST"])
def index():
predicted_breed = ""
cat_image = None
if request.method == "POST":
file = request.files["file"]
if file:
load_model() # Load the model
img = preprocess_image(file)
with session.as_default():
with session.graph.as_default():
predictions = model.predict(img)
class_indices = train_generator.class_indices
predicted_class = np.argmax(predictions)
for breed, idx in class_indices.items():
if idx == predicted_class:
predicted_breed = breed
break
else:
predicted_breed = "Unknown"
if predicted_breed not in allowed_breeds:
message = "Breed not recognized. The model is trained to identify Siamese, Bengal, Main Coon, Ragdoll, and Domestic Short Hair."
return render_template("index.html", predicted_breed=message, cat_image=cat_image)
# Save the image for rendering in the template
cat_image = file.read()
return render_template("index.html", predicted_breed=predicted_breed, cat_image=cat_image)
if __name__ == "__main__":
app.run(debug=True, port=8080)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment