Ahmedhassan54 commited on
Commit
4bafa27
·
verified ·
1 Parent(s): 3a1a754

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -120
app.py CHANGED
@@ -1,121 +1,121 @@
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
- import pandas as pd
8
- import logging
9
-
10
- # Disable GPU if not available (for Hugging Face Spaces)
11
- os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
12
-
13
- # Setup logging
14
- logging.basicConfig(level=logging.INFO)
15
- logger = logging.getLogger(__name__)
16
-
17
- # Configuration
18
- MODEL_REPO = "Ahmedhassan54/Image-Classification"
19
- MODEL_FILE = "best_model.h5"
20
-
21
- # Initialize model
22
- model = None
23
-
24
- def load_model():
25
- global model
26
- try:
27
- logger.info("Downloading model...")
28
- model_path = hf_hub_download(
29
- repo_id=MODEL_REPO,
30
- filename=MODEL_FILE,
31
- cache_dir=".",
32
- force_download=True
33
- )
34
- logger.info(f"Model path: {model_path}")
35
-
36
- # Explicitly disable GPU
37
- with tf.device('/CPU:0'):
38
- model = tf.keras.models.load_model(model_path)
39
- logger.info("Model loaded successfully!")
40
- except Exception as e:
41
- logger.error(f"Model loading failed: {str(e)}")
42
- model = None
43
-
44
- # Load model at startup
45
- load_model()
46
-
47
- def classify_image(image):
48
- try:
49
- if image is None:
50
- return {"Cat": 0.5, "Dog": 0.5}, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})
51
-
52
- # Convert to PIL Image if numpy array
53
- if isinstance(image, np.ndarray):
54
- image = Image.fromarray(image.astype('uint8'))
55
-
56
- # Preprocess
57
- image = image.resize((150, 150))
58
- img_array = np.array(image) / 255.0
59
- if len(img_array.shape) == 3:
60
- img_array = np.expand_dims(img_array, axis=0)
61
-
62
- # Predict
63
- if model is not None:
64
- with tf.device('/CPU:0'):
65
- pred = model.predict(img_array, verbose=0)
66
- confidence = float(pred[0][0])
67
- else:
68
- confidence = 0.75 # Demo value
69
-
70
- results = {
71
- "Cat": round(1 - confidence, 4),
72
- "Dog": round(confidence, 4)
73
- }
74
-
75
- plot_data = pd.DataFrame({
76
- 'Class': ['Cat', 'Dog'],
77
- 'Confidence': [1 - confidence, confidence]
78
- })
79
-
80
- return results, plot_data
81
-
82
- except Exception as e:
83
- logger.error(f"Error: {str(e)}")
84
- return {"Error": str(e)}, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})
85
-
86
- # Interface
87
- with gr.Blocks() as demo:
88
- gr.Markdown("# 🐾 Cat vs Dog Classifier 🦮")
89
-
90
- with gr.Row():
91
- with gr.Column():
92
- img_input = gr.Image(type="pil")
93
- classify_btn = gr.Button("Classify", variant="primary")
94
-
95
- with gr.Column():
96
- label_out = gr.Label(num_top_classes=2)
97
- plot_out = gr.BarPlot(
98
- pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]}),
99
- x="Class", y="Confidence", y_lim=[0,1]
100
- )
101
-
102
- classify_btn.click(
103
- classify_image,
104
- inputs=img_input,
105
- outputs=[label_out, plot_out]
106
- )
107
-
108
- # Examples section
109
- gr.Examples(
110
- examples=[
111
- ["https://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"],
112
- ["https://upload.wikimedia.org/wikipedia/commons/d/d9/Collage_of_Nine_Dogs.jpg"]
113
- ],
114
- inputs=img_input,
115
- outputs=[label_out, plot_out],
116
- fn=classify_image,
117
- cache_examples=True
118
- )
119
-
120
- if __name__ == "__main__":
121
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
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
+ import pandas as pd
8
+ import logging
9
+
10
+ # Disable GPU if not available (for Hugging Face Spaces)
11
+ os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
12
+
13
+ # Setup logging
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Configuration
18
+ MODEL_REPO = "Ahmedhassan54/Image-classifier"
19
+ MODEL_FILE = "final_model.h5"
20
+
21
+ # Initialize model
22
+ model = None
23
+
24
+ def load_model():
25
+ global model
26
+ try:
27
+ logger.info("Downloading model...")
28
+ model_path = hf_hub_download(
29
+ repo_id=MODEL_REPO,
30
+ filename=MODEL_FILE,
31
+ cache_dir=".",
32
+ force_download=True
33
+ )
34
+ logger.info(f"Model path: {model_path}")
35
+
36
+ # Explicitly disable GPU
37
+ with tf.device('/CPU:0'):
38
+ model = tf.keras.models.load_model(model_path)
39
+ logger.info("Model loaded successfully!")
40
+ except Exception as e:
41
+ logger.error(f"Model loading failed: {str(e)}")
42
+ model = None
43
+
44
+ # Load model at startup
45
+ load_model()
46
+
47
+ def classify_image(image):
48
+ try:
49
+ if image is None:
50
+ return {"Cat": 0.5, "Dog": 0.5}, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})
51
+
52
+ # Convert to PIL Image if numpy array
53
+ if isinstance(image, np.ndarray):
54
+ image = Image.fromarray(image.astype('uint8'))
55
+
56
+ # Preprocess
57
+ image = image.resize((150, 150))
58
+ img_array = np.array(image) / 255.0
59
+ if len(img_array.shape) == 3:
60
+ img_array = np.expand_dims(img_array, axis=0)
61
+
62
+ # Predict
63
+ if model is not None:
64
+ with tf.device('/CPU:0'):
65
+ pred = model.predict(img_array, verbose=0)
66
+ confidence = float(pred[0][0])
67
+ else:
68
+ confidence = 0.75 # Demo value
69
+
70
+ results = {
71
+ "Cat": round(1 - confidence, 4),
72
+ "Dog": round(confidence, 4)
73
+ }
74
+
75
+ plot_data = pd.DataFrame({
76
+ 'Class': ['Cat', 'Dog'],
77
+ 'Confidence': [1 - confidence, confidence]
78
+ })
79
+
80
+ return results, plot_data
81
+
82
+ except Exception as e:
83
+ logger.error(f"Error: {str(e)}")
84
+ return {"Error": str(e)}, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})
85
+
86
+ # Interface
87
+ with gr.Blocks() as demo:
88
+ gr.Markdown("# 🐾 Cat vs Dog Classifier 🦮")
89
+
90
+ with gr.Row():
91
+ with gr.Column():
92
+ img_input = gr.Image(type="pil")
93
+ classify_btn = gr.Button("Classify", variant="primary")
94
+
95
+ with gr.Column():
96
+ label_out = gr.Label(num_top_classes=2)
97
+ plot_out = gr.BarPlot(
98
+ pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]}),
99
+ x="Class", y="Confidence", y_lim=[0,1]
100
+ )
101
+
102
+ classify_btn.click(
103
+ classify_image,
104
+ inputs=img_input,
105
+ outputs=[label_out, plot_out]
106
+ )
107
+
108
+ # Examples section
109
+ gr.Examples(
110
+ examples=[
111
+ ["https://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"],
112
+ ["https://upload.wikimedia.org/wikipedia/commons/d/d9/Collage_of_Nine_Dogs.jpg"]
113
+ ],
114
+ inputs=img_input,
115
+ outputs=[label_out, plot_out],
116
+ fn=classify_image,
117
+ cache_examples=True
118
+ )
119
+
120
+ if __name__ == "__main__":
121
  demo.launch(server_name="0.0.0.0", server_port=7860)