import json import os import time import uuid import pika class Worker: def __init__(self, mq_host, mq_port, data_dir): self._parameters = pika.ConnectionParameters(host=mq_host, port=mq_port) self._data_dir = data_dir def produce_image_caption(self, image_url): return str(abs(hash(image_url)) % (10 ** 8)) def run(self): while True: try: connection = pika.BlockingConnection(self._parameters) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) channel.queue_declare(queue='result_queue', durable=True) channel.confirm_delivery() channel.basic_qos(prefetch_count=1) channel.basic_consume(queue='task_queue', on_message_callback=self.process) channel.start_consuming() except Exception: time.sleep(1) def process(self, channel, method, properties, body): task = json.loads(body) path = os.path.join(self._data_dir, f"{task['image_id']}.txt") if not os.path.exists(path): temp_path = f'{path}.{uuid.uuid4()}' with open(temp_path, 'w', encoding='utf-8') as file: file.write(self.produce_image_caption(task['image_url'])) os.replace(temp_path, path) channel.basic_publish( exchange='', routing_key='result_queue', body=task['image_id'], properties=pika.BasicProperties(delivery_mode=2)) channel.basic_ack(delivery_tag=method.delivery_tag) if __name__ == '__main__': worker = Worker('rabbitmq', 5672, '/data') worker.run()