LiamKhoaLe commited on
Commit
1bd6599
·
1 Parent(s): 142c453

Upd FastAPI backend img processing garbage det and cls + frontend JS side rendering

Browse files
Files changed (3) hide show
  1. app.py +53 -0
  2. statics/index.html +1 -1
  3. statics/script.js +24 -0
app.py CHANGED
@@ -40,6 +40,7 @@ os.environ["HF_HOME"] = CACHE
40
 
41
  # ── Load models once ───────────────────────────────────────────────────
42
  print("🔄 Loading models …")
 
43
  model_self = YOLO(f"{MODEL_DIR}/garbage_detector.pt") # YOLOv11(l)
44
  model_yolo5 = yolov5.load(f"{MODEL_DIR}/yolov5-detect-trash-classification.pt")
45
  processor_detr = DetrImageProcessor.from_pretrained(f"{MODEL_DIR}/detr")
@@ -48,7 +49,10 @@ feat_extractor = SegformerFeatureExtractor.from_pretrained(
48
  "nvidia/segformer-b4-finetuned-ade-512-512")
49
  segformer = SegformerForSemanticSegmentation.from_pretrained(
50
  "nvidia/segformer-b4-finetuned-ade-512-512")
 
51
  model_animal = YOLO(f"{MODEL_DIR}/yolov8n.pt") # Load COCO pre-trained YOLOv8 for animal detection
 
 
52
  print("✅ Models ready\n")
53
 
54
  # ── ADE-20K palette + custom mapping (verbatim) ─────────────────────────
@@ -413,6 +417,55 @@ async def detect_animals(file: UploadFile = File(...)):
413
  return FileResponse(result_path, media_type="image/jpeg")
414
 
415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416
  # ── Core pipeline (runs in background thread) ───────────────────────────
417
  def _pipeline(uid,img_path):
418
  print(f"▶️ [{uid}] processing")
 
40
 
41
  # ── Load models once ───────────────────────────────────────────────────
42
  print("🔄 Loading models …")
43
+ # Garbage detection
44
  model_self = YOLO(f"{MODEL_DIR}/garbage_detector.pt") # YOLOv11(l)
45
  model_yolo5 = yolov5.load(f"{MODEL_DIR}/yolov5-detect-trash-classification.pt")
46
  processor_detr = DetrImageProcessor.from_pretrained(f"{MODEL_DIR}/detr")
 
49
  "nvidia/segformer-b4-finetuned-ade-512-512")
50
  segformer = SegformerForSemanticSegmentation.from_pretrained(
51
  "nvidia/segformer-b4-finetuned-ade-512-512")
52
+ # Animal detection
53
  model_animal = YOLO(f"{MODEL_DIR}/yolov8n.pt") # Load COCO pre-trained YOLOv8 for animal detection
54
+ # Garbage classification
55
+ model_garbage_cls = YOLO(f"{MODEL_DIR}/garbage_cls_yolov8s.pt")
56
  print("✅ Models ready\n")
57
 
58
  # ── ADE-20K palette + custom mapping (verbatim) ─────────────────────────
 
417
  return FileResponse(result_path, media_type="image/jpeg")
418
 
419
 
