-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrmq_communication.py
58 lines (43 loc) · 1.83 KB
/
rmq_communication.py
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
import os
import pika
import json
import requests
from get_text import get_text, preprocessing
import utils
from dotenv import load_dotenv
load_dotenv()
HOST = os.getenv("HOST")
SENDER_QUEUE_NAME = os.getenv("SENDER_QUEUE_NAME")
CONSUMER_QUEUE_NAME = os.getenv("CONSUMER_QUEUE_NAME")
print(HOST, SENDER_QUEUE_NAME, CONSUMER_QUEUE_NAME)
connection = pika.BlockingConnection(pika.ConnectionParameters(HOST))
rmq_channel = connection.channel()
session = requests.Session()
rmq_channel.exchange_declare(exchange=SENDER_QUEUE_NAME, exchange_type='topic', durable=True)
def send(message: str) -> None:
print(message)
rmq_channel.basic_publish(exchange=SENDER_QUEUE_NAME, routing_key=SENDER_QUEUE_NAME, body=message)
def on_message(channel, method_frame, header_frame, body) -> None:
rmq_channel.basic_ack(method_frame.delivery_tag)
data = json.loads(body)
print(body)
if not utils.download_image(session, data["url"], "temp.png"):
return None
rect = data["rect"]
data.pop("url")
data.pop("rect")
data.update([("data", dict().fromkeys(["text"], [""]))])
data["data"]["text"] = get_text(preprocessing("temp.png", [int(rect["x"]), int(rect["y"]),
int(rect["width"]), int(rect["height"])]))\
.replace('\x0c', '')
send(json.dumps(data, separators=(',', ':'), ensure_ascii=False))
result = rmq_channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
rmq_channel.queue_bind(exchange=CONSUMER_QUEUE_NAME, queue=queue_name, routing_key=CONSUMER_QUEUE_NAME)
rmq_channel.basic_consume(
queue=queue_name, on_message_callback=on_message, auto_ack=False)
try:
rmq_channel.start_consuming()
except KeyboardInterrupt:
rmq_channel.close()
session.close()