Fun with websockets and monkeylearn

 


The code pieces are a python tornado websocket server, a monkeylearning API client and a simple websocket python client to kick things off.

Python tornado websocket server:

import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.websocket as ws
from tornado.options import define, options
import time
import monkeyclient

define('port', default=5002, help='Server port')

class websocket_handler(ws.WebSocketHandler):
    @classmethod
    def route_urls(claz):
        return [(r'/',claz, {}),]
    
    def setup(self):
        self.last = time.time()
        self.stop = False
    
    def open(self):
        self.setup()
        print("New client connected")
        self.write_message("You are connected")
        
    def on_message(self, message):
        print("received message {}".format(message))
        self.write_message("You said {}\n{}".format(message,
                                                  monkeyclient.get_response([message])))
        self.last = time.time()
    
    def on_close(self):
        print("Client connection closed!")
        #self.loop.stop()
    
    def check_origin(self, origin):
        return True

def start_server():
    app = tornado.web.Application(websocket_handler.route_urls(), debug=True)
    server = tornado.httpserver.HTTPServer(app)
    server.listen(options.port)

    tornado.ioloop.IOLoop.instance().start()


if __name__ == '__main__':
    start_server()

Monkeylearning API client:

Check pre-built text analysis models at MonkeyLearn API, create a login for yourself and get the API key
from monkeylearn import MonkeyLearn

MLOBJ = MonkeyLearn("MY_API_KEY")
MODEL_ID = "cl_WDyr2Q4F"

def get_response(data):
    assert isinstance(data, list)
    response = MLOBJ.classifiers.classify(
                   model_id=MODEL_ID,
                   data=data,)
    if response.body is None:
        return "I could not analyze your message"
    else:
        classification = list(response.body)[0]['classifications'][0]['tag_name']
        confidence = list(response.body)[0]['classifications'][0]['confidence']

        return f"I predict with {confidence * 100}% confidence that your message belongs to '{classification}' category"

if __name__ == '__main__':
    print(get_response(["This is a test message"]))

Python websocket client:

from websocket import create_connection

def communicate():
    print(">> Initiating connection...")
    ws = create_connection("ws://localhost:5002/")
    result =  ws.recv()
    print(">> Received '%s'" % result)
    while True:
       message = input(">> Your message $ ")
       ws.send(message)
       print(">> Sent message")
       result =  ws.recv()
       print(">> Received '%s'" % result)
if __name__ == '__main__':
    communicate()

Client server interaction:

(Python-3.7.4) debashish@debashish-Inspiron-20-Model-3048:~/Dev/pyscripts$ python tornadoclient.py 
>> Initiating connection...
>> Received 'You are connected'
>> Your message $ Football is a strenuous game
>> Sent message
>> Received 'You said Football is a strenuous game
I predict with 38.2% confidence that your message belongs to 'Sports' category'
>> Your message $ Tajmahal is in Agra
>> Sent message
>> Received 'You said Tajmahal is in Agra
I predict with 22.3% confidence that your message belongs to 'Arts & Culture' category'
>> Your message $ IBM planning about 10,000 job cuts in Europe ahead of unit sale
>> Sent message
>> Received 'You said IBM planning about 10,000 job cuts in Europe ahead of unit sale
I predict with 49.9% confidence that your message belongs to 'Business' category'
>> Your message $ Avocado is a nutritious food
>> Sent message
>> Received 'You said Avocado is a nutritious food
I predict with 22.5% confidence that your message belongs to 'Health & Living' category'
>> Your message $ 

In the next post, I will go over the nitty-gritty of websocket connections with an UI example.

Comments

Popular Posts