示例#1
0
文件: count.py 项目: sravel/pibooth
def main():
    """Application entry point.
    """
    configure_logging()
    plugin_manager = create_plugin_manager()
    config = PiConfigParser("~/.config/pibooth/pibooth.cfg", plugin_manager)

    counters = Counters(config.join_path("counters.pickle"),
                        taken=0,
                        printed=0,
                        forgotten=0,
                        remaining_duplicates=config.getint(
                            'PRINTER', 'max_duplicates'))

    if '--json' in sys.argv:
        print(json.dumps(counters.data))
    elif '--update' in sys.argv:
        try:
            print("\nUpdating counters (current value in square bracket):\n")
            for name in counters:
                value = input(" -> {:.<18} [{:>4}] : ".format(
                    name.capitalize(), counters[name]))
                if value.strip():
                    setattr(counters, name, int(value))
        except KeyboardInterrupt:
            pass
        print()
    else:
        print("\nListing current counters:\n")
        for name in counters:
            print(" -> {:.<25} : {:>4}".format(name.capitalize(),
                                               counters[name]))
        print()
示例#2
0
def main():
    """Application entry point.
    """
    configure_logging()
    plugin_manager = create_plugin_manager()
    config = PiConfigParser("~/.config/pibooth/pibooth.cfg", plugin_manager)

    # Register plugins
    plugin_manager.load_all_plugins(
        config.gettuple('GENERAL', 'plugins', 'path'),
        config.gettuple('GENERAL', 'plugins_disabled', str))

    LOGGER.info(
        "Installed plugins: %s", ", ".join([
            plugin_manager.get_friendly_name(p)
            for p in plugin_manager.list_external_plugins()
        ]))

    # Update configuration with plugins ones
    plugin_manager.hook.pibooth_configure(cfg=config)

    # Initialize varibales normally done by the app
    picture_plugin = plugin_manager.get_plugin('pibooth-core:picture')
    picture_plugin.texts_vars['date'] = datetime.now()
    picture_plugin.texts_vars['count'] = Counters(
        config.join_path("counters.pickle"),
        taken=0,
        printed=0,
        forgotten=0,
        remaining_duplicates=config.getint('PRINTER', 'max_duplicates'))

    for path in config.gettuple('GENERAL', 'directory', 'path'):
        regenerate_all_images(plugin_manager, config, path)
示例#3
0
def main():
    """Application entry point.
    """
    configure_logging()
    plugin_manager = create_plugin_manager()
    config = PiConfigParser("~/.config/pibooth/pibooth.cfg", plugin_manager)

    # Register plugins
    custom_paths = [p for p in config.gettuple('GENERAL', 'plugins', 'path') if p]
    load_plugins(plugin_manager, *custom_paths)

    # Update configuration with plugins ones
    plugin_manager.hook.pibooth_configure(cfg=config)

    for path in config.gettuple('GENERAL', 'directory', 'path'):
        regenerate_all_images(plugin_manager, config, path)
示例#4
0
def main():
    """Application entry point.
    """
    configure_logging()
    plugin_manager = create_plugin_manager()
    config = PiConfigParser("~/.config/pibooth/pibooth.cfg", plugin_manager)

    # Register plugins
    plugin_manager.load_all_plugins(config.gettuple('GENERAL', 'plugins', 'path'),
                                    config.gettuple('GENERAL', 'plugins_disabled', str))

    LOGGER.info("Installed plugins: %s", ", ".join(
        [plugin_manager.get_friendly_name(p) for p in plugin_manager.list_extern_plugins()]))

    # Update configuration with plugins ones
    plugin_manager.hook.pibooth_configure(cfg=config)

    for path in config.gettuple('GENERAL', 'directory', 'path'):
        regenerate_all_images(plugin_manager, config, path)
