Example #1
0
def main():
    import pyinsane2

    pyinsane2.init()
    try:
        devices = pyinsane2.get_devices()
        assert(len(devices) > 0)
        device = devices[0]
        print("I'm going to use the following scanner: %s" % (str(device)))

        pyinsane2.set_scanner_opt(device, 'resolution', [300])

    # Beware: Some scanners have "Lineart" or "Gray" as default mode
    # better set the mode everytime
        pyinsane2.set_scanner_opt(device, 'mode', ['Color'])

    # Beware: by default, some scanners only scan part of the area
    # they could scan.
        pyinsane2.maximize_scan_area(device)

        scan_session = device.scan(multiple=False)
        try:
            while True:
                scan_session.scan.read()
        except EOFError:
            pass
        image = scan_session.images[-1]
        image.save("output/"+str(datetime.datetime.now())+".png")

    finally:
        pyinsane2.exit()
def getImageFromScanner():

    try:
        import pyinsane2
    except:
        print "Scanning feature not supported on this OS. Disabling it..."

    pyinsane2.init()
    try:
        devices = pyinsane2.get_devices()
        assert (len(devices) > 0)
        device = devices[0]
        print("I'm going to use the following scanner: %s" % (str(device)))

        pyinsane2.set_scanner_opt(device, 'resolution', [75])

        # Beware: Some scanners have "Lineart" or "Gray" as default mode
        # better set the mode everytime

        # Beware: by default, some scanners only scan part of the area
        # they could scan.
        pyinsane2.maximize_scan_area(device)

        scan_session = device.scan(multiple=False)
        try:
            while True:
                scan_session.scan.read()
        except EOFError:
            pass
        finally:
            image = scan_session.images[-1]
            return image
    finally:
        pyinsane2.exit()
        return None
Example #3
0
 def onButton_scan(self, event):
     pyinsane2.init()
     try:
         scan()
     finally:
         pyinsane2.exit()
     wx.MessageBox('Scan comleated', 'Ok!', wx.OK)
Example #4
0
def scan_cards():
    pyinsane2.init()
    devices = pyinsane2.get_devices()
    try:
        device = devices[0]
        print(f'PyInsane2 initiatied using {device.name}.')
        # device.options['AutoDocumentSize']
        # Specify color scanning
        pyinsane2.set_scanner_opt(device, 'mode', ['24bit Color[Fast]'])
        # Set scan resolution
        pyinsane2.set_scanner_opt(device, 'resolution', [200])
        pyinsane2.maximize_scan_area(device)
        try:
            pyinsane2.set_scanner_opt(
                device, 'source',
                ['Automatic Document Feeder(center aligned,Duplex)'])
        except pyinsane2.PyinsaneException as e:
            print('No document feeder found', e)
        try:
            scan_session = device.scan(multiple=True)
            print("Scanning ...")
            while True:
                try:
                    scan_session.scan.read()
                except EOFError:
                    print('scanning page')
        except StopIteration:
            im_list = scan_session.images
            pyinsane2.exit()
            return im_list
    except:
        pyinsane2.exit()
Example #5
0
    def main(self, hook_func=None, skip_workdir_scan=False):
        """
        Where everything start.
        """
        parser = argparse.ArgumentParser(
            description='Manages scanned documents and PDFs')
        parser.add_argument('--version',
                            action='version',
                            version=str(__version__))
        parser.add_argument(
            "--debug",
            "-d",
            default=os.getenv("PAPERWORK_VERBOSE", "INFO"),
            choices=LogTracker.LOG_LEVELS.keys(),
            help="Set verbosity level. Can also be set via env"
            " PAPERWORK_VERBOSE (e.g. export PAPERWORK_VERBOSE=INFO)")
        args, unknown_args = parser.parse_known_args(sys.argv[1:])

        LogTracker.init()
        logging.getLogger().setLevel(LogTracker.LOG_LEVELS.get(args.debug))

        set_locale()

        if hasattr(GLib, "unix_signal_add"):
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                                 self.quit_nicely, None)
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM,
                                 self.quit_nicely, None)

        backend_state = paperwork_backend.init()

        logger.info("Initializing pyinsane ...")
        pyinsane2.init()
        try:
            logger.info("Initializing libnotify ...")
            Notify.init("Paperwork")

            self.config = load_config()
            self.config.read()

            self.main_win = MainWindow(self.config,
                                       self.main_loop,
                                       not skip_workdir_scan,
                                       flatpak=backend_state['flatpak'])
            if hook_func:
                hook_func(self.config, self.main_win)

            self.main_loop.run()

            logger.info("Writing configuration ...")
            self.config.write()

            logger.info("Stopping libnotify ...")
            Notify.uninit()
        finally:
            logger.info("Stopping Pyinsane ...")
            pyinsane2.exit()
        logger.info("Good bye")
