-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
169 lines (142 loc) · 6.02 KB
/
main.py
File metadata and controls
169 lines (142 loc) · 6.02 KB
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
161
162
163
164
165
166
167
168
169
import onnxruntime as ort
import numpy as np
from PIL import Image
import requests
import ijson
import json
import sys
import os
import glob
try:
session = ort.InferenceSession("insect_model.onnx")
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
input_shape = session.get_inputs()[0].shape
except Exception as e:
print(f"❌ Erreur modèle: {e}")
sys.exit(1)
with open('hierarchy_map.json', 'r') as f:
data = json.load(f)
hierarchy_map = data['full_taxa_map']
with open('hierarchy_labels.json', 'r') as f:
labels = json.load(f)
# Load classes in the order used for training
ordre_classes = [labels['id_to_name']['ordre'][str(i)] for i in range(labels['stats']['ordres'])]
famille_classes = [labels['id_to_name']['famille'][str(i)] for i in range(labels['stats']['familles'])]
genre_classes = [labels['id_to_name']['genre'][str(i)] for i in range(labels['stats']['genres'])]
sorted_class_to_idx = sorted(labels['class_to_idx'].items(), key=lambda x: x[1])
espece_classes = [full_name.split('_')[-1] for full_name, idx in sorted_class_to_idx]
class_counts = [len(ordre_classes), len(famille_classes), len(genre_classes), len(espece_classes)]
final_hierarchy = {}
for taxon_id_str, data in hierarchy_map.items():
try:
ordre_id = ordre_classes.index(data['ordre'])
famille_id = famille_classes.index(data['famille'])
genre_id = genre_classes.index(data['genre'])
espece_id = espece_classes.index(data['espece'])
final_hierarchy[espece_id] = [ordre_id, famille_id, genre_id, espece_id]
except (ValueError, KeyError):
continue
def decode_logits(logits: np.ndarray, class_counts: list) -> tuple:
"""Decode en ignorant padding après vraies classes."""
hierarchy_ids = []
confidences = []
for lvl, num_classes in enumerate(class_counts):
# SEULEMENT les PREMÈRES num_classes (ignore padding)
lvl_logits = logits[lvl, :num_classes]
pred_id = lvl_logits.argmax()
probs = np.exp(lvl_logits) / np.sum(np.exp(lvl_logits))
confidence = probs[pred_id] * 100
hierarchy_ids.append(pred_id)
confidences.append(confidence)
return hierarchy_ids, confidences
# === 4. PROCESSING ===
def preprocess_image(image_path: str) -> np.ndarray:
"""Image → ONNX tensor."""
image = Image.open(image_path).convert('RGB').resize((224, 224))
img_array = np.array(image).astype(np.float32) / 255.0
mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
img_array = (img_array - mean) / std
return img_array.transpose(2, 0, 1)[np.newaxis, ...] # [1,C,H,W]
def get_species_info(species_name: str) -> dict:
"""GBIF lookup."""
try:
search_url = "https://api.gbif.org/v1/species/search?q=" + species_name.replace(" ", "+")
resp = requests.get(search_url, headers={'User-Agent': 'Insect-ID/1.0'}, timeout=5)
if resp.status_code != 200 or not resp.json()['results']:
return {"error": "Aucune espèce trouvée"}
species_id = resp.json()['results'][0]['key']
detail_url = f"https://api.gbif.org/v1/species/{species_id}"
detail_resp = requests.get(detail_url, headers={'User-Agent': 'Insect-ID/1.0'}, timeout=5)
data = detail_resp.json()
return {
"nom": data.get("scientificName", species_name),
"famille": data.get("family", ""),
"genre": data.get("genus", ""),
"url": f"https://www.gbif.org/species/{species_id}"
}
except:
return {"error": "API erreur"}
# === 5. MAIN PROCESS ===
def process_image(image_path: str):
print(f"\n{'='*60}")
print(f"🖼️ Analyse: {os.path.basename(image_path)}")
print('='*60)
# Preprocess
input_tensor = preprocess_image(image_path)
# Inference
outputs = session.run([output_name], {input_name: input_tensor})
logits = outputs[0] # (1,4,2526) ou (4,2526)
if logits.ndim == 3:
logits = logits[0] # Retire batch
# Decode - Predict species only to avoid cascade
espece_id = logits[3, :class_counts[3]].argmax()
coherent_hierarchy = final_hierarchy.get(espece_id, [0,0,0,espece_id])
# Compute confidences for the coherent hierarchy
confidences = []
for lvl in range(4):
lvl_logits = logits[lvl, :class_counts[lvl]]
probs = np.exp(lvl_logits) / np.sum(np.exp(lvl_logits))
pred_id = coherent_hierarchy[lvl]
confidence = probs[pred_id] * 100
confidences.append(confidence)
avg_conf = np.mean(confidences)
# Noms
names = [
ordre_classes[coherent_hierarchy[0]],
famille_classes[coherent_hierarchy[1]],
genre_classes[coherent_hierarchy[2]],
espece_classes[coherent_hierarchy[3]]
]
# Overall confidence (average)
avg_conf = np.mean(confidences)
# Threshold check
if avg_conf < 60:
print("⚠️ Prédiction incertaine (confiance moyenne < 60%), le résultat peut être erroné.")
else:
print("✅ Prédiction fiable.")
print("\n🎯 RÉSULTAT FINAL:")
print("┌" + "─"*60 + "┐")
for lvl, name in enumerate(names):
conf = confidences[lvl]
print(f"│ {['Ordre','Famille','Genre','Espèce'][lvl]:8}: {name} ({conf:.1f}%)")
print(f"│ Confiance moyenne: {avg_conf:.1f}%")
print("└" + "─"*60 + "┘")
# GBIF
species_name = f"{names[2]} {names[3]}"
info = get_species_info(species_name)
print(f"🌍 GBIF '{species_name}': {info.get('nom', info.get('error', 'N/A'))}")
for k, v in info.items():
if k != 'nom':
print(f" {k.capitalize()}: {v}")
# === EXEC ===
if len(sys.argv) == 1:
image_paths = glob.glob("images/*.jpg") + glob.glob("images/*.png") + glob.glob("images/*.jpeg")
if not image_paths:
print("❌ Aucune image *.jpg/png/jpeg")
sys.exit(1)
for path in sorted(image_paths):
process_image(path)
else:
process_image(sys.argv[1])