示例#5
0
def main():
    """Application entry point.
    """
    if hasattr(multiprocessing, 'set_start_method'):
        # Avoid use 'fork': safely forking a multithreaded process is problematic
        multiprocessing.set_start_method('spawn')

    parser = argparse.ArgumentParser(usage="%(prog)s [options]",
                                     description=pibooth.__doc__)

    parser.add_argument('--version',
                        action='version',
                        version=pibooth.__version__,
                        help=u"show program's version number and exit")

    parser.add_argument("--config",
                        action='store_true',
                        help=u"edit the current configuration and exit")

    parser.add_argument("--translate",
                        action='store_true',
                        help=u"edit the GUI translations and exit")

    parser.add_argument(
        "--reset",
        action='store_true',
        help=u"restore the default configuration/translations and exit")

    parser.add_argument("--fonts",
                        action='store_true',
                        help=u"display all available fonts and exit")

    parser.add_argument(
        "--nolog",
        action='store_true',
        default=False,
        help=
        u"don't save console output in a file (avoid filling the /tmp directory)"
    )

    group = parser.add_mutually_exclusive_group()
    group.add_argument("-v",
                       "--verbose",
                       dest='logging',
                       action='store_const',
                       const=logging.DEBUG,
                       help=u"report more information about operations",
                       default=logging.INFO)
    group.add_argument("-q",
                       "--quiet",
                       dest='logging',
                       action='store_const',
                       const=logging.WARNING,
                       help=u"report only errors and warnings",
                       default=logging.INFO)

    options, _args = parser.parse_known_args()

    if not options.nolog:
        filename = osp.join(tempfile.gettempdir(), 'pibooth.log')
    else:
        filename = None
    configure_logging(options.logging,
                      '[ %(levelname)-8s] %(name)-18s: %(message)s',
                      filename=filename)

    plugin_manager = create_plugin_manager()

    # Load the configuration and languages
    config = PiConfigParser("~/.config/pibooth/pibooth.cfg", plugin_manager)
    language.init(config.join_path("translations.cfg"), options.reset)

    # Register plugins
    custom_paths = [
        p for p in config.gettuple('GENERAL', 'plugins', 'path') if p
    ]
    load_plugins(plugin_manager, *custom_paths)
    LOGGER.info("Installed plugins: %s",
                ", ".join(list_plugin_names(plugin_manager)))

    # Update configuration with plugins ones
    plugin_manager.hook.pibooth_configure(cfg=config)

    # Ensure config files are present in case of first pibooth launch
    if not options.reset:
        if not osp.isfile(config.filename):
            config.save(default=True)
        plugin_manager.hook.pibooth_reset(cfg=config, hard=False)

    if options.config:
        LOGGER.info("Editing the pibooth configuration...")
        config.edit()
    elif options.translate:
        LOGGER.info("Editing the GUI translations...")
        language.edit()
    elif options.fonts:
        LOGGER.info("Listing all fonts available...")
        print_columns_words(get_available_fonts(), 3)
    elif options.reset:
        config.save(default=True)
        plugin_manager.hook.pibooth_reset(cfg=config, hard=True)
    else:
        LOGGER.info("Starting the photo booth application %s", GPIO_INFO)
        app = PiApplication(config, plugin_manager)
        app.main_loop()
