Suhani-2407 commited on
Commit
23466eb
·
verified ·
1 Parent(s): d16e9f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -49
app.py CHANGED
@@ -1,56 +1,42 @@
1
- import os
2
- os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # Disable GPU warnings
3
  import gradio as gr
4
  import tensorflow as tf
5
  import numpy as np
6
  from PIL import Image
7
- import traceback
8
-
9
- # Load model
10
- model = tf.keras.models.load_model("MobileNet_model.h5")
11
- class_names = ["Fake", "Low", "Medium", "High"]
12
-
13
- def predict_image(img):
14
- try:
15
- if img is None:
16
- return {"error": "No image provided"}
17
-
18
- # If img is a file path, open it
19
- if isinstance(img, str):
20
- img = Image.open(img)
21
-
22
- # Ensure it's a PIL Image
23
- if not isinstance(img, Image.Image):
24
- return {"error": f"Expected PIL Image, got {type(img)}"}
25
-
26
- img = img.resize((128, 128))
27
- img_array = np.array(img) / 255.0
28
-
29
- # Handle grayscale images
30
- if len(img_array.shape) == 2:
31
- img_array = np.stack((img_array,) * 3, axis=-1)
32
- # Handle RGBA images
33
- elif img_array.shape[2] == 4:
34
- img_array = img_array[:, :, :3]
35
-
36
- img_array = np.expand_dims(img_array, axis=0)
37
- predictions = model.predict(img_array)
38
- class_index = np.argmax(predictions, axis=1)[0]
39
- confidence_scores = {class_names[i]: float(predictions[0][i]) for i in range(len(class_names))}
40
- return {"Predicted Class": class_names[class_index], "Confidence Scores": confidence_scores}
41
- except Exception as e:
42
- return {"error": str(e), "traceback": traceback.format_exc()}
43
-
44
- # Create interface with explicit input type
45
- iface = gr.Interface(
46
- fn=predict_image,
47
- inputs=gr.Image(type="pil", label="Upload Image"),
48
- outputs=gr.JSON(),
49
- examples=[["example1.jpg"], ["example2.jpg"]],
50
- title="Fire Detection API",
51
- description="Upload an image to detect fire presence and intensity"
52
  )
53
 
54
- # Launch with debugging enabled
55
- iface.launch(server_name="0.0.0.0", server_port=7860, share=True, debug=True, show_error=True)
 
56
 
 
 
 
1
  import gradio as gr
2
  import tensorflow as tf
3
  import numpy as np
4
  from PIL import Image
5
+
6
+ # Load the trained model
7
+ model = tf.keras.models.load_model("MobileNet_model.h5") # Ensure the model file is uploaded in the same directory
8
+
9
+ # Define class names
10
+ class_names = ["Fake", "Low", "Medium", "High"] # Modify if needed
11
+
12
+ # Image Preprocessing Function
13
+ img_size = (128, 128) # Ensure it matches the input size used during training
14
+
15
+ def preprocess_image(image):
16
+ image = image.resize(img_size) # Resize image
17
+ image = np.array(image) / 255.0 # Normalize as done in ImageDataGenerator (rescale=1./255)
18
+ image = np.expand_dims(image, axis=0) # Add batch dimension
19
+ return image
20
+
21
+ # API Endpoint for Prediction
22
+ def predict(image):
23
+ image = preprocess_image(image)
24
+ predictions = model.predict(image)
25
+ predicted_class = np.argmax(predictions, axis=1)[0] # Get predicted class index
26
+ confidence_scores = {class_names[i]: float(predictions[0][i]) for i in range(len(class_names))} # Get probability scores
27
+
28
+ return {"Predicted Class": class_names[predicted_class], "Confidence Scores": confidence_scores}
29
+
30
+ # Gradio API Interface
31
+ interface = gr.Interface(
32
+ fn=predict,
33
+ inputs=gr.Image(type="pil"), # Accept image as input
34
+ outputs=gr.JSON(), # Return JSON response
35
+ title="Waste Classification API",
36
+ description="Send an image to classify it into one of four categories: Fake, Low, Medium, or High."
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  )
38
 
39
+ # Launch API
40
+ if __name__ == "__main__":
41
+ interface.launch(share=True)
42