Example #6
0
    def main(self, hook_func=None, skip_workdir_scan=False):
        """
        Where everything start.
        """
        parser = argparse.ArgumentParser(
            description='Manages scanned documents and PDFs'
        )
        parser.add_argument('--version', action='version',
                            version=str(__version__))
        parser.add_argument(
            "--debug", "-d", default=os.getenv("PAPERWORK_VERBOSE", "INFO"),
            choices=LogTracker.LOG_LEVELS.keys(),
            help="Set verbosity level. Can also be set via env"
            " PAPERWORK_VERBOSE (e.g. export PAPERWORK_VERBOSE=INFO)"
        )
        args, unknown_args = parser.parse_known_args(sys.argv[1:])

        LogTracker.init()
        logging.getLogger().setLevel(LogTracker.LOG_LEVELS.get(args.debug))

        set_locale()

        if hasattr(GLib, "unix_signal_add"):
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                                 self.quit_nicely, None)
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM,
                                 self.quit_nicely, None)

        backend_state = paperwork_backend.init()

        logger.info("Initializing pyinsane ...")
        pyinsane2.init()
        try:
            logger.info("Initializing libnotify ...")
            Notify.init("Paperwork")

            self.config = load_config()
            self.config.read()

            self.main_win = MainWindow(
                self.config, self.main_loop, not skip_workdir_scan,
                flatpak=backend_state['flatpak']
            )
            if hook_func:
                hook_func(self.config, self.main_win)

            self.main_loop.run()

            logger.info("Writing configuration ...")
            self.config.write()

            logger.info("Stopping libnotify ...")
            Notify.uninit()
        finally:
            logger.info("Stopping Pyinsane ...")
            pyinsane2.exit()
        logger.info("Good bye")
Example #7
0
    def scanthread(self):  
        self.countread =0  
        pyinsane2.init()
        try:
            devices = pyinsane2.get_devices()
            if len(devices) > 0 :
                assert(len(devices) > 0)
                device = devices[0]
            
                GLib.idle_add(self.showprogressbar)
                pyinsane2.set_scanner_opt(device, 'resolution', [300])

                # Beware: Some scanners have "Lineart" or "Gray" as default mode
                # better set the mode everytime
                pyinsane2.set_scanner_opt(device, 'mode', ['Color'])

                # Beware: by default, some scanners only scan part of the area
                # they could scan.
                pyinsane2.maximize_scan_area(device)

                scan_session = device.scan(multiple=False)
                try:
                    while True:
                        scan_session.scan.read()
                        GLib.idle_add(self.updatescanprogress)
                       
                except EOFError:
                    pass
                scannedimage = scan_session.images[-1]
                GLib.idle_add(self.closescanprogress)
                jsonFile = open('conf.json', 'r')
                conf = json.load(jsonFile)
                ws_dir = conf["workspace_dir"]
                filename = ws_dir +"/" + str(datetime.datetime.now()) 
                global imgloc
                imgloc = filename
              
                scannedimage.save(filename,"JPEG")
                jsonFile.close()
                textviewinitial = builder.get_object("outputtextview")
                textviewinitial.get_buffer().set_text('')
                img = builder.get_object("previmage")
                img.set_from_file(imgloc)
                global skewcorrected
                skewcorrected = 0
                global zoomout
                zoomout = 1
             
            else:
             
                GLib.idle_add(self.nodeviceconnected)
                
            

        finally:
            pyinsane2.exit()        
