Esempio n. 1
0
 def test_to_safe_filename_start(self):
     actual = Scanarium().to_safe_filename('Äöquux')
     self.assertEqual(actual, 'quux')
Esempio n. 2
0
 def test_to_safe_filename_end(self):
     actual = Scanarium().to_safe_filename('quuxßĵ')
     self.assertEqual(actual, 'quux')
Esempio n. 3
0
 def test_to_safe_filename_eo(self):
     actual = Scanarium().to_safe_filename('FĝoĜo')
     self.assertEqual(actual, 'F-o-o')
Esempio n. 4
0
 def test_to_safe_filename_multiple(self):
     actual = Scanarium().to_safe_filename('FäöüoÄÖÜo')
     self.assertEqual(actual, 'F-o-o')
Esempio n. 5
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)
Esempio n. 6
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)
Esempio n. 7
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)
Esempio n. 8
0
 def test_get_versioned_filename(self):
     actual = Scanarium().get_versioned_filename('foo', 'bar', 'baz', 42)
     self.assertEqual(actual, os.path.join('foo', 'bar-d-42.baz'))
Esempio n. 9
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)
Esempio n. 10
0
import concurrent.futures
import http
import http.server
import os
import socketserver
import sys
import logging

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]

scanarium = Scanarium()
logger = logging.getLogger(__name__)

LOG_REQUESTS = False
SERVER_VERSION_OVERRIDE = None


class RequestHandler(http.server.CGIHTTPRequestHandler):
    """Simple HTTP handler that aliases user-generated-content"""
    cgi_directories = ['/cgi-bin']

    def version_string(self):
        ret = SERVER_VERSION_OVERRIDE
        if ret is None:
            ret = super().version_string()
        return ret
Esempio n. 11
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)
Esempio n. 12
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)
Esempio n. 13
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)
Esempio n. 14
0
 def test_to_safe_filename_digits(self):
     actual = Scanarium().to_safe_filename('F47o11o')
     self.assertEqual(actual, 'F47o11o')
Esempio n. 15
0
 def test_to_safe_filename_simple(self):
     actual = Scanarium().to_safe_filename('foo')
     self.assertEqual(actual, 'foo')
Esempio n. 16
0
 def test_to_safe_filename_punctuation(self):
     actual = Scanarium().to_safe_filename('F.o/,o')
     self.assertEqual(actual, 'F-o-o')
Esempio n. 17
0
 def test_to_safe_filename_empty(self):
     actual = Scanarium().to_safe_filename('')
     self.assertEqual(actual, 'unnamed')
Esempio n. 18
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)
Esempio n. 19
0
 def test_to_safe_filename_umlaut(self):
     actual = Scanarium().to_safe_filename('FäoöoüoÄoÖoÜoßo')
     self.assertEqual(actual, 'F-o-o-o-o-o-o-o')
Esempio n. 20
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)
Esempio n. 21
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)