|
import gradio as gr
|
|
import tensorflow as tf
|
|
import numpy as np
|
|
from PIL import Image
|
|
from huggingface_hub import hf_hub_download
|
|
import os
|
|
import pandas as pd
|
|
|
|
|
|
MODEL_REPO = "Ahmedhassan54/Image-Classification"
|
|
MODEL_FILE = "best_model.h5"
|
|
|
|
|
|
def load_model_from_hf():
|
|
try:
|
|
print("Attempting to load model...")
|
|
if not os.path.exists(MODEL_FILE):
|
|
print("Model file not found locally. Downloading...")
|
|
model_path = hf_hub_download(
|
|
repo_id=MODEL_REPO,
|
|
filename=MODEL_FILE,
|
|
cache_dir="."
|
|
)
|
|
print(f"Model downloaded to: {model_path}")
|
|
os.system(f"cp {model_path} {MODEL_FILE}")
|
|
print("Model copied to working directory")
|
|
|
|
print("Loading model...")
|
|
model = tf.keras.models.load_model(MODEL_FILE)
|
|
print("Model loaded successfully!")
|
|
return model
|
|
except Exception as e:
|
|
print(f"Model loading failed: {str(e)}")
|
|
raise gr.Error(f"Model loading failed: {str(e)}")
|
|
|
|
|
|
try:
|
|
model = load_model_from_hf()
|
|
except:
|
|
model = None
|
|
print("Proceeding without model - for debugging purposes")
|
|
|
|
def classify_image(image):
|
|
try:
|
|
print("\nClassification started...")
|
|
|
|
|
|
print(f"Input type: {type(image)}")
|
|
|
|
|
|
if isinstance(image, np.ndarray):
|
|
print("Converting numpy array to PIL Image")
|
|
image = Image.fromarray(image)
|
|
|
|
|
|
print("Preprocessing image...")
|
|
image = image.resize((150, 150))
|
|
image_array = np.array(image) / 255.0
|
|
image_array = np.expand_dims(image_array, axis=0)
|
|
|
|
|
|
print("Making prediction...")
|
|
if model is None:
|
|
|
|
confidence = 0.75
|
|
print("Using mock prediction (model not loaded)")
|
|
else:
|
|
prediction = model.predict(image_array, verbose=0)
|
|
confidence = float(prediction[0][0])
|
|
|
|
print(f"Raw confidence: {confidence}")
|
|
|
|
|
|
label_output = {
|
|
"Cat": 1 - confidence,
|
|
"Dog": confidence
|
|
}
|
|
|
|
|
|
plot_data = pd.DataFrame({
|
|
'Class': ['Cat', 'Dog'],
|
|
'Confidence': [1 - confidence, confidence]
|
|
})
|
|
|
|
print("Classification successful!")
|
|
print(f"Results: {label_output}")
|
|
|
|
return label_output, plot_data
|
|
|
|
except Exception as e:
|
|
print(f"Error during classification: {str(e)}")
|
|
raise gr.Error(f"Classification error: {str(e)}")
|
|
|
|
|
|
css = """
|
|
.gradio-container {
|
|
background: linear-gradient(to right, #f5f7fa, #c3cfe2);
|
|
}
|
|
footer {
|
|
visibility: hidden
|
|
}
|
|
.animate-pulse {
|
|
animation: pulse 2s infinite;
|
|
}
|
|
@keyframes pulse {
|
|
0% { opacity: 1; }
|
|
50% { opacity: 0.5; }
|
|
100% { opacity: 1; }
|
|
}
|
|
"""
|
|
|
|
|
|
with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
gr.Markdown("""
|
|
# 🐾 Cat vs Dog Classifier 🦮
|
|
Upload an image to classify whether it's a cat or dog
|
|
""")
|
|
|
|
with gr.Row():
|
|
with gr.Column():
|
|
image_input = gr.Image(label="Upload Image", type="pil")
|
|
with gr.Row():
|
|
submit_btn = gr.Button("Classify", variant="primary")
|
|
clear_btn = gr.Button("Clear")
|
|
|
|
with gr.Column():
|
|
label_output = gr.Label(label="Predictions", num_top_classes=2)
|
|
confidence_bar = gr.BarPlot(
|
|
pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]}),
|
|
x="Class",
|
|
y="Confidence",
|
|
y_lim=[0,1],
|
|
title="Confidence Scores",
|
|
width=400,
|
|
height=300,
|
|
container=False
|
|
)
|
|
|
|
|
|
gr.Examples(
|
|
examples=[
|
|
["https://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"],
|
|
["https://upload.wikimedia.org/wikipedia/commons/d/d9/Collage_of_Nine_Dogs.jpg"]
|
|
],
|
|
inputs=image_input,
|
|
outputs=[label_output, confidence_bar],
|
|
fn=classify_image,
|
|
cache_examples=True,
|
|
label="Try these examples:"
|
|
)
|
|
|
|
|
|
submit_btn.click(
|
|
fn=classify_image,
|
|
inputs=image_input,
|
|
outputs=[label_output, confidence_bar],
|
|
api_name="classify"
|
|
)
|
|
|
|
clear_btn.click(
|
|
fn=lambda: [None, None, None],
|
|
inputs=None,
|
|
outputs=[image_input, label_output, confidence_bar],
|
|
show_progress=False
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
demo.launch(debug=True) |