Spaces:
Sleeping

File size: 2,745 Bytes
d04eeeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
from ultralytics import YOLO
from PIL import Image, ImageDraw
import io
import base64
import os
import requests

MODEL_URL = "https://huggingface.co/yaseen113/microplastic-model/resolve/main/last.pt"
MODEL_PATH = "last.pt"

app = Flask(__name__, static_folder="static", template_folder="templates")
CORS(app)

# Download model first
if not os.path.exists(MODEL_PATH):
    print("Downloading model...")
    r = requests.get(MODEL_URL)
    with open(MODEL_PATH, "wb") as f:
        f.write(r.content)

print("Loading model...")
model = YOLO(MODEL_PATH)
print("Model loaded")

@app.route("/")
def index():
    return send_from_directory("templates", "index.html")

@app.route("/detect", methods=["POST"])
def detect():
    if "image" not in request.files:
        return jsonify({"error": "No image uploaded"}), 400

    file = request.files["image"]
    img_bytes = file.read()
    image = Image.open(io.BytesIO(img_bytes)).convert("RGB")

  
    results = model(image, conf=0.25)
    result = results[0]

    detections = []
    annotated_image = image.copy()
    draw = ImageDraw.Draw(annotated_image)

    boxes = result.boxes
    if boxes is not None and len(boxes) > 0:
        for box in boxes:
            x1, y1, x2, y2 = box.xyxy[0].tolist()
            conf = float(box.conf[0])
            cls_id = int(box.cls[0])
            label = model.names[cls_id]

           
            draw.rectangle([x1, y1, x2, y2], outline="#00FFCC", width=3)
            
          
            text = f"{label} {conf:.0%}"
            text_bbox = draw.textbbox((x1, y1 - 22), text)
            draw.rectangle(text_bbox, fill="#00FFCC")
            draw.text((x1, y1 - 22), text, fill="#000000")

            detections.append({
                "label": label,
                "confidence": round(conf, 4),
                "bbox": [round(x1), round(y1), round(x2), round(y2)],
                "width_px": round(x2 - x1),
                "height_px": round(y2 - y1),
            })

   
    buf = io.BytesIO()
    annotated_image.save(buf, format="PNG")
    encoded = base64.b64encode(buf.getvalue()).decode("utf-8")

    total = len(detections)
    avg_conf = round(sum(d["confidence"] for d in detections) / total, 4) if total else 0

    return jsonify({
        "total_detections": total,
        "average_confidence": avg_conf,
        "detections": detections,
        "annotated_image": f"data:image/png;base64,{encoded}",
        "image_size": {"width": image.width, "height": image.height},
    })

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)