| import gradio as gr |
| import tensorflow as tf |
| import numpy as np |
| from PIL import Image |
| import os |
| import io |
|
|
| |
| PHOTO_SIZE = 224 |
| MODEL_FILE_NAME = 'vgg_model50.h5' |
| CLASS_NAMES = ["Non-Autstic", "Autstic"] |
|
|
| |
| |
| model_path = os.path.join(os.path.dirname(__file__), MODEL_FILE_NAME) |
| if not os.path.exists(model_path): |
| |
| raise FileNotFoundError(f"Model file '{MODEL_FILE_NAME}' not found. Please upload it to the Space.") |
|
|
| try: |
| model = tf.keras.models.load_model(model_path) |
| print("Model loaded successfully.") |
| except Exception as e: |
| print(f"Error loading model: {e}") |
| |
| model = None |
|
|
| def preprocess_image(pil_image): |
| """ |
| Preprocesses the PIL image object for the VGG16 model. |
| Resizes to (PHOTO_SIZE, PHOTO_SIZE), normalizes to [0, 1]. |
| """ |
| try: |
| |
| img = pil_image.convert('RGB') |
| img = img.resize((PHOTO_SIZE, PHOTO_SIZE)) |
| np_image = np.array(img).astype('float32') / 255.0 |
| |
| np_image = np.expand_dims(np_image, axis=0) |
| print(f"Image preprocessed successfully. Shape: {np_image.shape}") |
| return np_image |
| except Exception as e: |
| print(f"Error preprocessing image: {e}") |
| return None |
|
|
| def predict_autism(image_input): |
| """ |
| Takes a PIL Image input from Gradio, preprocesses, predicts, and returns the class name. |
| """ |
| if model is None: |
| return "Error: Model not loaded." |
|
|
| print(f"Received image of type: {type(image_input)}") |
|
|
| |
| processed_image = preprocess_image(image_input) |
| if processed_image is None: |
| return "Error: Image preprocessing failed." |
|
|
| |
| print("Making prediction...") |
| prediction = model.predict(processed_image) |
| predicted_class_index = np.argmax(prediction, axis=1)[0] |
| predicted_class_name = CLASS_NAMES[predicted_class_index] |
| confidence = float(np.max(prediction)) |
|
|
| print(f"Prediction result index: {predicted_class_index}, Class: {predicted_class_name}, Confidence: {confidence:.4f}") |
|
|
| |
| |
| |
| |
| return predicted_class_name |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| iface = gr.Interface( |
| fn=predict_autism, |
| inputs=gr.Image(type="pil", label="Upload Image"), |
| outputs=gr.Textbox(label="Prediction Result"), |
| |
| title="Autism Classification from Facial Images (VGG16)", |
| description="Upload a facial image to classify as Autistic or Non-Autistic using a VGG16 model.", |
| allow_flagging="never", |
| |
| ) |
|
|
| |
| |
| if __name__ == "__main__": |
| iface.launch() |