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

Revision 427, 11.1 kB (checked in by jerome, 18 years ago)

Ensures the temporary file is removed in all cases.

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