[200] | 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 |
---|
[200] | 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 |
---|
[200] | 8 | # (at your option) any later version. |
---|
[463] | 9 | # |
---|
[200] | 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/>. |
---|
[200] | 17 | # |
---|
| 18 | # $Id$ |
---|
| 19 | # |
---|
| 20 | |
---|
[353] | 21 | """This is the main module of pkpgcounter. |
---|
| 22 | |
---|
| 23 | It defines the PDLAnalyzer class, which provides a generic way to parse |
---|
| 24 | input files, by automatically detecting the best parser to use.""" |
---|
| 25 | |
---|
[200] | 26 | import sys |
---|
[363] | 27 | import os |
---|
[200] | 28 | import tempfile |
---|
| 29 | |
---|
[539] | 30 | import version, pdlparser, postscript, pdf, pcl345, pclxl, hbp, \ |
---|
| 31 | pil, mscrap, cfax, lidil, escp2, dvi, tiff, ooo, zjstream, \ |
---|
| 32 | qpdl, spl1, escpages03, plain |
---|
[363] | 33 | import inkcoverage |
---|
[200] | 34 | |
---|
[358] | 35 | class 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] | 46 | class 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 |
---|
[491] | 57 | self.workfile = None |
---|
[353] | 58 | self.mustclose = None |
---|
[200] | 59 | |
---|
| 60 | def getJobSize(self) : |
---|
| 61 | """Returns the job's size.""" |
---|
[370] | 62 | size = 0 |
---|
[200] | 63 | self.openFile() |
---|
| 64 | try : |
---|
| 65 | try : |
---|
[411] | 66 | pdlhandler = self.detectPDLHandler() |
---|
[220] | 67 | size = pdlhandler.getJobSize() |
---|
[411] | 68 | except pdlparser.PDLParserError, msg : |
---|
[527] | 69 | raise pdlparser.PDLParserError, "Unsupported file format for %s (%s)" % (self.filename, msg) |
---|
[411] | 70 | finally : |
---|
| 71 | self.closeFile() |
---|
[370] | 72 | return size |
---|
[363] | 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 : |
---|
[411] | 84 | pdlhandler = self.detectPDLHandler() |
---|
[501] | 85 | dummyfile = tempfile.NamedTemporaryFile(mode="w+b") |
---|
| 86 | filename = dummyfile.name |
---|
[492] | 87 | try : |
---|
| 88 | pdlhandler.convertToTiffMultiPage24NC(filename, self.options.resolution) |
---|
| 89 | result = inkcoverage.getInkCoverage(filename, cspace) |
---|
| 90 | finally : |
---|
[501] | 91 | dummyfile.close() |
---|
[411] | 92 | except pdlparser.PDLParserError, msg : |
---|
[527] | 93 | raise pdlparser.PDLParserError, "Unsupported file format for %s (%s)" % (self.filename, msg) |
---|
[492] | 94 | finally : |
---|
[411] | 95 | self.closeFile() |
---|
[363] | 96 | return result |
---|
[200] | 97 | |
---|
| 98 | def openFile(self) : |
---|
| 99 | """Opens the job's data stream for reading.""" |
---|
[491] | 100 | self.mustclose = False # by default we don't want to close the file when finished |
---|
[200] | 101 | if hasattr(self.filename, "read") and hasattr(self.filename, "seek") : |
---|
| 102 | # filename is in fact a file-like object |
---|
| 103 | infile = self.filename |
---|
| 104 | elif self.filename == "-" : |
---|
| 105 | # we must read from stdin |
---|
| 106 | infile = sys.stdin |
---|
| 107 | else : |
---|
| 108 | # normal file |
---|
[491] | 109 | self.workfile = open(self.filename, "rb") |
---|
| 110 | self.mustclose = True |
---|
[200] | 111 | return |
---|
| 112 | |
---|
| 113 | # Use a temporary file, always seekable contrary to standard input. |
---|
[491] | 114 | self.workfile = tempfile.NamedTemporaryFile(mode="w+b") |
---|
| 115 | self.filename = self.workfile.name |
---|
| 116 | while True : |
---|
[220] | 117 | data = infile.read(pdlparser.MEGABYTE) |
---|
[200] | 118 | if not data : |
---|
| 119 | break |
---|
[491] | 120 | self.workfile.write(data) |
---|
| 121 | self.workfile.flush() |
---|
| 122 | self.workfile.seek(0) |
---|
[200] | 123 | |
---|
| 124 | def closeFile(self) : |
---|
[491] | 125 | """Closes the job's data stream if we have to.""" |
---|
[200] | 126 | if self.mustclose : |
---|
[491] | 127 | self.workfile.close() |
---|
[200] | 128 | |
---|
[522] | 129 | def readFirstAndLastBlocks(self, inputfile) : |
---|
[520] | 130 | """Reads the first and last blocks of data.""" |
---|
| 131 | # Now read first and last block of the input file |
---|
| 132 | # to be able to detect the real file format and the parser to use. |
---|
[522] | 133 | firstblock = inputfile.read(pdlparser.FIRSTBLOCKSIZE) |
---|
[520] | 134 | try : |
---|
[522] | 135 | inputfile.seek(-pdlparser.LASTBLOCKSIZE, 2) |
---|
| 136 | lastblock = inputfile.read(pdlparser.LASTBLOCKSIZE) |
---|
[520] | 137 | except IOError : |
---|
[522] | 138 | lastblock = "" |
---|
| 139 | return (firstblock, lastblock) |
---|
[520] | 140 | |
---|
[200] | 141 | def detectPDLHandler(self) : |
---|
| 142 | """Tries to autodetect the document format. |
---|
| 143 | |
---|
| 144 | Returns the correct PDL handler class or None if format is unknown |
---|
| 145 | """ |
---|
[491] | 146 | if not os.stat(self.filename).st_size : |
---|
[220] | 147 | raise pdlparser.PDLParserError, "input file %s is empty !" % str(self.filename) |
---|
[522] | 148 | (firstblock, lastblock) = self.readFirstAndLastBlocks(self.workfile) |
---|
[493] | 149 | |
---|
[491] | 150 | # IMPORTANT : the order is important below. FIXME. |
---|
| 151 | for module in (postscript, \ |
---|
| 152 | pclxl, \ |
---|
| 153 | pdf, \ |
---|
| 154 | qpdl, \ |
---|
| 155 | spl1, \ |
---|
| 156 | dvi, \ |
---|
| 157 | tiff, \ |
---|
[539] | 158 | cfax, \ |
---|
[491] | 159 | zjstream, \ |
---|
| 160 | ooo, \ |
---|
| 161 | hbp, \ |
---|
| 162 | lidil, \ |
---|
| 163 | pcl345, \ |
---|
| 164 | escp2, \ |
---|
| 165 | escpages03, \ |
---|
[501] | 166 | pil, \ |
---|
[523] | 167 | mscrap, \ |
---|
[491] | 168 | plain) : # IMPORTANT : don't move this one up ! |
---|
| 169 | try : |
---|
[529] | 170 | return module.Parser(self, self.filename, |
---|
| 171 | (firstblock, lastblock)) |
---|
[491] | 172 | except pdlparser.PDLParserError : |
---|
| 173 | pass # try next parser |
---|
[217] | 174 | raise pdlparser.PDLParserError, "Analysis of first data block failed." |
---|
[200] | 175 | |
---|
| 176 | def main() : |
---|
| 177 | """Entry point for PDL Analyzer.""" |
---|
[350] | 178 | import optparse |
---|
| 179 | from copy import copy |
---|
| 180 | |
---|
| 181 | def check_cichoice(option, opt, value) : |
---|
| 182 | """To add a CaseIgnore Choice option type.""" |
---|
| 183 | valower = value.lower() |
---|
| 184 | if valower in [v.lower() for v in option.cichoices] : |
---|
| 185 | return valower |
---|
| 186 | else : |
---|
[353] | 187 | choices = ", ".join([repr(o) for o in option.cichoices]) |
---|
[350] | 188 | raise optparse.OptionValueError( |
---|
| 189 | "option %s: invalid choice: %r (choose from %s)" |
---|
| 190 | % (opt, value, choices)) |
---|
| 191 | |
---|
| 192 | class MyOption(optparse.Option) : |
---|
| 193 | """New Option class, with CaseIgnore Choice type.""" |
---|
| 194 | TYPES = optparse.Option.TYPES + ("cichoice",) |
---|
| 195 | ATTRS = optparse.Option.ATTRS + ["cichoices"] |
---|
| 196 | TYPE_CHECKER = copy(optparse.Option.TYPE_CHECKER) |
---|
| 197 | TYPE_CHECKER["cichoice"] = check_cichoice |
---|
| 198 | |
---|
| 199 | parser = optparse.OptionParser(option_class=MyOption, |
---|
| 200 | usage="python analyzer.py [options] file1 [file2 ...]") |
---|
[348] | 201 | parser.add_option("-v", "--version", |
---|
| 202 | action="store_true", |
---|
| 203 | dest="version", |
---|
[350] | 204 | help="Show pkpgcounter's version number and exit.") |
---|
[348] | 205 | parser.add_option("-d", "--debug", |
---|
| 206 | action="store_true", |
---|
| 207 | dest="debug", |
---|
[350] | 208 | help="Activate debug mode.") |
---|
| 209 | parser.add_option("-c", "--colorspace", |
---|
| 210 | dest="colorspace", |
---|
| 211 | type="cichoice", |
---|
[439] | 212 | cichoices=["bw", "rgb", "cmyk", "cmy", "gc"], |
---|
| 213 | help="Activate the computation of ink usage, and defines the colorspace to use. Supported values are 'BW', 'RGB', 'CMYK', 'CMY', and 'GC'.") |
---|
[350] | 214 | parser.add_option("-r", "--resolution", |
---|
| 215 | type="int", |
---|
[367] | 216 | default=72, |
---|
[350] | 217 | dest="resolution", |
---|
[367] | 218 | help="The resolution in DPI to use when checking ink usage. Lower resolution is faster but less accurate. Default is 72 dpi.") |
---|
[348] | 219 | (options, arguments) = parser.parse_args() |
---|
| 220 | if options.version : |
---|
[200] | 221 | print "%s" % version.__version__ |
---|
[358] | 222 | elif not (72 <= options.resolution <= 1200) : |
---|
[367] | 223 | sys.stderr.write("ERROR: the argument to the --resolution command line option must be between 72 and 1200.\n") |
---|
[358] | 224 | sys.stderr.flush() |
---|
[200] | 225 | else : |
---|
[348] | 226 | if (not arguments) or ((not sys.stdin.isatty()) and ("-" not in arguments)) : |
---|
| 227 | arguments.append("-") |
---|
[200] | 228 | totalsize = 0 |
---|
[377] | 229 | lines = [] |
---|
[350] | 230 | try : |
---|
| 231 | for arg in arguments : |
---|
| 232 | try : |
---|
[351] | 233 | parser = PDLAnalyzer(arg, options) |
---|
[363] | 234 | if not options.colorspace : |
---|
| 235 | totalsize += parser.getJobSize() |
---|
| 236 | else : |
---|
[376] | 237 | (cspace, pages) = parser.getInkCoverage() |
---|
| 238 | for page in pages : |
---|
[377] | 239 | lineparts = [] |
---|
| 240 | for k in cspace : # NB : this way we preserve the order of the planes |
---|
[376] | 241 | try : |
---|
[383] | 242 | lineparts.append("%s : %s%%" % (k, ("%f" % page[k]).rjust(10))) |
---|
[376] | 243 | except KeyError : |
---|
| 244 | pass |
---|
[377] | 245 | lines.append(" ".join(lineparts)) |
---|
[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() |
---|
[377] | 252 | if not options.colorspace : |
---|
[491] | 253 | print "%i" % totalsize |
---|
[377] | 254 | else : |
---|
| 255 | print "\n".join(lines) |
---|
[200] | 256 | |
---|
| 257 | if __name__ == "__main__" : |
---|
| 258 | main() |
---|