File size: 2,019 Bytes
5323198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from fastai.vision.all import load_learner
import gradio as gr
import numpy as np

import pathlib
temp = pathlib.PosixPath
pathlib.PosixPath = pathlib.WindowsPath

# Function for recognizing species and behavior from an image
def recognize_image(input_image):
    # Add your model loading code here if not already loaded
    model = load_learner("final-v0.pkl")

    # Make predictions
    pred, idx, probabilities = model.predict(input_image)

    # Get all labels from the model's vocabulary
    all_labels = model.dls.vocab

    # List of behavior labels
    behavior_labels = ['F', 'H', 'M', 'M', 'P', 'R', 'T']

    # Get the top-k predicted labels
    top_k = 4
    top_indices = (-probabilities).argsort()[:top_k]
    top_labels = [all_labels[i] for i in top_indices]
    top_probabilities = [float(probabilities[i]) for i in top_indices]

    # Separate labels into behavior and species categories
    behavior_predictions = [label for label in top_labels if label in behavior_labels]
    species_predictions = [label for label in top_labels if label not in behavior_labels]

    # Create dictionaries for species and behavior predictions with their probabilities
    species_result = {
        'Species Predictions': dict(zip(species_predictions, [round(prob, 4) for prob in top_probabilities if prob not in behavior_labels])),
    }

    behavior_result = {
        'Behavior Predictions': dict(zip(behavior_predictions, [round(prob, 4) for prob in top_probabilities if prob in behavior_labels])),
    }

    return species_result, behavior_result

# Gradio interface
input_image = gr.inputs.Image(type='numpy', label='Upload Image')
output_species = gr.outputs.Label(label='Species Predictions')
output_behavior = gr.outputs.Label(label='Behavior Predictions')

gr.Interface(
    fn=recognize_image,
    inputs=input_image,
    outputs=[output_species, output_behavior],
    title='Species and Behavior Recognition',
    description='Upload an image and get predictions for species and behavior.'
).launch()