translator.py
2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/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)