Example #8
0
def main():
    parser = argparse.ArgumentParser(
        description="Scanning Program for rapid scanning with "
        "manual switching on a flatbed.")
    parser.add_argument("dest_dir",
                        type=str,
                        help="Directory to store scans in")
    parser.add_argument(
        "-p",
        "--prefix",
        type=str,
        default="brotherscan",
        help="Prefix for saved files.",
    )
    parser.add_argument(
        "-d",
        "--device",
        type=str,
        default=None,
        help="Name of device to use for scanning.",
    )
    parser.add_argument(
        "-t",
        "--timeout",
        type=int,
        default=0,
        help="Time between scans. 0 means wait for user input.",
    )
    args = parser.parse_args()

    dest_dir = pathlib.Path(os.path.expanduser(args.dest_dir)).absolute()
    dest_dir.mkdir(exist_ok=True)
    base_name = dest_dir.joinpath(args.prefix)
    device = setup_device(args.device, 300, "Gray")

    try:
        preexisting = [
            int(re.search(args.prefix + "_([\d]{3}).pdf", str(x)).groups()[0])
            for x in dest_dir.glob(args.prefix + "*.pdf")
        ]
        n = max(preexisting) + 1 if preexisting else 0
        while True:
            n += 1
            scan(device, f"{base_name}_{n:03d}.pdf")
            if args.timeout:
                for _ in tqdm.tqdm(range(int(args.timeout / 0.1)),
                                   desc="Sleeping"):
                    time.sleep(0.1)
            else:
                input("Press Enter to start scanning...")
    except (Exception, KeyboardInterrupt):
        pass
    finally:
        pyinsane2.exit()
Example #9
0
def login():

    pyinsane2.init()
    try:
        devices = pyinsane2.get_devices()
        assert (len(devices) > 0)
        device = devices[0]

        print("I'm going to use the following scanner: %s" % (str(device)))
        scanner_id = device.name
    finally:
        pyinsane2.exit()
Example #10
0
 def check_scanner_alive(cls):
     pyinsane2.init()
     try:
         devices = pyinsane2.get_devices()
         device = None
         if devices:
             device = devices[0]
             return str(device)
         else:
             return "No device"
     finally:
         pyinsane2.exit()
 def scanning_complete(self, scanned_list):
     pyinsane2.exit()
     self.statusBar().showMessage("")
     self.scanAction.setEnabled(True)
     if scanned_list:
         print("scanning successful")
         self.newImageList(scanned_list)
     else:
         QtWidgets.QMessageBox.critical(
             self,
             "Scanner Not Found",
             "No scanner was detected.\nYour scanner may not be connected properly.\nOr your scanner model may not be supported (see www.sane-project.org/lists/sane-mfgs-cvs.html for a list of supported devices).",
             QtWidgets.QMessageBox.Ok,
         )
 def com_hardware_scanner_scan(self, scanner_device, resolution, file_name):
     try:
         pyinsane2.set_scanner_opt(
             scanner_device, 'resolution', [resolution])
         pyinsane2.set_scanner_opt(scanner_device, 'mode', ['Color'])
         pyinsane2.maximize_scan_area(scanner_device)
         scan_session = scanner_device.scan(multiple=False)
         try:
             while True:
                 scan_session.scan.read()
         except EOFError:
             pass
         image = scan_session.images[-1]
         common_file.com_file_save_data(file_name, image)
     finally:
         pyinsane2.exit()
Example #13
0
    def main(self, hook_func=None, skip_workdir_scan=False):
        """
        Where everything start.
        """
        LogTracker.init()

        set_locale()

        if hasattr(GLib, "unix_signal_add"):
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                                 self.quit_nicely, None)
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM,
                                 self.quit_nicely, None)

        logger.info("Initializing pyinsane ...")
        pyinsane2.init()
        try:
            logger.info("Initializing libnotify ...")
            Notify.init("Paperwork")

            self.config = load_config()
            self.config.read()

            self.main_win = MainWindow(self.config, self.main_loop)
            ActionRefreshIndex(self.main_win,
                               self.config,
                               skip_examination=skip_workdir_scan).do()

            if hook_func:
                hook_func(self.config, self.main_win)

            self.main_loop.run()

            logger.info("Stopping schedulers ...")
            for scheduler in self.main_win.schedulers.values():
                scheduler.stop()

            logger.info("Writing configuration ...")
            self.config.write()

            logger.info("Stopping libnotify ...")
            Notify.uninit()
        finally:
            logger.info("Stopping Pyinsane ...")
            pyinsane2.exit()
        logger.info("Good bye")
Example #14
0
def check_sane():
    import pyinsane2
    missing = []
    try:
        pyinsane2.init()
        pyinsane2.exit()
    except:
        missing.append((
            'libsane',
            '(none)',
            {
                'debian': 'libsane',
                'fedora': 'sane-backends',
                'linuxmint': 'libsane',
                'ubuntu': 'libsane',
            },
        ))
    return missing
