aboutsummaryrefslogtreecommitdiff
path: root/scripts/time2tex.py
blob: 17661d557901dc8ebe6a4ceaae2970012112499d (plain)
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
#!/bin/python3
import sys, tex
from datetime import datetime, timedelta

def fmt_duration(sec):
  mins = (sec + 59) // 60 # integer divide, round up
  out = []

  if mins == 0:
    return "--"

  hour = mins // 60
  if hour > 0:
    out.append("%02dh" % (hour, ))
    mins = mins % 60

  out.append("%02dm" % (mins, ))

  return "\\,".join(out)

def fmt_percentage(fac):
  return tex.sgroup(
    tex.cmd('footnotesize') +\
    tex.cmd('itshape') +\
    tex.esc(f"({round(fac * 100)}%)")
  )

def fmt_member_overview(times):
  # calculations
  tracked = {}
  total_time = 0
  for time in times:
    if not time["name"] in tracked:
      tracked[time["name"]] = 0
    tracked[time["name"]] += time["duration"]
    total_time += time["duration"]

  out = ""

  # header
  out += tex.cmd('toprule')
  out += tex.tabrule(tex.cmd('textbf', 'Member'), tex.cmd('textbf', 'Tracked'), '')
  out += tex.cmd('midrule')

  # member overview
  members = sorted(list(set(time["name"] for time in times)))
  for name in members:
    out += tex.tabrule(name, fmt_duration(tracked[name]), fmt_percentage(tracked[name] / total_time))
  out += tex.cmd('midrule')

  # sum
  out += tex.tabrule('', fmt_duration(total_time), '')
  out += tex.cmd('bottomrule')

  out = tex.env('tabular', 'lr@{~}l', out)
  out = tex.cmd('centering') +\
        out +\
        tex.cmd('caption', 'Tracked time per group member') +\
        tex.cmd('label', 'tab:time-member')
  out = tex.env('table', out)

  return out

def fmt_weekly_overview(times):
  # calculations
  out = ""
  weeks = []
  member_totals = {}
  total_time = sum(time["duration"] for time in times)
  members = sorted(list(set(time["name"] for time in times)))
  time_start = min(time["date"] for time in times)
  time_end = max(time["date"] for time in times)
  week_start = time_start - timedelta(days=time_start.weekday()) # round down to nearest monday
  week_end = time_end + timedelta(days=7-time_end.weekday())

  week = week_start
  week_num = 1
  while week < week_end:
    week_times = [time for time in times if time["date"] >= week and time["date"] < (week + timedelta(days=7))]

    week_entry = {
      "num": week_num,
      "members": {},
      "total": sum(time["duration"] for time in week_times)
    }

    for member in members:
      week_entry["members"][member] = sum(time["duration"] for time in week_times if time["name"] == member)

    weeks.append(week_entry)
    week_num += 1
    week += timedelta(days=7)
  for member in members:
    member_totals[member] = sum(time["duration"] for time in times if time["name"] == member)

  # TODO: refactor
  # begin table
  out += r"\begin{table}\centering"
  out += r"\fitimg{"
  out += f"\\begin{{tabular}}{{l{'r@{~}l' * len(members)}@{{\\qquad}}r}}\\toprule"
  out += r"\textbf{\#}"
  for member in members:
    out += f"&\\textbf{{{member}}}&"
  out += r"&\textbf{Subtotal}\\\midrule{}"

  for entry in weeks:
    out += f"{entry['num']}"
    for member in members:
      out += f"&{fmt_duration(entry['members'][member])}&{fmt_percentage(entry['members'][member] / entry['total'])}"
    out += f"&{fmt_duration(entry['total'])}\\\\"

  out += r"\midrule{}"
  for member in members:
    out += f"&{fmt_duration(member_totals[member])}&{fmt_percentage(member_totals[member] / total_time)}"
  out += f"&{fmt_duration(total_time)}\\\\"

  # end table
  out += r"\bottomrule\end{tabular}"
  out += r"}" # \fitimg
  out += r"\caption{Tracked time per week}\label{tab:time-weekly}"
  out += r"\end{table}"

  return out

def duration2secs(duration):
  out = 0 # output (seconds)
  cur = 0 # current figure (unknown)
  for c in duration:
    if c.isdigit():
      cur = cur * 10 + int(c)
      continue
    if c == "h":
      out += cur * 3600
      cur = 0
      continue
    if c == "m":
      out += cur * 60
      cur = 0
      continue
    if c == "s":
      out += cur * 1
      cur = 0
      continue

    raise Exception("invalid duration format")
  if cur != 0: raise Exception("invalid duration format")
  return out

def line2data(line):
  # parse fields from input string
  data = {}
  next = line.find(':')
  data["name"] = line[0:next].strip()
  line = line[next+1:].strip()
  next = line.find(' ')
  data["date"] = line[0:next].strip()
  line = line[next+1:].strip()
  next = line.find(' ')
  data["duration"] = line[0:next].strip()
  line = line[next+1:].strip()
  data["description"] = line

  # deserialize parsed fields
  data["name"] = data["name"].title()
  data["date"] = datetime.strptime(data["date"], '%Y-%m-%d')
  data["duration"] = duration2secs(data["duration"])
  data["description"] = [el.strip() for el in data["description"].split("::")]

  return data

def parse(content):
  # split content at newlines
  lines = content.split("\n")
  out = []
  for i, line in enumerate(lines):
    line = line.strip()
    if line.startswith("#"): continue
    if len(line) == 0: continue

    try: out.append(line2data(line))
    except Exception as e: raise Exception(f"line {i+1}: {e}")
  return out

def fmt(times):
  return "\n\n".join([
    tex.cmd('section', 'Overviews'),
    tex.cmd('subsection', 'Members'),
    fmt_member_overview(times),
    tex.cmd('subsection', 'Weekly'),
    fmt_weekly_overview(times),
  ])

def main(input_file):
  content = ""
  with open(input_file, "r") as file:
    content = file.read()

  try: parsed = parse(content)
  except Exception as e:
    print(f"{input_file}: {e}")
    exit(1)
  output = fmt(parsed)

  output_file = input_file.removesuffix(".txt") + ".tex"
  with open(output_file, "w+") as file:
    file.write(output)

if __name__ == "__main__":
  if len(sys.argv) != 2:
    print("usage: time2tex.py time.txt")
    exit(1)
  main(sys.argv[1])