示例#6
0
def main():
    error = False
    configure_logging()
    write_log("Pibooth version installed: {}".format(pibooth.__version__))

    plugin_manager = create_plugin_manager()
    config = PiConfigParser("~/.config/pibooth/pibooth.cfg", plugin_manager)

    # Register plugins
    plugin_manager.load_all_plugins(
        config.gettuple('GENERAL', 'plugins', 'path'),
        config.gettuple('GENERAL', 'plugins_disabled', str))

    write_log("Installed plugins: {}".format(", ".join([
        plugin_manager.get_friendly_name(p)
        for p in plugin_manager.list_external_plugins()
    ])))

    if not gp:
        write_log("gPhoto2 not installed, cannot diagnose connected DSLR")
        sys.exit(1)

    gp_log_callback = gp.check_result(
        gp.gp_log_add_func(gp.GP_LOG_VERBOSE, gp_logging))
    write_log("Listing all connected DSLR camera")
    cameras_list = camera_connected()

    if not cameras_list:
        write_log('No compatible DSLR camera detected')
        sys.exit(1)

    cameras_list = sorted(cameras_list, key=lambda x: x[0])
    for index, (name, addr) in enumerate(cameras_list):
        write_log("{:02d} : addr-> {}  name-> {}".format(index, addr, name))

    write_log("Stating diagnostic of connected DSLR camera", True)
    camera = gp.Camera()
    camera.init()

    abilities = camera.get_abilities()
    preview_compat = gp.GP_OPERATION_CAPTURE_PREVIEW ==\
        abilities.operations & gp.GP_OPERATION_CAPTURE_PREVIEW
    write_log("* Preview compatible: {}".format(preview_compat))
    capture_compat = gp.GP_OPERATION_CAPTURE_IMAGE ==\
        abilities.operations & gp.GP_OPERATION_CAPTURE_IMAGE
    write_log("* Capture compatible: {}".format(capture_compat))

    if capture_compat:
        try:
            print_config(camera.get_config())

            write_log("Testing commands used by pibooth", True)

            set_config_value(camera, 'imgsettings', 'iso', '100')
            set_config_value(camera, 'settings', 'capturetarget',
                             'Memory card')

            viewfinder = get_config_value(camera, 'actions', 'viewfinder')
            if viewfinder is not None:
                set_config_value(camera, 'actions', 'viewfinder', 1)

            write_log("Take capture preview")
            camera.capture_preview()

            if viewfinder is not None:
                set_config_value(camera, 'actions', 'viewfinder', 0)

            write_log("Take a capture")
            gp_path = camera.capture(gp.GP_CAPTURE_IMAGE)

            write_log("Download file from DSLR")
            camera_file = camera.file_get(gp_path.folder, gp_path.name,
                                          gp.GP_FILE_TYPE_NORMAL)

            write_log("Save capture locally from memory buffer")
            data = camera_file.get_data_and_size()
            with open(APPNAME + '.raw', 'wb') as fd:
                fd.write(data)
            image = Image.open(io.BytesIO(data))
            image.save(APPNAME + '.jpg')

        except Exception as ex:
            write_log("ABORT   : exception occures: {}".format(ex), True)
            error = True

    if not error:
        write_log("SUCCESS : diagnostic completed", True)

    del gp_log_callback
    camera.exit()

    write_log(
        "If you are investigating why pibooth does not work with your DSLR camera,"
    )
    write_log(
        "please paste the content of generated file '{}'".format(APPNAME +
                                                                 '.log'))
    write_log("on https://github.com/pibooth/pibooth/issues")
示例#7
0
文件: printer.py 项目: jo-ei/pibooth
def main():
    """Application entry point.
    """
    configure_logging()
    plugin_manager = create_plugin_manager()
    config = PiConfigParser("~/.config/pibooth/pibooth.cfg", plugin_manager)

    conn = cups.Connection()
    name = config.get('PRINTER', 'printer_name')

    if not name or name.lower() == 'default':
        name = conn.getDefault()
        if not name and conn.getPrinters():
            name = list(conn.getPrinters().keys())[0]  # Take first one
    elif name not in conn.getPrinters():
        name = None

    if not name:
        if name.lower() == 'default':
            LOGGER.warning(
                "No printer configured in CUPS (see http://localhost:631)")
            return
        else:
            LOGGER.warning(
                "No printer named '%s' in CUPS (see http://localhost:631)",
                name)
            return
    else:
        LOGGER.info("Connected to printer '%s'", name)

    f = conn.getPPD(name)
    ppd = cups.PPD(f)
    groups = ppd.optionGroups
    options = []
    for group in groups:
        group_name = "{} - {}".format(group.name, group.text)
        for opt in group.options:
            option = {'group': group_name}
            values = list(map(lambda x: x["choice"], opt.choices))
            texts = list(map(lambda x: x["text"], opt.choices))
            option['keyword'] = opt.keyword
            option['value'] = opt.defchoice
            option['description'] = opt.text
            if values != texts:
                option['choices'] = dict([(v, texts[values.index(v)])
                                          for v in values])
            else:
                option['choices'] = values
            options.append(option)

    if '--json' in sys.argv:
        print(
            json.dumps(
                dict([(option['keyword'], option['value'])
                      for option in options])))
    else:
        for option in options:
            print("{} = {}".format(option['keyword'], option['value']))
            print("     Description: {}".format(option['description']))
            if isinstance(option['choices'], dict):
                choices = [
                    "{} = {}".format(value, descr)
                    for value, descr in option['choices'].items()
                ]
                print("     Choices:     {}".format(choices[0]))
                for choice in choices[1:]:
                    print("                  {}".format(choice))
            else:
                print("     Choices:     {}".format(", ".join(
                    option['choices'])))

            print()