Rahaf2001 commited on
Commit
bc84e9e
·
verified ·
1 Parent(s): 07f568d

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +68 -0
main.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from ultralytics import YOLO
4
+ from PIL import Image
5
+ import io, requests, os
6
+
7
+ app = FastAPI()
8
+
9
+ app.add_middleware(
10
+ CORSMiddleware,
11
+ allow_origins=["*"],
12
+ allow_methods=["*"],
13
+ allow_headers=["*"],
14
+ )
15
+
16
+ MODEL_URL = "https://huggingface.co/Rahaf2001/sabiq-road-detection/resolve/main/best.pt"
17
+
18
+ def download_model():
19
+ if not os.path.exists("best.pt"):
20
+ print("Downloading model...")
21
+ r = requests.get(MODEL_URL)
22
+ with open("best.pt", "wb") as f:
23
+ f.write(r.content)
24
+ print(" Model ready")
25
+
26
+ download_model()
27
+ model = YOLO("best.pt")
28
+
29
+ CLASS_NAMES = {0:'crack', 1:'pothole', 2:'other'}
30
+
31
+ def get_severity(conf, area):
32
+ if conf > 0.85 and area > 0.05: return 'high'
33
+ elif conf > 0.65: return 'medium'
34
+ else: return 'low'
35
+
36
+ @app.get("/")
37
+ def root():
38
+ return {"status": "SABIQ API running "}
39
+
40
+ @app.post("/detect")
41
+ async def detect(file: UploadFile = File(...)):
42
+ img = Image.open(io.BytesIO(await file.read()))
43
+ results = model(img)
44
+ detections = []
45
+ for box in results[0].boxes:
46
+ cls = int(box.cls)
47
+ conf = float(box.conf)
48
+ xywhn = box.xywhn[0].tolist()
49
+ area = xywhn[2] * xywhn[3]
50
+ detections.append({
51
+ "damage_type": CLASS_NAMES.get(cls, 'other'),
52
+ "confidence" : round(conf, 3),
53
+ "severity" : get_severity(conf, area),
54
+ "bbox" : xywhn
55
+ })
56
+ return {"total": len(detections), "detections": detections}
57
+ ```
58
+
59
+ ---
60
+
61
+ **`requirements.txt`**
62
+ ```
63
+ fastapi
64
+ uvicorn
65
+ ultralytics
66
+ pillow
67
+ requests
68
+ python-multipart