420
+ # Garbage classification endpoint
421
+ @app.post("/classification/")
422
+ async def classify_garbage(file: UploadFile = File(...)):
423
+ img_id = _uid()
424
+ img_path = f"{UPLOAD_DIR}/{img_id}_{file.filename}"
425
+ out_path = f"{OUTPUT_DIR}/{img_id}_classified.jpg"
426
+ # Load file
427
+ with open(img_path, "wb") as f:
428
+ shutil.copyfileobj(file.file, f)
429
+ # Read image
430
+ print(f"[Classification] Received image: {img_path}")
431
+ image = cv2.imread(img_path)
432
+ rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
433
+ pil = Image.fromarray(rgb)
434
+ # DETR for garbage detection boxes
435
+ detections = []
436
+ inp = processor_detr(images=pil, return_tensors="pt")
437
+ with torch.no_grad():
438
+ out = model_detr(**inp)
439
+ results = processor_detr.post_process_object_detection(
440
+ outputs=out,
441
+ target_sizes=torch.tensor([pil.size[::-1]]),
442
+ threshold=0.5
443
+ )[0]
444
+ # Bbox return
445
+ boxes = results["boxes"]
446
+ print(f"[Classification] {len(boxes)} garbage objects detected by DETR.")
447
+ # Mapping in between
448
+ for i, box in enumerate(boxes):
449
+ x1, y1, x2, y2 = map(int, box.tolist())
450
+ crop = image[y1:y2, x1:x2]
451
+ if crop.shape[0] < 10 or crop.shape[1] < 10:
452
+ continue # skip tiny crops
453
+ # Convert crop to RGB and classify
454
+ pil_crop = Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB))
455
+ pred = model_garbage_cls(pil_crop, verbose=False)[0]
456
+ class_id = int(pred.probs.top1)
457
+ class_name = model_garbage_cls.names[class_id]
458
+ conf = pred.probs.top1conf
459
+ # Labelling on output image
460
+ label = f"{class_name} ({conf:.2f})"
461
+ cv2.rectangle(image, (x1, y1), (x2, y2), (0, 165, 255), 2)
462
+ cv2.putText(image, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 165, 255), 2)
463
+ # Write image on render
464
+ cv2.imwrite(out_path, image)
465
+ print(f"[Classification] Output saved: {out_path}")
466
+ return FileResponse(out_path, media_type="image/jpeg")
467
+
468
+
469
  # ── Core pipeline (runs in background thread) ───────────────────────────
470
  def _pipeline(uid,img_path):
471
  print(f"▶️ [{uid}] processing")
statics/index.html CHANGED
@@ -24,7 +24,7 @@
24
  <div id="animal-result"></div>
25
  <div id="upload-container3">
26
  <input type="file" id="upload3" accept="image/*">
27
- <button id="checkTrashBtn" onclick="uploadAnimal()">Check Animal</button>
28
  </div>
29
  <div id="trash-result"></div>
30
  <script src="/statics/script.js"></script>
 
24
  <div id="animal-result"></div>
25
  <div id="upload-container3">
26
  <input type="file" id="upload3" accept="image/*">
27
+ <button id="checkTrashBtn" onclick="uploadTrash()">Classify Garbage</button>
28
  </div>
29
  <div id="trash-result"></div>
30
  <script src="/statics/script.js"></script>
statics/script.js CHANGED
@@ -62,5 +62,29 @@ async function uploadAnimal() {
62
  const imgURL = URL.createObjectURL(blob);
63
  document.getElementById("animal-result").innerHTML =
64
  `<p><b>Animal Detection Result:</b></p><img src="${imgURL}" width="640"/>`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  }
 
66
 
 
62
  const imgURL = URL.createObjectURL(blob);
63
  document.getElementById("animal-result").innerHTML =
64
  `<p><b>Animal Detection Result:</b></p><img src="${imgURL}" width="640"/>`;
65
+ }
66
+
67
+ async function uploadTrash() {
68
+ const fileInput = document.getElementById('upload3');
69
+ if (!fileInput.files.length) return alert("Upload an image first");
70
+ // Upload and read image file
71
+ const formData = new FormData();
72
+ formData.append("file", fileInput.files[0]);
73
+ // Handshake with FastAPI
74
+ const res = await fetch("/classification/", {
75
+ method: "POST",
76
+ body: formData
77
+ });
78
+ // Error
79
+ if (!res.ok) {
80
+ alert("Failed to process garbage classification.");
81
+ return;
82
+ }
83
+ // Create image
84
+ const blob = await res.blob();
85
+ const imgURL = URL.createObjectURL(blob);
86
+ document.getElementById("trash-result").innerHTML =
87
+ `<p><b>Garbage Classification Result:</b></p><img src="${imgURL}" width="640"/>`;
88
  }
89
+
90