Exemplo n.º 1
0
                        metavar='DURATION',
                        type=float,
                        help='Time (in seconds) to pause after processing an '
                        'image before grabbing the next. This is useful to '
                        'lessen the load of this service.',
                        default=get_conf('image_pause_period'))
    parser.add_argument('--state-file',
                        metavar='FILE',
                        help='The file to store/load state to/from. If '
                        'empty, state storing/loading is skipped.',
                        default=get_conf('state_file', allow_empty=True))


def run(scanarium, args):
    qr_state = QrState(scanarium, args.state_file)
    if args.bailout_period:
        watchdog = Watchdog(scanarium, qr_state, args.bailout_period,
                            args.bailout_mode, args.bailout_pause_period,
                            args.bailout_initial_pause_period)
        watchdog.start()
    scan_forever(scanarium, qr_state, args.image_error_pause_period,
                 args.image_pause_period)


if __name__ == "__main__":
    scanarium = Scanarium()
    args = scanarium.handle_arguments(
        'Continuously scans for images from '
        'the camera', register_arguments)
    scanarium.call_guarded(run, args, check_caller=False)
Exemplo n.º 2
0
                        raise ScanariumError(
                            'SE_SCAN_IMAGE_GREW_TOO_SMALL',
                            'Failed to identify sheet on scanned image')
                    else:
                        raise e
            else:
                raise e

        iteration += 1

    return scanarium.process_image_with_qr_code(image, qr_rect, data)


def scan_image(scanarium):
    ret = None
    try:
        ret = scan_image_no_outer_logging(scanarium)
    except Exception:
        ret = scanarium.get_command_logger().log(exc_info=sys.exc_info())
    return ret


def main(scanarium):
    return scan_image(scanarium)


if __name__ == "__main__":
    scanarium = Scanarium()
    scanarium.handle_arguments('Scans an processes an image from the camera')
    scanarium.call_guarded(main)
Exemplo n.º 3
0
    if not command and not parameter:
        regenerate_language_matrix(scanarium)
        regenerate_static_images(scanarium, force)


def register_arguments(scanarium, parser):
    parser.add_argument('--language',
                        help='Localize for the given language '
                        '(E.g.: \'de\' for German) Use `all` to localize for '
                        'all available languages',
                        default='all')
    parser.add_argument('--force',
                        help='Regenerate all files, even if they are not'
                        'stale',
                        action='store_true')
    parser.add_argument('COMMAND',
                        nargs='?',
                        help='Regenerate only the given command/scene')
    parser.add_argument('PARAMETER',
                        nargs='?',
                        help='Regenerate only the given parameter/actor')


if __name__ == "__main__":
    scanarium = Scanarium()
    args = scanarium.handle_arguments('Regenerates all static content',
                                      register_arguments)
    scanarium.call_guarded(regenerate_static_content, args.COMMAND,
                           args.PARAMETER, args.language, args.force)
Exemplo n.º 4
0
        if parts[0:2] == ['dynamic', 'scenes'] and \
                parts[3] in ['actors.json', 'actors-latest.json']:
            parts[2] = re.sub('[^a-zA-Z]', '-', parts[2])
            local_file = os.path.join(scanarium.get_dynamic_directory(),
                                      *parts[1:])

    if local_file is None:
        raise ScanariumError('SE_DYNAMIC_CONFIG_NOT_AVAILABLE',
                             'Dynamic config "{file}" is not available',
                             {'file': file})
    try:
        with open(local_file, 'r') as f:
            return json.load(f)
    except Exception:
        raise ScanariumError('SE_DYNAMIC_CONFIG_UNREADABLE',
                             'Dynamic config "{file}" cannot be read',
                             {'file': file})


def register_arguments(scanarium, parser):
    parser.add_argument('FILE', help='Path of the file to dump')


if __name__ == "__main__":
    scanarium = Scanarium()
    args = scanarium.handle_arguments('Dumps a config file',
                                      register_arguments,
                                      whitelisted_cgi_fields={'file': 1})

    scanarium.call_guarded(dump, args.FILE)
Exemplo n.º 5
0
import logging
import sys

SCANARIUM_DIR_ABS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, SCANARIUM_DIR_ABS)
from scanarium import Scanarium
del sys.path[0]

logger = logging.getLogger(__name__)


def reset_dynamic_content(scanarium, scene):
    scene = re.sub('[^a-zA-Z]+', '-', scene)
    return scanarium.reset_dynamic_content(scene)


def register_arguments(scanarium, parser):
    parser.add_argument('scene',
                        help='The scene to reset dynamic content for. If '
                        'empty, reset content for all scenes.',
                        nargs='?', default='')


if __name__ == "__main__":
    scanarium = Scanarium()
    args = scanarium.handle_arguments(
        'Resets dynamic content (Deletes scanned actors, ...)',
        register_arguments,
        whitelisted_cgi_fields={'scene': 1})
    scanarium.call_guarded(reset_dynamic_content, args.scene)
Exemplo n.º 6
0
                        'log all requests, `non-200` to log all requests that '
                        'have a response status different to 200, `non-2xx` '
                        'to log all requests that are outside of the '
                        '`success` range, or `none` to log no requests at '
                        ' all.',
                        choices=['all', 'non-200', 'non-2xx', 'none'],
                        default=get_conf('log_requests'))
    parser.add_argument('--server-version-override',
                        metavar='VERSION',
                        help='Override for response\'s `Server` header field',
                        default=get_conf('server_version_override',
                                         allow_empty=True))
    parser.add_argument('--thread-pool-size',
                        metavar='THREADS',
                        type=int,
                        help='Number of threads to serve requests from',
                        default=get_conf('thread_pool_size', kind='int'))


