app.py 5.49 KB
Newer Older
Shehan Liyanage's avatar
Shehan Liyanage committed
1 2
from flask import Flask, request
from flask_socketio import SocketIO, emit, send
Shehan Liyanage's avatar
Shehan Liyanage committed
3
import cv2
Shehan Liyanage's avatar
Shehan Liyanage committed
4
import io
Shehan Liyanage's avatar
Shehan Liyanage committed
5
import numpy as np
Shehan Liyanage's avatar
Shehan Liyanage committed
6
import base64
Shehan Liyanage's avatar
Shehan Liyanage committed
7
import tensorflow as tf
Shehan Liyanage's avatar
Shehan Liyanage committed
8 9
from tensorflow.keras.models import load_model
import mediapipe as mp
Shehan Liyanage's avatar
Shehan Liyanage committed
10 11

mp_holistic = mp.solutions.holistic
Shehan Liyanage's avatar
Shehan Liyanage committed
12 13 14 15 16
mp_drawing = mp.solutions.drawing_utils
actions = (["haloo", "dannwa", "mama", "obata", "puluwan", "suba", "udaasanak"])

# Load the saved model
model = load_model(r'./finalModel.h5')
Shehan Liyanage's avatar
Shehan Liyanage committed
17 18 19 20 21

sequence = []
sentence = []
predictions = []
threshold = 0.7
Shehan Liyanage's avatar
Shehan Liyanage committed
22
count = 31
Shehan Liyanage's avatar
Shehan Liyanage committed
23 24

def mediapipe_detection(image, model):
Shehan Liyanage's avatar
Shehan Liyanage committed
25 26 27 28 29
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # COLOR CONVERSION BGR 2 RGB
    image.flags.writeable = False                  # Image is no longer writeable
    results = model.process(image)                 # Make prediction
    image.flags.writeable = True                   # Image is now writeable
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # COLOR COVERSION RGB 2 BGR
Shehan Liyanage's avatar
Shehan Liyanage committed
30 31
    return image, results

Shehan Liyanage's avatar
Shehan Liyanage committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
def draw_landmarks(image, results):
    # Draw face connections
    mp_drawing.draw_landmarks(image, results.face_landmarks, mp_holistic.FACEMESH_TESSELATION,
                             mp_drawing.DrawingSpec(color=(70,110,10), thickness=1, circle_radius=1),
                             mp_drawing.DrawingSpec(color=(70,256,121), thickness=1, circle_radius=1))
    # Draw pose connections
    mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS,
                             mp_drawing.DrawingSpec(color=(70,22,10), thickness=2, circle_radius=4),
                             mp_drawing.DrawingSpec(color=(70,44,121), thickness=2, circle_radius=2))
    # Draw left hand connections
    mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS,
                             mp_drawing.DrawingSpec(color=(121,22,76), thickness=2, circle_radius=4),
                             mp_drawing.DrawingSpec(color=(121,44,250), thickness=2, circle_radius=2))
    # Draw right hand connections
    mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS,
                             mp_drawing.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=4),
                             mp_drawing.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2))

Shehan Liyanage's avatar
Shehan Liyanage committed
50 51 52 53 54 55 56
def extract_keypoints(results):
    pose = np.array([[res.x, res.y, res.z, res.visibility] for res in results.pose_landmarks.landmark]).flatten() if results.pose_landmarks else np.zeros(33*4)
    face = np.array([[res.x, res.y, res.z] for res in results.face_landmarks.landmark]).flatten() if results.face_landmarks else np.zeros(468*3)
    lh = np.array([[res.x, res.y, res.z] for res in results.left_hand_landmarks.landmark]).flatten() if results.left_hand_landmarks else np.zeros(21*3)
    rh = np.array([[res.x, res.y, res.z] for res in results.right_hand_landmarks.landmark]).flatten() if results.right_hand_landmarks else np.zeros(21*3)
    return np.concatenate([pose, face, lh, rh])

Shehan Liyanage's avatar
Shehan Liyanage committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70
def pad_sequence(sequence, target_length):
    if len(sequence) < target_length:
        padding = np.zeros((target_length - len(sequence), sequence.shape[1]))
        sequence = np.vstack((padding, sequence))
    return sequence

def PredictSign(frame):
    with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:
        global sequence
        global sentence
        global predictions
        global threshold
        global count

Shehan Liyanage's avatar
Shehan Liyanage committed
71
        image, results = mediapipe_detection(frame, holistic)
Shehan Liyanage's avatar
Shehan Liyanage committed
72
        draw_landmarks(image, results)
Shehan Liyanage's avatar
Shehan Liyanage committed
73 74
        keypoints = extract_keypoints(results)
        sequence.append(keypoints)
Shehan Liyanage's avatar
Shehan Liyanage committed
75 76
        sequence = sequence[-50:]  # Keep the last 50 keypoints

Shehan Liyanage's avatar
Shehan Liyanage committed
77
        if len(sequence) == 50:
Shehan Liyanage's avatar
Shehan Liyanage committed
78 79
            padded_sequence = pad_sequence(np.array(sequence), 50)
            res = model.predict(np.expand_dims(padded_sequence, axis=0))[0]
Shehan Liyanage's avatar
Shehan Liyanage committed
80
            predictions.append(np.argmax(res))
Shehan Liyanage's avatar
Shehan Liyanage committed
81
            if np.unique(predictions[-3:])[0] == np.argmax(res):
Shehan Liyanage's avatar
Shehan Liyanage committed
82 83 84 85
                if res[np.argmax(res)] > threshold:
                    if len(sentence) > 0:
                        if actions[np.argmax(res)] != sentence[-1]:
                            sentence.append(actions[np.argmax(res)])
Shehan Liyanage's avatar
Shehan Liyanage committed
86
                            return sentence[-1]
Shehan Liyanage's avatar
Shehan Liyanage committed
87 88
                    else:
                        sentence.append(actions[np.argmax(res)])
Shehan Liyanage's avatar
Shehan Liyanage committed
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
                        return sentence[-1]
            else:
                pass
        else:
            count -= 1

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'
socketio = SocketIO(app, cors_allowed_origins='*')

@app.route('/')
def index():
    return 'Running'

@socketio.on('connect')
def on_connect():
    emit('me', request.sid)

@socketio.on('disconnect')
def on_disconnect():
    send('callEnded', broadcast=True)

@socketio.on('predictionVideo')
def on_prediction_video(data):
    global actions
    img_bytes = base64.b64decode(data.split(',')[1])
    np_arr = np.frombuffer(img_bytes, np.uint8)
    img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
    ans = PredictSign(img)
    print(ans)
    emit('predictionVideo', ans)

@socketio.on('callUser')
def on_call_user(data):
    from_user = data['from']
    userToCall = data['userToCall']
    caller_name = data['name']
    signal = data['signalData']
    emit('callUser', {'from': from_user, 'name': caller_name, 'signal': signal}, room=userToCall)

@socketio.on('answerCall')
def on_answer_call(data):
    emit('callAccepted', data['signal'], room=data['to'])
Shehan Liyanage's avatar
Shehan Liyanage committed
132 133

if __name__ == '__main__':
Shehan Liyanage's avatar
Shehan Liyanage committed
134
    socketio.run(app, debug=True, port=5000)