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

Revision 1576, 21.7 kB (checked in by jalet, 20 years ago)

Increased speed by a factor of 2 in PCLXL parser

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