JameZMw commited on
Commit
047ac63
·
1 Parent(s): 8b1ac13

Add chess API files

Browse files
Files changed (6) hide show
  1. .dockerignore +8 -0
  2. Dockerfile +23 -0
  3. best.pt +3 -0
  4. main.py +68 -0
  5. model.py +54 -0
  6. requirements.txt +6 -0
.dockerignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ .git
3
+ .env
4
+ .vscode
5
+ *.pyc
6
+ node_modules
7
+ .DS_Store
8
+ runs/
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install system dependencies first (faster)
6
+ RUN apt-get update && apt-get install -y \
7
+ libsm6 libxext6 libxrender-dev \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ # Copy requirements first (Docker caches this layer)
11
+ COPY requirements.txt .
12
+
13
+ # Install Python packages with timeout
14
+ RUN pip install --no-cache-dir --default-timeout=1000 -r requirements.txt
15
+
16
+ # Copy code after (doesn't invalidate pip cache)
17
+ COPY main.py .
18
+ COPY model.py .
19
+ COPY best.pt .
20
+
21
+ EXPOSE 8000
22
+
23
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
best.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:561bc2f8f97037802476a90929984feed67719aebfd1fc3345ca3e3f73b6f2f0
3
+ size 6600915
main.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File, HTTPException
2
+ from fastapi.responses import StreamingResponse
3
+ import os
4
+ from io import BytesIO
5
+ import cv2
6
+
7
+ from model import load_model, predict_board
8
+
9
+ app = FastAPI()
10
+
11
+ MODEL_PATH = os.getenv("MODEL_PATH", "best.pt")
12
+ ALLOWED_TYPES = {"image/jpeg", "image/png", "image/jpg"}
13
+ MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MB
14
+
15
+ # Load model once at startup
16
+ try:
17
+ model = load_model(MODEL_PATH)
18
+ except Exception as e:
19
+ print(f"Warning: Could not load model at startup: {e}")
20
+ model = None
21
+
22
+
23
+ @app.get('/')
24
+ def health_check():
25
+ return {"message": "Chess board analyzer is running!"}
26
+
27
+
28
+ @app.post(
29
+ "/predict/image",
30
+ summary="Upload chessboard → annotated image with all pieces highlighted",
31
+ responses={
32
+ 200: {"content": {"image/png": {}}, "description": "Annotated PNG with pieces highlighted"},
33
+ 400: {"description": "Bad request (wrong file type, too large, invalid position)"},
34
+ 500: {"description": "Server / model error"},
35
+ },
36
+ )
37
+ async def predict_image(file: UploadFile = File(..., description="Chessboard Picture (JPG or PNG)")):
38
+ # 1. Validate type
39
+ if file.content_type not in ALLOWED_TYPES:
40
+ raise HTTPException(
41
+ status_code=400,
42
+ detail=f"Invalid file type '{file.content_type}'. Only JPG and PNG are accepted."
43
+ )
44
+
45
+ # 2. Read bytes
46
+ image_bytes = await file.read()
47
+
48
+ # 3. Validate size
49
+ if len(image_bytes) > MAX_FILE_SIZE:
50
+ raise HTTPException(status_code=400, detail="File too large. Maximum is 10 MB.")
51
+
52
+ # 4. Check model is loaded
53
+ if model is None:
54
+ raise HTTPException(status_code=500, detail="Model failed to load at startup.")
55
+
56
+ try:
57
+ result = predict_board(model, image_bytes) # ← Pass the MODEL object, not path
58
+
59
+ except ValueError as e:
60
+ raise HTTPException(status_code=400, detail=str(e))
61
+ except Exception as e:
62
+ raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")
63
+
64
+ # 5. Return the annotated image as PNG
65
+ return StreamingResponse(
66
+ BytesIO(result["image_bytes"]),
67
+ media_type="image/png"
68
+ )
model.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+ import base64
4
+ from ultralytics import YOLO
5
+
6
+
7
+ def load_model(model_path: str):
8
+ """Load YOLOv8 model from path."""
9
+ model = YOLO(model_path)
10
+ return model
11
+
12
+
13
+ def preprocess_image(image_bytes: bytes) -> np.ndarray:
14
+ """Convert bytes to OpenCV image array."""
15
+ nparr = np.frombuffer(image_bytes, np.uint8)
16
+ img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
17
+
18
+ if img is None:
19
+ raise ValueError("Could not decode image. Make sure it is a valid JPG or PNG.")
20
+
21
+ return img
22
+
23
+
24
+ def predict_board(model, image_bytes: bytes) -> dict:
25
+ """Run inference on image bytes and return annotated result."""
26
+ img = preprocess_image(image_bytes)
27
+
28
+ # Run inference
29
+ results = model(img, conf=0.1)
30
+
31
+ if not results or len(results) == 0:
32
+ raise ValueError("Model returned no results.")
33
+
34
+ result = results[0]
35
+
36
+ # OBB model uses .obb instead of .boxes
37
+ if result.obb is None or len(result.obb) == 0:
38
+ raise ValueError("No detections found in image.")
39
+
40
+ # Get detections from OBB
41
+ detections = result.obb.data.tolist()
42
+
43
+ # Plot still works the same
44
+ drawn_image = result.plot()
45
+
46
+ success, buffer = cv2.imencode(".png", drawn_image)
47
+ if not success:
48
+ raise RuntimeError("Failed to encode result image.")
49
+
50
+ return {
51
+ "image_bytes": buffer.tobytes(),
52
+ "image_base64": base64.b64encode(buffer).decode("utf-8"),
53
+ "detections": detections,
54
+ }
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi==0.104.1
2
+ uvicorn[standard]==0.24.0
3
+ ultralytics==8.0.200
4
+ opencv-python-headless==4.8.1.78
5
+ Pillow==10.0.1
6
+ python-multipart==0.0.6