fixed bugs in gradiome file

This commit is contained in:
Abubakar Abid 2018-12-19 23:41:24 -08:00
parent 9018c54b4f
commit ef1aa3459e
5 changed files with 162 additions and 42 deletions

55
.idea/workspace.xml generated
View File

@ -2,16 +2,11 @@
<project version="4">
<component name="ChangeListManager">
<list default="true" id="fd73cd66-e80f-470e-a2ec-e220d3b6b864" name="Default Changelist" comment="">
<change afterPath="$PROJECT_DIR$/gradiome.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Pipfile" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/Procfile" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/README.md" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/gradiome/__init__.py" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/gradiome/settings.py" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/gradiome/static/humans.txt" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/gradiome/urls.py" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/gradiome/wsgi.py" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/manage.py" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/css/download (1).png" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/css/download (2).png" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/css/download.png" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/gradiome.py" beforeDir="false" afterPath="$PROJECT_DIR$/gradiome.py" afterDir="false" />
</list>
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="SHOW_DIALOG" value="false" />
@ -47,36 +42,37 @@
<counts>
<entry key="css" value="1" />
<entry key="html" value="1491" />
<entry key="py" value="910" />
<entry key="py" value="2465" />
</counts>
</usages-collector>
<usages-collector id="statistics.file.types.edit">
<counts>
<entry key="CSS" value="1" />
<entry key="HTML" value="1491" />
<entry key="Python" value="910" />
<entry key="Python" value="2465" />
</counts>
</usages-collector>
</session>
</component>
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file pinned="false" current-in-tab="false">
<file pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/gradiome.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="221">
<caret line="13" column="7" selection-start-line="13" selection-start-column="7" selection-end-line="13" selection-end-column="7" />
<state relative-caret-position="425">
<caret line="94" column="96" selection-start-line="94" selection-start-column="96" selection-end-line="94" selection-end-column="96" />
<folding>
<element signature="e#76#90#0" expanded="true" />
<element signature="e#0#35#0" expanded="true" />
<marker date="1545291382009" expanded="true" signature="4437:5228" ph="..." />
</folding>
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="true">
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/templates/draw_a_digit.html">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="440">
<state relative-caret-position="1479">
<caret line="87" selection-start-line="87" selection-end-line="87" />
</state>
</provider>
@ -126,6 +122,8 @@
<find>ctx</find>
<find>clear-b</find>
<find>css/</find>
<find>communica</find>
<find>communicate</find>
</findStrings>
<replaceStrings>
<replace>400</replace>
@ -149,10 +147,10 @@
<option value="$PROJECT_DIR$/home/routing.py" />
<option value="$PROJECT_DIR$/gradiome/routing.py" />
<option value="$PROJECT_DIR$/home/consumers.py" />
<option value="$PROJECT_DIR$/gradiome.py" />
<option value="$PROJECT_DIR$/css/starter-template.css" />
<option value="$PROJECT_DIR$/client.html" />
<option value="$PROJECT_DIR$/templates/draw_a_digit.html" />
<option value="$PROJECT_DIR$/gradiome.py" />
</list>
</option>
</component>
@ -299,20 +297,21 @@
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/gradiome.py">
<entry file="file://$PROJECT_DIR$/templates/draw_a_digit.html">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="221">
<caret line="13" column="7" selection-start-line="13" selection-start-column="7" selection-end-line="13" selection-end-column="7" />
<folding>
<element signature="e#76#90#0" expanded="true" />
</folding>
<state relative-caret-position="1479">
<caret line="87" selection-start-line="87" selection-end-line="87" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/templates/draw_a_digit.html">
<entry file="file://$PROJECT_DIR$/gradiome.py">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="440">
<caret line="87" selection-start-line="87" selection-end-line="87" />
<state relative-caret-position="425">
<caret line="94" column="96" selection-start-line="94" selection-start-column="96" selection-end-line="94" selection-end-column="96" />
<folding>
<element signature="e#0#35#0" expanded="true" />
<marker date="1545291382009" expanded="true" signature="4437:5228" ph="..." />
</folding>
</state>
</provider>
</entry>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

View File