Example #15
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-o",
                        "--output_name",
                        default="scansione.jpg",
                        help="string to search into")
    parser.add_argument("-r",
                        "--resolution",
                        default="150",
                        help="string to search into")
    args = parser.parse_args()
    output_name = args.output_name
    resolution = args.resolution

    pyinsane2.init()

    try:
        devices = pyinsane2.get_devices()
        assert (len(devices) > 0)
        device = devices[0]
        print("I'm going to use the following scanner: %s" % (str(device)))

        pyinsane2.set_scanner_opt(device, 'resolution', [int(resolution)])

        # Beware: Some scanners have "Lineart" or "Gray" as default mode
        # better set the mode everytime
        #	pyinsane2.set_scanner_opt(device, 'mode', 'Gray')

        # Beware: by default, some scanners only scan part of the area
        # they could scan.
        pyinsane2.maximize_scan_area(device)

        scan_session = device.scan(multiple=False)
        try:
            while True:
                scan_session.scan.read()
        except EOFError:
            pass
        image = scan_session.images[-1]
        image.save(output_name, "JPEG")
        print("Done")
    finally:
        pyinsane2.exit()
Example #16
0
def check_sane():
    import pyinsane2
    missing = []
    try:
        pyinsane2.init()
        pyinsane2.exit()
    except:  # noqa: E722
        missing.append(
            (
                'libsane', '(none)',
                {
                    'debian': 'libsane',
                    'fedora': 'sane-backends',
                    'linuxmint': 'libsane',
                    'ubuntu': 'libsane',
                },
            )
        )
    return missing
Example #17
0
def main():
    import pyinsane2

    pyinsane2.init()
    try:
        devices = pyinsane2.get_devices()
        assert (len(devices) > 0)
        device = devices[0]
        print("I'm going to use the following scanner: %s" % (str(device)))

        try:
            pyinsane2.set_scanner_opt(device, 'source', ['ADF', 'Feeder'])
        except PyinsaneException:
            print("No document feeder found")
            return

    # Beware: Some scanners have "Lineart" or "Gray" as default mode
    # better set the mode everytime
        pyinsane2.set_scanner_opt(device, 'mode', ['Color'])

        # Beware: by default, some scanners only scan part of the area
        # they could scan.
        pyinsane2.maximize_scan_area(device)

        scan_session = device.scan(multiple=True)
        try:
            while True:
                try:
                    scan_session.scan.read()
                except EOFError:
                    print("Got a page ! (current number of pages read: %d)" %
                          (len(scan_session.images)))
        except StopIteration:
            print("Document feeder is now empty. Got %d pages" %
                  len(scan_session.images))

        for idx in range(0, len(scan_session.images)):
            image = scan_session.images[idx]
            image.save("output/" + str(datetime.datetime.now()) + ".png")
    finally:
        pyinsane2.exit()
Example #18
0
def Scan(Device, Param):
    '''
    This function makes use of the Pyinsane2 module and captures an image with the scanner. 
    
    Input:
    ---------------------
    Device (pyinsane2.wia.abstract.Scanner): 
        Selected scanner.
    
    Param (Dictionary):
        {'Brightness': Int, 'Contrast': int, 'Resolution': int} 
        
    Returns:
    ---------------------
        Image
        
    **NOTE
        If you want to use this function by itself, you first must start pyinsane by running: 
            pyinsane2.init()
            Device = pyinsane2.get_devices()
    '''
    Device.options['brightness'].value = Param['Brightness']
    Device.options['contrast'].value = Param['Contrast']

    try:
        pyinsane2.set_scanner_opt(Device, 'resolution', [Param['Resolution']])
        pyinsane2.set_scanner_opt(Device, 'mode', ['Color'])
        pyinsane2.maximize_scan_area(Device)
        scan_session = Device.scan(multiple=False)
        try:
            while True:
                scan_session.scan.read()
        except EOFError:
            pass
        Image = scan_session.images[-1]
    finally:
        pyinsane2.exit()
    return (Image)
