def post(self, request):
        printer = request.auth

        pic = request.FILES['pic']
        pic_id = int(timezone.now().timestamp())
        internal_url, external_url = save_file_obj(
            'raw/{}/{}.jpg'.format(printer.id, pic_id), pic,
            settings.PICS_CONTAINER)

        if not printer.is_printing():
            redis.printer_pic_set(printer.id, {'img_url': external_url},
                                  ex=STATUS_TTL_SECONDS)
            return command_response(printer)

        req = requests.get(settings.ML_API_HOST + '/p/',
                           params={'img': internal_url},
                           headers=ml_api_auth_headers(),
                           verify=False)
        req.raise_for_status()
        resp = req.json()

        detections = resp['detections']
        prediction, _ = PrinterPrediction.objects.get_or_create(
            printer=printer)
        update_prediction_with_detections(prediction, detections)
        prediction.save()

        pic.file.seek(
            0)  # Reset file object pointer so that we can load it again
        tagged_img = io.BytesIO()
        detections_to_visualize = [
            d for d in detections if d[1] > VISUALIZATION_THRESH
        ]
        overlay_detections(Image.open(pic),
                           detections_to_visualize).save(tagged_img, "JPEG")
        tagged_img.seek(0)
        _, external_url = save_file_obj(
            'tagged/{}/{}.jpg'.format(printer.id, pic_id), tagged_img,
            settings.PICS_CONTAINER)
        redis.printer_pic_set(printer.id, {'img_url': external_url},
                              ex=STATUS_TTL_SECONDS)

        prediction_json = serializers.serialize("json", [
            prediction,
        ])
        redis.printer_p_json_set(printer.id,
                                 pic_id,
                                 prediction_json,
                                 ex=60 * 60 * 24 * 2)

        if is_failing(prediction,
                      printer.detective_sensitivity,
                      escalating_factor=settings.ESCALATING_FACTOR):
            pause_if_needed(printer)
        elif is_failing(prediction,
                        printer.detective_sensitivity,
                        escalating_factor=1):
            alert_if_needed(printer)

        return command_response(printer)
示例#2
0
    def post(self, request):
        printer = request.auth

        pic = request.data['pic']
        internal_url, external_url = save_file_obj('{}/{}.jpg'.format(printer.id, int(time.time())), pic, settings.PICS_CONTAINER)

        if not printer.current_print_filename or not printer.current_print_started_at:
            redis.printer_pic_set(printer.id, {'img_url': external_url, 'p': '0'}, ex=STATUS_TTL_SECONDS)
            return command_response(printer)

        params = {
            'img': internal_url,
            'session_id': "{}|{}".format(printer.id, int(printer.current_print_started_at.timestamp()))
        }

        req = requests.get(settings.ML_API_HOST + '/p', params=params, headers=ml_api_auth_headers(), verify=False)
        req.raise_for_status()
        resp = req.json()
        p = resp['p']
        redis.printer_pic_set(printer.id, {'img_url': external_url, 'p': p}, ex=STATUS_TTL_SECONDS)

        print(resp['detections'])
        print(p)

        send_alert_if_needed(printer, p)
        return command_response(printer)
