forked from ArmaanSeth/EyeDirection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
93 lines (72 loc) · 2.83 KB
/
server.py
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
# import asyncio
# import websockets
# import cv2
# import numpy as np
# from test import Process
# async def handle_client(websocket, path):
# print("Someone connected")
# process=Process()
# try:
# while True:
# data = await websocket.recv()
# nparr = np.frombuffer(data, np.uint8)
# img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# response=process.ProcessImage(img_np)
# if response=="1":
# print("=============================Cheater=============================")
# await websocket.send(response)
# except websockets.exceptions.ConnectionClosed:
# print("Someone disconnected")
# if __name__ == "__main__":
# start_server = websockets.serve(handle_client, 'localhost', 8756)
# asyncio.get_event_loop().run_until_complete(start_server)
# asyncio.get_event_loop().run_forever()
from multiprocessing import process
from urllib import response
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
import numpy as np
import cv2
from test import Process
from fastapi.staticfiles import StaticFiles
app = FastAPI()
class ConnectionManager:
def __init__(self):
self.active_connections: list[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.process = Process()
self.active_connections.append(websocket)
async def send_personal_message(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message)
def disconnect(self, websocket: WebSocket):
self.process = None
self.active_connections.remove(websocket)
manager = ConnectionManager()
@app.get("/", status_code=200)
async def get():
# return success message and staus code
return {"status": "success", "message": "Server is running"}
@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_bytes()
nparr = np.frombuffer(data, np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
response = manager.process.ProcessImage(img_np)
if response == "1":
print(
"=============================Cheater============================="
)
await manager.send_personal_message(f"{response}", websocket)
except WebSocketDisconnect:
manager.disconnect(websocket)
# write a get request to ping server and send response
@app.get("/ping", status_code=200)
async def ping():
return {"response": "pong"}