[3410] | 1 | # -*- coding: utf-8 -*- |
---|
[200] | 2 | # |
---|
| 3 | # pkpgcounter : a generic Page Description Language parser |
---|
| 4 | # |
---|
[564] | 5 | # (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com> |
---|
[463] | 6 | # This program is free software: you can redistribute it and/or modify |
---|
[200] | 7 | # it under the terms of the GNU General Public License as published by |
---|
[463] | 8 | # the Free Software Foundation, either version 3 of the License, or |
---|
[200] | 9 | # (at your option) any later version. |
---|
[3436] | 10 | # |
---|
[200] | 11 | # This program is distributed in the hope that it will be useful, |
---|
| 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
| 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
| 14 | # GNU General Public License for more details. |
---|
[3436] | 15 | # |
---|
[200] | 16 | # You should have received a copy of the GNU General Public License |
---|
[463] | 17 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
---|
[200] | 18 | # |
---|
| 19 | # $Id$ |
---|
| 20 | # |
---|
| 21 | |
---|
[353] | 22 | """This is the main module of pkpgcounter. |
---|
| 23 | |
---|
| 24 | It defines the PDLAnalyzer class, which provides a generic way to parse |
---|
| 25 | input files, by automatically detecting the best parser to use.""" |
---|
| 26 | |
---|
[200] | 27 | import sys |
---|
[363] | 28 | import os |
---|
[200] | 29 | import tempfile |
---|
| 30 | |
---|
[539] | 31 | import version, pdlparser, postscript, pdf, pcl345, pclxl, hbp, \ |
---|
| 32 | pil, mscrap, cfax, lidil, escp2, dvi, tiff, ooo, zjstream, \ |
---|
[547] | 33 | pnmascii, bj, qpdl, spl1, escpages03, plain |
---|
[363] | 34 | import inkcoverage |
---|
[200] | 35 | |
---|
[358] | 36 | class AnalyzerOptions : |
---|
[353] | 37 | """A class for use as the options parameter to PDLAnalyzer's constructor.""" |
---|
| 38 | def __init__(self, debug=None, |
---|
| 39 | colorspace=None, |
---|
| 40 | resolution=None) : |
---|
| 41 | """Sets initial attributes.""" |
---|
| 42 | self.debug = debug |
---|
| 43 | self.colorspace = colorspace |
---|
| 44 | self.resolution = resolution |
---|
[3436] | 45 | |
---|
| 46 | |
---|
| 47 | class PDLAnalyzer : |
---|
[200] | 48 | """Class for PDL autodetection.""" |
---|
[358] | 49 | def __init__(self, filename, options=AnalyzerOptions()) : |
---|
[200] | 50 | """Initializes the PDL analyzer. |
---|
[3436] | 51 | |
---|
[200] | 52 | filename is the name of the file or '-' for stdin. |
---|
[3436] | 53 | filename can also be a file-like object which |
---|
[200] | 54 | supports read() and seek(). |
---|
| 55 | """ |
---|
[351] | 56 | self.options = options |
---|
[200] | 57 | self.filename = filename |
---|
[3436] | 58 | self.workfile = None |
---|
| 59 | |
---|
| 60 | def getJobSize(self) : |
---|
[200] | 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() |
---|
[3436] | 68 | except pdlparser.PDLParserError, msg : |
---|
[527] | 69 | raise pdlparser.PDLParserError, "Unsupported file format for %s (%s)" % (self.filename, msg) |
---|
[3436] | 70 | finally : |
---|
[411] | 71 | self.closeFile() |
---|
[370] | 72 | return size |
---|
[3436] | 73 | |
---|
[363] | 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() |
---|
[3457] | 85 | dummyfile = tempfile.NamedTemporaryFile(mode="w+b", |
---|
| 86 | prefix="pkpgcounter_", |
---|
| 87 | suffix=".tiff", |
---|
| 88 | dir=os.environ.get("PYKOTADIRECTORY") or tempfile.gettempdir()) |
---|
[501] | 89 | filename = dummyfile.name |
---|
[492] | 90 | try : |
---|
| 91 | pdlhandler.convertToTiffMultiPage24NC(filename, self.options.resolution) |
---|
| 92 | result = inkcoverage.getInkCoverage(filename, cspace) |
---|
[3436] | 93 | finally : |
---|
[501] | 94 | dummyfile.close() |
---|
[3436] | 95 | except pdlparser.PDLParserError, msg : |
---|
[527] | 96 | raise pdlparser.PDLParserError, "Unsupported file format for %s (%s)" % (self.filename, msg) |
---|
[492] | 97 | finally : |
---|
[411] | 98 | self.closeFile() |
---|
[363] | 99 | return result |
---|
[3436] | 100 | |
---|
| 101 | def openFile(self) : |
---|
[200] | 102 | """Opens the job's data stream for reading.""" |
---|
| 103 | if hasattr(self.filename, "read") and hasattr(self.filename, "seek") : |
---|
[3436] | 104 | # filename is in fact a file-like object |
---|
[200] | 105 | infile = self.filename |
---|
| 106 | elif self.filename == "-" : |
---|
| 107 | # we must read from stdin |
---|
| 108 | infile = sys.stdin |
---|
[3436] | 109 | else : |
---|
[200] | 110 | # normal file |
---|
[491] | 111 | self.workfile = open(self.filename, "rb") |
---|
[200] | 112 | return |
---|
[3436] | 113 | |
---|
[200] | 114 | # Use a temporary file, always seekable contrary to standard input. |
---|
[3457] | 115 | self.workfile = tempfile.NamedTemporaryFile(mode="w+b", |
---|
| 116 | prefix="pkpgcounter_", |
---|
| 117 | suffix=".prn", |
---|
| 118 | dir=os.environ.get("PYKOTADIRECTORY") or tempfile.gettempdir()) |
---|
[491] | 119 | self.filename = self.workfile.name |
---|
| 120 | while True : |
---|
[3436] | 121 | data = infile.read(pdlparser.MEGABYTE) |
---|
[200] | 122 | if not data : |
---|
| 123 | break |
---|
[491] | 124 | self.workfile.write(data) |
---|
[3436] | 125 | self.workfile.flush() |
---|
[491] | 126 | self.workfile.seek(0) |
---|
[3436] | 127 | |
---|
| 128 | def closeFile(self) : |
---|
[491] | 129 | """Closes the job's data stream if we have to.""" |
---|
[3460] | 130 | self.workfile.close() |
---|
[3436] | 131 | |
---|
[522] | 132 | def readFirstAndLastBlocks(self, inputfile) : |
---|
[520] | 133 | """Reads the first and last blocks of data.""" |
---|
| 134 | # Now read first and last block of the input file |
---|
| 135 | # to be able to detect the real file format and the parser to use. |
---|
[522] | 136 | firstblock = inputfile.read(pdlparser.FIRSTBLOCKSIZE) |
---|
[520] | 137 | try : |
---|
[522] | 138 | inputfile.seek(-pdlparser.LASTBLOCKSIZE, 2) |
---|
| 139 | lastblock = inputfile.read(pdlparser.LASTBLOCKSIZE) |
---|
[3436] | 140 | except IOError : |
---|
[522] | 141 | lastblock = "" |
---|
[3436] | 142 | return (firstblock, lastblock) |
---|
| 143 | |
---|
| 144 | def detectPDLHandler(self) : |
---|
[200] | 145 | """Tries to autodetect the document format. |
---|
[3436] | 146 | |
---|
[200] | 147 | Returns the correct PDL handler class or None if format is unknown |
---|
[3436] | 148 | """ |
---|
[491] | 149 | if not os.stat(self.filename).st_size : |
---|
[220] | 150 | raise pdlparser.PDLParserError, "input file %s is empty !" % str(self.filename) |
---|
[522] | 151 | (firstblock, lastblock) = self.readFirstAndLastBlocks(self.workfile) |
---|
[3436] | 152 | |
---|
[491] | 153 | # IMPORTANT : the order is important below. FIXME. |
---|
| 154 | for module in (postscript, \ |
---|
| 155 | pclxl, \ |
---|
| 156 | pdf, \ |
---|
| 157 | qpdl, \ |
---|
| 158 | spl1, \ |
---|
| 159 | dvi, \ |
---|
| 160 | tiff, \ |
---|
[539] | 161 | cfax, \ |
---|
[491] | 162 | zjstream, \ |
---|
| 163 | ooo, \ |
---|
| 164 | hbp, \ |
---|
| 165 | lidil, \ |
---|
| 166 | pcl345, \ |
---|
| 167 | escp2, \ |
---|
| 168 | escpages03, \ |
---|
[545] | 169 | bj, \ |
---|
[547] | 170 | pnmascii, \ |
---|
[501] | 171 | pil, \ |
---|
[523] | 172 | mscrap, \ |
---|
[491] | 173 | plain) : # IMPORTANT : don't move this one up ! |
---|
[3436] | 174 | try : |
---|
| 175 | return module.Parser(self, self.filename, |
---|
[529] | 176 | (firstblock, lastblock)) |
---|
[491] | 177 | except pdlparser.PDLParserError : |
---|
| 178 | pass # try next parser |
---|
[217] | 179 | raise pdlparser.PDLParserError, "Analysis of first data block failed." |
---|
[3436] | 180 | |
---|
| 181 | def main() : |
---|
[200] | 182 | """Entry point for PDL Analyzer.""" |
---|
[350] | 183 | import optparse |
---|
| 184 | from copy import copy |
---|
[3436] | 185 | |
---|
[350] | 186 | def check_cichoice(option, opt, value) : |
---|
| 187 | """To add a CaseIgnore Choice option type.""" |
---|
| 188 | valower = value.lower() |
---|
| 189 | if valower in [v.lower() for v in option.cichoices] : |
---|
| 190 | return valower |
---|
[3436] | 191 | else : |
---|
[353] | 192 | choices = ", ".join([repr(o) for o in option.cichoices]) |
---|
[350] | 193 | raise optparse.OptionValueError( |
---|
| 194 | "option %s: invalid choice: %r (choose from %s)" |
---|
| 195 | % (opt, value, choices)) |
---|
[3436] | 196 | |
---|
[350] | 197 | class MyOption(optparse.Option) : |
---|
| 198 | """New Option class, with CaseIgnore Choice type.""" |
---|
| 199 | TYPES = optparse.Option.TYPES + ("cichoice",) |
---|
| 200 | ATTRS = optparse.Option.ATTRS + ["cichoices"] |
---|
| 201 | TYPE_CHECKER = copy(optparse.Option.TYPE_CHECKER) |
---|
| 202 | TYPE_CHECKER["cichoice"] = check_cichoice |
---|
[3436] | 203 | |
---|
| 204 | parser = optparse.OptionParser(option_class=MyOption, |
---|
[350] | 205 | usage="python analyzer.py [options] file1 [file2 ...]") |
---|
[3436] | 206 | parser.add_option("-v", "--version", |
---|
| 207 | action="store_true", |
---|
[348] | 208 | dest="version", |
---|
[350] | 209 | help="Show pkpgcounter's version number and exit.") |
---|
[3436] | 210 | parser.add_option("-d", "--debug", |
---|
| 211 | action="store_true", |
---|
[348] | 212 | dest="debug", |
---|
[350] | 213 | help="Activate debug mode.") |
---|
[3436] | 214 | parser.add_option("-c", "--colorspace", |
---|
[350] | 215 | dest="colorspace", |
---|
| 216 | type="cichoice", |
---|
[439] | 217 | cichoices=["bw", "rgb", "cmyk", "cmy", "gc"], |
---|
| 218 | help="Activate the computation of ink usage, and defines the colorspace to use. Supported values are 'BW', 'RGB', 'CMYK', 'CMY', and 'GC'.") |
---|
[3436] | 219 | parser.add_option("-r", "--resolution", |
---|
| 220 | type="int", |
---|
| 221 | default=72, |
---|
[350] | 222 | dest="resolution", |
---|
[367] | 223 | help="The resolution in DPI to use when checking ink usage. Lower resolution is faster but less accurate. Default is 72 dpi.") |
---|
[348] | 224 | (options, arguments) = parser.parse_args() |
---|
| 225 | if options.version : |
---|
[3456] | 226 | sys.stdout.write("%s\n" % version.__version__) |
---|
[3436] | 227 | elif not (72 <= options.resolution <= 1200) : |
---|
[367] | 228 | sys.stderr.write("ERROR: the argument to the --resolution command line option must be between 72 and 1200.\n") |
---|
[358] | 229 | sys.stderr.flush() |
---|
[200] | 230 | else : |
---|
[348] | 231 | if (not arguments) or ((not sys.stdin.isatty()) and ("-" not in arguments)) : |
---|
| 232 | arguments.append("-") |
---|
[3436] | 233 | totalsize = 0 |
---|
[377] | 234 | lines = [] |
---|
[350] | 235 | try : |
---|
| 236 | for arg in arguments : |
---|
| 237 | try : |
---|
[351] | 238 | parser = PDLAnalyzer(arg, options) |
---|
[363] | 239 | if not options.colorspace : |
---|
| 240 | totalsize += parser.getJobSize() |
---|
| 241 | else : |
---|
[376] | 242 | (cspace, pages) = parser.getInkCoverage() |
---|
| 243 | for page in pages : |
---|
[377] | 244 | lineparts = [] |
---|
| 245 | for k in cspace : # NB : this way we preserve the order of the planes |
---|
[376] | 246 | try : |
---|
[383] | 247 | lineparts.append("%s : %s%%" % (k, ("%f" % page[k]).rjust(10))) |
---|
[376] | 248 | except KeyError : |
---|
| 249 | pass |
---|
[3436] | 250 | lines.append(" ".join(lineparts)) |
---|
| 251 | except (IOError, pdlparser.PDLParserError), msg : |
---|
[350] | 252 | sys.stderr.write("ERROR: %s\n" % msg) |
---|
| 253 | sys.stderr.flush() |
---|
[3436] | 254 | except KeyboardInterrupt : |
---|
[350] | 255 | sys.stderr.write("WARN: Aborted at user's request.\n") |
---|
| 256 | sys.stderr.flush() |
---|
[3436] | 257 | if not options.colorspace : |
---|
[3456] | 258 | sys.stdout.write("%i\n" % totalsize) |
---|
[3436] | 259 | else : |
---|
[3456] | 260 | sys.stdout.write("%s\n" % ("\n".join(lines))) |
---|
[3436] | 261 | |
---|
| 262 | if __name__ == "__main__" : |
---|
[200] | 263 | main() |
---|