示例#3
0
    def post(self, request):
        printer = request.auth
        printer.refresh_from_db()  # Connection is keep-alive, which means printer object can be stale.

        pic = request.FILES['pic']
        pic = cap_image_size(pic)
        pic_id = str(timezone.now().timestamp())

        if not printer.current_print:     # Some times pics come in when current_print is not set - maybe because printer status is out of sync between plugin and server?
            pic_path = f'{printer.id}/0/{pic_id}.jpg'
        else:
            pic_path = f'{printer.id}/{printer.current_print.id}/{pic_id}.jpg'
        internal_url, external_url = save_file_obj(f'raw/{pic_path}', pic, settings.PICS_CONTAINER, long_term_storage=False)

        if not printer.should_watch() or not printer.actively_printing():
            redis.printer_pic_set(printer.id, {'img_url': external_url}, ex=IMG_URL_TTL_SECONDS)
            send_status_to_web(printer.id)
            return Response({'result': 'ok'})

        req = requests.get(settings.ML_API_HOST + '/p/', params={'img': internal_url}, headers=ml_api_auth_headers(), verify=False)
        req.raise_for_status()
        resp = req.json()

        redis.print_num_predictions_incr(printer.current_print.id)

        detections = resp['detections']
        prediction, _ = PrinterPrediction.objects.get_or_create(printer=printer)
        update_prediction_with_detections(prediction, detections)
        prediction.save()

        if prediction.current_p > settings.THRESHOLD_LOW * 0.2:  # Select predictions high enough for focused feedback
            redis.print_high_prediction_add(printer.current_print.id, prediction.current_p, pic_id)

        pic.file.seek(0)  # Reset file object pointer so that we can load it again
        tagged_img = io.BytesIO()
        detections_to_visualize = [d for d in detections if d[1] > VISUALIZATION_THRESH]
        overlay_detections(Image.open(pic), detections_to_visualize).save(tagged_img, "JPEG")
        tagged_img.seek(0)

        _, external_url = save_file_obj(f'tagged/{pic_path}', tagged_img, settings.PICS_CONTAINER, long_term_storage=False)
        redis.printer_pic_set(printer.id, {'img_url': external_url}, ex=IMG_URL_TTL_SECONDS)

        prediction_json = serializers.serialize("json", [prediction, ])
        p_out = io.BytesIO()
        p_out.write(prediction_json.encode('UTF-8'))
        p_out.seek(0)
        save_file_obj(f'p/{printer.id}/{printer.current_print.id}/{pic_id}.json', p_out, settings.PICS_CONTAINER, long_term_storage=False)

        if is_failing(prediction, printer.detective_sensitivity, escalating_factor=settings.ESCALATING_FACTOR):
            pause_if_needed(printer)
        elif is_failing(prediction, printer.detective_sensitivity, escalating_factor=1):
            alert_if_needed(printer)

        send_status_to_web(printer.id)
        return Response({'result': 'ok'})
    def post(self, request):
        printer = request.auth

        pic = request.FILES['pic']
        pic_id = int(timezone.now().timestamp())
        internal_url, external_url = save_file_obj(
            'raw/{}/{}.jpg'.format(printer.id, pic_id), pic,
            settings.PICS_CONTAINER)

        if not printer.is_printing():
            redis.printer_pic_set(printer.id, {'img_url': external_url},
                                  ex=STATUS_TTL_SECONDS)
            return command_response(printer)

        req = requests.get(settings.ML_API_HOST + '/p/',
                           params={'img': internal_url},
                           headers=ml_api_auth_headers(),
                           verify=False)
        req.raise_for_status()
        resp = req.json()

        detections = resp['detections']
        prediction, _ = PrinterPrediction.objects.get_or_create(
            printer=printer)
        update_prediction_with_detections(prediction, detections)
        prediction.save()

        pic.file.seek(
            0)  # Reset file object pointer so that we can load it again
        tagged_img = io.BytesIO()
        overlay_detections(Image.open(pic),
                           detections).save(tagged_img, "JPEG")
        tagged_img.seek(0)
        _, external_url = save_file_obj(
            'tagged/{}/{}.jpg'.format(printer.id, pic_id), tagged_img,
            settings.PICS_CONTAINER)
        redis.printer_pic_set(printer.id, {'img_url': external_url},
                              ex=STATUS_TTL_SECONDS)

        prediction_json = serializers.serialize("json", [
            prediction,
        ])
        p_out = io.BytesIO()
        p_out.write(prediction_json.encode('UTF-8'))
        p_out.seek(0)
        save_file_obj('p/{}/{}.json'.format(printer.id, pic_id),
                      p_out,
                      settings.PICS_CONTAINER,
                      return_url=False)

        if is_failing(prediction, printer.detective_sensitivity):
            alert_if_needed(printer)

        return command_response(printer)
示例#5
0
def generate_print_poster(_print):

    (unrotated_jpg_url, rotated_jpg_url) = save_print_snapshot(_print,
                                                               last_pic_of_print(_print, 'raw'),
                                                               unrotated_jpg_path=f'snapshots/{_print.printer.id}/{_print.id}/{str(timezone.now().timestamp())}_unrotated.jpg',
                                                               rotated_jpg_path=f'private/{_print.id}_poster.jpg')

    if unrotated_jpg_url:
        redis.printer_pic_set(_print.printer.id, {'img_url': unrotated_jpg_url}, ex=IMG_URL_TTL_SECONDS)

    if rotated_jpg_url:
        _print.poster_url = rotated_jpg_url
        _print.save()
示例#6
0
def generate_print_poster(_print):
    (unrotated_jpg_url, rotated_jpg_url) = save_print_snapshot(
        _print,
        rotated_jpg_path=f'private/{_print.id}_poster.jpg',
        rotated_jpg_container=settings.TIMELAPSE_CONTAINER,
        rotated_jpg_long_term=True)

    if unrotated_jpg_url:
        redis.printer_pic_set(_print.printer.id,
                              {'img_url': unrotated_jpg_url},
                              ex=IMG_URL_TTL_SECONDS)

    if rotated_jpg_url:
        _print.poster_url = rotated_jpg_url
        _print.save()
