Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354from fastapi import FastAPIfrom fastapi.responses import HTMLResponseimport cv2import numpy as npimport mediapipe as mpfrom starlette.responses import StreamingResponseimport uvicornapp = FastAPI()# Load MediaPipe Hand modelmp_hands = mp.solutions.handshands = mp_hands.Hands()mp_draw = mp.solutions.drawing_utilsdef generate_frames():cap = cv2.VideoCapture(0)while True:success, frame = cap.read()if not success:break# Convert frame for MediaPipergb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)results = hands.process(rgb_frame)# Draw landmarksif results.multi_hand_landmarks:for hand_landmarks in results.multi_hand_landmarks:mp_draw.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)# Convert frame to JPEG_, buffer = cv2.imencode('.jpg', frame)yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')@app.get("/", response_class=HTMLResponse)def home():return """<html><head><title>Hand Gesture Recognition</title></head><body><h1>Hand Gesture Recognition App</h1><img src="/video" width="640" height="480"/></body></html>"""@app.get("/video")def video_feed():return StreamingResponse(generate_frames(), media_type="multipart/x-mixed-replace; boundary=frame")if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495from fastapi import FastAPI, WebSocket, UploadFile, File, Formfrom fastapi.responses import HTMLResponse, JSONResponseimport numpy as npimport tensorflow as tffrom tensorflow import kerasfrom PIL import Imageimport ioimport osimport cv2import base64import asyncioimport uvicornapp = FastAPI()MODEL_PATH = "model.h5"model = keras.models.load_model(MODEL_PATH) if os.path.exists(MODEL_PATH) else Nonedef preprocess_image(image_bytes):image = Image.open(io.BytesIO(image_bytes)).convert("RGB")image = image.resize((128, 128))image = np.array(image) / 255.0image = np.expand_dims(image, axis=0)return image@app.get("/", response_class=HTMLResponse)async def home():return """<html><head><script>let videoStream;async function startCamera() {videoStream = await navigator.mediaDevices.getUserMedia({ video: true });document.getElementById('video').srcObject = videoStream;}async function captureImage() {let canvas = document.createElement('canvas');let video = document.getElementById('video');canvas.width = video.videoWidth;canvas.height = video.videoHeight;canvas.getContext('2d').drawImage(video, 0, 0);let dataURL = canvas.toDataURL('image/jpeg');document.getElementById('capturedImage').src = dataURL;}</script></head><body><h2>Live Gesture Recognition</h2><button onclick="startCamera()">Start Camera</button><video id="video" autoplay></video><button onclick="captureImage()">Capture Image</button><img id="capturedImage" /></body></html>"""@app.post("/predict")async def predict(file: UploadFile = File(...)):if model is None:return JSONResponse(content={"error": "Model not trained yet."}, status_code=400)image_bytes = await file.read()image = preprocess_image(image_bytes)prediction = model.predict(image)predicted_class = np.argmax(prediction)return {"prediction": int(predicted_class)}@app.post("/train")async def train_model(files: list[UploadFile] = File(...), labels: list[int] = Form(...)):global modelimages = []labels_np = np.array(labels)for file in files:image_bytes = await file.read()images.append(preprocess_image(image_bytes)[0])images_np = np.array(images)model = keras.Sequential([keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(128,128,3)),keras.layers.MaxPooling2D(2,2),keras.layers.Flatten(),keras.layers.Dense(64, activation='relu'),keras.layers.Dense(len(set(labels)), activation='softmax')])model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit(images_np, labels_np, epochs=5, batch_size=4)model.save(MODEL_PATH)return {"message": "Model trained successfully!"}if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)
app.py+79-38