Commit 58943c87 authored by NEXUS-97's avatar NEXUS-97

backend frontend

parent a144dbcd
from flask import Flask, request, jsonify
import numpy as np
import tensorflow as tf
from PIL import Image
import torch
import torchvision
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import cv2
import base64
from io import BytesIO
app = Flask(__name__)
class GNN(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv1d(1, 10, kernel_size=2, stride=2)
self.fc1 = nn.Linear(16, 10)
def forward(self, x, adjacency):
x = F.relu(self.conv1(x))
x = x.view(-1, 16)
x = self.fc1(x)
return x
# Load the machine learning model
grown_ingrown_model = tf.keras.models.load_model('models/model_grown_status.h5.')
poision_edible_model = torch.load('models/poision_edible_model.pt')
def preprocess_image_grown_ingrown(image):
'''
s
'''
# Convert the image to an array
image_array = img_to_array(image)
# Reshape the array to have a single batch dimension
image_array = np.expand_dims(image_array, axis=0)
# Normalize the pixel values by dividing by 255
image_array = image_array / 255.0
return image_array
# Function to load and preprocess images
def preprocess_image_poision_edible(image):
# Resize the image to 64x64 pixels
image = np.array(cv2.resize(image, (64, 64)))
# Normalize pixel values to range [0, 1]
# image = image.astype(np.float32) / 255.0
return image
# Define the REST API endpoint for prediction
@app.route('/predict_poison_edible', methods=['POST', 'GET'])
def predict_poison_edible():
# Decode base64 image to bytes
image_bytes = base64.b64decode(request.json['image'])
# Create a BytesIO object to hold the image data
image_stream = BytesIO(image_bytes)
# Read the image stream as bytecode
bytecode = image_stream.read()
# Convert the image data to a NumPy array
nparr = np.frombuffer(bytecode, np.uint8)
# Decode the NumPy array into an image
image = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE)
# Preprocess the image
# Example usage
preprocessed_image = preprocess_image_poision_edible(image)
# Create a graph for each image
adjacency = torch.zeros((64, 64))
dataset_test = {}
lst_image_test = []
lst_image_test.append(preprocessed_image)
data_Test_ = {'images': np.array(lst_image_test)}
# Convert the data to tensors
Tensor_image = torch.tensor(data_Test_['images'].reshape(-1, 8 * 8), dtype=torch.float)
Tensor_image = Tensor_image.unsqueeze(1) # Add a channel dimension
# Make a prediction
output = poision_edible_model(Tensor_image[0].unsqueeze(0), adjacency)
pred = output.argmax(dim=1)
pred_value = pred.tolist()[0] # goes range from 0-20 1 and 0 is identified.. else predict not found
print("Predicted class:", pred_value)
# Extract the predicted class label should be implement
# 0 represents Poisson label
# Return the prediction result as JSON
result = "unknown"
if pred_value == 0:
result = 'poision'
elif pred_value == 1:
result = 'edible'
print('jsonify({ result})',jsonify({'result': result}))
print('result',result)
return jsonify({'result': result})
# Define the REST API endpoint for prediction
@app.route('/predict_grown_ingrown', methods=['POST', 'GET'])
def predict_grown_ingrown():
# Check if an image file was uploaded
image_bytes = base64.b64decode(request.json['image'])
# Create a BytesIO object to hold the image data
image_stream = BytesIO(image_bytes)
# Read the image stream as bytecode
bytecode = image_stream.read()
print('bytecode',bytecode)
# Load the image from the image data
image = Image.open(BytesIO(bytecode))
image = image.resize((224, 224)) # Resize if necessary
# Preprocess the image
# Example usage
preprocessed_image = preprocess_image_grown_ingrown(image)
# Make a prediction using the loaded model
prediction = grown_ingrown_model.predict(preprocessed_image)
# Extract the predicted class label
predicted_class = np.argmax(prediction[0])
print("Predicted class:", predicted_class)
# ## grown = 0
# # if predicted_class == 0:
# result = 'grown'
# elif predicted_class == 1:
# result = 'ingrown'
# Return the prediction result as JSON
return jsonify({'result': prediction})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
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