root / pykota / trunk / pykota / pdlanalyzer.py @ 1582

Revision 1580, 22.8 kB (checked in by jalet, 20 years ago)

Smallish optimization

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota - Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.22  2004/06/29 14:21:41  jalet
25# Smallish optimization
26#
27# Revision 1.21  2004/06/28 23:11:26  jalet
28# Code de-factorization in PCLXL parser
29#
30# Revision 1.20  2004/06/28 22:38:41  jalet
31# Increased speed by a factor of 2 in PCLXL parser
32#
33# Revision 1.19  2004/06/28 21:20:30  jalet
34# PCLXL support now works !
35#
36# Revision 1.18  2004/06/27 22:59:37  jalet
37# More work on PCLXL parser
38#
39# Revision 1.17  2004/06/26 23:20:01  jalet
40# Additionnal speedup for GhostScript generated PCL5 files
41#
42# Revision 1.16  2004/06/26 15:31:00  jalet
43# mmap reintroduced in PCL5 parser
44#
45# Revision 1.15  2004/06/26 14:14:31  jalet
46# Now uses Psyco if it is available
47#
48# Revision 1.14  2004/06/25 09:50:28  jalet
49# More debug info in PCLXL parser
50#
51# Revision 1.13  2004/06/25 08:10:08  jalet
52# Another fix for PCL5 parser
53#
54# Revision 1.12  2004/06/24 23:09:53  jalet
55# Fix for number of copies in PCL5 parser
56#
57# Revision 1.11  2004/06/23 22:07:50  jalet
58# Fixed PCL5 parser according to the sources of rastertohp
59#
60# Revision 1.10  2004/06/18 22:24:03  jalet
61# Removed old comments
62#
63# Revision 1.9  2004/06/18 22:21:27  jalet
64# Native PDF parser greatly improved.
65# GhostScript based PDF parser completely removed because native code
66# is now portable across Python versions.
67#
68# Revision 1.8  2004/06/18 20:49:46  jalet
69# "ERROR:" prefix added
70#
71# Revision 1.7  2004/06/18 17:48:04  jalet
72# Added native fast PDF parsing method
73#
74# Revision 1.6  2004/06/18 14:00:16  jalet
75# Added PDF support in smart PDL analyzer (through GhostScript for now)
76#
77# Revision 1.5  2004/06/18 10:09:05  jalet
78# Resets file pointer to start of file in all cases
79#
80# Revision 1.4  2004/06/18 06:16:14  jalet
81# Fixes PostScript detection code for incorrect drivers
82#
83# Revision 1.3  2004/05/21 20:40:08  jalet
84# All the code for pkpgcounter is now in pdlanalyzer.py
85#
86# Revision 1.2  2004/05/19 19:09:36  jalet
87# Speed improvement
88#
89# Revision 1.1  2004/05/18 09:59:54  jalet
90# pkpgcounter is now just a wrapper around the PDLAnalyzer class
91#
92#
93#
94
95import sys
96import os
97import re
98from struct import unpack
99import tempfile
100import mmap
101   
102KILOBYTE = 1024   
103MEGABYTE = 1024 * KILOBYTE   
104
105class PDLAnalyzerError(Exception):
106    """An exception for PDL Analyzer related stuff."""
107    def __init__(self, message = ""):
108        self.message = message
109        Exception.__init__(self, message)
110    def __repr__(self):
111        return self.message
112    __str__ = __repr__
113   
114class PostScriptAnalyzer :
115    def __init__(self, infile) :
116        """Initialize PostScript Analyzer."""
117        self.infile = infile
118       
119    def getJobSize(self) :   
120        """Count pages in a DSC compliant PostScript document."""
121        pagecount = 0
122        for line in self.infile.xreadlines() : 
123            if line.startswith("%%Page: ") :
124                pagecount += 1
125        return pagecount
126       
127class PDFAnalyzer :
128    def __init__(self, infile) :
129        """Initialize PDF Analyzer."""
130        self.infile = infile
131               
132    def getJobSize(self) :   
133        """Counts pages in a PDF document."""
134        regexp = re.compile(r"(/Type) ?(/Page)[/ \t\r\n]")
135        pagecount = 0
136        for line in self.infile.xreadlines() : 
137            pagecount += len(regexp.findall(line))
138        return pagecount   
139       
140class PCLAnalyzer :
141    def __init__(self, infile) :
142        """Initialize PCL Analyzer."""
143        self.infile = infile
144       
145    def getJobSize(self) :     
146        """Count pages in a PCL5 document."""
147        #
148        # Algorithm from pclcount
149        # (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin
150        # published under the terms of the GNU General Public Licence v2.
151        #
152        # Backported from C to Python by Jerome Alet, then enhanced
153        # with more PCL tags detected. I think all the necessary PCL tags
154        # are recognized to correctly handle PCL5 files wrt their number
155        # of pages. The documentation used for this was :
156        #
157        # HP PCL/PJL Reference Set
158        # PCL5 Printer Language Technical Quick Reference Guide
159        # http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf
160        #
161        infileno = self.infile.fileno()
162        minfile = mmap.mmap(infileno, os.fstat(infileno).st_size, access=mmap.ACCESS_READ)
163        tagsends = { "&n" : "W", 
164                     "&b" : "W", 
165                     "*i" : "W", 
166                     "*l" : "W", 
167                     "*m" : "W", 
168                     "*v" : "W", 
169                     "*c" : "W", 
170                     "(f" : "W", 
171                     "(s" : "W", 
172                     ")s" : "W", 
173                     "&p" : "X", 
174                     "&l" : "XH",
175                     "&a" : "G",
176                     # "*b" : "VW", # treated specially because it occurs very often
177                   } 
178        pagecount = resets = ejects = backsides = 0
179        tag = None
180        copies = {}
181        pos = 0
182        try :
183            while 1 :
184                char = minfile[pos] ; pos += 1
185                if char == "\014" :   
186                    pagecount += 1
187                elif char == "\033" :   
188                    #
189                    #     <ESC>*b###W -> Start of a raster data row/block
190                    #     <ESC>*b###V -> Start of a raster data plane
191                    #     <ESC>*c###W -> Start of a user defined pattern
192                    #     <ESC>*i###W -> Start of a viewing illuminant block
193                    #     <ESC>*l###W -> Start of a color lookup table
194                    #     <ESC>*m###W -> Start of a download dither matrix block
195                    #     <ESC>*v###W -> Start of a configure image data block
196                    #     <ESC>(s###W -> Start of a characters description block
197                    #     <ESC>)s###W -> Start of a fonts description block
198                    #     <ESC>(f###W -> Start of a symbol set block
199                    #     <ESC>&b###W -> Start of configuration data block
200                    #     <ESC>&l###X -> Number of copies for current page
201                    #     <ESC>&n###W -> Starts an alphanumeric string ID block
202                    #     <ESC>&p###X -> Start of a non printable characters block
203                    #     <ESC>&a2G -> Back side when duplex mode as generated by rastertohp
204                    #     <ESC>&l0H -> Eject if NumPlanes > 1, as generated by rastertohp
205                    #
206                    tagstart = minfile[pos] ; pos += 1
207                    if tagstart in "E9=YZ" : # one byte PCL tag
208                        if tagstart == "E" :
209                            resets += 1
210                        continue             # skip to next tag
211                    tag = tagstart + minfile[pos] ; pos += 1
212                    if tag == "*b" : 
213                        tagend = "VW"
214                    else :   
215                        try :
216                            tagend = tagsends[tag]
217                        except KeyError :   
218                            continue # Unsupported PCL tag
219                    # Now read the numeric argument
220                    size = 0
221                    while 1 :
222                        char = minfile[pos] ; pos += 1
223                        if not char.isdigit() :
224                            break
225                        size = (size * 10) + int(char)   
226                    if char in tagend :   
227                        if (tag == "&l") and (char == "X") : # copies for current page
228                            copies[pagecount] = size
229                        elif (tag == "&l") and (char == "H") and (size == 0) :   
230                            ejects += 1         # Eject
231                        elif (tag == "&a") and (size == 2) :
232                            backsides += 1      # Back side in duplex mode
233                        else :   
234                            # we just ignore the block.
235                            if tag == "&n" : 
236                                # we have to take care of the operation id byte
237                                # which is before the string itself
238                                size += 1
239                            pos += size   
240        except IndexError : # EOF ?
241            minfile.close() # reached EOF
242                           
243        # if pagecount is still 0, we will use the number
244        # of resets instead of the number of form feed characters.
245        # but the number of resets is always at least 2 with a valid
246        # pcl file : one at the very start and one at the very end
247        # of the job's data. So we substract 2 from the number of
248        # resets. And since on our test data we needed to substract
249        # 1 more, we finally substract 3, and will test several
250        # PCL files with this. If resets < 2, then the file is
251        # probably not a valid PCL file, so we use 0
252        if not pagecount :
253            pagecount = (pagecount or ((resets - 3) * (resets > 2)))
254        else :   
255            # here we add counters for other ways new pages may have
256            # been printed and ejected by the printer
257            pagecount += ejects + backsides
258       
259        # now handle number of copies for each page (may differ).
260        # in duplex mode, number of copies may be sent only once.
261        for pnum in range(pagecount) :
262            # if no number of copies defined, take the preceding one else 1.
263            nb = copies.get(pnum, copies.get(pnum-1, 1))
264            pagecount += (nb - 1)
265        return pagecount
266       
267class PCLXLAnalyzer :
268    def __init__(self, infile) :
269        """Initialize PCLXL Analyzer."""
270        # raise PDLAnalyzerError, "PCLXL (aka PCL6) is not supported yet."
271        self.infile = infile
272        self.endianness = None
273        found = 0
274        while not found :
275            line = self.infile.readline()
276            if not line :
277                break
278            if line[1:12] == " HP-PCL XL;" :
279                found = 1
280                endian = ord(line[0])
281                if endian == 0x29 :
282                    self.littleEndian()
283                elif endian == 0x28 :   
284                    self.bigEndian()
285                # elif endian == 0x27 : TODO : What can we do here ?   
286                #
287                else :   
288                    raise PDLAnalyzerError, "No endianness marker 0x%02x at start !" % endian
289        if not found :
290            raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)"
291        else :   
292            # Initialize table of tags
293            self.tags = [ 0 ] * 256   
294           
295            # GhostScript's sources tell us that HP printers
296            # only accept little endianness, but we can handle both.
297            self.tags[0x28] = self.bigEndian    # BigEndian
298            self.tags[0x29] = self.littleEndian # LittleEndian
299           
300            self.tags[0x43] = self.beginPage    # BeginPage
301           
302            self.tags[0xc0] = 1 # ubyte
303            self.tags[0xc1] = 2 # uint16
304            self.tags[0xc2] = 4 # uint32
305            self.tags[0xc3] = 2 # sint16
306            self.tags[0xc4] = 4 # sint32
307            self.tags[0xc5] = 4 # real32
308           
309            self.tags[0xc8] = self.array_8  # ubyte_array
310            self.tags[0xc9] = self.array_16 # uint16_array
311            self.tags[0xca] = self.array_32 # uint32_array
312            self.tags[0xcb] = self.array_16 # sint16_array
313            self.tags[0xcc] = self.array_32 # sint32_array
314            self.tags[0xcd] = self.array_32 # real32_array
315           
316            self.tags[0xd0] = 2 # ubyte_xy
317            self.tags[0xd1] = 4 # uint16_xy
318            self.tags[0xd2] = 8 # uint32_xy
319            self.tags[0xd3] = 4 # sint16_xy
320            self.tags[0xd4] = 8 # sint32_xy
321            self.tags[0xd5] = 8 # real32_xy
322           
323            self.tags[0xe0] = 4  # ubyte_box
324            self.tags[0xe1] = 8  # uint16_box
325            self.tags[0xe2] = 16 # uint32_box
326            self.tags[0xe3] = 8  # sint16_box
327            self.tags[0xe4] = 16 # sint32_box
328            self.tags[0xe5] = 16 # real32_box
329           
330            self.tags[0xf8] = 1 # attr_ubyte
331            self.tags[0xf9] = 2 # attr_uint16
332           
333            self.tags[0xfa] = self.embeddedData      # dataLength
334            self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
335           
336    def beginPage(self) :
337        """Indicates the beginning of a new page."""
338        self.pagecount += 1
339        return 0
340       
341    def array_8(self) :   
342        """Handles byte arrays."""
343        pos = self.pos
344        datatype = self.minfile[pos]
345        pos += 1
346        length = self.tags[ord(datatype)]
347        if callable(length) :
348            self.pos = pos
349            length = length()
350            pos = self.pos
351        posl = pos + length
352        self.pos = posl
353        if length == 1 :   
354            return unpack("B", self.minfile[pos:posl])[0]
355        elif length == 2 :   
356            return unpack(self.endianness + "H", self.minfile[pos:posl])[0]
357        elif length == 4 :   
358            return unpack(self.endianness + "I", self.minfile[pos:posl])[0]
359        else :   
360            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
361       
362    def array_16(self) :   
363        """Handles byte arrays."""
364        pos = self.pos
365        datatype = self.minfile[pos]
366        pos += 1
367        length = self.tags[ord(datatype)]
368        if callable(length) :
369            self.pos = pos
370            length = length()
371            pos = self.pos
372        posl = pos + length
373        self.pos = posl
374        if length == 1 :   
375            return 2 * unpack("B", self.minfile[pos:posl])[0]
376        elif length == 2 :   
377            return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
378        elif length == 4 :   
379            return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
380        else :   
381            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
382       
383    def array_32(self) :   
384        """Handles byte arrays."""
385        pos = self.pos
386        datatype = self.minfile[pos]
387        pos += 1
388        length = self.tags[ord(datatype)]
389        if callable(length) :
390            self.pos = pos
391            length = length()
392            pos = self.pos
393        posl = pos + length
394        self.pos = posl
395        if length == 1 :   
396            return 4 * unpack("B", self.minfile[pos:posl])[0]
397        elif length == 2 :   
398            return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
399        elif length == 4 :   
400            return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
401        else :   
402            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
403       
404    def embeddedDataSmall(self) :
405        """Handle small amounts of data."""
406        pos = self.pos
407        length = ord(self.minfile[pos])
408        self.pos = pos + 1
409        return length
410       
411    def embeddedData(self) :
412        """Handle normal amounts of data."""
413        pos = self.pos
414        pos4 = pos + 4
415        self.pos = pos4
416        return unpack(self.indianness + "I", self.minfile[pos:pos4])[0]
417       
418    def littleEndian(self) :       
419        """Toggles to little endianness."""
420        self.endianness = "<" # little endian
421        return 0
422       
423    def bigEndian(self) :   
424        """Toggles to big endianness."""
425        self.endianness = ">" # big endian
426        return 0
427   
428    def getJobSize(self) :
429        """Counts pages in a PCLXL (PCL6) document."""
430        infileno = self.infile.fileno()
431        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno).st_size, access=mmap.ACCESS_READ)
432        tags = self.tags
433        self.pagecount = 0
434        self.pos = pos = self.infile.tell()
435        try :
436            while 1 :
437                char = minfile[pos]
438                pos += 1
439                length = tags[ord(char)]
440                if not length :
441                    continue
442                if callable(length) :   
443                    self.pos = pos
444                    length = length()
445                    pos = self.pos
446                pos += length   
447        except IndexError : # EOF ?
448            self.minfile.close() # reached EOF
449        return self.pagecount
450       
451class PDLAnalyzer :   
452    """Generic PDL Analyzer class."""
453    def __init__(self, filename) :
454        """Initializes the PDL analyzer.
455       
456           filename is the name of the file or '-' for stdin.
457           filename can also be a file-like object which
458           supports read() and seek().
459        """
460        self.filename = filename
461        try :
462            import psyco 
463        except ImportError :   
464            pass # Psyco is not installed
465        else :   
466            # Psyco is installed, tell it to compile
467            # the CPU intensive methods : PCL and PCLXL
468            # parsing will greatly benefit from this,
469            # for PostScript and PDF the difference is
470            # barely noticeable since they are already
471            # almost optimal, and much more speedy anyway.
472            psyco.bind(PostScriptAnalyzer.getJobSize)
473            psyco.bind(PDFAnalyzer.getJobSize)
474            psyco.bind(PCLAnalyzer.getJobSize)
475            psyco.bind(PCLXLAnalyzer.getJobSize)
476       
477    def getJobSize(self) :   
478        """Returns the job's size."""
479        self.openFile()
480        try :
481            pdlhandler = self.detectPDLHandler()
482        except PDLAnalyzerError, msg :   
483            self.closeFile()
484            raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg)
485        else :
486            try :
487                size = pdlhandler(self.infile).getJobSize()
488            finally :   
489                self.closeFile()
490            return size
491       
492    def openFile(self) :   
493        """Opens the job's data stream for reading."""
494        self.mustclose = 0  # by default we don't want to close the file when finished
495        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
496            # filename is in fact a file-like object
497            infile = self.filename
498        elif self.filename == "-" :
499            # we must read from stdin
500            infile = sys.stdin
501        else :   
502            # normal file
503            self.infile = open(self.filename, "rb")
504            self.mustclose = 1
505            return
506           
507        # Use a temporary file, always seekable contrary to standard input.
508        self.infile = tempfile.TemporaryFile(mode="w+b")
509        while 1 :
510            data = infile.read(MEGABYTE) 
511            if not data :
512                break
513            self.infile.write(data)
514        self.infile.flush()   
515        self.infile.seek(0)
516           
517    def closeFile(self) :       
518        """Closes the job's data stream if we can close it."""
519        if self.mustclose :
520            self.infile.close()   
521        else :   
522            # if we don't have to close the file, then
523            # ensure the file pointer is reset to the
524            # start of the file in case the process wants
525            # to read the file again.
526            try :
527                self.infile.seek(0)
528            except :   
529                pass    # probably stdin, which is not seekable
530       
531    def isPostScript(self, data) :   
532        """Returns 1 if data is PostScript, else 0."""
533        if data.startswith("%!") or \
534           data.startswith("\004%!") or \
535           data.startswith("\033%-12345X%!PS") or \
536           ((data[:128].find("\033%-12345X") != -1) and \
537             ((data.find("LANGUAGE=POSTSCRIPT") != -1) or \
538              (data.find("LANGUAGE = POSTSCRIPT") != -1) or \
539              (data.find("LANGUAGE = Postscript") != -1))) or \
540              (data.find("%!PS-Adobe") != -1) :
541            return 1
542        else :   
543            return 0
544       
545    def isPDF(self, data) :   
546        """Returns 1 if data is PDF, else 0."""
547        if data.startswith("%PDF-") or \
548           data.startswith("\033%-12345X%PDF-") or \
549           ((data[:128].find("\033%-12345X") != -1) and (data.upper().find("LANGUAGE=PDF") != -1)) or \
550           (data.find("%PDF-") != -1) :
551            return 1
552        else :   
553            return 0
554       
555    def isPCL(self, data) :   
556        """Returns 1 if data is PCL, else 0."""
557        if data.startswith("\033E\033") or \
558           ((data[:128].find("\033%-12345X") != -1) and \
559             ((data.find("LANGUAGE=PCL") != -1) or \
560              (data.find("LANGUAGE = PCL") != -1) or \
561              (data.find("LANGUAGE = Pcl") != -1))) :
562            return 1
563        else :   
564            return 0
565       
566    def isPCLXL(self, data) :   
567        """Returns 1 if data is PCLXL aka PCL6, else 0."""
568        if ((data[:128].find("\033%-12345X") != -1) and \
569             (data.find(" HP-PCL XL;") != -1) and \
570             ((data.find("LANGUAGE=PCLXL") != -1) or \
571              (data.find("LANGUAGE = PCLXL") != -1))) :
572            return 1
573        else :   
574            return 0
575           
576    def detectPDLHandler(self) :   
577        """Tries to autodetect the document format.
578       
579           Returns the correct PDL handler class or None if format is unknown
580        """   
581        # Try to detect file type by reading first block of datas   
582        self.infile.seek(0)
583        firstblock = self.infile.read(KILOBYTE)
584        self.infile.seek(0)
585        if self.isPostScript(firstblock) :
586            return PostScriptAnalyzer
587        elif self.isPCLXL(firstblock) :   
588            return PCLXLAnalyzer
589        elif self.isPCL(firstblock) :   
590            return PCLAnalyzer
591        elif self.isPDF(firstblock) :   
592            return PDFAnalyzer
593        else :   
594            raise PDLAnalyzerError, "Analysis of first data block failed."
595           
596def main() :   
597    """Entry point for PDL Analyzer."""
598    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
599        sys.argv.append("-")
600       
601    totalsize = 0   
602    for arg in sys.argv[1:] :
603        try :
604            parser = PDLAnalyzer(arg)
605            totalsize += parser.getJobSize()
606        except PDLAnalyzerError, msg :   
607            sys.stderr.write("ERROR: %s\n" % msg)
608            sys.stderr.flush()
609    print "%s" % totalsize
610   
611if __name__ == "__main__" :   
612    main()
Note: See TracBrowser for help on using the browser.