Exemple #1
0
 def write_bbox(self, traces, time_consume):
     # cnt = 0
     # self.render_rect_cache[:] = [None] * self.cfg.cache_size
     for frame_idx, rects in traces.items():
         # old_rects = self.render_rect_cache[frame_idx % self.cache_size]
         if frame_idx in self.render_rect_cache:
             old_rects = self.render_rect_cache[frame_idx]
             self.render_rect_cache[frame_idx] = old_rects + rects
         else:
             self.render_rect_cache[frame_idx] = rects
         json_msg = creat_detect_msg_json(
             video_stream=self.cfg.rtsp,
             channel=self.cfg.channel,
             timestamp=get_local_time(time_consume),
             rects=rects,
             dol_id=self.dol_id,
             camera_id=self.cfg.camera_id,
             cfg=self.cfg)
         self.msg_queue.put(json_msg)
         # bbox rendering is post to render
         logger.debug(f'put detect message in msg_queue {json_msg}...')
         # print(rects)
     empty_msg = creat_detect_empty_msg_json(
         video_stream=self.cfg.rtsp,
         channel=self.cfg.channel,
         timestamp=get_local_time(time_consume),
         dol_id=self.dol_id,
         camera_id=self.cfg.camera_id)
     self.dol_id += 1
     self.msg_queue.put(empty_msg)
Exemple #2
0
def event_page(short_code=None):
    event = None
    try:
        event_id = short_url.decode_url(short_code)
        event = CtfEvent.query.get(event_id)

        event.local_start_date = get_local_time(event.start_date, request.remote_addr)
        event.local_end_date = get_local_time(event.end_date, request.remote_addr)
        event.details = json.loads(event.details)
    except Exception as e:
        print e
    return render_template('event.html', event=event, short_code=short_code)
Exemple #3
0
    async def bot_schedule(self):
        await self.wait_until_ready()
        channel = self.get_channel(main_channel)

        while not self.is_closed():
            # Update presence message
            activity = utils.jims_picker()
            await bot.change_presence(activity=discord.Game(activity))

            # Grabs the current time (Brisbane timezone)
            check_time = utils.get_local_time().time()

            # Good morning message (9am)
            if time(9, 0) <= check_time <= time(9, 2):
                await channel.send("Good Morning!")
                await self.send_motd()

            # New xkcd comic (3pm)
            if time(15, 0) <= check_time <= time(15, 2):
                check_day = datetime.utcnow().weekday()
                if check_day == 0 or check_day == 2 or check_day == 4:
                    await asyncio.sleep(60)
                    xkcd_comic = utils.get_xkcd()
                    await channel.send("New xkcd comic!")
                    await channel.send(xkcd_comic)

            # Sleep until the next hour
            minutesToSleep = 60 - datetime.utcnow().minute % 60
            await asyncio.sleep(minutesToSleep * 60)
Exemple #4
0
 def save_result(self, d):
     d['time'] = get_local_time()
     # save file result
     jpgdir = os.path.join(baseDir, RESULT_FILE)
     fobj = open(jpgdir, 'a+')
     fobj.write(json.dumps(d) + '\n')
     fobj.close()
def generate_weather_data(cities):
    full_weather_data = []
    for city in cities:
        latitude, longitude = utils.get_lat_and_lon()
        altitude = utils.get_altitude()
        local_time = utils.get_local_time()
        temperature = utils.get_temperature()
        pressure = utils.get_pressure()
        weather_condition = utils.get_condition(temperature)
        humidity = utils.get_humidity()

        entry = utils.create_weather_entry(city, latitude, longitude, altitude,
                                           local_time, weather_condition,
                                           temperature, pressure, humidity)
        full_weather_data.append(entry)
    return full_weather_data
