translator.py 2.43 KB
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author: Caio Marcelo Campoy Guedes
E-Mail: caiomcg@gmail.com

Author: Erickson Silva
E-Mail: erickson.silva@lavid.ufpb.br

Author: Jorismar Barbosa
E-Mail: jorismar.barbosa@lavid.ufpb.br

Author: Wesnydy Lima Ribeiro
E-Mail: wesnydy@lavid.ufpb.br
"""

import json
import logging
import os
import pika
import PikaManager

from PortGlosa import traduzir
from thread import start_new_thread
from time import sleep

# Logging configuration.
logger = logging.getLogger("translator")
logger.setLevel(logging.DEBUG)

fh = logging.FileHandler("/home/vlibras/log/translator.log")
fh.setLevel(logging.DEBUG)

ch = logging.StreamHandler()
ch.setLevel(logging.INFO)

formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
fh.setFormatter(formatter)
ch.setFormatter(formatter)

logger.addHandler(fh)
logger.addHandler(ch)

# Manager of queues connections.
#manager = PikaManager.PikaManager("150.165.205.10", "test", "test")

manager = PikaManager.PikaManager("rabbit")

def run(ch, method, properties, body):
	"""
    Execute the worker.

    Parameters
    ----------
    ch : object
        Channel of communication.
    method : function
        Callback method.
    properties : object
        Message containing a set of 14 properties.
    body : string
        Json string containing the necessary arguments for workers.
    """
	body = json.loads(body)
	print ("Translating...")
	try:
		logger.info("Translating: "+body["text"]+" id: "+properties.correlation_id.encode("utf-8"))
		gloss = traduzir(body["text"].encode("utf-8"))
		# Add gloss key with glosa content on the body.
		body["gloss"] = gloss
		# Remove text translated.
		del body["text"]
	except KeyError:
		pass

	logger.info("Sending gloss to the translations queue")
	manager.send_to_queue("translations", body, properties)
	print ("Ok")

def keep_alive(conn_send, conn_receive):
	"""
    Keep the connection alive.

    Parameters
    ----------
    conn_send : object
        Connection of writer.
    conn_receive : object
        Connection of receiver.
    """
	while True:
		sleep(30)
		try:
			conn_send.process_data_events()
			conn_receive.process_data_events()
		except:
			continue

start_new_thread(keep_alive, (manager.get_conn_send(), manager.get_conn_receive()))

print("Translator listening...")
while True:
	try:
		manager.receive_from_queue("extractions", run)
	except KeyboardInterrupt:
		manager.close_connections()
		os._exit(0)