Spaces:
Running
Running
Commit Β·
5f084a6
1
Parent(s): 0d15c78
retagging images
Browse files- api/detection.py +113 -146
api/detection.py
CHANGED
|
@@ -68,84 +68,57 @@ async def predict(
|
|
| 68 |
"results": new_results
|
| 69 |
}
|
| 70 |
# βββββββββββββββββ
|
| 71 |
-
#
|
| 72 |
# βββββββββββββββββ
|
| 73 |
|
| 74 |
-
|
| 75 |
-
# ================================================================
|
| 76 |
-
# VALID LABELS β must exactly match what process_images_batch()
|
| 77 |
-
# produces from the 3-stage YOLO pipeline:
|
| 78 |
-
# Stage 1: deer detected
|
| 79 |
-
# Stage 2: Buck β Stage 3: Whitetail | Mule
|
| 80 |
-
# Stage 2: Doe
|
| 81 |
-
# ================================================================
|
| 82 |
VALID_LABELS = {
|
| 83 |
-
"Deer | Doe", # trailing space matches pipeline output
|
| 84 |
-
"Deer | Buck | White Tail Bucks",
|
| 85 |
-
"Deer | Buck | Mule Bucks",
|
| 86 |
-
}
|
| 87 |
-
|
| 88 |
-
VALID_LABELS_DISPLAY = [ # clean version shown in error messages
|
| 89 |
"Deer | Doe",
|
| 90 |
"Deer | Buck | White Tail Bucks",
|
| 91 |
"Deer | Buck | Mule Bucks",
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def _normalise_label(label: str) -> str:
|
| 98 |
-
"""Strip and normalise label so 'Deer | Doe' == 'Deer | Doe '."""
|
| 99 |
return label.strip()
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
def
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
# Match against normalised versions of VALID_LABELS
|
| 106 |
-
if normalised not in {l.strip() for l in VALID_LABELS}:
|
| 107 |
raise HTTPException(
|
| 108 |
status_code=422,
|
| 109 |
-
detail=
|
| 110 |
-
f"Invalid label '{label}'. "
|
| 111 |
-
f"Must be one of: {VALID_LABELS_DISPLAY}"
|
| 112 |
-
)
|
| 113 |
)
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
return
|
| 119 |
-
|
| 120 |
-
|
| 121 |
# βββββββββββββββββ
|
| 122 |
# Request Models
|
| 123 |
# βββββββββββββββββ
|
| 124 |
-
|
| 125 |
class DetectionOperation(BaseModel):
|
| 126 |
action: Literal["add", "update", "delete"]
|
| 127 |
detection_index: Optional[int] = None
|
| 128 |
label: Optional[str] = None
|
| 129 |
-
bbox: Optional[List[float]] = None
|
| 130 |
-
|
| 131 |
@validator("label")
|
| 132 |
-
def
|
| 133 |
if v is None:
|
| 134 |
return v
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
if normalised not in valid_normalised:
|
| 138 |
-
raise ValueError(
|
| 139 |
-
f"Invalid label '{v}'. Must be one of: {VALID_LABELS_DISPLAY}"
|
| 140 |
-
)
|
| 141 |
-
# Return canonical form
|
| 142 |
-
for valid in VALID_LABELS:
|
| 143 |
-
if valid.strip() == normalised:
|
| 144 |
-
return valid
|
| 145 |
-
return v
|
| 146 |
-
|
| 147 |
@validator("bbox")
|
| 148 |
-
def
|
| 149 |
if v is None:
|
| 150 |
return v
|
| 151 |
if len(v) != 4:
|
|
@@ -154,127 +127,122 @@ class DetectionOperation(BaseModel):
|
|
| 154 |
if x2 <= x1 or y2 <= y1:
|
| 155 |
raise ValueError("bbox must satisfy x2 > x1 and y2 > y1")
|
| 156 |
return v
|
| 157 |
-
|
| 158 |
@validator("detection_index")
|
| 159 |
-
def
|
| 160 |
if v is not None and v < 0:
|
| 161 |
raise ValueError("detection_index must be >= 0")
|
| 162 |
return v
|
| 163 |
-
|
| 164 |
-
|
| 165 |
class MultiUpdateRequest(BaseModel):
|
| 166 |
user_id: str
|
| 167 |
camera_name: str
|
| 168 |
image_url: str
|
| 169 |
operations: List[DetectionOperation]
|
| 170 |
-
|
| 171 |
@validator("operations")
|
| 172 |
-
def
|
| 173 |
-
if not
|
| 174 |
raise ValueError("operations list cannot be empty")
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
# βββββββββββββββββ
|
| 196 |
# Endpoint
|
| 197 |
# βββββββββββββββββ
|
| 198 |
-
|
| 199 |
@router.post("/modify_detections")
|
| 200 |
async def modify_detections(req: MultiUpdateRequest):
|
| 201 |
-
|
| 202 |
-
Add, update, and delete detections (tags) for a given image.
|
| 203 |
-
Supports multiple operations in a single request.
|
| 204 |
-
Labels must match the detection pipeline format exactly.
|
| 205 |
-
"""
|
| 206 |
-
|
| 207 |
-
# ββ Validate user & camera ββββββββββββββββββββββββββββββββββββ
|
| 208 |
validate_user_and_camera(req.user_id, req.camera_name)
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
if not _key_exists(json_key):
|
| 213 |
raise HTTPException(status_code=404, detail="Detections file not found")
|
| 214 |
-
|
| 215 |
-
# ββ Load data from bucket βββββββββββββββββββββββββββββββββββββ
|
| 216 |
data = load_json(json_key)
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
record =
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
if record is None:
|
| 230 |
raise HTTPException(status_code=404, detail="Image not found")
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
dets = record["detections"]
|
| 237 |
-
|
| 238 |
-
# ββ Apply operations ββββββββββββββββββββββββββββββββββββββββββ
|
| 239 |
-
# Deletes run in reverse index order to avoid index shifting
|
| 240 |
delete_ops = [op for op in req.operations if op.action == "delete"]
|
| 241 |
-
other_ops
|
| 242 |
-
|
| 243 |
-
# DELETE (reverse order
|
| 244 |
-
for op in sorted(delete_ops, key=lambda x: x.detection_index
|
| 245 |
-
|
|
|
|
| 246 |
raise HTTPException(
|
| 247 |
status_code=400,
|
| 248 |
-
detail=f"Invalid delete index {
|
| 249 |
)
|
| 250 |
-
dets.pop(
|
| 251 |
-
|
| 252 |
-
# ADD + UPDATE
|
| 253 |
for op in other_ops:
|
| 254 |
-
|
| 255 |
if op.action == "add":
|
| 256 |
dets.append({
|
| 257 |
-
"label":
|
| 258 |
-
"confidence":
|
| 259 |
-
"bbox":
|
| 260 |
"manually_edited": True
|
| 261 |
})
|
| 262 |
-
|
| 263 |
elif op.action == "update":
|
| 264 |
-
|
|
|
|
| 265 |
raise HTTPException(
|
| 266 |
status_code=400,
|
| 267 |
-
detail=f"Invalid update index {
|
| 268 |
)
|
|
|
|
| 269 |
if op.label is not None:
|
| 270 |
-
dets[
|
|
|
|
| 271 |
if op.bbox is not None:
|
| 272 |
-
dets[
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
save_json(json_key, data)
|
| 277 |
-
|
| 278 |
logger.info(
|
| 279 |
"Detections modified | user=%s camera=%s file=%s ops=%d final_count=%d",
|
| 280 |
req.user_id,
|
|
@@ -283,12 +251,11 @@ async def modify_detections(req: MultiUpdateRequest):
|
|
| 283 |
len(req.operations),
|
| 284 |
len(dets)
|
| 285 |
)
|
| 286 |
-
|
| 287 |
return {
|
| 288 |
-
"success":
|
| 289 |
-
"message":
|
| 290 |
-
"filename":
|
| 291 |
"total_detections": len(dets),
|
| 292 |
-
"detections":
|
| 293 |
-
}
|
| 294 |
-
|
|
|
|
| 68 |
"results": new_results
|
| 69 |
}
|
| 70 |
# βββββββββββββββββ
|
| 71 |
+
# VALID LABELS
|
| 72 |
# βββββββββββββββββ
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
VALID_LABELS = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
"Deer | Doe",
|
| 76 |
"Deer | Buck | White Tail Bucks",
|
| 77 |
"Deer | Buck | Mule Bucks",
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
VALID_LABELS_DISPLAY = list(VALID_LABELS)
|
| 81 |
+
|
| 82 |
+
# Precompute normalized β canonical mapping (FAST lookup)
|
| 83 |
+
NORMALIZED_LABEL_MAP = {l.strip(): l for l in VALID_LABELS}
|
| 84 |
+
|
| 85 |
|
| 86 |
+
def normalize_label(label: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
return label.strip()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def validate_label(label: str) -> str:
|
| 91 |
+
norm = normalize_label(label)
|
| 92 |
+
if norm not in NORMALIZED_LABEL_MAP:
|
|
|
|
|
|
|
| 93 |
raise HTTPException(
|
| 94 |
status_code=422,
|
| 95 |
+
detail=f"Invalid label '{label}'. Must be one of: {VALID_LABELS_DISPLAY}"
|
|
|
|
|
|
|
|
|
|
| 96 |
)
|
| 97 |
+
return NORMALIZED_LABEL_MAP[norm]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def extract_filename(url: str) -> str:
|
| 101 |
+
return url.split("/")[-1].split("?")[0]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
# βββββββββββββββββ
|
| 105 |
# Request Models
|
| 106 |
# βββββββββββββββββ
|
| 107 |
+
|
| 108 |
class DetectionOperation(BaseModel):
|
| 109 |
action: Literal["add", "update", "delete"]
|
| 110 |
detection_index: Optional[int] = None
|
| 111 |
label: Optional[str] = None
|
| 112 |
+
bbox: Optional[List[float]] = None # [x1, y1, x2, y2]
|
| 113 |
+
|
| 114 |
@validator("label")
|
| 115 |
+
def validate_label_field(cls, v):
|
| 116 |
if v is None:
|
| 117 |
return v
|
| 118 |
+
return validate_label(v)
|
| 119 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
@validator("bbox")
|
| 121 |
+
def validate_bbox(cls, v):
|
| 122 |
if v is None:
|
| 123 |
return v
|
| 124 |
if len(v) != 4:
|
|
|
|
| 127 |
if x2 <= x1 or y2 <= y1:
|
| 128 |
raise ValueError("bbox must satisfy x2 > x1 and y2 > y1")
|
| 129 |
return v
|
| 130 |
+
|
| 131 |
@validator("detection_index")
|
| 132 |
+
def validate_index(cls, v):
|
| 133 |
if v is not None and v < 0:
|
| 134 |
raise ValueError("detection_index must be >= 0")
|
| 135 |
return v
|
| 136 |
+
|
| 137 |
+
|
| 138 |
class MultiUpdateRequest(BaseModel):
|
| 139 |
user_id: str
|
| 140 |
camera_name: str
|
| 141 |
image_url: str
|
| 142 |
operations: List[DetectionOperation]
|
| 143 |
+
|
| 144 |
@validator("operations")
|
| 145 |
+
def validate_operations(cls, ops):
|
| 146 |
+
if not ops:
|
| 147 |
raise ValueError("operations list cannot be empty")
|
| 148 |
+
|
| 149 |
+
for op in ops:
|
| 150 |
+
if op.action == "add":
|
| 151 |
+
if op.label is None or op.bbox is None:
|
| 152 |
+
raise ValueError("'add' requires both label and bbox")
|
| 153 |
+
|
| 154 |
+
elif op.action == "update":
|
| 155 |
+
if op.detection_index is None:
|
| 156 |
+
raise ValueError("'update' requires detection_index")
|
| 157 |
+
if op.label is None and op.bbox is None:
|
| 158 |
+
raise ValueError("'update' requires label or bbox")
|
| 159 |
+
|
| 160 |
+
elif op.action == "delete":
|
| 161 |
+
if op.detection_index is None:
|
| 162 |
+
raise ValueError("'delete' requires detection_index")
|
| 163 |
+
|
| 164 |
+
return ops
|
| 165 |
+
|
| 166 |
+
|
|
|
|
| 167 |
# βββββββββββββββββ
|
| 168 |
# Endpoint
|
| 169 |
# βββββββββββββββββ
|
| 170 |
+
|
| 171 |
@router.post("/modify_detections")
|
| 172 |
async def modify_detections(req: MultiUpdateRequest):
|
| 173 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
validate_user_and_camera(req.user_id, req.camera_name)
|
| 175 |
+
|
| 176 |
+
json_key = _bucket_key(
|
| 177 |
+
req.user_id,
|
| 178 |
+
req.camera_name,
|
| 179 |
+
f"{req.camera_name}_detections.json"
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
if not _key_exists(json_key):
|
| 183 |
raise HTTPException(status_code=404, detail="Detections file not found")
|
| 184 |
+
|
|
|
|
| 185 |
data = load_json(json_key)
|
| 186 |
+
|
| 187 |
+
target_filename = extract_filename(req.image_url)
|
| 188 |
+
|
| 189 |
+
# Find record (optimized)
|
| 190 |
+
record = next(
|
| 191 |
+
(
|
| 192 |
+
item for item in data
|
| 193 |
+
if extract_filename(item.get("image_url", item.get("filename", ""))) == target_filename
|
| 194 |
+
),
|
| 195 |
+
None
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
if record is None:
|
| 199 |
raise HTTPException(status_code=404, detail="Image not found")
|
| 200 |
+
|
| 201 |
+
dets = record.setdefault("detections", [])
|
| 202 |
+
|
| 203 |
+
# ββ Split operations βββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
delete_ops = [op for op in req.operations if op.action == "delete"]
|
| 205 |
+
other_ops = [op for op in req.operations if op.action != "delete"]
|
| 206 |
+
|
| 207 |
+
# ββ DELETE (reverse order) βββββββββββ
|
| 208 |
+
for op in sorted(delete_ops, key=lambda x: x.detection_index, reverse=True):
|
| 209 |
+
idx = op.detection_index
|
| 210 |
+
if idx is None or idx >= len(dets):
|
| 211 |
raise HTTPException(
|
| 212 |
status_code=400,
|
| 213 |
+
detail=f"Invalid delete index {idx} β only {len(dets)} detection(s) exist"
|
| 214 |
)
|
| 215 |
+
dets.pop(idx)
|
| 216 |
+
|
| 217 |
+
# ββ ADD + UPDATE ββββββββββββββββββββ
|
| 218 |
for op in other_ops:
|
| 219 |
+
|
| 220 |
if op.action == "add":
|
| 221 |
dets.append({
|
| 222 |
+
"label": op.label,
|
| 223 |
+
"confidence": 1.0,
|
| 224 |
+
"bbox": op.bbox,
|
| 225 |
"manually_edited": True
|
| 226 |
})
|
| 227 |
+
|
| 228 |
elif op.action == "update":
|
| 229 |
+
idx = op.detection_index
|
| 230 |
+
if idx is None or idx >= len(dets):
|
| 231 |
raise HTTPException(
|
| 232 |
status_code=400,
|
| 233 |
+
detail=f"Invalid update index {idx} β only {len(dets)} detection(s) exist"
|
| 234 |
)
|
| 235 |
+
|
| 236 |
if op.label is not None:
|
| 237 |
+
dets[idx]["label"] = op.label
|
| 238 |
+
|
| 239 |
if op.bbox is not None:
|
| 240 |
+
dets[idx]["bbox"] = op.bbox
|
| 241 |
+
|
| 242 |
+
dets[idx]["manually_edited"] = True
|
| 243 |
+
|
| 244 |
save_json(json_key, data)
|
| 245 |
+
|
| 246 |
logger.info(
|
| 247 |
"Detections modified | user=%s camera=%s file=%s ops=%d final_count=%d",
|
| 248 |
req.user_id,
|
|
|
|
| 251 |
len(req.operations),
|
| 252 |
len(dets)
|
| 253 |
)
|
| 254 |
+
|
| 255 |
return {
|
| 256 |
+
"success": True,
|
| 257 |
+
"message": "Detections modified successfully",
|
| 258 |
+
"filename": target_filename,
|
| 259 |
"total_detections": len(dets),
|
| 260 |
+
"detections": dets
|
| 261 |
+
}
|
|
|