Esempio n. 1
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()
Esempio n. 2
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()
Esempio n. 3
0
    def __init__(self,
                 args,
                 face_recognition=None,
                 device=None,
                 set_device=True):
        self.args = args
        if face_recognition is None:
            face_utils.set_face_model(args, verbose=False)
            face_recognition = face.Recognition(
                face_crop_size=args.image_size,
                face_crop_margin=args.margin,
                gpu_memory_fraction=args.gpu_memory_fraction,
            )
        self.face_recognition = face_recognition
        if args.load_document_type_detector:
            # loading document type detector
            self.document_detector = document_type_detector.DocumentTypeDetector(
            )
            self.document_detector.load_document_means(
                self.args.document_type_detector_means_path)
        else:
            self.document_detector = None

        if device is None and set_device:
            # setting scanner
            pyinsane2.init()
            device = pyinsane2.Scanner(name=args.scanner_name)
            device.options["mode"].value = "Color"
            device.options["resolution"].value = 600
            if args.hp_sane_scanner:
                device.options["tl-x"].value = 1 * 65536
                device.options["tl-y"].value = 1 * 65536
                device.options["br-x"].value = 84 * 65536
                device.options["br-y"].value = 51 * 65536
        self.scanner_device = device
Esempio n. 4
0
 def onButton_scan(self, event):
     pyinsane2.init()
     try:
         scan()
     finally:
         pyinsane2.exit()
     wx.MessageBox('Scan comleated', 'Ok!', wx.OK)
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
Esempio n. 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")
Esempio n. 7
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")
Esempio n. 8
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()        
Esempio n. 9
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()
Esempio n. 10
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()
    def scan_page(self):
        self.ui.textBrowser.setPlainText("")
        self.hide_textBrowser()

        self.cleandirectory(self.tempdir)
        temp_img_name = "1.png"
        temp_img_path = os.path.join(self.tempdir, temp_img_name)
        new_list = []
        self.scanAction.setEnabled(False)
        self.statusBar().showMessage("Scanning")
        pyinsane2.init()
        self.scan_thread.start()
Esempio n. 12
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")
Esempio n. 13
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
Esempio n. 14
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()
Esempio n. 15
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
Esempio n. 16
0
def main(hook_func=None):
    """
    Where everything start.
    """
    LogTracker.init()

    set_locale()

    GLib.threads_init()
    GObject.threads_init()
    Gdk.threads_init()

    if hasattr(GLib, 'set_application_name'):
        GLib.set_application_name("Paperwork")
    if hasattr(GLib, "unix_signal_add"):
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                             Gtk.main_quit, None)
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM,
                             Gtk.main_quit, None)

    try:
        pyinsane2.init()

        config = load_config()
        config.read()

        main_win = MainWindow(config)
        ActionRefreshIndex(main_win, config).do()

        if hook_func:
            thread = threading.Thread(target=hook_func,
                                      args=(config, main_win))
            thread.start()

        Gtk.main()

        for scheduler in main_win.schedulers.values():
            scheduler.stop()

        config.write()
    finally:
        logger.info("Good bye")
Esempio n. 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()
Esempio n. 18
0
def main(hook_func=None, skip_workdir_scan=False):
    """
    Where everything start.
    """
    LogTracker.init()

    set_locale()

    if hasattr(GLib, 'set_application_name'):
        GLib.set_application_name("Paperwork")
    if hasattr(GLib, "unix_signal_add"):
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                             Gtk.main_quit, None)
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM,
                             Gtk.main_quit, None)

    try:
        pyinsane2.init()

        config = load_config()
        config.read()

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

        if hook_func:
            hook_func(config, main_win)

        Gtk.main()

        for scheduler in main_win.schedulers.values():
            scheduler.stop()

        config.write()
    finally:
        logger.info("Good bye")
Esempio n. 19
0
def setup_device(device_name=None, resolution=300, mode="Gray"):

    pyinsane2.init()

    if device_name is not None:
        device = pyinsane2.Scanner(name="brother4:net1;dev0")
    else:
        devices = pyinsane2.get_devices()
        print("Scanners found:")
        for i, d in enumerate(devices):
            print(f"[{i}] {d}")
        device = devices[int(input("Select which one to use: "))]

    print(f"Will use: {device}")
    pyinsane2.set_scanner_opt(device, "source", ["Auto", "FlatBed"])
    pyinsane2.set_scanner_opt(device, "resolution", [resolution])
    try:
        pyinsane2.maximize_scan_area(device)
    except Exception as exc:
        print(f"Failed to maximize scan area: {exc}")
    pyinsane2.set_scanner_opt(device, "mode", [mode])

    return device
Esempio n. 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()
Esempio n. 21
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()
Esempio n. 22
0
 def setUp(self):
     pyinsane2.init()
Esempio n. 23
0
 def setUp(self):
     pyinsane2.init()
Esempio n. 24
0
 def setUp(self):
     pyinsane2.init()
     devices = pyinsane2.get_devices()
     self.assertTrue(len(devices) > 0)
     self.dev = devices[0]
Esempio n. 25
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()
 def __init__(self):
     pyinsane2.init()
Esempio n. 27
0
 def setUp(self):
     pyinsane2.init()
     devices = get_devices()
     self.assertTrue(len(devices) > 0)
     self.dev = devices[0]
Esempio n. 28
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()
Esempio n. 29
0
def sane(sanevariables, resolution=100, mode="Color", multiple=False ):

    # 先查看iventory文件夹是否存在
    inventory = createPageDir(InventoryPath)
    

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

            print('I am going to use the following scanner: %s' %(str(device)))
            scanner_id = device.name


            try:
                pyinsane2.set_scan_area_pos(device, 'source', ['ADF', 'Feeder'])

            except Exception as e:
                print(e)

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

        #     pyinsane2.set_scanner_opt(device, 'mode', [mode])

        #     pyinsane2.maximize_scan_area(device)

        #     try :
        #         scan_session = device.scan(multiple=multiple)
        #         print('scanning--------------------')
        #         while True:
        #             try:
        #                 scan_session.scan.read()
        #             except EOFError:
        #                 print("Got page %d" % (len(scan_session.images)))
        #                 img = scan_session.images[-1]
        #                 SaneTime = str(int(time.time()))
        #                 # 以时间戳的形式存储扫描结果为  "时间戳.jpg"
        #                 SanPathName = createPagePath(inventory, SaneTime+'.jpg')
                        
        #                 # imgpath = os.path.join('test111.jpg')
        #                 img.save(SanPathName)

        #                 # 将扫描出来的多余大片白色区域去掉
        #                 reshapeImg = origin_reshape.reshape(SanPathName, sanevariables)

        #                 # 寻找学号填写的格子,来判断是否是可以解析的扫描结果
        #                 # studentFrames.dectionStudentIDFrame(reshapeImg, )
                        
        #                 # 判断是否是上下颠倒的图片
        #                 # upsideDown = origin_reshape.upsideDown()
        #                 cv2.imwrite(SanPathName, reshapeImg)

        #     except StopIteration:
        #             print("Got %d pages" % len(scan_session.images))

        # else:
        #     print('没有找到打印机')
    except EOFError as err:
        # print(err)
        print('f**k')
    finally:
        print(1111)