Ricesuu commited on
Commit
b36a0df
·
verified ·
1 Parent(s): 31057e8

Upload 6 files

Browse files
README.md CHANGED
@@ -1,12 +1,39 @@
1
  ---
2
- title: BirdClassificationApp
3
- emoji: 🐨
4
- colorFrom: pink
5
- colorTo: green
6
  sdk: gradio
7
- sdk_version: 5.49.1
8
  app_file: app.py
9
  pinned: false
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Bird Species Classifier 🐦
3
+ emoji: 🪶
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 4.42.0
8
  app_file: app.py
9
  pinned: false
10
+ license: mit
11
+ python_version: 3.10
12
  ---
13
 
14
+ # 🐦 Bird Species Classifier (EfficientNet-B3 & EfficientNetV2-S)
15
+
16
+ A fine-grained bird species classifier powered by **EfficientNet models** (B3 and V2-S) trained on the **CUB-200 dataset**.
17
+ Users can upload or capture bird photos and choose between two models to identify the species.
18
+
19
+ ---
20
+
21
+ ## 🚀 Features
22
+
23
+ ✅ **Upload or Webcam Input** — Upload an image or use your camera in real time.
24
+ ✅ **Model Selection** — Choose between:
25
+
26
+ - **EfficientNet-B3** → lightweight, fast inference.
27
+ - **EfficientNetV2-S (in21k)** → larger, higher accuracy.
28
+ ✅ **Top-5 Predictions** with confidence percentages.
29
+ ✅ **Interactive Gradio UI** built for Hugging Face Spaces.
30
+ ✅ **GPU-ready** (automatically detects CUDA if available).
31
+
32
+ ---
33
+
34
+ ## 🧠 Models Used
35
+
36
+ - `tf_efficientnet_b3_ns` pretrained on ImageNet-1k, fine-tuned on CUB-200.
37
+ - `tf_efficientnetv2_s.in21k` pretrained on ImageNet-21k, fine-tuned on CUB-200.
38
+
39
+ Both models are saved under the `models/` folder:
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import timm
4
+ import torchvision.transforms as T
5
+ from PIL import Image
6
+ import numpy as np
7
+ import json
8
+
9
+ # ------------------------------
10
+ # CONFIG
11
+ # ------------------------------
12
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
13
+ NUM_CLASSES = 200 # change if your dataset differs
14
+
15
+ MODEL_PATHS = {
16
+ "EfficientNet-B3": "models/BestEfficientNetB3_model.pth",
17
+ "EfficientNetV2-S (in21k)": "models/BestEfficientNetV2S_model.pth"
18
+ }
19
+
20
+ MODEL_NAMES = {
21
+ "EfficientNet-B3": "tf_efficientnet_b3_ns",
22
+ "EfficientNetV2-S (in21k)": "tf_efficientnetv2_s.in21k"
23
+ }
24
+
25
+ # ------------------------------
26
+ # TRANSFORMS
27
+ # ------------------------------
28
+ transform = T.Compose([
29
+ T.Resize((300, 300)), # fits both models
30
+ T.ToTensor(),
31
+ T.Normalize(mean=[0.485, 0.456, 0.406],
32
+ std=[0.229, 0.224, 0.225])
33
+ ])
34
+
35
+ # ------------------------------
36
+ # LOAD MODEL
37
+ # ------------------------------
38
+ @torch.inference_mode()
39
+ def load_model(model_name):
40
+ model = timm.create_model(MODEL_NAMES[model_name], pretrained=False, num_classes=NUM_CLASSES)
41
+ model.load_state_dict(torch.load(MODEL_PATHS[model_name], map_location=DEVICE))
42
+ model = model.to(DEVICE)
43
+ model.eval()
44
+ return model
45
+
46
+ # Cache loaded models to avoid reloading
47
+ loaded_models = {}
48
+
49
+ def get_model(model_name):
50
+ if model_name not in loaded_models:
51
+ loaded_models[model_name] = load_model(model_name)
52
+ return loaded_models[model_name]
53
+
54
+ # ------------------------------
55
+ # CLASS LABELS (optional)
56
+ # ------------------------------
57
+ try:
58
+ with open("class_names.json", "r") as f:
59
+ CLASS_NAMES = json.load(f)
60
+ except FileNotFoundError:
61
+ CLASS_NAMES = [f"Class {i}" for i in range(NUM_CLASSES)]
62
+
63
+ # ------------------------------
64
+ # PREDICTION FUNCTION
65
+ # ------------------------------
66
+ def predict(image, model_choice):
67
+ if image is None:
68
+ return None, "Please upload an image."
69
+ model = get_model(model_choice)
70
+
71
+ # Preprocess
72
+ img = transform(image).unsqueeze(0).to(DEVICE)
73
+
74
+ with torch.no_grad():
75
+ logits = model(img)
76
+ probs = torch.nn.functional.softmax(logits, dim=1)[0]
77
+ top5 = torch.topk(probs, 5)
78
+
79
+ top_classes = [CLASS_NAMES[i] for i in top5.indices.cpu().numpy()]
80
+ top_scores = [float(p)*100 for p in top5.values.cpu().numpy()]
81
+
82
+ # Prepare output table
83
+ result_table = { "Class": top_classes, "Confidence (%)": [round(s, 2) for s in top_scores] }
84
+
85
+ # Optionally overlay class name
86
+ display = image.copy()
87
+ return result_table, f"✅ Prediction complete for {model_choice}"
88
+
89
+ # ------------------------------
90
+ # GRADIO UI
91
+ # ------------------------------
92
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
93
+ gr.Markdown(
94
+ """
95
+ # 🐦 Bird Species Classifier
96
+ Upload a bird image or use your camera to identify the species using EfficientNet models.
97
+ **Features:** model selection, top-5 predictions, and confidence scores.
98
+ """
99
+ )
100
+
101
+ with gr.Row():
102
+ with gr.Column(scale=1):
103
+ image_input = gr.Image(type="pil", label="Upload or Capture Image", sources=["upload", "webcam"])
104
+ model_choice = gr.Dropdown(list(MODEL_PATHS.keys()), value="EfficientNetV2-S (in21k)", label="Select Model")
105
+ classify_btn = gr.Button("🔍 Classify")
106
+ with gr.Column(scale=1):
107
+ result_output = gr.Dataframe(headers=["Class", "Confidence (%)"], label="Top-5 Predictions")
108
+ status_output = gr.Textbox(label="Status", interactive=False)
109
+
110
+ classify_btn.click(fn=predict, inputs=[image_input, model_choice], outputs=[result_output, status_output])
111
+
112
+ gr.Markdown(
113
+ """
114
+ ---
115
+ ### ⚙️ Tips
116
+ - Use **EfficientNetV2-S** for higher accuracy, **B3** for faster inference.
117
+ - Confidence scores show model certainty.
118
+ - You can expand this app with Grad-CAM visualizations or background blurring.
119
+ """
120
+ )
121
+
122
+ # ------------------------------
123
+ # LAUNCH
124
+ # ------------------------------
125
+ if __name__ == "__main__":
126
+ demo.launch(server_name="0.0.0.0", server_port=7860)
class_names.json ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ "Black footed Albatross",
3
+ "Laysan Albatross",
4
+ "Sooty Albatross",
5
+ "Groove billed Ani",
6
+ "Crested Auklet",
7
+ "Least Auklet",
8
+ "Parakeet Auklet",
9
+ "Rhinoceros Auklet",
10
+ "Brewer Blackbird",
11
+ "Red winged Blackbird",
12
+ "Rusty Blackbird",
13
+ "Yellow headed Blackbird",
14
+ "Bobolink",
15
+ "Indigo Bunting",
16
+ "Lazuli Bunting",
17
+ "Painted Bunting",
18
+ "Cardinal",
19
+ "Spotted Catbird",
20
+ "Gray Catbird",
21
+ "Yellow breasted Chat",
22
+ "Eastern Towhee",
23
+ "Chuck will Widow",
24
+ "Brandt Cormorant",
25
+ "Red faced Cormorant",
26
+ "Pelagic Cormorant",
27
+ "Bronzed Cowbird",
28
+ "Shiny Cowbird",
29
+ "Brown Creeper",
30
+ "American Crow",
31
+ "Fish Crow",
32
+ "Black billed Cuckoo",
33
+ "Mangrove Cuckoo",
34
+ "Yellow billed Cuckoo",
35
+ "Gray crowned Rosy Finch",
36
+ "Purple Finch",
37
+ "Northern Flicker",
38
+ "Acadian Flycatcher",
39
+ "Great Crested Flycatcher",
40
+ "Least Flycatcher",
41
+ "Olive sided Flycatcher",
42
+ "Scissor tailed Flycatcher",
43
+ "Vermilion Flycatcher",
44
+ "Yellow bellied Flycatcher",
45
+ "Frigatebird",
46
+ "Northern Fulmar",
47
+ "Gadwall",
48
+ "American Goldfinch",
49
+ "European Goldfinch",
50
+ "Boat tailed Grackle",
51
+ "Eared Grebe",
52
+ "Horned Grebe",
53
+ "Pied billed Grebe",
54
+ "Western Grebe",
55
+ "Blue Grosbeak",
56
+ "Evening Grosbeak",
57
+ "Pine Grosbeak",
58
+ "Rose breasted Grosbeak",
59
+ "Pigeon Guillemot",
60
+ "California Gull",
61
+ "Glaucous winged Gull",
62
+ "Heermann Gull",
63
+ "Herring Gull",
64
+ "Ivory Gull",
65
+ "Ring billed Gull",
66
+ "Slaty backed Gull",
67
+ "Western Gull",
68
+ "Anna Hummingbird",
69
+ "Ruby throated Hummingbird",
70
+ "Rufous Hummingbird",
71
+ "Green Violetear",
72
+ "Long tailed Jaeger",
73
+ "Pomarine Jaeger",
74
+ "Blue Jay",
75
+ "Florida Jay",
76
+ "Green Jay",
77
+ "Dark eyed Junco",
78
+ "Tropical Kingbird",
79
+ "Gray Kingbird",
80
+ "Belted Kingfisher",
81
+ "Green Kingfisher",
82
+ "Pied Kingfisher",
83
+ "Ringed Kingfisher",
84
+ "White breasted Kingfisher",
85
+ "Red legged Kittiwake",
86
+ "Horned Lark",
87
+ "Pacific Loon",
88
+ "Mallard",
89
+ "Western Meadowlark",
90
+ "Hooded Merganser",
91
+ "Red breasted Merganser",
92
+ "Mockingbird",
93
+ "Nighthawk",
94
+ "Clark Nutcracker",
95
+ "White breasted Nuthatch",
96
+ "Baltimore Oriole",
97
+ "Hooded Oriole",
98
+ "Orchard Oriole",
99
+ "Scott Oriole",
100
+ "Ovenbird",
101
+ "Brown Pelican",
102
+ "White Pelican",
103
+ "Western Wood Pewee",
104
+ "Sayornis",
105
+ "American Pipit",
106
+ "Whip poor Will",
107
+ "Horned Puffin",
108
+ "Common Raven",
109
+ "White necked Raven",
110
+ "American Redstart",
111
+ "Geococcyx",
112
+ "Loggerhead Shrike",
113
+ "Great Grey Shrike",
114
+ "Baird Sparrow",
115
+ "Black throated Sparrow",
116
+ "Brewer Sparrow",
117
+ "Chipping Sparrow",
118
+ "Clay colored Sparrow",
119
+ "House Sparrow",
120
+ "Field Sparrow",
121
+ "Fox Sparrow",
122
+ "Grasshopper Sparrow",
123
+ "Harris Sparrow",
124
+ "Henslow Sparrow",
125
+ "Le Conte Sparrow",
126
+ "Lincoln Sparrow",
127
+ "Nelson Sharp tailed Sparrow",
128
+ "Savannah Sparrow",
129
+ "Seaside Sparrow",
130
+ "Song Sparrow",
131
+ "Tree Sparrow",
132
+ "Vesper Sparrow",
133
+ "White crowned Sparrow",
134
+ "White throated Sparrow",
135
+ "Cape Glossy Starling",
136
+ "Bank Swallow",
137
+ "Barn Swallow",
138
+ "Cliff Swallow",
139
+ "Tree Swallow",
140
+ "Scarlet Tanager",
141
+ "Summer Tanager",
142
+ "Artic Tern",
143
+ "Black Tern",
144
+ "Caspian Tern",
145
+ "Common Tern",
146
+ "Elegant Tern",
147
+ "Forsters Tern",
148
+ "Least Tern",
149
+ "Green tailed Towhee",
150
+ "Brown Thrasher",
151
+ "Sage Thrasher",
152
+ "Black capped Vireo",
153
+ "Blue headed Vireo",
154
+ "Philadelphia Vireo",
155
+ "Red eyed Vireo",
156
+ "Warbling Vireo",
157
+ "White eyed Vireo",
158
+ "Yellow throated Vireo",
159
+ "Bay breasted Warbler",
160
+ "Black and white Warbler",
161
+ "Black throated Blue Warbler",
162
+ "Blue winged Warbler",
163
+ "Canada Warbler",
164
+ "Cape May Warbler",
165
+ "Cerulean Warbler",
166
+ "Chestnut sided Warbler",
167
+ "Golden winged Warbler",
168
+ "Hooded Warbler",
169
+ "Kentucky Warbler",
170
+ "Magnolia Warbler",
171
+ "Mourning Warbler",
172
+ "Myrtle Warbler",
173
+ "Nashville Warbler",
174
+ "Orange crowned Warbler",
175
+ "Palm Warbler",
176
+ "Pine Warbler",
177
+ "Prairie Warbler",
178
+ "Prothonotary Warbler",
179
+ "Swainson Warbler",
180
+ "Tennessee Warbler",
181
+ "Wilson Warbler",
182
+ "Worm eating Warbler",
183
+ "Yellow Warbler",
184
+ "Northern Waterthrush",
185
+ "Louisiana Waterthrush",
186
+ "Bohemian Waxwing",
187
+ "Cedar Waxwing",
188
+ "American Three toed Woodpecker",
189
+ "Pileated Woodpecker",
190
+ "Red bellied Woodpecker",
191
+ "Red cockaded Woodpecker",
192
+ "Red headed Woodpecker",
193
+ "Downy Woodpecker",
194
+ "Bewick Wren",
195
+ "Cactus Wren",
196
+ "Carolina Wren",
197
+ "House Wren",
198
+ "Marsh Wren",
199
+ "Rock Wren",
200
+ "Winter Wren",
201
+ "Common Yellowthroat"
202
+ ]
models/BestEfficientNetB3_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5bc72d1ef7a559a9d00884f06b3625ee2edcf543a55a93c91fc3026ff5942ad5
3
+ size 44573831
models/BestEfficientNetV2S_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:562fdce837012eb7b49f60473f51ae1e7746d179e1c2649a2984cdd6cb18d90b
3
+ size 82640587
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ timm
4
+ gradio
5
+ numpy
6
+ pillow