1 | #! /usr/bin/env python |
---|
2 | # -*- coding: ISO-8859-15 -*- |
---|
3 | # |
---|
4 | # pkpgcounter : a generic Page Description Language parser |
---|
5 | # |
---|
6 | # (c) 2003, 2004, 2005 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
---|
20 | # |
---|
21 | # $Id$ |
---|
22 | # |
---|
23 | |
---|
24 | import sys |
---|
25 | import os |
---|
26 | import tempfile |
---|
27 | import popen2 |
---|
28 | |
---|
29 | import pdlparser |
---|
30 | import inkcoverage |
---|
31 | |
---|
32 | class Parser(pdlparser.PDLParser) : |
---|
33 | """A parser for PostScript documents.""" |
---|
34 | def isValid(self) : |
---|
35 | """Returns 1 if data is PostScript, else 0.""" |
---|
36 | if self.firstblock.startswith("%!") or \ |
---|
37 | self.firstblock.startswith("\004%!") or \ |
---|
38 | self.firstblock.startswith("\033%-12345X%!PS") or \ |
---|
39 | ((self.firstblock[:128].find("\033%-12345X") != -1) and \ |
---|
40 | ((self.firstblock.find("LANGUAGE=POSTSCRIPT") != -1) or \ |
---|
41 | (self.firstblock.find("LANGUAGE = POSTSCRIPT") != -1) or \ |
---|
42 | (self.firstblock.find("LANGUAGE = Postscript") != -1))) or \ |
---|
43 | (self.firstblock.find("%!PS-Adobe") != -1) : |
---|
44 | self.logdebug("DEBUG: Input file is in the PostScript format.") |
---|
45 | return 1 |
---|
46 | else : |
---|
47 | return 0 |
---|
48 | |
---|
49 | def throughGhostScript(self) : |
---|
50 | """Get the count through GhostScript, useful for non-DSC compliant PS files.""" |
---|
51 | self.logdebug("Internal parser sucks, using GhostScript instead...") |
---|
52 | self.infile.seek(0) |
---|
53 | command = 'gs -sDEVICE=bbox -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null' |
---|
54 | child = popen2.Popen4(command) |
---|
55 | try : |
---|
56 | data = self.infile.read(pdlparser.MEGABYTE) |
---|
57 | while data : |
---|
58 | child.tochild.write(data) |
---|
59 | data = self.infile.read(pdlparser.MEGABYTE) |
---|
60 | child.tochild.flush() |
---|
61 | child.tochild.close() |
---|
62 | except (IOError, OSError), msg : |
---|
63 | raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg |
---|
64 | |
---|
65 | pagecount = 0 |
---|
66 | try : |
---|
67 | pagecount = int(child.fromchild.readline().strip()) |
---|
68 | except (IOError, OSError, AttributeError, ValueError), msg : |
---|
69 | raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg |
---|
70 | child.fromchild.close() |
---|
71 | |
---|
72 | try : |
---|
73 | child.wait() |
---|
74 | except OSError, msg : |
---|
75 | raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg |
---|
76 | self.logdebug("GhostScript said : %s pages" % pagecount) |
---|
77 | return pagecount * self.copies |
---|
78 | |
---|
79 | def natively(self) : |
---|
80 | """Count pages in a DSC compliant PostScript document.""" |
---|
81 | self.infile.seek(0) |
---|
82 | pagecount = 0 |
---|
83 | self.pages = { 0 : { "copies" : 1 } } |
---|
84 | oldpagenum = None |
---|
85 | previousline = "" |
---|
86 | notrust = 0 |
---|
87 | for line in self.infile.xreadlines() : |
---|
88 | if line.startswith(r"%%BeginResource: procset pdf") : |
---|
89 | notrust = 1 # Let this stuff be managed by GhostScript, but we still extract number of copies |
---|
90 | elif line.startswith(r"%%Page: ") or line.startswith(r"(%%[Page: ") : |
---|
91 | proceed = 1 |
---|
92 | try : |
---|
93 | newpagenum = int(line.split(']')[0].split()[1]) |
---|
94 | except : |
---|
95 | pass |
---|
96 | else : |
---|
97 | if newpagenum == oldpagenum : |
---|
98 | proceed = 0 |
---|
99 | else : |
---|
100 | oldpagenum = newpagenum |
---|
101 | if proceed : |
---|
102 | pagecount += 1 |
---|
103 | self.pages[pagecount] = { "copies" : self.pages[pagecount-1]["copies"] } |
---|
104 | elif line.startswith(r"%%Requirements: numcopies(") : |
---|
105 | try : |
---|
106 | number = int(line.strip().split('(')[1].split(')')[0]) |
---|
107 | except : |
---|
108 | pass |
---|
109 | else : |
---|
110 | if number > self.pages[pagecount]["copies"] : |
---|
111 | self.pages[pagecount]["copies"] = number |
---|
112 | elif line.startswith(r"%%BeginNonPPDFeature: NumCopies ") : |
---|
113 | # handle # of copies set by some Windows printer driver |
---|
114 | try : |
---|
115 | number = int(line.strip().split()[2]) |
---|
116 | except : |
---|
117 | pass |
---|
118 | else : |
---|
119 | if number > self.pages[pagecount]["copies"] : |
---|
120 | self.pages[pagecount]["copies"] = number |
---|
121 | elif line.startswith("1 dict dup /NumCopies ") : |
---|
122 | # handle # of copies set by mozilla/kprinter |
---|
123 | try : |
---|
124 | number = int(line.strip().split()[4]) |
---|
125 | except : |
---|
126 | pass |
---|
127 | else : |
---|
128 | if number > self.pages[pagecount]["copies"] : |
---|
129 | self.pages[pagecount]["copies"] = number |
---|
130 | elif line.startswith("/languagelevel where{pop languagelevel}{1}ifelse 2 ge{1 dict dup/NumCopies") : |
---|
131 | try : |
---|
132 | number = int(previousline.strip()[2:]) |
---|
133 | except : |
---|
134 | pass |
---|
135 | else : |
---|
136 | if number > self.pages[pagecount]["copies"] : |
---|
137 | self.pages[pagecount]["copies"] = number |
---|
138 | elif line.startswith("/#copies ") : |
---|
139 | try : |
---|
140 | number = int(line.strip().split()[1]) |
---|
141 | except : |
---|
142 | pass |
---|
143 | else : |
---|
144 | if number > self.pages[pagecount]["copies"] : |
---|
145 | self.pages[pagecount]["copies"] = number |
---|
146 | previousline = line |
---|
147 | |
---|
148 | # extract max number of copies to please the ghostscript parser, just |
---|
149 | # in case we will use it later |
---|
150 | self.copies = max([ v["copies"] for (k, v) in self.pages.items() ]) |
---|
151 | |
---|
152 | # now apply the number of copies to each page |
---|
153 | for pnum in range(1, pagecount + 1) : |
---|
154 | page = self.pages.get(pnum, self.pages.get(1, { "copies" : 1 })) |
---|
155 | copies = page["copies"] |
---|
156 | pagecount += (copies - 1) |
---|
157 | self.logdebug("%s * page #%s" % (copies, pnum)) |
---|
158 | self.logdebug("Internal parser said : %s pages" % pagecount) |
---|
159 | |
---|
160 | if notrust : |
---|
161 | pagecount = 0 # Let gs do counting |
---|
162 | return pagecount |
---|
163 | |
---|
164 | def getJobSize(self) : |
---|
165 | """Count pages in PostScript document.""" |
---|
166 | self.copies = 1 |
---|
167 | return self.natively() or self.throughGhostScript() |
---|
168 | |
---|
169 | def throughTiffMultiPage24NC(self, dpi) : |
---|
170 | """Converts the input file to TIFF format, X dpi, 24 bits per pixel, uncompressed. |
---|
171 | Returns percents of ink coverage and number of pages. |
---|
172 | """ |
---|
173 | self.logdebug("Converting input datas to TIFF...") |
---|
174 | result = None |
---|
175 | self.infile.seek(0) |
---|
176 | (handle, filename) = tempfile.mkstemp(".tmp", "pkpgcounter") |
---|
177 | os.close(handle) |
---|
178 | command = 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%i -sOutputFile="%s" -' % (dpi, filename) |
---|
179 | try : |
---|
180 | child = popen2.Popen4(command) |
---|
181 | try : |
---|
182 | data = self.infile.read(pdlparser.MEGABYTE) |
---|
183 | while data : |
---|
184 | child.tochild.write(data) |
---|
185 | data = self.infile.read(pdlparser.MEGABYTE) |
---|
186 | child.tochild.flush() |
---|
187 | child.tochild.close() |
---|
188 | except (IOError, OSError), msg : |
---|
189 | raise pdlparser.PDLParserError, "Problem during conversion to TIFF : %s" % msg |
---|
190 | |
---|
191 | child.fromchild.close() |
---|
192 | try : |
---|
193 | child.wait() |
---|
194 | except OSError, msg : |
---|
195 | raise pdlparser.PDLParserError, "Problem during conversion to TIFF : %s" % msg |
---|
196 | |
---|
197 | result = inkcoverage.getPercents(filename) |
---|
198 | finally : |
---|
199 | try : |
---|
200 | os.remove(filename) |
---|
201 | except : |
---|
202 | pass |
---|
203 | return result |
---|
204 | |
---|
205 | def test() : |
---|
206 | """Test function.""" |
---|
207 | if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) : |
---|
208 | sys.argv.append("-") |
---|
209 | totalsize = 0 |
---|
210 | for arg in sys.argv[1:] : |
---|
211 | if arg == "-" : |
---|
212 | infile = sys.stdin |
---|
213 | mustclose = 0 |
---|
214 | else : |
---|
215 | infile = open(arg, "rb") |
---|
216 | mustclose = 1 |
---|
217 | try : |
---|
218 | parser = Parser(infile, debug=1) |
---|
219 | totalsize += parser.getJobSize() |
---|
220 | except pdlparser.PDLParserError, msg : |
---|
221 | sys.stderr.write("ERROR: %s\n" % msg) |
---|
222 | sys.stderr.flush() |
---|
223 | if mustclose : |
---|
224 | infile.close() |
---|
225 | print "%s" % totalsize |
---|
226 | |
---|
227 | if __name__ == "__main__" : |
---|
228 | test() |
---|