@ -1,20 +1,141 @@
#!/usr/bin/env python
# WS server that sends messages at random intervals
from abc import ABC, abstractmethod
import base64
import asyncio
import datetime
import random
import websockets
import nest_asyncio
from PIL import Image
from io import BytesIO
import numpy as np
import os
import webbrowser
nest_asyncio.apply()
LOCALHOST_IP = '127.0.0.1'
SOCKET_PORT = 5679
async def time(websocket, path):
while True:
input = await websocket.recv()
print(input)
websocket.send(random.randint(0, 9))
def resize_and_crop(img, size, crop_type='top'):
"""
Resize and crop an image to fit the specified size.
args:
img_path: path for the image to resize.
modified_path: path to store the modified image.
size: `(width, height)` tuple.
crop_type: can be 'top', 'middle' or 'bottom', depending on this
value, the image will cropped getting the 'top/left', 'midle' or
'bottom/rigth' of the image to fit the size.
raises:
Exception: if can not open the file in img_path of there is problems
to save the image.
ValueError: if an invalid `crop_type` is provided.
"""
# Get current and desired ratio for the images
img_ratio = img.size[0] / float(img.size[1])
ratio = size[0] / float(size[1])
# The image is scaled/cropped vertically or horizontally depending on the ratio
if ratio > img_ratio:
img = img.resize((size[0], size[0] * img.size[1] / img.size[0]),
Image.ANTIALIAS)
# Crop in the top, middle or bottom
if crop_type == 'top':
box = (0, 0, img.size[0], size[1])
elif crop_type == 'middle':
box = (0, (img.size[1] - size[1]) / 2, img.size[0], (img.size[1] + size[1]) / 2)
elif crop_type == 'bottom':
box = (0, img.size[1] - size[1], img.size[0], img.size[1])
else:
raise ValueError('ERROR: invalid value for crop_type')
img = img.crop(box)
elif ratio < img_ratio:
img = img.resize((size[1] * img.size[0] / img.size[1], size[1]),
Image.ANTIALIAS)
# Crop in the top, middle or bottom
if crop_type == 'top':
box = (0, 0, size[0], img.size[1])
elif crop_type == 'middle':
box = ((img.size[0] - size[0]) / 2, 0, (img.size[0] + size[0]) / 2, img.size[1])
elif crop_type == 'bottom':
box = (img.size[0] - size[0], 0, img.size[0], img.size[1])
else:
raise ValueError('ERROR: invalid value for crop_type')
img = img.crop(box)
else:
img = img.resize((size[0], size[1]),
Image.ANTIALIAS)
# If the scale is the same, we do not need to crop
return img
start_server = websockets.serve(time, '127.0.0.1', 5679)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
class AbstractInterface(ABC):
"""
An abstract class for defining the methods that all gradio interfaces should have.
"""
def __init__(self, model_type, model_obj, **model_params):
"""
:param model_type: what kind of trained model, can be 'keras' or 'sklearn'.
:param model_obj: the model object, such as a sklearn classifier or keras model.
:param model_params: additional model parameters.
"""
self.model_type = model_type
self.model_obj = model_obj
self.model_params = model_params
super().__init__()
def start(self):
"""
Standard method shared by interfaces that launches a websocket at a specified IP address.
"""
webbrowser.open('file://' + os.path.realpath(self._get_template_path()))
start_server = websockets.serve(self.communicate, LOCALHOST_IP, SOCKET_PORT)
asyncio.get_event_loop().run_until_complete(start_server)
try:
asyncio.get_event_loop().run_forever()
except RuntimeError: # Runtime errors are thrown in jupyter notebooks because of async.
pass
@abstractmethod
def _get_template_path(self):
"""
All interfaces should define a method that returns the path to its template.
"""
pass
@abstractmethod
async def communicate(self, websocket, path):
"""
All interfaces should define a custom method that defines how they communicate with the websocket.
"""
pass
class DrawADigit(AbstractInterface):
def predict(self, array):
if self.model_type=='sklearn':
return self.model_obj.predict(array)[0]
else:
raise ValueError('model_type must be sklearn.')
def _get_template_path(self):
return 'templates/draw_a_digit.html'
def start(self):
super().start()
async def communicate(self, websocket, path):
"""
Method that defines how this interface communicates with the websocket.
:param websocket: a Websocket object used to communicate with the interface frontend
:param path: ignored
"""
while True:
imgstring = await websocket.recv()
content = imgstring.split(';')[1]
image_encoded = content.split(',')[1]
body = base64.decodebytes(image_encoded.encode('utf-8'))
im = Image.open(BytesIO(base64.b64decode(image_encoded))).convert('L')
im = resize_and_crop(im, (28, 28))
array = np.array(im).flatten().reshape(1, -1)
prediction = self.predict(array)
await websocket.send(str(prediction))