Spaces:
Sleeping
Sleeping
main edited (#6)
Browse files- main edited (c71b5af9e9634369ca59def8d57c3c15fffb7a81)
Co-authored-by: 13774haf moh <iahad1@users.noreply.huggingface.co>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788from fastapi import FastAPI, UploadFile, Filefrom fastapi.middleware.cors import CORSMiddlewarefrom ultralytics import YOLOimport os, tempfileapp = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_methods=["*"],allow_headers=["*"],)#tesssssssst# هذا لو كنت ابغى يعتمد على مودل موجود بالهقنق فيس# MODEL_URL = "https://huggingface.co/Rahaf2001/sabiq-road-detection/resolve/main/best.pt"# def download_model():# if not os.path.exists("best.pt"):# print("Downloading model...")# r = requests.get(MODEL_URL)# with open("best.pt", "wb") as f:# f.write(r.content)# print(" Model ready")print("Loading model...")model = YOLO("best.pt")print("Model ready")CLASS_NAMES = {0: 'crack',1: 'other',2: 'pothole'}def get_severity(conf, area):if conf > 0.85 and area > 0.05:return 'high'elif conf > 0.65:return 'medium'else:return 'low'@app.get("/")def root():return {"status": "SABIQ API running"}@app.post("/detect")async def detect(file: UploadFile = File(...)):contents = await file.read()suffix = '.' + file.filename.split('.')[-1]with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:tmp.write(contents)tmp_path = tmp.nameresults = model.predict(source = tmp_path,conf = 0.25,verbose = False,stream = True)all_detections = []frame_num = 0for result in results:for box in result.boxes:cls = int(box.cls)conf = float(box.conf)xywhn = box.xywhn[0].tolist()area = xywhn[2] * xywhn[3]all_detections.append({"damage_type": CLASS_NAMES.get(cls, 'other'),"confidence" : round(conf, 3),"severity" : get_severity(conf, area),"bbox" : xywhn,"frame" : frame_num})frame_num += 1os.unlink(tmp_path)return {"total" : len(all_detections),"detections": all_detections}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107from fastapi import FastAPI, UploadFile, Filefrom fastapi.middleware.cors import CORSMiddlewarefrom ultralytics import YOLOimport os, tempfile, randomapp = FastAPI()app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])print("Loading model...")model = YOLO("best.pt")print("Model ready")CLASS_NAMES = {0: "crack", 1: "other", 2: "pothole"}RIYADH_LAT = (24.55, 24.85)RIYADH_LNG = (46.55, 46.85)def random_riyadh():return round(random.uniform(*RIYADH_LAT), 6), round(random.uniform(*RIYADH_LNG), 6)def severity(conf, area):if conf > 0.85 and area > 0.05:return "high"elif conf > 0.65:return "medium"return "low"def is_image(name):return name.lower().rsplit(".", 1)[-1] in ("jpg", "jpeg", "png", "bmp", "webp")def process_image(path):results = model.predict(source=path, conf=0.25, verbose=False)out = []for r in results:for box in r.boxes:cls = int(box.cls)conf = float(box.conf)xywhn = box.xywhn[0].tolist()lat, lng = random_riyadh()out.append({"damage_type": CLASS_NAMES.get(cls, "other"),"confidence": round(conf, 3),"severity": severity(conf, xywhn[2] * xywhn[3]),"bbox": xywhn,"frame": 0,"latitude": lat,"longitude": lng,})return outdef process_video(path):results = model.track(source=path, conf=0.25, tracker="bytetrack.yaml",stream=True, verbose=False, save=True,)seen = {} # track_id -> best detectionfor frame_idx, r in enumerate(results):if r.boxes is None or r.boxes.id is None:continuefor tid, cls, conf, xywhn in zip(r.boxes.id.int().tolist(),r.boxes.cls.int().tolist(),r.boxes.conf.tolist(),r.boxes.xywhn.tolist(),):if tid not in seen or conf > seen[tid]["confidence"]:lat, lng = random_riyadh() if tid not in seen else (seen[tid]["latitude"], seen[tid]["longitude"])seen[tid] = {"damage_type": CLASS_NAMES.get(cls, "other"),"confidence": round(conf, 3),"severity": severity(conf, xywhn[2] * xywhn[3]),"bbox": xywhn,"frame": frame_idx,"latitude": lat,"longitude": lng,}return list(seen.values())@app.get("/")def root():return {"status": "SABIQ API running"}@app.post("/detect")async def detect(file: UploadFile = File(...)):contents = await file.read()suffix = "." + file.filename.split(".")[-1]with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:tmp.write(contents)tmp_path = tmp.nametry:detections = process_image(tmp_path) if is_image(file.filename) else process_video(tmp_path)finally:os.unlink(tmp_path)return {"total": len(detections), "detections": detections}
main.py+80-61