Example #1
0
def to_http(config, base_url):
    start = time()
    retry_strategy = Retry(total=5,
                           status_forcelist=[500, 502, 503, 504],
                           method_whitelist=["POST"],
                           backoff_factor=3)
    http = sessions.BaseUrlSession(base_url=BASE_URL())
    adaptor = HTTPAdapter(max_retries=retry_strategy)
    http.adapters = {"https://": adaptor, "http://": adaptor}

    while not quitevent.is_set():
        for item in config.generator:
            item['image'] = image_to_base64(item['image'])
            header = dict(sent_from=gethostname(),
                          uptime=str(time() - start),
                          device_name=str(config.device_name))
            data = dict(device_name=item['device_name'],
                        timestamp=datetime.utcnow().replace(
                            tzinfo=pytz.utc).isoformat(),
                        confidence=item['is_bad'],
                        coordinates=[item['lat'], item['lon']],
                        photo_data=item['image'])
            http.post(f"{base_url}/dev/upload",
                      data=dumps(data),
                      headers=header)
Example #2
0
def image_generator(camera: Camera,
                    gps: GPS,
                    model_path: str,
                    device_name: str,
                    min_predict_score: float,
                    sleep_time=5):
    if not Path(model_path).exists():
        raise FileNotFoundError(f"Couldn't load model file {model_path}")
    model = torch.load(model_path, map_location=torch.device('cpu'))
    model.eval()
    # While we don't have a kill signal
    while not quitevent.is_set():
        if not gps.gps_is_ready:
            logger.info(f"GPS not ready waiting {sleep_time}")
            gps.read_until_gps(300)
        else:
            try:
                lat, lon = gps.read_until_gps(300)
            except TypeError:
                # will return none if we couldn't get a GPS reading in _timeout_ time.
                continue
            image, tensor = camera.capture_still()
            t2_var = Variable(tensor, requires_grad=False).float()
            prediction = model(t2_var)
            data = prediction.data[0]
            output = dict(lat=lat,
                          lon=lon,
                          image=image,
                          is_good=float(data[0]),
                          is_bad=float(data[1]),
                          device_name=device_name)
            if output['is_bad'] > min_predict_score:
                yield output
Example #3
0
def to_file(config, file_path):
    # Friendly debugging command.
    serial = get_serial_number()
    image_int = 0
    file_path = Path(file_path)
    if file_path.is_file():
        raise FileExistsError(
            f"Inputted directory {file_path.absolute()} is a file")
    if not file_path.exists():
        file_path.mkdir(parents=True)
    while not quitevent.is_set():
        for image in config.generator:
            image_int += 1
            PIL_IMAGE.fromarray(image).save(
                f'{file_path.absolute()}/{image_int}.jpeg')
            with session_with_retry_policy() as Session:
                data = generate_payload(config=config, image=image)
                try:
                    response = Session.post(f"{config.gateway_url}upload",
                                            data=dumps(data))
                    with open(f"{file_path.absolute()}/{image_int}.txt",
                              'wb') as fp:
                        fp.write(response.content.decode('utf-8'))

                except Exception as e:
                    logger.warning(
                        f"got error {e} with payload {data} continuing anyway")
                    pass
Example #4
0
 def __update(self):
     # Short circuit on signal or stopped flag.
     while not quitevent.is_set() or not self.stopped:
         # video is lower quality but faster.
         for frame in self.capture_continuous(self.__capture_stream,
                                              format='jpeg',
                                              use_video_port=True):
             self.last_image = deepcopy(
                 PIL_IMAGE.open(self.__capture_stream))
             self.__capture_stream.seek(0)
             self.updated = True
Example #5
0
 def continue_until_stopped(self):
     while not quitevent.is_set():
         if self.__stop:
             break
         try:
             self.session.post(self.gateway_url,
                               data=dumps(
                                   dict(device_serial=self.serial,
                                        device_name=self.device_name)))
             sleep(30)
         except Exception as e:
             logger.debug(f"Error code {e} while pinging")
             sleep(30)
Example #6
0
def to_stdout(config, file_path):
    # Friendly debugging command.
    serial = get_serial_number()
    while not quitevent.is_set():
        for image in config.generator:
            with session_with_retry_policy() as Session:
                data = generate_payload(config=config, image=image)
                try:
                    response = Session.post(f"{config.gateway_url}upload",
                                            data=dumps(data))
                    print(response.content)
                except Exception as e:
                    logger.warning(
                        f"got error {e} with payload {data} continuing anyway")
                    pass
Example #7
0
def to_aws(config):
    serial = get_serial_number()
    ping = Pinger(gateway_URL=f"{config.gateway_url}ping",
                  device_name=config.device_name)
    ping.start()
    while not quitevent.is_set():
        for image in config.generator:
            # We got an event where the camera was diffed.
            with session_with_retry_policy() as Session:
                # Not strictly correct, not a binary image.
                data = generate_payload(config=config, image=image)
                response = Session.post(f"{config.gateway_url}upload",
                                        data=dumps(data))
                try:
                    response.raise_for_status()
                except Exception as e:
                    # If we get a non 200 status code, try again
                    logger.debug(e)
                    logger.warning(
                        f"got {response.status_code} \n for payload {data} \n with data {response.content}"
                    )
                    continue
                try:
                    response = response.json()
                    if len(response) == 0:
                        logger.info("no people in frame")
                        pass
                    else:
                        if response.get('activity') == 'compliant':
                            logger.info(
                                "Opening door. Thanks for wearing a mask.")
                            open_door(config, override=False)
                        else:
                            logger.info(
                                f"I see {len(response['sagemaker_response'])} people and one of you isn't wearing a mask."
                            )
                            logger.info(
                                "Wear a mask. I'm not opening the door until you do."
                            )
                            pass
                # If we can't decode this to JSON then it's an invalid payload
                except JSONDecodeError:
                    logger.warning(
                        f"Invalid JSON response from classify \n {response.content}"
                    )
                    continue
Example #8
0
def data_generator(Cam, threshold):
    images = []
    last_image = 0
    with Cam:
        # start getting images in a background thread
        # pre fill array
        images.append(Cam.read_frame())
        images.append(Cam.read_frame())
        # While we don't sigkill

        while not quitevent.is_set():
            if Cam.updated:
                images[last_image] = Cam.read_frame()
                # Sanity check that we have two images.
                if len(images) > 1:
                    threshold_percentage = Cam.compare_frames(
                        images[0], images[1])
                    if threshold_percentage > threshold:
                        yield images[last_image]
                # rotate frames
                if last_image == 0:
                    last_image = 1
                else:
                    last_image = 0
Example #9
0
toys = (
    '☢',
    '☣',
    '🍭',
    '🍼',
)


class Man(StoppableThread):
    def __init__(self, name):
        StoppableThread.__init__(self)
        self.name = name

    def run(self):
        print('🚼{} has quickened'.format(self.name))
        while not self.stopped:
            self.sleep(randint(1, 5))
            print('{} throws a {}'.format(self.name,
                                          toys[randint(0, len(toys)) - 1]))

        print('☠{} expires'.format(self.name))


if __name__ == '__main__':
    with Man('Trump'), Man('Wang'), Man('Erdoğan'):
        while not quitevent.is_set():
            quitevent.wait(1)

    print('God does not play dice')