Example #19
0
    def scan_document(self, filename):
        """
            Scan a new document and save it as 'filename'
            possible resolutions are : 75, 100, 200, 300, 600, 1200
        """
        pyinsane2.init()

        try:
            devices = pyinsane2.get_devices()
            device = None
            if devices:
                device = devices[0]
                print("I'm going to use the following scanner: %s" %
                      (str(device)))
                pyinsane2.set_scanner_opt(device, 'resolution', [75])
            else:
                print(
                    "Check if scanner is online, and you have the correct WIFI connection!"
                )

            # Scan in color mode
            pyinsane2.set_scanner_opt(device, 'mode', ['Color'])

            pyinsane2.maximize_scan_area(device)

            scan_session = device.scan(multiple=False)
            try:
                print("Initiating Scan operation")
                while True:
                    scan_session.scan.read()
            except EOFError:
                pass
            image = scan_session.images[-1]
            print("Saving image")
            image.save(filename)
        finally:
            pyinsane2.exit()
Example #20
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-o", "--output_name", default="scansione.jpg", help="string to search into")
    parser.add_argument("-r", "--resolution", default="150", help="string to search into")
    args = parser.parse_args()
    output_name=args.output_name
    resolution=args.resolution 

    pyinsane2.init()

    try:
            devices = pyinsane2.get_devices()
            assert(len(devices) > 0)
            device = devices[0]
            print("I'm going to use the following scanner: %s" % (str(device)))

            pyinsane2.set_scanner_opt(device, 'resolution', [int(resolution)])

    # Beware: Some scanners have "Lineart" or "Gray" as default mode
    # better set the mode everytime
    #	pyinsane2.set_scanner_opt(device, 'mode', 'Gray')

    # Beware: by default, some scanners only scan part of the area
    # they could scan.
            pyinsane2.maximize_scan_area(device)

            scan_session = device.scan(multiple=False)
            try:
                    while True:
                            scan_session.scan.read()
            except EOFError:
                    pass
            image = scan_session.images[-1]
            image.save(output_name, "JPEG")
            print("Done")
    finally:
            pyinsane2.exit()
Example #21
0
 def tearDown(self):
     del(self.dev)
     pyinsane2.exit()
Example #22
0
 def tearDown(self):
     for dev in self.devices:
         del(dev)
     del(self.devices)
     pyinsane2.exit()
 def com_hardware_scanner_close(self):
     pyinsane2.exit()
Example #24
0
            i += 1
            i %= len(PROGRESSION_INDICATOR)
            sys.stdout.write("\b%s" % PROGRESSION_INDICATOR[i])
            sys.stdout.flush()

            scan_session.scan.read()

            if steps:
                next_line = scan_session.scan.available_lines[1]
                if (next_line > last_line + 100):
                    subimg = scan_session.scan.get_image(last_line, next_line)
                    img.paste(subimg, (0, last_line))
                    img.save("%s-%05d.%s" % (steps_filename[0], last_line,
                                             steps_filename[1]), "JPEG")
                    last_line = next_line
    except EOFError:
        pass

    print("\b ")
    print("Writing output file ...")
    img = scan_session.images[0]
    img.save(output_file, "JPEG")
    print("Done")

if __name__ == "__main__":
    pyinsane2.init()
    try:
        main()
    finally:
        pyinsane2.exit()
Example #25
0
 def tearDown(self):
     for dev in self.devices:
         del(dev)
     del(self.devices)
     pyinsane2.exit()
Example #26
0
 def tearDown(self):
     pyinsane2.exit()
Example #27
0
 def exit(self):
     pyinsane2.exit()
Example #28
0
 def tearDown(self):
     pyinsane2.exit()
Example #29
0
    # is not guaranteed : It may raise StopIteration() immediately
    # or it may raise it when scan.read() is called

    try:
        scan_session = device.scan(multiple=True)
        print("Scanning ...")
        while True:
            try:
                scan_session.scan.read()
            except EOFError:
                print("Got page %d" % (len(scan_session.images)))
                img = scan_session.images[-1]
                imgpath = os.path.join(dstdir, "%d.jpg" %
                                       (len(scan_session.images)))
                img.save(imgpath)
    except StopIteration:
        print("Got %d pages" % len(scan_session.images))


if __name__ == "__main__":
    args = sys.argv[1:]
    if len(args) <= 0 or args[0][0] == '-':
        print("Usage:")
        print("  %s <dst directory>" % sys.argv[0])
        sys.exit(1)
    pyinsane2.init()
    try:
        main(args)
    finally:
        pyinsane2.exit()
Example #30
0
 def tearDown(self):
     del(self.dev)
     pyinsane2.exit()