[Pycodeocr-main] SF.net SVN: pycodeocr:[51] trunk
Status: Beta
Brought to you by:
drtrigon
|
From: <drt...@us...> - 2011-04-27 20:26:27
|
Revision: 51
http://pycodeocr.svn.sourceforge.net/pycodeocr/?rev=51&view=rev
Author: drtrigon
Date: 2011-04-27 20:26:18 +0000 (Wed, 27 Apr 2011)
Log Message:
-----------
more OCR code moved to utils, now main code below 1000 lines ;)
Modified Paths:
--------------
trunk/PyCodeOCR.py
trunk/utils/__init__.py
trunk/utils/checksum.py
trunk/utils/ocr.py
Property Changed:
----------------
trunk/utils/__init__.py
Modified: trunk/PyCodeOCR.py
===================================================================
--- trunk/PyCodeOCR.py 2011-04-27 19:43:41 UTC (rev 50)
+++ trunk/PyCodeOCR.py 2011-04-27 20:26:18 UTC (rev 51)
@@ -9,9 +9,6 @@
#
# $Id$
#
-# @todo This module/script has become large (more than 1000 lines)
-# and should be splitted into seperate files.
-#
# For further information please consult the @ref mainpage also.
#
# @mainpage PyCodeOCR
@@ -39,7 +36,7 @@
#
# python standard modules
-import os, re, sys, subprocess, time, gobject, string, struct
+import os, re, sys, time
# PyCodeOCR python standard utils (modules)
import utils
@@ -63,7 +60,6 @@
# PIL image library and it's SANE bindings
import Image, ImageDraw
#from PIL import Image
-import sane # f12: 'python-imaging-sane'
#(fedora 12 has no libWand, so it's not working at the moment...)
# ImageMagick's MagickWand API
@@ -102,6 +98,7 @@
# global variables and constants
## path from which this program is currently executed
local_path = os.path.realpath(os.path.dirname(sys.argv[0]))
+utils.ocr.local_path = local_path # (ugly patch)
## path of program without extension local_path/PyCodeOCR
raw_path = os.path.join(local_path, os.path.splitext(sys.argv[0])[0])
## users home path /home/user
@@ -256,7 +253,7 @@
# lock window
self.window1.set_sensitive(False)
# init sane
- self.run_sane = RunSANE(self.progress, self.window2, self.treeview1)
+ self.run_sane = utils.ocr.RunSANE(self.progress, self.window2, self.treeview1)
# try to set sensitivity, fails if no scanner is initialized yet
try:
@@ -465,7 +462,7 @@
self.on_spinbutton_value_changed() # scan selected range
self.on_combobox1_changed() # orientation mode
opt = { 'tmp_file': "02.tif",
- 'recog_class': RunExternal,
+ 'recog_class': utils.ocr.RunExternal,
'recog_cmd': self.cmd_tesser % (self.temp+"02", self.temp+"03"),
'recog_error_msg': [ "Unable" ],
'valid_code_len': self.valid_code_len,
@@ -475,7 +472,7 @@
self.scan_koords = std_scan_koords["A4"][0]
#self.mode = std_scan_koords["A4"][1]
opt = { 'tmp_file': "02.pnm",
- 'recog_class': RunExternal,
+ 'recog_class': utils.ocr.RunExternal,
'recog_cmd': self.cmd_gocr % (self.temp+"02",),
'recog_error_msg': [ "\nERROR pnm.c" ],
'valid_code_len': [ 13, 10, 9 ],
@@ -486,25 +483,25 @@
self.mode = std_scan_koords["A4"][1]
#pydmtx recognition
# opt = { 'tmp_file': "02.jpg", # some issues with recogition
-# 'recog_class': RunLibdmtx, # .
+# 'recog_class': utils.ocr.RunLibdmtx, # .
# 'recog_cmd': self.temp+"02.jpg", # of different file formats
# 'recog_error_msg': [ None ], # .
#dmtxread recognition
opt = { 'tmp_file': "02.jpg", # some issues with recogition
- 'recog_class': RunExternal, # .
+ 'recog_class': utils.ocr.RunExternal, # .
'recog_cmd': "%s -v -D %s02.jpg"%(paths["dmtxread"],self.temp), # of different file formats
'recog_error_msg': [ "error" ], # .
#opt = { 'tmp_file': "02.bmp", # and drawing/marking the
- # 'recog_cmd': (self.temp+"02.bmp", [ None ], RunLibdmtx), } # processed region(s)...
+ # 'recog_cmd': (self.temp+"02.bmp", [ None ], utils.ocr.RunLibdmtx), } # processed region(s)...
#opt = { 'tmp_file': "02.png", # (but this should work for 'tif')
- # 'recog_cmd': (self.temp+"02.png", [ None ], RunLibdmtx), } #
+ # 'recog_cmd': (self.temp+"02.png", [ None ], utils.ocr.RunLibdmtx), } #
'resolution': 150, }
elif (op_mode == self.MDE['PDF417']): # 3: PDF417 barcode (pdf417decode/wine)
self.on_spinbutton_value_changed() # scan selected range
self.on_combobox1_changed() # orientation mode
opt = { 'tmp_file': "02.png",
- 'recog_class': RunExternal,
+ 'recog_class': utils.ocr.RunExternal,
'recog_cmd': self.cmd_pdf417dec % (self.temp+"02",),
'recog_error_msg': [ "wine: cannot find", "pdf417decode.exe imagefile|string.txt|-i", "Decoding failed." ],
'resolution': 300, }
@@ -519,8 +516,8 @@
if source_mode: # SANE scanning interface
self.progress(1./max_steps, "Scanning data...")
self.inp_file = self.temp+"01.tif"
- #self.run_sane = RunExternal(self.cmd_scan % ( self.scan_koords + (inp_file,) ), [ "no SANE devices found" ])
- self.run_sane.post_init(self.scan_koords, self.inp_file) # RunSANE().post_init(...) 2nd part of __init__(...)
+ #self.run_sane = utils.ocr.RunExternal(self.cmd_scan % ( self.scan_koords + (inp_file,) ), [ "no SANE devices found" ])
+ self.run_sane.post_init(self.scan_koords, self.inp_file) # utils.ocr.RunSANE().post_init(...) 2nd part of __init__(...)
self.run_sane.resolution = opt["resolution"]
if self.run_sane():
self.progress(0., self.run_sane.stderr)
@@ -545,8 +542,8 @@
print "No input file. Please select input file or SANE Interface."
#self.progress(0., "No input file. Please select input file or SANE Interface.")
return None
- self.run_convert = RunExternal(self.cmd_convert % (self.inp_file, mode, self.temp+opt['tmp_file']), error_msg=[ "convert: unable to open image" ])
-# self.run_convert = RunMagickWand(inp_file, mode*90, self.temp+opt['tmp_file'])
+ self.run_convert = utils.ocr.RunExternal(self.cmd_convert % (self.inp_file, mode, self.temp+opt['tmp_file']), error_msg=[ "convert: unable to open image" ])
+# self.run_convert = utils.ocr.RunMagickWand(inp_file, mode*90, self.temp+opt['tmp_file'])
# improve quality by using imagemagicks filter and conversion capabilities...
if self.run_convert():
self.progress(0., self.run_convert.stderr[:-1])
@@ -742,7 +739,7 @@
im1 = Image.open(self.imageFile)
else:
#convert Image
- self.run_convert = RunExternal(self.cmd_convert % (imageFile, 0, self.temp+"04.jpg"), error_msg=[ "convert: unable to open image" ])
+ self.run_convert = utils.ocr.RunExternal(self.cmd_convert % (imageFile, 0, self.temp+"04.jpg"), error_msg=[ "convert: unable to open image" ])
if self.run_convert():
self.progress(0., self.run_convert.stderr[:-1])
return None
@@ -777,285 +774,6 @@
self.progressbar1.set_text(text)
self.refresh()
-## Run external shell command/application.
-class RunExternal:
-
- error_msg = [ "/bin/sh: " ]
-
- ## initialize
- def __init__(self, cmd, error_msg):
- self.cmd = cmd
- self.error_msg += error_msg
-
- ## call
- def __call__(self):
- (self.error, self.stdout, self.stderr) = self._run()
- return self.error
-
- ## Execute external shell command.
- def _run(self, piped=True):
- if piped:
- run = subprocess.Popen( self.cmd,
- stdin =subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- shell=True )
- (stdoutdata, stderrdata) = run.communicate()
- return ((max(map(stderrdata.find, self.error_msg)) != -1), stdoutdata, stderrdata)
- else:
- os.system( self.cmd )
- return (False, "", "")
-
-#class RunLibdmtx:
-# """ Use libdmtx python wrapper/bindings (pydmtx). """
-
-# def __init__(self, cmd, error_msg):
-# #self.cmd = cmd
-# #self.error_msg += error_msg
-# self.filename = cmd
-
-# def __call__(self):
-# (self.error, self.stdout, self.stderr) = self._run()
-# return self.error
-
-# # thanks to: http://www.pastequestion.com/blog/python/how-to-use-python-imaging-library.html
-# def _run(self):
-# """ Read a Data Matrix barcode. """
-# dm_read = DataMatrix()
-# #print self.filename
-# img = Image.open(self.filename)
-# try:
-# self.decode = dm_read.decode(img.size[0], img.size[1], buffer(img.tostring()))
-# self.count = dm_read.count()
-# self.message = [ dm_read.message(i+1) for i in range(self.count) ]
-# self.stats = [ dm_read.stats(i+1) for i in range(self.count) ]
-# except:
-# return (True, "error", sys.exc_info()[1])
-
-# print "Detected %i DataMatrix barcodes" % self.count
-# for i in range(self.count):
-# print "Code # %i:" % (i+1)
-# print self.message[i]
-# stats = self.stats[i]
-# print stats
-
-# # mark the recognized region and save back to file
-# points = list(stats[1])
-# points.append(points[0])
-# draw = ImageDraw.Draw(img)
-# old = points[0]
-# for i, xy in enumerate(points[1:]):
-# #draw.line(old+xy, fill=(0, 255, 0), width=2)
-# #draw.line(old+xy, fill=(0, 255, 0))
-# draw.line(old+xy, fill="rgb(0, 255, 0)")
-# old = xy
-# img.save(self.filename)
-
-# #return (False, self.message, "")
-# #print self.stats, (self.count == 0)
-# return ((self.count == 0), self.message, "")
-
-#class RunMagickWand:
-# """ Use Python bindings to ImageMagick's MagickWand API. """
-# # "convert %s.tif -crop 1600x250+800+960 -depth 8 %s.tif"
-# # "convert %s.tif -crop 1700x250+750+960 -depth 8 %s.tif"
-# # "convert %s.tif -crop 3400x500+1500+1900 -depth 8 %s.tif"
-# # "convert %s.tif -depth 8 %s.tif"
-# # "convert %s.tif -depth 8 -rotate %d %s.tif"
-# # "convert %s.tif -depth 8 -rotate %d %s"
-# #cmd_convert = "convert %s -depth 8 -rotate %d %s"
-#
-# def __init__(self, inp_filename, rotate, out_filename):
-# self.inp_filename = inp_filename
-# self.out_filename = out_filename
-# self.angle = rotate
-# self.depth = 8
-#
-# def __call__(self):
-# (self.error, self.stdout, self.stderr) = self._run()
-# return self.error
-#
-# # thanks to: http://www.assembla.com/wiki/show/pythonmagickwand
-# def _run(self):
-# """ This rotates, changes depth, format and writes a new file. """
-# try:
-# i = Image(self.inp_filename)
-# i.rotate(self.angle)
-# i.depth(self.depth)
-# i.format = self.out_filename[-3:].upper()
-# i.save(self.out_filename)
-# except:
-# return (True, "error", sys.exc_info()[1])
-#
-# return (False, "ok", "")
-
-## sSANE/PIL interface python wrapper/bindings.
-class RunSANE:
- # "scanimage --format=tif --resolution 300 --mode Gray > %s.tif"
- # "scanimage --format=tif --resolution 600 --mode Gray -t 82 -y 20 -l 60 -x 155.9 > %s.tif"
- #cmd_scan = "scanimage --format=tif --resolution 600 --mode Gray -t %d -l %d -y %d -x %d > %s.tif"
-
- resolution = 600
-
- ## Init of sane interface -> device.
- def __init__(self, progress, window2, treeview):
- print "init sane python interface ...",
- sys.stdout.flush()
-
- # Get the path set up properly
- #sys.path.append('.')
-
- # create treeview things
- list_store = gtk.ListStore(gobject.TYPE_STRING)
- treeview.set_model(list_store)
- col = gtk.TreeViewColumn("Devices", gtk.CellRendererText(),text=0)
- treeview.append_column(col)
-
- # get blacklist
- self.read_blacklist()
-
- # init SANE
- self.n=4.
- progress(0.,"init sane python interface ...")
- try:
- self.version = sane.init()
- progress(1./self.n,"init sane python interface ... search devices")
- # get sane devices
- self.devices1 = sane.get_devices()
- # init filtered list
- self.devices = []
-
- print "\n"
- # add found devices to treeview
- for i in range(len(self.devices1)):
- # filter devices: remove blacklisted devices
- if not self.devices1[i][1]+" "+self.devices1[i][2] in self.blacklist:
- self.devices.append(self.devices1[i])
- print str(i)+": "+self.devices1[i][1]+" "+self.devices1[i][2]
- list_store.append([self.devices1[i][1]+" "+self.devices1[i][2]])
- else:
- print str(i)+": "+self.devices1[i][1]+" "+self.devices1[i][2]+" BLOCKED"
- # self.devices is now filtered
-
- # check how many devices we found
- if len(self.devices) == 0:
- progress(0./self.n,"No device found.")
- self.found_scanner = False
- elif len(list_store) > 1:
- # more than one device, choose one.
- progress(2./self.n,"More than one device found.")
- if sys.argv[1:]:
- # choose one by command line
- devnr = raw_input("Choose device: ")
- progress(2./self.n,"More than one device found. Choose device number %i" % devnr)
- # continue to init scanner
- self.init_scanner(progress, window2, treeview, devnr)
- else:
- # simply continue and select device in GUI ( look in init_sane )
- progress(2./self.n,"More than one device found.")
-
- else:
- # only one device found
- progress(2./self.n,"Device: %s" % self.devices[0][1]+" "+self.devices[0][2])
- # continue to init scanner
- self.init_scanner(progress, window2, treeview, 0)
-
- except:
- # No device found at all
- self.found_scanner = False
- print "No sane device found. Restart to try it again."
-
- ## iInit of sane interface -> scanner
- def init_scanner(self, progress, window2, treeview, devnr):
- print "Use device number: "+str(devnr)
- try:
- # finish init device
- self.dev = self.devices[devnr][0] # choose first device
- print self.dev
- progress(3./self.n,"Device initialized. Open scanner...")
-
- # open scanner device
- self.scanner = sane.open(self.dev)
- self.params = self.scanner.get_parameters()
- self.opts = self.scanner.get_options()
-
- self.found_scanner = True
-
- progress(4./self.n,"Ready: %s" % self.devices[devnr][1]+" "+self.devices[devnr][2])
- print "done."
-
- except:
- # init scanner failed. maybe device has no scanner
- self.found_scanner = False
- print "Loading sane device failed. Restart to try it again."
-
-
- ## Not init of sane and scanner, but of scan operation.
- def post_init(self, coords, out_filename):
- self.coords = coords
- self.out_filename = out_filename
- self.info()
-
- ## call
- def __call__(self):
- (self.error, self.stdout, self.stderr) = self._run()
- return self.error
-
- ## Scan and save the PIL image object to file.
- # @see http://mail.python.org/pipermail/image-sig/1997-June/000307.html
- # @see http://sane-pygtk.sourceforge.net/)
- def _run(self):
- try:
- # Set scan parameters (also with higher resolution!)
- (t, l, y, x) = self.coords
- self.scanner.tl_y = float(t)
- self.scanner.tl_x = float(l)
- self.scanner.br_y = (float(y) + self.scanner.tl_y)
- self.scanner.br_x = (float(x) + self.scanner.tl_x)
- self.scanner.resolution = self.resolution
- self.scanner.mode = "Gray"
-
- # Initiate the scan
- self.scanner.start()
-
- # Get an Image object containing the scanned image
- im = self.scanner.snap()
-
- # Write the image out as a TIFF file (or whatever)
- im.save(self.out_filename)
-
- #self.scanner.close()
- except:
- return (True, "error", sys.exc_info()[1])
-
- return (False, "ok", "")
-
- ## Show some info about the scanner and SANE.
- def info(self):
- print 'SANE version:', self.version
- print 'Available devices=', self.devices
- print 'Selected device=', self.dev #, "\n"
-
- print 'SaneDev object=', self.scanner
- print 'Device parameters:', self.params
- #print 'Device options:', "\n",self.opts
-
- ## get blacklisted devices
- def read_blacklist(self):
- bl = open('%s/blacklist' % local_path, 'r' )
- temp = bl.readlines()
- bl.close
- self.blacklist = []
- for line in temp:
- self.blacklist.append(line.strip())
-
- ## write blacklisted devices
- # @todo add UI way to blacklist device
- def write_blacklist(self, blacklist):
- bl = open('%s/blacklist' % local_path, 'w' )
- bl.write(blacklist)
- bl.close()
-
if __name__ == '__main__':
## run main application
main = MainWindowGTK()
Modified: trunk/utils/__init__.py
===================================================================
--- trunk/utils/__init__.py 2011-04-27 19:43:41 UTC (rev 50)
+++ trunk/utils/__init__.py 2011-04-27 20:26:18 UTC (rev 51)
@@ -6,7 +6,7 @@
# @version 1.1
# @brief This is the utils package with important functions.
#
-# $Id: checksum.py -1 $
+# $Id$
#
# @section Description
#
Property changes on: trunk/utils/__init__.py
___________________________________________________________________
Added: svn:keywords
+ Id
Modified: trunk/utils/checksum.py
===================================================================
--- trunk/utils/checksum.py 2011-04-27 19:43:41 UTC (rev 50)
+++ trunk/utils/checksum.py 2011-04-27 20:26:18 UTC (rev 51)
@@ -33,7 +33,7 @@
try:
self.amount = str(int(amount[2:-1])/100.)
except ValueError:
- self.amount = amount + " (error)"
+ self.amount = amount + " [ERROR!]"
def _run(self, nr):
self.uebertrag = 0
Modified: trunk/utils/ocr.py
===================================================================
--- trunk/utils/ocr.py 2011-04-27 19:43:41 UTC (rev 50)
+++ trunk/utils/ocr.py 2011-04-27 20:26:18 UTC (rev 51)
@@ -4,7 +4,7 @@
# @namespace utils::ocr
# @authors drtrigon
# @version 1.1
-# @brief Character recogition (OCR) functions.
+# @brief Character recogition (OCR) functions and classes.
#
# $Id$
#
@@ -14,8 +14,12 @@
#
# python standard modules
-import re
+import os, re, sys, subprocess, gobject
+# PIL image library and it's SANE bindings
+import sane # f12: 'python-imaging-sane'
+
+
## Character correction after recogition (on basis that there should be numbers and few special chars).
#
# @test Add unittest to check correct operation of this important module/function.
@@ -74,3 +78,284 @@
if not (data == olddata): print 'subst: "%s" => "%s"' % (item[0], item[1])
return data
+
+
+## Run external shell command/application.
+class RunExternal:
+
+ error_msg = [ "/bin/sh: " ]
+
+ ## initialize
+ def __init__(self, cmd, error_msg):
+ self.cmd = cmd
+ self.error_msg += error_msg
+
+ ## call
+ def __call__(self):
+ (self.error, self.stdout, self.stderr) = self._run()
+ return self.error
+
+ ## Execute external shell command.
+ def _run(self, piped=True):
+ if piped:
+ run = subprocess.Popen( self.cmd,
+ stdin =subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ shell=True )
+ (stdoutdata, stderrdata) = run.communicate()
+ return ((max(map(stderrdata.find, self.error_msg)) != -1), stdoutdata, stderrdata)
+ else:
+ os.system( self.cmd )
+ return (False, "", "")
+
+#class RunLibdmtx:
+# """ Use libdmtx python wrapper/bindings (pydmtx). """
+
+# def __init__(self, cmd, error_msg):
+# #self.cmd = cmd
+# #self.error_msg += error_msg
+# self.filename = cmd
+
+# def __call__(self):
+# (self.error, self.stdout, self.stderr) = self._run()
+# return self.error
+
+# # thanks to: http://www.pastequestion.com/blog/python/how-to-use-python-imaging-library.html
+# def _run(self):
+# """ Read a Data Matrix barcode. """
+# dm_read = DataMatrix()
+# #print self.filename
+# img = Image.open(self.filename)
+# try:
+# self.decode = dm_read.decode(img.size[0], img.size[1], buffer(img.tostring()))
+# self.count = dm_read.count()
+# self.message = [ dm_read.message(i+1) for i in range(self.count) ]
+# self.stats = [ dm_read.stats(i+1) for i in range(self.count) ]
+# except:
+# return (True, "error", sys.exc_info()[1])
+
+# print "Detected %i DataMatrix barcodes" % self.count
+# for i in range(self.count):
+# print "Code # %i:" % (i+1)
+# print self.message[i]
+# stats = self.stats[i]
+# print stats
+
+# # mark the recognized region and save back to file
+# points = list(stats[1])
+# points.append(points[0])
+# draw = ImageDraw.Draw(img)
+# old = points[0]
+# for i, xy in enumerate(points[1:]):
+# #draw.line(old+xy, fill=(0, 255, 0), width=2)
+# #draw.line(old+xy, fill=(0, 255, 0))
+# draw.line(old+xy, fill="rgb(0, 255, 0)")
+# old = xy
+# img.save(self.filename)
+
+# #return (False, self.message, "")
+# #print self.stats, (self.count == 0)
+# return ((self.count == 0), self.message, "")
+
+#class RunMagickWand:
+# """ Use Python bindings to ImageMagick's MagickWand API. """
+# # "convert %s.tif -crop 1600x250+800+960 -depth 8 %s.tif"
+# # "convert %s.tif -crop 1700x250+750+960 -depth 8 %s.tif"
+# # "convert %s.tif -crop 3400x500+1500+1900 -depth 8 %s.tif"
+# # "convert %s.tif -depth 8 %s.tif"
+# # "convert %s.tif -depth 8 -rotate %d %s.tif"
+# # "convert %s.tif -depth 8 -rotate %d %s"
+# #cmd_convert = "convert %s -depth 8 -rotate %d %s"
+#
+# def __init__(self, inp_filename, rotate, out_filename):
+# self.inp_filename = inp_filename
+# self.out_filename = out_filename
+# self.angle = rotate
+# self.depth = 8
+#
+# def __call__(self):
+# (self.error, self.stdout, self.stderr) = self._run()
+# return self.error
+#
+# # thanks to: http://www.assembla.com/wiki/show/pythonmagickwand
+# def _run(self):
+# """ This rotates, changes depth, format and writes a new file. """
+# try:
+# i = Image(self.inp_filename)
+# i.rotate(self.angle)
+# i.depth(self.depth)
+# i.format = self.out_filename[-3:].upper()
+# i.save(self.out_filename)
+# except:
+# return (True, "error", sys.exc_info()[1])
+#
+# return (False, "ok", "")
+
+## SANE/PIL interface python wrapper/bindings.
+class RunSANE:
+ # "scanimage --format=tif --resolution 300 --mode Gray > %s.tif"
+ # "scanimage --format=tif --resolution 600 --mode Gray -t 82 -y 20 -l 60 -x 155.9 > %s.tif"
+ #cmd_scan = "scanimage --format=tif --resolution 600 --mode Gray -t %d -l %d -y %d -x %d > %s.tif"
+
+ resolution = 600
+
+ ## Init of sane interface -> device.
+ def __init__(self, progress, window2, treeview):
+ print "init sane python interface ...",
+ sys.stdout.flush()
+
+ # Get the path set up properly
+ #sys.path.append('.')
+
+ # create treeview things
+ import gtk # (ugly patch)
+ list_store = gtk.ListStore(gobject.TYPE_STRING)
+ treeview.set_model(list_store)
+ col = gtk.TreeViewColumn("Devices", gtk.CellRendererText(),text=0)
+ treeview.append_column(col)
+
+ # get blacklist
+ self.read_blacklist()
+
+ # init SANE
+ self.n=4.
+ progress(0.,"init sane python interface ...")
+ try:
+ self.version = sane.init()
+ progress(1./self.n,"init sane python interface ... search devices")
+ # get sane devices
+ self.devices1 = sane.get_devices()
+ # init filtered list
+ self.devices = []
+
+ print "\n"
+ # add found devices to treeview
+ for i in range(len(self.devices1)):
+ # filter devices: remove blacklisted devices
+ if not self.devices1[i][1]+" "+self.devices1[i][2] in self.blacklist:
+ self.devices.append(self.devices1[i])
+ print str(i)+": "+self.devices1[i][1]+" "+self.devices1[i][2]
+ list_store.append([self.devices1[i][1]+" "+self.devices1[i][2]])
+ else:
+ print str(i)+": "+self.devices1[i][1]+" "+self.devices1[i][2]+" BLOCKED"
+ # self.devices is now filtered
+
+ # check how many devices we found
+ if len(self.devices) == 0:
+ progress(0./self.n,"No device found.")
+ self.found_scanner = False
+ elif len(list_store) > 1:
+ # more than one device, choose one.
+ progress(2./self.n,"More than one device found.")
+ if sys.argv[1:]:
+ # choose one by command line
+ devnr = raw_input("Choose device: ")
+ progress(2./self.n,"More than one device found. Choose device number %i" % devnr)
+ # continue to init scanner
+ self.init_scanner(progress, window2, treeview, devnr)
+ else:
+ # simply continue and select device in GUI ( look in init_sane )
+ progress(2./self.n,"More than one device found.")
+
+ else:
+ # only one device found
+ progress(2./self.n,"Device: %s" % self.devices[0][1]+" "+self.devices[0][2])
+ # continue to init scanner
+ self.init_scanner(progress, window2, treeview, 0)
+
+ except:
+ # No device found at all
+ self.found_scanner = False
+ print "No sane device found. Restart to try it again."
+
+ ## iInit of sane interface -> scanner
+ def init_scanner(self, progress, window2, treeview, devnr):
+ print "Use device number: "+str(devnr)
+ try:
+ # finish init device
+ self.dev = self.devices[devnr][0] # choose first device
+ print self.dev
+ progress(3./self.n,"Device initialized. Open scanner...")
+
+ # open scanner device
+ self.scanner = sane.open(self.dev)
+ self.params = self.scanner.get_parameters()
+ self.opts = self.scanner.get_options()
+
+ self.found_scanner = True
+
+ progress(4./self.n,"Ready: %s" % self.devices[devnr][1]+" "+self.devices[devnr][2])
+ print "done."
+
+ except:
+ # init scanner failed. maybe device has no scanner
+ self.found_scanner = False
+ print "Loading sane device failed. Restart to try it again."
+
+
+ ## Not init of sane and scanner, but of scan operation.
+ def post_init(self, coords, out_filename):
+ self.coords = coords
+ self.out_filename = out_filename
+ self.info()
+
+ ## call
+ def __call__(self):
+ (self.error, self.stdout, self.stderr) = self._run()
+ return self.error
+
+ ## Scan and save the PIL image object to file.
+ # @see http://mail.python.org/pipermail/image-sig/1997-June/000307.html
+ # @see http://sane-pygtk.sourceforge.net/)
+ def _run(self):
+ try:
+ # Set scan parameters (also with higher resolution!)
+ (t, l, y, x) = self.coords
+ self.scanner.tl_y = float(t)
+ self.scanner.tl_x = float(l)
+ self.scanner.br_y = (float(y) + self.scanner.tl_y)
+ self.scanner.br_x = (float(x) + self.scanner.tl_x)
+ self.scanner.resolution = self.resolution
+ self.scanner.mode = "Gray"
+
+ # Initiate the scan
+ self.scanner.start()
+
+ # Get an Image object containing the scanned image
+ im = self.scanner.snap()
+
+ # Write the image out as a TIFF file (or whatever)
+ im.save(self.out_filename)
+
+ #self.scanner.close()
+ except:
+ return (True, "error", sys.exc_info()[1])
+
+ return (False, "ok", "")
+
+ ## Show some info about the scanner and SANE.
+ def info(self):
+ print 'SANE version:', self.version
+ print 'Available devices=', self.devices
+ print 'Selected device=', self.dev #, "\n"
+
+ print 'SaneDev object=', self.scanner
+ print 'Device parameters:', self.params
+ #print 'Device options:', "\n",self.opts
+
+ ## get blacklisted devices
+ def read_blacklist(self):
+ bl = open('%s/blacklist' % local_path, 'r' )
+ temp = bl.readlines()
+ bl.close
+ self.blacklist = []
+ for line in temp:
+ self.blacklist.append(line.strip())
+
+ ## write blacklisted devices
+ # @todo add UI way to blacklist device
+ def write_blacklist(self, blacklist):
+ bl = open('%s/blacklist' % local_path, 'w' )
+ bl.write(blacklist)
+ bl.close()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|