if __name__ == '__main__':
    args = scanarium.handle_arguments('Scanarium demo server',
                                      register_arguments)

    SERVER_VERSION_OVERRIDE = args.server_version_override
    LOG_REQUESTS = args.log_requests

    scanarium.call_guarded(serve_forever,
                           args.port,
                           args.thread_pool_size,
                           check_caller=False)
Exemplo n.º 7
0
                else:
                    last_exception_message = None

            if show_image:
                cv2.imshow(title, image)
            cv2.waitKey(25)
    finally:
        if store_final and original_image is not None:
            filename = scanarium.get_timestamp_for_filename() + '.png'
            cv2.imwrite(filename, original_image)
            logger.info('Stored last image as "%s"' % (filename))
        if camera is not None:
            scanarium.close_camera(camera)


def register_arguments(scanarium, parser):
    parser.add_argument('--mark',
                        help='Marks the QR-Code and suitable '
                        'contours, if found',
                        action='store_true')
    parser.add_argument('--store-final',
                        help='Writes the final image to disk',
                        action='store_true')


if __name__ == "__main__":
    scanarium = Scanarium()
    args = scanarium.handle_arguments('Shows the camera picture on screen',
                                      register_arguments)
    scanarium.call_guarded(show_source, args.mark, args.store_final)
Exemplo n.º 8
0

def scan_data(scanarium, data):
    with tempfile.TemporaryDirectory(prefix='scanarium-scan-data-') as dir:
        image_file = os.path.join(dir, 'image')
        with open(image_file, 'wb') as f:
            f.write(base64.standard_b64decode(data))
        # Temporarily switching the image source to the new image for scanning
        scanarium.set_config('scan', 'source', f'image:{image_file}')

        # As we switched from the configured image source to the passed image,
        # the calibration data for the configured image source no longer fits,
        # and we drop it as it may otherwise distort colors/geometry.
        scanarium.set_config('scan', 'calibration_xml_file', '')
        scanarium.set_config('scan', 'max_brightness', '')

        return scan_image(scanarium)


def register_arguments(scanarium, parser):
    parser.add_argument('DATA', help='The image data to scan')


if __name__ == "__main__":
    scanarium = Scanarium()
    args = scanarium.handle_arguments(
        'Scans an processes an image from a parameter',
        register_arguments,
        whitelisted_cgi_fields={'data': 1})
    scanarium.call_guarded(scan_data, args.DATA)
Exemplo n.º 9
0
import os
import logging
import sys

SCANARIUM_DIR_ABS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, SCANARIUM_DIR_ABS)
from scanarium import Scanarium
del sys.path[0]

logger = logging.getLogger(__name__)


def reindex(scanarium):
    dynamic_scenes_dir = os.path.join(scanarium.get_dynamic_directory(),
                                      'scenes')
    scenes_dir_abs = scanarium.get_scenes_dir_abs()
    for scene in os.listdir(scenes_dir_abs):
        if os.path.isdir(os.path.join(scenes_dir_abs, scene)):
            logging.debug(f'Reindexing scene "{scene}" ...')
            dynamic_scene_dir = os.path.join(dynamic_scenes_dir, scene)
            if not os.path.isdir(dynamic_scene_dir):
                os.makedirs(dynamic_scene_dir)
            scanarium.reindex_actors_for_scene(scene)


if __name__ == "__main__":
    scanarium = Scanarium()
    scanarium.handle_arguments('Reindexes dynamic content, such as actors')
    scanarium.call_guarded(reindex)
Exemplo n.º 10
0
            if format:
                os.rename(img_filename, f'{img_filename}.{format}')
        if userAgent:
            scanarium.dump_text(filename_base + '-user-agent.txt', userAgent)
    else:
        raise ScanariumError('SE_UNKNOWN_FEEDBACK_TARGET',
                             'Unknown feedback target "{feedback_target}"',
                             {'feedback_target': target})
    return True


def register_arguments(scanarium, parser):
    parser.add_argument('MESSAGE', help='The textual part of the feedback')
    parser.add_argument('EMAIL', nargs='?',
                        help='The email to send the answer to')
    parser.add_argument('LAST_FAILED_UPLOAD', nargs='?',
                        help='The last failed upload')
    parser.add_argument('USER_AGENT', nargs='?',
                        help='The browser identification')


if __name__ == "__main__":
    scanarium = Scanarium()
    args = scanarium.handle_arguments(
        'Reports feedback',
        register_arguments,
        whitelisted_cgi_fields={
            'message': 1, 'email': 2, 'lastFailedUpload': 3, 'userAgent': 4})
    scanarium.call_guarded(report_feedback, args.MESSAGE, args.EMAIL,
                           args.LAST_FAILED_UPLOAD, args.USER_AGENT)
Exemplo n.º 11
0
                                 'Backend failed')

        if e.code == 'SE_TIMEOUT':
            raise ScanariumError('SE_PWD_UPDATE_TIMEOUT',
                                 'Update process timed out')

        raise e
    return {}


def register_arguments(scanarium, parser):
    parser.add_argument('OLD_PASSWORD', help='The current password')
    parser.add_argument('NEW_PASSWORD', help='The new password')


if __name__ == "__main__":
    scanarium = Scanarium()
    args = scanarium.handle_arguments(
        'Updates the password for a user. Do NOT call this script directly in '
        'production, as passing passwords as command-line arguments on '
        'command-line might expose them to other users that can view process '
        'names. Instead, call it through CGI, where parameters are not passed '
        'as command-line arguments.',
        register_arguments,
        whitelisted_cgi_fields={
            'old-password': 1,
            'new-password': 2
        })
    scanarium.call_guarded(update_password, args.OLD_PASSWORD,
                           args.NEW_PASSWORD)