root / pkpgcounter / trunk / pkpgpdls / analyzer.py @ 363

Revision 363, 10.3 kB (checked in by jerome, 18 years ago)

Initial support for the computation of ink coverage for PostScript?
input files.

  • Property svn:keywords set to Auth Date Id Rev
RevLine 
[200]1#
2# pkpgcounter : a generic Page Description Language parser
3#
[303]4# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
[200]5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9#
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
16# along with this program; if not, write to the Free Software
[211]17# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
[200]18#
19# $Id$
20#
21
[353]22"""This is the main module of pkpgcounter.
23
24It defines the PDLAnalyzer class, which provides a generic way to parse
25input files, by automatically detecting the best parser to use."""
26
[200]27import sys
[363]28import os
[200]29import tempfile
30
[235]31import version, pdlparser, postscript, pdf, pcl345, pclxl, \
[328]32       escp2, dvi, tiff, ooo, zjstream
[363]33import inkcoverage
[200]34
[358]35class AnalyzerOptions :
[353]36    """A class for use as the options parameter to PDLAnalyzer's constructor."""
37    def __init__(self, debug=None,
38                       colorspace=None,
39                       resolution=None) :
40        """Sets initial attributes."""
41        self.debug = debug
42        self.colorspace = colorspace
43        self.resolution = resolution
[351]44   
[353]45   
[200]46class PDLAnalyzer :   
47    """Class for PDL autodetection."""
[358]48    def __init__(self, filename, options=AnalyzerOptions()) :
[200]49        """Initializes the PDL analyzer.
50       
51           filename is the name of the file or '-' for stdin.
52           filename can also be a file-like object which
53           supports read() and seek().
54        """
[351]55        self.options = options
[200]56        self.filename = filename
[353]57        self.infile = None
58        self.mustclose = None
[200]59       
60    def getJobSize(self) :   
61        """Returns the job's size."""
62        self.openFile()
63        try :
64            pdlhandler = self.detectPDLHandler()
65        except pdlparser.PDLParserError, msg :   
66            self.closeFile()
[220]67            raise pdlparser.PDLParserError, "Unknown file format for %s (%s)" % (self.filename, msg)
[200]68        else :
69            try :
[220]70                size = pdlhandler.getJobSize()
[200]71            finally :   
72                self.closeFile()
73            return size
[363]74           
75    def getInkCoverage(self, colorspace=None, resolution=None) :
76        """Extracts the percents of ink coverage from the input file."""
77        result = None
78        cspace = colorspace or self.options.colorspace
79        res = resolution or self.options.resolution
80        if (not cspace) or (not res) :
81            raise ValueError, "Invalid colorspace (%s) or resolution (%s)" % (cspace, res)
82        self.openFile()
83        try :
84            pdlhandler = self.detectPDLHandler()
85        except pdlparser.PDLParserError, msg :   
86            self.closeFile()
87            raise pdlparser.PDLParserError, "Unknown file format for %s (%s)" % (self.filename, msg)
88        else :
89            try :
90                tiffname = self.convertToTiffMultiPage24NC(pdlhandler)
91                result = inkcoverage.getInkCoverage(tiffname, cspace)
92                try :
93                    os.remove(tiffname)
94                except OSError :
95                    sys.stderr.write("Problem when trying to remove temporary file %s\n" % tiffname)
96            finally :   
97                self.closeFile()
98        return result
[200]99       
[363]100    def convertToTiffMultiPage24NC(self, handler) :   
101        """Converts the input file to TIFF format, X dpi, 24 bits per pixel, uncompressed.
102           Returns a temporary filename which names a file containing the TIFF datas.
103           The temporary file has to be deleted by the caller.
104        """   
105        self.infile.seek(0)
106        (handle, filename) = tempfile.mkstemp(".tmp", "pkpgcounter")   
107        os.close(handle)
108        handler.convertToTiffMultiPage24NC(filename, self.options.resolution)
109        return filename
110       
[200]111    def openFile(self) :   
112        """Opens the job's data stream for reading."""
113        self.mustclose = 0  # by default we don't want to close the file when finished
114        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
115            # filename is in fact a file-like object
116            infile = self.filename
117        elif self.filename == "-" :
118            # we must read from stdin
119            infile = sys.stdin
120        else :   
121            # normal file
122            self.infile = open(self.filename, "rb")
123            self.mustclose = 1
124            return
125           
126        # Use a temporary file, always seekable contrary to standard input.
127        self.infile = tempfile.TemporaryFile(mode="w+b")
128        while 1 :
[220]129            data = infile.read(pdlparser.MEGABYTE) 
[200]130            if not data :
131                break
132            self.infile.write(data)
133        self.infile.flush()   
134        self.infile.seek(0)
135           
136    def closeFile(self) :       
137        """Closes the job's data stream if we can close it."""
138        if self.mustclose :
139            self.infile.close()   
140        else :   
141            # if we don't have to close the file, then
142            # ensure the file pointer is reset to the
143            # start of the file in case the process wants
144            # to read the file again.
145            try :
146                self.infile.seek(0)
[353]147            except IOError :   
[200]148                pass    # probably stdin, which is not seekable
149       
150    def detectPDLHandler(self) :   
151        """Tries to autodetect the document format.
152       
153           Returns the correct PDL handler class or None if format is unknown
154        """   
[220]155        # Try to detect file type by reading first and last blocks of datas   
156        # Each parser can read them automatically, but here we do this only once.
[200]157        self.infile.seek(0)
[220]158        firstblock = self.infile.read(pdlparser.FIRSTBLOCKSIZE)
[200]159        try :
[220]160            self.infile.seek(-pdlparser.LASTBLOCKSIZE, 2)
161            lastblock = self.infile.read(pdlparser.LASTBLOCKSIZE)
[200]162        except IOError :   
163            lastblock = ""
164        self.infile.seek(0)
[217]165        if not firstblock :
[220]166            raise pdlparser.PDLParserError, "input file %s is empty !" % str(self.filename)
[200]167        else :   
[220]168            for module in (postscript, \
169                           pclxl, \
170                           pdf, \
171                           pcl345, \
172                           escp2, \
173                           dvi, \
[229]174                           tiff, \
[328]175                           zjstream, \
[229]176                           ooo) :
[220]177                try :               
[351]178                    return module.Parser(self.infile, self.options.debug, firstblock, lastblock)
[220]179                except pdlparser.PDLParserError :
180                    pass # try next parser
[217]181        raise pdlparser.PDLParserError, "Analysis of first data block failed."
[200]182           
183def main() :   
184    """Entry point for PDL Analyzer."""
[350]185    import optparse
186    from copy import copy
187   
188    def check_cichoice(option, opt, value) :
189        """To add a CaseIgnore Choice option type."""
190        valower = value.lower()
191        if valower in [v.lower() for v in option.cichoices] :
192            return valower
193        else :   
[353]194            choices = ", ".join([repr(o) for o in option.cichoices])
[350]195            raise optparse.OptionValueError(
196                "option %s: invalid choice: %r (choose from %s)"
197                % (opt, value, choices))
198   
199    class MyOption(optparse.Option) :
200        """New Option class, with CaseIgnore Choice type."""
201        TYPES = optparse.Option.TYPES + ("cichoice",)
202        ATTRS = optparse.Option.ATTRS + ["cichoices"]
203        TYPE_CHECKER = copy(optparse.Option.TYPE_CHECKER)
204        TYPE_CHECKER["cichoice"] = check_cichoice
205       
206    parser = optparse.OptionParser(option_class=MyOption, 
207                                   usage="python analyzer.py [options] file1 [file2 ...]")
[348]208    parser.add_option("-v", "--version", 
209                            action="store_true", 
210                            dest="version",
[350]211                            help="Show pkpgcounter's version number and exit.")
[348]212    parser.add_option("-d", "--debug", 
213                            action="store_true", 
214                            dest="debug",
[350]215                            help="Activate debug mode.")
216    parser.add_option("-c", "--colorspace", 
217                            dest="colorspace",
218                            type="cichoice",
[363]219                            cichoices=["bw", "rgb", "cmyk", "cmy"],
220                            help="Activate the computation of ink usage, and defines the colorspace to use. Supported values are 'BW', 'RGB', 'CMYK', and 'CMY'.")
[350]221    parser.add_option("-r", "--resolution", 
222                            type="int", 
223                            default=150, 
224                            dest="resolution",
225                            help="The resolution in DPI to use when checking ink usage. Lower resolution is faster. Default is 150.")
[348]226    (options, arguments) = parser.parse_args()
227    if options.version :
[200]228        print "%s" % version.__version__
[358]229    elif not (72 <= options.resolution <= 1200) :   
230        sys.stderr.write("ERROR: the argument to the --resolution command line switch must be between 72 and 1200.\n")
231        sys.stderr.flush()
[200]232    else :
[348]233        if (not arguments) or ((not sys.stdin.isatty()) and ("-" not in arguments)) :
234            arguments.append("-")
[200]235        totalsize = 0   
[350]236        try :
237            for arg in arguments :
238                try :
[351]239                    parser = PDLAnalyzer(arg, options)
[363]240                    if not options.colorspace :
241                        totalsize += parser.getJobSize()
242                    else :
243                        result = parser.getInkCoverage()
244                        totalsize += len(result)
245                        print result
[350]246                except (IOError, pdlparser.PDLParserError), msg :   
247                    sys.stderr.write("ERROR: %s\n" % msg)
248                    sys.stderr.flush()
249        except KeyboardInterrupt :           
250            sys.stderr.write("WARN: Aborted at user's request.\n")
251            sys.stderr.flush()
[200]252        print "%s" % totalsize
253   
254if __name__ == "__main__" :   
255    main()
Note: See TracBrowser for help on using the browser.