Skip to content

Instantly share code, notes, and snippets.

@Alladin9393
Created October 12, 2020 08:55
Show Gist options
  • Save Alladin9393/52c22ac263684d878ce8819642a07f1a to your computer and use it in GitHub Desktop.
Save Alladin9393/52c22ac263684d878ce8819642a07f1a to your computer and use it in GitHub Desktop.
Interaction with pattern recognition server
import asyncio
import time
import hashlib
import json
import websockets
import numpy
from statprly import MonoDigitRecognizer
def get_session_id():
encoded_time = hex(int(time.time())).encode()
time_hash = hashlib.sha1(encoded_time).digest()
return time_hash.hex()
SESSION_ID = get_session_id()
URI = "wss://sprs.herokuapp.com/first/" + SESSION_ID
SCALE = 5
NOISE = 0.44
TOTAL_STEPS = 30
async def server_interactor():
async with websockets.connect(URI, ping_interval=5000) as websocket:
start_message = {
'data': {
'message': "Let's start",
}
}
await websocket.send(json.dumps(start_message))
response = await websocket.recv()
response = json.loads(response)
width = response['data']['width'] * SCALE
height = response['data']['height'] * SCALE
req = {
'data': {
'width': width,
'height': height,
'totalSteps': TOTAL_STEPS,
'noise': NOISE,
'shuffle': False,
},
}
await websocket.send(json.dumps(req))
response = await websocket.recv()
with open('custom_standardts_data/standards_with_scale.json', 'w') as f:
d = json.loads(response)
json.dump(d['data'], f)
recognizer = MonoDigitRecognizer(digit_standards_path='custom_standardts_data/standards_with_scale.json')
for step in range(0, TOTAL_STEPS):
req = {
'data': {
'message': 'Ready'
}
}
await websocket.send(json.dumps(req))
response = await websocket.recv()
response = json.loads(response)
data_to_recognize = numpy.array(response['data']['matrix'])
recognized_digit = recognizer.recognize(data_to_recognize, NOISE)
print("recognized_digit: ", recognized_digit)
req = {
'data': {
'step': step + 1,
'answer': str(recognized_digit),
}
}
await websocket.send(json.dumps(req))
response = await websocket.recv()
response = json.loads(response)
print(response)
req = {'data': {'message': 'Bye'}}
await websocket.send(json.dumps(req))
response = await websocket.recv()
response = json.loads(response)
print(response)
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(server_interactor())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment