Spaces:
Sleeping
Sleeping
feat: init fastapi
Browse filesFiles changed (4)
- app.pyAdded+47
- best.ptAdded+3
- dockerfileAdded+12
- requirements.txtAdded+7
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647from fastapi import FastAPI, UploadFile, statusfrom fastapi.responses import StreamingResponse, JSONResponsefrom ultralytics import YOLOimport cv2import numpy as npfrom io import BytesIOfrom fastapi.middleware.cors import CORSMiddlewareapp = FastAPI()
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["POST"], allow_headers=["content-type", "accept"],)
model = YOLO("best.pt")
@app.post("/inference")async def inference(file: UploadFile): if file.content_type != "image/jpeg" and file.content_type != "image/png" and file.content_type != "image/jpg": return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={"error": "Invalid file format"} ) image_bytes = await file.read() img = np.frombuffer(image_bytes, dtype=np.uint8) img = cv2.imdecode(img, cv2.IMREAD_COLOR) results = model.predict(source=img, conf=0.5) for r in results: boxes = r.boxes for box in boxes: x1, y1, x2, y2 = box.xyxy[0] x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 255), 2)
label = box.cls[0].item() label_name = model.names[label] (text_width, text_height), baseline = cv2.getTextSize(label_name, cv2.FONT_HERSHEY_SIMPLEX, 0.9, 2) cv2.rectangle(img, (x1, y1 - text_height - baseline - 5), (x1 + text_width, y1), (255, 0, 255), -1) cv2.putText(img, label_name, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 0), 2) resp_img_bytes = cv2.imencode('.jpg', img)[1].tobytes() resp_filename = f"inferenced_{file.filename}" if file.filename else "inferenced_image.jpg" return StreamingResponse(BytesIO(resp_img_bytes), media_type="image/jpg", headers={"Content-Disposition": f"attachment; filename={resp_filename}"})123version https://git-lfs.github.com/spec/v1oid sha256:9e3e7ca8fa30f286ae485a1b568de3c68d71ea3113b54fb20caecdd9e42377basize 22504803123456789101112FROM python:3.10-slim
RUN useradd -m -u 1000 userUSER userENV PATH="/home/user/.local/bin:$PATH"
WORKDIR /app
COPY --chown=user . .RUN pip install --no-cache-dir -r requirements.txt
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]1234567fastapi==0.116.1numpy==2.2.6opencv-python==4.12.0.88python-multipart==0.0.20ultralytics==8.3.193ultralytics-thop==2.0.17uvicorn==0.35.0app.pyAdded+47
best.ptAdded+3
dockerfileAdded+12
requirements.txtAdded+7