Skip to content

Instantly share code, notes, and snippets.

@sam-thecoder
Created January 4, 2019 05:28
Show Gist options
  • Save sam-thecoder/56d2ba174d6c8a695ee582a547e6298f to your computer and use it in GitHub Desktop.
Save sam-thecoder/56d2ba174d6c8a695ee582a547e6298f to your computer and use it in GitHub Desktop.
import asyncio
import websockets
import json
import string
import random
import pickle
def random_filename(path=None, length=None):
text = string.ascii_uppercase + string.ascii_lowercase + string.digits
if path == None:
path = 'pickle_cells/'
if length == None:
guess = random.randrange(15, 30)
length = range(guess)
return path + ''.join( [random.choice(text) for x in length] ) + '.pickle'
async def get_cells(websocket, path):
async for message in websocket:
#print(message)
#width, height = message['img_width'], message['img_height']
message = json.loads(message)
for area in message['areas']:
width, height, x, y = area['width'], area['height'], area['top'], area['left']
result = []
r_width, r_height = 0, 0
area = width * height
status = 0
for _ in range(area):
result.append([x+r_width, y+r_height])
r_width += 1
if r_width == width:
r_width = 0
r_height += 1
status += 1
percentage = (status/area) * 100
if percentage % 5 == 0:
await websocket.send(json.dumps({'complete': False, 'status': percentage}))
filename = random_filename()
with open(filename, 'wb') as f:
# Pickle the 'data' dictionary using the highest protocol available.
pickle.dump(result, f, pickle.HIGHEST_PROTOCOL)
await websocket.send(json.dumps({'complete': True, 'filename': filename}))
asyncio.get_event_loop().run_until_complete(
websockets.serve(get_cells, 'localhost', 8765))
asyncio.get_event_loop().run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment