Spaces:
Sleeping
Sleeping
Krishs21 commited on
Commit ·
ff17737
1
Parent(s): b3112f5
Add application file
Browse files- app.py +52 -0
- requirements.txt +0 -0
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from tensorflow.keras.models import load_model
|
| 3 |
+
from keras.preprocessing.image import img_to_array, load_img
|
| 4 |
+
import numpy as np
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Load the pre-trained model at the start
|
| 8 |
+
model = load_model('best_cat_dog_classifier.keras')
|
| 9 |
+
|
| 10 |
+
# Image preprocessing function
|
| 11 |
+
def preprocess_image(image_path):
|
| 12 |
+
img = load_img(image_path, target_size=(128, 128))
|
| 13 |
+
img = img_to_array(img)
|
| 14 |
+
img = np.expand_dims(img, axis=0)
|
| 15 |
+
img /= 255.0
|
| 16 |
+
return img
|
| 17 |
+
|
| 18 |
+
# Prediction function
|
| 19 |
+
def predict_image(img):
|
| 20 |
+
# Save the image temporarily
|
| 21 |
+
img.save("temp_image.png")
|
| 22 |
+
img_path = "temp_image.png"
|
| 23 |
+
|
| 24 |
+
# Preprocess and predict
|
| 25 |
+
processed_img = preprocess_image(img_path)
|
| 26 |
+
prediction = model.predict(processed_img)
|
| 27 |
+
confidence_threshold = 0.5
|
| 28 |
+
|
| 29 |
+
if prediction >= confidence_threshold:
|
| 30 |
+
result = "dog"
|
| 31 |
+
confidence = float(prediction) * 100
|
| 32 |
+
else:
|
| 33 |
+
result = "cat"
|
| 34 |
+
confidence = float(1 - prediction) * 100
|
| 35 |
+
|
| 36 |
+
# Clean up
|
| 37 |
+
os.remove(img_path)
|
| 38 |
+
return {"result": result, "confidence": round(confidence, 2)}
|
| 39 |
+
|
| 40 |
+
# Define Gradio Interface
|
| 41 |
+
interface = gr.Interface(
|
| 42 |
+
fn=predict_image,
|
| 43 |
+
inputs=gr.inputs.Image(type="pil"),
|
| 44 |
+
outputs="json",
|
| 45 |
+
title="Cat vs Dog Classifier",
|
| 46 |
+
description="Upload an image to classify it as a cat or dog."
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# Launch the interface
|
| 50 |
+
interface.launch()
|
| 51 |
+
|
| 52 |
+
|
requirements.txt
ADDED
|
Binary file (66 Bytes). View file
|
|
|