Exemplo n.º 1
0
    def __init__(self, dev_id=None, source_name=None):
        self.libinsanelogger = self.Logger()
        Libinsane.register_logger(self.libinsanelogger)

        # scan device
        api = Libinsane.Api.new_safebet()
        if dev_id is None:
            devs = api.list_devices(Libinsane.DeviceLocations.ANY)
            if len(devs) == 0:
                raise Exception("No scan device find!")
            dev_id = devs[0].get_dev_id()
        self.dev = api.get_device(dev_id)
        logging.info("Using {} ({})".format(dev_id, self.dev.get_name()))

        # scan source
        sources = self.dev.get_children()
        for src in sources:
            if src.get_name() == source_name:
                self.source = src
                break
        else:
            if source_name is None:
                self.source = sources[0] if len(sources) > 0 else dev
            elif source_name == 'root':
                self.source = self.dev
            else:
                raise Exception("Source '{}' not found".format(source_name))
        logging.info("Using use scan source {}".format(self.source.get_name()))

        self.opts = {opt.get_name(): opt for opt in self.source.get_options()}
Exemplo n.º 2
0
def main():
    Libinsane.register_logger(ExampleLogger())
    api = Libinsane.Api.new_safebet()

    devs = api.list_devices(Libinsane.DeviceLocations.ANY)
    print("Found {} devices".format(len(devs)))
    for dev in devs:
        print(dev.to_string())

        dev = api.get_device(dev.get_dev_id())

        for item in [dev] + dev.get_children():
            print("|-- " + dev.get_name())
            opts = item.get_options()
            for opt in opts:
                print("|   |-- {}".format(opt.get_name()))
                print("|   |   |-- Title: {}".format(opt.get_title()))
                print("|   |   |-- Description: {}".format(opt.get_desc()))
                print("|   |   |-- Capabilities: {}".format(
                    opt.get_capabilities()))
                print("|   |   |-- Unit: {}".format(opt.get_value_unit()))
                print("|   |   |-- Constraint type: {}".format(
                    opt.get_constraint_type()))
                print("|   |   |-- Constraint: {}".format(
                    opt.get_constraint()))
                if opt.is_readable():
                    print("|   |   |-- Value: {}".format(opt.get_value()))
                else:
                    print("|   |   |-- Value: (unavailable)")
        print("")
        dev.close()
Exemplo n.º 3
0
def main():
    Libinsane.register_logger(ExampleLogger())
    #! [Logger]
    api = Libinsane.Api.new_safebet()
    devs = api.list_devices(Libinsane.DeviceLocations.ANY)
    print("Found {} devices".format(len(devs)))
    for dev in devs:
        print(dev.to_string())
Exemplo n.º 4
0
 def __init__(self):
     # Set logger
     Libinsane.register_logger(Logger())
     # Init Libinsane API
     self.api = Libinsane.Api.new_safebet()
     self.picture_format = (6, 4, "inch")
     self.number_of_pictures = 3
     self.orientation = "landscape"
     self.album_directory = ""
     self.device_list = []
     self.source_list = []
     self.active_source = None
     self.resolution = 600
Exemplo n.º 5
0
def main():
    Libinsane.register_logger(Logger())

    if len(sys.argv) <= 1 or (sys.argv[1] == "-h" or sys.argv[1] == "--help"):
        print("Syntax: {} <output directory>".format(sys.argv[0]))
        sys.exit(1)

    output_dir = sys.argv[1]

    print("Will write the scan result into {}/".format(output_dir))
    os.mkdir(output_dir)

    api = Libinsane.Api.new_safebet()

    print("Looking for devices ...")

    devs = get_devices(api)
    if len(devs) <= 0:
        print("No device found")
        sys.exit(1)

    for dev_id in devs:
        print("Will use device {}".format(dev_id))
        for t in range(0, 3):
            print("- Test {}".format(t))
            dev = api.get_device(dev_id)
            try:
                print("Using device {}".format(dev.get_name()))
                output_file = clean_filename(dev.get_name() + ".jpeg")
                output_file = os.path.join(output_dir, output_file)

                print("Looking for source flatbed ...")
                src = get_source(dev, "flatbed")
                list_opts(src)

                # set the options
                set_opt(src, 'resolution', [150, 200, 300])

                print("Scanning ...")
                scan(src, output_file)
                print("Scan done")
            finally:
                dev.close()

    print("All scan done")
def main():
    Libinsane.register_logger(ExampleLogger())
    #! [Logger]
    api = Libinsane.Api.new_safebet()
    print("Looking for devices ...")
    devs = api.list_devices(Libinsane.DeviceLocations.ANY)
    print("Found {} devices".format(len(devs)))
    for d in devs:
        try:
            dev = api.get_device(d.get_dev_id())
            print("|")
            print("|-- {} ({} ; {})".format(d.get_dev_id(), d.to_string(),
                                            dev.get_name()))
            try:
                for child in dev.get_children():
                    print("|   |-- {}".format(child.get_name()))
            finally:
                dev.close()
        except Exception as exc:
            print("ERROR: failed to open device {}: {}".format(
                d.get_dev_id(), str(exc)))
