brxerq commited on
Commit
c44903d
·
verified ·
1 Parent(s): c19be77

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -37
app.py CHANGED
@@ -1,45 +1,26 @@
1
  # app.py
2
 
3
- import gradio as gr
4
- import numpy as np
5
- import tensorflow_hub as hub
6
- from tensorflow.keras.models import load_model
7
- import cv2
8
- import os
9
-
10
- # Disable GPU (optional, for CPU-only execution)
11
- os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
12
 
13
- # Define a dictionary to map the custom layer to its implementation
14
- custom_objects = {'KerasLayer': hub.KerasLayer}
 
15
 
16
- # Load your model (ensure the path is correct)
17
- try:
18
- model = load_model('bird_model.h5', custom_objects=custom_objects)
19
- except Exception as e:
20
- print(f"Model loading failed with error: {e}")
21
- exit(1)
22
-
23
- # Define your class labels or categories for predictions
24
- train_info = [] # Replace with your actual class labels
25
 
26
- # Read image names from the text file
27
- with open('labelwithspace.txt', 'r') as file:
28
- train_info = [line.strip() for line in file.read().splitlines()]
29
 
30
- # Preprocess and predict function
31
- def predict_image(image):
32
- img = cv2.resize(image, (224, 224)) # Resize to match model input size
33
- img = img / 255.0 # Normalize pixel values
34
- img = img[np.newaxis, ...] # Add batch dimension
35
- predictions = model.predict(img)[0] # Get predictions
36
- top_class = np.argmax(predictions) # Get the index of the top prediction
37
- label = train_info[top_class] # Use the index to retrieve the label
38
- return label
39
 
40
- # Define Gradio interface
41
- input_image = gr.Image(shape=(224, 224), label="Input Image")
42
- output_label = gr.Label(label="Predicted Bird Species")
43
 
44
- # Launch Gradio
45
- gr.Interface(fn=predict_image, inputs=input_image, outputs=output_label).launch()
 
 
1
  # app.py
2
 
3
+ __all__ = ['bird', 'learn', 'classify_image', 'categories', 'image', 'label', 'examples', 'intf']
 
 
 
 
 
 
 
 
4
 
5
+ # Load categories from label.txt
6
+ with open('label.txt', 'r') as file:
7
+ categories = [line.strip() for line in file.readlines()]
8
 
9
+ # Load the model
10
+ from fastai.vision.all import *
11
+ import gradio as gr
 
 
 
 
 
 
12
 
13
+ learn = load_learner('model.pkl')
 
 
14
 
15
+ # Define the classification function
16
+ def classify_image(img):
17
+ preds, idx, probs = learn.predict(img)
18
+ return dict(zip(categories, map(float, probs)))
 
 
 
 
 
19
 
20
+ # Gradio components
21
+ image = gr.components.Image()
22
+ label = gr.components.Label(num_top_classes=3)
23
 
24
+ # Create and launch the interface
25
+ intf = gr.Interface(fn=classify_image, inputs=image, outputs=label)
26
+ intf.launch(inline=False, share=True)