Exemple #6
0
    async def bot_schedule(self):
        await self.wait_until_ready()
        channel = self.get_channel(MAIN_CHANNEL)

        while not self.is_closed():
            # Grabs the current time (Brisbane timezone)
            await self.update_activity()
            check_time = utils.get_local_time().time()

            # Good morning message (9am)
            if time(9, 0) <= check_time <= time(9, 2):
                await self.send_motd()

            # New xkcd comic (3pm)
            if time(15, 0) <= check_time <= time(15, 2):
                check_day = datetime.utcnow().weekday()
                if check_day == 0 or check_day == 2 or check_day == 4:
                    await self.send_xkcd()

            # Sleep until the next hour
            minutesToSleep = 60 - datetime.utcnow().minute % 60
            await asyncio.sleep(minutesToSleep * 60)
Exemple #7
0
# ┌────────────────────────────────────────────────────────────────────┐
# │                         Start training                             │
# └────────────────────────────────────────────────────────────────────┘
iterations = trainer.resume(checkpoint_directory,
                            param=config) if opts.resume else 0

to_pil = transforms.ToPILImage()

for epoch in range(config['n_epoch']):
    for it, (image_in, targets) in enumerate(train_loader):
        trainer.update_learning_rate()
        images_i, images_r, images_s, image_m = image_in.cuda().detach(), targets['albedo'].cuda().detach(), \
                                                targets['shading'].cuda().detach(), targets['mask'].cuda().detach()

        with Timer("<{}> [Epoch: {}] Elapsed time in update: %f".format(
                get_local_time(), epoch)):
            # ┌────────────────────────────────────────────────────────┐
            # │               Main training code                       │
            # └────────────────────────────────────────────────────────┘
            image_m = image_m > 0.1
            trainer.dis_update(images_i, images_r, images_s, config)
            trainer.gen_update(images_i, images_r, images_s, targets, config)
            torch.cuda.synchronize()

        # ┌────────────────────────────────────────────────────────────┐
        # │               Dump training stats in log file              │
        # └────────────────────────────────────────────────────────────┘
        if (iterations + 1) % config['log_iter'] == 0:
            print("<{}> Iteration: %08d/%08d".format(get_local_time()) %
                  (iterations + 1, max_iter))
            write_loss(iterations, trainer, train_writer)
Exemple #8
0
 def __str__(self):
     return "{}{}{}{}{}".format(self.block_no, self.nonce,
                                self.previous_hash,
                                get_local_time(self.timestamp), self.hash)
Exemple #9
0
def _updateTodo(todo, form):
    for k, v in form.items():
        setattr(todo, k, v)
    todo.ut = get_local_time(time.time())
Exemple #10
0
def time():
    context = get_local_time(request)
    return render_template('base.html', context=context)
Exemple #11
0
with torch.no_grad():
    t_bar = tqdm(test_list)
    t_bar.set_description('Processing')
    with open(log_pwd, 'w') as fid_w:
        for image_info in t_bar:
            img_pwd = image_info
            image = Image.open(img_pwd).convert('RGB')
            # cv2.imshow('{}'.format(CLASS_ID), np.asarray(image)[:, :, ::-1])
            # cv2.waitKey()
            label = int(os.path.dirname(img_pwd).split(os.sep)[-1].split('-')[0])
            image = transform(image)

            image = image.unsqueeze(0).cuda()

            pred = trainer.net(image)
            ps = torch.exp(pred)
            top_p, top_class = ps.topk(1, dim=1)
            accuracy = int(top_class.item() == label)
            accuracy_list.append(float(accuracy))

            if accuracy < 1:
                line_info = '{} | pred: {}, label: {}'.format(img_pwd, top_class.item(), label)
                print(line_info)
                fid_w.write(line_info + '\n')
                # cv2.imshow('error result', cv2.imread(img_pwd))
                # cv2.waitKey(10)

        mean_acc = np.mean(accuracy_list)
        print('\n<{}> Test result: accuracy: {}'.format(get_local_time(), mean_acc))
        fid_w.write('\n<{}> Test result: accuracy: {}\n'.format(get_local_time(), mean_acc))
