Clean YOLO API deployment without any tokens
Browse filesFiles changed (9)
- .gitignoreAdded+51
- DEPLOYMENT_GUIDE.mdAdded+147
- DockerfileAdded+54
- app.pyAdded+469
- raspberry_pi_client_example.pyAdded+374
- requirements.txtAdded+13
- test_api.pyAdded+151
- utils/image_processing.pyAdded+149
- utils/yolo_detector.pyAdded+185
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Python__pycache__/*.py[cod]*$py.class*.so.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/*.egg-info/.installed.cfg*.egg
# Virtual Environmentvenv/env/ENV/
# IDE.idea/.vscode/*.swp*.swo
# Logs*.loglogs/
# Local development.env.env.local
# Model files (these should be uploaded separately)# models/*.pt
# OS specific.DS_StoreThumbs.db
# Temporary files*.tmp*.bak123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147# Deployment Guide for HuggingFace Spaces
This guide provides step-by-step instructions for deploying the YOLO Detection API to HuggingFace Spaces.
## Prerequisites
- HuggingFace account- Git installed on your local machine- The three YOLO model files: - grape.pt - stem.pt - orange.pt
## Step 1: Clone the HuggingFace Space Repository
```bash# Clone the repositorygit clone https://huggingface.co/spaces/Kesherat/CK1cd CK1```
## Step 2: Copy the Application Files
Copy all the application files to the cloned repository:
```bash# Create necessary directoriesmkdir -p models utils
# Copy files from this repositorycp -r app.py Dockerfile requirements.txt README.md .gitignore utils/* .```
## Step 3: Add the Model Files
Copy your YOLO model files to the models directory:
```bash# Create models directory if it doesn't existmkdir -p models
# Copy model filescp /path/to/grape.pt models/cp /path/to/stem.pt models/cp /path/to/orange.pt models/```
## Step 4: Commit and Push Changes
```bash# Add all files to gitgit add .
# Commit changesgit commit -m "Initial deployment of YOLO Detection API"
# Push to HuggingFacegit push```
If this is your first time pushing to HuggingFace, you may need to authenticate:
```bash# Authenticate with HuggingFacegit config --global credential.helper storegit push# Enter your HuggingFace username and token when prompted```
## Step 5: Configure HuggingFace Space
1. Go to your HuggingFace Space: https://huggingface.co/spaces/Kesherat/CK12. Click on "Settings"3. Under "Hardware", select "Nvidia T4 small (4 vCPU • 15 GB RAM • 16 GB VRAM)"4. Under "Repository", make sure "Docker" is selected5. Under "Visibility", select "Public" (or your preferred visibility)6. Save changes
## Step 6: Monitor Deployment
1. Go to the "Deployments" tab2. Monitor the build logs to ensure the deployment is successful3. Once deployed, you should see "Running" status
## Step 7: Test the API
1. Open your Space URL: https://huggingface.co/spaces/Kesherat/CK12. You should see the web interface for testing the API3. Upload an image and click "Detect Objects" to test
## Step 8: Update Raspberry Pi Client
Update your Raspberry Pi client to use the new HuggingFace API endpoint:
```python# Example client code updateapi_url = "https://kesherat-ck1.hf.space/detect"api_key = "Bearer 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"
# Make requestresponse = requests.post( api_url, json={"image": base64_image}, headers={"Authorization": api_key})```
## Troubleshooting
### Common Issues
1. **Build Failure**: Check the build logs for errors. Common issues include: - Missing dependencies - CUDA compatibility issues - Model loading errors
2. **API Key Authentication**: Ensure you're using the correct API key format: ``` Authorization: Bearer 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 ```
3. **Model Loading Errors**: Check that the model files are correctly uploaded to the models directory.
4. **Performance Issues**: If inference is slow, check: - GPU availability in the /health endpoint - Model size and complexity - Image resolution being sent
### Logs and Monitoring
- Check the Space logs for real-time debugging- Monitor the Space metrics for resource usage- Use the /health endpoint to verify GPU availability
## Updating the Deployment
To update your deployment:
1. Make changes locally2. Commit and push to HuggingFace3. The Space will automatically rebuild and deploy
## Backup and Recovery
- Keep a local backup of all code and model files- Consider storing model files in HuggingFace Model Hub for better versioning- Document any custom configurations or environment variables123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354FROM nvidia/cuda:11.8.0-cudnn8-runtime-ubuntu22.04
# Set working directoryWORKDIR /app
# Set environment variablesENV DEBIAN_FRONTEND=noninteractiveENV PYTHONUNBUFFERED=1ENV PORT=7860
# Install system dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \ python3 \ python3-pip \ python3-dev \ libgl1-mesa-glx \ libglib2.0-0 \ libsm6 \ libxext6 \ libxrender-dev \ wget \ git \ && rm -rf /var/lib/apt/lists/* \ && apt-get clean
# Upgrade pipRUN pip3 install --no-cache-dir --upgrade pip
# Copy requirements fileCOPY requirements.txt .
# Install Python dependenciesRUN pip3 install --no-cache-dir -r requirements.txt
# Create models directoryRUN mkdir -p /app/models
# Copy application codeCOPY . .
# Make sure the models directory existsRUN mkdir -p /app/models
# Download default YOLOv8 model as fallbackRUN wget -q https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt -O /app/models/yolov8n.pt
# Verify CUDA installationRUN python3 -c "import torch; print('CUDA available:', torch.cuda.is_available()); print('CUDA device:', torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'None')"
# Expose the portEXPOSE 7860
# Command to run the applicationCMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469import osimport timeimport uuidimport torchimport numpy as npfrom fastapi import FastAPI, File, UploadFile, HTTPException, Depends, Header, Form, Requestfrom fastapi.responses import HTMLResponse, JSONResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.staticfiles import StaticFilesfrom fastapi.templating import Jinja2Templatesfrom pydantic import BaseModelfrom typing import List, Dict, Any, Optionalimport logging
# Import custom modulesfrom utils.yolo_detector import YOLODetectorfrom utils.image_processing import ( decode_base64_image, encode_image_to_base64, preprocess_image_for_detection, draw_detections)
# Configure logginglogging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')logger = logging.getLogger(__name__)
# Initialize FastAPI appapp = FastAPI( title="YOLO Detection API", description="API for real-time object detection using YOLO models", version="1.0.0")
# Add CORS middlewareapp.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# Get API key from environment variableAPI_KEY = os.getenv("API_KEY", "YOUR_HF_TOKEN_HERE")
# Create models directory if it doesn't existos.makedirs("models", exist_ok=True)
# Initialize YOLO detectortry: detector = YOLODetector( model_dir="models", default_model="grape.pt", device="cuda" if torch.cuda.is_available() else "cpu" ) logger.info(f"YOLO detector initialized with device: {detector.device}") logger.info(f"Available models: {detector.get_available_models()}")except Exception as e: logger.error(f"Failed to initialize YOLO detector: {str(e)}") detector = None
# Pydantic models for request/responseclass DetectionRequest(BaseModel): image: str # base64 encoded image model: Optional[str] = None # model to use (defaults to current) confidence: Optional[float] = 0.5 # confidence threshold iou: Optional[float] = 0.45 # IOU threshold class Detection(BaseModel): class_name: str confidence: float bbox: List[int] # [x1, y1, x2, y2] color: List[int] # [R, G, B]
class DetectionResponse(BaseModel): detections: List[Detection] processing_time: float model_used: str frame_id: str
# Authentication dependencyasync def verify_api_key(authorization: str = Header(None)): if not authorization: raise HTTPException(status_code=401, detail="API key is missing") if authorization != f"Bearer {API_KEY}": raise HTTPException(status_code=401, detail="Invalid API key") return authorization
# Endpoints@app.get("/health")async def health_check(): """Health check endpoint""" if detector is None: return { "status": "unhealthy", "error": "YOLO detector not initialized", "gpu": torch.cuda.is_available() } return { "status": "healthy", "gpu": torch.cuda.is_available(), "device": detector.device, "models": detector.get_available_models(), "current_model": detector.current_model }
@app.get("/", response_class=HTMLResponse)async def root(): """Simple web interface for testing""" html_content = """ <!DOCTYPE html> <html> <head> <title>YOLO Detection API</title> <style> body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; } h1 { color: #333; } .container { display: flex; flex-direction: column; gap: 20px; } .form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; font-weight: bold; } input, select { padding: 8px; border: 1px solid #ddd; border-radius: 4px; width: 100%; box-sizing: border-box; } button { background-color: #4CAF50; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #45a049; } #result { margin-top: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 4px; background-color: #f9f9f9; min-height: 100px; } #preview { max-width: 100%; margin-top: 10px; } .detection-box { position: absolute; border: 2px solid; box-sizing: border-box; } .detection-label { position: absolute; top: -20px; left: 0; padding: 2px 6px; color: white; font-size: 12px; } #image-container { position: relative; display: inline-block; } </style> </head> <body> <h1>YOLO Detection API</h1> <div class="container"> <div> <h2>Test Detection</h2> <div class="form-group"> <label for="image">Upload Image:</label> <input type="file" id="image" accept="image/*"> </div> <div class="form-group"> <label for="model">Model:</label> <select id="model"> <option value="grape.pt">Grape Detection</option> <option value="stem.pt">Stem Detection</option> <option value="orange.pt">Orange Detection</option> </select> </div> <div class="form-group"> <label for="confidence">Confidence Threshold:</label> <input type="range" id="confidence" min="0.1" max="0.9" step="0.1" value="0.5"> <span id="confidence-value">0.5</span> </div> <div class="form-group"> <label for="api-key">API Key:</label> <input type="text" id="api-key" placeholder="Bearer YOUR_HF_TOKEN_HERE..."> </div> <button id="detect-btn">Detect Objects</button> </div> <div> <h2>Preview</h2> <div id="image-container"> <img id="preview" src="" alt="Preview"> </div> </div> <div> <h2>Results</h2> <pre id="result">No results yet</pre> </div> </div>
<script> document.getElementById('image').addEventListener('change', function(e) { const file = e.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = function(event) { document.getElementById('preview').src = event.target.result; }; reader.readAsDataURL(file); } }); document.getElementById('confidence').addEventListener('input', function(e) { document.getElementById('confidence-value').textContent = e.target.value; }); document.getElementById('detect-btn').addEventListener('click', async function() { const imageInput = document.getElementById('image'); const modelSelect = document.getElementById('model'); const confidenceInput = document.getElementById('confidence'); const apiKeyInput = document.getElementById('api-key'); const resultDiv = document.getElementById('result'); if (!imageInput.files[0]) { alert('Please select an image'); return; } if (!apiKeyInput.value) { alert('Please enter API key'); return; } // Clear previous detection boxes const boxes = document.querySelectorAll('.detection-box'); boxes.forEach(box => box.remove()); // Read image as base64 const reader = new FileReader(); reader.onload = async function(event) { const base64Image = event.target.result.split(',')[1]; // Prepare request data const requestData = { image: base64Image, model: modelSelect.value, confidence: parseFloat(confidenceInput.value) }; try { resultDiv.textContent = 'Processing...'; // Send detection request const response = await fetch('/detect', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': apiKeyInput.value }, body: JSON.stringify(requestData) }); if (!response.ok) { const errorText = await response.text(); throw new Error(`Error: ${response.status} - ${errorText}`); } const result = await response.json(); resultDiv.textContent = JSON.stringify(result, null, 2); // Draw detection boxes const imgContainer = document.getElementById('image-container'); const img = document.getElementById('preview'); const imgRect = img.getBoundingClientRect(); const scaleX = img.naturalWidth / imgRect.width; const scaleY = img.naturalHeight / imgRect.height; result.detections.forEach(det => { const [x1, y1, x2, y2] = det.bbox; const box = document.createElement('div'); box.className = 'detection-box'; box.style.left = `${x1 / scaleX}px`; box.style.top = `${y1 / scaleY}px`; box.style.width = `${(x2 - x1) / scaleX}px`; box.style.height = `${(y2 - y1) / scaleY}px`; box.style.borderColor = `rgb(${det.color[0]}, ${det.color[1]}, ${det.color[2]})`; const label = document.createElement('div'); label.className = 'detection-label'; label.textContent = `${det.class_name}: ${det.confidence.toFixed(2)}`; label.style.backgroundColor = `rgb(${det.color[0]}, ${det.color[1]}, ${det.color[2]})`; box.appendChild(label); imgContainer.appendChild(box); }); } catch (error) { resultDiv.textContent = `Error: ${error.message}`; } }; reader.readAsDataURL(imageInput.files[0]); }); </script> </body> </html> """ return html_content
@app.get("/models")async def list_models(authorization: str = Depends(verify_api_key)): """List available models""" if detector is None: raise HTTPException(status_code=500, detail="YOLO detector not initialized") return { "models": detector.get_available_models(), "current": detector.current_model }
@app.post("/switch-model")async def switch_model(model: str, authorization: str = Depends(verify_api_key)): """Switch to a different model""" if detector is None: raise HTTPException(status_code=500, detail="YOLO detector not initialized") try: detector.load_model(model) return {"status": "success", "model": model} except Exception as e: raise HTTPException(status_code=400, detail=f"Failed to load model: {str(e)}")
@app.post("/detect", response_model=DetectionResponse)async def detect(request: DetectionRequest, authorization: str = Depends(verify_api_key)): """ Detect objects in an image The image should be provided as a base64-encoded string. Optionally specify a model to use and confidence threshold. """ if detector is None: raise HTTPException(status_code=500, detail="YOLO detector not initialized") try: start_time = time.time() # Decode base64 image try: image = decode_base64_image(request.image) except Exception as e: raise HTTPException(status_code=400, detail=f"Invalid image data: {str(e)}") # Switch model if requested if request.model and request.model != detector.current_model: try: detector.load_model(request.model) except Exception as e: raise HTTPException(status_code=400, detail=f"Failed to load model {request.model}: {str(e)}") # Preprocess image processed_image = preprocess_image_for_detection(image) # Run detection detections = detector.detect( processed_image, conf_threshold=request.confidence, iou_threshold=request.iou or 0.45 ) processing_time = time.time() - start_time # Generate unique frame ID frame_id = str(uuid.uuid4()) # Format response response = { "detections": detections, "processing_time": round(processing_time, 3), "model_used": detector.current_model, "frame_id": frame_id } return response except Exception as e: logger.error(f"Detection error: {str(e)}") raise HTTPException(status_code=500, detail=f"Detection failed: {str(e)}")
@app.post("/detect-and-visualize")async def detect_and_visualize(request: DetectionRequest, authorization: str = Depends(verify_api_key)): """ Detect objects and return the image with visualized detections The image should be provided as a base64-encoded string. Returns a base64-encoded image with detection boxes drawn. """ if detector is None: raise HTTPException(status_code=500, detail="YOLO detector not initialized") try: # Decode base64 image image = decode_base64_image(request.image) # Switch model if requested if request.model and request.model != detector.current_model: detector.load_model(request.model) # Run detection detections = detector.detect( image, conf_threshold=request.confidence, iou_threshold=request.iou or 0.45 ) # Draw detections on image result_image = draw_detections(image, detections) # Encode result image to base64 result_base64 = encode_image_to_base64(result_image) return { "image": result_base64, "detections": detections, "model_used": detector.current_model } except Exception as e: logger.error(f"Visualization error: {str(e)}") raise HTTPException(status_code=500, detail=f"Visualization failed: {str(e)}")
# Run the applicationif __name__ == "__main__": import uvicorn uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374#!/usr/bin/env python3"""Example Raspberry Pi client for the YOLO Detection APIThis script captures frames from a RealSense camera, sends them to the API,and displays the results with detection overlays."""
import pyrealsense2 as rsimport numpy as npimport cv2import requestsimport base64import timeimport jsonimport websocketimport threadingimport argparseimport loggingfrom typing import Dict, List, Any, Optional, Tuple
# Configure logginglogging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')logger = logging.getLogger(__name__)
class YOLODetectionClient: """Client for the YOLO Detection API with RealSense camera integration""" def __init__( self, api_url: str = "https://kesherat-ck1.hf.space/detect", api_key: str = "Bearer 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", railway_ws_url: str = "ws://localhost:8000/ws/client", camera_width: int = 640, camera_height: int = 480, camera_fps: int = 30, process_width: int = 416, process_height: int = 416, confidence: float = 0.5, skip_frames: int = 2, jpeg_quality: int = 75, show_display: bool = True ): """Initialize the client""" self.api_url = api_url self.api_key = api_key self.railway_ws_url = railway_ws_url # Camera settings self.camera_width = camera_width self.camera_height = camera_height self.camera_fps = camera_fps # Processing settings self.process_width = process_width self.process_height = process_height self.confidence = confidence self.skip_frames = skip_frames self.jpeg_quality = jpeg_quality self.show_display = show_display # Initialize state self.pipeline = None self.frame_count = 0 self.processing = False self.last_detections = [] self.ws = None self.ws_connected = False self.running = False logger.info("YOLODetectionClient initialized") logger.info(f"API URL: {api_url}") logger.info(f"Railway WebSocket URL: {railway_ws_url}") def initialize_camera(self) -> bool: """Initialize the RealSense camera""" try: logger.info("Initializing RealSense camera...") # Create pipeline self.pipeline = rs.pipeline() # Create config config = rs.config() config.enable_stream(rs.stream.color, self.camera_width, self.camera_height, rs.format.bgr8, self.camera_fps) config.enable_stream(rs.stream.depth, self.camera_width, self.camera_height, rs.format.z16, self.camera_fps) # Start pipeline self.pipeline.start(config) # Wait for camera to warm up time.sleep(2) logger.info("RealSense camera initialized successfully") return True except Exception as e: logger.error(f"Failed to initialize camera: {str(e)}") return False def connect_to_railway(self) -> bool: """Connect to Railway WebSocket server""" if not self.railway_ws_url or self.railway_ws_url == "ws://localhost:8000/ws/client": logger.info("Railway WebSocket URL not configured, skipping connection") return False try: logger.info(f"Connecting to Railway WebSocket: {self.railway_ws_url}") # Define WebSocket callbacks def on_open(ws): logger.info("Connected to Railway WebSocket") self.ws_connected = True def on_message(ws, message): # Process any messages from Railway pass def on_error(ws, error): logger.error(f"Railway WebSocket error: {str(error)}") self.ws_connected = False def on_close(ws, close_status_code, close_msg): logger.info("Railway WebSocket connection closed") self.ws_connected = False # Create WebSocket connection self.ws = websocket.WebSocketApp( self.railway_ws_url, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close ) # Start WebSocket connection in a separate thread threading.Thread(target=self.ws.run_forever, daemon=True).start() # Wait for connection timeout = 5 start_time = time.time() while not self.ws_connected and time.time() - start_time < timeout: time.sleep(0.1) return self.ws_connected except Exception as e: logger.error(f"Failed to connect to Railway: {str(e)}") return False def encode_image(self, image: np.ndarray) -> str: """Encode image as base64 string""" # Resize image for processing resized = cv2.resize(image, (self.process_width, self.process_height)) # Encode as JPEG _, buffer = cv2.imencode('.jpg', resized, [cv2.IMWRITE_JPEG_QUALITY, self.jpeg_quality]) # Convert to base64 return base64.b64encode(buffer).decode('utf-8') def send_to_api(self, image: np.ndarray) -> Dict[str, Any]: """Send image to API for detection""" try: # Encode image base64_image = self.encode_image(image) # Prepare request data request_data = { "image": base64_image, "confidence": self.confidence } # Prepare headers headers = { "Content-Type": "application/json", "Authorization": self.api_key } # Send request start_time = time.time() response = requests.post(self.api_url, json=request_data, headers=headers, timeout=10) latency = time.time() - start_time # Check response if response.status_code != 200: logger.error(f"API error: {response.status_code} - {response.text}") return {"error": f"API error: {response.status_code}"} # Parse response result = response.json() logger.info(f"Detection completed in {latency:.3f}s, found {len(result.get('detections', []))} objects") return result except Exception as e: logger.error(f"API request error: {str(e)}") return {"error": str(e)} def draw_detections(self, image: np.ndarray, detections: List[Dict[str, Any]]) -> np.ndarray: """Draw detection boxes on image""" output = image.copy() for det in detections: x1, y1, x2, y2 = det["bbox"] # Scale bounding box to original image size x1 = int(x1 * image.shape[1] / self.process_width) y1 = int(y1 * image.shape[0] / self.process_height) x2 = int(x2 * image.shape[1] / self.process_width) y2 = int(y2 * image.shape[0] / self.process_height) class_name = det["class_name"] confidence = det["confidence"] color = tuple(det["color"]) # Convert to tuple for OpenCV # Draw bounding box cv2.rectangle(output, (x1, y1), (x2, y2), color, 2) # Draw label background text = f"{class_name}: {confidence:.2f}" text_size, _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 2) cv2.rectangle(output, (x1, y1 - text_size[1] - 5), (x1 + text_size[0], y1), color, -1) # Draw text cv2.putText(output, text, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) return output def send_to_railway(self, image: np.ndarray, detections: List[Dict[str, Any]]) -> bool: """Send processed image to Railway WebSocket""" if not self.ws_connected: return False try: # Draw detections on image result_image = self.draw_detections(image, detections) # Encode image _, buffer = cv2.imencode('.jpg', result_image, [cv2.IMWRITE_JPEG_QUALITY, 70]) base64_image = base64.b64encode(buffer).decode('utf-8') # Prepare message message = { "type": "camera_frame", "image": base64_image, "detections": detections, "timestamp": time.time() } # Send message self.ws.send(json.dumps(message)) return True except Exception as e: logger.error(f"Failed to send to Railway: {str(e)}") return False def process_frame(self, color_frame: np.ndarray, depth_frame: np.ndarray) -> Tuple[np.ndarray, List[Dict[str, Any]]]: """Process a frame through the detection API""" # Skip frames if needed if self.frame_count % (self.skip_frames + 1) != 0: return color_frame, self.last_detections # Send to API self.processing = True result = self.send_to_api(color_frame) self.processing = False # Extract detections if "error" in result: detections = [] else: detections = result.get("detections", []) self.last_detections = detections # Draw detections output = self.draw_detections(color_frame, detections) # Send to Railway if connected if self.ws_connected: self.send_to_railway(color_frame, detections) return output, detections def run(self) -> None: """Run the client""" # Initialize camera if not self.initialize_camera(): logger.error("Failed to initialize camera, exiting") return # Connect to Railway self.connect_to_railway() # Main loop self.running = True self.frame_count = 0 try: while self.running: # Wait for frames frames = self.pipeline.wait_for_frames() color_frame = np.asanyarray(frames.get_color_frame().get_data()) depth_frame = np.asanyarray(frames.get_depth_frame().get_data()) # Process frame if not self.processing: result_frame, detections = self.process_frame(color_frame, depth_frame) else: # If still processing previous frame, just draw last detections result_frame = self.draw_detections(color_frame, self.last_detections) # Display result if self.show_display: cv2.imshow("YOLO Detection", result_frame) # Check for key press key = cv2.waitKey(1) if key == 27: # ESC key break self.frame_count += 1 except KeyboardInterrupt: logger.info("Interrupted by user") except Exception as e: logger.error(f"Error in main loop: {str(e)}") finally: # Clean up if self.pipeline: self.pipeline.stop() if self.ws_connected: self.ws.close() if self.show_display: cv2.destroyAllWindows() logger.info("Client stopped")
def main(): """Main function""" parser = argparse.ArgumentParser(description="Raspberry Pi client for YOLO Detection API") parser.add_argument("--api-url", default="https://kesherat-ck1.hf.space/detect", help="API URL") parser.add_argument("--api-key", default="Bearer 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", help="API key") parser.add_argument("--railway-url", default="ws://localhost:8000/ws/client", help="Railway WebSocket URL") parser.add_argument("--width", type=int, default=640, help="Camera width") parser.add_argument("--height", type=int, default=480, help="Camera height") parser.add_argument("--fps", type=int, default=30, help="Camera FPS") parser.add_argument("--confidence", type=float, default=0.5, help="Confidence threshold") parser.add_argument("--skip-frames", type=int, default=2, help="Number of frames to skip between detections") parser.add_argument("--no-display", action="store_true", help="Disable display window") args = parser.parse_args() client = YOLODetectionClient( api_url=args.api_url, api_key=args.api_key, railway_ws_url=args.railway_url, camera_width=args.width, camera_height=args.height, camera_fps=args.fps, confidence=args.confidence, skip_frames=args.skip_frames, show_display=not args.no_display ) client.run()
if __name__ == "__main__": main()12345678910111213fastapi==0.95.1uvicorn==0.22.0python-multipart==0.0.6ultralytics==8.0.120torch==2.0.1torchvision==0.15.2numpy==1.24.3Pillow==9.5.0python-dotenv==1.0.0pydantic==1.10.8opencv-python==4.7.0.72jinja2==3.1.2uuid==1.30123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151#!/usr/bin/env python3"""Test script for the YOLO Detection APIThis script sends a test image to the API and displays the results"""
import requestsimport argparseimport base64import jsonimport cv2import numpy as npimport osfrom typing import List, Dict, Any
def encode_image(image_path: str) -> str: """Encode image as base64 string""" with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode("utf-8")
def decode_base64_image(base64_string: str) -> np.ndarray: """Decode base64 string to image""" image_data = base64.b64decode(base64_string) nparr = np.frombuffer(image_data, np.uint8) return cv2.imdecode(nparr, cv2.IMREAD_COLOR)
def draw_detections(image: np.ndarray, detections: List[Dict[str, Any]]) -> np.ndarray: """Draw detection boxes on image""" output = image.copy() for det in detections: x1, y1, x2, y2 = det["bbox"] class_name = det["class_name"] confidence = det["confidence"] color = tuple(det["color"]) # Convert to tuple for OpenCV # Draw bounding box cv2.rectangle(output, (x1, y1), (x2, y2), color, 2) # Draw label background text = f"{class_name}: {confidence:.2f}" text_size, _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 2) cv2.rectangle(output, (x1, y1 - text_size[1] - 5), (x1 + text_size[0], y1), color, -1) # Draw text cv2.putText(output, text, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) return output
def test_api(image_path: str, api_url: str, api_key: str, model: str = None, confidence: float = 0.5) -> None: """Test the YOLO Detection API""" print(f"Testing API with image: {image_path}") # Check if image exists if not os.path.exists(image_path): print(f"Error: Image not found at {image_path}") return # Encode image print("Encoding image...") try: base64_image = encode_image(image_path) except Exception as e: print(f"Error encoding image: {str(e)}") return # Prepare request data request_data = { "image": base64_image, "confidence": confidence } if model: request_data["model"] = model # Prepare headers headers = { "Content-Type": "application/json", "Authorization": api_key } # Send request print(f"Sending request to {api_url}...") try: response = requests.post(api_url, json=request_data, headers=headers, timeout=30) except Exception as e: print(f"Error sending request: {str(e)}") return # Check response if response.status_code != 200: print(f"Error: API returned status code {response.status_code}") print(f"Response: {response.text}") return # Parse response try: result = response.json() except Exception as e: print(f"Error parsing response: {str(e)}") return # Print results print("\nDetection Results:") print(f"Model used: {result.get('model_used', 'unknown')}") print(f"Processing time: {result.get('processing_time', 0):.3f} seconds") print(f"Frame ID: {result.get('frame_id', 'unknown')}") detections = result.get("detections", []) print(f"Found {len(detections)} detections:") for i, det in enumerate(detections): print(f" {i+1}. {det.get('class_name', 'unknown')}: {det.get('confidence', 0):.2f}") # Display image with detections try: # Load original image image = cv2.imread(image_path) # Draw detections result_image = draw_detections(image, detections) # Display image cv2.imshow("Detection Results", result_image) print("\nPress any key to exit...") cv2.waitKey(0) cv2.destroyAllWindows() # Save result image output_path = f"{os.path.splitext(image_path)[0]}_result.jpg" cv2.imwrite(output_path, result_image) print(f"Result image saved to: {output_path}") except Exception as e: print(f"Error displaying results: {str(e)}")
def main(): """Main function""" parser = argparse.ArgumentParser(description="Test the YOLO Detection API") parser.add_argument("--image", required=True, help="Path to test image") parser.add_argument("--url", default="http://localhost:7860/detect", help="API URL") parser.add_argument("--key", default="Bearer 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", help="API key") parser.add_argument("--model", help="Model to use (e.g., grape.pt)") parser.add_argument("--confidence", type=float, default=0.5, help="Confidence threshold") args = parser.parse_args() test_api(args.image, args.url, args.key, args.model, args.confidence)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149import base64import cv2import numpy as npfrom typing import Tuple, Optional, Union
def decode_base64_image(base64_string: str) -> np.ndarray: """ Decode a base64 string to a numpy image array Args: base64_string: Base64 encoded image string Returns: numpy.ndarray: Decoded image in BGR format (OpenCV default) """ # Remove data URL prefix if present if base64_string.startswith('data:image'): base64_string = base64_string.split(',')[1] # Decode base64 string image_data = base64.b64decode(base64_string) # Convert to numpy array nparr = np.frombuffer(image_data, np.uint8) # Decode image image = cv2.imdecode(nparr, cv2.IMREAD_COLOR) if image is None: raise ValueError("Failed to decode base64 image") return image
def encode_image_to_base64(image: np.ndarray, format: str = '.jpg', quality: int = 90) -> str: """ Encode a numpy image array to base64 string Args: image: Image as numpy array (BGR format) format: Image format ('.jpg', '.png', etc.) quality: JPEG quality (0-100) if format is '.jpg' Returns: str: Base64 encoded image string """ # Set encoding parameters if format.lower() == '.jpg' or format.lower() == '.jpeg': params = [cv2.IMWRITE_JPEG_QUALITY, quality] elif format.lower() == '.png': params = [cv2.IMWRITE_PNG_COMPRESSION, min(9, quality // 10)] else: params = [] # Encode image _, buffer = cv2.imencode(format, image, params) # Convert to base64 base64_string = base64.b64encode(buffer).decode('utf-8') return base64_string
def resize_image(image: np.ndarray, target_size: Tuple[int, int], keep_aspect_ratio: bool = True) -> np.ndarray: """ Resize image to target size Args: image: Input image target_size: Target size as (width, height) keep_aspect_ratio: Whether to maintain aspect ratio Returns: numpy.ndarray: Resized image """ if keep_aspect_ratio: h, w = image.shape[:2] target_w, target_h = target_size # Calculate scaling factor scale = min(target_w / w, target_h / h) # Calculate new dimensions new_w, new_h = int(w * scale), int(h * scale) # Resize image resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) # Create canvas of target size canvas = np.zeros((target_h, target_w, 3), dtype=np.uint8) # Calculate position to paste resized image x_offset = (target_w - new_w) // 2 y_offset = (target_h - new_h) // 2 # Paste resized image onto canvas canvas[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized return canvas else: # Simple resize without preserving aspect ratio return cv2.resize(image, target_size, interpolation=cv2.INTER_AREA)
def draw_detections(image: np.ndarray, detections: list) -> np.ndarray: """ Draw detection bounding boxes on image Args: image: Input image detections: List of detection results with bbox, class_name, confidence, color Returns: numpy.ndarray: Image with bounding boxes drawn """ output = image.copy() for det in detections: x1, y1, x2, y2 = det["bbox"] class_name = det["class_name"] confidence = det["confidence"] color = tuple(det["color"]) # Convert to tuple for OpenCV # Draw bounding box cv2.rectangle(output, (x1, y1), (x2, y2), color, 2) # Draw label background text = f"{class_name}: {confidence:.2f}" text_size, _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 2) cv2.rectangle(output, (x1, y1 - text_size[1] - 5), (x1 + text_size[0], y1), color, -1) # Draw text cv2.putText(output, text, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) return output
def preprocess_image_for_detection(image: np.ndarray, target_size: Tuple[int, int] = (640, 640)) -> np.ndarray: """ Preprocess image for YOLO detection Args: image: Input image target_size: Target size for the model Returns: numpy.ndarray: Preprocessed image """ # Resize image resized = resize_image(image, target_size, keep_aspect_ratio=True) return resized123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185import osimport torchimport numpy as npimport cv2from ultralytics import YOLOfrom typing import List, Dict, Any, Optional, Tuple
class YOLODetector: """ YOLO detector class for managing multiple YOLO models and performing inference """ def __init__(self, model_dir: str = "models", default_model: str = "grape.pt", device: str = None): """ Initialize the YOLO detector Args: model_dir: Directory containing model files default_model: Default model to load device: Device to run inference on ('cuda' or 'cpu') """ self.model_dir = model_dir self.default_model = default_model # Determine device if device is None: self.device = "cuda" if torch.cuda.is_available() else "cpu" else: self.device = device # Initialize model cache self.models = {} self.current_model = default_model # Class colors mapping self.class_colors = { "grape": [255, 0, 0], # Red "stem": [0, 255, 0], # Green "orange": [255, 165, 0] # Orange } # Load default model self.load_model(default_model) print(f"YOLO Detector initialized with device: {self.device}") print(f"Available models: {self.get_available_models()}") print(f"Current model: {self.current_model}") def get_available_models(self) -> List[str]: """Get list of available model files""" if not os.path.exists(self.model_dir): return [] return [f for f in os.listdir(self.model_dir) if f.endswith('.pt') and os.path.isfile(os.path.join(self.model_dir, f))] def load_model(self, model_name: str) -> None: """ Load a YOLO model Args: model_name: Name of the model file (e.g., 'grape.pt') """ # Check if model is already loaded if model_name in self.models: self.current_model = model_name print(f"Using cached model: {model_name}") return # Check if model file exists model_path = os.path.join(self.model_dir, model_name) if not os.path.exists(model_path): raise FileNotFoundError(f"Model file not found: {model_path}") # Load model try: print(f"Loading model: {model_path} on {self.device}") model = YOLO(model_path) # Move model to device if self.device == "cuda" and torch.cuda.is_available(): # Enable half precision for faster inference if supported if torch.cuda.get_device_capability()[0] >= 7: model.half() print(f"Using half precision for {model_name}") self.models[model_name] = model self.current_model = model_name print(f"Model {model_name} loaded successfully") except Exception as e: raise RuntimeError(f"Failed to load model {model_name}: {str(e)}") def detect(self, image: np.ndarray, conf_threshold: float = 0.5, iou_threshold: float = 0.45) -> List[Dict[str, Any]]: """ Perform object detection on an image Args: image: Input image as numpy array (BGR format) conf_threshold: Confidence threshold for detections iou_threshold: IOU threshold for NMS Returns: List of detection results with class, confidence, bbox, and color """ if self.current_model not in self.models: raise RuntimeError(f"Model {self.current_model} not loaded") model = self.models[self.current_model] # Run inference results = model.predict( image, conf=conf_threshold, iou=iou_threshold, max_det=100, verbose=False )[0] # Process results detections = [] if hasattr(results.boxes, 'xyxy') and len(results.boxes.xyxy) > 0: boxes = results.boxes.xyxy.cpu().numpy().astype(int) scores = results.boxes.conf.cpu().numpy() class_ids = results.boxes.cls.cpu().numpy().astype(int) # Get class names class_names = results.names for i, (box, score, class_id) in enumerate(zip(boxes, scores, class_ids)): x1, y1, x2, y2 = box class_name = class_names[class_id] # Determine color based on class if class_name in self.class_colors: color = self.class_colors[class_name] else: # Default color if class not in mapping color = [0, 0, 255] # Blue detection = { "class_name": class_name, "confidence": float(score), "bbox": [int(x1), int(y1), int(x2), int(y2)], "color": color } detections.append(detection) return detections def visualize_detections(self, image: np.ndarray, detections: List[Dict[str, Any]]) -> np.ndarray: """ Draw detection bounding boxes on image Args: image: Input image detections: List of detection results Returns: Image with bounding boxes drawn """ vis_image = image.copy() for det in detections: x1, y1, x2, y2 = det["bbox"] class_name = det["class_name"] confidence = det["confidence"] color = tuple(det["color"]) # Convert to tuple for OpenCV # Draw bounding box cv2.rectangle(vis_image, (x1, y1), (x2, y2), color, 2) # Draw label background text = f"{class_name}: {confidence:.2f}" text_size, _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 2) cv2.rectangle(vis_image, (x1, y1 - text_size[1] - 5), (x1 + text_size[0], y1), color, -1) # Draw text cv2.putText(vis_image, text, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) return vis_image.gitignoreAdded+51
DEPLOYMENT_GUIDE.mdAdded+147
DockerfileAdded+54
app.pyAdded+469
raspberry_pi_client_example.pyAdded+374
requirements.txtAdded+13
test_api.pyAdded+151
utils/image_processing.pyAdded+149
utils/yolo_detector.pyAdded+185