suyash-77 commited on
Commit
13d47a7
·
1 Parent(s): 23647dc

Add YOLOv8 FastAPI application

Browse files
Files changed (3) hide show
  1. Dockerfile +24 -0
  2. app.py +56 -0
  3. requirements.txt +6 -0
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ # Install system dependencies as root for OpenCV support
4
+ USER root
5
+ RUN apt-get update && apt-get install -y \
6
+ libgl1-mesa-glx \
7
+ libglib2.0-0 \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ # Set up a new user named "user" with UID 1000 to comply with Hugging Face security
11
+ RUN useradd -m -u 1000 user
12
+ USER user
13
+ ENV PATH="/home/user/.local/bin:$PATH"
14
+
15
+ WORKDIR /app
16
+
17
+ # Copy dependencies first to leverage caching
18
+ COPY --chown=user ./requirements.txt requirements.txt
19
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
20
+
21
+ # Copy application files
22
+ COPY --chown=user . /app
23
+
24
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ import cv2
5
+ import numpy as np
6
+ import base64
7
+ from ultralytics import YOLO
8
+
9
+ app = FastAPI()
10
+
11
+ # Enable CORS so your React frontend/Node backend can query this Space
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"],
15
+ allow_credentials=True,
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
20
+ # Load lightweight YOLOv8 Nano model (pretrained on COCO dataset)
21
+ model = YOLO("yolov8n.pt")
22
+
23
+ class ImagePayload(BaseModel):
24
+ image: str
25
+
26
+ @app.get("/")
27
+ def home():
28
+ return {"status": "YOLOv8 Active", "model": "yolov8n"}
29
+
30
+ @app.post("/predict")
31
+ def predict(payload: ImagePayload):
32
+ try:
33
+ # Decode base64 image
34
+ encoded_data = payload.image.split(',')[1] if ',' in payload.image else payload.image
35
+ nparr = np.frombuffer(base64.b64decode(encoded_data), np.uint8)
36
+ img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
37
+
38
+ if img is None:
39
+ return {"phoneDetected": False, "error": "Invalid image data"}
40
+
41
+ # Run inference
42
+ results = model(img)
43
+ phone_detected = False
44
+
45
+ for r in results:
46
+ for box in r.boxes:
47
+ class_id = int(box.cls[0])
48
+ label = model.names[class_id]
49
+ # Label 'cell phone' or 'laptop' or 'remote' in COCO dataset
50
+ if label in ['cell phone', 'laptop', 'remote']:
51
+ phone_detected = True
52
+ break
53
+
54
+ return {"phoneDetected": phone_detected}
55
+ except Exception as e:
56
+ return {"phoneDetected": False, "error": str(e)}
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ ultralytics
4
+ opencv-python-headless
5
+ pydantic
6
+ numpy