Changeset 3436 for pkpgcounter/trunk/pkpgpdls/analyzer.py
- Timestamp:
- 10/06/08 00:22:07 (16 years ago)
- Files:
-
- 1 modified
Legend:
- Unmodified
- Added
- Removed
-
pkpgcounter/trunk/pkpgpdls/analyzer.py
r3410 r3436 8 8 # the Free Software Foundation, either version 3 of the License, or 9 9 # (at your option) any later version. 10 # 10 # 11 11 # This program is distributed in the hope that it will be useful, 12 12 # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 14 # GNU General Public License for more details. 15 # 15 # 16 16 # You should have received a copy of the GNU General Public License 17 17 # along with this program. If not, see <http://www.gnu.org/licenses/>. … … 43 43 self.colorspace = colorspace 44 44 self.resolution = resolution 45 46 47 class PDLAnalyzer : 45 46 47 class PDLAnalyzer : 48 48 """Class for PDL autodetection.""" 49 49 def __init__(self, filename, options=AnalyzerOptions()) : 50 50 """Initializes the PDL analyzer. 51 51 52 52 filename is the name of the file or '-' for stdin. 53 filename can also be a file-like object which 53 filename can also be a file-like object which 54 54 supports read() and seek(). 55 55 """ 56 56 self.options = options 57 57 self.filename = filename 58 self.workfile = None 58 self.workfile = None 59 59 self.mustclose = None 60 61 def getJobSize(self) : 60 61 def getJobSize(self) : 62 62 """Returns the job's size.""" 63 63 size = 0 … … 67 67 pdlhandler = self.detectPDLHandler() 68 68 size = pdlhandler.getJobSize() 69 except pdlparser.PDLParserError, msg : 69 except pdlparser.PDLParserError, msg : 70 70 raise pdlparser.PDLParserError, "Unsupported file format for %s (%s)" % (self.filename, msg) 71 finally : 71 finally : 72 72 self.closeFile() 73 73 return size 74 74 75 75 def getInkCoverage(self, colorspace=None, resolution=None) : 76 76 """Extracts the percents of ink coverage from the input file.""" … … 89 89 pdlhandler.convertToTiffMultiPage24NC(filename, self.options.resolution) 90 90 result = inkcoverage.getInkCoverage(filename, cspace) 91 finally : 91 finally : 92 92 dummyfile.close() 93 except pdlparser.PDLParserError, msg : 93 except pdlparser.PDLParserError, msg : 94 94 raise pdlparser.PDLParserError, "Unsupported file format for %s (%s)" % (self.filename, msg) 95 95 finally : 96 96 self.closeFile() 97 97 return result 98 99 def openFile(self) : 98 99 def openFile(self) : 100 100 """Opens the job's data stream for reading.""" 101 101 self.mustclose = False # by default we don't want to close the file when finished 102 102 if hasattr(self.filename, "read") and hasattr(self.filename, "seek") : 103 # filename is in fact a file-like object 103 # filename is in fact a file-like object 104 104 infile = self.filename 105 105 elif self.filename == "-" : 106 106 # we must read from stdin 107 107 infile = sys.stdin 108 else : 108 else : 109 109 # normal file 110 110 self.workfile = open(self.filename, "rb") 111 111 self.mustclose = True 112 112 return 113 113 114 114 # Use a temporary file, always seekable contrary to standard input. 115 115 self.workfile = tempfile.NamedTemporaryFile(mode="w+b") 116 116 self.filename = self.workfile.name 117 117 while True : 118 data = infile.read(pdlparser.MEGABYTE) 118 data = infile.read(pdlparser.MEGABYTE) 119 119 if not data : 120 120 break 121 121 self.workfile.write(data) 122 self.workfile.flush() 122 self.workfile.flush() 123 123 self.workfile.seek(0) 124 125 def closeFile(self) : 124 125 def closeFile(self) : 126 126 """Closes the job's data stream if we have to.""" 127 127 if self.mustclose : 128 self.workfile.close() 129 128 self.workfile.close() 129 130 130 def readFirstAndLastBlocks(self, inputfile) : 131 131 """Reads the first and last blocks of data.""" … … 136 136 inputfile.seek(-pdlparser.LASTBLOCKSIZE, 2) 137 137 lastblock = inputfile.read(pdlparser.LASTBLOCKSIZE) 138 except IOError : 138 except IOError : 139 139 lastblock = "" 140 return (firstblock, lastblock) 141 142 def detectPDLHandler(self) : 140 return (firstblock, lastblock) 141 142 def detectPDLHandler(self) : 143 143 """Tries to autodetect the document format. 144 144 145 145 Returns the correct PDL handler class or None if format is unknown 146 """ 146 """ 147 147 if not os.stat(self.filename).st_size : 148 148 raise pdlparser.PDLParserError, "input file %s is empty !" % str(self.filename) 149 149 (firstblock, lastblock) = self.readFirstAndLastBlocks(self.workfile) 150 150 151 151 # IMPORTANT : the order is important below. FIXME. 152 152 for module in (postscript, \ … … 170 170 mscrap, \ 171 171 plain) : # IMPORTANT : don't move this one up ! 172 try : 173 return module.Parser(self, self.filename, 172 try : 173 return module.Parser(self, self.filename, 174 174 (firstblock, lastblock)) 175 175 except pdlparser.PDLParserError : 176 176 pass # try next parser 177 177 raise pdlparser.PDLParserError, "Analysis of first data block failed." 178 179 def main() : 178 179 def main() : 180 180 """Entry point for PDL Analyzer.""" 181 181 import optparse 182 182 from copy import copy 183 183 184 184 def check_cichoice(option, opt, value) : 185 185 """To add a CaseIgnore Choice option type.""" … … 187 187 if valower in [v.lower() for v in option.cichoices] : 188 188 return valower 189 else : 189 else : 190 190 choices = ", ".join([repr(o) for o in option.cichoices]) 191 191 raise optparse.OptionValueError( 192 192 "option %s: invalid choice: %r (choose from %s)" 193 193 % (opt, value, choices)) 194 194 195 195 class MyOption(optparse.Option) : 196 196 """New Option class, with CaseIgnore Choice type.""" … … 199 199 TYPE_CHECKER = copy(optparse.Option.TYPE_CHECKER) 200 200 TYPE_CHECKER["cichoice"] = check_cichoice 201 202 parser = optparse.OptionParser(option_class=MyOption, 201 202 parser = optparse.OptionParser(option_class=MyOption, 203 203 usage="python analyzer.py [options] file1 [file2 ...]") 204 parser.add_option("-v", "--version", 205 action="store_true", 204 parser.add_option("-v", "--version", 205 action="store_true", 206 206 dest="version", 207 207 help="Show pkpgcounter's version number and exit.") 208 parser.add_option("-d", "--debug", 209 action="store_true", 208 parser.add_option("-d", "--debug", 209 action="store_true", 210 210 dest="debug", 211 211 help="Activate debug mode.") 212 parser.add_option("-c", "--colorspace", 212 parser.add_option("-c", "--colorspace", 213 213 dest="colorspace", 214 214 type="cichoice", 215 215 cichoices=["bw", "rgb", "cmyk", "cmy", "gc"], 216 216 help="Activate the computation of ink usage, and defines the colorspace to use. Supported values are 'BW', 'RGB', 'CMYK', 'CMY', and 'GC'.") 217 parser.add_option("-r", "--resolution", 218 type="int", 219 default=72, 217 parser.add_option("-r", "--resolution", 218 type="int", 219 default=72, 220 220 dest="resolution", 221 221 help="The resolution in DPI to use when checking ink usage. Lower resolution is faster but less accurate. Default is 72 dpi.") … … 223 223 if options.version : 224 224 print "%s" % version.__version__ 225 elif not (72 <= options.resolution <= 1200) : 225 elif not (72 <= options.resolution <= 1200) : 226 226 sys.stderr.write("ERROR: the argument to the --resolution command line option must be between 72 and 1200.\n") 227 227 sys.stderr.flush() … … 229 229 if (not arguments) or ((not sys.stdin.isatty()) and ("-" not in arguments)) : 230 230 arguments.append("-") 231 totalsize = 0 231 totalsize = 0 232 232 lines = [] 233 233 try : … … 246 246 except KeyError : 247 247 pass 248 lines.append(" ".join(lineparts)) 249 except (IOError, pdlparser.PDLParserError), msg : 248 lines.append(" ".join(lineparts)) 249 except (IOError, pdlparser.PDLParserError), msg : 250 250 sys.stderr.write("ERROR: %s\n" % msg) 251 251 sys.stderr.flush() 252 except KeyboardInterrupt : 252 except KeyboardInterrupt : 253 253 sys.stderr.write("WARN: Aborted at user's request.\n") 254 254 sys.stderr.flush() 255 if not options.colorspace : 255 if not options.colorspace : 256 256 print "%i" % totalsize 257 else : 257 else : 258 258 print "\n".join(lines) 259 260 if __name__ == "__main__" : 259 260 if __name__ == "__main__" : 261 261 main()