def main():
    if True:
        os.environ['LIBINSANE_NORMALIZER_ALL_OPTS_ON_ALL_SOURCES'] = "0"
        os.environ['LIBINSANE_NORMALIZER_BMP2RAW'] = "0"
        os.environ['LIBINSANE_NORMALIZER_CLEAN_DEV_DESCS'] = "0"
        os.environ['LIBINSANE_NORMALIZER_MIN_ONE_SOURCE'] = "0"
        os.environ['LIBINSANE_NORMALIZER_OPT_ALIASES'] = "0"
        os.environ['LIBINSANE_NORMALIZER_RAW24'] = "0"
        os.environ['LIBINSANE_NORMALIZER_RESOLUTION'] = "0"
        os.environ['LIBINSANE_NORMALIZER_SAFE_DEFAULTS'] = "0"
        os.environ['LIBINSANE_NORMALIZER_SOURCE_NAMES'] = "0"
        os.environ['LIBINSANE_NORMALIZER_SOURCE_NODES'] = "0"
        os.environ['LIBINSANE_NORMALIZER_SOURCE_TYPES'] = "0"
        os.environ['LIBINSANE_WORKAROUND_CACHE'] = "0"
        os.environ['LIBINSANE_WORKAROUND_CHECK_CAPABILITIES'] = "0"
        os.environ['LIBINSANE_WORKAROUND_DEDICATED_THREAD'] = "0"
        os.environ['LIBINSANE_WORKAROUND_ONE_PAGE_FLATBED'] = "0"
        os.environ['LIBINSANE_WORKAROUND_OPT_NAMES'] = "0"
        os.environ['LIBINSANE_WORKAROUND_OPT_VALUES'] = "0"

    Libinsane.register_logger(ExampleLogger())
    api = Libinsane.Api.new_safebet()

    devs = api.list_devices(Libinsane.DeviceLocations.ANY)
    print("Found {} devices".format(len(devs)))
    for dev in devs:
        print("")
        print("")
        print(dev.to_string())

        try:
            dev = api.get_device(dev.get_dev_id())
            children = dev.get_children()
            print("|-- Found {} sources".format(len(children)))

            for item in [dev] + children:
                print("|")
                print("|-- {} ({})".format(
                    item.get_name(), "device" if item == dev else "source"))
                opts = item.get_options()
                for opt in opts:
                    print("|   |-- {}".format(opt.get_name()))
                    print("|   |   |-- Title: {}".format(opt.get_title()))
                    print("|   |   |-- Description: {}".format(opt.get_desc()))
                    print("|   |   |-- Capabilities: {}".format(
                        opt.get_capabilities()))
                    print("|   |   |-- Unit: {}".format(opt.get_value_unit()))
                    print("|   |   |-- Constraint type: {}".format(
                        opt.get_constraint_type()))
                    print("|   |   |-- Constraint: {}".format(
                        opt.get_constraint()))
                    if opt.is_readable():
                        try:
                            print("|   |   |-- Value: {}".format(
                                opt.get_value()))
                        except Exception as exc:
                            print("|   |   |-- Value: [{}]".format(str(exc)))
                    else:
                        print("|   |   |-- Value: (unavailable)")
            print("")
            dev.close()
        except Exception as exc:
            print("EXCEPTION: {}".format(exc))
Exemplo n.º 8
0
def main():
    if False:
        os.environ['LIBINSANE_NORMALIZER_ALL_OPTS_ON_ALL_SOURCES'] = "0"
        os.environ['LIBINSANE_NORMALIZER_BMP2RAW'] = "0"
        os.environ['LIBINSANE_NORMALIZER_CLEAN_DEV_DESCS'] = "0"
        os.environ['LIBINSANE_NORMALIZER_MIN_ONE_SOURCE'] = "0"
        os.environ['LIBINSANE_NORMALIZER_OPT_ALIASES'] = "0"
        os.environ['LIBINSANE_NORMALIZER_RAW24'] = "0"
        os.environ['LIBINSANE_NORMALIZER_RESOLUTION'] = "0"
        os.environ['LIBINSANE_NORMALIZER_SAFE_DEFAULTS'] = "0"
        os.environ['LIBINSANE_NORMALIZER_SOURCE_NAMES'] = "0"
        os.environ['LIBINSANE_NORMALIZER_SOURCE_NODES'] = "0"
        os.environ['LIBINSANE_NORMALIZER_SOURCE_TYPES'] = "0"
        os.environ['LIBINSANE_WORKAROUND_CACHE'] = "0"
        os.environ['LIBINSANE_WORKAROUND_CHECK_CAPABILITIES'] = "0"
        os.environ['LIBINSANE_WORKAROUND_DEDICATED_THREAD'] = "0"
        os.environ['LIBINSANE_WORKAROUND_ONE_PAGE_FLATBED'] = "0"
        os.environ['LIBINSANE_WORKAROUND_OPT_NAMES'] = "0"
        os.environ['LIBINSANE_WORKAROUND_OPT_VALUES'] = "0"


