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

Revision 1588, 22.9 kB (checked in by jalet, 20 years ago)

Testsuite for PDL Analyzer added

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