Spaces:
Sleeping

File size: 6,597 Bytes
ae4fc97
8f34046
009bca3
8f34046
 
 
 
 
054243d
009bca3
054243d
a97c5ef
8f34046
 
054243d
8f34046
 
 
 
 
 
054243d
 
8f34046
054243d
 
8f34046
ba77233
 
 
 
1dc5565
7c52431
0f7a244
1dc5565
7c52431
 
ba77233
b683ab3
859c555
b683ab3
8f34046
 
b683ab3
7c52431
 
 
7e3e837
b683ab3
8f34046
7e3e837
1dc5565
 
b683ab3
 
7e3e837
 
 
 
0f7a244
 
b683ab3
 
 
ae4fc97
b683ab3
ae4fc97
 
b683ab3
 
 
8f34046
b683ab3
 
1dc5565
 
 
b683ab3
1dc5565
 
b683ab3
 
 
 
 
 
1dc5565
 
 
b683ab3
1dc5565
859c555
 
7056d53
7e3e837
ae4fc97
7c52431
859c555
 
b683ab3
 
ae4fc97
 
 
 
 
 
7c52431
ae4fc97
 
8f34046
7c52431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f34046
 
 
ba77233
 
 
7e3e837
ba77233
7c52431
 
1dc5565
7e3e837
b683ab3
ae4fc97
b683ab3
ba77233
8f34046
054243d
 
 
 
9c75783
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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)