CJR61 Claude Sonnet 4.6 commited on
Commit
10412fe
·
1 Parent(s): dead143

Fix 5 bugs in upload validation, inference, and file cleanup

Browse files

- Bug1: Replace second-precision timestamp with uuid suffix to prevent
filename collision under concurrent requests
- Bug2: Add file extension whitelist in save_uploaded_file; raise
ValueError for unsupported types before writing to disk
- Bug3: Remove misleading comment claiming SIM_THRES default is 0.75
- Bug4: Explicitly check model output keys and raise KeyError instead
of silently falling back to positional indices
- Bug5: Call os.remove(saved_path) in preprocessing failure path to
prevent orphaned files accumulating in uploads/

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (3) hide show
  1. app/main.py +7 -3
  2. app/model.py +7 -4
  3. app/utils.py +11 -3
app/main.py CHANGED
@@ -58,7 +58,10 @@ async def read_root():
58
  @app.post("/predict/")
59
  async def predict(file: UploadFile = File(...)):
60
  # Save uploaded image and generate ID
61
- saved_path, image_id = save_uploaded_file(app.state.uploads_dir, file)
 
 
 
62
  logger.info(f"Image saved: {saved_path}, ID: {image_id}")
63
 
64
  # Check if the image is valid
@@ -72,13 +75,14 @@ async def predict(file: UploadFile = File(...)):
72
  preprocessed_image = preprocess_image(saved_path)
73
  except Exception as e:
74
  logger.error(f"Image preprocessing failed - ID: {image_id}, Error: {str(e)}")
 
75
  return {"error": f"Image preprocessing failed: {str(e)}"}
76
 
77
  # Inference
78
  try:
79
  model = app.state.model
80
- ref_emb = app.state.ref_emb # <- lifespan 裡放好的參考 embedding
81
- thres = app.state.sim_thres # <- lifespan 裡放好的門檻 (預設 0.75)
82
 
83
  # 新版 predict_image:回傳 (is_in_criteria: bool, prob: float, sim: float)
84
  is_in_criteria, probability, sim = predict_image(model, preprocessed_image, ref_emb, thres=thres)
 
58
  @app.post("/predict/")
59
  async def predict(file: UploadFile = File(...)):
60
  # Save uploaded image and generate ID
61
+ try:
62
+ saved_path, image_id = save_uploaded_file(app.state.uploads_dir, file)
63
+ except ValueError as e:
64
+ return {"error": str(e)}
65
  logger.info(f"Image saved: {saved_path}, ID: {image_id}")
66
 
67
  # Check if the image is valid
 
75
  preprocessed_image = preprocess_image(saved_path)
76
  except Exception as e:
77
  logger.error(f"Image preprocessing failed - ID: {image_id}, Error: {str(e)}")
78
+ os.remove(saved_path)
79
  return {"error": f"Image preprocessing failed: {str(e)}"}
80
 
81
  # Inference
82
  try:
83
  model = app.state.model
84
+ ref_emb = app.state.ref_emb
85
+ thres = app.state.sim_thres
86
 
87
  # 新版 predict_image:回傳 (is_in_criteria: bool, prob: float, sim: float)
88
  is_in_criteria, probability, sim = predict_image(model, preprocessed_image, ref_emb, thres=thres)
app/model.py CHANGED
@@ -16,10 +16,13 @@ def predict_image(model, image, ref_emb, thres=0.75):
16
  out_map = {o.name: i for i, o in enumerate(model.get_outputs())} # e.g. {'embedding':0,'probability':1}
17
 
18
  outs = model.run(None, {inp: image})
19
-
20
- # 盡量用名稱抓;若名稱不同則回落到索引 0/1
21
- emb = outs[out_map.get("embedding", 0)].squeeze()
22
- prob = float(outs[out_map.get("probability", 1)].squeeze())
 
 
 
23
 
24
  # 相似度 + 門檻判斷
25
  sim = cosine_similarity(emb, ref_emb)
 
16
  out_map = {o.name: i for i, o in enumerate(model.get_outputs())} # e.g. {'embedding':0,'probability':1}
17
 
18
  outs = model.run(None, {inp: image})
19
+
20
+ missing = [k for k in ("embedding", "probability") if k not in out_map]
21
+ if missing:
22
+ raise KeyError(f"Model output missing expected keys: {missing}. Found: {list(out_map.keys())}")
23
+
24
+ emb = outs[out_map["embedding"]].squeeze()
25
+ prob = float(outs[out_map["probability"]].squeeze())
26
 
27
  # 相似度 + 門檻判斷
28
  sim = cosine_similarity(emb, ref_emb)
app/utils.py CHANGED
@@ -2,13 +2,21 @@ import cv2
2
  import numpy as np
3
  import os
4
  import csv
 
5
  from datetime import datetime
6
 
 
 
7
  def save_uploaded_file(save_dir, file):
8
- # Generate date-related ID
9
- image_id = datetime.now().strftime("%Y%m%d_%H%M%S")
 
 
 
 
 
10
  saved_path = os.path.join(save_dir, f"{image_id}.jpg")
11
-
12
  # Save file
13
  with open(saved_path, "wb") as f:
14
  f.write(file.file.read())
 
2
  import numpy as np
3
  import os
4
  import csv
5
+ import uuid
6
  from datetime import datetime
7
 
8
+ ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif"}
9
+
10
  def save_uploaded_file(save_dir, file):
11
+ # Validate file extension
12
+ _, ext = os.path.splitext(file.filename or "")
13
+ if ext.lower() not in ALLOWED_EXTENSIONS:
14
+ raise ValueError(f"Unsupported file type '{ext}'. Allowed: {ALLOWED_EXTENSIONS}")
15
+
16
+ # Generate unique ID (date prefix + uuid4) to avoid race condition
17
+ image_id = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:8]
18
  saved_path = os.path.join(save_dir, f"{image_id}.jpg")
19
+
20
  # Save file
21
  with open(saved_path, "wb") as f:
22
  f.write(file.file.read())