示例#7
0
    def post(self, request):
        printer = request.auth
        printer.refresh_from_db() # Connection is keep-alive, which means printer object can be stale.

        if not request.path.startswith('/api/v1'):
            LOGGER.warn(f'Beta plugin connecting from {printer.id}')

        pic = request.FILES['pic']
        pic_id = int(timezone.now().timestamp())
        internal_url, external_url = save_file_obj('raw/{}/{}.jpg'.format(printer.id, pic_id), pic, settings.PICS_CONTAINER)

        if not printer.should_watch() or not printer.actively_printing():
            redis.printer_pic_set(printer.id, {'img_url': external_url}, ex=STATUS_TTL_SECONDS)
            send_status_to_web(printer.id)
            return Response({'result': 'ok'})

        req = requests.get(settings.ML_API_HOST + '/p/', params={'img': internal_url}, headers=ml_api_auth_headers(), verify=False)
        req.raise_for_status()
        resp = req.json()

        detections = resp['detections']
        prediction, _ = PrinterPrediction.objects.get_or_create(printer=printer)
        update_prediction_with_detections(prediction, detections)
        prediction.save()

        pic.file.seek(0)  # Reset file object pointer so that we can load it again
        tagged_img = io.BytesIO()
        detections_to_visualize = [d for d in detections if d[1] > VISUALIZATION_THRESH]
        overlay_detections(Image.open(pic), detections_to_visualize).save(tagged_img, "JPEG")
        tagged_img.seek(0)
        _, external_url = save_file_obj('tagged/{}/{}.jpg'.format(printer.id, pic_id), tagged_img, settings.PICS_CONTAINER)
        redis.printer_pic_set(printer.id, {'img_url': external_url}, ex=STATUS_TTL_SECONDS)

        prediction_json = serializers.serialize("json", [prediction, ])
        redis.printer_p_json_set(printer.id, pic_id, prediction_json, ex=60*60*24*2)

        if is_failing(prediction, printer.detective_sensitivity, escalating_factor=settings.ESCALATING_FACTOR):
            pause_if_needed(printer)
        elif is_failing(prediction, printer.detective_sensitivity, escalating_factor=1):
            alert_if_needed(printer)

        redis.print_num_predictions_incr(printer.current_print.id)
        send_status_to_web(printer.id)
        return Response({'result': 'ok'})
示例#8
0
def generate_print_poster(_print):
    pic_dir = f'{_print.printer.id}/{_print.id}'
    print_pics = list_dir(f'raw/{pic_dir}/',
                          settings.PICS_CONTAINER,
                          long_term_storage=False)
    if not print_pics:
        return
    print_pics.sort()

    to_dir = os.path.join(tempfile.gettempdir(), str(_print.id))
    shutil.rmtree(to_dir, ignore_errors=True)
    os.mkdir(to_dir)
    unrotated_jpg = os.path.join(to_dir, 'ss.jpg')
    with open(unrotated_jpg, 'wb') as file_obj:
        retrieve_to_file_obj(print_pics[-1],
                             file_obj,
                             settings.PICS_CONTAINER,
                             long_term_storage=False)

    with open(unrotated_jpg, 'rb') as unrotated_jpg_file:
        _, ss_url = save_file_obj(f'raw/{_print.printer.id}/ss.jpg',
                                  unrotated_jpg_file,
                                  settings.PICS_CONTAINER,
                                  long_term_storage=False)
    redis.printer_pic_set(_print.printer.id, {'img_url': ss_url},
                          ex=IMG_URL_TTL_SECONDS)

    ffmpeg_extra_options = orientation_to_ffmpeg_options(
        _print.printer.settings)
    rotated_jpg = os.path.join(to_dir, 'rotated.jpg')
    cmd = f'ffmpeg -y -i {unrotated_jpg} {ffmpeg_extra_options} {rotated_jpg}'
    subprocess.run(cmd.split(), check=True)
    with open(rotated_jpg, 'rb') as poster_file:
        _, poster_file_url = save_file_obj(
            'private/{}_poster.jpg'.format(_print.id), poster_file,
            settings.TIMELAPSE_CONTAINER)

    _print.poster_url = poster_file_url
    _print.save()

    shutil.rmtree(to_dir, ignore_errors=True)