-
Notifications
You must be signed in to change notification settings - Fork 0
/
pagecounter.py
200 lines (164 loc) · 5.53 KB
/
pagecounter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import utils
import cmd, os
class PageCounterConsole(cmd.Cmd):
#Define default largeformatsize
# See module do_setsize for more information
largeformatsize = 95
#Override Cmd init
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = "==> "
self.intro = """
PDF Page Counter
Author: @amanqa
----------------------
Type 'help' for a list of commands.
Type 'help <command>' for help on any command
"""
##
## Page-counter commands
##
def do_filecount(self, args):
"""Process a document, count pages
Syntax:
filecount <filename>
"""
#Clean input
filepath = utils.clean_input(args)
#check if file exists
if not os.path.exists(filepath):
print 'Could not find a file at <{}>'.format(filepath)
return
#Make sure this is a file, not a direcotyr
if os.path.isdir(filepath):
print 'This path point to a directory, not a file.',
print 'Use the "dircount" command instead.'
return
#check file extension is PDF
if not filepath.endswith('.pdf'):
print 'Invalid extension'
return
#Get counts
s, count = utils.ProcessPDF(filepath, self.largeformatsize)
#Print out counts
lout = self._log_line
if s:
lout('\nFile Stats for <{}>\n'.format(filepath))
for k,v in count.iteritems():
lout('{}: \t{}\n'.format(k,v))
else:
#function returned error, handle here
error = count
lout(error + '\n')
def do_dircount(self, args):
"""Process a directory and all the files inside
Syntax:
dircount <x:\\path\\to\\dir\\>
"""
#Clean input
dirpath = utils.clean_input(args)
#Check that directory exists
if not os.path.exists(dirpath):
print 'Could not find specific path at <{}>'.format(dirpath)
return
#Make sure this is a file, not a direcotyr
if os.path.isfile(dirpath):
print 'This path point to a file, not a directory.'
print 'Use the "filecount" command instead.'
return
#Get counts
errors, counts = utils.ParseDir(dirpath, self.largeformatsize)
#Print output
self._log_output (dirpath, counts, errors)
def do_setsize(self, args):
"""Change the default size formats for counting.
Currently, you can only set the size that differentiates "large" format
pages from other pages.
Syntax:
setsize <MIN_SIZE_FOR_LARGE_PAGES>
Example:
setsize 95
MIN_SIZE_FOR_LARGE_PAGES should be number greater than zero, representing
size of a page in square inches. All pages larger than this will be counted
as large pages.
See:
http://en.wikipedia.org/wiki/Paper_size
Dimensions are in square inches. For reference, 8.5 x 11 is about 93.46
square inches. So the default value of 95 defines large format as pages
just over "Letter" size.
"""
try:
self.largeformatsize = float(args)
except ValueError:
print 'Invalid value for size.'
print 'Try again. Enter a single number in square inches. Example:'
print '\tsetsize 95'
return
print 'Set MIN_SIZE_FOR_LARGE_PAGES = {}'.format(self.largeformatsize)
##
## Utility Commands
##
def _log_output(self, loc, counts, errors):
lout = self._log_line
lout('\nDirectory Stats for <{}>:\n'.format(loc))
lout('(Includes sub-directories)\n')
lout('\tNumber of files: {}\n'.format(counts["nfiles"]))
lout('\tNumber of PDFs: {}\n'.format(counts["npdfs"]))
lout('\tNumber of pages: {}\n'.format(counts["npages"]))
lout('\t\tLarge pages: {}\n'.format(counts["nlargepages"]))
lout('\t\tSmall pages: {}\n'.format(counts["nsmallpages"]))
if errors:
#function encountered error, handle here
lout('Encountered errors in the following files:\n')
for err in errors:
lout('\t%s\n' % err)
#Print warning if any files were ignored
if counts["nfiles"] != counts["npdfs"]:
lout('Warning: Ignored {} files that were not PDFs.\n'.format(
counts["nfiles"] - counts["npdfs"]))
def _log_line(self, line):
print line,
fout = self.outfile.write
fout (line)
def do_hist(self, args):
"""Print recently used commands"""
print 'Recently used commands: '
history = ''
for h in self._hist[-11:-1] :
history += h + ', '
print '{}'.format(history.rstrip(', '))
def do_exit(self, args):
"""Exit from the console."""
return -1
def do_EOF(self, line):
"""EOF or <Control-D> to Exit from Console"""
return True
##
## Overide cmd methods
##
def preloop(self):
"""Initialization
"""
cmd.Cmd.preloop(self)
self._hist = []
self.logfilename = utils._get_logfile_name()
self.outfile = file(self.logfilename, 'wb')
print 'Logging to file <{}>.'.format(self.logfilename)
def precmd(self, line):
self._hist += [ line.strip() ]
return line
def postcmd(self, stop, line):
"""After each command is completed.
"""
print '-' * 10
return stop
def postloop(self):
"""On Exit
"""
cmd.Cmd.postloop(self)
self.outfile.close()
print 'Log saved to file <{}>.'.format(self.logfilename)
print 'Bye.\n'
if __name__ == "__main__":
console = PageCounterConsole()
console . cmdloop()