Spaces:
Sleeping

gesture / app.py
prashantscripts's picture
Update app.py
7e3e837 verified
Raw History Blame Contribute Delete
6.6 kB
from fastapi import FastAPI, WebSocket, UploadFile, File
from fastapi.responses import HTMLResponse, JSONResponse
import numpy as np
import tensorflow as tf
from tensorflow import keras
from PIL import Image
import io
import os
import uvicorn
app = FastAPI()
MODEL_PATH = "model.h5"
model = keras.models.load_model(MODEL_PATH) if os.path.exists(MODEL_PATH) else None
def preprocess_image(image_bytes):
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
image = image.resize((128, 128))
image = np.array(image) / 255.0
image = np.expand_dims(image, axis=0)
return image
@app.get("/", response_class=HTMLResponse)
async def home():
return """
<html>
<head>
<title>Live Gesture Recognition</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; background: #f4f4f4; }
h2 { color: #333; }
.container { max-width: 600px; margin: auto; background: white; padding: 20px; border-radius: 10px; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); }
.video-container { position: relative; display: flex; justify-content: center; align-items: center; width: 400px; height: 400px; margin: auto; }
video { width: 100%; height: 100%; object-fit: cover; border-radius: 10px; }
canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
#prediction-box { position: absolute; top: 10px; left: 50%; transform: translateX(-50%); background: rgba(0, 0, 0, 0.7); color: white; padding: 5px 10px; border-radius: 5px; }
input, button { margin: 5px; padding: 8px; }
</style>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/hands/hands.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script>
let videoStream;
let hands;
let trainingMode = false;
let collectedGestures = [];
let gestureName = "";
let isMirrored = true;
async function startCamera() {
videoStream = await navigator.mediaDevices.getUserMedia({ video: true });
document.getElementById('video').srcObject = videoStream;
setupHandTracking();
}
function toggleMirror() {
let video = document.getElementById('video');
isMirrored = !isMirrored;
video.style.transform = isMirrored ? "scaleX(-1)" : "scaleX(1)";
}
function setupHandTracking() {
hands = new Hands({locateFile: (file) => `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`});
hands.setOptions({
maxNumHands: 1,
modelComplexity: 1,
minDetectionConfidence: 0.7,
minTrackingConfidence: 0.7
});
hands.onResults(drawHandLandmarks);
detectHands();
}
async function detectHands() {
let video = document.getElementById('video');
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
async function processFrame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
await hands.send({image: video});
requestAnimationFrame(processFrame);
}
processFrame();
}
function drawHandLandmarks(results) {
let video = document.getElementById('video');
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
if (results.multiHandLandmarks) {
results.multiHandLandmarks.forEach((landmarks) => {
drawConnectors(ctx, landmarks, HAND_CONNECTIONS, {color: 'lime', lineWidth: 1});
drawLandmarks(ctx, landmarks, {color: 'red', radius: 1.5, fillColor: 'transparent'});
drawBoundingBox(ctx, landmarks);
if (trainingMode) saveGesture(landmarks);
});
}
}
function drawBoundingBox(ctx, landmarks) {
let xMin = Math.min(...landmarks.map(p => p.x)) * ctx.canvas.width;
let yMin = Math.min(...landmarks.map(p => p.y)) * ctx.canvas.height;
let xMax = Math.max(...landmarks.map(p => p.x)) * ctx.canvas.width;
let yMax = Math.max(...landmarks.map(p => p.y)) * ctx.canvas.height;
ctx.strokeStyle = "yellow";
ctx.lineWidth = 2;
ctx.strokeRect(xMin, yMin, xMax - xMin, yMax - yMin);
document.getElementById('prediction-box').innerText = "Gesture: Recognizing...";
}
function toggleTraining() {
trainingMode = !trainingMode;
document.getElementById('train-btn').innerText = trainingMode ? "Stop Training" : "Start Training";
}
function saveGesture(landmarks) {
if (gestureName) {
collectedGestures.push({name: gestureName, landmarks});
console.log(`Saved gesture: ${gestureName}`);
}
}
function setGestureName() {
gestureName = document.getElementById('gesture-name').value;
}
</script>
</head>
<body>
<div class="container">
<h2>Live Gesture Recognition</h2>
<button onclick="startCamera()">Start Camera</button>
<button onclick="toggleMirror()">Flip Camera</button>
<br>
<input type="text" id="gesture-name" placeholder="Enter Gesture Name" oninput="setGestureName()">
<button id="train-btn" onclick="toggleTraining()">Start Training</button>
<div class="video-container">
<video id="video" autoplay style="transform: scaleX(-1);"></video>
<canvas id="canvas"></canvas>
<div id="prediction-box">Gesture: </div>
</div>
</div>
</body>
</html>
"""
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)