import os import cv2 import numpy as np import tensorflow as tf from django.http import HttpResponse from django.core.files.base import ContentFile from PIL import Image from django.conf import settings from django.shortcuts import render from django.urls import reverse_lazy from django.views import View from django.views.generic.edit import CreateView from tensorflow.keras.models import load_model from .models import Attendance_Label_Prediction from django.urls import reverse_lazy from django.urls import reverse_lazy class PredictView(CreateView): template_name = 'predict_form.html' model = Attendance_Label_Prediction fields = ['image'] success_url = reverse_lazy('prediction_result') def form_valid(self, form): model_file = os.path.join(settings.BASE_DIR, 'prediction', 'Attendify-v2.h5') model = load_model(model_file) # Get the uploaded image from the form image = form.instance.image custom_image = cv2.imdecode(np.fromstring(image.read(), np.uint8), cv2.IMREAD_GRAYSCALE) custom_image = cv2.resize(custom_image, (224, 224)) custom_image = np.expand_dims(custom_image, axis=-1) custom_image = custom_image / 255.0 # Convert the NumPy array to a TensorFlow tensor custom_image_tensor = tf.convert_to_tensor(custom_image, dtype=tf.float32) # Make a prediction predicted_probs = model.predict(np.expand_dims(custom_image, axis=0)) # Convert predicted probabilities to class label (if using one-hot encoding) predicted_label = np.argmax(predicted_probs) # Save the predicted label along with the record form.instance.predicted_label = predicted_label form.save() return super().form_valid(form) from django.http import HttpResponse from PIL import Image class PredictionResultView(View): template_name = 'prediction_result.html' def get(self, request): try: # Fetch the latest prediction record (you might want to adjust this logic based on your needs) prediction_record = Attendance_Label_Prediction.objects.latest('id') except Attendance_Label_Prediction.DoesNotExist: prediction_record = None if prediction_record: # Get the uploaded image from the record image_content = prediction_record.image.read() # Get the file extension from the upload_to attribute of the ImageField file_extension = prediction_record.image.name.split('.')[-1] # Save the image locally temp_image_path = os.path.join(settings.MEDIA_ROOT, f'temp_image.{file_extension}') with open(temp_image_path, 'wb') as temp_image_file: temp_image_file.write(image_content) # Pass the image URL, image name, and predicted label to the template image_url = settings.MEDIA_URL + f'temp_image.{file_extension}' image_name = prediction_record.image.name predicted_label = prediction_record.predicted_label else: image_url = None image_name = None predicted_label = None return render(request, self.template_name, {'image_url': image_url, 'image_name': image_name, 'predicted_label': predicted_label})