root / pkpgcounter / trunk / pkpgpdls / pdlparser.py @ 493

Revision 493, 4.1 kB (checked in by jerome, 16 years ago)

Re-optimize disk access by not reopening and re-reading first and last block
more than once.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Auth Date Id Rev
RevLine 
[192]1#
2# pkpgcounter : a generic Page Description Language parser
3#
[443]4# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
[463]5# This program is free software: you can redistribute it and/or modify
[192]6# it under the terms of the GNU General Public License as published by
[463]7# the Free Software Foundation, either version 3 of the License, or
[192]8# (at your option) any later version.
[463]9#
[192]10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
[463]16# along with this program.  If not, see <http://www.gnu.org/licenses/>.
[192]17#
18# $Id$
19#
20
[360]21"""This module defines the base class for all Page Description Language parsers."""
22
[199]23import sys
[428]24import os
[371]25import popen2
[199]26
[220]27KILOBYTE = 1024   
28MEGABYTE = 1024 * KILOBYTE   
29FIRSTBLOCKSIZE = 16 * KILOBYTE
30LASTBLOCKSIZE = int(KILOBYTE / 4)
31
[193]32class PDLParserError(Exception):
33    """An exception for PDLParser related stuff."""
34    def __init__(self, message = ""):
35        self.message = message
36        Exception.__init__(self, message)
37    def __repr__(self):
38        return self.message
39    __str__ = __repr__
40       
[192]41class PDLParser :
42    """Generic PDL parser."""
[428]43    totiffcommands = None        # Default command to convert to TIFF
[491]44    openmode = "rb"              # Default file opening mode
[493]45    def __init__(self, filename, firstblock, lastblock, debug=0) :
[192]46        """Initialize the generic parser."""
[491]47        self.filename = filename
[192]48        self.debug = debug
[491]49        self.infile = None
[493]50        (self.firstblock, self.lastblock) = (firstblock, lastblock)
[220]51        if not self.isValid() :
52            raise PDLParserError, "Invalid file format !"
53        try :
54            import psyco 
55        except ImportError :   
56            pass # Psyco is not installed
57        else :   
58            # Psyco is installed, tell it to compile
59            # the CPU intensive methods : PCL and PCLXL
[432]60            # parsing will greatly benefit from this.
[220]61            psyco.bind(self.getJobSize)
[493]62        self.infile = open(self.filename, self.openmode)
63        # self.logdebug("Opened %s in '%s' mode." % (self.filename, self.openmode))
[220]64           
[491]65    def __del__(self) :
66        """Ensures the input file gets closed."""
67        if self.infile :
68            self.infile.close()
69           
[252]70    def logdebug(self, message) :       
71        """Logs a debug message if needed."""
72        if self.debug :
73            sys.stderr.write("%s\n" % message)
74           
[220]75    def isValid(self) :   
[387]76        """Returns True if data is in the expected format, else False."""
[192]77        raise RuntimeError, "Not implemented !"
[220]78       
79    def getJobSize(self) :   
80        """Counts pages in a document."""
81        raise RuntimeError, "Not implemented !"
[362]82       
[492]83    def convertToTiffMultiPage24NC(self, outfname, dpi) :
[362]84        """Converts the input file to TIFF format, X dpi, 24 bits per pixel, uncompressed.
[492]85           Writes TIFF datas to the file named by outfname.
[362]86        """   
[428]87        if self.totiffcommands :
[492]88            infname = self.filename
89            for totiffcommand in self.totiffcommands :
90                error = False
91                commandline = totiffcommand % locals()
92                # self.logdebug("Executing '%s'" % commandline)
93                status = os.system(commandline)
94                if os.WIFEXITED(status) :
95                    if os.WEXITSTATUS(status) :
[428]96                        error = True
[492]97                else :       
98                    error = True
99                if not os.path.exists(outfname) :
100                    error = True
101                elif not os.stat(outfname).st_size :
102                    error = True
103                else :       
104                    break       # Conversion worked fine it seems.
105                sys.stderr.write("Command failed : %s\n" % repr(commandline))
[428]106            if error :
107                raise PDLParserError, "Problem during conversion to TIFF."
[371]108        else :       
109            raise PDLParserError, "Impossible to compute ink coverage for this file format."
Note: See TracBrowser for help on using the browser.