Ahmedhassan54 commited on
Commit
a108e44
·
verified ·
1 Parent(s): 09fcd39

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -95
app.py CHANGED
@@ -1,96 +1,96 @@
1
- import gradio as gr
2
- import tensorflow as tf
3
- import numpy as np
4
- from PIL import Image
5
- from huggingface_hub import hf_hub_download
6
- import os
7
-
8
- # Configuration
9
- MODEL_REPO = "your_hf_username/cat-dog-classifier" # Replace with your HF username and repo
10
- MODEL_FILE = "best_model.h5"
11
-
12
- # Download model from Hugging Face Hub
13
- def load_model_from_hf():
14
- try:
15
- if not os.path.exists(MODEL_FILE):
16
- print("Downloading model from Hugging Face Hub...")
17
- model_path = hf_hub_download(
18
- repo_id=MODEL_REPO,
19
- filename=MODEL_FILE,
20
- cache_dir="."
21
- )
22
- os.system(f"cp {model_path} {MODEL_FILE}")
23
-
24
- return tf.keras.models.load_model(MODEL_FILE)
25
- except Exception as e:
26
- raise gr.Error(f"Model loading failed: {str(e)}")
27
-
28
- model = load_model_from_hf()
29
-
30
- def classify_image(image):
31
- try:
32
- image = Image.fromarray(image) if isinstance(image, np.ndarray) else image
33
- image = image.resize((150, 150))
34
- image_array = np.array(image) / 255.0
35
- image_array = np.expand_dims(image_array, axis=0)
36
-
37
- prediction = model.predict(image_array)
38
- confidence = float(prediction[0][0])
39
-
40
- return {
41
- "Dog": confidence,
42
- "Cat": 1 - confidence
43
- }
44
- except Exception as e:
45
- raise gr.Error(f"Classification error: {str(e)}")
46
-
47
- # Custom CSS for better UI
48
- css = """
49
- .gradio-container {
50
- background: linear-gradient(to right, #f5f7fa, #c3cfe2);
51
- }
52
- footer {
53
- visibility: hidden
54
- }
55
- """
56
-
57
- # Build the interface
58
- with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
59
- gr.Markdown("# 🐾 Cat vs Dog Classifier 🦮")
60
- gr.Markdown("Upload an image to classify whether it's a cat or dog")
61
-
62
- with gr.Row():
63
- with gr.Column():
64
- image_input = gr.Image(label="Upload Image", type="pil")
65
- submit_btn = gr.Button("Classify", variant="primary")
66
-
67
- with gr.Column():
68
- label_output = gr.Label(label="Predictions", num_top_classes=2)
69
- confidence_bar = gr.BarPlot(
70
- x=["Cat", "Dog"],
71
- y=[0.5, 0.5],
72
- y_lim=[0,1],
73
- title="Confidence Scores",
74
- width=400,
75
- height=300
76
- )
77
-
78
- # Example images
79
- gr.Examples(
80
- examples=[
81
- ["https://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"],
82
- ["https://upload.wikimedia.org/wikipedia/commons/d/d9/Collage_of_Nine_Dogs.jpg"]
83
- ],
84
- inputs=image_input
85
- )
86
-
87
- # Button action
88
- submit_btn.click(
89
- fn=classify_image,
90
- inputs=image_input,
91
- outputs=[label_output, confidence_bar],
92
- api_name="classify"
93
- )
94
-
95
- if __name__ == "__main__":
96
  demo.launch()
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ import numpy as np
4
+ from PIL import Image
5
+ from huggingface_hub import hf_hub_download
6
+ import os
7
+
8
+ # Configuration
9
+ MODEL_REPO = "Ahmedhassan54/Image-Classification" # Replace with your HF username and repo
10
+ MODEL_FILE = "best_model.h5"
11
+
12
+ # Download model from Hugging Face Hub
13
+ def load_model_from_hf():
14
+ try:
15
+ if not os.path.exists(MODEL_FILE):
16
+ print("Downloading model from Hugging Face Hub...")
17
+ model_path = hf_hub_download(
18
+ repo_id=MODEL_REPO,
19
+ filename=MODEL_FILE,
20
+ cache_dir="."
21
+ )
22
+ os.system(f"cp {model_path} {MODEL_FILE}")
23
+
24
+ return tf.keras.models.load_model(MODEL_FILE)
25
+ except Exception as e:
26
+ raise gr.Error(f"Model loading failed: {str(e)}")
27
+
28
+ model = load_model_from_hf()
29
+
30
+ def classify_image(image):
31
+ try:
32
+ image = Image.fromarray(image) if isinstance(image, np.ndarray) else image
33
+ image = image.resize((150, 150))
34
+ image_array = np.array(image) / 255.0
35
+ image_array = np.expand_dims(image_array, axis=0)
36
+
37
+ prediction = model.predict(image_array)
38
+ confidence = float(prediction[0][0])
39
+
40
+ return {
41
+ "Dog": confidence,
42
+ "Cat": 1 - confidence
43
+ }
44
+ except Exception as e:
45
+ raise gr.Error(f"Classification error: {str(e)}")
46
+
47
+ # Custom CSS for better UI
48
+ css = """
49
+ .gradio-container {
50
+ background: linear-gradient(to right, #f5f7fa, #c3cfe2);
51
+ }
52
+ footer {
53
+ visibility: hidden
54
+ }
55
+ """
56
+
57
+ # Build the interface
58
+ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
59
+ gr.Markdown("# 🐾 Cat vs Dog Classifier 🦮")
60
+ gr.Markdown("Upload an image to classify whether it's a cat or dog")
61
+
62
+ with gr.Row():
63
+ with gr.Column():
64
+ image_input = gr.Image(label="Upload Image", type="pil")
65
+ submit_btn = gr.Button("Classify", variant="primary")
66
+
67
+ with gr.Column():
68
+ label_output = gr.Label(label="Predictions", num_top_classes=2)
69
+ confidence_bar = gr.BarPlot(
70
+ x=["Cat", "Dog"],
71
+ y=[0.5, 0.5],
72
+ y_lim=[0,1],
73
+ title="Confidence Scores",
74
+ width=400,
75
+ height=300
76
+ )
77
+
78
+ # Example images
79
+ gr.Examples(
80
+ examples=[
81
+ ["https://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"],
82
+ ["https://upload.wikimedia.org/wikipedia/commons/d/d9/Collage_of_Nine_Dogs.jpg"]
83
+ ],
84
+ inputs=image_input
85
+ )
86
+
87
+ # Button action
88
+ submit_btn.click(
89
+ fn=classify_image,
90
+ inputs=image_input,
91
+ outputs=[label_output, confidence_bar],
92
+ api_name="classify"
93
+ )
94
+
95
+ if __name__ == "__main__":
96
  demo.launch()