hb-setosys commited on
Commit
60f2d73
·
verified ·
1 Parent(s): f9be48b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -0
app.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ from tensorflow.keras.applications import EfficientNetV2L
4
+ from tensorflow.keras.applications.efficientnet_v2 import preprocess_input, decode_predictions
5
+ import numpy as np
6
+ from PIL import Image
7
+
8
+ # Lazy loading to optimize memory usage
9
+ model = None
10
+
11
+ def load_model():
12
+ """Load the EfficientNetV2L model only when needed."""
13
+ global model
14
+ if model is None:
15
+ model = EfficientNetV2L(weights="imagenet")
16
+
17
+ def preprocess_image(image):
18
+ """Preprocess the image for EfficientNetV2L model inference."""
19
+ image = image.resize((480, 480)) # Resize for EfficientNetV2L
20
+ image_array = np.array(image) # Convert to NumPy array
21
+ image_array = preprocess_input(image_array) # Normalize input
22
+ image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
23
+ return image_array
24
+
25
+ def predict_image(image):
26
+ """
27
+ Process the uploaded image and return the top 3 predictions.
28
+ """
29
+ try:
30
+ load_model() # Ensure the model is loaded
31
+ image_array = preprocess_image(image) # Preprocess image
32
+ predictions = model.predict(image_array) # Get predictions
33
+ decoded_predictions = decode_predictions(predictions, top=3)[0]
34
+
35
+ # Format predictions as a dictionary (label -> confidence)
36
+ return {label: float(confidence) for _, label, confidence in decoded_predictions}
37
+
38
+ except Exception as e:
39
+ return {"Error": str(e)}
40
+
41
+ # Create the Gradio interface
42
+ interface = gr.Interface(
43
+ fn=predict_image,
44
+ inputs=gr.Image(type="pil"), # Accepts an image input
45
+ outputs=gr.Label(num_top_classes=3), # Shows top 3 predictions
46
+ title="EfficientNetV2L Image Classifier",
47
+ description="Upload an image, and the model will predict its content with high accuracy.",
48
+ allow_flagging="never" # Disable flagging to avoid unnecessary logs
49
+ )
50
+
51
+ # Launch the Gradio app
52
+ if __name__ == "__main__":
53
+ interface.launch()