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

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