test / app.py
diabolic6045's picture
Update app.py
63faebf verified
import os
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import Xception, xception
import gradio as gr
os.environ["KERAS_BACKEND"] = "tensorflow"
import keras
from huggingface_hub import login
login(os.getenv("HF_KEY"))
# Define the target names for classification
target_names = ['blur', 'crumbled', 'dark', 'multiple', 'proper', 'watermark']
IMG_WIDTH = 512
IMG_HEIGHT = 512
# Load the Xception model
model_path = 'Xception_final_model_512_500_6.keras'
model = keras.models.load_model(model_path)
preprocess_input = xception.preprocess_input
def predict_image(image):
# Preprocess the image
img = image.resize((IMG_WIDTH, IMG_HEIGHT))
x = keras.preprocessing.image.img_to_array(img)
x = preprocess_input(x)
x = np.expand_dims(x, axis=0)
# Make predictions
preds = model.predict(x, verbose=0)
preds = preds[0] # Extract predictions for the single image
# Map predictions to class names
class_probs = dict(zip(target_names, preds))
# Sort classes by probability in descending order
sorted_probs = {k: v for k, v in sorted(class_probs.items(), key=lambda item: item[1], reverse=True)}
return sorted_probs
# Create the Gradio app
with gr.Blocks() as demo:
gr.Markdown("# Image Classification App")
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="Upload Image", height=300)
submit_button = gr.Button("Submit")
with gr.Column():
output = gr.Label(num_top_classes=len(target_names), label="Prediction Results")
submit_button.click(fn=predict_image, inputs=[image_input], outputs=output)
# Launch the app
demo.launch(share=True)