forked from widdowquinn/scripts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjustify_me.py
executable file
·219 lines (187 loc) · 7.03 KB
/
justify_me.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env python
#
# justify_me.py
#
# A very short script to summarise time use from my personal lab book.
#
# My lab book is in LaTeX, and I record my work under \section{} and
# \subsection{} headers. The contents of these headers are in the format:
#
# SUBJECT: HHMM-HHMM; HHMM-HHMM;...
#
# The lab book source is stored in a hierarchical directory structure:
#
# YEAR/MM_month/YYYY-MM-DD/YYYY-MM-DD.tex
#
# This script takes a directory as input argument, searches all subdirectories
# for .tex source files, and scans them for \section{} and \subsection{}
# lines, parsing the content to calculate how much time was spent under each
# heading. It reports some summary statistics.
#
# TODO: Turn output into JSON/graphical output
#
# (c) L.Pritchard 2014
###
# IMPORTS
from argparse import ArgumentParser
from collections import defaultdict
import logging
import logging.handlers
import os
import re
import sys
import traceback
###
# FUNCTIONS
# Parse command-line
def parse_cmdline(args):
""" Parse command-line arguments
"""
parser = ArgumentParser(prog="justify_me.py")
parser.add_argument("-o", "--outfile", dest="outfilename",
action="store", default=None,
help="Output file")
parser.add_argument("-i", "--indir", dest="indirname",
action="store", default='.',
help="Input tab-separated plaintext table")
parser.add_argument("-v", "--verbose", dest="verbose",
action="store_true",
help="Give verbose output")
return parser.parse_args()
# Traverse subdirectories, collecting .tex files and processing the headers
def process_labbooks():
""" Starting from the input directory, traverse all subdirectories,
finding .tex files. Process each .tex file to find time spent under
each heading, and collate.
"""
# Traverse subdirectories and get list of lab book locations
texfiles = []
for root, dirs, files in os.walk(args.indirname):
texfiles.extend([os.path.join(root, f) for f in files if
os.path.splitext(f)[-1] == '.tex'])
# Process each book, returning a dictionary of time spent, keyed by
# section/subsection header
return [(os.path.split(texfile)[-1], scrape_time(texfile)) for
texfile in texfiles]
# Report time spent by lab book day
def report_by_day(times, outstream):
""" Report time spent by lab book day
"""
for filename, tlist in sorted(times):
outstream.write("\n%s:\n" % filename)
total = 0
for topic, t in sorted(tlist):
if t:
outstream.write("\t%30s:\t%.2fh\n" % (topic, t/60.))
total += t
outstream.write("Total time recorded: %.2fh\n" % (total/60.))
# Report total time recorded in lab boo
def report_total_time(times, outstream):
""" Report time recorded across all lab books
"""
totals = defaultdict(int)
days = 0
outstream.write("\nTotal time recorded:\n")
for filename, tlist in sorted(times):
days += 1
for topic, t in sorted(tlist):
if t:
totals[topic.upper()] += t
total = sum(totals.values())
for topic, t in sorted(totals.items()):
outstream.write("\t%30s:\t%dh%dm\t%.2fh\t(%.2f%%)\n" %
(topic, (t-t%60)/60, t%60, t/60., 100.*t/total))
outstream.write("Total time recorded: %dh%dm\t%.2fh\n" %
((total-total%60)/60, total%60, total/60.))
outstream.write("Total time recorded per lab book: %dh%dm\t%.2fh\n" %
(((total-total%60)/60)/days, (total%60)/days, total/60./days))
# Takes an iterable of .tex files and processes \section and \subsection
# headers to scrape times spent under the header
def scrape_time(filename):
""" Loops over a .tex file and scrapes the
time spent (in format HHMM-HHMM) from each \section and \subsection
header.
"""
section_re = r"((?<=\\section\{).*(?=\}))"
logger.info("Scraping %s" % filename)
with open(filename, 'rU') as fh:
data = fh.read()
# Get \section{} and \subsection{} elements
matches = [m for m in re.findall(section_re, data) if
len(m.strip()) and ':' in m]
# Process matches into subject, time values
times = [process_match(m) for m in matches]
return times
# Convert the section/subsection headers into a topic name and time spent
def process_match(match):
""" Takes a string regex match for a (sub)section header of format:
TOPIC: HHMM-HHMM; HHMM-HHMM...
and returns a tuple of (TOPIC, TIME SPENT IN MINUTES)
"""
time_re = "[0-9]{4}-[0-9]{4}"
topic, times = match.split(':', 1)
topic = topic.strip()
times = re.findall(time_re, times)
if not len(times):
return (topic, 0)
return (topic, calc_time(times))
# Convert string times HHMM-HHMM into time spent
def calc_time(times):
""" Takes a list of times in HHMM-HHMM format, and returns the difference
between the first and second times
"""
cumt = 0
for t in times:
t1, t2 = t.split('-')
tm = (int(t2[2:]) - int(t1[2:])) % 60
th = 60 * ((int(t2[:2]) - int(t1[:2])) % 24)
if int(t2[2:]) < int(t1[2:]):
th -= 60
cumt += tm + th
return cumt
###
# SCRIPT
if __name__ == '__main__':
# Parse command-line
args = parse_cmdline(sys.argv)
# We set up logging, and modify loglevel according to whether we need
# verbosity or not
logger = logging.getLogger('justify_me.py')
logger.setLevel(logging.DEBUG)
err_handler = logging.StreamHandler(sys.stderr)
err_formatter = logging.Formatter('%(levelname)s: %(message)s')
err_handler.setFormatter(err_formatter)
if args.verbose:
err_handler.setLevel(logging.INFO)
else:
err_handler.setLevel(logging.WARNING)
logger.addHandler(err_handler)
# Report arguments, if verbose
logger.info(args)
# Make sure the input directory is a directory
if not os.path.isdir(args.indirname):
logger.error("Input path %s is not a directory (exiting)" %
args.indirname)
sys.exit(1)
# Do we have an output file? No? Then use stdout
if args.outfilename is None:
outfhandle = sys.stdout
logger.info("Using stdout for output")
else:
logger.info("Using %s for output" % args.outfilename)
try:
outfhandle = open(args.outfilename, 'w')
except:
logger.error("Could not open output file: %s (exiting)" %
args.outfilename)
logger.error(''.join(
traceback.format_exception(sys.last_type,
sys.last_value,
sys.last_traceback)))
sys.exit(1)
# Process lab books
times = process_labbooks()
# Report time spent by day
report_by_day(times, outfhandle)
# Report total time spent
report_total_time(times, outfhandle)