Sun Jiao
commited on
Commit
·
79b13b9
1
Parent(s):
14c8ef9
add app
Browse files
app.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import math
|
3 |
+
import sqlite3
|
4 |
+
|
5 |
+
import streamlit as st
|
6 |
+
import torch
|
7 |
+
from PIL import Image
|
8 |
+
from huggingface_hub import hf_hub_download
|
9 |
+
from torchvision import transforms
|
10 |
+
from transformers import AutoModelForImageClassification
|
11 |
+
|
12 |
+
# Set the page title
|
13 |
+
st.title("Global Bird Classification App")
|
14 |
+
|
15 |
+
# Upload an image
|
16 |
+
uploaded_file = st.file_uploader("Please select an image", type=["jpg", "jpeg", "png"])
|
17 |
+
|
18 |
+
# Input latitude and longitude (optional)
|
19 |
+
latitude = st.number_input("Enter latitude (optional)", value=None, format="%f")
|
20 |
+
longitude = st.number_input("Enter longitude (optional)", value=None, format="%f")
|
21 |
+
|
22 |
+
lang = st.selectbox(
|
23 |
+
"Result Language",
|
24 |
+
options=[2, 1, 0],
|
25 |
+
format_func=lambda x: {
|
26 |
+
2: "Latina (Nomen Scientificum)",
|
27 |
+
1: "English (IOC 10.1)",
|
28 |
+
0: "中文 (中国大陆)",
|
29 |
+
}[x]
|
30 |
+
)
|
31 |
+
|
32 |
+
|
33 |
+
classify_transforms = transforms.Compose([
|
34 |
+
transforms.Resize((224, 224)),
|
35 |
+
transforms.ToTensor(),
|
36 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
37 |
+
])
|
38 |
+
|
39 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
40 |
+
|
41 |
+
|
42 |
+
# crop and classification
|
43 |
+
def classify_objects(classification_model, image, species_list):
|
44 |
+
input_tensor = classify_transforms(image).unsqueeze(0).to(device)
|
45 |
+
with torch.no_grad():
|
46 |
+
logits = classification_model(input_tensor)[0]
|
47 |
+
filtered = get_filtered_predictions(logits, species_list)
|
48 |
+
return softmax(filtered)
|
49 |
+
|
50 |
+
|
51 |
+
def softmax(tuples):
|
52 |
+
# `torch.nn.functional.softmax` requires the input to be `Tensor`, so I implemented it myself
|
53 |
+
values = [t[1] for t in tuples]
|
54 |
+
exp_values = [math.exp(v) for v in values]
|
55 |
+
sum_exp_values = sum(exp_values)
|
56 |
+
softmax_values = [ev / sum_exp_values for ev in exp_values]
|
57 |
+
updated_tuples = [(t[0], softmax_values[i]) for i, t in enumerate(tuples)]
|
58 |
+
updated_tuples.sort(key=lambda t: t[1], reverse=True)
|
59 |
+
|
60 |
+
return updated_tuples
|
61 |
+
|
62 |
+
|
63 |
+
def get_filtered_predictions(predictions: list[float], species_list: list[int]) -> list[tuple[int, float]]:
|
64 |
+
original = {index: value for index, value in enumerate(predictions)}
|
65 |
+
|
66 |
+
if species_list:
|
67 |
+
filtered_predictions = [(key, value) for key, value in original.items() if key in species_list]
|
68 |
+
else:
|
69 |
+
filtered_predictions = [(key, value) for key, value in original.items()]
|
70 |
+
|
71 |
+
return filtered_predictions
|
72 |
+
|
73 |
+
|
74 |
+
class DistributionDB:
|
75 |
+
def __init__(self, db_path):
|
76 |
+
self.con = sqlite3.connect(db_path)
|
77 |
+
self.cur = self.con.cursor()
|
78 |
+
|
79 |
+
|
80 |
+
def get_list(self, lat, lng) -> list:
|
81 |
+
self.cur.execute(f'''
|
82 |
+
SELECT m.cls
|
83 |
+
FROM distributions AS d
|
84 |
+
LEFT OUTER JOIN places AS p
|
85 |
+
ON p.worldid = d.worldid
|
86 |
+
LEFT OUTER JOIN sp_cls_map AS m
|
87 |
+
ON d.species = m.species
|
88 |
+
WHERE p.south <= {lat}
|
89 |
+
AND p.north >= {lat}
|
90 |
+
AND p.east >= {lng}
|
91 |
+
AND p.west <= {lng}
|
92 |
+
GROUP BY d.species, m.cls;
|
93 |
+
''')
|
94 |
+
|
95 |
+
return [row[0] for row in self.cur]
|
96 |
+
|
97 |
+
def close(self):
|
98 |
+
self.cur.close()
|
99 |
+
self.con.close()
|
100 |
+
|
101 |
+
|
102 |
+
# If the user uploads an image
|
103 |
+
if uploaded_file is not None:
|
104 |
+
try:
|
105 |
+
sqlite_path = hf_hub_download(repo_id='sunjiao/osea', filename='avonet.db')
|
106 |
+
st.success(f"Successfully downloaded distribution database from Hugging Face Hub!")
|
107 |
+
|
108 |
+
label_map_path = hf_hub_download(repo_id='sunjiao/osea', filename='bird_info.json')
|
109 |
+
st.success(f"Successfully downloaded labels from Hugging Face Hub!")
|
110 |
+
except Exception as e:
|
111 |
+
st.error(f"Failed to download the file: {e}")
|
112 |
+
st.stop()
|
113 |
+
|
114 |
+
db = DistributionDB(sqlite_path)
|
115 |
+
species_list = db.get_list(latitude, longitude)
|
116 |
+
db.close()
|
117 |
+
|
118 |
+
# Open the image
|
119 |
+
image = Image.open(uploaded_file)
|
120 |
+
|
121 |
+
# Display the uploaded image
|
122 |
+
st.image(image, caption="Uploaded Image", use_container_width=True)
|
123 |
+
|
124 |
+
model = AutoModelForImageClassification.from_pretrained('sunjiao/osea')
|
125 |
+
|
126 |
+
results = classify_objects(model, image, species_list)
|
127 |
+
|
128 |
+
top3_results = results[:3]
|
129 |
+
|
130 |
+
with open(label_map_path, 'r') as f:
|
131 |
+
data = f.read()
|
132 |
+
|
133 |
+
bird_info = json.loads(data)
|
134 |
+
|
135 |
+
# Display the top 3 results and their probabilities
|
136 |
+
st.subheader("Classification Results (Top 3):")
|
137 |
+
for result in top3_results:
|
138 |
+
st.write(f"{bird_info[result[0]][lang]}: {result[1]:.4f}")
|
139 |
+
|
140 |
+
# Display latitude and longitude if provided
|
141 |
+
if latitude is not None and longitude is not None:
|
142 |
+
st.write(f"Entered Latitude: {latitude}, Longitude: {longitude}")
|