#! [ExampleSetLogger]
    Libinsane.register_logger(ExampleLogger())
    #! [ExampleSetLogger]

    if len(sys.argv) <= 1 or (sys.argv[1] == "-h" or sys.argv[1] == "--help"):
        print("Syntax: {}"
              " <PNG output file>"
              " [<scan dev id> [<scan source name>]]".format(sys.argv[0]))
        sys.exit(1)

    output_file = sys.argv[1]
    dev_id = None
    source = None
    source_name = None
    if len(sys.argv) > 2:
        dev_id = sys.argv[2]
    if len(sys.argv) > 3:
        source_name = sys.argv[3]

    print("Will write the scan result into {}".format(output_file))

    #! [ExampleInit]
    api = Libinsane.Api.new_safebet()
    #! [ExampleInit]

    dev = get_device(api, dev_id)
    try:
        source = get_source(dev, source_name)

        list_opts(source)

        # set the options
        #! [ExampleOptsToSet]
        set_opt(source, 'resolution', 300)
        # set_opt(source, 'mode', "Lineart")
        # set_opt(source, 'depth', 1)
        #! [ExampleOptsToSet]

        print("Scanning ...")
        scan(source, output_file)
        print("Scan done")
    finally:
        dev.close()
Exemplo n.º 9
0
def main():
    Libinsane.register_logger(ExampleLogger())

    if len(sys.argv) > 1 and (sys.argv[1] == "-h" or sys.argv[1] == "--help"):
        print("Syntax: {}"
              " [<output file>]"
              " [<scan dev id> [<scan source name>]]".format(sys.argv[0]))
        sys.exit(1)

    output_file = sys.argv[1] if len(sys.argv) > 1 else "/dev/null"
    dev_id = None
    source = None
    source_name = None
    if len(sys.argv) > 2:
        dev_id = sys.argv[2]
    if len(sys.argv) > 3:
        source = sys.argv[3]

    print("Will write the scan result into {}".format(output_file))

    print("Looking for scan devices ...")
    api = Libinsane.Api.new_safebet()
    if dev_id is None:
        devs = api.list_devices(Libinsane.DeviceLocations.ANY)
        print("Found {} devices".format(len(devs)))
        for dev in devs:
            print("[{}] : [{}]".format(dev.get_dev_id(), dev.to_string()))
        dev_id = devs[0].get_dev_id()
    print("Will use device {}".format(dev_id))
    dev = api.get_device(dev_id)
    print("Using device {}".format(dev.get_name()))

    print("Looking for scan sources ...")
    sources = dev.get_children()
    print("Available scan sources:")
    for src in sources:
        print("- {}".format(src.to_string()))
        if src.get_name() == source_name:
            source = src
    if source == "root":
        source = dev
    if source_name is None:
        source = sources[0] if len(sources) > 0 else dev
    if source is None:
        print("Failed to find scan source \"{}\"".format(source_name))
        sys.exit(2)
    print("Will use scan source {}".format(source.get_name()))

    # set the options
    set_opt(source, 'source', 'Automatic Document Feeder')
    set_opt(source, 'mode', 'Color')
    set_opt(source, 'resolution', 300)
    set_opt(source, 'test-picture', 'Color pattern')

    scan_params = dev.get_scan_parameters()
    print("Expected scan parameters: {} ; {}x{} = {} bytes".format(
        scan_params.get_format(), scan_params.get_width(),
        scan_params.get_height(), scan_params.get_image_size()))
    total = scan_params.get_image_size()

    session = dev.scan_start()
    try:
        page_nb = 0
        while not session.end_of_feed() and page_nb < 20:
            img = []
            out = output_file.format(page_nb)
            r = 0
            print("Scanning page {} --> {}".format(page_nb, out))
            while True:
                data = session.read_bytes(32 * 1024)
                data = data.get_data()
                img.append(data)
                r += len(data)
                print("Got {}/{} bytes".format(r, total))
                if session.end_of_page():
                    break
            img = b"".join(img)
            img = raw_to_img(scan_params, img)
            img.save(out)
            page_nb += 1
    finally:
        session.cancel()
Exemplo n.º 10
0
from gi.repository import Libinsane


class LibinsaneLogger(GObject.GObject, Libinsane.Logger):
    CALLBACKS = {
        Libinsane.LogLevel.ERROR: _module_logger.error,
        Libinsane.LogLevel.WARNING: _module_logger.warning,
        Libinsane.LogLevel.INFO: _module_logger.info,
        Libinsane.LogLevel.DEBUG: lambda msg: 0,
    }

    def do_log(self, lvl, msg):
        self.CALLBACKS[lvl](msg)


Libinsane.register_logger(LibinsaneLogger())
libinsane = Libinsane.Api.new_safebet()

_module_logger.info('Scan library: Libinsane {}'.format(
    Libinsane.Api.get_version()))

####################################################################################################


class FileExistsError(NameError):
    pass


class PathError(NameError):
    pass