Exemple #12
0
        # cv2.imshow('image out', np.asarray(img_out)[:, :, ::-1])
        # cv2.waitKey()
        #
        # continue

        # trainer.dis_update(images_in, images_out, config)
        trainer.gen_update(images_in, images_out, config)

        # Dump training stats in log file
        # if (iterations + 1) % config['log_iter'] == 0:
        #     print('<{}> [Epoch: {}] [Iter: {}/{}] | Loss: {}'.format(get_local_time(), epoch, it, len(train_loader),
        #                                                              to_number(trainer.loss_total)))
        if (iterations + 1) % config['log_iter'] == 0:
            print(
                '<{}> [Epoch: {}] [Iter: {}/{}] | [Loss] Pixel: {}, Pair: {}, GT: {}, Total: {}'
                .format(get_local_time(), epoch, it, len(train_loader),
                        to_number(trainer.loss_pixel),
                        to_number(trainer.loss_pair),
                        to_number(trainer.loss_gt),
                        to_number(trainer.loss_total)))
            write_loss(iterations, trainer, train_writer)

        # Write images
        # if (iterations + 1) % config['image_save_iter'] == 0:
        #     with torch.no_grad():
        #         outputs = trainer.sample(images_in, images_out)
        #     # write_2images(outputs, display_size, image_directory, 'train_%08d' % (iterations + 1))
        #     # HTML
        #     write_html(output_directory + "/index.html", iterations + 1, config['image_save_iter'], 'images')

        iterations += 1
Exemple #13
0
 def __init__(self, form):
     self.id = self.getid()
     self.title = form.get("title", "")
     self.ct = get_local_time(time.time())
     self.ut = self.ct
Exemple #14
0
        # for i in range(0, images.shape[0]):
        #     img_i = images[i].cpu()
        #     img_i = img_i * 0.225 + 0.45
        #     img_i = to_pil(img_i)
        #     print(labels[i].item())
        #     cv2.imshow('image i', np.asarray(img_i)[:, :, ::-1])
        #     cv2.waitKey()
        # continue

        loss, acc = trainer.update(images, labels)
        log_counter += 1

        if log_counter % config['log_iter'] == 0:
            print(
                "<%s> Epoch: %03d/%03d, Iteration: %03d/%03d, Loss: %.8f, Acc: %.3f"
                % (get_local_time(), epoch + 1, config['n_epochs'], it + 1,
                   len(train_loader), loss, acc))
            iterations = epoch * len(train_loader) + it + 1
            write_loss(iterations, trainer, train_writer)

    if (epoch + 1) % config['test_iter'] == 0:
        t_bar = tqdm.tqdm(test_loader)
        t_bar.set_description('Epoch: {} - Testing'.format(epoch + 1))
        losses = []
        accuracy_list = []
        for (images, labels) in t_bar:
            images = images.cuda()
            labels = labels.cuda()
            loss, accuracy = trainer.evaluate(images, labels)
            losses.append(loss)
            accuracy_list.append(accuracy)
Exemple #15
0
    t_bar = tqdm(eval_list)
    t_bar.set_description('Processing')
    with open(log_pwd, 'w') as fid_w:
        for image_info in t_bar:
            img_pwd, label = image_info.split(' ')
            image = Image.open(img_pwd).convert('RGB')
            label = int(label)
            image = transform(image)

            image = image.unsqueeze(0).cuda()

            pred = trainer.model(image)
            ps = torch.exp(pred)
            top_p, top_class = ps.topk(1, dim=1)
            accuracy = int(top_class.item() == label)
            accuracy_list.append(float(accuracy))

            if accuracy < 1:
                line_info = '{} | pred: {}, label: {}'.format(
                    img_pwd, int(top_class.item()), int(label))
                # print(line_info)
                fid_w.write(line_info + '\n')
                # cv2.imshow('error result', cv2.imread(img_pwd))
                # cv2.waitKey(10)

        mean_acc = np.mean(accuracy_list)
        print('\n<{}> Eval result: accuracy: {}'.format(
            get_local_time(), mean_acc))
        fid_w.write('\n<{}> Eval result: accuracy: {}\n'.format(
            get_local_time(), mean_acc))