File size: 5,196 Bytes
2ded624 7fb195d 49a7401 d79e14c 688a048 bddc3d6 2ded624 a70a8b5 2ded624 a70a8b5 2ded624 a70a8b5 2ded624 a70a8b5 2ded624 a70a8b5 2ded624 a70a8b5 2ded624 a70a8b5 2ded624 a70a8b5 2ded624 a70a8b5 2ded624 a70a8b5 49a7401 a70a8b5 8732376 a70a8b5 aadf03a 8732376 aadf03a 7fb195d 8732376 7fb195d 688a048 7fb195d 164d735 688a048 3802471 688a048 164d735 8732376 7fb195d 8732376 688a048 8732376 a70a8b5 b6ab652 688a048 493777d 49a7401 b6ab652 a70a8b5 8732376 49a7401 a70a8b5 8732376 49a7401 abffa49 8732376 7fb195d b6ab652 7fb195d 49a7401 bda76e2 49a7401 688a048 f7724ab e6445f0 f7724ab 92d1004 e6445f0 f7724ab 493777d f7724ab 7fb195d f7724ab 49a7401 7fb195d 49a7401 493777d | 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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | import os
import json
import torch
from torch import nn
from torchvision import models
from torchvision.transforms import v2
from huggingface_hub import hf_hub_download
import gradio as gr
labels = [
'Pastel',
'Clown',
'Yellow Belly',
'Enchi',
'Piebald',
'Leopard',
'Orange Dream',
'Fire',
'Mojave',
'Spotnose',
'Banana',
'Desert Ghost',
'Black Pastel',
'Hypo',
'Normal',
'Pinstripe',
'GHI',
'Lesser',
'Cinnamon',
'Red Stripe',
'Black Head',
'Super Pastel',
'Chocolate',
'Axanthic (VPI)',
'Cypress',
'Vanilla',
'Gravel',
'Butter',
'Ultramel',
'Asphalt',
'Calico',
'Stranger',
'Spider',
'Lavender Albino',
'Hurricane',
'Mahogany',
'Albino'
]
num_labels = len(labels)
# Toggle between optimized per-class thresholds and a fixed 0.5 cutoff
USE_OPTIMIZED_THRESHOLD = True
# If using GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
hf_token = os.getenv('HF_token')
model_path = hf_hub_download(repo_id="samfhy/morphmarket_model", filename="model_v2_epoch26.pt", token=hf_token)
checkpoint = torch.load(model_path, map_location=device)
# Load per-class optimized thresholds
thresholds_path = hf_hub_download(repo_id="samfhy/morphmarket_model", filename="optimal_thresholds_v2.json", token=hf_token)
with open(thresholds_path, 'r') as f:
optimal_thresholds = json.load(f)
new_layers = nn.Sequential(
nn.LazyLinear(2048),
nn.BatchNorm1d(2048),
nn.ReLU(),
nn.Dropout(0.5),
nn.LazyLinear(num_labels)
)
IMAGE_SIZE = checkpoint['image_size']
transform = v2.Compose([
v2.ToImage(),
v2.Resize(int(IMAGE_SIZE * 1.14), antialias=True),
v2.CenterCrop(IMAGE_SIZE),
v2.ToDtype(torch.float32, scale=True),
v2.Normalize(mean=[0.6007, 0.5679, 0.5206], std=[0.2411, 0.2392, 0.2479])
])
tta_transform = v2.Compose([
v2.ToImage(),
v2.Resize(int(IMAGE_SIZE * 1.14), antialias=True),
v2.CenterCrop(IMAGE_SIZE),
v2.RandomHorizontalFlip(p=1.0), # always flip
v2.ToDtype(torch.float32, scale=True),
v2.Normalize(mean=[0.6007, 0.5679, 0.5206], std=[0.2411, 0.2392, 0.2479])
])
efficientnet = models.efficientnet_v2_l(weights=None)
efficientnet.classifier = new_layers
efficientnet.load_state_dict(checkpoint['model_state_dict'])
efficientnet.to(device).eval()
def predict(img):
if img is None:
return {}
img = img.convert('RGB')
base_input = transform(img).unsqueeze(0).to(device)
flipped_input = tta_transform(img).unsqueeze(0).to(device)
with torch.no_grad():
base_probs = torch.sigmoid(efficientnet(base_input))
flipped_probs = torch.sigmoid(efficientnet(flipped_input))
predicted_probs = base_probs.cpu().flatten().tolist()
predicted_probs = ((base_probs + flipped_probs) / 2.0).cpu().flatten().tolist()
prediction_dict = {}
for i, label in enumerate(labels):
thresh = optimal_thresholds.get(label, 0.5) if USE_OPTIMIZED_THRESHOLD else 0.5
if predicted_probs[i] >= thresh:
prediction_dict[label] = predicted_probs[i]
return prediction_dict
with gr.Blocks(title='Ball Python Morph Identifier') as demo:
gr.Markdown("# Ball Python Morph Identifier")
gr.Markdown("Upload or paste an image of your ball python to identify its morphs!")
gr.Markdown("""
If you're unfamiliar with snakes, ball pythons come in various patterns and colors,
called *morphs*, which can be difficult to distinguish without expert knowledge.
This tool automatically identifies these unique variations, making identification accessible to everyone.
Try selecting one of the examples and click "Identify Morphs" to see how it works!
""")
with gr.Accordion("Click here to show all the morphs that can be predicted", open=False):
gr.Markdown("""
Albino, Asphalt, Axanthic (VPI), Banana, Black Head, Black Pastel, Butter, Calico, Chocolate, Cinnamon, Clown,
Cypress, Desert Ghost, Enchi, Fire, GHI, Gravel, Hurricane, Hypo, Lavender Albino, Leopard, Lesser, Mahogany, Mojave,
Normal, Orange Dream, Pastel, Piebald, Pinstripe, Red Stripe, Spider, Spotnose, Stranger, Super Pastel, Ultramel, Vanilla, Yellow Belly
""")
with gr.Row():
with gr.Column(scale=1):
img_input = gr.Image(type="pil", label="Upload/Paste Image")
gr.Examples(
examples=[
["enchi_albino_clown.png", "Enchi, Albino, Clown"],
["mojave_ghi.png", "Mojave, GHI"],
["hypo_banana_pastel_enchi.png", "Hypo, Banana, Pastel, Enchi"],
["yb_pastel_gravel.png", "Yellow Belly, Pastel, Gravel"],
["ivory.png", "Super Yellow Belly"]
],
inputs=[img_input]
)
predict_btn = gr.Button("Identify Morphs", variant="primary")
with gr.Column(scale=1):
label_output = gr.Label(label="Predicted Morphs")
predict_btn.click(fn=predict, inputs=[img_input], outputs=label_output)
demo.launch() |