Esempio n. 1
0
async def message_handler(msg):
    global msgs_received, msgs_sent, params
    subject = msg.subject
    reply = msg.reply
    # data = msg.data.decode()
    # print("Received a message on '{subject} {reply}': {data}".format(
    #    subject=subject, reply=reply))
    msgs_received += 1
    if msgs_received % 100 == 0:
        print('msgs_received: ', msgs_received)
    # print("processed {data}".format(data=_msg.SerializeToString()))
    # ***************** your app's business logic here ********************
    # RFC: We could leverage `reply` topic as the destination topic which would not require DST_NATS_TOPIC to be provided
    # await nc.publish(reply, data)
    # ---------Busines logic-------------
    _msg = xi_iot_pb2.DataStreamMessage()
    _msg.ParseFromString(msg.data)
    image = Image.open(io.BytesIO(_msg.payload)).convert('RGB')
    image_np = np.array(image)
    if msgs_sent % 20 == 0:
        sql = """INSERT INTO detections(room,num)
             VALUES(%s,%s);"""
        d_num = detect(image_np)
        conn = None
        try:
            # connect to the PostgreSQL database
            conn = psycopg2.connect(**params)
            # create a new cursor
            cur = conn.cursor()
            # execute the INSERT statement
            cur.execute(sql, (
                'HQ1-511-Fuchsia (Cisco Room 14)',
                d_num,
            ))
            # commit the changes to the database
            conn.commit()
            # close communication with the database
            cur.close()
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        finally:
            if conn is not None:
                conn.close()
        print("Detect msg_sent: %d" % msgs_sent)
    image_str = draw_boxes(image_np)
    _msg = xi_iot_pb2.DataStreamMessage()
    _msg.payload = image_str
    print("Msgs_sent: %d" % msgs_sent)
    await nc.publish(dst_nats_topic, _msg.SerializeToString())
    # -------------------------------------
    # print("message published")
    msgs_sent += 1
    if msgs_sent % 100 == 0:
        print('msgs sent: ', msgs_sent)
Esempio n. 2
0
async def message_handler(msg):
    try:
        logger.info("Received a message!")
        _msg = xi_iot_pb2.DataStreamMessage()
        _msg.ParseFromString(msg.data)

        # Create a recognition command mix
        command = create_workflow_command_mix()

        # This assumes a mono-input network
        image_input = v07_ImageInput(source=b'data:image/*;binary,' +
                                     _msg.payload)
        inputs = create_images_input_mix([image_input])

        # Send the request
        logger.info("Sending inference request to worker")
        correlation_id = client.command(command_queue_name,
                                        response_queue.name, inputs, command)

        # Wait for response, `timeout=float('inf')` or `timeout=-1` for infinite wait, `timeout=None` for non blocking
        response = consumer.get(correlation_id, timeout=-1)
        # Put data as returned by Deepomatic API v0.7
        data = {
            'outputs': [
                MessageToDict(o,
                              preserving_proto_field_name=True,
                              including_default_value_fields=True)
                for o in response.to_parsed_result_buffer()
            ]
        }
        logger.info("Got inference response: {}".format(data))

        # Drawn label on image
        label = data['outputs'][0]['labels']['predicted'][0]['label_name']
        img = Image.open(io.BytesIO(_msg.payload))
        draw = ImageDraw.Draw(img)
        draw.text((10, 10), label, (255, 255, 255), font=font)
        with io.BytesIO() as buff:
            img.save(buff, format="JPEG")
            _msg = xi_iot_pb2.DataStreamMessage()
            _msg.payload = buff.getvalue()

        # RFC: We could leverage `reply` topic as the destination topic which would not require DST_NATS_TOPIC to be provided
        # await nc.publish(reply, data)
        await nc.publish(dst_nats_topic, _msg.SerializeToString())
    except Exception as e:
        logger.error("{}".format(e))
Esempio n. 3
0
async def publish(loop):
    nc = NATS()
    await nc.connect(nats_broker_url, loop=loop)
    i = 0
    base_msg = "this is jpeg {i}"
    while True:
        _msg = xi_iot_pb2.DataStreamMessage()
        _msg.payload = str.encode(base_msg.format(i=i))
        await nc.publish(dst_nats_topic, _msg.SerializeToString())
        await asyncio.sleep(2)
        i += 1
Esempio n. 4
0
async def message_handler(msg):
    global success
    try:
        logger.info("Received image from runtime")
        _msg = xi_iot_pb2.DataStreamMessage()
        _msg.ParseFromString(msg.data)

        img = Image.open(io.BytesIO(_msg.payload))
        img.save("result.jpg")
        success = True
    except Exception as e:
        logger.error("{}".format(e))
Esempio n. 5
0
 async def _message_handler(self, msg):
     ds_msg = xi_iot_pb2.DataStreamMessage()
     ds_msg.ParseFromString(msg.data)
     try:
         ds_msg.payload = self.func(ds_msg.payload)  # TODO error handling
     except Exception as e:
         logging.error("failed to process message #{}: {}".format(
             self.msg_idx, e))
     if self.msg_idx % 100 == 0:
         logging.info("processed message #{}".format(self.msg_idx))
     try:
         await self.nc.publish(str(self.dst_topic),
                               ds_msg.SerializeToString())
     except Exception as e:
         logging.error("failed to publish message #{}: {}".format(
             self.msg_idx, e))
     self.msg_idx += 1
Esempio n. 6
0
async def message_handler(msg):
    # print('recieved msg')
    global msgs_received, msgs_sent
    subject = msg.subject
    reply = msg.reply
    # data = msg.data.decode()
    # print("Received a message on '{subject} {reply}': {data}".format(
    #    subject=subject, reply=reply))
    msgs_received += 1
    if msgs_received % 100 == 0:
        print('msgs_received: ', msgs_received)
    _msg = xi_iot_pb2.DataStreamMessage()
    _msg.ParseFromString(msg.data)
    # print("processed {data}".format(data=_msg.SerializeToString()))
    # ***************** your app's business logic here ********************
    # RFC: We could leverage `reply` topic as the destination topic which would not require DST_NATS_TOPIC to be provided
    # await nc.publish(reply, data)
    await nc.publish(dst_nats_topic, _msg.SerializeToString())
    msgs_sent += 1
    if msgs_sent % 100 == 0:
        print('msgs sent: ', msgs_sent)
Esempio n. 7
0
async def publish(loop):
    nc = NATS()

    logging.info("broker: {b}, src topic: {s}, dst_topic: {d}".format(
        b=nats_broker_url, s=src_nats_topic, d=dst_nats_topic))
    await nc.connect(nats_broker_url, loop=loop)

    _msg = xi_iot_pb2.DataStreamMessage()
    _msg.payload = image

    logger.info("Subscribe to result topic: {}".format(dst_nats_topic))
    sid = await nc.subscribe(dst_nats_topic, cb=message_handler)

    logger.info("Sending image to source topic: {}".format(src_nats_topic))
    await nc.publish(src_nats_topic, _msg.SerializeToString())

    # Wait one second until message_handler is called
    await asyncio.sleep(10)

    # Remove interest in subscription.
    await nc.unsubscribe(sid)

    # Terminate connection to NATS.
    await nc.close()