[Pycodeocr-main] SF.net SVN: pycodeocr:[44]
Status: Beta
Brought to you by:
drtrigon
From: <drt...@us...> - 2011-04-27 12:25:27
|
Revision: 44 http://pycodeocr.svn.sourceforge.net/pycodeocr/?rev=44&view=rev Author: drtrigon Date: 2011-04-27 12:25:14 +0000 (Wed, 27 Apr 2011) Log Message: ----------- Thanks to the guys from VisTrails at the University of Utah we have code now for automatic dependency check and installation of needed repos. This works for fedora and ubuntu at the moment. Modified Paths: -------------- PyCodeOCR.py Added Paths: ----------- installbundle.py requirements.py Property Changed: ---------------- PyCodeOCR.py checksum.py Modified: PyCodeOCR.py =================================================================== --- PyCodeOCR.py 2011-04-26 21:19:41 UTC (rev 43) +++ PyCodeOCR.py 2011-04-27 12:25:14 UTC (rev 44) @@ -10,6 +10,14 @@ import os, re, sys, subprocess, time, gobject, string, struct +# check and install requirements +#print "To check and install requirements run: 'python %s --install-deps'" % sys.argv[0] +import requirements +if "--install-deps" in sys.argv: + requirements.check_all_pycodeocr_requirements() + sys.exit() + + # GTK, PyGTK, GLADE (GNOME) modules import pygtk pygtk.require('2.0') @@ -33,19 +41,26 @@ os.system('python %s' % sys.argv[0]) # sys.exit() # ## list of available pakages +print "To check and install requirements run: 'python %s --install-deps'" % sys.argv[0] pakages = [] # gocr -if os.path.exists("gocr"): +paths = { "gocr": requirements.which("gocr"), + "dmtxread": requirements.which("dmtxread"), + "pdf417decode.exe": requirements.which("pdf417decode.exe"), } +if os.path.exists(paths["gocr"]): pakages.append( "gocr" ) print "gocr found." # libdmtx bindings -try: - #from pydmtx import DataMatrix +#try: +# from pydmtx import DataMatrix +# pakages.append( "libdmtx" ) +# print "libdmtx and pydmtx found." +#except: pass +if os.path.exists(paths["dmtxread"]): pakages.append( "libdmtx" ) print "libdmtx and pydmtx found." -except: pass # pdf417decode -if os.path.exists("pdf417decode.exe"): +if os.path.exists(paths["pdf417decode.exe"]): pakages.append( "pdf417decode" ) print "pdf417decode.exe found." @@ -76,7 +91,7 @@ # initialization # (variables) max_retry = 3 # max. scan attempts - valid_code_len = [ 53, 42, 32 ] # valid code lenghts + valid_code_len = [ 53, 42, 32 ] # valid code lenghts scan_koords = std_scan_koords["0 deg"][0] # default scan pos. mode = std_scan_koords["0 deg"][1] # default scan orient. res_color = { True: gtk.gdk.color_parse("#00FF00"), @@ -87,11 +102,11 @@ os.path.join(home_path, "PyCodeOCR_debug.txt"), ) regex_gocr = re.compile('<barcode(.*?)/>') - #cmd_scan = "scanimage --format=tif --resolution 600 --mode Gray -t %d -l %d -y %d -x %d > %s" # SANE scan command - cmd_convert = "convert %s -depth 8 -rotate %d %s" # ImageMagick command - cmd_tesser = "tesseract %s.tif %s" # TesserAct command - cmd_gocr = os.path.join(local_path, "gocr") + " -i %s.pnm" # GOCR command (local) - cmd_pdf417dec = "wine " + os.path.join(local_path, "pdf417decode.exe") + " %s.png" # pdf417decode/wine command (local) + #cmd_scan = "scanimage --format=tif --resolution 600 --mode Gray -t %d -l %d -y %d -x %d > %s" # SANE scan command + cmd_convert = "convert %s -depth 8 -rotate %d %s" # ImageMagick command + cmd_tesser = "tesseract %s.tif %s" # TesserAct command + cmd_gocr = paths["gocr"] + " -i %s.pnm" # GOCR command (local) + cmd_pdf417dec = "wine " + paths["pdf417decode.exe"] + " %s.png" # pdf417decode/wine command (local) __stop = False @@ -440,13 +455,13 @@ self.mode = std_scan_koords["A4"][1] #pydmtx recognition # opt = { 'tmp_file': "02.jpg", # some issues with recogition -# 'recog_class': RunLibdmtx, # . -# 'recog_cmd': self.temp+"02.jpg", # of different file formats +# 'recog_class': 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_cmd': "dmtxread "+self.temp+"02.jpg", # of different file formats + opt = { 'tmp_file': "02.jpg", # some issues with recogition + 'recog_class': RunExternal, # . + 'recog_cmd': "%s %s02.jpg"%(paths["dmtxread"],self.temp), # of different file formats 'recog_error_msg': [ "error" ], # . #opt = { 'tmp_file': "02.bmp", # and drawing/marking the Property changes on: PyCodeOCR.py ___________________________________________________________________ Added: svn:keywords + Id Property changes on: checksum.py ___________________________________________________________________ Added: svn:keywords + Id Added: installbundle.py =================================================================== --- installbundle.py (rev 0) +++ installbundle.py 2011-04-27 12:25:14 UTC (rev 44) @@ -0,0 +1,158 @@ +############################################################################ +## +## Copyright (C) 2006-2010 University of Utah. All rights reserved. +## +## This file is part of VisTrails. +## +## This file may be used under the terms of the GNU General Public +## License version 2.0 as published by the Free Software Foundation +## and appearing in the file LICENSE.GPL included in the packaging of +## this file. Please review the following to ensure GNU General Public +## Licensing requirements will be met: +## http://www.opensource.org/licenses/gpl-license.php +## +## If you are unsure which license is appropriate for your use (for +## instance, you are interested in developing a commercial derivative +## of VisTrails), please contact us at vis...@sc.... +## +## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +## +## Changed 2011 by drtrigon. Source from 'core.bundles.installbundle' +## http://downloads.sourceforge.net/project/vistrails/vistrails/nightly/vistrails-src-nightly.tar.gz +## +## This file was modified to be used as part of PyCodeOCR. +## +############################################################################ + +"""Module with utilities to try and install a bundle if possible.""" + +import os + +############################################################################## + +def linux_ubuntu_install(package_name): + qt = has_qt() + hide_splash_if_necessary() + + if qt: + cmd = core.system.vistrails_root_directory() + cmd += '/core/bundles/linux_ubuntu_install.py' + else: + cmd = 'apt-get install -y' + + if type(package_name) == str: + cmd += ' ' + package_name + elif type(package_name) == list: + for package in package_name: + if type(package) != str: + raise TypeError("Expected string or list of strings") + cmd += ' ' + package + + if qt: + sucmd = guess_graphical_sudo() + " '" + cmd + "'" + else: + debug.warning("PyCodeOCR wants to install package(s) '%s'" % + package_name) + sucmd = "sudo " + cmd + + result = os.system(sucmd) + + return (result == 0) # 0 indicates success + +def linux_fedora_install(package_name): + qt = has_qt() + hide_splash_if_necessary() + if qt: + cmd = core.system.vistrails_root_directory() + cmd += '/core/bundles/linux_fedora_install.py' + else: + cmd = 'yum -y install' + + if type(package_name) == str: + cmd += ' ' + package_name + elif type(package_name) == list: + for package in package_name: + if type(package) != str: + raise TypeError("Expected string or list of strings") + cmd += ' ' + package + + if qt: + sucmd = guess_graphical_sudo() + " " + cmd + else: + debug.warning(("PyCodeOCR wants to install package(s) '%s' through " + "_sudo_. Make sure you are a sudoer.") % package_name) + sucmd = "sudo " + cmd + + debug.warning("EXECUTING: sucmd") + result = os.system(sucmd) + debug.warning("RETURN VALUE: %s" % result) + return (result == 0) + +def show_question(which_files): + qt = has_qt() + if qt: + import gui.utils + if type(which_files) == str: + which_files = [which_files] + v = gui.utils.show_question("Required packages missing", + "One or more required packages are missing: " + + " ".join(which_files) + + ". PyCodeOCR can " + + "automaticallly install them. " + + "If you click OK, PyCodeOCR will need "+ + "administrator privileges, and you " + + "might be asked for the administrator password.", + buttons=[gui.utils.OK_BUTTON, + gui.utils.CANCEL_BUTTON], + default=gui.utils.OK_BUTTON) + return v == gui.utils.OK_BUTTON + else: + print "Required package missing" + print ("A required package is missing, but PyCodeOCR can " + + "automatically install it. " + + "If you say Yes, PyCodeOCR will need "+ + "administrator privileges, and you" + + "might be asked for the administrator password.") + print "Give PyCodeOCR permission to try to install package? (y/N)" + v = raw_input().upper() + return v == 'Y' or v == 'YES' + + +def install(dependency_dictionary): + """Tries to import a python module. If unsuccessful, tries to install +the appropriate bundle and then reimport. py_import tries to be smart +about which system it runs on.""" + + # Ugly fix to avoid circular import + distro = guess_system() + if not dependency_dictionary.has_key(distro): + return False + else: + files = dependency_dictionary[distro] + if show_question(files): + callable_ = getattr(installbundle, + distro.replace('-', '_') + '_install') + return callable_(files) + else: + return False + +############################################################################## + +def guess_system(): + import platform + #print os.name, platform.platform() + return ("%s-%s" % (platform.system(), platform.dist()[0])).lower() + +def has_qt(): + return False + +import installbundle + +def hide_splash_if_necessary(): + pass + +class dbg(): + def warning(self, *args): + print "".join(args) +debug = dbg() Property changes on: installbundle.py ___________________________________________________________________ Added: svn:keywords + Id Added: svn:eol-style + native Added: requirements.py =================================================================== --- requirements.py (rev 0) +++ requirements.py 2011-04-27 12:25:14 UTC (rev 44) @@ -0,0 +1,186 @@ +############################################################################ +## +## Copyright (C) 2006-2010 University of Utah. All rights reserved. +## +## This file is part of VisTrails. +## +## This file may be used under the terms of the GNU General Public +## License version 2.0 as published by the Free Software Foundation +## and appearing in the file LICENSE.GPL included in the packaging of +## this file. Please review the following to ensure GNU General Public +## Licensing requirements will be met: +## http://www.opensource.org/licenses/gpl-license.php +## +## If you are unsure which license is appropriate for your use (for +## instance, you are interested in developing a commercial derivative +## of VisTrails), please contact us at vis...@sc.... +## +## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +## +## Changed 2011 by drtrigon. Source from 'core.requirements' +## http://downloads.sourceforge.net/project/vistrails/vistrails/nightly/vistrails-src-nightly.tar.gz +## +## This file was modified to be used as part of PyCodeOCR. +## +############################################################################ + +"""module that allows online inspection of environment to test presence of +runtime components such as binaries, libraries, other python modules, etc.""" + +import sys + +############################################################################## + +def python_module_exists(module_name): + """python_module_exists(module_name): Boolean. +Returns if python module of given name can be safely imported.""" + + try: + sys.modules[module_name] + return True + except KeyError: + pass + try: + __import__(module_name) + return True + except ImportError: + return False + + +def executable_file_exists(filename): + """executable_file_exists(filename): Boolean. +Returns if certain file is in current path and is executable.""" + result = executable_is_in_path(filename) + if result == "": + result = executable_is_in_pythonpath(filename) + return result != "" + +# FIXME: Add documentation. + +def require_python_module(module_name): + if not python_module_exists(module_name): + raise MissingRequirement(module_name) + +def require_executable(filename): + if not executable_file_exists(filename): + raise MissingRequirement(filename) + +def check_pyqt4(): + # checks for the presence of pyqt4, which is more important than the rest, + # since using pyqt requires a qapplication. + try: + require_python_module('PyQt4.QtGui') + require_python_module('PyQt4.QtOpenGL') + except MissingRequirement: + r = core.bundles.installbundle.install({'linux-ubuntu': ['python-qt4', + 'python-qt4-gl', + 'python-qt4-sql']}) + if not r: + raise + + +def check_all_vistrails_requirements(): + pass + + # check scipy +# try: +# require_python_module('scipy') +# except MissingRequirement: +# r = core.bundles.installbundle.install({'linux-ubuntu': 'python-scipy'}) +# if not r: +# raise + + +############################################################################## + +class MissingRequirement(Exception): + """Raise this exception in packages when necessary items are missing.""" + def __init__(self, req): + self.requirement = req + def __str__(self): + return "Missing Requirement: %s" % self.requirement + +############################################################################## + +import installbundle +import os + + +# http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python +def which(program, search_path=None): + is_exe = lambda fpath: os.path.exists(fpath) and os.access(fpath, os.X_OK) + #is_exe = lambda fpath: os.path.exists(fpath) + + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + return program + else: + if not search_path: + search_path = os.environ["PATH"].split(os.pathsep) + search_path += [ '.' ] # add local path + for path in search_path: + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + return "" + +def executable_is_in_path(filename): + #print os.system(filename) + return which(filename) + +def executable_is_in_pythonpath(filename): + return which(filename, search_path=os.environ.get("PYTHONPATH", None)) + + +def check_pygtk(): + # checks for the presence of pygtk, which is more important than the rest. + try: + require_python_module('pygtk') + #pygtk.require('2.0') + require_python_module('gtk') + require_python_module('gtk.glade') + require_python_module('gobject') + except MissingRequirement: + r = core.bundles.installbundle.install({'linux-fedora': ['pygtk2']}) + # other deps? + if not r: + raise + +def check_sane(): + try: + require_python_module('sane') + except MissingRequirement: + r = core.bundles.installbundle.install({'linux-fedora': ['python-imaging-sane']}) + # other deps? + if not r: + raise + +def check_optionals(): + try: + require_executable("gocr") + except MissingRequirement: + r = installbundle.install({'linux-fedora': ['gocr'], + 'linux-ubuntu': ['gocr']}) + + try: + #require_python_module('pydmtx') + require_executable("dmtxread") + except MissingRequirement: + r = installbundle.install({'linux-fedora': ['libdmtx-utils'], + 'linux-ubuntu': ['libdmtx-utils']}) + + +def check_all_pycodeocr_requirements(): + print "Checking all PyCodeOCR requirements:" + + # needed + print " * NEEDED 'pygtk2'" + check_pygtk() + print " * NEEDED 'sane' (scanner)" + check_sane() + + # optional + print " * OPTIONAL 'gocr', 'dmtxread'" + check_optionals() Property changes on: requirements.py ___________________________________________________________________ Added: svn:keywords + Id Added: svn:eol-style + native This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |