Download app.py from tetedd2/HelmetAI: direct link, hf CLI and curl.
- Browser
- Download file 1.05 kB
-
https://huggingface.co/spaces/tetedd2/HelmetAI/resolve/main/app.py
- Command line
-
hf download hf://spaces/tetedd2/HelmetAI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/tetedd2/HelmetAI/resolve/main/app.py
1.05 kB
| from fastapi import FastAPI, File, UploadFile | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import uvicorn | |
| import cv2 | |
| import numpy as np | |
| from ultralytics import YOLO | |
| app = FastAPI() | |
| # Allow CORS for GitHub Pages | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| model = YOLO("helmet.pt") | |
| async def predict(file: UploadFile = File(...)): | |
| image_bytes = await file.read() | |
| np_img = np.frombuffer(image_bytes, np.uint8) | |
| img = cv2.imdecode(np_img, cv2.IMREAD_COLOR) | |
| results = model(img)[0] | |
| detections = [] | |
| for box in results.boxes: | |
| cls = int(box.cls[0]) | |
| conf = float(box.conf[0]) | |
| label = model.names[cls] | |
| detections.append({ | |
| "label": label, | |
| "confidence": round(conf, 3) | |
| }) | |
| return { | |
| "count": len(detections), | |
| "detections": detections | |
| } | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |